Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(platform-linux): deliver libei pointer input to secondary monitors (#5853)

injaneity1e0da1a9649e
diff --git a/.github/workflows/ci-rust-linux.yml b/.github/workflows/ci-rust-linux.yml
index 663cf2905e..bacde19c51 100644
--- a/.github/workflows/ci-rust-linux.yml
+++ b/.github/workflows/ci-rust-linux.yml
@@ -167,6 +167,9 @@ jobs:
env:
CUA_TEST_REQUIRE_DRIVER_BIN: "1"
run: cargo test -p cua-driver -p cua-driver-e2e -p cua-driver-contract -p cua-driver-core -p cua-driver-testkit -p cursor-overlay -p cursor-theme-cli -p platform-linux --all-targets --locked
+ - name: Run Wayland libei tests (portal-input)
+ working-directory: libs/cua-driver/rust
+ run: cargo test --locked -p platform-linux --features portal-input --lib
- name: Run cua-cursor-motion tests (lab parity, golden trajectories)
working-directory: libs/cua-driver/rust
run: cargo test -p cua-cursor-motion --all-features --all-targets --locked
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs
index 4ab3a74517..6f9985d26f 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs
@@ -24,11 +24,12 @@
//! `~/.config/cua-driver/libei-persistent.token` and reused across daemon
//! restarts.
//!
-//! Coordinates: ei_pointer_absolute uses LOGICAL PIXELS inside an
-//! announced ei_device.Region — collected between device creation and
-//! the first device.Done event. Multi-monitor: pick the region
-//! containing the target (x, y).
+//! Coordinates: ei_pointer_absolute takes desktop-layout positions that must
+//! lie inside an announced ei_device.Region — collected between device creation
+//! and the first device.Done event. Multi-monitor: the region containing the
+//! target (x, y) selects the device; the point is sent unchanged.
+use super::region_route::{route_absolute, RegionRect};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::OnceLock;
@@ -656,29 +657,6 @@ struct SeatData {
capabilities: HashMap<String, u64>,
}
-/// One announced ei_device::Region — a single monitor's pixel rectangle
-/// inside the seat's logical coordinate space. Multi-monitor sessions
-/// announce one Region per output; we route each absolute (x, y) to the
-/// region containing it so the cursor lands on the correct monitor.
-#[derive(Clone, Copy, Debug)]
-struct RegionRect {
- offset_x: f32,
- offset_y: f32,
- width: f32,
- height: f32,
-}
-
-impl RegionRect {
- fn contains(&self, x: f64, y: f64) -> bool {
- let xf = x as f32;
- let yf = y as f32;
- xf >= self.offset_x
- && xf < self.offset_x + self.width
- && yf >= self.offset_y
- && yf < self.offset_y + self.height
- }
-}
-
#[derive(Default)]
struct DeviceData {
device_type: Option<reis::ei::device::DeviceType>,
@@ -1005,13 +983,13 @@ impl EisState {
})?;
}
Cmd::Click { x, y, button, .. } => {
- let (device, rel_x, rel_y) = self.pointer_device_for(*x, *y)?;
+ let device = self.pointer_device_for(*x, *y)?;
let serial = self.last_serial;
let ptr_abs =
require_device_interface::<reis::ei::PointerAbsolute>(&self.devices, &device)?;
let btn = require_device_interface::<reis::ei::Button>(&self.devices, &device)?;
- ptr_abs.motion_absolute(rel_x, rel_y);
+ ptr_abs.motion_absolute(*x as f32, *y as f32);
btn.button(button.to_evdev(), reis::ei::button::ButtonState::Press);
device.frame(serial, event_time_us());
btn.button(button.to_evdev(), reis::ei::button::ButtonState::Released);
@@ -1027,24 +1005,21 @@ impl EisState {
button,
..
} => {
- let (device, from_rx, from_ry) = self.pointer_device_for(*from_x, *from_y)?;
+ let device = self.pointer_device_for(*from_x, *from_y)?;
let serial = self.last_serial;
let ptr_abs =
require_device_interface::<reis::ei::PointerAbsolute>(&self.devices, &device)?;
let btn = require_device_interface::<reis::ei::Button>(&self.devices, &device)?;
- // Map the drag end into the SAME device's region (a single EIS
- // emulation session can't span devices). Fall back to the start
- // region's offset when no region of this device contains the end
- // (single-region device, or a point just off-screen) — this is
- // correct only within one region, but avoids the cross-monitor
- // mis-mapping of blindly reusing the start offset.
- let (to_rx, to_ry) =
- self.region_local_on(&device, *to_x, *to_y)
- .unwrap_or_else(|| {
- let off_x = *from_x as f32 - from_rx;
- let off_y = *from_y as f32 - from_ry;
- (*to_x as f32 - off_x, *to_y as f32 - off_y)
- });
+ // A single EIS emulation session can't span devices: the end
+ // must lie in a region of the device the start resolved to.
+ let regions = self
+ .devices
+ .get(&device)
+ .map(|d| d.regions.as_slice())
+ .unwrap_or_default();
+ route_absolute([((), regions)], *to_x, *to_y)?;
+ let (from_rx, from_ry) = (*from_x as f32, *from_y as f32);
+ let (to_rx, to_ry) = (*to_x as f32, *to_y as f32);
ptr_abs.motion_absolute(from_rx, from_ry);
device.frame(serial, event_time_us());
@@ -1075,12 +1050,12 @@ impl EisState {
device.frame(serial, event_time_us());
}
Cmd::MoveAbsolute { x, y, .. } => {
- let (device, rel_x, rel_y) = self.pointer_device_for(*x, *y)?;
+ let device = self.pointer_device_for(*x, *y)?;
let serial = self.last_serial;
let ptr_abs =
require_device_interface::<reis::ei::PointerAbsolute>(&self.devices, &device)?;
- ptr_abs.motion_absolute(rel_x, rel_y);
+ ptr_abs.motion_absolute(*x as f32, *y as f32);
device.frame(serial, event_time_us());
}
Cmd::Scroll { dx, dy, .. } => {
@@ -1195,55 +1170,29 @@ impl EisState {
Ok(())
}
- /// Pick a pointer device whose announced Region contains `(x, y)`,
- /// and translate the absolute screen coordinates into the device's
- /// region-local pixel coordinates.
- ///
- /// Multi-monitor seats announce one Region per output; routing each
- /// (x, y) by containment is what lets a click on monitor #2 actually
- /// land on monitor #2. When no device's region contains the point —
- /// e.g. coords just past the edge of an output, or a session with
- /// a single device that hasn't announced any regions yet — we fall
- /// back to the first pointer device with the raw coordinates, which
- /// matches the pre-multi-monitor behaviour.
- fn pointer_device_for(&self, x: f64, y: f64) -> anyhow::Result<(reis::ei::Device, f32, f32)> {
- // Absolute motion needs the device that actually carries
- // ei_pointer_absolute — Mutter/KWin split the relative and absolute
- // pointers onto separate devices, and only one of them accepts an
- // absolute warp.
- for (device, data) in self.devices.iter() {
- if !data.resumed || !data.interfaces.contains_key("ei_pointer_absolute") {
- continue;
- }
- for region in &data.regions {
- if region.contains(x, y) {
- let rel_x = x as f32 - region.offset_x;
- let rel_y = y as f32 - region.offset_y;
- return Ok((device.clone(), rel_x, rel_y));
- }
- }
+ /// Pick the absolute-pointer device whose announced Region contains
+ /// `(x, y)`. The region only selects the device: coordinates are
+ /// desktop-layout positions and are sent to EIS unchanged. When regions
+ /// were announced but none contains the point this is an error, since EIS
+ /// would silently drop the motion. Only when no region was announced at all
+ /// does it fall back to the first absolute-pointer device.
+ fn pointer_device_for(&self, x: f64, y: f64) -> anyhow::Result<reis::ei::Device> {
+ // Mutter/KWin split the relative and absolute pointers onto separate
+ // devices, and only the absolute one accepts an absolute warp.
+ let candidates = self
+ .devices
+ .iter()
+ .filter(|(_, data)| data.resumed && data.interfaces.contains_key("ei_pointer_absolute"))
+ .map(|(device, data)| (device, data.regions.as_slice()));
+ if let Some(device) = route_absolute(candidates, x, y)? {
+ return Ok(device.clone());
}
- // Fallback: first absolute-pointer device, raw coords (single-region).
- let device = self
- .device_with_interface("ei_pointer_absolute")
+ self.device_with_interface("ei_pointer_absolute")
.ok_or_else(|| {
anyhow::anyhow!(
"no EIS absolute-pointer device negotiated yet — wait for handshake"
)
- })?;
- Ok((device, x as f32, y as f32))
- }
-
- /// Region-local coordinates for absolute `(x, y)` within one of `device`'s
- /// announced regions, or `None` when no region of that device contains the
- /// point. Used to map a drag endpoint into the same device the drag start
- /// resolved to (a single EIS emulation session can't span devices).
- fn region_local_on(&self, device: &reis::ei::Device, x: f64, y: f64) -> Option<(f32, f32)> {
- let data = self.devices.get(device)?;
- data.regions
- .iter()
- .find(|r| r.contains(x, y))
- .map(|r| (x as f32 - r.offset_x, y as f32 - r.offset_y))
+ })
}
/// The negotiated device that exposes `iface` (e.g. `ei_pointer_absolute`,
@@ -1385,6 +1334,167 @@ fn drag_step_delay(duration_ms: u64, steps: u32) -> std::time::Duration {
)
}
+#[cfg(test)]
+pub(super) mod local_eis {
+ use super::*;
+ use reis::enumflags2::BitFlags;
+ use reis::handshake::EisHandshaker;
+ use reis::request::{DeviceCapability, EisRequest, EisRequestConverter};
+ use reis::PendingRequestResult;
+ use std::sync::{Arc, Mutex};
+
+ #[derive(Clone, Debug, PartialEq)]
+ pub(in crate::wayland) enum Emitted {
+ Motion(String, f32, f32),
+ Button(u32, bool),
+ Scroll(f32, f32),
+ }
+
+ const DEVICES: [(&str, &[u32]); 2] = [("wide", &[0, 3840]), ("far", &[10_000])];
+
+ type Log = Arc<Mutex<Vec<Emitted>>>;
+
+ struct Server {
+ ctx: reis::eis::Context,
+ handshaker: Option<EisHandshaker>,
+ converter: Option<EisRequestConverter>,
+ devices: Vec<reis::request::Device>,
+ log: Log,
+ }
+
+ impl Server {
+ fn pump(&mut self) {
+ if self.ctx.read().is_err() {
+ return;
+ }
+ while let Some(PendingRequestResult::Request(request)) = self.ctx.pending_request() {
+ if let Some(handshaker) = self.handshaker.as_mut() {
+ if let Some(resp) = handshaker.handle_request(request).unwrap() {
+ let converter = EisRequestConverter::new(&self.ctx, resp, 1);
+ let _ = converter.handle().add_seat(
+ Some("seat"),
+ DeviceCapability::PointerAbsolute
+ | DeviceCapability::Button
+ | DeviceCapability::Scroll,
+ );
+ self.converter = Some(converter);
+ self.handshaker = None;
+ }
+ continue;
+ }
+ let converter = self.converter.as_mut().unwrap();
+ converter.handle_request(request).unwrap();
+ let requests: Vec<_> = std::iter::from_fn(|| converter.next_request()).collect();
+ for request in requests {
+ self.record(request);
+ }
+ }
+ let _ = self.ctx.flush();
+ }
+
+ fn record(&mut self, request: EisRequest) {
+ let mut log = self.log.lock().unwrap();
+ match request {
+ EisRequest::Bind(bind) => {
+ for (name, offsets) in DEVICES {
+ let device = bind.seat.add_device(
+ Some(name),
+ reis::eis::device::DeviceType::Virtual,
+ BitFlags::from(DeviceCapability::PointerAbsolute)
+ | DeviceCapability::Button
+ | DeviceCapability::Scroll,
+ |device| {
+ for &x in offsets {
+ device.device().region(x, 0, 3840, 2160, 1.0);
+ }
+ },
+ );
+ device.resumed();
+ self.devices.push(device);
+ }
+ }
+ EisRequest::PointerMotionAbsolute(m) => log.push(Emitted::Motion(
+ m.device.name().unwrap_or_default().to_owned(),
+ m.dx_absolute,
+ m.dy_absolute,
+ )),
+ EisRequest::Button(b) => log.push(Emitted::Button(
+ b.button,
+ b.state == reis::eis::button::ButtonState::Press,
+ )),
+ EisRequest::ScrollDelta(s) => log.push(Emitted::Scroll(s.dx, s.dy)),
+ _ => {}
+ }
+ }
+ }
+
+ struct Fixture {
+ log: Log,
+ gate: Mutex<()>,
+ }
+
+ fn install() -> &'static Fixture {
+ use std::os::unix::net::UnixStream;
+ static FIXTURE: OnceLock<Fixture> = OnceLock::new();
+ FIXTURE.get_or_init(|| {
+ let log = Log::default();
+ let (tx, rx) = bounded::<Cmd>(64);
+ assert!(TX.set(tx).is_ok(), "real libei worker already started");
+ let (client_end, server_end) = UnixStream::pair().unwrap();
+ let mut client = reis::ei::Context::new(client_end).unwrap();
+ let ctx = reis::eis::Context::new(server_end).unwrap();
+ let handshaker = EisHandshaker::new(&ctx, 1);
+ let mut server = Server {
+ ctx,
+ handshaker: Some(handshaker),
+ converter: None,
+ devices: Vec::new(),
+ log: log.clone(),
+ };
+ thread::spawn(move || {
+ let mut state = EisState::default();
+ let _ = client.handshake();
+ let _ = client.flush();
+ loop {
+ server.pump();
+ let _ = state.handle_eis_readable(&mut client);
+ let resumed = state.devices.values().filter(|d| d.resumed).count();
+ if resumed == DEVICES.len() {
+ match rx.try_recv() {
+ Ok(Cmd::Shutdown)
+ | Err(crossbeam_channel::TryRecvError::Disconnected) => break,
+ Ok(cmd) => state.handle_command(cmd),
+ Err(_) => {}
+ }
+ }
+ state
+ .pending_sync
+ .retain(|_, (_, sent)| sent.elapsed().as_secs() < 5);
+ thread::sleep(std::time::Duration::from_millis(1));
+ }
+ });
+ Fixture {
+ log,
+ gate: Mutex::new(()),
+ }
+ })
+ }
+
+ /// Run `f` against a local EIS server and return what the server received
+ /// from it. A trailing barrier motion guarantees events from commands that
+ /// failed early are not still in flight when the log is read.
+ pub(in crate::wayland) fn record<R>(f: impl FnOnce() -> R) -> (R, Vec<Emitted>) {
+ let fixture = install();
+ let _gate = fixture.gate.lock().unwrap_or_else(|e| e.into_inner());
+ fixture.log.lock().unwrap().clear();
+ let result = f();
+ move_absolute(1.0, 1.0).unwrap();
+ let mut events = std::mem::take(&mut *fixture.log.lock().unwrap());
+ assert!(matches!(events.pop(), Some(Emitted::Motion(_, x, y)) if x == 1.0 && y == 1.0));
+ (result, events)
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1440,4 +1550,83 @@ mod tests {
]
);
}
+
+ use local_eis::{record, Emitted};
+
+ fn motion(device: &str, x: f32, y: f32) -> Emitted {
+ Emitted::Motion(device.into(), x, y)
+ }
+
+ const LEFT: u32 = 0x110;
+
+ #[test]
+ fn click_on_second_monitor_sends_layout_coordinate_unchanged() {
+ let (result, events) = record(|| click(6237.0, 1014.0, Button::Left));
+ result.unwrap();
+ assert_eq!(
+ events,
+ vec![
+ motion("wide", 6237.0, 1014.0),
+ Emitted::Button(LEFT, true),
+ Emitted::Button(LEFT, false),
+ ]
+ );
+ }
+
+ #[test]
+ fn click_routes_to_the_device_owning_the_region() {
+ let (result, events) = record(|| click(11_000.0, 50.0, Button::Left));
+ result.unwrap();
+ assert_eq!(events[0], motion("far", 11_000.0, 50.0));
+ }
+
+ #[test]
+ fn move_sends_layout_coordinate_unchanged_and_origin_literally() {
+ let (result, events) = record(|| move_absolute(6237.0, 1014.0));
+ result.unwrap();
+ assert_eq!(events, vec![motion("wide", 6237.0, 1014.0)]);
+
+ let (result, events) = record(|| move_absolute(0.0, 0.0));
+ result.unwrap();
+ assert_eq!(events, vec![motion("wide", 0.0, 0.0)]);
+ }
+
+ #[test]
+ fn drag_across_regions_of_one_device_holds_button_over_unchanged_endpoints() {
+ let (result, events) = record(|| drag(0.0, 0.0, 6237.0, 1014.0, 4, 0, Button::Left));
+ result.unwrap();
+ assert_eq!(events.first(), Some(&motion("wide", 0.0, 0.0)));
+ assert_eq!(events[1], Emitted::Button(LEFT, true));
+ assert_eq!(events[events.len() - 2], motion("wide", 6237.0, 1014.0));
+ assert_eq!(events.last(), Some(&Emitted::Button(LEFT, false)));
+ assert_eq!(events.len(), 2 + 1 + 4 + 1 - 1);
+ }
+
+ #[test]
+ fn drag_endpoint_outside_selected_device_fails_before_any_event() {
+ let (result, events) = record(|| drag(100.0, 100.0, 11_000.0, 100.0, 4, 0, Button::Left));
+ assert_eq!(
+ result.unwrap_err().to_string(),
+ "libei: (11000, 100) lies outside every announced pointer region"
+ );
+ assert_eq!(events, vec![]);
+ }
+
+ #[test]
+ fn pointer_commands_outside_every_region_fail_before_any_event() {
+ let (result, events) = record(|| {
+ (
+ click(8000.0, 100.0, Button::Left),
+ move_absolute(8000.0, 100.0),
+ drag(8000.0, 100.0, 100.0, 100.0, 4, 0, Button::Left),
+ )
+ });
+ for r in [result.0, result.1, result.2] {
+ assert_eq!(
+ r.unwrap_err().to_string(),
+ "libei: (8000, 100) lies outside every announced pointer region"
+ );
+ }
+ assert_eq!(events, vec![]);
+ }
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
index 069442d939..bf9989b4b4 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
@@ -21,6 +21,8 @@ pub mod persistent_vptr;
pub(crate) mod portal;
pub mod portal_screenshot;
mod primary_seat;
+#[cfg(any(feature = "portal-input", test))]
+mod region_route;
pub mod shell_helper;
pub mod sway_ipc;
mod virtual_keyboard;
@@ -1696,11 +1698,10 @@ pub fn with_target_foreground<T>(
)
}
-/// Query the first `wl_output`'s pixel dimensions via a short Wayland
-/// roundtrip, independent of the virtual-pointer protocol. Used by the libei
-/// fallback (which never opens a `VptrSession`) to reproduce the vptr path's
-/// default-to-centre and clamp behaviour so both backends treat coordinates
-/// identically. Falls back to `(1, 1)` when no output reports a mode.
+/// Query one `wl_output`'s pixel dimensions via a short Wayland roundtrip,
+/// independent of the virtual-pointer protocol. Only used by the libei click to
+/// resolve its `(0, 0)` centre default; it is not the desktop layout, so it
+/// must not bound coordinates. Falls back to `(1, 1)` when no output reports a mode.
#[cfg(feature = "portal-input")]
fn output_dimensions() -> anyhow::Result<(u32, u32)> {
let conn = Connection::connect_to_env()?;
@@ -1715,23 +1716,6 @@ fn output_dimensions() -> anyhow::Result<(u32, u32)> {
Ok((state.output_w.max(1), state.output_h.max(1)))
}
-/// Reproduce the wlroots vptr path's coordinate handling for the libei
-/// fallback: `(0, 0)` defaults to the output centre, and any value is clamped
-/// to `[0, dim-1]`. Keeps `click(.., 0, 0, ..)` landing on centre rather than
-/// the top-left corner across both backends.
-#[cfg(feature = "portal-input")]
-fn normalize_click_xy(x: i32, y: i32, w: u32, h: u32) -> (i32, i32) {
- let (px, py) = if x == 0 && y == 0 {
- ((w / 2) as i32, (h / 2) as i32)
- } else {
- (x, y)
- };
- (
- px.clamp(0, (w as i32).saturating_sub(1)),
- py.clamp(0, (h as i32).saturating_sub(1)),
- )
-}
-
/// Map a cua/X11 pointer button (1=left / 2=middle / 3=right) to its evdev
/// code, which is what `zwlr_virtual_pointer_v1::button` expects.
pub fn evdev_pointer_button(button: u8) -> u32 {
@@ -2635,9 +2619,24 @@ fn libei_wait_keyboard_ready() -> anyhow::Result<()> {
#[cfg(feature = "portal-input")]
fn libei_click(x: i32, y: i32, count: u32, button: u8) -> anyhow::Result<()> {
+ libei_click_with(x, y, count, button, output_dimensions)
+}
+
+#[cfg(feature = "portal-input")]
+fn libei_click_with(
+ x: i32,
+ y: i32,
+ count: u32,
+ button: u8,
+ dimensions: impl FnOnce() -> anyhow::Result<(u32, u32)>,
+) -> anyhow::Result<()> {
let btn = cua_button_to_libei(button);
- let (w, h) = output_dimensions()?;
- let (px, py) = normalize_click_xy(x, y, w, h);
+ let (px, py) = if (x, y) == (0, 0) {
+ let (w, h) = dimensions()?;
+ ((w / 2) as i32, (h / 2) as i32)
+ } else {
+ (x, y)
+ };
libei::move_absolute(px as f64, py as f64)?;
for i in 0..count.max(1) {
if i > 0 {
@@ -2670,13 +2669,8 @@ fn libei_scroll(direction: &str, amount: u32) -> anyhow::Result<()> {
#[cfg(feature = "portal-input")]
fn libei_move_absolute(x: i32, y: i32) -> anyhow::Result<()> {
- // Match `move_cursor_absolute_vptr`: clamp to output bounds (no
- // default-to-centre — an explicit (0,0) move means the top-left corner).
- let (w, h) = output_dimensions()?;
- let px = x.clamp(0, (w as i32).saturating_sub(1));
- let py = y.clamp(0, (h as i32).saturating_sub(1));
- libei::move_absolute(px as f64, py as f64)?;
- record_synth_cursor(px, py);
+ libei::move_absolute(x as f64, y as f64)?;
+ record_synth_cursor(x, y);
Ok(())
}
@@ -2692,24 +2686,18 @@ fn libei_drag(
) -> anyhow::Result<()> {
// ei_button exposes separate Press/Released states, so the libei worker can
// hold the button across the interpolated motion — a genuine
- // press→move→release drag. Clamp both endpoints to the output — but NOT via
- // `normalize_click_xy`, whose (0,0)→centre convention (for coordinate-free
- // clicks) is wrong here: a drag endpoint is always explicit and (0,0) is a
- // valid top-left corner target.
+ // press→move→release drag.
let btn = cua_button_to_libei(button);
- let (w, h) = output_dimensions()?;
- let cx = |x: i32| x.clamp(0, (w as i32).saturating_sub(1));
- let cy = |y: i32| y.clamp(0, (h as i32).saturating_sub(1));
libei::drag(
- cx(from_x) as f64,
- cy(from_y) as f64,
- cx(to_x) as f64,
- cy(to_y) as f64,
+ from_x as f64,
+ from_y as f64,
+ to_x as f64,
+ to_y as f64,
steps,
duration_ms,
btn,
)?;
- record_synth_cursor(cx(to_x), cy(to_y));
+ record_synth_cursor(to_x, to_y);
Ok(())
}
@@ -3878,6 +3866,141 @@ mod tests {
use super::*;
+ fn region(offset_x: f32) -> region_route::RegionRect {
+ region_route::RegionRect {
+ offset_x,
+ offset_y: 0.0,
+ width: 3840.0,
+ height: 2160.0,
+ }
+ }
+
+ #[test]
+ fn absolute_point_on_second_monitor_routes_to_its_region() {
+ let (l, r) = ([region(0.0)], [region(3840.0)]);
+ let one = [("abs", &[l[0], r[0]][..])];
+ assert_eq!(
+ region_route::route_absolute(one, 6237.0, 1014.0).unwrap(),
+ Some("abs")
+ );
+ let two = [("left", &l[..]), ("right", &r[..])];
+ assert_eq!(
+ region_route::route_absolute(two, 6237.0, 1014.0).unwrap(),
+ Some("right")
+ );
+ }
+
+ #[test]
+ fn point_outside_announced_regions_is_an_error() {
+ let both = [region(0.0), region(3840.0)];
+ for x in [8000.0, 7680.0] {
+ let err = region_route::route_absolute([("abs", &both[..])], x, 100.0).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ format!("libei: ({x}, 100) lies outside every announced pointer region")
+ );
+ }
+ }
+
+ #[test]
+ fn unmatched_point_cannot_escape_through_an_empty_candidate() {
+ let l = [region(0.0)];
+ let none: [region_route::RegionRect; 0] = [];
+ let mixed = [("empty", &none[..]), ("left", &l[..])];
+ let err = region_route::route_absolute(mixed, 6237.0, 1014.0).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "libei: (6237, 1014) lies outside every announced pointer region"
+ );
+ }
+
+ #[cfg(feature = "portal-input")]
+ mod libei_adapters {
+ use super::super::*;
+ use libei::local_eis::{record, Emitted};
+
+ fn motion(x: f32, y: f32) -> Emitted {
+ Emitted::Motion("wide".into(), x, y)
+ }
+
+ #[test]
+ fn click_adapter_does_not_clamp_or_shift_second_monitor_point() {
+ let (result, events) = record(|| libei_click(6237, 1014, 1, 1));
+ result.unwrap();
+ assert_eq!(events[0], motion(6237.0, 1014.0));
+ assert_eq!(events[1], motion(6237.0, 1014.0));
+ }
+
+ #[test]
+ fn click_at_origin_means_output_centre_not_literal_origin() {
+ let (result, events) = record(|| libei_click_with(0, 0, 1, 1, || Ok((3840, 2160))));
+ result.unwrap();
+ assert!(!events.contains(&motion(0.0, 0.0)));
+ assert_eq!(events.first(), Some(&motion(1920.0, 1080.0)));
+ let buttons: Vec<bool> = events
+ .iter()
+ .filter_map(|e| match e {
+ Emitted::Button(_, down) => Some(*down),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(buttons, vec![true, false]);
+ }
+
+ #[test]
+ fn move_adapter_keeps_second_monitor_point_and_literal_origin() {
+ let (result, events) = record(|| libei_move_absolute(6237, 1014));
+ result.unwrap();
+ assert_eq!(events, vec![motion(6237.0, 1014.0)]);
+ let (result, events) = record(|| libei_move_absolute(0, 0));
+ result.unwrap();
+ assert_eq!(events, vec![motion(0.0, 0.0)]);
+ }
+
+ #[test]
+ fn drag_adapter_keeps_endpoints_and_literal_origin() {
+ let (result, events) = record(|| libei_drag(0, 0, 6237, 1014, 2, 0, 1));
+ result.unwrap();
+ assert_eq!(events.first(), Some(&motion(0.0, 0.0)));
+ assert_eq!(events[events.len() - 2], motion(6237.0, 1014.0));
+ }
+
+ #[test]
+ fn positioned_scroll_scrolls_after_a_valid_move() {
+ let (result, events) = record(|| {
+ libei_move_absolute(6237, 1014)?;
+ libei_scroll("down", 1)
+ });
+ result.unwrap();
+ assert_eq!(
+ events,
+ vec![motion(6237.0, 1014.0), Emitted::Scroll(0.0, 10.0)]
+ );
+ }
+
+ #[test]
+ fn positioned_scroll_to_an_invalid_point_emits_no_scroll() {
+ let (result, events) = record(|| {
+ libei_move_absolute(8000, 100)?;
+ libei_scroll("down", 1)
+ });
+ assert_eq!(
+ result.unwrap_err().to_string(),
+ "libei: (8000, 100) lies outside every announced pointer region"
+ );
+ assert_eq!(events, vec![]);
+ }
+ }
+
+ #[test]
+ fn no_announced_regions_falls_back() {
+ let none: [region_route::RegionRect; 0] = [];
+ assert_eq!(
+ region_route::route_absolute([("abs", &none[..])], 6237.0, 1.0).unwrap(),
+ None
+ );
+ }
+
#[test]
fn punctuation_shortcuts_preserve_modifiers_without_implicit_shift() {
for (keys, expected_mods, physical_key) in [
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/region_route.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/region_route.rs
new file mode 100644
index 0000000000..0814775ea1
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/region_route.rs
@@ -0,0 +1,44 @@
+/// One announced ei_device::Region — a single monitor's pixel rectangle
+/// inside the seat's logical coordinate space. Multi-monitor sessions
+/// announce one Region per output; we route each absolute (x, y) to the
+/// region containing it so the cursor lands on the correct monitor.
+#[derive(Clone, Copy, Debug)]
+pub(super) struct RegionRect {
+ pub(super) offset_x: f32,
+ pub(super) offset_y: f32,
+ pub(super) width: f32,
+ pub(super) height: f32,
+}
+
+impl RegionRect {
+ pub(super) fn contains(&self, x: f64, y: f64) -> bool {
+ let xf = x as f32;
+ let yf = y as f32;
+ xf >= self.offset_x
+ && xf < self.offset_x + self.width
+ && yf >= self.offset_y
+ && yf < self.offset_y + self.height
+ }
+}
+
+/// First candidate whose regions contain `(x, y)`. `Ok(None)` means no
+/// candidate announced any region (caller falls back). Regions that exist but
+/// exclude the point are an error: EIS would silently discard the motion and
+/// the button would land at the stale pointer position.
+pub(super) fn route_absolute<'a, K>(
+ candidates: impl IntoIterator<Item = (K, &'a [RegionRect])>,
+ x: f64,
+ y: f64,
+) -> anyhow::Result<Option<K>> {
+ let mut announced = false;
+ for (key, regions) in candidates {
+ if regions.iter().any(|r| r.contains(x, y)) {
+ return Ok(Some(key));
+ }
+ announced |= !regions.is_empty();
+ }
+ if announced {
+ anyhow::bail!("libei: ({x}, {y}) lies outside every announced pointer region");
+ }
+ Ok(None)
+}