diff --git a/Cargo.lock b/Cargo.lock index e5c5c72..89a0056 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5547,6 +5547,7 @@ dependencies = [ "tunal-dirmeta", "tunal-elevate", "tunal-theme", + "tunal-thumbs", "zbus", ] diff --git a/Plans/06 Thumbnails/S018-thumbnails-in-views.md b/Plans/06 Thumbnails/S018-thumbnails-in-views.md index bdc51c6..d58d997 100644 --- a/Plans/06 Thumbnails/S018-thumbnails-in-views.md +++ b/Plans/06 Thumbnails/S018-thumbnails-in-views.md @@ -10,11 +10,11 @@ Previews on/off; thumbnails requested only for visible items, faded in on arriva crates/tunal-thumbs API; crates/tunal/ui/views/*.slint; crates/tunal/src/folder/. ## Steps -- [ ] Previews toggle in the toolbar, default in settings, per folder through `.directory` view settings. -- [ ] Request from row/cell `init` (ListView only instantiates visible delegates), cancel when the delegate goes away; in-memory LRU of `slint::Image`. -- [ ] Fade-in on arrival; sizes per view (details small, grid large). -- [ ] Settings Previews page: video timestamp (percent/seconds), maximum file size, previews on remote locations (off by default). -- [ ] PROGRESS entry, INDEX line, commit `S018: …` +- [x] Previews toggle in the toolbar, default in settings, per folder through `.directory` view settings. +- [x] Request from row/cell `init` (ListView only instantiates visible delegates), cancel when the delegate goes away; in-memory LRU of `slint::Image`. +- [x] Fade-in on arrival; sizes per view (details small, grid large). +- [x] Settings Previews page: video timestamp (percent/seconds), maximum file size, previews on remote locations (off by default). +- [x] PROGRESS entry, INDEX line, commit `S018: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 6858364..ca1f9ab 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -40,7 +40,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 06 Thumbnails - [x] [S017 — Thumbnail generation and cache](06%20Thumbnails/S017-thumbnail-crate.md) · Sonnet high -- [ ] [S018 — Thumbnails in the views](06%20Thumbnails/S018-thumbnails-in-views.md) · Opus medium +- [x] [S018 — Thumbnails in the views](06%20Thumbnails/S018-thumbnails-in-views.md) · Opus medium ## 07 Tag editor diff --git a/crates/tunal/Cargo.toml b/crates/tunal/Cargo.toml index dad8479..f9a37f4 100644 --- a/crates/tunal/Cargo.toml +++ b/crates/tunal/Cargo.toml @@ -12,6 +12,7 @@ png.workspace = true tunal-core = { path = "../tunal-core" } tunal-elevate = { path = "../tunal-elevate" } tunal-dirmeta = { path = "../tunal-dirmeta" } +tunal-thumbs = { path = "../tunal-thumbs" } jiff.workspace = true serde.workspace = true zbus.workspace = true diff --git a/crates/tunal/src/config.rs b/crates/tunal/src/config.rs index d15e7d0..b15786a 100644 --- a/crates/tunal/src/config.rs +++ b/crates/tunal/src/config.rs @@ -118,6 +118,15 @@ pub enum Clock { H24, } +/// Unit of the video frame position used for previews. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum FrameUnit { + #[default] + Percent, + Seconds, +} + /// `settings.toml`. Later plans add their fields here. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] @@ -135,6 +144,15 @@ pub struct Settings { pub motion: Motion, pub date_style: DateStyle, pub clock: Clock, + /// What a new pane starts with: thumbnails instead of plain glyphs. + pub previews: bool, + /// Where in a video the preview frame is taken: a percent of its length or seconds in. + pub preview_frame_unit: FrameUnit, + pub preview_frame: u32, + /// Images and SVG files above this size (MiB) get no preview. + pub preview_max_mib: u32, + /// Previews on network file systems (off: browsing them stays fast). + pub preview_remote: bool, } impl Default for Settings { @@ -151,6 +169,11 @@ impl Default for Settings { motion: Motion::System, date_style: DateStyle::Relative, clock: Clock::H12, + previews: true, + preview_frame_unit: FrameUnit::Percent, + preview_frame: 10, + preview_max_mib: 64, + preview_remote: false, } } } diff --git a/crates/tunal/src/folder/load.rs b/crates/tunal/src/folder/load.rs index 438ee06..2d0fea4 100644 --- a/crates/tunal/src/folder/load.rs +++ b/crates/tunal/src/folder/load.rs @@ -24,6 +24,8 @@ pub enum Msg { View(u64, View), /// Icons and names from the `.directory` of child folders (by raw name). Looks(u64, Vec<(Vec, Look)>), + /// Thumbnails arrived (the pane's inbox holds them). + Thumbs, } pub enum Change { diff --git a/crates/tunal/src/folder/mod.rs b/crates/tunal/src/folder/mod.rs index 57d31de..c28be11 100644 --- a/crates/tunal/src/folder/mod.rs +++ b/crates/tunal/src/folder/mod.rs @@ -7,19 +7,23 @@ pub mod format; mod load; pub mod look; mod motion; +mod previews; mod sort; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; +use std::os::unix::ffi::OsStrExt; use std::rc::Rc; use std::time::{Duration, Instant}; use slint::{Model, ModelNotify, ModelRc, ModelTracker, SharedString, VecModel}; use tunal_core::playlist::Playlist; use tunal_core::{Entry, Error, Locations, Uri, Watch}; +use tunal_thumbs::{Priority, ThumbSize}; use crate::config; use crate::icons::{self, Category}; +use crate::thumbs_bridge::{self, Thumbs}; use crate::{ DetailRow, FolderState, FolderStatus, GridRow, Grouping, MenuEntry, MenuItem, NavKey, SortColumn, Travel, ViewMode, @@ -28,6 +32,7 @@ pub use load::Deliver; use load::{Change, Msg}; use look::Look; use motion::{Anim, Clock, Key, Old}; +use previews::{Arrival, Previews, Viewport}; pub use sort::{GroupBy, Settings, SortKey}; /// One entry with what sorting and drawing need, computed once. @@ -130,6 +135,9 @@ struct State { edit: Option>, /// An entry still to appear (created or renamed): selected, and edited if asked, once shown. pending: Option, + previews: Previews, + /// `previews` as the settings dialog last had it: a change of it applies to the pane. + cfg_previews: bool, } struct Pending { @@ -146,6 +154,7 @@ pub struct FolderModel { notify: ModelNotify, locations: Locations, deliver: Deliver, + thumbs: Rc, /// Called after every change the window must reflect (state, menu). changed: RefCell, /// Length of a list change (`MotionPrefs.list-change`); zero means instant. @@ -153,7 +162,8 @@ pub struct FolderModel { } impl FolderModel { - pub fn new(locations: Locations, deliver: Deliver) -> Rc { + pub fn new(locations: Locations, deliver: Deliver, thumbs: Rc) -> Rc { + let cfg = config::load::("settings"); Rc::new(Self { state: RefCell::new(State { dir: None, @@ -163,7 +173,7 @@ impl FolderModel { by_name: HashMap::new(), rows: Vec::new(), row_of: HashMap::new(), - settings: Settings::from_config(&config::load("settings")), + settings: Settings::from_config(&cfg), inherited: None, remembered: false, playlists: Vec::new(), @@ -181,10 +191,13 @@ impl FolderModel { cut: HashSet::new(), edit: None, pending: None, + previews: Previews::default(), + cfg_previews: cfg.previews, }), notify: ModelNotify::default(), locations, deliver, + thumbs, changed: RefCell::new(Box::new(|_| {})), list_time: RefCell::new(Box::new(|| Duration::ZERO)), }) @@ -248,6 +261,7 @@ impl FolderModel { s.anchor = None; s.edit = None; s.pending = None; + s.previews.clear(); if let Some(base) = s.inherited.take() { s.settings = base; } @@ -287,6 +301,23 @@ impl FolderModel { } }, Msg::Watching(g, guard) if g == current => s.watches.push(guard), + Msg::Thumbs => { + let arrivals = std::mem::take( + &mut *s.previews.inbox.lock().unwrap_or_else(|e| e.into_inner()), + ); + let mut rows = Vec::new(); + for a in arrivals.into_iter().filter(|a| a.generation == current) { + if let Some(row) = s.previews.arrive(a).and_then(|n| s.row_of.get(&n).copied()) + { + rows.push(row); + } + } + drop(s); + for row in rows { + self.notify.row_changed(row); + } + return; + } Msg::Changed(g, changes) if g == current => { // Reads are reported too: only entries whose stat differs count. let mut changed = false; @@ -342,6 +373,7 @@ impl FolderModel { drop(s); self.notify.reset(); self.emit(); + self.pump(); } /// The pane's settings as a folder would keep them in its `.directory`. @@ -498,6 +530,7 @@ impl FolderModel { items: shown as i32, hidden: hidden as i32, mode: s.settings.mode, + previews: s.settings.previews, motion: s.epoch, travel: s.travel, travel_epoch: s.travel_epoch, @@ -540,6 +573,7 @@ impl FolderModel { self.notify.reset(); } self.emit(); + self.pump(); } /// The grid view's column count changed: the lines reflow at once. @@ -557,6 +591,7 @@ impl FolderModel { self.notify.reset(); } self.emit(); + self.pump(); } // ---- list motion ----------------------------------------------------------------- @@ -655,6 +690,7 @@ impl FolderModel { drop(s); self.notify.reset(); self.emit(); + self.pump(); } /// Column header click: a new key sorts ascending, the same key flips the direction. @@ -708,6 +744,16 @@ impl FolderModel { s.folders_first = folders_first; }); } + // The pane keeps its own previews choice until the default itself changes. + let default_changed = { + let mut s = self.state.borrow_mut(); + std::mem::replace(&mut s.cfg_previews, cfg.previews) != cfg.previews + }; + if default_changed { + self.update(|s| s.previews = cfg.previews); + } else { + self.pump(); + } } /// Redraws the rows (a date setting changed, or a minute passed). @@ -741,6 +787,114 @@ impl FolderModel { self.update(|s| s.show_hidden = !s.show_hidden); } + pub fn toggle_previews(&self) { + self.update(|s| s.previews = !s.previews); + } + + // ---- previews --------------------------------------------------------------------- + + /// The view scrolled or resized: `top` and `height` of what it shows, and the heights of + /// its rows and (grid) cells, all logical pixels. + pub fn set_viewport(&self, top: f32, height: f32, row: f32, cell: f32) { + self.state.borrow_mut().previews.viewport = Viewport { + top: top.max(0.0), + height, + row, + cell: if cell > 0.0 { cell } else { 1.0 }, + }; + self.pump(); + } + + /// Asks for the thumbnails of the rows in view (and a few beyond), drops requests for rows + /// that scrolled away. + fn pump(&self) { + let mut s = self.state.borrow_mut(); + let epoch = self.thumbs.epoch(); + if s.previews.epoch != epoch { + s.previews.restart(epoch); + } + let dir = s.dir.as_ref().and_then(Uri::to_path); + let Some(dir) = dir + .filter(|_| s.settings.previews && matches!(s.status, Status::Ready | Status::Loading)) + else { + s.previews.cancel_all(); + return; + }; + let remote = *s + .previews + .remote + .get_or_insert_with(|| thumbs_bridge::on_network_fs(&dir)); + let size = match s.settings.mode { + ViewMode::Details => ThumbSize::Normal, + ViewMode::Grid => ThumbSize::Large, + }; + // Name and whether it is on screen (else just beyond it). + let mut wanted: Vec<(Vec, bool)> = Vec::new(); + for (row, near) in visible_rows(&s) { + if let Some(Row::Item(i)) = s.rows.get(row) { + let item = &s.items[*i]; + if !item.is_dir + && matches!( + item.category, + Category::Image | Category::Audio | Category::Video + ) + { + wanted.push((item.entry.name.clone(), near)); + } + } + } + { + let keep = wanted.iter().map(|(n, _)| n.as_slice()).collect(); + s.previews.cancel_except(&keep); + } + let generation = s.generation; + for (name, near) in wanted { + s.previews.touch(&name); + if !s.previews.needs(&name, size) { + continue; + } + let id = s.previews.next_id(); + let inbox = s.previews.inbox.clone(); + let deliver = self.deliver.clone(); + let key = name.clone(); + let ticket = self.thumbs.request( + dir.join(std::ffi::OsStr::from_bytes(&name)), + size, + remote, + if near { + Priority::Normal + } else { + Priority::Low + }, + move |pixels| { + inbox + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(Arrival { + generation, + id, + name: key, + size, + pixels, + }); + deliver(Msg::Thumbs); + }, + ); + s.previews.wait_for(name, id, ticket, size); + } + } + + /// Applies thumbnails as they arrive until none is pending or `limit` is up (screenshots, + /// which have no event loop to deliver them). + pub fn wait_thumbs(&self, limit: Duration) { + let start = Instant::now(); + while self.state.borrow().previews.is_waiting() && start.elapsed() < limit { + std::thread::sleep(Duration::from_millis(20)); + self.apply(Msg::Thumbs); + } + self.apply(Msg::Thumbs); + } + /// The sort menu, built from the current settings and the folder's playlists. pub fn sort_menu(&self) -> Vec { let s = self.state.borrow(); @@ -1229,6 +1383,7 @@ fn upsert(s: &mut State, entry: Entry) { match s.by_name.get(&entry.name) { Some(&i) => { let look = s.items[i].look.take(); + s.previews.forget(&entry.name); s.items[i] = Item::new(entry).with_look(look); } None => { @@ -1243,6 +1398,7 @@ fn remove(s: &mut State, name: &[u8]) -> bool { let Some(i) = s.by_name.remove(name) else { return false; }; + s.previews.forget(name); s.items.swap_remove(i); if let Some(moved) = s.items.get(i) { s.by_name.insert(moved.entry.name.clone(), i); @@ -1367,6 +1523,9 @@ fn apply_view(s: &mut State, view: &tunal_dirmeta::View) { if let Some(h) = view.hidden { set.show_hidden = h; } + if let Some(p) = view.previews { + set.previews = p; + } if view.sort.as_deref() == Some("playlist") && let (Some(dir), Some(file)) = (s.dir.as_ref().and_then(Uri::to_path), &view.playlist) { @@ -1414,7 +1573,7 @@ fn view_of(s: &State) -> tunal_dirmeta::View { .into(), ), hidden: Some(set.show_hidden), - previews: None, + previews: Some(set.previews), playlist, } } @@ -1446,6 +1605,40 @@ fn error_text(e: &Error) -> String { } } +/// Rows in view (`true`) and the few beyond it (`false`), for the previews to ask for. +fn visible_rows(s: &State) -> Vec<(usize, bool)> { + let v = s.previews.viewport; + let (top, bottom) = (v.top, v.top + v.height); + match s.settings.mode { + ViewMode::Details => { + let first = (top / v.row).floor() as i64; + let last = (bottom / v.row).ceil() as i64; + (first - PREFETCH_ROWS..last + PREFETCH_ROWS) + .filter(|&r| r >= 0) + .map(|r| (r as usize, (first..last).contains(&r))) + .collect() + } + ViewMode::Grid => { + let mut rows = Vec::new(); + let mut y = 0.0; + for line in motion::grid(&headers(s), &[], s.columns).0 { + let height = if line.header { v.row } else { v.cell }; + let (from, to) = (y, y + height); + y = to; + if line.header || to < top - v.cell || from > bottom + v.cell { + continue; + } + let near = to > top && from < bottom; + rows.extend((line.start..line.start + line.count).map(|r| (r as usize, near))); + } + rows + } + } +} + +/// Rows beyond the view that get a (low priority) thumbnail request, details view. +const PREFETCH_ROWS: i64 = 6; + /// The row as the views draw it, with its list motion. fn row_data(s: &State, row: usize) -> Option { let mut data = match s.rows.get(row)? { @@ -1462,8 +1655,15 @@ fn row_data(s: &State, row: usize) -> Option { let picture = look .and_then(|l| l.picture.as_deref()) .and_then(look::picture); + let thumb = if s.settings.previews && !item.is_dir { + s.previews.image(&entry.name) + } else { + None + }; DetailRow { header: false, + has_thumb: thumb.is_some(), + thumb: thumb.unwrap_or_default(), // Editing shows the real name: that is what a rename changes. name: if s.edit.as_ref() == Some(&entry.name) { entry.display_name.as_str() diff --git a/crates/tunal/src/folder/previews.rs b/crates/tunal/src/folder/previews.rs new file mode 100644 index 0000000..58d7432 --- /dev/null +++ b/crates/tunal/src/folder/previews.rs @@ -0,0 +1,198 @@ +//! Thumbnails of a folder's rows: the images on show (a small LRU), the requests in flight +//! and the files that got none. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::{Arc, Mutex}; + +use slint::{Image, Rgba8Pixel, SharedPixelBuffer}; +use tunal_thumbs::{ThumbSize, Ticket}; + +/// Images kept; the viewport touches the ones it shows, so those go last. +const KEEP: usize = 200; + +/// What the view last reported about its scroll position, in logical pixels. +#[derive(Clone, Copy)] +pub struct Viewport { + pub top: f32, + pub height: f32, + pub row: f32, + pub cell: f32, +} + +struct Shown { + size: ThumbSize, + image: Image, +} + +struct Waiting { + id: u64, + ticket: Ticket, + size: ThumbSize, +} + +/// A worker's answer, queued until the UI thread applies it. +pub struct Arrival { + pub generation: u64, + pub id: u64, + pub name: Vec, + pub size: ThumbSize, + pub pixels: Option>, +} + +pub struct Previews { + shown: HashMap, Shown>, + order: VecDeque>, + waiting: HashMap, Waiting>, + /// Files without a thumbnail (unsupported, too large, failed): not asked for again. + none: HashSet>, + next_id: u64, + pub inbox: Arc>>, + pub viewport: Viewport, + /// The folder is on a network file system (looked up once per folder). + pub remote: Option, + /// The `Thumbs` epoch the requests were made in. + pub epoch: u64, +} + +impl Default for Previews { + fn default() -> Self { + Self { + shown: HashMap::new(), + order: VecDeque::new(), + waiting: HashMap::new(), + none: HashSet::new(), + next_id: 0, + inbox: Arc::default(), + viewport: Viewport { + top: 0.0, + height: 800.0, + row: 40.0, + cell: 116.0, + }, + remote: None, + epoch: 0, + } + } +} + +impl Previews { + pub fn image(&self, name: &[u8]) -> Option { + self.shown.get(name).map(|s| s.image.clone()) + } + + /// The thumbnail of `name` is missing or smaller than `size`, and nothing is on its way. + pub fn needs(&self, name: &[u8], size: ThumbSize) -> bool { + !self.none.contains(name) + && !self.waiting.contains_key(name) + && self + .shown + .get(name) + .is_none_or(|s| s.size.pixels() < size.pixels()) + } + + pub fn next_id(&mut self) -> u64 { + self.next_id += 1; + self.next_id + } + + pub fn wait_for(&mut self, name: Vec, id: u64, ticket: Ticket, size: ThumbSize) { + self.waiting.insert(name, Waiting { id, ticket, size }); + } + + pub fn is_waiting(&self) -> bool { + !self.waiting.is_empty() + } + + /// Cancels what is waiting for a name outside `keep`. + pub fn cancel_except(&mut self, keep: &HashSet<&[u8]>) { + self.waiting.retain(|name, w| { + let wanted = keep.contains(name.as_slice()); + if !wanted { + w.ticket.cancel(); + } + wanted + }); + } + + pub fn cancel_all(&mut self) { + for w in self.waiting.values() { + w.ticket.cancel(); + } + self.waiting.clear(); + } + + /// A new pool: whatever was asked of the old one is forgotten, refused files get a retry. + pub fn restart(&mut self, epoch: u64) { + self.cancel_all(); + self.none.clear(); + self.epoch = epoch; + } + + /// The file changed or went: its thumbnail is stale. + pub fn forget(&mut self, name: &[u8]) { + if let Some(w) = self.waiting.remove(name) { + w.ticket.cancel(); + } + self.shown.remove(name); + self.order.retain(|n| n != name); + self.none.remove(name); + } + + /// A new folder. + pub fn clear(&mut self) { + self.cancel_all(); + self.shown.clear(); + self.order.clear(); + self.none.clear(); + self.remote = None; + } + + /// Marks `name` as used just now. + pub fn touch(&mut self, name: &[u8]) { + if self.shown.contains_key(name) + && let Some(at) = self.order.iter().position(|n| n == name) + && let Some(n) = self.order.remove(at) + { + self.order.push_back(n); + } + } + + /// Takes a worker's answer; the name when its row has to be redrawn. Answers to requests + /// that were cancelled or replaced since are dropped. + pub fn arrive(&mut self, a: Arrival) -> Option> { + if self.waiting.get(&a.name).is_none_or(|w| w.id != a.id) { + return None; + } + let waiting = self.waiting.remove(&a.name)?; + debug_assert_eq!(waiting.size, a.size); + let Some(pixels) = a.pixels else { + self.none.insert(a.name.clone()); + return Some(a.name); + }; + if self.shown.is_empty() { + self.order.clear(); + } + if self + .shown + .insert( + a.name.clone(), + Shown { + size: a.size, + image: Image::from_rgba8(pixels), + }, + ) + .is_none() + { + self.order.push_back(a.name.clone()); + } + while self.shown.len() > KEEP { + match self.order.pop_front() { + Some(old) => { + self.shown.remove(&old); + } + None => break, + } + } + Some(a.name) + } +} diff --git a/crates/tunal/src/folder/sort.rs b/crates/tunal/src/folder/sort.rs index 0d6ab3b..dc5d124 100644 --- a/crates/tunal/src/folder/sort.rs +++ b/crates/tunal/src/folder/sort.rs @@ -35,6 +35,8 @@ pub struct Settings { pub folders_first: bool, pub group: GroupBy, pub show_hidden: bool, + /// Thumbnails in place of plain glyphs. + pub previews: bool, pub filter: String, /// Details or grid; per pane like the rest, carried over between folders. pub mode: ViewMode, @@ -59,6 +61,7 @@ impl Settings { config::Group::Size => GroupBy::Size, }, show_hidden: cfg.show_hidden, + previews: cfg.previews, filter: String::new(), // `TUNAL_VIEW=grid` starts in the grid view (screenshots). mode: match (std::env::var("TUNAL_VIEW").as_deref(), cfg.view) { diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs index 9127bcd..c7bb00d 100644 --- a/crates/tunal/src/main.rs +++ b/crates/tunal/src/main.rs @@ -13,6 +13,7 @@ mod settings; mod shapes; mod shell; mod theme_bridge; +mod thumbs_bridge; use std::path::PathBuf; use std::process::ExitCode; @@ -41,17 +42,25 @@ fn main() -> ExitCode { Ok(()) }) .map_err(|e| e.to_string()), - Some(options) if args.gallery => screenshot::run(options, || gallery(args.page)), + Some(options) if args.gallery => screenshot::run(options, || gallery(args.page), || {}), // A screenshot is one frame: list the folder before it is drawn. The shell lives until // the frame is drawn, so callbacks fired while drawing (grid columns) still reach it. Some(options) => { - let mut shell = None; - screenshot::run(options, || { - window(args.tabs, true).map(|(ui, s)| { - shell = Some(s); - ui - }) - }) + let shell = std::cell::RefCell::new(None); + screenshot::run( + options, + || { + window(args.tabs, true).map(|(ui, s)| { + *shell.borrow_mut() = Some(s); + ui + }) + }, + || { + if let Some(shell) = shell.borrow().as_ref() { + shell.settle_thumbs(); + } + }, + ) } }); match result { diff --git a/crates/tunal/src/screenshot.rs b/crates/tunal/src/screenshot.rs index d8854b1..f26663a 100644 --- a/crates/tunal/src/screenshot.rs +++ b/crates/tunal/src/screenshot.rs @@ -33,6 +33,7 @@ pub struct Options { pub fn run( options: Options, new: impl FnOnce() -> Result, + settle: impl FnOnce(), ) -> Result<(), String> { let window = MinimalSoftwareWindow::new(RepaintBufferType::NewBuffer); slint::platform::set_platform(Box::new(Offscreen(window.clone()))) @@ -62,6 +63,12 @@ pub fn run( }); drag(&window, &spec); } + // Lay the window out once so the views report what they show, then let work they asked + // for (thumbnails) finish before the frame. + window.draw_if_needed(|renderer| { + renderer.render(&mut pixels, width as usize); + }); + settle(); window.request_redraw(); window.draw_if_needed(|renderer| { renderer.render(&mut pixels, width as usize); diff --git a/crates/tunal/src/settings.rs b/crates/tunal/src/settings.rs index cf6e75d..19b589e 100644 --- a/crates/tunal/src/settings.rs +++ b/crates/tunal/src/settings.rs @@ -7,7 +7,7 @@ use std::rc::{Rc, Weak}; use slint::{ComponentHandle, ModelRc, VecModel}; use crate::actions::{Action, Actions}; -use crate::config::{self, Clock, DateStyle, Group, Motion, Sort, View}; +use crate::config::{self, Clock, DateStyle, FrameUnit, Group, Motion, Sort, View}; use crate::folder::format; use crate::menus::{Context, SEPARATOR}; use crate::shell::Shell; @@ -71,6 +71,11 @@ impl SettingsUi { motion: cfg.motion as i32, date_style: cfg.date_style as i32, clock: cfg.clock as i32, + previews: cfg.previews, + preview_frame_unit: cfg.preview_frame_unit as i32, + preview_frame: cfg.preview_frame as i32, + preview_max_mib: cfg.preview_max_mib as i32, + preview_remote: cfg.preview_remote, } } @@ -104,6 +109,12 @@ impl SettingsUi { cfg.date_style = [DateStyle::Relative, DateStyle::Absolute][data.date_style.clamp(0, 1) as usize]; cfg.clock = [Clock::H12, Clock::H24][data.clock.clamp(0, 1) as usize]; + cfg.previews = data.previews; + cfg.preview_frame_unit = + [FrameUnit::Percent, FrameUnit::Seconds][data.preview_frame_unit.clamp(0, 1) as usize]; + cfg.preview_frame = data.preview_frame.clamp(0, 3600) as u32; + cfg.preview_max_mib = data.preview_max_mib.clamp(1, 4096) as u32; + cfg.preview_remote = data.preview_remote; // The window's own sidebar state is saved with the session, not by this dialog. if let Some(ui) = self.ui.upgrade() { cfg.show_sidebar = ui.get_show_sidebar(); @@ -112,6 +123,7 @@ impl SettingsUi { config::store("settings", &cfg); format::set_dates(cfg.date_style, cfg.clock); if let Some(shell) = self.shell.upgrade() { + shell.thumbs().configure(&cfg); for pane in shell.panes() { pane.model.apply_config(&cfg); pane.model.redraw_dates(); diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs index afc4e15..ac33e80 100644 --- a/crates/tunal/src/shell/mod.rs +++ b/crates/tunal/src/shell/mod.rs @@ -18,6 +18,7 @@ use crate::config::{self, Session, TabSession}; use crate::dnd::DragDrop; use crate::folder::format; use crate::settings::SettingsUi; +use crate::thumbs_bridge::Thumbs; use crate::{ Completion, Crumb, MainWindow, MenuEntry, MenuItem, PaneData, PlaceItem, SidebarSection, TabData, @@ -44,6 +45,7 @@ pub struct Shell { me: Weak, locations: Locations, blocking: bool, + thumbs: Rc, /// Tabs in opening order, as the tab model rows. tabs: RefCell>, current: Cell, @@ -77,6 +79,7 @@ impl Shell { me: me.clone(), locations, blocking, + thumbs: Rc::new(Thumbs::new(&config::load("settings"))), tabs: RefCell::new(Vec::new()), current: Cell::new(0), next_id: Cell::new(1), @@ -175,7 +178,13 @@ impl Shell { let Some(ui) = self.ui.upgrade() else { unreachable!("panes are made while the window lives"); }; - let pane = Pane::new(id, &ui, self.locations.clone(), self.blocking); + let pane = Pane::new( + id, + &ui, + self.locations.clone(), + self.thumbs.clone(), + self.blocking, + ); let me = self.me.clone(); pane.model.on_changed(move |_| { if let Some(shell) = me.upgrade() { @@ -322,6 +331,17 @@ impl Shell { tabs.get(self.current.get())?.panes.get(index).cloned() } + pub(crate) fn thumbs(&self) -> &Rc { + &self.thumbs + } + + /// Waits for the thumbnails of the rows in view (screenshots, which run no event loop). + pub fn settle_thumbs(&self) { + for pane in self.panes() { + pane.model.wait_thumbs(std::time::Duration::from_secs(20)); + } + } + /// Every pane of every tab. pub(crate) fn panes(&self) -> Vec> { let tabs = self.tabs.borrow(); @@ -777,6 +797,10 @@ impl Shell { on_pane!(on_filter_typed, |_s, p, text| p.model.type_filter(&text)); on_pane!(on_filter_edited, |_s, p, text| p.model.set_filter(&text)); on_pane!(on_toggle_hidden, |_s, p| p.model.toggle_hidden()); + on_pane!(on_toggle_previews, |_s, p| p.model.toggle_previews()); + on_pane!(on_viewport_changed, |_s, p, top, height, row, cell| { + p.model.set_viewport(top, height, row, cell) + }); on_pane!(on_row_clicked, |_s, p, row, ctrl, shift| { p.model.click(row.max(0) as usize, ctrl, shift) }); diff --git a/crates/tunal/src/shell/pane.rs b/crates/tunal/src/shell/pane.rs index 554a46a..1cbcc84 100644 --- a/crates/tunal/src/shell/pane.rs +++ b/crates/tunal/src/shell/pane.rs @@ -11,6 +11,7 @@ use tunal_core::{Locations, Uri}; use super::path; use crate::folder::{Deliver, FolderModel}; +use crate::thumbs_bridge::Thumbs; use crate::{MainWindow, MotionPrefs, PaneData, Travel}; thread_local! { @@ -28,7 +29,13 @@ pub struct Pane { } impl Pane { - pub fn new(id: u64, ui: &MainWindow, locations: Locations, blocking: bool) -> Rc { + pub fn new( + id: u64, + ui: &MainWindow, + locations: Locations, + thumbs: Rc, + blocking: bool, + ) -> Rc { let deliver: Deliver = Arc::new(move |msg| { let _ = slint::invoke_from_event_loop(move || { let model = MODELS.with(|m| m.borrow().get(&id).and_then(Weak::upgrade)); @@ -37,7 +44,7 @@ impl Pane { } }); }); - let model = FolderModel::new(locations, deliver); + let model = FolderModel::new(locations, deliver, thumbs); MODELS.with(|m| m.borrow_mut().insert(id, Rc::downgrade(&model))); let weak = ui.as_weak(); model.set_list_time(move || { diff --git a/crates/tunal/src/thumbs_bridge.rs b/crates/tunal/src/thumbs_bridge.rs new file mode 100644 index 0000000..c3d3234 --- /dev/null +++ b/crates/tunal/src/thumbs_bridge.rs @@ -0,0 +1,199 @@ +//! Thumbnails for the folder views: the `tunal-thumbs` worker pool configured from the +//! settings, PNG decoding off the UI thread, and the network-file-system check. + +use std::cell::{Cell, RefCell}; +use std::fs::File; +use std::io::BufReader; +use std::path::Path; + +use slint::{Rgba8Pixel, SharedPixelBuffer}; +use tunal_thumbs::{Config, Outcome, Priority, Request, ThumbSize, Thumbnailer, Ticket, VideoTime}; + +use crate::config::{self, FrameUnit}; + +/// The pool shared by every pane; it is rebuilt when a preview setting changes. +pub struct Thumbs { + pool: RefCell, + config: RefCell, + /// Bumped with each rebuild: panes drop what they were waiting for and ask again. + epoch: Cell, +} + +fn pool_config(cfg: &config::Settings) -> Config { + Config { + max_file_size: u64::from(cfg.preview_max_mib.max(1)) << 20, + allow_remote: cfg.preview_remote, + video_time: match cfg.preview_frame_unit { + FrameUnit::Percent => VideoTime::Percent(f64::from(cfg.preview_frame.min(99))), + FrameUnit::Seconds => VideoTime::Seconds(f64::from(cfg.preview_frame)), + }, + ..Config::default() + } +} + +impl Thumbs { + pub fn new(cfg: &config::Settings) -> Self { + let config = pool_config(cfg); + Self { + pool: RefCell::new(Thumbnailer::new(config.clone())), + config: RefCell::new(config), + epoch: Cell::new(0), + } + } + + /// Applies the preview settings; true when the pool had to be rebuilt (running jobs + /// finish, queued ones are dropped). + pub fn configure(&self, cfg: &config::Settings) -> bool { + let config = pool_config(cfg); + { + let old = self.config.borrow(); + if old.max_file_size == config.max_file_size + && old.allow_remote == config.allow_remote + && old.video_time == config.video_time + { + return false; + } + } + *self.pool.borrow_mut() = Thumbnailer::new(config.clone()); + *self.config.borrow_mut() = config; + self.epoch.set(self.epoch.get() + 1); + true + } + + pub fn epoch(&self) -> u64 { + self.epoch.get() + } + + /// Asks for a thumbnail; `done` runs on a worker thread with the decoded image, or `None` + /// when there is none (unsupported, too large, failed, cancelled). + pub fn request( + &self, + path: std::path::PathBuf, + size: ThumbSize, + remote: bool, + priority: Priority, + done: impl FnOnce(Option>) + Send + 'static, + ) -> Ticket { + self.pool.borrow().request(Request { + path, + size, + priority, + remote, + done: Box::new(move |outcome| { + done(match outcome { + Outcome::Ready(png) => decode(&png), + _ => None, + }) + }), + }) + } +} + +/// A cache PNG as pixels (other apps' thumbnails may be RGB or grey). +fn decode(path: &Path) -> Option> { + let mut decoder = png::Decoder::new(BufReader::new(File::open(path).ok()?)); + decoder.set_transformations(png::Transformations::normalize_to_color8()); + let mut reader = decoder.read_info().ok()?; + let mut data = vec![0; reader.output_buffer_size()?]; + let info = reader.next_frame(&mut data).ok()?; + let data = &data[..info.buffer_size()]; + let mut pixels = SharedPixelBuffer::::new(info.width, info.height); + let out = pixels.make_mut_slice(); + let count = out.len(); + match info.color_type { + png::ColorType::Rgba if data.len() >= count * 4 => { + for (dst, src) in out.iter_mut().zip(data.as_chunks::<4>().0) { + *dst = Rgba8Pixel::new(src[0], src[1], src[2], src[3]); + } + } + png::ColorType::Rgb if data.len() >= count * 3 => { + for (dst, src) in out.iter_mut().zip(data.as_chunks::<3>().0) { + *dst = Rgba8Pixel::new(src[0], src[1], src[2], 255); + } + } + png::ColorType::GrayscaleAlpha if data.len() >= count * 2 => { + for (dst, src) in out.iter_mut().zip(data.as_chunks::<2>().0) { + *dst = Rgba8Pixel::new(src[0], src[0], src[0], src[1]); + } + } + png::ColorType::Grayscale if data.len() >= count => { + for (dst, &g) in out.iter_mut().zip(data) { + *dst = Rgba8Pixel::new(g, g, g, 255); + } + } + _ => return None, + } + Some(pixels) +} + +/// True when `path` lies on a network or FUSE-remote file system (from `/proc/self/mountinfo`). +pub fn on_network_fs(path: &Path) -> bool { + let Ok(info) = std::fs::read_to_string("/proc/self/mountinfo") else { + return false; + }; + let mut best: Option<(usize, &str)> = None; + for line in info.lines() { + let Some((head, tail)) = line.split_once(" - ") else { + continue; + }; + let (Some(point), Some(fstype)) = (head.split(' ').nth(4), tail.split(' ').next()) else { + continue; + }; + let point = unescape(point); + if path.starts_with(&point) && best.is_none_or(|(len, _)| point.len() >= len) { + best = Some((point.len(), fstype)); + } + } + best.is_some_and(|(_, fstype)| { + fstype.starts_with("nfs") + || matches!( + fstype, + "cifs" + | "smb3" + | "smbfs" + | "9p" + | "afs" + | "ceph" + | "glusterfs" + | "lustre" + | "davfs" + ) + || fstype.strip_prefix("fuse.").is_some_and(|name| { + matches!( + name, + "sshfs" + | "rclone" + | "gvfsd-fuse" + | "curlftpfs" + | "s3fs" + | "davfs2" + | "mtpfs" + | "jmtpfs" + | "simple-mtpfs" + | "ifuse" + ) + }) + }) +} + +/// mountinfo writes space, tab, newline and backslash as `\040`-style octal escapes. +fn unescape(field: &str) -> String { + let mut out = Vec::with_capacity(field.len()); + let bytes = field.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'\\' + && i + 4 <= bytes.len() + && let Some(v) = std::str::from_utf8(&bytes[i + 1..i + 4]) + .ok() + .and_then(|d| u8::from_str_radix(d, 8).ok()) + { + out.push(v); + i += 4; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint index 3ea6156..027991b 100644 --- a/crates/tunal/ui/app.slint +++ b/crates/tunal/ui/app.slint @@ -67,6 +67,8 @@ export component MainWindow inherits Window { callback filter-typed(int, string); callback filter-edited(int, string); callback toggle-hidden(int); + callback toggle-previews(int); + callback viewport-changed(int, length, length, length, length); callback row-clicked(int, int, bool, bool); callback row-activated(int, int); callback select-all(int); @@ -408,6 +410,10 @@ export component MainWindow inherits Window { view-mode-selected(mode) => { root.view-mode-selected(root.active-pane, mode); } + previews: root.active-pane < root.panes.length ? root.panes[root.active-pane].folder.previews : false; + previews-toggled => { + root.toggle-previews(root.active-pane); + } back => { root.back(); } @@ -507,6 +513,9 @@ export component MainWindow inherits Window { motion-settled => { root.motion-settled(i); } + viewport-changed(top, height, row, cell) => { + root.viewport-changed(i, top, height, row, cell); + } row-renamed(row, text) => { root.row-renamed(i, row, text); } diff --git a/crates/tunal/ui/components/icon.slint b/crates/tunal/ui/components/icon.slint index 4cf01eb..565fcda 100644 --- a/crates/tunal/ui/components/icon.slint +++ b/crates/tunal/ui/components/icon.slint @@ -27,6 +27,7 @@ export global Icons { out property close: "\u{e5cd}"; out property cancel: "\u{e5c9}"; out property add: "\u{e145}"; + out property remove: "\u{e15b}"; out property search: "\u{e8b6}"; out property star: "\u{e838}"; out property grid-view: "\u{e9b0}"; diff --git a/crates/tunal/ui/components/list-row.slint b/crates/tunal/ui/components/list-row.slint index c5de600..f73be2d 100644 --- a/crates/tunal/ui/components/list-row.slint +++ b/crates/tunal/ui/components/list-row.slint @@ -4,6 +4,7 @@ import { Icon } from "icon.slint"; import { StateLayer } from "state-layer.slint"; import { RenameField } from "rename-field.slint"; import { Shape, ShapeKind } from "shape.slint"; +import { Preview } from "thumb.slint"; // One row of a list: leading icon, title, optional supporting line, and a trailing slot for // the row's children. Selection grows a tonal fill from the centre. @@ -20,6 +21,9 @@ export component ListRow inherits StateLayer { // An image drawn in the shaped container in place of the glyph. in property picture; in property has-picture; + // The file's thumbnail, which takes the shape's place once there. + in property thumb; + in property has-thumb; in property shape: ShapeKind.circle; in property active-shape: ShapeKind.cookie9; in property shape-size: 36px; @@ -73,24 +77,31 @@ export component ListRow inherits StateLayer { alignment: center; min-width: root.shape-size; - Shape { - size: root.shape-size; - shape: root.shape; - active-shape: root.active-shape; - active: root.selected; - glyph: root.icon; - picture: root.picture; - has-picture: root.has-picture; - fill: root.enabled ? root.shape-fill : Theme.on-surface.with-alpha(Theme.disabled-container); - active-fill: root.enabled ? Theme.primary : Theme.on-surface.with-alpha(Theme.disabled-container); - glyph-color: !root.enabled ? root.detail-color : root.selected ? Theme.on-primary : root.shape-ink; + Preview { + width: root.shape-size; + height: root.shape-size; + source: root.thumb; + shown: root.has-thumb; - if root.badge != "": Icon { - x: parent.width - self.width; - y: parent.height - self.height; - glyph: root.badge; - size: 14px; - color: Theme.primary; + Shape { + size: root.shape-size; + shape: root.shape; + active-shape: root.active-shape; + active: root.selected; + glyph: root.icon; + picture: root.picture; + has-picture: root.has-picture; + fill: root.enabled ? root.shape-fill : Theme.on-surface.with-alpha(Theme.disabled-container); + active-fill: root.enabled ? Theme.primary : Theme.on-surface.with-alpha(Theme.disabled-container); + glyph-color: !root.enabled ? root.detail-color : root.selected ? Theme.on-primary : root.shape-ink; + + if root.badge != "": Icon { + x: parent.width - self.width; + y: parent.height - self.height; + glyph: root.badge; + size: 14px; + color: Theme.primary; + } } } } diff --git a/crates/tunal/ui/components/thumb.slint b/crates/tunal/ui/components/thumb.slint new file mode 100644 index 0000000..8b09f56 --- /dev/null +++ b/crates/tunal/ui/components/thumb.slint @@ -0,0 +1,39 @@ +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; + +// A file's icon slot: its children (the shaped glyph) until a thumbnail arrives, which fades +// in as a rounded tile while the glyph fades out. An entry drawn with its thumbnail already +// there appears at once; only the arrival animates. +export component Preview { + in property source; + in property shown; + in property radius: Theme.corner-sm; + + Rectangle { + opacity: root.shown ? 0 : 1; + animate opacity { + duration: Motion.time(Motion.medium1); + easing: Motion.standard; + } + + @children + } + + Rectangle { + border-radius: root.radius; + clip: true; + background: Theme.surface-container-highest; + opacity: root.shown ? 1 : 0; + animate opacity { + duration: Motion.time(Motion.medium1); + easing: Motion.standard; + } + + Image { + width: 100%; + height: 100%; + source: root.source; + image-fit: cover; + } + } +} diff --git a/crates/tunal/ui/dialogs/settings.slint b/crates/tunal/ui/dialogs/settings.slint index 76d34e7..210f311 100644 --- a/crates/tunal/ui/dialogs/settings.slint +++ b/crates/tunal/ui/dialogs/settings.slint @@ -6,6 +6,7 @@ import { ListRow } from "../components/list-row.slint"; import { Switch } from "../components/switch.slint"; import { Chip } from "../components/chip.slint"; import { Icons } from "../components/icon.slint"; +import { IconButton } from "../components/icon-button.slint"; import { MenuEditor, EditRow } from "menu-editor.slint"; export { EditRow } @@ -25,6 +26,12 @@ export struct SettingsData { date-style: int, // 0 12-hour, 1 24-hour. clock: int, + previews: bool, + // 0 percent of the video's length, 1 seconds in. + preview-frame-unit: int, + preview-frame: int, + preview-max-mib: int, + preview-remote: bool, } // One choice out of a few, as a row of chips. @@ -87,6 +94,58 @@ component Setting inherits HorizontalLayout { } } +// A whole number with minus and plus buttons. +component Stepper inherits HorizontalLayout { + in property value; + in property lo; + in property hi; + in property step; + in property unit; + callback picked(int); + + spacing: Theme.space-2; + + VerticalLayout { + alignment: center; + IconButton { + icon: Icons.remove; + tonal: true; + size: 32px; + icon-size: 18px; + enabled: root.value > root.lo; + tooltip: "Less"; + clicked => { + root.picked(max(root.lo, root.value - root.step)); + } + } + } + + Text { + text: "\{root.value} \{root.unit}"; + width: 72px; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + horizontal-alignment: center; + vertical-alignment: center; + } + + VerticalLayout { + alignment: center; + IconButton { + icon: Icons.add; + tonal: true; + size: 32px; + icon-size: 18px; + enabled: root.value < root.hi; + tooltip: "More"; + clicked => { + root.picked(min(root.hi, root.value + root.step)); + } + } + } +} + // A choice with its name above the chips. component ChoiceSetting inherits VerticalLayout { in property title; @@ -286,19 +345,71 @@ export component SettingsDialog inherits Dialog { if root.page == 2: VerticalLayout { alignment: start; - Text { - text: "Previews"; - color: Theme.on-surface; - font-size: Theme.title-medium.size; - font-weight: Theme.title-medium.weight; + Setting { + title: "Show previews"; + hint: "Thumbnails of images, covers and videos. The toolbar button sets it per folder."; + Switch { + checked: root.data.previews; + changed checked => { + root.data.previews = self.checked; + root.changed(root.data); + } + } } - Text { - text: "Thumbnails and the preview panel will be set up here."; - color: Theme.on-surface-variant; - font-size: Theme.body-medium.size; - font-weight: Theme.body-medium.weight; - wrap: word-wrap; + ChoiceSetting { + title: "Video frame"; + names: ["Percent of the length", "Seconds in"]; + current: root.data.preview-frame-unit; + picked(i) => { + root.data.preview-frame-unit = i; + root.data.preview-frame = i == 0 ? min(root.data.preview-frame, 99) : root.data.preview-frame; + root.changed(root.data); + } + } + + Setting { + title: "Frame position"; + hint: "Applies to videos that have no thumbnail yet."; + Stepper { + value: root.data.preview-frame; + lo: 0; + hi: root.data.preview-frame-unit == 0 ? 99 : 3600; + step: root.data.preview-frame-unit == 0 ? 5 : 5; + unit: root.data.preview-frame-unit == 0 ? "%" : "s"; + picked(v) => { + root.data.preview-frame = v; + root.changed(root.data); + } + } + } + + Setting { + title: "Largest image"; + hint: "Images and SVG files above this size get no preview."; + Stepper { + value: root.data.preview-max-mib; + lo: 1; + hi: 1024; + step: 8; + unit: "MiB"; + picked(v) => { + root.data.preview-max-mib = v; + root.changed(root.data); + } + } + } + + Setting { + title: "Network drives"; + hint: "Previews on network and FUSE mounts. Off keeps them quick to open."; + Switch { + checked: root.data.preview-remote; + changed checked => { + root.data.preview-remote = self.checked; + root.changed(root.data); + } + } } } diff --git a/crates/tunal/ui/shell/pane.slint b/crates/tunal/ui/shell/pane.slint index bb3ce19..5f4070c 100644 --- a/crates/tunal/ui/shell/pane.slint +++ b/crates/tunal/ui/shell/pane.slint @@ -44,6 +44,7 @@ export component Pane inherits Rectangle { callback row-renamed(int, string); callback rename-cancelled(); callback context-menu(int, length, length); + callback viewport-changed(length, length, length, length); // The view keeps the focus away from a name being edited. public function focus-view() { @@ -123,6 +124,9 @@ export component Pane inherits Rectangle { motion-settled => { root.motion-settled(); } + viewport-changed(top, height, row, cell) => { + root.viewport-changed(top, height, row, cell); + } row-renamed(row, text) => { root.row-renamed(row, text); } diff --git a/crates/tunal/ui/shell/toolbar.slint b/crates/tunal/ui/shell/toolbar.slint index 7db442d..4e5fda4 100644 --- a/crates/tunal/ui/shell/toolbar.slint +++ b/crates/tunal/ui/shell/toolbar.slint @@ -17,6 +17,7 @@ export component Toolbar inherits Rectangle { in property path; in property <[Completion]> completions; in property view-mode; + in property previews; in-out property highlight <=> crumb.highlight; out property editing: crumb.editing; // Where the completion list goes, in window coordinates. @@ -29,6 +30,7 @@ export component Toolbar inherits Rectangle { callback up(); callback toggle-split(); callback view-mode-selected(ViewMode); + callback previews-toggled(); callback toggle-sidebar(); callback go(int); callback path-edited(string); @@ -140,6 +142,24 @@ export component Toolbar inherits Rectangle { } } + VerticalLayout { + alignment: center; + IconButton { + // `checked` is flipped by the click: follow `previews` again after it. + property state: root.previews; + icon: Icons.image; + toggle: true; + checked: self.state; + changed state => { + self.checked = self.state; + } + tooltip: "Previews"; + clicked => { + root.previews-toggled(); + } + } + } + VerticalLayout { alignment: center; IconButton { diff --git a/crates/tunal/ui/views/details-view.slint b/crates/tunal/ui/views/details-view.slint index b1fa363..b162dd4 100644 --- a/crates/tunal/ui/views/details-view.slint +++ b/crates/tunal/ui/views/details-view.slint @@ -28,6 +28,9 @@ export struct DetailRow { // The folder's own image icon, drawn in place of the glyph. picture: image, has-picture: bool, + // The file's thumbnail, once it arrived. + thumb: image, + has-thumb: bool, badge: string, size: string, kind: string, @@ -66,6 +69,8 @@ export struct FolderState { items: int, hidden: int, mode: ViewMode, + // Thumbnails instead of plain glyphs in this folder. + previews: bool, // Bumped when a list change starts that rows animate (see DetailRow). motion: int, travel: Travel, @@ -399,6 +404,8 @@ export component DetailsView inherits Rectangle { callback rename-cancelled(); // A right click on a row (-1 for none) at window coordinates. callback context-menu(int, length, length); + // What is in view (top, height) and the row and cell heights, for the previews. + callback viewport-changed(length, length, length, length); // This pane's index in the tab, for drag and drop. in property pane; @@ -431,6 +438,21 @@ export component DetailsView inherits Rectangle { } } + property scrolled: -list.content-y; + property shown-height: list.visible-height; + function report() { + root.viewport-changed(root.scrolled, root.shown-height, Columns.row-height, 0px); + } + changed scrolled => { + root.report(); + } + changed shown-height => { + root.report(); + } + init => { + root.report(); + } + background: Theme.surface; forward-focus: keys; @@ -617,6 +639,8 @@ export component DetailsView inherits Rectangle { shape-size: 32px; picture: row.picture; has-picture: row.has-picture; + thumb: row.thumb; + has-thumb: row.has-thumb; shape: FileShapes.shape(row.shape-glyph); active-shape: FileShapes.active-shape(row.shape-glyph); shape-fill: FileShapes.fill(row.shape-glyph); diff --git a/crates/tunal/ui/views/grid-view.slint b/crates/tunal/ui/views/grid-view.slint index 8916b28..80c6de1 100644 --- a/crates/tunal/ui/views/grid-view.slint +++ b/crates/tunal/ui/views/grid-view.slint @@ -4,6 +4,7 @@ import { Motion } from "../motion.slint"; import { Icon, Icons } from "../components/icon.slint"; import { ForceState, StateLayer } from "../components/state-layer.slint"; import { Shape, FileShapes } from "../components/shape.slint"; +import { Preview } from "../components/thumb.slint"; import { RenameField } from "../components/rename-field.slint"; import { IconButton } from "../components/icon-button.slint"; import { @@ -27,6 +28,9 @@ global Grid { out property min-cell-width: 112px; out property cell-height: 116px; out property icon-size: 56px; + // With previews the picture slot grows to hold the thumbnail tile, and the cell with it. + out property preview-size: 80px; + out property preview-cell-height: cell-height + preview-size - icon-size; // Gap around each cell's shape, inside its slot. out property gap: Theme.space-1; } @@ -37,6 +41,8 @@ component GridCell inherits StateLayer { in property entry; in property cursor-ring; in property edit-select; + // The picture slot: `Grid.icon-size`, or `Grid.preview-size` with previews. + in property slot: Grid.icon-size; callback renamed(text: string); callback rename-cancelled(); @@ -77,25 +83,35 @@ component GridCell inherits StateLayer { HorizontalLayout { alignment: center; - Shape { - size: Grid.icon-size; - shape: FileShapes.shape(root.entry.shape-glyph); - active-shape: FileShapes.active-shape(root.entry.shape-glyph); - active: root.entry.selected; - fill: FileShapes.fill(root.entry.shape-glyph); - active-fill: Theme.primary; - glyph: root.entry.glyph; - picture: root.entry.picture; - has-picture: root.entry.has-picture; - glyph-color: root.entry.selected ? Theme.on-primary : FileShapes.ink(root.entry.shape-glyph); - glyph-ratio: 0.5; + Preview { + width: root.slot; + height: root.slot; + source: root.entry.thumb; + shown: root.entry.has-thumb; + radius: Theme.corner-md; - if root.entry.badge != "": Icon { - x: parent.width - self.width; - y: parent.height - self.height; - glyph: root.entry.badge; - size: 18px; - color: Theme.primary; + Shape { + x: (parent.width - self.width) / 2; + y: (parent.height - self.height) / 2; + size: Grid.icon-size; + shape: FileShapes.shape(root.entry.shape-glyph); + active-shape: FileShapes.active-shape(root.entry.shape-glyph); + active: root.entry.selected; + fill: FileShapes.fill(root.entry.shape-glyph); + active-fill: Theme.primary; + glyph: root.entry.glyph; + picture: root.entry.picture; + has-picture: root.entry.has-picture; + glyph-color: root.entry.selected ? Theme.on-primary : FileShapes.ink(root.entry.shape-glyph); + glyph-ratio: 0.5; + + if root.entry.badge != "": Icon { + x: parent.width - self.width; + y: parent.height - self.height; + glyph: root.entry.badge; + size: 18px; + color: Theme.primary; + } } } } @@ -157,14 +173,17 @@ export component GridView inherits Rectangle { callback row-renamed(int, string); callback rename-cancelled(); callback context-menu(int, length, length); + // What is in view (top, height) and the row and cell heights, for the previews. + callback viewport-changed(length, length, length, length); out property columns: max(1, floor((list.visible-width - 2 * Columns.inset) / Grid.min-cell-width)); property cell-width: (list.visible-width - 2 * Columns.inset) / root.columns; property settle: Motion.settle(root.motion); + property cell-height: root.state.previews ? Grid.preview-cell-height : Grid.cell-height; // Vertical offset of a moving row from its slot (see DetailRow). function shift-y(row: DetailRow) -> length { - Grid.cell-height * (row.to-y + (row.from-y - row.to-y) * (1 - root.settle)) + root.cell-height * (row.to-y + (row.from-y - row.to-y) * (1 - root.settle)) + Columns.row-height * (row.to-h + (row.from-h - row.to-h) * (1 - root.settle)) } @@ -172,6 +191,24 @@ export component GridView inherits Rectangle { root.columns-changed(root.columns); } + property scrolled: -list.content-y; + property shown-height: list.visible-height; + function report() { + root.viewport-changed(root.scrolled, root.shown-height, Columns.row-height, root.cell-height); + } + changed scrolled => { + root.report(); + } + changed shown-height => { + root.report(); + } + changed cell-height => { + root.report(); + } + init => { + root.report(); + } + public function focus-view() { keys.focus(); } @@ -182,8 +219,8 @@ export component GridView inherits Rectangle { return; } let headers = root.lines[line].headers-before; - let top = headers * Columns.row-height + (line - headers) * Grid.cell-height; - let height = root.lines[line].header ? Columns.row-height : Grid.cell-height; + let top = headers * Columns.row-height + (line - headers) * root.cell-height; + let height = root.lines[line].header ? Columns.row-height : root.cell-height; if top < -list.content-y { list.content-y = -top; } else if top + height > -list.content-y + list.visible-height { @@ -206,7 +243,7 @@ export component GridView inherits Rectangle { state: root.state; horizontal: true; move(key, shift) => { - root.reveal(root.navigate(key, shift, max(1, floor(list.visible-height / Grid.cell-height)))); + root.reveal(root.navigate(key, shift, max(1, floor(list.visible-height / root.cell-height)))); } filter-typed(text) => { root.filter-typed(text); @@ -307,7 +344,7 @@ export component GridView inherits Rectangle { visible: root.lines.length > 0; for line in root.lines: Rectangle { - height: line.header ? Columns.row-height : Grid.cell-height; + height: line.header ? Columns.row-height : root.cell-height; if line.header: Text { property entry: root.rows[line.start]; @@ -336,7 +373,7 @@ export component GridView inherits Rectangle { * (c + self.entry.to-x + (self.entry.from-x - self.entry.to-x) * (1 - root.settle)); y: root.shift-y(self.entry); width: root.cell-width; - height: Grid.cell-height; + height: root.cell-height; opacity: self.size; transform-scale: Motion.enter-scale + (1 - Motion.enter-scale) * self.size; @@ -361,7 +398,8 @@ export component GridView inherits Rectangle { drag-image: Dnd.image(root.pane, cell.index, tile.pressed, Theme.secondary-container, Theme.on-secondary-container, Theme.primary, Theme.on-primary); tile := GridCell { - entry: cell.entry; + entry: cell.entry; + slot: root.state.previews ? Grid.preview-size : Grid.icon-size; cursor-ring: cell.entry.cursor && keys.has-focus; edit-select: root.state.edit-select; opacity: cell.entry.dimmed ? Theme.disabled-content : 1; diff --git a/crates/tunal/ui/views/view-switch.slint b/crates/tunal/ui/views/view-switch.slint index 0f4e882..905826d 100644 --- a/crates/tunal/ui/views/view-switch.slint +++ b/crates/tunal/ui/views/view-switch.slint @@ -110,6 +110,8 @@ export component FolderView inherits Rectangle { callback context-menu(int, length, length); // The list change of `state.motion` has ended: leaving rows can go. callback motion-settled(); + // What the visible view shows: top, height, row and cell heights (for the previews). + callback viewport-changed(length, length, length, length); property grid: root.state.mode == ViewMode.grid; @@ -198,6 +200,9 @@ export component FolderView inherits Rectangle { context-menu(row, x, y) => { root.context-menu(row, x, y); } + viewport-changed(top, height, row, cell) => { + root.viewport-changed(top, height, row, cell); + } } grid := GridView { @@ -251,6 +256,9 @@ export component FolderView inherits Rectangle { context-menu(row, x, y) => { root.context-menu(row, x, y); } + viewport-changed(top, height, row, cell) => { + root.viewport-changed(top, height, row, cell); + } columns-changed(n) => { root.columns-changed(n); } diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 85645eb..4347e3b 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -178,6 +178,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: no pkexec/polkit run (D-009, S036); "Retry as administrator" not clicked in a live window; `.directory` save not yet wired to `write_file` (S015's files; API sent to S015); `Bridge::elevation` has `allow(dead_code)` until then. - Later: remove that allow once S015 calls it; elevated trash goes to root's trash (left as is: Elevation passes trash through the helper → Unsupported). +## S018 — Thumbnails in the views +- Done: `thumbs_bridge.rs` (`Thumbs`: shared `tunal-thumbs` pool built from settings, rebuilt when max size / video frame / remote change; PNG decode off the UI thread; `on_network_fs` from mountinfo). `FolderModel` owns `folder/previews.rs` (LRU of 200 `slint::Image`, requests in flight, files without a thumbnail). Views report `viewport-changed(top, height, row, cell)` (init, scroll, resize, cell size); the model asks for rows in view (Normal priority) + a few beyond (Low), cancels the rest; details use 128 px, grid 256 px. `DetailRow.thumb/has-thumb`; `Preview` (components/thumb.slint) fades glyph out and a rounded tile in on arrival (cached ones appear at once). Grid cells grow to a 80 px slot with previews. Toolbar toggle (per pane, per folder via `.directory` `previews`), default `previews` in `settings.toml`; Settings → Previews page: on/off, video frame (percent/seconds + stepper), largest image (MiB), network drives. +- Verified: build; clippy -D warnings on `tunal`/`tunal-thumbs` (`--no-deps`; only S026's `places.rs` expectation and `tunal-devices` lint fail); fmt; literal grep empty; screenshots (reduced motion) of image/SVG/MP3 cover/MP4/plain mp3/broken png folder in details + grid, light + dark, previews off (settings.toml), Settings Previews page. +- Not done: arrival fade, scroll cancel and live toggle not watched (single frames); a link badge hides while a thumbnail shows; video frame change doesn't redo existing thumbnails; plain `workspace` clippy red until S026 fixes `tunal-devices`. Screenshots now draw once, run `Shell::settle_thumbs`, then draw again. +- Later: preview panel; thumbnails for PDFs; remote locations (SFTP/devices) need a read path in the pool. + ## Later - (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034. -