1use gpui_kit::{Bounds, Corners, Pixels, RenderImage, Window};
7use std::sync::Arc;
8
9pub struct ImageFrameCache<K> {
11 entry: Option<(K, Arc<RenderImage>)>,
12 generated: u64,
13}
14
15impl<K> Default for ImageFrameCache<K> {
16 fn default() -> Self {
17 Self {
18 entry: None,
19 generated: 0,
20 }
21 }
22}
23
24impl<K: PartialEq> ImageFrameCache<K> {
25 pub fn paint(
27 &mut self,
28 key: K,
29 bounds: Bounds<Pixels>,
30 window: &mut Window,
31 build: impl FnOnce() -> Arc<RenderImage>,
32 ) -> gpui_kit::Result<()> {
33 if self
34 .entry
35 .as_ref()
36 .is_none_or(|(previous, _)| previous != &key)
37 {
38 let image = build();
39 self.clear(window)?;
40 self.entry = Some((key, image));
41 self.generated += 1;
42 }
43 let image = self.entry.as_ref().expect("帧已生成").1.clone();
44 window.paint_image(bounds, bounds, Corners::default(), image, 0, false)
45 }
46
47 pub fn clear(&mut self, window: &mut Window) -> gpui_kit::Result<()> {
49 if let Some((_, image)) = self.entry.take() {
50 window.drop_image(image)?;
51 }
52 Ok(())
53 }
54
55 pub fn generated_frames(&self) -> u64 {
57 self.generated
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64 use gpui_kit::test::TestWindowExt as _;
65 use gpui_kit::{Context, IntoElement, Render, Styled, TestAppContext, canvas};
66 use std::{cell::RefCell, rc::Rc};
67
68 struct Host {
69 cache: Rc<RefCell<ImageFrameCache<u64>>>,
70 key: u64,
71 }
72 impl Render for Host {
73 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
74 let cache = self.cache.clone();
75 let key = self.key;
76 canvas(
77 |_, _, _| (),
78 move |bounds, _, window, _| {
79 cache
80 .borrow_mut()
81 .paint(key, bounds, window, || {
82 Arc::new(RenderImage::new(vec![image::Frame::new(
83 image::RgbaImage::new(2, 2),
84 )]))
85 })
86 .unwrap();
87 },
88 )
89 .size_full()
90 }
91 }
92
93 #[gpui_kit::test]
94 fn stable_key_reuses_frame_and_replacement_evicts_atlas(cx: &mut TestAppContext) {
95 let cache = Rc::new(RefCell::new(ImageFrameCache::default()));
96 let (host, vcx) = cx.add_window_view(|_, _| Host {
97 cache: cache.clone(),
98 key: 1,
99 });
100 vcx.update(|window, cx| window.render_frame(cx));
101 let image = cache.borrow().entry.as_ref().unwrap().1.clone();
102 for _ in 0..200 {
103 vcx.update(|window, cx| window.render_frame(cx));
104 }
105 assert_eq!(cache.borrow().generated_frames(), 1);
106 host.update(vcx, |host, cx| {
107 host.key = 2;
108 cx.notify();
109 });
110 vcx.update(|window, cx| {
111 window.render_frame(cx);
112 assert!(!window.has_image_atlas_entry(&image));
113 assert_eq!(cache.borrow().generated_frames(), 2);
114 cache.borrow_mut().clear(window).unwrap();
115 assert!(cache.borrow().entry.is_none());
116 });
117 }
118}