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
use std::{
cell::{Cell, RefCell},
ffi::{CString, OsString},
io,
os::unix::io::RawFd,
process::abort,
rc::Rc,
};
use libc::{STDIN_FILENO, STDOUT_FILENO};
use nix::{
fcntl::{fcntl, FcntlArg, OFlag},
sys::wait::{waitpid, WaitStatus},
unistd::{close, dup2, execv, fork, ForkResult},
};
use wayland_client::{
global_filter, protocol::wl_seat::WlSeat, ConnectError, Display, GlobalError, GlobalManager, Interface, Main,
};
use wayland_protocols::wlr::unstable::data_control::v1::client::zwlr_data_control_manager_v1::ZwlrDataControlManagerV1;
use crate::{
handlers::{data_device_handler, seat_handler, DataDeviceHandler},
seat_data::SeatData,
};
pub fn is_text(mime_type: &str) -> bool {
match mime_type {
"TEXT" | "STRING" | "UTF8_STRING" => true,
x if x.starts_with("text/") => true,
_ => false,
}
}
#[derive(thiserror::Error, Debug)]
pub enum CopyDataError {
#[error("Couldn't set the source file descriptor flags")]
SetSourceFdFlags(#[source] nix::Error),
#[error("Couldn't set the target file descriptor flags")]
SetTargetFdFlags(#[source] nix::Error),
#[error("Couldn't fork")]
Fork(#[source] nix::Error),
#[error("Couldn't close the source file descriptor")]
CloseSourceFd(#[source] nix::Error),
#[error("Couldn't close the target file descriptor")]
CloseTargetFd(#[source] nix::Error),
#[error("Couldn't wait for the child process")]
Wait(#[source] nix::Error),
#[error("Received an unexpected status when waiting for the child process: {:?}", _0)]
WaitUnexpected(WaitStatus),
#[error("The child process exited with a non-zero error code: {}", _0)]
ChildError(i32),
}
#[allow(unsafe_code)]
pub fn copy_data(from_fd: Option<RawFd>, to_fd: RawFd, wait: bool) -> Result<(), CopyDataError> {
if let Some(from_fd) = from_fd {
fcntl(from_fd, FcntlArg::F_SETFL(OFlag::empty())).map_err(CopyDataError::SetSourceFdFlags)?;
}
fcntl(to_fd, FcntlArg::F_SETFL(OFlag::empty())).map_err(CopyDataError::SetTargetFdFlags)?;
let bin_env = CString::new("/usr/bin/env").unwrap();
let env = CString::new("env").unwrap();
let cat = CString::new("cat").unwrap();
let fork_result = unsafe { fork() }.map_err(CopyDataError::Fork)?;
match fork_result {
ForkResult::Child => {
if let Some(fd) = from_fd {
if dup2(fd, STDIN_FILENO).is_err() {
abort();
}
}
if dup2(to_fd, STDOUT_FILENO).is_err() {
abort();
}
if let Some(fd) = from_fd {
if close(fd).is_err() {
abort();
}
}
if close(to_fd).is_err() {
abort();
}
if execv(&bin_env, &[&env, &cat]).is_err() {
abort();
}
}
ForkResult::Parent { child } => {
if let Some(fd) = from_fd {
close(fd).map_err(CopyDataError::CloseSourceFd)?;
}
close(to_fd).map_err(CopyDataError::CloseTargetFd)?;
if wait {
match waitpid(child, None).map_err(CopyDataError::Wait)? {
WaitStatus::Exited(_, status) => {
if status != 0 {
return Err(CopyDataError::ChildError(status));
}
}
x => return Err(CopyDataError::WaitUnexpected(x)),
}
}
}
}
Ok(())
}
#[derive(thiserror::Error, Debug)]
pub enum PrimarySelectionCheckError {
#[error("There are no seats")]
NoSeats,
#[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 },
}
#[inline]
pub fn is_primary_selection_supported() -> Result<bool, PrimarySelectionCheckError> {
is_primary_selection_supported_internal(None)
}
pub(crate) fn is_primary_selection_supported_internal(socket_name: Option<OsString>)
-> Result<bool, PrimarySelectionCheckError> {
let display = match socket_name {
Some(name) => Display::connect_to_name(name),
None => Display::connect_to_env(),
}.map_err(PrimarySelectionCheckError::WaylandConnection)?;
let mut queue = display.create_event_queue();
let display = display.attach(queue.token());
let seats = Rc::new(RefCell::new(Vec::<Main<WlSeat>>::new()));
let seats_2 = seats.clone();
let global_manager =
GlobalManager::new_with_cb(&display,
global_filter!([WlSeat, 2, move |seat: Main<WlSeat>, _: DispatchData| {
let seat_data = RefCell::new(SeatData::default());
seat.as_ref().user_data().set(move || seat_data);
seat.quick_assign(seat_handler);
seats_2.borrow_mut().push(seat);
}]));
queue.sync_roundtrip(&mut (), |_, _, _| {})
.map_err(PrimarySelectionCheckError::WaylandCommunication)?;
let clipboard_manager = match global_manager.instantiate_exact::<ZwlrDataControlManagerV1>(2) {
Ok(manager) => manager,
Err(GlobalError::Missing) => {
return Err(PrimarySelectionCheckError::MissingProtocol { name: ZwlrDataControlManagerV1::NAME,
version: 1 })
}
Err(GlobalError::VersionTooLow(_)) => return Ok(false),
};
if seats.borrow_mut().is_empty() {
return Err(PrimarySelectionCheckError::NoSeats);
}
let supports_primary = Rc::new(Cell::new(false));
for seat in &*seats.borrow_mut() {
let mut handler = DataDeviceHandler::new(seat.detach(), true, 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(PrimarySelectionCheckError::WaylandCommunication)?;
Ok(supports_primary.get())
}