diff options
author | 2019-12-04 04:28:07 +0100 | |
---|---|---|
committer | 2019-12-04 04:28:07 +0100 | |
commit | d1eb187e2673150b6c3f9fed0c15a1804ce0d75b (patch) | |
tree | 18ba66323f0aa2f3b8c25b80d1d74acfa41c13a2 | |
parent | 6c145bbb239e87569bf4aa797ea7f8d34e25cf62 (diff) | |
parent | 2144109dd7f9ab811393d3d725ba1cb7371aa672 (diff) | |
download | iced-d1eb187e2673150b6c3f9fed0c15a1804ce0d75b.tar.gz iced-d1eb187e2673150b6c3f9fed0c15a1804ce0d75b.tar.bz2 iced-d1eb187e2673150b6c3f9fed0c15a1804ce0d75b.zip |
Merge pull request #90 from hecrj/feature/image-from-bytes
Load images from memory and image viewer example
Diffstat (limited to '')
-rw-r--r-- | Cargo.toml | 2 | ||||
-rw-r--r-- | core/CHANGELOG.md | 5 | ||||
-rw-r--r-- | core/src/color.rs | 12 | ||||
-rw-r--r-- | examples/pokedex.rs | 231 | ||||
-rw-r--r-- | native/CHANGELOG.md | 11 | ||||
-rw-r--r-- | native/src/widget/image.rs | 135 | ||||
-rw-r--r-- | src/native.rs | 9 | ||||
-rw-r--r-- | wgpu/src/image.rs | 102 | ||||
-rw-r--r-- | wgpu/src/primitive.rs | 6 | ||||
-rw-r--r-- | wgpu/src/renderer.rs | 5 | ||||
-rw-r--r-- | wgpu/src/renderer/widget/image.rs | 12 |
11 files changed, 479 insertions, 51 deletions
@@ -39,6 +39,8 @@ env_logger = "0.7" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" directories = "2.0" +reqwest = "0.9" +rand = "0.7" [target.'cfg(target_arch = "wasm32")'.dev-dependencies] wasm-bindgen = "0.2.51" diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md index 30050238..c0796e66 100644 --- a/core/CHANGELOG.md +++ b/core/CHANGELOG.md @@ -5,6 +5,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added +- `Color::from_rgb8` to easily build a `Color` from its hexadecimal representation. [#90] + +[#90]: https://github.com/hecrj/iced/pull/90 + ## [0.1.0] - 2019-11-25 ### Added diff --git a/core/src/color.rs b/core/src/color.rs index ec48c185..7b3649ad 100644 --- a/core/src/color.rs +++ b/core/src/color.rs @@ -25,6 +25,18 @@ impl Color { a: 1.0, }; + /// Creates a [`Color`] from its RGB8 components. + /// + /// [`Color`]: struct.Color.html + pub fn from_rgb8(r: u8, g: u8, b: u8) -> Color { + Color { + r: f32::from(r) / 255.0, + g: f32::from(g) / 255.0, + b: f32::from(b) / 255.0, + a: 1.0, + } + } + /// Converts the [`Color`] into its linear values. /// /// [`Color`]: struct.Color.html diff --git a/examples/pokedex.rs b/examples/pokedex.rs new file mode 100644 index 00000000..8e0af7b2 --- /dev/null +++ b/examples/pokedex.rs @@ -0,0 +1,231 @@ +use iced::{ + button, image, Align, Application, Background, Button, Color, Column, + Command, Container, Element, Image, Length, Row, Settings, Text, +}; + +pub fn main() { + Pokedex::run(Settings::default()) +} + +#[derive(Debug)] +enum Pokedex { + Loading, + Loaded { + pokemon: Pokemon, + search: button::State, + }, + Errored { + error: Error, + try_again: button::State, + }, +} + +#[derive(Debug, Clone)] +enum Message { + PokemonFound(Result<Pokemon, Error>), + Search, +} + +impl Application for Pokedex { + type Message = Message; + + fn new() -> (Pokedex, Command<Message>) { + ( + Pokedex::Loading, + Command::perform(Pokemon::search(), Message::PokemonFound), + ) + } + + fn title(&self) -> String { + let subtitle = match self { + Pokedex::Loading => "Loading", + Pokedex::Loaded { pokemon, .. } => &pokemon.name, + Pokedex::Errored { .. } => "Whoops!", + }; + + format!("{} - Pokédex", subtitle) + } + + fn update(&mut self, message: Message) -> Command<Message> { + match message { + Message::PokemonFound(Ok(pokemon)) => { + *self = Pokedex::Loaded { + pokemon, + search: button::State::new(), + }; + + Command::none() + } + Message::PokemonFound(Err(error)) => { + *self = Pokedex::Errored { + error, + try_again: button::State::new(), + }; + + Command::none() + } + Message::Search => match self { + Pokedex::Loading => Command::none(), + _ => { + *self = Pokedex::Loading; + + Command::perform(Pokemon::search(), Message::PokemonFound) + } + }, + } + } + + fn view(&mut self) -> Element<Message> { + let content = match self { + Pokedex::Loading => Column::new().width(Length::Shrink).push( + Text::new("Searching for Pokémon...") + .width(Length::Shrink) + .size(40), + ), + Pokedex::Loaded { pokemon, search } => Column::new() + .max_width(500) + .spacing(20) + .align_items(Align::End) + .push(pokemon.view()) + .push( + button(search, "Keep searching!").on_press(Message::Search), + ), + Pokedex::Errored { try_again, .. } => Column::new() + .width(Length::Shrink) + .spacing(20) + .align_items(Align::End) + .push( + Text::new("Whoops! Something went wrong...") + .width(Length::Shrink) + .size(40), + ) + .push(button(try_again, "Try again").on_press(Message::Search)), + }; + + Container::new(content) + .width(Length::Fill) + .height(Length::Fill) + .center_x() + .center_y() + .into() + } +} + +#[derive(Debug, Clone)] +struct Pokemon { + number: u16, + name: String, + description: String, + image: image::Handle, +} + +impl Pokemon { + const TOTAL: u16 = 807; + + fn view(&self) -> Element<Message> { + Row::new() + .spacing(20) + .align_items(Align::Center) + .push(Image::new(self.image.clone())) + .push( + Column::new() + .spacing(20) + .push( + Row::new() + .align_items(Align::Center) + .spacing(20) + .push(Text::new(&self.name).size(30)) + .push( + Text::new(format!("#{}", self.number)) + .width(Length::Shrink) + .size(20) + .color([0.5, 0.5, 0.5]), + ), + ) + .push(Text::new(&self.description)), + ) + .into() + } + + async fn search() -> Result<Pokemon, Error> { + use rand::Rng; + use serde::Deserialize; + use std::io::Read; + + #[derive(Debug, Deserialize)] + struct Entry { + id: u32, + name: String, + flavor_text_entries: Vec<FlavorText>, + } + + #[derive(Debug, Deserialize)] + struct FlavorText { + flavor_text: String, + language: Language, + } + + #[derive(Debug, Deserialize)] + struct Language { + name: String, + } + + let id = { + let mut rng = rand::thread_rng(); + + rng.gen_range(0, Pokemon::TOTAL) + }; + + let url = format!("https://pokeapi.co/api/v2/pokemon-species/{}", id); + let sprite = format!("https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/{}.png", id); + + let entry: Entry = reqwest::get(&url)?.json()?; + + let description = entry + .flavor_text_entries + .iter() + .filter(|text| text.language.name == "en") + .next() + .ok_or(Error::LanguageError)?; + + let mut sprite = reqwest::get(&sprite)?; + let mut bytes = Vec::new(); + + sprite + .read_to_end(&mut bytes) + .map_err(|_| Error::ImageError)?; + + Ok(Pokemon { + number: id, + name: entry.name.to_uppercase(), + description: description + .flavor_text + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(), + image: image::Handle::from_memory(bytes), + }) + } +} + +#[derive(Debug, Clone)] +enum Error { + APIError, + ImageError, + LanguageError, +} + +impl From<reqwest::Error> for Error { + fn from(error: reqwest::Error) -> Error { + dbg!(&error); + + Error::APIError + } +} + +fn button<'a>(state: &'a mut button::State, text: &str) -> Button<'a, Message> { + Button::new(state, Text::new(text).color(Color::WHITE)) + .background(Background::Color([0.11, 0.42, 0.87].into())) + .border_radius(10) + .padding(10) +} diff --git a/native/CHANGELOG.md b/native/CHANGELOG.md index d3638207..2a4bba3f 100644 --- a/native/CHANGELOG.md +++ b/native/CHANGELOG.md @@ -5,6 +5,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added +- `image::Handle` type with `from_path` and `from_memory` methods. [#90] +- `image::Data` enum representing different kinds of image data. [#90] + +### Changed +- `Image::new` takes an `Into<image::Handle>` now instead of an `Into<String>`. [#90] + +### Fixed +- `Image` widget not keeping aspect ratio consistently. [#90] + +[#90]: https://github.com/hecrj/iced/pull/90 ## [0.1.0] - 2019-11-25 ### Added diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index bcfc40b2..20375822 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -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, + sync::Arc, +}; /// 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,24 +72,22 @@ 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; - // TODO: Deal with additional cases - let (width, height) = match (self.width, self.height) { - (Length::Units(width), _) => ( - self.width, - Length::Units((width as f32 / aspect_ratio).round() as u16), - ), - (_, _) => { - (Length::Units(width as u16), Length::Units(height as u16)) - } - }; + let mut size = limits + .width(self.width) + .height(self.height) + .resolve(Size::new(width as f32, height as f32)); - let mut size = limits.width(width).height(height).resolve(Size::ZERO); + let viewport_aspect_ratio = size.width / size.height; - size.height = size.width / aspect_ratio; + if viewport_aspect_ratio > aspect_ratio { + size.width = width as f32 * size.height / height as f32; + } else { + size.height = height as f32 * size.width / width as f32; + } layout::Node::new(size) } @@ -96,16 +98,107 @@ 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) { - self.path.hash(state); + self.handle.hash(state); self.width.hash(state); self.height.hash(state); } } +/// An [`Image`] handle. +/// +/// [`Image`]: struct.Image.html +#[derive(Debug, Clone)] +pub struct Handle { + id: u64, + data: Arc<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. + /// + /// This is useful if you already have your image loaded in-memory, maybe + /// because you downloaded or generated it procedurally. + /// + /// [`Handle`]: struct.Handle.html + pub fn from_memory(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: Arc::new(data), + } + } + + /// Returns the unique 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) + } +} + +impl Hash for Handle { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + self.id.hash(state); + } +} + +/// The data of an [`Image`]. +/// +/// [`Image`]: struct.Image.html +#[derive(Clone, Hash)] +pub enum Data { + /// File data + Path(PathBuf), + + /// In-memory data + Bytes(Vec<u8>), +} + +impl std::fmt::Debug for Data { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Data::Path(path) => write!(f, "Path({:?})", path), + Data::Bytes(_) => write!(f, "Bytes(...)"), + } + } +} + /// The renderer of an [`Image`]. /// /// Your [renderer] will need to implement this trait before being able to use @@ -117,12 +210,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> diff --git a/src/native.rs b/src/native.rs index 926b2d11..3537dd52 100644 --- a/src/native.rs +++ b/src/native.rs @@ -75,11 +75,16 @@ pub mod widget { pub use iced_winit::slider::{Slider, State}; } - pub use iced_winit::{Checkbox, Image, Radio, Text}; + pub mod image { + //! Display images in your user interface. + pub use iced_winit::image::{Handle, Image}; + } + + pub use iced_winit::{Checkbox, Radio, Text}; #[doc(no_inline)] pub use { - button::Button, scrollable::Scrollable, slider::Slider, + button::Button, image::Image, scrollable::Scrollable, slider::Slider, text_input::TextInput, }; diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index 40d9c318..7e4e2670 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -1,11 +1,19 @@ use crate::Transformation; -use iced_native::Rectangle; - -use std::{cell::RefCell, collections::HashMap, mem, rc::Rc}; +use iced_native::{ + image::{Data, Handle}, + Rectangle, +}; + +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + mem, + rc::Rc, +}; #[derive(Debug)] pub struct Pipeline { - cache: RefCell<HashMap<String, Memory>>, + cache: RefCell<Cache>, pipeline: wgpu::RenderPipeline, uniforms: wgpu::Buffer, @@ -185,7 +193,7 @@ impl Pipeline { }); Pipeline { - cache: RefCell::new(HashMap::new()), + cache: RefCell::new(Cache::new()), pipeline, uniforms: uniforms_buffer, @@ -197,23 +205,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_mut().get(handle).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(&handle) { + 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, memory); } } @@ -245,12 +266,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(&image.handle) .unwrap() .upload(device, encoder, &self.texture_layout) { @@ -314,6 +335,10 @@ impl Pipeline { } } } + + pub fn trim_cache(&mut self) { + self.cache.borrow_mut().trim(); + } } #[derive(Debug)] @@ -327,6 +352,7 @@ enum Memory { height: u32, }, NotFound, + Invalid, } impl Memory { @@ -335,6 +361,7 @@ impl Memory { Memory::Host { image } => image.dimensions(), Memory::Device { width, height, .. } => (*width, *height), Memory::NotFound => (1, 1), + Memory::Invalid => (1, 1), } } @@ -417,12 +444,49 @@ impl Memory { } Memory::Device { bind_group, .. } => Some(bind_group.clone()), Memory::NotFound => None, + Memory::Invalid => None, + } + } +} + +#[derive(Debug)] +struct Cache { + map: HashMap<u64, Memory>, + hits: HashSet<u64>, +} + +impl Cache { + fn new() -> Self { + Self { + map: HashMap::new(), + hits: HashSet::new(), } } + + fn contains(&self, handle: &Handle) -> bool { + self.map.contains_key(&handle.id()) + } + + fn get(&mut self, handle: &Handle) -> Option<&mut Memory> { + let _ = self.hits.insert(handle.id()); + + self.map.get_mut(&handle.id()) + } + + fn insert(&mut self, handle: &Handle, memory: Memory) { + let _ = self.map.insert(handle.id(), memory); + } + + fn trim(&mut self) { + let hits = &self.hits; + + self.map.retain(|k, _| hits.contains(k)); + self.hits.clear(); + } } pub struct Image { - pub path: String, + pub handle: Handle, pub position: [f32; 2], pub scale: [f32; 2], } diff --git a/wgpu/src/primitive.rs b/wgpu/src/primitive.rs index 9efd74f6..04264e5d 100644 --- a/wgpu/src/primitive.rs +++ b/wgpu/src/primitive.rs @@ -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, }, diff --git a/wgpu/src/renderer.rs b/wgpu/src/renderer.rs index 268a3630..fa52bd96 100644 --- a/wgpu/src/renderer.rs +++ b/wgpu/src/renderer.rs @@ -127,6 +127,7 @@ impl Renderer { } self.queue.submit(&[encoder.finish()]); + self.image_pipeline.trim_cache(); *mouse_cursor } @@ -229,9 +230,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], }); diff --git a/wgpu/src/renderer/widget/image.rs b/wgpu/src/renderer/widget/image.rs index 0006dde1..70dc5d97 100644 --- a/wgpu/src/renderer/widget/image.rs +++ b/wgpu/src/renderer/widget/image.rs @@ -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, |