diff options
| author | Aram Drevekenin <aram@poor.dev> | 2026-04-28 17:14:59 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-04-28 17:14:59 +0200 |
| commit | 227142dd567ee72bcc137c116bc1ce2b818975e7 (patch) | |
| tree | 8958a994dddb80bf20ce1e6bf2694687736b0b19 | |
| parent | upgrade rustls-webpki (#5106) (diff) | |
| download | sl0ppij-227142dd567ee72bcc137c116bc1ce2b818975e7.tar.gz sl0ppij-227142dd567ee72bcc137c116bc1ce2b818975e7.tar.xz sl0ppij-227142dd567ee72bcc137c116bc1ce2b818975e7.zip | |
Support CSI2031 (dark/light theme switching) + remove STDIN cache to avoid stale color queries (#5105)
* initial phase 1 implementation
* various fies
* some fixes
* fix fragmented stdin cases
* some fixes
* renaming
* guard against old clients
* implement csi 2031
* allow toggling theme with actions
* rustfmt
* fix: finalize trailing characters in ansi parser as well
* add pr
52 files changed, 5687 insertions, 969 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index ea17ec26..aa583406 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) * fix: occasional dropped characters in web client (https://github.com/zellij-org/zellij/pull/5080) * fix: restore kitty keyboard mode on error, handle DECRPM 2026 state 3, clean up client terminal teardown sequences (https://github.com/zellij-org/zellij/pull/5058) * fix: prevent occasional duplicate characters in the web client due to IME (https://github.com/zellij-org/zellij/pull/4975) +* feat: support `CSI 2031` + dark/light mode theme switching (https://github.com/zellij-org/zellij/pull/5105) ## [0.44.1] - 2026-04-07 * fix: don't display default ports as offline in `share` plugin (https://github.com/zellij-org/zellij/pull/4908) diff --git a/zellij-client/Cargo.toml b/zellij-client/Cargo.toml index a83b4dd0..70d313a2 100644 --- a/zellij-client/Cargo.toml +++ b/zellij-client/Cargo.toml @@ -69,6 +69,9 @@ rcgen = "0.13" serde_json = "1.0" serial_test = "3.0" tempfile = "3" +# `test-util` enables `tokio::time::pause` / `advance`, used by the +# forward-timeout timer tests to drive virtual time deterministically. +tokio = { workspace = true, features = ["test-util"] } [features] unstable = [] diff --git a/zellij-client/src/input_handler.rs b/zellij-client/src/input_handler.rs index 8c6c7b28..cc4b4d75 100644 --- a/zellij-client/src/input_handler.rs +++ b/zellij-client/src/input_handler.rs @@ -253,15 +253,15 @@ impl InputHandler { raw_bytes, }); }, - Ok((InputInstruction::StartedParsing, _error_context)) => { - self.send_client_instructions - .send(ClientInstruction::StartedParsingStdinQuery) - .unwrap(); - }, - Ok((InputInstruction::DoneParsing, _error_context)) => { - self.send_client_instructions - .send(ClientInstruction::DoneParsingStdinQuery) - .unwrap(); + Ok(( + InputInstruction::ForwardedReplyFromHostComplete { token, reply_bytes }, + _error_context, + )) => { + self.os_input + .send_to_server(ClientToServerMsg::ForwardedReplyFromHost { + token, + reply_bytes, + }); }, Ok((InputInstruction::Exit, _error_context)) => { self.should_exit = true; @@ -317,6 +317,10 @@ impl InputHandler { .send(ClientInstruction::SetSynchronizedOutput(enabled)) .unwrap(); }, + AnsiStdinInstruction::HostTerminalThemeChanged(mode) => { + self.os_input + .send_to_server(ClientToServerMsg::HostTerminalThemeChanged { mode }); + }, } } fn handle_mouse_event(&mut self, mouse_event: &MouseEvent) { diff --git a/zellij-client/src/keyboard_parser.rs b/zellij-client/src/keyboard_parser.rs index 73b36d06..86c29b6d 100644 --- a/zellij-client/src/keyboard_parser.rs +++ b/zellij-client/src/keyboard_parser.rs @@ -11,6 +11,22 @@ enum KittyKeysParsingState { DoneParsingWithTilde, } +/// Three-way outcome of `KittyKeyboardParser::feed()`. Lets a long-lived +/// parser distinguish a finished sequence (consume + reset) from a +/// valid prefix (keep state, wait for the next chunk) from an unrelated +/// byte stream (reset and let a fallback parser handle it). +#[derive(Debug)] +pub enum KittyParseOutcome { + /// Complete sequence parsed; parser resets to Ground. + Complete(KeyWithModifier), + /// Bytes are a valid prefix; parser keeps state. Caller should let + /// termwiz also see them this round and call `feed()` again on the + /// next chunk. + Incomplete, + /// Bytes are not a Kitty sequence; parser resets to Ground. + NoMatch, +} + #[derive(Debug)] pub struct KittyKeyboardParser { state: KittyKeysParsingState, @@ -18,6 +34,15 @@ pub struct KittyKeyboardParser { modifier_bytes: Vec<u8>, } +/// CSI final-byte range (0x40..=0x7E), minus `u` and `~` which trigger +/// the explicit `DoneParsingWith{U,Tilde}` states inside the parser. +/// A trailing letter in this range while still in +/// `ParsingNumber`/`ParsingModifiers` indicates a complete +/// letter-terminated sequence (e.g. `\x1b[A`, `\x1b[1;2A`). +fn is_csi_final_letter(b: u8) -> bool { + (0x40..=0x7E).contains(&b) && b != b'u' && b != b'~' +} + impl KittyKeyboardParser { pub fn new() -> Self { KittyKeyboardParser { @@ -26,40 +51,95 @@ impl KittyKeyboardParser { modifier_bytes: vec![], } } - pub fn parse(&mut self, buffer: &[u8]) -> Option<KeyWithModifier> { - for byte in buffer { + + fn reset(&mut self) { + self.state = KittyKeysParsingState::Ground; + self.number_bytes.clear(); + self.modifier_bytes.clear(); + } + + /// Stateful, cross-chunk-aware entry point. Drives the same + /// state machine as `parse()` but: + /// * resets to Ground after producing `Complete`/`NoMatch`, so the + /// parser can be reused for the next sequence; + /// * preserves state on `Incomplete`, so a sequence split across + /// chunks still resolves on a follow-up call. + /// + /// The existing `parse()` wrapper is retained for the unit tests in + /// this file, which construct `::new()` per assertion. + pub fn feed(&mut self, bytes: &[u8]) -> KittyParseOutcome { + for byte in bytes { if !self.advance(*byte) { - return None; + self.reset(); + return KittyParseOutcome::NoMatch; } } match self.state { KittyKeysParsingState::DoneParsingWithU => { - // CSI number ; modifiers u - KeyWithModifier::from_bytes_with_u(&self.number_bytes, &self.modifier_bytes) + let result = + KeyWithModifier::from_bytes_with_u(&self.number_bytes, &self.modifier_bytes); + self.reset(); + match result { + Some(k) => KittyParseOutcome::Complete(k), + None => KittyParseOutcome::NoMatch, + } }, KittyKeysParsingState::DoneParsingWithTilde => { - // CSI number ; modifiers ~ - KeyWithModifier::from_bytes_with_tilde(&self.number_bytes, &self.modifier_bytes) - }, - KittyKeysParsingState::ParsingModifiers => { - // CSI 1; modifiers [ABCDEFHPQS] - match self.modifier_bytes.pop() { - Some(last_modifier) => KeyWithModifier::from_bytes_with_no_ending_byte( - &[last_modifier], - &self.modifier_bytes, - ), - None => None, + let result = KeyWithModifier::from_bytes_with_tilde( + &self.number_bytes, + &self.modifier_bytes, + ); + self.reset(); + match result { + Some(k) => KittyParseOutcome::Complete(k), + None => KittyParseOutcome::NoMatch, } }, KittyKeysParsingState::ParsingNumber => { - KeyWithModifier::from_bytes_with_no_ending_byte( - &self.number_bytes, - &self.modifier_bytes, - ) + // ParsingNumber holds either a digit run waiting for a + // terminator (Incomplete) or a single letter that is + // itself the terminator — `\x1b[A` etc. (Complete). + match self.number_bytes.last().copied() { + Some(last) if is_csi_final_letter(last) => { + let result = KeyWithModifier::from_bytes_with_no_ending_byte( + &self.number_bytes, + &self.modifier_bytes, + ); + self.reset(); + match result { + Some(k) => KittyParseOutcome::Complete(k), + None => KittyParseOutcome::NoMatch, + } + }, + _ => KittyParseOutcome::Incomplete, + } + }, + KittyKeysParsingState::ParsingModifiers => { + // ParsingModifiers holds either modifier digits waiting + // for the terminator letter (Incomplete) or modifier + // digits + a trailing letter terminator + // — `\x1b[1;2A` etc. (Complete). + match self.modifier_bytes.last().copied() { + Some(last) if is_csi_final_letter(last) => { + let last_modifier = self.modifier_bytes.pop().unwrap(); + let result = KeyWithModifier::from_bytes_with_no_ending_byte( + &[last_modifier], + &self.modifier_bytes, + ); + self.reset(); + match result { + Some(k) => KittyParseOutcome::Complete(k), + None => KittyParseOutcome::NoMatch, + } + }, + _ => KittyParseOutcome::Incomplete, + } }, - _ => None, + KittyKeysParsingState::ReceivedEscapeCharacter => KittyParseOutcome::Incomplete, + KittyKeysParsingState::Ground => KittyParseOutcome::NoMatch, } } + pub fn advance(&mut self, byte: u8) -> bool { // returns false if we failed parsing match (&self.state, byte) { @@ -104,241 +184,255 @@ impl KittyKeyboardParser { } } +/// Test helper. Drives the production `feed()` entry point on a single +/// chunk and projects its three-way outcome onto an `Option` so the +/// existing assertion shape (`Some(KeyWithModifier { … })`) stays +/// readable. The full-byte tests in this file expect the input to be a +/// single complete sequence; `Incomplete` and `NoMatch` both flatten to +/// `None`. +#[cfg(test)] +fn parse_for_test(bytes: &[u8]) -> Option<KeyWithModifier> { + match KittyKeyboardParser::new().feed(bytes) { + KittyParseOutcome::Complete(k) => Some(k), + KittyParseOutcome::Incomplete | KittyParseOutcome::NoMatch => None, + } +} + #[test] pub fn can_parse_bare_keys() { use zellij_utils::data::BareKey; let key = "\u{1b}[97u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('a'))), "Can parse a bare 'a' keypress" ); let key = "\u{1b}[49u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('1'))), "Can parse a bare '1' keypress" ); let key = "\u{1b}[27u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Esc)), "Can parse a bare 'ESC' keypress" ); let key = "\u{1b}[13u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Enter)), "Can parse a bare 'ENTER' keypress" ); let key = "\u{1b}[9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Tab)), "Can parse a bare 'Tab' keypress" ); let key = "\u{1b}[127u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Backspace)), "Can parse a bare 'Backspace' keypress" ); let key = "\u{1b}[57358u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::CapsLock)), "Can parse a bare 'CapsLock' keypress" ); let key = "\u{1b}[57359u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::ScrollLock)), "Can parse a bare 'ScrollLock' keypress" ); let key = "\u{1b}[57360u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::NumLock)), "Can parse a bare 'NumLock' keypress" ); let key = "\u{1b}[57361u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PrintScreen)), "Can parse a bare 'PrintScreen' keypress" ); let key = "\u{1b}[57362u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Pause)), "Can parse a bare 'Pause' keypress" ); let key = "\u{1b}[57363u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Menu)), "Can parse a bare 'Menu' keypress" ); let key = "\u{1b}[2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Insert)), "Can parse a bare 'Insert' keypress" ); let key = "\u{1b}[3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Delete)), "Can parse a bare 'Delete' keypress" ); let key = "\u{1b}[5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageUp)), "Can parse a bare 'PageUp' keypress" ); let key = "\u{1b}[6~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageDown)), "Can parse a bare 'PageDown' keypress" ); let key = "\u{1b}[7~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home)), "Can parse a bare 'Home' keypress" ); let key = "\u{1b}[8~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End)), "Can parse a bare 'End' keypress" ); let key = "\u{1b}[11~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1))), "Can parse a bare 'F1' keypress" ); let key = "\u{1b}[12~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2))), "Can parse a bare 'F2' keypress" ); let key = "\u{1b}[13~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(3))), "Can parse a bare 'F3' keypress" ); let key = "\u{1b}[14~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4))), "Can parse a bare 'F4' keypress" ); let key = "\u{1b}[15~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(5))), "Can parse a bare 'F5' keypress" ); let key = "\u{1b}[17~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(6))), "Can parse a bare 'F6' keypress" ); let key = "\u{1b}[18~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(7))), "Can parse a bare 'F7' keypress" ); let key = "\u{1b}[19~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(8))), "Can parse a bare 'F8' keypress" ); let key = "\u{1b}[20~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(9))), "Can parse a bare 'F9' keypress" ); let key = "\u{1b}[21~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(10))), "Can parse a bare 'F10' keypress" ); let key = "\u{1b}[23~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(11))), "Can parse a bare 'F11' keypress" ); let key = "\u{1b}[24~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(12))), "Can parse a bare 'F12' keypress" ); let key = "\u{1b}[D"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Left)), "Can parse a bare 'Left' keypress" ); let key = "\u{1b}[C"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Right)), "Can parse a bare 'Right' keypress" ); let key = "\u{1b}[A"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Up)), "Can parse a bare 'Up' keypress" ); let key = "\u{1b}[B"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Down)), "Can parse a bare 'Down' keypress" ); let key = "\u{1b}[H"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home)), "Can parse a bare 'Home' keypress" ); let key = "\u{1b}[F"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End)), "Can parse a bare 'End' keypress" ); let key = "\u{1b}[P"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1))), "Can parse a bare 'F1 (alternate)' keypress" ); let key = "\u{1b}[Q"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2))), "Can parse a bare 'F2 (alternate)' keypress" ); let key = "\u{1b}[S"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4))), "Can parse a bare 'F4 (alternate)' keypress" ); @@ -349,236 +443,236 @@ pub fn can_parse_keys_with_shift_modifier() { use zellij_utils::data::BareKey; let key = "\u{1b}[97;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('a')).with_shift_modifier()), "Can parse a bare 'a' keypress with shift" ); let key = "\u{1b}[49;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('1')).with_shift_modifier()), "Can parse a bare '1' keypress with shift" ); let key = "\u{1b}[27;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Esc).with_shift_modifier()), "Can parse a bare 'ESC' keypress with shift" ); let key = "\u{1b}[13;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Enter).with_shift_modifier()), "Can parse a bare 'ENTER' keypress with shift" ); let key = "\u{1b}[9;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Tab).with_shift_modifier()), "Can parse a bare 'Tab' keypress with shift" ); let key = "\u{1b}[127;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Backspace).with_shift_modifier()), "Can parse a bare 'Backspace' keypress with shift" ); let key = "\u{1b}[57358;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::CapsLock).with_shift_modifier()), "Can parse a bare 'CapsLock' keypress with shift" ); let key = "\u{1b}[57359;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::ScrollLock).with_shift_modifier()), "Can parse a bare 'ScrollLock' keypress with shift" ); let key = "\u{1b}[57360;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::NumLock).with_shift_modifier()), "Can parse a bare 'NumLock' keypress with shift" ); let key = "\u{1b}[57361;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PrintScreen).with_shift_modifier()), "Can parse a bare 'PrintScreen' keypress with shift" ); let key = "\u{1b}[57362;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Pause).with_shift_modifier()), "Can parse a bare 'Pause' keypress with shift" ); let key = "\u{1b}[57363;2u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Menu).with_shift_modifier()), "Can parse a bare 'Menu' keypress with shift" ); let key = "\u{1b}[2;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Insert).with_shift_modifier()), "Can parse a bare 'Insert' keypress with shift" ); let key = "\u{1b}[3;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Delete).with_shift_modifier()), "Can parse a bare 'Delete' keypress with shift" ); let key = "\u{1b}[5;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageUp).with_shift_modifier()), "Can parse a bare 'PageUp' keypress with shift" ); let key = "\u{1b}[6;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageDown).with_shift_modifier()), "Can parse a bare 'PageDown' keypress with shift" ); let key = "\u{1b}[7;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home).with_shift_modifier()), "Can parse a bare 'Home' keypress with shift" ); let key = "\u{1b}[8;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End).with_shift_modifier()), "Can parse a bare 'End' keypress with shift" ); let key = "\u{1b}[11;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1)).with_shift_modifier()), "Can parse a bare 'F1' keypress with shift" ); let key = "\u{1b}[12;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2)).with_shift_modifier()), "Can parse a bare 'F2' keypress with shift" ); let key = "\u{1b}[13;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(3)).with_shift_modifier()), "Can parse a bare 'F3' keypress with shift" ); let key = "\u{1b}[14;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4)).with_shift_modifier()), "Can parse a bare 'F4' keypress with shift" ); let key = "\u{1b}[15;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(5)).with_shift_modifier()), "Can parse a bare 'F5' keypress with shift" ); let key = "\u{1b}[17;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(6)).with_shift_modifier()), "Can parse a bare 'F6' keypress with shift" ); let key = "\u{1b}[18;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(7)).with_shift_modifier()), "Can parse a bare 'F7' keypress with shift" ); let key = "\u{1b}[19;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(8)).with_shift_modifier()), "Can parse a bare 'F8' keypress with shift" ); let key = "\u{1b}[20;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(9)).with_shift_modifier()), "Can parse a bare 'F9' keypress with shift" ); let key = "\u{1b}[21;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(10)).with_shift_modifier()), "Can parse a bare 'F10' keypress with shift" ); let key = "\u{1b}[23;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(11)).with_shift_modifier()), "Can parse a bare 'F11' keypress with shift" ); let key = "\u{1b}[24;2~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(12)).with_shift_modifier()), "Can parse a bare 'F12' keypress with shift" ); let key = "\u{1b}[1;2D"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Left).with_shift_modifier()), "Can parse a bare 'Left' keypress with shift" ); let key = "\u{1b}[1;2C"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Right).with_shift_modifier()), "Can parse a bare 'Right' keypress with shift" ); let key = "\u{1b}[1;2A"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Up).with_shift_modifier()), "Can parse a bare 'Up' keypress with shift" ); let key = "\u{1b}[1;2B"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Down).with_shift_modifier()), "Can parse a bare 'Down' keypress with shift" ); let key = "\u{1b}[1;2H"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home).with_shift_modifier()), "Can parse a bare 'Home' keypress with shift" ); let key = "\u{1b}[1;2F"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End).with_shift_modifier()), "Can parse a bare 'End' keypress with shift" ); let key = "\u{1b}[1;2P"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1)).with_shift_modifier()), "Can parse a bare 'F1 (alternate)' keypress with shift" ); let key = "\u{1b}[1;2Q"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2)).with_shift_modifier()), "Can parse a bare 'F2 (alternate)' keypress with shift" ); let key = "\u{1b}[1;2S"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4)).with_shift_modifier()), "Can parse a bare 'F4 (alternate)' keypress with shift" ); @@ -589,236 +683,236 @@ pub fn can_parse_keys_with_alt_modifier() { use zellij_utils::data::BareKey; let key = "\u{1b}[97;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('a')).with_alt_modifier()), "Can parse a bare 'a' keypress with alt" ); let key = "\u{1b}[49;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('1')).with_alt_modifier()), "Can parse a bare '1' keypress with alt" ); let key = "\u{1b}[27;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Esc).with_alt_modifier()), "Can parse a bare 'ESC' keypress with alt" ); let key = "\u{1b}[13;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Enter).with_alt_modifier()), "Can parse a bare 'ENTER' keypress with alt" ); let key = "\u{1b}[9;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Tab).with_alt_modifier()), "Can parse a bare 'Tab' keypress with alt" ); let key = "\u{1b}[127;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Backspace).with_alt_modifier()), "Can parse a bare 'Backspace' keypress with alt" ); let key = "\u{1b}[57358;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::CapsLock).with_alt_modifier()), "Can parse a bare 'CapsLock' keypress with alt" ); let key = "\u{1b}[57359;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::ScrollLock).with_alt_modifier()), "Can parse a bare 'ScrollLock' keypress with alt" ); let key = "\u{1b}[57360;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::NumLock).with_alt_modifier()), "Can parse a bare 'NumLock' keypress with alt" ); let key = "\u{1b}[57361;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PrintScreen).with_alt_modifier()), "Can parse a bare 'PrintScreen' keypress with alt" ); let key = "\u{1b}[57362;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Pause).with_alt_modifier()), "Can parse a bare 'Pause' keypress with alt" ); let key = "\u{1b}[57363;3u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Menu).with_alt_modifier()), "Can parse a bare 'Menu' keypress with alt" ); let key = "\u{1b}[2;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Insert).with_alt_modifier()), "Can parse a bare 'Insert' keypress with alt" ); let key = "\u{1b}[3;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Delete).with_alt_modifier()), "Can parse a bare 'Delete' keypress with alt" ); let key = "\u{1b}[5;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageUp).with_alt_modifier()), "Can parse a bare 'PageUp' keypress with alt" ); let key = "\u{1b}[6;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageDown).with_alt_modifier()), "Can parse a bare 'PageDown' keypress with alt" ); let key = "\u{1b}[7;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home).with_alt_modifier()), "Can parse a bare 'Home' keypress with alt" ); let key = "\u{1b}[8;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End).with_alt_modifier()), "Can parse a bare 'End' keypress with alt" ); let key = "\u{1b}[11;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1)).with_alt_modifier()), "Can parse a bare 'F1' keypress with alt" ); let key = "\u{1b}[12;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2)).with_alt_modifier()), "Can parse a bare 'F2' keypress with alt" ); let key = "\u{1b}[13;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(3)).with_alt_modifier()), "Can parse a bare 'F3' keypress with alt" ); let key = "\u{1b}[14;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4)).with_alt_modifier()), "Can parse a bare 'F4' keypress with alt" ); let key = "\u{1b}[15;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(5)).with_alt_modifier()), "Can parse a bare 'F5' keypress with alt" ); let key = "\u{1b}[17;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(6)).with_alt_modifier()), "Can parse a bare 'F6' keypress with alt" ); let key = "\u{1b}[18;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(7)).with_alt_modifier()), "Can parse a bare 'F7' keypress with alt" ); let key = "\u{1b}[19;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(8)).with_alt_modifier()), "Can parse a bare 'F8' keypress with alt" ); let key = "\u{1b}[20;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(9)).with_alt_modifier()), "Can parse a bare 'F9' keypress with alt" ); let key = "\u{1b}[21;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(10)).with_alt_modifier()), "Can parse a bare 'F10' keypress with alt" ); let key = "\u{1b}[23;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(11)).with_alt_modifier()), "Can parse a bare 'F11' keypress with alt" ); let key = "\u{1b}[24;3~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(12)).with_alt_modifier()), "Can parse a bare 'F12' keypress with alt" ); let key = "\u{1b}[1;3D"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Left).with_alt_modifier()), "Can parse a bare 'Left' keypress with alt" ); let key = "\u{1b}[1;3C"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Right).with_alt_modifier()), "Can parse a bare 'Right' keypress with alt" ); let key = "\u{1b}[1;3A"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Up).with_alt_modifier()), "Can parse a bare 'Up' keypress with alt" ); let key = "\u{1b}[1;3B"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Down).with_alt_modifier()), "Can parse a bare 'Down' keypress with alt" ); let key = "\u{1b}[1;3H"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home).with_alt_modifier()), "Can parse a bare 'Home' keypress with alt" ); let key = "\u{1b}[1;3F"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End).with_alt_modifier()), "Can parse a bare 'End' keypress with alt" ); let key = "\u{1b}[1;3P"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1)).with_alt_modifier()), "Can parse a bare 'F1 (alternate)' keypress with alt" ); let key = "\u{1b}[1;3Q"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2)).with_alt_modifier()), "Can parse a bare 'F2 (alternate)' keypress with alt" ); let key = "\u{1b}[1;3S"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4)).with_alt_modifier()), "Can parse a bare 'F4 (alternate)' keypress with alt" ); @@ -829,236 +923,236 @@ pub fn can_parse_keys_with_ctrl_modifier() { use zellij_utils::data::BareKey; let key = "\u{1b}[97;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier()), "Can parse a bare 'a' keypress with ctrl" ); let key = "\u{1b}[49;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('1')).with_ctrl_modifier()), "Can parse a bare '1' keypress with ctrl" ); let key = "\u{1b}[27;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Esc).with_ctrl_modifier()), "Can parse a bare 'ESC' keypress with ctrl" ); let key = "\u{1b}[13;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Enter).with_ctrl_modifier()), "Can parse a bare 'ENTER' keypress with ctrl" ); let key = "\u{1b}[9;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Tab).with_ctrl_modifier()), "Can parse a bare 'Tab' keypress with ctrl" ); let key = "\u{1b}[127;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Backspace).with_ctrl_modifier()), "Can parse a bare 'Backspace' keypress with ctrl" ); let key = "\u{1b}[57358;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::CapsLock).with_ctrl_modifier()), "Can parse a bare 'CapsLock' keypress with ctrl" ); let key = "\u{1b}[57359;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::ScrollLock).with_ctrl_modifier()), "Can parse a bare 'ScrollLock' keypress with ctrl" ); let key = "\u{1b}[57360;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::NumLock).with_ctrl_modifier()), "Can parse a bare 'NumLock' keypress with ctrl" ); let key = "\u{1b}[57361;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PrintScreen).with_ctrl_modifier()), "Can parse a bare 'PrintScreen' keypress with ctrl" ); let key = "\u{1b}[57362;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Pause).with_ctrl_modifier()), "Can parse a bare 'Pause' keypress with ctrl" ); let key = "\u{1b}[57363;5u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Menu).with_ctrl_modifier()), "Can parse a bare 'Menu' keypress with ctrl" ); let key = "\u{1b}[2;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Insert).with_ctrl_modifier()), "Can parse a bare 'Insert' keypress with ctrl" ); let key = "\u{1b}[3;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Delete).with_ctrl_modifier()), "Can parse a bare 'Delete' keypress with ctrl" ); let key = "\u{1b}[5;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageUp).with_ctrl_modifier()), "Can parse a bare 'PageUp' keypress with ctrl" ); let key = "\u{1b}[6;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageDown).with_ctrl_modifier()), "Can parse a bare 'PageDown' keypress with ctrl" ); let key = "\u{1b}[7;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home).with_ctrl_modifier()), "Can parse a bare 'Home' keypress with ctrl" ); let key = "\u{1b}[8;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End).with_ctrl_modifier()), "Can parse a bare 'End' keypress with ctrl" ); let key = "\u{1b}[11;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1)).with_ctrl_modifier()), "Can parse a bare 'F1' keypress with ctrl" ); let key = "\u{1b}[12;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2)).with_ctrl_modifier()), "Can parse a bare 'F2' keypress with ctrl" ); let key = "\u{1b}[13;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(3)).with_ctrl_modifier()), "Can parse a bare 'F3' keypress with ctrl" ); let key = "\u{1b}[14;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4)).with_ctrl_modifier()), "Can parse a bare 'F4' keypress with ctrl" ); let key = "\u{1b}[15;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(5)).with_ctrl_modifier()), "Can parse a bare 'F5' keypress with ctrl" ); let key = "\u{1b}[17;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(6)).with_ctrl_modifier()), "Can parse a bare 'F6' keypress with ctrl" ); let key = "\u{1b}[18;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(7)).with_ctrl_modifier()), "Can parse a bare 'F7' keypress with ctrl" ); let key = "\u{1b}[19;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(8)).with_ctrl_modifier()), "Can parse a bare 'F8' keypress with ctrl" ); let key = "\u{1b}[20;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(9)).with_ctrl_modifier()), "Can parse a bare 'F9' keypress with ctrl" ); let key = "\u{1b}[21;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(10)).with_ctrl_modifier()), "Can parse a bare 'F10' keypress with ctrl" ); let key = "\u{1b}[23;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(11)).with_ctrl_modifier()), "Can parse a bare 'F11' keypress with ctrl" ); let key = "\u{1b}[24;5~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(12)).with_ctrl_modifier()), "Can parse a bare 'F12' keypress with ctrl" ); let key = "\u{1b}[1;5D"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Left).with_ctrl_modifier()), "Can parse a bare 'Left' keypress with ctrl" ); let key = "\u{1b}[1;5C"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Right).with_ctrl_modifier()), "Can parse a bare 'Right' keypress with ctrl" ); let key = "\u{1b}[1;5A"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Up).with_ctrl_modifier()), "Can parse a bare 'Up' keypress with ctrl" ); let key = "\u{1b}[1;5B"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Down).with_ctrl_modifier()), "Can parse a bare 'Down' keypress with ctrl" ); let key = "\u{1b}[1;5H"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home).with_ctrl_modifier()), "Can parse a bare 'Home' keypress with ctrl" ); let key = "\u{1b}[1;5F"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End).with_ctrl_modifier()), "Can parse a bare 'End' keypress with ctrl" ); let key = "\u{1b}[1;5P"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1)).with_ctrl_modifier()), "Can parse a bare 'F1 (ctrlernate)' keypress with ctrl" ); let key = "\u{1b}[1;5Q"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2)).with_ctrl_modifier()), "Can parse a bare 'F2 (ctrlernate)' keypress with ctrl" ); let key = "\u{1b}[1;5S"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4)).with_ctrl_modifier()), "Can parse a bare 'F4 (ctrlernate)' keypress with ctrl" ); @@ -1069,236 +1163,236 @@ pub fn can_parse_keys_with_super_modifier() { use zellij_utils::data::BareKey; let key = "\u{1b}[97;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('a')).with_super_modifier()), "Can parse a bare 'a' keypress with super" ); let key = "\u{1b}[49;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Char('1')).with_super_modifier()), "Can parse a bare '1' keypress with super" ); let key = "\u{1b}[27;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Esc).with_super_modifier()), "Can parse a bare 'ESC' keypress with super" ); let key = "\u{1b}[13;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Enter).with_super_modifier()), "Can parse a bare 'ENTER' keypress with super" ); let key = "\u{1b}[9;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Tab).with_super_modifier()), "Can parse a bare 'Tab' keypress with super" ); let key = "\u{1b}[127;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Backspace).with_super_modifier()), "Can parse a bare 'Backspace' keypress with super" ); let key = "\u{1b}[57358;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::CapsLock).with_super_modifier()), "Can parse a bare 'CapsLock' keypress with super" ); let key = "\u{1b}[57359;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::ScrollLock).with_super_modifier()), "Can parse a bare 'ScrollLock' keypress with super" ); let key = "\u{1b}[57360;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::NumLock).with_super_modifier()), "Can parse a bare 'NumLock' keypress with super" ); let key = "\u{1b}[57361;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PrintScreen).with_super_modifier()), "Can parse a bare 'PrintScreen' keypress with super" ); let key = "\u{1b}[57362;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Pause).with_super_modifier()), "Can parse a bare 'Pause' keypress with super" ); let key = "\u{1b}[57363;9u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Menu).with_super_modifier()), "Can parse a bare 'Menu' keypress with super" ); let key = "\u{1b}[2;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Insert).with_super_modifier()), "Can parse a bare 'Insert' keypress with super" ); let key = "\u{1b}[3;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Delete).with_super_modifier()), "Can parse a bare 'Delete' keypress with super" ); let key = "\u{1b}[5;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageUp).with_super_modifier()), "Can parse a bare 'PageUp' keypress with super" ); let key = "\u{1b}[6;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::PageDown).with_super_modifier()), "Can parse a bare 'PageDown' keypress with super" ); let key = "\u{1b}[7;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home).with_super_modifier()), "Can parse a bare 'Home' keypress with super" ); let key = "\u{1b}[8;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End).with_super_modifier()), "Can parse a bare 'End' keypress with super" ); let key = "\u{1b}[11;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1)).with_super_modifier()), "Can parse a bare 'F1' keypress with super" ); let key = "\u{1b}[12;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2)).with_super_modifier()), "Can parse a bare 'F2' keypress with super" ); let key = "\u{1b}[13;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(3)).with_super_modifier()), "Can parse a bare 'F3' keypress with super" ); let key = "\u{1b}[14;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4)).with_super_modifier()), "Can parse a bare 'F4' keypress with super" ); let key = "\u{1b}[15;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(5)).with_super_modifier()), "Can parse a bare 'F5' keypress with super" ); let key = "\u{1b}[17;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(6)).with_super_modifier()), "Can parse a bare 'F6' keypress with super" ); let key = "\u{1b}[18;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(7)).with_super_modifier()), "Can parse a bare 'F7' keypress with super" ); let key = "\u{1b}[19;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(8)).with_super_modifier()), "Can parse a bare 'F8' keypress with super" ); let key = "\u{1b}[20;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(9)).with_super_modifier()), "Can parse a bare 'F9' keypress with super" ); let key = "\u{1b}[21;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(10)).with_super_modifier()), "Can parse a bare 'F10' keypress with super" ); let key = "\u{1b}[23;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(11)).with_super_modifier()), "Can parse a bare 'F11' keypress with super" ); let key = "\u{1b}[24;9~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(12)).with_super_modifier()), "Can parse a bare 'F12' keypress with super" ); let key = "\u{1b}[1;9D"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Left).with_super_modifier()), "Can parse a bare 'Left' keypress with super" ); let key = "\u{1b}[1;9C"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Right).with_super_modifier()), "Can parse a bare 'Right' keypress with super" ); let key = "\u{1b}[1;9A"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Up).with_super_modifier()), "Can parse a bare 'Up' keypress with super" ); let key = "\u{1b}[1;9B"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Down).with_super_modifier()), "Can parse a bare 'Down' keypress with super" ); let key = "\u{1b}[1;9H"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::Home).with_super_modifier()), "Can parse a bare 'Home' keypress with super" ); let key = "\u{1b}[1;9F"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::End).with_super_modifier()), "Can parse a bare 'End' keypress with super" ); let key = "\u{1b}[1;9P"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(1)).with_super_modifier()), "Can parse a bare 'F1 (alternate)' keypress with super" ); let key = "\u{1b}[1;9Q"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(2)).with_super_modifier()), "Can parse a bare 'F2 (alternate)' keypress with super" ); let key = "\u{1b}[1;9S"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some(KeyWithModifier::new(BareKey::F(4)).with_super_modifier()), "Can parse a bare 'F4 (alternate)' keypress with super" ); @@ -1309,7 +1403,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { use zellij_utils::data::BareKey; let key = "\u{1b}[97;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Char('a')) .with_super_modifier() @@ -1321,7 +1415,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[49;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Char('1')) .with_super_modifier() @@ -1333,7 +1427,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[27;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Esc) .with_super_modifier() @@ -1345,7 +1439,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[13;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Enter) .with_super_modifier() @@ -1357,7 +1451,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[9;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Tab) .with_super_modifier() @@ -1369,7 +1463,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[127;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Backspace) .with_super_modifier() @@ -1381,7 +1475,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[57358;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::CapsLock) .with_super_modifier() @@ -1393,7 +1487,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[57359;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::ScrollLock) .with_super_modifier() @@ -1405,7 +1499,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[57360;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::NumLock) .with_super_modifier() @@ -1417,7 +1511,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[57361;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::PrintScreen) .with_super_modifier() @@ -1429,7 +1523,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[57362;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Pause) .with_super_modifier() @@ -1441,7 +1535,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[57363;16u"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Menu) .with_super_modifier() @@ -1454,7 +1548,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { let key = "\u{1b}[2;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Insert) .with_super_modifier() @@ -1466,7 +1560,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[3;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Delete) .with_super_modifier() @@ -1478,7 +1572,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[5;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::PageUp) .with_super_modifier() @@ -1490,7 +1584,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[6;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::PageDown) .with_super_modifier() @@ -1502,7 +1596,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[7;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Home) .with_super_modifier() @@ -1514,7 +1608,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[8;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::End) .with_super_modifier() @@ -1526,7 +1620,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[11;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(1)) .with_super_modifier() @@ -1538,7 +1632,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[12;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(2)) .with_super_modifier() @@ -1550,7 +1644,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[13;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(3)) .with_super_modifier() @@ -1562,7 +1656,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[14;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(4)) .with_super_modifier() @@ -1574,7 +1668,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[15;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(5)) .with_super_modifier() @@ -1586,7 +1680,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[17;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(6)) .with_super_modifier() @@ -1598,7 +1692,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[18;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(7)) .with_super_modifier() @@ -1610,7 +1704,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[19;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(8)) .with_super_modifier() @@ -1622,7 +1716,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[20;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(9)) .with_super_modifier() @@ -1634,7 +1728,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[21;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(10)) .with_super_modifier() @@ -1646,7 +1740,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[23;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(11)) .with_super_modifier() @@ -1658,7 +1752,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[24;16~"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(12)) .with_super_modifier() @@ -1670,7 +1764,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16D"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Left) .with_super_modifier() @@ -1682,7 +1776,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16C"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Right) .with_super_modifier() @@ -1694,7 +1788,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16A"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Up) .with_super_modifier() @@ -1706,7 +1800,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16B"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Down) .with_super_modifier() @@ -1718,7 +1812,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16H"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::Home) .with_super_modifier() @@ -1730,7 +1824,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16F"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::End) .with_super_modifier() @@ -1742,7 +1836,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16P"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(1)) .with_super_modifier() @@ -1754,7 +1848,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16Q"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(2)) .with_super_modifier() @@ -1766,7 +1860,7 @@ pub fn can_parse_keys_with_multiple_modifiers() { ); let key = "\u{1b}[1;16S"; assert_eq!( - KittyKeyboardParser::new().parse(&key.as_bytes()), + parse_for_test(key.as_bytes()), Some( KeyWithModifier::new(BareKey::F(4)) .with_super_modifier() @@ -1777,3 +1871,61 @@ pub fn can_parse_keys_with_multiple_modifiers() { "Can parse a bare 'F4 (superernate)' keypress with all modifiers" ); } + +// ===================================================================== +// Cross-chunk fragmentation tests for the long-lived feed() entry +// point. Under SSH or any kernel-boundary-fragmented stdin read, a +// single Kitty CSI sequence routinely arrives split across multiple +// chunks; feed() must keep state across calls so the sequence still +// resolves on a follow-up chunk instead of degrading to legacy CSI +// form (and losing modifier metadata). +// ===================================================================== + +#[test] +fn fragmented_kitty_csi_u_emits_one_event() { + use zellij_utils::data::BareKey; + let mut p = KittyKeyboardParser::new(); + let r1 = p.feed(b"\x1b[97;"); + assert!(matches!(r1, KittyParseOutcome::Incomplete)); + match p.feed(b"2u") { + KittyParseOutcome::Complete(k) => { + assert_eq!( + k, + KeyWithModifier::new(BareKey::Char('a')).with_shift_modifier() + ); + }, + other => panic!("expected Complete, got {:?}", other), + } +} + +#[test] +fn fragmented_kitty_byte_by_byte() { + use zellij_utils::data::BareKey; + let full = b"\x1b[97;5u"; // ctrl+a + let mut p = KittyKeyboardParser::new(); + for &b in &full[..full.len() - 1] { + assert!( + matches!(p.feed(&[b]), KittyParseOutcome::Incomplete), + "byte 0x{:02x} should be Incomplete", + b + ); + } + match p.feed(&[full[full.len() - 1]]) { + KittyParseOutcome::Complete(k) => { + assert_eq!( + k, + KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier() + ); + }, + other => panic!("expected Complete, got {:?}", other), + } +} + +#[test] +fn non_kitty_bytes_yield_nomatch_and_reset() { + // Plain printable bytes don't form a Kitty sequence — must return + // NoMatch (not Incomplete) so the caller falls through to termwiz + // immediately rather than buffering forever. + let mut p = KittyKeyboardParser::new(); + assert!(matches!(p.feed(b"hello"), KittyParseOutcome::NoMatch)); +} diff --git a/zellij-client/src/lib.rs b/zellij-client/src/lib.rs index de50cfb6..a1fcf387 100644 --- a/zellij-client/src/lib.rs +++ b/zellij-client/src/lib.rs @@ -54,6 +54,17 @@ const SHOW_CURSOR: &str = "\u{1b}[?25h"; const ENTER_KITTY_KEYBOARD_MODE: &str = "\u{1b}[>1u"; const EXIT_KITTY_KEYBOARD_MODE: &str = "\u{1b}[<1u"; const CLEAR_CLIENT_TERMINAL_ATTRIBUTES: &str = "\u{1b}[?1l\u{1b}=\u{1b}[r\u{1b}[?1000l\u{1b}[?1002l\u{1b}[?1003l\u{1b}[?1005l\u{1b}[?1006l\u{1b}[?12l"; +/// Subscribe to host color-palette theme notifications (CSI 2031). Hosts +/// that support it begin emitting unsolicited DSR 997 reports on theme +/// change after this is sent. +const ENABLE_HOST_THEME_NOTIFY: &str = "\u{1b}[?2031h"; +/// Cancel the CSI 2031 subscription (sent on detach / shutdown so we +/// don't leave the host emitting DSR 997s into nothing). +const DISABLE_HOST_THEME_NOTIFY: &str = "\u{1b}[?2031l"; +/// Actively query the current host theme (DSR 996). Reply arrives in the +/// same `CSI ? 997 ; {1|2} n` form as unsolicited notifications, so the +/// stdin parser handles both uniformly. +const QUERY_HOST_THEME: &str = "\u{1b}[?996n"; /// Spawn an async runtime for this client instance. /// @@ -139,7 +150,7 @@ use crate::{ }; use zellij_utils::cli::CliArgs; use zellij_utils::{ - channels::{self, ChannelWithContext, RecvTimeoutError, SenderWithContext}, + channels::{self, ChannelWithContext, SenderWithContext}, consts::{set_permissions, ZELLIJ_SOCK_DIR}, data::{ClientId, ConnectToSession, KeyWithModifier, LayoutInfo, LayoutMetadata}, envs, @@ -158,8 +169,6 @@ pub(crate) enum ClientInstruction { UnblockInputThread, Exit(ExitReason), Connected, - StartedParsingStdinQuery, - DoneParsingStdinQuery, Log(Vec<String>), LogError(Vec<String>), SwitchSession(ConnectToSession), @@ -171,6 +180,12 @@ pub(crate) enum ClientInstruction { #[allow(dead_code)] // we need the session name here even though we're not currently using it RenamedSession(String), // String -> new session name ConfigFileUpdated, + /// Server asked us to forward `query_bytes` to the host terminal and + /// collect the reply bytes into the window identified by `token`. + ForwardQueryToHost { + token: u32, + query_bytes: Vec<u8>, + }, } impl From<ServerToClientMsg> for ClientInstruction { @@ -193,6 +208,9 @@ impl From<ServerToClientMsg> for ClientInstruction { ServerToClientMsg::StartWebServer => ClientInstruction::StartWebServer, ServerToClientMsg::RenamedSession { name } => ClientInstruction::RenamedSession(name), ServerToClientMsg::ConfigFileUpdated => ClientInstruction::ConfigFileUpdated, + ServerToClientMsg::ForwardQueryToHost { token, query_bytes } => { + ClientInstruction::ForwardQueryToHost { token, query_bytes } + }, // Subscribe-only messages — not handled by regular interactive clients ServerToClientMsg::PaneRenderUpdate { .. } => ClientInstruction::UnblockInputThread, ServerToClientMsg::SubscribedPaneClosed { .. } => ClientInstruction::UnblockInputThread, @@ -210,8 +228,6 @@ impl From<&ClientInstruction> for ClientContext { ClientInstruction::Connected => ClientContext::Connected, ClientInstruction::Log(_) => ClientContext::Log, ClientInstruction::LogError(_) => ClientContext::LogError, - ClientInstruction::StartedParsingStdinQuery => ClientContext::StartedParsingStdinQuery, - ClientInstruction::DoneParsingStdinQuery => ClientContext::DoneParsingStdinQuery, ClientInstruction::SwitchSession(..) => ClientContext::SwitchSession, ClientInstruction::SetSynchronizedOutput(..) => ClientContext::SetSynchronisedOutput, ClientInstruction::UnblockCliPipeInput(..) => ClientContext::UnblockCliPipeInput, @@ -220,6 +236,7 @@ impl From<&ClientInstruction> for ClientContext { ClientInstruction::StartWebServer => ClientContext::StartWebServer, ClientInstruction::RenamedSession(..) => ClientContext::RenamedSession, ClientInstruction::ConfigFileUpdated => ClientContext::ConfigFileUpdated, + ClientInstruction::ForwardQueryToHost { .. } => ClientContext::ForwardQueryToHost, } } } @@ -414,8 +431,13 @@ pub(crate) enum InputInstruction { MouseEvent(zellij_utils::input::mouse::MouseEvent), AnsiStdinInstructions(Vec<AnsiStdinInstruction>), DesktopNotificationResponse(Vec<u8>), - StartedParsing, - DoneParsing, + /// The continuous host-reply parser closed a forwarding window (barrier + /// reply seen or timeout fired). Payload is the accumulated raw bytes + /// to ship to the server. + ForwardedReplyFromHostComplete { + token: u32, + reply_bytes: Vec<u8>, + }, Exit, } @@ -635,6 +657,10 @@ pub fn start_remote_client( stdout .write_all(ENTER_KITTY_KEYBOARD_MODE.as_bytes()) .unwrap(); + stdout + .write_all(ENABLE_HOST_THEME_NOTIFY.as_bytes()) + .unwrap(); + stdout.write_all(QUERY_HOST_THEME.as_bytes()).unwrap(); envs::set_zellij("0".to_string()); @@ -730,6 +756,14 @@ pub fn start_client( .write_all(ENTER_KITTY_KEYBOARD_MODE.as_bytes()) .unwrap(); } + // Subscribe to host CSI 2031 theme notifications and query the + // current mode. Sent right after CLEAR_CLIENT_TERMINAL_ATTRIBUTES + // so there's no window in which the host is unsubscribed. + // Hosts that don't support 2031 ignore both sequences. + stdout + .write_all(ENABLE_HOST_THEME_NOTIFY.as_bytes()) + .unwrap(); + stdout.write_all(QUERY_HOST_THEME.as_bytes()).unwrap(); } envs::set_zellij("0".to_string()); config.env.set_vars(); @@ -968,6 +1002,24 @@ pub fn start_client( } }); + // Apps running inside Zellij panes can issue a whitelisted set + // of queries to the host terminal (bg/fg colour, palette + // registers, window pixel dimensions). Each query opens a + // "forward slot" on the client: we write the query + a + // Primary-DA barrier to stdout, then collect any reply bytes + // that arrive on stdin until the barrier reply closes the slot. + // The pane that asked gets the captured bytes piped to its pty. + // + // If the host never answers, we must close the slot anyway so + // the server can dispatch the next queued forward. A per-slot + // timer task enforces that deadline: opening a forward spawns + // an async sleep on `forward_timeout_runtime()`; on wake it + // tries to close the slot for that specific token. If the + // barrier (or a later forward) closed the slot first, the + // timer's close call is a no-op — the token-guard makes + // cancellation implicit. Spawn site: the + // `ClientInstruction::ForwardQueryToHost` handler below. + let _input_thread = thread::Builder::new() .name("input_handler".to_string()) .spawn({ @@ -1074,77 +1126,15 @@ pub fn start_client( }; let mut exit_msg = String::new(); - let mut loading = true; - let mut showed_loading_message = false; - let loading_start = std::time::Instant::now(); - let loading_delay = std::time::Duration::from_millis(400); - let mut pending_instructions = vec![]; let mut synchronised_output = match os_input.env_variable("TERM").as_deref() { Some("alacritty") => Some(SyncOutput::DCS), _ => None, }; - let mut stdout = os_input.get_stdout_writer(); - loop { - let (client_instruction, mut err_ctx) = if !loading && !pending_instructions.is_empty() { - // there are buffered instructions, we need to go through them before processing the - // new ones - pending_instructions.remove(0) - } else if loading && !showed_loading_message { - let remaining = loading_delay - .checked_sub(loading_start.elapsed()) - .unwrap_or(std::time::Duration::ZERO); - match receive_client_instructions.recv_timeout(remaining) { - Ok(instruction) => instruction, - Err(RecvTimeoutError::Timeout) => { - // 400ms elapsed with no completion — show loading UI - stdout - .write_all("\u{1b}[1m\u{1b}[HLoading Zellij\u{1b}[m\n\r".as_bytes()) - .expect("cannot write to stdout"); - stdout.flush().expect("could not flush"); - showed_loading_message = true; - // Now block normally - receive_client_instructions - .recv() - .expect("failed to receive app instruction on channel") - }, - Err(RecvTimeoutError::Disconnected) => { - panic!("client instruction channel disconnected"); - }, - } - } else { - receive_client_instructions - .recv() - .expect("failed to receive app instruction on channel") - }; - - if loading { - // when the app is still loading, we buffer instructions and show a loading screen - match client_instruction { - ClientInstruction::StartedParsingStdinQuery => { - if showed_loading_message { - stdout - .write_all("Querying terminal emulator for \u{1b}[32;1mdefault colors\u{1b}[m and \u{1b}[32;1mpixel/cell\u{1b}[m ratio...".as_bytes()) - .expect("cannot write to stdout"); - stdout.flush().expect("could not flush"); - } - }, - ClientInstruction::DoneParsingStdinQuery => { - if showed_loading_message { - stdout - .write_all("done".as_bytes()) - .expect("cannot write to stdout"); - stdout.flush().expect("could not flush"); - } - loading = false; - }, - instruction => { - pending_instructions.push((instruction, err_ctx)); - }, - } - continue; - } + let (client_instruction, mut err_ctx) = receive_client_instructions + .recv() + .expect("failed to receive app instruction on channel"); err_ctx.add_call(ContextType::Client((&client_instruction).into())); @@ -1224,6 +1214,41 @@ pub fn start_client( }, } }, + ClientInstruction::ForwardQueryToHost { token, query_bytes } => { + // 1. Open a forwarding window on the parser so any reply + // events that arrive before the barrier are captured. + stdin_ansi_parser.lock().unwrap().open_forward(token); + // 2. Spawn a per-forward timer on the dedicated async + // runtime. When the deadline fires, the task closes + // the slot (if it's still open for this token) and + // relays `ForwardedReplyFromHostComplete` so the + // server releases `forward_in_flight` and dispatches + // the next queued forward. + let runtime = stdin_ansi_parser::forward_timeout_runtime(); + let parser_for_timer = stdin_ansi_parser.clone(); + let sender_for_timer = send_input_instructions.clone(); + stdin_ansi_parser::schedule_forward_timeout( + runtime.handle(), + parser_for_timer, + token, + std::time::Duration::from_millis(500), + move |token, reply_bytes| { + let _ = sender_for_timer.send( + InputInstruction::ForwardedReplyFromHostComplete { token, reply_bytes }, + ); + }, + ); + // 3. Write the query + Primary-DA barrier in a single + // write_all. The barrier closes the window on the + // parser side when its reply arrives — the timer + // task's eventual wake-up finds an empty slot for + // this token and no-ops. + let mut blob = query_bytes; + blob.extend_from_slice(b"\x1b[c"); + let mut out = os_input.get_stdout_writer(); + let _ = out.write_all(&blob); + let _ = out.flush(); + }, _ => {}, } } @@ -1391,8 +1416,9 @@ fn terminal_teardown_message(message: &str, rows: usize, include_kitty_exit: boo "" }; format!( - "{}{}{}{}{}{}\n", + "{}{}{}{}{}{}{}\n", kitty_exit, + DISABLE_HOST_THEME_NOTIFY, EXIT_ALTERNATE_SCREEN, RESET_STYLE, SHOW_CURSOR, diff --git a/zellij-client/src/stdin_ansi_parser.rs b/zellij-client/src/stdin_ansi_parser.rs index f0e2df27..d6800010 100644 --- a/zellij-client/src/stdin_ansi_parser.rs +++ b/zellij-client/src/stdin_ansi_parser.rs @@ -1,17 +1,21 @@ -use std::time::{Duration, Instant}; +//! Continuous, parser for host-terminal replies arriving on +//! stdin. +//! +//! This parser routes stdin bytes through a private `termwiz::InputParser`, +//! classifies OSC / CSI-report events into `HostReply` variants, and lets +//! all other bytes (keyboard input) pass through as a residue byte sequence +//! that the caller feeds to the normal keyboard parser. -const STARTUP_PARSE_DEADLINE_MS: u64 = 500; use lazy_static::lazy_static; use regex::Regex; +use serde::{Deserialize, Serialize}; use zellij_utils::{ - consts::ZELLIJ_STDIN_CACHE_FILE, ipc::PixelDimensions, pane_size::SizeInPixels, + data::HostTerminalThemeMode, + ipc::PixelDimensions, + pane_size::SizeInPixels, + vendored::termwiz::input::{InputEvent, InputParser}, }; -use anyhow::Result; -use serde::{Deserialize, Serialize}; -use std::fs::{File, OpenOptions}; -use std::io::{Read, Write}; - /// Describe the terminal implementation of synchronised output #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum SyncOutput { @@ -39,280 +43,579 @@ impl SyncOutput { } } -#[derive(Debug)] -pub struct StdinAnsiParser { - raw_buffer: Vec<u8>, - pending_color_sequences: Vec<(usize, String)>, - pending_events: Vec<AnsiStdinInstruction>, - parse_deadline: Option<Instant>, -} - -impl StdinAnsiParser { - pub fn new() -> Self { - StdinAnsiParser { - raw_buffer: vec![], - pending_color_sequences: vec![], - pending_events: vec![], - parse_deadline: None, - } - } - pub fn terminal_emulator_query_string(&mut self) -> String { - // note that this assumes the String will be sent to the terminal emulator and so starts a - // deadline timeout (self.parse_deadline) - - // <ESC>[14t => get text area size in pixels, - // <ESC>[16t => get character cell size in pixels - // <ESC>]11;?<ESC>\ => get background color - // <ESC>]10;?<ESC>\ => get foreground color - // <ESC>[?2026$p => get synchronised output mode - let mut query_string = String::from( - "\u{1b}[14t\u{1b}[16t\u{1b}]11;?\u{1b}\u{5c}\u{1b}]10;?\u{1b}\u{5c}\u{1b}[?2026$p", - ); - - // query colors - // eg. <ESC>]4;5;?<ESC>\ => query color register number 5 - for i in 0..256 { - query_string.push_str(&format!("\u{1b}]4;{};?\u{1b}\u{5c}", i)); - } - self.parse_deadline = - Some(Instant::now() + Duration::from_millis(STARTUP_PARSE_DEADLINE_MS)); - query_string - } - fn drain_pending_events(&mut self) -> Vec<AnsiStdinInstruction> { - let mut events = vec![]; - events.append(&mut self.pending_events); - if let Some(color_registers) = - AnsiStdinInstruction::color_registers_from_bytes(&mut self.pending_color_sequences) - { - events.push(color_registers); - } - events - } - pub fn should_parse(&self) -> bool { - if let Some(parse_deadline) = self.parse_deadline { - if parse_deadline >= Instant::now() { - return true; - } - } - false - } - pub fn startup_query_duration(&self) -> u64 { - STARTUP_PARSE_DEADLINE_MS - } - pub fn parse(&mut self, mut raw_bytes: Vec<u8>) -> Vec<AnsiStdinInstruction> { - for byte in raw_bytes.drain(..) { - self.parse_byte(byte); - } - self.drain_pending_events() - } - pub fn read_cache(&self) -> Option<Vec<AnsiStdinInstruction>> { - match OpenOptions::new() - .read(true) - .open(ZELLIJ_STDIN_CACHE_FILE.as_path()) - { - Ok(mut file) => { - let mut json_cache = String::new(); - file.read_to_string(&mut json_cache).ok()?; - let instructions = - serde_json::from_str::<Vec<AnsiStdinInstruction>>(&json_cache).ok()?; - if instructions.is_empty() { - None - } else { - Some(instructions) - } - }, - Err(e) => { - log::error!("Failed to open STDIN cache file: {:?}", e); - None - }, - } - } - pub fn write_cache(&self, events: Vec<AnsiStdinInstruction>) { - if let Ok(serialized_events) = serde_json::to_string(&events) { - if let Some(parent) = ZELLIJ_STDIN_CACHE_FILE.parent() { - let _ = std::fs::create_dir_all(parent); - } - if let Ok(mut file) = File::create(ZELLIJ_STDIN_CACHE_FILE.as_path()) { - let _ = file.write_all(serialized_events.as_bytes()); - } - }; - } - fn parse_byte(&mut self, byte: u8) { - if byte == b't' { - self.raw_buffer.push(byte); - match AnsiStdinInstruction::pixel_dimensions_from_bytes(&self.raw_buffer) { - Ok(ansi_sequence) => { - self.pending_events.push(ansi_sequence); - self.raw_buffer.clear(); - }, - Err(_) => { - self.raw_buffer.clear(); - }, - } - } else if byte == b'\\' { - self.raw_buffer.push(byte); - if let Ok(ansi_sequence) = AnsiStdinInstruction::bg_or_fg_from_bytes(&self.raw_buffer) { - self.pending_events.push(ansi_sequence); - self.raw_buffer.clear(); - } else if let Ok((color_register, color_sequence)) = - color_sequence_from_bytes(&self.raw_buffer) - { - self.raw_buffer.clear(); - self.pending_color_sequences - .push((color_register, color_sequence)); - } else { - self.raw_buffer.clear(); - } - } else if byte == b'y' { - self.raw_buffer.push(byte); - if let Some(ansi_sequence) = - AnsiStdinInstruction::synchronized_output_from_bytes(&self.raw_buffer) - { - self.pending_events.push(ansi_sequence); - self.raw_buffer.clear(); - } - } else { - self.raw_buffer.push(byte); - } - } -} - +/// A classified host-terminal reply received on stdin. +/// +/// The variants track the reply types Zellij consumes for its own +/// synchronous render hot-path (pixel dims, bg/fg, palette registers, +/// sync-output support). Accumulated forwarded-query byte streams take +/// a separate path: they ride `ParseOutput::completed_forward` through +/// a dedicated input-instruction channel so they don't get co-mingled +/// with semantically-typed state updates. #[derive(Debug, Clone, Serialize, Deserialize)] -pub enum AnsiStdinInstruction { +pub enum HostReply { PixelDimensions(PixelDimensions), BackgroundColor(String), ForegroundColor(String), ColorRegisters(Vec<(usize, String)>), SynchronizedOutput(Option<SyncOutput>), + /// DSR 997 reply / unsolicited notification reporting the host + /// terminal's color-palette theme mode (CSI 2031). + HostTerminalThemeChanged(HostTerminalThemeMode), } -impl AnsiStdinInstruction { - pub fn pixel_dimensions_from_bytes(bytes: &[u8]) -> Result<Self, &'static str> { - // eg. <ESC>[4;21;8t +/// Retained alias for the pre-refactor type name used by other modules in +/// the client. New code should prefer `HostReply`; the alias keeps the +/// existing `InputInstruction::AnsiStdinInstructions(Vec<...>)` plumbing +/// stable during the migration. +pub type AnsiStdinInstruction = HostReply; + +impl HostReply { + /// Classify an OSC payload (the bytes between the `ESC ]` prefix and + /// the ST/BEL terminator) into a known `HostReply`, if possible. + pub fn from_osc_payload(payload: &[u8]) -> Option<HostReply> { lazy_static! { - static ref RE: Regex = Regex::new(r"^\u{1b}\[(\d+);(\d+);(\d+)t$").unwrap(); + // OSC 10 (foreground) / OSC 11 (background) answer form: + // OSC 10 ; <color> ST e.g. "10;rgb:ffff/ffff/ffff" + // OSC 11 ; <color> ST + static ref FG_RE: Regex = Regex::new(r"^10;(.*)$").unwrap(); + static ref BG_RE: Regex = Regex::new(r"^11;(.*)$").unwrap(); + // OSC 4 ; N ; <color> — palette-register answer. + static ref COLOR_REGISTER_RE: Regex = Regex::new(r"^4;(\d+);(.*)$").unwrap(); } - let key_string = String::from_utf8_lossy(bytes); // TODO: handle error - let captures = RE - .captures_iter(&key_string) - .next() - .ok_or("invalid_instruction")?; - let csi_index = captures[1].parse::<usize>(); - let first_field = captures[2].parse::<usize>(); - let second_field = captures[3].parse::<usize>(); - if csi_index.is_err() || first_field.is_err() || second_field.is_err() { - return Err("invalid_instruction"); + let s = std::str::from_utf8(payload).ok()?; + if let Some(caps) = BG_RE.captures(s) { + return Some(HostReply::BackgroundColor(caps[1].to_string())); } - match csi_index { - Ok(4) => { - // text area size - Ok(AnsiStdinInstruction::PixelDimensions(PixelDimensions { + if let Some(caps) = FG_RE.captures(s) { + return Some(HostReply::ForegroundColor(caps[1].to_string())); + } + if let Some(caps) = COLOR_REGISTER_RE.captures(s) { + let index: usize = caps[1].parse().ok()?; + let color = caps[2].to_string(); + return Some(HostReply::ColorRegisters(vec![(index, color)])); + } + None + } + + /// Classify a CSI-based report (the full raw sequence including the + /// leading `ESC [`) into a `HostReply`, if possible. + /// + /// Recognised final bytes: `t` (pixel-dims reply, `CSI 4/6 ; H ; W t`), + /// `y` (DECRPM reply to `CSI ?2026$p` — sync-output support + /// advertisement). + pub fn from_csi_report(raw: &[u8]) -> Option<HostReply> { + let s = std::str::from_utf8(raw).ok()?; + lazy_static! { + // <ESC>[4;H;Wt or <ESC>[6;H;Wt + static ref PIX_RE: Regex = Regex::new(r"^\u{1b}\[(\d+);(\d+);(\d+)t$").unwrap(); + // <ESC>[?2026;Ny — DECRPM reply for sync-output (VT mode 2026) + static ref SYNC_RE: Regex = Regex::new(r"^\u{1b}\[\?2026;([0-4])\$y$").unwrap(); + // <ESC>[?997;1n (dark) / <ESC>[?997;2n (light) — DSR 997 reply + // to CSI ?996n, or unsolicited host-theme notification when + // CSI ?2031h is enabled. + static ref THEME_RE: Regex = Regex::new(r"^\u{1b}\[\?997;([12])n$").unwrap(); + } + if let Some(caps) = PIX_RE.captures(s) { + let which: usize = caps[1].parse().ok()?; + let first: usize = caps[2].parse().ok()?; + let second: usize = caps[3].parse().ok()?; + return match which { + 4 => Some(HostReply::PixelDimensions(PixelDimensions { character_cell_size: None, text_area_size: Some(SizeInPixels { - height: first_field.unwrap(), - width: second_field.unwrap(), + height: first, + width: second, }), - })) - }, - Ok(6) => { - // character cell size - Ok(AnsiStdinInstruction::PixelDimensions(PixelDimensions { + })), + 6 => Some(HostReply::PixelDimensions(PixelDimensions { character_cell_size: Some(SizeInPixels { - height: first_field.unwrap(), - width: second_field.unwrap(), + height: first, + width: second, }), text_area_size: None, - })) - }, - _ => Err("invalid sequence"), + })), + _ => None, + }; } - } - pub fn bg_or_fg_from_bytes(bytes: &[u8]) -> Result<Self, &'static str> { - // eg. <ESC>]11;rgb:0000/0000/0000\ - lazy_static! { - static ref BACKGROUND_RE: Regex = Regex::new(r"\]11;(.*)\u{1b}\\$").unwrap(); + if let Some(caps) = SYNC_RE.captures(s) { + let code: usize = caps[1].parse().ok()?; + return match code { + 1 | 2 | 3 => Some(HostReply::SynchronizedOutput(Some(SyncOutput::CSI))), + _ => Some(HostReply::SynchronizedOutput(None)), + }; } - // eg. <ESC>]10;rgb:ffff/ffff/ffff\ - lazy_static! { - static ref FOREGROUND_RE: Regex = Regex::new(r"\]10;(.*)\u{1b}\\$").unwrap(); + if let Some(caps) = THEME_RE.captures(s) { + let mode = match &caps[1] { + "1" => HostTerminalThemeMode::Dark, + "2" => HostTerminalThemeMode::Light, + _ => return None, + }; + return Some(HostReply::HostTerminalThemeChanged(mode)); } - let key_string = String::from_utf8_lossy(bytes); - if let Some(captures) = BACKGROUND_RE.captures_iter(&key_string).next() { - let background_query_response = captures[1].parse::<String>(); - match background_query_response { - Ok(background_query_response) => Ok(AnsiStdinInstruction::BackgroundColor( - background_query_response, - )), - _ => Err("invalid_instruction"), - } - } else if let Some(captures) = FOREGROUND_RE.captures_iter(&key_string).next() { - let foreground_query_response = captures[1].parse::<String>(); - match foreground_query_response { - Ok(foreground_query_response) => Ok(AnsiStdinInstruction::ForegroundColor( - foreground_query_response, - )), - _ => Err("invalid_instruction"), - } - } else { - Err("invalid_instruction") + None + } +} + +/// The "slot" tracking state for a single forwarded query currently in +/// flight to the host terminal. The parser accumulates raw reply bytes +/// into `reply_bytes` until it sees a Primary-DA (`c`) reply, which acts +/// as the serializing barrier. The timer that enforces the 500 ms +/// deadline lives on the forward-timeout runtime and owns its own +/// wall-clock — the parser itself is deadline-agnostic. +#[derive(Debug, Clone)] +pub struct ForwardSlot { + pub token: u32, + pub reply_bytes: Vec<u8>, +} + +/// Return value of `feed()`. +#[derive(Debug, Clone, Default)] +pub struct ParseOutput { + /// Classified host replies (zero or more). + pub replies: Vec<HostReply>, + /// A completed forwarded reply (Primary-DA barrier seen), ready to be + /// sent to the server. At most one per feed call; more than one in a + /// single feed would indicate the host emitted two barriers, in which + /// case only the first is honored. + pub completed_forward: Option<(u32, Vec<u8>)>, + /// OSC 99 notification-response payloads (one per OSC 99 found in + /// the chunk). Routed by the caller as + /// `InputInstruction::DesktopNotificationResponse`. Lives here, not + /// in the keyboard-parser path, because the residue scrubber + /// strips all OSC bytes before the keyboard parser sees them. + pub desktop_notifications: Vec<Vec<u8>>, + /// Residue bytes that were not classified as host replies. These are + /// the bytes the caller should feed to the keyboard parser. + pub residue: Vec<u8>, + /// `true` when the parser still holds buffered partial OSC/CSI + /// bytes that need an idle-flush to release. The caller uses this + /// to schedule a finalize tick even when the current chunk + /// produced no residue (so a lone trailing ESC isn't stranded + /// indefinitely). See `StdinAnsiParser::finalize`. + pub has_partial_state: bool, +} + +/// Cap on the size of an in-flight partial OSC/CSI buffer. Sized to +/// pass legitimate OSC 52 clipboard payloads, which carry the entire +/// clipboard base64-encoded and have no protocol-level limit (images, +/// multi-MB text dumps, etc.). Beyond this we assume a runaway or +/// malformed sequence and flush the buffered bytes back to residue — +/// same observable behaviour as today for unterminated OSC, just +/// bounded. +const PARTIAL_BUFFER_CAP_BYTES: usize = 100 * 1024 * 1024; + +/// Outcome of a single OSC/CSI walk over a byte buffer. Distinguishing +/// "needs more bytes" from "malformed" is what lets the residue +/// scrubber buffer partial sequences across `feed()` calls instead of +/// leaking their bytes into keyboard residue. +#[derive(Debug, Clone, Copy)] +enum SeqStatus { + /// Sequence is complete; consume `len` bytes from the head of buf. + Complete(usize), + /// Sequence is a valid prefix; caller should buffer these bytes + /// and prepend them to the next chunk. + NeedMore, + /// Sequence is malformed (bare ESC mid-payload, non-whitelisted + /// final byte, length cap hit). Caller should fall through to + /// emitting the leading byte as residue. + Malformed, +} + +/// Continuous host-reply parser. Lives for the whole client session. +pub struct StdinAnsiParser { + inner: InputParser, + /// Active forwarding slot: `Some` while a forwarded query is in + /// flight, `None` otherwise. + active_forward: Option<ForwardSlot>, + /// Bytes of an OSC sequence whose terminator hasn't arrived yet. + /// Carried across feed() calls so the next chunk can complete it. + partial_osc: Vec<u8>, + /// Same for CSI device-control reports. + partial_csi: Vec<u8>, +} + +impl std::fmt::Debug for StdinAnsiParser { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StdinAnsiParser") + .field("active_forward", &self.active_forward) + .field("partial_osc_len", &self.partial_osc.len()) + .field("partial_csi_len", &self.partial_csi.len()) + .finish() + } +} + +impl StdinAnsiParser { + pub fn new() -> Self { + StdinAnsiParser { + inner: InputParser::new(), + active_forward: None, + partial_osc: Vec::new(), + partial_csi: Vec::new(), } } - pub fn color_registers_from_bytes(color_sequences: &mut Vec<(usize, String)>) -> Option<Self> { - if color_sequences.is_empty() { - return None; + + /// Open a forwarding window for `token`. Subsequent reply events that + /// arrive before the Primary-DA barrier will be accumulated into the + /// slot's `reply_bytes`, in addition to being dispatched as normal + /// classified `HostReply` events. + /// + /// The server serializes forwarded queries globally (`forward_in_flight` + /// on `Screen`), so in a well-behaved session this is only ever called + /// when the slot is empty. The guards below catch a misbehaving server + /// or a race that reached through: debug builds panic so bugs surface + /// during testing, release builds log and clobber the previous slot + /// (whose accumulated bytes would otherwise silently leak). + pub fn open_forward(&mut self, token: u32) { + debug_assert!( + self.active_forward.is_none(), + "open_forward({}) called while slot for token {:?} is still active", + token, + self.active_forward.as_ref().map(|s| s.token), + ); + if let Some(existing) = self.active_forward.as_ref() { + log::warn!( + "open_forward({}) re-entered with existing slot token={} ({} accumulated bytes \ + will be dropped); server serialization should have prevented this", + token, + existing.token, + existing.reply_bytes.len(), + ); } - let mut registers = vec![]; - for (color_register, color_sequence) in color_sequences.drain(..) { - registers.push((color_register, color_sequence)); + self.active_forward = Some(ForwardSlot { + token, + reply_bytes: Vec::new(), + }); + } + + /// Close an active forwarding window without a barrier (timeout path). + /// Returns the accumulated reply bytes and the token, if any. + pub fn close_forward_on_timeout(&mut self, token: u32) -> Option<(u32, Vec<u8>)> { + match &self.active_forward { + Some(slot) if slot.token == token => { + let slot = self.active_forward.take().unwrap(); + Some((slot.token, slot.reply_bytes)) + }, + _ => None, } - Some(AnsiStdinInstruction::ColorRegisters(registers)) } - pub fn synchronized_output_from_bytes(bytes: &[u8]) -> Option<Self> { - lazy_static! { - static ref RE: Regex = Regex::new(r"^\u{1b}\[\?2026;([0|1|2|3|4])\$y$").unwrap(); + /// Currently-open slot's token, if any. Test-only inspector; + /// production code drives slot lifecycle through `open_forward`, + /// `close_forward_on_timeout`, and `feed()` directly. + #[cfg(test)] + pub fn active_forward_token(&self) -> Option<u32> { + self.active_forward.as_ref().map(|s| s.token) + } + + /// Consume a chunk of raw stdin bytes. Returns classified host replies + /// (to be dispatched to the server's cached-state consumers), at most + /// one completed forwarded reply (barrier closed the window), and the + /// residue bytes that were not part of any classified sequence — these + /// are the bytes the caller should feed to the keyboard parser. + pub fn feed(&mut self, bytes: &[u8]) -> ParseOutput { + let mut out = ParseOutput::default(); + // Collect events first (borrow-splits the InputParser across the + // callback and the post-processing mutations). + let mut events = Vec::new(); + let mut residue = Vec::new(); + self.inner.parse( + bytes, + |event| { + events.push(event); + }, + true, // maybe_more — typical stream usage + ); + for event in events { + match event { + InputEvent::OperatingSystemCommand(payload) => { + // OSC 99 (desktop-notification response) is routed + // here rather than from the keyboard parser because + // the residue scrubber removes all OSC bytes before + // the keyboard parser runs. Other OSCs are + // classified into `HostReply` for cached-state + // refinement. + if payload.starts_with(b"99;") { + out.desktop_notifications + .push(payload.get(3..).unwrap_or_default().to_vec()); + } else if let Some(reply) = HostReply::from_osc_payload(&payload) { + out.replies.push(reply); + } + if let Some(slot) = self.active_forward.as_mut() { + // Re-serialize so the pane's pty sees a legal OSC. + // Terminators vary by host; ST (ESC \) is always safe. + slot.reply_bytes.extend_from_slice(b"\x1b]"); + slot.reply_bytes.extend_from_slice(&payload); + slot.reply_bytes.extend_from_slice(b"\x1b\\"); + } + }, + InputEvent::DeviceControlReply { + params, + final_byte, + raw, + .. + } => { + match final_byte { + b'c' => { + // Primary-DA — the barrier. Close the slot and + // emit the completed forwarded reply if active. + if let Some(slot) = self.active_forward.take() { + out.completed_forward = Some((slot.token, slot.reply_bytes)); + } + // Primary-DA is NOT double-dispatched — it has + // no cached-state counterpart. + }, + _ => { + if let Some(reply) = HostReply::from_csi_report(&raw) { + out.replies.push(reply); + } + if let Some(slot) = self.active_forward.as_mut() { + slot.reply_bytes.extend_from_slice(&raw); + } + // Suppress unused-variable warning for params. + let _ = params; + }, + } + }, + // Everything else is keyboard / mouse / paste / wake input; + // we need those bytes to reach the keyboard parser. We can + // not reconstruct the exact bytes from a parsed event here, + // so we rely on the caller's own second pass through the + // keyboard parser: the residue is the concatenation of all + // input bytes that are NOT part of a classified reply. To + // produce that residue deterministically, we re-scan the + // buffer a second time below. + _ => {}, + } } - let key_string = String::from_utf8_lossy(bytes); - if let Some(captures) = RE.captures_iter(&key_string).next() { - match captures[1].parse::<usize>().ok()? { - 1 | 2 | 3 => Some(AnsiStdinInstruction::SynchronizedOutput(Some( - SyncOutput::CSI, - ))), - _ => Some(AnsiStdinInstruction::SynchronizedOutput(None)), + // Produce the residue: replay the input through a scratch parser + // that strips out OSC payloads and whitelisted CSI reports. All + // other bytes pass through unchanged. The walk is stateful so + // an OSC/CSI sequence split across `feed()` calls is buffered + // rather than leaking into residue. + residue.extend(self.strip_replies(bytes)); + out.residue = residue; + out.has_partial_state = !self.partial_osc.is_empty() || !self.partial_csi.is_empty(); + out + } + + /// Drain any speculatively-buffered partial OSC/CSI bytes back into + /// keyboard residue. Called from the stdin handler's idle-timeout + /// path so a lone trailing ESC (or any unterminated host-reply + /// prefix that never received a follow-up byte) reaches the + /// keyboard parser instead of being stuck forever waiting for a + /// disambiguating byte that is never coming. + pub fn finalize(&mut self) -> Vec<u8> { + let mut out = Vec::with_capacity(self.partial_osc.len() + self.partial_csi.len()); + out.append(&mut self.partial_osc); + out.append(&mut self.partial_csi); + out + } + + /// Walk `bytes` (with any pending partial buffer prepended) and drop + /// any OSC/whitelisted-CSI sequences, returning the remaining bytes + /// verbatim (keyboard residue). This is a byte-level scrubber — it + /// does not produce events, only bytes. + /// + /// If the chunk ends mid-sequence, the unterminated tail is held in + /// `self.partial_osc` or `self.partial_csi` and prepended to the + /// next call's input — so the corresponding bytes never reach + /// residue (and never appear as spurious keypresses) while waiting + /// for the rest of the sequence. + fn strip_replies(&mut self, bytes: &[u8]) -> Vec<u8> { + // Prepend any pending partial. At most one of (partial_osc, + // partial_csi) is non-empty at any time — the previous walk + // either completed all sequences or stopped at exactly one + // unterminated tail. + let mut working: Vec<u8> = + Vec::with_capacity(self.partial_osc.len() + self.partial_csi.len() + bytes.len()); + working.append(&mut self.partial_osc); + working.append(&mut self.partial_csi); + working.extend_from_slice(bytes); + + let mut out = Vec::with_capacity(working.len()); + let mut i = 0; + while i < working.len() { + let rest = &working[i..]; + // OSC: ESC ] ... (BEL | ESC \) + if rest.len() >= 2 && rest[0] == 0x1b && rest[1] == b']' { + match osc_status(rest) { + SeqStatus::Complete(len) => { + i += len; + continue; + }, + SeqStatus::NeedMore => { + let tail = rest.to_vec(); + if tail.len() > PARTIAL_BUFFER_CAP_BYTES { + // Cap exceeded: flush buffered bytes to + // residue and reset, preserving the + // semantic that unterminated bytes are not + // silently swallowed. + out.extend_from_slice(&tail); + } else { + self.partial_osc = tail; + } + return out; + }, + SeqStatus::Malformed => { + out.push(working[i]); + i += 1; + continue; + }, + } + } + // Whitelisted CSI report: ESC [ <params>* <intermediates>* <final> + if rest.len() >= 2 && rest[0] == 0x1b && rest[1] == b'[' { + match csi_status(rest) { + SeqStatus::Complete(len) => { + i += len; + continue; + }, + SeqStatus::NeedMore => { + let tail = rest.to_vec(); + if tail.len() > PARTIAL_BUFFER_CAP_BYTES { + out.extend_from_slice(&tail); + } else { + self.partial_csi = tail; + } + return out; + }, + SeqStatus::Malformed => { + out.push(working[i]); + i += 1; + continue; + }, + } } - } else { - None + // Lone trailing ESC at the tail — could be the start of + // either OSC or CSI; the next byte will disambiguate. Buffer + // it under partial_osc by convention; the next call's + // walker re-routes based on the actual second byte. + if rest.len() == 1 && rest[0] == 0x1b { + self.partial_osc = vec![0x1b]; + return out; + } + out.push(working[i]); + i += 1; } + out } } -fn color_sequence_from_bytes(bytes: &[u8]) -> Result<(usize, String), &'static str> { - lazy_static! { - static ref COLOR_REGISTER_RE: Regex = Regex::new(r"\]4;(.*);(.*)\u{1b}\\$").unwrap(); - } - lazy_static! { - // this form is used by eg. Alacritty, where the leading 4 is dropped in the response - static ref ALTERNATIVE_COLOR_REGISTER_RE: Regex = Regex::new(r"\](.*);(.*)\u{1b}\\$").unwrap(); +/// Walk an OSC sequence starting at the head of `buf`. Returns whether +/// the sequence is complete, needs more bytes, or is malformed. +fn osc_status(buf: &[u8]) -> SeqStatus { + if buf.get(0) != Some(&0x1b) || buf.get(1) != Some(&b']') { + return SeqStatus::Malformed; } - let key_string = String::from_utf8_lossy(bytes); - if let Some(captures) = COLOR_REGISTER_RE.captures_iter(&key_string).next() { - let color_register_response = captures[1].parse::<usize>(); - let color_response = captures[2].parse::<String>(); - match (color_register_response, color_response) { - (Ok(crr), Ok(cr)) => Ok((crr, cr)), - _ => Err("invalid_instruction"), + let mut i = 2; + while i < buf.len() { + match buf[i] { + 0x07 => return SeqStatus::Complete(i + 1), + 0x1b => match buf.get(i + 1) { + Some(&b'\\') => return SeqStatus::Complete(i + 2), + // Bare ESC followed by something other than `\` — + // malformed under the ST-only termination we accept. + Some(_) => return SeqStatus::Malformed, + // ESC at the very tail; the next chunk may bring `\` + // and finish the sequence. + None => return SeqStatus::NeedMore, + }, + _ => i += 1, } - } else if let Some(captures) = ALTERNATIVE_COLOR_REGISTER_RE - .captures_iter(&key_string) - .next() - { - let color_register_response = captures[1].parse::<usize>(); - let color_response = captures[2].parse::<String>(); - match (color_register_response, color_response) { - (Ok(crr), Ok(cr)) => Ok((crr, cr)), - _ => Err("invalid_instruction"), + } + SeqStatus::NeedMore +} + +/// Walk a whitelisted CSI report starting at the head of `buf`. +fn csi_status(buf: &[u8]) -> SeqStatus { + if buf.get(0) != Some(&0x1b) || buf.get(1) != Some(&b'[') { + return SeqStatus::Malformed; + } + let mut i = 2; + let max = 256; + while i < buf.len() && i < max { + let b = buf[i]; + match b { + 0x30..=0x3F | 0x20..=0x2F => i += 1, + b't' | b'y' | b'c' | b'n' => return SeqStatus::Complete(i + 1), + 0x40..=0x7E => return SeqStatus::Malformed, // non-whitelisted final + _ => return SeqStatus::Malformed, } + } + if i >= max { + // CSI ran past the cap without terminating — treat as malformed + // so the leading byte falls through to residue and parsing + // resumes from the next position. + SeqStatus::Malformed } else { - Err("invalid_instruction") + SeqStatus::NeedMore } } + +// ===================================================================== +// Forward-slot timeout infrastructure +// ===================================================================== + +use std::sync::{Arc, Mutex, OnceLock}; + +/// Dedicated, lazily-initialised runtime for driving forward-slot +/// timeouts. A single current-thread executor runs on its own OS +/// thread; timer tasks are `spawn`-ed onto it from the synchronous +/// `ClientInstruction::ForwardQueryToHost` handler. One-thread model +/// because timer tasks do no CPU work — they just sleep and perform a +/// millisecond-scale mutex check on wake-up. +static FORWARD_TIMEOUT_RUNTIME: OnceLock<Arc<tokio::runtime::Runtime>> = OnceLock::new(); + +pub fn forward_timeout_runtime() -> &'static Arc<tokio::runtime::Runtime> { + FORWARD_TIMEOUT_RUNTIME.get_or_init(|| { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .expect("failed to build forward-timeout runtime"); + let rt = Arc::new(rt); + let rt_for_driver = rt.clone(); + // `block_on(pending())` keeps the executor loop alive forever + // on this thread; spawned timer tasks are polled as they + // become ready (on spawn, on wake from the time driver). + std::thread::Builder::new() + .name("zellij-client-forward-timeout".into()) + .spawn(move || { + rt_for_driver.block_on(std::future::pending::<()>()); + }) + .expect("failed to spawn forward-timeout driver thread"); + rt + }) +} + +/// Spawn a timer task that closes a forward slot after `deadline` and +/// invokes `on_timeout(token, reply_bytes)` with whatever the slot +/// accumulated. Token-guard idempotent: if the barrier (or a +/// replacement forward) has already cleared the slot by the time the +/// timer wakes, `close_forward_on_timeout(token)` returns `None` and +/// `on_timeout` is never called — no explicit cancellation path +/// required. +/// +/// Extracted as a free function so tests can drive it against a +/// `tokio::time::pause()`-backed paused runtime without instantiating +/// the full client. +pub fn schedule_forward_timeout<F>( + runtime: &tokio::runtime::Handle, + parser: Arc<Mutex<StdinAnsiParser>>, + token: u32, + deadline: std::time::Duration, + on_timeout: F, +) where + F: FnOnce(u32, Vec<u8>) + Send + 'static, +{ + runtime.spawn(async move { + tokio::time::sleep(deadline).await; + let payload = parser.lock().unwrap().close_forward_on_timeout(token); + if let Some((t, bytes)) = payload { + on_timeout(t, bytes); + } + }); +} + +#[cfg(test)] +#[path = "stdin_ansi_parser_tests.rs"] +mod tests; diff --git a/zellij-client/src/stdin_ansi_parser_tests.rs b/zellij-client/src/stdin_ansi_parser_tests.rs new file mode 100644 index 00000000..0c3b442e --- /dev/null +++ b/zellij-client/src/stdin_ansi_parser_tests.rs @@ -0,0 +1,819 @@ +//! Unit tests for the continuous host-reply parser. + +use super::{schedule_forward_timeout, HostReply, StdinAnsiParser}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// Helper: collect replies and residue from a single `feed` call. +fn feed_once(parser: &mut StdinAnsiParser, bytes: &[u8]) -> (Vec<HostReply>, Vec<u8>) { + let out = parser.feed(bytes); + (out.replies, out.residue) +} + +#[test] +fn pixel_dimensions_text_area_reply() { + // CSI 4 ; H ; W t + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b[4;720;1280t"); + assert!( + residue.is_empty(), + "pixel-dim reply should be fully consumed" + ); + assert_eq!(replies.len(), 1); + match &replies[0] { + HostReply::PixelDimensions(pd) => { + let tas = pd.text_area_size.expect("text area size"); + assert_eq!(tas.height, 720); + assert_eq!(tas.width, 1280); + assert!(pd.character_cell_size.is_none()); + }, + other => panic!("unexpected reply: {:?}", other), + } +} + +#[test] +fn pixel_dimensions_character_cell_reply() { + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b[6;18;9t"); + assert!(residue.is_empty()); + match &replies[0] { + HostReply::PixelDimensions(pd) => { + let ccs = pd.character_cell_size.expect("cell size"); + assert_eq!(ccs.height, 18); + assert_eq!(ccs.width, 9); + }, + other => panic!("unexpected reply: {:?}", other), + } +} + +#[test] +fn background_color_reply() { + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b]11;rgb:0000/0000/0000\x1b\\"); + assert!(residue.is_empty()); + match &replies[0] { + HostReply::BackgroundColor(s) => assert_eq!(s, "rgb:0000/0000/0000"), + other => panic!("unexpected reply: {:?}", other), + } +} + +#[test] +fn foreground_color_reply() { + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b]10;rgb:ffff/ffff/ffff\x1b\\"); + assert!(residue.is_empty()); + match &replies[0] { + HostReply::ForegroundColor(s) => assert_eq!(s, "rgb:ffff/ffff/ffff"), + other => panic!("unexpected reply: {:?}", other), + } +} + +#[test] +fn color_register_reply() { + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b]4;5;rgb:8080/8080/8080\x1b\\"); + assert!(residue.is_empty()); + match &replies[0] { + HostReply::ColorRegisters(regs) => { + assert_eq!(regs.len(), 1); + assert_eq!(regs[0].0, 5); + assert_eq!(regs[0].1, "rgb:8080/8080/8080"); + }, + other => panic!("unexpected reply: {:?}", other), + } +} + +#[test] +fn synchronized_output_supported_reply() { + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b[?2026;1$y"); + assert!(residue.is_empty()); + match &replies[0] { + HostReply::SynchronizedOutput(Some(_)) => {}, + other => panic!("unexpected reply: {:?}", other), + } +} + +#[test] +fn keyboard_residue_passes_through_unchanged() { + // Arrow key escape sequence is NOT a whitelisted CSI report (final + // byte 'A'), so it must survive as keyboard residue verbatim. + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b[A"); + assert!(replies.is_empty()); + assert_eq!(residue, b"\x1b[A"); +} + +#[test] +fn mixed_keyboard_and_reply_extracts_both_cleanly() { + // Arrow keys bracketing a pixel-dim reply — residue should be just + // the arrow-key bytes, reply should be classified. + let mut parser = StdinAnsiParser::new(); + let mut input = Vec::new(); + input.extend_from_slice(b"\x1b[A"); + input.extend_from_slice(b"\x1b[4;720;1280t"); + input.extend_from_slice(b"\x1b[B"); + let (replies, residue) = feed_once(&mut parser, &input); + assert_eq!(replies.len(), 1); + matches!(replies[0], HostReply::PixelDimensions(_)); + assert_eq!(residue, b"\x1b[A\x1b[B"); +} + +#[test] +fn unterminated_osc_within_single_chunk_is_buffered() { + // An OSC that never terminates within a chunk is held in the + // partial-OSC buffer for the next call to complete; nothing leaks + // into residue. This is the cross-chunk-aware replacement for the + // pre-fix behaviour where unterminated OSC bytes fell through to + // residue and surfaced as spurious keypresses. + let mut parser = StdinAnsiParser::new(); + let (_replies, residue) = feed_once(&mut parser, b"\x1b]10;partial"); + assert!( + residue.is_empty(), + "unterminated OSC must be buffered, not leaked to residue: {:?}", + residue + ); +} + +#[test] +fn forwarding_window_accumulates_and_barrier_closes() { + let mut parser = StdinAnsiParser::new(); + parser.open_forward(42); + // Feed an OSC 11 reply, then the Primary-DA barrier. Use color + // bytes that do NOT contain `c` so the barrier-absence assertion + // below can use a simple byte search. + let mut chunk = Vec::new(); + chunk.extend_from_slice(b"\x1b]11;rgb:aaaa/bbbb/dddd\x1b\\"); + chunk.extend_from_slice(b"\x1b[?65;1c"); + let out = parser.feed(&chunk); + // OSC 11 was classified (double-dispatch). + assert_eq!(out.replies.len(), 1); + matches!(out.replies[0], HostReply::BackgroundColor(_)); + // Barrier closed the window, producing a completed forward. + let (token, reply_bytes) = out + .completed_forward + .expect("barrier should close the window"); + assert_eq!(token, 42); + // Reply bytes should contain the OSC 11 (re-serialized) but NOT the + // barrier reply itself. + assert!( + reply_bytes.windows(5).any(|w| w == b"]11;r"), + "OSC 11 should be in the forwarded buffer: {:?}", + reply_bytes + ); + assert!( + !reply_bytes.contains(&b'c'), + "Primary-DA barrier (final byte 'c') must not appear in forwarded reply" + ); + // Slot released. + assert!(parser.active_forward_token().is_none()); +} + +#[test] +fn unsolicited_osc_between_forwarded_query_and_barrier() { + // Scenario: host emits a stray OSC 10 between the app's OSC 11 query + // and the barrier. Both replies should end up in the forwarded + // buffer, and the barrier closes the window. + let mut parser = StdinAnsiParser::new(); + parser.open_forward(7); + let mut chunk = Vec::new(); + chunk.extend_from_slice(b"\x1b]11;rgb:1111/1111/1111\x1b\\"); + chunk.extend_from_slice(b"\x1b]10;rgb:2222/2222/2222\x1b\\"); + chunk.extend_from_slice(b"\x1b[c"); + let out = parser.feed(&chunk); + assert_eq!(out.replies.len(), 2); + let (token, reply_bytes) = out.completed_forward.unwrap(); + assert_eq!(token, 7); + // Both OSCs present. + assert!(reply_bytes.windows(4).any(|w| w == b"]11;")); + assert!(reply_bytes.windows(4).any(|w| w == b"]10;")); +} + +#[test] +fn double_dispatch_without_active_forward_still_emits_reply() { + let mut parser = StdinAnsiParser::new(); + // No open_forward — reply should still be classified. + let out = parser.feed(b"\x1b]11;rgb:ffff/ffff/ffff\x1b\\"); + assert_eq!(out.replies.len(), 1); + matches!(out.replies[0], HostReply::BackgroundColor(_)); + assert!(out.completed_forward.is_none()); +} + +#[test] +fn timeout_flushes_accumulated_bytes() { + let mut parser = StdinAnsiParser::new(); + parser.open_forward(99); + let out = parser.feed(b"\x1b]11;rgb:ffff/ffff/ffff\x1b\\"); + assert!(out.completed_forward.is_none(), "no barrier yet"); + assert!(parser.active_forward_token() == Some(99)); + // Simulate timeout firing on the watcher. + let flushed = parser.close_forward_on_timeout(99); + let (token, bytes) = flushed.expect("timeout flush should produce a payload"); + assert_eq!(token, 99); + assert!(bytes.windows(4).any(|w| w == b"]11;")); + assert!(parser.active_forward_token().is_none()); +} + +#[test] +fn stale_token_timeout_does_nothing() { + let mut parser = StdinAnsiParser::new(); + parser.open_forward(1); + // Ask to timeout a different token — nothing happens. + assert!(parser.close_forward_on_timeout(999).is_none()); + assert_eq!(parser.active_forward_token(), Some(1)); +} + +#[test] +fn fragmented_osc_does_not_leak_into_residue() { + let full = b"\x1b]11;rgb:0000/0000/0000\x1b\\"; + for split in 1..full.len() { + let mut p = StdinAnsiParser::new(); + let r1 = p.feed(&full[..split]); + let r2 = p.feed(&full[split..]); + assert!( + r1.residue.is_empty(), + "split at {}: chunk 1 residue should be empty, got {:?}", + split, + r1.residue + ); + assert!( + r2.residue.is_empty(), + "split at {}: chunk 2 residue should be empty, got {:?}", + split, + r2.residue + ); + assert_eq!( + r1.replies.len() + r2.replies.len(), + 1, + "split at {}: exactly one reply across both chunks", + split + ); + } +} + +#[test] +fn fragmented_csi_report_does_not_leak() { + // Pixel-dimensions reply (final byte 't'). + let full = b"\x1b[4;800;1200t"; + for split in 1..full.len() { + let mut p = StdinAnsiParser::new(); + let r1 = p.feed(&full[..split]); + let r2 = p.feed(&full[split..]); + assert!( + r1.residue.is_empty(), + "split at {}: c1 residue {:?}", + split, + r1.residue + ); + assert!( + r2.residue.is_empty(), + "split at {}: c2 residue {:?}", + split, + r2.residue + ); + assert_eq!(r1.replies.len() + r2.replies.len(), 1); + } +} + +#[test] +fn fragmented_osc_byte_by_byte() { + // Every byte in its own chunk — the worst case. + let full = b"\x1b]11;rgb:abcd/ef01/2345\x1b\\"; + let mut p = StdinAnsiParser::new(); + let mut total_replies = 0; + for &b in full { + let out = p.feed(&[b]); + assert!(out.residue.is_empty(), "byte 0x{:02x} leaked to residue", b); + total_replies += out.replies.len(); + } + assert_eq!(total_replies, 1); +} + +#[test] +fn lone_trailing_esc_is_buffered_then_finalized_as_residue() { + // A bare ESC byte at the tail of a chunk could be the start of an + // OSC or CSI host-reply that's been fragmented at the ESC + // boundary, so `feed` parks it under partial state instead of + // leaking it as a keyboard residue. But the byte must not stay + // parked forever — `finalize()` is the idle drain that releases + // it back to the keyboard parser when no follow-up arrives. + let mut p = StdinAnsiParser::new(); + let out = p.feed(b"\x1b"); + assert!( + out.residue.is_empty(), + "lone ESC must not leak immediately: {:?}", + out.residue + ); + assert!( + out.has_partial_state, + "lone ESC must mark has_partial_state so the caller schedules a finalize tick" + ); + let drained = p.finalize(); + assert_eq!( + drained, + vec![0x1b], + "finalize must release the parked ESC as keyboard residue" + ); + // Subsequent finalize is a no-op once the parker is empty. + assert!(p.finalize().is_empty()); +} + +#[test] +fn fragmented_osc_does_not_finalize_partial() { + // Inverse case: a real fragmented host-reply (ESC then `]...` + // arrived in two chunks with no idle between them) must NOT be + // released by finalize. The key signal is timing — if the second + // chunk arrives quickly enough the idle path is never taken, and + // the OSC completes normally. We exercise that order here. + let full = b"\x1b]11;rgb:0000/0000/0000\x1b\\"; + let mut p = StdinAnsiParser::new(); + let r1 = p.feed(&full[..1]); + assert!(r1.residue.is_empty()); + assert!(r1.has_partial_state); + let r2 = p.feed(&full[1..]); + assert!(r2.residue.is_empty(), "tail must complete the OSC"); + assert_eq!(r1.replies.len() + r2.replies.len(), 1); + assert!(p.finalize().is_empty(), "no partial left after completion"); +} + +#[test] +fn partial_osc_overflow_falls_back_to_residue() { + // An unterminated OSC larger than the cap must not grow memory + // unbounded. After the cap is hit the buffered bytes flush to + // residue and parsing resumes from a clean state. + let mut p = StdinAnsiParser::new(); + let _ = p.feed(b"\x1b]52;c;"); + let chunk = vec![b'A'; 1024 * 1024]; // 1 MB + let mut total_residue = 0usize; + for _ in 0..110 { + let out = p.feed(&chunk); + total_residue += out.residue.len(); + } + assert!( + total_residue > 0, + "overflowed partial buffer should flush to residue, not silently grow" + ); +} + +#[test] +fn osc_99_routes_into_desktop_notifications() { + // OSC 99 is the desktop-notification response. It must surface in + // ParseOutput.desktop_notifications (where the stdin handler routes + // it as InputInstruction::DesktopNotificationResponse), NOT in + // residue (which would never reach the keyboard parser anyway, + // since the scrubber strips OSC bytes). + let mut p = StdinAnsiParser::new(); + let out = p.feed(b"\x1b]99;notification body\x1b\\"); + assert!(out.residue.is_empty(), "OSC 99 must not leak to residue"); + assert!(out.replies.is_empty(), "OSC 99 is not a HostReply variant"); + assert_eq!(out.desktop_notifications.len(), 1); + assert_eq!(out.desktop_notifications[0], b"notification body".to_vec()); +} + +#[test] +fn fragmented_osc_99_emits_one_notification() { + // Cross-chunk regression: OSC 99 split across two feed() calls + // must still emit exactly one notification, with no leak into + // residue. + let full = b"\x1b]99;hello world\x1b\\"; + for split in 1..full.len() { + let mut p = StdinAnsiParser::new(); + let r1 = p.feed(&full[..split]); + let r2 = p.feed(&full[split..]); + assert!(r1.residue.is_empty(), "split at {}: c1 residue", split); + assert!(r2.residue.is_empty(), "split at {}: c2 residue", split); + let total = r1.desktop_notifications.len() + r2.desktop_notifications.len(); + assert_eq!(total, 1, "split at {}: exactly one notification", split); + } +} + +#[test] +fn malformed_osc_still_does_not_eat_following_keyboard_bytes() { + // Pre-existing invariant. An unterminated OSC followed (in a later + // chunk) by plain keyboard input — the keyboard input must reach + // residue intact once the OSC closes via proper flush. + let mut p = StdinAnsiParser::new(); + let _ = p.feed(b"\x1b]10;partial"); + let _ = p.feed(b"\x1b\\"); + let out = p.feed(b"hello"); + assert_eq!(out.residue, b"hello"); +} + +#[test] +fn cross_chunk_osc_assembles_across_feeds() { + // An OSC 11 reply split across two `feed()` calls. The inner + // `InputParser` buffers OSC state across calls, so the second + // chunk's terminator completes the sequence and the parser + // emits a single classified reply. The first chunk produces no + // reply; what lands in residue on the first chunk is byte-level + // scrubber behaviour and intentionally not pinned here (see the + // follow-up chunked_residue tests for those shapes). + let mut parser = StdinAnsiParser::new(); + let first = parser.feed(b"\x1b]11;rgb:ffff/"); + assert!( + first.replies.is_empty(), + "first chunk must not classify a reply yet: {:?}", + first.replies + ); + + let second = parser.feed(b"ffff/ffff\x1b\\"); + assert_eq!( + second.replies.len(), + 1, + "second chunk completes the OSC; parser emits one reply: {:?}", + second.replies + ); + match &second.replies[0] { + HostReply::BackgroundColor(s) => assert_eq!(s, "rgb:ffff/ffff/ffff"), + other => panic!("expected BackgroundColor, got {:?}", other), + } +} + +#[test] +fn double_dispatch_matrix_with_forward_active() { + // For each whitelisted reply variant, opening a forward window and + // feeding the reply must (a) classify the variant into + // `ParseOutput.replies` and (b) accumulate the raw bytes into the + // forward's reply buffer — both paths always fire, so cached state + // and the forwarded-to pane stay in sync. OSC 11 is already + // covered by `forwarding_window_accumulates_and_barrier_closes`; + // this test sweeps OSC 10, OSC 4, CSI 14t / 16t replies, and + // DECRPM 2026. + let cases: Vec<(&[u8], fn(&HostReply) -> bool, &str)> = vec![ + ( + b"\x1b]10;rgb:1111/2222/3333\x1b\\", + |r| matches!(r, HostReply::ForegroundColor(_)), + "OSC 10", + ), + ( + b"\x1b]4;9;rgb:4444/5555/6666\x1b\\", + |r| matches!(r, HostReply::ColorRegisters(_)), + "OSC 4", + ), + ( + b"\x1b[4;720;1280t", + |r| matches!(r, HostReply::PixelDimensions(_)), + "CSI 14t reply", + ), + ( + b"\x1b[6;18;9t", + |r| matches!(r, HostReply::PixelDimensions(_)), + "CSI 16t reply", + ), + ( + b"\x1b[?2026;1$y", + |r| matches!(r, HostReply::SynchronizedOutput(_)), + "DECRPM 2026", + ), + ]; + for (bytes, is_expected_variant, label) in cases { + let mut parser = StdinAnsiParser::new(); + parser.open_forward(11); + let out = parser.feed(bytes); + assert_eq!( + out.replies.len(), + 1, + "{}: should classify exactly one reply (got {:?})", + label, + out.replies + ); + assert!( + is_expected_variant(&out.replies[0]), + "{}: wrong variant {:?}", + label, + out.replies[0] + ); + assert!( + out.completed_forward.is_none(), + "{}: no barrier yet, slot must stay open", + label + ); + // Close the window to inspect the forward buffer. + let (token, raw) = parser + .close_forward_on_timeout(11) + .expect("forward slot should still be open"); + assert_eq!(token, 11, "{}: token preserved", label); + assert!( + !raw.is_empty(), + "{}: reply bytes must have been accumulated into the forward buffer", + label + ); + } +} + +#[test] +fn primary_da_barrier_accepts_extended_forms() { + // The barrier is "any CSI reply with final byte `c`". Real hosts + // emit parameters (`\x1b[?62;1;6c`) or the secondary-DA-esque + // prefix (`\x1b[>0;276;0c`). Both must close the forward window + // the same way the bare `\x1b[c` does. + for barrier in [ + b"\x1b[c".as_ref(), + b"\x1b[?62;1;6c".as_ref(), + b"\x1b[>0;276;0c".as_ref(), + ] { + let mut parser = StdinAnsiParser::new(); + parser.open_forward(5); + let mut chunk = Vec::new(); + chunk.extend_from_slice(b"\x1b]11;rgb:aaaa/bbbb/cccc\x1b\\"); + chunk.extend_from_slice(barrier); + let out = parser.feed(&chunk); + let (token, reply_bytes) = out + .completed_forward + .expect("every Primary-DA reply form must close the forward window"); + assert_eq!(token, 5); + assert!( + reply_bytes.windows(4).any(|w| w == b"]11;"), + "OSC 11 should be present in the forwarded buffer for barrier {:?}", + std::str::from_utf8(barrier).unwrap_or("<non-utf8>") + ); + assert!(parser.active_forward_token().is_none()); + } +} + +// ===================================================================== +// Re-entry guard on `open_forward` +// ===================================================================== + +#[test] +#[should_panic(expected = "while slot for token")] +fn open_forward_debug_asserts_on_reentry() { + // In debug builds (which is where tests run) the guard fires. This + // catches a misbehaving server that dispatches a second forward + // before receiving the first's completion — a scenario that should + // be impossible given `forward_in_flight` serialization, but the + // parser asserts it anyway so regressions surface in CI. + let mut parser = StdinAnsiParser::new(); + parser.open_forward(1); + parser.open_forward(2); // panics via debug_assert! +} + +// ===================================================================== +// `schedule_forward_timeout` — async timer, driven by paused tokio clock +// ===================================================================== + +/// Build a paused current-thread runtime with `enable_time()`. With +/// `start_paused(true)` the clock only advances when we explicitly +/// call `tokio::time::advance`, so tests don't wall-clock sleep. +fn paused_runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread() + .enable_time() + .start_paused(true) + .build() + .expect("paused runtime build must succeed") +} + +#[test] +fn timer_fires_after_deadline_and_closes_slot() { + let rt = paused_runtime(); + let parser = Arc::new(Mutex::new(StdinAnsiParser::new())); + parser.lock().unwrap().open_forward(7); + + let captured: Arc<Mutex<Option<(u32, Vec<u8>)>>> = Arc::new(Mutex::new(None)); + let captured_clone = captured.clone(); + schedule_forward_timeout( + rt.handle(), + parser.clone(), + 7, + Duration::from_millis(500), + move |token, bytes| { + *captured_clone.lock().unwrap() = Some((token, bytes)); + }, + ); + + // Drive the runtime enough to run the just-spawned task up to its + // sleep point, then jump past the deadline. + rt.block_on(async { + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_millis(600)).await; + // One more yield so the woken task can complete synchronously. + tokio::task::yield_now().await; + }); + + let (token, bytes) = captured + .lock() + .unwrap() + .take() + .expect("timer must have invoked on_timeout"); + assert_eq!(token, 7); + assert!( + bytes.is_empty(), + "nothing was fed to the parser → buffer is empty" + ); + assert!( + parser.lock().unwrap().active_forward_token().is_none(), + "slot must have been cleared by the timer" + ); +} + +#[test] +fn timer_is_noop_when_barrier_already_closed_the_slot() { + let rt = paused_runtime(); + let parser = Arc::new(Mutex::new(StdinAnsiParser::new())); + parser.lock().unwrap().open_forward(11); + + let fired: Arc<Mutex<bool>> = Arc::new(Mutex::new(false)); + let fired_clone = fired.clone(); + schedule_forward_timeout( + rt.handle(), + parser.clone(), + 11, + Duration::from_millis(500), + move |_, _| { + *fired_clone.lock().unwrap() = true; + }, + ); + + // Before the deadline, simulate the barrier arriving: feed a reply + // and the Primary-DA barrier; the parser's `completed_forward` + // path clears the slot. + { + let mut p = parser.lock().unwrap(); + let mut chunk = Vec::new(); + chunk.extend_from_slice(b"\x1b]11;rgb:0/0/0\x1b\\"); + chunk.extend_from_slice(b"\x1b[c"); + let out = p.feed(&chunk); + assert!(out.completed_forward.is_some(), "barrier should close slot"); + } + + // Now let the timer wake up — token-guard idempotency should make + // it a no-op. + rt.block_on(async { + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_millis(600)).await; + tokio::task::yield_now().await; + }); + + assert!( + !*fired.lock().unwrap(), + "timer must not invoke on_timeout once the barrier has closed the slot" + ); +} + +#[test] +fn timer_is_noop_when_slot_holds_a_different_token() { + // This models re-entry *after* the server has moved on: the old + // timer's token no longer matches the active slot, so + // `close_forward_on_timeout(old_token)` returns None and the + // callback doesn't fire. + let rt = paused_runtime(); + let parser = Arc::new(Mutex::new(StdinAnsiParser::new())); + parser.lock().unwrap().open_forward(1); + + let fired: Arc<Mutex<bool>> = Arc::new(Mutex::new(false)); + let fired_clone = fired.clone(); + schedule_forward_timeout( + rt.handle(), + parser.clone(), + 1, + Duration::from_millis(500), + move |_, _| { + *fired_clone.lock().unwrap() = true; + }, + ); + + // Close slot for token 1 via the barrier path, then open a fresh + // slot for a different token. The earlier spawned timer is still + // sleeping and holds a snapshot of token=1. + { + let mut p = parser.lock().unwrap(); + let mut chunk = Vec::new(); + chunk.extend_from_slice(b"\x1b[c"); + let _ = p.feed(&chunk); // close via barrier + p.open_forward(2); + } + + rt.block_on(async { + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_millis(600)).await; + tokio::task::yield_now().await; + }); + + assert!( + !*fired.lock().unwrap(), + "stale timer must not close the new slot" + ); + assert_eq!( + parser.lock().unwrap().active_forward_token(), + Some(2), + "new slot untouched" + ); +} + +#[test] +fn timer_preserves_accumulated_reply_bytes_on_timeout() { + // If the host went silent after emitting partial replies, the + // timer still has to flush whatever landed in the buffer so the + // pane sees *something* — empty is fine, partial is better. + let rt = paused_runtime(); + let parser = Arc::new(Mutex::new(StdinAnsiParser::new())); + parser.lock().unwrap().open_forward(22); + + // Simulate a single OSC 11 reply arriving before the host goes + // silent. + { + let mut p = parser.lock().unwrap(); + let _ = p.feed(b"\x1b]11;rgb:1234/5678/9abc\x1b\\"); + } + + let captured: Arc<Mutex<Option<(u32, Vec<u8>)>>> = Arc::new(Mutex::new(None)); + let captured_clone = captured.clone(); + schedule_forward_timeout( + rt.handle(), + parser.clone(), + 22, + Duration::from_millis(500), + move |t, b| { + *captured_clone.lock().unwrap() = Some((t, b)); + }, + ); + + rt.block_on(async { + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_millis(600)).await; + tokio::task::yield_now().await; + }); + + let (token, bytes) = captured.lock().unwrap().take().expect("timer must fire"); + assert_eq!(token, 22); + assert!( + bytes.windows(4).any(|w| w == b"]11;"), + "buffered OSC 11 bytes must appear in the flushed payload: {:?}", + bytes + ); +} + +#[test] +fn host_theme_dsr_997_dark_in_one_chunk() { + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b[?997;1n"); + assert!(residue.is_empty(), "DSR 997 reply must be fully consumed"); + assert_eq!(replies.len(), 1); + match &replies[0] { + HostReply::HostTerminalThemeChanged(mode) => { + assert_eq!(*mode, zellij_utils::data::HostTerminalThemeMode::Dark); + }, + other => panic!("expected HostTerminalThemeChanged, got {:?}", other), + } +} + +#[test] +fn host_theme_dsr_997_light_in_one_chunk() { + let mut parser = StdinAnsiParser::new(); + let (replies, residue) = feed_once(&mut parser, b"\x1b[?997;2n"); + assert!(residue.is_empty()); + match &replies[0] { + HostReply::HostTerminalThemeChanged(mode) => { + assert_eq!(*mode, zellij_utils::data::HostTerminalThemeMode::Light); + }, + other => panic!("expected HostTerminalThemeChanged, got {:?}", other), + } +} + +#[test] +fn host_theme_dsr_997_across_chunk_boundaries() { + // Same coverage philosophy as fragmented_csi_report_does_not_leak: + // split the DSR at every internal byte position and assert the + // parser still emits exactly one HostReply with no leaked residue. + let full = b"\x1b[?997;1n"; + for split in 1..full.len() { + let mut p = StdinAnsiParser::new(); + let r1 = p.feed(&full[..split]); + let r2 = p.feed(&full[split..]); + assert!( + r1.residue.is_empty(), + "split at {}: chunk 1 leaked residue {:?}", + split, + r1.residue + ); + assert!( + r2.residue.is_empty(), + "split at {}: chunk 2 leaked residue {:?}", + split, + r2.residue + ); + let total = r1.replies.len() + r2.replies.len(); + assert_eq!(total, 1, "split at {}: got {} replies", split, total); + let reply = r1.replies.into_iter().chain(r2.replies).next().unwrap(); + match reply { + HostReply::HostTerminalThemeChanged(mode) => { + assert_eq!(mode, zellij_utils::data::HostTerminalThemeMode::Dark); + }, + other => panic!("expected HostTerminalThemeChanged, got {:?}", other), + } + } +} + +#[test] +fn host_theme_dsr_997_unknown_param_dropped() { + let mut parser = StdinAnsiParser::new(); + // CSI ?997;3n is not a defined Dark/Light value; the parser + // recognises the CSI shape (final byte n) but + // `from_csi_report` rejects unknown payloads, so no HostReply is + // produced and no residue leaks (the bytes were consumed by termwiz). + let out = parser.feed(b"\x1b[?997;3n"); + assert!( + out.replies.is_empty(), + "unknown ?997;N value must not classify" + ); +} diff --git a/zellij-client/src/stdin_handler.rs b/zellij-client/src/stdin_handler.rs index dc948b06..c33e0dbf 100644 --- a/zellij-client/src/stdin_handler.rs +++ b/zellij-client/src/stdin_handler.rs @@ -1,4 +1,4 @@ -use crate::keyboard_parser::KittyKeyboardParser; +use crate::keyboard_parser::{KittyKeyboardParser, KittyParseOutcome}; use crate::os_input_output::ClientOsApi; use crate::stdin_ansi_parser::StdinAnsiParser; #[cfg(windows)] @@ -11,20 +11,6 @@ use zellij_utils::{ vendored::termwiz::input::{InputEvent, InputParser}, }; -fn send_done_parsing_after_query_timeout( - send_input_instructions: SenderWithContext<InputInstruction>, - query_duration: u64, -) { - std::thread::spawn({ - move || { - std::thread::sleep(Duration::from_millis(query_duration)); - send_input_instructions - .send(InputInstruction::DoneParsing) - .unwrap(); - } - }); -} - pub(crate) fn stdin_loop( mut os_input: Box<dyn ClientOsApi>, send_input_instructions: SenderWithContext<InputInstruction>, @@ -46,48 +32,26 @@ pub(crate) fn stdin_loop( #[cfg(windows)] let use_vt_reader = std::env::var("TERM").is_ok() && enable_vt_input(); + // Send the startup host query string so the host terminal replies + // with its live pixel dimensions, fg/bg, sync-output support, and + // palette registers. These replies will be classified by the + // continuous parser as they arrive and routed via `InputInstruction:: + // AnsiStdinInstructions` — no deadline, no cache, no loading gate. { - // on startup we send a query to the terminal emulator for stuff like the pixel size and colors - // we get a response through STDIN, so it makes sense to do this here - let mut stdin_ansi_parser = stdin_ansi_parser.lock().unwrap(); - match stdin_ansi_parser.read_cache() { - Some(events) => { - let _ = - send_input_instructions.send(InputInstruction::AnsiStdinInstructions(events)); - let _ = send_input_instructions - .send(InputInstruction::DoneParsing) - .unwrap(); - }, - None => { - // On Windows native console, the crossterm event::read() loop - // reads INPUT_RECORDs via ReadConsoleInput — not raw bytes — so - // ANSI query responses can never be read on that path. On the - // VT reader path (TERM is set), fill_buf() reads raw VT bytes - // just like Unix, so terminal queries work normally. - #[cfg(windows)] - let can_query_terminal = use_vt_reader; - #[cfg(not(windows))] - let can_query_terminal = true; + // On Windows native console, the crossterm event::read() loop + // reads INPUT_RECORDs via ReadConsoleInput — not raw bytes — so + // ANSI query responses can never be read on that path. + #[cfg(windows)] + let can_query_terminal = use_vt_reader; + #[cfg(not(windows))] + let can_query_terminal = true; - if can_query_terminal { - send_input_instructions - .send(InputInstruction::StartedParsing) - .unwrap(); - let terminal_emulator_query_string = - stdin_ansi_parser.terminal_emulator_query_string(); - let _ = os_input - .get_stdout_writer() - .write(terminal_emulator_query_string.as_bytes()) - .unwrap(); - let query_duration = stdin_ansi_parser.startup_query_duration(); - send_done_parsing_after_query_timeout( - send_input_instructions.clone(), - query_duration, - ); - } else { - let _ = send_input_instructions.send(InputInstruction::DoneParsing); - } - }, + if can_query_terminal { + let query_string = build_startup_query_string(); + let _ = os_input + .get_stdout_writer() + .write(query_string.as_bytes()) + .unwrap(); } } @@ -110,8 +74,12 @@ pub(crate) fn stdin_loop( // etc.) with ENABLE_VIRTUAL_TERMINAL_INPUT enabled so stdin delivers raw VT // byte sequences. let mut input_parser = InputParser::new(); + // Kitty keyboard parser is long-lived so a Kitty CSI sequence split + // across stdin reads still resolves on a follow-up chunk instead of + // silently degrading to a legacy CSI form (and losing modifier + // metadata). + let mut kitty_parser = KittyKeyboardParser::new(); let mut current_buffer = vec![]; - let mut ansi_stdin_events = vec![]; let (stdin_tx, stdin_rx) = mpsc::sync_channel(32); let _stdin_pump = std::thread::Builder::new() .name("stdin_pump".to_string()) @@ -142,36 +110,57 @@ pub(crate) fn stdin_loop( Ok(result) => { match result { Ok(buf) => { - { - // here we check if we need to parse specialized ANSI instructions sent over STDIN - // this happens either on startup (see above) or on SIGWINCH - // - // if we need to parse them, we do so with an internal timeout - anything else we - // receive on STDIN during that timeout is unceremoniously dropped - let mut stdin_ansi_parser = stdin_ansi_parser.lock().unwrap(); - if stdin_ansi_parser.should_parse() { - let events = stdin_ansi_parser.parse(buf); - if !events.is_empty() { - ansi_stdin_events.append(&mut events.clone()); - let _ = send_input_instructions - .send(InputInstruction::AnsiStdinInstructions(events)); - } - continue; - } + // Strip + classify any host-reply sequences + // continuously. The residue is the byte stream + // the keyboard parser should see. + let parse_output = { + let mut p = stdin_ansi_parser.lock().unwrap(); + p.feed(&buf) + }; + if !parse_output.replies.is_empty() { + let _ = send_input_instructions.send( + InputInstruction::AnsiStdinInstructions(parse_output.replies), + ); + } + if let Some((token, reply_bytes)) = parse_output.completed_forward { + let _ = send_input_instructions.send( + InputInstruction::ForwardedReplyFromHostComplete { + token, + reply_bytes, + }, + ); + } + for payload in parse_output.desktop_notifications { + let _ = send_input_instructions + .send(InputInstruction::DesktopNotificationResponse(payload)); } - if !ansi_stdin_events.is_empty() { - stdin_ansi_parser - .lock() - .unwrap() - .write_cache(ansi_stdin_events.drain(..).collect()); + let has_partial = parse_output.has_partial_state; + let residue = parse_output.residue; + if residue.is_empty() { + // If all bytes were consumed by the host-reply + // parser, nothing to feed to the keyboard + // parser. But if the host-reply parser is + // sitting on a buffered partial sequence + // (e.g. a lone trailing ESC waiting to be + // disambiguated), schedule a finalize tick + // so the idle drain releases it as keyboard + // residue when no follow-up arrives. + if has_partial { + needs_finalization = true; + } + continue; } - current_buffer.append(&mut buf.to_vec()); + current_buffer.append(&mut residue.clone()); if !explicitly_disable_kitty_keyboard_protocol { // first we try to parse with the KittyKeyboardParser - // if we fail, we try to parse normally - match KittyKeyboardParser::new().parse(&buf) { - Some(key_with_modifier) => { + // if we fail, we try to parse normally. + // Incomplete and NoMatch both fall through to the + // termwiz parser below; on Incomplete the Kitty + // parser keeps its state so the next chunk's + // continuation completes the sequence. + match kitty_parser.feed(&residue) { + KittyParseOutcome::Complete(key_with_modifier) => { send_input_instructions .send(InputInstruction::KeyWithModifierEvent( key_with_modifier, @@ -181,7 +170,7 @@ pub(crate) fn stdin_loop( .unwrap(); continue; }, - None => {}, + KittyParseOutcome::Incomplete | KittyParseOutcome::NoMatch => {}, } } @@ -192,36 +181,24 @@ pub(crate) fn stdin_loop( let maybe_more = true; let mut events = vec![]; input_parser.parse( - &buf, + &residue, |input_event: InputEvent| { events.push(input_event); }, maybe_more, ); + // Residue contains no OSC or whitelisted CSI + // reports — `StdinAnsiParser::feed` strips both + // before the keyboard parser sees the bytes. + // Every termwiz event is a key/mouse/paste/etc. for input_event in events.into_iter() { - match input_event { - InputEvent::OperatingSystemCommand(ref payload) => { - if payload.starts_with(b"99;") { - let notification_payload = - payload.get(3..).unwrap_or_default().to_vec(); - let _ = send_input_instructions.send( - InputInstruction::DesktopNotificationResponse( - notification_payload, - ), - ); - } - // Other OSC types at runtime: silently drop. - }, - other => { - send_input_instructions - .send(InputInstruction::KeyEvent( - other, - current_buffer.drain(..).collect(), - )) - .unwrap(); - }, - } + send_input_instructions + .send(InputInstruction::KeyEvent( + input_event, + current_buffer.drain(..).collect(), + )) + .unwrap(); } needs_finalization = true; @@ -242,6 +219,7 @@ pub(crate) fn stdin_loop( &mut input_parser, &mut current_buffer, send_input_instructions.clone(), + &stdin_ansi_parser, ); needs_finalization = false; }, @@ -258,34 +236,54 @@ fn finalize_events( input_parser: &mut InputParser, current_buffer: &mut Vec<u8>, send_input_instructions: SenderWithContext<InputInstruction>, + stdin_ansi_parser: &Arc<Mutex<StdinAnsiParser>>, ) { + // Drain any speculatively-buffered partial host-reply bytes (a + // lone trailing ESC, or an unterminated OSC/CSI prefix whose + // follow-up never arrived). They become keyboard residue — same + // path real keypress bytes take. Without this drain, a real Esc + // press whose byte was parked under partial_osc would be lost. + let drained = stdin_ansi_parser.lock().unwrap().finalize(); + if !drained.is_empty() { + current_buffer.extend_from_slice(&drained); + } + let mut events = vec![]; input_parser.parse( - &[], + &drained, |input_event: InputEvent| { events.push(input_event); }, false, ); + // Residue contains no OSC or whitelisted CSI reports — every + // termwiz event drained on idle is a key/mouse/paste/etc. for input_event in events { - match input_event { - InputEvent::OperatingSystemCommand(ref payload) => { - if payload.starts_with(b"99;") { - let notification_payload = payload.get(3..).unwrap_or_default().to_vec(); - let _ = send_input_instructions.send( - InputInstruction::DesktopNotificationResponse(notification_payload), - ); - } - // Other OSC types at runtime: silently drop. - }, - other => { - send_input_instructions - .send(InputInstruction::KeyEvent( - other, - current_buffer.drain(..).collect(), - )) - .unwrap(); - }, - } + send_input_instructions + .send(InputInstruction::KeyEvent( + input_event, + current_buffer.drain(..).collect(), + )) + .unwrap(); + } +} + +/// Build the fire-and-forget host-query batch sent at client startup. +/// The host's replies refine `Screen`'s cached state asynchronously as +/// they arrive; the UI does not block on them. +fn build_startup_query_string() -> String { + // <ESC>[14t => get text area size in pixels, + // <ESC>[16t => get character cell size in pixels + // <ESC>]11;?<ESC>\ => get background color + // <ESC>]10;?<ESC>\ => get foreground color + // <ESC>[?2026$p => get synchronised output mode + let mut query_string = String::from( + "\u{1b}[14t\u{1b}[16t\u{1b}]11;?\u{1b}\u{5c}\u{1b}]10;?\u{1b}\u{5c}\u{1b}[?2026$p", + ); + // query colors + // eg. <ESC>]4;5;?<ESC>\ => query color register number 5 + for i in 0..256 { + query_string.push_str(&format!("\u{1b}]4;{};?\u{1b}\u{5c}", i)); } + query_string } diff --git a/zellij-client/src/web_client/message_handlers.rs b/zellij-client/src/web_client/message_handlers.rs index 0f2c7b54..d5974ea5 100644 --- a/zellij-client/src/web_client/message_handlers.rs +++ b/zellij-client/src/web_client/message_handlers.rs @@ -1,5 +1,5 @@ use crate::input_handler::from_termwiz; -use crate::keyboard_parser::KittyKeyboardParser; +use crate::keyboard_parser::{KittyKeyboardParser, KittyParseOutcome}; use crate::os_input_output::ClientOsApi; use crate::web_client::types::BRACKETED_PASTE_END; use crate::web_client::types::BRACKETED_PASTE_START; @@ -14,6 +14,131 @@ use zellij_utils::{ vendored::termwiz::input::{InputEvent, InputParser}, }; +/// Per-WebSocket-connection parsing state. Owns the Kitty and termwiz +/// parsers so a CSI / Kitty sequence split across two WebSocket frames +/// resolves on the second frame instead of being dropped or +/// degraded-and-emitted as separate keys. +pub struct StdinSession { + kitty_parser: KittyKeyboardParser, + input_parser: InputParser, + explicitly_disable_kitty_keyboard_protocol: bool, + /// Set when the last frame left the termwiz parser holding an + /// ambiguous-but-complete event (e.g. a bare ESC). Cleared by + /// `finalize` when an idle timeout drains those events. + pending_finalize: bool, +} + +impl StdinSession { + pub fn new(explicitly_disable_kitty_keyboard_protocol: bool) -> Self { + StdinSession { + kitty_parser: KittyKeyboardParser::new(), + input_parser: InputParser::new(), + explicitly_disable_kitty_keyboard_protocol, + pending_finalize: false, + } + } + + pub fn pending_finalize(&self) -> bool { + self.pending_finalize + } + + /// Clear the pending-finalize flag without draining events. Used + /// when the WebSocket loop hits an idle timeout but the client + /// connection has already been removed — there's nowhere to send + /// the drained events, and leaving the flag set would busy-loop the + /// idle timer. + pub fn clear_pending_finalize(&mut self) { + self.pending_finalize = false; + } + + /// Drain any ambiguous-but-complete events that termwiz held back + /// on the previous `parse_stdin` call. Called from the WebSocket + /// loop after an idle interval with no further frames, mirroring + /// `stdin_handler::finalize_events`. + pub fn finalize(&mut self, os_input: &dyn ClientOsApi, mouse_old_event: &mut MouseEvent) { + let mut events = vec![]; + self.input_parser.parse( + &[], + |input_event: InputEvent| { + events.push(input_event); + }, + false, + ); + for input_event in events { + dispatch_termwiz_event(os_input, mouse_old_event, input_event, &[]); + } + self.pending_finalize = false; + } +} + +/// Dispatch a single termwiz `InputEvent` produced by either the live +/// path or the idle finalize path. `raw_bytes` is the byte slice that +/// produced the event in the live path; finalize passes an empty slice +/// because no frame is associated with the drained events. +fn dispatch_termwiz_event( + os_input: &dyn ClientOsApi, + mouse_old_event: &mut MouseEvent, + input_event: InputEvent, + raw_bytes: &[u8], +) { + match input_event { + InputEvent::Key(key_event) => { + let raw_bytes_vec = raw_bytes.to_vec(); + let key = cast_termwiz_key(key_event.clone(), &raw_bytes_vec, None); + os_input.send_to_server(ClientToServerMsg::Key { + key: key.clone(), + raw_bytes: raw_bytes_vec, + is_kitty_keyboard_protocol: false, + }); + }, + InputEvent::Mouse(mouse_event) => { + let mouse_event = from_termwiz(mouse_old_event, mouse_event); + let action = Action::MouseEvent { event: mouse_event }; + os_input.send_to_server(ClientToServerMsg::Action { + action, + terminal_id: None, + client_id: None, + is_cli_client: false, + }); + }, + InputEvent::Paste(pasted_text) => { + os_input.send_to_server(ClientToServerMsg::Action { + action: Action::Write { + key_with_modifier: None, + bytes: BRACKETED_PASTE_START.to_vec(), + is_kitty_keyboard_protocol: false, + }, + terminal_id: None, + client_id: None, + is_cli_client: false, + }); + os_input.send_to_server(ClientToServerMsg::Action { + action: Action::Write { + key_with_modifier: None, + bytes: pasted_text.as_bytes().to_vec(), + is_kitty_keyboard_protocol: false, + }, + terminal_id: None, + client_id: None, + is_cli_client: false, + }); + os_input.send_to_server(ClientToServerMsg::Action { + action: Action::Write { + key_with_modifier: None, + bytes: BRACKETED_PASTE_END.to_vec(), + is_kitty_keyboard_protocol: false, + }, + terminal_id: None, + client_id: None, + is_cli_client: false, + }); + }, + _ => { + log::error!("Unsupported event: {:#?}", input_event); + }, + } +} + use axum::extract::ws::{CloseFrame, Message, WebSocket}; use futures::{prelude::stream::SplitSink, SinkExt}; use tokio::sync::mpsc::UnboundedReceiver; @@ -85,11 +210,11 @@ pub fn parse_stdin( buf: &[u8], os_input: Box<dyn ClientOsApi>, mouse_old_event: &mut MouseEvent, - explicitly_disable_kitty_keyboard_protocol: bool, + session: &mut StdinSession, ) { - if !explicitly_disable_kitty_keyboard_protocol { - match KittyKeyboardParser::new().parse(&buf) { - Some(key_with_modifier) => { + if !session.explicitly_disable_kitty_keyboard_protocol { + match session.kitty_parser.feed(buf) { + KittyParseOutcome::Complete(key_with_modifier) => { os_input.send_to_server(ClientToServerMsg::Key { key: key_with_modifier.clone(), raw_bytes: buf.to_vec(), @@ -97,15 +222,17 @@ pub fn parse_stdin( }); return; }, - None => {}, + KittyParseOutcome::Incomplete | KittyParseOutcome::NoMatch => {}, } } - let mut input_parser = InputParser::new(); - let maybe_more = false; + // maybe_more = true so termwiz buffers ambiguous prefixes across + // WebSocket frames; the WebSocket loop calls `session.finalize` + // after an idle interval to drain any remaining ambiguous events. + let maybe_more = true; let mut events = vec![]; - input_parser.parse( - &buf, + session.input_parser.parse( + buf, |input_event: InputEvent| { events.push(input_event); }, @@ -138,53 +265,13 @@ pub fn parse_stdin( is_kitty_keyboard_protocol: false, }); }, - InputEvent::Mouse(mouse_event) => { - let mouse_event = from_termwiz(mouse_old_event, mouse_event); - let action = Action::MouseEvent { event: mouse_event }; - os_input.send_to_server(ClientToServerMsg::Action { - action, - terminal_id: None, - client_id: None, - is_cli_client: false, - }); - }, - InputEvent::Paste(pasted_text) => { - os_input.send_to_server(ClientToServerMsg::Action { - action: Action::Write { - key_with_modifier: None, - bytes: BRACKETED_PASTE_START.to_vec(), - is_kitty_keyboard_protocol: false, - }, - terminal_id: None, - client_id: None, - is_cli_client: false, - }); - os_input.send_to_server(ClientToServerMsg::Action { - action: Action::Write { - key_with_modifier: None, - bytes: pasted_text.as_bytes().to_vec(), - is_kitty_keyboard_protocol: false, - }, - terminal_id: None, - client_id: None, - is_cli_client: false, - }); - os_input.send_to_server(ClientToServerMsg::Action { - action: Action::Write { - key_with_modifier: None, - bytes: BRACKETED_PASTE_END.to_vec(), - is_kitty_keyboard_protocol: false, - }, - terminal_id: None, - client_id: None, - is_cli_client: false, - }); - }, - _ => { - log::error!("Unsupported event: {:#?}", input_event); + other => { + dispatch_termwiz_event(&*os_input, mouse_old_event, other, buf); }, } } + + session.pending_finalize = true; } #[cfg(test)] @@ -263,12 +350,13 @@ mod tests { fn ime_multi_char_input_uses_per_char_raw_bytes() { let os_input = RecordingOsInput::default(); let mut mouse_old_event = MouseEvent::new(); + let mut session = super::StdinSession::new(false); parse_stdin( "你好".as_bytes(), Box::new(os_input.clone()), &mut mouse_old_event, - false, + &mut session, ); let sent_messages = os_input.take_sent_messages(); @@ -292,12 +380,13 @@ mod tests { fn single_char_input_keeps_original_raw_bytes() { let os_input = RecordingOsInput::default(); let mut mouse_old_event = MouseEvent::new(); + let mut session = super::StdinSession::new(false); parse_stdin( "a".as_bytes(), Box::new(os_input.clone()), &mut mouse_old_event, - false, + &mut session, ); let sent_messages = os_input.take_sent_messages(); @@ -310,4 +399,89 @@ mod tests { other => panic!("expected key message, got {other:?}"), } } + + /// Cross-frame fragmentation regression. Under WebSocket transport, + /// a single ANSI sequence routinely arrives split across two frames. + /// The per-connection `StdinSession` must keep parser state across + /// `parse_stdin` calls so a Kitty CSI sequence that crosses a frame + /// boundary still resolves on the second frame. + #[test] + fn fragmented_kitty_sequence_resolves_across_frames() { + use zellij_utils::data::{BareKey, KeyWithModifier}; + let os_input = RecordingOsInput::default(); + let mut mouse_old_event = MouseEvent::new(); + let mut session = super::StdinSession::new(false); + + // Frame 1: prefix only — incomplete. + parse_stdin( + b"\x1b[97;", + Box::new(os_input.clone()), + &mut mouse_old_event, + &mut session, + ); + assert!( + os_input.take_sent_messages().is_empty(), + "incomplete Kitty prefix must not emit a key on frame 1" + ); + + // Frame 2: completes the sequence — Kitty parser emits. + parse_stdin( + b"5u", + Box::new(os_input.clone()), + &mut mouse_old_event, + &mut session, + ); + let sent = os_input.take_sent_messages(); + assert_eq!( + sent.len(), + 1, + "exactly one Kitty key event after both frames; got {:?}", + sent + ); + match &sent[0] { + ClientToServerMsg::Key { + key, + is_kitty_keyboard_protocol, + .. + } => { + assert!(*is_kitty_keyboard_protocol); + assert_eq!( + *key, + KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier() + ); + }, + other => panic!("expected Key message, got {other:?}"), + } + } + + /// Plain printable bytes that aren't a Kitty sequence must NOT be + /// trapped in the long-lived Kitty parser. After `feed()` returns + /// `NoMatch` and resets, the bytes flow through the termwiz path + /// and reach the server as ordinary key events. + #[test] + fn non_kitty_bytes_pass_through_to_termwiz_path() { + let os_input = RecordingOsInput::default(); + let mut mouse_old_event = MouseEvent::new(); + let mut session = super::StdinSession::new(false); + + parse_stdin( + b"ab", + Box::new(os_input.clone()), + &mut mouse_old_event, + &mut session, + ); + + let sent = os_input.take_sent_messages(); + // Two Char events ('a', 'b'), both via the termwiz path. + assert_eq!(sent.len(), 2); + for msg in &sent { + match msg { + ClientToServerMsg::Key { + is_kitty_keyboard_protocol, + .. + } => assert!(!*is_kitty_keyboard_protocol), + other => panic!("expected Key, got {other:?}"), + } + } + } } diff --git a/zellij-client/src/web_client/server_listener.rs b/zellij-client/src/web_client/server_listener.rs index 7ac5fa2e..c8f1c64d 100644 --- a/zellij-client/src/web_client/server_listener.rs +++ b/zellij-client/src/web_client/server_listener.rs @@ -233,6 +233,12 @@ pub fn zellij_server_listener( // Subscribe-only messages — not relevant for web clients Some(ServerToClientMsg::PaneRenderUpdate { .. }) => {}, Some(ServerToClientMsg::SubscribedPaneClosed { .. }) => {}, + Some(ServerToClientMsg::ForwardQueryToHost { .. }) => { + // Web clients do not currently participate in + // host-terminal query forwarding — the browser + // side has no stdin writer wired for the + // barrier-based protocol. Silently drop. + }, None => { if unknown_message_count >= 1000 { log::error!("Error: Received more than 1000 consecutive unknown server messages, disconnecting."); diff --git a/zellij-client/src/web_client/websocket_handlers.rs b/zellij-client/src/web_client/websocket_handlers.rs index ac7dd0ec..86b9dead 100644 --- a/zellij-client/src/web_client/websocket_handlers.rs +++ b/zellij-client/src/web_client/websocket_handlers.rs @@ -4,7 +4,7 @@ use crate::web_client::control_message::{ WebClientToWebServerControlMessagePayload, WebServerToWebClientControlMessage, }; use crate::web_client::message_handlers::{ - parse_stdin, render_to_client, send_control_messages_to_client, + parse_stdin, render_to_client, send_control_messages_to_client, StdinSession, }; use crate::web_client::server_listener::zellij_server_listener; use crate::web_client::types::{AppState, TerminalParams}; @@ -221,7 +221,46 @@ async fn handle_ws_terminal( let _ = attachment_complete_rx.await; let mut mouse_old_event = MouseEvent::new(); - while let Some(Ok(msg)) = client_terminal_channel_rx.next().await { + // Per-connection parser state. Hoisted so a CSI / Kitty sequence + // split across two WebSocket frames resolves on the second frame. + let mut stdin_session = StdinSession::new(explicitly_disable_kitty_keyboard_protocol); + let finalize_idle = std::time::Duration::from_millis(50); + loop { + // When termwiz is holding ambiguous-but-complete events from + // the previous frame, race the next frame against an idle + // timeout so the held events still drain if no further frame + // arrives. + let result = if stdin_session.pending_finalize() { + tokio::select! { + msg = client_terminal_channel_rx.next() => Some(msg), + _ = tokio::time::sleep(finalize_idle) => None, + } + } else { + Some(client_terminal_channel_rx.next().await) + }; + let msg = match result { + Some(Some(Ok(m))) => m, + Some(_) => break, + None => { + // Idle timeout fired with `pending_finalize` set: + // drain any ambiguous-but-complete events termwiz held + // back on the previous frame. + if let Some(client_connection) = state + .connection_table + .lock() + .unwrap() + .get_client_os_api(&web_client_id) + .cloned() + { + stdin_session.finalize(&*client_connection, &mut mouse_old_event); + } else { + // No client to send drained events to — clear the + // flag so we don't busy-loop the idle timer. + stdin_session.clear_pending_finalize(); + } + continue; + }, + }; match msg { Message::Binary(buf) => { let Some(client_connection) = state @@ -238,7 +277,7 @@ async fn handle_ws_terminal( &buf, client_connection.clone(), &mut mouse_old_event, - explicitly_disable_kitty_keyboard_protocol, + &mut stdin_session, ); }, Message::Text(msg) => { @@ -256,7 +295,7 @@ async fn handle_ws_terminal( msg.as_bytes(), client_connection.clone(), &mut mouse_old_event, - explicitly_disable_kitty_keyboard_protocol, + &mut stdin_session, ); }, Message::Close(_) => { diff --git a/zellij-server/src/host_query.rs b/zellij-server/src/host_query.rs new file mode 100644 index 00000000..cf35c9f4 --- /dev/null +++ b/zellij-server/src/host_query.rs @@ -0,0 +1,180 @@ +//! Classified representation of the host-terminal queries Zellij +//! forwards on behalf of apps running inside panes. +//! +//! The grid dispatcher already parses incoming OSC / CSI sequences +//! via `vte`; rather than stashing the raw bytes and re-parsing them +//! at the reply-synthesis stage, we capture the classification at +//! intercept time into a [`HostQuery`]. The pipeline from Grid → +//! Tab → Screen carries this enum; Screen's cache-fallback synthesis +//! matches on the variants directly (no byte-level regex). When we +//! have to actually send bytes on the wire (server → client → host +//! terminal), [`HostQuery::to_query_bytes`] re-derives them from the +//! enum. + +/// The two OSC string terminators in common use. Apps that phrase +/// their query with one expect the reply to mirror it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OscTerminator { + /// `ESC \` (String Terminator, xterm-style). + St, + /// `BEL` (`\x07`). + Bel, +} + +impl OscTerminator { + pub fn from_bell_terminated(bell_terminated: bool) -> Self { + if bell_terminated { + OscTerminator::Bel + } else { + OscTerminator::St + } + } + + pub fn as_bytes(self) -> &'static [u8] { + match self { + OscTerminator::St => b"\x1b\\", + OscTerminator::Bel => b"\x07", + } + } +} + +/// A whitelisted host-terminal query. Variants correspond one-to-one +/// with the entries Grid intercepts and pushes on +/// `pending_forwarded_queries`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HostQuery { + /// `CSI 14 t` — text-area pixel dimensions. + TextAreaPixelSize, + /// `CSI 16 t` — character-cell pixel dimensions. + CharacterCellPixelSize, + /// `OSC 10 ; ? <term>` — default foreground colour. + DefaultForeground { terminator: OscTerminator }, + /// `OSC 11 ; ? <term>` — default background colour. + DefaultBackground { terminator: OscTerminator }, + /// `OSC 4 ; N ; ? <term>` — palette register `N`. + PaletteRegister { + index: u8, + terminator: OscTerminator, + }, + /// `CSI ? 996 n` — query the host terminal's color-palette theme + /// mode (light or dark). NOT forwarded to the host. Zellij has + /// already queried the host once at startup (via the client's + /// `\e[?996n` write) and tracks unsolicited DSR 997 updates while + /// `\e[?2031h` is enabled, so it can answer this from cache. The + /// Screen handler short-circuits this variant: rather than writing + /// to the wire it synthesises `\e[?997;{0|1|2}n` directly into the + /// originating pane's pty. + ColorPaletteMode, +} + +impl HostQuery { + /// Re-serialize this query as the byte sequence the host terminal + /// expects. Used by the client when it writes the query to its + /// stdout, and by tests that assert on wire shape. + pub fn to_query_bytes(&self) -> Vec<u8> { + match self { + HostQuery::TextAreaPixelSize => b"\x1b[14t".to_vec(), + HostQuery::CharacterCellPixelSize => b"\x1b[16t".to_vec(), + HostQuery::DefaultForeground { terminator } => { + let mut v = b"\x1b]10;?".to_vec(); + v.extend_from_slice(terminator.as_bytes()); + v + }, + HostQuery::DefaultBackground { terminator } => { + let mut v = b"\x1b]11;?".to_vec(); + v.extend_from_slice(terminator.as_bytes()); + v + }, + HostQuery::PaletteRegister { index, terminator } => { + let mut v = format!("\x1b]4;{};?", index).into_bytes(); + v.extend_from_slice(terminator.as_bytes()); + v + }, + // `ColorPaletteMode` is answered locally by Zellij and never + // sent on the wire. Returning empty bytes keeps the call + // total without dirtying the wire format. Callers that + // bypass `Screen::forward_host_query` for this variant + // shouldn't be calling `to_query_bytes` on it at all. + HostQuery::ColorPaletteMode => Vec::new(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_area_pixel_size_serializes_as_csi_14t() { + assert_eq!(HostQuery::TextAreaPixelSize.to_query_bytes(), b"\x1b[14t"); + } + + #[test] + fn character_cell_pixel_size_serializes_as_csi_16t() { + assert_eq!( + HostQuery::CharacterCellPixelSize.to_query_bytes(), + b"\x1b[16t" + ); + } + + #[test] + fn default_foreground_mirrors_terminator() { + assert_eq!( + HostQuery::DefaultForeground { + terminator: OscTerminator::St, + } + .to_query_bytes(), + b"\x1b]10;?\x1b\\", + ); + assert_eq!( + HostQuery::DefaultForeground { + terminator: OscTerminator::Bel, + } + .to_query_bytes(), + b"\x1b]10;?\x07", + ); + } + + #[test] + fn default_background_serializes_correctly() { + assert_eq!( + HostQuery::DefaultBackground { + terminator: OscTerminator::St, + } + .to_query_bytes(), + b"\x1b]11;?\x1b\\", + ); + } + + #[test] + fn palette_register_carries_index_and_terminator() { + assert_eq!( + HostQuery::PaletteRegister { + index: 5, + terminator: OscTerminator::Bel, + } + .to_query_bytes(), + b"\x1b]4;5;?\x07", + ); + assert_eq!( + HostQuery::PaletteRegister { + index: 255, + terminator: OscTerminator::St, + } + .to_query_bytes(), + b"\x1b]4;255;?\x1b\\", + ); + } + + #[test] + fn from_bell_terminated_maps_bool_to_variant() { + assert_eq!( + OscTerminator::from_bell_terminated(true), + OscTerminator::Bel + ); + assert_eq!( + OscTerminator::from_bell_terminated(false), + OscTerminator::St + ); + } +} diff --git a/zellij-server/src/lib.rs b/zellij-server/src/lib.rs index 1f2b4d14..dea778f4 100644 --- a/zellij-server/src/lib.rs +++ b/zellij-server/src/lib.rs @@ -5,6 +5,7 @@ mod os_input_output_unix; #[path = "os_input_output_windows.rs"] mod os_input_output_windows; +pub mod host_query; pub mod os_input_output; pub mod output; pub mod panes; @@ -132,6 +133,10 @@ pub enum ServerInstruction { WebServerStarted(String), // String -> base_url FailedToStartWebServer(String), ClearMouseHelpText(ClientId), + /// Relay a forwarded-query dispatch from Screen to the server main + /// loop. The main loop writes `ServerToClientMsg::ForwardQueryToHost` + /// to any connected regular client. + ForwardQueryToHost(u32, Vec<u8>), } impl From<&ServerInstruction> for ServerContext { @@ -180,6 +185,7 @@ impl From<&ServerInstruction> for ServerContext { ServerContext::SendWebClientsForbidden }, ServerInstruction::ClearMouseHelpText(..) => ServerContext::ClearMouseHelpText, + ServerInstruction::ForwardQueryToHost(..) => ServerContext::ForwardQueryToHost, } } } @@ -377,6 +383,28 @@ impl SessionMetaData { ..Default::default() }) }); + let host_theme_dark = new_config + .options + .theme_dark + .as_ref() + .and_then(|name| new_config.theme_config(Some(name))); + let host_theme_light = new_config + .options + .theme_light + .as_ref() + .and_then(|name| new_config.theme_config(Some(name))); + if new_config.options.theme_dark.is_some() && host_theme_dark.is_none() { + log::warn!( + "theme_dark='{}' not found in themes; auto-theme switch disabled for dark.", + new_config.options.theme_dark.as_deref().unwrap_or("?") + ); + } + if new_config.options.theme_light.is_some() && host_theme_light.is_none() { + log::warn!( + "theme_light='{}' not found in themes; auto-theme switch disabled for light.", + new_config.options.theme_light.as_deref().unwrap_or("?") + ); + } self.senders .send_to_screen(ScreenInstruction::Reconfigure { client_id, @@ -388,6 +416,8 @@ impl SessionMetaData { theme: new_config .theme_config(new_config.options.theme.as_ref()) .unwrap_or_else(|| default_palette().into()), + host_theme_dark, + host_theme_light, simplified_ui: new_config.options.simplified_ui.unwrap_or(false), default_shell: new_config.options.default_shell, pane_frames: new_config.options.pane_frames.unwrap_or(true), @@ -464,10 +494,43 @@ impl Drop for SessionMetaData { } } +/// Remove a client from session state and synthesize empty +/// `ForwardedReplyFromHost` instructions for any host-query forwards +/// that had been dispatched to it. Without this, a client that goes +/// away while holding an in-flight forward leaves `Screen`'s +/// `forward_in_flight` flag stuck — the flag is only released by +/// replies, and no reply will ever come. +fn remove_client_and_flush_forwards( + client_id: ClientId, + os_input: &mut Box<dyn ServerOsApi>, + session_state: &Arc<RwLock<SessionState>>, + session_data: &Arc<RwLock<Option<SessionMetaData>>>, +) { + let _ = os_input.remove_client(client_id); + let stuck_tokens = session_state.write().unwrap().remove_client(client_id); + if stuck_tokens.is_empty() { + return; + } + if let Some(session) = session_data.read().unwrap().as_ref() { + for token in stuck_tokens { + let _ = session + .senders + .send_to_screen(ScreenInstruction::ForwardedReplyFromHost { + token, + reply_bytes: Vec::new(), + }); + } + } +} + macro_rules! remove_client { - ($client_id:expr, $os_input:expr, $session_state:expr) => { - $os_input.remove_client($client_id).unwrap(); - $session_state.write().unwrap().remove_client($client_id); + ($client_id:expr, $os_input:expr, $session_state:expr, $session_data:expr) => { + $crate::remove_client_and_flush_forwards( + $client_id, + &mut $os_input, + &$session_state, + &$session_data, + ); }; } @@ -479,7 +542,7 @@ macro_rules! remove_watcher { } macro_rules! send_to_client { - ($client_id:expr, $os_input:expr, $msg:expr, $session_state:expr) => { + ($client_id:expr, $os_input:expr, $msg:expr, $session_state:expr, $session_data:expr) => { let send_to_client_res = $os_input.send_to_client($client_id, $msg); if let Err(e) = send_to_client_res { // Try to recover the message @@ -497,7 +560,7 @@ macro_rules! send_to_client { // Log it so it isn't lost Err::<(), _>(e).context(context).non_fatal(); // failed to send to client, remove it - remove_client!($client_id, $os_input, $session_state); + remove_client!($client_id, $os_input, $session_state, $session_data); } }; } @@ -508,6 +571,13 @@ pub(crate) struct SessionState { pipes: HashMap<String, ClientId>, // String => pipe_id watchers: HashMap<ClientId, bool>, // watcher clients (read-only observers) bool -> is_web_client last_active_client: Option<ClientId>, // last client that sent a Key message + /// Host-query forward tokens that have been dispatched to a + /// specific client and are waiting for a reply. Used to clean up + /// when that client disconnects (or when there's no client to + /// dispatch to in the first place) — each stuck token gets an + /// empty synthetic reply so `Screen`'s `forward_in_flight` slot + /// releases and the queued forwards keep moving. + forwards_in_flight: HashMap<u32, ClientId>, } impl SessionState { @@ -517,6 +587,7 @@ impl SessionState { pipes: HashMap::new(), watchers: HashMap::new(), last_active_client: None, + forwards_in_flight: HashMap::new(), } } pub fn new_client(&mut self) -> ClientId { @@ -541,10 +612,25 @@ impl SessionState { pub fn associate_pipe_with_client(&mut self, pipe_id: String, client_id: ClientId) { self.pipes.insert(pipe_id, client_id); } - pub fn remove_client(&mut self, client_id: ClientId) { + /// Remove a client and return any host-query tokens that had + /// been dispatched to this client and were still awaiting a + /// reply. Callers must synthesize an empty reply for each token + /// (via `ScreenInstruction::ForwardedReplyFromHost`) so + /// `Screen`'s in-flight slot releases and any queued forwards + /// can proceed. + pub fn remove_client(&mut self, client_id: ClientId) -> Vec<u32> { self.clients.remove(&client_id); self.pipes.retain(|_p_id, c_id| c_id != &client_id); self.clear_last_active_client(client_id); + let stuck: Vec<u32> = self + .forwards_in_flight + .iter() + .filter_map(|(token, owner)| (*owner == client_id).then_some(*token)) + .collect(); + for token in &stuck { + self.forwards_in_flight.remove(token); + } + stuck } pub fn set_client_size(&mut self, client_id: ClientId, size: Size) { self.clients @@ -648,6 +734,96 @@ impl SessionState { self.last_active_client = None; } } + pub fn mark_forward_in_flight(&mut self, token: u32, client_id: ClientId) { + self.forwards_in_flight.insert(token, client_id); + } + pub fn clear_forward_in_flight(&mut self, token: u32) { + self.forwards_in_flight.remove(&token); + } + /// Client to route a host-query forward to. Prefers whichever + /// client most recently interacted with the session; falls back + /// to any currently-connected non-watcher client. Returns `None` + /// only when no regular client is connected. + pub fn pick_forward_target(&self) -> Option<ClientId> { + if let Some(candidate) = self.last_active_client { + if self.clients.contains_key(&candidate) { + return Some(candidate); + } + } + self.clients.keys().copied().next() + } +} + +#[cfg(test)] +mod session_state_tests { + use super::*; + + fn with_client(id: ClientId) -> SessionState { + let mut s = SessionState::new(); + s.clients.insert(id, None); + s + } + + #[test] + fn pick_forward_target_prefers_last_active_when_still_connected() { + let mut s = SessionState::new(); + s.clients.insert(1, None); + s.clients.insert(2, None); + s.set_last_active_client(2); + assert_eq!(s.pick_forward_target(), Some(2)); + } + + #[test] + fn pick_forward_target_falls_back_when_last_active_disconnected() { + let mut s = SessionState::new(); + s.clients.insert(1, None); + s.clients.insert(2, None); + // Client 3 was last active but has since disconnected — not in + // `clients` map anymore. Must fall through to any connected + // client rather than returning None. + s.last_active_client = Some(3); + let picked = s + .pick_forward_target() + .expect("some client still connected"); + assert!(picked == 1 || picked == 2); + } + + #[test] + fn pick_forward_target_none_when_no_clients() { + let s = SessionState::new(); + assert_eq!(s.pick_forward_target(), None); + } + + #[test] + fn remove_client_returns_stuck_forward_tokens() { + let mut s = with_client(1); + s.mark_forward_in_flight(10, 1); + s.mark_forward_in_flight(11, 1); + // A forward dispatched to a *different* client — must not be + // returned when we remove client 1. + s.clients.insert(2, None); + s.mark_forward_in_flight(12, 2); + + let mut stuck = s.remove_client(1); + stuck.sort_unstable(); + assert_eq!(stuck, vec![10, 11]); + assert_eq!(s.forwards_in_flight.get(&12), Some(&2)); + } + + #[test] + fn remove_client_returns_empty_when_no_forwards_in_flight() { + let mut s = with_client(1); + assert!(s.remove_client(1).is_empty()); + } + + #[test] + fn clear_forward_in_flight_removes_entry() { + let mut s = with_client(1); + s.mark_forward_in_flight(42, 1); + s.clear_forward_in_flight(42); + // After clear, removing the client yields no stuck tokens. + assert!(s.remove_client(1).is_empty()); + } } pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { @@ -1048,7 +1224,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { client_id, os_input, ServerToClientMsg::UnblockInputThread, - session_state + session_state, + session_data ); } }, @@ -1062,7 +1239,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { ServerToClientMsg::UnblockCliPipeInput { pipe_name: pipe_name.clone() }, - session_state + session_state, + session_data ); }, None => { @@ -1075,7 +1253,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { ServerToClientMsg::UnblockCliPipeInput { pipe_name: pipe_name.clone() }, - session_state + session_state, + session_data ); } }, @@ -1092,7 +1271,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { pipe_name: pipe_name.clone(), output: output.clone() }, - session_state + session_state, + session_data ); }, None => { @@ -1106,7 +1286,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { pipe_name: pipe_name.clone(), output: output.clone() }, - session_state + session_state, + session_data ); } }, @@ -1136,7 +1317,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { os_input.remove_client(client_id).unwrap(); } else { // Handle regular client removal - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); drop(completion_tx); // prevent deadlock with route thread if let Some(min_size) = session_state.read().unwrap().min_client_terminal_size() { @@ -1176,7 +1357,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { .collect(); // these are just the pipes for client_id in client_ids_to_cleanup { - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); } let watcher_client_ids: Vec<ClientId> = @@ -1211,7 +1392,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { os_input.remove_client(client_id).unwrap(); } else { // Handle regular client removal - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); if let Some(min_size) = session_state.read().unwrap().min_client_terminal_size() { session_data @@ -1248,7 +1429,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { exit_reason: ExitReason::WebClientsForbidden, }, ); - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); if let Some(min_size) = session_state.read().unwrap().min_client_terminal_size() { session_data .write() @@ -1269,7 +1450,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { exit_reason: ExitReason::Normal, }, ); - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); } break; }, @@ -1289,7 +1470,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { exit_reason: ExitReason::KickedByHost, }, ); - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); } }, ServerInstruction::DetachSession(client_ids, completion_tx) => { @@ -1300,7 +1481,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { exit_reason: ExitReason::Normal, }, ); - remove_client!(*client_id, os_input, session_state); + remove_client!(*client_id, os_input, session_state, session_data); } drop(completion_tx); // we do this here explicitly to signal that the clients have // already disconnected and to prevent a deadlock below caused @@ -1348,7 +1529,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { ServerToClientMsg::Render { content: client_render_instruction.clone() }, - session_state + session_state, + session_data ); } } else { @@ -1360,7 +1542,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { exit_reason: ExitReason::Normal, }, ); - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); } // Also disconnect all watchers @@ -1378,7 +1560,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { exit_reason: ExitReason::Normal, }, ); - remove_client!(watcher_id, os_input, session_state); + remove_client!(watcher_id, os_input, session_state, session_data); } break; } @@ -1392,13 +1574,13 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { exit_reason: ExitReason::Error(backtrace.clone()), }, ); - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); } break; }, ServerInstruction::ConnStatus(client_id) => { let _ = os_input.send_to_client(client_id, ServerToClientMsg::Connected); - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); }, ServerInstruction::Log( lines_to_log, @@ -1412,7 +1594,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { ServerToClientMsg::Log { lines: lines_to_log }, - session_state + session_state, + session_data ); }, ServerInstruction::LogError( @@ -1427,7 +1610,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { ServerToClientMsg::LogError { lines: lines_to_log }, - session_state + session_state, + session_data ); }, ServerInstruction::SwitchSession(mut connect_to_session, client_id, completion_tx) => { @@ -1453,9 +1637,10 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { client_id, os_input, ServerToClientMsg::SwitchSession { connect_to_session }, - session_state + session_state, + session_data ); - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); drop(completion_tx); // do not deadlock with route thread if let Some(min_size) = session_state.read().unwrap().min_client_terminal_size() @@ -1551,7 +1736,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { client_id, os_input, ServerToClientMsg::ConfigFileUpdated, - session_state + session_state, + session_data ); } }, @@ -1593,7 +1779,8 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { client_id, os_input, ServerToClientMsg::StartWebServer, - session_state + session_state, + session_data ); } else { // TODO: test this @@ -1644,7 +1831,7 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { exit_reason: ExitReason::WebClientsForbidden, }, ); - remove_client!(client_id, os_input, session_state); + remove_client!(client_id, os_input, session_state, session_data); } let web_watcher_client_ids: Vec<ClientId> = session_state .read() @@ -1707,6 +1894,51 @@ pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) { .send_to_screen(ScreenInstruction::ClearMouseHelpText(client_id)) .unwrap(); }, + ServerInstruction::ForwardQueryToHost(token, query_bytes) => { + // Pick a regular (non-watcher) client to carry the + // forward. Preference is the most recently active + // client (whichever last sent input); falls back to + // any connected client. When the host terminals of + // attached clients differ, the recently-active one + // is the best proxy for "what the user is currently + // looking at". + let target_client_id = { + let mut session = session_state.write().unwrap(); + let picked = session.pick_forward_target(); + if let Some(cid) = picked { + session.mark_forward_in_flight(token, cid); + } + picked + }; + if let Some(client_id) = target_client_id { + send_to_client!( + client_id, + os_input, + ServerToClientMsg::ForwardQueryToHost { token, query_bytes }, + session_state, + session_data + ); + } else { + // No client to ask — synthesize an empty reply + // so `Screen`'s in-flight slot releases. Without + // this, a detached session (apps still running) + // accumulates forwards in `forward_queue` with + // no way for them to drain until someone + // reattaches. + log::warn!( + "No connected client to forward host query (token={}); returning empty reply", + token + ); + if let Some(session) = session_data.read().unwrap().as_ref() { + let _ = session.senders.send_to_screen( + ScreenInstruction::ForwardedReplyFromHost { + token, + reply_bytes: Vec::new(), + }, + ); + } + } + }, } } diff --git a/zellij-server/src/panes/grid.rs b/zellij-server/src/panes/grid.rs index c3e5a588..ee468e7b 100644 --- a/zellij-server/src/panes/grid.rs +++ b/zellij-server/src/panes/grid.rs @@ -5,7 +5,9 @@ use std::collections::BTreeMap; use std::collections::HashMap; use std::rc::Rc; use unicode_width::UnicodeWidthChar; -use zellij_utils::data::{HighlightLayer, HighlightStyle, RegexHighlight, Style}; +use zellij_utils::data::{ + HighlightLayer, HighlightStyle, HostTerminalThemeMode, RegexHighlight, Style, +}; use zellij_utils::errors::prelude::*; use std::{ @@ -601,7 +603,9 @@ pub struct Grid { scroll_region: (usize, usize), active_charset: CharsetIndex, preceding_char: Option<TerminalCharacter>, + #[allow(dead_code)] terminal_emulator_colors: Rc<RefCell<Palette>>, + #[allow(dead_code)] terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>, pub(crate) output_buffer: OutputBuffer, title_stack: Vec<String>, @@ -630,12 +634,24 @@ pub struct Grid { pub mouse_mode: MouseMode, pub mouse_tracking: MouseTracking, pub focus_event_tracking: bool, + /// Has the app in this pane subscribed to host color-palette theme + /// notifications via `CSI ? 2031 h`? When true, host-emitted DSR 997 + /// notifications (received by the client and forwarded as + /// `ScreenInstruction::HostTerminalThemeChanged`) are pushed onto + /// `pending_messages_to_pty` for this pane. + pub color_palette_notification_enabled: bool, pub search_results: SearchResult, pub pending_clipboard_update: Option<String>, pub pending_osc7_cwd: Option<std::path::PathBuf>, /// Pending desktop notifications: (payload, terminator) /// Payload is the semicolon-joined params after "99", terminator is "\x07" or "\x1b\\" pub pending_desktop_notifications: Vec<(String, String)>, + /// Whitelisted host-terminal queries intercepted from the app running + /// in this pane (CSI 14t / 16t pixel-dim queries, OSC 10;? / 11;? / + /// 4;N;? color queries). Each entry is the raw byte sequence that + /// Zellij should forward to the host terminal; the host's reply is + /// later routed back to this pane's pty. + pub pending_forwarded_queries: Vec<crate::host_query::HostQuery>, ui_component_bytes: Option<Vec<u8>>, style: Style, debug: bool, @@ -647,8 +663,15 @@ pub struct Grid { // disabled by user config? click: Click, hyperlink_tracker: HyperlinkTracker, - pub pane_default_fg: Option<AnsiCode>, - pub pane_default_bg: Option<AnsiCode>, + /// Pane-scoped override for the default foreground colour. Narrow + /// to literal RGB by construction — the setters below refuse + /// palette-indexed / named variants silently, so this field can be + /// converted to an `OSC 10` reply without fallibility and the + /// render path can wrap it unconditionally. + pub pane_default_fg: Option<(u8, u8, u8)>, + /// Pane-scoped override for the default background colour. Same + /// invariant as `pane_default_fg`. + pub pane_default_bg: Option<(u8, u8, u8)>, pub plugin_highlights: HashMap<u32, Vec<(String, CompiledHighlight)>>, // key: plugin_id (u32), inner vec: (pattern, compiled) pairs pub hover_position: Option<Position>, // pane-relative cursor cell; None when outside pane @@ -657,27 +680,51 @@ pub struct Grid { impl Grid { pub fn set_pane_default_colors(&mut self, fg: Option<String>, bg: Option<String>) { - self.pane_default_fg = fg.as_ref().and_then(|s| xparse_color(s.as_bytes())); - self.pane_default_bg = bg.as_ref().and_then(|s| xparse_color(s.as_bytes())); + // Parse inputs; anything that isn't literal RGB (palette + // index / named colour / parse failure) is silently dropped so + // the invariant on `pane_default_{fg,bg}` is preserved. + self.pane_default_fg = fg + .as_ref() + .and_then(|s| xparse_color(s.as_bytes())) + .and_then(rgb_of_ansi_code); + self.pane_default_bg = bg + .as_ref() + .and_then(|s| xparse_color(s.as_bytes())) + .and_then(rgb_of_ansi_code); self.output_buffer.update_all_lines(); } pub fn get_pane_default_color_strings(&self) -> (Option<String>, Option<String>) { ( - self.pane_default_fg.and_then(ansi_code_to_color_string), - self.pane_default_bg.and_then(ansi_code_to_color_string), + self.pane_default_fg.map(rgb_to_hex_string), + self.pane_default_bg.map(rgb_to_hex_string), ) } } -fn ansi_code_to_color_string(code: AnsiCode) -> Option<String> { +/// Extract the RGB triple from an `AnsiCode`, or `None` for any +/// other variant. Used at the ingress points that populate +/// `Grid::pane_default_{fg,bg}` to keep those fields narrow to +/// literal RGB. +fn rgb_of_ansi_code(code: AnsiCode) -> Option<(u8, u8, u8)> { match code { - AnsiCode::RgbCode((r, g, b)) => Some(format!("#{:02x}{:02x}{:02x}", r, g, b)), - AnsiCode::ColorIndex(idx) => Some(format!("{}", idx)), - AnsiCode::NamedColor(named) => Some(format!("{:?}", named).to_lowercase()), + AnsiCode::RgbCode(rgb) => Some(rgb), _ => None, } } +fn rgb_to_hex_string((r, g, b): (u8, u8, u8)) -> String { + format!("#{:02x}{:02x}{:02x}", r, g, b) +} + +/// Format an RGB triple as the body of an OSC 10/11 reply — +/// `rgb:RRRR/GGGG/BBBB` per xterm's ctlseqs, where each 8-bit +/// component is widened to the 16-bit hex form by repetition +/// (`0xAB` → `0xABAB`). +fn osc_color_reply_body((r, g, b): (u8, u8, u8)) -> String { + let expand = |c: u8| (c as u16) * 0x0101; + format!("rgb:{:04x}/{:04x}/{:04x}", expand(r), expand(g), expand(b)) +} + /// A compiled highlight entry for one plugin/pattern combination. #[derive(Clone)] pub struct CompiledHighlight { @@ -916,12 +963,14 @@ impl Grid { mouse_mode: MouseMode::default(), mouse_tracking: MouseTracking::default(), focus_event_tracking: false, + color_palette_notification_enabled: false, character_cell_size, search_results: Default::default(), sixel_grid, pending_clipboard_update: None, pending_osc7_cwd: None, pending_desktop_notifications: Vec::new(), + pending_forwarded_queries: Vec::new(), ui_component_bytes: None, style, debug, @@ -1521,7 +1570,15 @@ impl Grid { for character_chunk in character_chunks.iter_mut() { character_chunk.add_changed_colors(self.changed_colors); - character_chunk.add_pane_defaults(self.pane_default_fg, self.pane_default_bg); + // CharacterChunk still carries `Option<AnsiCode>` because + // `adjust_styles_for_custom_bg_fg` assigns the value into + // `CharacterStyles.{foreground,background}` (themselves + // `Option<AnsiCode>`). Re-wrap the narrow RGB at the + // boundary so the downstream pipeline stays uniform. + character_chunk.add_pane_defaults( + self.pane_default_fg.map(AnsiCode::RgbCode), + self.pane_default_bg.map(AnsiCode::RgbCode), + ); if self .selection .contains_row(character_chunk.y.saturating_sub(content_y)) @@ -3229,6 +3286,20 @@ impl Grid { pub fn reset_cursor_position(&mut self) { self.cursor = Cursor::new(0, 0, self.styled_underlines); } + /// Queue a CSI ?997;{1|2}n DSR notification of host color-palette + /// theme mode onto this grid's pty-write queue. No-op when the app + /// has not opted in via `CSI ? 2031 h`. + pub fn push_color_palette_dsr(&mut self, mode: HostTerminalThemeMode) { + if !self.color_palette_notification_enabled { + return; + } + let code = match mode { + HostTerminalThemeMode::Dark => 1, + HostTerminalThemeMode::Light => 2, + }; + self.pending_messages_to_pty + .push(format!("\u{1b}[?997;{}n", code).into_bytes()); + } pub fn lock_renders(&mut self) { self.lock_renders = true; } @@ -3489,15 +3560,20 @@ impl Perform for Grid { return; } else if chunk.get(1).as_ref().and_then(|c| c.get(0)) == Some(&b'?') { if let Some(index) = index { - let terminal_emulator_color_codes = - self.terminal_emulator_color_codes.borrow(); - let color = terminal_emulator_color_codes.get(&(index as usize)); - if let Some(color) = color { - let color_response_message = - format!("\u{1b}]4;{};{}{}", index, color, terminator); - self.pending_messages_to_pty - .push(color_response_message.as_bytes().to_vec()); - } + // Forward palette-register queries to the + // host — apps want the actual host palette, + // not Zellij's cached copy. (Zellij's cache + // still auto-refreshes via double-dispatch + // when the host's reply comes back.) + self.pending_forwarded_queries.push( + crate::host_query::HostQuery::PaletteRegister { + index, + terminator: + crate::host_query::OscTerminator::from_bell_terminated( + bell_terminated, + ), + }, + ); } } } @@ -3519,40 +3595,69 @@ impl Perform for Grid { if let Some(mut dynamic_code) = parse_number(params[0]) { for param in ¶ms[1..] { if param == b"?" { - // Query: respond with pane default if set, else terminal default - let color_rgb = if dynamic_code == 10 { - match self.pane_default_fg { - Some(AnsiCode::RgbCode((r, g, b))) => Some((r, g, b)), - _ => match self.terminal_emulator_colors.borrow().fg { - PaletteColor::Rgb((r, g, b)) => Some((r, g, b)), - _ => None, + // If this pane has a local override for + // the channel being queried (set via + // `zellij action set-pane-color` or via + // a prior OSC 10;<rgb> / 11;<rgb> from + // inside the pane), answer with that + // override directly instead of + // forwarding to the host. Apps inside + // the pane must see the colors Zellij + // is actually rendering for them, not + // the host terminal's background. + let local_override = match dynamic_code { + 10 => self.pane_default_fg, + 11 => self.pane_default_bg, + _ => None, + }; + if let Some(rgb) = local_override { + let reply = format!( + "\u{1b}]{};{}{}", + dynamic_code, + osc_color_reply_body(rgb), + terminator + ); + self.pending_messages_to_pty.push(reply.as_bytes().to_vec()); + } else { + // No local override — forward to + // the host so the app observes the + // terminal's actual color. Zellij's + // cached copy is refreshed via the + // double-dispatch on the reply. + let term = + crate::host_query::OscTerminator::from_bell_terminated( + bell_terminated, + ); + let query = match dynamic_code { + 10 => crate::host_query::HostQuery::DefaultForeground { + terminator: term, }, - } - } else if dynamic_code == 11 { - match self.pane_default_bg { - Some(AnsiCode::RgbCode((r, g, b))) => Some((r, g, b)), - _ => match self.terminal_emulator_colors.borrow().bg { - PaletteColor::Rgb((r, g, b)) => Some((r, g, b)), - _ => None, + 11 => crate::host_query::HostQuery::DefaultBackground { + terminator: term, }, - } - } else { - None - }; - let (r, g, b) = color_rgb.unwrap_or((0, 0, 0)); - let color_response_message = format!( - "\u{1b}]{};rgb:{1:02x}{1:02x}/{2:02x}{2:02x}/{3:02x}{3:02x}{4}", - dynamic_code, r, g, b, terminator - ); - self.pending_messages_to_pty - .push(color_response_message.as_bytes().to_vec()); + _ => { + // Out-of-range dynamic_code + // (shouldn't happen since + // the outer match pins it to + // 10 or 11): skip. + dynamic_code += 1; + continue; + }, + }; + self.pending_forwarded_queries.push(query); + } } else { - // Set: parse color and store as pane default - if let Some(color) = xparse_color(param) { + // Set: parse color and store as pane + // default. Only literal RGB is stored; + // palette-indexed / named variants (or + // a parse failure) are silently dropped + // to keep the pane-default fields + // narrow. + if let Some(rgb) = xparse_color(param).and_then(rgb_of_ansi_code) { if dynamic_code == 10 { - self.pane_default_fg = Some(color); + self.pane_default_fg = Some(rgb); } else if dynamic_code == 11 { - self.pane_default_bg = Some(color); + self.pane_default_bg = Some(rgb); } self.output_buffer.update_all_lines(); } @@ -3838,6 +3943,9 @@ impl Perform for Grid { 1006 => { self.mouse_mode = MouseMode::NoEncoding; }, + 2031 => { + self.color_palette_notification_enabled = false; + }, _ => {}, }; } @@ -3943,6 +4051,9 @@ impl Perform for Grid { 1006 => { self.mouse_mode = MouseMode::Sgr; }, + 2031 => { + self.color_palette_notification_enabled = true; + }, _ => {}, } } @@ -4200,27 +4311,51 @@ impl Perform for Grid { } else if c == 'n' { // DSR - device status report // https://vt100.net/docs/vt510-rm/DSR.html - match next_param_or(0) { - 5 => { - // report terminal status - let all_good = "\u{1b}[0n"; - self.pending_messages_to_pty - .push(all_good.as_bytes().to_vec()); - }, - 6 => { - // CPR - cursor position report + let first_intermediate_is_questionmark = match intermediates.get(0) { + Some(b'?') => true, + None => false, + _ => false, + }; + if first_intermediate_is_questionmark { + // CSI ? 996 n — query host terminal color-palette mode + // (Contour spec; see contour-terminal.org). Zellij + // short-circuits this query: we know the host's mode + // from our own startup `\e[?996n` plus unsolicited DSR + // 997 updates while `\e[?2031h` is enabled, so the + // pane gets answered locally without a host round-trip. + // Pushing onto `pending_forwarded_queries` enrols the + // query in the existing Grid → Tab → Screen pipeline; + // Screen recognises the variant and writes the reply + // straight to the pane's pty. + for param in params_iter.map(|param| param[0]) { + if param == 996 { + self.pending_forwarded_queries + .push(crate::host_query::HostQuery::ColorPaletteMode); + } + } + } else { + match next_param_or(0) { + 5 => { + // report terminal status + let all_good = "\u{1b}[0n"; + self.pending_messages_to_pty + .push(all_good.as_bytes().to_vec()); + }, + 6 => { + // CPR - cursor position report - // Note that this is relative to scrolling region. - let offset = self.scroll_region.0; // scroll_region_top - let position_report = format!( - "\u{1b}[{};{}R", - self.cursor.y + 1 - offset, - self.cursor.x + 1 - ); - self.pending_messages_to_pty - .push(position_report.as_bytes().to_vec()); - }, - _ => {}, + // Note that this is relative to scrolling region. + let offset = self.scroll_region.0; // scroll_region_top + let position_report = format!( + "\u{1b}[{};{}R", + self.cursor.y + 1 - offset, + self.cursor.x + 1 + ); + self.pending_messages_to_pty + .push(position_report.as_bytes().to_vec()); + }, + _ => {}, + } } } else if c == 'x' { // DECREQTPARM - Request Terminal Parameters @@ -4244,25 +4379,18 @@ impl Perform for Grid { } else if c == 't' { match next_param_or(1) as usize { 14 => { - if let Some(character_cell_size) = *self.character_cell_size.borrow() { - let text_area_pixel_size_report = format!( - "\x1b[4;{};{}t", - character_cell_size.height * self.height, - character_cell_size.width * self.width - ); - self.pending_messages_to_pty - .push(text_area_pixel_size_report.as_bytes().to_vec()); - } + // Forward to host: apps asking for text-area pixels + // want the real window size, not Zellij's synthesised + // (cell_size * grid_size) value. The host's reply will + // be written back to this pane by the forwarding + // infrastructure on Screen. + self.pending_forwarded_queries + .push(crate::host_query::HostQuery::TextAreaPixelSize); }, 16 => { - if let Some(character_cell_size) = *self.character_cell_size.borrow() { - let character_cell_size_report = format!( - "\x1b[6;{};{}t", - character_cell_size.height, character_cell_size.width - ); - self.pending_messages_to_pty - .push(character_cell_size_report.as_bytes().to_vec()); - } + // Forward to host: character-cell pixel size. + self.pending_forwarded_queries + .push(crate::host_query::HostQuery::CharacterCellPixelSize); }, 18 => { // report text area diff --git a/zellij-server/src/panes/terminal_pane.rs b/zellij-server/src/panes/terminal_pane.rs index 5aeef4f2..eeec67d9 100644 --- a/zellij-server/src/panes/terminal_pane.rs +++ b/zellij-server/src/panes/terminal_pane.rs @@ -586,6 +586,14 @@ impl Pane for TerminalPane { self.grid.pending_messages_to_pty.drain(..).collect() } + fn drain_forwarded_queries(&mut self) -> Vec<crate::host_query::HostQuery> { + self.grid.pending_forwarded_queries.drain(..).collect() + } + + fn push_color_palette_dsr(&mut self, mode: zellij_utils::data::HostTerminalThemeMode) { + self.grid.push_color_palette_dsr(mode); + } + fn drain_clipboard_update(&mut self) -> Option<String> { self.grid.pending_clipboard_update.take() } diff --git a/zellij-server/src/panes/unit/grid_tests.rs b/zellij-server/src/panes/unit/grid_tests.rs index ed3bc3ac..8e8618b6 100644 --- a/zellij-server/src/panes/unit/grid_tests.rs +++ b/zellij-server/src/panes/unit/grid_tests.rs @@ -3260,12 +3260,16 @@ fn terminal_pixel_size_reports() { for byte in content { vte_parser.advance(&mut grid, byte); } + // CSI 14t and CSI 16t are forwarded to the host; Zellij no longer + // synthesises local replies from character_cell_size for these. + assert!(grid.pending_messages_to_pty.is_empty()); + use crate::host_query::HostQuery; assert_eq!( - grid.pending_messages_to_pty - .iter() - .map(|bytes| String::from_utf8(bytes.clone()).unwrap()) - .collect::<Vec<String>>(), - vec!["\x1b[4;1071;776t", "\x1b[6;21;8t"] + grid.pending_forwarded_queries, + vec![ + HostQuery::TextAreaPixelSize, + HostQuery::CharacterCellPixelSize + ], ); } @@ -3299,13 +3303,17 @@ fn terminal_pixel_size_reports_in_unsupported_terminals() { for byte in content { vte_parser.advance(&mut grid, byte); } - let expected: Vec<String> = vec![]; + // Forwarding is independent of character_cell_size availability — + // the host terminal is authoritative for these queries regardless + // of what Zellij knows locally. + assert!(grid.pending_messages_to_pty.is_empty()); + use crate::host_query::HostQuery; assert_eq!( - grid.pending_messages_to_pty - .iter() - .map(|bytes| String::from_utf8(bytes.clone()).unwrap()) - .collect::<Vec<String>>(), - expected, + grid.pending_forwarded_queries, + vec![ + HostQuery::TextAreaPixelSize, + HostQuery::CharacterCellPixelSize + ], ); } @@ -3586,15 +3594,16 @@ pub fn osc_4_background_query() { for byte in content.as_bytes() { vte_parser.advance(&mut grid, *byte); } - let message_string = grid - .pending_messages_to_pty + // Post-refactor: OSC 10;? is forwarded to the host, not answered + // from Zellij's cached palette. pending_messages_to_pty must stay + // empty. + assert!(grid.pending_messages_to_pty.is_empty()); + let forwarded_string: String = grid + .pending_forwarded_queries .iter() - .map(|m| String::from_utf8_lossy(m)) - .fold(String::new(), |mut acc, s| { - acc.push_str(&s); - acc - }); - assert_eq!(message_string, "\u{1b}]10;rgb:0000/0000/0000\u{1b}\\"); + .map(|q| String::from_utf8(q.to_query_bytes()).unwrap()) + .collect(); + assert_eq!(forwarded_string, "\u{1b}]10;?\u{1b}\\"); } #[test] @@ -3626,15 +3635,13 @@ pub fn osc_4_foreground_query() { for byte in content.as_bytes() { vte_parser.advance(&mut grid, *byte); } - let message_string = grid - .pending_messages_to_pty + assert!(grid.pending_messages_to_pty.is_empty()); + let forwarded_string: String = grid + .pending_forwarded_queries .iter() - .map(|m| String::from_utf8_lossy(m)) - .fold(String::new(), |mut acc, s| { - acc.push_str(&s); - acc - }); - assert_eq!(message_string, "\u{1b}]11;rgb:0000/0000/0000\u{1b}\\"); + .map(|q| String::from_utf8(q.to_query_bytes()).unwrap()) + .collect(); + assert_eq!(forwarded_string, "\u{1b}]11;?\u{1b}\\"); } #[test] @@ -3668,15 +3675,14 @@ pub fn osc_4_color_query() { for byte in content.as_bytes() { vte_parser.advance(&mut grid, *byte); } - let message_string = grid - .pending_messages_to_pty + // OSC 4;N;? is forwarded to the host for the real palette value. + assert!(grid.pending_messages_to_pty.is_empty()); + let forwarded_string: String = grid + .pending_forwarded_queries .iter() - .map(|m| String::from_utf8_lossy(m)) - .fold(String::new(), |mut acc, s| { - acc.push_str(&s); - acc - }); - assert_eq!(message_string, "\u{1b}]4;222;rgb:ffff/d7d7/8787\u{1b}\\"); + .map(|q| String::from_utf8(q.to_query_bytes()).unwrap()) + .collect(); + assert_eq!(forwarded_string, "\u{1b}]4;222;?\u{1b}\\"); } #[test] @@ -4397,21 +4403,26 @@ fn osc_11_set_and_query_pane_default_bg() { vte_parser.advance(&mut grid, *byte); } - assert_eq!(grid.pane_default_bg, Some(AnsiCode::RgbCode((0, 26, 58)))); + assert_eq!(grid.pane_default_bg, Some((0, 26, 58))); - // Query background via OSC 11 + // Query background via OSC 11 — because a pane-scoped override is + // in place, the query is short-circuited: apps inside the pane + // must see what Zellij is actually rendering, not the host + // terminal's bg. The reply uses xterm's canonical + // `rgb:RRRR/GGGG/BBBB` form with each 8-bit channel widened by + // repetition (0x00 → 0x0000, 0x1a → 0x1a1a, 0x3a → 0x3a3a). let query_bg = b"\x1b]11;?\x07"; for byte in query_bg.iter() { vte_parser.advance(&mut grid, *byte); } - assert_eq!(grid.pending_messages_to_pty.len(), 1); - let response = String::from_utf8(grid.pending_messages_to_pty[0].clone()).unwrap(); assert!( - response.contains("11;rgb:0000/1a1a/3a3a"), - "Response was: {}", - response + grid.pending_forwarded_queries.is_empty(), + "OSC 11 query must not be forwarded when a pane override is set" ); + assert_eq!(grid.pending_messages_to_pty.len(), 1); + let reply = String::from_utf8(grid.pending_messages_to_pty[0].clone()).unwrap(); + assert_eq!(reply, "\u{1b}]11;rgb:0000/1a1a/3a3a\u{7}",); } #[test] @@ -4443,21 +4454,23 @@ fn osc_10_set_and_query_pane_default_fg() { vte_parser.advance(&mut grid, *byte); } - assert_eq!(grid.pane_default_fg, Some(AnsiCode::RgbCode((0, 224, 0)))); + assert_eq!(grid.pane_default_fg, Some((0, 224, 0))); - // Query foreground via OSC 10 + // Query foreground via OSC 10 — pane-scoped override is in place, + // so the query is answered locally (see OSC 11 equivalent test for + // the short-circuit rationale). let query_fg = b"\x1b]10;?\x07"; for byte in query_fg.iter() { vte_parser.advance(&mut grid, *byte); } - assert_eq!(grid.pending_messages_to_pty.len(), 1); - let response = String::from_utf8(grid.pending_messages_to_pty[0].clone()).unwrap(); assert!( - response.contains("10;rgb:0000/e0e0/0000"), - "Response was: {}", - response + grid.pending_forwarded_queries.is_empty(), + "OSC 10 query must not be forwarded when a pane override is set" ); + assert_eq!(grid.pending_messages_to_pty.len(), 1); + let reply = String::from_utf8(grid.pending_messages_to_pty[0].clone()).unwrap(); + assert_eq!(reply, "\u{1b}]10;rgb:0000/e0e0/0000\u{7}",); } #[test] @@ -4493,8 +4506,8 @@ fn osc_110_111_reset_pane_default_colors() { vte_parser.advance(&mut grid, *byte); } - assert_eq!(grid.pane_default_fg, Some(AnsiCode::RgbCode((0, 224, 0)))); - assert_eq!(grid.pane_default_bg, Some(AnsiCode::RgbCode((0, 26, 58)))); + assert_eq!(grid.pane_default_fg, Some((0, 224, 0))); + assert_eq!(grid.pane_default_bg, Some((0, 26, 58))); // Reset foreground via OSC 110 let reset_fg = b"\x1b]110\x07"; @@ -4502,7 +4515,7 @@ fn osc_110_111_reset_pane_default_colors() { vte_parser.advance(&mut grid, *byte); } assert_eq!(grid.pane_default_fg, None); - assert_eq!(grid.pane_default_bg, Some(AnsiCode::RgbCode((0, 26, 58)))); + assert_eq!(grid.pane_default_bg, Some((0, 26, 58))); // Reset background via OSC 111 let reset_bg = b"\x1b]111\x07"; @@ -4542,7 +4555,7 @@ fn osc_11_set_bg_produces_ansi_in_render_output() { vte_parser.advance(&mut grid, *byte); } - assert_eq!(grid.pane_default_bg, Some(AnsiCode::RgbCode((0, 26, 58)))); + assert_eq!(grid.pane_default_bg, Some((0, 26, 58))); // Render the grid and check that the pane defaults are stamped on chunks let style = Style::default(); @@ -5690,3 +5703,361 @@ fn row_without_scroll_has_no_bg_color() { "rows not created by scroll should have no bg_color" ); } + +fn new_grid_for_forwarding_test() -> Grid { + Grid::new( + 10, + 20, + Rc::new(RefCell::new(Palette::default())), + Rc::new(RefCell::new(HashMap::new())), + Rc::new(RefCell::new(LinkHandler::new())), + Rc::new(RefCell::new(Some(SizeInPixels { + width: 8, + height: 16, + }))), + Rc::new(RefCell::new(SixelImageStore::default())), + Style::default(), + false, + true, + true, + true, + false, + ) +} + +#[test] +fn csi_14t_forwards_to_host_not_local() { + // CSI 14t used to synthesize a local "\x1b[4;H;Wt" reply; after the + // refactor it must be forwarded to the host instead so apps observe + // the terminal's real window pixel dimensions. + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + for byte in b"\x1b[14t" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.pending_messages_to_pty.is_empty(), + "local reply path must not fire for 14t" + ); + assert_eq!(grid.pending_forwarded_queries.len(), 1); + assert_eq!( + grid.pending_forwarded_queries[0], + crate::host_query::HostQuery::TextAreaPixelSize, + "forwarded classification must be TextAreaPixelSize" + ); +} + +#[test] +fn csi_16t_forwards_to_host_not_local() { + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + for byte in b"\x1b[16t" { + parser.advance(&mut grid, *byte); + } + assert!(grid.pending_messages_to_pty.is_empty()); + assert_eq!(grid.pending_forwarded_queries.len(), 1); + assert_eq!( + grid.pending_forwarded_queries[0], + crate::host_query::HostQuery::CharacterCellPixelSize, + ); +} + +#[test] +fn csi_18t_still_answered_locally() { + // 18 reports Zellij's own text-area size in cells — Zellij is + // authoritative for this, do NOT forward. + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + for byte in b"\x1b[18t" { + parser.advance(&mut grid, *byte); + } + assert_eq!(grid.pending_messages_to_pty.len(), 1); + assert!(grid.pending_forwarded_queries.is_empty()); +} + +#[test] +fn osc_11_set_stays_local() { + // OSC 11;<rgb> (set pane default bg) must stay local — Zellij needs + // to track it for its own rendering. + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + for byte in b"\x1b]11;rgb:ffff/ffff/ffff\x07" { + parser.advance(&mut grid, *byte); + } + assert!(grid.pending_messages_to_pty.is_empty()); + assert!( + grid.pending_forwarded_queries.is_empty(), + "set (not query) must not forward" + ); + assert!(grid.pane_default_bg.is_some()); +} + +#[test] +fn osc_11_query_without_override_forwards_to_host() { + // When no pane-local override is in place the query must still be + // forwarded — the host's actual bg is what the app asked for. + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + assert!(grid.pane_default_bg.is_none()); + for byte in b"\x1b]11;?\x07" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.pending_messages_to_pty.is_empty(), + "no override → no local reply" + ); + assert_eq!(grid.pending_forwarded_queries.len(), 1); + assert!(matches!( + grid.pending_forwarded_queries[0], + crate::host_query::HostQuery::DefaultBackground { .. } + )); +} + +#[test] +fn osc_10_query_without_override_forwards_to_host() { + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + assert!(grid.pane_default_fg.is_none()); + for byte in b"\x1b]10;?\x07" { + parser.advance(&mut grid, *byte); + } + assert!(grid.pending_messages_to_pty.is_empty()); + assert_eq!(grid.pending_forwarded_queries.len(), 1); + assert!(matches!( + grid.pending_forwarded_queries[0], + crate::host_query::HostQuery::DefaultForeground { .. } + )); +} + +#[test] +fn set_pane_default_colors_short_circuits_osc_queries() { + // The CLI path (`zellij action set-pane-color`) lands on + // `Grid::set_pane_default_colors`. A later OSC 10/11 query must + // read that override, not be forwarded — the entire point of the + // CLI override is that apps see the color Zellij is painting, not + // the underlying host's. + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + grid.set_pane_default_colors(Some("#ff8040".to_string()), Some("#102030".to_string())); + + for byte in b"\x1b]10;?\x07" { + parser.advance(&mut grid, *byte); + } + for byte in b"\x1b]11;?\x07" { + parser.advance(&mut grid, *byte); + } + + assert!( + grid.pending_forwarded_queries.is_empty(), + "overrides set via set_pane_default_colors must suppress forwarding" + ); + assert_eq!(grid.pending_messages_to_pty.len(), 2); + let fg_reply = String::from_utf8(grid.pending_messages_to_pty[0].clone()).unwrap(); + let bg_reply = String::from_utf8(grid.pending_messages_to_pty[1].clone()).unwrap(); + assert_eq!(fg_reply, "\u{1b}]10;rgb:ffff/8080/4040\u{7}"); + assert_eq!(bg_reply, "\u{1b}]11;rgb:1010/2020/3030\u{7}"); +} + +#[test] +fn osc_11_override_short_circuits_only_the_overridden_channel() { + // Setting only the bg must not short-circuit fg queries — each + // channel's override is independent. If only `pane_default_bg` is + // populated, an OSC 10 query (fg) still goes to the host. + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + for byte in b"\x1b]11;rgb:1010/2020/3030\x07" { + parser.advance(&mut grid, *byte); + } + assert!(grid.pane_default_bg.is_some()); + assert!(grid.pane_default_fg.is_none()); + + for byte in b"\x1b]10;?\x07" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.pending_messages_to_pty.is_empty(), + "fg has no override → must forward" + ); + assert_eq!(grid.pending_forwarded_queries.len(), 1); +} + +#[test] +fn csi_2026_dollar_p_stays_local() { + // DECRQM mode 2026 (synchronised output) is emulated by Zellij + // itself — never forwarded. The response is the DECRPM form + // `\x1b[?2026;2$y` (2 = "reset but recognised"; Zellij brackets its + // own frames, so individual panes are treated as "not enabled"). + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + for byte in b"\x1b[?2026$p" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.pending_forwarded_queries.is_empty(), + "CSI ?2026$p is emulated locally, must not forward" + ); + assert_eq!(grid.pending_messages_to_pty.len(), 1); + assert_eq!( + grid.pending_messages_to_pty[0], b"\x1b[?2026;2$y", + "DECRPM reply must use the `$y` suffix per spec" + ); +} + +#[test] +fn csi_22t_and_23t_stay_local() { + // CSI 22t / 23t manipulate the pane's title stack — Zellij owns + // that state, so forwarding would route an app's push/pop to the + // host's unrelated title stack instead of the visible pane title. + // They produce no reply; both queues must stay empty after each. + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + grid.set_title("hello".to_string()); + + for byte in b"\x1b[22;0t" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.pending_forwarded_queries.is_empty(), + "22t is a stack op, not a query" + ); + assert!( + grid.pending_messages_to_pty.is_empty(), + "22t produces no reply" + ); + + // The push actually landed on Zellij's per-pane stack: restore it. + grid.set_title("different".to_string()); + for byte in b"\x1b[23;0t" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.pending_forwarded_queries.is_empty(), + "23t is a stack op, not a query" + ); + assert!( + grid.pending_messages_to_pty.is_empty(), + "23t produces no reply" + ); + assert_eq!( + grid.title.as_deref(), + Some("hello"), + "pop should restore the previously-pushed title" + ); +} + +#[test] +fn osc_4_set_stays_local() { + // OSC 4;<index>;<rgb> writes to Zellij's in-memory palette; only + // the query form (`OSC 4;N;?`) ever forwards to the host. + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + for byte in b"\x1b]4;5;rgb:ffff/0000/0000\x07" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.pending_forwarded_queries.is_empty(), + "OSC 4 set must not forward" + ); + assert!( + grid.pending_messages_to_pty.is_empty(), + "OSC 4 set produces no reply" + ); + let changed = grid + .changed_colors + .expect("changed_colors should be populated by OSC 4 set"); + assert!(changed[5].is_some(), "index 5 should have been written"); +} + +#[test] +fn decset_2031_enables_color_palette_notification() { + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + assert!( + !grid.color_palette_notification_enabled, + "default state must be disabled" + ); + for byte in b"\x1b[?2031h" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.color_palette_notification_enabled, + "DECSET 2031 must enable the flag" + ); + for byte in b"\x1b[?2031l" { + parser.advance(&mut grid, *byte); + } + assert!( + !grid.color_palette_notification_enabled, + "DECRST 2031 must disable the flag" + ); +} + +#[test] +fn push_color_palette_dsr_emits_when_enabled() { + let mut grid = new_grid_for_forwarding_test(); + grid.color_palette_notification_enabled = true; + grid.push_color_palette_dsr(zellij_utils::data::HostTerminalThemeMode::Dark); + assert_eq!(grid.pending_messages_to_pty.len(), 1); + assert_eq!( + grid.pending_messages_to_pty[0], + b"\x1b[?997;1n".to_vec(), + "Dark mode emits ?997;1n" + ); + grid.push_color_palette_dsr(zellij_utils::data::HostTerminalThemeMode::Light); + assert_eq!(grid.pending_messages_to_pty.len(), 2); + assert_eq!( + grid.pending_messages_to_pty[1], + b"\x1b[?997;2n".to_vec(), + "Light mode emits ?997;2n" + ); +} + +#[test] +fn push_color_palette_dsr_noop_when_disabled() { + let mut grid = new_grid_for_forwarding_test(); + assert!(!grid.color_palette_notification_enabled); + grid.push_color_palette_dsr(zellij_utils::data::HostTerminalThemeMode::Dark); + assert!( + grid.pending_messages_to_pty.is_empty(), + "no DSR is queued when the app has not opted in via CSI ?2031h" + ); +} + +#[test] +fn csi_996n_pushes_color_palette_mode_query_to_forwarded_queries() { + use crate::host_query::HostQuery; + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + for byte in b"\x1b[?996n" { + parser.advance(&mut grid, *byte); + } + assert_eq!( + grid.pending_forwarded_queries, + vec![HostQuery::ColorPaletteMode], + "CSI ?996n must push HostQuery::ColorPaletteMode for Screen to short-circuit" + ); + assert!( + grid.pending_messages_to_pty.is_empty(), + "Grid must NOT answer locally — Screen owns the host_terminal_theme_mode cache" + ); +} + +#[test] +fn csi_5n_status_query_still_handled_locally() { + let mut parser = vte::Parser::new(); + let mut grid = new_grid_for_forwarding_test(); + // Plain DSR 5 (no `?` intermediate) is not the new theme query and + // must continue to receive its `\e[0n` "all good" reply locally. + for byte in b"\x1b[5n" { + parser.advance(&mut grid, *byte); + } + assert!( + grid.pending_forwarded_queries.is_empty(), + "DSR 5 is not a forwarded query" + ); + assert_eq!( + grid.pending_messages_to_pty, + vec![b"\x1b[0n".to_vec()], + "DSR 5 must still produce its local 'all good' reply" + ); +} diff --git a/zellij-server/src/route.rs b/zellij-server/src/route.rs index 155997f9..849e3405 100644 --- a/zellij-server/src/route.rs +++ b/zellij-server/src/route.rs @@ -1149,6 +1149,27 @@ pub(crate) fn route_action( .with_context(err_context)?; should_break = true; }, + Action::SetDarkTheme => { + senders + .send_to_screen(ScreenInstruction::SetDarkTheme(Some(NotificationEnd::new( + completion_tx, + )))) + .with_context(err_context)?; + }, + Action::SetLightTheme => { + senders + .send_to_screen(ScreenInstruction::SetLightTheme(Some( + NotificationEnd::new(completion_tx), + ))) + .with_context(err_context)?; + }, + Action::ToggleTheme => { + senders + .send_to_screen(ScreenInstruction::ToggleTheme(Some(NotificationEnd::new( + completion_tx, + )))) + .with_context(err_context)?; + }, Action::SwitchSession { name, tab_position, @@ -2598,6 +2619,37 @@ pub(crate) fn route_thread_main( retry_queue ); }, + ClientToServerMsg::ForwardedReplyFromHost { + token, + ref reply_bytes, + } => { + // The client that owns this forward + // answered — drop the in-flight entry + // first so a later disconnect of that + // client can't synthesize a spurious + // empty reply for the same token. + session_state + .write() + .unwrap() + .clear_forward_in_flight(token); + let _ = send_to_screen_or_retry_queue!( + senders, + ScreenInstruction::ForwardedReplyFromHost { + token, + reply_bytes: reply_bytes.clone(), + }, + instruction, + retry_queue + ); + }, + ClientToServerMsg::HostTerminalThemeChanged { mode } => { + let _ = send_to_screen_or_retry_queue!( + senders, + ScreenInstruction::HostTerminalThemeChanged(mode), + instruction, + retry_queue + ); + }, ClientToServerMsg::SubscribeToPaneRenders { ref pane_ids, ref scrollback, diff --git a/zellij-server/src/screen.rs b/zellij-server/src/screen.rs index f05b0823..f3d130ec 100644 --- a/zellij-server/src/screen.rs +++ b/zellij-server/src/screen.rs @@ -29,7 +29,7 @@ //! - `tab_history: BTreeMap<ClientId, Vec<usize>>`: History of tab IDs per client use std::cell::RefCell; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::net::{IpAddr, Ipv4Addr}; use std::path::PathBuf; use std::rc::Rc; @@ -41,10 +41,10 @@ use crate::route::NotificationEnd; use log::{debug, warn}; use zellij_utils::data::{ CommandOrPlugin, Direction, EventType, FloatingPaneCoordinates, GetFocusedPaneInfoResponse, - KeyWithModifier, LayoutInfo, LayoutWithError, ListPanesResponse, ListTabsResponse, - NewPanePlacement, PaneContents, PaneInfo, PaneListEntry, PaneManifest, PaneRenderReport, - PaneScrollbackResponse, PluginPermission, RegexHighlight, Resize, ResizeStrategy, SessionInfo, - Styling, TabInfo, WebSharing, + HostTerminalThemeMode, KeyWithModifier, LayoutInfo, LayoutWithError, ListPanesResponse, + ListTabsResponse, NewPanePlacement, PaneContents, PaneInfo, PaneListEntry, PaneManifest, + PaneRenderReport, PaneScrollbackResponse, PluginPermission, RegexHighlight, Resize, + ResizeStrategy, SessionInfo, Styling, TabInfo, WebSharing, }; use zellij_utils::errors::prelude::*; use zellij_utils::input::command::RunCommand; @@ -80,6 +80,7 @@ use crate::{ panes::PaneId, plugins::{DumpSessionLayoutResponse, PluginId, PluginInstruction, PluginRenderAsset}, pty::{get_default_shell, ClientTabIndexOrPaneId, PtyInstruction, VteBytes}, + pty_writer::PtyWriteInstruction, tab::{SuppressedPanes, Tab}, thread_bus::Bus, ui::loading_indication::LoadingIndication, @@ -500,6 +501,37 @@ pub enum ScreenInstruction { TerminalBackgroundColor(String), TerminalForegroundColor(String), TerminalColorRegisters(Vec<(usize, String)>), + /// A pane's Grid intercepted an app-in-pane whitelisted query; Screen + /// assigns a token, queues the forward, and dispatches to the client. + /// `query` carries the classified form so Screen can match on it + /// directly (for cache-fallback synthesis) without re-parsing bytes. + ForwardHostQuery { + pane_id: PaneId, + query: crate::host_query::HostQuery, + }, + /// The client observed the host's reply to a previously forwarded + /// query (closed by the Primary-DA barrier or the 500 ms timeout). + /// The reply bytes are written verbatim to the originating pane. + ForwardedReplyFromHost { + token: u32, + reply_bytes: Vec<u8>, + }, + /// The host terminal reported a color-palette theme mode (DSR 997 reply + /// to `CSI ? 996 n`, or unsolicited notification while `CSI ? 2031 h` + /// is enabled). Triggers auto-theme switch (when configured), the + /// `HostTerminalThemeChanged` plugin event, and per-pane DSR forwarding + /// for panes that opted in via `CSI ? 2031 h`. + HostTerminalThemeChanged(HostTerminalThemeMode), + /// Manual theme actions issued via the CLI (e.g. `zellij action set-dark-theme`) + /// or a keybinding. They share the same convergence point as + /// `HostTerminalThemeChanged`, but additionally surface a CLI-friendly error + /// via `NotificationEnd` if `theme_dark` and `theme_light` are not both set + /// (the auto-switch gate). "Last one wins": these compete naively with + /// terminal-driven notifications via the dedupe in + /// `update_host_terminal_theme_mode`. + SetDarkTheme(Option<NotificationEnd>), + SetLightTheme(Option<NotificationEnd>), + ToggleTheme(Option<NotificationEnd>), ChangeMode(ModeInfo, ClientId, Option<NotificationEnd>), ChangeModeForAllClients(ModeInfo, Option<NotificationEnd>), MouseEvent(MouseEvent, ClientId, Option<NotificationEnd>), @@ -672,6 +704,12 @@ pub enum ScreenInstruction { keybinds: Keybinds, default_mode: InputMode, theme: Styling, + /// Resolved styling for `theme_dark`. When both this and + /// `host_theme_light` are `Some`, Screen auto-switches the active + /// palette in response to host CSI 2031 / DSR 997 notifications. + host_theme_dark: Option<Styling>, + /// Resolved styling for `theme_light`. See `host_theme_dark`. + host_theme_light: Option<Styling>, simplified_ui: bool, default_shell: Option<PathBuf>, pane_frames: bool, @@ -935,6 +973,16 @@ impl From<&ScreenInstruction> for ScreenContext { ScreenContext::TerminalForegroundColor }, ScreenInstruction::TerminalColorRegisters(..) => ScreenContext::TerminalColorRegisters, + ScreenInstruction::ForwardHostQuery { .. } => ScreenContext::ForwardHostQuery, + ScreenInstruction::ForwardedReplyFromHost { .. } => { + ScreenContext::ForwardedReplyFromHost + }, + ScreenInstruction::HostTerminalThemeChanged(..) => { + ScreenContext::HostTerminalThemeChanged + }, + ScreenInstruction::SetDarkTheme(..) => ScreenContext::SetDarkTheme, + ScreenInstruction::SetLightTheme(..) => ScreenContext::SetLightTheme, + ScreenInstruction::ToggleTheme(..) => ScreenContext::ToggleTheme, ScreenInstruction::ChangeMode(..) => ScreenContext::ChangeMode, ScreenInstruction::ChangeModeForAllClients(..) => { ScreenContext::ChangeModeForAllClients @@ -1356,8 +1404,89 @@ pub(crate) struct Screen { pane_render_subscribers: HashMap<ClientId, PaneRenderSubscription>, plugins_need_ansi_pane_contents: bool, background_plugin_subscriptions: HashMap<(PluginId, ClientId), HashSet<EventType>>, + /// Monotonic counter used to tag each forwarded host-terminal query + /// with a unique token. 0 is reserved as a sentinel (see + /// `STARTUP_SENTINEL_TOKEN`); real forwards start at 1. + next_forward_token: u32, + /// Map of forwarded-query token → the originating pane plus the + /// raw query bytes. When the client sends back the reply for + /// `token`, the server looks up the pane here and writes the + /// reply bytes to its pty. The retained `query_bytes` feed the + /// cache-fallback synthesis: if the reply comes back empty + /// (detached session, client crash, host timeout), we use the + /// cached bg/fg/pixel/palette state to answer in the host's + /// stead. + pending_forwarded_queries: HashMap<u32, PendingForwardEntry>, + /// Serialization queue for forwarded queries. Invariant: at most one + /// forward is in flight to the client at a time (enforced by + /// `forward_in_flight`). When the reply (or timeout) closes the + /// active slot, the next queued forward is dispatched. + forward_queue: VecDeque<PendingForward>, + /// Token of the forward currently in flight to the (single) + /// connected client, if any. Used to: + /// * serialize forwarded queries globally (only one at a time); + /// * gate slot release on `handle_forwarded_reply_from_host` to a + /// token-equality match, so a late server-side timeout for an + /// already-answered forward cannot clobber a queued forward that + /// the real reply just dispatched. + forward_in_flight_token: Option<u32>, + /// Last-known host terminal color-palette theme mode (CSI 2031 / + /// DSR 997). `None` until the host first reports. Used both for + /// auto-theme switching and to dedupe duplicate notifications. + host_terminal_theme_mode: Option<HostTerminalThemeMode>, + /// Resolved styling to apply when `host_terminal_theme_mode == Dark`. + /// `None` disables auto-switch. Refreshed on each reconfigure. + host_theme_dark_styling: Option<Styling>, + /// Resolved styling to apply when `host_terminal_theme_mode == Light`. + /// `None` disables auto-switch. Refreshed on each reconfigure. + host_theme_light_styling: Option<Styling>, +} + +/// A pending forward waiting to be dispatched once the current in-flight +/// forward's barrier reply (or timeout) arrives. +#[derive(Debug, Clone)] +struct PendingForward { + token: u32, + pane_id: PaneId, + query: crate::host_query::HostQuery, +} + +/// A forward currently in flight (dispatched to the client, waiting +/// for a reply). Retains the `HostQuery` classification so we can +/// fall back to cache-synthesized replies when the live reply is +/// empty (no client attached, client-side timeout, etc.) without +/// re-parsing byte strings. +#[derive(Debug, Clone)] +struct PendingForwardEntry { + pane_id: PaneId, + query: crate::host_query::HostQuery, } +/// Reserved sentinel token for Zellij's own startup batch of host +/// queries (pixel dims, bg/fg, sync-output, palette registers). The +/// existing fire-and-forget startup plumbing is unchanged today; the +/// sentinel exists so a future migration can route the startup batch +/// through the same forwarded-query mechanism as per-pane queries +/// while keeping its replies routable to `Screen`'s cached state +/// rather than to a pane's pty. Reserved value 0 is excluded from +/// `next_forward_token` allocation by the wrap-skip in +/// `forward_host_query`. +const STARTUP_SENTINEL_TOKEN: u32 = 0; + +/// Server-side deadline for a forwarded host query. If no +/// `ForwardedReplyFromHost` arrives within this window, the server +/// synthesizes an empty reply for itself so the in-flight slot +/// releases and queued forwards continue to drain. +/// +/// This recovers the worst-case where the connected client doesn't +/// understand `ServerToClientMsg::ForwardQueryToHost` (an old client +/// against a new server) — without it the slot would deadlock and +/// every app-issued host query would hang. The window is generous +/// relative to the 500 ms client-side deadline so a well-behaved new +/// client always replies first; only the old-client and +/// network-pathological cases ever see this fire. +const SERVER_FORWARD_TIMEOUT_MS: u64 = 1000; + impl Screen { /// Creates and returns a new [`Screen`]. pub fn new( @@ -1457,6 +1586,13 @@ impl Screen { pane_render_subscribers: HashMap::new(), plugins_need_ansi_pane_contents: false, background_plugin_subscriptions: HashMap::new(), + next_forward_token: 1, // 0 is reserved as the startup sentinel + pending_forwarded_queries: HashMap::new(), + forward_queue: VecDeque::new(), + forward_in_flight_token: None, + host_terminal_theme_mode: None, + host_theme_dark_styling: None, + host_theme_light_styling: None, } } @@ -1953,6 +2089,237 @@ impl Screen { } } + /// Enqueue a whitelisted host-terminal query from pane `pane_id`. + /// Queries are serialized globally: at most one is in flight to the + /// client at a time; the rest wait in `forward_queue`. Returns the + /// allocated token so callers (tests) can observe it if useful. + pub fn forward_host_query( + &mut self, + pane_id: PaneId, + query: crate::host_query::HostQuery, + ) -> u32 { + // ColorPaletteMode is answered locally — Zellij already knows + // the host's mode from its own startup query and from + // unsolicited DSR 997 updates. Skip the entire forwarding + // machinery (no token, no in-flight slot, no host round-trip) + // and write the reply straight to the originating pane's pty. + if let crate::host_query::HostQuery::ColorPaletteMode = query { + self.answer_color_palette_mode_query_locally(pane_id); + return STARTUP_SENTINEL_TOKEN; // sentinel: no real forward happened + } + let token = self.next_forward_token; + // Skip over the reserved sentinel (0) on wrap; allocate a fresh + // u32 for every forward. + self.next_forward_token = self.next_forward_token.wrapping_add(1); + if self.next_forward_token == STARTUP_SENTINEL_TOKEN { + self.next_forward_token = 1; + } + if self.forward_in_flight_token.is_some() { + self.forward_queue.push_back(PendingForward { + token, + pane_id, + query, + }); + } else { + self.dispatch_forward(token, pane_id, query); + } + token + } + + /// Synthesise the DSR 997 reply to a `CSI ? 996 n` query from + /// `host_terminal_theme_mode` and write it directly to the + /// originating pane's pty. Plugin panes are skipped (they receive + /// `Event::HostTerminalThemeChanged` and have no notion of + /// VT-protocol queries). When Zellij has not yet learned the host + /// mode, the pane receives no reply — matching what a host that + /// does not implement CSI 2031 would do. The Contour spec only + /// defines `;1` (dark) and `;2` (light); fabricating any other + /// code (e.g. `;0`) would be non-conformant. + fn answer_color_palette_mode_query_locally(&mut self, pane_id: PaneId) { + let terminal_id = match pane_id { + PaneId::Terminal(id) => id, + PaneId::Plugin(_) => return, + }; + let code: u8 = match self.host_terminal_theme_mode { + Some(HostTerminalThemeMode::Dark) => 1, + Some(HostTerminalThemeMode::Light) => 2, + None => { + log::debug!( + "CSI ?996n received but host_terminal_theme_mode is unknown; \ + dropping (spec defines only 1=dark / 2=light)" + ); + return; + }, + }; + let reply = format!("\u{1b}[?997;{}n", code).into_bytes(); + let _ = self + .bus + .senders + .send_to_pty_writer(PtyWriteInstruction::Write(reply, terminal_id, None)); + } + + /// Dispatch a forward to the client and mark the slot as in-flight. + /// Spawns a one-shot timeout task on the global tokio runtime that + /// synthesizes an empty reply for `token` after + /// `SERVER_FORWARD_TIMEOUT_MS`. The handler's token-equality guard + /// makes the timeout a no-op if a real reply arrived first, so no + /// explicit cancellation is needed. + fn dispatch_forward( + &mut self, + token: u32, + pane_id: PaneId, + query: crate::host_query::HostQuery, + ) { + let query_bytes = query.to_query_bytes(); + self.pending_forwarded_queries + .insert(token, PendingForwardEntry { pane_id, query }); + self.forward_in_flight_token = Some(token); + let _ = self + .bus + .senders + .send_to_server(ServerInstruction::ForwardQueryToHost(token, query_bytes)); + let senders = self.bus.senders.clone(); + crate::global_async_runtime::get_tokio_runtime().spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(SERVER_FORWARD_TIMEOUT_MS)).await; + let _ = senders.send_to_screen(ScreenInstruction::ForwardedReplyFromHost { + token, + reply_bytes: Vec::new(), + }); + }); + } + + /// Handle a host-reply observed by the client for token `token`. + /// Writes the bytes to the originating pane's pty (if still present) + /// and releases the in-flight slot so the next queued forward can + /// dispatch. + /// + /// An empty `reply_bytes` is treated as "nobody answered" — either + /// because no client was attached to forward the query, or the + /// chosen client's host timed out. In that case we try to answer + /// from Zellij's cached view of the host (pixel dims, bg/fg, + /// palette) so the pane still gets a well-formed reply instead of + /// zero bytes. If the cache has nothing relevant either, the pane + /// receives an empty write and the app decides what to do. + pub fn handle_forwarded_reply_from_host( + &mut self, + token: u32, + reply_bytes: Vec<u8>, + ) -> Result<()> { + // Stale-reply guard. Both the real `ForwardedReplyFromHost` + // path and the server-side timeout path land here. If a real + // reply landed first (releasing the slot AND dispatching the + // next queued forward), the late timeout's empty reply for the + // already-cleared token must be a no-op — releasing the slot + // again would clobber the new in-flight forward. The same + // logic also rejects duplicate replies and replies for tokens + // belonging to a previously-closed pane. + if self.forward_in_flight_token != Some(token) { + log::debug!( + "Dropping stale forwarded reply (token={}, in-flight={:?}, len={} bytes)", + token, + self.forward_in_flight_token, + reply_bytes.len(), + ); + return Ok(()); + } + if let Some(entry) = self.pending_forwarded_queries.remove(&token) { + let PendingForwardEntry { pane_id, query } = entry; + match pane_id { + PaneId::Terminal(terminal_id) => { + let payload = if reply_bytes.is_empty() { + self.synthesize_cached_reply(&query) + } else { + reply_bytes + }; + let _ = self + .bus + .senders + .send_to_pty_writer(PtyWriteInstruction::Write(payload, terminal_id, None)); + }, + PaneId::Plugin(_) => { + // Plugin panes do not issue whitelisted host queries; + // if we reach here the mapping was populated + // erroneously. Drop the reply. + log::warn!( + "Discarding host reply for plugin pane (token={}); plugins do not forward CSI/OSC queries", + token + ); + }, + } + } + // Release the slot and dispatch the next queued forward, if any. + self.forward_in_flight_token = None; + if let Some(next) = self.forward_queue.pop_front() { + self.dispatch_forward(next.token, next.pane_id, next.query); + } + Ok(()) + } + + /// Build a reply for `query` from whatever host state Zellij has + /// cached, or an empty `Vec` if nothing relevant is cached. The + /// classification happened at intercept time (Grid produces a + /// [`HostQuery`]), so this method is pure structural dispatch — + /// no re-parsing of bytes. + fn synthesize_cached_reply(&self, query: &crate::host_query::HostQuery) -> Vec<u8> { + use crate::host_query::HostQuery; + match query { + HostQuery::TextAreaPixelSize => self + .pixel_dimensions + .text_area_size + .map(|dims| format!("\x1b[4;{};{}t", dims.height, dims.width).into_bytes()) + .unwrap_or_default(), + HostQuery::CharacterCellPixelSize => self + .pixel_dimensions + .character_cell_size + .map(|dims| format!("\x1b[6;{};{}t", dims.height, dims.width).into_bytes()) + .unwrap_or_default(), + HostQuery::DefaultForeground { terminator } + | HostQuery::DefaultBackground { terminator } => { + let palette = self.terminal_emulator_colors.borrow(); + let (channel, color) = match query { + HostQuery::DefaultForeground { .. } => (10u32, palette.fg), + HostQuery::DefaultBackground { .. } => (11u32, palette.bg), + _ => unreachable!(), + }; + if let PaletteColor::Rgb((r, g, b)) = color { + let mut out = format!( + "\x1b]{};rgb:{:04x}/{:04x}/{:04x}", + channel, + (r as u16) * 0x0101, + (g as u16) * 0x0101, + (b as u16) * 0x0101, + ) + .into_bytes(); + out.extend_from_slice(terminator.as_bytes()); + out + } else { + Vec::new() + } + }, + HostQuery::PaletteRegister { index, terminator } => { + let codes = self.terminal_emulator_color_codes.borrow(); + if let Some(color) = codes.get(&(*index as usize)) { + let mut out = format!("\x1b]4;{};{}", index, color).into_bytes(); + out.extend_from_slice(terminator.as_bytes()); + out + } else { + Vec::new() + } + }, + // Should not reach here: ColorPaletteMode short-circuits in + // `forward_host_query` before any cache-fallback path runs. + // The Contour spec only defines `;1` and `;2`; if the host + // mode is unknown there is no compliant reply, so return + // empty bytes (the existing convention for "no synthesis + // possible"). + HostQuery::ColorPaletteMode => match self.host_terminal_theme_mode { + Some(HostTerminalThemeMode::Dark) => b"\x1b[?997;1n".to_vec(), + Some(HostTerminalThemeMode::Light) => b"\x1b[?997;2n".to_vec(), + None => Vec::new(), + }, + } + } + pub fn render(&mut self, plugin_render_assets: Option<Vec<PluginRenderAsset>>) -> Result<()> { // here we schedule the RenderToClients background job which debounces renders every 10ms // rather than actually rendering @@ -4103,6 +4470,136 @@ impl Screen { } Ok(()) } + /// Apply a host-reported color-palette theme mode (CSI 2031 / DSR 997). + /// + /// This is the Phase 2 entry-point: it + /// 1. de-duplicates against the last-known mode, + /// 2. swaps the active palette to the configured `theme_dark` / `theme_light` + /// (when both are configured) by reusing the reconfigure propagation, + /// 3. fans out an `Event::HostTerminalThemeChanged` plugin event, + /// 4. forwards a `CSI ?997;{1|2}n` DSR onto the pty of every terminal pane + /// whose app opted in via `CSI ? 2031 h`. + pub fn update_host_terminal_theme_mode(&mut self, mode: HostTerminalThemeMode) -> Result<()> { + let err_context = || "Failed to update host terminal theme mode".to_string(); + + // dedupe + if self.host_terminal_theme_mode == Some(mode) { + return Ok(()); + } + self.host_terminal_theme_mode = Some(mode); + + // resolve target styling + let resolved = match mode { + HostTerminalThemeMode::Dark => self.host_theme_dark_styling, + HostTerminalThemeMode::Light => self.host_theme_light_styling, + }; + + // theme propagation when both keys configured and the resolved + // styling exists. (If only one of theme_dark/theme_light is set, + // skip auto-switch; the static `theme` stays authoritative.) + let auto_switch_enabled = + self.host_theme_dark_styling.is_some() && self.host_theme_light_styling.is_some(); + if auto_switch_enabled { + if let Some(theme) = resolved { + self.default_mode_info.update_theme(theme); + for tab in self.tabs.values_mut() { + tab.update_theme(theme); + } + // Iterate every connected client (active_tab_ids is the + // canonical "who is connected" map). Iterating + // self.mode_info.keys() would skip any client that has + // never manually changed mode + let client_ids: Vec<ClientId> = self.active_tab_ids.keys().copied().collect(); + let default_for_new = self.default_mode_info.clone(); + for client_id in client_ids { + let mode_info = self + .mode_info + .entry(client_id) + .or_insert_with(|| default_for_new.clone()); + mode_info.update_theme(theme); + let mode_info_clone = mode_info.clone(); + // Push the freshly-themed mode_info into every tab's + // per-client mode_info map. `update_input_modes` below + // reads from THAT map (not Screen's) when fanning out + // ModeUpdate to plugins, so without this step plugins + // receive ModeUpdate carrying the *old* style and the + // status-bar / tab-bar do not repaint. Also mark the + // active pane for rerender so terminal panes refresh + // their borders/title using the new palette. + for tab in self.tabs.values_mut() { + tab.change_mode_info(mode_info_clone.clone(), client_id); + tab.mark_active_pane_for_rerender(client_id); + } + } + for tab in self.tabs.values_mut() { + tab.update_input_modes().with_context(err_context)?; + } + } else { + log::warn!( + "host theme auto-switch enabled but resolved styling missing for {:?}", + mode + ); + } + } + + // fan out the plugin event + self.bus + .senders + .send_to_plugin(PluginInstruction::Update(vec![( + None, + None, + Event::HostTerminalThemeChanged(mode), + )])) + .with_context(err_context)?; + + // forward DSR to opted-in terminal panes + let mut pty_writes: Vec<(Vec<u8>, u32)> = vec![]; + for tab in self.tabs.values_mut() { + for pane_id in tab.get_all_pane_ids() { + if let PaneId::Terminal(terminal_id) = pane_id { + if let Some(pane) = tab.get_pane_with_id_mut(pane_id) { + pane.push_color_palette_dsr(mode); + for bytes in pane.drain_messages_to_pty() { + pty_writes.push((bytes, terminal_id)); + } + } + } + } + } + for (bytes, terminal_id) in pty_writes { + let _ = self + .bus + .senders + .send_to_pty_writer(PtyWriteInstruction::Write(bytes, terminal_id, None)); + } + + self.render(None)?; + Ok(()) + } + /// Apply a manual host-terminal theme mode change requested via the CLI or a + /// keybinding. Surfaces a clear error to the CLI if the auto-switch gate + /// (both `theme_dark` and `theme_light` configured) is not satisfied; + /// otherwise delegates to `update_host_terminal_theme_mode`, which dedupes, + /// repaints, fans out the plugin event, and forwards DSR to opted-in panes. + pub fn apply_manual_host_terminal_theme_mode( + &mut self, + mode: HostTerminalThemeMode, + completion_tx: &mut Option<NotificationEnd>, + ) -> Result<()> { + let auto_switch_enabled = + self.host_theme_dark_styling.is_some() && self.host_theme_light_styling.is_some(); + if !auto_switch_enabled { + if let Some(c) = completion_tx.as_mut() { + c.set_exit_status(1); + c.set_error_message( + "Manual theme switching requires both `theme_dark` and `theme_light` to be configured." + .to_string(), + ); + } + return Ok(()); + } + self.update_host_terminal_theme_mode(mode) + } pub fn toggle_pane_pinned(&mut self, client_id: ClientId) { active_tab_and_connected_client_id!( self, @@ -4960,6 +5457,33 @@ pub(crate) fn screen_thread_main( debug: bool, default_layout: Box<Layout>, ) -> Result<()> { + // Resolve `theme_dark` / `theme_light` to concrete `Styling` from the + // bundled themes BEFORE `config.options` is moved out below. These + // populate Screen's auto-switch state at startup; runtime updates + // continue to flow through `propagate_configuration_changes`. + let host_theme_dark_styling = config + .options + .theme_dark + .as_ref() + .and_then(|name| config.themes.get_theme(name).map(|t| t.palette)); + let host_theme_light_styling = config + .options + .theme_light + .as_ref() + .and_then(|name| config.themes.get_theme(name).map(|t| t.palette)); + if config.options.theme_dark.is_some() && host_theme_dark_styling.is_none() { + log::warn!( + "theme_dark='{}' not found in themes; auto-theme switch disabled for dark.", + config.options.theme_dark.as_deref().unwrap_or("?") + ); + } + if config.options.theme_light.is_some() && host_theme_light_styling.is_none() { + log::warn!( + "theme_light='{}' not found in themes; auto-theme switch disabled for light.", + config.options.theme_light.as_deref().unwrap_or("?") + ); + } + let config_options = config.options; let arrow_fonts = !config_options.simplified_ui.unwrap_or_default(); let draw_pane_frames = config_options.pane_frames.unwrap_or(true); @@ -5059,6 +5583,8 @@ pub(crate) fn screen_thread_main( web_server_ip, web_server_port, ); + screen.host_theme_dark_styling = host_theme_dark_styling; + screen.host_theme_light_styling = host_theme_light_styling; let mut pending_tab_ids: HashSet<usize> = HashSet::new(); let mut pending_tab_switches: HashSet<(usize, ClientId)> = HashSet::new(); // usize is the @@ -6628,6 +7154,36 @@ pub(crate) fn screen_thread_main( ScreenInstruction::TerminalColorRegisters(color_registers) => { screen.update_terminal_color_registers(color_registers); }, + ScreenInstruction::ForwardHostQuery { pane_id, query } => { + screen.forward_host_query(pane_id, query); + }, + ScreenInstruction::ForwardedReplyFromHost { token, reply_bytes } => { + screen.handle_forwarded_reply_from_host(token, reply_bytes)?; + }, + ScreenInstruction::HostTerminalThemeChanged(mode) => { + screen.update_host_terminal_theme_mode(mode)?; + }, + ScreenInstruction::SetDarkTheme(mut completion_tx) => { + screen.apply_manual_host_terminal_theme_mode( + HostTerminalThemeMode::Dark, + &mut completion_tx, + )?; + }, + ScreenInstruction::SetLightTheme(mut completion_tx) => { + screen.apply_manual_host_terminal_theme_mode( + HostTerminalThemeMode::Light, + &mut completion_tx, + )?; + }, + ScreenInstruction::ToggleTheme(mut completion_tx) => { + let next = match screen.host_terminal_theme_mode { + Some(HostTerminalThemeMode::Dark) => HostTerminalThemeMode::Light, + Some(HostTerminalThemeMode::Light) => HostTerminalThemeMode::Dark, + // No prior mode: treat as Dark and toggle to Light. + None => HostTerminalThemeMode::Light, + }; + screen.apply_manual_host_terminal_theme_mode(next, &mut completion_tx)?; + }, ScreenInstruction::ChangeMode( mode_info, client_id, @@ -8026,6 +8582,8 @@ pub(crate) fn screen_thread_main( keybinds, default_mode, theme, + host_theme_dark, + host_theme_light, simplified_ui, default_shell, pane_frames, @@ -8043,6 +8601,8 @@ pub(crate) fn screen_thread_main( focus_follows_mouse, mouse_click_through, } => { + screen.host_theme_dark_styling = host_theme_dark; + screen.host_theme_light_styling = host_theme_light; screen .reconfigure( keybinds, diff --git a/zellij-server/src/tab/mod.rs b/zellij-server/src/tab/mod.rs index 928f7c79..36744b96 100644 --- a/zellij-server/src/tab/mod.rs +++ b/zellij-server/src/tab/mod.rs @@ -409,6 +409,17 @@ pub trait Pane { // we should probably refactor away from this trait at some point vec![] } + fn drain_forwarded_queries(&mut self) -> Vec<crate::host_query::HostQuery> { + // Only terminal panes forward whitelisted queries to the host; + // plugin panes have no such concept. + vec![] + } + /// Push a CSI ?997 DSR notification (host color-palette theme mode) + /// onto this pane's pending pty-write queue, but only if the pane's + /// underlying app opted in via `CSI ? 2031 h`. + /// Only relevant to terminal panes, plugin panes receive this through + /// `Event::HostTerminalThemeChanged` + fn push_color_palette_dsr(&mut self, _mode: zellij_utils::data::HostTerminalThemeMode) {} fn drain_clipboard_update(&mut self) -> Option<String> { None } @@ -2723,6 +2734,7 @@ impl Tab { } terminal_output.handle_pty_bytes(bytes); let messages_to_pty = terminal_output.drain_messages_to_pty(); + let forwarded_queries = terminal_output.drain_forwarded_queries(); let clipboard_update = terminal_output.drain_clipboard_update(); let desktop_notifications = terminal_output.drain_desktop_notifications(); let osc7_cwd = terminal_output.drain_osc7_cwd(); @@ -2730,6 +2742,14 @@ impl Tab { self.write_to_pane_id_without_preprocessing(message, PaneId::Terminal(pid)) .with_context(err_context)?; } + for query in forwarded_queries { + let _ = self + .senders + .send_to_screen(ScreenInstruction::ForwardHostQuery { + pane_id: PaneId::Terminal(pid), + query, + }); + } if let Some(string) = clipboard_update { self.write_selection_to_clipboard(&string) .with_context(err_context)?; @@ -5529,6 +5549,13 @@ impl Tab { } pub fn update_theme(&mut self, theme: Styling) { self.style.colors = theme; + // The tab's `default_mode_info` is what `update_input_modes` + // falls back to when no per-client entry exists in + // `self.mode_info`. Without this update, plugins on a + // freshly-connected client (one that has never manually + // changed mode) receive `Event::ModeUpdate` carrying the old + // style and skip their re-render. + self.default_mode_info.update_theme(theme); self.floating_panes.update_pane_themes(theme); self.tiled_panes.update_pane_themes(theme); for (_, pane) in self.suppressed_panes.values_mut() { diff --git a/zellij-server/src/unit/screen_tests.rs b/zellij-server/src/unit/screen_tests.rs index 27304131..ef2da903 100644 --- a/zellij-server/src/unit/screen_tests.rs +++ b/zellij-server/src/unit/screen_tests.rs @@ -8322,3 +8322,873 @@ pub fn pty_bytes_and_hold_pane_buffered_before_new_pane() { dumped ); } + +// ===================================================================== +// Host-reply forwarding (CSI 2031) +// +// These tests exercise the token-lifecycle API on `Screen` directly — +// no route.rs, no thread spawn, no client. The harness plugs real +// `to_server` / `to_pty_writer` channels into the Bus so the forward +// dispatch (→ `ServerInstruction::ForwardQueryToHost`) and the reply +// write (→ `PtyWriteInstruction::Write`) can be asserted. +// ===================================================================== + +struct ForwardCapture { + server_rx: Receiver<(ServerInstruction, ErrorContext)>, + pty_writer_rx: Receiver<(PtyWriteInstruction, ErrorContext)>, +} + +impl ForwardCapture { + /// Drain every pending `ServerInstruction::ForwardQueryToHost` and + /// return them as `(token, query_bytes)` pairs. Other variants are + /// dropped — the forward path only ever emits this one. + fn drain_forward_queries(&self) -> Vec<(u32, Vec<u8>)> { + let mut out = Vec::new(); + while let Ok((instr, _ctx)) = self.server_rx.try_recv() { + if let ServerInstruction::ForwardQueryToHost(token, bytes) = instr { + out.push((token, bytes)); + } + } + out + } + + /// Drain every pending `PtyWriteInstruction::Write`, returning + /// `(bytes, terminal_id)` — the two fields the reply path sets. + fn drain_pty_writes(&self) -> Vec<(Vec<u8>, u32)> { + let mut out = Vec::new(); + while let Ok((instr, _ctx)) = self.pty_writer_rx.try_recv() { + if let PtyWriteInstruction::Write(bytes, terminal_id, _) = instr { + out.push((bytes, terminal_id)); + } + } + out + } +} + +fn create_new_screen_with_forward_capture(size: Size) -> (Screen, ForwardCapture) { + let (server_tx, server_rx) = channels::unbounded::<(ServerInstruction, ErrorContext)>(); + let (pty_writer_tx, pty_writer_rx) = + channels::unbounded::<(PtyWriteInstruction, ErrorContext)>(); + + let mut bus: Bus<ScreenInstruction> = Bus::empty(); + bus.senders.to_server = Some(SenderWithContext::new(server_tx)); + bus.senders.to_pty_writer = Some(SenderWithContext::new(pty_writer_tx)); + let fake_os_input = FakeInputOutput::default(); + bus.os_input = Some(Box::new(fake_os_input)); + + let client_attributes = ClientAttributes { + size, + ..Default::default() + }; + let max_panes = None; + let mut mode_info = ModeInfo::default(); + mode_info.session_name = Some("zellij-test".into()); + let draw_pane_frames = false; + let auto_layout = true; + let session_is_mirrored = true; + let copy_options = CopyOptions::default(); + let default_layout = Box::new(Layout::default()); + let default_layout_name = None; + let default_shell = PathBuf::from("my_default_shell"); + let session_serialization = true; + let serialize_pane_viewport = false; + let scrollback_lines_to_serialize = None; + let layout_dir = None; + let debug = false; + let styled_underlines = true; + let osc8_hyperlinks = true; + let arrow_fonts = true; + let explicitly_disable_kitty_keyboard_protocol = false; + let stacked_resize = true; + let web_sharing = WebSharing::Off; + let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + let web_server_port = 8080; + let visual_bell = true; + let screen = Screen::new( + bus, + &client_attributes, + max_panes, + mode_info, + draw_pane_frames, + auto_layout, + session_is_mirrored, + copy_options, + debug, + default_layout, + default_layout_name, + default_shell, + session_serialization, + serialize_pane_viewport, + scrollback_lines_to_serialize, + styled_underlines, + osc8_hyperlinks, + arrow_fonts, + layout_dir, + explicitly_disable_kitty_keyboard_protocol, + stacked_resize, + None, + false, + web_sharing, + true, + true, + visual_bell, + false, // focus_follows_mouse + false, // mouse_click_through + web_server_ip, + web_server_port, + ); + ( + screen, + ForwardCapture { + server_rx, + pty_writer_rx, + }, + ) +} + +// Convenience constructors for the forwarding tests — all callers +// want a fresh `HostQuery` value with the default terminator. +use crate::host_query::{HostQuery, OscTerminator}; + +fn bg_query() -> HostQuery { + HostQuery::DefaultBackground { + terminator: OscTerminator::St, + } +} +fn fg_query() -> HostQuery { + HostQuery::DefaultForeground { + terminator: OscTerminator::St, + } +} +fn fg_query_bel() -> HostQuery { + HostQuery::DefaultForeground { + terminator: OscTerminator::Bel, + } +} +fn palette_query(index: u8) -> HostQuery { + HostQuery::PaletteRegister { + index, + terminator: OscTerminator::St, + } +} + +#[test] +fn forward_host_query_when_idle_dispatches_immediately() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane_id = PaneId::Terminal(42); + let query = bg_query(); + + let token = screen.forward_host_query(pane_id, query.clone()); + + assert_eq!( + screen.forward_in_flight_token, + Some(token), + "slot must flip to in-flight for the dispatched token" + ); + assert_eq!( + screen + .pending_forwarded_queries + .get(&token) + .map(|e| e.pane_id), + Some(pane_id), + "token→pane mapping must be populated" + ); + let forwards = capture.drain_forward_queries(); + assert_eq!(forwards.len(), 1, "exactly one forward dispatched"); + assert_eq!( + forwards[0], + (token, query.to_query_bytes()), + "wire bytes must be derived from the HostQuery" + ); +} + +#[test] +fn forward_host_query_when_busy_queues_instead_of_dispatching() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let first_pane = PaneId::Terminal(1); + let second_pane = PaneId::Terminal(2); + + let first_token = screen.forward_host_query(first_pane, bg_query()); + let second_token = screen.forward_host_query(second_pane, fg_query()); + + // The first call dispatched; the second waits in the queue. Only + // the first token should be in the map; the second lives in + // `forward_queue`. + let forwards = capture.drain_forward_queries(); + assert_eq!(forwards.len(), 1, "second call must not dispatch yet"); + assert_eq!(forwards[0].0, first_token); + assert_eq!(screen.forward_queue.len(), 1); + assert_eq!(screen.forward_queue[0].token, second_token); + assert_eq!(screen.forward_queue[0].pane_id, second_pane); +} + +#[test] +fn handle_reply_writes_to_pane_pty_and_releases_slot() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane_id = PaneId::Terminal(7); + let token = screen.forward_host_query(pane_id, bg_query()); + let _ = capture.drain_forward_queries(); // discard the dispatch + + let reply = b"\x1b]11;rgb:1111/2222/3333\x1b\\".to_vec(); + screen + .handle_forwarded_reply_from_host(token, reply.clone()) + .expect("handler must not fail"); + + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1, "one pty write expected"); + assert_eq!(writes[0], (reply, 7)); + assert!( + screen.forward_in_flight_token.is_none(), + "slot released so the next queued forward can dispatch" + ); + assert!( + screen.pending_forwarded_queries.get(&token).is_none(), + "token entry must have been removed from the map" + ); +} + +#[test] +fn handle_reply_dispatches_next_queued_forward() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let first_pane = PaneId::Terminal(1); + let second_pane = PaneId::Terminal(2); + let first_token = screen.forward_host_query(first_pane, bg_query()); + let second_token = screen.forward_host_query(second_pane, fg_query()); + // First dispatch already emitted; drop it. + let _ = capture.drain_forward_queries(); + + screen + .handle_forwarded_reply_from_host(first_token, b"reply".to_vec()) + .expect("ok"); + + // The queued second forward must now dispatch, and the map now + // carries the second token → second pane. + let forwards = capture.drain_forward_queries(); + assert_eq!(forwards.len(), 1, "next queued forward must dispatch"); + assert_eq!(forwards[0].0, second_token); + assert!(screen.forward_queue.is_empty()); + assert_eq!(screen.forward_in_flight_token, Some(second_token)); + assert_eq!( + screen + .pending_forwarded_queries + .get(&second_token) + .map(|e| e.pane_id), + Some(second_pane) + ); +} + +#[test] +fn handle_reply_with_unknown_token_is_silent_noop() { + // Token not in the map AND not the in-flight token: the handler + // must not panic, must not write any bytes, and crucially must + // NOT release the slot — the actually-in-flight forward still + // owns it. (See `late_timeout_after_real_reply_does_not_clobber` + // for the race scenario this guard prevents.) + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let first_pane = PaneId::Terminal(1); + let second_pane = PaneId::Terminal(2); + let first_token = screen.forward_host_query(first_pane, bg_query()); + let _second_token = screen.forward_host_query(second_pane, fg_query()); + let _ = capture.drain_forward_queries(); + + // Reply for a stale / unknown token (neither first nor second). + screen + .handle_forwarded_reply_from_host(9999, b"dropped".to_vec()) + .expect("unknown tokens must not error"); + + assert!( + capture.drain_pty_writes().is_empty(), + "unknown token must not produce any pty write" + ); + assert_eq!( + screen.forward_in_flight_token, + Some(first_token), + "in-flight token must still be the original" + ); + assert!( + capture.drain_forward_queries().is_empty(), + "stale reply must not advance the queue" + ); +} + +#[test] +fn late_timeout_after_real_reply_does_not_clobber_next_in_flight() { + // The race the token-equality guard exists to prevent: + // 1. dispatch token A (slot in-flight = A; A's timer is sleeping). + // 2. real reply for A arrives → handler releases slot, dispatches + // queued token B → slot in-flight = B; B's timer is sleeping. + // 3. A's server-side timeout fires after the real reply, sending + // an empty `ForwardedReplyFromHost { token: A, reply_bytes: [] }`. + // + // Without the guard, step 3 would clear the slot for token B and + // pop the next queued forward, clobbering an actively-in-flight + // request. The guard makes the late timeout a no-op. + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane_a = PaneId::Terminal(1); + let pane_b = PaneId::Terminal(2); + let pane_c = PaneId::Terminal(3); + let token_a = screen.forward_host_query(pane_a, bg_query()); + let token_b = screen.forward_host_query(pane_b, fg_query()); + let token_c = screen.forward_host_query(pane_c, palette_query(5)); + let _ = capture.drain_forward_queries(); + + // Real reply for A arrives → slot moves to B. + screen + .handle_forwarded_reply_from_host(token_a, b"real-A".to_vec()) + .expect("ok"); + let dispatched = capture.drain_forward_queries(); + assert_eq!(dispatched.len(), 1, "B must dispatch on A's release"); + assert_eq!(dispatched[0].0, token_b); + assert_eq!(screen.forward_in_flight_token, Some(token_b)); + // Drain the real reply's pty write so the late-timeout assertion + // below only sees writes (or absence thereof) caused by step 3. + let real_writes = capture.drain_pty_writes(); + assert_eq!(real_writes.len(), 1, "real reply should write once"); + + // Late timeout for A fires (server-side timer woke up after the + // real reply already advanced the queue). + screen + .handle_forwarded_reply_from_host(token_a, Vec::new()) + .expect("late timeout must be a no-op, not an error"); + + assert_eq!( + screen.forward_in_flight_token, + Some(token_b), + "B's slot must NOT be released by A's late timeout" + ); + assert_eq!( + screen.forward_queue.front().map(|p| p.token), + Some(token_c), + "C must still be queued — A's late timeout must not have popped it" + ); + assert!( + capture.drain_forward_queries().is_empty(), + "no spurious dispatch from a late timeout" + ); + assert!( + capture.drain_pty_writes().is_empty(), + "no synthetic write to any pane from a late timeout" + ); +} + +#[test] +fn timeout_for_in_flight_token_releases_slot_with_cache_fallback() { + // The non-racing case: server-side timeout fires while the token + // is still in flight (no client reply ever arrived — the old-client + // compatibility path). The handler must synthesize a cache-derived + // reply for the pane, release the slot, and dispatch the next + // queued forward. (Identical externally to the empty-reply + // cache-fallback case, since the timer fires by sending an empty + // reply for the in-flight token.) + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + screen.update_terminal_background_color("rgb:1010/2020/3030".to_string()); + let pane = PaneId::Terminal(11); + let queued_pane = PaneId::Terminal(12); + let token = screen.forward_host_query(pane, bg_query()); + let queued_token = screen.forward_host_query(queued_pane, fg_query()); + let _ = capture.drain_forward_queries(); + + // Simulate the timeout firing: empty reply for the in-flight token. + screen + .handle_forwarded_reply_from_host(token, Vec::new()) + .expect("ok"); + + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1, "cache fallback writes one reply"); + assert_eq!( + std::str::from_utf8(&writes[0].0).unwrap(), + "\u{1b}]11;rgb:1010/2020/3030\u{1b}\\", + ); + assert_eq!( + screen.forward_in_flight_token, + Some(queued_token), + "queued forward dispatched on slot release" + ); +} + +#[test] +fn token_counter_wraps_skipping_sentinel() { + // `next_forward_token == u32::MAX` → first allocation yields + // `u32::MAX`, the counter then wraps to 0 which is the reserved + // sentinel and is skipped, so the next allocation yields 1. + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + screen.next_forward_token = u32::MAX; + + let t1 = screen.forward_host_query(PaneId::Terminal(1), bg_query()); + // Clear the in-flight slot so the next call actually allocates + // (the queueing branch would still allocate, but we want the + // dispatch branch here). + screen + .handle_forwarded_reply_from_host(t1, b"r".to_vec()) + .expect("ok"); + let _ = capture.drain_forward_queries(); + let _ = capture.drain_pty_writes(); + + let t2 = screen.forward_host_query(PaneId::Terminal(2), fg_query()); + assert_eq!(t1, u32::MAX, "first token should land on u32::MAX"); + assert_eq!( + t2, 1, + "sentinel 0 must be skipped; next allocation wraps to 1" + ); +} + +#[test] +fn plugin_pane_reply_is_dropped_without_write() { + // Plugin panes never emit whitelisted host queries in production + // code, but if a token → PaneId::Plugin mapping ever lands in the + // map (via tests or future misuse), the handler must drop the + // reply rather than routing it to the pty writer (plugin panes + // don't have a pty). + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + screen.pending_forwarded_queries.insert( + 77, + super::PendingForwardEntry { + pane_id: PaneId::Plugin(42), + query: bg_query(), + }, + ); + screen.forward_in_flight_token = Some(77); + + screen + .handle_forwarded_reply_from_host(77, b"\x1b]11;rgb:0/0/0\x1b\\".to_vec()) + .expect("ok"); + + assert!( + capture.drain_pty_writes().is_empty(), + "plugin-pane token must not produce a pty write" + ); + assert!( + screen.pending_forwarded_queries.get(&77).is_none(), + "map entry must still be cleared even when the reply is dropped" + ); + assert!( + screen.forward_in_flight_token.is_none(), + "slot still released" + ); +} + +// ===================================================================== +// Cache-fallback synthesis: empty reply → answer from Screen's caches +// ===================================================================== + +#[test] +fn empty_reply_falls_back_to_cached_background() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane = PaneId::Terminal(9); + screen.update_terminal_background_color("rgb:1010/2020/3030".to_string()); + let token = screen.forward_host_query(pane, bg_query()); + let _ = capture.drain_forward_queries(); + + // Empty reply — the client couldn't or didn't answer. + screen + .handle_forwarded_reply_from_host(token, Vec::new()) + .expect("ok"); + + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1, "synthesis must write exactly one reply"); + let (bytes, terminal_id) = &writes[0]; + assert_eq!(*terminal_id, 9); + assert_eq!( + std::str::from_utf8(bytes).unwrap(), + "\u{1b}]11;rgb:1010/2020/3030\u{1b}\\", + ); +} + +#[test] +fn empty_reply_falls_back_to_cached_foreground_with_bel_terminator() { + // Query used BEL; reply must mirror the same terminator. + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane = PaneId::Terminal(1); + screen.update_terminal_foreground_color("rgb:dcdc/dcdc/dcdc".to_string()); + let token = screen.forward_host_query(pane, fg_query_bel()); + let _ = capture.drain_forward_queries(); + + screen + .handle_forwarded_reply_from_host(token, Vec::new()) + .expect("ok"); + + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1); + assert_eq!( + std::str::from_utf8(&writes[0].0).unwrap(), + "\u{1b}]10;rgb:dcdc/dcdc/dcdc\u{7}", + ); +} + +#[test] +fn empty_reply_falls_back_to_cached_pixel_dimensions() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane = PaneId::Terminal(1); + screen.update_pixel_dimensions(PixelDimensions { + character_cell_size: Some(SizeInPixels { + height: 19, + width: 9, + }), + text_area_size: Some(SizeInPixels { + height: 608, + width: 931, + }), + }); + + // CSI 14t — text-area pixels. + let token = screen.forward_host_query(pane, HostQuery::TextAreaPixelSize); + let _ = capture.drain_forward_queries(); + screen + .handle_forwarded_reply_from_host(token, Vec::new()) + .expect("ok"); + let writes = capture.drain_pty_writes(); + assert_eq!( + std::str::from_utf8(&writes[0].0).unwrap(), + "\u{1b}[4;608;931t" + ); + + // CSI 16t — cell size. + let token = screen.forward_host_query(pane, HostQuery::CharacterCellPixelSize); + let _ = capture.drain_forward_queries(); + screen + .handle_forwarded_reply_from_host(token, Vec::new()) + .expect("ok"); + let writes = capture.drain_pty_writes(); + assert_eq!(std::str::from_utf8(&writes[0].0).unwrap(), "\u{1b}[6;19;9t"); +} + +#[test] +fn empty_reply_falls_back_to_cached_palette_register() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane = PaneId::Terminal(1); + screen.update_terminal_color_registers(vec![(42, "rgb:abab/cdcd/efef".to_string())]); + let token = screen.forward_host_query(pane, palette_query(42)); + let _ = capture.drain_forward_queries(); + + screen + .handle_forwarded_reply_from_host(token, Vec::new()) + .expect("ok"); + + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1); + assert_eq!( + std::str::from_utf8(&writes[0].0).unwrap(), + "\u{1b}]4;42;rgb:abab/cdcd/efef\u{1b}\\", + ); +} + +#[test] +fn empty_reply_with_no_cache_writes_empty() { + // No background override, no palette, no pixel dims: synthesis + // returns empty and the pane receives an empty write — the app + // decides what to do with "host declined". + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane = PaneId::Terminal(1); + + // Default Palette::fg is EightBit(0), not Rgb — synthesis refuses. + let token = screen.forward_host_query(pane, fg_query()); + let _ = capture.drain_forward_queries(); + screen + .handle_forwarded_reply_from_host(token, Vec::new()) + .expect("ok"); + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1, "still writes — the write is empty bytes"); + assert!( + writes[0].0.is_empty(), + "no rgb cache → synthesis returns empty" + ); +} + +#[test] +fn non_empty_reply_bypasses_synthesis() { + // A real reply from the host must be passed through verbatim — + // we must not second-guess it with cached state. + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + let pane = PaneId::Terminal(1); + screen.update_terminal_background_color("rgb:0000/0000/0000".to_string()); + let token = screen.forward_host_query(pane, bg_query()); + let _ = capture.drain_forward_queries(); + + let real = b"\x1b]11;rgb:ffff/ffff/ffff\x1b\\".to_vec(); + screen + .handle_forwarded_reply_from_host(token, real.clone()) + .expect("ok"); + + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1); + assert_eq!( + writes[0].0, real, + "real reply must be forwarded verbatim, not replaced by cached bg" + ); +} + +// ===================================================================== +// (CSI 2031 / DSR 997) (dark/light theme changes) +// ===================================================================== + +struct ThemeCapture { + plugin_rx: Receiver<(PluginInstruction, ErrorContext)>, + pty_writer_rx: Receiver<(PtyWriteInstruction, ErrorContext)>, +} + +impl ThemeCapture { + fn drain_plugin_events(&self) -> Vec<Event> { + let mut out = Vec::new(); + while let Ok((instr, _ctx)) = self.plugin_rx.try_recv() { + if let PluginInstruction::Update(updates) = instr { + for (_pid, _cid, ev) in updates { + out.push(ev); + } + } + } + out + } + fn drain_pty_writes(&self) -> Vec<(Vec<u8>, u32)> { + let mut out = Vec::new(); + while let Ok((instr, _ctx)) = self.pty_writer_rx.try_recv() { + if let PtyWriteInstruction::Write(bytes, terminal_id, _) = instr { + out.push((bytes, terminal_id)); + } + } + out + } +} + +fn create_new_screen_with_theme_capture(size: Size) -> (Screen, ThemeCapture) { + let (plugin_tx, plugin_rx) = channels::unbounded::<(PluginInstruction, ErrorContext)>(); + let (pty_writer_tx, pty_writer_rx) = + channels::unbounded::<(PtyWriteInstruction, ErrorContext)>(); + + let mut bus: Bus<ScreenInstruction> = Bus::empty(); + bus.senders.to_plugin = Some(SenderWithContext::new(plugin_tx)); + bus.senders.to_pty_writer = Some(SenderWithContext::new(pty_writer_tx)); + let fake_os_input = FakeInputOutput::default(); + bus.os_input = Some(Box::new(fake_os_input)); + + let client_attributes = ClientAttributes { + size, + ..Default::default() + }; + let mut mode_info = ModeInfo::default(); + mode_info.session_name = Some("zellij-test".into()); + let copy_options = CopyOptions::default(); + let default_layout = Box::new(Layout::default()); + let default_shell = PathBuf::from("my_default_shell"); + let web_sharing = WebSharing::Off; + let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + let web_server_port = 8080; + let screen = Screen::new( + bus, + &client_attributes, + None, + mode_info, + false, + true, + true, + copy_options, + false, + default_layout, + None, + default_shell, + true, + false, + None, + true, + true, + true, + None, + false, + true, + None, + false, + web_sharing, + true, + true, + true, + false, + false, + web_server_ip, + web_server_port, + ); + ( + screen, + ThemeCapture { + plugin_rx, + pty_writer_rx, + }, + ) +} + +#[test] +fn host_theme_first_update_emits_plugin_event() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_theme_capture(size); + + screen + .update_host_terminal_theme_mode(zellij_utils::data::HostTerminalThemeMode::Dark) + .expect("update ok"); + + let events = capture.drain_plugin_events(); + assert!( + events.iter().any(|e| matches!( + e, + Event::HostTerminalThemeChanged(zellij_utils::data::HostTerminalThemeMode::Dark) + )), + "Event::HostTerminalThemeChanged(Dark) must be fanned out, got: {:?}", + events + ); + assert_eq!( + screen.host_terminal_theme_mode, + Some(zellij_utils::data::HostTerminalThemeMode::Dark), + "stored mode must be updated" + ); +} + +#[test] +fn host_theme_dedupes_duplicate_mode() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_theme_capture(size); + + screen + .update_host_terminal_theme_mode(zellij_utils::data::HostTerminalThemeMode::Light) + .expect("first ok"); + let _ = capture.drain_plugin_events(); + + screen + .update_host_terminal_theme_mode(zellij_utils::data::HostTerminalThemeMode::Light) + .expect("second ok"); + + let events = capture.drain_plugin_events(); + assert!( + events.is_empty(), + "duplicate mode must not re-emit any plugin events, got: {:?}", + events + ); +} + +#[test] +fn host_theme_emits_again_on_mode_flip() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_theme_capture(size); + + screen + .update_host_terminal_theme_mode(zellij_utils::data::HostTerminalThemeMode::Dark) + .expect("first ok"); + let _ = capture.drain_plugin_events(); + + screen + .update_host_terminal_theme_mode(zellij_utils::data::HostTerminalThemeMode::Light) + .expect("flip ok"); + + let events = capture.drain_plugin_events(); + assert!( + events.iter().any(|e| matches!( + e, + Event::HostTerminalThemeChanged(zellij_utils::data::HostTerminalThemeMode::Light) + )), + "mode flip must re-emit the plugin event, got: {:?}", + events + ); +} + +#[test] +fn color_palette_mode_query_short_circuits_to_dark_reply() { + use crate::host_query::HostQuery; + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + screen.host_terminal_theme_mode = Some(zellij_utils::data::HostTerminalThemeMode::Dark); + + let token = screen.forward_host_query(PaneId::Terminal(13), HostQuery::ColorPaletteMode); + + assert_eq!( + token, 0, + "ColorPaletteMode must return the sentinel token; no real forward was queued" + ); + assert!( + capture.drain_forward_queries().is_empty(), + "must NOT forward to host — Zellij answers from cache" + ); + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1, "exactly one pty reply expected"); + assert_eq!(writes[0], (b"\x1b[?997;1n".to_vec(), 13)); + assert!( + screen.forward_in_flight_token.is_none(), + "slot must remain free; short-circuit does not occupy the queue" + ); +} + +#[test] +fn color_palette_mode_query_short_circuits_to_light_reply() { + use crate::host_query::HostQuery; + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + screen.host_terminal_theme_mode = Some(zellij_utils::data::HostTerminalThemeMode::Light); + + let _ = screen.forward_host_query(PaneId::Terminal(4), HostQuery::ColorPaletteMode); + + let writes = capture.drain_pty_writes(); + assert_eq!(writes.len(), 1); + assert_eq!(writes[0], (b"\x1b[?997;2n".to_vec(), 4)); +} + +#[test] +fn color_palette_mode_query_stays_silent_when_host_mode_unknown() { + use crate::host_query::HostQuery; + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + assert!( + screen.host_terminal_theme_mode.is_none(), + "precondition: no host mode learned yet" + ); + + let _ = screen.forward_host_query(PaneId::Terminal(1), HostQuery::ColorPaletteMode); + + assert!( + capture.drain_pty_writes().is_empty(), + "Contour spec defines only ;1 (dark) and ;2 (light); when Zellij has \ + not learned the host's mode it must stay silent rather than fabricate \ + a non-conformant reply (e.g. ;0)" + ); +} + +#[test] +fn color_palette_mode_query_skips_plugin_panes() { + use crate::host_query::HostQuery; + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_forward_capture(size); + screen.host_terminal_theme_mode = Some(zellij_utils::data::HostTerminalThemeMode::Dark); + + let _ = screen.forward_host_query(PaneId::Plugin(99), HostQuery::ColorPaletteMode); + + assert!( + capture.drain_pty_writes().is_empty(), + "plugin panes have no VT pty — they get Event::HostTerminalThemeChanged instead" + ); +} + +#[test] +fn host_theme_no_pty_writes_when_no_panes_subscribed() { + let size = Size { cols: 80, rows: 20 }; + let (mut screen, capture) = create_new_screen_with_theme_capture(size); + + screen + .update_host_terminal_theme_mode(zellij_utils::data::HostTerminalThemeMode::Dark) + .expect("ok"); + + let writes = capture.drain_pty_writes(); + assert!( + writes.is_empty(), + "no panes exist (or none subscribed via CSI ?2031h), so no DSR forward is queued, got: {:?}", + writes + ); +} diff --git a/zellij-utils/assets/prost/api.action.rs b/zellij-utils/assets/prost/api.action.rs index 267b900c..17bdc9c0 100644 --- a/zellij-utils/assets/prost/api.action.rs +++ b/zellij-utils/assets/prost/api.action.rs @@ -1117,6 +1117,9 @@ pub enum ActionName { ShowFloatingPanes = 98, HideFloatingPanes = 99, AreFloatingPanesVisible = 100, + SetDarkTheme = 101, + SetLightTheme = 102, + ToggleTheme = 103, } impl ActionName { /// String value of the enum field names used in the ProtoBuf definition. @@ -1223,6 +1226,9 @@ impl ActionName { ActionName::ShowFloatingPanes => "ShowFloatingPanes", ActionName::HideFloatingPanes => "HideFloatingPanes", ActionName::AreFloatingPanesVisible => "AreFloatingPanesVisible", + ActionName::SetDarkTheme => "SetDarkTheme", + ActionName::SetLightTheme => "SetLightTheme", + ActionName::ToggleTheme => "ToggleTheme", } } /// Creates an enum from field names used in the ProtoBuf definition. @@ -1326,6 +1332,9 @@ impl ActionName { "ShowFloatingPanes" => Some(Self::ShowFloatingPanes), "HideFloatingPanes" => Some(Self::HideFloatingPanes), "AreFloatingPanesVisible" => Some(Self::AreFloatingPanesVisible), + "SetDarkTheme" => Some(Self::SetDarkTheme), + "SetLightTheme" => Some(Self::SetLightTheme), + "ToggleTheme" => Some(Self::ToggleTheme), _ => None, } } diff --git a/zellij-utils/assets/prost/api.event.rs b/zellij-utils/assets/prost/api.event.rs index 2ec490b0..38976384 100644 --- a/zellij-utils/assets/prost/api.event.rs +++ b/zellij-utils/assets/prost/api.event.rs @@ -9,7 +9,7 @@ pub struct EventNameList { pub struct Event { #[prost(enumeration="EventType", tag="1")] pub name: i32, - #[prost(oneof="event::Payload", tags="2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39")] + #[prost(oneof="event::Payload", tags="2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40")] pub payload: ::core::option::Option<event::Payload>, } /// Nested message and enum types in `Event`. @@ -93,10 +93,18 @@ pub mod event { InitialKeybindsPayload(super::InitialKeybindsPayload), #[prost(message, tag="39")] CommandChangedPayload(super::CommandChangedPayload), + #[prost(message, tag="40")] + HostTerminalThemeChangedPayload(super::HostTerminalThemeChangedPayload), } } #[allow(clippy::derive_partial_eq_without_eq)] #[derive(Clone, PartialEq, ::prost::Message)] +pub struct HostTerminalThemeChangedPayload { + #[prost(enumeration="HostTerminalThemeIndication", tag="1")] + pub mode: i32, +} +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, PartialEq, ::prost::Message)] pub struct CwdChangedPayload { #[prost(message, optional, tag="1")] pub pane_id: ::core::option::Option<PaneId>, @@ -830,6 +838,7 @@ pub enum EventType { PaneRenderReportWithAnsi = 43, InitialKeybinds = 44, CommandChanged = 45, + HostTerminalThemeChanged = 46, } impl EventType { /// String value of the enum field names used in the ProtoBuf definition. @@ -883,6 +892,7 @@ impl EventType { EventType::PaneRenderReportWithAnsi => "PaneRenderReportWithAnsi", EventType::InitialKeybinds => "InitialKeybinds", EventType::CommandChanged => "CommandChanged", + EventType::HostTerminalThemeChanged => "HostTerminalThemeChanged", } } /// Creates an enum from field names used in the ProtoBuf definition. @@ -933,6 +943,33 @@ impl EventType { "PaneRenderReportWithAnsi" => Some(Self::PaneRenderReportWithAnsi), "InitialKeybinds" => Some(Self::InitialKeybinds), "CommandChanged" => Some(Self::CommandChanged), + "HostTerminalThemeChanged" => Some(Self::HostTerminalThemeChanged), + _ => None, + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] +pub enum HostTerminalThemeIndication { + Dark = 0, + Light = 1, +} +impl HostTerminalThemeIndication { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + HostTerminalThemeIndication::Dark => "Dark", + HostTerminalThemeIndication::Light => "Light", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option<Self> { + match value { + "Dark" => Some(Self::Dark), + "Light" => Some(Self::Light), _ => None, } } diff --git a/zellij-utils/assets/prost_ipc/client_server_contract.rs b/zellij-utils/assets/prost_ipc/client_server_contract.rs index 5ae8460b..142609f7 100644 --- a/zellij-utils/assets/prost_ipc/client_server_contract.rs +++ b/zellij-utils/assets/prost_ipc/client_server_contract.rs @@ -119,7 +119,7 @@ pub struct RgbColor { #[allow(clippy::derive_partial_eq_without_eq)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct Action { - #[prost(oneof="action::ActionType", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136")] + #[prost(oneof="action::ActionType", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139")] pub action_type: ::core::option::Option<action::ActionType>, } /// Nested message and enum types in `Action`. @@ -401,6 +401,12 @@ pub mod action { FocusPaneByPaneId(super::FocusPaneByPaneIdAction), #[prost(message, tag="136")] AreFloatingPanesVisible(super::AreFloatingPanesVisibleAction), + #[prost(message, tag="137")] + SetDarkTheme(super::SetDarkThemeAction), + #[prost(message, tag="138")] + SetLightTheme(super::SetLightThemeAction), + #[prost(message, tag="139")] + ToggleTheme(super::ToggleThemeAction), } } // Action message definitions (all 92 variants) @@ -552,6 +558,18 @@ pub struct DetachAction { } #[allow(clippy::derive_partial_eq_without_eq)] #[derive(Clone, PartialEq, ::prost::Message)] +pub struct SetDarkThemeAction { +} +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct SetLightThemeAction { +} +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct ToggleThemeAction { +} +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, PartialEq, ::prost::Message)] pub struct CopyAction { } #[allow(clippy::derive_partial_eq_without_eq)] @@ -1927,6 +1945,10 @@ pub struct Options { pub focus_follows_mouse: ::core::option::Option<bool>, #[prost(bool, optional, tag="45")] pub mouse_click_through: ::core::option::Option<bool>, + #[prost(string, optional, tag="46")] + pub theme_dark: ::core::option::Option<::prost::alloc::string::String>, + #[prost(string, optional, tag="47")] + pub theme_light: ::core::option::Option<::prost::alloc::string::String>, } /// Pane-targeting action messages #[allow(clippy::derive_partial_eq_without_eq)] @@ -2857,7 +2879,7 @@ impl WebSharing { #[allow(clippy::derive_partial_eq_without_eq)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct ClientToServerMsg { - #[prost(oneof="client_to_server_msg::Message", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18")] + #[prost(oneof="client_to_server_msg::Message", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20")] pub message: ::core::option::Option<client_to_server_msg::Message>, } /// Nested message and enum types in `ClientToServerMsg`. @@ -2901,6 +2923,10 @@ pub mod client_to_server_msg { SubscribeToPaneRenders(super::SubscribeToPaneRendersMsg), #[prost(message, tag="18")] DesktopNotificationResponse(super::DesktopNotificationResponseMsg), + #[prost(message, tag="19")] + ForwardedReplyFromHost(super::ForwardedReplyFromHostMsg), + #[prost(message, tag="20")] + HostTerminalThemeChanged(super::HostTerminalThemeChangedMsg), } } #[allow(clippy::derive_partial_eq_without_eq)] @@ -3034,8 +3060,48 @@ pub struct DesktopNotificationResponseMsg { } #[allow(clippy::derive_partial_eq_without_eq)] #[derive(Clone, PartialEq, ::prost::Message)] +pub struct ForwardedReplyFromHostMsg { + #[prost(uint32, tag="1")] + pub token: u32, + #[prost(bytes="vec", tag="2")] + pub reply_bytes: ::prost::alloc::vec::Vec<u8>, +} +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct HostTerminalThemeChangedMsg { + #[prost(enumeration="HostTerminalThemeIndication", tag="1")] + pub mode: i32, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] +pub enum HostTerminalThemeIndication { + Dark = 0, + Light = 1, +} +impl HostTerminalThemeIndication { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + HostTerminalThemeIndication::Dark => "HOST_TERMINAL_THEME_INDICATION_DARK", + HostTerminalThemeIndication::Light => "HOST_TERMINAL_THEME_INDICATION_LIGHT", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option<Self> { + match value { + "HOST_TERMINAL_THEME_INDICATION_DARK" => Some(Self::Dark), + "HOST_TERMINAL_THEME_INDICATION_LIGHT" => Some(Self::Light), + _ => None, + } + } +} +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, PartialEq, ::prost::Message)] pub struct ServerToClientMsg { - #[prost(oneof="server_to_client_msg::Message", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15")] + #[prost(oneof="server_to_client_msg::Message", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16")] pub message: ::core::option::Option<server_to_client_msg::Message>, } /// Nested message and enum types in `ServerToClientMsg`. @@ -3073,6 +3139,8 @@ pub mod server_to_client_msg { PaneRenderUpdate(super::PaneRenderUpdateMsg), #[prost(message, tag="15")] SubscribedPaneClosed(super::SubscribedPaneClosedMsg), + #[prost(message, tag="16")] + ForwardQueryToHost(super::ForwardQueryToHostMsg), } } #[allow(clippy::derive_partial_eq_without_eq)] @@ -3172,3 +3240,11 @@ pub struct SubscribedPaneClosedMsg { #[prost(message, optional, tag="1")] pub pane_id: ::core::option::Option<PaneId>, } +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct ForwardQueryToHostMsg { + #[prost(uint32, tag="1")] + pub token: u32, + #[prost(bytes="vec", tag="2")] + pub query_bytes: ::prost::alloc::vec::Vec<u8>, +} diff --git a/zellij-utils/src/cli.rs b/zellij-utils/src/cli.rs index f02ace98..5b169170 100644 --- a/zellij-utils/src/cli.rs +++ b/zellij-utils/src/cli.rs @@ -1621,6 +1621,12 @@ tail -f /tmp/my-live-logfile | zellij action pipe --name logs --plugin https://e }, /// Detach from the current session Detach, + /// Switch the theme to dark (uses configured `theme_dark`). + SetDarkTheme, + /// Switch the theme to light (uses configured `theme_light`). + SetLightTheme, + /// Toggle between dark and light themes (used configured `theme_dark` and `theme_light`) + ToggleTheme, /// Switch to a different session SwitchSession { /// Name of the session to switch to diff --git a/zellij-utils/src/client_server_contract/client_to_server.proto b/zellij-utils/src/client_server_contract/client_to_server.proto index 2e783f3d..834feccd 100644 --- a/zellij-utils/src/client_server_contract/client_to_server.proto +++ b/zellij-utils/src/client_server_contract/client_to_server.proto @@ -23,6 +23,8 @@ message ClientToServerMsg { AttachWatcherClientMsg attach_watcher_client = 16; SubscribeToPaneRendersMsg subscribe_to_pane_renders = 17; DesktopNotificationResponseMsg desktop_notification_response = 18; + ForwardedReplyFromHostMsg forwarded_reply_from_host = 19; + HostTerminalThemeChangedMsg host_terminal_theme_changed = 20; } } @@ -109,3 +111,17 @@ message SubscribeToPaneRendersMsg { message DesktopNotificationResponseMsg { bytes raw_bytes = 1; } + +message ForwardedReplyFromHostMsg { + uint32 token = 1; + bytes reply_bytes = 2; +} + +message HostTerminalThemeChangedMsg { + HostTerminalThemeIndication mode = 1; +} + +enum HostTerminalThemeIndication { + HOST_TERMINAL_THEME_INDICATION_DARK = 0; + HOST_TERMINAL_THEME_INDICATION_LIGHT = 1; +} diff --git a/zellij-utils/src/client_server_contract/common_types.proto b/zellij-utils/src/client_server_contract/common_types.proto index e610eb2a..b592eb8d 100644 --- a/zellij-utils/src/client_server_contract/common_types.proto +++ b/zellij-utils/src/client_server_contract/common_types.proto @@ -274,6 +274,9 @@ message Action { MoveTabByTabIdAction move_tab_by_tab_id = 134; FocusPaneByPaneIdAction focus_pane_by_pane_id = 135; AreFloatingPanesVisibleAction are_floating_panes_visible = 136; + SetDarkThemeAction set_dark_theme = 137; + SetLightThemeAction set_light_theme = 138; + ToggleThemeAction toggle_theme = 139; } } @@ -322,6 +325,9 @@ message CloseTabAction {} message ToggleTabAction {} message UndoRenameTabAction {} message DetachAction {} +message SetDarkThemeAction {} +message SetLightThemeAction {} +message ToggleThemeAction {} message CopyAction {} message ConfirmAction {} message DenyAction {} @@ -1166,6 +1172,8 @@ message Options { optional bool visual_bell = 43; optional bool focus_follows_mouse = 44; optional bool mouse_click_through = 45; + optional string theme_dark = 46; + optional string theme_light = 47; } enum OnForceClose { diff --git a/zellij-utils/src/client_server_contract/server_to_client.proto b/zellij-utils/src/client_server_contract/server_to_client.proto index e0b8b529..b2fc3bd6 100644 --- a/zellij-utils/src/client_server_contract/server_to_client.proto +++ b/zellij-utils/src/client_server_contract/server_to_client.proto @@ -20,6 +20,7 @@ message ServerToClientMsg { ConfigFileUpdatedMsg config_file_updated = 13; PaneRenderUpdateMsg pane_render_update = 14; SubscribedPaneClosedMsg subscribed_pane_closed = 15; + ForwardQueryToHostMsg forward_query_to_host = 16; } } @@ -88,3 +89,8 @@ message PaneRenderUpdateMsg { message SubscribedPaneClosedMsg { PaneId pane_id = 1; } + +message ForwardQueryToHostMsg { + uint32 token = 1; + bytes query_bytes = 2; +} diff --git a/zellij-utils/src/consts.rs b/zellij-utils/src/consts.rs index 32bb8153..0e8b5112 100644 --- a/zellij-utils/src/consts.rs +++ b/zellij-utils/src/consts.rs @@ -106,8 +106,6 @@ lazy_static! { pub static ref ZELLIJ_SESSION_INFO_CACHE_DIR: PathBuf = ZELLIJ_CACHE_DIR .join(CLIENT_SERVER_CONTRACT_DIR.clone()) .join("session_info"); - pub static ref ZELLIJ_STDIN_CACHE_FILE: PathBuf = - ZELLIJ_CACHE_DIR.join(VERSION).join("stdin_cache"); pub static ref ZELLIJ_PLUGIN_ARTIFACT_DIR: PathBuf = ZELLIJ_CACHE_DIR.join(VERSION); pub static ref ZELLIJ_SEEN_RELEASE_NOTES_CACHE_FILE: PathBuf = ZELLIJ_CACHE_DIR.join(VERSION).join("seen_release_notes"); diff --git a/zellij-utils/src/data.rs b/zellij-utils/src/data.rs index cfcc3692..7b8ebf3f 100644 --- a/zellij-utils/src/data.rs +++ b/zellij-utils/src/data.rs @@ -1025,6 +1025,14 @@ pub enum Event { /// Plugins that subscribe to this event signal they cache keybindings /// and can handle lightweight ModeUpdate events without keybindings. InitialKeybinds(KeybindsVec), + /// The host terminal indicated its color palette theme mode (CSI 2031 / DSR 997). + HostTerminalThemeChanged(HostTerminalThemeMode), +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum HostTerminalThemeMode { + Dark, + Light, } #[derive(Debug, Clone, PartialEq, Eq, EnumDiscriminants, Display, Serialize, Deserialize)] diff --git a/zellij-utils/src/errors.rs b/zellij-utils/src/errors.rs index 5bb8e955..484b4dfb 100644 --- a/zellij-utils/src/errors.rs +++ b/zellij-utils/src/errors.rs @@ -310,6 +310,12 @@ pub enum ScreenContext { TerminalBackgroundColor, TerminalForegroundColor, TerminalColorRegisters, + ForwardHostQuery, + ForwardedReplyFromHost, + HostTerminalThemeChanged, + SetDarkTheme, + SetLightTheme, + ToggleTheme, ChangeMode, ChangeModeForAllClients, LeftClick, @@ -553,8 +559,6 @@ pub enum ClientContext { Log, LogError, OwnClientId, - StartedParsingStdinQuery, - DoneParsingStdinQuery, SwitchSession, SetSynchronisedOutput, UnblockCliPipeInput, @@ -564,6 +568,7 @@ pub enum ClientContext { StartWebServer, RenamedSession, ConfigFileUpdated, + ForwardQueryToHost, } /// Stack call representations corresponding to the different types of [`ServerInstruction`]s. @@ -599,6 +604,7 @@ pub enum ServerContext { FailedToStartWebServer, SendWebClientsForbidden, ClearMouseHelpText, + ForwardQueryToHost, } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] diff --git a/zellij-utils/src/input/actions.rs b/zellij-utils/src/input/actions.rs index ab4c9ae3..7f6fabfe 100644 --- a/zellij-utils/src/input/actions.rs +++ b/zellij-utils/src/input/actions.rs @@ -353,6 +353,12 @@ pub enum Action { }, /// Detach session and exit Detach, + /// Switch the host-terminal theme mode to dark (uses configured `theme_dark`). + SetDarkTheme, + /// Switch the host-terminal theme mode to light (uses configured `theme_light`). + SetLightTheme, + /// Toggle between dark and light host-terminal theme modes. + ToggleTheme, /// Switch to a different session SwitchSession { name: String, @@ -2052,6 +2058,9 @@ impl Action { } }, CliAction::Detach => Ok(vec![Action::Detach]), + CliAction::SetDarkTheme => Ok(vec![Action::SetDarkTheme]), + CliAction::SetLightTheme => Ok(vec![Action::SetLightTheme]), + CliAction::ToggleTheme => Ok(vec![Action::ToggleTheme]), CliAction::SwitchSession { name, tab_position, @@ -3053,6 +3062,42 @@ mod tests { assert!(matches!(actions[0], Action::CloseTab)); } + #[test] + fn test_set_dark_theme_cli_to_action() { + let result = Action::actions_from_cli( + CliAction::SetDarkTheme, + Box::new(|| PathBuf::from("/tmp")), + None, + ); + let actions = result.expect("SetDarkTheme conversion should succeed"); + assert_eq!(actions.len(), 1); + assert!(matches!(actions[0], Action::SetDarkTheme)); + } + + #[test] + fn test_set_light_theme_cli_to_action() { + let result = Action::actions_from_cli( + CliAction::SetLightTheme, + Box::new(|| PathBuf::from("/tmp")), + None, + ); + let actions = result.expect("SetLightTheme conversion should succeed"); + assert_eq!(actions.len(), 1); + assert!(matches!(actions[0], Action::SetLightTheme)); + } + + #[test] + fn test_toggle_theme_cli_to_action() { + let result = Action::actions_from_cli( + CliAction::ToggleTheme, + Box::new(|| PathBuf::from("/tmp")), + None, + ); + let actions = result.expect("ToggleTheme conversion should succeed"); + assert_eq!(actions.len(), 1); + assert!(matches!(actions[0], Action::ToggleTheme)); + } + // 21. RenameTab #[test] fn test_rename_tab_with_tab_id() { diff --git a/zellij-utils/src/input/options.rs b/zellij-utils/src/input/options.rs index bb90b7b1..854ef271 100644 --- a/zellij-utils/src/input/options.rs +++ b/zellij-utils/src/input/options.rs @@ -48,6 +48,16 @@ pub struct Options { /// Set the default theme #[clap(long, value_parser)] pub theme: Option<String>, + /// Theme name to apply when the host terminal reports a dark color palette + /// (CSI 2031 / DSR 997). Requires `theme_light` to also be set; if either + /// is missing the static `theme` remains authoritative. + #[clap(long, value_parser)] + pub theme_dark: Option<String>, + /// Theme name to apply when the host terminal reports a light color palette + /// (CSI 2031 / DSR 997). Requires `theme_dark` to also be set; if either + /// is missing the static `theme` remains authoritative. + #[clap(long, value_parser)] + pub theme_light: Option<String>, /// Set the default mode #[clap(long, arg_enum, hide_possible_values = true, value_parser)] pub default_mode: Option<InputMode>, @@ -319,6 +329,8 @@ impl Options { let layout_dir = other.layout_dir.or_else(|| self.layout_dir.clone()); let theme_dir = other.theme_dir.or_else(|| self.theme_dir.clone()); let theme = other.theme.or_else(|| self.theme.clone()); + let theme_dark = other.theme_dark.or_else(|| self.theme_dark.clone()); + let theme_light = other.theme_light.or_else(|| self.theme_light.clone()); let on_force_close = other.on_force_close.or(self.on_force_close); let scroll_buffer_size = other.scroll_buffer_size.or(self.scroll_buffer_size); let copy_command = other.copy_command.or_else(|| self.copy_command.clone()); @@ -376,6 +388,8 @@ impl Options { Options { simplified_ui, theme, + theme_dark, + theme_light, default_mode, default_shell, default_cwd, @@ -454,6 +468,8 @@ impl Options { let layout_dir = other.layout_dir.or_else(|| self.layout_dir.clone()); let theme_dir = other.theme_dir.or_else(|| self.theme_dir.clone()); let theme = other.theme.or_else(|| self.theme.clone()); + let theme_dark = other.theme_dark.or_else(|| self.theme_dark.clone()); + let theme_light = other.theme_light.or_else(|| self.theme_light.clone()); let on_force_close = other.on_force_close.or(self.on_force_close); let scroll_buffer_size = other.scroll_buffer_size.or(self.scroll_buffer_size); let copy_command = other.copy_command.or_else(|| self.copy_command.clone()); @@ -507,6 +523,8 @@ impl Options { Options { simplified_ui, theme, + theme_dark, + theme_light, default_mode, default_shell, default_cwd, diff --git a/zellij-utils/src/ipc.rs b/zellij-utils/src/ipc.rs index 854ef0b9..5f54478d 100644 --- a/zellij-utils/src/ipc.rs +++ b/zellij-utils/src/ipc.rs @@ -1,6 +1,6 @@ //! IPC stuff for starting to split things into a client and server model. use crate::{ - data::{ClientId, ConnectToSession, KeyWithModifier, PaneId, Style}, + data::{ClientId, ConnectToSession, HostTerminalThemeMode, KeyWithModifier, PaneId, Style}, errors::{prelude::*, ErrorContext}, input::{actions::Action, cli_assets::CliAssets}, pane_size::{Size, SizeInPixels}, @@ -156,6 +156,21 @@ pub enum ClientToServerMsg { DesktopNotificationResponse { raw_bytes: Vec<u8>, }, + /// Raw reply bytes observed by the client inside a forwarding window + /// closed by the Primary-DA barrier. The server routes these bytes + /// verbatim to the pane whose app issued the whitelisted query + /// (tracked on the server by `token`). + ForwardedReplyFromHost { + token: u32, + reply_bytes: Vec<u8>, + }, + /// The host terminal reported a color-palette theme mode (DSR 997 reply + /// to `CSI ? 996 n`, or unsolicited notification while `CSI ? 2031 h` + /// is enabled). The server propagates this to the active configured + /// theme and to subscribed plugins/panes. + HostTerminalThemeChanged { + mode: HostTerminalThemeMode, + }, } // Types of messages sent from the server to the client @@ -200,6 +215,14 @@ pub enum ServerToClientMsg { SubscribedPaneClosed { pane_id: PaneId, }, + /// Instruct the client to write `query_bytes` followed by the + /// Primary-DA barrier to stdout, open a forwarding window keyed by + /// `token`, and reply with a `ForwardedReplyFromHost` once the + /// barrier closes or the window times out. + ForwardQueryToHost { + token: u32, + query_bytes: Vec<u8>, + }, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] diff --git a/zellij-utils/src/ipc/protobuf_conversion.rs b/zellij-utils/src/ipc/protobuf_conversion.rs index 656ef54c..8025d66f 100644 --- a/zellij-utils/src/ipc/protobuf_conversion.rs +++ b/zellij-utils/src/ipc/protobuf_conversion.rs @@ -5,15 +5,18 @@ use crate::{ ClientToServerMsg as ProtoClientToServerMsg, ColorRegistersMsg, ConfigFileUpdatedMsg, ConnStatusMsg, ConnectedMsg, DesktopNotificationResponseMsg, DetachSessionMsg, ExitMsg, ExitReason as ProtoExitReason, FailedToStartWebServerMsg, FirstClientConnectedMsg, - ForegroundColorMsg, InputMode as ProtoInputMode, KeyMsg, KillSessionMsg, - LayoutMetadata as ProtoLayoutMetadata, LogErrorMsg, LogMsg, - PaneMetadata as ProtoPaneMetadata, PaneRenderUpdateMsg, QueryTerminalSizeMsg, - RenamedSessionMsg, RenderMsg, ServerToClientMsg as ProtoServerToClientMsg, - StartWebServerMsg, SubscribeToPaneRendersMsg, SubscribedPaneClosedMsg, SwitchSessionMsg, - TabMetadata as ProtoTabMetadata, TerminalPixelDimensionsMsg, TerminalResizeMsg, - UnblockCliPipeInputMsg, UnblockInputThreadMsg, WebServerStartedMsg, + ForegroundColorMsg, ForwardQueryToHostMsg, ForwardedReplyFromHostMsg, + HostTerminalThemeChangedMsg, + HostTerminalThemeIndication as ProtoHostTerminalThemeIndication, + InputMode as ProtoInputMode, KeyMsg, KillSessionMsg, LayoutMetadata as ProtoLayoutMetadata, + LogErrorMsg, LogMsg, PaneMetadata as ProtoPaneMetadata, PaneRenderUpdateMsg, + QueryTerminalSizeMsg, RenamedSessionMsg, RenderMsg, + ServerToClientMsg as ProtoServerToClientMsg, StartWebServerMsg, SubscribeToPaneRendersMsg, + SubscribedPaneClosedMsg, SwitchSessionMsg, TabMetadata as ProtoTabMetadata, + TerminalPixelDimensionsMsg, TerminalResizeMsg, UnblockCliPipeInputMsg, + UnblockInputThreadMsg, WebServerStartedMsg, }, - data::{InputMode, PaneId}, + data::{HostTerminalThemeMode, InputMode, PaneId}, errors::prelude::*, ipc::{ ClientToServerMsg, ColorRegister, ExitReason, PaneReference, PixelDimensions, @@ -129,6 +132,20 @@ impl From<ClientToServerMsg> for ProtoClientToServerMsg { DesktopNotificationResponseMsg { raw_bytes }, ) }, + ClientToServerMsg::ForwardedReplyFromHost { token, reply_bytes } => { + client_to_server_msg::Message::ForwardedReplyFromHost(ForwardedReplyFromHostMsg { + token, + reply_bytes, + }) + }, + ClientToServerMsg::HostTerminalThemeChanged { mode } => { + let proto_mode: ProtoHostTerminalThemeIndication = mode.into(); + client_to_server_msg::Message::HostTerminalThemeChanged( + HostTerminalThemeChangedMsg { + mode: proto_mode as i32, + }, + ) + }, }; ProtoClientToServerMsg { @@ -257,6 +274,19 @@ impl TryFrom<ProtoClientToServerMsg> for ClientToServerMsg { raw_bytes: msg.raw_bytes, }) }, + Some(client_to_server_msg::Message::ForwardedReplyFromHost(msg)) => { + Ok(ClientToServerMsg::ForwardedReplyFromHost { + token: msg.token, + reply_bytes: msg.reply_bytes, + }) + }, + Some(client_to_server_msg::Message::HostTerminalThemeChanged(msg)) => { + let proto_mode = ProtoHostTerminalThemeIndication::from_i32(msg.mode) + .ok_or_else(|| anyhow!("Unknown HostTerminalThemeIndication: {}", msg.mode))?; + Ok(ClientToServerMsg::HostTerminalThemeChanged { + mode: proto_mode.into(), + }) + }, None => Err(anyhow!("Empty ClientToServerMsg message")), } } @@ -336,6 +366,12 @@ impl From<ServerToClientMsg> for ProtoServerToClientMsg { pane_id: Some(pane_id.into()), }) }, + ServerToClientMsg::ForwardQueryToHost { token, query_bytes } => { + server_to_client_msg::Message::ForwardQueryToHost(ForwardQueryToHostMsg { + token, + query_bytes, + }) + }, }; ProtoServerToClientMsg { @@ -442,6 +478,12 @@ impl TryFrom<ProtoServerToClientMsg> for ServerToClientMsg { .try_into()?; Ok(ServerToClientMsg::SubscribedPaneClosed { pane_id }) }, + Some(server_to_client_msg::Message::ForwardQueryToHost(msg)) => { + Ok(ServerToClientMsg::ForwardQueryToHost { + token: msg.token, + query_bytes: msg.query_bytes, + }) + }, None => Err(anyhow!("Empty ServerToClientMsg message")), } } @@ -625,6 +667,8 @@ impl From<crate::input::options::Options> Self { simplified_ui: options.simplified_ui, theme: options.theme, + theme_dark: options.theme_dark, + theme_light: options.theme_light, default_mode: options.default_mode.map(|m| input_mode_to_proto_i32(m)), default_shell: options .default_shell @@ -707,6 +751,8 @@ impl TryFrom<crate::client_server_contract::client_server_contract::Options> Ok(Self { simplified_ui: options.simplified_ui, theme: options.theme, + theme_dark: options.theme_dark, + theme_light: options.theme_light, default_mode: options .default_mode .map(|m| proto_i32_to_input_mode(m)) @@ -897,6 +943,8 @@ impl From<crate::input::actions::Action> SearchAction, SearchInputAction, SearchToggleOptionAction, + SetDarkThemeAction, + SetLightThemeAction, SetPaneBorderlessAction, SetPaneColorAction, ShowFloatingPanesAction, @@ -924,6 +972,7 @@ impl From<crate::input::actions::Action> TogglePanePinnedAction, TogglePanePinnedByPaneIdAction, ToggleTabAction, + ToggleThemeAction, UndoRenamePaneAction, UndoRenamePaneByPaneIdAction, UndoRenameTabAction, @@ -1278,6 +1327,15 @@ impl From<crate::input::actions::Action> near_current_pane, }), crate::input::actions::Action::Detach => ActionType::Detach(DetachAction {}), + crate::input::actions::Action::SetDarkTheme => { + ActionType::SetDarkTheme(SetDarkThemeAction {}) + }, + crate::input::actions::Action::SetLightTheme => { + ActionType::SetLightTheme(SetLightThemeAction {}) + }, + crate::input::actions::Action::ToggleTheme => { + ActionType::ToggleTheme(ToggleThemeAction {}) + }, crate::input::actions::Action::SwitchSession { name, tab_position, @@ -2139,6 +2197,9 @@ impl TryFrom<crate::client_server_contract::client_server_contract::Action> near_current_pane: run_action.near_current_pane, }), ActionType::Detach(_) => Ok(crate::input::actions::Action::Detach), + ActionType::SetDarkTheme(_) => Ok(crate::input::actions::Action::SetDarkTheme), + ActionType::SetLightTheme(_) => Ok(crate::input::actions::Action::SetLightTheme), + ActionType::ToggleTheme(_) => Ok(crate::input::actions::Action::ToggleTheme), ActionType::SwitchSession(switch_session_action) => { Ok(crate::input::actions::Action::SwitchSession { name: switch_session_action.name.clone(), @@ -2952,6 +3013,24 @@ impl TryFrom<ProtoExitReason> for ExitReason { } } +impl From<HostTerminalThemeMode> for ProtoHostTerminalThemeIndication { + fn from(mode: HostTerminalThemeMode) -> Self { + match mode { + HostTerminalThemeMode::Dark => ProtoHostTerminalThemeIndication::Dark, + HostTerminalThemeMode::Light => ProtoHostTerminalThemeIndication::Light, + } + } +} + +impl From<ProtoHostTerminalThemeIndication> for HostTerminalThemeMode { + fn from(mode: ProtoHostTerminalThemeIndication) -> Self { + match mode { + ProtoHostTerminalThemeIndication::Dark => HostTerminalThemeMode::Dark, + ProtoHostTerminalThemeIndication::Light => HostTerminalThemeMode::Light, + } + } +} + // InputMode conversion helper functions fn input_mode_to_proto_i32(mode: InputMode) -> i32 { match mode { diff --git a/zellij-utils/src/ipc/tests/roundtrip_tests.rs b/zellij-utils/src/ipc/tests/roundtrip_tests.rs index 23b8c4ac..4847b679 100644 --- a/zellij-utils/src/ipc/tests/roundtrip_tests.rs +++ b/zellij-utils/src/ipc/tests/roundtrip_tests.rs @@ -1,8 +1,8 @@ use super::test_framework::*; use crate::data::{ - BareKey, CommandOrPlugin, ConnectToSession, Direction, FloatingPaneCoordinates, InputMode, - KeyModifier, KeyWithModifier, LayoutInfo, LayoutMetadata, NewPanePlacement, OriginatingPlugin, - PaneId, PluginTag, Resize, WebSharing, + BareKey, CommandOrPlugin, ConnectToSession, Direction, FloatingPaneCoordinates, + HostTerminalThemeMode, InputMode, KeyModifier, KeyWithModifier, LayoutInfo, LayoutMetadata, + NewPanePlacement, OriginatingPlugin, PaneId, PluginTag, Resize, WebSharing, }; use crate::input::actions::{Action, SearchDirection, SearchOption}; use crate::input::cli_assets::CliAssets; @@ -433,6 +433,8 @@ fn test_client_messages() { configuration_options: Some(Options { simplified_ui: Some(true), theme: Some("theme".to_owned()), + theme_dark: Some("theme_dark".to_owned()), + theme_light: Some("theme_light".to_owned()), default_mode: Some(InputMode::Normal), default_shell: Some(PathBuf::from("default_shell")), default_cwd: Some(PathBuf::from("default_cwd")), @@ -3538,6 +3540,35 @@ fn test_client_messages() { client_id: Some(100), is_cli_client: true, }); + test_client_roundtrip!(ClientToServerMsg::ForwardedReplyFromHost { + token: 0, + reply_bytes: vec![], + }); + test_client_roundtrip!(ClientToServerMsg::ForwardedReplyFromHost { + token: 42, + reply_bytes: b"\x1b]11;rgb:ffff/ffff/ffff\x1b\\".to_vec(), + }); + test_client_roundtrip!(ClientToServerMsg::ForwardedReplyFromHost { + token: u32::MAX, + reply_bytes: (0u8..=255u8).collect(), + }); + // Guard against protobuf string-vs-bytes encoding regressions: a + // payload mixing NULs, ESC, and CSI framing must round-trip + // byte-for-byte or the pane will receive corrupt terminal data. + test_client_roundtrip!(ClientToServerMsg::ForwardedReplyFromHost { + token: 17, + reply_bytes: vec![ + 0x00, 0x1b, b'[', b'?', b'6', b'2', b';', b'1', b';', b'6', b'c', 0x00, 0x1b, b']', + b'1', b'1', b';', b'r', b'g', b'b', b':', b'f', b'f', b'f', b'f', b'/', b'f', b'f', + b'f', b'f', b'/', b'f', b'f', b'f', b'f', 0x07, 0xff, 0x00, + ], + }); + test_client_roundtrip!(ClientToServerMsg::HostTerminalThemeChanged { + mode: HostTerminalThemeMode::Dark, + }); + test_client_roundtrip!(ClientToServerMsg::HostTerminalThemeChanged { + mode: HostTerminalThemeMode::Light, + }); } fn test_server_messages() { @@ -3673,6 +3704,18 @@ fn test_server_messages() { test_server_roundtrip!(ServerToClientMsg::SubscribedPaneClosed { pane_id: PaneId::Plugin(3), }); + test_server_roundtrip!(ServerToClientMsg::ForwardQueryToHost { + token: 0, + query_bytes: vec![], + }); + test_server_roundtrip!(ServerToClientMsg::ForwardQueryToHost { + token: 7, + query_bytes: b"\x1b[14t".to_vec(), + }); + test_server_roundtrip!(ServerToClientMsg::ForwardQueryToHost { + token: u32::MAX, + query_bytes: (0u8..=255u8).collect(), + }); } #[test] diff --git a/zellij-utils/src/kdl/mod.rs b/zellij-utils/src/kdl/mod.rs index 2b009e1a..c7cc5366 100644 --- a/zellij-utils/src/kdl/mod.rs +++ b/zellij-utils/src/kdl/mod.rs @@ -74,6 +74,9 @@ macro_rules! parse_kdl_action_arguments { "ToggleTab" => Ok(Action::ToggleTab), "UndoRenameTab" => Ok(Action::UndoRenameTab), "Detach" => Ok(Action::Detach), + "SetDarkTheme" => Ok(Action::SetDarkTheme), + "SetLightTheme" => Ok(Action::SetLightTheme), + "ToggleTheme" => Ok(Action::ToggleTheme), "Copy" => Ok(Action::Copy), "Confirm" => Ok(Action::Confirm), "Deny" => Ok(Action::Deny), @@ -2674,6 +2677,10 @@ impl Options { kdl_property_first_arg_as_bool_or_error!(kdl_options, "auto_layout").map(|(v, _)| v); let theme = kdl_property_first_arg_as_string_or_error!(kdl_options, "theme") .map(|(theme, _entry)| theme.to_string()); + let theme_dark = kdl_property_first_arg_as_string_or_error!(kdl_options, "theme_dark") + .map(|(theme, _entry)| theme.to_string()); + let theme_light = kdl_property_first_arg_as_string_or_error!(kdl_options, "theme_light") + .map(|(theme, _entry)| theme.to_string()); let default_mode = match kdl_property_first_arg_as_string_or_error!(kdl_options, "default_mode") { Some((string, entry)) => Some(InputMode::from_str(string).map_err(|_| { @@ -2821,6 +2828,8 @@ impl Options { Ok(Options { simplified_ui, theme, + theme_dark, + theme_light, default_mode, default_shell, default_cwd, @@ -2958,6 +2967,62 @@ impl Options { None } } + fn theme_dark_to_kdl(&self, add_comments: bool) -> Option<KdlNode> { + let comment_text = format!( + "{}\n{}\n{}\n{}", + " ", + "// Theme to use when the host terminal reports a dark color palette.", + "// Requires `theme_light` to also be set; otherwise `theme` is used.", + "// ", + ); + + let create_node = |node_value: &str| -> KdlNode { + let mut node = KdlNode::new("theme_dark"); + node.push(node_value.to_owned()); + node + }; + if let Some(theme) = &self.theme_dark { + let mut node = create_node(theme); + if add_comments { + node.set_leading(format!("{}\n", comment_text)); + } + Some(node) + } else if add_comments { + let mut node = create_node("dracula"); + node.set_leading(format!("{}\n// ", comment_text)); + Some(node) + } else { + None + } + } + fn theme_light_to_kdl(&self, add_comments: bool) -> Option<KdlNode> { + let comment_text = format!( + "{}\n{}\n{}\n{}", + " ", + "// Theme to use when the host terminal reports a light color palette.", + "// Requires `theme_dark` to also be set; otherwise `theme` is used.", + "// ", + ); + + let create_node = |node_value: &str| -> KdlNode { + let mut node = KdlNode::new("theme_light"); + node.push(node_value.to_owned()); + node + }; + if let Some(theme) = &self.theme_light { + let mut node = create_node(theme); + if add_comments { + node.set_leading(format!("{}\n", comment_text)); + } + Some(node) + } else if add_comments { + let mut node = create_node("solarized-light"); + node.set_leading(format!("{}\n// ", comment_text)); + Some(node) + } else { + None + } + } fn default_mode_to_kdl(&self, add_comments: bool) -> Option<KdlNode> { let comment_text = format!( "{}\n{}\n{}\n{}", @@ -4190,6 +4255,12 @@ impl Options { if let Some(theme_node) = self.theme_to_kdl(add_comments) { nodes.push(theme_node); } + if let Some(theme_dark_node) = self.theme_dark_to_kdl(add_comments) { + nodes.push(theme_dark_node); + } + if let Some(theme_light_node) = self.theme_light_to_kdl(add_comments) { + nodes.push(theme_light_node); + } if let Some(default_mode) = self.default_mode_to_kdl(add_comments) { nodes.push(default_mode); } diff --git a/zellij-utils/src/kdl/snapshots/zellij_utils__kdl__bare_config_from_default_assets_to_string_with_comments.snap b/zellij-utils/src/kdl/snapshots/zellij_utils__kdl__bare_config_from_default_assets_to_string_with_comments.snap index 6dad8aea..c49fa8f9 100644 --- a/zellij-utils/src/kdl/snapshots/zellij_utils__kdl__bare_config_from_default_assets_to_string_with_comments.snap +++ b/zellij-utils/src/kdl/snapshots/zellij_utils__kdl__bare_config_from_default_assets_to_string_with_comments.snap @@ -303,6 +303,16 @@ web_client { // // theme "dracula" +// Theme to use when the host terminal reports a dark color palette. +// Requires `theme_light` to also be set; otherwise `theme` is used. +// +// theme_dark "dracula" + +// Theme to use when the host terminal reports a light color palette. +// Requires `theme_dark` to also be set; otherwise `theme` is used. +// +// theme_light "solarized-light" + // Choose the base input mode of zellij. // Default: normal // @@ -572,3 +582,4 @@ web_client { // typically work best. Set to 0 to use the number of (physical) CPU cores. // Note: This only applies to web clients at the moment. // client_async_worker_tasks 4 + diff --git a/zellij-utils/src/kdl/snapshots/zellij_utils__kdl__config_options_to_string_with_comments.snap b/zellij-utils/src/kdl/snapshots/zellij_utils__kdl__config_options_to_string_with_comments.snap index e1f47782..eda40849 100644 --- a/zellij-utils/src/kdl/snapshots/zellij_utils__kdl__config_options_to_string_with_comments.snap +++ b/zellij-utils/src/kdl/snapshots/zellij_utils__kdl__config_options_to_string_with_comments.snap @@ -22,6 +22,16 @@ simplified_ui true // theme "dracula" +// Theme to use when the host terminal reports a dark color palette. +// Requires `theme_light` to also be set; otherwise `theme` is used. +// +// theme_dark "dracula" + +// Theme to use when the host terminal reports a light color palette. +// Requires `theme_dark` to also be set; otherwise `theme` is used. +// +// theme_light "solarized-light" + // Choose the base input mode of zellij. // Default: normal // @@ -291,3 +301,4 @@ web_sharing "disabled" // typically work best. Set to 0 to use the number of (physical) CPU cores. // Note: This only applies to web clients at the moment. // client_async_worker_tasks 4 + diff --git a/zellij-utils/src/plugin_api/action.proto b/zellij-utils/src/plugin_api/action.proto index ea043d56..28a8337e 100644 --- a/zellij-utils/src/plugin_api/action.proto +++ b/zellij-utils/src/plugin_api/action.proto @@ -490,6 +490,9 @@ enum ActionName { ShowFloatingPanes = 98; HideFloatingPanes = 99; AreFloatingPanesVisible = 100; + SetDarkTheme = 101; + SetLightTheme = 102; + ToggleTheme = 103; } message Position { diff --git a/zellij-utils/src/plugin_api/action.rs b/zellij-utils/src/plugin_api/action.rs index cbd62e5b..cd3e1522 100644 --- a/zellij-utils/src/plugin_api/action.rs +++ b/zellij-utils/src/plugin_api/action.rs @@ -611,6 +611,18 @@ impl TryFrom<ProtobufAction> for Action { Some(_) => Err("Detach should not have a payload"), None => Ok(Action::Detach), }, + Some(ProtobufActionName::SetDarkTheme) => match protobuf_action.optional_payload { + Some(_) => Err("SetDarkTheme should not have a payload"), + None => Ok(Action::SetDarkTheme), + }, + Some(ProtobufActionName::SetLightTheme) => match protobuf_action.optional_payload { + Some(_) => Err("SetLightTheme should not have a payload"), + None => Ok(Action::SetLightTheme), + }, + Some(ProtobufActionName::ToggleTheme) => match protobuf_action.optional_payload { + Some(_) => Err("ToggleTheme should not have a payload"), + None => Ok(Action::ToggleTheme), + }, Some(ProtobufActionName::LeftClick) => match protobuf_action.optional_payload { Some(OptionalPayload::LeftClickPayload(payload)) => { let position = payload.try_into()?; @@ -1567,6 +1579,18 @@ impl TryFrom<Action> for ProtobufAction { name: ProtobufActionName::Detach as i32, optional_payload: None, }), + Action::SetDarkTheme => Ok(ProtobufAction { + name: ProtobufActionName::SetDarkTheme as i32, + optional_payload: None, + }), + Action::SetLightTheme => Ok(ProtobufAction { + name: ProtobufActionName::SetLightTheme as i32, + optional_payload: None, + }), + Action::ToggleTheme => Ok(ProtobufAction { + name: ProtobufActionName::ToggleTheme as i32, + optional_payload: None, + }), Action::LaunchOrFocusPlugin { plugin: run_plugin_or_alias, should_float, diff --git a/zellij-utils/src/plugin_api/event.proto b/zellij-utils/src/plugin_api/event.proto index 3c3a8490..5334f434 100644 --- a/zellij-utils/src/plugin_api/event.proto +++ b/zellij-utils/src/plugin_api/event.proto @@ -68,6 +68,7 @@ enum EventType { PaneRenderReportWithAnsi = 43; InitialKeybinds = 44; CommandChanged = 45; + HostTerminalThemeChanged = 46; } message EventNameList { @@ -115,9 +116,19 @@ message Event { PaneRenderReportPayload pane_render_report_with_ansi_payload = 37; InitialKeybindsPayload initial_keybinds_payload = 38; CommandChangedPayload command_changed_payload = 39; + HostTerminalThemeChangedPayload host_terminal_theme_changed_payload = 40; } } +message HostTerminalThemeChangedPayload { + HostTerminalThemeIndication mode = 1; +} + +enum HostTerminalThemeIndication { + Dark = 0; + Light = 1; +} + message CwdChangedPayload { PaneId pane_id = 1; string new_cwd = 2; diff --git a/zellij-utils/src/plugin_api/event.rs b/zellij-utils/src/plugin_api/event.rs index 6f138742..af421fac 100644 --- a/zellij-utils/src/plugin_api/event.rs +++ b/zellij-utils/src/plugin_api/event.rs @@ -11,6 +11,8 @@ pub use super::generated_api::api::{ CopyDestination as ProtobufCopyDestination, CwdChangedPayload as ProtobufCwdChangedPayload, Event as ProtobufEvent, EventNameList as ProtobufEventNameList, EventType as ProtobufEventType, FileMetadata as ProtobufFileMetadata, + HostTerminalThemeChangedPayload as ProtobufHostTerminalThemeChangedPayload, + HostTerminalThemeIndication as ProtobufHostTerminalThemeIndication, InputModeKeybinds as ProtobufInputModeKeybinds, KdlError as ProtobufKdlError, KdlErrorVariant as ProtobufKdlErrorVariant, KeyBind as ProtobufKeyBind, LayoutInfo as ProtobufLayoutInfo, LayoutMetadata as ProtobufLayoutMetadata, @@ -35,11 +37,11 @@ pub use super::generated_api::api::{ }; #[allow(hidden_glob_reexports)] use crate::data::{ - ClientId, ClientInfo, CopyDestination, Event, EventType, FileMetadata, InputMode, - KeyWithModifier, LayoutInfo, LayoutMetadata, ModeInfo, Mouse, PaneContents, PaneId, PaneInfo, - PaneManifest, PaneMetadata, PaneScrollbackResponse, PermissionStatus, PluginCapabilities, - PluginInfo, SelectedText, SessionInfo, Style, TabInfo, TabMetadata, WebServerStatus, - WebSharing, + ClientId, ClientInfo, CopyDestination, Event, EventType, FileMetadata, HostTerminalThemeMode, + InputMode, KeyWithModifier, LayoutInfo, LayoutMetadata, ModeInfo, Mouse, PaneContents, PaneId, + PaneInfo, PaneManifest, PaneMetadata, PaneScrollbackResponse, PermissionStatus, + PluginCapabilities, PluginInfo, SelectedText, SessionInfo, Style, TabInfo, TabMetadata, + WebServerStatus, WebSharing, }; use crate::errors::prelude::*; @@ -578,6 +580,14 @@ impl TryFrom<ProtobufEvent> for Event { }, _ => Err("Malformed payload for InitialKeybinds Event"), }, + Some(ProtobufEventType::HostTerminalThemeChanged) => match protobuf_event.payload { + Some(ProtobufEventPayload::HostTerminalThemeChangedPayload(p)) => { + let mode = ProtobufHostTerminalThemeIndication::from_i32(p.mode) + .ok_or("Unknown HostTerminalThemeIndication")?; + Ok(Event::HostTerminalThemeChanged(mode.into())) + }, + _ => Err("Malformed payload for HostTerminalThemeChanged Event"), + }, None => Err("Unknown Protobuf Event"), } } @@ -1109,6 +1119,16 @@ impl TryFrom<Event> for ProtobufEvent { }, )), }), + Event::HostTerminalThemeChanged(mode) => { + let proto_mode: ProtobufHostTerminalThemeIndication = mode.into(); + let payload = ProtobufHostTerminalThemeChangedPayload { + mode: proto_mode as i32, + }; + Ok(ProtobufEvent { + name: ProtobufEventType::HostTerminalThemeChanged as i32, + payload: Some(event::Payload::HostTerminalThemeChangedPayload(payload)), + }) + }, Event::InitialKeybinds(keybinds) => { let mut protobuf_keybinds: Vec<ProtobufInputModeKeybinds> = vec![]; for (input_mode, input_mode_keybinds) in keybinds { @@ -2057,6 +2077,7 @@ impl TryFrom<ProtobufEventType> for EventType { ProtobufEventType::PluginConfigurationChanged => EventType::PluginConfigurationChanged, ProtobufEventType::HighlightClicked => EventType::HighlightClicked, ProtobufEventType::InitialKeybinds => EventType::InitialKeybinds, + ProtobufEventType::HostTerminalThemeChanged => EventType::HostTerminalThemeChanged, }) } } @@ -2110,10 +2131,29 @@ impl TryFrom<EventType> for ProtobufEventType { EventType::PluginConfigurationChanged => ProtobufEventType::PluginConfigurationChanged, EventType::HighlightClicked => ProtobufEventType::HighlightClicked, EventType::InitialKeybinds => ProtobufEventType::InitialKeybinds, + EventType::HostTerminalThemeChanged => ProtobufEventType::HostTerminalThemeChanged, }) } } +impl From<HostTerminalThemeMode> for ProtobufHostTerminalThemeIndication { + fn from(mode: HostTerminalThemeMode) -> Self { + match mode { + HostTerminalThemeMode::Dark => ProtobufHostTerminalThemeIndication::Dark, + HostTerminalThemeMode::Light => ProtobufHostTerminalThemeIndication::Light, + } + } +} + +impl From<ProtobufHostTerminalThemeIndication> for HostTerminalThemeMode { + fn from(mode: ProtobufHostTerminalThemeIndication) -> Self { + match mode { + ProtobufHostTerminalThemeIndication::Dark => HostTerminalThemeMode::Dark, + ProtobufHostTerminalThemeIndication::Light => HostTerminalThemeMode::Light, + } + } +} + impl From<ProtobufResurrectableSession> for (String, Duration) { fn from(protobuf_resurrectable_session: ProtobufResurrectableSession) -> (String, Duration) { ( diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__cli_arguments_override_config_options.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__cli_arguments_override_config_options.snap index 1b86c6f4..a13669e5 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__cli_arguments_override_config_options.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__cli_arguments_override_config_options.snap @@ -7,6 +7,8 @@ Options { true, ), theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__cli_arguments_override_layout_options.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__cli_arguments_override_layout_options.snap index aacf3843..9a0e7eda 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__cli_arguments_override_layout_options.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__cli_arguments_override_layout_options.snap @@ -5,6 +5,8 @@ expression: "format!(\"{:#?}\", options)" Options { simplified_ui: None, theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__default_config_with_no_cli_arguments-3.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__default_config_with_no_cli_arguments-3.snap index 47949964..52734174 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__default_config_with_no_cli_arguments-3.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__default_config_with_no_cli_arguments-3.snap @@ -5,6 +5,8 @@ expression: "format!(\"{:#?}\", options)" Options { simplified_ui: None, theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__default_config_with_no_cli_arguments.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__default_config_with_no_cli_arguments.snap index 243ea7ba..2b17d5a3 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__default_config_with_no_cli_arguments.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__default_config_with_no_cli_arguments.snap @@ -5983,6 +5983,8 @@ Config { options: Options { simplified_ui: None, theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_env_vars_override_config_env_vars.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_env_vars_override_config_env_vars.snap index 6c352256..1f1e8268 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_env_vars_override_config_env_vars.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_env_vars_override_config_env_vars.snap @@ -5983,6 +5983,8 @@ Config { options: Options { simplified_ui: None, theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_keybinds_override_config_keybinds.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_keybinds_override_config_keybinds.snap index c5f742db..8ad32dc7 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_keybinds_override_config_keybinds.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_keybinds_override_config_keybinds.snap @@ -92,6 +92,8 @@ Config { options: Options { simplified_ui: None, theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_options_override_config_options.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_options_override_config_options.snap index 9f4a1e40..74927ae6 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_options_override_config_options.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_options_override_config_options.snap @@ -5,6 +5,8 @@ expression: "format!(\"{:#?}\", options)" Options { simplified_ui: None, theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_themes_override_config_themes.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_themes_override_config_themes.snap index 027cee69..28c7b32d 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_themes_override_config_themes.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_themes_override_config_themes.snap @@ -5983,6 +5983,8 @@ Config { options: Options { simplified_ui: None, theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_ui_config_overrides_config_ui_config.snap b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_ui_config_overrides_config_ui_config.snap index 70b23c18..43f29c48 100644 --- a/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_ui_config_overrides_config_ui_config.snap +++ b/zellij-utils/src/snapshots/zellij_utils__setup__setup_test__layout_ui_config_overrides_config_ui_config.snap @@ -5983,6 +5983,8 @@ Config { options: Options { simplified_ui: None, theme: None, + theme_dark: None, + theme_light: None, default_mode: None, default_shell: None, default_cwd: None, diff --git a/zellij-utils/src/vendored/termwiz/input.rs b/zellij-utils/src/vendored/termwiz/input.rs index 42ebf736..c25f712b 100644 --- a/zellij-utils/src/vendored/termwiz/input.rs +++ b/zellij-utils/src/vendored/termwiz/input.rs @@ -139,6 +139,19 @@ pub enum InputEvent { /// An Operating System Command sequence was received. /// Contains the raw payload between \x1b] and the terminator. OperatingSystemCommand(Vec<u8>), + /// A CSI-based device control / status report reply emitted by the + /// host terminal (not a keyboard event). This variant is only produced + /// for a deliberately narrow whitelist of final bytes — `t` (pixel + /// dimensions reply), `y` (DECRPM reply), `c` (Primary-DA reply), and + /// `n` (DSR reply). The raw field contains the exact byte sequence of + /// the original report (including the leading ESC) so it can be + /// forwarded verbatim without re-serialization. + DeviceControlReply { + intermediates: Vec<u8>, + params: Vec<u8>, + final_byte: u8, + raw: Vec<u8>, + }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -811,6 +824,73 @@ fn parse_sgr_mouse(buf: &[u8]) -> Option<(InputEvent, usize)> { /// OSC sequence is found, where `payload` is the bytes between `\x1b]` and the /// terminator, and `len` is the total number of bytes consumed. /// Returns `None` if the buffer does not start with `\x1b]` or the sequence is incomplete. +/// Attempt to parse a CSI-based host-terminal report (device-attribute +/// responses, DSR replies, DECRPM, pixel-dims reply, etc.) from the start +/// of `buf`. +/// +/// Only a narrow whitelist of final bytes is recognised: `t`, `y`, `c`, +/// `n`. Any other final byte returns `None` so the bytes fall through to +/// the regular CSI key-mapping machinery. +/// +/// Returns `Some((event, len))` on a full match, `None` if the bytes do +/// not look like a whitelisted CSI report (caller should try the next +/// parser) and reserves returning None with the buffer starting with +/// `ESC [` for two distinct cases — not currently disambiguated here: +/// - truly malformed / unsupported sequence, or +/// - incomplete input; caller handles incompleteness via `maybe_more`. +fn parse_csi_report(buf: &[u8]) -> Option<(InputEvent, usize)> { + if buf.get(0) != Some(&0x1b) || buf.get(1) != Some(&b'[') { + return None; + } + // Scan forward looking for a final byte in the whitelist, or bail if + // we hit something that clearly is not a CSI report (a non-printable + // byte other than the known final bytes). + let mut i = 2; + let mut intermediates: Vec<u8> = Vec::new(); + let mut params: Vec<u8> = Vec::new(); + // Parameters (0x30..=0x3F) come first, then intermediates (0x20..=0x2F), + // then a final byte (0x40..=0x7E). We only scan up to a reasonable + // length to avoid pathological buffers. + let max_scan = buf.len().min(256); + while i < max_scan { + let b = buf[i]; + match b { + // Parameters: digits, `;`, `:`, `?`, `<`, `=`, `>` + 0x30..=0x3F => { + params.push(b); + i += 1; + }, + // Intermediates: space, `!`, `"`, ... `/` + 0x20..=0x2F => { + intermediates.push(b); + i += 1; + }, + // Final byte (0x40..=0x7E): must be one of the whitelisted bytes. + b't' | b'y' | b'c' | b'n' => { + let raw = buf[0..=i].to_vec(); + return Some(( + InputEvent::DeviceControlReply { + intermediates, + params, + final_byte: b, + raw, + }, + i + 1, + )); + }, + 0x40..=0x7E => { + // Final byte outside the whitelist — not ours. + return None; + }, + _ => { + // Something unexpected inside the CSI — give up. + return None; + }, + } + } + None +} + fn parse_osc(buf: &[u8]) -> Option<(InputEvent, usize)> { // OSC sequences start with ESC ] (0x1b 0x5d) if buf.get(0) != Some(&0x1b) || buf.get(1) != Some(&b']') { @@ -1573,6 +1653,25 @@ impl InputParser { if maybe_more && self.buf.as_slice().starts_with(b"\x1b[<") { return; } + + // CSI-based host-terminal report (pixel-dims reply, + // DECRPM, DSR, Primary-DA). Must come before the + // regular CSI key-mapping machinery, which would + // otherwise match "\x1b[" as an escape prefix and + // pass the bytes through as keyboard input. + if let Some((event, len)) = parse_csi_report(self.buf.as_slice()) { + self.buf.advance(len); + callback(event); + continue; + } + + // Incomplete CSI ?... report (DECRPM, DSR 997, etc.) — + // wait for more data so the report-classification path + // can match the full sequence rather than letting the + // keymap dispatch the leading bytes as separate keys. + if maybe_more && self.buf.as_slice().starts_with(b"\x1b[?") { + return; + } } match ( @@ -2479,4 +2578,103 @@ mod test { inputs ); } + + // ===================================================================== + // parse_csi_report (CSI report whitelist for host-reply forwarding) + // ===================================================================== + + fn csi_reply(intermediates: &[u8], params: &[u8], final_byte: u8, raw: &[u8]) -> InputEvent { + InputEvent::DeviceControlReply { + intermediates: intermediates.to_vec(), + params: params.to_vec(), + final_byte, + raw: raw.to_vec(), + } + } + + #[test] + fn csi_report_recognises_each_whitelisted_final_byte() { + // `t` — pixel-dimension reply form `\x1b[4;H;Wt`. + let bytes = b"\x1b[4;600;800t"; + let (evt, consumed) = parse_csi_report(bytes).expect("t accepted"); + assert_eq!(consumed, bytes.len()); + assert_eq!(evt, csi_reply(b"", b"4;600;800", b't', bytes)); + + // `y` — DECRPM, e.g. sync-output support. Intermediate `$`. + let bytes = b"\x1b[?2026;1$y"; + let (evt, consumed) = parse_csi_report(bytes).expect("y accepted"); + assert_eq!(consumed, bytes.len()); + assert_eq!(evt, csi_reply(b"$", b"?2026;1", b'y', bytes)); + + // `c` — Primary-DA reply (barrier). + let bytes = b"\x1b[?62;1;6c"; + let (evt, consumed) = parse_csi_report(bytes).expect("c accepted"); + assert_eq!(consumed, bytes.len()); + assert_eq!(evt, csi_reply(b"", b"?62;1;6", b'c', bytes)); + + // `n` — DSR reply (used for theme notifications). + let bytes = b"\x1b[?997;1n"; + let (evt, consumed) = parse_csi_report(bytes).expect("n accepted"); + assert_eq!(consumed, bytes.len()); + assert_eq!(evt, csi_reply(b"", b"?997;1", b'n', bytes)); + } + + #[test] + fn csi_report_preserves_intermediates() { + // DECRPM uses `$` as its intermediate byte — it must land in + // `intermediates`, not `params`. + let bytes = b"\x1b[?2026;2$y"; + let (evt, _len) = parse_csi_report(bytes).expect("DECRPM accepted"); + let InputEvent::DeviceControlReply { + intermediates, + params, + final_byte, + raw, + } = evt + else { + panic!("expected DeviceControlReply, got {:?}", evt); + }; + assert_eq!(intermediates, b"$"); + assert_eq!(params, b"?2026;2"); + assert_eq!(final_byte, b'y'); + assert_eq!(raw, bytes); + } + + #[test] + fn csi_report_rejects_non_whitelisted_final_bytes() { + // `A` = cursor-up (keyboard input, not a report). + assert!(parse_csi_report(b"\x1b[A").is_none()); + // `R` = cursor-position report — not whitelisted; must pass + // through to the keyboard path. + assert!(parse_csi_report(b"\x1b[24;80R").is_none()); + // `m` = SGR; appears in render streams but should never reach + // stdin as a report. + assert!(parse_csi_report(b"\x1b[0m").is_none()); + } + + #[test] + fn csi_report_returns_none_on_truncated_input() { + // No final byte within the supplied slice → caller should wait + // for more bytes; `parse_csi_report` must not "commit" to a + // partial parse. + assert!(parse_csi_report(b"\x1b[4;600;800").is_none()); + // Only the lead-in; parameters haven't started. + assert!(parse_csi_report(b"\x1b[").is_none()); + // Empty input — zero bytes to consume. + assert!(parse_csi_report(b"").is_none()); + } + + #[test] + fn csi_report_raw_preserves_input_byte_for_byte() { + // `raw` must include the leading ESC through the final byte + // inclusive, without adding or dropping any byte — the + // forwarding path writes it verbatim to the pane's pty. + let bytes = b"\x1b[4;16;8t"; + let (evt, consumed) = parse_csi_report(bytes).expect("accepted"); + assert_eq!(consumed, bytes.len()); + let InputEvent::DeviceControlReply { raw, .. } = evt else { + panic!("wrong variant"); + }; + assert_eq!(&raw[..], bytes, "raw must be byte-identical to input"); + } } |
