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 <[email protected]>
This commit is contained in:
astar76 2026-11-18 20:28:31 -06:00
commit 7ba6ae8eae
27 changed files with 1376 additions and 28 deletions

View file

@ -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 <png> [--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 -- <dir> --screenshot <png> --size 1000x700` (`XDG_CONFIG_HOME=<scratch>`) | settings dialog page over a folder | S013 |
| `TUNAL_DRAG=x1,y1,x2,y2[,hold] TUNAL_REDUCED_MOTION=1 cargo run -p tunal -- <dir> --screenshot <png> --size 1200x760` (`XDG_CONFIG_HOME=<scratch>`) | drags between window points and drops (drop menu) or holds (glow + drag image) before the frame | S014 |
| `TUNAL_APPEARANCE=1 XDG_CONFIG_HOME=<scratch> cargo run -p tunal -- <dir> --screenshot <png> --size 1000x760` | folder appearance dialog for `<dir>` (theme icons looked up at once); `cargo run -p tunal-dirmeta --example roundtrip -- <dir>` sets `Icon` in `<dir>/.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.

1
Cargo.lock generated
View file

@ -5544,6 +5544,7 @@ dependencies = [
"slint-build",
"toml",
"tunal-core",
"tunal-dirmeta",
"tunal-theme",
"zbus",
]

View file

@ -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

View file

@ -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

View file

@ -0,0 +1,15 @@
//! Smoke run: edits `Icon` in a sample with comments and unknown keys; prints the result.
//! Usage: roundtrip <dir> (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");
}

View file

@ -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<String>,
/// 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 `<dir>/.directory`; a missing file gives an empty one.
pub fn load(dir: &Path) -> io::Result<Self> {
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 `<dir>/.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<String> {
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<String> {
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<char> {
self.tunal("Glyph")?.chars().next()
}
pub fn set_glyph(&mut self, glyph: Option<char>) {
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<String>,
pub sort: Option<String>,
pub descending: Option<bool>,
pub group: Option<String>,
pub hidden: Option<bool>,
pub previews: Option<bool>,
/// File name of the playlist the folder is sorted by (D-021).
pub playlist: Option<String>,
}
/// `[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())
}
}
}

View file

@ -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

View file

@ -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<Menus>,
opener: Rc<Opener>,
properties: Rc<Properties>,
appearance: Rc<Appearance>,
}
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

View file

@ -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<ThemeDir> {
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<PathBuf> = 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<String> {
let mut names: Vec<String> = 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).

View file

@ -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<Vec<Pick>> = const { RefCell::new(Vec::new()) };
}
type Saved = Box<dyn Fn(&Path, bool)>;
pub struct Appearance {
ui: slint::Weak<MainWindow>,
elevation: Arc<Elevation>,
open: RefCell<Option<Open>>,
/// Called after a save with the folder and whether it now remembers a view.
saved: RefCell<Saved>,
/// The view settings to keep when "remember" is on, as the pane shows them now.
view: RefCell<View>,
/// Bumped per opening: a late icon lookup for an earlier one is dropped.
serial: Arc<AtomicU64>,
}
impl Appearance {
pub fn attach(ui: &MainWindow, elevation: Arc<Elevation>) -> Rc<Self> {
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<PathBuf>)> {
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<slint::Image>) -> 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<PathBuf>)>) {
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 `<dir>/.directory`: through the elevation helper when `elevated`.
fn write(
dir: &Path,
name: &str,
image: &str,
pick: &Pick,
remember: Option<View>,
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())
}
}
}

View file

