Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(scap-targets): batch x11 window queries

Kyzerdd9f24ea1ccd
diff --git a/apps/desktop-gpui/src/devices.rs b/apps/desktop-gpui/src/devices.rs
index 6f6995139..122afc197 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<Window> {
candidates.into_iter().next().map(|(window, _)| window)
}
-#[cfg(not(target_os = "macos"))]
+#[cfg(target_os = "linux")]
+pub fn topmost_foreign_window_at_cursor() -> Option<Window> {
+ 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> {
Window::get_topmost_at_cursor()
}
@@ -734,6 +742,11 @@ pub fn list_windows() -> Vec<WindowOption> {
/// `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<Vec<(WindowOption, Window)>> {
+ 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 767c0bb5a..27a986bfd 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 000000000..60c4ae02c
--- /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<usize, String> {
+ 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::<usize>()
+ .map_err(|error| format!("invalid --{name}: {error}"));
+ }
+ }
+ Ok(default)
+ }
+
+ struct CreatedWindows {
+ conn: x11rb::rust_connection::RustConnection,
+ windows: Vec<u32>,
+ }
+
+ 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<CreatedWindows, String> {
+ 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<u32, String> {
+ 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<u32>,
+ type_: impl Into<u32>,
+ 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<u64>,
+ }
+
+ fn bits(value: f64) -> u64 {
+ value.to_bits()
+ }
+
+ fn picker_rows_per_call() -> Vec<PickerRow> {
+ 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<Vec<PickerRow>, 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<u64, String> {
+ 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<u64, String> {
+ 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<u64, String>,
+ ) -> Result<Vec<f64>, 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 1dbb6c3b9..0de5c38ee 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::<Vec<_>>()
- })
- .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<uuid::Uuid> {
@@ -231,6 +199,33 @@ impl WindowImpl {
})
}
+ pub fn owner_pid(&self) -> Option<u32> {
+ 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<Vec<X11WindowSnapshot>> {
+ 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<Option<X11WindowSnapshot>> {
+ 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<Window> {
.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::<Vec<_>>())
- .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> {
+ 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<Vec<Window>> {
+ let reply = conn
+ .get_property(false, root, atom, AtomEnum::WINDOW, 0, u32::MAX)
+ .ok()?
+ .reply()
+ .ok()?;
+ reply
+ .value32()
+ .map(|values| values.collect::<Vec<_>>())
+ .filter(|windows| !windows.is_empty())
+}
+
fn query_window_tree(conn: &RustConnection, root: Window) -> Vec<Window> {
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<String> {
+ 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<u32> {
.ok()?
.reply()
.ok()?;
+ cardinal_from_reply(&reply)
+}
+
+fn cardinal_from_reply(reply: &GetPropertyReply) -> Option<u32> {
reply.value32()?.next()
}
@@ -491,3 +500,735 @@ fn get_cursor_position() -> Option<PhysicalPosition> {
reply.root_y.into(),
))
}
+
+pub struct X11WindowSnapshot {
+ pub window: crate::Window,
+ pub name: String,
+ pub owner_name: Option<String>,
+ pub owner_pid: Option<u32>,
+ 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<T> {
+ Present(T),
+ Vanished,
+ Missing,
+}
+
+struct WindowReplies {
+ geometry: ReplyOutcome<(u16, u16)>,
+ translation: ReplyOutcome<(i16, i16)>,
+ net_wm_name: ReplyOutcome<Option<String>>,
+ wm_name: ReplyOutcome<Option<String>>,
+ pid: ReplyOutcome<Option<u32>>,
+ wm_class: ReplyOutcome<Option<String>>,
+}
+
+struct ParsedWindow {
+ name: String,
+ owner_name: Option<String>,
+ owner_pid: Option<u32>,
+ bounds: PhysicalBounds,
+ display: DisplayImpl,
+}
+
+struct PendingWindow<'conn> {
+ window: Window,
+ geometry: Result<Cookie<'conn, RustConnection, GetGeometryReply>, ConnectionError>,
+ translation: Result<Cookie<'conn, RustConnection, TranslateCoordinatesReply>, ConnectionError>,
+ net_wm_name: Result<Cookie<'conn, RustConnection, GetPropertyReply>, ConnectionError>,
+ wm_name: Result<Cookie<'conn, RustConnection, GetPropertyReply>, ConnectionError>,
+ pid: Option<Result<Cookie<'conn, RustConnection, GetPropertyReply>, ConnectionError>>,
+ wm_class: Option<Result<Cookie<'conn, RustConnection, GetPropertyReply>, ConnectionError>>,
+}
+
+fn x11_pass(
+ mode: QueryMode,
+ with_cursor: bool,
+) -> Option<(Vec<X11WindowSnapshot>, Option<PhysicalPosition>)> {
+ 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<DisplayImpl> {
+ 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<Cookie<'_, RustConnection, GetMonitorsReply>>,
+ screen_width: u16,
+ screen_height: u16,
+) -> Vec<DisplayImpl> {
+ 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::<Vec<_>>()
+ })
+ .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<Result<Cookie<'_, RustConnection, InternAtomReply>, 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<Result<Cookie<'_, RustConnection, InternAtomReply>, ConnectionError>>,
+) -> Option<X11Atoms> {
+ 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<PhysicalPosition> {
+ 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<PendingWindow<'conn>> {
+ 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<PendingWindow<'_>>,
+ displays: &[DisplayImpl],
+) -> Vec<X11WindowSnapshot> {
+ 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<R: TryParse>(
+ cookie: Result<Cookie<'_, RustConnection, R>, ConnectionError>,
+) -> ReplyOutcome<R> {
+ match cookie {
+ Ok(cookie) => outcome_from_reply(cookie.reply()),
+ Err(_) => ReplyOutcome::Missing,
+ }
+}
+
+fn outcome_from_reply<T>(result: Result<T, ReplyError>) -> ReplyOutcome<T> {
+ 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<T, U>(outcome: ReplyOutcome<T>, map: impl FnOnce(T) -> U) -> ReplyOutcome<U> {
+ 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<String>,
+) -> Option<ParsedWindow> {
+ 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<T>(outcome: ReplyOutcome<T>) -> Option<T> {
+ match outcome {
+ ReplyOutcome::Present(value) => Some(value),
+ ReplyOutcome::Vanished | ReplyOutcome::Missing => None,
+ }
+}
+
+fn resolve_owner_name(
+ pid: Option<u32>,
+ wm_class: Option<String>,
+ proc_name: &impl Fn(u32) -> Option<String>,
+) -> Option<String> {
+ 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<Option<String>>,
+ wm_name: ReplyOutcome<Option<String>>,
+ pid: ReplyOutcome<Option<u32>>,
+ wm_class: ReplyOutcome<Option<String>>,
+ ) -> 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<u32> {
+ 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<u8>) -> 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::<Vec<_>>();
+ 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::<Vec<_>>();
+ 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");
+ }
+}