Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

18.8 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Cua AI, Inc.

//! Wayland-native capture for Hyprland.
//!
//! Identified per-window capture using wayland-client (no grim subprocess).
//!
//! - **Per-window**: `hyprland-toplevel-export-v1` (vendored XML, bindings
//!   generated by wayland-scanner). Copies the toplevel's own buffer, so a
//!   background window captures *its* content even when occluded or on
//!   another workspace — unlike the grim screen-region crop it replaces.
//!   The protocol handle is the `hyprctl clients` window address truncated
//!   to its low 32 bits (Hyprland's `getWindowFromHandle` compares
//!   `ptr & 0xFFFFFFFF`).
//!
//! Frame dispatch is deadline-bounded: `copy` with `ignore_damage=0` waits
//! for window damage and would hang forever on an idle window. Captures use
//! one short-lived connection per call.
//!
//! Caveat (documented in the skill): when Hyprland's
//! `ecosystem:enforce_permissions` is enabled and screencopy is denied,
//! the compositor reports a *successful* capture containing a black
//! "permission denied" frame — there is no failed event to detect.

use std::fs::File;
use std::os::fd::{AsFd, AsRawFd};
use std::os::unix::fs::FileExt;
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use wayland_client::protocol::{
    wl_buffer::WlBuffer,
    wl_callback::{self, WlCallback},
    wl_registry,
    wl_shm::{self, WlShm},
    wl_shm_pool::WlShmPool,
};
use wayland_client::{delegate_noop, Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum};
// ---------------------------------------------------------------------------
// Generated bindings for hyprland-toplevel-export-v1 (vendored XML).
//
// The v2 request `capture_toplevel_with_wlr_toplevel_handle` references
// zwlr_foreign_toplevel_handle_v1, so the wlr foreign_toplevel interfaces
// must be in scope for both the __interfaces module and the outer module.
// ---------------------------------------------------------------------------
pub mod hyprland_toplevel_export {
    #![allow(non_upper_case_globals, non_camel_case_types, missing_docs)]
    use wayland_client;
    use wayland_client::protocol::*;
    use wayland_protocols_wlr::foreign_toplevel::v1::client::*;

    pub mod __interfaces {
        use wayland_client::protocol::__interfaces::*;
        use wayland_protocols_wlr::foreign_toplevel::v1::client::__interfaces::*;
        wayland_scanner::generate_interfaces!("./protocols/hyprland-toplevel-export-v1.xml");
    }
    use self::__interfaces::*;

    wayland_scanner::generate_client_code!("./protocols/hyprland-toplevel-export-v1.xml");
}

use hyprland_toplevel_export::{
    hyprland_toplevel_export_frame_v1::{self, HyprlandToplevelExportFrameV1},
    hyprland_toplevel_export_manager_v1::HyprlandToplevelExportManagerV1,
};

/// Default deadline for buffer-param negotiation and frame copy. Generous
/// enough for a busy compositor, short enough that a recording hook never
/// stalls a tool call noticeably.
const CAPTURE_DEADLINE: Duration = Duration::from_secs(4);
const MAX_FRAME_BYTES: u64 = 256 * 1024 * 1024;

// ---------------------------------------------------------------------------
// Capture state machine shared by both frame protocols.
// ---------------------------------------------------------------------------
#[derive(Debug, Default)]
struct CaptureState {
    shm: Option<WlShm>,
    manager: Option<HyprlandToplevelExportManagerV1>,
    registry_done: bool,
    /// (format, width, height, stride) from the frame's `buffer` event.
    shm_params: Option<(wl_shm::Format, u32, u32, u32)>,
    buffer_done: bool,
    y_invert: bool,
    ready: bool,
    failed: bool,
}

