diff --git a/FEATURES.md b/FEATURES.md
index 0f8cd20..74d678d 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -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 |
diff --git a/Plans/03 File browsing/S008-folder-model-details.md b/Plans/03 File browsing/S008-folder-model-details.md
index 0434cf8..1569165 100644
--- a/Plans/03 File browsing/S008-folder-model-details.md
+++ b/Plans/03 File browsing/S008-folder-model-details.md
@@ -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
` 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 `/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 ` 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.
diff --git a/Plans/INDEX.md b/Plans/INDEX.md
index 7e7fd7d..deda911 100644
--- a/Plans/INDEX.md
+++ b/Plans/INDEX.md
@@ -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
diff --git a/crates/tunal-core/src/lib.rs b/crates/tunal-core/src/lib.rs
index f1c695e..5169200 100644
--- a/crates/tunal-core/src/lib.rs
+++ b/crates/tunal-core/src/lib.rs
@@ -6,6 +6,7 @@ mod local;
mod location;
pub mod mime;
pub mod ops;
+pub mod playlist;
mod registry;
pub mod trash;
mod uri;
diff --git a/crates/tunal-core/src/playlist.rs b/crates/tunal-core/src/playlist.rs
new file mode 100644
index 0000000..d3e6a15
--- /dev/null
+++ b/crates/tunal-core/src/playlist.rs
@@ -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 {
+ 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 {
+ 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 {
+ 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> {
+ 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 {
+ 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, "", "")
+ .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- {
+ 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 {
+ 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::>()
+ .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 {
+ 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, usize>,
+ /// Track file name → first position, for tracks that moved.
+ by_name: HashMap, 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 {
+ 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 {
+ let Some(music) = music_dir() else {
+ return Vec::new();
+ };
+ if !in_music(folder, &music) {
+ return Vec::new();
+ }
+ let mut paths: Vec = 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 = 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()
+}
diff --git a/crates/tunal/Cargo.toml b/crates/tunal/Cargo.toml
index d795fba..659df74 100644
--- a/crates/tunal/Cargo.toml
+++ b/crates/tunal/Cargo.toml
@@ -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
diff --git a/crates/tunal/src/folder/format.rs b/crates/tunal/src/folder/format.rs
new file mode 100644
index 0000000..08674d5
--- /dev/null
+++ b/crates/tunal/src/folder/format.rs
@@ -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()
+ }
+}
diff --git a/crates/tunal/src/folder/load.rs b/crates/tunal/src/folder/load.rs
new file mode 100644
index 0000000..574e680
--- /dev/null
+++ b/crates/tunal/src/folder/load.rs
@@ -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),
+ Done(u64, Result<(), Error>),
+ Watching(u64, Watch),
+ Changed(u64, Vec),
+ Playlists(u64, Vec),
+ /// A file in the shared playlist folder changed: look the playlists up again.
+ PlaylistsChanged(u64),
+}
+
+pub enum Change {
+ Upsert(Entry),
+ Removed(Vec),
+}
+
+pub type Deliver = Arc;
+
+/// 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,
+) {
+ 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, bool)> = Vec::new();
+ let mut pending: Vec = 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, u64)>;
+
+/// Modification time and size of each file in `dir`.
+fn stamps(dir: &Path) -> HashMap {
+ 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, bool)]) -> Vec {
+ let entries: Vec<(&[u8], bool)> = names.iter().map(|(n, d)| (n.as_slice(), *d)).collect();
+ playlist::candidates(path, &entries)
+}
diff --git a/crates/tunal/src/folder/mod.rs b/crates/tunal/src/folder/mod.rs
new file mode 100644
index 0000000..5dd81d8
--- /dev/null
+++ b/crates/tunal/src/folder/mod.rs
@@ -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,
+ generation: u64,
+ status: Status,
+ items: Vec
- ,
+ /// Raw name → index into `items`.
+ by_name: HashMap, usize>,
+ rows: Vec
,
+ /// Raw name → row, for the rows shown.
+ row_of: HashMap, usize>,
+ settings: Settings,
+ playlists: Vec,
+ /// The playlist `SortKey::Playlist` refers to, kept across lookups.
+ playlist_path: Option,
+ selected: HashSet>,
+ cursor: Option>,
+ anchor: Option>,
+ watches: Vec,
+}
+
+type Listener = Box;
+
+/// 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,
+ notify: ModelNotify,
+ locations: Locations,
+ deliver: Deliver,
+ /// Called after every change the window must reflect (state, menu).
+ changed: RefCell,
+}
+
+impl FolderModel {
+ pub fn new(locations: Locations, deliver: Deliver) -> Rc {
+ 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, 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