Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

fix: keep sgr pixel mouse units consistent (#4971)

akbash4d8a601a3cda
diff --git a/src/client/catalog_reload.rs b/src/client/catalog_reload.rs
index 89715f7d7..6f982c994 100644
--- a/src/client/catalog_reload.rs
+++ b/src/client/catalog_reload.rs
@@ -71,6 +71,7 @@ pub(super) fn apply_profiles(
}) {
catalog.select_local();
}
+ let pixel_mouse_available = state.pixel_mouse_available();
if let Some(shell) = state.shell.as_mut() {
shell.set_endpoint_catalog(&catalog.ssh);
if endpoints.active_surface_available()
@@ -84,7 +85,7 @@ pub(super) fn apply_profiles(
state.reported_size.1,
state.reported_cell_size.0,
state.reported_cell_size.1,
- state.pixel_geometry_exact,
+ pixel_mouse_available,
));
}
}
diff --git a/src/client/config_reload.rs b/src/client/config_reload.rs
index 418cab936..696158fc6 100644
--- a/src/client/config_reload.rs
+++ b/src/client/config_reload.rs
@@ -40,8 +40,7 @@ pub(super) fn apply_reload(
let sgr_pixels = effective_sgr_pixel_mouse(
enabled,
state.endpoint_sgr_pixels_requested,
- state.pixel_geometry_exact,
- state.host_sgr_pixel_mouse,
+ state.pixel_mouse_available(),
);
if enabled != state.mouse_capture_active
|| sgr_pixels != host_sgr_pixels_active.load(Ordering::Acquire)
@@ -52,6 +51,7 @@ pub(super) fn apply_reload(
host_mouse_capture_active.store(enabled, Ordering::Release);
host_sgr_pixels_active.store(sgr_pixels, Ordering::Release);
}
+ let pixel_mouse_available = state.pixel_mouse_available();
let (frame, resize) = if let Some(shell) = state.shell.as_mut() {
let previous_size = shell.surface_size(state.reported_size.0, state.reported_size.1);
shell.reload_client_config();
@@ -64,7 +64,7 @@ pub(super) fn apply_reload(
state.reported_size.1,
state.reported_cell_size.0,
state.reported_cell_size.1,
- state.pixel_geometry_exact,
+ pixel_mouse_available,
)
});
(
diff --git a/src/client/endpoint/supervisor.rs b/src/client/endpoint/supervisor.rs
index 5b4e7ad15..efad076ba 100644
--- a/src/client/endpoint/supervisor.rs
+++ b/src/client/endpoint/supervisor.rs
@@ -20,6 +20,7 @@ pub(crate) struct EndpointConnectOptions {
pub(crate) cell_width_px: u32,
pub(crate) cell_height_px: u32,
pub(crate) pixel_geometry_exact: bool,
+ pub(crate) pixel_mouse: bool,
pub(crate) surface_size: ClientSurfaceSize,
pub(crate) endpoint_keybindings: bool,
pub(crate) mouse_capture: bool,
@@ -298,7 +299,10 @@ fn connect_once(
options.rows,
options.cell_width_px,
options.cell_height_px,
- options.pixel_geometry_exact,
+ super::super::HandshakePixelCapabilities {
+ exact_geometry: options.pixel_geometry_exact,
+ sgr_mouse: options.pixel_mouse,
+ },
Some(options.surface_size),
options.endpoint_keybindings,
options.mouse_capture,
diff --git a/src/client/handshake.rs b/src/client/handshake.rs
index 2520286cd..75241ad17 100644
--- a/src/client/handshake.rs
+++ b/src/client/handshake.rs
@@ -144,7 +144,10 @@ pub(crate) fn probe_endpoint_negotiation(
24,
0,
0,
- false,
+ HandshakePixelCapabilities {
+ exact_geometry: false,
+ sgr_mouse: false,
+ },
Some(crate::protocol::ClientSurfaceSize { cols: 80, rows: 24 }),
false,
false,
@@ -158,6 +161,11 @@ pub(crate) fn probe_endpoint_negotiation(
))
}
+pub(super) struct HandshakePixelCapabilities {
+ pub(super) exact_geometry: bool,
+ pub(super) sgr_mouse: bool,
+}
+
/// Performs the client→server handshake.
///
/// Direct terminal clients retain the same-install private protocol. Client-owned
@@ -170,7 +178,7 @@ pub(super) fn do_handshake(
rows: u16,
cell_width_px: u32,
cell_height_px: u32,
- exact_cell_size: bool,
+ pixel_capabilities: HandshakePixelCapabilities,
shell_surface_size: Option<crate::protocol::ClientSurfaceSize>,
endpoint_keybindings: bool,
mouse_capture: bool,
@@ -188,10 +196,10 @@ pub(super) fn do_handshake(
cell_width_px,
cell_height_px,
surface_size,
- pixel_mouse: exact_cell_size && cfg!(unix),
+ pixel_mouse: pixel_capabilities.exact_geometry && pixel_capabilities.sgr_mouse,
direct_graphics: direct_graphics_capability(
local_transport,
- exact_cell_size,
+ pixel_capabilities.exact_geometry,
(cell_width_px, cell_height_px),
direct_graphics_profile_allowed(),
),
@@ -219,7 +227,7 @@ pub(super) fn do_handshake(
rows,
cell_width_px,
cell_height_px,
- pixel_mouse: exact_cell_size && cfg!(unix),
+ pixel_mouse: pixel_capabilities.exact_geometry && pixel_capabilities.sgr_mouse,
}
};
protocol::write_message(stream, &hello)
diff --git a/src/client/input.rs b/src/client/input.rs
index e2bd2b9d2..023596aa6 100644
--- a/src/client/input.rs
+++ b/src/client/input.rs
@@ -512,6 +512,12 @@ mod tests {
};
assert_eq!(data, report);
assert_eq!(captured, geometry);
+ let Some(ClientLoopEvent::StdinInput(cell_report)) =
+ classify_unix_input(report.clone(), false, Some(geometry))
+ else {
+ panic!("unconfirmed host pixel mode must keep cell reports on the raw path");
+ };
+ assert_eq!(cell_report, report);
assert!(classify_unix_input(report, true, None).is_none());
for raw in [
diff --git a/src/client/mod.rs b/src/client/mod.rs
index 1e77e7375..f55db195f 100644
--- a/src/client/mod.rs
+++ b/src/client/mod.rs
@@ -128,7 +128,10 @@ use frame_output::{
write_encoded_frame_with_graphics,
};
pub(crate) use handshake::probe_endpoint_negotiation;
-use handshake::{client_shell_keybinding_source, do_handshake, is_remote_client_process};
+use handshake::{
+ client_shell_keybinding_source, do_handshake, is_remote_client_process,
+ HandshakePixelCapabilities,
+};
#[cfg(test)]
use handshake::{
direct_graphics_profile_values, handshake_read_timeout, REMOTE_HANDSHAKE_READ_TIMEOUT,
@@ -252,10 +255,25 @@ fn run_client_with_mode(
}
};
- // Get the terminal geometry before handshake (before raw mode).
+ // Get one coherent geometry snapshot before raw mode changes the terminal.
let (cols, rows, cell_width_px, cell_height_px, exact_cell_size) =
initial_terminal_geometry(pixel_geometry_enabled, kitty_graphics_enabled)?;
+ let direct_attach = attach_escape.is_some();
+ let mut terminal_guard = if direct_attach {
+ setup_direct_attach_terminal(mouse_capture)
+ } else {
+ setup_terminal(mouse_capture)
+ }
+ .map_err(|err| {
+ eprintln!("herdr: failed to set up terminal: {err}");
+ err
+ })?;
+ 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();
+
let shell_surface_size = loop_config
.shell_config
.as_ref()
@@ -269,7 +287,10 @@ fn run_client_with_mode(
rows,
cell_width_px,
cell_height_px,
- exact_cell_size,
+ HandshakePixelCapabilities {
+ exact_geometry: exact_cell_size,
+ sgr_mouse: loop_config.host_sgr_pixel_mouse == Some(true),
+ },
shell_surface_size,
endpoint_keybindings,
loop_config.mouse_capture_active,
@@ -310,22 +331,6 @@ fn run_client_with_mode(
Err(error) => return Err(error),
};
- // The federated shell can show connection notices without any server snapshot.
- let direct_attach = attach_escape.is_some();
- let mut terminal_guard = if direct_attach {
- setup_direct_attach_terminal(mouse_capture)
- } else {
- setup_terminal(mouse_capture)
- }
- .map_err(|err| {
- eprintln!("herdr: failed to set up terminal: {err}");
- err
- })?;
- 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.
let panic_restore = terminal_guard.panic_restore();
let original_hook = std::panic::take_hook();
@@ -769,6 +774,7 @@ async fn run_client_loop(
cell_width_px: state.reported_cell_size.0,
cell_height_px: state.reported_cell_size.1,
pixel_geometry_exact: state.pixel_geometry_exact,
+ pixel_mouse: state.pixel_mouse_available(),
surface_size: shell.surface_size(state.reported_size.0, state.reported_size.1),
endpoint_keybindings: config.endpoint_keybindings,
mouse_capture: state.shell_mouse_capture_preference,
@@ -1251,7 +1257,9 @@ async fn run_client_loop(
host_theme_query_pending.fetch_add(1, Ordering::AcqRel);
query_host_terminal_theme();
}
- if !pixel_geometry_exact && host_sgr_pixels_active.load(Ordering::Acquire) {
+ let pixel_mouse_available =
+ pixel_geometry_exact && state.host_sgr_pixel_mouse == Some(true);
+ if !pixel_mouse_available && host_sgr_pixels_active.load(Ordering::Acquire) {
set_mouse_capture(state.mouse_capture_active, false)
.map_err(ClientError::ConnectionFailed)?;
host_sgr_pixels_active.store(false, Ordering::Release);
@@ -1285,7 +1293,7 @@ async fn run_client_loop(
new_rows,
cell_width_px,
cell_height_px,
- pixel_geometry_exact,
+ pixel_mouse_available,
)
} else {
ClientMessage::Resize {
@@ -1293,7 +1301,7 @@ async fn run_client_loop(
rows: new_rows,
cell_width_px,
cell_height_px,
- pixel_mouse: pixel_geometry_exact,
+ pixel_mouse: pixel_mouse_available,
}
};
if let Some(activation) = pending_activation.as_mut() {
@@ -2015,8 +2023,7 @@ async fn run_client_loop(
let next_sgr_pixels = effective_sgr_pixel_mouse(
enabled,
sgr_pixels,
- state.pixel_geometry_exact,
- state.host_sgr_pixel_mouse,
+ state.pixel_mouse_available(),
);
let mouse_mode_changed = enabled != state.mouse_capture_active
|| next_sgr_pixels != host_sgr_pixels_active.load(Ordering::Acquire);
diff --git a/src/client/shell_runtime.rs b/src/client/shell_runtime.rs
index 42e6ebee7..66a418642 100644
--- a/src/client/shell_runtime.rs
+++ b/src/client/shell_runtime.rs
@@ -126,12 +126,8 @@ 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,
- state.host_sgr_pixel_mouse,
- );
+ let sgr_pixels =
+ super::effective_sgr_pixel_mouse(enabled, false, state.pixel_mouse_available());
if enabled != state.mouse_capture_active
|| sgr_pixels != host_sgr_pixels_active.load(std::sync::atomic::Ordering::Acquire)
{
@@ -312,7 +308,7 @@ pub(super) fn begin_endpoint_activation(
state.reported_size.1,
state.reported_cell_size.0,
state.reported_cell_size.1,
- state.pixel_geometry_exact,
+ state.pixel_mouse_available(),
);
match endpoint::PendingEndpointActivation::prepare(
shell,
@@ -644,6 +640,7 @@ pub(super) fn install_client_shell_snapshot(
let generation = connection.generation;
let project_snapshot =
!projection_pending && endpoints.active_id() == endpoint_id && connection.surface_active;
+ let pixel_mouse_available = state.pixel_mouse_available();
let (composed, resize, graphics_cleanup) = if let Some(shell) = &mut state.shell {
let waits_for_selected_surface = projection_pending
|| (endpoints.active_id() == endpoint_id
@@ -673,7 +670,7 @@ pub(super) fn install_client_shell_snapshot(
state.reported_size.1,
state.reported_cell_size.0,
state.reported_cell_size.1,
- state.pixel_geometry_exact,
+ pixel_mouse_available,
)
}),
graphics_cleanup,
@@ -719,7 +716,7 @@ pub(super) fn finish_client_shell_input(
state.reported_size.1,
state.reported_cell_size.0,
state.reported_cell_size.1,
- state.pixel_geometry_exact,
+ state.pixel_mouse_available(),
);
if let Some(activation) = pending_activation.as_mut() {
if let Err(error) = activation.update_resize(resize, endpoints) {
diff --git a/src/client/state.rs b/src/client/state.rs
index fb3322220..312c65cac 100644
--- a/src/client/state.rs
+++ b/src/client/state.rs
@@ -96,6 +96,10 @@ impl Drop for ClientState {
}
impl ClientState {
+ pub(super) fn pixel_mouse_available(&self) -> bool {
+ self.pixel_geometry_exact && self.host_sgr_pixel_mouse == Some(true)
+ }
+
#[cfg(test)]
pub(super) fn test_new() -> Self {
Self {
diff --git a/src/client/terminal_sessions.rs b/src/client/terminal_sessions.rs
index aeecbf47e..2cc7784b1 100644
--- a/src/client/terminal_sessions.rs
+++ b/src/client/terminal_sessions.rs
@@ -12,7 +12,7 @@ use crate::protocol::{
};
use crate::server::socket_paths::client_socket_path;
-use super::{do_handshake, init_logging, write_to_server, ClientError};
+use super::{do_handshake, init_logging, write_to_server, ClientError, HandshakePixelCapabilities};
/// Runs a read-only terminal session observer and prints one JSON envelope per frame.
pub fn run_terminal_session_observe(target: String, cols: u16, rows: u16) -> io::Result<()> {
@@ -95,7 +95,10 @@ fn connect_terminal_session_stream(
rows,
0,
0,
- false,
+ HandshakePixelCapabilities {
+ exact_geometry: false,
+ sgr_mouse: false,
+ },
None,
false,
false,
diff --git a/src/client/terminal_setup.rs b/src/client/terminal_setup.rs
index 3a692a847..8a0a45eb8 100644
--- a/src/client/terminal_setup.rs
+++ b/src/client/terminal_setup.rs
@@ -77,7 +77,7 @@ pub(super) fn setup_terminal_with_capabilities(
let (host_probe, buffered_host_input) = if enable_client_protocols {
terminal_guard.reset_keyboard_enhancements = true;
push_keyboard_enhancement_flags()?;
- let (probe, buffered_input) = query_host_escape_disambiguation();
+ let (probe, buffered_input) = query_host_capabilities(true);
set_mouse_capture(mouse_capture, false)?;
execute!(io::stdout(), EnableBracketedPaste, EnableFocusChange)?;
if host_color_scheme_reports {
@@ -89,9 +89,10 @@ pub(super) fn setup_terminal_with_capabilities(
if should_enable_host_color_scheme_reports(true) {
write_host_color_scheme_report_mode(&mut io::stdout(), false)?;
}
+ let (probe, buffered_input) = query_host_capabilities(false);
set_mouse_capture(mouse_capture, false)?;
execute!(io::stdout(), EnableBracketedPaste)?;
- (HostTerminalProbe::default(), Vec::new())
+ (probe, buffered_input)
};
#[cfg(windows)]
@@ -149,7 +150,7 @@ pub(super) struct TerminalGuard {
}
#[cfg(not(windows))]
-const HOST_KEYBOARD_QUERY_TIMEOUT: Duration = Duration::from_millis(250);
+const HOST_CAPABILITY_QUERY_TIMEOUT: Duration = Duration::from_millis(250);
#[cfg(not(windows))]
const MAX_BUFFERED_HOST_INPUT: usize = 64 * 1024;
@@ -157,9 +158,7 @@ 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>,
+ sgr_pixel_mouse_status: Option<u8>,
primary_device_attributes: bool,
}
@@ -167,27 +166,33 @@ struct HostKeyboardProbeResponses {
#[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.
+ /// None when the host did not answer; exact pixel input stays disabled.
pub(super) sgr_pixel_mouse: Option<bool>,
}
#[cfg(not(windows))]
-fn query_host_escape_disambiguation() -> (HostTerminalProbe, Vec<u8>) {
- const QUERY: &[u8] = b"\x1b[?u\x1b[?1016$p\x1b[c";
+fn query_host_capabilities(query_keyboard: bool) -> (HostTerminalProbe, Vec<u8>) {
+ const FULL_QUERY: &[u8] = b"\x1b[?1016$p\x1b[?u\x1b[c";
+ const PIXEL_MOUSE_QUERY: &[u8] = b"\x1b[?1016$p\x1b[c";
let mut buffered_input = Vec::new();
+ let query = if query_keyboard {
+ FULL_QUERY
+ } else {
+ PIXEL_MOUSE_QUERY
+ };
if let Err(err) = io::stdout()
- .write_all(QUERY)
+ .write_all(query)
.and_then(|()| io::stdout().flush())
{
- tracing::debug!(%err, "host keyboard enhancement query unavailable");
+ tracing::debug!(%err, "host capability query unavailable");
return (HostTerminalProbe::default(), buffered_input);
}
// Bypass StdinLock's shared buffer so poll and read observe the same bytes.
let stdin = io::stdin();
let stdin_fd = stdin.as_raw_fd();
- let deadline = Instant::now() + HOST_KEYBOARD_QUERY_TIMEOUT;
+ let deadline = Instant::now() + HOST_CAPABILITY_QUERY_TIMEOUT;
let mut responses = HostKeyboardProbeResponses::default();
while !responses.primary_device_attributes && buffered_input.len() < MAX_BUFFERED_HOST_INPUT {
let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
@@ -226,10 +231,21 @@ fn query_host_escape_disambiguation() -> (HostTerminalProbe, Vec<u8>) {
#[cfg(not(windows))]
fn host_terminal_probe(responses: &HostKeyboardProbeResponses) -> HostTerminalProbe {
+ let sgr_pixel_mouse = match responses.sgr_pixel_mouse_status {
+ // The query follows an explicit reset, so a host still reporting SET may
+ // send pixels where Herdr expects cells. Wrong mouse units beat refusing
+ // to start, so keep pixel mouse off and continue.
+ Some(status @ (1 | 3)) => {
+ tracing::warn!(status, "host SGR pixel mouse mode stays set after reset");
+ Some(false)
+ }
+ Some(2) => Some(true),
+ Some(0 | 4) => Some(false),
+ _ => None,
+ };
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,
+ sgr_pixel_mouse,
}
}
@@ -285,19 +301,14 @@ 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).
+ // DECRPM: CSI ? 1016 ; Ps $ y.
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));
+ if let Some(status) = parse_sgr_pixel_mouse_status(body) {
+ responses.sgr_pixel_mouse_status = Some(status);
buffered_input.drain(start..=end + 1);
continue;
}
@@ -335,6 +346,14 @@ fn consume_host_keyboard_probe_responses(
}
}
+#[cfg(not(windows))]
+fn parse_sgr_pixel_mouse_status(body: &[u8]) -> Option<u8> {
+ let mut fields = body.split(|byte| *byte == b';');
+ (fields.next()? == b"1016").then_some(())?;
+ let status = std::str::from_utf8(fields.next()?).ok()?.parse().ok()?;
+ (fields.next().is_none() && status <= 4).then_some(status)
+}
+
#[cfg(not(windows))]
fn host_control_string_end(bytes: &[u8]) -> Option<Option<usize>> {
if bytes.first() != Some(&0x1b) {
@@ -364,7 +383,7 @@ fn host_control_string_end(bytes: &[u8]) -> Option<Option<usize>> {
}
#[cfg(windows)]
-fn query_host_escape_disambiguation() -> (HostTerminalProbe, Vec<u8>) {
+fn query_host_capabilities(_query_keyboard: bool) -> (HostTerminalProbe, Vec<u8>) {
(HostTerminalProbe::default(), Vec::new())
}
@@ -563,16 +582,12 @@ 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>,
+ pixel_mouse_available: bool,
) -> bool {
- enabled && requested && exact_geometry && host_support != Some(false)
+ enabled && requested && pixel_mouse_available
}
#[cfg(any(windows, test))]
@@ -1092,8 +1107,8 @@ mod tests {
#[cfg(not(windows))]
#[test]
- fn host_keyboard_probe_consumes_fragmented_responses_and_preserves_input() {
- let stream = b"before\x1b[?7u-middle-\x1b[?1;2cafter";
+ fn host_capability_probe_consumes_fragmented_responses_and_preserves_input() {
+ let stream = b"before\x1b[?1016;2$y-middle-\x1b[?7u-\x1b[?1;2cafter";
for split in 1..stream.len() {
let mut buffered = Vec::new();
@@ -1103,37 +1118,28 @@ mod tests {
buffered.extend_from_slice(&stream[split..]);
consume_host_keyboard_probe_responses(&mut buffered, &mut responses);
+ assert_eq!(responses.sgr_pixel_mouse_status, Some(2), "split {split}");
assert_eq!(responses.flags, Some(7), "split {split}");
assert!(responses.primary_device_attributes, "split {split}");
- assert_eq!(buffered, b"before-middle-after", "split {split}");
+ assert_eq!(buffered, b"before-middle--after", "split {split}");
}
}
#[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}");
- }
+ fn host_capability_probe_accepts_only_usable_sgr_pixel_mouse_states() {
+ for status in 0..=4 {
+ let mut buffered = format!("\x1b[?1016;{status}$y").into_bytes();
+ let mut responses = HostKeyboardProbeResponses::default();
+
+ consume_host_keyboard_probe_responses(&mut buffered, &mut responses);
+
+ assert_eq!(
+ host_terminal_probe(&responses).sgr_pixel_mouse,
+ Some(status == 2),
+ "status {status}"
+ );
+ assert!(buffered.is_empty());
}
}
@@ -1151,12 +1157,13 @@ mod tests {
#[cfg(not(windows))]
#[test]
fn host_keyboard_probe_preserves_typed_input_before_responses() {
- let mut buffered = b"aPtyped\x1b[?7u\x1b[?1;2c".to_vec();
+ let mut buffered = b"aPtyped\x1b[?1016;2$y\x1b[?7u\x1b[?1;2c".to_vec();
let mut responses = HostKeyboardProbeResponses::default();
consume_host_keyboard_probe_responses(&mut buffered, &mut responses);
assert!(host_escape_disambiguation_confirmed(&responses));
+ assert_eq!(host_terminal_probe(&responses).sgr_pixel_mouse, Some(true));
assert_eq!(buffered, b"aPtyped");
}
@@ -1190,27 +1197,33 @@ mod tests {
#[cfg(not(windows))]
#[test]
fn host_keyboard_probe_preserves_response_shaped_payloads() {
- let opaque = b"\x1b[200~paste \x1b[?1u \x1b[?1;2c\x1b[201~-\x1bPdata \x1b[?7u\x1b\\";
- let mut buffered = [opaque.as_slice(), b"\x1b[?7u\x1b[?1;2c"].concat();
+ let opaque =
+ b"\x1b[200~paste \x1b[?1016;2$y \x1b[?1u \x1b[?1;2c\x1b[201~-\x1bPdata \x1b[?7u\x1b\\";
+ let mut buffered = [opaque.as_slice(), b"\x1b[?1016;2$y\x1b[?7u\x1b[?1;2c"].concat();
let mut responses = HostKeyboardProbeResponses::default();
consume_host_keyboard_probe_responses(&mut buffered, &mut responses);
assert!(host_escape_disambiguation_confirmed(&responses));
+ assert_eq!(host_terminal_probe(&responses).sgr_pixel_mouse, Some(true));
assert_eq!(buffered, opaque);
}
#[cfg(not(windows))]
#[test]
fn host_keyboard_probe_preserves_malformed_responses() {
- let mut buffered = b"a\x1b[?7;1ub\x1b[?65536uc".to_vec();
+ let mut buffered = b"a\x1b[?7;1ub\x1b[?65536uc\x1b[?1016;5$y\x1b[?1006;2$y".to_vec();
let mut responses = HostKeyboardProbeResponses::default();
consume_host_keyboard_probe_responses(&mut buffered, &mut responses);
assert_eq!(responses.flags, None);
+ assert_eq!(responses.sgr_pixel_mouse_status, None);
assert!(!responses.primary_device_attributes);
- assert_eq!(buffered, b"a\x1b[?7;1ub\x1b[?65536uc");
+ assert_eq!(
+ buffered,
+ b"a\x1b[?7;1ub\x1b[?65536uc\x1b[?1016;5$y\x1b[?1006;2$y"
+ );
}
#[test]
diff --git a/src/client/tests/mod.rs b/src/client/tests/mod.rs
index 2d3f022a3..323af2f87 100644
--- a/src/client/tests/mod.rs
+++ b/src/client/tests/mod.rs
@@ -499,11 +499,8 @@ 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, 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)));
+ assert!(effective_sgr_pixel_mouse(true, true, true));
+ assert!(!effective_sgr_pixel_mouse(true, true, false));
}
#[test]
diff --git a/src/pane/input.rs b/src/pane/input.rs
index 13cc67701..87c1c6f6f 100644
--- a/src/pane/input.rs
+++ b/src/pane/input.rs
@@ -214,7 +214,7 @@ pub(super) fn ghostty_mods_from_key_modifiers(modifiers: crossterm::event::KeyMo
pub(super) fn ghostty_mouse_encoder_for_terminal(
terminal: &crate::ghostty::Terminal,
position: crate::input::mouse::Position,
-) -> Option<crate::ghostty::MouseEncoder> {
+) -> Option<(crate::ghostty::MouseEncoder, (f32, f32))> {
let mut encoder = crate::ghostty::MouseEncoder::new().ok()?;
encoder.set_from_terminal(terminal);
let cols = terminal.cols().ok()? as u32;
@@ -222,35 +222,46 @@ pub(super) fn ghostty_mouse_encoder_for_terminal(
let sgr_pixels = terminal
.mode_get(crate::ghostty::MODE_MOUSE_SGR_PIXELS)
.ok()?;
- match position {
- crate::input::mouse::Position::Cell { .. } => {
- if sgr_pixels {
- encoder.set_format(crate::ghostty::MOUSE_FORMAT_SGR);
+ let event_position = match position {
+ crate::input::mouse::Position::Cell { column, row } if sgr_pixels => {
+ let width_px = terminal.width_px().ok()?;
+ let height_px = terminal.height_px().ok()?;
+ let x = cell_center_px(u32::from(column), cols, width_px)?;
+ let y = cell_center_px(u32::from(row), rows, height_px)?;
+ encoder.set_format(crate::ghostty::MOUSE_FORMAT_SGR_PIXELS);
+ encoder.set_size(width_px, height_px, width_px / cols, height_px / rows);
+ (x as f32, y as f32)
+ }
+ crate::input::mouse::Position::Cell { column, row } => {
+ if cols == 0 || rows == 0 {
+ return None;
}
encoder.set_size(cols, rows, 1, 1);
+ (f32::from(column), f32::from(row))
}
- crate::input::mouse::Position::Pixels { .. } => {
- if sgr_pixels {
- encoder.set_format(crate::ghostty::MOUSE_FORMAT_SGR_PIXELS);
- }
+ crate::input::mouse::Position::Pixels { x, y } => {
let width_px = terminal.width_px().ok()?;
let height_px = terminal.height_px().ok()?;
if width_px == 0 || height_px == 0 || cols == 0 || rows == 0 {
return None;
}
+ if sgr_pixels {
+ encoder.set_format(crate::ghostty::MOUSE_FORMAT_SGR_PIXELS);
+ }
encoder.set_size(width_px, height_px, width_px / cols, height_px / rows);
+ (x as f32, y as f32)
}
- }
- Some(encoder)
+ };
+ Some((encoder, event_position))
}
-pub(super) fn ghostty_mouse_position_for_terminal(
- position: crate::input::mouse::Position,
-) -> Option<(f32, f32)> {
- match position {
- crate::input::mouse::Position::Pixels { x, y } => Some((x as f32, y as f32)),
- crate::input::mouse::Position::Cell { column, row } => Some((column as f32, row as f32)),
+fn cell_center_px(index: u32, count: u32, extent: u32) -> Option<u32> {
+ if count == 0 || extent == 0 || index >= count {
+ return None;
}
+ let start = u64::from(index) * u64::from(extent) / u64::from(count);
+ let end = u64::from(index + 1) * u64::from(extent) / u64::from(count);
+ u32::try_from(start + end.saturating_sub(start) / 2).ok()
}
pub(super) fn ghostty_mouse_event_from_button_kind(
diff --git a/src/pane/terminal.rs b/src/pane/terminal.rs
index 44d321147..d4b7ef575 100644
--- a/src/pane/terminal.rs
+++ b/src/pane/terminal.rs
@@ -28,7 +28,7 @@ use super::{
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,
+ legacy_shell_key, legacy_super_chord,
},
kitty_keyboard::KittyKeyboardTracker,
osc::{
@@ -2135,8 +2135,7 @@ impl GhosttyPaneTerminal {
if require_any_motion && !core.terminal.mode_get(MODE_MOUSE_ANY_MOTION).ok()? {
return None;
}
- let mut encoder = ghostty_mouse_encoder_for_terminal(&core.terminal, position)?;
- let (x, y) = ghostty_mouse_position_for_terminal(position)?;
+ let (mut encoder, (x, y)) = ghostty_mouse_encoder_for_terminal(&core.terminal, position)?;
event.set_position(x, y);
encoder
.encode(&event)
@@ -5611,7 +5610,7 @@ mod tests {
}
#[test]
- fn ghostty_mouse_sgr_pixels_preserves_exact_and_downgrades_cell_input() {
+ fn ghostty_mouse_sgr_pixels_preserves_exact_and_scales_cell_input() {
let (tx, _rx) = mpsc::channel(4);
let mut terminal = crate::ghostty::Terminal::new(80, 24, 0).unwrap();
terminal.resize(80, 24, 10, 20).unwrap();
@@ -5630,7 +5629,7 @@ mod tests {
);
assert_eq!(exact.as_deref(), Some(&b"\x1b[<35;48;139M"[..]));
- assert_eq!(fallback.as_deref(), Some(&b"\x1b[<35;5;7M"[..]));
+ assert_eq!(fallback.as_deref(), Some(&b"\x1b[<35;45;130M"[..]));
}
#[test]
diff --git a/src/server/headless/tests/mod.rs b/src/server/headless/tests/mod.rs
index 03da0108b..3ab7ec0fd 100644
--- a/src/server/headless/tests/mod.rs
+++ b/src/server/headless/tests/mod.rs
@@ -5489,6 +5489,43 @@ fn client_pane_pixel_mouse_uses_runtime_pixel_encoding() {
rt.shutdown_timeout(Duration::from_millis(100));
}
+#[test]
+fn client_pane_cell_mouse_uses_pixel_units_when_sgr_pixels_is_set() {
+ let rt = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("test runtime");
+ let _runtime_guard = rt.enter();
+ let (runtime, mut input_rx) =
+ crate::terminal::TerminalRuntime::test_with_channel_and_scrollback_bytes(
+ 20,
+ 5,
+ 0,
+ b"\x1b[?1003h\x1b[?1006h\x1b[?1016h",
+ 4,
+ );
+ runtime.resize(5, 20, 10, 20);
+
+ apply_client_pane_input_events(
+ &runtime,
+ &[crate::protocol::ClientPaneInputEvent::Mouse {
+ kind: crate::protocol::ClientMouseKind::Moved,
+ position: crate::protocol::ClientMousePosition::Cell { column: 2, row: 1 },
+ geometry: None,
+ modifiers: 0,
+ lines: 3,
+ }],
+ )
+ .expect("cell-aligned pixel mouse input");
+ assert_eq!(
+ input_rx.try_recv().expect("encoded pixel-unit mouse"),
+ Bytes::from_static(b"\x1b[<35;25;30M")
+ );
+ drop(runtime);
+ drop(_runtime_guard);
+ rt.shutdown_timeout(Duration::from_millis(100));
+}
+
#[test]
fn client_pane_pixel_mouse_stays_pixel_scaled_when_sgr_is_reasserted() {
let rt = tokio::runtime::Builder::new_current_thread()
diff --git a/src/server/headless/tests/pane_graphics.rs b/src/server/headless/tests/pane_graphics.rs
index 70904fd5e..03386aedf 100644
--- a/src/server/headless/tests/pane_graphics.rs
+++ b/src/server/headless/tests/pane_graphics.rs
@@ -620,3 +620,24 @@ async fn pixel_mouse_activation_follows_child_1016_without_graphics_demand() {
}
));
}
+
+#[tokio::test]
+async fn mouse_capture_stays_cell_based_without_host_pixel_capability() {
+ let (mut server, _client_rx, _pane_id) =
+ retained_test_server(b"\x1b[?1003h\x1b[?1006h\x1b[?1016h");
+ let (writer, control_rx, _render_rx) = test_client_writer();
+ let client = server.clients.get_mut(&1).unwrap();
+ client.writer = Some(writer);
+ client.pixel_mouse = false;
+ client.host_mouse_capture_active = None;
+ client.host_sgr_pixels_active = None;
+
+ server.stream_host_mouse_capture_mode();
+ assert!(matches!(
+ read_server_message(control_rx.recv_timeout(Duration::from_millis(100)).unwrap()),
+ ServerMessage::MouseCapture {
+ enabled: true,
+ sgr_pixels: false
+ }
+ ));
+}