/// A captured frame with tightly packed rows (`width * 4` bytes per row),
/// y-flip already applied. `format` is the wire format: pixel byte order in
/// memory is B,G,R,[A|X] for `?rgb8888` and R,G,B,[A|X] for `?bgr8888`.
pub struct RawFrame {
    pub width: u32,
    pub height: u32,
    pub format: wl_shm::Format,
    pub data: Vec<u8>,
}

impl Dispatch<wl_registry::WlRegistry, ()> for CaptureState {
    fn event(
        state: &mut Self,
        registry: &wl_registry::WlRegistry,
        event: wl_registry::Event,
        _data: &(),
        _conn: &Connection,
        qh: &QueueHandle<Self>,
    ) {
        if let wl_registry::Event::Global {
            name,
            interface,
            version,
        } = event
        {
            if interface == WlShm::interface().name {
                state.shm = Some(registry.bind(name, version.min(1), qh, ()));
            } else if interface == HyprlandToplevelExportManagerV1::interface().name {
                state.manager = Some(registry.bind(name, version.min(2), qh, ()));
            }
        }
    }
}

impl Dispatch<WlCallback, ()> for CaptureState {
    fn event(
        state: &mut Self,
        _: &WlCallback,
        event: wl_callback::Event,
        _: &(),
        _: &Connection,
        _: &QueueHandle<Self>,
    ) {
        if let wl_callback::Event::Done { .. } = event {
            state.registry_done = true;
        }
    }
}

impl Dispatch<HyprlandToplevelExportFrameV1, ()> for CaptureState {
    fn event(
        state: &mut Self,
        _proxy: &HyprlandToplevelExportFrameV1,
        event: hyprland_toplevel_export_frame_v1::Event,
        _data: &(),
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
    ) {
        use hyprland_toplevel_export_frame_v1::Event;
        match event {
            Event::Buffer {
                format: WEnum::Value(format),
                width,
                height,
                stride,
            } => {
                state.shm_params = Some((format, width, height, stride));
            }
            Event::BufferDone => state.buffer_done = true,
            Event::Flags {
                flags: WEnum::Value(flags),
            } => {
                state.y_invert = flags.contains(hyprland_toplevel_export_frame_v1::Flags::YInvert);
            }
            Event::Ready { .. } => state.ready = true,
            Event::Failed => state.failed = true,
            // damage / linux_dmabuf / unknown-enum values are irrelevant
            // for shm capture.
            _ => {}
        }
    }
}

delegate_noop!(CaptureState: ignore WlShm); // advertises `format` events
delegate_noop!(CaptureState: WlShmPool); // no events
delegate_noop!(CaptureState: ignore WlBuffer); // `release` event
delegate_noop!(CaptureState: HyprlandToplevelExportManagerV1); // no events

// ---------------------------------------------------------------------------
// Deadline-bounded dispatch
// ---------------------------------------------------------------------------

/// Dispatch events until `done(state)` or the deadline expires. Equivalent to
/// `blocking_dispatch` but with a hard timeout, so a compositor that never
/// answers (or a damage-gated copy) cannot wedge the recording hook path.
fn dispatch_until(
    queue: &mut EventQueue<CaptureState>,
    state: &mut CaptureState,
    deadline: Instant,
    what: &str,
    done: impl Fn(&CaptureState) -> bool,
) -> Result<()> {
    loop {
        queue
            .dispatch_pending(state)
            .context("wayland dispatch failed")?;
        if done(state) {
            return Ok(());
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            bail!("wayland capture timed out waiting for {what}");
        }
        queue.flush().context("wayland flush failed")?;
        let Some(guard) = queue.prepare_read() else {
            continue; // events already queued — dispatch them
        };
        let fd = guard.connection_fd().as_raw_fd();
        let mut pfd = libc::pollfd {
            fd,
            events: libc::POLLIN,
            revents: 0,
        };
        let timeout_ms = remaining.as_millis().min(i32::MAX as u128) as i32;
        let n = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
        if n < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(err).context("poll on wayland fd failed");
        }
        if n == 0 {
            bail!("wayland capture timed out waiting for {what}");
        }
        match guard.read() {
            Ok(_) => {}
            // Another reader (none in practice — one connection per capture)
            // or a spurious wakeup; loop and retry.
            Err(wayland_client::backend::WaylandError::Io(e))
                if e.kind() == std::io::ErrorKind::WouldBlock => {}
            Err(e) => return Err(e).context("wayland read failed"),
        }
    }
}

