mirror of
https://github.com/emilk/egui.git
synced 2026-08-31 13:50:04 -04:00
Managed texture loading (#3297)
* add types from proposal * add load methods on `egui::Context` * implement loaders from proposal in `egui_extras` * impl `From<Vec2>` for `SizeHint` * re-export `SizeHint` from `egui` root * rework `svg` example to use new managed `Image` * split loaders into separate files + add logging * add `log_trace` * clean up `RetainedImage` from `svg` example * refactor ehttp loader response to bytes mapping * remove spammy trace * load images even without extension * fix lints * remove unused imports * use `Image2` in `download_image` * use `visuals.error_fg_color` in `Image2` error state * update lockfile * use `Arc<ColorImage>` in `ImageData` + add `forget` API * add `ui.image2` * add byte size query api * use iterators to sum loader byte sizes * add static image loading * use static image in `svg` example * small refactor of `Image2::ui` texture loading code * add `ImageFit` to size images properly * remove println calls * add bad image load to `download_image` example * add loader file extension support tests * fix lint errors in `loaders` * remove unused `poll-promise` dependency * add some docs to `Image2` * add some docs to `egui_extras::loaders::install` * explain `loaders::install` in examples * fix lint * upgrade `ehttp` to `0.3` for some crates * Remove some unused dependencies * Remove unnecessary context clone * Turn on the `log` create feature of egui_extras in all examples * rename `forget` and document it * derive `Debug` on `SizeHint` Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com> * round when converting SizeHint from vec2 Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com> * add `load` module docs * docstring `add_loader` methods * expose + document `load_include_bytes` * cache texture handles in `DefaultTextureLoader` * add `image2` doctest + further document `Image2` * use `Default` for default `Image2` options * update `image2` doc comment * mention immediate-mode safety * more fit calculation into inherent impl * add hover text on spinner * add `all-loaders` feature * clarify `egui_extras::loaders::install` behavior * explain how to enable image formats * properly format `uri` * use `thread::Builder` instead of `spawn` * use eq op instead of `matches` * inline `From<Arc<ColorImage>>` for `ImageData` * allow non-`'static` bytes + `forget` in `DefaultTextureLoader` * sort features * change `ehttp` feature to `http` * update `Image2` docs * refactor loader cache type --------- Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>
This commit is contained in:
107
crates/egui_extras/src/loaders/ehttp_loader.rs
Normal file
107
crates/egui_extras/src/loaders/ehttp_loader.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
use egui::{
|
||||
ahash::HashMap,
|
||||
load::{Bytes, BytesLoadResult, BytesLoader, BytesPoll, LoadError},
|
||||
mutex::Mutex,
|
||||
};
|
||||
use std::{sync::Arc, task::Poll};
|
||||
|
||||
type Entry = Poll<Result<Arc<[u8]>, String>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct EhttpLoader {
|
||||
cache: Arc<Mutex<HashMap<String, Entry>>>,
|
||||
}
|
||||
|
||||
const PROTOCOLS: &[&str] = &["http://", "https://"];
|
||||
|
||||
fn starts_with_one_of(s: &str, prefixes: &[&str]) -> bool {
|
||||
prefixes.iter().any(|prefix| s.starts_with(prefix))
|
||||
}
|
||||
|
||||
fn get_image_bytes(
|
||||
uri: &str,
|
||||
response: Result<ehttp::Response, String>,
|
||||
) -> Result<Arc<[u8]>, String> {
|
||||
let response = response?;
|
||||
if !response.ok {
|
||||
match response.text() {
|
||||
Some(response_text) => {
|
||||
return Err(format!(
|
||||
"failed to load {uri:?}: {} {} {response_text}",
|
||||
response.status, response.status_text
|
||||
))
|
||||
}
|
||||
None => {
|
||||
return Err(format!(
|
||||
"failed to load {uri:?}: {} {}",
|
||||
response.status, response.status_text
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(content_type) = response.content_type() else {
|
||||
return Err(format!("failed to load {uri:?}: no content-type header found"));
|
||||
};
|
||||
if !content_type.starts_with("image/") {
|
||||
return Err(format!("failed to load {uri:?}: expected content-type starting with \"image/\", found {content_type:?}"));
|
||||
}
|
||||
|
||||
Ok(response.bytes.into())
|
||||
}
|
||||
|
||||
impl BytesLoader for EhttpLoader {
|
||||
fn load(&self, ctx: &egui::Context, uri: &str) -> BytesLoadResult {
|
||||
if !starts_with_one_of(uri, PROTOCOLS) {
|
||||
return Err(LoadError::NotSupported);
|
||||
}
|
||||
|
||||
let mut cache = self.cache.lock();
|
||||
if let Some(entry) = cache.get(uri).cloned() {
|
||||
match entry {
|
||||
Poll::Ready(Ok(bytes)) => Ok(BytesPoll::Ready {
|
||||
size: None,
|
||||
bytes: Bytes::Shared(bytes),
|
||||
}),
|
||||
Poll::Ready(Err(err)) => Err(LoadError::Custom(err)),
|
||||
Poll::Pending => Ok(BytesPoll::Pending { size: None }),
|
||||
}
|
||||
} else {
|
||||
crate::log_trace!("started loading {uri:?}");
|
||||
|
||||
let uri = uri.to_owned();
|
||||
cache.insert(uri.clone(), Poll::Pending);
|
||||
drop(cache);
|
||||
|
||||
ehttp::fetch(ehttp::Request::get(uri.clone()), {
|
||||
let ctx = ctx.clone();
|
||||
let cache = self.cache.clone();
|
||||
move |response| {
|
||||
let result = get_image_bytes(&uri, response);
|
||||
crate::log_trace!("finished loading {uri:?}");
|
||||
let prev = cache.lock().insert(uri, Poll::Ready(result));
|
||||
assert!(matches!(prev, Some(Poll::Pending)));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
|
||||
Ok(BytesPoll::Pending { size: None })
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&self, uri: &str) {
|
||||
let _ = self.cache.lock().remove(uri);
|
||||
}
|
||||
|
||||
fn byte_size(&self) -> usize {
|
||||
self.cache
|
||||
.lock()
|
||||
.values()
|
||||
.map(|entry| match entry {
|
||||
Poll::Ready(Ok(bytes)) => bytes.len(),
|
||||
Poll::Ready(Err(err)) => err.len(),
|
||||
_ => 0,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user