| 1 | use std::collections::HashMap; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use gpui_kit::{ |
| 6 | App, AppContext, Entity, Global, ImageCacheError, ImageCacheItem, ImageSource, RenderImage, Resource, Window, |
| 7 | hash, |
| 8 | }; |
| 9 | |
| 10 | const BUDGET_BYTES: u64 = 64 * 1024 * 1024; |
| 11 | const KEEP_RECENT: Duration = Duration::from_secs(10); |
| 12 | |
| 13 | /// An image source whose decoded pixels are freed again once the image has been off screen for a while and the budget is full. |
| 14 | pub fn bounded(source: impl Into<ImageSource>) -> ImageSource { |
| 15 | match source.into() { |
| 16 | ImageSource::Resource(resource) => ImageSource::Custom(Arc::new(move |window, cx| load(&resource, window, cx))), |
| 17 | other => other, |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | struct SharedImages(Entity<BoundedImages>); |
| 22 | |
| 23 | impl Global for SharedImages {} |
| 24 | |
| 25 | fn load(resource: &Resource, window: &mut Window, cx: &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>> { |
| 26 | let images = match cx.try_global::<SharedImages>() { |
| 27 | Some(shared) => shared.0.clone(), |
| 28 | None => { |
| 29 | let images = cx.new(|_| BoundedImages::default()); |
| 30 | cx.set_global(SharedImages(images.clone())); |
| 31 | images |
| 32 | } |
| 33 | }; |
| 34 | images.update(cx, |images, cx| images.load(resource, window, cx)) |
| 35 | } |
| 36 | |
| 37 | struct Entry { |
| 38 | item: ImageCacheItem, |
| 39 | last_use: Instant, |
| 40 | bytes: u64, |
| 41 | } |
| 42 | |
| 43 | #[derive(Default)] |
| 44 | struct BoundedImages { |
| 45 | entries: HashMap<u64, Entry>, |
| 46 | } |
| 47 | |
| 48 | impl BoundedImages { |
| 49 | fn load(&mut self, resource: &Resource, window: &mut Window, cx: &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>> { |
| 50 | let now = Instant::now(); |
| 51 | let key = hash(resource); |
| 52 | let entry = self.entries.entry(key).or_insert_with(|| Entry { item: ImageCacheItem::new(resource, cx), last_use: now, bytes: 0 }); |
| 53 | entry.last_use = now; |
| 54 | let result = entry.item.use_image(window); |
| 55 | if entry.bytes == 0 |
| 56 | && let Some(Ok(image)) = &result |
| 57 | { |
| 58 | entry.bytes = decoded_bytes(image); |
| 59 | self.trim(now); |
| 60 | } |
| 61 | result |
| 62 | } |
| 63 | |
| 64 | fn trim(&mut self, now: Instant) { |
| 65 | let sizes: Vec<(u64, Instant, u64)> = |
| 66 | self.entries.iter().map(|(key, entry)| (*key, entry.last_use, entry.bytes)).collect(); |
| 67 | for key in evictions(sizes, now) { |
| 68 | self.entries.remove(&key); |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | fn decoded_bytes(image: &RenderImage) -> u64 { |
| 74 | (0..image.frame_count()) |
| 75 | .map(|frame| { |
| 76 | let size = image.size(frame); |
| 77 | u64::from(size.width.0.max(0) as u32) * u64::from(size.height.0.max(0) as u32) * 4 |
| 78 | }) |
| 79 | .sum::<u64>() |
| 80 | .max(1) |
| 81 | } |
| 82 | |
| 83 | fn evictions(mut sizes: Vec<(u64, Instant, u64)>, now: Instant) -> Vec<u64> { |
| 84 | let mut total: u64 = sizes.iter().map(|(_, _, bytes)| bytes).sum(); |
| 85 | sizes.sort_by_key(|(_, last_use, _)| *last_use); |
| 86 | let mut evicted = Vec::new(); |
| 87 | for (key, last_use, bytes) in sizes { |
| 88 | if total <= BUDGET_BYTES || now.duration_since(last_use) < KEEP_RECENT { |
| 89 | break; |
| 90 | } |
| 91 | total -= bytes; |
| 92 | evicted.push(key); |
| 93 | } |
| 94 | evicted |
| 95 | } |
| 96 | |
| 97 | #[cfg(test)] |
| 98 | mod tests { |
| 99 | use super::*; |
| 100 | |
| 101 | const MEGABYTE: u64 = 1024 * 1024; |
| 102 | |
| 103 | #[test] |
| 104 | fn the_oldest_images_go_until_the_rest_fits() { |
| 105 | let now = Instant::now() + Duration::from_secs(600); |
| 106 | let sizes = vec![ |
| 107 | (1, now - Duration::from_secs(300), 40 * MEGABYTE), |
| 108 | (2, now - Duration::from_secs(200), 30 * MEGABYTE), |
| 109 | (3, now - Duration::from_secs(100), 20 * MEGABYTE), |
| 110 | ]; |
| 111 | assert_eq!(evictions(sizes, now), vec![1]); |
| 112 | } |
| 113 | |
| 114 | #[test] |
| 115 | fn images_shown_just_now_stay_even_over_budget() { |
| 116 | let now = Instant::now() + Duration::from_secs(600); |
| 117 | let sizes = vec![(1, now - Duration::from_secs(2), 50 * MEGABYTE), (2, now, 50 * MEGABYTE)]; |
| 118 | assert!(evictions(sizes, now).is_empty()); |
| 119 | } |
| 120 | |
| 121 | #[test] |
| 122 | fn nothing_goes_under_budget() { |
| 123 | let now = Instant::now() + Duration::from_secs(600); |
| 124 | assert!(evictions(vec![(1, now - Duration::from_secs(300), MEGABYTE)], now).is_empty()); |
| 125 | } |
| 126 | } |