agentmux_srv/server/streamed_browser/screen/
x.rs1use 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 w: AtomicU16,
24 h: AtomicU16,
25 resized: AtomicBool,
27 pub opened: Arc<AtomicUsize>,
30}
31
32impl Screen {
33 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 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 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 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 pub fn take_resized(&self) -> bool {
70 self.resized.swap(false, Ordering::SeqCst)
71 }
72
73 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 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 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 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 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 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 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 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 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 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}