Compare commits

...
Author SHA1 Message Date
1e46fed95a
fix: pull oreintation workaround from imagey
it also made sense to create the thumnail in the function,
since it is easier to rotate a smaller image.
(this is fine because max_width == max_height)
2026-08-09 15:59:23 -07:00
7d45896a6f
perf: create thumbnails, preload 2026-08-09 15:53:48 -07:00
d9751fe2e6
fix: flickering
it does still reload the image,
but at least it doesn't flicker while doing so

this also exposes a problem with the error reporting,
since with so many error-reporting operations going on,
the errors that do happen are most often immediately cleared.
2026-08-09 15:32:24 -07:00
26268f9771
fix: two possible causes of flickering
still flickers, likely due to aborting not working
since the async code isn't really async...
2026-08-09 15:27:38 -07:00
e179b824c8
feat: parallel loading 2026-08-09 15:10:16 -07:00
eaf0c674ab
refactor: prepare for parrelel loading with MaybeImage 2026-08-09 15:09:22 -07:00
05c5f7d37a
refactor: apply clippy lint 2026-08-09 14:19:36 -07:00
d6549939a8
feat: pick folder dialog 2026-08-09 14:04:44 -07:00
0c8149bd53
feat: ordered paths
this isn't a very robust solution,
but it is efficent and works on basic filenames.
2026-08-09 13:43:54 -07:00
6312d0a610
feat: show filename under thumbnail 2026-08-09 13:43:04 -07:00
5 changed files with 184 additions and 48 deletions

View file

@ -32,6 +32,8 @@
libxcb
]
++ lib.optionals stdenv.hostPlatform.isLinux [
dbus.lib
vulkan-loader
wayland
];

28
src/app/maybe_image.rs Normal file
View file

@ -0,0 +1,28 @@
use iced::{task, widget};
use image::DynamicImage;
#[derive(Clone, Debug, Default)]
pub enum MaybeImage {
#[default]
Unloaded,
#[allow(dead_code)]
/// should be abort_on_drop,
/// so that it will abort, for instance,
/// when it's set back to `Self::Unloaded`
Loading(task::Handle),
Loaded(widget::image::Handle),
}
impl MaybeImage {
pub fn handle(&self) -> Option<&widget::image::Handle> {
match self {
Self::Loaded(h) => Some(&h),
_ => None,
}
}
}
pub fn handle_from_image(image: DynamicImage) -> widget::image::Handle {
widget::image::Handle::from_rgba(image.width(), image.height(), image.into_rgba8().into_raw())
}

View file

