arboard 3.6.1

Image and text handling for the OS clipboard.
Documentation
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::{
	borrow::Cow,
	os::unix::ffi::OsStrExt,
	path::{Path, PathBuf},
	time::Instant,
};

#[cfg(feature = "wayland-data-control")]
use log::{trace, warn};
use percent_encoding::{percent_decode, percent_encode, AsciiSet, CONTROLS};

#[cfg(feature = "image-data")]
use crate::ImageData;
use crate::{common::private, Error};

// Magic strings used in `Set::exclude_from_history()` on linux
const KDE_EXCLUSION_MIME: &str = "x-kde-passwordManagerHint";
const KDE_EXCLUSION_HINT: &[u8] = b"secret";

mod x11;

#[cfg(feature = "wayland-data-control")]
mod wayland;

fn into_unknown<E: std::fmt::Display>(error: E) -> Error {
	Error::Unknown { description: error.to_string() }
}

#[cfg(feature = "image-data")]
fn encode_as_png(image: &ImageData) -> Result<Vec<u8>, Error> {
	use image::ImageEncoder as _;

	if image.bytes.is_empty() || image.width == 0 || image.height == 0 {
		return Err(Error::ConversionFailure);
	}

	let mut png_bytes = Vec::new();
	let encoder = image::codecs::png::PngEncoder::new(&mut png_bytes);
	encoder
		.write_image(
			image.bytes.as_ref(),
			image.width as u32,
			image.height as u32,
			image::ExtendedColorType::Rgba8,
		)
		.map_err(|_| Error::ConversionFailure)?;

	Ok(png_bytes)
}

fn paths_from_uri_list(uri_list: Vec<u8>) -> Vec<PathBuf> {
	uri_list
		.split(|char| *char == b'\n')
		.filter_map(|line| line.strip_prefix(b"file://"))
		.filter_map(|s| percent_decode(s).decode_utf8().ok())
		.map(|decoded| PathBuf::from(decoded.as_ref()))
		.collect()
}

fn paths_to_uri_list(file_list: &[impl AsRef<Path>]) -> Result<String, Error> {
	// The characters that require encoding, which includes £ and € but they can't be added to the set.
	const ASCII_SET: &AsciiSet = &CONTROLS
		.add(b'#')
		.add(b';')
		.add(b'?')
		.add(b'[')
		.add(b']')
		.add(b' ')
		.add(b'\"')
		.add(b'%')
		.add(b'<')
		.add(b'>')
		.add(b'\\')
		.add(b'^')
		.add(b'`')
		.add(b'{')
		.add(b'|')
		.add(b'}');

	file_list
		.iter()
		.filter_map(|path| {
			path.as_ref().canonicalize().ok().map(|path| {
				format!("file://{}", percent_encode(path.as_os_str().as_bytes(), ASCII_SET))
			})
		})
		.reduce(|uri_list, uri| uri_list + "\n" + &uri)
		.ok_or(Error::ConversionFailure)
}

/// Clipboard selection
///
/// Linux has a concept of clipboard "selections" which tend to be used in different contexts. This
/// enum provides a way to get/set to a specific clipboard (the default
/// [`Clipboard`](Self::Clipboard) being used for the common platform API). You can choose which
/// clipboard to use with [`GetExtLinux::clipboard`] and [`SetExtLinux::clipboard`].
///
/// See <https://specifications.freedesktop.org/clipboards-spec/clipboards-0.1.txt> for a better
/// description of the different clipboards.
#[derive(Copy, Clone, Debug)]
pub enum LinuxClipboardKind {
	/// Typically used selection for explicit cut/copy/paste actions (ie. windows/macos like
	/// clipboard behavior)
	Clipboard,

	/// Typically used for mouse selections and/or currently selected text. Accessible via middle
	/// mouse click.
	///
	/// *On Wayland, this may not be available for all systems (requires a compositor supporting
	/// version 2 or above) and operations using this will return an error if unsupported.*
	Primary,

	/// The secondary clipboard is rarely used but theoretically available on X11.
	///
	/// *On Wayland, this is not be available and operations using this variant will return an
	/// error.*
	Secondary,
}

pub(crate) enum Clipboard {
	X11(x11::Clipboard),

	#[cfg(feature = "wayland-data-control")]
	WlDataControl(wayland::Clipboard),
}

impl Clipboard {
	pub(crate) fn new() -> Result<Self, Error> {
		#[cfg(feature = "wayland-data-control")]
		{
			if std::env::var_os("WAYLAND_DISPLAY").is_some() {
				// Wayland is available
				match wayland::Clipboard::new() {
					Ok(clipboard) => {
						trace!("Successfully initialized the Wayland data control clipboard.");
						return Ok(Self::WlDataControl(clipboard));
					}
					Err(e) => warn!(
						"Tried to initialize the wayland data control protocol clipboard, but failed. Falling back to the X11 clipboard protocol. The error was: {}",
						e
					),
				}
			}
		}
		Ok(Self::X11(x11::Clipboard::new()?))
	}
}

