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): verify native Hyprland capture and observation (#3557)

Francesco Bonacci3513443c9df8
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index dbccdb19a4..91491f5f02 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -3213,6 +3213,7 @@ dependencies = [
"async-trait",
"atspi",
"base64",
+ "bitflags 2.11.1",
"calloop",
"clipboard-rs",
"crossbeam-channel",
@@ -3234,6 +3235,7 @@ dependencies = [
"reis",
"serde",
"serde_json",
+ "socket2",
"tempfile",
"thiserror 1.0.69",
"tiny-skia",
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
index 43aba3df93..3b89031233 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
@@ -71,18 +71,19 @@ pub const STALE_TOKEN_ERROR: &str =
"element_token is stale; call get_window_state again to refresh";
/// One valid snapshot retained in the per-pid LRU.
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone)]
struct SnapshotEntry {
/// Monotonic, process-global id assigned by [`mint_snapshot_id`].
snapshot_id: u32,
/// The window the snapshot was taken against. Resolution returns
/// this so tools can verify the caller's `window_id` arg matches —
/// a token-only call doesn't have to pass window_id at all.
- window_id: u32,
+ window_id: u64,
/// Maximum element_index that was assigned in this snapshot. The
/// resolver rejects out-of-range tokens up-front instead of waiting
/// for the per-platform cache to NPE.
max_element_index: usize,
+ indices: Option<std::collections::HashSet<usize>>,
}
/// Process-global token registry. Thread-safe; tools resolve from any
@@ -115,6 +116,36 @@ impl TokenRegistry {
/// in its lane, the oldest is evicted and any token that referenced
/// it becomes stale — that's the contract.
pub fn register_snapshot(&self, pid: i32, window_id: u32, element_count: usize) -> u32 {
+ self.register_snapshot_wide(pid, u64::from(window_id), element_count)
+ }
+
+ /// Preserve full native identities on platforms with 64-bit window IDs.
+ /// The token format is unchanged; only the server-side binding is wider.
+ pub fn register_snapshot_wide(&self, pid: i32, window_id: u64, element_count: usize) -> u32 {
+ self.register_snapshot_entry(pid, window_id, element_count, None)
+ }
+
+ /// Window-scoped AT-SPI snapshots retain application-wide (sparse) indices.
+ /// Bind exactly the emitted indices instead of treating the count as a range.
+ pub fn register_snapshot_indices(&self, pid: i32, window_id: u64, indices: &[usize]) -> u32 {
+ self.register_snapshot_entry(
+ pid,
+ window_id,
+ indices
+ .iter()
+ .max()
+ .map_or(0, |index| index.saturating_add(1)),
+ Some(indices.iter().copied().collect()),
+ )
+ }
+
+ fn register_snapshot_entry(
+ &self,
+ pid: i32,
+ window_id: u64,
+ element_count: usize,
+ indices: Option<std::collections::HashSet<usize>>,
+ ) -> u32 {
// Keep the full 32-bit counter. Truncating to 16 bits repeats an id
// every 65,536 process-global snapshots. A long-lived daemon can then
// mint an id that still exists in another runtime/pid lane, allowing a
@@ -132,6 +163,7 @@ impl TokenRegistry {
snapshot_id: id,
window_id,
max_element_index: element_count.saturating_sub(1),
+ indices,
});
// Evict oldest. The loop guards against pre-existing over-cap
// state from a previous version of the binary; in steady state
@@ -154,6 +186,14 @@ impl TokenRegistry {
/// - `"element_token element_index out of range"` — the index in
/// the token is past the max recorded for the snapshot.
pub fn resolve(&self, pid: i32, token: &str) -> Result<(u32, usize), String> {
+ let (window, index) = self.resolve_wide(pid, token)?;
+ let window = u32::try_from(window).map_err(|_| {
+ "element_token window does not fit this platform's native ID".to_owned()
+ })?;
+ Ok((window, index))
+ }
+
+ pub fn resolve_wide(&self, pid: i32, token: &str) -> Result<(u64, usize), String> {
let (sid, idx) =
parse_token(token).ok_or_else(|| "element_token has invalid format".to_string())?;
let runtime_scope = current_runtime_scope();
@@ -179,7 +219,12 @@ impl TokenRegistry {
STALE_TOKEN_ERROR.to_owned()
}
})?;
- if idx > entry.max_element_index {
+ if idx > entry.max_element_index
+ || entry
+ .indices
+ .as_ref()
+ .is_some_and(|indices| !indices.contains(&idx))
+ {
return Err(format!(
"element_token element_index {idx} out of range (snapshot had {} elements)",
entry.max_element_index + 1
@@ -195,6 +240,17 @@ impl TokenRegistry {
before - entries.len()
}
+ pub fn invalidate_window(&self, pid: i32, window_id: u64) {
+ if let Some(lane) = self
+ .by_runtime_and_pid
+ .lock()
+ .unwrap()
+ .get_mut(&(current_runtime_scope(), pid))
+ {
+ lane.retain(|entry| entry.window_id != window_id);
+ }
+ }
+
/// Build the canonical token string for `snapshot_id` / `element_index`.
/// Pure helper, mirrors [`format_token`] but lives on the registry so
/// callers don't have to import the free function.
@@ -311,7 +367,7 @@ pub fn token_for(snapshot_id: u32, element_index: usize) -> String {
/// Result of validating an `element_token` or snapshot-bound `element_index`
/// on a tool call's args. Returned by [`resolve_element_args`].
#[derive(Debug, Clone)]
-pub enum ResolvedElement {
+pub enum ResolvedElement<WindowId = u32> {
/// Neither `element_token` nor `element_index` was supplied — the
/// tool should fall through to its non-element addressing mode
/// (typically pixel `x, y`) or error.
@@ -320,7 +376,7 @@ pub enum ResolvedElement {
/// through the snapshot registry, so `window_id` is always present. The
/// optional shape remains temporarily to avoid duplicating tool plumbing.
Element {
- window_id: Option<u32>,
+ window_id: Option<WindowId>,
element_index: usize,
/// True when the caller supplied a token and we resolved
/// through the registry — informational, used by tools that
@@ -357,6 +413,43 @@ pub fn resolve_element_args(
args_window_id: Option<u32>,
tool_name: &str,
) -> Result<ResolvedElement, crate::protocol::ToolResult> {
+ match resolve_element_args_wide(
+ pid,
+ args_element_index,
+ args_element_token,
+ args_snapshot_id,
+ args_window_id.map(u64::from),
+ tool_name,
+ )? {
+ ResolvedElement::None => Ok(ResolvedElement::None),
+ ResolvedElement::Element {
+ window_id,
+ element_index,
+ via_token,
+ } => {
+ let window_id = window_id.map(u32::try_from).transpose().map_err(|_| {
+ crate::protocol::ToolResult::error(
+ "element_token window does not fit this platform's native ID",
+ )
+ })?;
+ Ok(ResolvedElement::Element {
+ window_id,
+ element_index,
+ via_token,
+ })
+ }
+ }
+}
+
+/// The same target validation without narrowing a platform's native ID.
+pub fn resolve_element_args_wide(
+ pid: i32,
+ args_element_index: Option<usize>,
+ args_element_token: Option<&str>,
+ args_snapshot_id: Option<&str>,
+ args_window_id: Option<u64>,
+ tool_name: &str,
+) -> Result<ResolvedElement<u64>, crate::protocol::ToolResult> {
let refusal = |code: &str, message: String| {
crate::protocol::ToolResult::error(message.clone()).with_structured(serde_json::json!({
"status": "refused",
@@ -364,7 +457,7 @@ pub fn resolve_element_args(
}))
};
let resolve_token = |tok: &str| {
- let (wid, idx) = global().resolve(pid, tok).map_err(|message| {
+ let (wid, idx) = global().resolve_wide(pid, tok).map_err(|message| {
let code = if message.contains("another runtime generation") {
"generation_mismatch"
} else if message == STALE_TOKEN_ERROR {
@@ -551,6 +644,55 @@ mod tests {
assert_eq!(reg.resolve(pid, &format_token(s2, 0)).unwrap().0, 2);
}
+ #[test]
+ fn wide_window_ids_with_equal_low_words_remain_distinct() {
+ let reg = fresh_registry();
+ let a = 0x100000010;
+ let b = 0x200000010;
+ let sa = reg.register_snapshot_wide(42, a, 3);
+ let sb = reg.register_snapshot_wide(42, b, 3);
+ assert_eq!(reg.resolve_wide(42, &format_token(sa, 1)).unwrap(), (a, 1));
+ assert_eq!(reg.resolve_wide(42, &format_token(sb, 1)).unwrap(), (b, 1));
+ assert!(reg.resolve(42, &format_token(sa, 1)).is_err());
+ }
+
+ #[test]
+ fn sparse_window_indices_are_not_replaced_by_a_count_range() {
+ let reg = fresh_registry();
+ let sid = reg.register_snapshot_indices(42, 0x100000010, &[10, 13]);
+ assert!(reg.resolve_wide(42, &format_token(sid, 10)).is_ok());
+ assert!(reg.resolve_wide(42, &format_token(sid, 13)).is_ok());
+ assert!(reg.resolve_wide(42, &format_token(sid, 0)).is_err());
+ assert!(reg.resolve_wide(42, &format_token(sid, 11)).is_err());
+ reg.invalidate_window(42, 0x100000010);
+ assert!(reg.resolve_wide(42, &format_token(sid, 10)).is_err());
+ }
+
+ #[test]
+ fn wide_token_rejects_same_low_word_explicit_window() {
+ let pid = 0x7fff_0010;
+ let sid = global().register_snapshot_wide(pid, 0x100000010, 3);
+ let token = format_token(sid, 1);
+ let resolved =
+ resolve_element_args_wide(pid, None, Some(&token), None, None, "click").unwrap();
+ assert!(matches!(
+ resolved,
+ ResolvedElement::Element {
+ window_id: Some(0x100000010),
+ ..
+ }
+ ));
+ assert!(resolve_element_args_wide(
+ pid,
+ None,
+ Some(&token),
+ None,
+ Some(0x200000010),
+ "click"
+ )
+ .is_err());
+ }
+
#[test]
fn lru_eviction_invalidates_oldest_snapshot() {
let reg = fresh_registry();
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
index 362f76118a..acd86dc4ec 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
@@ -530,7 +530,7 @@ impl RecordingSession {
args.get("element_token").and_then(Value::as_str),
) {
if let Ok((resolved_window, resolved_index)) =
- crate::element_token::global().resolve(pid, token)
+ crate::element_token::global().resolve_wide(pid, token)
{
window_id = Some(u64::from(resolved_window));
element_index = u64::try_from(resolved_index).ok();
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
index 5960943065..69b94ab6ef 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
@@ -891,6 +891,10 @@ pub mod macos {
}
}
+#[cfg(any(target_os = "linux", all(test, unix)))]
+#[path = "observer_hyprland.rs"]
+mod hyprland;
+
#[cfg(target_os = "linux")]
pub mod linux {
use std::process::{Command, Stdio};
@@ -915,6 +919,7 @@ pub mod linux {
enum SessionKind {
X11,
Sway,
+ Hyprland,
Gnome,
CuaCompositor,
Missing,
@@ -925,6 +930,8 @@ pub mod linux {
stop: Arc<AtomicBool>,
events: Arc<Mutex<Vec<FocusEvent>>>,
sampler: Option<JoinHandle<()>>,
+ hyprland_journal: Option<super::hyprland::Journal>,
+ probe_error: Option<ObserverError>,
}
impl LinuxObserver {
@@ -933,11 +940,20 @@ pub mod linux {
.map(|value| value.eq_ignore_ascii_case("wayland"))
.unwrap_or(false)
|| std::env::var_os("WAYLAND_DISPLAY").is_some();
+ let mut probe_error = None;
let session = if explicit_wayland {
if cua_compositor_available() {
SessionKind::CuaCompositor
} else if sway_available() {
SessionKind::Sway
+ } else if std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some() {
+ match super::hyprland::probe() {
+ Ok(()) => SessionKind::Hyprland,
+ Err(error) => {
+ probe_error = Some(error);
+ SessionKind::Missing
+ }
+ }
} else if gnome_windows().is_ok() {
SessionKind::Gnome
} else {
@@ -957,6 +973,8 @@ pub mod linux {
stop: Arc::new(AtomicBool::new(false)),
events: Arc::new(Mutex::new(Vec::new())),
sampler: None,
+ hyprland_journal: None,
+ probe_error,
}
}
}
@@ -970,7 +988,7 @@ pub mod linux {
impl ObserverBackend for LinuxObserver {
fn capabilities(&self) -> ObserverCapabilities {
match self.session {
- SessionKind::X11 => ObserverCapabilities {
+ SessionKind::X11 | SessionKind::Hyprland => ObserverCapabilities {
focus: true,
z_order: true,
cursor: true,
@@ -989,9 +1007,13 @@ pub mod linux {
}
fn snapshot(&self, target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ if let Some(error) = &self.probe_error {
+ return Err(error.clone());
+ }
match self.session {
SessionKind::X11 => x11_snapshot(target),
SessionKind::Sway => sway_snapshot(target),
+ SessionKind::Hyprland => super::hyprland::snapshot(target),
SessionKind::Gnome => gnome_snapshot(target),
SessionKind::CuaCompositor => cua_compositor_snapshot(target),
SessionKind::Missing => Ok(DesktopSnapshot {
@@ -1004,6 +1026,13 @@ pub mod linux {
}
fn start_journal(&mut self) -> Result<(), ObserverError> {
+ if self.session == SessionKind::Hyprland {
+ if self.hyprland_journal.is_some() {
+ return Err(ObserverError::new("Hyprland focus journal already active"));
+ }
+ self.hyprland_journal = Some(super::hyprland::Journal::start()?);
+ return Ok(());
+ }
if self.sampler.is_some() {
return Err(ObserverError::new("Linux focus journal already active"));
}
@@ -1019,6 +1048,7 @@ pub mod linux {
let focus_identity = || match session {
SessionKind::X11 => x11_focus_identity(),
SessionKind::Sway => sway_focus_identity(),
+ SessionKind::Hyprland => super::hyprland::focus_identity(),
SessionKind::Gnome => gnome_focus_identity(),
SessionKind::CuaCompositor => cua_compositor_focus_identity(),
SessionKind::Missing => Ok(None),
@@ -1041,6 +1071,9 @@ pub mod linux {
}
fn drain_journal(&mut self) -> Result<DesktopJournal, ObserverError> {
+ if let Some(journal) = self.hyprland_journal.take() {
+ return journal.drain();
+ }
self.stop.store(true, Ordering::Release);
if let Some(sampler) = self.sampler.take() {
sampler
@@ -1054,6 +1087,22 @@ pub mod linux {
}
}
+ pub(crate) fn hyprland_client_address(pid: u32) -> Result<String, ObserverError> {
+ super::hyprland::client_address(TargetWindow { pid, native_id: 0 })
+ }
+
+ pub(crate) fn hyprland_target_address(target: TargetWindow) -> Result<String, ObserverError> {
+ super::hyprland::client_address(target)
+ }
+
+ pub(crate) fn hyprland_cursor_position() -> Result<(f64, f64), ObserverError> {
+ super::hyprland::cursor_position()
+ }
+
+ pub(crate) fn hyprland_monitor_regions() -> Result<Vec<(f64, f64, f64, f64)>, ObserverError> {
+ super::hyprland::monitor_regions()
+ }
+
impl Drop for LinuxObserver {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer_hyprland.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer_hyprland.rs
new file mode 100644
index 0000000000..2c68248ae0
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer_hyprland.rs
@@ -0,0 +1,764 @@
+//! Independent Hyprland observations, adapted from contributions in #3052/#3466.
+//! This module never calls driver capture, geometry, or input implementations.
+#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
+
+use std::io::{ErrorKind, Read};
+use std::os::fd::AsRawFd;
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::thread::JoinHandle;
+use std::time::{Duration, Instant};
+
+use serde::{de::DeserializeOwned, Deserialize};
+
+use super::{DesktopJournal, DesktopSnapshot, FocusEvent, ObserverError, TargetWindow, TargetZ};
+
+const QUERY_TIMEOUT: Duration = Duration::from_secs(1);
+const OUTPUT_LIMIT: usize = 1024 * 1024;
+
+struct ReapedChild(Child);
+
+impl Drop for ReapedChild {
+ fn drop(&mut self) {
+ // Always reap, including malformed output, timeout and read-error paths.
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+}
+
+fn nonblocking(pipe: &impl AsRawFd) -> Result<(), ObserverError> {
+ let fd = pipe.as_raw_fd();
+ let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
+ if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 {
+ return Err(ObserverError::new(format!(
+ "hyprctl pipe setup: {}",
+ std::io::Error::last_os_error()
+ )));
+ }
+ Ok(())
+}
+
+fn read_available(
+ pipe: &mut impl Read,
+ bytes: &mut Vec<u8>,
+ limit: usize,
+) -> Result<bool, ObserverError> {
+ let mut buffer = [0; 8192];
+ // Limit work per iteration as well as retained output, so a writer cannot
+ // starve deadline checks. A child inheriting the pipe cannot block EOF.
+ for _ in 0..16 {
+ match pipe.read(&mut buffer) {
+ Ok(0) => return Ok(true),
+ Ok(count) => {
+ if bytes.len().saturating_add(count) > limit {
+ return Err(ObserverError::new("hyprctl output exceeded limit"));
+ }
+ bytes.extend_from_slice(&buffer[..count]);
+ }
+ Err(error) if error.kind() == ErrorKind::WouldBlock => return Ok(false),
+ Err(error) if error.kind() == ErrorKind::Interrupted => continue,
+ Err(error) => return Err(ObserverError::new(format!("hyprctl pipe read: {error}"))),
+ }
+ }
+ Ok(false)
+}
+
+fn bounded_output(
+ command: &mut Command,
+ timeout: Duration,
+ limit: usize,
+) -> Result<Vec<u8>, ObserverError> {
+ let mut child = ReapedChild(
+ command
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|error| ObserverError::new(format!("hyprctl spawn: {error}")))?,
+ );
+ let mut stdout = child.0.stdout.take().expect("piped stdout");
+ let mut stderr = child.0.stderr.take().expect("piped stderr");
+ nonblocking(&stdout)?;
+ nonblocking(&stderr)?;
+ let deadline = Instant::now() + timeout;
+ let mut out = Vec::new();
+ let mut err = Vec::new();
+ loop {
+ let out_done = read_available(&mut stdout, &mut out, limit)?;
+ let err_done = read_available(&mut stderr, &mut err, limit)?;
+ if let Some(status) = child
+ .0
+ .try_wait()
+ .map_err(|error| ObserverError::new(format!("hyprctl wait: {error}")))?
+ {
+ if out_done && err_done {
+ return if status.success() {
+ Ok(out)
+ } else {
+ Err(ObserverError::new(format!(
+ "hyprctl exited with {status}: {}",
+ String::from_utf8_lossy(&err)
+ )))
+ };
+ }
+ }
+ if Instant::now() >= deadline {
+ return Err(ObserverError::new("hyprctl query timed out"));
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+}
+
+fn query<T: DeserializeOwned>(name: &str) -> Result<T, ObserverError> {
+ let output = bounded_output(
+ Command::new("hyprctl").args(["-j", name]),
+ QUERY_TIMEOUT,
+ OUTPUT_LIMIT,
+ )
+ .map_err(|error| ObserverError::new(format!("hyprctl {name}: {error}")))?;
+ serde_json::from_slice(&output)
+ .map_err(|error| ObserverError::new(format!("invalid hyprctl {name} JSON: {error}")))
+}
+
+#[derive(Clone, Debug, Deserialize)]
+struct Workspace {
+ id: i64,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+struct Client {
+ address: String,
+ pid: u32,
+ workspace: Workspace,
+ monitor: i64,
+ at: [i64; 2],
+ size: [i64; 2],
+ mapped: bool,
+ hidden: bool,
+ fullscreen: i64,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+struct Monitor {
+ id: i64,
+ x: f64,
+ y: f64,
+ width: f64,
+ height: f64,
+ scale: f64,
+ transform: u8,
+ #[serde(rename = "activeWorkspace")]
+ active_workspace: Workspace,
+ #[serde(rename = "specialWorkspace")]
+ special_workspace: Workspace,
+}
+
+fn address(value: &str) -> Result<u64, ObserverError> {
+ value
+ .strip_prefix("0x")
+ .and_then(|value| u64::from_str_radix(value, 16).ok())
+ .filter(|value| *value != 0)
+ .ok_or_else(|| ObserverError::new("invalid Hyprland client address"))
+}
+
+fn clients() -> Result<Vec<Client>, ObserverError> {
+ let clients: Vec<Client> = query("clients")?;
+ for client in &clients {
+ address(&client.address)?;
+ }
+ Ok(clients)
+}
+
+fn select(clients: &[Client], target: TargetWindow) -> Result<Option<&Client>, ObserverError> {
+ if target.native_id != 0 {
+ let client = clients
+ .iter()
+ .find(|client| address(&client.address).ok() == Some(target.native_id));
+ if client.is_some_and(|client| client.pid != target.pid) {
+ return Err(ObserverError::new(
+ "Hyprland target address belongs to a different pid",
+ ));
+ }
+ return Ok(client);
+ }
+ let mut matches = clients
+ .iter()
+ .filter(|client| client.pid == target.pid && client.mapped);
+ let first = matches.next();
+ if matches.next().is_some() {
+ return Err(ObserverError::new(
+ "Hyprland target pid has multiple mapped clients; native_id required",
+ ));
+ }
+ Ok(first)
+}
+
+pub(super) fn client_address(target: TargetWindow) -> Result<String, ObserverError> {
+ select(&clients()?, target)?
+ .map(|client| client.address.clone())
+ .ok_or_else(|| ObserverError::new("Hyprland target client not found"))
+}
+
+fn parse_focus(value: serde_json::Value) -> Result<Option<u64>, ObserverError> {
+ if value.as_object().is_some_and(|object| object.is_empty()) {
+ return Ok(None);
+ }
+ let raw = value
+ .get("address")
+ .and_then(|address| address.as_str())
+ .ok_or_else(|| ObserverError::new("Hyprland activewindow omitted address"))?;
+ address(raw).map(Some)
+}
+
+pub(super) fn focus_identity() -> Result<Option<u64>, ObserverError> {
+ parse_focus(query("activewindow")?)
+}
+
+#[derive(Deserialize)]
+struct Cursor {
+ x: f64,
+ y: f64,
+}
+
+pub(super) fn cursor_position() -> Result<(f64, f64), ObserverError> {
+ let cursor: Cursor = query("cursorpos")?;
+ if !cursor.x.is_finite() || !cursor.y.is_finite() {
+ return Err(ObserverError::new(
+ "Hyprland cursor coordinates are not finite",
+ ));
+ }
+ Ok((cursor.x, cursor.y))
+}
+
+fn monitor_region(monitor: &Monitor) -> Result<(f64, f64, f64, f64), ObserverError> {
+ if ![
+ monitor.x,
+ monitor.y,
+ monitor.width,
+ monitor.height,
+ monitor.scale,
+ ]
+ .iter()
+ .all(|v| v.is_finite())
+ || monitor.width <= 0.0
+ || monitor.height <= 0.0
+ || monitor.scale <= 0.0
+ || monitor.transform > 7
+ {
+ return Err(ObserverError::new("invalid Hyprland monitor geometry"));
+ }
+ let (width, height) = if monitor.transform % 2 == 1 {
+ (monitor.height, monitor.width)
+ } else {
+ (monitor.width, monitor.height)
+ };
+ let (width, height) = (width / monitor.scale, height / monitor.scale);
+ if !width.is_finite() || !height.is_finite() {
+ return Err(ObserverError::new(
+ "invalid Hyprland logical monitor extent",
+ ));
+ }
+ Ok((monitor.x, monitor.y, width, height))
+}
+
+pub(super) fn monitor_regions() -> Result<Vec<(f64, f64, f64, f64)>, ObserverError> {
+ let monitors: Vec<Monitor> = query("monitors")?;
+ if monitors.is_empty() {
+ return Err(ObserverError::new("Hyprland has no active monitors"));
+ }
+ monitors.iter().map(monitor_region).collect()
+}
+
+#[derive(Deserialize)]
+struct Instance {
+ instance: String,
+ wl_socket: String,
+}
+
+fn instance_matches(
+ instances: &[Instance],
+ signature: &str,
+ display: &str,
+ runtime: Option<&str>,
+) -> bool {
+ instances.iter().any(|instance| {
+ instance.instance == signature
+ && (instance.wl_socket == display
+ || runtime.is_some_and(|runtime| {
+ std::path::Path::new(runtime).join(&instance.wl_socket)
+ == std::path::Path::new(display)
+ }))
+ })
+}
+
+pub(super) fn probe() -> Result<(), ObserverError> {
+ let signature = std::env::var("HYPRLAND_INSTANCE_SIGNATURE")
+ .map_err(|_| ObserverError::new("Hyprland observer requires an instance signature"))?;
+ let display = std::env::var("WAYLAND_DISPLAY")
+ .map_err(|_| ObserverError::new("Hyprland observer requires WAYLAND_DISPLAY"))?;
+ let runtime = std::env::var("XDG_RUNTIME_DIR").ok();
+ let instances = query::<Vec<Instance>>("instances")?;
+ if !instance_matches(&instances, &signature, &display, runtime.as_deref()) {
+ return Err(ObserverError::new(
+ "Hyprland instance signature does not match WAYLAND_DISPLAY",
+ ));
+ }
+ clients()?;
+ focus_identity()?;
+ monitor_regions()?;
+ cursor_position()?;
+ Ok(())
+}
+
+fn overlaps(a: &Client, b: &Client) -> bool {
+ (0..2).all(|i| {
+ a.at[i] < b.at[i].saturating_add(b.size[i]) && b.at[i] < a.at[i].saturating_add(a.size[i])
+ })
+}
+
+fn contains(a: &Client, b: &Client) -> bool {
+ (0..2).all(|i| {
+ a.at[i] <= b.at[i] && a.at[i].saturating_add(a.size[i]) >= b.at[i].saturating_add(b.size[i])
+ })
+}
+
+fn classify(
+ clients: &[Client],
+ active: Option<u64>,
+ monitors: &[Monitor],
+ target: TargetWindow,
+) -> Result<TargetZ, ObserverError> {
+ let Some(target) = select(clients, target)? else {
+ return Ok(TargetZ::NotFound);
+ };
+ let monitor = monitors
+ .iter()
+ .find(|monitor| monitor.id == target.monitor)
+ .ok_or_else(|| ObserverError::new("Hyprland target monitor missing"))?;
+ if !target.mapped
+ || target.hidden
+ || (target.workspace.id != monitor.active_workspace.id
+ && target.workspace.id != monitor.special_workspace.id)
+ {
+ return Ok(TargetZ::Minimized);
+ }
+ if address(&target.address)? == active.unwrap_or(0) {
+ return Ok(TargetZ::Foreground);
+ }
+ if target.size.iter().any(|size| *size <= 0) {
+ return Err(ObserverError::new("Hyprland target has invalid extent"));
+ }
+ // An open special workspace overlays the regular workspace. Its coverage
+ // and stacking cannot be inferred from the ordinary clients list.
+ if monitor.special_workspace.id != 0 && target.workspace.id != monitor.special_workspace.id {
+ return Err(ObserverError::new(
+ "Hyprland special-workspace occlusion is ambiguous",
+ ));
+ }
+ let others: Vec<_> = clients
+ .iter()
+ .filter(|client| {
+ client.address != target.address
+ && client.mapped
+ && !client.hidden
+ && client.workspace.id == target.workspace.id
+ && overlaps(client, target)
+ })
+ .collect();
+ if others.iter().any(|client| {
+ address(&client.address).ok() == active
+ && client.monitor == target.monitor
+ && client.fullscreen == 2
+ && contains(client, target)
+ }) {
+ return Ok(TargetZ::BackgroundOccluded);
+ }
+ if !others.is_empty() {
+ return Err(ObserverError::new(
+ "Hyprland overlapping clients have ambiguous z-order",
+ ));
+ }
+ Ok(TargetZ::BackgroundVisible)
+}
+
+pub(super) fn snapshot(target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ let clients = clients()?;
+ let active = focus_identity()?;
+ let monitors = query::<Vec<Monitor>>("monitors")?;
+ for monitor in &monitors {
+ monitor_region(monitor)?;
+ }
+ let target_z = classify(&clients, active, &monitors, target)?;
+ Ok(DesktopSnapshot {
+ foreground: active,
+ input_focus: active,
+ target_z,
+ cursor_pos: Some(cursor_position()?),
+ })
+}
+
+pub(super) struct Journal {
+ stop: Arc<AtomicBool>,
+ sampler: Option<JoinHandle<Result<DesktopJournal, ObserverError>>>,
+}
+
+impl Journal {
+ pub(super) fn start() -> Result<Self, ObserverError> {
+ Self::with_query(focus_identity)
+ }
+
+ fn with_query(
+ query: impl Fn() -> Result<Option<u64>, ObserverError> + Send + 'static,
+ ) -> Result<Self, ObserverError> {
+ // Establish baseline before returning to the action under observation.
+ let mut previous = query()?;
+ let stop = Arc::new(AtomicBool::new(false));
+ let thread_stop = Arc::clone(&stop);
+ let sampler = std::thread::spawn(move || {
+ let mut journal = DesktopJournal::default();
+ while !thread_stop.load(Ordering::Acquire) {
+ let current = query()?;
+ if current != previous {
+ if journal.focus_events.len() >= 10_000 {
+ return Err(ObserverError::new(
+ "Hyprland focus journal exceeded event limit",
+ ));
+ }
+ journal.focus_events.push(FocusEvent {
+ from: previous,
+ to: current,
+ });
+ previous = current;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ Ok(journal)
+ });
+ Ok(Self {
+ stop,
+ sampler: Some(sampler),
+ })
+ }
+
+ pub(super) fn drain(mut self) -> Result<DesktopJournal, ObserverError> {
+ self.stop.store(true, Ordering::Release);
+ // Each iteration contains one bounded query and a 10ms sleep. Thus
+ // shutdown is bounded by QUERY_TIMEOUT plus scheduling and child reap.
+ self.sampler
+ .take()
+ .expect("active journal")
+ .join()
+ .map_err(|_| ObserverError::new("Hyprland focus journal panicked"))?
+ }
+}
+
+impl Drop for Journal {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Release);
+ if let Some(sampler) = self.sampler.take() {
+ let _ = sampler.join();
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+ use std::sync::atomic::AtomicUsize;
+
+ fn client(id: u64, pid: u32) -> Client {
+ serde_json::from_value(json!({"address": format!("0x{id:x}"), "pid": pid,
+ "workspace": {"id": 1}, "monitor": 0, "at": [10,20], "size": [100,80],
+ "mapped": true, "hidden": false, "fullscreen": 0}))
+ .unwrap()
+ }
+
+ fn monitor() -> Monitor {
+ serde_json::from_value(json!({"id": 0, "x": -100, "y": 0, "width": 1920,
+ "height": 1080, "scale": 1.5, "transform": 1,
+ "activeWorkspace": {"id": 1}, "specialWorkspace": {"id": 0}}))
+ .unwrap()
+ }
+
+ fn target() -> TargetWindow {
+ TargetWindow {
+ pid: 100,
+ native_id: 0x10,
+ }
+ }
+
+ #[test]
+ fn explicit_identity_never_selects_larger_sibling_or_missing_id_fallback() {
+ let small = client(0x10, 100);
+ let mut large = client(0x11, 100);
+ large.size = [1000, 1000];
+ let clients = [large, small];
+ assert_eq!(select(&clients, target()).unwrap().unwrap().address, "0x10");
+ assert!(select(
+ &clients,
+ TargetWindow {
+ native_id: 0x12,
+ ..target()
+ }
+ )
+ .unwrap()
+ .is_none());
+ assert!(select(
+ &clients,
+ TargetWindow {
+ native_id: 0,
+ ..target()
+ }
+ )
+ .is_err());
+ assert!(select(
+ &clients,
+ TargetWindow {
+ pid: 200,
+ ..target()
+ }
+ )
+ .is_err());
+ }
+
+ #[test]
+ fn pid_only_identity_requires_unique_mapped_client() {
+ let clients = [client(0x10, 100)];
+ assert!(select(
+ &clients,
+ TargetWindow {
+ native_id: 0,
+ ..target()
+ }
+ )
+ .unwrap()
+ .is_some());
+ let mut unmapped = client(0x11, 100);
+ unmapped.mapped = false;
+ assert!(select(
+ &[clients[0].clone(), unmapped],
+ TargetWindow {
+ native_id: 0,
+ ..target()
+ }
+ )
+ .unwrap()
+ .is_some());
+ }
+
+ #[test]
+ fn fullscreen_requires_actual_cover_and_maximized_is_ambiguous() {
+ let mut cover = client(0x20, 200);
+ cover.fullscreen = 2;
+ cover.at = [0, 0];
+ cover.size = [1920, 1080];
+ let mut clients = [client(0x10, 100), cover];
+ assert_eq!(
+ classify(&clients, Some(0x20), &[monitor()], target()).unwrap(),
+ TargetZ::BackgroundOccluded
+ );
+ clients[1].fullscreen = 1;
+ assert!(classify(&clients, Some(0x20), &[monitor()], target()).is_err());
+ clients[1].fullscreen = 2;
+ clients[1].size = [30, 30];
+ assert!(classify(&clients, Some(0x20), &[monitor()], target()).is_err());
+ clients[1].at = [1000, 1000];
+ assert_eq!(
+ classify(&clients, Some(0x20), &[monitor()], target()).unwrap(),
+ TargetZ::BackgroundVisible
+ );
+ }
+
+ #[test]
+ fn hidden_and_off_workspace_precede_foreground_and_special_overlay_is_unknown() {
+ let mut clients = [client(0x10, 100)];
+ clients[0].workspace.id = 9;
+ assert_eq!(
+ classify(&clients, Some(0x10), &[monitor()], target()).unwrap(),
+ TargetZ::Minimized
+ );
+ clients[0].workspace.id = 1;
+ clients[0].hidden = true;
+ assert_eq!(
+ classify(&clients, Some(0x10), &[monitor()], target()).unwrap(),
+ TargetZ::Minimized
+ );
+ clients[0].hidden = false;
+ let mut monitor = monitor();
+ monitor.special_workspace.id = -99;
+ assert!(classify(&clients, None, &[monitor], target()).is_err());
+ }
+
+ #[test]
+ fn monitor_regions_preserve_negative_origins_rotation_and_scale() {
+ let mut monitor = monitor();
+ assert_eq!(
+ monitor_region(&monitor).unwrap(),
+ (-100.0, 0.0, 720.0, 1280.0)
+ );
+ monitor.scale = f64::NAN;
+ assert!(monitor_region(&monitor).is_err());
+ monitor.scale = 0.0;
+ assert!(monitor_region(&monitor).is_err());
+ monitor.scale = 1.0;
+ monitor.transform = 8;
+ assert!(monitor_region(&monitor).is_err());
+ }
+
+ #[test]
+ fn malformed_focus_is_not_silently_treated_as_unfocused() {
+ assert_eq!(parse_focus(json!({})).unwrap(), None);
+ assert_eq!(
+ parse_focus(json!({"address": "0x123"})).unwrap(),
+ Some(0x123)
+ );
+ for value in [
+ json!(null),
+ json!([]),
+ json!({"address": "invalid"}),
+ json!({"pid": 10}),
+ json!({"address": "0x0"}),
+ ] {
+ assert!(parse_focus(value).is_err());
+ }
+ assert!(serde_json::from_value::<Client>(json!({"address": "0x10"})).is_err());
+ assert!(serde_json::from_slice::<Cursor>(br#"{"x":2}"#).is_err());
+ let cursor: Cursor = serde_json::from_slice(br#"{"x":4367,"y":-964}"#).unwrap();
+ assert_eq!((cursor.x, cursor.y), (4367.0, -964.0));
+ }
+
+ #[test]
+ fn stale_instance_signature_cannot_probe_a_different_display() {
+ let instances = [Instance {
+ instance: "session-a".into(),
+ wl_socket: "wayland-1".into(),
+ }];
+ assert!(instance_matches(&instances, "session-a", "wayland-1", None));
+ assert!(instance_matches(
+ &instances,
+ "session-a",
+ "/run/example/wayland-1",
+ Some("/run/example")
+ ));
+ assert!(!instance_matches(
+ &instances,
+ "session-a",
+ "wayland-2",
+ None
+ ));
+ assert!(!instance_matches(
+ &instances,
+ "session-b",
+ "wayland-1",
+ None
+ ));
+ }
+
+ #[test]
+ fn bounded_process_rejects_timeout_and_reaps_child() {
+ let directory = tempfile::tempdir().unwrap();
+ let pid_file = directory.path().join("pid");
+ let start = Instant::now();
+ let error = bounded_output(
+ Command::new("sh")
+ .args(["-c", "echo $$ > \"$1\"; exec sleep 10", "observer-test"])
+ .arg(&pid_file),
+ Duration::from_millis(100),
+ 1024,
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("timed out"));
+ assert!(start.elapsed() < Duration::from_secs(2));
+ let pid: i32 = std::fs::read_to_string(pid_file)
+ .unwrap()
+ .trim()
+ .parse()
+ .unwrap();
+ assert_eq!(
+ unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) },
+ -1
+ );
+ assert_eq!(
+ std::io::Error::last_os_error().raw_os_error(),
+ Some(libc::ECHILD)
+ );
+ }
+
+ #[test]
+ fn bounded_process_limits_both_streams_and_reports_exit_failure() {
+ for script in [
+ "while :; do printf '0123456789'; done",
+ "while :; do printf '0123456789' >&2; done",
+ ] {
+ let error = bounded_output(
+ Command::new("sh").args(["-c", script]),
+ Duration::from_secs(1),
+ 64,
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("output exceeded limit"));
+ }
+ let error = bounded_output(
+ Command::new("sh").args(["-c", "printf 'query rejected' >&2; exit 7"]),
+ Duration::from_secs(1),
+ 64,
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("query rejected"));
+ let output = bounded_output(
+ Command::new("sh").args(["-c", "printf '{}' "]),
+ Duration::from_secs(1),
+ 64,
+ )
+ .unwrap();
+ assert_eq!(output, b"{}");
+ }
+
+ #[test]
+ fn journal_reports_baseline_and_sampler_errors() {
+ assert!(Journal::with_query(|| Err(ObserverError::new("baseline failure"))).is_err());
+ let count = AtomicUsize::new(0);
+ let journal = Journal::with_query(move || {
+ if count.fetch_add(1, Ordering::Relaxed) == 0 {
+ Ok(Some(1))
+ } else {
+ Err(ObserverError::new("sampler failure"))
+ }
+ })
+ .unwrap();
+ let deadline = Instant::now() + Duration::from_secs(1);
+ while !journal.sampler.as_ref().unwrap().is_finished() && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert_eq!(journal.drain().unwrap_err().to_string(), "sampler failure");
+ }
+
+ #[test]
+ fn journal_stop_waits_only_for_bounded_inflight_query() {
+ let count = AtomicUsize::new(0);
+ let (started, ready) = std::sync::mpsc::channel();
+ let journal = Journal::with_query(move || {
+ if count.fetch_add(1, Ordering::Relaxed) == 0 {
+ return Ok(Some(1));
+ }
+ started.send(()).unwrap();
+ bounded_output(
+ Command::new("sleep").arg("10"),
+ Duration::from_millis(100),
+ 64,
+ )?;
+ Ok(Some(1))
+ })
+ .unwrap();
+ ready.recv_timeout(Duration::from_secs(1)).unwrap();
+ let start = Instant::now();
+ assert!(journal
+ .drain()
+ .unwrap_err()
+ .to_string()
+ .contains("timed out"));
+ assert!(start.elapsed() < Duration::from_secs(2));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
index a902337f73..faf2e546ff 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
@@ -9,9 +9,14 @@ use crate::e2e::OracleKind;
use crate::observer::{DesktopObserver, NativeObserver, TargetWindow};
use crate::{harness_app, spawn_in_job, BehaviorRecording, ChildReaper, Driver};
+#[cfg(any(target_os = "linux", test))]
+#[path = "sentinel_hyprland.rs"]
+mod hyprland;
+
/// A foreground Electron window that journals focus and leaked input while it
/// fully occludes the background target.
pub struct ForegroundSentinel {
+ cursor_calibrated: bool,
journal_path: std::path::PathBuf,
target: TargetWindow,
_reaper: ChildReaper,
@@ -131,10 +136,19 @@ impl ForegroundSentinel {
"focused by setup click",
);
}
+ let cursor_calibrated = !is_wayland_session();
+ #[cfg(target_os = "linux")]
+ let cursor_calibrated = if hyprland::is_session() {
+ hyprland::calibrate(driver, target)?;
+ true
+ } else {
+ cursor_calibrated
+ };
fs::write(&journal_path, "")
.map_err(|error| format!("reset focused sentinel journal: {error}"))?;
Ok(Self {
+ cursor_calibrated,
journal_path,
target,
_reaper: reaper,
@@ -250,19 +264,7 @@ impl ForegroundSentinel {
#[cfg(target_os = "linux")]
set_sway_fullscreen(driver, self.target, false)?;
- let raised = driver.call(
- "bring_to_front",
- serde_json::json!({
- "pid": background_target.pid,
- "window_id": background_target.native_id,
- }),
- );
- if raised.is_error() {
- return Err(format!(
- "focus-loss canary could not raise the background target: {}",
- raised.text()
- ));
- }
+ raise_for_focus_canary(driver, background_target)?;
#[cfg(target_os = "linux")]
focus_sway_target(driver, background_target)?;
if is_wayland_session() {
@@ -378,10 +380,7 @@ impl ForegroundSentinel {
));
}
let mut native_oracles = vec![OracleKind::Focus, OracleKind::ZOrder];
- if std::env::var("XDG_SESSION_TYPE")
- .map(|session| !session.eq_ignore_ascii_case("wayland"))
- .unwrap_or(true)
- {
+ if self.cursor_calibrated {
native_oracles.push(OracleKind::Cursor);
}
let (result, delta) = observer
@@ -476,10 +475,34 @@ fn activate_native_foreground(driver: &mut impl Driver, target: TargetWindow) {
.unwrap_or_else(|error| panic!("could not activate foreground sentinel: {error}"));
}
+fn raise_for_focus_canary(driver: &mut impl Driver, target: TargetWindow) -> Result<(), String> {
+ #[cfg(target_os = "linux")]
+ if hyprland::is_session() {
+ return hyprland::activate(driver, target).map_err(|error| {
+ format!("Hyprland focus-loss canary could not raise target over fullscreen sentinel: {error}")
+ });
+ }
+ let raised = driver.call(
+ "bring_to_front",
+ serde_json::json!({ "pid": target.pid, "window_id": target.native_id }),
+ );
+ if raised.is_error() {
+ return Err(format!(
+ "focus-loss canary could not raise the background target: {}",
+ raised.text()
+ ));
+ }
+ Ok(())
+}
+
fn try_activate_native_foreground(
driver: &mut impl Driver,
target: TargetWindow,
) -> Result<(), String> {
+ #[cfg(target_os = "linux")]
+ if hyprland::is_session() {
+ return hyprland::activate(driver, target);
+ }
let response = driver.call(
"bring_to_front",
serde_json::json!({
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel_hyprland.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel_hyprland.rs
new file mode 100644
index 0000000000..3f7a978f04
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel_hyprland.rs
@@ -0,0 +1,387 @@
+//! Cursor guard adapted from contributor PR #3466; compositor observations
+//! remain independent of Driver geometry, capture and input implementations.
+
+use crate::observer::{DesktopSnapshot, TargetZ};
+
+type Point = (f64, f64);
+type Region = (f64, f64, f64, f64);
+
+fn canary_destination(original: Point, regions: &[Region]) -> Result<Point, String> {
+ if !original.0.is_finite() || !original.1.is_finite() {
+ return Err("Hyprland cursor is not finite".into());
+ }
+ // Regions are compositor logical coordinates, already scaled/rotated by
+ // the independent observer. Never use an enclosing desktop bounding box:
+ // it can include gaps between outputs and discard negative origins.
+ for &(x, y, width, height) in regions {
+ if ![x, y, width, height, x + width, y + height]
+ .iter()
+ .all(|value| value.is_finite())
+ || width <= 0.0
+ || height <= 0.0
+ {
+ return Err("Hyprland monitor region is invalid".into());
+ }
+ }
+ let &(x, y, width, height) = regions
+ .iter()
+ .find(|&&(x, y, width, height)| {
+ original.0 >= x && original.0 < x + width && original.1 >= y && original.1 < y + height
+ })
+ .ok_or("Hyprland original cursor is outside active logical monitors")?;
+ for fraction in [0.25, 0.75] {
+ let candidate = (
+ (x + width * fraction).round(),
+ (y + height * fraction).round(),
+ );
+ if candidate.0 >= x
+ && candidate.0 < x + width
+ && candidate.1 >= y
+ && candidate.1 < y + height
+ && (candidate.0 - original.0).hypot(candidate.1 - original.1) > 8.0
+ {
+ return Ok(candidate);
+ }
+ }
+ Err("Hyprland monitor has no distinct interior cursor canary".into())
+}
+
+trait CalibrationIo {
+ fn snapshot(&mut self) -> Result<DesktopSnapshot, String>;
+ fn regions(&mut self) -> Result<Vec<Region>, String>;
+ fn move_cursor(&mut self, point: Point) -> Result<(), String>;
+ fn restore_focus(&mut self) -> Result<(), String>;
+}
+
+fn at_destination(actual: Option<Point>, requested: Point) -> bool {
+ actual.is_some_and(|point| {
+ point.0.is_finite()
+ && point.1.is_finite()
+ && (point.0 - requested.0).abs() <= 1.0
+ && (point.1 - requested.1).abs() <= 1.0
+ })
+}
+
+fn same_posture(left: &DesktopSnapshot, right: &DesktopSnapshot) -> bool {
+ left.foreground == right.foreground
+ && left.input_focus == right.input_focus
+ && left.target_z == right.target_z
+}
+
+fn calibrate_io(io: &mut impl CalibrationIo) -> Result<(), String> {
+ let before = io.snapshot()?;
+ if before.target_z != TargetZ::Foreground
+ || before.foreground.is_none()
+ || before.foreground != before.input_focus
+ {
+ return Err("Hyprland cursor calibration requires a focused sentinel".into());
+ }
+ let original = before
+ .cursor_pos
+ .ok_or("Hyprland cursor position unavailable")?;
+ if !original.0.is_finite() || !original.1.is_finite() {
+ return Err("Hyprland original cursor is not finite".into());
+ }
+ let result = (|| {
+ let regions = io.regions()?;
+ let destination = canary_destination(original, &regions)?;
+ let read_only = io.snapshot()?;
+ if before != read_only {
+ return Err("Hyprland read-only cursor samples changed desktop state".into());
+ }
+ io.move_cursor(destination)?;
+ let moved = io.snapshot()?;
+ if !at_destination(moved.cursor_pos, destination) {
+ return Err(format!(
+ "Hyprland cursor canary missed requested destination {destination:?}: {:?}",
+ moved.cursor_pos
+ ));
+ }
+ Ok(())
+ })();
+
+ // Execute every restoration step even after failed input or observation.
+ // Preserve both the original error and cleanup errors; never certify a
+ // successful move with an unverified restoration.
+ let cursor_restore = io.move_cursor(original);
+ let focus_restore = io.restore_focus();
+ let restored = io.snapshot();
+ let mut errors: Vec<String> = [result, cursor_restore, focus_restore]
+ .into_iter()
+ .filter_map(Result::err)
+ .collect();
+ match restored {
+ Ok(restored) => {
+ if restored.cursor_pos != Some(original) || !same_posture(&before, &restored) {
+ errors.push(format!("Hyprland cursor/focus/z-order restoration mismatch: {before:?} -> {restored:?}"));
+ }
+ }
+ Err(error) => errors.push(format!(
+ "Hyprland restoration could not be verified: {error}"
+ )),
+ }
+ if errors.is_empty() {
+ Ok(())
+ } else {
+ Err(errors.join("; "))
+ }
+}
+
+#[cfg(target_os = "linux")]
+pub(super) fn is_session() -> bool {
+ (super::is_wayland_session() || std::env::var_os("WAYLAND_DISPLAY").is_some())
+ && (std::env::var("CUA_E2E_WAYLAND_SESSION")
+ .is_ok_and(|session| session.eq_ignore_ascii_case("hyprland"))
+ || std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some())
+}
+
+#[cfg(target_os = "linux")]
+pub(super) fn activate(
+ driver: &mut impl crate::Driver,
+ target: crate::observer::TargetWindow,
+) -> Result<(), String> {
+ use crate::observer::{DesktopObserver, NativeObserver};
+ // Resolve exact identity independently before Driver activation. A stale
+ // native id or ambiguous pid must not focus another client.
+ crate::observer::linux::hyprland_target_address(target).map_err(|error| error.to_string())?;
+ let observer = DesktopObserver::new(NativeObserver::new(), target);
+ observer.snapshot().map_err(|error| error.to_string())?;
+ let response = driver.call(
+ "bring_to_front",
+ serde_json::json!({
+ "pid": target.pid, "window_id": target.native_id,
+ }),
+ );
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
+ loop {
+ let after = observer.snapshot().map_err(|error| error.to_string())?;
+ if response.is_error() {
+ return Err(format!(
+ "Hyprland Driver activation failed: {}",
+ response.text()
+ ));
+ }
+ if after.target_z == TargetZ::Foreground
+ && after.foreground == Some(target.native_id)
+ && after.input_focus == Some(target.native_id)
+ {
+ return Ok(());
+ }
+ if std::time::Instant::now() >= deadline {
+ return Err(format!(
+ "Hyprland Driver activation did not focus target: {after:?}"
+ ));
+ }
+ std::thread::sleep(std::time::Duration::from_millis(25));
+ }
+}
+
+#[cfg(target_os = "linux")]
+pub(super) fn calibrate(
+ driver: &mut impl crate::Driver,
+ target: crate::observer::TargetWindow,
+) -> Result<(), String> {
+ struct NativeIo<'a, D> {
+ driver: &'a mut D,
+ target: crate::observer::TargetWindow,
+ }
+ impl<D: crate::Driver> CalibrationIo for NativeIo<'_, D> {
+ fn snapshot(&mut self) -> Result<DesktopSnapshot, String> {
+ use crate::observer::{DesktopObserver, NativeObserver};
+ // Bracket the explicit Driver action with fresh Driver perception,
+ // while retaining compositor queries as the independent oracle.
+ let state = self.driver.call("get_desktop_state", serde_json::json!({}));
+ if state.is_error() {
+ return Err(format!(
+ "Hyprland calibration perception failed: {}",
+ state.text()
+ ));
+ }
+ let snapshot = DesktopObserver::new(NativeObserver::new(), self.target)
+ .snapshot()
+ .map_err(|error| error.to_string())?;
+ let cursor = crate::observer::linux::hyprland_cursor_position()
+ .map_err(|error| error.to_string())?;
+ if snapshot.cursor_pos != Some(cursor) {
+ return Err("Hyprland cursor sample was unstable".into());
+ }
+ Ok(snapshot)
+ }
+ fn regions(&mut self) -> Result<Vec<Region>, String> {
+ crate::observer::linux::hyprland_monitor_regions().map_err(|error| error.to_string())
+ }
+ fn move_cursor(&mut self, point: Point) -> Result<(), String> {
+ let response = self.driver.call(
+ "move_cursor",
+ serde_json::json!({
+ "x": point.0, "y": point.1, "scope": "desktop",
+ }),
+ );
+ if response.is_error() {
+ Err(format!(
+ "Hyprland explicit desktop cursor move failed: {}",
+ response.text()
+ ))
+ } else {
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ Ok(())
+ }
+ }
+ fn restore_focus(&mut self) -> Result<(), String> {
+ activate(self.driver, self.target)
+ }
+ }
+ calibrate_io(&mut NativeIo { driver, target })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::VecDeque;
+
+ fn state(cursor: Point) -> DesktopSnapshot {
+ DesktopSnapshot {
+ foreground: Some(7),
+ input_focus: Some(7),
+ target_z: TargetZ::Foreground,
+ cursor_pos: Some(cursor),
+ }
+ }
+ struct FakeIo {
+ snapshots: VecDeque<Result<DesktopSnapshot, String>>,
+ moves: Vec<Point>,
+ focus_restored: bool,
+ fail_move: bool,
+ fail_restore: bool,
+ }
+ impl CalibrationIo for FakeIo {
+ fn snapshot(&mut self) -> Result<DesktopSnapshot, String> {
+ self.snapshots.pop_front().unwrap()
+ }
+ fn regions(&mut self) -> Result<Vec<Region>, String> {
+ Ok(vec![(0.0, 0.0, 100.0, 100.0)])
+ }
+ fn move_cursor(&mut self, point: Point) -> Result<(), String> {
+ self.moves.push(point);
+ if self.fail_move || (self.fail_restore && self.moves.len() == 2) {
+ Err("injected move failure".into())
+ } else {
+ Ok(())
+ }
+ }
+ fn restore_focus(&mut self) -> Result<(), String> {
+ self.focus_restored = true;
+ Ok(())
+ }
+ }
+ fn io(samples: Vec<Result<DesktopSnapshot, String>>) -> FakeIo {
+ FakeIo {
+ snapshots: samples.into(),
+ moves: vec![],
+ focus_restored: false,
+ fail_move: false,
+ fail_restore: false,
+ }
+ }
+ #[test]
+ fn destination_uses_real_scaled_monitor_with_negative_origin() {
+ let regions = [
+ (-1280.0, -720.0, 1280.0, 720.0),
+ (200.0, 0.0, 1920.0, 1080.0),
+ ];
+ assert_eq!(
+ canary_destination((-640.0, -360.0), &regions).unwrap(),
+ (-960.0, -540.0)
+ );
+ assert!(canary_destination((100.0, 100.0), &regions).is_err());
+ }
+ #[test]
+ fn destination_rejects_invalid_or_tiny_regions() {
+ for region in [
+ (0.0, 0.0, f64::NAN, 100.0),
+ (0.0, 0.0, 1.0, 1.0),
+ (0.0, 0.0, -1.0, 100.0),
+ ] {
+ assert!(canary_destination((0.0, 0.0), &[region]).is_err());
+ }
+ }
+ #[test]
+ fn calibration_requires_destination_and_verified_restore() {
+ let original = state((50.0, 50.0));
+ let mut io = io(vec![
+ Ok(original.clone()),
+ Ok(original.clone()),
+ Ok(state((25.0, 25.0))),
+ Ok(original),
+ ]);
+ assert!(calibrate_io(&mut io).is_ok());
+ assert_eq!(io.moves, [(25.0, 25.0), (50.0, 50.0)]);
+ assert!(io.focus_restored);
+ }
+ #[test]
+ fn arbitrary_motion_or_query_error_never_calibrates_and_always_restores() {
+ for moved in [Ok(state((60.0, 60.0))), Err("query failed".into())] {
+ let original = state((50.0, 50.0));
+ let mut io = io(vec![
+ Ok(original.clone()),
+ Ok(original.clone()),
+ moved,
+ Ok(original),
+ ]);
+ assert!(calibrate_io(&mut io).is_err());
+ assert_eq!(io.moves.last(), Some(&(50.0, 50.0)));
+ assert!(io.focus_restored);
+ }
+ }
+ #[test]
+ fn negative_sample_failure_still_restores() {
+ let original = state((50.0, 50.0));
+ for negative in [Ok(state((51.0, 50.0))), Err("query failed".into())] {
+ let mut io = io(vec![Ok(original.clone()), negative, Ok(original.clone())]);
+ assert!(calibrate_io(&mut io).is_err());
+ assert_eq!(io.moves, [(50.0, 50.0)]);
+ assert!(io.focus_restored);
+ }
+ }
+ #[test]
+ fn failed_move_still_attempts_all_cleanup() {
+ let original = state((50.0, 50.0));
+ let mut io = io(vec![
+ Ok(original.clone()),
+ Ok(original.clone()),
+ Ok(original),
+ ]);
+ io.fail_move = true;
+ assert!(calibrate_io(&mut io).is_err());
+ assert_eq!(io.moves.len(), 2);
+ assert!(io.focus_restored);
+ }
+ #[test]
+ fn restoration_query_posture_or_move_failure_is_fatal() {
+ let original = state((50.0, 50.0));
+ let mut changed = original.clone();
+ changed.foreground = Some(8);
+ for restored in [
+ Err("restore query failed".into()),
+ Ok(changed),
+ Ok(state((40.0, 40.0))),
+ Ok(state((50.5, 50.0))),
+ ] {
+ let mut io = io(vec![
+ Ok(original.clone()),
+ Ok(original.clone()),
+ Ok(state((25.0, 25.0))),
+ restored,
+ ]);
+ assert!(calibrate_io(&mut io).is_err());
+ }
+ let mut io = io(vec![
+ Ok(original.clone()),
+ Ok(original.clone()),
+ Ok(state((25.0, 25.0))),
+ Ok(original),
+ ]);
+ io.fail_restore = true;
+ assert!(calibrate_io(&mut io).is_err());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/hyprland_native_observation_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/hyprland_native_observation_test.rs
new file mode 100644
index 0000000000..a8756233d2
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/hyprland_native_observation_test.rs
@@ -0,0 +1,145 @@
+//! Focused native Hyprland regression; supplements, never replaces, the
+//! canonical desktop matrix. Run only in a disposable Hyprland desktop with
+//! the repository GTK3 fixture and exact-candidate Driver installed.
+#![cfg(target_os = "linux")]
+
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use cua_driver_testkit::e2e::OracleKind;
+use cua_driver_testkit::observer::{DesktopObserver, NativeObserver, TargetWindow, TargetZ};
+use cua_driver_testkit::{harness_app, spawn_in_job, Driver, McpDriver, ToolResponse};
+use serde_json::json;
+
+fn launch(driver: &mut McpDriver) -> TargetWindow {
+ let child = spawn_in_job(
+ Command::new(harness_app("harness-gtk3", "CuaTestHarness.Gtk3"))
+ .stdout(Stdio::null())
+ .stderr(Stdio::inherit()),
+ )
+ .expect("launch repository GTK3 fixture");
+ let pid = child.id();
+ driver.reaper().push(child);
+ let deadline = Instant::now() + Duration::from_secs(15);
+ loop {
+ let windows = driver.call("list_windows", json!({"pid": pid}));
+ if let Some(window) = windows.structured()["windows"].as_array().and_then(|ws| {
+ ws.iter().find(|w| {
+ w["pid"].as_u64() == Some(u64::from(pid))
+ && w["title"].as_str() == Some("CuaTestHarness GTK3")
+ })
+ }) {
+ return TargetWindow {
+ pid,
+ native_id: window["window_id"].as_u64().unwrap(),
+ };
+ }
+ assert!(
+ Instant::now() < deadline,
+ "GTK3 fixture did not map: {}",
+ windows.text()
+ );
+ std::thread::sleep(Duration::from_millis(100));
+ }
+}
+
+fn snapshot(driver: &mut McpDriver, target: TargetWindow) -> ToolResponse {
+ let state = driver.call(
+ "get_window_state",
+ json!({"pid": target.pid, "window_id": target.native_id}),
+ );
+ assert!(!state.is_error(), "{}", state.text());
+ assert!(
+ state.structured().get("screenshot_error").is_none(),
+ "{}",
+ state.structured()
+ );
+ assert!(state.structured()["screenshot_width"].as_u64().unwrap_or(0) > 0);
+ assert!(
+ state.tree_text().contains("HARNESS_TEXT_MARKER_v1"),
+ "{}",
+ state.tree_text()
+ );
+ state
+}
+
+#[test]
+#[ignore = "requires disposable native Hyprland, GTK3 fixture, and exact-candidate Driver"]
+fn native_window_capture_and_background_ax_keep_exact_identity() {
+ assert!(std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some());
+ assert_eq!(
+ std::env::var("CUA_DRIVER_RS_ENABLE_WAYLAND").as_deref(),
+ Ok("1")
+ );
+ let mut driver = McpDriver::spawn_named_with_overlay("hyprland-native-observation")
+ .expect("exact-candidate Driver is required");
+ let target = launch(&mut driver);
+ snapshot(&mut driver, target);
+ let foreground = launch(&mut driver);
+ snapshot(&mut driver, foreground);
+ std::thread::sleep(Duration::from_millis(500));
+
+ let before = snapshot(&mut driver, target);
+ let token = before.structured()["elements"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|element| element["label"].as_str() == Some("btn-increment"))
+ .and_then(|element| element["element_token"].as_str())
+ .expect("exact-window increment token")
+ .to_owned();
+ let mut observer = DesktopObserver::new(NativeObserver::new(), target);
+ let baseline = observer.snapshot().expect("independent Hyprland observer");
+ assert_eq!(baseline.foreground, Some(foreground.native_id));
+ assert!(matches!(
+ baseline.target_z,
+ TargetZ::BackgroundVisible | TargetZ::BackgroundOccluded
+ ));
+ let (clicked, delta) = observer
+ .observe(
+ &[OracleKind::Focus, OracleKind::ZOrder, OracleKind::Cursor],
+ || driver.call("click", json!({"pid": target.pid, "element_token": token})),
+ )
+ .expect("independent action observation");
+ assert!(!clicked.is_error(), "{}", clicked.text());
+ delta.ensure_supported().unwrap();
+ assert!(delta.violations().is_empty(), "{:?}", delta.violations());
+ assert_eq!(delta.before.cursor_pos, delta.after.cursor_pos);
+ let after = snapshot(&mut driver, target);
+ assert!(
+ after.tree_text().contains("counter=1"),
+ "{}",
+ after.tree_text()
+ );
+ assert!(snapshot(&mut driver, foreground)
+ .tree_text()
+ .contains("counter=0"));
+
+ // An explicit owner mismatch and a token paired with a sibling address
+ // must refuse before any accessibility actuation.
+ let wrong_owner = driver.call(
+ "get_window_state",
+ json!({
+ "pid": foreground.pid, "window_id": target.native_id,
+ }),
+ );
+ assert!(wrong_owner.is_error());
+ let fresh = snapshot(&mut driver, target);
+ let token = fresh.structured()["elements"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|element| element["label"].as_str() == Some("btn-increment"))
+ .and_then(|element| element["element_token"].as_str())
+ .unwrap();
+ let conflict = driver.call(
+ "click",
+ json!({
+ "pid": target.pid, "window_id": foreground.native_id, "element_token": token,
+ }),
+ );
+ assert!(conflict.is_error());
+ assert!(snapshot(&mut driver, target)
+ .tree_text()
+ .contains("counter=1"));
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
index 5021c634f8..35b526289d 100644
--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
@@ -46,6 +46,9 @@ meval = "0.2"
wayland-client = "0.31"
wayland-backend = "0.3"
wayland-scanner = "0.31"
+# Vendored toplevel-export bindings and bounded compositor IPC connections.
+bitflags = "2"
+socket2 = "0.6"
wayland-protocols-wlr = { version = "0.3", features = ["client"] }
# Wayland staging protocols: ext-foreign-toplevel-list-v1,
# ext-image-capture-source-v1, ext-image-copy-capture-v1 (per-window
diff --git a/libs/cua-driver/rust/crates/platform-linux/protocols/hyprland-toplevel-export-v1.xml b/libs/cua-driver/rust/crates/platform-linux/protocols/hyprland-toplevel-export-v1.xml
new file mode 100644
index 0000000000..b1185aa54f
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/protocols/hyprland-toplevel-export-v1.xml
@@ -0,0 +1,228 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="hyprland_toplevel_export_v1">
+ <copyright>
+ Copyright © 2022 Vaxry
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ 3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ </copyright>
+
+ <description summary="capturing the contents of toplevel windows">
+ This protocol allows clients to ask for exporting another toplevel's
+ surface(s) to a buffer.
+
+ Particularly useful for sharing a single window.
+ </description>
+
+ <interface name="hyprland_toplevel_export_manager_v1" version="2">
+ <description summary="manager to inform clients and begin capturing">
+ This object is a manager which offers requests to start capturing from a
+ source.
+ </description>
+
+ <request name="capture_toplevel">
+ <description summary="capture a toplevel">
+ Capture the next frame of a toplevel. (window)
+
+ The captured frame will not contain any server-side decorations and will
+ ignore the compositor-set geometry, like e.g. rounded corners.
+
+ It will contain all the subsurfaces and popups, however the latter will be clipped
+ to the geometry of the base surface.
+
+ The handle parameter refers to the address of the window as seen in `hyprctl clients`.
+ For example, for d161e7b0 it would be 3512854448.
+ </description>
+ <arg name="frame" type="new_id" interface="hyprland_toplevel_export_frame_v1"/>
+ <arg name="overlay_cursor" type="int"
+ summary="composite cursor onto the frame"/>
+ <arg name="handle" type="uint" summary="the handle of the toplevel (window) to be captured"/>
+ </request>
+
+ <request name="destroy" type="destructor">
+ <description summary="destroy the manager">
+ All objects created by the manager will still remain valid, until their
+ appropriate destroy request has been called.
+ </description>
+ </request>
+
+ <!-- Version 2 -->
+ <request name="capture_toplevel_with_wlr_toplevel_handle" since="2">
+ <description summary="capture a toplevel">
+ Same as capture_toplevel, but with a zwlr_foreign_toplevel_handle_v1 handle.
+ </description>
+ <arg name="frame" type="new_id" interface="hyprland_toplevel_export_frame_v1"/>
+ <arg name="overlay_cursor" type="int"
+ summary="composite cursor onto the frame"/>
+ <arg name="handle" type="object" interface="zwlr_foreign_toplevel_handle_v1" allow-null="false" summary="the zwlr_foreign_toplevel_handle_v1 handle of the toplevel to be captured"/>
+ </request>
+ <!-- End Version 2 -->
+ </interface>
+
+ <interface name="hyprland_toplevel_export_frame_v1" version="2">
+ <description summary="a frame ready for copy">
+ This object represents a single frame.
+
+ When created, a series of buffer events will be sent, each representing a
+ supported buffer type. The "buffer_done" event is sent afterwards to
+ indicate that all supported buffer types have been enumerated. The client
+ will then be able to send a "copy" request. If the capture is successful,
+ the compositor will send a "flags" followed by a "ready" event.
+
+ wl_shm buffers are always supported, ie. the "buffer" event is guaranteed to be sent.
+
+ If the capture failed, the "failed" event is sent. This can happen anytime
+ before the "ready" event.
+
+ Once either a "ready" or a "failed" event is received, the client should
+ destroy the frame.
+ </description>
+
+ <event name="buffer">
+ <description summary="wl_shm buffer information">
+ Provides information about wl_shm buffer parameters that need to be
+ used for this frame. This event is sent once after the frame is created
+ if wl_shm buffers are supported.
+ </description>
+ <arg name="format" type="uint" enum="wl_shm.format" summary="buffer format"/>
+ <arg name="width" type="uint" summary="buffer width"/>
+ <arg name="height" type="uint" summary="buffer height"/>
+ <arg name="stride" type="uint" summary="buffer stride"/>
+ </event>
+
+ <request name="copy">
+ <description summary="copy the frame">
+ Copy the frame to the supplied buffer. The buffer must have the
+ correct size, see hyprland_toplevel_export_frame_v1.buffer and
+ hyprland_toplevel_export_frame_v1.linux_dmabuf. The buffer needs to have a
+ supported format.
+
+ If the frame is successfully copied, a "flags" and a "ready" event is
+ sent. Otherwise, a "failed" event is sent.
+
+ This event will wait for appropriate damage to be copied, unless the ignore_damage
+ arg is set to a non-zero value.
+ </description>
+ <arg name="buffer" type="object" interface="wl_buffer"/>
+ <arg name="ignore_damage" type="int"/>
+ </request>
+
+ <event name="damage">
+ <description summary="carries the coordinates of the damaged region">
+ This event is sent right before the ready event when ignore_damage was
+ not set. It may be generated multiple times for each copy
+ request.
+
+ The arguments describe a box around an area that has changed since the
+ last copy request that was derived from the current screencopy manager
+ instance.
+
+ The union of all regions received between the call to copy
+ and a ready event is the total damage since the prior ready event.
+ </description>
+ <arg name="x" type="uint" summary="damaged x coordinates"/>
+ <arg name="y" type="uint" summary="damaged y coordinates"/>
+ <arg name="width" type="uint" summary="current width"/>
+ <arg name="height" type="uint" summary="current height"/>
+ </event>
+
+ <enum name="error">
+ <entry name="already_used" value="0"
+ summary="the object has already been used to copy a wl_buffer"/>
+ <entry name="invalid_buffer" value="1"
+ summary="buffer attributes are invalid"/>
+ </enum>
+
+ <enum name="flags" bitfield="true">
+ <entry name="y_invert" value="1" summary="contents are y-inverted"/>
+ </enum>
+
+ <event name="flags">
+ <description summary="frame flags">
+ Provides flags about the frame. This event is sent once before the
+ "ready" event.
+ </description>
+ <arg name="flags" type="uint" enum="flags" summary="frame flags"/>
+ </event>
+
+ <event name="ready">
+ <description summary="indicates frame is available for reading">
+ Called as soon as the frame is copied, indicating it is available
+ for reading. This event includes the time at which presentation happened
+ at.
+
+ The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples,
+ each component being an unsigned 32-bit value. Whole seconds are in
+ tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo,
+ and the additional fractional part in tv_nsec as nanoseconds. Hence,
+ for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part
+ may have an arbitrary offset at start.
+
+ After receiving this event, the client should destroy the object.
+ </description>
+ <arg name="tv_sec_hi" type="uint"
+ summary="high 32 bits of the seconds part of the timestamp"/>
+ <arg name="tv_sec_lo" type="uint"
+ summary="low 32 bits of the seconds part of the timestamp"/>
+ <arg name="tv_nsec" type="uint"
+ summary="nanoseconds part of the timestamp"/>
+ </event>
+
+ <event name="failed">
+ <description summary="frame copy failed">
+ This event indicates that the attempted frame copy has failed.
+
+ After receiving this event, the client should destroy the object.
+ </description>
+ </event>
+
+ <request name="destroy" type="destructor">
+ <description summary="delete this object, used or not">
+ Destroys the frame. This request can be sent at any time by the client.
+ </description>
+ </request>
+
+ <event name="linux_dmabuf">
+ <description summary="linux-dmabuf buffer information">
+ Provides information about linux-dmabuf buffer parameters that need to
+ be used for this frame. This event is sent once after the frame is
+ created if linux-dmabuf buffers are supported.
+ </description>
+ <arg name="format" type="uint" summary="fourcc pixel format"/>
+ <arg name="width" type="uint" summary="buffer width"/>
+ <arg name="height" type="uint" summary="buffer height"/>
+ </event>
+
+ <event name="buffer_done">
+ <description summary="all buffer types reported">
+ This event is sent once after all buffer events have been sent.
+
+ The client should proceed to create a buffer of one of the supported
+ types, and send a "copy" request.
+ </description>
+ </event>
+ </interface>
+</protocol>
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
index faf7d32845..51ff02fd10 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
@@ -246,6 +246,14 @@ pub fn get_element_bounds(pid: u32, idx: usize) -> Result<(i32, i32, u32, u32)>
native::get_element_bounds(pid, idx)
}
+pub fn get_element_bounds_for_window(
+ pid: u32,
+ xid: u64,
+ idx: usize,
+) -> Result<(i32, i32, u32, u32)> {
+ native::get_element_bounds_for_window(pid, xid, idx)
+}
+
// ── Internal helpers ─────────────────────────────────────────────────────────
/// Minimal X11 property-based tree (fallback when AT-SPI is unavailable).
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
index 01dfc99795..fce3a49f2c 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
@@ -15,7 +15,7 @@
use std::sync::OnceLock;
use std::time::Duration;
-use anyhow::{anyhow, Result};
+use anyhow::{anyhow, Context, Result};
use atspi::connection::{AccessibilityConnection, P2P};
use atspi::proxy::accessible::AccessibleProxy;
use atspi::proxy::proxy_ext::ProxyExt;
@@ -606,6 +606,30 @@ async fn resolve_window_frame(
xid: u64,
seeds: &[RawObjectRef],
) -> Option<usize> {
+ if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ let window = crate::wayland::hyprland::accessibility_window(xid, pid)?;
+ let mut matches = Vec::new();
+ for (ordinal, oref) in seeds.iter().enumerate() {
+ let Some(Ok(acc)) = call(accessible_for(conn, oref)).await else {
+ continue;
+ };
+ let Some(Ok(role)) = call(acc.get_role_name()).await else {
+ continue;
+ };
+ if !matches!(
+ role.as_str(),
+ "frame" | "window" | "dialog" | "alert" | "file chooser"
+ ) {
+ continue;
+ }
+ if matches!(call(acc.name()).await, Some(Ok(name)) if name == window.title) {
+ matches.push(ordinal);
+ }
+ }
+ // Title is only an AX-to-client correlation within the already
+ // attested PID. Duplicate frame names must never select a sibling.
+ return (matches.len() == 1).then(|| matches[0]);
+ }
if seeds.len() == 1 {
// One top-level: the caller's window is the only thing this
// application could be showing, and no geometry round-trip can make
@@ -1178,7 +1202,7 @@ pub(super) fn walk_tree_bounded_with_timeout(
let (markdown, nodes) = render(&visited, scoped_frame);
let bounds = match before_snapshot_deadline(
deadline,
- element_bounds_for_visited(&visited, pid, xid),
+ element_bounds_for_visited(&visited, pid, xid, scoped_frame),
)
.await
{
@@ -2108,7 +2132,7 @@ pub fn perform_action_at_point(pid: u32, win_x: i32, win_y: i32) -> Result<Optio
Some(v) => v,
None => return Ok(None),
};
- let web_document_origin = web_document_origin_for_visited(&visited, pid)
+ let web_document_origin = web_document_origin_for_visited(&visited, pid, None)
.await
.unwrap_or((0, 0));
@@ -2209,7 +2233,7 @@ pub fn perform_action_at_screen_point(
Some(v) => v,
None => return Ok(None),
};
- let web_document_origin = web_document_origin_for_visited(&visited, pid)
+ let web_document_origin = web_document_origin_for_visited(&visited, pid, None)
.await
.unwrap_or((0, 0));
@@ -2394,13 +2418,18 @@ pub fn set_value(pid: u32, idx: usize, value: &str) -> Result<()> {
}
pub fn get_element_bounds(pid: u32, idx: usize) -> Result<(i32, i32, u32, u32)> {
+ if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ let window = crate::wayland::hyprland::window_for_pid(pid)
+ .context("Hyprland bounds require an exact window for multi-window apps")?;
+ return get_element_bounds_for_window(pid, window.address, idx);
+ }
bounded(
async {
let conn = shared_connection().await?;
let visited = collect_visited(conn, pid)
.await?
.ok_or_else(|| anyhow!("no AT-SPI application for pid {pid}"))?;
- let web_document_origin = web_document_origin_for_visited(&visited, pid)
+ let web_document_origin = web_document_origin_for_visited(&visited, pid, None)
.await
.unwrap_or((0, 0));
let action_nodes: Vec<&Visited> = visited.iter().filter(|v| is_indexable(v)).collect();
@@ -2456,6 +2485,41 @@ pub fn get_element_bounds(pid: u32, idx: usize) -> Result<(i32, i32, u32, u32)>
)
}
+pub fn get_element_bounds_for_window(
+ pid: u32,
+ xid: u64,
+ idx: usize,
+) -> Result<(i32, i32, u32, u32)> {
+ if !crate::wayland::is_wayland() || !crate::wayland::hyprland::is_session() {
+ return get_element_bounds(pid, idx);
+ }
+ bounded(
+ async {
+ let conn = shared_connection().await?;
+ let (visited, scoped_frame) = collect_visited_bounded(conn, pid, xid, None, None)
+ .await?
+ .context("no AT-SPI application")?;
+ let scope =
+ scoped_frame.context("Hyprland accessibility window identity is unproven")?;
+ let target = visited
+ .iter()
+ .filter(|v| is_indexable(v))
+ .nth(idx)
+ .context("element no longer exists")?;
+ if target.frame_ordinal != scope {
+ return Err(anyhow!("element does not belong to the requested window"));
+ }
+ element_bounds_for_visited(&visited, pid, xid, Some(scope))
+ .await
+ .into_iter()
+ .find(|(index, ..)| *index == idx)
+ .map(|(_, x, y, w, h)| (x, y, w, h))
+ .context("element has no compositor-attested screen bounds")
+ },
+ || Err(anyhow!("Hyprland element bounds timed out")),
+ )
+}
+
/// Real on-screen origin (root-relative top-left) of an X11 window, or `None`
/// if it can't be resolved. Mirrors `list_windows`' geometry path.
fn x11_window_origin(xid: u64) -> Option<(i32, i32)> {
@@ -2541,6 +2605,16 @@ fn parse_gtk_frame_extents(vals: &[u32]) -> Option<(i32, i32)> {
/// query screen origins, by design) or when no X11 window resolves.
fn window_to_screen_offset(pid: u32, xid: u64, title: Option<&str>) -> Option<(i32, i32)> {
if crate::wayland::is_wayland() {
+ if crate::wayland::hyprland::is_session() {
+ // Never promote toolkit-local coordinates or a stale PID origin
+ // to screen coordinates when native target geometry is missing.
+ let window = if xid != 0 {
+ crate::wayland::hyprland::window_for_address(xid)
+ } else {
+ crate::wayland::hyprland::window_for_pid(pid)
+ }?;
+ return (window.pid == pid).then_some((window.x, window.y));
+ }
// Native Wayland: clients can't query a window's screen origin, and
// AT-SPI CoordType::Screen collapses to (0,0) on Mutter. The bundled
// `org.cua.WinRects` GNOME Shell extension supplies the window's screen
@@ -2634,7 +2708,11 @@ fn combine_wayland_content_offsets(
/// Compositor decorations and toolkit document offsets are independent and
/// therefore additive: choosing one or the other leaves WebKit controls one
/// title bar away from the pixels shown to the caller.
-async fn web_document_origin_for_visited(visited: &[Visited<'_>], pid: u32) -> Option<(i32, i32)> {
+async fn web_document_origin_for_visited(
+ visited: &[Visited<'_>],
+ pid: u32,
+ scoped_frame: Option<usize>,
+) -> Option<(i32, i32)> {
if !crate::wayland::is_wayland() {
return None;
}
@@ -2644,6 +2722,7 @@ async fn web_document_origin_for_visited(visited: &[Visited<'_>], pid: u32) -> O
.map(|window| (window.content_x, window.content_y));
let document = visited
.iter()
+ .filter(|node| scoped_frame.is_none_or(|scope| node.frame_ordinal == scope))
.filter(|node| node.has_component)
.filter(|node| is_document_role(&node.role) || node.in_web_doc)
.min_by_key(|node| node.depth);
@@ -2675,7 +2754,9 @@ async fn web_document_origin_for_visited(visited: &[Visited<'_>], pid: u32) -> O
} else {
None
};
- let document_is_separate = visited.iter().any(|node| node.on_web_process_bus);
+ let document_is_separate = visited.iter().any(|node| {
+ scoped_frame.is_none_or(|scope| node.frame_ordinal == scope) && node.on_web_process_bus
+ });
let combined = combine_wayland_content_offsets(compositor, document, document_is_separate);
dlog!(
"Wayland web content offset: compositor={compositor:?} document={document:?} separate_process={document_is_separate} combined={combined:?}"
@@ -2738,6 +2819,7 @@ async fn element_bounds_for_visited(
visited: &[Visited<'_>],
pid: u32,
xid: u64,
+ scoped_frame: Option<usize>,
) -> Vec<(usize, i32, i32, u32, u32)> {
// Query WINDOW-relative extents and add a deterministic screen offset
// (X11 window origin + GTK4 CSD inset). This fixes GTK4 — whose
@@ -2746,13 +2828,20 @@ async fn element_bounds_for_visited(
// window resolves, `offset` is None and we keep the legacy Screen path
// so non-X11 behaviour is unchanged.
let window_title = visited.iter().find_map(|node| {
- matches!(
- node.role.to_ascii_lowercase().as_str(),
- "frame" | "window" | "dialog" | "alert" | "file chooser"
- )
+ (scoped_frame.is_none_or(|scope| node.frame_ordinal == scope)
+ && matches!(
+ node.role.to_ascii_lowercase().as_str(),
+ "frame" | "window" | "dialog" | "alert" | "file chooser"
+ ))
.then_some(node.name.as_str())
});
let offset = window_to_screen_offset(pid, xid, window_title);
+ if crate::wayland::is_wayland()
+ && crate::wayland::hyprland::is_session()
+ && (offset.is_none() || scoped_frame.is_none())
+ {
+ return Vec::new();
+ }
let coord = if offset.is_some() {
CoordType::Window
} else {
@@ -2768,7 +2857,8 @@ async fn element_bounds_for_visited(
let screen_rebase = if offset.is_none() && !crate::wayland::is_wayland() && xid != 0 {
let x11_origin = x11_window_origin(xid);
let frame = visited.iter().find(|node| {
- node.has_component
+ scoped_frame.is_none_or(|scope| node.frame_ordinal == scope)
+ && node.has_component
&& matches!(
node.role.to_ascii_lowercase().as_str(),
"frame" | "window" | "dialog" | "alert" | "file chooser"
@@ -2801,7 +2891,8 @@ async fn element_bounds_for_visited(
// no-op there.
let window_frame_origin = if offset.is_some() {
let frame = visited.iter().find(|node| {
- node.has_component
+ scoped_frame.is_none_or(|scope| node.frame_ordinal == scope)
+ && node.has_component
&& matches!(
node.role.to_ascii_lowercase().as_str(),
"frame" | "window" | "dialog" | "alert" | "file chooser"
@@ -2830,7 +2921,7 @@ async fn element_bounds_for_visited(
// descendants only. Electron commonly contributes zero for both; WebKitGTK
// under Sway needs the sum.
let web_document_origin = if offset.is_some() {
- web_document_origin_for_visited(visited, pid).await
+ web_document_origin_for_visited(visited, pid, scoped_frame).await
} else {
None
};
@@ -2854,6 +2945,9 @@ async fn element_bounds_for_visited(
let deadline = std::time::Instant::now() + Duration::from_secs(20);
let mut out = Vec::with_capacity(action_nodes.len());
for (idx, node) in action_nodes.iter().enumerate() {
+ if scoped_frame.is_some_and(|scope| node.frame_ordinal != scope) {
+ continue;
+ }
if std::time::Instant::now() >= deadline {
dlog!(
"snapshot bounds: 20s budget exhausted at node {idx}; returning {} bound(s)",
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 cb340012f3..508521f6e5 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
@@ -91,7 +91,7 @@ fn element_window_local_xy_blocking(
) -> Option<(f64, f64)> {
let pid = u32::try_from(pid).ok()?;
let (screen_x, screen_y, width, height) =
- crate::atspi::get_element_bounds(pid, element_index as usize).ok()?;
+ crate::atspi::get_element_bounds_for_window(pid, window_id, element_index as usize).ok()?;
let window = resolve_window_for_recording(pid, Some(window_id))?;
Some((
f64::from(screen_x - window.x) + f64::from(width) / 2.0,
@@ -105,6 +105,13 @@ fn resolve_window_for_recording(
window_id: Option<u64>,
) -> Option<crate::x11::WindowInfo> {
let windows = crate::wayland::list_windows_dispatch(Some(pid));
+ if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ return match window_id {
+ Some(id) => windows.into_iter().find(|window| window.xid == id),
+ None if windows.len() == 1 => windows.into_iter().next(),
+ _ => None,
+ };
+ }
if crate::wayland::is_wayland() {
// Foreign-toplevel protocol object ids are scoped to one Wayland
// connection. Recording hooks open a fresh connection, so re-resolve
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 0c7a8a44d6..b9416c1655 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
@@ -774,7 +774,7 @@ impl Tool for GetWindowStateTool {
// Tuple: (Option<b64>, Option<file_path>, w, h, Option<original_w>).
let mut screenshot_error = None;
let screenshot = if should_capture {
- match crate::wayland::screenshot_dispatch(xid) {
+ match crate::wayland::screenshot_dispatch_with_pid(xid, pid) {
Ok(raw) => {
let orig_w = crate::capture::png_dimensions_pub(&raw)
.map(|(w, _)| w)
@@ -838,9 +838,21 @@ impl Tool for GetWindowStateTool {
// by an opaque per-snapshot `element_token` alongside
// its existing integer `element_index`. The integer
// surface stays unchanged — the token is additive.
- let snapshot_id = (!observation_only).then(|| {
- cua_driver_core::element_token::global()
- .register_snapshot(pid as i32, xid as u32, count)
+ let target_scoped = !(crate::wayland::is_wayland()
+ && crate::wayland::hyprland::is_session())
+ || tr.window_scoped;
+ if !observation_only && !target_scoped {
+ cua_driver_core::element_token::global().invalidate_window(pid as i32, xid);
+ }
+ let snapshot_id = (!observation_only && target_scoped).then(|| {
+ cua_driver_core::element_token::global().register_snapshot_indices(
+ pid as i32,
+ xid,
+ &tr.nodes
+ .iter()
+ .filter_map(|node| node.element_index)
+ .collect::<Vec<_>>(),
+ )
});
// Structured `elements` array: one entry per actionable node.
@@ -936,7 +948,10 @@ impl Tool for GetWindowStateTool {
// daemon isn't on the desktop session bus so the registry is
// empty), or it's a non-AX surface (canvas/WebGL). Mark it
// degraded so callers don't read `elements: []` as authoritative.
- if !source_trusted {
+ if !target_scoped {
+ structured["degraded"] = json!(true);
+ structured["degraded_reason"] = json!("accessibility_window_identity_unproven: tree is application-scoped; exact-window element tokens and bounds are unavailable");
+ } else if !source_trusted {
structured["degraded"] = json!(true);
structured["degraded_reason"] = json!(source_degraded_reason
.unwrap_or_else(|| {
@@ -1525,7 +1540,11 @@ fn resolve_element_local_coords(
idx: usize,
xid_hint: Option<u64>,
) -> anyhow::Result<(u64, f64, f64)> {
- let (bx, by, bw, bh) = crate::atspi::get_element_bounds(pid, idx)?;
+ let (bx, by, bw, bh) = if let Some(xid) = xid_hint {
+ crate::atspi::get_element_bounds_for_window(pid, xid, idx)?
+ } else {
+ crate::atspi::get_element_bounds(pid, idx)?
+ };
let screen_cx = bx as f64 + bw as f64 / 2.0;
let screen_cy = by as f64 + bh as f64 / 2.0;
@@ -1572,8 +1591,11 @@ fn resolve_element_local_coords(
Ok((xid, local_x, local_y))
}
-fn element_screen_center(pid: u32, idx: usize) -> anyhow::Result<(f64, f64)> {
- let (bx, by, bw, bh) = crate::atspi::get_element_bounds(pid, idx)?;
+fn element_screen_center(pid: u32, idx: usize, xid: Option<u64>) -> anyhow::Result<(f64, f64)> {
+ let (bx, by, bw, bh) = match xid {
+ Some(xid) => crate::atspi::get_element_bounds_for_window(pid, xid, idx)?,
+ None => crate::atspi::get_element_bounds(pid, idx)?,
+ };
Ok((bx as f64 + bw as f64 / 2.0, by as f64 + bh as f64 / 2.0))
}
@@ -2226,7 +2248,7 @@ fn explicit_keyboard_cursor_target(
pixel_target: Option<(f64, f64)>,
) -> Option<(f64, f64)> {
if let Some(element_index) = element_index {
- let (sx, sy) = element_screen_center(pid, element_index).ok()?;
+ let (sx, sy) = element_screen_center(pid, element_index, (xid != 0).then_some(xid)).ok()?;
return Some((sx, sy));
}
@@ -2619,12 +2641,12 @@ impl Tool for ClickTool {
let element_token_arg = args.opt_str("element_token");
let window_id_arg = args.opt_u64("window_id");
let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);
- let resolved = match cua_driver_core::element_token::resolve_element_args(
+ let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
element_index_arg,
element_token_arg.as_deref(),
args.opt_str("snapshot_id").as_deref(),
- window_id_arg.map(|v| v as u32),
+ window_id_arg,
"click",
) {
Ok(r) => r,
@@ -2650,27 +2672,31 @@ impl Tool for ClickTool {
// matching the coordinate path below and the macOS/Windows backends.
// Previously perform_action ran inside this spawn_blocking, so the
// app updated before the cursor visibly arrived.
- let (xid, sx, sy) = tokio::task::spawn_blocking(move || -> (u64, f64, f64) {
- let (cx, cy) = element_screen_center(pid, idx).unwrap_or((0.0, 0.0));
- let xid = xid_hint
- .or_else(|| {
- crate::x11::list_windows(Some(pid))
- .into_iter()
- .next()
- .map(|w| w.xid)
- })
- .unwrap_or(0);
- (xid, cx, cy)
- })
- .await
- .unwrap_or((0, 0.0, 0.0));
- if xid != 0 {
- crate::overlay::send_command_for(
- cursor_id.clone(),
- cursor_overlay::OverlayCommand::PinAbove(xid),
- );
+ let placement =
+ tokio::task::spawn_blocking(move || -> anyhow::Result<(u64, f64, f64)> {
+ let (cx, cy) = element_screen_center(pid, idx, xid_hint)?;
+ let xid = xid_hint
+ .or_else(|| {
+ crate::x11::list_windows(Some(pid))
+ .into_iter()
+ .next()
+ .map(|w| w.xid)
+ })
+ .unwrap_or(0);
+ Ok((xid, cx, cy))
+ })
+ .await
+ .ok()
+ .and_then(Result::ok);
+ if let Some((xid, sx, sy)) = placement {
+ if xid != 0 {
+ crate::overlay::send_command_for(
+ cursor_id.clone(),
+ cursor_overlay::OverlayCommand::PinAbove(xid),
+ );
+ }
+ reveal_pointer_action_for(&self.state, &cursor_id, sx, sy, true).await;
}
- reveal_pointer_action_for(&self.state, &cursor_id, sx, sy, true).await;
// Chromium can execute a genuine AT-SPI action without focus. Try
// that route before applying its background synthetic-input gate.
@@ -2712,6 +2738,8 @@ impl Tool for ClickTool {
// ignore a targeted XSendEvent; limiting XTest to modified
// clicks made those rows addressable but not selectable.
if delivery.is_foreground() && !crate::wayland::wayland_input_enabled() {
+ let (_, sx, sy) = placement
+ .ok_or_else(|| anyhow::anyhow!("element screen bounds unavailable"))?;
crate::input::with_x11_foreground(xid2, 80, || {
crate::input::send_click_xtest_desktop_with_modifiers(
sx.round() as i32,
@@ -3103,12 +3131,12 @@ impl Tool for TypeTextTool {
// Surface 6: resolve element_token / element_index for the
// optional pre-typing focus glide below. The token also carries
// the window_id when supplied so the caller can omit window_id.
- let resolved = match cua_driver_core::element_token::resolve_element_args(
+ let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
args.opt_u64("element_index").map(|v| v as usize),
args.opt_str("element_token").as_deref(),
args.opt_str("snapshot_id").as_deref(),
- args.opt_u64("window_id").map(|v| v as u32),
+ args.opt_u64("window_id"),
"type_text",
) {
Ok(r) => r,
@@ -3724,12 +3752,12 @@ impl Tool for PressKeyTool {
let element_token_arg = args.opt_str("element_token");
let window_id_arg = args.opt_u64("window_id");
let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);
- let resolved = match cua_driver_core::element_token::resolve_element_args(
+ let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
element_index_arg,
element_token_arg.as_deref(),
args.opt_str("snapshot_id").as_deref(),
- window_id_arg.map(|v| v as u32),
+ window_id_arg,
"press_key",
) {
Ok(r) => r,
@@ -4052,12 +4080,12 @@ impl Tool for HotkeyTool {
let pid = args.u64_or("pid", 0) as u32;
let window_id_arg = args.opt_u64("window_id");
let element_index_arg = args.opt_u64("element_index").map(|value| value as usize);
- let resolved = match cua_driver_core::element_token::resolve_element_args(
+ let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
element_index_arg,
args.opt_str("element_token").as_deref(),
args.opt_str("snapshot_id").as_deref(),
- window_id_arg.map(|value| value as u32),
+ window_id_arg,
"hotkey",
) {
Ok(resolved) => resolved,
@@ -4337,12 +4365,12 @@ impl Tool for SetValueTool {
Err(e) => return e,
};
// Surface 6: element_token / element_index precedence resolution.
- let resolved = match cua_driver_core::element_token::resolve_element_args(
+ let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
args.opt_u64("element_index").map(|v| v as usize),
args.opt_str("element_token").as_deref(),
args.opt_str("snapshot_id").as_deref(),
- args.opt_u64("window_id").map(|v| v as u32),
+ args.opt_u64("window_id"),
"set_value",
) {
Ok(r) => r,
@@ -4473,12 +4501,12 @@ impl Tool for ScrollTool {
// element (X11 scroll buttons go to the window root), but the
// token still needs to be accepted + validated so a stale
// token surfaces an error instead of silently no-op'ing.
- let resolved = match cua_driver_core::element_token::resolve_element_args(
+ let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
args.opt_u64("element_index").map(|v| v as usize),
args.opt_str("element_token").as_deref(),
args.opt_str("snapshot_id").as_deref(),
- args.opt_u64("window_id").map(|v| v as u32),
+ args.opt_u64("window_id"),
"scroll",
) {
Ok(r) => r,
@@ -4859,12 +4887,12 @@ impl Tool for DoubleClickTool {
return refusal;
}
// Surface 6: element_token / element_index precedence.
- let resolved = match cua_driver_core::element_token::resolve_element_args(
+ let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
args.opt_u64("element_index").map(|v| v as usize),
args.opt_str("element_token").as_deref(),
args.opt_str("snapshot_id").as_deref(),
- args.opt_u64("window_id").map(|v| v as u32),
+ args.opt_u64("window_id"),
"double_click",
) {
Ok(r) => r,
@@ -4890,8 +4918,10 @@ impl Tool for DoubleClickTool {
.await;
return match result {
Ok(Ok((xid, lx, ly))) => {
- if let Ok(Ok((sx, sy))) =
- tokio::task::spawn_blocking(move || element_screen_center(pid, idx)).await
+ if let Ok(Ok((sx, sy))) = tokio::task::spawn_blocking(move || {
+ element_screen_center(pid, idx, Some(xid))
+ })
+ .await
{
crate::overlay::send_command_for(
cursor_id.clone(),
@@ -5085,12 +5115,12 @@ impl Tool for RightClickTool {
return refusal;
}
// Surface 6: element_token / element_index precedence.
- let resolved = match cua_driver_core::element_token::resolve_element_args(
+ let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
args.opt_u64("element_index").map(|v| v as usize),
args.opt_str("element_token").as_deref(),
args.opt_str("snapshot_id").as_deref(),
- args.opt_u64("window_id").map(|v| v as u32),
+ args.opt_u64("window_id"),
"right_click",
) {
Ok(r) => r,
@@ -5116,8 +5146,10 @@ impl Tool for RightClickTool {
.await;
return match result {
Ok(Ok((xid, lx, ly))) => {
- if let Ok(Ok((sx, sy))) =
- tokio::task::spawn_blocking(move || element_screen_center(pid, idx)).await
+ if let Ok(Ok((sx, sy))) = tokio::task::spawn_blocking(move || {
+ element_screen_center(pid, idx, Some(xid))
+ })
+ .await
{
crate::overlay::send_command_for(
cursor_id.clone(),
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
new file mode 100644
index 0000000000..d92df0bab4
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs
@@ -0,0 +1,390 @@
+//! Read-only Hyprland identity and geometry, adapted from #3052.
+//!
+//! Native IDs are full compositor addresses, never title matches or truncated
+//! protocol object IDs. IPC and capture must belong to the same compositor.
+
+use anyhow::{bail, Context, Result};
+use serde::Deserialize;
+use std::collections::HashSet;
+use std::io::{Read, Write};
+use std::os::fd::{AsRawFd, RawFd};
+use std::os::unix::net::UnixStream;
+use std::path::PathBuf;
+use std::time::{Duration, Instant};
+
+const QUERY_TIMEOUT: Duration = Duration::from_secs(1);
+const MAX_REPLY_BYTES: usize = 4 * 1024 * 1024;
+const MAX_LOGICAL_PIXELS: u64 = 64 * 1024 * 1024;
+
+#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
+struct Workspace {
+ id: i64,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+struct Client {
+ address: String,
+ mapped: bool,
+ hidden: bool,
+ pid: i64,
+ title: String,
+ class: String,
+ at: [i32; 2],
+ size: [i32; 2],
+ workspace: Workspace,
+}
+
+#[derive(Deserialize)]
+struct Monitor {
+ #[serde(rename = "activeWorkspace")]
+ active_workspace: Workspace,
+ #[serde(rename = "specialWorkspace")]
+ special_workspace: Workspace,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Window {
+ pub address: u64,
+ pub pid: u32,
+ pub title: String,
+ pub app_id: String,
+ pub x: i32,
+ pub y: i32,
+ pub width: u32,
+ pub height: u32,
+ pub workspace: i64,
+ pub visible: bool,
+ hidden: bool,
+}
+
+pub fn is_session() -> bool {
+ !super::is_inject_mode()
+ && std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some_and(|s| !s.is_empty())
+}
+
+fn ipc_path() -> Result<PathBuf> {
+ let runtime = std::env::var_os("XDG_RUNTIME_DIR").context("missing XDG_RUNTIME_DIR")?;
+ let signature = std::env::var("HYPRLAND_INSTANCE_SIGNATURE")
+ .context("missing HYPRLAND_INSTANCE_SIGNATURE")?;
+ if signature.is_empty()
+ || !signature
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b == b'_')
+ {
+ bail!("invalid Hyprland instance signature");
+ }
+ let runtime = PathBuf::from(runtime);
+ if !runtime.is_absolute() {
+ bail!("XDG_RUNTIME_DIR must be absolute");
+ }
+ Ok(runtime.join("hypr").join(signature).join(".socket.sock"))
+}
+
+pub(super) fn peer_pid(fd: RawFd) -> Result<libc::pid_t> {
+ let mut cred: libc::ucred = unsafe { std::mem::zeroed() };
+ let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
+ let result = unsafe {
+ libc::getsockopt(
+ fd,
+ libc::SOL_SOCKET,
+ libc::SO_PEERCRED,
+ (&mut cred as *mut libc::ucred).cast(),
+ &mut len,
+ )
+ };
+ if result != 0
+ || len as usize != std::mem::size_of::<libc::ucred>()
+ || cred.pid <= 0
+ || cred.uid != unsafe { libc::geteuid() }
+ {
+ bail!("could not verify same-user compositor peer");
+ }
+ Ok(cred.pid)
+}
+
+fn ipc_connection() -> Result<UnixStream> {
+ let socket = socket2::Socket::new(socket2::Domain::UNIX, socket2::Type::STREAM, None)?;
+ socket.connect_timeout(&socket2::SockAddr::unix(ipc_path()?)?, QUERY_TIMEOUT)?;
+ Ok(socket.into())
+}
+
+/// Bound the socket connection as well as protocol dispatch. Inherited
+/// WAYLAND_SOCKET descriptors are deliberately unsupported here: this adapter
+/// opens independent, attested connections for each observation.
+pub(super) fn wayland_connection() -> Result<wayland_client::Connection> {
+ if std::env::var_os("WAYLAND_SOCKET").is_some() {
+ bail!("Hyprland observation requires a named WAYLAND_DISPLAY socket");
+ }
+ let display =
+ PathBuf::from(std::env::var_os("WAYLAND_DISPLAY").context("missing WAYLAND_DISPLAY")?);
+ let path = if display.is_absolute() {
+ display
+ } else {
+ if display.components().count() != 1 {
+ bail!("invalid WAYLAND_DISPLAY socket name");
+ }
+ let runtime =
+ PathBuf::from(std::env::var_os("XDG_RUNTIME_DIR").context("missing XDG_RUNTIME_DIR")?);
+ if !runtime.is_absolute() {
+ bail!("XDG_RUNTIME_DIR must be absolute");
+ }
+ runtime.join(display)
+ };
+ let socket = socket2::Socket::new(socket2::Domain::UNIX, socket2::Type::STREAM, None)?;
+ socket.connect_timeout(&socket2::SockAddr::unix(path)?, QUERY_TIMEOUT)?;
+ wayland_client::Connection::from_socket(socket.into()).context("Wayland connection failed")
+}
+
+/// Bind the Wayland connection to the IPC compositor before accepting pixels.
+pub(super) fn verify_capture_peer(connection: &wayland_client::Connection) -> Result<()> {
+ let ipc = ipc_connection()?;
+ if peer_pid(ipc.as_raw_fd())? != peer_pid(connection.backend().poll_fd().as_raw_fd())? {
+ bail!("Hyprland IPC and WAYLAND_DISPLAY name different compositor processes");
+ }
+ Ok(())
+}
+
+fn query<T: serde::de::DeserializeOwned>(command: &str) -> Result<T> {
+ let mut ipc = ipc_connection()?;
+ // A stale inherited instance signature must not supply geometry for a
+ // different nested Wayland desktop. No protocol roundtrip is needed.
+ let wayland = wayland_connection()?;
+ if peer_pid(ipc.as_raw_fd())? != peer_pid(wayland.backend().poll_fd().as_raw_fd())? {
+ bail!("Hyprland IPC and WAYLAND_DISPLAY name different compositor processes");
+ }
+ let reply = read_reply(&mut ipc, command.as_bytes(), QUERY_TIMEOUT)?;
+ serde_json::from_slice(&reply).context("invalid Hyprland IPC JSON")
+}
+
+fn read_reply(stream: &mut UnixStream, command: &[u8], timeout: Duration) -> Result<Vec<u8>> {
+ let deadline = Instant::now() + timeout;
+ stream.set_write_timeout(Some(timeout))?;
+ stream.write_all(command)?;
+ let mut reply = Vec::new();
+ let mut chunk = [0u8; 8192];
+ loop {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ bail!("Hyprland IPC query timed out");
+ }
+ stream.set_read_timeout(Some(remaining))?;
+ let count = stream
+ .read(&mut chunk)
+ .context("Hyprland IPC reply unavailable")?;
+ if count == 0 {
+ break;
+ }
+ if reply.len() + count > MAX_REPLY_BYTES {
+ bail!("Hyprland IPC reply exceeds size limit");
+ }
+ reply.extend_from_slice(&chunk[..count]);
+ }
+ Ok(reply)
+}
+
+fn windows_from_clients(clients: Vec<Client>, active: &HashSet<i64>) -> Result<Vec<Window>> {
+ let mut seen = HashSet::new();
+ let mut windows = Vec::new();
+ for c in clients.into_iter().filter(|c| c.mapped) {
+ let address = u64::from_str_radix(c.address.strip_prefix("0x").unwrap_or(&c.address), 16)?;
+ let pid = u32::try_from(c.pid)?;
+ let width = u32::try_from(c.size[0])?;
+ let height = u32::try_from(c.size[1])?;
+ if address == 0 || pid == 0 || !valid_dimensions(width, height) || !seen.insert(address) {
+ bail!("invalid or duplicate Hyprland window identity/geometry");
+ }
+ windows.push(Window {
+ address,
+ pid,
+ title: c.title,
+ app_id: c.class,
+ x: c.at[0],
+ y: c.at[1],
+ width,
+ height,
+ workspace: c.workspace.id,
+ visible: !c.hidden && active.contains(&c.workspace.id),
+ hidden: c.hidden,
+ });
+ }
+ Ok(windows)
+}
+
+fn valid_dimensions(width: u32, height: u32) -> bool {
+ width > 0 && height > 0 && u64::from(width) * u64::from(height) <= MAX_LOGICAL_PIXELS
+}
+
+pub fn list_windows() -> Result<Vec<Window>> {
+ let monitors: Vec<Monitor> = query("j/monitors")?;
+ let active = monitors
+ .into_iter()
+ .flat_map(|m| [m.active_workspace.id, m.special_workspace.id])
+ .filter(|id| *id != 0)
+ .collect();
+ windows_from_clients(query("j/clients")?, &active)
+}
+
+pub fn window_for_address(address: u64) -> Option<Window> {
+ list_windows()
+ .ok()?
+ .into_iter()
+ .find(|w| w.address == address)
+}
+
+/// AT-SPI has no native Hyprland handle. Correlate only when the title is
+/// unique among this PID's mapped compositor clients, as well as AX roots.
+pub fn accessibility_window(address: u64, pid: u32) -> Option<Window> {
+ accessibility_target(&list_windows().ok()?, address, pid)
+}
+
+fn accessibility_target(windows: &[Window], address: u64, pid: u32) -> Option<Window> {
+ let target = windows
+ .iter()
+ .find(|w| w.address == address && w.pid == pid)?;
+ (!target.title.is_empty()
+ && windows
+ .iter()
+ .filter(|w| w.pid == pid && w.title == target.title)
+ .count()
+ == 1)
+ .then(|| target.clone())
+}
+
+/// The legacy PID-only bounds caller has no window identity: allow only a
+/// single mapped client. Explicit IDs never fall back to this function.
+pub fn window_for_pid(pid: u32) -> Option<Window> {
+ let mut owned = list_windows().ok()?.into_iter().filter(|w| w.pid == pid);
+ let first = owned.next()?;
+ owned.next().is_none().then_some(first)
+}
+
+pub fn target_is_active(address: u64, pid: Option<u32>) -> Result<bool> {
+ let target = window_for_address(address).context("Hyprland target no longer exists")?;
+ if pid.is_some_and(|pid| pid != target.pid) {
+ bail!("Hyprland target belongs to a different process");
+ }
+ let active: serde_json::Value = query("j/activewindow")?;
+ Ok(
+ active.get("address").and_then(|v| v.as_str()) == Some(format!("0x{address:x}").as_str())
+ && active.get("pid").and_then(|v| v.as_u64()) == Some(u64::from(target.pid)),
+ )
+}
+
+fn capture_target(windows: &[Window], address: u64, pid: Option<u32>) -> Result<Window> {
+ let target = windows
+ .iter()
+ .find(|w| w.address == address)
+ .context("requested Hyprland window no longer exists; refresh list_windows")?;
+ if pid.is_some_and(|pid| target.pid != pid) || target.hidden {
+ bail!("requested Hyprland target ownership/visibility is unproven");
+ }
+ // The v1 wire request takes only the low word. Refuse collisions across
+ // ALL mapped clients, including other processes and hidden windows.
+ if windows
+ .iter()
+ .filter(|w| w.address as u32 == address as u32)
+ .count()
+ != 1
+ {
+ bail!("Hyprland toplevel export handle is ambiguous");
+ }
+ Ok(target.clone())
+}
+
+pub fn capture(address: u64, pid: Option<u32>) -> Result<Vec<u8>> {
+ let before = capture_target(&list_windows()?, address, pid)?;
+ let bytes = super::hyprland_capture::capture_toplevel_png(address)?;
+ let after = capture_target(&list_windows()?, address, pid)?;
+ if before != after {
+ bail!("Hyprland target changed during capture; refresh the snapshot");
+ }
+ // Keep the established window-local logical coordinate contract. Physical
+ // toplevel buffers can use a fractional render scale; do not make callers
+ // infer it from a monitor mode or apply an output-origin offset.
+ let image = image::load_from_memory(&bytes)?;
+ if image.width() == before.width && image.height() == before.height {
+ return Ok(bytes);
+ }
+ let image = image.resize_exact(
+ before.width,
+ before.height,
+ image::imageops::FilterType::Triangle,
+ );
+ let mut out = std::io::Cursor::new(Vec::new());
+ image.write_to(&mut out, image::ImageFormat::Png)?;
+ Ok(out.into_inner())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn window(address: u64, pid: u32) -> Window {
+ Window {
+ address,
+ pid,
+ title: "Fixture".into(),
+ app_id: "fixture".into(),
+ x: 967,
+ y: 38,
+ width: 800,
+ height: 600,
+ workspace: 1,
+ visible: true,
+ hidden: false,
+ }
+ }
+
+ #[test]
+ fn exact_identity_never_falls_back_to_sibling_or_other_pid() {
+ let windows = [window(0x10, 42), window(0x20, 42)];
+ assert_eq!(
+ capture_target(&windows, 0x10, Some(42)).unwrap().address,
+ 0x10
+ );
+ assert!(capture_target(&windows, 0x30, Some(42)).is_err());
+ assert!(capture_target(&windows, 0x10, Some(43)).is_err());
+ }
+
+ #[test]
+ fn accessibility_correlation_rejects_duplicate_compositor_titles() {
+ let a = window(0x10, 42);
+ let b = window(0x20, 42);
+ assert!(accessibility_target(&[a.clone()], a.address, a.pid).is_some());
+ assert!(accessibility_target(&[a.clone(), b], a.address, a.pid).is_none());
+ }
+
+ #[test]
+ fn truncated_handle_collision_refuses_even_across_pids() {
+ assert!(capture_target(
+ &[window(0x100000010, 42), window(0x200000010, 43)],
+ 0x100000010,
+ Some(42)
+ )
+ .is_err());
+ }
+
+ #[test]
+ fn off_workspace_target_is_capturable_but_hidden_target_refuses() {
+ let mut target = window(0x10, 42);
+ target.visible = false;
+ assert!(capture_target(&[target.clone()], 0x10, Some(42)).is_ok());
+ target.hidden = true;
+ assert!(capture_target(&[target], 0x10, Some(42)).is_err());
+ }
+
+ #[test]
+ fn stalled_ipc_reply_is_bounded() {
+ let (mut client, _server) = UnixStream::pair().unwrap();
+ let start = Instant::now();
+ assert!(read_reply(&mut client, b"j/clients", Duration::from_millis(30)).is_err());
+ assert!(start.elapsed() < Duration::from_secs(1));
+ }
+
+ #[test]
+ fn logical_resize_is_bounded_before_allocation() {
+ assert!(valid_dimensions(3840, 2160));
+ assert!(!valid_dimensions(0, 1));
+ assert!(!valid_dimensions(u32::MAX, u32::MAX));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_capture.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_capture.rs
new file mode 100644
index 0000000000..a1815d828b
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_capture.rs
@@ -0,0 +1,536 @@
+//! Wayland-native capture for Hyprland.
+//!
+//! Identified per-window capture using wayland-client (no grim subprocess).
+//!
+//! - **Per-window**: `hyprland-toplevel-export-v1` (vendored XML, bindings
+//! generated by wayland-scanner). Copies the toplevel's own buffer, so a
+//! background window captures *its* content even when occluded or on
+//! another workspace — unlike the grim screen-region crop it replaces.
+//! The protocol handle is the `hyprctl clients` window address truncated
+//! to its low 32 bits (Hyprland's `getWindowFromHandle` compares
+//! `ptr & 0xFFFFFFFF`).
+//!
+//! Frame dispatch is deadline-bounded: `copy` with `ignore_damage=0` waits
+//! for window damage and would hang forever on an idle window. Captures use
+//! one short-lived connection per call.
+//!
+//! Caveat (documented in the skill): when Hyprland's
+//! `ecosystem:enforce_permissions` is enabled and screencopy is denied,
+//! the compositor reports a *successful* capture containing a black
+//! "permission denied" frame — there is no failed event to detect.
+
+use std::fs::File;
+use std::os::fd::{AsFd, AsRawFd};
+use std::os::unix::fs::FileExt;
+use std::time::{Duration, Instant};
+
+use anyhow::{bail, Context, Result};
+use wayland_client::protocol::{
+ wl_buffer::WlBuffer,
+ wl_callback::{self, WlCallback},
+ wl_registry,
+ wl_shm::{self, WlShm},
+ wl_shm_pool::WlShmPool,
+};
+use wayland_client::{delegate_noop, Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum};
+// ---------------------------------------------------------------------------
+// Generated bindings for hyprland-toplevel-export-v1 (vendored XML).
+//
+// The v2 request `capture_toplevel_with_wlr_toplevel_handle` references
+// zwlr_foreign_toplevel_handle_v1, so the wlr foreign_toplevel interfaces
+// must be in scope for both the __interfaces module and the outer module.
+// ---------------------------------------------------------------------------
+pub mod hyprland_toplevel_export {
+ #![allow(non_upper_case_globals, non_camel_case_types, missing_docs)]
+ use wayland_client;
+ use wayland_client::protocol::*;
+ use wayland_protocols_wlr::foreign_toplevel::v1::client::*;
+
+ pub mod __interfaces {
+ use wayland_client::protocol::__interfaces::*;
+ use wayland_protocols_wlr::foreign_toplevel::v1::client::__interfaces::*;
+ wayland_scanner::generate_interfaces!("./protocols/hyprland-toplevel-export-v1.xml");
+ }
+ use self::__interfaces::*;
+
+ wayland_scanner::generate_client_code!("./protocols/hyprland-toplevel-export-v1.xml");
+}
+
+use hyprland_toplevel_export::{
+ hyprland_toplevel_export_frame_v1::{self, HyprlandToplevelExportFrameV1},
+ hyprland_toplevel_export_manager_v1::HyprlandToplevelExportManagerV1,
+};
+
+/// Default deadline for buffer-param negotiation and frame copy. Generous
+/// enough for a busy compositor, short enough that a recording hook never
+/// stalls a tool call noticeably.
+const CAPTURE_DEADLINE: Duration = Duration::from_secs(4);
+const MAX_FRAME_BYTES: u64 = 256 * 1024 * 1024;
+
+// ---------------------------------------------------------------------------
+// Capture state machine shared by both frame protocols.
+// ---------------------------------------------------------------------------
+#[derive(Debug, Default)]
+struct CaptureState {
+ shm: Option<WlShm>,
+ manager: Option<HyprlandToplevelExportManagerV1>,
+ registry_done: bool,
+ /// (format, width, height, stride) from the frame's `buffer` event.
+ shm_params: Option<(wl_shm::Format, u32, u32, u32)>,
+ buffer_done: bool,
+ y_invert: bool,
+ ready: bool,
+ failed: bool,
+}
+
+/// A captured frame with tightly packed rows (`width * 4` bytes per row),
+/// y-flip already applied. `format` is the wire format: pixel byte order in
+/// memory is B,G,R,[A|X] for `?rgb8888` and R,G,B,[A|X] for `?bgr8888`.
+pub struct RawFrame {
+ pub width: u32,
+ pub height: u32,
+ pub format: wl_shm::Format,
+ pub data: Vec<u8>,
+}
+
+impl Dispatch<wl_registry::WlRegistry, ()> for CaptureState {
+ fn event(
+ state: &mut Self,
+ registry: &wl_registry::WlRegistry,
+ event: wl_registry::Event,
+ _data: &(),
+ _conn: &Connection,
+ qh: &QueueHandle<Self>,
+ ) {
+ if let wl_registry::Event::Global {
+ name,
+ interface,
+ version,
+ } = event
+ {
+ if interface == WlShm::interface().name {
+ state.shm = Some(registry.bind(name, version.min(1), qh, ()));
+ } else if interface == HyprlandToplevelExportManagerV1::interface().name {
+ state.manager = Some(registry.bind(name, version.min(2), qh, ()));
+ }
+ }
+ }
+}
+
+impl Dispatch<WlCallback, ()> for CaptureState {
+ fn event(
+ state: &mut Self,
+ _: &WlCallback,
+ event: wl_callback::Event,
+ _: &(),
+ _: &Connection,
+ _: &QueueHandle<Self>,
+ ) {
+ if let wl_callback::Event::Done { .. } = event {
+ state.registry_done = true;
+ }
+ }
+}
+
+impl Dispatch<HyprlandToplevelExportFrameV1, ()> for CaptureState {
+ fn event(
+ state: &mut Self,
+ _proxy: &HyprlandToplevelExportFrameV1,
+ event: hyprland_toplevel_export_frame_v1::Event,
+ _data: &(),
+ _conn: &Connection,
+ _qh: &QueueHandle<Self>,
+ ) {
+ use hyprland_toplevel_export_frame_v1::Event;
+ match event {
+ Event::Buffer {
+ format: WEnum::Value(format),
+ width,
+ height,
+ stride,
+ } => {
+ state.shm_params = Some((format, width, height, stride));
+ }
+ Event::BufferDone => state.buffer_done = true,
+ Event::Flags {
+ flags: WEnum::Value(flags),
+ } => {
+ state.y_invert = flags.contains(hyprland_toplevel_export_frame_v1::Flags::YInvert);
+ }
+ Event::Ready { .. } => state.ready = true,
+ Event::Failed => state.failed = true,
+ // damage / linux_dmabuf / unknown-enum values are irrelevant
+ // for shm capture.
+ _ => {}
+ }
+ }
+}
+
+delegate_noop!(CaptureState: ignore WlShm); // advertises `format` events
+delegate_noop!(CaptureState: WlShmPool); // no events
+delegate_noop!(CaptureState: ignore WlBuffer); // `release` event
+delegate_noop!(CaptureState: HyprlandToplevelExportManagerV1); // no events
+
+// ---------------------------------------------------------------------------
+// Deadline-bounded dispatch
+// ---------------------------------------------------------------------------
+
+/// Dispatch events until `done(state)` or the deadline expires. Equivalent to
+/// `blocking_dispatch` but with a hard timeout, so a compositor that never
+/// answers (or a damage-gated copy) cannot wedge the recording hook path.
+fn dispatch_until(
+ queue: &mut EventQueue<CaptureState>,
+ state: &mut CaptureState,
+ deadline: Instant,
+ what: &str,
+ done: impl Fn(&CaptureState) -> bool,
+) -> Result<()> {
+ loop {
+ queue
+ .dispatch_pending(state)
+ .context("wayland dispatch failed")?;
+ if done(state) {
+ return Ok(());
+ }
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ bail!("wayland capture timed out waiting for {what}");
+ }
+ queue.flush().context("wayland flush failed")?;
+ let Some(guard) = queue.prepare_read() else {
+ continue; // events already queued — dispatch them
+ };
+ let fd = guard.connection_fd().as_raw_fd();
+ let mut pfd = libc::pollfd {
+ fd,
+ events: libc::POLLIN,
+ revents: 0,
+ };
+ let timeout_ms = remaining.as_millis().min(i32::MAX as u128) as i32;
+ let n = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
+ if n < 0 {
+ let err = std::io::Error::last_os_error();
+ if err.kind() == std::io::ErrorKind::Interrupted {
+ continue;
+ }
+ return Err(err).context("poll on wayland fd failed");
+ }
+ if n == 0 {
+ bail!("wayland capture timed out waiting for {what}");
+ }
+ match guard.read() {
+ Ok(_) => {}
+ // Another reader (none in practice — one connection per capture)
+ // or a spurious wakeup; loop and retry.
+ Err(wayland_client::backend::WaylandError::Io(e))
+ if e.kind() == std::io::ErrorKind::WouldBlock => {}
+ Err(e) => return Err(e).context("wayland read failed"),
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// wl_shm helpers
+// ---------------------------------------------------------------------------
+
+/// Anonymous shared-memory file of `len` bytes (memfd, CLOEXEC).
+fn create_shm_file(len: u64) -> Result<File> {
+ use std::os::fd::FromRawFd;
+ let name = std::ffi::CString::new("cua-driver-capture").unwrap();
+ let fd = unsafe { libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC) };
+ if fd < 0 {
+ return Err(std::io::Error::last_os_error()).context("memfd_create failed");
+ }
+ let file = unsafe { File::from_raw_fd(fd) };
+ file.set_len(len).context("ftruncate on memfd failed")?;
+ Ok(file)
+}
+
+struct ShmBuffer {
+ file: File,
+ pool: WlShmPool,
+ buffer: WlBuffer,
+}
+
+impl ShmBuffer {
+ fn create(
+ shm: &WlShm,
+ qh: &QueueHandle<CaptureState>,
+ params: (wl_shm::Format, u32, u32, u32),
+ ) -> Result<Self> {
+ let (format, width, height, stride) = params;
+ let len = validated_buffer_len(format, width, height, stride)?;
+ let file = create_shm_file(len)?;
+ let pool = shm.create_pool(file.as_fd(), len as i32, qh, ());
+ let buffer = pool.create_buffer(
+ 0,
+ width as i32,
+ height as i32,
+ stride as i32,
+ format,
+ qh,
+ (),
+ );
+ Ok(ShmBuffer { file, pool, buffer })
+ }
+
+ fn destroy(self) {
+ self.buffer.destroy();
+ self.pool.destroy();
+ }
+}
+
+/// Copy shm rows into a tightly packed buffer, dropping stride padding and
+/// un-flipping when the compositor reported y_invert.
+fn validated_buffer_len(
+ format: wl_shm::Format,
+ width: u32,
+ height: u32,
+ stride: u32,
+) -> Result<u64> {
+ if !matches!(
+ format,
+ wl_shm::Format::Argb8888
+ | wl_shm::Format::Xrgb8888
+ | wl_shm::Format::Abgr8888
+ | wl_shm::Format::Xbgr8888
+ ) {
+ bail!("unsupported wl_shm capture format {format:?}");
+ }
+ let row_bytes = width.checked_mul(4).context("capture row overflow")?;
+ let len = u64::from(stride) * u64::from(height);
+ if width == 0
+ || height == 0
+ || stride < row_bytes
+ || stride > i32::MAX as u32
+ || width > i32::MAX as u32
+ || height > i32::MAX as u32
+ || len > MAX_FRAME_BYTES
+ {
+ bail!("invalid or oversized toplevel buffer parameters");
+ }
+ Ok(len)
+}
+
+fn pack_rows(raw: &[u8], width: u32, height: u32, stride: u32, y_invert: bool) -> Result<Vec<u8>> {
+ let len = validated_buffer_len(wl_shm::Format::Argb8888, width, height, stride)?;
+ if raw.len() as u64 != len {
+ bail!("toplevel buffer length mismatch");
+ }
+ let row_bytes = width as usize * 4;
+ let mut out = Vec::with_capacity(row_bytes * height as usize);
+ for y in 0..height as usize {
+ let src_y = if y_invert { height as usize - 1 - y } else { y };
+ let start = src_y * stride as usize;
+ out.extend_from_slice(&raw[start..start + row_bytes]);
+ }
+ Ok(out)
+}
+
+/// Convert a packed frame to RGBA8 in place semantics (returns a new Vec).
+/// Returns an error for wl_shm formats outside the four common 32-bit ones.
+pub fn frame_to_rgba8(frame: &RawFrame) -> Result<Vec<u8>> {
+ let expected = u64::from(frame.width) * u64::from(frame.height) * 4;
+ if expected > MAX_FRAME_BYTES || frame.data.len() as u64 != expected {
+ bail!("packed frame length mismatch");
+ }
+ let mut rgba = frame.data.clone();
+ match frame.format {
+ // Memory order B,G,R,[A|X] — swap to R,G,B,A.
+ wl_shm::Format::Argb8888 | wl_shm::Format::Xrgb8888 => {
+ let opaque = frame.format == wl_shm::Format::Xrgb8888;
+ for px in rgba.chunks_exact_mut(4) {
+ px.swap(0, 2);
+ if opaque {
+ px[3] = 0xFF;
+ }
+ }
+ }
+ // Memory order already R,G,B,[A|X].
+ wl_shm::Format::Abgr8888 | wl_shm::Format::Xbgr8888 => {
+ if frame.format == wl_shm::Format::Xbgr8888 {
+ for px in rgba.chunks_exact_mut(4) {
+ px[3] = 0xFF;
+ }
+ }
+ }
+ other => bail!("unsupported wl_shm capture format {other:?}"),
+ }
+ Ok(rgba)
+}
+
+/// The hyprland-toplevel-export protocol handle for a `hyprctl clients`
+/// window address: the low 32 bits of the (64-bit) address.
+pub fn toplevel_handle(address: u64) -> u32 {
+ (address & 0xFFFF_FFFF) as u32
+}
+
+// ---------------------------------------------------------------------------
+// One-shot per-window capture (hyprland-toplevel-export-v1)
+// ---------------------------------------------------------------------------
+
+/// Capture one frame of a Hyprland toplevel by its `hyprctl clients` address.
+/// Works for occluded windows and windows on other workspaces — the
+/// compositor renders the toplevel's own surface tree into the buffer.
+///
+/// Fully synchronous; call from a blocking context. Buffer dimensions are
+/// physical pixels at the window's render scale (a 1.5x-scaled 800x600
+/// window yields a 1200x900 frame).
+pub fn capture_toplevel_frame(address: u64, overlay_cursor: bool) -> Result<RawFrame> {
+ let conn = super::hyprland::wayland_connection()?;
+ super::hyprland::verify_capture_peer(&conn)?;
+ let mut queue = conn.new_event_queue::<CaptureState>();
+ let qh = queue.handle();
+ let mut state = CaptureState::default();
+ let deadline = Instant::now() + CAPTURE_DEADLINE;
+ let _registry = conn.display().get_registry(&qh, ());
+ conn.display().sync(&qh, ());
+ dispatch_until(
+ &mut queue,
+ &mut state,
+ deadline,
+ "registry enumeration",
+ |s| s.registry_done,
+ )?;
+ let shm = state.shm.clone().context("compositor lacks wl_shm")?;
+ let manager = state
+ .manager
+ .clone()
+ .context("compositor lacks Hyprland toplevel export")?;
+ let handle = toplevel_handle(address);
+ let frame = manager.capture_toplevel(overlay_cursor as i32, handle, &qh, ());
+
+ // Phase 1: buffer params (buffer → buffer_done).
+ dispatch_until(
+ &mut queue,
+ &mut state,
+ deadline,
+ "toplevel buffer params",
+ |s| s.buffer_done || s.failed,
+ )?;
+ if state.failed {
+ frame.destroy();
+ bail!("toplevel export failed for window 0x{address:x} (handle 0x{handle:08x})");
+ }
+ let Some(params) = state.shm_params else {
+ frame.destroy();
+ bail!("compositor offered no wl_shm buffer params");
+ };
+
+ // Phase 2: copy. ignore_damage=1 — with 0 the copy waits for window
+ // damage and hangs forever on an idle window.
+ let shm_buf = match ShmBuffer::create(&shm, &qh, params) {
+ Ok(b) => b,
+ Err(e) => {
+ frame.destroy();
+ return Err(e);
+ }
+ };
+ frame.copy(&shm_buf.buffer, 1);
+ let copy_result = dispatch_until(
+ &mut queue,
+ &mut state,
+ deadline,
+ "toplevel frame copy",
+ |s| s.ready || s.failed,
+ );
+
+ frame.destroy();
+ let (format, width, height, stride) = params;
+ let result = (|| {
+ copy_result?;
+ if state.failed {
+ bail!("toplevel export copy failed for window 0x{address:x}");
+ }
+ let mut raw = vec![0u8; stride as usize * height as usize];
+ shm_buf
+ .file
+ .read_exact_at(&mut raw, 0)
+ .context("read from shm file failed")?;
+ Ok(RawFrame {
+ width,
+ height,
+ format,
+ data: pack_rows(&raw, width, height, stride, state.y_invert)?,
+ })
+ })();
+ shm_buf.destroy();
+ result
+}
+
+/// Per-window PNG capture for the screenshot path. Converts to RGBA and
+/// encodes with the shared core encoder.
+pub fn capture_toplevel_png(address: u64) -> Result<Vec<u8>> {
+ let frame = capture_toplevel_frame(address, false)?;
+ let rgba = frame_to_rgba8(&frame)?;
+ cua_driver_core::image_utils::encode_rgba_to_png(&rgba, frame.width, frame.height)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn toplevel_handle_truncates_to_low_32_bits() {
+ // The protocol doc's own example: address d161e7b0 -> 3512854448.
+ assert_eq!(toplevel_handle(0xd161e7b0), 3512854448);
+ // Full 64-bit heap pointer keeps only the low word.
+ assert_eq!(toplevel_handle(0x56226558b1d0), 0x6558b1d0);
+ assert_eq!(toplevel_handle(0xFFFF_FFFF_0000_0001), 1);
+ }
+
+ #[test]
+ fn pack_rows_drops_stride_padding() {
+ // 2x2 frame, stride 12 (4 bytes padding per row).
+ let raw: Vec<u8> = vec![
+ 1, 1, 1, 1, 2, 2, 2, 2, 99, 99, 99, 99, // row 0 + pad
+ 3, 3, 3, 3, 4, 4, 4, 4, 99, 99, 99, 99, // row 1 + pad
+ ];
+ let packed = pack_rows(&raw, 2, 2, 12, false).unwrap();
+ assert_eq!(packed, vec![1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]);
+ }
+
+ #[test]
+ fn pack_rows_unflips_y_invert() {
+ let raw: Vec<u8> = vec![
+ 1, 1, 1, 1, // row 0
+ 2, 2, 2, 2, // row 1
+ ];
+ let packed = pack_rows(&raw, 1, 2, 4, true).unwrap();
+ assert_eq!(packed, vec![2, 2, 2, 2, 1, 1, 1, 1]);
+ }
+
+ #[test]
+ fn frame_to_rgba8_swaps_bgr_and_forces_alpha() {
+ let frame = RawFrame {
+ width: 1,
+ height: 1,
+ format: wl_shm::Format::Xrgb8888,
+ data: vec![0x10, 0x20, 0x30, 0x00], // B,G,R,X
+ };
+ assert_eq!(
+ frame_to_rgba8(&frame).unwrap(),
+ vec![0x30, 0x20, 0x10, 0xFF]
+ );
+
+ let frame = RawFrame {
+ width: 1,
+ height: 1,
+ format: wl_shm::Format::Abgr8888,
+ data: vec![0x10, 0x20, 0x30, 0x77], // already R,G,B,A
+ };
+ assert_eq!(
+ frame_to_rgba8(&frame).unwrap(),
+ vec![0x10, 0x20, 0x30, 0x77]
+ );
+ }
+
+ #[test]
+ fn invalid_buffer_sizes_and_formats_refuse_before_allocation() {
+ assert!(validated_buffer_len(wl_shm::Format::Argb8888, 800, 600, 16).is_err());
+ assert!(validated_buffer_len(wl_shm::Format::Argb8888, u32::MAX, 1, u32::MAX).is_err());
+ assert!(validated_buffer_len(wl_shm::Format::Argb8888, 8192, 8193, 32768).is_err());
+ assert!(validated_buffer_len(wl_shm::Format::Rgb565, 800, 600, 1600).is_err());
+ assert!(pack_rows(&[0; 4], 2, 1, 8, false).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 5c1cb614a8..f1079159d4 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
@@ -11,6 +11,8 @@
pub mod ext_screencopy;
pub mod ext_toplevel;
+pub mod hyprland;
+pub mod hyprland_capture;
pub mod kwin_helper;
pub mod overlay;
pub mod persistent_vptr;
@@ -1065,6 +1067,23 @@ fn screenshot_window_bytes_with_dispatch(
/// surface is currently rendered; otherwise it fails closed. Output-level
/// capture remains available through [`screenshot_display_dispatch`].
pub fn screenshot_dispatch(xid: u64) -> anyhow::Result<Vec<u8>> {
+ screenshot_dispatch_for_pid(xid, None)
+}
+
+pub fn screenshot_dispatch_with_pid(xid: u64, pid: u32) -> anyhow::Result<Vec<u8>> {
+ screenshot_dispatch_for_pid(xid, Some(pid))
+}
+
+fn screenshot_dispatch_for_pid(xid: u64, pid: Option<u32>) -> anyhow::Result<Vec<u8>> {
+ if is_wayland() && hyprland::is_session() {
+ return hyprland::capture(xid, pid).map_err(|error| {
+ tracing::debug!("Hyprland target capture refused: {error:#}");
+ surface_identity_unproven(
+ xid,
+ "Hyprland target identity or toplevel export could not be verified",
+ )
+ });
+ }
screenshot_window_bytes_with_dispatch(
is_wayland(),
xid,
@@ -1172,13 +1191,7 @@ fn checked_shell_helper_capture(
/// point for callers outside `get_window_state`; it shares the same fail-closed
/// Wayland contract as [`screenshot_dispatch`].
pub fn screenshot_window_dispatch(xid: u64) -> anyhow::Result<Vec<u8>> {
- screenshot_window_bytes_with_dispatch(
- is_wayland(),
- xid,
- wayland_window_crop,
- screenshot_display_dispatch,
- crate::capture::screenshot_window_bytes,
- )
+ screenshot_dispatch(xid)
}
// ── Input session helper ─────────────────────────────────────────────────────
@@ -1337,6 +1350,15 @@ pub fn activate_window_for_input_target(
window_id: u64,
target_pid: Option<u32>,
) -> anyhow::Result<()> {
+ if is_wayland() && hyprland::is_session() {
+ // A full compositor address must never enter the generic protocol-id
+ // or title-matching route. This observation-only adapter can attest an
+ // already-active target, but cannot switch focus to a different one.
+ if hyprland::target_is_active(window_id, target_pid)? {
+ return Ok(());
+ }
+ anyhow::bail!("foreground_unavailable: exact-address Hyprland activation is not implemented; refusing title-based activation");
+ }
if is_inject_mode() {
let pid = target_pid.ok_or_else(|| {
anyhow::anyhow!(
@@ -1603,6 +1625,11 @@ pub fn window_local_to_output(window_id: u64, x: i32, y: i32) -> (i32, i32) {
/// object ID came from an earlier Wayland connection. Protocol object IDs are
/// connection-local, so direct equality is only a fast path.
pub fn window_geometry(window_id: u64) -> Option<(i32, i32, u32, u32)> {
+ if is_wayland() && hyprland::is_session() {
+ // Do not fall back to title, app-id, X11, or another compositor when
+ // an explicit native Hyprland address is missing.
+ return hyprland::window_for_address(window_id).map(|w| (w.x, w.y, w.width, w.height));
+ }
if let Some(window) = sway_ipc::window_for_id(window_id) {
return Some((window.x, window.y, window.width, window.height));
}
@@ -3141,6 +3168,34 @@ fn apply_pid_filter(mut windows: Vec<WindowInfo>, filter_pid: Option<u32>) -> Ve
/// Window-enumeration dispatcher: native Wayland when available, else X11.
pub fn list_windows_dispatch(filter_pid: Option<u32>) -> Vec<WindowInfo> {
if wayland_enabled() && std::env::var_os("WAYLAND_DISPLAY").is_some() {
+ if hyprland::is_session() {
+ // Hyprland IPC already attests PID and full native identity. A
+ // foreign-toplevel title join only makes that identity weaker.
+ return match hyprland::list_windows() {
+ Ok(windows) => listed_windows(apply_pid_filter(
+ windows
+ .into_iter()
+ .map(|w| WindowInfo {
+ xid: w.address,
+ pid: Some(w.pid),
+ app_name: w.app_id,
+ title: w.title,
+ is_on_screen: w.visible,
+ z_index: None,
+ x: w.x,
+ y: w.y,
+ width: w.width,
+ height: w.height,
+ })
+ .collect(),
+ filter_pid,
+ )),
+ Err(error) => {
+ tracing::warn!("Hyprland window enumeration unavailable: {error:#}");
+ Vec::new()
+ }
+ };
+ }
if let Some(ws) = kwin_helper::list_window_infos() {
return listed_windows(apply_pid_filter(ws, filter_pid));
}