ailloli_ui_winit/
clipboard.rs

1//! Native system clipboard for the Ailloli UI runtime.
2
3use std::cell::RefCell;
4
5use ailloli_ui_runtime::app::ClipboardProvider;
6
7/// Lazy `arboard` clipboard wired into [`ClipboardProvider`].
8///
9/// The native clipboard is created on first read/write attempt. Failed creation
10/// is retried on the next operation because the internal slot remains `None`.
11/// This type uses `RefCell` and is neither a cross-thread synchronization point
12/// nor reentrant during one provider call.
13///
14/// # Examples
15///
16/// ```
17/// use ailloli_ui_winit::clipboard::NativeClipboard;
18/// let clipboard = NativeClipboard::new();
19/// let _ = clipboard; // Native resources are still uninitialized.
20/// ```
21#[derive(Default)]
22pub struct NativeClipboard {
23    /// Lazily initialized process clipboard handle.
24    clipboard: RefCell<Option<arboard::Clipboard>>,
25}
26
27/// Construction and lazy native access.
28impl NativeClipboard {
29    /// Creates an empty lazy provider without touching the host clipboard.
30    ///
31    /// # Examples
32    ///
33    /// ```
34    /// use ailloli_ui_winit::clipboard::NativeClipboard;
35    /// let clipboard: NativeClipboard = NativeClipboard::new();
36    /// let _ = clipboard;
37    /// ```
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    /// Initializes on demand and runs `f`, returning `None` when initialization fails.
43    fn with_clipboard<T>(&self, f: impl FnOnce(&mut arboard::Clipboard) -> T) -> Option<T> {
44        let mut slot = self.clipboard.borrow_mut();
45        if slot.is_none() {
46            *slot = arboard::Clipboard::new().ok();
47        }
48        slot.as_mut().map(f)
49    }
50}
51
52/// Runtime clipboard operations; native errors become `None` or display strings.
53impl ClipboardProvider for NativeClipboard {
54    /// Returns current text, or `None` when the platform clipboard cannot be read.
55    fn read_text(&self) -> Option<String> {
56        self.with_clipboard(|clipboard| clipboard.get_text().ok())
57            .flatten()
58    }
59
60    /// Replaces clipboard text and stringifies any platform-specific failure.
61    ///
62    /// # Errors
63    ///
64    /// Returns `native clipboard unavailable` when lazy initialization fails, or
65    /// the platform clipboard error's display string when the write fails.
66    fn write_text(&self, text: &str) -> Result<(), String> {
67        self.with_clipboard(|clipboard| clipboard.set_text(text.to_string()))
68            .ok_or_else(|| "native clipboard unavailable".to_string())?
69            .map_err(|err| err.to_string())
70    }
71}