From cbbfa9875da46a8ca1d640d619b2c389801cad18 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 18 Nov 2026 18:49:24 -0600 Subject: [PATCH] S012: properties dialog, open in default app, Open with chooser and desktop entry helpers Also carries S013's shared-file hunks (actions.rs, app.slint, main.rs, shell/mod.rs). Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + .../S012-properties-open-with.md | 10 +- Plans/INDEX.md | 2 +- crates/tunal/Cargo.toml | 1 + crates/tunal/src/actions.rs | 155 +++- crates/tunal/src/desktop_apps.rs | 694 ++++++++++++++++++ crates/tunal/src/main.rs | 12 + crates/tunal/src/open.rs | 239 ++++++ crates/tunal/src/properties.rs | 410 +++++++++++ crates/tunal/src/shell/mod.rs | 16 +- crates/tunal/src/shell/pane.rs | 8 +- crates/tunal/ui/app.slint | 111 ++- crates/tunal/ui/dialogs/open-with.slint | 171 +++++ crates/tunal/ui/dialogs/properties.slint | 176 +++++ docs/PROGRESS.md | 6 + 15 files changed, 1960 insertions(+), 52 deletions(-) create mode 100644 crates/tunal/src/desktop_apps.rs create mode 100644 crates/tunal/src/open.rs create mode 100644 crates/tunal/src/properties.rs create mode 100644 crates/tunal/ui/dialogs/open-with.slint create mode 100644 crates/tunal/ui/dialogs/properties.slint diff --git a/Cargo.lock b/Cargo.lock index 4373047..f7a52e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5500,6 +5500,7 @@ dependencies = [ "toml", "tunal-core", "tunal-theme", + "zbus", ] [[package]] diff --git a/Plans/03 File browsing/S012-properties-open-with.md b/Plans/03 File browsing/S012-properties-open-with.md index 7e51cd0..015479d 100644 --- a/Plans/03 File browsing/S012-properties-open-with.md +++ b/Plans/03 File browsing/S012-properties-open-with.md @@ -10,11 +10,11 @@ Properties dialog; files open in their default app; an Open with chooser lists a crates/tunal/src/actions.rs; crates/tunal/ui/components/dialog.slint; crates/tunal-core trait. ## Steps -- [ ] Properties: name, type, location, size (recursive count off-thread with live update), dates, permissions as text and rwx grid, owner/group names, symlink target; multi-selection summary. Read only (editing → Later). -- [ ] Open: Enter/double-click on a file → portal `OpenURI` via zbus; fallback spawn `xdg-open` without a shell. -- [ ] Desktop apps: parse `.desktop` files from `XDG_DATA_DIRS/applications` and `mimeapps.list` (defaults, added/removed associations); app icons from the icon theme with a glyph fallback. -- [ ] Open with dialog: apps for the mime type, other apps, set as default (writes `$XDG_CONFIG_HOME/mimeapps.list`); launch with Exec field codes (%f %F %u %U), no shell. -- [ ] PROGRESS entry, INDEX line, commit `S012: …` +- [x] Properties: name, type, location, size (recursive count off-thread with live update), dates, permissions as text and rwx grid, owner/group names, symlink target; multi-selection summary. Read only (editing → Later). +- [x] Open: Enter/double-click on a file → portal `OpenURI` via zbus; fallback spawn `xdg-open` without a shell. +- [x] Desktop apps: parse `.desktop` files from `XDG_DATA_DIRS/applications` and `mimeapps.list` (defaults, added/removed associations); app icons from the icon theme with a glyph fallback. +- [x] Open with dialog: apps for the mime type, other apps, set as default (writes `$XDG_CONFIG_HOME/mimeapps.list`); launch with Exec field codes (%f %F %u %U), no shell. +- [x] PROGRESS entry, INDEX line, commit `S012: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index f27064e..650da3b 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -24,7 +24,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v - [x] [S009 — Icon grid view and list motion](03%20File%20browsing/S009-grid-and-list-motion.md) · Opus high - [x] [S010 — Tabs, split view, breadcrumbs, history and places](03%20File%20browsing/S010-navigation-shell.md) · Opus medium - [x] [S011 — File operation actions](03%20File%20browsing/S011-file-op-actions.md) · Sonnet high -- [ ] [S012 — Properties, Open and Open with](03%20File%20browsing/S012-properties-open-with.md) · Sonnet medium +- [x] [S012 — Properties, Open and Open with](03%20File%20browsing/S012-properties-open-with.md) · Sonnet medium - [x] [S013 — Settings dialog and editable context menus](03%20File%20browsing/S013-settings-context-menus.md) · Sonnet high - [ ] [S014 — In-app drag and drop](03%20File%20browsing/S014-in-app-dnd.md) · Opus medium diff --git a/crates/tunal/Cargo.toml b/crates/tunal/Cargo.toml index 3e27bd7..97daccd 100644 --- a/crates/tunal/Cargo.toml +++ b/crates/tunal/Cargo.toml @@ -12,6 +12,7 @@ png.workspace = true tunal-core = { path = "../tunal-core" } jiff.workspace = true serde.workspace = true +zbus.workspace = true toml.workspace = true [build-dependencies] diff --git a/crates/tunal/src/actions.rs b/crates/tunal/src/actions.rs index 867b999..a496d89 100644 --- a/crates/tunal/src/actions.rs +++ b/crates/tunal/src/actions.rs @@ -11,6 +11,9 @@ use tunal_core::ops::{self, JobKind}; use tunal_core::{Locations, Uri}; use crate::jobs_bridge::Bridge; +use crate::menus::{Context as MenuContext, Menus}; +use crate::open::Opener; +use crate::properties::Properties; use crate::shell::Shell; use crate::shell::pane::Pane; use crate::{MainWindow, MenuEntry, MenuItem}; @@ -28,6 +31,10 @@ pub enum Action { Delete, Restore, EmptyTrash, + Settings, + Open, + OpenWith, + Properties, } enum Shortcut { @@ -36,7 +43,7 @@ enum Shortcut { } impl Action { - pub const ALL: [Action; 10] = [ + pub const ALL: [Action; 14] = [ Self::Cut, Self::Copy, Self::Paste, @@ -47,12 +54,12 @@ impl Action { Self::Delete, Self::Restore, Self::EmptyTrash, + Self::Settings, + Self::Open, + Self::OpenWith, + Self::Properties, ]; - #[expect( - dead_code, - reason = "the context menu editor (S013) refers to actions by id" - )] pub fn id(self) -> &'static str { match self { Self::Cut => "cut", @@ -65,9 +72,17 @@ impl Action { Self::Delete => "delete", Self::Restore => "restore", Self::EmptyTrash => "empty-trash", + Self::Settings => "settings", + Self::Open => "open", + Self::OpenWith => "open-with", + Self::Properties => "properties", } } + pub fn from_id(id: &str) -> Option { + Self::ALL.into_iter().find(|a| a.id() == id) + } + pub fn label(self) -> &'static str { match self { Self::Cut => "Cut", @@ -80,6 +95,10 @@ impl Action { Self::Delete => "Delete permanently", Self::Restore => "Restore", Self::EmptyTrash => "Empty Trash", + Self::Settings => "Settings", + Self::Open => "Open", + Self::OpenWith => "Open with…", + Self::Properties => "Properties", } } @@ -96,6 +115,10 @@ impl Action { Self::Delete => "\u{e92b}", Self::Restore => "\u{e938}", Self::EmptyTrash => "\u{e16c}", + Self::Settings => "\u{e8b8}", + Self::Open => "\u{e89e}", + Self::OpenWith => "\u{e5c3}", + Self::Properties => "\u{e88e}", } } @@ -110,11 +133,14 @@ impl Action { Self::NewFolder => (Shortcut::Char('n'), true), Self::Trash => (Shortcut::Key(Key::Delete), false), Self::Delete => (Shortcut::Key(Key::Delete), true), - Self::Restore | Self::EmptyTrash => return None, + Self::Settings => (Shortcut::Char(','), false), + Self::Restore | Self::EmptyTrash | Self::Open | Self::OpenWith | Self::Properties => { + return None; + } }) } - fn shortcut_text(self) -> String { + pub fn shortcut_text(self) -> String { match self.shortcut() { None => String::new(), Some((Shortcut::Char(c), shift)) => { @@ -155,6 +181,9 @@ impl Action { Self::Delete => ctx.selected > 0 && (ctx.writable || ctx.in_trash), Self::Restore => ctx.in_trash && ctx.selected > 0, Self::EmptyTrash => ctx.in_trash, + Self::Settings => true, + Self::Open | Self::OpenWith => files && ctx.selected > 0, + Self::Properties => true, } } } @@ -170,32 +199,6 @@ pub struct Context { pub paste: bool, } -/// The default context menu: `None` is a separator. -fn menu_layout(in_trash: bool) -> Vec> { - if in_trash { - return vec![ - Some(Action::Restore), - Some(Action::Copy), - Some(Action::CopyPath), - None, - Some(Action::Delete), - Some(Action::EmptyTrash), - ]; - } - vec![ - Some(Action::Cut), - Some(Action::Copy), - Some(Action::Paste), - None, - Some(Action::CopyPath), - Some(Action::Rename), - Some(Action::NewFolder), - None, - Some(Action::Trash), - Some(Action::Delete), - ] -} - #[derive(Default)] struct Clipboard { uris: Vec, @@ -211,11 +214,17 @@ pub struct Actions { clipboard: RefCell, /// The actions of the open context menu, by item (separators are `None`). menu: RefCell>>, + /// The layout of every context menu (`menus.toml`). + menus: RefCell, + opener: Rc, + properties: Rc, } impl Actions { pub fn attach(ui: &MainWindow, shell: &Rc, locations: Locations) -> Rc { let bridge = Bridge::attach(ui, locations.clone()); + let opener = Opener::attach(ui, locations.clone(), bridge.clone()); + let properties = Properties::attach(ui, locations.clone()); let actions = Rc::new_cyclic(|me| Self { me: me.clone(), ui: ui.as_weak(), @@ -224,6 +233,9 @@ impl Actions { bridge, clipboard: RefCell::new(Clipboard::default()), menu: RefCell::new(Vec::new()), + menus: RefCell::new(Menus::load()), + opener, + properties, }); let me = actions.me.clone(); let shell_weak = Rc::downgrade(shell); @@ -267,9 +279,46 @@ impl Actions { // ---- menus and keys ----------------------------------------------------------------- - fn menu_items(&self, pane: &Pane) -> Vec { + /// Which menu a right click opens: by the row under the pointer (`over`) and the selection. + fn menu_context(&self, pane: &Pane, ctx: &Context, over: bool) -> MenuContext { + if ctx.in_trash { + MenuContext::Trash + } else if !over || ctx.selected == 0 { + MenuContext::Empty + } else if ctx.selected > 1 { + MenuContext::Multiple + } else if pane.model.selection_is_dir() { + MenuContext::Folder + } else { + MenuContext::File + } + } + + /// The ids of a context's menu, for the editor. + pub fn menu_ids(&self, ctx: MenuContext) -> Vec { + self.menus.borrow().ids(ctx) + } + + pub fn menu_is_default(&self, ctx: MenuContext) -> bool { + self.menus.borrow().is_default(ctx) + } + + /// `None` puts the default menu back. + pub fn set_menu(&self, ctx: MenuContext, ids: Option>) { + let mut menus = self.menus.borrow_mut(); + match ids { + Some(ids) => menus.set(ctx, ids), + None => menus.reset(ctx), + } + menus.save(); + } + + fn menu_items(&self, pane: &Pane, over: bool) -> Vec { let ctx = self.context(pane); - let layout = menu_layout(ctx.in_trash); + let layout = self + .menus + .borrow() + .layout(self.menu_context(pane, &ctx, over)); let items = layout .iter() .map(|entry| match entry { @@ -296,7 +345,8 @@ impl Actions { } /// Opens the menu for the active pane; a right click on a row not in the selection - /// selects that row first. + /// selects that row first. `row` -1 is the empty area, -2 the toolbar button (the + /// selection decides). fn open_menu(&self, pane: usize, row: i32, x: f32, y: f32) { let Some(shell) = self.shell() else { return; @@ -312,7 +362,7 @@ impl Actions { { p.model.click(r, false, false); } - let items = self.menu_items(&p); + let items = self.menu_items(&p, row != -1); if let Some(ui) = self.ui.upgrade() { ui.set_context_menu_items(ModelRc::new(VecModel::from(items))); ui.invoke_open_context_menu(x, y); @@ -350,6 +400,11 @@ impl Actions { // ---- actions ------------------------------------------------------------------------ + /// Enter or double-click on a file. + pub fn open_file(&self, uri: Uri) { + self.opener.open(&uri); + } + pub fn run(&self, action: Action) { let Some(shell) = self.shell() else { return; @@ -392,6 +447,30 @@ impl Actions { } }); } + Action::Open => { + // One folder opens in this pane; otherwise the files open and folders are skipped. + if let [only] = uris.as_slice() + && pane.model.selection_is_dir() + { + pane.go(only.clone()); + } else { + for uri in uris.iter().filter(|_| !pane.model.selection_is_dir()) { + self.opener.open(uri); + } + } + } + Action::OpenWith => self.opener.open_with(uris), + Action::Properties => { + self.properties + .show(if uris.is_empty() { vec![dir] } else { uris }); + return; + } + Action::Settings => { + if let Some(ui) = self.ui.upgrade() { + ui.invoke_show_settings(0); + } + return; + } Action::EmptyTrash => { let me = self.me.clone(); self.bridge.confirm( @@ -549,7 +628,7 @@ impl Actions { ui.on_actions_menu_requested(move |x, y| { if let Some(a) = me.upgrade() { let active = a.shell().map_or(0, |s| s.active_index()); - a.open_menu(active, -1, x, y); + a.open_menu(active, -2, x, y); } }); let me = self.me.clone(); diff --git a/crates/tunal/src/desktop_apps.rs b/crates/tunal/src/desktop_apps.rs new file mode 100644 index 0000000..96cc800 --- /dev/null +++ b/crates/tunal/src/desktop_apps.rs @@ -0,0 +1,694 @@ +//! Installed applications: `.desktop` entries, `mimeapps.list` associations, Exec launching +//! and icon theme lookup (the freedesktop specs; no shell is ever involved). + +use std::collections::{HashMap, HashSet}; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +const DESKTOP_GROUP: &str = "Desktop Entry"; +const DEFAULTS: &str = "Default Applications"; +const ADDED: &str = "Added Associations"; +const REMOVED: &str = "Removed Associations"; + +#[derive(Clone, Debug)] +pub struct App { + /// Desktop file id (`org.example.App.desktop`). + pub id: String, + pub name: String, + pub exec: String, + pub icon: Option, + pub mime_types: Vec, + pub terminal: bool, + /// `NoDisplay`: usable for its own types but not offered as "other". + pub no_display: bool, + pub path: PathBuf, +} + +/// The apps for a mime type: the ones that handle it (default first), then everything else. +pub struct Choices { + pub handlers: Vec, + pub others: Vec, + /// Id of the default among `handlers`, when there is one. + pub default: Option, +} + +#[derive(Default)] +struct Associations { + defaults: HashMap>, + added: HashMap>, + removed: HashMap>, +} + +pub struct Apps { + apps: Vec, + assoc: Associations, +} + +// ---- directories ---------------------------------------------------------------------------- + +fn env_path(name: &str) -> Option { + std::env::var_os(name) + .map(PathBuf::from) + .filter(|p| p.is_absolute()) +} + +fn home() -> Option { + env_path("HOME") +} + +pub fn config_home() -> Option { + env_path("XDG_CONFIG_HOME").or_else(|| home().map(|h| h.join(".config"))) +} + +fn data_home() -> Option { + env_path("XDG_DATA_HOME").or_else(|| home().map(|h| h.join(".local/share"))) +} + +fn list_env(name: &str, default: &str) -> Vec { + let value = std::env::var(name) + .ok() + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| default.to_string()); + value + .split(':') + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .collect() +} + +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 +} + +// ---- INI ------------------------------------------------------------------------------------ + +/// `(group, key, value)` of every entry, in file order. +fn parse_ini(text: &str) -> Vec<(String, String, String)> { + let mut group = String::new(); + let mut out = Vec::new(); + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + group = name.to_string(); + } else if let Some((key, value)) = line.split_once('=') { + out.push(( + group.clone(), + key.trim().to_string(), + value.trim().to_string(), + )); + } + } + out +} + +fn split_list(value: &str) -> Vec { + value + .split(';') + .filter(|s| !s.is_empty()) + .map(String::from) + .collect() +} + +/// Undoes the desktop entry value escapes (`\s \n \t \r \\`). +fn unescape(value: &str) -> String { + let mut out = String::new(); + let mut chars = value.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('s') => out.push(' '), + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some(other) => out.push(other), + None => out.push('\\'), + } + } + out +} + +/// `Name[de_DE]` suffixes to try, most specific first, from `LC_MESSAGES` / `LANG`. +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())) + .unwrap_or_default(); + let lang = lang.split('.').next().unwrap_or("").to_string(); + let short = lang.split('_').next().unwrap_or("").to_string(); + let mut out = Vec::new(); + if !lang.is_empty() && lang != "C" && lang != "POSIX" { + out.push(lang.clone()); + if short != lang { + out.push(short); + } + } + out +} + +// ---- desktop entries ------------------------------------------------------------------------ + +fn parse_desktop(id: &str, path: &Path, text: &str, locales: &[String]) -> Option { + let mut name = None; + let mut localized: Vec> = vec![None; locales.len()]; + let (mut exec, mut icon, mut kind) = (None, None, None); + let mut mime_types = Vec::new(); + let (mut terminal, mut no_display, mut hidden) = (false, false, false); + for (group, key, value) in parse_ini(text) { + if group != DESKTOP_GROUP { + continue; + } + match key.as_str() { + "Name" => name = Some(unescape(&value)), + "Exec" => exec = Some(value), + "Icon" => icon = Some(unescape(&value)), + "Type" => kind = Some(value), + "MimeType" => mime_types = split_list(&value), + "Terminal" => terminal = value == "true", + "NoDisplay" => no_display = value == "true", + "Hidden" => hidden = value == "true", + _ => { + if let Some(locale) = key.strip_prefix("Name[").and_then(|k| k.strip_suffix(']')) + && let Some(i) = locales.iter().position(|l| l == locale) + { + localized[i] = Some(unescape(&value)); + } + } + } + } + if hidden || kind.as_deref() != Some("Application") { + return None; + } + let name = localized.into_iter().flatten().next().or(name)?; + Some(App { + id: id.to_string(), + name, + exec: exec?, + icon: icon.filter(|i| !i.is_empty()), + mime_types, + terminal, + no_display, + path: path.to_path_buf(), + }) +} + +fn scan(dir: &Path, prefix: &str, locales: &[String], out: &mut Vec) { + let Ok(read) = fs::read_dir(dir) else { + return; + }; + for entry in read.flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().into_owned(); + if path.is_dir() { + scan(&path, &format!("{prefix}{name}-"), locales, out); + } else if name.ends_with(".desktop") + && let Ok(text) = fs::read_to_string(&path) + && let Some(app) = parse_desktop(&format!("{prefix}{name}"), &path, &text, locales) + { + out.push(app); + } + } +} + +fn mimeapps_files() -> Vec { + let mut files: Vec = config_home() + .into_iter() + .map(|c| c.join("mimeapps.list")) + .collect(); + files.extend( + list_env("XDG_CONFIG_DIRS", "/etc/xdg") + .into_iter() + .map(|d| d.join("mimeapps.list")), + ); + files.extend( + data_dirs() + .into_iter() + .map(|d| d.join("applications/mimeapps.list")), + ); + files +} + +impl Associations { + /// Folds files in, most important first: earlier files win for defaults, and removals + /// apply to what the same or an earlier file added. + fn load() -> Self { + let mut assoc = Self::default(); + for file in mimeapps_files() { + let Ok(text) = fs::read_to_string(file) else { + continue; + }; + for (group, mime, value) in parse_ini(&text) { + let map = match group.as_str() { + DEFAULTS => &mut assoc.defaults, + ADDED => &mut assoc.added, + REMOVED => &mut assoc.removed, + _ => continue, + }; + let list = map.entry(mime).or_default(); + for id in split_list(&value) { + if !list.contains(&id) { + list.push(id); + } + } + } + } + assoc + } +} + +impl Apps { + pub fn load() -> Self { + let locales = locale_suffixes(); + let mut found = Vec::new(); + for dir in data_dirs() { + scan(&dir.join("applications"), "", &locales, &mut found); + } + // The first directory that has an id wins. + let mut seen = HashSet::new(); + found.retain(|a| seen.insert(a.id.clone())); + Self { + apps: found, + assoc: Associations::load(), + } + } + + pub fn get(&self, id: &str) -> Option<&App> { + self.apps.iter().find(|a| a.id == id) + } + + /// Apps for `mime`: the defaults, the added associations, then apps that list the type. + pub fn choices(&self, mime: &str) -> Choices { + let removed = self.assoc.removed.get(mime); + let allowed = |id: &str| removed.is_none_or(|r| !r.iter().any(|x| x == id)); + let mut ids: Vec = Vec::new(); + let mut push = |id: &str| { + if !ids.iter().any(|x| x == id) { + ids.push(id.to_string()); + } + }; + let default_ids = self.assoc.defaults.get(mime).into_iter().flatten(); + let added_ids = self.assoc.added.get(mime).into_iter().flatten(); + for id in default_ids.chain(added_ids) { + push(id); + } + for app in &self.apps { + if app.mime_types.iter().any(|m| m == mime) && allowed(&app.id) { + push(&app.id); + } + } + let handlers: Vec = ids.iter().filter_map(|id| self.get(id).cloned()).collect(); + let default = self + .assoc + .defaults + .get(mime) + .and_then(|d| d.iter().find(|id| handlers.iter().any(|a| &a.id == *id))) + .cloned(); + let mut others: Vec = self + .apps + .iter() + .filter(|a| !a.no_display && !handlers.iter().any(|h| h.id == a.id)) + .cloned() + .collect(); + others.sort_by_key(|a| a.name.to_lowercase()); + Choices { + handlers, + others, + default, + } + } +} + +/// Makes `app_id` the default for `mime` in `$XDG_CONFIG_HOME/mimeapps.list`, keeping every +/// other line. +pub fn set_default(mime: &str, app_id: &str) -> std::io::Result<()> { + let dir = config_home().ok_or_else(|| std::io::Error::other("no config directory"))?; + let file = dir.join("mimeapps.list"); + let text = fs::read_to_string(&file).unwrap_or_default(); + let updated = with_default(&text, mime, app_id); + fs::create_dir_all(&dir)?; + let tmp = dir.join("mimeapps.list.tunal-tmp"); + let mut out = fs::File::create(&tmp)?; + out.write_all(updated.as_bytes())?; + out.sync_all()?; + fs::rename(tmp, file) +} + +/// `text` with `mime=app_id;` first in `[Default Applications]` (the group is added when +/// missing) and `app_id` no longer removed for `mime`. +fn with_default(text: &str, mime: &str, app_id: &str) -> String { + let mut lines: Vec = text.lines().map(String::from).collect(); + let group_range = |lines: &[String], name: &str| { + let start = lines.iter().position(|l| l.trim() == format!("[{name}]"))?; + let end = lines[start + 1..] + .iter() + .position(|l| l.trim().starts_with('[')) + .map_or(lines.len(), |i| start + 1 + i); + Some((start, end)) + }; + let key_line = |lines: &[String], range: (usize, usize)| { + (range.0 + 1..range.1).find(|&i| { + lines[i] + .split_once('=') + .is_some_and(|(k, _)| k.trim() == mime) + }) + }; + // Drop the app from the removed list. + if let Some(range) = group_range(&lines, REMOVED) + && let Some(i) = key_line(&lines, range) + { + let value = lines[i].split_once('=').map_or("", |(_, v)| v).to_string(); + let kept: Vec = split_list(&value) + .into_iter() + .filter(|id| id != app_id) + .collect(); + if kept.is_empty() { + lines.remove(i); + } else { + lines[i] = format!("{mime}={};", kept.join(";")); + } + } + let new = format!("{mime}={app_id};"); + match group_range(&lines, DEFAULTS) { + Some(range) => match key_line(&lines, range) { + Some(i) => lines[i] = new, + None => lines.insert(range.0 + 1, new), + }, + None => { + if lines.last().is_some_and(|l| !l.trim().is_empty()) { + lines.push(String::new()); + } + lines.push(format!("[{DEFAULTS}]")); + lines.push(new); + } + } + let mut out = lines.join("\n"); + out.push('\n'); + out +} + +// ---- Exec ----------------------------------------------------------------------------------- + +/// What an Exec line is run on: a local path and its URL. +pub struct Target { + pub path: PathBuf, +} + +impl Target { + fn url(&self) -> String { + tunal_core::Uri::from_path(&self.path).to_string() + } +} + +/// Splits an Exec value into arguments: spaces separate, double quotes group, and inside +/// quotes `\"`, `\``, `\$` and `\\` are literal. (The `\\` of the string escape layer is +/// undone first, as the spec asks.) +pub fn split_exec(exec: &str) -> Vec { + let exec = unescape_exec(exec); + let mut args = Vec::new(); + let mut current = String::new(); + let mut started = false; + let mut quoted = false; + let mut chars = exec.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '"' => { + quoted = !quoted; + started = true; + } + '\\' if quoted && matches!(chars.peek(), Some('"' | '`' | '$' | '\\')) => { + current.extend(chars.next()); + } + ' ' | '\t' if !quoted => { + if started { + args.push(std::mem::take(&mut current)); + started = false; + } + } + _ => { + current.push(c); + started = true; + } + } + } + if started { + args.push(current); + } + args +} + +/// The string-level escapes of the Exec key (`\\` and friends) before argument splitting. +fn unescape_exec(exec: &str) -> String { + let mut out = String::new(); + let mut chars = exec.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\\' && chars.peek() == Some(&'\\') { + chars.next(); + out.push('\\'); + out.push('\\'); + } else { + out.push(c); + } + } + out +} + +fn takes_lists(args: &[String]) -> bool { + args.iter().any(|a| a == "%F" || a == "%U") +} + +/// Command lines for opening `targets` with `app`: one when the Exec takes lists (`%F`/`%U`) +/// or when nothing is passed, else one per target. +pub fn command_lines(app: &App, targets: &[Target]) -> Vec> { + let template = split_exec(&app.exec); + if takes_lists(&template) || targets.len() <= 1 { + return vec![expand(&template, app, targets)]; + } + targets + .iter() + .map(|t| expand(&template, app, std::slice::from_ref(t))) + .collect() +} + +fn expand(template: &[String], app: &App, targets: &[Target]) -> Vec { + let mut out = Vec::new(); + for arg in template { + match arg.as_str() { + "%F" => out.extend( + targets + .iter() + .map(|t| t.path.to_string_lossy().into_owned()), + ), + "%U" => out.extend(targets.iter().map(Target::url)), + "%i" => { + if let Some(icon) = &app.icon { + out.push("--icon".into()); + out.push(icon.clone()); + } + } + _ => { + let one = targets.first(); + let mut text = String::new(); + let mut chars = arg.chars(); + while let Some(c) = chars.next() { + if c != '%' { + text.push(c); + continue; + } + match chars.next() { + Some('%') => text.push('%'), + Some('f') | Some('F') => { + text.extend(one.map(|t| t.path.to_string_lossy().into_owned())); + } + Some('u') | Some('U') => text.extend(one.map(Target::url)), + Some('c') => text.push_str(&app.name), + Some('k') => text.push_str(&app.path.to_string_lossy()), + // %i inside a longer argument, and the deprecated codes: nothing. + Some(_) | None => {} + } + } + // An argument that was only a code with nothing to pass disappears. + if !(text.is_empty() && arg.starts_with('%')) { + out.push(text); + } + } + } + } + out +} + +/// Starts `app` on `targets` (detached, no shell). Errors name what failed. +pub fn launch(app: &App, targets: &[Target]) -> Result<(), String> { + for mut argv in command_lines(app, targets) { + if app.terminal { + let mut full = vec!["xdg-terminal-exec".to_string()]; + full.append(&mut argv); + argv = full; + } + let Some((program, args)) = argv.split_first() else { + return Err(format!("{} has no command to run", app.name)); + }; + let mut command = Command::new(program); + command + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let mut child = command + .spawn() + .map_err(|e| format!("Couldn't start {}: {e}", app.name))?; + // Reap it when it ends; the app is not ours to wait for. + std::thread::spawn(move || { + let _ = child.wait(); + }); + } + Ok(()) +} + +// ---- icons ---------------------------------------------------------------------------------- + +struct ThemeDir { + path: PathBuf, + size: u32, + scalable: bool, + apps: bool, + /// Position of its theme in the inheritance chain. + theme: usize, +} + +fn gtk_icon_theme() -> Option { + let file = config_home()?.join("gtk-3.0/settings.ini"); + parse_ini(&fs::read_to_string(file).ok()?) + .into_iter() + .find(|(_, k, _)| k == "gtk-icon-theme-name") + .map(|(_, _, v)| v) +} + +fn theme_chain(name: &str, bases: &[PathBuf], chain: &mut Vec) { + if chain.iter().any(|n| n == name) { + return; + } + chain.push(name.to_string()); + for base in bases { + if let Ok(text) = fs::read_to_string(base.join(name).join("index.theme")) { + let inherits = parse_ini(&text) + .into_iter() + .find(|(g, k, _)| g == "Icon Theme" && k == "Inherits") + .map(|(_, _, v)| split_commas(&v)) + .unwrap_or_default(); + for parent in inherits { + theme_chain(&parent, bases, chain); + } + return; + } + } +} + +fn split_commas(value: &str) -> Vec { + value + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(String::from) + .collect() +} + +fn theme_dirs(base: &Path, name: &str, theme: usize) -> Vec { + let root = base.join(name); + let Ok(text) = fs::read_to_string(root.join("index.theme")) else { + return Vec::new(); + }; + let ini = parse_ini(&text); + let listed = ini + .iter() + .filter(|(g, k, _)| g == "Icon Theme" && (k == "Directories" || k == "ScaledDirectories")) + .flat_map(|(_, _, v)| split_commas(v)); + listed + .filter_map(|dir| { + let get = |key: &str| { + ini.iter() + .find(|(g, k, _)| *g == dir && k == key) + .map(|(_, _, v)| v.as_str()) + }; + let size = get("Size")?.parse().ok()?; + let context = get("Context").unwrap_or(""); + Some(ThemeDir { + path: root.join(&dir), + size, + scalable: get("Type") == Some("Scalable"), + theme, + apps: context.eq_ignore_ascii_case("Applications") + || dir.to_lowercase().contains("apps"), + }) + }) + .collect() +} + +/// 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). + dirs: Vec, +} + +impl IconTheme { + pub fn load() -> 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(); + if let Some(theme) = gtk_icon_theme() { + theme_chain(&theme, &bases, &mut chain); + } + theme_chain("hicolor", &bases, &mut chain); + let mut dirs = Vec::new(); + for (index, theme) in chain.iter().enumerate() { + for base in &bases { + let mut found = theme_dirs(base, theme, index); + found.retain(|d| d.apps); + dirs.extend(found); + } + } + Self { dirs } + } + + /// 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). + pub fn find(&self, name: &str, size: u32) -> Option { + 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 + } + }; + let mut order: Vec<&ThemeDir> = self.dirs.iter().collect(); + order.sort_by_key(|d| (d.theme, distance(d))); + for dir in order { + for ext in ["svg", "png"] { + let file = dir.path.join(format!("{name}.{ext}")); + if file.is_file() { + return Some(file); + } + } + } + for ext in ["svg", "png"] { + let file = PathBuf::from(format!("/usr/share/pixmaps/{name}.{ext}")); + if file.is_file() { + return Some(file); + } + } + None + } +} diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs index 5e8bbae..2c007d1 100644 --- a/crates/tunal/src/main.rs +++ b/crates/tunal/src/main.rs @@ -1,9 +1,14 @@ mod actions; mod config; +mod desktop_apps; mod folder; mod icons; mod jobs_bridge; +mod menus; +mod open; +mod properties; mod screenshot; +mod settings; mod shell; mod theme_bridge; @@ -61,6 +66,13 @@ fn window( .map(|dirs| dirs.iter().map(|d| Uri::from_path(d)).collect()) .collect(); let shell = shell::Shell::attach(&ui, Locations::with_local(), tabs, blocking); + // `TUNAL_SETTINGS=` opens the settings dialog (screenshots). + if let Some(page) = std::env::var("TUNAL_SETTINGS") + .ok() + .and_then(|p| p.parse().ok()) + { + ui.invoke_show_settings(page); + } Ok((ui, shell)) } diff --git a/crates/tunal/src/open.rs b/crates/tunal/src/open.rs new file mode 100644 index 0000000..b717504 --- /dev/null +++ b/crates/tunal/src/open.rs @@ -0,0 +1,239 @@ +//! Opening a file in its default application: the desktop portal first, `xdg-open` when the +//! portal is missing or refuses. Both run off the UI thread; a failure comes back as text. + +use std::collections::HashMap; +use std::fs::File; +use std::path::PathBuf; +use std::process::{Command, Stdio}; + +use zbus::blocking::{Connection, Proxy}; +use zbus::zvariant::{Fd, Value}; + +/// Opens `path` and calls `done(Err(message))` when neither way worked. +pub fn open(path: PathBuf, done: impl FnOnce(Result<(), String>) + Send + 'static) { + std::thread::spawn(move || { + let result = match portal(&path) { + Ok(()) => Ok(()), + Err(portal_error) => xdg_open(&path).map_err(|e| format!("{e} ({portal_error})")), + }; + done(result); + }); +} + +/// `org.freedesktop.portal.OpenURI.OpenFile` with the file as a descriptor (the portal's way +/// for local files; the answer arrives later on a request object, so only the call is checked). +fn portal(path: &PathBuf) -> Result<(), String> { + let file = File::open(path).map_err(|e| e.to_string())?; + let conn = Connection::session().map_err(|e| e.to_string())?; + let proxy = Proxy::new( + &conn, + "org.freedesktop.portal.Desktop", + "/org/freedesktop/portal/desktop", + "org.freedesktop.portal.OpenURI", + ) + .map_err(|e| e.to_string())?; + let options: HashMap<&str, Value> = HashMap::new(); + proxy + .call_method("OpenFile", &("", Fd::from(&file), options)) + .map(|_| ()) + .map_err(|e| e.to_string()) +} + +fn xdg_open(path: &PathBuf) -> Result<(), String> { + let status = Command::new("xdg-open") + .arg(path) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map_err(|e| format!("Couldn't start xdg-open: {e}"))?; + if status.success() { + Ok(()) + } else { + Err("No application could open this file".into()) + } +} + +// ---- the window side: Open and the Open with dialog ---------------------------------------- + +use std::cell::RefCell; +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::jobs_bridge::Bridge; +use crate::{AppRow, MainWindow}; + +/// Size of the application icons in the chooser. +const ICON_SIZE: u32 = 32; + +thread_local! { + static OPENER: RefCell> = const { RefCell::new(Weak::new()) }; +} + +/// What the open dialog is asking about. +struct Pending { + mime: String, + targets: Vec, + /// The apps in the dialog's rows. + apps: Vec, +} + +pub struct Opener { + ui: slint::Weak, + locations: Locations, + bridge: Rc, + pending: RefCell>, +} + +/// A row's data that can be built off the UI thread. +struct Prepared { + app: App, + icon: Option, + section: &'static str, + is_default: bool, +} + +/// The mime type of `first` and the app rows for it (reads the installed apps and icons). +fn prepare(locations: &Locations, first: &Uri) -> (&'static str, Vec) { + let mime = locations + .resolve(first) + .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 mut prepared = Vec::new(); + for (list, section) in [ + (&choices.handlers, "Recommended"), + (&choices.others, "Other applications"), + ] { + for (i, app) in list.iter().enumerate() { + prepared.push(Prepared { + icon: app.icon.as_ref().and_then(|n| icons.find(n, ICON_SIZE)), + is_default: choices.default.as_deref() == Some(&app.id), + section: if i == 0 { section } else { "" }, + app: app.clone(), + }); + } + } + (mime, prepared) +} + +impl Opener { + pub fn attach(ui: &MainWindow, locations: Locations, bridge: Rc) -> Rc { + let opener = Rc::new(Self { + ui: ui.as_weak(), + locations, + bridge, + pending: RefCell::new(None), + }); + OPENER.with(|o| *o.borrow_mut() = Rc::downgrade(&opener)); + ui.on_open_with_chosen(|row, as_default| { + if let Some(o) = OPENER.with(|o| o.borrow().upgrade()) { + o.chosen(row, as_default); + } + }); + opener + } + + fn with(f: impl FnOnce(&Opener) + Send + 'static) { + let _ = slint::invoke_from_event_loop(move || { + if let Some(o) = OPENER.with(|o| o.borrow().upgrade()) { + f(&o); + } + }); + } + + /// Opens `uri` in its default application. + pub fn open(&self, uri: &Uri) { + let Some(path) = uri.to_path() else { + self.bridge + .notify("Files here can't be opened yet; copy them somewhere first"); + return; + }; + open(path, |result| { + if let Err(message) = result { + Self::with(move |o| o.bridge.notify(message)); + } + }); + } + + /// Shows the chooser for `uris` (one thread reads the files and the installed apps). + pub fn open_with(&self, uris: Vec) { + let targets: Vec = uris + .iter() + .filter_map(|u| u.to_path().map(|path| Target { path })) + .collect(); + let (Some(first), false) = (uris.first().cloned(), targets.is_empty()) else { + self.bridge + .notify("Files here can't be opened yet; copy them somewhere first"); + return; + }; + let locations = self.locations.clone(); + std::thread::spawn(move || { + let (mime, prepared) = prepare(&locations, &first); + Self::with(move |o| o.show_chooser(mime, targets, prepared)); + }); + } + + fn show_chooser(&self, mime: &str, targets: Vec, prepared: Vec) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let rows: Vec = prepared + .iter() + .map(|p| { + let icon = p + .icon + .as_ref() + .and_then(|path| Image::load_from_path(path).ok()); + AppRow { + name: p.app.name.as_str().into(), + has_icon: icon.is_some(), + icon: icon.unwrap_or_default(), + section: p.section.into(), + is_default: p.is_default, + } + }) + .collect(); + ui.set_open_with_selected(if rows.is_empty() { -1 } else { 0 }); + ui.set_open_with_mime(mime.into()); + ui.set_open_with_as_default(false); + ui.set_open_with_apps(ModelRc::new(VecModel::from(rows))); + *self.pending.borrow_mut() = Some(Pending { + mime: mime.to_string(), + targets, + apps: prepared.into_iter().map(|p| p.app).collect(), + }); + ui.invoke_show_open_with(); + } + + /// `row` -1: cancelled. + fn chosen(&self, row: i32, as_default: bool) { + if let Some(ui) = self.ui.upgrade() { + ui.invoke_close_open_with(); + } + let Some(pending) = self.pending.borrow_mut().take() else { + return; + }; + let Some(app) = usize::try_from(row).ok().and_then(|r| pending.apps.get(r)) else { + return; + }; + if as_default { + match desktop_apps::set_default(&pending.mime, &app.id) { + Ok(()) => self.bridge.notify(format!( + "{} is now the default for {}", + app.name, pending.mime + )), + Err(e) => self + .bridge + .notify(format!("Couldn't save the default application: {e}")), + } + } + if let Err(message) = desktop_apps::launch(app, &pending.targets) { + self.bridge.notify(message); + } + } +} diff --git a/crates/tunal/src/properties.rs b/crates/tunal/src/properties.rs new file mode 100644 index 0000000..58b7164 --- /dev/null +++ b/crates/tunal/src/properties.rs @@ -0,0 +1,410 @@ +//! What the Properties dialog shows: facts about the selection, collected off the UI thread, +//! with the size of folders counted in the background and reported as it grows. + +use std::fs; +use std::ops::ControlFlow; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant, SystemTime}; + +use tunal_core::{Entry, Kind, Locations, Uri}; + +use crate::folder::format; +use crate::icons::{self, Category}; + +/// How often the counted size is reported while it grows. +const REPORT_EVERY: Duration = Duration::from_millis(100); + +/// Plain data for the dialog (it crosses threads before it becomes a Slint struct). +#[derive(Clone, Default)] +pub struct Info { + pub title: String, + pub glyph: &'static str, + /// `(label, value)` lines under the title. + pub rows: Vec<(String, String)>, + /// Size and contents lines, updated while folders are counted. + pub size: String, + pub contents: String, + pub scanning: bool, + /// Owner, group and others as `rwx` flags; `None` when the location has no permissions. + pub perms: Option<[bool; 9]>, + pub perm_text: String, +} + +#[derive(Default, Clone, Copy)] +struct Totals { + files: u64, + folders: u64, + bytes: u64, +} + +/// Stops the background count when dropped or cancelled. +#[derive(Clone, Default)] +pub struct Cancel(Arc); + +impl Cancel { + pub fn cancel(&self) { + self.0.store(true, Ordering::Relaxed); + } + + pub fn cancelled(&self) -> bool { + self.0.load(Ordering::Relaxed) + } +} + +/// Collects the facts of `uris` on a worker thread: `report` gets the dialog at once and +/// again as the folder count grows. Stops quietly when `cancel` is set. +pub fn gather( + locations: Locations, + uris: Vec, + cancel: Cancel, + report: impl Fn(Info) + Send + 'static, +) { + std::thread::spawn(move || { + let mut entries = Vec::new(); + let mut failed = 0; + for uri in &uris { + match locations.resolve(uri).and_then(|l| l.stat(uri)) { + Ok(entry) => entries.push((uri.clone(), entry)), + Err(_) => failed += 1, + } + } + let mut info = describe(&locations, &uris, &entries, failed); + let mut totals = Totals::default(); + let mut has_folder = false; + for (_, entry) in &entries { + if entry.kind == Kind::Dir { + has_folder = true; + totals.folders += 1; + } else { + totals.files += 1; + totals.bytes += entry.size; + } + } + info.size = size_text(totals.bytes); + info.scanning = has_folder; + // One plain file has nothing to count. + let counts = has_folder || entries.len() > 1; + if counts { + info.contents = contents_text(totals, has_folder); + } + report(info.clone()); + if !has_folder { + return; + } + let mut last = Instant::now(); + for (uri, entry) in &entries { + if entry.kind != Kind::Dir { + continue; + } + totals.folders -= 1; // counted again by the walk, which starts at the folder + let Ok(location) = locations.resolve(uri) else { + continue; + }; + walk(&*location, uri, &mut totals, &cancel, &mut |t| { + if last.elapsed() >= REPORT_EVERY { + last = Instant::now(); + let mut now = info.clone(); + now.size = size_text(t.bytes); + now.contents = contents_text(t, true); + report(now); + } + }); + if cancel.cancelled() { + return; + } + } + info.scanning = false; + info.size = size_text(totals.bytes); + info.contents = contents_text(totals, false); + report(info); + }); +} + +/// Adds the folder at `dir` and everything below it (links are counted, not followed). +fn walk( + location: &dyn tunal_core::Location, + dir: &Uri, + totals: &mut Totals, + cancel: &Cancel, + progress: &mut dyn FnMut(Totals), +) { + totals.folders += 1; + let mut subdirs = Vec::new(); + let mut sink = |chunk: Vec| { + for entry in chunk { + if entry.kind == Kind::Dir { + subdirs.push(dir.join(&entry.name)); + } else { + totals.files += 1; + totals.bytes += entry.size; + } + } + if cancel.cancelled() { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }; + // An unreadable folder counts as empty. + let _ = location.list(dir, &mut sink); + progress(*totals); + for sub in subdirs { + if cancel.cancelled() { + return; + } + walk(location, &sub, totals, cancel, progress); + } +} + +fn size_text(bytes: u64) -> String { + if bytes < 1024 { + format!("{bytes} B") + } else { + format!("{} ({bytes} bytes)", format::size(bytes)) + } +} + +fn contents_text(totals: Totals, scanning: bool) -> String { + let plural = |n: u64, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); + let text = format!( + "{}, {}", + plural(totals.files, "file", "files"), + plural(totals.folders, "folder", "folders") + ); + if scanning { format!("{text}…") } else { text } +} + +fn describe(locations: &Locations, uris: &[Uri], entries: &[(Uri, Entry)], failed: usize) -> Info { + let mut info = Info::default(); + if entries.is_empty() { + info.title = "Properties".into(); + info.glyph = Category::Other.glyph(); + info.rows.push(( + "Error".into(), + if failed > 0 { + "The item can't be read any more.".into() + } else { + "Nothing is selected.".into() + }, + )); + return info; + } + let place = |uri: &Uri| match uri.parent() { + Some(parent) => parent + .to_path() + .map_or_else(|| parent.to_string(), |p| p.to_string_lossy().into_owned()), + None => uri.to_string(), + }; + if let [(uri, entry)] = entries { + let category = Category::of(entry); + info.title = entry.display_name.clone(); + info.glyph = category.glyph(); + info.rows + .push(("Type".into(), icons::type_label(entry, category))); + info.rows.push(("Location".into(), place(uri))); + if let Kind::Symlink { target, .. } = &entry.kind { + info.rows + .push(("Link to".into(), tunal_core::display_name(target))); + } + if let Some(time) = entry.mtime { + info.rows.push(("Modified".into(), long_date(time))); + } + if let Some(path) = uri.to_path() + && let Ok(meta) = fs::symlink_metadata(&path) + { + if let Ok(time) = meta.accessed() { + info.rows.push(("Accessed".into(), long_date(time))); + } + if let Ok(time) = meta.created() { + info.rows.push(("Created".into(), long_date(time))); + } + } + let permissions = locations + .resolve(uri) + .is_ok_and(|l| l.capabilities().permissions); + if permissions { + info.rows.push(("Owner".into(), user_name(entry.uid))); + info.rows.push(("Group".into(), group_name(entry.gid))); + let mode = entry.mode; + info.perms = Some(std::array::from_fn(|i| mode & (0o400 >> i) != 0)); + info.perm_text = format!("{} ({:04o})", mode_text(mode), mode & 0o7777); + } + return info; + } + let folders = entries.iter().filter(|(_, e)| e.kind == Kind::Dir).count(); + let files = entries.len() - folders; + info.title = format!("{} items", entries.len()); + info.glyph = Category::Other.glyph(); + let count = + |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); + info.rows.push(( + "Selection".into(), + format!( + "{}, {}", + count(files, "file", "files"), + count(folders, "folder", "folders") + ), + )); + let first = place(&uris[0]); + let same = entries.iter().all(|(u, _)| place(u) == first); + info.rows.push(( + "Location".into(), + if same { + first + } else { + "Several folders".into() + }, + )); + if failed > 0 { + info.rows + .push(("Unreadable".into(), count(failed, "item", "items"))); + } + info +} + +fn long_date(time: SystemTime) -> String { + jiff::Timestamp::try_from(time) + .map(|ts| { + ts.to_zoned(jiff::tz::TimeZone::system()) + .strftime("%a %-d %b %Y, %H:%M:%S") + .to_string() + }) + .unwrap_or_default() +} + +/// `drwxr-xr-x` style text without the type letter: `rwxr-xr-x`, with `s`/`t` for the +/// special bits. +fn mode_text(mode: u32) -> String { + let mut out = String::new(); + for (i, c) in "rwxrwxrwx".chars().enumerate() { + let set = mode & (0o400 >> i) != 0; + let special = match i { + 2 => mode & 0o4000 != 0, + 5 => mode & 0o2000 != 0, + 8 => mode & 0o1000 != 0, + _ => false, + }; + out.push(match (special, set, i) { + (true, true, 8) => 't', + (true, false, 8) => 'T', + (true, true, _) => 's', + (true, false, _) => 'S', + (false, true, _) => c, + (false, false, _) => '-', + }); + } + out +} + +fn user_name(uid: u32) -> String { + lookup("/etc/passwd", uid) +} + +fn group_name(gid: u32) -> String { + lookup("/etc/group", gid) +} + +/// Name of `id` in a passwd or group file (third field); the number when it isn't listed. +fn lookup(file: &str, id: u32) -> String { + fs::read_to_string(file) + .ok() + .and_then(|text| { + text.lines().find_map(|line| { + let mut fields = line.split(':'); + let name = fields.next()?; + (fields.nth(1)?.parse::().ok()? == id).then(|| name.to_string()) + }) + }) + .unwrap_or_else(|| id.to_string()) +} + +// ---- the window side ------------------------------------------------------------------------ + +use std::cell::RefCell; +use std::rc::Rc; + +use slint::{ComponentHandle, ModelRc, VecModel}; + +use crate::{MainWindow, PropRow, PropertiesInfo}; + +pub struct Properties { + ui: slint::Weak, + locations: Locations, + /// Stops the count of the dialog that is showing. + cancel: RefCell, +} + +impl Properties { + pub fn attach(ui: &MainWindow, locations: Locations) -> Rc { + let me = Rc::new(Self { + ui: ui.as_weak(), + locations, + cancel: RefCell::new(Cancel::default()), + }); + let weak = Rc::downgrade(&me); + ui.on_properties_closed(move || { + if let Some(me) = weak.upgrade() { + me.cancel.borrow().cancel(); + if let Some(ui) = me.ui.upgrade() { + ui.invoke_close_properties(); + } + } + }); + me + } + + /// Shows the dialog for `uris`; the folder sizes fill in while it is open. + pub fn show(&self, uris: Vec) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + self.cancel.borrow().cancel(); + let cancel = Cancel::default(); + *self.cancel.borrow_mut() = cancel.clone(); + ui.set_properties(convert(&Info { + title: "Properties".into(), + glyph: Category::Other.glyph(), + scanning: true, + ..Info::default() + })); + ui.invoke_show_properties(); + let weak = self.ui.clone(); + let stop = cancel.clone(); + gather(self.locations.clone(), uris, cancel, move |info| { + let stop = stop.clone(); + let _ = weak.upgrade_in_event_loop(move |ui| { + if !stop.cancelled() { + ui.set_properties(convert(&info)); + } + }); + }); + } +} + +fn convert(info: &Info) -> PropertiesInfo { + let rows: Vec = info + .rows + .iter() + .map(|(label, value)| PropRow { + label: label.as_str().into(), + value: value.as_str().into(), + }) + .collect(); + let perms: Vec = info.perms.map(|p| p.to_vec()).unwrap_or_default(); + PropertiesInfo { + title: info.title.as_str().into(), + glyph: info.glyph.into(), + rows: ModelRc::new(VecModel::from(rows)), + size: if info.scanning && info.size.is_empty() { + "Counting…".into() + } else { + info.size.as_str().into() + }, + contents: info.contents.as_str().into(), + scanning: info.scanning, + has_perms: info.perms.is_some(), + perms: ModelRc::new(VecModel::from(perms)), + perm_text: info.perm_text.as_str().into(), + } +} diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs index 6b93aac..9b192c8 100644 --- a/crates/tunal/src/shell/mod.rs +++ b/crates/tunal/src/shell/mod.rs @@ -16,6 +16,7 @@ use tunal_core::{Locations, Uri}; use crate::actions::Actions; use crate::config::{self, Session, TabSession}; use crate::folder::format; +use crate::settings::SettingsUi; use crate::{ Completion, Crumb, MainWindow, MenuEntry, MenuItem, PaneData, PlaceItem, SidebarSection, TabData, @@ -54,6 +55,8 @@ pub struct Shell { completion: Arc, /// The file actions; set once the shell exists. actions: OnceCell>, + /// The settings dialog; kept alive here. + settings: OnceCell>, } impl Shell { @@ -80,10 +83,11 @@ impl Shell { menu_target: Cell::new(None), completion: Arc::new(AtomicU64::new(0)), actions: OnceCell::new(), + settings: OnceCell::new(), }); - let _ = shell - .actions - .set(Actions::attach(ui, &shell, shell.locations.clone())); + let actions = Actions::attach(ui, &shell, shell.locations.clone()); + let _ = shell.settings.set(SettingsUi::attach(ui, &shell, &actions)); + let _ = shell.actions.set(actions); ui.set_tabs(ModelRc::from(shell.tab_rows.clone())); ui.set_panes(ModelRc::from(shell.pane_rows.clone())); let settings: config::Settings = config::load("settings"); @@ -723,7 +727,11 @@ impl Shell { p.model.click(row.max(0) as usize, ctrl, shift) }); on_pane!(on_row_activated, |s, p, row| { - p.activate(usize::try_from(row).ok()); + if let (Some(file), Some(actions)) = + (p.activate(usize::try_from(row).ok()), s.actions.get()) + { + actions.open_file(file); + } s.show_chrome() }); on_pane!(on_select_all, |_s, p| p.model.select_all()); diff --git a/crates/tunal/src/shell/pane.rs b/crates/tunal/src/shell/pane.rs index 0fa9ef3..554a46a 100644 --- a/crates/tunal/src/shell/pane.rs +++ b/crates/tunal/src/shell/pane.rs @@ -112,16 +112,18 @@ impl Pane { } } - /// Enter or double-click on a row: a folder opens in this pane, with history. - pub fn activate(&self, row: Option) { + /// Enter or double-click on a row: a folder opens in this pane, with history; a file is + /// returned for the caller to open. + pub fn activate(&self, row: Option) -> Option { let before = self.dir(); - self.model.activate(row); + let file = self.model.activate(row); if self.dir() != before { if let Some(before) = before { self.back.borrow_mut().push(before); } self.forward.borrow_mut().clear(); } + file } pub fn can_back(&self) -> bool { diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint index 86677d8..ace1cdc 100644 --- a/crates/tunal/ui/app.slint +++ b/crates/tunal/ui/app.slint @@ -18,9 +18,13 @@ import { DialogAction } from "components/dialog.slint"; import { ConflictDialog, ConflictInfo } from "dialogs/conflict.slint"; 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 { SettingsDialog, SettingsData, EditRow } from "dialogs/settings.slint"; export { Theme, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode, GridRow } -export { ButtonKind, TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem, ToastData, ToastProgress, DialogAction, ConflictInfo } +export { ButtonKind, TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem, ToastData, ToastProgress, DialogAction, ConflictInfo, SettingsData, EditRow } +export { PropertiesInfo, PropRow, AppRow } export { Gallery, GalleryPage } from "gallery.slint"; // The window: sidebar, tab bar, toolbar with the breadcrumb, the panes of the current tab @@ -97,6 +101,33 @@ export component MainWindow inherits Window { in property errors-default; callback errors-answered(int); + // Settings dialog (settings.rs). `settings-opening` runs before it shows, so Rust can + // fill it in. + in-out property settings; + in property <[string]> menu-contexts; + in property menu-context; + in property <[EditRow]> menu-rows; + in property <[EditRow]> menu-available; + in property menu-can-reset; + callback settings-opening(); + callback settings-changed(SettingsData); + callback menu-context-selected(int); + callback menu-moved(int, int); + callback menu-removed(int); + callback menu-added(int); + callback menu-separator-added(); + callback menu-reset(); + + // Properties (properties.rs) and Open with (open.rs). + in property properties; + callback properties-closed(); + in property <[AppRow]> open-with-apps; + in-out property open-with-selected; + in-out property open-with-as-default; + in property open-with-mime; + // Row -1: cancelled. + callback open-with-chosen(int, bool); + // Navigation of the active pane. in property can-back; in property can-forward; @@ -141,6 +172,12 @@ export component MainWindow inherits Window { context-popup.open-at(x, y); } + public function show-settings(page: int) { + root.settings-opening(); + settings-dialog.page = page; + settings-dialog.show(); + } + public function show-conflict() { conflict-dialog.apply-all = false; conflict-dialog.show(); @@ -158,6 +195,22 @@ export component MainWindow inherits Window { confirm-dialog.close(); } + public function show-properties() { + properties-dialog.show(); + } + + public function close-properties() { + properties-dialog.close(); + } + + public function show-open-with() { + open-with-dialog.show(); + } + + public function close-open-with() { + open-with-dialog.close(); + } + public function show-errors() { errors-dialog.show(); } @@ -493,6 +546,41 @@ export component MainWindow inherits Window { } } + settings-dialog := SettingsDialog { + width: 100%; + height: 100%; + data <=> root.settings; + menu-contexts: root.menu-contexts; + menu-context: root.menu-context; + menu-rows: root.menu-rows; + menu-available: root.menu-available; + menu-can-reset: root.menu-can-reset; + changed(data) => { + root.settings-changed(data); + } + menu-context-selected(i) => { + root.menu-context-selected(i); + } + menu-moved(from, to) => { + root.menu-moved(from, to); + } + menu-removed(i) => { + root.menu-removed(i); + } + menu-added(i) => { + root.menu-added(i); + } + menu-separator-added => { + root.menu-separator-added(); + } + menu-reset => { + root.menu-reset(); + } + closed => { + root.focus-pane(); + } + } + conflict-dialog := ConflictDialog { width: 100%; height: 100%; @@ -513,6 +601,27 @@ export component MainWindow inherits Window { } } + properties-dialog := PropertiesDialog { + width: 100%; + height: 100%; + info: root.properties; + closed => { + root.properties-closed(); + } + } + + open-with-dialog := OpenWithDialog { + width: 100%; + height: 100%; + apps: root.open-with-apps; + mime: root.open-with-mime; + selected <=> root.open-with-selected; + as-default <=> root.open-with-as-default; + chosen(row, as-default) => { + root.open-with-chosen(row, as-default); + } + } + errors-dialog := ErrorsDialog { width: 100%; height: 100%; diff --git a/crates/tunal/ui/dialogs/open-with.slint b/crates/tunal/ui/dialogs/open-with.slint new file mode 100644 index 0000000..cc54e1f --- /dev/null +++ b/crates/tunal/ui/dialogs/open-with.slint @@ -0,0 +1,171 @@ +import { ListView } from "std-widgets.slint"; +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Icon } 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"; + +// One application. `section` is a heading shown above the row when it starts a group. +// `has-icon` tells the icon image from the glyph fallback. +export struct AppRow { + name: string, + icon: image, + has-icon: bool, + section: string, + is-default: bool, +} + +// Asks which application opens the files. `chosen(row, as-default)` runs on Open or a double +// click; the owner closes the dialog. +export component OpenWithDialog inherits Dialog { + in property <[AppRow]> apps; + in-out property selected: -1; + in-out property as-default; + in property mime; + callback chosen(int, bool); + + title: "Open with"; + body: root.mime; + dialog-width: 440px; + content-focus: true; + actions: [{ text: "Cancel", kind: ButtonKind.text }, { text: "Open", kind: ButtonKind.filled }]; + default-action: 1; + cancel-action: 0; + focus-content => { + keys.focus(); + } + action(i) => { + if i == 1 { + if root.selected >= 0 { + root.chosen(root.selected, root.as-default); + } + } else { + root.chosen(-1, false); + } + } + + keys := FocusScope { + key-pressed(event) => { + if event.text == Key.UpArrow && root.selected > 0 { + root.selected -= 1; + return accept; + } + if event.text == Key.DownArrow && root.selected < root.apps.length - 1 { + root.selected += 1; + return accept; + } + reject + } + + height: 288px; + + if root.apps.length == 0: Text { + text: "No applications are installed for this kind of file."; + color: Theme.on-surface-variant; + font-size: Theme.body-medium.size; + wrap: word-wrap; + } + + ListView { + for app[i] in root.apps: VerticalLayout { + if app.section != "": Text { + height: 32px; + text: app.section; + color: Theme.primary; + font-size: Theme.label-medium.size; + font-weight: Theme.label-medium.weight; + vertical-alignment: bottom; + horizontal-alignment: left; + } + + StateLayer { + height: 48px; + border-radius: Theme.corner-full(self.height); + focusable: false; + ring-offset: -Theme.focus-ring-width; + accessible-role: list-item; + accessible-label: app.name; + accessible-item-selectable: true; + accessible-item-selected: i == root.selected; + clicked => { + root.selected = i; + } + double-clicked => { + root.selected = i; + root.chosen(i, root.as-default); + } + + Rectangle { + border-radius: parent.border-radius; + background: Theme.secondary-container; + opacity: i == root.selected ? 1 : 0; + animate opacity { + duration: Motion.time(Motion.short4); + easing: Motion.standard; + } + } + + HorizontalLayout { + padding-left: Theme.space-4; + padding-right: Theme.space-4; + spacing: Theme.space-3; + + VerticalLayout { + alignment: center; + + if app.has-icon: Image { + source: app.icon; + width: 32px; + height: 32px; + } + + if !app.has-icon: Icon { + glyph: "\u{e5c3}"; + size: 32px; + } + } + + Text { + horizontal-stretch: 1; + text: app.name; + color: i == root.selected ? Theme.on-secondary-container : Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + overflow: elide; + } + + if app.is-default: Text { + text: "Default"; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + vertical-alignment: center; + } + } + } + } + } + } + + HorizontalLayout { + spacing: Theme.space-3; + + Switch { + checked <=> root.as-default; + accessible-label: "Always open this kind of file with the selected application"; + } + + Text { + horizontal-stretch: 1; + text: "Always use for " + root.mime; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + overflow: elide; + } + } +} diff --git a/crates/tunal/ui/dialogs/properties.slint b/crates/tunal/ui/dialogs/properties.slint new file mode 100644 index 0000000..c74f5e5 --- /dev/null +++ b/crates/tunal/ui/dialogs/properties.slint @@ -0,0 +1,176 @@ +import { ListView } from "std-widgets.slint"; +import { Theme } from "../theme.slint"; +import { Icon, Icons } from "../components/icon.slint"; +import { Dialog } from "../components/dialog.slint"; +import { ButtonKind } from "../components/button.slint"; + +export struct PropRow { + label: string, + value: string, +} + +// What the Properties dialog shows, formatted by Rust. `perms` holds nine flags (owner, +// group, others × read, write, execute) when `has-perms`. +export struct PropertiesInfo { + title: string, + glyph: string, + rows: [PropRow], + size: string, + contents: string, + scanning: bool, + has-perms: bool, + perms: [bool], + perm-text: string, +} + +component Line inherits HorizontalLayout { + in property label; + in property value; + + spacing: Theme.space-4; + height: 20px; + + Text { + width: 88px; + text: root.label; + color: Theme.on-surface-variant; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + } + + Text { + horizontal-stretch: 1; + text: root.value; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + overflow: elide; + } +} + +// One cell of the permission grid: a check when granted, a dash when not. +component Flag inherits Rectangle { + in property on; + + width: 56px; + height: 20px; + + if root.on: Icon { + glyph: Icons.check; + size: 18px; + color: Theme.primary; + } + + if !root.on: Rectangle { + width: 8px; + height: 2px; + border-radius: 1px; + background: Theme.outline-variant; + } +} + +component PermissionRow inherits HorizontalLayout { + in property who; + in property <[bool]> perms; + in property first; + + spacing: Theme.space-2; + height: 20px; + + Text { + width: 96px; + text: root.who; + color: Theme.on-surface-variant; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + } + + for i in 3: Flag { + on: root.first + i < root.perms.length && root.perms[root.first + i]; + } +} + +// Read-only facts about the selection; the folder size is counted in the background and +// `info.scanning` shows while it grows. +export component PropertiesDialog inherits Dialog { + in property info; + callback closed(); + + title: root.info.title; + dialog-width: 440px; + actions: [{ text: "Close", kind: ButtonKind.filled }]; + default-action: 0; + cancel-action: 0; + action(i) => { + root.closed(); + } + + VerticalLayout { + spacing: Theme.space-2; + + for row in root.info.rows: Line { + label: row.label; + value: row.value; + } + + Line { + label: "Size"; + value: root.info.size; + } + + if root.info.contents != "": Line { + label: "Contains"; + value: root.info.contents; + } + + if root.info.has-perms: VerticalLayout { + spacing: Theme.space-1; + padding-top: Theme.space-2; + + Text { + text: "Permissions " + root.info.perm-text; + color: Theme.primary; + font-size: Theme.label-medium.size; + font-weight: Theme.label-medium.weight; + } + + HorizontalLayout { + spacing: Theme.space-2; + + Rectangle { + width: 96px; + } + + for name in ["Read", "Write", "Run"]: Text { + width: 56px; + text: name; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + horizontal-alignment: center; + } + } + + PermissionRow { + who: "Owner"; + perms: root.info.perms; + first: 0; + } + + PermissionRow { + who: "Group"; + perms: root.info.perms; + first: 3; + } + + PermissionRow { + who: "Others"; + perms: root.info.perms; + first: 6; + } + } + } +} diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 492bdaa..8579921 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -122,5 +122,11 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: sidebar place menu still its own fixed list (Open in new tab, bookmark edit). No live drag run (pointer drag, motion); clippy not clean until S012 lands. `TUNAL_SETTINGS=` opens the dialog in a screenshot. Shared files `actions.rs`, `app.slint`, `main.rs`, `shell/mod.rs` hold S012 hunks too: left uncommitted here. - Later: autoscroll while dragging in a long menu; Previews page (S018); sidebar menu from the model. +## S012 — Properties, Open and Open with +- Done: `properties.rs` (`Properties::show(uris)`; `gather` thread: stat, then recursive count with live updates every 100 ms, cancelled when the dialog closes; type, location, link target, dates (accessed/created for local files), owner/group from /etc/passwd + /etc/group, `rwx` text + 3×3 grid, multi-selection summary; empty-area menu = the folder). `open.rs`: `open(path, done)` = portal `OpenURI.OpenFile` (zbus, fd) then `xdg-open` (no shell); `Opener` (Enter/double-click on a file via `FolderModel::activate` → `Option`, actions `open`, `open-with`). `desktop_apps.rs`: `.desktop` scan (XDG dirs, ids, localized Name), `mimeapps.list` (defaults/added/removed, all XDG files), `Apps::choices(mime)`, `set_default` (atomic, keeps other lines), `split_exec` + `command_lines` (%f %F %u %U %i %c %k %%, one launch per file when no list code), `launch` (detached, no shell, `Terminal=true` via `xdg-terminal-exec`), `IconTheme::load().find(name, size)` (gtk theme + Inherits + hicolor + pixmaps; **S015 reuses this**). Dialogs `dialogs/{properties,open-with}.slint`; actions `open`, `open-with`, `properties` (no shortcuts) in the registry and S013's default menus. +- Verified: workspace build, clippy -D warnings, fmt --check; screenshots (temporary hook, removed): properties for a file (light) and a folder (dark, count 2 files/2 folders, 298 KiB), Open with for a text file (icons from theme, svg ok); temporary test (removed): Exec splitting/expansion for %f, %U, one launch per file, `set_default` on an empty and an existing mimeapps.list in a scratch `XDG_CONFIG_HOME`. +- Not done: no live window (double-click open, portal call, a real launch); Alt+Enter shortcut; mixed file+folder selection with Open sends folders to the portal. +- Later: properties editing (permissions, owner); open folders in new tabs; Alt+Enter; icons loaded lazily for long lists. + ## Later -