Compare commits

...
Author SHA1 Message Date
sanapachandClaude Opus 5.5 595c886303 Show both keymap notice and logging warning at startup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:26:30 +02:00
sanapachandClaude Opus 5.5 78bf2cf583 Keep all tabs visible on narrow terminals and wrap the podcasts placeholder
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:26:30 +02:00
sanapachandClaude Opus 5.5 df7ad3c8b7 Reject a keymap version nested in a binding; fix macOS keymap path in docs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:26:30 +02:00
sanapachandClaude Opus 5.5 df171208eb Document the new tab order and keymap version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:18:00 +02:00
sanapachandClaude Opus 5.5 e78f1627da Reorder tabs and migrate legacy keymap tab indices
Tabs are now 1 Library, 2 Playlists, 3 Queue, 4 Podcasts, 5 Settings,
6 Logs. The Podcasts tab is a placeholder that states podcasts are not
available in this build yet; it gets its own "podcasts" key context.

Keymap files gain an optional top-level `version`. The default keymap
declares `version = 2` and binds "6" to the Logs tab. Files without a
version (or with version 1) have their GoToTab indices remapped in
memory (3 -> 4, 4 -> 5, and 5 -> 3 for the prototype podcast build) with
a startup notice; the user's file is never rewritten. The help window
names the target tab instead of "Go to tab N".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:17:59 +02:00
Aleksandr Bogomiakov 292f17fee1 Added MODE status 2026-11-18 16:18:56 +00:00
Aleksandr Bogomiakov 3e46f21804 Fixed artist card fed update 2026-11-18 15:43:43 +00:00
Aleksandr Bogomiakov 7f0ca2984f Fixed artist card fed update 2026-11-18 15:41:54 +00:00
Aleksandr Bogomiakov 0ad3844d37 Bump 2026-11-16 00:17:50 +00:00
Aleksandr Bogomiakov 2253ec7d91 Added simple status visual 2026-11-15 23:48:33 +00:00
Aleksandr Bogomiakov 8dd3ededf6 Fixed queue bug 2026-10-10 00:19:10 +01:00
Aleksandr Bogomiakov 81fdcf13ae Fixed queue bug 2026-10-10 00:18:07 +01:00
Aleksandr Bogomiakov a6d502e319 Fix duplicate queue playback position 2026-10-09 23:54:07 +01:00
29 changed files with 3122 additions and 181 deletions

No files matched your search

