1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use std::net::SocketAddr;
use std::time::Duration;
use anyhow::{anyhow, bail, Context, Result};
use tokio::{sync::watch, task, time};
use tracing::{debug, trace, warn};
use x11rb_async::connection::Connection;
use x11rb_async::protocol::xproto::{Atom, AtomEnum, ConnectionExt, Property, Time};
use x11rb_async::protocol::{xfixes, Event};
use x11rb_async::x11_utils::TryParse;
use crate::x11clipboard::{convert, shared};
/// Task that listens for updates to the clipboard types (local cut or copy).
/// Sends out an event when an update occurs, indicating a new clipboard is available.
pub struct ClipboardTypeWatcher {
context: shared::XContext,
atoms: shared::Atoms,
}
impl ClipboardTypeWatcher {
pub async fn start(types_tx: watch::Sender<Vec<String>>) -> Result<()> {
// Fail up-front if context can't be created at least once
let mut watcher = new_watcher().await?;
task::spawn(async move {
loop {
match watcher.types_wait().await {
Ok(types) => {
// We should only announce clipboard events from other applications.
// If we announce our own type updates, then something like this will happen:
// - we get advertised types pushed from server/client
// - we store the advertised types to X11 for future pastes into other applications
// - we see the update and think that another application took over the clipboard
if types.is_empty()
|| types.contains(&shared::NIKAU_REMOTE_TARGET.to_string())
{
debug!(
"Ignoring clipboard update that's empty or from nikau itself: {:?}",
types
);
continue;
}
debug!(
"Received updated clipboard from local system with types: {:?}",
types
);
if let Err(e) = types_tx.send(types) {
warn!("Failed to send updated clipboard types: {}", e);
}
}
Err(e) => {
warn!("Failed to wait for new clipboard types: {}", e);
// This can happen if the context is lost (e.g. WM crash?). Try to create a new context.
match new_watcher().await {
Ok(w) => {
watcher = w;
}
Err(e) => {
warn!("Failed to init new watcher: {}", e);
}
}
}
}
}
});
Ok(())
}
async fn types_wait(&mut self) -> Result<Vec<String>> {
let buf = self.read_wait(self.atoms.targets).await?;
let mut atom_names = Vec::new();
for atom in to_atoms(&buf)? {
atom_names.push(self.atoms.get_name(&self.context.conn, atom).await?);
}
Ok(atom_names)
}
async fn read_wait(&self, target: Atom) -> Result<Vec<u8>> {
let screen = &self
.context
.conn
.setup()
.roots
.get(self.context.screen)
.ok_or(anyhow!("xcb connection error: invalid screen"))?;
xfixes::query_version(&self.context.conn, 5, 0).await?;
xfixes::select_selection_input(
&self.context.conn,
screen.root,
self.atoms.clipboard,
xfixes::SelectionEventMask::default(),
)
.await?;
xfixes::select_selection_input(
&self.context.conn,
screen.root,
self.atoms.clipboard,
xfixes::SelectionEventMask::SET_SELECTION_OWNER
| xfixes::SelectionEventMask::SELECTION_CLIENT_CLOSE
| xfixes::SelectionEventMask::SELECTION_WINDOW_DESTROY,
)
.await?
.check()
.await?;
let mut buf = Vec::new();
process_event(
&self.context,
&self.atoms,
&mut buf,
0,
target,
self.atoms.recv_clipboard,
)
.await?;
self.context
.conn
.delete_property(self.context.window, self.atoms.recv_clipboard)
.await?
.check()
.await?;
Ok(buf)
}
}
async fn new_watcher() -> Result<ClipboardTypeWatcher> {
let context = shared::XContext::new()
.await
.context("Failed to set up X11 API context")?;
let atoms = shared::Atoms::new(&context.conn).await?;
Ok(ClipboardTypeWatcher { context, atoms })
}
pub struct ClipboardReader {
context: shared::XContext,
atoms: shared::Atoms,
}
impl ClipboardReader {
pub async fn new() -> Result<Self> {
let context = shared::XContext::new()
.await
.context("Failed to set up X11 API context")?;
let atoms = shared::Atoms::new(&context.conn)
.await
.context("Failed to set up X11 Atoms storage")?;
Ok(Self { context, atoms })
}
/// Reads the clipboard data for the specified type.
/// The result may be converted/compressed to a different type for network transfer, see ret.1.
pub async fn read(
&mut self,
requested_type: &str,
max_size_bytes: u64,
request_client: &Option<SocketAddr>,
) -> Result<(Vec<u8>, Option<String>)> {
debug!(
"Reading local clipboard content as requested by {}: requested_type={} max_size_bytes={}",
if let Some(c) = request_client {
format!("client {}", c)
} else {
"server".to_string()
},
requested_type,
max_size_bytes
);
let type_atom = self
.atoms
.get_atom(&self.context.conn, requested_type)
.await?;
self.context
.conn
.convert_selection(
self.context.window,
self.atoms.clipboard,
type_atom,
self.atoms.recv_clipboard,
Time::CURRENT_TIME,
)
.await?
.check()
.await?;
let mut buf = Vec::new();
// If there's a bug in clipboard state management, retrieval can get stuck forever.
// So just in case let's avoid waiting forever here.
match time::timeout(
Duration::from_secs(shared::CLIPBOARD_TIMEOUT_SECS),
process_event(
&self.context,
&self.atoms,
&mut buf,
max_size_bytes,
type_atom,
self.atoms.recv_clipboard,
),
)
.await
{
Ok(Ok(())) => {}
Ok(Err(e)) => {
bail!("X11 clipboard read failed: {:?}", e);
}
Err(_e) => {
warn!(
"X11 clipboard read timed out after {}s",
shared::CLIPBOARD_TIMEOUT_SECS
);
buf.clear();
// Continue below, try to clear the status
}
}
self.context
.conn
.delete_property(self.context.window, self.atoms.recv_clipboard)
.await?
.check()
.await?;
convert::read(buf, max_size_bytes, requested_type).await
}
}
async fn process_event(
context: &shared::XContext,
atoms: &shared::Atoms,
buf: &mut Vec<u8>,
max_size_bytes: u64,
target: Atom,
property: Atom,
) -> Result<()> {
let mut is_incr = false;
loop {
let event = context.conn.wait_for_event().await?;
trace!("X11 reader event: {:?}", event);
match event {
Event::XfixesSelectionNotify(event) => {
context
.conn
.convert_selection(
context.window,
atoms.clipboard,
target,
property,
event.timestamp,
)
.await?
.check()
.await?;
}
Event::SelectionNotify(event) => {
if event.selection != atoms.clipboard {
continue;
}
if event.property == Atom::from(AtomEnum::NONE) {
break;
}
let reply = context
.conn
.get_property(
false,
context.window,
event.property,
AtomEnum::NONE,
// Fetch data as of this offset
buf.len() as u32,
u32::MAX,
)
.await?
.reply()
.await?;
if reply.type_ == atoms.incr {
if let Some(mut value) = reply.value32() {
if let Some(size) = value.next() {
buf.reserve(size as usize);
}
}
context
.conn
.delete_property(context.window, property)
.await?
.check()
.await?;
is_incr = true;
continue;
}
buf.extend_from_slice(&reply.value);
break;
}
Event::PropertyNotify(event) if is_incr => {
if event.state != Property::NEW_VALUE {
continue;
};
let length = context
.conn
.get_property(false, context.window, property, AtomEnum::NONE, 0, 0)
.await?
.reply()
.await?
.bytes_after;
let reply = context
.conn
.get_property(true, context.window, property, AtomEnum::NONE, 0, length)
.await?
.reply()
.await?;
if reply.type_ != target {
continue;
};
if reply.value.is_empty() {
// End of data
break;
}
if max_size_bytes > 0 && (buf.len() + reply.value.len()) > max_size_bytes as usize {
// When this happens, we still need to send _something_ back,
// so that the receiving client (and its WM) can stop waiting.
// So let's just send back a zero-byte clipboard, which isn't great but probably won't hurt.
warn!(
"Sending empty clipboard data: size read so far ({}) exceeds max={}",
buf.len() + reply.value.len(),
max_size_bytes
);
buf.clear();
break;
}
buf.extend_from_slice(&reply.value);
}
_ => (),
}
}
Ok(())
}
fn to_atoms(buf: &Vec<u8>) -> Result<Vec<Atom>> {
if buf.len() % 4 != 0 {
bail!("Expected u32s, but buf.len={}", buf.len());
}
let mut atoms: Vec<Atom> = Vec::new();
let mut next = buf.as_slice();
loop {
if next.is_empty() {
break;
}
if let Ok((atom, remaining)) = Atom::try_parse(next) {
atoms.push(atom);
next = remaining;
} else {
break;
}
}
Ok(atoms)
}