Merge pull request #2796 from tarkah/feat/gallery-enhancements

Add blurhash to gallery
This commit is contained in:
Héctor 2025-02-09 08:36:34 +01:00 committed by GitHub
commit 12653114bd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 225 additions and 60 deletions

7
Cargo.lock generated
View file

@ -664,6 +664,12 @@ dependencies = [
"piper", "piper",
] ]
[[package]]
name = "blurhash"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e79769241dcd44edf79a732545e8b5cec84c247ac060f5252cd51885d093a8fc"
[[package]] [[package]]
name = "built" name = "built"
version = "0.7.5" version = "0.7.5"
@ -1863,6 +1869,7 @@ dependencies = [
name = "gallery" name = "gallery"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"blurhash",
"bytes", "bytes",
"iced", "iced",
"image", "image",

View file

@ -200,6 +200,7 @@ unused_results = "deny"
[workspace.lints.clippy] [workspace.lints.clippy]
type-complexity = "allow" type-complexity = "allow"
map-entry = "allow"
semicolon_if_nothing_returned = "deny" semicolon_if_nothing_returned = "deny"
trivially-copy-pass-by-ref = "deny" trivially-copy-pass-by-ref = "deny"
default_trait_access = "deny" default_trait_access = "deny"

View file

@ -13,6 +13,7 @@ where
T: Clone + Copy + PartialEq + Float, T: Clone + Copy + PartialEq + Float,
{ {
raw: lilt::Animated<T, Instant>, raw: lilt::Animated<T, Instant>,
duration: Duration, // TODO: Expose duration getter in `lilt`
} }
impl<T> Animation<T> impl<T> Animation<T>
@ -23,6 +24,7 @@ where
pub fn new(state: T) -> Self { pub fn new(state: T) -> Self {
Self { Self {
raw: lilt::Animated::new(state), raw: lilt::Animated::new(state),
duration: Duration::from_millis(100),
} }
} }
@ -58,6 +60,7 @@ where
/// Sets the duration of the [`Animation`] to the given value. /// Sets the duration of the [`Animation`] to the given value.
pub fn duration(mut self, duration: Duration) -> Self { pub fn duration(mut self, duration: Duration) -> Self {
self.raw = self.raw.duration(duration.as_secs_f32() * 1_000.0); self.raw = self.raw.duration(duration.as_secs_f32() * 1_000.0);
self.duration = duration;
self self
} }
@ -133,4 +136,13 @@ impl Animation<bool> {
{ {
self.raw.animate_bool(start, end, at) self.raw.animate_bool(start, end, at)
} }
/// Returns the remaining [`Duration`] of the [`Animation`].
pub fn remaining(&self, at: Instant) -> Duration {
Duration::from_secs_f32(self.interpolate(
self.duration.as_secs_f32(),
0.0,
at,
))
}
} }

View file

@ -77,8 +77,8 @@ impl From<f32> for Length {
} }
} }
impl From<u16> for Length { impl From<u32> for Length {
fn from(units: u16) -> Self { fn from(units: u32) -> Self {
Length::Fixed(f32::from(units)) Length::Fixed(units as f32)
} }
} }

View file

@ -20,9 +20,9 @@ impl From<f32> for Pixels {
} }
} }
impl From<u16> for Pixels { impl From<u32> for Pixels {
fn from(amount: u16) -> Self { fn from(amount: u32) -> Self {
Self(f32::from(amount)) Self(amount as f32)
} }
} }

View file

@ -19,5 +19,7 @@ bytes.workspace = true
image.workspace = true image.workspace = true
tokio.workspace = true tokio.workspace = true
blurhash = "0.2.3"
[lints] [lints]
workspace = true workspace = true

View file

