menu: new context actions, executables dialog, own default-app lookup

Terminal, open in tab/split, create new, duplicate, add to places, copy/move
to, other pane, compress, extract, invert selection; entries with a missing
tool are hidden, Play only for audio. Run / Run in terminal and an Ask dialog
for executables; default apps resolved from desktop entries, else Open with.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-19 10:51:00 -06:00
commit 5e42b203f8
10 changed files with 1347 additions and 195 deletions

View file

@ -34,6 +34,8 @@ pub enum JobKind {
Restore(Vec<Uri>),
EmptyTrash,
Mkdir(Uri),
/// Creates an empty file; fails if the name is taken.
CreateFile(Uri),
Rename {
from: Uri,
to: Uri,
@ -48,7 +50,10 @@ pub enum JobKind {
impl JobKind {
/// Single quick calls that should not wait behind a long copy.
fn is_quick(&self) -> bool {
matches!(self, Self::Mkdir(_) | Self::Rename { .. })
matches!(
self,
Self::Mkdir(_) | Self::CreateFile(_) | Self::Rename { .. }
)
}
}

View file

@ -135,6 +135,17 @@ impl Runner<'_> {
}
self.file_done();
}
JobKind::CreateFile(uri) => {
self.progress.total_files = 1;
self.set_phase(Phase::Running);
self.step(uri);
if let Some(backend) = self.backend(uri)? {
self.attempt(uri, |_| {
backend.open_write(uri, WriteMode::CreateNew).map(drop)
})?;
}
self.file_done();
}
JobKind::Rename { from, to } => {
self.progress.total_files = 1;
self.set_phase(Phase::Running);

View file

@ -1,26 +1,32 @@
//! File actions: one registry (id, label, glyph, shortcut, when enabled) behind the toolbar
//! File actions: one registry (id, label, glyph, when shown and enabled) behind the toolbar
//! menu, the keyboard and the context menu, plus the internal clipboard and what each action
//! does. Long work goes to the jobs bridge.
//! does. Long work goes to the jobs bridge. Shortcuts come from the keymap (`keymap.rs`):
//! an action whose id is a command id runs on that command's keys.
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::ffi::OsString;
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::rc::{Rc, Weak};
use slint::platform::Key;
use slint::{ComponentHandle, Model, ModelRc, VecModel};
use tunal_core::ops::{self, JobKind};
use tunal_core::{Locations, Uri};
use tunal_core::{Entry, Kind, Locations, Uri};
use crate::clipboard;
use crate::config::Executables;
use crate::folder::appearance::Appearance;
use crate::jobs_bridge::Bridge;
use crate::menus::{Context as MenuContext, Menus};
use crate::keymap::Command;
use crate::menus::{self, Context as MenuContext, Menus};
use crate::open::Opener;
use crate::player_bridge::{self, PlayerUi};
use crate::properties::Properties;
use crate::shell::Shell;
use crate::shell::pane::Pane;
use crate::tags_bridge::{self, Tags};
use crate::{MainWindow, MenuEntry, MenuItem};
use crate::tools::{self, Executable, Format};
use crate::{ButtonKind, DialogAction, MainWindow, MenuEntry, MenuItem};
/// Every action, by stable id (the context menu editor refers to these).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@ -37,23 +43,38 @@ pub enum Action {
EmptyTrash,
Settings,
Open,
OpenInNewTab,
OpenInSplit,
OpenWith,
Run,
RunInTerminal,
Terminal,
Properties,
Appearance,
EditTags,
Play,
/// Submenu: a folder, a text file or an empty file.
CreateNew,
Duplicate,
AddToPlaces,
/// Submenus over the other pane, home and the bookmarks.
CopyTo,
MoveTo,
CopyToOtherPane,
MoveToOtherPane,
/// Submenu over the archive formats.
Compress,
ExtractHere,
ExtractTo,
SelectAll,
InvertSelection,
/// Submenus over the pane's sort and view settings.
SortBy,
ViewMode,
}
enum Shortcut {
Char(char),
Key(Key),
}
impl Action {
pub const ALL: [Action; 19] = [
pub const ALL: [Action; 36] = [
Self::Cut,
Self::Copy,
Self::Paste,
@ -66,11 +87,28 @@ impl Action {
Self::EmptyTrash,
Self::Settings,
Self::Open,
Self::OpenInNewTab,
Self::OpenInSplit,
Self::OpenWith,
Self::Run,
Self::RunInTerminal,
Self::Terminal,
Self::Properties,
Self::Appearance,
Self::EditTags,
Self::Play,
Self::CreateNew,
Self::Duplicate,
Self::AddToPlaces,
Self::CopyTo,
Self::MoveTo,
Self::CopyToOtherPane,
Self::MoveToOtherPane,
Self::Compress,
Self::ExtractHere,
Self::ExtractTo,
Self::SelectAll,
Self::InvertSelection,
Self::SortBy,
Self::ViewMode,
];
@ -89,11 +127,28 @@ impl Action {
Self::EmptyTrash => "empty-trash",
Self::Settings => "settings",
Self::Open => "open",
Self::OpenInNewTab => "open-new-tab",
Self::OpenInSplit => "open-split",
Self::OpenWith => "open-with",
Self::Run => "run",
Self::RunInTerminal => "run-in-terminal",
Self::Terminal => "terminal",
Self::Properties => "properties",
Self::Appearance => "appearance",
Self::EditTags => "edit-tags",
Self::Play => "play",
Self::CreateNew => "create-new",
Self::Duplicate => "duplicate",
Self::AddToPlaces => "add-to-places",
Self::CopyTo => "copy-to",
Self::MoveTo => "move-to",
Self::CopyToOtherPane => "copy-to-other-pane",
Self::MoveToOtherPane => "move-to-other-pane",
Self::Compress => "compress",
Self::ExtractHere => "extract-here",
Self::ExtractTo => "extract-to-folder",
Self::SelectAll => "select-all",
Self::InvertSelection => "invert-selection",
Self::SortBy => "sort-by",
Self::ViewMode => "view-mode",
}
@ -117,11 +172,28 @@ impl Action {
Self::EmptyTrash => "Empty Trash",
Self::Settings => "Settings",
Self::Open => "Open",
Self::OpenInNewTab => "Open in new tab",
Self::OpenInSplit => "Open in split view",
Self::OpenWith => "Open with…",
Self::Run => "Run",
Self::RunInTerminal => "Run in terminal",
Self::Terminal => "Open terminal here",
Self::Properties => "Properties",
Self::Appearance => "Folder appearance…",
Self::EditTags => "Edit tags…",
Self::Play => "Play",
Self::CreateNew => "Create new",
Self::Duplicate => "Duplicate here",
Self::AddToPlaces => "Add to places",
Self::CopyTo => "Copy to",
Self::MoveTo => "Move to",
Self::CopyToOtherPane => "Copy to the other pane",
Self::MoveToOtherPane => "Move to the other pane",
Self::Compress => "Compress",
Self::ExtractHere => "Extract here",
Self::ExtractTo => "Extract to a folder",
Self::SelectAll => "Select all",
Self::InvertSelection => "Invert selection",
Self::SortBy => "Sort by",
Self::ViewMode => "View mode",
}
@ -142,94 +214,74 @@ impl Action {
Self::EmptyTrash => "\u{e16c}",
Self::Settings => "\u{e8b8}",
Self::Open => "\u{e89e}",
Self::OpenInNewTab => "\u{e8d8}",
Self::OpenInSplit => "\u{e949}",
Self::OpenWith => "\u{e5c3}",
Self::Run => "\u{eb9b}",
Self::RunInTerminal | Self::Terminal => "\u{eb8e}",
Self::Properties => "\u{e88e}",
Self::Appearance => "\u{e40a}",
Self::EditTags => "\u{e892}",
Self::Play => "\u{e037}",
Self::CreateNew => "\u{e89c}",
Self::Duplicate => "\u{e173}",
Self::AddToPlaces => "\u{e598}",
Self::CopyTo | Self::CopyToOtherPane => "\u{e14d}",
Self::MoveTo | Self::MoveToOtherPane => "\u{e9a1}",
Self::Compress => "\u{eb2c}",
Self::ExtractHere | Self::ExtractTo => "\u{e169}",
Self::SelectAll => "\u{e162}",
Self::InvertSelection => "\u{e3e8}",
Self::SortBy => "\u{e164}",
Self::ViewMode => "\u{e9b0}",
}
}
/// `(key, shift)`; every shortcut but F2, Delete and Space holds Ctrl.
fn shortcut(self) -> Option<(Shortcut, bool)> {
Some(match self {
Self::Cut => (Shortcut::Char('x'), false),
Self::Copy => (Shortcut::Char('c'), false),
Self::Paste => (Shortcut::Char('v'), false),
Self::CopyPath => (Shortcut::Char('c'), true),
Self::Rename => (Shortcut::Key(Key::F2), false),
Self::NewFolder => (Shortcut::Char('n'), true),
Self::Trash => (Shortcut::Key(Key::Delete), false),
Self::Delete => (Shortcut::Key(Key::Delete), true),
Self::Settings => (Shortcut::Char(','), false),
Self::Play => (Shortcut::Key(Key::Space), false),
Self::Restore
| Self::EmptyTrash
| Self::Open
| Self::OpenWith
| Self::Properties
| Self::Appearance
| Self::EditTags
| Self::SortBy
| Self::ViewMode => {
return None;
}
})
}
pub fn shortcut_text(self) -> String {
match self.shortcut() {
None => String::new(),
Some((Shortcut::Char(c), shift)) => {
format!(
"Ctrl+{}{}",
if shift { "Shift+" } else { "" },
c.to_ascii_uppercase()
)
}
Some((Shortcut::Key(key), shift)) => {
let name = match key {
Key::F2 => "F2",
Key::Space => "Space",
_ => "Del",
};
format!("{}{name}", if shift { "Shift+" } else { "" })
/// Whether the action is in a menu at all here (hidden, not greyed out): what the
/// selection is and which tools are installed decide.
pub fn shown(self, ctx: &Context) -> bool {
match self {
Self::Play => ctx.audio,
Self::Run => ctx.executable,
Self::RunInTerminal => ctx.executable && tools::terminal().is_some(),
Self::Terminal => ctx.local && tools::terminal().is_some(),
Self::OpenInNewTab | Self::OpenInSplit => ctx.folders,
Self::CopyToOtherPane | Self::MoveToOtherPane => ctx.split,
Self::Compress => {
ctx.local && ctx.selected > 0 && Format::ALL.into_iter().any(tools::can_compress)
}
Self::ExtractHere | Self::ExtractTo => ctx.archives,
_ => true,
}
}
fn matches(self, text: &str, ctrl: bool, shift: bool) -> bool {
let Some((key, wants_shift)) = self.shortcut() else {
return false;
};
let (wants_ctrl, hit) = match key {
Shortcut::Char(c) => (true, text.eq_ignore_ascii_case(c.encode_utf8(&mut [0; 4]))),
Shortcut::Key(key) => (false, text == String::from(char::from(key))),
};
hit && ctrl == wants_ctrl && shift == wants_shift
}
pub fn enabled(self, ctx: &Context) -> bool {
let files = !ctx.in_trash;
let some = ctx.selected > 0;
match self {
Self::Cut => files && ctx.selected > 0 && ctx.writable,
Self::Copy => ctx.selected > 0,
Self::Cut | Self::MoveTo | Self::MoveToOtherPane => files && some && ctx.writable,
Self::Copy => some,
Self::CopyTo | Self::CopyToOtherPane => files && some,
Self::Paste => files && ctx.paste && ctx.writable,
Self::CopyPath => true,
Self::Rename => files && ctx.selected == 1 && ctx.writable,
Self::NewFolder => files && ctx.writable,
Self::Trash => files && ctx.selected > 0 && ctx.can_trash,
Self::Delete => ctx.selected > 0 && (ctx.writable || ctx.in_trash),
Self::Restore => ctx.in_trash && ctx.selected > 0,
Self::NewFolder | Self::CreateNew => files && ctx.writable,
Self::Duplicate | Self::Compress => files && some && ctx.writable,
Self::ExtractHere | Self::ExtractTo => files && ctx.archives && ctx.writable,
Self::Trash => files && some && ctx.can_trash,
Self::Delete => some && (ctx.writable || ctx.in_trash),
Self::Restore => ctx.in_trash && some,
Self::EmptyTrash => ctx.in_trash,
Self::Settings => true,
Self::Open | Self::OpenWith => files && ctx.selected > 0,
Self::Settings | Self::SelectAll | Self::InvertSelection => true,
Self::Open | Self::OpenWith => files && some,
Self::OpenInNewTab | Self::OpenInSplit => files && ctx.folders,
Self::Run | Self::RunInTerminal => ctx.executable,
Self::Terminal => ctx.local,
Self::AddToPlaces => files,
Self::Properties | Self::SortBy | Self::ViewMode => true,
Self::Appearance => files && ctx.selected <= 1,
Self::EditTags => files && ctx.taggable,
Self::Play => files && ctx.playable,
Self::Play => files && ctx.audio,
}
}
}
@ -245,8 +297,32 @@ pub struct Context {
pub paste: bool,
/// Every selected entry is a local audio file whose tags can be written.
pub taggable: bool,
/// Every selected entry is a local audio or video file (video plays its sound).
pub playable: bool,
/// Every selected entry is a local audio file (Play; a video plays only when asked).
pub audio: bool,
/// One local executable file is selected.
pub executable: bool,
/// Every selected entry is a folder.
pub folders: bool,
/// The folder shown is on this computer (terminal, archives).
pub local: bool,
/// Every selected entry is a local archive a tool here unpacks.
pub archives: bool,
/// The tab is split: the other pane is a target.
pub split: bool,
}
/// What a local executable is, from its entry in `dir`.
fn executable(dir: &Uri, entry: &Entry) -> Option<Executable> {
let link = match &entry.kind {
Kind::File => false,
Kind::Symlink {
target_type: Some(tunal_core::FileType::File),
..
} => true,
_ => return None,
};
let path = dir.join(&entry.name).to_path()?;
tools::executable(&path, entry.mime, entry.mode, link)
}
#[derive(Default)]
@ -264,6 +340,10 @@ pub struct Actions {
clipboard: RefCell<Clipboard>,
/// The actions of the open context menu, by item (separators are `None`).
menu: RefCell<Vec<Option<Action>>>,
/// What the open context menu was opened on, while one of its items runs.
menu_context: Cell<Option<MenuContext>>,
/// The folders of the open menu's Copy to and Move to submenus.
targets: RefCell<Vec<Uri>>,
/// The layout of every context menu (`menus.toml`).
menus: RefCell<Menus>,
opener: Rc<Opener>,
@ -279,6 +359,13 @@ impl Actions {
self.bridge.notify(message);
}
/// A toast for what went wrong, if something did.
fn report(&self, result: Result<(), String>) {
if let Err(message) = result {
self.bridge.notify(message);
}
}
pub fn attach(ui: &MainWindow, shell: &Rc<Shell>, locations: Locations) -> Rc<Self> {
let bridge = Bridge::attach(ui, locations.clone());
let opener = Opener::attach(ui, locations.clone(), bridge.clone());
@ -294,6 +381,8 @@ impl Actions {
bridge,
clipboard: RefCell::new(Clipboard::default()),
menu: RefCell::new(Vec::new()),
menu_context: Cell::new(None),
targets: RefCell::new(Vec::new()),
menus: RefCell::new(Menus::load()),
opener,
properties,
@ -341,6 +430,11 @@ impl Actions {
self.bridge.submit(kind);
}
/// True while a dialog of the jobs bridge is open: shortcuts stay quiet.
pub fn modal(&self) -> bool {
self.bridge.modal()
}
/// The items on the clipboard to be moved.
pub fn cut_uris(&self) -> Vec<Uri> {
let clipboard = self.clipboard.borrow();
@ -355,19 +449,45 @@ impl Actions {
self.shell.upgrade()
}
/// The first key of the command with the action's id, for menus.
pub fn shortcut_text(&self, action: Action) -> String {
match (Command::from_id(action.id()), self.shell()) {
(Some(cmd), Some(shell)) => shell.keymap().first(cmd),
_ => String::new(),
}
}
fn context(&self, pane: &Pane) -> Context {
let caps = pane
.dir()
.and_then(|d| self.locations.resolve(&d).ok())
let dir = pane.dir();
let caps = dir
.as_ref()
.and_then(|d| self.locations.resolve(d).ok())
.map(|l| l.capabilities())
.unwrap_or_default();
let selected = pane.model.selected_uris();
let files = !selected.is_empty() && !pane.model.selection_is_dir();
let entries = pane.model.selected_entries();
let folders = !selected.is_empty() && pane.model.selection_is_dir();
let files = !selected.is_empty() && !folders;
let local = dir.as_ref().is_some_and(|d| d.to_path().is_some());
Context {
taggable: files && selected.iter().all(tags_bridge::can_tag),
playable: files && selected.iter().all(player_bridge::can_play),
audio: files && selected.iter().all(player_bridge::is_audio),
executable: match (entries.as_slice(), &dir) {
([only], Some(dir)) => executable(dir, only).is_some(),
_ => false,
},
archives: local
&& !entries.is_empty()
&& entries
.iter()
.all(|e| !e.kind.is_dir() && tools::can_extract(&e.name)),
folders,
local,
split: self.shell().is_some_and(|s| s.other_pane().is_some()),
selected: selected.len(),
in_trash: pane.dir().is_some_and(|d| d.scheme() == tunal_core::TRASH),
in_trash: dir
.as_ref()
.is_some_and(|d| d.scheme() == tunal_core::TRASH),
writable: caps.write,
can_trash: caps.trash,
paste: !self.clipboard.borrow().uris.is_empty() || clipboard::has_foreign(),
@ -410,26 +530,76 @@ impl Actions {
menus.save();
}
/// Copy to and Move to: the other pane's folder, home, then the bookmarks, without the
/// folder shown.
fn target_entries(&self, pane: &Pane) -> Vec<MenuEntry> {
let Some(shell) = self.shell() else {
return Vec::new();
};
let here = pane.dir();
let mut targets: Vec<(String, &'static str, Uri)> = Vec::new();
if let Some(dir) = shell.other_pane().and_then(|p| p.dir()) {
let (name, _) = shell.title_of(&dir);
targets.push((format!("Other pane: {name}"), "\u{e949}", dir));
}
let home = Uri::from_path(&crate::shell::places::home());
targets.push(("Home".into(), "\u{e88a}", home));
for (name, uri) in shell.bookmarks() {
targets.push((name, "\u{e866}", uri));
}
let mut seen = Vec::new();
targets.retain(|(_, _, uri)| {
let keep = Some(uri) != here.as_ref() && !seen.contains(uri);
seen.push(uri.clone());
keep
});
*self.targets.borrow_mut() = targets.iter().map(|(_, _, u)| u.clone()).collect();
targets
.into_iter()
.map(|(text, icon, _)| entry(&text, icon, false))
.collect()
}
fn submenu(&self, action: Action, pane: &Pane) -> Vec<MenuEntry> {
match action {
Action::SortBy => pane.model.sort_submenu(),
Action::ViewMode => pane.model.view_menu(),
Action::CreateNew => vec![
entry("Folder", Action::NewFolder.glyph(), false),
entry("Text file", "\u{f1c6}", false),
entry("Empty file", "\u{e873}", false),
],
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)))
.collect(),
_ => Vec::new(),
}
}
fn menu_items(&self, pane: &Pane, over: bool) -> Vec<MenuItem> {
let ctx = self.context(pane);
let layout = self
.menus
.borrow()
.layout(self.menu_context(pane, &ctx, over));
let menu_ctx = self.menu_context(pane, &ctx, over);
self.menu_context.set(Some(menu_ctx));
let layout = menus::tidy(
self.menus
.borrow()
.layout(menu_ctx)
.into_iter()
.filter(|a| a.is_none_or(|a| a.shown(&ctx)))
.collect(),
);
let items = layout
.iter()
.map(|entry| match entry {
Some(action) => MenuItem {
text: action.label().into(),
icon: action.glyph().into(),
shortcut: action.shortcut_text().into(),
shortcut: self.shortcut_text(*action).into(),
disabled: !action.enabled(&ctx),
separator: false,
submenu: ModelRc::new(VecModel::from(match action {
Action::SortBy => pane.model.sort_submenu(),
Action::ViewMode => pane.model.view_menu(),
_ => Vec::new(),
})),
submenu: ModelRc::new(VecModel::from(self.submenu(*action, pane))),
},
None => MenuItem {
text: Default::default(),
@ -474,41 +644,138 @@ impl Actions {
fn menu_activated(&self, index: usize, sub: i32) {
let action = self.menu.borrow().get(index).copied().flatten();
let pane = self.shell().and_then(|s| s.active());
match (action, usize::try_from(sub), pane) {
(Some(Action::SortBy), Ok(sub), Some(pane)) => pane.model.sort_menu_activated(sub, -1),
(Some(Action::ViewMode), Ok(sub), Some(pane)) => pane.model.view_menu_activated(sub),
(Some(action), _, _) => self.run(action),
_ => {}
let (Some(action), Some(pane)) = (action, pane) else {
return;
};
match (action, usize::try_from(sub)) {
(Action::SortBy, Ok(sub)) => pane.model.sort_menu_activated(sub, -1),
(Action::ViewMode, Ok(sub)) => pane.model.view_menu_activated(sub),
(Action::CreateNew, Ok(sub)) => {
if let Some(dir) = pane.dir() {
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"),
}
}
}
(Action::CopyTo | Action::MoveTo, Ok(sub)) => {
let dest = self.targets.borrow().get(sub).cloned();
if let Some(dest) = dest {
self.transfer(pane.model.selected_uris(), dest, action == Action::MoveTo);
}
}
(Action::Compress, Ok(sub)) => {
if let Some(&format) = Format::ALL.get(sub) {
self.compress(&pane, format);
}
}
// A submenu's own row does nothing.
(_, Ok(_)) => {}
(action, Err(_)) => {
if !matches!(
action,
Action::CreateNew | Action::CopyTo | Action::MoveTo | Action::Compress
) {
self.run(action);
}
}
}
self.menu_context.set(None);
}
/// A key the window saw: true when it was an enabled action's shortcut.
pub fn key(&self, text: &str, ctrl: bool, shift: bool, alt: bool) -> bool {
if alt || self.bridge.modal() {
return false;
}
/// A shortcut: runs `action` when it applies to the active pane now. False when it
/// doesn't, so the key goes on to the view.
pub fn run_enabled(&self, action: Action) -> bool {
let Some(pane) = self.shell().and_then(|s| s.active()) else {
return false;
};
if pane.model.editing().is_some() {
let ctx = self.context(&pane);
if !action.shown(&ctx) || !action.enabled(&ctx) {
return false;
}
let ctx = self.context(&pane);
let Some(action) = Action::ALL
.into_iter()
.find(|a| a.matches(text, ctrl, shift) && a.enabled(&ctx))
else {
return false;
};
self.run(action);
true
}
// ---- actions ------------------------------------------------------------------------
/// Enter or double-click on a file.
pub fn open_file(&self, uri: Uri) {
self.opener.open(&uri);
/// Enter or double-click on a file of `pane`: an executable asks first (or runs, or
/// opens, as the setting says); anything else opens in its application.
pub fn open_file(&self, pane: &Pane, uri: Uri) {
let kind = uri
.file_name()
.and_then(|name| pane.model.entry(name))
.zip(pane.dir())
.and_then(|(entry, dir)| executable(&dir, &entry));
let (Some(kind), Some(path)) = (kind, uri.to_path()) else {
self.opener.open(&uri);
return;
};
let setting = self
.shell()
.map_or(Executables::Ask, |s| s.prefs().executables);
match setting {
Executables::Run => self.report(tools::run(&path)),
Executables::Open => self.opener.open(&uri),
Executables::Ask => self.ask_run(uri, path, kind),
}
}
/// "Run “name”?" with Run, Run in terminal, Open (scripts) and Cancel.
fn ask_run(&self, uri: Uri, path: PathBuf, kind: Executable) {
#[derive(Clone, Copy)]
enum Choice {
Cancel,
Open,
Terminal,
Run,
}
let button = |text: &str, kind: ButtonKind| DialogAction {
text: text.into(),
kind,
};
let mut choices = vec![(button("Cancel", ButtonKind::Text), Choice::Cancel)];
if kind == Executable::Script {
choices.push((button("Open", ButtonKind::Text), Choice::Open));
}
if tools::terminal().is_some() {
choices.push((
button("Run in terminal", ButtonKind::Text),
Choice::Terminal,
));
}
choices.push((button("Run", ButtonKind::Filled), Choice::Run));
let name = uri
.file_name()
.map(tunal_core::display_name)
.unwrap_or_default();
let body = match kind {
Executable::Script => "This is a script. Run it as a program, or open it to read it.",
Executable::Program => {
"This is a program. Run it only if you trust where it came from."
}
};
let (actions, picks): (Vec<_>, Vec<_>) = choices.into_iter().unzip();
let me = self.me.clone();
self.bridge.ask(
Action::Run.glyph(),
&format!("Run “{name}”?"),
body,
actions,
0,
move |i| {
let Some(me) = me.upgrade() else {
return;
};
match picks.get(i).copied().unwrap_or(Choice::Cancel) {
Choice::Cancel => {}
Choice::Open => me.opener.open_with(vec![uri]),
Choice::Terminal => me.report(tools::run_in_terminal(&path)),
Choice::Run => me.report(tools::run(&path)),
}
},
);
}
pub fn run(&self, action: Action) {
@ -522,6 +789,9 @@ impl Actions {
return;
};
let uris = pane.model.selected_uris();
// Folder-menu items act on the selected folder; keys and the empty-area menu on the
// folder shown.
let on_folder = self.menu_context.get() == Some(MenuContext::Folder);
match action {
Action::Copy => self.set_clipboard(&shell, uris, false),
Action::Cut => self.set_clipboard(&shell, uris, true),
@ -559,13 +829,70 @@ impl Actions {
&& 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);
} else if !pane.model.selection_is_dir() {
for uri in uris {
self.open_file(&pane, uri);
}
}
}
Action::OpenInNewTab => {
for uri in uris {
shell.open_at(uri, true);
}
return;
}
Action::OpenInSplit => {
if let Some(uri) = uris.into_iter().next() {
shell.open_in_other_pane(uri);
}
return;
}
Action::OpenWith => self.opener.open_with(uris),
Action::Run | Action::RunInTerminal => {
if let Some(path) = uris.first().and_then(|u| u.to_path()) {
self.report(if action == Action::Run {
tools::run(&path)
} else {
tools::run_in_terminal(&path)
});
}
}
Action::Terminal => {
let target = match uris.as_slice() {
[only] if on_folder => only.clone(),
_ => dir,
};
if let Some(path) = target.to_path() {
self.report(tools::open_terminal(&path));
}
}
Action::Duplicate => self.bridge.submit(JobKind::Copy {
sources: uris,
dest: dir,
}),
Action::AddToPlaces => {
let folders = if on_folder || (pane.model.selection_is_dir() && !uris.is_empty()) {
uris
} else {
vec![dir]
};
shell.add_bookmarks(&folders);
self.bridge.notify(if folders.len() == 1 {
"Added to places".to_string()
} else {
format!("{} folders added to places", folders.len())
});
}
Action::CopyToOtherPane | Action::MoveToOtherPane => {
if let Some(dest) = shell.other_pane().and_then(|p| p.dir()) {
self.transfer(uris, dest, action == Action::MoveToOtherPane);
}
}
Action::ExtractHere | Action::ExtractTo => {
self.extract(&pane, action == Action::ExtractTo);
}
Action::SelectAll => pane.model.select_all(),
Action::InvertSelection => pane.model.invert_selection(),
Action::Properties => {
self.properties
.show(if uris.is_empty() { vec![dir] } else { uris });
@ -596,12 +923,12 @@ impl Actions {
return;
}
Action::Play => {
// The folder's playable files queue up after the first one chosen.
// The folder's audio files queue up after the first one chosen.
let queue: Vec<_> = pane
.model
.shown_files()
.iter()
.filter(|u| player_bridge::can_play(u))
.filter(|u| player_bridge::is_audio(u))
.filter_map(|u| u.to_path())
.collect();
if let Some(first) = uris.first().and_then(|u| u.to_path()) {
@ -615,7 +942,12 @@ impl Actions {
return;
}
// Only submenus: their entries run in `menu_activated`.
Action::SortBy | Action::ViewMode => return,
Action::SortBy
| Action::ViewMode
| Action::CreateNew
| Action::CopyTo
| Action::MoveTo
| Action::Compress => return,
Action::EmptyTrash => {
let me = self.me.clone();
self.bridge.confirm(
@ -654,17 +986,18 @@ impl Actions {
}
}
/// Pastes the clipboard into the folder of the active pane (middle click on empty space).
pub fn paste_here(&self) {
let _ = self.run_enabled(Action::Paste);
}
fn paste(&self, shell: &Shell, dest: Uri) {
// Files another app copied since ours win.
let me = self.me.clone();
let to = dest.clone();
if clipboard::paste_foreign(move |sources, cut| {
if let Some(me) = me.upgrade() {
me.bridge.submit(if cut {
JobKind::Move { sources, dest: to }
} else {
JobKind::Copy { sources, dest: to }
});
me.transfer(sources, to, cut);
}
}) {
return;
@ -679,10 +1012,20 @@ impl Actions {
if cut {
*self.clipboard.borrow_mut() = Clipboard::default();
self.show_cut(shell);
self.bridge.submit(JobKind::Move { sources, dest });
} else {
self.bridge.submit(JobKind::Copy { sources, dest });
}
self.transfer(sources, dest, cut);
}
/// Copies or moves `sources` into the folder `dest`.
fn transfer(&self, sources: Vec<Uri>, dest: Uri, mv: bool) {
if sources.is_empty() {
return;
}
self.bridge.submit(if mv {
JobKind::Move { sources, dest }
} else {
JobKind::Copy { sources, dest }
});
}
/// The selected paths (or the folder's) as text, one per line.
@ -706,18 +1049,119 @@ impl Actions {
});
}
/// Makes `New folder` (numbered when taken) and starts editing its name once it shows.
fn new_folder(&self, pane: &Pane, dir: Uri) {
let mut name = b"New folder".to_vec();
/// `base`, numbered (`base (2)`) until no entry of `pane` has the name.
fn free_name(pane: &Pane, base: &[u8]) -> Vec<u8> {
let mut name = base.to_vec();
let mut n = 2;
while pane.model.has_name(&name) {
name = ops::numbered(b"New folder", n);
name = ops::numbered(base, n);
n += 1;
}
name
}
/// Makes `New folder` (numbered when taken) and starts editing its name once it shows.
pub fn new_folder(&self, pane: &Pane, dir: Uri) {
let name = Self::free_name(pane, b"New folder");
pane.model.select_when_shown(name.clone(), true);
self.bridge.submit(JobKind::Mkdir(dir.join(&name)));
}
/// Makes an empty file named `base` (numbered when taken) and edits its name once it
/// shows. The job refuses a name that appeared in the meantime.
fn new_file(&self, pane: &Pane, dir: Uri, base: &[u8]) {
let name = Self::free_name(pane, base);
pane.model.select_when_shown(name.clone(), true);
self.bridge.submit(JobKind::CreateFile(dir.join(&name)));
}
/// 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) {
let (Some(dir), uris) = (pane.dir(), pane.model.selected_uris()) else {
return;
};
let Some(dir_path) = dir.to_path() else {
return;
};
let names: Vec<OsString> = uris
.iter()
.filter_map(|u| u.file_name())
.map(|n| std::ffi::OsStr::from_bytes(n).to_os_string())
.collect();
let base = match names.as_slice() {
[only] => only.as_bytes().to_vec(),
_ => dir.file_name().map_or(b"Archive".to_vec(), <[u8]>::to_vec),
};
let mut wanted = base;
wanted.extend_from_slice(format.ext().as_bytes());
let name = Self::free_name(pane, &wanted);
let dest = dir_path.join(std::ffi::OsStr::from_bytes(&name));
let shown = tunal_core::display_name(&name);
pane.model.select_when_shown(name, false);
self.bridge
.task(format!("Compressing into “{shown}”"), move |cancel| {
let refs: Vec<&std::ffi::OsStr> = names.iter().map(OsString::as_os_str).collect();
let cmd = tools::compress_command(format, &dir_path, &refs, &dest)
.ok_or("No archive tool for this format")?;
let result = tools::run_to_end(cmd, cancel);
if result.is_err() || cancel.load(std::sync::atomic::Ordering::Relaxed) {
let _ = std::fs::remove_file(&dest);
}
result.map(|()| format!("Made “{shown}”"))
});
}
/// Unpacks the selected archives into the folder shown, or each into a new folder named
/// after it. Files already there are kept.
fn extract(&self, pane: &Pane, own_folder: bool) {
let Some(dir) = pane.dir().and_then(|d| d.to_path()) else {
return;
};
let archives: Vec<PathBuf> = pane
.model
.selected_uris()
.iter()
.filter_map(Uri::to_path)
.collect();
let mut jobs: Vec<(PathBuf, PathBuf, bool)> = Vec::new();
for archive in archives {
if own_folder {
let stem = tools::archive_stem(&archive);
let name = Self::free_name(pane, stem.as_bytes());
let target = dir.join(std::ffi::OsStr::from_bytes(&name));
if jobs.is_empty() {
pane.model.select_when_shown(name, false);
}
jobs.push((archive, target, true));
} else {
jobs.push((archive, dir.clone(), false));
}
}
let title = match jobs.as_slice() {
[(only, ..)] => format!(
"“{}”",
only.file_name().unwrap_or_default().to_string_lossy()
),
_ => format!("{} archives", jobs.len()),
};
self.bridge
.task(format!("Extracting {title}"), move |cancel| {
for (archive, target, make) in jobs {
if cancel.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
if make {
std::fs::create_dir(&target).map_err(|e| e.to_string())?;
}
let cmd = tools::extract_command(&archive, &target)
.ok_or("No tool here unpacks this archive")?;
tools::run_to_end(cmd, cancel)?;
}
Ok(format!("Extracted {title}"))
});
}
/// The edited name of the entry in `pane` was accepted.
fn renamed(&self, pane: usize, text: &str) {
let Some(p) = self.shell().and_then(|s| s.pane_at(pane)) else {
@ -760,7 +1204,6 @@ impl Actions {
}
}
/// After a job: panes whose location can't watch (the Trash) list again.
/// A folder's appearance was saved: panes showing it (as a folder or inside it) pick up
/// its icon and name, and the folder shown keeps or forgets its view settings.
fn appearance_saved(&self, dir: &std::path::Path, remembered: bool) {
@ -776,6 +1219,7 @@ impl Actions {
shell.show_chrome();
}
/// After a job: panes whose location can't watch (the Trash) list again.
fn refresh_unwatched(&self, shell: &Shell) {
for pane in shell.panes() {
let watches = pane
@ -789,10 +1233,6 @@ impl Actions {
}
fn bind(&self, ui: &MainWindow) {
let me = self.me.clone();
ui.on_action_key(move |text, ctrl, shift, alt| {
me.upgrade().is_some_and(|a| a.key(&text, ctrl, shift, alt))
});
let me = self.me.clone();
ui.on_context_menu_requested(move |pane, row, x, y| {
if let Some(a) = me.upgrade() {
@ -826,3 +1266,13 @@ impl Actions {
});
}
}
fn entry(text: &str, icon: &str, disabled: bool) -> MenuEntry {
MenuEntry {
text: text.into(),
icon: icon.into(),
shortcut: Default::default(),
disabled,
separator: false,
}
}

View file

@ -20,6 +20,8 @@ pub struct App {
pub exec: String,
pub icon: Option<String>,
pub mime_types: Vec<String>,
/// `Categories` (`TerminalEmulator`, …).
pub categories: Vec<String>,
pub terminal: bool,
/// `NoDisplay`: usable for its own types but not offered as "other".
pub no_display: bool,
@ -162,6 +164,7 @@ fn parse_desktop(id: &str, path: &Path, text: &str, locales: &[String]) -> Optio
let mut localized: Vec<Option<String>> = vec![None; locales.len()];
let (mut exec, mut icon, mut kind) = (None, None, None);
let mut mime_types = Vec::new();
let mut categories = 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 {
@ -173,6 +176,7 @@ fn parse_desktop(id: &str, path: &Path, text: &str, locales: &[String]) -> Optio
"Icon" => icon = Some(unescape(&value)),
"Type" => kind = Some(value),
"MimeType" => mime_types = split_list(&value),
"Categories" => categories = split_list(&value),
"Terminal" => terminal = value == "true",
"NoDisplay" => no_display = value == "true",
"Hidden" => hidden = value == "true",
@ -195,6 +199,7 @@ fn parse_desktop(id: &str, path: &Path, text: &str, locales: &[String]) -> Optio
exec: exec?,
icon: icon.filter(|i| !i.is_empty()),
mime_types,
categories,
terminal,
no_display,
path: path.to_path_buf(),
@ -281,6 +286,17 @@ impl Apps {
}
}
/// Terminal emulators (`Categories=TerminalEmulator`), shown ones first.
pub fn terminals(&self) -> Vec<&App> {
let mut found: Vec<&App> = self
.apps
.iter()
.filter(|a| a.categories.iter().any(|c| c == "TerminalEmulator"))
.collect();
found.sort_by_key(|a| a.no_display);
found
}
pub fn get(&self, id: &str) -> Option<&App> {
self.apps.iter().find(|a| a.id == id)
}
@ -527,11 +543,15 @@ fn expand(template: &[String], app: &App, targets: &[Target]) -> Vec<String> {
/// 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) {
for 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 argv: Vec<std::ffi::OsString> = argv.into_iter().map(Into::into).collect();
let dir = targets
.first()
.and_then(|t| t.path.parent())
.unwrap_or(Path::new("/"));
crate::tools::in_terminal(&argv, dir)?;
continue;
}
let Some((program, args)) = argv.split_first() else {
return Err(format!("{} has no command to run", app.name));

View file

@ -1207,6 +1207,35 @@ impl FolderModel {
self.select(|s| s.selected.clear());
}
/// Selects what is shown and not selected, and unselects the rest.
pub fn invert_selection(&self) {
self.select(|s| {
let names: HashSet<Vec<u8>> = s
.row_of
.keys()
.filter(|n| !s.selected.contains(*n))
.cloned()
.collect();
s.selected = names;
});
}
/// The entries `selected_uris` names, in the same order.
pub fn selected_entries(&self) -> Vec<tunal_core::Entry> {
let names: Vec<Vec<u8>> = self
.selected_uris()
.iter()
.filter_map(|u| u.file_name().map(<[u8]>::to_vec))
.collect();
names.iter().filter_map(|n| self.entry(n)).collect()
}
/// The entry named `name` in the folder.
pub fn entry(&self, name: &[u8]) -> Option<tunal_core::Entry> {
let s = self.state.borrow();
s.by_name.get(name).map(|&i| s.items[i].entry.clone())
}
/// Selected entries, in the order shown (the cursor entry when nothing is selected).
pub fn selected_uris(&self) -> Vec<Uri> {
let s = self.state.borrow();

View file

@ -9,6 +9,7 @@ use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::ThreadId;
use std::time::Duration;
@ -45,6 +46,24 @@ enum Prompt {
action: String,
then: Box<dyn FnOnce()>,
},
/// A question with its own buttons; `then` gets the button chosen (`cancel` for Escape).
Choice {
glyph: String,
title: String,
body: String,
actions: Vec<DialogAction>,
cancel: usize,
then: Box<dyn FnOnce(usize)>,
},
}
/// What a toast belongs to.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Owner {
Message,
Job(JobId),
/// A background task (`Bridge::task`), by number.
Task(u64),
}
struct JobInfo {
@ -55,8 +74,11 @@ struct JobInfo {
#[derive(Default)]
struct State {
jobs: HashMap<JobId, JobInfo>,
/// Job of each toast, parallel to the toast model (none for plain messages).
toast_jobs: Vec<Option<JobId>>,
/// Owner of each toast, parallel to the toast model.
toast_owners: Vec<Owner>,
/// Cancel flags of the running background tasks.
tasks: HashMap<u64, Arc<AtomicBool>>,
next_task: u64,
queue: VecDeque<Prompt>,
active: Option<Prompt>,
}
@ -140,7 +162,7 @@ impl Bridge {
/// A short message toast.
pub fn notify(&self, message: impl Into<String>) {
self.state.borrow_mut().toast_jobs.push(None);
self.state.borrow_mut().toast_owners.push(Owner::Message);
self.toasts.push(ToastData {
message: message.into().into(),
action: Default::default(),
@ -161,14 +183,100 @@ impl Bridge {
});
}
/// Asks `title` / `body` with `actions` (left to right, the main one last); `then` gets the
/// index chosen, `cancel` when the dialog is dismissed.
pub fn ask(
&self,
glyph: &str,
title: &str,
body: &str,
actions: Vec<DialogAction>,
cancel: usize,
then: impl FnOnce(usize) + 'static,
) {
self.prompt(Prompt::Choice {
glyph: glyph.into(),
title: title.into(),
body: body.into(),
actions,
cancel,
then: Box::new(then),
});
}
/// Runs `work` on a thread behind a cancellable toast saying `message`. `work` checks the
/// flag it gets and stops when it is set; what it returns (done or the error) shows as a
/// toast, then the panes that can't watch list again.
pub fn task(
&self,
message: String,
work: impl FnOnce(&AtomicBool) -> Result<String, String> + Send + 'static,
) {
let cancel = Arc::new(AtomicBool::new(false));
let id = {
let mut state = self.state.borrow_mut();
state.next_task += 1;
let id = state.next_task;
state.tasks.insert(id, cancel.clone());
state.toast_owners.push(Owner::Task(id));
id
};
self.toasts.push(ToastData {
message: message.into(),
action: Default::default(),
cancellable: true,
progress_kind: ToastProgress::Indeterminate,
progress: 0.0,
closing: false,
});
std::thread::spawn(move || {
let result = work(&cancel);
let cancelled = cancel.load(Ordering::Relaxed);
let _ = slint::invoke_from_event_loop(move || {
if let Some(bridge) = BRIDGE.with(|b| b.borrow().upgrade()) {
bridge.task_done(
id,
if cancelled {
Ok("Cancelled".into())
} else {
result
},
);
}
});
});
}
fn task_done(&self, id: u64, result: Result<String, String>) {
let index = {
let mut state = self.state.borrow_mut();
state.tasks.remove(&id);
let index = state
.toast_owners
.iter()
.position(|o| *o == Owner::Task(id));
if let Some(i) = index {
state.toast_owners[i] = Owner::Message;
}
index
};
if let Some(i) = index {
self.close_toast(i);
}
match result {
Ok(message) | Err(message) => self.notify(message),
}
(self.on_finished.borrow())();
}
// ---- toasts -------------------------------------------------------------------------
fn toast_of(&self, job: JobId) -> Option<usize> {
self.state
.borrow()
.toast_jobs
.toast_owners
.iter()
.position(|j| *j == Some(job))
.position(|o| *o == Owner::Job(job))
}
fn progress_toast(&self, job: JobId, progress: &Progress) -> Option<ToastData> {
@ -209,7 +317,7 @@ impl Bridge {
let Some(data) = self.progress_toast(job, &handle.progress()) else {
return;
};
self.state.borrow_mut().toast_jobs.push(Some(job));
self.state.borrow_mut().toast_owners.push(Owner::Job(job));
self.toasts.push(data);
}
@ -223,20 +331,24 @@ impl Bridge {
fn toast_removed(&self, index: usize) {
if index < self.toasts.row_count() {
self.toasts.remove(index);
self.state.borrow_mut().toast_jobs.remove(index);
self.state.borrow_mut().toast_owners.remove(index);
}
}
fn toast_cancelled(&self, index: usize) {
let state = self.state.borrow();
if let Some(info) = state
.toast_jobs
.get(index)
.copied()
.flatten()
.and_then(|job| state.jobs.get(&job))
{
info.handle.cancel();
match state.toast_owners.get(index) {
Some(Owner::Job(job)) => {
if let Some(info) = state.jobs.get(job) {
info.handle.cancel();
}
}
Some(Owner::Task(id)) => {
if let Some(flag) = state.tasks.get(id) {
flag.store(true, Ordering::Relaxed);
}
}
_ => {}
}
}
@ -260,7 +372,7 @@ impl Bridge {
fn finished(&self, job: JobId, report: Report) {
if let Some(i) = self.toast_of(job) {
self.close_toast(i);
self.state.borrow_mut().toast_jobs[i] = None;
self.state.borrow_mut().toast_owners[i] = Owner::Message;
}
let Some(info) = self.state.borrow_mut().jobs.remove(&job) else {
return;
@ -318,6 +430,23 @@ impl Bridge {
ui.set_conflict(conflict_info(request));
ui.invoke_show_conflict();
}
Prompt::Choice {
glyph,
title,
body,
actions,
cancel,
..
} => {
ui.set_errors_glyph(glyph.into());
ui.set_errors_title(title.into());
ui.set_errors_body(body.into());
ui.set_errors_lines(ModelRc::new(VecModel::default()));
ui.set_errors_actions(ModelRc::new(VecModel::from(actions.clone())));
ui.set_errors_default(actions.len() as i32 - 1);
ui.set_errors_cancel(*cancel as i32);
ui.invoke_show_errors();
}
Prompt::Confirm {
title,
body,
@ -342,6 +471,7 @@ impl Bridge {
if request.needs_elevation() {
body.push_str(" Administrator rights are needed.");
}
ui.set_errors_glyph(Default::default());
ui.set_errors_title("Couldn't finish".into());
ui.set_errors_body(body.into());
ui.set_errors_lines(ModelRc::new(VecModel::default()));
@ -353,9 +483,11 @@ impl Bridge {
}
ui.set_errors_actions(ModelRc::new(VecModel::from(actions)));
ui.set_errors_default(2);
ui.set_errors_cancel(2);
ui.invoke_show_errors();
}
Prompt::Failures { title, lines } => {
ui.set_errors_glyph(Default::default());
ui.set_errors_title(title.into());
ui.set_errors_body("These were skipped:".into());
ui.set_errors_lines(ModelRc::new(VecModel::from(
@ -369,6 +501,7 @@ impl Bridge {
kind: ButtonKind::Filled,
}])));
ui.set_errors_default(0);
ui.set_errors_cancel(0);
ui.invoke_show_errors();
}
}
@ -415,7 +548,10 @@ impl Bridge {
if let Some(ui) = self.ui.upgrade() {
ui.invoke_close_errors();
}
if let Some(Prompt::Error(request, thread)) = self.finish_prompt() {
let prompt = self.finish_prompt();
if let Some(Prompt::Choice { then, cancel, .. }) = prompt {
then(usize::try_from(index).unwrap_or(cancel));
} else if let Some(Prompt::Error(request, thread)) = prompt {
request.reply.send(match index {
0 => ErrorAction::Abort,
1 => ErrorAction::SkipAll,
@ -462,7 +598,10 @@ impl Bridge {
}
fn is_quick(kind: &JobKind) -> bool {
matches!(kind, JobKind::Mkdir(_) | JobKind::Rename { .. })
matches!(
kind,
JobKind::Mkdir(_) | JobKind::CreateFile(_) | JobKind::Rename { .. }
)
}
fn name_of(uri: &Uri) -> String {
@ -485,7 +624,10 @@ fn count(kind: &JobKind) -> usize {
| JobKind::Move { sources, .. }
| JobKind::Link { sources, .. } => sources.len(),
JobKind::Delete(uris) | JobKind::Trash(uris) | JobKind::Restore(uris) => uris.len(),
JobKind::EmptyTrash | JobKind::Mkdir(_) | JobKind::Rename { .. } => 1,
JobKind::EmptyTrash
| JobKind::Mkdir(_)
| JobKind::CreateFile(_)
| JobKind::Rename { .. } => 1,
}
}
@ -499,6 +641,7 @@ fn verb(kind: &JobKind) -> &'static str {
JobKind::Restore(_) => "Restore",
JobKind::EmptyTrash => "Empty Trash",
JobKind::Mkdir(_) => "New folder",
JobKind::CreateFile(_) => "New file",
JobKind::Rename { .. } => "Rename",
JobKind::Link { .. } => "Link",
}
@ -515,6 +658,7 @@ fn describe(kind: &JobKind) -> String {
JobKind::Restore(_) => format!("Restoring {n}"),
JobKind::EmptyTrash => "Emptying Trash".into(),
JobKind::Mkdir(_) => "Creating folder".into(),
JobKind::CreateFile(_) => "Creating file".into(),
JobKind::Rename { .. } => "Renaming".into(),
JobKind::Link { .. } => format!("Linking {n}"),
}
@ -531,6 +675,7 @@ fn summary(kind: &JobKind) -> String {
JobKind::Restore(_) => format!("Restored {n}"),
JobKind::EmptyTrash => "Trash emptied".into(),
JobKind::Mkdir(_) => "Folder created".into(),
JobKind::CreateFile(_) => "File created".into(),
JobKind::Rename { .. } => "Renamed".into(),
JobKind::Link { .. } => format!("Linked {n}"),
}

View file

@ -45,6 +45,8 @@ impl Context {
Self::File => &[
"open",
"play",
"run",
"run-in-terminal",
"open-with",
"edit-tags",
"-",
@ -52,8 +54,18 @@ impl Context {
"copy",
"paste",
"-",
"copy-to",
"move-to",
"copy-to-other-pane",
"move-to-other-pane",
"-",
"copy-path",
"rename",
"duplicate",
"-",
"compress",
"extract-here",
"extract-to-folder",
"-",
"trash",
"delete",
@ -62,31 +74,49 @@ impl Context {
],
Self::Folder => &[
"open",
"open-new-tab",
"open-split",
"terminal",
"-",
"cut",
"copy",
"paste",
"-",
"copy-to",
"move-to",
"copy-to-other-pane",
"move-to-other-pane",
"-",
"copy-path",
"rename",
"new-folder",
"duplicate",
"add-to-places",
"compress",
"-",
"trash",
"delete",
"-",
"sort-by",
"view-mode",
"-",
"appearance",
"properties",
],
Self::Multiple => &[
"open-new-tab",
"play",
"edit-tags",
"-",
"cut",
"copy",
"-",
"copy-to",
"move-to",
"copy-to-other-pane",
"move-to-other-pane",
"-",
"copy-path",
"duplicate",
"compress",
"extract-here",
"extract-to-folder",
"-",
"trash",
"delete",
@ -95,12 +125,17 @@ impl Context {
],
Self::Empty => &[
"paste",
"new-folder",
"create-new",
"-",
"select-all",
"invert-selection",
"-",
"sort-by",
"view-mode",
"-",
"terminal",
"copy-path",
"add-to-places",
"-",
"appearance",
"properties",
@ -112,6 +147,20 @@ impl Context {
}
}
/// Drops separators at either end and the second of two in a row.
pub fn tidy(items: Vec<Option<Action>>) -> Vec<Option<Action>> {
let mut out: Vec<Option<Action>> = Vec::new();
for item in items {
if item.is_some() || (!out.is_empty() && out.last() != Some(&None)) {
out.push(item);
}
}
if out.last() == Some(&None) {
out.pop();
}
out
}
/// `menus.toml`: a context that is missing keeps its default.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default)]
@ -157,20 +206,15 @@ impl Menus {
/// The menu as shown: known actions only, `None` for a separator, with no separator at
/// either end or twice in a row.
pub fn layout(&self, ctx: Context) -> Vec<Option<Action>> {
let mut out: Vec<Option<Action>> = Vec::new();
for id in self.ids(ctx) {
if id == SEPARATOR {
if !out.is_empty() && out.last() != Some(&None) {
out.push(None);
}
} else if let Some(action) = Action::from_id(&id) {
out.push(Some(action));
}
}
if out.last() == Some(&None) {
out.pop();
}
out
tidy(
self.ids(ctx)
.iter()
.filter_map(|id| match Action::from_id(id) {
Some(action) => Some(Some(action)),
None => (id == SEPARATOR).then_some(None),
})
.collect(),
)
}
pub fn set(&mut self, ctx: Context, ids: Vec<String>) {

View file

@ -1,5 +1,7 @@
//! 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.
//! Opening a file in its default application: the app `mimeapps.list` names (or the first
//! that handles the type) is started directly; a type no app handles opens our own Open with
//! dialog. The desktop portal, then `xdg-open`, are the fallback when starting the app fails.
//! All of it runs off the UI thread; a failure comes back as text.
use std::collections::HashMap;
use std::fs::File;
@ -9,15 +11,28 @@ 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);
});
/// Hands `path` to the portal, then `xdg-open`; the error when neither worked.
fn open_elsewhere(path: &PathBuf) -> Result<(), String> {
match portal(path) {
Ok(()) => Ok(()),
Err(portal_error) => xdg_open(path).map_err(|e| format!("{e} ({portal_error})")),
}
}
/// The app that opens `mime`: the default, else the first that handles it. Scripts and other
/// text types no app names fall back to plain text.
fn app_for(apps: &Apps, mime: &str) -> Option<App> {
let pick = |mime: &str| {
let choices = apps.choices(mime);
let default = choices
.default
.as_ref()
.and_then(|id| choices.handlers.iter().find(|a| &a.id == id))
.cloned();
default.or_else(|| choices.handlers.into_iter().next())
};
let texty = mime.starts_with("text/") || mime.contains("script") || mime == "application/x-sh";
pick(mime).or_else(|| texty.then(|| pick("text/plain")).flatten())
}
/// `org.freedesktop.portal.OpenURI.OpenFile` with the file as a descriptor (the portal's way
@ -146,14 +161,27 @@ impl Opener {
});
}
/// Opens `uri` in its default application.
/// Opens `uri` in its default application, or asks which one when there is none.
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| {
let locations = self.locations.clone();
let uri = uri.clone();
std::thread::spawn(move || {
let mime = locations
.resolve(&uri)
.and_then(|l| l.stat(&uri))
.map_or("application/octet-stream", |e| e.mime);
let Some(app) = app_for(&Apps::load(), mime) else {
Self::with(move |o| o.open_with(vec![uri]));
return;
};
let target = Target { path: path.clone() };
let result = desktop_apps::launch(&app, &[target])
.or_else(|e| open_elsewhere(&path).map_err(|other| format!("{e} ({other})")));
if let Err(message) = result {
Self::with(move |o| o.bridge.notify(message));
}

View file

@ -50,6 +50,14 @@ fn with(f: impl FnOnce(&PlayerUi)) {
}
}
/// A local audio file: what Play and Space offer (a video plays only when asked for by name).
pub fn is_audio(uri: &Uri) -> bool {
can_play(uri)
&& uri
.file_name()
.is_some_and(|name| !mime::mime_type(name, &Kind::File).starts_with("video/"))
}
/// A local audio or video file (a video plays its sound). Formats neither decoder knows get
/// an error toast when played.
pub fn can_play(uri: &Uri) -> bool {

412
crates/tunal/src/tools.rs Normal file
View file

@ -0,0 +1,412 @@
//! Programs Tunal starts: a terminal, executable files, and the archive tools (`tar`,
//! `bsdtar`, `zip`, `unzip`), found on `PATH` when first needed. A missing tool turns its
//! menu entries off. Everything runs detached or on a worker thread, never through a shell.
use std::ffi::{OsStr, OsString};
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use crate::desktop_apps::{self, Apps};
/// `name` on `PATH` (or `name` itself when it is a path to an executable file).
pub fn find_program(name: &str) -> Option<PathBuf> {
let executable = |p: &Path| {
p.metadata()
.is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
};
if name.contains('/') {
let path = PathBuf::from(name);
return executable(&path).then_some(path);
}
std::env::split_paths(&std::env::var_os("PATH")?)
.map(|dir| dir.join(name))
.find(|p| executable(p))
}
/// Starts `argv` in `cwd`, detached: no input, output discarded, reaped when it ends.
pub fn spawn(argv: &[OsString], cwd: &Path) -> Result<(), String> {
let Some((program, args)) = argv.split_first() else {
return Err("Nothing to start".into());
};
let mut child = Command::new(program)
.args(args)
.current_dir(cwd)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("Couldn't start {}: {e}", Path::new(program).display()))?;
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
// ---- terminal -------------------------------------------------------------------------------
/// How a terminal takes a command to run.
#[derive(Clone, Copy, Debug)]
enum Style {
/// `term cmd args…`
Plain,
/// `term -e cmd args…`
DashE,
/// `term start --cwd <dir> -- cmd args…`
Start,
}
#[derive(Clone, Debug)]
pub struct Terminal {
/// The program and the arguments before the command.
argv: Vec<OsString>,
style: Style,
}
/// Terminals known by their binary name, in the order they are looked for after `$TERMINAL`.
const KNOWN: [(&str, Style); 6] = [
("xdg-terminal-exec", Style::Plain),
("x-terminal-emulator", Style::DashE),
("kitty", Style::Plain),
("alacritty", Style::DashE),
("foot", Style::Plain),
("wezterm", Style::Start),
];
fn style_of(program: &Path) -> Style {
let name = program
.file_name()
.and_then(OsStr::to_str)
.unwrap_or_default();
KNOWN
.iter()
.find(|(known, _)| *known == name)
.map_or(Style::DashE, |(_, style)| *style)
}
fn find_terminal() -> Option<Terminal> {
let from = |program: PathBuf, rest: Vec<OsString>| {
let style = style_of(&program);
let mut argv = vec![program.into_os_string()];
argv.extend(rest);
Terminal { argv, style }
};
if let Ok(value) = std::env::var("TERMINAL") {
let mut words = value.split_whitespace();
if let Some(program) = words.next().and_then(find_program) {
return Some(from(program, words.map(OsString::from).collect()));
}
}
if let Some(program) = KNOWN.iter().find_map(|(name, _)| find_program(name)) {
return Some(from(program, Vec::new()));
}
// An installed terminal's desktop entry (Categories=TerminalEmulator).
let apps = Apps::load();
apps.terminals().into_iter().find_map(|app| {
let mut words: Vec<String> = desktop_apps::split_exec(&app.exec)
.into_iter()
.filter(|w| !w.starts_with('%'))
.collect();
if words.is_empty() {
return None;
}
let program = find_program(&words.remove(0))?;
Some(from(
program,
words.into_iter().map(OsString::from).collect(),
))
})
}
/// The terminal to use, looked for once.
pub fn terminal() -> Option<&'static Terminal> {
static FOUND: OnceLock<Option<Terminal>> = OnceLock::new();
FOUND.get_or_init(find_terminal).as_ref()
}
impl Terminal {
fn command(&self, dir: &Path, run: &[OsString]) -> Vec<OsString> {
let mut argv = self.argv.clone();
match self.style {
Style::Start => {
argv.extend(["start".into(), "--cwd".into(), dir.into()]);
if !run.is_empty() {
argv.push("--".into());
}
}
Style::DashE if !run.is_empty() => argv.push("-e".into()),
Style::DashE | Style::Plain => {}
}
argv.extend(run.iter().cloned());
argv
}
}
/// Opens a terminal in `dir`.
pub fn open_terminal(dir: &Path) -> Result<(), String> {
let term = terminal().ok_or("No terminal found")?;
spawn(&term.command(dir, &[]), dir)
}
/// Runs `argv` in a terminal window, in `dir`.
pub fn in_terminal(argv: &[OsString], dir: &Path) -> Result<(), String> {
let term = terminal().ok_or("No terminal found")?;
spawn(&term.command(dir, argv), dir)
}
// ---- executable files -----------------------------------------------------------------------
/// What an executable file is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Executable {
/// A compiled program or an AppImage: it only runs.
Program,
/// A script: it runs, or opens as text.
Script,
}
/// MIME types of scripts (by extension).
const SCRIPTS: [&str; 8] = [
"application/x-sh",
"application/x-shellscript",
"application/x-csh",
"text/x-python",
"text/x-script.python",
"application/x-perl",
"text/x-perl",
"application/x-ruby",
];
/// MIME types of programs (by extension).
const PROGRAMS: [&str; 5] = [
"application/x-executable",
"application/x-sharedlib",
"application/x-pie-executable",
"application/vnd.appimage",
"application/x-appimage",
];
/// A local file with an execute bit that is a program or a script: by its MIME type
/// (guessed from the name), or with no known type at all. `mode` is the entry's own mode
/// (a link's is looked up through it).
pub fn executable(path: &Path, mime: &str, mode: u32, link: bool) -> Option<Executable> {
let mode = if link {
path.metadata()
.ok()
.filter(|m| m.is_file())?
.permissions()
.mode()
} else {
mode
};
if mode & 0o111 == 0 {
return None;
}
let appimage = path
.extension()
.and_then(OsStr::to_str)
.is_some_and(|e| e.eq_ignore_ascii_case("appimage"));
if SCRIPTS.contains(&mime) {
Some(Executable::Script)
} else if appimage || PROGRAMS.contains(&mime) || mime == tunal_core::mime::UNKNOWN {
Some(Executable::Program)
} else {
None
}
}
/// Runs the file itself, detached, in its folder (its path is argv[0]).
pub fn run(path: &Path) -> Result<(), String> {
spawn(&[path.into()], path.parent().unwrap_or(Path::new("/")))
}
pub fn run_in_terminal(path: &Path) -> Result<(), String> {
in_terminal(&[path.into()], path.parent().unwrap_or(Path::new("/")))
}
// ---- archives -------------------------------------------------------------------------------
/// Archive formats Tunal makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
TarGz,
Zip,
}
impl Format {
pub const ALL: [Format; 2] = [Self::TarGz, Self::Zip];
pub fn label(self) -> &'static str {
match self {
Self::TarGz => "Tar archive (.tar.gz)",
Self::Zip => "Zip archive (.zip)",
}
}
pub fn ext(self) -> &'static str {
match self {
Self::TarGz => ".tar.gz",
Self::Zip => ".zip",
}
}
}
fn tool(name: &'static str) -> Option<&'static Path> {
static TOOLS: OnceLock<Vec<(&'static str, Option<PathBuf>)>> = OnceLock::new();
let tools = TOOLS.get_or_init(|| {
["tar", "bsdtar", "zip", "unzip"]
.into_iter()
.map(|n| (n, find_program(n)))
.collect()
});
tools
.iter()
.find(|(n, _)| *n == name)
.and_then(|(_, p)| p.as_deref())
}
pub fn can_compress(format: Format) -> bool {
compress_command(format, Path::new("/"), &[], Path::new("/")).is_some()
}
/// The command that packs `names` (in `dir`) into `dest`.
pub fn compress_command(
format: Format,
dir: &Path,
names: &[&OsStr],
dest: &Path,
) -> Option<Command> {
// `./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")?);
cmd.args(["-r", "-q", "-y"]).arg(dest);
cmd
}
Format::Zip => {
let mut cmd = Command::new(tool("bsdtar")?);
cmd.args(["--format", "zip", "-cf"]).arg(dest);
cmd
}
};
cmd.args(items).current_dir(dir);
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),
];
/// 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()
}
/// The command that unpacks `archive` into `dest`, never overwriting what is there.
pub fn extract_command(archive: &Path, dest: &Path) -> Option<Command> {
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")?);
cmd.args(["-x", "-k", "-f"])
.arg(archive)
.arg("-C")
.arg(dest);
cmd
};
cmd.current_dir(dest);
Some(cmd)
}
/// The archive's name without its ending: `photos.tar.gz` → `photos`.
pub fn archive_stem(archive: &Path) -> String {
let name = archive
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let lower = name.to_lowercase();
ARCHIVES
.iter()
.filter(|(ext, _)| lower.ends_with(ext))
.map(|(ext, _)| ext.len())
.max()
.filter(|&n| n < name.len())
.map_or(name.clone(), |n| name[..name.len() - n].to_string())
}
/// Runs `cmd` to the end, killing it when `cancel` is set. The error carries the tool's own
/// last line of output.
pub fn run_to_end(mut cmd: Command, cancel: &AtomicBool) -> Result<(), String> {
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("Couldn't start the archive tool: {e}"))?;
// Read the errors on the side so a chatty tool never fills the pipe and stalls.
let mut stderr = child.stderr.take();
let reader = std::thread::spawn(move || {
let mut text = String::new();
if let Some(err) = stderr.as_mut() {
let _ = err.read_to_string(&mut text);
}
text
});
let status = loop {
if cancel.load(Ordering::Relaxed) {
let _ = child.kill();
let _ = child.wait();
return Ok(());
}
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => std::thread::sleep(Duration::from_millis(100)),
Err(e) => return Err(e.to_string()),
}
};
let output = reader.join().unwrap_or_default();
if status.success() {
Ok(())
} else {
let last = output.lines().rev().find(|l| !l.trim().is_empty());
Err(last.unwrap_or("The archive tool failed").trim().to_string())
}
}