Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
8288a0a287
feat: "x" to copy image_path 2026-11-03 13:08:35 -08:00
7c271f8be9
refactor: fix clippy lints 2026-11-02 15:45:27 -08:00
3f994e6184
feat: don't show the app name in infobar 2026-11-02 15:43:34 -08:00
97dfa89a4a
feat: increase the size to use nearest scaling 2026-11-02 15:35:05 -08:00
7fb5173583
refactor: remove extra .into() 2026-10-31 18:28:46 -07:00
4333248ecc
refactor: simplify view code 2026-10-31 18:27:13 -07:00
88e0086db3
feat: improve infobar display
this makes WAY more sense:
now the error and status don't take up a fixed 1/2 space and wrap,
but instead they take space from each other as needed.
2026-10-31 18:07:56 -07:00
903dd4994c
build: update deps
without updating, I had an issue with hardware rendering
that made it fall back to slightly stuttery software rendering each time.

no error messages from iced or wgpu,
but I did get the following when running it with mangohud:
shim: Failed to load from "/nix/store/69q712zji0lqph80g6k75z6d3jhbbmb7-mangohud-0.8.4/lib/mangohud/libMangoHud_opengl.so": /nix/store/57iz36553175g3178pvxjij8z5rcsd4n-glibc-2.42-61/lib/libm.so.6: version `GLIBC_2.44' not found (required by /nix/store/69q712zji0lqph80g6k75z6d3jhbbmb7-mangohud-0.8.4/lib/mangohud/libMangoHud_opengl.so)
shim: Failed to load from ${ORIGIN}/libMangoHud_opengl.so: /nix/store/57iz36553175g3178pvxjij8z5rcsd4n-glibc-2.42-61/lib/libm.so.6: version `GLIBC_2.44' not found (required by /nix/store/69q712zji0lqph80g6k75z6d3jhbbmb7-mangohud-0.8.4/lib/mangohud/libMangoHud_opengl.so)
2026-10-07 18:32:47 -07:00
f4241b9711
refactor: use iced 0.15 rich clipboard
it does use arboard internally,
but it's nicer to use stuff built into iced
instead of dealing with the Clipboard object ourselves.
2026-08-28 12:31:20 -07:00
95a24fa987
refactor: use Cow<str> for errors
since some errors are just string literals;
this lets us avoid allocating a new string
2026-08-25 09:37:00 -07:00
63f6b6f81b
refactor: match keyboard keys in State::subscription
this is more flexible, and maybe more performant
2026-08-25 09:34:17 -07:00
869e38f3a5
refactor: filter out events in State::subscription
this may improve performance, saving update and view calls
2026-08-15 09:49:24 -07:00
65ddef28df
fix: missing svg mime type in desktopItem 2026-08-14 11:36:40 -07:00
85a80346e3
refactor: move svg integration into crate 2026-08-14 11:27:07 -07:00
16e13be214
minor: use name SVG over extension svg to identify errors
since the extension could be svg or svgz
2026-08-14 10:53:07 -07:00
a87a7bc0a1
feat: svg support 2026-08-14 10:25:46 -07:00
603678ba34
refactor: move kra to crate
in the interest of reusing that code in a gallery app
2026-08-03 23:30:21 -07:00
db457fc4e7
docs: add readme 2026-08-03 11:27:29 -07:00
e57c1c9322
fix: jxls being rotated twice 2026-08-01 10:22:41 -07:00
d3bc84769e
refactor: improve clipboard put code style 2026-07-31 20:17:25 -07:00
cb5e1d837a
feat: image copy and paste 2026-07-31 20:08:58 -07:00
1f909904c2
fix: print error on failed to read metadata
this should be very rare, so no need to display it or abort
2026-07-31 17:47:12 -07:00
808a8bf31d
feat: put the bars together
this made sense now that I made error messages shorter,
and figured out how to properly align things in a row.