+5
View File
@@ -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
+61
View File
@@ -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
@@ -293,6 +315,17 @@ created or edited while Furumi is running without rebuilding or restarting the
application. Bundled scripts use the same path and contract as user scripts,
so built-in and custom visualizations exercise the same runtime.
The v2 primitives are sufficient for small perspective wireframes without a
native 3D engine. The bundled morphing cube transforms eight vertices in Rhai
and batches its twelve edges into trace/vertical-line commands. Perspective,
audio-driven deformation, and depth cues stay in the user-editable script;
Rust rasterizes the resulting 2D commands. This deliberately avoids per-cell
script command maps and does not provide filled meshes or a depth buffer.
The richer cube preset adds bounded particle, ring, inner-cage, and echo
layers. Echo poses are reconstructed from earlier times with current audio
features, rather than retaining previous frames; particles have deterministic
lifetimes. Small terminals omit expensive layers and reduce particle counts.
The Rhai engine is configured as a sandboxed computation environment. Module
loading through `import` and `export` is disabled, no filesystem or network API
is exposed to scripts, and execution is bounded by limits on operations, call
@@ -305,6 +338,34 @@ intended role: transforming current audio features into drawing commands. It
is not a plugin mechanism for accessing the library, network, or player
controls.
Fullscreen execution currently happens synchronously during UI drawing, with a fresh
Rhai scope for each frame; scripts should derive motion from time and the
already-smoothed audio features rather than rely on retained mutable state.
The 50 ms animation timer gives a nominal 20 FPS cadence (other events can
also trigger redraws). Operation limits are not wall-clock deadlines. The
host also checks the script modification time during drawing, so slow script
storage or expensive custom scripts can still delay input. Benchmark script
evaluation and buffer drawing separately from real terminal throughput before
increasing scene complexity or the refresh rate.
The embedded status surface uses the same Rhai engine, input map, command
decoder, and clipped buffer rasterizer with a one-row viewport. It has an
independent AST cache and a fixed user-editable script in
`visualizations/status/braille.rhai`, installed if absent. Exact copies of the
previous bundled default can be atomically upgraded; edited files are preserved. It is not a
fullscreen preset. During local playback the visual timer samples the audio
analyzer without increasing trusted-device publication frequency. At most
one blocking render job is in flight; excess ticks are dropped. File access,
compilation, evaluation, and buffer preparation happen on that worker.
An `AppEvent` delivers a prepared row to `AppState`; UI drawing only copies
cells. Its audio input comes from the decoded-source analyzer before output
volume scaling; the volume field remains informational. Pause suspends jobs
and retains the last frame, even when the row needs resizing. Generation
checks discard results invalidated by track changes, resize, pause/resume,
or stop. Script errors are confined to the row and retried so
editing the file repairs the display. Status scripts have a smaller operation
budget, bounded source/output sizes, and cannot draw outside their viewport.
## Music-similarity indexing
Similarity search is an optional local capability and is disabled by default.
+25
View File
@@ -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
View File
@@ -1715,7 +1715,7 @@ dependencies = [
[[package]]
name = "furumi_tui"
version = "0.3.2"
version = "0.3.5"
dependencies = [
"anyhow",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "furumi_tui"
version = "0.3.2"
version = "0.3.5"
edition = "2024"
rust-version = "1.97"
description = "A federated P2P player for personal music libraries"
+35
View File
@@ -101,6 +101,9 @@ Download a prebuilt archive from the
[GitHub releases](https://github.com/house-of-vanity/furumi_tui/releases), or
build Furumi from source with Rust 1.97 or newer:
The repository selects the stable Rust toolchain. With rustup, run
`rustup update stable` to install or update it before building.
```bash
cargo build --release --locked
./target/release/furumi
@@ -146,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
+1 -1
View File
@@ -1,4 +1,4 @@
[toolchain]
channel = "1.97.0"
channel = "stable"
profile = "minimal"
components = ["clippy", "rust-src", "rustfmt"]
+4 -1
View File
@@ -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(),
+141
View File
@@ -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(_) => {}
}
}
+1
View File
@@ -14,6 +14,7 @@ pub enum AppEvent {
UpdateProgress(String),
UpdateInstalled(Result<(), String>),
StatusMessage(String),
StatusVisualizationReady(crate::visualizer::status::Ready),
/// A page of the artists list arrived (or failed).
ArtistsLoaded(Result<ArtistsPage, String>),
/// A full reload after a library change: replaces the loaded artist
+200 -83
View File
@@ -1,6 +1,7 @@
pub mod action;
mod cmdline;
pub mod command;
mod enrichment;
pub mod event;
pub mod input;
pub(crate) mod popup;
@@ -75,6 +76,7 @@ pub struct Runtime {
pub media_tx: std::sync::mpsc::Sender<crate::media::MediaUpdate>,
pub last_media_push: Option<std::time::Instant>,
pub status_publisher: crate::status::Publisher,
pub status_visualizer: crate::visualizer::status::Renderer,
}
#[derive(Debug, Clone, Copy)]
@@ -91,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:#}")
}
@@ -309,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) {
@@ -430,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()
@@ -510,6 +481,7 @@ pub async fn run(
media_tx,
last_media_push: None,
status_publisher: crate::status::Publisher::spawn(),
status_visualizer: crate::visualizer::status::Renderer::default(),
};
spawn_content_id_backfill(&runtime);
if state.similarity.settings.enabled {
@@ -533,6 +505,7 @@ pub async fn run(
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut visual_tick = tokio::time::interval(VISUALIZER_TICK_INTERVAL);
visual_tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut redraw = true;
loop {
let plain_text = match state.popup.as_ref() {
@@ -552,7 +525,8 @@ pub async fn run(
_ => {}
}
if !runtime.plain_text_mode {
sync_status_visualizer_target(&mut state, terminal.get_frame().area());
if !runtime.plain_text_mode && (redraw || runtime.force_redraw) {
if runtime.force_redraw {
terminal.clear()?;
runtime.force_redraw = false;
@@ -560,6 +534,7 @@ pub async fn run(
terminal.draw(|frame| ui::draw(frame, &state, &keymap))?;
}
redraw = true;
tokio::select! {
maybe_event = input.next() => match maybe_event {
Some(Ok(event)) => handle_terminal_event(&mut state, &mut keymap, &mut runtime, event),
@@ -578,8 +553,21 @@ pub async fn run(
maybe_prefetch_next(&mut state, &runtime);
push_media_update(&state, &mut runtime, false);
}
_ = visual_tick.tick(), if state.visualizer.active => {
sync_player_shared(&mut state, &runtime);
_ = visual_tick.tick(), if state.visualizer.active || crate::visualizer::status::playing(&state) => {
if state.visualizer.active {
sync_player_shared(&mut state, &runtime);
} else {
// The embedded meter only needs the atomic audio snapshot;
// keep device publication on the ordinary player tick.
state.player.audio_analysis = runtime.player.shared.audio_analysis();
// The ready event will repaint. Avoid rendering the old
// meter once here and the new meter again on completion.
redraw = false;
}
sync_status_visualizer_target(&mut state, terminal.get_frame().area());
if !runtime.plain_text_mode {
runtime.status_visualizer.request(&state, runtime.event_tx.clone());
}
}
}
@@ -630,6 +618,21 @@ fn leave_plain_text_mode() -> Result<()> {
Ok(())
}
fn sync_status_visualizer_target(state: &mut AppState, screen: ratatui::layout::Rect) {
let area = ui::status_visualizer_area(screen, state);
let target = if crate::visualizer::status::visible(state) && !area.is_empty() {
state
.player
.current
.as_ref()
.map(|track| (area.width, track_playback_key(track)))
} else {
None
};
state.status_visualizer.set_target(target);
state.status_visualizer.set_paused(state.player.paused);
}
fn sync_player_shared(state: &mut AppState, runtime: &Runtime) {
if state.device_playback.is_control() {
extrapolate_control_position(state);
@@ -1162,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 {
@@ -3041,6 +3043,24 @@ fn reset_artist_pagination(state: &mut AppState) {
global.reloading = false;
}
/// Preserve the queue position while refreshing library-backed entries.
///
/// A playback key identifies a track, not a queue occurrence: the same track
/// may intentionally appear more than once. Only entries removed before the
/// current position can therefore move the current occurrence.
fn queue_position_after_refresh(
queue: &[crate::library::models::TrackItem],
queue_pos: usize,
refreshed_ids: &std::collections::HashSet<i64>,
) -> usize {
let removed_before_current = queue
.iter()
.take(queue_pos)
.filter(|track| track.id >= 0 && !refreshed_ids.contains(&track.id))
.count();
queue_pos.saturating_sub(removed_before_current)
}
/// Swap queue entries for their fresh library copies; tracks that were
/// deleted leave the queue.
fn apply_queue_refresh(
@@ -3050,6 +3070,9 @@ fn apply_queue_refresh(
) {
let by_id: std::collections::HashMap<i64, _> =
tracks.into_iter().map(|track| (track.id, track)).collect();
let refreshed_ids: std::collections::HashSet<i64> = by_id.keys().copied().collect();
let refreshed_queue_pos =
queue_position_after_refresh(&state.player.queue, state.player.queue_pos, &refreshed_ids);
let by_key: std::collections::HashMap<String, _> = by_id
.values()
.cloned()
@@ -3085,26 +3108,38 @@ fn apply_queue_refresh(
state.queue_tab.cursor = 0;
return;
}
state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1);
state.queue_tab.cursor = state.queue_tab.cursor.min(state.player.queue.len() - 1);
match (current_id, current_key) {
(Some(id), _) if id < 0 => {
// The current source can be an ephemeral federated stream while
// the queue is refreshed after save-on-listen. It is not a
// deleted library row, so keep playback untouched.
state.player.queue_pos = state.player.queue_pos.min(state.player.queue.len() - 1);
state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1);
}
(Some(id), Some(key)) if by_id.contains_key(&id) || by_key.contains_key(&key) => {
if let Some(position) = state
// Keep the occurrence at the old position. Searching by key here
// would jump to the first copy when a track is queued repeatedly.
let position_matches_current = state
.player
.queue
.iter()
.position(|track| track_playback_key(track) == key)
.get(state.player.queue_pos)
.is_some_and(|track| track.id == id || track_playback_key(track) == key);
if !position_matches_current
&& let Some(position) = state
.player
.queue
.iter()
.position(|track| track.id == id || track_playback_key(track) == key)
{
state.player.queue_pos = position;
}
state.player.current = by_id
.get(&id)
state.player.current = state
.player
.queue
.get(state.player.queue_pos)
.cloned()
.or_else(|| by_id.get(&id).cloned())
.or_else(|| by_key.get(&key).cloned());
push_media_metadata(state, runtime);
}
@@ -3112,14 +3147,14 @@ fn apply_queue_refresh(
// The playing track was deleted from the library.
runtime.player_start_pending = false;
runtime.player.stop();
state.player.queue_pos = state.player.queue_pos.min(state.player.queue.len() - 1);
state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1);
state.player.current = None;
state.player.playing = false;
state.player.paused = false;
push_media_update(state, runtime, true);
}
(None, _) => {
state.player.queue_pos = state.player.queue_pos.min(state.player.queue.len() - 1);
state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1);
}
}
}
@@ -3271,6 +3306,10 @@ fn handle_playback_command(
fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent) {
match event {
AppEvent::StatusVisualizationReady(ready) => {
runtime.status_visualizer.busy = false;
state.status_visualizer.apply(ready);
}
AppEvent::UpdateChecked(result) => {
state.updater.busy = false;
state.updater.message = match result {
@@ -3734,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");
@@ -3867,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 {
@@ -3878,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
@@ -4371,6 +4411,57 @@ mod similarity_search_tests {
}
}
#[cfg(test)]
mod queue_refresh_tests {
use super::*;
use crate::library::models::TrackItem;
fn track(id: i64) -> TrackItem {
TrackItem {
id,
title: "duplicate".into(),
track_number: None,
disc_number: None,
duration_seconds: 1.0,
artists: vec![],
featured_artists: vec![],
release_id: 1,
release_title: "release".into(),
release_year: None,
cover_path: None,
file_path: format!("/music/{id}"),
content_id: None,
audio_format: None,
audio_bitrate: None,
audio_sample_rate: None,
audio_bit_depth: None,
file_size_bytes: None,
play_count: 0,
fed: None,
}
}
#[test]
fn queue_refresh_keeps_the_selected_duplicate_occurrence() {
let queue = vec![track(7), track(7), track(7)];
let refreshed_ids = std::collections::HashSet::from([7]);
assert_eq!(
queue_position_after_refresh(&queue, 2, &refreshed_ids),
2,
"refreshing duplicate queue entries must not select the first one"
);
}
#[test]
fn queue_refresh_shifts_position_only_for_removed_entries_before_it() {
let queue = vec![track(8), track(7), track(7)];
let refreshed_ids = std::collections::HashSet::from([7]);
assert_eq!(queue_position_after_refresh(&queue, 2, &refreshed_ids), 1);
}
}
/// Mirror the playback state to the OS now-playing surface. `force` skips
/// the position throttle (track switches, pauses).
fn push_media_update(state: &AppState, runtime: &mut Runtime, force: bool) {
@@ -4407,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);
}
}
+34 -1
View File
@@ -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,
}
@@ -1672,6 +1691,7 @@ pub struct AppState {
pub device_playback: DevicePlaybackState,
pub jam: crate::jam::JamStatus,
pub visualizer: crate::visualizer::VisualizerState,
pub status_visualizer: crate::visualizer::status::State,
pub global: GlobalTab,
pub artist_views: HashMap<i64, Loadable<ArtistDetail>>,
/// Federated card data that enriches a local artist page in-place.
@@ -1679,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.
@@ -1716,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
View File
@@ -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 => {}
}
}
+364
View File
@@ -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"));
}
}
+20 -4
View File
@@ -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
View File
@@ -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
View File
@@ -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],
+42
View File
@@ -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
View File
@@ -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
+22
View File
@@ -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()),
+262 -26
View File
@@ -1,10 +1,13 @@
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;
pub mod theme;
use ratatui::Frame;
@@ -48,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) {
@@ -71,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),
}
@@ -138,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
@@ -334,7 +491,7 @@ fn format_secs(secs: f64) -> String {
/// Playback time, progress bar, queue position, volume and mode flags.
/// Wider consoles get a longer bar and full flags; narrow ones drop pieces.
fn player_right_line(state: &AppState, width: u16) -> Line<'static> {
fn player_right_line(state: &AppState, width: u16) -> (Line<'static>, u16) {
let player = &state.player;
let mut spans: Vec<Span<'static>> = Vec::new();
if let Some(track) = &player.current
@@ -364,6 +521,7 @@ fn player_right_line(state: &AppState, width: u16) -> Line<'static> {
));
}
}
let volume_offset = spans.iter().map(Span::width).sum::<usize>() + 2;
if width >= 80 {
let volume_cells = usize::from(player.volume / 10);
spans.extend([
@@ -397,29 +555,99 @@ fn player_right_line(state: &AppState, width: u16) -> Line<'static> {
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(" "));
Line::from(spans)
(
Line::from(spans),
volume_offset.min(usize::from(u16::MAX)) as 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 [_, 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,
message_row.y,
version_width,
message_row.height,
);
let message = Rect::new(
message_row.x,
message_row.y,
version.x.saturating_sub(message_row.x).saturating_sub(1),
message_row.height,
);
// On wide terminals align exactly with "vol". On narrow ones keep the
// centered version readable, shrinking the histogram into the remainder.
let start = right
.x
.saturating_add(volume_offset)
.max(version.right().saturating_add(1))
.min(message_row.right());
let visual = Rect::new(
start,
message_row.y,
message_row.right().saturating_sub(start),
message_row.height,
);
[message, version, visual]
}
pub(crate) fn status_visualizer_area(screen: Rect, state: &AppState) -> Rect {
let [_, _, status] = Layout::vertical([
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(2),
])
.areas(screen);
footer_areas(status, state)[2]
}
fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
let [player_row, message_row] =
let [player_row, _] =
Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(area);
let [message_row, version_area, visual_area] = footer_areas(area, state);
let player = &state.player;
// 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 {
@@ -444,6 +672,16 @@ 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);
}
if state.cmdline.active {
// Vim-style command line takes over the message row.
@@ -453,7 +691,6 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
usize::from(message_row.width.saturating_sub(2)),
));
frame.render_widget(Paragraph::new(Line::from(spans)), message_row);
draw_version(frame, message_row);
return;
}
@@ -475,7 +712,6 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
},
};
frame.render_widget(Paragraph::new(message), message_row);
draw_version(frame, message_row);
if let Some(pending) = &state.pending_keys {
let pending = Paragraph::new(Line::styled(
@@ -494,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) {
@@ -507,7 +743,7 @@ fn active_artist_peer_search(state: &AppState) -> Option<String> {
fn draw_version(frame: &mut Frame, area: Rect) {
let version = format!("v{}", env!("CARGO_PKG_VERSION"));
frame.render_widget(
Paragraph::new(Line::styled(version, theme::dim())).alignment(Alignment::Right),
Paragraph::new(Line::styled(version, theme::dim())).alignment(Alignment::Center),
area,
);
}
+58
View File
@@ -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)
}
+142
View File
@@ -0,0 +1,142 @@
use super::*;
use ratatui::{Terminal, backend::TestBackend};
fn playing_state() -> AppState {
let mut state = AppState::default();
state.player.current = Some(crate::library::models::TrackItem {
id: 1,
title: "Песня 界".into(),
track_number: None,
disc_number: None,
duration_seconds: 240.0,
artists: vec![],
featured_artists: vec![],
release_id: 1,
release_title: "Release".into(),
release_year: None,
cover_path: None,
file_path: "/unused/test.flac".into(),
content_id: None,
audio_format: None,
audio_bitrate: None,
audio_sample_rate: None,
audio_bit_depth: None,
file_size_bytes: None,
play_count: 0,
fed: None,
});
state.player.playing = true;
state.player.position_secs = 12.0;
state
}
#[test]
fn footer_centers_version_and_aligns_visualization_under_volume() {
let mut state = playing_state();
for width in [160, 200] {
for shuffle in [false, true] {
state.player.shuffle = shuffle;
let mut terminal = Terminal::new(TestBackend::new(width, 2)).unwrap();
terminal
.draw(|frame| draw_status(frame, frame.area(), &state))
.unwrap();
let buffer = terminal.backend().buffer();
let version = format!("v{}", env!("CARGO_PKG_VERSION"));
// Count display cells, not UTF-8 bytes: the title is non-ASCII.
let volume_x = (0..width)
.find(|x| {
buffer[(*x, 0)].symbol() == "v"
&& *x + 2 < width
&& buffer[(*x + 1, 0)].symbol() == "o"
&& buffer[(*x + 2, 0)].symbol() == "l"
})
.unwrap();
let areas = footer_areas(Rect::new(0, 0, width, 2), &state);
assert_eq!(areas[2].x, volume_x);
assert_eq!(areas[2].y, 1);
assert_eq!(areas[2].right(), width);
let version_x = (width - version.len() as u16) / 2;
for (offset, ch) in version.chars().enumerate() {
assert_eq!(
buffer[(version_x + offset as u16, 1)].symbol(),
ch.to_string()
);
}
assert_eq!(
status_visualizer_area(Rect::new(0, 0, width, 24), &state).x,
volume_x
);
}
}
}
#[test]
fn footer_regions_do_not_overlap_on_narrow_terminals_or_command_input() {
let mut state = playing_state();
state.status_message = Some("long status message ".repeat(20));
for width in [1, 5, 8, 20, 40, 80, 120, 200] {
let areas = footer_areas(Rect::new(0, 0, width, 2), &state);
assert!(areas[0].right() <= areas[1].x);
assert!(areas[1].right() <= areas[2].x);
assert!(areas[2].right() <= width);
for command in [false, true] {
state.cmdline.active = command;
let mut terminal = Terminal::new(TestBackend::new(width, 2)).unwrap();
terminal
.draw(|frame| draw_status(frame, frame.area(), &state))
.unwrap();
// Neither messages nor the command prompt may paint the graph.
for x in areas[2].x..areas[2].right() {
assert_eq!(terminal.backend().buffer()[(x, 1)].symbol(), " ");
}
}
}
}
#[test]
fn status_animation_requires_local_unpaused_playback() {
let mut state = playing_state();
assert!(crate::visualizer::status::playing(&state));
state.player.paused = true;
assert!(!crate::visualizer::status::playing(&state));
assert!(crate::visualizer::status::visible(&state));
state.player.paused = false;
state.player.playing = false;
assert!(!crate::visualizer::status::playing(&state));
assert!(!crate::visualizer::status::visible(&state));
state.player.playing = true;
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);
}
}
}
}
}
+13
View File
@@ -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,
+279
View File
@@ -0,0 +1,279 @@
// name: Morphing cube
// protocol: furumi-visualizer-v2
// bundle-version: 6
//
// Audio-reactive neon wireframe, echo contours, core, shock rings, sparks
// and a bounded particle field. No native 3D API or retained state required.
// Echoes sample earlier rotation times with CURRENT audio; they are analytic
// trails, not stored frames. Particle lifetimes use time, rings also expand
// as the smoothed beat envelope decays. No beat history is available in v2.
//
// Fixed budgets: 8 mesh vertices, at most 48 particles + 24 short tails,
// 20 background stars, 3 rings, 2 echoes. Edges/rings use bulk trace commands.
// Smaller terminals omit echoes/rings and reduce particle counts.
fn clamp(v, lo, hi) {
if v < lo { lo } else if v > hi { hi } else { v }
}
fn min(a, b) { if a < b { a } else { b } }
fn rgb(r, g, b) {
to_int(clamp(r, 0.0, 255.0)) * 65536
+ to_int(clamp(g, 0.0, 255.0)) * 256
+ to_int(clamp(b, 0.0, 255.0))
}
// trace runs left-to-right. Swap endpoints for reversed edges and use
// vline for vertical ones (including an edge projected to a single cell).
fn edge(ax, ay, bx, by, fg, bg) {
if ax > bx {
let tx = ax; ax = bx; bx = tx;
let ty = ay; ay = by; by = ty;
}
if ax == bx {
return #{ op: "vline", x: ax, y: min(ay, by),
h: abs(to_float(by - ay)).to_int() + 1, ch: "|", fg: fg, bg: bg };
}
let dx = bx - ax;
let dy = by - ay;
let ch = if abs(to_float(dy)) * 3.0 < to_float(dx) { "-" }
else if abs(to_float(dy)) > to_float(dx) { "|" }
else if dy < 0 { "/" } else { "\\" };
let ys = [];
let slope = to_float(dy) / to_float(dx);
for x in 0..=dx {
ys.push(to_int(to_float(ay) + to_float(x) * slope + 0.5));
}
#{ op: "trace", x: ax, ys: ys, ch: ch, line_ch: ch,
fg: fg, line_fg: fg, bg: bg }
}
// Lift quieter passages without a hard gain/clipping threshold.
fn response(level) { 1.0 - pow(1.0 - clamp(level, 0.0, 1.0), 1.6) }
fn palette(t, heat, light) {
rgb((95.0 + 125.0 * heat + 35.0 * sin(t * 0.43)) * light,
(185.0 - 95.0 * heat + 55.0 * sin(t * 0.31 + 1.3)) * light,
255.0 * light)
}
// A single projected mesh, fitted uniformly: never clamp individual corners.
fn mesh(t, energy, bass, mid, treble, beat, width, height) {
let pulse = 0.70 + energy * 0.45 + beat * 0.85;
let sx = pulse * (1.0 + bass * 0.55);
let sy = pulse * (1.0 - bass * 0.42 + mid * 0.15);
let sz = pulse * (1.0 + treble * 0.22);
// A bounded beat kick, not time * instantaneous_energy (which jumps).
let ax = t * 0.47 + 0.35 + beat * 0.22 * sin(t * 1.3);
let ay = t * 0.63 + 0.55;
let az = t * 0.23 + beat * 0.16 * cos(t * 0.7);
let cx = cos(ax); let snx = sin(ax);
let cy = cos(ay); let sny = sin(ay);
let cz = cos(az); let snz = sin(az);
let twist = mid * 0.95 * sin(t * 0.83);
let ct = cos(twist); let st = sin(twist);
let vertices = [
[-1.0, -1.0, -1.0], [1.0, -1.0, -1.0],
[1.0, 1.0, -1.0], [-1.0, 1.0, -1.0],
[-1.0, -1.0, 1.0], [1.0, -1.0, 1.0],
[1.0, 1.0, 1.0], [-1.0, 1.0, 1.0]
];
let projected = [];
let extent = 0.01;
for i in 0..8 {
let v = vertices[i];
let pull = 1.0 + treble * 0.38 * sin(t * 2.3 + to_float(i) * 2.4)
+ beat * 0.14 * cos(to_float(i) * 1.7 + t);
let x = v[0] * sx * pull;
let y = v[1] * sy * pull;
let z = v[2] * sz * pull;
let xt = x * ct + z * st * v[1];
let zt = z * ct - x * st * v[1];
let y1 = y * cx - zt * snx;
let z1 = y * snx + zt * cx;
let x2 = xt * cy + z1 * sny;
let z2 = z1 * cy - xt * sny;
let x3 = x2 * cz - y1 * snz;
let y3 = x2 * snz + y1 * cz;
// Even the largest deformed vertex stays < 6.4 from the origin.
let perspective = 10.0 / (10.0 + z2);
let px = x3 * perspective;
let py = y3 * perspective;
if abs(px) > extent { extent = abs(px); }
if abs(py) > extent { extent = abs(py); }
projected.push([px, py, z2]);
}
// CELL_ASPECT is cell height / width; adjust for a different font.
let CELL_ASPECT = 2.0;
let span = min(to_float(width - 4) / CELL_ASPECT, to_float(height - 4));
let scale = span * min(0.23, 0.46 / extent);
let center_x = to_float(width - 1) * 0.5;
let center_y = to_float(height - 1) * 0.5;
let points = [];
for p in projected {
points.push([to_int(center_x + p[0] * scale * CELL_ASPECT + 0.5),
to_int(center_y + p[1] * scale + 0.5), p[2]]);
}
points
}
// Method calls mutate the command array in place; don't copy it into helpers.
fn dot(x, y, ch, fg, bg, width, height) {
let px = to_int(x + 0.5); let py = to_int(y + 0.5);
if x >= 0.0 && y >= 1.0 && px < width && py < height - 1 {
this.push(#{ op: "cell", x: px, y: py, ch: ch, fg: fg, bg: bg });
}
}
fn render(input) {
let bg = 0x020610;
let cmds = [#{ op: "clear", bg: bg }];
if input.width < 12 || input.height < 8 { return cmds; }
let w = input.width; let h = input.height;
let t = input.time;
let energy = response(input.energy);
let bass = response(input.bass);
let mid = response(input.mid);
let treble = response(input.treble);
let beat = response(input.beat);
let drive = clamp(energy * 0.4 + treble * 0.3 + beat * 0.8, 0.0, 1.0);
let small = w < 40 || h < 16;
let center_x = to_float(w - 1) * 0.5;
let center_y = to_float(h - 1) * 0.5;
let span = min(to_float(w - 4) * 0.5, to_float(h - 4));
let points = mesh(t, energy, bass, mid, treble, beat, w, h);
let edges = [[0,1], [1,2], [2,3], [3,0], [4,5], [5,6],
[6,7], [7,4], [0,4], [1,5], [2,6], [3,7]];
// Sparse drifting starfield; deterministic, independent of audio hardware.
let stars = if small { 8 } else { 20 };
for i in 0..stars {
let phase = to_float(i);
let x = (phase * 37.71 + t * (0.3 + to_float(i % 3) * 0.2)) % to_float(w - 1);
let y = 1.0 + (phase * 13.37) % to_float(h - 3);
let light = 0.12 + treble * 0.16 * (0.5 + 0.5 * sin(t * 2.0 + phase));
cmds.dot(x, y, ".", palette(t, 0.0, light), bg, w, h);
}
// Three elliptical shock fronts. On a transient they brighten and
// spread; release of the beat envelope carries them farther outward.
if !small && drive > 0.04 {
for ring in 0..3 {
let phase = (t * 0.45 + to_float(ring) / 3.0) % 1.0;
let radius = 0.22 + phase * 0.55 + (1.0 - beat) * 0.18;
let rx = span * radius;
let ry = span * radius * (0.22 + mid * 0.10);
let left = to_int(center_x - rx);
let right = to_int(center_x + rx);
let top = []; let bottom = [];
for x in left..=right {
let nx = clamp((to_float(x) - center_x) / rx, -1.0, 1.0);
let dy = sqrt(1.0 - nx * nx) * ry;
top.push(to_int(center_y - dy + 0.5));
bottom.push(to_int(center_y + dy + 0.5));
}
let fg = palette(t + to_float(ring), beat, (1.0 - phase) * (0.12 + beat * 0.45 + bass * 0.12));
for ys in [top, bottom] {
cmds.push(#{ op: "trace", x: left, ys: ys, ch: ".", line_ch: ".",
fg: fg, line_fg: fg, bg: bg });
}
}
}
// Particles launch from the eight corners with staggered lifetimes.
// Speed/age depend on time; audio changes reach and brightness instead
// of rescaling time and teleporting particles on each audio update.
if drive > 0.04 {
let particles = if small { 16 } else { 48 };
for i in 0..particles {
let fi = to_float(i);
let age = (t * (0.27 + to_float(i % 5) * 0.025) + fi * 0.618034) % 1.0;
let angle = fi * 2.39996 + t * 0.16;
let dx = cos(angle); let dy = sin(angle);
let origin = points[i % 8];
let travel = span * (0.35 + energy * 0.55 + beat * 0.8);
let distance = age * travel;
let light = sin(age * 3.14159) * (0.15 + drive * 0.85);
let fg = palette(t + fi * 0.13, beat, light);
let ch = if beat > 0.45 && i % 3 == 0 { "*" } else if treble > 0.35 { "+" } else { "." };
if !small && i % 2 == 0 {
let tail = distance - span * 0.04;
cmds.dot(to_float(origin[0]) + dx * tail * 2.0,
to_float(origin[1]) + dy * tail, ".", palette(t, beat, light * 0.3), bg, w, h);
}
cmds.dot(to_float(origin[0]) + dx * distance * 2.0,
to_float(origin[1]) + dy * distance, ch, fg, bg, w, h);
}
}
// Analytic motion echoes. These are recomputed poses, not frame history.
if !small && drive > 0.04 {
for echo in [2, 1] {
let lag = to_float(echo) * (0.14 + beat * 0.10);
let ghost = mesh(t - lag, energy, bass, mid, treble, beat, w, h);
let fg = palette(t + to_float(echo), 1.0 - beat, (0.08 + drive * 0.16) / to_float(echo));
for e in edges {
let a = ghost[e[0]]; let b = ghost[e[1]];
cmds.push(edge(a[0], a[1], b[0], b[1], fg, bg));
}
}
}
// A warm inner cage gives depth and a second pulse inside the main mesh.
if !small {
let inner = [];
let size = 0.35 + beat * 0.25;
for p in points {
inner.push([to_int(center_x + (to_float(p[0]) - center_x) * size + 0.5),
to_int(center_y + (to_float(p[1]) - center_y) * size + 0.5)]);
}
let fg = rgb(100.0 + beat * 155.0, 45.0 + energy * 75.0, 65.0 + treble * 70.0);
for e in edges {
let a = inner[e[0]]; let b = inner[e[1]];
cmds.push(edge(a[0], a[1], b[0], b[1], fg, bg));
}
}
let ordered = [];
for e in edges {
let depth = (points[e[0]][2] + points[e[1]][2]) * 0.5;
let at = 0;
while at < ordered.len() && ordered[at][2] > depth { at += 1; }
ordered.insert(at, [e[0], e[1], depth]);
}
for e in ordered {
let a = points[e[0]]; let b = points[e[1]];
let light = clamp(0.78 - e[2] * 0.14 + beat * 0.12, 0.3, 1.0);
cmds.push(edge(a[0], a[1], b[0], b[1], palette(t, beat, light), bg));
}
// Sparks travel along edges; no more than twelve extra cells.
if treble > 0.08 || beat > 0.08 {
for i in 0..12 {
let e = edges[i]; let a = points[e[0]]; let b = points[e[1]];
let phase = (t * 0.8 + to_float(i) * 0.137) % 1.0;
cmds.dot(to_float(a[0]) + to_float(b[0] - a[0]) * phase,
to_float(a[1]) + to_float(b[1] - a[1]) * phase,
"*", 0xffe8c0, bg, w, h);
}
}
for p in points {
if !small && beat > 0.45 {
let glow = palette(t, beat, beat * 0.45);
for offset in [[-1,0], [1,0], [0,-1], [0,1]] {
cmds.dot(to_float(p[0] + offset[0]), to_float(p[1] + offset[1]), "+", glow, bg, w, h);
}
}
cmds.push(#{ op: "cell", x: p[0], y: p[1], ch: "o", fg: 0xe8f6ff, bg: bg });
}
if input.show_clock {
cmds.push(#{ op: "text", x: 1, y: 0, text: input.clock, fg: 0xa6cde0, bg: bg });
}
if input.paused {
cmds.push(#{ op: "text", x: w - 7, y: 0, text: "paused", fg: 0xa6cde0, bg: bg });
}
if w >= 16 {
cmds.push(#{ op: "text", x: 1, y: h - 1, text: "MORPHING CUBE", fg: 0x527b98, bg: bg });
}
cmds
}
+57
View File
@@ -0,0 +1,57 @@
// name: Status braille histogram
// protocol: furumi-visualizer-v2
// surface: status
// revision: 2
//
// One-row waveform histogram. Input is decoded audio BEFORE output volume.
// The host freezes the last frame on pause, including custom scripts.
// Edit this file to customize it; only untouched bundled defaults upgrade.
// Each Braille character packs two independent four-dot vertical columns.
// "default" background retains the terminal's background color.
fn clamp(value, low, high) {
if value < low { low } else if value > high { high } else { value }
}
// Local RMS for one slice of the recent waveform. Method syntax avoids
// copying the complete sample array for every column.
fn level(index, columns, reference) {
let count = this.len();
if count == 0 { return 0; }
let start = index * count / columns;
let end = (index + 1) * count / columns;
let square = 0.0;
let total = 0;
for i in start..end {
square += this[i] * this[i];
total += 1;
}
let rms = if total > 0 { sqrt(square / to_float(total)) }
else { abs(this[start]) };
// Remove the near-silent baseline and spread useful levels over 0..4.
// No additive bass/energy/beat floor: quiet columns really become empty.
let normalized = clamp((rms / reference - 0.12) / 0.72, 0.0, 1.0);
to_int(normalized * 4.0 + 0.5)
}
fn render(input) {
let commands = [#{ op: "clear", bg: "default" }];
if input.width <= 0 || input.height <= 0 { return commands; }
let samples = input.samples;
let square = 0.0;
for sample in samples { square += sample * sample; }
let rms = if samples.len() > 0 { sqrt(square / to_float(samples.len())) } else { 0.0 };
// Adapt headroom to the current recording, with an absolute noise floor
// so silence/very quiet passages are never normalized into a full row.
let reference = if rms * 1.8 > 0.10 { rms * 1.8 } else { 0.10 };
let dots = ["⠀⢀⢠⢰⢸", "⡀⣀⣠⣰⣸", "⡄⣄⣤⣴⣼", "⡆⣆⣦⣶⣾", "⡇⣇⣧⣷⣿"];
let columns = input.width * 2;
for x in 0..input.width {
let left = samples.level(x * 2, columns, reference);
let right = samples.level(x * 2 + 1, columns, reference);
let glyph = dots[left].sub_string(right, 1);
commands.push(#{ op: "cell", x: x, y: 0, ch: glyph,
fg: 0x48c9c0, bg: "default" });
}
commands
}
+353 -32
View File
@@ -1,4 +1,4 @@
//! Script-backed fullscreen visualizers.
//! Script-backed fullscreen and status-bar visualizers.
//!
//! Rust owns the audio tap, script loading, sandboxed execution limits and
//! terminal drawing primitives. Visual math lives in `.rhai` files: every
@@ -11,6 +11,9 @@ use std::time::{Instant, SystemTime};
use anyhow::{Context as _, Result};
use ratatui::Frame;
use ratatui::buffer::Buffer;
pub mod status;
use ratatui::layout::Rect;
use ratatui::style::{Color, Style};
use ratatui::widgets::{Clear, Paragraph};
@@ -20,12 +23,12 @@ use serde::{Deserialize, Serialize};
use crate::app::state::AppState;
const PRIMARY_SCRIPT_ID: &str = "scope_spectrum";
const BUNDLE_VERSION: u32 = 5;
struct BundledScript {
id: &'static str,
file_name: &'static str,
display_name: &'static str,
version: u32,
source: &'static str,
}
@@ -34,14 +37,23 @@ const BUNDLED_SCRIPTS: &[BundledScript] = &[
id: PRIMARY_SCRIPT_ID,
file_name: "scope_spectrum.rhai",
display_name: "Scope spectrum",
version: 5,
source: include_str!("visualizations/scope_spectrum.rhai"),
},
BundledScript {
id: "pulsing_sphere",
file_name: "pulsing_sphere.rhai",
display_name: "Pulsing sphere",
version: 5,
source: include_str!("visualizations/pulsing_sphere.rhai"),
},
BundledScript {
id: "morphing_cube",
file_name: "morphing_cube.rhai",
display_name: "Morphing cube",
version: 6,
source: include_str!("visualizations/morphing_cube.rhai"),
},
];
#[derive(Debug, Clone)]
@@ -114,6 +126,9 @@ impl VisualizerState {
}
pub fn load_library(&mut self) -> Result<()> {
if let Err(err) = status::ensure_script() {
tracing::warn!(%err, "status visualization initialization failed");
}
ensure_bundled_scripts()?;
self.config = load_config().unwrap_or_else(|err| {
tracing::warn!(%err, "visualization settings failed to load; using defaults");
@@ -284,7 +299,10 @@ pub fn draw(frame: &mut Frame, state: &AppState) {
}
fn input_map(area: Rect, state: &AppState) -> Map {
let features = features_from_state(state);
input_map_with_features(area, state, features_from_state(state, true))
}
fn input_map_with_features(area: Rect, state: &AppState, features: AudioFeatures) -> Map {
let mut input = Map::new();
insert_int(&mut input, "width", i64::from(area.width));
insert_int(&mut input, "height", i64::from(area.height));
@@ -329,7 +347,7 @@ fn input_map(area: Rect, state: &AppState) -> Map {
input
}
fn features_from_state(state: &AppState) -> AudioFeatures {
fn features_from_state(state: &AppState, scale_output: bool) -> AudioFeatures {
let elapsed_secs = state
.visualizer
.started_at
@@ -355,12 +373,18 @@ fn features_from_state(state: &AppState) -> AudioFeatures {
.unwrap_or(0.17);
let analysis = &state.player.audio_analysis;
let volume = f64::from(state.player.volume.min(100)) / 100.0;
let output_scale = if state.player.volume == 0 {
let output_scale = if !scale_output {
1.0
} else if state.player.volume == 0 {
0.0
} else {
0.35 + volume * 0.65
};
let active_scale = if state.player.paused { 0.12 } else { 1.0 };
let active_scale = if scale_output && state.player.paused {
0.12
} else {
1.0
};
let scale = output_scale * active_scale;
AudioFeatures {
@@ -373,7 +397,7 @@ fn features_from_state(state: &AppState) -> AudioFeatures {
bass: (analysis.bass * scale).clamp(0.0, 1.0),
mid: (analysis.mid * scale).clamp(0.0, 1.0),
treble: (analysis.treble * scale).clamp(0.0, 1.0),
beat: if state.player.paused {
beat: if scale_output && state.player.paused {
0.0
} else {
(analysis.beat * output_scale).clamp(0.0, 1.0)
@@ -423,6 +447,10 @@ impl Default for ScriptRuntime {
.set_max_string_size(1_000_000)
.set_max_array_size(120_000)
.set_max_map_size(1_000_000);
engine.on_print(|message| tracing::debug!(message, "visualizer script"));
engine.on_debug(|message, source, position| {
tracing::debug!(message, ?source, ?position, "visualizer script")
});
engine.disable_symbol("import");
engine.disable_symbol("export");
engine.register_fn("sin", |value: FLOAT| value.sin());
@@ -606,11 +634,15 @@ impl DrawCommand {
}
fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
render_commands_to_buffer(frame.buffer_mut(), area, commands);
}
fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCommand]) {
for command in commands {
match command {
DrawCommand::Clear { bg } => fill_rect(frame, area, " ", Style::new().bg(*bg)),
DrawCommand::Clear { bg } => fill_rect(buffer, area, " ", Style::new().bg(*bg)),
DrawCommand::Cell { x, y, ch, fg, bg } => {
write_cell(frame, area, *x, *y, ch, Style::new().fg(*fg).bg(*bg));
write_cell(buffer, area, *x, *y, ch, Style::new().fg(*fg).bg(*bg));
}
DrawCommand::HLine {
x,
@@ -621,8 +653,8 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
bg,
} => {
let style = Style::new().fg(*fg).bg(*bg);
for offset in 0..*w {
write_cell(frame, area, x.saturating_add(offset), *y, ch, style);
for offset in 0..(*w).min(area.width.saturating_sub(*x)) {
write_cell(buffer, area, x.saturating_add(offset), *y, ch, style);
}
}
DrawCommand::VLine {
@@ -634,8 +666,8 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
bg,
} => {
let style = Style::new().fg(*fg).bg(*bg);
for offset in 0..*h {
write_cell(frame, area, *x, y.saturating_add(offset), ch, style);
for offset in 0..(*h).min(area.height.saturating_sub(*y)) {
write_cell(buffer, area, *x, y.saturating_add(offset), ch, style);
}
}
DrawCommand::Rect {
@@ -648,10 +680,10 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
bg,
} => {
let style = Style::new().fg(*fg).bg(*bg);
for row in 0..*h {
for col in 0..*w {
for row in 0..(*h).min(area.height.saturating_sub(*y)) {
for col in 0..(*w).min(area.width.saturating_sub(*x)) {
write_cell(
frame,
buffer,
area,
x.saturating_add(col),
y.saturating_add(row),
@@ -673,7 +705,12 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
let line_style = Style::new().fg(*line_fg).bg(*bg);
let point_style = Style::new().fg(*fg).bg(*bg);
let mut previous_y: Option<u16> = None;
for (index, y) in ys.iter().copied().enumerate() {
for (index, y) in ys
.iter()
.copied()
.take(usize::from(area.width.saturating_sub(*x)))
.enumerate()
{
let Ok(offset) = u16::try_from(index) else {
break;
};
@@ -681,21 +718,25 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
if let Some(previous) = previous_y {
let from = previous.min(y);
let to = previous.max(y);
for y in from..=to {
write_cell(frame, area, x, y, line_ch, line_style);
for y in from..=to.min(area.height.saturating_sub(1)) {
write_cell(buffer, area, x, y, line_ch, line_style);
}
}
write_cell(frame, area, x, y, ch, point_style);
write_cell(buffer, area, x, y, ch, point_style);
previous_y = Some(y);
}
}
DrawCommand::Text { x, y, text, fg, bg } => {
for (offset, ch) in text.chars().enumerate() {
for (offset, ch) in text
.chars()
.take(usize::from(area.width.saturating_sub(*x)))
.enumerate()
{
let Ok(offset) = u16::try_from(offset) else {
break;
};
write_cell(
frame,
buffer,
area,
x.saturating_add(offset),
*y,
@@ -708,24 +749,21 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
}
}
fn fill_rect(frame: &mut Frame, area: Rect, symbol: &'static str, style: Style) {
fn fill_rect(buffer: &mut Buffer, area: Rect, symbol: &'static str, style: Style) {
for y in area.y..area.y + area.height {
for x in area.x..area.x + area.width {
if let Some(cell) = frame.buffer_mut().cell_mut((x, y)) {
if let Some(cell) = buffer.cell_mut((x, y)) {
cell.set_symbol(symbol).set_style(style);
}
}
}
}
fn write_cell(frame: &mut Frame, area: Rect, x: u16, y: u16, symbol: &str, style: Style) {
fn write_cell(buffer: &mut Buffer, area: Rect, x: u16, y: u16, symbol: &str, style: Style) {
if x >= area.width || y >= area.height {
return;
}
if let Some(cell) = frame
.buffer_mut()
.cell_mut((area.x.saturating_add(x), area.y.saturating_add(y)))
{
if let Some(cell) = buffer.cell_mut((area.x.saturating_add(x), area.y.saturating_add(y))) {
cell.set_symbol(symbol).set_style(style);
}
}
@@ -774,6 +812,9 @@ fn rgb_color(value: INT) -> Color {
}
fn parse_color(text: &str) -> Option<Color> {
if text == "default" {
return Some(Color::Reset);
}
let hex = text.trim().trim_start_matches('#').trim_start_matches("0x");
let value = u32::from_str_radix(hex, 16).ok()?;
Some(Color::Rgb(
@@ -850,7 +891,7 @@ fn ensure_bundled_scripts() -> Result<()> {
fn should_replace_bundled_script(existing: &str, script: &BundledScript) -> bool {
let name_marker = format!("// name: {}", script.display_name);
let version_marker = format!("// bundle-version: {BUNDLE_VERSION}");
let version_marker = format!("// bundle-version: {}", script.version);
existing
.lines()
.take(3)
@@ -918,9 +959,9 @@ mod tests {
insert_int(&mut input, "analysis_sequence", 1);
input.insert(
"samples".into(),
(0..128)
(0..256)
.map(|index| {
let sample = ((index as f64 / 128.0) * std::f64::consts::TAU).sin();
let sample = ((index as f64 / 256.0) * std::f64::consts::TAU).sin();
Dynamic::from_float(sample as FLOAT)
})
.collect::<Array>()
@@ -991,4 +1032,284 @@ mod tests {
scope,
));
}
fn cube_file() -> tempfile::NamedTempFile {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
file.path(),
include_str!("visualizations/morphing_cube.rhai"),
)
.unwrap();
file
}
#[test]
fn cube_update_does_not_upgrade_other_presets() {
let cube = BUNDLED_SCRIPTS
.iter()
.find(|script| script.id == "morphing_cube")
.unwrap();
let old_cube = cube
.source
.replacen("// bundle-version: 6", "// bundle-version: 5", 1);
assert!(should_replace_bundled_script(&old_cube, cube));
for script in BUNDLED_SCRIPTS {
assert!(!should_replace_bundled_script(script.source, script));
}
let custom = old_cube.replacen("// name: Morphing cube", "// name: My cube", 1);
assert!(!should_replace_bundled_script(&custom, cube));
}
#[test]
fn cube_music_adds_particles_echoes_and_a_larger_pulse() {
let file = cube_file();
let mut runtime = ScriptRuntime::default();
let mut input = test_input();
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, 0.0);
}
let quiet = runtime.render(file.path(), input.clone()).unwrap();
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, 0.8);
}
let loud = runtime.render(file.path(), input).unwrap();
let effects = |commands: &[DrawCommand]| {
commands
.iter()
.filter(|command| matches!(command, DrawCommand::Cell { ch, .. } if ch != "o"))
.count()
};
assert!(
effects(&loud) > effects(&quiet) + 30,
"music should visibly populate the scene"
);
let lines = |commands: &[DrawCommand]| {
commands
.iter()
.filter(|command| {
matches!(
command,
DrawCommand::Trace { .. } | DrawCommand::VLine { .. }
)
})
.count()
};
assert_eq!(
lines(&loud),
lines(&quiet) + 30,
"two echoes and three rings"
);
let footprint = |commands: &[DrawCommand]| {
let vertices = cube_vertices(commands);
let xs: Vec<_> = vertices.iter().map(|p| p.0).collect();
let ys: Vec<_> = vertices.iter().map(|p| p.1).collect();
u32::from(xs.iter().max().unwrap() - xs.iter().min().unwrap())
* u32::from(ys.iter().max().unwrap() - ys.iter().min().unwrap())
};
assert!(
footprint(&loud) > footprint(&quiet) * 2,
"pulse should be substantially larger"
);
}
fn cube_vertices(commands: &[DrawCommand]) -> Vec<(u16, u16)> {
commands
.iter()
.filter_map(|command| match command {
DrawCommand::Cell { x, y, ch, .. } if ch == "o" => Some((*x, *y)),
_ => None,
})
.collect()
}
#[test]
fn cube_rotates_and_each_audio_control_deforms_geometry() {
let file = cube_file();
let mut runtime = ScriptRuntime::default();
let mut input = test_input();
insert_int(&mut input, "width", 160);
insert_int(&mut input, "height", 60);
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, 0.0);
}
let quiet = cube_vertices(&runtime.render(file.path(), input.clone()).unwrap());
assert_eq!(quiet.len(), 8);
for band in ["energy", "bass", "mid", "treble", "beat"] {
let mut loud = input.clone();
insert_float(&mut loud, band, 1.0);
let deformed = cube_vertices(&runtime.render(file.path(), loud).unwrap());
assert_ne!(
quiet, deformed,
"{band} should move vertices, not just colors"
);
}
insert_float(&mut input, "time", 3.0);
let rotated = cube_vertices(&runtime.render(file.path(), input).unwrap());
assert_ne!(quiet, rotated, "rotation should continue in silence");
}
#[test]
fn cube_stays_bounded_across_sizes_times_and_audio_extremes() {
let file = cube_file();
let mut runtime = ScriptRuntime::default();
// Much tighter than the production two-million-operation ceiling.
runtime.engine.set_max_operations(200_000);
for (width, height) in [
(1, 1),
(11, 7),
(12, 8),
(24, 80),
(80, 24),
(160, 50),
(320, 100),
] {
for level in [0.0, 0.5, 1.0] {
for tick in 0..12 {
let mut input = test_input();
insert_int(&mut input, "width", width);
insert_int(&mut input, "height", height);
insert_float(&mut input, "time", f64::from(tick) * 1.37);
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, level);
}
let commands = runtime.render(file.path(), input).unwrap();
assert!(commands.len() <= 220);
if width < 12 || height < 8 {
assert_eq!(commands.len(), 1);
continue;
}
assert_eq!(cube_vertices(&commands).len(), 8);
let mut edges = 0;
for command in &commands {
match command {
DrawCommand::Trace { x, ys, .. } => {
edges += 1;
assert!(usize::from(*x) + ys.len() <= width as usize);
assert!(ys.iter().all(|y| i64::from(*y) < height));
}
DrawCommand::VLine { x, y, h, .. } => {
edges += 1;
assert!(i64::from(*x) < width);
assert!(i64::from(*y) + i64::from(*h) <= height);
}
DrawCommand::Cell { x, y, .. } => {
assert!(i64::from(*x) < width && i64::from(*y) < height);
}
_ => {}
}
}
assert!((12..=54).contains(&edges));
}
}
}
}
#[test]
fn cube_edges_handle_reversed_vertical_and_collapsed_projections() {
let runtime = ScriptRuntime::default();
let ast = runtime
.engine
.compile(include_str!("visualizations/morphing_cube.rhai"))
.unwrap();
for (ax, ay, bx, by) in [
(2_i64, 3_i64, 8_i64, 9_i64),
(8, 9, 2, 3),
(2, 9, 8, 3),
(8, 3, 2, 9),
(4, 9, 4, 3),
(4, 3, 4, 3),
] {
let output = runtime
.engine
.call_fn::<Dynamic>(
&mut Scope::new(),
&ast,
"edge",
(ax, ay, bx, by, 0xffffff_i64, 0_i64),
)
.unwrap();
match DrawCommand::from_dynamic(output).unwrap() {
DrawCommand::Trace { x, ys, .. } => {
assert_eq!(i64::from(x), ax.min(bx));
assert_eq!(ys.len(), (ax - bx).unsigned_abs() as usize + 1);
let (left_y, right_y) = if ax < bx { (ay, by) } else { (by, ay) };
assert_eq!(i64::from(ys[0]), left_y);
assert_eq!(i64::from(*ys.last().unwrap()), right_y);
}
DrawCommand::VLine { x, y, h, .. } => {
assert_eq!(i64::from(x), ax);
assert_eq!(i64::from(y), ay.min(by));
assert_eq!(u64::from(h), (ay - by).unsigned_abs() + 1);
}
other => panic!("unexpected edge: {other:?}"),
}
}
}
/// Explicit, reproducible CPU measurement; no audio hardware or user config.
/// TestBackend includes buffer drawing/diff, but not terminal I/O/emulation.
#[test]
#[ignore = "manual benchmark: cargo test --release benchmark_visualizers -- --ignored --nocapture"]
fn benchmark_visualizers() {
use ratatui::{Terminal, backend::TestBackend};
for script in BUNDLED_SCRIPTS {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), script.source).unwrap();
let mut runtime = ScriptRuntime::default();
for (width, height) in [(80_u16, 24_u16), (160, 50), (240, 80)] {
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
let mut script_times = Vec::new();
let mut frame_times = Vec::new();
let mut max_commands = 0;
for tick in 0..230 {
let mut input = test_input();
insert_int(&mut input, "width", i64::from(width));
insert_int(&mut input, "height", i64::from(height));
let time = f64::from(tick) * 0.05;
insert_float(&mut input, "time", time);
for (i, band) in ["energy", "bass", "mid", "treble", "beat"]
.iter()
.enumerate()
{
insert_float(&mut input, band, (time * (i + 1) as f64).sin() * 0.5 + 0.5);
}
let started = Instant::now();
let commands = runtime.render(file.path(), input).unwrap();
let script_elapsed = started.elapsed();
terminal
.draw(|frame| render_commands(frame, frame.area(), &commands))
.unwrap();
if tick >= 30 {
script_times.push(script_elapsed.as_secs_f64() * 1000.0);
frame_times.push(started.elapsed().as_secs_f64() * 1000.0);
max_commands = max_commands.max(commands.len());
}
}
script_times.sort_by(f64::total_cmp);
frame_times.sort_by(f64::total_cmp);
println!(
"{} {width}x{height}: script p95={:.3}ms; frame median={:.3}ms p95={:.3}ms max={:.3}ms; commands<={max_commands}",
script.id,
script_times[189],
frame_times[99],
frame_times[189],
frame_times[199]
);
if script.id == "morphing_cube" && width == 80 {
for row in terminal
.backend()
.buffer()
.content
.chunks(usize::from(width))
{
println!(
"{}",
row.iter().map(|cell| cell.symbol()).collect::<String>()
);
}
}
}
}
}
}
@@ -0,0 +1,57 @@
// name: Status braille histogram
// protocol: furumi-visualizer-v2
// surface: status
//
// Always-on, one-row visualization. Edit this file to customize it; saved
// changes reload during playback. The host never overwrites an existing file.
// Same render(input) and draw commands as fullscreen scripts; height is 1.
// Audio bands and waveform amplitudes drive the bars (not a full FFT).
// Each Braille character packs two independent four-dot vertical columns.
// "default" background retains the terminal's background color.
// A method reads the waveform through `this`, avoiding an array copy for
// every column in this continuously running visualization.
fn level(index, columns, band, energy, beat) {
let wave = 0.0;
let count = this.len();
if count > 0 {
let start = index * count / columns;
let end = (index + 1) * count / columns;
let total = 0;
for i in start..end {
wave += abs(this[i]);
total += 1;
}
if total > 0 { wave /= to_float(total); }
else { wave = abs(this[start]); }
}
let value = band * 0.55 + wave * 0.8 + energy * 0.12 + beat * 0.18;
if value <= 0.01 { 0 }
else if value < 0.20 { 1 }
else if value < 0.40 { 2 }
else if value < 0.65 { 3 }
else { 4 }
}
fn render(input) {
let commands = [#{ op: "clear", bg: "default" }];
if input.width <= 0 || input.height <= 0 || input.paused { return commands; }
// Lookup table indexed by left/right bar heights, from the bottom up.
let dots = ["⠀⢀⢠⢰⢸", "⡀⣀⣠⣰⣸", "⡄⣄⣤⣴⣼", "⡆⣆⣦⣶⣾", "⡇⣇⣧⣷⣿"];
let columns = input.width * 2;
let samples = input.samples;
for x in 0..input.width {
let levels = [];
for side in 0..2 {
let index = x * 2 + side;
let phase = to_float(index) / to_float(columns);
let band = if phase < 0.33 { input.bass }
else if phase < 0.67 { input.mid } else { input.treble };
levels.push(samples.level(index, columns, band, input.energy, input.beat));
}
let glyph = dots[levels[0]].sub_string(levels[1], 1);
commands.push(#{ op: "cell", x: x, y: 0, ch: glyph,
fg: 0x48c9c0, bg: "default" });
}
commands
}
+583
View File
@@ -0,0 +1,583 @@
//! One-row surface: blocking preparation runs off the UI thread; views copy
//! only the prepared buffer. Uses the fullscreen engine and drawing commands.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use ratatui::{
Frame,
buffer::Buffer,
layout::Rect,
style::{Color, Style},
widgets::Paragraph,
};
use tokio::sync::mpsc;
use unicode_width::UnicodeWidthStr;
use super::{
ScriptRuntime, features_from_state, input_map_with_features, render_commands_to_buffer,
};
use crate::app::{event::AppEvent, state::AppState};
const SOURCE: &str = include_str!("../visualizations/status/braille.rhai");
const LEGACY_SOURCE: &str = include_str!("fixtures/status_braille_v1.rhai");
pub fn script_path() -> anyhow::Result<PathBuf> {
Ok(super::visualizations_dir()?
.join("status")
.join("braille.rhai"))
}
pub(super) fn ensure_script() -> anyhow::Result<()> {
install_script_at(&script_path()?)
}
fn install_script_at(path: &Path) -> anyhow::Result<()> {
ensure_script_at(path)?;
// Upgrade only a byte-for-byte stock script, never a user's edited one.
if std::fs::metadata(path)?.len() == LEGACY_SOURCE.len() as u64
&& std::fs::read(path)? == LEGACY_SOURCE.as_bytes()
{
let mut replacement =
tempfile::NamedTempFile::new_in(path.parent().unwrap_or(Path::new(".")))?;
replacement.write_all(SOURCE.as_bytes())?;
replacement.as_file().sync_all()?;
if std::fs::read(path)? == LEGACY_SOURCE.as_bytes() {
replacement.persist(path)?;
}
}
Ok(())
}
fn ensure_script_at(path: &Path) -> anyhow::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
{
Ok(mut file) => file.write_all(SOURCE.as_bytes())?,
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(err) => return Err(err.into()),
}
Ok(())
}
pub fn visible(state: &AppState) -> bool {
state.player.playing && state.player.current.is_some() && state.device_playback.is_audio_owner()
}
pub fn playing(state: &AppState) -> bool {
visible(state) && !state.player.paused
}
fn source_input(width: u16, state: &AppState, elapsed: f64) -> rhai::Map {
// AnalyzedSource taps decoded audio before rodio's output volume. Keep
// those source levels intact; input.volume remains available as metadata.
let mut features = features_from_state(state, false);
features.elapsed_secs = elapsed;
input_map_with_features(Rect::new(0, 0, width, 1), state, features)
}
#[derive(Debug, Default)]
pub struct State {
target: Option<(u16, String)>,
generation: u64,
frame: Option<Buffer>,
error: Option<String>,
paused: bool,
}
impl State {
/// Invalidates in-flight results. A resize keeps the last frame until a
/// replacement arrives, including when playback is paused.
pub fn set_target(&mut self, target: Option<(u16, String)>) {
if self.target != target {
let same_track = self
.target
.as_ref()
.zip(target.as_ref())
.is_some_and(|(old, new)| old.1 == new.1);
self.target = target;
self.generation = self.generation.wrapping_add(1);
if !same_track {
self.frame = None;
}
self.error = None;
}
}
pub fn set_paused(&mut self, paused: bool) {
if self.paused != paused {
self.paused = paused;
self.generation = self.generation.wrapping_add(1);
}
}
pub fn apply(&mut self, ready: Ready) {
if ready.generation != self.generation || self.target.is_none() || self.paused {
return;
}
match ready.result {
Ok(frame) => {
self.frame = Some(frame);
self.error = None;
}
Err(error) => {
if self.error.as_ref() != Some(&error) {
tracing::warn!(%error, "status visualization failed");
}
self.frame = None;
self.error = Some(error);
}
}
}
pub fn draw(&self, frame: &mut Frame, area: Rect) {
if area.is_empty() {
return;
}
if let Some(buffer) = &self.frame {
if buffer.area.width == 0 {
return;
}
for x in 0..area.width {
let source_x =
usize::from(x) * usize::from(buffer.area.width) / usize::from(area.width);
if let Some(target) = frame.buffer_mut().cell_mut((area.x + x, area.y)) {
*target = buffer.content[source_x].clone();
}
}
} else if let Some(error) = &self.error {
frame.render_widget(
Paragraph::new(format!("viz: {error}")).style(Style::new().fg(Color::Red)),
area,
);
}
}
}
#[derive(Debug)]
pub struct Ready {
generation: u64,
result: Result<Buffer, String>,
}
/// One in-flight job at most: slow custom scripts drop ticks, never queue
/// frames or block input. AST caches are independent of fullscreen selection.
pub struct Renderer {
runtime: Arc<Mutex<ScriptRuntime>>,
started: Instant,
pub busy: bool,
}
impl Default for Renderer {
fn default() -> Self {
let mut runtime = ScriptRuntime::default();
runtime
.engine
.set_max_operations(200_000)
.set_max_array_size(8192)
.set_max_map_size(4096)
.set_max_string_size(32_768);
Self {
runtime: Arc::new(Mutex::new(runtime)),
started: Instant::now(),
busy: false,
}
}
}
impl Renderer {
pub fn request(&mut self, state: &AppState, tx: mpsc::UnboundedSender<AppEvent>) {
let Some((width, _)) = &state.status_visualizer.target else {
return;
};
if self.busy || !playing(state) || state.visualizer.active {
return;
}
self.busy = true;
let width = *width;
let generation = state.status_visualizer.generation;
let input = source_input(width, state, self.started.elapsed().as_secs_f64());
let runtime = Arc::clone(&self.runtime);
tokio::spawn(async move {
let result = tokio::task::spawn_blocking(move || {
let path = script_path().map_err(|e| e.to_string())?;
let mut runtime = runtime
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if runtime.cached_path.is_none() {
// Retry initialization after a transient startup error.
install_script_at(&path).map_err(|e| e.to_string())?;
}
prepare(&mut runtime, &path, input, width)
})
.await
.unwrap_or_else(|err| Err(err.to_string()));
let _ = tx.send(AppEvent::StatusVisualizationReady(Ready {
generation,
result,
}));
});
}
}
fn prepare(
runtime: &mut ScriptRuntime,
path: &Path,
input: rhai::Map,
width: u16,
) -> Result<Buffer, String> {
if std::fs::metadata(path).map_err(|e| e.to_string())?.len() > 65_536 {
return Err("status script exceeds 64 KiB".into());
}
let commands = runtime.render(path, input)?;
if commands.len() > 4096 {
return Err("too many status drawing commands".into());
}
let area = Rect::new(0, 0, width, 1);
let mut buffer = Buffer::empty(area);
render_commands_to_buffer(&mut buffer, area, &commands);
// A user-supplied cell string must never spill into neighboring UI areas.
for cell in &mut buffer.content {
if cell.symbol().width() != 1 || cell.symbol().chars().any(char::is_control) {
cell.set_symbol(" ");
}
}
Ok(buffer)
}
#[cfg(test)]
mod tests {
use super::super::insert_float;
use super::*;
use ratatui::{Terminal, backend::TestBackend};
use rhai::{Array, Dynamic};
fn input(width: u16, level: f64) -> rhai::Map {
let mut input = source_input(width, &AppState::default(), 0.0);
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, level);
}
input.insert(
"samples".into(),
(0..256)
.map(|index| {
Dynamic::from_float(level * (index as f64 * std::f64::consts::TAU / 64.0).sin())
})
.collect::<Array>()
.into(),
);
input
}
#[test]
fn histogram_uses_braille_and_real_levels_in_one_row() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("status/braille.rhai");
ensure_script_at(&path).unwrap();
let renderer = Renderer::default();
let mut runtime = renderer.runtime.lock().unwrap();
for width in [0, 1, 8, 60, 200] {
let quiet = prepare(&mut runtime, &path, input(width, 0.0), width).unwrap();
let loud = prepare(&mut runtime, &path, input(width, 1.0), width).unwrap();
assert_eq!(loud.area, Rect::new(0, 0, width, 1));
assert!(quiet.content.iter().all(|cell| cell.symbol() == "⠀"));
assert!(loud.content.iter().all(|cell| {
cell.symbol()
.chars()
.all(|ch| ('\u{2800}'..='\u{28ff}').contains(&ch))
&& cell.bg == Color::Reset
}));
if width > 0 {
assert_ne!(loud, quiet);
}
let mut paused = input(width, 1.0);
paused.insert("paused".into(), true.into());
assert_eq!(prepare(&mut runtime, &path, paused, width).unwrap(), loud);
}
}
#[test]
fn existing_user_script_survives_and_hot_reload_recovers_from_errors() {
let file = tempfile::NamedTempFile::new().unwrap();
let path = file.path();
let mut runtime = ScriptRuntime::default();
for (revision, symbol) in [(1, "A"), (2, "B"), (3, "bad"), (4, "C")] {
let source = if symbol == "bad" {
"fn render(".into()
} else {
format!(
"fn render(input) {{ [#{{ op: \"text\", x: 0, y: 0, text: \"{symbol}\" }}] }}"
)
};
std::fs::write(path, &source).unwrap();
file.as_file()
.set_times(std::fs::FileTimes::new().set_modified(
std::time::UNIX_EPOCH
+ std::time::Duration::from_secs(1_700_000_000 + revision),
))
.unwrap();
install_script_at(path).unwrap();
assert_eq!(std::fs::read_to_string(path).unwrap(), source);
let frame = prepare(&mut runtime, path, input(8, 0.0), 8);
if symbol == "bad" {
assert!(frame.is_err());
} else {
assert_eq!(frame.unwrap().content[0].symbol(), symbol);
}
}
}
#[test]
fn status_commands_are_clipped_and_cannot_spill_into_the_ui() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
file.path(),
r##"fn render(input) { [
#{ op: "rect", x: 0, y: 0, w: 65535, h: 65535, ch: "#" },
#{ op: "text", x: 0, y: 1, text: "outside" },
#{ op: "trace", x: 6, ys: [65535, 0, 65535], ch: "*" },
#{ op: "cell", x: 0, y: 0, ch: "界" },
#{ op: "cell", x: 1, y: 0, ch: "\n" },
#{ op: "cell", x: 2, y: 0, ch: "too long" }
] }"##,
)
.unwrap();
let buffer = prepare(&mut ScriptRuntime::default(), file.path(), input(8, 0.0), 8).unwrap();
assert!(buffer.content[..3].iter().all(|cell| cell.symbol() == " "));
let state = State {
frame: Some(buffer),
..State::default()
};
let mut terminal = Terminal::new(TestBackend::new(20, 4)).unwrap();
terminal
.draw(|frame| {
for cell in &mut frame.buffer_mut().content {
cell.set_symbol("x");
}
state.draw(frame, Rect::new(11, 3, 8, 1));
})
.unwrap();
let buffer = terminal.backend().buffer();
for y in 0..4 {
for x in 0..20 {
if y != 3 || !(11..19).contains(&x) {
assert_eq!(buffer[(x, y)].symbol(), "x");
}
}
}
}
#[test]
fn stale_frames_are_discarded_after_resize_track_change_or_stop() {
let mut state = State::default();
state.set_target(Some((8, "track-a".into())));
let generation = state.generation;
state.apply(Ready {
generation,
result: Ok(Buffer::empty(Rect::new(0, 0, 8, 1))),
});
assert!(state.frame.is_some());
for target in [
Some((12, "track-a".into())),
Some((12, "track-b".into())),
None,
] {
state.set_target(target);
let previous_frame = state.frame.clone();
state.apply(Ready {
generation,
result: Ok(Buffer::empty(Rect::new(0, 0, 8, 1))),
});
assert_eq!(state.frame, previous_frame);
}
assert!(state.frame.is_none());
}
#[test]
fn pause_freezes_the_last_frame_and_rejects_in_flight_work() {
let mut state = State::default();
state.set_target(Some((8, "track".into())));
let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 1));
for cell in &mut buffer.content {
cell.set_symbol("⣤");
}
let generation = state.generation;
state.apply(Ready {
generation,
result: Ok(buffer.clone()),
});
state.set_paused(true);
state.apply(Ready {
generation,
result: Err("late error".into()),
});
state.apply(Ready {
generation: state.generation,
result: Ok(Buffer::empty(buffer.area)),
});
assert_eq!(state.frame.as_ref(), Some(&buffer));
// A paused resize adapts the frozen row instead of erasing it.
state.set_target(Some((12, "track".into())));
let mut terminal = Terminal::new(TestBackend::new(12, 1)).unwrap();
terminal
.draw(|frame| state.draw(frame, frame.area()))
.unwrap();
assert!(
terminal
.backend()
.buffer()
.content
.iter()
.all(|cell| cell.symbol() == "⣤")
);
let paused_generation = state.generation;
state.set_paused(false);
state.apply(Ready {
generation: paused_generation,
result: Err("stale pause".into()),
});
assert_eq!(state.frame.as_ref(), Some(&buffer));
state.apply(Ready {
generation: state.generation,
result: Ok(Buffer::empty(Rect::new(0, 0, 12, 1))),
});
assert_ne!(state.frame.as_ref(), Some(&buffer));
state.set_target(None);
assert!(state.frame.is_none());
}
#[test]
fn source_audio_input_is_independent_of_output_volume_and_pause() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), SOURCE).unwrap();
let mut state = AppState::default();
state.player.audio_analysis = crate::player::AudioAnalysisSnapshot {
energy: 0.8,
bass: 0.9,
mid: 0.6,
treble: 0.3,
beat: 0.5,
scope: (0..256).map(|i| (i as f64 * 0.13).sin() * 0.7).collect(),
..Default::default()
};
let mut runtime = ScriptRuntime::default();
let expected =
prepare(&mut runtime, file.path(), source_input(64, &state, 1.0), 64).unwrap();
for volume in [0, 1, 25, 80, 100] {
for paused in [false, true] {
state.player.volume = volume;
state.player.paused = paused;
let map = source_input(64, &state, 1.0);
for (key, level) in [
("energy", 0.8),
("bass", 0.9),
("mid", 0.6),
("treble", 0.3),
("beat", 0.5),
] {
assert_eq!(map[key].as_float().unwrap(), level);
}
assert_eq!(map["volume"].as_float().unwrap(), f64::from(volume) / 100.0);
assert_eq!(
prepare(&mut runtime, file.path(), map, 64).unwrap(),
expected
);
}
}
}
#[test]
fn loud_recordings_use_multiple_heights_instead_of_a_solid_row() {
let file = tempfile::NamedTempFile::new().unwrap();
let mut runtime = ScriptRuntime::default();
std::fs::write(file.path(), LEGACY_SOURCE).unwrap();
let old = prepare(&mut runtime, file.path(), input(64, 1.0), 64).unwrap();
assert!(old.content.iter().all(|cell| cell.symbol() == "⣿"));
install_script_at(file.path()).unwrap();
// A fresh runtime also models a restart installing the new default.
let mut runtime = ScriptRuntime::default();
let new = prepare(&mut runtime, file.path(), input(64, 1.0), 64).unwrap();
let symbols: std::collections::HashSet<_> =
new.content.iter().map(|cell| cell.symbol()).collect();
assert!(symbols.len() >= 4, "{symbols:?}");
assert!(
new.content
.iter()
.filter(|cell| cell.symbol() == "⣿")
.count()
< 32
);
assert!(new.content.iter().any(|cell| cell.symbol() == "⠀"));
// Compressed band/beat values alone must not create a filled baseline.
let mut silence = input(64, 1.0);
silence.insert(
"samples".into(),
(0..256)
.map(|_| Dynamic::from_float(0.001))
.collect::<Array>()
.into(),
);
let silent = prepare(&mut runtime, file.path(), silence, 64).unwrap();
assert!(silent.content.iter().all(|cell| cell.symbol() == "⠀"));
}
#[test]
fn only_the_untouched_previous_default_is_upgraded() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), LEGACY_SOURCE).unwrap();
install_script_at(file.path()).unwrap();
assert_eq!(std::fs::read_to_string(file.path()).unwrap(), SOURCE);
install_script_at(file.path()).unwrap();
assert_eq!(std::fs::read_to_string(file.path()).unwrap(), SOURCE);
for stock in [LEGACY_SOURCE, SOURCE] {
let custom = format!("{stock}\n// user customization\n");
std::fs::write(file.path(), &custom).unwrap();
install_script_at(file.path()).unwrap();
assert_eq!(std::fs::read_to_string(file.path()).unwrap(), custom);
}
}
#[test]
fn status_script_infinite_loop_hits_the_operation_limit() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), "fn render(input) { loop {} [] }").unwrap();
let renderer = Renderer::default();
let mut runtime = renderer.runtime.lock().unwrap();
let err = prepare(&mut runtime, file.path(), input(8, 0.0), 8).unwrap_err();
assert!(err.contains("operations"), "{err}");
}
#[test]
#[ignore = "manual benchmark: cargo test --release benchmark_status_visualizer -- --ignored --nocapture"]
fn benchmark_status_visualizer() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), SOURCE).unwrap();
let renderer = Renderer::default();
let mut runtime = renderer.runtime.lock().unwrap();
for width in [32, 64, 128] {
let mut times = Vec::new();
for tick in 0..230 {
let level = (f64::from(tick) * 0.13).sin() * 0.5 + 0.5;
let input = input(width, level);
let start = Instant::now();
let frame = prepare(&mut runtime, file.path(), input, width).unwrap();
std::hint::black_box(frame);
if tick >= 30 {
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
}
times.sort_by(f64::total_cmp);
println!(
"status {width}x1: median={:.3}ms p95={:.3}ms max={:.3}ms",
times[99], times[189], times[199]
);
}
}
}