1
0
mirror of https://github.com/emilk/egui.git synced 2026-09-01 06:10:06 -04:00

Improved texture loading (#3315)

* rework loading around `Arc<Loaders>`

* use `Bytes` instead of splitting api

* remove unwraps in `texture_handle`

* make `FileLoader` optional under `file` feature

* hide http load error stack trace from UI

* implement image fit

* support more image sources

* center spinner if we know size ahead of time

* allocate final size for spinner

* improve image format guessing

* remove `ui.image`, `Image`, add `RawImage`

* deprecate `RetainedImage`

* `image2` -> `image`

* add viewer example

* update `examples/image` + remove `svg` and `download_image` exapmles

* fix lints and tests

* fix doc link

* add image controls to `images` example

* add more `From` str-like types

* add api to forget all images

* fix max size

* do not scale original size unless necessary

* fix doc link

* add more docs for `Image` and `RawImage`

* make paint_at `pub`

* update `ImageButton` to use new `Image` API

* fix double rendering

* `SizeHint::Original` -> `Scale` + remove `Option` wrapper

* Update crates/egui/src/load.rs

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>

* remove special `None` value for `forget`

* Update crates/egui/src/load.rs

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>

* add more examples to `ui.image` + add `include_image` macro

* Update crates/egui/src/ui.rs

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>

* update `menu_image_button` to use `ImageSource`

* `OrderedFloat::get` -> `into_inner`

* derive `Eq` on `SizedTexture`

* add `id` to loaders + `is_installed` check

* move `images` to demo + simplify `images` example

* log trace when installing loaders

* fix lint

* fix doc link

* add more documentation

* more `egui_extras::loaders` docs

* Update examples/images/src/main.rs

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>

* update `images` example screenshots + readme

* remove unused `rfd` from `images` example

* Update crates/egui_extras/src/loaders/ehttp_loader.rs

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>

* add `must_use` on `Image` and `RawImage`

* document `loaders::install` multiple call safety

* Update crates/egui_extras/Cargo.toml

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>

* reshuffle `is_loader_installed`

* make `include_image` produce `ImageSource` + update docs

* update `include_image` docs

* remove `None` mentions from loader `forget`

* inline `From` texture id + size for `SizedTexture`

* add warning about statically known path

* change image load error + use in image button

* add `.size()` to `Image`

* Update crates/egui_demo_app/Cargo.toml

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>

* add explanations to image viewer ui

---------

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>
This commit is contained in:
Jan Procházka
2023-09-12 10:39:17 +02:00
committed by GitHub
parent dbcf15b49e
commit 2bc6814acc
47 changed files with 1563 additions and 770 deletions

View File

@@ -5,52 +5,60 @@ use egui::{
};
use std::{sync::Arc, task::Poll};
type Entry = Poll<Result<Arc<[u8]>, String>>;
#[derive(Clone)]
struct File {
bytes: Arc<[u8]>,
mime: Option<String>,
}
impl File {
fn from_response(uri: &str, response: ehttp::Response) -> Result<Self, String> {
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 mime = response.content_type().map(|v| v.to_owned());
let bytes = response.bytes.into();
Ok(File { bytes, mime })
}
}
type Entry = Poll<Result<File, String>>;
#[derive(Default)]
pub struct EhttpLoader {
cache: Arc<Mutex<HashMap<String, Entry>>>,
}
impl EhttpLoader {
pub const ID: &str = egui::generate_loader_id!(EhttpLoader);
}
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 id(&self) -> &str {
Self::ID
}
fn load(&self, ctx: &egui::Context, uri: &str) -> BytesLoadResult {
if !starts_with_one_of(uri, PROTOCOLS) {
return Err(LoadError::NotSupported);
@@ -59,9 +67,10 @@ impl BytesLoader for EhttpLoader {
let mut cache = self.cache.lock();
if let Some(entry) = cache.get(uri).cloned() {
match entry {
Poll::Ready(Ok(bytes)) => Ok(BytesPoll::Ready {
Poll::Ready(Ok(file)) => Ok(BytesPoll::Ready {
size: None,
bytes: Bytes::Shared(bytes),
bytes: Bytes::Shared(file.bytes),
mime: file.mime,
}),
Poll::Ready(Err(err)) => Err(LoadError::Custom(err)),
Poll::Pending => Ok(BytesPoll::Pending { size: None }),
@@ -77,7 +86,14 @@ impl BytesLoader for EhttpLoader {
let ctx = ctx.clone();
let cache = self.cache.clone();
move |response| {
let result = get_image_bytes(&uri, response);
let result = match response {
Ok(response) => File::from_response(&uri, response),
Err(err) => {
// Log details; return summary
crate::log_err!("Failed to load {uri:?}: {err}");
Err(format!("Failed to load {uri:?}"))
}
};
crate::log_trace!("finished loading {uri:?}");
let prev = cache.lock().insert(uri, Poll::Ready(result));
assert!(matches!(prev, Some(Poll::Pending)));
@@ -93,12 +109,18 @@ impl BytesLoader for EhttpLoader {
let _ = self.cache.lock().remove(uri);
}
fn forget_all(&self) {
self.cache.lock().clear();
}
fn byte_size(&self) -> usize {
self.cache
.lock()
.values()
.map(|entry| match entry {
Poll::Ready(Ok(bytes)) => bytes.len(),
Poll::Ready(Ok(file)) => {
file.bytes.len() + file.mime.as_ref().map_or(0, |m| m.len())
}
Poll::Ready(Err(err)) => err.len(),
_ => 0,
})