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
use std::{
cell::{Cell, RefCell},
collections::HashSet,
ffi::OsString,
io, mem,
os::unix::io::AsRawFd,
rc::Rc,
};
use os_pipe::{pipe, PipeReader};
use wayland_client::{ConnectError, EventQueue};
use wayland_protocols::wlr::unstable::data_control::v1::client::zwlr_data_control_offer_v1::ZwlrDataControlOfferV1;
use crate::{
common::{self, initialize, CommonData},
handlers::{data_device_handler, DataDeviceHandler},
seat_data::SeatData,
utils::is_text,
};
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
pub enum ClipboardType {
Regular,
Primary,
}
impl Default for ClipboardType {
#[inline]
fn default() -> Self {
ClipboardType::Regular
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
pub enum MimeType<'a> {
Any,
Text,
TextWithPriority(&'a str),
Specific(&'a str),
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
pub enum Seat<'a> {
Unspecified,
Specific(&'a str),
}
impl Default for Seat<'_> {
#[inline]
fn default() -> Self {
Seat::Unspecified
}
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("There are no seats")]
NoSeats,
#[error("The clipboard of the requested seat is empty")]
ClipboardEmpty,
#[error("No suitable type of content copied")]
NoMimeType,
#[error("Couldn't connect to the Wayland compositor")]
WaylandConnection(#[source] ConnectError),
#[error("Wayland compositor communication error")]
WaylandCommunication(#[source] io::Error),
#[error("A required Wayland protocol ({} version {}) is not supported by the compositor",
name,
version)]
MissingProtocol { name: &'static str, version: u32 },
#[error("The compositor does not support primary selection")]
PrimarySelectionUnsupported,
#[error("The requested seat was not found")]
SeatNotFound,
#[error("Couldn't create a pipe for content transfer")]
PipeCreation(#[source] io::Error),
}
impl From<common::Error> for Error {
fn from(x: common::Error) -> Self {
use common::Error::*;
match x {
WaylandConnection(err) => Error::WaylandConnection(err),
WaylandCommunication(err) => Error::WaylandCommunication(err),
MissingProtocol { name, version } => Error::MissingProtocol { name, version },
}
}
}
fn get_offer(primary: bool,
seat: Seat<'_>,
socket_name: Option<OsString>)
-> Result<(EventQueue, ZwlrDataControlOfferV1), Error> {
let CommonData { mut queue,
clipboard_manager,
seats, } = initialize(primary, socket_name)?;
if seats.borrow_mut().is_empty() {
return Err(Error::NoSeats);
}
let supports_primary = Rc::new(Cell::new(false));
for seat in &*seats.borrow_mut() {
let mut handler = DataDeviceHandler::new(seat.detach(), primary, supports_primary.clone());
let device = clipboard_manager.get_data_device(seat);
device.quick_assign(move |data_device, event, dispatch_data| {
data_device_handler(&mut handler, data_device, event, dispatch_data)
});
}
queue.sync_roundtrip(&mut (), |_, _, _| {})
.map_err(Error::WaylandCommunication)?;
if primary && !supports_primary.get() {
return Err(Error::PrimarySelectionUnsupported);
}
let offer = seats.borrow_mut()
.iter()
.map(|seat| seat.as_ref().user_data().get::<RefCell<SeatData>>().unwrap().borrow())
.find_map(|data| {
let SeatData { name, offer, .. } = &*data;
match seat {
Seat::Unspecified => return Some(offer.clone()),
Seat::Specific(desired_name) => {
if let Some(name) = name {
if name == desired_name {
return Some(offer.clone());
}
}
}
}
None
});
if offer.is_none() {
return Err(Error::SeatNotFound);
}
offer.unwrap().map(|x| (queue, x)).ok_or(Error::ClipboardEmpty)
}
#[inline]
pub fn get_mime_types(clipboard: ClipboardType, seat: Seat<'_>) -> Result<HashSet<String>, Error> {
get_mime_types_internal(clipboard, seat, None)
}
pub(crate) fn get_mime_types_internal(clipboard: ClipboardType,
seat: Seat<'_>,
socket_name: Option<OsString>)
-> Result<HashSet<String>, Error> {
let primary = clipboard == ClipboardType::Primary;
let (_, offer) = get_offer(primary, seat, socket_name)?;
let mut mime_types = offer.as_ref()
.user_data()
.get::<RefCell<HashSet<String>>>()
.unwrap()
.borrow_mut();
let empty_hash_set = HashSet::new();
Ok(mem::replace(&mut *mime_types, empty_hash_set))
}
#[inline]
pub fn get_contents(clipboard: ClipboardType,
seat: Seat<'_>,
mime_type: MimeType<'_>)
-> Result<(PipeReader, String), Error> {
get_contents_internal(clipboard, seat, mime_type, None)
}
pub(crate) fn get_contents_internal(clipboard: ClipboardType,
seat: Seat<'_>,
mime_type: MimeType<'_>,
socket_name: Option<OsString>)
-> Result<(PipeReader, String), Error> {
let primary = clipboard == ClipboardType::Primary;
let (mut queue, offer) = get_offer(primary, seat, socket_name)?;
let mut mime_types = offer.as_ref()
.user_data()
.get::<RefCell<HashSet<String>>>()
.unwrap()
.borrow_mut();
let mime_type = match mime_type {
MimeType::Any => mime_types.take("text/plain;charset=utf-8")
.or_else(|| mime_types.take("UTF8_STRING"))
.or_else(|| mime_types.iter().find(|x| is_text(x)).cloned())
.or_else(|| mime_types.drain().next()),
MimeType::Text => mime_types.take("text/plain;charset=utf-8")
.or_else(|| mime_types.take("UTF8_STRING"))
.or_else(|| mime_types.drain().find(|x| is_text(x))),
MimeType::TextWithPriority(priority) => mime_types.take(priority)
.or_else(|| mime_types.take("text/plain;charset=utf-8"))
.or_else(|| mime_types.take("UTF8_STRING"))
.or_else(|| mime_types.drain().find(|x| is_text(x))),
MimeType::Specific(mime_type) => mime_types.take(mime_type),
};
if mime_type.is_none() {
return Err(Error::NoMimeType);
}
let mime_type = mime_type.unwrap();
let (read, write) = pipe().map_err(Error::PipeCreation)?;
offer.receive(mime_type.clone(), write.as_raw_fd());
drop(write);
queue.sync_roundtrip(&mut (), |_, _, _| {})
.map_err(Error::WaylandCommunication)?;
Ok((read, mime_type))
}