fix(app): free decoded chat images beyond a 64 MB budget
- Chat images, previews, cards, GIFs and the viewer load through a bounded cache - Least recently shown images are freed once the budget is full; ones shown in the last 10 s stay Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use std::collections::HashMap;
2
3
use std::rc::Rc;
3
4
@@ -228,7 +229,7 @@ fn background_layer(url: &str, radius: f32) -> AnyElement {
228
229
.rounded(px(radius))
229
230
.overflow_hidden()
230
231
.child(
231
img(url.to_owned())
232
img(bounded(url.to_owned()))
232
233
.size_full()
233
234
.object_fit(ObjectFit::Cover)
234
235
.with_loading(|| div().into_any_element())
@@ -699,7 +700,7 @@ fn image_view(image: &CardImage, id: &str) -> AnyElement {
699
700
frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))
700
701
})
701
702
.child(
702
img(image.url.clone())
703
img(bounded(image.url.clone()))
703
704
.size_full()
704
705
.rounded(radius)
705
706
.object_fit(ObjectFit::Cover)
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use std::collections::HashMap;2
use std::collections::HashMap;2
use std::rc::Rc;3
use std::rc::Rc;3
4
@@ -228,7 +229,7 @@ fn background_layer(url: &str, radius: f32) -> AnyElement {228
.rounded(px(radius))229
.rounded(px(radius))229
.overflow_hidden()230
.overflow_hidden()230
.child(231
.child(231
img(url.to_owned())232
img(bounded(url.to_owned()))232
.size_full()233
.size_full()233
.object_fit(ObjectFit::Cover)234
.object_fit(ObjectFit::Cover)234
.with_loading(|| div().into_any_element())235
.with_loading(|| div().into_any_element())@@ -699,7 +700,7 @@ fn image_view(image: &CardImage, id: &str) -> AnyElement {699
frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))700
frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))700
})701
})701
.child(702
.child(702
img(image.url.clone())703
img(bounded(image.url.clone()))703
.size_full()704
.size_full()704
.rounded(radius)705
.rounded(radius)705
.object_fit(ObjectFit::Cover)706
.object_fit(ObjectFit::Cover)@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use gpui_kit::*;
2
3
use teams_core::{AnnouncementBanner, BannerBackground};
3
4
@@ -52,7 +53,7 @@ pub fn banner_frame(background: &BannerBackground, directory: &Directory) -> Div
52
53
BannerBackground::LocalImage(path) => frame
53
54
.bg(banner_fill(""))
54
55
.child(
55
img(std::path::PathBuf::from(path))
56
img(bounded(std::path::PathBuf::from(path)))
56
57
.absolute()
57
58
.inset_0()
58
59
.size_full()
@@ -64,7 +65,7 @@ pub fn banner_frame(background: &BannerBackground, directory: &Directory) -> Div
64
65
match directory.image(url) {
65
66
Some(entry) => frame
66
67
.child(
67
img(entry.path.clone())
68
img(bounded(entry.path.clone()))
68
69
.absolute()
69
70
.inset_0()
70
71
.size_full()
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use gpui_kit::*;2
use gpui_kit::*;2
use teams_core::{AnnouncementBanner, BannerBackground};3
use teams_core::{AnnouncementBanner, BannerBackground};3
4
@@ -52,7 +53,7 @@ pub fn banner_frame(background: &BannerBackground, directory: &Directory) -> Div52
BannerBackground::LocalImage(path) => frame53
BannerBackground::LocalImage(path) => frame53
.bg(banner_fill(""))54
.bg(banner_fill(""))54
.child(55
.child(55
img(std::path::PathBuf::from(path))56
img(bounded(std::path::PathBuf::from(path)))56
.absolute()57
.absolute()57
.inset_0()58
.inset_0()58
.size_full()59
.size_full()@@ -64,7 +65,7 @@ pub fn banner_frame(background: &BannerBackground, directory: &Directory) -> Div64
match directory.image(url) {65
match directory.image(url) {65
Some(entry) => frame66
Some(entry) => frame66
.child(67
.child(67
img(entry.path.clone())68
img(bounded(entry.path.clone()))68
.absolute()69
.absolute()69
.inset_0()70
.inset_0()70
.size_full()71
.size_full()@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use std::rc::Rc;
2
3
3
4
use gpui_kit::assets::IconName;
@@ -116,7 +117,7 @@ fn image_view(
116
117
let frame = frame
117
118
.cursor_pointer()
118
119
.child(
119
img(entry.path.clone())
120
img(bounded(entry.path.clone()))
120
121
.id(image_id)
121
122
.size_full()
122
123
.rounded(px(IMAGE_RADIUS))
@@ -200,7 +201,7 @@ fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
200
201
.rounded(px(IMAGE_RADIUS))
201
202
.overflow_hidden()
202
203
.child(
203
img(image.image.clone())
204
img(bounded(image.image.clone()))
204
205
.id(image_id)
205
206
.size_full()
206
207
.rounded(px(IMAGE_RADIUS))
@@ -266,8 +267,8 @@ fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stat
266
267
let frame = match image {
267
268
Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => frame
268
269
.bg(theme::white())
269
.child(img(path).w_full().h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO)).object_fit(ObjectFit::Cover)),
270
Some(path) => frame.child(img(path).size_full().object_fit(match card.kind {
270
.child(img(bounded(path)).w_full().h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO)).object_fit(ObjectFit::Cover)),
271
Some(path) => frame.child(img(bounded(path)).size_full().object_fit(match card.kind {
271
272
FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,
272
273
_ => ObjectFit::Contain,
273
274
})),
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use std::rc::Rc;2
use std::rc::Rc;2
3
3
use gpui_kit::assets::IconName;4
use gpui_kit::assets::IconName;@@ -116,7 +117,7 @@ fn image_view(116
let frame = frame117
let frame = frame117
.cursor_pointer()118
.cursor_pointer()118
.child(119
.child(119
img(entry.path.clone())120
img(bounded(entry.path.clone()))120
.id(image_id)121
.id(image_id)121
.size_full()122
.size_full()122
.rounded(px(IMAGE_RADIUS))123
.rounded(px(IMAGE_RADIUS))@@ -200,7 +201,7 @@ fn local_image_view(image: &LocalImage, id: String) -> AnyElement {200
.rounded(px(IMAGE_RADIUS))201
.rounded(px(IMAGE_RADIUS))201
.overflow_hidden()202
.overflow_hidden()202
.child(203
.child(203
img(image.image.clone())204
img(bounded(image.image.clone()))204
.id(image_id)205
.id(image_id)205
.size_full()206
.size_full()206
.rounded(px(IMAGE_RADIUS))207
.rounded(px(IMAGE_RADIUS))@@ -266,8 +267,8 @@ fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stat266
let frame = match image {267
let frame = match image {267
Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => frame268
Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => frame268
.bg(theme::white())269
.bg(theme::white())269
.child(img(path).w_full().h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO)).object_fit(ObjectFit::Cover)),270
.child(img(bounded(path)).w_full().h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO)).object_fit(ObjectFit::Cover)),270
Some(path) => frame.child(img(path).size_full().object_fit(match card.kind {271
Some(path) => frame.child(img(bounded(path)).size_full().object_fit(match card.kind {271
FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,272
FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,272
_ => ObjectFit::Contain,273
_ => ObjectFit::Contain,273
})),274
})),@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use gpui_kit::prelude::FluentBuilder as _;
2
3
use gpui_kit::*;
3
4
@@ -130,7 +131,7 @@ pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {
130
131
.rounded_full()
131
132
.overflow_hidden()
132
133
.child(
133
img(url.clone())
134
img(bounded(url.clone()))
134
135
.size_full()
135
136
.rounded_full()
136
137
.object_fit(ObjectFit::Cover)
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use gpui_kit::prelude::FluentBuilder as _;2
use gpui_kit::prelude::FluentBuilder as _;2
use gpui_kit::*;3
use gpui_kit::*;3
4
@@ -130,7 +131,7 @@ pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {130
.rounded_full()131
.rounded_full()131
.overflow_hidden()132
.overflow_hidden()132
.child(133
.child(133
img(url.clone())134
img(bounded(url.clone()))134
.size_full()135
.size_full()135
.rounded_full()136
.rounded_full()136
.object_fit(ObjectFit::Cover)137
.object_fit(ObjectFit::Cover)@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use std::path::PathBuf;
2
3
3
4
use calling::{CameraEffects, HoldState};
@@ -369,7 +370,7 @@ fn thumbnail(
369
370
.cursor_pointer()
370
371
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
371
372
.child(match path {
372
Some(path) => img(path)
373
Some(path) => img(bounded(path))
373
374
.size_full()
374
375
.object_fit(ObjectFit::Cover)
375
376
.into_any_element(),
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use std::path::PathBuf;2
use std::path::PathBuf;2
3
3
use calling::{CameraEffects, HoldState};4
use calling::{CameraEffects, HoldState};@@ -369,7 +370,7 @@ fn thumbnail(369
.cursor_pointer()370
.cursor_pointer()370
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))371
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))371
.child(match path {372
.child(match path {372
Some(path) => img(path)373
Some(path) => img(bounded(path))373
.size_full()374
.size_full()374
.object_fit(ObjectFit::Cover)375
.object_fit(ObjectFit::Cover)375
.into_any_element(),376
.into_any_element(),@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use gpui_kit::component::{h_flex, v_flex};
2
3
use gpui_kit::prelude::FluentBuilder as _;
3
4
use gpui_kit::*;
@@ -171,7 +172,7 @@ fn thumbnail_image(recording: &RecordingCard, directory: &Directory) -> AnyEleme
171
172
.as_ref()
172
173
.and_then(|thumbnail| directory.image(&thumbnail.url));
173
174
match image {
174
Some(entry) => img(entry.path.clone())
175
Some(entry) => img(bounded(entry.path.clone()))
175
176
.size_full()
176
177
.object_fit(ObjectFit::Cover)
177
178
.into_any_element(),
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;4
use gpui_kit::*;@@ -171,7 +172,7 @@ fn thumbnail_image(recording: &RecordingCard, directory: &Directory) -> AnyEleme171
.as_ref()172
.as_ref()172
.and_then(|thumbnail| directory.image(&thumbnail.url));173
.and_then(|thumbnail| directory.image(&thumbnail.url));173
match image {174
match image {174
Some(entry) => img(entry.path.clone())175
Some(entry) => img(bounded(entry.path.clone()))175
.size_full()176
.size_full()176
.object_fit(ObjectFit::Cover)177
.object_fit(ObjectFit::Cover)177
.into_any_element(),178
.into_any_element(),@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use gpui_kit::assets::IconName;
2
3
use gpui_kit::*;
3
4
use teams_core::{CardActionIcon, CardIcon, IconSize};
@@ -147,7 +148,7 @@ pub fn icon_view(card_icon: &CardIcon) -> AnyElement {
147
148
pub fn action_icon_view(action_icon: &CardActionIcon) -> AnyElement {
148
149
match action_icon {
149
150
CardActionIcon::Named(name) => glyph_view(name, ACTION_ICON_SIZE, theme::accent_text()),
150
CardActionIcon::Url(url) => img(url.clone())
151
CardActionIcon::Url(url) => img(bounded(url.clone()))
151
152
.size(px(ACTION_ICON_SIZE))
152
153
.flex_none()
153
154
.object_fit(ObjectFit::Contain)
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use gpui_kit::assets::IconName;2
use gpui_kit::assets::IconName;2
use gpui_kit::*;3
use gpui_kit::*;3
use teams_core::{CardActionIcon, CardIcon, IconSize};4
use teams_core::{CardActionIcon, CardIcon, IconSize};@@ -147,7 +148,7 @@ pub fn icon_view(card_icon: &CardIcon) -> AnyElement {147
pub fn action_icon_view(action_icon: &CardActionIcon) -> AnyElement {148
pub fn action_icon_view(action_icon: &CardActionIcon) -> AnyElement {148
match action_icon {149
match action_icon {149
CardActionIcon::Named(name) => glyph_view(name, ACTION_ICON_SIZE, theme::accent_text()),150
CardActionIcon::Named(name) => glyph_view(name, ACTION_ICON_SIZE, theme::accent_text()),150
CardActionIcon::Url(url) => img(url.clone())151
CardActionIcon::Url(url) => img(bounded(url.clone()))151
.size(px(ACTION_ICON_SIZE))152
.size(px(ACTION_ICON_SIZE))152
.flex_none()153
.flex_none()153
.object_fit(ObjectFit::Contain)154
.object_fit(ObjectFit::Contain)@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use gpui_kit::assets::IconName;
2
3
use gpui_kit::component::checkbox::Checkbox;
3
4
use gpui_kit::component::date_picker::DatePicker;
@@ -151,7 +152,7 @@ fn inline_action_view(
151
152
(Some(ActionPhase::Done), _) => {
152
153
symbol("done", INLINE_ICON_SIZE, theme::green()).into_any_element()
153
154
}
154
(_, Some(url)) if url.starts_with("https://") => img(url.clone())
155
(_, Some(url)) if url.starts_with("https://") => img(bounded(url.clone()))
155
156
.size(px(INLINE_ICON_SIZE))
156
157
.into_any_element(),
157
158
_ => {
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use gpui_kit::assets::IconName;2
use gpui_kit::assets::IconName;2
use gpui_kit::component::checkbox::Checkbox;3
use gpui_kit::component::checkbox::Checkbox;3
use gpui_kit::component::date_picker::DatePicker;4
use gpui_kit::component::date_picker::DatePicker;@@ -151,7 +152,7 @@ fn inline_action_view(151
(Some(ActionPhase::Done), _) => {152
(Some(ActionPhase::Done), _) => {152
symbol("done", INLINE_ICON_SIZE, theme::green()).into_any_element()153
symbol("done", INLINE_ICON_SIZE, theme::green()).into_any_element()153
}154
}154
(_, Some(url)) if url.starts_with("https://") => img(url.clone())155
(_, Some(url)) if url.starts_with("https://") => img(bounded(url.clone()))155
.size(px(INLINE_ICON_SIZE))156
.size(px(INLINE_ICON_SIZE))156
.into_any_element(),157
.into_any_element(),157
_ => {158
_ => {@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use gpui_kit::assets::IconName;
2
3
use gpui_kit::component::tooltip::Tooltip;
3
4
use gpui_kit::prelude::FluentBuilder as _;
@@ -76,7 +77,7 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
76
77
}
77
78
78
79
fn poster_image(url: String) -> Img {
79
img(url)
80
img(bounded(url))
80
81
.size_full()
81
82
.rounded(px(MEDIA_RADIUS))
82
83
.object_fit(ObjectFit::Cover)
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use gpui_kit::assets::IconName;2
use gpui_kit::assets::IconName;2
use gpui_kit::component::tooltip::Tooltip;3
use gpui_kit::component::tooltip::Tooltip;3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::prelude::FluentBuilder as _;@@ -76,7 +77,7 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {76
}77
}77
78
78
fn poster_image(url: String) -> Img {79
fn poster_image(url: String) -> Img {79
img(url)80
img(bounded(url))80
.size_full()81
.size_full()81
.rounded(px(MEDIA_RADIUS))82
.rounded(px(MEDIA_RADIUS))82
.object_fit(ObjectFit::Cover)83
.object_fit(ObjectFit::Cover)@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use std::rc::Rc;
2
3
use std::time::Duration;
3
4
@@ -519,7 +520,7 @@ impl FunPicker {
519
520
.cursor_pointer()
520
521
.hover(|tile| tile.opacity(0.85))
521
522
.child(
522
img(image_source(&gif.preview_url))
523
img(bounded(image_source(&gif.preview_url)))
523
524
.id(("fun-picker-gif-image", index))
524
525
.size_full()
525
526
.object_fit(ObjectFit::Cover),
@@ -639,7 +640,7 @@ impl FunPicker {
639
640
.cursor_pointer()
640
641
.hover(|tile| tile.bg(theme::border_strong()))
641
642
.child(
642
img(image_source(&sticker.url()))
643
img(bounded(image_source(&sticker.url())))
643
644
.size_full()
644
645
.object_fit(ObjectFit::Contain),
645
646
)
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use std::rc::Rc;2
use std::rc::Rc;2
use std::time::Duration;3
use std::time::Duration;3
4
@@ -519,7 +520,7 @@ impl FunPicker {519
.cursor_pointer()520
.cursor_pointer()520
.hover(|tile| tile.opacity(0.85))521
.hover(|tile| tile.opacity(0.85))521
.child(522
.child(522
img(image_source(&gif.preview_url))523
img(bounded(image_source(&gif.preview_url)))523
.id(("fun-picker-gif-image", index))524
.id(("fun-picker-gif-image", index))524
.size_full()525
.size_full()525
.object_fit(ObjectFit::Cover),526
.object_fit(ObjectFit::Cover),@@ -639,7 +640,7 @@ impl FunPicker {639
.cursor_pointer()640
.cursor_pointer()640
.hover(|tile| tile.bg(theme::border_strong()))641
.hover(|tile| tile.bg(theme::border_strong()))641
.child(642
.child(642
img(image_source(&sticker.url()))643
img(bounded(image_source(&sticker.url())))643
.size_full()644
.size_full()644
.object_fit(ObjectFit::Contain),645
.object_fit(ObjectFit::Contain),645
)646
)@@ -0,0 +1,126 @@
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
}
@@ -0,0 +1,126 @@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
images32
}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 == 056
&& let Some(Ok(image)) = &result57
{58
entry.bytes = decoded_bytes(image);59
self.trim(now);60
}61
result62
}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) * 478
})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
evicted95
}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
}@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use std::io::Cursor;
2
3
use std::path::{Path, PathBuf};
3
4
use std::sync::Arc;
@@ -820,7 +821,7 @@ impl ImageViewer {
820
821
.top(px(origin.1))
821
822
.w(px(display.0))
822
823
.h(px(display.1))
823
.child(img(source).size_full().object_fit(ObjectFit::Fill))
824
.child(img(bounded(source)).size_full().object_fit(ObjectFit::Fill))
824
825
.on_mouse_down(
825
826
MouseButton::Left,
826
827
cx.listener(|this, event: &MouseDownEvent, _, cx| {
@@ -874,7 +875,7 @@ impl ImageViewer {
874
875
.when(!current, |frame| frame.opacity(0.7))
875
876
.map(|frame| match path {
876
877
Some(path) => {
877
frame.child(img(path).size_full().object_fit(ObjectFit::Cover))
878
frame.child(img(bounded(path)).size_full().object_fit(ObjectFit::Cover))
878
879
}
879
880
None => frame.child(symbol("image", 18., white().opacity(0.5))),
880
881
}),
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use std::io::Cursor;2
use std::io::Cursor;2
use std::path::{Path, PathBuf};3
use std::path::{Path, PathBuf};3
use std::sync::Arc;4
use std::sync::Arc;@@ -820,7 +821,7 @@ impl ImageViewer {820
.top(px(origin.1))821
.top(px(origin.1))821
.w(px(display.0))822
.w(px(display.0))822
.h(px(display.1))823
.h(px(display.1))823
.child(img(source).size_full().object_fit(ObjectFit::Fill))824
.child(img(bounded(source)).size_full().object_fit(ObjectFit::Fill))824
.on_mouse_down(825
.on_mouse_down(825
MouseButton::Left,826
MouseButton::Left,826
cx.listener(|this, event: &MouseDownEvent, _, cx| {827
cx.listener(|this, event: &MouseDownEvent, _, cx| {@@ -874,7 +875,7 @@ impl ImageViewer {874
.when(!current, |frame| frame.opacity(0.7))875
.when(!current, |frame| frame.opacity(0.7))875
.map(|frame| match path {876
.map(|frame| match path {876
Some(path) => {877
Some(path) => {877
frame.child(img(path).size_full().object_fit(ObjectFit::Cover))878
frame.child(img(bounded(path)).size_full().object_fit(ObjectFit::Cover))878
}879
}879
None => frame.child(symbol("image", 18., white().opacity(0.5))),880
None => frame.child(symbol("image", 18., white().opacity(0.5))),880
}),881
}),@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use std::rc::Rc;
2
3
3
4
use gpui_kit::assets::IconName;
@@ -67,7 +68,7 @@ fn thumbnail(
67
68
Some(match entry {
68
69
Some(entry) => frame
69
70
.child(
70
img(entry.path.clone())
71
img(bounded(entry.path.clone()))
71
72
.size_full()
72
73
.object_fit(ObjectFit::Cover),
73
74
)
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use std::rc::Rc;2
use std::rc::Rc;2
3
3
use gpui_kit::assets::IconName;4
use gpui_kit::assets::IconName;@@ -67,7 +68,7 @@ fn thumbnail(67
Some(match entry {68
Some(match entry {68
Some(entry) => frame69
Some(entry) => frame69
.child(70
.child(70
img(entry.path.clone())71
img(bounded(entry.path.clone()))71
.size_full()72
.size_full()72
.object_fit(ObjectFit::Cover),73
.object_fit(ObjectFit::Cover),73
)74
)@@ -54,6 +54,7 @@ pub mod forward_dialog;
54
54
pub mod find_panel;
55
55
pub mod fun_picker;
56
56
pub mod group_name;
57
pub mod image_memory;
57
58
pub mod image_menu;
58
59
pub mod image_viewer;
59
60
pub mod join_dialog;
@@ -54,6 +54,7 @@ pub mod forward_dialog;54
pub mod find_panel;54
pub mod find_panel;55
pub mod fun_picker;55
pub mod fun_picker;56
pub mod group_name;56
pub mod group_name;57
pub mod image_memory;57
pub mod image_menu;58
pub mod image_menu;58
pub mod image_viewer;59
pub mod image_viewer;59
pub mod join_dialog;60
pub mod join_dialog;@@ -1,3 +1,4 @@
1
use crate::views::image_memory::bounded;
1
2
use std::rc::Rc;
2
3
3
4
use chrono::Local;
@@ -81,7 +82,7 @@ fn reaction_emoji(glyph: &str, label: &str, size: f32, directory: &Directory) ->
81
82
.into_any_element();
82
83
};
83
84
match directory.image(&image.url) {
84
Some(entry) => img(entry.path.clone())
85
Some(entry) => img(bounded(entry.path.clone()))
85
86
.size(px(size))
86
87
.object_fit(ObjectFit::Contain)
87
88
.flex_none()
@@ -1,3 +1,4 @@1
use crate::views::image_memory::bounded;1
use std::rc::Rc;2
use std::rc::Rc;2
3
3
use chrono::Local;4
use chrono::Local;@@ -81,7 +82,7 @@ fn reaction_emoji(glyph: &str, label: &str, size: f32, directory: &Directory) ->81
.into_any_element();82
.into_any_element();82
};83
};83
match directory.image(&image.url) {84
match directory.image(&image.url) {84
Some(entry) => img(entry.path.clone())85
Some(entry) => img(bounded(entry.path.clone()))85
.size(px(size))86
.size(px(size))86
.object_fit(ObjectFit::Contain)87
.object_fit(ObjectFit::Contain)87
.flex_none()88
.flex_none()