S008: folder model, playlist sort and details view
FolderModel loads and watches folders off the UI thread, sorts (natural name, size, type, modified, playlist), groups, filters and keeps the selection; the details view shows it in a virtualized list with a click-to-sort header, filter chip and empty/loading/error states. tunal-core::playlist reads m3u/m3u8/pls/xspf/wpl (D-030). tunal <dir> opens a folder. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
ff45d747eb
commit
048581938e
19 changed files with 2425 additions and 42 deletions
|
|
@ -9,8 +9,8 @@ Status: planned → done (later plans update their rows when they ship a feature
|
|||
| Location layer (list, stat, read, write, copy, move, rename, delete, trash), local backend | planned | S006 | tunal-core |
|
||||
| Copy, cut, paste, rename, delete, move to trash, file operations with progress, cancel and conflicts | planned | S007, S011 | tunal-core, tunal |
|
||||
| Details view and icon grid view, type-to-filter | planned | S008, S009 | tunal |
|
||||
| Sorting, grouping, hidden files toggle | planned | S008 | tunal |
|
||||
| Playlist sort in the music folder (m3u, m3u8, pls, xspf order) | planned | S008 | tunal-core::playlist, tunal |
|
||||
| Sorting, grouping, hidden files toggle | done | S008 | tunal |
|
||||
| Playlist sort in the music folder (m3u, m3u8, pls, xspf, wpl order; folder and shared Playlists folder) | done | S008 | tunal-core::playlist, tunal |
|
||||
| Tabs, split view, editable breadcrumb path bar, back / forward / up, places sidebar | planned | S010 | tunal |
|
||||
| Copy path, properties, Open, Open with | planned | S012 | tunal |
|
||||
| Settings dialog and context menus the user can edit (add, remove, reorder) | planned | S013 | tunal |
|
||||
|
|
@ -26,7 +26,7 @@ Status: planned → done (later plans update their rows when they ship a feature
|
|||
| Theme and Motion token globals, window, screenshot command | planned | S003 | tunal |
|
||||
| Animated base controls, menus, dialogs, toasts | done | S004, S005 | tunal |
|
||||
| List insert / remove / reorder motion | planned | S009 | tunal |
|
||||
| Material icons for files and folders | planned | S008 | tunal |
|
||||
| Material icons for files and folders | done | S008 | tunal |
|
||||
| Thumbnails: images, video frames, embedded album art | planned | S017, S018 | tunal-thumbs |
|
||||
| Motion audit and visual sign-off | planned | S034, S035 | tunal |
|
||||
|
||||
|
|
|
|||
|
|
@ -10,14 +10,14 @@ A folder model fed from the location layer off the UI thread (sorting, grouping,
|
|||
CLAUDE.md §3, §4; crates/tunal-core trait; crates/tunal/ui/components/list-row.slint, menu.slint.
|
||||
|
||||
## Steps
|
||||
- [ ] `FolderModel`: load off-thread in chunks, apply watch diffs (insert/remove/change) keeping selection; a Slint `Model` that stays fast at 10 000+ rows.
|
||||
- [ ] Sorting (natural name order, size, type, modified; folders first toggle; asc/desc) and grouping (none, type, modified date buckets, size buckets) with group header rows.
|
||||
- [ ] Playlist sort (D-021): in folders under `XDG_MUSIC_DIR` that hold a playlist (`.m3u`, `.m3u8`, `.pls`, `.xspf`), the sort options show **Playlist sort** (one entry per playlist when there are several); files listed in the playlist come first in playlist order, the rest follow in natural name order; desc reverses; the playlist file is watched and re-sorts on change. Parser in `tunal-core::playlist` (relative/absolute paths, `file://` URLs, percent-decoding, `#EXT` lines skipped).
|
||||
- [ ] Hidden files toggle (dot files) and type-to-filter (typing filters by substring, a filter chip shows the text, Esc clears).
|
||||
- [ ] Mime → Material Symbols glyph map (folder, image, audio, video, text, code, archive, PDF, executable, generic, symlink badge).
|
||||
- [ ] Details view: `ListView` rows on `ListRow`, column header with click-to-sort and animated indicator, empty/loading/error states.
|
||||
- [ ] Selection: click, Ctrl, Shift range, Ctrl+A, arrows/Home/End/PageUp/PageDown, Enter on a folder opens it. Temporary: `tunal <dir>` opens that folder.
|
||||
- [ ] PROGRESS entry, INDEX line, commit `S008: …`
|
||||
- [x] `FolderModel`: load off-thread in chunks, apply watch diffs (insert/remove/change) keeping selection; a Slint `Model` that stays fast at 10 000+ rows.
|
||||
- [x] Sorting (natural name order, size, type, modified; folders first toggle; asc/desc) and grouping (none, type, modified date buckets, size buckets) with group header rows.
|
||||
- [x] Playlist sort (D-021, details D-030): in folders under `XDG_MUSIC_DIR`, playlists from the folder itself and from `<Music>/Playlists` (also `playlists`/`Playlist`/`playlist`) that place at least one entry here are offered as **Playlist sort** (one entry per playlist, the one named like the folder, else the one placing most entries, first); listed entries first in playlist order (subfolders by their first track, moved tracks by file name), the rest in natural name order; desc reverses; playlist changes re-sort. Parser in `tunal-core::playlist` (.m3u .m3u8 .pls .xspf .wpl; relative/absolute paths, `file://` URLs, percent-decoding, `#EXT` lines skipped; UTF-8 → UTF-16 → cp1252/Latin-1).
|
||||
- [x] Hidden files toggle (dot files) and type-to-filter (typing filters by substring, a filter chip shows the text, Esc clears).
|
||||
- [x] Mime → Material Symbols glyph map (folder, image, audio, video, text, code, archive, PDF, executable, generic, symlink badge).
|
||||
- [x] Details view: `ListView` rows on `ListRow`, column header with click-to-sort and animated indicator, empty/loading/error states.
|
||||
- [x] Selection: click, Ctrl, Shift range, Ctrl+A, arrows/Home/End/PageUp/PageDown, Enter on a folder opens it. Temporary: `tunal <dir>` opens that folder.
|
||||
- [x] PROGRESS entry, INDEX line, commit `S008: …`
|
||||
|
||||
## End criteria
|
||||
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
|
|||
|
||||
- [x] [S006 — Location layer and local backend](03%20File%20browsing/S006-location-layer.md) · Opus medium
|
||||
- [x] [S007 — File operations engine and trash](03%20File%20browsing/S007-file-ops-engine.md) · Opus medium
|
||||
- [ ] [S008 — Folder model and details view](03%20File%20browsing/S008-folder-model-details.md) · Opus medium
|
||||
- [x] [S008 — Folder model and details view](03%20File%20browsing/S008-folder-model-details.md) · Opus medium
|
||||
- [ ] [S009 — Icon grid view and list motion](03%20File%20browsing/S009-grid-and-list-motion.md) · Opus high
|
||||
- [ ] [S010 — Tabs, split view, breadcrumbs, history and places](03%20File%20browsing/S010-navigation-shell.md) · Opus medium
|
||||
- [ ] [S011 — File operation actions](03%20File%20browsing/S011-file-op-actions.md) · Sonnet high
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ mod local;
|
|||
mod location;
|
||||
pub mod mime;
|
||||
pub mod ops;
|
||||
pub mod playlist;
|
||||
mod registry;
|
||||
pub mod trash;
|
||||
mod uri;
|
||||
|
|
|
|||
381
crates/tunal-core/src/playlist.rs
Normal file
381
crates/tunal-core/src/playlist.rs
Normal file
|
|
@ -0,0 +1,381 @@
|
|||
//! Playlist files (`.m3u`, `.m3u8`, `.pls`, `.xspf`, `.wpl`) and the playlist sort order of
|
||||
//! a music folder (D-030).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::os::unix::ffi::{OsStrExt, OsStringExt};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use crate::uri::percent_decode;
|
||||
|
||||
/// File extensions of the formats `read` understands, lower case.
|
||||
pub const EXTENSIONS: [&str; 5] = ["m3u", "m3u8", "pls", "xspf", "wpl"];
|
||||
|
||||
/// Folder names inside the music folder that hold shared playlists, in lookup order.
|
||||
const SHARED_DIRS: [&str; 4] = ["Playlists", "playlists", "Playlist", "playlist"];
|
||||
|
||||
/// True when `name` has a playlist extension.
|
||||
pub fn is_playlist(name: &[u8]) -> bool {
|
||||
extension(Path::new(OsStr::from_bytes(name))).is_some()
|
||||
}
|
||||
|
||||
fn extension(path: &Path) -> Option<&'static str> {
|
||||
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
|
||||
EXTENSIONS.into_iter().find(|e| *e == ext)
|
||||
}
|
||||
|
||||
/// `XDG_MUSIC_DIR` from `user-dirs.dirs`, else `~/Music`.
|
||||
pub fn music_dir() -> Option<PathBuf> {
|
||||
let home = PathBuf::from(std::env::var_os("HOME")?);
|
||||
let config = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute())
|
||||
.unwrap_or_else(|| home.join(".config"));
|
||||
let configured = std::fs::read(config.join("user-dirs.dirs"))
|
||||
.ok()
|
||||
.and_then(|text| user_dir(&text, &home));
|
||||
Some(configured.unwrap_or_else(|| home.join("Music")))
|
||||
}
|
||||
|
||||
/// Parses the `XDG_MUSIC_DIR="$HOME/…"` line of a `user-dirs.dirs` file.
|
||||
fn user_dir(text: &[u8], home: &Path) -> Option<PathBuf> {
|
||||
let line = text
|
||||
.split(|&b| b == b'\n')
|
||||
.find_map(|l| l.trim_ascii().strip_prefix(b"XDG_MUSIC_DIR="))?;
|
||||
let value = line.strip_prefix(b"\"")?.strip_suffix(b"\"")?;
|
||||
let path = match value.strip_prefix(b"$HOME") {
|
||||
Some(rest) => {
|
||||
let mut p = home.as_os_str().as_bytes().to_vec();
|
||||
p.extend_from_slice(rest);
|
||||
p
|
||||
}
|
||||
None => value.to_vec(),
|
||||
};
|
||||
let path = PathBuf::from(OsString::from_vec(path));
|
||||
// A music dir equal to $HOME means "disabled" in the XDG spec.
|
||||
(path.is_absolute() && path != home).then_some(path)
|
||||
}
|
||||
|
||||
/// True when `folder` is the music folder or inside it.
|
||||
pub fn in_music(folder: &Path, music: &Path) -> bool {
|
||||
folder.starts_with(music)
|
||||
}
|
||||
|
||||
/// The shared playlist folder inside `music`, if one exists.
|
||||
pub fn shared_dir(music: &Path) -> Option<PathBuf> {
|
||||
SHARED_DIRS
|
||||
.iter()
|
||||
.map(|name| music.join(name))
|
||||
.find(|p| p.is_dir())
|
||||
}
|
||||
|
||||
/// Absolute paths of the tracks in a playlist file, in order; stream URLs are left out.
|
||||
pub fn read(path: &Path) -> std::io::Result<Vec<PathBuf>> {
|
||||
let raw = std::fs::read(path)?;
|
||||
let base = path.parent().unwrap_or(Path::new("/"));
|
||||
Ok(parse(&raw, extension(path).unwrap_or("m3u"), base))
|
||||
}
|
||||
|
||||
/// Parses playlist bytes of format `ext` (one of `EXTENSIONS`); relative entries resolve
|
||||
/// against `base`.
|
||||
pub fn parse(raw: &[u8], ext: &str, base: &Path) -> Vec<PathBuf> {
|
||||
let text = decode(raw);
|
||||
let entries: Vec<(String, bool)> = match ext {
|
||||
"pls" => {
|
||||
let mut items: Vec<(u32, &str)> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let (key, value) = line.split_once('=')?;
|
||||
let key = key.trim();
|
||||
let n = key
|
||||
.get(..4)?
|
||||
.eq_ignore_ascii_case("file")
|
||||
.then_some(&key[4..])?;
|
||||
Some((n.parse().ok()?, value))
|
||||
})
|
||||
.collect();
|
||||
items.sort_by_key(|(n, _)| *n);
|
||||
items
|
||||
.into_iter()
|
||||
.map(|(_, v)| (v.to_owned(), false))
|
||||
.collect()
|
||||
}
|
||||
"xspf" => tag_values(&text, "<location>", "</location>")
|
||||
.map(|v| (unescape_xml(v), true))
|
||||
.collect(),
|
||||
"wpl" => tag_values(&text, "src=\"", "\"")
|
||||
.map(|v| (unescape_xml(v), false))
|
||||
.collect(),
|
||||
_ => text
|
||||
.lines()
|
||||
.filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
|
||||
.map(|l| (l.to_owned(), false))
|
||||
.collect(),
|
||||
};
|
||||
entries
|
||||
.iter()
|
||||
.filter_map(|(entry, uri_ref)| resolve(entry, base, *uri_ref))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every substring between `open` and the next `close`.
|
||||
fn tag_values<'a>(text: &'a str, open: &'a str, close: &'a str) -> impl Iterator<Item = &'a str> {
|
||||
text.split(open)
|
||||
.skip(1)
|
||||
.filter_map(move |part| part.split_once(close).map(|(v, _)| v.trim()))
|
||||
}
|
||||
|
||||
/// UTF-8 (BOM optional), then UTF-16 (BOM or NUL bytes), then Windows-1252 with Latin-1 for
|
||||
/// its five unassigned bytes.
|
||||
fn decode(raw: &[u8]) -> String {
|
||||
let raw = raw.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(raw);
|
||||
if let Ok(text) = std::str::from_utf8(raw) {
|
||||
return text.to_owned();
|
||||
}
|
||||
if let Some(text) = decode_utf16(raw) {
|
||||
return text;
|
||||
}
|
||||
raw.iter().map(|&b| cp1252(b)).collect()
|
||||
}
|
||||
|
||||
fn decode_utf16(raw: &[u8]) -> Option<String> {
|
||||
let (big_endian, body) = match raw {
|
||||
[0xFF, 0xFE, rest @ ..] => (false, rest),
|
||||
[0xFE, 0xFF, rest @ ..] => (true, rest),
|
||||
// No BOM: ASCII-heavy UTF-16 has a NUL in every other byte.
|
||||
_ if raw.len() >= 2 && raw.len().is_multiple_of(2) => {
|
||||
let nul_odd = raw.iter().skip(1).step_by(2).filter(|&&b| b == 0).count();
|
||||
let nul_even = raw.iter().step_by(2).filter(|&&b| b == 0).count();
|
||||
let half = raw.len() / 4;
|
||||
match (nul_odd > half, nul_even > half) {
|
||||
(true, false) => (false, raw),
|
||||
(false, true) => (true, raw),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
if !body.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
let units = body.as_chunks::<2>().0.iter().map(|c| {
|
||||
if big_endian {
|
||||
u16::from_be_bytes([c[0], c[1]])
|
||||
} else {
|
||||
u16::from_le_bytes([c[0], c[1]])
|
||||
}
|
||||
});
|
||||
char::decode_utf16(units)
|
||||
.collect::<Result<String, _>>()
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn cp1252(b: u8) -> char {
|
||||
const HIGH: [u16; 32] = [
|
||||
0x20AC, 0x81, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160,
|
||||
0x2039, 0x0152, 0x8D, 0x017D, 0x8F, 0x90, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013,
|
||||
0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x9D, 0x017E, 0x0178,
|
||||
];
|
||||
match b {
|
||||
0x80..=0x9F => char::from_u32(HIGH[(b - 0x80) as usize].into()).unwrap_or('\u{FFFD}'),
|
||||
_ => b as char,
|
||||
}
|
||||
}
|
||||
|
||||
fn unescape_xml(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut rest = s;
|
||||
while let Some(i) = rest.find('&') {
|
||||
out.push_str(&rest[..i]);
|
||||
rest = &rest[i..];
|
||||
let Some(end) = rest.find(';').filter(|&e| e <= 10) else {
|
||||
out.push('&');
|
||||
rest = &rest[1..];
|
||||
continue;
|
||||
};
|
||||
let name = &rest[1..end];
|
||||
let c = match name {
|
||||
"amp" => Some('&'),
|
||||
"lt" => Some('<'),
|
||||
"gt" => Some('>'),
|
||||
"quot" => Some('"'),
|
||||
"apos" => Some('\''),
|
||||
_ => name
|
||||
.strip_prefix("#x")
|
||||
.or_else(|| name.strip_prefix("#X"))
|
||||
.and_then(|h| u32::from_str_radix(h, 16).ok())
|
||||
.or_else(|| name.strip_prefix('#').and_then(|d| d.parse().ok()))
|
||||
.and_then(char::from_u32),
|
||||
};
|
||||
match c {
|
||||
Some(c) => {
|
||||
out.push(c);
|
||||
rest = &rest[end + 1..];
|
||||
}
|
||||
None => {
|
||||
out.push('&');
|
||||
rest = &rest[1..];
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// One playlist entry → absolute, lexically normalised path. `uri_ref` entries (XSPF) are URI
|
||||
/// references, so relative ones are percent-decoded too.
|
||||
fn resolve(entry: &str, base: &Path, uri_ref: bool) -> Option<PathBuf> {
|
||||
let entry = entry.trim().trim_start_matches('\u{feff}');
|
||||
if entry.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let decode = |s: &str| percent_decode(s).unwrap_or_else(|| s.as_bytes().to_vec());
|
||||
let bytes = if entry
|
||||
.get(..5)
|
||||
.is_some_and(|p| p.eq_ignore_ascii_case("file:"))
|
||||
{
|
||||
let rest = &entry[5..];
|
||||
// `file://host/path` → `/path`; `file:/path` as is.
|
||||
let path = match rest.strip_prefix("//") {
|
||||
Some(after) => &after[after.find('/')?..],
|
||||
None => rest,
|
||||
};
|
||||
decode(path)
|
||||
} else if entry.contains("://") {
|
||||
return None;
|
||||
} else if uri_ref {
|
||||
decode(entry)
|
||||
} else {
|
||||
entry.replace('\\', "/").into_bytes()
|
||||
};
|
||||
let path = PathBuf::from(OsString::from_vec(bytes));
|
||||
Some(normalize(&base.join(path)))
|
||||
}
|
||||
|
||||
/// Resolves `.` and `..` without touching the disk.
|
||||
fn normalize(path: &Path) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
for part in path.components() {
|
||||
match part {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
out.pop();
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where each entry of one folder goes in a playlist's order.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Ranks {
|
||||
/// Direct child name → position of its first track (a file, or the subfolder holding it).
|
||||
by_child: HashMap<Vec<u8>, usize>,
|
||||
/// Track file name → first position, for tracks that moved.
|
||||
by_name: HashMap<Vec<u8>, usize>,
|
||||
}
|
||||
|
||||
impl Ranks {
|
||||
pub fn new(folder: &Path, tracks: &[PathBuf]) -> Self {
|
||||
let mut ranks = Self::default();
|
||||
for (i, track) in tracks.iter().enumerate() {
|
||||
if let Some(name) = track.file_name() {
|
||||
ranks.by_name.entry(name.as_bytes().to_vec()).or_insert(i);
|
||||
}
|
||||
if let Ok(rest) = track.strip_prefix(folder)
|
||||
&& let Some(first) = rest.components().next()
|
||||
{
|
||||
let child = first.as_os_str().as_bytes().to_vec();
|
||||
ranks.by_child.entry(child).or_insert(i);
|
||||
}
|
||||
}
|
||||
ranks
|
||||
}
|
||||
|
||||
/// Position of the folder entry `name`; `is_dir` entries match only by path.
|
||||
pub fn rank(&self, name: &[u8], is_dir: bool) -> Option<usize> {
|
||||
let by_path = self.by_child.get(name).copied();
|
||||
if is_dir {
|
||||
by_path
|
||||
} else {
|
||||
by_path.or_else(|| self.by_name.get(name).copied())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A playlist offered as a sort order for one folder.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Playlist {
|
||||
pub path: PathBuf,
|
||||
/// File name for menus.
|
||||
pub title: String,
|
||||
pub ranks: Ranks,
|
||||
/// Folder entries the playlist places.
|
||||
pub matches: usize,
|
||||
}
|
||||
|
||||
/// Playlists that place at least one entry of `folder` (whose entries are `entries`:
|
||||
/// name, is folder), from the folder itself and the shared playlist folder, when `folder`
|
||||
/// is inside the music folder. The first one is the preselected pick: named like the folder,
|
||||
/// else the one placing the most entries.
|
||||
pub fn candidates(folder: &Path, entries: &[(&[u8], bool)]) -> Vec<Playlist> {
|
||||
let Some(music) = music_dir() else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !in_music(folder, &music) {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut paths: Vec<PathBuf> = entries
|
||||
.iter()
|
||||
.filter(|(name, is_dir)| !is_dir && is_playlist(name))
|
||||
.map(|(name, _)| folder.join(OsStr::from_bytes(name)))
|
||||
.collect();
|
||||
if let Some(shared) = shared_dir(&music).filter(|d| d != folder)
|
||||
&& let Ok(dir) = std::fs::read_dir(&shared)
|
||||
{
|
||||
let mut shared: Vec<PathBuf> = dir
|
||||
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||
.filter(|p| is_playlist(p.as_os_str().as_bytes()) && p.is_file())
|
||||
.collect();
|
||||
shared.sort();
|
||||
paths.extend(shared);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let folder_name = folder
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_lowercase());
|
||||
let mut found: Vec<(bool, Playlist)> = paths
|
||||
.into_iter()
|
||||
.filter(|p| seen.insert(p.clone()))
|
||||
.filter_map(|path| {
|
||||
let tracks = read(&path).ok()?;
|
||||
let ranks = Ranks::new(folder, &tracks);
|
||||
let matches = entries
|
||||
.iter()
|
||||
.filter(|(name, is_dir)| ranks.rank(name, *is_dir).is_some())
|
||||
.count();
|
||||
let stem = path.file_stem().map(|s| s.to_string_lossy().to_lowercase());
|
||||
let named = stem.is_some() && stem == folder_name;
|
||||
let title = path.file_name()?.to_string_lossy().into_owned();
|
||||
(matches > 0).then_some((
|
||||
named,
|
||||
Playlist {
|
||||
path,
|
||||
title,
|
||||
ranks,
|
||||
matches,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let pick = (0..found.len()).max_by_key(|&i| {
|
||||
// `max_by_key` keeps the last maximum; `Reverse(i)` makes the earliest one win ties.
|
||||
(found[i].0, found[i].1.matches, std::cmp::Reverse(i))
|
||||
});
|
||||
if let Some(pick) = pick {
|
||||
let first = found.remove(pick);
|
||||
found.insert(0, first);
|
||||
}
|
||||
found.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
|
@ -9,6 +9,8 @@ publish.workspace = true
|
|||
slint.workspace = true
|
||||
tunal-theme = { path = "../tunal-theme" }
|
||||
png.workspace = true
|
||||
tunal-core = { path = "../tunal-core" }
|
||||
jiff.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
slint-build.workspace = true
|
||||
|
|
|
|||
42
crates/tunal/src/folder/format.rs
Normal file
42
crates/tunal/src/folder/format.rs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
//! Size and date text for the details columns.
|
||||
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `512 B`, `1.4 KiB`, `23 MiB`: one decimal below 10, none above.
|
||||
pub fn size(bytes: u64) -> String {
|
||||
const UNITS: [&str; 6] = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
|
||||
if bytes < 1024 {
|
||||
return format!("{bytes} B");
|
||||
}
|
||||
let mut value = bytes as f64 / 1024.0;
|
||||
let mut unit = 0;
|
||||
while value >= 1024.0 && unit < UNITS.len() - 1 {
|
||||
value /= 1024.0;
|
||||
unit += 1;
|
||||
}
|
||||
if value < 10.0 {
|
||||
format!("{value:.1} {}", UNITS[unit])
|
||||
} else {
|
||||
format!("{value:.0} {}", UNITS[unit])
|
||||
}
|
||||
}
|
||||
|
||||
/// `Today 14:03`, `Yesterday 09:10`, `12 Mar 14:03` this year, `12 Mar 2024` before.
|
||||
pub fn date(time: SystemTime) -> String {
|
||||
let Ok(ts) = jiff::Timestamp::try_from(time) else {
|
||||
return String::new();
|
||||
};
|
||||
let tz = jiff::tz::TimeZone::system();
|
||||
let when = ts.to_zoned(tz.clone());
|
||||
let today = jiff::Timestamp::now().to_zoned(tz).date();
|
||||
let day = when.date();
|
||||
if day == today {
|
||||
when.strftime("Today %H:%M").to_string()
|
||||
} else if today.yesterday().is_ok_and(|y| y == day) {
|
||||
when.strftime("Yesterday %H:%M").to_string()
|
||||
} else if day.year() == today.year() {
|
||||
when.strftime("%-d %b %H:%M").to_string()
|
||||
} else {
|
||||
when.strftime("%-d %b %Y").to_string()
|
||||
}
|
||||
}
|
||||
161
crates/tunal/src/folder/load.rs
Normal file
161
crates/tunal/src/folder/load.rs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
//! Folder listing, watching and playlist lookup, run off the UI thread.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ops::ControlFlow;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
use tunal_core::playlist::{self, Playlist};
|
||||
use tunal_core::{Entry, Error, Locations, Uri, Watch, WatchEvent};
|
||||
|
||||
/// Results for the model; `generation` drops those of a folder no longer shown.
|
||||
pub enum Msg {
|
||||
Chunk(u64, Vec<Entry>),
|
||||
Done(u64, Result<(), Error>),
|
||||
Watching(u64, Watch),
|
||||
Changed(u64, Vec<Change>),
|
||||
Playlists(u64, Vec<Playlist>),
|
||||
/// A file in the shared playlist folder changed: look the playlists up again.
|
||||
PlaylistsChanged(u64),
|
||||
}
|
||||
|
||||
pub enum Change {
|
||||
Upsert(Entry),
|
||||
Removed(Vec<u8>),
|
||||
}
|
||||
|
||||
pub type Deliver = Arc<dyn Fn(Msg) + Send + Sync>;
|
||||
|
||||
/// Listing chunks are batched up to this long, so the model sorts a few times, not per chunk.
|
||||
const FLUSH: Duration = Duration::from_millis(60);
|
||||
|
||||
/// Lists `dir` into `deliver`, then looks up its playlists. With `watch`, also watches the
|
||||
/// folder (and the shared playlist folder) and reports changes through it.
|
||||
pub fn load(
|
||||
locations: &Locations,
|
||||
dir: &Uri,
|
||||
generation: u64,
|
||||
deliver: &dyn Fn(Msg),
|
||||
watch: Option<Deliver>,
|
||||
) {
|
||||
let backend = match locations.resolve(dir) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return deliver(Msg::Done(generation, Err(e))),
|
||||
};
|
||||
// Watch first so changes made while listing are not lost (the model applies them in order).
|
||||
if let Some(watcher) = watch.clone() {
|
||||
let folder = dir.clone();
|
||||
let stat_backend = backend.clone();
|
||||
let callback = Box::new(move |event: WatchEvent| {
|
||||
let msg = match event {
|
||||
// No live updates then; the view still shows the last listing.
|
||||
WatchEvent::Error(_) => return,
|
||||
// The backend also reports reads (the listing itself touches the folder), so the
|
||||
// folder's own event only matters when the folder is gone.
|
||||
WatchEvent::Changed(uris)
|
||||
if uris.contains(&folder) && stat_backend.stat(&folder).is_err() =>
|
||||
{
|
||||
Msg::Done(generation, Err(Error::NotFound))
|
||||
}
|
||||
WatchEvent::Changed(uris) => Msg::Changed(
|
||||
generation,
|
||||
uris.iter()
|
||||
.filter(|uri| **uri != folder)
|
||||
.filter_map(|uri| {
|
||||
let name = uri.file_name()?.to_vec();
|
||||
Some(match stat_backend.stat(uri) {
|
||||
Ok(entry) => Change::Upsert(entry),
|
||||
Err(_) => Change::Removed(name),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
};
|
||||
watcher(msg);
|
||||
});
|
||||
if let Ok(guard) = backend.watch(dir, callback) {
|
||||
deliver(Msg::Watching(generation, guard));
|
||||
}
|
||||
}
|
||||
|
||||
let mut names: Vec<(Vec<u8>, bool)> = Vec::new();
|
||||
let mut pending: Vec<Entry> = Vec::new();
|
||||
let mut last = Instant::now();
|
||||
let mut first = true;
|
||||
let result = backend.list(dir, &mut |chunk| {
|
||||
names.extend(chunk.iter().map(|e| (e.name.clone(), e.kind.is_dir())));
|
||||
pending.extend(chunk);
|
||||
// The first chunk goes out at once so something shows quickly.
|
||||
if first || last.elapsed() >= FLUSH {
|
||||
first = false;
|
||||
last = Instant::now();
|
||||
deliver(Msg::Chunk(generation, std::mem::take(&mut pending)));
|
||||
}
|
||||
ControlFlow::Continue(())
|
||||
});
|
||||
if !pending.is_empty() {
|
||||
deliver(Msg::Chunk(generation, pending));
|
||||
}
|
||||
let ok = result.is_ok();
|
||||
deliver(Msg::Done(generation, result));
|
||||
if !ok {
|
||||
return;
|
||||
}
|
||||
let Some(path) = dir.to_path() else {
|
||||
return;
|
||||
};
|
||||
deliver(Msg::Playlists(generation, playlists(&path, &names)));
|
||||
|
||||
// Shared playlists live elsewhere in the music folder: watch that folder too.
|
||||
if let Some(watcher) = watch
|
||||
&& let Some(music) = playlist::music_dir()
|
||||
&& playlist::in_music(&path, &music)
|
||||
&& let Some(shared) = playlist::shared_dir(&music).filter(|s| *s != path)
|
||||
{
|
||||
let refresh = watcher.clone();
|
||||
// Looking the playlists up reads them, which the backend reports too: refresh only
|
||||
// when a file's size or time differs from what was last seen.
|
||||
let seen = Mutex::new(stamps(&shared));
|
||||
let callback = Box::new(move |event| {
|
||||
let WatchEvent::Changed(uris) = event else {
|
||||
return;
|
||||
};
|
||||
let mut seen = seen.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut changed = false;
|
||||
for path in uris.iter().filter_map(Uri::to_path) {
|
||||
let stamp = std::fs::metadata(&path)
|
||||
.ok()
|
||||
.map(|m| (m.modified().ok(), m.len()));
|
||||
changed |= seen.insert(path, stamp).flatten() != stamp;
|
||||
}
|
||||
if changed {
|
||||
refresh(Msg::PlaylistsChanged(generation));
|
||||
}
|
||||
});
|
||||
if let Ok(guard) = backend.watch(&Uri::from_path(&shared), callback) {
|
||||
watcher(Msg::Watching(generation, guard));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Stamp = Option<(Option<SystemTime>, u64)>;
|
||||
|
||||
/// Modification time and size of each file in `dir`.
|
||||
fn stamps(dir: &Path) -> HashMap<PathBuf, Stamp> {
|
||||
std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let e = e.ok()?;
|
||||
let m = e.metadata().ok()?;
|
||||
Some((e.path(), Some((m.modified().ok(), m.len()))))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Playlists for the folder at `path` holding `names` (name, is folder).
|
||||
pub fn playlists(path: &Path, names: &[(Vec<u8>, bool)]) -> Vec<Playlist> {
|
||||
let entries: Vec<(&[u8], bool)> = names.iter().map(|(n, d)| (n.as_slice(), *d)).collect();
|
||||
playlist::candidates(path, &entries)
|
||||
}
|
||||
787
crates/tunal/src/folder/mod.rs
Normal file
787
crates/tunal/src/folder/mod.rs
Normal file
|
|
@ -0,0 +1,787 @@
|
|||
//! The folder model behind the details view: entries from the location layer (loaded and
|
||||
//! watched off the UI thread), sorted, grouped and filtered into rows, plus the selection.
|
||||
|
||||
mod format;
|
||||
mod load;
|
||||
mod sort;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use slint::{ComponentHandle, Model, ModelNotify, ModelRc, ModelTracker, SharedString, VecModel};
|
||||
use tunal_core::playlist::Playlist;
|
||||
use tunal_core::{Entry, Error, Locations, Uri, Watch};
|
||||
|
||||
use crate::icons::{self, Category};
|
||||
use crate::{
|
||||
DetailRow, FolderState, FolderStatus, Grouping, MainWindow, MenuEntry, MenuItem, NavKey,
|
||||
SortColumn,
|
||||
};
|
||||
use load::{Change, Deliver, Msg};
|
||||
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 }
|
||||
}
|
||||
}
|
||||
|
||||
enum Row {
|
||||
Header(&'static str),
|
||||
Item(usize),
|
||||
}
|
||||
|
||||
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>,
|
||||
}
|
||||
|
||||
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>,
|
||||
}
|
||||
|
||||
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::default(),
|
||||
playlists: Vec::new(),
|
||||
playlist_path: None,
|
||||
selected: HashSet::new(),
|
||||
cursor: None,
|
||||
anchor: None,
|
||||
watches: Vec::new(),
|
||||
}),
|
||||
notify: ModelNotify::default(),
|
||||
locations,
|
||||
deliver,
|
||||
changed: RefCell::new(Box::new(|_| {})),
|
||||
})
|
||||
}
|
||||
|
||||
/// Shows `dir`: listing and watching run on a worker thread.
|
||||
pub fn open(&self, dir: Uri) {
|
||||
let generation = self.reset_to(dir.clone());
|
||||
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.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;
|
||||
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);
|
||||
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)));
|
||||
});
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- view settings ----------------------------------------------------------------
|
||||
|
||||
fn update(&self, f: impl FnOnce(&mut Settings)) {
|
||||
let mut s = self.state.borrow_mut();
|
||||
f(&mut s.settings);
|
||||
rebuild(&mut s);
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
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(_) => 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());
|
||||
}
|
||||
|
||||
/// Keyboard move of the cursor; `page` is rows per page. Returns the cursor row (or -1).
|
||||
pub fn navigate(&self, key: NavKey, shift: bool, page: usize) -> i32 {
|
||||
let target = {
|
||||
let s = self.state.borrow();
|
||||
let items: Vec<usize> = (0..s.rows.len())
|
||||
.filter(|&r| matches!(s.rows[r], Row::Item(_)))
|
||||
.collect();
|
||||
if items.is_empty() {
|
||||
return -1;
|
||||
}
|
||||
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() - 1;
|
||||
let page = page.max(1);
|
||||
let to = match (key, current) {
|
||||
(NavKey::Up | NavKey::End, None) => last,
|
||||
(_, None) => 0,
|
||||
(NavKey::Up, Some(c)) => c.saturating_sub(1),
|
||||
(NavKey::Down, 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),
|
||||
};
|
||||
items[to]
|
||||
};
|
||||
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);
|
||||
});
|
||||
target as i32
|
||||
}
|
||||
|
||||
/// Enter or double-click: opens the folder at `row` (the cursor row when `None`).
|
||||
pub fn activate(&self, row: Option<usize>) {
|
||||
let target = {
|
||||
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)) if s.items[*i].is_dir => {
|
||||
s.dir.as_ref().map(|d| d.join(&s.items[*i].entry.name))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if let Some(dir) = target {
|
||||
self.open(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
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.row_of = rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(r, row)| match row {
|
||||
Row::Item(i) => Some((s.items[*i].entry.name.clone(), r)),
|
||||
Row::Header(_) => None,
|
||||
})
|
||||
.collect();
|
||||
s.rows = rows;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
let s = self.state.borrow();
|
||||
Some(match s.rows.get(row)? {
|
||||
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),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn model_tracker(&self) -> &dyn ModelTracker {
|
||||
&self.notify
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects a folder model to the window: rows, state, sort menu and every view callback.
|
||||
pub fn attach(ui: &MainWindow, locations: Locations) -> Rc<FolderModel> {
|
||||
let weak = ui.as_weak();
|
||||
let deliver: Deliver = Arc::new(move |msg| {
|
||||
let _ = weak.upgrade_in_event_loop(move |ui| {
|
||||
if let Some(model) = ui.get_rows().as_any().downcast_ref::<FolderModel>() {
|
||||
model.apply(msg);
|
||||
}
|
||||
});
|
||||
});
|
||||
let model = FolderModel::new(locations, deliver);
|
||||
ui.set_rows(ModelRc::from(model.clone()));
|
||||
|
||||
let weak = ui.as_weak();
|
||||
model.on_changed(move |model| {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.set_folder(model.state());
|
||||
ui.set_sort_menu(ModelRc::new(VecModel::from(model.sort_menu())));
|
||||
}
|
||||
});
|
||||
|
||||
let m = Rc::downgrade(&model);
|
||||
let with = move |f: &dyn Fn(&FolderModel)| {
|
||||
if let Some(model) = m.upgrade() {
|
||||
f(&model);
|
||||
}
|
||||
};
|
||||
let w = with.clone();
|
||||
ui.on_sort_by(move |column| w(&|m| m.sort_column(column)));
|
||||
let w = with.clone();
|
||||
ui.on_filter_typed(move |text| w(&|m| m.type_filter(&text)));
|
||||
let w = with.clone();
|
||||
ui.on_filter_edited(move |text| w(&|m| m.set_filter(&text)));
|
||||
let w = with.clone();
|
||||
ui.on_toggle_hidden(move || w(&|m| m.toggle_hidden()));
|
||||
let w = with.clone();
|
||||
ui.on_row_clicked(move |row, ctrl, shift| w(&|m| m.click(row.max(0) as usize, ctrl, shift)));
|
||||
let w = with.clone();
|
||||
ui.on_row_activated(move |row| w(&|m| m.activate(usize::try_from(row).ok())));
|
||||
let w = with.clone();
|
||||
ui.on_select_all(move || w(&|m| m.select_all()));
|
||||
let w = with.clone();
|
||||
ui.on_clear_selection(move || w(&|m| m.clear_selection()));
|
||||
let m = Rc::downgrade(&model);
|
||||
ui.on_navigate(move |key, shift, page| {
|
||||
m.upgrade()
|
||||
.map_or(-1, |m| m.navigate(key, shift, page.max(1) as usize))
|
||||
});
|
||||
model.emit();
|
||||
model
|
||||
}
|
||||
204
crates/tunal/src/folder/sort.rs
Normal file
204
crates/tunal/src/folder/sort.rs
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
//! Row order: natural name compare, sort keys, group buckets.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tunal_core::playlist::Ranks;
|
||||
|
||||
use super::Item;
|
||||
use crate::icons::Category;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SortKey {
|
||||
Name,
|
||||
Size,
|
||||
Type,
|
||||
Modified,
|
||||
/// Index into the folder's playlists.
|
||||
Playlist(usize),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GroupBy {
|
||||
None,
|
||||
Type,
|
||||
Modified,
|
||||
Size,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Settings {
|
||||
pub key: SortKey,
|
||||
pub descending: bool,
|
||||
pub folders_first: bool,
|
||||
pub group: GroupBy,
|
||||
pub show_hidden: bool,
|
||||
pub filter: String,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
key: SortKey::Name,
|
||||
descending: false,
|
||||
folders_first: true,
|
||||
group: GroupBy::None,
|
||||
show_hidden: false,
|
||||
filter: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares lower-cased names with digit runs as numbers: `file2` < `file10`.
|
||||
pub fn natural_cmp(a: &str, b: &str) -> Ordering {
|
||||
let (mut a, mut b) = (a, b);
|
||||
loop {
|
||||
match (a.chars().next(), b.chars().next()) {
|
||||
(None, None) => return Ordering::Equal,
|
||||
(None, _) => return Ordering::Less,
|
||||
(_, None) => return Ordering::Greater,
|
||||
(Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
|
||||
let (da, ra) = split_digits(a);
|
||||
let (db, rb) = split_digits(b);
|
||||
let (ta, tb) = (da.trim_start_matches('0'), db.trim_start_matches('0'));
|
||||
let order = ta
|
||||
.len()
|
||||
.cmp(&tb.len())
|
||||
.then_with(|| ta.cmp(tb))
|
||||
// Same value: fewer leading zeros first.
|
||||
.then_with(|| da.len().cmp(&db.len()));
|
||||
if order != Ordering::Equal {
|
||||
return order;
|
||||
}
|
||||
(a, b) = (ra, rb);
|
||||
}
|
||||
(Some(x), Some(y)) => {
|
||||
if x != y {
|
||||
return x.cmp(&y);
|
||||
}
|
||||
(a, b) = (&a[x.len_utf8()..], &b[y.len_utf8()..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn split_digits(s: &str) -> (&str, &str) {
|
||||
s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()))
|
||||
}
|
||||
|
||||
/// Natural order, then the exact names so the order is total.
|
||||
pub fn name_cmp(a: &Item, b: &Item) -> Ordering {
|
||||
natural_cmp(&a.key, &b.key)
|
||||
.then_with(|| a.entry.display_name.cmp(&b.entry.display_name))
|
||||
.then_with(|| a.entry.name.cmp(&b.entry.name))
|
||||
}
|
||||
|
||||
/// Order of two items under `settings` (without groups). `ranks` is the playlist in use.
|
||||
pub fn compare(a: &Item, b: &Item, settings: &Settings, ranks: Option<&Ranks>) -> Ordering {
|
||||
if let SortKey::Playlist(_) = settings.key {
|
||||
let rank = |i: &Item| ranks.and_then(|r| r.rank(&i.entry.name, i.is_dir));
|
||||
// Listed first in playlist order, the rest by name; descending reverses it all.
|
||||
let order = match (rank(a), rank(b)) {
|
||||
(Some(x), Some(y)) => x.cmp(&y).then_with(|| name_cmp(a, b)),
|
||||
(Some(_), None) => Ordering::Less,
|
||||
(None, Some(_)) => Ordering::Greater,
|
||||
(None, None) => name_cmp(a, b),
|
||||
};
|
||||
return if settings.descending {
|
||||
order.reverse()
|
||||
} else {
|
||||
order
|
||||
};
|
||||
}
|
||||
if settings.folders_first && a.is_dir != b.is_dir {
|
||||
return b.is_dir.cmp(&a.is_dir);
|
||||
}
|
||||
let order = match settings.key {
|
||||
SortKey::Size => a.size().cmp(&b.size()),
|
||||
SortKey::Type => a
|
||||
.category
|
||||
.cmp(&b.category)
|
||||
.then_with(|| a.entry.mime.cmp(b.entry.mime)),
|
||||
SortKey::Modified => a.entry.mtime.cmp(&b.entry.mtime),
|
||||
SortKey::Name | SortKey::Playlist(_) => Ordering::Equal,
|
||||
}
|
||||
.then_with(|| name_cmp(a, b));
|
||||
if settings.descending {
|
||||
order.reverse()
|
||||
} else {
|
||||
order
|
||||
}
|
||||
}
|
||||
|
||||
/// Start of today, yesterday, this week, this month and this year in local time.
|
||||
pub struct Calendar {
|
||||
starts: [SystemTime; 5],
|
||||
}
|
||||
|
||||
impl Calendar {
|
||||
pub fn now() -> Self {
|
||||
let now = jiff::Zoned::now();
|
||||
let day = now.start_of_day().unwrap_or_else(|_| now.clone());
|
||||
let back = |days: i64| {
|
||||
day.checked_sub(jiff::Span::new().days(days))
|
||||
.unwrap_or_else(|_| day.clone())
|
||||
};
|
||||
let week = back(i64::from(day.weekday().to_monday_zero_offset()));
|
||||
let month = back(i64::from(day.day()) - 1);
|
||||
let year = back(i64::from(day.day_of_year()) - 1);
|
||||
let to_system = |z: &jiff::Zoned| {
|
||||
let secs = z.timestamp().as_second();
|
||||
UNIX_EPOCH + Duration::from_secs(secs.max(0) as u64)
|
||||
};
|
||||
Self {
|
||||
starts: [&day, &back(1), &week, &month, &year].map(to_system),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bucket of a modification time: 0 today … 5 older, 6 unknown.
|
||||
fn bucket(&self, mtime: Option<SystemTime>) -> u8 {
|
||||
match mtime {
|
||||
None => 6,
|
||||
Some(t) => self.starts.iter().position(|s| t >= *s).unwrap_or(5) as u8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DATE_GROUPS: [&str; 7] = [
|
||||
"Today",
|
||||
"Yesterday",
|
||||
"Earlier this week",
|
||||
"Earlier this month",
|
||||
"Earlier this year",
|
||||
"Older",
|
||||
"Unknown date",
|
||||
];
|
||||
|
||||
const SIZE_GROUPS: [(u64, &str); 6] = [
|
||||
(1, "Empty"),
|
||||
(16 << 10, "Tiny (under 16 KiB)"),
|
||||
(1 << 20, "Small (under 1 MiB)"),
|
||||
(128 << 20, "Medium (under 128 MiB)"),
|
||||
(1 << 30, "Large (under 1 GiB)"),
|
||||
(u64::MAX, "Huge (1 GiB and more)"),
|
||||
];
|
||||
|
||||
/// Group of an item as (rank, label); groups show in rank order.
|
||||
pub fn group(item: &Item, group: GroupBy, calendar: &Calendar) -> (u8, &'static str) {
|
||||
match group {
|
||||
GroupBy::None => (0, ""),
|
||||
GroupBy::Type => (item.category as u8, item.category.group_label()),
|
||||
GroupBy::Modified => {
|
||||
let b = calendar.bucket(item.entry.mtime);
|
||||
(b, DATE_GROUPS[b as usize])
|
||||
}
|
||||
GroupBy::Size if item.category == Category::Folder => (0, "Folders"),
|
||||
GroupBy::Size => {
|
||||
let i = SIZE_GROUPS
|
||||
.iter()
|
||||
.position(|(limit, _)| item.entry.size < *limit)
|
||||
.unwrap_or(SIZE_GROUPS.len() - 1);
|
||||
(i as u8 + 1, SIZE_GROUPS[i].1)
|
||||
}
|
||||
}
|
||||
}
|
||||
173
crates/tunal/src/icons.rs
Normal file
173
crates/tunal/src/icons.rs
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
//! MIME type → kind of file, its Material Symbols glyph and its type label.
|
||||
|
||||
use tunal_core::{Entry, Kind, mime};
|
||||
|
||||
/// What a file is, coarse enough for an icon, a type group and a type label.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Category {
|
||||
Folder,
|
||||
Image,
|
||||
Audio,
|
||||
Video,
|
||||
Text,
|
||||
Code,
|
||||
Pdf,
|
||||
Archive,
|
||||
Executable,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Category {
|
||||
pub fn of(entry: &Entry) -> Self {
|
||||
if entry.kind.is_dir() {
|
||||
return Self::Folder;
|
||||
}
|
||||
let m = entry.mime;
|
||||
let (top, sub) = m.split_once('/').unwrap_or((m, ""));
|
||||
let sub = sub.strip_prefix("x-").unwrap_or(sub);
|
||||
match top {
|
||||
"image" => Self::Image,
|
||||
"audio" => Self::Audio,
|
||||
"video" => Self::Video,
|
||||
_ if sub == "pdf" => Self::Pdf,
|
||||
_ if ARCHIVES.contains(&sub) => Self::Archive,
|
||||
_ if EXECUTABLES.contains(&sub) => Self::Executable,
|
||||
_ if CODE.contains(&sub) => Self::Code,
|
||||
"text" if sub == "plain" || sub == "markdown" => Self::Text,
|
||||
"text" => Self::Code,
|
||||
// No extension, but the execute bit is set: a program or script.
|
||||
_ if m == mime::UNKNOWN && entry.kind == Kind::File && entry.mode & 0o111 != 0 => {
|
||||
Self::Executable
|
||||
}
|
||||
_ => Self::Other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Codepoint of the Material Symbols Rounded glyph.
|
||||
pub fn glyph(self) -> &'static str {
|
||||
match self {
|
||||
Self::Folder => "\u{e2c7}",
|
||||
Self::Image => "\u{e3f4}",
|
||||
Self::Audio => "\u{eb82}",
|
||||
Self::Video => "\u{eb87}",
|
||||
Self::Text => "\u{e873}",
|
||||
Self::Code => "\u{e86f}",
|
||||
Self::Pdf => "\u{e415}",
|
||||
Self::Archive => "\u{eb2c}",
|
||||
Self::Executable => "\u{eb8e}",
|
||||
Self::Other => "\u{e66d}",
|
||||
}
|
||||
}
|
||||
|
||||
/// Header of the type group.
|
||||
pub fn group_label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Folder => "Folders",
|
||||
Self::Image => "Images",
|
||||
Self::Audio => "Audio",
|
||||
Self::Video => "Videos",
|
||||
Self::Text => "Text",
|
||||
Self::Code => "Code",
|
||||
Self::Pdf => "PDF documents",
|
||||
Self::Archive => "Archives",
|
||||
Self::Executable => "Programs",
|
||||
Self::Other => "Other",
|
||||
}
|
||||
}
|
||||
|
||||
fn noun(self) -> &'static str {
|
||||
match self {
|
||||
Self::Folder => "folder",
|
||||
Self::Image => "image",
|
||||
Self::Audio => "audio",
|
||||
Self::Video => "video",
|
||||
Self::Text => "text",
|
||||
Self::Code => "source",
|
||||
Self::Pdf => "document",
|
||||
Self::Archive => "archive",
|
||||
Self::Executable => "program",
|
||||
Self::Other => "file",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Badge drawn over the glyph of a symlink: a link, or a broken link.
|
||||
pub fn link_badge(kind: &Kind) -> &'static str {
|
||||
match kind {
|
||||
Kind::Symlink {
|
||||
target_type: None, ..
|
||||
} => "\u{e16f}",
|
||||
Kind::Symlink { .. } => "\u{e157}",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Type column text: "Folder", "PNG image", "Broken link", or the plain noun.
|
||||
pub fn type_label(entry: &Entry, category: Category) -> String {
|
||||
if matches!(
|
||||
entry.kind,
|
||||
Kind::Symlink {
|
||||
target_type: None,
|
||||
..
|
||||
}
|
||||
) {
|
||||
return "Broken link".into();
|
||||
}
|
||||
if category == Category::Folder {
|
||||
return "Folder".into();
|
||||
}
|
||||
let ext = entry
|
||||
.display_name
|
||||
.rsplit_once('.')
|
||||
.filter(|(stem, ext)| !stem.is_empty() && !ext.is_empty() && ext.len() <= 5)
|
||||
.map(|(_, ext)| ext.to_uppercase());
|
||||
match ext {
|
||||
Some(ext) => format!("{ext} {}", category.noun()),
|
||||
None => {
|
||||
let noun = category.noun();
|
||||
noun[..1].to_uppercase() + &noun[1..]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ARCHIVES: [&str; 14] = [
|
||||
"zip",
|
||||
"tar",
|
||||
"gtar",
|
||||
"gzip",
|
||||
"bzip2",
|
||||
"xz",
|
||||
"zstd",
|
||||
"7z-compressed",
|
||||
"rar-compressed",
|
||||
"vnd.rar",
|
||||
"rar",
|
||||
"java-archive",
|
||||
"compressed",
|
||||
"lzma",
|
||||
];
|
||||
|
||||
const EXECUTABLES: [&str; 6] = [
|
||||
"executable",
|
||||
"msdownload",
|
||||
"sharedlib",
|
||||
"vnd.appimage",
|
||||
"elf",
|
||||
"vnd.microsoft.portable-executable",
|
||||
];
|
||||
|
||||
const CODE: [&str; 13] = [
|
||||
"javascript",
|
||||
"typescript",
|
||||
"json",
|
||||
"xml",
|
||||
"sh",
|
||||
"shellscript",
|
||||
"toml",
|
||||
"yaml",
|
||||
"python",
|
||||
"rust",
|
||||
"csrc",
|
||||
"c++src",
|
||||
"sql",
|
||||
];
|
||||
|
|
@ -1,19 +1,27 @@
|
|||
mod folder;
|
||||
mod icons;
|
||||
mod screenshot;
|
||||
mod theme_bridge;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use tunal_core::{Locations, Uri};
|
||||
|
||||
slint::include_modules!();
|
||||
|
||||
const USAGE: &str =
|
||||
"usage: tunal [--gallery [--page menu|dialog]] [--screenshot <png> [--dark] [--size WxH]]";
|
||||
const USAGE: &str = "usage: tunal [<folder>] [--gallery [--page menu|dialog]] \
|
||||
[--screenshot <png> [--dark] [--size WxH]]";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let result = parse(std::env::args().skip(1)).and_then(|args| match args.screenshot {
|
||||
None if args.gallery => gallery(args.page).and_then(run).map_err(|e| e.to_string()),
|
||||
None => MainWindow::new().and_then(run).map_err(|e| e.to_string()),
|
||||
None => window(args.dir, false)
|
||||
.and_then(run)
|
||||
.map_err(|e| e.to_string()),
|
||||
Some(options) if args.gallery => screenshot::run(options, || gallery(args.page)),
|
||||
Some(options) => screenshot::run(options, MainWindow::new),
|
||||
// A screenshot is one frame: list the folder before it is drawn.
|
||||
Some(options) => screenshot::run(options, || window(args.dir, true)),
|
||||
});
|
||||
match result {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
|
|
@ -24,6 +32,27 @@ fn main() -> ExitCode {
|
|||
}
|
||||
}
|
||||
|
||||
/// The main window, showing `dir` if given (temporary until places and navigation land).
|
||||
fn window(dir: Option<PathBuf>, blocking: bool) -> Result<MainWindow, slint::PlatformError> {
|
||||
let ui = MainWindow::new()?;
|
||||
let model = folder::attach(&ui, Locations::with_local());
|
||||
let m = std::rc::Rc::downgrade(&model);
|
||||
ui.on_sort_menu_activated(move |index, sub| {
|
||||
if let Some(m) = m.upgrade() {
|
||||
m.sort_menu_activated(index.max(0) as usize, sub);
|
||||
}
|
||||
});
|
||||
if let Some(dir) = dir {
|
||||
let uri = Uri::from_path(&dir);
|
||||
if blocking {
|
||||
model.open_blocking(uri);
|
||||
} else {
|
||||
model.open(uri);
|
||||
}
|
||||
}
|
||||
Ok(ui)
|
||||
}
|
||||
|
||||
fn gallery(page: GalleryPage) -> Result<Gallery, slint::PlatformError> {
|
||||
let ui = Gallery::new()?;
|
||||
ui.set_page(page);
|
||||
|
|
@ -37,12 +66,14 @@ fn run(ui: impl theme_bridge::Themed) -> Result<(), slint::PlatformError> {
|
|||
}
|
||||
|
||||
struct Args {
|
||||
dir: Option<PathBuf>,
|
||||
gallery: bool,
|
||||
page: GalleryPage,
|
||||
screenshot: Option<screenshot::Options>,
|
||||
}
|
||||
|
||||
fn parse(mut args: impl Iterator<Item = String>) -> Result<Args, String> {
|
||||
let mut dir = None;
|
||||
let mut gallery = false;
|
||||
let mut page = GalleryPage::Controls;
|
||||
let mut options = screenshot::Options {
|
||||
|
|
@ -77,6 +108,7 @@ fn parse(mut args: impl Iterator<Item = String>) -> Result<Args, String> {
|
|||
options.size = (parse(w)?, parse(h)?);
|
||||
screenshot_flags = true;
|
||||
}
|
||||
_ if !arg.starts_with('-') && dir.is_none() => dir = Some(PathBuf::from(arg)),
|
||||
_ => return Err(USAGE.into()),
|
||||
}
|
||||
}
|
||||
|
|
@ -85,6 +117,7 @@ fn parse(mut args: impl Iterator<Item = String>) -> Result<Args, String> {
|
|||
}
|
||||
if !screenshot_flags {
|
||||
return Ok(Args {
|
||||
dir,
|
||||
gallery,
|
||||
page,
|
||||
screenshot: None,
|
||||
|
|
@ -95,6 +128,7 @@ fn parse(mut args: impl Iterator<Item = String>) -> Result<Args, String> {
|
|||
}
|
||||
options.reduced_motion = gallery;
|
||||
Ok(Args {
|
||||
dir,
|
||||
gallery,
|
||||
page,
|
||||
screenshot: Some(options),
|
||||
|
|
|
|||
|
|
@ -2,8 +2,10 @@ import "../../../assets/fonts/MaterialSymbolsRounded[FILL,GRAD,opsz,wght].ttf";
|
|||
import { Theme } from "theme.slint";
|
||||
import { Motion, MotionPrefs } from "motion.slint";
|
||||
import { Icon, Icons } from "components/icon.slint";
|
||||
import { Menu, MenuItem, MenuEntry } from "components/menu.slint";
|
||||
import { DetailsView, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn } from "views/details-view.slint";
|
||||
|
||||
export { Theme, MotionPrefs }
|
||||
export { Theme, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn }
|
||||
export { Gallery, GalleryPage } from "gallery.slint";
|
||||
|
||||
// Placeholder shell (sidebar + content) until the views land.
|
||||
|
|
@ -17,6 +19,21 @@ export component MainWindow inherits Window {
|
|||
background: Theme.surface;
|
||||
animate background { duration: Motion.time(Motion.medium2); easing: Motion.standard; }
|
||||
|
||||
// The open folder (FolderModel in Rust).
|
||||
in property <[DetailRow]> rows;
|
||||
in property <FolderState> folder;
|
||||
in property <[MenuItem]> sort-menu;
|
||||
callback sort-by <=> details.sort-by;
|
||||
callback filter-typed <=> details.filter-typed;
|
||||
callback filter-edited <=> details.filter-edited;
|
||||
callback toggle-hidden <=> details.toggle-hidden;
|
||||
callback row-clicked <=> details.row-clicked;
|
||||
callback row-activated <=> details.row-activated;
|
||||
callback select-all <=> details.select-all;
|
||||
callback clear-selection <=> details.clear-selection;
|
||||
callback navigate <=> details.navigate;
|
||||
callback sort-menu-activated(int, int);
|
||||
|
||||
HorizontalLayout {
|
||||
sidebar := Rectangle {
|
||||
width: 240px;
|
||||
|
|
@ -50,35 +67,65 @@ export component MainWindow inherits Window {
|
|||
}
|
||||
}
|
||||
|
||||
// The details view stays built (its callbacks are bound above); the placeholder covers
|
||||
// it until a folder is open.
|
||||
Rectangle {
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
spacing: Theme.space-2;
|
||||
details := DetailsView {
|
||||
rows: root.rows;
|
||||
state: root.folder;
|
||||
open-sort-menu(x, y) => {
|
||||
sort-popup.open-at(x, y);
|
||||
}
|
||||
init => {
|
||||
self.focus-view();
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
if !root.folder.open: Rectangle {
|
||||
background: Theme.surface;
|
||||
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
Icon {
|
||||
glyph: Icons.folder;
|
||||
size: 48px;
|
||||
spacing: Theme.space-2;
|
||||
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
Icon {
|
||||
glyph: Icons.folder;
|
||||
size: 48px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
text: "No folder open";
|
||||
color: Theme.on-surface;
|
||||
font-size: Theme.title-medium.size;
|
||||
font-weight: Theme.title-medium.weight;
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
Text {
|
||||
text: "No folder open";
|
||||
color: Theme.on-surface;
|
||||
font-size: Theme.title-medium.size;
|
||||
font-weight: Theme.title-medium.weight;
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
|
||||
Text {
|
||||
text: "Folders you open appear here";
|
||||
color: Theme.on-surface-variant;
|
||||
font-size: Theme.body-medium.size;
|
||||
font-weight: Theme.body-medium.weight;
|
||||
horizontal-alignment: center;
|
||||
Text {
|
||||
text: "Folders you open appear here";
|
||||
color: Theme.on-surface-variant;
|
||||
font-size: Theme.body-medium.size;
|
||||
font-weight: Theme.body-medium.weight;
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort-popup := Menu {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
items: root.sort-menu;
|
||||
leading-icons: true;
|
||||
activated(index, sub) => {
|
||||
root.sort-menu-activated(index, sub);
|
||||
}
|
||||
closed => {
|
||||
details.focus-view();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,4 +41,7 @@ export global Icons {
|
|||
out property <string> open-in-new: "\u{e89e}";
|
||||
out property <string> sort: "\u{e164}";
|
||||
out property <string> info: "\u{e88e}";
|
||||
out property <string> arrow-upward: "\u{e5d8}";
|
||||
out property <string> arrow-downward: "\u{e5db}";
|
||||
out property <string> error: "\u{e000}";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ import { StateLayer } from "state-layer.slint";
|
|||
export component ListRow inherits StateLayer {
|
||||
// Glyph from `Icons`; empty for none.
|
||||
in property <string> icon;
|
||||
// Small glyph over the icon's corner (a link); empty for none.
|
||||
in property <string> badge;
|
||||
in property <string> title;
|
||||
in property <string> supporting;
|
||||
in property <bool> selected;
|
||||
|
|
@ -53,9 +55,22 @@ export component ListRow inherits StateLayer {
|
|||
if root.icon != "": VerticalLayout {
|
||||
alignment: center;
|
||||
|
||||
Icon {
|
||||
glyph: root.icon;
|
||||
color: root.detail-color;
|
||||
Rectangle {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
|
||||
Icon {
|
||||
glyph: root.icon;
|
||||
color: root.detail-color;
|
||||
}
|
||||
|
||||
if root.badge != "": Icon {
|
||||
x: parent.width - self.width + Theme.space-1;
|
||||
y: parent.height - self.height + Theme.space-1;
|
||||
glyph: root.badge;
|
||||
size: 14px;
|
||||
color: root.selected ? Theme.on-secondary-container : Theme.primary;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -21,6 +21,8 @@ export component StateLayer inherits Rectangle {
|
|||
// Gap between shape and focus ring; `-Theme.focus-ring-width` draws the ring inside the
|
||||
// shape, for controls stacked edge to edge (rows, tabs).
|
||||
in property <length> ring-offset: Theme.focus-ring-offset;
|
||||
// Off for rows of a list that owns the keyboard itself: no Tab stop per row.
|
||||
in property <bool> focusable: true;
|
||||
|
||||
out property <bool> hovered: enabled && (touch.has-hover || force-state == ForceState.hover);
|
||||
out property <bool> pressed: enabled && (touch.pressed || force-state == ForceState.pressed);
|
||||
|
|
@ -31,6 +33,9 @@ export component StateLayer inherits Rectangle {
|
|||
callback clicked;
|
||||
// For the control itself (toggle its own state), called before `clicked`.
|
||||
callback activated;
|
||||
callback double-clicked;
|
||||
// Keys held at the last pointer press, for Ctrl/Shift clicks.
|
||||
out property <KeyboardModifiers> modifiers;
|
||||
|
||||
property <bool> keyboard-focus;
|
||||
property <length> ring-inset: Theme.focus-ring-width + root.ring-offset;
|
||||
|
|
@ -63,7 +68,7 @@ export component StateLayer inherits Rectangle {
|
|||
keys := FocusScope {
|
||||
x: 0;
|
||||
width: 0;
|
||||
enabled: root.enabled;
|
||||
enabled: root.enabled && root.focusable;
|
||||
focus-on-click: false;
|
||||
|
||||
// Only keyboard focus shows the ring.
|
||||
|
|
@ -87,6 +92,14 @@ export component StateLayer inherits Rectangle {
|
|||
clicked => {
|
||||
root.activate();
|
||||
}
|
||||
double-clicked => {
|
||||
root.double-clicked();
|
||||
}
|
||||
pointer-event(event) => {
|
||||
if event.kind == PointerEventKind.down {
|
||||
root.modifiers = event.modifiers;
|
||||
}
|
||||
}
|
||||
changed has-hover => {
|
||||
if !self.has-hover {
|
||||
root.tip-due = false;
|
||||
|
|
|
|||
511
crates/tunal/ui/views/details-view.slint
Normal file
511
crates/tunal/ui/views/details-view.slint
Normal file
|
|
@ -0,0 +1,511 @@
|
|||
import { ListView } from "std-widgets.slint";
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Motion } from "../motion.slint";
|
||||
import { Icon, Icons } from "../components/icon.slint";
|
||||
import { ForceState, StateLayer } from "../components/state-layer.slint";
|
||||
import { ListRow } from "../components/list-row.slint";
|
||||
import { IconButton } from "../components/icon-button.slint";
|
||||
import { Chip, ChipKind } from "../components/chip.slint";
|
||||
|
||||
export enum SortColumn { name, size, type, modified, playlist }
|
||||
export enum Grouping { none, type, modified, size }
|
||||
export enum FolderStatus { loading, ready, error }
|
||||
export enum NavKey { up, down, home, end, page-up, page-down }
|
||||
|
||||
// One row of the details list: a group header (only `name` set) or an entry.
|
||||
export struct DetailRow {
|
||||
header: bool,
|
||||
name: string,
|
||||
glyph: string,
|
||||
badge: string,
|
||||
size: string,
|
||||
kind: string,
|
||||
modified: string,
|
||||
selected: bool,
|
||||
cursor: bool,
|
||||
}
|
||||
|
||||
// What the view shows around the rows, set from Rust.
|
||||
export struct FolderState {
|
||||
open: bool,
|
||||
status: FolderStatus,
|
||||
error: string,
|
||||
sort: SortColumn,
|
||||
// Index of the playlist in use when `sort` is `playlist`, else -1.
|
||||
playlist: int,
|
||||
descending: bool,
|
||||
group: Grouping,
|
||||
filter: string,
|
||||
// Entries shown, and entries left out because hidden files are off.
|
||||
items: int,
|
||||
hidden: int,
|
||||
}
|
||||
|
||||
// Column widths shared by the header and the rows.
|
||||
global Columns {
|
||||
out property <length> size: 88px;
|
||||
out property <length> kind: 128px;
|
||||
out property <length> modified: 144px;
|
||||
// The trailing slot under the header's sort button.
|
||||
out property <length> tools: 32px;
|
||||
out property <length> row-height: 40px;
|
||||
out property <length> header-height: 34px;
|
||||
out property <length> inset: Theme.space-2;
|
||||
}
|
||||
|
||||
// Up and down arrows cross-fade and slide past each other when the direction flips.
|
||||
component Arrow inherits Rectangle {
|
||||
in property <bool> active;
|
||||
in property <bool> descending;
|
||||
property <length> shift: Theme.space-1;
|
||||
|
||||
Icon {
|
||||
glyph: Icons.arrow-upward;
|
||||
size: 16px;
|
||||
color: Theme.primary;
|
||||
y: (parent.height - self.height) / 2 + (root.active && !root.descending ? 0 : root.shift);
|
||||
opacity: root.active && !root.descending ? 1 : 0;
|
||||
animate y, opacity { duration: Motion.time(Motion.short4); easing: Motion.emphasized-decelerate; }
|
||||
}
|
||||
|
||||
Icon {
|
||||
glyph: Icons.arrow-downward;
|
||||
size: 16px;
|
||||
color: Theme.primary;
|
||||
y: (parent.height - self.height) / 2 - (root.active && root.descending ? 0 : root.shift);
|
||||
opacity: root.active && root.descending ? 1 : 0;
|
||||
animate y, opacity { duration: Motion.time(Motion.short4); easing: Motion.emphasized-decelerate; }
|
||||
}
|
||||
}
|
||||
|
||||
// A column title: click sorts. The arrow fades in on the sorted column and slides to show
|
||||
// the direction; it sits on the side away from the text's alignment edge.
|
||||
component HeaderCell inherits StateLayer {
|
||||
in property <string> text;
|
||||
in property <bool> active;
|
||||
in property <bool> descending;
|
||||
in property <bool> end-aligned;
|
||||
|
||||
focusable: false;
|
||||
height: 28px;
|
||||
border-radius: Theme.corner-full(self.height);
|
||||
squeeze: Motion.squeeze;
|
||||
accessible-role: button;
|
||||
accessible-label: root.text;
|
||||
accessible-action-default => {
|
||||
self.activate();
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-2;
|
||||
padding-right: Theme.space-2;
|
||||
spacing: Theme.space-1;
|
||||
alignment: root.end-aligned ? end : start;
|
||||
|
||||
if root.end-aligned: Rectangle {
|
||||
width: 16px;
|
||||
Arrow {
|
||||
active: root.active;
|
||||
descending: root.descending;
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
text: root.text;
|
||||
color: root.active ? Theme.on-surface : Theme.on-surface-variant;
|
||||
font-size: Theme.label-medium.size;
|
||||
font-weight: Theme.label-medium.weight;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
animate color { duration: Motion.time(Motion.short4); easing: Motion.standard; }
|
||||
}
|
||||
|
||||
if !root.end-aligned: Rectangle {
|
||||
width: 16px;
|
||||
Arrow {
|
||||
active: root.active;
|
||||
descending: root.descending;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A header cell centred in a fixed-width column.
|
||||
component HeaderColumn inherits VerticalLayout {
|
||||
in property <string> text;
|
||||
in property <bool> active;
|
||||
in property <bool> descending;
|
||||
in property <bool> end-aligned;
|
||||
callback clicked;
|
||||
|
||||
alignment: center;
|
||||
|
||||
HeaderCell {
|
||||
text: root.text;
|
||||
active: root.active;
|
||||
descending: root.descending;
|
||||
end-aligned: root.end-aligned;
|
||||
clicked => {
|
||||
root.clicked();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A details column cell: fixed width, the same inner padding as its header cell.
|
||||
component Cell inherits HorizontalLayout {
|
||||
in property <string> text;
|
||||
in property <color> color;
|
||||
in property <bool> end-aligned;
|
||||
|
||||
padding-left: Theme.space-2;
|
||||
padding-right: Theme.space-2;
|
||||
|
||||
Text {
|
||||
text: root.text;
|
||||
color: root.color;
|
||||
font-size: Theme.body-small.size;
|
||||
font-weight: Theme.body-small.weight;
|
||||
horizontal-alignment: root.end-aligned ? right : left;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
|
||||
// Centred message for the loading, empty and error states.
|
||||
component Message inherits VerticalLayout {
|
||||
in property <string> glyph;
|
||||
in property <string> title;
|
||||
in property <string> body;
|
||||
|
||||
alignment: center;
|
||||
spacing: Theme.space-2;
|
||||
padding: Theme.space-6;
|
||||
|
||||
if root.glyph != "": HorizontalLayout {
|
||||
alignment: center;
|
||||
Icon {
|
||||
glyph: root.glyph;
|
||||
size: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
text: root.title;
|
||||
color: Theme.on-surface;
|
||||
font-size: Theme.title-medium.size;
|
||||
font-weight: Theme.title-medium.weight;
|
||||
horizontal-alignment: center;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
|
||||
if root.body != "": Text {
|
||||
text: root.body;
|
||||
color: Theme.on-surface-variant;
|
||||
font-size: Theme.body-medium.size;
|
||||
font-weight: Theme.body-medium.weight;
|
||||
horizontal-alignment: center;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
|
||||
// The details view of one folder: column header, filter chip, virtualized rows and the
|
||||
// loading/empty/error states. It owns the keyboard: arrows move the cursor, typing filters.
|
||||
export component DetailsView inherits Rectangle {
|
||||
in property <[DetailRow]> rows;
|
||||
in property <FolderState> state;
|
||||
|
||||
callback sort-by(SortColumn);
|
||||
// Window coordinates of the point the sort menu should open at.
|
||||
callback open-sort-menu(length, length);
|
||||
// Printable text appends to the filter, "\u{8}" removes its last character.
|
||||
callback filter-typed(string);
|
||||
callback filter-edited(string);
|
||||
callback toggle-hidden();
|
||||
callback row-clicked(int, bool, bool);
|
||||
// -1 for the cursor row.
|
||||
callback row-activated(int);
|
||||
callback select-all();
|
||||
callback clear-selection();
|
||||
// Moves the cursor; returns the new cursor row, or -1.
|
||||
callback navigate(NavKey, bool, int) -> int;
|
||||
|
||||
// Narrow views drop the Type column so names keep their room.
|
||||
property <bool> compact: root.width < 640px;
|
||||
|
||||
public function focus-view() {
|
||||
keys.focus();
|
||||
}
|
||||
|
||||
// Last non-empty filter, so the chip keeps its text while it collapses.
|
||||
property <string> chip-text;
|
||||
changed state => {
|
||||
if root.state.filter != "" {
|
||||
root.chip-text = root.state.filter;
|
||||
}
|
||||
}
|
||||
|
||||
function move(key: NavKey, shift: bool) {
|
||||
root.reveal(root.navigate(key, shift, floor(list.visible-height / Columns.row-height)));
|
||||
}
|
||||
|
||||
// Scrolls just enough to show `row`.
|
||||
function reveal(row: int) {
|
||||
if row < 0 {
|
||||
return;
|
||||
}
|
||||
let top = row * Columns.row-height;
|
||||
if top < -list.content-y {
|
||||
list.content-y = -top;
|
||||
} else if top + Columns.row-height > -list.content-y + list.visible-height {
|
||||
list.content-y = -(top + Columns.row-height - list.visible-height);
|
||||
}
|
||||
}
|
||||
|
||||
background: Theme.surface;
|
||||
forward-focus: keys;
|
||||
|
||||
keys := FocusScope {
|
||||
key-pressed(event) => {
|
||||
if event.modifiers.control && (event.text == "a" || event.text == "A") {
|
||||
root.select-all();
|
||||
return accept;
|
||||
}
|
||||
if event.modifiers.control && (event.text == "h" || event.text == "H") {
|
||||
root.toggle-hidden();
|
||||
return accept;
|
||||
}
|
||||
if event.modifiers.control || event.modifiers.alt || event.modifiers.meta {
|
||||
return reject;
|
||||
}
|
||||
if event.text == Key.UpArrow {
|
||||
root.move(NavKey.up, event.modifiers.shift);
|
||||
} else if event.text == Key.DownArrow {
|
||||
root.move(NavKey.down, event.modifiers.shift);
|
||||
} else if event.text == Key.Home {
|
||||
root.move(NavKey.home, event.modifiers.shift);
|
||||
} else if event.text == Key.End {
|
||||
root.move(NavKey.end, event.modifiers.shift);
|
||||
} else if event.text == Key.PageUp {
|
||||
root.move(NavKey.page-up, event.modifiers.shift);
|
||||
} else if event.text == Key.PageDown {
|
||||
root.move(NavKey.page-down, event.modifiers.shift);
|
||||
} else if event.text == Key.Return {
|
||||
root.row-activated(-1);
|
||||
} else if event.text == Key.Escape {
|
||||
if root.state.filter != "" {
|
||||
root.filter-edited("");
|
||||
} else {
|
||||
root.clear-selection();
|
||||
}
|
||||
} else if event.text == Key.Backspace {
|
||||
root.filter-typed("\u{8}");
|
||||
} else if event.text != "" && event.text != Key.Tab && event.text != Key.Backtab {
|
||||
root.filter-typed(event.text);
|
||||
} else {
|
||||
return reject;
|
||||
}
|
||||
accept
|
||||
}
|
||||
|
||||
VerticalLayout {
|
||||
// Column header, aligned with the row columns below. Sized to the list's visible
|
||||
// width (the rows end at the scrollbar), outside the layout so the two don't loop.
|
||||
Rectangle {
|
||||
height: Columns.header-height;
|
||||
header := HorizontalLayout {
|
||||
x: 0;
|
||||
width: list.visible-width;
|
||||
height: parent.height;
|
||||
// Row inset + ListRow padding + icon + spacing, minus the cell's own padding.
|
||||
padding-left: Columns.inset + Theme.space-4 + 24px + Theme.space-3 - Theme.space-2;
|
||||
padding-right: Columns.inset + Theme.space-2;
|
||||
spacing: Theme.space-3;
|
||||
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
HorizontalLayout {
|
||||
alignment: start;
|
||||
HeaderCell {
|
||||
text: "Name";
|
||||
active: root.state.sort == SortColumn.name;
|
||||
descending: root.state.descending;
|
||||
clicked => {
|
||||
root.sort-by(SortColumn.name);
|
||||
keys.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HeaderColumn {
|
||||
width: Columns.size;
|
||||
text: "Size";
|
||||
end-aligned: true;
|
||||
active: root.state.sort == SortColumn.size;
|
||||
descending: root.state.descending;
|
||||
clicked => {
|
||||
root.sort-by(SortColumn.size);
|
||||
keys.focus();
|
||||
}
|
||||
}
|
||||
|
||||
if !root.compact: HeaderColumn {
|
||||
width: Columns.kind;
|
||||
text: "Type";
|
||||
active: root.state.sort == SortColumn.type;
|
||||
descending: root.state.descending;
|
||||
clicked => {
|
||||
root.sort-by(SortColumn.type);
|
||||
keys.focus();
|
||||
}
|
||||
}
|
||||
|
||||
HeaderColumn {
|
||||
width: Columns.modified;
|
||||
text: "Modified";
|
||||
active: root.state.sort == SortColumn.modified;
|
||||
descending: root.state.descending;
|
||||
clicked => {
|
||||
root.sort-by(SortColumn.modified);
|
||||
keys.focus();
|
||||
}
|
||||
}
|
||||
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
width: Columns.tools;
|
||||
sort-button := IconButton {
|
||||
icon: Icons.sort;
|
||||
size: Columns.tools;
|
||||
icon-size: 20px;
|
||||
tooltip: "Sort and view options";
|
||||
clicked => {
|
||||
root.open-sort-menu(
|
||||
self.absolute-position.x + self.width,
|
||||
self.absolute-position.y + self.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
height: Theme.hairline;
|
||||
background: Theme.outline-variant;
|
||||
}
|
||||
|
||||
// Filter chip: grows in while typing, collapses when cleared.
|
||||
Rectangle {
|
||||
height: root.state.filter != "" ? 32px + 2 * Theme.space-2 : 0;
|
||||
clip: true;
|
||||
animate height { duration: Motion.time(Motion.short4); easing: Motion.emphasized-decelerate; }
|
||||
|
||||
HorizontalLayout {
|
||||
y: 0;
|
||||
height: 32px + 2 * Theme.space-2;
|
||||
padding: Theme.space-2;
|
||||
padding-left: Columns.inset + Theme.space-2;
|
||||
alignment: start;
|
||||
|
||||
Chip {
|
||||
kind: ChipKind.assist;
|
||||
icon: Icons.search;
|
||||
text: "Filter: " + root.chip-text;
|
||||
tooltip: "Clear the filter (Esc)";
|
||||
clicked => {
|
||||
root.filter-edited("");
|
||||
keys.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
vertical-stretch: 1;
|
||||
|
||||
list := ListView {
|
||||
visible: root.rows.length > 0;
|
||||
|
||||
for row[i] in root.rows: Rectangle {
|
||||
height: Columns.row-height;
|
||||
|
||||
if row.header: Text {
|
||||
x: Columns.inset + Theme.space-4;
|
||||
width: parent.width - 2 * (Columns.inset + Theme.space-4);
|
||||
height: parent.height;
|
||||
text: row.name;
|
||||
color: Theme.primary;
|
||||
font-size: Theme.label-medium.size;
|
||||
font-weight: Theme.label-medium.weight;
|
||||
vertical-alignment: bottom;
|
||||
overflow: elide;
|
||||
accessible-role: text;
|
||||
}
|
||||
|
||||
if !row.header: ListRow {
|
||||
x: Columns.inset;
|
||||
width: parent.width - 2 * Columns.inset;
|
||||
focusable: false;
|
||||
icon: row.glyph;
|
||||
badge: row.badge;
|
||||
title: row.name;
|
||||
selected: row.selected;
|
||||
force-state: row.cursor && keys.has-focus ? ForceState.focused : ForceState.none;
|
||||
clicked => {
|
||||
keys.focus();
|
||||
root.row-clicked(i, self.modifiers.control, self.modifiers.shift);
|
||||
}
|
||||
double-clicked => {
|
||||
root.row-activated(i);
|
||||
}
|
||||
|
||||
Cell {
|
||||
width: Columns.size;
|
||||
text: row.size;
|
||||
end-aligned: true;
|
||||
color: row.selected ? Theme.on-secondary-container : Theme.on-surface-variant;
|
||||
}
|
||||
|
||||
if !root.compact: Cell {
|
||||
width: Columns.kind;
|
||||
text: row.kind;
|
||||
color: row.selected ? Theme.on-secondary-container : Theme.on-surface-variant;
|
||||
}
|
||||
|
||||
Cell {
|
||||
width: Columns.modified;
|
||||
text: row.modified;
|
||||
color: row.selected ? Theme.on-secondary-container : Theme.on-surface-variant;
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
width: Columns.tools;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if root.state.status == FolderStatus.error: Message {
|
||||
glyph: Icons.error;
|
||||
title: "Can't open this folder";
|
||||
body: root.state.error;
|
||||
}
|
||||
|
||||
if root.state.status == FolderStatus.loading && root.rows.length == 0: Message {
|
||||
title: "Loading…";
|
||||
}
|
||||
|
||||
if root.state.status == FolderStatus.ready && root.state.items == 0: Message {
|
||||
glyph: Icons.folder;
|
||||
title: root.state.filter != "" ? "Nothing matches “" + root.state.filter + "”"
|
||||
: root.state.hidden > 0 ? "Only hidden items here"
|
||||
: "This folder is empty";
|
||||
body: root.state.filter != "" ? "Press Esc to clear the filter"
|
||||
: root.state.hidden > 0 ? "Press Ctrl+H to show hidden files"
|
||||
: "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -33,3 +33,4 @@ D-028 — 2026-11-18 — The user's old, buggy Tunal prototype (`/home/astar76/D
|
|||
D-029 — 2026-11-18 — Orchestration: backend-only plans whose dependencies are done and whose files are a crate of their own (S017, S019, S020, S022, S025, S027) may run out of INDEX order in the second parallel slot beside the UI chain; still at most 2 sessions at once; each commits with explicit paths — orchestrator (user asked to keep everything runnable going) — S017–S027.
|
||||
D-030 — 2026-11-18 — Playlist sort refined (supersedes D-021's details, keeps its UI): candidate playlists come from the viewed folder and from <Music>/Playlists (also playlists/Playlist/playlist); only playlists with ≥ 1 track in the viewed folder are offered, one "Playlist sort" option each; preselected = the playlist named after the folder, else the one with most tracks from it; subfolders sort by their first listed track; tracks that moved still match by file name; formats .m3u .m3u8 .pls .xspf .wpl, text decoded utf-8 → utf-16 → cp1252 → latin-1; ordering stays listed-first in playlist order, rest natural name order, desc reverses — orchestrator, from the user's old prototype behaviour (D-028) — S008.
|
||||
D-031 — 2026-11-18 — Floating surfaces don't use `PopupWindow` (it closes without exit motion): `Menu` and `Dialog` inherit `Overlay` and `ToastStack` is a plain layer, each placed last in the window at `width: 100%; height: 100%` in the order ToastStack, Dialog, Menu; they open with window coordinates and play exit motion by animating a `progress` that reverses mid-flight. Dialogs never close themselves (owner calls `close()` from `action`); toast models are owned outside (`closing` ends one, `removed(index)` drops it). Tooltips stay on `PopupWindow` (fade in, leave at once) — S005 — every UI plan with menus, dialogs or toasts (S010–S013, S018–S031).
|
||||
D-032 — 2026-11-18 — Folder views use `folder::FolderModel` (one per view, `Rc`, a Slint `Model` of `DetailRow`s formatted on demand; worker results reach it through `upgrade_in_event_loop` + `as_any` downcast and carry a generation); selection is a set of raw names (`click`, `navigate`, `select_all`); sort menus are built in Rust as `[MenuItem]` and opened at window level (D-031); list rows set `StateLayer.focusable: false` and the view's `FocusScope` owns the keys; watch events are hints (unchanged stat is ignored: the local backend also reports reads) — S008 — S009–S015.
|
||||
|
|
|
|||
|
|
@ -69,5 +69,13 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
|
|||
- Not done: workspace-wide clippy currently fails in `tunal-core` (S008's in-progress `playlist.rs`), not in this plan's files. Real MusicBrainz JSON shape checked against docs only, not live. No search by AcoustID.
|
||||
- Later: `inc` for labels/barcode; honour `Retry-After`; cache of lookups.
|
||||
|
||||
## S008 — Folder model and details view
|
||||
- Done: `crates/tunal/src/folder/` `FolderModel` (Slint `Model<Data = DetailRow>`, rows formatted on demand): `attach(&MainWindow, Locations) -> Rc<FolderModel>` wires rows, `FolderState`, sort menu and view callbacks; `open(Uri)` (worker thread: watch, chunked list flushed at most every 60 ms, playlist lookup; a generation drops stale results), `open_blocking` (screenshots), `sort_column`, `sort_menu`/`sort_menu_activated`, `set_filter`/`type_filter`, `toggle_hidden`, `click(row, ctrl, shift)`, `navigate(NavKey, shift, page) -> row`, `select_all`, `clear_selection`, `activate(row)` (opens folders). Selection, cursor and anchor are kept by raw name across sorts and watch diffs. Sort name (natural)/size/type/modified/playlist, desc, folders first; groups type/date/size with header rows; hidden toggle; filter chip; empty/loading/error states; Type column hidden below 640 px.
|
||||
- `tunal-core::playlist` (D-030): `read`, `parse`, `candidates(folder, entries)` (preselected first), `Ranks`, `music_dir`, `shared_dir`. `icons.rs`: `Category::of(entry)`, `glyph`, `group_label`, `link_badge`, `type_label`. Shared components gained `StateLayer.focusable/modifiers/double-clicked`, `ListRow.badge`, 3 icons. `tunal <dir>` opens a folder (also with `--screenshot`).
|
||||
- Verified: workspace build, clippy -D warnings, fmt --check, literal grep empty; looked at 10 000-file light + dark, mixed folder (links, broken link, non-UTF-8 name, groups, selection, filter chip, 720x480), permission-denied / missing / empty folder. A temporary uncommitted hook dumped row order for every sort/group/filter/selection case, injected keys through the window (arrows, Shift, End, Ctrl+A, Ctrl+H, typing, Backspace, Esc), checked playlist sort on m3u/xspf/pls/cp1252/UTF-16 wpl, and drove the watch path (insert, remove, rename, playlist edit and removal re-sort) through a message queue.
|
||||
- Not done: no live window run (pointer clicks, double-click, header/indicator motion, sort menu, PageUp/Down page size not exercised in a real event loop). No folder item counts in the Size column.
|
||||
- Found: the local watch (S006) also reports reads (opening a file, listing the folder). The model ignores events whose stat is unchanged, and the folder's own event unless it is gone; the shared playlist watch compares mtime/size. Without that, listing and watch looped.
|
||||
- Later: filter access events in `LocalLocation::watch` itself (debouncer-mini hides the event kind); back/up navigation and per-folder sort in `.directory` (S010, S015).
|
||||
|
||||
## Later
|
||||
-
|
||||
|
|
|
|||
Loading…
Reference in a new issue