capri-perception: add capture module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent bc76ff5cfa
commit 39a8a94e4b
1 file changed
+203
+203
View File
@@ -0,0 +1,203 @@
//! Pixel capture backends. Callers must hold an owner grant
//! (`CapturePolicy`) or an active computer-control session: nothing here checks consent.
//!
//! KDE: KWin `ScreenShot2` (`CaptureScreen`/`CaptureWindow`, raw pixels over a pipe). KWin only
//! answers executables whose installed `.desktop` file declares
//! `X-KDE-DBUS-Restricted-Interfaces=org.kde.KWin.ScreenShot2`; that is why `capri_linux/capture.py`
//! used Spectacle (a Python interpreter cannot be authorized). The Rust binary can be, see
//! [`kwin_desktop_entry`]; until then output captures fall back to Spectacle + crop.
//! i3/X11: `GetImage` on the root window (outputs) or the window drawable.
use std::collections::HashMap;
use std::io::Read;
use std::os::fd::{AsFd, FromRawFd, OwnedFd};
use std::time::Duration;
use anyhow::{anyhow, bail, ensure, Context, Result};
use async_trait::async_trait;
use image::RgbImage;
use x11rb::connection::Connection as _;
use x11rb::protocol::xproto::{ConnectionExt, ImageFormat};
use zbus::zvariant::{Fd, OwnedValue, Value};
use crate::imaging::{self, Rect};
use crate::platform::{Desktop, DesktopState, DesktopWindow, Output};
#[async_trait]
pub trait Capturer: Send + Sync {
/// Pixel-free window/output listing.
async fn state(&self) -> Result<DesktopState>;
async fn window(&self, w: &DesktopWindow) -> Result<RgbImage>;
/// `native`: physical resolution (clips); otherwise logical size is fine.
async fn output(&self, o: &Output, native: bool) -> Result<RgbImage>;
}
#[async_trait]
impl Capturer for Desktop {
async fn state(&self) -> Result<DesktopState> {
Desktop::state(self, false).await
}
async fn window(&self, w: &DesktopWindow) -> Result<RgbImage> {
match self {
Desktop::Kde(k) => screenshot2(k.connection(), "CaptureWindow", &w.native, false, true).await,
Desktop::X11(x) => {
let id: u32 = w.native.parse()?;
let g = x.conn.get_geometry(id)?.reply()?;
x11_image(&x.conn, id, Rect { x: 0, y: 0, width: g.width as u32, height: g.height as u32 })
}
}
}
async fn output(&self, o: &Output, native: bool) -> Result<RgbImage> {
match self {
Desktop::Kde(k) => match screenshot2(k.connection(), "CaptureScreen", &o.name, native, false).await {
Ok(img) => Ok(img),
Err(e) => {
tracing::debug!("ScreenShot2 unavailable, using Spectacle: {e}");
let state = Desktop::state(self, false).await?;
spectacle(&state, o).await
}
},
Desktop::X11(x) => x11_image(&x.conn, x.root, o.rect),
}
}
}
fn pipe() -> Result<(OwnedFd, OwnedFd)> {
let mut fds = [0; 2];
// SAFETY: pipe2 fills two new descriptors we immediately own.
if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) } != 0 {
bail!("Cannot create capture pipe");
}
Ok(unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) })
}
async fn screenshot2(conn: &zbus::Connection, method: &str, target: &str, native: bool, window: bool) -> Result<RgbImage> {
let (read, write) = pipe()?;
let reader = tokio::task::spawn_blocking(move || -> Result<Vec<u8>> {
let mut data = Vec::new();
std::fs::File::from(read).take(16384 * 16384 * 4 + 1).read_to_end(&mut data)?;
Ok(data)
});
let mut options: HashMap<&str, Value> = HashMap::new();
options.insert("include-cursor", Value::from(false));
options.insert("native-resolution", Value::from(native));
if window {
options.insert("include-decoration", Value::from(true));
}
let reply = {
let args = (target, options, Fd::from(write.as_fd()));
let call = conn.call_method(Some("org.kde.KWin"), "/org/kde/KWin/ScreenShot2", Some("org.kde.KWin.ScreenShot2"), method, &args);
tokio::time::timeout(Duration::from_secs(12), call).await.context("KWin capture timed out")?
};
drop(write);
let reply: HashMap<String, OwnedValue> = reply.context("KDE has not authorized Capri to capture windows")?.body().deserialize()?;
let data = tokio::time::timeout(Duration::from_secs(12), reader).await.context("KWin capture timed out")???;
let num = |k: &str| reply.get(k).and_then(|v| v.downcast_ref::<u32>().ok()).ok_or_else(|| anyhow!("KWin capture result lacks {k}"));
imaging::decode_raw(num("format")?, num("width")?, num("height")?, num("stride")?, &data)
}
fn x11_image(conn: &x11rb::rust_connection::RustConnection, drawable: u32, r: Rect) -> Result<RgbImage> {
ensure!(r.width > 0 && r.height > 0 && r.width <= 16384 && r.height <= 16384, "Display exceeds limits");
let reply = conn.get_image(ImageFormat::Z_PIXMAP, drawable, r.x as i16, r.y as i16, r.width as u16, r.height as u16, !0)?.reply().context("The window is not visible")?;
let bpp = conn.setup().pixmap_formats.iter().find(|f| f.depth == reply.depth).map(|f| f.bits_per_pixel);
ensure!(bpp == Some(32), "Unsupported X11 pixel depth");
imaging::decode_bgrx(r.width, r.height, &reply.data)
}
/// Spectacle full-desktop capture cropped to one output.
async fn spectacle(state: &DesktopState, o: &Output) -> Result<RgbImage> {
let dir = std::env::var_os("XDG_RUNTIME_DIR").map(std::path::PathBuf::from).unwrap_or_else(std::env::temp_dir);
let path = dir.join(format!("capri-capture-{}.png", uuid::Uuid::new_v4()));
let status = tokio::time::timeout(
Duration::from_secs(12),
tokio::process::Command::new("spectacle").args(["--background", "--nonotify", "--fullscreen", "--output"]).arg(&path).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true).status(),
)
.await;
let image = std::fs::read(&path);
let _ = std::fs::remove_file(&path);
ensure!(matches!(status, Ok(Ok(s)) if s.success()), "The desktop could not be captured");
let full = image::load_from_memory_with_format(&image?, image::ImageFormat::Png)?.to_rgb8();
let bounds = state.desktop_bounds().ok_or_else(|| anyhow!("No active display."))?;
let (sx, sy) = (full.width() as f64 / bounds.width as f64, full.height() as f64 / bounds.height as f64);
let (x, y) = (((o.rect.x - bounds.x) as f64 * sx).round() as u32, ((o.rect.y - bounds.y) as f64 * sy).round() as u32);
let (w, h) = ((o.rect.width as f64 * sx).round() as u32, (o.rect.height as f64 * sy).round() as u32);
ensure!(x + w <= full.width() && y + h <= full.height(), "Capture geometry differs from its image");
Ok(image::imageops::crop_imm(&full, x, y, w, h).to_image())
}
/// The `.desktop` entry that authorizes the Capri binary for KWin ScreenShot2.
/// Install as `~/.local/share/applications/capri.desktop`; `Exec` must be the running binary.
pub fn kwin_desktop_entry(exe: &std::path::Path) -> String {
format!(
"[Desktop Entry]\nType=Application\nName=Capri\nExec={}\nIcon=capri\nStartupWMClass=capri\nX-KDE-DBUS-Restricted-Interfaces=org.kde.KWin.ScreenShot2\n",
exe.display()
)
}
/// The monitor holding the foreground window, at the size of its desktop bounds:
/// used by clips and computer control. Returns the image and its bounds.
pub async fn active_display(desktop: &dyn Capturer) -> Result<(RgbImage, Rect)> {
let state = desktop.state().await?;
let output = state.active().and_then(|w| state.output_of(w)).or(state.outputs.first()).cloned().ok_or_else(|| anyhow!("No active display."))?;
let r = output.rect;
ensure!(r.width > 0 && r.height > 0 && r.width <= 16384 && r.height <= 16384 && r.width as u64 * r.height as u64 <= 40_000_000, "Display exceeds limits");
let mut image = desktop.output(&output, true).await?;
if image.dimensions() != (r.width, r.height) {
image = image::imageops::resize(&image, r.width, r.height, image::imageops::FilterType::Lanczos3);
}
Ok((image, r))
}
/// Native target of an owner-selected source.
#[derive(Clone, Debug, PartialEq)]
pub enum NativeSource {
Window(DesktopWindow),
Output(Output),
/// 2..=8 outputs sorted by y, x.
Outputs(Vec<Output>),
}
/// One frame of a source, scaled to at most 1280x720 (monitor sets: mosaic).
pub async fn frame(capturer: &dyn Capturer, source: &NativeSource) -> Result<RgbImage> {
Ok(match source {
NativeSource::Window(w) => imaging::fit(&capturer.window(w).await?, 1280, 720),
NativeSource::Output(o) => imaging::fit(&capturer.output(o, false).await?, 1280, 720),
NativeSource::Outputs(list) => {
let mut tiles = Vec::new();
for o in list {
tiles.push(imaging::fit(&capturer.output(o, false).await?, 1280, 800));
}
imaging::mosaic(&tiles)?
}
})
}
#[cfg(test)]
mod tests {
use super::*;
struct Fake;
#[async_trait]
impl Capturer for Fake {
async fn state(&self) -> Result<DesktopState> {
Ok(DesktopState::default())
}
async fn window(&self, _: &DesktopWindow) -> Result<RgbImage> {
Ok(RgbImage::new(2000, 1000))
}
async fn output(&self, o: &Output, _: bool) -> Result<RgbImage> {
Ok(RgbImage::new(o.rect.width, o.rect.height))
}
}
#[tokio::test]
async fn frames_are_bounded() {
let w = frame(&Fake, &NativeSource::Window(DesktopWindow::default())).await.unwrap();
assert_eq!(w.dimensions(), (1280, 640));
let o = |x| Output { name: format!("O{x}"), rect: Rect { x, y: 0, width: 1920, height: 1080 } };
let m = frame(&Fake, &NativeSource::Outputs(vec![o(0), o(1920)])).await.unwrap();
assert!(m.width() == 1280 && m.height() <= 720);
assert!(kwin_desktop_entry(std::path::Path::new("/usr/bin/capri")).contains("Exec=/usr/bin/capri\n"));
}
}