@ -1,27 +1,46 @@
use std::{borrow::Cow, collections::HashMap, env, path::PathBuf, process};
use std::{
borrow::Cow,
collections::BTreeMap,
env,
path::{Path, PathBuf},
process,
sync::Arc,
};
use iced::{
Color, Element, Event, Length, Renderer, Subscription, Task, Theme, application, event,
keyboard, theme, widget, window,
};
use ignore::{WalkBuilder, types::TypesBuilder};
use image::ImageError;
use rayon::iter::{ParallelBridge, ParallelIterator};
use rfd::AsyncFileDialog;
use crate::SUPPORTED_TYPES;
use crate::{
SUPPORTED_TYPES,
app::maybe_image::{MaybeImage, handle_from_image},
utils,
};
mod maybe_image;
#[derive(Clone, Debug)]
enum Message {
LoadImage(PathBuf),
ImageLoaded(Result<(PathBuf, widget::image::Handle), Arc<ImageError>>),
UnloadImage(PathBuf),
OpenImage(PathBuf),
OpenPath(Option<PathBuf>),
KeyPressed(keyboard::Key, keyboard::Modifiers),
}
#[derive(Default)]
struct State {
images: HashMap<PathBuf, Option<widget::image::Handle>>,
images: BTreeMap<PathBuf, MaybeImage>,
columns: usize,
@ -29,47 +48,58 @@ struct State {
}
impl State {
fn new() -> Self {
let mut builder = TypesBuilder::new();
builder.add_defaults();
for ext in SUPPORTED_TYPES {
builder.add("supportedImages", ext).unwrap();
}
builder.select("supportedImages");
fn new() -> (Self, Task<Message>) {
(
Self {
columns: 3,
error: None,
images: WalkBuilder::new(
images: BTreeMap::new(),
},
Task::done(Message::OpenPath(Some(
env::args()
.nth(1)
.map(Cow::Owned)
.unwrap_or(Cow::Borrowed("./"))
.as_ref(),
.unwrap_or_else(|| String::from("./"))
.into(),
))),
)
.types(builder.build().unwrap())
.max_depth(Some(1))
.build()
.par_bridge()
.filter_map(|r| {
r.inspect_err(|e| eprintln!("{e}"))
.ok()
.map(|entry| entry.into_path())
})
.filter(|path| path.is_file())
.map(|path| (path, None))
.collect(),
}
}
fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::LoadImage(path) => {
self.images
.entry(path.clone())
.and_modify(|e| *e = Some(widget::image::Handle::from_path(path)));
let entry = self.images.entry(path.clone()).or_default();
if matches!(entry, MaybeImage::Unloaded) {
let size = 1000 / self.columns as u32;
let (task, handle) = Task::perform(
async move {
utils::load_thumbnail(&path, size)
.map(|img| (path, handle_from_image(img)))
.map_err(Arc::new)
},
Message::ImageLoaded,
)
.abortable();
*entry = MaybeImage::Loading(handle.abort_on_drop());
return task;
}
}
Message::ImageLoaded(result) => {
self.error = result.as_ref().err().map(|e| e.to_string());
if let Ok((path, handle)) = result {
let entry = self.images.entry(path).or_default();
if matches!(entry, MaybeImage::Loaded(_)) {
self.error = Some("tried to load already-loaded image!".into())
} else {
*entry = MaybeImage::Loaded(handle)
}
}
}
Message::UnloadImage(path) => {
self.images.entry(path).and_modify(|e| *e = None);
self.images.entry(path).insert_entry(MaybeImage::Unloaded);
}
Message::OpenImage(path) => {
@ -80,6 +110,17 @@ impl State {
.err()
}
Message::OpenPath(opt_path) => {
self.error = match opt_path {
Some(_) => None,
None => Some("no path to open given".into()),
};
if let Some(path) = opt_path {
self.open_path(path);
}
}
Message::KeyPressed(key, modifiers) => match key.as_ref() {
// input field cycling
keyboard::Key::Named(keyboard::key::Named::Tab) => {
@ -90,6 +131,13 @@ impl State {
};
}
keyboard::Key::Character("o") => {
return Task::perform(
async { AsyncFileDialog::new().pick_folder().await.map(Into::into) },
Message::OpenPath,
);
}
keyboard::Key::Character("=" | "+") => {
self.columns = (self.columns + 1).clamp(1, 10)
}
@ -109,18 +157,28 @@ impl State {
fn view(&self) -> Element<'_, Message, Theme, Renderer> {
widget::column([
widget::scrollable(
widget::grid(self.images.iter().map(|(path, opt_handle)| {
widget::button(
widget::grid(self.images.iter().map(|(path, maybe_image)| {
widget::button(widget::column([
widget::container(
widget::sensor(opt_handle.as_ref().map_or_else(
widget::sensor(maybe_image.handle().map_or_else(
|| Element::from(widget::space()),
|handle| widget::image(handle).into(),
))
.anticipate(2000)
.on_show(|_size| Message::LoadImage(path.clone()))
.on_hide(Message::UnloadImage(path.clone())),
)
.center(Length::Fill),
.center(Length::Fill)
.into(),
widget::text(
path.file_name()
.map_or(Cow::Borrowed("[no file]"), |extension| {
extension.to_string_lossy()
}),
)
.center()
.into(),
]))
.style(widget::button::subtle)
.on_press(Message::OpenImage(path.clone()))
.into()
@ -129,13 +187,10 @@ impl State {
)
.height(Length::Fill)
.into(),
self.error
.as_ref()
.map_or_else(
self.error.as_ref().map_or_else(
|| Element::from(widget::space()),
|error| widget::text(error).style(widget::text::danger).into(),
)
.into(),
),
])
.into()
}
@ -148,6 +203,29 @@ impl State {
_ => None,
})
}
fn open_path(&mut self, path: impl AsRef<Path>) {
let mut builder = TypesBuilder::new();
builder.add_defaults();
for ext in SUPPORTED_TYPES {
builder.add("supportedImages", ext).unwrap();
}
builder.select("supportedImages");
self.images = WalkBuilder::new(path)
.types(builder.build().unwrap())
.max_depth(Some(1))
.build()
.par_bridge()
.filter_map(|r| {
r.inspect_err(|e| eprintln!("{e}"))
.ok()
.map(|entry| entry.into_path())
})
.filter(|path| path.is_file())
.map(|path| (path, MaybeImage::Unloaded))
.collect();
}
}
pub fn run() -> Result<(), impl std::error::Error> {

View file

@ -1,4 +1,5 @@
mod app;
mod utils;
const SUPPORTED_TYPES: &[&str; 20] = &[
"*.png", "*.PNG", "*.jpg", "*.JPG", "*.jpeg", "*.JPEG", "*.avif", "*.jxl", "*.bmp", "*.exr",

27
src/utils.rs Normal file
View file

@ -0,0 +1,27 @@
use std::{ffi::OsStr, path::Path};
use image::{DynamicImage, ImageDecoder, ImageReader, ImageResult};
pub fn load_thumbnail(path: impl AsRef<Path>, max_size: u32) -> ImageResult<DynamicImage> {
let mut decoder = ImageReader::open(&path)?
.with_guessed_format()?
.into_decoder()?;
let oreintation = decoder.orientation()?;
let mut decoded_image = DynamicImage::from_decoder(decoder)?.thumbnail(max_size, max_size);
// 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)
}