mgui-shell 0.2.0

平台无关 Shell 抽象:Clock / ShellMetrics / Clipboard 能力契约
Documentation
//! 平台无关的窗口图标数据。
//!
//! 图标在窗口创建前以 32bpp RGBA8 位图形式传入;desktop shell 再转换到
//! winit/平台 API。`small` 用于标题栏(Windows `ICON_SMALL`),`large`
//! 用于任务栏/窗口切换器(Windows `ICON_BIG`,Linux `_NET_WM_ICON`)。

use std::sync::Arc;

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

impl IconImage {
    /// 校验尺寸与 RGBA 长度;尺寸为 0 或字节数不等于 `width * height * 4` 时返回 `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 })
    }

    /// 从 `Vec<u8>` 构造 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
    }
}

/// 窗口图标:小图用于标题栏,大图用于任务栏/窗口切换器。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindowIcon {
    small: IconImage,
    large: IconImage,
}

impl WindowIcon {
    pub fn new(small: IconImage, large: IconImage) -> Self {
        Self { small, large }
    }

    /// 只有一张图时同时用于小/大图标(由平台缩放)。
    pub fn single(image: IconImage) -> Self {
        Self { small: image.clone(), large: image }
    }

    pub fn small(&self) -> &IconImage {
        &self.small
    }

    pub fn large(&self) -> &IconImage {
        &self.large
    }
}

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

    fn solid(width: u32, height: u32) -> IconImage {
        IconImage::from_rgba(width, height, vec![255; width as usize * height as usize * 4]).expect("valid rgba")
    }

    #[test]
    fn validates_dimensions_and_length() {
        assert!(IconImage::new(2, 2, vec![0; 16]).is_some());
        assert!(IconImage::new(0, 2, Vec::new()).is_none(), "零宽无效");
        assert!(IconImage::new(2, 2, vec![0; 15]).is_none(), "字节数不匹配");
        assert!(IconImage::new(2, 2, vec![0; 20]).is_none(), "字节数不匹配");
    }

    #[test]
    fn single_icon_shares_image() {
        let image = solid(32, 32);
        let icon = WindowIcon::single(image.clone());
        assert_eq!(icon.small(), &image);
        assert_eq!(icon.large(), &image);
        assert_eq!(Arc::strong_count(&image.rgba), 3, "single 复用同一块 RGBA");
    }

    #[test]
    fn explicit_small_and_large_are_kept() {
        let small = solid(32, 32);
        let large = solid(256, 256);
        let icon = WindowIcon::new(small.clone(), large.clone());
        assert_eq!(icon.small().width(), 32);
        assert_eq!(icon.large().width(), 256);
    }
}