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/state.rs b/src/app/state.rs index 811d46e..df4ffbf 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,6 +1490,7 @@ impl Tab { Tab::Global => "Library", Tab::Playlists => "Playlists", Tab::Queue => "Queue", + Tab::Podcasts => "Podcasts", Tab::Federation => "Settings", Tab::Logs => "Logs", } @@ -1511,6 +1517,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..ed25168 100644 --- a/src/config/default_keymap.toml +++ b/src/config/default_keymap.toml @@ -4,12 +4,22 @@ # (~/.config/furumi/keymap.toml on Linux/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. 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 +61,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..9bf057b 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", } @@ -56,6 +66,9 @@ struct RawBinding { #[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 +100,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 +125,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,8 +304,69 @@ 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| { let keys = parse_sequence(&raw.key_sequence) @@ -287,7 +377,8 @@ fn parse_bindings(text: &str) -> Result> { context: raw.context, }) }) - .collect() + .collect::>()?; + Ok((file.version, bindings)) } fn parse_sequence(s: &str) -> Result> { @@ -597,6 +688,174 @@ 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 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/ui/mod.rs b/src/ui/mod.rs index 5d5cac3..fb747b0 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,62 @@ 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:?}"); + } + + #[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 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 +130,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), } diff --git a/src/ui/podcasts.rs b/src/ui/podcasts.rs new file mode 100644 index 0000000..e44e28d --- /dev/null +++ b/src/ui/podcasts.rs @@ -0,0 +1,44 @@ +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(), + ), + ]; + let height = (lines.len() as u16).min(inner.height); + let body = Rect { + y: inner.y + inner.height.saturating_sub(height) / 2, + height, + ..inner + }; + frame.render_widget( + Paragraph::new(lines) + .alignment(Alignment::Center) + .wrap(Wrap { trim: true }), + body, + ); +}