BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / image_memory.rs

image_memory.rs

image_memory.rs 8.5 KiB Download Raw
1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use gpui_kit::{
7 App, AppContext, Entity, EntityId, Global, ImageCacheError, ImageCacheItem, ImageSource, RenderImage, Resource,
8 Window, hash,
9};
10use image::imageops::FilterType;
11use image::{Frame, ImageFormat, ImageReader};
12
13const BUDGET_BYTES: u64 = 48 * MEGABYTE;
14const KEEP_RECENT: Duration = Duration::from_secs(10);
15const REPORT_EVERY: Duration = Duration::from_secs(60);
16const MEGABYTE: u64 = 1024 * 1024;
17const PREVIEW_EDGE: u32 = 720;
18
19/// An image source whose decoded pixels are freed again once the image has been off screen for a while and the budget is full.
20pub fn bounded(source: impl Into<ImageSource>) -> ImageSource {
21 match source.into() {
22 ImageSource::Resource(resource) => {
23 ImageSource::Custom(Arc::new(move |window, cx| load(Request::Full(&resource), window, cx)))
24 }
25 other => other,
26 }
27}
28
29/// Like [`bounded`], but a still picture is decoded scaled down to at most [`PREVIEW_EDGE`] pixels, for thumbnails of full-size photos.
30pub fn preview(path: PathBuf) -> ImageSource {
31 let path: Arc<Path> = path.into();
32 ImageSource::Custom(Arc::new(move |window, cx| load(Request::Preview(&path), window, cx)))
33}
34
35#[derive(Clone, Copy)]
36enum Request<'a> {
37 Full(&'a Resource),
38 Preview(&'a Arc<Path>),
39}
40
41struct SharedImages(Entity<BoundedImages>);
42
43impl Global for SharedImages {}
44
45fn load(request: Request, window: &mut Window, cx: &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
46 let images = match cx.try_global::<SharedImages>() {
47 Some(shared) => shared.0.clone(),
48 None => {
49 let images = cx.new(|_| BoundedImages::default());
50 cx.set_global(SharedImages(images.clone()));
51 images
52 }
53 };
54 let handle = images.clone();
55 images.update(cx, |images, cx| images.load(request, &handle, window, cx))
56}
57
58enum Pixels {
59 Item(ImageCacheItem),
60 Decoding { waiting: Vec<EntityId> },
61 Decoded(Arc<RenderImage>),
62}
63
64struct Entry {
65 pixels: Pixels,
66 last_use: Instant,
67 bytes: u64,
68}
69
70#[derive(Default)]
71struct BoundedImages {
72 entries: HashMap<u64, Entry>,
73 freed_bytes: u64,
74 last_report: Option<Instant>,
75}
76
77impl BoundedImages {
78 fn load(
79 &mut self,
80 request: Request,
81 handle: &Entity<Self>,
82 window: &mut Window,
83 cx: &mut App,
84 ) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
85 let now = Instant::now();
86 let key = match request {
87 Request::Full(resource) => hash(resource),
88 Request::Preview(path) => hash(&(path, PREVIEW_EDGE)),
89 };
90 let entry = self.entries.entry(key).or_insert_with(|| Entry {
91 pixels: match request {
92 Request::Full(resource) => Pixels::Item(ImageCacheItem::new(resource, cx)),
93 Request::Preview(path) => {
94 start_preview(handle, key, path.clone(), cx);
95 Pixels::Decoding { waiting: Vec::new() }
96 }
97 },
98 last_use: now,
99 bytes: 0,
100 });
101 entry.last_use = now;
102 let result = match &mut entry.pixels {
103 Pixels::Item(item) => item.use_image(window),
104 Pixels::Decoding { waiting } => {
105 let view = window.current_view();
106 if !waiting.contains(&view) {
107 waiting.push(view);
108 }
109 None
110 }
111 Pixels::Decoded(image) => Some(Ok(image.clone())),
112 };
113 if entry.bytes == 0
114 && let Some(Ok(image)) = &result
115 {
116 entry.bytes = decoded_bytes(image);
117 self.trim(now);
118 }
119 result
120 }
121
122 fn finish_preview(&mut self, key: u64, path: Arc<Path>, decoded: Option<RenderImage>, cx: &mut App) {
123 let Some(entry) = self.entries.get_mut(&key) else {
124 return;
125 };
126 let pixels = match decoded {
127 Some(image) => Pixels::Decoded(Arc::new(image)),
128 None => Pixels::Item(ImageCacheItem::new(&Resource::Path(path), cx)),
129 };
130 if let Pixels::Decoding { waiting } = std::mem::replace(&mut entry.pixels, pixels) {
131 for view in waiting {
132 cx.notify(view);
133 }
134 }
135 }
136
137 fn trim(&mut self, now: Instant) {
138 let sizes: Vec<(u64, Instant, u64)> =
139 self.entries.iter().map(|(key, entry)| (*key, entry.last_use, entry.bytes)).collect();
140 let mut freed_bytes = 0;
141 for key in evictions(sizes, now) {
142 freed_bytes += self.entries.remove(&key).map_or(0, |entry| entry.bytes);
143 }
144 self.freed_bytes += freed_bytes;
145 if self.last_report.is_none_or(|last| now.duration_since(last) >= REPORT_EVERY) {
146 self.last_report = Some(now);
147 let kept_bytes: u64 = self.entries.values().map(|entry| entry.bytes).sum();
148 app_base::diagnostics::record(&format!(
149 "images: {} kept ({} MB), {} MB freed so far",
150 self.entries.len(),
151 kept_bytes / MEGABYTE,
152 self.freed_bytes / MEGABYTE
153 ));
154 }
155 }
156}
157
158fn start_preview(handle: &Entity<BoundedImages>, key: u64, path: Arc<Path>, cx: &mut App) {
159 let images = handle.downgrade();
160 cx.spawn(async move |cx| {
161 let source = path.clone();
162 let decoded = cx.background_executor().spawn(async move { decode_preview(&source) }).await;
163 images.update(cx, |images, cx| images.finish_preview(key, path, decoded, cx)).ok();
164 })
165 .detach();
166}
167
168fn decode_preview(path: &Path) -> Option<RenderImage> {
169 let reader = ImageReader::open(path).ok()?.with_guessed_format().ok()?;
170 if !matches!(reader.format()?, ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Bmp) {
171 return None;
172 }
173 let decoded = reader.decode().ok()?;
174 let scaled = if decoded.width().max(decoded.height()) > PREVIEW_EDGE {
175 decoded.resize(PREVIEW_EDGE, PREVIEW_EDGE, FilterType::Triangle)
176 } else {
177 decoded
178 };
179 let mut pixels = scaled.to_rgba8();
180 for pixel in pixels.chunks_exact_mut(4) {
181 pixel.swap(0, 2);
182 }
183 Some(RenderImage::new(vec![Frame::new(pixels)]))
184}
185
186fn decoded_bytes(image: &RenderImage) -> u64 {
187 (0..image.frame_count())
188 .map(|frame| {
189 let size = image.size(frame);
190 u64::from(size.width.0.max(0) as u32) * u64::from(size.height.0.max(0) as u32) * 4
191 })
192 .sum::<u64>()
193 .max(1)
194}
195
196fn evictions(mut sizes: Vec<(u64, Instant, u64)>, now: Instant) -> Vec<u64> {
197 let mut total: u64 = sizes.iter().map(|(_, _, bytes)| bytes).sum();
198 sizes.sort_by_key(|(_, last_use, _)| *last_use);
199 let mut evicted = Vec::new();
200 for (key, last_use, bytes) in sizes {
201 if total <= BUDGET_BYTES || now.duration_since(last_use) < KEEP_RECENT {
202 break;
203 }
204 total -= bytes;
205 evicted.push(key);
206 }
207 evicted
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 #[test]
215 fn the_oldest_images_go_until_the_rest_fits() {
216 let now = Instant::now() + Duration::from_secs(600);
217 let sizes = vec![
218 (1, now - Duration::from_secs(300), 40 * MEGABYTE),
219 (2, now - Duration::from_secs(200), 30 * MEGABYTE),
220 (3, now - Duration::from_secs(100), 20 * MEGABYTE),
221 ];
222 assert_eq!(evictions(sizes, now), vec![1, 2]);
223 }
224
225 #[test]
226 fn images_shown_just_now_stay_even_over_budget() {
227 let now = Instant::now() + Duration::from_secs(600);
228 let sizes = vec![(1, now - Duration::from_secs(2), 50 * MEGABYTE), (2, now, 50 * MEGABYTE)];
229 assert!(evictions(sizes, now).is_empty());
230 }
231
232 #[test]
233 fn nothing_goes_under_budget() {
234 let now = Instant::now() + Duration::from_secs(600);
235 assert!(evictions(vec![(1, now - Duration::from_secs(300), MEGABYTE)], now).is_empty());
236 }
237
238 #[test]
239 fn a_large_photo_is_decoded_scaled_down_and_an_animation_is_left_to_gpui() {
240 let directory = tempfile::tempdir().unwrap();
241 let photo = directory.path().join("photo");
242 image::RgbaImage::new(3000, 2000).save_with_format(&photo, ImageFormat::Png).unwrap();
243 let decoded = decode_preview(&photo).unwrap();
244 assert_eq!((decoded.size(0).width.0, decoded.size(0).height.0), (720, 480));
245 let animation = directory.path().join("animation");
246 image::RgbaImage::new(10, 10).save_with_format(&animation, ImageFormat::Gif).unwrap();
247 assert!(decode_preview(&animation).is_none());
248 }
249}