Skip to content

Commit 2024295

Browse files
bircnilucasmerlinemilk
authored
Make ImageLoader use background thread (#5394)
This is the same change as in #4069 but as this is stale I wanted to reopen a non stale PR Modifies ImageLoader's load function to use background threads for the image decoding work. This avoids blocking the main thread that is especially noticeable when loading many images at once. This was modelled after the other loader implementations that also use threads. * Closes <#5375> * [x] I have followed the instructions in the PR template --------- Co-authored-by: lucasmerlin <[email protected]> Co-authored-by: Emil Ernerfeldt <[email protected]>
1 parent 58b2ac8 commit 2024295

File tree

3 files changed

+75
-25
lines changed

3 files changed

+75
-25
lines changed

crates/egui_demo_app/tests/test_demo_app.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ fn test_demo_app() {
6767
}
6868

6969
// Can't use Harness::run because fractal clock keeps requesting repaints
70-
harness.run_steps(2);
70+
harness.run_steps(4);
7171

7272
results.add(harness.try_snapshot(&anchor.to_string()));
7373
}

crates/egui_extras/src/loaders/image_loader.rs

Lines changed: 73 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
use ahash::HashMap;
22
use egui::{
33
decode_animated_image_uri,
4-
load::{BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint},
4+
load::{Bytes, BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint},
55
mutex::Mutex,
66
ColorImage,
77
};
88
use image::ImageFormat;
9-
use std::{mem::size_of, path::Path, sync::Arc};
9+
use std::{mem::size_of, path::Path, sync::Arc, task::Poll};
1010

11-
type Entry = Result<Arc<ColorImage>, LoadError>;
11+
#[cfg(not(target_arch = "wasm32"))]
12+
use std::thread;
13+
14+
type Entry = Poll<Result<Arc<ColorImage>, String>>;
1215

1316
#[derive(Default)]
1417
pub struct ImageCrateLoader {
15-
cache: Mutex<HashMap<String, Entry>>,
18+
cache: Arc<Mutex<HashMap<String, Entry>>>,
1619
}
1720

1821
impl ImageCrateLoader {
@@ -73,11 +76,69 @@ impl ImageLoader for ImageCrateLoader {
7376
return Err(LoadError::NotSupported);
7477
}
7578

76-
let mut cache = self.cache.lock();
77-
if let Some(entry) = cache.get(uri).cloned() {
78-
match entry {
79+
#[cfg(not(target_arch = "wasm32"))]
80+
#[allow(clippy::unnecessary_wraps)] // needed here to match other return types
81+
fn load_image(
82+
ctx: &egui::Context,
83+
uri: &str,
84+
cache: &Arc<Mutex<HashMap<String, Entry>>>,
85+
bytes: &Bytes,
86+
) -> ImageLoadResult {
87+
let uri = uri.to_owned();
88+
cache.lock().insert(uri.clone(), Poll::Pending);
89+
90+
// Do the image parsing on a bg thread
91+
thread::Builder::new()
92+
.name(format!("egui_extras::ImageLoader::load({uri:?})"))
93+
.spawn({
94+
let ctx = ctx.clone();
95+
let cache = cache.clone();
96+
97+
let uri = uri.clone();
98+
let bytes = bytes.clone();
99+
move || {
100+
log::trace!("ImageLoader - started loading {uri:?}");
101+
let result = crate::image::load_image_bytes(&bytes)
102+
.map(Arc::new)
103+
.map_err(|err| err.to_string());
104+
log::trace!("ImageLoader - finished loading {uri:?}");
105+
let prev = cache.lock().insert(uri, Poll::Ready(result));
106+
debug_assert!(matches!(prev, Some(Poll::Pending)));
107+
108+
ctx.request_repaint();
109+
}
110+
})
111+
.expect("failed to spawn thread");
112+
113+
Ok(ImagePoll::Pending { size: None })
114+
}
115+
116+
#[cfg(target_arch = "wasm32")]
117+
fn load_image(
118+
_ctx: &egui::Context,
119+
uri: &str,
120+
cache: &Arc<Mutex<HashMap<String, Entry>>>,
121+
bytes: &Bytes,
122+
) -> ImageLoadResult {
123+
let mut cache_lock = cache.lock();
124+
log::trace!("started loading {uri:?}");
125+
let result = crate::image::load_image_bytes(bytes)
126+
.map(Arc::new)
127+
.map_err(|err| err.to_string());
128+
log::trace!("finished loading {uri:?}");
129+
cache_lock.insert(uri.into(), std::task::Poll::Ready(result.clone()));
130+
match result {
79131
Ok(image) => Ok(ImagePoll::Ready { image }),
80-
Err(err) => Err(err),
132+
Err(err) => Err(LoadError::Loading(err)),
133+
}
134+
}
135+
136+
let entry = self.cache.lock().get(uri).cloned();
137+
if let Some(entry) = entry {
138+
match entry {
139+
Poll::Ready(Ok(image)) => Ok(ImagePoll::Ready { image }),
140+
Poll::Ready(Err(err)) => Err(LoadError::Loading(err)),
141+
Poll::Pending => Ok(ImagePoll::Pending { size: None }),
81142
}
82143
} else {
83144
match ctx.try_load_bytes(uri) {
@@ -90,19 +151,7 @@ impl ImageLoader for ImageCrateLoader {
90151
});
91152
}
92153
}
93-
94-
if bytes.starts_with(b"version https://git-lfs") {
95-
return Err(LoadError::FormatNotSupported {
96-
detected_format: Some("git-lfs".to_owned()),
97-
});
98-
}
99-
100-
// (3)
101-
log::trace!("started loading {uri:?}");
102-
let result = crate::image::load_image_bytes(&bytes).map(Arc::new);
103-
log::trace!("finished loading {uri:?}");
104-
cache.insert(uri.into(), result.clone());
105-
result.map(|image| ImagePoll::Ready { image })
154+
load_image(ctx, uri, &self.cache, &bytes)
106155
}
107156
Ok(BytesPoll::Pending { size }) => Ok(ImagePoll::Pending { size }),
108157
Err(err) => Err(err),
@@ -123,8 +172,9 @@ impl ImageLoader for ImageCrateLoader {
123172
.lock()
124173
.values()
125174
.map(|result| match result {
126-
Ok(image) => image.pixels.len() * size_of::<egui::Color32>(),
127-
Err(err) => err.byte_size(),
175+
Poll::Ready(Ok(image)) => image.pixels.len() * size_of::<egui::Color32>(),
176+
Poll::Ready(Err(err)) => err.len(),
177+
Poll::Pending => 0,
128178
})
129179
.sum()
130180
}

deny.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ skip = [
5757
{ name = "redox_syscall" }, # old version via winit
5858
{ name = "thiserror" }, # ecosystem is in the process of migrating from 1.x to 2.x
5959
{ name = "thiserror-impl" }, # same as above
60-
{ name = "time" }, # old version pulled in by unmaintianed crate 'chrono'
60+
{ name = "time" }, # old version pulled in by unmaintained crate 'chrono'
6161
{ name = "windows-core" }, # Chrono pulls in 0.51, accesskit uses 0.58.0
6262
{ name = "windows-sys" }, # glutin pulls in 0.52.0, accesskit pulls in 0.59.0, rfd pulls 0.48, webbrowser pulls 0.45.0 (via jni)
6363
]

0 commit comments

Comments
 (0)