@ -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<Playlist>),
/// 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<u8>, 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<u8>, bool)> = Vec::new();
let mut pending: Vec<Entry> = 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<u8>> = 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<PathBuf, Stamp> {
.collect()
}
/// The looks of the child folders `names` of `path` that have one.
pub fn looks<'a>(
path: &Path,
names: impl IntoIterator<Item = &'a Vec<u8>>,
) -> Vec<(Vec<u8>, 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<u8>, bool)]) -> Vec<Playlist> {
let entries: Vec<(&[u8], bool)> = names.iter().map(|(n, d)| (n.as_slice(), *d)).collect();

View file

@ -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<String>,
/// A Material glyph (`Glyph` key).
pub glyph: Option<char>,
/// An image file: the `Icon` key, resolved through the icon theme.
pub picture: Option<PathBuf>,
}
type Cache = Mutex<HashMap<PathBuf, (SystemTime, Option<Look>)>>;
fn cache() -> &'static Cache {
static CACHE: OnceLock<Cache> = OnceLock::new();
CACHE.get_or_init(Default::default)
}
/// Modification time of `<dir>/.directory`; `None` when there is no such file.
fn stamp(dir: &Path) -> Option<SystemTime> {
std::fs::metadata(dir.join(FILE_NAME)).ok()?.modified().ok()
}
/// The look `<dir>/.directory` gives `dir`, `None` when it gives none.
pub fn read(dir: &Path) -> Option<Look> {
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<Look> {
static THEME: OnceLock<IconTheme> = 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 `<dir>/.directory` asks for, `None` when it asks for none.
pub fn view(dir: &Path) -> Option<View> {
stamp(dir)?;
let meta = DirMeta::load(dir).ok()?;
meta.has_view().then(|| meta.view())
}
/// Reads `<dir>/.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<slint::Image> {
thread_local! {
static IMAGES: std::cell::RefCell<HashMap<PathBuf, Option<slint::Image>>> = Default::default();
}
IMAGES.with(|images| {
images
.borrow_mut()
.entry(path.to_owned())
.or_insert_with(|| slint::Image::load_from_path(path).ok())
.clone()
})
}

View file

@ -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<Look>,
}
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<Look>) -> 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<Look>) {
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<Vec<u8>, usize>,
settings: Settings,
/// The pane's settings before the folder's own view settings were applied.
inherited: Option<Settings>,
/// The folder keeps its view settings in its `.directory`: changes are written back.
remembered: bool,
playlists: Vec<Playlist>,
/// The playlist `SortKey::Playlist` refers to, kept across lookups.
playlist_path: Option<std::path::PathBuf>,
@ -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<Vec<u8>>) {
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<DetailRow> {
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()

View file

@ -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))
}

View file

@ -72,6 +72,7 @@ impl Context {
"trash",
"delete",
"-",
"appearance",
"properties",
],
Self::Multiple => &[
@ -91,6 +92,7 @@ impl Context {
"-",
"copy-path",
"-",
"appearance",
"properties",
"settings",
],

View file

@ -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<PlaceItem> = 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 {

View file

@ -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<Segment> {
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<Segment> {
.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),

View file

@ -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 <int> appearance-choice;
in-out property <string> appearance-name;
in-out property <string> appearance-image;
in-out property <bool> appearance-remember;
in property <string> appearance-placeholder;
in property <string> appearance-error;
in property <bool> appearance-can-elevate;
callback appearance-saved(bool);
callback appearance-done(bool);
// Properties (properties.rs) and Open with (open.rs).
in property <PropertiesInfo> 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%;

View file

@ -17,6 +17,9 @@ export component ListRow inherits StateLayer {
in property <bool> selected;
// Draws the icon in a shaped tonal container that morphs to `active-shape` when selected.
in property <bool> shaped;
// An image drawn in the shaped container in place of the glyph.
in property <image> picture;
in property <bool> has-picture;
in property <ShapeKind> shape: ShapeKind.circle;
in property <ShapeKind> active-shape: ShapeKind.cookie9;
in property <length> 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;

View file

@ -44,6 +44,9 @@ export component Shape {
in property <brush> fill: Theme.secondary-container;
in property <brush> active-fill: root.fill;
in property <string> glyph;
// An image drawn in place of the glyph (a folder's own icon).
in property <image> picture;
in property <bool> has-picture;
in property <color> glyph-color: Theme.on-secondary-container;
in property <length> 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;

Some files were not shown because too many files have changed in this diff Show more