Skip to main content

cranpose_app_shell/
system_clipboard.rs

1use cranpose_render_common::Renderer;
2
3use crate::AppShell;
4
5#[cfg(all(
6    feature = "clipboard-native",
7    not(target_arch = "wasm32"),
8    not(target_os = "android"),
9    not(target_os = "ios")
10))]
11#[derive(Default)]
12struct SystemClipboard {
13    // Opened at the first copy or paste: opened at launch, it held the main
14    // thread ~0.8 ms on an Apple M5, for apps that never touch it too.
15    inner: std::cell::OnceCell<std::cell::RefCell<Option<arboard::Clipboard>>>,
16}
17
18#[cfg(all(
19    feature = "clipboard-native",
20    not(target_arch = "wasm32"),
21    not(target_os = "android"),
22    not(target_os = "ios")
23))]
24impl SystemClipboard {
25    fn with<T>(
26        &self,
27        use_clipboard: impl FnOnce(&mut arboard::Clipboard) -> Option<T>,
28    ) -> Option<T> {
29        self.inner
30            .get_or_init(|| std::cell::RefCell::new(arboard::Clipboard::new().ok()))
31            .borrow_mut()
32            .as_mut()
33            .and_then(use_clipboard)
34    }
35}
36
37#[cfg(all(
38    feature = "clipboard-native",
39    not(target_arch = "wasm32"),
40    not(target_os = "android"),
41    not(target_os = "ios")
42))]
43impl cranpose_ui::clipboard_session::PlatformClipboard for SystemClipboard {
44    fn write_text(&self, text: &str) {
45        self.with(|clipboard| clipboard.set_text(text).ok());
46    }
47
48    fn read_text(&self) -> Option<String> {
49        self.with(|clipboard| clipboard.get_text().ok())
50    }
51}
52
53impl<R: Renderer> AppShell<R> {
54    /// Copies and pastes through the system clipboard from now on, as a shell
55    /// shown in a window does. A shell that never calls it, such as a test's,
56    /// keeps what it copies to itself.
57    #[cfg(all(
58        feature = "clipboard-native",
59        not(target_arch = "wasm32"),
60        not(target_os = "android"),
61        not(target_os = "ios")
62    ))]
63    pub fn use_system_clipboard(&self) {
64        self.app.app_context.enter(|| {
65            cranpose_ui::clipboard_session::set_platform_clipboard(std::rc::Rc::new(
66                SystemClipboard::default(),
67            ));
68        });
69    }
70
71    /// Does nothing: this build reaches the system clipboard through its runner.
72    #[cfg(not(all(
73        feature = "clipboard-native",
74        not(target_arch = "wasm32"),
75        not(target_os = "android"),
76        not(target_os = "ios")
77    )))]
78    pub fn use_system_clipboard(&self) {}
79}