1use std::{cell::RefCell, fmt, rc::Rc};
2
3pub trait ClipboardBackend {
10 fn text(&mut self) -> Option<String>;
11 fn set_text(&mut self, text: &str);
12}
13
14#[derive(Debug, Default)]
16pub struct LocalClipboardBackend {
17 text: Option<String>,
18}
19
20impl LocalClipboardBackend {
21 pub fn new() -> Self {
22 Self::default()
23 }
24}
25
26impl ClipboardBackend for LocalClipboardBackend {
27 fn text(&mut self) -> Option<String> {
28 self.text.clone()
29 }
30
31 fn set_text(&mut self, text: &str) {
32 self.text = Some(text.to_string());
33 }
34}
35
36#[derive(Clone)]
42pub struct Clipboard {
43 inner: Rc<RefCell<Box<dyn ClipboardBackend>>>,
44}
45
46impl Clipboard {
47 pub fn new() -> Self {
48 Self::with_backend(LocalClipboardBackend::new())
49 }
50
51 pub fn with_backend(backend: impl ClipboardBackend + 'static) -> Self {
52 Self {
53 inner: Rc::new(RefCell::new(Box::new(backend))),
54 }
55 }
56
57 pub fn set_backend(&self, backend: impl ClipboardBackend + 'static) {
59 *self.inner.borrow_mut() = Box::new(backend);
60 }
61
62 pub fn text(&self) -> Option<String> {
63 self.inner.borrow_mut().text()
64 }
65
66 pub fn set_text(&self, text: impl AsRef<str>) {
67 self.inner.borrow_mut().set_text(text.as_ref());
68 }
69}
70
71impl Default for Clipboard {
72 fn default() -> Self {
73 Self::new()
74 }
75}
76
77impl fmt::Debug for Clipboard {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 f.debug_struct("Clipboard").finish_non_exhaustive()
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 #[test]
88 fn local_backend_round_trips_text() {
89 let clipboard = Clipboard::new();
90 assert_eq!(clipboard.text(), None);
91
92 clipboard.set_text("hello");
93 assert_eq!(clipboard.text().as_deref(), Some("hello"));
94 }
95
96 #[test]
97 fn clones_share_storage_and_backend_swaps_apply_to_all_handles() {
98 let clipboard = Clipboard::new();
99 let clone = clipboard.clone();
100 clipboard.set_text("shared");
101 assert_eq!(clone.text().as_deref(), Some("shared"));
102
103 clone.set_backend(LocalClipboardBackend::new());
104 assert_eq!(clipboard.text(), None);
105 }
106}