// ---------------------------------------------------------------------------
// wl_shm helpers
// ---------------------------------------------------------------------------

/// Anonymous shared-memory file of `len` bytes (memfd, CLOEXEC).
fn create_shm_file(len: u64) -> Result<File> {
    use std::os::fd::FromRawFd;
    let name = std::ffi::CString::new("cua-driver-capture").unwrap();
    let fd = unsafe { libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC) };
    if fd < 0 {
        return Err(std::io::Error::last_os_error()).context("memfd_create failed");
    }
    let file = unsafe { File::from_raw_fd(fd) };
    file.set_len(len).context("ftruncate on memfd failed")?;
    Ok(file)
}

struct ShmBuffer {
    file: File,
    pool: WlShmPool,
    buffer: WlBuffer,
}

impl ShmBuffer {
    fn create(
        shm: &WlShm,
        qh: &QueueHandle<CaptureState>,
        params: (wl_shm::Format, u32, u32, u32),
    ) -> Result<Self> {
        let (format, width, height, stride) = params;
        let len = validated_buffer_len(format, width, height, stride)?;
        let file = create_shm_file(len)?;
        let pool = shm.create_pool(file.as_fd(), len as i32, qh, ());
        let buffer = pool.create_buffer(
            0,
            width as i32,
            height as i32,
            stride as i32,
            format,
            qh,
            (),
        );
        Ok(ShmBuffer { file, pool, buffer })
    }

    fn destroy(self) {
        self.buffer.destroy();
        self.pool.destroy();
    }
}

/// Copy shm rows into a tightly packed buffer, dropping stride padding and
/// un-flipping when the compositor reported y_invert.
fn validated_buffer_len(
    format: wl_shm::Format,
    width: u32,
    height: u32,
    stride: u32,
) -> Result<u64> {
    if !matches!(
        format,
        wl_shm::Format::Argb8888
            | wl_shm::Format::Xrgb8888
            | wl_shm::Format::Abgr8888
            | wl_shm::Format::Xbgr8888
    ) {
        bail!("unsupported wl_shm capture format {format:?}");
    }
    let row_bytes = width.checked_mul(4).context("capture row overflow")?;
    let len = u64::from(stride) * u64::from(height);
    if width == 0
        || height == 0
        || stride < row_bytes
        || stride > i32::MAX as u32
        || width > i32::MAX as u32
        || height > i32::MAX as u32
        || len > MAX_FRAME_BYTES
    {
        bail!("invalid or oversized toplevel buffer parameters");
    }
    Ok(len)
}

fn pack_rows(raw: &[u8], width: u32, height: u32, stride: u32, y_invert: bool) -> Result<Vec<u8>> {
    let len = validated_buffer_len(wl_shm::Format::Argb8888, width, height, stride)?;
    if raw.len() as u64 != len {
        bail!("toplevel buffer length mismatch");
    }
    let row_bytes = width as usize * 4;
    let mut out = Vec::with_capacity(row_bytes * height as usize);
    for y in 0..height as usize {
        let src_y = if y_invert { height as usize - 1 - y } else { y };
        let start = src_y * stride as usize;
        out.extend_from_slice(&raw[start..start + row_bytes]);
    }
    Ok(out)
}

