forked from Furumi/furumi-tui
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
595c886303 | ||
|
|
78bf2cf583 | ||
|
|
df7ad3c8b7 | ||
|
|
df171208eb | ||
|
|
e78f1627da | ||
|
|
292f17fee1 | ||
|
|
3e46f21804 | ||
|
|
7f0ca2984f |
No files matched your search
@@ -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
|
||||
|
||||
@@ -123,6 +123,14 @@ The DHT is the distributed index. Nodes publish compact searchable
|
||||
descriptions of their local library and query the network without contacting a
|
||||
central search service.
|
||||
|
||||
Opening a local artist or release card in a network-enabled library view
|
||||
enriches it asynchronously. DHT matches identify likely catalog owners, while
|
||||
a bounded set of known peers can also answer directly when the index is
|
||||
incomplete. Card results are replaceable snapshots: reopening a card or
|
||||
periodic maintenance retries discovery, with at most one request per card in
|
||||
flight. A failed refresh keeps the last usable snapshot, and never prevents
|
||||
browsing the local tracks.
|
||||
|
||||
Similarity discovery uses a separate schema-independent DHT overlay. A node
|
||||
derives a deterministic 256-bit routing signature from every local embedding,
|
||||
groups them into fixed two-level LSH buckets, and publishes compact summaries
|
||||
@@ -249,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
|
||||
|
||||
@@ -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
|
||||
|
||||
Generated
+1
-1
@@ -1715,7 +1715,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "furumi_tui"
|
||||
version = "0.3.4"
|
||||
version = "0.3.5"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "furumi_tui"
|
||||
version = "0.3.4"
|
||||
version = "0.3.5"
|
||||
edition = "2024"
|
||||
rust-version = "1.97"
|
||||
description = "A federated P2P player for personal music libraries"
|
||||
|
||||
@@ -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
|
||||
|
||||
+4
-1
@@ -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(),
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Scheduling for local cards enriched by replaceable federation data.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::state::{AppState, GlobalView, Loadable, Tab};
|
||||
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub(super) enum Card {
|
||||
Artist(i64),
|
||||
Release(i64),
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct RefreshState {
|
||||
visible: Option<Card>,
|
||||
/// None means a request is in flight; Some is its completion time.
|
||||
requests: HashMap<Card, Option<Instant>>,
|
||||
}
|
||||
|
||||
impl RefreshState {
|
||||
pub(super) fn is_loading(&self, card: Card) -> bool {
|
||||
matches!(self.requests.get(&card), Some(None))
|
||||
}
|
||||
|
||||
fn begin(&mut self, visible: Option<Card>, now: Instant) -> bool {
|
||||
let reopened = self.visible != visible;
|
||||
self.visible = visible;
|
||||
let Some(card) = visible else { return false };
|
||||
match self.requests.get(&card) {
|
||||
Some(None) => return false,
|
||||
Some(Some(completed))
|
||||
if !reopened && now.duration_since(*completed) < REFRESH_INTERVAL =>
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.requests.insert(card, None);
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn complete(&mut self, card: Card, now: Instant) {
|
||||
self.requests.insert(card, Some(now));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) enum Request {
|
||||
Artist {
|
||||
id: i64,
|
||||
name: String,
|
||||
},
|
||||
Release {
|
||||
id: i64,
|
||||
title: String,
|
||||
artists: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Called on navigation and maintenance ticks. A cached success or failure
|
||||
/// must not suppress discovery for the rest of the session.
|
||||
pub(super) fn prepare(state: &mut AppState, now: Instant) -> Option<Request> {
|
||||
let visible = if state.federation.settings.enabled
|
||||
&& state.global.filters.source_mode.includes_network()
|
||||
&& state.active_tab == Tab::Global
|
||||
{
|
||||
match state.global.stack.last() {
|
||||
Some(GlobalView::Artist { id, .. }) => Some(Card::Artist(*id)),
|
||||
Some(GlobalView::Release { id, .. }) => Some(Card::Release(*id)),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let request = match visible {
|
||||
Some(Card::Artist(id)) => match state.artist_views.get(&id) {
|
||||
Some(Loadable::Ready(detail)) => Some(Request::Artist {
|
||||
id,
|
||||
name: detail.name.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
},
|
||||
Some(Card::Release(id)) => match state.release_views.get(&id) {
|
||||
Some(Loadable::Ready(detail)) => {
|
||||
let mut artists = Vec::new();
|
||||
for artist in &detail.artists {
|
||||
if !artists.iter().any(|name: &String| {
|
||||
music_dht::normalize_name(name) == music_dht::normalize_name(&artist.name)
|
||||
}) {
|
||||
artists.push(artist.name.clone());
|
||||
}
|
||||
}
|
||||
(!artists.is_empty()).then(|| Request::Release {
|
||||
id,
|
||||
title: detail.title.clone(),
|
||||
artists,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
if !state
|
||||
.card_enrichment
|
||||
.begin(visible.filter(|_| request.is_some()), now)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
match &request {
|
||||
Some(Request::Artist { id, .. }) => mark_loading(&mut state.artist_fed_views, *id),
|
||||
Some(Request::Release { id, .. }) => mark_loading(&mut state.release_fed_views, *id),
|
||||
None => {}
|
||||
}
|
||||
request
|
||||
}
|
||||
|
||||
fn mark_loading<T>(views: &mut HashMap<i64, Loadable<T>>, id: i64) {
|
||||
if !matches!(views.get(&id), Some(Loadable::Ready(_))) {
|
||||
views.insert(id, Loadable::Loading);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the last usable snapshot if a refresh fails while peers are offline.
|
||||
pub(super) fn store_result<T>(
|
||||
views: &mut HashMap<i64, Loadable<T>>,
|
||||
id: i64,
|
||||
result: Result<T, String>,
|
||||
) {
|
||||
match result {
|
||||
Ok(value) => {
|
||||
views.insert(id, Loadable::Ready(value));
|
||||
}
|
||||
Err(message) if !matches!(views.get(&id), Some(Loadable::Ready(_))) => {
|
||||
views.insert(id, Loadable::Failed(message));
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
+68
-72
@@ -1,6 +1,7 @@
|
||||
pub mod action;
|
||||
mod cmdline;
|
||||
pub mod command;
|
||||
mod enrichment;
|
||||
pub mod event;
|
||||
pub mod input;
|
||||
pub(crate) mod popup;
|
||||
@@ -92,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<String>,
|
||||
second: Option<String>,
|
||||
) -> Option<String> {
|
||||
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:#}")
|
||||
}
|
||||
@@ -310,54 +322,16 @@ fn spawn_release_federation_enrichment(
|
||||
});
|
||||
}
|
||||
|
||||
fn maybe_enrich_open_artist(state: &mut AppState, runtime: &Runtime) {
|
||||
if !state.federation.settings.enabled || state.active_tab != state::Tab::Global {
|
||||
return;
|
||||
}
|
||||
let Some(state::GlobalView::Artist { id, .. }) = state.global.stack.last().copied() else {
|
||||
return;
|
||||
};
|
||||
if state.artist_fed_views.contains_key(&id) {
|
||||
return;
|
||||
}
|
||||
let Some(state::Loadable::Ready(detail)) = state.artist_views.get(&id) else {
|
||||
return;
|
||||
};
|
||||
let name = detail.name.clone();
|
||||
state.artist_fed_views.insert(id, state::Loadable::Loading);
|
||||
spawn_artist_federation_enrichment(runtime, id, name);
|
||||
}
|
||||
|
||||
fn maybe_enrich_open_release(state: &mut AppState, runtime: &Runtime) {
|
||||
if !state.federation.settings.enabled
|
||||
|| !state.global.filters.source_mode.includes_network()
|
||||
|| state.active_tab != state::Tab::Global
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(state::GlobalView::Release { id, .. }) = state.global.stack.last().copied() else {
|
||||
return;
|
||||
};
|
||||
if state.release_fed_views.contains_key(&id) {
|
||||
return;
|
||||
}
|
||||
let Some(state::Loadable::Ready(detail)) = state.release_views.get(&id) else {
|
||||
return;
|
||||
};
|
||||
let mut artists = Vec::new();
|
||||
for artist in &detail.artists {
|
||||
if !artists.iter().any(|name: &String| {
|
||||
music_dht::normalize_name(name) == music_dht::normalize_name(&artist.name)
|
||||
}) {
|
||||
artists.push(artist.name.clone());
|
||||
fn maybe_enrich_open_card(state: &mut AppState, runtime: &Runtime) {
|
||||
match enrichment::prepare(state, std::time::Instant::now()) {
|
||||
Some(enrichment::Request::Artist { id, name }) => {
|
||||
spawn_artist_federation_enrichment(runtime, id, name);
|
||||
}
|
||||
Some(enrichment::Request::Release { id, title, artists }) => {
|
||||
spawn_release_federation_enrichment(runtime, id, title, artists);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if artists.is_empty() {
|
||||
return;
|
||||
}
|
||||
let title = detail.title.clone();
|
||||
state.release_fed_views.insert(id, state::Loadable::Loading);
|
||||
spawn_release_federation_enrichment(runtime, id, title, artists);
|
||||
}
|
||||
|
||||
fn spawn_content_id_backfill(runtime: &Runtime) {
|
||||
@@ -431,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()
|
||||
@@ -1195,8 +1165,7 @@ fn maintenance(state: &mut AppState, runtime: &mut Runtime) {
|
||||
|
||||
maybe_refresh_network_library(state, runtime);
|
||||
maybe_fetch_network_artist_images(state, runtime);
|
||||
maybe_enrich_open_artist(state, runtime);
|
||||
maybe_enrich_open_release(state, runtime);
|
||||
maybe_enrich_open_card(state, runtime);
|
||||
|
||||
// Liked ids load once per session — markers are shown everywhere.
|
||||
if !state.likes_loaded {
|
||||
@@ -3804,26 +3773,27 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
}
|
||||
AppEvent::ArtistFederationLoaded { id, name, result } => {
|
||||
let cursor_anchor = state::artist_cursor_anchor(state, id);
|
||||
let entry = match result {
|
||||
Ok(card) => state::Loadable::Ready(card),
|
||||
Err(message) => {
|
||||
tracing::debug!(artist = id, %name, %message, "artist federation enrichment failed");
|
||||
state::Loadable::Failed(message)
|
||||
}
|
||||
};
|
||||
state.artist_fed_views.insert(id, entry);
|
||||
state
|
||||
.card_enrichment
|
||||
.complete(enrichment::Card::Artist(id), std::time::Instant::now());
|
||||
if let Err(message) = &result {
|
||||
tracing::debug!(artist = id, %name, %message, "artist federation enrichment failed");
|
||||
}
|
||||
enrichment::store_result(&mut state.artist_fed_views, id, result);
|
||||
state::restore_artist_cursor_anchor(state, id, cursor_anchor);
|
||||
}
|
||||
AppEvent::ReleaseFederationLoaded { id, result } => {
|
||||
let entry = match result {
|
||||
Ok(Some(release)) => state::Loadable::Ready(release),
|
||||
Ok(None) => state::Loadable::Ready(crate::federation::FedRelease::default()),
|
||||
Err(message) => {
|
||||
tracing::debug!(release = id, %message, "release federation enrichment failed");
|
||||
state::Loadable::Failed(message)
|
||||
}
|
||||
};
|
||||
state.release_fed_views.insert(id, entry);
|
||||
state
|
||||
.card_enrichment
|
||||
.complete(enrichment::Card::Release(id), std::time::Instant::now());
|
||||
if let Err(message) = &result {
|
||||
tracing::debug!(release = id, %message, "release federation enrichment failed");
|
||||
}
|
||||
enrichment::store_result(
|
||||
&mut state.release_fed_views,
|
||||
id,
|
||||
result.map(Option::unwrap_or_default),
|
||||
);
|
||||
}
|
||||
AppEvent::NetworkArtistCacheUpdated { source_id, count } => {
|
||||
tracing::debug!(source = %source_id, count, "network artist cache updated");
|
||||
@@ -3937,7 +3907,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
}
|
||||
};
|
||||
state.artist_views.insert(id, entry);
|
||||
maybe_enrich_open_artist(state, runtime);
|
||||
maybe_enrich_open_card(state, runtime);
|
||||
}
|
||||
AppEvent::ReleaseViewLoaded { id, result } => {
|
||||
let entry = match result {
|
||||
@@ -3948,7 +3918,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
}
|
||||
};
|
||||
state.release_views.insert(id, entry);
|
||||
maybe_enrich_open_release(state, runtime);
|
||||
maybe_enrich_open_card(state, runtime);
|
||||
// A Shift-J jump was waiting for this release: focus its track.
|
||||
if let Some((release_id, track_id)) = state.pending_release_focus
|
||||
&& release_id == id
|
||||
@@ -4528,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);
|
||||
}
|
||||
}
|
||||
+33
-1
@@ -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,
|
||||
}
|
||||
@@ -1680,6 +1699,7 @@ pub struct AppState {
|
||||
pub release_views: HashMap<i64, Loadable<ReleaseDetail>>,
|
||||
/// Federated tracks that enrich an already-open local release view.
|
||||
pub release_fed_views: HashMap<i64, Loadable<crate::federation::FedRelease>>,
|
||||
pub(super) card_enrichment: super::enrichment::RefreshState,
|
||||
pub playlists: PlaylistsTab,
|
||||
pub playlist_views: HashMap<i64, Loadable<PlaylistDetail>>,
|
||||
/// Liked local-library content ids, for the ♥ markers everywhere tracks are shown.
|
||||
@@ -1717,6 +1737,18 @@ pub struct AppState {
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn artist_federation_loading(&self, id: i64) -> bool {
|
||||
self.card_enrichment
|
||||
.is_loading(super::enrichment::Card::Artist(id))
|
||||
|| matches!(self.artist_fed_views.get(&id), Some(Loadable::Loading))
|
||||
}
|
||||
|
||||
pub fn release_federation_loading(&self, id: i64) -> bool {
|
||||
self.card_enrichment
|
||||
.is_loading(super::enrichment::Card::Release(id))
|
||||
|| matches!(self.release_fed_views.get(&id), Some(Loadable::Loading))
|
||||
}
|
||||
|
||||
pub fn advance_spinner(&mut self) {
|
||||
self.spinner_frame = self.spinner_frame.wrapping_add(1);
|
||||
}
|
||||
|
||||
+4
-4
@@ -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<TrackItem> {
|
||||
.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 => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
@@ -1073,3 +1164,276 @@ fn view_toggle() {
|
||||
update(&mut state, Action::ToggleViewMode);
|
||||
assert_eq!(state.global.view, ViewMode::Tiles);
|
||||
}
|
||||
|
||||
fn enrichment_state(release: bool) -> AppState {
|
||||
use crate::library::models::{ArtistRef, ReleaseDetail};
|
||||
let mut state = AppState::default();
|
||||
state.federation.settings.enabled = true;
|
||||
state.global.filters.source_mode = crate::config::settings::LibrarySourceMode::Global;
|
||||
state.artist_views.insert(
|
||||
1,
|
||||
Loadable::Ready(ArtistDetail {
|
||||
id: 1,
|
||||
name: "Artist".into(),
|
||||
image_path: None,
|
||||
total_track_count: 1,
|
||||
total_play_count: 0,
|
||||
top_tracks: vec![test_track(1)],
|
||||
featured_tracks: vec![],
|
||||
releases: vec![],
|
||||
}),
|
||||
);
|
||||
state.release_views.insert(
|
||||
1,
|
||||
Loadable::Ready(ReleaseDetail {
|
||||
id: 1,
|
||||
title: "Release".into(),
|
||||
release_type: "album".into(),
|
||||
year: None,
|
||||
cover_path: None,
|
||||
artists: vec![ArtistRef {
|
||||
id: 1,
|
||||
name: "Artist".into(),
|
||||
}],
|
||||
tracks: vec![test_track(1)],
|
||||
}),
|
||||
);
|
||||
state.global.stack.push(if release {
|
||||
GlobalView::Release { id: 1, cursor: 0 }
|
||||
} else {
|
||||
GlobalView::Artist { id: 1, cursor: 0 }
|
||||
});
|
||||
state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn card_enrichment_retries_startup_failure_without_reopening() {
|
||||
use crate::app::enrichment::{self, Card, Request};
|
||||
use std::time::{Duration, Instant};
|
||||
for release in [false, true] {
|
||||
let mut state = enrichment_state(release);
|
||||
let now = Instant::now();
|
||||
let request = enrichment::prepare(&mut state, now).unwrap();
|
||||
let card = match request {
|
||||
Request::Artist { id: 1, ref name } if name == "Artist" => Card::Artist(1),
|
||||
Request::Release {
|
||||
id: 1,
|
||||
ref title,
|
||||
ref artists,
|
||||
} if title == "Release" && artists == &["Artist"] => Card::Release(1),
|
||||
_ => panic!("wrong enrichment request: {request:?}"),
|
||||
};
|
||||
// Slow requests are never duplicated, even after the refresh interval.
|
||||
assert!(enrichment::prepare(&mut state, now + Duration::from_secs(60)).is_none());
|
||||
let completed = now + Duration::from_secs(60);
|
||||
state.card_enrichment.complete(card, completed);
|
||||
if release {
|
||||
enrichment::store_result(
|
||||
&mut state.release_fed_views,
|
||||
1,
|
||||
Err("federation is not running".into()),
|
||||
);
|
||||
} else {
|
||||
enrichment::store_result(
|
||||
&mut state.artist_fed_views,
|
||||
1,
|
||||
Err("federation is not running".into()),
|
||||
);
|
||||
}
|
||||
assert!(enrichment::prepare(&mut state, completed + Duration::from_secs(1)).is_none());
|
||||
assert_eq!(
|
||||
enrichment::prepare(&mut state, completed + Duration::from_secs(30)),
|
||||
Some(request)
|
||||
);
|
||||
assert!(matches!(
|
||||
state.artist_views.get(&1),
|
||||
Some(Loadable::Ready(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
state.release_views.get(&1),
|
||||
Some(Loadable::Ready(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn card_enrichment_reopens_cached_cards_and_keeps_success_during_failed_refresh() {
|
||||
use crate::app::enrichment::{self, Card};
|
||||
use std::time::{Duration, Instant};
|
||||
for release in [false, true] {
|
||||
let mut state = enrichment_state(release);
|
||||
let now = Instant::now();
|
||||
let request = enrichment::prepare(&mut state, now).unwrap();
|
||||
state.card_enrichment.complete(
|
||||
if release {
|
||||
Card::Release(1)
|
||||
} else {
|
||||
Card::Artist(1)
|
||||
},
|
||||
now,
|
||||
);
|
||||
if release {
|
||||
enrichment::store_result(
|
||||
&mut state.release_fed_views,
|
||||
1,
|
||||
Ok(crate::federation::FedRelease {
|
||||
title: "Release".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
enrichment::store_result(
|
||||
&mut state.artist_fed_views,
|
||||
1,
|
||||
Ok(crate::federation::FedArtistCard {
|
||||
name: "Artist".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Successful but local-only/empty snapshots must also be refreshed.
|
||||
assert!(enrichment::prepare(&mut state, now).is_none());
|
||||
let view = state.global.stack.pop().unwrap();
|
||||
assert!(enrichment::prepare(&mut state, now).is_none());
|
||||
state.global.stack.push(view);
|
||||
assert_eq!(
|
||||
enrichment::prepare(&mut state, now + Duration::from_secs(1)),
|
||||
Some(request)
|
||||
);
|
||||
if release {
|
||||
assert!(matches!(
|
||||
state.release_fed_views.get(&1),
|
||||
Some(Loadable::Ready(_))
|
||||
));
|
||||
enrichment::store_result(&mut state.release_fed_views, 1, Err("offline".into()));
|
||||
assert!(
|
||||
matches!(state.release_fed_views.get(&1), Some(Loadable::Ready(card)) if card.title == "Release")
|
||||
);
|
||||
} else {
|
||||
assert!(matches!(
|
||||
state.artist_fed_views.get(&1),
|
||||
Some(Loadable::Ready(_))
|
||||
));
|
||||
enrichment::store_result(&mut state.artist_fed_views, 1, Err("offline".into()));
|
||||
assert!(
|
||||
matches!(state.artist_fed_views.get(&1), Some(Loadable::Ready(card)) if card.name == "Artist")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn card_enrichment_respects_network_mode_and_deduplicates_navigation() {
|
||||
use crate::app::enrichment;
|
||||
use crate::config::settings::LibrarySourceMode;
|
||||
use std::time::Instant;
|
||||
for release in [false, true] {
|
||||
let mut state = enrichment_state(release);
|
||||
let now = Instant::now();
|
||||
state.federation.settings.enabled = false;
|
||||
assert!(enrichment::prepare(&mut state, now).is_none());
|
||||
state.federation.settings.enabled = true;
|
||||
state.global.filters.source_mode = LibrarySourceMode::Local;
|
||||
assert!(enrichment::prepare(&mut state, now).is_none());
|
||||
state.global.filters.source_mode = LibrarySourceMode::Global;
|
||||
assert!(enrichment::prepare(&mut state, now).is_some());
|
||||
state.active_tab = Tab::Queue;
|
||||
assert!(enrichment::prepare(&mut state, now).is_none());
|
||||
state.active_tab = Tab::Global;
|
||||
assert!(enrichment::prepare(&mut state, now).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn card_enrichment_refreshes_local_only_success_while_still_open() {
|
||||
use crate::app::enrichment::{self, Card};
|
||||
use std::time::{Duration, Instant};
|
||||
for release in [false, true] {
|
||||
let mut state = enrichment_state(release);
|
||||
let now = Instant::now();
|
||||
let request = enrichment::prepare(&mut state, now).unwrap();
|
||||
state.card_enrichment.complete(
|
||||
if release {
|
||||
Card::Release(1)
|
||||
} else {
|
||||
Card::Artist(1)
|
||||
},
|
||||
now,
|
||||
);
|
||||
if release {
|
||||
enrichment::store_result(&mut state.release_fed_views, 1, Ok(Default::default()));
|
||||
} else {
|
||||
enrichment::store_result(&mut state.artist_fed_views, 1, Ok(Default::default()));
|
||||
}
|
||||
assert!(enrichment::prepare(&mut state, now + Duration::from_secs(29)).is_none());
|
||||
assert_eq!(
|
||||
enrichment::prepare(&mut state, now + Duration::from_secs(30)),
|
||||
Some(request)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn render_enrichment_card(state: &AppState) -> String {
|
||||
use ratatui::{Terminal, backend::TestBackend};
|
||||
let mut terminal = Terminal::new(TestBackend::new(160, 40)).unwrap();
|
||||
terminal
|
||||
.draw(|frame| crate::ui::global::draw(frame, frame.area(), state))
|
||||
.unwrap();
|
||||
terminal
|
||||
.backend()
|
||||
.buffer()
|
||||
.content
|
||||
.iter()
|
||||
.map(|cell| cell.symbol())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_card_explains_source_filter_instead_of_waiting_for_a_request() {
|
||||
use crate::app::enrichment;
|
||||
let mut state = enrichment_state(false);
|
||||
state.global.filters.source_mode = crate::config::settings::LibrarySourceMode::Local;
|
||||
assert!(enrichment::prepare(&mut state, std::time::Instant::now()).is_none());
|
||||
let text = render_enrichment_card(&state);
|
||||
assert!(
|
||||
!text.contains("federation: pending"),
|
||||
"Local mode must not promise a request that is disabled"
|
||||
);
|
||||
assert!(
|
||||
text.contains("Local"),
|
||||
"the card must explain why network results are hidden"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn card_refresh_animates_while_previous_results_stay_visible() {
|
||||
use crate::app::enrichment::{self, Card};
|
||||
use std::time::{Duration, Instant};
|
||||
for release in [false, true] {
|
||||
let mut state = enrichment_state(release);
|
||||
let now = Instant::now();
|
||||
assert!(enrichment::prepare(&mut state, now).is_some());
|
||||
let card = if release {
|
||||
Card::Release(1)
|
||||
} else {
|
||||
Card::Artist(1)
|
||||
};
|
||||
state.card_enrichment.complete(card, now);
|
||||
if release {
|
||||
enrichment::store_result(&mut state.release_fed_views, 1, Ok(Default::default()));
|
||||
} else {
|
||||
enrichment::store_result(&mut state.artist_fed_views, 1, Ok(Default::default()));
|
||||
}
|
||||
assert!(enrichment::prepare(&mut state, now + Duration::from_secs(30)).is_some());
|
||||
let first = render_enrichment_card(&state);
|
||||
assert!(first.contains(&format!("{} searching peers", state.spinner())));
|
||||
state.advance_spinner();
|
||||
let next = render_enrichment_card(&state);
|
||||
assert!(next.contains(&format!("{} searching peers", state.spinner())));
|
||||
assert_ne!(first, next);
|
||||
state
|
||||
.card_enrichment
|
||||
.complete(card, now + Duration::from_secs(31));
|
||||
assert!(!render_enrichment_card(&state).contains("searching peers"));
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,27 @@
|
||||
# Default keybindings for furumi.
|
||||
#
|
||||
# To customize, copy entries into <config dir>/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"
|
||||
|
||||
+297
-4
@@ -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<toml::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
struct KeymapFile {
|
||||
/// Format version; `None` means a legacy (pre-version-2) file.
|
||||
#[serde(default)]
|
||||
version: Option<u32>,
|
||||
#[serde(default)]
|
||||
keymaps: Vec<RawBinding>,
|
||||
}
|
||||
@@ -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<PathBuf> {
|
||||
}
|
||||
|
||||
fn parse_bindings(text: &str) -> Result<Vec<Binding>> {
|
||||
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<Binding>,
|
||||
notice: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_user_keymap(text: &str) -> Result<UserKeymap> {
|
||||
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<u32>, Vec<Binding>)> {
|
||||
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<Vec<Binding>> {
|
||||
context: raw.context,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
.collect::<Result<_>>()?;
|
||||
Ok((file.version, bindings))
|
||||
}
|
||||
|
||||
fn parse_sequence(s: &str) -> Result<Vec<KeyCombination>> {
|
||||
@@ -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<usize> {
|
||||
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);
|
||||
|
||||
+57
-22
@@ -1486,31 +1486,38 @@ impl Federation {
|
||||
let own = service.endpoint_id();
|
||||
let own_hex = own.to_string();
|
||||
let normalized = music_dht::normalize_name(name);
|
||||
let outcome = service
|
||||
.search_network(name)
|
||||
.await
|
||||
.map_err(|err| anyhow::anyhow!("federated search failed: {err}"))?;
|
||||
// A partial/unavailable DHT index must not prevent direct catalog
|
||||
// requests to peers we already know. Keep discovery bounded so an
|
||||
// open card cannot remain in Loading indefinitely.
|
||||
let network_results = match tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
service.search_network(name),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(outcome)) => outcome.network_results,
|
||||
Ok(Err(error)) => {
|
||||
tracing::debug!(artist = %name, %error, "artist discovery failed; trying known peers");
|
||||
Vec::new()
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::debug!(artist = %name, "artist discovery timed out; trying known peers");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let cached_metadata = self.cached_metadata_snapshot();
|
||||
let has_cached_artist = cached_metadata
|
||||
.iter()
|
||||
.any(|cached| cached_has_artist(cached, &normalized));
|
||||
let owners: std::collections::HashSet<EndpointId> = outcome
|
||||
.network_results
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
(item.kind == ItemKind::Artist && item.normalized_name == normalized)
|
||||
|| item
|
||||
.artist_names
|
||||
.iter()
|
||||
.any(|artist| music_dht::normalize_name(artist) == normalized)
|
||||
|| item
|
||||
.featured_artist_names
|
||||
.iter()
|
||||
.any(|artist| music_dht::normalize_name(artist) == normalized)
|
||||
})
|
||||
.map(|item| item.owner)
|
||||
.filter(|owner| *owner != own)
|
||||
.collect();
|
||||
let owners = artist_catalog_owners(
|
||||
&network_results,
|
||||
&normalized,
|
||||
own,
|
||||
service
|
||||
.connected_peers()
|
||||
.into_iter()
|
||||
.chain(service.known_peers().into_iter().map(|peer| peer.peer_id)),
|
||||
);
|
||||
|
||||
let local_library = Arc::clone(&self.library);
|
||||
let local_name = name.to_string();
|
||||
@@ -1565,7 +1572,7 @@ impl Federation {
|
||||
}
|
||||
}
|
||||
let mut card = catalog::merge_catalogs(name, catalogs);
|
||||
add_dht_appearance_hits(&mut card, &outcome.network_results, &normalized, name);
|
||||
add_dht_appearance_hits(&mut card, &network_results, &normalized, name);
|
||||
add_cached_appearance_hits(&mut card, &cached_metadata, &normalized, name);
|
||||
anyhow::ensure!(
|
||||
!card.releases.is_empty() || !card.appears_on.is_empty(),
|
||||
@@ -2406,6 +2413,34 @@ fn cached_has_artist(cached: &CachedTrackMetadata, normalized_artist: &str) -> b
|
||||
.any(|artist| music_dht::normalize_name(artist) == normalized_artist)
|
||||
}
|
||||
|
||||
/// Prefer advertised owners, then ask a bounded set of known peers directly.
|
||||
/// Catalog lookup is useful even before those peers' DHT records arrive.
|
||||
fn artist_catalog_owners(
|
||||
items: &[LibraryItem],
|
||||
normalized: &str,
|
||||
own: EndpointId,
|
||||
known: impl IntoIterator<Item = EndpointId>,
|
||||
) -> Vec<EndpointId> {
|
||||
const MAX_CATALOG_PEERS: usize = 32;
|
||||
let advertised = items
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
(item.kind == ItemKind::Artist && item.normalized_name == normalized)
|
||||
|| item
|
||||
.artist_names
|
||||
.iter()
|
||||
.chain(&item.featured_artist_names)
|
||||
.any(|artist| music_dht::normalize_name(artist) == normalized)
|
||||
})
|
||||
.map(|item| item.owner);
|
||||
let mut seen = std::collections::HashSet::from([own]);
|
||||
advertised
|
||||
.chain(known)
|
||||
.filter(|owner| seen.insert(*owner))
|
||||
.take(MAX_CATALOG_PEERS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rank_fed_search_results(
|
||||
artists: &mut [FedArtistHit],
|
||||
tracks: &mut [FedTrack],
|
||||
|
||||
@@ -93,3 +93,45 @@ fn federation_search_ranks_exact_names_first() {
|
||||
assert_eq!(artists[0].name, "Ежемесячные");
|
||||
assert_eq!(tracks[0].title, "Ежемесячные");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artist_catalog_discovery_uses_known_peers_without_dht_hits() {
|
||||
let own = music_dht::SecretKey::from_bytes(&[8; 32]).public();
|
||||
let peer = test_owner();
|
||||
assert_eq!(
|
||||
artist_catalog_owners(&[], "artist", own, [own, peer, peer]),
|
||||
vec![peer]
|
||||
);
|
||||
// Unrelated records must not send the card request to their owners.
|
||||
assert!(artist_catalog_owners(&[dht_track(&["Other"], &[])], "artist", own, []).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artist_catalog_discovery_prioritizes_matching_owners_and_bounds_fanout() {
|
||||
let own = music_dht::SecretKey::from_bytes(&[8; 32]).public();
|
||||
let peer = test_owner();
|
||||
let known: Vec<_> = (10..60)
|
||||
.map(|seed| music_dht::SecretKey::from_bytes(&[seed; 32]).public())
|
||||
.collect();
|
||||
for item in [
|
||||
dht_track(&["Artist"], &[]),
|
||||
dht_track(&["Host"], &["Artist"]),
|
||||
] {
|
||||
let owners = artist_catalog_owners(
|
||||
&[item],
|
||||
"artist",
|
||||
own,
|
||||
known.iter().copied().chain([own, peer]),
|
||||
);
|
||||
assert_eq!(owners.len(), 32);
|
||||
assert_eq!(owners[0], peer);
|
||||
assert!(!owners.contains(&own));
|
||||
assert_eq!(
|
||||
owners
|
||||
.iter()
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
.len(),
|
||||
owners.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -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
|
||||
|
||||
@@ -537,6 +537,17 @@ fn draw_artist(frame: &mut Frame, area: Rect, state: &AppState, id: i64, cursor:
|
||||
about.push_str(&format!(" · appears on {}", detail.featured_tracks.len()));
|
||||
}
|
||||
let federation_line = match state.artist_fed_views.get(&id) {
|
||||
_ if state.federation.settings.enabled
|
||||
&& !state.global.filters.source_mode.includes_network() =>
|
||||
{
|
||||
Some(Line::styled(
|
||||
"federation: hidden by Local filter",
|
||||
theme::dim(),
|
||||
))
|
||||
}
|
||||
_ if state.artist_federation_loading(id) => {
|
||||
Some(super::loading_line(state, "searching peers…"))
|
||||
}
|
||||
Some(Loadable::Loading) => Some(super::loading_line(state, "searching peers…")),
|
||||
Some(Loadable::Ready(card)) => {
|
||||
let tracks: usize = card
|
||||
@@ -839,6 +850,17 @@ fn draw_release(frame: &mut Frame, area: Rect, state: &AppState, id: i64, cursor
|
||||
let year = detail.year.map(|y| format!(" · {y}")).unwrap_or_default();
|
||||
let tracks = crate::app::state::release_tracks(state, id, detail);
|
||||
let federation_line = match state.release_fed_views.get(&id) {
|
||||
_ if state.federation.settings.enabled
|
||||
&& !state.global.filters.source_mode.includes_network() =>
|
||||
{
|
||||
Some(Line::styled(
|
||||
"federation: hidden by Local filter",
|
||||
theme::dim(),
|
||||
))
|
||||
}
|
||||
_ if state.release_federation_loading(id) => {
|
||||
Some(super::loading_line(state, "searching peers…"))
|
||||
}
|
||||
Some(Loadable::Loading) => Some(super::loading_line(state, "searching peers…")),
|
||||
Some(Loadable::Ready(release)) if !release.tracks.is_empty() => Some(Line::styled(
|
||||
format!("federation: +{} tracks", release.tracks.len()),
|
||||
|
||||
+204
-24
@@ -1,9 +1,10 @@
|
||||
mod additional_settings;
|
||||
pub mod art;
|
||||
mod federation;
|
||||
mod global;
|
||||
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::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.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<usize> = [
|
||||
"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
|
||||
@@ -400,10 +555,12 @@ fn player_right_line(state: &AppState, width: u16) -> (Line<'static>, u16) {
|
||||
format!(" {} ", state.device_playback.role.label()),
|
||||
theme::role_pill(state.device_playback.role),
|
||||
));
|
||||
spans.push(Span::styled(
|
||||
format!(" · online {}", state.device_playback.online_devices.max(1)),
|
||||
theme::dim(),
|
||||
));
|
||||
if width >= 160 {
|
||||
spans.push(Span::styled(
|
||||
format!(" · online {}", state.device_playback.online_devices.max(1)),
|
||||
theme::dim(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// Keep a gap between the flags and the username block to the right.
|
||||
spans.push(Span::raw(" "));
|
||||
@@ -413,14 +570,34 @@ fn player_right_line(state: &AppState, width: u16) -> (Line<'static>, u16) {
|
||||
)
|
||||
}
|
||||
|
||||
/// Reserve the source-mode badge first so playback details cannot clip it.
|
||||
fn player_row_areas(row: Rect, state: &AppState) -> [Rect; 3] {
|
||||
let badge_width = (format!(" federation: {} ", state.global.filters.source_mode.label()).len()
|
||||
as u16)
|
||||
.min(row.width);
|
||||
let content = Rect::new(
|
||||
row.x,
|
||||
row.y,
|
||||
row.width.saturating_sub(badge_width),
|
||||
row.height,
|
||||
);
|
||||
let badge = Rect::new(content.right(), row.y, badge_width, row.height);
|
||||
let (line, _) = player_right_line(state, content.width);
|
||||
let right_width = line.width().min(usize::from(content.width)) as u16;
|
||||
let [title, right] = Layout::horizontal([
|
||||
Constraint::Min(8.min(content.width)),
|
||||
Constraint::Length(right_width),
|
||||
])
|
||||
.areas(content);
|
||||
[title, right, badge]
|
||||
}
|
||||
|
||||
/// Shared geometry for rendering and background visualization requests.
|
||||
fn footer_areas(area: Rect, state: &AppState) -> [Rect; 3] {
|
||||
let [player_row, message_row] =
|
||||
Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(area);
|
||||
let (line, volume_offset) = player_right_line(state, area.width);
|
||||
let right_width = line.width().min(usize::from(area.width)) as u16;
|
||||
let [_, right] =
|
||||
Layout::horizontal([Constraint::Min(8), Constraint::Length(right_width)]).areas(player_row);
|
||||
let [_, right, badge] = player_row_areas(player_row, state);
|
||||
let (_, volume_offset) = player_right_line(state, area.width.saturating_sub(badge.width));
|
||||
let version_width = (env!("CARGO_PKG_VERSION").len() as u16 + 1).min(message_row.width);
|
||||
let version = Rect::new(
|
||||
message_row.x + message_row.width.saturating_sub(version_width) / 2,
|
||||
@@ -469,11 +646,8 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
|
||||
// Layout: track title left, time/progress/flags on the right. The
|
||||
// right block is built first and gets a fixed width; the title
|
||||
// truncates into whatever is left.
|
||||
let (center, _) = player_right_line(state, area.width);
|
||||
let center_width = (center.width() as u16).min(area.width);
|
||||
let [title_area, right_area] =
|
||||
Layout::horizontal([Constraint::Min(8), Constraint::Length(center_width)])
|
||||
.areas(player_row);
|
||||
let [title_area, right_area, mode_area] = player_row_areas(player_row, state);
|
||||
let (center, _) = player_right_line(state, area.width.saturating_sub(mode_area.width));
|
||||
|
||||
let mut spans = Vec::new();
|
||||
match &player.current {
|
||||
@@ -498,6 +672,12 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
|
||||
}
|
||||
frame.render_widget(Paragraph::new(Line::from(spans)), title_area);
|
||||
frame.render_widget(Paragraph::new(center), right_area);
|
||||
let mode = state.global.filters.source_mode;
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!(" federation: {} ", mode.label()))
|
||||
.style(theme::source_mode_pill(mode)),
|
||||
mode_area,
|
||||
);
|
||||
draw_version(frame, version_area);
|
||||
if crate::visualizer::status::visible(state) {
|
||||
state.status_visualizer.draw(frame, visual_area);
|
||||
@@ -550,7 +730,7 @@ fn active_artist_peer_search(state: &AppState) -> Option<String> {
|
||||
let Some(GlobalView::Artist { id, .. }) = state.global.stack.last() else {
|
||||
return None;
|
||||
};
|
||||
if !matches!(state.artist_fed_views.get(id), Some(Loadable::Loading)) {
|
||||
if !state.artist_federation_loading(*id) {
|
||||
return None;
|
||||
}
|
||||
let name = match state.artist_views.get(id) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -108,3 +108,35 @@ fn status_animation_requires_local_unpaused_playback() {
|
||||
state.device_playback.role = crate::app::state::DevicePlaybackRole::Control;
|
||||
assert!(!crate::visualizer::status::playing(&state));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn federation_mode_badge_stays_visible_at_the_right_edge() {
|
||||
use crate::config::settings::LibrarySourceMode;
|
||||
use ratatui::style::Color;
|
||||
let mut state = playing_state();
|
||||
for (mode, background) in [
|
||||
(LibrarySourceMode::Local, Color::Yellow),
|
||||
(LibrarySourceMode::My, Color::Cyan),
|
||||
(LibrarySourceMode::Global, Color::Green),
|
||||
] {
|
||||
state.global.filters.source_mode = mode;
|
||||
for width in [20, 40, 80, 160, 200] {
|
||||
for playing in [false, true] {
|
||||
state.player.playing = playing;
|
||||
state.cmdline.active = !playing;
|
||||
let mut terminal = Terminal::new(TestBackend::new(width, 2)).unwrap();
|
||||
terminal
|
||||
.draw(|frame| draw_status(frame, frame.area(), &state))
|
||||
.unwrap();
|
||||
let label = format!(" federation: {} ", mode.label());
|
||||
let start = width - label.len() as u16;
|
||||
for (offset, ch) in label.chars().enumerate() {
|
||||
let cell = &terminal.backend().buffer()[(start + offset as u16, 0)];
|
||||
assert_eq!(cell.symbol(), ch.to_string());
|
||||
assert_eq!(cell.bg, background);
|
||||
assert_eq!(cell.fg, Color::Black);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,19 @@ pub fn role_pill(role: DevicePlaybackRole) -> Style {
|
||||
.add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
pub fn source_mode_pill(mode: crate::config::settings::LibrarySourceMode) -> Style {
|
||||
use crate::config::settings::LibrarySourceMode;
|
||||
let bg = match mode {
|
||||
LibrarySourceMode::Local => Color::Yellow,
|
||||
LibrarySourceMode::My => Color::Cyan,
|
||||
LibrarySourceMode::Global => Color::Green,
|
||||
};
|
||||
Style::new()
|
||||
.fg(Color::Black)
|
||||
.bg(bg)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
fn accent_color_for(state: &AppState) -> Color {
|
||||
match state.device_playback.role {
|
||||
DevicePlaybackRole::Jam => JAM_ACCENT,
|
||||
|
||||
Reference in new issue
Block a user