arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
//! 按内容键复用离屏帧,并显式回收 GPUI 图集条目。
//!
//! 仅丢弃 `Arc<RenderImage>` 不会释放窗口 sprite atlas。宿主必须在页面卸载时
//! 调用 `clear`;替换帧时本类型会自动释放旧条目。每个缓存只能用于一个窗口。

use gpui_kit::{Bounds, Corners, Pixels, RenderImage, Window};
use std::sync::Arc;

/// 单帧缓存:相机、尺寸或场景版本变化时才重新生成和上传。
pub struct ImageFrameCache<K> {
    entry: Option<(K, Arc<RenderImage>)>,
    generated: u64,
}

impl<K> Default for ImageFrameCache<K> {
    fn default() -> Self {
        Self {
            entry: None,
            generated: 0,
        }
    }
}

impl<K: PartialEq> ImageFrameCache<K> {
    /// 绘制缓存帧;闭包只在键变化时执行,返回图集绘制结果。
    pub fn paint(
        &mut self,
        key: K,
        bounds: Bounds<Pixels>,
        window: &mut Window,
        build: impl FnOnce() -> Arc<RenderImage>,
    ) -> gpui_kit::Result<()> {
        if self
            .entry
            .as_ref()
            .is_none_or(|(previous, _)| previous != &key)
        {
            let image = build();
            self.clear(window)?;
            self.entry = Some((key, image));
            self.generated += 1;
        }
        let image = self.entry.as_ref().expect("帧已生成").1.clone();
        window.paint_image(bounds, bounds, Corners::default(), image, 0, false)
    }

    /// 页面卸载或释放设备时调用;同时释放 CPU 像素与 GPU 图集条目。
    pub fn clear(&mut self, window: &mut Window) -> gpui_kit::Result<()> {
        if let Some((_, image)) = self.entry.take() {
            window.drop_image(image)?;
        }
        Ok(())
    }

    /// 实际生成次数;空闲重绘不应使此数增长。
    pub fn generated_frames(&self) -> u64 {
        self.generated
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui_kit::test::TestWindowExt as _;
    use gpui_kit::{Context, IntoElement, Render, Styled, TestAppContext, canvas};
    use std::{cell::RefCell, rc::Rc};

    struct Host {
        cache: Rc<RefCell<ImageFrameCache<u64>>>,
        key: u64,
    }
    impl Render for Host {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let cache = self.cache.clone();
            let key = self.key;
            canvas(
                |_, _, _| (),
                move |bounds, _, window, _| {
                    cache
                        .borrow_mut()
                        .paint(key, bounds, window, || {
                            Arc::new(RenderImage::new(vec![image::Frame::new(
                                image::RgbaImage::new(2, 2),
                            )]))
                        })
                        .unwrap();
                },
            )
            .size_full()
        }
    }

    #[gpui_kit::test]
    fn stable_key_reuses_frame_and_replacement_evicts_atlas(cx: &mut TestAppContext) {
        let cache = Rc::new(RefCell::new(ImageFrameCache::default()));
        let (host, vcx) = cx.add_window_view(|_, _| Host {
            cache: cache.clone(),
            key: 1,
        });
        vcx.update(|window, cx| window.render_frame(cx));
        let image = cache.borrow().entry.as_ref().unwrap().1.clone();
        for _ in 0..200 {
            vcx.update(|window, cx| window.render_frame(cx));
        }
        assert_eq!(cache.borrow().generated_frames(), 1);
        host.update(vcx, |host, cx| {
            host.key = 2;
            cx.notify();
        });
        vcx.update(|window, cx| {
            window.render_frame(cx);
            assert!(!window.has_image_atlas_entry(&image));
            assert_eq!(cache.borrow().generated_frames(), 2);
            cache.borrow_mut().clear(window).unwrap();
            assert!(cache.borrow().entry.is_none());
        });
    }
}