From dd9f24ea1ccd5f7cf8535a717a989e09d743ce75 Mon Sep 17 00:00:00 2001 From: Kyzer Date: Wed, 21 Oct 2026 10:37:52 +0000 Subject: [PATCH 1/3] perf(scap-targets): batch x11 window queries Keep one X11 connection per listing. Intern the atoms and query RandR once, then pipeline the per-window requests into a snapshot so the picker and the cursor probe stop opening a connection per field. --- apps/desktop-gpui/src/devices.rs | 49 +- crates/scap-targets/Cargo.toml | 4 + .../src/bin/x11_window_list_bench.rs | 369 ++++++++ crates/scap-targets/src/platform/linux.rs | 859 ++++++++++++++++-- 4 files changed, 1221 insertions(+), 60 deletions(-) create mode 100644 crates/scap-targets/src/bin/x11_window_list_bench.rs diff --git a/apps/desktop-gpui/src/devices.rs b/apps/desktop-gpui/src/devices.rs index 6f6995139f6..122afc1979d 100644 --- a/apps/desktop-gpui/src/devices.rs +++ b/apps/desktop-gpui/src/devices.rs @@ -676,7 +676,15 @@ pub fn topmost_foreign_window_at_cursor() -> Option { candidates.into_iter().next().map(|(window, _)| window) } -#[cfg(not(target_os = "macos"))] +#[cfg(target_os = "linux")] +pub fn topmost_foreign_window_at_cursor() -> Option { + match scap_targets::WindowImpl::topmost_x11_snapshot_at_cursor() { + Some(found) => found.map(|snapshot| snapshot.window), + None => Window::get_topmost_at_cursor(), + } +} + +#[cfg(not(any(target_os = "macos", target_os = "linux")))] pub fn topmost_foreign_window_at_cursor() -> Option { Window::get_topmost_at_cursor() } @@ -734,6 +742,11 @@ pub fn list_windows() -> Vec { /// `collect_windows_with_thumbnails` (`thumbnails/mod.rs:107-137`), which needs /// the handle for both the ScreenCaptureKit filter and `Window::app_icon()`. pub fn list_window_targets() -> Vec<(WindowOption, Window)> { + #[cfg(target_os = "linux")] + if let Some(targets) = linux_window_targets_from_snapshot() { + return targets; + } + Window::list() .into_iter() .filter_map(|window| { @@ -786,6 +799,40 @@ pub fn list_window_targets() -> Vec<(WindowOption, Window)> { .collect() } +#[cfg(target_os = "linux")] +fn linux_window_targets_from_snapshot() -> Option> { + let snapshots = scap_targets::WindowImpl::list_x11_snapshots()?; + Some( + snapshots + .into_iter() + .filter_map(|snapshot| { + let size = snapshot.logical_size(); + let position = snapshot.display_relative_origin(); + let refresh_rate = snapshot.refresh_rate(); + let id = snapshot.window.id(); + if snapshot.name.trim().is_empty() { + return None; + } + let app = snapshot.owner_name?; + if app == "Window Server" { + return None; + } + Some(( + WindowOption { + id, + label: snapshot.name, + app, + size: Some((size.width() as u32, size.height() as u32)), + position, + refresh_rate: Some(refresh_rate), + }, + snapshot.window, + )) + }) + .collect(), + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/scap-targets/Cargo.toml b/crates/scap-targets/Cargo.toml index 767c0bb5ae1..27a986bfdb9 100644 --- a/crates/scap-targets/Cargo.toml +++ b/crates/scap-targets/Cargo.toml @@ -37,6 +37,10 @@ windows = { workspace = true, features = [ "Win32_Storage_FileSystem", ] } +[[bin]] +name = "x11-window-list-bench" +path = "src/bin/x11_window_list_bench.rs" + [target.'cfg(target_os = "linux")'.dependencies] x11rb = { version = "0.13.2", features = ["randr"] } rustix = { version = "1.1", features = ["event"] } diff --git a/crates/scap-targets/src/bin/x11_window_list_bench.rs b/crates/scap-targets/src/bin/x11_window_list_bench.rs new file mode 100644 index 00000000000..60c4ae02ca4 --- /dev/null +++ b/crates/scap-targets/src/bin/x11_window_list_bench.rs @@ -0,0 +1,369 @@ +use std::process::ExitCode; + +fn main() -> ExitCode { + #[cfg(target_os = "linux")] + { + match linux::run() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("{error}"); + ExitCode::from(1) + } + } + } + #[cfg(not(target_os = "linux"))] + { + eprintln!("x11-window-list-bench runs on linux"); + ExitCode::from(1) + } +} + +#[cfg(target_os = "linux")] +mod linux { + use std::time::Instant; + + use x11rb::COPY_DEPTH_FROM_PARENT; + use x11rb::connection::Connection; + use x11rb::protocol::xproto::{ + AtomEnum, ConnectionExt, CreateWindowAux, PropMode, WindowClass, + }; + + use scap_targets::{Window, WindowImpl}; + + pub fn run() -> Result<(), String> { + let windows = arg_usize("windows", 40)?; + let runs = arg_usize("runs", 11)?; + if runs == 0 { + return Err("runs must be at least 1".to_string()); + } + let created = create_windows(windows)?; + let old_rows = picker_rows_per_call(); + let new_rows = picker_rows_snapshot()?; + if old_rows != new_rows { + return Err(format!( + "picker mismatch: per-call {} rows, snapshot {} rows", + old_rows.len(), + new_rows.len() + )); + } + let old_hover = Window::get_topmost_at_cursor().map(|window| window.id().to_string()); + let new_hover = WindowImpl::topmost_x11_snapshot_at_cursor() + .ok_or_else(|| "snapshot cursor probe unavailable".to_string())? + .map(|snapshot| snapshot.window.id().to_string()); + if old_hover != new_hover { + return Err(format!( + "hover mismatch: per-call {old_hover:?}, snapshot {new_hover:?}" + )); + } + + let _ = std::hint::black_box(&old_rows); + let picker_old = measure(runs, || Ok(picker_checksum_per_call()))?; + let picker_new = measure(runs, picker_checksum_snapshot)?; + let hover_old = measure(runs, || Ok(hover_checksum_per_call()))?; + let hover_new = measure(runs, hover_checksum_snapshot)?; + drop(created); + + println!("windows={windows}"); + println!("runs={runs}"); + println!("picker_rows={}", old_rows.len()); + println!( + "hover_id={}", + old_hover.unwrap_or_else(|| "none".to_string()) + ); + print_stats("picker_per_call_ms", &picker_old); + print_stats("picker_snapshot_ms", &picker_new); + print_stats("hover_per_call_ms", &hover_old); + print_stats("hover_snapshot_ms", &hover_new); + Ok(()) + } + + fn arg_usize(name: &str, default: usize) -> Result { + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + if arg == format!("--{name}") { + let value = args + .next() + .ok_or_else(|| format!("missing value for --{name}"))?; + return value + .parse::() + .map_err(|error| format!("invalid --{name}: {error}")); + } + } + Ok(default) + } + + struct CreatedWindows { + conn: x11rb::rust_connection::RustConnection, + windows: Vec, + } + + impl Drop for CreatedWindows { + fn drop(&mut self) { + for window in &self.windows { + if let Ok(cookie) = self.conn.destroy_window(*window) { + let _ = cookie.check(); + } + } + let _ = self.conn.flush(); + } + } + + fn create_windows(count: usize) -> Result { + let (conn, screen_num) = x11rb::connect(None).map_err(|error| error.to_string())?; + let screen = conn + .setup() + .roots + .get(screen_num) + .ok_or_else(|| "missing X screen".to_string())?; + let root = screen.root; + let white = screen.white_pixel; + let mut windows = Vec::with_capacity(count); + for index in 0..count { + let window = conn.generate_id().map_err(|error| error.to_string())?; + let column = index % 10; + let row = index / 10; + let x = i16::try_from(column * 120).map_err(|error| error.to_string())?; + let y = i16::try_from(row * 90).map_err(|error| error.to_string())?; + conn.create_window( + COPY_DEPTH_FROM_PARENT, + window, + root, + x, + y, + 100, + 70, + 0, + WindowClass::INPUT_OUTPUT, + 0, + &CreateWindowAux::new().background_pixel(white), + ) + .map_err(|error| error.to_string())? + .check() + .map_err(|error| error.to_string())?; + let name = format!("bench-window-{index}"); + let class = format!("bench-{index}\0Bench\0"); + let pid = std::process::id().to_ne_bytes(); + let net_wm_name = intern(&conn, "_NET_WM_NAME")?; + let net_wm_pid = intern(&conn, "_NET_WM_PID")?; + replace_property( + &conn, + window, + net_wm_name, + AtomEnum::STRING, + 8, + name.as_bytes(), + )?; + replace_property( + &conn, + window, + AtomEnum::WM_NAME, + AtomEnum::STRING, + 8, + name.as_bytes(), + )?; + replace_property( + &conn, + window, + AtomEnum::WM_CLASS, + AtomEnum::STRING, + 8, + class.as_bytes(), + )?; + replace_property(&conn, window, net_wm_pid, AtomEnum::CARDINAL, 32, &pid)?; + conn.map_window(window) + .map_err(|error| error.to_string())? + .check() + .map_err(|error| error.to_string())?; + windows.push(window); + } + let stacking = intern(&conn, "_NET_CLIENT_LIST_STACKING")?; + let client_list = intern(&conn, "_NET_CLIENT_LIST")?; + let mut bytes = Vec::with_capacity(windows.len() * 4); + for window in &windows { + bytes.extend_from_slice(&window.to_ne_bytes()); + } + replace_property(&conn, root, stacking, AtomEnum::WINDOW, 32, &bytes)?; + replace_property(&conn, root, client_list, AtomEnum::WINDOW, 32, &bytes)?; + if windows.is_empty() { + return Err("no windows".to_string()); + } + let column = (count - 1) % 10; + let row = (count - 1) / 10; + let cursor_x = i16::try_from(column * 120 + 50).map_err(|error| error.to_string())?; + let cursor_y = i16::try_from(row * 90 + 35).map_err(|error| error.to_string())?; + conn.warp_pointer(x11rb::NONE, root, 0, 0, 0, 0, cursor_x, cursor_y) + .map_err(|error| error.to_string())? + .check() + .map_err(|error| error.to_string())?; + conn.flush().map_err(|error| error.to_string())?; + Ok(CreatedWindows { conn, windows }) + } + + fn intern(conn: &impl Connection, name: &str) -> Result { + Ok(conn + .intern_atom(false, name.as_bytes()) + .map_err(|error| error.to_string())? + .reply() + .map_err(|error| error.to_string())? + .atom) + } + + fn replace_property( + conn: &impl Connection, + window: u32, + property: impl Into, + type_: impl Into, + format: u8, + data: &[u8], + ) -> Result<(), String> { + let data_len = match format { + 8 => u32::try_from(data.len()).map_err(|error| error.to_string())?, + 32 => u32::try_from(data.len() / 4).map_err(|error| error.to_string())?, + _ => return Err(format!("unsupported property format {format}")), + }; + conn.change_property( + PropMode::REPLACE, + window, + property.into(), + type_.into(), + format, + data_len, + data, + ) + .map_err(|error| error.to_string())? + .check() + .map_err(|error| error.to_string()) + } + + #[derive(PartialEq)] + struct PickerRow { + id: String, + label: String, + app: String, + size: Option<(u32, u32)>, + position: Option<(u64, u64)>, + refresh: Option, + } + + fn bits(value: f64) -> u64 { + value.to_bits() + } + + fn picker_rows_per_call() -> Vec { + Window::list() + .into_iter() + .filter_map(|window| { + let label = window.name().filter(|name| !name.trim().is_empty())?; + let app = window.owner_name()?; + if app == "Window Server" { + return None; + } + Some(PickerRow { + id: window.id().to_string(), + label, + app, + size: window.logical_size().map(|size| { + ( + u32::try_from(size.width() as i64).unwrap_or(0), + u32::try_from(size.height() as i64).unwrap_or(0), + ) + }), + position: window + .display_relative_logical_bounds() + .map(|bounds| (bits(bounds.position().x()), bits(bounds.position().y()))), + refresh: window.display().map(|display| bits(display.refresh_rate())), + }) + }) + .collect() + } + + fn picker_rows_snapshot() -> Result, String> { + let snapshots = WindowImpl::list_x11_snapshots() + .ok_or_else(|| "snapshot listing unavailable".to_string())?; + Ok(snapshots + .into_iter() + .filter_map(|snapshot| { + let size = snapshot.logical_size(); + let position = snapshot + .display_relative_origin() + .map(|(x, y)| (bits(x), bits(y))); + let refresh = bits(snapshot.refresh_rate()); + let id = snapshot.window.id().to_string(); + if snapshot.name.trim().is_empty() { + return None; + } + let app = snapshot.owner_name?; + if app == "Window Server" { + return None; + } + Some(PickerRow { + id, + label: snapshot.name, + app, + size: Some(( + u32::try_from(size.width() as i64).unwrap_or(0), + u32::try_from(size.height() as i64).unwrap_or(0), + )), + position, + refresh: Some(refresh), + }) + }) + .collect()) + } + + fn picker_checksum_per_call() -> u64 { + picker_rows_per_call().iter().fold(0u64, fold_row) + } + + fn picker_checksum_snapshot() -> Result { + Ok(picker_rows_snapshot()?.iter().fold(0u64, fold_row)) + } + + fn fold_row(checksum: u64, row: &PickerRow) -> u64 { + checksum + .wrapping_add(hash_str(&row.id)) + .wrapping_add(hash_str(&row.label)) + .wrapping_add(hash_str(&row.app)) + } + + fn hash_str(value: &str) -> u64 { + value.bytes().fold(0u64, |acc, byte| { + acc.wrapping_mul(31).wrapping_add(u64::from(byte)) + }) + } + + fn hover_checksum_per_call() -> u64 { + Window::get_topmost_at_cursor().map_or(0, |window| hash_str(&window.id().to_string())) + } + + fn hover_checksum_snapshot() -> Result { + let found = WindowImpl::topmost_x11_snapshot_at_cursor() + .ok_or_else(|| "snapshot cursor probe unavailable".to_string())?; + Ok(found.map_or(0, |snapshot| hash_str(&snapshot.window.id().to_string()))) + } + + fn measure( + runs: usize, + mut sample: impl FnMut() -> Result, + ) -> Result, String> { + let _ = std::hint::black_box(sample()?); + let mut samples = Vec::with_capacity(runs); + for _ in 0..runs { + let start = Instant::now(); + let value = std::hint::black_box(sample()?); + let elapsed = start.elapsed().as_secs_f64() * 1000.0; + let _ = std::hint::black_box(value); + samples.push(elapsed); + } + Ok(samples) + } + + fn print_stats(label: &str, samples: &[f64]) { + let mut ordered = samples.to_vec(); + ordered.sort_by(f64::total_cmp); + let min = ordered.first().copied().unwrap_or(0.0); + let max = ordered.last().copied().unwrap_or(0.0); + let median = ordered.get(ordered.len() / 2).copied().unwrap_or(0.0); + println!("{label} median={median:.3} min={min:.3} max={max:.3}"); + } +} diff --git a/crates/scap-targets/src/platform/linux.rs b/crates/scap-targets/src/platform/linux.rs index 1dbb6c3b966..0de5c38eed2 100644 --- a/crates/scap-targets/src/platform/linux.rs +++ b/crates/scap-targets/src/platform/linux.rs @@ -2,11 +2,19 @@ use std::{env, fs, str::FromStr}; use x11rb::{ connection::Connection, + cookie::Cookie, + errors::{ConnectionError, ReplyError}, protocol::{ - randr::ConnectionExt as RandrConnectionExt, - xproto::{Atom, AtomEnum, ConnectionExt as XprotoConnectionExt, MapState, Window}, + ErrorKind, + randr::{ConnectionExt as RandrConnectionExt, GetMonitorsReply}, + xproto::{ + Atom, AtomEnum, ConnectionExt as XprotoConnectionExt, GetGeometryReply, + GetPropertyReply, InternAtomReply, MapState, QueryPointerReply, + TranslateCoordinatesReply, Window, + }, }, rust_connection::RustConnection, + x11_utils::TryParse, }; use crate::bounds::{ @@ -48,47 +56,7 @@ impl DisplayImpl { let Ok((conn, screen_num)) = x11_connection() else { return wayland_displays(); }; - let screen = &conn.setup().roots[screen_num]; - let root = screen.root; - - let monitors = conn - .randr_get_monitors(root, true) - .ok() - .and_then(|cookie| cookie.reply().ok()) - .map(|reply| { - reply - .monitors - .into_iter() - .enumerate() - .filter(|(_, monitor)| monitor.width > 0 && monitor.height > 0) - .map(|(index, monitor)| Self { - id: index as u32, - x: monitor.x.into(), - y: monitor.y.into(), - width: monitor.width.into(), - height: monitor.height.into(), - refresh_rate: 60.0, - logical_bounds: None, - wayland_uuid: None, - }) - .collect::>() - }) - .unwrap_or_default(); - - if !monitors.is_empty() { - return monitors; - } - - vec![Self { - id: 0, - x: 0, - y: 0, - width: screen.width_in_pixels.into(), - height: screen.height_in_pixels.into(), - refresh_rate: 60.0, - logical_bounds: None, - wayland_uuid: None, - }] + displays_on_connection(&conn, screen_num) } pub fn wayland_uuid(&self) -> Option { @@ -231,6 +199,33 @@ impl WindowImpl { }) } + pub fn owner_pid(&self) -> Option { + if is_wayland_portal_window(self.0) { + return None; + } + let (conn, _) = x11_connection().ok()?; + window_pid(&conn, self.0) + } + + pub fn list_x11_snapshots() -> Option> { + x11_pass(QueryMode::Picker, false).map(|(snapshots, _)| snapshots) + } + + /// `None` when X11 is unavailable. `Some(None)` when the probe ran and no + /// listed window contains the pointer. + pub fn topmost_x11_snapshot_at_cursor() -> Option> { + let (snapshots, cursor) = x11_pass(QueryMode::Listing, true)?; + let Some(cursor) = cursor else { + return Some(None); + }; + Some( + snapshots + .into_iter() + .rev() + .find(|snapshot| snapshot.bounds.contains_point(cursor)), + ) + } + pub fn id(&self) -> WindowIdImpl { WindowIdImpl(self.0) } @@ -404,19 +399,29 @@ fn client_list(conn: &RustConnection, root: Window) -> Vec { .into_iter() .find_map(|name| { let atom = intern_atom(conn, name)?; - let reply = conn - .get_property(false, root, atom, AtomEnum::WINDOW, 0, u32::MAX) - .ok()? - .reply() - .ok()?; - reply - .value32() - .map(|values| values.collect::>()) - .filter(|windows| !windows.is_empty()) + window_list_property(conn, root, atom) }) .unwrap_or_else(|| query_window_tree(conn, root)) } +fn client_windows(conn: &RustConnection, root: Window, atoms: &X11Atoms) -> Vec { + window_list_property(conn, root, atoms.client_list_stacking) + .or_else(|| window_list_property(conn, root, atoms.client_list)) + .unwrap_or_else(|| query_window_tree(conn, root)) +} + +fn window_list_property(conn: &RustConnection, root: Window, atom: Atom) -> Option> { + let reply = conn + .get_property(false, root, atom, AtomEnum::WINDOW, 0, u32::MAX) + .ok()? + .reply() + .ok()?; + reply + .value32() + .map(|values| values.collect::>()) + .filter(|windows| !windows.is_empty()) +} + fn query_window_tree(conn: &RustConnection, root: Window) -> Vec { let mut windows = Vec::new(); let mut stack = conn @@ -449,15 +454,15 @@ fn window_property_string( .ok()? .reply() .ok()?; - if reply.value.is_empty() { + property_text(&reply.value) +} + +fn property_text(bytes: &[u8]) -> Option { + if bytes.is_empty() { return None; } - let nul = reply - .value - .iter() - .position(|b| *b == 0) - .unwrap_or(reply.value.len()); - String::from_utf8(reply.value[..nul].to_vec()) + let nul = bytes.iter().position(|b| *b == 0).unwrap_or(bytes.len()); + String::from_utf8(bytes[..nul].to_vec()) .ok() .filter(|value| !value.is_empty()) } @@ -469,6 +474,10 @@ fn window_pid(conn: &RustConnection, window: Window) -> Option { .ok()? .reply() .ok()?; + cardinal_from_reply(&reply) +} + +fn cardinal_from_reply(reply: &GetPropertyReply) -> Option { reply.value32()?.next() } @@ -491,3 +500,735 @@ fn get_cursor_position() -> Option { reply.root_y.into(), )) } + +pub struct X11WindowSnapshot { + pub window: crate::Window, + pub name: String, + pub owner_name: Option, + pub owner_pid: Option, + pub bounds: PhysicalBounds, + pub display: DisplayImpl, +} + +impl X11WindowSnapshot { + pub fn logical_size(&self) -> LogicalSize { + let size = self.bounds.size(); + LogicalSize::new(size.width(), size.height()) + } + + pub fn display_relative_origin(&self) -> Option<(f64, f64)> { + let display_bounds = self.display.logical_bounds()?; + let position = self.bounds.position(); + Some(( + position.x() - display_bounds.position().x(), + position.y() - display_bounds.position().y(), + )) + } + + pub fn refresh_rate(&self) -> f64 { + self.display.refresh_rate() + } +} + +#[derive(Clone, Copy)] +enum QueryMode { + Listing, + Picker, +} + +struct X11Atoms { + client_list_stacking: Atom, + client_list: Atom, + net_wm_name: Atom, + wm_name: Atom, + net_wm_pid: Atom, + wm_class: Atom, +} + +enum ReplyOutcome { + Present(T), + Vanished, + Missing, +} + +struct WindowReplies { + geometry: ReplyOutcome<(u16, u16)>, + translation: ReplyOutcome<(i16, i16)>, + net_wm_name: ReplyOutcome>, + wm_name: ReplyOutcome>, + pid: ReplyOutcome>, + wm_class: ReplyOutcome>, +} + +struct ParsedWindow { + name: String, + owner_name: Option, + owner_pid: Option, + bounds: PhysicalBounds, + display: DisplayImpl, +} + +struct PendingWindow<'conn> { + window: Window, + geometry: Result, ConnectionError>, + translation: Result, ConnectionError>, + net_wm_name: Result, ConnectionError>, + wm_name: Result, ConnectionError>, + pid: Option, ConnectionError>>, + wm_class: Option, ConnectionError>>, +} + +fn x11_pass( + mode: QueryMode, + with_cursor: bool, +) -> Option<(Vec, Option)> { + if prefers_wayland() { + return None; + } + let (conn, screen_num) = x11_connection().ok()?; + let (root, screen_width, screen_height) = screen_geometry(&conn, screen_num)?; + let atom_cookies = send_interns(&conn); + let monitors_cookie = conn.randr_get_monitors(root, true).ok(); + let pointer_cookie = if with_cursor { + conn.query_pointer(root).ok() + } else { + None + }; + let atoms = recv_interns(atom_cookies)?; + let displays = recv_displays(monitors_cookie, screen_width, screen_height); + let cursor = pointer_cookie.and_then(pointer_position); + let windows = client_windows(&conn, root, &atoms); + let pending = send_window_queries(&conn, root, &windows, &atoms, mode); + let snapshots = finish_window_queries(pending, &displays); + Some((snapshots, cursor)) +} + +fn screen_geometry(conn: &RustConnection, screen_num: usize) -> Option<(Window, u16, u16)> { + let screen = conn.setup().roots.get(screen_num)?; + Some((screen.root, screen.width_in_pixels, screen.height_in_pixels)) +} + +fn displays_on_connection(conn: &RustConnection, screen_num: usize) -> Vec { + let Some((root, screen_width, screen_height)) = screen_geometry(conn, screen_num) else { + return Vec::new(); + }; + let monitors_cookie = conn.randr_get_monitors(root, true).ok(); + recv_displays(monitors_cookie, screen_width, screen_height) +} + +fn recv_displays( + cookie: Option>, + screen_width: u16, + screen_height: u16, +) -> Vec { + let monitors = cookie + .and_then(|cookie| cookie.reply().ok()) + .map(|reply| { + reply + .monitors + .into_iter() + .enumerate() + .filter(|(_, monitor)| monitor.width > 0 && monitor.height > 0) + .map(|(index, monitor)| DisplayImpl { + id: index as u32, + x: monitor.x.into(), + y: monitor.y.into(), + width: monitor.width.into(), + height: monitor.height.into(), + refresh_rate: 60.0, + logical_bounds: None, + wayland_uuid: None, + }) + .collect::>() + }) + .unwrap_or_default(); + if !monitors.is_empty() { + return monitors; + } + vec![DisplayImpl { + id: 0, + x: 0, + y: 0, + width: screen_width.into(), + height: screen_height.into(), + refresh_rate: 60.0, + logical_bounds: None, + wayland_uuid: None, + }] +} + +fn send_interns( + conn: &RustConnection, +) -> Vec, ConnectionError>> { + [ + "_NET_CLIENT_LIST_STACKING", + "_NET_CLIENT_LIST", + "_NET_WM_NAME", + "WM_NAME", + "_NET_WM_PID", + "WM_CLASS", + ] + .into_iter() + .map(|name| conn.intern_atom(false, name.as_bytes())) + .collect() +} + +fn recv_interns( + cookies: Vec, ConnectionError>>, +) -> Option { + let mut atoms = [0; 6]; + if cookies.len() != atoms.len() { + return None; + } + for (slot, cookie) in atoms.iter_mut().zip(cookies) { + let atom = cookie.ok()?.reply().ok()?.atom; + if atom == x11rb::NONE { + return None; + } + *slot = atom; + } + Some(X11Atoms { + client_list_stacking: atoms[0], + client_list: atoms[1], + net_wm_name: atoms[2], + wm_name: atoms[3], + net_wm_pid: atoms[4], + wm_class: atoms[5], + }) +} + +fn pointer_position( + cookie: Cookie<'_, RustConnection, QueryPointerReply>, +) -> Option { + let reply = cookie.reply().ok()?; + Some(PhysicalPosition::new( + reply.root_x.into(), + reply.root_y.into(), + )) +} + +fn send_window_queries<'conn>( + conn: &'conn RustConnection, + root: Window, + windows: &[Window], + atoms: &X11Atoms, + mode: QueryMode, +) -> Vec> { + let picker = matches!(mode, QueryMode::Picker); + windows + .iter() + .copied() + .map(|window| PendingWindow { + window, + geometry: conn.get_geometry(window), + translation: conn.translate_coordinates(window, root, 0, 0), + net_wm_name: conn.get_property( + false, + window, + atoms.net_wm_name, + AtomEnum::ANY, + 0, + 1024, + ), + wm_name: conn.get_property(false, window, atoms.wm_name, AtomEnum::ANY, 0, 1024), + pid: picker.then(|| { + conn.get_property(false, window, atoms.net_wm_pid, AtomEnum::CARDINAL, 0, 1) + }), + wm_class: picker + .then(|| conn.get_property(false, window, atoms.wm_class, AtomEnum::ANY, 0, 1024)), + }) + .collect() +} + +fn finish_window_queries( + pending: Vec>, + displays: &[DisplayImpl], +) -> Vec { + pending + .into_iter() + .filter_map(|pending| { + let replies = WindowReplies { + geometry: map_present(cookie_outcome(pending.geometry), |reply| { + (reply.width, reply.height) + }), + translation: map_present(cookie_outcome(pending.translation), |reply| { + (reply.dst_x, reply.dst_y) + }), + net_wm_name: map_present(cookie_outcome(pending.net_wm_name), |reply| { + property_text(&reply.value) + }), + wm_name: map_present(cookie_outcome(pending.wm_name), |reply| { + property_text(&reply.value) + }), + pid: match pending.pid { + Some(cookie) => { + map_present(cookie_outcome(cookie), |reply| cardinal_from_reply(&reply)) + } + None => ReplyOutcome::Present(None), + }, + wm_class: match pending.wm_class { + Some(cookie) => { + map_present(cookie_outcome(cookie), |reply| property_text(&reply.value)) + } + None => ReplyOutcome::Present(None), + }, + }; + let window = pending.window; + parse_window_replies(replies, displays, &process_name).map(|parsed| X11WindowSnapshot { + window: crate::Window(WindowImpl(window)), + name: parsed.name, + owner_name: parsed.owner_name, + owner_pid: parsed.owner_pid, + bounds: parsed.bounds, + display: parsed.display, + }) + }) + .collect() +} + +fn cookie_outcome( + cookie: Result, ConnectionError>, +) -> ReplyOutcome { + match cookie { + Ok(cookie) => outcome_from_reply(cookie.reply()), + Err(_) => ReplyOutcome::Missing, + } +} + +fn outcome_from_reply(result: Result) -> ReplyOutcome { + match result { + Ok(value) => ReplyOutcome::Present(value), + Err(ReplyError::X11Error(error)) if is_vanished_error_kind(error.error_kind) => { + ReplyOutcome::Vanished + } + Err(ReplyError::X11Error(_) | ReplyError::ConnectionError(_)) => ReplyOutcome::Missing, + } +} + +fn is_vanished_error_kind(kind: ErrorKind) -> bool { + matches!(kind, ErrorKind::Window | ErrorKind::Drawable) +} + +fn map_present(outcome: ReplyOutcome, map: impl FnOnce(T) -> U) -> ReplyOutcome { + match outcome { + ReplyOutcome::Present(value) => ReplyOutcome::Present(map(value)), + ReplyOutcome::Vanished => ReplyOutcome::Vanished, + ReplyOutcome::Missing => ReplyOutcome::Missing, + } +} + +fn parse_window_replies( + replies: WindowReplies, + displays: &[DisplayImpl], + proc_name: &impl Fn(u32) -> Option, +) -> Option { + let (width, height) = present(replies.geometry)?; + let (dst_x, dst_y) = present(replies.translation)?; + let net_wm_name = present(replies.net_wm_name)?; + let wm_name = present(replies.wm_name)?; + let owner_pid = present(replies.pid)?; + let wm_class = present(replies.wm_class)?; + if width == 0 || height == 0 { + return None; + } + let name = net_wm_name.or(wm_name)?; + let bounds = PhysicalBounds::new( + PhysicalPosition::new(dst_x.into(), dst_y.into()), + PhysicalSize::new(width.into(), height.into()), + ); + let center = PhysicalPosition::new( + bounds.position().x() + bounds.size().width() / 2.0, + bounds.position().y() + bounds.size().height() / 2.0, + ); + let display = displays.iter().copied().find(|display| { + display + .physical_bounds() + .is_some_and(|display_bounds| display_bounds.contains_point(center)) + })?; + Some(ParsedWindow { + name, + owner_name: resolve_owner_name(owner_pid, wm_class, proc_name), + owner_pid, + bounds, + display, + }) +} + +fn present(outcome: ReplyOutcome) -> Option { + match outcome { + ReplyOutcome::Present(value) => Some(value), + ReplyOutcome::Vanished | ReplyOutcome::Missing => None, + } +} + +fn resolve_owner_name( + pid: Option, + wm_class: Option, + proc_name: &impl Fn(u32) -> Option, +) -> Option { + pid.and_then(proc_name).or(wm_class) +} + +#[cfg(test)] +mod tests { + use super::{ + DisplayImpl, ReplyOutcome, WindowImpl, WindowReplies, cardinal_from_reply, + is_vanished_error_kind, parse_window_replies, property_text, resolve_owner_name, + }; + use x11rb::protocol::{ + ErrorKind, + xproto::{AtomEnum, ConnectionExt, CreateWindowAux, PropMode, WindowClass, create_window}, + }; + use x11rb::{ + COPY_DEPTH_FROM_PARENT, connection::Connection, protocol::xproto::GetPropertyReply, + rust_connection::RustConnection, + }; + + fn display_box(x: i32, y: i32, width: u32, height: u32) -> DisplayImpl { + DisplayImpl { + id: 0, + x, + y, + width, + height, + refresh_rate: 60.0, + logical_bounds: None, + wayland_uuid: None, + } + } + + fn replies( + geometry: ReplyOutcome<(u16, u16)>, + translation: ReplyOutcome<(i16, i16)>, + net_wm_name: ReplyOutcome>, + wm_name: ReplyOutcome>, + pid: ReplyOutcome>, + wm_class: ReplyOutcome>, + ) -> WindowReplies { + WindowReplies { + geometry, + translation, + net_wm_name, + wm_name, + pid, + wm_class, + } + } + + fn kept(name: &str) -> WindowReplies { + replies( + ReplyOutcome::Present((100, 80)), + ReplyOutcome::Present((10, 20)), + ReplyOutcome::Present(Some(name.to_string())), + ReplyOutcome::Present(None), + ReplyOutcome::Present(Some(42)), + ReplyOutcome::Present(Some("Bench".to_string())), + ) + } + + fn surviving_ids(rows: Vec<(u32, WindowReplies)>) -> Vec { + let displays = [display_box(0, 0, 1920, 1080)]; + rows.into_iter() + .filter_map(|(id, row)| { + parse_window_replies(row, &displays, &|pid| Some(format!("proc-{pid}"))).map(|_| id) + }) + .collect() + } + + fn property_reply(format: u8, value: Vec) -> GetPropertyReply { + GetPropertyReply { + format, + sequence: 0, + length: 0, + type_: AtomEnum::CARDINAL.into(), + bytes_after: 0, + value_len: 0, + value, + } + } + + #[test] + fn property_text_stops_at_the_first_nul() { + assert_eq!(property_text(b"hello\0world"), Some("hello".to_string())); + assert_eq!( + property_text(b"instance\0class\0"), + Some("instance".to_string()) + ); + assert_eq!(property_text(b"plain"), Some("plain".to_string())); + } + + #[test] + fn property_text_rejects_empty_and_invalid_utf8() { + assert_eq!(property_text(b""), None); + assert_eq!(property_text(&[0]), None); + assert_eq!(property_text(&[0xff, 0xfe]), None); + } + + #[test] + fn cardinal_reply_reads_the_first_native_u32() { + let reply = property_reply(32, 0x0102_0304u32.to_ne_bytes().to_vec()); + assert_eq!(cardinal_from_reply(&reply), Some(0x0102_0304)); + } + + #[test] + fn cardinal_reply_rejects_a_non_32bit_format() { + let reply = property_reply(8, 0x0102_0304u32.to_ne_bytes().to_vec()); + assert_eq!(cardinal_from_reply(&reply), None); + } + + #[test] + fn bad_window_and_bad_drawable_count_as_vanished() { + assert!(is_vanished_error_kind(ErrorKind::Window)); + assert!(is_vanished_error_kind(ErrorKind::Drawable)); + assert!(!is_vanished_error_kind(ErrorKind::Atom)); + assert!(!is_vanished_error_kind(ErrorKind::Match)); + } + + #[test] + fn vanished_window_is_skipped_and_neighbors_stay() { + let mut vanished = kept("gone"); + vanished.geometry = ReplyOutcome::Vanished; + assert_eq!( + surviving_ids(vec![(1, kept("one")), (2, vanished), (3, kept("three"))]), + vec![1, 3] + ); + } + + #[test] + fn vanished_property_after_geometry_skips_only_that_window() { + let mut vanished = kept("gone"); + vanished.pid = ReplyOutcome::Vanished; + assert_eq!( + surviving_ids(vec![(1, kept("one")), (2, vanished), (3, kept("three"))]), + vec![1, 3] + ); + } + + #[test] + fn missing_geometry_skips_that_window_only() { + let mut missing = kept("gone"); + missing.geometry = ReplyOutcome::Missing; + assert_eq!( + surviving_ids(vec![(1, kept("one")), (2, missing), (3, kept("three"))]), + vec![1, 3] + ); + } + + #[test] + fn wm_name_fills_in_when_net_wm_name_is_absent() { + let displays = [display_box(0, 0, 1920, 1080)]; + let row = replies( + ReplyOutcome::Present((40, 40)), + ReplyOutcome::Present((0, 0)), + ReplyOutcome::Present(None), + ReplyOutcome::Present(Some("legacy".to_string())), + ReplyOutcome::Present(None), + ReplyOutcome::Present(Some("Legacy".to_string())), + ); + let parsed = parse_window_replies(row, &displays, &|_| None).expect("window"); + assert_eq!(parsed.name, "legacy"); + assert_eq!(parsed.owner_name.as_deref(), Some("Legacy")); + assert_eq!(parsed.owner_pid, None); + } + + #[test] + fn owner_name_prefers_the_process_name() { + assert_eq!( + resolve_owner_name(Some(7), Some("class".into()), &|_| Some("from-proc".into())), + Some("from-proc".into()) + ); + assert_eq!( + resolve_owner_name(Some(7), Some("class".into()), &|_| None), + Some("class".into()) + ); + assert_eq!( + resolve_owner_name(None, Some("class".into()), &|_| Some("unused".into())), + Some("class".into()) + ); + } + + #[test] + fn zero_size_and_offscreen_windows_are_skipped() { + let displays = [display_box(0, 0, 200, 200)]; + assert!(parse_window_replies(kept("zero"), &displays, &|_| None).is_some()); + let mut zero = kept("zero"); + zero.geometry = ReplyOutcome::Present((0, 40)); + assert!(parse_window_replies(zero, &displays, &|_| None).is_none()); + let mut offscreen = kept("off"); + offscreen.translation = ReplyOutcome::Present((1000, 1000)); + assert!(parse_window_replies(offscreen, &displays, &|_| None).is_none()); + } + + #[test] + #[ignore = "needs an X server; run under Xvfb"] + fn snapshot_matches_per_field_queries() { + let (conn, screen_num) = x11rb::connect(None).expect("X11 connection"); + let screen = &conn.setup().roots[screen_num]; + let root = screen.root; + let mut windows = Vec::new(); + for index in 0..4u32 { + let window = conn.generate_id().expect("window id"); + create_window( + &conn, + COPY_DEPTH_FROM_PARENT, + window, + root, + i16::try_from(index * 30).unwrap_or(0), + 10, + 80, + 60, + 0, + WindowClass::INPUT_OUTPUT, + 0, + &CreateWindowAux::new().background_pixel(screen.white_pixel), + ) + .expect("create_window") + .check() + .expect("create accepted"); + let name = format!("snap-{index}"); + let class = format!("inst-{index}\0Bench\0"); + let pid = std::process::id().to_ne_bytes(); + let net_wm_name = intern(&conn, "_NET_WM_NAME"); + let wm_name = AtomEnum::WM_NAME.into(); + let wm_class = AtomEnum::WM_CLASS.into(); + let net_wm_pid = intern(&conn, "_NET_WM_PID"); + replace_property( + &conn, + window, + net_wm_name, + AtomEnum::STRING.into(), + 8, + name.as_bytes(), + ); + replace_property( + &conn, + window, + wm_name, + AtomEnum::STRING.into(), + 8, + name.as_bytes(), + ); + replace_property( + &conn, + window, + wm_class, + AtomEnum::STRING.into(), + 8, + class.as_bytes(), + ); + replace_property( + &conn, + window, + net_wm_pid, + AtomEnum::CARDINAL.into(), + 32, + &pid, + ); + conn.map_window(window) + .expect("map") + .check() + .expect("map accepted"); + windows.push(window); + } + let stale = windows.remove(1); + conn.destroy_window(stale) + .expect("destroy") + .check() + .expect("destroy accepted"); + let mut listed = windows.clone(); + listed.insert(1, stale); + let stacking = intern(&conn, "_NET_CLIENT_LIST_STACKING"); + let client_list = intern(&conn, "_NET_CLIENT_LIST"); + let mut bytes = Vec::with_capacity(listed.len() * 4); + for window in &listed { + bytes.extend_from_slice(&window.to_ne_bytes()); + } + replace_property(&conn, root, stacking, AtomEnum::WINDOW.into(), 32, &bytes); + replace_property( + &conn, + root, + client_list, + AtomEnum::WINDOW.into(), + 32, + &bytes, + ); + conn.flush().expect("flush"); + + let snapshots = WindowImpl::list_x11_snapshots().expect("x11 snapshots"); + let snapshot_ids = snapshots + .iter() + .map(|snapshot| snapshot.window.0.0) + .filter(|id| listed.contains(id)) + .collect::>(); + assert_eq!(snapshot_ids, windows, "stale window id must be skipped"); + + let listed_ids = WindowImpl::list() + .into_iter() + .map(|window| window.0) + .filter(|id| listed.contains(id)) + .collect::>(); + assert_eq!(listed_ids, snapshot_ids); + + for snapshot in snapshots + .iter() + .filter(|snapshot| windows.contains(&snapshot.window.0.0)) + { + let handle = WindowImpl(snapshot.window.0.0); + assert_eq!(handle.name().as_deref(), Some(snapshot.name.as_str())); + assert_eq!(handle.owner_name(), snapshot.owner_name); + assert_eq!(handle.owner_pid(), snapshot.owner_pid); + assert_eq!(snapshot.owner_pid, Some(std::process::id())); + let bounds = handle.physical_bounds().expect("bounds"); + assert_eq!(bounds.position().x(), snapshot.bounds.position().x()); + assert_eq!(bounds.position().y(), snapshot.bounds.position().y()); + assert_eq!(bounds.size().width(), snapshot.bounds.size().width()); + assert_eq!(bounds.size().height(), snapshot.bounds.size().height()); + assert_eq!( + handle.display().map(|display| display.raw_id()), + Some(snapshot.display.raw_id()) + ); + } + + for window in windows { + if let Ok(cookie) = conn.destroy_window(window) { + let _ = cookie.check(); + } + } + let _ = conn.flush(); + } + + fn intern(conn: &RustConnection, name: &str) -> u32 { + conn.intern_atom(false, name.as_bytes()) + .expect("intern") + .reply() + .expect("intern reply") + .atom + } + + fn replace_property( + conn: &RustConnection, + window: u32, + property: u32, + type_: u32, + format: u8, + data: &[u8], + ) { + let data_len = match format { + 8 => u32::try_from(data.len()).unwrap_or(0), + 32 => u32::try_from(data.len() / 4).unwrap_or(0), + _ => 0, + }; + conn.change_property( + PropMode::REPLACE, + window, + property, + type_, + format, + data_len, + data, + ) + .expect("change_property") + .check() + .expect("property accepted"); + } +} From 2da8a75dc445b3a0084bbbcec9e8741ad4d46ba3 Mon Sep 17 00:00:00 2001 From: Kyzer Date: Thu, 22 Oct 2026 07:57:46 +0000 Subject: [PATCH 2/3] fix(scap-targets): fall back to the x11 window tree Retry the window tree when the client list yields no candidates, and refuse to run the window list bench unless CAP_X11_BENCH_ISOLATED=1 is set. --- .../src/bin/x11_window_list_bench.rs | 19 ++ crates/scap-targets/src/platform/linux.rs | 213 +++++++++++++++++- 2 files changed, 228 insertions(+), 4 deletions(-) diff --git a/crates/scap-targets/src/bin/x11_window_list_bench.rs b/crates/scap-targets/src/bin/x11_window_list_bench.rs index 60c4ae02ca4..de6ecb1a527 100644 --- a/crates/scap-targets/src/bin/x11_window_list_bench.rs +++ b/crates/scap-targets/src/bin/x11_window_list_bench.rs @@ -1,3 +1,9 @@ +//! Refuses to run unless `CAP_X11_BENCH_ISOLATED=1`. It replaces +//! `_NET_CLIENT_LIST` and `_NET_CLIENT_LIST_STACKING` on the current `DISPLAY` +//! and warps the pointer. Start an isolated server first +//! (`Xvfb :99 -screen 0 1920x1080x24`), then run with +//! `CAP_X11_BENCH_ISOLATED=1 DISPLAY=:99`. + use std::process::ExitCode; fn main() -> ExitCode { @@ -31,6 +37,7 @@ mod linux { use scap_targets::{Window, WindowImpl}; pub fn run() -> Result<(), String> { + ensure_isolated_display()?; let windows = arg_usize("windows", 40)?; let runs = arg_usize("runs", 11)?; if runs == 0 { @@ -77,6 +84,18 @@ mod linux { Ok(()) } + fn ensure_isolated_display() -> Result<(), String> { + if std::env::var("CAP_X11_BENCH_ISOLATED").ok().as_deref() == Some("1") { + return Ok(()); + } + Err( + "refusing to run: set CAP_X11_BENCH_ISOLATED=1. This bench replaces \ +_NET_CLIENT_LIST and _NET_CLIENT_LIST_STACKING and warps the pointer on the \ +current DISPLAY. Use an isolated server, for example: Xvfb :99 -screen 0 1920x1080x24" + .to_string(), + ) + } + fn arg_usize(name: &str, default: usize) -> Result { let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { diff --git a/crates/scap-targets/src/platform/linux.rs b/crates/scap-targets/src/platform/linux.rs index 0de5c38eed2..9b4e312aa74 100644 --- a/crates/scap-targets/src/platform/linux.rs +++ b/crates/scap-targets/src/platform/linux.rs @@ -404,10 +404,13 @@ fn client_list(conn: &RustConnection, root: Window) -> Vec { .unwrap_or_else(|| query_window_tree(conn, root)) } -fn client_windows(conn: &RustConnection, root: Window, atoms: &X11Atoms) -> Vec { +fn client_list_windows( + conn: &RustConnection, + root: Window, + atoms: &X11Atoms, +) -> Option> { window_list_property(conn, root, atoms.client_list_stacking) .or_else(|| window_list_property(conn, root, atoms.client_list)) - .unwrap_or_else(|| query_window_tree(conn, root)) } fn window_list_property(conn: &RustConnection, root: Window, atom: Atom) -> Option> { @@ -597,9 +600,16 @@ fn x11_pass( let atoms = recv_interns(atom_cookies)?; let displays = recv_displays(monitors_cookie, screen_width, screen_height); let cursor = pointer_cookie.and_then(pointer_position); - let windows = client_windows(&conn, root, &atoms); + let listed = client_list_windows(&conn, root, &atoms); + let from_client_list = listed.is_some(); + let windows = listed.unwrap_or_else(|| query_window_tree(&conn, root)); let pending = send_window_queries(&conn, root, &windows, &atoms, mode); - let snapshots = finish_window_queries(pending, &displays); + let mut snapshots = finish_window_queries(pending, &displays); + if snapshots.is_empty() && from_client_list { + let tree = query_window_tree(&conn, root); + let pending = send_window_queries(&conn, root, &tree, &atoms, mode); + snapshots = finish_window_queries(pending, &displays); + } Some((snapshots, cursor)) } @@ -1197,6 +1207,201 @@ mod tests { let _ = conn.flush(); } + #[test] + #[ignore = "needs an X server; run under Xvfb"] + fn stale_client_list_falls_back_to_the_window_tree() { + let (conn, screen_num) = x11rb::connect(None).expect("X11 connection"); + let screen = &conn.setup().roots[screen_num]; + let root = screen.root; + let white = screen.white_pixel; + let window_a = open_named_window(&conn, root, white, 0, 20, 20); + let window_b = open_named_window(&conn, root, white, 1, 200, 20); + let guard = MappedWindows { + conn, + windows: vec![window_a, window_b], + }; + publish_client_list(&guard.conn, root, &[window_a]); + guard + .conn + .warp_pointer(x11rb::NONE, root, 0, 0, 0, 0, 240, 50) + .expect("warp") + .check() + .expect("warp accepted"); + + assert_eq!(snapshot_ids(), vec![window_a]); + assert_eq!(list_ids(), vec![window_a]); + assert_eq!( + WindowImpl::topmost_x11_snapshot_at_cursor() + .map(|found| found.map(|snapshot| snapshot.window.0.0)), + Some(None) + ); + + let decoy = guard.conn.generate_id().expect("decoy id"); + create_window( + &guard.conn, + COPY_DEPTH_FROM_PARENT, + decoy, + root, + 400, + 20, + 40, + 40, + 0, + WindowClass::INPUT_OUTPUT, + 0, + &CreateWindowAux::new().background_pixel(white), + ) + .expect("create decoy") + .check() + .expect("decoy accepted"); + guard + .conn + .destroy_window(decoy) + .expect("destroy decoy") + .check() + .expect("decoy destroyed"); + publish_client_list(&guard.conn, root, &[decoy]); + + let listed = list_ids(); + assert!( + listed.contains(&window_a) && listed.contains(&window_b), + "list missed a live window: {listed:?}" + ); + assert!( + !listed.contains(&decoy), + "destroyed client-list id survived: {listed:?}" + ); + assert_eq!(snapshot_ids(), listed); + assert_eq!( + WindowImpl::topmost_x11_snapshot_at_cursor() + .map(|found| found.map(|snapshot| snapshot.window.0.0)), + Some(Some(window_b)) + ); + } + + struct MappedWindows { + conn: RustConnection, + windows: Vec, + } + + impl Drop for MappedWindows { + fn drop(&mut self) { + for window in &self.windows { + if let Ok(cookie) = self.conn.destroy_window(*window) { + let _ = cookie.check(); + } + } + let _ = self.conn.flush(); + } + } + + fn open_named_window( + conn: &RustConnection, + root: u32, + white: u32, + index: u32, + x: i16, + y: i16, + ) -> u32 { + let window = conn.generate_id().expect("window id"); + create_window( + conn, + COPY_DEPTH_FROM_PARENT, + window, + root, + x, + y, + 80, + 60, + 0, + WindowClass::INPUT_OUTPUT, + 0, + &CreateWindowAux::new().background_pixel(white), + ) + .expect("create_window") + .check() + .expect("create accepted"); + let name = format!("tree-fallback-{index}"); + let class = format!("tree-{index}\0Bench\0"); + let pid = std::process::id().to_ne_bytes(); + replace_property( + conn, + window, + intern(conn, "_NET_WM_NAME"), + AtomEnum::STRING.into(), + 8, + name.as_bytes(), + ); + replace_property( + conn, + window, + AtomEnum::WM_NAME.into(), + AtomEnum::STRING.into(), + 8, + name.as_bytes(), + ); + replace_property( + conn, + window, + AtomEnum::WM_CLASS.into(), + AtomEnum::STRING.into(), + 8, + class.as_bytes(), + ); + replace_property( + conn, + window, + intern(conn, "_NET_WM_PID"), + AtomEnum::CARDINAL.into(), + 32, + &pid, + ); + conn.map_window(window) + .expect("map") + .check() + .expect("map accepted"); + window + } + + fn publish_client_list(conn: &RustConnection, root: u32, windows: &[u32]) { + let mut bytes = Vec::with_capacity(windows.len() * 4); + for window in windows { + bytes.extend_from_slice(&window.to_ne_bytes()); + } + replace_property( + conn, + root, + intern(conn, "_NET_CLIENT_LIST_STACKING"), + AtomEnum::WINDOW.into(), + 32, + &bytes, + ); + replace_property( + conn, + root, + intern(conn, "_NET_CLIENT_LIST"), + AtomEnum::WINDOW.into(), + 32, + &bytes, + ); + conn.flush().expect("flush"); + } + + fn snapshot_ids() -> Vec { + WindowImpl::list_x11_snapshots() + .expect("x11 snapshots") + .into_iter() + .map(|snapshot| snapshot.window.0.0) + .collect() + } + + fn list_ids() -> Vec { + WindowImpl::list() + .into_iter() + .map(|window| window.0) + .collect() + } + fn intern(conn: &RustConnection, name: &str) -> u32 { conn.intern_atom(false, name.as_bytes()) .expect("intern") From f89ca0741e1f4cdd2f5d3ed82577967d4172f0a6 Mon Sep 17 00:00:00 2001 From: Kyzer Date: Thu, 22 Oct 2026 09:06:34 +0000 Subject: [PATCH 3/3] fix(scap-targets): serialize the ignored x11 display tests Hold one mutex across both Xvfb tests so they cannot replace each other's client list. --- crates/scap-targets/src/platform/linux.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/scap-targets/src/platform/linux.rs b/crates/scap-targets/src/platform/linux.rs index 9b4e312aa74..af6d6ff9d2b 100644 --- a/crates/scap-targets/src/platform/linux.rs +++ b/crates/scap-targets/src/platform/linux.rs @@ -1069,9 +1069,16 @@ mod tests { assert!(parse_window_replies(offscreen, &displays, &|_| None).is_none()); } + fn lock_shared_x11_display() -> std::sync::MutexGuard<'static, ()> { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + LOCK.lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + #[test] #[ignore = "needs an X server; run under Xvfb"] fn snapshot_matches_per_field_queries() { + let _x11_display = lock_shared_x11_display(); let (conn, screen_num) = x11rb::connect(None).expect("X11 connection"); let screen = &conn.setup().roots[screen_num]; let root = screen.root; @@ -1210,6 +1217,7 @@ mod tests { #[test] #[ignore = "needs an X server; run under Xvfb"] fn stale_client_list_falls_back_to_the_window_tree() { + let _x11_display = lock_shared_x11_display(); let (conn, screen_num) = x11rb::connect(None).expect("X11 connection"); let screen = &conn.setup().roots[screen_num]; let root = screen.root;