BlueGit

ict rusty-teams

Files

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

image_memory.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
image_memory.rs 8.9 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,
8 RenderImage, Resource, 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) => ImageSource::Custom(Arc::new(move |window, cx| {
23 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| {
33 load(Request::Preview(&path), window, cx)
34 }))
35}
36
37#[derive(Clone, Copy)]
38enum Request<'a> {
39 Full(&'a Resource),
40 Preview(&'a Arc<Path>),
41}
42
43struct SharedImages(Entity<BoundedImages>);
44
45impl Global for SharedImages {}
46
47fn load(
48 request: Request,
49 window: &mut Window,
50 cx: &mut App,
51) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
52 let images = match cx.try_global::<SharedImages>() {
53 Some(shared) => shared.0.clone(),
54 None => {
55 let images = cx.new(|_| BoundedImages::default());
56 cx.set_global(SharedImages(images.clone()));
57 images
58 }
59 };
60 let handle = images.clone();
61 images.update(cx, |images, cx| images.load(request, &handle, window, cx))
62}
63
64enum Pixels {
65 Item(ImageCacheItem),
66 Decoding { waiting: Vec<EntityId> },
67 Decoded(Arc<RenderImage>),
68}
69
70struct Entry {
71 pixels: Pixels,
72 last_use: Instant,
73 bytes: u64,
74}
75
76#[derive(Default)]
77struct BoundedImages {
78 entries: HashMap<u64, Entry>,
79 freed_bytes: u64,
80 last_report: Option<Instant>,
81}
82
83impl BoundedImages {
84 fn load(
85 &mut self,
86 request: Request,
87 handle: &Entity<Self>,
88 window: &mut Window,
89 cx: &mut App,
90 ) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
91 let now = Instant::now();
92 let key = match request {
93 Request::Full(resource) => hash(resource),
94 Request::Preview(path) => hash(&(path, PREVIEW_EDGE)),
95 };
96 let entry = self.entries.entry(key).or_insert_with(|| Entry {
97 pixels: match request {
98 Request::Full(resource) => Pixels::Item(ImageCacheItem::new(resource, cx)),
99 Request::Preview(path) => {
100 start_preview(handle, key, path.clone(), cx);
101 Pixels::Decoding {
102 waiting: Vec::new(),
103 }
104 }
105 },
106 last_use: now,
107 bytes: 0,
108 });
109 entry.last_use = now;
110 let result = match &mut entry.pixels {
111 Pixels::Item(item) => item.use_image(window),
112 Pixels::Decoding { waiting } => {
113 let view = window.current_view();
114 if !waiting.contains(&view) {
115 waiting.push(view);
116 }
117 None
118 }
119 Pixels::Decoded(image) => Some(Ok(image.clone())),
120 };
121 if entry.bytes == 0
122 && let Some(Ok(image)) = &result
123 {
124 entry.bytes = decoded_bytes(image);
125 self.trim(now);
126 }
127 result
128 }
129
130 fn finish_preview(
131 &mut self,
132 key: u64,
133 path: Arc<Path>,
134 decoded: Option<RenderImage>,
135 cx: &mut App,
136 ) {
137 let Some(entry) = self.entries.get_mut(&key) else {
138 return;
139 };
140 let pixels = match decoded {
141 Some(image) => Pixels::Decoded(Arc::new(image)),
142 None => Pixels::Item(ImageCacheItem::new(&Resource::Path(path), cx)),
143 };
144 if let Pixels::Decoding { waiting } = std::mem::replace(&mut entry.pixels, pixels) {
145 for view in waiting {
146 cx.notify(view);
147 }
148 }
149 }
150
151 fn trim(&mut self, now: Instant) {
152 let sizes: Vec<(u64, Instant, u64)> = self
153 .entries
154 .iter()
155 .map(|(key, entry)| (*key, entry.last_use, entry.bytes))
156 .collect();
157 let mut freed_bytes = 0;
158 for key in evictions(sizes, now) {
159 freed_bytes += self.entries.remove(&key).map_or(0, |entry| entry.bytes);
160 }
161 self.freed_bytes += freed_bytes;
162 if self
163 .last_report
164 .is_none_or(|last| now.duration_since(last) >= REPORT_EVERY)
165 {
166 self.last_report = Some(now);
167 let kept_bytes: u64 = self.entries.values().map(|entry| entry.bytes).sum();
168 app_base::diagnostics::record(&format!(
169 "images: {} kept ({} MB), {} MB freed so far",
170 self.entries.len(),
171 kept_bytes / MEGABYTE,
172 self.freed_bytes / MEGABYTE
173 ));
174 }
175 }
176}
177
178fn start_preview(handle: &Entity<BoundedImages>, key: u64, path: Arc<Path>, cx: &mut App) {
179 let images = handle.downgrade();
180 cx.spawn(async move |cx| {
181 let source = path.clone();
182 let decoded = cx
183 .background_executor()
184 .spawn(async move { decode_preview(&source) })
185 .await;
186 images
187 .update(cx, |images, cx| {
188 images.finish_preview(key, path, decoded, cx)
189 })
190 .ok();
191 })
192 .detach();
193}
194
195fn decode_preview(path: &Path) -> Option<RenderImage> {
196 let reader = ImageReader::open(path).ok()?.with_guessed_format().ok()?;
197 if !matches!(
198 reader.format()?,
199 ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Bmp
200 ) {
201 return None;
202 }
203 let decoded = reader.decode().ok()?;
204 let scaled = if decoded.width().max(decoded.height()) > PREVIEW_EDGE {
205 decoded.resize(PREVIEW_EDGE, PREVIEW_EDGE, FilterType::Triangle)
206 } else {
207 decoded
208 };
209 let mut pixels = scaled.to_rgba8();
210 for pixel in pixels.chunks_exact_mut(4) {
211 pixel.swap(0, 2);
212 }
213 Some(RenderImage::new(vec![Frame::new(pixels)]))
214}
215
216fn decoded_bytes(image: &RenderImage) -> u64 {
217 (0..image.frame_count())
218 .map(|frame| {
219 let size = image.size(frame);
220 u64::from(size.width.0.max(0) as u32) * u64::from(size.height.0.max(0) as u32) * 4
221 })
222 .sum::<u64>()
223 .max(1)
224}
225
226fn evictions(mut sizes: Vec<(u64, Instant, u64)>, now: Instant) -> Vec<u64> {
227 let mut total: u64 = sizes.iter().map(|(_, _, bytes)| bytes).sum();
228 sizes.sort_by_key(|(_, last_use, _)| *last_use);
229 let mut evicted = Vec::new();
230 for (key, last_use, bytes) in sizes {
231 if total <= BUDGET_BYTES || now.duration_since(last_use) < KEEP_RECENT {
232 break;
233 }
234 total -= bytes;
235 evicted.push(key);
236 }
237 evicted
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn the_oldest_images_go_until_the_rest_fits() {
246 let now = Instant::now() + Duration::from_secs(600);
247 let sizes = vec![
248 (1, now - Duration::from_secs(300), 40 * MEGABYTE),
249 (2, now - Duration::from_secs(200), 30 * MEGABYTE),
250 (3, now - Duration::from_secs(100), 20 * MEGABYTE),
251 ];
252 assert_eq!(evictions(sizes, now), vec![1, 2]);
253 }
254
255 #[test]
256 fn images_shown_just_now_stay_even_over_budget() {
257 let now = Instant::now() + Duration::from_secs(600);
258 let sizes = vec![
259 (1, now - Duration::from_secs(2), 50 * MEGABYTE),
260 (2, now, 50 * MEGABYTE),
261 ];
262 assert!(evictions(sizes, now).is_empty());
263 }
264
265 #[test]
266 fn nothing_goes_under_budget() {
267 let now = Instant::now() + Duration::from_secs(600);
268 assert!(evictions(vec![(1, now - Duration::from_secs(300), MEGABYTE)], now).is_empty());
269 }
270
271 #[test]
272 fn a_large_photo_is_decoded_scaled_down_and_an_animation_is_left_to_gpui() {
273 let directory = tempfile::tempdir().unwrap();
274 let photo = directory.path().join("photo");
275 image::RgbaImage::new(3000, 2000)
276 .save_with_format(&photo, ImageFormat::Png)
277 .unwrap();
278 let decoded = decode_preview(&photo).unwrap();
279 assert_eq!(
280 (decoded.size(0).width.0, decoded.size(0).height.0),
281 (720, 480)
282 );
283 let animation = directory.path().join("animation");
284 image::RgbaImage::new(10, 10)
285 .save_with_format(&animation, ImageFormat::Gif)
286 .unwrap();
287 assert!(decode_preview(&animation).is_none());
288 }
289}