agentmux_srv/server/streamed_browser/screen/
clipboard.rs1use std::sync::mpsc;
11use std::sync::{Arc, Mutex};
12use std::time::Duration;
13
14use x11rb::connection::{Connection, RequestConnection};
15use x11rb::protocol::xproto::{Atom, AtomEnum, ConnectionExt as _, CreateWindowAux, EventMask, PropMode, SelectionNotifyEvent, SelectionRequestEvent, WindowClass, SELECTION_NOTIFY_EVENT};
16use x11rb::protocol::Event;
17use x11rb::rust_connection::RustConnection;
18use x11rb::wrapper::ConnectionExt as _;
19use x11rb::{COPY_FROM_PARENT, CURRENT_TIME, NONE};
20
21pub const MAX_TEXT: usize = 1024 * 1024;
23pub const OFFER_HOLD: Duration = Duration::from_millis(1500);
25const FETCH_WAIT: Duration = Duration::from_secs(1);
27
28pub struct Atoms {
30 pub clipboard: Atom,
31 pub utf8: Atom,
32 pub targets: Atom,
33 pub plain_utf8: Atom,
34 pub incr: Atom,
35 pub property: Atom,
36}
37
38#[derive(Debug, PartialEq, Eq)]
40pub enum Answer {
41 Targets(Vec<Atom>),
43 Text,
45 Refuse,
47}
48
49pub fn answer(a: &Atoms, target: Atom, offering: bool) -> Answer {
51 if !offering {
52 Answer::Refuse
53 } else if target == a.targets {
54 Answer::Targets(vec![a.targets, a.utf8, a.plain_utf8])
55 } else if target == a.utf8 || target == a.plain_utf8 {
56 Answer::Text
57 } else {
58 Answer::Refuse
59 }
60}
61
62#[derive(Default)]
64struct Offered {
65 text: Option<String>,
66 generation: u64,
67}
68
69impl Offered {
70 fn offer(&mut self, text: String) -> u64 {
71 self.generation += 1;
72 self.text = Some(text);
73 self.generation
74 }
75
76 fn end(&mut self, generation: u64) -> bool {
78 if self.generation != generation || self.text.is_none() {
79 return false;
80 }
81 self.text = None;
82 true
83 }
84}
85
86pub struct Clipboard {
87 conn: Arc<RustConnection>,
88 window: u32,
89 atoms: Arc<Atoms>,
90 offered: Arc<Mutex<Offered>>,
91 reading: Arc<Mutex<Option<mpsc::Sender<bool>>>>,
93}
94
95impl Clipboard {
96 pub fn connect(display: &str) -> Result<Self, String> {
98 let (conn, n) = RustConnection::connect(Some(display)).map_err(|e| format!("cannot reach the virtual screen {display}: {e}"))?;
99 let root = conn.setup().roots[n].root;
100 let window = conn.generate_id().map_err(|e| e.to_string())?;
101 conn.create_window(COPY_FROM_PARENT as u8, window, root, 0, 0, 1, 1, 0, WindowClass::INPUT_ONLY, COPY_FROM_PARENT, &CreateWindowAux::new())
102 .map_err(|e| e.to_string())?
103 .check()
104 .map_err(|e| format!("the clipboard's window could not be made: {e}"))?;
105 let atom = |name: &[u8]| -> Result<Atom, String> {
106 Ok(conn.intern_atom(false, name).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?.atom)
107 };
108 let atoms = Arc::new(Atoms {
109 clipboard: atom(b"CLIPBOARD")?,
110 utf8: atom(b"UTF8_STRING")?,
111 targets: atom(b"TARGETS")?,
112 plain_utf8: atom(b"text/plain;charset=utf-8")?,
113 incr: atom(b"INCR")?,
114 property: atom(b"AGENTMUX_CLIPBOARD")?,
115 });
116 let this = Self { conn: Arc::new(conn), window, atoms, offered: Arc::default(), reading: Arc::default() };
117 this.serve();
118 Ok(this)
119 }
120
121 fn serve(&self) {
123 let (conn, atoms, offered, reading) = (self.conn.clone(), self.atoms.clone(), self.offered.clone(), self.reading.clone());
124 std::thread::spawn(move || loop {
125 let Ok(event) = conn.wait_for_event() else { return };
126 match event {
127 Event::SelectionRequest(r) => {
128 let _ = reply(&conn, &atoms, &offered, &r);
129 }
130 Event::SelectionNotify(n) => {
131 if let Some(tx) = reading.lock().ok().and_then(|mut r| r.take()) {
132 let _ = tx.send(n.property != NONE);
133 }
134 }
135 Event::SelectionClear(_) => {
136 if let Ok(mut o) = offered.lock() {
137 o.text = None;
138 }
139 }
140 _ => {}
141 }
142 });
143 }
144
145 pub fn offer(&self, text: &str) -> Result<u64, String> {
147 if text.len() > MAX_TEXT || text.len() + 100 > self.conn.maximum_request_bytes() {
148 return Err("that paste is too long for the remote browser's clipboard".to_string());
149 }
150 let generation = self.offered.lock().map_err(|_| "the clipboard is busy".to_string())?.offer(text.to_string());
151 self.conn.set_selection_owner(self.window, self.atoms.clipboard, CURRENT_TIME).map_err(|e| e.to_string())?;
152 self.conn.flush().map_err(|e| e.to_string())?;
153 let owner = self.conn.get_selection_owner(self.atoms.clipboard).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?.owner;
154 if owner != self.window {
155 return Err("the remote browser's clipboard could not be taken".to_string());
156 }
157 Ok(generation)
158 }
159
160 pub fn end(&self, generation: u64) {
162 if self.offered.lock().is_ok_and(|mut o| o.end(generation)) {
163 let _ = self.conn.set_selection_owner(NONE, self.atoms.clipboard, CURRENT_TIME);
164 let _ = self.conn.flush();
165 }
166 }
167
168 pub fn fetch(&self) -> Result<Option<String>, String> {
170 let (tx, rx) = mpsc::channel();
171 *self.reading.lock().map_err(|_| "the clipboard is busy".to_string())? = Some(tx);
172 self.conn
173 .convert_selection(self.window, self.atoms.clipboard, self.atoms.utf8, self.atoms.property, CURRENT_TIME)
174 .map_err(|e| e.to_string())?;
175 self.conn.flush().map_err(|e| e.to_string())?;
176 match rx.recv_timeout(FETCH_WAIT) {
177 Ok(true) => {}
178 Ok(false) => return Ok(None),
179 Err(_) => {
180 if let Ok(mut r) = self.reading.lock() {
181 r.take();
182 }
183 return Err("the remote browser did not answer for its clipboard".to_string());
184 }
185 }
186 let got = self
187 .conn
188 .get_property(true, self.window, self.atoms.property, AtomEnum::ANY, 0, (MAX_TEXT / 4 + 1) as u32)
189 .map_err(|e| e.to_string())?
190 .reply()
191 .map_err(|e| e.to_string())?;
192 if got.type_ == self.atoms.incr {
193 return Err("that copy is too long to bring over".to_string());
194 }
195 if got.bytes_after > 0 {
196 return Err("that copy is too long to bring over".to_string());
197 }
198 Ok(String::from_utf8(got.value).ok().filter(|t| !t.is_empty()))
199 }
200}
201
202fn reply(conn: &RustConnection, a: &Atoms, offered: &Mutex<Offered>, r: &SelectionRequestEvent) -> Result<(), String> {
204 let text = offered.lock().ok().and_then(|o| o.text.clone());
205 let property = if r.property == NONE { r.target } else { r.property };
206 let given = if r.selection != a.clipboard {
207 NONE
208 } else {
209 match answer(a, r.target, text.is_some()) {
210 Answer::Targets(list) => {
211 conn.change_property32(PropMode::REPLACE, r.requestor, property, AtomEnum::ATOM, &list).map_err(|e| e.to_string())?;
212 property
213 }
214 Answer::Text => {
215 let text = text.unwrap_or_default();
216 conn.change_property8(PropMode::REPLACE, r.requestor, property, r.target, text.as_bytes()).map_err(|e| e.to_string())?;
217 property
218 }
219 Answer::Refuse => NONE,
220 }
221 };
222 let notify = SelectionNotifyEvent { response_type: SELECTION_NOTIFY_EVENT, sequence: 0, time: r.time, requestor: r.requestor, selection: r.selection, target: r.target, property: given };
223 conn.send_event(false, r.requestor, EventMask::NO_EVENT, notify).map_err(|e| e.to_string())?;
224 conn.flush().map_err(|e| e.to_string())
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230
231 fn atoms() -> Atoms {
232 Atoms { clipboard: 10, utf8: 11, targets: 12, plain_utf8: 13, incr: 14, property: 15 }
233 }
234
235 #[test]
236 fn text_is_given_in_the_kinds_the_browser_asks_for_and_nothing_else() {
237 let a = atoms();
238 assert_eq!(answer(&a, a.utf8, true), Answer::Text);
239 assert_eq!(answer(&a, a.plain_utf8, true), Answer::Text);
240 assert_eq!(answer(&a, a.targets, true), Answer::Targets(vec![12, 11, 13]));
241 assert_eq!(answer(&a, 99, true), Answer::Refuse, "a kind that is not text");
242 }
243
244 #[test]
245 fn nothing_is_given_when_nothing_is_on_offer() {
246 let a = atoms();
247 for target in [a.utf8, a.plain_utf8, a.targets, 99] {
248 assert_eq!(answer(&a, target, false), Answer::Refuse);
249 }
250 }
251
252 #[test]
253 fn an_old_offers_end_does_not_end_a_newer_offer() {
254 let mut o = Offered::default();
255 let first = o.offer("one".to_string());
256 let second = o.offer("two".to_string());
257 assert!(!o.end(first), "the first offer was replaced");
258 assert_eq!(o.text.as_deref(), Some("two"));
259 assert!(o.end(second));
260 assert_eq!(o.text, None);
261 assert!(!o.end(second), "already ended");
262 }
263}