looks good! might even consider keeping the infobar on by default
2026-07-31 17:32:52 -07:00
6fa0e29eae
feat: display file size 2026-07-31 17:23:29 -07:00
18de039e77
feat: make pickers async 2026-07-31 15:53:11 -07:00
9d4e24e809
refactor: apply clippy lints
cargo clippy --no-deps -- --deny clippy::nursery --deny clippy::pedantic
(does not quite pass due to unused `&self` in State::subscription)
I am considering ignoring events when the file picker is opened,
but that isn't a very nice solution (should just make it async atp)
2026-07-31 14:39:18 -07:00
94c905db38
build: seperate linux-specific deps 2026-07-31 14:19:53 -07:00
754dd6126d
fix: wrong dbus output (?) 2026-07-31 11:21:37 -07:00
26c17d5cf9
docs: add safety note 2026-07-31 11:14:05 -07:00
5a84b56025
build: use libdbus over zenity
I completely misunderstood the RFD doc comments,
thought that save file dialogs were not avaliable on linux outside of gtk

this helps avoid the wrapper, which is nice;
but I imagine it would fail if portals are unavaliable.
2026-07-31 09:55:08 -07:00
e98f268e59
refactor: do not format each ImageError
this makes the code much nicer,
but also it reduces the amount of extra fluff in the error messages.
2026-07-31 09:51:57 -07:00
973703726f
feat: guess format from magic numbers as well
this allows opening files with extensions that don't match the filetype
2026-07-31 09:16:38 -07:00
fca4577c0f
refactor(kra): factor out error mapping 2026-07-31 00:24:39 -07:00
57ad7dfb1e
build: reduce indirection slightly 2026-07-31 00:05:48 -07:00
b8b4d8698c
build: remove no-op wrapper argument 2026-07-31 00:03:35 -07:00
13976b91ea
fix: add .kra (krita) support to mimeTypes 2026-07-30 23:54:37 -07:00
101adc7a89
refactor: split kra (krita) logic into image hook
may further split this into its own crate;
seems quite useful! (albeit somewhat short and easy)

since there aren't any runtime dependancies,
it could even go into image-extras maybe
2026-07-30 23:40:14 -07:00
c96a1cbdd1
feat: default to FilterMethod::Nearest on small image
helps make pixelart sharp without the need to change it yourself
2026-07-30 22:54:56 -07:00
fc92ff60e0
feat: kra (krita) support 2026-07-30 22:41:17 -07:00
2e8a6c8546
feat: use single quotes in usage to reduce noise 2026-07-30 21:43:06 -07:00
50b5ed58b0
feat: add to usage reference 2026-07-30 21:40:14 -07:00
b1157474c9
feat: simplify theme 2026-07-30 20:35:45 -07:00
9bdd556c9d
refactor: use newer helper method in State::new
this should keep it from printing "no image to allocate"
each time when started without an argument
2026-07-30 20:27:34 -07:00
7ce87e2870
feat: optional infobar
literally the title; except on the bottom
2026-07-30 20:17:21 -07:00
97ce6754dd
feat: change scale limits
zooming in a lot is sometimes useful,
but zooming out is basically useless and annoying
(when you want to put it back to covering the full window)

if you really need to zoom out, you can always resize the window
2026-07-30 19:21:12 -07:00
f279c3aa15
feat: f to switch FilterMethod
useful to scale pixelart images nicely.

