feat: keyboard shortcuts
Space plays or pauses, ⌘←/→ skips, ⇧←/→ seeks 10 seconds, ⌘↑/↓ sets the volume, ⌘L likes the playing track, ⌘F or / focuses search, ⌘[ or ⌥← goes back, ⌘1–5 and ⌘, open the sidebar sections and Settings, and Esc closes what's open. ⌘ is Ctrl on Windows and Linux. Keys a focused text field uses never reach the shortcuts, and letters fall back to their key position so they work on a Russian layout. Opening Search now puts the cursor in the field. Settings lists the shortcuts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
766ed22726
commit
e5c43fbb77
6 files changed
+316
-2
No files matched your search
+84
-1
@@ -25,6 +25,7 @@ use crate::screens::wave::WaveScreen;
|
||||
use crate::screens::detail::{self, Page};
|
||||
use crate::screens::{self, Loadable, sign_in};
|
||||
use crate::session::{self, Restored};
|
||||
use crate::shortcuts::{self, Shortcut};
|
||||
use crate::store::{self, Appearance, Locale, Quality, Settings};
|
||||
use crate::ui::theme::{self, shell};
|
||||
use crate::widgets::drawer::{self, Panel};
|
||||
@@ -138,6 +139,7 @@ pub enum Message {
|
||||
ClearCoverCache,
|
||||
CoverCacheCleared(Result<(), String>),
|
||||
Media(crate::media::Command),
|
||||
Shortcut(Shortcut),
|
||||
/// A window opened; Windows media controls need its handle.
|
||||
WindowOpened(iced::window::Id),
|
||||
MediaWindow(u64),
|
||||
@@ -273,6 +275,9 @@ impl App {
|
||||
if let Session::SignedOut(sign_in) = &self.session {
|
||||
subs.push(sign_in.subscription().map(Message::SignIn));
|
||||
}
|
||||
if matches!(self.session, Session::SignedIn { .. }) {
|
||||
subs.push(shortcuts::subscription().map(Message::Shortcut));
|
||||
}
|
||||
// The hero's lines drift only while My Wave plays and the hero is on screen.
|
||||
let hero_visible = matches!(self.nav.current(), Route::Home | Route::Wave);
|
||||
let wave_playing = self.player.wave_station() == Some(MY_WAVE)
|
||||
@@ -470,7 +475,9 @@ impl App {
|
||||
self.sheet = None;
|
||||
self.nav.go(route);
|
||||
let (close, _) = self.search.update(search::Msg::CloseSuggestions, None);
|
||||
return Task::batch([close, self.on_enter(route)]);
|
||||
// Opening Search is a request to type.
|
||||
let focus = if route == Route::Search { focus_search() } else { Task::none() };
|
||||
return Task::batch([close, self.on_enter(route), focus]);
|
||||
}
|
||||
Message::AccountRefreshed(Ok(fresh)) => {
|
||||
if let Session::SignedIn { account, .. } = &mut self.session {
|
||||
@@ -550,6 +557,7 @@ impl App {
|
||||
};
|
||||
return self.update(Message::Player(msg));
|
||||
}
|
||||
Message::Shortcut(shortcut) => return self.shortcut(shortcut),
|
||||
Message::SkipFromMenu => {
|
||||
self.sheet = None;
|
||||
return self.update(Message::Player(player::Msg::Next));
|
||||
@@ -860,6 +868,40 @@ impl App {
|
||||
Task::none()
|
||||
}
|
||||
|
||||
fn shortcut(&mut self, shortcut: Shortcut) -> Task<Message> {
|
||||
use crate::media::Command;
|
||||
let to_player = Message::Player;
|
||||
let msg = match shortcut {
|
||||
Shortcut::TogglePlay => to_player(player::Msg::Toggle),
|
||||
Shortcut::Next => to_player(player::Msg::Next),
|
||||
Shortcut::Previous => to_player(player::Msg::Previous),
|
||||
Shortcut::SeekForward => Message::Media(Command::SeekBy { forward: true, by: shortcuts::SEEK_STEP }),
|
||||
Shortcut::SeekBack => Message::Media(Command::SeekBy { forward: false, by: shortcuts::SEEK_STEP }),
|
||||
Shortcut::VolumeUp => to_player(player::Msg::SetVolume(self.player.volume + shortcuts::VOLUME_STEP)),
|
||||
Shortcut::VolumeDown => to_player(player::Msg::SetVolume(self.player.volume - shortcuts::VOLUME_STEP)),
|
||||
Shortcut::ToggleLike => {
|
||||
let Some(track) = self.player.track().cloned() else { return Task::none() };
|
||||
let liked = self.library.liked.contains(&track.id);
|
||||
Message::LikeTrack(track, !liked)
|
||||
}
|
||||
Shortcut::FocusSearch => return focus_search(),
|
||||
Shortcut::Back if self.nav.can_go_back() => Message::Back,
|
||||
Shortcut::Back => return Task::none(),
|
||||
Shortcut::Dismiss => {
|
||||
if self.sheet.is_some() {
|
||||
self.sheet = None;
|
||||
} else if self.search.suggestions().is_some() {
|
||||
return self.update(Message::Search(search::Msg::CloseSuggestions));
|
||||
} else {
|
||||
self.drawer = None;
|
||||
}
|
||||
return Task::none();
|
||||
}
|
||||
Shortcut::Go(route) => Message::Navigate(route),
|
||||
};
|
||||
self.update(msg)
|
||||
}
|
||||
|
||||
/// Loads what a route shows on first visit, and retries after a failure.
|
||||
fn on_enter(&mut self, route: Route) -> Task<Message> {
|
||||
match route {
|
||||
@@ -1176,6 +1218,12 @@ fn trace(message: &Message) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Puts the cursor in the search field with its text selected, so typing replaces the last query.
|
||||
fn focus_search() -> Task<Message> {
|
||||
use iced::widget::operation;
|
||||
Task::batch([operation::focus(topbar::SEARCH_ID), operation::select_all(topbar::SEARCH_ID)])
|
||||
}
|
||||
|
||||
fn restore() -> Task<Message> {
|
||||
Task::future(session::restore()).map(Message::Restored)
|
||||
}
|
||||
@@ -1249,6 +1297,41 @@ mod tests {
|
||||
assert_eq!(app.player.track().unwrap().id, "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_closes_the_menu_then_the_drawer() {
|
||||
let mut app = signed_in();
|
||||
let _ = app.update(Message::ToggleDrawer(Panel::Queue));
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false }));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert!(app.sheet.is_none());
|
||||
assert_eq!(app.drawer, Some(Panel::Queue));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert_eq!(app.drawer, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcuts_drive_the_player_and_navigation() {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Next));
|
||||
assert_eq!(app.player.track().unwrap().id, "b");
|
||||
|
||||
let _ = app.update(Message::Player(player::Msg::SetVolume(0.03)));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::VolumeDown));
|
||||
assert_eq!(app.player.volume, 0.0);
|
||||
let _ = app.update(Message::Shortcut(Shortcut::VolumeUp));
|
||||
assert!((app.player.volume - shortcuts::VOLUME_STEP).abs() < f32::EPSILON);
|
||||
|
||||
// Back does nothing on the first page, then returns from where ⌘2 went.
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Back));
|
||||
assert_eq!(app.nav.current(), Route::Home);
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Go(Route::Wave)));
|
||||
assert_eq!(app.nav.current(), Route::Wave);
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Back));
|
||||
assert_eq!(app.nav.current(), Route::Home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_next_on_the_playing_track_says_so() {
|
||||
let mut app = signed_in();
|
||||
|
||||
@@ -10,6 +10,16 @@ pub fn get(english: &str) -> Option<&'static str> {
|
||||
"Collection" => "Коллекция",
|
||||
"Podcasts" => "Подкасты",
|
||||
"Settings" => "Настройки",
|
||||
"Keyboard shortcuts" => "Сочетания клавиш",
|
||||
"Play or pause" => "Играть или пауза",
|
||||
"Space" => "Пробел",
|
||||
"Next or previous track" => "Следующий или предыдущий трек",
|
||||
"Skip 10 seconds forward or back" => "Перемотать на 10 секунд вперёд или назад",
|
||||
"Volume up or down" => "Громче или тише",
|
||||
"Like or unlike the track playing" => "«Мне нравится» для играющего трека",
|
||||
"Go back" => "Назад",
|
||||
"Close a menu or panel" => "Закрыть меню или панель",
|
||||
"Home, My Wave, Search, Collection, Podcasts" => "Главная, Моя волна, Поиск, Коллекция, Подкасты",
|
||||
"Album" => "Альбом",
|
||||
"Artist" => "Исполнитель",
|
||||
"Playlist" => "Плейлист",
|
||||
|
||||
@@ -10,6 +10,7 @@ mod player;
|
||||
mod route;
|
||||
mod screens;
|
||||
mod session;
|
||||
mod shortcuts;
|
||||
mod store;
|
||||
#[cfg(feature = "snapshot")]
|
||||
mod snapshot;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Settings: account, streaming quality, appearance, storage.
|
||||
|
||||
use iced::widget::{Row, button, column, container, row};
|
||||
use iced::widget::{Column, Row, button, column, container, row, space};
|
||||
use iced::{Alignment, Element, Fill};
|
||||
use crate::app::Message;
|
||||
use crate::store::{Appearance, Locale, Quality, Settings};
|
||||
@@ -42,6 +42,7 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me
|
||||
.spacing(12)
|
||||
.into(),
|
||||
),
|
||||
section(t, tr("Keyboard shortcuts"), shortcuts(t)),
|
||||
line(trf("Musyx {} · unofficial Yandex Music client", &[&env!("CARGO_PKG_VERSION")]), theme::BODY, size::SMALL, t.muted),
|
||||
]
|
||||
.spacing(28)
|
||||
@@ -64,3 +65,17 @@ fn chip<'a>(t: &'static Tokens, label: &'static str, on: bool, msg: Message) ->
|
||||
.on_press_maybe((!on).then_some(msg))
|
||||
.into()
|
||||
}
|
||||
|
||||
fn shortcuts<'a>(t: &'static Tokens) -> Element<'a, Message> {
|
||||
let rows = crate::shortcuts::help().into_iter().map(|(action, keys)| {
|
||||
let caps = Row::with_children(keys.into_iter().map(|k| {
|
||||
container(line(k, theme::MEDIUM, size::META, t.fg)).padding([2, 8]).style(theme::kbd).into()
|
||||
}))
|
||||
.spacing(6);
|
||||
row![line(action, theme::BODY, size::BODY, t.fg), space::horizontal(), caps]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.into()
|
||||
});
|
||||
Column::with_children(rows).spacing(10).max_width(560).into()
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Keyboard shortcuts. Only keys a focused text field didn't use arrive here, so
|
||||
//! Space typed into search stays a space. Letters and punctuation are read by
|
||||
//! their position as a fallback, so ⌘F still works on a Russian layout.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use iced::Subscription;
|
||||
use iced::keyboard::key::{Code, Named, Physical};
|
||||
use iced::keyboard::{self, Key, Modifiers};
|
||||
|
||||
use crate::i18n::tr;
|
||||
use crate::route::Route;
|
||||
|
||||
/// One step of the volume keys.
|
||||
pub const VOLUME_STEP: f32 = 0.05;
|
||||
/// How far the seek keys jump.
|
||||
pub const SEEK_STEP: Duration = Duration::from_secs(10);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Shortcut {
|
||||
TogglePlay,
|
||||
Next,
|
||||
Previous,
|
||||
SeekForward,
|
||||
SeekBack,
|
||||
VolumeUp,
|
||||
VolumeDown,
|
||||
ToggleLike,
|
||||
FocusSearch,
|
||||
Back,
|
||||
/// Esc: closes the menu, then the search suggestions, then the drawer.
|
||||
Dismiss,
|
||||
Go(Route),
|
||||
}
|
||||
|
||||
pub fn subscription() -> Subscription<Shortcut> {
|
||||
keyboard::listen().filter_map(|event| match event {
|
||||
keyboard::Event::KeyPressed { key, physical_key, modifiers, repeat, .. } => {
|
||||
from_key(&key, physical_key, modifiers, repeat)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn from_key(key: &Key, physical: Physical, mods: Modifiers, repeat: bool) -> Option<Shortcut> {
|
||||
use Shortcut as S;
|
||||
let cmd = mods.command();
|
||||
// Shortcuts that Alt or the other platform's Ctrl would change into something else.
|
||||
let plain = !mods.alt() && !(mods.control() && mods.logo());
|
||||
|
||||
if let Key::Named(named) = key {
|
||||
let shortcut = match (named, cmd, mods.shift(), mods.alt()) {
|
||||
(Named::Space, false, false, false) if !mods.control() && !mods.logo() => S::TogglePlay,
|
||||
(Named::Escape, false, false, false) => S::Dismiss,
|
||||
(Named::ArrowRight, true, false, false) => S::Next,
|
||||
(Named::ArrowLeft, true, false, false) => S::Previous,
|
||||
(Named::ArrowUp, true, false, false) => S::VolumeUp,
|
||||
(Named::ArrowDown, true, false, false) => S::VolumeDown,
|
||||
(Named::ArrowRight, false, true, false) => S::SeekForward,
|
||||
(Named::ArrowLeft, false, true, false) => S::SeekBack,
|
||||
(Named::ArrowLeft, false, false, true) => S::Back,
|
||||
_ => return None,
|
||||
};
|
||||
// Holding a key repeats volume and seek steps; a held Space must not flicker play and pause.
|
||||
let repeats = matches!(shortcut, S::VolumeUp | S::VolumeDown | S::SeekForward | S::SeekBack);
|
||||
return (!repeat || repeats).then_some(shortcut);
|
||||
}
|
||||
|
||||
if repeat || !plain || mods.shift() {
|
||||
return None;
|
||||
}
|
||||
let c = latin(key, physical)?;
|
||||
if !cmd {
|
||||
// "/" by character, or by position where the layout puts something else there.
|
||||
let slash = c == '/' || physical == Physical::Code(Code::Slash);
|
||||
return (slash && !mods.control() && !mods.logo()).then_some(S::FocusSearch);
|
||||
}
|
||||
Some(match c {
|
||||
'f' => S::FocusSearch,
|
||||
'l' => S::ToggleLike,
|
||||
'[' => S::Back,
|
||||
',' => S::Go(Route::Settings),
|
||||
'1'..='5' => S::Go(Route::NAV[c as usize - '1' as usize]),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The character a key stands for on a Latin layout.
|
||||
fn latin(key: &Key, physical: Physical) -> Option<char> {
|
||||
if let Key::Character(s) = key {
|
||||
let mut chars = s.chars();
|
||||
if let (Some(c), None) = (chars.next(), chars.next())
|
||||
&& c.is_ascii()
|
||||
{
|
||||
return Some(c.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
match physical {
|
||||
Physical::Code(Code::Slash) => Some('/'),
|
||||
Physical::Code(Code::BracketLeft) => Some('['),
|
||||
Physical::Code(Code::Comma) => Some(','),
|
||||
_ => key.to_latin(physical),
|
||||
}
|
||||
}
|
||||
|
||||
/// The list Settings shows: what each shortcut does and the keys for it.
|
||||
pub fn help() -> Vec<(&'static str, Vec<String>)> {
|
||||
let (cmd, shift, alt) = if cfg!(target_os = "macos") { ("⌘", "⇧", "⌥") } else { ("Ctrl+", "Shift+", "Alt+") };
|
||||
let with = |m: &str, k: &str| format!("{m}{k}");
|
||||
vec![
|
||||
(tr("Play or pause"), vec![tr("Space").to_owned()]),
|
||||
(tr("Next or previous track"), vec![with(cmd, "→"), with(cmd, "←")]),
|
||||
(tr("Skip 10 seconds forward or back"), vec![with(shift, "→"), with(shift, "←")]),
|
||||
(tr("Volume up or down"), vec![with(cmd, "↑"), with(cmd, "↓")]),
|
||||
(tr("Like or unlike the track playing"), vec![with(cmd, "L")]),
|
||||
(tr("Search"), vec![with(cmd, "F"), "/".to_owned()]),
|
||||
(tr("Go back"), vec![with(cmd, "["), with(alt, "←")]),
|
||||
(tr("Close a menu or panel"), vec!["Esc".to_owned()]),
|
||||
(tr("Home, My Wave, Search, Collection, Podcasts"), vec![format!("{cmd}1 … {cmd}5")]),
|
||||
(tr("Settings"), vec![with(cmd, ",")]),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use iced::keyboard::key::NativeCode;
|
||||
|
||||
fn press(key: Key, code: Code, mods: Modifiers) -> Option<Shortcut> {
|
||||
from_key(&key, Physical::Code(code), mods, false)
|
||||
}
|
||||
|
||||
fn ch(s: &str) -> Key {
|
||||
Key::Character(s.into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_toggles_only_without_modifiers() {
|
||||
assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::empty()), Some(Shortcut::TogglePlay));
|
||||
assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::COMMAND), None);
|
||||
assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::SHIFT), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_space_does_not_repeat_but_volume_does() {
|
||||
let space = from_key(&Key::Named(Named::Space), Physical::Code(Code::Space), Modifiers::empty(), true);
|
||||
assert_eq!(space, None);
|
||||
let up = from_key(&Key::Named(Named::ArrowUp), Physical::Code(Code::ArrowUp), Modifiers::COMMAND, true);
|
||||
assert_eq!(up, Some(Shortcut::VolumeUp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_and_seek_arrows() {
|
||||
let arrow = |n, code, m| press(Key::Named(n), code, m);
|
||||
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::COMMAND), Some(Shortcut::Next));
|
||||
assert_eq!(arrow(Named::ArrowLeft, Code::ArrowLeft, Modifiers::COMMAND), Some(Shortcut::Previous));
|
||||
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::SHIFT), Some(Shortcut::SeekForward));
|
||||
assert_eq!(arrow(Named::ArrowLeft, Code::ArrowLeft, Modifiers::ALT), Some(Shortcut::Back));
|
||||
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::empty()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letters_follow_the_key_position_on_a_russian_layout() {
|
||||
// ⌘ plus the key that types "а" in the Russian layout is ⌘F.
|
||||
assert_eq!(press(ch("а"), Code::KeyF, Modifiers::COMMAND), Some(Shortcut::FocusSearch));
|
||||
assert_eq!(press(ch("д"), Code::KeyL, Modifiers::COMMAND), Some(Shortcut::ToggleLike));
|
||||
assert_eq!(press(ch("х"), Code::BracketLeft, Modifiers::COMMAND), Some(Shortcut::Back));
|
||||
assert_eq!(press(ch("."), Code::Slash, Modifiers::empty()), Some(Shortcut::FocusSearch));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letters_follow_the_character_on_latin_layouts() {
|
||||
// On AZERTY the key in QWERTY's F position still types "f".
|
||||
assert_eq!(press(ch("f"), Code::KeyF, Modifiers::COMMAND), Some(Shortcut::FocusSearch));
|
||||
assert_eq!(press(ch("l"), Code::KeyO, Modifiers::COMMAND), Some(Shortcut::ToggleLike));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_keys_open_the_sidebar_sections() {
|
||||
assert_eq!(press(ch("1"), Code::Digit1, Modifiers::COMMAND), Some(Shortcut::Go(Route::Home)));
|
||||
assert_eq!(press(ch("5"), Code::Digit5, Modifiers::COMMAND), Some(Shortcut::Go(Route::Podcasts)));
|
||||
assert_eq!(press(ch("6"), Code::Digit6, Modifiers::COMMAND), None);
|
||||
assert_eq!(press(ch(","), Code::Comma, Modifiers::COMMAND), Some(Shortcut::Go(Route::Settings)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_letters_and_shifted_combinations_do_nothing() {
|
||||
assert_eq!(press(ch("f"), Code::KeyF, Modifiers::empty()), None);
|
||||
assert_eq!(press(ch("l"), Code::KeyL, Modifiers::COMMAND | Modifiers::SHIFT), None);
|
||||
assert_eq!(press(ch("l"), Code::KeyL, Modifiers::COMMAND | Modifiers::ALT), None);
|
||||
let unknown = from_key(&ch("ж"), Physical::Unidentified(NativeCode::Unidentified), Modifiers::COMMAND, false);
|
||||
assert_eq!(unknown, None);
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,17 @@ pub fn badge(theme: &Theme) -> container::Style {
|
||||
}
|
||||
}
|
||||
|
||||
/// A key cap in the shortcut list.
|
||||
pub fn kbd(theme: &Theme) -> container::Style {
|
||||
let t = tokens(theme);
|
||||
container::Style {
|
||||
background: Some(t.raised.into()),
|
||||
text_color: Some(t.fg),
|
||||
border: Border { radius: radius::SMALL_COVER.into(), ..Border::default() },
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn accent_dot(theme: &Theme) -> container::Style {
|
||||
container::Style {
|
||||
background: Some(tokens(theme).accent.into()),
|
||||
|
||||
Reference in new issue
Block a user