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(cua-driver): support multi-monitor Hyprland desktops (#4305)

Iann298674a6832086
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/render_map.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/render_map.rs
index 941edd9104..f526c469e0 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/render_map.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/render_map.rs
@@ -303,7 +303,7 @@ impl<S: RenderEntry, P> RenderMap<S, P> {
return false;
};
let core = cursor.core_mut();
- if !(core.cfg.enabled && core.pos.0 < -50.0) {
+ if !(core.cfg.enabled && !crate::render_state::is_placed(core.pos)) {
return false;
}
core.pos = seed_position(target_x, target_y, frame);
@@ -533,6 +533,10 @@ mod tests {
map.cursors["sessA"].pos = (30.0, 30.0);
assert!(!map.seed_start_if_sentinel("sessA", 80.0, 80.0, frame));
assert_eq!(map.cursors["sessA"].pos, (30.0, 30.0));
+ // A cursor placed on a monitor left of the layout origin is no sentinel.
+ map.cursors["sessA"].pos = (-2220.0, 980.0);
+ assert!(!map.seed_start_if_sentinel("sessA", 80.0, 80.0, frame));
+ assert_eq!(map.cursors["sessA"].pos, (-2220.0, 980.0));
map.cursor_mut("disabled").unwrap().cfg.enabled = false;
assert!(!map.seed_start_if_sentinel("disabled", 80.0, 80.0, frame));
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
index 919bf12e7f..31c8db3499 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
@@ -44,6 +44,17 @@ use std::sync::Arc;
pub const SESSION_BADGE_HOLD_SECS: f64 = 2.0;
pub const SESSION_BADGE_FADE_SECS: f64 = 0.4;
+/// Position of a cursor that has never been placed. It lies far outside any
+/// compositor layout: layouts reach negative coordinates when a monitor sits
+/// left of or above the primary one, so a small negative sentinel (the old
+/// `(-200, -200)`) is indistinguishable from a real position there.
+pub const UNPLACED_POS: (f64, f64) = (-1.0e9, -1.0e9);
+
+/// Whether `pos` is a real position rather than [`UNPLACED_POS`].
+pub fn is_placed(pos: (f64, f64)) -> bool {
+ pos.0 > -1.0e8
+}
+
/// Platform-agnostic render state shared by macOS / Windows / Linux overlays.
///
/// Each platform wraps this in its own struct that adds OS-specific fields
@@ -137,7 +148,7 @@ impl RenderStateCore {
semantic_cue: false,
theme,
theme_fallback,
- pos: (-200.0, -200.0),
+ pos: UNPLACED_POS,
heading: std::f64::consts::FRAC_PI_4,
path: None,
dist: 0.0,
@@ -158,10 +169,10 @@ impl RenderStateCore {
}
}
- /// Whether the cursor currently paints pixels: user-visible, placed on
- /// screen (not the `(-200, -200)` sentinel), and not fully idle-faded.
+ /// Whether the cursor currently paints pixels: user-visible, placed
+ /// (not [`UNPLACED_POS`]), and not fully idle-faded.
pub fn is_revealed(&self) -> bool {
- self.visible && self.pos.0 >= -100.0 && self.idle_alpha >= 0.004
+ self.visible && is_placed(self.pos) && self.idle_alpha >= 0.004
}
/// Whether a revealed cursor keeps changing pixels while it rests.
@@ -202,10 +213,8 @@ impl RenderStateCore {
/// `motion.idle_hide_ms` of inactivity) is currently animating.
pub fn idle_fade_in_progress(&self) -> bool {
self.motion.idle_hide_ms > 0.0
- && self.visible
- && self.pos.0 >= -100.0
+ && self.is_revealed()
&& self.idle_secs >= self.motion.idle_hide_ms / 1000.0
- && self.idle_alpha >= 0.004
}
/// The shared frame-tick predicate: true while the next tick can change
@@ -231,7 +240,7 @@ impl RenderStateCore {
/// the fade has already started.
pub fn idle_fade_wait(&self) -> Option<std::time::Duration> {
if !self.visible
- || self.pos.0 < -100.0
+ || !is_placed(self.pos)
|| self.motion.idle_hide_ms <= 0.0
|| self.path.is_some()
|| self.spring.is_some()
@@ -631,7 +640,7 @@ impl RenderStateCore {
///
/// `move_to_snap_sentinel` controls macOS-only behaviour: when `true`,
/// `MoveTo` snaps `self.pos` to the offset target if the cursor is
- /// still at the off-screen sentinel (`pos.0 < -50.0`). Windows/Linux
+ /// still at [`UNPLACED_POS`]. Windows/Linux
/// pass `false` here.
///
/// `click_pulse_sentinel_only` likewise controls macOS-only behaviour:
@@ -660,7 +669,7 @@ impl RenderStateCore {
// macOS-only: if the cursor is still at the initial off-screen
// sentinel, snap it to the offset target so the path starts on-screen.
- if move_to_snap_sentinel && self.pos.0 < -50.0 {
+ if move_to_snap_sentinel && !is_placed(self.pos) {
self.pos = (tx, ty);
}
let (x0, y0) = self.pos;
@@ -724,7 +733,7 @@ impl RenderStateCore {
// that the cursor stays where the animation landed. Windows
// and Linux always snap. Both anchor the click point so the
// hotspot stays on it instead of jumping by the anchor offset.
- if !click_pulse_sentinel_only || self.pos.0 < -50.0 {
+ if !click_pulse_sentinel_only || !is_placed(self.pos) {
self.pos = crate::anchor_for_pointer(x, y, self.heading);
}
self.click_t = Some(0.0);
@@ -904,11 +913,7 @@ pub fn paint_cursor(
focus_rect: Option<FocusRect>,
backing_scale: f32,
) {
- if !core.visible
- || core.pinned_target_off_workspace
- || core.pos.0 < -100.0
- || core.idle_alpha < 0.004
- {
+ if !core.is_revealed() || core.pinned_target_off_workspace {
return;
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
index 6e87daec70..326da4d6a2 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
@@ -609,7 +609,11 @@ fn set_remote_debugging(
.checked_add(i32::try_from(height / 2)?)
.ok_or_else(|| anyhow::anyhow!("checkbox center y overflowed"))?;
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
- crate::wayland::click_desktop(center_x, center_y, 1, 1)?;
+ // AT-SPI screen bounds are layout coordinates, as in
+ // browser_consent_ui's click_focused path, not
+ // desktop-frame points, so no frame conversion applies.
+ let space = crate::wayland::DesktopInputSpace::default();
+ crate::wayland::click_desktop(&space, center_x, center_y, 1, 1)?;
} else {
crate::input::send_click_xtest_desktop(center_x, center_y, 1, 1)?;
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
index 2674dff87a..d9ddbb8432 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
@@ -568,12 +568,7 @@ pub fn is_visible_for_session(key: &str) -> bool {
guard
.as_ref()
.and_then(|map| map.cursors.get(key))
- .map(|rs| {
- rs.core.cfg.enabled
- && rs.core.visible
- && rs.core.idle_alpha >= 0.004
- && rs.core.pos.0 >= -100.0
- })
+ .map(|rs| rs.core.cfg.enabled && rs.core.is_revealed())
})
.unwrap_or(false)
}
@@ -591,7 +586,7 @@ pub fn current_position_for(key: &str) -> (f64, f64) {
.and_then(|m| m.cursors.get(key))
.map(|rs| rs.core.pos)
})
- .unwrap_or((-200.0, -200.0))
+ .unwrap_or(cursor_overlay::render_state::UNPLACED_POS)
}
pub fn current_motion_for(key: &str) -> cursor_overlay::MotionConfig {
@@ -650,7 +645,9 @@ pub async fn animate_cursor_to_for(key: CursorKey, x: f64, y: f64) {
let guard = RENDER.lock().unwrap();
matches!(
guard.as_ref().and_then(|m| m.cursors.get(&key)),
- Some(rs) if rs.core.cfg.enabled && rs.core.visible && rs.core.pos.0 > -50.0
+ Some(rs) if rs.core.cfg.enabled
+ && rs.core.visible
+ && cursor_overlay::render_state::is_placed(rs.core.pos)
)
};
if !should_animate {
@@ -2295,7 +2292,7 @@ fn cursor_tile_bounds(
screen_width: u32,
screen_height: u32,
) -> Option<X11TileBounds> {
- if !core.visible || core.pos.0 < -100.0 || core.idle_alpha < 0.004 {
+ if !core.is_revealed() {
return None;
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs
index e068429c7a..a87cd8ee79 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs
@@ -179,7 +179,10 @@ pub fn hyprland_pixel_recording_point(
x: f64,
y: f64,
) -> Option<(f64, f64)> {
- let (width, height, _) = crate::wayland::hyprland::screen_size().ok()?;
+ // The recorded image is the desktop frame. Window geometry is in layout
+ // coordinates, so move a window point into the frame before placing it.
+ let frame = crate::wayland::hyprland::desktop_frame().ok()?;
+ let (width, height) = (frame.width, frame.height);
match (window_id, pid) {
(Some(window_id), Some(pid)) => {
let pid = u32::try_from(pid).ok()?;
@@ -187,9 +190,10 @@ pub fn hyprland_pixel_recording_point(
if window.pid != Some(pid) {
return None;
}
+ let (frame_x, frame_y) = frame.from_layout(window.x, window.y);
hyprland_output_point(
- (f64::from(window.x) + x, f64::from(window.y) + y),
- (window.x, window.y, window.width, window.height),
+ (f64::from(frame_x) + x, f64::from(frame_y) + y),
+ (frame_x, frame_y, window.width, window.height),
(width, height),
)
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
index 33d7685288..2dad6f3778 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
@@ -49,6 +49,14 @@ fn pid_window_target_candidates(pid: i64) -> Vec<WindowTargetCandidate> {
fn desktop_point_window_resolver() -> cua_driver_core::window_target::DesktopPointWindowResolver {
Arc::new(move |pid, x, y| {
let pid = u32::try_from(pid).ok()?;
+ // Window geometry is in layout coordinates; on Hyprland the desktop
+ // frame starts at the top-left powered output, not the layout origin.
+ let (x, y) = if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ let frame = crate::wayland::hyprland::desktop_frame().ok()?;
+ (x + f64::from(frame.x), y + f64::from(frame.y))
+ } else {
+ (x, y)
+ };
topmost_window_at(&crate::wayland::list_windows_dispatch(Some(pid)), pid, x, y)
})
}
@@ -5346,6 +5354,18 @@ async fn overlay_glide_to_for(cursor_id: &str, sx: f64, sy: f64) {
crate::overlay::animate_cursor_to_for(cursor_id.to_owned(), sx, sy).await;
}
+/// The compositor snapshot a desktop-scope action is addressed in. One
+/// snapshot converts the action's points, places the overlay and sizes the
+/// virtual pointer, so they cannot disagree about the monitor layout.
+async fn desktop_input_space() -> anyhow::Result<crate::wayland::DesktopInputSpace> {
+ if !crate::wayland::wayland_input_enabled() {
+ return Ok(crate::wayland::DesktopInputSpace::default());
+ }
+ tokio::task::spawn_blocking(crate::wayland::DesktopInputSpace::current)
+ .await
+ .map_err(|error| anyhow::anyhow!("task error: {error}"))?
+}
+
/// Keep the logical cursor position in sync with every visibly targeted
/// pointer action. Overlay delivery is intentionally best-effort: registry
/// state is still updated when no renderer is running or its queue is closed.
@@ -6242,6 +6262,12 @@ impl Tool for ClickTool {
return ToolResult::error("click.count must be at least 1.")
.with_structured(json!({ "code": "invalid_arguments" }));
}
+ let space = match desktop_input_space().await {
+ Ok(space) => space,
+ Err(error) => {
+ return ToolResult::error(format!("desktop-scope click failed: {error}"))
+ }
+ };
let (action_x, action_y) = if let Some(capture_id) = args.opt_str("capture_id") {
match crate::capture_action_frame::admit_desktop_click(
&self.state.capture_service,
@@ -6262,8 +6288,16 @@ impl Tool for ClickTool {
// / Windows desktop paths already do this). Without it the overlay
// sits idle elsewhere while only the real pointer warps, so a viewer
// sees the cursor "click somewhere else."
- reveal_pointer_action_for(&self.state, &cursor_id, f64::from(sx), f64::from(sy), true)
- .await;
+ // The overlay draws in layout coordinates, like the input below.
+ let (overlay_x, overlay_y) = space.to_layout(sx, sy);
+ reveal_pointer_action_for(
+ &self.state,
+ &cursor_id,
+ f64::from(overlay_x),
+ f64::from(overlay_y),
+ true,
+ )
+ .await;
let r = tokio::task::spawn_blocking(move || {
if crate::wayland::wayland_input_enabled() {
if !modifiers.is_empty() {
@@ -6272,7 +6306,7 @@ impl Tool for ClickTool {
the virtual-pointer route cannot carry keyboard modifier state"
);
}
- crate::wayland::click_desktop(sx, sy, n as u32, button)
+ crate::wayland::click_desktop(&space, sx, sy, n as u32, button)
} else {
let modifier_refs: Vec<&str> = modifiers.iter().map(String::as_str).collect();
crate::input::send_click_xtest_desktop_with_modifiers(
@@ -9347,19 +9381,24 @@ impl Tool for ScrollTool {
let display = direction.clone();
let wayland = crate::wayland::wayland_input_enabled();
let path = if wayland { "wayland_desktop" } else { "xtest" };
+ let space = match desktop_input_space().await {
+ Ok(space) => space,
+ Err(error) => return ToolResult::error(error.to_string()),
+ };
if named_session_cursor_key(&args).is_some() {
+ let (overlay_x, overlay_y) = space.to_layout(x, y);
reveal_pointer_action_for(
&self.state,
&cursor_id,
- f64::from(x),
- f64::from(y),
+ f64::from(overlay_x),
+ f64::from(overlay_y),
false,
)
.await;
}
let result = tokio::task::spawn_blocking(move || {
if wayland {
- crate::wayland::scroll_desktop(x, y, &direction, amount as u32)
+ crate::wayland::scroll_desktop(&space, x, y, &direction, amount as u32)
} else {
crate::input::send_scroll_xtest_desktop(x, y, &direction, amount)
}
@@ -10491,9 +10530,21 @@ impl Tool for DragTool {
return wayland_modified_drag_refusal();
}
let path = if wayland { "wayland_desktop" } else { "xtest" };
+ let space = match desktop_input_space().await {
+ Ok(space) => space,
+ Err(error) => return ToolResult::error(error.to_string()),
+ };
+ // The overlay draws in layout coordinates, like the input below.
+ let overlay_point = |x: f64, y: f64| {
+ let (lx, ly) = space.to_layout(x.round() as i32, y.round() as i32);
+ (f64::from(lx), f64::from(ly))
+ };
+ let (overlay_from, overlay_to) =
+ (overlay_point(from_x, from_y), overlay_point(to_x, to_y));
let result = tokio::task::spawn_blocking(move || {
if wayland {
crate::wayland::drag_desktop(
+ &space,
from_x.round() as i32,
from_y.round() as i32,
to_x.round() as i32,
@@ -10518,8 +10569,8 @@ impl Tool for DragTool {
});
let visual_drag = track_overlay_drag_for(
cursor_id.clone(),
- (from_x, from_y),
- (to_x, to_y),
+ overlay_from,
+ overlay_to,
duration_ms,
steps,
);
@@ -10527,7 +10578,7 @@ impl Tool for DragTool {
if matches!(&result, Ok(Ok(()))) {
self.state
.cursor_registry
- .update_position(&cursor_id, to_x, to_y);
+ .update_position(&cursor_id, overlay_to.0, overlay_to.1);
}
return match result {
Ok(Ok(())) => ToolResult::text("Dragged on the desktop.").with_structured(
@@ -12027,21 +12078,56 @@ impl Tool for GetScreenSizeTool {
// Shared manifest admission needs content-free display
// metadata even when this native desktop has no X11 DISPLAY.
// The adapter attests the IPC/Wayland compositor peer and
- // refuses layouts outside its qualified single-output frame.
+ // refuses layouts its logical frame cannot represent: no
+ // powered output, or a rotated powered output.
// Scaled outputs report logical pixels plus the output scale.
- return crate::wayland::hyprland::screen_size();
+ // The size and the monitor list come from one snapshot.
+ let (frame, monitors) = crate::wayland::hyprland::screen_report()?;
+ return Ok((frame.width, frame.height, frame.scale, Some(monitors)));
}
// X11 reports pixel dimensions; scale factor on X11 is not
// well-defined per-monitor, so report 1.0 (matches DPI-unaware
// assumption). Other Wayland compositors retain their existing
// limitation; do not infer native metadata support there.
let (w, h) = x11_screen_size()?;
- Ok::<(u32, u32, f64), anyhow::Error>((w, h, 1.0))
+ Ok::<(u32, u32, f64, Option<Value>), anyhow::Error>((w, h, 1.0, None))
})
.await;
match result {
+ Ok(Ok((w, h, scale, Some(monitors)))) => {
+ // Tell the agent which monitors are actually on: the desktop
+ // frame covers powered monitors only and changes as they turn
+ // on or off, so re-read it after any display change.
+ let describe = |m: &Value| {
+ let name = m["name"].as_str().unwrap_or("?");
+ match (
+ m["powered"].as_bool(),
+ m["frame_x"].as_i64(),
+ m["frame_y"].as_i64(),
+ ) {
+ (Some(true), Some(x), Some(y)) => format!(
+ "{name} {}x{} on, at ({x},{y}) in the desktop frame",
+ m["width"], m["height"]
+ ),
+ _ => format!("{name} off (standby), not in the desktop frame"),
+ }
+ };
+ let lines: Vec<String> = monitors
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(describe)
+ .collect();
+ ToolResult::text(format!(
+ "✅ Desktop frame: {w}x{h} points @ {scale}x, spanning every monitor that is on.\n{}",
+ lines.join("\n")
+ ))
+ .with_structured(json!({
+ "width": w, "height": h, "scale_factor": scale, "monitors": monitors,
+ }))
+ }
// Matches Swift text format 1:1.
- Ok(Ok((w, h, scale))) => {
+ Ok(Ok((w, h, scale, None))) => {
ToolResult::text(format!("✅ Main display: {w}x{h} points @ {scale}x"))
.with_structured(json!({ "width": w, "height": h, "scale_factor": scale }))
}
@@ -12162,11 +12248,26 @@ impl Tool for GetDesktopStateTool {
// The agent reads this image, so the Driver's own cursor and
// session pill are hidden around the grab (or the limitation is
// reported) instead of being baked over the controls it reads.
+ // Hyprland: read the desktop frame once. The screenshot, its action
+ // size and the window geometry below all use it.
+ let hyprland_plan =
+ if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ Some(crate::wayland::hyprland::desktop_capture_plan()?)
+ } else {
+ None
+ };
let (native_png, overlay_capture) =
cursor_overlay::capture_exclusion::capture_excluding_overlays(
&crate::overlay_capture::OverlayExcluder,
|hidden| {
- let png = crate::capture::screenshot_display_bytes()?;
+ // A multi-monitor layout is composed from the frame
+ // read above, so the image is exactly that frame.
+ let png = match &hyprland_plan {
+ Some(plan) if plan.composite => {
+ crate::wayland::hyprland::compose_desktop_capture(&plan.frame)?
+ }
+ _ => crate::capture::screenshot_display_bytes()?,
+ };
Ok::<_, anyhow::Error>(crate::overlay_capture::verify_hidden_capture(
png, hidden,
))
@@ -12182,7 +12283,10 @@ impl Tool for GetDesktopStateTool {
// abort the tool even though the screenshot already succeeded.
// Only fall back to the X11 root-window geometry off Wayland, so
// the X11 / XWayland path is unchanged. See #2017 / Sway testing.
- let (screen_w, screen_h) = if crate::wayland::is_wayland() {
+ let hyprland_frame = hyprland_plan.map(|plan| plan.frame);
+ let (screen_w, screen_h) = if let Some(frame) = &hyprland_frame {
+ (frame.width, frame.height)
+ } else if crate::wayland::is_wayland() {
crate::capture_action_frame::desktop_action_dimensions((native_w, native_h))?
} else {
x11_screen_size()?
@@ -12218,6 +12322,16 @@ impl Tool for GetDesktopStateTool {
let mut windows = crate::wayland::list_windows_dispatch(None);
windows
.retain(|w| w.is_on_screen && w.pid.is_some_and(crate::proc_fs::is_process_live));
+ if let Some(frame) = &hyprland_frame {
+ // Window geometry is in layout coordinates; screenshot pixel
+ // (0, 0) is the frame origin. Refuse rather than pair this
+ // capture with a layout that changed meanwhile.
+ anyhow::ensure!(
+ crate::wayland::hyprland::desktop_frame()? == *frame,
+ "the Hyprland monitor layout changed during get_desktop_state; call it again"
+ );
+ frame.rebase_windows(&mut windows);
+ }
let capture_id = crate::capture_action_frame::publish_desktop(
&capture_service,
&capture_args,
@@ -12382,6 +12496,28 @@ impl Tool for GetCursorPositionTool {
{
return result;
}
+ // Hyprland reports the real pointer over IPC; return it in the
+ // desktop-frame coordinates that get_desktop_state and desktop actions use.
+ if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ let position = tokio::task::spawn_blocking(|| -> anyhow::Result<(i32, i32)> {
+ let (x, y) = crate::wayland::hyprland::cursor_position()?;
+ Ok(crate::wayland::hyprland::desktop_frame()?
+ .from_layout(x.round() as i32, y.round() as i32))
+ })
+ .await;
+ // The synthetic registry below holds layout coordinates, not the
+ // desktop frame, so a failed compositor query is an error here.
+ return match position {
+ Ok(Ok((x, y))) => {
+ ToolResult::text(format!("✅ Cursor at ({x}, {y}) in the desktop frame"))
+ .with_structured(json!({ "x": x, "y": y, "source": "compositor" }))
+ }
+ Ok(Err(e)) => ToolResult::error(format!(
+ "Could not read the Hyprland pointer position: {e:#}"
+ )),
+ Err(e) => ToolResult::error(format!("Task error: {e}")),
+ };
+ }
// Native Wayland: there's no protocol for clients to query the real
// global cursor position. Fall back to the synthetic registry that
// records every `motion_absolute` this process emits.
@@ -12472,7 +12608,8 @@ impl Tool for MoveCursorTool {
};
let result = if wayland {
tokio::task::spawn_blocking(move || {
- crate::wayland::move_cursor_absolute(None, xi, yi)
+ let space = crate::wayland::DesktopInputSpace::current()?;
+ crate::wayland::move_cursor_desktop(&space, xi, yi)
})
.await
} else {
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs
index 48e95b40e0..9aaa2a0535 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs
@@ -49,16 +49,140 @@ struct Monitor {
active_workspace: Workspace,
#[serde(rename = "specialWorkspace")]
special_workspace: Workspace,
+ /// A monitor in DPMS standby still owns its workspaces, but nothing on it
+ /// is visible to the user.
+ #[serde(rename = "dpmsStatus", default = "powered_by_default")]
+ dpms_status: bool,
}
#[derive(Clone, Debug, Deserialize)]
struct DisplayMonitor {
+ #[serde(default)]
+ name: String,
width: u32,
height: u32,
scale: f64,
x: i32,
y: i32,
transform: u32,
+ #[serde(default)]
+ disabled: bool,
+ #[serde(rename = "dpmsStatus", default = "powered_by_default")]
+ dpms_status: bool,
+ /// Name of the output this one mirrors, or `"none"`.
+ #[serde(rename = "mirrorOf", default)]
+ mirror_of: String,
+}
+
+fn powered_by_default() -> bool {
+ true
+}
+
+impl DisplayMonitor {
+ /// A mirror repeats another output's content and has no area of its own
+ /// in the layout.
+ fn in_layout(&self) -> bool {
+ !self.disabled && matches!(self.mirror_of.as_str(), "" | "none")
+ }
+
+ /// In the layout and not in DPMS standby: the user can actually see it.
+ fn powered(&self) -> bool {
+ self.in_layout() && self.dpms_status
+ }
+
+ /// The output mode divided by its scale, rounded as Hyprland rounds its
+ /// logical monitor size. Window geometry and the layout use this size.
+ /// Hyprland reports the mode in the panel's native orientation; quarter
+ /// turns (wl_output transforms 1 and 3) swap the logical axes, and flipped
+ /// transforms (4-7) are refused.
+ fn logical_size(&self) -> Result<(u32, u32)> {
+ if !self.scale.is_finite() || self.scale <= 0.0 {
+ bail!("invalid Hyprland display scale");
+ }
+ if self.transform > 3 {
+ bail!("Hyprland display identity requires unflipped outputs");
+ }
+ if !valid_dimensions(self.width, self.height) {
+ bail!("invalid Hyprland display dimensions");
+ }
+ let (width, height) = super::logical_output_size((self.width, self.height), self.transform);
+ let logical_width = (f64::from(width) / self.scale).round();
+ let logical_height = (f64::from(height) / self.scale).round();
+ if !logical_width.is_finite()
+ || !logical_height.is_finite()
+ || logical_width < 1.0
+ || logical_height < 1.0
+ || logical_width > f64::from(u32::MAX)
+ || logical_height > f64::from(u32::MAX)
+ {
+ bail!("invalid Hyprland logical display dimensions");
+ }
+ let (logical_width, logical_height) = (logical_width as u32, logical_height as u32);
+ if !valid_dimensions(logical_width, logical_height) {
+ bail!("invalid Hyprland logical display dimensions");
+ }
+ Ok((logical_width, logical_height))
+ }
+}
+
+/// One output's logical rectangle in Hyprland layout coordinates.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct FrameOutput {
+ pub name: String,
+ pub x: i32,
+ pub y: i32,
+ pub width: u32,
+ pub height: u32,
+}
+
+/// The desktop action frame: the bounding box of every powered output
+/// (enabled and not in DPMS standby), in logical Hyprland layout coordinates.
+/// Desktop-scope screenshots, sizes and actions all use this frame, with
+/// frame pixel (0, 0) at layout point (`x`, `y`). It is re-derived from the
+/// compositor on every call, so monitors turned on or off take effect
+/// immediately.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DesktopFrame {
+ pub x: i32,
+ pub y: i32,
+ pub width: u32,
+ pub height: u32,
+ /// Output scale reported with the frame: the largest scale among its
+ /// outputs, so a single output reports its own scale.
+ pub scale: f64,
+ pub outputs: Vec<FrameOutput>,
+}
+
+impl DesktopFrame {
+ pub fn to_layout(&self, x: i32, y: i32) -> (i32, i32) {
+ (self.x.saturating_add(x), self.y.saturating_add(y))
+ }
+
+ pub fn from_layout(&self, x: i32, y: i32) -> (i32, i32) {
+ (x.saturating_sub(self.x), y.saturating_sub(self.y))
+ }
+
+ /// Whether a layout point lies on one of the frame's outputs. With
+ /// several outputs the frame's bounding box can include gaps and outputs
+ /// in standby, where the compositor would move the pointer to some other
+ /// output edge instead of the point the caller saw.
+ pub fn output_contains_layout(&self, x: i32, y: i32) -> bool {
+ self.outputs.iter().any(|o| {
+ let (x, y) = (i64::from(x), i64::from(y));
+ x >= i64::from(o.x)
+ && y >= i64::from(o.y)
+ && x < i64::from(o.x) + i64::from(o.width)
+ && y < i64::from(o.y) + i64::from(o.height)
+ })
+ }
+
+ /// Move window geometry from layout coordinates into this frame, so it
+ /// shares an origin with a screenshot of the frame.
+ pub fn rebase_windows(&self, windows: &mut [crate::x11::WindowInfo]) {
+ for window in windows {
+ (window.x, window.y) = self.from_layout(window.x, window.y);
+ }
+ }
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -334,52 +458,322 @@ fn valid_dimensions(width: u32, height: u32) -> bool {
width > 0 && height > 0 && u64::from(width) * u64::from(height) <= MAX_LOGICAL_PIXELS
}
-/// Content-free logical geometry for a qualified single-output desktop: the
-/// output mode divided by its scale, rounded as Hyprland rounds its logical
-/// monitor size, plus that scale. Desktop capture, desktop action admission,
-/// and the virtual-pointer extent all use this frame, matching the logical
-/// window geometry and window captures. The common policy adapter uses it for
-/// display-scoped observation. Never substitute a screenshot, XWayland root,
-/// or guessed primary monitor here.
+/// Content-free logical geometry of the desktop frame (see [`DesktopFrame`])
+/// plus its output scale. A single output's frame is its mode divided by its
+/// scale, rounded as Hyprland rounds its logical monitor size. Desktop
+/// capture, desktop action admission, and the virtual-pointer extent all use
+/// this frame, matching the logical window geometry and window captures. The
+/// common policy adapter uses it for display-scoped observation. Never
+/// substitute a screenshot, XWayland root, or guessed primary monitor here.
pub fn screen_size() -> Result<(u32, u32, f64)> {
screen_size_from_monitors(query("j/monitors")?)
}
fn screen_size_from_monitors(monitors: Vec<DisplayMonitor>) -> Result<(u32, u32, f64)> {
- let [monitor] = monitors.as_slice() else {
- bail!("Hyprland display identity requires exactly one active output");
+ let frame = desktop_frame_from_monitors(monitors)?;
+ Ok((frame.width, frame.height, frame.scale))
+}
+
+/// The desktop frame and every monitor in the layout with its power state
+/// and scale, both from one compositor snapshot so the size and the monitor
+/// list always describe the same layout. Sizes and positions are
+/// desktop-frame (logical) pixels; positions are `None` for monitors outside
+/// the frame (standby). Mirrors are omitted: they repeat another output.
+pub fn screen_report() -> Result<(DesktopFrame, serde_json::Value)> {
+ screen_report_from_monitors(query("j/monitors")?)
+}
+
+fn screen_report_from_monitors(
+ monitors: Vec<DisplayMonitor>,
+) -> Result<(DesktopFrame, serde_json::Value)> {
+ let frame = desktop_frame_from_monitors(monitors.clone())?;
+ let report = monitor_report_for(&monitors, &frame);
+ Ok((frame, report))
+}
+
+fn monitor_report_for(monitors: &[DisplayMonitor], frame: &DesktopFrame) -> serde_json::Value {
+ serde_json::Value::Array(
+ monitors
+ .iter()
+ .filter(|m| m.in_layout())
+ .map(|m| {
+ let size = m.logical_size().ok();
+ let (fx, fy) = frame.from_layout(m.x, m.y);
+ let in_frame = frame.outputs.iter().any(|o| o.name == m.name);
+ serde_json::json!({
+ "name": m.name,
+ "width": size.map(|(width, _)| width),
+ "height": size.map(|(_, height)| height),
+ "scale": m.scale,
+ "powered": m.powered(),
+ "frame_x": in_frame.then_some(fx),
+ "frame_y": in_frame.then_some(fy),
+ })
+ })
+ .collect(),
+ )
+}
+
+/// One compositor snapshot of everything a desktop-scope action needs: the
+/// desktop frame (screenshot coordinates) and the virtual-pointer layout.
+/// `pointer` is `None` when the layout is a single output the pointer layout
+/// cannot qualify; the virtual pointer then keeps that output's own mode.
+#[derive(Clone, Debug)]
+pub struct DesktopSnapshot {
+ pub frame: DesktopFrame,
+ pub pointer: Option<(i32, i32, u32, u32)>,
+}
+
+pub fn desktop_snapshot() -> Result<DesktopSnapshot> {
+ desktop_snapshot_from_monitors(query("j/monitors")?)
+}
+
+fn desktop_snapshot_from_monitors(monitors: Vec<DisplayMonitor>) -> Result<DesktopSnapshot> {
+ Ok(DesktopSnapshot {
+ frame: desktop_frame_from_monitors(monitors.clone())?,
+ pointer: pointer_space_from_monitors(monitors)?,
+ })
+}
+
+/// Current desktop frame spanning every powered output.
+pub fn desktop_frame() -> Result<DesktopFrame> {
+ desktop_frame_from_monitors(query("j/monitors")?)
+}
+
+fn desktop_frame_from_monitors(monitors: Vec<DisplayMonitor>) -> Result<DesktopFrame> {
+ let in_layout: Vec<DisplayMonitor> = monitors
+ .into_iter()
+ .filter(DisplayMonitor::in_layout)
+ .collect();
+ // An output in DPMS standby shows nothing, so the frame leaves it out
+ // while another output is on. With every output in standby the display is
+ // only idle (hypridle turned it off): keep the whole layout, as a single
+ // output always did, so observation and the input that wakes it still work.
+ let powered: Vec<DisplayMonitor> = if in_layout.iter().any(|m| m.dpms_status) {
+ in_layout.into_iter().filter(|m| m.dpms_status).collect()
+ } else {
+ in_layout
};
- if !monitor.scale.is_finite() || monitor.scale <= 0.0 {
- bail!("invalid Hyprland display scale");
+ if powered.is_empty() {
+ bail!("Hyprland has no enabled output: every monitor is disabled or mirrors another");
}
- // Hyprland reports the mode in the panel's native orientation. Rotated
- // outputs (wl_output transforms 1-3) are supported by reporting the logical
- // frame that windows and input use; flipped transforms (4-7) still refuse.
- if monitor.transform > 3 || monitor.x != 0 || monitor.y != 0 {
- bail!("Hyprland display identity requires an unflipped output at the origin");
+ let mut outputs = Vec::with_capacity(powered.len());
+ for monitor in &powered {
+ // A lone output may be rotated: its logical rectangle swaps axes and
+ // the single-output capture rotates into it. Composing several outputs
+ // assumes unrotated ones, so a rotated output among others refuses.
+ if monitor.transform != 0 && powered.len() > 1 {
+ bail!("Hyprland multi-monitor desktops require unrotated outputs");
+ }
+ outputs.push(frame_output(monitor)?);
}
- if !valid_dimensions(monitor.width, monitor.height) {
+ let (x, y, width, height) = bounding_box(&outputs)?;
+ let scale = powered.iter().map(|m| m.scale).fold(f64::MIN, f64::max);
+ Ok(DesktopFrame {
+ x,
+ y,
+ width,
+ height,
+ scale,
+ outputs,
+ })
+}
+
+fn frame_output(monitor: &DisplayMonitor) -> Result<FrameOutput> {
+ let (width, height) = monitor.logical_size()?;
+ Ok(FrameOutput {
+ name: monitor.name.clone(),
+ x: monitor.x,
+ y: monitor.y,
+ width,
+ height,
+ })
+}
+
+/// Bounding box of logical output rectangles, in layout coordinates.
+fn bounding_box(outputs: &[FrameOutput]) -> Result<(i32, i32, u32, u32)> {
+ let min_x = outputs
+ .iter()
+ .map(|o| i64::from(o.x))
+ .min()
+ .context("no outputs")?;
+ let min_y = outputs
+ .iter()
+ .map(|o| i64::from(o.y))
+ .min()
+ .context("no outputs")?;
+ let max_x = outputs
+ .iter()
+ .map(|o| i64::from(o.x) + i64::from(o.width))
+ .max()
+ .context("no outputs")?;
+ let max_y = outputs
+ .iter()
+ .map(|o| i64::from(o.y) + i64::from(o.height))
+ .max()
+ .context("no outputs")?;
+ let width = u32::try_from(max_x - min_x)?;
+ let height = u32::try_from(max_y - min_y)?;
+ if !valid_dimensions(width, height) {
bail!("invalid Hyprland display dimensions");
}
+ Ok((i32::try_from(min_x)?, i32::try_from(min_y)?, width, height))
+}
- let (width, height) =
- super::logical_output_size((monitor.width, monitor.height), monitor.transform);
- let logical_width = (f64::from(width) / monitor.scale).round();
- let logical_height = (f64::from(height) / monitor.scale).round();
- if !logical_width.is_finite()
- || !logical_height.is_finite()
- || logical_width < 1.0
- || logical_height < 1.0
- || logical_width > f64::from(u32::MAX)
- || logical_height > f64::from(u32::MAX)
- {
- bail!("invalid Hyprland logical display dimensions");
+/// Hyprland maps absolute virtual-pointer motion across the bounding box of
+/// every enabled, unmirrored output's logical rectangle; DPMS standby does
+/// not change the layout. Returns `(x, y, width, height)` of that box in
+/// layout coordinates. A lone output may be rotated (its logical rectangle
+/// swaps axes); a rotated output among others is refused.
+fn pointer_layout_from_monitors(monitors: Vec<DisplayMonitor>) -> Result<(i32, i32, u32, u32)> {
+ let in_layout: Vec<&DisplayMonitor> = monitors.iter().filter(|m| m.in_layout()).collect();
+ let mut outputs = Vec::new();
+ for monitor in &in_layout {
+ if monitor.transform != 0 && in_layout.len() > 1 {
+ bail!(
+ "Hyprland pointer layout requires unrotated outputs ({} has transform {}{})",
+ monitor.name,
+ monitor.transform,
+ if monitor.dpms_status {
+ ""
+ } else {
+ ", in standby"
+ }
+ );
+ }
+ outputs.push(frame_output(monitor)?);
}
- let (logical_width, logical_height) = (logical_width as u32, logical_height as u32);
- if !valid_dimensions(logical_width, logical_height) {
- bail!("invalid Hyprland logical display dimensions");
+ bounding_box(&outputs)
+}
+
+/// Virtual-pointer layout, or `None` for a single output it cannot qualify
+/// (a rotated one), whose own mode is then the whole layout. With several
+/// outputs in the layout no single output's mode is the layout, so an
+/// unqualified output (even one in standby) is an error, not a fallback.
+pub fn pointer_space() -> Result<Option<(i32, i32, u32, u32)>> {
+ pointer_space_from_monitors(query("j/monitors")?)
+}
+
+fn pointer_space_from_monitors(
+ monitors: Vec<DisplayMonitor>,
+) -> Result<Option<(i32, i32, u32, u32)>> {
+ let in_layout = monitors.iter().filter(|m| m.in_layout()).count();
+ match pointer_layout_from_monitors(monitors) {
+ Ok(layout) => Ok(Some(layout)),
+ Err(_) if in_layout <= 1 => Ok(None),
+ // Keep the cause in the message itself: tools report only the outer
+ // error, and the agent needs to know which output blocks the action.
+ Err(error) => Err(anyhow::anyhow!(
+ "{error}; the virtual pointer spans every monitor in the layout, including ones in standby, so it cannot be sized"
+ )),
}
- Ok((logical_width, logical_height, monitor.scale))
+}
+
+/// Desktop capture for layouts the generic capture cannot represent. With a
+/// single output this returns `None` and the caller keeps its capture
+/// cascade, whose buffer is that output. With several outputs the generic
+/// capture would copy only the first one, so each powered output is copied
+/// with `grim -o`, scaled to its logical size, and placed at its layout
+/// offset. Areas no powered output covers stay black. The image is exactly
+/// the desktop frame.
+///
+/// The generic path is kept only once the layout is known to be a single
+/// output: if the monitor query fails, the capture fails too, rather than
+/// copying one output of what may be a multi-monitor desktop.
+pub fn composite_desktop_capture() -> Option<Result<Vec<u8>>> {
+ let monitors: Vec<DisplayMonitor> = match query("j/monitors") {
+ Ok(monitors) => monitors,
+ Err(error) => return Some(Err(error)),
+ };
+ // One output: use the generic capture. It needs no desktop frame, so
+ // pixel-only callers such as trajectory recording keep working on a
+ // rotated output, which desktop actions refuse.
+ if monitors.len() <= 1 {
+ return None;
+ }
+ Some(desktop_frame_from_monitors(monitors).and_then(|frame| compose_desktop_capture(&frame)))
+}
+
+/// The desktop frame and whether capturing it needs per-output composition
+/// (more than one monitor in the layout), read from one compositor snapshot.
+pub struct DesktopCapturePlan {
+ pub frame: DesktopFrame,
+ pub composite: bool,
+}
+
+pub fn desktop_capture_plan() -> Result<DesktopCapturePlan> {
+ desktop_capture_plan_from_monitors(query("j/monitors")?)
+}
+
+fn desktop_capture_plan_from_monitors(monitors: Vec<DisplayMonitor>) -> Result<DesktopCapturePlan> {
+ let composite = monitors.len() > 1;
+ Ok(DesktopCapturePlan {
+ frame: desktop_frame_from_monitors(monitors)?,
+ composite,
+ })
+}
+
+/// Compose `frame` from per-output captures (see [`composite_desktop_capture`]).
+pub fn compose_desktop_capture(frame: &DesktopFrame) -> Result<Vec<u8>> {
+ let canvas = compose_frame(frame, |output| {
+ let png = capture_output_png(&output.name)?;
+ Ok(image::load_from_memory_with_format(&png, image::ImageFormat::Png)?.to_rgba8())
+ })?;
+ let mut encoded = std::io::Cursor::new(Vec::new());
+ image::DynamicImage::ImageRgba8(canvas).write_to(&mut encoded, image::ImageFormat::Png)?;
+ Ok(encoded.into_inner())
+}
+
+fn capture_output_png(name: &str) -> Result<Vec<u8>> {
+ // The PNG is decoded right away, so skip compression.
+ let out = std::process::Command::new("grim")
+ .args(["-t", "png", "-l", "0", "-o", name, "-"])
+ .output()
+ .context("grim is required for multi-monitor Hyprland desktop capture")?;
+ if !out.status.success() || out.stdout.is_empty() {
+ bail!(
+ "grim could not capture output {name}: {}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ }
+ Ok(out.stdout)
+}
+
+/// Place each output's capture at its logical rectangle inside the frame. A
+/// scaled output's capture is resized to its logical size, which must be a
+/// uniform scaling of the captured image.
+fn compose_frame(
+ frame: &DesktopFrame,
+ mut capture: impl FnMut(&FrameOutput) -> Result<image::RgbaImage>,
+) -> Result<image::RgbaImage> {
+ let mut canvas = image::RgbaImage::new(frame.width, frame.height);
+ for output in &frame.outputs {
+ let mut image = capture(output)?;
+ if (image.width(), image.height()) != (output.width, output.height) {
+ let scale_x = f64::from(image.width()) / f64::from(output.width);
+ let scale_y = f64::from(image.height()) / f64::from(output.height);
+ if (scale_x - scale_y).abs() > 0.01 {
+ bail!(
+ "output {} captured at {}x{}, which does not scale uniformly to its {}x{} \
+ logical size",
+ output.name,
+ image.width(),
+ image.height(),
+ output.width,
+ output.height
+ );
+ }
+ image = image::imageops::resize(
+ &image,
+ output.width,
+ output.height,
+ image::imageops::FilterType::Lanczos3,
+ );
+ }
+ let (left, top) = frame.from_layout(output.x, output.y);
+ image::imageops::replace(&mut canvas, &image, i64::from(left), i64::from(top));
+ }
+ Ok(canvas)
}
/// wl_output transform of the single active output. Full-display screencopy
@@ -395,8 +789,13 @@ pub fn single_output_transform() -> Result<u32> {
pub fn list_windows() -> Result<Vec<Window>> {
let monitors: Vec<Monitor> = query("j/monitors")?;
+ // Windows on an output in DPMS standby are not visible while another
+ // output is on. With every output in standby the display is only idle,
+ // so its workspaces stay on screen.
+ let any_powered = monitors.iter().any(|m| m.dpms_status);
let active = monitors
.into_iter()
+ .filter(|m| m.dpms_status || !any_powered)
.flat_map(|m| [m.active_workspace.id, m.special_workspace.id])
.filter(|id| *id != 0)
.collect();
@@ -1015,10 +1414,12 @@ mod tests {
for ((mode_w, mode_h), scale, _) in SCALED_OUTPUTS {
let (frame_w, frame_h, _) =
screen_size_from_monitors(vec![scaled_monitor(mode_w, mode_h, scale)]).unwrap();
- let extent = super::super::select_virtual_pointer_extent(
- (mode_w, mode_h),
- Some((frame_w, frame_h)),
- );
+ let layout =
+ pointer_layout_from_monitors(vec![scaled_monitor(mode_w, mode_h, scale)]).unwrap();
+ let (origin_x, origin_y, extent_w, extent_h) =
+ super::super::select_virtual_pointer_space((mode_w, mode_h), Some(layout));
+ let extent = (extent_w, extent_h);
+ assert_eq!((origin_x, origin_y), (0, 0), "{mode_w}x{mode_h} @ {scale}");
assert_eq!(extent, (frame_w, frame_h), "{mode_w}x{mode_h} @ {scale}");
let landed = |(x, y): (u32, u32), (extent_w, extent_h): (u32, u32)| {
@@ -1056,6 +1457,275 @@ mod tests {
}
}
+ fn monitor_at(name: &str, x: i32, y: i32) -> DisplayMonitor {
+ let mut monitor = display_monitor();
+ (monitor.name, monitor.x, monitor.y) = (name.to_string(), x, y);
+ monitor
+ }
+
+ #[test]
+ fn desktop_frame_spans_every_powered_output() {
+ let frame =
+ desktop_frame_from_monitors(vec![monitor_at("A", -1920, 0), monitor_at("B", 0, 0)])
+ .unwrap();
+ assert_eq!(
+ (frame.x, frame.y, frame.width, frame.height),
+ (-1920, 0, 3840, 1080)
+ );
+ assert_eq!(frame.to_layout(1920, 10), (0, 10));
+ assert_eq!(frame.from_layout(-1920, 0), (0, 0));
+ assert_eq!(
+ screen_size_from_monitors(vec![monitor_at("A", 0, 0), monitor_at("B", 1920, 0)])
+ .unwrap(),
+ (3840, 1080, 1.0)
+ );
+ }
+
+ #[test]
+ fn desktop_frame_ignores_outputs_in_standby_or_disabled() {
+ let mut off = monitor_at("A", -1920, 0);
+ off.dpms_status = false;
+ let frame = desktop_frame_from_monitors(vec![off.clone(), monitor_at("B", 0, 0)]).unwrap();
+ assert_eq!((frame.x, frame.width, frame.outputs.len()), (0, 1920, 1));
+ // Only the left monitor on: the frame follows it to its layout offset.
+ let mut right_off = monitor_at("B", 0, 0);
+ right_off.disabled = true;
+ let frame =
+ desktop_frame_from_monitors(vec![monitor_at("A", -1920, 0), right_off]).unwrap();
+ assert_eq!((frame.x, frame.width), (-1920, 1920));
+ // Every output in standby: the display is idle, and the frame keeps it.
+ let frame = desktop_frame_from_monitors(vec![off]).unwrap();
+ assert_eq!(
+ (frame.x, frame.width, frame.outputs.len()),
+ (-1920, 1920, 1)
+ );
+ let mut disabled = monitor_at("A", 0, 0);
+ disabled.disabled = true;
+ assert!(desktop_frame_from_monitors(vec![disabled]).is_err());
+ }
+
+ /// #4161: a laptop panel with a second monitor stacked above it, so the
+ /// top output sits at a negative layout offset.
+ fn stacked_outputs() -> Vec<DisplayMonitor> {
+ vec![monitor_at("eDP-1", 0, 0), monitor_at("HDMI-A-1", 0, -1080)]
+ }
+
+ #[test]
+ fn desktop_frame_spans_outputs_stacked_at_a_negative_offset() {
+ let frame = desktop_frame_from_monitors(stacked_outputs()).unwrap();
+ assert_eq!(
+ (frame.x, frame.y, frame.width, frame.height, frame.scale),
+ (0, -1080, 1920, 2160, 1.0)
+ );
+ assert_eq!(frame.from_layout(0, -1080), (0, 0));
+ assert_eq!(frame.from_layout(0, 0), (0, 1080));
+ assert_eq!(frame.to_layout(960, 540), (960, -540));
+ assert_eq!(
+ pointer_layout_from_monitors(stacked_outputs()).unwrap(),
+ (0, -1080, 1920, 2160)
+ );
+ }
+
+ #[test]
+ fn desktop_frame_mixes_output_scales_in_logical_pixels() {
+ let mut laptop = scaled_monitor(2160, 1350, 1.6666666);
+ laptop.name = "eDP-1".into();
+ let mut external = monitor_at("DP-1", 1296, 0);
+ (external.width, external.height) = (2560, 1440);
+ let frame = desktop_frame_from_monitors(vec![laptop.clone(), external.clone()]).unwrap();
+ assert_eq!(
+ (frame.x, frame.y, frame.width, frame.height),
+ (0, 0, 3856, 1440)
+ );
+ assert_eq!(frame.scale, 1.6666666);
+ assert_eq!(
+ frame
+ .outputs
+ .iter()
+ .map(|o| (o.name.as_str(), o.x, o.width, o.height))
+ .collect::<Vec<_>>(),
+ [("eDP-1", 0, 1296, 810), ("DP-1", 1296, 2560, 1440)]
+ );
+ assert_eq!(
+ pointer_layout_from_monitors(vec![laptop, external]).unwrap(),
+ (0, 0, 3856, 1440)
+ );
+ }
+
+ #[test]
+ fn mirrored_outputs_have_no_area_in_the_frame_or_pointer_layout() {
+ let mut mirror = monitor_at("HDMI-A-1", 1920, 0);
+ mirror.mirror_of = "eDP-1".into();
+ let monitors = vec![monitor_at("eDP-1", 0, 0), mirror];
+ let frame = desktop_frame_from_monitors(monitors.clone()).unwrap();
+ assert_eq!(
+ (frame.width, frame.height, frame.outputs.len()),
+ (1920, 1080, 1)
+ );
+ assert_eq!(
+ pointer_layout_from_monitors(monitors).unwrap(),
+ (0, 0, 1920, 1080)
+ );
+ }
+
+ #[test]
+ fn screen_report_describes_the_same_snapshot_as_its_frame() {
+ let mut off = monitor_at("C", 1920, 0);
+ off.dpms_status = false;
+ let (frame, report) = screen_report_from_monitors(vec![
+ monitor_at("A", -1920, 0),
+ monitor_at("B", 0, 0),
+ off,
+ ])
+ .unwrap();
+ assert_eq!((frame.x, frame.width, frame.height), (-1920, 3840, 1080));
+ let report = report.as_array().unwrap();
+ assert_eq!(report.len(), 3);
+ assert_eq!(
+ (report[0]["frame_x"].as_i64(), report[1]["frame_x"].as_i64()),
+ (Some(0), Some(1920))
+ );
+ assert_eq!(
+ (
+ report[2]["powered"].as_bool(),
+ report[2]["frame_x"].as_i64()
+ ),
+ (Some(false), None)
+ );
+ assert!(screen_report_from_monitors(vec![]).is_err());
+ }
+
+ #[test]
+ fn window_geometry_is_rebased_onto_the_frame_origin() {
+ let frame =
+ desktop_frame_from_monitors(vec![monitor_at("A", -1920, 0), monitor_at("B", 0, 0)])
+ .unwrap();
+ let mut windows = vec![crate::x11::WindowInfo {
+ xid: 1,
+ pid: Some(42),
+ app_name: "fixture".into(),
+ title: "Fixture".into(),
+ is_on_screen: true,
+ z_index: None,
+ x: -1820,
+ y: 36,
+ width: 800,
+ height: 600,
+ }];
+ frame.rebase_windows(&mut windows);
+ assert_eq!((windows[0].x, windows[0].y), (100, 36));
+ }
+
+ #[test]
+ fn capture_plan_composes_every_layout_with_more_than_one_monitor() {
+ let plan = desktop_capture_plan_from_monitors(vec![monitor_at("A", 0, 0)]).unwrap();
+ assert!(!plan.composite);
+ // A second monitor, even in standby, means the generic capture (which
+ // copies one output) cannot be trusted to be the frame.
+ let mut standby = monitor_at("B", 1920, 0);
+ standby.dpms_status = false;
+ let plan =
+ desktop_capture_plan_from_monitors(vec![monitor_at("A", 0, 0), standby]).unwrap();
+ assert!(plan.composite);
+ assert_eq!((plan.frame.width, plan.frame.outputs.len()), (1920, 1));
+ }
+
+ #[test]
+ fn pointer_space_falls_back_only_for_a_single_unqualified_output() {
+ let mut rotated = monitor_at("B", 0, 0);
+ rotated.transform = 1;
+ // One rotated output: its logical rectangle (axes swapped) is the layout.
+ assert_eq!(
+ pointer_space_from_monitors(vec![rotated.clone()]).unwrap(),
+ Some((0, 0, 1080, 1920))
+ );
+ // One flipped output stays unqualified: its own mode is the whole layout.
+ let mut flipped = monitor_at("B", 0, 0);
+ flipped.transform = 5;
+ assert_eq!(pointer_space_from_monitors(vec![flipped]).unwrap(), None);
+ // A rotated output in standby beside a powered one: no fallback is right.
+ rotated.dpms_status = false;
+ let monitors = vec![monitor_at("A", -1920, 0), rotated];
+ assert!(desktop_frame_from_monitors(monitors.clone()).is_ok());
+ let error = pointer_space_from_monitors(monitors.clone())
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("B has transform 1, in standby"), "{error}");
+ assert!(desktop_snapshot_from_monitors(monitors).is_err());
+ // A qualified layout is used as is.
+ assert_eq!(
+ pointer_space_from_monitors(vec![monitor_at("A", -1920, 0), monitor_at("B", 0, 0)])
+ .unwrap(),
+ Some((-1920, 0, 3840, 1080))
+ );
+ }
+
+ #[test]
+ fn frame_points_off_every_output_are_detected() {
+ // L-shaped layout: a gap at the bottom right of the bounding box.
+ let frame =
+ desktop_frame_from_monitors(vec![monitor_at("A", 0, 0), monitor_at("B", 1920, -1080)])
+ .unwrap();
+ assert_eq!(
+ (frame.x, frame.y, frame.width, frame.height),
+ (0, -1080, 3840, 2160)
+ );
+ assert!(frame.output_contains_layout(10, 10));
+ assert!(frame.output_contains_layout(1920, -1080));
+ assert!(frame.output_contains_layout(3839, -1));
+ assert!(!frame.output_contains_layout(1920, 0));
+ assert!(!frame.output_contains_layout(10, -10));
+ assert!(!frame.output_contains_layout(3840, -1));
+ }
+
+ #[test]
+ fn desktop_frame_allows_rotation_only_for_a_lone_output() {
+ let mut rotated = monitor_at("A", 0, 0);
+ rotated.transform = 1;
+ let frame = desktop_frame_from_monitors(vec![rotated.clone()]).unwrap();
+ assert_eq!((frame.width, frame.height), (1080, 1920));
+ assert!(desktop_frame_from_monitors(vec![rotated, monitor_at("B", 1080, 0)]).is_err());
+ let mut flipped = monitor_at("A", 0, 0);
+ flipped.transform = 4;
+ assert!(desktop_frame_from_monitors(vec![flipped]).is_err());
+ }
+
+ #[test]
+ fn pointer_layout_keeps_outputs_in_standby() {
+ let mut standby = monitor_at("HDMI-A-1", 0, -1080);
+ standby.dpms_status = false;
+ let monitors = vec![monitor_at("eDP-1", 0, 0), standby];
+ let frame = desktop_frame_from_monitors(monitors.clone()).unwrap();
+ assert_eq!((frame.y, frame.height), (0, 1080));
+ assert_eq!(
+ pointer_layout_from_monitors(monitors).unwrap(),
+ (0, -1080, 1920, 2160)
+ );
+ }
+
+ /// A desktop-frame point must land on the same layout point after the
+ /// pointer maps `abs / extent` across its layout box.
+ #[test]
+ fn frame_points_reach_the_pointer_layout_at_a_negative_offset() {
+ let frame = desktop_frame_from_monitors(stacked_outputs()).unwrap();
+ let layout = pointer_layout_from_monitors(stacked_outputs()).unwrap();
+ let (origin_x, origin_y, extent_w, extent_h) =
+ super::super::select_virtual_pointer_space((1920, 1080), Some(layout));
+ for point in [(0, 0), (10, 80), (960, 1079), (960, 1080), (1919, 2159)] {
+ let (layout_x, layout_y) = frame.to_layout(point.0, point.1);
+ let (abs_x, abs_y) = super::super::pointer_abs(
+ origin_x, origin_y, extent_w, extent_h, layout_x, layout_y,
+ );
+ let landed = (
+ layout.0
+ + (f64::from(abs_x) / f64::from(extent_w) * f64::from(layout.2)).round() as i32,
+ layout.1
+ + (f64::from(abs_y) / f64::from(extent_h) * f64::from(layout.3)).round() as i32,
+ );
+ assert_eq!(landed, (layout_x, layout_y), "frame point {point:?}");
+ }
+ }
+
#[test]
fn display_identity_reports_the_logical_frame_of_rotated_outputs() {
for (transform, expected) in [(1, (1080, 1920)), (2, (1920, 1080)), (3, (1080, 1920))] {
@@ -1067,17 +1737,49 @@ mod tests {
}
#[test]
- fn display_identity_rejects_ambiguous_outputs_and_unsupported_frames() {
+ fn composed_frame_places_each_output_at_its_logical_rectangle() {
+ let red = image::Rgba([255, 0, 0, 255]);
+ let blue = image::Rgba([0, 0, 255, 255]);
+ let mut panel = monitor_at("panel", 0, 0);
+ (panel.width, panel.height) = (2, 2);
+ // A scale-2 output stacked above the panel: its physical 4x4 capture
+ // covers a 2x2 logical rectangle and must not spill onto the panel.
+ let mut above = scaled_monitor(4, 4, 2.0);
+ (above.name, above.y) = ("above".into(), -2);
+ let frame = desktop_frame_from_monitors(vec![panel, above]).unwrap();
+ let canvas = compose_frame(&frame, |output| {
+ Ok(match output.name.as_str() {
+ "above" => image::RgbaImage::from_pixel(4, 4, red),
+ _ => image::RgbaImage::from_pixel(2, 2, blue),
+ })
+ })
+ .unwrap();
+ assert_eq!(canvas.dimensions(), (2, 4));
+ for x in 0..2 {
+ assert_eq!(*canvas.get_pixel(x, 0), red);
+ assert_eq!(*canvas.get_pixel(x, 1), red);
+ assert_eq!(*canvas.get_pixel(x, 2), blue);
+ assert_eq!(*canvas.get_pixel(x, 3), blue);
+ }
+
+ let error = compose_frame(&frame, |_| Ok(image::RgbaImage::new(4, 2))).unwrap_err();
+ assert!(
+ error.to_string().contains("does not scale uniformly"),
+ "{error}"
+ );
+ }
+
+ #[test]
+ fn display_identity_rejects_missing_and_unsupported_frames() {
assert!(screen_size_from_monitors(vec![]).is_err());
- assert!(screen_size_from_monitors(vec![display_monitor(), display_monitor()]).is_err());
for scale in [0.0, f64::NAN, f64::INFINITY] {
let mut monitor = display_monitor();
monitor.scale = scale;
assert!(screen_size_from_monitors(vec![monitor]).is_err());
}
- for (x, y, transform) in [(100, 0, 0), (0, -100, 0), (0, 0, 4), (0, 0, 7)] {
+ for transform in [4, 7] {
let mut monitor = display_monitor();
- (monitor.x, monitor.y, monitor.transform) = (x, y, transform);
+ monitor.transform = transform;
assert!(screen_size_from_monitors(vec![monitor]).is_err());
}
}
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 c846df1d98..0909579d85 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
@@ -1154,6 +1154,14 @@ fn crop_png_to_rect(
/// first use per session.
/// 5. X11: existing root-window path.
pub fn screenshot_display_dispatch() -> anyhow::Result<Vec<u8>> {
+ if is_wayland() && hyprland::is_session() {
+ // The desktop action frame spans every powered output. The cascade
+ // below copies only the first output, so a multi-monitor layout is
+ // composed per output; a single output keeps the cascade.
+ if let Some(capture) = hyprland::composite_desktop_capture() {
+ return capture;
+ }
+ }
if is_wayland() {
// Tier 1: the opt-in GNOME compositor helper. It avoids probing
// wlroots-only protocols and captures the Shell stage without consent.
@@ -1308,9 +1316,87 @@ pub struct VptrSession {
pub seat: WlSeat,
pub vptr: ZwlrVirtualPointerV1,
/// `motion_absolute` extent, in the same frame as caller coordinates.
- /// See [`virtual_pointer_extent`].
+ /// See [`virtual_pointer_space`].
pub output_w: u32,
pub output_h: u32,
+ /// Layout position of pointer-space (0, 0). Callers pass layout
+ /// coordinates; [`VptrSession::abs`] converts them for `motion_absolute`.
+ pub origin_x: i32,
+ pub origin_y: i32,
+}
+
+impl VptrSession {
+ /// Layout point -> clamped `motion_absolute` coordinates.
+ pub fn abs(&self, x: i32, y: i32) -> (u32, u32) {
+ pointer_abs(
+ self.origin_x,
+ self.origin_y,
+ self.output_w,
+ self.output_h,
+ x,
+ y,
+ )
+ }
+}
+
+pub(crate) fn pointer_abs(
+ origin_x: i32,
+ origin_y: i32,
+ w: u32,
+ h: u32,
+ x: i32,
+ y: i32,
+) -> (u32, u32) {
+ (
+ x.saturating_sub(origin_x)
+ .clamp(0, (w as i32).saturating_sub(1)) as u32,
+ y.saturating_sub(origin_y)
+ .clamp(0, (h as i32).saturating_sub(1)) as u32,
+ )
+}
+
+/// How one desktop-scope action is addressed: desktop-frame points (from
+/// `get_desktop_state`) convert to layout coordinates, and the virtual pointer
+/// is sized, from a single compositor snapshot. Other compositors keep the
+/// frame at the layout origin and the pointer on the output's own mode.
+#[derive(Clone, Debug, Default)]
+pub struct DesktopInputSpace {
+ snapshot: Option<hyprland::DesktopSnapshot>,
+}
+
+impl DesktopInputSpace {
+ pub fn current() -> anyhow::Result<Self> {
+ let snapshot = if is_wayland() && hyprland::is_session() {
+ Some(hyprland::desktop_snapshot()?)
+ } else {
+ None
+ };
+ Ok(Self { snapshot })
+ }
+
+ /// Layout coordinates of a desktop-frame point.
+ pub fn to_layout(&self, x: i32, y: i32) -> (i32, i32) {
+ self.snapshot
+ .as_ref()
+ .map_or((x, y), |snapshot| snapshot.frame.to_layout(x, y))
+ }
+
+ /// Layout coordinates of a desktop-frame point that input may target.
+ /// On a multi-monitor frame a point in a gap or on an output in standby
+ /// is refused rather than left for the compositor to move to another
+ /// output edge. A single output keeps the existing edge clamping.
+ pub fn input_layout(&self, x: i32, y: i32) -> anyhow::Result<(i32, i32)> {
+ let Some(snapshot) = self.snapshot.as_ref() else {
+ return Ok((x, y));
+ };
+ let (layout_x, layout_y) = snapshot.frame.to_layout(x, y);
+ anyhow::ensure!(
+ snapshot.frame.outputs.len() <= 1
+ || snapshot.frame.output_contains_layout(layout_x, layout_y),
+ "desktop point ({x}, {y}) is not on a powered monitor in the current layout; call get_desktop_state again"
+ );
+ Ok((layout_x, layout_y))
+ }
}
impl VptrSession {
@@ -1352,31 +1438,31 @@ pub(crate) fn compositor_logical_frame() -> Option<anyhow::Result<(u32, u32)>> {
.then(|| hyprland::screen_size().map(|(width, height, _scale)| (width, height)))
}
-/// Extent to pass with `zwlr_virtual_pointer_v1::motion_absolute`. The
-/// compositor maps `x / x_extent` onto its logical layout, so the extent must
-/// be in the caller's coordinate frame. Hyprland window geometry, window
-/// captures, and desktop captures are logical; a scaled output's `wl_output`
-/// mode is physical and would land every motion at `1 / scale` of its target.
-/// Layouts the Hyprland adapter cannot qualify (rotated, off-origin, or
-/// multiple outputs) keep the first output's mode until that adapter
-/// publishes a frame for them.
-fn virtual_pointer_extent(output_mode: (u32, u32)) -> (u32, u32) {
- let logical = compositor_logical_frame().and_then(|frame| {
- frame
- .map_err(|error| {
- tracing::debug!("virtual pointer keeps the wl_output mode extent: {error:#}")
- })
- .ok()
- });
- select_virtual_pointer_extent(output_mode, logical)
+/// Pointer space for `zwlr_virtual_pointer_v1::motion_absolute`, as
+/// `(origin_x, origin_y, extent_w, extent_h)`. The compositor maps
+/// `x / x_extent` onto its logical layout, so the extent must be in the
+/// caller's coordinate frame. Hyprland maps absolute motion across the
+/// bounding box of every enabled output's logical rectangle, not just the
+/// first `wl_output`; a scaled output's `wl_output` mode is physical and
+/// would land every motion at `1 / scale` of its target. A single output
+/// the Hyprland adapter cannot qualify (a rotated one) keeps its own mode
+/// until that adapter publishes a layout for it; with several outputs that
+/// fallback would misplace every motion, so it is an error instead.
+fn virtual_pointer_space(output_mode: (u32, u32)) -> anyhow::Result<(i32, i32, u32, u32)> {
+ let layout = if hyprland::is_session() {
+ hyprland::pointer_space()?
+ } else {
+ None
+ };
+ Ok(select_virtual_pointer_space(output_mode, layout))
}
-fn select_virtual_pointer_extent(
+fn select_virtual_pointer_space(
output_mode: (u32, u32),
- compositor_logical: Option<(u32, u32)>,
-) -> (u32, u32) {
- let (width, height) = compositor_logical.unwrap_or(output_mode);
- (width.max(1), height.max(1))
+ compositor_layout: Option<(i32, i32, u32, u32)>,
+) -> (i32, i32, u32, u32) {
+ let (x, y, width, height) = compositor_layout.unwrap_or((0, 0, output_mode.0, output_mode.1));
+ (x, y, width.max(1), height.max(1))
}
/// Bind manager + seat + virtual-pointer + first output, optionally activate a
@@ -1386,6 +1472,15 @@ fn select_virtual_pointer_extent(
/// pointer event in *output* coordinates and rely on the activated toplevel
/// covering the centre.
pub fn open_vptr_session(activate_window_id: Option<u64>) -> anyhow::Result<VptrSession> {
+ open_vptr_session_in(activate_window_id, None)
+}
+
+/// [`open_vptr_session`] sized from `snapshot` when a desktop action was
+/// addressed in one.
+fn open_vptr_session_in(
+ activate_window_id: Option<u64>,
+ snapshot: Option<&hyprland::DesktopSnapshot>,
+) -> anyhow::Result<VptrSession> {
let conn = Connection::connect_to_env()?;
let mut queue = conn.new_event_queue::<State>();
let qh = queue.handle();
@@ -1445,7 +1540,12 @@ pub fn open_vptr_session(activate_window_id: Option<u64>) -> anyhow::Result<Vptr
}
let vptr = mgr.create_virtual_pointer(Some(&seat), &qh, ());
- let (output_w, output_h) = virtual_pointer_extent((state.output_w, state.output_h));
+ let (origin_x, origin_y, output_w, output_h) = match snapshot {
+ Some(snapshot) => {
+ select_virtual_pointer_space((state.output_w, state.output_h), snapshot.pointer)
+ }
+ None => virtual_pointer_space((state.output_w, state.output_h))?,
+ };
Ok(VptrSession {
conn,
queue,
@@ -1454,6 +1554,8 @@ pub fn open_vptr_session(activate_window_id: Option<u64>) -> anyhow::Result<Vptr
vptr,
output_w,
output_h,
+ origin_x,
+ origin_y,
})
}
@@ -1639,7 +1741,7 @@ fn event_time_ms() -> u32 {
/// to discriminate single vs. double clicks.
pub fn click(window_id: u64, x: i32, y: i32, count: u32, button: u8) -> anyhow::Result<()> {
with_libei_fallback(
- || click_vptr(Some(window_id), x, y, count, button),
+ || click_vptr(Some(window_id), x, y, count, button, None),
|| {
libei_wait_pointer_ready()?;
activate_window_for_input(window_id)?;
@@ -1657,7 +1759,7 @@ pub fn click(window_id: u64, x: i32, y: i32, count: u32, button: u8) -> anyhow::
#[cfg(feature = "portal-input")]
pub fn click_focused(x: i32, y: i32, count: u32, button: u8) -> anyhow::Result<()> {
with_libei_fallback(
- || click_vptr(None, x, y, count, button),
+ || click_vptr(None, x, y, count, button, None),
|| {
libei_wait_pointer_ready()?;
if let Some((pid, window_id)) = current_foreground_target() {
@@ -1670,19 +1772,26 @@ pub fn click_focused(x: i32, y: i32, count: u32, button: u8) -> anyhow::Result<(
#[cfg(not(feature = "portal-input"))]
pub fn click_focused(x: i32, y: i32, count: u32, button: u8) -> anyhow::Result<()> {
- click_vptr(None, x, y, count, button)
+ click_vptr(None, x, y, count, button, None)
}
/// Click a desktop-absolute point without selecting or activating a toplevel.
/// This is the Wayland peer of an XTest root-window click and is used only by
/// the explicit desktop capture scope.
-pub fn click_desktop(x: i32, y: i32, count: u32, button: u8) -> anyhow::Result<()> {
+pub fn click_desktop(
+ space: &DesktopInputSpace,
+ x: i32,
+ y: i32,
+ count: u32,
+ button: u8,
+) -> anyhow::Result<()> {
if is_inject_mode() {
let btn = evdev_button(button as u32);
return inject_send(&[format!("d {x} {y} {} {btn}", count.max(1))]);
}
+ let (x, y) = space.input_layout(x, y)?;
with_libei_fallback(
- || click_vptr(None, x, y, count, button),
+ || click_vptr(None, x, y, count, button, space.snapshot.as_ref()),
|| libei_click(x, y, count, button),
)
}
@@ -1695,17 +1804,16 @@ fn click_vptr(
y: i32,
count: u32,
button: u8,
+ snapshot: Option<&hyprland::DesktopSnapshot>,
) -> anyhow::Result<()> {
- let mut sess = open_vptr_session(window_id)?;
+ let mut sess = open_vptr_session_in(window_id, snapshot)?;
std::thread::sleep(std::time::Duration::from_millis(40));
let (w, h) = (sess.output_w, sess.output_h);
- let (px, py) = if x == 0 && y == 0 {
- ((w / 2) as i32, (h / 2) as i32)
+ let (px, py) = if x == 0 && y == 0 && !hyprland::is_session() {
+ (w / 2, h / 2)
} else {
- (x, y)
+ sess.abs(x, y)
};
- let px = px.clamp(0, w as i32 - 1) as u32;
- let py = py.clamp(0, h as i32 - 1) as u32;
let btn = evdev_pointer_button(button);
for i in 0..count.max(1) {
if i > 0 {
@@ -1730,7 +1838,7 @@ fn click_vptr(
}
// Keep the synthetic-cursor registry in sync with the warp we just
// performed so a subsequent `get_cursor_position` reflects reality.
- record_synth_cursor(px as i32, py as i32);
+ record_synth_cursor(sess.origin_x + px as i32, sess.origin_y + py as i32);
sess.vptr.destroy();
sess.queue.roundtrip(&mut sess.state)?;
Ok(())
@@ -1834,7 +1942,7 @@ pub fn scroll_at(
) -> anyhow::Result<()> {
let direction = direction.to_string();
with_libei_fallback(
- || scroll_vptr(Some(window_id), point, &direction, amount),
+ || scroll_vptr(Some(window_id), point, &direction, amount, None),
|| {
libei_wait_scroll_ready()?;
activate_window_for_input(window_id)?;
@@ -1847,13 +1955,28 @@ pub fn scroll_at(
}
/// Scroll at a desktop-absolute point without activating a named toplevel.
-pub fn scroll_desktop(x: i32, y: i32, direction: &str, amount: u32) -> anyhow::Result<()> {
+pub fn scroll_desktop(
+ space: &DesktopInputSpace,
+ x: i32,
+ y: i32,
+ direction: &str,
+ amount: u32,
+) -> anyhow::Result<()> {
if is_inject_mode() {
return inject_scroll_desktop(x, y, direction, amount);
}
+ let (x, y) = space.input_layout(x, y)?;
let direction = direction.to_string();
with_libei_fallback(
- || scroll_vptr(None, Some((x, y)), &direction, amount),
+ || {
+ scroll_vptr(
+ None,
+ Some((x, y)),
+ &direction,
+ amount,
+ space.snapshot.as_ref(),
+ )
+ },
|| {
libei_wait_scroll_ready()?;
libei_move_absolute(x, y)?;
@@ -1868,13 +1991,13 @@ fn scroll_vptr(
point: Option<(i32, i32)>,
direction: &str,
amount: u32,
+ snapshot: Option<&hyprland::DesktopSnapshot>,
) -> anyhow::Result<()> {
- let mut sess = open_vptr_session(window_id)?;
+ let mut sess = open_vptr_session_in(window_id, snapshot)?;
if let Some((x, y)) = point {
- let px = x.clamp(0, (sess.output_w as i32).saturating_sub(1)) as u32;
- let py = y.clamp(0, (sess.output_h as i32).saturating_sub(1)) as u32;
+ let (px, py) = sess.abs(x, y);
sess.point_at(px, py)?;
- record_synth_cursor(px as i32, py as i32);
+ record_synth_cursor(sess.origin_x + px as i32, sess.origin_y + py as i32);
std::thread::sleep(std::time::Duration::from_millis(15));
}
let (axis, sign): (Axis, i32) = match direction.to_ascii_lowercase().as_str() {
@@ -1937,21 +2060,34 @@ pub fn last_synth_cursor_pos() -> Option<(i32, i32)> {
/// the synthetic-cursor registry so `last_synth_cursor_pos` can report it.
pub fn move_cursor_absolute(window_id: Option<u64>, x: i32, y: i32) -> anyhow::Result<()> {
with_libei_fallback(
- || move_cursor_absolute_vptr(window_id, x, y),
+ || move_cursor_absolute_vptr(window_id, x, y, None),
+ || libei_move_absolute(x, y),
+ )
+}
+
+/// Warp the cursor to a desktop-frame point (the `get_desktop_state` frame).
+pub fn move_cursor_desktop(space: &DesktopInputSpace, x: i32, y: i32) -> anyhow::Result<()> {
+ let (x, y) = space.input_layout(x, y)?;
+ with_libei_fallback(
+ || move_cursor_absolute_vptr(None, x, y, space.snapshot.as_ref()),
|| libei_move_absolute(x, y),
)
}
/// wlroots virtual-pointer implementation of [`move_cursor_absolute`].
-fn move_cursor_absolute_vptr(window_id: Option<u64>, x: i32, y: i32) -> anyhow::Result<()> {
- let mut sess = open_vptr_session(window_id)?;
+fn move_cursor_absolute_vptr(
+ window_id: Option<u64>,
+ x: i32,
+ y: i32,
+ snapshot: Option<&hyprland::DesktopSnapshot>,
+) -> anyhow::Result<()> {
+ let mut sess = open_vptr_session_in(window_id, snapshot)?;
let (w, h) = (sess.output_w, sess.output_h);
- let px = x.clamp(0, (w as i32).saturating_sub(1)) as u32;
- let py = y.clamp(0, (h as i32).saturating_sub(1)) as u32;
+ let (px, py) = sess.abs(x, y);
sess.vptr.motion_absolute(event_time_ms(), px, py, w, h);
sess.vptr.frame();
sess.queue.roundtrip(&mut sess.state)?;
- record_synth_cursor(px as i32, py as i32);
+ record_synth_cursor(sess.origin_x + px as i32, sess.origin_y + py as i32);
sess.vptr.destroy();
sess.queue.roundtrip(&mut sess.state)?;
Ok(())
@@ -1972,7 +2108,18 @@ pub fn drag(
) -> anyhow::Result<()> {
let ((from_x, from_y), (to_x, to_y)) = (from, to);
with_libei_fallback(
- || drag_vptr(Some(window_id), from_x, from_y, to_x, to_y, steps, button),
+ || {
+ drag_vptr(
+ Some(window_id),
+ from_x,
+ from_y,
+ to_x,
+ to_y,
+ steps,
+ button,
+ None,
+ )
+ },
|| {
libei_wait_pointer_ready()?;
activate_window_for_input(window_id)?;
@@ -1983,6 +2130,7 @@ pub fn drag(
/// Drag through desktop-absolute points without activating a named toplevel.
pub fn drag_desktop(
+ space: &DesktopInputSpace,
from_x: i32,
from_y: i32,
to_x: i32,
@@ -1991,8 +2139,21 @@ pub fn drag_desktop(
duration_ms: u64,
button: u8,
) -> anyhow::Result<()> {
+ let (from_x, from_y) = space.input_layout(from_x, from_y)?;
+ let (to_x, to_y) = space.input_layout(to_x, to_y)?;
with_libei_fallback(
- || drag_vptr(None, from_x, from_y, to_x, to_y, steps, button),
+ || {
+ drag_vptr(
+ None,
+ from_x,
+ from_y,
+ to_x,
+ to_y,
+ steps,
+ button,
+ space.snapshot.as_ref(),
+ )
+ },
|| {
libei_wait_pointer_ready()?;
libei_drag(from_x, from_y, to_x, to_y, steps, duration_ms, button)
@@ -2010,17 +2171,14 @@ fn drag_vptr(
to_y: i32,
steps: u32,
button: u8,
+ snapshot: Option<&hyprland::DesktopSnapshot>,
) -> anyhow::Result<()> {
- let mut sess = open_vptr_session(window_id)?;
+ let mut sess = open_vptr_session_in(window_id, snapshot)?;
std::thread::sleep(std::time::Duration::from_millis(40));
let (w, h) = (sess.output_w, sess.output_h);
let btn = evdev_pointer_button(button);
- let clamp_xy = |x: i32, y: i32| -> (u32, u32) {
- (
- x.clamp(0, w as i32 - 1) as u32,
- y.clamp(0, h as i32 - 1) as u32,
- )
- };
+ let (origin_x, origin_y) = (sess.origin_x, sess.origin_y);
+ let clamp_xy = |x: i32, y: i32| pointer_abs(origin_x, origin_y, w, h, x, y);
let (fx, fy) = clamp_xy(from_x, from_y);
sess.vptr.motion_absolute(event_time_ms(), fx, fy, w, h);
sess.vptr.frame();
@@ -2049,7 +2207,7 @@ fn drag_vptr(
sess.vptr.frame();
// Sync the synthetic-cursor registry with the drag endpoint so a
// subsequent `get_cursor_position` reports where we left the pointer.
- record_synth_cursor(tx as i32, ty as i32);
+ record_synth_cursor(origin_x + tx as i32, origin_y + ty as i32);
sess.queue.roundtrip(&mut sess.state)?;
sess.vptr.destroy();
sess.queue.roundtrip(&mut sess.state)?;
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
index b17f395007..36d736e109 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
@@ -479,9 +479,7 @@ fn visible_cores_for_output<'a>(
let mut visible_cores: Vec<_> = cores
.iter()
.filter(|(_, core)| {
- core.visible
- && core.pos.0 >= -100.0
- && core.idle_alpha >= 0.004
+ core.is_revealed()
&& select_output(layouts, core.pos.0, core.pos.1)
.is_some_and(|selected| selected.id == output_id)
})
@@ -837,7 +835,7 @@ fn tick_all_cores(cores: &mut CursorMap<RenderStateCore>, dt: f64) -> Vec<Cursor
/// gated on a shown, placed cursor: a hidden cursor's motion is quiesced by
/// [`quiesce_hidden`] and never repaints a layer surface.
fn needs_frame_tick(core: &RenderStateCore) -> bool {
- core.visible && core.pos.0 >= -100.0 && core.needs_frame_tick()
+ core.visible && cursor_overlay::render_state::is_placed(core.pos) && core.needs_frame_tick()
}
fn quiesce_hidden(core: &mut RenderStateCore) {
@@ -875,7 +873,7 @@ fn redraw(
.render
.cursors
.values()
- .filter(|core| core.visible && core.pos.0 >= -100.0 && core.idle_alpha >= 0.004)
+ .filter(|core| core.is_revealed())
.map(|core| core.pos);
let (selected, targets) = frame_plan(
&layouts,
@@ -1476,6 +1474,42 @@ mod tests {
assert!(visible_cores_for_output(&cores, &layouts, 8).is_empty());
}
+ #[test]
+ fn a_cursor_on_a_monitor_left_of_the_origin_is_drawn_there() {
+ // A left-hand monitor puts real cursor positions far below zero; they
+ // must not be mistaken for the never-placed sentinel.
+ let layouts = vec![
+ OutputLayout {
+ id: 3,
+ origin_x: -3840,
+ origin_y: 0,
+ width: 3840,
+ height: 2160,
+ },
+ OutputLayout {
+ id: 4,
+ origin_x: 0,
+ origin_y: 0,
+ width: 3840,
+ height: 2160,
+ },
+ ];
+ let mut core = positioned_core();
+ core.pos = (-2220.0, 980.0);
+ let cores = CursorMap::from([("session".to_owned(), core)]);
+ assert_eq!(visible_cores_for_output(&cores, &layouts, 3).len(), 1);
+ assert!(visible_cores_for_output(&cores, &layouts, 4).is_empty());
+ // And it paints there: a 160 px crop of the left monitor around it.
+ let mut crop = tiny_skia::Pixmap::new(160, 160).unwrap();
+ cursor_overlay::paint_cursor(&mut crop, &cores["session"], -2300.0, 900.0, None, 1.0);
+ assert!(crop.pixels().iter().any(|pixel| pixel.alpha() > 0));
+ let unplaced = CursorMap::from([(
+ "session".to_owned(),
+ RenderStateCore::new(CursorConfig::default()),
+ )]);
+ assert!(visible_cores_for_output(&unplaced, &layouts, 3).is_empty());
+ }
+
#[test]
fn initial_configured_outputs_each_plan_one_transparent_frame() {
let layouts = three_monitor_layout();
@@ -1804,7 +1838,7 @@ mod tests {
));
let core = state.render.cursors.get("session-a").unwrap();
assert_eq!(core.session_label.as_deref(), Some("Synthetic session"));
- assert!(core.pos.0 < -50.0);
+ assert!(!cursor_overlay::render_state::is_placed(core.pos));
assert!(state.outputs.is_empty());
assert!(matches!(
rx.try_recv(),
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/persistent_vptr.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/persistent_vptr.rs
index 9ee2718e12..be594ba20f 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/persistent_vptr.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/persistent_vptr.rs
@@ -72,9 +72,12 @@ struct ActivePointer {
/// evdev codes of buttons currently held down. When this set becomes
/// empty the vptr is destroyed and the entry dropped from the map.
held: HashSet<u32>,
- /// Output extent at session open time — needed for motion_absolute.
+ /// Pointer-space extent and layout origin at session open time — needed
+ /// for motion_absolute.
out_w: u32,
out_h: u32,
+ origin_x: i32,
+ origin_y: i32,
}
/// Process-global command channel into the owner thread. Lazily started on
@@ -149,8 +152,7 @@ fn handle_press(
// as long as the Connection is alive).
let mut sess = open_vptr_session(Some(window_id))?;
let (w, h) = (sess.output_w, sess.output_h);
- let px = x.clamp(0, w as i32 - 1) as u32;
- let py = y.clamp(0, h as i32 - 1) as u32;
+ let (px, py) = sess.abs(x, y);
let btn = evdev_pointer_button(button);
sess.vptr.motion_absolute(0, px, py, w, h);
@@ -178,6 +180,8 @@ fn handle_press(
held,
out_w: w,
out_h: h,
+ origin_x: sess.origin_x,
+ origin_y: sess.origin_y,
},
);
Ok(())
@@ -194,8 +198,14 @@ fn handle_move(
"no held mouse button for cursor '{cursor_id}'; call mouse_button_down first"
)
})?;
- let px = x.clamp(0, entry.out_w as i32 - 1) as u32;
- let py = y.clamp(0, entry.out_h as i32 - 1) as u32;
+ let (px, py) = super::pointer_abs(
+ entry.origin_x,
+ entry.origin_y,
+ entry.out_w,
+ entry.out_h,
+ x,
+ y,
+ );
entry
.vptr
.motion_absolute(0, px, py, entry.out_w, entry.out_h);
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
index 3e67830a00..7c4dfff989 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
@@ -137,13 +137,42 @@ pub(crate) fn overlay_may_show_pixels() -> bool {
.is_some_and(|last| last.elapsed() < OVERLAY_CLEAR_GRACE)
}
+/// Whether the macOS overlay, which covers the main screen from (0, 0), draws
+/// a cursor at `pos`. This is the existing visibility gate: a cursor more
+/// than 50 points left of or above the main screen's origin is not drawn,
+/// session badge included. One predicate decides both painting and pixel
+/// presence, so they cannot disagree.
+fn on_main_screen(pos: (f64, f64)) -> bool {
+ pos.0 > -50.0 && pos.1 > -50.0
+}
+
fn cursor_may_paint(state: &RenderState) -> bool {
state.focus_rect.is_some()
|| (state.core.cfg.enabled
&& state.core.visible
&& state.core.idle_alpha > 0.0
- && state.core.pos.0 > -50.0
- && state.core.pos.1 > -50.0)
+ && on_main_screen(state.core.pos))
+}
+
+/// Paint every cursor the main-screen overlay draws into `pm`.
+fn paint_main_screen(pm: &mut tiny_skia::Pixmap, map: &RenderMap, backing_scale: f32) {
+ for rs in map.cursors.values() {
+ if !on_main_screen(rs.core.pos) {
+ continue;
+ }
+ let focus = rs.focus_rect.map(|rect| FocusRect {
+ rect,
+ t: rs.focus_rect_t,
+ });
+ cursor_overlay::paint_cursor(
+ pm,
+ &rs.core,
+ 0.0,
+ 0.0, // macOS uses screen-local coords (no origin offset)
+ focus,
+ backing_scale,
+ );
+ }
}
/// Screen-global geometry kept beside the shared keyed render map
@@ -335,7 +364,7 @@ pub fn current_theme_state(
/// the sentinel and only `ClickPulse` snapped a static arrow, which is easy to
/// miss. See the AX-no-glide report.
///
-/// No-op when the cursor is already on-screen (pos.0 > -50.0) or absent. The
+/// No-op when the cursor is already placed (`is_placed`) or absent. The
/// seed is clamped to the main screen frame so it never starts off-display.
/// Returns true if a seed was applied (i.e. the cursor was at the sentinel and
/// is now primed to glide).
@@ -366,7 +395,7 @@ pub async fn animate_cursor_to(key: CursorKey, x: f64, y: f64) {
return;
}
// Seed a sentinel cursor on-screen so the MoveTo below glides instead of
- // being short-circuited. After this the cursor's pos.0 > -50.0, so the
+ // being short-circuited. After this the cursor is placed (`is_placed`), so the
// should-animate check passes on the first action just like later ones.
seed_start_if_sentinel(&key, x, y);
@@ -376,7 +405,7 @@ pub async fn animate_cursor_to(key: CursorKey, x: f64, y: f64) {
let guard = RENDER.lock().unwrap();
matches!(
guard.as_ref().and_then(|m| m.cursors.get(&key)),
- Some(rs) if rs.core.cfg.enabled && rs.core.pos.0 > -50.0
+ Some(rs) if rs.core.cfg.enabled && cursor_overlay::render_state::is_placed(rs.core.pos)
)
};
if !should_animate {
@@ -578,10 +607,7 @@ impl RenderEntry for RenderState {
fn needs_frame_tick(&self) -> bool {
self.core.needs_frame_tick()
|| self.focus_rect.is_some()
- || (self.core.motion.idle_hide_ms > 0.0
- && self.core.visible
- && self.core.pos.0 >= -100.0
- && self.core.idle_alpha >= 0.004)
+ || (self.core.motion.idle_hide_ms > 0.0 && self.core.is_revealed())
}
}
@@ -933,20 +959,7 @@ fn render_loop(
.unwrap_or_else(|| tiny_skia::Pixmap::new(1, 1).unwrap());
let backing_scale_f32 = scale as f32;
note_overlay_frame(map.cursors.values().any(cursor_may_paint));
- for (_k, rs) in &map.cursors {
- let focus = rs.focus_rect.map(|rect| FocusRect {
- rect,
- t: rs.focus_rect_t,
- });
- cursor_overlay::paint_cursor(
- &mut pm,
- &rs.core,
- 0.0,
- 0.0, // macOS uses screen-local coords (no origin offset)
- focus,
- backing_scale_f32,
- );
- }
+ paint_main_screen(&mut pm, map, backing_scale_f32);
pm
} else {
break;
@@ -1049,8 +1062,7 @@ fn hardware_cursor_position() -> Option<(f64, f64)> {
fn cursor_is_externally_visible(state: &RenderState) -> bool {
state.core.cfg.enabled
&& state.core.visible
- && state.core.pos.0 > -50.0
- && state.core.pos.1 > -50.0
+ && on_main_screen(state.core.pos)
&& state.core.idle_alpha >= 0.004
}
@@ -1494,6 +1506,27 @@ mod tests {
assert!(!cursor_is_externally_visible(&map.cursors["sessA"]));
}
+ #[test]
+ fn a_cursor_left_of_the_main_screen_paints_nothing_there() {
+ let mut map = empty_map();
+ let state = placed(&mut map, "sessA");
+ state.core.session_label = Some("A".to_owned());
+ let painted = |map: &RenderMap| {
+ let mut pm = tiny_skia::Pixmap::new(100, 100).unwrap();
+ paint_main_screen(&mut pm, map, 1.0);
+ pm.pixels().iter().any(|pixel| pixel.alpha() > 0)
+ };
+ assert!(painted(&map));
+ assert!(cursor_may_paint(&map.cursors["sessA"]));
+
+ // Placed on a display left of the main screen: the label would clamp
+ // its badge into the main-screen pixmap if this cursor were painted.
+ map.cursors.get_mut("sessA").unwrap().core.pos = (-200.0, 30.0);
+ assert!(!painted(&map));
+ assert!(!cursor_may_paint(&map.cursors["sessA"]));
+ assert!(!cursor_is_externally_visible(&map.cursors["sessA"]));
+ }
+
#[test]
fn removal_through_the_adapter_releases_only_that_arrival_waiter() {
let mut map = empty_map();
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
index 389b6c7abd..5454d8d7e6 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
@@ -320,12 +320,7 @@ pub fn is_visible_for_session(key: &str) -> bool {
guard
.as_ref()
.and_then(|map| map.cursors.get(key))
- .map(|rs| {
- rs.core.cfg.enabled
- && rs.core.visible
- && rs.core.idle_alpha >= 0.004
- && rs.core.pos.0 >= -100.0
- })
+ .map(|rs| rs.core.cfg.enabled && rs.core.is_revealed())
})
.unwrap_or(false)
}
@@ -371,7 +366,7 @@ pub fn current_position(key: &str) -> (f64, f64) {
.and_then(|m| m.cursors.get(key))
.map(|rs| rs.core.pos)
})
- .unwrap_or((-200.0, -200.0))
+ .unwrap_or(cursor_overlay::render_state::UNPLACED_POS)
}
/// Seed a brand-new (sentinel-positioned) cursor at an on-screen start point
@@ -411,7 +406,7 @@ pub async fn animate_cursor_to(key: CursorKey, x: f64, y: f64) {
let guard = RENDER.lock().unwrap();
matches!(
guard.as_ref().and_then(|m| m.cursors.get(&key)),
- Some(rs) if rs.core.cfg.enabled && rs.core.pos.0 > -50.0
+ Some(rs) if rs.core.cfg.enabled && cursor_overlay::render_state::is_placed(rs.core.pos)
)
};
if !should_animate {
@@ -520,7 +515,7 @@ impl RenderState {
&& self.core.click_t.is_none()
&& self.core.motion.idle_hide_ms > 0.0
&& self.core.visible
- && self.core.pos.0 >= -100.0
+ && cursor_overlay::render_state::is_placed(self.core.pos)
&& self.core.idle_alpha >= 1.0
}
}
@@ -902,7 +897,7 @@ fn composite_dirty(map: &RenderMap) -> Option<DirtyRect> {
// (mirrors paint_cursor's own visibility early-return).
let mut current: Option<DirtyRect> = None;
for rs in map.cursors.values() {
- if !rs.core.visible || rs.core.pos.0 < -100.0 || rs.core.idle_alpha < 0.004 {
+ if !rs.core.is_revealed() {
continue;
}
let cx = (rs.core.pos.0 - screen.virt_x as f64).round() as i32;