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
489static RESOLVER: OnceLock<fn() -> std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
492
493pub fn install_resolver(resolve: fn() -> std::sync::Arc<dyn ClipboardBackend>) {
496 let _ = RESOLVER.set(resolve);
497}
498
499#[must_use]
503pub fn current() -> std::sync::Arc<dyn ClipboardBackend> {
504 static IN_PROCESS: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
505 if let Some(resolve) = RESOLVER.get() {
506 return resolve();
507 }
508 IN_PROCESS
509 .get_or_init(|| std::sync::Arc::new(InProcessClipboard::default()))
510 .clone()
511}
512
513pub fn unavailable() -> std::sync::Arc<dyn ClipboardBackend> {
516 std::sync::Arc::new(Nowhere)
517}
518
519pub fn is_unavailable(backend: &dyn ClipboardBackend) -> bool {
522 backend.name() == Nowhere.name()
523}
524
525pub fn os() -> std::sync::Arc<dyn ClipboardBackend> {
533 #[cfg(any(target_os = "linux", target_os = "macos", windows))]
534 {
535 static OS: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
536 OS.get_or_init(|| std::sync::Arc::new(native::NativeClipboard::default()))
537 .clone()
538 }
539 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
540 {
541 unavailable()
542 }
543}
544
545pub fn warn_fallback_once(op: &str) {
550 static WARNED: OnceLock<()> = OnceLock::new();
551 WARNED.get_or_init(|| {
552 tracing::warn!(
553 target: "tilo_ui::clipboard",
554 operation = op,
555 "no system clipboard: falling back to an in-process buffer. Copy and paste \
556 will work inside this process and silently do nothing between processes. \
557 On Wayland this means the compositor offers neither \
558 zwlr_data_control_manager_v1 nor ext_data_control_v1 and no X11 (XWayland) \
559 clipboard is reachable either."
560 );
561 });
562}
563
564struct Nowhere;
565
566impl ClipboardBackend for Nowhere {
567 fn set_text(&self, _target: ClipboardTarget, _text: &str) -> bool {
568 false
569 }
570
571 fn text(&self, _target: ClipboardTarget) -> Option<String> {
572 None
573 }
574
575 fn name(&self) -> &'static str {
576 "unavailable"
577 }
578}
579
580#[derive(Debug, Default)]
587pub struct InProcessClipboard {
588 clipboard: Mutex<Option<String>>,
589 primary: Mutex<Option<String>>,
590 rich: Mutex<Option<String>>,
591}
592
593impl InProcessClipboard {
594 fn slot(&self, target: ClipboardTarget) -> &Mutex<Option<String>> {
595 match target {
596 ClipboardTarget::Clipboard => &self.clipboard,
597 ClipboardTarget::Primary => &self.primary,
598 }
599 }
600}
601
602impl ClipboardBackend for InProcessClipboard {
603 fn set_text(&self, target: ClipboardTarget, text: &str) -> bool {
604 let Ok(mut slot) = self.slot(target).lock() else {
605 return false;
606 };
607 *slot = Some(text.to_string());
608 if target == ClipboardTarget::Clipboard
609 && let Ok(mut rich) = self.rich.lock()
610 {
611 *rich = None;
612 }
613 true
614 }
615
616 fn text(&self, target: ClipboardTarget) -> Option<String> {
617 self.slot(target).lock().ok()?.clone()
618 }
619
620 fn set_rich_text(&self, html: &str, plain: &str) -> bool {
621 if !self.set_text(ClipboardTarget::Clipboard, plain) {
622 return false;
623 }
624 let Ok(mut rich) = self.rich.lock() else {
625 return false;
626 };
627 *rich = Some(html.to_owned());
628 true
629 }
630
631 fn rich_text(&self) -> Option<RichTextOffer> {
632 let html = self.rich.lock().ok()?.clone()?;
633 let plain = self.text(ClipboardTarget::Clipboard);
634 Some(RichTextOffer { html, plain }).filter(RichTextOffer::is_valid)
635 }
636
637 fn set_shared_text(&self, _target: ClipboardTarget, _text: &str) -> bool {
638 false
639 }
640
641 fn name(&self) -> &'static str {
642 "in-process"
643 }
644}
645
646#[cfg(test)]
647pub(crate) mod tests {
648 use super::*;
649
650 pub(crate) static SYSTEM: Mutex<()> = Mutex::new(());
652
653 #[test]
654 fn a_copy_settles_once_and_runs_what_waits_on_it() {
655 let (copy, settler) = ClipboardCopy::pending();
656 let (ran, outcomes) = std::sync::mpsc::channel();
657 let early = ran.clone();
658 copy.on_settled(move |copied| early.send(("before", copied)).unwrap());
659 assert_eq!(copy.outcome(), None);
660 assert!(
661 outcomes.try_recv().is_err(),
662 "nothing runs before it settles"
663 );
664 settler.settle(true);
665 assert_eq!(copy.outcome(), Some(true));
666 assert!(copy.wait());
667 copy.on_settled(move |copied| ran.send(("after", copied)).unwrap());
668 assert_eq!(
669 outcomes.try_iter().collect::<Vec<_>>(),
670 [("before", true), ("after", true)]
671 );
672
673 let (copy, settler) = ClipboardCopy::pending();
674 drop(settler);
675 assert_eq!(copy.outcome(), Some(false), "an abandoned copy failed");
676 }
677
678 #[test]
679 fn the_in_process_clipboard_keeps_text_inside_the_process() {
680 let clipboard = InProcessClipboard::default();
681 assert!(clipboard.set_text(ClipboardTarget::Clipboard, "local"));
682 assert_eq!(
683 clipboard.text(ClipboardTarget::Clipboard).as_deref(),
684 Some("local")
685 );
686 assert!(clipboard.set_rich_text("<b>bold</b>", "bold"));
687 assert_eq!(
688 clipboard.rich_text().map(|offer| offer.plain),
689 Some(Some("bold".to_owned()))
690 );
691 assert!(
692 !clipboard.set_shared_text(ClipboardTarget::Clipboard, "shared"),
693 "an in-process buffer does not claim a shared copy"
694 );
695 assert!(
696 !clipboard.set_secret_text("secret"),
697 "an in-process buffer does not claim a secret copy"
698 );
699 assert!(!clipboard.set_image(1, 1, &[0, 0, 0, 0]));
700 assert!(clipboard.image().is_none());
701 }
702
703 #[test]
704 fn a_process_handed_no_connection_holds_and_takes_nothing() {
705 let nowhere = unavailable();
706 assert!(!nowhere.set_text(ClipboardTarget::Clipboard, "lost"));
707 assert_eq!(nowhere.text(ClipboardTarget::Clipboard), None);
708 assert!(!nowhere.set_shared_text(ClipboardTarget::Clipboard, "lost"));
709 assert!(!nowhere.set_secret_text("lost"));
710 assert!(!nowhere.set_image(1, 1, &[0, 0, 0, 0]));
711 assert!(nowhere.image().is_none());
712 assert_eq!(nowhere.name(), "unavailable");
713 }
714
715 tilo_test_env::scenario! {
716 fn the_in_process_and_system_clipboards_conform;
717
718 phase the_in_process_clipboard_conforms;
719 {
720 conformance::check_local(&InProcessClipboard::default());
721 }
722
723 phase the_system_clipboard_conforms_with_or_without_a_system_clipboard;
724 {
725 let _system = SYSTEM.lock();
726 let system = os();
727 conformance::check_system(&*system);
728 assert!(std::ptr::addr_eq(
729 std::sync::Arc::as_ptr(&system),
730 std::sync::Arc::as_ptr(&self::os())
731 ));
732 }
733 }
734}