pub(crate) struct Get<'clipboard> {
	clipboard: &'clipboard mut Clipboard,
	selection: LinuxClipboardKind,
}

impl<'clipboard> Get<'clipboard> {
	pub(crate) fn new(clipboard: &'clipboard mut Clipboard) -> Self {
		Self { clipboard, selection: LinuxClipboardKind::Clipboard }
	}

	pub(crate) fn text(self) -> Result<String, Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => clipboard.get_text(self.selection),
			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => clipboard.get_text(self.selection),
		}
	}

	#[cfg(feature = "image-data")]
	pub(crate) fn image(self) -> Result<ImageData<'static>, Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => clipboard.get_image(self.selection),
			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => clipboard.get_image(self.selection),
		}
	}

	pub(crate) fn html(self) -> Result<String, Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => clipboard.get_html(self.selection),
			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => clipboard.get_html(self.selection),
		}
	}

	pub(crate) fn file_list(self) -> Result<Vec<PathBuf>, Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => clipboard.get_file_list(self.selection),
			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => clipboard.get_file_list(self.selection),
		}
	}
}

/// Linux-specific extensions to the [`Get`](super::Get) builder.
pub trait GetExtLinux: private::Sealed {
	/// Sets the clipboard the operation will retrieve data from.
	///
	/// If wayland support is enabled and available, attempting to use the Secondary clipboard will
	/// return an error.
	fn clipboard(self, selection: LinuxClipboardKind) -> Self;
}

impl GetExtLinux for crate::Get<'_> {
	fn clipboard(mut self, selection: LinuxClipboardKind) -> Self {
		self.platform.selection = selection;
		self
	}
}

/// Configuration on how long to wait for a new X11 copy event is emitted.
#[derive(Default)]
pub(crate) enum WaitConfig {
	/// Waits until the given [`Instant`] has reached.
	Until(Instant),

	/// Waits forever until a new event is reached.
	Forever,

	/// It shouldn't wait.
	#[default]
	None,
}

pub(crate) struct Set<'clipboard> {
	clipboard: &'clipboard mut Clipboard,
	wait: WaitConfig,
	selection: LinuxClipboardKind,
	exclude_from_history: bool,
}

impl<'clipboard> Set<'clipboard> {
	pub(crate) fn new(clipboard: &'clipboard mut Clipboard) -> Self {
		Self {
			clipboard,
			wait: WaitConfig::default(),
			selection: LinuxClipboardKind::Clipboard,
			exclude_from_history: false,
		}
	}

	pub(crate) fn text(self, text: Cow<'_, str>) -> Result<(), Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => {
				clipboard.set_text(text, self.selection, self.wait, self.exclude_from_history)
			}

			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => {
				clipboard.set_text(text, self.selection, self.wait, self.exclude_from_history)
			}
		}
	}

	pub(crate) fn html(self, html: Cow<'_, str>, alt: Option<Cow<'_, str>>) -> Result<(), Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => {
				clipboard.set_html(html, alt, self.selection, self.wait, self.exclude_from_history)
			}

			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => {
				clipboard.set_html(html, alt, self.selection, self.wait, self.exclude_from_history)
			}
		}
	}

	#[cfg(feature = "image-data")]
	pub(crate) fn image(self, image: ImageData<'_>) -> Result<(), Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => {
				clipboard.set_image(image, self.selection, self.wait, self.exclude_from_history)
			}

			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => {
				clipboard.set_image(image, self.selection, self.wait, self.exclude_from_history)
			}
		}
	}

	pub(crate) fn file_list(self, file_list: &[impl AsRef<Path>]) -> Result<(), Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => clipboard.set_file_list(
				file_list,
				self.selection,
				self.wait,
				self.exclude_from_history,
			),

			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => clipboard.set_file_list(
				file_list,
				self.selection,
				self.wait,
				self.exclude_from_history,
			),
		}
	}
}

/// Linux specific extensions to the [`Set`](super::Set) builder.
pub trait SetExtLinux: private::Sealed {
	/// Whether to wait for the clipboard's contents to be replaced after setting it.
	///
	/// The Wayland and X11 clipboards work by having the clipboard content being, at any given
	/// time, "owned" by a single process, and that process is expected to reply to all the requests
	/// from any other system process that wishes to access the clipboard's contents. As a
	/// consequence, when that process exits the contents of the clipboard will effectively be
	/// cleared since there is no longer anyone around to serve requests for it.
	///
	/// This poses a problem for short-lived programs that just want to copy to the clipboard and
	/// then exit, since they don't want to wait until the user happens to copy something else just
	/// to finish. To resolve that, whenever the user copies something you can offload the actual
	/// work to a newly-spawned daemon process which will run in the background (potentially
	/// outliving the current process) and serve all the requests. That process will then
	/// automatically and silently exit once the user copies something else to their clipboard so it
	/// doesn't take up too many resources.
	///
	/// To support that pattern, this method will not only have the contents of the clipboard be
	/// set, but will also wait and continue to serve requests until the clipboard is overwritten.
	/// As long as you don't exit the current process until that method has returned, you can avoid
	/// all surprising situations where the clipboard's contents seemingly disappear from under your
	/// feet.
	///
	/// See the [daemonize example] for a demo of how you could implement this.
	///
	/// [daemonize example]: https://github.com/1Password/arboard/blob/master/examples/daemonize.rs
	fn wait(self) -> Self;

