309 lines
11 KiB
Rust
309 lines
11 KiB
Rust
//! Every action, its name and its shortcut. A new action is a variant of `Action`, a line in `ALL`, an `action.<id>` text,
|
|
//! and its arm in `App::run` or `Main::run`; the shortcuts page and the palette show it by themselves.
|
|
|
|
use eframe::egui::{Event, Key, Modifiers, Ui};
|
|
use medlar_core::settings::Settings;
|
|
use medlar_core::strings;
|
|
use std::cell::RefCell;
|
|
use std::collections::HashMap;
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
|
pub enum Action {
|
|
Add,
|
|
Find,
|
|
Palette,
|
|
Settings,
|
|
Rail,
|
|
View,
|
|
ResumeAll,
|
|
PauseAll,
|
|
Snail,
|
|
Network,
|
|
Quit,
|
|
SelectAll,
|
|
OpenOrRun,
|
|
Toggle,
|
|
Details,
|
|
Show,
|
|
Copy,
|
|
Page,
|
|
Start,
|
|
Resume,
|
|
Pause,
|
|
Stop,
|
|
Redownload,
|
|
Rename,
|
|
Folder,
|
|
Link,
|
|
Up,
|
|
Down,
|
|
Remove,
|
|
Bin,
|
|
}
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub enum Group {
|
|
/// Anywhere in the window.
|
|
App,
|
|
/// In the list, most of them for the selected downloads.
|
|
List,
|
|
}
|
|
|
|
impl Group {
|
|
pub const ALL: [Group; 2] = [Group::App, Group::List];
|
|
|
|
pub fn label(self) -> String {
|
|
let id = match self {
|
|
Group::App => "app",
|
|
Group::List => "list",
|
|
};
|
|
strings::text(&format!("keys.group.{id}"), &[])
|
|
}
|
|
}
|
|
|
|
pub struct Entry {
|
|
pub action: Action,
|
|
pub id: &'static str,
|
|
pub icon: &'static str,
|
|
pub group: Group,
|
|
/// As `Shortcut::parse` reads it; empty for none.
|
|
keys: &'static str,
|
|
}
|
|
|
|
const fn entry(action: Action, id: &'static str, icon: &'static str, group: Group, keys: &'static str) -> Entry {
|
|
Entry { action, id, icon, group, keys }
|
|
}
|
|
|
|
pub const ALL: &[Entry] = &[
|
|
entry(Action::Add, "add", "add", Group::App, "Ctrl+N"),
|
|
entry(Action::Find, "find", "search", Group::App, "Ctrl+F"),
|
|
entry(Action::Palette, "palette", "terminal", Group::App, "Ctrl+K"),
|
|
entry(Action::Settings, "settings", "settings", Group::App, "Ctrl+,"),
|
|
entry(Action::Rail, "rail", "menu", Group::App, "Ctrl+B"),
|
|
entry(Action::View, "view", "view_agenda", Group::App, "Ctrl+Shift+V"),
|
|
entry(Action::ResumeAll, "resume_all", "play_arrow", Group::App, "Ctrl+Shift+R"),
|
|
entry(Action::PauseAll, "pause_all", "pause", Group::App, "Ctrl+Shift+P"),
|
|
entry(Action::Snail, "snail", "slow_motion_video", Group::App, "Ctrl+Shift+S"),
|
|
entry(Action::Network, "network", "language", Group::App, ""),
|
|
entry(Action::Quit, "quit", "power_settings_new", Group::App, "Ctrl+Q"),
|
|
entry(Action::SelectAll, "select_all", "select_all", Group::List, "Ctrl+A"),
|
|
entry(Action::OpenOrRun, "open", "open_in_new", Group::List, "Enter"),
|
|
entry(Action::Toggle, "toggle", "play_circle", Group::List, "Space"),
|
|
entry(Action::Details, "details", "info", Group::List, "Alt+Enter"),
|
|
entry(Action::Show, "show", "folder_open", Group::List, "Ctrl+O"),
|
|
entry(Action::Copy, "copy", "content_copy", Group::List, "Ctrl+C"),
|
|
entry(Action::Page, "page", "public", Group::List, ""),
|
|
entry(Action::Start, "start", "bolt", Group::List, "Ctrl+Enter"),
|
|
entry(Action::Resume, "resume", "play_arrow", Group::List, ""),
|
|
entry(Action::Pause, "pause", "pause", Group::List, ""),
|
|
entry(Action::Stop, "stop", "low_priority", Group::List, ""),
|
|
entry(Action::Redownload, "redownload", "replay", Group::List, "Ctrl+R"),
|
|
entry(Action::Rename, "rename", "edit", Group::List, "F2"),
|
|
entry(Action::Folder, "folder", "folder", Group::List, "Ctrl+M"),
|
|
entry(Action::Link, "link", "link", Group::List, "Ctrl+L"),
|
|
entry(Action::Up, "up", "arrow_upward", Group::List, "Alt+Up"),
|
|
entry(Action::Down, "down", "arrow_downward", Group::List, "Alt+Down"),
|
|
entry(Action::Remove, "remove", "close", Group::List, "Del"),
|
|
entry(Action::Bin, "bin", "delete", Group::List, "Shift+Del"),
|
|
];
|
|
|
|
impl Entry {
|
|
pub fn label(&self) -> String {
|
|
strings::text(&format!("action.{}", self.id), &[])
|
|
}
|
|
}
|
|
|
|
impl Action {
|
|
pub fn entry(self) -> &'static Entry {
|
|
ALL.iter().find(|e| e.action == self).expect("every action has a line in ALL")
|
|
}
|
|
}
|
|
|
|
/// One key with any of Ctrl, Alt and Shift.
|
|
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
|
pub struct Shortcut {
|
|
pub ctrl: bool,
|
|
pub alt: bool,
|
|
pub shift: bool,
|
|
pub key: Key,
|
|
}
|
|
|
|
/// Keys with a short name of their own.
|
|
const SHORT: [(Key, &str); 6] = [
|
|
(Key::Delete, "Del"),
|
|
(Key::ArrowUp, "Up"),
|
|
(Key::ArrowDown, "Down"),
|
|
(Key::ArrowLeft, "Left"),
|
|
(Key::ArrowRight, "Right"),
|
|
(Key::Comma, ","),
|
|
];
|
|
|
|
impl Shortcut {
|
|
pub fn new(m: Modifiers, key: Key) -> Shortcut {
|
|
Shortcut { ctrl: m.command || m.ctrl, alt: m.alt, shift: m.shift, key }
|
|
}
|
|
|
|
/// `Ctrl+Shift+N`. None for what can't be a shortcut.
|
|
pub fn parse(text: &str) -> Option<Shortcut> {
|
|
let mut m = Modifiers::NONE;
|
|
let mut rest = text.trim();
|
|
// The key itself may be a plus.
|
|
while let Some((name, after)) = rest.split_once('+').filter(|(name, after)| !name.is_empty() && !after.is_empty()) {
|
|
match name.to_ascii_lowercase().as_str() {
|
|
"ctrl" => m.ctrl = true,
|
|
"alt" => m.alt = true,
|
|
"shift" => m.shift = true,
|
|
_ => return None,
|
|
}
|
|
rest = after;
|
|
}
|
|
let short = SHORT.iter().find(|(_, name)| name.eq_ignore_ascii_case(rest)).map(|(k, _)| *k);
|
|
Some(Shortcut::new(m, short.or_else(|| Key::from_name(rest))?))
|
|
}
|
|
|
|
pub fn label(self) -> String {
|
|
let name = SHORT.iter().find(|(k, _)| *k == self.key).map_or(self.key.name(), |(_, n)| n);
|
|
let mods = [(self.ctrl, "Ctrl+"), (self.alt, "Alt+"), (self.shift, "Shift+")];
|
|
mods.iter().filter(|(on, _)| *on).map(|(_, n)| *n).chain([name]).collect()
|
|
}
|
|
|
|
/// Moving about, leaving and pasting belong to the window.
|
|
pub fn taken(self) -> bool {
|
|
let moves = [Key::ArrowUp, Key::ArrowDown, Key::ArrowLeft, Key::ArrowRight, Key::Home, Key::End, Key::PageUp, Key::PageDown, Key::Tab, Key::Escape];
|
|
let edits = [Key::V, Key::X, Key::Z];
|
|
moves.contains(&self.key) && !self.alt || self.key == Key::Tab || self.ctrl && !self.alt && !self.shift && edits.contains(&self.key)
|
|
}
|
|
|
|
/// Would type something or press what has the keyboard, so it can't count everywhere.
|
|
pub fn types(self) -> bool {
|
|
let function = self.key.name().strip_prefix('F').is_some_and(|n| n.parse::<u8>().is_ok());
|
|
!self.ctrl && !self.alt && !function
|
|
}
|
|
|
|
/// The window system turns copying and cutting into events of their own.
|
|
fn fits(self, e: &Event) -> bool {
|
|
match e {
|
|
Event::Key { key, pressed: true, modifiers, .. } => Shortcut::new(*modifiers, *key) == self,
|
|
Event::Copy => self == Shortcut { ctrl: true, alt: false, shift: false, key: Key::C },
|
|
Event::Cut => self == Shortcut { ctrl: true, alt: false, shift: false, key: Key::X },
|
|
_ => false,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// What was pressed, for recording a shortcut.
|
|
pub fn recorded(ui: &Ui) -> Option<Shortcut> {
|
|
let plain = |key| Some(Shortcut { ctrl: true, alt: false, shift: false, key });
|
|
ui.input(|i| {
|
|
i.events.iter().find_map(|e| match e {
|
|
Event::Key { key, pressed: true, modifiers, .. } => Some(Shortcut::new(*modifiers, *key)),
|
|
Event::Copy => plain(Key::C),
|
|
Event::Cut => plain(Key::X),
|
|
Event::Paste(_) => plain(Key::V),
|
|
_ => None,
|
|
})
|
|
})
|
|
}
|
|
|
|
thread_local! {
|
|
/// The window's own; set once per change of the settings.
|
|
static MAP: RefCell<HashMap<Action, Option<Shortcut>>> = RefCell::default();
|
|
}
|
|
|
|
/// Takes the shortcuts of the settings.
|
|
pub fn set(s: &Settings) {
|
|
MAP.set(ALL.iter().map(|e| (e.action, of(s, e.action))).collect());
|
|
}
|
|
|
|
/// The shortcut in these settings: the user's own, or the usual one. What can't be read counts as the usual one.
|
|
pub fn of(s: &Settings, action: Action) -> Option<Shortcut> {
|
|
let e = action.entry();
|
|
match s.shortcuts.get(e.id) {
|
|
Some(own) if own.is_empty() => None,
|
|
Some(own) => Shortcut::parse(own).or(usual(action)),
|
|
None => usual(action),
|
|
}
|
|
}
|
|
|
|
pub fn usual(action: Action) -> Option<Shortcut> {
|
|
Shortcut::parse(action.entry().keys)
|
|
}
|
|
|
|
/// None takes it away.
|
|
pub fn change(s: &mut Settings, action: Action, keys: Option<Shortcut>) {
|
|
let id = action.entry().id.to_string();
|
|
if keys == usual(action) {
|
|
s.shortcuts.remove(&id);
|
|
} else {
|
|
s.shortcuts.insert(id, keys.map(Shortcut::label).unwrap_or_default());
|
|
}
|
|
}
|
|
|
|
/// The others with the same keys. Both groups are heard at once, so all of them count.
|
|
pub fn conflicts(s: &Settings, action: Action) -> Vec<Action> {
|
|
let Some(keys) = of(s, action) else { return vec![] };
|
|
ALL.iter().map(|e| e.action).filter(|a| *a != action && of(s, *a) == Some(keys)).collect()
|
|
}
|
|
|
|
/// For tooltips and menus; empty without one.
|
|
pub fn label(action: Action) -> String {
|
|
MAP.with_borrow(|m| m.get(&action).copied().unwrap_or_else(|| usual(action))).map(Shortcut::label).unwrap_or_default()
|
|
}
|
|
|
|
/// Was its shortcut pressed? Nothing else sees it then.
|
|
pub fn pressed(ui: &Ui, action: Action) -> bool {
|
|
let Some(keys) = MAP.with_borrow(|m| m.get(&action).copied().unwrap_or_else(|| usual(action))) else { return false };
|
|
if keys.types() && ui.ctx().text_edit_focused() {
|
|
return false;
|
|
}
|
|
ui.input_mut(|i| {
|
|
let before = i.events.len();
|
|
i.events.retain(|e| !keys.fits(e));
|
|
i.events.len() < before
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::collections::HashSet;
|
|
|
|
#[test]
|
|
fn every_action_has_one_line_a_text_and_readable_keys() {
|
|
let mut seen = HashSet::new();
|
|
for e in ALL {
|
|
assert!(seen.insert(e.id), "{}", e.id);
|
|
assert_ne!(e.label(), format!("action.{}", e.id));
|
|
assert!(e.keys.is_empty() || usual(e.action).is_some_and(|k| k.label() == e.keys && !k.taken()), "{}", e.keys);
|
|
assert_eq!(conflicts(&Settings::default(), e.action), [], "{}", e.id);
|
|
if e.group == Group::App {
|
|
assert!(usual(e.action).is_none_or(|k| !k.types()), "{}", e.id);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn shortcuts_are_read_and_written_the_same() {
|
|
for text in ["Ctrl+N", "Alt+Up", "Shift+Del", "F2", "Ctrl+Alt+Shift+Enter", "Ctrl+,", "Space"] {
|
|
assert_eq!(Shortcut::parse(text).unwrap().label(), text);
|
|
}
|
|
for bad in ["", "Ctrl+", "Meta+N", "Ctrl+Nothing"] {
|
|
assert_eq!(Shortcut::parse(bad), None, "{bad}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn own_shortcuts_replace_the_usual_ones_and_conflicts_are_seen() {
|
|
let mut s = Settings::default();
|
|
let n = Shortcut::parse("Ctrl+N");
|
|
change(&mut s, Action::Find, n);
|
|
assert_eq!((of(&s, Action::Find), conflicts(&s, Action::Find)), (n, vec![Action::Add]));
|
|
change(&mut s, Action::Add, None);
|
|
assert_eq!((of(&s, Action::Add), conflicts(&s, Action::Find)), (None, vec![]));
|
|
change(&mut s, Action::Find, usual(Action::Find));
|
|
change(&mut s, Action::Add, usual(Action::Add));
|
|
assert!(s.shortcuts.is_empty());
|
|
s.shortcuts.insert("add".into(), "rubbish".into());
|
|
assert_eq!(of(&s, Action::Add), n);
|
|
}
|
|
}
|