/// Convert a packed frame to RGBA8 in place semantics (returns a new Vec).
/// Returns an error for wl_shm formats outside the four common 32-bit ones.
pub fn frame_to_rgba8(frame: &RawFrame) -> Result<Vec<u8>> {
    let expected = u64::from(frame.width) * u64::from(frame.height) * 4;
    if expected > MAX_FRAME_BYTES || frame.data.len() as u64 != expected {
        bail!("packed frame length mismatch");
    }
    let mut rgba = frame.data.clone();
    match frame.format {
        // Memory order B,G,R,[A|X] — swap to R,G,B,A.
        wl_shm::Format::Argb8888 | wl_shm::Format::Xrgb8888 => {
            let opaque = frame.format == wl_shm::Format::Xrgb8888;
            for px in rgba.chunks_exact_mut(4) {
                px.swap(0, 2);
                if opaque {
                    px[3] = 0xFF;
                }
            }
        }
        // Memory order already R,G,B,[A|X].
        wl_shm::Format::Abgr8888 | wl_shm::Format::Xbgr8888 => {
            if frame.format == wl_shm::Format::Xbgr8888 {
                for px in rgba.chunks_exact_mut(4) {
                    px[3] = 0xFF;
                }
            }
        }
        other => bail!("unsupported wl_shm capture format {other:?}"),
    }
    Ok(rgba)
}

/// The hyprland-toplevel-export protocol handle for a `hyprctl clients`
/// window address: the low 32 bits of the (64-bit) address.
pub fn toplevel_handle(address: u64) -> u32 {
    (address & 0xFFFF_FFFF) as u32
}

// ---------------------------------------------------------------------------
// One-shot per-window capture (hyprland-toplevel-export-v1)
// ---------------------------------------------------------------------------

/// Capture one frame of a Hyprland toplevel by its `hyprctl clients` address.
/// Works for occluded windows and windows on other workspaces — the
/// compositor renders the toplevel's own surface tree into the buffer.
///
/// Fully synchronous; call from a blocking context. Buffer dimensions are
/// physical pixels at the window's render scale (a 1.5x-scaled 800x600
/// window yields a 1200x900 frame).
pub fn capture_toplevel_frame(address: u64, overlay_cursor: bool) -> Result<RawFrame> {
    let conn = super::hyprland::wayland_connection()?;
    super::hyprland::verify_capture_peer(&conn)?;
    let mut queue = conn.new_event_queue::<CaptureState>();
    let qh = queue.handle();
    let mut state = CaptureState::default();
    let deadline = Instant::now() + CAPTURE_DEADLINE;
    let _registry = conn.display().get_registry(&qh, ());
    conn.display().sync(&qh, ());
    dispatch_until(
        &mut queue,
        &mut state,
        deadline,
        "registry enumeration",
        |s| s.registry_done,
    )?;
    let shm = state.shm.clone().context("compositor lacks wl_shm")?;
    let manager = state
        .manager
        .clone()
        .context("compositor lacks Hyprland toplevel export")?;
    let handle = toplevel_handle(address);
    let frame = manager.capture_toplevel(overlay_cursor as i32, handle, &qh, ());

    // Phase 1: buffer params (buffer → buffer_done).
    dispatch_until(
        &mut queue,
        &mut state,
        deadline,
        "toplevel buffer params",
        |s| s.buffer_done || s.failed,
    )?;
    if state.failed {
        frame.destroy();
        bail!("toplevel export failed for window 0x{address:x} (handle 0x{handle:08x})");
    }
    let Some(params) = state.shm_params else {
        frame.destroy();
        bail!("compositor offered no wl_shm buffer params");
    };

    // Phase 2: copy. ignore_damage=1 — with 0 the copy waits for window
    // damage and hangs forever on an idle window.
    let shm_buf = match ShmBuffer::create(&shm, &qh, params) {
        Ok(b) => b,
        Err(e) => {
            frame.destroy();
            return Err(e);
        }
    };
    frame.copy(&shm_buf.buffer, 1);
    let copy_result = dispatch_until(
        &mut queue,
        &mut state,
        deadline,
        "toplevel frame copy",
        |s| s.ready || s.failed,
    );

    frame.destroy();
    let (format, width, height, stride) = params;
    let result = (|| {
        copy_result?;
        if state.failed {
            bail!("toplevel export copy failed for window 0x{address:x}");
        }
        let mut raw = vec![0u8; stride as usize * height as usize];
        shm_buf
            .file
            .read_exact_at(&mut raw, 0)
            .context("read from shm file failed")?;
        Ok(RawFrame {
            width,
            height,
            format,
            data: pack_rows(&raw, width, height, stride, state.y_invert)?,
        })
    })();
    shm_buf.destroy();
    result
}

