Seek bar, spring motion, archive formats, file pickers, icon browser and launchers
Seeking and the sidebar selection spring to the click. Compress and extract cover the 7z formats. Path fields get a file picker, icon dialogs a browser with categories. Create new makes launchers, Edit launcher changes them. New tabs open Home and a file path opens its folder. Dialogs opened from a menu keep the focus. Remote noted in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
4acabfc76a
commit
7b13c1658e
34 changed files with 1528 additions and 141 deletions
|
|
@ -53,7 +53,7 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~
|
|||
- **User validates personally (🧑)**, all in phase 12 (D-009): visual review (S035), the polkit password prompt, real iPhone/Android devices, native drag/clipboard with other apps, a real SFTP host (S036). Plans that need these stop at that step and report.
|
||||
- **Design references (read only, D-027, D-028)**: the user's own Material You apps — `~/Projects/Damson` (`src/theme.rs`, `src/motion.rs`, `src/ui/`), `~/Projects/Mulberry` (`src/theme.rs`, `src/ui/`), `~/Projects/Nacre` (`src/theme.rs`, `src/ui/widgets.rs`, `src/ui/chrome.rs`). They use egui, not Slint: borrow look and feel (colour roles, state layers, shapes, spacing, motion curves and timings) and port the idea to our Slint tokens; never change our stack, never edit them. Their code is the user's own, so copying is allowed where it fits. Also the user's old, buggy Tunal prototype in `/home/astar76/Documents/Apps/tunal-files/tunal/` (Python): look at its elements for ideas only, never copy its code — the new UI is meant to be new. A library default that looks off is not a reason to accept it: build the control ourselves on `Theme`/`Motion`.
|
||||
- **Motion rules** (`app-taste` skill): tokens only, hover tint and press squeeze on every control, interruptible motion, honour reduced motion, no idle animation, repaint only while something moves. Build new motion with the `animate` skill; `/unslop` and `/improve-animations` run in phase 12 (S034, S035; there is no `/review-animations`).
|
||||
- No Forgejo remote yet: the user wants local-only git for now.
|
||||
- Remote: `origin` = `forgejo:astar76/Tunal.git` (Astar Hub, private), since 2026-11-25.
|
||||
|
||||
## 3. Code rules
|
||||
|
||||
|
|
@ -104,7 +104,7 @@ Don't assume a tool exists: check first. When your plan creates a tool, add its
|
|||
|
||||
## 6. Git
|
||||
|
||||
Local repository only; no remote and no push until the user says so. `.gitignore` covers `target/`. One commit per logical step, message `SNNN: …` in English. No `reset --hard` / force push without an explicit request.
|
||||
Remote `origin` is Astar Hub (`forgejo:astar76/Tunal.git`); the user asked for the first push on 2026-11-25. `.gitignore` covers `target/`. One commit per logical step, message `SNNN: …` in English. No `reset --hard` / force push without an explicit request.
|
||||
|
||||
## 7. Definition of done
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ mod palette;
|
|||
mod portal;
|
||||
|
||||
pub use palette::{FALLBACK_SEED, Palette, Palettes, Style};
|
||||
pub use portal::{pick_color, read, watch};
|
||||
pub use portal::{pick_color, pick_file, read, watch};
|
||||
|
||||
/// Accent colour as the portal reports it: sRGB components in `0.0..=1.0`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
//! `org.freedesktop.portal.Settings` and the screen colour picker over the session bus (zbus blocking API).
|
||||
//! `org.freedesktop.portal.Settings`, the screen colour picker and the file picker over the
|
||||
//! session bus (zbus blocking API).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::{OsStrExt, OsStringExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
use zbus::blocking::{Connection, Proxy, proxy::Builder};
|
||||
|
|
@ -64,10 +68,13 @@ fn watch_loop(on_change: impl Fn(Appearance)) -> zbus::Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Lets the user pick a colour from the screen (the Screenshot portal) and waits for it:
|
||||
/// `Ok(None)` when they cancel. Blocks; call it off the UI thread.
|
||||
pub fn pick_color() -> zbus::Result<Option<u32>> {
|
||||
const TOKEN: &str = "tunal_pick_color";
|
||||
/// Makes a portal request and waits for its answer: `Ok(None)` when the user cancels. `call`
|
||||
/// gets the portal object and the handle token to pass on.
|
||||
fn request(
|
||||
interface: &'static str,
|
||||
token: &'static str,
|
||||
call: impl FnOnce(&Proxy, Value<'static>) -> zbus::Result<OwnedObjectPath>,
|
||||
) -> zbus::Result<Option<HashMap<String, OwnedValue>>> {
|
||||
let conn = Connection::session()?;
|
||||
let sender = conn
|
||||
.unique_name()
|
||||
|
|
@ -77,20 +84,19 @@ pub fn pick_color() -> zbus::Result<Option<u32>> {
|
|||
let request: Proxy = Builder::new(&conn)
|
||||
.destination("org.freedesktop.portal.Desktop")?
|
||||
.path(format!(
|
||||
"/org/freedesktop/portal/desktop/request/{sender}/{TOKEN}"
|
||||
"/org/freedesktop/portal/desktop/request/{sender}/{token}"
|
||||
))?
|
||||
.interface("org.freedesktop.portal.Request")?
|
||||
.cache_properties(CacheProperties::No)
|
||||
.build()?;
|
||||
let mut responses = request.receive_signal("Response")?;
|
||||
let options = HashMap::from([("handle_token", Value::from(TOKEN))]);
|
||||
let portal = Proxy::new(
|
||||
&conn,
|
||||
"org.freedesktop.portal.Desktop",
|
||||
"/org/freedesktop/portal/desktop",
|
||||
"org.freedesktop.portal.Screenshot",
|
||||
interface,
|
||||
)?;
|
||||
let _: OwnedObjectPath = portal.call("PickColor", &("", options))?;
|
||||
call(&portal, Value::from(token))?;
|
||||
let Some(msg) = responses.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
|
@ -99,12 +105,77 @@ pub fn pick_color() -> zbus::Result<Option<u32>> {
|
|||
.deserialize::<(u32, HashMap<String, OwnedValue>)>()?;
|
||||
// 0 picked, 1 cancelled, 2 ended some other way.
|
||||
match code {
|
||||
0 => Ok(results.get("color").and_then(parse_accent).map(|c| c.rgb())),
|
||||
0 => Ok(Some(results)),
|
||||
1 => Ok(None),
|
||||
_ => Err(zbus::Error::Failure("the colour picker failed".into())),
|
||||
_ => Err(zbus::Error::Failure("the portal request failed".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets the user pick a colour from the screen (the Screenshot portal) and waits for it:
|
||||
/// `Ok(None)` when they cancel. Blocks; call it off the UI thread.
|
||||
pub fn pick_color() -> zbus::Result<Option<u32>> {
|
||||
let results = request(
|
||||
"org.freedesktop.portal.Screenshot",
|
||||
"tunal_pick_color",
|
||||
|portal, token| portal.call("PickColor", &("", HashMap::from([("handle_token", token)]))),
|
||||
)?;
|
||||
Ok(results
|
||||
.and_then(|r| r.get("color").and_then(parse_accent))
|
||||
.map(|c| c.rgb()))
|
||||
}
|
||||
|
||||
/// Lets the user choose one local file (the FileChooser portal), of the MIME types `types`
|
||||
/// (all for none), starting in `folder`: `Ok(None)` when they cancel. Blocks; call it off the
|
||||
/// UI thread.
|
||||
pub fn pick_file(
|
||||
title: &str,
|
||||
types: &[&str],
|
||||
folder: Option<&Path>,
|
||||
) -> zbus::Result<Option<PathBuf>> {
|
||||
let mut options: HashMap<&str, Value> = HashMap::new();
|
||||
if !types.is_empty() {
|
||||
// Kind 1 is a MIME type (0 a pattern).
|
||||
let list: Vec<(u32, String)> = types.iter().map(|t| (1, (*t).to_owned())).collect();
|
||||
options.insert("filters", Value::new(vec![("Images".to_owned(), list)]));
|
||||
}
|
||||
if let Some(folder) = folder {
|
||||
let mut bytes = folder.as_os_str().as_bytes().to_vec();
|
||||
bytes.push(0);
|
||||
options.insert("current_folder", Value::new(bytes));
|
||||
}
|
||||
let results = request(
|
||||
"org.freedesktop.portal.FileChooser",
|
||||
"tunal_pick_file",
|
||||
|portal, token| {
|
||||
options.insert("handle_token", token);
|
||||
portal.call("OpenFile", &("", title, options))
|
||||
},
|
||||
)?;
|
||||
let uris = results
|
||||
.as_ref()
|
||||
.and_then(|r| r.get("uris"))
|
||||
.and_then(|v| v.downcast_ref::<zbus::zvariant::Array>().ok())
|
||||
.and_then(|a| a.get::<String>(0).ok().flatten());
|
||||
Ok(uris.as_deref().and_then(file_path))
|
||||
}
|
||||
|
||||
/// The path of a `file:` URI.
|
||||
fn file_path(uri: &str) -> Option<PathBuf> {
|
||||
let path = uri.strip_prefix("file://")?;
|
||||
let path = &path[path.find('/')?..];
|
||||
let mut bytes = Vec::with_capacity(path.len());
|
||||
let mut rest = path.as_bytes();
|
||||
while let [first, tail @ ..] = rest {
|
||||
let hex = (*first == b'%')
|
||||
.then(|| std::str::from_utf8(tail.get(..2)?).ok())
|
||||
.flatten()
|
||||
.and_then(|h| u8::from_str_radix(h, 16).ok());
|
||||
bytes.push(hex.unwrap_or(*first));
|
||||
rest = if hex.is_some() { &tail[2..] } else { tail };
|
||||
}
|
||||
Some(PathBuf::from(OsString::from_vec(bytes)))
|
||||
}
|
||||
|
||||
fn connect() -> zbus::Result<Proxy<'static>> {
|
||||
let conn = Connection::session()?;
|
||||
Builder::new(&conn)
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ use crate::config::Executables;
|
|||
use crate::folder::appearance::Appearance;
|
||||
use crate::jobs_bridge::Bridge;
|
||||
use crate::keymap::Command;
|
||||
use crate::launcher::{self, Launcher};
|
||||
use crate::menus::{self, Context as MenuContext, Menus};
|
||||
use crate::open::Opener;
|
||||
use crate::player_bridge::{self, PlayerUi};
|
||||
|
|
@ -53,8 +54,9 @@ pub enum Action {
|
|||
Properties,
|
||||
Appearance,
|
||||
EditTags,
|
||||
EditLauncher,
|
||||
Play,
|
||||
/// Submenu: a folder, a text file or an empty file.
|
||||
/// Submenu: a folder, a text file, an empty file or a launcher.
|
||||
CreateNew,
|
||||
Duplicate,
|
||||
AddToPlaces,
|
||||
|
|
@ -75,7 +77,7 @@ pub enum Action {
|
|||
}
|
||||
|
||||
impl Action {
|
||||
pub const ALL: [Action; 36] = [
|
||||
pub const ALL: [Action; 37] = [
|
||||
Self::Cut,
|
||||
Self::Copy,
|
||||
Self::Paste,
|
||||
|
|
@ -97,6 +99,7 @@ impl Action {
|
|||
Self::Properties,
|
||||
Self::Appearance,
|
||||
Self::EditTags,
|
||||
Self::EditLauncher,
|
||||
Self::Play,
|
||||
Self::CreateNew,
|
||||
Self::Duplicate,
|
||||
|
|
@ -137,6 +140,7 @@ impl Action {
|
|||
Self::Properties => "properties",
|
||||
Self::Appearance => "appearance",
|
||||
Self::EditTags => "edit-tags",
|
||||
Self::EditLauncher => "edit-launcher",
|
||||
Self::Play => "play",
|
||||
Self::CreateNew => "create-new",
|
||||
Self::Duplicate => "duplicate",
|
||||
|
|
@ -182,6 +186,7 @@ impl Action {
|
|||
Self::Properties => "Properties",
|
||||
Self::Appearance => "Folder appearance…",
|
||||
Self::EditTags => "Edit tags…",
|
||||
Self::EditLauncher => "Edit launcher…",
|
||||
Self::Play => "Play",
|
||||
Self::CreateNew => "Create new",
|
||||
Self::Duplicate => "Duplicate here",
|
||||
|
|
@ -223,6 +228,7 @@ impl Action {
|
|||
Self::Properties => "\u{e88e}",
|
||||
Self::Appearance => "\u{e40a}",
|
||||
Self::EditTags => "\u{e892}",
|
||||
Self::EditLauncher => "\u{eb9b}",
|
||||
Self::Play => "\u{e037}",
|
||||
Self::CreateNew => "\u{e89c}",
|
||||
Self::Duplicate => "\u{e173}",
|
||||
|
|
@ -243,6 +249,7 @@ impl Action {
|
|||
pub fn shown(self, ctx: &Context) -> bool {
|
||||
match self {
|
||||
Self::Play => ctx.audio,
|
||||
Self::EditLauncher => ctx.launcher,
|
||||
Self::Run => ctx.executable,
|
||||
Self::RunInTerminal => ctx.executable && tools::terminal().is_some(),
|
||||
Self::Terminal => ctx.local && tools::terminal().is_some(),
|
||||
|
|
@ -282,6 +289,7 @@ impl Action {
|
|||
Self::Properties | Self::SortBy | Self::ViewMode => true,
|
||||
Self::Appearance => files && ctx.selected <= 1,
|
||||
Self::EditTags => files && ctx.taggable,
|
||||
Self::EditLauncher => files && ctx.launcher,
|
||||
Self::Play => files && ctx.audio,
|
||||
}
|
||||
}
|
||||
|
|
@ -300,6 +308,8 @@ pub struct Context {
|
|||
pub taggable: bool,
|
||||
/// Every selected entry is a local audio file (Play; a video plays only when asked).
|
||||
pub audio: bool,
|
||||
/// One local launcher (`.desktop` file) is selected.
|
||||
pub launcher: bool,
|
||||
/// One local executable file is selected.
|
||||
pub executable: bool,
|
||||
/// Every selected entry is a folder.
|
||||
|
|
@ -350,6 +360,7 @@ pub struct Actions {
|
|||
opener: Rc<Opener>,
|
||||
properties: Rc<Properties>,
|
||||
appearance: Rc<Appearance>,
|
||||
launcher: Rc<Launcher>,
|
||||
tags: Rc<Tags>,
|
||||
player: Rc<PlayerUi>,
|
||||
}
|
||||
|
|
@ -372,6 +383,7 @@ impl Actions {
|
|||
let opener = Opener::attach(ui, locations.clone(), bridge.clone());
|
||||
let properties = Properties::attach(ui, locations.clone());
|
||||
let appearance = Appearance::attach(ui, bridge.elevation());
|
||||
let launcher = Launcher::attach(ui);
|
||||
let tags = Tags::attach(ui, bridge.clone());
|
||||
let player = PlayerUi::attach(ui, bridge.clone());
|
||||
let actions = Rc::new_cyclic(|me| Self {
|
||||
|
|
@ -388,6 +400,7 @@ impl Actions {
|
|||
opener,
|
||||
properties,
|
||||
appearance,
|
||||
launcher,
|
||||
tags,
|
||||
player,
|
||||
});
|
||||
|
|
@ -399,6 +412,14 @@ impl Actions {
|
|||
}
|
||||
});
|
||||
let me = actions.me.clone();
|
||||
actions.launcher.on_made(move |name| {
|
||||
let shell = me.upgrade().and_then(|m| m.shell());
|
||||
if let Some(pane) = shell.and_then(|s| s.active()) {
|
||||
let name = std::os::unix::ffi::OsStrExt::as_bytes(name).to_vec();
|
||||
pane.model.select_when_shown(name, false);
|
||||
}
|
||||
});
|
||||
let me = actions.me.clone();
|
||||
actions.appearance.on_saved(move |dir, remembered| {
|
||||
if let Some(me) = me.upgrade() {
|
||||
me.appearance_saved(dir, remembered);
|
||||
|
|
@ -473,6 +494,8 @@ impl Actions {
|
|||
Context {
|
||||
taggable: files && selected.iter().all(tags_bridge::can_tag),
|
||||
audio: files && selected.iter().all(player_bridge::is_audio),
|
||||
launcher: files
|
||||
&& matches!(selected.as_slice(), [only] if only.to_path().is_some_and(|p| launcher::is_launcher(&p))),
|
||||
executable: match (entries.as_slice(), &dir) {
|
||||
([only], Some(dir)) => executable(dir, only).is_some(),
|
||||
_ => false,
|
||||
|
|
@ -569,11 +592,20 @@ impl Actions {
|
|||
entry("Folder", Action::NewFolder.glyph(), false),
|
||||
entry("Text file", "\u{f1c6}", false),
|
||||
entry("Empty file", "\u{e873}", false),
|
||||
entry(
|
||||
"Launcher…",
|
||||
Action::EditLauncher.glyph(),
|
||||
pane.dir().is_none_or(|d| d.to_path().is_none()),
|
||||
),
|
||||
],
|
||||
Action::CopyTo | Action::MoveTo => self.target_entries(pane),
|
||||
Action::Compress => Format::ALL
|
||||
.into_iter()
|
||||
.map(|f| entry(f.label(), Action::Compress.glyph(), !tools::can_compress(f)))
|
||||
.map(|f| {
|
||||
let fits = !f.single() || self.one_file(pane);
|
||||
let usable = fits && tools::can_compress(f);
|
||||
entry(f.label(), Action::Compress.glyph(), !usable)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
|
|
@ -656,7 +688,12 @@ impl Actions {
|
|||
match sub {
|
||||
0 => self.new_folder(&pane, dir),
|
||||
1 => self.new_file(&pane, dir, b"New text file.txt"),
|
||||
_ => self.new_file(&pane, dir, b"New file"),
|
||||
2 => self.new_file(&pane, dir, b"New file"),
|
||||
_ => {
|
||||
if let Some(path) = dir.to_path() {
|
||||
self.launcher.create(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -916,6 +953,12 @@ impl Actions {
|
|||
}
|
||||
return;
|
||||
}
|
||||
Action::EditLauncher => {
|
||||
if let Some(path) = uris.first().and_then(|u| u.to_path()) {
|
||||
self.report(self.launcher.edit(path));
|
||||
}
|
||||
return;
|
||||
}
|
||||
Action::EditTags => {
|
||||
let files: Vec<_> = uris.iter().filter_map(|u| u.to_path()).collect();
|
||||
if !files.is_empty() {
|
||||
|
|
@ -1076,6 +1119,11 @@ impl Actions {
|
|||
self.bridge.submit(JobKind::CreateFile(dir.join(&name)));
|
||||
}
|
||||
|
||||
/// One file and no folder is selected.
|
||||
fn one_file(&self, pane: &Pane) -> bool {
|
||||
pane.model.selected_uris().len() == 1 && !pane.model.selection_is_dir()
|
||||
}
|
||||
|
||||
/// Packs the selection into one archive next to it, named after the one item (or the
|
||||
/// folder), in the background.
|
||||
fn compress(&self, pane: &Pane, format: Format) {
|
||||
|
|
@ -1157,7 +1205,12 @@ impl Actions {
|
|||
}
|
||||
let cmd = tools::extract_command(&archive, &target)
|
||||
.ok_or("No tool here unpacks this archive")?;
|
||||
tools::run_to_end(cmd, cancel)?;
|
||||
let done = tools::run_to_end(cmd, cancel);
|
||||
if make && done.is_err() {
|
||||
// Nothing came out: no empty folder stays (one with files does).
|
||||
let _ = std::fs::remove_dir(&target);
|
||||
}
|
||||
done?;
|
||||
}
|
||||
Ok(format!("Extracted {title}"))
|
||||
});
|
||||
|
|
|
|||
|
|
@ -119,7 +119,7 @@ fn split_list(value: &str) -> Vec<String> {
|
|||
}
|
||||
|
||||
/// Undoes the desktop entry value escapes (`\s \n \t \r \\`).
|
||||
fn unescape(value: &str) -> String {
|
||||
pub fn unescape(value: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut chars = value.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
|
|
@ -140,7 +140,7 @@ fn unescape(value: &str) -> String {
|
|||
}
|
||||
|
||||
/// `Name[de_DE]` suffixes to try, most specific first, from `LC_MESSAGES` / `LANG`.
|
||||
fn locale_suffixes() -> Vec<String> {
|
||||
pub fn locale_suffixes() -> Vec<String> {
|
||||
let lang = ["LC_ALL", "LC_MESSAGES", "LANG"]
|
||||
.iter()
|
||||
.find_map(|v| std::env::var(v).ok().filter(|v| !v.is_empty()))
|
||||
|
|
@ -584,6 +584,17 @@ struct ThemeDir {
|
|||
theme: usize,
|
||||
}
|
||||
|
||||
impl ThemeDir {
|
||||
/// How far its icons are from `size` px; scalable ones match any size.
|
||||
fn distance(&self, size: u32) -> u32 {
|
||||
if self.scalable {
|
||||
0
|
||||
} else {
|
||||
self.size.abs_diff(size) + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a theme directory's icons are for.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum IconContext {
|
||||
|
|
@ -592,13 +603,25 @@ pub enum IconContext {
|
|||
Places,
|
||||
/// File types.
|
||||
Types,
|
||||
Devices,
|
||||
/// Emblems, states, actions and emoticons.
|
||||
Symbols,
|
||||
/// Everything drawn at a size worth showing (no small tool and panel icons).
|
||||
Any,
|
||||
}
|
||||
|
||||
impl IconContext {
|
||||
const ALL: [(Self, &str, &str); 3] = [
|
||||
const ALL: [(Self, &str, &str); 9] = [
|
||||
(Self::Apps, "Applications", "apps"),
|
||||
(Self::Places, "Places", "places"),
|
||||
(Self::Types, "MimeTypes", "mimetypes"),
|
||||
(Self::Devices, "Devices", "devices"),
|
||||
(Self::Symbols, "Emblems", "emblems"),
|
||||
(Self::Symbols, "Status", "status"),
|
||||
(Self::Symbols, "Actions", "actions"),
|
||||
(Self::Symbols, "Emotes", "emotes"),
|
||||
// Programs by kind: some themes keep all their app icons there too.
|
||||
(Self::Apps, "Categories", "categories"),
|
||||
];
|
||||
|
||||
/// By the directory's `Context` key, else by its path.
|
||||
|
|
@ -707,7 +730,10 @@ impl IconTheme {
|
|||
for (index, theme) in chain.iter().enumerate() {
|
||||
for base in &bases {
|
||||
let mut found = theme_dirs(base, theme, index);
|
||||
found.retain(|d| d.context == Some(context));
|
||||
found.retain(|d| match context {
|
||||
IconContext::Any => d.scalable || d.size >= 48,
|
||||
_ => d.context == Some(context),
|
||||
});
|
||||
dirs.extend(found);
|
||||
}
|
||||
}
|
||||
|
|
@ -734,6 +760,34 @@ impl IconTheme {
|
|||
names
|
||||
}
|
||||
|
||||
/// Every icon by name with its file at about `size` px and what it is for, sorted (no
|
||||
/// `-symbolic` ones).
|
||||
pub fn all(&self, size: u32) -> Vec<(String, PathBuf, Option<IconContext>)> {
|
||||
let mut dirs: Vec<&ThemeDir> = self.dirs.iter().collect();
|
||||
dirs.sort_by_key(|d| (d.theme, d.distance(size)));
|
||||
let mut icons: std::collections::BTreeMap<String, (PathBuf, Option<IconContext>)> =
|
||||
Default::default();
|
||||
let files = dirs
|
||||
.iter()
|
||||
.filter_map(|d| Some((d.context, fs::read_dir(&d.path).ok()?)))
|
||||
.flat_map(|(context, files)| files.map(move |f| (context, f)));
|
||||
for (context, entry) in files {
|
||||
let Ok(entry) = entry else { continue };
|
||||
let Ok(name) = entry.file_name().into_string() else {
|
||||
continue;
|
||||
};
|
||||
let stem = name
|
||||
.strip_suffix(".svg")
|
||||
.or_else(|| name.strip_suffix(".png"));
|
||||
if let Some(stem) = stem.filter(|s| !s.ends_with("-symbolic")) {
|
||||
icons
|
||||
.entry(stem.to_owned())
|
||||
.or_insert_with(|| (entry.path(), context));
|
||||
}
|
||||
}
|
||||
icons.into_iter().map(|(n, (p, c))| (n, p, c)).collect()
|
||||
}
|
||||
|
||||
/// The file of icon `name` at about `size` px: an absolute path as is, else the closest
|
||||
/// size of the first theme that has it, then `pixmaps`. `None` when nothing is installed
|
||||
/// (callers draw a glyph).
|
||||
|
|
@ -741,16 +795,9 @@ impl IconTheme {
|
|||
if name.starts_with('/') {
|
||||
return Some(PathBuf::from(name)).filter(|p| p.is_file());
|
||||
}
|
||||
// The first theme that has it; fixed sizes by distance, scalable ones match any size.
|
||||
let distance = |d: &ThemeDir| {
|
||||
if d.scalable {
|
||||
0
|
||||
} else {
|
||||
d.size.abs_diff(size) + 1
|
||||
}
|
||||
};
|
||||
// The first theme that has it.
|
||||
let mut order: Vec<&ThemeDir> = self.dirs.iter().collect();
|
||||
order.sort_by_key(|d| (d.theme, distance(d)));
|
||||
order.sort_by_key(|d| (d.theme, d.distance(size)));
|
||||
for dir in order {
|
||||
for ext in ["svg", "png"] {
|
||||
let file = dir.path.join(format!("{name}.{ext}"));
|
||||
|
|
|
|||
|
|
@ -113,6 +113,19 @@ pub fn places_theme() -> &'static IconTheme {
|
|||
THEME.get_or_init(|| IconTheme::load(IconContext::Places))
|
||||
}
|
||||
|
||||
/// The theme's icons of every kind.
|
||||
pub fn any_theme() -> &'static IconTheme {
|
||||
static THEME: OnceLock<IconTheme> = OnceLock::new();
|
||||
THEME.get_or_init(|| IconTheme::load(IconContext::Any))
|
||||
}
|
||||
|
||||
/// The file of the theme icon (or image path) `name`: a folder icon before any other.
|
||||
pub fn find(name: &str) -> Option<PathBuf> {
|
||||
places_theme()
|
||||
.find(name, SIZE)
|
||||
.or_else(|| any_theme().find(name, SIZE))
|
||||
}
|
||||
|
||||
/// The theme's picture of the type `mime`, looked up once.
|
||||
fn type_icon(mime: &str) -> Option<PathBuf> {
|
||||
static THEME: OnceLock<IconTheme> = OnceLock::new();
|
||||
|
|
|
|||
67
crates/tunal/src/file_picker.rs
Normal file
67
crates/tunal/src/file_picker.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
//! The desktop's file picker, for the fields that take a file's path.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::{Rc, Weak};
|
||||
|
||||
use slint::ComponentHandle;
|
||||
|
||||
use crate::shell::{Shell, places};
|
||||
use crate::{FileKind, FilePicks, MainWindow};
|
||||
|
||||
const IMAGES: [&str; 2] = ["image/png", "image/jpeg"];
|
||||
const ICONS: [&str; 5] = [
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/svg+xml",
|
||||
"image/webp",
|
||||
"image/gif",
|
||||
];
|
||||
|
||||
pub fn attach(ui: &MainWindow, shell: &Rc<Shell>) {
|
||||
let shell: Weak<Shell> = Rc::downgrade(shell);
|
||||
let weak = ui.as_weak();
|
||||
let me = shell.clone();
|
||||
ui.global::<FilePicks>().on_failed(move || {
|
||||
if let Some(shell) = me.upgrade() {
|
||||
shell.notify("This desktop has no file picker.".into());
|
||||
}
|
||||
});
|
||||
ui.global::<FilePicks>()
|
||||
.on_pick(move |request, kind, current| {
|
||||
// Where the field's file is, else a sensible folder for its kind.
|
||||
let current = Path::new(current.trim())
|
||||
.parent()
|
||||
.filter(|p| p.is_absolute() && kind != FileKind::Program)
|
||||
.map(Path::to_owned);
|
||||
let folder: Option<PathBuf> = current.or_else(|| match kind {
|
||||
FileKind::Key => Some(places::home().join(".ssh")),
|
||||
_ => shell.upgrade()?.active_dir()?.to_path(),
|
||||
});
|
||||
let (title, types): (_, &'static [&'static str]) = match kind {
|
||||
FileKind::Key => ("Choose a key file", &[]),
|
||||
FileKind::Program => ("Choose a program", &[]),
|
||||
FileKind::Cover => ("Choose a cover image", &IMAGES),
|
||||
_ => ("Choose an image", &ICONS),
|
||||
};
|
||||
let ui = weak.clone();
|
||||
std::thread::spawn(move || {
|
||||
let picked = tunal_theme::pick_file(title, types, folder.as_deref());
|
||||
let _ = ui.upgrade_in_event_loop(move |ui| match picked {
|
||||
Ok(Some(path)) => {
|
||||
let picks = ui.global::<FilePicks>();
|
||||
let path = path.to_string_lossy();
|
||||
picks.set_path(match kind {
|
||||
FileKind::Program => crate::launcher::quote(&path).into(),
|
||||
_ => path.as_ref().into(),
|
||||
});
|
||||
picks.set_done(request);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
eprintln!("tunal: file picker: {e}");
|
||||
ui.global::<FilePicks>().invoke_failed();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -125,13 +125,9 @@ impl Appearance {
|
|||
};
|
||||
let name = ui.get_appearance_name().trim().to_owned();
|
||||
let image = ui.get_appearance_image().trim().to_owned();
|
||||
let pick = PICKS
|
||||
.with(|p| {
|
||||
p.borrow()
|
||||
.get(usize::try_from(ui.get_appearance_choice()).unwrap_or(0))
|
||||
.cloned()
|
||||
})
|
||||
.unwrap_or(Pick::Default);
|
||||
let pick = PICKS.with(|p| {
|
||||
icon_picker::picked(p, ui.get_appearance_choice(), &ui.get_appearance_browsed())
|
||||
});
|
||||
if !icon_picker::valid_image(&image) {
|
||||
ui.set_appearance_error(icon_picker::NO_IMAGE.into());
|
||||
return;
|
||||
|
|
@ -187,7 +183,18 @@ fn fill(ui: &MainWindow, meta: &DirMeta, themed: Vec<(String, Option<PathBuf>)>)
|
|||
{
|
||||
ui.set_appearance_image(icon.into());
|
||||
}
|
||||
ui.set_appearance_choice(current.unwrap_or(0) as i32);
|
||||
// One the short list lacks came from the browser.
|
||||
let browsed = match current {
|
||||
None => icon_picker::browsed(meta.icon().unwrap_or_default()),
|
||||
Some(_) => Default::default(),
|
||||
};
|
||||
let outside = !browsed.label.is_empty();
|
||||
ui.set_appearance_browsed(browsed);
|
||||
ui.set_appearance_choice(if outside {
|
||||
-1
|
||||
} else {
|
||||
current.unwrap_or(0) as i32
|
||||
});
|
||||
ui.set_appearance_icons(ModelRc::new(VecModel::from(cells)));
|
||||
PICKS.with(|p| *p.borrow_mut() = picks);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -49,9 +49,7 @@ pub fn from_meta(meta: &DirMeta) -> Option<Look> {
|
|||
let look = Look {
|
||||
name: meta.name(),
|
||||
glyph: meta.glyph(),
|
||||
picture: meta
|
||||
.icon()
|
||||
.and_then(|i| file_icons::places_theme().find(i, 64)),
|
||||
picture: meta.icon().and_then(file_icons::find),
|
||||
};
|
||||
(look != Look::default()).then_some(look)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,15 @@
|
|||
//! The icons the icon picker offers (folder appearance, sidebar entries).
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::IconChoice;
|
||||
use slint::{ComponentHandle, Model, ModelNotify, ModelRc, ModelTracker, VecModel};
|
||||
|
||||
use crate::desktop_apps::IconContext;
|
||||
use crate::file_icons;
|
||||
use crate::folder::look;
|
||||
use crate::{IconBrowser, IconChoice, IconRow, MainWindow};
|
||||
|
||||
/// Material glyphs the picker offers (label, codepoint).
|
||||
const GLYPHS: [(&str, char); 17] = [
|
||||
|
|
@ -28,7 +33,7 @@ const GLYPHS: [(&str, char); 17] = [
|
|||
];
|
||||
|
||||
/// How many theme icons the picker lists.
|
||||
const THEME_ICONS: usize = 18;
|
||||
const THEME_ICONS: usize = 16;
|
||||
|
||||
/// What a picker cell stands for (`Default` is cell 0).
|
||||
#[derive(Clone)]
|
||||
|
|
@ -74,6 +79,15 @@ pub fn cells(
|
|||
picks.push(Pick::Glyph(glyph));
|
||||
cells.push(choice(label, &glyph.to_string(), None));
|
||||
}
|
||||
add_themed(&mut picks, &mut cells, themed);
|
||||
(picks, cells)
|
||||
}
|
||||
|
||||
fn add_themed(
|
||||
picks: &mut Vec<Pick>,
|
||||
cells: &mut Vec<IconChoice>,
|
||||
themed: Vec<(String, Option<PathBuf>)>,
|
||||
) {
|
||||
for (name, file) in themed {
|
||||
let Some(image) = file.as_deref().and_then(look::picture) else {
|
||||
continue;
|
||||
|
|
@ -81,6 +95,16 @@ pub fn cells(
|
|||
cells.push(choice(&name, "", Some(image)));
|
||||
picks.push(Pick::Theme(name));
|
||||
}
|
||||
}
|
||||
|
||||
/// Cells of theme icons alone, after the default one.
|
||||
pub fn theme_cells(
|
||||
default: &str,
|
||||
themed: Vec<(String, Option<PathBuf>)>,
|
||||
) -> (Vec<Pick>, Vec<IconChoice>) {
|
||||
let mut picks = vec![Pick::Default];
|
||||
let mut cells = vec![choice("Default", default, None)];
|
||||
add_themed(&mut picks, &mut cells, themed);
|
||||
(picks, cells)
|
||||
}
|
||||
|
||||
|
|
@ -90,3 +114,118 @@ pub fn valid_image(path: &str) -> bool {
|
|||
}
|
||||
|
||||
pub const NO_IMAGE: &str = "That image file doesn't exist. Use its full path.";
|
||||
|
||||
/// What the dialog's `choice` stands for: a cell, or (-1) the icon the browser gave.
|
||||
pub fn picked(picks: &RefCell<Vec<Pick>>, choice: i32, browsed: &IconChoice) -> Pick {
|
||||
if choice < 0 && !browsed.label.is_empty() {
|
||||
return Pick::Theme(browsed.label.to_string());
|
||||
}
|
||||
let cell = usize::try_from(choice).ok();
|
||||
cell.and_then(|i| picks.borrow().get(i).cloned())
|
||||
.unwrap_or(Pick::Default)
|
||||
}
|
||||
|
||||
/// The browser's cell for the theme icon `name`, empty for none by that name.
|
||||
pub fn browsed(name: &str) -> IconChoice {
|
||||
match file_icons::find(name).as_deref().and_then(look::picture) {
|
||||
Some(image) if !name.is_empty() && !name.starts_with('/') => choice(name, "", Some(image)),
|
||||
_ => IconChoice::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Name, file and what it is for.
|
||||
type ThemeIcon = (String, PathBuf, Option<IconContext>);
|
||||
|
||||
/// The browser's categories, in the order of its chips (the first shows all).
|
||||
const CATEGORIES: [Option<IconContext>; 6] = [
|
||||
None,
|
||||
Some(IconContext::Places),
|
||||
Some(IconContext::Apps),
|
||||
Some(IconContext::Types),
|
||||
Some(IconContext::Devices),
|
||||
Some(IconContext::Symbols),
|
||||
];
|
||||
|
||||
/// Every icon of the theme with its file, read once (off the UI thread).
|
||||
fn all_icons() -> &'static [ThemeIcon] {
|
||||
static ALL: OnceLock<Vec<ThemeIcon>> = OnceLock::new();
|
||||
ALL.get_or_init(|| file_icons::any_theme().all(64))
|
||||
}
|
||||
|
||||
/// Rows of the browser; their pictures load as the list shows them.
|
||||
struct Rows {
|
||||
found: Vec<usize>,
|
||||
columns: usize,
|
||||
notify: ModelNotify,
|
||||
}
|
||||
|
||||
impl Model for Rows {
|
||||
type Data = IconRow;
|
||||
|
||||
fn row_count(&self) -> usize {
|
||||
self.found.len().div_ceil(self.columns)
|
||||
}
|
||||
|
||||
fn row_data(&self, row: usize) -> Option<IconRow> {
|
||||
let cells: Vec<IconChoice> = self
|
||||
.found
|
||||
.chunks(self.columns)
|
||||
.nth(row)?
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
let (name, file, _) = &all_icons()[i];
|
||||
choice(name, "", look::picture(file))
|
||||
})
|
||||
.collect();
|
||||
Some(IconRow {
|
||||
cells: ModelRc::new(VecModel::from(cells)),
|
||||
})
|
||||
}
|
||||
|
||||
fn model_tracker(&self) -> &dyn ModelTracker {
|
||||
&self.notify
|
||||
}
|
||||
}
|
||||
|
||||
fn show(ui: &MainWindow, text: &str, category: i32, columns: i32) {
|
||||
let category = usize::try_from(category).ok();
|
||||
let category = category.and_then(|c| CATEGORIES.get(c).copied().flatten());
|
||||
let text = text.trim().to_lowercase();
|
||||
let found: Vec<usize> = all_icons()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, _, context))| category.is_none() || *context == category)
|
||||
.filter(|(_, (name, ..))| {
|
||||
let name = name.to_lowercase();
|
||||
text.split_whitespace().all(|w| name.contains(w))
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
let browser = ui.global::<IconBrowser>();
|
||||
browser.set_found(found.len() as i32);
|
||||
browser.set_rows(ModelRc::new(Rows {
|
||||
found,
|
||||
columns: columns.max(1) as usize,
|
||||
notify: ModelNotify::default(),
|
||||
}));
|
||||
}
|
||||
|
||||
/// Serves the icon browser of `ui`.
|
||||
pub fn attach(ui: &MainWindow) {
|
||||
let weak = ui.as_weak();
|
||||
ui.global::<IconBrowser>()
|
||||
.on_search(move |text, category, columns| {
|
||||
let Some(ui) = weak.upgrade() else {
|
||||
return;
|
||||
};
|
||||
if ui.global::<IconBrowser>().get_found() >= 0 {
|
||||
show(&ui, &text, category, columns);
|
||||
return;
|
||||
}
|
||||
let weak = weak.clone();
|
||||
std::thread::spawn(move || {
|
||||
all_icons();
|
||||
let _ = weak.upgrade_in_event_loop(move |ui| show(&ui, &text, category, columns));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
|||
293
crates/tunal/src/launcher.rs
Normal file
293
crates/tunal/src/launcher.rs
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
//! The launcher dialog: makes a desktop entry, or changes the plain parts of one (name,
|
||||
//! description, command, icon, terminal) and keeps everything else in it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use slint::{ComponentHandle, ModelRc, VecModel};
|
||||
use tunal_dirmeta::DirMeta;
|
||||
|
||||
use crate::desktop_apps::{locale_suffixes, unescape};
|
||||
use crate::icon_picker::{self, Pick};
|
||||
use crate::{LauncherData, MainWindow};
|
||||
|
||||
const ENTRY: &str = "Desktop Entry";
|
||||
|
||||
/// The plain program icon, drawn while a launcher has none.
|
||||
const GLYPH: &str = "\u{eb8e}";
|
||||
|
||||
/// Theme icons the picker offers, where the theme has them.
|
||||
const ICONS: [&str; 15] = [
|
||||
"utilities-terminal",
|
||||
"applications-games",
|
||||
"applications-internet",
|
||||
"applications-multimedia",
|
||||
"applications-graphics",
|
||||
"applications-office",
|
||||
"applications-development",
|
||||
"applications-system",
|
||||
"applications-utilities",
|
||||
"system-file-manager",
|
||||
"web-browser",
|
||||
"text-editor",
|
||||
"accessories-calculator",
|
||||
"preferences-system",
|
||||
"system-run",
|
||||
];
|
||||
|
||||
enum Target {
|
||||
/// A new file in this folder.
|
||||
New(PathBuf),
|
||||
Edit(PathBuf),
|
||||
}
|
||||
|
||||
type Made = Box<dyn Fn(&OsStr)>;
|
||||
|
||||
pub struct Launcher {
|
||||
ui: slint::Weak<MainWindow>,
|
||||
target: RefCell<Option<Target>>,
|
||||
picks: RefCell<Vec<Pick>>,
|
||||
/// An icon the theme here lacks: stays while none is chosen.
|
||||
kept_icon: RefCell<Option<String>>,
|
||||
/// Called with the file name of a new launcher, before it is written.
|
||||
made: RefCell<Made>,
|
||||
}
|
||||
|
||||
/// `path` is a desktop entry by its name.
|
||||
pub fn is_launcher(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e == "desktop")
|
||||
}
|
||||
|
||||
/// `path` as the command of a launcher: quoted when it has to be.
|
||||
pub fn quote(path: &str) -> String {
|
||||
let path = path.replace('%', "%%");
|
||||
if path
|
||||
.chars()
|
||||
.all(|c| c.is_alphanumeric() || "/._-+%".contains(c))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
let mut out = String::from("\"");
|
||||
for c in path.chars() {
|
||||
if matches!(c, '"' | '`' | '$' | '\\') {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
impl Launcher {
|
||||
pub fn attach(ui: &MainWindow) -> Rc<Self> {
|
||||
let me = Rc::new(Self {
|
||||
ui: ui.as_weak(),
|
||||
target: RefCell::new(None),
|
||||
picks: RefCell::default(),
|
||||
kept_icon: RefCell::default(),
|
||||
made: RefCell::new(Box::new(|_| {})),
|
||||
});
|
||||
let weak = Rc::downgrade(&me);
|
||||
ui.on_launcher_saved(move || {
|
||||
if let Some(me) = weak.upgrade() {
|
||||
me.save();
|
||||
}
|
||||
});
|
||||
me
|
||||
}
|
||||
|
||||
pub fn on_made(&self, f: impl Fn(&OsStr) + 'static) {
|
||||
*self.made.borrow_mut() = Box::new(f);
|
||||
}
|
||||
|
||||
pub fn create(&self, dir: PathBuf) {
|
||||
self.open(Target::New(dir), &DirMeta::default());
|
||||
}
|
||||
|
||||
pub fn edit(&self, path: PathBuf) -> Result<(), String> {
|
||||
let text =
|
||||
fs::read_to_string(&path).map_err(|e| format!("Can't read the launcher: {e}"))?;
|
||||
let meta = DirMeta::parse(&text);
|
||||
if meta.get(ENTRY, "Type").is_some_and(|t| t != "Application") {
|
||||
return Err("This file is a link, not an app launcher".into());
|
||||
}
|
||||
self.open(Target::Edit(path), &meta);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open(&self, target: Target, meta: &DirMeta) {
|
||||
let Some(ui) = self.ui.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let get = |key: &str| unescape(meta.get(ENTRY, key).unwrap_or_default());
|
||||
let themed = ICONS
|
||||
.iter()
|
||||
.map(|n| ((*n).to_owned(), crate::file_icons::find(n)))
|
||||
.collect();
|
||||
let (picks, cells) = icon_picker::theme_cells(GLYPH, themed);
|
||||
let icon = get("Icon");
|
||||
let current = picks.iter().position(|p| match p {
|
||||
Pick::Default => icon.is_empty(),
|
||||
Pick::Theme(name) => *name == icon,
|
||||
Pick::Glyph(_) => false,
|
||||
});
|
||||
let browsed = match current {
|
||||
None => icon_picker::browsed(&icon),
|
||||
Some(_) => Default::default(),
|
||||
};
|
||||
let unknown = current.is_none() && browsed.label.is_empty() && !icon.starts_with('/');
|
||||
*self.kept_icon.borrow_mut() = unknown.then(|| icon.clone());
|
||||
ui.set_launcher(LauncherData {
|
||||
editing: matches!(target, Target::Edit(_)),
|
||||
name: localized(meta, "Name").into(),
|
||||
comment: localized(meta, "Comment").into(),
|
||||
command: get("Exec").into(),
|
||||
terminal: get("Terminal") == "true",
|
||||
choice: match current {
|
||||
Some(i) => i as i32,
|
||||
None if !browsed.label.is_empty() => -1,
|
||||
None => 0,
|
||||
},
|
||||
image_path: if icon.starts_with('/') {
|
||||
icon.into()
|
||||
} else {
|
||||
"".into()
|
||||
},
|
||||
browsed,
|
||||
error: "".into(),
|
||||
});
|
||||
ui.set_launcher_icons(ModelRc::new(VecModel::from(cells)));
|
||||
*self.picks.borrow_mut() = picks;
|
||||
*self.target.borrow_mut() = Some(target);
|
||||
ui.invoke_show_launcher();
|
||||
}
|
||||
|
||||
fn save(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let mut data = ui.get_launcher();
|
||||
match self.write(&data) {
|
||||
Ok(()) => ui.invoke_close_launcher(),
|
||||
Err(message) => {
|
||||
data.error = message.into();
|
||||
ui.set_launcher(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, data: &LauncherData) -> Result<(), String> {
|
||||
let target = self.target.borrow();
|
||||
let Some(target) = target.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
let (name, command) = (data.name.trim(), data.command.trim());
|
||||
if name.is_empty() {
|
||||
return Err("Give the launcher a name.".into());
|
||||
}
|
||||
if command.is_empty() {
|
||||
return Err("Enter the command it runs, or choose a program.".into());
|
||||
}
|
||||
let image = data.image_path.trim();
|
||||
if !icon_picker::valid_image(image) {
|
||||
return Err(icon_picker::NO_IMAGE.into());
|
||||
}
|
||||
let icon = match icon_picker::picked(&self.picks, data.choice, &data.browsed) {
|
||||
_ if !image.is_empty() => Some(image.to_owned()),
|
||||
Pick::Theme(name) => Some(name),
|
||||
Pick::Glyph(_) | Pick::Default => self.kept_icon.borrow().clone(),
|
||||
};
|
||||
let apply = |meta: &mut DirMeta| {
|
||||
meta.set(ENTRY, "Type", Some("Application"));
|
||||
localize(meta, "Name", name);
|
||||
localize(meta, "Comment", data.comment.trim());
|
||||
meta.set(ENTRY, "Exec", Some(&command.replace('\\', "\\\\")));
|
||||
meta.set(ENTRY, "Icon", icon.as_deref());
|
||||
let terminal = if data.terminal { "true" } else { "false" };
|
||||
meta.set(ENTRY, "Terminal", Some(terminal));
|
||||
};
|
||||
let failed = |e: io::Error| match e.kind() {
|
||||
io::ErrorKind::PermissionDenied => "You don't have permission to write here.".into(),
|
||||
_ => format!("Couldn't save the launcher: {e}"),
|
||||
};
|
||||
match target {
|
||||
Target::Edit(path) => {
|
||||
let mut meta = DirMeta::parse(&fs::read_to_string(path).map_err(failed)?);
|
||||
apply(&mut meta);
|
||||
replace(path, &meta.to_string()).map_err(failed)
|
||||
}
|
||||
Target::New(dir) => {
|
||||
let mut meta = DirMeta::default();
|
||||
apply(&mut meta);
|
||||
// The name may hold what a file name can't.
|
||||
let stem = name.replace('/', "-");
|
||||
let stem = stem.trim_start_matches('.');
|
||||
for n in 1.. {
|
||||
let file = match n {
|
||||
1 => format!("{stem}.desktop"),
|
||||
n => format!("{stem} {n}.desktop"),
|
||||
};
|
||||
let path = dir.join(&file);
|
||||
if path.symlink_metadata().is_ok() {
|
||||
continue;
|
||||
}
|
||||
(self.made.borrow())(OsStr::new(&file));
|
||||
// Executable, so desktops trust it to start.
|
||||
let mut out = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o755)
|
||||
.open(&path)
|
||||
.map_err(failed)?;
|
||||
return out.write_all(meta.to_string().as_bytes()).map_err(failed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts `text` in the file at `path` (the one a link leads to) in one step.
|
||||
fn replace(path: &Path, text: &str) -> io::Result<()> {
|
||||
let path = path.canonicalize()?;
|
||||
let mode = path.metadata()?.permissions().mode();
|
||||
let mut temp = path.clone().into_os_string();
|
||||
temp.push(format!(".tunal-{}", std::process::id()));
|
||||
let result = fs::write(&temp, text)
|
||||
.and_then(|()| fs::set_permissions(&temp, fs::Permissions::from_mode(mode)))
|
||||
.and_then(|()| fs::rename(&temp, &path));
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&temp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The key this language shows for `key`: `Name[de]`, else `Name`.
|
||||
fn shown_key(meta: &DirMeta, key: &str) -> String {
|
||||
locale_suffixes()
|
||||
.iter()
|
||||
.map(|l| format!("{key}[{l}]"))
|
||||
.find(|k| meta.get(ENTRY, k).is_some())
|
||||
.unwrap_or_else(|| key.to_owned())
|
||||
}
|
||||
|
||||
fn localized(meta: &DirMeta, key: &str) -> String {
|
||||
unescape(meta.get(ENTRY, &shown_key(meta, key)).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Sets what this language shows for `key`; other languages keep theirs.
|
||||
fn localize(meta: &mut DirMeta, key: &str, value: &str) {
|
||||
let shown = shown_key(meta, key);
|
||||
// Removing a translation would bring the plain text back: that goes too.
|
||||
if value.is_empty() {
|
||||
meta.set(ENTRY, &shown, None);
|
||||
meta.set(ENTRY, key, None);
|
||||
} else {
|
||||
meta.set(ENTRY, &shown, Some(&value.replace('\\', "\\\\")));
|
||||
}
|
||||
}
|
||||
|
|
@ -5,11 +5,13 @@ mod desktop_apps;
|
|||
mod devices_bridge;
|
||||
mod dnd;
|
||||
mod file_icons;
|
||||
mod file_picker;
|
||||
mod folder;
|
||||
mod icon_picker;
|
||||
mod icons;
|
||||
mod jobs_bridge;
|
||||
mod keymap;
|
||||
mod launcher;
|
||||
mod menus;
|
||||
mod native;
|
||||
mod net_bridge;
|
||||
|
|
@ -129,6 +131,8 @@ fn window(
|
|||
let mtp = devices_bridge::register(&mut locations);
|
||||
let net = net_bridge::register(&mut locations, &ui);
|
||||
let shell = shell::Shell::attach(&ui, locations, tabs, blocking);
|
||||
file_picker::attach(&ui, &shell);
|
||||
icon_picker::attach(&ui);
|
||||
devices_bridge::attach(&shell, mtp);
|
||||
net_bridge::attach(&ui, &shell, net);
|
||||
// `TUNAL_SETTINGS=<page 0-7>` opens the settings dialog (screenshots); on the Shortcuts
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ impl Context {
|
|||
"run-in-terminal",
|
||||
"open-with",
|
||||
"edit-tags",
|
||||
"edit-launcher",
|
||||
"-",
|
||||
"cut",
|
||||
"copy",
|
||||
|
|
|
|||
|
|
@ -397,7 +397,12 @@ impl PlayerUi {
|
|||
let Some(track) = track.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let to = to.min(track.duration);
|
||||
// A length not known yet is no limit.
|
||||
let to = if track.duration.is_zero() {
|
||||
to
|
||||
} else {
|
||||
to.min(track.duration)
|
||||
};
|
||||
track.position = to;
|
||||
to
|
||||
};
|
||||
|
|
|
|||
|
|
@ -81,6 +81,8 @@ pub struct Shell {
|
|||
pane_rows: Rc<VecModel<PaneData>>,
|
||||
places: RefCell<Places>,
|
||||
menu_target: Cell<Option<MenuTarget>>,
|
||||
/// The sidebar entry last opened.
|
||||
opened_place: Cell<Option<(Section, usize)>>,
|
||||
/// Bumped per completion request; older results are dropped.
|
||||
completion: Arc<AtomicU64>,
|
||||
/// The file actions; set once the shell exists.
|
||||
|
|
@ -129,6 +131,7 @@ impl Shell {
|
|||
pane_rows: Rc::new(VecModel::default()),
|
||||
places: RefCell::new(Places::load()),
|
||||
menu_target: Cell::new(None),
|
||||
opened_place: Cell::new(None),
|
||||
completion: Arc::new(AtomicU64::new(0)),
|
||||
actions: OnceCell::new(),
|
||||
settings: OnceCell::new(),
|
||||
|
|
@ -263,8 +266,7 @@ impl Shell {
|
|||
|
||||
/// A new tab at the active pane's folder.
|
||||
fn new_tab(&self) {
|
||||
let dir = self.active().and_then(|p| p.dir());
|
||||
self.open_tab(vec![dir.unwrap_or_else(|| Uri::from_path(&places::home()))]);
|
||||
self.open_tab(vec![Uri::from_path(&places::home())]);
|
||||
self.show_current();
|
||||
}
|
||||
|
||||
|
|
@ -643,13 +645,28 @@ impl Shell {
|
|||
|
||||
fn show_sidebar(&self, ui: &MainWindow, dir: Option<&Uri>) {
|
||||
let places = self.places.borrow();
|
||||
let current = self.current_place(&places, dir);
|
||||
// A folded section has no rows; an empty one has its text.
|
||||
let rows = |s: Section| match places.items(s).len() {
|
||||
_ if places.collapsed(s) => 0,
|
||||
n => n.max(1),
|
||||
};
|
||||
let shown = current.filter(|(s, _)| !places.collapsed(*s));
|
||||
ui.set_has_current_place(shown.is_some());
|
||||
if let Some((section, index)) = shown {
|
||||
let before = Section::ALL.into_iter().take_while(|s| *s != section);
|
||||
ui.set_current_place_section(before.clone().count() as i32);
|
||||
ui.set_current_place_rows_before(before.map(rows).sum::<usize>() as i32);
|
||||
ui.set_current_place_row(index as i32);
|
||||
}
|
||||
let sections: Vec<SidebarSection> = Section::ALL
|
||||
.into_iter()
|
||||
.map(|section| {
|
||||
let items: Vec<PlaceItem> = places
|
||||
.items(section)
|
||||
.iter()
|
||||
.map(|p| {
|
||||
.enumerate()
|
||||
.map(|(i, p)| {
|
||||
let (name, tip) = path::shown_name(&p.uri, p.name.clone());
|
||||
let picture = p.picture.as_deref().and_then(look::picture);
|
||||
PlaceItem {
|
||||
|
|
@ -658,7 +675,7 @@ impl Shell {
|
|||
glyph: p.shown_glyph().into(),
|
||||
has_picture: picture.is_some(),
|
||||
picture: picture.unwrap_or_default(),
|
||||
current: Some(&p.uri) == dir,
|
||||
current: current == Some((section, i)),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
|
@ -685,6 +702,18 @@ impl Shell {
|
|||
}
|
||||
}
|
||||
|
||||
/// The sidebar entry for `dir`: the one last opened when several are it.
|
||||
fn current_place(&self, places: &Places, dir: Option<&Uri>) -> Option<(Section, usize)> {
|
||||
let dir = dir?;
|
||||
let is = |(s, i): &(Section, usize)| places.get(*s, *i).is_some_and(|p| p.uri == *dir);
|
||||
self.opened_place.get().filter(is).or_else(|| {
|
||||
Section::ALL
|
||||
.into_iter()
|
||||
.flat_map(|s| (0..places.items(s).len()).map(move |i| (s, i)))
|
||||
.find(is)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn focus_active(&self) {
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
ui.set_focus_request(ui.get_focus_request().wrapping_add(1));
|
||||
|
|
@ -707,6 +736,7 @@ impl Shell {
|
|||
// ---- places -------------------------------------------------------------------------
|
||||
|
||||
fn open_place(&self, section: Section, index: usize, new_tab: bool) {
|
||||
self.opened_place.set(Some((section, index)));
|
||||
if section == Section::Network {
|
||||
crate::net_bridge::open(self, index, new_tab);
|
||||
return;
|
||||
|
|
@ -897,13 +927,33 @@ impl Shell {
|
|||
fn path_accepted(&self, text: &str) {
|
||||
self.complete(String::new());
|
||||
let current = self.active().and_then(|p| p.dir());
|
||||
if let Some(uri) = path::parse(text, current.as_ref()) {
|
||||
self.go(uri);
|
||||
} else {
|
||||
let Some(uri) = path::parse(text, current.as_ref()) else {
|
||||
self.focus_active();
|
||||
return;
|
||||
};
|
||||
// A file's path: its folder, with the file selected.
|
||||
let file = uri.to_path().is_some_and(|p| p.is_file());
|
||||
match (uri.parent(), uri.file_name().map(<[u8]>::to_vec)) {
|
||||
(Some(dir), Some(name)) if file => {
|
||||
self.with_active(|p| {
|
||||
if current.as_ref() == Some(&dir) {
|
||||
p.model.refresh();
|
||||
} else {
|
||||
p.go(dir);
|
||||
}
|
||||
p.model.select_when_shown(name, false);
|
||||
});
|
||||
self.focus_active();
|
||||
}
|
||||
_ => self.go(uri),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder the active pane shows.
|
||||
pub(crate) fn active_dir(&self) -> Option<Uri> {
|
||||
self.active()?.dir()
|
||||
}
|
||||
|
||||
fn go_crumb(&self, index: usize) {
|
||||
if let Some(uri) = self.crumb_uri(index) {
|
||||
self.go(uri);
|
||||
|
|
|
|||
|
|
@ -91,6 +91,11 @@ pub fn text(uri: &Uri) -> String {
|
|||
/// `current`. `.` and `..` are resolved here.
|
||||
pub fn parse(text: &str, current: Option<&Uri>) -> Option<Uri> {
|
||||
let text = text.trim();
|
||||
// A path copied with quotes round it.
|
||||
let text = ['\'', '"']
|
||||
.into_iter()
|
||||
.find_map(|q| text.strip_prefix(q)?.strip_suffix(q))
|
||||
.unwrap_or(text);
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,13 +41,14 @@ impl Shell {
|
|||
ui.set_place_icon_error(icon_picker::NO_IMAGE.into());
|
||||
return;
|
||||
}
|
||||
let choice = usize::try_from(ui.get_place_icon_choice()).unwrap_or(0);
|
||||
let pick = PICKS.with(|p| p.borrow().get(choice).cloned());
|
||||
let pick = PICKS.with(|p| {
|
||||
icon_picker::picked(p, ui.get_place_icon_choice(), &ui.get_place_icon_browsed())
|
||||
});
|
||||
let icon = match pick {
|
||||
_ if !image.is_empty() => Some(image),
|
||||
Some(Pick::Glyph(g)) => Some(g.to_string()),
|
||||
Some(Pick::Theme(name)) => Some(name),
|
||||
Some(Pick::Default) | None => None,
|
||||
Pick::Glyph(g) => Some(g.to_string()),
|
||||
Pick::Theme(name) => Some(name),
|
||||
Pick::Default => None,
|
||||
};
|
||||
ui.invoke_close_place_icon();
|
||||
self.menu_target.set(None);
|
||||
|
|
@ -69,10 +70,26 @@ fn fill(ui: &MainWindow, place: &Place, themed: Vec<(String, Option<std::path::P
|
|||
Pick::Theme(name) => name == icon,
|
||||
});
|
||||
// The theme icons come after the dialog shows: a choice made meanwhile stays.
|
||||
if !late || matches!(current.map(|i| &picks[i]), Some(Pick::Theme(_))) {
|
||||
ui.set_place_icon_choice(current.unwrap_or(0) as i32);
|
||||
}
|
||||
if !late {
|
||||
if late {
|
||||
// One of them may be what the browser's cell shows until now.
|
||||
if let Some(i) = current.filter(|_| {
|
||||
ui.get_place_icon_choice() == -1 && ui.get_place_icon_browsed().label == icon
|
||||
}) {
|
||||
ui.set_place_icon_choice(i as i32);
|
||||
ui.set_place_icon_browsed(Default::default());
|
||||
}
|
||||
} else {
|
||||
let browsed = match current {
|
||||
None => icon_picker::browsed(icon),
|
||||
Some(_) => Default::default(),
|
||||
};
|
||||
let outside = !browsed.label.is_empty();
|
||||
ui.set_place_icon_browsed(browsed);
|
||||
ui.set_place_icon_choice(if outside {
|
||||
-1
|
||||
} else {
|
||||
current.unwrap_or(0) as i32
|
||||
});
|
||||
ui.set_place_icon_image(if icon.starts_with('/') { icon } else { "" }.into());
|
||||
}
|
||||
ui.set_place_icons(ModelRc::new(VecModel::from(cells)));
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ impl Place {
|
|||
self.picture = icon
|
||||
.as_deref()
|
||||
.filter(|i| glyph_of(i).is_none())
|
||||
.and_then(|i| file_icons::places_theme().find(i, 64));
|
||||
.and_then(file_icons::find);
|
||||
self.icon = icon;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -231,35 +231,93 @@ pub fn run_in_terminal(path: &Path) -> Result<(), String> {
|
|||
|
||||
// ---- archives -------------------------------------------------------------------------------
|
||||
|
||||
/// Archive formats Tunal makes.
|
||||
/// Archive formats Tunal makes: everything 7z writes, and compressed tar archives.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Format {
|
||||
TarGz,
|
||||
Zip,
|
||||
SevenZ,
|
||||
Tar,
|
||||
TarGz,
|
||||
TarBz2,
|
||||
TarXz,
|
||||
TarZst,
|
||||
Wim,
|
||||
Gz,
|
||||
Bz2,
|
||||
Xz,
|
||||
}
|
||||
|
||||
impl Format {
|
||||
pub const ALL: [Format; 2] = [Self::TarGz, Self::Zip];
|
||||
pub const ALL: [Format; 11] = [
|
||||
Self::Zip,
|
||||
Self::SevenZ,
|
||||
Self::Tar,
|
||||
Self::TarGz,
|
||||
Self::TarBz2,
|
||||
Self::TarXz,
|
||||
Self::TarZst,
|
||||
Self::Wim,
|
||||
Self::Gz,
|
||||
Self::Bz2,
|
||||
Self::Xz,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::TarGz => "Tar archive (.tar.gz)",
|
||||
Self::Zip => "Zip archive (.zip)",
|
||||
Self::SevenZ => "7z archive (.7z)",
|
||||
Self::Tar => "Tar archive, not compressed (.tar)",
|
||||
Self::TarGz => "Tar archive (.tar.gz)",
|
||||
Self::TarBz2 => "Tar archive (.tar.bz2)",
|
||||
Self::TarXz => "Tar archive (.tar.xz)",
|
||||
Self::TarZst => "Tar archive (.tar.zst)",
|
||||
Self::Wim => "Windows image (.wim)",
|
||||
Self::Gz => "One file, gzip (.gz)",
|
||||
Self::Bz2 => "One file, bzip2 (.bz2)",
|
||||
Self::Xz => "One file, xz (.xz)",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ext(self) -> &'static str {
|
||||
match self {
|
||||
Self::TarGz => ".tar.gz",
|
||||
Self::Zip => ".zip",
|
||||
Self::SevenZ => ".7z",
|
||||
Self::Tar => ".tar",
|
||||
Self::TarGz => ".tar.gz",
|
||||
Self::TarBz2 => ".tar.bz2",
|
||||
Self::TarXz => ".tar.xz",
|
||||
Self::TarZst => ".tar.zst",
|
||||
Self::Wim => ".wim",
|
||||
Self::Gz => ".gz",
|
||||
Self::Bz2 => ".bz2",
|
||||
Self::Xz => ".xz",
|
||||
}
|
||||
}
|
||||
|
||||
/// Packs a single file, no folders.
|
||||
pub fn single(self) -> bool {
|
||||
matches!(self, Self::Gz | Self::Bz2 | Self::Xz)
|
||||
}
|
||||
|
||||
/// The name 7z has for the format, if it makes it in one step.
|
||||
fn seven_type(self) -> Option<&'static str> {
|
||||
Some(match self {
|
||||
Self::Zip => "zip",
|
||||
Self::SevenZ => "7z",
|
||||
Self::Tar => "tar",
|
||||
Self::Wim => "wim",
|
||||
Self::Gz => "gzip",
|
||||
Self::Bz2 => "bzip2",
|
||||
Self::Xz => "xz",
|
||||
Self::TarGz | Self::TarBz2 | Self::TarXz | Self::TarZst => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn tool(name: &'static str) -> Option<&'static Path> {
|
||||
static TOOLS: OnceLock<Vec<(&'static str, Option<PathBuf>)>> = OnceLock::new();
|
||||
let tools = TOOLS.get_or_init(|| {
|
||||
["tar", "bsdtar", "zip", "unzip"]
|
||||
["tar", "bsdtar", "zip", "unzip", "7z", "7zz", "7za"]
|
||||
.into_iter()
|
||||
.map(|n| (n, find_program(n)))
|
||||
.collect()
|
||||
|
|
@ -270,6 +328,11 @@ fn tool(name: &'static str) -> Option<&'static Path> {
|
|||
.and_then(|(_, p)| p.as_deref())
|
||||
}
|
||||
|
||||
/// 7-Zip, under the names it is installed as.
|
||||
fn seven() -> Option<&'static Path> {
|
||||
["7z", "7zz", "7za"].into_iter().find_map(tool)
|
||||
}
|
||||
|
||||
pub fn can_compress(format: Format) -> bool {
|
||||
compress_command(format, Path::new("/"), &[], Path::new("/")).is_some()
|
||||
}
|
||||
|
|
@ -283,20 +346,29 @@ pub fn compress_command(
|
|||
) -> Option<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")?);
|
||||
let mut cmd = match (format, tool("zip"), seven()) {
|
||||
(Format::Zip, Some(zip), _) => {
|
||||
let mut cmd = Command::new(zip);
|
||||
cmd.args(["-r", "-q", "-y"]).arg(dest);
|
||||
cmd
|
||||
}
|
||||
Format::Zip => {
|
||||
let mut cmd = Command::new(tool("bsdtar")?);
|
||||
cmd.args(["--format", "zip", "-cf"]).arg(dest);
|
||||
// Symbolic links as links, names as they are (no wildcards).
|
||||
(_, _, Some(seven)) if let Some(kind) = format.seven_type() => {
|
||||
let mut cmd = Command::new(seven);
|
||||
cmd.arg("a").arg(format!("-t{kind}"));
|
||||
if !format.single() {
|
||||
cmd.arg("-snl");
|
||||
}
|
||||
cmd.args(["-spd", "-y", "-bso0", "-bsp0"]).arg(dest);
|
||||
cmd
|
||||
}
|
||||
_ if format.single() || matches!(format, Format::SevenZ | Format::Wim) => return None,
|
||||
// The ending of `dest` names the format.
|
||||
_ => {
|
||||
let bsdtar = tool("bsdtar");
|
||||
let gnu = tool("tar").filter(|_| format != Format::Zip);
|
||||
let mut cmd = Command::new(bsdtar.or(gnu)?);
|
||||
cmd.arg("-acf").arg(dest);
|
||||
cmd
|
||||
}
|
||||
};
|
||||
|
|
@ -304,23 +376,97 @@ pub fn compress_command(
|
|||
Some(cmd)
|
||||
}
|
||||
|
||||
/// Archive name endings and whether only `bsdtar` reads them.
|
||||
const ARCHIVES: [(&str, bool); 13] = [
|
||||
(".tar", false),
|
||||
(".tar.gz", false),
|
||||
(".tgz", false),
|
||||
(".tar.bz2", false),
|
||||
(".tbz2", false),
|
||||
(".tar.xz", false),
|
||||
(".txz", false),
|
||||
(".tar.zst", false),
|
||||
(".zip", false),
|
||||
(".7z", true),
|
||||
(".rar", true),
|
||||
(".iso", true),
|
||||
(".cpio", true),
|
||||
/// What unpacks an archive, best first.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Reader {
|
||||
/// `bsdtar`, else `tar`.
|
||||
Tar,
|
||||
/// `bsdtar`, else `7z`, else `unzip`.
|
||||
Zip,
|
||||
/// `7z`, else `bsdtar`.
|
||||
Seven,
|
||||
/// `7z` alone.
|
||||
OnlySeven,
|
||||
/// `bsdtar` alone.
|
||||
OnlyBsd,
|
||||
}
|
||||
|
||||
/// Archive name endings; the longest that fits counts.
|
||||
const ARCHIVES: [(&str, Reader); 64] = [
|
||||
(".tar", Reader::Tar),
|
||||
(".tar.gz", Reader::Tar),
|
||||
(".tgz", Reader::Tar),
|
||||
(".tar.bz2", Reader::Tar),
|
||||
(".tbz2", Reader::Tar),
|
||||
(".tbz", Reader::Tar),
|
||||
(".tar.xz", Reader::Tar),
|
||||
(".txz", Reader::Tar),
|
||||
(".tar.zst", Reader::Tar),
|
||||
(".tzst", Reader::Tar),
|
||||
(".tar.lzma", Reader::Tar),
|
||||
(".tlz", Reader::Tar),
|
||||
(".tar.lz4", Reader::OnlyBsd),
|
||||
(".tar.lz", Reader::Tar),
|
||||
(".tar.z", Reader::Tar),
|
||||
(".taz", Reader::Tar),
|
||||
(".zip", Reader::Zip),
|
||||
(".zipx", Reader::Seven),
|
||||
(".jar", Reader::Zip),
|
||||
(".war", Reader::Zip),
|
||||
(".apk", Reader::Zip),
|
||||
(".ipa", Reader::Zip),
|
||||
(".xpi", Reader::Zip),
|
||||
(".appx", Reader::Zip),
|
||||
(".cbz", Reader::Zip),
|
||||
(".7z", Reader::Seven),
|
||||
(".cb7", Reader::Seven),
|
||||
(".rar", Reader::Seven),
|
||||
(".cbr", Reader::Seven),
|
||||
(".iso", Reader::Seven),
|
||||
(".cpio", Reader::Seven),
|
||||
(".cab", Reader::Seven),
|
||||
(".lzh", Reader::Seven),
|
||||
(".lha", Reader::Seven),
|
||||
(".xar", Reader::Seven),
|
||||
(".pkg", Reader::Seven),
|
||||
(".rpm", Reader::Seven),
|
||||
(".deb", Reader::Seven),
|
||||
(".ar", Reader::Seven),
|
||||
(".arj", Reader::OnlySeven),
|
||||
(".wim", Reader::OnlySeven),
|
||||
(".swm", Reader::OnlySeven),
|
||||
(".esd", Reader::OnlySeven),
|
||||
(".msi", Reader::OnlySeven),
|
||||
(".chm", Reader::OnlySeven),
|
||||
(".dmg", Reader::OnlySeven),
|
||||
(".img", Reader::OnlySeven),
|
||||
(".udf", Reader::OnlySeven),
|
||||
(".squashfs", Reader::OnlySeven),
|
||||
(".vhd", Reader::OnlySeven),
|
||||
(".vhdx", Reader::OnlySeven),
|
||||
(".vmdk", Reader::OnlySeven),
|
||||
(".vdi", Reader::OnlySeven),
|
||||
(".qcow2", Reader::OnlySeven),
|
||||
(".7z.001", Reader::OnlySeven),
|
||||
(".zip.001", Reader::OnlySeven),
|
||||
(".rar.001", Reader::OnlySeven),
|
||||
(".gz", Reader::OnlySeven),
|
||||
(".bz2", Reader::OnlySeven),
|
||||
(".xz", Reader::OnlySeven),
|
||||
(".zst", Reader::OnlySeven),
|
||||
(".lzma", Reader::OnlySeven),
|
||||
(".z", Reader::OnlySeven),
|
||||
(".pmd", Reader::OnlySeven),
|
||||
];
|
||||
|
||||
/// The ending of the lower-case archive name `name`, and what reads it.
|
||||
fn archive_kind(name: &str) -> Option<(&'static str, Reader)> {
|
||||
ARCHIVES
|
||||
.into_iter()
|
||||
.filter(|(ext, _)| name.ends_with(ext))
|
||||
.max_by_key(|(ext, _)| ext.len())
|
||||
}
|
||||
|
||||
/// True when `name` is an archive a tool here can unpack.
|
||||
pub fn can_extract(name: &[u8]) -> bool {
|
||||
extract_command(Path::new(OsStr::from_bytes(name)), Path::new("/")).is_some()
|
||||
|
|
@ -329,29 +475,39 @@ pub fn can_extract(name: &[u8]) -> bool {
|
|||
/// The command that unpacks `archive` into `dest`, never overwriting what is there.
|
||||
pub fn extract_command(archive: &Path, dest: &Path) -> Option<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")?);
|
||||
let (_, reader) = archive_kind(&name)?;
|
||||
let tar = |program: &Path| {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.args(["-x", "-k", "-f"])
|
||||
.arg(archive)
|
||||
.arg("-C")
|
||||
.arg(dest);
|
||||
cmd
|
||||
};
|
||||
let seven = || {
|
||||
let mut out = std::ffi::OsString::from("-o");
|
||||
out.push(dest);
|
||||
let mut cmd = Command::new(seven()?);
|
||||
// An empty password: an encrypted archive fails instead of asking on a terminal.
|
||||
cmd.args(["x", "-y", "-aos", "-p", "-spd", "-bso0", "-bsp0"])
|
||||
.arg(out)
|
||||
.arg("--")
|
||||
.arg(archive);
|
||||
Some(cmd)
|
||||
};
|
||||
let unzip = || {
|
||||
let mut cmd = Command::new(tool("unzip")?);
|
||||
cmd.args(["-q", "-n"]).arg(archive).arg("-d").arg(dest);
|
||||
Some(cmd)
|
||||
};
|
||||
let bsd = || tool("bsdtar").map(tar);
|
||||
let mut cmd = match reader {
|
||||
Reader::Tar => bsd().or_else(|| tool("tar").map(tar)),
|
||||
Reader::Zip => bsd().or_else(seven).or_else(unzip),
|
||||
Reader::Seven => seven().or_else(bsd),
|
||||
Reader::OnlySeven => seven(),
|
||||
Reader::OnlyBsd => bsd(),
|
||||
}?;
|
||||
cmd.current_dir(dest);
|
||||
Some(cmd)
|
||||
}
|
||||
|
|
@ -363,11 +519,8 @@ pub fn archive_stem(archive: &Path) -> String {
|
|||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let lower = name.to_lowercase();
|
||||
ARCHIVES
|
||||
.iter()
|
||||
.filter(|(ext, _)| lower.ends_with(ext))
|
||||
archive_kind(&lower)
|
||||
.map(|(ext, _)| ext.len())
|
||||
.max()
|
||||
.filter(|&n| n < name.len())
|
||||
.map_or(name.clone(), |n| name[..name.len() - n].to_string())
|
||||
}
|
||||
|
|
@ -406,7 +559,13 @@ pub fn run_to_end(mut cmd: Command, cancel: &AtomicBool) -> Result<(), String> {
|
|||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
let last = output.lines().rev().find(|l| !l.trim().is_empty());
|
||||
// 7z's last line only counts errors; the ones that start with ERROR say what they are.
|
||||
let mut lines = output.lines().rev().filter(|l| !l.trim().is_empty());
|
||||
let last = lines.clone().find(|l| l.starts_with("ERROR"));
|
||||
let last = last.or_else(|| lines.next());
|
||||
if output.contains("Wrong password") {
|
||||
return Err("This archive needs a password, which Tunal can't enter yet".into());
|
||||
}
|
||||
Err(last.unwrap_or("The archive tool failed").trim().to_string())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,8 +25,9 @@ import { ErrorsDialog } from "dialogs/errors.slint";
|
|||
import { PropertiesDialog, PropertiesInfo, PropRow } from "dialogs/properties.slint";
|
||||
import { OpenWithDialog, AppRow } from "dialogs/open-with.slint";
|
||||
import { FolderAppearanceDialog } from "dialogs/folder-appearance.slint";
|
||||
import { LauncherDialog, LauncherData } from "dialogs/launcher.slint";
|
||||
import { PlaceIconDialog } from "dialogs/place-icon.slint";
|
||||
import { IconChoice } from "components/icon-picker.slint";
|
||||
import { IconChoice, IconBrowser, IconRow } from "components/icon-picker.slint";
|
||||
import { TagEditorDialog, TagEditorData, TagField } from "dialogs/tag-editor.slint";
|
||||
import { TagLookupDialog, TagLookupData, ReleaseRow, MapRow } from "dialogs/tag-lookup.slint";
|
||||
import { SettingsDialog, SettingsData, EditRow, KeyRow } from "dialogs/settings.slint";
|
||||
|
|
@ -36,6 +37,8 @@ import { SecretPromptDialog, SecretPromptData } from "dialogs/secret-prompt.slin
|
|||
import { Dnd, DropAction, DropMenu, DropTarget } from "components/drop-menu.slint";
|
||||
|
||||
export { Theme, Shapes, ShapeKind, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode, GridRow }
|
||||
export { IconBrowser, IconRow, LauncherData }
|
||||
export { FileKind, FilePicks } from "components/text-field.slint";
|
||||
export { ColorPicks, Swatch } from "dialogs/appearance-page.slint";
|
||||
export { ButtonKind, TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem, ToastData, ToastProgress, DialogAction, ConflictInfo, SettingsData, EditRow }
|
||||
export { PlayerData, FolderActions, ViewKeys, KeyRow, ConnectionData, HostKeyData, SecretPromptData }
|
||||
|
|
@ -159,6 +162,7 @@ export component MainWindow inherits Window {
|
|||
in-out property <int> appearance-choice;
|
||||
in-out property <string> appearance-name;
|
||||
in-out property <string> appearance-image;
|
||||
in-out property <IconChoice> appearance-browsed;
|
||||
in-out property <bool> appearance-remember;
|
||||
in property <string> appearance-placeholder;
|
||||
in property <string> appearance-error;
|
||||
|
|
@ -244,16 +248,25 @@ export component MainWindow inherits Window {
|
|||
}
|
||||
in property <[MenuItem]> place-menu;
|
||||
callback toggle-sidebar();
|
||||
in property <bool> has-current-place;
|
||||
in property <int> current-place-section;
|
||||
in property <int> current-place-row;
|
||||
in property <int> current-place-rows-before;
|
||||
callback place-opened(int, int, bool);
|
||||
callback section-toggled(int);
|
||||
callback add-bookmark();
|
||||
callback place-menu-requested(int, int);
|
||||
callback place-menu-activated(int, int);
|
||||
callback place-renamed(string);
|
||||
// The launcher maker and editor (launcher.rs).
|
||||
in-out property <LauncherData> launcher;
|
||||
in property <[IconChoice]> launcher-icons;
|
||||
callback launcher-saved();
|
||||
// The icon of a sidebar entry (shell/place_icon.rs).
|
||||
in property <[IconChoice]> place-icons;
|
||||
in-out property <int> place-icon-choice;
|
||||
in-out property <string> place-icon-image;
|
||||
in-out property <IconChoice> place-icon-browsed;
|
||||
in property <string> place-icon-error;
|
||||
callback place-icon-saved();
|
||||
|
||||
|
|
@ -297,6 +310,14 @@ export component MainWindow inherits Window {
|
|||
place-popup.open-at(x, y);
|
||||
}
|
||||
|
||||
public function show-launcher() {
|
||||
launcher-dialog.show();
|
||||
}
|
||||
|
||||
public function close-launcher() {
|
||||
launcher-dialog.close();
|
||||
}
|
||||
|
||||
public function show-place-icon() {
|
||||
place-icon-dialog.show();
|
||||
}
|
||||
|
|
@ -432,6 +453,10 @@ export component MainWindow inherits Window {
|
|||
width: root.show-sidebar ? 240px : 0;
|
||||
visible: self.width > 0;
|
||||
sections: root.sections;
|
||||
has-current: root.has-current-place;
|
||||
current-section: root.current-place-section;
|
||||
current-row: root.current-place-row;
|
||||
rows-before: root.current-place-rows-before;
|
||||
animate width { duration: Motion.time(Motion.medium2); easing: Motion.emphasized; }
|
||||
open(section, index, new-tab) => {
|
||||
root.place-opened(section, index, new-tab);
|
||||
|
|
@ -876,6 +901,7 @@ export component MainWindow inherits Window {
|
|||
choice <=> root.appearance-choice;
|
||||
name-text <=> root.appearance-name;
|
||||
image-path <=> root.appearance-image;
|
||||
browsed <=> root.appearance-browsed;
|
||||
remember <=> root.appearance-remember;
|
||||
placeholder: root.appearance-placeholder;
|
||||
error: root.appearance-error;
|
||||
|
|
@ -885,12 +911,23 @@ export component MainWindow inherits Window {
|
|||
}
|
||||
}
|
||||
|
||||
launcher-dialog := LauncherDialog {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
data <=> root.launcher;
|
||||
icons: root.launcher-icons;
|
||||
saved => {
|
||||
root.launcher-saved();
|
||||
}
|
||||
}
|
||||
|
||||
place-icon-dialog := PlaceIconDialog {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
icons: root.place-icons;
|
||||
choice <=> root.place-icon-choice;
|
||||
image-path <=> root.place-icon-image;
|
||||
browsed <=> root.place-icon-browsed;
|
||||
error: root.place-icon-error;
|
||||
saved => {
|
||||
root.place-icon-saved();
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue