S018: thumbnails in the folder views, previews toggle and settings

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-18 20:48:34 -06:00
commit eba5db311b
26 changed files with 1033 additions and 76 deletions

1
Cargo.lock generated
View file

@ -5547,6 +5547,7 @@ dependencies = [
"tunal-dirmeta",
"tunal-elevate",
"tunal-theme",
"tunal-thumbs",
"zbus",
]

View file

@ -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.

View file

@ -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

View file

@ -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

View file

@ -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,
}
}
}

View file

@ -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<u8>, Look)>),
/// Thumbnails arrived (the pane's inbox holds them).
Thumbs,
}
pub enum Change {

View file

@ -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<Vec<u8>>,
/// An entry still to appear (created or renamed): selected, and edited if asked, once shown.
pending: Option<Pending>,
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<Thumbs>,
/// Called after every change the window must reflect (state, menu).
changed: RefCell<Listener>,
/// 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<Self> {
pub fn new(locations: Locations, deliver: Deliver, thumbs: Rc<Thumbs>) -> Rc<Self> {
let cfg = config::load::<config::Settings>("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<u8>, 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<MenuItem> {
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<DetailRow> {
let mut data = match s.rows.get(row)? {
@ -1462,8 +1655,15 @@ fn row_data(s: &State, row: usize) -> Option<DetailRow> {
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()

View file

@ -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<u8>,
pub size: ThumbSize,
pub pixels: Option<SharedPixelBuffer<Rgba8Pixel>>,
}
pub struct Previews {
shown: HashMap<Vec<u8>, Shown>,
order: VecDeque<Vec<u8>>,
waiting: HashMap<Vec<u8>, Waiting>,
/// Files without a thumbnail (unsupported, too large, failed): not asked for again.
none: HashSet<Vec<u8>>,
next_id: u64,
pub inbox: Arc<Mutex<Vec<Arrival>>>,
pub viewport: Viewport,
/// The folder is on a network file system (looked up once per folder).
pub remote: Option<bool>,
/// 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<Image> {
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<u8>, 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<Vec<u8>> {
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)
}
}

View file

@ -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) {

View file

@ -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 {

View file

@ -33,6 +33,7 @@ pub struct Options {
pub fn run<C: Themed>(
options: Options,
new: impl FnOnce() -> Result<C, PlatformError>,
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<C: Themed>(
});
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);

View file

@ -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();

View file

@ -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<Shell>,
locations: Locations,
blocking: bool,
thumbs: Rc<Thumbs>,
/// Tabs in opening order, as the tab model rows.
tabs: RefCell<Vec<Tab>>,
current: Cell<usize>,
@ -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<Thumbs> {
&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<Rc<Pane>> {
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)
});

View file

@ -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<Self> {
pub fn new(
id: u64,
ui: &MainWindow,
locations: Locations,
thumbs: Rc<Thumbs>,
blocking: bool,
) -> Rc<Self> {
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 || {

View file

@ -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<Thumbnailer>,
config: RefCell<Config>,
/// Bumped with each rebuild: panes drop what they were waiting for and ask again.
epoch: Cell<u64>,
}
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<SharedPixelBuffer<Rgba8Pixel>>) + 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<SharedPixelBuffer<Rgba8Pixel>> {
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::<Rgba8Pixel>::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()
}

View file

@ -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);
}

View file

@ -27,6 +27,7 @@ export global Icons {
out property <string> close: "\u{e5cd}";
out property <string> cancel: "\u{e5c9}";
out property <string> add: "\u{e145}";
out property <string> remove: "\u{e15b}";
out property <string> search: "\u{e8b6}";
out property <string> star: "\u{e838}";
out property <string> grid-view: "\u{e9b0}";

View file

@ -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 <image> picture;
in property <bool> has-picture;
// The file's thumbnail, which takes the shape's place once there.
in property <image> thumb;
in property <bool> has-thumb;
in property <ShapeKind> shape: ShapeKind.circle;
in property <ShapeKind> active-shape: ShapeKind.cookie9;
in property <length> 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;
}
}
}
}

View file

@ -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 <image> source;
in property <bool> shown;
in property <length> 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;
}
}
}

View file

@ -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 <int> value;
in property <int> lo;
in property <int> hi;
in property <int> step;
in property <string> 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 <string> 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);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show more