Allow to load an image from memory

New `image::Handle` opaque type uniquely identifying some `image::Data`,
allowing reliable caching.
This commit is contained in:
Héctor Ramón Jiménez 2019-11-29 21:44:39 +01:00
parent 811d8b90d7
commit 505588d585
5 changed files with 133 additions and 33 deletions

View File

@ -2,7 +2,11 @@
use crate::{layout, Element, Hasher, Layout, Length, Point, Size, Widget};
use std::hash::Hash;
use std::{
hash::{Hash, Hasher as _},
path::PathBuf,
rc::Rc,
};
/// A frame that displays an image while keeping aspect ratio.
///
@ -17,7 +21,7 @@ use std::hash::Hash;
/// <img src="https://github.com/hecrj/iced/blob/9712b319bb7a32848001b96bd84977430f14b623/examples/resources/ferris.png?raw=true" width="300">
#[derive(Debug)]
pub struct Image {
path: String,
handle: Handle,
width: Length,
height: Length,
}
@ -26,9 +30,9 @@ impl Image {
/// Creates a new [`Image`] with the given path.
///
/// [`Image`]: struct.Image.html
pub fn new<T: Into<String>>(path: T) -> Self {
pub fn new<T: Into<Handle>>(handle: T) -> Self {
Image {
path: path.into(),
handle: handle.into(),
width: Length::Shrink,
height: Length::Shrink,
}
@ -68,7 +72,7 @@ where
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
let (width, height) = renderer.dimensions(&self.path);
let (width, height) = renderer.dimensions(&self.handle);
let aspect_ratio = width as f32 / height as f32;
@ -96,7 +100,7 @@ where
layout: Layout<'_>,
_cursor_position: Point,
) -> Renderer::Output {
renderer.draw(&self.path, layout)
renderer.draw(self.handle.clone(), layout)
}
fn hash_layout(&self, state: &mut Hasher) {
@ -105,6 +109,79 @@ where
}
}
/// An [`Image`] handle.
///
/// [`Image`]: struct.Image.html
#[derive(Debug, Clone)]
pub struct Handle {
id: u64,
data: Rc<Data>,
}
impl Handle {
/// Creates an image [`Handle`] pointing to the image of the given path.
///
/// [`Handle`]: struct.Handle.html
pub fn from_path<T: Into<PathBuf>>(path: T) -> Handle {
Self::from_data(Data::Path(path.into()))
}
/// Creates an image [`Handle`] containing the image data directly.
///
/// [`Handle`]: struct.Handle.html
pub fn from_bytes(bytes: Vec<u8>) -> Handle {
Self::from_data(Data::Bytes(bytes))
}
fn from_data(data: Data) -> Handle {
let mut hasher = Hasher::default();
data.hash(&mut hasher);
Handle {
id: hasher.finish(),
data: Rc::new(data),
}
}
/// Returns the uniquie identifier of the [`Handle`].
///
/// [`Handle`]: struct.Handle.html
pub fn id(&self) -> u64 {
self.id
}
/// Returns a reference to the image [`Data`].
///
/// [`Data`]: enum.Data.html
pub fn data(&self) -> &Data {
&self.data
}
}
impl From<String> for Handle {
fn from(path: String) -> Handle {
Handle::from_path(path)
}
}
impl From<&str> for Handle {
fn from(path: &str) -> Handle {
Handle::from_path(path)
}
}
/// The data of an [`Image`].
///
/// [`Image`]: struct.Image.html
#[derive(Debug, Clone, Hash)]
pub enum Data {
/// File data
Path(PathBuf),
/// In-memory data
Bytes(Vec<u8>),
}
/// The renderer of an [`Image`].
///
/// Your [renderer] will need to implement this trait before being able to use
@ -116,12 +193,12 @@ pub trait Renderer: crate::Renderer {
/// Returns the dimensions of an [`Image`] located on the given path.
///
/// [`Image`]: struct.Image.html
fn dimensions(&self, path: &str) -> (u32, u32);
fn dimensions(&self, handle: &Handle) -> (u32, u32);
/// Draws an [`Image`].
///
/// [`Image`]: struct.Image.html
fn draw(&mut self, path: &str, layout: Layout<'_>) -> Self::Output;
fn draw(&mut self, handle: Handle, layout: Layout<'_>) -> Self::Output;
}
impl<'a, Message, Renderer> From<Image> for Element<'a, Message, Renderer>

View File

@ -1,11 +1,14 @@
use crate::Transformation;
use iced_native::Rectangle;
use iced_native::{
image::{Data, Handle},
Rectangle,
};
use std::{cell::RefCell, collections::HashMap, mem, rc::Rc};
#[derive(Debug)]
pub struct Pipeline {
cache: RefCell<HashMap<String, Memory>>,
cache: RefCell<HashMap<u64, Memory>>,
pipeline: wgpu::RenderPipeline,
uniforms: wgpu::Buffer,
@ -197,23 +200,36 @@ impl Pipeline {
}
}
pub fn dimensions(&self, path: &str) -> (u32, u32) {
self.load(path);
pub fn dimensions(&self, handle: &Handle) -> (u32, u32) {
self.load(handle);
self.cache.borrow().get(path).unwrap().dimensions()
self.cache.borrow().get(&handle.id()).unwrap().dimensions()
}
fn load(&self, path: &str) {
if !self.cache.borrow().contains_key(path) {
let memory = if let Ok(image) = image::open(path) {
Memory::Host {
image: image.to_bgra(),
fn load(&self, handle: &Handle) {
if !self.cache.borrow().contains_key(&handle.id()) {
let memory = match handle.data() {
Data::Path(path) => {
if let Ok(image) = image::open(path) {
Memory::Host {
image: image.to_bgra(),
}
} else {
Memory::NotFound
}
}
Data::Bytes(bytes) => {
if let Ok(image) = image::load_from_memory(&bytes) {
Memory::Host {
image: image.to_bgra(),
}
} else {
Memory::Invalid
}
}
} else {
Memory::NotFound
};
let _ = self.cache.borrow_mut().insert(path.to_string(), memory);
let _ = self.cache.borrow_mut().insert(handle.id(), memory);
}
}
@ -245,12 +261,12 @@ impl Pipeline {
//
// [1]: https://github.com/nical/guillotiere
for image in instances {
self.load(&image.path);
self.load(&image.handle);
if let Some(texture) = self
.cache
.borrow_mut()
.get_mut(&image.path)
.get_mut(&image.handle.id())
.unwrap()
.upload(device, encoder, &self.texture_layout)
{
@ -327,6 +343,7 @@ enum Memory {
height: u32,
},
NotFound,
Invalid,
}
impl Memory {
@ -335,6 +352,7 @@ impl Memory {
Memory::Host { image } => image.dimensions(),
Memory::Device { width, height, .. } => (*width, *height),
Memory::NotFound => (1, 1),
Memory::Invalid => (1, 1),
}
}
@ -417,12 +435,13 @@ impl Memory {
}
Memory::Device { bind_group, .. } => Some(bind_group.clone()),
Memory::NotFound => None,
Memory::Invalid => None,
}
}
}
pub struct Image {
pub path: String,
pub handle: Handle,
pub position: [f32; 2],
pub scale: [f32; 2],
}

View File

@ -1,5 +1,5 @@
use iced_native::{
Background, Color, Font, HorizontalAlignment, Rectangle, Vector,
image, Background, Color, Font, HorizontalAlignment, Rectangle, Vector,
VerticalAlignment,
};
@ -41,8 +41,8 @@ pub enum Primitive {
},
/// An image primitive
Image {
/// The path of the image
path: String,
/// The handle of the image
handle: image::Handle,
/// The bounds of the image
bounds: Rectangle,
},

View File

@ -229,9 +229,9 @@ impl Renderer {
border_radius: *border_radius as f32,
});
}
Primitive::Image { path, bounds } => {
Primitive::Image { handle, bounds } => {
layer.images.push(Image {
path: path.clone(),
handle: handle.clone(),
position: [bounds.x, bounds.y],
scale: [bounds.width, bounds.height],
});

View File

@ -2,14 +2,18 @@ use crate::{Primitive, Renderer};
use iced_native::{image, Layout, MouseCursor};
impl image::Renderer for Renderer {
fn dimensions(&self, path: &str) -> (u32, u32) {
self.image_pipeline.dimensions(path)
fn dimensions(&self, handle: &image::Handle) -> (u32, u32) {
self.image_pipeline.dimensions(handle)
}
fn draw(&mut self, path: &str, layout: Layout<'_>) -> Self::Output {
fn draw(
&mut self,
handle: image::Handle,
layout: Layout<'_>,
) -> Self::Output {
(
Primitive::Image {
path: String::from(path),
handle,
bounds: layout.bounds(),
},
MouseCursor::OutOfBounds,