icons: theme file icons with previews, sidebar icons and folders dropped into Places

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-25 01:01:23 -06:00
commit 4acabfc76a
27 changed files with 1125 additions and 329 deletions

View file

@ -12,6 +12,8 @@ Status: done = built and checked here; built, awaiting real-world check = built
| Sorting, grouping, hidden files toggle | done | S008 | tunal |
| Playlist sort in the music folder (m3u, m3u8, pls, xspf, wpl order; folder and shared Playlists folder) | done | S008 | tunal-core::playlist, tunal |
| Tabs, split view, editable breadcrumb path bar, back / forward / up, places sidebar | done | S010 | tunal |
| Own folders in Places and Bookmarks by drag, in any order, with their own sidebar icons | done | user request | tunal |
| File-type and folder icons of the desktop icon theme (previews on) or plain glyphs (previews off) | done | user request | tunal |
| Copy path, properties, Open, Open with | done | S012 | tunal |
| Relative dates ("5 minutes ago", "Yesterday, 3:42 PM") turning into date and time, 12/24-hour clock, both set in Settings | done | S039 | tunal |
| Settings dialog and context menus the user can edit (add, remove, reorder) | done | S013 | tunal |

View file

@ -24,6 +24,7 @@ use crate::player_bridge::{self, PlayerUi};
use crate::properties::Properties;
use crate::shell::Shell;
use crate::shell::pane::Pane;
use crate::shell::places::Section;
use crate::tags_bridge::{self, Tags};
use crate::tools::{self, Executable, Format};
use crate::{ButtonKind, DialogAction, MainWindow, MenuEntry, MenuItem};
@ -876,7 +877,7 @@ impl Actions {
} else {
vec![dir]
};
shell.add_bookmarks(&folders);
shell.add_places(Section::Bookmarks, &folders, None);
self.bridge.notify(if folders.len() == 1 {
"Added to places".to_string()
} else {

View file

@ -241,7 +241,7 @@ pub struct Settings {
pub motion: Motion,
pub date_style: DateStyle,
pub clock: Clock,
/// What a new pane starts with: thumbnails instead of plain glyphs.
/// What a new pane starts with: thumbnails and theme icons instead of plain glyphs.
pub previews: bool,
/// Where in a video the preview frame is taken: a percent of its length or seconds in.
pub preview_frame_unit: FrameUnit,

View file

@ -80,7 +80,7 @@ fn list_env(name: &str, default: &str) -> Vec<PathBuf> {
.collect()
}
fn data_dirs() -> Vec<PathBuf> {
pub fn data_dirs() -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = data_home().into_iter().collect();
dirs.extend(list_env("XDG_DATA_DIRS", "/usr/local/share:/usr/share"));
dirs
@ -579,12 +579,48 @@ struct ThemeDir {
path: PathBuf,
size: u32,
scalable: bool,
apps: bool,
places: bool,
context: Option<IconContext>,
/// Position of its theme in the inheritance chain.
theme: usize,
}
/// What a theme directory's icons are for.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum IconContext {
Apps,
/// Folders.
Places,
/// File types.
Types,
}
impl IconContext {
const ALL: [(Self, &str, &str); 3] = [
(Self::Apps, "Applications", "apps"),
(Self::Places, "Places", "places"),
(Self::Types, "MimeTypes", "mimetypes"),
];
/// By the directory's `Context` key, else by its path.
fn of(context: &str, dir: &str) -> Option<Self> {
let dir = dir.to_lowercase();
let by = |f: &dyn Fn(&str, &str) -> bool| {
let hit = Self::ALL.iter().find(|(_, name, part)| f(name, part));
hit.map(|(c, ..)| *c)
};
by(&|name, _| context.eq_ignore_ascii_case(name))
.or_else(|| by(&|_, part| dir.contains(part)))
}
}
/// The `Icon` key of the desktop entry at `path`.
pub fn entry_icon(path: &Path) -> Option<String> {
parse_ini(&fs::read_to_string(path).ok()?)
.into_iter()
.find(|(g, k, v)| g == "Desktop Entry" && k == "Icon" && !v.is_empty())
.map(|(_, _, v)| v)
}
fn gtk_icon_theme() -> Option<String> {
let file = config_home()?.join("gtk-3.0/settings.ini");
parse_ini(&fs::read_to_string(file).ok()?)
@ -646,10 +682,7 @@ fn theme_dirs(base: &Path, name: &str, theme: usize) -> Vec<ThemeDir> {
size,
scalable: get("Type") == Some("Scalable"),
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"),
context: IconContext::of(context, &dir),
})
})
.collect()
@ -657,21 +690,12 @@ fn theme_dirs(base: &Path, name: &str, theme: usize) -> Vec<ThemeDir> {
/// The current icon theme and its parents, read once; `find` looks icons up in it.
pub struct IconTheme {
/// Directories of the Applications context, theme by theme (child before parent).
/// Directories of one context, theme by theme (child before parent).
dirs: Vec<ThemeDir>,
}
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 {
pub fn load(context: IconContext) -> 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();
@ -683,7 +707,7 @@ impl IconTheme {
for (index, theme) in chain.iter().enumerate() {
for base in &bases {
let mut found = theme_dirs(base, theme, index);
found.retain(|d| if places { d.places } else { d.apps });
found.retain(|d| d.context == Some(context));
dirs.extend(found);
}
}

View file

@ -106,14 +106,9 @@ fn show(lists: &Mutex<Lists>, update: impl FnOnce(&mut Lists)) {
let _ = slint::invoke_from_event_loop(move || {
let items = places
.into_iter()
.map(|p| Place {
name: p.name,
glyph: if p.uri.scheme() == ios::SCHEME && !can_eject(&p.uri) {
APPS
} else {
PHONE
},
uri: p.uri,
.map(|p| {
let app = p.uri.scheme() == ios::SCHEME && !can_eject(&p.uri);
Place::new(p.name, if app { APPS } else { PHONE }, p.uri)
})
.collect();
if let Some(shell) = SHELL.with(|s| s.borrow().upgrade()) {

View file

@ -1,5 +1,5 @@
//! In-app drag and drop: files from the views onto folders, panes, tabs, breadcrumb
//! segments and places; bookmarks onto bookmarks (reorder) or the bookmarks section (add).
//! segments and places; folders into a sidebar section (add); sidebar entries onto a slot (move).
//!
//! The payload is a `text/uri-list` string (one URI per line, CRLF), plus the file paths
//! when every item is local, so other applications can take it (native DnD hands the same
@ -20,15 +20,16 @@ use crate::shell::Shell;
use crate::shell::places::Section;
use crate::{Dnd, DropAction, DropTarget, MainWindow};
/// A bookmark being dragged (in-process only, carried as user data).
struct BookmarkDrag(usize);
/// A sidebar entry being dragged (in-process only, carried as user data).
#[derive(Clone, Copy)]
struct PlaceDrag(Section, usize);
/// The last payload read back, since `accepts` runs on every pointer move.
#[derive(Default)]
struct Parsed {
text: SharedString,
uris: Rc<Vec<Uri>>,
/// Every item is a local folder (bookmarks section), checked once when first asked.
/// Every item is a local folder (sidebar sections), checked once when first asked.
dirs: OnceCell<bool>,
}
@ -42,6 +43,10 @@ pub struct DragDrop {
pending: RefCell<Option<(Vec<Uri>, Uri)>>,
}
fn section_at(index: i32) -> Option<Section> {
Section::ALL.get(usize::try_from(index).ok()?).copied()
}
/// One URI per line, as `text/uri-list` has them.
pub fn uri_list(uris: &[Uri]) -> String {
uris.iter().map(|u| format!("{u}\r\n")).collect()
@ -105,9 +110,11 @@ impl DragDrop {
}
image
});
global.on_bookmark_payload(|index| {
global.on_place_payload(|section, index| {
let mut data = DataTransfer::default();
data.set_user_data(Rc::new(BookmarkDrag(index.max(0) as usize)));
if let Some(section) = section_at(section) {
data.set_user_data(Rc::new(PlaceDrag(section, index.max(0) as usize)));
}
data
});
let me = Rc::downgrade(self);
@ -178,9 +185,9 @@ impl DragDrop {
parsed.uris.clone()
}
fn bookmark(data: &DataTransfer) -> Option<usize> {
fn place(data: &DataTransfer) -> Option<PlaceDrag> {
let any: Rc<dyn Any> = data.user_data()?;
any.downcast_ref::<BookmarkDrag>().map(|b| b.0)
any.downcast_ref::<PlaceDrag>().copied()
}
fn target_dir(&self, target: DropTarget, a: i32, b: i32) -> Option<Uri> {
@ -192,23 +199,26 @@ impl DragDrop {
DropTarget::Tab => shell.tab_dir(a),
DropTarget::Crumb => shell.crumb_uri(index(a)?),
DropTarget::Place => shell.place_uri(*Section::ALL.get(index(a)?)?, index(b)?),
DropTarget::Bookmarks => None,
DropTarget::Section => None,
}
}
fn accepts(&self, data: &DataTransfer, target: DropTarget, a: i32, b: i32) -> bool {
let bookmarks = Section::ALL.iter().position(|&s| s == Section::Bookmarks);
if let Some(from) = Self::bookmark(data) {
return target == DropTarget::Place
&& usize::try_from(a).ok() == bookmarks
&& usize::try_from(b).is_ok_and(|to| to != from);
let editable = section_at(a).filter(|s| s.editable());
if let Some(PlaceDrag(from, index)) = Self::place(data) {
return matches!(target, DropTarget::Place | DropTarget::Section)
&& editable.is_some_and(|to| {
self.shell
.upgrade()
.is_some_and(|s| s.can_move_place(from, index, to))
});
}
let uris = self.uris(data);
if uris.is_empty() {
return false;
}
if target == DropTarget::Bookmarks {
return usize::try_from(a).ok() == bookmarks && self.all_dirs();
if target == DropTarget::Section {
return editable.is_some() && self.all_dirs();
}
let Some(dir) = self.target_dir(target, a, b) else {
return false;
@ -253,15 +263,21 @@ impl DragDrop {
let Some(shell) = self.shell.upgrade() else {
return;
};
if let Some(from) = Self::bookmark(data) {
if let Ok(to) = usize::try_from(b) {
shell.move_bookmark(from, to);
let slot = usize::try_from(b).ok();
if let Some(PlaceDrag(from, index)) = Self::place(data) {
if let Some(to) = section_at(a) {
// Onto a row below it in its own section: it takes that row's place.
let onto = target == DropTarget::Place && from == to;
let slot = slot.map(|s| if onto && s > index { s + 1 } else { s });
shell.move_place((from, index), (to, slot));
}
return;
}
let uris = self.uris(data).to_vec();
if target == DropTarget::Bookmarks {
shell.add_bookmarks(&uris);
if target == DropTarget::Section {
if let Some(section) = section_at(a) {
shell.add_places(section, &uris, slot);
}
return;
}
let Some(dir) = self.target_dir(target, a, b) else {

View file

@ -0,0 +1,249 @@
//! The desktop icon theme's picture of a file or folder: its type by name (shared MIME info)
//! or, for names that tell nothing, by its first bytes.
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use tunal_core::{Entry, FileType, Kind, Uri};
use crate::desktop_apps::{self, IconContext, IconTheme};
use crate::shell::places;
/// Size looked up; the views scale it.
const SIZE: u32 = 64;
/// Bytes read of a file whose name tells nothing.
const HEAD: usize = 1024;
/// The name patterns and icon names of shared MIME info.
#[derive(Default)]
struct Db {
/// Whole names, and what a name ends with (`.tar.gz`), to (weight, type).
names: HashMap<String, (u32, String)>,
suffixes: HashMap<String, (u32, String)>,
prefixes: Vec<(String, String)>,
/// Icon names of types that have an own one, and of their families.
icons: HashMap<String, String>,
generic: HashMap<String, String>,
}
impl Db {
fn load() -> Self {
let mut db = Self::default();
for dir in desktop_apps::data_dirs() {
let read = |name: &str| {
std::fs::read_to_string(dir.join("mime").join(name)).unwrap_or_default()
};
for line in read("globs2").lines() {
db.add_glob(line);
}
for (file, map) in [("icons", &mut db.icons), ("generic-icons", &mut db.generic)] {
for (mime, icon) in read(file).lines().filter_map(|l| l.split_once(':')) {
map.entry(mime.into()).or_insert_with(|| icon.into());
}
}
}
db
}
/// A line `weight:type:pattern[:flags]`; earlier ones win at equal weight. Patterns with
/// wildcards anywhere but at one end are rare and left out.
fn add_glob(&mut self, line: &str) {
let mut parts = line.splitn(4, ':');
let (Some(weight), Some(mime), Some(glob)) = (parts.next(), parts.next(), parts.next())
else {
return;
};
let Ok(weight) = weight.parse::<u32>() else {
return;
};
let wild = |s: &str| s.contains(['*', '?', '[']);
let add = |map: &mut HashMap<String, (u32, String)>, key: &str| {
if map.get(key).is_none_or(|(w, _)| *w < weight) {
map.insert(key.to_owned(), (weight, mime.to_owned()));
}
};
if let Some(end) = glob.strip_prefix('*').filter(|s| !wild(s)) {
add(&mut self.suffixes, end);
} else if let Some(start) = glob.strip_suffix('*').filter(|s| !wild(s)) {
self.prefixes.push((start.to_owned(), mime.to_owned()));
} else if !wild(glob) {
add(&mut self.names, glob);
}
}
fn mime(&self, name: &str) -> Option<&str> {
let lower = name.to_lowercase();
[name, lower.as_str()]
.into_iter()
.find_map(|n| self.mime_as_is(n))
}
fn mime_as_is(&self, name: &str) -> Option<&str> {
if let Some((_, mime)) = self.names.get(name) {
return Some(mime);
}
// The heaviest pattern, among equals the longest (they come longest first).
let mut best: Option<&(u32, String)> = None;
for (at, _) in name.char_indices() {
if let Some(hit) = self.suffixes.get(&name[at..])
&& best.is_none_or(|b| b.0 < hit.0)
{
best = Some(hit);
}
}
best.map(|(_, mime)| mime.as_str()).or_else(|| {
let hit = self.prefixes.iter().find(|(p, _)| name.starts_with(p));
hit.map(|(_, mime)| mime.as_str())
})
}
}
fn db() -> &'static Db {
static DB: OnceLock<Db> = OnceLock::new();
DB.get_or_init(Db::load)
}
/// The theme's folder icons.
pub fn places_theme() -> &'static IconTheme {
static THEME: OnceLock<IconTheme> = OnceLock::new();
THEME.get_or_init(|| IconTheme::load(IconContext::Places))
}
/// The theme's picture of the type `mime`, looked up once.
fn type_icon(mime: &str) -> Option<PathBuf> {
static THEME: OnceLock<IconTheme> = OnceLock::new();
static FOUND: OnceLock<Mutex<HashMap<String, Option<PathBuf>>>> = OnceLock::new();
let mut found = FOUND
.get_or_init(Default::default)
.lock()
.unwrap_or_else(|e| e.into_inner());
if let Some(icon) = found.get(mime) {
return icon.clone();
}
let theme = THEME.get_or_init(|| IconTheme::load(IconContext::Types));
let top = mime.split('/').next().unwrap_or_default();
let mut names: Vec<String> = Vec::new();
names.extend(db().icons.get(mime).cloned());
names.push(mime.replace('/', "-"));
names.extend(db().generic.get(mime).cloned());
names.push(format!("{top}-x-generic"));
names.extend(["application-octet-stream", "unknown"].map(String::from));
let icon = names.iter().find_map(|n| theme.find(n, SIZE));
found.insert(mime.to_owned(), icon.clone());
icon
}
/// The icon of folder `dir`: the one of a user folder (Downloads, Music …) or the plain one.
fn folder_icon(dir: Option<&Uri>) -> Option<PathBuf> {
static FOUND: OnceLock<(HashMap<PathBuf, PathBuf>, Option<PathBuf>)> = OnceLock::new();
let (special, plain) = FOUND.get_or_init(|| {
let theme = places_theme();
let special = places::special_dirs()
.into_iter()
.filter_map(|(path, name)| Some((path, theme.find(name, SIZE)?)))
.collect();
(special, theme.find("folder", SIZE))
});
dir.and_then(Uri::to_path)
.and_then(|p| special.get(&p))
.or(plain.as_ref())
.cloned()
}
/// A regular file, or a link to one.
fn is_file(entry: &Entry) -> bool {
matches!(
entry.kind,
Kind::File
| Kind::Symlink {
target_type: Some(FileType::File),
..
}
)
}
/// The icon for `entry` of `dir` by its name alone; reads only the MIME and theme indexes, and
/// those once.
pub fn by_name(dir: Option<&Uri>, entry: &Entry) -> Option<PathBuf> {
if entry.kind.is_dir() {
return folder_icon(dir.map(|d| d.join(&entry.name)).as_ref());
}
if !is_file(entry) {
return None;
}
type_icon(
db().mime(&entry.display_name)
.unwrap_or(tunal_core::mime::UNKNOWN),
)
}
/// The name of `entry` doesn't say what its icon is: see `by_content`.
pub fn needs_content(entry: &Entry) -> bool {
is_file(entry)
&& db()
.mime(&entry.display_name)
.is_none_or(|m| m == "application/x-desktop")
}
/// The icon of the local file at `path` by what is in it; `None` when that says nothing more
/// than its name.
pub fn by_content(path: &Path) -> Option<PathBuf> {
static APPS: OnceLock<IconTheme> = OnceLock::new();
if path.extension().is_some_and(|e| e == "desktop") {
let name = desktop_apps::entry_icon(path)?;
return APPS
.get_or_init(|| IconTheme::load(IconContext::Apps))
.find(&name, SIZE);
}
let mut head = Vec::with_capacity(HEAD);
File::open(path)
.ok()?
.take(HEAD as u64)
.read_to_end(&mut head)
.ok()?;
type_icon(sniff(&head)?)
}
fn sniff(head: &[u8]) -> Option<&'static str> {
const MAGIC: [(&[u8], &str); 10] = [
(b"\x89PNG", "image/png"),
(b"\xff\xd8\xff", "image/jpeg"),
(b"GIF8", "image/gif"),
(b"%PDF-", "application/pdf"),
(b"PK\x03\x04", "application/zip"),
(b"\x1f\x8b", "application/gzip"),
(b"\x28\xb5\x2f\xfd", "application/zstd"),
(b"7z\xbc\xaf", "application/x-7z-compressed"),
(b"SQLite format 3", "application/vnd.sqlite3"),
(b"MZ", "application/vnd.microsoft.portable-executable"),
];
if head.is_empty() {
return Some("application/x-zerosize");
}
if head.starts_with(b"\x7fELF") {
return Some("application/x-executable");
}
if let Some(line) = head.strip_prefix(b"#!") {
let line = String::from_utf8_lossy(line.split(|b| *b == b'\n').next().unwrap_or(line));
return Some(match () {
_ if line.contains("python") => "text/x-python",
_ if line.contains("perl") => "application/x-perl",
_ if line.contains("ruby") => "application/x-ruby",
_ if line.contains("node") => "application/javascript",
_ => "application/x-shellscript",
});
}
if let Some((_, mime)) = MAGIC.iter().find(|(m, _)| head.starts_with(m)) {
return Some(mime);
}
// Text; the last character may be cut off where the reading stopped.
let text = match std::str::from_utf8(head) {
Ok(_) => true,
Err(e) => e.error_len().is_none(),
};
(text && !head.contains(&0)).then_some("text/plain")
}

View file

@ -13,41 +13,8 @@ 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),
}
use crate::MainWindow;
use crate::icon_picker::{self, Pick, theme_icons};
struct Open {
dir: PathBuf,
@ -165,8 +132,8 @@ impl Appearance {
.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());
if !icon_picker::valid_image(&image) {
ui.set_appearance_error(icon_picker::NO_IMAGE.into());
return;
}
let remember = ui
@ -202,45 +169,9 @@ impl Appearance {
}
}
/// 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 (picks, cells) = icon_picker::cells("\u{e2c7}", themed);
let current = match (meta.glyph(), meta.icon()) {
(Some(g), _) => picks
.iter()

View file

@ -25,6 +25,8 @@ pub struct Item {
pub category: Category,
/// The folder's own icon and name from its `.directory`.
pub look: Option<Look>,
/// Its picture in the icon theme, where the name alone doesn't tell it.
pub icon: Option<PathBuf>,
}
impl Item {
@ -35,6 +37,7 @@ impl Item {
category: Category::of(&entry),
entry,
look: None,
icon: None,
}
}

View file

@ -7,6 +7,7 @@ use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};
use super::look::{self, Look};
use crate::{file_icons, thumbs_bridge};
use tunal_core::playlist::{self, Playlist};
use tunal_core::{Entry, Error, Locations, Uri, Watch, WatchEvent};
use tunal_dirmeta::View;
@ -24,6 +25,8 @@ pub enum Msg {
View(u64, View),
/// Icons and names from the `.directory` of child folders (by raw name).
Looks(u64, Vec<(Vec<u8>, Look)>),
/// Icons of files whose name doesn't tell their type (by raw name).
Icons(u64, Vec<(Vec<u8>, PathBuf)>),
/// Thumbnails arrived (the pane's inbox holds them).
Thumbs,
}
@ -91,11 +94,19 @@ pub fn load(
deliver(Msg::View(generation, view));
}
let mut names: Vec<(Vec<u8>, bool)> = Vec::new();
let mut unnamed: Vec<Vec<u8>> = Vec::new();
let mut pending: Vec<Entry> = Vec::new();
let mut last = Instant::now();
let mut first = true;
let result = backend.list(dir, &mut |chunk| {
names.extend(chunk.iter().map(|e| (e.name.clone(), e.kind.is_dir())));
for entry in chunk.iter() {
// Reads the icon indexes here, so drawing a row finds them in memory.
let _ = file_icons::by_name(Some(dir), entry);
if file_icons::needs_content(entry) {
unnamed.push(entry.name.clone());
}
}
pending.extend(chunk);
// The first chunk goes out at once so something shows quickly.
if first || last.elapsed() >= FLUSH {
@ -119,6 +130,9 @@ pub fn load(
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)));
if !unnamed.is_empty() && !thumbs_bridge::on_network_fs(&path) {
deliver(Msg::Icons(generation, icons(&path, &unnamed)));
}
// Shared playlists live elsewhere in the music folder: watch that folder too.
if let Some(watcher) = watch
@ -182,6 +196,18 @@ pub fn looks<'a>(
.collect()
}
/// The icons of the files `names` of `path` that their content tells.
pub fn icons(path: &Path, names: &[Vec<u8>]) -> Vec<(Vec<u8>, PathBuf)> {
use std::os::unix::ffi::OsStrExt;
names
.iter()
.filter_map(|n| {
let file = path.join(std::ffi::OsStr::from_bytes(n));
Some((n.clone(), file_icons::by_content(&file)?))
})
.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

@ -9,7 +9,7 @@ use std::time::SystemTime;
use tunal_dirmeta::{DirMeta, FILE_NAME, View};
pub use super::item::Look;
use crate::desktop_apps::IconTheme;
use crate::file_icons;
type Cache = Mutex<HashMap<PathBuf, (SystemTime, Option<Look>)>>;
@ -46,13 +46,12 @@ pub fn read(dir: &Path) -> Option<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)),
.and_then(|i| file_icons::places_theme().find(i, 64)),
};
(look != Look::default()).then_some(look)
}

View file

@ -23,6 +23,7 @@ use tunal_core::{Entry, Error, Locations, Uri, Watch};
use tunal_thumbs::{Priority, ThumbSize};
use crate::config;
use crate::file_icons;
use crate::icons::{self, Category};
use crate::thumbs_bridge::{self, Thumbs};
use crate::{
@ -79,7 +80,7 @@ pub struct Settings {
pub folders_first: bool,
pub group: GroupBy,
pub show_hidden: bool,
/// Thumbnails in place of plain glyphs.
/// Thumbnails, the icon theme's file icons and folders' own icons in place of plain glyphs.
pub previews: bool,
pub filter: String,
/// Details or grid.
@ -381,6 +382,7 @@ impl FolderModel {
// Reads are reported too: only entries whose stat differs count.
let mut changed = false;
let mut new_dirs = Vec::new();
let mut unnamed = Vec::new();
for change in changes {
match change {
Change::Upsert(entry) => {
@ -389,6 +391,9 @@ impl FolderModel {
if same.is_none() && entry.kind.is_dir() {
new_dirs.push(entry.name.clone());
}
if file_icons::needs_content(&entry) {
unnamed.push(entry.name.clone());
}
upsert(&mut s, entry);
changed = true;
}
@ -402,7 +407,7 @@ 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);
self.refresh_looks(&s, new_dirs, unnamed);
}
Msg::PlaylistsChanged(g) if g == current => self.refresh_playlists(&s),
Msg::View(g, view) if g == current => apply_view(&mut s, &view),
@ -413,6 +418,13 @@ impl FolderModel {
}
}
}
Msg::Icons(g, icons) if g == current => {
for (name, icon) in icons {
if let Some(&i) = s.by_name.get(&name) {
s.items[i].icon = Some(icon);
}
}
}
Msg::Playlists(g, found) if g == current => {
s.playlists = found;
if let Some(path) = s.playlist_path.clone() {
@ -467,7 +479,7 @@ impl FolderModel {
.filter(|i| i.is_dir)
.map(|i| i.entry.name.clone())
.collect();
self.refresh_looks(&s, names);
self.refresh_looks(&s, names, Vec::new());
}
/// A folder that remembers its view keeps it current in its `.directory` (off-thread; a
@ -489,13 +501,14 @@ impl FolderModel {
});
}
/// Reads the `.directory` of the new folders `names` off the UI thread.
fn refresh_looks(&self, s: &State, names: Vec<Vec<u8>>) {
/// Reads the `.directory` of the new folders `names`, and what is in the changed files
/// `files` whose name doesn't tell their icon, off the UI thread.
fn refresh_looks(&self, s: &State, names: Vec<Vec<u8>>, files: Vec<Vec<u8>>) {
let Some(path) = s
.dir
.as_ref()
.and_then(Uri::to_path)
.filter(|_| !names.is_empty())
.filter(|_| !names.is_empty() || !files.is_empty())
else {
return;
};
@ -506,6 +519,9 @@ impl FolderModel {
if !looks.is_empty() {
deliver(Msg::Looks(generation, looks));
}
if !files.is_empty() && !thumbs_bridge::on_network_fs(&path) {
deliver(Msg::Icons(generation, load::icons(&path, &files)));
}
});
}
@ -1567,8 +1583,11 @@ fn upsert(s: &mut State, entry: Entry) {
match s.by_name.get(&entry.name) {
Some(&i) => {
let look = s.items[i].look.take();
// Kept until its content is read again.
let icon = s.items[i].icon.take();
s.previews.forget(&entry.name);
s.items[i] = Item::new(entry).with_look(look);
s.items[i].icon = icon;
}
None => {
s.by_name.insert(entry.name.clone(), s.items.len());
@ -1866,10 +1885,20 @@ 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();
// Without previews every entry has its plain glyph.
let look = item.look.as_ref().filter(|_| s.settings.previews);
let picture = look
.and_then(|l| l.picture.as_deref())
.and_then(look::picture);
.and_then(look::picture)
.or_else(|| {
let themed = s.settings.previews && look.is_none_or(|l| l.glyph.is_none());
let icon = themed.then(|| {
item.icon
.clone()
.or_else(|| file_icons::by_name(s.dir.as_ref(), entry))
});
icon.flatten().as_deref().and_then(look::picture)
});
let thumb = if s.settings.previews && !item.is_dir {
s.previews.image(&entry.name)
} else {

View file

@ -0,0 +1,92 @@
//! The icons the icon picker offers (folder appearance, sidebar entries).
use std::path::PathBuf;
use crate::IconChoice;
use crate::file_icons;
use crate::folder::look;
/// 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)]
pub enum Pick {
Default,
Glyph(char),
Theme(String),
}
/// The theme's `folder-*` icons with their files.
pub fn theme_icons() -> Vec<(String, Option<PathBuf>)> {
let theme = file_icons::places_theme();
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(),
}
}
/// The picker's cells (the default, `default` glyph, then the Material glyphs and the theme
/// icons `themed`) with what each stands for.
pub fn cells(
default: &str,
themed: Vec<(String, Option<PathBuf>)>,
) -> (Vec<Pick>, Vec<IconChoice>) {
let mut picks = vec![Pick::Default];
let mut cells = vec![choice("Default", default, 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));
}
(picks, cells)
}
/// The text of an image file field names a file, or is empty.
pub fn valid_image(path: &str) -> bool {
path.is_empty() || (path.starts_with('/') && std::path::Path::new(path).is_file())
}
pub const NO_IMAGE: &str = "That image file doesn't exist. Use its full path.";

View file

@ -4,7 +4,9 @@ mod config;
mod desktop_apps;
mod devices_bridge;
mod dnd;
mod file_icons;
mod folder;
mod icon_picker;
mod icons;
mod jobs_bridge;
mod keymap;

View file

@ -481,7 +481,7 @@ impl Net {
shell.set_network(
places
.into_iter()
.map(|(name, glyph, uri)| Place { name, glyph, uri })
.map(|(name, glyph, uri)| Place::new(name, glyph, uri))
.collect(),
);
}

View file

@ -77,7 +77,7 @@ use std::rc::{Rc, Weak};
use slint::{ComponentHandle, Image, ModelRc, VecModel};
use tunal_core::{Locations, Uri};
use crate::desktop_apps::{self, App, Apps, IconTheme, Target};
use crate::desktop_apps::{self, App, Apps, IconContext, IconTheme, Target};
use crate::jobs_bridge::Bridge;
use crate::{AppRow, MainWindow};
@ -118,7 +118,7 @@ fn prepare(locations: &Locations, first: &Uri) -> (&'static str, Vec<Prepared>)
.and_then(|l| l.stat(first))
.map_or("application/octet-stream", |e| e.mime);
let choices = Apps::load().choices(mime);
let icons = IconTheme::load();
let icons = IconTheme::load(IconContext::Apps);
let mut prepared = Vec::new();
for (list, section) in [
(&choices.handlers, "Recommended"),

View file

@ -4,6 +4,7 @@
mod commands;
pub(crate) mod pane;
mod path;
mod place_icon;
pub mod places;
use std::cell::{Cell, OnceCell, RefCell};
@ -19,7 +20,7 @@ use crate::config::{
self, Click, EmptyDouble, MiddleEmpty, MiddleItem, Session, SideButtons, TabSession,
};
use crate::dnd::DragDrop;
use crate::folder::format;
use crate::folder::{format, look};
use crate::keymap::Keymap;
use crate::settings::SettingsUi;
use crate::thumbs_bridge::Thumbs;
@ -37,6 +38,28 @@ struct Tab {
active: usize,
}
/// What the menu of a sidebar entry the user arranges offers.
#[derive(Clone, Copy)]
enum PlaceAction {
Rename,
ChangeIcon,
MoveUp,
MoveDown,
Remove,
}
impl PlaceAction {
fn label(self) -> (&'static str, &'static str) {
match self {
Self::Rename => ("Rename", "\u{e3c9}"),
Self::ChangeIcon => ("Change icon…", "\u{e40a}"),
Self::MoveUp => ("Move up", "\u{e5d8}"),
Self::MoveDown => ("Move down", "\u{e5db}"),
Self::Remove => ("Remove", "\u{e872}"),
}
}
}
/// What the place menu was opened on.
#[derive(Clone, Copy)]
struct MenuTarget {
@ -628,10 +651,13 @@ impl Shell {
.iter()
.map(|p| {
let (name, tip) = path::shown_name(&p.uri, p.name.clone());
let picture = p.picture.as_deref().and_then(look::picture);
PlaceItem {
name: name.into(),
tip: tip.into(),
glyph: p.glyph.into(),
glyph: p.shown_glyph().into(),
has_picture: picture.is_some(),
picture: picture.unwrap_or_default(),
current: Some(&p.uri) == dir,
}
})
@ -642,6 +668,7 @@ impl Shell {
collapsed: places.collapsed(section),
empty: section.empty().into(),
can_add: section == Section::Bookmarks,
editable: section.editable(),
can_connect: section == Section::Network,
}
})
@ -705,7 +732,9 @@ impl Shell {
return;
};
let (name, _) = path::title(&dir);
self.places.borrow_mut().add_bookmark(name, dir);
self.places
.borrow_mut()
.add(Section::Bookmarks, name, dir, None);
self.show_chrome();
}
@ -727,12 +756,17 @@ impl Shell {
submenu: ModelRc::new(VecModel::<MenuEntry>::default()),
};
let mut items = vec![item("Open in new tab", "\u{e89e}", false)];
if section == Section::Bookmarks {
if section.editable() {
let last = self.places.borrow().items(section).len().saturating_sub(1);
items.push(item("Rename", "\u{e3c9}", false));
items.push(item("Move up", "\u{e5d8}", index == 0));
items.push(item("Move down", "\u{e5db}", index >= last));
items.push(item("Remove", "\u{e872}", false));
for action in self.place_actions(section, index) {
let (text, icon) = action.label();
let disabled = match action {
PlaceAction::MoveUp => index == 0,
PlaceAction::MoveDown => index >= last,
_ => false,
};
items.push(item(text, icon, disabled));
}
}
if self.ejectable(section, index).is_some() {
items.push(item("Eject", "\u{e8fb}", false));
@ -745,6 +779,21 @@ impl Shell {
items
}
/// The menu of an entry the user arranges, after "Open in new tab".
fn place_actions(&self, section: Section, index: usize) -> Vec<PlaceAction> {
use PlaceAction::*;
let standard = self
.places
.borrow()
.get(section, index)
.is_some_and(|p| p.standard);
if standard {
vec![ChangeIcon, MoveUp, MoveDown]
} else {
vec![Rename, ChangeIcon, MoveUp, MoveDown, Remove]
}
}
/// The URI of a device entry that can be ejected.
fn ejectable(&self, section: Section, index: usize) -> Option<Uri> {
let places = self.places.borrow();
@ -765,33 +814,44 @@ impl Shell {
crate::devices_bridge::eject(&uri);
}
}
1 => {
let name = self
.places
.borrow()
.get(section, index)
.map(|p| p.name.clone());
if let (Some(name), Some(ui)) = (name, self.ui.upgrade()) {
ui.invoke_rename_bookmark(name.into());
c => {
let action = self.place_actions(section, index).get(c - 1).copied();
match action {
Some(PlaceAction::Rename) => {
let name = self
.places
.borrow()
.get(section, index)
.map(|p| p.name.clone());
if let (Some(name), Some(ui)) = (name, self.ui.upgrade()) {
ui.invoke_rename_place(name.into());
}
// The dialog's answer is for this target.
return;
}
Some(PlaceAction::ChangeIcon) => {
self.show_place_icon(section, index);
return;
}
Some(PlaceAction::MoveUp) => {
let slot = Some(index.saturating_sub(1));
self.move_place((section, index), (section, slot));
}
Some(PlaceAction::MoveDown) => {
self.move_place((section, index), (section, Some(index + 2)));
}
Some(PlaceAction::Remove) => self.places.borrow_mut().remove(section, index),
None => {}
}
return;
}
2 => self.places.borrow_mut().move_bookmark(index, -1),
3 => self.places.borrow_mut().move_bookmark(index, 1),
4 => self.places.borrow_mut().remove_bookmark(index),
_ => {}
}
self.menu_target.set(None);
self.show_chrome();
}
fn rename_bookmark(&self, name: &str) {
if let Some(MenuTarget {
section: Section::Bookmarks,
index,
}) = self.menu_target.take()
{
self.places.borrow_mut().rename_bookmark(index, name);
fn rename_place(&self, name: &str) {
if let Some(MenuTarget { section, index }) = self.menu_target.take() {
self.places.borrow_mut().rename(section, index, name);
self.show_chrome();
}
}
@ -872,18 +932,25 @@ impl Shell {
.map(|p| p.uri.clone())
}
pub(crate) fn add_bookmarks(&self, dirs: &[Uri]) {
for dir in dirs {
/// Adds folders to `section` at `slot` (the end for `None`).
pub(crate) fn add_places(&self, section: Section, dirs: &[Uri], slot: Option<usize>) {
for (i, dir) in dirs.iter().enumerate() {
let (name, _) = path::title(dir);
self.places.borrow_mut().add_bookmark(name, dir.clone());
let slot = slot.map(|s| s + i);
self.places
.borrow_mut()
.add(section, name, dir.clone(), slot);
}
self.show_chrome();
}
/// Puts bookmark `from` at slot `to`.
pub(crate) fn move_bookmark(&self, from: usize, to: usize) {
let by = to as isize - from as isize;
self.places.borrow_mut().move_bookmark(from, by);
pub(crate) fn can_move_place(&self, from: Section, index: usize, to: Section) -> bool {
self.places.borrow().can_move(from, index, to)
}
/// Moves a sidebar entry before a slot (the end for `None`).
pub(crate) fn move_place(&self, from: (Section, usize), to: (Section, Option<usize>)) {
self.places.borrow_mut().move_to(from, to);
self.show_chrome();
}
@ -1004,7 +1071,8 @@ impl Shell {
on!(on_place_menu_activated, |s, index, _sub| {
s.place_menu_activated(index.max(0) as usize)
});
on!(on_bookmark_renamed, |s, name| s.rename_bookmark(&name));
on!(on_place_renamed, |s, name| s.rename_place(&name));
on!(on_place_icon_saved, |s| s.save_place_icon());
self.bind_mouse_buttons(ui);
self.bind_keys(ui);

View file

@ -0,0 +1,80 @@
//! The icon dialog of a sidebar entry.
use std::cell::RefCell;
use slint::{ModelRc, VecModel};
use super::Shell;
use super::places::{Place, Section, glyph_of};
use crate::MainWindow;
use crate::icon_picker::{self, Pick, theme_icons};
thread_local! {
/// What each cell of the open dialog stands for.
static PICKS: RefCell<Vec<Pick>> = const { RefCell::new(Vec::new()) };
}
impl Shell {
/// Opens the dialog for the entry the place menu was opened on.
pub(super) fn show_place_icon(&self, section: Section, index: usize) {
let place = self.places.borrow().get(section, index).cloned();
let (Some(place), Some(ui)) = (place, self.ui.upgrade()) else {
return;
};
ui.set_place_icon_error("".into());
fill(&ui, &place, Vec::new());
ui.invoke_show_place_icon();
// The theme's icons are looked up off the UI thread.
let weak = self.ui.clone();
std::thread::spawn(move || {
let themed = theme_icons();
let _ = weak.upgrade_in_event_loop(move |ui| fill(&ui, &place, themed));
});
}
pub(super) fn save_place_icon(&self) {
let (Some(target), Some(ui)) = (self.menu_target.get(), self.ui.upgrade()) else {
return;
};
let image = ui.get_place_icon_image().trim().to_owned();
if !icon_picker::valid_image(&image) {
ui.set_place_icon_error(icon_picker::NO_IMAGE.into());
return;
}
let choice = usize::try_from(ui.get_place_icon_choice()).unwrap_or(0);
let pick = PICKS.with(|p| p.borrow().get(choice).cloned());
let icon = match pick {
_ if !image.is_empty() => Some(image),
Some(Pick::Glyph(g)) => Some(g.to_string()),
Some(Pick::Theme(name)) => Some(name),
Some(Pick::Default) | None => None,
};
ui.invoke_close_place_icon();
self.menu_target.set(None);
self.places
.borrow_mut()
.set_icon(target.section, target.index, icon);
self.show_chrome();
}
}
/// Fills the picker and selects what `place` has.
fn fill(ui: &MainWindow, place: &Place, themed: Vec<(String, Option<std::path::PathBuf>)>) {
let late = !themed.is_empty();
let (picks, cells) = icon_picker::cells(place.glyph, themed);
let icon = place.icon.as_deref().unwrap_or_default();
let current = picks.iter().position(|p| match p {
Pick::Default => icon.is_empty(),
Pick::Glyph(g) => glyph_of(icon) == Some(*g),
Pick::Theme(name) => name == icon,
});
// The theme icons come after the dialog shows: a choice made meanwhile stays.
if !late || matches!(current.map(|i| &picks[i]), Some(Pick::Theme(_))) {
ui.set_place_icon_choice(current.unwrap_or(0) as i32);
}
if !late {
ui.set_place_icon_image(if icon.starts_with('/') { icon } else { "" }.into());
}
ui.set_place_icons(ModelRc::new(VecModel::from(cells)));
PICKS.with(|p| *p.borrow_mut() = picks);
}

View file

@ -1,4 +1,5 @@
//! The sidebar's places: home and the XDG user dirs, Trash, bookmarks (`places.toml`), and
//! The sidebar's places: home, the XDG user dirs, Trash and the user's own, bookmarks (both
//! `places.toml`), and
//! the Devices and Network sections later plans fill through [`Places::set_section`].
use std::collections::HashSet;
@ -8,6 +9,7 @@ use serde::{Deserialize, Serialize};
use tunal_core::{TRASH, Uri};
use crate::config;
use crate::file_icons;
pub const HOME: &str = "\u{e88a}";
pub const FOLDER: &str = "\u{e2c7}";
@ -47,6 +49,11 @@ impl Section {
}
}
/// Takes folders of the user's, in an order of theirs.
pub fn editable(self) -> bool {
matches!(self, Self::Places | Self::Bookmarks)
}
fn key(self) -> &'static str {
match self {
Self::Places => "places",
@ -62,25 +69,92 @@ pub struct Place {
pub name: String,
pub glyph: &'static str,
pub uri: Uri,
/// The user's icon: a Material glyph, an image file's path or a theme icon's name.
pub icon: Option<String>,
/// The file `icon` stands for, if it is no glyph.
pub picture: Option<PathBuf>,
/// One of the places every user has: it can't be renamed, removed or leave its section.
pub standard: bool,
}
impl Place {
pub fn new(name: String, glyph: &'static str, uri: Uri) -> Self {
Self {
name,
glyph,
uri,
icon: None,
picture: None,
standard: false,
}
}
fn with_icon(mut self, icon: Option<String>) -> Self {
self.set_icon(icon);
self
}
fn set_icon(&mut self, icon: Option<String>) {
self.picture = icon
.as_deref()
.filter(|i| glyph_of(i).is_none())
.and_then(|i| file_icons::places_theme().find(i, 64));
self.icon = icon;
}
/// The glyph drawn: the user's, else the place's own.
pub fn shown_glyph(&self) -> String {
let own = self.icon.as_deref().and_then(glyph_of);
own.map_or_else(|| self.glyph.to_owned(), String::from)
}
}
/// The Material glyph an icon setting stands for, `None` for a file or a theme icon.
pub fn glyph_of(icon: &str) -> Option<char> {
let mut chars = icon.chars();
let first = chars.next().filter(|c| !c.is_ascii())?;
chars.next().is_none().then_some(first)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Bookmark {
struct Saved {
name: String,
uri: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
icon: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
standard: bool,
}
impl Saved {
fn of(p: &Place) -> Self {
Self {
name: p.name.clone(),
uri: p.uri.to_string(),
icon: p.icon.clone(),
standard: p.standard,
}
}
fn place(self) -> Option<Place> {
let uri = Uri::parse(&self.uri)?;
Some(Place::new(self.name, BOOKMARK, uri).with_icon(self.icon))
}
}
/// `places.toml`.
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(default)]
struct PlacesFile {
bookmarks: Vec<Bookmark>,
bookmarks: Vec<Saved>,
/// The Places section in its order, once the user changed it.
places: Vec<Saved>,
/// Keys of the collapsed sections.
collapsed: Vec<String>,
}
pub struct Places {
standard: Vec<Place>,
places: Vec<Place>,
bookmarks: Vec<Place>,
devices: Vec<Place>,
network: Vec<Place>,
@ -93,20 +167,14 @@ impl Places {
let bookmarks = file
.bookmarks
.into_iter()
.filter_map(|b| {
Some(Place {
name: b.name,
glyph: BOOKMARK,
uri: Uri::parse(&b.uri)?,
})
})
.filter_map(Saved::place)
.collect();
let collapsed = Section::ALL
.into_iter()
.filter(|s| file.collapsed.iter().any(|k| k == s.key()))
.collect();
Self {
standard: standard(),
places: ordered(file.places),
bookmarks,
devices: Vec::new(),
network: Vec::new(),
@ -116,14 +184,8 @@ impl Places {
fn save(&self) {
let file = PlacesFile {
bookmarks: self
.bookmarks
.iter()
.map(|p| Bookmark {
name: p.name.clone(),
uri: p.uri.to_string(),
})
.collect(),
bookmarks: self.bookmarks.iter().map(Saved::of).collect(),
places: self.places.iter().map(Saved::of).collect(),
collapsed: Section::ALL
.into_iter()
.filter(|s| self.collapsed.contains(s))
@ -135,7 +197,7 @@ impl Places {
pub fn items(&self, section: Section) -> &[Place] {
match section {
Section::Places => &self.standard,
Section::Places => &self.places,
Section::Bookmarks => &self.bookmarks,
Section::Devices => &self.devices,
Section::Network => &self.network,
@ -166,49 +228,117 @@ impl Places {
self.save();
}
/// Bookmarks `uri` under `name`, unless it is bookmarked already.
pub fn add_bookmark(&mut self, name: String, uri: Uri) {
if self.bookmarks.iter().any(|p| p.uri == uri) {
/// The items of a section the user arranges.
fn own(&mut self, section: Section) -> Option<&mut Vec<Place>> {
match section {
Section::Places => Some(&mut self.places),
Section::Bookmarks => Some(&mut self.bookmarks),
Section::Devices | Section::Network => None,
}
}
/// Adds `uri` to `section` as `name` at slot `at` (the end for `None`), unless it is there
/// already.
pub fn add(&mut self, section: Section, name: String, uri: Uri, at: Option<usize>) {
let Some(items) = self.own(section) else {
return;
};
if items.iter().any(|p| p.uri == uri) {
return;
}
self.bookmarks.push(Place {
name,
glyph: BOOKMARK,
uri,
});
self.collapsed.remove(&Section::Bookmarks);
let at = at.unwrap_or(items.len()).min(items.len());
let glyph = if section == Section::Places {
FOLDER
} else {
BOOKMARK
};
items.insert(at, Place::new(name, glyph, uri));
self.collapsed.remove(&section);
self.save();
}
pub fn rename_bookmark(&mut self, index: usize, name: &str) {
pub fn rename(&mut self, section: Section, index: usize, name: &str) {
let name = name.trim();
if let Some(p) = self.bookmarks.get_mut(index).filter(|_| !name.is_empty()) {
let place = self.own(section).and_then(|items| items.get_mut(index));
if let Some(p) = place.filter(|p| !p.standard && !name.is_empty()) {
p.name = name.to_owned();
self.save();
}
}
pub fn remove_bookmark(&mut self, index: usize) {
if index < self.bookmarks.len() {
self.bookmarks.remove(index);
pub fn set_icon(&mut self, section: Section, index: usize, icon: Option<String>) {
if let Some(p) = self.own(section).and_then(|items| items.get_mut(index)) {
p.set_icon(icon);
self.save();
}
}
/// Moves bookmark `index` by `by` places (up is negative).
pub fn move_bookmark(&mut self, index: usize, by: isize) {
let Some(to) = index
.checked_add_signed(by)
.filter(|&t| t < self.bookmarks.len())
else {
return;
};
if index < self.bookmarks.len() {
let p = self.bookmarks.remove(index);
self.bookmarks.insert(to, p);
pub fn remove(&mut self, section: Section, index: usize) {
if let Some(items) = self.own(section)
&& items.get(index).is_some_and(|p| !p.standard)
{
items.remove(index);
self.save();
}
}
/// Entry `index` of `from` may go to `to`: a standard place stays in its section, and
/// nothing is listed twice.
pub fn can_move(&self, from: Section, index: usize, to: Section) -> bool {
to.editable()
&& self.get(from, index).is_some_and(|p| {
from == to || (!p.standard && self.items(to).iter().all(|q| q.uri != p.uri))
})
}
/// Moves entry `index` of `from` before slot `slot` of `to` (the end for `None`).
pub fn move_to(
&mut self,
(from, index): (Section, usize),
(to, slot): (Section, Option<usize>),
) {
if !self.can_move(from, index, to) {
return;
}
let Some(mut place) = self.own(from).map(|items| items.remove(index)) else {
return;
};
if from != to {
place.glyph = if to == Section::Places {
FOLDER
} else {
BOOKMARK
};
}
if let Some(items) = self.own(to) {
let slot = slot.unwrap_or(usize::MAX);
let slot = if from == to && slot > index {
slot - 1
} else {
slot
};
items.insert(slot.min(items.len()), place);
}
self.collapsed.remove(&to);
self.save();
}
}
/// The Places section as saved: the user's order, with standard places that came since at the
/// end and those that went left out.
fn ordered(saved: Vec<Saved>) -> Vec<Place> {
let mut standard = standard();
let mut places = Vec::new();
for entry in saved {
if entry.standard {
let at = standard.iter().position(|p| p.uri.to_string() == entry.uri);
places.extend(at.map(|i| standard.remove(i).with_icon(entry.icon)));
} else {
places.extend(entry.place().map(|p| Place { glyph: FOLDER, ..p }));
}
}
places.extend(standard);
places
}
pub fn home() -> PathBuf {
@ -218,11 +348,7 @@ pub fn home() -> PathBuf {
/// Home, the user dirs that exist (in the usual order), and Trash.
fn standard() -> Vec<Place> {
let home = home();
let mut places = vec![Place {
name: "Home".into(),
glyph: HOME,
uri: Uri::from_path(&home),
}];
let mut places = vec![Place::new("Home".into(), HOME, Uri::from_path(&home))];
let dirs = user_dirs(&home);
const KINDS: [(&str, &str, &str); 6] = [
("DESKTOP", "Desktop", "\u{e30c}"),
@ -243,20 +369,41 @@ fn standard() -> Vec<Place> {
let name = path
.file_name()
.map_or_else(|| fallback.to_owned(), |n| n.to_string_lossy().into_owned());
places.push(Place {
name,
glyph,
uri: Uri::from_path(path),
});
places.push(Place::new(name, glyph, Uri::from_path(path)));
}
places.push(Place::new(
"Trash".into(),
TRASH_GLYPH,
Uri::new(TRASH, "", "/"),
));
for p in &mut places {
p.standard = true;
}
places.push(Place {
name: "Trash".into(),
glyph: TRASH_GLYPH,
uri: Uri::new(TRASH, "", "/"),
});
places
}
/// Home and the user dirs with the names of their folder icons.
pub fn special_dirs() -> Vec<(PathBuf, &'static str)> {
const ICONS: [(&str, &str); 8] = [
("DESKTOP", "user-desktop"),
("DOCUMENTS", "folder-documents"),
("DOWNLOAD", "folder-download"),
("MUSIC", "folder-music"),
("PICTURES", "folder-pictures"),
("VIDEOS", "folder-videos"),
("PUBLICSHARE", "folder-publicshare"),
("TEMPLATES", "folder-templates"),
];
let home = home();
let mut dirs: Vec<(PathBuf, &str)> = user_dirs(&home)
.into_iter()
.filter(|(_, path)| *path != home)
.filter_map(|(key, path)| Some((path, ICONS.iter().find(|(k, _)| *k == key)?.1)))
.collect();
dirs.push((home, "user-home"));
dirs
}
/// `$XDG_CONFIG_HOME/user-dirs.dirs` as (`DESKTOP`, path) pairs.
fn user_dirs(home: &Path) -> Vec<(String, PathBuf)> {
let config = std::env::var_os("XDG_CONFIG_HOME")

View file

@ -24,7 +24,9 @@ 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 { FolderAppearanceDialog } from "dialogs/folder-appearance.slint";
import { PlaceIconDialog } from "dialogs/place-icon.slint";
import { IconChoice } from "components/icon-picker.slint";
import { TagEditorDialog, TagEditorData, TagField } from "dialogs/tag-editor.slint";
import { TagLookupDialog, TagLookupData, ReleaseRow, MapRow } from "dialogs/tag-lookup.slint";
import { SettingsDialog, SettingsData, EditRow, KeyRow } from "dialogs/settings.slint";
@ -247,7 +249,13 @@ export component MainWindow inherits Window {
callback add-bookmark();
callback place-menu-requested(int, int);
callback place-menu-activated(int, int);
callback bookmark-renamed(string);
callback place-renamed(string);
// The icon of a sidebar entry (shell/place_icon.rs).
in property <[IconChoice]> place-icons;
in-out property <int> place-icon-choice;
in-out property <string> place-icon-image;
in property <string> place-icon-error;
callback place-icon-saved();
in property <string> status;
@ -289,7 +297,15 @@ export component MainWindow inherits Window {
place-popup.open-at(x, y);
}
public function rename-bookmark(name: string) {
public function show-place-icon() {
place-icon-dialog.show();
}
public function close-place-icon() {
place-icon-dialog.close();
}
public function rename-place(name: string) {
rename-field.text = name;
rename-dialog.show();
}
@ -730,7 +746,7 @@ export component MainWindow inherits Window {
glyph: Icons.edit;
width: 100%;
height: 100%;
title: "Rename bookmark";
title: "Rename place";
body: "The folder itself keeps its name.";
content-focus: true;
actions: [{ text: "Cancel", kind: ButtonKind.text }, { text: "Rename", kind: ButtonKind.filled }];
@ -742,7 +758,7 @@ export component MainWindow inherits Window {
action(i) => {
self.close();
if i == 1 {
root.bookmark-renamed(rename-field.text);
root.place-renamed(rename-field.text);
}
}
@ -869,6 +885,18 @@ export component MainWindow inherits Window {
}
}
place-icon-dialog := PlaceIconDialog {
width: 100%;
height: 100%;
icons: root.place-icons;
choice <=> root.place-icon-choice;
image-path <=> root.place-icon-image;
error: root.place-icon-error;
saved => {
root.place-icon-saved();
}
}
tag-editor-dialog := TagEditorDialog {
width: 100%;
height: 100%;

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