	/// Whether or not to wait for the clipboard's content to be replaced after setting it. This waits until the
	/// `deadline` has exceeded.
	///
	/// This is useful for short-lived programs so it won't block until new contents on the clipboard
	/// were added.
	///
	/// Note: this is a superset of [`wait()`][SetExtLinux::wait] and will overwrite any state
	/// that was previously set using it.
	fn wait_until(self, deadline: Instant) -> Self;

	/// Sets the clipboard the operation will store its data to.
	///
	/// If wayland support is enabled and available, attempting to use the Secondary clipboard will
	/// return an error.
	///
	/// # Examples
	///
	/// ```
	/// use arboard::{Clipboard, SetExtLinux, LinuxClipboardKind};
	/// # fn main() -> Result<(), arboard::Error> {
	/// let mut ctx = Clipboard::new()?;
	///
	/// let clipboard = "This goes in the traditional (ex. Copy & Paste) clipboard.";
	/// ctx.set().clipboard(LinuxClipboardKind::Clipboard).text(clipboard.to_owned())?;
	///
	/// let primary = "This goes in the primary keyboard. It's typically used via middle mouse click.";
	/// ctx.set().clipboard(LinuxClipboardKind::Primary).text(primary.to_owned())?;
	/// # Ok(())
	/// # }
	/// ```
	fn clipboard(self, selection: LinuxClipboardKind) -> Self;

	/// Excludes the data which will be set on the clipboard from being added to
	/// the desktop clipboard managers' histories by adding the MIME-Type `x-kde-passwordMangagerHint`
	/// to the clipboard's selection data.
	///
	/// This is the most widely adopted convention on Linux.
	fn exclude_from_history(self) -> Self;
}

impl SetExtLinux for crate::Set<'_> {
	fn wait(mut self) -> Self {
		self.platform.wait = WaitConfig::Forever;
		self
	}

	fn clipboard(mut self, selection: LinuxClipboardKind) -> Self {
		self.platform.selection = selection;
		self
	}

	fn wait_until(mut self, deadline: Instant) -> Self {
		self.platform.wait = WaitConfig::Until(deadline);
		self
	}

	fn exclude_from_history(mut self) -> Self {
		self.platform.exclude_from_history = true;
		self
	}
}

pub(crate) struct Clear<'clipboard> {
	clipboard: &'clipboard mut Clipboard,
}

impl<'clipboard> Clear<'clipboard> {
	pub(crate) fn new(clipboard: &'clipboard mut Clipboard) -> Self {
		Self { clipboard }
	}

	pub(crate) fn clear(self) -> Result<(), Error> {
		self.clear_inner(LinuxClipboardKind::Clipboard)
	}

	fn clear_inner(self, selection: LinuxClipboardKind) -> Result<(), Error> {
		match self.clipboard {
			Clipboard::X11(clipboard) => clipboard.clear(selection),
			#[cfg(feature = "wayland-data-control")]
			Clipboard::WlDataControl(clipboard) => clipboard.clear(selection),
		}
	}
}

/// Linux specific extensions to the [Clear] builder.
pub trait ClearExtLinux: private::Sealed {
	/// Performs the "clear" operation on the selected clipboard.
	///
	/// ### Example
	///
	/// ```no_run
	/// # use arboard::{Clipboard, LinuxClipboardKind, ClearExtLinux, Error};
	/// # fn main() -> Result<(), Error> {
	/// let mut clipboard = Clipboard::new()?;
	///
	/// clipboard
	///     .clear_with()
	///     .clipboard(LinuxClipboardKind::Secondary)?;
	/// # Ok(())
	/// # }
	/// ```
	///
	/// If wayland support is enabled and available, attempting to use the Secondary clipboard will
	/// return an error.
	fn clipboard(self, selection: LinuxClipboardKind) -> Result<(), Error>;
}

impl ClearExtLinux for crate::Clear<'_> {
	fn clipboard(self, selection: LinuxClipboardKind) -> Result<(), Error> {
		self.platform.clear_inner(selection)
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_decoding_uri_list() {
		// Test that paths_from_uri_list correctly decodes
		// differents percent encoded characters
		let file_list = [
			"file:///tmp/bar.log",
			"file:///tmp/test%5C.txt",
			"file:///tmp/foo%3F.png",
			"file:///tmp/white%20space.txt",
		];

		let paths = vec![
			PathBuf::from("/tmp/bar.log"),
			PathBuf::from("/tmp/test\\.txt"),
			PathBuf::from("/tmp/foo?.png"),
			PathBuf::from("/tmp/white space.txt"),
		];
		assert_eq!(paths_from_uri_list(file_list.join("\n").into()), paths);
	}
}