Skip to main content

agentmux_srv/server/streamed_browser/screen/
x.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The virtual X screen: its pixels read out, and pointer and key events sent to it at screen level (the XTEST extension: the same
5//! events a person's mouse and keyboard make). Nothing here attaches to the browser; the browser is a program on a screen.
6
7use std::sync::atomic::{AtomicBool, AtomicU16, AtomicUsize, Ordering};
8use std::sync::Arc;
9
10use x11rb::connection::Connection;
11use x11rb::protocol::damage::{ConnectionExt as _, ReportLevel};
12use x11rb::protocol::Event;
13use x11rb::protocol::xproto::{ChangeWindowAttributesAux, ConnectionExt as _, EventMask, ImageFormat, MapState, BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, KEY_PRESS_EVENT, KEY_RELEASE_EVENT, MOTION_NOTIFY_EVENT};
14use x11rb::protocol::xtest::ConnectionExt as _;
15use x11rb::rust_connection::RustConnection;
16
17use super::frames::Rect;
18
19pub struct Screen {
20    pub(super) conn: RustConnection,
21    pub(super) root: u32,
22    /// The screen's size now: it changes when the screen is resized (`resize`, or another connection's, which `follow_size` hears of).
23    w: AtomicU16,
24    h: AtomicU16,
25    /// Set when the screen's size changed under this connection; read (and cleared) by `take_resized`.
26    resized: AtomicBool,
27    /// How many windows have opened (after the browser's first), counted by the thread that watches the screen's windows. Text being typed
28    /// stops when it changes, so what is left of a paste does not go to a window the person has not seen.
29    pub opened: Arc<AtomicUsize>,
30}
31
32impl Screen {
33    /// Connect to display `display` (`:12`).
34    pub fn connect(display: &str) -> Result<Self, String> {
35        let (conn, n) = RustConnection::connect(Some(display)).map_err(|e| format!("cannot reach the virtual screen {display}: {e}"))?;
36        let s = &conn.setup().roots[n];
37        let (root, w, h) = (s.root, s.width_in_pixels, s.height_in_pixels);
38        Ok(Self { conn, root, w: AtomicU16::new(w), h: AtomicU16::new(h), resized: AtomicBool::new(false), opened: Arc::default() })
39    }
40
41    /// The screen's width and height now.
42    pub fn size(&self) -> (u16, u16) {
43        (self.w.load(Ordering::SeqCst), self.h.load(Ordering::SeqCst))
44    }
45
46    pub(super) fn set_size(&self, w: u16, h: u16) {
47        self.w.store(w, Ordering::SeqCst);
48        self.h.store(h, Ordering::SeqCst);
49    }
50
51    /// Ask for the screen's own events (its size changing), so a resize made by another connection is known here. Needed by whoever reads the screen.
52    pub fn follow_size(&self) -> Result<(), String> {
53        let attrs = ChangeWindowAttributesAux::new().event_mask(EventMask::STRUCTURE_NOTIFY);
54        self.conn.change_window_attributes(self.root, &attrs).map_err(|e| e.to_string())?.check().map_err(|e| format!("the screen's size could not be followed: {e}"))
55    }
56
57    /// Read the screen's size from the screen itself (a read of it failed: it may have changed size under this connection). True when it differs.
58    pub fn refresh_size(&self) -> bool {
59        let Ok(g) = self.conn.get_geometry(self.root).map_err(|e| e.to_string()).and_then(|c| c.reply().map_err(|e| e.to_string())) else { return false };
60        if self.size() == (g.width, g.height) {
61            return false;
62        }
63        self.set_size(g.width, g.height);
64        self.resized.store(true, Ordering::SeqCst);
65        true
66    }
67
68    /// True once if the screen changed size since the last call.
69    pub fn take_resized(&self) -> bool {
70        self.resized.swap(false, Ordering::SeqCst)
71    }
72
73    /// The whole screen: four bytes a pixel (blue, green, red, one unused), row after row.
74    pub fn grab(&self) -> Result<Vec<u8>, String> {
75        let (w, h) = self.size();
76        let reply = self
77            .conn
78            .get_image(ImageFormat::Z_PIXMAP, self.root, 0, 0, w, h, u32::MAX)
79            .map_err(|e| e.to_string())?
80            .reply()
81            .map_err(|e| format!("the screen could not be read: {e}"))?;
82        Ok(reply.data)
83    }
84
85    /// A part of the screen, as `grab` gives the whole of it.
86    pub fn grab_rect(&self, at: Rect) -> Result<Vec<u8>, String> {
87        let reply = self
88            .conn
89            .get_image(ImageFormat::Z_PIXMAP, self.root, at.x as i16, at.y as i16, at.w, at.h, u32::MAX)
90            .map_err(|e| e.to_string())?
91            .reply()
92            .map_err(|e| format!("the screen could not be read: {e}"))?;
93        Ok(reply.data)
94    }
95
96    /// Ask the screen to say which part of it changed (the damage extension), so the screen is read when it changed and only where. The
97    /// answer is the damage's id, for `clear_damage`.
98    pub fn watch_damage(&self) -> Result<u32, String> {
99        self.conn.damage_query_version(1, 1).map_err(|e| e.to_string())?.reply().map_err(|e| format!("the screen has no damage extension: {e}"))?;
100        let id = self.conn.generate_id().map_err(|e| e.to_string())?;
101        self.conn.damage_create(id, self.root, ReportLevel::RAW_RECTANGLES).map_err(|e| e.to_string())?.check().map_err(|e| format!("the screen's changes could not be followed: {e}"))?;
102        Ok(id)
103    }
104
105    /// Wait until some part of the screen changes, and say which part (cut to the screen); none when the screen changed size (see
106    /// `take_resized`: all of it is new). An error when the screen has gone.
107    pub fn wait_damage(&self) -> Result<Option<Rect>, String> {
108        loop {
109            let event = self.conn.wait_for_event().map_err(|e| format!("the screen has gone: {e}"))?;
110            if let Some(at) = self.damaged(&event) {
111                return Ok(Some(at));
112            }
113            if self.resized.load(Ordering::SeqCst) {
114                return Ok(None);
115            }
116        }
117    }
118
119    /// The parts that changed since the last look, as one rectangle that holds them all; none when nothing did.
120    pub fn take_damage(&self) -> Result<Option<Rect>, String> {
121        let mut all: Option<Rect> = None;
122        while let Some(event) = self.conn.poll_for_event().map_err(|e| format!("the screen has gone: {e}"))? {
123            if let Some(at) = self.damaged(&event) {
124                all = Some(all.map_or(at, |a| a.union(at)));
125            }
126        }
127        Ok(all)
128    }
129
130    /// Tell the screen the changes so far are taken in (it forgets the region it has kept for them).
131    pub fn clear_damage(&self, id: u32) -> Result<(), String> {
132        self.conn.damage_subtract(id, x11rb::NONE, x11rb::NONE).map_err(|e| e.to_string())?;
133        self.conn.flush().map_err(|e| e.to_string())
134    }
135
136    fn damaged(&self, event: &Event) -> Option<Rect> {
137        match event {
138            Event::DamageNotify(d) => {
139                let (w, h) = self.size();
140                Rect::clipped(d.area.x, d.area.y, d.area.width, d.area.height, w, h)
141            }
142            Event::ConfigureNotify(c) if c.window == self.root => {
143                if self.size() != (c.width, c.height) {
144                    self.set_size(c.width, c.height);
145                    self.resized.store(true, Ordering::SeqCst);
146                }
147                None
148            }
149            _ => None,
150        }
151    }
152
153    /// How many top-level windows a person would see: shown, not a menu or tooltip (override-redirect), and bigger than 100 by 100.
154    pub fn visible_windows(&self) -> Result<usize, String> {
155        let tree = self.conn.query_tree(self.root).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?;
156        let mut shown = 0;
157        for window in tree.children {
158            let Ok(attrs) = self.conn.get_window_attributes(window).map_err(|e| e.to_string())?.reply() else { continue };
159            if attrs.map_state != MapState::VIEWABLE || attrs.override_redirect {
160                continue;
161            }
162            if let Ok(geometry) = self.conn.get_geometry(window).map_err(|e| e.to_string())?.reply() {
163                if geometry.width >= 100 && geometry.height >= 100 {
164                    shown += 1;
165                }
166            }
167        }
168        Ok(shown)
169    }
170
171    /// Ask the screen to say when a top-level window is mapped, unmapped or destroyed (events on the root window), so a window opening is known
172    /// at the moment it opens and not at the next look.
173    pub fn follow_windows(&self) -> Result<(), String> {
174        let attrs = ChangeWindowAttributesAux::new().event_mask(EventMask::SUBSTRUCTURE_NOTIFY);
175        self.conn.change_window_attributes(self.root, &attrs).map_err(|e| e.to_string())?.check().map_err(|e| format!("the screen's window events could not be followed: {e}"))
176    }
177
178    /// Wait for the next event about a top-level window (after `follow_windows`). An error when the screen has gone.
179    pub fn next_window_event(&self) -> Result<(), String> {
180        self.conn.wait_for_event().map(|_| ()).map_err(|e| format!("the screen has gone: {e}"))
181    }
182
183    fn fake(&self, kind: u8, detail: u8, x: i16, y: i16) -> Result<(), String> {
184        self.conn.xtest_fake_input(kind, detail, 0, self.root, x, y, 0).map_err(|e| e.to_string())?;
185        self.conn.flush().map_err(|e| e.to_string())
186    }
187
188    pub fn move_to(&self, x: f64, y: f64) -> Result<(), String> {
189        let (w, h) = self.size();
190        let (x, y) = (x.round().clamp(0.0, f64::from(w) - 1.0) as i16, y.round().clamp(0.0, f64::from(h) - 1.0) as i16);
191        self.fake(MOTION_NOTIFY_EVENT, 0, x, y)
192    }
193
194    /// Button 1 left, 2 middle, 3 right, 4 and 5 wheel up and down, 6 and 7 wheel left and right.
195    pub fn button(&self, button: u8, down: bool) -> Result<(), String> {
196        self.fake(if down { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, button, 0, 0)
197    }
198
199    pub fn key(&self, keycode: u8, down: bool) -> Result<(), String> {
200        self.fake(if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT }, keycode, 0, 0)
201    }
202}