This makes me consider expanding the status bar to include info;
partially because I don't use window decorations usually
(so I don't see the info in the title)
2026-07-30 19:19:23 -07:00
e7e1400c3a
style: avoid toml curly braces
else it causes messy diffs and is generally less writable and readable
2026-07-29 16:11:48 -07:00
5a83fe39e9
feat: switch to pure-rust jxl decoder
this makes the logic drastically simpler;
as it comes with image crate integration.

however, images can no longer be saved as JXL with this version
(as jxl-oxide is decoder-only)
2026-07-29 16:11:35 -07:00
8 changed files with 1907 additions and 1439 deletions

2695
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -5,11 +5,25 @@ edition = "2024"
license = "AGPL-3.0-or-later"
[dependencies]
iced = { version = "0.14.0", features = [ "image" ] }
dirs = "6.0.0"
misc-image-integration = "0.1.0"
resvg = "0.48.1"
rfd = "0.17.2"
jpegxl-rs = "0.14.0"
size = "0.5.0"
zip = "8.6.0"
[dependencies.iced]
version = "0.15.0-dev"
features = [ "image" ]
[dependencies.image]
version = "0.25.10"
features = [ "avif-native" ]
[dependencies.jxl-oxide]
version = "0.12.6"
# I really wish the image crate was named better
features = [ "image" ]
[patch.crates-io]
iced.git = "https://github.com/iced-rs/iced"

41
README.md Normal file
View file

@ -0,0 +1,41 @@
# imagey
image viewer and maybe editor; inspired by mpv's simplicity
name is subject to change, suggestions welcome :)
## usage
```sh
# try it out!
nix run git+https://git.federated.nexus/electria/imagey
# install it imperatively
nix profile install git+https://git.federated.nexus/electria/imagey
```
keybinds are shown on startup if you didn't start it with an image
## known issues
### JXL
1. encoding is not implemented (jxl-oxide is decoding-only)
2. oreintation is incorrect in some cases
if the image has metadata oreintation AND
it's a jxl without the right extension OR
it's a jpeg with the jxl extension
this is due to the JXL decoder automatically rotating the image,
while the JPEG decoder (for instance) requires the extra step.
my workaround is to check the path of the input file,
not changing the oreintation if it has the jxl extension;
causing these caveats for cases where the extension is wrong.
### clipboard
1. large images (eg photos) don't seem to copy on linux/wayland,
(despite set_image not returning any error)

23
flake.lock generated
View file

