mgui-core 0.8.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! 剪贴板抽象 — 纯 trait + 可克隆句柄,无第三方依赖、无 unsafe。
//!
//! 上层组件只依赖本模块;桌面/headless/测试分别注入 arboard、Noop 或 Mock。
//! 除纯文本外,默认方法覆盖 HTML、RGBA 图片和文件列表;不支持时返回 None/false。

use std::cell::RefCell;
use std::fmt;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;

/// 行优先、非预乘 alpha 的 RGBA8 剪贴板图片。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClipboardImage {
    width: u32,
    height: u32,
    rgba: Arc<[u8]>,
}

impl ClipboardImage {
    /// 校验尺寸与 RGBA 长度;非法时返回 None。
    pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Option<Self> {
        let rgba = rgba.into();
        if width == 0 || height == 0 {
            return None;
        }
        let expected = (width as usize).checked_mul(height as usize).and_then(|pixels| pixels.checked_mul(4));
        if expected != Some(rgba.len()) {
            return None;
        }
        Some(Self { width, height, rgba })
    }

    pub fn from_rgba(width: u32, height: u32, rgba: Vec<u8>) -> Option<Self> {
        Self::new(width, height, rgba)
    }

    pub fn width(&self) -> u32 {
        self.width
    }

    pub fn height(&self) -> u32 {
        self.height
    }

    pub fn rgba(&self) -> &[u8] {
        &self.rgba
    }
}

/// 剪贴板抽象 trait。core 层不依赖任何第三方剪贴板 crate。
///
/// 组件只需要纯文本;富剪贴板(HTML/图片/文件列表)由应用层通过默认方法使用,
/// 平台不支持时保持 None/false。
pub trait ClipboardProvider {
    /// 从系统剪贴板读纯文本;不可用(无权限/不支持/初始化失败)返回 None
    fn get_text(&mut self) -> Option<String>;
    /// 向系统剪贴板写纯文本;成功返回 true
    fn set_text(&mut self, text: &str) -> bool;

    /// 读取 HTML(通常同时带纯文本 alternative)。
    fn get_html(&mut self) -> Option<String> {
        None
    }
    /// 写入 HTML 与可选纯文本 alternative。
    fn set_html(&mut self, _html: &str, _alt_text: Option<&str>) -> bool {
        false
    }
    fn get_image(&mut self) -> Option<ClipboardImage> {
        None
    }
    fn set_image(&mut self, _image: &ClipboardImage) -> bool {
        false
    }
    fn get_file_list(&mut self) -> Option<Vec<PathBuf>> {
        None
    }
    fn set_file_list(&mut self, _paths: &[PathBuf]) -> bool {
        false
    }
}

/// 空实现:剪贴板不可用 / 未初始化时的 fallback(静默无操作)
pub struct NoopClipboard;

impl ClipboardProvider for NoopClipboard {
    fn get_text(&mut self) -> Option<String> {
        None
    }
    fn set_text(&mut self, _text: &str) -> bool {
        false
    }
}

/// 可在 UI 回调间克隆的剪贴板句柄(共享同一个 provider 实例)。
#[derive(Clone)]
pub struct ClipboardHandle(Rc<RefCell<Box<dyn ClipboardProvider>>>);

impl ClipboardHandle {
    pub fn new(provider: Box<dyn ClipboardProvider>) -> Self {
        Self(Rc::new(RefCell::new(provider)))
    }

    /// 无操作句柄(headless / 不支持剪贴板的 shell)。
    pub fn noop() -> Self {
        Self::new(Box::new(NoopClipboard))
    }

    pub fn get_text(&self) -> Option<String> {
        self.0.borrow_mut().get_text()
    }

    pub fn set_text(&self, text: &str) -> bool {
        self.0.borrow_mut().set_text(text)
    }

    pub fn get_html(&self) -> Option<String> {
        self.0.borrow_mut().get_html()
    }

    pub fn set_html(&self, html: &str, alt_text: Option<&str>) -> bool {
        self.0.borrow_mut().set_html(html, alt_text)
    }

    pub fn get_image(&self) -> Option<ClipboardImage> {
        self.0.borrow_mut().get_image()
    }

    pub fn set_image(&self, image: &ClipboardImage) -> bool {
        self.0.borrow_mut().set_image(image)
    }

    pub fn get_file_list(&self) -> Option<Vec<PathBuf>> {
        self.0.borrow_mut().get_file_list()
    }

    pub fn set_file_list(&self, paths: &[PathBuf]) -> bool {
        self.0.borrow_mut().set_file_list(paths)
    }
}

impl Default for ClipboardHandle {
    fn default() -> Self {
        Self::noop()
    }
}

impl fmt::Debug for ClipboardHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClipboardHandle").finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Default)]
    struct MockClipboard {
        text: Option<String>,
        html: Option<String>,
        image: Option<ClipboardImage>,
        files: Option<Vec<PathBuf>>,
    }

    impl ClipboardProvider for MockClipboard {
        fn get_text(&mut self) -> Option<String> {
            self.text.clone()
        }
        fn set_text(&mut self, text: &str) -> bool {
            self.text = Some(text.to_string());
            true
        }
        fn get_html(&mut self) -> Option<String> {
            self.html.clone()
        }
        fn set_html(&mut self, html: &str, _alt: Option<&str>) -> bool {
            self.html = Some(html.to_string());
            true
        }
        fn get_image(&mut self) -> Option<ClipboardImage> {
            self.image.clone()
        }
        fn set_image(&mut self, image: &ClipboardImage) -> bool {
            self.image = Some(image.clone());
            true
        }
        fn get_file_list(&mut self) -> Option<Vec<PathBuf>> {
            self.files.clone()
        }
        fn set_file_list(&mut self, paths: &[PathBuf]) -> bool {
            self.files = Some(paths.to_vec());
            true
        }
    }

    #[test]
    fn clipboard_handle_roundtrips_rich_data() {
        let cb = ClipboardHandle::new(Box::new(MockClipboard::default()));
        assert!(cb.set_text("hello"));
        assert_eq!(cb.get_text().as_deref(), Some("hello"));
        assert!(cb.set_html("<b>hi</b>", Some("hi")));
        assert_eq!(cb.get_html().as_deref(), Some("<b>hi</b>"));

        let image = ClipboardImage::from_rgba(2, 2, vec![255; 16]).expect("valid image");
        assert!(cb.set_image(&image));
        assert_eq!(cb.get_image(), Some(image));

        let files = vec![PathBuf::from("a.txt"), PathBuf::from("b.md")];
        assert!(cb.set_file_list(&files));
        assert_eq!(cb.get_file_list(), Some(files));
    }

    #[test]
    fn clipboard_image_validates_dimensions() {
        assert!(ClipboardImage::from_rgba(1, 1, vec![0; 4]).is_some());
        assert!(ClipboardImage::from_rgba(0, 1, Vec::new()).is_none());
        assert!(ClipboardImage::from_rgba(1, 1, vec![0; 3]).is_none());
    }

    #[test]
    fn noop_handle_never_panics() {
        let cb = ClipboardHandle::noop();
        assert_eq!(cb.get_text(), None);
        assert!(!cb.set_text("x"));
        assert!(!cb.set_html("<b>x</b>", None));
        assert_eq!(cb.get_image(), None);
        assert!(!cb.set_file_list(&[PathBuf::from("x")]));
    }
}