imagey/src/main.rs

332 lines
12 KiB
Rust
Raw Permalink Normal View History

2026-11-03 13:04:16 -08:00
use std::{borrow::Cow, env, ffi::OsStr, os::unix::fs::MetadataExt, path::PathBuf};
2026-06-28 10:14:56 -07:00
use iced::{
Alignment, Color, Length, Renderer, Subscription, Task, Theme, Widget, clipboard, event,
2026-06-28 10:14:56 -07:00
keyboard::{self, Key, key},
2026-06-28 10:44:42 -07:00
theme, widget, window,
2026-06-28 10:14:56 -07:00
};
2026-07-09 20:48:34 -07:00
use image::{EncodableLayout, RgbaImage, imageops};
2026-07-31 17:23:29 -07:00
use size::Size;
2026-07-09 20:48:34 -07:00
mod utils;
2026-06-28 10:14:56 -07:00
#[derive(Clone, Debug)]
enum Message {
Open,
Rotate,
Invert,
Filter,
Bar,
Save,
Quit,
Yank,
Put,
ImageYanked(Result<(), clipboard::Error>),
ImagePut(Result<clipboard::Image, clipboard::Error>),
2026-11-03 13:04:16 -08:00
YankPath,
PathYanked(Result<(), clipboard::Error>),
FocusNext,
FocusPrevious,
ImagePicked(Result<PathBuf, Cow<'static, str>>),
2026-06-28 17:58:23 -07:00
ImageDisplayReady(Result<widget::image::Allocation, widget::image::Error>),
SavePathPicked(Result<PathBuf, Cow<'static, str>>),
2026-06-28 17:58:23 -07:00
FileDropped(PathBuf),
2026-06-28 10:14:56 -07:00
}
2026-07-31 19:36:58 -07:00
#[derive(Default)]
2026-06-28 10:14:56 -07:00
struct State {
2026-07-01 08:56:03 -07:00
image: Option<RgbaImage>,
2026-06-28 17:58:23 -07:00
image_display: Option<widget::image::Allocation>,
image_filter: widget::image::FilterMethod,
2026-11-03 13:04:16 -08:00
image_path: Option<PathBuf>,
2026-07-01 09:36:46 -07:00
error: Option<Cow<'static, str>>,
info: Option<String>,
infobar_shown: bool,
2026-06-28 10:14:56 -07:00
}
impl State {
2026-06-28 17:58:23 -07:00
fn new() -> (Self, Task<Message>) {
let mut state = Self::default();
2026-07-01 09:36:46 -07:00
if let Some(path) = env::args().nth(1) {
match state.load_image(path) {
Err(e) => state.error = Some(e.into()),
Ok(task) => return (state, task),
}
}
2026-06-28 17:58:23 -07:00
(state, Task::none())
2026-06-28 10:14:56 -07:00
}
fn view(&self) -> impl Widget<Message, Theme, Renderer> {
let main = self.image_display.as_ref().map_or_else(
|| {
widget::container(widget::text(include_str!("usage.txt")))
2026-10-31 18:25:24 -07:00
.center_x(Length::Fill)
.center_y(Length::Fill)
.boxed()
},
|allocation| {
widget::image::viewer(allocation.handle().clone())
.filter_method(self.image_filter)
.max_scale(50.)
.min_scale(1.)
.width(Length::Fill)
.height(Length::Fill)
.boxed()
},
);
2026-10-31 18:25:24 -07:00
let error = self
.error
.as_ref()
.map(|error| widget::text(error).style(widget::text::danger));
let info = self.infobar_shown.then_some(()).and_then(|()| {
self.info.as_ref().map(|info| {
widget::container(widget::text(info))
.align_x(Alignment::End)
.width(Length::Fill)
})
2026-10-31 18:25:24 -07:00
});
widget::column![main, widget::row![error, info]]
2026-06-28 10:14:56 -07:00
}
fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::ImagePicked(result) => {
match result.and_then(|path| self.load_image(path).map_err(Cow::from)) {
2026-10-31 18:28:46 -07:00
Err(e) => self.error = Some(e),
Ok(task) => {
self.error = None;
return task;
}
2026-07-31 15:11:41 -07:00
}
}
2026-06-28 17:58:23 -07:00
Message::ImageDisplayReady(result) => {
self.image_display = Some(result.unwrap());
}
2026-07-31 15:11:41 -07:00
Message::SavePathPicked(result) => {
self.error = result
.and_then(|path| {
self.image.as_ref().map_or_else(
|| Err("no image to save".into()),
|image| image.save(path).map_err(|e| e.to_string().into()),
2026-07-31 15:11:41 -07:00
)
})
.err();
}
2026-06-28 17:58:23 -07:00
Message::FocusNext => return widget::operation::focus_next(),
Message::FocusPrevious => return widget::operation::focus_previous(),
2026-06-28 10:14:56 -07:00
Message::Open => {
return Task::perform(utils::pick_image(), Message::ImagePicked);
}
2026-07-01 08:56:03 -07:00
Message::Rotate => match self.image.as_ref() {
None => self.error = Some("no image to rotate".into()),
Some(image) => {
self.error = None;
self.image = Some(imageops::rotate90(image));
return self.allocate_image();
}
},
Message::Invert => match self.image.as_mut() {
None => self.error = Some("no image to invert".into()),
Some(image) => {
self.error = None;
imageops::invert(image);
return self.allocate_image();
}
},
Message::Filter => {
self.image_filter = match self.image_filter {
widget::image::FilterMethod::Linear => widget::image::FilterMethod::Nearest,
widget::image::FilterMethod::Nearest => widget::image::FilterMethod::Linear,
}
}
Message::Bar => {
self.infobar_shown = !self.infobar_shown;
}
2026-07-01 08:56:03 -07:00
Message::Save => {
if self.image.is_some() {
self.error = None;
return Task::perform(utils::pick_save_path(), Message::SavePathPicked);
2026-06-29 08:46:45 -07:00
}
self.error = Some("no image to save".into());
}
2026-06-29 08:46:45 -07:00
Message::Quit => return window::latest().and_then(window::close),
2026-07-01 08:56:03 -07:00
Message::Yank => {
if let Some(image) = self.image.as_ref() {
2026-11-02 15:45:27 -08:00
return clipboard::write(utils::clipboard_image_from_rgbaimage(image))
.map(Message::ImageYanked);
} else {
self.error = Some("no image to yank".into());
2026-07-31 19:36:58 -07:00
}
}
Message::Put => return clipboard::read_image().map(Message::ImagePut),
2026-07-31 19:36:58 -07:00
Message::ImagePut(result) => {
self.error = result.as_ref().err().map(|e| format!("{e:?}").into());
if let Ok(image) = result {
2026-11-02 15:45:27 -08:00
self.info = Some(format!("{}x{}", image.size.width, image.size.height));
if (image.size.width, image.size.height) < (100, 100) {
self.image_filter = widget::image::FilterMethod::Nearest;
}
self.image = Some(utils::rgbaimage_from_clipboard_image(image));
return self.allocate_image();
}
}
2026-06-28 10:14:56 -07:00
2026-11-03 13:04:16 -08:00
Message::YankPath => {
if let Some(path) = self.image_path.as_ref() {
return clipboard::write(clipboard::Content::Text(
path.to_string_lossy().to_string(),
))
.map(Message::PathYanked);
} else {
self.error = Some("no path to yank".into());
}
}
Message::ImageYanked(result) | Message::PathYanked(result) => {
self.error = result.err().map(|e| format!("{e:?}").into());
}
Message::FileDropped(path) => match self.load_image(path) {
Ok(task) => {
self.error = None;
return task;
2026-07-27 21:42:52 -07:00
}
Err(e) => self.error = Some(e.into()),
},
2026-06-28 10:14:56 -07:00
}
Task::none()
}
2026-11-03 13:04:16 -08:00
fn load_image(&mut self, path: impl Into<PathBuf>) -> Result<Task<Message>, String> {
let path = path.into();
utils::load_image(&path).map(|image| {
self.info = Some(format!(
2026-07-31 17:23:29 -07:00
"{} {} {}x{}",
2026-11-03 13:04:16 -08:00
path.file_name()
.map_or(Cow::Borrowed("[no file]"), OsStr::to_string_lossy),
2026-11-03 13:04:16 -08:00
path.metadata().map_or_else(
|e| {
eprintln!("failed to read metadata: {e}");
Cow::Borrowed("[no size]")
},
|m| Cow::Owned(Size::from_bytes(m.size()).to_string())
),
image.width(),
image.height(),
));
2026-11-03 13:04:16 -08:00
self.image_path = Some(path);
if image.dimensions() < (192, 192) {
self.image_filter = widget::image::FilterMethod::Nearest;
}
2026-11-03 13:04:16 -08:00
self.image = Some(image);
2026-07-27 21:42:52 -07:00
self.allocate_image()
})
}
2026-07-01 09:52:20 -07:00
2026-06-28 18:02:09 -07:00
fn allocate_image(&self) -> Task<Message> {
2026-07-01 08:56:03 -07:00
let Some(image) = self.image.as_ref() else {
eprintln!("no image to allocate");
return Task::none();
};
2026-06-28 18:02:09 -07:00
widget::image::allocate(widget::image::Handle::from_rgba(
2026-07-01 08:56:03 -07:00
image.width(),
image.height(),
2026-07-31 11:14:05 -07:00
// SAFETY: this is a sort of race condition;
// will cause panics with large enough images,
// when they are edited consecutively.
//
// this can be reproduced by holding down 'i' with a 10k by 10k px image,
// which will invert the colors rapidly and eventually crash the app.
//
// however, that is not such a problem in this case,
// and I don't know a different way of doing this that doesn't copy
// (performance loss, which is can be pretty big)
// or likely cause flickering instead in such cases
// (like using Handle over Allocation to immediately drop the last one)
2026-07-03 15:51:55 -07:00
unsafe { std::mem::transmute::<&[u8], &'static [u8]>(image.as_bytes()) },
2026-06-28 18:02:09 -07:00
))
.map(Message::ImageDisplayReady)
}
2026-06-28 10:14:56 -07:00
fn subscription(&self) -> Subscription<Message> {
event::listen().filter_map(|event| match event {
iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) => {
match key.as_ref() {
Key::Named(key::Named::Tab) => Some(if modifiers.shift() {
Message::FocusPrevious
} else {
Message::FocusNext
}),
Key::Character("o") => Some(Message::Open),
Key::Character("r") => Some(Message::Rotate),
Key::Character("i") => Some(Message::Invert),
Key::Character("f") => Some(Message::Filter),
Key::Character("b") => Some(Message::Bar),
Key::Character("s") => Some(Message::Save),
Key::Character("q") => Some(Message::Quit),
2026-11-02 15:45:27 -08:00
Key::Character("y" | "c") => Some(Message::Yank),
Key::Character("p" | "v") => Some(Message::Put),
2026-11-03 13:04:16 -08:00
Key::Character("x") => Some(Message::YankPath),
_ => None,
}
}
iced::Event::Window(window::Event::FileDropped(path)) => {
Some(Message::FileDropped(path))
}
_ => None,
})
2026-06-28 10:14:56 -07:00
}
fn title(&self) -> String {
self.info.as_ref().map_or_else(
|| "imagey".into(),
|info| {
format!(
"imagey {info} {}",
utils::string_from_filter_type(self.image_filter),
)
},
)
}
2026-06-28 10:14:56 -07:00
}
fn main() -> Result<(), iced::Error> {
jxl_oxide::integration::register_image_decoding_hook();
misc_image_integration::register();
2026-06-28 10:14:56 -07:00
iced::application(State::new, State::update, State::view)
.subscription(State::subscription)
.title(State::title)
2026-06-28 10:14:56 -07:00
.theme(Theme::custom(
"custom",
theme::palette::Seed {
2026-07-30 20:35:45 -07:00
background: Color::BLACK,
2026-06-28 10:14:56 -07:00
text: Color::WHITE,
..theme::palette::Seed::DARK
2026-06-28 10:14:56 -07:00
},
))
.run()
}