Skip to main content

gpui/elements/
image_cache.rs

1use crate::{
2    AnyElement, AnyEntity, App, AppContext, Asset, AssetLogger, Bounds, Element, ElementId, Entity,
3    GlobalElementId, ImageAssetLoader, ImageCacheError, InspectorElementId, LayoutId,
4    ParentElement, Pixels, RenderImage, Resource, Style, StyleRefinement, Styled, Window, hash,
5};
6
7use crate::asset_cache::CachedLoad;
8use refineable::Refineable;
9use smallvec::SmallVec;
10use std::{collections::HashMap, fmt, sync::Arc};
11
12/// An image cache element, all its child img elements will use the cache specified by this element.
13/// Note that this could as simple as passing an `Entity<T: ImageCache>`
14pub fn image_cache(image_cache_provider: impl ImageCacheProvider) -> ImageCacheElement {
15    ImageCacheElement {
16        image_cache_provider: Box::new(image_cache_provider),
17        style: StyleRefinement::default(),
18        children: SmallVec::default(),
19    }
20}
21
22/// A dynamically typed image cache, which can be used to store any image cache
23#[derive(Clone)]
24pub struct AnyImageCache {
25    image_cache: AnyEntity,
26    load_fn: fn(
27        image_cache: &AnyEntity,
28        resource: &Resource,
29        window: &mut Window,
30        cx: &mut App,
31    ) -> Option<Result<Arc<RenderImage>, ImageCacheError>>,
32}
33
34impl<I: ImageCache> From<Entity<I>> for AnyImageCache {
35    fn from(image_cache: Entity<I>) -> Self {
36        Self {
37            image_cache: image_cache.into_any(),
38            load_fn: any_image_cache::load::<I>,
39        }
40    }
41}
42
43impl AnyImageCache {
44    /// Load an image given a resource
45    /// returns the result of loading the image if it has finished loading, or None if it is still loading
46    pub fn load(
47        &self,
48        resource: &Resource,
49        window: &mut Window,
50        cx: &mut App,
51    ) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
52        (self.load_fn)(&self.image_cache, resource, window, cx)
53    }
54}
55
56mod any_image_cache {
57    use super::*;
58
59    pub(crate) fn load<I: 'static + ImageCache>(
60        image_cache: &AnyEntity,
61        resource: &Resource,
62        window: &mut Window,
63        cx: &mut App,
64    ) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
65        let image_cache = image_cache.clone().downcast::<I>().unwrap();
66        image_cache.update(cx, |image_cache, cx| image_cache.load(resource, window, cx))
67    }
68}
69
70/// An image cache element.
71pub struct ImageCacheElement {
72    image_cache_provider: Box<dyn ImageCacheProvider>,
73    style: StyleRefinement,
74    children: SmallVec<[AnyElement; 2]>,
75}
76
77impl ParentElement for ImageCacheElement {
78    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
79        self.children.extend(elements)
80    }
81}
82
83impl Styled for ImageCacheElement {
84    fn style(&mut self) -> &mut StyleRefinement {
85        &mut self.style
86    }
87}
88
89impl Element for ImageCacheElement {
90    type RequestLayoutState = SmallVec<[LayoutId; 4]>;
91    type PrepaintState = ();
92
93    fn id(&self) -> Option<ElementId> {
94        None
95    }
96
97    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
98        None
99    }
100
101    fn request_layout(
102        &mut self,
103        _id: Option<&GlobalElementId>,
104        _inspector_id: Option<&InspectorElementId>,
105        window: &mut Window,
106        cx: &mut App,
107    ) -> (LayoutId, Self::RequestLayoutState) {
108        let image_cache = self.image_cache_provider.provide(window, cx);
109        window.with_image_cache(Some(image_cache), |window| {
110            let child_layout_ids = self
111                .children
112                .iter_mut()
113                .map(|child| child.request_layout(window, cx))
114                .collect::<SmallVec<_>>();
115            let mut style = Style::default();
116            style.refine(&self.style);
117            let layout_id = window.request_layout(style, child_layout_ids.iter().copied(), cx);
118            (layout_id, child_layout_ids)
119        })
120    }
121
122    fn prepaint(
123        &mut self,
124        _id: Option<&GlobalElementId>,
125        _inspector_id: Option<&InspectorElementId>,
126        _bounds: Bounds<Pixels>,
127        _request_layout: &mut Self::RequestLayoutState,
128        window: &mut Window,
129        cx: &mut App,
130    ) -> Self::PrepaintState {
131        for child in &mut self.children {
132            child.prepaint(window, cx);
133        }
134    }
135
136    fn paint(
137        &mut self,
138        _id: Option<&GlobalElementId>,
139        _inspector_id: Option<&InspectorElementId>,
140        _bounds: Bounds<Pixels>,
141        _request_layout: &mut Self::RequestLayoutState,
142        _prepaint: &mut Self::PrepaintState,
143        window: &mut Window,
144        cx: &mut App,
145    ) {
146        let image_cache = self.image_cache_provider.provide(window, cx);
147        window.with_image_cache(Some(image_cache), |window| {
148            for child in &mut self.children {
149                child.paint(window, cx);
150            }
151        })
152    }
153}
154
155/// Owns an image load and its cached result.
156///
157/// Dropping the entry cancels a pending load. Image caches must remove loaded
158/// images from windows before discarding the entry.
159pub struct ImageCacheItem(CachedLoad<Result<Arc<RenderImage>, ImageCacheError>>);
160
161impl std::fmt::Debug for ImageCacheItem {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.debug_struct("ImageCacheItem")
164            .field("result", &self.get())
165            .finish()
166    }
167}
168
169impl ImageCacheItem {
170    /// Starts loading an image into a new cache entry.
171    pub fn new(source: &Resource, cx: &mut App) -> Self {
172        let future = AssetLogger::<ImageAssetLoader>::load(source.clone(), cx);
173        Self(CachedLoad::new(future, cx))
174    }
175
176    /// Returns the cached result without subscribing to completion notifications.
177    pub fn get(&self) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
178        self.0.get()
179    }
180
181    /// Returns the cached result or subscribes the current view to completion.
182    pub fn use_image(&self, window: &Window) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
183        self.0.use_by(window.current_view())
184    }
185}
186
187/// An object that can handle the caching and unloading of images.
188/// Implementations of this trait should ensure that images are removed from all windows when they are no longer needed.
189pub trait ImageCache: 'static {
190    /// Load an image given a resource
191    /// returns the result of loading the image if it has finished loading, or None if it is still loading
192    fn load(
193        &mut self,
194        resource: &Resource,
195        window: &mut Window,
196        cx: &mut App,
197    ) -> Option<Result<Arc<RenderImage>, ImageCacheError>>;
198}
199
200/// An object that can create an ImageCache during the render phase.
201/// See the ImageCache trait for more information.
202pub trait ImageCacheProvider: 'static {
203    /// Called during the request_layout phase to create an ImageCache.
204    fn provide(&mut self, _window: &mut Window, _cx: &mut App) -> AnyImageCache;
205}
206
207impl<T: ImageCache> ImageCacheProvider for Entity<T> {
208    fn provide(&mut self, _window: &mut Window, _cx: &mut App) -> AnyImageCache {
209        self.clone().into()
210    }
211}
212
213/// An implementation of ImageCache, that uses an LRU caching strategy to unload images when the cache is full
214pub struct RetainAllImageCache(HashMap<u64, ImageCacheItem>);
215
216impl fmt::Debug for RetainAllImageCache {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        f.debug_struct("HashMapImageCache")
219            .field("num_images", &self.0.len())
220            .finish()
221    }
222}
223
224impl RetainAllImageCache {
225    /// Create a new image cache.
226    #[inline]
227    pub fn new(cx: &mut App) -> Entity<Self> {
228        let e = cx.new(|_cx| RetainAllImageCache(HashMap::new()));
229        cx.observe_release(&e, |image_cache, cx| {
230            for (_, item) in std::mem::replace(&mut image_cache.0, HashMap::new()) {
231                if let Some(Ok(image)) = item.get() {
232                    cx.drop_image(image, None);
233                }
234            }
235        })
236        .detach();
237        e
238    }
239
240    /// Load an image from the given source.
241    ///
242    /// Returns `None` if the image is loading.
243    pub fn load(
244        &mut self,
245        source: &Resource,
246        window: &mut Window,
247        cx: &mut App,
248    ) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
249        let hash = hash(source);
250
251        self.0
252            .entry(hash)
253            .or_insert_with(|| ImageCacheItem::new(source, cx))
254            .use_image(window)
255    }
256
257    /// Clear the image cache.
258    pub fn clear(&mut self, window: &mut Window, cx: &mut App) {
259        for (_, item) in std::mem::replace(&mut self.0, HashMap::new()) {
260            if let Some(Ok(image)) = item.get() {
261                cx.drop_image(image, Some(window));
262            }
263        }
264    }
265
266    /// Remove the image from the cache by the given source.
267    pub fn remove(&mut self, source: &Resource, window: &mut Window, cx: &mut App) {
268        let hash = hash(source);
269        if let Some(item) = self.0.remove(&hash)
270            && let Some(Ok(image)) = item.get()
271        {
272            cx.drop_image(image, Some(window));
273        }
274    }
275
276    /// Returns the number of images in the cache.
277    pub fn len(&self) -> usize {
278        self.0.len()
279    }
280
281    /// Returns true if the cache is empty.
282    pub fn is_empty(&self) -> bool {
283        self.0.is_empty()
284    }
285}
286
287impl ImageCache for RetainAllImageCache {
288    fn load(
289        &mut self,
290        resource: &Resource,
291        window: &mut Window,
292        cx: &mut App,
293    ) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
294        RetainAllImageCache::load(self, resource, window, cx)
295    }
296}
297
298/// Constructs a retain-all image cache that uses the element state associated with the given ID.
299pub fn retain_all(id: impl Into<ElementId>) -> RetainAllImageCacheProvider {
300    RetainAllImageCacheProvider { id: id.into() }
301}
302
303/// A provider struct for creating a retain-all image cache inline
304pub struct RetainAllImageCacheProvider {
305    id: ElementId,
306}
307
308impl ImageCacheProvider for RetainAllImageCacheProvider {
309    fn provide(&mut self, window: &mut Window, cx: &mut App) -> AnyImageCache {
310        window
311            .with_global_id(self.id.clone(), |global_id, window| {
312                window.with_element_state::<Entity<RetainAllImageCache>, _>(
313                    global_id,
314                    |cache, _window| {
315                        let cache = cache.unwrap_or_else(|| RetainAllImageCache::new(cx));
316                        (cache.clone(), cache)
317                    },
318                )
319            })
320            .into()
321    }
322}