From 505588d5851fed8a3bb334edacfa6d96c545d562 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 29 Nov 2019 21:44:39 +0100 Subject: Allow to load an image from memory New `image::Handle` opaque type uniquely identifying some `image::Data`, allowing reliable caching. --- native/src/widget/image.rs | 93 +++++++++++++++++++++++++++++++++++---- wgpu/src/image.rs | 51 ++++++++++++++------- wgpu/src/primitive.rs | 6 +-- wgpu/src/renderer.rs | 4 +- wgpu/src/renderer/widget/image.rs | 12 +++-- 5 files changed, 133 insertions(+), 33 deletions(-) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index 4c588c9d..c82525e4 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, + rc::Rc, +}; /// A frame that displays an image while keeping aspect ratio. /// @@ -17,7 +21,7 @@ use std::hash::Hash; /// #[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>(path: T) -> Self { + pub fn new>(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, +} + +impl Handle { + /// Creates an image [`Handle`] pointing to the image of the given path. + /// + /// [`Handle`]: struct.Handle.html + pub fn from_path>(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) -> 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 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), +} + /// 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 for Element<'a, Message, Renderer> diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index 5dc972ac..479eb841 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -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>, + cache: RefCell>, 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], } 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 f27a4b8a..ad081383 100644 --- a/wgpu/src/renderer.rs +++ b/wgpu/src/renderer.rs @@ -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], }); 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, -- cgit From cdd34e1e4b741a97dc6da8813a00d792eda8172a Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sat, 30 Nov 2019 02:14:56 +0100 Subject: Implement `image` viewer example --- Cargo.toml | 1 + core/src/color.rs | 12 +++ examples/image.rs | 202 +++++++++++++++++++++++++++++++++++++++++++++ native/src/widget/image.rs | 39 +++++---- src/native.rs | 9 +- 5 files changed, 245 insertions(+), 18 deletions(-) create mode 100644 examples/image.rs diff --git a/Cargo.toml b/Cargo.toml index 7039a5b3..71d3b3cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ env_logger = "0.7" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" directories = "2.0" +reqwest = "0.9" [target.'cfg(target_arch = "wasm32")'.dev-dependencies] wasm-bindgen = "0.2.51" 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/image.rs b/examples/image.rs new file mode 100644 index 00000000..a64c0782 --- /dev/null +++ b/examples/image.rs @@ -0,0 +1,202 @@ +use iced::{ + button, image, Align, Application, Background, Button, Color, Column, + Command, Container, Element, HorizontalAlignment, Image, Length, Row, + Settings, Text, +}; +use serde::Deserialize; + +pub fn main() { + Example::run(Settings::default()) +} + +#[derive(Default)] +struct Example { + cats_button: button::State, + dogs_button: button::State, + image: Option, + state: State, +} + +enum State { + Idle, + Loading(Pet), + Error(LoadError), +} + +impl Default for State { + fn default() -> State { + State::Idle + } +} + +#[derive(Debug, Clone)] +enum Message { + PetChosen(Pet), + ImageLoaded(Result), +} + +#[derive(Debug, Clone, Copy)] +enum Pet { + Cat, + Dog, +} + +impl Application for Example { + type Message = Message; + + fn new() -> (Self, Command) { + (Self::default(), Command::none()) + } + + fn title(&self) -> String { + String::from("Image viewer - Iced") + } + + fn update(&mut self, message: Message) -> Command { + match message { + Message::PetChosen(pet) => match self.state { + State::Loading(_) => Command::none(), + _ => { + self.state = State::Loading(pet); + + Command::perform(get_pet_image(pet), Message::ImageLoaded) + } + }, + Message::ImageLoaded(Ok(image)) => { + self.image = Some(image); + self.state = State::Idle; + + Command::none() + } + Message::ImageLoaded(Err(error)) => { + self.state = State::Error(error); + + Command::none() + } + } + } + + fn view(&mut self) -> Element { + let Example { + cats_button, + dogs_button, + state, + image, + } = self; + + let choose: Element<_> = match state { + State::Loading(pet) => Text::new(format!( + "Getting your {} ready...", + match pet { + Pet::Cat => "cat", + Pet::Dog => "dog", + } + )) + .width(Length::Shrink) + .color([0.4, 0.4, 0.4]) + .into(), + _ => Row::new() + .width(Length::Shrink) + .spacing(20) + .push( + button( + cats_button, + "Cats", + Color::from_rgb8(0x89, 0x80, 0xF5), + ) + .on_press(Message::PetChosen(Pet::Cat)), + ) + .push( + button( + dogs_button, + "Dogs", + Color::from_rgb8(0x21, 0xD1, 0x9F), + ) + .on_press(Message::PetChosen(Pet::Dog)), + ) + .into(), + }; + + let content = Column::new() + .width(Length::Shrink) + .padding(20) + .spacing(20) + .align_items(Align::Center) + .push( + Text::new("What do you want to see?") + .width(Length::Shrink) + .horizontal_alignment(HorizontalAlignment::Center) + .size(40), + ) + .push(choose); + + let content = if let Some(image) = image { + content.push(Image::new(image.clone()).height(Length::Fill)) + } else { + content + }; + + Container::new(content) + .width(Length::Fill) + .height(Length::Fill) + .center_x() + .center_y() + .into() + } +} + +fn button<'a, Message>( + state: &'a mut button::State, + label: &str, + color: Color, +) -> Button<'a, Message> { + Button::new( + state, + Text::new(label) + .horizontal_alignment(HorizontalAlignment::Center) + .color(Color::WHITE) + .size(30), + ) + .padding(10) + .min_width(100) + .border_radius(10) + .background(Background::Color(color)) +} + +#[derive(Debug, Deserialize)] +pub struct SearchResult { + url: String, +} + +#[derive(Debug, Clone)] +enum LoadError { + RequestError, +} + +async fn get_pet_image(pet: Pet) -> Result { + use std::io::Read; + + let search = match pet { + Pet::Cat => "https://api.thecatapi.com/v1/images/search?limit=1&mime_types=jpg,png", + Pet::Dog => "https://api.thedogapi.com/v1/images/search?limit=1&mime_types=jpg,png", + }; + + let results: Vec = reqwest::get(search)?.json()?; + let url = &results.first().unwrap().url; + + let mut image = reqwest::get(url)?; + let mut bytes = Vec::new(); + + image + .read_to_end(&mut bytes) + .map_err(|_| LoadError::RequestError)?; + + Ok(image::Handle::from_bytes(bytes)) +} + +impl From for LoadError { + fn from(error: reqwest::Error) -> LoadError { + dbg!(&error); + LoadError::RequestError + } +} diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index c82525e4..aaa3eca5 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -5,7 +5,7 @@ use crate::{layout, Element, Hasher, Layout, Length, Point, Size, Widget}; use std::{ hash::{Hash, Hasher as _}, path::PathBuf, - rc::Rc, + sync::Arc, }; /// A frame that displays an image while keeping aspect ratio. @@ -76,20 +76,18 @@ where 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) } @@ -115,7 +113,7 @@ where #[derive(Debug, Clone)] pub struct Handle { id: u64, - data: Rc, + data: Arc, } impl Handle { @@ -139,7 +137,7 @@ impl Handle { Handle { id: hasher.finish(), - data: Rc::new(data), + data: Arc::new(data), } } @@ -173,7 +171,7 @@ impl From<&str> for Handle { /// The data of an [`Image`]. /// /// [`Image`]: struct.Image.html -#[derive(Debug, Clone, Hash)] +#[derive(Clone, Hash)] pub enum Data { /// File data Path(PathBuf), @@ -182,6 +180,15 @@ pub enum Data { Bytes(Vec), } +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 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, }; -- cgit From fab6d79e84adaad436c7a507ae2e38897ff1739c Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sat, 30 Nov 2019 02:55:14 +0100 Subject: Implement basic image cache trimming in iced_wgpu --- wgpu/src/image.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++------- wgpu/src/renderer.rs | 1 + 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index 479eb841..4e814468 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -4,11 +4,16 @@ use iced_native::{ Rectangle, }; -use std::{cell::RefCell, collections::HashMap, mem, rc::Rc}; +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + mem, + rc::Rc, +}; #[derive(Debug)] pub struct Pipeline { - cache: RefCell>, + cache: RefCell, pipeline: wgpu::RenderPipeline, uniforms: wgpu::Buffer, @@ -188,7 +193,7 @@ impl Pipeline { }); Pipeline { - cache: RefCell::new(HashMap::new()), + cache: RefCell::new(Cache::new()), pipeline, uniforms: uniforms_buffer, @@ -203,11 +208,11 @@ impl Pipeline { pub fn dimensions(&self, handle: &Handle) -> (u32, u32) { self.load(handle); - self.cache.borrow().get(&handle.id()).unwrap().dimensions() + self.cache.borrow_mut().get(handle).unwrap().dimensions() } fn load(&self, handle: &Handle) { - if !self.cache.borrow().contains_key(&handle.id()) { + if !self.cache.borrow().contains(&handle) { let memory = match handle.data() { Data::Path(path) => { if let Ok(image) = image::open(path) { @@ -229,7 +234,7 @@ impl Pipeline { } }; - let _ = self.cache.borrow_mut().insert(handle.id(), memory); + let _ = self.cache.borrow_mut().insert(&handle, memory); } } @@ -266,7 +271,7 @@ impl Pipeline { if let Some(texture) = self .cache .borrow_mut() - .get_mut(&image.handle.id()) + .get(&image.handle) .unwrap() .upload(device, encoder, &self.texture_layout) { @@ -330,6 +335,10 @@ impl Pipeline { } } } + + pub fn trim_cache(&mut self) { + self.cache.borrow_mut().trim(); + } } #[derive(Debug)] @@ -440,6 +449,42 @@ impl Memory { } } +#[derive(Debug)] +struct Cache { + map: HashMap, + hits: HashSet, +} + +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 handle: Handle, pub position: [f32; 2], diff --git a/wgpu/src/renderer.rs b/wgpu/src/renderer.rs index ad081383..8f0f7432 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 } -- cgit From 1747eb2745d032275dff652aed2c4d8730d377e6 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sat, 30 Nov 2019 04:10:16 +0100 Subject: Fix typo in `image::Handle` docs --- native/src/widget/image.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index aaa3eca5..1b3964d7 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -141,7 +141,7 @@ impl Handle { } } - /// Returns the uniquie identifier of the [`Handle`]. + /// Returns the unique identifier of the [`Handle`]. /// /// [`Handle`]: struct.Handle.html pub fn id(&self) -> u64 { -- cgit From 4293dcb2540144cc69a9f1370103bb780eca69f3 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 4 Dec 2019 03:55:33 +0100 Subject: Rename `image::Handle::from_bytes` to `from_memory` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also, replace `image` example with a new `pokedex` example using the PokéAPI. --- Cargo.toml | 1 + examples/image.rs | 202 --------------------------------------- examples/pokedex.rs | 231 +++++++++++++++++++++++++++++++++++++++++++++ native/src/widget/image.rs | 5 +- 4 files changed, 236 insertions(+), 203 deletions(-) delete mode 100644 examples/image.rs create mode 100644 examples/pokedex.rs diff --git a/Cargo.toml b/Cargo.toml index 71d3b3cd..888a1c07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,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/examples/image.rs b/examples/image.rs deleted file mode 100644 index a64c0782..00000000 --- a/examples/image.rs +++ /dev/null @@ -1,202 +0,0 @@ -use iced::{ - button, image, Align, Application, Background, Button, Color, Column, - Command, Container, Element, HorizontalAlignment, Image, Length, Row, - Settings, Text, -}; -use serde::Deserialize; - -pub fn main() { - Example::run(Settings::default()) -} - -#[derive(Default)] -struct Example { - cats_button: button::State, - dogs_button: button::State, - image: Option, - state: State, -} - -enum State { - Idle, - Loading(Pet), - Error(LoadError), -} - -impl Default for State { - fn default() -> State { - State::Idle - } -} - -#[derive(Debug, Clone)] -enum Message { - PetChosen(Pet), - ImageLoaded(Result), -} - -#[derive(Debug, Clone, Copy)] -enum Pet { - Cat, - Dog, -} - -impl Application for Example { - type Message = Message; - - fn new() -> (Self, Command) { - (Self::default(), Command::none()) - } - - fn title(&self) -> String { - String::from("Image viewer - Iced") - } - - fn update(&mut self, message: Message) -> Command { - match message { - Message::PetChosen(pet) => match self.state { - State::Loading(_) => Command::none(), - _ => { - self.state = State::Loading(pet); - - Command::perform(get_pet_image(pet), Message::ImageLoaded) - } - }, - Message::ImageLoaded(Ok(image)) => { - self.image = Some(image); - self.state = State::Idle; - - Command::none() - } - Message::ImageLoaded(Err(error)) => { - self.state = State::Error(error); - - Command::none() - } - } - } - - fn view(&mut self) -> Element { - let Example { - cats_button, - dogs_button, - state, - image, - } = self; - - let choose: Element<_> = match state { - State::Loading(pet) => Text::new(format!( - "Getting your {} ready...", - match pet { - Pet::Cat => "cat", - Pet::Dog => "dog", - } - )) - .width(Length::Shrink) - .color([0.4, 0.4, 0.4]) - .into(), - _ => Row::new() - .width(Length::Shrink) - .spacing(20) - .push( - button( - cats_button, - "Cats", - Color::from_rgb8(0x89, 0x80, 0xF5), - ) - .on_press(Message::PetChosen(Pet::Cat)), - ) - .push( - button( - dogs_button, - "Dogs", - Color::from_rgb8(0x21, 0xD1, 0x9F), - ) - .on_press(Message::PetChosen(Pet::Dog)), - ) - .into(), - }; - - let content = Column::new() - .width(Length::Shrink) - .padding(20) - .spacing(20) - .align_items(Align::Center) - .push( - Text::new("What do you want to see?") - .width(Length::Shrink) - .horizontal_alignment(HorizontalAlignment::Center) - .size(40), - ) - .push(choose); - - let content = if let Some(image) = image { - content.push(Image::new(image.clone()).height(Length::Fill)) - } else { - content - }; - - Container::new(content) - .width(Length::Fill) - .height(Length::Fill) - .center_x() - .center_y() - .into() - } -} - -fn button<'a, Message>( - state: &'a mut button::State, - label: &str, - color: Color, -) -> Button<'a, Message> { - Button::new( - state, - Text::new(label) - .horizontal_alignment(HorizontalAlignment::Center) - .color(Color::WHITE) - .size(30), - ) - .padding(10) - .min_width(100) - .border_radius(10) - .background(Background::Color(color)) -} - -#[derive(Debug, Deserialize)] -pub struct SearchResult { - url: String, -} - -#[derive(Debug, Clone)] -enum LoadError { - RequestError, -} - -async fn get_pet_image(pet: Pet) -> Result { - use std::io::Read; - - let search = match pet { - Pet::Cat => "https://api.thecatapi.com/v1/images/search?limit=1&mime_types=jpg,png", - Pet::Dog => "https://api.thedogapi.com/v1/images/search?limit=1&mime_types=jpg,png", - }; - - let results: Vec = reqwest::get(search)?.json()?; - let url = &results.first().unwrap().url; - - let mut image = reqwest::get(url)?; - let mut bytes = Vec::new(); - - image - .read_to_end(&mut bytes) - .map_err(|_| LoadError::RequestError)?; - - Ok(image::Handle::from_bytes(bytes)) -} - -impl From for LoadError { - fn from(error: reqwest::Error) -> LoadError { - dbg!(&error); - LoadError::RequestError - } -} 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), + Search, +} + +impl Application for Pokedex { + type Message = Message; + + fn new() -> (Pokedex, Command) { + ( + 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 { + 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 { + 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 { + 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 { + use rand::Rng; + use serde::Deserialize; + use std::io::Read; + + #[derive(Debug, Deserialize)] + struct Entry { + id: u32, + name: String, + flavor_text_entries: Vec, + } + + #[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 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/src/widget/image.rs b/native/src/widget/image.rs index 1b3964d7..0d73fdb0 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -126,8 +126,11 @@ impl Handle { /// 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_bytes(bytes: Vec) -> Handle { + pub fn from_memory(bytes: Vec) -> Handle { Self::from_data(Data::Bytes(bytes)) } -- cgit From 1f60e2820463ef9f7fe9dda5d8b8fa040fdd8666 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 4 Dec 2019 04:04:18 +0100 Subject: Update `Image::hash_layout` to hash new `Handle` --- native/src/widget/image.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index 7a7138ff..20375822 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -102,7 +102,7 @@ where } fn hash_layout(&self, state: &mut Hasher) { - self.path.hash(state); + self.handle.hash(state); self.width.hash(state); self.height.hash(state); } @@ -172,6 +172,12 @@ impl From<&str> for Handle { } } +impl Hash for Handle { + fn hash(&self, state: &mut H) { + self.id.hash(state); + } +} + /// The data of an [`Image`]. /// /// [`Image`]: struct.Image.html -- cgit From 2144109dd7f9ab811393d3d725ba1cb7371aa672 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 4 Dec 2019 04:10:56 +0100 Subject: Update changelogs --- core/CHANGELOG.md | 5 +++++ native/CHANGELOG.md | 11 +++++++++++ 2 files changed, 16 insertions(+) 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/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` now instead of an `Into`. [#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 -- cgit