@ -10,6 +10,7 @@ use std::sync::Arc;
pub struct Image { pub struct Image {
pub id: Id, pub id: Id,
url: String, url: String,
hash: String,
} }
impl Image { impl Image {
@ -40,20 +41,37 @@ impl Image {
Ok(response.items) Ok(response.items)
} }
pub async fn blurhash(
self,
width: u32,
height: u32,
) -> Result<Rgba, Error> {
task::spawn_blocking(move || {
let pixels = blurhash::decode(&self.hash, width, height, 1.0)?;
Ok::<_, Error>(Rgba {
width,
height,
pixels: Bytes::from(pixels),
})
})
.await?
}
pub async fn download(self, size: Size) -> Result<Rgba, Error> { pub async fn download(self, size: Size) -> Result<Rgba, Error> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let bytes = client let bytes = client
.get(match size { .get(match size {
Size::Original => self.url, Size::Original => self.url,
Size::Thumbnail => self Size::Thumbnail { width } => self
.url .url
.split("/") .split("/")
.map(|part| { .map(|part| {
if part.starts_with("width=") { if part.starts_with("width=") {
"width=640" format!("width={}", width * 2) // High DPI
} else { } else {
part part.to_owned()
} }
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
@ -107,7 +125,7 @@ impl fmt::Debug for Rgba {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum Size { pub enum Size {
Original, Original,
Thumbnail, Thumbnail { width: u32 },
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -117,6 +135,7 @@ pub enum Error {
IOFailed(Arc<io::Error>), IOFailed(Arc<io::Error>),
JoinFailed(Arc<task::JoinError>), JoinFailed(Arc<task::JoinError>),
ImageDecodingFailed(Arc<image::ImageError>), ImageDecodingFailed(Arc<image::ImageError>),
BlurhashDecodingFailed(Arc<blurhash::Error>),
} }
impl From<reqwest::Error> for Error { impl From<reqwest::Error> for Error {
@ -142,3 +161,9 @@ impl From<image::ImageError> for Error {
Self::ImageDecodingFailed(Arc::new(error)) Self::ImageDecodingFailed(Arc::new(error))
} }
} }
impl From<blurhash::Error> for Error {
fn from(error: blurhash::Error) -> Self {
Self::BlurhashDecodingFailed(Arc::new(error))
}
}

View file

@ -7,7 +7,7 @@ mod civitai;
use crate::civitai::{Error, Id, Image, Rgba, Size}; use crate::civitai::{Error, Id, Image, Rgba, Size};
use iced::animation; use iced::animation;
use iced::time::Instant; use iced::time::{milliseconds, Instant};
use iced::widget::{ use iced::widget::{
button, center_x, container, horizontal_space, image, mouse_area, opaque, button, center_x, container, horizontal_space, image, mouse_area, opaque,
pop, row, scrollable, stack, pop, row, scrollable, stack,
@ -28,7 +28,7 @@ fn main() -> iced::Result {
struct Gallery { struct Gallery {
images: Vec<Image>, images: Vec<Image>,
thumbnails: HashMap<Id, Thumbnail>, previews: HashMap<Id, Preview>,
viewer: Viewer, viewer: Viewer,
now: Instant, now: Instant,
} }
@ -40,6 +40,7 @@ enum Message {
ImageDownloaded(Result<Rgba, Error>), ImageDownloaded(Result<Rgba, Error>),
ThumbnailDownloaded(Id, Result<Rgba, Error>), ThumbnailDownloaded(Id, Result<Rgba, Error>),
ThumbnailHovered(Id, bool), ThumbnailHovered(Id, bool),
BlurhashDecoded(Id, Result<Rgba, Error>),
Open(Id), Open(Id),
Close, Close,
Animate(Instant), Animate(Instant),
@ -50,7 +51,7 @@ impl Gallery {
( (
Self { Self {
images: Vec::new(), images: Vec::new(),
thumbnails: HashMap::new(), previews: HashMap::new(),
viewer: Viewer::new(), viewer: Viewer::new(),
now: Instant::now(), now: Instant::now(),
}, },
@ -64,9 +65,9 @@ impl Gallery {
pub fn subscription(&self) -> Subscription<Message> { pub fn subscription(&self) -> Subscription<Message> {
let is_animating = self let is_animating = self
.thumbnails .previews
.values() .values()
.any(|thumbnail| thumbnail.is_animating(self.now)) .any(|preview| preview.is_animating(self.now))
|| self.viewer.is_animating(self.now); || self.viewer.is_animating(self.now);
if is_animating { if is_animating {
@ -93,9 +94,18 @@ impl Gallery {
return Task::none(); return Task::none();
}; };
Task::perform(image.download(Size::Thumbnail), move |result| { Task::batch(vec![
Message::ThumbnailDownloaded(id, result) Task::perform(
}) image.clone().blurhash(Preview::WIDTH, Preview::HEIGHT),
move |result| Message::BlurhashDecoded(id, result),
),
Task::perform(
image.download(Size::Thumbnail {
width: Preview::WIDTH,
}),
move |result| Message::ThumbnailDownloaded(id, result),
),
])
} }
Message::ImageDownloaded(Ok(rgba)) => { Message::ImageDownloaded(Ok(rgba)) => {
self.viewer.show(rgba); self.viewer.show(rgba);
@ -103,14 +113,27 @@ impl Gallery {
Task::none() Task::none()
} }
Message::ThumbnailDownloaded(id, Ok(rgba)) => { Message::ThumbnailDownloaded(id, Ok(rgba)) => {
let thumbnail = Thumbnail::new(rgba); let thumbnail = if let Some(preview) = self.previews.remove(&id)
let _ = self.thumbnails.insert(id, thumbnail); {
preview.load(rgba)
} else {
Preview::ready(rgba)
};
let _ = self.previews.insert(id, thumbnail);
Task::none() Task::none()
} }
Message::ThumbnailHovered(id, is_hovered) => { Message::ThumbnailHovered(id, is_hovered) => {
if let Some(thumbnail) = self.thumbnails.get_mut(&id) { if let Some(preview) = self.previews.get_mut(&id) {
thumbnail.zoom.go_mut(is_hovered); preview.toggle_zoom(is_hovered);
}
Task::none()
}
Message::BlurhashDecoded(id, Ok(rgba)) => {
if !self.previews.contains_key(&id) {
let _ = self.previews.insert(id, Preview::loading(rgba));
} }
Task::none() Task::none()
@ -144,7 +167,8 @@ impl Gallery {
} }
Message::ImagesListed(Err(error)) Message::ImagesListed(Err(error))
| Message::ImageDownloaded(Err(error)) | Message::ImageDownloaded(Err(error))
| Message::ThumbnailDownloaded(_, Err(error)) => { | Message::ThumbnailDownloaded(_, Err(error))
| Message::BlurhashDecoded(_, Err(error)) => {
dbg!(error); dbg!(error);
Task::none() Task::none()
@ -157,7 +181,7 @@ impl Gallery {
row((0..=Image::LIMIT).map(|_| placeholder())) row((0..=Image::LIMIT).map(|_| placeholder()))
} else { } else {
row(self.images.iter().map(|image| { row(self.images.iter().map(|image| {
card(image, self.thumbnails.get(&image.id), self.now) card(image, self.previews.get(&image.id), self.now)
})) }))
} }
.spacing(10) .spacing(10)
@ -174,33 +198,52 @@ impl Gallery {
fn card<'a>( fn card<'a>(
metadata: &'a Image, metadata: &'a Image,
thumbnail: Option<&'a Thumbnail>, preview: Option<&'a Preview>,
now: Instant, now: Instant,
) -> Element<'a, Message> { ) -> Element<'a, Message> {
let image: Element<'_, _> = if let Some(thumbnail) = thumbnail { let image = if let Some(preview) = preview {
image(&thumbnail.handle) let thumbnail: Element<'_, _> =
.width(Fill) if let Preview::Ready { thumbnail, .. } = &preview {
.height(Fill) image(&thumbnail.handle)
.content_fit(ContentFit::Cover) .width(Fill)
.opacity(thumbnail.fade_in.interpolate(0.0, 1.0, now)) .height(Fill)
.scale(thumbnail.zoom.interpolate(1.0, 1.1, now)) .content_fit(ContentFit::Cover)
.into() .opacity(thumbnail.fade_in.interpolate(0.0, 1.0, now))
.scale(thumbnail.zoom.interpolate(1.0, 1.1, now))
.into()
} else {
horizontal_space().into()
};
if let Some(blurhash) = preview.blurhash(now) {
let blurhash = image(&blurhash.handle)
.width(Fill)
.height(Fill)
.content_fit(ContentFit::Cover)
.opacity(blurhash.fade_in.interpolate(0.0, 1.0, now));
stack![blurhash, thumbnail].into()
} else {
thumbnail
}
} else { } else {
horizontal_space().into() horizontal_space().into()
}; };
let card = mouse_area( let card = mouse_area(
container(image) container(image)
.width(Thumbnail::WIDTH) .width(Preview::WIDTH)
.height(Thumbnail::HEIGHT) .height(Preview::HEIGHT)
.style(container::dark), .style(container::dark),
) )
.on_enter(Message::ThumbnailHovered(metadata.id, true)) .on_enter(Message::ThumbnailHovered(metadata.id, true))
.on_exit(Message::ThumbnailHovered(metadata.id, false)); .on_exit(Message::ThumbnailHovered(metadata.id, false));
if thumbnail.is_some() { if let Some(preview) = preview {
let is_thumbnail = matches!(preview, Preview::Ready { .. });
button(card) button(card)
.on_press(Message::Open(metadata.id)) .on_press_maybe(is_thumbnail.then_some(Message::Open(metadata.id)))
.padding(0) .padding(0)
.style(button::text) .style(button::text)
.into() .into()
@ -213,23 +256,102 @@ fn card<'a>(
fn placeholder<'a>() -> Element<'a, Message> { fn placeholder<'a>() -> Element<'a, Message> {
container(horizontal_space()) container(horizontal_space())
.width(Thumbnail::WIDTH) .width(Preview::WIDTH)
.height(Thumbnail::HEIGHT) .height(Preview::HEIGHT)
.style(container::dark) .style(container::dark)
.into() .into()
} }
enum Preview {
Loading {
blurhash: Blurhash,
},
Ready {
blurhash: Option<Blurhash>,
thumbnail: Thumbnail,
},
}
struct Blurhash {
handle: image::Handle,
fade_in: Animation<bool>,
}
struct Thumbnail { struct Thumbnail {
handle: image::Handle, handle: image::Handle,
fade_in: Animation<bool>, fade_in: Animation<bool>,
zoom: Animation<bool>, zoom: Animation<bool>,
} }
impl Thumbnail { impl Preview {
const WIDTH: u16 = 320; const WIDTH: u32 = 320;
const HEIGHT: u16 = 410; const HEIGHT: u32 = 410;
fn new(rgba: Rgba) -> Self { fn loading(rgba: Rgba) -> Self {
Self::Loading {
blurhash: Blurhash {
fade_in: Animation::new(false)
.duration(milliseconds(700))
.easing(animation::Easing::EaseIn)
.go(true),
handle: image::Handle::from_rgba(
rgba.width,
rgba.height,
rgba.pixels,
),
},
}
}
fn ready(rgba: Rgba) -> Self {
Self::Ready {
blurhash: None,
thumbnail: Thumbnail::new(rgba),
}
}
fn load(self, rgba: Rgba) -> Self {
let Self::Loading { blurhash } = self else {
return self;
};
Self::Ready {
blurhash: Some(blurhash),
thumbnail: Thumbnail::new(rgba),
}
}
fn toggle_zoom(&mut self, enabled: bool) {
if let Self::Ready { thumbnail, .. } = self {
thumbnail.zoom.go_mut(enabled);
}
}
fn is_animating(&self, now: Instant) -> bool {
match &self {
Self::Loading { blurhash } => blurhash.fade_in.is_animating(now),
Self::Ready { thumbnail, .. } => {
thumbnail.fade_in.is_animating(now)
|| thumbnail.zoom.is_animating(now)
}
}
}
fn blurhash(&self, now: Instant) -> Option<&Blurhash> {
match self {
Self::Loading { blurhash, .. } => Some(blurhash),
Self::Ready {
blurhash: Some(blurhash),
thumbnail,
..
} if thumbnail.fade_in.is_animating(now) => Some(blurhash),
Self::Ready { .. } => None,
}
}
}
impl Thumbnail {
pub fn new(rgba: Rgba) -> Self {
Self { Self {
handle: image::Handle::from_rgba( handle: image::Handle::from_rgba(
rgba.width, rgba.width,
@ -242,10 +364,6 @@ impl Thumbnail {
.easing(animation::Easing::EaseInOut), .easing(animation::Easing::EaseInOut),
} }
} }
fn is_animating(&self, now: Instant) -> bool {
self.fade_in.is_animating(now) || self.zoom.is_animating(now)
}
} }
struct Viewer { struct Viewer {

View file

@ -21,9 +21,9 @@ pub fn main() -> iced::Result {
struct ScrollableDemo { struct ScrollableDemo {
scrollable_direction: Direction, scrollable_direction: Direction,
scrollbar_width: u16, scrollbar_width: u32,
scrollbar_margin: u16, scrollbar_margin: u32,
scroller_width: u16, scroller_width: u32,
current_scroll_offset: scrollable::RelativeOffset, current_scroll_offset: scrollable::RelativeOffset,
anchor: scrollable::Anchor, anchor: scrollable::Anchor,
} }
@ -39,9 +39,9 @@ enum Direction {
enum Message { enum Message {
SwitchDirection(Direction), SwitchDirection(Direction),
AlignmentChanged(scrollable::Anchor), AlignmentChanged(scrollable::Anchor),
ScrollbarWidthChanged(u16), ScrollbarWidthChanged(u32),
ScrollbarMarginChanged(u16), ScrollbarMarginChanged(u32),
ScrollerWidthChanged(u16), ScrollerWidthChanged(u32),
ScrollToBeginning, ScrollToBeginning,
ScrollToEnd, ScrollToEnd,
Scrolled(scrollable::Viewport), Scrolled(scrollable::Viewport),

View file

@ -24,12 +24,12 @@ pub struct Tour {
screen: Screen, screen: Screen,
slider: u8, slider: u8,
layout: Layout, layout: Layout,
spacing: u16, spacing: u32,
text_size: u16, text_size: u32,
text_color: Color, text_color: Color,
language: Option<Language>, language: Option<Language>,
toggler: bool, toggler: bool,
image_width: u16, image_width: u32,
image_filter_method: image::FilterMethod, image_filter_method: image::FilterMethod,
input_value: String, input_value: String,
input_is_secure: bool, input_is_secure: bool,
@ -43,11 +43,11 @@ pub enum Message {
NextPressed, NextPressed,
SliderChanged(u8), SliderChanged(u8),
LayoutChanged(Layout), LayoutChanged(Layout),
SpacingChanged(u16), SpacingChanged(u32),
TextSizeChanged(u16), TextSizeChanged(u32),
TextColorChanged(Color), TextColorChanged(Color),
LanguageSelected(Language), LanguageSelected(Language),
ImageWidthChanged(u16), ImageWidthChanged(u32),
ImageUseNearestToggled(bool), ImageUseNearestToggled(bool),
InputChanged(String), InputChanged(String),
ToggleSecureInput(bool), ToggleSecureInput(bool),
@ -537,7 +537,7 @@ impl Screen {
} }
fn ferris<'a>( fn ferris<'a>(
width: u16, width: u32,
filter_method: image::FilterMethod, filter_method: image::FilterMethod,
) -> Container<'a, Message> { ) -> Container<'a, Message> {
center_x( center_x(