Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

refactor: route all pane key encoding through libghostty (#5017)

Can Celika124eed73c1f
diff --git a/crates/ghostty-vt/src/lib.rs b/crates/ghostty-vt/src/lib.rs
index 7deaaa8dd..357cd64bf 100644
--- a/crates/ghostty-vt/src/lib.rs
+++ b/crates/ghostty-vt/src/lib.rs
@@ -3021,13 +3021,19 @@ impl Drop for RenderState {
pub struct KeyEvent {
raw: ffi::GhosttyKeyEvent,
+ // libghostty borrows the UTF-8 pointer instead of copying it, so the event
+ // owns the text for as long as the handle can be encoded.
+ utf8: Box<str>,
}
impl KeyEvent {
pub fn new() -> Result<Self, Error> {
let mut raw = ptr::null_mut();
unsafe { ffi::ghostty_key_event_new(ptr::null(), &mut raw).into_result()? };
- Ok(Self { raw })
+ Ok(Self {
+ raw,
+ utf8: Box::from(""),
+ })
}
pub fn set_action(&mut self, action: ffi::GhosttyKeyAction) {
@@ -3043,14 +3049,27 @@ impl KeyEvent {
}
pub fn set_utf8(&mut self, text: &str) {
+ self.utf8 = Box::from(text);
unsafe {
- ffi::ghostty_key_event_set_utf8(self.raw, text.as_ptr().cast::<c_char>(), text.len())
+ ffi::ghostty_key_event_set_utf8(
+ self.raw,
+ self.utf8.as_ptr().cast::<c_char>(),
+ self.utf8.len(),
+ )
}
}
pub fn set_unshifted_codepoint(&mut self, codepoint: u32) {
unsafe { ffi::ghostty_key_event_set_unshifted_codepoint(self.raw, codepoint) }
}
+
+ pub fn set_consumed_mods(&mut self, mods: u16) {
+ unsafe { ffi::ghostty_key_event_set_consumed_mods(self.raw, mods) }
+ }
+
+ pub fn set_composing(&mut self, composing: bool) {
+ unsafe { ffi::ghostty_key_event_set_composing(self.raw, composing) }
+ }
}
impl Drop for KeyEvent {
@@ -3074,6 +3093,23 @@ impl KeyEncoder {
unsafe { ffi::ghostty_key_encoder_setopt_from_terminal(self.raw, terminal.raw()) }
}
+ /// Whether macOS Option acts as Alt (ESC prefix) rather than a text
+ /// modifier. `set_from_terminal` resets this to false.
+ pub fn set_macos_option_as_alt(&mut self, enabled: bool) {
+ let value = if enabled {
+ ffi::GhosttyOptionAsAlt_GHOSTTY_OPTION_AS_ALT_TRUE
+ } else {
+ ffi::GhosttyOptionAsAlt_GHOSTTY_OPTION_AS_ALT_FALSE
+ };
+ unsafe {
+ ffi::ghostty_key_encoder_setopt(
+ self.raw,
+ ffi::GhosttyKeyEncoderOption_GHOSTTY_KEY_ENCODER_OPT_MACOS_OPTION_AS_ALT,
+ (&value as *const ffi::GhosttyOptionAsAlt).cast(),
+ )
+ }
+ }
+
pub fn encode(&mut self, event: &KeyEvent) -> Result<Vec<u8>, Error> {
encode_with_retry(|buf, len, out_len| unsafe {
ffi::ghostty_key_encoder_encode(self.raw, event.raw, buf, len, out_len)
diff --git a/scripts/windows_conpty_enhanced_input_probe.ps1 b/scripts/windows_conpty_enhanced_input_probe.ps1
index 559396c4f..574ea42f2 100644
--- a/scripts/windows_conpty_enhanced_input_probe.ps1
+++ b/scripts/windows_conpty_enhanced_input_probe.ps1
@@ -399,9 +399,10 @@ fn main() {
$kittyInitialHex = Get-LatestProbeHex -PaneText $report.kitty_initial
$report.device_attributes_response = $kittyInitialHex -match "1b5b3f(?:3[0-9]|3b)+63"
$report.kitty_query_response = $kittyInitialHex.Contains("1b5b3f3775")
- $report.kitty_alt_v = Send-KeyAndObserve -PaneId $kittyPane -Key "alt+v" -ExpectedHex "1b5b3131383b333a3175"
- $report.kitty_ctrl_u = Send-KeyAndObserve -PaneId $kittyPane -Key "ctrl+u" -ExpectedHex "1b5b3131373b353a3175"
- $report.kitty_ctrl_v = Send-KeyAndObserve -PaneId $kittyPane -Key "ctrl+v" -ExpectedHex "1b5b3131383b353a3175"
+ # libghostty omits the default press event type (`;3u`, not `;3:1u`).
+ $report.kitty_alt_v = Send-KeyAndObserve -PaneId $kittyPane -Key "alt+v" -ExpectedHex "1b5b3131383b3375"
+ $report.kitty_ctrl_u = Send-KeyAndObserve -PaneId $kittyPane -Key "ctrl+u" -ExpectedHex "1b5b3131373b3575"
+ $report.kitty_ctrl_v = Send-KeyAndObserve -PaneId $kittyPane -Key "ctrl+v" -ExpectedHex "1b5b3131383b3575"
$report.kitty_shift_enter = Send-KeyAndObserve -PaneId $kittyPane -Key "shift+enter" -ExpectedHex "1b5b31333b3275"
$report.kitty_ctrl_backspace = Send-KeyAndObserve -PaneId $kittyPane -Key "ctrl+backspace" -ExpectedHex "1b5b3132373b3575"
$report.kitty_up = Send-KeyAndObserve -PaneId $kittyPane -Key "up" -ExpectedHex "1b5b313b313a3141"
@@ -414,6 +415,11 @@ fn main() {
$report.raw_kitty_ctrl_delete = Send-RawAndObserve -PaneId $kittyPane -Text ([char]27 + "[57426;5u") -ExpectedHex "1b5b35373432363b3575"
$report.raw_alt_v = Send-RawAndObserve -PaneId $kittyPane -Text ([char]27 + "v") -ExpectedHex "1b76"
$report.raw_ctrl_u = Send-RawAndObserve -PaneId $kittyPane -Text ([string][char]0x15) -ExpectedHex "15"
+ # ConPTY must pass the richer Kitty and modifyOtherKeys forms through intact.
+ $report.raw_kitty_release = Send-RawAndObserve -PaneId $kittyPane -Text ([char]27 + "[97;1:3u") -ExpectedHex "1b5b39373b313a3375"
+ $report.raw_kitty_alternate = Send-RawAndObserve -PaneId $kittyPane -Text ([char]27 + "[97:65;2u") -ExpectedHex "1b5b39373a36353b3275"
+ $report.raw_kitty_associated_text = Send-RawAndObserve -PaneId $kittyPane -Text ([char]27 + "[97;;97u") -ExpectedHex "1b5b39373b3b393775"
+ $report.raw_modify_other_keys = Send-RawAndObserve -PaneId $kittyPane -Text ([char]27 + "[27;5;97~") -ExpectedHex "1b5b32373b353b39377e"
$nativePane = New-ProbePane -Mode "native"
# Win32 input mode records use CSI Vk;Scan;Unicode;Down;Control;Repeat _.
@@ -465,6 +471,10 @@ fn main() {
-or -not $report.raw_kitty_ctrl_delete.delivered `
-or -not $report.raw_alt_v.delivered `
-or -not $report.raw_ctrl_u.delivered `
+ -or -not $report.raw_kitty_release.delivered `
+ -or -not $report.raw_kitty_alternate.delivered `
+ -or -not $report.raw_kitty_associated_text.delivered `
+ -or -not $report.raw_modify_other_keys.delivered `
-or -not $report.native_escape_down.delivered `
-or -not $report.native_escape_release.delivered `
-or ($appLocalHostRequired -and -not $report.app_local_console_host)
diff --git a/scripts/windows_cross.py b/scripts/windows_cross.py
index 55795d359..6d71c36af 100644
--- a/scripts/windows_cross.py
+++ b/scripts/windows_cross.py
@@ -73,7 +73,20 @@ def lint() -> None:
env = {**os.environ, LIBC_ENV: str(libc_path()), "LIBGHOSTTY_VT_SIMD": "false"}
subprocess.run(["rustup", "target", "add", TARGET], check=True)
subprocess.run(
- ["cargo", "clippy", "--bin", "herdr", "--locked", "--target", TARGET, "--", "-D", "warnings"],
+ # --tests also checks Windows-only test code, which Unix builds never compile.
+ [
+ "cargo",
+ "clippy",
+ "--bin",
+ "herdr",
+ "--tests",
+ "--locked",
+ "--target",
+ TARGET,
+ "--",
+ "-D",
+ "warnings",
+ ],
env=env,
check=True,
)
diff --git a/scripts/windows_input/report.py b/scripts/windows_input/report.py
index f63e700e5..1d6cc5244 100644
--- a/scripts/windows_input/report.py
+++ b/scripts/windows_input/report.py
@@ -38,6 +38,10 @@ def catalogue():
key("letter-a", 65, "a")
key("shift-letter", 65, "A", (16,))
+ # xterm modifyOtherKeys level 2 keeps Shift on printable keys and treats
+ # 0x40-0x7f as control input, so Shift+A is CSI 27;2;65~ (xterm input.c,
+ # ModifyOtherKeys and IsControlInput).
+ cases[-1]["expected"]["mok2"] = {"hex": [hex_of("\x1b[27;2;65~")]}
key("enter", 13, "\r")
key("shift-enter", 13, None, (16,), 13)
cases[-1]["expected"]["legacy"] = {"loss": "enter", "hex": ["0d"]}
diff --git a/src/app/api/panes.rs b/src/app/api/panes.rs
index 13d30a63d..435ecdc00 100644
--- a/src/app/api/panes.rs
+++ b/src/app/api/panes.rs
@@ -2044,7 +2044,7 @@ impl App {
Ok(encoded_keys) => encoded_keys,
Err(key) => return encode_error(id, "invalid_key", format!("unsupported key {key}")),
};
- for bytes in encoded_keys {
+ for bytes in encoded_keys.into_iter().filter(|bytes| !bytes.is_empty()) {
if let Err(err) = runtime.try_send_bytes(Bytes::from(bytes)) {
return encode_error(id, "pane_send_failed", err.to_string());
}
@@ -2835,7 +2835,7 @@ mod tests {
}
#[tokio::test]
- async fn api_pane_send_keys_preserves_super_chord_in_legacy_pane() {
+ async fn api_pane_send_keys_does_not_type_super_chord_into_legacy_pane() {
let (mut app, pane_id, mut rx) = app_with_send_key_runtime(1);
let internal_pane_id = app.state.workspaces[0].tabs[0].root_pane;
assert_eq!(
@@ -2856,11 +2856,38 @@ mod tests {
let success: SuccessResponse = serde_json::from_str(&response).unwrap();
assert_eq!(success.id, "req");
assert_eq!(success.result, ResponseResult::Ok {});
+ // Neither a bare "c" (#3710) nor a Kitty report the shell prints (#4356).
+ assert!(rx.try_recv().is_err());
+ }
+
+ #[tokio::test]
+ async fn api_pane_send_keys_reports_super_chord_to_kitty_pane() {
+ let (mut app, pane_id) = app_with_test_workspace();
+ let internal_pane_id = app.state.workspaces[0].tabs[0].root_pane;
+ let (runtime, mut rx) =
+ crate::terminal::TerminalRuntime::test_with_channel_and_scrollback_bytes(
+ 80,
+ 24,
+ 0,
+ b"\x1b[>1u",
+ 1,
+ );
+ app.state.insert_test_runtime(internal_pane_id, runtime);
+
+ let response = app.handle_api_request(crate::api::schema::Request {
+ id: "req".into(),
+ method: crate::api::schema::Method::PaneSendKeys(PaneSendKeysParams {
+ pane_id,
+ keys: vec!["cmd+c".into()],
+ }),
+ });
+
+ let success: SuccessResponse = serde_json::from_str(&response).unwrap();
+ assert_eq!(success.result, ResponseResult::Ok {});
assert_eq!(
rx.try_recv().unwrap(),
bytes::Bytes::from_static(b"\x1b[99;9u")
);
- assert!(rx.try_recv().is_err());
}
#[tokio::test]
diff --git a/src/client/attach.rs b/src/client/attach.rs
index 2cabe5bbb..9a9e3fdea 100644
--- a/src/client/attach.rs
+++ b/src/client/attach.rs
@@ -153,7 +153,7 @@ impl AttachEscapeState {
#[cfg(unix)]
fn single_attach_key(data: &[u8]) -> Option<crate::input::TerminalKey> {
- let mut events = crate::raw_input::parse_raw_input_bytes_sync(data);
+ let mut events = crate::raw_input::parse_framed_input(data);
if events.len() != 1 {
return None;
}
@@ -172,19 +172,17 @@ pub(super) fn direct_attach_pixel_mouse(
crate::protocol::ClientMousePosition,
u8,
)> {
- let (x, y) = crate::input::mouse::parse_report(data)?;
- let (column, row) = geometry.cell(x, y)?;
- let cell_report = crate::input::mouse::report_at_cell(data, column, row)?;
- let mut events = crate::raw_input::parse_raw_input_bytes_sync(&cell_report);
- if events.len() != 1 {
- return None;
- }
- let crate::raw_input::RawInputEvent::Mouse(mouse) = events.pop()? else {
- return None;
- };
+ let report = crate::raw_input::parse_sgr_mouse_report(data)?;
+ let (column, row) = geometry.cell(report.x, report.y)?;
+ let mouse = report.at_cell(column, row);
Some((
crate::protocol::ClientMouseKind::from_crossterm(mouse.kind)?,
- crate::protocol::ClientMousePosition::Pixels { x, y, column, row },
+ crate::protocol::ClientMousePosition::Pixels {
+ x: report.x,
+ y: report.y,
+ column,
+ row,
+ },
mouse.modifiers.bits(),
))
}
@@ -195,7 +193,7 @@ fn attach_scroll_action(
viewport_rows: u16,
mouse_scroll_lines: usize,
) -> Option<AttachSemanticAction> {
- let mut events = crate::raw_input::parse_raw_input_bytes_sync(data);
+ let mut events = crate::raw_input::parse_framed_input(data);
if events.len() != 1 {
return None;
}
diff --git a/src/client/clipboard_images.rs b/src/client/clipboard_images.rs
index 1faebf390..cd2f1480e 100644
--- a/src/client/clipboard_images.rs
+++ b/src/client/clipboard_images.rs
@@ -79,7 +79,7 @@ pub(super) fn should_bridge_clipboard_image_paste(
return false;
};
- let events = crate::raw_input::parse_raw_input_bytes_sync(data);
+ let events = crate::raw_input::parse_framed_input(data);
matches!(
events.as_slice(),
[crate::raw_input::RawInputEvent::Key(key)]
diff --git a/src/client/config_reload.rs b/src/client/config_reload.rs
index c20de760c..418cab936 100644
--- a/src/client/config_reload.rs
+++ b/src/client/config_reload.rs
@@ -41,6 +41,7 @@ pub(super) fn apply_reload(
enabled,
state.endpoint_sgr_pixels_requested,
state.pixel_geometry_exact,
+ state.host_sgr_pixel_mouse,
);
if enabled != state.mouse_capture_active
|| sgr_pixels != host_sgr_pixels_active.load(Ordering::Acquire)
diff --git a/src/client/input.rs b/src/client/input.rs
index 08254155d..e2bd2b9d2 100644
--- a/src/client/input.rs
+++ b/src/client/input.rs
@@ -10,21 +10,21 @@
//! - We avoid duplicating parsing logic in the client
//! - Host terminal control replies can be buffered or discarded before they leak
-use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
+#[cfg(unix)]
+use std::sync::atomic::Ordering;
+use std::sync::atomic::{AtomicBool, AtomicU32};
use std::sync::Arc;
#[cfg(unix)]
use std::io::{self, Read};
#[cfg(unix)]
use std::os::fd::AsRawFd;
-#[cfg(windows)]
-use std::time::Duration;
use tokio::sync::mpsc;
use super::ClientLoopEvent;
#[cfg(any(windows, test))]
-mod windows_vti;
+pub(super) mod windows_vti;
// ---------------------------------------------------------------------------
// Stdin reader thread
@@ -126,7 +126,7 @@ fn unix_stdin_reader_loop(
if (framer.has_pending_input() || !pending_palette.is_empty())
&& stdin_read_ready(
&reader,
- idle_flush_timeout_ms(&framer, host_mouse_capture_active.load(Ordering::Acquire)),
+ framer.idle_flush_timeout_ms(host_mouse_capture_active.load(Ordering::Acquire)),
) == Some(false)
{
let had_pending = framer.has_pending_input();
@@ -228,10 +228,8 @@ fn unix_stdin_reader_loop(
return;
}
- let timeout_ms = idle_flush_timeout_ms(
- &framer,
- host_mouse_capture_active.load(Ordering::Acquire),
- );
+ let timeout_ms =
+ framer.idle_flush_timeout_ms(host_mouse_capture_active.load(Ordering::Acquire));
if stdin_read_ready(&reader, timeout_ms) == Some(false) {
let had_pending = framer.has_pending_input();
let chunks = framer.flush_timeout();
@@ -351,7 +349,7 @@ fn classify_unix_input(
sgr_pixels: bool,
geometry: Option<crate::input::mouse::HostGeometry>,
) -> Option<ClientLoopEvent> {
- if sgr_pixels && crate::input::mouse::parse_report(&data).is_some() {
+ if sgr_pixels && crate::raw_input::parse_sgr_mouse_report(&data).is_some() {
return geometry.map(|geometry| ClientLoopEvent::PixelMouse(data, geometry));
}
Some(ClientLoopEvent::StdinInput(data))
@@ -371,238 +369,26 @@ fn flush_unix_palette_input(
.is_ok()
}
-#[cfg(unix)]
-fn idle_flush_timeout_ms(
- framer: &crate::raw_input::RawInputByteFramer,
- host_mouse_capture_active: bool,
-) -> i32 {
- if !host_mouse_capture_active {
- return crate::raw_input::RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS;
- }
- if framer.has_pending_lone_escape() || framer.has_pending_incomplete_mouse_sequence() {
- crate::raw_input::MOUSE_ACTIVE_ESCAPE_SEQUENCE_FLUSH_TIMEOUT_MS
- } else if framer.has_pending_csi_introducer() {
- // A mouse report split after ESC[ is still ambiguous with legacy Alt+[.
- crate::raw_input::MOUSE_ACTIVE_CSI_INTRODUCER_FLUSH_TIMEOUT_MS
- } else {
- crate::raw_input::RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS
- }
-}
-
#[cfg(windows)]
fn windows_stdin_reader_loop(
event_tx: mpsc::Sender<ClientLoopEvent>,
should_quit: &Arc<AtomicBool>,
host_color_query_sent: bool,
) {
- if !super::windows_vti_input_backend_enabled() {
- windows_vti::trace_input_transport("reader=crossterm");
- windows_crossterm_reader_loop(event_tx, should_quit);
- } else {
- match windows_vti::console_input_handle() {
- Ok(handle) => {
- windows_vti::trace_input_transport("reader=windows-console");
- windows_vti::raw_console_reader_loop(
- handle,
- event_tx,
- should_quit,
- host_color_query_sent,
- );
- }
- _ => {
- windows_vti::trace_input_transport("reader=crossterm-fallback");
- windows_crossterm_reader_loop(event_tx, should_quit);
- }
- }
- }
-}
-
-#[cfg(windows)]
-fn windows_crossterm_reader_loop(
- event_tx: mpsc::Sender<ClientLoopEvent>,
- should_quit: &Arc<AtomicBool>,
-) {
- let mut framer = crate::raw_input::RawInputFramer::for_host_input();
-
- while !should_quit.load(Ordering::Acquire) {
- match crossterm::event::poll(Duration::from_millis(10)) {
- Ok(true) => {}
- Ok(false) => {
- if framer.has_pending_input() {
- tracing::debug!("windows input raw sequence timed out; flushing");
- if !send_windows_raw_events(framer.flush_timeout(), &event_tx) {
- return;
- }
- }
- continue;
- }
- Err(_) => break,
- }
-
- let event = match crossterm::event::read() {
- Ok(event) => event,
- Err(_) => break,
- };
-
- let (raw_events, event) = frame_windows_crossterm_event(&mut framer, event);
- if !send_windows_raw_events(raw_events, &event_tx) {
- return;
- }
- let Some(event) = event else {
- continue;
- };
- if event_tx
- .blocking_send(ClientLoopEvent::StdinEvents(vec![event]))
- .is_err()
- {
- return;
- }
- }
-
- if framer.has_pending_input() {
- let _ = send_windows_raw_events(framer.flush_interrupted(), &event_tx);
- }
-}
-
-#[cfg(any(windows, test))]
-fn frame_windows_crossterm_event(
- framer: &mut crate::raw_input::RawInputFramer,
- event: crossterm::event::Event,
-) -> (
- Vec<crate::raw_input::RawInputEvent>,
- Option<crate::protocol::ClientInputEvent>,
-) {
- let raw_sequence_pending = framer.has_pending_input();
- if let Some(bytes) = windows_key_raw_bytes(&event, raw_sequence_pending) {
- tracing::debug!(
- bytes = ?bytes,
- pending_before = raw_sequence_pending,
- "windows input routed through raw framer"
- );
- return (framer.push(&bytes), None);
- }
-
- if windows_event_is_control_key(&event) {
- tracing::debug!(event = ?event, "windows control key forwarded as semantic input");
- }
- let Some(event) = windows_crossterm_input_event(event) else {
- // Preserve the existing flush for unrelated pending input, but do not
- // cancel mouse recovery for an event that will not be forwarded.
- return (
- if raw_sequence_pending {
- framer.flush_timeout()
- } else {
- Vec::new()
- },
- None,
- );
- };
- if raw_sequence_pending {
- tracing::debug!("windows input raw sequence interrupted by semantic event; flushing");
- }
- // Even a dormant mouse prefix must stop claiming bytes after semantic input.
- (framer.flush_interrupted(), Some(event))
-}
-
-#[cfg(any(windows, test))]
-fn windows_crossterm_input_event(
- event: crossterm::event::Event,
-) -> Option<crate::protocol::ClientInputEvent> {
- let event = crate::protocol::ClientInputEvent::from_crossterm(event)?;
- match event {
- crate::protocol::ClientInputEvent::Key {
- code: crate::protocol::ClientKeyCode::Char(codepoint),
- modifiers: 0,
- kind: crate::protocol::ClientKeyKind::Press,
- source,
- ..
- } => Some(crate::protocol::ClientInputEvent::Key {
- code: crate::protocol::ClientKeyCode::Char(codepoint),
- modifiers: 0,
- kind: crate::protocol::ClientKeyKind::Press,
- repeat_count: 1,
- generated_text: Some(codepoint.to_string()),
- source,
- }),
- event => Some(event),
- }
-}
-
-#[cfg(any(windows, test))]
-fn windows_event_is_control_key(event: &crossterm::event::Event) -> bool {
- use crossterm::event::{Event, KeyModifiers};
-
- matches!(
- event,
- Event::Key(key)
- if key.modifiers.contains(KeyModifiers::CONTROL)
- || matches!(key.code, crossterm::event::KeyCode::Char(ch) if ch.is_control())
- )
-}
-
-#[cfg(any(windows, test))]
-fn windows_key_raw_bytes(
- event: &crossterm::event::Event,
- raw_sequence_pending: bool,
-) -> Option<Vec<u8>> {
- use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers};
-
- let Event::Key(key) = event else {
- return None;
- };
- if key.kind == KeyEventKind::Release {
- return None;
- }
-
- match key.code {
- KeyCode::Esc if key.modifiers.is_empty() => Some(vec![0x1b]),
- KeyCode::Char('[') if !raw_sequence_pending && key.modifiers == KeyModifiers::CONTROL => {
- Some(vec![0x1b])
- }
- KeyCode::Char(ch)
- if !raw_sequence_pending
- && matches!(ch, 'i' | 'I')
- && key.modifiers.contains(KeyModifiers::CONTROL)
- && !key.modifiers.contains(KeyModifiers::ALT) =>
- {
- let mut buf = [0; 4];
- Some(ch.encode_utf8(&mut buf).as_bytes().to_vec())
+ match windows_vti::console_input_handle() {
+ Ok(handle) => {
+ windows_vti::trace_input_transport("reader=windows-console");
+ windows_vti::raw_console_reader_loop(
+ handle,
+ event_tx,
+ should_quit,
+ host_color_query_sent,
+ );
}
- KeyCode::Char(ch) if raw_sequence_pending || ch.is_control() => {
- let mut bytes = Vec::new();
- if key.modifiers.contains(KeyModifiers::ALT) {
- bytes.push(0x1b);
- }
- let mut buf = [0; 4];
- bytes.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
- Some(bytes)
+ Err(err) => {
+ tracing::error!(%err, "no Windows console input available; keyboard input is disabled");
}
- _ => None,
- }
-}
-
-#[cfg(windows)]
-fn send_windows_raw_events(
- events: Vec<crate::raw_input::RawInputEvent>,
- event_tx: &mpsc::Sender<ClientLoopEvent>,
-) -> bool {
- let raw_event_count = events.len();
- let events = events
- .into_iter()
- .filter_map(windows_client_input_event_from_raw)
- .collect::<Vec<_>>();
- if events.is_empty() {
- return true;
}
-
- tracing::debug!(
- raw_event_count,
- forwarded_event_count = events.len(),
- "windows raw-framed input events forwarded"
- );
- event_tx
- .blocking_send(ClientLoopEvent::StdinEvents(events))
- .is_ok()
}
#[cfg(any(windows, test))]
@@ -792,7 +578,7 @@ mod tests {
let events = framer.push(b"\x1b\x1b");
assert_eq!(events.len(), 1);
- assert!(framer.has_pending_input());
+ // The second escape is still pending until the idle flush.
assert_eq!(framer.flush_timeout().len(), 1);
}
@@ -805,7 +591,7 @@ mod tests {
next: &[u8],
) -> Vec<Vec<u8>> {
let first_wait =
- std::time::Duration::from_millis(idle_flush_timeout_ms(framer, mouse_capture) as u64);
+ std::time::Duration::from_millis(framer.idle_flush_timeout_ms(mouse_capture) as u64);
let mut chunks = Vec::new();
if gap >= first_wait {
chunks.extend(framer.flush_timeout());
@@ -1058,7 +844,7 @@ mod tests {
}
#[test]
- fn mouse_active_escape_sequences_get_longer_reassembly_window() {
+ fn only_ambiguous_escape_prefixes_get_the_short_keyboard_window() {
let mut escape = crate::raw_input::RawInputByteFramer::default();
assert!(escape.push(b"\x1b").is_empty());
let mut csi = crate::raw_input::RawInputByteFramer::default();
@@ -1070,26 +856,30 @@ mod tests {
let mut unrelated = crate::raw_input::RawInputByteFramer::default();
assert!(unrelated.push(b"\x1b[49:33;2:").is_empty());
- for framer in [&escape, &csi, &sgr_mouse, &default_mouse, &unrelated] {
+ // A lone ESC or ESC[ may still be a key (Escape, Alt+[).
+ for framer in [&escape, &csi] {
assert_eq!(
- idle_flush_timeout_ms(framer, false),
+ framer.idle_flush_timeout_ms(false),
crate::raw_input::RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS
);
}
- for framer in [&escape, &sgr_mouse, &default_mouse] {
- assert_eq!(
- idle_flush_timeout_ms(framer, true),
- crate::raw_input::MOUSE_ACTIVE_ESCAPE_SEQUENCE_FLUSH_TIMEOUT_MS
- );
- }
assert_eq!(
- idle_flush_timeout_ms(&csi, true),
- crate::raw_input::MOUSE_ACTIVE_CSI_INTRODUCER_FLUSH_TIMEOUT_MS
+ escape.idle_flush_timeout_ms(true),
+ crate::raw_input::MOUSE_ACTIVE_ESCAPE_SEQUENCE_FLUSH_TIMEOUT_MS
);
assert_eq!(
- idle_flush_timeout_ms(&unrelated, true),
- crate::raw_input::RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS
+ csi.idle_flush_timeout_ms(true),
+ crate::raw_input::MOUSE_ACTIVE_CSI_INTRODUCER_FLUSH_TIMEOUT_MS
);
+ // Anything further inside a sequence cannot be a key: wait for the rest.
+ for framer in [&sgr_mouse, &default_mouse, &unrelated] {
+ for mouse_capture in [false, true] {
+ assert_eq!(
+ framer.idle_flush_timeout_ms(mouse_capture),
+ crate::raw_input::INCOMPLETE_SEQUENCE_FLUSH_TIMEOUT_MS
+ );
+ }
+ }
let mouse_timeout_ms =
std::hint::black_box(crate::raw_input::MOUSE_ACTIVE_ESCAPE_SEQUENCE_FLUSH_TIMEOUT_MS);
@@ -1100,201 +890,6 @@ mod tests {
#[cfg(test)]
mod windows_tests {
use super::*;
- use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
-
- #[test]
- fn windows_control_chars_are_reframed_as_raw_bytes() {
- let escape = Event::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()));
- assert_eq!(
- windows_key_raw_bytes(&escape, false).as_deref(),
- Some(b"\x1b".as_slice())
- );
-
- let enter = Event::Key(KeyEvent::new(KeyCode::Char('\r'), KeyModifiers::empty()));
- assert_eq!(
- windows_key_raw_bytes(&enter, false).as_deref(),
- Some(b"\r".as_slice())
- );
-
- let printable = Event::Key(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::empty()));
- assert_eq!(windows_key_raw_bytes(&printable, false), None);
-
- let pending_arrow_tail =
- Event::Key(KeyEvent::new(KeyCode::Char('['), KeyModifiers::empty()));
- assert_eq!(
- windows_key_raw_bytes(&pending_arrow_tail, true).as_deref(),
- Some(b"[".as_slice())
- );
- }
-
- #[test]
- fn windows_crossterm_semantic_input_cancels_dormant_and_buffered_mouse_recovery() {
- for buffered in [false, true] {
- let mut framer = crate::raw_input::RawInputFramer::for_host_input();
- assert!(framer.push(b"\x1b[<3").is_empty());
- assert!(framer.flush_timeout().is_empty());
- assert!(framer.flush_timeout().is_empty());
- if buffered {
- assert!(framer.push(b"5").is_empty());
- }
- // Printable input bypasses the raw route when no bytes are pending;
- // an arrow bypasses it even when a continuation is buffered.
- let key = if buffered {
- KeyCode::Up
- } else {
- KeyCode::Char('x')
- };
- let event = Event::Key(KeyEvent::new(key, KeyModifiers::empty()));
- let (raw, semantic) = frame_windows_crossterm_event(&mut framer, event.clone());
- let raw_bytes: Vec<_> = raw
- .into_iter()
- .filter_map(|event| {
- let crate::raw_input::RawInputEvent::Key(key) = event else {
- return None;
- };
- key.vt_bytes().map(ToOwned::to_owned)
- })
- .collect();
- assert_eq!(
- raw_bytes.concat(),
- if buffered { b"5".as_slice() } else { b"" }
- );
- assert_eq!(semantic, windows_crossterm_input_event(event));
- assert_eq!(framer.push(b"5;28;31M").len(), 8);
- }
- }
-
- #[test]
- fn windows_crossterm_ignored_event_preserves_mouse_recovery() {
- let mut framer = crate::raw_input::RawInputFramer::for_host_input();
- assert!(framer.push(b"\x1b[<3").is_empty());
- assert!(framer.flush_timeout().is_empty());
- assert!(framer.push(b"5").is_empty());
- let (raw, semantic) = frame_windows_crossterm_event(&mut framer, Event::Resize(80, 24));
- assert!(raw.is_empty());
- assert!(semantic.is_none());
- let events = framer.push(b";28;31Mx");
- assert!(
- matches!(events.as_slice(), [crate::raw_input::RawInputEvent::Key(key)]
- if key.code == KeyCode::Char('x'))
- );
- assert!(!framer.has_pending_input());
- }
-
- #[test]
- fn windows_crossterm_printable_press_keeps_key_semantics_and_text() {
- let event = Event::Key(KeyEvent::new(KeyCode::Char('你'), KeyModifiers::empty()));
-
- assert_eq!(
- windows_crossterm_input_event(event),
- Some(crate::protocol::ClientInputEvent::Key {
- code: crate::protocol::ClientKeyCode::Char('你'),
- modifiers: 0,
- kind: crate::protocol::ClientKeyKind::Press,
- repeat_count: 1,
- generated_text: Some("你".to_string()),
- source: crate::protocol::ClientKeySource::Synthesized,
- })
- );
- }
-
- #[test]
- fn windows_ctrl_bracket_starts_raw_escape_sequence() {
- let ctrl_bracket = Event::Key(KeyEvent::new(KeyCode::Char('['), KeyModifiers::CONTROL));
- assert_eq!(
- windows_key_raw_bytes(&ctrl_bracket, false).as_deref(),
- Some(b"\x1b".as_slice())
- );
-
- let mut framer = crate::raw_input::RawInputFramer::default();
- assert!(framer.push(b"\x1b").is_empty());
- let events = framer.push(b"[<35;48;26M");
- assert_eq!(events.len(), 1);
-
- let event = windows_client_input_event_from_raw(events.into_iter().next().unwrap())
- .expect("raw mouse converts");
- assert!(matches!(
- event,
- crate::protocol::ClientInputEvent::Mouse {
- kind: crate::protocol::ClientMouseKind::Moved,
- column: 47,
- row: 25,
- modifiers: _,
- }
- ));
- }
-
- #[test]
- fn windows_ctrl_shift_bracket_stays_semantic() {
- let ctrl_shift_bracket = Event::Key(KeyEvent::new(
- KeyCode::Char('['),
- KeyModifiers::CONTROL | KeyModifiers::SHIFT,
- ));
- assert_eq!(windows_key_raw_bytes(&ctrl_shift_bracket, false), None);
- }
-
- #[cfg(windows)]
- #[test]
- fn windows_ctrl_d_semantic_event_encodes_to_eot() {
- let event = Event::Key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
- assert_eq!(windows_key_raw_bytes(&event, false), None);
-
- let event =
- crate::protocol::ClientInputEvent::from_crossterm(event).expect("ctrl-d converts");
- let raw = event.to_raw_input_event();
- let crate::raw_input::RawInputEvent::Key(key) = raw else {
- panic!("expected key");
- };
- assert_eq!(key.code, KeyCode::Char('d'));
- assert_eq!(key.modifiers, KeyModifiers::CONTROL);
- assert_eq!(
- crate::input::encode_terminal_key(key, crate::input::KeyboardProtocol::Legacy),
- b"\x04"
- );
- }
-
- #[test]
- fn windows_pasted_printable_ctrl_i_routes_as_literal_i() {
- let event = Event::Key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::CONTROL));
- assert_eq!(
- windows_key_raw_bytes(&event, false).as_deref(),
- Some(b"i".as_slice())
- );
-
- let event = Event::Key(KeyEvent::new(
- KeyCode::Char('I'),
- KeyModifiers::CONTROL | KeyModifiers::SHIFT,
- ));
- assert_eq!(
- windows_key_raw_bytes(&event, false).as_deref(),
- Some(b"I".as_slice())
- );
- }
-
- #[test]
- fn windows_eot_control_char_normalizes_to_ctrl_d() {
- let event = Event::Key(KeyEvent::new(KeyCode::Char('\u{4}'), KeyModifiers::empty()));
- let bytes = windows_key_raw_bytes(&event, false).expect("eot routes through raw framer");
- assert_eq!(bytes, b"\x04");
-
- let mut framer = crate::raw_input::RawInputFramer::default();
- let events = framer.push(&bytes);
- assert_eq!(events.len(), 1);
-
- let event = windows_client_input_event_from_raw(events.into_iter().next().unwrap())
- .expect("raw eot converts");
- assert_eq!(
- event,
- crate::protocol::ClientInputEvent::Key {
- code: crate::protocol::ClientKeyCode::Char('d'),
- modifiers: KeyModifiers::CONTROL.bits(),
- kind: crate::protocol::ClientKeyKind::Press,
- repeat_count: 1,
- generated_text: None,
- source: crate::protocol::ClientKeySource::Vt { bytes: vec![4] },
- }
- );
- }
#[test]
fn windows_pending_escape_sequence_converts_to_semantic_arrow() {
diff --git a/src/client/input/windows_vti.rs b/src/client/input/windows_vti.rs
index 6d8344046..70967f817 100644
--- a/src/client/input/windows_vti.rs
+++ b/src/client/input/windows_vti.rs
@@ -106,19 +106,48 @@ fn push_platform_input_events(
}
#[cfg(windows)]
+/// The console input buffer: standard input when it is the console, otherwise
+/// the attached console's `CONIN$` (stdin redirected, e.g. mintty).
pub(super) fn console_input_handle() -> std::io::Result<windows_sys::Win32::Foundation::HANDLE> {
- use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};
+ use windows_sys::Win32::Foundation::{
+ GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE,
+ };
+ use windows_sys::Win32::Storage::FileSystem::{
+ CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
+ };
use windows_sys::Win32::System::Console::{GetConsoleMode, GetStdHandle, STD_INPUT_HANDLE};
- let handle: HANDLE = unsafe { GetStdHandle(STD_INPUT_HANDLE) };
- if handle.is_null() || handle == INVALID_HANDLE_VALUE {
- return Err(std::io::Error::last_os_error());
- }
- let mut mode = 0;
- if unsafe { GetConsoleMode(handle, &mut mode) } == 0 {
- return Err(std::io::Error::last_os_error());
+ let is_console = |handle: HANDLE| {
+ let mut mode = 0;
+ !handle.is_null()
+ && handle != INVALID_HANDLE_VALUE
+ && unsafe { GetConsoleMode(handle, &mut mode) } != 0
+ };
+
+ // SAFETY: querying the process standard input handle has no preconditions.
+ let stdin: HANDLE = unsafe { GetStdHandle(STD_INPUT_HANDLE) };
+ if is_console(stdin) {
+ return Ok(stdin);
+ }
+ let name: Vec<u16> = "CONIN$".encode_utf16().chain(Some(0)).collect();
+ // SAFETY: `name` is NUL-terminated and outlives the call; the handle is owned
+ // by the reader for the rest of the process.
+ let conin = unsafe {
+ CreateFileW(
+ name.as_ptr(),
+ GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ std::ptr::null(),
+ OPEN_EXISTING,
+ 0,
+ std::ptr::null_mut(),
+ )
+ };
+ if is_console(conin) {
+ Ok(conin)
+ } else {
+ Err(std::io::Error::last_os_error())
}
- Ok(handle)
}
#[cfg(windows)]
@@ -754,6 +783,26 @@ struct WindowsInputTranslator {
pump: WindowsInputPump,
}
+/// Test handle that feeds native key records through the real Windows input
+/// translation (mapper + pump), for cross-module conformance tests.
+#[cfg(all(test, windows))]
+#[derive(Default)]
+pub(crate) struct TestWindowsInput(WindowsInputTranslator);
+
+#[cfg(all(test, windows))]
+impl TestWindowsInput {
+ pub(crate) fn key(
+ &mut self,
+ record: crate::input::WindowsKeyRecord,
+ ) -> Vec<crate::protocol::ClientInputEvent> {
+ self.0.translate(WindowsInputRecord::Key(record))
+ }
+
+ pub(crate) fn idle(&mut self) -> Vec<crate::protocol::ClientInputEvent> {
+ self.0.idle()
+ }
+}
+
#[cfg(test)]
impl WindowsInputTranslator {
fn translate(&mut self, record: WindowsInputRecord) -> Vec<crate::protocol::ClientInputEvent> {
@@ -1110,7 +1159,7 @@ impl WindowsInputMapper {
kind: crate::protocol::ClientKeyKind,
oem_char: Option<char>,
) -> Option<crate::protocol::ClientInputEvent> {
- let modifiers = windows_key_modifiers(key.control_key_state);
+ let modifiers = windows_record_modifiers(key);
if key.virtual_key_code == 0 {
let codepoint = self.utf16_unit_to_char(key.unicode)?;
if !codepoint.is_control() {
@@ -1166,6 +1215,7 @@ impl WindowsInputMapper {
.or_else(|| {
windows_virtual_key_to_char_code(key.virtual_key_code, key.unicode, modifiers)
})
+ .or_else(|| oem_char.map(crate::protocol::ClientKeyCode::Char))
};
code.map(|code| {
@@ -1483,12 +1533,10 @@ fn ctrl_key_code(vk: u16, u: u16, oem: Option<char>) -> Option<crate::protocol::
})
}
+/// Punctuation keys report no character under Ctrl or a non-producing AltGr.
+/// Ask the current layout which key it is so the record is still forwarded.
fn resolve_ctrl_oem_char(key: WindowsKeyRecord) -> Option<char> {
- if key.virtual_key_code == 0xbf
- && key.unicode == 0
- && windows_key_modifiers(key.control_key_state)
- .contains(crossterm::event::KeyModifiers::CONTROL)
- {
+ if is_oem_virtual_key(key.virtual_key_code) && key.unicode == 0 {
#[cfg(windows)]
return crate::platform::resolve_base_printable_key(
key.virtual_key_code,
@@ -1498,6 +1546,28 @@ fn resolve_ctrl_oem_char(key: WindowsKeyRecord) -> Option<char> {
None
}
+fn is_oem_virtual_key(vk: u16) -> bool {
+ matches!(vk, 0xba..=0xc0 | 0xdb..=0xdf | 0xe2)
+}
+
+/// Modifiers for a key record. AltGr is a character shift on character keys
+/// (which may also be dead keys that report no character yet, #3948). On keys
+/// that never type a character it is the Ctrl+Alt chord Windows reports.
+fn windows_record_modifiers(key: WindowsKeyRecord) -> crossterm::event::KeyModifiers {
+ const RIGHT_ALT_PRESSED: u32 = 0x0001;
+ const LEFT_CTRL_PRESSED: u32 = 0x0008;
+ let modifiers = windows_key_modifiers(key.control_key_state);
+ let alt_gr = key.control_key_state & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
+ == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
+ let character_key = matches!(key.virtual_key_code, 0x30..=0x39 | 0x41..=0x5a)
+ || is_oem_virtual_key(key.virtual_key_code);
+ if alt_gr && key.unicode == 0 && !character_key {
+ modifiers | crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::ALT
+ } else {
+ modifiers
+ }
+}
+
#[cfg(windows)]
fn windows_input_trace_enabled() -> bool {
std::env::var_os("HERDR_WINDOWS_INPUT_TRACE").is_some()
@@ -3063,6 +3133,28 @@ mod tests {
}
}
+ #[test]
+ fn altgr_is_ctrl_alt_only_on_keys_that_never_type_characters() {
+ let altgr = |virtual_key_code: u16, unicode: u16| WindowsKeyRecord {
+ key_down: true,
+ repeat_count: 1,
+ virtual_key_code,
+ virtual_scan_code: 0,
+ unicode,
+ control_key_state: 0x0009,
+ };
+ let ctrl_alt =
+ crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::ALT;
+
+ // PageUp and Space type nothing: the chord must not look like a plain key.
+ assert_eq!(windows_record_modifiers(altgr(0x21, 0)), ctrl_alt);
+ assert_eq!(windows_record_modifiers(altgr(0x20, 0)), ctrl_alt);
+ // Character keys keep AltGr as a character shift, dead keys included.
+ assert!(windows_record_modifiers(altgr(0x34, 0)).is_empty());
+ assert!(windows_record_modifiers(altgr(0xba, 0)).is_empty());
+ assert!(windows_record_modifiers(altgr(0x51, u16::from(b'@'))).is_empty());
+ }
+
#[test]
fn vti_altgr_dead_key_preserves_native_record_without_command_modifiers() {
// AltGr+4 press captured in #3948, Spanish ISO layout.
@@ -3094,10 +3186,12 @@ mod tests {
events
.into_iter()
.flat_map(|event| match event.to_raw_input_event() {
- crate::raw_input::RawInputEvent::Key(key) => crate::input::encode_terminal_key(
- key,
- crate::input::KeyboardProtocol::Kitty { flags },
- ),
+ crate::raw_input::RawInputEvent::Key(key) => {
+ crate::pane::test_encode_key_for_app(
+ format!("\x1b[>{flags}u").as_bytes(),
+ key,
+ )
+ }
crate::raw_input::RawInputEvent::Text(text) => {
text.as_str().as_bytes().to_vec()
}
@@ -3228,23 +3322,14 @@ mod tests {
let crate::raw_input::RawInputEvent::Key(key) = events[0].to_raw_input_event() else {
panic!("expected translated key");
};
+ assert_eq!(crate::pane::test_encode_key_for_app(b"", key.clone()), b"/");
assert_eq!(
- crate::input::encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy),
+ crate::pane::test_encode_key_for_app(b"\x1b[>7u", key.clone()),
b"/"
);
assert_eq!(
- crate::input::encode_terminal_key(
- key.clone(),
- crate::input::KeyboardProtocol::Kitty { flags: 7 },
- ),
- b"/"
- );
- assert_eq!(
- crate::input::encode_terminal_key(
- key,
- crate::input::KeyboardProtocol::Kitty { flags: 15 },
- ),
- b"\x1b[47;2:1u"
+ crate::pane::test_encode_key_for_app(b"\x1b[>15u", key),
+ b"\x1b[47;2u"
);
}
@@ -3353,7 +3438,7 @@ mod tests {
assert_eq!(key.modifiers.bits(), modifiers, "{name}: modifiers");
assert_eq!(key.generated_text.as_deref(), text, "{name}: text");
assert_eq!(
- crate::input::encode_terminal_key(key, crate::input::KeyboardProtocol::Legacy),
+ crate::pane::test_encode_key_for_app(b"", key),
expected,
"{name}: encoding"
);
diff --git a/src/client/loop_config.rs b/src/client/loop_config.rs
index 97979bbfa..c4e659178 100644
--- a/src/client/loop_config.rs
+++ b/src/client/loop_config.rs
@@ -10,6 +10,7 @@ pub(super) struct ClientLoopConfig {
pub(super) pixel_geometry_fallback: bool,
pub(super) mouse_capture_active: bool,
pub(super) host_escape_disambiguation_active: bool,
+ pub(super) host_sgr_pixel_mouse: Option<bool>,
pub(super) initial_host_input: Vec<u8>,
pub(super) endpoint_keybindings: bool,
pub(super) remote_image_paste_key:
diff --git a/src/client/mod.rs b/src/client/mod.rs
index 6a754e1fb..9ce1440e4 100644
--- a/src/client/mod.rs
+++ b/src/client/mod.rs
@@ -86,7 +86,7 @@ fn refresh_host_mouse_capture(enabled: bool, sgr_pixels: bool) {
}
#[cfg(windows)]
-use terminal_setup::{is_ssh_session, windows_vti_input_backend_enabled};
+use terminal_setup::is_ssh_session;
#[cfg(test)]
use terminal_setup::{
should_enable_host_color_scheme_reports, windows_virtual_terminal_input_mode,
@@ -205,6 +205,7 @@ fn run_client_with_mode(
pixel_geometry_fallback: kitty_graphics_enabled,
mouse_capture_active: mouse_capture,
host_escape_disambiguation_active: false,
+ host_sgr_pixel_mouse: None,
initial_host_input: Vec::new(),
endpoint_keybindings,
remote_image_paste_key,
@@ -308,6 +309,7 @@ fn run_client_with_mode(
})?;
loop_config.host_escape_disambiguation_active =
terminal_guard.host_escape_disambiguation_active();
+ loop_config.host_sgr_pixel_mouse = terminal_guard.host_sgr_pixel_mouse();
loop_config.initial_host_input = terminal_guard.take_buffered_host_input();
// Install a panic hook so the foreground client always restores its terminal.
@@ -449,6 +451,7 @@ async fn run_client_loop(
kitty_graphics_enabled: config.kitty_graphics_enabled,
pixel_geometry_enabled: config.pixel_geometry_enabled,
pixel_geometry_exact: initial_pixel_geometry_exact,
+ host_sgr_pixel_mouse: config.host_sgr_pixel_mouse,
#[cfg(unix)]
direct_graphics_response: Arc::new(Mutex::new(direct_graphics::ResponseMatcher::default())),
#[cfg(unix)]
@@ -472,6 +475,8 @@ async fn run_client_loop(
};
let mut federated = endpoint_catalog.has_enabled_ssh();
if let Some(shell) = state.shell.as_mut() {
+ shell.set_host_reports_key_releases(config.host_escape_disambiguation_active);
+ shell.set_host_erase_byte(crate::platform::terminal_erase_byte());
shell.set_graphics_cell_size(initial_cell_width_px, initial_cell_height_px);
shell.set_endpoint_catalog(&endpoint_catalog.ssh);
shell.set_endpoint_methods_for(
@@ -809,7 +814,7 @@ async fn run_client_loop(
);
if state.shell.is_some() {
if will_query_host_cell_size {
- let events = crate::raw_input::parse_raw_input_bytes_sync(&data);
+ let events = crate::raw_input::parse_framed_input(&data);
if let Some((width_px, height_px)) = reported_cell_size_from_events(&events)
{
store_reported_cell_size(&reported_cell_size, width_px, height_px);
@@ -850,7 +855,7 @@ async fn run_client_loop(
continue;
}
}
- let events = crate::raw_input::parse_raw_input_bytes_sync(&data);
+ let events = crate::raw_input::parse_framed_input(&data);
if crate::raw_input::events_require_host_mode_refresh(&events) {
refresh_host_mouse_capture(
state.mouse_capture_active,
@@ -925,7 +930,7 @@ async fn run_client_loop(
AttachInputAction::None => continue,
}
} else {
- let events = crate::raw_input::parse_raw_input_bytes_sync(&data);
+ let events = crate::raw_input::parse_framed_input(&data);
if crate::raw_input::events_require_host_surface_redraw(
&events,
state.redraw_on_focus_gained,
@@ -1979,11 +1984,12 @@ async fn run_client_loop(
enabled,
sgr_pixels,
state.pixel_geometry_exact,
+ state.host_sgr_pixel_mouse,
);
let mouse_mode_changed = enabled != state.mouse_capture_active
|| next_sgr_pixels != host_sgr_pixels_active.load(Ordering::Acquire);
#[cfg(windows)]
- if enabled && windows_vti_input_backend_enabled() && is_ssh_session() {
+ if enabled && is_ssh_session() {
_terminal_guard
.recover_windows_virtual_terminal_input()
.map_err(ClientError::ConnectionFailed)?;
@@ -1993,7 +1999,7 @@ async fn run_client_loop(
.map_err(ClientError::ConnectionFailed)?;
}
#[cfg(windows)]
- if enabled && windows_vti_input_backend_enabled() && !is_ssh_session() {
+ if enabled && !is_ssh_session() {
_terminal_guard
.recover_windows_virtual_terminal_input()
.map_err(ClientError::ConnectionFailed)?;
diff --git a/src/client/shell/input.rs b/src/client/shell/input.rs
index c7664f290..98fe28947 100644
--- a/src/client/shell/input.rs
+++ b/src/client/shell/input.rs
@@ -98,9 +98,55 @@ impl ClientShellState {
)
}
+ pub(crate) fn set_host_reports_key_releases(&mut self, reports: bool) {
+ self.host_reports_key_releases = reports;
+ }
+
+ pub(crate) fn set_host_reports_all_keys(&mut self, reports_all: bool) {
+ self.host_reports_all_keys = reports_all;
+ }
+
+ /// While the pane asks for every key as an escape code, committed text
+ /// (IME, compose) must reach it as text, not as invented key reports.
+ /// On a Kitty host switched to report-all, typed keys arrive as reports,
+ /// so any plain text is a commit (kitty sends those as text too). A legacy
+ /// host sends both as plain text; non-ASCII text has no key in the
+ /// keyboard model, so only that is treated as a commit there.
+ fn host_text_commit(&self, key: &crate::input::TerminalKey) -> Option<String> {
+ if !self.host_reports_all_keys || key.kind != KeyEventKind::Press {
+ return None;
+ }
+ let plain_text = key
+ .vt_bytes()
+ .is_some_and(|bytes| bytes.first().is_some_and(|byte| *byte != 0x1b));
+ let text = key.generated_text.as_ref().filter(|_| plain_text)?;
+ (self.host_reports_key_releases || !text.is_ascii()).then(|| text.clone())
+ }
+
+ pub(crate) fn set_host_erase_byte(&mut self, erase: Option<u8>) {
+ self.host_erase_is_ctrl_h = erase == Some(0x08);
+ }
+
+ /// A raw 0x08 (or ESC 0x08) from a host whose erase character is `^H` is
+ /// its Backspace key (#3244).
+ fn host_erase_key(&self, key: crate::input::TerminalKey) -> crate::input::TerminalKey {
+ if !self.host_erase_is_ctrl_h {
+ return key;
+ }
+ let alt = match key.vt_bytes() {
+ Some([0x08]) => KeyModifiers::empty(),
+ Some([0x1b, 0x08]) => KeyModifiers::ALT,
+ _ => return key,
+ };
+ let bytes = key.vt_bytes().map(<[u8]>::to_vec).unwrap_or_default();
+ crate::input::TerminalKey::new(KeyCode::Backspace, alt)
+ .with_kind(key.kind)
+ .with_vt_bytes(bytes)
+ }
+
#[cfg(test)]
pub(crate) fn handle_input_bytes(&mut self, data: &[u8]) -> ClientShellInput {
- self.handle_raw_events(crate::raw_input::parse_raw_input_bytes_sync(data))
+ self.handle_raw_events(crate::raw_input::parse_framed_input(data))
}
#[cfg(any(unix, test))]
@@ -109,21 +155,19 @@ impl ClientShellState {
data: &[u8],
geometry: crate::input::mouse::HostGeometry,
) -> ClientShellInput {
- let Some((x, y)) = crate::input::mouse::parse_report(data) else {
- return ClientShellInput::default();
- };
- let Some((column, row)) = geometry.cell(x, y) else {
+ let Some(report) = crate::raw_input::parse_sgr_mouse_report(data) else {
return ClientShellInput::default();
};
- let Some(cell_report) = crate::input::mouse::report_at_cell(data, column, row) else {
+ let Some((column, row)) = geometry.cell(report.x, report.y) else {
return ClientShellInput::default();
};
- let events = crate::raw_input::parse_raw_input_bytes_sync(&cell_report);
- if events.len() != 1 || !matches!(events[0], RawInputEvent::Mouse(_)) {
- return ClientShellInput::default();
- }
- self.host_mouse_pixels = Some(crate::input::mouse::HostPixels { x, y, geometry });
- let outcome = self.handle_raw_events(events);
+ self.host_mouse_pixels = Some(crate::input::mouse::HostPixels {
+ x: report.x,
+ y: report.y,
+ geometry,
+ });
+ let outcome =
+ self.handle_raw_events(vec![RawInputEvent::Mouse(report.at_cell(column, row))]);
self.host_mouse_pixels = None;
outcome
}
@@ -176,6 +220,13 @@ impl ClientShellState {
outcome.repaint = true;
}
for event in events {
+ let event = match event {
+ RawInputEvent::Key(key) => match self.host_text_commit(&key) {
+ Some(text) => RawInputEvent::Text(crate::input::TextCommit::new(text)),
+ None => RawInputEvent::Key(key),
+ },
+ other => other,
+ };
if self.handle_machine_badge_event(&event, &mut outcome) {
continue;
}
@@ -183,7 +234,10 @@ impl ClientShellState {
push_host_theme_update(&mut outcome.requests, update);
}
match event {
- RawInputEvent::Key(key) => self.handle_key(key, &mut outcome),
+ RawInputEvent::Key(key) => {
+ let key = self.host_erase_key(key);
+ self.handle_key(key, &mut outcome)
+ }
RawInputEvent::Text(text) => {
let text = text.into_string();
if matches!(
@@ -324,6 +378,11 @@ impl ClientShellState {
self.copy_input_queue.push_back(key);
return;
}
+ let key = if self.host_reports_key_releases && key.generated_text.is_some() {
+ key.with_physical_identity_hint(true)
+ } else {
+ key
+ };
let lease_key = crate::input::InputLeaseKey::new(LOCAL_INPUT_SOURCE, &key);
let key = self.input_leases.normalize_press(&lease_key, key);
match key.kind {
@@ -351,21 +410,48 @@ impl ClientShellState {
self.execute_repeat_plan(lease_key, key, plan, outcome);
}
KeyEventKind::Release => {
- if let Some(lease) = self.input_leases.remove_forwarded(&lease_key) {
- let release = lease
+ let Some(lease) = self.take_release_lease(&lease_key, &key) else {
+ return;
+ };
+ let crate::input::InputLease::Forwarded(lease) = lease else {
+ // Herdr consumed the press; its release stays with Herdr.
+ return;
+ };
+ // A native record is released as the recorded key. A VT release
+ // report already names its key and shifted character exactly,
+ // except a non-Latin Ctrl chord pressed as its physical key: it
+ // is released as that key, matching the press the pane saw.
+ let physical_chord = key.base_layout_key().map(KeyCode::Char)
+ == Some(lease.key.code)
+ && key.code != lease.key.code;
+ let release = if key.physical_key_id().is_some() || physical_chord {
+ lease
.key
.with_modifiers(key.modifiers)
- .with_kind(KeyEventKind::Release);
- self.push_pane_key(lease.target, release, outcome);
+ .with_kind(KeyEventKind::Release)
} else {
- let _ = self.input_leases.remove(&lease_key);
- }
+ key
+ };
+ self.push_pane_key(lease.target, release, outcome);
}
}
}
fn release_input_leases(&mut self, outcome: &mut ClientShellInput) {
for lease in self.input_leases.remove_source(LOCAL_INPUT_SOURCE) {
+ // A press that arrived as plain text (IME commits, and printable keys
+ // the host sends as text) reached the pane as text, not as a key
+ // event. IME commits never get a host release, so inventing one per
+ // character is noise. Key reports, with or without text, still get
+ // their release.
+ let plain_text_press = lease.key.generated_text.is_some()
+ && lease
+ .key
+ .vt_bytes()
+ .is_some_and(|bytes| bytes.first().is_some_and(|byte| *byte != 0x1b));
+ if plain_text_press {
+ continue;
+ }
self.push_pane_key(
lease.target,
lease.key.with_kind(KeyEventKind::Release),
@@ -1029,6 +1115,51 @@ impl ClientShellState {
.map(crate::protocol::ClientClipboardImageTarget::Pane)
}
+ /// The tracked press for a release. A press that arrived as text ("A") is
+ /// reported released as its key ("a", shifted alternate "A"), possibly after
+ /// Shift was let go, so the shifted alternate and the letter's other case
+ /// also match.
+ fn take_release_lease(
+ &mut self,
+ lease_key: &crate::input::InputLeaseKey<u8>,
+ key: &crate::input::TerminalKey,
+ ) -> Option<crate::input::InputLease<ClientInputContext, ClientInputTarget>> {
+ if let Some(lease) = self.input_leases.remove(lease_key) {
+ return Some(lease);
+ }
+ let KeyCode::Char(c) = key.code else {
+ return None;
+ };
+ fn single(mut chars: impl Iterator<Item = char>) -> Option<char> {
+ match (chars.next(), chars.next()) {
+ (Some(only), None) => Some(only),
+ _ => None,
+ }
+ }
+ let other_case = if c.is_lowercase() {
+ single(c.to_uppercase())
+ } else {
+ single(c.to_lowercase())
+ }
+ .filter(|other| *other != c);
+ key.shifted_codepoint
+ .and_then(char::from_u32)
+ .into_iter()
+ .chain(other_case)
+ // A Ctrl chord on a non-Latin layout was leased as its physical key;
+ // its release names the layout character if Ctrl was let go first.
+ .chain(key.base_layout_key())
+ .find_map(|candidate| {
+ self.input_leases.remove(&crate::input::InputLeaseKey::new(
+ LOCAL_INPUT_SOURCE,
+ &crate::input::TerminalKey::new(KeyCode::Char(candidate), key.modifiers),
+ ))
+ })
+ // Shifted punctuation ("?") released after Shift: the report names
+ // only the unshifted key ("/"), which depends on the layout.
+ .or_else(|| self.input_leases.remove_sole_text_press(LOCAL_INPUT_SOURCE))
+ }
+
fn popup_input_target(&self) -> Option<ClientInputTarget> {
self.popup_terminal_id
.as_ref()
diff --git a/src/client/shell/state.rs b/src/client/shell/state.rs
index 9c69fbe56..19eb19d1e 100644
--- a/src/client/shell/state.rs
+++ b/src/client/shell/state.rs
@@ -907,6 +907,15 @@ pub(crate) struct ClientShellState {
pub(super) pane_mouse_gesture: Option<ClientPaneMouseGesture>,
pub(super) link_hover: Option<super::link_hover::LinkHover>,
pub(super) url_click_consumes_until_up: bool,
+ /// The host terminal reports key releases (Kitty event types), so text
+ /// presses can be tracked until their release arrives.
+ pub(super) host_reports_key_releases: bool,
+ /// The host tty's erase character is `^H`: a raw 0x08 is Backspace, not
+ /// Ctrl+H (MobaXterm, PuTTY-style terminals; tmux reads VERASE the same way).
+ pub(super) host_erase_is_ctrl_h: bool,
+ /// The focused pane asks for every key as an escape code, so Herdr pushed
+ /// report-all to the host; plain text input then reaches it as text.
+ pub(super) host_reports_all_keys: bool,
pub(super) replaying_url_click: bool,
pub(super) selection: Option<crate::selection::Selection<String>>,
pub(super) last_pane_click: Option<ClientPaneClick>,
@@ -1072,6 +1081,9 @@ impl ClientShellState {
pane_mouse_gesture: None,
link_hover: None,
url_click_consumes_until_up: false,
+ host_reports_key_releases: false,
+ host_erase_is_ctrl_h: false,
+ host_reports_all_keys: false,
replaying_url_click: false,
selection: None,
last_pane_click: None,
diff --git a/src/client/shell/tests/input.rs b/src/client/shell/tests/input.rs
index 145c7ae6b..941cee92a 100644
--- a/src/client/shell/tests/input.rs
+++ b/src/client/shell/tests/input.rs
@@ -282,6 +282,216 @@ fn invalid_experimental_reload_keeps_input_source_preference() {
assert!(!shell.switch_ascii_input_source_in_prefix);
}
+fn pane_key_events(
+ outcome: &ClientShellInput,
+) -> Vec<(
+ crate::protocol::ClientKeyCode,
+ crate::protocol::ClientKeyKind,
+)> {
+ outcome
+ .requests
+ .iter()
+ .filter_map(|request| match request {
+ ClientMessage::ClientShellPaneInput { events, .. } => Some(events),
+ _ => None,
+ })
+ .flatten()
+ .filter_map(|event| match event {
+ ClientPaneInputEvent::Key { code, kind, .. } => Some((code.clone(), *kind)),
+ _ => None,
+ })
+ .collect()
+}
+
+#[test]
+fn text_press_release_survives_shift_released_first_and_never_becomes_a_repeat() {
+ use crate::protocol::{ClientKeyCode, ClientKeyKind};
+
+ let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));
+ state.set_host_reports_key_releases(true);
+ state.set_snapshot(Box::new(snapshot()));
+ state.set_pane_surface(surface());
+
+ // Shift+A arrives as text; Shift is let go before A, so the release names
+ // plain `a` with no shifted alternate.
+ let press = state.handle_input_bytes(b"A");
+ assert_eq!(
+ pane_key_events(&press),
+ [(ClientKeyCode::Char('A'), ClientKeyKind::Press)]
+ );
+ let release = state.handle_input_bytes(b"\x1b[97;1:3u");
+ assert_eq!(
+ pane_key_events(&release),
+ [(ClientKeyCode::Char('a'), ClientKeyKind::Release)]
+ );
+
+ // A text press whose release never arrived must not turn the next press
+ // into a repeat routed to the old target.
+ let _ = state.handle_input_bytes(b"%");
+ let again = state.handle_input_bytes(b"%");
+ assert_eq!(
+ pane_key_events(&again),
+ [(ClientKeyCode::Char('%'), ClientKeyKind::Press)]
+ );
+}
+
+#[test]
+fn raw_backspace_follows_the_host_tty_erase_character() {
+ use crate::protocol::{ClientKeyCode, ClientKeyKind};
+
+ // #3244: MobaXterm sends 0x08 for Backspace and its tty says erase is ^H.
+ for (erase, plain, alt) in [
+ (
+ Some(0x08),
+ ClientKeyCode::Backspace,
+ ClientKeyCode::Backspace,
+ ),
+ (
+ Some(0x7f),
+ ClientKeyCode::Char('h'),
+ ClientKeyCode::Char('h'),
+ ),
+ (None, ClientKeyCode::Char('h'), ClientKeyCode::Char('h')),
+ ] {
+ let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));
+ state.set_host_erase_byte(erase);
+ state.set_snapshot(Box::new(snapshot()));
+ state.set_pane_surface(surface());
+
+ let press = state.handle_input_bytes(b"\x08");
+ assert_eq!(
+ pane_key_events(&press),
+ [(plain.clone(), ClientKeyKind::Press)],
+ "erase {erase:?}"
+ );
+ let alt_press = state.handle_input_bytes(b"\x1b\x08");
+ assert_eq!(
+ pane_key_events(&alt_press),
+ [(alt, ClientKeyKind::Press)],
+ "alt, erase {erase:?}"
+ );
+ }
+}
+
+#[test]
+fn shifted_punctuation_release_after_shift_reaches_the_pane() {
+ use crate::protocol::{ClientKeyCode, ClientKeyKind};
+
+ let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));
+ state.set_host_reports_key_releases(true);
+ state.set_snapshot(Box::new(snapshot()));
+ state.set_pane_surface(surface());
+
+ // "?" arrives as text; with Shift let go first the release names only the
+ // unshifted key, which no layout-free rule can relate to "?".
+ let _ = state.handle_input_bytes(b"?");
+ let release = state.handle_input_bytes(b"\x1b[47;1:3u");
+ assert_eq!(
+ pane_key_events(&release),
+ [(ClientKeyCode::Char('/'), ClientKeyKind::Release)]
+ );
+ // Nothing is left to be released later as a stale "?".
+ let blur = state.handle_input_bytes(b"\x1b[O");
+ assert!(pane_key_events(&blur).is_empty());
+
+ // With two text keys held the release is ambiguous and nothing is taken.
+ let _ = state.handle_input_bytes(b"?");
+ let _ = state.handle_input_bytes(b"!");
+ let ambiguous = state.handle_input_bytes(b"\x1b[47;1:3u");
+ assert!(pane_key_events(&ambiguous).is_empty());
+}
+
+#[test]
+fn held_key_reports_keep_their_release_around_ime_commits_and_focus_loss() {
+ use crate::protocol::{ClientKeyCode, ClientKeyKind};
+
+ let new_state = || {
+ let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));
+ state.set_host_reports_key_releases(true);
+ state.set_snapshot(Box::new(snapshot()));
+ state.set_pane_surface(surface());
+ state
+ };
+
+ // A key report carrying its text (report-all host) is a real held key:
+ // losing focus releases it.
+ let mut state = new_state();
+ let _ = state.handle_input_bytes(b"\x1b[97;;97u");
+ let blur = state.handle_input_bytes(b"\x1b[O");
+ assert_eq!(
+ pane_key_events(&blur),
+ [(ClientKeyCode::Char('a'), ClientKeyKind::Release)]
+ );
+
+ // Many IME commits while a key is held never displace that key: its
+ // release still reaches the pane as the held key.
+ let mut state = new_state();
+ let _ = state.handle_input_bytes(b"\x1b[120;;120u");
+ for ch in
+ "\u{65e5}\u{672c}\u{8a9e}\u{d55c}\u{ad6d}\u{c5b4}\u{4e2d}\u{6587}\u{3042}\u{3044}\u{3046}"
+ .chars()
+ {
+ let _ = state.handle_input_bytes(ch.to_string().as_bytes());
+ }
+ let release = state.handle_input_bytes(b"\x1b[120;1:3u");
+ assert_eq!(
+ pane_key_events(&release),
+ [(ClientKeyCode::Char('x'), ClientKeyKind::Release)]
+ );
+}
+
+#[test]
+fn non_latin_ctrl_chord_release_matches_after_ctrl_is_let_go() {
+ use crate::protocol::{ClientKeyCode, ClientKeyKind};
+
+ let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));
+ state.set_host_reports_key_releases(true);
+ state.set_snapshot(Box::new(snapshot()));
+ state.set_pane_surface(surface());
+
+ // Russian layout: Ctrl+\u{441} is the C key; Ctrl goes up before C.
+ let press = state.handle_input_bytes(b"\x1b[1089::99;5u");
+ assert_eq!(
+ pane_key_events(&press),
+ [(ClientKeyCode::Char('c'), ClientKeyKind::Press)]
+ );
+ let release = state.handle_input_bytes(b"\x1b[1089::99;1:3u");
+ assert_eq!(
+ pane_key_events(&release),
+ [(ClientKeyCode::Char('c'), ClientKeyKind::Release)]
+ );
+
+ // Plain Cyrillic typing still releases as its own key.
+ let _ = state.handle_input_bytes(b"\x1b[1089::99;;1089u");
+ let release = state.handle_input_bytes(b"\x1b[1089::99;1:3u");
+ assert_eq!(
+ pane_key_events(&release),
+ [(ClientKeyCode::Char('\u{441}'), ClientKeyKind::Release)]
+ );
+}
+
+#[test]
+fn unmatched_release_never_takes_a_held_key_while_herdr_owns_another_press() {
+ use crate::protocol::{ClientKeyCode, ClientKeyKind};
+
+ let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));
+ state.set_host_reports_key_releases(true);
+ state.set_snapshot(Box::new(snapshot()));
+ state.set_pane_surface(surface());
+
+ // Hold `a` in the pane, then press the prefix: Herdr owns that press.
+ let _ = state.handle_input_bytes(b"a");
+ let _ = state.handle_input_bytes(b"\x1b[98;5u");
+ // A release the leases cannot name must not be charged to the held `a`.
+ let stray = state.handle_input_bytes(b"\x1b[47;1:3u");
+ assert!(pane_key_events(&stray).is_empty());
+ let release = state.handle_input_bytes(b"\x1b[97;1:3u");
+ assert_eq!(
+ pane_key_events(&release),
+ [(ClientKeyCode::Char('a'), ClientKeyKind::Release)]
+ );
+}
+
#[test]
fn physical_release_uses_the_leased_press_code_with_current_modifiers() {
let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));
diff --git a/src/client/shell/tests/input_conformance.rs b/src/client/shell/tests/input_conformance.rs
new file mode 100644
index 000000000..a3382e1b0
--- /dev/null
+++ b/src/client/shell/tests/input_conformance.rs
@@ -0,0 +1,1636 @@
+//! Keyboard transparency conformance.
+//!
+//! Herdr should be invisible to the application in a pane: for every keystroke,
+//! the pane must receive the bytes it would receive running directly in the
+//! host terminal. The oracle is libghostty's encoder fed the same key event the
+//! Ghostty app builds from an OS key event. The Herdr path is the real one:
+//! host bytes -> host framer -> client shell routing -> server pane input ->
+//! pane encoder, with the pane's modes set by application output.
+//!
+//! Keystrokes whose host bytes cannot distinguish keys the pane would see
+//! differently are counted as host-lossy, not as Herdr failures.
+
+// The Unix-host checks are compiled out on Windows, leaving helpers that only
+// they use.
+#![cfg_attr(windows, allow(dead_code))]
+
+use std::collections::{BTreeMap, HashMap};
+
+use super::*;
+
+use crate::ghostty::{self, ffi};
+
+#[derive(Clone, Copy)]
+struct KeyDef {
+ name: &'static str,
+ key: ffi::GhosttyKey,
+ /// US layout text: (unshifted, shifted).
+ text: Option<(char, char)>,
+}
+
+const fn text(name: &'static str, key: ffi::GhosttyKey, base: char, shifted: char) -> KeyDef {
+ KeyDef {
+ name,
+ key,
+ text: Some((base, shifted)),
+ }
+}
+
+const fn func(name: &'static str, key: ffi::GhosttyKey) -> KeyDef {
+ KeyDef {
+ name,
+ key,
+ text: None,
+ }
+}
+
+const KEYS: &[KeyDef] = &[
+ text("a", ffi::GhosttyKey_GHOSTTY_KEY_A, 'a', 'A'),
+ text("b", ffi::GhosttyKey_GHOSTTY_KEY_B, 'b', 'B'),
+ text("c", ffi::GhosttyKey_GHOSTTY_KEY_C, 'c', 'C'),
+ text("d", ffi::GhosttyKey_GHOSTTY_KEY_D, 'd', 'D'),
+ text("e", ffi::GhosttyKey_GHOSTTY_KEY_E, 'e', 'E'),
+ text("f", ffi::GhosttyKey_GHOSTTY_KEY_F, 'f', 'F'),
+ text("g", ffi::GhosttyKey_GHOSTTY_KEY_G, 'g', 'G'),
+ text("h", ffi::GhosttyKey_GHOSTTY_KEY_H, 'h', 'H'),
+ text("i", ffi::GhosttyKey_GHOSTTY_KEY_I, 'i', 'I'),
+ text("j", ffi::GhosttyKey_GHOSTTY_KEY_J, 'j', 'J'),
+ text("k", ffi::GhosttyKey_GHOSTTY_KEY_K, 'k', 'K'),
+ text("l", ffi::GhosttyKey_GHOSTTY_KEY_L, 'l', 'L'),
+ text("m", ffi::GhosttyKey_GHOSTTY_KEY_M, 'm', 'M'),
+ text("n", ffi::GhosttyKey_GHOSTTY_KEY_N, 'n', 'N'),
+ text("o", ffi::GhosttyKey_GHOSTTY_KEY_O, 'o', 'O'),
+ text("p", ffi::GhosttyKey_GHOSTTY_KEY_P, 'p', 'P'),
+ text("q", ffi::GhosttyKey_GHOSTTY_KEY_Q, 'q', 'Q'),
+ text("r", ffi::GhosttyKey_GHOSTTY_KEY_R, 'r', 'R'),
+ text("s", ffi::GhosttyKey_GHOSTTY_KEY_S, 's', 'S'),
+ text("t", ffi::GhosttyKey_GHOSTTY_KEY_T, 't', 'T'),
+ text("u", ffi::GhosttyKey_GHOSTTY_KEY_U, 'u', 'U'),
+ text("v", ffi::GhosttyKey_GHOSTTY_KEY_V, 'v', 'V'),
+ text("w", ffi::GhosttyKey_GHOSTTY_KEY_W, 'w', 'W'),
+ text("x", ffi::GhosttyKey_GHOSTTY_KEY_X, 'x', 'X'),
+ text("y", ffi::GhosttyKey_GHOSTTY_KEY_Y, 'y', 'Y'),
+ text("z", ffi::GhosttyKey_GHOSTTY_KEY_Z, 'z', 'Z'),
+ text("0", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_0, '0', ')'),
+ text("1", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_1, '1', '!'),
+ text("2", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_2, '2', '@'),
+ text("3", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_3, '3', '#'),
+ text("4", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_4, '4', '$'),
+ text("5", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_5, '5', '%'),
+ text("6", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_6, '6', '^'),
+ text("7", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_7, '7', '&'),
+ text("8", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_8, '8', '*'),
+ text("9", ffi::GhosttyKey_GHOSTTY_KEY_DIGIT_9, '9', '('),
+ text("`", ffi::GhosttyKey_GHOSTTY_KEY_BACKQUOTE, '`', '~'),
+ text("-", ffi::GhosttyKey_GHOSTTY_KEY_MINUS, '-', '_'),
+ text("=", ffi::GhosttyKey_GHOSTTY_KEY_EQUAL, '=', '+'),
+ text("[", ffi::GhosttyKey_GHOSTTY_KEY_BRACKET_LEFT, '[', '{'),
+ text("]", ffi::GhosttyKey_GHOSTTY_KEY_BRACKET_RIGHT, ']', '}'),
+ text("\\", ffi::GhosttyKey_GHOSTTY_KEY_BACKSLASH, '\\', '|'),
+ text(";", ffi::GhosttyKey_GHOSTTY_KEY_SEMICOLON, ';', ':'),
+ text("'", ffi::GhosttyKey_GHOSTTY_KEY_QUOTE, '\'', '"'),
+ text(",", ffi::GhosttyKey_GHOSTTY_KEY_COMMA, ',', '<'),
+ text(".", ffi::GhosttyKey_GHOSTTY_KEY_PERIOD, '.', '>'),
+ text("/", ffi::GhosttyKey_GHOSTTY_KEY_SLASH, '/', '?'),
+ text("space", ffi::GhosttyKey_GHOSTTY_KEY_SPACE, ' ', ' '),
+ func("enter", ffi::GhosttyKey_GHOSTTY_KEY_ENTER),
+ func("tab", ffi::GhosttyKey_GHOSTTY_KEY_TAB),
+ func("backspace", ffi::GhosttyKey_GHOSTTY_KEY_BACKSPACE),
+ func("escape", ffi::GhosttyKey_GHOSTTY_KEY_ESCAPE),
+ func("up", ffi::GhosttyKey_GHOSTTY_KEY_ARROW_UP),
+ func("down", ffi::GhosttyKey_GHOSTTY_KEY_ARROW_DOWN),
+ func("left", ffi::GhosttyKey_GHOSTTY_KEY_ARROW_LEFT),
+ func("right", ffi::GhosttyKey_GHOSTTY_KEY_ARROW_RIGHT),
+ func("home", ffi::GhosttyKey_GHOSTTY_KEY_HOME),
+ func("end", ffi::GhosttyKey_GHOSTTY_KEY_END),
+ func("pageup", ffi::GhosttyKey_GHOSTTY_KEY_PAGE_UP),
+ func("pagedown", ffi::GhosttyKey_GHOSTTY_KEY_PAGE_DOWN),
+ func("insert", ffi::GhosttyKey_GHOSTTY_KEY_INSERT),
+ func("delete", ffi::GhosttyKey_GHOSTTY_KEY_DELETE),
+ func("f1", ffi::GhosttyKey_GHOSTTY_KEY_F1),
+ func("f2", ffi::GhosttyKey_GHOSTTY_KEY_F2),
+ func("f3", ffi::GhosttyKey_GHOSTTY_KEY_F3),
+ func("f4", ffi::GhosttyKey_GHOSTTY_KEY_F4),
+ func("f5", ffi::GhosttyKey_GHOSTTY_KEY_F5),
+ func("f6", ffi::GhosttyKey_GHOSTTY_KEY_F6),
+ func("f7", ffi::GhosttyKey_GHOSTTY_KEY_F7),
+ func("f8", ffi::GhosttyKey_GHOSTTY_KEY_F8),
+ func("f9", ffi::GhosttyKey_GHOSTTY_KEY_F9),
+ func("f10", ffi::GhosttyKey_GHOSTTY_KEY_F10),
+ func("f11", ffi::GhosttyKey_GHOSTTY_KEY_F11),
+ func("f12", ffi::GhosttyKey_GHOSTTY_KEY_F12),
+];
+
+/// Modes an application can request by writing to its terminal.
+const PANE_MODES: &[(&str, &[u8])] = &[
+ ("legacy", b""),
+ ("legacy+decckm", b"\x1b[?1h"),
+ ("modifyOtherKeys1", b"\x1b[>4;1m"),
+ ("modifyOtherKeys2", b"\x1b[>4;2m"),
+ ("kitty1", b"\x1b[>1u"),
+ ("kitty3", b"\x1b[>3u"),
+ ("kitty7", b"\x1b[>7u"),
+ ("kitty11", b"\x1b[>11u"),
+ ("kitty15", b"\x1b[>15u"),
+ ("kitty31", b"\x1b[>31u"),
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+enum HostProfile {
+ /// Kitty keyboard host (Ghostty, kitty, WezTerm, foot...). Herdr pushes 7,
+ /// or 31 while the pane wants all keys reported.
+ Kitty,
+ /// Host without an enhanced keyboard protocol.
+ Legacy,
+}
+
+impl HostProfile {
+ fn name(self) -> &'static str {
+ match self {
+ Self::Kitty => "kitty-host",
+ Self::Legacy => "legacy-host",
+ }
+ }
+
+ fn setup(self, pane_mode: &[u8]) -> &'static [u8] {
+ match self {
+ Self::Kitty if pane_mode == b"\x1b[>11u" || pane_mode == b"\x1b[>15u" => b"\x1b[>31u",
+ Self::Kitty if pane_mode == b"\x1b[>31u" => b"\x1b[>31u",
+ Self::Kitty => b"\x1b[>7u",
+ Self::Legacy => b"",
+ }
+ }
+}
+
+const MODS: [(u16, &str); 4] = [
+ (ghostty::MOD_CTRL, "ctrl"),
+ (ghostty::MOD_ALT, "alt"),
+ (ghostty::MOD_SHIFT, "shift"),
+ (ghostty::MOD_SUPER, "super"),
+];
+
+fn mods_name(mods: u16) -> String {
+ let mut parts: Vec<&str> = MODS
+ .iter()
+ .filter(|(bit, _)| mods & bit != 0)
+ .map(|(_, name)| *name)
+ .collect();
+ if parts.is_empty() {
+ parts.push("plain");
+ }
+ parts.join("+")
+}
+
+/// Host bytes for one keystroke: (press, release).
+type HostKeystroke = (Vec<u8>, Vec<u8>);
+
+struct Oracle {
+ _terminal: ghostty::Terminal,
+ encoder: ghostty::KeyEncoder,
+}
+
+impl Oracle {
+ fn new(app_output: &[u8]) -> Self {
+ let mut terminal = ghostty::Terminal::new(80, 24, 0).expect("terminal");
+ terminal.write(app_output);
+ let mut encoder = ghostty::KeyEncoder::new().expect("encoder");
+ encoder.set_from_terminal(&terminal);
+ // Keystrokes here carry an interpreted Alt, as on Linux; keep the oracle
+ // identical on macOS, where libghostty would otherwise treat Option as text.
+ encoder.set_macos_option_as_alt(true);
+ Self {
+ _terminal: terminal,
+ encoder,
+ }
+ }
+
+ /// Bytes for one keystroke (press then release), built like the Ghostty app
+ /// builds key events from the OS: physical key, modifiers, layout text, the
+ /// unshifted codepoint, and Shift consumed when it produced the text.
+ fn keystroke(&mut self, def: KeyDef, mods: u16) -> HostKeystroke {
+ let press = self.encode(def, mods, ffi::GhosttyKeyAction_GHOSTTY_KEY_ACTION_PRESS);
+ let release = self.encode(def, mods, ffi::GhosttyKeyAction_GHOSTTY_KEY_ACTION_RELEASE);
+ (press, release)
+ }
+
+ fn encode(&mut self, def: KeyDef, mods: u16, action: ffi::GhosttyKeyAction) -> Vec<u8> {
+ let mut event = ghostty::KeyEvent::new().expect("key event");
+ event.set_key(def.key);
+ event.set_mods(mods);
+ event.set_action(action);
+ let utf8;
+ if let Some((base, shifted)) = def.text {
+ let shift = mods & ghostty::MOD_SHIFT != 0;
+ utf8 = if shift { shifted } else { base }.to_string();
+ event.set_utf8(&utf8);
+ event.set_unshifted_codepoint(base as u32);
+ if shift && shifted != base {
+ event.set_consumed_mods(ghostty::MOD_SHIFT);
+ }
+ }
+ self.encoder.encode(&event).expect("encode")
+ }
+}
+
+/// Panes that negotiated nothing. Like Ghostty, modifyOtherKeys level 1 counts
+/// as nothing.
+fn is_legacy_pane(pane_mode: &[u8]) -> bool {
+ matches!(pane_mode, b"" | b"\x1b[?1h" | b"\x1b[>4;1m")
+}
+
+/// Agreed exception table: panes that negotiated no keyboard protocol keep the
+/// classic bytes for keys where Ghostty's escape sequences break shells, and
+/// get no Super chords (see `is_legacy_pane` use above).
+fn legacy_shell_exception(pane_mode: &[u8], key: &str, mods: u16) -> Option<Vec<u8>> {
+ if !is_legacy_pane(pane_mode) {
+ return None;
+ }
+ let alt = mods & ghostty::MOD_ALT != 0;
+ let base = mods & !ghostty::MOD_ALT;
+ let classic: &[u8] = match (key, base) {
+ ("enter", m) if m != 0 => b"\r",
+ ("m", ghostty::MOD_CTRL) => b"\r",
+ ("i", ghostty::MOD_CTRL) | ("tab", ghostty::MOD_CTRL) => b"\t",
+ ("[", ghostty::MOD_CTRL) => b"\x1b",
+ // Real terminals (lab: Alacritty, WezTerm) send the control byte.
+ (letter, m)
+ if m == ghostty::MOD_CTRL | ghostty::MOD_SHIFT
+ && letter.len() == 1
+ && letter.as_bytes()[0].is_ascii_lowercase() =>
+ {
+ let control = [letter.as_bytes()[0] & 0x1f];
+ return Some(if alt {
+ [b"\x1b".as_slice(), &control].concat()
+ } else {
+ control.to_vec()
+ });
+ }
+ _ => return None,
+ };
+ Some(if alt {
+ [b"\x1b", classic].concat()
+ } else {
+ classic.to_vec()
+ })
+}
+
+struct HerdrPath {
+ state: ClientShellState,
+ framer: crate::raw_input::RawInputByteFramer,
+ runtime: crate::terminal::TerminalRuntime,
+ rx: tokio::sync::mpsc::Receiver<bytes::Bytes>,
+ host: HostProfile,
+ host_reports_all: bool,
+}
+
+impl HerdrPath {
+ fn new(host: HostProfile, app_output: &[u8]) -> Self {
+ // Mirrors the client: report-all is pushed to the host while the pane
+ // asks for it (`HostProfile::setup` picks 31 for those panes).
+ let host_reports_all = matches!(app_output, b"\x1b[>11u" | b"\x1b[>15u" | b"\x1b[>31u");
+ let (runtime, mut rx) =
+ crate::terminal::TerminalRuntime::test_with_channel_and_scrollback_bytes(
+ 80, 24, 0, b"", 4096,
+ );
+ runtime.test_process_pty_bytes(app_output);
+ while rx.try_recv().is_ok() {}
+ Self {
+ state: Self::fresh_state(host, host_reports_all),
+ framer: Self::fresh_framer(host),
+ runtime,
+ rx,
+ host,
+ host_reports_all,
+ }
+ }
+
+ fn fresh_state(host: HostProfile, host_reports_all: bool) -> ClientShellState {
+ let mut state = ClientShellState::new(ClientShellConfig::from_config(&Config::default()));
+ // Mirrors the client: Herdr pushes Kitty event types on Kitty hosts.
+ state.set_host_reports_key_releases(host == HostProfile::Kitty);
+ state.set_host_reports_all_keys(host_reports_all);
+ state.set_snapshot(Box::new(snapshot()));
+ state.set_pane_surface(surface());
+ state
+ }
+
+ fn fresh_framer(host: HostProfile) -> crate::raw_input::RawInputByteFramer {
+ #[allow(unused_mut)] // only mutated on unix
+ let mut framer = crate::raw_input::RawInputByteFramer::for_host_input();
+ #[cfg(unix)]
+ framer.set_host_escape_disambiguation_active(host == HostProfile::Kitty);
+ #[cfg(not(unix))]
+ let _ = host;
+ framer
+ }
+
+ /// Collect pane input from one client outcome, the way the client loop does:
+ /// side requests (pane focus) are ignored, link lookups get a no-link answer
+ /// and the held mouse events are replayed. Returns true when Herdr kept the
+ /// input for itself.
+ fn absorb(
+ &mut self,
+ outcome: ClientShellInput,
+ events: &mut Vec<ClientPaneInputEvent>,
+ ) -> bool {
+ let mut owned = outcome.detach;
+ for request in outcome.requests {
+ if let ClientMessage::ClientShellPaneInput { events: batch, .. } = request {
+ events.extend(batch);
+ }
+ }
+ let mut replay = Vec::new();
+ for action in outcome.actions {
+ match action {
+ ClientShellAction::Endpoint {
+ boot_id, request, ..
+ } if matches!(
+ request.method,
+ crate::api::schema::Method::PaneLinkActivate(_)
+ ) =>
+ {
+ let (_, actions) = self.state.handle_endpoint_result(
+ &boot_id,
+ &request.id,
+ Ok(crate::api::schema::ResponseResult::PaneLinkActivated {
+ url: None,
+ handled: false,
+ }),
+ );
+ for action in actions {
+ match action {
+ ClientShellAction::ReplayMouse(mouse) => replay.extend(mouse),
+ _ => owned = true,
+ }
+ }
+ }
+ ClientShellAction::Endpoint { .. } => {}
+ ClientShellAction::ReplayMouse(mouse) => replay.extend(mouse),
+ _ => owned = true,
+ }
+ }
+ if !replay.is_empty() {
+ let outcome = self.state.replay_mouse_events(replay);
+ owned |= self.absorb(outcome, events);
+ }
+ owned
+ }
+
+ fn reset_client(&mut self) {
+ self.state = Self::fresh_state(self.host, self.host_reports_all);
+ self.framer = Self::fresh_framer(self.host);
+ }
+
+ /// Feed one host write, then let idle flushes run. Returns None when Herdr
+ /// itself consumed the key (prefix, binding, mode change).
+ fn feed(&mut self, host_bytes: &[u8]) -> Option<Vec<u8>> {
+ let mut chunks = self.framer.push(host_bytes);
+ for _ in 0..3 {
+ if !self.framer.has_pending_input() {
+ break;
+ }
+ chunks.extend(self.framer.flush_timeout());
+ }
+ let outcomes = chunks
+ .iter()
+ .map(|chunk| self.state.handle_input_bytes(chunk))
+ .collect();
+ self.deliver(outcomes)
+ }
+
+ /// Route client outcomes through server pane input and collect the bytes the
+ /// pane receives. None when Herdr kept the input for itself.
+ fn deliver(&mut self, outcomes: Vec<ClientShellInput>) -> Option<Vec<u8>> {
+ let mut events = Vec::new();
+ let mut herdr_owned = false;
+ for outcome in outcomes {
+ herdr_owned |= self.absorb(outcome, &mut events);
+ }
+ herdr_owned |= self.state.mode != ClientShellMode::Terminal || self.state.overlay.is_some();
+ if herdr_owned {
+ return None;
+ }
+ let mut out = Vec::new();
+ if let Err(err) =
+ crate::server::pane_input::test_apply_client_pane_input_events(&self.runtime, &events)
+ {
+ out.extend_from_slice(format!("<server error: {err}>").as_bytes());
+ }
+ while let Ok(bytes) = self.rx.try_recv() {
+ out.extend_from_slice(&bytes);
+ }
+ Some(out)
+ }
+}
+
+/// Kitty's default event type is press, so `;mods:1` and `;mods` are the same
+/// report. Strip the explicit form so equivalent encodings compare equal.
+fn normalize_kitty_press(bytes: &[u8]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i..].starts_with(b":1")
+ && bytes
+ .get(i + 2)
+ .is_some_and(|b| matches!(b, b'u' | b'~' | b';') || b.is_ascii_uppercase())
+ {
+ i += 2;
+ continue;
+ }
+ out.push(bytes[i]);
+ i += 1;
+ }
+ out
+}
+
+#[derive(Default)]
+struct Tally {
+ scored: usize,
+ passed: usize,
+ equivalent: usize,
+ host_lossy: usize,
+ herdr_owned: usize,
+}
+
+struct Failure {
+ host: &'static str,
+ pane: &'static str,
+ keystroke: String,
+ expected: Vec<u8>,
+ actual: Vec<u8>,
+}
+
+fn show(bytes: &[u8]) -> String {
+ bytes.escape_ascii().to_string()
+}
+
+struct Report {
+ by_cell: BTreeMap<(&'static str, &'static str, &'static str), Tally>,
+ failures: Vec<Failure>,
+ owned: Vec<String>,
+}
+
+fn run_keyboard_conformance() -> Report {
+ let mut report = Report {
+ by_cell: BTreeMap::new(),
+ failures: Vec::new(),
+ owned: Vec::new(),
+ };
+ for host in [HostProfile::Kitty, HostProfile::Legacy] {
+ for &(pane_name, pane_mode) in PANE_MODES {
+ let mut host_oracle = Oracle::new(host.setup(pane_mode));
+ let mut direct_oracle = Oracle::new(pane_mode);
+
+ let mut cases = Vec::new();
+ for def in KEYS {
+ for mods in 0u16..16 {
+ let mods = MODS
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| mods & (1 << i) != 0)
+ .fold(0, |acc, (_, (bit, _))| acc | bit);
+ let host_bytes = host_oracle.keystroke(*def, mods);
+ let (mut press, release) = direct_oracle.keystroke(*def, mods);
+ if is_legacy_pane(pane_mode) && mods & ghostty::MOD_SUPER != 0 {
+ press = Vec::new();
+ } else if let Some(classic) = legacy_shell_exception(pane_mode, def.name, mods)
+ {
+ press = classic;
+ }
+ // A host that never reports releases gives nobody a release to forward.
+ let expected = if host_bytes.1.is_empty() {
+ press
+ } else {
+ [press, release].concat()
+ };
+ cases.push((*def, mods, host_bytes, expected));
+ }
+ }
+
+ let mut expected_by_host_bytes: HashMap<&HostKeystroke, Vec<&Vec<u8>>> = HashMap::new();
+ for (_, mods, host_bytes, expected) in &cases {
+ if host == HostProfile::Legacy && mods & ghostty::MOD_SUPER != 0 {
+ continue;
+ }
+ expected_by_host_bytes
+ .entry(host_bytes)
+ .or_default()
+ .push(expected);
+ }
+
+ let mut herdr = HerdrPath::new(host, pane_mode);
+ for (def, mods, host_bytes, expected) in &cases {
+ let group = if mods & ghostty::MOD_SUPER != 0 {
+ "super"
+ } else {
+ "core"
+ };
+ let tally = report
+ .by_cell
+ .entry((host.name(), pane_name, group))
+ .or_default();
+ // Legacy hosts cannot report Super at all (they drop it or send
+ // the chord without it), so nothing downstream can recover it.
+ let super_unreportable =
+ host == HostProfile::Legacy && mods & ghostty::MOD_SUPER != 0;
+ // Plain text names a character, not a key: which key and Shift state
+ // produced punctuation depends on the layout. Only a letter's Shift
+ // is layout independent (its case). Legacy hosts never report
+ // Shift for non-letters; Kitty hosts send unmodified punctuation
+ // presses as plain text.
+ let non_letter_text = def.text.is_some_and(|(base, _)| !base.is_alphabetic());
+ let plain_text_press =
+ host_bytes.0.len() == 1 && host_bytes.0[0].is_ascii_graphic();
+ let layout_unreportable = non_letter_text
+ && mods & ghostty::MOD_SHIFT != 0
+ && (host == HostProfile::Legacy || plain_text_press);
+ let ambiguous = expected_by_host_bytes
+ .get(host_bytes)
+ .is_some_and(|distinct| distinct.iter().any(|other| *other != expected));
+ if super_unreportable || layout_unreportable || ambiguous {
+ tally.host_lossy += 1;
+ continue;
+ }
+ let press = herdr.feed(&host_bytes.0);
+ let release = herdr.feed(&host_bytes.1);
+ let page_key_scrolls_herdr = *mods == 0
+ && matches!(def.name, "pageup" | "pagedown")
+ && herdr.runtime.plain_page_keys_use_host_scrollback() == Some(true);
+ let (Some(press), Some(release), false) = (press, release, page_key_scrolls_herdr)
+ else {
+ report.owned.push(format!(
+ "{}\t{}\t{}+{}",
+ host.name(),
+ pane_name,
+ mods_name(*mods),
+ def.name
+ ));
+ tally.herdr_owned += 1;
+ herdr.reset_client();
+ continue;
+ };
+ let actual = [press, release].concat();
+ tally.scored += 1;
+ if &actual == expected {
+ tally.passed += 1;
+ } else if normalize_kitty_press(&actual) == normalize_kitty_press(expected) {
+ tally.passed += 1;
+ tally.equivalent += 1;
+ } else {
+ report.failures.push(Failure {
+ host: host.name(),
+ pane: pane_name,
+ keystroke: format!("{}+{}", mods_name(*mods), def.name),
+ expected: expected.clone(),
+ actual,
+ });
+ }
+ }
+ }
+ }
+ report
+}
+
+fn print_report(report: &Report) {
+ let mut total = Tally::default();
+ println!(
+ "\n{:<12} {:<17} {:<6} {:>7} {:>7} {:>7} {:>7} {:>7} {:>7}",
+ "host", "pane", "keys", "scored", "passed", "score", "equiv", "lossy", "owned"
+ );
+ for ((host, pane, group), tally) in &report.by_cell {
+ println!(
+ "{:<12} {:<17} {:<6} {:>7} {:>7} {:>6.1}% {:>7} {:>7} {:>7}",
+ host,
+ pane,
+ group,
+ tally.scored,
+ tally.passed,
+ 100.0 * tally.passed as f64 / tally.scored.max(1) as f64,
+ tally.equivalent,
+ tally.host_lossy,
+ tally.herdr_owned
+ );
+ total.scored += tally.scored;
+ total.passed += tally.passed;
+ total.equivalent += tally.equivalent;
+ total.host_lossy += tally.host_lossy;
+ total.herdr_owned += tally.herdr_owned;
+ }
+ println!(
+ "{:<37} {:>7} {:>7} {:>6.1}% {:>7} {:>7} {:>7}",
+ "TOTAL",
+ total.scored,
+ total.passed,
+ 100.0 * total.passed as f64 / total.scored.max(1) as f64,
+ total.equivalent,
+ total.host_lossy,
+ total.herdr_owned
+ );
+
+ if let Ok(path) = std::env::var("HERDR_INPUT_CONFORMANCE_FAILURES") {
+ let lines: Vec<String> = report
+ .failures
+ .iter()
+ .map(|failure| {
+ format!(
+ "{}\t{}\t{}\texpected={}\tactual={}",
+ failure.host,
+ failure.pane,
+ failure.keystroke,
+ show(&failure.expected),
+ show(&failure.actual)
+ )
+ })
+ .chain(report.owned.iter().map(|owned| format!("owned\t{owned}")))
+ .collect();
+ std::fs::write(path, lines.join("\n")).expect("write failures");
+ }
+}
+
+// Ratchet: failure counts may only go down. Lower them when a change fixes
+// cases; a rise means a regression in Herdr's input transparency.
+// Remaining: Alt+], Alt+Shift+P/X, Alt+^, Alt+_ behind legacy hosts. Their bytes
+// also start host replies, so they are never forwarded and the reply-tail
+// discard can swallow the next keystroke (#344).
+const KEYBOARD_FAILURES_BASELINE: usize = 60;
+const MOUSE_FAILURES_BASELINE: usize = 96;
+// Remaining: legacy hosts split right after ESC[, which is also Alt+[.
+const SPLIT_IDLE_MISMATCH_BASELINE: usize = 207;
+
+// ---------------------------------------------------------------------------
+// Mouse
+// ---------------------------------------------------------------------------
+
+const MOUSE_TRACKING: &[(&str, &[u8])] = &[
+ ("off", b""),
+ ("x10", b"\x1b[?9h"),
+ ("normal", b"\x1b[?1000h"),
+ ("button", b"\x1b[?1002h"),
+ ("any", b"\x1b[?1003h"),
+];
+
+const MOUSE_FORMATS: &[(&str, &[u8])] = &[
+ ("default", b""),
+ ("utf8", b"\x1b[?1005h"),
+ ("sgr", b"\x1b[?1006h"),
+ ("urxvt", b"\x1b[?1015h"),
+];
+
+/// What Herdr asks the host for while it captures the mouse.
+const HOST_MOUSE_SETUP: &[u8] = b"\x1b[?1003h\x1b[?1006h";
+
+#[derive(Clone, Copy)]
+struct MouseStep {
+ action: ffi::GhosttyMouseAction,
+ button: Option<ffi::GhosttyMouseButton>,
+ /// Offset added to the gesture's start cell.
+ dx: u16,
+ dy: u16,
+}
+
+const fn step(
+ action: ffi::GhosttyMouseAction,
+ button: Option<ffi::GhosttyMouseButton>,
+ dx: u16,
+ dy: u16,
+) -> MouseStep {
+ MouseStep {
+ action,
+ button,
+ dx,
+ dy,
+ }
+}
+
+const GESTURES: &[(&str, &[MouseStep])] = &[
+ (
+ "click-left",
+ &[
+ step(
+ ghostty::MOUSE_ACTION_PRESS,
+ Some(ghostty::MOUSE_BUTTON_LEFT),
+ 0,
+ 0,
+ ),
+ step(
+ ghostty::MOUSE_ACTION_RELEASE,
+ Some(ghostty::MOUSE_BUTTON_LEFT),
+ 0,
+ 0,
+ ),
+ ],
+ ),
+ (
+ "click-middle",
+ &[
+ step(
+ ghostty::MOUSE_ACTION_PRESS,
+ Some(ghostty::MOUSE_BUTTON_MIDDLE),
+ 0,
+ 0,
+ ),
+ step(
+ ghostty::MOUSE_ACTION_RELEASE,
+ Some(ghostty::MOUSE_BUTTON_MIDDLE),
+ 0,
+ 0,
+ ),
+ ],
+ ),
+ (
+ "click-right",
+ &[
+ step(
+ ghostty::MOUSE_ACTION_PRESS,
+ Some(ghostty::MOUSE_BUTTON_RIGHT),
+ 0,
+ 0,
+ ),
+ step(
+ ghostty::MOUSE_ACTION_RELEASE,
+ Some(ghostty::MOUSE_BUTTON_RIGHT),
+ 0,
+ 0,
+ ),
+ ],
+ ),
+ (
+ "drag-left",
+ &[
+ step(
+ ghostty::MOUSE_ACTION_PRESS,
+ Some(ghostty::MOUSE_BUTTON_LEFT),
+ 0,
+ 0,
+ ),
+ step(
+ ghostty::MOUSE_ACTION_MOTION,
+ Some(ghostty::MOUSE_BUTTON_LEFT),
+ 1,
+ 0,
+ ),
+ step(
+ ghostty::MOUSE_ACTION_MOTION,
+ Some(ghostty::MOUSE_BUTTON_LEFT),
+ 2,
+ 1,
+ ),
+ step(
+ ghostty::MOUSE_ACTION_RELEASE,
+ Some(ghostty::MOUSE_BUTTON_LEFT),
+ 2,
+ 1,
+ ),
+ ],
+ ),
+ (
+ "move",
+ &[
+ step(ghostty::MOUSE_ACTION_MOTION, None, 0, 0),
+ step(ghostty::MOUSE_ACTION_MOTION, None, 1, 1),
+ ],
+ ),
+ (
+ "wheel-up",
+ &[step(
+ ghostty::MOUSE_ACTION_PRESS,
+ Some(ghostty::MOUSE_BUTTON_WHEEL_UP),
+ 0,
+ 0,
+ )],
+ ),
+ (
+ "wheel-down",
+ &[step(
+ ghostty::MOUSE_ACTION_PRESS,
+ Some(ghostty::MOUSE_BUTTON_WHEEL_DOWN),
+ 0,
+ 0,
+ )],
+ ),
+ (
+ "wheel-left",
+ &[step(
+ ghostty::MOUSE_ACTION_PRESS,
+ Some(ghostty::MOUSE_BUTTON_WHEEL_LEFT),
+ 0,
+ 0,
+ )],
+ ),
+ (
+ "wheel-right",
+ &[step(
+ ghostty::MOUSE_ACTION_PRESS,
+ Some(ghostty::MOUSE_BUTTON_WHEEL_RIGHT),
+ 0,
+ 0,
+ )],
+ ),
+];
+
+const MOUSE_MODS: [(u16, &str); 4] = [
+ (0, "plain"),
+ (ghostty::MOD_SHIFT, "shift"),
+ (ghostty::MOD_ALT, "alt"),
+ (ghostty::MOD_CTRL, "ctrl"),
+];
+
+struct MouseOracle {
+ _terminal: ghostty::Terminal,
+ encoder: ghostty::MouseEncoder,
+}
+
+impl MouseOracle {
+ fn new(app_output: &[u8], cols: u16, rows: u16) -> Self {
+ let mut terminal = ghostty::Terminal::new(cols, rows, 0).expect("terminal");
+ terminal.write(app_output);
+ let mut encoder = ghostty::MouseEncoder::new().expect("encoder");
+ encoder.set_from_terminal(&terminal);
+ encoder.set_size(u32::from(cols), u32::from(rows), 1, 1);
+ Self {
+ _terminal: terminal,
+ encoder,
+ }
+ }
+
+ fn encode(&mut self, step: MouseStep, mods: u16, column: u16, row: u16) -> Vec<u8> {
+ let mut event = ghostty::MouseEvent::new().expect("mouse event");
+ event.set_action(step.action);
+ match step.button {
+ Some(button) => event.set_button(button),
+ None => event.clear_button(),
+ }
+ event.set_mods(mods);
+ event.set_position(f32::from(column), f32::from(row));
+ self.encoder.encode(&event).expect("encode mouse")
+ }
+}
+
+const MOUSE_PANE_COLS: u16 = 40;
+const MOUSE_PANE_ROWS: u16 = 10;
+
+fn mouse_surface(mouse_reporting: bool) -> PaneSurfaceFrame {
+ let mut surface = surface();
+ let pane = &mut surface.panes[0];
+ for rect in [&mut pane.rect, &mut pane.inner_rect] {
+ rect.width = MOUSE_PANE_COLS;
+ rect.height = MOUSE_PANE_ROWS;
+ }
+ pane.mouse_reporting = mouse_reporting;
+ surface
+}
+
+fn run_mouse_conformance() -> Report {
+ let mut report = Report {
+ by_cell: BTreeMap::new(),
+ failures: Vec::new(),
+ owned: Vec::new(),
+ };
+ for &(tracking_name, tracking) in MOUSE_TRACKING {
+ for &(format_name, format) in MOUSE_FORMATS {
+ let pane_mode = [tracking, format].concat();
+ let pane_name: &'static str =
+ Box::leak(format!("{tracking_name}/{format_name}").into_boxed_str());
+ let tally = report
+ .by_cell
+ .entry(("kitty-host", pane_name, "mouse"))
+ .or_default();
+
+ let mut herdr = HerdrPath::new(HostProfile::Kitty, &pane_mode);
+ herdr
+ .state
+ .set_pane_surface(mouse_surface(!tracking.is_empty()));
+ herdr.state.compose(106, 20).expect("composed frame");
+ let inner = herdr.state.hits.panes[0].inner_rect;
+ let mut direct = MouseOracle::new(&pane_mode, 80, 24);
+ let mut host = MouseOracle::new(HOST_MOUSE_SETUP, 106, 20);
+
+ let starts = [
+ (0u16, 0u16),
+ (inner.width / 2, inner.height / 2),
+ (
+ inner.width.saturating_sub(3),
+ inner.height.saturating_sub(2),
+ ),
+ ];
+ for &(gesture_name, steps) in GESTURES {
+ for &(mods, mods_label) in &MOUSE_MODS {
+ for &(column, row) in &starts {
+ let mut expected = Vec::new();
+ let mut actual = Vec::new();
+ let mut owned = false;
+ for step in steps {
+ let (c, r) = (column + step.dx, row + step.dy);
+ expected.extend(direct.encode(*step, mods, c, r));
+ let host_bytes = host.encode(*step, mods, inner.x + c, inner.y + r);
+ match herdr.feed(&host_bytes) {
+ Some(bytes) => actual.extend(bytes),
+ None => owned = true,
+ }
+ }
+ if owned {
+ tally.herdr_owned += 1;
+ report.owned.push(format!(
+ "{pane_name}\t{mods_label}+{gesture_name}@{column},{row}"
+ ));
+ herdr.reset_client();
+ herdr
+ .state
+ .set_pane_surface(mouse_surface(!tracking.is_empty()));
+ herdr.state.compose(106, 20).expect("composed frame");
+ continue;
+ }
+ tally.scored += 1;
+ if actual == expected {
+ tally.passed += 1;
+ } else {
+ report.failures.push(Failure {
+ host: "kitty-host",
+ pane: pane_name,
+ keystroke: format!("{mods_label}+{gesture_name}@{column},{row}"),
+ expected,
+ actual,
+ });
+ }
+ }
+ }
+ }
+ }
+ }
+ report
+}
+
+// ---------------------------------------------------------------------------
+// Split reads
+// ---------------------------------------------------------------------------
+
+fn host_input_corpus() -> Vec<(HostProfile, Vec<u8>)> {
+ let mut corpus = Vec::new();
+ for (host, setup) in [
+ (HostProfile::Kitty, &b"\x1b[>7u"[..]),
+ (HostProfile::Kitty, &b"\x1b[>31u"[..]),
+ (HostProfile::Legacy, &b""[..]),
+ ] {
+ let mut oracle = Oracle::new(setup);
+ for def in KEYS {
+ for mods in [
+ 0,
+ ghostty::MOD_SHIFT,
+ ghostty::MOD_CTRL,
+ ghostty::MOD_ALT,
+ ghostty::MOD_CTRL | ghostty::MOD_SHIFT,
+ ghostty::MOD_CTRL | ghostty::MOD_ALT,
+ ] {
+ let (press, release) = oracle.keystroke(*def, mods);
+ corpus.push((host, press));
+ if !release.is_empty() {
+ corpus.push((host, release));
+ }
+ }
+ }
+ }
+ let mut mouse = MouseOracle::new(HOST_MOUSE_SETUP, 300, 100);
+ for &(_, steps) in GESTURES {
+ for &(mods, _) in &MOUSE_MODS {
+ for step in steps {
+ corpus.push((HostProfile::Kitty, mouse.encode(*step, mods, 7, 3)));
+ corpus.push((HostProfile::Kitty, mouse.encode(*step, mods, 150, 42)));
+ }
+ }
+ }
+ corpus.sort();
+ corpus.dedup();
+ corpus.retain(|(_, bytes)| bytes.len() > 1);
+ corpus
+}
+
+/// Replies Herdr asks the host for at startup and on focus (colors, palette,
+/// cell size, appearance).
+const HOST_REPLIES: &[&[u8]] = &[
+ b"\x1b]10;rgb:ffff/ffff/ffff\x1b\\",
+ b"\x1b]11;rgb:1e1e/1e1e/2e2e\x07",
+ b"\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\",
+ b"\x1b]4;1;rgb:cdcd/0000/0000\x1b\\",
+ b"\x1b]4;255;rgb:eeee/eeee/eeee\x07",
+ b"\x1b[6;20;10t",
+ b"\x1b[?997;1n",
+ b"\x1b[?997;2n",
+];
+
+/// A network hiccup between two reads of one sequence (SSH, slow links).
+const SPLIT_PAUSE_MS: i32 = 50;
+
+fn framed_events(host: HostProfile, pieces: &[&[u8]], pause_ms: Option<i32>) -> String {
+ framed_events_with(host, pieces, pause_ms, false)
+}
+
+/// Feed `pieces` as separate reads. With `pause_ms`, the reads are that far
+/// apart: like the client loop, the framer is flushed only when the pause
+/// outlasts the wait it asked for.
+fn framed_events_with(
+ host: HostProfile,
+ pieces: &[&[u8]],
+ pause_ms: Option<i32>,
+ awaiting_replies: bool,
+) -> String {
+ let mut framer = HerdrPath::fresh_framer(host);
+ if awaiting_replies {
+ // Mirrors the Unix client right after it sent its host queries.
+ framer.host_color_query_sent();
+ framer.enable_host_color_scheme_change_tracking();
+ framer.enable_host_appearance_query_on_focus();
+ framer.host_cell_size_query_sent();
+ }
+ let mut chunks = Vec::new();
+ for (index, piece) in pieces.iter().enumerate() {
+ chunks.extend(framer.push(piece));
+ let Some(pause_ms) = pause_ms.filter(|_| index + 1 < pieces.len()) else {
+ continue;
+ };
+ let mut waited = 0;
+ for _ in 0..3 {
+ let wait = framer.idle_flush_timeout_ms(true);
+ if !framer.has_pending_input() || waited + wait > pause_ms {
+ break;
+ }
+ waited += wait;
+ chunks.extend(framer.flush_timeout());
+ }
+ }
+ for _ in 0..3 {
+ if !framer.has_pending_input() {
+ break;
+ }
+ chunks.extend(framer.flush_timeout());
+ }
+ let events: Vec<_> = chunks
+ .iter()
+ .flat_map(|chunk| crate::raw_input::parse_raw_input_bytes_sync(chunk))
+ .collect();
+ format!("{events:?}")
+}
+
+// The keyboard, mouse and split-read checks model a Unix host sending terminal
+// bytes. Windows input arrives as native records; see `windows_records`.
+#[cfg(unix)]
+#[test]
+fn split_read_robustness() {
+ let corpus = host_input_corpus();
+ let mut splits = 0usize;
+ let mut burst_mismatch = Vec::new();
+ let mut idle_mismatch = Vec::new();
+ for (host, bytes) in &corpus {
+ let whole = framed_events(*host, &[bytes], None);
+ for cut in 1..bytes.len() {
+ splits += 1;
+ let pieces = [&bytes[..cut], &bytes[cut..]];
+ if framed_events(*host, &pieces, None) != whole {
+ burst_mismatch.push(format!(
+ "{}\t{}|{}",
+ host.name(),
+ show(pieces[0]),
+ show(pieces[1])
+ ));
+ }
+ if framed_events(*host, &pieces, Some(SPLIT_PAUSE_MS)) != whole {
+ idle_mismatch.push(format!(
+ "{}\t{}|{}",
+ host.name(),
+ show(pieces[0]),
+ show(pieces[1])
+ ));
+ }
+ }
+ }
+ let mut reply_splits = 0usize;
+ let mut reply_burst_mismatch = Vec::new();
+ let mut reply_idle_mismatch = Vec::new();
+ for reply in HOST_REPLIES {
+ let whole = framed_events_with(HostProfile::Kitty, &[reply], None, true);
+ for cut in 1..reply.len() {
+ reply_splits += 1;
+ let pieces = [&reply[..cut], &reply[cut..]];
+ let line = format!("reply\t{}|{}", show(pieces[0]), show(pieces[1]));
+ if framed_events_with(HostProfile::Kitty, &pieces, None, true) != whole {
+ reply_burst_mismatch.push(line.clone());
+ }
+ if framed_events_with(HostProfile::Kitty, &pieces, Some(SPLIT_PAUSE_MS), true) != whole
+ {
+ reply_idle_mismatch.push(line);
+ }
+ }
+ }
+ println!(
+ "\nhost replies: {} replies, {} splits\n burst (no pause): {} differ\n {SPLIT_PAUSE_MS}ms pause: {} differ",
+ HOST_REPLIES.len(),
+ reply_splits,
+ reply_burst_mismatch.len(),
+ reply_idle_mismatch.len()
+ );
+
+ let pct = |bad: usize| 100.0 * (splits - bad) as f64 / splits.max(1) as f64;
+ println!(
+ "\nsplit reads: {} sequences, {} splits\n burst (no pause): {:.1}% identical ({} differ)\n {SPLIT_PAUSE_MS}ms pause: {:.1}% identical ({} differ)",
+ corpus.len(),
+ splits,
+ pct(burst_mismatch.len()),
+ burst_mismatch.len(),
+ pct(idle_mismatch.len()),
+ idle_mismatch.len()
+ );
+ if let Ok(path) = std::env::var("HERDR_INPUT_CONFORMANCE_FAILURES") {
+ let lines: Vec<String> = burst_mismatch
+ .iter()
+ .chain(&reply_burst_mismatch)
+ .map(|line| format!("burst\t{line}"))
+ .chain(
+ idle_mismatch
+ .iter()
+ .chain(&reply_idle_mismatch)
+ .map(|line| format!("idle\t{line}")),
+ )
+ .collect();
+ std::fs::write(path, lines.join("\n")).expect("write failures");
+ }
+ assert!(
+ burst_mismatch.is_empty() && reply_burst_mismatch.is_empty(),
+ "split reads without a pause changed the decoded input"
+ );
+ assert!(
+ idle_mismatch.len() <= SPLIT_IDLE_MISMATCH_BASELINE,
+ "split-read robustness regressed: {} > {SPLIT_IDLE_MISMATCH_BASELINE}",
+ idle_mismatch.len()
+ );
+ assert!(
+ reply_idle_mismatch.is_empty(),
+ "split host replies changed after a {SPLIT_PAUSE_MS}ms pause: {reply_idle_mismatch:?}"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Reporter captures: exact bytes and timing from real terminals in issues.
+// ---------------------------------------------------------------------------
+
+/// (issue, host, reads, gap between reads in ms, Herdr awaiting host replies)
+type SplitCapture = (
+ &'static str,
+ HostProfile,
+ &'static [&'static [u8]],
+ i32,
+ bool,
+);
+
+#[cfg(unix)]
+#[test]
+fn reporter_split_captures_decode_like_the_unsplit_input() {
+ let captures: &[SplitCapture] = &[
+ // Alacritty 0.17 on Windows over SSH: the space release split after
+ // `ESC[32;1`, the tail arrived 36 ms later (client log in the issue).
+ (
+ "#4856",
+ HostProfile::Kitty,
+ &[b"\x1b[115;1:3u\x1b[32;1", b":3u"],
+ 36,
+ false,
+ ),
+ // tmux 3.6 relays each OSC 4 palette reply from the outer terminal
+ // with arbitrary gaps; the tail of `e4e4` gray entries leaked.
+ (
+ "#4025",
+ HostProfile::Kitty,
+ &[b"\x1b]4;254;rgb:e4", b"e4/e4e4/e4e4\x1b\\"],
+ 200,
+ true,
+ ),
+ (
+ "#4025",
+ HostProfile::Legacy,
+ &[b"\x1b", b"]4;254;rgb:e4e4/e4e4/e4e4\x07"],
+ 200,
+ true,
+ ),
+ ];
+ for &(issue, host, reads, gap_ms, awaiting) in captures {
+ let whole = reads.concat();
+ assert_eq!(
+ framed_events_with(host, reads, Some(gap_ms), awaiting),
+ framed_events_with(host, &[&whole], None, awaiting),
+ "{issue}: {} read(s) {gap_ms}ms apart",
+ reads.len()
+ );
+ }
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn ime_committed_text_reaches_every_pane_mode_exactly_once() {
+ // IME commits (CJK, Korean syllables) arrive as plain UTF-8 text on every
+ // host, with no key releases. Split reads can cut inside a character.
+ // (Spaces between words are the space key, not part of a commit.)
+ let text = "日本語한국어中文";
+ let bytes = text.as_bytes();
+ for host in [HostProfile::Kitty, HostProfile::Legacy] {
+ for &(pane_name, pane_mode) in PANE_MODES {
+ for cut in [None, Some(1), Some(4), Some(bytes.len() - 2)] {
+ let mut herdr = HerdrPath::new(host, pane_mode);
+ let got = match cut {
+ None => herdr.feed(bytes),
+ Some(cut) => {
+ let mut chunks = herdr.framer.push(&bytes[..cut]);
+ chunks.extend(herdr.framer.push(&bytes[cut..]));
+ for _ in 0..3 {
+ chunks.extend(herdr.framer.flush_timeout());
+ }
+ let outcomes = chunks
+ .iter()
+ .map(|chunk| herdr.state.handle_input_bytes(chunk))
+ .collect();
+ herdr.deliver(outcomes)
+ }
+ }
+ .expect("text reaches the pane");
+ assert_eq!(
+ String::from_utf8_lossy(&got),
+ text,
+ "{} {pane_name} cut {cut:?}",
+ host.name()
+ );
+ // Losing focus must not replay releases for committed text.
+ let after = herdr.feed(b"\x1b[O").unwrap_or_default();
+ assert!(
+ !String::from_utf8_lossy(&after).contains(":3u"),
+ "{} {pane_name}: focus loss sent {}",
+ host.name(),
+ show(&after)
+ );
+ }
+ }
+ }
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn lab_kitty_function_keys_reach_the_pane() {
+ // #4403, recorded from kitty 0.47.1 through real key presses: with Herdr's
+ // keyboard flags pushed, unmodified F1, F2 and F4 arrive as bare CSI P/Q/S.
+ for (host_bytes, plain_shell) in [
+ (&b"\x1b[P"[..], &b"\x1bOP"[..]),
+ (b"\x1b[Q", b"\x1bOQ"),
+ (b"\x1b[13~", b"\x1bOR"),
+ (b"\x1b[S", b"\x1bOS"),
+ ] {
+ let mut herdr = HerdrPath::new(HostProfile::Kitty, b"");
+ let got = herdr
+ .feed(host_bytes)
+ .expect("function key reaches the pane");
+ assert_eq!(show(&got), show(plain_shell), "{}", show(host_bytes));
+ }
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn reporter_text_key_release_reaches_kitty_event_pane() {
+ // #4184: an app asking for event types gets typed-letter releases.
+ // (pane mode, kitty host bytes for `a` press then release, pane bytes)
+ for (pane_mode, press, want) in [
+ // Event types only: Herdr keeps the host at flags 7, so the press
+ // arrives as text and its release as a report (the reporter's capture).
+ (&b"\x1b[>3u"[..], &b"a"[..], &b"a\x1b[97;1:3u"[..]),
+ // All keys too: Herdr switches the host to report-all (31), so kitty
+ // reports the press with its text.
+ (b"\x1b[>11u", b"\x1b[97;;97u", b"\x1b[97u\x1b[97;1:3u"),
+ ] {
+ let mut herdr = HerdrPath::new(HostProfile::Kitty, pane_mode);
+ let press = herdr.feed(press).expect("press reaches the pane");
+ let release = herdr
+ .feed(b"\x1b[97;1:3u")
+ .expect("release reaches the pane");
+ assert_eq!(
+ show(&[press, release].concat()),
+ show(want),
+ "{}",
+ show(pane_mode)
+ );
+ }
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn mouse_transparency_conformance() {
+ let report = run_mouse_conformance();
+ print_report(&report);
+ assert!(
+ report.failures.len() <= MOUSE_FAILURES_BASELINE,
+ "mouse transparency regressed: {} failures > {MOUSE_FAILURES_BASELINE}",
+ report.failures.len()
+ );
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn keyboard_transparency_conformance() {
+ let report = run_keyboard_conformance();
+ print_report(&report);
+ assert!(
+ report.failures.len() <= KEYBOARD_FAILURES_BASELINE,
+ "keyboard transparency regressed: {} failures > {KEYBOARD_FAILURES_BASELINE}",
+ report.failures.len()
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Windows: native key records
+// ---------------------------------------------------------------------------
+//
+// In Windows Terminal each keypress reaches ConPTY as a native key record
+// (win32-input-mode). Herdr's pane is a ConPTY too, so for a pane that
+// negotiated no keyboard protocol, transparency means the pane's ConPTY gets
+// the same records Herdr received. Records are built from the real keyboard
+// layouts with ToUnicodeEx, the way Windows produces them.
+
+#[cfg(windows)]
+mod windows_records {
+ use super::*;
+ use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
+ GetKeyboardLayout, LoadKeyboardLayoutW, MapVirtualKeyExW, ToUnicodeEx, HKL,
+ KLF_NOTELLSHELL, MAPVK_VK_TO_VSC,
+ };
+
+ const RIGHT_ALT_PRESSED: u32 = 0x0001;
+ const LEFT_ALT_PRESSED: u32 = 0x0002;
+ const LEFT_CTRL_PRESSED: u32 = 0x0008;
+ const SHIFT_PRESSED: u32 = 0x0010;
+ const ENHANCED_KEY: u32 = 0x0100;
+
+ const VK_SHIFT: usize = 0x10;
+ const VK_CONTROL: usize = 0x11;
+ const VK_MENU: usize = 0x12;
+ const VK_LSHIFT: usize = 0xa0;
+ const VK_LCONTROL: usize = 0xa2;
+ const VK_LMENU: usize = 0xa4;
+ const VK_RMENU: usize = 0xa5;
+
+ const LAYOUTS: &[(&str, &str)] = &[("us", "00000409"), ("de", "00000407")];
+
+ #[derive(Clone, Copy)]
+ struct Chord {
+ name: &'static str,
+ shift: bool,
+ ctrl: bool,
+ left_alt: bool,
+ /// AltGr: Windows reports it as Right Alt plus Left Ctrl.
+ alt_gr: bool,
+ }
+
+ const fn chord(
+ name: &'static str,
+ shift: bool,
+ ctrl: bool,
+ left_alt: bool,
+ alt_gr: bool,
+ ) -> Chord {
+ Chord {
+ name,
+ shift,
+ ctrl,
+ left_alt,
+ alt_gr,
+ }
+ }
+
+ const CHORDS: &[Chord] = &[
+ chord("plain", false, false, false, false),
+ chord("shift", true, false, false, false),
+ chord("ctrl", false, true, false, false),
+ chord("alt", false, false, true, false),
+ chord("ctrl+shift", true, true, false, false),
+ chord("alt+shift", true, false, true, false),
+ chord("ctrl+alt", false, true, true, false),
+ chord("altgr", false, false, false, true),
+ chord("altgr+shift", true, false, false, true),
+ ];
+
+ fn virtual_keys() -> Vec<(String, u16, bool)> {
+ let mut keys: Vec<(String, u16, bool)> = Vec::new();
+ for vk in (0x41..=0x5a).chain(0x30..=0x39) {
+ keys.push((format!("vk{vk:02x}"), vk, false));
+ }
+ for vk in [
+ 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xdb, 0xdc, 0xdd, 0xde, 0xe2,
+ ] {
+ keys.push((format!("oem{vk:02x}"), vk, false));
+ }
+ for (name, vk) in [
+ ("space", 0x20),
+ ("enter", 0x0d),
+ ("tab", 0x09),
+ ("backspace", 0x08),
+ ("escape", 0x1b),
+ ] {
+ keys.push((name.to_owned(), vk, false));
+ }
+ for (name, vk) in [
+ ("pageup", 0x21),
+ ("pagedown", 0x22),
+ ("end", 0x23),
+ ("home", 0x24),
+ ("left", 0x25),
+ ("up", 0x26),
+ ("right", 0x27),
+ ("down", 0x28),
+ ("insert", 0x2d),
+ ("delete", 0x2e),
+ ] {
+ keys.push((name.to_owned(), vk, true));
+ }
+ for n in 0..12u16 {
+ keys.push((format!("f{}", n + 1), 0x70 + n, false));
+ }
+ keys
+ }
+
+ /// Sessions without a desktop (SSH) can only use the current layout.
+ fn load_layout(klid: &str) -> Option<HKL> {
+ let wide: Vec<u16> = klid.encode_utf16().chain(Some(0)).collect();
+ // SAFETY: `wide` is a NUL-terminated layout id that outlives the call.
+ let loaded = unsafe { LoadKeyboardLayoutW(wide.as_ptr(), KLF_NOTELLSHELL) };
+ if !loaded.is_null() {
+ return Some(loaded);
+ }
+ // SAFETY: querying the calling thread's layout has no preconditions.
+ let current = unsafe { GetKeyboardLayout(0) };
+ let current_id = (current as usize & 0xffff) as u32;
+ (u32::from_str_radix(klid, 16).ok()? & 0xffff == current_id).then_some(current)
+ }
+
+ /// The press and release records Windows produces for `vk` under `chord`,
+ /// or None for dead keys and multi-unit output.
+ fn key_records(
+ layout: HKL,
+ vk: u16,
+ enhanced: bool,
+ chord: Chord,
+ ) -> Option<(
+ crate::input::WindowsKeyRecord,
+ crate::input::WindowsKeyRecord,
+ )> {
+ // SAFETY: pure layout lookup.
+ let scan = unsafe { MapVirtualKeyExW(u32::from(vk), MAPVK_VK_TO_VSC, layout) } as u16;
+ let mut state = [0u8; 256];
+ let mut control_key_state = if enhanced { ENHANCED_KEY } else { 0 };
+ if chord.shift {
+ state[VK_SHIFT] = 0x80;
+ state[VK_LSHIFT] = 0x80;
+ control_key_state |= SHIFT_PRESSED;
+ }
+ if chord.ctrl || chord.alt_gr {
+ state[VK_CONTROL] = 0x80;
+ state[VK_LCONTROL] = 0x80;
+ control_key_state |= LEFT_CTRL_PRESSED;
+ }
+ if chord.left_alt {
+ state[VK_MENU] = 0x80;
+ state[VK_LMENU] = 0x80;
+ control_key_state |= LEFT_ALT_PRESSED;
+ }
+ if chord.alt_gr {
+ state[VK_MENU] = 0x80;
+ state[VK_RMENU] = 0x80;
+ control_key_state |= RIGHT_ALT_PRESSED;
+ }
+ let mut buf = [0u16; 8];
+ // SAFETY: buffers are valid for the given lengths. Flag 0x4 leaves the
+ // kernel dead-key state untouched.
+ let written = unsafe {
+ ToUnicodeEx(
+ u32::from(vk),
+ u32::from(scan),
+ state.as_ptr(),
+ buf.as_mut_ptr(),
+ buf.len() as i32,
+ 0x4,
+ layout,
+ )
+ };
+ let unicode = match written {
+ 0 => 0,
+ 1 => buf[0],
+ _ => return None,
+ };
+ let press = crate::input::WindowsKeyRecord {
+ key_down: true,
+ repeat_count: 1,
+ virtual_key_code: vk,
+ virtual_scan_code: scan,
+ unicode,
+ control_key_state,
+ };
+ Some((
+ press,
+ crate::input::WindowsKeyRecord {
+ key_down: false,
+ ..press
+ },
+ ))
+ }
+
+ fn win32_input_mode(record: crate::input::WindowsKeyRecord) -> Vec<u8> {
+ format!(
+ "\x1b[{};{};{};{};{};{}_",
+ record.virtual_key_code,
+ record.virtual_scan_code,
+ record.unicode,
+ u8::from(record.key_down),
+ record.control_key_state,
+ record.repeat_count
+ )
+ .into_bytes()
+ }
+
+ fn deliver_record(
+ herdr: &mut HerdrPath,
+ input: &mut crate::client::input::windows_vti::TestWindowsInput,
+ record: crate::input::WindowsKeyRecord,
+ ) -> Option<Vec<u8>> {
+ let mut events = input.key(record);
+ events.extend(input.idle());
+ let outcome = herdr.state.handle_client_events(&events);
+ herdr.deliver(vec![outcome])
+ }
+
+ fn run() -> Report {
+ let mut report = Report {
+ by_cell: BTreeMap::new(),
+ failures: Vec::new(),
+ owned: Vec::new(),
+ };
+ for &(layout_name, klid) in LAYOUTS {
+ let Some(layout) = load_layout(klid) else {
+ println!(
+ "keyboard layout {layout_name} ({klid}) unavailable in this session; skipped"
+ );
+ continue;
+ };
+ let mut herdr = HerdrPath::new(HostProfile::Legacy, b"");
+ let mut input = crate::client::input::windows_vti::TestWindowsInput::default();
+ for (key_name, vk, enhanced) in virtual_keys() {
+ for chord in CHORDS {
+ let tally = report
+ .by_cell
+ .entry(("windows", layout_name, chord.name))
+ .or_default();
+ let Some((press, release)) = key_records(layout, vk, enhanced, *chord) else {
+ tally.host_lossy += 1;
+ continue;
+ };
+ let expected = [win32_input_mode(press), win32_input_mode(release)].concat();
+ let pressed = deliver_record(&mut herdr, &mut input, press);
+ let released = deliver_record(&mut herdr, &mut input, release);
+ let page_key_scrolls_herdr = chord.name == "plain"
+ && matches!(key_name.as_str(), "pageup" | "pagedown")
+ && herdr.runtime.plain_page_keys_use_host_scrollback() == Some(true);
+ let (Some(pressed), Some(released), false) =
+ (pressed, released, page_key_scrolls_herdr)
+ else {
+ tally.herdr_owned += 1;
+ herdr.reset_client();
+ input = Default::default();
+ continue;
+ };
+ let actual = [pressed, released].concat();
+ tally.scored += 1;
+ if actual == expected {
+ tally.passed += 1;
+ } else {
+ report.failures.push(Failure {
+ host: "windows",
+ pane: layout_name,
+ keystroke: format!(
+ "{}+{key_name} vk={vk:#x} uc={:#x}",
+ chord.name, press.unicode
+ ),
+ expected,
+ actual,
+ });
+ }
+ }
+ }
+ }
+ report
+ }
+
+ #[tokio::test(flavor = "multi_thread")]
+ async fn windows_key_record_transparency() {
+ let report = run();
+ print_report(&report);
+ assert!(
+ report.failures.len() <= WINDOWS_RECORD_FAILURES_BASELINE,
+ "windows key record transparency regressed: {} failures > {WINDOWS_RECORD_FAILURES_BASELINE}",
+ report.failures.len()
+ );
+ }
+
+ // Ratchet (may only go down). Remaining: Ctrl+[ is forwarded as a plain
+ // Escape record rather than its own key record.
+ const WINDOWS_RECORD_FAILURES_BASELINE: usize = 1;
+}
diff --git a/src/client/shell/tests/mod.rs b/src/client/shell/tests/mod.rs
index 9d9601439..9d9da64b4 100644
--- a/src/client/shell/tests/mod.rs
+++ b/src/client/shell/tests/mod.rs
@@ -252,6 +252,7 @@ mod copy;
mod endpoint_requests;
mod endpoints;
mod graphics;
+mod input_conformance;
#[path = "input.rs"]
mod input_domain;
mod keybindings_settings;
diff --git a/src/client/shell_runtime.rs b/src/client/shell_runtime.rs
index 1ab3e287c..8435b7f8b 100644
--- a/src/client/shell_runtime.rs
+++ b/src/client/shell_runtime.rs
@@ -100,6 +100,9 @@ pub(super) fn sync_client_shell_keyboard_report_all(
crate::terminal_modes::set_host_kitty_keyboard_report_all(&mut io::stdout(), desired)
.map_err(ClientError::ConnectionFailed)?;
state.keyboard_report_all_active = desired;
+ if let Some(shell) = state.shell.as_mut() {
+ shell.set_host_reports_all_keys(desired);
+ }
Ok(())
}
@@ -115,7 +118,12 @@ pub(super) fn clear_endpoint_host_effects(
} else {
state.direct_mouse_capture_preference
};
- let sgr_pixels = super::effective_sgr_pixel_mouse(enabled, false, state.pixel_geometry_exact);
+ let sgr_pixels = super::effective_sgr_pixel_mouse(
+ enabled,
+ false,
+ state.pixel_geometry_exact,
+ state.host_sgr_pixel_mouse,
+ );
if enabled != state.mouse_capture_active
|| sgr_pixels != host_sgr_pixels_active.load(std::sync::atomic::Ordering::Acquire)
{
diff --git a/src/client/state.rs b/src/client/state.rs
index 2cadfa629..03bfc56e2 100644
--- a/src/client/state.rs
+++ b/src/client/state.rs
@@ -51,6 +51,8 @@ pub(super) struct ClientState {
pub(super) kitty_graphics_enabled: bool,
pub(super) pixel_geometry_enabled: bool,
pub(super) pixel_geometry_exact: bool,
+ /// The host's answer to the SGR pixel mouse probe; None when unknown.
+ pub(super) host_sgr_pixel_mouse: Option<bool>,
#[cfg(unix)]
pub(super) direct_graphics_response: Arc<Mutex<direct_graphics::ResponseMatcher>>,
#[cfg(unix)]
@@ -114,6 +116,7 @@ impl ClientState {
kitty_graphics_enabled: false,
pixel_geometry_enabled: false,
pixel_geometry_exact: false,
+ host_sgr_pixel_mouse: None,
#[cfg(unix)]
direct_graphics_response: Default::default(),
#[cfg(unix)]
diff --git a/src/client/terminal_setup.rs b/src/client/terminal_setup.rs
index 249e29ad1..9c2ddf0e0 100644
--- a/src/client/terminal_setup.rs
+++ b/src/client/terminal_setup.rs
@@ -48,6 +48,7 @@ pub(super) fn setup_terminal_with_capabilities(
ratatui::init();
let mut terminal_guard = TerminalGuard {
host_escape_disambiguation_active: false,
+ host_sgr_pixel_mouse: None,
buffered_host_input: Vec::new(),
reset_keyboard_enhancements: false,
reset_modify_other_keys: false,
@@ -63,38 +64,37 @@ pub(super) fn setup_terminal_with_capabilities(
#[cfg(windows)]
let windows_ssh_session = is_ssh_session();
#[cfg(windows)]
- let mut windows_virtual_terminal_input =
- if windows_vti_input_backend_enabled() && windows_ssh_session {
- enable_windows_virtual_terminal_input(
- &terminal_guard.restore_claimed,
- &terminal_guard.restore_windows_input_mode,
- )
- } else {
- WindowsVirtualTerminalInputSetup::default()
- };
+ let mut windows_virtual_terminal_input = if windows_ssh_session {
+ enable_windows_virtual_terminal_input(
+ &terminal_guard.restore_claimed,
+ &terminal_guard.restore_windows_input_mode,
+ )
+ } else {
+ WindowsVirtualTerminalInputSetup::default()
+ };
- let (host_escape_disambiguation_active, buffered_host_input) = if enable_client_protocols {
+ let (host_probe, buffered_host_input) = if enable_client_protocols {
terminal_guard.reset_keyboard_enhancements = true;
push_keyboard_enhancement_flags()?;
- let (active, buffered_input) = query_host_escape_disambiguation();
+ let (probe, buffered_input) = query_host_escape_disambiguation();
set_mouse_capture(mouse_capture, false)?;
execute!(io::stdout(), EnableBracketedPaste, EnableFocusChange)?;
if host_color_scheme_reports {
terminal_guard.reset_host_color_scheme_reports = true;
write_host_color_scheme_report_mode(&mut io::stdout(), true)?;
}
- (active, buffered_input)
+ (probe, buffered_input)
} else {
if should_enable_host_color_scheme_reports(true) {
write_host_color_scheme_report_mode(&mut io::stdout(), false)?;
}
set_mouse_capture(mouse_capture, false)?;
execute!(io::stdout(), EnableBracketedPaste)?;
- (false, Vec::new())
+ (HostTerminalProbe::default(), Vec::new())
};
#[cfg(windows)]
- if enable_client_protocols && windows_vti_input_backend_enabled() && !windows_ssh_session {
+ if enable_client_protocols && !windows_ssh_session {
windows_virtual_terminal_input = enable_windows_virtual_terminal_input(
&terminal_guard.restore_claimed,
&terminal_guard.restore_windows_input_mode,
@@ -103,7 +103,6 @@ pub(super) fn setup_terminal_with_capabilities(
#[cfg(windows)]
if enable_client_protocols
- && windows_vti_input_backend_enabled()
&& windows_virtual_terminal_input.active
&& windows_win32_input_mode_enabled()
{
@@ -121,7 +120,8 @@ pub(super) fn setup_terminal_with_capabilities(
execute!(io::stdout(), DisableLineWrap)?;
- terminal_guard.host_escape_disambiguation_active = host_escape_disambiguation_active;
+ terminal_guard.host_escape_disambiguation_active = host_probe.escape_disambiguation;
+ terminal_guard.host_sgr_pixel_mouse = host_probe.sgr_pixel_mouse;
terminal_guard.buffered_host_input = buffered_host_input;
Ok(terminal_guard)
}
@@ -133,6 +133,7 @@ pub(super) fn should_enable_host_color_scheme_reports(enable_client_protocols: b
/// Guard that restores the terminal when dropped.
pub(super) struct TerminalGuard {
host_escape_disambiguation_active: bool,
+ host_sgr_pixel_mouse: Option<bool>,
buffered_host_input: Vec<u8>,
reset_keyboard_enhancements: bool,
reset_modify_other_keys: bool,
@@ -152,12 +153,23 @@ const MAX_BUFFERED_HOST_INPUT: usize = 64 * 1024;
#[derive(Default)]
struct HostKeyboardProbeResponses {
flags: Option<u16>,
+ /// DECRPM for SGR pixel mouse (1016): Some(true) when the host knows the
+ /// mode, Some(false) when it reports it unsupported.
+ sgr_pixel_mouse: Option<bool>,
primary_device_attributes: bool,
}
+/// What the startup probe learned about the host terminal.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(super) struct HostTerminalProbe {
+ pub(super) escape_disambiguation: bool,
+ /// None when the host did not answer: keep assuming support.
+ pub(super) sgr_pixel_mouse: Option<bool>,
+}
+
#[cfg(not(windows))]
-fn query_host_escape_disambiguation() -> (bool, Vec<u8>) {
- const QUERY: &[u8] = b"\x1b[?u\x1b[c";
+fn query_host_escape_disambiguation() -> (HostTerminalProbe, Vec<u8>) {
+ const QUERY: &[u8] = b"\x1b[?u\x1b[?1016$p\x1b[c";
let mut buffered_input = Vec::new();
if let Err(err) = io::stdout()
@@ -165,7 +177,7 @@ fn query_host_escape_disambiguation() -> (bool, Vec<u8>) {
.and_then(|()| io::stdout().flush())
{
tracing::debug!(%err, "host keyboard enhancement query unavailable");
- return (false, buffered_input);
+ return (HostTerminalProbe::default(), buffered_input);
}
// Bypass StdinLock's shared buffer so poll and read observe the same bytes.
@@ -205,10 +217,16 @@ fn query_host_escape_disambiguation() -> (bool, Vec<u8>) {
}
}
- (
- host_escape_disambiguation_confirmed(&responses),
- buffered_input,
- )
+ (host_terminal_probe(&responses), buffered_input)
+}
+
+#[cfg(not(windows))]
+fn host_terminal_probe(responses: &HostKeyboardProbeResponses) -> HostTerminalProbe {
+ HostTerminalProbe {
+ escape_disambiguation: host_escape_disambiguation_confirmed(responses),
+ // An explicit mode answer stands even if the probe timed out later.
+ sgr_pixel_mouse: responses.sgr_pixel_mouse,
+ }
}
#[cfg(not(windows))]
@@ -263,6 +281,26 @@ fn consume_host_keyboard_probe_responses(
break;
}
let body = &buffered_input[start + 3..end];
+ // DECRPM: CSI ? 1016 ; Ps $ y (0 = not recognized, 4 = permanently reset).
+ if buffered_input[end] == b'$' {
+ let Some(&final_byte) = buffered_input.get(end + 1) else {
+ break;
+ };
+ let reply = std::str::from_utf8(body)
+ .ok()
+ .and_then(|body| body.split_once(';'))
+ .filter(|(mode, _)| *mode == "1016")
+ .and_then(|(_, state)| state.parse::<u8>().ok());
+ if final_byte == b'y' {
+ if let Some(state) = reply {
+ responses.sgr_pixel_mouse = Some(matches!(state, 1..=3));
+ buffered_input.drain(start..=end + 1);
+ continue;
+ }
+ }
+ offset += 1;
+ continue;
+ }
let recognized = match buffered_input[end] {
b'u' if !body.is_empty() && body.iter().all(u8::is_ascii_digit) => {
std::str::from_utf8(body)
@@ -322,8 +360,8 @@ fn host_control_string_end(bytes: &[u8]) -> Option<Option<usize>> {
}
#[cfg(windows)]
-fn query_host_escape_disambiguation() -> (bool, Vec<u8>) {
- (false, Vec::new())
+fn query_host_escape_disambiguation() -> (HostTerminalProbe, Vec<u8>) {
+ (HostTerminalProbe::default(), Vec::new())
}
pub(super) fn write_host_color_scheme_report_mode(
@@ -495,13 +533,6 @@ pub(super) fn is_ssh_session() -> bool {
std::env::var_os("SSH_CONNECTION").is_some() || std::env::var_os("SSH_TTY").is_some()
}
-#[cfg(windows)]
-pub(super) fn windows_vti_input_backend_enabled() -> bool {
- std::env::var("HERDR_WINDOWS_INPUT_BACKEND")
- .map(|backend| !backend.eq_ignore_ascii_case("crossterm"))
- .unwrap_or(true)
-}
-
#[cfg(any(windows, test))]
pub(super) fn windows_virtual_terminal_input_mode(mode: u32) -> u32 {
mode | 0x0200
@@ -528,12 +559,16 @@ pub(super) fn effective_mouse_capture(
server_enabled || direct_attach_preference
}
+/// Host SGR pixel reports are used only when exact cell geometry maps them to
+/// cells and the host did not report the mode unsupported (`host_support`
+/// None means it never answered the probe).
pub(super) fn effective_sgr_pixel_mouse(
enabled: bool,
requested: bool,
exact_geometry: bool,
+ host_support: Option<bool>,
) -> bool {
- enabled && requested && exact_geometry
+ enabled && requested && exact_geometry && host_support != Some(false)
}
#[cfg(any(windows, test))]
@@ -555,8 +590,7 @@ fn set_windows_native_mouse_capture<W: io::Write>(
#[cfg(windows)]
fn windows_uses_vt_mouse_reporting() -> bool {
- windows_vti_input_backend_enabled()
- && (is_ssh_session() || crate::platform::windows_virtual_terminal_input_active())
+ is_ssh_session() || crate::platform::windows_virtual_terminal_input_active()
}
pub(super) fn set_mouse_capture(enabled: bool, sgr_pixels: bool) -> io::Result<()> {
@@ -666,7 +700,7 @@ fn restore_terminal_state(
write_terminal_restore_postlude(&mut io::stdout(), reset_host_color_scheme_reports);
#[cfg(windows)]
- if windows_vti_input_backend_enabled() && windows_win32_input_mode_enabled() {
+ if windows_win32_input_mode_enabled() {
let _ = disable_windows_win32_input_mode(&mut io::stdout());
}
@@ -720,6 +754,11 @@ impl TerminalGuard {
self.host_escape_disambiguation_active
}
+ /// Whether the host answered that it supports SGR pixel mouse reports.
+ pub(super) fn host_sgr_pixel_mouse(&self) -> Option<bool> {
+ self.host_sgr_pixel_mouse
+ }
+
pub(super) fn take_buffered_host_input(&mut self) -> Vec<u8> {
std::mem::take(&mut self.buffered_host_input)
}
@@ -867,6 +906,45 @@ mod tests {
}
}
+ #[cfg(not(windows))]
+ #[test]
+ fn host_probe_reads_sgr_pixel_mouse_support_at_any_split() {
+ // kitty/Ghostty answer 2 (reset, supported); Alacritty answers 0 (unknown).
+ for (reply, expected) in [
+ (&b"\x1b[?1016;2$y"[..], Some(true)),
+ (b"\x1b[?1016;1$y", Some(true)),
+ (b"\x1b[?1016;0$y", Some(false)),
+ (b"\x1b[?1016;4$y", Some(false)),
+ (b"", None),
+ ] {
+ let stream = [&b"x\x1b[?7u"[..], reply, b"\x1b[?1;2cy"].concat();
+ for split in 1..stream.len() {
+ let mut buffered = stream[..split].to_vec();
+ let mut responses = HostKeyboardProbeResponses::default();
+ consume_host_keyboard_probe_responses(&mut buffered, &mut responses);
+ buffered.extend_from_slice(&stream[split..]);
+ consume_host_keyboard_probe_responses(&mut buffered, &mut responses);
+
+ assert_eq!(
+ responses.sgr_pixel_mouse, expected,
+ "{reply:?} split {split}"
+ );
+ assert_eq!(buffered, b"xy", "{reply:?} split {split}");
+ }
+ }
+ }
+
+ #[cfg(not(windows))]
+ #[test]
+ fn host_probe_keeps_a_pixel_mouse_answer_without_device_attributes() {
+ let mut buffered = b"\x1b[?1016;0$y".to_vec();
+ let mut responses = HostKeyboardProbeResponses::default();
+ consume_host_keyboard_probe_responses(&mut buffered, &mut responses);
+
+ assert!(!responses.primary_device_attributes);
+ assert_eq!(host_terminal_probe(&responses).sgr_pixel_mouse, Some(false));
+ }
+
#[cfg(not(windows))]
#[test]
fn host_keyboard_probe_preserves_typed_input_before_responses() {
diff --git a/src/client/tests/mod.rs b/src/client/tests/mod.rs
index 323af2f87..2d3f022a3 100644
--- a/src/client/tests/mod.rs
+++ b/src/client/tests/mod.rs
@@ -499,8 +499,11 @@ fn direct_attach_mouse_capture_combines_local_preference_with_child_demand() {
assert!(effective_mouse_capture(false, true));
assert!(effective_mouse_capture(true, false));
assert!(!effective_mouse_capture(false, false));
- assert!(effective_sgr_pixel_mouse(true, true, true));
- assert!(!effective_sgr_pixel_mouse(true, true, false));
+ assert!(effective_sgr_pixel_mouse(true, true, true, None));
+ assert!(effective_sgr_pixel_mouse(true, true, true, Some(true)));
+ assert!(!effective_sgr_pixel_mouse(true, true, false, None));
+ // A host that reports 1016 unsupported keeps sending cell reports.
+ assert!(!effective_sgr_pixel_mouse(true, true, true, Some(false)));
}
#[test]
diff --git a/src/input/encode.rs b/src/input/encode.rs
deleted file mode 100644
index 91b28fc83..000000000
--- a/src/input/encode.rs
+++ /dev/null
@@ -1,1309 +0,0 @@
-use std::fmt::Write as _;
-
-use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEventKind};
-
-use super::model::KITTY_FLAG_REPORT_ALL_KEYS;
-use super::{KeyboardProtocol, MouseProtocolEncoding, TerminalKey};
-
-const KITTY_FLAG_REPORT_EVENT_TYPES: u16 = 0b0000_0010;
-const KITTY_FLAG_REPORT_ALTERNATE_KEYS: u16 = 0b0000_0100;
-const KITTY_FLAG_REPORT_ASSOCIATED_TEXT: u16 = 0b0001_0000;
-
-/// Encode a key event for a PTY child using the pane's negotiated keyboard protocol.
-#[allow(dead_code)] // exercised in input unit tests; production uses TerminalRuntime helpers
-pub fn encode_key(key: KeyEvent, protocol: KeyboardProtocol) -> Vec<u8> {
- encode_terminal_key(key.into(), protocol)
-}
-
-pub fn encode_terminal_key(key: TerminalKey, protocol: KeyboardProtocol) -> Vec<u8> {
- // The host layout has not committed text for this Windows dead key. Neither
- // legacy nor Kitty panes should receive its physical character fallback.
- // Legacy Windows panes take the native ConPTY fallback before reaching this encoder.
- if key.is_windows_dead_key() {
- return Vec::new();
- }
-
- // Super has no legacy character encoding, and Ctrl+Shift+letter would
- // collapse into the same C0 byte as Ctrl+letter. Preserve both chords with
- // CSI-u, matching Ghostty's legacy encoder.
- if matches!(protocol, KeyboardProtocol::Legacy)
- && key.kind != crossterm::event::KeyEventKind::Release
- && legacy_chord_needs_csi_u(&key)
- {
- if let Some(bytes) = try_encode_csi_u(&key, 0) {
- return bytes;
- }
- }
-
- // REPORT_ALL_KEYS must retain physical press/repeat/release semantics instead of
- // reducing a native key to its layout-generated text.
- let preserve_physical_key = key.has_physical_identity() && protocol.reports_all_keys();
- if !preserve_physical_key && key.kind != crossterm::event::KeyEventKind::Release {
- if let Some(text) = &key.generated_text {
- return text.as_bytes().to_vec();
- }
- }
-
- // A release event only produces bytes when the pane protocol reports event
- // types (Kitty REPORT_EVENT_TYPES). Otherwise the child expects a single
- // legacy byte per keystroke, so re-emitting it on release would double keys
- // like Enter/Backspace. The Ghostty wrapper can route release events through
- // this fallback, so guard the fallback encoder too.
- if key.kind == crossterm::event::KeyEventKind::Release && !protocol.reports_event_types() {
- return Vec::new();
- }
-
- let kitty_first = protocol.reports_all_keys()
- || (key.kind == crossterm::event::KeyEventKind::Release && protocol.reports_event_types());
-
- if kitty_first {
- if let KeyboardProtocol::Kitty { flags } = protocol {
- if let Some(bytes) = try_encode_csi_u(&key, flags) {
- return bytes;
- }
- }
- }
-
- if let Some(bytes) = encode_text_input(&key) {
- return bytes;
- }
-
- if !kitty_first {
- if let KeyboardProtocol::Kitty { flags } = protocol {
- if let Some(bytes) = try_encode_csi_u(&key, flags) {
- return bytes;
- }
- }
- }
- if key.kind == crossterm::event::KeyEventKind::Release && protocol.reports_event_types() {
- return Vec::new();
- }
- encode_legacy(key)
-}
-
-fn legacy_chord_needs_csi_u(key: &TerminalKey) -> bool {
- let KeyCode::Char(ch) = key.code else {
- return false;
- };
- key.modifiers.contains(KeyModifiers::SUPER)
- || (ch.is_ascii_alphabetic()
- && key
- .modifiers
- .contains(KeyModifiers::CONTROL | KeyModifiers::SHIFT))
-}
-
-#[allow(dead_code)] // exercised in input unit tests; production uses TerminalRuntime helpers
-pub fn encode_cursor_key(code: KeyCode, application_cursor: bool) -> Vec<u8> {
- match (code, application_cursor) {
- (KeyCode::Up, true) => b"\x1bOA".to_vec(),
- (KeyCode::Down, true) => b"\x1bOB".to_vec(),
- (KeyCode::Right, true) => b"\x1bOC".to_vec(),
- (KeyCode::Left, true) => b"\x1bOD".to_vec(),
- (KeyCode::Up, false) => b"\x1b[A".to_vec(),
- (KeyCode::Down, false) => b"\x1b[B".to_vec(),
- (KeyCode::Right, false) => b"\x1b[C".to_vec(),
- (KeyCode::Left, false) => b"\x1b[D".to_vec(),
- _ => encode_legacy(KeyEvent::new(code, KeyModifiers::empty()).into()),
- }
-}
-
-#[allow(dead_code)] // exercised in input unit tests; pane runtime uses backend helpers
-pub fn encode_mouse_scroll(
- kind: MouseEventKind,
- column: u16,
- row: u16,
- modifiers: KeyModifiers,
- encoding: MouseProtocolEncoding,
-) -> Option<Vec<u8>> {
- let button = match kind {
- MouseEventKind::ScrollUp => 64u16,
- MouseEventKind::ScrollDown => 65u16,
- MouseEventKind::ScrollLeft => 66u16,
- MouseEventKind::ScrollRight => 67u16,
- _ => return None,
- };
- encode_mouse_cb(button, false, column, row, modifiers, encoding)
-}
-
-#[allow(dead_code)] // exercised in input unit tests; pane runtime uses backend helpers
-pub fn encode_mouse_button(
- kind: MouseEventKind,
- column: u16,
- row: u16,
- modifiers: KeyModifiers,
- encoding: MouseProtocolEncoding,
-) -> Option<Vec<u8>> {
- let (button, release) = match kind {
- MouseEventKind::Down(MouseButton::Left) => (0u16, false),
- MouseEventKind::Down(MouseButton::Middle) => (1u16, false),
- MouseEventKind::Down(MouseButton::Right) => (2u16, false),
- MouseEventKind::Up(MouseButton::Left) => (0u16, true),
- MouseEventKind::Up(MouseButton::Middle) => (1u16, true),
- MouseEventKind::Up(MouseButton::Right) => (2u16, true),
- MouseEventKind::Drag(MouseButton::Left) => (32u16, false),
- MouseEventKind::Drag(MouseButton::Middle) => (33u16, false),
- MouseEventKind::Drag(MouseButton::Right) => (34u16, false),
- _ => return None,
- };
- encode_mouse_cb(button, release, column, row, modifiers, encoding)
-}
-
-#[allow(dead_code)] // only reached through mouse encoding helpers above
-fn encode_mouse_cb(
- base_button: u16,
- release: bool,
- column: u16,
- row: u16,
- modifiers: KeyModifiers,
- encoding: MouseProtocolEncoding,
-) -> Option<Vec<u8>> {
- let mut cb = match (encoding, release) {
- (MouseProtocolEncoding::Sgr | MouseProtocolEncoding::SgrPixels, true) => base_button,
- (_, true) => 3,
- (_, false) => base_button,
- };
- if modifiers.contains(KeyModifiers::SHIFT) {
- cb += 4;
- }
- if modifiers.contains(KeyModifiers::ALT) {
- cb += 8;
- }
- if modifiers.contains(KeyModifiers::CONTROL) {
- cb += 16;
- }
-
- let column = column as u32 + 1;
- let row = row as u32 + 1;
-
- match encoding {
- MouseProtocolEncoding::Sgr | MouseProtocolEncoding::SgrPixels => Some(
- format!(
- "\x1b[<{cb};{column};{row}{}",
- if release { 'm' } else { 'M' }
- )
- .into_bytes(),
- ),
- MouseProtocolEncoding::Default => {
- let cb = u8::try_from(cb + 32).ok()?;
- let column = u8::try_from(column + 32).ok()?;
- let row = u8::try_from(row + 32).ok()?;
- Some(vec![0x1b, b'[', b'M', cb, column, row])
- }
- MouseProtocolEncoding::Utf8 => {
- let mut bytes = Vec::with_capacity(16);
- bytes.extend_from_slice(b"\x1b[M");
- push_mouse_codepoint(&mut bytes, cb as u32 + 32)?;
- push_mouse_codepoint(&mut bytes, column + 32)?;
- push_mouse_codepoint(&mut bytes, row + 32)?;
- Some(bytes)
- }
- }
-}
-
-#[allow(dead_code)] // only reached through mouse encoding helpers above
-fn push_mouse_codepoint(bytes: &mut Vec<u8>, value: u32) -> Option<()> {
- let ch = char::from_u32(value)?;
- let mut buf = [0u8; 4];
- bytes.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
- Some(())
-}
-
-/// CSI u encoding: \e[{codepoint};{modifiers}u
-/// Used when the child has pushed Kitty keyboard enhancement.
-/// Returns None if the key doesn't need CSI u (unmodified basic keys).
-fn try_encode_csi_u(key: &TerminalKey, flags: u16) -> Option<Vec<u8>> {
- let mods = key.modifiers;
- let event_suffix = kitty_event_suffix(key, flags);
- let report_all_keys = flags & KITTY_FLAG_REPORT_ALL_KEYS != 0;
-
- if !report_all_keys
- && key.modifiers.is_empty()
- && matches!(key.code, KeyCode::Enter | KeyCode::Tab | KeyCode::Backspace)
- {
- return None;
- }
-
- // Unmodified keys use legacy encoding (more compatible)
- if mods.is_empty() && event_suffix.is_none() && !report_all_keys {
- return None;
- }
-
- // Special keys (arrows, F-keys, etc.) have well-established legacy
- // xterm modified formats (\x1b[1;3A for Alt+Up, etc.) that are universally
- // understood. Even Ghostty sends these in legacy format with kitty mode on.
- // Only use CSI u for character keys and keys without legacy representations.
- match key.code {
- KeyCode::Up
- | KeyCode::Down
- | KeyCode::Left
- | KeyCode::Right
- | KeyCode::Home
- | KeyCode::End
- | KeyCode::PageUp
- | KeyCode::PageDown
- | KeyCode::Insert
- | KeyCode::Delete
- | KeyCode::F(_)
- if event_suffix.is_none() && !report_all_keys =>
- {
- return None; // let legacy handle these
- }
- _ => {}
- }
-
- let (codepoint, alternate_shifted) = match key.code {
- KeyCode::Char(c) => {
- let base = canonical_kitty_char(c, mods);
- let shifted = alternate_shifted_codepoint(key, flags);
- (base as u32, shifted)
- }
- KeyCode::Enter => (13, None),
- KeyCode::Tab => (9, None),
- KeyCode::Backspace => (127, None),
- KeyCode::Esc => (27, None),
- KeyCode::Left => (57417, None),
- KeyCode::Right => (57418, None),
- KeyCode::Up => (57419, None),
- KeyCode::Down => (57420, None),
- KeyCode::PageUp => (57421, None),
- KeyCode::PageDown => (57422, None),
- KeyCode::Home => (57423, None),
- KeyCode::End => (57424, None),
- KeyCode::Insert => (57425, None),
- KeyCode::Delete => (57426, None),
- _ => return None, // fall back to legacy for unhandled keys
- };
-
- let modifier = kitty_modifier(mods);
-
- let mut sequence = String::with_capacity(32);
- sequence.push_str("\x1b[");
- write!(&mut sequence, "{codepoint}").ok()?;
- if let Some(shifted) = alternate_shifted {
- write!(&mut sequence, ":{shifted}").ok()?;
- }
- write!(&mut sequence, ";{modifier}").ok()?;
- if let Some(event) = event_suffix {
- write!(&mut sequence, ":{event}").ok()?;
- }
- if flags & KITTY_FLAG_REPORT_ASSOCIATED_TEXT != 0 {
- if let Some(text) = text_codepoint_for_key(key) {
- write!(&mut sequence, ";{text}").ok()?;
- }
- }
- sequence.push('u');
-
- Some(sequence.into_bytes())
-}
-
-fn text_codepoint_for_key(key: &TerminalKey) -> Option<u32> {
- let ch = text_char_for_key(key)?;
- (!ch.is_control()).then_some(ch as u32)
-}
-
-/// Legacy terminal encoding (standard escape sequences).
-fn encode_legacy(key: TerminalKey) -> Vec<u8> {
- let mods = key.modifiers;
-
- // Modified special keys (arrows, home, end, etc.) use xterm format:
- // \x1b[1;{modifier}A for arrows/home/end
- // \x1b[{n};{modifier}~ for insert/delete/pgup/pgdn
- // The ESC-prefix hack doesn't work for these since they're already escape sequences.
- if !mods.is_empty() {
- if let Some(bytes) = encode_modified_special(key.code, mods) {
- return bytes;
- }
- }
-
- // Alt modifier on character keys: prefix with ESC
- if mods.contains(KeyModifiers::ALT) {
- let inner = key.with_modifiers(mods.difference(KeyModifiers::ALT));
- let mut bytes = vec![0x1b];
- bytes.extend(encode_legacy_inner(inner));
- return bytes;
- }
- encode_legacy_inner(key)
-}
-
-/// xterm-style encoding for modified special keys.
-/// Modifier value: 1 + (shift?1:0) + (alt?2:0) + (ctrl?4:0)
-fn encode_modified_special(code: KeyCode, mods: KeyModifiers) -> Option<Vec<u8>> {
- let modifier = xterm_modifier(mods);
- if modifier <= 1 {
- return None; // no modifiers to encode
- }
-
- match code {
- // CSI 1;{mod}{letter} format
- KeyCode::Up => Some(format!("\x1b[1;{modifier}A").into_bytes()),
- KeyCode::Down => Some(format!("\x1b[1;{modifier}B").into_bytes()),
- KeyCode::Right => Some(format!("\x1b[1;{modifier}C").into_bytes()),
- KeyCode::Left => Some(format!("\x1b[1;{modifier}D").into_bytes()),
- KeyCode::Home => Some(format!("\x1b[1;{modifier}H").into_bytes()),
- KeyCode::End => Some(format!("\x1b[1;{modifier}F").into_bytes()),
- // CSI {n};{mod}~ format
- KeyCode::Insert => Some(format!("\x1b[2;{modifier}~").into_bytes()),
- KeyCode::Delete => Some(format!("\x1b[3;{modifier}~").into_bytes()),
- KeyCode::PageUp => Some(format!("\x1b[5;{modifier}~").into_bytes()),
- KeyCode::PageDown => Some(format!("\x1b[6;{modifier}~").into_bytes()),
- // F1-F4: CSI 1;{mod}{P-S}
- KeyCode::F(1) => Some(format!("\x1b[1;{modifier}P").into_bytes()),
- KeyCode::F(2) => Some(format!("\x1b[1;{modifier}Q").into_bytes()),
- KeyCode::F(3) => Some(format!("\x1b[1;{modifier}R").into_bytes()),
- KeyCode::F(4) => Some(format!("\x1b[1;{modifier}S").into_bytes()),
- // F5-F12: CSI {n};{mod}~
- KeyCode::F(n @ 5..=12) => {
- let code = match n {
- 5 => 15,
- 6 => 17,
- 7 => 18,
- 8 => 19,
- 9 => 20,
- 10 => 21,
- 11 => 23,
- 12 => 24,
- _ => unreachable!(),
- };
- Some(format!("\x1b[{code};{modifier}~").into_bytes())
- }
- _ => None,
- }
-}
-
-/// xterm modifier encoding: 1 + shift(1) + alt(2) + ctrl(4)
-/// Used for legacy modified special keys (arrows, function keys, etc.)
-fn xterm_modifier(mods: KeyModifiers) -> u32 {
- let mut m = 1u32;
- if mods.contains(KeyModifiers::SHIFT) {
- m += 1;
- }
- if mods.contains(KeyModifiers::ALT) {
- m += 2;
- }
- if mods.contains(KeyModifiers::CONTROL) {
- m += 4;
- }
- m
-}
-
-/// Kitty protocol modifier encoding: 1 + shift(1) + alt(2) + ctrl(4) + super(8) + hyper(16) + meta(32)
-/// Superset of xterm — adds Super/Hyper/Meta bits.
-fn kitty_modifier(mods: KeyModifiers) -> u32 {
- let mut m = xterm_modifier(mods);
- if mods.contains(KeyModifiers::SUPER) {
- m += 8;
- }
- if mods.contains(KeyModifiers::HYPER) {
- m += 16;
- }
- if mods.contains(KeyModifiers::META) {
- m += 32;
- }
- m
-}
-
-fn encode_text_input(key: &TerminalKey) -> Option<Vec<u8>> {
- let ch = text_char_for_key(key)?;
- let mut buf = [0u8; 4];
- Some(ch.encode_utf8(&mut buf).as_bytes().to_vec())
-}
-
-fn text_char_for_key(key: &TerminalKey) -> Option<char> {
- if key.kind == crossterm::event::KeyEventKind::Release {
- return None;
- }
-
- let KeyCode::Char(ch) = key.code else {
- return None;
- };
-
- if key.modifiers.is_empty() {
- return Some(ch);
- }
- if key.modifiers == KeyModifiers::SHIFT {
- return shifted_text_char(key, ch);
- }
- None
-}
-
-fn shifted_text_char(key: &TerminalKey, ch: char) -> Option<char> {
- if let Some(shifted) = key.shifted_codepoint.and_then(char::from_u32) {
- return Some(shifted);
- }
-
- if ch.is_ascii_uppercase() {
- return Some(ch);
- }
-
- if ch.is_ascii_lowercase() {
- return Some(ch.to_ascii_uppercase());
- }
-
- if is_shifted_ascii_punctuation(ch) {
- return Some(ch);
- }
-
- None
-}
-
-fn is_shifted_ascii_punctuation(ch: char) -> bool {
- matches!(
- ch,
- '!' | '@'
- | '#'
- | '$'
- | '%'
- | '^'
- | '&'
- | '*'
- | '('
- | ')'
- | '_'
- | '+'
- | '{'
- | '}'
- | '|'
- | ':'
- | '"'
- | '<'
- | '>'
- | '?'
- | '~'
- )
-}
-
-fn canonical_kitty_char(ch: char, mods: KeyModifiers) -> char {
- if mods.contains(KeyModifiers::SHIFT) && ch.is_ascii_uppercase() {
- ch.to_ascii_lowercase()
- } else {
- ch
- }
-}
-
-fn alternate_shifted_codepoint(key: &TerminalKey, flags: u16) -> Option<u32> {
- if flags & KITTY_FLAG_REPORT_ALTERNATE_KEYS == 0 {
- return None;
- }
-
- if let Some(shifted) = key.shifted_codepoint {
- return Some(shifted);
- }
-
- match key.code {
- KeyCode::Char(ch)
- if key.modifiers.contains(KeyModifiers::SHIFT) && ch.is_ascii_uppercase() =>
- {
- Some(ch as u32)
- }
- _ => None,
- }
-}
-
-fn kitty_event_suffix(key: &TerminalKey, flags: u16) -> Option<u8> {
- if flags & KITTY_FLAG_REPORT_EVENT_TYPES == 0 {
- return None;
- }
-
- Some(match key.kind {
- crossterm::event::KeyEventKind::Press => 1,
- crossterm::event::KeyEventKind::Repeat => 2,
- crossterm::event::KeyEventKind::Release => 3,
- })
-}
-
-fn encode_legacy_inner(key: TerminalKey) -> Vec<u8> {
- match key.code {
- KeyCode::Char(ch) => {
- if key.modifiers.contains(KeyModifiers::CONTROL) {
- let upper = ch.to_ascii_uppercase();
- match upper {
- 'A'..='Z' => vec![upper as u8 - 64],
- ' ' | '@' | '2' => vec![0],
- '[' | '3' => vec![27],
- '\\' | '4' => vec![28],
- ']' | '5' => vec![29],
- '^' | '6' => vec![30],
- '_' | '/' | '7' | '-' => vec![31],
- _ => ch.to_string().into_bytes(),
- }
- } else {
- let ch = if key.modifiers == KeyModifiers::SHIFT {
- shifted_text_char(&key, ch).unwrap_or(ch)
- } else {
- ch
- };
- let mut buf = [0u8; 4];
- ch.encode_utf8(&mut buf).as_bytes().to_vec()
- }
- }
- KeyCode::Enter => vec![b'\r'],
- KeyCode::Backspace => vec![127],
- KeyCode::Tab => vec![9],
- KeyCode::BackTab => vec![27, 91, 90],
- KeyCode::Esc => vec![27],
- KeyCode::Left => vec![27, 91, 68],
- KeyCode::Right => vec![27, 91, 67],
- KeyCode::Up => vec![27, 91, 65],
- KeyCode::Down => vec![27, 91, 66],
- KeyCode::Home => vec![27, 91, 72],
- KeyCode::End => vec![27, 91, 70],
- KeyCode::PageUp => vec![27, 91, 53, 126],
- KeyCode::PageDown => vec![27, 91, 54, 126],
- KeyCode::Delete => vec![27, 91, 51, 126],
- KeyCode::Insert => vec![27, 91, 50, 126],
- KeyCode::F(n) => encode_f_key(n),
- _ => vec![],
- }
-}
-
-fn encode_f_key(n: u8) -> Vec<u8> {
- match n {
- 1 => vec![27, 79, 80],
- 2 => vec![27, 79, 81],
- 3 => vec![27, 79, 82],
- 4 => vec![27, 79, 83],
- 5 => vec![27, 91, 49, 53, 126],
- 6 => vec![27, 91, 49, 55, 126],
- 7 => vec![27, 91, 49, 56, 126],
- 8 => vec![27, 91, 49, 57, 126],
- 9 => vec![27, 91, 50, 48, 126],
- 10 => vec![27, 91, 50, 49, 126],
- 11 => vec![27, 91, 50, 51, 126],
- 12 => vec![27, 91, 50, 52, 126],
- _ => vec![],
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
-
- use super::*;
- use crate::input::parse_terminal_key_sequence;
-
- fn assert_terminal_key_eq(
- actual: TerminalKey,
- code: KeyCode,
- modifiers: KeyModifiers,
- kind: crossterm::event::KeyEventKind,
- shifted_codepoint: Option<u32>,
- ) {
- assert_eq!(actual.code, code);
- assert_eq!(actual.modifiers, modifiers);
- assert_eq!(actual.kind, kind);
- assert_eq!(actual.shifted_codepoint, shifted_codepoint);
- }
-
- #[test]
- fn kitty_all_keys_does_not_encode_windows_altgr_dead_key_phases() {
- use crossterm::event::KeyEventKind;
-
- let key = TerminalKey::new(KeyCode::Char('4'), KeyModifiers::empty()).with_windows_record(
- crate::input::WindowsKeyRecord {
- key_down: true,
- repeat_count: 1,
- virtual_key_code: 52,
- virtual_scan_code: 5,
- unicode: 0,
- control_key_state: 9,
- },
- );
- for kind in [
- KeyEventKind::Press,
- KeyEventKind::Repeat,
- KeyEventKind::Release,
- ] {
- assert!(
- encode_terminal_key(
- key.clone().with_kind(kind),
- KeyboardProtocol::Kitty { flags: 31 },
- )
- .is_empty(),
- "{kind:?}"
- );
- }
- }
-
- #[test]
- fn legacy_enter() {
- let key = KeyEvent::new(KeyCode::Enter, KeyModifiers::empty());
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), vec![b'\r']);
- }
-
- #[test]
- fn legacy_ctrl_c() {
- let key = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), vec![3]);
- }
-
- #[test]
- fn legacy_ctrl_shift_letter_preserves_shift_with_csi_u() {
- for ch in ['c', 'C'] {
- let key = KeyEvent::new(
- KeyCode::Char(ch),
- KeyModifiers::CONTROL | KeyModifiers::SHIFT,
- );
- assert_eq!(
- encode_key(key, KeyboardProtocol::Legacy),
- b"\x1b[99;6u",
- "ch={ch}"
- );
- }
- }
-
- #[test]
- fn legacy_ctrl_alt_shift_letter_uses_csi_u() {
- let key = KeyEvent::new(
- KeyCode::Char('c'),
- KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT,
- );
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1b[99;8u");
- }
-
- #[test]
- fn legacy_ctrl_shift_letter_from_kitty_host_input_keeps_shift() {
- let key = parse_terminal_key_sequence("\x1b[99:67;6:1u").expect("Ctrl+Shift+C");
- assert_eq!(
- encode_terminal_key(key, KeyboardProtocol::Legacy),
- b"\x1b[99;6u"
- );
- }
-
- #[test]
- fn legacy_ctrl_shift_punctuation_keeps_c0_byte() {
- let key = KeyEvent::new(
- KeyCode::Char('_'),
- KeyModifiers::CONTROL | KeyModifiers::SHIFT,
- );
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), vec![31]);
- }
-
- #[test]
- fn legacy_ctrl_slash_aliases_ctrl_underscore() {
- let key = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::CONTROL);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), vec![31]);
- }
-
- #[test]
- fn legacy_ctrl_non_ascii_char_uses_utf8() {
- let key = KeyEvent::new(KeyCode::Char('ß'), KeyModifiers::CONTROL);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), "ß".as_bytes());
- }
-
- #[test]
- fn legacy_shift_enter_is_just_cr() {
- let key = KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), vec![b'\r']);
- }
-
- #[test]
- fn legacy_alt_up() {
- let key = KeyEvent::new(KeyCode::Up, KeyModifiers::ALT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1b[1;3A");
- }
-
- #[test]
- fn legacy_shift_right() {
- let key = KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1b[1;2C");
- }
-
- #[test]
- fn legacy_ctrl_left() {
- let key = KeyEvent::new(KeyCode::Left, KeyModifiers::CONTROL);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1b[1;5D");
- }
-
- #[test]
- fn legacy_ctrl_shift_end() {
- let key = KeyEvent::new(KeyCode::End, KeyModifiers::CONTROL | KeyModifiers::SHIFT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1b[1;6F");
- }
-
- #[test]
- fn legacy_alt_delete() {
- let key = KeyEvent::new(KeyCode::Delete, KeyModifiers::ALT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1b[3;3~");
- }
-
- #[test]
- fn legacy_shift_f5() {
- let key = KeyEvent::new(KeyCode::F(5), KeyModifiers::SHIFT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1b[15;2~");
- }
-
- #[test]
- fn legacy_alt_char_still_esc_prefix() {
- let key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::ALT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1ba");
- }
-
- #[test]
- fn legacy_alt_shift_punctuation_uses_shifted_text() {
- let key = parse_terminal_key_sequence("\x1b[44:60;4u").unwrap();
- assert_eq!(encode_terminal_key(key, KeyboardProtocol::Legacy), b"\x1b<");
- }
-
- #[test]
- fn legacy_alt_backspace_sends_escape_delete() {
- let key = KeyEvent::new(KeyCode::Backspace, KeyModifiers::ALT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"\x1b\x7f");
- }
-
- #[test]
- fn application_cursor_keys_use_ss3_sequences() {
- assert_eq!(encode_cursor_key(KeyCode::Up, true), b"\x1bOA");
- assert_eq!(encode_cursor_key(KeyCode::Down, true), b"\x1bOB");
- }
-
- #[test]
- fn normal_cursor_keys_use_csi_sequences() {
- assert_eq!(encode_cursor_key(KeyCode::Up, false), b"\x1b[A");
- assert_eq!(encode_cursor_key(KeyCode::Down, false), b"\x1b[B");
- }
-
- #[test]
- fn sgr_mouse_scroll_encodes_wheel_button_and_coordinates() {
- let encoded = encode_mouse_scroll(
- crossterm::event::MouseEventKind::ScrollDown,
- 4,
- 6,
- KeyModifiers::SHIFT,
- MouseProtocolEncoding::Sgr,
- )
- .expect("mouse scroll should encode");
-
- assert_eq!(encoded, b"\x1b[<69;5;7M");
- }
-
- #[test]
- fn sgr_mouse_release_keeps_button_code() {
- let encoded = encode_mouse_button(
- crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
- 11,
- 9,
- KeyModifiers::empty(),
- MouseProtocolEncoding::Sgr,
- )
- .expect("mouse release should encode");
-
- assert_eq!(encoded, b"\x1b[<0;12;10m");
- }
-
- #[test]
- fn kitty_shift_enter() {
- let key = KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[13;2u"
- );
- }
-
- #[test]
- fn kitty_ctrl_shift_a() {
- let key = KeyEvent::new(
- KeyCode::Char('a'),
- KeyModifiers::CONTROL | KeyModifiers::SHIFT,
- );
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[97;6u"
- );
- }
-
- #[test]
- fn kitty_shift_uppercase_letter_sends_text() {
- let key = KeyEvent::new(KeyCode::Char('L'), KeyModifiers::SHIFT);
- assert_eq!(encode_key(key, KeyboardProtocol::Kitty { flags: 1 }), b"L");
- }
-
- #[test]
- fn kitty_shift_uppercase_letter_ignores_alternate_key_reporting_for_text() {
- let key = KeyEvent::new(KeyCode::Char('L'), KeyModifiers::SHIFT);
- assert_eq!(encode_key(key, KeyboardProtocol::Kitty { flags: 7 }), b"L");
- }
-
- #[test]
- fn kitty_shift_lowercase_letter_sends_uppercase_text() {
- let key = KeyEvent::new(KeyCode::Char('l'), KeyModifiers::SHIFT);
- assert_eq!(encode_key(key, KeyboardProtocol::Kitty { flags: 1 }), b"L");
- }
-
- #[test]
- fn kitty_alt_shift_uppercase_letter_uses_base_codepoint() {
- let key = KeyEvent::new(KeyCode::Char('L'), KeyModifiers::ALT | KeyModifiers::SHIFT);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[108;4u"
- );
- }
-
- #[test]
- fn kitty_ctrl_shift_uppercase_letter_uses_base_codepoint() {
- let key = KeyEvent::new(
- KeyCode::Char('L'),
- KeyModifiers::CONTROL | KeyModifiers::SHIFT,
- );
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[108;6u"
- );
- }
-
- #[test]
- fn legacy_shift_uppercase_letter_stays_uppercase() {
- let key = KeyEvent::new(KeyCode::Char('L'), KeyModifiers::SHIFT);
- assert_eq!(encode_key(key, KeyboardProtocol::Legacy), b"L");
- }
-
- #[test]
- fn kitty_alt_enter() {
- let key = KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[13;3u"
- );
- }
-
- #[test]
- fn kitty_alt_backspace_uses_csi_u() {
- let key = KeyEvent::new(KeyCode::Backspace, KeyModifiers::ALT);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[127;3u"
- );
- }
-
- #[test]
- fn kitty_plain_ctrl_c_uses_csi_u() {
- let key = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[99;5u"
- );
- }
-
- #[test]
- fn kitty_plain_ctrl_c_includes_press_event_when_requested() {
- let key = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 3 }),
- b"\x1b[99;5:1u"
- );
- }
-
- #[test]
- fn kitty_unmodified_uses_legacy() {
- let key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty());
- assert_eq!(encode_key(key, KeyboardProtocol::Kitty { flags: 1 }), b"a");
- }
-
- #[test]
- fn kitty_report_event_types_keeps_basic_compatibility_keys_legacy() {
- let cases = [
- (KeyCode::Enter, b"\r".as_slice()),
- (KeyCode::Tab, b"\t".as_slice()),
- (KeyCode::Backspace, b"\x7f".as_slice()),
- ];
-
- for (code, expected) in cases {
- let press = KeyEvent::new_with_kind(
- code,
- KeyModifiers::empty(),
- crossterm::event::KeyEventKind::Press,
- );
- assert_eq!(
- encode_key(press, KeyboardProtocol::Kitty { flags: 3 }),
- expected,
- "{code:?} press should stay legacy-compatible without REPORT_ALL_KEYS"
- );
-
- let repeat = KeyEvent::new_with_kind(
- code,
- KeyModifiers::empty(),
- crossterm::event::KeyEventKind::Repeat,
- );
- assert_eq!(
- encode_key(repeat, KeyboardProtocol::Kitty { flags: 3 }),
- expected,
- "{code:?} repeat should stay legacy-compatible without REPORT_ALL_KEYS"
- );
-
- let release = KeyEvent::new_with_kind(
- code,
- KeyModifiers::empty(),
- crossterm::event::KeyEventKind::Release,
- );
- assert_eq!(
- encode_key(release, KeyboardProtocol::Kitty { flags: 3 }),
- b"",
- "{code:?} release should not fall back to legacy bytes"
- );
- }
- }
-
- #[test]
- fn kitty_report_all_keys_encodes_basic_compatibility_keys_with_events() {
- let enter_press = KeyEvent::new_with_kind(
- KeyCode::Enter,
- KeyModifiers::empty(),
- crossterm::event::KeyEventKind::Press,
- );
- assert_eq!(
- encode_key(enter_press, KeyboardProtocol::Kitty { flags: 9 }),
- b"\x1b[13;1u"
- );
-
- let backspace_press = KeyEvent::new_with_kind(
- KeyCode::Backspace,
- KeyModifiers::empty(),
- crossterm::event::KeyEventKind::Press,
- );
- assert_eq!(
- encode_key(backspace_press, KeyboardProtocol::Kitty { flags: 11 }),
- b"\x1b[127;1:1u"
- );
-
- let backspace_release = KeyEvent::new_with_kind(
- KeyCode::Backspace,
- KeyModifiers::empty(),
- crossterm::event::KeyEventKind::Release,
- );
- assert_eq!(
- encode_key(backspace_release, KeyboardProtocol::Kitty { flags: 11 }),
- b"\x1b[127;1:3u"
- );
- }
-
- #[test]
- fn kitty_report_all_keys_encodes_printable_event_kinds() {
- for (kind, expected) in [
- (
- crossterm::event::KeyEventKind::Press,
- b"\x1b[106;1:1u".as_slice(),
- ),
- (
- crossterm::event::KeyEventKind::Repeat,
- b"\x1b[106;1:2u".as_slice(),
- ),
- (
- crossterm::event::KeyEventKind::Release,
- b"\x1b[106;1:3u".as_slice(),
- ),
- ] {
- let key = KeyEvent::new_with_kind(KeyCode::Char('j'), KeyModifiers::empty(), kind);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 15 }),
- expected
- );
- }
- }
-
- #[test]
- fn kitty_report_associated_text_embeds_shifted_printables() {
- let cases = [
- (
- TerminalKey::new(KeyCode::Char('A'), KeyModifiers::SHIFT),
- b"\x1b[97;2;65u".as_slice(),
- ),
- (
- TerminalKey::new(KeyCode::Char('1'), KeyModifiers::SHIFT)
- .with_shifted_codepoint('!' as u32),
- b"\x1b[49;2;33u".as_slice(),
- ),
- (
- TerminalKey::new(KeyCode::Char(':'), KeyModifiers::SHIFT),
- b"\x1b[58;2;58u".as_slice(),
- ),
- ];
-
- for (key, expected) in cases {
- assert_eq!(
- encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 25 }),
- expected
- );
- }
- }
-
- #[test]
- fn kitty_associated_text_composes_with_alternates_and_events() {
- for (kind, expected) in [
- (
- crossterm::event::KeyEventKind::Press,
- b"\x1b[97:65;2:1;65u".as_slice(),
- ),
- (
- crossterm::event::KeyEventKind::Repeat,
- b"\x1b[97:65;2:2;65u".as_slice(),
- ),
- (
- crossterm::event::KeyEventKind::Release,
- b"\x1b[97:65;2:3u".as_slice(),
- ),
- ] {
- let key = TerminalKey::new(KeyCode::Char('A'), KeyModifiers::SHIFT).with_kind(kind);
- assert_eq!(
- encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 31 }),
- expected
- );
- }
- }
-
- #[test]
- fn kitty_printable_release_is_encoded_without_report_all() {
- let release = KeyEvent::new_with_kind(
- KeyCode::Char('j'),
- KeyModifiers::empty(),
- crossterm::event::KeyEventKind::Release,
- );
- assert_eq!(
- encode_key(release, KeyboardProtocol::Kitty { flags: 3 }),
- b"\x1b[106;1:3u"
- );
-
- let mut malformed_release = TerminalKey::from(release);
- malformed_release.generated_text = Some("j".to_owned());
- assert_eq!(
- encode_terminal_key(malformed_release, KeyboardProtocol::Kitty { flags: 3 }),
- b"\x1b[106;1:3u"
- );
- }
-
- #[test]
- fn kitty_shift_tab() {
- let key = KeyEvent::new(KeyCode::Tab, KeyModifiers::SHIFT);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[9;2u"
- );
- }
-
- #[test]
- fn kitty_ctrl_shift_enter() {
- let key = KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL | KeyModifiers::SHIFT);
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 1 }),
- b"\x1b[13;6u"
- );
- }
-
- #[test]
- fn kitty_repeat_event_type_is_encoded_when_requested() {
- let key = KeyEvent::new_with_kind(
- KeyCode::Enter,
- KeyModifiers::SHIFT,
- crossterm::event::KeyEventKind::Repeat,
- );
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 3 }),
- b"\x1b[13;2:2u"
- );
- }
-
- #[test]
- fn kitty_shift_letter_release_uses_csi_u() {
- let key = KeyEvent::new_with_kind(
- KeyCode::Char('L'),
- KeyModifiers::SHIFT,
- crossterm::event::KeyEventKind::Release,
- );
- assert_eq!(
- encode_key(key, KeyboardProtocol::Kitty { flags: 7 }),
- b"\x1b[108:76;2:3u"
- );
- }
-
- #[test]
- fn kitty_shifted_punctuation_literals_send_text() {
- for ch in "!@#$%^&*()_+{}|:\"<>?~".chars() {
- let key = TerminalKey::new(KeyCode::Char(ch), KeyModifiers::SHIFT);
- let encoded = encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 });
- assert_eq!(encoded, ch.to_string().into_bytes(), "ch={ch}");
- }
- }
-
- #[test]
- fn kitty_shifted_punctuation_release_does_not_emit_text() {
- let key = TerminalKey::new(KeyCode::Char('?'), KeyModifiers::SHIFT)
- .with_kind(crossterm::event::KeyEventKind::Release);
- assert_eq!(
- encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 }),
- b"\x1b[63;2:3u"
- );
- }
-
- #[test]
- fn kitty_shifted_punctuation_does_not_infer_layout() {
- let key = TerminalKey::new(KeyCode::Char('1'), KeyModifiers::SHIFT);
- assert_eq!(
- encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 }),
- b"\x1b[49;2:1u"
- );
- }
-
- #[test]
- fn kitty_modified_shifted_punctuation_stays_modified_key() {
- for (modifiers, expected) in [
- (
- KeyModifiers::CONTROL | KeyModifiers::SHIFT,
- b"\x1b[33;6:1u".as_slice(),
- ),
- (
- KeyModifiers::ALT | KeyModifiers::SHIFT,
- b"\x1b[33;4:1u".as_slice(),
- ),
- (
- KeyModifiers::SUPER | KeyModifiers::SHIFT,
- b"\x1b[33;10:1u".as_slice(),
- ),
- ] {
- let key = TerminalKey::new(KeyCode::Char('!'), modifiers);
- let encoded = encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 });
- assert_eq!(encoded, expected, "modifiers={modifiers:?}");
- }
- }
-
- #[test]
- fn release_bytes_gated_on_report_event_types() {
- for code in [KeyCode::Enter, KeyCode::Backspace] {
- let release = KeyEvent::new_with_kind(
- code,
- KeyModifiers::empty(),
- crossterm::event::KeyEventKind::Release,
- );
-
- // Legacy and Kitty disambiguate-only (no REPORT_EVENT_TYPES) must not
- // emit a byte on release, otherwise Enter/Backspace double (issue #769).
- assert_eq!(encode_key(release, KeyboardProtocol::Legacy), b"");
- assert_eq!(
- encode_key(release, KeyboardProtocol::Kitty { flags: 1 }),
- b""
- );
- }
-
- let modified_release = KeyEvent::new_with_kind(
- KeyCode::Enter,
- KeyModifiers::CONTROL,
- crossterm::event::KeyEventKind::Release,
- );
- assert_eq!(
- encode_key(modified_release, KeyboardProtocol::Kitty { flags: 3 }),
- b"\x1b[13;5:3u"
- );
- }
-
- #[test]
- fn kitty_shifted_symbol_sends_text() {
- let key = TerminalKey::new(KeyCode::Char('1'), KeyModifiers::SHIFT)
- .with_shifted_codepoint('!' as u32);
- assert_eq!(
- encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 }),
- b"!"
- );
- }
-
- #[test]
- fn legacy_modified_special_roundtrip_matrix() {
- let cases = [
- KeyEvent::new(KeyCode::Up, KeyModifiers::ALT),
- KeyEvent::new(KeyCode::Down, KeyModifiers::ALT),
- KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT),
- KeyEvent::new(KeyCode::Left, KeyModifiers::CONTROL),
- KeyEvent::new(KeyCode::Home, KeyModifiers::CONTROL),
- KeyEvent::new(KeyCode::End, KeyModifiers::CONTROL | KeyModifiers::SHIFT),
- KeyEvent::new(KeyCode::PageUp, KeyModifiers::ALT),
- KeyEvent::new(KeyCode::PageDown, KeyModifiers::CONTROL),
- KeyEvent::new(KeyCode::Insert, KeyModifiers::SHIFT),
- KeyEvent::new(KeyCode::Delete, KeyModifiers::ALT),
- ];
-
- for key in cases {
- let encoded = encode_key(key, KeyboardProtocol::Legacy);
- let parsed =
- parse_terminal_key_sequence(std::str::from_utf8(&encoded).unwrap()).unwrap();
- assert_terminal_key_eq(parsed, key.code, key.modifiers, key.kind, None);
- }
- }
-
- #[test]
- fn kitty_shifted_symbol_prefers_text_over_roundtrip_key_identity() {
- let key = TerminalKey::new(KeyCode::Char('1'), KeyModifiers::SHIFT)
- .with_shifted_codepoint('!' as u32);
- let encoded = encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 });
- assert_eq!(encoded, b"!");
- }
-
- #[test]
- fn legacy_basic_special_roundtrip_matrix() {
- let cases = [
- KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Tab, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Backspace, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Up, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Down, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Left, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Right, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Home, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::End, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::PageUp, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::PageDown, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Insert, KeyModifiers::empty()),
- KeyEvent::new(KeyCode::Delete, KeyModifiers::empty()),
- ];
-
- for key in cases {
- let encoded = encode_key(key, KeyboardProtocol::Legacy);
- let parsed =
- parse_terminal_key_sequence(std::str::from_utf8(&encoded).unwrap()).unwrap();
- assert_terminal_key_eq(parsed, key.code, key.modifiers, key.kind, None);
- }
- }
-
- #[test]
- fn legacy_super_character_preserves_csi_u_chord() {
- let sequence = "\x1b[99;9u";
- let key = parse_terminal_key_sequence(sequence).expect("Super+C CSI-u key");
-
- assert_eq!(key.code, KeyCode::Char('c'));
- assert_eq!(key.modifiers, KeyModifiers::SUPER);
- assert_eq!(
- encode_terminal_key(key, KeyboardProtocol::Legacy),
- sequence.as_bytes()
- );
- }
-
- #[test]
- fn kitty_shifted_symbol_pair_matrix_is_encoded_as_text() {
- let cases = [('1', '!'), ('/', '?'), ('[', '{')];
-
- for (base, shifted) in cases {
- let key = TerminalKey::new(KeyCode::Char(base), KeyModifiers::SHIFT)
- .with_shifted_codepoint(shifted as u32);
- let encoded = encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 });
- assert_eq!(encoded, shifted.to_string().into_bytes(), "base={base}");
- }
- }
-
- #[test]
- fn chinese_char_encodes_as_utf8() {
- let key = TerminalKey::new(KeyCode::Char('中'), KeyModifiers::empty());
- let encoded = encode_terminal_key(key, KeyboardProtocol::Legacy);
- assert_eq!(encoded, "中".as_bytes());
- }
-
- #[test]
- fn chinese_char_with_kitty_protocol_encodes_as_utf8() {
- let key = TerminalKey::new(KeyCode::Char('文'), KeyModifiers::empty());
- let encoded = encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 });
- assert_eq!(encoded, "文".as_bytes());
- }
-
- #[test]
- fn chinese_char_with_modifiers_falls_back_to_kitty_encoding() {
- let key = TerminalKey::new(KeyCode::Char('测'), KeyModifiers::ALT);
- let encoded = encode_terminal_key(key, KeyboardProtocol::Kitty { flags: 7 });
- assert!(!encoded.is_empty());
- assert_ne!(encoded, "测".as_bytes());
- }
-}
diff --git a/src/input/lease.rs b/src/input/lease.rs
index 0352df427..afcee4875 100644
--- a/src/input/lease.rs
+++ b/src/input/lease.rs
@@ -18,6 +18,12 @@ impl<Source> InputLeaseKey<Source> {
}
}
+/// A press that arrived as text (typed, or committed by an IME) rather than as
+/// a native key record.
+fn is_text_press(key: &TerminalKey) -> bool {
+ key.generated_text.is_some() && key.physical_key_id().is_none()
+}
+
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct ForwardedInputLease<Target> {
pub(crate) target: Target,
@@ -69,8 +75,11 @@ where
lease_key: &InputLeaseKey<Source>,
key: TerminalKey,
) -> TerminalKey {
+ // A VT text press is always a new press: hosts send text repeats as
+ // text, and a stale lease (release reported after Shift was let go)
+ // must not turn the next press into a repeat routed to an old target.
if key.kind != crossterm::event::KeyEventKind::Press
- || (key.generated_text.is_some() && !key.has_physical_identity())
+ || (key.generated_text.is_some() && key.physical_key_id().is_none())
{
return key;
}
@@ -172,14 +181,28 @@ where
allowed
}
- pub(crate) fn remove_forwarded(
+ /// The forwarded text press from `source` when it is the only key held.
+ /// A text press ("?") names a character, not a key, so its release ("/"
+ /// after Shift was let go) cannot be matched by identity. When it is the
+ /// only tracked key the match is certain; with any other press held,
+ /// forwarded or consumed by Herdr, nothing is taken.
+ pub(crate) fn remove_sole_text_press(
&mut self,
- key: &InputLeaseKey<Source>,
- ) -> Option<ForwardedInputLease<Target>> {
- match self.leases.remove(key) {
- Some(InputLease::Forwarded(lease)) => Some(lease),
- Some(InputLease::Consumed(_)) | None => None,
- }
+ source: Source,
+ ) -> Option<InputLease<Context, Target>> {
+ let mut held = self
+ .leases
+ .iter()
+ .filter(|(lease_key, _)| lease_key.source == source);
+ let (Some((lease_key, lease)), None) = (held.next(), held.next()) else {
+ return None;
+ };
+ let is_text_press =
+ matches!(lease, InputLease::Forwarded(lease) if is_text_press(&lease.key));
+ let lease_key = *lease_key;
+ is_text_press
+ .then(|| self.leases.remove(&lease_key))
+ .flatten()
}
#[cfg(test)]
@@ -375,7 +398,10 @@ mod tests {
leases.plan_repeat(lease_key, &repeated, Some(&context)),
RepeatPlan::Forwarded(10)
));
- assert!(leases.remove_forwarded(&lease_key).is_some());
+ assert!(matches!(
+ leases.remove(&lease_key),
+ Some(InputLease::Forwarded(_))
+ ));
}
#[test]
@@ -408,7 +434,7 @@ mod tests {
leases.complete_press(lease_key, &key, Some(&context), Some(&context), Some(10)),
RepeatPlan::Ignore
));
- assert_eq!(leases.remove_forwarded(&lease_key), None);
+ assert!(leases.remove(&lease_key).is_none());
}
#[test]
diff --git a/src/input/mod.rs b/src/input/mod.rs
index 13b8ffa3f..5580da255 100644
--- a/src/input/mod.rs
+++ b/src/input/mod.rs
@@ -1,4 +1,3 @@
-mod encode;
mod keybind_help;
mod keybindings;
mod lease;
@@ -6,10 +5,6 @@ mod model;
pub(crate) mod mouse;
mod parse;
-#[allow(unused_imports)]
-pub use encode::{
- encode_cursor_key, encode_key, encode_mouse_button, encode_mouse_scroll, encode_terminal_key,
-};
pub(crate) use keybind_help::{
filter_keybind_help_groups, keybind_help_groups, keybind_help_text_char,
};
@@ -18,14 +13,13 @@ pub(crate) use keybindings::{
resolve_non_indexed_action, resolve_prefix_binding, KeybindAction, KeybindDispatch,
KeybindMatch,
};
-pub(crate) use lease::{InputLeaseKey, InputLeaseTable, RepeatPlan};
+pub(crate) use lease::{InputLease, InputLeaseKey, InputLeaseTable, RepeatPlan};
#[cfg(not(windows))]
pub use model::ime_compatible_keyboard_enhancement_flags;
-#[cfg(any(unix, test))]
-pub use model::MouseProtocolMode;
pub use model::WindowsKeyRecord;
pub use model::{
- host_modify_other_keys_mode, KeyIdentity, KeyboardProtocol, MouseProtocolEncoding, TerminalKey,
- TextCommit,
+ host_modify_other_keys_mode, KeyIdentity, KeyboardProtocol, TerminalKey, TextCommit,
};
+#[cfg(any(unix, test))]
+pub use model::{MouseProtocolEncoding, MouseProtocolMode};
pub use parse::parse_terminal_key_sequence;
diff --git a/src/input/model.rs b/src/input/model.rs
index 3828174ff..8ad591fe4 100644
--- a/src/input/model.rs
+++ b/src/input/model.rs
@@ -79,6 +79,10 @@ pub struct TerminalKey {
pub generated_text: Option<String>,
physical_identity_hint: bool,
windows_dead_key: bool,
+ /// The base-layout (physical) key a Kitty host named for this key. Client
+ /// side only: it pairs releases whose layout character differs from the
+ /// press (Ctrl let go first on a non-Latin layout).
+ base_layout_key: Option<char>,
source: KeySource,
}
@@ -93,10 +97,20 @@ impl TerminalKey {
generated_text: None,
physical_identity_hint: false,
windows_dead_key: false,
+ base_layout_key: None,
source: KeySource::Synthesized,
}
}
+ pub(crate) fn with_base_layout_key(mut self, key: Option<char>) -> Self {
+ self.base_layout_key = key;
+ self
+ }
+
+ pub(crate) fn base_layout_key(&self) -> Option<char> {
+ self.base_layout_key
+ }
+
pub fn with_kind(mut self, kind: crossterm::event::KeyEventKind) -> Self {
if kind == crossterm::event::KeyEventKind::Release {
self.repeat_count = 1;
@@ -173,11 +187,10 @@ impl TerminalKey {
self
}
- #[cfg(any(windows, test))]
pub(crate) fn vt_bytes(&self) -> Option<&[u8]> {
match &self.source {
KeySource::Vt { bytes } => Some(bytes),
- KeySource::Synthesized | KeySource::WindowsConsole { .. } => None,
+ _ => None,
}
}
@@ -358,6 +371,7 @@ impl MouseProtocolMode {
}
}
+#[cfg(any(unix, test))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MouseProtocolEncoding {
diff --git a/src/input/mouse.rs b/src/input/mouse.rs
index eeaf4decc..7579e709e 100644
--- a/src/input/mouse.rs
+++ b/src/input/mouse.rs
@@ -124,44 +124,6 @@ fn map_axis_within_cell(
.checked_add(1)
}
-#[cfg(any(unix, test))]
-pub(crate) fn parse_report(data: &[u8]) -> Option<(u32, u32)> {
- let body = data.strip_prefix(b"\x1b[<")?;
- let body = body
- .strip_suffix(b"M")
- .or_else(|| body.strip_suffix(b"m"))?;
- let mut fields = body.split(|byte| *byte == b';');
- parse_number(fields.next()?)?;
- let x = parse_number(fields.next()?)?;
- let y = parse_number(fields.next()?)?;
- fields.next().is_none().then_some((x, y))
-}
-
-#[cfg(any(unix, test))]
-pub(crate) fn report_at_cell(data: &[u8], column: u16, row: u16) -> Option<Vec<u8>> {
- let body = data.strip_prefix(b"\x1b[<")?;
- let suffix = if body.ends_with(b"M") { 'M' } else { 'm' };
- let body = body.strip_suffix(&[suffix as u8])?;
- let buttons = body.split(|byte| *byte == b';').next()?;
- Some(
- format!(
- "\x1b[<{};{};{}{}",
- std::str::from_utf8(buttons).ok()?,
- u32::from(column) + 1,
- u32::from(row) + 1,
- suffix
- )
- .into_bytes(),
- )
-}
-
-#[cfg(any(unix, test))]
-fn parse_number(value: &[u8]) -> Option<u32> {
- (!value.is_empty() && value.iter().all(u8::is_ascii_digit))
- .then(|| std::str::from_utf8(value).ok()?.parse().ok())
- .flatten()
-}
-
fn boundary(index: u16, count: u16, extent: u32) -> Option<u32> {
(count > 0 && index <= count && extent > 0)
.then(|| (u64::from(index) * u64::from(extent) / u64::from(count)) as u32)
@@ -189,19 +151,6 @@ fn scale(pixel: u32, source: u32, target: u32) -> u32 {
mod tests {
use super::*;
- #[test]
- fn parser_accepts_only_complete_sgr_mouse_reports() {
- for (input, expected) in [
- (b"\x1b[<35;321;241M".as_slice(), Some((321, 241))),
- (b"\x1b[<0;1;2m".as_slice(), Some((1, 2))),
- (b"key".as_slice(), None),
- (b"\x1b[<0;1;2Mkey".as_slice(), None),
- (b"\x1b[<0;1M".as_slice(), None),
- ] {
- assert_eq!(parse_report(input), expected);
- }
- }
-
#[test]
fn integer_cell_pitch_ignores_trailing_pixel_remainder() {
let geometry = HostGeometry::new(127, 31, 1_276, 626).unwrap();
diff --git a/src/input/parse.rs b/src/input/parse.rs
index 0213bf3fb..c75efa939 100644
--- a/src/input/parse.rs
+++ b/src/input/parse.rs
@@ -33,8 +33,28 @@ fn parse_kitty_key_sequence(data: &str) -> Option<TerminalKey> {
.next()
.filter(|field| !field.is_empty())
.and_then(|field| field.parse::<u32>().ok());
+ let base_layout_codepoint = key_fields
+ .next()
+ .filter(|field| !field.is_empty())
+ .and_then(|field| field.parse::<u32>().ok());
- let code = kitty_codepoint_to_keycode(codepoint)?;
+ let mut code = kitty_codepoint_to_keycode(codepoint)?;
+ // Ctrl chords on a non-Latin layout (Ctrl+\u{441} on Russian) are shortcuts
+ // for the physical key the host names in the base-layout field: Ctrl+C.
+ // Kitty sends ^C to a plain shell for them, and the Kitty spec tells apps
+ // to match shortcuts on that key.
+ let mut shifted_codepoint = shifted_codepoint;
+ if let (KeyCode::Char(ch), Some(base)) = (code, base_layout_codepoint.and_then(char::from_u32))
+ {
+ if key_modifiers_from_u8(modifier).contains(KeyModifiers::CONTROL)
+ && !ch.is_ascii()
+ && base.is_ascii_graphic()
+ {
+ code = KeyCode::Char(base);
+ // The shifted alternate belongs to the layout character.
+ shifted_codepoint = None;
+ }
+ }
let associated_text = match associated_text {
Some(value) => match parse_kitty_associated_text(value) {
Some(text) => Some(text),
@@ -54,7 +74,12 @@ fn parse_kitty_key_sequence(data: &str) -> Option<TerminalKey> {
modifiers |= KeyModifiers::SHIFT;
}
- let mut key = TerminalKey::new(code, modifiers).with_kind(kind);
+ let base_layout_key = base_layout_codepoint
+ .and_then(char::from_u32)
+ .filter(char::is_ascii_graphic);
+ let mut key = TerminalKey::new(code, modifiers)
+ .with_kind(kind)
+ .with_base_layout_key(base_layout_key);
if let Some(shifted_codepoint) = shifted_codepoint {
key = key.with_shifted_codepoint(shifted_codepoint);
}
@@ -197,10 +222,18 @@ fn parse_legacy_special_sequence(data: &str) -> Option<TerminalKey> {
"\x1bOj" => Some(TerminalKey::new(KeyCode::Char('*'), KeyModifiers::empty())),
"\x1bOo" => Some(TerminalKey::new(KeyCode::Char('/'), KeyModifiers::empty())),
"\x1bOM" => Some(TerminalKey::new(KeyCode::Enter, KeyModifiers::empty())),
- "\x1bOP" | "\x1b[11~" => Some(TerminalKey::new(KeyCode::F(1), KeyModifiers::empty())),
- "\x1bOQ" | "\x1b[12~" => Some(TerminalKey::new(KeyCode::F(2), KeyModifiers::empty())),
+ // Kitty keyboard hosts send unmodified F1, F2 and F4 as bare `CSI P/Q/S`
+ // (#4403). F3 stays `CSI 13~` there: a bare `CSI R` is a cursor report.
+ "\x1bOP" | "\x1b[11~" | "\x1b[P" => {
+ Some(TerminalKey::new(KeyCode::F(1), KeyModifiers::empty()))
+ }
+ "\x1bOQ" | "\x1b[12~" | "\x1b[Q" => {
+ Some(TerminalKey::new(KeyCode::F(2), KeyModifiers::empty()))
+ }
"\x1bOR" | "\x1b[13~" => Some(TerminalKey::new(KeyCode::F(3), KeyModifiers::empty())),
- "\x1bOS" | "\x1b[14~" => Some(TerminalKey::new(KeyCode::F(4), KeyModifiers::empty())),
+ "\x1bOS" | "\x1b[14~" | "\x1b[S" => {
+ Some(TerminalKey::new(KeyCode::F(4), KeyModifiers::empty()))
+ }
"\x1b[15~" => Some(TerminalKey::new(KeyCode::F(5), KeyModifiers::empty())),
"\x1b[17~" => Some(TerminalKey::new(KeyCode::F(6), KeyModifiers::empty())),
"\x1b[18~" => Some(TerminalKey::new(KeyCode::F(7), KeyModifiers::empty())),
@@ -405,7 +438,6 @@ mod tests {
use crossterm::event::{KeyCode, KeyModifiers, ModifierKeyCode};
use super::*;
- use crate::input::{encode_terminal_key, KeyboardProtocol};
fn assert_terminal_key_eq(
actual: TerminalKey,
@@ -586,7 +618,7 @@ mod tests {
crossterm::event::KeyEventKind::Press,
None,
);
- assert_eq!(encode_terminal_key(key, KeyboardProtocol::Legacy), b"\x1bA");
+ assert_eq!(crate::pane::test_encode_key_for_app(b"", key), b"\x1bA");
}
#[test]
@@ -600,10 +632,7 @@ mod tests {
crossterm::event::KeyEventKind::Press,
None,
);
- assert_eq!(
- encode_terminal_key(key, KeyboardProtocol::Legacy),
- b"\x1b\x06"
- );
+ assert_eq!(crate::pane::test_encode_key_for_app(b"", key), b"\x1b\x06");
}
#[test]
@@ -749,6 +778,43 @@ mod tests {
assert_eq!(key.generated_text.as_deref(), Some("你好"));
}
+ #[test]
+ fn parse_ctrl_chords_on_non_latin_layouts_as_their_base_layout_key() {
+ // Lab capture, kitty on a Russian layout: Ctrl+\u{441} is the C key.
+ for (sequence, code, modifiers) in [
+ (
+ "\x1b[1089::99;5u",
+ KeyCode::Char('c'),
+ KeyModifiers::CONTROL,
+ ),
+ (
+ "\x1b[1089:1057:99;6u",
+ KeyCode::Char('c'),
+ KeyModifiers::CONTROL | KeyModifiers::SHIFT,
+ ),
+ (
+ "\x1b[1089::99;5:3u",
+ KeyCode::Char('c'),
+ KeyModifiers::CONTROL,
+ ),
+ // Without Ctrl it is text on that layout; without a base key
+ // nothing is known about the physical key.
+ (
+ "\x1b[1089::99u",
+ KeyCode::Char('\u{441}'),
+ KeyModifiers::empty(),
+ ),
+ (
+ "\x1b[1089;5u",
+ KeyCode::Char('\u{441}'),
+ KeyModifiers::CONTROL,
+ ),
+ ] {
+ let key = parse_terminal_key_sequence(sequence).expect(sequence);
+ assert_eq!((key.code, key.modifiers), (code, modifiers), "{sequence:?}");
+ }
+ }
+
#[test]
fn parse_wezterm_control_associated_text_keeps_report_all_key_events() {
for (sequence, expected_code, expected_kind) in [
@@ -954,7 +1020,7 @@ mod tests {
#[test]
fn legacy_lf_roundtrips_as_lf() {
let key = parse_terminal_key_sequence("\n").unwrap();
- assert_eq!(encode_terminal_key(key, KeyboardProtocol::Legacy), b"\n");
+ assert_eq!(crate::pane::test_encode_key_for_app(b"", key), b"\n");
}
#[test]
diff --git a/src/pane.rs b/src/pane.rs
index a48f77323..5b4d6b53a 100644
--- a/src/pane.rs
+++ b/src/pane.rs
@@ -42,6 +42,8 @@ use self::agent_detection::{
AGENT_PENDING_IDLE_RECHECK, AGENT_STARTUP_GRACE_WINDOW,
};
use self::background_agent::{AgentJobStatus, AgentJobTracker};
+#[cfg(test)]
+pub(crate) use self::terminal::test_encode_key_for_app;
#[cfg(unix)]
pub use self::terminal::InputState;
use self::terminal::{GhosttyPaneTerminal, PaneTerminal};
@@ -3647,8 +3649,7 @@ impl PaneRuntime {
}
pub fn encode_terminal_key(&self, key: crate::input::TerminalKey) -> Vec<u8> {
- self.terminal
- .encode_terminal_key(key, self.keyboard_protocol())
+ self.terminal.encode_terminal_key(key)
}
pub fn try_send_bytes(&self, bytes: Bytes) -> Result<(), mpsc::error::TrySendError<Bytes>> {
diff --git a/src/pane/input.rs b/src/pane/input.rs
index 10900c948..13cc67701 100644
--- a/src/pane/input.rs
+++ b/src/pane/input.rs
@@ -1,6 +1,23 @@
+/// Build the key event the Ghostty app would build from an OS key event, so
+/// libghostty can encode it for the pane's current keyboard modes: physical
+/// key, modifiers, the layout text, the unshifted codepoint, and Shift marked
+/// consumed when it produced the text. `legacy_pane` is true when the pane
+/// negotiated no keyboard protocol.
+///
+/// Hyper and Meta have no Ghostty equivalent, so those chords are not
+/// forwarded rather than typed as their bare key.
pub(super) fn ghostty_key_event_from_terminal_key(
key: &crate::input::TerminalKey,
+ legacy_pane: bool,
) -> Option<crate::ghostty::KeyEvent> {
+ use crossterm::event::{KeyCode, KeyModifiers};
+
+ if key
+ .modifiers
+ .intersects(KeyModifiers::HYPER | KeyModifiers::META)
+ {
+ return None;
+ }
let mut event = crate::ghostty::KeyEvent::new().ok()?;
event.set_action(match key.kind {
crossterm::event::KeyEventKind::Press => {
@@ -14,31 +31,167 @@ pub(super) fn ghostty_key_event_from_terminal_key(
}
});
let mut mods = ghostty_mods_from_key_modifiers(key.modifiers);
- if matches!(key.code, crossterm::event::KeyCode::BackTab) {
- // Ghostty represents backtab as Tab with Shift rather than a distinct key.
- mods |= crate::ghostty::MOD_SHIFT;
+ match key.code {
+ KeyCode::Char(c) => {
+ // An uppercase letter's key is its lowercase letter on every layout.
+ // Nothing else is inferred: Kitty reports already name the unshifted
+ // key (`+` on a German layout stays `+`), and legacy input does not
+ // say which key produced punctuation.
+ let base = unshifted_letter(c);
+ if base != c {
+ mods |= crate::ghostty::MOD_SHIFT;
+ }
+ event.set_key(
+ ghostty_key_from_char(base)
+ .unwrap_or(crate::ghostty::ffi::GhosttyKey_GHOSTTY_KEY_UNIDENTIFIED),
+ );
+ event.set_unshifted_codepoint(base as u32);
+ let shifted = mods & crate::ghostty::MOD_SHIFT != 0;
+ if let Some(text) = key_text(key, base, shifted) {
+ // Text the host reported with Shift held already includes Shift
+ // (e.g. Shift+7 = "/" on a German layout, where `base` cannot
+ // be recovered from the character alone).
+ let reported_shifted_text = key.generated_text.is_some() && text != " ";
+ // A non-letter given with Shift and no reported shifted character
+ // is the produced character itself ("shift+?" is "?"). Kitty
+ // hosts report shifted alternates, so a changed character shows
+ // up there.
+ let given_shifted_char =
+ key.shifted_codepoint.is_none() && !base.is_alphabetic() && text != " ";
+ if shifted
+ && (!text.starts_with(base) || reported_shifted_text || given_shifted_char)
+ {
+ event.set_consumed_mods(crate::ghostty::MOD_SHIFT);
+ }
+ // Legacy Alt prefixes the produced text, but libghostty on macOS
+ // prefixes the unshifted codepoint for non-ASCII text (it
+ // assumes Option translated it). Herdr already decoded Alt, so
+ // the text is the key's real output: Alt+Shift+ö is ESC Ö.
+ if legacy_pane
+ && key.modifiers.contains(KeyModifiers::ALT)
+ && !key.modifiers.contains(KeyModifiers::CONTROL)
+ {
+ if let Some(produced) = single_char(&text).filter(|c| !c.is_ascii()) {
+ event.set_unshifted_codepoint(produced as u32);
+ }
+ }
+ event.set_utf8(&text);
+ }
+ }
+ KeyCode::BackTab => {
+ // Ghostty represents backtab as Tab with Shift rather than a distinct key.
+ mods |= crate::ghostty::MOD_SHIFT;
+ event.set_key(crate::ghostty::ffi::GhosttyKey_GHOSTTY_KEY_TAB);
+ }
+ code => event.set_key(ghostty_key_from_key_code(code)?),
}
event.set_mods(mods);
- event.set_key(ghostty_key_from_crossterm_key_code(
- key.code,
- key.shifted_codepoint,
- )?);
+ event.set_composing(key.is_windows_dead_key());
- if let Some(text) = ghostty_key_text(key) {
- event.set_utf8(&text);
- } else {
- event.set_utf8("");
+ Some(event)
+}
+
+/// Configure `encoder` for a pane's live terminal modes. Herdr has already
+/// decoded Alt from the host, so macOS Option must keep its Alt meaning (ESC
+/// prefix) instead of being treated as a text modifier.
+pub(super) fn configure_key_encoder(
+ encoder: &mut crate::ghostty::KeyEncoder,
+ terminal: &crate::ghostty::Terminal,
+) {
+ encoder.set_from_terminal(terminal);
+ encoder.set_macos_option_as_alt(true);
+}
+
+/// Exception table for panes that negotiated no keyboard protocol. Ghostty sends
+/// these chords as escape sequences that plain shells do not understand; keep
+/// the classic key instead. libghostty still encodes the result (so Alt keeps
+/// its ESC prefix).
+pub(super) fn legacy_shell_key(key: crate::input::TerminalKey) -> crate::input::TerminalKey {
+ use crossterm::event::{KeyCode, KeyModifiers};
+
+ let alt = key.modifiers & KeyModifiers::ALT;
+ let chord = key.modifiers - KeyModifiers::ALT;
+ let classic = match (key.code, chord) {
+ (KeyCode::Enter, chord) if !chord.is_empty() => KeyCode::Enter,
+ (KeyCode::Char('m'), KeyModifiers::CONTROL) => KeyCode::Enter,
+ (KeyCode::Char('i'), KeyModifiers::CONTROL) | (KeyCode::Tab, KeyModifiers::CONTROL) => {
+ KeyCode::Tab
+ }
+ (KeyCode::Char('['), KeyModifiers::CONTROL) => KeyCode::Esc,
+ // Ghostty reports Ctrl+Shift+letter as CSI u; every terminal sends the
+ // plain control byte, which is all a shell can read.
+ // WezTerm names it Ctrl plus an uppercase letter, without Shift.
+ (KeyCode::Char(c), chord)
+ if chord - KeyModifiers::SHIFT == KeyModifiers::CONTROL
+ && c.is_ascii_alphabetic()
+ && (chord.contains(KeyModifiers::SHIFT) || c.is_ascii_uppercase()) =>
+ {
+ // Ctrl+I and Ctrl+M then follow the rows above (Tab, Enter).
+ return legacy_shell_key(
+ crate::input::TerminalKey::new(
+ KeyCode::Char(c.to_ascii_lowercase()),
+ KeyModifiers::CONTROL | alt,
+ )
+ .with_kind(key.kind)
+ .with_repeat_count(key.repeat_count),
+ );
+ }
+ _ => return key,
+ };
+ crate::input::TerminalKey::new(classic, alt)
+ .with_kind(key.kind)
+ .with_repeat_count(key.repeat_count)
+}
+
+/// Second exception for panes that negotiated nothing: legacy encoding has no
+/// Super, so these chords are not forwarded. Typing the bare key turns Cmd+C
+/// into "c" (#3710), and a Kitty report prints as garbage in plain shells
+/// (#4356). Ghostty on macOS sends nothing for them either.
+pub(super) fn legacy_super_chord(key: &crate::input::TerminalKey) -> bool {
+ key.modifiers
+ .contains(crossterm::event::KeyModifiers::SUPER)
+}
+
+fn single_char(text: &str) -> Option<char> {
+ let mut chars = text.chars();
+ match (chars.next(), chars.next()) {
+ (Some(only), None) => Some(only),
+ _ => None,
}
+}
- if let Some(codepoint) = ghostty_unshifted_codepoint(key) {
- event.set_unshifted_codepoint(codepoint);
+/// Text the key produced on the user's layout, before Ctrl/Alt transformations.
+fn key_text(key: &crate::input::TerminalKey, base: char, shifted: bool) -> Option<String> {
+ if let Some(text) = key
+ .generated_text
+ .as_ref()
+ .filter(|text| !text.is_empty() && !text.chars().any(char::is_control))
+ {
+ return Some(text.clone());
}
+ // Without a reported shifted character, only a letter's Shift is known.
+ let produced = match key.shifted_codepoint.and_then(char::from_u32) {
+ Some(shifted_char) if shifted => shifted_char,
+ _ if shifted => shifted_letter(base),
+ _ => base,
+ };
+ (!produced.is_control()).then(|| produced.to_string())
+}
- Some(event)
+fn shifted_letter(c: char) -> char {
+ let mut upper = c.to_uppercase();
+ match (upper.next(), upper.next()) {
+ (Some(upper), None) if c.is_lowercase() => upper,
+ _ => c,
+ }
}
-pub(super) fn ghostty_prefers_herdr_text_encoding(key: &crate::input::TerminalKey) -> bool {
- matches!(key.code, crossterm::event::KeyCode::Char(_))
+fn unshifted_letter(c: char) -> char {
+ let mut lower = c.to_lowercase();
+ match (lower.next(), lower.next()) {
+ (Some(lower), None) if c.is_uppercase() => lower,
+ _ => c,
+ }
}
pub(super) fn ghostty_mods_from_key_modifiers(modifiers: crossterm::event::KeyModifiers) -> u16 {
@@ -196,31 +349,14 @@ pub(super) fn ghostty_mouse_event_from_wheel_kind(
Some(event)
}
-fn ghostty_key_text(key: &crate::input::TerminalKey) -> Option<String> {
- match key.code {
- crossterm::event::KeyCode::Char(c) => Some(
- key.shifted_codepoint
- .and_then(char::from_u32)
- .unwrap_or(c)
- .to_string(),
- ),
- _ => None,
- }
-}
-
-fn ghostty_unshifted_codepoint(key: &crate::input::TerminalKey) -> Option<u32> {
- match key.code {
- crossterm::event::KeyCode::Char(c) => Some(c as u32),
- _ => None,
- }
-}
-
-fn ghostty_key_from_crossterm_key_code(
+/// Physical key for a non-character key code. Keys libghostty has no name for
+/// (some media keys, Hyper/Meta, ISO level shifts) return None; the Ghostty app
+/// cannot send them either.
+fn ghostty_key_from_key_code(
code: crossterm::event::KeyCode,
- shifted_codepoint: Option<u32>,
) -> Option<crate::ghostty::ffi::GhosttyKey> {
use crate::ghostty::ffi;
- use crossterm::event::KeyCode;
+ use crossterm::event::{KeyCode, MediaKeyCode, ModifierKeyCode};
match code {
KeyCode::Backspace => Some(ffi::GhosttyKey_GHOSTTY_KEY_BACKSPACE),
@@ -250,26 +386,75 @@ fn ghostty_key_from_crossterm_key_code(
10 => ffi::GhosttyKey_GHOSTTY_KEY_F10,
11 => ffi::GhosttyKey_GHOSTTY_KEY_F11,
12 => ffi::GhosttyKey_GHOSTTY_KEY_F12,
+ 13 => ffi::GhosttyKey_GHOSTTY_KEY_F13,
+ 14 => ffi::GhosttyKey_GHOSTTY_KEY_F14,
+ 15 => ffi::GhosttyKey_GHOSTTY_KEY_F15,
+ 16 => ffi::GhosttyKey_GHOSTTY_KEY_F16,
+ 17 => ffi::GhosttyKey_GHOSTTY_KEY_F17,
+ 18 => ffi::GhosttyKey_GHOSTTY_KEY_F18,
+ 19 => ffi::GhosttyKey_GHOSTTY_KEY_F19,
+ 20 => ffi::GhosttyKey_GHOSTTY_KEY_F20,
+ 21 => ffi::GhosttyKey_GHOSTTY_KEY_F21,
+ 22 => ffi::GhosttyKey_GHOSTTY_KEY_F22,
+ 23 => ffi::GhosttyKey_GHOSTTY_KEY_F23,
+ 24 => ffi::GhosttyKey_GHOSTTY_KEY_F24,
+ 25 => ffi::GhosttyKey_GHOSTTY_KEY_F25,
_ => return None,
}),
- KeyCode::Char(c) => ghostty_key_from_char(c, shifted_codepoint),
+ KeyCode::CapsLock => Some(ffi::GhosttyKey_GHOSTTY_KEY_CAPS_LOCK),
+ KeyCode::ScrollLock => Some(ffi::GhosttyKey_GHOSTTY_KEY_SCROLL_LOCK),
+ KeyCode::NumLock => Some(ffi::GhosttyKey_GHOSTTY_KEY_NUM_LOCK),
+ KeyCode::PrintScreen => Some(ffi::GhosttyKey_GHOSTTY_KEY_PRINT_SCREEN),
+ KeyCode::Pause => Some(ffi::GhosttyKey_GHOSTTY_KEY_PAUSE),
+ KeyCode::Menu => Some(ffi::GhosttyKey_GHOSTTY_KEY_CONTEXT_MENU),
+ KeyCode::KeypadBegin => Some(ffi::GhosttyKey_GHOSTTY_KEY_NUMPAD_BEGIN),
+ KeyCode::Media(MediaKeyCode::PlayPause) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_MEDIA_PLAY_PAUSE)
+ }
+ KeyCode::Media(MediaKeyCode::Stop) => Some(ffi::GhosttyKey_GHOSTTY_KEY_MEDIA_STOP),
+ KeyCode::Media(MediaKeyCode::TrackNext) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_MEDIA_TRACK_NEXT)
+ }
+ KeyCode::Media(MediaKeyCode::TrackPrevious) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS)
+ }
+ KeyCode::Media(MediaKeyCode::LowerVolume) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_AUDIO_VOLUME_DOWN)
+ }
+ KeyCode::Media(MediaKeyCode::RaiseVolume) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_AUDIO_VOLUME_UP)
+ }
+ KeyCode::Media(MediaKeyCode::MuteVolume) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_AUDIO_VOLUME_MUTE)
+ }
+ KeyCode::Modifier(ModifierKeyCode::LeftShift) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_SHIFT_LEFT)
+ }
+ KeyCode::Modifier(ModifierKeyCode::RightShift) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_SHIFT_RIGHT)
+ }
+ KeyCode::Modifier(ModifierKeyCode::LeftControl) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_CONTROL_LEFT)
+ }
+ KeyCode::Modifier(ModifierKeyCode::RightControl) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_CONTROL_RIGHT)
+ }
+ KeyCode::Modifier(ModifierKeyCode::LeftAlt) => Some(ffi::GhosttyKey_GHOSTTY_KEY_ALT_LEFT),
+ KeyCode::Modifier(ModifierKeyCode::RightAlt) => Some(ffi::GhosttyKey_GHOSTTY_KEY_ALT_RIGHT),
+ KeyCode::Modifier(ModifierKeyCode::LeftSuper) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_META_LEFT)
+ }
+ KeyCode::Modifier(ModifierKeyCode::RightSuper) => {
+ Some(ffi::GhosttyKey_GHOSTTY_KEY_META_RIGHT)
+ }
_ => None,
}
}
-fn ghostty_key_from_char(
- c: char,
- shifted_codepoint: Option<u32>,
-) -> Option<crate::ghostty::ffi::GhosttyKey> {
+fn ghostty_key_from_char(base: char) -> Option<crate::ghostty::ffi::GhosttyKey> {
use crate::ghostty::ffi;
- let base = if let Some(shifted) = shifted_codepoint.and_then(char::from_u32) {
- ghostty_unshifted_ascii_pair(shifted).unwrap_or(c)
- } else {
- c
- };
-
- match base.to_ascii_lowercase() {
+ match base {
'a' => Some(ffi::GhosttyKey_GHOSTTY_KEY_A),
'b' => Some(ffi::GhosttyKey_GHOSTTY_KEY_B),
'c' => Some(ffi::GhosttyKey_GHOSTTY_KEY_C),
@@ -321,30 +506,3 @@ fn ghostty_key_from_char(
_ => None,
}
}
-
-fn ghostty_unshifted_ascii_pair(c: char) -> Option<char> {
- Some(match c {
- '!' => '1',
- '@' => '2',
- '#' => '3',
- '$' => '4',
- '%' => '5',
- '^' => '6',
- '&' => '7',
- '*' => '8',
- '(' => '9',
- ')' => '0',
- '_' => '-',
- '+' => '=',
- '{' => '[',
- '}' => ']',
- '|' => '\\',
- ':' => ';',
- '"' => '\'',
- '<' => ',',
- '>' => '.',
- '?' => '/',
- '~' => '`',
- _ => return None,
- })
-}
diff --git a/src/pane/kitty_keyboard.rs b/src/pane/kitty_keyboard.rs
index bc8876e6e..4c6667e32 100644
--- a/src/pane/kitty_keyboard.rs
+++ b/src/pane/kitty_keyboard.rs
@@ -1,3 +1,7 @@
+/// Handoff-only record of the keyboard modes a pane's app requested, so an
+/// update handoff can replay the full Kitty keyboard stack into the new server.
+/// It is never consulted for live input: libghostty owns keyboard state and
+/// encoding. Remove once handoff restores panes from libghostty snapshots.
#[derive(Debug, Clone, Default)]
pub(crate) struct KittyKeyboardTracker {
pending: Vec<u8>,
@@ -67,15 +71,11 @@ impl KittyKeyboardTracker {
}
}
+ #[cfg(test)]
pub(crate) fn modify_other_keys_level(&self) -> u8 {
self.modify_other_keys_level
}
- #[cfg(windows)]
- pub(crate) fn modify_other_keys_enabled(&self) -> bool {
- self.modify_other_keys_level > 0
- }
-
fn observe_modify_other_keys(&mut self, params: &[u8]) {
let Some(params) = params.strip_prefix(b">") else {
return;
@@ -173,14 +173,10 @@ mod tests {
assert_eq!(tracker.flags, 1);
assert_eq!(tracker.stack, vec![0]);
assert_eq!(tracker.modify_other_keys_level(), 1);
- #[cfg(windows)]
- {
- assert!(tracker.modify_other_keys_enabled());
- tracker.observe(b"\x1b[>1m");
- assert!(tracker.modify_other_keys_enabled());
- tracker.observe(b"\x1b[>04n");
- assert!(!tracker.modify_other_keys_enabled());
- }
+ tracker.observe(b"\x1b[>1m");
+ assert_eq!(tracker.modify_other_keys_level(), 1);
+ tracker.observe(b"\x1b[>04n");
+ assert_eq!(tracker.modify_other_keys_level(), 0);
}
#[test]
diff --git a/src/pane/terminal.rs b/src/pane/terminal.rs
index d43aca1a8..c5d6d85f1 100644
--- a/src/pane/terminal.rs
+++ b/src/pane/terminal.rs
@@ -9,7 +9,7 @@ use ratatui::{layout::Rect, Frame};
#[cfg(any(unix, test))]
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
-use tracing::{debug, error};
+use tracing::{debug, error, warn};
use unicode_width::UnicodeWidthStr;
use crate::layout::PaneId;
@@ -25,10 +25,10 @@ use super::cursor::CURSOR_POSITION_SETTLE;
use super::cursor::{CursorPositionSettleState, DecscusrTracker};
use super::{
input::{
- ghostty_key_event_from_terminal_key, ghostty_mouse_encoder_for_terminal,
- ghostty_mouse_event_from_button_kind, ghostty_mouse_event_from_motion_kind,
- ghostty_mouse_event_from_wheel_kind, ghostty_mouse_position_for_terminal,
- ghostty_prefers_herdr_text_encoding,
+ configure_key_encoder, ghostty_key_event_from_terminal_key,
+ ghostty_mouse_encoder_for_terminal, ghostty_mouse_event_from_button_kind,
+ ghostty_mouse_event_from_motion_kind, ghostty_mouse_event_from_wheel_kind,
+ ghostty_mouse_position_for_terminal, legacy_shell_key, legacy_super_chord,
},
kitty_keyboard::KittyKeyboardTracker,
osc::{
@@ -636,12 +636,8 @@ impl PaneTerminal {
.filter(|ansi| !ansi.is_empty())
}
- pub fn encode_terminal_key(
- &self,
- key: crate::input::TerminalKey,
- protocol: crate::input::KeyboardProtocol,
- ) -> Vec<u8> {
- self.ghostty.encode_terminal_key(key, protocol)
+ pub fn encode_terminal_key(&self, key: crate::input::TerminalKey) -> Vec<u8> {
+ self.ghostty.encode_terminal_key(key)
}
pub(crate) fn encode_mouse_button(
@@ -1172,7 +1168,7 @@ impl GhosttyPaneTerminal {
let initial_default_background = initial_colors.map(|colors| colors.background);
let mut key_encoder =
crate::ghostty::KeyEncoder::new().map_err(|e| std::io::Error::other(e.to_string()))?;
- key_encoder.set_from_terminal(&terminal);
+ configure_key_encoder(&mut key_encoder, &terminal);
Ok(Self {
#[cfg(test)]
scroll_metrics_reads: std::sync::atomic::AtomicUsize::new(0),
@@ -1432,7 +1428,7 @@ impl GhosttyPaneTerminal {
debug!(pane = pane_id.raw(), "processed kitty graphics sequence");
}
if let Ok(mut key_encoder) = self.key_encoder.lock() {
- key_encoder.set_from_terminal(&core.terminal);
+ configure_key_encoder(&mut key_encoder, &core.terminal);
}
let synchronized_output = core
.terminal
@@ -1582,7 +1578,7 @@ impl GhosttyPaneTerminal {
#[cfg(windows)]
windows_recent_fallback::update(&mut core);
if let Ok(mut key_encoder) = self.key_encoder.lock() {
- key_encoder.set_from_terminal(&core.terminal);
+ configure_key_encoder(&mut key_encoder, &core.terminal);
}
}
@@ -1646,7 +1642,7 @@ impl GhosttyPaneTerminal {
}
if let Ok(mut key_encoder) = self.key_encoder.lock() {
- key_encoder.set_from_terminal(&core.terminal);
+ configure_key_encoder(&mut key_encoder, &core.terminal);
}
}
@@ -1669,7 +1665,7 @@ impl GhosttyPaneTerminal {
core.kitty_keyboard.observe(ansi.as_bytes());
core.terminal.write(ansi.as_bytes());
if let Ok(mut key_encoder) = self.key_encoder.lock() {
- key_encoder.set_from_terminal(&core.terminal);
+ configure_key_encoder(&mut key_encoder, &core.terminal);
}
}
@@ -1854,10 +1850,16 @@ impl GhosttyPaneTerminal {
.is_ok_and(|core| core.terminal.mouse_tracking_enabled().unwrap_or(false))
}
+ /// libghostty tracks only level 2; like Ghostty, level 1 behaves as if the
+ /// app negotiated nothing.
pub fn modify_other_keys_level(&self) -> u8 {
- self.core
- .lock()
- .map_or(0, |core| core.kitty_keyboard.modify_other_keys_level())
+ self.core.lock().map_or(0, |core| {
+ if core.terminal.modify_other_keys_enabled().unwrap_or(false) {
+ 2
+ } else {
+ 0
+ }
+ })
}
pub fn sgr_pixel_mouse_enabled(&self) -> bool {
@@ -2020,90 +2022,59 @@ impl GhosttyPaneTerminal {
.unwrap_or((true, 0))
}
- pub fn encode_terminal_key(
- &self,
- key: crate::input::TerminalKey,
- protocol: crate::input::KeyboardProtocol,
- ) -> Vec<u8> {
+ /// libghostty encodes every key for the pane's live keyboard modes. The only
+ /// Herdr policy is the legacy shell table for panes that negotiated nothing.
+ ///
+ /// The terminal lock is held until the key and its grouped repeats are
+ /// encoded, so a mode change from the PTY reader cannot split the decision
+ /// (legacy table) from the encoder's configuration. Lock order matches
+ /// output processing: terminal core, then key encoder.
+ pub fn encode_terminal_key(&self, key: crate::input::TerminalKey) -> Vec<u8> {
+ let Ok(core) = self.core.lock() else {
+ return Vec::new();
+ };
+ let negotiated_nothing = keyboard_negotiated_nothing(&core.terminal);
+ // Before the Windows record fallback too: a remote client can report
+ // Super, and a record would deliver the bare key (#3710).
+ if negotiated_nothing && legacy_super_chord(&key) {
+ debug!(code = ?key.code, "super chord in a pane without keyboard protocol; not forwarded");
+ return Vec::new();
+ }
#[cfg(windows)]
- if self.core.lock().is_ok_and(|core| {
- core.terminal
- .kitty_keyboard_flags()
- .is_ok_and(|flags| flags == 0)
- && !core.kitty_keyboard.modify_other_keys_enabled()
- && core
- .terminal
- .modify_other_keys_enabled()
- .is_ok_and(|enabled| !enabled)
- }) {
+ if negotiated_nothing {
if let Some(bytes) = crate::platform::encode_windows_conpty_fallback(&key) {
return bytes;
}
}
+ let Ok(mut encoder) = self.key_encoder.lock() else {
+ return Vec::new();
+ };
let repeat_count = key.repeat_count;
let first = key.with_repeat_count(1);
- let mut bytes = self.encode_terminal_key_once(first.clone(), protocol);
+ let mut bytes = encode_key_with(&mut encoder, negotiated_nothing, first.clone());
if repeat_count > 1 && first.kind != crossterm::event::KeyEventKind::Release {
let repeated = first.with_kind(crossterm::event::KeyEventKind::Repeat);
- let repeated_bytes = self.encode_terminal_key_once(repeated, protocol);
+ let repeated_bytes = encode_key_with(&mut encoder, negotiated_nothing, repeated);
for _ in 1..repeat_count {
bytes.extend_from_slice(&repeated_bytes);
}
}
+ drop(encoder);
+ drop(core);
bytes
}
- fn encode_terminal_key_once(
- &self,
- key: crate::input::TerminalKey,
- protocol: crate::input::KeyboardProtocol,
- ) -> Vec<u8> {
- // Ghostty emits extended Enter sequences even without negotiation.
- // Ordinary shells need legacy input unless the child enabled an extension.
- if key.code == crossterm::event::KeyCode::Enter
- && !key.modifiers.is_empty()
- && self.core.lock().is_ok_and(|core| {
- core.terminal
- .kitty_keyboard_flags()
- .is_ok_and(|flags| flags == 0)
- && core.kitty_keyboard.modify_other_keys_level() == 0
- && core
- .terminal
- .modify_other_keys_enabled()
- .is_ok_and(|enabled| !enabled)
- })
- {
- return crate::input::encode_terminal_key(key, crate::input::KeyboardProtocol::Legacy);
- }
-
- if matches!(protocol, crate::input::KeyboardProtocol::Legacy)
- && key.code == crossterm::event::KeyCode::Tab
- && key.modifiers == crossterm::event::KeyModifiers::CONTROL
- {
- return crate::input::encode_terminal_key(key, protocol);
- }
-
- if ghostty_prefers_herdr_text_encoding(&key) {
- return crate::input::encode_terminal_key(key, protocol);
- }
-
- let Some(event) = ghostty_key_event_from_terminal_key(&key) else {
- return crate::input::encode_terminal_key(key, protocol);
+ #[cfg(test)]
+ fn encode_terminal_key_once(&self, key: crate::input::TerminalKey) -> Vec<u8> {
+ let Ok(core) = self.core.lock() else {
+ return Vec::new();
};
-
+ let negotiated_nothing = keyboard_negotiated_nothing(&core.terminal);
let Ok(mut encoder) = self.key_encoder.lock() else {
- return crate::input::encode_terminal_key(key, protocol);
+ return Vec::new();
};
- match encoder.encode(&event) {
- Ok(bytes)
- if !bytes.is_empty()
- && encoded_key_preserves_event_kind(&bytes, &key, protocol) =>
- {
- bytes
- }
- Ok(_) | Err(_) => crate::input::encode_terminal_key(key, protocol),
- }
+ encode_key_with(&mut encoder, negotiated_nothing, key)
}
pub(crate) fn encode_mouse_button(
@@ -2513,21 +2484,42 @@ impl GhosttyPaneTerminal {
}
}
-fn encoded_key_preserves_event_kind(
- bytes: &[u8],
- key: &crate::input::TerminalKey,
- protocol: crate::input::KeyboardProtocol,
-) -> bool {
- if !protocol.reports_event_types() || key.kind == crossterm::event::KeyEventKind::Press {
- return true;
- }
+/// Encode one key with an encoder configured for the same mode snapshot as
+/// `negotiated_nothing`.
+fn encode_key_with(
+ encoder: &mut crate::ghostty::KeyEncoder,
+ negotiated_nothing: bool,
+ key: crate::input::TerminalKey,
+) -> Vec<u8> {
+ // Before the shell table: Super+Enter must not become a plain Enter.
+ if negotiated_nothing && legacy_super_chord(&key) {
+ debug!(code = ?key.code, "super chord in a pane without keyboard protocol; not forwarded");
+ return Vec::new();
+ }
+ let key = if negotiated_nothing {
+ legacy_shell_key(key)
+ } else {
+ key
+ };
+ let Some(event) = ghostty_key_event_from_terminal_key(&key, negotiated_nothing) else {
+ debug!(code = ?key.code, modifiers = ?key.modifiers, "key has no libghostty equivalent; not forwarded");
+ return Vec::new();
+ };
+ encoder.encode(&event).unwrap_or_else(|err| {
+ warn!(?err, code = ?key.code, "libghostty key encoding failed");
+ Vec::new()
+ })
+}
- std::str::from_utf8(bytes)
- .ok()
- .and_then(crate::input::parse_terminal_key_sequence)
- .is_some_and(|parsed| {
- parsed.code == key.code && parsed.modifiers == key.modifiers && parsed.kind == key.kind
- })
+/// True when the pane's app asked for no enhanced keyboard protocol (no Kitty
+/// flags, no modifyOtherKeys 2), read from libghostty's live state.
+fn keyboard_negotiated_nothing(terminal: &crate::ghostty::Terminal) -> bool {
+ terminal
+ .kitty_keyboard_flags()
+ .is_ok_and(|flags| flags == 0)
+ && terminal
+ .modify_other_keys_enabled()
+ .is_ok_and(|enabled| !enabled)
}
fn effective_cursor_state(
@@ -3631,6 +3623,21 @@ fn should_probe_host_terminal_theme_restore(core: &GhosttyPaneCore) -> bool {
.unwrap_or(false)
}
+/// Encode one `key` the way a Unix server's pane does after its app wrote
+/// `app_output` (for example a Kitty keyboard push): the libghostty path,
+/// without the Windows ConPTY record fallback (covered by the Windows harness).
+#[cfg(test)]
+pub(crate) fn test_encode_key_for_app(
+ app_output: &[u8],
+ key: crate::input::TerminalKey,
+) -> Vec<u8> {
+ let (tx, _rx) = mpsc::channel(4);
+ let terminal = crate::ghostty::Terminal::new(80, 24, 0).expect("terminal");
+ let pane = GhosttyPaneTerminal::new(terminal, tx.clone()).expect("pane terminal");
+ pane.process_pty_bytes(PaneId::from_raw(1), 0, app_output, &tx);
+ pane.encode_terminal_key_once(key)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -4724,13 +4731,10 @@ mod tests {
let terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
- let encoded = pane.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Char('a'),
- crossterm::event::KeyModifiers::empty(),
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let encoded = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Char('a'),
+ crossterm::event::KeyModifiers::empty(),
+ ));
assert_eq!(encoded, b"a");
}
@@ -4747,16 +4751,15 @@ mod tests {
terminal.write(format!("\x1b[>{flags}u").as_bytes());
}
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
- let protocol = pane.keyboard_protocol().unwrap();
for modifiers in [
crossterm::event::KeyModifiers::empty(),
crossterm::event::KeyModifiers::SHIFT,
] {
- let encoded = pane.encode_terminal_key(
- crate::input::TerminalKey::new(crossterm::event::KeyCode::BackTab, modifiers),
- protocol,
- );
+ let encoded = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::BackTab,
+ modifiers,
+ ));
assert_eq!(encoded, expected, "backtab with modifiers {modifiers:?}");
}
}
@@ -4764,13 +4767,10 @@ mod tests {
let (tx, _rx) = mpsc::channel(4);
let terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
- let encoded = pane.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Tab,
- crossterm::event::KeyModifiers::empty(),
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let encoded = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Tab,
+ crossterm::event::KeyModifiers::empty(),
+ ));
assert_eq!(encoded, b"\t");
}
@@ -4784,18 +4784,12 @@ mod tests {
crossterm::event::KeyModifiers::CONTROL,
);
- assert_eq!(
- legacy.encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy),
- b"\t"
- );
+ assert_eq!(legacy.encode_terminal_key(key.clone()), b"\t");
let mut terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
terminal.write(b"\x1b[>3u");
let kitty = GhosttyPaneTerminal::new(terminal, tx).unwrap();
- assert_eq!(
- kitty.encode_terminal_key(key, crate::input::KeyboardProtocol::Kitty { flags: 3 }),
- b"\x1b[9;5u"
- );
+ assert_eq!(kitty.encode_terminal_key(key), b"\x1b[9;5u");
}
#[cfg(unix)]
@@ -4806,7 +4800,6 @@ mod tests {
let (tx, _rx) = mpsc::channel(4);
let terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
- let protocol = crate::input::KeyboardProtocol::Legacy;
for modifiers in [
KeyModifiers::empty(),
@@ -4819,25 +4812,29 @@ mod tests {
KeyModifiers::ALT | KeyModifiers::CONTROL | KeyModifiers::SUPER,
] {
let key = crate::input::TerminalKey::new(KeyCode::Enter, modifiers);
- let expected = if modifiers.contains(KeyModifiers::ALT) {
+ // Super chords never reach a plain shell, so Cmd+Enter cannot run
+ // the command line.
+ let expected = if modifiers.contains(KeyModifiers::SUPER) {
+ b"".as_slice()
+ } else if modifiers.contains(KeyModifiers::ALT) {
b"\x1b\r".as_slice()
} else {
b"\r".as_slice()
};
for kind in [KeyEventKind::Press, KeyEventKind::Repeat] {
assert_eq!(
- pane.encode_terminal_key(key.clone().with_kind(kind), protocol),
+ pane.encode_terminal_key(key.clone().with_kind(kind)),
expected,
"{modifiers:?} {kind:?}"
);
}
assert_eq!(
- pane.encode_terminal_key(key.clone().with_repeat_count(3), protocol),
+ pane.encode_terminal_key(key.clone().with_repeat_count(3)),
expected.repeat(3),
"{modifiers:?} grouped repeat"
);
assert!(
- pane.encode_terminal_key(key.with_kind(KeyEventKind::Release), protocol)
+ pane.encode_terminal_key(key.with_kind(KeyEventKind::Release))
.is_empty(),
"{modifiers:?} release"
);
@@ -4853,8 +4850,9 @@ mod tests {
let terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
let pane = GhosttyPaneTerminal::new(terminal, tx.clone()).unwrap();
let pane_id = PaneId::from_raw(1);
- let legacy = ["\r", "\r", "\r", "\x1b\r"];
- let mode_one = ["\x1b[27;2;13~", "\x1b[27;5;13~", "\x1b[27;9;13~", "\x1b\r"];
+ // Like Ghostty, modifyOtherKeys level 1 behaves as if nothing was negotiated.
+ // Super+Enter is not forwarded to panes without a keyboard protocol.
+ let legacy = ["\r", "\r", "", "\x1b\r"];
let mode_two = [
"\x1b[27;2;13~",
"\x1b[27;5;13~",
@@ -4865,7 +4863,7 @@ mod tests {
for (sequence, expected) in [
("", legacy),
- ("\x1b[>4;1m", mode_one),
+ ("\x1b[>4;1m", legacy),
("\x1b[>4;2m", mode_two),
("\x1b[>4n", legacy),
("\x1b[>4;2m", mode_two),
@@ -4875,7 +4873,7 @@ mod tests {
("\x1b[>4;2m\x1b[>1u", kitty),
("\x1b[<u", mode_two),
("\x1b[>4;0m", legacy),
- ("\x1b[>4;1m", mode_one),
+ ("\x1b[>4;1m", legacy),
("\x1b[>04n", legacy),
("\x1b[>4;2m", mode_two),
("\x1b[>4", mode_two),
@@ -4893,7 +4891,7 @@ mod tests {
{
let key = crate::input::TerminalKey::new(KeyCode::Enter, modifiers);
assert_eq!(
- pane.encode_terminal_key(key, crate::input::KeyboardProtocol::Legacy),
+ pane.encode_terminal_key(key),
expected.as_bytes(),
"{modifiers:?} after {sequence:?}"
);
@@ -4912,10 +4910,7 @@ mod tests {
crossterm::event::KeyModifiers::SHIFT,
);
- assert_eq!(
- pane.encode_terminal_key(key, crate::input::KeyboardProtocol::Legacy),
- b"\x1b[27;2;13~"
- );
+ assert_eq!(pane.encode_terminal_key(key), b"\x1b[27;2;13~");
}
#[test]
@@ -4928,14 +4923,13 @@ mod tests {
crossterm::event::KeyCode::Enter,
crossterm::event::KeyCode::Backspace,
] {
- let press = pane.encode_terminal_key(
- crate::input::TerminalKey::new(code, crossterm::event::KeyModifiers::empty()),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let press = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ code,
+ crossterm::event::KeyModifiers::empty(),
+ ));
let release = pane.encode_terminal_key(
crate::input::TerminalKey::new(code, crossterm::event::KeyModifiers::empty())
.with_kind(crossterm::event::KeyEventKind::Release),
- crate::input::KeyboardProtocol::Legacy,
);
assert!(!press.is_empty(), "{code:?} press should emit bytes");
assert!(
@@ -4957,10 +4951,10 @@ mod tests {
(crossterm::event::KeyCode::Enter, b"\r".as_slice()),
(crossterm::event::KeyCode::Backspace, b"\x7f".as_slice()),
] {
- let press = pane.encode_terminal_key(
- crate::input::TerminalKey::new(code, crossterm::event::KeyModifiers::empty()),
- pane.keyboard_protocol().unwrap(),
- );
+ let press = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ code,
+ crossterm::event::KeyModifiers::empty(),
+ ));
assert_eq!(
press, expected,
"{code:?} press should stay legacy-compatible without REPORT_ALL_KEYS"
@@ -4969,7 +4963,6 @@ mod tests {
let release = pane.encode_terminal_key(
crate::input::TerminalKey::new(code, crossterm::event::KeyModifiers::empty())
.with_kind(crossterm::event::KeyEventKind::Release),
- pane.keyboard_protocol().unwrap(),
);
assert!(
release.is_empty(),
@@ -4979,21 +4972,173 @@ mod tests {
}
#[test]
- fn ghostty_char_keys_still_use_herdr_encoding() {
+ fn ghostty_alt_letters_keep_esc_prefix_on_every_platform() {
+ // libghostty treats macOS Option as a text modifier unless told otherwise;
+ // Herdr has already decoded Alt from these host bytes.
+ for (host_bytes, expected) in [
+ ("\x1bf", &b"\x1bf"[..]),
+ ("\x1bb", b"\x1bb"),
+ ("\x1bA", b"\x1bA"),
+ ("\x1b.", b"\x1b."),
+ ] {
+ let key = crate::input::parse_terminal_key_sequence(host_bytes).expect("alt key");
+ assert_eq!(
+ test_encode_key_for_app(b"", key),
+ expected,
+ "{host_bytes:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn hyper_and_meta_chords_are_never_typed_as_their_bare_key() {
+ // iTerm2 can report Ctrl as Meta (#4476): `CSI 97;33u`. Typing "a"
+ // would run a command in vim normal mode; libghostty has no Meta.
+ for host_bytes in ["\x1b[97;33u", "\x1b[120;17u"] {
+ let key = crate::input::parse_terminal_key_sequence(host_bytes).expect("kitty key");
+ for app_output in [&b""[..], b"\x1b[>1u", b"\x1b[>31u"] {
+ assert!(
+ test_encode_key_for_app(app_output, key.clone()).is_empty(),
+ "{host_bytes:?} after {app_output:?}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn super_chords_reach_only_panes_that_negotiated_a_keyboard_protocol() {
+ // Super+Space from a Kitty host (#4356) and Cmd+C (#3710).
+ // Super+Enter must not become a plain Enter that runs the command line.
+ for (host_bytes, kitty) in [
+ ("\x1b[32;9u", &b"\x1b[32;9u"[..]),
+ ("\x1b[99;9u", b"\x1b[99;9u"),
+ ("\x1b[13;9u", b"\x1b[13;9u"),
+ ] {
+ let key = crate::input::parse_terminal_key_sequence(host_bytes).expect("kitty key");
+ assert!(
+ test_encode_key_for_app(b"", key.clone()).is_empty(),
+ "{host_bytes:?} in a plain shell"
+ );
+ assert_eq!(
+ test_encode_key_for_app(b"\x1b[>1u", key),
+ kitty,
+ "{host_bytes:?} in a Kitty pane"
+ );
+ }
+ }
+
+ #[test]
+ fn ctrl_shift_letters_reach_plain_shells_as_control_bytes() {
+ // Lab capture: Alacritty and WezTerm (with or without Kitty keyboard)
+ // send 0x01 for Ctrl+Shift+A; Ghostty's CSI u prints as garbage in a shell.
+ for (host_bytes, plain, kitty) in [
+ ("\x1b[97;6u", &b"\x01"[..], &b"\x1b[97;6u"[..]),
+ ("\x1b[65;5u", b"\x01", b"\x1b[97;6u"),
+ ("\x1b[97;8u", b"\x1b\x01", b"\x1b[97;8u"),
+ ] {
+ let key = crate::input::parse_terminal_key_sequence(host_bytes).expect("kitty key");
+ assert_eq!(
+ test_encode_key_for_app(b"", key.clone()),
+ plain,
+ "{host_bytes:?} in a plain shell"
+ );
+ assert_eq!(
+ test_encode_key_for_app(b"\x1b[>1u", key),
+ kitty,
+ "{host_bytes:?} in a Kitty pane"
+ );
+ }
+ }
+
+ #[test]
+ fn ctrl_on_a_russian_layout_interrupts_a_plain_shell() {
+ // Lab capture: kitty reports Ctrl+\u{441} as `CSI 1089::99;5u`; kitty
+ // itself sends ^C to a plain shell.
+ let key = crate::input::parse_terminal_key_sequence("\x1b[1089::99;5u").expect("key");
+ assert_eq!(test_encode_key_for_app(b"", key.clone()), b"\x03");
+ assert_eq!(test_encode_key_for_app(b"\x1b[>1u", key), b"\x1b[99;5u");
+ }
+
+ #[test]
+ fn legacy_alt_prefixes_the_produced_non_ascii_text() {
+ // A legacy host's Alt+Shift+\u{f6}. libghostty on macOS would prefix the
+ // unshifted "\u{f6}" instead.
+ for host_bytes in ["\x1b\u{d6}", "\x1b\u{f6}"] {
+ let key = crate::input::parse_terminal_key_sequence(host_bytes).expect("alt key");
+ assert_eq!(
+ test_encode_key_for_app(b"", key),
+ host_bytes.as_bytes(),
+ "{host_bytes:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn ghostty_kitty_reports_keep_non_us_key_identity() {
+ // Ctrl++ on a German layout, where + is an unshifted key. The report
+ // already names the key; nothing may reinterpret it as US Shift+=.
+ let key = crate::input::parse_terminal_key_sequence("\x1b[43;5u").expect("kitty key");
+ assert_eq!(test_encode_key_for_app(b"\x1b[>1u", key), b"\x1b[43;5u");
+ }
+
+ #[test]
+ fn ghostty_disambiguate_reports_ctrl_letters_as_kitty_keys() {
let (tx, _rx) = mpsc::channel(4);
let mut terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
terminal.write(b"\x1b[>1u");
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
- let encoded = pane.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Char('a'),
- crossterm::event::KeyModifiers::CONTROL,
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let encoded = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Char('a'),
+ crossterm::event::KeyModifiers::CONTROL,
+ ));
+
+ assert_eq!(encoded, b"\x1b[97;5u");
+ }
- assert_eq!(encoded, vec![1]);
+ #[test]
+ fn ghostty_encodes_text_keys_with_layout_text() {
+ let (tx, _rx) = mpsc::channel(4);
+ let terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
+ let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
+
+ for (key, expected) in [
+ (
+ crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Char('D'),
+ crossterm::event::KeyModifiers::SHIFT,
+ ),
+ "D",
+ ),
+ (
+ crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Char('%'),
+ crossterm::event::KeyModifiers::empty(),
+ ),
+ "%",
+ ),
+ (
+ crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Char('ö'),
+ crossterm::event::KeyModifiers::empty(),
+ )
+ .with_generated_text(Some("ö".to_owned())),
+ "ö",
+ ),
+ (
+ crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Char('8'),
+ crossterm::event::KeyModifiers::CONTROL,
+ ),
+ "\x7f",
+ ),
+ ] {
+ assert_eq!(
+ pane.encode_terminal_key(key.clone()),
+ expected.as_bytes(),
+ "{key:?}"
+ );
+ }
}
#[test]
@@ -5005,13 +5150,10 @@ mod tests {
.unwrap();
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
- let encoded = pane.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Up,
- crossterm::event::KeyModifiers::empty(),
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let encoded = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Up,
+ crossterm::event::KeyModifiers::empty(),
+ ));
assert_eq!(encoded, b"\x1bOA");
}
@@ -5051,17 +5193,14 @@ mod tests {
);
assert_eq!(pane.modify_other_keys_level(), 2);
- let encoded = pane.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Up,
- crossterm::event::KeyModifiers::empty(),
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let encoded = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Up,
+ crossterm::event::KeyModifiers::empty(),
+ ));
assert_eq!(encoded, b"\x1bOA");
let key = crate::input::parse_terminal_key_sequence("\x1b[13;2u").unwrap();
- let encoded = pane.encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy);
+ let encoded = pane.encode_terminal_key(key.clone());
assert_eq!(encoded, b"\x1b[27;2;13~");
let encoded = pane.encode_mouse_wheel(
@@ -5083,10 +5222,7 @@ mod tests {
)
.with_repeat_count(3);
- assert_eq!(
- pane.encode_terminal_key(key, crate::input::KeyboardProtocol::Legacy),
- b"xxx"
- );
+ assert_eq!(pane.encode_terminal_key(key), b"xxx");
let shifted = crate::input::TerminalKey::new(
crossterm::event::KeyCode::Char('/'),
@@ -5105,17 +5241,14 @@ mod tests {
let legacy_expected = b"\x1b[55;8;47;1;16;3_".as_slice();
#[cfg(not(windows))]
let legacy_expected = b"///".as_slice();
- assert_eq!(
- pane.encode_terminal_key(shifted.clone(), crate::input::KeyboardProtocol::Legacy,),
- legacy_expected
- );
+ assert_eq!(pane.encode_terminal_key(shifted.clone()), legacy_expected);
let mut terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
terminal.write(b"\x1b[>15u");
let (tx, _rx) = mpsc::channel(4);
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
assert_eq!(
- pane.encode_terminal_key(shifted, crate::input::KeyboardProtocol::Kitty { flags: 15 },),
- b"\x1b[47;2:1u\x1b[47;2:2u\x1b[47;2:2u"
+ pane.encode_terminal_key(shifted),
+ b"\x1b[47;2u\x1b[47;2:2u\x1b[47;2:2u"
);
}
@@ -5125,21 +5258,17 @@ mod tests {
let mut terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
terminal.write(b"\x1b[>11u");
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
- let protocol = pane.keyboard_protocol().unwrap();
let release = crate::input::TerminalKey::new(
crossterm::event::KeyCode::Up,
crossterm::event::KeyModifiers::empty(),
)
.with_kind(crossterm::event::KeyEventKind::Release);
- let expected = pane.encode_terminal_key(release.clone(), protocol);
+ let expected = pane.encode_terminal_key(release.clone());
assert!(!expected.is_empty());
let mut malformed_release = release;
malformed_release.repeat_count = 3;
- assert_eq!(
- pane.encode_terminal_key(malformed_release, protocol),
- expected
- );
+ assert_eq!(pane.encode_terminal_key(malformed_release), expected);
}
#[test]
@@ -5149,24 +5278,18 @@ mod tests {
let pane = GhosttyPaneTerminal::new(terminal, tx.clone()).unwrap();
let pane_id = PaneId::from_raw(1);
- let before = pane.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Up,
- crossterm::event::KeyModifiers::empty(),
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let before = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Up,
+ crossterm::event::KeyModifiers::empty(),
+ ));
assert_eq!(before, b"\x1b[A");
pane.process_pty_bytes(pane_id, 0, b"\x1b[?1h", &tx);
- let after = pane.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Up,
- crossterm::event::KeyModifiers::empty(),
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let after = pane.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Up,
+ crossterm::event::KeyModifiers::empty(),
+ ));
assert_eq!(after, b"\x1bOA");
}
@@ -5181,9 +5304,9 @@ mod tests {
crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::SHIFT,
);
- let before = pane.encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy);
+ let before = pane.encode_terminal_key(key.clone());
pane.process_pty_bytes(pane_id, 0, b"\x1b[>1u", &tx);
- let after = pane.encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy);
+ let after = pane.encode_terminal_key(key.clone());
assert_ne!(before, after);
assert_eq!(after, b"\x1b[13;6u");
@@ -5198,7 +5321,7 @@ mod tests {
pane.process_pty_bytes(pane_id, 0, b"\x1b[>5u", &tx);
let key = crate::input::parse_terminal_key_sequence("\x1b[13;2u").unwrap();
- let encoded = pane.encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy);
+ let encoded = pane.encode_terminal_key(key.clone());
assert_eq!(
pane.keyboard_protocol(),
@@ -5216,7 +5339,7 @@ mod tests {
pane.seed_keyboard_protocol_flags(5);
let key = crate::input::parse_terminal_key_sequence("\x1b[13;2u").unwrap();
- let encoded = pane.encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy);
+ let encoded = pane.encode_terminal_key(key.clone());
assert_eq!(
pane.keyboard_protocol(),
@@ -5261,10 +5384,7 @@ mod tests {
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
let key = crate::input::parse_terminal_key_sequence("\x1b[13;2u").unwrap();
- assert_eq!(
- pane.encode_terminal_key(key, crate::input::KeyboardProtocol::Legacy),
- b"\x1b[13;28;13;1;16;1_"
- );
+ assert_eq!(pane.encode_terminal_key(key), b"\x1b[13;28;13;1;16;1_");
}
#[cfg(windows)]
@@ -5282,30 +5402,31 @@ mod tests {
b"\x1b[13;28;13;1;16;1_".as_slice(),
),
(crossterm::event::KeyModifiers::CONTROL, b"\r".as_slice()),
- (crossterm::event::KeyModifiers::SUPER, b"\r".as_slice()),
+ // Super chords never reach a plain shell (no command-line submit).
+ (crossterm::event::KeyModifiers::SUPER, b"".as_slice()),
(crossterm::event::KeyModifiers::ALT, b"\x1b\r".as_slice()),
] {
let key = crate::input::TerminalKey::new(crossterm::event::KeyCode::Enter, modifiers);
- assert_eq!(
- pane.encode_terminal_key(key, crate::input::KeyboardProtocol::Legacy),
- expected,
- "{modifiers:?}"
- );
+ assert_eq!(pane.encode_terminal_key(key), expected, "{modifiers:?}");
}
}
#[test]
- fn ghostty_modify_other_keys_mode_one_preserves_shift_enter() {
+ fn ghostty_modify_other_keys_mode_one_is_treated_as_unnegotiated() {
let (tx, _rx) = mpsc::channel(4);
let terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
let key = crate::input::parse_terminal_key_sequence("\x1b[13;2u").unwrap();
pane.seed_history_ansi("\x1b[>4;1m");
- assert_eq!(pane.modify_other_keys_level(), 1);
- let encoded = pane.encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy);
+ assert_eq!(pane.modify_other_keys_level(), 0);
+ let encoded = pane.encode_terminal_key(key.clone());
- assert_eq!(encoded, b"\x1b[27;2;13~");
+ // An unnegotiated Windows pane gets the native ConPTY record instead.
+ #[cfg(windows)]
+ assert_eq!(encoded, b"\x1b[13;28;13;1;16;1_");
+ #[cfg(not(windows))]
+ assert_eq!(encoded, b"\r");
}
#[test]
@@ -5317,7 +5438,7 @@ mod tests {
pane.process_pty_bytes(pane_id, 0, b"\x1b[>1u", &tx);
let key = crate::input::parse_terminal_key_sequence("\x1b\x7f").unwrap();
- let encoded = pane.encode_terminal_key(key.clone(), crate::input::KeyboardProtocol::Legacy);
+ let encoded = pane.encode_terminal_key(key.clone());
assert_eq!(encoded, b"\x1b[127;3u");
}
@@ -5334,7 +5455,7 @@ mod tests {
let crate::raw_input::RawInputEvent::Key(key) = events.remove(0) else {
panic!("expected key event");
};
- let encoded = pane.encode_terminal_key(key, pane.keyboard_protocol().unwrap());
+ let encoded = pane.encode_terminal_key(key);
assert_eq!(encoded, b"\x1b[102;7u");
}
@@ -5352,22 +5473,13 @@ mod tests {
crossterm::event::KeyCode::Backspace,
crossterm::event::KeyModifiers::CONTROL,
);
- assert_eq!(
- legacy.encode_terminal_key(
- ctrl_backspace.clone(),
- crate::input::KeyboardProtocol::Legacy
- ),
- b"\x08"
- );
+ assert_eq!(legacy.encode_terminal_key(ctrl_backspace.clone()), b"\x08");
let plain_backspace = crate::input::TerminalKey::new(
crossterm::event::KeyCode::Backspace,
crossterm::event::KeyModifiers::empty(),
);
- assert_eq!(
- legacy.encode_terminal_key(plain_backspace, crate::input::KeyboardProtocol::Legacy),
- b"\x7f"
- );
+ assert_eq!(legacy.encode_terminal_key(plain_backspace), b"\x7f");
let kitty = GhosttyPaneTerminal::new(
crate::ghostty::Terminal::new(80, 24, 0).unwrap(),
@@ -5377,10 +5489,7 @@ mod tests {
let pane_id = PaneId::from_raw(1);
kitty.process_pty_bytes(pane_id, 0, b"\x1b[>1u", &tx);
- assert_eq!(
- kitty.encode_terminal_key(ctrl_backspace, crate::input::KeyboardProtocol::Legacy),
- b"\x1b[127;5u"
- );
+ assert_eq!(kitty.encode_terminal_key(ctrl_backspace), b"\x1b[127;5u");
}
#[test]
@@ -5399,20 +5508,14 @@ mod tests {
first.process_pty_bytes(PaneId::from_raw(1), 0, b"\x1b[?1h", &tx);
- let first_encoded = first.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Up,
- crossterm::event::KeyModifiers::empty(),
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
- let second_encoded = second.encode_terminal_key(
- crate::input::TerminalKey::new(
- crossterm::event::KeyCode::Up,
- crossterm::event::KeyModifiers::empty(),
- ),
- crate::input::KeyboardProtocol::Legacy,
- );
+ let first_encoded = first.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Up,
+ crossterm::event::KeyModifiers::empty(),
+ ));
+ let second_encoded = second.encode_terminal_key(crate::input::TerminalKey::new(
+ crossterm::event::KeyCode::Up,
+ crossterm::event::KeyModifiers::empty(),
+ ));
assert_eq!(first_encoded, b"\x1bOA");
assert_eq!(second_encoded, b"\x1b[A");
diff --git a/src/platform/mod.rs b/src/platform/mod.rs
index 2e7a601b0..14259c021 100644
--- a/src/platform/mod.rs
+++ b/src/platform/mod.rs
@@ -207,6 +207,15 @@ pub(crate) const fn capabilities() -> PlatformCapabilities {
}
}
+/// The byte the host terminal sends for Backspace according to the tty's erase
+/// setting (e.g. `^H` for MobaXterm and PuTTY-style terminals), when known.
+pub(crate) fn terminal_erase_byte() -> Option<u8> {
+ #[cfg(unix)]
+ return unix_common::terminal_erase_byte();
+ #[cfg(not(unix))]
+ None
+}
+
pub(crate) fn terminal_grid_size() -> std::io::Result<(u16, u16)> {
#[cfg(unix)]
let (cols, rows) = unix_common::read_terminal_grid_size()?;
diff --git a/src/platform/unix_common.rs b/src/platform/unix_common.rs
index 52a7bbb65..b013b06c1 100644
--- a/src/platform/unix_common.rs
+++ b/src/platform/unix_common.rs
@@ -17,6 +17,17 @@ pub(crate) fn read_fd(fd: std::os::fd::RawFd, data: &mut [u8]) -> std::io::Resul
}
}
+/// The tty's erase character (VERASE) on stdin, when one is set.
+pub(super) fn terminal_erase_byte() -> Option<u8> {
+ let mut termios: libc::termios = unsafe { std::mem::zeroed() };
+ if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut termios) } != 0 {
+ return None;
+ }
+ let erase = termios.c_cc[libc::VERASE];
+ // 0 (Linux) and 0xff (BSD) disable the special character.
+ (erase != 0 && erase != 0xff).then_some(erase)
+}
+
pub(crate) fn poll_fd_readable(fd: std::os::fd::RawFd, timeout_ms: i32) -> std::io::Result<bool> {
let mut descriptor = libc::pollfd {
fd,
diff --git a/src/protocol/wire.rs b/src/protocol/wire.rs
index 6d49592d2..ead2ddd7b 100644
--- a/src/protocol/wire.rs
+++ b/src/protocol/wire.rs
@@ -397,29 +397,6 @@ impl ClientPaneInputEvent {
#[cfg(any(windows, test))]
impl ClientInputEvent {
- pub(crate) fn from_crossterm(event: crossterm::event::Event) -> Option<Self> {
- match event {
- crossterm::event::Event::Key(key) => Some(Self::Key {
- code: ClientKeyCode::from_crossterm(key.code)?,
- modifiers: key.modifiers.bits(),
- kind: ClientKeyKind::from_crossterm(key.kind),
- repeat_count: 1,
- generated_text: None,
- source: ClientKeySource::Synthesized,
- }),
- crossterm::event::Event::Mouse(mouse) => Some(Self::Mouse {
- kind: ClientMouseKind::from_crossterm(mouse.kind)?,
- column: mouse.column,
- row: mouse.row,
- modifiers: mouse.modifiers.bits(),
- }),
- crossterm::event::Event::Paste(text) => Some(Self::Paste { text }),
- crossterm::event::Event::FocusGained => Some(Self::FocusGained),
- crossterm::event::Event::FocusLost => Some(Self::FocusLost),
- crossterm::event::Event::Resize(_, _) => None,
- }
- }
-
pub(crate) fn to_raw_input_event(&self) -> crate::raw_input::RawInputEvent {
match self {
Self::Key {
@@ -2225,11 +2202,7 @@ mod tests {
};
assert!(key.is_windows_dead_key());
assert_eq!(key.windows_record(), None);
- assert!(crate::input::encode_terminal_key(
- key,
- crate::input::KeyboardProtocol::Kitty { flags: 1 },
- )
- .is_empty());
+ assert!(crate::pane::test_encode_key_for_app(b"\x1b[>1u", key).is_empty());
}
#[tokio::test]
@@ -2307,10 +2280,7 @@ mod tests {
};
assert!(roundtripped.has_physical_identity());
- let encoded = crate::input::encode_terminal_key(
- roundtripped,
- crate::input::KeyboardProtocol::Kitty { flags: 8 },
- );
+ let encoded = crate::pane::test_encode_key_for_app(b"\x1b[>8u", roundtripped);
assert_ne!(encoded, b"/");
assert!(encoded.starts_with(b"\x1b["));
}
diff --git a/src/raw_input.rs b/src/raw_input.rs
index c66d75840..8c0cb8541 100644
--- a/src/raw_input.rs
+++ b/src/raw_input.rs
@@ -1,12 +1,11 @@
use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
-#[cfg(windows)]
use std::time::{Duration, Instant};
/// Parse raw terminal input bytes into a list of `RawInputEvent`s.
///
/// This directly extracts events without going through a channel, making it
/// suitable for synchronous use.
-#[cfg(any(unix, test))]
+#[cfg(test)]
pub fn parse_raw_input_bytes_sync(data: &[u8]) -> Vec<RawInputEvent> {
let mut framer = RawInputFramer::default();
let mut events = framer.push(data);
@@ -14,6 +13,24 @@ pub fn parse_raw_input_bytes_sync(data: &[u8]) -> Vec<RawInputEvent> {
events
}
+/// Decode bytes the byte framer already split into complete input. This applies
+/// no timing policy of its own: the reader decided where each event ends.
+#[cfg(any(unix, test))]
+pub(crate) fn parse_framed_input(data: &[u8]) -> Vec<RawInputEvent> {
+ let mut events = Vec::new();
+ let mut rest = data;
+ while !rest.is_empty() {
+ let Some((event, consumed)) = extract_one_event(rest) else {
+ // A lone ESC or Alt introducer the reader released as a key.
+ events.extend(events_from_framed_chunks(vec![rest.to_vec()]));
+ break;
+ };
+ events.push(event);
+ rest = &rest[consumed..];
+ }
+ events
+}
+
use crate::input::{parse_terminal_key_sequence, TerminalKey, TextCommit};
use crate::terminal_theme::{
parse_default_color_response, parse_palette_color_response, DefaultColorKind, HostAppearance,
@@ -21,16 +38,20 @@ use crate::terminal_theme::{
};
const ESC: u8 = 0x1b;
-#[cfg(unix)]
+#[cfg(any(unix, test))]
pub(crate) const RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS: i32 = 10;
-#[cfg(unix)]
+#[cfg(any(unix, test))]
pub(crate) const MOUSE_ACTIVE_ESCAPE_SEQUENCE_FLUSH_TIMEOUT_MS: i32 = 150;
/// Covers the 33 ms split in #4630 without gluing legacy Alt+[ to the next key.
-#[cfg(unix)]
+#[cfg(any(unix, test))]
pub(crate) const MOUSE_ACTIVE_CSI_INTRODUCER_FLUSH_TIMEOUT_MS: i32 = 50;
/// Covers the 350 ms mouse tail delay in #3480. Other input ends it early (#4751).
#[cfg(unix)]
const DISAMBIGUATED_MOUSE_TAIL_FLUSH_TIMEOUT_MS: i32 = 500;
+/// Bytes already inside a sequence cannot be a key, so wait long enough for a
+/// split read over a slow link before giving up on them.
+#[cfg(any(unix, test))]
+pub(crate) const INCOMPLETE_SEQUENCE_FLUSH_TIMEOUT_MS: i32 = 500;
pub(crate) const GHOSTTY_COLOR_SCHEME_DARK_REPORT: &[u8] = b"\x1b[?997;1n";
pub(crate) const GHOSTTY_COLOR_SCHEME_LIGHT_REPORT: &[u8] = b"\x1b[?997;2n";
const BRACKETED_PASTE_START: &[u8] = b"\x1b[200~";
@@ -79,13 +100,15 @@ pub enum RawInputEvent {
Unsupported,
}
+/// Byte framer plus event decoding, for the Windows input pump.
+#[cfg(any(windows, test))]
#[derive(Default)]
pub(crate) struct RawInputFramer {
byte_framer: RawInputByteFramer,
}
+#[cfg(any(windows, test))]
impl RawInputFramer {
- #[cfg(any(windows, test))]
pub(crate) fn for_host_input() -> Self {
Self {
byte_framer: RawInputByteFramer::for_host_input(),
@@ -98,12 +121,7 @@ impl RawInputFramer {
}
pub(crate) fn push(&mut self, data: &[u8]) -> Vec<RawInputEvent> {
- Self::events_from_chunks(self.byte_framer.push(data))
- }
-
- #[cfg(any(windows, test))]
- pub(crate) fn has_pending_input(&self) -> bool {
- self.byte_framer.has_pending_input()
+ events_from_framed_chunks(self.byte_framer.push(data))
}
#[cfg(windows)]
@@ -121,58 +139,61 @@ impl RawInputFramer {
false
}
- #[cfg(any(windows, test))]
pub(crate) fn has_pending_bracketed_paste(&self) -> bool {
self.byte_framer.has_pending_bracketed_paste()
}
- #[cfg(any(windows, test))]
pub(crate) fn has_pending_default_mouse_sequence(&self) -> bool {
starts_with_incomplete_default_mouse_sequence(&self.byte_framer.buffer)
}
pub(crate) fn flush_timeout(&mut self) -> Vec<RawInputEvent> {
- Self::events_from_chunks(self.byte_framer.flush_timeout())
+ events_from_framed_chunks(self.byte_framer.flush_timeout())
}
- #[cfg(any(windows, test))]
pub(crate) fn flush_keyboard_escape(&mut self) -> Vec<RawInputEvent> {
if self.byte_framer.buffer.as_slice() == [ESC] {
self.byte_framer.lone_escape_recently_flushed = true;
- Self::events_from_chunks(vec![std::mem::take(&mut self.byte_framer.buffer)])
+ events_from_framed_chunks(vec![std::mem::take(&mut self.byte_framer.buffer)])
} else {
self.flush_timeout()
}
}
/// Semantic input ends mouse recovery, unlike another idle interval.
- #[cfg(any(windows, test))]
pub(crate) fn flush_interrupted(&mut self) -> Vec<RawInputEvent> {
#[cfg(windows)]
self.byte_framer.flush_lone_escape_on_interruption();
let mut chunks = self.byte_framer.flush_timeout();
self.byte_framer.timed_out_mouse_prefix = None;
chunks.extend(self.byte_framer.drain_available_chunks());
- Self::events_from_chunks(chunks)
+ events_from_framed_chunks(chunks)
}
+}
- fn events_from_chunks(chunks: Vec<Vec<u8>>) -> Vec<RawInputEvent> {
- chunks
- .into_iter()
- .filter_map(|chunk| {
- if chunk.as_slice() == [ESC] {
- return Some(RawInputEvent::Key(
- TerminalKey::new(crossterm::event::KeyCode::Esc, KeyModifiers::empty())
- .with_vt_bytes(chunk),
- ));
- }
- extract_one_event(&chunk).map(|(event, _consumed)| {
- tracing::debug!(raw_bytes = ?chunk, event = ?event, "raw input event parsed");
- event
- })
+/// Events for chunks the byte framer released as complete input.
+fn events_from_framed_chunks(chunks: Vec<Vec<u8>>) -> Vec<RawInputEvent> {
+ chunks
+ .into_iter()
+ .filter_map(|chunk| {
+ if chunk.as_slice() == [ESC] {
+ return Some(RawInputEvent::Key(
+ TerminalKey::new(crossterm::event::KeyCode::Esc, KeyModifiers::empty())
+ .with_vt_bytes(chunk),
+ ));
+ }
+ // The byte framer released this introducer as a key on its own.
+ if is_alt_key_introducer(&chunk) {
+ let text = std::str::from_utf8(&chunk).ok()?;
+ return parse_terminal_key_sequence(text)
+ .map(|key| RawInputEvent::Key(key.with_vt_bytes(chunk.clone())));
+ }
+ extract_one_event(&chunk).map(|(event, _consumed)| {
+ tracing::debug!(raw_bytes = ?chunk, event = ?event, "raw input event parsed");
+ event
})
- .collect()
- }
+ })
+ .collect()
}
#[derive(Default)]
@@ -194,6 +215,9 @@ pub(crate) struct RawInputByteFramer {
host_color_tail_split_st: bool,
host_cell_size_replies_awaited: u16,
host_appearance_reply_awaited: bool,
+ /// Last query sent or reply received. Hosts may answer only part of a
+ /// query (or none of it), so the reply counters alone never expire.
+ host_reply_activity_at: Option<Instant>,
held_pending_host_reply_esc: bool,
host_color_scheme_change_tracking: bool,
host_appearance_query_on_focus: bool,
@@ -205,6 +229,9 @@ pub(crate) struct RawInputByteFramer {
}
const HOST_COLOR_QUERY_REPLIES: u16 = 258;
+/// How long after the last query or reply Herdr still treats `ESC[` / `ESC]`
+/// as a possible host reply instead of a key.
+const HOST_REPLY_QUIET_WINDOW: Duration = Duration::from_secs(1);
#[cfg(any(unix, test))]
const HOST_CELL_SIZE_QUERY_REPLIES: u16 = 1;
const MAX_ORPHANED_SGR_MOUSE_TAIL_BYTES: usize = 32;
@@ -254,6 +281,7 @@ impl RawInputByteFramer {
fn host_color_query_sent_with_replies(&mut self, replies: u16) {
self.host_color_replies_awaited = self.host_color_replies_awaited.saturating_add(replies);
self.held_pending_host_reply_esc = false;
+ self.host_reply_activity_at = Some(Instant::now());
}
#[cfg(windows)]
@@ -267,6 +295,7 @@ impl RawInputByteFramer {
fn host_appearance_query_sent(&mut self) {
self.host_appearance_reply_awaited = true;
self.held_pending_host_reply_esc = false;
+ self.host_reply_activity_at = Some(Instant::now());
}
/// Same hold window as `host_color_query_sent`, for the XTWINOPS cell size
@@ -275,12 +304,41 @@ impl RawInputByteFramer {
pub(crate) fn host_cell_size_query_sent(&mut self) {
self.host_cell_size_replies_awaited = HOST_CELL_SIZE_QUERY_REPLIES;
self.held_pending_host_reply_esc = false;
+ self.host_reply_activity_at = Some(Instant::now());
}
fn awaiting_host_reply(&self) -> bool {
- self.host_color_replies_awaited > 0
+ (self.host_color_replies_awaited > 0
|| self.host_cell_size_replies_awaited > 0
- || self.host_appearance_reply_awaited
+ || self.host_appearance_reply_awaited)
+ && self
+ .host_reply_activity_at
+ .is_some_and(|at| at.elapsed() < HOST_REPLY_QUIET_WINDOW)
+ }
+
+ /// Stop expecting replies the host never sent, so their reply handling no
+ /// longer holds or discards what is now ordinary input.
+ fn expire_unanswered_host_queries(&mut self) {
+ if self.awaiting_host_reply() || self.host_reply_activity_at.is_none() {
+ return;
+ }
+ // The Windows default color query keeps its own reply deadline.
+ #[cfg(windows)]
+ if self.host_default_color_query_deadline.is_some() {
+ return;
+ }
+ self.host_color_replies_awaited = 0;
+ self.host_cell_size_replies_awaited = 0;
+ self.host_appearance_reply_awaited = false;
+ self.held_pending_host_reply_esc = false;
+ self.host_reply_activity_at = None;
+ }
+
+ #[cfg(test)]
+ fn age_host_reply_activity(&mut self, by: Duration) {
+ self.host_reply_activity_at = self
+ .host_reply_activity_at
+ .and_then(|at| at.checked_sub(by));
}
#[cfg(any(unix, test))]
@@ -295,6 +353,7 @@ impl RawInputByteFramer {
self.host_appearance_query_on_focus = true;
}
+ #[cfg(any(unix, test))]
pub(crate) fn has_pending_input(&self) -> bool {
!self.buffer.is_empty()
}
@@ -304,6 +363,44 @@ impl RawInputByteFramer {
self.host_escape_disambiguation_active = active;
}
+ /// Pending bytes that could still be a key on their own: a lone ESC or ESC
+ /// plus one introducer. Legacy hosts send those for Escape and Alt+key, and
+ /// host text bindings (e.g. Ghostty `text:\x1bO`) send them even when the
+ /// host disambiguates escapes.
+ #[cfg(any(unix, test))]
+ fn pending_could_be_escape_key(&self) -> bool {
+ is_escape_key_prefix(&self.buffer)
+ }
+
+ /// How long to wait for more input before `flush_timeout`. Only bytes that
+ /// could still be a key get the short keyboard window; anything already
+ /// inside a sequence waits long enough for split reads over slow links.
+ #[cfg(any(unix, test))]
+ pub(crate) fn idle_flush_timeout_ms(&self, host_mouse_capture_active: bool) -> i32 {
+ if self.buffer.is_empty() {
+ return RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS;
+ }
+ // A reply Herdr asked for can split right after its introducer.
+ if self.awaiting_host_reply() && matches!(self.buffer.as_slice(), b"\x1b[" | b"\x1b]") {
+ return INCOMPLETE_SEQUENCE_FLUSH_TIMEOUT_MS;
+ }
+ if self.pending_could_be_escape_key() {
+ if !host_mouse_capture_active {
+ return RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS;
+ }
+ return match self.buffer.as_slice() {
+ [ESC] => MOUSE_ACTIVE_ESCAPE_SEQUENCE_FLUSH_TIMEOUT_MS,
+ // A mouse report split after ESC[ is still ambiguous with legacy Alt+[.
+ b"\x1b[" => MOUSE_ACTIVE_CSI_INTRODUCER_FLUSH_TIMEOUT_MS,
+ _ => RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS,
+ };
+ }
+ if self.buffer.first() == Some(&ESC) || starts_with_incomplete_utf8_char(&self.buffer) {
+ return INCOMPLETE_SEQUENCE_FLUSH_TIMEOUT_MS;
+ }
+ RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS
+ }
+
/// How long to keep holding input after a first idle flush held it.
#[cfg(unix)]
pub(crate) fn held_input_flush_timeout_ms(&self) -> i32 {
@@ -314,22 +411,6 @@ impl RawInputByteFramer {
}
}
- #[cfg(unix)]
- pub(crate) fn has_pending_lone_escape(&self) -> bool {
- self.buffer.as_slice() == [ESC]
- }
-
- #[cfg(unix)]
- pub(crate) fn has_pending_csi_introducer(&self) -> bool {
- self.buffer.as_slice() == b"\x1b["
- }
-
- #[cfg(unix)]
- pub(crate) fn has_pending_incomplete_mouse_sequence(&self) -> bool {
- starts_with_incomplete_sgr_mouse_sequence(&self.buffer)
- || starts_with_incomplete_default_mouse_sequence(&self.buffer)
- }
-
#[cfg(any(windows, test))]
pub(crate) fn has_pending_bracketed_paste(&self) -> bool {
self.buffer.starts_with(BRACKETED_PASTE_START)
@@ -338,6 +419,7 @@ impl RawInputByteFramer {
pub(crate) fn flush_timeout(&mut self) -> Vec<Vec<u8>> {
let mut chunks = self.drain_available_chunks();
+ self.expire_unanswered_host_queries();
#[cfg(windows)]
let host_color_query_expired = self
@@ -392,8 +474,11 @@ impl RawInputByteFramer {
#[cfg(not(unix))]
let mouse_wait_served = false;
#[cfg(unix)]
+ // Prefixes already inside a sequence waited the long window; only the
+ // ambiguous ESC / ESC[ prefixes need this extra mouse-tail hold.
if !mouse_wait_served
&& self.host_escape_disambiguation_active
+ && self.pending_could_be_escape_key()
&& could_continue_as_mouse_report(&self.buffer)
{
self.awaiting_mouse_tail_after = Some(self.buffer.len());
@@ -515,6 +600,15 @@ impl RawInputByteFramer {
return chunks;
}
+ // A legacy host sends Alt+[, Alt+O and Alt+Escape as ESC plus that byte. When nothing
+ // followed and no reply is expected, it was the key. String introducers
+ // (OSC, DCS, APC, PM, SOS) also start host replies, so they keep the
+ // control-string path and are never forwarded as Alt keys (#344).
+ if is_alt_key_introducer(&self.buffer) && !self.awaiting_host_reply() {
+ chunks.push(std::mem::take(&mut self.buffer));
+ return chunks;
+ }
+
if let Some(ControlString::Incomplete { family }) = control_string(&self.buffer) {
tracing::debug!(
len = self.buffer.len(),
@@ -715,6 +809,10 @@ impl RawInputByteFramer {
self.host_color_query_sent();
}
}
+ if is_host_reply_event(&event) && self.host_reply_activity_at.is_some() {
+ // Long reply bursts (256 palette entries) stay protected.
+ self.host_reply_activity_at = Some(Instant::now());
+ }
self.held_pending_host_reply_esc = false;
chunks.push(self.buffer[..consumed].to_vec());
self.buffer.drain(..consumed);
@@ -991,6 +1089,34 @@ fn starts_with_incomplete_host_cell_size_report(buffer: &[u8]) -> bool {
&& !(height.is_some_and(<[u8]>::is_empty) && width.is_some())
}
+fn is_host_reply_event(event: &RawInputEvent) -> bool {
+ matches!(
+ event,
+ RawInputEvent::HostDefaultColor { .. }
+ | RawInputEvent::HostPaletteColors { .. }
+ | RawInputEvent::HostCellSizeReport { .. }
+ | RawInputEvent::HostColorSchemeChanged(_)
+ )
+}
+
+/// ESC plus a byte that can also start a longer sequence: Alt+[, Alt+O, and
+/// Alt+Escape (ESC ESC, kept whole where doubled escapes are preserved).
+fn is_alt_key_introducer(buffer: &[u8]) -> bool {
+ matches!(buffer, [ESC, b'[' | b'O' | ESC])
+}
+
+#[cfg(any(unix, test))]
+fn is_escape_key_prefix(buffer: &[u8]) -> bool {
+ match buffer {
+ [ESC] => true,
+ [ESC, introducer] => matches!(
+ introducer,
+ b'[' | b'O' | b'P' | b']' | b'X' | b'^' | b'_' | 0x1b
+ ),
+ _ => false,
+ }
+}
+
fn control_string(buffer: &[u8]) -> Option<ControlString> {
let family = match buffer.get(..2)? {
b"\x1b]" => ControlStringFamily::Osc,
@@ -1121,6 +1247,7 @@ fn could_continue_as_mouse_report(buffer: &[u8]) -> bool {
}
#[cfg(any(unix, windows, test))]
+#[cfg(any(windows, test))]
fn starts_with_incomplete_default_mouse_sequence(buffer: &[u8]) -> bool {
buffer.starts_with(b"\x1b[M") && buffer.len() < 6
}
@@ -1318,36 +1445,66 @@ fn parse_default_mouse(sequence: &[u8]) -> Option<MouseEvent> {
}
fn parse_sgr_mouse(sequence: &str) -> Option<MouseEvent> {
- let body = sequence.strip_prefix("\x1b[<")?;
- let final_char = body.chars().last()?;
- if final_char != 'M' && final_char != 'm' {
- return None;
- }
+ let report = parse_sgr_mouse_report(sequence.as_bytes())?;
+ let column = u16::try_from(report.x.checked_sub(1)?).ok()?;
+ let row = u16::try_from(report.y.checked_sub(1)?).ok()?;
+ Some(report.at_cell(column, row))
+}
- let payload = &body[..body.len() - 1];
- let mut parts = payload.split(';');
- let cb = parts.next()?.parse::<u8>().ok()?;
- let column = parts.next()?.parse::<u16>().ok()?.checked_sub(1)?;
- let row = parts.next()?.parse::<u16>().ok()?.checked_sub(1)?;
- let (kind, modifiers) = parse_mouse_cb(cb)?;
+/// One SGR mouse report (`CSI < Cb ; x ; y M/m`) with its raw 1-based
+/// coordinates: cells normally, pixels when the host reports SGR pixels (1016).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct SgrMouseReport {
+ kind: MouseEventKind,
+ modifiers: KeyModifiers,
+ pub(crate) x: u32,
+ pub(crate) y: u32,
+}
- let kind = if final_char == 'm' {
- match kind {
- MouseEventKind::Down(button) => MouseEventKind::Up(button),
- other => other,
+impl SgrMouseReport {
+ /// The report as a mouse event at a 0-based cell.
+ pub(crate) fn at_cell(self, column: u16, row: u16) -> MouseEvent {
+ MouseEvent {
+ kind: self.kind,
+ column,
+ row,
+ modifiers: self.modifiers,
}
- } else {
- kind
- };
+ }
+}
- Some(MouseEvent {
+pub(crate) fn parse_sgr_mouse_report(sequence: &[u8]) -> Option<SgrMouseReport> {
+ let body = sequence.strip_prefix(b"\x1b[<")?;
+ let (&final_byte, payload) = body.split_last()?;
+ if final_byte != b'M' && final_byte != b'm' {
+ return None;
+ }
+ let mut parts = payload.split(|byte| *byte == b';');
+ let cb = u8::try_from(parse_report_number(parts.next()?)?).ok()?;
+ let x = parse_report_number(parts.next()?)?;
+ let y = parse_report_number(parts.next()?)?;
+ if parts.next().is_some() {
+ return None;
+ }
+ let (kind, modifiers) = parse_mouse_cb(cb)?;
+ let kind = match (final_byte, kind) {
+ (b'm', MouseEventKind::Down(button)) => MouseEventKind::Up(button),
+ (_, kind) => kind,
+ };
+ Some(SgrMouseReport {
kind,
- column,
- row,
modifiers,
+ x,
+ y,
})
}
+fn parse_report_number(value: &[u8]) -> Option<u32> {
+ (!value.is_empty() && value.iter().all(u8::is_ascii_digit))
+ .then(|| std::str::from_utf8(value).ok()?.parse().ok())
+ .flatten()
+}
+
fn parse_mouse_cb(cb: u8) -> Option<(MouseEventKind, KeyModifiers)> {
let button_number = (cb & 0b0000_0011) | ((cb & 0b1100_0000) >> 4);
let dragging = cb & 0b0010_0000 == 0b0010_0000;
@@ -1489,6 +1646,24 @@ mod tests {
assert!(!is_complete_text_bracketed_paste(b"\x1b[200~\xff\x1b[201~"));
}
+ #[test]
+ fn sgr_mouse_report_parser_accepts_only_complete_reports() {
+ for (input, expected) in [
+ (b"\x1b[<35;321;241M".as_slice(), Some((321, 241))),
+ (b"\x1b[<0;1;2m".as_slice(), Some((1, 2))),
+ (b"key".as_slice(), None),
+ (b"\x1b[<0;1;2Mkey".as_slice(), None),
+ (b"\x1b[<0;1M".as_slice(), None),
+ (b"\x1b[<0;1;2;3M".as_slice(), None),
+ ] {
+ assert_eq!(
+ parse_sgr_mouse_report(input).map(|report| (report.x, report.y)),
+ expected,
+ "{input:?}"
+ );
+ }
+ }
+
#[test]
fn parses_sgr_mouse() {
let (RawInputEvent::Mouse(mouse), consumed) = extract_one_event(b"\x1b[<0;20;10M").unwrap()
@@ -2662,6 +2837,48 @@ mod tests {
assert_eq!(framer.push(b"b"), vec![b"b".to_vec()]);
}
+ #[test]
+ fn preserved_doubled_escape_is_alt_escape_after_a_short_wait() {
+ // macOS keeps legacy ESC ESC whole: Alt+Escape (and Ctrl+Alt+3).
+ let mut framer = RawInputByteFramer::with_host_input_policy(true);
+ assert!(framer.push(b"\x1b\x1b").is_empty());
+ assert_eq!(
+ framer.idle_flush_timeout_ms(false),
+ RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS
+ );
+ let chunks = framer.flush_timeout();
+ assert_eq!(chunks, vec![b"\x1b\x1b".to_vec()]);
+ let events = events_from_framed_chunks(chunks);
+ assert!(
+ matches!(&events[..], [RawInputEvent::Key(key)]
+ if key.code == KeyCode::Esc && key.modifiers == KeyModifiers::ALT),
+ "{events:?}"
+ );
+ assert_eq!(framer.push(b"a"), vec![b"a".to_vec()]);
+ // A longer Alt sequence still joins up within the window.
+ assert!(framer.push(b"\x1b\x1b").is_empty());
+ assert_eq!(framer.push(b"[A"), vec![b"\x1b\x1b[A".to_vec()]);
+ }
+
+ #[test]
+ fn csi_and_ss3_introducers_without_expected_reply_are_alt_keys() {
+ for (bytes, code) in [
+ (&b"\x1b["[..], KeyCode::Char('[')),
+ (b"\x1bO", KeyCode::Char('O')),
+ ] {
+ let mut framer = RawInputFramer::default();
+ assert!(framer.push(bytes).is_empty());
+ let events = framer.flush_timeout();
+ assert!(
+ matches!(&events[..], [RawInputEvent::Key(key)]
+ if key.code == code && key.modifiers.contains(KeyModifiers::ALT)),
+ "{bytes:?}: {events:?}"
+ );
+ // The next keystroke is not swallowed as a sequence tail.
+ assert_eq!(framer.push(b"a").len(), 1, "{bytes:?}");
+ }
+ }
+
#[test]
fn parse_raw_input_bytes_sync_does_not_parse_incomplete_strings_as_alt_keys() {
for bytes in [
@@ -2903,6 +3120,43 @@ mod tests {
assert_eq!(alt_bracket.flush_timeout(), vec![b"\x1b[".to_vec()]);
}
+ #[test]
+ fn unanswered_host_query_stops_holding_alt_bracket() {
+ // Many hosts answer only part of the 256-entry palette query, or no
+ // cell size query at all. Once nothing arrives for a while, ESC[ is a
+ // key again: a short wait, released alone, next key not swallowed.
+ let mut framer = RawInputByteFramer::default();
+ framer.host_color_query_sent();
+ framer.host_cell_size_query_sent();
+ framer.age_host_reply_activity(HOST_REPLY_QUIET_WINDOW);
+
+ assert!(framer.push(b"\x1b[").is_empty());
+ assert_eq!(
+ framer.idle_flush_timeout_ms(false),
+ RAW_INPUT_IDLE_FLUSH_TIMEOUT_MS
+ );
+ assert_eq!(framer.flush_timeout(), vec![b"\x1b[".to_vec()]);
+ assert_eq!(framer.push(b"a"), vec![b"a".to_vec()]);
+ }
+
+ #[test]
+ fn host_reply_burst_keeps_split_protection_alive() {
+ let mut framer = RawInputByteFramer::default();
+ framer.host_color_query_sent();
+ framer.age_host_reply_activity(HOST_REPLY_QUIET_WINDOW);
+ // A reply arriving late still refreshes the window for the next one.
+ assert_eq!(
+ framer.push(b"\x1b]4;1;rgb:cd/00/00\x1b\\").len(),
+ 1,
+ "palette reply"
+ );
+ assert!(framer.push(b"\x1b]").is_empty());
+ assert_eq!(
+ framer.idle_flush_timeout_ms(false),
+ INCOMPLETE_SEQUENCE_FLUSH_TIMEOUT_MS
+ );
+ }
+
#[test]
fn malformed_host_reply_tail_preserves_following_input() {
let mut framer = RawInputByteFramer::default();
diff --git a/src/server/headless/render.rs b/src/server/headless/render.rs
index 5bc17c100..1283100f0 100644
--- a/src/server/headless/render.rs
+++ b/src/server/headless/render.rs
@@ -33,6 +33,43 @@ impl HeadlessServer {
.map(|runtime| (runtime, pane_id))
}
+ /// Whether a pane the client shows asked for SGR pixel mouse reports. Host
+ /// reports go to whichever pane is under the pointer, so an unfocused pane
+ /// needs pixels from the host too (#4750); others get them as cells.
+ fn shell_visible_pane_wants_sgr_pixels(&self, client_id: u64) -> bool {
+ if self
+ .shell_focused_runtime(client_id)
+ .is_some_and(|(runtime, _)| runtime.sgr_pixel_mouse_enabled())
+ {
+ return true;
+ }
+ let Some(target) = self.shell_target_for_client(client_id) else {
+ return false;
+ };
+ let Some(tab) = self
+ .app
+ .state
+ .workspaces
+ .get(target.workspace_index)
+ .and_then(|workspace| workspace.tabs.get(target.tab_index))
+ else {
+ return false;
+ };
+ if tab.zoomed {
+ return false;
+ }
+ tab.layout.pane_ids().into_iter().any(|pane_id| {
+ self.app
+ .state
+ .runtime_for_pane_in_workspace(
+ &self.app.terminal_runtimes,
+ target.workspace_index,
+ pane_id,
+ )
+ .is_some_and(crate::terminal::TerminalRuntime::sgr_pixel_mouse_enabled)
+ })
+ }
+
pub(super) fn stream_host_mouse_capture_mode(&mut self) {
let requested = self
.clients
@@ -46,7 +83,8 @@ impl HeadlessServer {
let child_requests_mouse =
focused.is_some_and(|(runtime, _)| runtime.mouse_reporting_enabled());
let sgr_pixels = client.pixel_mouse
- && focused.is_some_and(|(runtime, _)| runtime.sgr_pixel_mouse_enabled());
+ && client.shell_surface_active
+ && self.shell_visible_pane_wants_sgr_pixels(client_id);
Some((
client_id,
client.shell_surface_active
diff --git a/src/server/headless/tests/mod.rs b/src/server/headless/tests/mod.rs
index a9687e873..708400fb0 100644
--- a/src/server/headless/tests/mod.rs
+++ b/src/server/headless/tests/mod.rs
@@ -6037,6 +6037,75 @@ async fn client_shell_release_cleanup_does_not_promote_and_survives_disconnect()
shutdown_test_runtimes(&mut server);
}
+// Pixel mouse is a Unix client capability.
+#[cfg(unix)]
+#[tokio::test]
+async fn client_shell_requests_host_pixels_for_an_unfocused_pixel_pane() {
+ // #4750: host reports go to the pane under the pointer, focused or not.
+ let mut server = test_headless_server();
+ let mut workspace = crate::workspace::Workspace::test_new("pixel-split");
+ let first = workspace.tabs[0].root_pane;
+ let second = workspace.test_split(ratatui::layout::Direction::Horizontal);
+ let focused = workspace.focused_pane_id().expect("focused pane");
+ let unfocused = if focused == first { second } else { first };
+ workspace.insert_test_runtime(
+ focused,
+ crate::terminal::TerminalRuntime::test_with_screen_bytes(40, 23, b"plain"),
+ );
+ workspace.insert_test_runtime(
+ unfocused,
+ crate::terminal::TerminalRuntime::test_with_screen_bytes(
+ 40,
+ 23,
+ b"\x1b[?1003h\x1b[?1006h\x1b[?1016h",
+ ),
+ );
+ server.app.state.workspaces = vec![workspace];
+ server.app.state.active = Some(0);
+ server.app.state.selected = 0;
+ server.app.state.mode = crate::app::Mode::Terminal;
+ let (writer, control_rx, _render_rx) = test_client_writer();
+ assert!(
+ server.handle_server_event(ServerEvent::ClientShellConnected {
+ surface_reuse: false,
+ surface_delta: false,
+ surface_scroll: false,
+ client_id: 7,
+ surface_cols: 80,
+ surface_rows: 23,
+ cell_width_px: 10,
+ cell_height_px: 20,
+ pixel_mouse: true,
+ direct_graphics: false,
+ endpoint_keybindings: false,
+ mouse_capture: true,
+ surface_active: true,
+ writer,
+ })
+ );
+
+ // Control messages arrive asynchronously; wait for the mode instead of
+ // reading the channel once.
+ let mut mouse_modes = Vec::new();
+ for _ in 0..20 {
+ server.stream_host_mouse_capture_mode();
+ while let Ok(bytes) = control_rx.recv_timeout(Duration::from_millis(50)) {
+ if let ServerMessage::MouseCapture {
+ enabled,
+ sgr_pixels,
+ } = read_server_message(bytes)
+ {
+ mouse_modes.push((enabled, sgr_pixels));
+ }
+ }
+ if mouse_modes.last() == Some(&(true, true)) {
+ break;
+ }
+ }
+ assert_eq!(mouse_modes.last(), Some(&(true, true)), "{mouse_modes:?}");
+ shutdown_test_runtimes(&mut server);
+}
+
#[test]
fn client_shell_mouse_capture_combines_local_preference_with_endpoint_demand() {
let mut server = test_headless_server();
@@ -6222,11 +6291,12 @@ fn direct_terminal_streams_child_keyboard_and_mouse_modes() {
read_server_message(
client_control_rx
.recv_timeout(Duration::from_millis(100))
- .expect("modifyOtherKeys mode-one keyboard message")
+ .expect("kitty flags change with modifyOtherKeys mode one")
),
+ // Like Ghostty, modifyOtherKeys level 1 is not a negotiated mode.
ServerMessage::DirectTerminalKeyboardProtocol {
flags: 3,
- modify_other_keys_level: 1
+ modify_other_keys_level: 0
}
));
diff --git a/src/server/pane_input.rs b/src/server/pane_input.rs
index 4eb64cab7..7c656fccd 100644
--- a/src/server/pane_input.rs
+++ b/src/server/pane_input.rs
@@ -200,6 +200,14 @@ pub(super) fn apply_terminal_attach_input(
}
}
+#[cfg(test)]
+pub(crate) fn test_apply_client_pane_input_events(
+ runtime: &crate::terminal::TerminalRuntime,
+ events: &[ClientPaneInputEvent],
+) -> Result<(), String> {
+ apply_client_pane_input_events(runtime, events)
+}
+
pub(super) fn apply_client_pane_input_events(
runtime: &crate::terminal::TerminalRuntime,
events: &[ClientPaneInputEvent],