1#![cfg_attr(
2 test,
3 allow(
4 clippy::disallowed_methods,
5 reason = "in a test these are the assertion, not a hazard"
6 )
7)]
8
9use std::sync::{Mutex, OnceLock};
27
28mod caps;
29pub use caps::{Availability, Feature, Unsupported, availability, available};
30
31pub mod conformance;
32pub mod events;
33#[cfg(any(unix, windows))]
36pub mod service;
37
38#[cfg(any(unix, windows))]
39mod images;
40#[cfg(any(target_os = "linux", target_os = "macos", windows))]
41mod native;
42#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
43mod web;
44
45pub const MAX_CLIPBOARD_HTML_BYTES: usize = 1024 * 1024;
46
47pub const MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES: usize = 1024 * 1024;
49
50#[derive(Clone, PartialEq, Eq)]
54pub struct RichTextOffer {
55 pub html: String,
56 pub plain: Option<String>,
57}
58
59impl RichTextOffer {
60 #[must_use]
61 pub fn is_valid(&self) -> bool {
62 !self.html.is_empty()
63 && self.html.len() <= MAX_CLIPBOARD_HTML_BYTES
64 && self
65 .plain
66 .as_ref()
67 .is_none_or(|plain| plain.len() <= MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES)
68 }
69}
70
71impl std::fmt::Debug for RichTextOffer {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 f.debug_struct("RichTextOffer")
74 .field("html_bytes", &self.html.len())
75 .field("plain_bytes", &self.plain.as_ref().map(String::len))
76 .finish()
77 }
78}
79
80pub const SECRET_MIME: &str = "application/x-tilo-secret";
84
85pub const PASSWORD_MANAGER_HINT_MIME: &str = "x-kde-passwordManagerHint";
89
90pub const SECRET_MARKER: &[u8] = b"secret";
91
92pub const MAX_CLIPBOARD_IMAGE_BYTES: usize = 8 * 1024 * 1024;
93
94pub const MAX_CLIPBOARD_IMAGE_INPUT_BYTES: usize = 64 * 1024 * 1024;
95
96pub const MAX_PASTED_IMAGE_BYTES: usize = 32 * 1024 * 1024;
97
98pub const PASTED_IMAGE_TYPES: [&str; 3] = ["image/png", "image/jpeg", "image/webp"];
99
100#[derive(Clone, PartialEq, Eq)]
101pub struct ClipboardImage {
102 pub mime: &'static str,
103 pub bytes: Vec<u8>,
105}
106
107impl std::fmt::Debug for ClipboardImage {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 f.debug_struct("ClipboardImage")
110 .field("mime", &self.mime)
111 .field("len", &self.bytes.len())
112 .finish()
113 }
114}
115
116pub fn preferred_image_type<'a>(
117 offered: impl IntoIterator<Item = &'a str>,
118) -> Option<&'static str> {
119 let offered: Vec<&str> = offered.into_iter().collect();
120 PASTED_IMAGE_TYPES
121 .into_iter()
122 .find(|mime| offered.contains(mime))
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum ClipboardTarget {
127 Clipboard,
128 Primary,
133}
134
135pub trait ClipboardBackend: Send + Sync {
142 fn set_text(&self, target: ClipboardTarget, text: &str) -> bool;
143
144 fn text(&self, target: ClipboardTarget) -> Option<String>;
147
148 fn request_text(&self, target: ClipboardTarget) -> std::sync::mpsc::Receiver<Option<String>> {
152 let (reply, result) = std::sync::mpsc::channel();
153 let _ = reply.send(self.text(target));
154 result
155 }
156
157 fn rich_text(&self) -> Option<RichTextOffer> {
163 None
164 }
165
166 fn set_rich_text(&self, html: &str, plain: &str) -> bool {
174 let _ = html;
175 self.set_text(ClipboardTarget::Clipboard, plain)
176 }
177
178 fn set_image(&self, width: usize, height: usize, rgba: &[u8]) -> bool {
181 let _ = (width, height, rgba);
182 false
183 }
184
185 fn image(&self) -> Option<ClipboardImage> {
189 None
190 }
191
192 fn set_shared_text(&self, target: ClipboardTarget, text: &str) -> bool {
198 self.set_text(target, text)
199 }
200
201 fn set_secret_text(&self, text: &str) -> bool {
211 let _ = text;
212 false
213 }
214
215 fn copy(&self, content: CopyContent<'_>) -> ClipboardCopy {
223 copy_now(self, content)
224 }
225
226 fn reserve_text(&self) -> Option<ReservedCopy> {
233 None
234 }
235
236 fn name(&self) -> &'static str;
237}
238
239fn copy_now<B: ClipboardBackend + ?Sized>(backend: &B, content: CopyContent<'_>) -> ClipboardCopy {
240 ClipboardCopy::settled(match content {
241 CopyContent::Text(text) => backend.set_text(ClipboardTarget::Clipboard, text),
242 CopyContent::SharedText(text) => backend.set_shared_text(ClipboardTarget::Clipboard, text),
243 CopyContent::SecretText(text) => backend.set_secret_text(text),
244 CopyContent::Rich { html, plain } => backend.set_rich_text(html, plain),
245 CopyContent::Image {
246 width,
247 height,
248 rgba,
249 } => backend.set_image(width, height, rgba),
250 })
251}
252
253#[derive(Clone, Copy)]
256pub enum CopyContent<'a> {
257 Text(&'a str),
258 SharedText(&'a str),
261 SecretText(&'a str),
262 Rich {
265 html: &'a str,
266 plain: &'a str,
267 },
268 Image {
270 width: usize,
271 height: usize,
272 rgba: &'a [u8],
273 },
274}
275
276impl std::fmt::Debug for CopyContent<'_> {
277 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 match self {
280 Self::Text(text) => f.debug_tuple("Text").field(&text.len()).finish(),
281 Self::SharedText(text) => f.debug_tuple("SharedText").field(&text.len()).finish(),
282 Self::SecretText(_) => f.write_str("SecretText"),
283 Self::Rich { html, plain } => f
284 .debug_struct("Rich")
285 .field("html", &html.len())
286 .field("plain", &plain.len())
287 .finish(),
288 Self::Image { width, height, .. } => f
289 .debug_struct("Image")
290 .field("width", width)
291 .field("height", height)
292 .finish(),
293 }
294 }
295}
296
297#[derive(Clone)]
302#[must_use = "a copy can fail after it returns; read its outcome"]
303pub struct ClipboardCopy {
304 state: std::sync::Arc<CopyState>,
305}
306
307struct CopyState {
308 progress: Mutex<CopyProgress>,
309 settled: std::sync::Condvar,
310 wake: tilo_rt::wake::WakeHandle,
311}
312
313#[derive(Default)]
314struct CopyProgress {
315 outcome: Option<bool>,
316 then: Vec<Box<dyn FnOnce(bool) + Send>>,
317}
318
319impl CopyState {
320 fn progress(&self) -> std::sync::MutexGuard<'_, CopyProgress> {
321 self.progress
322 .lock()
323 .unwrap_or_else(std::sync::PoisonError::into_inner)
324 }
325}
326
327impl ClipboardCopy {
328 pub fn settled(copied: bool) -> Self {
329 let (copy, settle) = Self::pending();
330 settle.settle(copied);
331 copy
332 }
333
334 pub fn pending() -> (Self, CopySettler) {
335 let state = std::sync::Arc::new(CopyState {
336 progress: Mutex::default(),
337 settled: std::sync::Condvar::new(),
338 wake: tilo_rt::wake::WakeHandle::new(),
339 });
340 (
341 Self {
342 state: std::sync::Arc::clone(&state),
343 },
344 CopySettler { state: Some(state) },
345 )
346 }
347
348 #[must_use]
349 pub fn outcome(&self) -> Option<bool> {
350 self.state.progress().outcome
351 }
352
353 pub fn on_settled(&self, then: impl FnOnce(bool) + Send + 'static) {
354 let mut progress = self.state.progress();
355 match progress.outcome {
356 Some(copied) => {
357 drop(progress);
358 then(copied);
359 }
360 None => progress.then.push(Box::new(then)),
361 }
362 }
363
364 #[must_use]
368 pub fn wait(&self) -> bool {
369 let mut progress = self.state.progress();
370 loop {
371 if let Some(copied) = progress.outcome {
372 return copied;
373 }
374 progress = self
375 .state
376 .settled
377 .wait(progress)
378 .unwrap_or_else(std::sync::PoisonError::into_inner);
379 }
380 }
381}
382
383impl std::fmt::Debug for ClipboardCopy {
384 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385 f.debug_tuple("ClipboardCopy")
386 .field(&self.outcome())
387 .finish()
388 }
389}
390
391pub struct CopySettler {
394 state: Option<std::sync::Arc<CopyState>>,
395}
396
397impl CopySettler {
398 pub fn settle(mut self, copied: bool) {
399 self.finish(copied);
400 }
401
402 fn finish(&mut self, copied: bool) {
403 if let Some(state) = self.state.take() {
404 let then = {
405 let mut progress = state.progress();
406 progress.outcome = Some(copied);
407 std::mem::take(&mut progress.then)
408 };
409 state.settled.notify_all();
410 for then in then {
411 then(copied);
412 }
413 state.wake.wake();
414 }
415 }
416}
417
418impl Drop for CopySettler {
419 fn drop(&mut self) {
420 self.finish(false);
421 }
422}
423
424#[must_use = "dropping a reserved copy gives it up"]
425pub struct ReservedCopy {
426 fill: Option<Fill>,
427}
428
429type Fill = Box<dyn FnOnce(Option<&str>) -> ClipboardCopy + Send>;
430
431impl ReservedCopy {
432 pub fn new(fill: impl FnOnce(Option<&str>) -> ClipboardCopy + Send + 'static) -> Self {
433 Self {
434 fill: Some(Box::new(fill)),
435 }
436 }
437
438 pub fn fill(mut self, text: &str) -> ClipboardCopy {
439 self.fill
440 .take()
441 .map_or_else(|| ClipboardCopy::settled(false), |fill| fill(Some(text)))
442 }
443}
444
445impl Drop for ReservedCopy {
446 fn drop(&mut self) {
447 if let Some(fill) = self.fill.take() {
448 let _ = fill(None);
449 }
450 }
451}
452
453impl std::fmt::Debug for ReservedCopy {
454 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
455 f.write_str("ReservedCopy")
456 }
457}
458
459pub fn system() -> std::sync::Arc<dyn ClipboardBackend> {
463 static SYSTEM: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
464 SYSTEM.get_or_init(backend).clone()
465}
466
467#[cfg(all(unix, not(all(target_arch = "wasm32", target_os = "unknown"))))]
468fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
469 service::ServiceClipboard::from_env().map_or_else(unavailable, |clipboard| {
470 std::sync::Arc::new(clipboard) as std::sync::Arc<dyn ClipboardBackend>
471 })
472}
473
474#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
475fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
476 std::sync::Arc::new(web::BrowserClipboard)
477}
478
479#[cfg(windows)]
480fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
481 os()
482}
483
484#[cfg(not(any(unix, windows, all(target_arch = "wasm32", target_os = "unknown"))))]
485fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
486 unavailable()
487}
488
489pub fn unavailable() -> std::sync::Arc<dyn ClipboardBackend> {
492 std::sync::Arc::new(Nowhere)
493}
494
495pub fn is_unavailable(backend: &dyn ClipboardBackend) -> bool {
498 backend.name() == Nowhere.name()
499}
500
501pub fn os() -> std::sync::Arc<dyn ClipboardBackend> {
509 #[cfg(any(target_os = "linux", target_os = "macos", windows))]
510 {
511 static OS: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
512 OS.get_or_init(|| std::sync::Arc::new(native::NativeClipboard::default()))
513 .clone()
514 }
515 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
516 {
517 unavailable()
518 }
519}
520
521pub fn warn_fallback_once(op: &str) {
526 static WARNED: OnceLock<()> = OnceLock::new();
527 WARNED.get_or_init(|| {
528 tracing::warn!(
529 target: "tilo_ui::clipboard",
530 operation = op,
531 "no system clipboard: falling back to an in-process buffer. Copy and paste \
532 will work inside this process and silently do nothing between processes. \
533 On Wayland this means the compositor offers neither \
534 zwlr_data_control_manager_v1 nor ext_data_control_v1 and no X11 (XWayland) \
535 clipboard is reachable either."
536 );
537 });
538}
539
540struct Nowhere;
541
542impl ClipboardBackend for Nowhere {
543 fn set_text(&self, _target: ClipboardTarget, _text: &str) -> bool {
544 false
545 }
546
547 fn text(&self, _target: ClipboardTarget) -> Option<String> {
548 None
549 }
550
551 fn name(&self) -> &'static str {
552 "unavailable"
553 }
554}
555
556#[derive(Debug, Default)]
563pub struct InProcessClipboard {
564 clipboard: Mutex<Option<String>>,
565 primary: Mutex<Option<String>>,
566 rich: Mutex<Option<String>>,
567}
568
569impl InProcessClipboard {
570 fn slot(&self, target: ClipboardTarget) -> &Mutex<Option<String>> {
571 match target {
572 ClipboardTarget::Clipboard => &self.clipboard,
573 ClipboardTarget::Primary => &self.primary,
574 }
575 }
576}
577
578impl ClipboardBackend for InProcessClipboard {
579 fn set_text(&self, target: ClipboardTarget, text: &str) -> bool {
580 let Ok(mut slot) = self.slot(target).lock() else {
581 return false;
582 };
583 *slot = Some(text.to_string());
584 if target == ClipboardTarget::Clipboard
585 && let Ok(mut rich) = self.rich.lock()
586 {
587 *rich = None;
588 }
589 true
590 }
591
592 fn text(&self, target: ClipboardTarget) -> Option<String> {
593 self.slot(target).lock().ok()?.clone()
594 }
595
596 fn set_rich_text(&self, html: &str, plain: &str) -> bool {
597 if !self.set_text(ClipboardTarget::Clipboard, plain) {
598 return false;
599 }
600 let Ok(mut rich) = self.rich.lock() else {
601 return false;
602 };
603 *rich = Some(html.to_owned());
604 true
605 }
606
607 fn rich_text(&self) -> Option<RichTextOffer> {
608 let html = self.rich.lock().ok()?.clone()?;
609 let plain = self.text(ClipboardTarget::Clipboard);
610 Some(RichTextOffer { html, plain }).filter(RichTextOffer::is_valid)
611 }
612
613 fn set_shared_text(&self, _target: ClipboardTarget, _text: &str) -> bool {
614 false
615 }
616
617 fn name(&self) -> &'static str {
618 "in-process"
619 }
620}
621
622#[cfg(test)]
623pub(crate) mod tests {
624 use super::*;
625
626 pub(crate) static SYSTEM: Mutex<()> = Mutex::new(());
628
629 #[test]
630 fn a_copy_settles_once_and_runs_what_waits_on_it() {
631 let (copy, settler) = ClipboardCopy::pending();
632 let (ran, outcomes) = std::sync::mpsc::channel();
633 let early = ran.clone();
634 copy.on_settled(move |copied| early.send(("before", copied)).unwrap());
635 assert_eq!(copy.outcome(), None);
636 assert!(
637 outcomes.try_recv().is_err(),
638 "nothing runs before it settles"
639 );
640 settler.settle(true);
641 assert_eq!(copy.outcome(), Some(true));
642 assert!(copy.wait());
643 copy.on_settled(move |copied| ran.send(("after", copied)).unwrap());
644 assert_eq!(
645 outcomes.try_iter().collect::<Vec<_>>(),
646 [("before", true), ("after", true)]
647 );
648
649 let (copy, settler) = ClipboardCopy::pending();
650 drop(settler);
651 assert_eq!(copy.outcome(), Some(false), "an abandoned copy failed");
652 }
653
654 #[test]
655 fn the_in_process_clipboard_keeps_text_inside_the_process() {
656 let clipboard = InProcessClipboard::default();
657 assert!(clipboard.set_text(ClipboardTarget::Clipboard, "local"));
658 assert_eq!(
659 clipboard.text(ClipboardTarget::Clipboard).as_deref(),
660 Some("local")
661 );
662 assert!(clipboard.set_rich_text("<b>bold</b>", "bold"));
663 assert_eq!(
664 clipboard.rich_text().map(|offer| offer.plain),
665 Some(Some("bold".to_owned()))
666 );
667 assert!(
668 !clipboard.set_shared_text(ClipboardTarget::Clipboard, "shared"),
669 "an in-process buffer does not claim a shared copy"
670 );
671 assert!(
672 !clipboard.set_secret_text("secret"),
673 "an in-process buffer does not claim a secret copy"
674 );
675 assert!(!clipboard.set_image(1, 1, &[0, 0, 0, 0]));
676 assert!(clipboard.image().is_none());
677 }
678
679 #[test]
680 fn a_process_handed_no_connection_holds_and_takes_nothing() {
681 let nowhere = unavailable();
682 assert!(!nowhere.set_text(ClipboardTarget::Clipboard, "lost"));
683 assert_eq!(nowhere.text(ClipboardTarget::Clipboard), None);
684 assert!(!nowhere.set_shared_text(ClipboardTarget::Clipboard, "lost"));
685 assert!(!nowhere.set_secret_text("lost"));
686 assert!(!nowhere.set_image(1, 1, &[0, 0, 0, 0]));
687 assert!(nowhere.image().is_none());
688 assert_eq!(nowhere.name(), "unavailable");
689 }
690
691 tilo_test_env::scenario! {
692 fn the_in_process_and_system_clipboards_conform;
693
694 phase the_in_process_clipboard_conforms;
695 {
696 conformance::check_local(&InProcessClipboard::default());
697 }
698
699 phase the_system_clipboard_conforms_with_or_without_a_system_clipboard;
700 {
701 let _system = SYSTEM.lock();
702 let system = os();
703 conformance::check_system(&*system);
704 assert!(std::ptr::addr_eq(
705 std::sync::Arc::as_ptr(&system),
706 std::sync::Arc::as_ptr(&self::os())
707 ));
708 }
709 }
710}