From 3f66f9a7bec3a2121e5fab55ca8f203ba83410ec Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:49 +0100 Subject: [PATCH] capri-ui: add x11 module --- crates/capri-ui/src/x11.rs | 177 +++++++++++++++++++++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 crates/capri-ui/src/x11.rs diff --git a/crates/capri-ui/src/x11.rs b/crates/capri-ui/src/x11.rs new file mode 100644 index 0000000..94adaac --- /dev/null +++ b/crates/capri-ui/src/x11.rs @@ -0,0 +1,177 @@ +//! X11 plumbing for Capri's own windows (i3, and KDE Plasma through XWayland): EWMH states, +//! input shapes for click-through, stacking, pointer, and the EWMH window list +//! used as the docking fallback. All coordinates are X11 root pixels. +use anyhow::{Context, Result}; +use raw_window_handle::{HasWindowHandle, RawWindowHandle}; +use x11rb::connection::Connection; +use x11rb::protocol::randr::ConnectionExt as _; +use x11rb::protocol::shape::{ConnectionExt as _, SK, SO}; +use x11rb::protocol::xproto::{AtomEnum, ClientMessageEvent, ClipOrdering, ConfigureWindowAux, ConnectionExt, EventMask, Rectangle, StackMode, Window}; +use x11rb::rust_connection::RustConnection; + +pub struct X11 { + conn: RustConnection, + root: Window, +} + +/// A rectangle in root pixels. +pub type Px = [i32; 4]; + +pub struct ClientWindow { + pub id: u32, + pub pid: u32, + pub title: String, + /// Frame rectangle (decorations included). + pub rect: Px, +} + +pub fn window_id(frame: &eframe::Frame) -> Option { + match frame.window_handle().ok()?.as_raw() { + RawWindowHandle::Xlib(h) => Some(h.window as u32), + RawWindowHandle::Xcb(h) => Some(h.window.get()), + _ => None, + } +} + +impl X11 { + pub fn connect() -> Result { + let (conn, screen) = x11rb::connect(None).context("X11 connection")?; + let root = conn.setup().roots[screen].root; + Ok(Self { conn, root }) + } + + fn atom(&self, name: &str) -> Result { + Ok(self.conn.intern_atom(false, name.as_bytes())?.reply()?.atom) + } + + fn prop32(&self, window: Window, name: &str) -> Vec { + let Ok(atom) = self.atom(name) else { return vec![] }; + self.conn + .get_property(false, window, atom, AtomEnum::ANY, 0, 4096) + .ok() + .and_then(|c| c.reply().ok()) + .and_then(|r| r.value32().map(|v| v.collect())) + .unwrap_or_default() + } + + fn text(&self, window: Window, name: &str) -> Option { + let atom = self.atom(name).ok()?; + let reply = self.conn.get_property(false, window, atom, AtomEnum::ANY, 0, 1024).ok()?.reply().ok()?; + Some(String::from_utf8_lossy(&reply.value).into_owned()) + } + + fn state(&self, window: Window, add: bool, first: &str, second: &str) -> Result<()> { + let event = ClientMessageEvent::new(32, window, self.atom("_NET_WM_STATE")?, [add as u32, self.atom(first)?, self.atom(second)?, 1, 0]); + self.conn.send_event(false, self.root, EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY, event)?; + Ok(()) + } + + /// Out of the taskbar and pager, on every desktop, and above others when `above`. + /// winit requests these before mapping, which KWin and i3 ignore, so they are sent again. + pub fn pin(&self, window: Window, above: bool) -> Result<()> { + self.state(window, true, "_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_STATE_SKIP_PAGER")?; + self.state(window, true, "_NET_WM_STATE_STICKY", "_NET_WM_STATE_STICKY")?; + self.state(window, above, "_NET_WM_STATE_ABOVE", "_NET_WM_STATE_ABOVE")?; + // "All desktops" is desktop 0xFFFFFFFF for KWin and i3. + let desktop = ClientMessageEvent::new(32, window, self.atom("_NET_WM_DESKTOP")?, [0xFFFF_FFFF, 1, 0, 0, 0]); + self.conn.send_event(false, self.root, EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY, desktop)?; + self.conn.flush()?; + Ok(()) + } + + /// Clicks pass through everything outside `rects` (window-relative pixels). + pub fn set_input(&self, window: Window, rects: &[Px]) -> Result<()> { + let rects: Vec = rects + .iter() + .filter(|r| r[2] > 0 && r[3] > 0) + .map(|r| Rectangle { x: r[0].clamp(-32768, 32767) as i16, y: r[1].clamp(-32768, 32767) as i16, width: r[2].min(65535) as u16, height: r[3].min(65535) as u16 }) + .collect(); + self.conn.shape_rectangles(SO::SET, SK::INPUT, ClipOrdering::UNSORTED, window, 0, 0, &rects)?; + self.conn.flush()?; + Ok(()) + } + + /// Keeps an overlay above managed windows without focusing it. + pub fn raise(&self, window: Window) { + let _ = self.conn.configure_window(window, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE)); + let _ = self.conn.flush(); + } + + /// One of our own windows (immediate viewports expose no handle) by exact title and our PID. + pub fn find_own(&self, title: &str) -> Option { + let pid = std::process::id(); + let mut stack = vec![(self.root, 0)]; + while let Some((window, depth)) = stack.pop() { + if window != self.root && self.prop32(window, "_NET_WM_PID").first() == Some(&pid) && self.text(window, "_NET_WM_NAME").as_deref() == Some(title) { + return Some(window); + } + if depth < 3 + && let Some(tree) = self.conn.query_tree(window).ok().and_then(|c| c.reply().ok()) + { + stack.extend(tree.children.into_iter().map(|c| (c, depth + 1))); + } + } + None + } + + /// Global pointer. On KDE Wayland this is only right while the pointer is over an X11 window. + pub fn pointer(&self) -> Option<(i32, i32)> { + let r = self.conn.query_pointer(self.root).ok()?.reply().ok()?; + Some((r.root_x as i32, r.root_y as i32)) + } + + /// RandR monitors, with the EWMH work area clipped to each (one rectangle for all outputs). + pub fn displays(&self) -> Vec<(Px, Px)> { + let monitors = self.conn.randr_get_monitors(self.root, true).ok().and_then(|c| c.reply().ok()).map(|r| r.monitors).unwrap_or_default(); + let work = self.prop32(self.root, "_NET_WORKAREA"); + monitors + .iter() + .map(|m| { + let b = [m.x as i32, m.y as i32, m.width as i32, m.height as i32]; + let w = if work.len() >= 4 { intersect(b, [work[0] as i32, work[1] as i32, work[2] as i32, work[3] as i32]).unwrap_or(b) } else { b }; + (b, w) + }) + .collect() + } + + /// Managed windows on the current desktop, top-most first (EWMH, i.e. XWayland windows only on KDE). + pub fn client_windows(&self) -> Vec { + let current = self.prop32(self.root, "_NET_CURRENT_DESKTOP").first().copied(); + let hidden = self.atom("_NET_WM_STATE_HIDDEN").ok(); + let mut list = self.prop32(self.root, "_NET_CLIENT_LIST_STACKING"); + list.reverse(); + list.into_iter() + .filter_map(|id| { + let desktop = self.prop32(id, "_NET_WM_DESKTOP").first().copied(); + if desktop.is_some_and(|d| d != 0xFFFF_FFFF && Some(d) != current) || self.prop32(id, "_NET_WM_STATE").iter().any(|a| Some(*a) == hidden) { + return None; + } + let g = self.conn.get_geometry(id).ok()?.reply().ok()?; + let t = self.conn.translate_coordinates(id, self.root, 0, 0).ok()?.reply().ok()?; + let e = self.prop32(id, "_NET_FRAME_EXTENTS"); + let [l, r, top, b] = if e.len() == 4 { [e[0], e[1], e[2], e[3]].map(|v| v as i32) } else { [0; 4] }; + Some(ClientWindow { + id, + pid: self.prop32(id, "_NET_WM_PID").first().copied().unwrap_or(0), + title: self.text(id, "_NET_WM_NAME").or_else(|| self.text(id, "WM_NAME")).unwrap_or_default(), + rect: [t.dst_x as i32 - l, t.dst_y as i32 - top, g.width as i32 + l + r, g.height as i32 + top + b], + }) + }) + .collect() + } + + pub fn pid_of(&self, window: Window) -> u32 { + self.prop32(window, "_NET_WM_PID").first().copied().unwrap_or(0) + } + + /// i3's IPC socket path (root property `I3_SOCKET_PATH`). + pub fn i3_socket(&self) -> Option { + self.text(self.root, "I3_SOCKET_PATH").filter(|s| !s.is_empty()) + } +} + +pub fn intersect(a: Px, b: Px) -> Option { + let (x0, y0) = (a[0].max(b[0]), a[1].max(b[1])); + let (x1, y1) = ((a[0] + a[2]).min(b[0] + b[2]), (a[1] + a[3]).min(b[1] + b[3])); + (x1 > x0 && y1 > y0).then_some([x0, y0, x1 - x0, y1 - y0]) +}