diff --git a/FEATURES.md b/FEATURES.md index 0571cf1..249e8c2 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -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 | diff --git a/crates/tunal/src/actions.rs b/crates/tunal/src/actions.rs index 6460481..d1f22cb 100644 --- a/crates/tunal/src/actions.rs +++ b/crates/tunal/src/actions.rs @@ -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 { diff --git a/crates/tunal/src/config.rs b/crates/tunal/src/config.rs index 5c0c91d..abfaa11 100644 --- a/crates/tunal/src/config.rs +++ b/crates/tunal/src/config.rs @@ -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, diff --git a/crates/tunal/src/desktop_apps.rs b/crates/tunal/src/desktop_apps.rs index 4c18d9b..b215138 100644 --- a/crates/tunal/src/desktop_apps.rs +++ b/crates/tunal/src/desktop_apps.rs @@ -80,7 +80,7 @@ fn list_env(name: &str, default: &str) -> Vec { .collect() } -fn data_dirs() -> Vec { +pub fn data_dirs() -> Vec { let mut dirs: Vec = 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, /// 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 { + 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 { + 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 { 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 { 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 { /// 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, } 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 = 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); } } diff --git a/crates/tunal/src/devices_bridge.rs b/crates/tunal/src/devices_bridge.rs index 1fc5d28..7866539 100644 --- a/crates/tunal/src/devices_bridge.rs +++ b/crates/tunal/src/devices_bridge.rs @@ -106,14 +106,9 @@ fn show(lists: &Mutex, 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()) { diff --git a/crates/tunal/src/dnd.rs b/crates/tunal/src/dnd.rs index 1aee2b0..b226dc8 100644 --- a/crates/tunal/src/dnd.rs +++ b/crates/tunal/src/dnd.rs @@ -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>, - /// 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, } @@ -42,6 +43,10 @@ pub struct DragDrop { pending: RefCell, Uri)>>, } +fn section_at(index: i32) -> Option
{ + 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 { + fn place(data: &DataTransfer) -> Option { let any: Rc = data.user_data()?; - any.downcast_ref::().map(|b| b.0) + any.downcast_ref::().copied() } fn target_dir(&self, target: DropTarget, a: i32, b: i32) -> Option { @@ -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 { diff --git a/crates/tunal/src/file_icons.rs b/crates/tunal/src/file_icons.rs new file mode 100644 index 0000000..147a26c --- /dev/null +++ b/crates/tunal/src/file_icons.rs @@ -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, + suffixes: HashMap, + prefixes: Vec<(String, String)>, + /// Icon names of types that have an own one, and of their families. + icons: HashMap, + generic: HashMap, +} + +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::() else { + return; + }; + let wild = |s: &str| s.contains(['*', '?', '[']); + let add = |map: &mut HashMap, 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 = OnceLock::new(); + DB.get_or_init(Db::load) +} + +/// The theme's folder icons. +pub fn places_theme() -> &'static IconTheme { + static THEME: OnceLock = 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 { + static THEME: OnceLock = OnceLock::new(); + static FOUND: OnceLock>>> = 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 = 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 { + static FOUND: OnceLock<(HashMap, Option)> = 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 { + 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 { + static APPS: OnceLock = 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") +} diff --git a/crates/tunal/src/folder/appearance.rs b/crates/tunal/src/folder/appearance.rs index 2b6cdd8..1693f82 100644 --- a/crates/tunal/src/folder/appearance.rs +++ b/crates/tunal/src/folder/appearance.rs @@ -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)> { - let theme = IconTheme::load_places(); - theme - .names("folder-") - .into_iter() - .filter(|n| !n.ends_with("-open")) - .take(THEME_ICONS) - .map(|n| { - let file = theme.find(&n, 64); - (n, file) - }) - .collect() -} - -fn choice(label: &str, glyph: &str, picture: Option) -> IconChoice { - IconChoice { - glyph: glyph.into(), - has_picture: picture.is_some(), - picture: picture.unwrap_or_default(), - label: label.into(), - } -} - /// Fills the picker with the glyphs and the theme icons, and selects what the file has. fn fill(ui: &MainWindow, meta: &DirMeta, themed: Vec<(String, Option)>) { - let mut picks = vec![Pick::Default]; - let mut cells = vec![choice("Default", "\u{e2c7}", None)]; - for (label, glyph) in GLYPHS { - picks.push(Pick::Glyph(glyph)); - cells.push(choice(label, &glyph.to_string(), None)); - } - for (name, file) in themed { - let Some(image) = file.as_deref().and_then(look::picture) else { - continue; - }; - cells.push(choice(&name, "", Some(image))); - picks.push(Pick::Theme(name)); - } + let (picks, cells) = icon_picker::cells("\u{e2c7}", themed); let current = match (meta.glyph(), meta.icon()) { (Some(g), _) => picks .iter() diff --git a/crates/tunal/src/folder/item.rs b/crates/tunal/src/folder/item.rs index 3806575..242db25 100644 --- a/crates/tunal/src/folder/item.rs +++ b/crates/tunal/src/folder/item.rs @@ -25,6 +25,8 @@ pub struct Item { pub category: Category, /// The folder's own icon and name from its `.directory`. pub look: Option, + /// Its picture in the icon theme, where the name alone doesn't tell it. + pub icon: Option, } impl Item { @@ -35,6 +37,7 @@ impl Item { category: Category::of(&entry), entry, look: None, + icon: None, } } diff --git a/crates/tunal/src/folder/load.rs b/crates/tunal/src/folder/load.rs index 2d0fea4..117f233 100644 --- a/crates/tunal/src/folder/load.rs +++ b/crates/tunal/src/folder/load.rs @@ -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, Look)>), + /// Icons of files whose name doesn't tell their type (by raw name). + Icons(u64, Vec<(Vec, 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, bool)> = Vec::new(); + let mut unnamed: Vec> = Vec::new(); let mut pending: Vec = Vec::new(); let mut last = Instant::now(); let mut first = true; let result = backend.list(dir, &mut |chunk| { names.extend(chunk.iter().map(|e| (e.name.clone(), e.kind.is_dir()))); + 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> = 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]) -> Vec<(Vec, 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, bool)]) -> Vec { let entries: Vec<(&[u8], bool)> = names.iter().map(|(n, d)| (n.as_slice(), *d)).collect(); diff --git a/crates/tunal/src/folder/look.rs b/crates/tunal/src/folder/look.rs index d07669c..da7389f 100644 --- a/crates/tunal/src/folder/look.rs +++ b/crates/tunal/src/folder/look.rs @@ -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)>>; @@ -46,13 +46,12 @@ pub fn read(dir: &Path) -> Option { } pub fn from_meta(meta: &DirMeta) -> Option { - static THEME: OnceLock = OnceLock::new(); let look = Look { name: meta.name(), glyph: meta.glyph(), picture: meta .icon() - .and_then(|i| THEME.get_or_init(IconTheme::load_places).find(i, 64)), + .and_then(|i| file_icons::places_theme().find(i, 64)), }; (look != Look::default()).then_some(look) } diff --git a/crates/tunal/src/folder/mod.rs b/crates/tunal/src/folder/mod.rs index f8af0c8..ed98bcb 100644 --- a/crates/tunal/src/folder/mod.rs +++ b/crates/tunal/src/folder/mod.rs @@ -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>) { + /// 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>, files: Vec>) { 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 { 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 { diff --git a/crates/tunal/src/icon_picker.rs b/crates/tunal/src/icon_picker.rs new file mode 100644 index 0000000..e4d8519 --- /dev/null +++ b/crates/tunal/src/icon_picker.rs @@ -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)> { + 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) -> 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)>, +) -> (Vec, Vec) { + 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."; diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs index d4e1325..6b1914f 100644 --- a/crates/tunal/src/main.rs +++ b/crates/tunal/src/main.rs @@ -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; diff --git a/crates/tunal/src/net_bridge.rs b/crates/tunal/src/net_bridge.rs index 7f9c8c8..3e7ca18 100644 --- a/crates/tunal/src/net_bridge.rs +++ b/crates/tunal/src/net_bridge.rs @@ -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(), ); } diff --git a/crates/tunal/src/open.rs b/crates/tunal/src/open.rs index 184f780..5208825 100644 --- a/crates/tunal/src/open.rs +++ b/crates/tunal/src/open.rs @@ -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) .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"), diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs index 37b93d4..e85ad70 100644 --- a/crates/tunal/src/shell/mod.rs +++ b/crates/tunal/src/shell/mod.rs @@ -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::::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 { + 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 { 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) { + 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)) { + 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); diff --git a/crates/tunal/src/shell/place_icon.rs b/crates/tunal/src/shell/place_icon.rs new file mode 100644 index 0000000..30cd169 --- /dev/null +++ b/crates/tunal/src/shell/place_icon.rs @@ -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> = 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)>) { + 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); +} diff --git a/crates/tunal/src/shell/places.rs b/crates/tunal/src/shell/places.rs index b4767db..70d2f86 100644 --- a/crates/tunal/src/shell/places.rs +++ b/crates/tunal/src/shell/places.rs @@ -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, + /// The file `icon` stands for, if it is no glyph. + pub picture: Option, + /// 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) -> Self { + self.set_icon(icon); + self + } + + fn set_icon(&mut self, icon: Option) { + 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 { + 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, + #[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 { + 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, + bookmarks: Vec, + /// The Places section in its order, once the user changed it. + places: Vec, /// Keys of the collapsed sections. collapsed: Vec, } pub struct Places { - standard: Vec, + places: Vec, bookmarks: Vec, devices: Vec, network: Vec, @@ -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> { + 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) { + 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(§ion); 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) { + 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), + ) { + 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) -> Vec { + 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 { 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 { 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") diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint index ca152cb..2928bcf 100644 --- a/crates/tunal/ui/app.slint +++ b/crates/tunal/ui/app.slint @@ -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 place-icon-choice; + in-out property place-icon-image; + in property place-icon-error; + callback place-icon-saved(); in property 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%; diff --git a/crates/tunal/ui/components/drop-menu.slint b/crates/tunal/ui/components/drop-menu.slint index 2fd175f..6f15f4b 100644 --- a/crates/tunal/ui/components/drop-menu.slint +++ b/crates/tunal/ui/components/drop-menu.slint @@ -5,8 +5,8 @@ import { Menu } from "menu.slint"; // What a drop landed on; `a` and `b` of the Dnd callbacks name it: // row (pane, row), pane (pane, -), tab (tab, -), crumb (crumb, -), place (section, index), -// bookmarks (the bookmarks section: adds folders). -export enum DropTarget { row, pane, tab, crumb, place, bookmarks } +// section (section, slot or -1 for the end: adds folders to the sidebar). +export enum DropTarget { row, pane, tab, crumb, place, section } // What the drop does: `ask` opens the drop menu (no modifier held). export enum DropAction { ask, move, copy, link } @@ -21,8 +21,8 @@ export global Dnd { pure callback payload(pane: int, row: int, fresh: bool) -> data-transfer; // The picture under the pointer: the first name and, for several items, their count. pure callback image(pane: int, row: int, fresh: bool, fill: color, ink: color, badge: color, badge-ink: color) -> image; - // A bookmark's payload (reordering). - pure callback bookmark-payload(index: int) -> data-transfer; + // A sidebar entry's payload (moving it to another slot). + pure callback place-payload(section: int, index: int) -> data-transfer; pure callback accepts(data: data-transfer, target: DropTarget, a: int, b: int) -> bool; // At window coordinates, for the drop menu. callback dropped(data: data-transfer, action: DropAction, target: DropTarget, a: int, b: int, x: length, y: length); diff --git a/crates/tunal/ui/components/icon-picker.slint b/crates/tunal/ui/components/icon-picker.slint new file mode 100644 index 0000000..b964f92 --- /dev/null +++ b/crates/tunal/ui/components/icon-picker.slint @@ -0,0 +1,95 @@ +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { StateLayer } from "state-layer.slint"; +import { TextField } from "text-field.slint"; +import { Shape, ShapeKind } from "shape.slint"; + +// One icon the picker offers: a Material glyph, or an image from the icon theme. The first +// one is the default look. +export struct IconChoice { + glyph: string, + picture: image, + has-picture: bool, + label: string, +} + +component Cell inherits StateLayer { + in property choice; + in property selected; + + width: 44px; + height: 44px; + border-radius: Theme.corner-md; + focusable: false; + tooltip: root.choice.label; + accessible-role: radio-button; + accessible-label: root.choice.label; + accessible-checkable: true; + accessible-checked: root.selected; + + Rectangle { + border-radius: parent.border-radius; + background: Theme.secondary-container; + opacity: root.selected ? 1 : 0; + animate opacity { + duration: Motion.time(Motion.short4); + easing: Motion.standard; + } + } + + Shape { + size: 32px; + x: (root.width - self.width) / 2; + y: (root.height - self.height) / 2; + plain: !Theme.icon-shapes; + shape: ShapeKind.cookie9; + fill: root.selected ? Theme.primary : Theme.primary-container; + glyph: root.choice.glyph; + picture: root.choice.picture; + has-picture: root.choice.has-picture; + glyph-color: self.plain ? Theme.on-secondary-container : root.selected ? Theme.on-primary : Theme.on-primary-container; + } +} + +// Cells to choose an icon from, and a field for an image file that takes their place. +export component IconPicker inherits VerticalLayout { + in property <[IconChoice]> icons; + in-out property choice; + in-out property image-path; + callback accepted(); + + spacing: Theme.space-4; + + Text { + text: "Icon"; + color: Theme.on-surface-variant; + font-size: Theme.label-medium.size; + font-weight: Theme.label-medium.weight; + } + + // Wraps in rows of cells; the height follows the number of choices. + property columns: 9; + Rectangle { + height: ceil(root.icons.length / root.columns) * 44px; + + for item[i] in root.icons: Cell { + x: mod(i, root.columns) * 46px; + y: floor(i / root.columns) * 44px; + choice: item; + selected: i == root.choice && root.image-path == ""; + clicked => { + root.choice = i; + root.image-path = ""; + } + } + } + + TextField { + label: "Or an image file"; + placeholder: "/path/to/picture.png"; + text <=> root.image-path; + accepted => { + root.accepted(); + } + } +} diff --git a/crates/tunal/ui/dialogs/folder-appearance.slint b/crates/tunal/ui/dialogs/folder-appearance.slint index faca42b..1aba18c 100644 --- a/crates/tunal/ui/dialogs/folder-appearance.slint +++ b/crates/tunal/ui/dialogs/folder-appearance.slint @@ -1,58 +1,10 @@ import { Theme } from "../theme.slint"; -import { Motion } from "../motion.slint"; import { Icon, Icons } from "../components/icon.slint"; import { Dialog } from "../components/dialog.slint"; import { ButtonKind } from "../components/button.slint"; -import { StateLayer } from "../components/state-layer.slint"; import { Switch } from "../components/switch.slint"; import { TextField } from "../components/text-field.slint"; -import { Shape, ShapeKind } from "../components/shape.slint"; - -// One icon the picker offers: a Material glyph, or an image from the icon theme. The first -// one is the folder's default look. -export struct IconChoice { - glyph: string, - picture: image, - has-picture: bool, - label: string, -} - -component Cell inherits StateLayer { - in property choice; - in property selected; - - width: 44px; - height: 44px; - border-radius: Theme.corner-md; - focusable: false; - tooltip: root.choice.label; - accessible-role: radio-button; - accessible-label: root.choice.label; - accessible-checkable: true; - accessible-checked: root.selected; - - Rectangle { - border-radius: parent.border-radius; - background: Theme.secondary-container; - opacity: root.selected ? 1 : 0; - animate opacity { - duration: Motion.time(Motion.short4); - easing: Motion.standard; - } - } - - Shape { - size: 32px; - x: (root.width - self.width) / 2; - y: (root.height - self.height) / 2; - shape: ShapeKind.cookie9; - fill: root.selected ? Theme.primary : Theme.primary-container; - glyph: root.choice.glyph; - picture: root.choice.picture; - has-picture: root.choice.has-picture; - glyph-color: root.selected ? Theme.on-primary : Theme.on-primary-container; - } -} +import { IconChoice, IconPicker } from "../components/icon-picker.slint"; // Display name, icon and per-folder view settings of one folder. `saved` runs on Save with the // fields; the owner closes the dialog, or sets `error` (with `can-elevate` after a permission @@ -98,36 +50,15 @@ export component FolderAppearanceDialog inherits Dialog { } } - Text { - text: "Icon"; - color: Theme.on-surface-variant; - font-size: Theme.label-medium.size; - font-weight: Theme.label-medium.weight; - } - - // Wraps in rows of cells; the height follows the number of choices. - property columns: 9; - Rectangle { - height: ceil(root.icons.length / root.columns) * 44px; - - for item[i] in root.icons: Cell { - x: mod(i, root.columns) * 46px; - y: floor(i / root.columns) * 44px; - choice: item; - selected: i == root.choice && root.image-path == ""; - clicked => { - root.choice = i; - root.image-path = ""; - } + IconPicker { + icons: root.icons; + choice <=> root.choice; + image-path <=> root.image-path; + accepted => { + root.saved(root.can-elevate); } } - TextField { - label: "Or an image file"; - placeholder: "/path/to/picture.png"; - text <=> root.image-path; - } - HorizontalLayout { spacing: Theme.space-3; diff --git a/crates/tunal/ui/dialogs/place-icon.slint b/crates/tunal/ui/dialogs/place-icon.slint new file mode 100644 index 0000000..241484b --- /dev/null +++ b/crates/tunal/ui/dialogs/place-icon.slint @@ -0,0 +1,46 @@ +import { Theme } from "../theme.slint"; +import { Icons } from "../components/icon.slint"; +import { Dialog } from "../components/dialog.slint"; +import { ButtonKind } from "../components/button.slint"; +import { IconChoice, IconPicker } from "../components/icon-picker.slint"; + +// The icon of one sidebar entry. `saved` runs on Save; the owner closes the dialog or sets +// `error`. +export component PlaceIconDialog inherits Dialog { + in property <[IconChoice]> icons; + in-out property choice; + in-out property image-path; + in property error; + callback saved(); + + glyph: Icons.edit; + title: "Change icon"; + body: "Changes the sidebar only. The folder keeps its own icon."; + dialog-width: 456px; + actions: [{ text: "Cancel", kind: ButtonKind.text }, { text: "Save", kind: ButtonKind.filled }]; + default-action: 1; + cancel-action: 0; + action(i) => { + if i == 1 { + root.saved(); + } else { + root.close(); + } + } + + IconPicker { + icons: root.icons; + choice <=> root.choice; + image-path <=> root.image-path; + accepted => { + root.saved(); + } + } + + if root.error != "": Text { + text: root.error; + color: Theme.error; + font-size: Theme.body-small.size; + wrap: word-wrap; + } +} diff --git a/crates/tunal/ui/dialogs/settings.slint b/crates/tunal/ui/dialogs/settings.slint index 45d5bdb..8309ac5 100644 --- a/crates/tunal/ui/dialogs/settings.slint +++ b/crates/tunal/ui/dialogs/settings.slint @@ -264,7 +264,7 @@ export component SettingsDialog inherits Dialog { Setting { title: "Show previews"; - hint: "Thumbnails of images, covers and videos. The toolbar button sets it per folder."; + hint: "Thumbnails, file-type icons and folders' own icons. Off: plain icons."; Switch { checked: root.data.previews; changed checked => { diff --git a/crates/tunal/ui/shell/sidebar.slint b/crates/tunal/ui/shell/sidebar.slint index 0c9cc24..56f0fc6 100644 --- a/crates/tunal/ui/shell/sidebar.slint +++ b/crates/tunal/ui/shell/sidebar.slint @@ -12,6 +12,9 @@ export struct PlaceItem { // The real name of a folder shown by another one. tip: string, glyph: string, + // An image in place of the glyph. + picture: image, + has-picture: bool, // Shows the selection fill: the active pane is at this place. current: bool, } @@ -25,6 +28,8 @@ export struct SidebarSection { empty: string, // Offers "Add the current folder" in its header (bookmarks). can-add: bool, + // Takes folders, and its entries can be moved (places, bookmarks). + editable: bool, // Offers "Add a connection" in its header (network). can-connect: bool, } @@ -119,13 +124,15 @@ export component Sidebar inherits Rectangle { callback item-menu(section: int, index: int, x: length, y: length); property row-height: 44px; + // The drop strip between two rows. + property gap-height: 12px; // Resting shapes of the place glyphs, in turn; the current place morphs to a cookie9. property <[ShapeKind]> shapes: [ShapeKind.cookie6, ShapeKind.clover, ShapeKind.cookie12, ShapeKind.scallop, ShapeKind.cookie4]; // On the window's surface-container: the sidebar has no fill of its own. Flickable { - // Mouse drags start drags of bookmarks; the wheel scrolls. + // Mouse drags start drags of entries; the wheel scrolls. mouse-drag-pan-enabled: false; content-height: max(self.height, column.preferred-height); @@ -150,9 +157,9 @@ export component Sidebar inherits Rectangle { root.add-connection(); } - // Folders dropped on the header become bookmarks (Rust accepts only there). + // Folders dropped on the header join the section (if it takes any). DropZone { - target: DropTarget.bookmarks; + target: DropTarget.section; a: s; radius: parent.border-radius; } @@ -178,15 +185,15 @@ export component Sidebar inherits Rectangle { overflow: elide; } - // Files dropped on the empty bookmarks text become bookmarks too. + // So do those dropped on the empty section's text. if section.items.length == 0: DropZone { - target: DropTarget.bookmarks; + target: DropTarget.section; a: s; radius: Theme.corner-full(root.row-height); } - // A place takes drops into its folder; a bookmark dragged onto another - // takes its slot. + // A place takes drops into its folder; an entry dragged onto another takes + // its slot. A thin strip between two takes folders into the section. for item[i] in section.items: Rectangle { x: 0; y: i * root.row-height; @@ -200,13 +207,15 @@ export component Sidebar inherits Rectangle { radius: place.border-radius; DragArea { - enabled: section.can-add; + enabled: section.editable; allow-move: true; - data: Dnd.bookmark-payload(i); + data: Dnd.place-payload(s, i); place := ListRow { height: root.row-height; icon: item.glyph; + picture: item.picture; + has-picture: item.has-picture; title: item.name; tooltip: item.tip; selected: item.current; @@ -227,6 +236,24 @@ export component Sidebar inherits Rectangle { } } } + + if section.editable: DropZone { + y: i == 0 ? 0 : -self.height / 2; + height: root.gap-height; + target: DropTarget.section; + a: s; + b: i; + radius: Theme.corner-full(self.height); + } + } + + if section.editable && section.items.length > 0: DropZone { + y: parent.full - self.height; + height: root.gap-height; + target: DropTarget.section; + a: s; + b: section.items.length; + radius: Theme.corner-full(self.height); } } } diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index e2a1fb2..d60f6ca 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -292,5 +292,10 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Verified: clippy on tunal + tunal-theme, fmt, release build, two PNGs (settings page; Opus file in the playing bar with plain icons and a green palette). - Not done: no test run (user: save credits); Pick… not tried live. +## Theme file icons, sidebar icons and Places drops (user request) +- Done: `file_icons.rs` (shared MIME globs + first bytes → icon theme picture; user folders; `.desktop` icons), shown while previews are on; off = plain glyphs, no `.directory` icon (its name stays). Places and Bookmarks: drop folders on the header or between rows, move entries within and across the two by drag, Change icon… (`icon_picker.rs`, `ui/components/icon-picker.slint` shared with folder appearance). `places.toml` gains `places`, `icon`, `standard`. +- Verified: clippy on tunal, fmt, release build; PNGs (previews on/off), drags (folder → Places, bookmark → Places), icon dialog saved under Xvfb. +- Not done: no test run (user: save credits); MIME globs with wildcards in the middle are ignored. + ## Later -