diff --git a/src/main.rs b/src/main.rs index 663d849..4a7180e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,4 @@ -use std::{env, ffi::OsStr, fs}; +use std::{env, ffi::OsStr, fs, path::Path}; use iced::{ Alignment, Color, Element, Length, Renderer, Subscription, Task, Theme, color, event, @@ -15,7 +15,7 @@ enum Message { Event(iced::Event), } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] struct State { image: Option, image_display: Option, @@ -24,20 +24,9 @@ struct State { } impl State { fn new() -> (Self, Task) { - let state = State { - image_display: None, - image: env::args().nth(1).and_then(|path| { - Some( - ImageReader::open(path) - .unwrap() - .decode() - .unwrap() - .into_rgba8(), - ) - }), + let mut state = State::default(); - error: None, - }; + env::args().nth(1).and_then(|path| state.load_image(path)); let allocate_image = state.allocate_image(); (state, allocate_image) @@ -124,6 +113,31 @@ impl State { Task::none() } + fn load_image(&mut self, path: impl AsRef) -> Option { + let reader = match ImageReader::open(&path) { + Ok(r) => r, + Err(e) => { + return Some(format!( + "failed to create reader for '{}': {e}", + path.as_ref().display() + )); + } + }; + + let decoded_image = match reader.decode() { + Ok(i) => i, + Err(e) => { + return Some(format!( + "failed to decode image '{}': {e}", + path.as_ref().display() + )); + } + }; + + self.image = Some(decoded_image.into_rgba8()); + + None + } fn open_image(&mut self) -> Option { let Some(path) = FileDialog::new() .add_filter( @@ -138,19 +152,7 @@ impl State { return Some("no path to open provided".into()); }; - let reader = match ImageReader::open(path) { - Ok(r) => r, - Err(e) => return Some(format!("failed to create reader: {e}")), - }; - - let decoded_image = match reader.decode() { - Ok(i) => i, - Err(e) => return Some(format!("failed to decode image: {e}")), - }; - - self.image = Some(decoded_image.into_rgba8()); - - None + self.load_image(path) } fn save_image(&self) -> Option {