From 7ba6ae8eaeab4df45e5e47c006f1a1b30d06cf8e Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 18 Nov 2026 20:28:31 -0600 Subject: [PATCH] S015: .directory folder metadata (lossless dirmeta, folder icons/names/views, appearance dialog) Needs S016's Bridge::elevation() and tunal-elevate to build. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 1 + Cargo.lock | 1 + .../S015-directory-metadata.md | 10 +- Plans/INDEX.md | 2 +- crates/tunal-dirmeta/examples/roundtrip.rs | 15 + crates/tunal-dirmeta/src/lib.rs | 318 +++++++++++++++++- crates/tunal/Cargo.toml | 1 + crates/tunal/src/actions.rs | 57 +++- crates/tunal/src/desktop_apps.rs | 34 +- crates/tunal/src/folder/appearance.rs | 304 +++++++++++++++++ crates/tunal/src/folder/load.rs | 26 ++ crates/tunal/src/folder/look.rs | 96 ++++++ crates/tunal/src/folder/mod.rs | 234 ++++++++++++- crates/tunal/src/main.rs | 4 + crates/tunal/src/menus.rs | 2 + crates/tunal/src/shell/mod.rs | 22 +- crates/tunal/src/shell/path.rs | 17 + crates/tunal/ui/app.slint | 39 ++- crates/tunal/ui/components/list-row.slint | 5 + crates/tunal/ui/components/shape.slint | 14 +- crates/tunal/ui/components/text-field.slint | 4 + .../tunal/ui/dialogs/folder-appearance.slint | 155 +++++++++ crates/tunal/ui/shell/breadcrumb.slint | 5 + crates/tunal/ui/shell/sidebar.slint | 3 + crates/tunal/ui/views/details-view.slint | 15 +- crates/tunal/ui/views/grid-view.slint | 10 +- docs/PROGRESS.md | 10 + 27 files changed, 1376 insertions(+), 28 deletions(-) create mode 100644 crates/tunal-dirmeta/examples/roundtrip.rs create mode 100644 crates/tunal/src/folder/appearance.rs create mode 100644 crates/tunal/src/folder/look.rs create mode 100644 crates/tunal/ui/dialogs/folder-appearance.slint diff --git a/CLAUDE.md b/CLAUDE.md index 80881af..3ae9615 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -91,6 +91,7 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~ | `cargo run -p tunal -- --gallery --page menu\|dialog --screenshot [--dark] --size 960x640` | open menu + submenu + two toasts, or dialog + indeterminate toast, over a stand-in folder | S005 | | `TUNAL_SETTINGS=<0-4> cargo run -p tunal -- --screenshot --size 1000x700` (`XDG_CONFIG_HOME=`) | settings dialog page over a folder | S013 | | `TUNAL_DRAG=x1,y1,x2,y2[,hold] TUNAL_REDUCED_MOTION=1 cargo run -p tunal -- --screenshot --size 1200x760` (`XDG_CONFIG_HOME=`) | drags between window points and drops (drop menu) or holds (glow + drag image) before the frame | S014 | +| `TUNAL_APPEARANCE=1 XDG_CONFIG_HOME= cargo run -p tunal -- --screenshot --size 1000x760` | folder appearance dialog for `` (theme icons looked up at once); `cargo run -p tunal-dirmeta --example roundtrip -- ` sets `Icon` in `/.directory` and prints the old values | S015 | Don't assume a tool exists: check first. When your plan creates a tool, add its row here. diff --git a/Cargo.lock b/Cargo.lock index aae71b7..4d8ec92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5544,6 +5544,7 @@ dependencies = [ "slint-build", "toml", "tunal-core", + "tunal-dirmeta", "tunal-theme", "zbus", ] diff --git a/Plans/04 Directory metadata/S015-directory-metadata.md b/Plans/04 Directory metadata/S015-directory-metadata.md index 0b983ef..03dfb28 100644 --- a/Plans/04 Directory metadata/S015-directory-metadata.md +++ b/Plans/04 Directory metadata/S015-directory-metadata.md @@ -10,11 +10,11 @@ Read `.directory` files for folder icon, display name and view settings, apply t CLAUDE.md §4 (.directory); docs/DECISIONS.md D-017; crates/tunal/src/folder/ API; crates/tunal/src/desktop_apps.rs (icon theme lookup). ## Steps -- [ ] Lossless parser/writer: keeps comments, blank lines, unknown groups/keys, localized keys (`Name[de]`); get/set API. -- [ ] Keys (D-017): `[Desktop Entry]` `Icon` (theme name or absolute path) and `Name` (localized by `LANG`); our view settings in `[X-Tunal]` (view mode, sort, sort order, grouping, hidden files, previews) and `Glyph` for a Material glyph. -- [ ] Apply: child folder icons and names in views (read lazily off-thread, cached by mtime); opening a folder applies its view settings; the display name shows in breadcrumb/sidebar with the real name as tooltip. -- [ ] Folder appearance dialog (context menu action): icon picker (Material glyphs, theme `folder-*` icons, image file), display name, 'remember view settings for this folder'. -- [ ] Write failure with PermissionDenied → error with the elevation hook (S016). +- [x] Lossless parser/writer: keeps comments, blank lines, unknown groups/keys, localized keys (`Name[de]`); get/set API. +- [x] Keys (D-017): `[Desktop Entry]` `Icon` (theme name or absolute path) and `Name` (localized by `LANG`); our view settings in `[X-Tunal]` (view mode, sort, sort order, grouping, hidden files, previews) and `Glyph` for a Material glyph. +- [x] Apply: child folder icons and names in views (read lazily off-thread, cached by mtime); opening a folder applies its view settings; the display name shows in breadcrumb/sidebar with the real name as tooltip. +- [x] Folder appearance dialog (context menu action): icon picker (Material glyphs, theme `folder-*` icons, image file), display name, 'remember view settings for this folder'. +- [x] Write failure with PermissionDenied → error with the elevation hook (S016). - [ ] PROGRESS entry, INDEX line, commit `S015: …` ## End criteria diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 4e29784..1b1e955 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -31,7 +31,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 04 Directory metadata -- [ ] [S015 — `.directory` folder metadata](04%20Directory%20metadata/S015-directory-metadata.md) · Sonnet high +- [x] [S015 — `.directory` folder metadata](04%20Directory%20metadata/S015-directory-metadata.md) · Sonnet high ## 05 Elevation diff --git a/crates/tunal-dirmeta/examples/roundtrip.rs b/crates/tunal-dirmeta/examples/roundtrip.rs new file mode 100644 index 0000000..dc0673c --- /dev/null +++ b/crates/tunal-dirmeta/examples/roundtrip.rs @@ -0,0 +1,15 @@ +//! Smoke run: edits `Icon` in a sample with comments and unknown keys; prints the result. +//! Usage: roundtrip (the dir needs a `.directory`; it is rewritten). +use tunal_dirmeta::DirMeta; + +fn main() { + let dir = std::path::PathBuf::from(std::env::args().nth(1).expect("dir")); + let mut meta = DirMeta::load(&dir).expect("read"); + println!( + "icon={:?} name={:?}", + meta.icon(), + meta.name_for(Some("de_DE.UTF-8")) + ); + meta.set_icon(Some("folder-music")); + meta.save(&dir).expect("write"); +} diff --git a/crates/tunal-dirmeta/src/lib.rs b/crates/tunal-dirmeta/src/lib.rs index c008186..52fdaa6 100644 --- a/crates/tunal-dirmeta/src/lib.rs +++ b/crates/tunal-dirmeta/src/lib.rs @@ -1 +1,317 @@ -//! Reading and writing `.directory` folder metadata. +//! Reading and writing `.directory` folder metadata (desktop entry format). +//! +//! The file is kept as lines, so a write changes only the keys it sets: comments, blank +//! lines, unknown groups and keys, and localized keys (`Name[de]`) survive untouched. +//! +//! Standard keys (D-017): `[Desktop Entry]` `Icon` and `Name`. Our own settings live in the +//! `[X-Tunal]` group; other apps' groups are never written. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +pub const FILE_NAME: &str = ".directory"; +const ENTRY: &str = "Desktop Entry"; +const TUNAL: &str = "X-Tunal"; + +/// A parsed `.directory` file. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DirMeta { + lines: Vec, + /// The file ended without a newline: kept so a write doesn't change its last line. + no_final_newline: bool, +} + +impl DirMeta { + pub fn parse(text: &str) -> Self { + Self { + lines: text.lines().map(str::to_owned).collect(), + no_final_newline: !text.is_empty() && !text.ends_with('\n'), + } + } + + /// Reads `/.directory`; a missing file gives an empty one. + pub fn load(dir: &Path) -> io::Result { + match fs::read_to_string(dir.join(FILE_NAME)) { + Ok(text) => Ok(Self::parse(&text)), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Self::default()), + Err(e) => Err(e), + } + } + + /// Writes `/.directory` atomically; an empty file removes it. + pub fn save(&self, dir: &Path) -> io::Result<()> { + let path = dir.join(FILE_NAME); + if self.lines.iter().all(|l| l.trim().is_empty()) { + return match fs::remove_file(&path) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + }; + } + let temp = dir.join(format!(".directory.tunal-{}", std::process::id())); + let result = fs::write(&temp, self.to_string()).and_then(|()| fs::rename(&temp, &path)); + if result.is_err() { + let _ = fs::remove_file(&temp); + } + result + } + + /// Value of `key` in `group`, the last one if repeated. + pub fn get(&self, group: &str, key: &str) -> Option<&str> { + let mut found = None; + let mut current = None; + for line in &self.lines { + if let Some(name) = header(line) { + current = Some(name); + } else if current == Some(group) + && let Some((k, v)) = pair(line) + && k == key + { + found = Some(v); + } + } + found + } + + /// Sets `key` in `group`, adding the group at the end when missing; `None` removes the + /// key (and the group, once it holds no key at all). + pub fn set(&mut self, group: &str, key: &str, value: Option<&str>) { + let mut current = None; + let mut at = None; + let mut group_end = None; + for (i, line) in self.lines.iter().enumerate() { + if let Some(name) = header(line) { + current = Some(name); + if name == group { + group_end = Some(i + 1); + } + } else if current == Some(group) { + if !line.trim().is_empty() { + group_end = Some(i + 1); + } + if pair(line).is_some_and(|(k, _)| k == key) { + at = Some(i); + } + } + } + match (at, value, group_end) { + (Some(i), Some(v), _) => self.lines[i] = format!("{key}={}", escape(v)), + (Some(i), None, _) => { + self.lines.remove(i); + self.drop_empty_group(group); + } + (None, Some(v), Some(end)) => self.lines.insert(end, format!("{key}={}", escape(v))), + (None, Some(v), None) => { + if self.lines.last().is_some_and(|l| !l.trim().is_empty()) { + self.lines.push(String::new()); + } + self.lines.push(format!("[{group}]")); + self.lines.push(format!("{key}={}", escape(v))); + } + (None, None, _) => {} + } + } + + /// Removes `group` when nothing but its header (and blank lines) is left. + fn drop_empty_group(&mut self, group: &str) { + let Some(start) = self.lines.iter().position(|l| header(l) == Some(group)) else { + return; + }; + let end = self.lines[start + 1..] + .iter() + .position(|l| header(l).is_some()) + .map_or(self.lines.len(), |p| start + 1 + p); + if self.lines[start + 1..end] + .iter() + .all(|l| l.trim().is_empty()) + { + self.lines.drain(start..end); + } + } + + /// The folder icon: a theme name or an absolute path. + pub fn icon(&self) -> Option<&str> { + self.get(ENTRY, "Icon").filter(|v| !v.is_empty()) + } + + pub fn set_icon(&mut self, icon: Option<&str>) { + self.set(ENTRY, "Icon", icon.filter(|v| !v.is_empty())); + } + + /// The display name, localized by `LANG`/`LC_MESSAGES`: `Name[de_DE]`, `Name[de]`, `Name`. + pub fn name(&self) -> Option { + let locale = ["LC_ALL", "LC_MESSAGES", "LANG"] + .iter() + .find_map(|v| std::env::var(v).ok().filter(|s| !s.is_empty())); + self.name_for(locale.as_deref()) + } + + pub fn name_for(&self, locale: Option<&str>) -> Option { + let mut candidates = Vec::new(); + if let Some(l) = locale { + // `de_DE.UTF-8@euro` → `de_DE@euro`, `de_DE`, `de@euro`, `de`. + let (rest, modifier) = l.split_once('@').map_or((l, None), |(a, b)| (a, Some(b))); + let rest = rest.split('.').next().unwrap_or(rest); + let (lang, country) = rest + .split_once('_') + .map_or((rest, None), |(a, b)| (a, Some(b))); + if let (Some(c), Some(m)) = (country, modifier) { + candidates.push(format!("{lang}_{c}@{m}")); + } + if let Some(c) = country { + candidates.push(format!("{lang}_{c}")); + } + if let Some(m) = modifier { + candidates.push(format!("{lang}@{m}")); + } + if lang != "C" && lang != "POSIX" { + candidates.push(lang.to_owned()); + } + } + let value = candidates + .iter() + .find_map(|c| self.get(ENTRY, &format!("Name[{c}]"))) + .or_else(|| self.get(ENTRY, "Name"))?; + Some(value.to_owned()).filter(|v| !v.is_empty()) + } + + /// Sets the unlocalized `Name`. + pub fn set_name(&mut self, name: Option<&str>) { + self.set(ENTRY, "Name", name.filter(|v| !v.is_empty())); + } + + /// Value of one of our own settings. + pub fn tunal(&self, key: &str) -> Option<&str> { + self.get(TUNAL, key) + } + + pub fn set_tunal(&mut self, key: &str, value: Option<&str>) { + self.set(TUNAL, key, value); + } + + /// Whether the file holds our view settings. + pub fn has_view(&self) -> bool { + VIEW_KEYS.iter().any(|k| self.tunal(k).is_some()) + } + + /// Forgets our view settings. + pub fn clear_view(&mut self) { + for key in VIEW_KEYS { + self.set_tunal(key, None); + } + } + + pub fn view(&self) -> View { + let get = |k| self.tunal(k).map(str::to_owned); + View { + mode: get("View"), + sort: get("Sort"), + descending: self.tunal("SortOrder").map(|v| v == "descending"), + group: get("Group"), + hidden: self.tunal("ShowHidden").map(|v| v == "true"), + previews: self.tunal("Previews").map(|v| v == "true"), + playlist: get("Playlist"), + } + } + + pub fn set_view(&mut self, view: &View) { + let flag = |b: bool| if b { "true" } else { "false" }; + self.set_tunal("View", view.mode.as_deref()); + self.set_tunal("Sort", view.sort.as_deref()); + self.set_tunal( + "SortOrder", + view.descending + .map(|d| if d { "descending" } else { "ascending" }), + ); + self.set_tunal("Group", view.group.as_deref()); + self.set_tunal("ShowHidden", view.hidden.map(flag)); + self.set_tunal("Previews", view.previews.map(flag)); + self.set_tunal("Playlist", view.playlist.as_deref()); + } + + /// The Material glyph (a codepoint character) that stands for the folder. + pub fn glyph(&self) -> Option { + self.tunal("Glyph")?.chars().next() + } + + pub fn set_glyph(&mut self, glyph: Option) { + self.set_tunal("Glyph", glyph.map(String::from).as_deref()); + } +} + +const VIEW_KEYS: [&str; 7] = [ + "View", + "Sort", + "SortOrder", + "Group", + "ShowHidden", + "Previews", + "Playlist", +]; + +/// View settings kept per folder in `[X-Tunal]`; `None` = not set, use the default. +/// Values are the words the app uses (`details`, `grid`, `name`, `size`, …). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct View { + pub mode: Option, + pub sort: Option, + pub descending: Option, + pub group: Option, + pub hidden: Option, + pub previews: Option, + /// File name of the playlist the folder is sorted by (D-021). + pub playlist: Option, +} + +/// `[Group]` header name. +fn header(line: &str) -> Option<&str> { + let t = line.trim(); + t.strip_prefix('[')?.strip_suffix(']') +} + +/// `key=value` of a line; comments and blank lines give `None`. +fn pair(line: &str) -> Option<(&str, &str)> { + let t = line.trim_start(); + if t.starts_with('#') || t.starts_with('[') { + return None; + } + let (k, v) = t.split_once('=')?; + Some((k.trim_end(), v.trim_start())) +} + +/// Values stay on one line: newlines would start a new key. +fn escape(value: &str) -> String { + value.replace(['\n', '\r'], " ") +} + +impl std::fmt::Display for DirMeta { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let last = self.lines.len().saturating_sub(1); + for (i, line) in self.lines.iter().enumerate() { + if i == last && self.no_final_newline { + write!(f, "{line}")?; + } else { + writeln!(f, "{line}")?; + } + } + Ok(()) + } +} + +/// Where a folder's icon points: a theme icon name or a file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum IconRef { + Theme(String), + File(PathBuf), +} + +impl IconRef { + /// An absolute `Icon` is a file, anything else a theme name. + pub fn parse(value: &str) -> Self { + if value.starts_with('/') { + Self::File(PathBuf::from(value)) + } else { + Self::Theme(value.to_owned()) + } + } +} diff --git a/crates/tunal/Cargo.toml b/crates/tunal/Cargo.toml index 97daccd..1079ba0 100644 --- a/crates/tunal/Cargo.toml +++ b/crates/tunal/Cargo.toml @@ -10,6 +10,7 @@ slint = { workspace = true, features = ["unstable-winit-030"] } tunal-theme = { path = "../tunal-theme" } png.workspace = true tunal-core = { path = "../tunal-core" } +tunal-dirmeta = { path = "../tunal-dirmeta" } jiff.workspace = true serde.workspace = true zbus.workspace = true diff --git a/crates/tunal/src/actions.rs b/crates/tunal/src/actions.rs index 2cd7cf5..d365f9f 100644 --- a/crates/tunal/src/actions.rs +++ b/crates/tunal/src/actions.rs @@ -10,6 +10,7 @@ use slint::{ComponentHandle, Model, ModelRc, VecModel}; use tunal_core::ops::{self, JobKind}; use tunal_core::{Locations, Uri}; +use crate::folder::appearance::Appearance; use crate::jobs_bridge::Bridge; use crate::menus::{Context as MenuContext, Menus}; use crate::open::Opener; @@ -35,6 +36,7 @@ pub enum Action { Open, OpenWith, Properties, + Appearance, } enum Shortcut { @@ -43,7 +45,7 @@ enum Shortcut { } impl Action { - pub const ALL: [Action; 14] = [ + pub const ALL: [Action; 15] = [ Self::Cut, Self::Copy, Self::Paste, @@ -58,6 +60,7 @@ impl Action { Self::Open, Self::OpenWith, Self::Properties, + Self::Appearance, ]; pub fn id(self) -> &'static str { @@ -76,6 +79,7 @@ impl Action { Self::Open => "open", Self::OpenWith => "open-with", Self::Properties => "properties", + Self::Appearance => "appearance", } } @@ -99,6 +103,7 @@ impl Action { Self::Open => "Open", Self::OpenWith => "Open with…", Self::Properties => "Properties", + Self::Appearance => "Folder appearance…", } } @@ -119,6 +124,7 @@ impl Action { Self::Open => "\u{e89e}", Self::OpenWith => "\u{e5c3}", Self::Properties => "\u{e88e}", + Self::Appearance => "\u{e40a}", } } @@ -134,7 +140,12 @@ impl Action { Self::Trash => (Shortcut::Key(Key::Delete), false), Self::Delete => (Shortcut::Key(Key::Delete), true), Self::Settings => (Shortcut::Char(','), false), - Self::Restore | Self::EmptyTrash | Self::Open | Self::OpenWith | Self::Properties => { + Self::Restore + | Self::EmptyTrash + | Self::Open + | Self::OpenWith + | Self::Properties + | Self::Appearance => { return None; } }) @@ -184,6 +195,7 @@ impl Action { Self::Settings => true, Self::Open | Self::OpenWith => files && ctx.selected > 0, Self::Properties => true, + Self::Appearance => files && ctx.selected <= 1, } } } @@ -218,6 +230,7 @@ pub struct Actions { menus: RefCell, opener: Rc, properties: Rc, + appearance: Rc, } impl Actions { @@ -225,6 +238,7 @@ impl Actions { let bridge = Bridge::attach(ui, locations.clone()); let opener = Opener::attach(ui, locations.clone(), bridge.clone()); let properties = Properties::attach(ui, locations.clone()); + let appearance = Appearance::attach(ui, bridge.elevation()); let actions = Rc::new_cyclic(|me| Self { me: me.clone(), ui: ui.as_weak(), @@ -236,6 +250,7 @@ impl Actions { menus: RefCell::new(Menus::load()), opener, properties, + appearance, }); let me = actions.me.clone(); let shell_weak = Rc::downgrade(shell); @@ -244,6 +259,12 @@ impl Actions { me.refresh_unwatched(&shell); } }); + let me = actions.me.clone(); + actions.appearance.on_saved(move |dir, remembered| { + if let Some(me) = me.upgrade() { + me.appearance_saved(dir, remembered); + } + }); actions.bind(ui); actions } @@ -470,6 +491,23 @@ impl Actions { .show(if uris.is_empty() { vec![dir] } else { uris }); return; } + Action::Appearance => { + // One folder selected: that one; nothing selected: the folder shown. + let target = match uris.as_slice() { + [] => Some(dir), + [only] if pane.model.selection_is_dir() => Some(only.clone()), + _ => None, + }; + if let Some(path) = target.and_then(|t| t.to_path()) { + let shown = pane.dir().and_then(|d| d.to_path()) == Some(path.clone()); + self.appearance.show( + path, + pane.model.view_snapshot(), + shown && pane.model.remembers_view(), + ); + } + return; + } Action::Settings => { if let Some(ui) = self.ui.upgrade() { ui.invoke_show_settings(0); @@ -606,6 +644,21 @@ impl Actions { } /// After a job: panes whose location can't watch (the Trash) list again. + /// A folder's appearance was saved: panes showing it (as a folder or inside it) pick up + /// its icon and name, and the folder shown keeps or forgets its view settings. + fn appearance_saved(&self, dir: &std::path::Path, remembered: bool) { + let Some(shell) = self.shell() else { + return; + }; + for pane in shell.panes() { + if pane.dir().and_then(|d| d.to_path()).as_deref() == Some(dir) { + pane.model.set_remembers_view(remembered); + } + pane.model.reload_looks(); + } + shell.show_chrome(); + } + fn refresh_unwatched(&self, shell: &Shell) { for pane in shell.panes() { let watches = pane diff --git a/crates/tunal/src/desktop_apps.rs b/crates/tunal/src/desktop_apps.rs index 96cc800..4cc7add 100644 --- a/crates/tunal/src/desktop_apps.rs +++ b/crates/tunal/src/desktop_apps.rs @@ -560,6 +560,7 @@ struct ThemeDir { size: u32, scalable: bool, apps: bool, + places: bool, /// Position of its theme in the inheritance chain. theme: usize, } @@ -627,6 +628,8 @@ fn theme_dirs(base: &Path, name: &str, theme: usize) -> Vec { theme, apps: context.eq_ignore_ascii_case("Applications") || dir.to_lowercase().contains("apps"), + places: context.eq_ignore_ascii_case("Places") + || dir.to_lowercase().contains("places"), }) }) .collect() @@ -640,6 +643,15 @@ pub struct IconTheme { impl IconTheme { pub fn load() -> Self { + Self::load_context(false) + } + + /// The same for the Places context (folder icons) instead of Applications. + pub fn load_places() -> Self { + Self::load_context(true) + } + + fn load_context(places: bool) -> Self { let mut bases: Vec = home().map(|h| h.join(".icons")).into_iter().collect(); bases.extend(data_dirs().into_iter().map(|d| d.join("icons"))); let mut chain = Vec::new(); @@ -651,13 +663,33 @@ impl IconTheme { for (index, theme) in chain.iter().enumerate() { for base in &bases { let mut found = theme_dirs(base, theme, index); - found.retain(|d| d.apps); + found.retain(|d| if places { d.places } else { d.apps }); dirs.extend(found); } } Self { dirs } } + /// Names of the icons that start with `prefix` (no `-symbolic` ones), sorted. + pub fn names(&self, prefix: &str) -> Vec { + let mut names: Vec = self + .dirs + .iter() + .filter_map(|d| fs::read_dir(&d.path).ok()) + .flatten() + .filter_map(|e| { + let name = e.ok()?.file_name().into_string().ok()?; + let stem = name + .strip_suffix(".svg") + .or_else(|| name.strip_suffix(".png"))?; + (stem.starts_with(prefix) && !stem.ends_with("-symbolic")).then(|| stem.to_owned()) + }) + .collect(); + names.sort(); + names.dedup(); + names + } + /// The file of icon `name` at about `size` px: an absolute path as is, else the closest /// size of the first theme that has it, then `pixmaps`. `None` when nothing is installed /// (callers draw a glyph). diff --git a/crates/tunal/src/folder/appearance.rs b/crates/tunal/src/folder/appearance.rs new file mode 100644 index 0000000..2b6cdd8 --- /dev/null +++ b/crates/tunal/src/folder/appearance.rs @@ -0,0 +1,304 @@ +//! The folder appearance dialog: icon, display name and remembered view of one folder, kept +//! in its `.directory`. Saving runs off the UI thread; a permission failure offers to retry +//! as administrator through the elevation helper. + +use std::cell::RefCell; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use slint::{ComponentHandle, ModelRc, VecModel}; +use tunal_core::{Error, Uri}; +use tunal_dirmeta::{DirMeta, FILE_NAME, View}; +use tunal_elevate::Elevation; + +use super::look; +use crate::desktop_apps::IconTheme; +use crate::{IconChoice, MainWindow}; + +/// Material glyphs the picker offers (label, codepoint). +const GLYPHS: [(&str, char); 17] = [ + ("Special folder", '\u{e2c8}'), + ("Star", '\u{e838}'), + ("Favourite", '\u{e87d}'), + ("Home", '\u{e88a}'), + ("Music", '\u{e405}'), + ("Movies", '\u{e02c}'), + ("Pictures", '\u{e3f4}'), + ("Documents", '\u{e873}'), + ("Code", '\u{e86f}'), + ("Downloads", '\u{f090}'), + ("Work", '\u{e8f9}'), + ("School", '\u{e80c}'), + ("Camera", '\u{e412}'), + ("Cloud", '\u{e2bd}'), + ("Private", '\u{e897}'), + ("Tools", '\u{e869}'), + ("Bookmark", '\u{e866}'), +]; + +/// How many theme icons the picker lists. +const THEME_ICONS: usize = 18; + +/// What a picker cell stands for (`Default` is cell 0). +#[derive(Clone)] +enum Pick { + Default, + Glyph(char), + Theme(String), +} + +struct Open { + dir: PathBuf, +} + +thread_local! { + /// What each cell of the open dialog's picker stands for (UI thread only; the theme icons + /// arrive after the dialog shows). + static PICKS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +type Saved = Box; + +pub struct Appearance { + ui: slint::Weak, + elevation: Arc, + open: RefCell>, + /// Called after a save with the folder and whether it now remembers a view. + saved: RefCell, + /// The view settings to keep when "remember" is on, as the pane shows them now. + view: RefCell, + /// Bumped per opening: a late icon lookup for an earlier one is dropped. + serial: Arc, +} + +impl Appearance { + pub fn attach(ui: &MainWindow, elevation: Arc) -> Rc { + let me = Rc::new(Self { + ui: ui.as_weak(), + elevation, + open: RefCell::new(None), + saved: RefCell::new(Box::new(|_, _| {})), + view: RefCell::new(View::default()), + serial: Arc::new(AtomicU64::new(0)), + }); + let weak = Rc::downgrade(&me); + ui.on_appearance_saved(move |elevate| { + if let Some(me) = weak.upgrade() { + me.save(elevate); + } + }); + let weak = Rc::downgrade(&me); + ui.on_appearance_done(move |remembered| { + if let Some(me) = weak.upgrade() { + let dir = me.open.borrow().as_ref().map(|o| o.dir.clone()); + if let Some(dir) = dir { + (me.saved.borrow())(&dir, remembered); + } + } + }); + me + } + + pub fn on_saved(&self, f: impl Fn(&Path, bool) + 'static) { + *self.saved.borrow_mut() = Box::new(f); + } + + /// Opens the dialog for `dir`. `view` is what "remember" would keep (the pane's settings). + pub fn show(&self, dir: PathBuf, view: View, remembers: bool) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let meta = DirMeta::load(&dir).unwrap_or_default(); + let open_dir = dir.clone(); + *self.view.borrow_mut() = view; + ui.set_appearance_name(meta.get("Desktop Entry", "Name").unwrap_or("").into()); + ui.set_appearance_placeholder( + dir.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default() + .into(), + ); + ui.set_appearance_remember(remembers || meta.has_view()); + ui.set_appearance_error("".into()); + ui.set_appearance_can_elevate(false); + ui.set_appearance_image("".into()); + ui.set_appearance_choice(0); + PICKS.with(|p| *p.borrow_mut() = vec![Pick::Default]); + *self.open.borrow_mut() = Some(Open { dir: open_dir }); + fill(&ui, &meta, Vec::new()); + ui.invoke_show_appearance(); + // The theme's folder icons are looked up off the UI thread (`TUNAL_APPEARANCE`, set + // by screenshots that have no event loop, looks them up at once). + if std::env::var_os("TUNAL_APPEARANCE").is_some() { + fill(&ui, &meta, theme_icons()); + return; + } + let weak = self.ui.clone(); + let serial = self.serial.fetch_add(1, Ordering::Relaxed) + 1; + let latest = self.serial.clone(); + std::thread::spawn(move || { + let names = theme_icons(); + let _ = weak.upgrade_in_event_loop(move |ui| { + // Not for a dialog that has since moved on. + if latest.load(Ordering::Relaxed) == serial { + fill(&ui, &meta, names); + } + }); + }); + } + + fn save(&self, elevate: bool) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let Some(dir) = self.open.borrow().as_ref().map(|o| o.dir.clone()) else { + return; + }; + let name = ui.get_appearance_name().trim().to_owned(); + let image = ui.get_appearance_image().trim().to_owned(); + let pick = PICKS + .with(|p| { + p.borrow() + .get(usize::try_from(ui.get_appearance_choice()).unwrap_or(0)) + .cloned() + }) + .unwrap_or(Pick::Default); + if !image.is_empty() && !(image.starts_with('/') && Path::new(&image).is_file()) { + ui.set_appearance_error("That image file doesn't exist. Use its full path.".into()); + return; + } + let remember = ui + .get_appearance_remember() + .then(|| self.view.borrow().clone()); + let elevation = self.elevation.clone(); + let weak = self.ui.clone(); + let remembered = remember.is_some(); + let folder = dir.clone(); + std::thread::spawn(move || { + let result = write( + &folder, + &name, + &image, + &pick, + remember, + elevate.then_some(&*elevation), + ); + let _ = weak.upgrade_in_event_loop(move |ui| match result { + Ok(()) => { + ui.invoke_close_appearance(); + ui.invoke_appearance_done(remembered); + } + Err(Error::PermissionDenied) => { + ui.set_appearance_error( + "You don't have permission to change this folder.".into(), + ); + ui.set_appearance_can_elevate(true); + } + Err(e) => ui.set_appearance_error(e.to_string().into()), + }); + }); + } +} + +/// The theme's `folder-*` icons with their files. +fn theme_icons() -> Vec<(String, Option)> { + let theme = IconTheme::load_places(); + theme + .names("folder-") + .into_iter() + .filter(|n| !n.ends_with("-open")) + .take(THEME_ICONS) + .map(|n| { + let file = theme.find(&n, 64); + (n, file) + }) + .collect() +} + +fn choice(label: &str, glyph: &str, picture: Option) -> IconChoice { + IconChoice { + glyph: glyph.into(), + has_picture: picture.is_some(), + picture: picture.unwrap_or_default(), + label: label.into(), + } +} + +/// Fills the picker with the glyphs and the theme icons, and selects what the file has. +fn fill(ui: &MainWindow, meta: &DirMeta, themed: Vec<(String, Option)>) { + let mut picks = vec![Pick::Default]; + let mut cells = vec![choice("Default", "\u{e2c7}", None)]; + for (label, glyph) in GLYPHS { + picks.push(Pick::Glyph(glyph)); + cells.push(choice(label, &glyph.to_string(), None)); + } + for (name, file) in themed { + let Some(image) = file.as_deref().and_then(look::picture) else { + continue; + }; + cells.push(choice(&name, "", Some(image))); + picks.push(Pick::Theme(name)); + } + let current = match (meta.glyph(), meta.icon()) { + (Some(g), _) => picks + .iter() + .position(|p| matches!(p, Pick::Glyph(c) if *c == g)), + (None, Some(i)) => picks + .iter() + .position(|p| matches!(p, Pick::Theme(n) if n == i)), + _ => None, + }; + // An icon that is no cell is a file path. + if let (None, Some(icon)) = (current, meta.icon()) + && icon.starts_with('/') + { + ui.set_appearance_image(icon.into()); + } + ui.set_appearance_choice(current.unwrap_or(0) as i32); + ui.set_appearance_icons(ModelRc::new(VecModel::from(cells))); + PICKS.with(|p| *p.borrow_mut() = picks); +} + +/// Writes the changes into `/.directory`: through the elevation helper when `elevated`. +fn write( + dir: &Path, + name: &str, + image: &str, + pick: &Pick, + remember: Option, + elevated: Option<&Elevation>, +) -> Result<(), Error> { + let mut meta = DirMeta::load(dir)?; + meta.set_name((!name.is_empty()).then_some(name)); + match (image, pick) { + ("", Pick::Default) => { + meta.set_icon(None); + meta.set_glyph(None); + } + ("", Pick::Glyph(g)) => { + meta.set_icon(None); + meta.set_glyph(Some(*g)); + } + ("", Pick::Theme(n)) => { + meta.set_icon(Some(n)); + meta.set_glyph(None); + } + (path, _) => { + meta.set_icon(Some(path)); + meta.set_glyph(None); + } + } + match remember { + Some(view) => meta.set_view(&view), + None => meta.clear_view(), + } + match elevated { + None => meta.save(dir).map_err(Error::from), + Some(elevation) => { + let uri = Uri::from_path(&dir.join(FILE_NAME)); + elevation.write_file(&uri, meta.to_string().as_bytes()) + } + } +} diff --git a/crates/tunal/src/folder/load.rs b/crates/tunal/src/folder/load.rs index 574e680..438ee06 100644 --- a/crates/tunal/src/folder/load.rs +++ b/crates/tunal/src/folder/load.rs @@ -6,8 +6,10 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime}; +use super::look::{self, Look}; use tunal_core::playlist::{self, Playlist}; use tunal_core::{Entry, Error, Locations, Uri, Watch, WatchEvent}; +use tunal_dirmeta::View; /// Results for the model; `generation` drops those of a folder no longer shown. pub enum Msg { @@ -18,6 +20,10 @@ pub enum Msg { Playlists(u64, Vec), /// A file in the shared playlist folder changed: look the playlists up again. PlaylistsChanged(u64), + /// The view settings the folder's own `.directory` asks for. + View(u64, View), + /// Icons and names from the `.directory` of child folders (by raw name). + Looks(u64, Vec<(Vec, Look)>), } pub enum Change { @@ -79,6 +85,9 @@ pub fn load( } } + if let Some(view) = dir.to_path().and_then(|p| look::view(&p)) { + deliver(Msg::View(generation, view)); + } let mut names: Vec<(Vec, bool)> = Vec::new(); let mut pending: Vec = Vec::new(); let mut last = Instant::now(); @@ -105,6 +114,8 @@ pub fn load( let Some(path) = dir.to_path() else { return; }; + let dirs: Vec<&Vec> = names.iter().filter(|(_, d)| *d).map(|(n, _)| n).collect(); + deliver(Msg::Looks(generation, looks(&path, dirs))); deliver(Msg::Playlists(generation, playlists(&path, &names))); // Shared playlists live elsewhere in the music folder: watch that folder too. @@ -154,6 +165,21 @@ fn stamps(dir: &Path) -> HashMap { .collect() } +/// The looks of the child folders `names` of `path` that have one. +pub fn looks<'a>( + path: &Path, + names: impl IntoIterator>, +) -> Vec<(Vec, Look)> { + use std::os::unix::ffi::OsStrExt; + names + .into_iter() + .filter_map(|n| { + let child = path.join(std::ffi::OsStr::from_bytes(n)); + Some((n.clone(), look::read(&child)?)) + }) + .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(); diff --git a/crates/tunal/src/folder/look.rs b/crates/tunal/src/folder/look.rs new file mode 100644 index 0000000..62bfcea --- /dev/null +++ b/crates/tunal/src/folder/look.rs @@ -0,0 +1,96 @@ +//! What a folder's `.directory` changes about how it is drawn: icon, display name and the +//! view settings it asks for. Read off the UI thread, cached by the file's modification time. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; +use std::time::SystemTime; + +use tunal_dirmeta::{DirMeta, FILE_NAME, View}; + +use crate::desktop_apps::IconTheme; + +/// A folder's own icon and name; each part optional. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Look { + pub name: Option, + /// A Material glyph (`Glyph` key). + pub glyph: Option, + /// An image file: the `Icon` key, resolved through the icon theme. + pub picture: Option, +} + +type Cache = Mutex)>>; + +fn cache() -> &'static Cache { + static CACHE: OnceLock = OnceLock::new(); + CACHE.get_or_init(Default::default) +} + +/// Modification time of `/.directory`; `None` when there is no such file. +fn stamp(dir: &Path) -> Option { + std::fs::metadata(dir.join(FILE_NAME)).ok()?.modified().ok() +} + +/// The look `/.directory` gives `dir`, `None` when it gives none. +pub fn read(dir: &Path) -> Option { + let Some(time) = stamp(dir) else { + cache() + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(dir); + return None; + }; + if let Some((seen, look)) = cache().lock().unwrap_or_else(|e| e.into_inner()).get(dir) + && *seen == time + { + return look.clone(); + } + let look = DirMeta::load(dir).ok().and_then(|m| from_meta(&m)); + cache() + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(dir.to_owned(), (time, look.clone())); + look +} + +pub fn from_meta(meta: &DirMeta) -> Option { + static THEME: OnceLock = OnceLock::new(); + let look = Look { + name: meta.name(), + glyph: meta.glyph(), + picture: meta + .icon() + .and_then(|i| THEME.get_or_init(IconTheme::load_places).find(i, 64)), + }; + (look != Look::default()).then_some(look) +} + +/// The view settings `/.directory` asks for, `None` when it asks for none. +pub fn view(dir: &Path) -> Option { + stamp(dir)?; + let meta = DirMeta::load(dir).ok()?; + meta.has_view().then(|| meta.view()) +} + +/// Reads `/.directory`, lets `f` change it and writes it back (the file goes away when +/// nothing is left in it). +pub fn write_meta(dir: &Path, f: impl FnOnce(&mut DirMeta)) -> std::io::Result<()> { + let mut meta = DirMeta::load(dir)?; + f(&mut meta); + meta.save(dir) +} + +/// The image at `path` as the views draw it, decoded once. +pub fn picture(path: &Path) -> Option { + thread_local! { + static IMAGES: std::cell::RefCell>> = Default::default(); + } + IMAGES.with(|images| { + images + .borrow_mut() + .entry(path.to_owned()) + .or_insert_with(|| slint::Image::load_from_path(path).ok()) + .clone() + }) +} diff --git a/crates/tunal/src/folder/mod.rs b/crates/tunal/src/folder/mod.rs index 17f8e77..57d31de 100644 --- a/crates/tunal/src/folder/mod.rs +++ b/crates/tunal/src/folder/mod.rs @@ -2,8 +2,10 @@ //! (loaded and watched off the UI thread), sorted, grouped and filtered into rows, plus the //! selection, the grid's lines and the list motion of each change. +pub mod appearance; pub mod format; mod load; +pub mod look; mod motion; mod sort; @@ -24,6 +26,7 @@ use crate::{ }; pub use load::Deliver; use load::{Change, Msg}; +use look::Look; use motion::{Anim, Clock, Key, Old}; pub use sort::{GroupBy, Settings, SortKey}; @@ -34,6 +37,8 @@ pub struct Item { pub key: String, pub is_dir: bool, pub category: Category, + /// The folder's own icon and name from its `.directory`. + pub look: Option, } impl Item { @@ -43,9 +48,30 @@ impl Item { is_dir: entry.kind.is_dir(), category: Category::of(&entry), entry, + look: None, } } + fn with_look(mut self, look: Option) -> Self { + self.set_look(look); + self + } + + /// Sets the look; a display name from it sorts and filters in place of the real name. + fn set_look(&mut self, look: Option) { + let name = look.as_ref().and_then(|l| l.name.as_deref()); + self.key = name.unwrap_or(&self.entry.display_name).to_lowercase(); + self.look = look; + } + + /// The name shown for the entry. + fn shown_name(&self) -> &str { + self.look + .as_ref() + .and_then(|l| l.name.as_deref()) + .unwrap_or(&self.entry.display_name) + } + /// Folders count as empty for size order. pub fn size(&self) -> u64 { if self.is_dir { 0 } else { self.entry.size } @@ -78,6 +104,10 @@ struct State { /// Raw name → row, for the rows shown. row_of: HashMap, usize>, settings: Settings, + /// The pane's settings before the folder's own view settings were applied. + inherited: Option, + /// The folder keeps its view settings in its `.directory`: changes are written back. + remembered: bool, playlists: Vec, /// The playlist `SortKey::Playlist` refers to, kept across lookups. playlist_path: Option, @@ -134,6 +164,8 @@ impl FolderModel { rows: Vec::new(), row_of: HashMap::new(), settings: Settings::from_config(&config::load("settings")), + inherited: None, + remembered: false, playlists: Vec::new(), playlist_path: None, selected: HashSet::new(), @@ -216,6 +248,10 @@ impl FolderModel { s.anchor = None; s.edit = None; s.pending = None; + if let Some(base) = s.inherited.take() { + s.settings = base; + } + s.remembered = false; s.settings.filter.clear(); s.playlist_path = None; if let SortKey::Playlist(_) = s.settings.key { @@ -254,11 +290,15 @@ impl FolderModel { Msg::Changed(g, changes) if g == current => { // Reads are reported too: only entries whose stat differs count. let mut changed = false; + let mut new_dirs = Vec::new(); for change in changes { match change { Change::Upsert(entry) => { let same = s.by_name.get(&entry.name).map(|&i| &s.items[i].entry); if same != Some(&entry) { + if same.is_none() && entry.kind.is_dir() { + new_dirs.push(entry.name.clone()); + } upsert(&mut s, entry); changed = true; } @@ -272,8 +312,17 @@ impl FolderModel { // A track or playlist appearing or leaving can change which playlists place // entries here (outside the music folder the lookup returns at once). self.refresh_playlists(&s); + self.refresh_looks(&s, new_dirs); } Msg::PlaylistsChanged(g) if g == current => self.refresh_playlists(&s), + Msg::View(g, view) if g == current => apply_view(&mut s, &view), + Msg::Looks(g, looks) if g == current => { + for (name, look) in looks { + if let Some(&i) = s.by_name.get(&name) { + s.items[i].set_look(Some(look)); + } + } + } Msg::Playlists(g, found) if g == current => { s.playlists = found; if let Some(path) = s.playlist_path.clone() { @@ -295,6 +344,80 @@ impl FolderModel { self.emit(); } + /// The pane's settings as a folder would keep them in its `.directory`. + pub fn view_snapshot(&self) -> tunal_dirmeta::View { + view_of(&self.state.borrow()) + } + + /// True when the folder shown keeps its view settings in its `.directory`. + pub fn remembers_view(&self) -> bool { + self.state.borrow().remembered + } + + /// The folder shown now remembers (or forgets) its view: from here on changes are written + /// back to its `.directory`. + pub fn set_remembers_view(&self, on: bool) { + let mut s = self.state.borrow_mut(); + if s.remembered == on { + return; + } + s.remembered = on; + if on && s.inherited.is_none() { + s.inherited = Some(s.settings.clone()); + } + } + + /// Reads the icons and names of the child folders again (their `.directory` changed). + pub fn reload_looks(&self) { + let s = self.state.borrow(); + let names = s + .items + .iter() + .filter(|i| i.is_dir) + .map(|i| i.entry.name.clone()) + .collect(); + self.refresh_looks(&s, names); + } + + /// A folder that remembers its view keeps it current in its `.directory` (off-thread; a + /// failure only shows in the appearance dialog, which asks for elevation). + fn write_view(&self, s: &State) { + let Some(dir) = s + .dir + .as_ref() + .and_then(Uri::to_path) + .filter(|_| s.remembered) + else { + return; + }; + let view = view_of(s); + std::thread::spawn(move || { + if let Err(e) = look::write_meta(&dir, |m| m.set_view(&view)) { + eprintln!("tunal: couldn't save {}: {e}", dir.display()); + } + }); + } + + /// Reads the `.directory` of the new folders `names` off the UI thread. + fn refresh_looks(&self, s: &State, names: Vec>) { + let Some(path) = s + .dir + .as_ref() + .and_then(Uri::to_path) + .filter(|_| !names.is_empty()) + else { + return; + }; + let generation = s.generation; + let deliver = self.deliver.clone(); + std::thread::spawn(move || { + let looks = load::looks(&path, &names); + if !looks.is_empty() { + deliver(Msg::Looks(generation, looks)); + } + }); + } + fn refresh_playlists(&self, s: &State) { let Some(path) = s.dir.as_ref().and_then(Uri::to_path) else { return; @@ -410,6 +533,7 @@ impl FolderModel { return; } s.settings.mode = mode; + self.write_view(&s); still(&mut s) }; if ghosts { @@ -527,6 +651,7 @@ impl FolderModel { f(&mut s.settings); rebuild(&mut s); self.animate(&mut s, old); + self.write_view(&s); drop(s); self.notify.reset(); self.emit(); @@ -1102,7 +1227,10 @@ fn still(s: &mut State) -> bool { fn upsert(s: &mut State, entry: Entry) { match s.by_name.get(&entry.name) { - Some(&i) => s.items[i] = Item::new(entry), + Some(&i) => { + let look = s.items[i].look.take(); + s.items[i] = Item::new(entry).with_look(look); + } None => { s.by_name.insert(entry.name.clone(), s.items.len()); s.items.push(Item::new(entry)); @@ -1206,6 +1334,91 @@ fn base_len(s: &State, name: &[u8]) -> usize { } } +/// Applies the view settings a folder's `.directory` asks for, keeping the pane's own to +/// return to when another folder opens. +fn apply_view(s: &mut State, view: &tunal_dirmeta::View) { + s.inherited = Some(s.settings.clone()); + s.remembered = true; + let set = &mut s.settings; + match view.mode.as_deref() { + Some("details") => set.mode = ViewMode::Details, + Some("grid") => set.mode = ViewMode::Grid, + _ => {} + } + match view.sort.as_deref() { + Some("name") => set.key = SortKey::Name, + Some("size") => set.key = SortKey::Size, + Some("type") => set.key = SortKey::Type, + Some("modified") => set.key = SortKey::Modified, + // Chosen once the playlists are found. + Some("playlist") => set.key = SortKey::Name, + _ => {} + } + if let Some(d) = view.descending { + set.descending = d; + } + match view.group.as_deref() { + Some("none") => set.group = GroupBy::None, + Some("type") => set.group = GroupBy::Type, + Some("modified") => set.group = GroupBy::Modified, + Some("size") => set.group = GroupBy::Size, + _ => {} + } + if let Some(h) = view.hidden { + set.show_hidden = h; + } + if view.sort.as_deref() == Some("playlist") + && let (Some(dir), Some(file)) = (s.dir.as_ref().and_then(Uri::to_path), &view.playlist) + { + s.playlist_path = Some(dir.join(file)); + } +} + +/// The settings as a folder keeps them in its `.directory`. +fn view_of(s: &State) -> tunal_dirmeta::View { + let set = &s.settings; + let playlist = match set.key { + SortKey::Playlist(_) => s + .playlist_path + .as_ref() + .and_then(|p| p.file_name()) + .map(|n| n.to_string_lossy().into_owned()), + _ => None, + }; + tunal_dirmeta::View { + mode: Some( + match set.mode { + ViewMode::Grid => "grid", + _ => "details", + } + .into(), + ), + sort: Some( + match set.key { + SortKey::Name => "name", + SortKey::Size => "size", + SortKey::Type => "type", + SortKey::Modified => "modified", + SortKey::Playlist(_) => "playlist", + } + .into(), + ), + descending: Some(set.descending), + group: Some( + match set.group { + GroupBy::None => "none", + GroupBy::Type => "type", + GroupBy::Modified => "modified", + GroupBy::Size => "size", + } + .into(), + ), + hidden: Some(set.show_hidden), + previews: None, + playlist, + } +} + /// Recomputes `row_of` from `rows`. fn index(s: &mut State) { s.row_of = s @@ -1245,10 +1458,25 @@ fn row_data(s: &State, row: usize) -> Option { Row::Item(i) => { let item = &s.items[*i]; let entry = &item.entry; + let look = item.look.as_ref(); + let picture = look + .and_then(|l| l.picture.as_deref()) + .and_then(look::picture); DetailRow { header: false, - name: entry.display_name.as_str().into(), - glyph: item.category.glyph().into(), + // Editing shows the real name: that is what a rename changes. + name: if s.edit.as_ref() == Some(&entry.name) { + entry.display_name.as_str() + } else { + item.shown_name() + } + .into(), + glyph: look + .and_then(|l| l.glyph) + .map_or(item.category.glyph().into(), |g| g.to_string().into()), + shape_glyph: item.category.glyph().into(), + has_picture: picture.is_some(), + picture: picture.unwrap_or_default(), badge: icons::link_badge(&entry.kind).into(), size: if item.is_dir { SharedString::new() diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs index 87472ce..ca0748b 100644 --- a/crates/tunal/src/main.rs +++ b/crates/tunal/src/main.rs @@ -75,6 +75,10 @@ fn window( { ui.invoke_show_settings(page); } + // `TUNAL_APPEARANCE=1` opens the folder appearance dialog for the folder shown. + if std::env::var_os("TUNAL_APPEARANCE").is_some() { + shell.run_action(actions::Action::Appearance); + } Ok((ui, shell)) } diff --git a/crates/tunal/src/menus.rs b/crates/tunal/src/menus.rs index 8c55458..e419c1f 100644 --- a/crates/tunal/src/menus.rs +++ b/crates/tunal/src/menus.rs @@ -72,6 +72,7 @@ impl Context { "trash", "delete", "-", + "appearance", "properties", ], Self::Multiple => &[ @@ -91,6 +92,7 @@ impl Context { "-", "copy-path", "-", + "appearance", "properties", "settings", ], diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs index 70ac290..afc4e15 100644 --- a/crates/tunal/src/shell/mod.rs +++ b/crates/tunal/src/shell/mod.rs @@ -430,7 +430,14 @@ impl Shell { } /// Tab bar selection, toolbar, breadcrumb, sort menu, sidebar and status bar. - fn show_chrome(&self) { + /// Runs an action as if chosen from a menu (screenshot hooks). + pub(crate) fn run_action(&self, action: crate::actions::Action) { + if let Some(actions) = self.actions.get() { + actions.run(action); + } + } + + pub(crate) fn show_chrome(&self) { let Some(ui) = self.ui.upgrade() else { return; }; @@ -456,6 +463,7 @@ impl Shell { .into_iter() .map(|s| Crumb { name: s.name.into(), + tip: s.tip.into(), glyph: s.glyph.into(), }) .collect(); @@ -474,10 +482,14 @@ impl Shell { let items: Vec = places .items(section) .iter() - .map(|p| PlaceItem { - name: p.name.as_str().into(), - glyph: p.glyph.into(), - current: Some(&p.uri) == dir, + .map(|p| { + let (name, tip) = path::shown_name(&p.uri, p.name.clone()); + PlaceItem { + name: name.into(), + tip: tip.into(), + glyph: p.glyph.into(), + current: Some(&p.uri) == dir, + } }) .collect(); SidebarSection { diff --git a/crates/tunal/src/shell/path.rs b/crates/tunal/src/shell/path.rs index 66b4581..10b9c5f 100644 --- a/crates/tunal/src/shell/path.rs +++ b/crates/tunal/src/shell/path.rs @@ -10,6 +10,8 @@ use super::places::{self, FOLDER, HOME, REMOTE, ROOT, TRASH_GLYPH}; pub struct Segment { pub name: String, + /// The real name when the folder shows another one (from its `.directory`). + pub tip: String, pub glyph: &'static str, pub uri: Uri, } @@ -34,8 +36,10 @@ pub fn segments(uri: &Uri) -> Vec { None => root_name(u), } }; + let (name, tip) = shown_name(u, name); Segment { name, + tip, glyph, uri: u.clone(), } @@ -43,6 +47,19 @@ pub fn segments(uri: &Uri) -> Vec { .collect() } +/// The name a local folder is shown by (its `.directory` may give one) and, when that differs, +/// the real name for a tooltip. +pub fn shown_name(uri: &Uri, name: String) -> (String, String) { + match uri + .to_path() + .and_then(|p| crate::folder::look::read(&p)) + .and_then(|l| l.name) + { + Some(custom) if custom != name => (custom, name), + _ => (name, String::new()), + } +} + fn root_name(uri: &Uri) -> (String, &'static str) { match uri.scheme() { FILE => ("File system".to_owned(), ROOT), diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint index 0ad99e2..3ea6156 100644 --- a/crates/tunal/ui/app.slint +++ b/crates/tunal/ui/app.slint @@ -22,12 +22,13 @@ import { ConfirmDialog } from "dialogs/confirm.slint"; import { ErrorsDialog } from "dialogs/errors.slint"; import { PropertiesDialog, PropertiesInfo, PropRow } from "dialogs/properties.slint"; import { OpenWithDialog, AppRow } from "dialogs/open-with.slint"; +import { FolderAppearanceDialog, IconChoice } from "dialogs/folder-appearance.slint"; import { SettingsDialog, SettingsData, EditRow } from "dialogs/settings.slint"; import { Dnd, DropAction, DropMenu, DropTarget } from "components/drop-menu.slint"; export { Theme, Shapes, ShapeKind, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode, GridRow } export { ButtonKind, TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem, ToastData, ToastProgress, DialogAction, ConflictInfo, SettingsData, EditRow } -export { PropertiesInfo, PropRow, AppRow, Dnd, DropAction, DropTarget } +export { PropertiesInfo, PropRow, AppRow, IconChoice, Dnd, DropAction, DropTarget } export { Gallery, GalleryPage } from "gallery.slint"; // The window: sidebar, tab bar, toolbar with the breadcrumb, the panes of the current tab @@ -122,6 +123,18 @@ export component MainWindow inherits Window { callback menu-separator-added(); callback menu-reset(); + // Folder appearance (folder/appearance.rs). + in property <[IconChoice]> appearance-icons; + in-out property appearance-choice; + in-out property appearance-name; + in-out property appearance-image; + in-out property appearance-remember; + in property appearance-placeholder; + in property appearance-error; + in property appearance-can-elevate; + callback appearance-saved(bool); + callback appearance-done(bool); + // Properties (properties.rs) and Open with (open.rs). in property properties; callback properties-closed(); @@ -213,6 +226,14 @@ export component MainWindow inherits Window { properties-dialog.close(); } + public function show-appearance() { + appearance-dialog.show(); + } + + public function close-appearance() { + appearance-dialog.close(); + } + public function show-open-with() { open-with-dialog.show(); } @@ -674,6 +695,22 @@ export component MainWindow inherits Window { } } + appearance-dialog := FolderAppearanceDialog { + width: 100%; + height: 100%; + icons: root.appearance-icons; + choice <=> root.appearance-choice; + name-text <=> root.appearance-name; + image-path <=> root.appearance-image; + remember <=> root.appearance-remember; + placeholder: root.appearance-placeholder; + error: root.appearance-error; + can-elevate: root.appearance-can-elevate; + saved(elevate) => { + root.appearance-saved(elevate); + } + } + errors-dialog := ErrorsDialog { width: 100%; height: 100%; diff --git a/crates/tunal/ui/components/list-row.slint b/crates/tunal/ui/components/list-row.slint index 4950646..c5de600 100644 --- a/crates/tunal/ui/components/list-row.slint +++ b/crates/tunal/ui/components/list-row.slint @@ -17,6 +17,9 @@ export component ListRow inherits StateLayer { in property selected; // Draws the icon in a shaped tonal container that morphs to `active-shape` when selected. in property shaped; + // An image drawn in the shaped container in place of the glyph. + in property picture; + in property has-picture; in property shape: ShapeKind.circle; in property active-shape: ShapeKind.cookie9; in property shape-size: 36px; @@ -76,6 +79,8 @@ export component ListRow inherits StateLayer { active-shape: root.active-shape; active: root.selected; glyph: root.icon; + picture: root.picture; + has-picture: root.has-picture; fill: root.enabled ? root.shape-fill : Theme.on-surface.with-alpha(Theme.disabled-container); active-fill: root.enabled ? Theme.primary : Theme.on-surface.with-alpha(Theme.disabled-container); glyph-color: !root.enabled ? root.detail-color : root.selected ? Theme.on-primary : root.shape-ink; diff --git a/crates/tunal/ui/components/shape.slint b/crates/tunal/ui/components/shape.slint index 1aa5916..fb43bee 100644 --- a/crates/tunal/ui/components/shape.slint +++ b/crates/tunal/ui/components/shape.slint @@ -44,6 +44,9 @@ export component Shape { in property fill: Theme.secondary-container; in property active-fill: root.fill; in property glyph; + // An image drawn in place of the glyph (a folder's own icon). + in property picture; + in property has-picture; in property glyph-color: Theme.on-secondary-container; in property size: 40px; // Glyph size as a share of the container. @@ -80,7 +83,16 @@ export component Shape { } } - if root.glyph != "": Icon { + if root.has-picture: Image { + x: (root.width - self.width) / 2; + y: (root.height - self.height) / 2; + width: root.size * root.glyph-ratio * 1.3; + height: self.width; + source: root.picture; + image-fit: contain; + } + + if root.glyph != "" && !root.has-picture: Icon { x: (root.width - self.width) / 2; y: (root.height - self.height) / 2; glyph: root.glyph; diff --git a/crates/tunal/ui/components/text-field.slint b/crates/tunal/ui/components/text-field.slint index 5e983c5..2525c8c 100644 --- a/crates/tunal/ui/components/text-field.slint +++ b/crates/tunal/ui/components/text-field.slint @@ -15,6 +15,10 @@ export component TextField { in property enabled: true; in property force-state: ForceState.none; in-out property text; + public function focus-input() { + input.focus(); + } + callback edited(text: string); callback accepted(text: string); diff --git a/crates/tunal/ui/dialogs/folder-appearance.slint b/crates/tunal/ui/dialogs/folder-appearance.slint new file mode 100644 index 0000000..faca42b --- /dev/null +++ b/crates/tunal/ui/dialogs/folder-appearance.slint @@ -0,0 +1,155 @@ +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Icon, Icons } from "../components/icon.slint"; +import { Dialog } from "../components/dialog.slint"; +import { ButtonKind } from "../components/button.slint"; +import { StateLayer } from "../components/state-layer.slint"; +import { Switch } from "../components/switch.slint"; +import { TextField } from "../components/text-field.slint"; +import { Shape, ShapeKind } from "../components/shape.slint"; + +// One icon the picker offers: a Material glyph, or an image from the icon theme. The first +// one is the folder's default look. +export struct IconChoice { + glyph: string, + picture: image, + has-picture: bool, + label: string, +} + +component Cell inherits StateLayer { + in property choice; + in property selected; + + width: 44px; + height: 44px; + border-radius: Theme.corner-md; + focusable: false; + tooltip: root.choice.label; + accessible-role: radio-button; + accessible-label: root.choice.label; + accessible-checkable: true; + accessible-checked: root.selected; + + Rectangle { + border-radius: parent.border-radius; + background: Theme.secondary-container; + opacity: root.selected ? 1 : 0; + animate opacity { + duration: Motion.time(Motion.short4); + easing: Motion.standard; + } + } + + Shape { + size: 32px; + x: (root.width - self.width) / 2; + y: (root.height - self.height) / 2; + shape: ShapeKind.cookie9; + fill: root.selected ? Theme.primary : Theme.primary-container; + glyph: root.choice.glyph; + picture: root.choice.picture; + has-picture: root.choice.has-picture; + glyph-color: root.selected ? Theme.on-primary : Theme.on-primary-container; + } +} + +// Display name, icon and per-folder view settings of one folder. `saved` runs on Save with the +// fields; the owner closes the dialog, or sets `error` (with `can-elevate` after a permission +// failure, which turns Save into "Save as administrator"). +export component FolderAppearanceDialog inherits Dialog { + glyph: Icons.folder; + in property <[IconChoice]> icons; + in-out property choice; + in-out property name-text; + in-out property image-path; + in-out property remember; + in property placeholder; + in property error; + in property can-elevate; + callback saved(bool); + + title: "Folder appearance"; + dialog-width: 456px; + actions: [ + { text: "Cancel", kind: ButtonKind.text }, + { text: root.can-elevate ? "Save as administrator" : "Save", kind: ButtonKind.filled } + ]; + default-action: 1; + cancel-action: 0; + content-focus: true; + focus-content => { + name-field.focus-input(); + } + action(i) => { + if i == 1 { + root.saved(root.can-elevate); + } else { + root.close(); + } + } + + name-field := TextField { + label: "Display name"; + placeholder: root.placeholder; + text <=> root.name-text; + accepted => { + root.saved(root.can-elevate); + } + } + + Text { + text: "Icon"; + color: Theme.on-surface-variant; + font-size: Theme.label-medium.size; + font-weight: Theme.label-medium.weight; + } + + // Wraps in rows of cells; the height follows the number of choices. + property columns: 9; + Rectangle { + height: ceil(root.icons.length / root.columns) * 44px; + + for item[i] in root.icons: Cell { + x: mod(i, root.columns) * 46px; + y: floor(i / root.columns) * 44px; + choice: item; + selected: i == root.choice && root.image-path == ""; + clicked => { + root.choice = i; + root.image-path = ""; + } + } + } + + TextField { + label: "Or an image file"; + placeholder: "/path/to/picture.png"; + text <=> root.image-path; + } + + HorizontalLayout { + spacing: Theme.space-3; + + Text { + horizontal-stretch: 1; + text: "Remember this view for the folder"; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + } + + Switch { + checked <=> root.remember; + accessible-label: "Remember this view for the folder"; + } + } + + if root.error != "": Text { + text: root.error; + color: Theme.error; + font-size: Theme.body-small.size; + wrap: word-wrap; + } +} diff --git a/crates/tunal/ui/shell/breadcrumb.slint b/crates/tunal/ui/shell/breadcrumb.slint index e9d3efb..a0ad48b 100644 --- a/crates/tunal/ui/shell/breadcrumb.slint +++ b/crates/tunal/ui/shell/breadcrumb.slint @@ -7,6 +7,8 @@ import { DropTarget, DropZone } from "../components/drop-menu.slint"; // One segment of the path: the root (glyph and name) or a folder. export struct Crumb { name: string, + // The real name of a folder shown by another one. + tip: string, glyph: string, } @@ -19,6 +21,7 @@ export struct Completion { component CrumbChip inherits StateLayer { in property name; in property glyph; + in property tip; in property last; // Only this chip gives up width (eliding its name) when the bar is short. in property shrink; @@ -32,6 +35,7 @@ component CrumbChip inherits StateLayer { squeeze: Motion.squeeze; tint: root.content; focusable: false; + tooltip: root.tip; accessible-role: button; accessible-label: root.name; accessible-action-default => { @@ -146,6 +150,7 @@ export component Breadcrumb inherits Rectangle { alignment: center; CrumbChip { name: crumb.name; + tip: crumb.tip; glyph: crumb.glyph; last: i == root.crumbs.length - 1; shrink: i == 0 && root.crumbs.length > 1; diff --git a/crates/tunal/ui/shell/sidebar.slint b/crates/tunal/ui/shell/sidebar.slint index 0d40cc7..bf9c89b 100644 --- a/crates/tunal/ui/shell/sidebar.slint +++ b/crates/tunal/ui/shell/sidebar.slint @@ -9,6 +9,8 @@ import { Dnd, DropTarget, DropZone } from "../components/drop-menu.slint"; export struct PlaceItem { name: string, + // The real name of a folder shown by another one. + tip: string, glyph: string, // Shows the selection fill: the active pane is at this place. current: bool, @@ -184,6 +186,7 @@ export component Sidebar inherits Rectangle { height: root.row-height; icon: item.glyph; title: item.name; + tooltip: item.tip; selected: item.current; shaped: true; shape: root.shapes[mod(i, root.shapes.length)]; diff --git a/crates/tunal/ui/views/details-view.slint b/crates/tunal/ui/views/details-view.slint index 19823ad..b1fa363 100644 --- a/crates/tunal/ui/views/details-view.slint +++ b/crates/tunal/ui/views/details-view.slint @@ -23,6 +23,11 @@ export struct DetailRow { header: bool, name: string, glyph: string, + // The category's glyph: picks the shape and colours (a folder with its own glyph stays a folder). + shape-glyph: string, + // The folder's own image icon, drawn in place of the glyph. + picture: image, + has-picture: bool, badge: string, size: string, kind: string, @@ -610,10 +615,12 @@ export component DetailsView inherits Rectangle { badge: row.badge; shaped: true; shape-size: 32px; - shape: FileShapes.shape(row.glyph); - active-shape: FileShapes.active-shape(row.glyph); - shape-fill: FileShapes.fill(row.glyph); - shape-ink: FileShapes.ink(row.glyph); + picture: row.picture; + has-picture: row.has-picture; + shape: FileShapes.shape(row.shape-glyph); + active-shape: FileShapes.active-shape(row.shape-glyph); + shape-fill: FileShapes.fill(row.shape-glyph); + shape-ink: FileShapes.ink(row.shape-glyph); title: row.name; selected: row.selected; editing: row.editing; diff --git a/crates/tunal/ui/views/grid-view.slint b/crates/tunal/ui/views/grid-view.slint index 2000306..8916b28 100644 --- a/crates/tunal/ui/views/grid-view.slint +++ b/crates/tunal/ui/views/grid-view.slint @@ -79,13 +79,15 @@ component GridCell inherits StateLayer { Shape { size: Grid.icon-size; - shape: FileShapes.shape(root.entry.glyph); - active-shape: FileShapes.active-shape(root.entry.glyph); + shape: FileShapes.shape(root.entry.shape-glyph); + active-shape: FileShapes.active-shape(root.entry.shape-glyph); active: root.entry.selected; - fill: FileShapes.fill(root.entry.glyph); + fill: FileShapes.fill(root.entry.shape-glyph); active-fill: Theme.primary; glyph: root.entry.glyph; - glyph-color: root.entry.selected ? Theme.on-primary : FileShapes.ink(root.entry.glyph); + picture: root.entry.picture; + has-picture: root.entry.has-picture; + glyph-color: root.entry.selected ? Theme.on-primary : FileShapes.ink(root.entry.shape-glyph); glyph-ratio: 0.5; if root.entry.badge != "": Icon { diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 33f3cb4..8931773 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -160,6 +160,16 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: no live window (real pointer, Shift/Ctrl keys, tab hover switch, menu choice running a job); count badge not looked at (single-item image only). - Later: autoscroll at list edges while dragging; select the row a drag starts from; spring-open folders on hover; breadcrumb crumbs overlap in a long path (seen in S014 smoke, already in HEAD before S014). +## S015 — `.directory` folder metadata +- Done: `tunal-dirmeta` `DirMeta` (`parse/load/save`, lossless line store: comments, blank lines, unknown groups/keys, `Name[de]`, missing final newline kept; `get/set(group, key, Option)`, empty group dropped; empty file removed on save). Typed: `icon/set_icon` (`[Desktop Entry] Icon`), `name/set_name` (localized by LC_ALL/LC_MESSAGES/LANG), `glyph/set_glyph` and `view/set_view/has_view/clear_view` in `[X-Tunal]` (`Glyph`, `View` details|grid, `Sort` name|size|type|modified|playlist, `SortOrder`, `Group`, `ShowHidden`, `Previews` (read/written, not applied: no previews setting yet), `Playlist` file name for D-021). +- Per folder: view mode, sort + order, grouping, hidden files, playlist sort. Opening a folder with them applies them over the pane's settings and restores the pane's own on leaving (`inherited`); a folder that remembers its view writes later changes back (off-thread). +- Apply: `folder/look.rs` (`Look {name, glyph, picture}` read off-thread after the listing, cached by `.directory` mtime; `Icon` resolved via `IconTheme::load_places()`); rows show name/glyph/picture, shape stays the folder's (`DetailRow.shape-glyph`, `picture`, `has-picture`); the display name sorts and filters, rename edits the real name. Breadcrumb and sidebar show the name with the real name as tooltip (`Crumb.tip`, `PlaceItem.tip`). +- Dialog: action `appearance` ("Folder appearance…", in the folder and empty-area menus; one selected folder, else the folder shown): `ui/dialogs/folder-appearance.slint`, `folder/appearance.rs`. Display name, icon picker (Default, 17 Material glyphs, theme `folder-*` icons), image path field, "remember view" switch. Save runs off-thread; `PermissionDenied` shows an error and turns Save into "Save as administrator" (`Elevation::write_file` from S016). +- Small changes outside the plan files: `desktop_apps.rs` (`IconTheme::load_places`, `names`), `TextField.focus-input`, `Shape`/`ListRow` picture, `actions.rs`/`menus.rs`/`shell/mod.rs` (action, `run_action`, `show_chrome` pub(crate)), `main.rs` (`TUNAL_APPEARANCE`). +- Verified: workspace build, clippy -D warnings, fmt --check; round trip with `cargo run -p tunal-dirmeta --example roundtrip -- ` (diff = the Icon line only); screenshots: folder list with custom names, glyphs and a theme image icon; the dialog. +- Not done: no live window (menu click, real save, polkit prompt via "Save as administrator" is a user check); previews not applied; image picker is a path field (no file chooser); grid view not looked at; sidebar/crumb names only for local folders. +- Later: file chooser for the image; `Previews` once a setting exists; names for places other than local folders. + ## Later - (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034. -