refactor: deduplicate into fn load_image

This commit is contained in:
electria 2026-07-02 10:15:46 -07:00
commit 53f78d9588
Signed by: electria
SSH key fingerprint: SHA256:8LlB3ucPbBHqozqkhsNbaV5oG3SlzzqUj8FZDL6IPQs

View file

@ -1,4 +1,4 @@
use std::{env, ffi::OsStr, fs}; use std::{env, ffi::OsStr, fs, path::Path};
use iced::{ use iced::{
Alignment, Color, Element, Length, Renderer, Subscription, Task, Theme, color, event, Alignment, Color, Element, Length, Renderer, Subscription, Task, Theme, color, event,
@ -15,7 +15,7 @@ enum Message {
Event(iced::Event), Event(iced::Event),
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
struct State { struct State {
image: Option<RgbaImage>, image: Option<RgbaImage>,
image_display: Option<widget::image::Allocation>, image_display: Option<widget::image::Allocation>,
@ -24,20 +24,9 @@ struct State {
} }
impl State { impl State {
fn new() -> (Self, Task<Message>) { fn new() -> (Self, Task<Message>) {
let state = State { let mut state = State::default();
image_display: None,
image: env::args().nth(1).and_then(|path| {
Some(
ImageReader::open(path)
.unwrap()
.decode()
.unwrap()
.into_rgba8(),
)
}),
error: None, env::args().nth(1).and_then(|path| state.load_image(path));
};
let allocate_image = state.allocate_image(); let allocate_image = state.allocate_image();
(state, allocate_image) (state, allocate_image)
@ -124,6 +113,31 @@ impl State {
Task::none() Task::none()
} }
fn load_image(&mut self, path: impl AsRef<Path>) -> Option<String> {
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<String> { fn open_image(&mut self) -> Option<String> {
let Some(path) = FileDialog::new() let Some(path) = FileDialog::new()
.add_filter( .add_filter(
@ -138,19 +152,7 @@ impl State {
return Some("no path to open provided".into()); return Some("no path to open provided".into());
}; };
let reader = match ImageReader::open(path) { self.load_image(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
} }
fn save_image(&self) -> Option<String> { fn save_image(&self) -> Option<String> {