diff --git a/CLAUDE.md b/CLAUDE.md
index 94396df..df80dfc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -89,9 +89,9 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~
| `XDG_DATA_HOME=
/data cargo run -p tunal-core --example ops -- ` (refuses unless XDG_DATA_HOME is inside ``) | job engine + trash smoke run: conflicts, cancel, trash/restore/empty | S007 |
| `cargo run -p tunal -- --gallery --screenshot [--dark] --size 1200x1000` (`--gallery` alone opens it in a window) | every control in rest/hover/pressed/focused/disabled; press squeeze not drawn by the software renderer | S004 |
| `cargo run -p tunal -- --gallery --page menu\|dialog --screenshot [--dark] --size 960x640` | open menu + submenu + two toasts, or dialog + indeterminate toast, over a stand-in folder | S005 |
-| `TUNAL_SETTINGS=<0-5> cargo run -p tunal -- --screenshot --size 1000x700` (`XDG_CONFIG_HOME=`) | settings dialog page over a folder | S013 |
+| `TUNAL_SETTINGS=<0-7> cargo run -p tunal -- --screenshot --size 1000x700` (`XDG_CONFIG_HOME=`) | settings dialog page over a folder (6 Mouse, 7 Shortcuts); add `TUNAL_KEYS=:` to record that chord on the Shortcuts page (a taken chord shows the conflict row) | S013 |
| `TUNAL_DRAG=x1,y1,x2,y2[,hold] TUNAL_REDUCED_MOTION=1 cargo run -p tunal -- --screenshot --size 1200x760` (`XDG_CONFIG_HOME=`) | drags between window points and drops (drop menu) or holds (glow + drag image) before the frame | S014 |
-| `Xvfb :97 &` then `env -u WAYLAND_DISPLAY DISPLAY=:97 target/debug/tunal &` and `DISPLAY=:97 target/debug/examples/xdnd_probe x1 y1 x2 y2` (or `in x y `) | X11 native DnD: fake XTEST drag out of the window onto a probe target, or a probe source dropping into the app; Xvfb only | S031 |
+| `Xvfb :97 &` then `env -u WAYLAND_DISPLAY DISPLAY=:97 target/debug/tunal &` and `DISPLAY=:97 target/debug/examples/xdnd_probe x1 y1 x2 y2` (or `in x y `) | X11 native DnD: fake XTEST drag out of the window onto a probe target, or a probe source dropping into the app; Xvfb only. Also `xdnd_probe click x y [count] [gap_ms] [hover_ms] [button]` (2 = middle) and `xdnd_probe key ctrl+t f3 alt+2 …` (focuses the window under the pointer, then presses each chord); screenshot with `import -window root ` | S031 |
| same, with `SLINT_BACKEND=winit-software` (so `DISPLAY=:97 import -window root ` captures it), then `DISPLAY=:97 target/debug/examples/xdnd_probe click x y [count] [gap_ms] [hover_ms]` | real clicks (XTEST) on a window point after resting `hover_ms` there, e.g. the split toggle with a tooltip showing; Xvfb only | split/tooltip fix |
| `TUNAL_APPEARANCE=1 XDG_CONFIG_HOME= cargo run -p tunal -- --screenshot --size 1000x760` | folder appearance dialog for `` (theme icons looked up at once); `cargo run -p tunal-dirmeta --example roundtrip -- ` sets `Icon` in `/.directory` and prints the old values | S015 |
| `TUNAL_PLAY= XDG_CONFIG_HOME= cargo run -p tunal -- --screenshot [--dark] --size 1200x760` (`TUNAL_PLAY_STATE=playing` draws it playing: the wave) | player bar open on that file, a third in (tags, cover, length read at once; no audio output), paused unless asked | S023 |
diff --git a/crates/tunal/examples/xdnd_probe.rs b/crates/tunal/examples/xdnd_probe.rs
index c20ca10..1a9b805 100644
--- a/crates/tunal/examples/xdnd_probe.rs
+++ b/crates/tunal/examples/xdnd_probe.rs
@@ -8,14 +8,19 @@
//!
//! `xdnd_probe click x y [count] [gap_ms] [hover_ms]`: moves the pointer to (x, y), rests
//! there `hover_ms` (default 0), then clicks `count` times (default 1) `gap_ms` apart
-//! (default 400), printing the seconds since the epoch of each click.
+//! (default 400), printing the seconds since the epoch of each click. `button` (default 1,
+//! 2 is the middle button) as a sixth number.
+//!
+//! `xdnd_probe key ctrl+shift+t f3 alt+2 …`: presses each chord in turn (XTEST), 300 ms
+//! apart; letters, digits, `f1`–`f12` and the modifiers `ctrl`, `shift`, `alt`.
use std::time::{Duration, Instant};
use x11rb::connection::Connection;
use x11rb::protocol::Event;
use x11rb::protocol::xproto::{
- AtomEnum, ClientMessageEvent, ConnectionExt, CreateWindowAux, EventMask, PropMode, WindowClass,
+ AtomEnum, ClientMessageEvent, ConnectionExt, CreateWindowAux, EventMask, InputFocus, PropMode,
+ WindowClass,
};
use x11rb::protocol::xtest::ConnectionExt as _;
use x11rb::wrapper::ConnectionExt as _;
@@ -36,6 +41,9 @@ fn main() {
if std::env::args().nth(1).as_deref() == Some("click") {
return click();
}
+ if std::env::args().nth(1).as_deref() == Some("key") {
+ return keys();
+ }
let n: Vec = std::env::args()
.skip(1)
.filter_map(|a| a.parse().ok())
@@ -151,13 +159,14 @@ fn click() {
.skip(2)
.filter_map(|a| a.parse().ok())
.collect();
- let (x, y, count, gap, hover) = match n[..] {
- [x, y] => (x, y, 1, 400, 0),
- [x, y, c] => (x, y, c, 400, 0),
- [x, y, c, g] => (x, y, c, g, 0),
- [x, y, c, g, h] => (x, y, c, g, h),
+ let (x, y, count, gap, hover, button) = match n[..] {
+ [x, y] => (x, y, 1, 400, 0, 1),
+ [x, y, c] => (x, y, c, 400, 0, 1),
+ [x, y, c, g] => (x, y, c, g, 0, 1),
+ [x, y, c, g, h] => (x, y, c, g, h, 1),
+ [x, y, c, g, h, b] => (x, y, c, g, h, b as u8),
_ => {
- eprintln!("usage: xdnd_probe click x y [count] [gap_ms] [hover_ms]");
+ eprintln!("usage: xdnd_probe click x y [count] [gap_ms] [hover_ms] [button]");
return;
}
};
@@ -175,11 +184,11 @@ fn click() {
if i > 0 {
std::thread::sleep(Duration::from_millis(gap));
}
- c.xtest_fake_input(4, 1, CURRENT_TIME, root, 0, 0, 0)
+ c.xtest_fake_input(4, button, CURRENT_TIME, root, 0, 0, 0)
.unwrap();
c.get_input_focus().unwrap().reply().unwrap();
std::thread::sleep(Duration::from_millis(40));
- c.xtest_fake_input(5, 1, CURRENT_TIME, root, 0, 0, 0)
+ c.xtest_fake_input(5, button, CURRENT_TIME, root, 0, 0, 0)
.unwrap();
// A round trip: the server has taken the release before the next press (or exit).
c.get_input_focus().unwrap().reply().unwrap();
@@ -190,6 +199,72 @@ fn click() {
}
}
+/// The keysym of one key name of a chord.
+fn keysym(name: &str) -> Option {
+ Some(match name {
+ "ctrl" => 0xffe3,
+ "shift" => 0xffe1,
+ "alt" => 0xffe9,
+ _ if name.len() == 1 => name.chars().next()? as u32,
+ _ => {
+ 0xffbe
+ + name
+ .strip_prefix('f')?
+ .parse::()
+ .ok()?
+ .checked_sub(1)?
+ }
+ })
+}
+
+fn keys() {
+ let (c, screen) = x11rb::connect(None).unwrap();
+ let root = c.setup().roots[screen].root;
+ let (min, max) = (c.setup().min_keycode, c.setup().max_keycode);
+ let map = c
+ .get_keyboard_mapping(min, max - min + 1)
+ .unwrap()
+ .reply()
+ .unwrap();
+ let per = map.keysyms_per_keycode as usize;
+ // No window manager under Xvfb: give the keyboard to the window under the pointer.
+ let under = c.query_pointer(root).unwrap().reply().unwrap().child;
+ if under != 0 {
+ c.set_input_focus(InputFocus::PARENT, under, CURRENT_TIME)
+ .unwrap();
+ }
+ let code = |sym: u32| {
+ map.keysyms
+ .chunks(per)
+ .position(|syms| syms.contains(&sym))
+ .map(|i| min + i as u8)
+ };
+ for chord in std::env::args().skip(2) {
+ let lower = chord.to_ascii_lowercase();
+ let Some(codes) = lower
+ .split('+')
+ .map(|k| keysym(k).and_then(code))
+ .collect::>>()
+ else {
+ eprintln!("probe: unknown key in {chord}");
+ continue;
+ };
+ for &k in &codes {
+ c.xtest_fake_input(2, k, CURRENT_TIME, root, 0, 0, 0)
+ .unwrap();
+ }
+ c.get_input_focus().unwrap().reply().unwrap();
+ std::thread::sleep(Duration::from_millis(40));
+ for &k in codes.iter().rev() {
+ c.xtest_fake_input(3, k, CURRENT_TIME, root, 0, 0, 0)
+ .unwrap();
+ }
+ c.get_input_focus().unwrap().reply().unwrap();
+ println!("probe: key {chord}");
+ std::thread::sleep(Duration::from_millis(300));
+ }
+}
+
fn d_copy(c: &impl Connection) -> u32 {
atom(c, "XdndActionCopy")
}
diff --git a/crates/tunal/src/config.rs b/crates/tunal/src/config.rs
index 2958bf1..e5b5957 100644
--- a/crates/tunal/src/config.rs
+++ b/crates/tunal/src/config.rs
@@ -1,6 +1,7 @@
//! The config directory, `$XDG_CONFIG_HOME/tunal/`: one TOML file per concern, read with
//! defaults for missing files and fields, written atomically (temp file, then rename).
+use std::collections::BTreeMap;
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
@@ -128,6 +129,73 @@ pub enum FrameUnit {
Seconds,
}
+/// What opens an item: a double click (and Enter), or a single click.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Click {
+ #[default]
+ Double,
+ Single,
+}
+
+/// A middle click on an item.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum MiddleItem {
+ /// A folder opens in a new tab, a file in the Open with dialog.
+ #[default]
+ NewTab,
+ /// Like a double click.
+ Open,
+ Nothing,
+}
+
+/// A middle click on empty space.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum MiddleEmpty {
+ #[default]
+ Nothing,
+ Paste,
+ /// The folder shown, in a new tab.
+ NewTab,
+}
+
+/// The mouse's back and forward side buttons.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SideButtons {
+ #[default]
+ History,
+ /// Back goes up one folder; forward does nothing.
+ Up,
+ /// Previous and next tab.
+ Tabs,
+ Nothing,
+}
+
+/// A double click on empty space.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum EmptyDouble {
+ #[default]
+ Nothing,
+ SelectAll,
+ Up,
+ NewFolder,
+}
+
+/// Opening an executable file (a program, script or AppImage).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Executables {
+ #[default]
+ Ask,
+ Run,
+ /// Open it like a document (a script in a text editor).
+ Open,
+}
+
/// `settings.toml`. Later plans add their fields here.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
@@ -164,6 +232,15 @@ pub struct Settings {
pub keepalive_secs: u32,
/// Minutes of no use before a connection closes.
pub idle_close_mins: u32,
+ pub click: Click,
+ pub middle_item: MiddleItem,
+ pub middle_empty: MiddleEmpty,
+ pub side_buttons: SideButtons,
+ pub empty_double: EmptyDouble,
+ pub executables: Executables,
+ /// Keyboard shortcuts that differ from the defaults: command id → chords (`keymap.rs`).
+ /// A table, so it stays last.
+ pub shortcuts: BTreeMap>,
}
impl Default for Settings {
@@ -190,6 +267,13 @@ impl Default for Settings {
connect_timeout_secs: 15,
keepalive_secs: 30,
idle_close_mins: 5,
+ click: Click::Double,
+ middle_item: MiddleItem::NewTab,
+ middle_empty: MiddleEmpty::Nothing,
+ side_buttons: SideButtons::History,
+ empty_double: EmptyDouble::Nothing,
+ executables: Executables::Ask,
+ shortcuts: BTreeMap::new(),
}
}
}
diff --git a/crates/tunal/src/keymap.rs b/crates/tunal/src/keymap.rs
new file mode 100644
index 0000000..5bc295d
--- /dev/null
+++ b/crates/tunal/src/keymap.rs
@@ -0,0 +1,602 @@
+//! Keyboard shortcuts: every bindable command with its default chords, key chords as text
+//! (`Ctrl+Shift+N`), the user's overrides (the `[shortcuts]` table of `settings.toml`) and
+//! conflict checks. Pure: the window turns key events into a [`Chord`] and runs the
+//! [`Command`] the [`Keymap`] finds.
+//!
+//! Where a chord works follows from the chord: plain Space and Backspace are folder view keys
+//! (they also type the filter, so they only act while none is typed); every other chord works
+//! anywhere in the window. Two commands conflict when they share a chord.
+
+use std::collections::BTreeMap;
+use std::fmt;
+
+/// A key with its modifiers. `key` is a canonical name: an upper-case letter, a digit or
+/// punctuation character, `Plus`, or a named key (`F2`, `Delete`, `PgDown`, …).
+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct Chord {
+ pub ctrl: bool,
+ pub alt: bool,
+ pub shift: bool,
+ pub meta: bool,
+ pub key: String,
+}
+
+/// Named keys: Slint's character for each and the name chords use.
+const NAMED: [(char, &str); 22] = [
+ ('\u{0008}', "Backspace"),
+ ('\u{0009}', "Tab"),
+ ('\u{000a}', "Enter"),
+ ('\u{001b}', "Escape"),
+ ('\u{007f}', "Delete"),
+ (' ', "Space"),
+ ('\u{F700}', "Up"),
+ ('\u{F701}', "Down"),
+ ('\u{F702}', "Left"),
+ ('\u{F703}', "Right"),
+ ('\u{F727}', "Insert"),
+ ('\u{F729}', "Home"),
+ ('\u{F72B}', "End"),
+ ('\u{F72C}', "PgUp"),
+ ('\u{F72D}', "PgDown"),
+ ('\u{F72F}', "ScrollLock"),
+ ('\u{F730}', "Pause"),
+ ('\u{F731}', "Print"),
+ ('\u{F734}', "Stop"),
+ ('\u{F735}', "Menu"),
+ ('\u{F748}', "Back"),
+ ('+', "Plus"),
+];
+
+/// Slint's Backtab: Shift+Tab.
+const BACKTAB: char = '\u{0019}';
+/// Slint's F1; F1 to F24 follow it.
+const F1: u32 = 0xF704;
+/// Slint's characters for modifier keys pressed alone (Shift … MetaR, CapsLock).
+const MODIFIER_KEYS: std::ops::RangeInclusive = '\u{0010}'..='\u{0018}';
+
+/// Other names `parse` accepts for a key.
+const ALIASES: [(&str, &str); 8] = [
+ ("Del", "Delete"),
+ ("Ins", "Insert"),
+ ("Return", "Enter"),
+ ("Esc", "Escape"),
+ ("PageUp", "PgUp"),
+ ("PageDown", "PgDown"),
+ ("Minus", "-"),
+ ("Comma", ","),
+];
+
+impl Chord {
+ /// The chord of a key event: Slint's key text and the modifiers held. `None` for a
+ /// modifier pressed alone or text that is not one key.
+ pub fn from_event(text: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> Option {
+ let mut chars = text.chars();
+ let (c, None) = (chars.next()?, chars.next()) else {
+ return None;
+ };
+ if MODIFIER_KEYS.contains(&c) {
+ return None;
+ }
+ let (key, shift) = if c == BACKTAB {
+ ("Tab".to_string(), true)
+ } else if let Some((_, name)) = NAMED.iter().find(|(k, _)| *k == c) {
+ // `+` takes Shift on most layouts; like any punctuation it names itself.
+ (name.to_string(), shift && c != '+')
+ } else if let Some(n) = (c as u32).checked_sub(F1).filter(|n| *n < 24) {
+ (format!("F{}", n + 1), shift)
+ } else if c.is_alphabetic() {
+ (c.to_uppercase().collect(), shift)
+ } else if c.is_control() || ('\u{F700}'..='\u{F8FF}').contains(&c) {
+ return None;
+ } else {
+ // Digits and punctuation: Shift is part of the character typed.
+ (c.to_string(), false)
+ };
+ Some(Self {
+ ctrl,
+ alt,
+ shift,
+ meta,
+ key,
+ })
+ }
+
+ /// `Ctrl+Shift+N`, `Alt+Enter`, `Ctrl+Plus`, `F3`. Case and order of the modifiers don't
+ /// matter; `Ctrl++` reads as `Ctrl+Plus`.
+ pub fn parse(text: &str) -> Option {
+ let text = text.trim();
+ let (mods, key) = match text.strip_suffix("++") {
+ Some(rest) => (rest, "+"),
+ None => match text.rsplit_once('+') {
+ Some((mods, key)) => (mods, key),
+ None => ("", text),
+ },
+ };
+ let mut chord = Self {
+ ctrl: false,
+ alt: false,
+ shift: false,
+ meta: false,
+ key: String::new(),
+ };
+ for m in mods.split('+').filter(|m| !m.is_empty()) {
+ match m.trim().to_ascii_lowercase().as_str() {
+ "ctrl" | "control" => chord.ctrl = true,
+ "alt" => chord.alt = true,
+ "shift" => chord.shift = true,
+ "meta" | "super" => chord.meta = true,
+ _ => return None,
+ }
+ }
+ let key = key.trim();
+ let key = ALIASES
+ .iter()
+ .find(|(alias, _)| alias.eq_ignore_ascii_case(key))
+ .map_or(key, |(_, name)| name);
+ chord.key = if key == "+" {
+ "Plus".to_string()
+ } else if let Some((_, name)) = NAMED.iter().find(|(_, n)| n.eq_ignore_ascii_case(key)) {
+ name.to_string()
+ } else if let Some(n) = key
+ .strip_prefix(['F', 'f'])
+ .and_then(|n| n.parse::().ok())
+ .filter(|n| (1..=24).contains(n))
+ {
+ format!("F{n}")
+ } else {
+ let mut chars = key.chars();
+ let (c, None) = (chars.next()?, chars.next()) else {
+ return None;
+ };
+ if c.is_control() {
+ return None;
+ }
+ c.to_uppercase().collect()
+ };
+ Some(chord)
+ }
+
+ fn named(&self) -> bool {
+ self.key.chars().count() > 1
+ }
+
+ /// Plain Space or Backspace: a key of the folder view, which also types the filter.
+ pub fn is_view_key(&self) -> bool {
+ !self.ctrl && !self.alt && !self.meta && matches!(self.key.as_str(), "Space" | "Backspace")
+ }
+
+ /// Why this chord can't be a shortcut, or `None` when it can: a letter, digit or
+ /// punctuation key needs Ctrl, Alt or Super (it types into the folder filter), and Escape
+ /// is kept for closing things.
+ pub fn refusal(&self) -> Option<&'static str> {
+ if self.key == "Escape" {
+ return Some("Escape can't be a shortcut");
+ }
+ let plain = !self.ctrl && !self.alt && !self.meta;
+ if plain && (!self.named() || self.key == "Plus") {
+ return Some("Add Ctrl or Alt to a letter, digit or symbol key");
+ }
+ None
+ }
+}
+
+impl fmt::Display for Chord {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ for (on, name) in [
+ (self.ctrl, "Ctrl+"),
+ (self.alt, "Alt+"),
+ (self.shift, "Shift+"),
+ (self.meta, "Super+"),
+ ] {
+ if on {
+ f.write_str(name)?;
+ }
+ }
+ f.write_str(&self.key)
+ }
+}
+
+/// Every command a shortcut can run, by stable id (the `[shortcuts]` keys). Ids shared with
+/// the file actions (`copy`, `rename`, …) run that action.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub enum Command {
+ NewWindow,
+ NewTab,
+ CloseTab,
+ ReopenTab,
+ NextTab,
+ PrevTab,
+ /// Go to tab 1 to 9.
+ Tab(u8),
+ LastTab,
+ Quit,
+ Split,
+ FocusOtherPane,
+ CopyToOtherPane,
+ MoveToOtherPane,
+ Back,
+ Forward,
+ Up,
+ Home,
+ Reload,
+ Location,
+ Find,
+ ToggleHidden,
+ ZoomIn,
+ ZoomOut,
+ ZoomReset,
+ Sidebar,
+ Previews,
+ SelectAll,
+ InvertSelection,
+ Cut,
+ Copy,
+ Paste,
+ CopyPath,
+ Rename,
+ NewFolder,
+ Trash,
+ Delete,
+ Properties,
+ Terminal,
+ AddToPlaces,
+ Settings,
+ Play,
+}
+
+impl Command {
+ pub const ALL: [Command; 49] = [
+ Self::NewWindow,
+ Self::NewTab,
+ Self::CloseTab,
+ Self::ReopenTab,
+ Self::NextTab,
+ Self::PrevTab,
+ Self::Tab(1),
+ Self::Tab(2),
+ Self::Tab(3),
+ Self::Tab(4),
+ Self::Tab(5),
+ Self::Tab(6),
+ Self::Tab(7),
+ Self::Tab(8),
+ Self::Tab(9),
+ Self::LastTab,
+ Self::Quit,
+ Self::Split,
+ Self::FocusOtherPane,
+ Self::CopyToOtherPane,
+ Self::MoveToOtherPane,
+ Self::Back,
+ Self::Forward,
+ Self::Up,
+ Self::Home,
+ Self::Reload,
+ Self::Location,
+ Self::Find,
+ Self::ToggleHidden,
+ Self::ZoomIn,
+ Self::ZoomOut,
+ Self::ZoomReset,
+ Self::Sidebar,
+ Self::Previews,
+ Self::SelectAll,
+ Self::InvertSelection,
+ Self::Cut,
+ Self::Copy,
+ Self::Paste,
+ Self::CopyPath,
+ Self::Rename,
+ Self::NewFolder,
+ Self::Trash,
+ Self::Delete,
+ Self::Properties,
+ Self::Terminal,
+ Self::AddToPlaces,
+ Self::Settings,
+ Self::Play,
+ ];
+
+ pub fn id(self) -> &'static str {
+ match self {
+ Self::NewWindow => "new-window",
+ Self::NewTab => "new-tab",
+ Self::CloseTab => "close-tab",
+ Self::ReopenTab => "reopen-tab",
+ Self::NextTab => "next-tab",
+ Self::PrevTab => "prev-tab",
+ Self::Tab(1) => "tab-1",
+ Self::Tab(2) => "tab-2",
+ Self::Tab(3) => "tab-3",
+ Self::Tab(4) => "tab-4",
+ Self::Tab(5) => "tab-5",
+ Self::Tab(6) => "tab-6",
+ Self::Tab(7) => "tab-7",
+ Self::Tab(8) => "tab-8",
+ Self::Tab(_) => "tab-9",
+ Self::LastTab => "last-tab",
+ Self::Quit => "quit",
+ Self::Split => "split",
+ Self::FocusOtherPane => "focus-other-pane",
+ Self::CopyToOtherPane => "copy-to-other-pane",
+ Self::MoveToOtherPane => "move-to-other-pane",
+ Self::Back => "back",
+ Self::Forward => "forward",
+ Self::Up => "up",
+ Self::Home => "home",
+ Self::Reload => "reload",
+ Self::Location => "location",
+ Self::Find => "find",
+ Self::ToggleHidden => "toggle-hidden",
+ Self::ZoomIn => "zoom-in",
+ Self::ZoomOut => "zoom-out",
+ Self::ZoomReset => "zoom-reset",
+ Self::Sidebar => "sidebar",
+ Self::Previews => "previews",
+ Self::SelectAll => "select-all",
+ Self::InvertSelection => "invert-selection",
+ Self::Cut => "cut",
+ Self::Copy => "copy",
+ Self::Paste => "paste",
+ Self::CopyPath => "copy-path",
+ Self::Rename => "rename",
+ Self::NewFolder => "new-folder",
+ Self::Trash => "trash",
+ Self::Delete => "delete",
+ Self::Properties => "properties",
+ Self::Terminal => "terminal",
+ Self::AddToPlaces => "add-to-places",
+ Self::Settings => "settings",
+ Self::Play => "play",
+ }
+ }
+
+ pub fn from_id(id: &str) -> Option {
+ Self::ALL.into_iter().find(|c| c.id() == id)
+ }
+
+ pub fn label(self) -> String {
+ if let Self::Tab(n) = self {
+ return format!("Go to tab {n}");
+ }
+ match self {
+ Self::NewWindow => "New window",
+ Self::NewTab => "New tab",
+ Self::CloseTab => "Close tab",
+ Self::ReopenTab => "Reopen closed tab",
+ Self::NextTab => "Next tab",
+ Self::PrevTab => "Previous tab",
+ Self::LastTab => "Go to the last tab",
+ Self::Quit => "Quit",
+ Self::Split => "Split view",
+ Self::FocusOtherPane => "Focus the other pane",
+ Self::CopyToOtherPane => "Copy to the other pane",
+ Self::MoveToOtherPane => "Move to the other pane",
+ Self::Back => "Back",
+ Self::Forward => "Forward",
+ Self::Up => "Up one folder",
+ Self::Home => "Home folder",
+ Self::Reload => "Reload",
+ Self::Location => "Edit the location",
+ Self::Find => "Filter this folder",
+ Self::ToggleHidden => "Show hidden files",
+ Self::ZoomIn => "Larger icons",
+ Self::ZoomOut => "Smaller icons",
+ Self::ZoomReset => "Default icon size",
+ Self::Sidebar => "Show the sidebar",
+ Self::Previews => "Show previews",
+ Self::SelectAll => "Select all",
+ Self::InvertSelection => "Invert selection",
+ Self::Cut => "Cut",
+ Self::Copy => "Copy",
+ Self::Paste => "Paste",
+ Self::CopyPath => "Copy path",
+ Self::Rename => "Rename",
+ Self::NewFolder => "New folder",
+ Self::Trash => "Move to Trash",
+ Self::Delete => "Delete permanently",
+ Self::Properties => "Properties",
+ Self::Terminal => "Open terminal here",
+ Self::AddToPlaces => "Add to places",
+ Self::Settings => "Settings",
+ Self::Play => "Play",
+ Self::Tab(_) => unreachable!("labelled above"),
+ }
+ .to_string()
+ }
+
+ /// The chords before the user changes them.
+ pub fn defaults(self) -> &'static [&'static str] {
+ match self {
+ Self::NewWindow => &["Ctrl+N"],
+ Self::NewTab => &["Ctrl+T"],
+ Self::CloseTab => &["Ctrl+W"],
+ Self::ReopenTab => &["Ctrl+Shift+T"],
+ Self::NextTab => &["Ctrl+Tab", "Ctrl+PgDown"],
+ Self::PrevTab => &["Ctrl+Shift+Tab", "Ctrl+PgUp"],
+ Self::Tab(1) => &["Alt+1"],
+ Self::Tab(2) => &["Alt+2"],
+ Self::Tab(3) => &["Alt+3"],
+ Self::Tab(4) => &["Alt+4"],
+ Self::Tab(5) => &["Alt+5"],
+ Self::Tab(6) => &["Alt+6"],
+ Self::Tab(7) => &["Alt+7"],
+ Self::Tab(8) => &["Alt+8"],
+ Self::Tab(_) => &["Alt+9"],
+ Self::LastTab => &["Alt+0"],
+ Self::Quit => &["Ctrl+Q"],
+ Self::Split => &["F3"],
+ Self::FocusOtherPane => &["Ctrl+F3"],
+ Self::CopyToOtherPane => &["Shift+F5"],
+ Self::MoveToOtherPane => &["Shift+F6"],
+ Self::Back => &["Alt+Left", "Back"],
+ Self::Forward => &["Alt+Right"],
+ Self::Up => &["Alt+Up", "Backspace"],
+ Self::Home => &["Alt+Home"],
+ Self::Reload => &["F5"],
+ Self::Location => &["Ctrl+L", "F6"],
+ Self::Find => &["Ctrl+F", "Ctrl+I"],
+ Self::ToggleHidden => &["Ctrl+H", "Alt+."],
+ Self::ZoomIn => &["Ctrl+Plus", "Ctrl+="],
+ Self::ZoomOut => &["Ctrl+-"],
+ Self::ZoomReset => &["Ctrl+0"],
+ Self::Sidebar => &["F9"],
+ Self::Previews => &["F12"],
+ Self::SelectAll => &["Ctrl+A"],
+ Self::InvertSelection => &["Ctrl+Shift+A"],
+ Self::Cut => &["Ctrl+X"],
+ Self::Copy => &["Ctrl+C", "Ctrl+Insert"],
+ Self::Paste => &["Ctrl+V", "Shift+Insert"],
+ Self::CopyPath => &["Ctrl+Shift+C"],
+ Self::Rename => &["F2"],
+ Self::NewFolder => &["Ctrl+Shift+N"],
+ Self::Trash => &["Delete"],
+ Self::Delete => &["Shift+Delete"],
+ Self::Properties => &["Alt+Enter"],
+ Self::Terminal => &["F4", "Shift+F4"],
+ Self::AddToPlaces => &["Ctrl+D"],
+ Self::Settings => &["Ctrl+,"],
+ Self::Play => &["Space"],
+ }
+ }
+
+ /// Commands that still work while a text field (the location, a name being edited) has
+ /// the keyboard: the others' keys edit the text.
+ pub fn works_in_text(self) -> bool {
+ matches!(
+ self,
+ Self::NewWindow
+ | Self::NewTab
+ | Self::CloseTab
+ | Self::ReopenTab
+ | Self::NextTab
+ | Self::PrevTab
+ | Self::Tab(_)
+ | Self::LastTab
+ | Self::Quit
+ | Self::Split
+ | Self::Location
+ | Self::Sidebar
+ | Self::Settings
+ )
+ }
+}
+
+/// The chords of every command: the defaults, with the user's overrides on top.
+#[derive(Clone, Debug)]
+pub struct Keymap {
+ bindings: BTreeMap>,
+}
+
+fn parse_all(texts: &[impl AsRef]) -> Vec {
+ let mut out: Vec = Vec::new();
+ for chord in texts.iter().filter_map(|t| Chord::parse(t.as_ref())) {
+ if !out.contains(&chord) {
+ out.push(chord);
+ }
+ }
+ out
+}
+
+impl Default for Keymap {
+ fn default() -> Self {
+ Self::new(&BTreeMap::new())
+ }
+}
+
+impl Keymap {
+ /// The keymap with `overrides` (command id → chords; an empty list unbinds). Unknown
+ /// ids and chords that don't parse are skipped.
+ pub fn new(overrides: &BTreeMap>) -> Self {
+ let bindings = Command::ALL
+ .into_iter()
+ .map(|cmd| {
+ let chords = match overrides.get(cmd.id()) {
+ Some(texts) => parse_all(texts),
+ None => parse_all(cmd.defaults()),
+ };
+ (cmd, chords)
+ })
+ .collect();
+ Self { bindings }
+ }
+
+ pub fn chords(&self, cmd: Command) -> &[Chord] {
+ self.bindings.get(&cmd).map_or(&[], Vec::as_slice)
+ }
+
+ /// `Ctrl+C, Ctrl+Insert`; empty when unbound.
+ pub fn text(&self, cmd: Command) -> String {
+ let chords: Vec = self.chords(cmd).iter().map(Chord::to_string).collect();
+ chords.join(", ")
+ }
+
+ /// The first chord, for menus.
+ pub fn first(&self, cmd: Command) -> String {
+ self.chords(cmd)
+ .first()
+ .map(Chord::to_string)
+ .unwrap_or_default()
+ }
+
+ /// The command `chord` runs (the first one, if several share it).
+ pub fn lookup(&self, chord: &Chord) -> Option {
+ self.bindings
+ .iter()
+ .find(|(_, chords)| chords.contains(chord))
+ .map(|(cmd, _)| *cmd)
+ }
+
+ /// Another command than `cmd` that `chord` already runs.
+ pub fn holder(&self, chord: &Chord, cmd: Command) -> Option {
+ self.bindings
+ .iter()
+ .find(|(c, chords)| **c != cmd && chords.contains(chord))
+ .map(|(c, _)| *c)
+ }
+
+ /// Chords bound to more than one command, with the commands.
+ pub fn conflicts(&self) -> Vec<(Chord, Vec)> {
+ let mut by_chord: BTreeMap<&Chord, Vec> = BTreeMap::new();
+ for (cmd, chords) in &self.bindings {
+ for chord in chords {
+ by_chord.entry(chord).or_default().push(*cmd);
+ }
+ }
+ by_chord
+ .into_iter()
+ .filter(|(_, cmds)| cmds.len() > 1)
+ .map(|(chord, cmds)| (chord.clone(), cmds))
+ .collect()
+ }
+
+ /// Makes `chord` the only shortcut of `cmd`, taking it from any command that had it.
+ pub fn assign(&mut self, cmd: Command, chord: Chord) {
+ for chords in self.bindings.values_mut() {
+ chords.retain(|c| *c != chord);
+ }
+ self.bindings.insert(cmd, vec![chord]);
+ }
+
+ pub fn reset(&mut self, cmd: Command) {
+ self.bindings.insert(cmd, parse_all(cmd.defaults()));
+ }
+
+ pub fn is_default(&self, cmd: Command) -> bool {
+ self.chords(cmd) == parse_all(cmd.defaults()).as_slice()
+ }
+
+ /// What `settings.toml` keeps: the commands that differ from their defaults.
+ pub fn overrides(&self) -> BTreeMap> {
+ self.bindings
+ .iter()
+ .filter(|(cmd, _)| !self.is_default(**cmd))
+ .map(|(cmd, chords)| {
+ (
+ cmd.id().to_string(),
+ chords.iter().map(Chord::to_string).collect(),
+ )
+ })
+ .collect()
+ }
+}
diff --git a/crates/tunal/src/lib.rs b/crates/tunal/src/lib.rs
index 064c6a9..f9a9cf6 100644
--- a/crates/tunal/src/lib.rs
+++ b/crates/tunal/src/lib.rs
@@ -1,7 +1,9 @@
//! The pure parts of the app crate as a library, for the integration tests in `tests/`.
//! The binary (`main.rs`) builds these same files as its own modules.
+pub mod config;
pub mod icons;
+pub mod keymap;
pub mod folder {
pub mod item;
diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs
index a750940..d4e1325 100644
--- a/crates/tunal/src/main.rs
+++ b/crates/tunal/src/main.rs
@@ -7,6 +7,7 @@ mod dnd;
mod folder;
mod icons;
mod jobs_bridge;
+mod keymap;
mod menus;
mod native;
mod net_bridge;
@@ -20,6 +21,7 @@ mod shell;
mod tags_bridge;
mod theme_bridge;
mod thumbs_bridge;
+mod tools;
use std::path::PathBuf;
use std::process::ExitCode;
@@ -109,7 +111,17 @@ fn window(
let ui = MainWindow::new()?;
let tabs = tabs
.iter()
- .map(|dirs| dirs.iter().map(|d| Uri::from_path(d)).collect())
+ .map(|dirs| {
+ dirs.iter()
+ .map(|d| {
+ // A folder elsewhere (`sftp://…`) comes as its URI.
+ d.to_str()
+ .filter(|t| t.contains("://"))
+ .and_then(Uri::parse)
+ .unwrap_or_else(|| Uri::from_path(d))
+ })
+ .collect()
+ })
.collect();
let mut locations = Locations::with_local();
let mtp = devices_bridge::register(&mut locations);
@@ -117,12 +129,16 @@ fn window(
let shell = shell::Shell::attach(&ui, locations, tabs, blocking);
devices_bridge::attach(&shell, mtp);
net_bridge::attach(&ui, &shell, net);
- // `TUNAL_SETTINGS=` opens the settings dialog (screenshots).
+ // `TUNAL_SETTINGS=` opens the settings dialog (screenshots); on the Shortcuts
+ // page `TUNAL_KEYS=:` records that key for the command.
if let Some(page) = std::env::var("TUNAL_SETTINGS")
.ok()
.and_then(|p| p.parse().ok())
{
ui.invoke_show_settings(page);
+ if let Ok(spec) = std::env::var("TUNAL_KEYS") {
+ shell.debug_keys(&spec);
+ }
}
// `TUNAL_APPEARANCE=1` opens the folder appearance dialog for the folder shown.
if std::env::var_os("TUNAL_APPEARANCE").is_some() {
diff --git a/crates/tunal/src/settings.rs b/crates/tunal/src/settings.rs
index 71f9690..018471d 100644
--- a/crates/tunal/src/settings.rs
+++ b/crates/tunal/src/settings.rs
@@ -1,5 +1,6 @@
-//! The settings dialog: the options in `settings.toml` and the context menu editor
-//! (`menus.toml`). Every change is applied and stored at once.
+//! The settings dialog: the options in `settings.toml`, the shortcut editor (its
+//! `[shortcuts]` table) and the context menu editor (`menus.toml`). Every change is applied
+//! and stored at once.
use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
@@ -7,11 +8,15 @@ use std::rc::{Rc, Weak};
use slint::{ComponentHandle, ModelRc, VecModel};
use crate::actions::{Action, Actions};
-use crate::config::{self, Clock, DateStyle, FrameUnit, Group, Motion, Sort, View};
+use crate::config::{
+ self, Click, Clock, DateStyle, EmptyDouble, Executables, FrameUnit, Group, MiddleEmpty,
+ MiddleItem, Motion, SideButtons, Sort, View,
+};
use crate::folder::format;
+use crate::keymap::{Chord, Command};
use crate::menus::{Context, SEPARATOR};
use crate::shell::Shell;
-use crate::{EditRow, MainWindow, SettingsData, theme_bridge};
+use crate::{EditRow, KeyRow, MainWindow, SettingsData, theme_bridge};
pub struct SettingsUi {
me: Weak,
@@ -22,6 +27,11 @@ pub struct SettingsUi {
context: Cell,
/// The ids of that menu: what the editor edits.
ids: RefCell>,
+ /// The shortcut editor's search text.
+ key_search: RefCell,
+ /// The command a key is being recorded for, and a key that waits for Replace.
+ recording: Cell>,
+ pending: RefCell >,
/// Once a minute: redraws "5 minutes ago" stamps; a tick with none under an hour old
/// repaints nothing.
tick: slint::Timer,
@@ -36,6 +46,9 @@ impl SettingsUi {
actions: actions.clone(),
context: Cell::new(0),
ids: RefCell::new(Vec::new()),
+ key_search: RefCell::new(String::new()),
+ recording: Cell::new(None),
+ pending: RefCell::new(None),
tick: slint::Timer::default(),
});
let cfg = config::load::("settings");
@@ -81,6 +94,12 @@ impl SettingsUi {
connect_timeout: cfg.connect_timeout_secs as i32,
keepalive: cfg.keepalive_secs as i32,
idle_close: cfg.idle_close_mins as i32,
+ click: cfg.click as i32,
+ middle_item: cfg.middle_item as i32,
+ middle_empty: cfg.middle_empty as i32,
+ side_buttons: cfg.side_buttons as i32,
+ empty_double: cfg.empty_double as i32,
+ executables: cfg.executables as i32,
}
}
@@ -96,6 +115,8 @@ impl SettingsUi {
.collect::>(),
)));
self.show_menu(self.context.get().min(Context::ALL.len() - 1));
+ self.key_search.borrow_mut().clear();
+ self.stop_recording();
}
fn changed(&self, data: SettingsData) {
@@ -125,6 +146,28 @@ impl SettingsUi {
cfg.connect_timeout_secs = data.connect_timeout.clamp(5, 120) as u32;
cfg.keepalive_secs = data.keepalive.clamp(0, 300) as u32;
cfg.idle_close_mins = data.idle_close.clamp(1, 120) as u32;
+ cfg.click = [Click::Double, Click::Single][data.click.clamp(0, 1) as usize];
+ cfg.middle_item = [MiddleItem::NewTab, MiddleItem::Open, MiddleItem::Nothing]
+ [data.middle_item.clamp(0, 2) as usize];
+ cfg.middle_empty = [
+ MiddleEmpty::Nothing,
+ MiddleEmpty::Paste,
+ MiddleEmpty::NewTab,
+ ][data.middle_empty.clamp(0, 2) as usize];
+ cfg.side_buttons = [
+ SideButtons::History,
+ SideButtons::Up,
+ SideButtons::Tabs,
+ SideButtons::Nothing,
+ ][data.side_buttons.clamp(0, 3) as usize];
+ cfg.empty_double = [
+ EmptyDouble::Nothing,
+ EmptyDouble::SelectAll,
+ EmptyDouble::Up,
+ EmptyDouble::NewFolder,
+ ][data.empty_double.clamp(0, 3) as usize];
+ cfg.executables = [Executables::Ask, Executables::Run, Executables::Open]
+ [data.executables.clamp(0, 2) as usize];
// The window's own sidebar state is saved with the session, not by this dialog.
if let Some(ui) = self.ui.upgrade() {
cfg.show_sidebar = ui.get_show_sidebar();
@@ -133,6 +176,7 @@ impl SettingsUi {
config::store("settings", &cfg);
format::set_dates(cfg.date_style, cfg.clock);
if let Some(shell) = self.shell.upgrade() {
+ shell.set_prefs(&cfg);
shell.thumbs().configure(&cfg);
crate::net_bridge::configure(&shell, &cfg);
for pane in shell.panes() {
@@ -148,7 +192,7 @@ impl SettingsUi {
Context::ALL[self.context.get().min(Context::ALL.len() - 1)]
}
- fn row(id: &str) -> Option {
+ fn row(&self, id: &str) -> Option {
if id == SEPARATOR {
return Some(EditRow {
text: Default::default(),
@@ -161,7 +205,7 @@ impl SettingsUi {
Some(EditRow {
text: action.label().into(),
icon: action.glyph().into(),
- shortcut: action.shortcut_text().into(),
+ shortcut: self.actions.shortcut_text(action).into(),
separator: false,
})
}
@@ -186,11 +230,11 @@ impl SettingsUi {
return;
};
let ids = self.ids.borrow();
- let rows: Vec = ids.iter().filter_map(|id| Self::row(id)).collect();
+ let rows: Vec = ids.iter().filter_map(|id| self.row(id)).collect();
let available: Vec = Action::ALL
.iter()
.filter(|a| !ids.iter().any(|id| id == a.id()))
- .filter_map(|a| Self::row(a.id()))
+ .filter_map(|a| self.row(a.id()))
.collect();
ui.set_menu_context(self.context.get() as i32);
ui.set_menu_rows(ModelRc::new(VecModel::from(rows)));
@@ -249,6 +293,130 @@ impl SettingsUi {
self.show_menu(self.context.get());
}
+ // ---- shortcut editor ----------------------------------------------------------------
+
+ /// Shows the commands that match the search, with their keys.
+ fn show_keys(&self) {
+ let (Some(ui), Some(shell)) = (self.ui.upgrade(), self.shell.upgrade()) else {
+ return;
+ };
+ let keymap = shell.keymap();
+ let search = self.key_search.borrow().to_lowercase();
+ let rows: Vec = Command::ALL
+ .iter()
+ .enumerate()
+ .filter(|(_, cmd)| {
+ search.is_empty()
+ || cmd.label().to_lowercase().contains(&search)
+ || keymap.text(**cmd).to_lowercase().contains(&search)
+ })
+ .map(|(i, cmd)| KeyRow {
+ index: i as i32,
+ label: cmd.label().into(),
+ keys: keymap.text(*cmd).into(),
+ edited: !keymap.is_default(*cmd),
+ })
+ .collect();
+ ui.set_key_rows(ModelRc::new(VecModel::from(rows)));
+ ui.set_key_can_reset_all(!keymap.overrides().is_empty());
+ ui.set_key_recording(
+ self.recording
+ .get()
+ .and_then(|c| Command::ALL.iter().position(|x| *x == c))
+ .map_or(-1, |i| i as i32),
+ );
+ }
+
+ fn set_key_message(&self, message: &str, conflict: bool) {
+ if let Some(ui) = self.ui.upgrade() {
+ ui.set_key_message(message.into());
+ ui.set_key_conflict(conflict);
+ }
+ }
+
+ fn stop_recording(&self) {
+ self.recording.set(None);
+ *self.pending.borrow_mut() = None;
+ self.set_key_message("", false);
+ self.show_keys();
+ }
+
+ /// Changes the keymap in use and stores it in `settings.toml`.
+ fn edit_keymap(&self, edit: impl FnOnce(&mut crate::keymap::Keymap)) {
+ let Some(shell) = self.shell.upgrade() else {
+ return;
+ };
+ let mut keymap = shell.keymap().clone();
+ edit(&mut keymap);
+ let mut cfg: config::Settings = config::load("settings");
+ cfg.shortcuts = keymap.overrides();
+ config::store("settings", &cfg);
+ shell.set_prefs(&cfg);
+ shell.set_keymap(keymap);
+ }
+
+ fn record(&self, index: usize) {
+ self.recording.set(Command::ALL.get(index).copied());
+ *self.pending.borrow_mut() = None;
+ self.set_key_message("", false);
+ self.show_keys();
+ }
+
+ /// A key while recording: refused, a conflict to confirm, or the command's new key.
+ fn key_pressed(&self, text: &str, mods: [bool; 4]) {
+ let [ctrl, shift, alt, meta] = mods;
+ // A modifier on its own: wait for the key.
+ if let Some(chord) = Chord::from_event(text, ctrl, shift, alt, meta) {
+ self.chord_pressed(chord);
+ }
+ }
+
+ fn chord_pressed(&self, chord: Chord) {
+ let (Some(cmd), Some(shell)) = (self.recording.get(), self.shell.upgrade()) else {
+ return;
+ };
+ if let Some(reason) = chord.refusal() {
+ *self.pending.borrow_mut() = None;
+ self.set_key_message(&format!("{chord}: {reason}"), false);
+ return;
+ }
+ let holder = shell.keymap().holder(&chord, cmd);
+ if let Some(other) = holder {
+ self.set_key_message(
+ &format!("{chord} is already used by {} — Replace?", other.label()),
+ true,
+ );
+ *self.pending.borrow_mut() = Some(chord);
+ return;
+ }
+ self.edit_keymap(|k| k.assign(cmd, chord));
+ self.stop_recording();
+ }
+
+ /// Screenshots (`TUNAL_KEYS=:`): records `chord` for the command, which
+ /// shows the conflict when another command has it.
+ pub fn debug_record(&self, spec: &str) {
+ let Some((id, chord)) = spec.split_once(':') else {
+ return;
+ };
+ if let (Some(i), Some(chord)) = (
+ Command::ALL.iter().position(|c| c.id() == id),
+ Chord::parse(chord),
+ ) {
+ self.record(i);
+ self.chord_pressed(chord);
+ }
+ }
+
+ fn replace(&self) {
+ let (Some(cmd), Some(chord)) = (self.recording.get(), self.pending.borrow_mut().take())
+ else {
+ return;
+ };
+ self.edit_keymap(|k| k.assign(cmd, chord));
+ self.stop_recording();
+ }
+
fn bind(&self, ui: &MainWindow) {
macro_rules! on {
($setter:ident, |$s:ident $(, $arg:ident)*| $body:expr) => {{
@@ -273,5 +441,24 @@ impl SettingsUi {
s.commit();
});
on!(on_menu_reset, |s| s.reset());
+ on!(on_key_search, |s, text| {
+ *s.key_search.borrow_mut() = text.into();
+ s.show_keys();
+ });
+ on!(on_key_record, |s, i| s.record(i.max(0) as usize));
+ on!(on_key_pressed, |s, text, ctrl, shift, alt, meta| s
+ .key_pressed(&text, [ctrl, shift, alt, meta]));
+ on!(on_key_replace, |s| s.replace());
+ on!(on_key_cancel, |s| s.stop_recording());
+ on!(on_key_reset, |s, i| {
+ if let Some(&cmd) = Command::ALL.get(i.max(0) as usize) {
+ s.edit_keymap(|k| k.reset(cmd));
+ }
+ s.stop_recording();
+ });
+ on!(on_key_reset_all, |s| {
+ s.edit_keymap(|k| *k = crate::keymap::Keymap::default());
+ s.stop_recording();
+ });
}
}
diff --git a/crates/tunal/src/shell/commands.rs b/crates/tunal/src/shell/commands.rs
new file mode 100644
index 0000000..cdb00bf
--- /dev/null
+++ b/crates/tunal/src/shell/commands.rs
@@ -0,0 +1,339 @@
+//! The one way keys reach the app: a Slint key event becomes a chord, the keymap names the
+//! command, and `Shell::command` runs it. Also the window-level commands themselves: new
+//! windows, the tab menu and the closed-tab stack.
+
+use std::ffi::OsString;
+use std::rc::Rc;
+
+use slint::{ComponentHandle, ModelRc, VecModel};
+use tunal_core::Uri;
+
+use super::{Shell, Tab, path, places};
+use crate::actions::Action;
+use crate::keymap::{Chord, Command};
+use crate::{MenuEntry, MenuItem, ViewKeys};
+
+/// Closed tabs kept for Reopen.
+const CLOSED_TABS: usize = 10;
+
+/// Starts another window of the app (its own process) with a tab of `dirs`: one folder, or
+/// two for a split tab. A local folder goes as its path, anything else as its URI.
+pub(crate) fn spawn_window(dirs: &[Uri]) -> Result<(), String> {
+ let exe = std::env::current_exe().map_err(|e| format!("Couldn't find Tunal itself: {e}"))?;
+ let arg = |u: &Uri| -> OsString {
+ u.to_path()
+ .map_or_else(|| u.to_string().into(), |p| p.into_os_string())
+ };
+ let mut argv: Vec = vec![exe.into_os_string()];
+ match dirs {
+ [a, b] => argv.extend(["--split".into(), arg(a), arg(b)]),
+ _ => argv.extend(dirs.iter().take(1).map(arg)),
+ }
+ crate::tools::spawn(&argv, &places::home())
+}
+
+impl Shell {
+ /// A key the window saw (before the focused control): true when it ran a shortcut.
+ /// `text_focus` is set while the location field has the keyboard.
+ pub(crate) fn shortcut(&self, text: &str, mods: [bool; 4], text_focus: bool) -> bool {
+ let [ctrl, shift, alt, meta] = mods;
+ let Some(chord) = Chord::from_event(text, ctrl, shift, alt, meta) else {
+ return false;
+ };
+ // Space and Backspace belong to the folder view (`view_key`).
+ if chord.is_view_key() {
+ return false;
+ }
+ let Some(cmd) = self.keymap.borrow().lookup(&chord) else {
+ return false;
+ };
+ let editing = text_focus || self.active().is_some_and(|p| p.model.editing().is_some());
+ if editing && !cmd.works_in_text() {
+ return false;
+ }
+ if self.actions.get().is_some_and(|a| a.modal()) {
+ return false;
+ }
+ self.command(cmd)
+ }
+
+ /// Space or Backspace in a folder view with no filter typed.
+ fn view_key(&self, text: &str, shift: bool) -> bool {
+ let Some(chord) = Chord::from_event(text, false, shift, false, false) else {
+ return false;
+ };
+ let cmd = self.keymap.borrow().lookup(&chord);
+ cmd.is_some_and(|cmd| self.command(cmd))
+ }
+
+ /// Runs `cmd`; false when it doesn't apply now (the key goes on to the view).
+ pub(crate) fn command(&self, cmd: Command) -> bool {
+ if let Some(action) = Action::from_id(cmd.id()) {
+ return self.actions.get().is_some_and(|a| a.run_enabled(action));
+ }
+ let pane = self.active();
+ match cmd {
+ Command::NewWindow => {
+ let dir = pane.and_then(|p| p.dir());
+ let result = spawn_window(&dir.into_iter().collect::>());
+ if let Err(message) = result {
+ self.notify(message);
+ }
+ }
+ Command::NewTab => self.new_tab(),
+ Command::CloseTab => self.close_tab(self.current.get()),
+ Command::ReopenTab => self.reopen_tab(),
+ Command::NextTab => self.cycle(false),
+ Command::PrevTab => self.cycle(true),
+ Command::Tab(n) => self.select_slot(usize::from(n) - 1),
+ Command::LastTab => {
+ let last = self.tabs.borrow().len() - 1;
+ self.select_slot(last);
+ }
+ Command::Quit => {
+ let _ = slint::quit_event_loop();
+ }
+ Command::Split => self.toggle_split(),
+ Command::FocusOtherPane => {
+ if self.other_pane().is_some() {
+ self.set_active_pane(1 - self.active_index());
+ self.focus_active();
+ }
+ }
+ Command::Back => self.with_active(|p| p.back()),
+ Command::Forward => self.with_active(|p| p.forward()),
+ Command::Up => self.with_active(|p| p.up()),
+ Command::Home => self.go(Uri::from_path(&places::home())),
+ Command::Reload => {
+ if let Some(p) = pane {
+ p.model.refresh();
+ }
+ }
+ Command::Location => {
+ if let Some(ui) = self.ui.upgrade() {
+ ui.invoke_edit_path();
+ }
+ }
+ Command::Find => {
+ self.focus_active();
+ self.notify("Type to filter this folder".into());
+ }
+ Command::ToggleHidden => {
+ if let Some(p) = pane {
+ p.model.toggle_hidden();
+ }
+ }
+ Command::Previews => {
+ if let Some(p) = pane {
+ p.model.toggle_previews();
+ }
+ }
+ Command::ZoomIn | Command::ZoomOut | Command::ZoomReset => {
+ let by = match cmd {
+ Command::ZoomIn => 1,
+ Command::ZoomOut => -1,
+ _ => 0,
+ };
+ if let Some(p) = pane {
+ p.model.zoom(by);
+ }
+ }
+ Command::Sidebar => {
+ if let Some(ui) = self.ui.upgrade() {
+ ui.set_show_sidebar(!ui.get_show_sidebar());
+ }
+ }
+ // Commands with an action of the same id ran above.
+ _ => return false,
+ }
+ true
+ }
+
+ // ---- tabs ---------------------------------------------------------------------------
+
+ /// Selects the tab shown at `slot`, if there is one.
+ fn select_slot(&self, slot: usize) {
+ let index = self.tabs.borrow().iter().position(|t| t.slot == slot);
+ if let Some(index) = index {
+ self.select_tab(index);
+ }
+ }
+
+ /// A tab is closing: its folders go on the stack Reopen takes from.
+ pub(super) fn remember_closed(&self, tab: &Tab) {
+ let dirs: Vec = tab.panes.iter().filter_map(|p| p.dir()).collect();
+ if dirs.is_empty() {
+ return;
+ }
+ let mut closed = self.closed.borrow_mut();
+ closed.push(dirs);
+ if closed.len() > CLOSED_TABS {
+ closed.remove(0);
+ }
+ }
+
+ fn reopen_tab(&self) {
+ let Some(dirs) = self.closed.borrow_mut().pop() else {
+ return;
+ };
+ self.open_tab(dirs);
+ self.show_current();
+ }
+
+ fn tab_dirs(&self, index: usize) -> Vec {
+ self.tabs.borrow()[index]
+ .panes
+ .iter()
+ .filter_map(|p| p.dir())
+ .collect()
+ }
+
+ /// The right-click menu of tab `id`.
+ fn show_tab_menu(&self, id: i32) {
+ let Some(index) = self.index_of(id) else {
+ return;
+ };
+ self.tab_menu.set(Some(id));
+ let (count, slot) = {
+ let tabs = self.tabs.borrow();
+ (tabs.len(), tabs[index].slot)
+ };
+ let keys = self.keymap.borrow();
+ let item = |text: &str, icon: &str, cmd: Option, disabled: bool| MenuItem {
+ text: text.into(),
+ icon: icon.into(),
+ shortcut: cmd.map(|c| keys.first(c)).unwrap_or_default().into(),
+ disabled,
+ separator: false,
+ submenu: ModelRc::new(VecModel::::default()),
+ };
+ let items = vec![
+ item("Close tab", "\u{f745}", Some(Command::CloseTab), count < 2),
+ item("Close other tabs", "\u{e5cd}", None, count < 2),
+ item(
+ "Close tabs to the right",
+ "\u{e5cc}",
+ None,
+ slot + 1 >= count,
+ ),
+ item(
+ "Reopen closed tab",
+ "\u{e166}",
+ Some(Command::ReopenTab),
+ self.closed.borrow().is_empty(),
+ ),
+ item("Duplicate tab", "\u{f744}", None, false),
+ item("Move to new window", "\u{f742}", None, count < 2),
+ ];
+ if let Some(ui) = self.ui.upgrade() {
+ ui.set_tab_menu(ModelRc::new(VecModel::from(items)));
+ }
+ }
+
+ fn tab_menu_activated(&self, choice: usize) {
+ let Some(index) = self.tab_menu.take().and_then(|id| self.index_of(id)) else {
+ return;
+ };
+ let id = self.tabs.borrow()[index].id;
+ let slot = self.tabs.borrow()[index].slot;
+ // Ids of the tabs to close, given which ones stay.
+ let close_where = |keep: &dyn Fn(&Tab) -> bool| {
+ let ids: Vec = self
+ .tabs
+ .borrow()
+ .iter()
+ .filter(|t| !keep(t))
+ .map(|t| t.id)
+ .collect();
+ for id in ids {
+ if let Some(i) = self.index_of(id) {
+ self.close_tab(i);
+ }
+ }
+ };
+ match choice {
+ 0 => self.close_tab(index),
+ 1 => {
+ if let Some(i) = self.index_of(id) {
+ self.select_tab(i);
+ }
+ close_where(&|t| t.id == id);
+ }
+ 2 => close_where(&|t| t.slot <= slot),
+ 3 => self.reopen_tab(),
+ 4 => {
+ self.open_tab(self.tab_dirs(index));
+ self.show_current();
+ }
+ 5 => match spawn_window(&self.tab_dirs(index)) {
+ Ok(()) => self.close_tab(index),
+ Err(message) => self.notify(message),
+ },
+ _ => {}
+ }
+ }
+
+ // ---- panes and places, for the actions --------------------------------------------------
+
+ /// The pane of the current tab that is not active, in split view.
+ pub(crate) fn other_pane(&self) -> Option> {
+ let tabs = self.tabs.borrow();
+ let tab = tabs.get(self.current.get())?;
+ (tab.panes.len() > 1)
+ .then(|| tab.panes.get(1 - tab.active).cloned())
+ .flatten()
+ }
+
+ /// Opens `uri` in the other pane, splitting the tab first when it isn't (the new pane
+ /// is then the active one).
+ pub(crate) fn open_in_other_pane(&self, uri: Uri) {
+ match self.other_pane() {
+ Some(p) => {
+ p.go(uri);
+ self.show_chrome();
+ }
+ None => {
+ self.toggle_split();
+ self.with_active(|p| p.go(uri));
+ }
+ }
+ }
+
+ /// The bookmarks of the sidebar, as names and folders.
+ pub(crate) fn bookmarks(&self) -> Vec<(String, Uri)> {
+ let places = self.places.borrow();
+ places
+ .items(places::Section::Bookmarks)
+ .iter()
+ .map(|p| (path::shown_name(&p.uri, p.name.clone()).0, p.uri.clone()))
+ .collect()
+ }
+
+ /// A folder's name as tabs show it.
+ pub(crate) fn title_of(&self, uri: &Uri) -> (String, &'static str) {
+ path::title(uri)
+ }
+
+ pub(super) fn bind_keys(&self, ui: &crate::MainWindow) {
+ let me = self.me.clone();
+ ui.on_shortcut_key(move |text, ctrl, shift, alt, meta, text_focus| {
+ me.upgrade()
+ .is_some_and(|s| s.shortcut(&text, [ctrl, shift, alt, meta], text_focus))
+ });
+ let me = self.me.clone();
+ ui.global::()
+ .on_key(move |text, shift| me.upgrade().is_some_and(|s| s.view_key(&text, shift)));
+ let me = self.me.clone();
+ ui.on_tab_menu_requested(move |id| {
+ if let Some(s) = me.upgrade() {
+ s.show_tab_menu(id);
+ }
+ });
+ let me = self.me.clone();
+ ui.on_tab_menu_activated(move |i, _sub| {
+ if let Some(s) = me.upgrade() {
+ s.tab_menu_activated(i.max(0) as usize);
+ }
+ });
+ }
+}
diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs
index 1425804..37b93d4 100644
--- a/crates/tunal/src/shell/mod.rs
+++ b/crates/tunal/src/shell/mod.rs
@@ -1,6 +1,7 @@
//! The navigation shell: tabs of one or two panes, history, the breadcrumb, the places
//! sidebar and the status bar, bound to the `MainWindow`.
+mod commands;
pub(crate) mod pane;
mod path;
pub mod places;
@@ -14,14 +15,17 @@ use slint::{ComponentHandle, Model, ModelRc, VecModel};
use tunal_core::{Locations, Uri};
use crate::actions::Actions;
-use crate::config::{self, Session, TabSession};
+use crate::config::{
+ self, Click, EmptyDouble, MiddleEmpty, MiddleItem, Session, SideButtons, TabSession,
+};
use crate::dnd::DragDrop;
use crate::folder::format;
+use crate::keymap::Keymap;
use crate::settings::SettingsUi;
use crate::thumbs_bridge::Thumbs;
use crate::{
- Completion, Crumb, MainWindow, MenuEntry, MenuItem, PaneData, PlaceItem, SidebarSection,
- TabData,
+ Completion, Crumb, FolderActions, MainWindow, MenuEntry, MenuItem, PaneData, PlaceItem,
+ SidebarSection, TabData,
};
use pane::Pane;
use places::{Places, Section};
@@ -62,6 +66,14 @@ pub struct Shell {
settings: OnceCell>,
/// Drag and drop; kept alive here.
dnd: OnceCell>,
+ /// The keyboard shortcuts in use.
+ keymap: RefCell,
+ /// `settings.toml` as last applied (mouse buttons, opening executables).
+ prefs: RefCell,
+ /// Folders of the last closed tabs, newest last.
+ closed: RefCell>>,
+ /// The tab whose menu is open.
+ tab_menu: Cell>,
}
impl Shell {
@@ -74,6 +86,13 @@ impl Shell {
tabs: Vec>,
blocking: bool,
) -> Rc {
+ let prefs: config::Settings = config::load("settings");
+ let keymap = Keymap::new(&prefs.shortcuts);
+ // Only a hand-edited settings.toml can do this; the first command wins the key.
+ for (chord, cmds) in keymap.conflicts() {
+ let ids: Vec<&str> = cmds.iter().map(|c| c.id()).collect();
+ eprintln!("tunal: {chord} is bound to {}", ids.join(", "));
+ }
let shell = Rc::new_cyclic(|me| Self {
ui: ui.as_weak(),
me: me.clone(),
@@ -91,6 +110,10 @@ impl Shell {
actions: OnceCell::new(),
settings: OnceCell::new(),
dnd: OnceCell::new(),
+ keymap: RefCell::new(keymap),
+ prefs: RefCell::new(prefs),
+ closed: RefCell::new(Vec::new()),
+ tab_menu: Cell::new(None),
});
let actions = Actions::attach(ui, &shell, shell.locations.clone());
let _ = shell.settings.set(SettingsUi::attach(ui, &shell, &actions));
@@ -250,6 +273,7 @@ impl Shell {
return;
}
let closed = tabs.remove(index);
+ self.remember_closed(&closed);
for t in tabs.iter_mut().filter(|t| t.slot > closed.slot) {
t.slot -= 1;
}
@@ -318,6 +342,24 @@ impl Shell {
}
}
+ // ---- settings -----------------------------------------------------------------------
+
+ pub(crate) fn keymap(&self) -> std::cell::Ref<'_, Keymap> {
+ self.keymap.borrow()
+ }
+
+ pub(crate) fn set_keymap(&self, keymap: Keymap) {
+ *self.keymap.borrow_mut() = keymap;
+ }
+
+ pub(crate) fn prefs(&self) -> std::cell::Ref<'_, config::Settings> {
+ self.prefs.borrow()
+ }
+
+ pub(crate) fn set_prefs(&self, cfg: &config::Settings) {
+ *self.prefs.borrow_mut() = cfg.clone();
+ }
+
// ---- panes --------------------------------------------------------------------------
pub(crate) fn active(&self) -> Option> {
@@ -485,6 +527,12 @@ impl Shell {
}
}
+ pub(crate) fn debug_keys(&self, spec: &str) {
+ if let Some(settings) = self.settings.get() {
+ settings.debug_record(spec);
+ }
+ }
+
pub(crate) fn run_action(&self, action: crate::actions::Action) {
if let Some(actions) = self.actions.get() {
actions.run(action);
@@ -877,8 +925,6 @@ impl Shell {
on!(on_tab_moved, |s, id, slot| s
.move_tab(id, slot.max(0) as usize));
on!(on_new_tab, |s| s.new_tab());
- on!(on_cycle_tab, |s, backward| s.cycle(backward));
- on!(on_close_tab, |s| s.close_tab(s.current.get()));
on!(on_pane_activated, |s, i| s
.set_active_pane(i.max(0) as usize));
on!(on_toggle_split, |s| s.toggle_split());
@@ -897,39 +943,33 @@ impl Shell {
});
on_pane!(on_sort_by, |_s, p, column| p.model.sort_column(column));
- // Space with no filter typed plays the selected audio file (the Play action).
- on_pane!(on_filter_typed, |s, p, text| if !(text == " "
- && p.model.state().filter.is_empty()
- && s.actions
- .get()
- .is_some_and(|a| a.key(&text, false, false, false)))
- {
- p.model.type_filter(&text)
- });
+ on_pane!(on_filter_typed, |_s, p, text| p.model.type_filter(&text));
on_pane!(on_filter_edited, |_s, p, text| p.model.set_filter(&text));
on_pane!(on_toggle_hidden, |_s, p| p.model.toggle_hidden());
on_pane!(on_toggle_previews, |_s, p| p.model.toggle_previews());
on_pane!(on_viewport_changed, |_s, p, top, height, row, cell| {
p.model.set_viewport(top, height, row, cell)
});
- on_pane!(on_row_clicked, |_s, p, row, ctrl, shift| {
- p.model.click(row.max(0) as usize, ctrl, shift)
- });
- on_pane!(on_row_activated, |s, p, row| {
- if let (Some(file), Some(actions)) =
- (p.activate(usize::try_from(row).ok()), s.actions.get())
- {
- actions.open_file(file);
+ // In single-click mode a plain click opens; the double click that may follow (row
+ // >= 0; Enter sends -1) is then ignored.
+ on_pane!(on_row_clicked, |s, p, row, ctrl, shift| {
+ p.model.click(row.max(0) as usize, ctrl, shift);
+ if !ctrl && !shift && s.prefs().click == Click::Single {
+ s.activate_row(&p, usize::try_from(row).ok());
}
- s.show_chrome()
});
+ on_pane!(
+ on_row_activated,
+ |s, p, row| if row < 0 || s.prefs().click == Click::Double {
+ s.activate_row(&p, usize::try_from(row).ok())
+ }
+ );
on_pane!(on_select_all, |_s, p| p.model.select_all());
on_pane!(on_grid_columns_changed, |_s, p, n| p
.model
.set_columns(n.max(1) as usize));
on_pane!(on_motion_settled, |_s, p| p.model.motion_settled());
on_pane!(on_view_mode_selected, |_s, p, mode| p.model.set_mode(mode));
- on_pane!(on_zoom, |_s, p, by| p.model.zoom(by.signum()));
on_pane!(on_clear_selection, |_s, p| p.model.clear_selection());
let me = self.me.clone();
ui.on_navigate(move |i, key, shift, page| {
@@ -967,9 +1007,90 @@ impl Shell {
on!(on_bookmark_renamed, |s, name| s.rename_bookmark(&name));
self.bind_mouse_buttons(ui);
+ self.bind_keys(ui);
+ let me = self.me.clone();
+ ui.global::()
+ .on_middle_clicked(move |pane, row| {
+ if let Some(s) = me.upgrade() {
+ s.middle_clicked(pane.max(0) as usize, row);
+ }
+ });
+ let me = self.me.clone();
+ ui.global::()
+ .on_empty_double_clicked(move |pane| {
+ if let Some(s) = me.upgrade() {
+ s.empty_double_clicked(pane.max(0) as usize);
+ }
+ });
}
- /// Mouse back and forward buttons go to the pane under the pointer, and Ctrl with the
+ /// Opens what `row` of `p` shows (the cursor row for `None`): a folder in place, a file
+ /// in its application.
+ fn activate_row(&self, p: &Pane, row: Option) {
+ if let (Some(file), Some(actions)) = (p.activate(row), self.actions.get()) {
+ actions.open_file(p, file);
+ }
+ self.show_chrome();
+ }
+
+ /// A middle click on `row` of pane `index` (-1: empty space), as the Mouse settings say.
+ fn middle_clicked(&self, index: usize, row: i32) {
+ self.set_active_pane(index);
+ let Some(p) = self.pane_at(index) else {
+ return;
+ };
+ let prefs = self.prefs().clone();
+ let Ok(row) = usize::try_from(row) else {
+ match prefs.middle_empty {
+ MiddleEmpty::Nothing => {}
+ MiddleEmpty::Paste => {
+ if let Some(actions) = self.actions.get() {
+ actions.paste_here();
+ }
+ }
+ MiddleEmpty::NewTab => self.new_tab(),
+ }
+ return;
+ };
+ match prefs.middle_item {
+ MiddleItem::Nothing => {}
+ MiddleItem::Open => {
+ p.model.click(row, false, false);
+ self.activate_row(&p, Some(row));
+ }
+ MiddleItem::NewTab => match p.model.folder_at(row) {
+ Some(dir) => self.open_at(dir, true),
+ None => {
+ p.model.click(row, false, false);
+ if let Some(actions) = self.actions.get() {
+ actions.run(crate::actions::Action::OpenWith);
+ }
+ }
+ },
+ }
+ }
+
+ /// A double click on the empty space of pane `index`.
+ fn empty_double_clicked(&self, index: usize) {
+ self.set_active_pane(index);
+ let Some(p) = self.pane_at(index) else {
+ return;
+ };
+ let what = self.prefs().empty_double;
+ match what {
+ EmptyDouble::Nothing => {}
+ EmptyDouble::SelectAll => p.model.select_all(),
+ EmptyDouble::Up => self.with_active(|p| p.up()),
+ EmptyDouble::NewFolder => {
+ if let (Some(actions), Some(dir)) = (self.actions.get(), p.dir()) {
+ actions.new_folder(&p, dir);
+ }
+ }
+ }
+ }
+
+ /// Mouse back and forward buttons (as the Mouse settings say) go to the pane under the
+ /// pointer, and Ctrl with the
/// wheel zooms its grid. Slint's own touch areas take every button press (and its lists
/// every wheel turn), so these are caught before Slint sees them.
fn bind_mouse_buttons(&self, ui: &MainWindow) {
@@ -1016,10 +1137,14 @@ impl Shell {
if hovered >= 0 {
shell.set_active_pane(hovered as usize);
}
- if *button == MouseButton::Back {
- shell.with_active(|p| p.back());
- } else {
- shell.with_active(|p| p.forward());
+ let back = *button == MouseButton::Back;
+ let what = shell.prefs().side_buttons;
+ match what {
+ SideButtons::History if back => shell.with_active(|p| p.back()),
+ SideButtons::History => shell.with_active(|p| p.forward()),
+ SideButtons::Up if back => shell.with_active(|p| p.up()),
+ SideButtons::Tabs => shell.cycle(back),
+ SideButtons::Up | SideButtons::Nothing => return EventResult::Propagate,
}
EventResult::PreventDefault
}
diff --git a/crates/tunal/tests/keymap.rs b/crates/tunal/tests/keymap.rs
new file mode 100644
index 0000000..10b3000
--- /dev/null
+++ b/crates/tunal/tests/keymap.rs
@@ -0,0 +1,193 @@
+//! Key chords, the default shortcuts and the user's overrides in `settings.toml`.
+
+use std::collections::BTreeMap;
+
+use tunal::config::{self, Settings};
+use tunal::keymap::{Chord, Command, Keymap};
+
+#[test]
+fn chords_round_trip_through_text() {
+ for text in [
+ "Ctrl+Shift+N",
+ "F3",
+ "Shift+Delete",
+ "Alt+Enter",
+ "Ctrl+Plus",
+ "Ctrl+=",
+ "Ctrl+-",
+ "Ctrl+,",
+ "Alt+.",
+ "Ctrl+PgDown",
+ "Ctrl+Shift+Tab",
+ "Ctrl+Alt+Shift+Super+F12",
+ "Space",
+ "Backspace",
+ ] {
+ let chord = Chord::parse(text).unwrap_or_else(|| panic!("{text} parses"));
+ assert_eq!(chord.to_string(), text);
+ assert_eq!(Chord::parse(&chord.to_string()), Some(chord));
+ }
+}
+
+#[test]
+fn parse_accepts_other_spellings() {
+ let same = |a: &str, b: &str| assert_eq!(Chord::parse(a), Chord::parse(b), "{a} = {b}");
+ same("ctrl+shift+n", "Ctrl+Shift+N");
+ same("Shift+Ctrl+N", "Ctrl+Shift+N");
+ same("Ctrl++", "Ctrl+Plus");
+ same("Del", "Delete");
+ same("Alt+Return", "Alt+Enter");
+ same("Ctrl+PageUp", "Ctrl+PgUp");
+ assert_eq!(Chord::parse("Hyper+X"), None);
+ assert_eq!(Chord::parse("Ctrl+"), None);
+ assert_eq!(Chord::parse("Ctrl+XY"), None);
+}
+
+#[test]
+fn key_events_become_chords() {
+ let event = |text: &str, ctrl, shift, alt| {
+ Chord::from_event(text, ctrl, shift, alt, false).map(|c| c.to_string())
+ };
+ assert_eq!(
+ event("n", true, true, false).as_deref(),
+ Some("Ctrl+Shift+N")
+ );
+ assert_eq!(
+ event("N", true, true, false).as_deref(),
+ Some("Ctrl+Shift+N")
+ );
+ // Shift+Tab arrives as Backtab.
+ assert_eq!(
+ event("\u{19}", true, true, false).as_deref(),
+ Some("Ctrl+Shift+Tab")
+ );
+ // Shift is part of a typed symbol.
+ assert_eq!(event("+", true, true, false).as_deref(), Some("Ctrl+Plus"));
+ assert_eq!(event("!", false, true, true).as_deref(), Some("Alt+!"));
+ assert_eq!(
+ event("\u{F706}", false, false, false).as_deref(),
+ Some("F3")
+ );
+ assert_eq!(
+ event("\u{7f}", false, true, false).as_deref(),
+ Some("Shift+Delete")
+ );
+ // A modifier pressed alone is no chord.
+ assert_eq!(event("\u{10}", false, true, false), None);
+ assert_eq!(event("\u{11}", true, false, false), None);
+}
+
+#[test]
+fn plain_letters_and_escape_are_refused() {
+ let refused = |t: &str| Chord::parse(t).unwrap().refusal().is_some();
+ assert!(refused("A"));
+ assert!(refused("Shift+A"));
+ assert!(refused("1"));
+ assert!(refused("Escape"));
+ assert!(!refused("Ctrl+A"));
+ assert!(!refused("F2"));
+ assert!(!refused("Delete"));
+ assert!(!refused("Space"));
+}
+
+#[test]
+fn every_default_parses_and_none_conflict() {
+ let keymap = Keymap::default();
+ for cmd in Command::ALL {
+ assert_eq!(
+ keymap.chords(cmd).len(),
+ cmd.defaults().len(),
+ "{} defaults parse",
+ cmd.id()
+ );
+ assert_eq!(Command::from_id(cmd.id()), Some(cmd));
+ for chord in keymap.chords(cmd) {
+ assert_eq!(chord.refusal(), None, "{chord} of {}", cmd.id());
+ }
+ }
+ assert!(keymap.conflicts().is_empty(), "{:?}", keymap.conflicts());
+ assert!(keymap.overrides().is_empty());
+}
+
+#[test]
+fn defaults_follow_the_usual_set() {
+ let keymap = Keymap::default();
+ let runs = |chord: &str| keymap.lookup(&Chord::parse(chord).unwrap());
+ assert_eq!(runs("Ctrl+T"), Some(Command::NewTab));
+ assert_eq!(runs("Ctrl+Shift+T"), Some(Command::ReopenTab));
+ assert_eq!(runs("Alt+2"), Some(Command::Tab(2)));
+ assert_eq!(runs("Alt+0"), Some(Command::LastTab));
+ assert_eq!(runs("F3"), Some(Command::Split));
+ assert_eq!(runs("Ctrl+F3"), Some(Command::FocusOtherPane));
+ assert_eq!(runs("Ctrl+="), Some(Command::ZoomIn));
+ assert_eq!(runs("Shift+Insert"), Some(Command::Paste));
+ assert_eq!(runs("Ctrl+K"), None);
+}
+
+#[test]
+fn overrides_replace_defaults_and_conflicts_show() {
+ let mut overrides = BTreeMap::new();
+ overrides.insert("rename".to_string(), vec!["Ctrl+R".to_string()]);
+ overrides.insert("reload".to_string(), vec!["Ctrl+R".to_string()]);
+ overrides.insert("quit".to_string(), Vec::new());
+ overrides.insert("no-such-command".to_string(), vec!["Ctrl+J".to_string()]);
+ let keymap = Keymap::new(&overrides);
+ assert_eq!(keymap.text(Command::Rename), "Ctrl+R");
+ assert_eq!(keymap.text(Command::Quit), "");
+ assert_eq!(keymap.lookup(&Chord::parse("F2").unwrap()), None);
+ let conflicts = keymap.conflicts();
+ assert_eq!(conflicts.len(), 1);
+ assert_eq!(conflicts[0].0.to_string(), "Ctrl+R");
+ assert_eq!(conflicts[0].1, vec![Command::Reload, Command::Rename]);
+ let r = Chord::parse("Ctrl+R").unwrap();
+ assert_eq!(keymap.holder(&r, Command::Rename), Some(Command::Reload));
+}
+
+#[test]
+fn assign_takes_the_chord_from_its_holder() {
+ let mut keymap = Keymap::default();
+ let f2 = Chord::parse("F2").unwrap();
+ assert_eq!(keymap.holder(&f2, Command::Reload), Some(Command::Rename));
+ keymap.assign(Command::Reload, f2.clone());
+ assert_eq!(keymap.lookup(&f2), Some(Command::Reload));
+ assert!(keymap.chords(Command::Rename).is_empty());
+ assert!(keymap.conflicts().is_empty());
+ let overrides = keymap.overrides();
+ assert_eq!(overrides.get("reload"), Some(&vec!["F2".to_string()]));
+ assert_eq!(overrides.get("rename"), Some(&Vec::new()));
+ keymap.reset(Command::Rename);
+ // Rename has F2 again: both hold it now.
+ assert_eq!(keymap.conflicts().len(), 1);
+ keymap.reset(Command::Reload);
+ assert!(keymap.overrides().is_empty());
+}
+
+#[test]
+fn overrides_survive_settings_toml() {
+ let mut keymap = Keymap::default();
+ keymap.assign(Command::NewWindow, Chord::parse("Ctrl+Alt+N").unwrap());
+ keymap.assign(Command::Quit, Chord::parse("Ctrl+Plus").unwrap());
+ let settings = Settings {
+ shortcuts: keymap.overrides(),
+ ..Settings::default()
+ };
+
+ // Pure serde first, then the real file in a scratch config directory.
+ let text = toml::to_string_pretty(&settings).expect("serializes");
+ assert!(text.contains("[shortcuts]"), "{text}");
+ let back: Settings = toml::from_str(&text).expect("parses");
+ assert_eq!(back.shortcuts, settings.shortcuts);
+
+ let dir = std::env::temp_dir().join(format!("tunal-keymap-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ // SAFETY: the only test in this binary that reads or sets the environment.
+ unsafe { std::env::set_var("XDG_CONFIG_HOME", &dir) };
+ config::save("settings", &settings).expect("saves");
+ let loaded: Settings = config::load("settings");
+ std::fs::remove_dir_all(&dir).unwrap();
+
+ let again = Keymap::new(&loaded.shortcuts);
+ assert_eq!(again.text(Command::NewWindow), "Ctrl+Alt+N");
+ assert_eq!(again.text(Command::Quit), "Ctrl+Plus");
+ assert_eq!(again.text(Command::NewTab), "Ctrl+T");
+}
diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint
index 463cf63..af32e4a 100644
--- a/crates/tunal/ui/app.slint
+++ b/crates/tunal/ui/app.slint
@@ -7,7 +7,7 @@ import { Menu, MenuItem, MenuEntry } from "components/menu.slint";
import { Dialog } from "components/dialog.slint";
import { ButtonKind } from "components/button.slint";
import { TextField } from "components/text-field.slint";
-import { DetailRow, FolderActions, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode } from "views/details-view.slint";
+import { DetailRow, FolderActions, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewKeys, ViewMode } from "views/details-view.slint";
import { GridRow } from "views/grid-view.slint";
import { TabBar, TabData } from "shell/tab-bar.slint";
import { Toolbar } from "shell/toolbar.slint";
@@ -27,7 +27,7 @@ import { OpenWithDialog, AppRow } from "dialogs/open-with.slint";
import { FolderAppearanceDialog, IconChoice } from "dialogs/folder-appearance.slint";
import { TagEditorDialog, TagEditorData, TagField } from "dialogs/tag-editor.slint";
import { TagLookupDialog, TagLookupData, ReleaseRow, MapRow } from "dialogs/tag-lookup.slint";
-import { SettingsDialog, SettingsData, EditRow } from "dialogs/settings.slint";
+import { SettingsDialog, SettingsData, EditRow, KeyRow } from "dialogs/settings.slint";
import { ConnectionDialog, ConnectionData } from "dialogs/connection.slint";
import { HostKeyDialog, HostKeyData } from "dialogs/host-key.slint";
import { SecretPromptDialog, SecretPromptData } from "dialogs/secret-prompt.slint";
@@ -35,7 +35,7 @@ import { Dnd, DropAction, DropMenu, DropTarget } from "components/drop-menu.slin
export { Theme, Shapes, ShapeKind, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode, GridRow }
export { ButtonKind, TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem, ToastData, ToastProgress, DialogAction, ConflictInfo, SettingsData, EditRow }
-export { PlayerData, FolderActions, ConnectionData, HostKeyData, SecretPromptData }
+export { PlayerData, FolderActions, ViewKeys, KeyRow, ConnectionData, HostKeyData, SecretPromptData }
export { PropertiesInfo, PropRow, AppRow, IconChoice, Dnd, DropAction, DropTarget, TagEditorData, TagField, TagLookupData, ReleaseRow, MapRow }
export { Gallery, GalleryPage } from "gallery.slint";
@@ -60,8 +60,9 @@ export component MainWindow inherits Window {
callback tab-closed(int);
callback tab-moved(int, int);
callback new-tab();
- callback cycle-tab(bool);
- callback close-tab();
+ in property <[MenuItem]> tab-menu;
+ callback tab-menu-requested(int);
+ callback tab-menu-activated(int, int);
// The panes of the current tab; the toolbar, breadcrumb and keys act on the active one.
in property <[PaneData]> panes;
@@ -85,15 +86,14 @@ export component MainWindow inherits Window {
callback grid-columns-changed(int, int);
callback motion-settled(int);
callback view-mode-selected(int, ViewMode);
- // Grid icon size of a pane: one size larger (1), smaller (-1) or the default (0).
- callback zoom(int, int);
in property <[MenuItem]> sort-menu;
callback sort-menu-activated(int, int);
- // File actions (actions.rs): the keys, the context menu, inline rename, jobs.
- // Called for every key the window sees with Ctrl, or a function or Delete key; true when
- // it was an action's shortcut.
- callback action-key(string, bool, bool, bool) -> bool;
+ // Every key the window sees, before the focused control: text, Ctrl, Shift, Alt, Super,
+ // and whether the location field has the keyboard. True when it ran a shortcut
+ // (keymap.rs, shell/commands.rs).
+ callback shortcut-key(string, bool, bool, bool, bool, bool) -> bool;
+ // File actions (actions.rs): the context menu, inline rename, jobs.
in property <[MenuItem]> context-menu-items;
// A right click in pane `i` on row (-1: none) at window coordinates.
callback context-menu-requested(int, int, length, length);
@@ -114,8 +114,11 @@ export component MainWindow inherits Window {
in property errors-body;
in property <[string]> errors-lines;
in property <[DialogAction]> errors-actions;
- // The button Enter and Escape press.
+ // The cookie's glyph; empty for the error sign.
+ in property errors-glyph;
+ // The buttons Enter and Escape press.
in property errors-default;
+ in property errors-cancel;
callback errors-answered(int);
// Settings dialog (settings.rs). `settings-opening` runs before it shows, so Rust can
@@ -134,6 +137,19 @@ export component MainWindow inherits Window {
callback menu-added(int);
callback menu-separator-added();
callback menu-reset();
+ // The shortcut editor (settings.rs).
+ in property <[KeyRow]> key-rows;
+ in property key-recording: -1;
+ in property key-message;
+ in property key-conflict;
+ in property key-can-reset-all;
+ callback key-search(string);
+ callback key-record(int);
+ callback key-pressed(string, bool, bool, bool, bool);
+ callback key-replace();
+ callback key-cancel();
+ callback key-reset(int);
+ callback key-reset-all();
// Folder appearance (folder/appearance.rs).
in property <[IconChoice]> appearance-icons;
@@ -240,6 +256,7 @@ export component MainWindow inherits Window {
// Returns the reason it can't be saved, or an empty string.
callback connection-saved(ConnectionData) -> string;
callback connection-removed();
+ callback connection-host-edited(ConnectionData) -> ConnectionData;
callback add-connection();
in property host-key;
// 0 refuse, 1 connect once, 2 connect and remember.
@@ -387,66 +404,7 @@ export component MainWindow inherits Window {
if event.text == Key.Shift || event.text == Key.ShiftR {
Dnd.shift = true;
}
- // Text fields (breadcrumb, rename) keep their own editing keys; Rust checks the rest.
- if !toolbar.editing
- && (event.modifiers.control || event.text == Key.F2 || event.text == Key.Delete)
- && root.action-key(event.text, event.modifiers.control, event.modifiers.shift, event.modifiers.alt) {
- return accept;
- }
- if event.modifiers.control && !event.modifiers.alt {
- if event.text == Key.Tab || event.text == Key.Backtab {
- root.cycle-tab(event.modifiers.shift || event.text == Key.Backtab);
- return accept;
- }
- if event.text == "t" || event.text == "T" {
- root.new-tab();
- return accept;
- }
- if event.text == "w" || event.text == "W" {
- root.close-tab();
- return accept;
- }
- if event.text == "l" || event.text == "L" {
- toolbar.edit-path();
- return accept;
- }
- if event.text == "d" || event.text == "D" {
- root.add-bookmark();
- return accept;
- }
- if !toolbar.editing && (event.text == "+" || event.text == "=") {
- root.zoom(root.active-pane, 1);
- return accept;
- }
- if !toolbar.editing && (event.text == "-" || event.text == "_") {
- root.zoom(root.active-pane, -1);
- return accept;
- }
- if !toolbar.editing && event.text == "0" {
- root.zoom(root.active-pane, 0);
- return accept;
- }
- }
- if event.modifiers.alt && !event.modifiers.control && !toolbar.editing {
- if event.text == Key.LeftArrow {
- root.back();
- return accept;
- }
- if event.text == Key.RightArrow {
- root.forward();
- return accept;
- }
- if event.text == Key.UpArrow {
- root.up();
- return accept;
- }
- }
- if event.text == Key.F3 {
- root.toggle-split();
- return accept;
- }
- if event.text == Key.F9 {
- root.toggle-sidebar();
+ if root.shortcut-key(event.text, event.modifiers.control, event.modifiers.shift, event.modifiers.alt, event.modifiers.meta, toolbar.editing) {
return accept;
}
reject
@@ -498,6 +456,10 @@ export component MainWindow inherits Window {
new-tab => {
root.new-tab();
}
+ tab-menu(id, x, y) => {
+ root.tab-menu-requested(id);
+ tab-popup.open-at(x, y);
+ }
}
}
@@ -740,6 +702,19 @@ export component MainWindow inherits Window {
}
}
+ tab-popup := Menu {
+ width: 100%;
+ height: 100%;
+ items: root.tab-menu;
+ leading-icons: true;
+ activated(index, sub) => {
+ root.tab-menu-activated(index, sub);
+ }
+ closed => {
+ root.focus-pane();
+ }
+ }
+
place-popup := Menu {
width: 100%;
height: 100%;
@@ -805,6 +780,32 @@ export component MainWindow inherits Window {
menu-reset => {
root.menu-reset();
}
+ key-rows: root.key-rows;
+ key-recording: root.key-recording;
+ key-message: root.key-message;
+ key-conflict: root.key-conflict;
+ key-can-reset-all: root.key-can-reset-all;
+ key-search(text) => {
+ root.key-search(text);
+ }
+ key-record(i) => {
+ root.key-record(i);
+ }
+ key-pressed(text, ctrl, shift, alt, meta) => {
+ root.key-pressed(text, ctrl, shift, alt, meta);
+ }
+ key-replace => {
+ root.key-replace();
+ }
+ key-cancel => {
+ root.key-cancel();
+ }
+ key-reset(i) => {
+ root.key-reset(i);
+ }
+ key-reset-all => {
+ root.key-reset-all();
+ }
closed => {
root.focus-pane();
}
@@ -937,8 +938,9 @@ export component MainWindow inherits Window {
body: root.errors-body;
lines: root.errors-lines;
actions: root.errors-actions;
+ glyph: root.errors-glyph != "" ? root.errors-glyph : Icons.error;
default-action: root.errors-default;
- cancel-action: root.errors-default;
+ cancel-action: root.errors-cancel;
answered(i) => {
root.errors-answered(i);
}
@@ -951,6 +953,9 @@ export component MainWindow inherits Window {
saved(data) => {
return root.connection-saved(data);
}
+ host-edited(data) => {
+ return root.connection-host-edited(data);
+ }
removed => {
root.connection-removed();
}
diff --git a/crates/tunal/ui/components/dialog.slint b/crates/tunal/ui/components/dialog.slint
index 858bc13..c1ecc0f 100644
--- a/crates/tunal/ui/components/dialog.slint
+++ b/crates/tunal/ui/components/dialog.slint
@@ -32,6 +32,8 @@ export component Dialog inherits Overlay {
// Fixed per kind of dialog so it doesn't resize while typing.
in property dialog-width: 400px;
in property content-focus;
+ // The children take every key, Escape, Tab and Enter too (a shortcut being recorded).
+ in property pass-keys;
callback action(index: int);
callback focus-content;
@@ -123,6 +125,9 @@ export component Dialog inherits Overlay {
// Runs before the focused child sees the key.
capture-key-pressed(event) => {
+ if root.pass-keys {
+ return reject;
+ }
if event.text == Key.Escape {
root.cancel();
return accept;
diff --git a/crates/tunal/ui/dialogs/setting-rows.slint b/crates/tunal/ui/dialogs/setting-rows.slint
new file mode 100644
index 0000000..2464b6b
--- /dev/null
+++ b/crates/tunal/ui/dialogs/setting-rows.slint
@@ -0,0 +1,145 @@
+import { Theme } from "../theme.slint";
+import { Chip } from "../components/chip.slint";
+import { Icons } from "../components/icon.slint";
+import { IconButton } from "../components/icon-button.slint";
+
+// The rows settings pages are made of.
+
+// One choice out of a few, as a row of chips.
+export component Choices inherits HorizontalLayout {
+ in property <[string]> names;
+ in property current;
+ callback picked(int);
+
+ spacing: Theme.space-2;
+ alignment: start;
+
+ for name[i] in root.names: Chip {
+ property sel: i == root.current;
+
+ text: name;
+ checked: self.sel;
+ changed sel => {
+ self.checked = self.sel;
+ }
+ clicked => {
+ root.picked(i);
+ self.checked = true;
+ }
+ }
+}
+
+// A setting: its name and a line about it, the control on the right.
+export component Setting inherits HorizontalLayout {
+ in property title;
+ in property hint;
+
+ spacing: Theme.space-4;
+ height: 52px;
+
+ VerticalLayout {
+ alignment: center;
+ horizontal-stretch: 1;
+
+ Text {
+ text: root.title;
+ color: Theme.on-surface;
+ font-size: Theme.body-medium.size;
+ font-weight: Theme.body-medium.weight;
+ overflow: elide;
+ }
+
+ if root.hint != "": Text {
+ text: root.hint;
+ color: Theme.on-surface-variant;
+ font-size: Theme.body-small.size;
+ font-weight: Theme.body-small.weight;
+ overflow: elide;
+ }
+ }
+
+ VerticalLayout {
+ alignment: center;
+
+ @children
+ }
+}
+
+// A whole number with minus and plus buttons.
+export component Stepper inherits HorizontalLayout {
+ in property value;
+ in property lo;
+ in property hi;
+ in property step;
+ in property unit;
+ callback picked(int);
+
+ spacing: Theme.space-2;
+
+ VerticalLayout {
+ alignment: center;
+ IconButton {
+ icon: Icons.remove;
+ tonal: true;
+ size: 32px;
+ icon-size: 18px;
+ enabled: root.value > root.lo;
+ tooltip: "Less";
+ clicked => {
+ root.picked(max(root.lo, root.value - root.step));
+ }
+ }
+ }
+
+ Text {
+ text: "\{root.value} \{root.unit}";
+ width: 72px;
+ color: Theme.on-surface;
+ font-size: Theme.body-medium.size;
+ font-weight: Theme.body-medium.weight;
+ horizontal-alignment: center;
+ vertical-alignment: center;
+ }
+
+ VerticalLayout {
+ alignment: center;
+ IconButton {
+ icon: Icons.add;
+ tonal: true;
+ size: 32px;
+ icon-size: 18px;
+ enabled: root.value < root.hi;
+ tooltip: "More";
+ clicked => {
+ root.picked(min(root.hi, root.value + root.step));
+ }
+ }
+ }
+}
+
+// A choice with its name above the chips.
+export component ChoiceSetting inherits VerticalLayout {
+ in property title;
+ in property <[string]> names;
+ in property current;
+ callback picked(int);
+
+ spacing: Theme.space-2;
+ padding-top: Theme.space-2;
+ padding-bottom: Theme.space-2;
+
+ Text {
+ text: root.title;
+ color: Theme.on-surface;
+ font-size: Theme.body-medium.size;
+ font-weight: Theme.body-medium.weight;
+ }
+
+ Choices {
+ names: root.names;
+ current: root.current;
+ picked(i) => {
+ root.picked(i);
+ }
+ }
+}
diff --git a/crates/tunal/ui/dialogs/settings.slint b/crates/tunal/ui/dialogs/settings.slint
index cf7f9a1..35bdf11 100644
--- a/crates/tunal/ui/dialogs/settings.slint
+++ b/crates/tunal/ui/dialogs/settings.slint
@@ -5,12 +5,13 @@ import { Dialog } from "../components/dialog.slint";
import { ButtonKind } from "../components/button.slint";
import { ListRow } from "../components/list-row.slint";
import { Switch } from "../components/switch.slint";
-import { Chip } from "../components/chip.slint";
import { Icons } from "../components/icon.slint";
-import { IconButton } from "../components/icon-button.slint";
import { MenuEditor, EditRow } from "menu-editor.slint";
+import { ChoiceSetting, Setting, Stepper } from "setting-rows.slint";
+import { MousePage } from "mouse-page.slint";
+import { ShortcutEditor, KeyRow } from "shortcut-editor.slint";
-export { EditRow }
+export { EditRow, KeyRow }
// What the settings pages show and change; Rust applies and stores every change.
export struct SettingsData {
@@ -39,145 +40,13 @@ export struct SettingsData {
connect-timeout: int,
keepalive: int,
idle-close: int,
-}
-
-// One choice out of a few, as a row of chips.
-component Choices inherits HorizontalLayout {
- in property <[string]> names;
- in property current;
- callback picked(int);
-
- spacing: Theme.space-2;
- alignment: start;
-
- for name[i] in root.names: Chip {
- property sel: i == root.current;
-
- text: name;
- checked: self.sel;
- changed sel => {
- self.checked = self.sel;
- }
- clicked => {
- root.picked(i);
- self.checked = true;
- }
- }
-}
-
-// A setting: its name and a line about it, the control on the right.
-component Setting inherits HorizontalLayout {
- in property title;
- in property hint;
-
- spacing: Theme.space-4;
- height: 52px;
-
- VerticalLayout {
- alignment: center;
- horizontal-stretch: 1;
-
- Text {
- text: root.title;
- color: Theme.on-surface;
- font-size: Theme.body-medium.size;
- font-weight: Theme.body-medium.weight;
- overflow: elide;
- }
-
- if root.hint != "": Text {
- text: root.hint;
- color: Theme.on-surface-variant;
- font-size: Theme.body-small.size;
- font-weight: Theme.body-small.weight;
- overflow: elide;
- }
- }
-
- VerticalLayout {
- alignment: center;
-
- @children
- }
-}
-
-// A whole number with minus and plus buttons.
-component Stepper inherits HorizontalLayout {
- in property value;
- in property lo;
- in property hi;
- in property step;
- in property unit;
- callback picked(int);
-
- spacing: Theme.space-2;
-
- VerticalLayout {
- alignment: center;
- IconButton {
- icon: Icons.remove;
- tonal: true;
- size: 32px;
- icon-size: 18px;
- enabled: root.value > root.lo;
- tooltip: "Less";
- clicked => {
- root.picked(max(root.lo, root.value - root.step));
- }
- }
- }
-
- Text {
- text: "\{root.value} \{root.unit}";
- width: 72px;
- color: Theme.on-surface;
- font-size: Theme.body-medium.size;
- font-weight: Theme.body-medium.weight;
- horizontal-alignment: center;
- vertical-alignment: center;
- }
-
- VerticalLayout {
- alignment: center;
- IconButton {
- icon: Icons.add;
- tonal: true;
- size: 32px;
- icon-size: 18px;
- enabled: root.value < root.hi;
- tooltip: "More";
- clicked => {
- root.picked(min(root.hi, root.value + root.step));
- }
- }
- }
-}
-
-// A choice with its name above the chips.
-component ChoiceSetting inherits VerticalLayout {
- in property title;
- in property <[string]> names;
- in property current;
- callback picked(int);
-
- spacing: Theme.space-2;
- padding-top: Theme.space-2;
- padding-bottom: Theme.space-2;
-
- Text {
- text: root.title;
- color: Theme.on-surface;
- font-size: Theme.body-medium.size;
- font-weight: Theme.body-medium.weight;
- }
-
- Choices {
- names: root.names;
- current: root.current;
- picked(i) => {
- root.picked(i);
- }
- }
+ // Mouse page: indexes into its choices (mouse-page.slint).
+ click: int,
+ middle-item: int,
+ middle-empty: int,
+ side-buttons: int,
+ empty-double: int,
+ executables: int,
}
// The settings, one page at a time; the pages are listed on the left.
@@ -191,6 +60,19 @@ export component SettingsDialog inherits Dialog {
in property <[EditRow]> menu-rows;
in property <[EditRow]> menu-available;
in property menu-can-reset;
+ // The shortcut editor (page 7).
+ in property <[KeyRow]> key-rows;
+ in property key-recording: -1;
+ in property key-message;
+ in property key-conflict;
+ in property key-can-reset-all;
+ callback key-search(string);
+ callback key-record(int);
+ callback key-pressed(string, bool, bool, bool, bool);
+ callback key-replace();
+ callback key-cancel();
+ callback key-reset(int);
+ callback key-reset-all();
callback changed(SettingsData);
callback menu-context-selected(int);
callback menu-moved(from: int, to: int);
@@ -200,14 +82,16 @@ export component SettingsDialog inherits Dialog {
callback menu-reset();
callback closed();
- property <[string]> pages: ["General", "View", "Previews", "Motion", "Network", "Context menus"];
- property <[string]> glyphs: ["\u{e8b8}", "\u{e8f4}", "\u{e3f4}", "\u{e037}", "\u{e2bd}", "\u{e5d4}"];
+ property <[string]> pages: ["General", "View", "Previews", "Motion", "Network", "Context menus", "Mouse", "Shortcuts"];
+ property <[string]> glyphs: ["\u{e8b8}", "\u{e8f4}", "\u{e3f4}", "\u{e037}", "\u{e2bd}", "\u{e5d4}", "\u{e323}", "\u{e312}"];
title: "Settings";
dialog-width: 780px;
actions: [{ text: "Done", kind: ButtonKind.filled }];
default-action: 0;
cancel-action: 0;
+ // While a shortcut is recorded, Escape, Tab and Enter are keys to record.
+ pass-keys: root.page == 7 && root.key-recording >= 0;
action(i) => {
self.close();
root.closed();
@@ -228,6 +112,9 @@ export component SettingsDialog inherits Dialog {
icon: root.glyphs[i];
selected: i == root.page;
clicked => {
+ if root.key-recording >= 0 {
+ root.key-cancel();
+ }
root.page = i;
}
}
@@ -236,7 +123,7 @@ export component SettingsDialog inherits Dialog {
Rectangle {
horizontal-stretch: 1;
- if root.page < 5: ScrollView {
+ if root.page < 5 || root.page == 6: ScrollView {
VerticalLayout {
alignment: start;
@@ -245,7 +132,7 @@ export component SettingsDialog inherits Dialog {
Setting {
title: "Show hidden files";
- hint: "Files whose names start with a dot. Ctrl+H in a folder.";
+ hint: "Files whose names start with a dot. The keys are on the Shortcuts page.";
Switch {
checked: root.data.show-hidden;
changed checked => {
@@ -523,7 +410,61 @@ export component SettingsDialog inherits Dialog {
}
}
+ if root.page == 6: MousePage {
+ click: root.data.click;
+ middle-item: root.data.middle-item;
+ middle-empty: root.data.middle-empty;
+ side-buttons: root.data.side-buttons;
+ empty-double: root.data.empty-double;
+ executables: root.data.executables;
+ picked(row, value) => {
+ if row == 0 {
+ root.data.click = value;
+ } else if row == 1 {
+ root.data.middle-item = value;
+ } else if row == 2 {
+ root.data.middle-empty = value;
+ } else if row == 3 {
+ root.data.side-buttons = value;
+ } else if row == 4 {
+ root.data.empty-double = value;
+ } else {
+ root.data.executables = value;
+ }
+ root.changed(root.data);
+ }
}
+
+ }
+ }
+
+ if root.page == 7: ShortcutEditor {
+ rows: root.key-rows;
+ recording: root.key-recording;
+ message: root.key-message;
+ conflict: root.key-conflict;
+ can-reset-all: root.key-can-reset-all;
+ search(text) => {
+ root.key-search(text);
+ }
+ record(i) => {
+ root.key-record(i);
+ }
+ pressed(text, ctrl, shift, alt, meta) => {
+ root.key-pressed(text, ctrl, shift, alt, meta);
+ }
+ replace => {
+ root.key-replace();
+ }
+ cancel => {
+ root.key-cancel();
+ }
+ reset(i) => {
+ root.key-reset(i);
+ }
+ reset-all => {
+ root.key-reset-all();
+ }
}
if root.page == 5: MenuEditor {
diff --git a/crates/tunal/ui/dialogs/shortcut-editor.slint b/crates/tunal/ui/dialogs/shortcut-editor.slint
new file mode 100644
index 0000000..d057423
--- /dev/null
+++ b/crates/tunal/ui/dialogs/shortcut-editor.slint
@@ -0,0 +1,236 @@
+import { ListView } from "std-widgets.slint";
+import { Theme } from "../theme.slint";
+import { Motion } from "../motion.slint";
+import { Icons } from "../components/icon.slint";
+import { IconButton } from "../components/icon-button.slint";
+import { Button, ButtonKind } from "../components/button.slint";
+import { Chip, ChipKind } from "../components/chip.slint";
+import { StateLayer } from "../components/state-layer.slint";
+import { TextField } from "../components/text-field.slint";
+
+// One command with its keys, as the editor lists it.
+export struct KeyRow {
+ // The command, for the callbacks (its place in the full list).
+ index: int,
+ label: string,
+ // `Ctrl+C, Ctrl+Insert`; empty when unbound.
+ keys: string,
+ // Differs from the default: the row offers Reset.
+ edited: bool,
+}
+
+// The keys of one command: a pill, or the prompt while a new key is recorded.
+component KeysPill inherits Rectangle {
+ in property keys;
+ in property recording;
+
+ property shown: root.recording ? "Press a key…" : root.keys != "" ? root.keys : "None";
+
+ height: 28px;
+ width: label.preferred-width + 2 * Theme.space-3;
+ border-radius: Theme.corner-full(self.height);
+ background: root.recording ? Theme.primary-container : Theme.surface-container-highest;
+ animate background { duration: Motion.time(Motion.short4); easing: Motion.standard; }
+
+ label := Text {
+ text: root.shown;
+ color: root.recording ? Theme.on-primary-container
+ : root.keys != "" ? Theme.on-surface : Theme.on-surface-variant;
+ font-size: Theme.label-large.size;
+ font-weight: Theme.label-large.weight;
+ horizontal-alignment: center;
+ vertical-alignment: center;
+ }
+}
+
+// The shortcut editor: a searchable list of commands with their keys. A click records a new
+// key for that command; a key another command has shows the conflict in the row, with Replace
+// (which takes it from the other command) and Cancel. The owner applies and stores each
+// change and hands back the rows.
+export component ShortcutEditor inherits FocusScope {
+ in property <[KeyRow]> rows;
+ // The command being recorded (a row's `index`), -1 for none.
+ in property recording: -1;
+ // Under the recording row: why the key can't be used, or the conflict.
+ in property message;
+ // `message` is a conflict that Replace settles.
+ in property conflict;
+ in property can-reset-all;
+ callback search(text: string);
+ callback record(index: int);
+ // A key while recording: Slint's key text and Ctrl, Shift, Alt, Super.
+ callback pressed(text: string, ctrl: bool, shift: bool, alt: bool, meta: bool);
+ callback replace();
+ callback cancel();
+ callback reset(index: int);
+ callback reset-all();
+
+ property row-h: 44px;
+
+ // Takes the keys while a command is recorded; Escape gives up.
+ focus-on-click: false;
+ changed recording => {
+ if root.recording >= 0 {
+ root.focus();
+ }
+ }
+ key-pressed(event) => {
+ if root.recording < 0 {
+ return reject;
+ }
+ if event.text == Key.Escape {
+ root.cancel();
+ } else {
+ root.pressed(event.text, event.modifiers.control, event.modifiers.shift, event.modifiers.alt, event.modifiers.meta);
+ }
+ accept
+ }
+
+ VerticalLayout {
+ spacing: Theme.space-2;
+
+ HorizontalLayout {
+ spacing: Theme.space-3;
+ vertical-stretch: 0;
+
+ TextField {
+ horizontal-stretch: 1;
+ placeholder: "Search commands or keys";
+ edited(text) => {
+ root.search(text);
+ }
+ }
+
+ VerticalLayout {
+ alignment: start;
+ padding-top: Theme.space-1;
+
+ Chip {
+ kind: ChipKind.assist;
+ icon: Icons.restore;
+ text: "Reset all";
+ enabled: root.can-reset-all;
+ clicked => {
+ root.reset-all();
+ }
+ }
+ }
+ }
+
+ ListView {
+ vertical-stretch: 1;
+
+ for row in root.rows: StateLayer {
+ property is-recording: row.index == root.recording;
+ property open: self.is-recording && root.message != "";
+
+ height: root.row-h + (self.open ? root.row-h : 0);
+ border-radius: Theme.corner-sm;
+ squeeze: Motion.squeeze-large;
+ ring-offset: -Theme.focus-ring-width;
+ focusable: false;
+ background: self.is-recording ? Theme.surface-container-highest : transparent;
+ animate height { duration: Motion.time(Motion.short4); easing: Motion.emphasized; }
+ animate background { duration: Motion.time(Motion.short3); easing: Motion.standard; }
+ clip: true;
+ accessible-role: list-item;
+ accessible-label: row.label;
+ accessible-description: row.keys;
+ clicked => {
+ root.record(row.index);
+ }
+
+ VerticalLayout {
+ padding-left: Theme.space-3;
+ padding-right: Theme.space-1;
+
+ HorizontalLayout {
+ height: root.row-h;
+ spacing: Theme.space-2;
+
+ Text {
+ horizontal-stretch: 1;
+ text: row.label;
+ color: Theme.on-surface;
+ font-size: Theme.body-medium.size;
+ font-weight: Theme.body-medium.weight;
+ vertical-alignment: center;
+ overflow: elide;
+ }
+
+ VerticalLayout {
+ alignment: center;
+
+ KeysPill {
+ keys: row.keys;
+ recording: row.index == root.recording;
+ }
+ }
+
+ VerticalLayout {
+ alignment: center;
+ width: 32px;
+
+ if row.edited: IconButton {
+ size: 32px;
+ icon-size: 20px;
+ icon: Icons.restore;
+ tooltip: "Back to the default keys";
+ clicked => {
+ root.reset(row.index);
+ }
+ }
+ }
+ }
+
+ if row.index == root.recording && root.message != "": HorizontalLayout {
+ height: root.row-h;
+ spacing: Theme.space-2;
+
+ Text {
+ horizontal-stretch: 1;
+ text: root.message;
+ color: root.conflict ? Theme.on-surface : Theme.error;
+ font-size: Theme.body-small.size;
+ font-weight: Theme.body-small.weight;
+ vertical-alignment: center;
+ wrap: word-wrap;
+ }
+
+ VerticalLayout {
+ alignment: center;
+
+ Button {
+ text: "Cancel";
+ kind: ButtonKind.text;
+ clicked => {
+ root.cancel();
+ }
+ }
+ }
+
+ if root.conflict: VerticalLayout {
+ alignment: center;
+
+ Button {
+ text: "Replace";
+ kind: ButtonKind.tonal;
+ clicked => {
+ root.replace();
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Text {
+ text: root.recording >= 0 ? "Press the new key with its modifiers. Escape cancels." : "Click a command to give it a new key.";
+ color: Theme.on-surface-variant;
+ font-size: Theme.body-small.size;
+ font-weight: Theme.body-small.weight;
+ wrap: word-wrap;
+ }
+}
+}
diff --git a/crates/tunal/ui/shell/tab-bar.slint b/crates/tunal/ui/shell/tab-bar.slint
index 3286f73..babd9cf 100644
--- a/crates/tunal/ui/shell/tab-bar.slint
+++ b/crates/tunal/ui/shell/tab-bar.slint
@@ -21,6 +21,8 @@ component ShellTab inherits StateLayer {
// Off for the only tab: there is always one.
in property closable;
callback close();
+ // A right click, at window coordinates.
+ callback menu(length, length);
// Left press moved past the drag threshold, then each move while dragged.
callback drag-moved(length);
callback drag-ended();
@@ -52,6 +54,9 @@ component ShellTab inherits StateLayer {
if event.button == PointerEventButton.middle && event.kind == PointerEventKind.up && root.closable {
root.close();
}
+ if event.button == PointerEventButton.right && event.kind == PointerEventKind.down {
+ root.menu(root.absolute-position.x + root.mouse-x, root.absolute-position.y + root.mouse-y);
+ }
if event.button == PointerEventButton.left && event.kind == PointerEventKind.up && root.dragging {
root.dragging = false;
root.drag-ended();
@@ -120,6 +125,8 @@ export component TabBar {
// Tab `id` dropped at `slot`.
callback moved(id: int, slot: int);
callback new-tab();
+ // Right click on tab `id` at window coordinates.
+ callback tab-menu(id: int, x: length, y: length);
property gap: Theme.space-1;
property tab-height: 36px;
@@ -190,6 +197,9 @@ export component TabBar {
close => {
root.close(tab.id);
}
+ menu(x, y) => {
+ root.tab-menu(tab.id, x, y);
+ }
drag-moved(dx) => {
if root.drag-id != tab.id {
root.drag-id = tab.id;
diff --git a/crates/tunal/ui/views/details-view.slint b/crates/tunal/ui/views/details-view.slint
index f3def79..04cc7da 100644
--- a/crates/tunal/ui/views/details-view.slint
+++ b/crates/tunal/ui/views/details-view.slint
@@ -218,9 +218,19 @@ component Cell inherits HorizontalLayout {
}
}
-// Buttons of the folder messages that act on a pane's folder (the shell finds the pane).
+// Buttons of the folder messages that act on a pane's folder (the shell finds the pane),
+// and the clicks Rust decides on from the Mouse settings.
export global FolderActions {
callback retry();
+ // A middle click in pane `pane` on `row` (-1: empty space).
+ callback middle-clicked(pane: int, row: int);
+ callback empty-double-clicked(pane: int);
+}
+
+// Plain Space or Backspace in a folder view with no filter typed: Rust runs the shortcut
+// bound to it (keymap.rs) and returns true, or the key types into the filter.
+export global ViewKeys {
+ callback key(text: string, shift: bool) -> bool;
}
// Centred message for the loading, empty and error states.
@@ -276,9 +286,10 @@ export component Message inherits VerticalLayout {
}
}
-// The keyboard of a folder view: arrows move the cursor (`move`), typing filters, Ctrl+A
-// selects all, Ctrl+H toggles hidden files, Enter opens, Esc clears the filter, then the
-// selection. Left and Right only reach `move` when `horizontal` is set (the grid).
+// The keyboard of a folder view: arrows move the cursor (`move`), typing filters, Enter
+// opens, Esc clears the filter, then the selection; Space and Backspace run their shortcut
+// first (ViewKeys). Left and Right only reach `move` when `horizontal` is set (the grid).
+// The window's shortcuts (keymap.rs) see every key before this.
export component FolderKeys inherits FocusScope {
in property state;
in property horizontal;
@@ -291,17 +302,13 @@ export component FolderKeys inherits FocusScope {
callback clear-selection();
key-pressed(event) => {
- if event.modifiers.control && (event.text == "a" || event.text == "A") {
- root.select-all();
- return accept;
- }
- if event.modifiers.control && (event.text == "h" || event.text == "H") {
- root.toggle-hidden();
- return accept;
- }
if event.modifiers.control || event.modifiers.alt || event.modifiers.meta {
return reject;
}
+ if root.state.filter == "" && (event.text == Key.Space || event.text == Key.Backspace)
+ && ViewKeys.key(event.text, event.modifiers.shift) {
+ return accept;
+ }
if event.text == Key.UpArrow {
root.move(NavKey.up, event.modifiers.shift);
} else if event.text == Key.DownArrow {
@@ -694,6 +701,9 @@ export component DetailsView inherits Rectangle {
if event.button == PointerEventButton.right && event.kind == PointerEventKind.down {
root.context-menu(i, self.absolute-position.x + self.mouse-x, self.absolute-position.y + self.mouse-y);
}
+ if event.button == PointerEventButton.middle && event.kind == PointerEventKind.up {
+ FolderActions.middle-clicked(root.pane, i);
+ }
}
clicked => {
keys.focus();