Tunal/crates/tunal/src/folder/mod.rs

1293 lines
43 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 format;
mod load;
mod motion;
mod sort;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
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 crate::config;
use crate::icons::{self, Category};
use crate::{
DetailRow, FolderState, FolderStatus, GridRow, Grouping, MenuEntry, MenuItem, NavKey,
SortColumn, Travel, ViewMode,
};
pub use load::Deliver;
use load::{Change, Msg};
use motion::{Anim, Clock, Key, Old};
pub use sort::{GroupBy, Settings, SortKey};
/// One entry with what sorting and drawing need, computed once.
pub struct Item {
pub entry: Entry,
/// Lower-cased display name, for natural order and the filter.
pub key: String,
pub is_dir: bool,
pub category: Category,
}
impl Item {
fn new(entry: Entry) -> Self {
Self {
key: entry.display_name.to_lowercase(),
is_dir: entry.kind.is_dir(),
category: Category::of(&entry),
entry,
}
}
/// Folders count as empty for size order.
pub fn size(&self) -> u64 {
if self.is_dir { 0 } else { self.entry.size }
}
}
#[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,
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>>,
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>,
}
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,
/// 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) -> Rc<Self> {
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(&config::load("settings")),
playlists: Vec::new(),
playlist_path: None,
selected: 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,
}),
notify: ModelNotify::default(),
locations,
deliver,
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.
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.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::Changed(g, changes) if g == current => {
// Reads are reported too: only entries whose stat differs count.
let mut changed = false;
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) {
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);
}
Msg::PlaylistsChanged(g) if g == current => self.refresh_playlists(&s),
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();
}
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,
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 ghosts = {
let mut s = self.state.borrow_mut();
if s.settings.mode == mode {
return;
}
s.settings.mode = mode;
still(&mut s)
};
if ghosts {
self.notify.reset();
}
self.emit();
}
/// 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();
}
// ---- 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);
drop(s);
self.notify.reset();
self.emit();
}
/// 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.
pub fn apply_config(&self, cfg: &config::Settings) {
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;
});
}
}
/// 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);
}
/// 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();
let set = &s.settings;
let check = |on: bool| SharedString::from(if on { "\u{e5ca}" } else { "" });
let item = |text: &str, on: bool, shortcut: &str| MenuItem {
text: text.into(),
icon: check(on),
shortcut: shortcut.into(),
..Default::default()
};
let mut menu = vec![
item("Name", set.key == SortKey::Name, ""),
item("Size", set.key == SortKey::Size, ""),
item("Type", set.key == SortKey::Type, ""),
item("Modified", set.key == SortKey::Modified, ""),
];
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 groups = [
("None", GroupBy::None),
("Type", GroupBy::Type),
("Modified", GroupBy::Modified),
("Size", GroupBy::Size),
];
let submenu: Vec<MenuEntry> = groups
.iter()
.map(|(text, g)| MenuEntry {
text: (*text).into(),
icon: check(set.group == *g),
..Default::default()
})
.collect();
menu.extend([
MenuItem {
separator: true,
..Default::default()
},
item("Descending", set.descending, ""),
item("Folders first", set.folders_first, ""),
MenuItem {
text: "Group by".into(),
submenu: ModelRc::new(VecModel::from(submenu)),
..Default::default()
},
MenuItem {
separator: true,
..Default::default()
},
item("Show hidden files", set.show_hidden, "Ctrl+H"),
]);
menu
}
/// 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();
let keys = [
SortKey::Name,
SortKey::Size,
SortKey::Type,
SortKey::Modified,
];
match index {
i if i < 4 => {
self.state.borrow_mut().playlist_path = None;
self.update(|s| s.key = keys[i]);
}
i if i < 4 + playlists => {
{
let mut s = self.state.borrow_mut();
s.playlist_path = Some(s.playlists[i - 4].path.clone());
}
self.update(|s| s.key = SortKey::Playlist(i - 4));
}
i => match i - 4 - playlists {
1 => self.update(|s| s.descending = !s.descending),
2 => self.update(|s| s.folders_first = !s.folders_first),
3 => {
let group = [
GroupBy::None,
GroupBy::Type,
GroupBy::Modified,
GroupBy::Size,
];
if let Some(g) = usize::try_from(sub).ok().and_then(|i| group.get(i)) {
self.update(|s| s.group = *g);
}
}
5 => self.toggle_hidden(),
_ => {}
},
}
}
// ---- 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);
});
}
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());
}
/// 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()
}
/// 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) => s.items[i] = Item::new(entry),
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.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 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], settings, 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(),
}
}
/// 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(),
}
}
/// 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;
DetailRow {
header: false,
name: entry.display_name.as_str().into(),
glyph: item.category.glyph().into(),
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
}
}