Load images in the background

This commit is contained in:
Antonio Scandurra 2024-01-24 13:15:31 +01:00
parent e3157f7212
commit 92b0184036
2 changed files with 37 additions and 40 deletions

View file

@ -104,7 +104,7 @@ impl Element for Img {
cx.with_z_index(1, |cx| { cx.with_z_index(1, |cx| {
match source { match source {
ImageSource::Uri(uri) => { ImageSource::Uri(uri) => {
let image_future = cx.image_cache.get(uri.clone()); let image_future = cx.image_cache.get(uri.clone(), cx);
if let Some(data) = image_future if let Some(data) = image_future
.clone() .clone()
.now_or_never() .now_or_never()

View file

@ -1,9 +1,6 @@
use crate::{ImageData, ImageId, SharedUrl}; use crate::{AppContext, ImageData, ImageId, SharedUrl, Task};
use collections::HashMap; use collections::HashMap;
use futures::{ use futures::{future::Shared, AsyncReadExt, FutureExt, TryFutureExt};
future::{BoxFuture, Shared},
AsyncReadExt, FutureExt, TryFutureExt,
};
use image::ImageError; use image::ImageError;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::Arc; use std::sync::Arc;
@ -44,10 +41,10 @@ impl From<ImageError> for Error {
pub(crate) struct ImageCache { pub(crate) struct ImageCache {
client: Arc<dyn HttpClient>, client: Arc<dyn HttpClient>,
images: Arc<Mutex<HashMap<SharedUrl, FetchImageFuture>>>, images: Arc<Mutex<HashMap<SharedUrl, FetchImageTask>>>,
} }
type FetchImageFuture = Shared<BoxFuture<'static, Result<Arc<ImageData>, Error>>>; type FetchImageTask = Shared<Task<Result<Arc<ImageData>, Error>>>;
impl ImageCache { impl ImageCache {
pub fn new(client: Arc<dyn HttpClient>) -> Self { pub fn new(client: Arc<dyn HttpClient>) -> Self {
@ -57,10 +54,7 @@ impl ImageCache {
} }
} }
pub fn get( pub fn get(&self, uri: impl Into<SharedUrl>, cx: &AppContext) -> FetchImageTask {
&self,
uri: impl Into<SharedUrl>,
) -> Shared<BoxFuture<'static, Result<Arc<ImageData>, Error>>> {
let uri = uri.into(); let uri = uri.into();
let mut images = self.images.lock(); let mut images = self.images.lock();
@ -68,36 +62,39 @@ impl ImageCache {
Some(future) => future.clone(), Some(future) => future.clone(),
None => { None => {
let client = self.client.clone(); let client = self.client.clone();
let future = { let future = cx
let uri = uri.clone(); .background_executor()
async move { .spawn(
let mut response = client.get(uri.as_ref(), ().into(), true).await?; {
let mut body = Vec::new(); let uri = uri.clone();
response.body_mut().read_to_end(&mut body).await?; async move {
let mut response =
client.get(uri.as_ref(), ().into(), true).await?;
let mut body = Vec::new();
response.body_mut().read_to_end(&mut body).await?;
if !response.status().is_success() { if !response.status().is_success() {
return Err(Error::BadStatus { return Err(Error::BadStatus {
status: response.status(), status: response.status(),
body: String::from_utf8_lossy(&body).into_owned(), body: String::from_utf8_lossy(&body).into_owned(),
}); });
}
let format = image::guess_format(&body)?;
let image = image::load_from_memory_with_format(&body, format)?
.into_bgra8();
Ok(Arc::new(ImageData::new(image)))
}
} }
.map_err({
let format = image::guess_format(&body)?; let uri = uri.clone();
let image = move |error| {
image::load_from_memory_with_format(&body, format)?.into_bgra8(); log::log!(log::Level::Error, "{:?} {:?}", &uri, &error);
Ok(Arc::new(ImageData::new(image))) error
} }
} }),
.map_err({ )
let uri = uri.clone(); .shared();
move |error| {
log::log!(log::Level::Error, "{:?} {:?}", &uri, &error);
error
}
})
.boxed()
.shared();
images.insert(uri, future.clone()); images.insert(uri, future.clone());
future future