Skip to main content

mgui_core/
clipboard.rs

1//! 剪贴板抽象 — 纯 trait + 可克隆句柄,无第三方依赖、无 unsafe。
2//!
3//! 上层组件只依赖本模块;桌面/headless/测试分别注入 arboard、Noop 或 Mock。
4//! 除纯文本外,默认方法覆盖 HTML、RGBA 图片和文件列表;不支持时返回 None/false。
5
6use std::cell::RefCell;
7use std::fmt;
8use std::path::PathBuf;
9use std::rc::Rc;
10use std::sync::Arc;
11
12/// 行优先、非预乘 alpha 的 RGBA8 剪贴板图片。
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct ClipboardImage {
15    width: u32,
16    height: u32,
17    rgba: Arc<[u8]>,
18}
19
20impl ClipboardImage {
21    /// 校验尺寸与 RGBA 长度;非法时返回 None。
22    pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Option<Self> {
23        let rgba = rgba.into();
24        if width == 0 || height == 0 {
25            return None;
26        }
27        let expected = (width as usize).checked_mul(height as usize).and_then(|pixels| pixels.checked_mul(4));
28        if expected != Some(rgba.len()) {
29            return None;
30        }
31        Some(Self { width, height, rgba })
32    }
33
34    pub fn from_rgba(width: u32, height: u32, rgba: Vec<u8>) -> Option<Self> {
35        Self::new(width, height, rgba)
36    }
37
38    pub fn width(&self) -> u32 {
39        self.width
40    }
41
42    pub fn height(&self) -> u32 {
43        self.height
44    }
45
46    pub fn rgba(&self) -> &[u8] {
47        &self.rgba
48    }
49}
50
51/// 剪贴板抽象 trait。core 层不依赖任何第三方剪贴板 crate。
52///
53/// 组件只需要纯文本;富剪贴板(HTML/图片/文件列表)由应用层通过默认方法使用,
54/// 平台不支持时保持 None/false。
55pub trait ClipboardProvider {
56    /// 从系统剪贴板读纯文本;不可用(无权限/不支持/初始化失败)返回 None
57    fn get_text(&mut self) -> Option<String>;
58    /// 向系统剪贴板写纯文本;成功返回 true
59    fn set_text(&mut self, text: &str) -> bool;
60
61    /// 读取 HTML(通常同时带纯文本 alternative)。
62    fn get_html(&mut self) -> Option<String> {
63        None
64    }
65    /// 写入 HTML 与可选纯文本 alternative。
66    fn set_html(&mut self, _html: &str, _alt_text: Option<&str>) -> bool {
67        false
68    }
69    fn get_image(&mut self) -> Option<ClipboardImage> {
70        None
71    }
72    fn set_image(&mut self, _image: &ClipboardImage) -> bool {
73        false
74    }
75    fn get_file_list(&mut self) -> Option<Vec<PathBuf>> {
76        None
77    }
78    fn set_file_list(&mut self, _paths: &[PathBuf]) -> bool {
79        false
80    }
81}
82
83/// 空实现:剪贴板不可用 / 未初始化时的 fallback(静默无操作)
84pub struct NoopClipboard;
85
86impl ClipboardProvider for NoopClipboard {
87    fn get_text(&mut self) -> Option<String> {
88        None
89    }
90    fn set_text(&mut self, _text: &str) -> bool {
91        false
92    }
93}
94
95/// 可在 UI 回调间克隆的剪贴板句柄(共享同一个 provider 实例)。
96#[derive(Clone)]
97pub struct ClipboardHandle(Rc<RefCell<Box<dyn ClipboardProvider>>>);
98
99impl ClipboardHandle {
100    pub fn new(provider: Box<dyn ClipboardProvider>) -> Self {
101        Self(Rc::new(RefCell::new(provider)))
102    }
103
104    /// 无操作句柄(headless / 不支持剪贴板的 shell)。
105    pub fn noop() -> Self {
106        Self::new(Box::new(NoopClipboard))
107    }
108
109    pub fn get_text(&self) -> Option<String> {
110        self.0.borrow_mut().get_text()
111    }
112
113    pub fn set_text(&self, text: &str) -> bool {
114        self.0.borrow_mut().set_text(text)
115    }
116
117    pub fn get_html(&self) -> Option<String> {
118        self.0.borrow_mut().get_html()
119    }
120
121    pub fn set_html(&self, html: &str, alt_text: Option<&str>) -> bool {
122        self.0.borrow_mut().set_html(html, alt_text)
123    }
124
125    pub fn get_image(&self) -> Option<ClipboardImage> {
126        self.0.borrow_mut().get_image()
127    }
128
129    pub fn set_image(&self, image: &ClipboardImage) -> bool {
130        self.0.borrow_mut().set_image(image)
131    }
132
133    pub fn get_file_list(&self) -> Option<Vec<PathBuf>> {
134        self.0.borrow_mut().get_file_list()
135    }
136
137    pub fn set_file_list(&self, paths: &[PathBuf]) -> bool {
138        self.0.borrow_mut().set_file_list(paths)
139    }
140}
141
142impl Default for ClipboardHandle {
143    fn default() -> Self {
144        Self::noop()
145    }
146}
147
148impl fmt::Debug for ClipboardHandle {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        f.debug_struct("ClipboardHandle").finish_non_exhaustive()
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[derive(Default)]
159    struct MockClipboard {
160        text: Option<String>,
161        html: Option<String>,
162        image: Option<ClipboardImage>,
163        files: Option<Vec<PathBuf>>,
164    }
165
166    impl ClipboardProvider for MockClipboard {
167        fn get_text(&mut self) -> Option<String> {
168            self.text.clone()
169        }
170        fn set_text(&mut self, text: &str) -> bool {
171            self.text = Some(text.to_string());
172            true
173        }
174        fn get_html(&mut self) -> Option<String> {
175            self.html.clone()
176        }
177        fn set_html(&mut self, html: &str, _alt: Option<&str>) -> bool {
178            self.html = Some(html.to_string());
179            true
180        }
181        fn get_image(&mut self) -> Option<ClipboardImage> {
182            self.image.clone()
183        }
184        fn set_image(&mut self, image: &ClipboardImage) -> bool {
185            self.image = Some(image.clone());
186            true
187        }
188        fn get_file_list(&mut self) -> Option<Vec<PathBuf>> {
189            self.files.clone()
190        }
191        fn set_file_list(&mut self, paths: &[PathBuf]) -> bool {
192            self.files = Some(paths.to_vec());
193            true
194        }
195    }
196
197    #[test]
198    fn clipboard_handle_roundtrips_rich_data() {
199        let cb = ClipboardHandle::new(Box::new(MockClipboard::default()));
200        assert!(cb.set_text("hello"));
201        assert_eq!(cb.get_text().as_deref(), Some("hello"));
202        assert!(cb.set_html("<b>hi</b>", Some("hi")));
203        assert_eq!(cb.get_html().as_deref(), Some("<b>hi</b>"));
204
205        let image = ClipboardImage::from_rgba(2, 2, vec![255; 16]).expect("valid image");
206        assert!(cb.set_image(&image));
207        assert_eq!(cb.get_image(), Some(image));
208
209        let files = vec![PathBuf::from("a.txt"), PathBuf::from("b.md")];
210        assert!(cb.set_file_list(&files));
211        assert_eq!(cb.get_file_list(), Some(files));
212    }
213
214    #[test]
215    fn clipboard_image_validates_dimensions() {
216        assert!(ClipboardImage::from_rgba(1, 1, vec![0; 4]).is_some());
217        assert!(ClipboardImage::from_rgba(0, 1, Vec::new()).is_none());
218        assert!(ClipboardImage::from_rgba(1, 1, vec![0; 3]).is_none());
219    }
220
221    #[test]
222    fn noop_handle_never_panics() {
223        let cb = ClipboardHandle::noop();
224        assert_eq!(cb.get_text(), None);
225        assert!(!cb.set_text("x"));
226        assert!(!cb.set_html("<b>x</b>", None));
227        assert_eq!(cb.get_image(), None);
228        assert!(!cb.set_file_list(&[PathBuf::from("x")]));
229    }
230}