mirror of
https://github.com/emilk/egui.git
synced 2026-09-01 14:20:04 -04:00
Merge branch 'master' of https://github.com/emilk/egui into multiples_viewports
This commit is contained in:
@@ -4,7 +4,7 @@ version = "0.22.0"
|
||||
authors = ["Emil Ernerfeldt <emil.ernerfeldt@gmail.com>"]
|
||||
description = "An easy-to-use immediate mode GUI that runs on both web and native"
|
||||
edition = "2021"
|
||||
rust-version = "1.67"
|
||||
rust-version = "1.70"
|
||||
homepage = "https://github.com/emilk/egui"
|
||||
license = "MIT OR Apache-2.0"
|
||||
readme = "../../README.md"
|
||||
|
||||
@@ -239,6 +239,8 @@ struct ContextImpl {
|
||||
is_accesskit_enabled: bool,
|
||||
#[cfg(feature = "accesskit")]
|
||||
accesskit_node_classes: accesskit::NodeClassSet,
|
||||
|
||||
loaders: load::Loaders,
|
||||
}
|
||||
|
||||
impl ContextImpl {
|
||||
@@ -2294,6 +2296,159 @@ impl Context {
|
||||
}
|
||||
}
|
||||
|
||||
/// ## Image loading
|
||||
impl Context {
|
||||
/// Associate some static bytes with a `uri`.
|
||||
///
|
||||
/// The same `uri` may be passed to [`Ui::image2`] later to load the bytes as an image.
|
||||
pub fn include_static_bytes(&self, uri: &'static str, bytes: &'static [u8]) {
|
||||
self.read(|ctx| ctx.loaders.include.insert_static(uri, bytes));
|
||||
}
|
||||
|
||||
/// Associate some bytes with a `uri`.
|
||||
///
|
||||
/// The same `uri` may be passed to [`Ui::image2`] later to load the bytes as an image.
|
||||
pub fn include_bytes(&self, uri: &'static str, bytes: impl Into<Arc<[u8]>>) {
|
||||
self.read(|ctx| ctx.loaders.include.insert_shared(uri, bytes));
|
||||
}
|
||||
|
||||
/// Append an entry onto the chain of bytes loaders.
|
||||
///
|
||||
/// See [`load`] for more information.
|
||||
pub fn add_bytes_loader(&self, loader: Arc<dyn load::BytesLoader + Send + Sync + 'static>) {
|
||||
self.write(|ctx| ctx.loaders.bytes.push(loader));
|
||||
}
|
||||
|
||||
/// Append an entry onto the chain of image loaders.
|
||||
///
|
||||
/// See [`load`] for more information.
|
||||
pub fn add_image_loader(&self, loader: Arc<dyn load::ImageLoader + Send + Sync + 'static>) {
|
||||
self.write(|ctx| ctx.loaders.image.push(loader));
|
||||
}
|
||||
|
||||
/// Append an entry onto the chain of texture loaders.
|
||||
///
|
||||
/// See [`load`] for more information.
|
||||
pub fn add_texture_loader(&self, loader: Arc<dyn load::TextureLoader + Send + Sync + 'static>) {
|
||||
self.write(|ctx| ctx.loaders.texture.push(loader));
|
||||
}
|
||||
|
||||
/// Release all memory and textures related to the given image URI.
|
||||
///
|
||||
/// If you attempt to load the image again, it will be reloaded from scratch.
|
||||
pub fn forget_image(&self, uri: &str) {
|
||||
self.write(|ctx| {
|
||||
use crate::load::BytesLoader as _;
|
||||
|
||||
ctx.loaders.include.forget(uri);
|
||||
|
||||
for loader in &ctx.loaders.bytes {
|
||||
loader.forget(uri);
|
||||
}
|
||||
|
||||
for loader in &ctx.loaders.image {
|
||||
loader.forget(uri);
|
||||
}
|
||||
|
||||
for loader in &ctx.loaders.texture {
|
||||
loader.forget(uri);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Try loading the bytes from the given uri using any available bytes loaders.
|
||||
///
|
||||
/// Loaders are expected to cache results, so that this call is immediate-mode safe.
|
||||
///
|
||||
/// This calls the loaders one by one in the order in which they were registered.
|
||||
/// If a loader returns [`LoadError::NotSupported`][not_supported],
|
||||
/// then the next loader is called. This process repeats until all loaders have
|
||||
/// been exhausted, at which point this returns [`LoadError::NotSupported`][not_supported].
|
||||
///
|
||||
/// # Errors
|
||||
/// This may fail with:
|
||||
/// - [`LoadError::NotSupported`][not_supported] if none of the registered loaders support loading the given `uri`.
|
||||
/// - [`LoadError::Custom`][custom] if one of the loaders _does_ support loading the `uri`, but the loading process failed.
|
||||
///
|
||||
/// [not_supported]: crate::load::LoadError::NotSupported
|
||||
/// [custom]: crate::load::LoadError::Custom
|
||||
pub fn try_load_bytes(&self, uri: &str) -> load::BytesLoadResult {
|
||||
self.read(|this| {
|
||||
for loader in &this.loaders.bytes {
|
||||
match loader.load(self, uri) {
|
||||
Err(load::LoadError::NotSupported) => continue,
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
|
||||
Err(load::LoadError::NotSupported)
|
||||
})
|
||||
}
|
||||
|
||||
/// Try loading the image from the given uri using any available image loaders.
|
||||
///
|
||||
/// Loaders are expected to cache results, so that this call is immediate-mode safe.
|
||||
///
|
||||
/// This calls the loaders one by one in the order in which they were registered.
|
||||
/// If a loader returns [`LoadError::NotSupported`][not_supported],
|
||||
/// then the next loader is called. This process repeats until all loaders have
|
||||
/// been exhausted, at which point this returns [`LoadError::NotSupported`][not_supported].
|
||||
///
|
||||
/// # Errors
|
||||
/// This may fail with:
|
||||
/// - [`LoadError::NotSupported`][not_supported] if none of the registered loaders support loading the given `uri`.
|
||||
/// - [`LoadError::Custom`][custom] if one of the loaders _does_ support loading the `uri`, but the loading process failed.
|
||||
///
|
||||
/// [not_supported]: crate::load::LoadError::NotSupported
|
||||
/// [custom]: crate::load::LoadError::Custom
|
||||
pub fn try_load_image(&self, uri: &str, size_hint: load::SizeHint) -> load::ImageLoadResult {
|
||||
self.read(|this| {
|
||||
for loader in &this.loaders.image {
|
||||
match loader.load(self, uri, size_hint) {
|
||||
Err(load::LoadError::NotSupported) => continue,
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
|
||||
Err(load::LoadError::NotSupported)
|
||||
})
|
||||
}
|
||||
|
||||
/// Try loading the texture from the given uri using any available texture loaders.
|
||||
///
|
||||
/// Loaders are expected to cache results, so that this call is immediate-mode safe.
|
||||
///
|
||||
/// This calls the loaders one by one in the order in which they were registered.
|
||||
/// If a loader returns [`LoadError::NotSupported`][not_supported],
|
||||
/// then the next loader is called. This process repeats until all loaders have
|
||||
/// been exhausted, at which point this returns [`LoadError::NotSupported`][not_supported].
|
||||
///
|
||||
/// # Errors
|
||||
/// This may fail with:
|
||||
/// - [`LoadError::NotSupported`][not_supported] if none of the registered loaders support loading the given `uri`.
|
||||
/// - [`LoadError::Custom`][custom] if one of the loaders _does_ support loading the `uri`, but the loading process failed.
|
||||
///
|
||||
/// [not_supported]: crate::load::LoadError::NotSupported
|
||||
/// [custom]: crate::load::LoadError::Custom
|
||||
pub fn try_load_texture(
|
||||
&self,
|
||||
uri: &str,
|
||||
texture_options: TextureOptions,
|
||||
size_hint: load::SizeHint,
|
||||
) -> load::TextureLoadResult {
|
||||
self.read(|this| {
|
||||
for loader in &this.loaders.texture {
|
||||
match loader.load(self, uri, texture_options, size_hint) {
|
||||
Err(load::LoadError::NotSupported) => continue,
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
|
||||
Err(load::LoadError::NotSupported)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// ## Viewports
|
||||
impl Context {
|
||||
/// Return the `ViewportId` of the current viewport
|
||||
|
||||
@@ -314,6 +314,7 @@ mod input_state;
|
||||
pub mod introspection;
|
||||
pub mod layers;
|
||||
mod layout;
|
||||
pub mod load;
|
||||
mod memory;
|
||||
pub mod menu;
|
||||
pub mod os;
|
||||
@@ -371,6 +372,7 @@ pub use {
|
||||
input_state::{InputState, MultiTouchInfo, PointerState},
|
||||
layers::{LayerId, Order},
|
||||
layout::*,
|
||||
load::SizeHint,
|
||||
memory::{Memory, Options},
|
||||
painter::Painter,
|
||||
response::{InnerResponse, Response},
|
||||
|
||||
417
crates/egui/src/load.rs
Normal file
417
crates/egui/src/load.rs
Normal file
@@ -0,0 +1,417 @@
|
||||
//! Types and traits related to image loading.
|
||||
//!
|
||||
//! If you just want to load some images, see [`egui_extras`](https://crates.io/crates/egui_extras/),
|
||||
//! which contains reasonable default implementations of these traits. You can get started quickly
|
||||
//! using [`egui_extras::loaders::install`](https://docs.rs/egui_extras/latest/egui_extras/loaders/fn.install.html).
|
||||
//!
|
||||
//! ## Loading process
|
||||
//!
|
||||
//! There are three kinds of loaders:
|
||||
//! - [`BytesLoader`]: load the raw bytes of an image
|
||||
//! - [`ImageLoader`]: decode the bytes into an array of colors
|
||||
//! - [`TextureLoader`]: ask the backend to put an image onto the GPU
|
||||
//!
|
||||
//! The different kinds of loaders represent different layers in the loading process:
|
||||
//!
|
||||
//! ```text,ignore
|
||||
//! ui.image2("file://image.png")
|
||||
//! └► ctx.try_load_texture("file://image.png", ...)
|
||||
//! └► TextureLoader::load("file://image.png", ...)
|
||||
//! └► ctx.try_load_image("file://image.png", ...)
|
||||
//! └► ImageLoader::load("file://image.png", ...)
|
||||
//! └► ctx.try_load_bytes("file://image.png", ...)
|
||||
//! └► BytesLoader::load("file://image.png", ...)
|
||||
//! ```
|
||||
//!
|
||||
//! As each layer attempts to load the URI, it first asks the layer below it
|
||||
//! for the data it needs to do its job. But this is not a strict requirement,
|
||||
//! an implementation could instead generate the data it needs!
|
||||
//!
|
||||
//! Loader trait implementations may be registered on a context with:
|
||||
//! - [`Context::add_bytes_loader`]
|
||||
//! - [`Context::add_image_loader`]
|
||||
//! - [`Context::add_texture_loader`]
|
||||
//!
|
||||
//! There may be multiple loaders of the same kind registered at the same time.
|
||||
//! The `try_load` methods on [`Context`] will attempt to call each loader one by one,
|
||||
//! until one of them returns something other than [`LoadError::NotSupported`].
|
||||
//!
|
||||
//! The loaders are stored in the context. This means they may hold state across frames,
|
||||
//! which they can (and _should_) use to cache the results of the operations they perform.
|
||||
//!
|
||||
//! For example, a [`BytesLoader`] that loads file URIs (`file://image.png`)
|
||||
//! would cache each file read. A [`TextureLoader`] would cache each combination
|
||||
//! of `(URI, TextureOptions)`, and so on.
|
||||
//!
|
||||
//! Each URI will be passed through the loaders as a plain `&str`.
|
||||
//! The loaders are free to derive as much meaning from the URI as they wish to.
|
||||
//! For example, a loader may determine that it doesn't support loading a specific URI
|
||||
//! if the protocol does not match what it expects.
|
||||
|
||||
use crate::Context;
|
||||
use ahash::HashMap;
|
||||
use epaint::mutex::Mutex;
|
||||
use epaint::TextureHandle;
|
||||
use epaint::{textures::TextureOptions, ColorImage, TextureId, Vec2};
|
||||
use std::ops::Deref;
|
||||
use std::{error::Error as StdError, fmt::Display, sync::Arc};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum LoadError {
|
||||
/// This loader does not support this protocol or image format.
|
||||
NotSupported,
|
||||
|
||||
/// A custom error message (e.g. "File not found: foo.png").
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
impl Display for LoadError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
LoadError::NotSupported => f.write_str("not supported"),
|
||||
LoadError::Custom(message) => f.write_str(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdError for LoadError {}
|
||||
|
||||
pub type Result<T, E = LoadError> = std::result::Result<T, E>;
|
||||
|
||||
/// Given as a hint for image loading requests.
|
||||
///
|
||||
/// Used mostly for rendering SVG:s to a good size.
|
||||
///
|
||||
/// All variants will preserve the original aspect ratio.
|
||||
///
|
||||
/// Similar to `usvg::FitTo`.
|
||||
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum SizeHint {
|
||||
/// Keep original size.
|
||||
#[default]
|
||||
Original,
|
||||
|
||||
/// Scale to width.
|
||||
Width(u32),
|
||||
|
||||
/// Scale to height.
|
||||
Height(u32),
|
||||
|
||||
/// Scale to size.
|
||||
Size(u32, u32),
|
||||
}
|
||||
|
||||
impl From<Vec2> for SizeHint {
|
||||
fn from(value: Vec2) -> Self {
|
||||
Self::Size(value.x.round() as u32, value.y.round() as u32)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: API for querying bytes caches in each loader
|
||||
|
||||
pub type Size = [usize; 2];
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Bytes {
|
||||
Static(&'static [u8]),
|
||||
Shared(Arc<[u8]>),
|
||||
}
|
||||
|
||||
impl From<&'static [u8]> for Bytes {
|
||||
#[inline]
|
||||
fn from(value: &'static [u8]) -> Self {
|
||||
Bytes::Static(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Arc<[u8]>> for Bytes {
|
||||
#[inline]
|
||||
fn from(value: Arc<[u8]>) -> Self {
|
||||
Bytes::Shared(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for Bytes {
|
||||
#[inline]
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
match self {
|
||||
Bytes::Static(bytes) => bytes,
|
||||
Bytes::Shared(bytes) => bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Bytes {
|
||||
type Target = [u8];
|
||||
|
||||
#[inline]
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum BytesPoll {
|
||||
/// Bytes are being loaded.
|
||||
Pending {
|
||||
/// Set if known (e.g. from a HTTP header, or by parsing the image file header).
|
||||
size: Option<Size>,
|
||||
},
|
||||
|
||||
/// Bytes are loaded.
|
||||
Ready {
|
||||
/// Set if known (e.g. from a HTTP header, or by parsing the image file header).
|
||||
size: Option<Size>,
|
||||
|
||||
/// File contents, e.g. the contents of a `.png`.
|
||||
bytes: Bytes,
|
||||
},
|
||||
}
|
||||
|
||||
pub type BytesLoadResult = Result<BytesPoll>;
|
||||
|
||||
pub trait BytesLoader {
|
||||
/// Try loading the bytes from the given uri.
|
||||
///
|
||||
/// Implementations should call `ctx.request_repaint` to wake up the ui
|
||||
/// once the data is ready.
|
||||
///
|
||||
/// The implementation should cache any result, so that calling this
|
||||
/// is immediate-mode safe.
|
||||
///
|
||||
/// # Errors
|
||||
/// This may fail with:
|
||||
/// - [`LoadError::NotSupported`] if the loader does not support loading `uri`.
|
||||
/// - [`LoadError::Custom`] if the loading process failed.
|
||||
fn load(&self, ctx: &Context, uri: &str) -> BytesLoadResult;
|
||||
|
||||
/// Forget the given `uri`.
|
||||
///
|
||||
/// If `uri` is cached, it should be evicted from cache,
|
||||
/// so that it may be fully reloaded.
|
||||
fn forget(&self, uri: &str);
|
||||
|
||||
/// Implementations may use this to perform work at the end of a frame,
|
||||
/// such as evicting unused entries from a cache.
|
||||
fn end_frame(&self, frame_index: usize) {
|
||||
let _ = frame_index;
|
||||
}
|
||||
|
||||
/// If the loader caches any data, this should return the size of that cache.
|
||||
fn byte_size(&self) -> usize;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum ImagePoll {
|
||||
/// Image is loading.
|
||||
Pending {
|
||||
/// Set if known (e.g. from a HTTP header, or by parsing the image file header).
|
||||
size: Option<Size>,
|
||||
},
|
||||
|
||||
/// Image is loaded.
|
||||
Ready { image: Arc<ColorImage> },
|
||||
}
|
||||
|
||||
pub type ImageLoadResult = Result<ImagePoll>;
|
||||
|
||||
pub trait ImageLoader {
|
||||
/// Try loading the image from the given uri.
|
||||
///
|
||||
/// Implementations should call `ctx.request_repaint` to wake up the ui
|
||||
/// once the image is ready.
|
||||
///
|
||||
/// The implementation should cache any result, so that calling this
|
||||
/// is immediate-mode safe.
|
||||
///
|
||||
/// # Errors
|
||||
/// This may fail with:
|
||||
/// - [`LoadError::NotSupported`] if the loader does not support loading `uri`.
|
||||
/// - [`LoadError::Custom`] if the loading process failed.
|
||||
fn load(&self, ctx: &Context, uri: &str, size_hint: SizeHint) -> ImageLoadResult;
|
||||
|
||||
/// Forget the given `uri`.
|
||||
///
|
||||
/// If `uri` is cached, it should be evicted from cache,
|
||||
/// so that it may be fully reloaded.
|
||||
fn forget(&self, uri: &str);
|
||||
|
||||
/// Implementations may use this to perform work at the end of a frame,
|
||||
/// such as evicting unused entries from a cache.
|
||||
fn end_frame(&self, frame_index: usize) {
|
||||
let _ = frame_index;
|
||||
}
|
||||
|
||||
/// If the loader caches any data, this should return the size of that cache.
|
||||
fn byte_size(&self) -> usize;
|
||||
}
|
||||
|
||||
/// A texture with a known size.
|
||||
#[derive(Clone)]
|
||||
pub struct SizedTexture {
|
||||
pub id: TextureId,
|
||||
pub size: Size,
|
||||
}
|
||||
|
||||
impl SizedTexture {
|
||||
pub fn from_handle(handle: &TextureHandle) -> Self {
|
||||
Self {
|
||||
id: handle.id(),
|
||||
size: handle.size(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum TexturePoll {
|
||||
/// Texture is loading.
|
||||
Pending {
|
||||
/// Set if known (e.g. from a HTTP header, or by parsing the image file header).
|
||||
size: Option<Size>,
|
||||
},
|
||||
|
||||
/// Texture is loaded.
|
||||
Ready { texture: SizedTexture },
|
||||
}
|
||||
|
||||
pub type TextureLoadResult = Result<TexturePoll>;
|
||||
|
||||
pub trait TextureLoader {
|
||||
/// Try loading the texture from the given uri.
|
||||
///
|
||||
/// Implementations should call `ctx.request_repaint` to wake up the ui
|
||||
/// once the texture is ready.
|
||||
///
|
||||
/// The implementation should cache any result, so that calling this
|
||||
/// is immediate-mode safe.
|
||||
///
|
||||
/// # Errors
|
||||
/// This may fail with:
|
||||
/// - [`LoadError::NotSupported`] if the loader does not support loading `uri`.
|
||||
/// - [`LoadError::Custom`] if the loading process failed.
|
||||
fn load(
|
||||
&self,
|
||||
ctx: &Context,
|
||||
uri: &str,
|
||||
texture_options: TextureOptions,
|
||||
size_hint: SizeHint,
|
||||
) -> TextureLoadResult;
|
||||
|
||||
/// Forget the given `uri`.
|
||||
///
|
||||
/// If `uri` is cached, it should be evicted from cache,
|
||||
/// so that it may be fully reloaded.
|
||||
fn forget(&self, uri: &str);
|
||||
|
||||
/// Implementations may use this to perform work at the end of a frame,
|
||||
/// such as evicting unused entries from a cache.
|
||||
fn end_frame(&self, frame_index: usize) {
|
||||
let _ = frame_index;
|
||||
}
|
||||
|
||||
/// If the loader caches any data, this should return the size of that cache.
|
||||
fn byte_size(&self) -> usize;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct DefaultBytesLoader {
|
||||
cache: Mutex<HashMap<&'static str, Bytes>>,
|
||||
}
|
||||
|
||||
impl DefaultBytesLoader {
|
||||
pub(crate) fn insert_static(&self, uri: &'static str, bytes: &'static [u8]) {
|
||||
self.cache
|
||||
.lock()
|
||||
.entry(uri)
|
||||
.or_insert_with(|| Bytes::Static(bytes));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_shared(&self, uri: &'static str, bytes: impl Into<Arc<[u8]>>) {
|
||||
self.cache
|
||||
.lock()
|
||||
.entry(uri)
|
||||
.or_insert_with(|| Bytes::Shared(bytes.into()));
|
||||
}
|
||||
}
|
||||
|
||||
impl BytesLoader for DefaultBytesLoader {
|
||||
fn load(&self, _: &Context, uri: &str) -> BytesLoadResult {
|
||||
match self.cache.lock().get(uri).cloned() {
|
||||
Some(bytes) => Ok(BytesPoll::Ready { size: None, bytes }),
|
||||
None => Err(LoadError::NotSupported),
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&self, uri: &str) {
|
||||
let _ = self.cache.lock().remove(uri);
|
||||
}
|
||||
|
||||
fn byte_size(&self) -> usize {
|
||||
self.cache.lock().values().map(|bytes| bytes.len()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DefaultTextureLoader {
|
||||
cache: Mutex<HashMap<(String, TextureOptions), TextureHandle>>,
|
||||
}
|
||||
|
||||
impl TextureLoader for DefaultTextureLoader {
|
||||
fn load(
|
||||
&self,
|
||||
ctx: &Context,
|
||||
uri: &str,
|
||||
texture_options: TextureOptions,
|
||||
size_hint: SizeHint,
|
||||
) -> TextureLoadResult {
|
||||
let mut cache = self.cache.lock();
|
||||
if let Some(handle) = cache.get(&(uri.into(), texture_options)) {
|
||||
let texture = SizedTexture::from_handle(handle);
|
||||
Ok(TexturePoll::Ready { texture })
|
||||
} else {
|
||||
match ctx.try_load_image(uri, size_hint)? {
|
||||
ImagePoll::Pending { size } => Ok(TexturePoll::Pending { size }),
|
||||
ImagePoll::Ready { image } => {
|
||||
let handle = ctx.load_texture(uri, image, texture_options);
|
||||
let texture = SizedTexture::from_handle(&handle);
|
||||
cache.insert((uri.into(), texture_options), handle);
|
||||
Ok(TexturePoll::Ready { texture })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&self, uri: &str) {
|
||||
self.cache.lock().retain(|(u, _), _| u != uri);
|
||||
}
|
||||
|
||||
fn end_frame(&self, _: usize) {}
|
||||
|
||||
fn byte_size(&self) -> usize {
|
||||
self.cache
|
||||
.lock()
|
||||
.values()
|
||||
.map(|texture| texture.byte_size())
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Loaders {
|
||||
pub include: Arc<DefaultBytesLoader>,
|
||||
pub bytes: Vec<Arc<dyn BytesLoader + Send + Sync + 'static>>,
|
||||
pub image: Vec<Arc<dyn ImageLoader + Send + Sync + 'static>>,
|
||||
pub texture: Vec<Arc<dyn TextureLoader + Send + Sync + 'static>>,
|
||||
}
|
||||
|
||||
impl Default for Loaders {
|
||||
fn default() -> Self {
|
||||
let include = Arc::new(DefaultBytesLoader::default());
|
||||
Self {
|
||||
bytes: vec![include.clone()],
|
||||
image: Vec::new(),
|
||||
// By default we only include `DefaultTextureLoader`.
|
||||
texture: vec![Arc::new(DefaultTextureLoader::default())],
|
||||
include,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -466,7 +466,9 @@ impl Focus {
|
||||
}
|
||||
});
|
||||
|
||||
let current_rect = *self.focus_widgets_cache.get(&focus_id).unwrap();
|
||||
let Some(current_rect) = self.focus_widgets_cache.get(&focus_id) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let mut best_score = std::f32::INFINITY;
|
||||
let mut best_id = None;
|
||||
|
||||
@@ -1590,6 +1590,25 @@ impl Ui {
|
||||
pub fn image(&mut self, texture_id: impl Into<TextureId>, size: impl Into<Vec2>) -> Response {
|
||||
Image::new(texture_id, size).ui(self)
|
||||
}
|
||||
|
||||
/// Show an image available at the given `uri`.
|
||||
///
|
||||
/// ⚠ This will do nothing unless you install some image loaders first!
|
||||
/// The easiest way to do this is via [`egui_extras::loaders::install`](https://docs.rs/egui_extras/latest/egui_extras/loaders/fn.install.html).
|
||||
///
|
||||
/// The loaders handle caching image data, sampled textures, etc. across frames, so calling this is immediate-mode safe.
|
||||
///
|
||||
/// ```
|
||||
/// # egui::__run_test_ui(|ui| {
|
||||
/// ui.image2("file://ferris.svg");
|
||||
/// # });
|
||||
/// ```
|
||||
///
|
||||
/// See also [`crate::Image2`] and [`crate::ImageSource`].
|
||||
#[inline]
|
||||
pub fn image2<'a>(&mut self, source: impl Into<ImageSource<'a>>) -> Response {
|
||||
Image2::new(source.into()).ui(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// # Colors
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::load::Bytes;
|
||||
use crate::{load::SizeHint, load::TexturePoll, *};
|
||||
use emath::Rot2;
|
||||
|
||||
/// An widget to show an image of a given size.
|
||||
@@ -173,3 +176,219 @@ impl Widget for Image {
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
/// A widget which displays an image.
|
||||
///
|
||||
/// There are three ways to construct this widget:
|
||||
/// - [`Image2::from_uri`]
|
||||
/// - [`Image2::from_bytes`]
|
||||
/// - [`Image2::from_static_bytes`]
|
||||
///
|
||||
/// In both cases the task of actually loading the image
|
||||
/// is deferred to when the `Image2` is added to the [`Ui`].
|
||||
///
|
||||
/// See [`crate::load`] for more information.
|
||||
pub struct Image2<'a> {
|
||||
source: ImageSource<'a>,
|
||||
texture_options: TextureOptions,
|
||||
size_hint: SizeHint,
|
||||
fit: ImageFit,
|
||||
sense: Sense,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy)]
|
||||
enum ImageFit {
|
||||
// TODO: options for aspect ratio
|
||||
// TODO: other fit strategies
|
||||
// FitToWidth,
|
||||
// FitToHeight,
|
||||
// FitToWidthExact(f32),
|
||||
// FitToHeightExact(f32),
|
||||
#[default]
|
||||
ShrinkToFit,
|
||||
}
|
||||
|
||||
impl ImageFit {
|
||||
pub fn calculate_final_size(&self, available_size: Vec2, image_size: Vec2) -> Vec2 {
|
||||
let aspect_ratio = image_size.x / image_size.y;
|
||||
// TODO: more image sizing options
|
||||
match self {
|
||||
// ImageFit::FitToWidth => todo!(),
|
||||
// ImageFit::FitToHeight => todo!(),
|
||||
// ImageFit::FitToWidthExact(_) => todo!(),
|
||||
// ImageFit::FitToHeightExact(_) => todo!(),
|
||||
ImageFit::ShrinkToFit => {
|
||||
let width = if available_size.x < image_size.x {
|
||||
available_size.x
|
||||
} else {
|
||||
image_size.x
|
||||
};
|
||||
let height = if available_size.y < image_size.y {
|
||||
available_size.y
|
||||
} else {
|
||||
image_size.y
|
||||
};
|
||||
if width < height {
|
||||
Vec2::new(width, width / aspect_ratio)
|
||||
} else {
|
||||
Vec2::new(height * aspect_ratio, height)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This type tells the [`Ui`] how to load the image.
|
||||
pub enum ImageSource<'a> {
|
||||
/// Load the image from a URI.
|
||||
///
|
||||
/// This could be a `file://` url, `http://` url, or a `bare` identifier.
|
||||
/// How the URI will be turned into a texture for rendering purposes is
|
||||
/// up to the registered loaders to handle.
|
||||
///
|
||||
/// See [`crate::load`] for more information.
|
||||
Uri(&'a str),
|
||||
|
||||
/// Load the image from some raw bytes.
|
||||
///
|
||||
/// The [`Bytes`] may be:
|
||||
/// - `'static`, obtained from `include_bytes!` or similar
|
||||
/// - Anything that can be converted to `Arc<[u8]>`
|
||||
///
|
||||
/// This instructs the [`Ui`] to cache the raw bytes, which are then further processed by any registered loaders.
|
||||
///
|
||||
/// See [`crate::load`] for more information.
|
||||
Bytes(&'static str, Bytes),
|
||||
}
|
||||
|
||||
impl<'a> From<&'a str> for ImageSource<'a> {
|
||||
#[inline]
|
||||
fn from(value: &'a str) -> Self {
|
||||
Self::Uri(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Into<Bytes>> From<(&'static str, T)> for ImageSource<'static> {
|
||||
#[inline]
|
||||
fn from((uri, bytes): (&'static str, T)) -> Self {
|
||||
Self::Bytes(uri, bytes.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Image2<'a> {
|
||||
/// Load the image from some source.
|
||||
pub fn new(source: ImageSource<'a>) -> Self {
|
||||
Self {
|
||||
source,
|
||||
texture_options: Default::default(),
|
||||
size_hint: Default::default(),
|
||||
fit: Default::default(),
|
||||
sense: Sense::hover(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load the image from a URI.
|
||||
///
|
||||
/// See [`ImageSource::Uri`].
|
||||
pub fn from_uri(uri: &'a str) -> Self {
|
||||
Self {
|
||||
source: ImageSource::Uri(uri),
|
||||
texture_options: Default::default(),
|
||||
size_hint: Default::default(),
|
||||
fit: Default::default(),
|
||||
sense: Sense::hover(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load the image from some raw `'static` bytes.
|
||||
///
|
||||
/// For example, you can use this to load an image from bytes obtained via [`include_bytes`].
|
||||
///
|
||||
/// See [`ImageSource::Bytes`].
|
||||
pub fn from_static_bytes(name: &'static str, bytes: &'static [u8]) -> Self {
|
||||
Self {
|
||||
source: ImageSource::Bytes(name, Bytes::Static(bytes)),
|
||||
texture_options: Default::default(),
|
||||
size_hint: Default::default(),
|
||||
fit: Default::default(),
|
||||
sense: Sense::hover(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load the image from some raw bytes.
|
||||
///
|
||||
/// See [`ImageSource::Bytes`].
|
||||
pub fn from_bytes(name: &'static str, bytes: impl Into<Arc<[u8]>>) -> Self {
|
||||
Self {
|
||||
source: ImageSource::Bytes(name, Bytes::Shared(bytes.into())),
|
||||
texture_options: Default::default(),
|
||||
size_hint: Default::default(),
|
||||
fit: Default::default(),
|
||||
sense: Sense::hover(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture options used when creating the texture.
|
||||
#[inline]
|
||||
pub fn texture_options(mut self, texture_options: TextureOptions) -> Self {
|
||||
self.texture_options = texture_options;
|
||||
self
|
||||
}
|
||||
|
||||
/// Size hint used when creating the texture.
|
||||
#[inline]
|
||||
pub fn size_hint(mut self, size_hint: impl Into<SizeHint>) -> Self {
|
||||
self.size_hint = size_hint.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Make the image respond to clicks and/or drags.
|
||||
#[inline]
|
||||
pub fn sense(mut self, sense: Sense) -> Self {
|
||||
self.sense = sense;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Widget for Image2<'a> {
|
||||
fn ui(self, ui: &mut Ui) -> Response {
|
||||
let uri = match self.source {
|
||||
ImageSource::Uri(uri) => uri,
|
||||
ImageSource::Bytes(uri, bytes) => {
|
||||
match bytes {
|
||||
Bytes::Static(bytes) => ui.ctx().include_static_bytes(uri, bytes),
|
||||
Bytes::Shared(bytes) => ui.ctx().include_bytes(uri, bytes),
|
||||
}
|
||||
uri
|
||||
}
|
||||
};
|
||||
|
||||
match ui
|
||||
.ctx()
|
||||
.try_load_texture(uri, self.texture_options, self.size_hint)
|
||||
{
|
||||
Ok(TexturePoll::Ready { texture }) => {
|
||||
let final_size = self.fit.calculate_final_size(
|
||||
ui.available_size(),
|
||||
Vec2::new(texture.size[0] as f32, texture.size[1] as f32),
|
||||
);
|
||||
|
||||
let (rect, response) = ui.allocate_exact_size(final_size, self.sense);
|
||||
|
||||
let mut mesh = Mesh::with_texture(texture.id);
|
||||
mesh.add_rect_with_uv(
|
||||
rect,
|
||||
Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
|
||||
Color32::WHITE,
|
||||
);
|
||||
ui.painter().add(Shape::mesh(mesh));
|
||||
|
||||
response
|
||||
}
|
||||
Ok(TexturePoll::Pending { .. }) => {
|
||||
ui.spinner().on_hover_text(format!("Loading {uri:?}…"))
|
||||
}
|
||||
Err(err) => ui.colored_label(ui.visuals().error_fg_color, err.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ pub mod text_edit;
|
||||
pub use button::*;
|
||||
pub use drag_value::DragValue;
|
||||
pub use hyperlink::*;
|
||||
pub use image::Image;
|
||||
pub use image::{Image, Image2, ImageSource};
|
||||
pub use label::*;
|
||||
pub use progress_bar::ProgressBar;
|
||||
pub use selected_label::SelectableLabel;
|
||||
|
||||
Reference in New Issue
Block a user