diff --git a/AGENTS.md b/AGENTS.md index 34b5e49..b11237f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -186,6 +186,11 @@ The TUI is keyboard-first and cross-platform. - Use semantic `Action` values rather than checking raw keys inside views. - Add default bindings in `src/config/default_keymap.toml`. - Preserve user overrides and context-specific bindings. +- Tabs are ordered Library, Playlists, Queue, Podcasts, Settings, Logs + (`1`–`6`). `Tab::ALL` defines that order for the tab bar, Tab/Shift+Tab, + and `GoToTab` indices. Changing it, or the meaning of any other + positional action argument, requires a new `KEYMAP_VERSION` and an + in-memory migration of older keymap files; never rewrite the user's file. - Account for narrow terminals, Unicode display width, and empty/loading/error states. - Restore raw mode, alternate screen, bracketed paste, and keyboard diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 06dbf21..48b1cfa 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -257,6 +257,20 @@ The audio engine is similarly isolated. The application owns the logical queue, while `player::Controller` owns rodio playback and receives explicit commands. Prefetching prepares the next source before the current item ends. +### Versioned key bindings + +Key bindings are semantic `Action` values loaded from the bundled defaults and +merged with the user's `keymap.toml`. Some actions carry positional meaning +(`GoToTab(index)` follows the displayed tab order), so changing the tab order +changes what an existing user file means. The keymap file therefore carries a +format `version`. Files from an older format are adapted in memory when they +are loaded and the user is told once per start; Furumi never rewrites a +user's configuration. The current format, version 2, orders tabs as Library, +Playlists, Queue, Podcasts, Settings, Logs; unversioned files use the earlier +order and have their tab indices remapped. A `version` key that TOML attached +to a binding (written after a `[[keymaps]]` header) is rejected, so a versioned +file is never silently mistaken for a legacy one. + ## Scripted visualizations Visualizations are an extension boundary rather than hard-coded rendering diff --git a/CHANGELOG.md b/CHANGELOG.md index 3145a1d..a8beae7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- A Podcasts tab on `4`. It is a placeholder in this build and states that + podcasts are not available yet. +- An optional top-level `version` in `keymap.toml`; the current format is + `version = 2`, and a `podcasts` binding context. + +### Changed + +- Tab order is now `1` Library, `2` Playlists, `3` Queue, `4` Podcasts, + `5` Settings, `6` Logs, for the tab bar, Tab/Shift+Tab, and the default + number keys. +- Keymap files without `version` keep their tab shortcuts: `GoToTab` indices + are remapped in memory (3 → 4 Settings, 4 → 5 Logs, and 5 → 3 Podcasts + from the prototype podcast build) with a non-blocking startup notice. The + file is not rewritten; `version = 2` files are used as written. A `version` + key placed inside a `[[keymaps]]` entry is reported as an error instead of + being ignored. +- The tab bar shortens titles, then shows only numbers (keeping the active + tab's full title) on terminals too narrow for all six tabs. +- A keymap notice no longer hides a "logging disabled" startup warning; both + are shown. +- The help window names the target tab for number-key shortcuts + ("Go to Settings") instead of "Go to tab N". + ## [0.2.8] - 2026-09-02 ### Added diff --git a/README.md b/README.md index 6a2cd17..fcc6902 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,38 @@ The **Additional settings** window also contains the music save directory and visualization controls. Use Up/Down (or j/k) to navigate, Enter to select, and Esc to return to Settings. Long lists scroll with the selection. +### Tabs and key bindings + +The number keys open the tabs in the order they are shown, and Tab / +Shift+Tab cycle through them: + +| Key | Tab | +| --- | --- | +| `1` | Library | +| `2` | Playlists | +| `3` | Queue | +| `4` | Podcasts | +| `5` | Settings | +| `6` | Logs | + +The Podcasts tab is a placeholder in this build; podcast support is not +available yet. On narrow terminals the tab bar shortens titles and then shows +only the numbers, keeping the active tab's full name. Press `?` for the full list of bindings and commands. + +Bindings can be overridden in `keymap.toml` in the platform config directory +(`~/.config/furumi/keymap.toml` on Linux, +`~/Library/Application Support/furumi/keymap.toml` on macOS); the bundled +`src/config/default_keymap.toml` documents the format. Start the file with +`version = 2`, the current format: its `GoToTab` indices are used exactly as +written (`0` Library … `5` Logs). `version` must come before the first +`[[keymaps]]` entry; written after one, TOML would attach it to that entry, so +Furumi rejects such a file with an error instead of guessing. Files without `version` were written for the +older tab order (Settings and Logs on `4`/`5`, Podcasts on `6` in the +prototype podcast build); Furumi adapts their tab shortcuts in memory so they +keep opening the same tabs, shows a short notice at startup, and never +rewrites the file. Add `version = 2` once the indices match the new order to +take them literally and silence the notice. + ### Now playing in tmux While Furumi is running, a second invocation can print a cheap, single-line diff --git a/src/app/action.rs b/src/app/action.rs index ec21964..229c01d 100644 --- a/src/app/action.rs +++ b/src/app/action.rs @@ -170,7 +170,10 @@ impl Action { Action::Quit => "Quit".into(), Action::NextTab => "Next tab".into(), Action::PrevTab => "Previous tab".into(), - Action::GoToTab(i) => format!("Go to tab {}", i + 1), + Action::GoToTab(i) => match crate::app::state::Tab::from_index(*i) { + Some(tab) => format!("Go to {}", tab.title()), + None => format!("Go to tab {}", i + 1), + }, Action::MoveUp => "Move up".into(), Action::MoveDown => "Move down".into(), Action::MoveLeft => "Move left".into(), diff --git a/src/app/mod.rs b/src/app/mod.rs index 9c4517a..8c90611 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -93,6 +93,17 @@ fn now_epoch_seconds() -> i64 { .unwrap_or(0) } +/// Joins two optional startup status messages with `; `, keeping both. +pub(crate) fn join_status_messages( + first: Option, + second: Option, +) -> Option { + match (first, second) { + (Some(left), Some(right)) => Some(format!("{left}; {right}")), + (left, right) => left.or(right), + } +} + fn err_string(err: anyhow::Error) -> String { format!("{err:#}") } @@ -394,11 +405,7 @@ pub async fn run( tracing::info!(path = %db_path.display(), "library opened"); let (settings, settings_warning) = crate::config::settings::load(); - let status_message = match (startup_warning, settings_warning) { - (Some(left), Some(right)) => Some(format!("{left}; {right}")), - (Some(message), None) | (None, Some(message)) => Some(message), - (None, None) => None, - }; + let status_message = join_status_messages(startup_warning, settings_warning); let mut state = AppState { status_message, ..AppState::default() @@ -4491,3 +4498,29 @@ fn push_media_metadata(state: &AppState, runtime: &Runtime) { }); } } + +#[cfg(test)] +mod status_message_tests { + use super::join_status_messages; + + #[test] + fn startup_messages_are_joined_not_dropped() { + assert_eq!( + join_status_messages( + Some("keymap notice".into()), + Some("logging disabled: x".into()) + ) + .as_deref(), + Some("keymap notice; logging disabled: x") + ); + assert_eq!( + join_status_messages(None, Some("only".into())).as_deref(), + Some("only") + ); + assert_eq!( + join_status_messages(Some("only".into()), None).as_deref(), + Some("only") + ); + assert_eq!(join_status_messages(None, None), None); + } +} diff --git a/src/app/state.rs b/src/app/state.rs index 811d46e..a787484 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -1467,15 +1467,20 @@ pub enum Tab { Global, Playlists, Queue, + Podcasts, Federation, Logs, } impl Tab { - pub const ALL: [Tab; 5] = [ + /// Display, Tab/Shift+Tab and `GoToTab` index order (`1`..`6`). Changing + /// it changes what `GoToTab(n)` means in users' keymap files: bump + /// `config::keymap::KEYMAP_VERSION` and remap older files in memory. + pub const ALL: [Tab; 6] = [ Tab::Global, Tab::Playlists, Tab::Queue, + Tab::Podcasts, Tab::Federation, Tab::Logs, ]; @@ -1485,11 +1490,24 @@ impl Tab { Tab::Global => "Library", Tab::Playlists => "Playlists", Tab::Queue => "Queue", + Tab::Podcasts => "Podcasts", Tab::Federation => "Settings", Tab::Logs => "Logs", } } + /// Abbreviated title for the tab bar on narrow terminals. + pub fn short_title(self) -> &'static str { + match self { + Tab::Global => "Lib", + Tab::Playlists => "Lists", + Tab::Queue => "Queue", + Tab::Podcasts => "Pods", + Tab::Federation => "Set", + Tab::Logs => "Logs", + } + } + pub fn index(self) -> usize { Self::ALL.iter().position(|t| *t == self).unwrap() } @@ -1511,6 +1529,7 @@ impl Tab { Tab::Global => KeyContext::Library, Tab::Playlists => KeyContext::Playlists, Tab::Queue => KeyContext::Queue, + Tab::Podcasts => KeyContext::Podcasts, Tab::Federation => KeyContext::Federation, Tab::Logs => KeyContext::Logs, } diff --git a/src/app/update.rs b/src/app/update.rs index 2fab271..2d091c9 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -1016,7 +1016,7 @@ fn current_track_list_context(state: &AppState) -> Option<(TrackSelectionScope, state.queue_tab.cursor, state.player.queue.len(), )), - Tab::Federation | Tab::Logs => None, + Tab::Podcasts | Tab::Federation | Tab::Logs => None, } } @@ -1070,7 +1070,7 @@ fn current_track_list(state: &AppState) -> Option<(TrackSelectionScope, usize, V state.queue_tab.cursor, state.player.queue.clone(), )), - Tab::Federation | Tab::Logs => None, + Tab::Podcasts | Tab::Federation | Tab::Logs => None, } } @@ -1371,7 +1371,7 @@ pub fn selected_track(state: &AppState) -> Option { .map(|track| (*track).clone()) } Tab::Queue => state.player.queue.get(state.queue_tab.cursor).cloned(), - Tab::Federation | Tab::Logs => None, + Tab::Podcasts | Tab::Federation | Tab::Logs => None, } } @@ -3250,7 +3250,7 @@ fn reset_tab(state: &mut AppState, tab: Tab) { state.logs.follow = true; state.logs.selected_seq = None; } - Tab::Queue => {} + Tab::Queue | Tab::Podcasts => {} } } diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index 8f57a03..b4efc57 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -186,6 +186,97 @@ fn tab_cycling_wraps() { assert_eq!(state.active_tab, Tab::Global); } +#[test] +fn tabs_follow_the_documented_order() { + use crate::config::keymap::KeyContext; + + assert_eq!( + Tab::ALL, + [ + Tab::Global, + Tab::Playlists, + Tab::Queue, + Tab::Podcasts, + Tab::Federation, + Tab::Logs, + ] + ); + let titles: Vec<_> = Tab::ALL.iter().map(|tab| tab.title()).collect(); + assert_eq!( + titles, + [ + "Library", + "Playlists", + "Queue", + "Podcasts", + "Settings", + "Logs" + ] + ); + for (index, tab) in Tab::ALL.iter().enumerate() { + assert_eq!(tab.index(), index); + assert_eq!(Tab::from_index(index), Some(*tab)); + } + assert_eq!(Tab::from_index(Tab::ALL.len()), None); + assert_eq!(Tab::Podcasts.key_context(), KeyContext::Podcasts); + assert_eq!(Tab::Federation.key_context(), KeyContext::Federation); +} + +#[test] +fn next_and_prev_tab_visit_every_tab_in_order() { + let mut state = AppState::default(); + for expected in Tab::ALL.iter().cycle().skip(1).take(Tab::ALL.len()) { + update(&mut state, Action::NextTab); + assert_eq!(state.active_tab, *expected); + } + assert_eq!(state.active_tab, Tab::Global); + for expected in Tab::ALL.iter().rev() { + update(&mut state, Action::PrevTab); + assert_eq!(state.active_tab, *expected); + } + assert_eq!(state.active_tab, Tab::Global); +} + +#[test] +fn go_to_tab_uses_the_new_numbering() { + let mut state = AppState::default(); + for (index, tab) in [ + (3, Tab::Podcasts), + (4, Tab::Federation), + (5, Tab::Logs), + (2, Tab::Queue), + ] { + update(&mut state, Action::GoToTab(index)); + assert_eq!(state.active_tab, tab); + } + // Out-of-range indices are ignored. + update(&mut state, Action::GoToTab(6)); + assert_eq!(state.active_tab, Tab::Queue); + // Re-selecting the placeholder tab is a harmless reset. + update(&mut state, Action::GoToTab(3)); + update(&mut state, Action::GoToTab(3)); + assert_eq!(state.active_tab, Tab::Podcasts); +} + +#[test] +fn help_names_tabs_for_go_to_tab() { + let labels: Vec<_> = (0..Tab::ALL.len()) + .map(|index| Action::GoToTab(index).describe()) + .collect(); + assert_eq!( + labels, + [ + "Go to Library", + "Go to Playlists", + "Go to Queue", + "Go to Podcasts", + "Go to Settings", + "Go to Logs", + ] + ); + assert_eq!(Action::GoToTab(6).describe(), "Go to tab 7"); +} + #[test] fn volume_clamps() { let mut state = AppState::default(); diff --git a/src/config/default_keymap.toml b/src/config/default_keymap.toml index 06d62dd..ace50f5 100644 --- a/src/config/default_keymap.toml +++ b/src/config/default_keymap.toml @@ -1,15 +1,27 @@ # Default keybindings for furumi. # -# To customize, copy entries into /furumi/keymap.toml -# (~/.config/furumi/keymap.toml on Linux/macOS). A user binding replaces the -# default binding with the same key sequence and context. +# To customize, copy entries into keymap.toml in the platform config dir +# (~/.config/furumi/keymap.toml on Linux, +# ~/Library/Application Support/furumi/keymap.toml on macOS). A user binding +# replaces the default binding with the same key sequence and context. +# +# version: keymap format version; put `version = 2` at the top of your file, +# before the first [[keymaps]] entry (after one, TOML attaches it to that +# entry and the file is rejected). Version 2 numbers tabs in this order: +# GoToTab = 0 Library, 1 Playlists, 2 Queue, 3 Podcasts, 4 Settings, 5 Logs. +# A file without `version` is treated as the older layout and its GoToTab +# indices are adapted in memory (3 -> 4 Settings, 4 -> 5 Logs, and 5 -> 3 +# Podcasts from the prototype podcast build); the file itself is never +# rewritten. With `version = 2` indices are used exactly as written. # # key_sequence: space-separated chords, e.g. "g g" or "ctrl-a x". # Modifiers: ctrl-, alt-, shift-, cmd-. Uppercase letters: "shift-g". # command: an Action name, optionally with parameters: # command = { SeekForward = { seconds = 30 } } # context: optional view filter — global (default), library, search, -# playlists, queue, logs. +# playlists, queue, podcasts, settings, logs. + +version = 2 [[keymaps]] key_sequence = "q" @@ -51,6 +63,10 @@ command = { GoToTab = 3 } key_sequence = "5" command = { GoToTab = 4 } +[[keymaps]] +key_sequence = "6" +command = { GoToTab = 5 } + [[keymaps]] key_sequence = "y" command = "DownloadSelected" diff --git a/src/config/keymap.rs b/src/config/keymap.rs index 444b1e2..b126271 100644 --- a/src/config/keymap.rs +++ b/src/config/keymap.rs @@ -9,6 +9,14 @@ use crate::app::action::Action; const DEFAULT_KEYMAP: &str = include_str!("default_keymap.toml"); +/// Current keymap file format, declared as a top-level `version = 2`. +/// +/// Version 2 introduced the tab order Library, Playlists, Queue, Podcasts, +/// Settings, Logs. Files without a version (or with `version = 1`) were +/// written for the older order and have their `GoToTab` indices remapped in +/// memory; the user's file itself is never rewritten. +pub const KEYMAP_VERSION: u32 = 2; + /// Input context a binding applies to. `Global` bindings work everywhere; /// view-specific bindings shadow global ones for the same key sequence. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] @@ -20,6 +28,7 @@ pub enum KeyContext { Search, Playlists, Queue, + Podcasts, #[serde(rename = "settings", alias = "federation")] Federation, Logs, @@ -33,6 +42,7 @@ impl KeyContext { KeyContext::Search => "search", KeyContext::Playlists => "playlists", KeyContext::Queue => "queue", + KeyContext::Podcasts => "podcasts", KeyContext::Federation => "settings", KeyContext::Logs => "logs", } @@ -52,10 +62,18 @@ struct RawBinding { command: Action, #[serde(default)] context: KeyContext, + /// Never valid here: a `version = N` line written after a `[[keymaps]]` + /// header lands inside that entry. Caught so the file is not silently + /// treated as legacy (and its tab indices remapped) despite the version. + #[serde(default)] + version: Option, } #[derive(Debug, Default, Deserialize)] struct KeymapFile { + /// Format version; `None` means a legacy (pre-version-2) file. + #[serde(default)] + version: Option, #[serde(default)] keymaps: Vec, } @@ -87,9 +105,15 @@ impl Keymap { { match fs::read_to_string(&path) .map_err(anyhow::Error::from) - .and_then(|text| parse_bindings(&text)) + .and_then(|text| parse_user_keymap(&text)) { - Ok(user) => merge(&mut bindings, user), + Ok(user) => { + if let Some(notice) = user.notice { + tracing::info!(path = %path.display(), "{notice}"); + warning = Some(format!("{}: {notice}", path.display())); + } + merge(&mut bindings, user.bindings); + } Err(err) => { warning = Some(format!( "{} ignored: {err:#}; using default keybindings", @@ -106,6 +130,16 @@ impl Keymap { (keymap, warning) } + /// The embedded defaults only, without reading the user's file. + #[cfg(test)] + pub(crate) fn defaults() -> Self { + Self { + bindings: parse_bindings(DEFAULT_KEYMAP).expect("embedded default keymap must parse"), + pending: Vec::new(), + format: KeyCombinationFormat::default(), + } + } + /// Feed one key combination; returns an action, a pending-chord state, or /// nothing. Esc clears a pending chord instead of resolving. pub fn resolve(&mut self, key: KeyCombination, context: KeyContext) -> KeyResolution { @@ -275,10 +309,76 @@ pub fn user_keymap_path() -> Option { } fn parse_bindings(text: &str) -> Result> { + parse_file(text).map(|(_, bindings)| bindings) +} + +/// A user keymap after version handling, plus a one-time, non-blocking +/// notice for the status bar and log when its meaning was adapted. +struct UserKeymap { + bindings: Vec, + notice: Option, +} + +fn parse_user_keymap(text: &str) -> Result { + let (version, mut bindings) = parse_file(text)?; + let notice = match version { + None | Some(1) => { + let remapped = remap_legacy_tab_indices(&mut bindings); + (remapped > 0).then(|| { + format!( + "{remapped} tab shortcut(s) adapted to the new tab order \ + (4 Podcasts, 5 Settings, 6 Logs); \ + add `version = {KEYMAP_VERSION}` to use indices as written" + ) + }) + } + Some(KEYMAP_VERSION) => None, + Some(0) => bail!("unsupported keymap version 0"), + Some(newer) => Some(format!( + "keymap version {newer} is newer than this build supports \ + ({KEYMAP_VERSION}); bindings are used as written" + )), + }; + Ok(UserKeymap { bindings, notice }) +} + +/// Pre-version-2 `GoToTab` index → current index. Index 5 only existed in the +/// prototype podcast build, where it opened Podcasts. +fn legacy_tab_index(index: usize) -> usize { + match index { + 3 => 4, // Settings + 4 => 5, // Logs + 5 => 3, // Podcasts (prototype) + other => other, + } +} + +/// Rewrites legacy `GoToTab` indices in memory; returns how many changed. +fn remap_legacy_tab_indices(bindings: &mut [Binding]) -> usize { + let mut remapped = 0; + for binding in bindings { + if let Action::GoToTab(index) = &mut binding.action { + let current = legacy_tab_index(*index); + if current != *index { + *index = current; + remapped += 1; + } + } + } + remapped +} + +fn parse_file(text: &str) -> Result<(Option, Vec)> { let file: KeymapFile = toml::from_str(text).context("invalid TOML")?; - file.keymaps + let bindings = file + .keymaps .into_iter() .map(|raw| { + if raw.version.is_some() { + bail!( + "`version` must be a top-level key placed before the first [[keymaps]] entry" + ); + } let keys = parse_sequence(&raw.key_sequence) .with_context(|| format!("bad key_sequence {:?}", raw.key_sequence))?; Ok(Binding { @@ -287,7 +387,8 @@ fn parse_bindings(text: &str) -> Result> { context: raw.context, }) }) - .collect() + .collect::>()?; + Ok((file.version, bindings)) } fn parse_sequence(s: &str) -> Result> { @@ -597,6 +698,198 @@ mod tests { ); } + #[test] + fn default_keymap_declares_current_version() { + let (version, _) = parse_file(DEFAULT_KEYMAP).unwrap(); + assert_eq!(version, Some(KEYMAP_VERSION)); + assert!(parse_user_keymap(DEFAULT_KEYMAP).unwrap().notice.is_none()); + } + + #[test] + fn default_digit_keys_follow_tab_order() { + let mut km = keymap_from(DEFAULT_KEYMAP); + for (index, key) in ['1', '2', '3', '4', '5', '6'].into_iter().enumerate() { + let combo = KeyCombination::new(KeyCode::Char(key), KeyModifiers::NONE); + assert_eq!( + km.resolve(combo, KeyContext::Library), + KeyResolution::Action(Action::GoToTab(index)) + ); + } + } + + fn go_to_tab_indices(bindings: &[Binding]) -> Vec { + bindings + .iter() + .filter_map(|b| match b.action { + Action::GoToTab(index) => Some(index), + _ => None, + }) + .collect() + } + + const LEGACY_TABS: &str = r#" + [[keymaps]] + key_sequence = "1" + command = { GoToTab = 0 } + + [[keymaps]] + key_sequence = "f2" + command = { GoToTab = 2 } + + [[keymaps]] + key_sequence = "f4" + command = { GoToTab = 3 } + + [[keymaps]] + key_sequence = "f5" + command = { GoToTab = 4 } + + [[keymaps]] + key_sequence = "f6" + command = { GoToTab = 5 } + context = "logs" + + [[keymaps]] + key_sequence = "x" + command = "ToggleHelp" + "#; + + #[test] + fn legacy_keymap_tab_indices_are_remapped_in_memory() { + let user = parse_user_keymap(LEGACY_TABS).unwrap(); + // Settings 3 -> 4, Logs 4 -> 5, prototype Podcasts 5 -> 3. + assert_eq!(go_to_tab_indices(&user.bindings), [0, 2, 4, 5, 3]); + assert_eq!(user.bindings[4].context, KeyContext::Logs); + assert_eq!(user.bindings[5].action, Action::ToggleHelp); + let notice = user.notice.expect("remap must be reported"); + assert!(notice.starts_with("3 tab shortcut(s)"), "{notice}"); + assert!(notice.contains("version = 2"), "{notice}"); + } + + #[test] + fn explicit_version_one_is_treated_as_legacy() { + let user = parse_user_keymap(&format!("version = 1\n{LEGACY_TABS}")).unwrap(); + assert_eq!(go_to_tab_indices(&user.bindings), [0, 2, 4, 5, 3]); + assert!(user.notice.is_some()); + } + + #[test] + fn legacy_keymap_without_changed_tab_indices_has_no_notice() { + let user = parse_user_keymap( + r#" + [[keymaps]] + key_sequence = "1" + command = { GoToTab = 0 } + + [[keymaps]] + key_sequence = "q" + command = "Back" + "#, + ) + .unwrap(); + assert_eq!(go_to_tab_indices(&user.bindings), [0]); + assert!(user.notice.is_none()); + } + + #[test] + fn versioned_keymap_is_taken_literally() { + let user = parse_user_keymap(&format!("version = 2\n{LEGACY_TABS}")).unwrap(); + assert_eq!(go_to_tab_indices(&user.bindings), [0, 2, 3, 4, 5]); + assert!(user.notice.is_none()); + } + + #[test] + fn newer_keymap_version_is_used_as_written_with_a_notice() { + let user = parse_user_keymap(&format!("version = 3\n{LEGACY_TABS}")).unwrap(); + assert_eq!(go_to_tab_indices(&user.bindings), [0, 2, 3, 4, 5]); + assert!(user.notice.unwrap().contains("newer")); + } + + #[test] + fn version_inside_a_keymaps_entry_is_rejected() { + // Appended at the end, TOML puts `version` into the last entry; the + // file must not silently fall back to the legacy remap. + let err = parse_user_keymap( + "[[keymaps]]\nkey_sequence = \"4\"\ncommand = { GoToTab = 3 }\nversion = 2\n", + ) + .err() + .expect("misplaced version must be rejected"); + assert!( + format!("{err:#}").contains("before the first [[keymaps]]"), + "{err:#}" + ); + } + + #[test] + fn unknown_keys_in_keymaps_entries_are_still_ignored() { + let user = parse_user_keymap( + "version = 2\n[[keymaps]]\nkey_sequence = \"4\"\ncommand = { GoToTab = 3 }\nnote = \"mine\"\n", + ) + .unwrap(); + assert_eq!(go_to_tab_indices(&user.bindings), [3]); + } + + #[test] + fn keymap_version_zero_is_rejected() { + assert!(parse_user_keymap("version = 0").is_err()); + } + + #[test] + fn legacy_user_digit_override_keeps_its_old_target() { + let mut bindings = parse_bindings(DEFAULT_KEYMAP).unwrap(); + // An old file that swapped "4" and "5" (Settings / Logs). + let user = parse_user_keymap( + r#" + [[keymaps]] + key_sequence = "4" + command = { GoToTab = 4 } + + [[keymaps]] + key_sequence = "5" + command = { GoToTab = 3 } + "#, + ) + .unwrap(); + merge(&mut bindings, user.bindings); + let mut km = Keymap { + bindings, + pending: Vec::new(), + format: KeyCombinationFormat::default(), + }; + let four = KeyCombination::new(KeyCode::Char('4'), KeyModifiers::NONE); + let five = KeyCombination::new(KeyCode::Char('5'), KeyModifiers::NONE); + let six = KeyCombination::new(KeyCode::Char('6'), KeyModifiers::NONE); + // Still Logs and Settings, now at their new indices. + assert_eq!( + km.resolve(four, KeyContext::Library), + KeyResolution::Action(Action::GoToTab(5)) + ); + assert_eq!( + km.resolve(five, KeyContext::Library), + KeyResolution::Action(Action::GoToTab(4)) + ); + // The new default "6" is untouched by the user's file. + assert_eq!( + km.resolve(six, KeyContext::Library), + KeyResolution::Action(Action::GoToTab(5)) + ); + } + + #[test] + fn podcasts_context_parses() { + let bindings = parse_bindings( + r#" + [[keymaps]] + key_sequence = "z" + command = "ToggleHelp" + context = "podcasts" + "#, + ) + .unwrap(); + assert_eq!(bindings[0].context, KeyContext::Podcasts); + assert_eq!(KeyContext::Podcasts.label(), "podcasts"); + } + #[test] fn default_listening_history_key_resolves() { let mut km = keymap_from(DEFAULT_KEYMAP); diff --git a/src/main.rs b/src/main.rs index a540345..c906a76 100644 --- a/src/main.rs +++ b/src/main.rs @@ -65,7 +65,9 @@ fn main() -> Result<()> { // after local guards have been dropped and the terminal has been restored. let _stderr_capture = capture_stderr(); let (keymap, keymap_warning) = config::keymap::Keymap::load(); - let startup_warning = keymap_warning.or(startup_warning); + // The keymap message may be an informational notice; keep both so a + // logging failure is not hidden behind it. + let startup_warning = app::join_status_messages(keymap_warning, startup_warning); // The app (tokio + TUI) runs on a worker thread; the main thread stays // dedicated to the OS media-key event loop — on macOS the system only diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 5d5cac3..1b199fa 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -4,6 +4,7 @@ mod federation; pub(crate) mod global; mod logs; mod playlists; +mod podcasts; mod popup; #[cfg(test)] mod status_tests; @@ -50,6 +51,126 @@ mod tests { assert_eq!(label, "●"); assert_eq!(style, client_style); } + + fn render(state: &AppState, width: u16, height: u16) -> String { + let keymap = Keymap::defaults(); + let mut terminal = + ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height)).unwrap(); + terminal.draw(|frame| draw(frame, state, &keymap)).unwrap(); + let buffer = terminal.backend().buffer(); + (0..height) + .map(|y| { + (0..width) + .map(|x| buffer[(x, y)].symbol()) + .collect::() + }) + .collect::>() + .join("\n") + } + + #[test] + fn tab_bar_numbers_tabs_in_the_new_order() { + let screen = render(&AppState::default(), 120, 10); + let bar = screen.lines().next().unwrap(); + let positions: Vec = [ + "1 Library", + "2 Playlists", + "3 Queue", + "4 Podcasts", + "5 Settings", + "6 Logs", + ] + .iter() + .map(|title| { + bar.find(title) + .unwrap_or_else(|| panic!("{title} in {bar:?}")) + }) + .collect(); + assert!(positions.is_sorted(), "{bar:?}"); + } + + /// Each tab's number appears once, in order, and the active tab's label + /// is fully on screen. + fn assert_tab_bar_fits(width: u16, active: Tab, active_label: &str) { + let mut state = AppState::default(); + state.active_tab = active; + let screen = render(&state, width, 10); + let bar = screen.lines().next().unwrap(); + let digits: String = bar.chars().filter(char::is_ascii_digit).collect(); + assert_eq!(digits, "123456", "width {width}: {bar:?}"); + assert!( + bar.contains(active_label), + "width {width}: {active_label} missing in {bar:?}" + ); + } + + #[test] + fn tab_bar_keeps_every_tab_visible_on_narrow_terminals() { + for width in [80, 77, 76, 70, 65, 60, 48, 40, 30] { + assert_tab_bar_fits(width, Tab::Logs, "6 Logs"); + assert_tab_bar_fits(width, Tab::Global, "1 Lib"); + } + // Full titles while they fit. + assert_tab_bar_fits(80, Tab::Global, "5 Settings"); + assert_tab_bar_fits(65, Tab::Global, "5 Settings"); + // Numbers only, but the active tab keeps its full title. + assert_tab_bar_fits(30, Tab::Federation, "5 Settings"); + assert_tab_bar_fits(30, Tab::Playlists, "2 Playlists"); + } + + #[test] + fn tab_bar_highlights_active_tab_when_compact() { + let mut state = AppState::default(); + state.active_tab = Tab::Logs; + let keymap = Keymap::defaults(); + let mut terminal = + ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 10)).unwrap(); + terminal.draw(|frame| draw(frame, &state, &keymap)).unwrap(); + let buffer = terminal.backend().buffer(); + let bar: String = (0..60).map(|x| buffer[(x, 0)].symbol()).collect(); + let x = bar.find("6 Logs").expect("active tab on screen") as u16; + let highlight = theme::tab_active_for(&state); + let cell = buffer[(x, 0)].style(); + assert_eq!((cell.fg, cell.bg), (highlight.fg, highlight.bg)); + } + + #[test] + fn podcasts_tab_shows_placeholder() { + let mut state = AppState::default(); + state.active_tab = Tab::Podcasts; + let screen = render(&state, 100, 12); + assert!(screen.contains(podcasts::UNAVAILABLE), "{screen}"); + } + + #[test] + fn podcasts_placeholder_wraps_without_losing_text_on_narrow_terminals() { + let mut state = AppState::default(); + state.active_tab = Tab::Podcasts; + for width in [60, 40] { + let screen = render(&state, width, 14); + let words: Vec<&str> = screen + .split(|c: char| c.is_whitespace() || c == '│') + .filter(|word| !word.is_empty()) + .collect(); + for word in ["available", "progress", "appear", "here."] { + assert!( + words.contains(&word), + "{word} missing at {width}:\n{screen}" + ); + } + } + } + + #[test] + fn help_lists_tab_names_for_digit_shortcuts() { + let mut state = AppState::default(); + state.help_visible = true; + let screen = render(&state, 160, 80); + for title in ["Go to Podcasts", "Go to Settings", "Go to Logs"] { + assert!(screen.contains(title), "{title} missing:\n{screen}"); + } + assert!(!screen.contains("Go to tab"), "{screen}"); + } } pub fn draw(frame: &mut Frame, state: &AppState, keymap: &Keymap) { @@ -73,6 +194,7 @@ pub fn draw(frame: &mut Frame, state: &AppState, keymap: &Keymap) { Tab::Global => global::draw(frame, main_area, state), Tab::Playlists => playlists::draw(frame, main_area, state), Tab::Queue => draw_queue(frame, main_area, state), + Tab::Podcasts => podcasts::draw(frame, main_area, state), Tab::Federation => federation::draw(frame, main_area, state), Tab::Logs => logs::draw(frame, main_area, state), } @@ -140,15 +262,48 @@ fn is_waiting_message(message: &str) -> bool { } fn draw_tabs(frame: &mut Frame, area: Rect, state: &AppState) { - let titles = Tab::ALL - .iter() - .map(|tab| format!(" {} {} ", tab.index() + 1, tab.title())); - let tabs = Tabs::new(titles) - .select(state.active_tab.index()) - .style(theme::dim()) - .highlight_style(theme::tab_active_for(state)) - .divider(""); - frame.render_widget(tabs, area); + frame.render_widget(tab_bar(state, area.width), area); +} + +/// The widest tab bar that fits `width`. Narrow terminals drop the outer +/// padding, then abbreviate titles, then show only numbers (keeping the +/// active tab's full title), so all six shortcuts and the highlight stay +/// visible instead of the last tabs being cut off. +fn tab_bar(state: &AppState, width: u16) -> Tabs<'static> { + use unicode_width::UnicodeWidthStr as _; + + let active = state.active_tab; + let build = |label: &dyn Fn(Tab) -> String, padded: bool| { + let tabs = Tabs::new(Tab::ALL.iter().map(|&tab| label(tab))) + .select(active.index()) + .style(theme::dim()) + .highlight_style(theme::tab_active_for(state)) + .divider(""); + if padded { tabs } else { tabs.padding("", "") } + }; + let full = |tab: Tab| format!(" {} {} ", tab.index() + 1, tab.title()); + let short = |tab: Tab| format!(" {} {} ", tab.index() + 1, tab.short_title()); + let numbers_with_active = |tab: Tab| { + if tab == active { + full(tab) + } else { + format!(" {} ", tab.index() + 1) + } + }; + let numbers = |tab: Tab| format!(" {} ", tab.index() + 1); + let candidates: [(&dyn Fn(Tab) -> String, bool); 4] = [ + (&full, true), + (&full, false), + (&short, false), + (&numbers_with_active, false), + ]; + for (label, padded) in candidates { + let tabs = build(label, padded); + if tabs.width() <= usize::from(width) { + return tabs; + } + } + build(&numbers, false) } /// One track row used by every track list: ♥ marker for liked tracks, the diff --git a/src/ui/podcasts.rs b/src/ui/podcasts.rs new file mode 100644 index 0000000..3891593 --- /dev/null +++ b/src/ui/podcasts.rs @@ -0,0 +1,58 @@ +use ratatui::Frame; +use ratatui::layout::{Alignment, Rect}; +use ratatui::text::Line; +use ratatui::widgets::{Block, Paragraph, Wrap}; + +use super::theme; +use crate::app::state::AppState; + +/// Placeholder notice shown until podcast support lands: the tab already +/// holds its final position so the numeric shortcuts stay stable. +pub(crate) const UNAVAILABLE: &str = "Podcasts are not available in this build yet."; + +pub fn draw(frame: &mut Frame, area: Rect, state: &AppState) { + let block = Block::bordered() + .title(" Podcasts ") + .title_style(theme::header_for(state)) + .border_style(theme::border_for(state)); + let inner = block.inner(area); + frame.render_widget(block, area); + if inner.height == 0 { + return; + } + + let lines = vec![ + Line::styled(UNAVAILABLE, theme::header_for(state)), + Line::default(), + Line::styled( + "Subscriptions, episodes and listening progress will appear here.", + theme::dim(), + ), + ]; + // Center on the estimated wrapped height, but let the paragraph use every + // row down to the bottom so narrow terminals never cut off the text. + let wrapped = estimated_rows(&lines, inner.width).min(inner.height); + let top = inner.height.saturating_sub(wrapped) / 2; + let body = Rect { + y: inner.y + top, + height: inner.height - top, + ..inner + }; + frame.render_widget( + Paragraph::new(lines) + .alignment(Alignment::Center) + .wrap(Wrap { trim: true }), + body, + ); +} + +/// Rows the lines need when wrapped to `width` (a lower bound: word wrapping +/// may need one more row per line, which the paragraph area leaves room for). +fn estimated_rows(lines: &[Line], width: u16) -> u16 { + let width = usize::from(width.max(1)); + let rows: usize = lines + .iter() + .map(|line| line.width().div_ceil(width).max(1)) + .sum(); + u16::try_from(rows).unwrap_or(u16::MAX) +}