/// Per-window PNG capture for the screenshot path. Converts to RGBA and
/// encodes with the shared core encoder.
pub fn capture_toplevel_png(address: u64) -> Result<Vec<u8>> {
    let frame = capture_toplevel_frame(address, false)?;
    let rgba = frame_to_rgba8(&frame)?;
    cua_driver_core::image_utils::encode_rgba_to_png(&rgba, frame.width, frame.height)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn toplevel_handle_truncates_to_low_32_bits() {
        // The protocol doc's own example: address d161e7b0 -> 3512854448.
        assert_eq!(toplevel_handle(0xd161e7b0), 3512854448);
        // Full 64-bit heap pointer keeps only the low word.
        assert_eq!(toplevel_handle(0x56226558b1d0), 0x6558b1d0);
        assert_eq!(toplevel_handle(0xFFFF_FFFF_0000_0001), 1);
    }

    #[test]
    fn pack_rows_drops_stride_padding() {
        // 2x2 frame, stride 12 (4 bytes padding per row).
        let raw: Vec<u8> = vec![
            1, 1, 1, 1, 2, 2, 2, 2, 99, 99, 99, 99, // row 0 + pad
            3, 3, 3, 3, 4, 4, 4, 4, 99, 99, 99, 99, // row 1 + pad
        ];
        let packed = pack_rows(&raw, 2, 2, 12, false).unwrap();
        assert_eq!(packed, vec![1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]);
    }

    #[test]
    fn pack_rows_unflips_y_invert() {
        let raw: Vec<u8> = vec![
            1, 1, 1, 1, // row 0
            2, 2, 2, 2, // row 1
        ];
        let packed = pack_rows(&raw, 1, 2, 4, true).unwrap();
        assert_eq!(packed, vec![2, 2, 2, 2, 1, 1, 1, 1]);
    }

    #[test]
    fn frame_to_rgba8_swaps_bgr_and_forces_alpha() {
        let frame = RawFrame {
            width: 1,
            height: 1,
            format: wl_shm::Format::Xrgb8888,
            data: vec![0x10, 0x20, 0x30, 0x00], // B,G,R,X
        };
        assert_eq!(
            frame_to_rgba8(&frame).unwrap(),
            vec![0x30, 0x20, 0x10, 0xFF]
        );

        let frame = RawFrame {
            width: 1,
            height: 1,
            format: wl_shm::Format::Abgr8888,
            data: vec![0x10, 0x20, 0x30, 0x77], // already R,G,B,A
        };
        assert_eq!(
            frame_to_rgba8(&frame).unwrap(),
            vec![0x10, 0x20, 0x30, 0x77]
        );
    }

    #[test]
    fn invalid_buffer_sizes_and_formats_refuse_before_allocation() {
        assert!(validated_buffer_len(wl_shm::Format::Argb8888, 800, 600, 16).is_err());
        assert!(validated_buffer_len(wl_shm::Format::Argb8888, u32::MAX, 1, u32::MAX).is_err());
        assert!(validated_buffer_len(wl_shm::Format::Argb8888, 8192, 8193, 32768).is_err());
        assert!(validated_buffer_len(wl_shm::Format::Rgb565, 800, 600, 1600).is_err());
        assert!(pack_rows(&[0; 4], 2, 1, 8, false).is_err());
    }
}