Tunal/crates/tunal/src/folder/mod.rs
2026-11-25 23:02:37 -06:00

2015 lines
69 KiB
Rust

//! The folder model behind the details and grid views: entries from the location layer
//! (loaded and watched off the UI thread), sorted, grouped and filtered into rows, plus the
//! selection, the grid's lines and the list motion of each change.
pub mod appearance;
pub mod format;
pub mod item;
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::file_icons;
use crate::icons::{self, Category};
use crate::thumbs_bridge::{self, Thumbs};
use crate::{
DetailRow, FolderState, FolderStatus, GridRow, Grouping, MenuEntry, MenuItem, NavKey,
SortColumn, Travel, ViewMode,
};
pub use item::Item;
pub use load::Deliver;
use load::{Change, Msg};
use motion::{Anim, Clock, Key, Old};
use previews::{Arrival, Previews, Viewport};
pub use sort::{GroupBy, Order, SortKey};
/// Icon size of the grid, smallest first; `FolderState.zoom` is its index.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Zoom {
Small,
#[default]
Medium,
Large,
ExtraLarge,
}
impl Zoom {
pub const ALL: [Zoom; 4] = [Self::Small, Self::Medium, Self::Large, Self::ExtraLarge];
/// `by` sizes larger (negative: smaller), stopping at either end.
pub fn step(self, by: i32) -> Self {
let i = (self as i32 + by).clamp(0, Self::ALL.len() as i32 - 1);
Self::ALL[i as usize]
}
/// The word a folder's `.directory` keeps (`IconSize`).
fn word(self) -> &'static str {
match self {
Self::Small => "small",
Self::Medium => "medium",
Self::Large => "large",
Self::ExtraLarge => "extra-large",
}
}
fn from_word(word: &str) -> Option<Self> {
Self::ALL.into_iter().find(|z| z.word() == word)
}
}
/// A pane's view settings. Sort, grouping and hidden files carry over between folders; view
/// mode and icon size go back to the defaults in a folder that keeps none of its own.
#[derive(Clone, Debug)]
pub struct Settings {
pub key: SortKey,
pub descending: bool,
pub folders_first: bool,
pub group: GroupBy,
pub show_hidden: bool,
/// Thumbnails, the icon theme's file icons and folders' own icons in place of plain glyphs.
pub previews: bool,
pub filter: String,
/// Details or grid.
pub mode: ViewMode,
/// Icon size of the grid.
pub zoom: Zoom,
}
impl Settings {
/// A new pane's settings: the defaults chosen in the settings dialog.
pub fn from_config(cfg: &config::Settings) -> Self {
let (mode, zoom) = default_view(cfg);
Self {
key: match cfg.sort {
config::Sort::Name => SortKey::Name,
config::Sort::Size => SortKey::Size,
config::Sort::Type => SortKey::Type,
config::Sort::Modified => SortKey::Modified,
},
descending: cfg.sort_descending,
folders_first: cfg.folders_first,
group: match cfg.group {
config::Group::None => GroupBy::None,
config::Group::Type => GroupBy::Type,
config::Group::Modified => GroupBy::Modified,
config::Group::Size => GroupBy::Size,
},
show_hidden: cfg.show_hidden,
previews: cfg.previews,
filter: String::new(),
mode,
zoom,
}
}
pub fn order(&self) -> Order {
Order {
key: self.key,
descending: self.descending,
folders_first: self.folders_first,
}
}
}
/// The view mode and icon size of a folder that keeps none of its own.
fn default_view(cfg: &config::Settings) -> (ViewMode, Zoom) {
// `TUNAL_VIEW=grid` starts in the grid view (screenshots).
if std::env::var("TUNAL_VIEW").as_deref() == Ok("grid") {
return (ViewMode::Grid, Zoom::Medium);
}
match cfg.view {
config::View::Details => (ViewMode::Details, Zoom::Medium),
config::View::Grid => (ViewMode::Grid, Zoom::Medium),
config::View::Large => (ViewMode::Grid, Zoom::Large),
}
}
#[derive(Clone)]
enum Row {
Header(&'static str),
Item(usize),
/// A removed row kept while it collapses out (list motion).
Leaving(Key, Box<DetailRow>),
}
enum Status {
Idle,
Loading,
Ready,
Failed(String),
}
struct State {
dir: Option<Uri>,
generation: u64,
status: Status,
items: Vec<Item>,
/// Raw name → index into `items`.
by_name: HashMap<Vec<u8>, usize>,
rows: Vec<Row>,
/// Raw name → row, for the rows shown.
row_of: HashMap<Vec<u8>, usize>,
settings: Settings,
/// The pane's settings before the folder's own view settings were applied.
inherited: Option<Settings>,
/// The folder keeps its view settings in its `.directory`: changes are written back.
remembered: bool,
playlists: Vec<Playlist>,
/// The playlist `SortKey::Playlist` refers to, kept across lookups.
playlist_path: Option<std::path::PathBuf>,
selected: HashSet<Vec<u8>>,
cursor: Option<Vec<u8>>,
anchor: Option<Vec<u8>>,
/// The selection a selection box started from.
band_base: HashSet<Vec<u8>>,
watches: Vec<Watch>,
/// List motion of the rows, parallel to `rows` (empty when still), and its clock.
anim: Vec<Anim>,
clock: Option<Clock>,
/// Bumped per list change the view animates (`FolderState.motion`).
epoch: i32,
/// Grid columns the view last reported.
columns: usize,
travel: Travel,
travel_epoch: i32,
/// Items on the clipboard to be moved, drawn dimmed.
cut: HashSet<Uri>,
/// The entry whose name is being edited in its row.
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,
/// The default view mode and icon size: what a folder without its own shows.
default_view: (ViewMode, Zoom),
}
struct Pending {
name: Vec<u8>,
edit: bool,
}
type Listener = Box<dyn Fn(&FolderModel)>;
/// A Slint `Model` of `DetailRow`s. Rows are formatted when the view asks for them, so a
/// 10 000-entry folder costs one sort, not 10 000 row structs.
pub struct FolderModel {
state: RefCell<State>,
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.
list_time: RefCell<Box<dyn Fn() -> Duration>>,
}
impl FolderModel {
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,
generation: 0,
status: Status::Idle,
items: Vec::new(),
by_name: HashMap::new(),
rows: Vec::new(),
row_of: HashMap::new(),
settings: Settings::from_config(&cfg),
inherited: None,
remembered: false,
playlists: Vec::new(),
playlist_path: None,
selected: HashSet::new(),
band_base: HashSet::new(),
cursor: None,
anchor: None,
watches: Vec::new(),
anim: Vec::new(),
clock: None,
epoch: 0,
columns: 1,
travel: Travel::None,
travel_epoch: 0,
cut: HashSet::new(),
edit: None,
pending: None,
previews: Previews::default(),
cfg_previews: cfg.previews,
default_view: default_view(&cfg),
}),
notify: ModelNotify::default(),
locations,
deliver,
thumbs,
changed: RefCell::new(Box::new(|_| {})),
list_time: RefCell::new(Box::new(|| Duration::ZERO)),
})
}
/// Shows `dir`: listing and watching run on a worker thread.
pub fn open(&self, dir: Uri) {
self.open_travel(dir, Travel::None);
}
/// Shows `dir`, its content sliding in from the side `travel` points to (into a folder
/// and forward from the right, up and back from the left).
pub fn open_travel(&self, dir: Uri, travel: Travel) {
let generation = self.reset_to(dir.clone());
{
let mut s = self.state.borrow_mut();
if travel != Travel::None {
s.travel = travel;
s.travel_epoch += 1;
}
}
let locations = self.locations.clone();
let deliver = self.deliver.clone();
std::thread::spawn(move || {
let send = |msg| deliver(msg);
load::load(&locations, &dir, generation, &send, Some(deliver.clone()));
});
self.emit();
}
/// Shows `dir`, listing it on this thread and without watching (screenshots).
pub fn open_blocking(&self, dir: Uri) {
let generation = self.reset_to(dir.clone());
let messages = RefCell::new(Vec::new());
load::load(
&self.locations,
&dir,
generation,
&|msg| messages.borrow_mut().push(msg),
None,
);
for msg in messages.into_inner() {
self.apply(msg);
}
self.emit();
}
/// Starts a new generation for `dir`: messages for the previous folder are dropped.
/// Sort, grouping and hidden files carry over; filter, playlist and selection don't, and
/// view mode and icon size go back to the defaults until the folder's own arrive.
fn reset_to(&self, dir: Uri) -> u64 {
let mut s = self.state.borrow_mut();
s.generation += 1;
s.dir = Some(dir);
s.status = Status::Loading;
s.items.clear();
s.by_name.clear();
s.playlists.clear();
s.watches.clear();
s.selected.clear();
s.cursor = None;
s.anchor = None;
s.edit = None;
s.pending = None;
s.previews.clear();
if let Some(base) = s.inherited.take() {
s.settings = base;
}
s.remembered = false;
(s.settings.mode, s.settings.zoom) = s.default_view;
s.settings.filter.clear();
s.playlist_path = None;
if let SortKey::Playlist(_) = s.settings.key {
s.settings.key = SortKey::Name;
}
rebuild(&mut s);
drop(s);
self.notify.reset();
self.state.borrow().generation
}
/// Applies a worker message (on the UI thread).
pub fn apply(&self, msg: Msg) {
let mut s = self.state.borrow_mut();
let current = s.generation;
// Watch events and playlist re-sorts animate; listing chunks don't.
let old = match &msg {
Msg::Changed(g, _) | Msg::Playlists(g, _) if *g == current => self.snapshot(&s),
_ => None,
};
match msg {
Msg::Chunk(g, entries) if g == current => {
for entry in entries {
upsert(&mut s, entry);
}
}
Msg::Done(g, result) if g == current => match result {
Ok(()) => s.status = Status::Ready,
Err(e) => {
s.status = Status::Failed(error_text(&e));
s.items.clear();
s.by_name.clear();
}
},
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;
let mut new_dirs = Vec::new();
let mut unnamed = Vec::new();
for change in changes {
match change {
Change::Upsert(entry) => {
let same = s.by_name.get(&entry.name).map(|&i| &s.items[i].entry);
if same != Some(&entry) {
if same.is_none() && entry.kind.is_dir() {
new_dirs.push(entry.name.clone());
}
if file_icons::needs_content(&entry) {
unnamed.push(entry.name.clone());
}
upsert(&mut s, entry);
changed = true;
}
}
Change::Removed(name) => changed |= remove(&mut s, &name),
}
}
if !changed {
return;
}
// A track or playlist appearing or leaving can change which playlists place
// entries here (outside the music folder the lookup returns at once).
self.refresh_playlists(&s);
self.refresh_looks(&s, new_dirs, unnamed);
}
Msg::PlaylistsChanged(g) if g == current => self.refresh_playlists(&s),
Msg::View(g, view) if g == current => apply_view(&mut s, &view),
Msg::Looks(g, looks) if g == current => {
for (name, look) in looks {
if let Some(&i) = s.by_name.get(&name) {
s.items[i].set_look(Some(look));
}
}
}
Msg::Icons(g, icons) if g == current => {
for (name, icon) in icons {
if let Some(&i) = s.by_name.get(&name) {
s.items[i].icon = Some(icon);
}
}
}
Msg::Playlists(g, found) if g == current => {
s.playlists = found;
if let Some(path) = s.playlist_path.clone() {
match s.playlists.iter().position(|p| p.path == path) {
Some(i) => s.settings.key = SortKey::Playlist(i),
None => {
s.playlist_path = None;
s.settings.key = SortKey::Name;
}
}
}
}
_ => return,
}
rebuild(&mut s);
self.animate(&mut s, old);
drop(s);
self.notify.reset();
self.emit();
self.pump();
}
/// The pane's settings as a folder would keep them in its `.directory`.
pub fn view_snapshot(&self) -> tunal_dirmeta::View {
view_of(&self.state.borrow())
}
/// True when the folder shown keeps its view settings in its `.directory`.
pub fn remembers_view(&self) -> bool {
self.state.borrow().remembered
}
/// The folder shown now remembers (or forgets) its view: from here on changes are written
/// back to its `.directory`.
pub fn set_remembers_view(&self, on: bool) {
let mut s = self.state.borrow_mut();
if s.remembered == on {
return;
}
s.remembered = on;
if on && s.inherited.is_none() {
s.inherited = Some(s.settings.clone());
}
}
/// Reads the icons and names of the child folders again (their `.directory` changed).
pub fn reload_looks(&self) {
let s = self.state.borrow();
let names = s
.items
.iter()
.filter(|i| i.is_dir)
.map(|i| i.entry.name.clone())
.collect();
self.refresh_looks(&s, names, Vec::new());
}
/// A folder that remembers its view keeps it current in its `.directory` (off-thread; a
/// failure only shows in the appearance dialog, which asks for elevation).
fn write_view(&self, s: &State) {
let Some(dir) = s
.dir
.as_ref()
.and_then(Uri::to_path)
.filter(|_| s.remembered)
else {
return;
};
let view = view_of(s);
std::thread::spawn(move || {
if let Err(e) = look::write_meta(&dir, |m| m.set_view(&view)) {
eprintln!("tunal: couldn't save {}: {e}", dir.display());
}
});
}
/// Reads the `.directory` of the new folders `names`, and what is in the changed files
/// `files` whose name doesn't tell their icon, off the UI thread.
fn refresh_looks(&self, s: &State, names: Vec<Vec<u8>>, files: Vec<Vec<u8>>) {
let Some(path) = s
.dir
.as_ref()
.and_then(Uri::to_path)
.filter(|_| !names.is_empty() || !files.is_empty())
else {
return;
};
let generation = s.generation;
let deliver = self.deliver.clone();
std::thread::spawn(move || {
let looks = load::looks(&path, &names);
if !looks.is_empty() {
deliver(Msg::Looks(generation, looks));
}
if !files.is_empty() && !thumbs_bridge::on_network_fs(&path) {
deliver(Msg::Icons(generation, load::icons(&path, &files)));
}
});
}
fn refresh_playlists(&self, s: &State) {
let Some(path) = s.dir.as_ref().and_then(Uri::to_path) else {
return;
};
let names: Vec<(Vec<u8>, bool)> = s
.items
.iter()
.map(|i| (i.entry.name.clone(), i.is_dir))
.collect();
let generation = s.generation;
let deliver = self.deliver.clone();
std::thread::spawn(move || {
deliver(Msg::Playlists(generation, load::playlists(&path, &names)));
});
}
/// Where list changes read their length (`MotionPrefs.list-change`); until set, or while
/// it returns zero (reduced motion), changes are instant.
pub fn set_list_time(&self, f: impl Fn() -> Duration + 'static) {
*self.list_time.borrow_mut() = Box::new(f);
}
/// Runs `f` after every change of state the window shows.
pub fn on_changed(&self, f: impl Fn(&FolderModel) + 'static) {
*self.changed.borrow_mut() = Box::new(f);
}
fn emit(&self) {
(self.changed.borrow())(self);
}
/// The folder shown (or loading), `None` before the first `open`.
pub fn dir(&self) -> Option<Uri> {
self.state.borrow().dir.clone()
}
/// Selected entries and their total size (folders count as empty).
pub fn selection(&self) -> (usize, u64) {
let s = self.state.borrow();
let items = s.selected.iter().filter_map(|n| s.by_name.get(n));
items.fold((0, 0), |(n, bytes), &i| (n + 1, bytes + s.items[i].size()))
}
pub fn state(&self) -> FolderState {
let s = self.state.borrow();
let (status, error) = match &s.status {
Status::Idle | Status::Ready => (FolderStatus::Ready, String::new()),
Status::Loading => (FolderStatus::Loading, String::new()),
Status::Failed(e) => (FolderStatus::Error, e.clone()),
};
let shown = s.rows.iter().filter(|r| matches!(r, Row::Item(_))).count();
let hidden = if s.settings.show_hidden {
0
} else {
s.items.iter().filter(|i| i.entry.hidden).count()
};
let (column, playlist) = match s.settings.key {
SortKey::Name => (SortColumn::Name, -1),
SortKey::Size => (SortColumn::Size, -1),
SortKey::Type => (SortColumn::Type, -1),
SortKey::Modified => (SortColumn::Modified, -1),
SortKey::Playlist(i) => (SortColumn::Playlist, i as i32),
};
FolderState {
open: s.dir.is_some(),
status,
error: error.into(),
sort: column,
playlist,
descending: s.settings.descending,
group: match s.settings.group {
GroupBy::None => Grouping::None,
GroupBy::Type => Grouping::Type,
GroupBy::Modified => Grouping::Modified,
GroupBy::Size => Grouping::Size,
},
filter: s.settings.filter.as_str().into(),
items: shown as i32,
hidden: hidden as i32,
mode: s.settings.mode,
zoom: s.settings.zoom as i32,
columns: s.columns as i32,
previews: s.settings.previews,
motion: s.epoch,
travel: s.travel,
travel_epoch: s.travel_epoch,
edit_row: s
.edit
.as_ref()
.and_then(|n| s.row_of.get(n))
.map_or(-1, |&row| match s.settings.mode {
ViewMode::Details => row as i32,
// The grid scrolls by line.
ViewMode::Grid => motion::grid(&headers(&s), &[], s.columns)
.0
.iter()
.position(|l| {
!l.header && (l.start..l.start + l.count).contains(&(row as i32))
})
.map_or(-1, |l| l as i32),
}),
edit_select: s.edit.as_ref().map_or(0, |n| base_len(&s, n)) as i32,
}
}
/// The grid's lines for the current rows and column count.
pub fn grid_lines(&self) -> Vec<GridRow> {
let s = self.state.borrow();
motion::grid(&headers(&s), &[], s.columns).0
}
pub fn set_mode(&self, mode: ViewMode) {
let zoom = self.state.borrow().settings.zoom;
self.set_view(mode, zoom);
}
/// Icon size `by` steps larger (negative: smaller), or back to the default size with 0;
/// the grid only (the details rows keep their size).
pub fn zoom(&self, by: i32) {
let zoom = {
let s = self.state.borrow();
if s.settings.mode != ViewMode::Grid {
return;
}
if by == 0 {
s.default_view.1
} else {
s.settings.zoom.step(by)
}
};
self.set_view(ViewMode::Grid, zoom);
}
/// Grid view with icons of `zoom` (the View mode menu).
pub fn set_view(&self, mode: ViewMode, zoom: Zoom) {
let ghosts = {
let mut s = self.state.borrow_mut();
if (s.settings.mode, s.settings.zoom) == (mode, zoom) {
return;
}
s.settings.mode = mode;
s.settings.zoom = zoom;
self.write_view(&s);
still(&mut s)
};
if ghosts {
self.notify.reset();
}
self.emit();
self.pump();
}
pub fn mode(&self) -> (ViewMode, Zoom) {
let s = self.state.borrow();
(s.settings.mode, s.settings.zoom)
}
/// The grid view's column count changed: the lines reflow at once.
pub fn set_columns(&self, columns: usize) {
let ghosts = {
let mut s = self.state.borrow_mut();
let columns = columns.max(1);
if s.columns == columns {
return;
}
s.columns = columns;
still(&mut s)
};
if ghosts {
self.notify.reset();
}
self.emit();
self.pump();
}
// ---- list motion -----------------------------------------------------------------
/// What the rows look like and where they are drawn, before a change that may animate.
/// `None` when it shouldn't: reduced motion, still loading, or too many rows.
fn snapshot(&self, s: &State) -> Option<Vec<Old>> {
if (self.list_time.borrow())().is_zero()
|| !matches!(s.status, Status::Ready)
|| s.rows.len() > motion::LIMIT
{
return None;
}
let progress = s.clock.map_or(1.0, |c| c.settled());
let drawn = motion::drawn(s.settings.mode, &headers(s), &s.anim, s.columns, progress);
Some(
(0..s.rows.len())
.map(|r| {
let mut row = row_data(s, r).unwrap_or_default();
row.selected = false;
row.cursor = false;
Old {
key: key_of(s, r),
row,
drawn: drawn[r],
leaving: matches!(s.rows[r], Row::Leaving(..)),
}
})
.collect(),
)
}
/// After a rebuild: puts the removed rows back as leaving copies and starts the motion
/// from `old` to the new rows.
fn animate(&self, s: &mut State, old: Option<Vec<Old>>) {
let Some(old) = old else {
return;
};
if s.rows.len() > motion::LIMIT {
return;
}
let new: Vec<Key> = (0..s.rows.len()).map(|r| key_of(s, r)).collect();
let merged = motion::merge(&old, &new);
let flags: Vec<bool> = merged
.iter()
.map(|m| match *m {
Ok(n) => matches!(s.rows[n], Row::Header(_)),
Err(o) => old[o].row.header,
})
.collect();
let Some(anims) = motion::plan(s.settings.mode, &old, &new, &merged, &flags, s.columns)
else {
return;
};
s.rows = merged
.iter()
.map(|m| match *m {
Ok(n) => s.rows[n].clone(),
Err(o) => Row::Leaving(old[o].key.clone(), Box::new(old[o].row.clone())),
})
.collect();
index(s);
s.anim = anims;
s.clock = Some(Clock {
start: Instant::now(),
duration: (self.list_time.borrow())(),
});
s.epoch += 1;
}
/// The view's clock ran out: leaving rows go.
pub fn motion_settled(&self) {
let ghosts = {
let mut s = self.state.borrow_mut();
// A clock that ends right after a new change started belongs to the old one.
match s.clock {
Some(c) if c.start.elapsed() >= c.duration / 2 => still(&mut s),
_ => return,
}
};
if ghosts {
self.notify.reset();
self.emit();
}
}
// ---- view settings ----------------------------------------------------------------
fn update(&self, f: impl FnOnce(&mut Settings)) {
let mut s = self.state.borrow_mut();
let old = self.snapshot(&s);
f(&mut s.settings);
rebuild(&mut s);
self.animate(&mut s, old);
self.write_view(&s);
drop(s);
self.notify.reset();
self.emit();
self.pump();
}
/// Column header click: a new key sorts ascending, the same key flips the direction.
pub fn sort_column(&self, column: SortColumn) {
let key = match column {
SortColumn::Size => SortKey::Size,
SortColumn::Type => SortKey::Type,
SortColumn::Modified => SortKey::Modified,
SortColumn::Name | SortColumn::Playlist => SortKey::Name,
};
self.state.borrow_mut().playlist_path = None;
self.update(|s| {
if s.key == key {
s.descending = !s.descending;
} else {
s.key = key;
s.descending = false;
}
});
}
pub fn set_filter(&self, text: &str) {
self.update(|s| s.filter = text.to_owned());
}
/// Type-to-filter: printable text appends, `"\u{8}"` (Backspace) drops the last char.
pub fn type_filter(&self, text: &str) {
let mut filter = self.state.borrow().settings.filter.clone();
if text == "\u{8}" {
if filter.pop().is_none() {
return;
}
} else if !text.is_empty() && text.chars().all(|c| !c.is_control() && !is_key_code(c)) {
filter.push_str(text);
} else {
return;
}
self.set_filter(&filter);
}
/// The settings dialog changed what applies to panes already open: a new default view
/// shows at once in a folder that keeps none of its own.
pub fn apply_config(&self, cfg: &config::Settings) {
let view = default_view(cfg);
let follow = {
let mut s = self.state.borrow_mut();
std::mem::replace(&mut s.default_view, view) != view && !s.remembered
};
if follow {
self.set_view(view.0, view.1);
}
let (hidden, folders_first) = (cfg.show_hidden, cfg.folders_first);
let current = {
let s = self.state.borrow();
(s.settings.show_hidden, s.settings.folders_first)
};
if current != (hidden, folders_first) {
self.update(|s| {
s.show_hidden = hidden;
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).
pub fn redraw_dates(&self) {
self.notify.reset();
}
/// True when a row shows a date that changes within the hour.
pub fn has_fresh_dates(&self) -> bool {
let s = self.state.borrow();
s.items
.iter()
.any(|i| i.entry.mtime.is_some_and(format::is_fresh))
}
/// True when everything selected (or under the cursor) is a folder.
pub fn selection_is_dir(&self) -> bool {
let s = self.state.borrow();
let names: Vec<&Vec<u8>> = if s.selected.is_empty() {
s.cursor.iter().collect()
} else {
s.selected.iter().collect()
};
!names.is_empty()
&& names
.iter()
.all(|n| s.by_name.get(*n).is_some_and(|&i| s.items[i].is_dir))
}
pub fn toggle_hidden(&self) {
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: keys,
/// direction, then folders first, grouping and hidden files.
pub fn sort_menu(&self) -> Vec<MenuItem> {
let s = self.state.borrow();
let set = &s.settings;
let check = |on: bool| SharedString::from(if on { CHECK } else { "" });
let item = |text: &str, on: bool, shortcut: &str| MenuItem {
text: text.into(),
icon: check(on),
shortcut: shortcut.into(),
..Default::default()
};
let separator = || MenuItem {
separator: true,
..Default::default()
};
let mut menu: Vec<MenuItem> = SORT_KEYS
.iter()
.map(|(text, key)| item(text, set.key == *key, ""))
.collect();
let several = s.playlists.len() > 1;
for (i, p) in s.playlists.iter().enumerate() {
let text = if several {
format!("Playlist sort: {}", p.title)
} else {
"Playlist sort".to_owned()
};
menu.push(item(&text, set.key == SortKey::Playlist(i), ""));
}
let submenu: Vec<MenuEntry> = GROUPS
.iter()
.map(|(text, g)| MenuEntry {
text: (*text).into(),
icon: check(set.group == *g),
..Default::default()
})
.collect();
menu.extend([
separator(),
item("Ascending", !set.descending, ""),
item("Descending", set.descending, ""),
separator(),
item("Folders first", set.folders_first, ""),
MenuItem {
text: "Group by".into(),
submenu: ModelRc::new(VecModel::from(submenu)),
..Default::default()
},
separator(),
item("Show hidden files", set.show_hidden, "Ctrl+H"),
]);
menu
}
/// The sort menu as a submenu (the context menu's Sort by): keys, direction and folders
/// first; the indices are the sort menu's.
pub fn sort_submenu(&self) -> Vec<MenuEntry> {
let menu = self.sort_menu();
// Leaves out Group by (a submenu of its own), its separator and Show hidden files.
let end = menu.len() - 3;
menu.into_iter()
.take(end)
.map(|m| MenuEntry {
text: m.text,
icon: m.icon,
shortcut: m.shortcut,
disabled: m.disabled,
separator: m.separator,
})
.collect()
}
/// Runs the sort menu item at `index` (`sub` in its submenu, else -1).
pub fn sort_menu_activated(&self, index: usize, sub: i32) {
let playlists = self.state.borrow().playlists.len();
match index {
i if i < SORT_KEYS.len() => {
self.state.borrow_mut().playlist_path = None;
self.update(|s| s.key = SORT_KEYS[i].1);
}
i if i < SORT_KEYS.len() + playlists => {
let p = i - SORT_KEYS.len();
{
let mut s = self.state.borrow_mut();
s.playlist_path = Some(s.playlists[p].path.clone());
}
self.update(|s| s.key = SortKey::Playlist(p));
}
i => match i - SORT_KEYS.len() - playlists {
1 => self.update(|s| s.descending = false),
2 => self.update(|s| s.descending = true),
4 => self.update(|s| s.folders_first = !s.folders_first),
5 => {
if let Some((_, g)) = usize::try_from(sub).ok().and_then(|i| GROUPS.get(i)) {
self.update(|s| s.group = *g);
}
}
7 => self.toggle_hidden(),
_ => {}
},
}
}
/// The View mode submenu: details, icons, then the icon sizes (checked in the grid).
pub fn view_menu(&self) -> Vec<MenuEntry> {
let (mode, zoom) = self.mode();
let grid = mode == ViewMode::Grid;
let check = |on: bool| SharedString::from(if on { CHECK } else { "" });
let entry = |text: &str, on: bool| MenuEntry {
text: text.into(),
icon: check(on),
..Default::default()
};
let mut menu = vec![
entry("Details", !grid),
entry("Icons", grid),
MenuEntry {
separator: true,
..Default::default()
},
];
menu.extend(
ZOOM_NAMES
.iter()
.zip(Zoom::ALL)
.map(|(text, z)| entry(text, grid && zoom == z)),
);
menu
}
pub fn view_menu_activated(&self, index: usize) {
let zoom = self.mode().1;
match index {
0 => self.set_view(ViewMode::Details, zoom),
1 => self.set_view(ViewMode::Grid, zoom),
i => {
if let Some(z) = i.checked_sub(3).and_then(|i| Zoom::ALL.get(i)) {
self.set_view(ViewMode::Grid, *z);
}
}
}
}
// ---- selection -------------------------------------------------------------------
/// Changes selection and cursor, then repaints only the rows whose look changed.
fn select(&self, f: impl FnOnce(&mut State)) {
let mut s = self.state.borrow_mut();
let before: HashSet<Vec<u8>> = s.selected.iter().chain(&s.cursor).cloned().collect();
f(&mut s);
// Moving the cursor away ends a name edit.
if s.edit.is_some() && s.edit != s.cursor {
s.edit = None;
}
let after: HashSet<Vec<u8>> = s.selected.iter().chain(&s.cursor).cloned().collect();
let rows: Vec<usize> = before
.symmetric_difference(&after)
.chain(s.cursor.iter())
.filter_map(|n| s.row_of.get(n).copied())
.collect();
drop(s);
for row in rows {
self.notify.row_changed(row);
}
}
fn name_at(&self, row: usize) -> Option<Vec<u8>> {
let s = self.state.borrow();
match s.rows.get(row)? {
Row::Item(i) => Some(s.items[*i].entry.name.clone()),
Row::Header(_) | Row::Leaving(..) => None,
}
}
/// Pointer click on `row`: plain selects it alone, Ctrl toggles it, Shift selects the range
/// from the anchor.
pub fn click(&self, row: usize, ctrl: bool, shift: bool) {
let Some(name) = self.name_at(row) else {
return;
};
self.select(|s| {
if shift {
let anchor = s.anchor.clone().unwrap_or_else(|| name.clone());
let range = range(s, &anchor, &name);
if !ctrl {
s.selected.clear();
}
s.selected.extend(range);
s.anchor = Some(anchor);
} else if ctrl {
if !s.selected.remove(&name) {
s.selected.insert(name.clone());
}
s.anchor = Some(name.clone());
} else {
s.selected = HashSet::from([name.clone()]);
s.anchor = Some(name.clone());
}
s.cursor = Some(name);
});
}
/// The selection box covers columns `cols` (fractions, cell or row widths from the first)
/// and content heights `ys`: its entries join the selection it started from (`add`: flip
/// in it). `start` begins a new box.
pub fn band(&self, cols: (f32, f32), ys: (f32, f32), add: bool, start: bool) {
let rows: Vec<usize> = {
let s = self.state.borrow();
let view = s.previews.viewport;
let hits = |c: usize| (c as f32) < cols.1 && (c + 1) as f32 > cols.0;
let mut rows = Vec::new();
let mut top = 0.0;
if s.settings.mode == ViewMode::Grid {
for line in motion::grid(&headers(&s), &[], s.columns).0 {
let height = if line.header { view.row } else { view.cell };
if !line.header && top < ys.1 && top + height > ys.0 {
let start = line.start.max(0) as usize;
rows.extend(
(0..line.count.max(0) as usize)
.filter(|c| hits(*c))
.map(|c| start + c),
);
}
top += height;
}
} else if hits(0) && view.row > 0.0 {
let first = (ys.0 / view.row).floor().max(0.0) as usize;
let last = (ys.1 / view.row).floor().max(0.0) as usize;
rows.extend(first..=last.min(s.rows.len().saturating_sub(1)));
}
rows
};
let names: HashSet<Vec<u8>> = rows.into_iter().filter_map(|r| self.name_at(r)).collect();
self.select(|s| {
if start {
s.band_base = if add {
s.selected.clone()
} else {
HashSet::new()
};
}
s.selected = if add {
s.band_base.symmetric_difference(&names).cloned().collect()
} else {
&s.band_base | &names
};
});
}
pub fn select_all(&self) {
self.select(|s| {
let names: Vec<Vec<u8>> = s.row_of.keys().cloned().collect();
s.selected.extend(names);
});
}
pub fn clear_selection(&self) {
self.select(|s| s.selected.clear());
}
/// Selects what is shown and not selected, and unselects the rest.
pub fn invert_selection(&self) {
self.select(|s| {
let names: HashSet<Vec<u8>> = s
.row_of
.keys()
.filter(|n| !s.selected.contains(*n))
.cloned()
.collect();
s.selected = names;
});
}
/// The entries `selected_uris` names, in the same order.
pub fn selected_entries(&self) -> Vec<tunal_core::Entry> {
let names: Vec<Vec<u8>> = self
.selected_uris()
.iter()
.filter_map(|u| u.file_name().map(<[u8]>::to_vec))
.collect();
names.iter().filter_map(|n| self.entry(n)).collect()
}
/// The entry named `name` in the folder.
pub fn entry(&self, name: &[u8]) -> Option<tunal_core::Entry> {
let s = self.state.borrow();
s.by_name.get(name).map(|&i| s.items[i].entry.clone())
}
/// Selected entries, in the order shown (the cursor entry when nothing is selected).
pub fn selected_uris(&self) -> Vec<Uri> {
let s = self.state.borrow();
let Some(dir) = &s.dir else {
return Vec::new();
};
let names: Vec<&Vec<u8>> = if s.selected.is_empty() {
s.cursor.iter().collect()
} else {
s.rows
.iter()
.filter_map(|r| match r {
Row::Item(i) => Some(&s.items[*i].entry.name),
_ => None,
})
.filter(|n| s.selected.contains(*n))
.collect()
};
names.into_iter().map(|n| dir.join(n)).collect()
}
/// The files shown (no folders), in the order shown.
pub fn shown_files(&self) -> Vec<Uri> {
let s = self.state.borrow();
let Some(dir) = &s.dir else {
return Vec::new();
};
s.rows
.iter()
.filter_map(|r| match r {
Row::Item(i) if !s.items[*i].is_dir => Some(dir.join(&s.items[*i].entry.name)),
_ => None,
})
.collect()
}
/// What a drag from `row` carries: the selection when the row is in it, else the row.
pub fn drag_uris(&self, row: usize) -> Vec<Uri> {
let Some(name) = self.name_at(row) else {
return Vec::new();
};
if self.state.borrow().selected.contains(&name) {
return self.selected_uris();
}
let s = self.state.borrow();
s.dir.iter().map(|d| d.join(&name)).collect()
}
/// The folder `row` shows, if it is one.
pub fn folder_at(&self, row: usize) -> Option<Uri> {
let s = self.state.borrow();
match s.rows.get(row)? {
Row::Item(i) if s.items[*i].is_dir => {
Some(s.dir.as_ref()?.join(&s.items[*i].entry.name))
}
_ => None,
}
}
/// The items to draw dimmed: those on the clipboard to be moved.
pub fn set_cut(&self, uris: &[Uri]) {
let mut s = self.state.borrow_mut();
let cut: HashSet<Uri> = uris.iter().cloned().collect();
if s.cut == cut {
return;
}
let dir = s.dir.clone();
let rows: Vec<usize> = s
.rows
.iter()
.enumerate()
.filter_map(|(r, row)| match (row, &dir) {
(Row::Item(i), Some(d)) => {
let uri = d.join(&s.items[*i].entry.name);
(s.cut.contains(&uri) != cut.contains(&uri)).then_some(r)
}
_ => None,
})
.collect();
s.cut = cut;
drop(s);
for row in rows {
self.notify.row_changed(row);
}
}
/// True when an entry with this exact name is in the folder.
pub fn has_name(&self, name: &[u8]) -> bool {
self.state.borrow().by_name.contains_key(name)
}
/// Edits the name of the cursor entry in its row; false when there is none.
pub fn begin_edit(&self) -> bool {
let name = {
let s = self.state.borrow();
s.cursor
.clone()
.filter(|n| s.row_of.contains_key(n))
.or_else(|| s.selected.iter().next().cloned())
};
let Some(name) = name else {
return false;
};
self.select(|s| {
s.selected = HashSet::from([name.clone()]);
s.anchor = Some(name.clone());
s.cursor = Some(name.clone());
s.edit = Some(name);
});
self.emit();
true
}
pub fn end_edit(&self) {
let row = {
let mut s = self.state.borrow_mut();
let name = s.edit.take();
name.and_then(|n| s.row_of.get(&n).copied())
};
if let Some(row) = row {
self.notify.row_changed(row);
}
self.emit();
}
/// The entry being edited.
pub fn editing(&self) -> Option<Vec<u8>> {
self.state.borrow().edit.clone()
}
/// Selects `name` once it shows up in the folder, and edits its name there if `edit`.
pub fn select_when_shown(&self, name: Vec<u8>, edit: bool) {
self.state.borrow_mut().pending = Some(Pending { name, edit });
}
/// Lists the folder again (locations that can't watch, the trash).
pub fn refresh(&self) {
let Some(dir) = self.dir() else {
return;
};
let (selected, cursor) = {
let s = self.state.borrow();
(s.selected.clone(), s.cursor.clone())
};
self.open(dir);
let mut s = self.state.borrow_mut();
s.selected = selected;
s.cursor = cursor;
}
/// Keyboard move of the cursor; `page` is rows (details) or lines (grid) per page.
/// Returns the line to show: the cursor row, or the grid line holding it (-1 for none).
pub fn navigate(&self, key: NavKey, shift: bool, page: usize) -> i32 {
let (target, line) = {
let s = self.state.borrow();
let page = page.max(1);
let found = match s.settings.mode {
ViewMode::Details => list_move(&s, key, page).map(|r| (r, r)),
ViewMode::Grid => grid_move(&s, key, page),
};
let Some(found) = found else {
return -1;
};
found
};
let Some(name) = self.name_at(target) else {
return -1;
};
self.select(|s| {
if shift {
let anchor = s.anchor.clone().unwrap_or_else(|| name.clone());
s.selected = range(s, &anchor, &name).into_iter().collect();
s.anchor = Some(anchor);
} else {
s.selected = HashSet::from([name.clone()]);
s.anchor = Some(name.clone());
}
s.cursor = Some(name);
});
line as i32
}
/// Enter or double-click: opens the folder at `row` (the cursor row when `None`); a file
/// is returned for the caller to open.
pub fn activate(&self, row: Option<usize>) -> Option<Uri> {
let (uri, is_dir) = {
let s = self.state.borrow();
let row = row.or_else(|| s.cursor.as_ref().and_then(|c| s.row_of.get(c)).copied());
match row.and_then(|r| s.rows.get(r)) {
Some(Row::Item(i)) => (
s.dir.as_ref().map(|d| d.join(&s.items[*i].entry.name)),
s.items[*i].is_dir,
),
_ => (None, false),
}
};
if is_dir {
self.open_travel(uri?, Travel::Into);
return None;
}
uri
}
}
/// Names of the shown rows from `a` to `b`, inclusive, in either direction.
fn range(s: &State, a: &[u8], b: &[u8]) -> Vec<Vec<u8>> {
let (x, y) = (
s.row_of.get(a).copied().unwrap_or(0),
s.row_of.get(b).copied().unwrap_or(0),
);
s.rows[x.min(y)..=x.max(y)]
.iter()
.filter_map(|r| match r {
Row::Item(i) => Some(s.items[*i].entry.name.clone()),
Row::Header(_) | Row::Leaving(..) => None,
})
.collect()
}
/// Details view: the row a key moves the cursor to.
fn list_move(s: &State, key: NavKey, page: usize) -> Option<usize> {
let items: Vec<usize> = (0..s.rows.len())
.filter(|&r| matches!(s.rows[r], Row::Item(_)))
.collect();
let current = s
.cursor
.as_ref()
.and_then(|c| s.row_of.get(c))
.and_then(|r| items.iter().position(|i| i == r));
let last = items.len().checked_sub(1)?;
let to = match (key, current) {
(NavKey::Up | NavKey::End, None) => last,
(_, None) => 0,
(NavKey::Up | NavKey::Left, Some(c)) => c.saturating_sub(1),
(NavKey::Down | NavKey::Right, Some(c)) => (c + 1).min(last),
(NavKey::Home, _) => 0,
(NavKey::End, _) => last,
(NavKey::PageUp, Some(c)) => c.saturating_sub(page),
(NavKey::PageDown, Some(c)) => (c + page).min(last),
};
Some(items[to])
}
/// Grid view: the row a key moves the cursor to, and the grid line holding it. Up and Down
/// keep the column (or take the last cell of a shorter line), Left and Right step through
/// the entries.
fn grid_move(s: &State, key: NavKey, page: usize) -> Option<(usize, usize)> {
let (lines, _) = motion::grid(&headers(s), &[], s.columns);
// Lines of cells as (grid line, entry rows).
let cells: Vec<(usize, Vec<usize>)> = lines
.iter()
.enumerate()
.filter(|(_, l)| !l.header)
.map(|(li, l)| {
let rows = (l.start as usize..(l.start + l.count) as usize)
.filter(|&r| matches!(s.rows[r], Row::Item(_)))
.collect::<Vec<_>>();
(li, rows)
})
.filter(|(_, rows)| !rows.is_empty())
.collect();
let last_line = cells.len().checked_sub(1)?;
let place = s
.cursor
.as_ref()
.and_then(|c| s.row_of.get(c))
.and_then(|&r| {
cells
.iter()
.enumerate()
.find_map(|(i, (_, rows))| rows.iter().position(|&x| x == r).map(|c| (i, c)))
});
let at = |line: usize, col: usize| {
let (li, rows) = &cells[line];
(rows[col.min(rows.len() - 1)], *li)
};
let first = at(0, 0);
let last = at(last_line, usize::MAX);
Some(match (key, place) {
(NavKey::Up | NavKey::Left | NavKey::End | NavKey::PageUp, None) => last,
(_, None) => first,
(NavKey::Home, _) => first,
(NavKey::End, _) => last,
(NavKey::Up, Some((l, c))) => at(l.saturating_sub(1), c),
(NavKey::Down, Some((l, c))) => at((l + 1).min(last_line), c),
(NavKey::PageUp, Some((l, c))) => at(l.saturating_sub(page), c),
(NavKey::PageDown, Some((l, c))) => at((l + page).min(last_line), c),
(NavKey::Left, Some((l, c))) if c > 0 => at(l, c - 1),
(NavKey::Left, Some((l, _))) if l > 0 => at(l - 1, usize::MAX),
(NavKey::Right, Some((l, c))) if c + 1 < cells[l].1.len() => at(l, c + 1),
(NavKey::Right, Some((l, _))) if l < last_line => at(l + 1, 0),
(NavKey::Left | NavKey::Right, Some((l, c))) => at(l, c),
})
}
/// Header flags of the rows (leaving copies included).
fn headers(s: &State) -> Vec<bool> {
s.rows
.iter()
.map(|r| match r {
Row::Header(_) => true,
Row::Item(_) => false,
Row::Leaving(_, row) => row.header,
})
.collect()
}
fn key_of(s: &State, row: usize) -> Key {
match &s.rows[row] {
Row::Header(label) => Key::Header(label),
Row::Item(i) => Key::Item(s.items[*i].entry.name.clone()),
Row::Leaving(key, _) => key.clone(),
}
}
/// Ends any list motion at once: leaving rows go. True if there were any.
fn still(s: &mut State) -> bool {
let ghosts = s.rows.iter().any(|r| matches!(r, Row::Leaving(..)));
if ghosts {
s.rows.retain(|r| !matches!(r, Row::Leaving(..)));
index(s);
}
s.anim.clear();
s.clock = None;
ghosts
}
fn upsert(s: &mut State, entry: Entry) {
match s.by_name.get(&entry.name) {
Some(&i) => {
let look = s.items[i].look.take();
// Kept until its content is read again.
let icon = s.items[i].icon.take();
s.previews.forget(&entry.name);
s.items[i] = Item::new(entry).with_look(look);
s.items[i].icon = icon;
}
None => {
s.by_name.insert(entry.name.clone(), s.items.len());
s.items.push(Item::new(entry));
}
}
}
/// Removes the entry `name`; false if there was none.
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);
}
true
}
/// Recomputes the shown rows from items and settings, and drops selection that is no longer
/// shown.
fn rebuild(s: &mut State) {
let settings = &s.settings;
let filter = settings.filter.to_lowercase();
let mut shown: Vec<usize> = (0..s.items.len())
.filter(|&i| {
let item = &s.items[i];
(settings.show_hidden || !item.entry.hidden)
&& (filter.is_empty() || item.key.contains(&filter))
})
.collect();
let ranks = match settings.key {
SortKey::Playlist(i) => s.playlists.get(i).map(|p| &p.ranks),
_ => None,
};
let order = settings.order();
let calendar = sort::Calendar::now();
let groups: Vec<(u8, &'static str)> = s
.items
.iter()
.map(|item| sort::group(item, settings.group, &calendar))
.collect();
shown.sort_by(|&a, &b| {
groups[a]
.0
.cmp(&groups[b].0)
.then_with(|| sort::compare(&s.items[a], &s.items[b], &order, ranks))
});
let mut rows = Vec::with_capacity(shown.len() + 8);
let mut last_group = None;
for i in shown {
if settings.group != GroupBy::None && last_group != Some(groups[i].0) {
last_group = Some(groups[i].0);
rows.push(Row::Header(groups[i].1));
}
rows.push(Row::Item(i));
}
s.rows = rows;
s.anim.clear();
s.clock = None;
index(s);
let row_of = &s.row_of;
s.selected.retain(|n| row_of.contains_key(n));
if s.cursor.as_ref().is_some_and(|c| !row_of.contains_key(c)) {
s.cursor = None;
}
if s.edit.as_ref().is_some_and(|n| !s.row_of.contains_key(n)) {
s.edit = None;
}
if let Some(Pending { name, edit }) = s.pending.take_if(|p| s.row_of.contains_key(&p.name)) {
s.selected = HashSet::from([name.clone()]);
s.cursor = Some(name.clone());
s.anchor = Some(name.clone());
if edit {
s.edit = Some(name);
}
}
}
/// Bytes of the display name before its extension (`.tar.gz` counts as one), or all of it
/// for a folder or a name without one: what editing a name preselects.
fn base_len(s: &State, name: &[u8]) -> usize {
let Some(&i) = s.by_name.get(name) else {
return 0;
};
let item = &s.items[i];
let text = item.entry.display_name.as_str();
if item.is_dir {
return text.len();
}
match text.rfind('.') {
Some(dot) if dot > 0 => {
let stem = &text[..dot];
if stem.len() > 4 && stem.ends_with(".tar") {
stem.len() - 4
} else {
dot
}
}
_ => text.len(),
}
}
/// Applies the view settings a folder's `.directory` asks for, keeping the pane's own to
/// return to when another folder opens.
fn apply_view(s: &mut State, view: &tunal_dirmeta::View) {
s.inherited = Some(s.settings.clone());
s.remembered = true;
let set = &mut s.settings;
match view.mode.as_deref() {
Some("details") => set.mode = ViewMode::Details,
Some("grid") => set.mode = ViewMode::Grid,
_ => {}
}
if let Some(zoom) = view.zoom.as_deref().and_then(Zoom::from_word) {
set.zoom = zoom;
}
match view.sort.as_deref() {
Some("name") => set.key = SortKey::Name,
Some("size") => set.key = SortKey::Size,
Some("type") => set.key = SortKey::Type,
Some("modified") => set.key = SortKey::Modified,
// Chosen once the playlists are found.
Some("playlist") => set.key = SortKey::Name,
_ => {}
}
if let Some(d) = view.descending {
set.descending = d;
}
match view.group.as_deref() {
Some("none") => set.group = GroupBy::None,
Some("type") => set.group = GroupBy::Type,
Some("modified") => set.group = GroupBy::Modified,
Some("size") => set.group = GroupBy::Size,
_ => {}
}
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)
{
s.playlist_path = Some(dir.join(file));
}
}
/// The settings as a folder keeps them in its `.directory`.
fn view_of(s: &State) -> tunal_dirmeta::View {
let set = &s.settings;
let playlist = match set.key {
SortKey::Playlist(_) => s
.playlist_path
.as_ref()
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned()),
_ => None,
};
tunal_dirmeta::View {
mode: Some(
match set.mode {
ViewMode::Grid => "grid",
_ => "details",
}
.into(),
),
sort: Some(
match set.key {
SortKey::Name => "name",
SortKey::Size => "size",
SortKey::Type => "type",
SortKey::Modified => "modified",
SortKey::Playlist(_) => "playlist",
}
.into(),
),
descending: Some(set.descending),
group: Some(
match set.group {
GroupBy::None => "none",
GroupBy::Type => "type",
GroupBy::Modified => "modified",
GroupBy::Size => "size",
}
.into(),
),
hidden: Some(set.show_hidden),
previews: Some(set.previews),
zoom: Some(set.zoom.word().into()),
playlist,
}
}
/// Recomputes `row_of` from `rows`.
fn index(s: &mut State) {
s.row_of = s
.rows
.iter()
.enumerate()
.filter_map(|(r, row)| match row {
Row::Item(i) => Some((s.items[*i].entry.name.clone(), r)),
Row::Header(_) | Row::Leaving(..) => None,
})
.collect();
}
/// Slint sends special keys (arrows, F-keys) as private-use characters.
fn is_key_code(c: char) -> bool {
('\u{F700}'..='\u{F8FF}').contains(&c)
}
fn error_text(e: &Error) -> String {
match e {
Error::NotFound => "This folder doesn't exist.".into(),
Error::PermissionDenied => "You don't have permission to open this folder.".into(),
Error::Unsupported => "This kind of location can't be opened yet.".into(),
other => other.to_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
}
}
}
/// The check mark of a chosen menu item (Material `check`).
const CHECK: &str = "\u{e5ca}";
/// The sort keys in menu order.
const SORT_KEYS: [(&str, SortKey); 4] = [
("Name", SortKey::Name),
("Size", SortKey::Size),
("Modified", SortKey::Modified),
("Type", SortKey::Type),
];
const GROUPS: [(&str, GroupBy); 4] = [
("None", GroupBy::None),
("Type", GroupBy::Type),
("Modified", GroupBy::Modified),
("Size", GroupBy::Size),
];
/// Names of the icon sizes, by `Zoom`.
const ZOOM_NAMES: [&str; 4] = [
"Small icons",
"Medium icons",
"Large icons",
"Extra large icons",
];
/// 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)? {
Row::Leaving(_, data) => (**data).clone(),
Row::Header(label) => DetailRow {
header: true,
name: (*label).into(),
..Default::default()
},
Row::Item(i) => {
let item = &s.items[*i];
let entry = &item.entry;
// Without previews every entry has its plain glyph.
let look = item.look.as_ref().filter(|_| s.settings.previews);
let picture = look
.and_then(|l| l.picture.as_deref())
.and_then(look::picture)
.or_else(|| {
let themed = s.settings.previews && look.is_none_or(|l| l.glyph.is_none());
let icon = themed.then(|| {
item.icon
.clone()
.or_else(|| file_icons::by_name(s.dir.as_ref(), entry))
});
icon.flatten().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()
} else {
item.shown_name()
}
.into(),
glyph: look
.and_then(|l| l.glyph)
.map_or(item.category.glyph().into(), |g| g.to_string().into()),
shape_glyph: item.category.glyph().into(),
has_picture: picture.is_some(),
picture: picture.unwrap_or_default(),
badge: icons::link_badge(&entry.kind).into(),
size: if item.is_dir {
SharedString::new()
} else {
format::size(entry.size).into()
},
kind: icons::type_label(entry, item.category).into(),
modified: entry.mtime.map(format::date).unwrap_or_default().into(),
selected: s.selected.contains(&entry.name),
cursor: s.cursor.as_ref() == Some(&entry.name),
dimmed: !s.cut.is_empty()
&& s.dir
.as_ref()
.is_some_and(|d| s.cut.contains(&d.join(&entry.name))),
editing: s.edit.as_ref() == Some(&entry.name),
..Default::default()
}
}
};
s.anim.get(row).copied().unwrap_or_default().fill(&mut data);
Some(data)
}
impl Model for FolderModel {
type Data = DetailRow;
fn row_count(&self) -> usize {
self.state.borrow().rows.len()
}
fn row_data(&self, row: usize) -> Option<DetailRow> {
row_data(&self.state.borrow(), row)
}
fn model_tracker(&self) -> &dyn ModelTracker {
&self.notify
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}