From 7b13c1658e6348fb78f5d3f3625723188edf050f Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 01:51:39 -0600 Subject: [PATCH] Seek bar, spring motion, archive formats, file pickers, icon browser and launchers Seeking and the sidebar selection spring to the click. Compress and extract cover the 7z formats. Path fields get a file picker, icon dialogs a browser with categories. Create new makes launchers, Edit launcher changes them. New tabs open Home and a file path opens its folder. Dialogs opened from a menu keep the focus. Remote noted in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +- crates/tunal-theme/src/lib.rs | 2 +- crates/tunal-theme/src/portal.rs | 93 +++++- crates/tunal/src/actions.rs | 63 +++- crates/tunal/src/desktop_apps.rs | 73 ++++- crates/tunal/src/file_icons.rs | 13 + crates/tunal/src/file_picker.rs | 67 ++++ crates/tunal/src/folder/appearance.rs | 23 +- crates/tunal/src/folder/look.rs | 4 +- crates/tunal/src/icon_picker.rs | 143 ++++++++- crates/tunal/src/launcher.rs | 293 ++++++++++++++++++ crates/tunal/src/main.rs | 4 + crates/tunal/src/menus.rs | 1 + crates/tunal/src/player_bridge.rs | 7 +- crates/tunal/src/shell/mod.rs | 64 +++- crates/tunal/src/shell/path.rs | 5 + crates/tunal/src/shell/place_icon.rs | 35 ++- crates/tunal/src/shell/places.rs | 2 +- crates/tunal/src/tools.rs | 267 ++++++++++++---- crates/tunal/ui/app.slint | 39 ++- crates/tunal/ui/components/dialog.slint | 19 ++ crates/tunal/ui/components/icon-picker.slint | 160 +++++++++- crates/tunal/ui/components/icon.slint | 1 + crates/tunal/ui/components/list-row.slint | 4 +- crates/tunal/ui/components/text-field.slint | 47 ++- crates/tunal/ui/dialogs/connection.slint | 3 +- .../tunal/ui/dialogs/folder-appearance.slint | 5 +- crates/tunal/ui/dialogs/launcher.slint | 126 ++++++++ crates/tunal/ui/dialogs/place-icon.slint | 5 +- crates/tunal/ui/dialogs/tag-editor.slint | 8 +- crates/tunal/ui/motion.slint | 3 + crates/tunal/ui/shell/player-bar.slint | 48 ++- crates/tunal/ui/shell/sidebar.slint | 38 +++ docs/PROGRESS.md | 6 + 34 files changed, 1531 insertions(+), 144 deletions(-) create mode 100644 crates/tunal/src/file_picker.rs create mode 100644 crates/tunal/src/launcher.rs create mode 100644 crates/tunal/ui/dialogs/launcher.slint diff --git a/CLAUDE.md b/CLAUDE.md index df80dfc..92dc85c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,7 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~ - **User validates personally (šŸ§‘)**, all in phase 12 (D-009): visual review (S035), the polkit password prompt, real iPhone/Android devices, native drag/clipboard with other apps, a real SFTP host (S036). Plans that need these stop at that step and report. - **Design references (read only, D-027, D-028)**: the user's own Material You apps — `~/Projects/Damson` (`src/theme.rs`, `src/motion.rs`, `src/ui/`), `~/Projects/Mulberry` (`src/theme.rs`, `src/ui/`), `~/Projects/Nacre` (`src/theme.rs`, `src/ui/widgets.rs`, `src/ui/chrome.rs`). They use egui, not Slint: borrow look and feel (colour roles, state layers, shapes, spacing, motion curves and timings) and port the idea to our Slint tokens; never change our stack, never edit them. Their code is the user's own, so copying is allowed where it fits. Also the user's old, buggy Tunal prototype in `/home/astar76/Documents/Apps/tunal-files/tunal/` (Python): look at its elements for ideas only, never copy its code — the new UI is meant to be new. A library default that looks off is not a reason to accept it: build the control ourselves on `Theme`/`Motion`. - **Motion rules** (`app-taste` skill): tokens only, hover tint and press squeeze on every control, interruptible motion, honour reduced motion, no idle animation, repaint only while something moves. Build new motion with the `animate` skill; `/unslop` and `/improve-animations` run in phase 12 (S034, S035; there is no `/review-animations`). -- No Forgejo remote yet: the user wants local-only git for now. +- Remote: `origin` = `forgejo:astar76/Tunal.git` (Astar Hub, private), since 2026-11-25. ## 3. Code rules @@ -104,7 +104,7 @@ Don't assume a tool exists: check first. When your plan creates a tool, add its ## 6. Git -Local repository only; no remote and no push until the user says so. `.gitignore` covers `target/`. One commit per logical step, message `SNNN: …` in English. No `reset --hard` / force push without an explicit request. +Remote `origin` is Astar Hub (`forgejo:astar76/Tunal.git`); the user asked for the first push on 2026-11-25. `.gitignore` covers `target/`. One commit per logical step, message `SNNN: …` in English. No `reset --hard` / force push without an explicit request. ## 7. Definition of done diff --git a/crates/tunal-theme/src/lib.rs b/crates/tunal-theme/src/lib.rs index 320b527..16b76f1 100644 --- a/crates/tunal-theme/src/lib.rs +++ b/crates/tunal-theme/src/lib.rs @@ -4,7 +4,7 @@ mod palette; mod portal; pub use palette::{FALLBACK_SEED, Palette, Palettes, Style}; -pub use portal::{pick_color, read, watch}; +pub use portal::{pick_color, pick_file, read, watch}; /// Accent colour as the portal reports it: sRGB components in `0.0..=1.0`. #[derive(Debug, Clone, Copy, PartialEq)] diff --git a/crates/tunal-theme/src/portal.rs b/crates/tunal-theme/src/portal.rs index f88921e..b6d91bc 100644 --- a/crates/tunal-theme/src/portal.rs +++ b/crates/tunal-theme/src/portal.rs @@ -1,6 +1,10 @@ -//! `org.freedesktop.portal.Settings` and the screen colour picker over the session bus (zbus blocking API). +//! `org.freedesktop.portal.Settings`, the screen colour picker and the file picker over the +//! session bus (zbus blocking API). use std::collections::HashMap; +use std::ffi::OsString; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; +use std::path::{Path, PathBuf}; use std::thread::{self, JoinHandle}; use zbus::blocking::{Connection, Proxy, proxy::Builder}; @@ -64,10 +68,13 @@ fn watch_loop(on_change: impl Fn(Appearance)) -> zbus::Result<()> { Ok(()) } -/// Lets the user pick a colour from the screen (the Screenshot portal) and waits for it: -/// `Ok(None)` when they cancel. Blocks; call it off the UI thread. -pub fn pick_color() -> zbus::Result> { - const TOKEN: &str = "tunal_pick_color"; +/// Makes a portal request and waits for its answer: `Ok(None)` when the user cancels. `call` +/// gets the portal object and the handle token to pass on. +fn request( + interface: &'static str, + token: &'static str, + call: impl FnOnce(&Proxy, Value<'static>) -> zbus::Result, +) -> zbus::Result>> { let conn = Connection::session()?; let sender = conn .unique_name() @@ -77,20 +84,19 @@ pub fn pick_color() -> zbus::Result> { let request: Proxy = Builder::new(&conn) .destination("org.freedesktop.portal.Desktop")? .path(format!( - "/org/freedesktop/portal/desktop/request/{sender}/{TOKEN}" + "/org/freedesktop/portal/desktop/request/{sender}/{token}" ))? .interface("org.freedesktop.portal.Request")? .cache_properties(CacheProperties::No) .build()?; let mut responses = request.receive_signal("Response")?; - let options = HashMap::from([("handle_token", Value::from(TOKEN))]); let portal = Proxy::new( &conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", - "org.freedesktop.portal.Screenshot", + interface, )?; - let _: OwnedObjectPath = portal.call("PickColor", &("", options))?; + call(&portal, Value::from(token))?; let Some(msg) = responses.next() else { return Ok(None); }; @@ -99,12 +105,77 @@ pub fn pick_color() -> zbus::Result> { .deserialize::<(u32, HashMap)>()?; // 0 picked, 1 cancelled, 2 ended some other way. match code { - 0 => Ok(results.get("color").and_then(parse_accent).map(|c| c.rgb())), + 0 => Ok(Some(results)), 1 => Ok(None), - _ => Err(zbus::Error::Failure("the colour picker failed".into())), + _ => Err(zbus::Error::Failure("the portal request failed".into())), } } +/// Lets the user pick a colour from the screen (the Screenshot portal) and waits for it: +/// `Ok(None)` when they cancel. Blocks; call it off the UI thread. +pub fn pick_color() -> zbus::Result> { + let results = request( + "org.freedesktop.portal.Screenshot", + "tunal_pick_color", + |portal, token| portal.call("PickColor", &("", HashMap::from([("handle_token", token)]))), + )?; + Ok(results + .and_then(|r| r.get("color").and_then(parse_accent)) + .map(|c| c.rgb())) +} + +/// Lets the user choose one local file (the FileChooser portal), of the MIME types `types` +/// (all for none), starting in `folder`: `Ok(None)` when they cancel. Blocks; call it off the +/// UI thread. +pub fn pick_file( + title: &str, + types: &[&str], + folder: Option<&Path>, +) -> zbus::Result> { + let mut options: HashMap<&str, Value> = HashMap::new(); + if !types.is_empty() { + // Kind 1 is a MIME type (0 a pattern). + let list: Vec<(u32, String)> = types.iter().map(|t| (1, (*t).to_owned())).collect(); + options.insert("filters", Value::new(vec![("Images".to_owned(), list)])); + } + if let Some(folder) = folder { + let mut bytes = folder.as_os_str().as_bytes().to_vec(); + bytes.push(0); + options.insert("current_folder", Value::new(bytes)); + } + let results = request( + "org.freedesktop.portal.FileChooser", + "tunal_pick_file", + |portal, token| { + options.insert("handle_token", token); + portal.call("OpenFile", &("", title, options)) + }, + )?; + let uris = results + .as_ref() + .and_then(|r| r.get("uris")) + .and_then(|v| v.downcast_ref::().ok()) + .and_then(|a| a.get::(0).ok().flatten()); + Ok(uris.as_deref().and_then(file_path)) +} + +/// The path of a `file:` URI. +fn file_path(uri: &str) -> Option { + let path = uri.strip_prefix("file://")?; + let path = &path[path.find('/')?..]; + let mut bytes = Vec::with_capacity(path.len()); + let mut rest = path.as_bytes(); + while let [first, tail @ ..] = rest { + let hex = (*first == b'%') + .then(|| std::str::from_utf8(tail.get(..2)?).ok()) + .flatten() + .and_then(|h| u8::from_str_radix(h, 16).ok()); + bytes.push(hex.unwrap_or(*first)); + rest = if hex.is_some() { &tail[2..] } else { tail }; + } + Some(PathBuf::from(OsString::from_vec(bytes))) +} + fn connect() -> zbus::Result> { let conn = Connection::session()?; Builder::new(&conn) diff --git a/crates/tunal/src/actions.rs b/crates/tunal/src/actions.rs index d1f22cb..f217ca5 100644 --- a/crates/tunal/src/actions.rs +++ b/crates/tunal/src/actions.rs @@ -18,6 +18,7 @@ use crate::config::Executables; use crate::folder::appearance::Appearance; use crate::jobs_bridge::Bridge; use crate::keymap::Command; +use crate::launcher::{self, Launcher}; use crate::menus::{self, Context as MenuContext, Menus}; use crate::open::Opener; use crate::player_bridge::{self, PlayerUi}; @@ -53,8 +54,9 @@ pub enum Action { Properties, Appearance, EditTags, + EditLauncher, Play, - /// Submenu: a folder, a text file or an empty file. + /// Submenu: a folder, a text file, an empty file or a launcher. CreateNew, Duplicate, AddToPlaces, @@ -75,7 +77,7 @@ pub enum Action { } impl Action { - pub const ALL: [Action; 36] = [ + pub const ALL: [Action; 37] = [ Self::Cut, Self::Copy, Self::Paste, @@ -97,6 +99,7 @@ impl Action { Self::Properties, Self::Appearance, Self::EditTags, + Self::EditLauncher, Self::Play, Self::CreateNew, Self::Duplicate, @@ -137,6 +140,7 @@ impl Action { Self::Properties => "properties", Self::Appearance => "appearance", Self::EditTags => "edit-tags", + Self::EditLauncher => "edit-launcher", Self::Play => "play", Self::CreateNew => "create-new", Self::Duplicate => "duplicate", @@ -182,6 +186,7 @@ impl Action { Self::Properties => "Properties", Self::Appearance => "Folder appearance…", Self::EditTags => "Edit tags…", + Self::EditLauncher => "Edit launcher…", Self::Play => "Play", Self::CreateNew => "Create new", Self::Duplicate => "Duplicate here", @@ -223,6 +228,7 @@ impl Action { Self::Properties => "\u{e88e}", Self::Appearance => "\u{e40a}", Self::EditTags => "\u{e892}", + Self::EditLauncher => "\u{eb9b}", Self::Play => "\u{e037}", Self::CreateNew => "\u{e89c}", Self::Duplicate => "\u{e173}", @@ -243,6 +249,7 @@ impl Action { pub fn shown(self, ctx: &Context) -> bool { match self { Self::Play => ctx.audio, + Self::EditLauncher => ctx.launcher, Self::Run => ctx.executable, Self::RunInTerminal => ctx.executable && tools::terminal().is_some(), Self::Terminal => ctx.local && tools::terminal().is_some(), @@ -282,6 +289,7 @@ impl Action { Self::Properties | Self::SortBy | Self::ViewMode => true, Self::Appearance => files && ctx.selected <= 1, Self::EditTags => files && ctx.taggable, + Self::EditLauncher => files && ctx.launcher, Self::Play => files && ctx.audio, } } @@ -300,6 +308,8 @@ pub struct Context { pub taggable: bool, /// Every selected entry is a local audio file (Play; a video plays only when asked). pub audio: bool, + /// One local launcher (`.desktop` file) is selected. + pub launcher: bool, /// One local executable file is selected. pub executable: bool, /// Every selected entry is a folder. @@ -350,6 +360,7 @@ pub struct Actions { opener: Rc, properties: Rc, appearance: Rc, + launcher: Rc, tags: Rc, player: Rc, } @@ -372,6 +383,7 @@ impl Actions { let opener = Opener::attach(ui, locations.clone(), bridge.clone()); let properties = Properties::attach(ui, locations.clone()); let appearance = Appearance::attach(ui, bridge.elevation()); + let launcher = Launcher::attach(ui); let tags = Tags::attach(ui, bridge.clone()); let player = PlayerUi::attach(ui, bridge.clone()); let actions = Rc::new_cyclic(|me| Self { @@ -388,6 +400,7 @@ impl Actions { opener, properties, appearance, + launcher, tags, player, }); @@ -399,6 +412,14 @@ impl Actions { } }); let me = actions.me.clone(); + actions.launcher.on_made(move |name| { + let shell = me.upgrade().and_then(|m| m.shell()); + if let Some(pane) = shell.and_then(|s| s.active()) { + let name = std::os::unix::ffi::OsStrExt::as_bytes(name).to_vec(); + pane.model.select_when_shown(name, false); + } + }); + let me = actions.me.clone(); actions.appearance.on_saved(move |dir, remembered| { if let Some(me) = me.upgrade() { me.appearance_saved(dir, remembered); @@ -473,6 +494,8 @@ impl Actions { Context { taggable: files && selected.iter().all(tags_bridge::can_tag), audio: files && selected.iter().all(player_bridge::is_audio), + launcher: files + && matches!(selected.as_slice(), [only] if only.to_path().is_some_and(|p| launcher::is_launcher(&p))), executable: match (entries.as_slice(), &dir) { ([only], Some(dir)) => executable(dir, only).is_some(), _ => false, @@ -569,11 +592,20 @@ impl Actions { entry("Folder", Action::NewFolder.glyph(), false), entry("Text file", "\u{f1c6}", false), entry("Empty file", "\u{e873}", false), + entry( + "Launcher…", + Action::EditLauncher.glyph(), + pane.dir().is_none_or(|d| d.to_path().is_none()), + ), ], Action::CopyTo | Action::MoveTo => self.target_entries(pane), Action::Compress => Format::ALL .into_iter() - .map(|f| entry(f.label(), Action::Compress.glyph(), !tools::can_compress(f))) + .map(|f| { + let fits = !f.single() || self.one_file(pane); + let usable = fits && tools::can_compress(f); + entry(f.label(), Action::Compress.glyph(), !usable) + }) .collect(), _ => Vec::new(), } @@ -656,7 +688,12 @@ impl Actions { match sub { 0 => self.new_folder(&pane, dir), 1 => self.new_file(&pane, dir, b"New text file.txt"), - _ => self.new_file(&pane, dir, b"New file"), + 2 => self.new_file(&pane, dir, b"New file"), + _ => { + if let Some(path) = dir.to_path() { + self.launcher.create(path); + } + } } } } @@ -916,6 +953,12 @@ impl Actions { } return; } + Action::EditLauncher => { + if let Some(path) = uris.first().and_then(|u| u.to_path()) { + self.report(self.launcher.edit(path)); + } + return; + } Action::EditTags => { let files: Vec<_> = uris.iter().filter_map(|u| u.to_path()).collect(); if !files.is_empty() { @@ -1076,6 +1119,11 @@ impl Actions { self.bridge.submit(JobKind::CreateFile(dir.join(&name))); } + /// One file and no folder is selected. + fn one_file(&self, pane: &Pane) -> bool { + pane.model.selected_uris().len() == 1 && !pane.model.selection_is_dir() + } + /// Packs the selection into one archive next to it, named after the one item (or the /// folder), in the background. fn compress(&self, pane: &Pane, format: Format) { @@ -1157,7 +1205,12 @@ impl Actions { } let cmd = tools::extract_command(&archive, &target) .ok_or("No tool here unpacks this archive")?; - tools::run_to_end(cmd, cancel)?; + let done = tools::run_to_end(cmd, cancel); + if make && done.is_err() { + // Nothing came out: no empty folder stays (one with files does). + let _ = std::fs::remove_dir(&target); + } + done?; } Ok(format!("Extracted {title}")) }); diff --git a/crates/tunal/src/desktop_apps.rs b/crates/tunal/src/desktop_apps.rs index b215138..de6ef82 100644 --- a/crates/tunal/src/desktop_apps.rs +++ b/crates/tunal/src/desktop_apps.rs @@ -119,7 +119,7 @@ fn split_list(value: &str) -> Vec { } /// Undoes the desktop entry value escapes (`\s \n \t \r \\`). -fn unescape(value: &str) -> String { +pub fn unescape(value: &str) -> String { let mut out = String::new(); let mut chars = value.chars(); while let Some(c) = chars.next() { @@ -140,7 +140,7 @@ fn unescape(value: &str) -> String { } /// `Name[de_DE]` suffixes to try, most specific first, from `LC_MESSAGES` / `LANG`. -fn locale_suffixes() -> Vec { +pub fn locale_suffixes() -> Vec { let lang = ["LC_ALL", "LC_MESSAGES", "LANG"] .iter() .find_map(|v| std::env::var(v).ok().filter(|v| !v.is_empty())) @@ -584,6 +584,17 @@ struct ThemeDir { theme: usize, } +impl ThemeDir { + /// How far its icons are from `size` px; scalable ones match any size. + fn distance(&self, size: u32) -> u32 { + if self.scalable { + 0 + } else { + self.size.abs_diff(size) + 1 + } + } +} + /// What a theme directory's icons are for. #[derive(Clone, Copy, PartialEq, Eq)] pub enum IconContext { @@ -592,13 +603,25 @@ pub enum IconContext { Places, /// File types. Types, + Devices, + /// Emblems, states, actions and emoticons. + Symbols, + /// Everything drawn at a size worth showing (no small tool and panel icons). + Any, } impl IconContext { - const ALL: [(Self, &str, &str); 3] = [ + const ALL: [(Self, &str, &str); 9] = [ (Self::Apps, "Applications", "apps"), (Self::Places, "Places", "places"), (Self::Types, "MimeTypes", "mimetypes"), + (Self::Devices, "Devices", "devices"), + (Self::Symbols, "Emblems", "emblems"), + (Self::Symbols, "Status", "status"), + (Self::Symbols, "Actions", "actions"), + (Self::Symbols, "Emotes", "emotes"), + // Programs by kind: some themes keep all their app icons there too. + (Self::Apps, "Categories", "categories"), ]; /// By the directory's `Context` key, else by its path. @@ -707,7 +730,10 @@ impl IconTheme { for (index, theme) in chain.iter().enumerate() { for base in &bases { let mut found = theme_dirs(base, theme, index); - found.retain(|d| d.context == Some(context)); + found.retain(|d| match context { + IconContext::Any => d.scalable || d.size >= 48, + _ => d.context == Some(context), + }); dirs.extend(found); } } @@ -734,6 +760,34 @@ impl IconTheme { names } + /// Every icon by name with its file at about `size` px and what it is for, sorted (no + /// `-symbolic` ones). + pub fn all(&self, size: u32) -> Vec<(String, PathBuf, Option)> { + let mut dirs: Vec<&ThemeDir> = self.dirs.iter().collect(); + dirs.sort_by_key(|d| (d.theme, d.distance(size))); + let mut icons: std::collections::BTreeMap)> = + Default::default(); + let files = dirs + .iter() + .filter_map(|d| Some((d.context, fs::read_dir(&d.path).ok()?))) + .flat_map(|(context, files)| files.map(move |f| (context, f))); + for (context, entry) in files { + let Ok(entry) = entry else { continue }; + let Ok(name) = entry.file_name().into_string() else { + continue; + }; + let stem = name + .strip_suffix(".svg") + .or_else(|| name.strip_suffix(".png")); + if let Some(stem) = stem.filter(|s| !s.ends_with("-symbolic")) { + icons + .entry(stem.to_owned()) + .or_insert_with(|| (entry.path(), context)); + } + } + icons.into_iter().map(|(n, (p, c))| (n, p, c)).collect() + } + /// The file of icon `name` at about `size` px: an absolute path as is, else the closest /// size of the first theme that has it, then `pixmaps`. `None` when nothing is installed /// (callers draw a glyph). @@ -741,16 +795,9 @@ impl IconTheme { if name.starts_with('/') { return Some(PathBuf::from(name)).filter(|p| p.is_file()); } - // The first theme that has it; fixed sizes by distance, scalable ones match any size. - let distance = |d: &ThemeDir| { - if d.scalable { - 0 - } else { - d.size.abs_diff(size) + 1 - } - }; + // The first theme that has it. let mut order: Vec<&ThemeDir> = self.dirs.iter().collect(); - order.sort_by_key(|d| (d.theme, distance(d))); + order.sort_by_key(|d| (d.theme, d.distance(size))); for dir in order { for ext in ["svg", "png"] { let file = dir.path.join(format!("{name}.{ext}")); diff --git a/crates/tunal/src/file_icons.rs b/crates/tunal/src/file_icons.rs index 147a26c..5449f6d 100644 --- a/crates/tunal/src/file_icons.rs +++ b/crates/tunal/src/file_icons.rs @@ -113,6 +113,19 @@ pub fn places_theme() -> &'static IconTheme { THEME.get_or_init(|| IconTheme::load(IconContext::Places)) } +/// The theme's icons of every kind. +pub fn any_theme() -> &'static IconTheme { + static THEME: OnceLock = OnceLock::new(); + THEME.get_or_init(|| IconTheme::load(IconContext::Any)) +} + +/// The file of the theme icon (or image path) `name`: a folder icon before any other. +pub fn find(name: &str) -> Option { + places_theme() + .find(name, SIZE) + .or_else(|| any_theme().find(name, SIZE)) +} + /// The theme's picture of the type `mime`, looked up once. fn type_icon(mime: &str) -> Option { static THEME: OnceLock = OnceLock::new(); diff --git a/crates/tunal/src/file_picker.rs b/crates/tunal/src/file_picker.rs new file mode 100644 index 0000000..d5da40f --- /dev/null +++ b/crates/tunal/src/file_picker.rs @@ -0,0 +1,67 @@ +//! The desktop's file picker, for the fields that take a file's path. + +use std::path::{Path, PathBuf}; +use std::rc::{Rc, Weak}; + +use slint::ComponentHandle; + +use crate::shell::{Shell, places}; +use crate::{FileKind, FilePicks, MainWindow}; + +const IMAGES: [&str; 2] = ["image/png", "image/jpeg"]; +const ICONS: [&str; 5] = [ + "image/png", + "image/jpeg", + "image/svg+xml", + "image/webp", + "image/gif", +]; + +pub fn attach(ui: &MainWindow, shell: &Rc) { + let shell: Weak = Rc::downgrade(shell); + let weak = ui.as_weak(); + let me = shell.clone(); + ui.global::().on_failed(move || { + if let Some(shell) = me.upgrade() { + shell.notify("This desktop has no file picker.".into()); + } + }); + ui.global::() + .on_pick(move |request, kind, current| { + // Where the field's file is, else a sensible folder for its kind. + let current = Path::new(current.trim()) + .parent() + .filter(|p| p.is_absolute() && kind != FileKind::Program) + .map(Path::to_owned); + let folder: Option = current.or_else(|| match kind { + FileKind::Key => Some(places::home().join(".ssh")), + _ => shell.upgrade()?.active_dir()?.to_path(), + }); + let (title, types): (_, &'static [&'static str]) = match kind { + FileKind::Key => ("Choose a key file", &[]), + FileKind::Program => ("Choose a program", &[]), + FileKind::Cover => ("Choose a cover image", &IMAGES), + _ => ("Choose an image", &ICONS), + }; + let ui = weak.clone(); + std::thread::spawn(move || { + let picked = tunal_theme::pick_file(title, types, folder.as_deref()); + let _ = ui.upgrade_in_event_loop(move |ui| match picked { + Ok(Some(path)) => { + let picks = ui.global::(); + let path = path.to_string_lossy(); + picks.set_path(match kind { + FileKind::Program => crate::launcher::quote(&path).into(), + _ => path.as_ref().into(), + }); + picks.set_done(request); + } + Ok(None) => {} + Err(e) => { + eprintln!("tunal: file picker: {e}"); + ui.global::().invoke_failed(); + } + }); + }); + }); +} diff --git a/crates/tunal/src/folder/appearance.rs b/crates/tunal/src/folder/appearance.rs index 1693f82..b9dd89f 100644 --- a/crates/tunal/src/folder/appearance.rs +++ b/crates/tunal/src/folder/appearance.rs @@ -125,13 +125,9 @@ impl Appearance { }; let name = ui.get_appearance_name().trim().to_owned(); let image = ui.get_appearance_image().trim().to_owned(); - let pick = PICKS - .with(|p| { - p.borrow() - .get(usize::try_from(ui.get_appearance_choice()).unwrap_or(0)) - .cloned() - }) - .unwrap_or(Pick::Default); + let pick = PICKS.with(|p| { + icon_picker::picked(p, ui.get_appearance_choice(), &ui.get_appearance_browsed()) + }); if !icon_picker::valid_image(&image) { ui.set_appearance_error(icon_picker::NO_IMAGE.into()); return; @@ -187,7 +183,18 @@ fn fill(ui: &MainWindow, meta: &DirMeta, themed: Vec<(String, Option)>) { ui.set_appearance_image(icon.into()); } - ui.set_appearance_choice(current.unwrap_or(0) as i32); + // One the short list lacks came from the browser. + let browsed = match current { + None => icon_picker::browsed(meta.icon().unwrap_or_default()), + Some(_) => Default::default(), + }; + let outside = !browsed.label.is_empty(); + ui.set_appearance_browsed(browsed); + ui.set_appearance_choice(if outside { + -1 + } else { + current.unwrap_or(0) as i32 + }); ui.set_appearance_icons(ModelRc::new(VecModel::from(cells))); PICKS.with(|p| *p.borrow_mut() = picks); } diff --git a/crates/tunal/src/folder/look.rs b/crates/tunal/src/folder/look.rs index da7389f..634c58e 100644 --- a/crates/tunal/src/folder/look.rs +++ b/crates/tunal/src/folder/look.rs @@ -49,9 +49,7 @@ pub fn from_meta(meta: &DirMeta) -> Option { let look = Look { name: meta.name(), glyph: meta.glyph(), - picture: meta - .icon() - .and_then(|i| file_icons::places_theme().find(i, 64)), + picture: meta.icon().and_then(file_icons::find), }; (look != Look::default()).then_some(look) } diff --git a/crates/tunal/src/icon_picker.rs b/crates/tunal/src/icon_picker.rs index e4d8519..51004f5 100644 --- a/crates/tunal/src/icon_picker.rs +++ b/crates/tunal/src/icon_picker.rs @@ -1,10 +1,15 @@ //! The icons the icon picker offers (folder appearance, sidebar entries). +use std::cell::RefCell; use std::path::PathBuf; +use std::sync::OnceLock; -use crate::IconChoice; +use slint::{ComponentHandle, Model, ModelNotify, ModelRc, ModelTracker, VecModel}; + +use crate::desktop_apps::IconContext; use crate::file_icons; use crate::folder::look; +use crate::{IconBrowser, IconChoice, IconRow, MainWindow}; /// Material glyphs the picker offers (label, codepoint). const GLYPHS: [(&str, char); 17] = [ @@ -28,7 +33,7 @@ const GLYPHS: [(&str, char); 17] = [ ]; /// How many theme icons the picker lists. -const THEME_ICONS: usize = 18; +const THEME_ICONS: usize = 16; /// What a picker cell stands for (`Default` is cell 0). #[derive(Clone)] @@ -74,6 +79,15 @@ pub fn cells( picks.push(Pick::Glyph(glyph)); cells.push(choice(label, &glyph.to_string(), None)); } + add_themed(&mut picks, &mut cells, themed); + (picks, cells) +} + +fn add_themed( + picks: &mut Vec, + cells: &mut Vec, + themed: Vec<(String, Option)>, +) { for (name, file) in themed { let Some(image) = file.as_deref().and_then(look::picture) else { continue; @@ -81,6 +95,16 @@ pub fn cells( cells.push(choice(&name, "", Some(image))); picks.push(Pick::Theme(name)); } +} + +/// Cells of theme icons alone, after the default one. +pub fn theme_cells( + default: &str, + themed: Vec<(String, Option)>, +) -> (Vec, Vec) { + let mut picks = vec![Pick::Default]; + let mut cells = vec![choice("Default", default, None)]; + add_themed(&mut picks, &mut cells, themed); (picks, cells) } @@ -90,3 +114,118 @@ pub fn valid_image(path: &str) -> bool { } pub const NO_IMAGE: &str = "That image file doesn't exist. Use its full path."; + +/// What the dialog's `choice` stands for: a cell, or (-1) the icon the browser gave. +pub fn picked(picks: &RefCell>, choice: i32, browsed: &IconChoice) -> Pick { + if choice < 0 && !browsed.label.is_empty() { + return Pick::Theme(browsed.label.to_string()); + } + let cell = usize::try_from(choice).ok(); + cell.and_then(|i| picks.borrow().get(i).cloned()) + .unwrap_or(Pick::Default) +} + +/// The browser's cell for the theme icon `name`, empty for none by that name. +pub fn browsed(name: &str) -> IconChoice { + match file_icons::find(name).as_deref().and_then(look::picture) { + Some(image) if !name.is_empty() && !name.starts_with('/') => choice(name, "", Some(image)), + _ => IconChoice::default(), + } +} + +/// Name, file and what it is for. +type ThemeIcon = (String, PathBuf, Option); + +/// The browser's categories, in the order of its chips (the first shows all). +const CATEGORIES: [Option; 6] = [ + None, + Some(IconContext::Places), + Some(IconContext::Apps), + Some(IconContext::Types), + Some(IconContext::Devices), + Some(IconContext::Symbols), +]; + +/// Every icon of the theme with its file, read once (off the UI thread). +fn all_icons() -> &'static [ThemeIcon] { + static ALL: OnceLock> = OnceLock::new(); + ALL.get_or_init(|| file_icons::any_theme().all(64)) +} + +/// Rows of the browser; their pictures load as the list shows them. +struct Rows { + found: Vec, + columns: usize, + notify: ModelNotify, +} + +impl Model for Rows { + type Data = IconRow; + + fn row_count(&self) -> usize { + self.found.len().div_ceil(self.columns) + } + + fn row_data(&self, row: usize) -> Option { + let cells: Vec = self + .found + .chunks(self.columns) + .nth(row)? + .iter() + .map(|&i| { + let (name, file, _) = &all_icons()[i]; + choice(name, "", look::picture(file)) + }) + .collect(); + Some(IconRow { + cells: ModelRc::new(VecModel::from(cells)), + }) + } + + fn model_tracker(&self) -> &dyn ModelTracker { + &self.notify + } +} + +fn show(ui: &MainWindow, text: &str, category: i32, columns: i32) { + let category = usize::try_from(category).ok(); + let category = category.and_then(|c| CATEGORIES.get(c).copied().flatten()); + let text = text.trim().to_lowercase(); + let found: Vec = all_icons() + .iter() + .enumerate() + .filter(|(_, (_, _, context))| category.is_none() || *context == category) + .filter(|(_, (name, ..))| { + let name = name.to_lowercase(); + text.split_whitespace().all(|w| name.contains(w)) + }) + .map(|(i, _)| i) + .collect(); + let browser = ui.global::(); + browser.set_found(found.len() as i32); + browser.set_rows(ModelRc::new(Rows { + found, + columns: columns.max(1) as usize, + notify: ModelNotify::default(), + })); +} + +/// Serves the icon browser of `ui`. +pub fn attach(ui: &MainWindow) { + let weak = ui.as_weak(); + ui.global::() + .on_search(move |text, category, columns| { + let Some(ui) = weak.upgrade() else { + return; + }; + if ui.global::().get_found() >= 0 { + show(&ui, &text, category, columns); + return; + } + let weak = weak.clone(); + std::thread::spawn(move || { + all_icons(); + let _ = weak.upgrade_in_event_loop(move |ui| show(&ui, &text, category, columns)); + }); + }); +} diff --git a/crates/tunal/src/launcher.rs b/crates/tunal/src/launcher.rs new file mode 100644 index 0000000..e1a2f7f --- /dev/null +++ b/crates/tunal/src/launcher.rs @@ -0,0 +1,293 @@ +//! The launcher dialog: makes a desktop entry, or changes the plain parts of one (name, +//! description, command, icon, terminal) and keeps everything else in it. + +use std::cell::RefCell; +use std::ffi::OsStr; +use std::fs; +use std::io::{self, Write}; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +use slint::{ComponentHandle, ModelRc, VecModel}; +use tunal_dirmeta::DirMeta; + +use crate::desktop_apps::{locale_suffixes, unescape}; +use crate::icon_picker::{self, Pick}; +use crate::{LauncherData, MainWindow}; + +const ENTRY: &str = "Desktop Entry"; + +/// The plain program icon, drawn while a launcher has none. +const GLYPH: &str = "\u{eb8e}"; + +/// Theme icons the picker offers, where the theme has them. +const ICONS: [&str; 15] = [ + "utilities-terminal", + "applications-games", + "applications-internet", + "applications-multimedia", + "applications-graphics", + "applications-office", + "applications-development", + "applications-system", + "applications-utilities", + "system-file-manager", + "web-browser", + "text-editor", + "accessories-calculator", + "preferences-system", + "system-run", +]; + +enum Target { + /// A new file in this folder. + New(PathBuf), + Edit(PathBuf), +} + +type Made = Box; + +pub struct Launcher { + ui: slint::Weak, + target: RefCell>, + picks: RefCell>, + /// An icon the theme here lacks: stays while none is chosen. + kept_icon: RefCell>, + /// Called with the file name of a new launcher, before it is written. + made: RefCell, +} + +/// `path` is a desktop entry by its name. +pub fn is_launcher(path: &Path) -> bool { + path.extension().is_some_and(|e| e == "desktop") +} + +/// `path` as the command of a launcher: quoted when it has to be. +pub fn quote(path: &str) -> String { + let path = path.replace('%', "%%"); + if path + .chars() + .all(|c| c.is_alphanumeric() || "/._-+%".contains(c)) + { + return path; + } + let mut out = String::from("\""); + for c in path.chars() { + if matches!(c, '"' | '`' | '$' | '\\') { + out.push('\\'); + } + out.push(c); + } + out.push('"'); + out +} + +impl Launcher { + pub fn attach(ui: &MainWindow) -> Rc { + let me = Rc::new(Self { + ui: ui.as_weak(), + target: RefCell::new(None), + picks: RefCell::default(), + kept_icon: RefCell::default(), + made: RefCell::new(Box::new(|_| {})), + }); + let weak = Rc::downgrade(&me); + ui.on_launcher_saved(move || { + if let Some(me) = weak.upgrade() { + me.save(); + } + }); + me + } + + pub fn on_made(&self, f: impl Fn(&OsStr) + 'static) { + *self.made.borrow_mut() = Box::new(f); + } + + pub fn create(&self, dir: PathBuf) { + self.open(Target::New(dir), &DirMeta::default()); + } + + pub fn edit(&self, path: PathBuf) -> Result<(), String> { + let text = + fs::read_to_string(&path).map_err(|e| format!("Can't read the launcher: {e}"))?; + let meta = DirMeta::parse(&text); + if meta.get(ENTRY, "Type").is_some_and(|t| t != "Application") { + return Err("This file is a link, not an app launcher".into()); + } + self.open(Target::Edit(path), &meta); + Ok(()) + } + + fn open(&self, target: Target, meta: &DirMeta) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let get = |key: &str| unescape(meta.get(ENTRY, key).unwrap_or_default()); + let themed = ICONS + .iter() + .map(|n| ((*n).to_owned(), crate::file_icons::find(n))) + .collect(); + let (picks, cells) = icon_picker::theme_cells(GLYPH, themed); + let icon = get("Icon"); + let current = picks.iter().position(|p| match p { + Pick::Default => icon.is_empty(), + Pick::Theme(name) => *name == icon, + Pick::Glyph(_) => false, + }); + let browsed = match current { + None => icon_picker::browsed(&icon), + Some(_) => Default::default(), + }; + let unknown = current.is_none() && browsed.label.is_empty() && !icon.starts_with('/'); + *self.kept_icon.borrow_mut() = unknown.then(|| icon.clone()); + ui.set_launcher(LauncherData { + editing: matches!(target, Target::Edit(_)), + name: localized(meta, "Name").into(), + comment: localized(meta, "Comment").into(), + command: get("Exec").into(), + terminal: get("Terminal") == "true", + choice: match current { + Some(i) => i as i32, + None if !browsed.label.is_empty() => -1, + None => 0, + }, + image_path: if icon.starts_with('/') { + icon.into() + } else { + "".into() + }, + browsed, + error: "".into(), + }); + ui.set_launcher_icons(ModelRc::new(VecModel::from(cells))); + *self.picks.borrow_mut() = picks; + *self.target.borrow_mut() = Some(target); + ui.invoke_show_launcher(); + } + + fn save(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let mut data = ui.get_launcher(); + match self.write(&data) { + Ok(()) => ui.invoke_close_launcher(), + Err(message) => { + data.error = message.into(); + ui.set_launcher(data); + } + } + } + + fn write(&self, data: &LauncherData) -> Result<(), String> { + let target = self.target.borrow(); + let Some(target) = target.as_ref() else { + return Ok(()); + }; + let (name, command) = (data.name.trim(), data.command.trim()); + if name.is_empty() { + return Err("Give the launcher a name.".into()); + } + if command.is_empty() { + return Err("Enter the command it runs, or choose a program.".into()); + } + let image = data.image_path.trim(); + if !icon_picker::valid_image(image) { + return Err(icon_picker::NO_IMAGE.into()); + } + let icon = match icon_picker::picked(&self.picks, data.choice, &data.browsed) { + _ if !image.is_empty() => Some(image.to_owned()), + Pick::Theme(name) => Some(name), + Pick::Glyph(_) | Pick::Default => self.kept_icon.borrow().clone(), + }; + let apply = |meta: &mut DirMeta| { + meta.set(ENTRY, "Type", Some("Application")); + localize(meta, "Name", name); + localize(meta, "Comment", data.comment.trim()); + meta.set(ENTRY, "Exec", Some(&command.replace('\\', "\\\\"))); + meta.set(ENTRY, "Icon", icon.as_deref()); + let terminal = if data.terminal { "true" } else { "false" }; + meta.set(ENTRY, "Terminal", Some(terminal)); + }; + let failed = |e: io::Error| match e.kind() { + io::ErrorKind::PermissionDenied => "You don't have permission to write here.".into(), + _ => format!("Couldn't save the launcher: {e}"), + }; + match target { + Target::Edit(path) => { + let mut meta = DirMeta::parse(&fs::read_to_string(path).map_err(failed)?); + apply(&mut meta); + replace(path, &meta.to_string()).map_err(failed) + } + Target::New(dir) => { + let mut meta = DirMeta::default(); + apply(&mut meta); + // The name may hold what a file name can't. + let stem = name.replace('/', "-"); + let stem = stem.trim_start_matches('.'); + for n in 1.. { + let file = match n { + 1 => format!("{stem}.desktop"), + n => format!("{stem} {n}.desktop"), + }; + let path = dir.join(&file); + if path.symlink_metadata().is_ok() { + continue; + } + (self.made.borrow())(OsStr::new(&file)); + // Executable, so desktops trust it to start. + let mut out = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o755) + .open(&path) + .map_err(failed)?; + return out.write_all(meta.to_string().as_bytes()).map_err(failed); + } + Ok(()) + } + } + } +} + +/// Puts `text` in the file at `path` (the one a link leads to) in one step. +fn replace(path: &Path, text: &str) -> io::Result<()> { + let path = path.canonicalize()?; + let mode = path.metadata()?.permissions().mode(); + let mut temp = path.clone().into_os_string(); + temp.push(format!(".tunal-{}", std::process::id())); + let result = fs::write(&temp, text) + .and_then(|()| fs::set_permissions(&temp, fs::Permissions::from_mode(mode))) + .and_then(|()| fs::rename(&temp, &path)); + if result.is_err() { + let _ = fs::remove_file(&temp); + } + result +} + +/// The key this language shows for `key`: `Name[de]`, else `Name`. +fn shown_key(meta: &DirMeta, key: &str) -> String { + locale_suffixes() + .iter() + .map(|l| format!("{key}[{l}]")) + .find(|k| meta.get(ENTRY, k).is_some()) + .unwrap_or_else(|| key.to_owned()) +} + +fn localized(meta: &DirMeta, key: &str) -> String { + unescape(meta.get(ENTRY, &shown_key(meta, key)).unwrap_or_default()) +} + +/// Sets what this language shows for `key`; other languages keep theirs. +fn localize(meta: &mut DirMeta, key: &str, value: &str) { + let shown = shown_key(meta, key); + // Removing a translation would bring the plain text back: that goes too. + if value.is_empty() { + meta.set(ENTRY, &shown, None); + meta.set(ENTRY, key, None); + } else { + meta.set(ENTRY, &shown, Some(&value.replace('\\', "\\\\"))); + } +} diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs index 6b1914f..5ef5750 100644 --- a/crates/tunal/src/main.rs +++ b/crates/tunal/src/main.rs @@ -5,11 +5,13 @@ mod desktop_apps; mod devices_bridge; mod dnd; mod file_icons; +mod file_picker; mod folder; mod icon_picker; mod icons; mod jobs_bridge; mod keymap; +mod launcher; mod menus; mod native; mod net_bridge; @@ -129,6 +131,8 @@ fn window( let mtp = devices_bridge::register(&mut locations); let net = net_bridge::register(&mut locations, &ui); let shell = shell::Shell::attach(&ui, locations, tabs, blocking); + file_picker::attach(&ui, &shell); + icon_picker::attach(&ui); devices_bridge::attach(&shell, mtp); net_bridge::attach(&ui, &shell, net); // `TUNAL_SETTINGS=` opens the settings dialog (screenshots); on the Shortcuts diff --git a/crates/tunal/src/menus.rs b/crates/tunal/src/menus.rs index 4799ce9..3fac4ba 100644 --- a/crates/tunal/src/menus.rs +++ b/crates/tunal/src/menus.rs @@ -49,6 +49,7 @@ impl Context { "run-in-terminal", "open-with", "edit-tags", + "edit-launcher", "-", "cut", "copy", diff --git a/crates/tunal/src/player_bridge.rs b/crates/tunal/src/player_bridge.rs index 701cb38..cb63758 100644 --- a/crates/tunal/src/player_bridge.rs +++ b/crates/tunal/src/player_bridge.rs @@ -397,7 +397,12 @@ impl PlayerUi { let Some(track) = track.as_mut() else { return; }; - let to = to.min(track.duration); + // A length not known yet is no limit. + let to = if track.duration.is_zero() { + to + } else { + to.min(track.duration) + }; track.position = to; to }; diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs index e85ad70..a7b8ab4 100644 --- a/crates/tunal/src/shell/mod.rs +++ b/crates/tunal/src/shell/mod.rs @@ -81,6 +81,8 @@ pub struct Shell { pane_rows: Rc>, places: RefCell, menu_target: Cell>, + /// The sidebar entry last opened. + opened_place: Cell>, /// Bumped per completion request; older results are dropped. completion: Arc, /// The file actions; set once the shell exists. @@ -129,6 +131,7 @@ impl Shell { pane_rows: Rc::new(VecModel::default()), places: RefCell::new(Places::load()), menu_target: Cell::new(None), + opened_place: Cell::new(None), completion: Arc::new(AtomicU64::new(0)), actions: OnceCell::new(), settings: OnceCell::new(), @@ -263,8 +266,7 @@ impl Shell { /// A new tab at the active pane's folder. fn new_tab(&self) { - let dir = self.active().and_then(|p| p.dir()); - self.open_tab(vec![dir.unwrap_or_else(|| Uri::from_path(&places::home()))]); + self.open_tab(vec![Uri::from_path(&places::home())]); self.show_current(); } @@ -643,13 +645,28 @@ impl Shell { fn show_sidebar(&self, ui: &MainWindow, dir: Option<&Uri>) { let places = self.places.borrow(); + let current = self.current_place(&places, dir); + // A folded section has no rows; an empty one has its text. + let rows = |s: Section| match places.items(s).len() { + _ if places.collapsed(s) => 0, + n => n.max(1), + }; + let shown = current.filter(|(s, _)| !places.collapsed(*s)); + ui.set_has_current_place(shown.is_some()); + if let Some((section, index)) = shown { + let before = Section::ALL.into_iter().take_while(|s| *s != section); + ui.set_current_place_section(before.clone().count() as i32); + ui.set_current_place_rows_before(before.map(rows).sum::() as i32); + ui.set_current_place_row(index as i32); + } let sections: Vec = Section::ALL .into_iter() .map(|section| { let items: Vec = places .items(section) .iter() - .map(|p| { + .enumerate() + .map(|(i, p)| { let (name, tip) = path::shown_name(&p.uri, p.name.clone()); let picture = p.picture.as_deref().and_then(look::picture); PlaceItem { @@ -658,7 +675,7 @@ impl Shell { glyph: p.shown_glyph().into(), has_picture: picture.is_some(), picture: picture.unwrap_or_default(), - current: Some(&p.uri) == dir, + current: current == Some((section, i)), } }) .collect(); @@ -685,6 +702,18 @@ impl Shell { } } + /// The sidebar entry for `dir`: the one last opened when several are it. + fn current_place(&self, places: &Places, dir: Option<&Uri>) -> Option<(Section, usize)> { + let dir = dir?; + let is = |(s, i): &(Section, usize)| places.get(*s, *i).is_some_and(|p| p.uri == *dir); + self.opened_place.get().filter(is).or_else(|| { + Section::ALL + .into_iter() + .flat_map(|s| (0..places.items(s).len()).map(move |i| (s, i))) + .find(is) + }) + } + pub(crate) fn focus_active(&self) { if let Some(ui) = self.ui.upgrade() { ui.set_focus_request(ui.get_focus_request().wrapping_add(1)); @@ -707,6 +736,7 @@ impl Shell { // ---- places ------------------------------------------------------------------------- fn open_place(&self, section: Section, index: usize, new_tab: bool) { + self.opened_place.set(Some((section, index))); if section == Section::Network { crate::net_bridge::open(self, index, new_tab); return; @@ -897,13 +927,33 @@ impl Shell { fn path_accepted(&self, text: &str) { self.complete(String::new()); let current = self.active().and_then(|p| p.dir()); - if let Some(uri) = path::parse(text, current.as_ref()) { - self.go(uri); - } else { + let Some(uri) = path::parse(text, current.as_ref()) else { self.focus_active(); + return; + }; + // A file's path: its folder, with the file selected. + let file = uri.to_path().is_some_and(|p| p.is_file()); + match (uri.parent(), uri.file_name().map(<[u8]>::to_vec)) { + (Some(dir), Some(name)) if file => { + self.with_active(|p| { + if current.as_ref() == Some(&dir) { + p.model.refresh(); + } else { + p.go(dir); + } + p.model.select_when_shown(name, false); + }); + self.focus_active(); + } + _ => self.go(uri), } } + /// The folder the active pane shows. + pub(crate) fn active_dir(&self) -> Option { + self.active()?.dir() + } + fn go_crumb(&self, index: usize) { if let Some(uri) = self.crumb_uri(index) { self.go(uri); diff --git a/crates/tunal/src/shell/path.rs b/crates/tunal/src/shell/path.rs index 10b9c5f..6936185 100644 --- a/crates/tunal/src/shell/path.rs +++ b/crates/tunal/src/shell/path.rs @@ -91,6 +91,11 @@ pub fn text(uri: &Uri) -> String { /// `current`. `.` and `..` are resolved here. pub fn parse(text: &str, current: Option<&Uri>) -> Option { let text = text.trim(); + // A path copied with quotes round it. + let text = ['\'', '"'] + .into_iter() + .find_map(|q| text.strip_prefix(q)?.strip_suffix(q)) + .unwrap_or(text); if text.is_empty() { return None; } diff --git a/crates/tunal/src/shell/place_icon.rs b/crates/tunal/src/shell/place_icon.rs index 30cd169..86909a4 100644 --- a/crates/tunal/src/shell/place_icon.rs +++ b/crates/tunal/src/shell/place_icon.rs @@ -41,13 +41,14 @@ impl Shell { 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 pick = PICKS.with(|p| { + icon_picker::picked(p, ui.get_place_icon_choice(), &ui.get_place_icon_browsed()) + }); 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, + Pick::Glyph(g) => Some(g.to_string()), + Pick::Theme(name) => Some(name), + Pick::Default => None, }; ui.invoke_close_place_icon(); self.menu_target.set(None); @@ -69,10 +70,26 @@ fn fill(ui: &MainWindow, place: &Place, themed: Vec<(String, Option 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 { + if late { + // One of them may be what the browser's cell shows until now. + if let Some(i) = current.filter(|_| { + ui.get_place_icon_choice() == -1 && ui.get_place_icon_browsed().label == icon + }) { + ui.set_place_icon_choice(i as i32); + ui.set_place_icon_browsed(Default::default()); + } + } else { + let browsed = match current { + None => icon_picker::browsed(icon), + Some(_) => Default::default(), + }; + let outside = !browsed.label.is_empty(); + ui.set_place_icon_browsed(browsed); + ui.set_place_icon_choice(if outside { + -1 + } else { + current.unwrap_or(0) as i32 + }); ui.set_place_icon_image(if icon.starts_with('/') { icon } else { "" }.into()); } ui.set_place_icons(ModelRc::new(VecModel::from(cells))); diff --git a/crates/tunal/src/shell/places.rs b/crates/tunal/src/shell/places.rs index 70d2f86..f7e3663 100644 --- a/crates/tunal/src/shell/places.rs +++ b/crates/tunal/src/shell/places.rs @@ -98,7 +98,7 @@ impl Place { self.picture = icon .as_deref() .filter(|i| glyph_of(i).is_none()) - .and_then(|i| file_icons::places_theme().find(i, 64)); + .and_then(file_icons::find); self.icon = icon; } diff --git a/crates/tunal/src/tools.rs b/crates/tunal/src/tools.rs index 643b135..852a016 100644 --- a/crates/tunal/src/tools.rs +++ b/crates/tunal/src/tools.rs @@ -231,35 +231,93 @@ pub fn run_in_terminal(path: &Path) -> Result<(), String> { // ---- archives ------------------------------------------------------------------------------- -/// Archive formats Tunal makes. +/// Archive formats Tunal makes: everything 7z writes, and compressed tar archives. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Format { - TarGz, Zip, + SevenZ, + Tar, + TarGz, + TarBz2, + TarXz, + TarZst, + Wim, + Gz, + Bz2, + Xz, } impl Format { - pub const ALL: [Format; 2] = [Self::TarGz, Self::Zip]; + pub const ALL: [Format; 11] = [ + Self::Zip, + Self::SevenZ, + Self::Tar, + Self::TarGz, + Self::TarBz2, + Self::TarXz, + Self::TarZst, + Self::Wim, + Self::Gz, + Self::Bz2, + Self::Xz, + ]; pub fn label(self) -> &'static str { match self { - Self::TarGz => "Tar archive (.tar.gz)", Self::Zip => "Zip archive (.zip)", + Self::SevenZ => "7z archive (.7z)", + Self::Tar => "Tar archive, not compressed (.tar)", + Self::TarGz => "Tar archive (.tar.gz)", + Self::TarBz2 => "Tar archive (.tar.bz2)", + Self::TarXz => "Tar archive (.tar.xz)", + Self::TarZst => "Tar archive (.tar.zst)", + Self::Wim => "Windows image (.wim)", + Self::Gz => "One file, gzip (.gz)", + Self::Bz2 => "One file, bzip2 (.bz2)", + Self::Xz => "One file, xz (.xz)", } } pub fn ext(self) -> &'static str { match self { - Self::TarGz => ".tar.gz", Self::Zip => ".zip", + Self::SevenZ => ".7z", + Self::Tar => ".tar", + Self::TarGz => ".tar.gz", + Self::TarBz2 => ".tar.bz2", + Self::TarXz => ".tar.xz", + Self::TarZst => ".tar.zst", + Self::Wim => ".wim", + Self::Gz => ".gz", + Self::Bz2 => ".bz2", + Self::Xz => ".xz", } } + + /// Packs a single file, no folders. + pub fn single(self) -> bool { + matches!(self, Self::Gz | Self::Bz2 | Self::Xz) + } + + /// The name 7z has for the format, if it makes it in one step. + fn seven_type(self) -> Option<&'static str> { + Some(match self { + Self::Zip => "zip", + Self::SevenZ => "7z", + Self::Tar => "tar", + Self::Wim => "wim", + Self::Gz => "gzip", + Self::Bz2 => "bzip2", + Self::Xz => "xz", + Self::TarGz | Self::TarBz2 | Self::TarXz | Self::TarZst => return None, + }) + } } fn tool(name: &'static str) -> Option<&'static Path> { static TOOLS: OnceLock)>> = OnceLock::new(); let tools = TOOLS.get_or_init(|| { - ["tar", "bsdtar", "zip", "unzip"] + ["tar", "bsdtar", "zip", "unzip", "7z", "7zz", "7za"] .into_iter() .map(|n| (n, find_program(n))) .collect() @@ -270,6 +328,11 @@ fn tool(name: &'static str) -> Option<&'static Path> { .and_then(|(_, p)| p.as_deref()) } +/// 7-Zip, under the names it is installed as. +fn seven() -> Option<&'static Path> { + ["7z", "7zz", "7za"].into_iter().find_map(tool) +} + pub fn can_compress(format: Format) -> bool { compress_command(format, Path::new("/"), &[], Path::new("/")).is_some() } @@ -283,20 +346,29 @@ pub fn compress_command( ) -> Option { // `./name` keeps a name that starts with `-` from reading as an option. let items = names.iter().map(|n| Path::new(".").join(n)); - let mut cmd = match format { - Format::TarGz => { - let mut cmd = Command::new(tool("tar").or(tool("bsdtar"))?); - cmd.arg("-czf").arg(dest); - cmd - } - Format::Zip if tool("zip").is_some() => { - let mut cmd = Command::new(tool("zip")?); + let mut cmd = match (format, tool("zip"), seven()) { + (Format::Zip, Some(zip), _) => { + let mut cmd = Command::new(zip); cmd.args(["-r", "-q", "-y"]).arg(dest); cmd } - Format::Zip => { - let mut cmd = Command::new(tool("bsdtar")?); - cmd.args(["--format", "zip", "-cf"]).arg(dest); + // Symbolic links as links, names as they are (no wildcards). + (_, _, Some(seven)) if let Some(kind) = format.seven_type() => { + let mut cmd = Command::new(seven); + cmd.arg("a").arg(format!("-t{kind}")); + if !format.single() { + cmd.arg("-snl"); + } + cmd.args(["-spd", "-y", "-bso0", "-bsp0"]).arg(dest); + cmd + } + _ if format.single() || matches!(format, Format::SevenZ | Format::Wim) => return None, + // The ending of `dest` names the format. + _ => { + let bsdtar = tool("bsdtar"); + let gnu = tool("tar").filter(|_| format != Format::Zip); + let mut cmd = Command::new(bsdtar.or(gnu)?); + cmd.arg("-acf").arg(dest); cmd } }; @@ -304,23 +376,97 @@ pub fn compress_command( Some(cmd) } -/// Archive name endings and whether only `bsdtar` reads them. -const ARCHIVES: [(&str, bool); 13] = [ - (".tar", false), - (".tar.gz", false), - (".tgz", false), - (".tar.bz2", false), - (".tbz2", false), - (".tar.xz", false), - (".txz", false), - (".tar.zst", false), - (".zip", false), - (".7z", true), - (".rar", true), - (".iso", true), - (".cpio", true), +/// What unpacks an archive, best first. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Reader { + /// `bsdtar`, else `tar`. + Tar, + /// `bsdtar`, else `7z`, else `unzip`. + Zip, + /// `7z`, else `bsdtar`. + Seven, + /// `7z` alone. + OnlySeven, + /// `bsdtar` alone. + OnlyBsd, +} + +/// Archive name endings; the longest that fits counts. +const ARCHIVES: [(&str, Reader); 64] = [ + (".tar", Reader::Tar), + (".tar.gz", Reader::Tar), + (".tgz", Reader::Tar), + (".tar.bz2", Reader::Tar), + (".tbz2", Reader::Tar), + (".tbz", Reader::Tar), + (".tar.xz", Reader::Tar), + (".txz", Reader::Tar), + (".tar.zst", Reader::Tar), + (".tzst", Reader::Tar), + (".tar.lzma", Reader::Tar), + (".tlz", Reader::Tar), + (".tar.lz4", Reader::OnlyBsd), + (".tar.lz", Reader::Tar), + (".tar.z", Reader::Tar), + (".taz", Reader::Tar), + (".zip", Reader::Zip), + (".zipx", Reader::Seven), + (".jar", Reader::Zip), + (".war", Reader::Zip), + (".apk", Reader::Zip), + (".ipa", Reader::Zip), + (".xpi", Reader::Zip), + (".appx", Reader::Zip), + (".cbz", Reader::Zip), + (".7z", Reader::Seven), + (".cb7", Reader::Seven), + (".rar", Reader::Seven), + (".cbr", Reader::Seven), + (".iso", Reader::Seven), + (".cpio", Reader::Seven), + (".cab", Reader::Seven), + (".lzh", Reader::Seven), + (".lha", Reader::Seven), + (".xar", Reader::Seven), + (".pkg", Reader::Seven), + (".rpm", Reader::Seven), + (".deb", Reader::Seven), + (".ar", Reader::Seven), + (".arj", Reader::OnlySeven), + (".wim", Reader::OnlySeven), + (".swm", Reader::OnlySeven), + (".esd", Reader::OnlySeven), + (".msi", Reader::OnlySeven), + (".chm", Reader::OnlySeven), + (".dmg", Reader::OnlySeven), + (".img", Reader::OnlySeven), + (".udf", Reader::OnlySeven), + (".squashfs", Reader::OnlySeven), + (".vhd", Reader::OnlySeven), + (".vhdx", Reader::OnlySeven), + (".vmdk", Reader::OnlySeven), + (".vdi", Reader::OnlySeven), + (".qcow2", Reader::OnlySeven), + (".7z.001", Reader::OnlySeven), + (".zip.001", Reader::OnlySeven), + (".rar.001", Reader::OnlySeven), + (".gz", Reader::OnlySeven), + (".bz2", Reader::OnlySeven), + (".xz", Reader::OnlySeven), + (".zst", Reader::OnlySeven), + (".lzma", Reader::OnlySeven), + (".z", Reader::OnlySeven), + (".pmd", Reader::OnlySeven), ]; +/// The ending of the lower-case archive name `name`, and what reads it. +fn archive_kind(name: &str) -> Option<(&'static str, Reader)> { + ARCHIVES + .into_iter() + .filter(|(ext, _)| name.ends_with(ext)) + .max_by_key(|(ext, _)| ext.len()) +} + /// True when `name` is an archive a tool here can unpack. pub fn can_extract(name: &[u8]) -> bool { extract_command(Path::new(OsStr::from_bytes(name)), Path::new("/")).is_some() @@ -329,29 +475,39 @@ pub fn can_extract(name: &[u8]) -> bool { /// The command that unpacks `archive` into `dest`, never overwriting what is there. pub fn extract_command(archive: &Path, dest: &Path) -> Option { let name = archive.file_name()?.to_string_lossy().to_lowercase(); - let (_, bsd_only) = ARCHIVES.iter().find(|(ext, _)| name.ends_with(ext))?; - let zip = name.ends_with(".zip"); - let mut cmd = if let Some(bsdtar) = tool("bsdtar") { - let mut cmd = Command::new(bsdtar); - cmd.args(["-x", "-k", "-f"]) - .arg(archive) - .arg("-C") - .arg(dest); - cmd - } else if *bsd_only { - return None; - } else if zip { - let mut cmd = Command::new(tool("unzip")?); - cmd.args(["-q", "-n"]).arg(archive).arg("-d").arg(dest); - cmd - } else { - let mut cmd = Command::new(tool("tar")?); + let (_, reader) = archive_kind(&name)?; + let tar = |program: &Path| { + let mut cmd = Command::new(program); cmd.args(["-x", "-k", "-f"]) .arg(archive) .arg("-C") .arg(dest); cmd }; + let seven = || { + let mut out = std::ffi::OsString::from("-o"); + out.push(dest); + let mut cmd = Command::new(seven()?); + // An empty password: an encrypted archive fails instead of asking on a terminal. + cmd.args(["x", "-y", "-aos", "-p", "-spd", "-bso0", "-bsp0"]) + .arg(out) + .arg("--") + .arg(archive); + Some(cmd) + }; + let unzip = || { + let mut cmd = Command::new(tool("unzip")?); + cmd.args(["-q", "-n"]).arg(archive).arg("-d").arg(dest); + Some(cmd) + }; + let bsd = || tool("bsdtar").map(tar); + let mut cmd = match reader { + Reader::Tar => bsd().or_else(|| tool("tar").map(tar)), + Reader::Zip => bsd().or_else(seven).or_else(unzip), + Reader::Seven => seven().or_else(bsd), + Reader::OnlySeven => seven(), + Reader::OnlyBsd => bsd(), + }?; cmd.current_dir(dest); Some(cmd) } @@ -363,11 +519,8 @@ pub fn archive_stem(archive: &Path) -> String { .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let lower = name.to_lowercase(); - ARCHIVES - .iter() - .filter(|(ext, _)| lower.ends_with(ext)) + archive_kind(&lower) .map(|(ext, _)| ext.len()) - .max() .filter(|&n| n < name.len()) .map_or(name.clone(), |n| name[..name.len() - n].to_string()) } @@ -406,7 +559,13 @@ pub fn run_to_end(mut cmd: Command, cancel: &AtomicBool) -> Result<(), String> { if status.success() { Ok(()) } else { - let last = output.lines().rev().find(|l| !l.trim().is_empty()); + // 7z's last line only counts errors; the ones that start with ERROR say what they are. + let mut lines = output.lines().rev().filter(|l| !l.trim().is_empty()); + let last = lines.clone().find(|l| l.starts_with("ERROR")); + let last = last.or_else(|| lines.next()); + if output.contains("Wrong password") { + return Err("This archive needs a password, which Tunal can't enter yet".into()); + } Err(last.unwrap_or("The archive tool failed").trim().to_string()) } } diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint index 2928bcf..04056c6 100644 --- a/crates/tunal/ui/app.slint +++ b/crates/tunal/ui/app.slint @@ -25,8 +25,9 @@ import { ErrorsDialog } from "dialogs/errors.slint"; import { PropertiesDialog, PropertiesInfo, PropRow } from "dialogs/properties.slint"; import { OpenWithDialog, AppRow } from "dialogs/open-with.slint"; import { FolderAppearanceDialog } from "dialogs/folder-appearance.slint"; +import { LauncherDialog, LauncherData } from "dialogs/launcher.slint"; import { PlaceIconDialog } from "dialogs/place-icon.slint"; -import { IconChoice } from "components/icon-picker.slint"; +import { IconChoice, IconBrowser, IconRow } 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"; @@ -36,6 +37,8 @@ import { SecretPromptDialog, SecretPromptData } from "dialogs/secret-prompt.slin import { Dnd, DropAction, DropMenu, DropTarget } from "components/drop-menu.slint"; export { Theme, Shapes, ShapeKind, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode, GridRow } +export { IconBrowser, IconRow, LauncherData } +export { FileKind, FilePicks } from "components/text-field.slint"; export { ColorPicks, Swatch } from "dialogs/appearance-page.slint"; export { ButtonKind, TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem, ToastData, ToastProgress, DialogAction, ConflictInfo, SettingsData, EditRow } export { PlayerData, FolderActions, ViewKeys, KeyRow, ConnectionData, HostKeyData, SecretPromptData } @@ -159,6 +162,7 @@ export component MainWindow inherits Window { in-out property appearance-choice; in-out property appearance-name; in-out property appearance-image; + in-out property appearance-browsed; in-out property appearance-remember; in property appearance-placeholder; in property appearance-error; @@ -244,16 +248,25 @@ export component MainWindow inherits Window { } in property <[MenuItem]> place-menu; callback toggle-sidebar(); + in property has-current-place; + in property current-place-section; + in property current-place-row; + in property current-place-rows-before; callback place-opened(int, int, bool); callback section-toggled(int); callback add-bookmark(); callback place-menu-requested(int, int); callback place-menu-activated(int, int); callback place-renamed(string); + // The launcher maker and editor (launcher.rs). + in-out property launcher; + in property <[IconChoice]> launcher-icons; + callback launcher-saved(); // 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-out property place-icon-browsed; in property place-icon-error; callback place-icon-saved(); @@ -297,6 +310,14 @@ export component MainWindow inherits Window { place-popup.open-at(x, y); } + public function show-launcher() { + launcher-dialog.show(); + } + + public function close-launcher() { + launcher-dialog.close(); + } + public function show-place-icon() { place-icon-dialog.show(); } @@ -432,6 +453,10 @@ export component MainWindow inherits Window { width: root.show-sidebar ? 240px : 0; visible: self.width > 0; sections: root.sections; + has-current: root.has-current-place; + current-section: root.current-place-section; + current-row: root.current-place-row; + rows-before: root.current-place-rows-before; animate width { duration: Motion.time(Motion.medium2); easing: Motion.emphasized; } open(section, index, new-tab) => { root.place-opened(section, index, new-tab); @@ -876,6 +901,7 @@ export component MainWindow inherits Window { choice <=> root.appearance-choice; name-text <=> root.appearance-name; image-path <=> root.appearance-image; + browsed <=> root.appearance-browsed; remember <=> root.appearance-remember; placeholder: root.appearance-placeholder; error: root.appearance-error; @@ -885,12 +911,23 @@ export component MainWindow inherits Window { } } + launcher-dialog := LauncherDialog { + width: 100%; + height: 100%; + data <=> root.launcher; + icons: root.launcher-icons; + saved => { + root.launcher-saved(); + } + } + place-icon-dialog := PlaceIconDialog { width: 100%; height: 100%; icons: root.place-icons; choice <=> root.place-icon-choice; image-path <=> root.place-icon-image; + browsed <=> root.place-icon-browsed; error: root.place-icon-error; saved => { root.place-icon-saved(); diff --git a/crates/tunal/ui/components/dialog.slint b/crates/tunal/ui/components/dialog.slint index c1ecc0f..866a781 100644 --- a/crates/tunal/ui/components/dialog.slint +++ b/crates/tunal/ui/components/dialog.slint @@ -39,6 +39,11 @@ export component Dialog inherits Overlay { public function show() { root.open = true; + root.take-focus(); + root.settling = true; + } + + function take-focus() { if root.content-focus { root.focus-content(); } else { @@ -46,6 +51,20 @@ export component Dialog inherits Overlay { } } + // A menu that opened this dialog gives focus back to the view one turn of the event loop + // later; take it again after that. + property settling; + settle := Timer { + interval: 1ms; + running: root.settling; + triggered => { + root.settling = false; + if root.open { + root.take-focus(); + } + } + } + public function close() { root.open = false; trap.clear-focus(); diff --git a/crates/tunal/ui/components/icon-picker.slint b/crates/tunal/ui/components/icon-picker.slint index b964f92..f07714f 100644 --- a/crates/tunal/ui/components/icon-picker.slint +++ b/crates/tunal/ui/components/icon-picker.slint @@ -1,7 +1,11 @@ +import { ListView } from "std-widgets.slint"; import { Theme } from "../theme.slint"; import { Motion } from "../motion.slint"; +import { Icons } from "icon.slint"; +import { Chip } from "chip.slint"; +import { IconButton } from "icon-button.slint"; import { StateLayer } from "state-layer.slint"; -import { TextField } from "text-field.slint"; +import { FileKind, 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 @@ -51,30 +55,77 @@ component Cell inherits StateLayer { } } -// Cells to choose an icon from, and a field for an image file that takes their place. +// A line of the icon browser. +export struct IconRow { + cells: [IconChoice], +} + +// The icon theme's icons, served by Rust (icon_picker.rs): `search` fills `rows`. +export global IconBrowser { + in property <[IconRow]> rows; + // Icons that match, or -1 while the theme is read. + in property found: -1; + // Category 0 is all of them. + callback search(text: string, category: int, columns: int); +} + +// Cells to choose an icon from, and a field for an image file that takes their place. The +// last cell, a plus, opens a browser over the whole icon theme; what is chosen there shows +// before it (`browsed`, its label is the icon's name) and is `choice` -1. export component IconPicker inherits VerticalLayout { in property <[IconChoice]> icons; in-out property choice; in-out property image-path; + in-out property browsed; callback accepted(); + // The browser shows; the owner turns it off when its dialog closes. + in-out property browsing; + property columns: 9; + property has-browsed: root.browsed.label != ""; + property cells: root.icons.length + (root.has-browsed ? 2 : 1); + property search; + property category; + function refresh() { + // One column less than the short list: room for the scrollbar. + IconBrowser.search(root.search, root.category, root.columns - 1); + } + property cell-width: 46px; + property cell-height: 44px; + spacing: Theme.space-4; - Text { - text: "Icon"; - color: Theme.on-surface-variant; - font-size: Theme.label-medium.size; - font-weight: Theme.label-medium.weight; + HorizontalLayout { + Text { + horizontal-stretch: 1; + text: !root.browsing ? "Icon" + : IconBrowser.found < 0 ? "Reading the icon theme…" + : IconBrowser.found == 1 ? "1 icon" + : IconBrowser.found + " icons"; + color: Theme.on-surface-variant; + font-size: Theme.label-medium.size; + font-weight: Theme.label-medium.weight; + vertical-alignment: center; + } + + if root.browsing: IconButton { + icon: Icons.close; + size: 32px; + icon-size: 20px; + tooltip: "Back to the short list"; + clicked => { + root.browsing = false; + } + } } // Wraps in rows of cells; the height follows the number of choices. - property columns: 9; - Rectangle { - height: ceil(root.icons.length / root.columns) * 44px; + if !root.browsing: Rectangle { + height: ceil(root.cells / root.columns) * root.cell-height; for item[i] in root.icons: Cell { - x: mod(i, root.columns) * 46px; - y: floor(i / root.columns) * 44px; + x: mod(i, root.columns) * root.cell-width; + y: floor(i / root.columns) * root.cell-height; choice: item; selected: i == root.choice && root.image-path == ""; clicked => { @@ -82,11 +133,94 @@ export component IconPicker inherits VerticalLayout { root.image-path = ""; } } + + if root.has-browsed: Cell { + x: mod(root.icons.length, root.columns) * root.cell-width; + y: floor(root.icons.length / root.columns) * root.cell-height; + choice: root.browsed; + selected: root.choice == -1 && root.image-path == ""; + clicked => { + root.choice = -1; + root.image-path = ""; + } + } + + IconButton { + x: mod(root.cells - 1, root.columns) * root.cell-width + (root.cell-height - self.width) / 2; + y: floor((root.cells - 1) / root.columns) * root.cell-height + (root.cell-height - self.height) / 2; + icon: Icons.add; + size: 36px; + tonal: true; + tooltip: "More icons…"; + clicked => { + root.search = ""; + root.category = 0; + root.browsing = true; + root.refresh(); + } + } } - TextField { + if root.browsing: VerticalLayout { + find := TextField { + label: "Search icons"; + placeholder: "folder, steam, music…"; + init => { + self.focus-input(); + } + edited(text) => { + root.search = text; + root.refresh(); + } + } + + for names[r] in [["All", "Folders", "Apps"], ["File types", "Devices", "Symbols"]]: HorizontalLayout { + spacing: Theme.space-2; + padding-bottom: Theme.space-2; + alignment: start; + + for name[i] in names: Chip { + property sel: r * 3 + i == root.category; + + text: name; + checked: self.sel; + changed sel => { + self.checked = self.sel; + } + clicked => { + root.category = r * 3 + i; + self.checked = true; + root.refresh(); + } + } + } + + ListView { + height: 4 * root.cell-height; + + for row in IconBrowser.rows: HorizontalLayout { + height: root.cell-height; + spacing: root.cell-width - root.cell-height; + alignment: start; + + for item in row.cells: Cell { + choice: item; + selected: root.choice == -1 && item.label == root.browsed.label; + clicked => { + root.browsed = item; + root.choice = -1; + root.image-path = ""; + root.browsing = false; + } + } + } + } + } + + if !root.browsing: TextField { label: "Or an image file"; placeholder: "/path/to/picture.png"; + picks: FileKind.image; text <=> root.image-path; accepted => { root.accepted(); diff --git a/crates/tunal/ui/components/icon.slint b/crates/tunal/ui/components/icon.slint index 30a5f6c..a996320 100644 --- a/crates/tunal/ui/components/icon.slint +++ b/crates/tunal/ui/components/icon.slint @@ -72,6 +72,7 @@ export global Icons { out property refresh: "\u{e5d5}"; // File categories (icons.rs). out property image: "\u{e3f4}"; + out property folder-open: "\u{e2c8}"; out property audio: "\u{eb82}"; out property video: "\u{eb87}"; out property code: "\u{e86f}"; diff --git a/crates/tunal/ui/components/list-row.slint b/crates/tunal/ui/components/list-row.slint index b9d6d01..a9d7f45 100644 --- a/crates/tunal/ui/components/list-row.slint +++ b/crates/tunal/ui/components/list-row.slint @@ -16,6 +16,8 @@ export component ListRow inherits StateLayer { in property title; in property supporting; in property selected; + // Off: the owner draws the selection fill behind the row (one that travels). + in property own-fill: true; // Draws the icon in a shaped tonal container that morphs to `active-shape` when selected. in property shaped; // An image drawn in the shaped container in place of the glyph. @@ -60,7 +62,7 @@ export component ListRow inherits StateLayer { Rectangle { border-radius: root.border-radius; background: root.enabled ? Theme.secondary-container : Theme.on-surface.with-alpha(Theme.disabled-container); - opacity: root.selected ? 1 : 0; + opacity: root.selected && root.own-fill ? 1 : 0; transform-scale-x: root.selected ? 1 : Motion.squeeze; animate opacity, transform-scale-x { duration: Motion.time(Motion.short4); diff --git a/crates/tunal/ui/components/text-field.slint b/crates/tunal/ui/components/text-field.slint index 72b5486..15bba91 100644 --- a/crates/tunal/ui/components/text-field.slint +++ b/crates/tunal/ui/components/text-field.slint @@ -4,9 +4,24 @@ import { Icons } from "icon.slint"; import { IconButton } from "icon-button.slint"; import { ForceState } from "state-layer.slint"; +// What a field's file picker offers. +export enum FileKind { none, image, cover, key, program } + +// The desktop's file picker, served by Rust (file_picker.rs). +export global FilePicks { + // The last request; its answer sets `path`, then `done` to the same number. + in-out property request; + in-out property path; + in-out property done; + callback pick(request: int, kind: FileKind, current: string); + // The desktop has no file picker. + callback failed(); +} + // A single-line text field: label above, outlined frame, clear button while there is text, // and a message line below (supporting text, or the error in its place). The message line -// is always reserved so an error never pushes the content under the field. +// is always reserved so an error never pushes the content under the field. With `picks`, a +// button opens the file picker for it. export component TextField { in property label; in property placeholder; @@ -15,6 +30,7 @@ export component TextField { in property enabled: true; // Dots instead of the characters (passwords, passphrases). in property secret; + in property picks: FileKind.none; in property force-state: ForceState.none; in-out property text; public function focus-input() { @@ -23,6 +39,19 @@ export component TextField { callback edited(text: string); callback accepted(text: string); + // A file was chosen; `text` has its path. + callback picked(text: string); + + property request: -1; + property done: FilePicks.done; + changed done => { + if root.done == root.request { + root.request = -1; + root.text = FilePicks.path; + root.edited(root.text); + root.picked(root.text); + } + } out property focused: enabled && (input.has-focus || force-state == ForceState.focused); property hovered: enabled && (touch.has-hover || force-state == ForceState.hover); @@ -119,6 +148,22 @@ export component TextField { } } } + + if root.picks != FileKind.none && root.enabled: VerticalLayout { + alignment: center; + + IconButton { + icon: Icons.folder-open; + size: 32px; + icon-size: 20px; + tooltip: "Choose a file…"; + clicked => { + FilePicks.request += 1; + root.request = FilePicks.request; + FilePicks.pick(root.request, root.picks, root.text); + } + } + } } } diff --git a/crates/tunal/ui/dialogs/connection.slint b/crates/tunal/ui/dialogs/connection.slint index ab50f87..f1d6f78 100644 --- a/crates/tunal/ui/dialogs/connection.slint +++ b/crates/tunal/ui/dialogs/connection.slint @@ -2,7 +2,7 @@ import { Theme } from "../theme.slint"; import { Icons } from "../components/icon.slint"; import { Dialog } from "../components/dialog.slint"; import { ButtonKind } from "../components/button.slint"; -import { TextField } from "../components/text-field.slint"; +import { FileKind, TextField } from "../components/text-field.slint"; import { Chip } from "../components/chip.slint"; // A saved SFTP connection as the dialog edits it. The password is never part of it. @@ -135,6 +135,7 @@ export component ConnectionDialog inherits Dialog { if root.data.auth == 1: TextField { label: "Key file"; placeholder: "~/.ssh/id_ed25519"; + picks: FileKind.key; supporting: "The passphrase is asked when needed and never saved."; text <=> root.data.key-file; } diff --git a/crates/tunal/ui/dialogs/folder-appearance.slint b/crates/tunal/ui/dialogs/folder-appearance.slint index 1aba18c..eef13f7 100644 --- a/crates/tunal/ui/dialogs/folder-appearance.slint +++ b/crates/tunal/ui/dialogs/folder-appearance.slint @@ -15,6 +15,7 @@ export component FolderAppearanceDialog inherits Dialog { in-out property choice; in-out property name-text; in-out property image-path; + in-out property browsed; in-out property remember; in property placeholder; in property error; @@ -34,6 +35,7 @@ export component FolderAppearanceDialog inherits Dialog { name-field.focus-input(); } action(i) => { + picker.browsing = false; if i == 1 { root.saved(root.can-elevate); } else { @@ -50,10 +52,11 @@ export component FolderAppearanceDialog inherits Dialog { } } - IconPicker { + picker := IconPicker { icons: root.icons; choice <=> root.choice; image-path <=> root.image-path; + browsed <=> root.browsed; accepted => { root.saved(root.can-elevate); } diff --git a/crates/tunal/ui/dialogs/launcher.slint b/crates/tunal/ui/dialogs/launcher.slint new file mode 100644 index 0000000..9764dea --- /dev/null +++ b/crates/tunal/ui/dialogs/launcher.slint @@ -0,0 +1,126 @@ +import { Theme } from "../theme.slint"; +import { Dialog } from "../components/dialog.slint"; +import { ButtonKind } from "../components/button.slint"; +import { IconChoice, IconPicker } from "../components/icon-picker.slint"; +import { Switch } from "../components/switch.slint"; +import { FileKind, TextField } from "../components/text-field.slint"; + +export struct LauncherData { + // Changes a file that exists. + editing: bool, + name: string, + comment: string, + command: string, + terminal: bool, + choice: int, + image-path: string, + browsed: IconChoice, + error: string, +} + +// Makes or changes a launcher (a desktop entry). `saved` runs on Save; the owner closes the +// dialog or sets `error`. +export component LauncherDialog inherits Dialog { + in-out property data; + in property <[IconChoice]> icons; + callback saved(); + + title: root.data.editing ? "Edit launcher" : "New launcher"; + dialog-width: 456px; + actions: [{ text: "Cancel", kind: ButtonKind.text }, { text: root.data.editing ? "Save" : "Create", kind: ButtonKind.filled }]; + default-action: 1; + cancel-action: 0; + content-focus: true; + focus-content => { + picker.browsing = false; + name-field.focus-input(); + } + action(i) => { + picker.browsing = false; + if i == 1 { + root.saved(); + } else { + root.close(); + } + } + + // While the icon browser is open it has the dialog to itself. + Rectangle { + height: picker.browsing ? 0 : fields.preferred-height; + visible: !picker.browsing; + clip: true; + + fields := VerticalLayout { + width: 100%; + + HorizontalLayout { + spacing: Theme.space-3; + + name-field := TextField { + width: (fields.width - Theme.space-3) / 2; + label: "Name"; + placeholder: "My app"; + text <=> root.data.name; + accepted => { + root.saved(); + } + } + + TextField { + width: (fields.width - Theme.space-3) / 2; + label: "Description"; + placeholder: "Optional"; + text <=> root.data.comment; + accepted => { + root.saved(); + } + } + } + + TextField { + label: "Command or program"; + placeholder: "firefox --private-window"; + picks: FileKind.program; + text <=> root.data.command; + accepted => { + root.saved(); + } + } + + HorizontalLayout { + spacing: Theme.space-3; + + Text { + horizontal-stretch: 1; + text: "Run in a terminal"; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + } + + Switch { + checked <=> root.data.terminal; + accessible-label: "Run in a terminal"; + } + } + } + } + + picker := IconPicker { + icons: root.icons; + choice <=> root.data.choice; + image-path <=> root.data.image-path; + browsed <=> root.data.browsed; + accepted => { + root.saved(); + } + } + + if root.data.error != "": Text { + text: root.data.error; + color: Theme.error; + font-size: Theme.body-small.size; + wrap: word-wrap; + } +} diff --git a/crates/tunal/ui/dialogs/place-icon.slint b/crates/tunal/ui/dialogs/place-icon.slint index 241484b..ef68049 100644 --- a/crates/tunal/ui/dialogs/place-icon.slint +++ b/crates/tunal/ui/dialogs/place-icon.slint @@ -10,6 +10,7 @@ export component PlaceIconDialog inherits Dialog { in property <[IconChoice]> icons; in-out property choice; in-out property image-path; + in-out property browsed; in property error; callback saved(); @@ -21,6 +22,7 @@ export component PlaceIconDialog inherits Dialog { default-action: 1; cancel-action: 0; action(i) => { + picker.browsing = false; if i == 1 { root.saved(); } else { @@ -28,10 +30,11 @@ export component PlaceIconDialog inherits Dialog { } } - IconPicker { + picker := IconPicker { icons: root.icons; choice <=> root.choice; image-path <=> root.image-path; + browsed <=> root.browsed; accepted => { root.saved(); } diff --git a/crates/tunal/ui/dialogs/tag-editor.slint b/crates/tunal/ui/dialogs/tag-editor.slint index aeb5d43..19a755b 100644 --- a/crates/tunal/ui/dialogs/tag-editor.slint +++ b/crates/tunal/ui/dialogs/tag-editor.slint @@ -5,7 +5,7 @@ import { Icons } from "../components/icon.slint"; import { Dialog } from "../components/dialog.slint"; import { ButtonKind } from "../components/button.slint"; import { IconButton } from "../components/icon-button.slint"; -import { TextField } from "../components/text-field.slint"; +import { FileKind, TextField } from "../components/text-field.slint"; import { Shape, ShapeKind } from "../components/shape.slint"; // One text field of the editor. `mixed` fields start empty with "Keep" as their placeholder: @@ -220,9 +220,13 @@ export component TagEditorDialog inherits Dialog { } TextField { - label: "Cover image (full path, then Enter) or drop one on the cover"; + label: "Cover image, or drop one on the cover"; placeholder: "/path/to/cover.jpg"; + picks: FileKind.cover; text <=> root.data.cover-path; + picked(text) => { + root.cover-path-accepted(text); + } accepted(text) => { root.cover-path-accepted(text); } diff --git a/crates/tunal/ui/motion.slint b/crates/tunal/ui/motion.slint index d926e4c..93aea44 100644 --- a/crates/tunal/ui/motion.slint +++ b/crates/tunal/ui/motion.slint @@ -35,6 +35,9 @@ export global Motion { out property emphasized: cubic-bezier(0.2, 0, 0, 1); out property emphasized-decelerate: cubic-bezier(0.05, 0.7, 0.1, 1); out property emphasized-accelerate: cubic-bezier(0.3, 0, 0.8, 0.15); + // A spring's path: runs past its end and comes back (M3 expressive, fast spatial). For + // things that travel to where the pointer clicked; run it for `medium3`. + out property spring: cubic-bezier(0.42, 1.67, 0.21, 0.9); out property standard: cubic-bezier(0.2, 0, 0, 1); out property standard-decelerate: cubic-bezier(0, 0, 0, 1); out property standard-accelerate: cubic-bezier(0.3, 0, 1, 1); diff --git a/crates/tunal/ui/shell/player-bar.slint b/crates/tunal/ui/shell/player-bar.slint index 16abbda..b9a5346 100644 --- a/crates/tunal/ui/shell/player-bar.slint +++ b/crates/tunal/ui/shell/player-bar.slint @@ -51,8 +51,8 @@ component PlayButton inherits StateLayer { // The wavy seek bar: the played part is a sine line that travels while the track plays and // flattens when it pauses; a gap, the handle at the playhead, another gap, then the flat rest -// of the track with a stop dot at its end. Press or drag anywhere: the handle follows the -// pointer and release seeks; ←/→ step. Paused (or under reduced motion) nothing moves, so +// of the track with a stop dot at its end. Press anywhere: the handle springs to the pointer; +// drag it on, and release seeks. ←/→ step. Paused (or under reduced motion) nothing moves, so // nothing repaints. component SeekBar { // 0..1 @@ -73,8 +73,17 @@ component SeekBar { property phase: root.amplitude > 0 && !Motion.reduced ? Math.mod(animation-tick() / Motion.wave-period, 1) : 0; // The handle's centre runs from half a handle in to half a handle before the end. property travel: max(1px, root.width - Theme.seek-handle-width); - property shown: touch.pressed ? clamp((touch.mouse-x - Theme.seek-handle-width / 2) / root.travel, 0, 1) : root.position; - property head: Theme.seek-handle-width / 2 + root.shown * root.travel; + property pointed: clamp((touch.mouse-x - Theme.seek-handle-width / 2) / root.travel, 0, 1); + // Where a release or step sent the playhead: shown while the handle springs there, so a + // position reported meanwhile doesn't cut the spring short. + property target; + property springing; + property shown: touch.pressed ? root.pointed : root.springing ? root.target : root.position; + animate shown { + duration: root.springing ? Motion.time(Motion.medium3) : Motion.none; + easing: Motion.spring; + } + property head: Theme.seek-handle-width / 2 + clamp(root.shown, 0, 1) * root.travel; property wave-end: max(0, root.head - Theme.seek-handle-width / 2 - root.gap); property rest-start: root.head + Theme.seek-handle-width / 2 + root.gap; property band: 2 * root.amplitude + root.stroke; @@ -90,8 +99,29 @@ component SeekBar { root.band-top + root.amplitude * (1 - Math.sin((x / Theme.seek-wave-length - root.phase) * 360deg)) + root.stroke / 2 } + function spring() { + root.springing = !Motion.reduced; + rest.restart(); + } + + rest := Timer { + running: root.springing; + interval: Motion.medium3; + triggered => { + root.springing = false; + } + } + + // Focused by a click: no focus ring until a key is used. + property clicked-focus; keys := FocusScope { + changed has-focus => { + if !self.has-focus { + root.clicked-focus = false; + } + } key-pressed(event) => { + root.clicked-focus = false; if event.text == Key.LeftArrow { root.step(-1); return accept; @@ -168,7 +198,7 @@ component SeekBar { } // Keyboard focus: a ring round the bar. - if keys.has-focus: Rectangle { + if keys.has-focus && !root.clicked-focus: Rectangle { x: -Theme.space-1; width: root.width + 2 * Theme.space-1; border-radius: Theme.corner-sm; @@ -180,10 +210,16 @@ component SeekBar { mouse-cursor: pointer; pointer-event(event) => { if event.kind == PointerEventKind.down { + root.clicked-focus = true; keys.focus(); + root.target = root.pointed; + root.spring(); } + // `pressed` is off by now: the pointer tells where, not `shown`. if event.kind == PointerEventKind.up && event.button == PointerEventButton.left { - root.seek(root.shown); + root.target = root.pointed; + root.seek(root.pointed); + root.spring(); } } } diff --git a/crates/tunal/ui/shell/sidebar.slint b/crates/tunal/ui/shell/sidebar.slint index 56f0fc6..0092025 100644 --- a/crates/tunal/ui/shell/sidebar.slint +++ b/crates/tunal/ui/shell/sidebar.slint @@ -116,6 +116,11 @@ component SectionHeader inherits StateLayer { export component Sidebar inherits Rectangle { in property <[SidebarSection]> sections; // Left click (or middle click, `new-tab`) on item `index` of section `section`. + // The current place: its section and row, and the rows of the open sections before it. + in property has-current; + in property current-section; + in property current-row; + in property rows-before; callback open(section: int, index: int, new-tab: bool); callback toggle(section: int); callback add-bookmark(); @@ -124,6 +129,17 @@ export component Sidebar inherits Rectangle { callback item-menu(section: int, index: int, x: length, y: length); property row-height: 44px; + property header-height: 36px; + // Rows move because a section folds: the selection goes with them instead of springing. + property folding; + + fold-time := Timer { + running: root.folding; + interval: Motion.medium2; + triggered => { + root.folding = false; + } + } // 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. @@ -136,6 +152,26 @@ export component Sidebar inherits Rectangle { mouse-drag-pan-enabled: false; content-height: max(self.height, column.preferred-height); + // The selection: springs to the place that was opened. + Rectangle { + x: Theme.space-3; + y: Theme.space-3 + root.header-height + root.current-section * (root.header-height + Theme.space-1) + + (root.rows-before + root.current-row) * root.row-height; + width: parent.width - 2 * Theme.space-3; + height: root.row-height; + border-radius: Theme.corner-full(self.height); + background: Theme.secondary-container; + opacity: root.has-current ? 1 : 0; + animate y { + duration: Motion.time(root.folding ? Motion.medium2 : Motion.medium3); + easing: root.folding ? Motion.emphasized : Motion.spring; + } + animate opacity { + duration: Motion.time(Motion.short4); + easing: Motion.standard; + } + } + column := VerticalLayout { padding: Theme.space-3; spacing: Theme.space-1; @@ -148,6 +184,7 @@ export component Sidebar inherits Rectangle { can-add: section.can-add; can-connect: section.can-connect; clicked => { + root.folding = !Motion.reduced; root.toggle(s); } add => { @@ -219,6 +256,7 @@ export component Sidebar inherits Rectangle { title: item.name; tooltip: item.tip; selected: item.current; + own-fill: false; shaped: true; shape: root.shapes[mod(i, root.shapes.length)]; focusable: false; diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index d60f6ca..23d3fdd 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -297,5 +297,11 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - 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. +## Seek, spring motion, archives, pickers (user request) +- Done: seek bar seeks (the release read `pressed`, already off); its handle and the sidebar selection spring to the click (`Motion.spring`); Compress: zip, 7z, tar, tar.gz/bz2/xz/zst, wim, and gz/bz2/xz for one file; extraction of everything in `tools::ARCHIVES` (7z or bsdtar); file picker (portal) on every path field (`FilePicks`, `file_picker.rs`); icon browser over the whole icon theme in both icon dialogs; the browser has categories; Create new → Launcher… and Edit launcher… (`launcher.rs`); new tab opens Home; a file's path in the location bar opens its folder with it selected. +- Also fixed: a dialog opened from a menu lost focus to the view (`Dialog.settle`), so typing filtered the folder. +- Verified: clippy, fmt, release build, seek / sidebar / icon browser / new launcher under Xvfb, pack + unpack of each format with the same commands by hand. +- Not done: no test run (user: save credits); file picker not opened live; encrypted archives only report that they need a password. + ## Later -