@ -2,11 +2,11 @@
"nodes": {
"crane": {
"locked": {
"lastModified": 1781825982,
"narHash": "sha256-SlXKwIRIhrOSAcTjCB3ftPLzJWZStQIPS7J1FlZPnKk=",
"lastModified": 1790899423,
"narHash": "sha256-THGtz65UGJU+sonZidRboyCMk+9DclpMF7pwL4uDV4M=",
"owner": "ipetkov",
"repo": "crane",
"rev": "469fd08d0bcf6926321fa973c6777fbc87785dd7",
"rev": "47b6b27ed9a3a9181415e4367d0c30ab2a0e0250",
"type": "github"
},
"original": {
@ -35,18 +35,15 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1782175435,
"narHash": "sha256-EMzXKmnOtBQ2MnvpiNOm7E+kOMvdPrIKaeg52Tip2Uk=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "89570f24e97e614aa34aa9ab1c927b6578a43775",
"type": "github"
"lastModified": 1791260994,
"narHash": "sha256-MFBjw66d4h06MvpW6lIl7RwarLteD0sk859CncGwb1Q=",
"rev": "151fa4e8ddfdd8dd25d945ad94ed54a13de9f6e4",
"type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1086391.151fa4e8ddfd/nixexprs.tar.zst?lastModified=1791260994&rev=151fa4e8ddfdd8dd25d945ad94ed54a13de9f6e4"
},
"original": {
"owner": "nixos",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
"type": "tarball",
"url": "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst"
}
},
"root": {

View file

@ -1,6 +1,6 @@
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
nixpkgs.url = "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst";
crane.url = "github:ipetkov/crane";
@ -19,19 +19,25 @@
cargoToml = fromTOML (builtins.readFile ./Cargo.toml);
name = cargoToml.package.name;
dlDeps = with pkgs; [
# needed for both x11 and wayland
libxkbcommon
libGL
vulkan-loader
dlDeps =
with pkgs;
[
# needed for both x11 and wayland
libxkbcommon
libGL
wayland
libx11
libxcursor
libxi
libxcb
]
++ lib.optionals stdenv.hostPlatform.isLinux [
# libdbus, for rfd
dbus.lib
libx11
libxcursor
libxi
libxcb
];
vulkan-loader
wayland
];
commonArgs = {
# all that's needed for artifacts and checks
@ -39,15 +45,12 @@
pkg-config
];
buildInputs = with pkgs; [
libjxl
dav1d
];
src = ./.;
};
LD_LIBRARY_PATH = lib.makeLibraryPath dlDeps;
# Build *just* the cargo dependencies,
# to reuse them for build and test derivations.
cargoArtifacts = craneLib.buildDepsOnly commonArgs;
@ -71,6 +74,8 @@
"image/tiff"
"image/bmp"
"image/vnd.microsoft.icon" # .ico
"application/x-krita"
"image/svg+xml"
];
};
in
@ -79,19 +84,13 @@
// {
inherit cargoArtifacts;
nativeBuildInputs =
commonArgs.nativeBuildInputs
++ [
pkgs.autoPatchelfHook
]
++ lib.optional pkgs.stdenv.hostPlatform.isLinux pkgs.makeBinaryWrapper;
nativeBuildInputs = commonArgs.nativeBuildInputs ++ [
pkgs.autoPatchelfHook
];
buildInputs =
commonArgs.buildInputs
++ [
pkgs.libgcc
]
++ lib.optional pkgs.stdenv.hostPlatform.isLinux pkgs.zenity;
buildInputs = commonArgs.buildInputs ++ [
pkgs.libgcc
];
runtimeDependencies = dlDeps;
@ -100,10 +99,6 @@
postFixup = ''
mkdir -p "$out/share/applications"
ln -s "${desktopItem}"/share/applications/* "$out/share/applications/"
''
+ lib.optionalString pkgs.stdenv.hostPlatform.isLinux /* sh */ ''
wrapProgram $out/bin/${name} --inherit-argv0 \
--prefix PATH : ${lib.makeBinPath [ pkgs.zenity ]}
'';
}
);
@ -123,7 +118,7 @@
};
devShells.default = craneLib.devShell {
inherit LD_LIBRARY_PATH;
LD_LIBRARY_PATH = lib.makeLibraryPath dlDeps;
inputsFrom = [ crate ];
packages = [ pkgs.rust-analyzer ];

View file

@ -1,153 +1,247 @@
use std::{env, path::Path};
use std::{borrow::Cow, env, ffi::OsStr, os::unix::fs::MetadataExt, path::PathBuf};
use iced::{
Alignment, Color, Element, Length, Renderer, Subscription, Task, Theme, color, event,
Alignment, Color, Length, Renderer, Subscription, Task, Theme, Widget, clipboard, event,
keyboard::{self, Key, key},
theme, widget, window,
};
use image::{EncodableLayout, RgbaImage, imageops};
use size::Size;
mod utils;
#[derive(Clone, Debug)]
enum Message {
ImageDisplayReady(Result<widget::image::Allocation, widget::image::Error>),
Open,
Rotate,
Invert,
Filter,
Bar,
Save,
Quit,
Event(iced::Event),
Yank,
Put,
ImageYanked(Result<(), clipboard::Error>),
ImagePut(Result<clipboard::Image, clipboard::Error>),
YankPath,
PathYanked(Result<(), clipboard::Error>),
FocusNext,
FocusPrevious,
ImagePicked(Result<PathBuf, Cow<'static, str>>),
ImageDisplayReady(Result<widget::image::Allocation, widget::image::Error>),
SavePathPicked(Result<PathBuf, Cow<'static, str>>),
FileDropped(PathBuf),
}
#[derive(Clone, Debug, Default)]
#[derive(Default)]
struct State {
image: Option<RgbaImage>,
image_display: Option<widget::image::Allocation>,
image_filter: widget::image::FilterMethod,
image_path: Option<PathBuf>,
error: Option<String>,
error: Option<Cow<'static, str>>,
info: Option<String>,
infobar_shown: bool,
}
impl State {
fn new() -> (Self, Task<Message>) {
let mut state = State::default();
let mut state = Self::default();
state.error = env::args().nth(1).and_then(|path| {
utils::load_image(path)
.map(|image| state.image = Some(image))
.err()
});
let allocate_image = state.allocate_image();
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),
}
}
(state, allocate_image)
(state, Task::none())
}
fn view(&self) -> Element<'_, Message, Theme, Renderer> {
widget::column([
if let Some(allocation) = self.image_display.as_ref() {
widget::image::viewer(allocation.handle().clone())
.width(Length::Fill)
.height(Length::Fill)
.into()
} else {
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")))
.height(Length::Fill)
.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)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.into()
.height(Length::Fill)
.boxed()
},
if let Some(error) = self.error.as_ref() {
widget::text(error).style(widget::text::danger).into()
} else {
widget::space().into()
},
])
.into()
);
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)
})
});
widget::column![main, widget::row![error, info]]
}
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)) {
Err(e) => self.error = Some(e),
Ok(task) => {
self.error = None;
return task;
}
}
}
Message::ImageDisplayReady(result) => {
self.image_display = Some(result.unwrap());
}
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()),
)
})
.err();
}
Message::Event(iced::Event::Keyboard(keyboard::Event::KeyPressed {
key,
modifiers,
..
})) => match key.as_ref() {
// input field cycling
Key::Named(key::Named::Tab) => {
if modifiers.shift() {
return widget::operation::focus_previous();
} else {
return widget::operation::focus_next();
}
Message::FocusNext => return widget::operation::focus_next(),
Message::FocusPrevious => return widget::operation::focus_previous(),
Message::Open => {
return Task::perform(utils::pick_image(), Message::ImagePicked);
}
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();
}
Key::Character("o") => match self.pick_and_load_image() {
Ok(task) => {
self.error = None;
return task;
}
Err(e) => self.error = Some(e),
},
Key::Character("r") => {
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();
}
};
}
Key::Character("i") => {
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();
}
};
}
Key::Character("s") => {
self.save_image();
}
Key::Character("q") => return window::latest().and_then(window::close),
// ignore unused keys
_ => {}
},
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;
}
Message::Event(iced::Event::Window(window::Event::FileDropped(file))) => {
match self.load_image(file) {
Ok(task) => {
self.error = None;
return task;
Message::Save => {
if self.image.is_some() {
self.error = None;
return Task::perform(utils::pick_save_path(), Message::SavePathPicked);
}
self.error = Some("no image to save".into());
}
Message::Quit => return window::latest().and_then(window::close),
Message::Yank => {
if let Some(image) = self.image.as_ref() {
return clipboard::write(utils::clipboard_image_from_rgbaimage(image))
.map(Message::ImageYanked);
} else {
self.error = Some("no image to yank".into());
}
}
Message::Put => return clipboard::read_image().map(Message::ImagePut),
Message::ImagePut(result) => {
self.error = result.as_ref().err().map(|e| format!("{e:?}").into());
if let Ok(image) = result {
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;
}
Err(e) => self.error = Some(e),
self.image = Some(utils::rgbaimage_from_clipboard_image(image));
return self.allocate_image();
}
}
// ignore unused events
Message::Event(_) => {}
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;
}
Err(e) => self.error = Some(e.into()),
},
}
Task::none()
}
fn load_image(&mut self, path: impl AsRef<Path>) -> Result<Task<Message>, String> {
utils::load_image(path).map(|image| {
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!(
"{} {} {}x{}",
path.file_name()
.map_or(Cow::Borrowed("[no file]"), OsStr::to_string_lossy),
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(),
));
self.image_path = Some(path);
if image.dimensions() < (192, 192) {
self.image_filter = widget::image::FilterMethod::Nearest;
}
self.image = Some(image);
self.allocate_image()
})
}
fn pick_and_load_image(&mut self) -> Result<Task<Message>, String> {
utils::pick_image().and_then(|path| self.load_image(path))
}
fn save_image(&mut self) {
self.error = utils::save_image(self.image.as_ref()).err();
}
fn allocate_image(&self) -> Task<Message> {
let Some(image) = self.image.as_ref() else {
@ -158,35 +252,80 @@ impl State {
widget::image::allocate(widget::image::Handle::from_rgba(
image.width(),
image.height(),
// 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)
unsafe { std::mem::transmute::<&[u8], &'static [u8]>(image.as_bytes()) },
))
.map(Message::ImageDisplayReady)
}
fn subscription(&self) -> Subscription<Message> {
event::listen().map(Message::Event)
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),
Key::Character("y" | "c") => Some(Message::Yank),
Key::Character("p" | "v") => Some(Message::Put),
Key::Character("x") => Some(Message::YankPath),
_ => None,
}
}
iced::Event::Window(window::Event::FileDropped(path)) => {
Some(Message::FileDropped(path))
}
_ => None,
})
}
fn title(&self) -> String {
match self.image.as_ref() {
Some(image) => format!("imagey {}x{}", image.width(), image.height()),
None => "imagey".into(),
}
self.info.as_ref().map_or_else(
|| "imagey".into(),
|info| {
format!(
"imagey {info} {}",
utils::string_from_filter_type(self.image_filter),
)
},
)
}
}
fn main() -> Result<(), iced::Error> {
jxl_oxide::integration::register_image_decoding_hook();
misc_image_integration::register();
iced::application(State::new, State::update, State::view)
.subscription(State::subscription)
.title(State::title)
.theme(Theme::custom(
"custom",
theme::Palette {
background: color!(0x080808),
theme::palette::Seed {
background: Color::BLACK,
text: Color::WHITE,
primary: color!(0xff00ff),
success: color!(0x00ff00),
warning: color!(0x880000),
danger: color!(0xff0000),
..theme::palette::Seed::DARK
},
))
.run()

View file

@ -1,5 +1,12 @@
"o" to open a new image
"r" to rotate
"i" to invert colors
"s" to save the image
"q" to quit
'o' to open a new image
'r' to rotate
'i' to invert colors
'f' to switch filter
'b' to toggle the bar
's' to save the image
'q' to quit
'y' or 'c' to yank
'p' or 'v' to put
'x' to yank the path

View file

@ -1,150 +1,84 @@
use std::{
borrow::Cow,
ffi::OsStr,
fs,
io::Write,
path::{Path, PathBuf},
};
use image::{DynamicImage, ImageDecoder, ImageReader, RgbaImage};
use jpegxl_rs::image::ToDynamic;
use rfd::FileDialog;
use iced::{clipboard, widget};
use image::{DynamicImage, EncodableLayout, ImageDecoder, ImageReader, ImageResult, RgbaImage};
use rfd::AsyncFileDialog;
pub fn load_image(path: impl AsRef<Path>) -> Result<RgbaImage, String> {
let path = path.as_ref();
load_image_impl(path).map_err(|e| e.to_string())
}
fn load_image_impl(path: impl AsRef<Path>) -> ImageResult<RgbaImage> {
let mut decoder = ImageReader::open(&path)?
.with_guessed_format()?
.into_decoder()?;
let decoded_image = match path.extension().map(OsStr::to_string_lossy).as_deref() {
Some("jxl") => {
let data = match std::fs::read(path) {
Ok(d) => d,
Err(e) => {
return Err(format!(
"failed to read data from '{}': {e}",
path.display()
));
}
};
let oreintation = decoder.orientation()?;
match jpegxl_rs::decoder_builder()
.build()
.unwrap()
.decode_to_image(&data)
{
Ok(Some(decoded_image)) => decoded_image,
Ok(None) => {
return Err(format!(
"failed to convert jxl '{}' to DynamicImage",
path.display()
));
}
Err(e) => {
return Err(format!("failed to decode jxl '{}': {e}", path.display()));
}
}
}
let mut decoded_image = DynamicImage::from_decoder(decoder)?;
_ => {
let reader = match ImageReader::open(path) {
Ok(r) => r,
Err(e) => {
return Err(format!(
"failed to create reader for '{}': {e}",
path.display()
));
}
};
let mut decoder = match reader.into_decoder() {
Ok(d) => d,
Err(e) => {
return Err(format!(
"failed to create decoder for '{}': {e}",
path.display()
));
}
};
let oreintation = match decoder.orientation() {
Ok(o) => o,
Err(e) => {
return Err(format!(
"failed to get oreintation of '{}': {e}",
path.display()
));
}
};
let mut decoded_image = match DynamicImage::from_decoder(decoder) {
Ok(i) => i,
Err(e) => {
return Err(format!("failed to decode image '{}': {e}", path.display()));
}
};
decoded_image.apply_orientation(oreintation);
decoded_image
}
};
// the condition is a workaround to not rotate JXL images twice;
// since they are already rotated by the decoder
// (while jpegs for instance aren't)
if !path
.as_ref()
.extension()
.map(OsStr::to_string_lossy)
.is_some_and(|s| s == "jxl")
{
decoded_image.apply_orientation(oreintation);
}
Ok(decoded_image.into_rgba8())
}
pub fn pick_image() -> Result<PathBuf, String> {
let Some(path) = FileDialog::new()
pub async fn pick_image() -> Result<PathBuf, Cow<'static, str>> {
let Some(filehandle) = AsyncFileDialog::new()
.add_filter(
"image",
&[
"png", "PNG", "jpg", "JPG", "jpeg", "JPEG", "avif", "jxl", "bmp", "exr", "ff",
"gif", "hdr", "ico", "pnm", "qoi", "tga", "tiff", "webp",
"gif", "hdr", "ico", "pnm", "qoi", "tga", "tiff", "webp", "kra", "svg", "svgz",
],
)
.pick_file()
.await
else {
return Err("no path to open provided".into());
};
Ok(path)
Ok(filehandle.path().to_owned())
}
pub fn save_image(image: Option<&RgbaImage>) -> Result<(), String> {
let Some(image) = image else {
return Err("no image to save".into());
};
let Some(path) = FileDialog::new().save_file() else {
pub async fn pick_save_path() -> Result<PathBuf, Cow<'static, str>> {
let Some(filehandle) = AsyncFileDialog::new().save_file().await else {
return Err("no path to save provided".into());
};
let mut file = match fs::File::create(&path) {
Ok(f) => f,
Err(e) => return Err(format!("failed to create file '{}': {e}", path.display())),
};
Ok(filehandle.path().to_owned())
}
match path.extension().map(OsStr::to_string_lossy).as_deref() {
Some("jxl") => {
let mut encoder = jpegxl_rs::encoder_builder()
.speed(jpegxl_rs::encode::EncoderSpeed::Glacier)
.lossless(true)
.build()
.unwrap();
let rgb_image = DynamicImage::from(image.to_owned()).into_rgb8();
let jxl =
match encoder.encode::<u8, u8>(&rgb_image, rgb_image.width(), rgb_image.height()) {
Ok(j) => j,
Err(e) => {
return Err(format!("failed to encode jxl '{}': {e}", path.display()));
}
};
pub const fn string_from_filter_type(f: widget::image::FilterMethod) -> &'static str {
match f {
widget::image::FilterMethod::Linear => "bilinear",
widget::image::FilterMethod::Nearest => "nearest neighbor",
}
}
if let Err(e) = file.write(&jxl.data) {
return Err(format!("failed to write jxl to '{}': {e}", path.display()));
};
}
_ => {
if let Err(e) = image.save(&path) {
return Err(format!("failed to save '{}': {e}", path.display()));
};
}
};
Ok(())
pub fn clipboard_image_from_rgbaimage(image: &RgbaImage) -> clipboard::Image {
clipboard::Image {
size: (image.width(), image.height()).into(),
// SAFETY: this is also probably a race condition,
// where if the user switches the image before it's done,
// then something will die.
//
// however, especially with larger images,
// copying them is just too expensive.
rgba: unsafe { std::mem::transmute::<&[u8], &'static [u8]>(image.as_bytes()) }.into(),
}
}
pub fn rgbaimage_from_clipboard_image(image: clipboard::Image) -> RgbaImage {
RgbaImage::from_raw(image.size.width, image.size.height, image.rgba.into()).unwrap()
}