From 23efdbd563e7cbd460080fe1d17c87e3de8c882a Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:14:58 -0400 Subject: [PATCH 01/12] feat: load validated configuration with Figment --- Cargo.lock | 164 +++++++++++- Cargo.toml | 9 +- README.md | 48 +++- src/config.rs | 573 ++++++++++++++++++++++++++++++++++++++++++ src/downloader.rs | 8 +- src/main.rs | 11 +- src/player.rs | 11 +- src/ui/environment.rs | 8 +- src/ui/init.rs | 13 +- src/ui/input.rs | 179 +++++++++---- src/ui/interface.rs | 16 +- 11 files changed, 958 insertions(+), 82 deletions(-) create mode 100644 src/config.rs diff --git a/Cargo.lock b/Cargo.lock index a205110..210efa2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -229,6 +229,15 @@ dependencies = [ "syn", ] +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -866,6 +875,22 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "figment" +version = "0.10.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" +dependencies = [ + "atomic", + "parking_lot", + "pear", + "serde", + "tempfile", + "toml", + "uncased", + "version_check", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1345,6 +1370,12 @@ dependencies = [ "web-time", ] +[[package]] +name = "inlinable_string" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" + [[package]] name = "ipnet" version = "2.12.0" @@ -1530,6 +1561,7 @@ dependencies = [ "dirs", "eyre", "fastrand", + "figment", "futures-util", "html-escape", "indicatif", @@ -1892,6 +1924,29 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pear" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" +dependencies = [ + "inlinable_string", + "pear_codegen", + "yansi", +] + +[[package]] +name = "pear_codegen" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" +dependencies = [ + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -2024,7 +2079,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit", + "toml_edit 0.25.12+spec-1.1.0", ] [[package]] @@ -2036,6 +2091,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "version_check", + "yansi", +] + [[package]] name = "quinn" version = "0.11.9" @@ -2514,6 +2582,15 @@ dependencies = [ "syn", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "servo_arc" version = "0.4.3" @@ -2977,6 +3054,27 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + [[package]] name = "toml_datetime" version = "1.1.1+spec-1.1.0" @@ -2986,6 +3084,20 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + [[package]] name = "toml_edit" version = "0.25.12+spec-1.1.0" @@ -2993,9 +3105,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7" dependencies = [ "indexmap", - "toml_datetime", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", - "winnow", + "winnow 1.0.3", ] [[package]] @@ -3004,9 +3116,15 @@ version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ - "winnow", + "winnow 1.0.3", ] +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tower" version = "0.5.3" @@ -3111,6 +3229,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + [[package]] name = "unicode-ident" version = "1.0.24" @@ -3188,6 +3315,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "walkdir" version = "2.5.0" @@ -3703,6 +3836,15 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "1.0.3" @@ -3724,6 +3866,12 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + [[package]] name = "yoke" version = "0.8.3" @@ -3776,7 +3924,7 @@ dependencies = [ "uds_windows", "uuid", "windows-sys 0.61.2", - "winnow", + "winnow 1.0.3", "zbus_macros", "zbus_names", "zvariant", @@ -3804,7 +3952,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7074f3e50b894eac91750142016d30d0a89be8e67dbfd9704fb875825760e52d" dependencies = [ "serde", - "winnow", + "winnow 1.0.3", "zvariant", ] @@ -3903,7 +4051,7 @@ dependencies = [ "endi", "enumflags2", "serde", - "winnow", + "winnow 1.0.3", "zvariant_derive", "zvariant_utils", ] @@ -3931,5 +4079,5 @@ dependencies = [ "quote", "serde", "syn", - "winnow", + "winnow 1.0.3", ] diff --git a/Cargo.toml b/Cargo.toml index d2b7b4b..a02feda 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,6 @@ mpris = ["dep:mpris-server", "dep:arc-swap"] media-controls = ["dep:souvlaki", "dep:windows"] extra-audio-formats = ["rodio/default"] scrape = [ - "dep:serde", "dep:serde_json", "dep:html-escape", "dep:scraper", @@ -38,6 +37,8 @@ clap = { version = "4.5.61", features = ["derive", "cargo"] } eyre = "0.6.12" fastrand = "2.4.1" thiserror = "2.0.18" +figment = { version = "0.10.19", default-features = false, features = ["env", "toml"] } +serde = { version = "1.0.228", features = ["derive"] } # Async tokio = { version = "1.52.3", features = ["macros", "rt", "fs", "io-util", "sync", "time"], default-features = false } @@ -60,12 +61,14 @@ unicode-segmentation = "1.12.0" url = { version = "2.5.8", default-features = false } # Scraper -serde = { version = "1.0.228", features = ["derive"], optional = true } serde_json = { version = "1.0.150", optional = true } scraper = { version = "0.27.0", optional = true } html-escape = { version = "0.2.13", optional = true } indicatif = { version = "0.18.4", optional = true } +[dev-dependencies] +figment = { version = "0.10.19", default-features = false, features = ["env", "toml", "test"] } + [target.'cfg(target_os = "linux")'.dependencies] libc = "0.2.186" @@ -76,4 +79,4 @@ windows = { version = "0.62", optional = true, features = [ "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_WindowsAndMessaging", -] } \ No newline at end of file +] } diff --git a/README.md b/README.md index 095f2b5..dacf6a6 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ slightly tweak the UI or behavior of the menu. The flags can be viewed with `low | `-c`, `--clock` | Include a clock | | `-p`, `--paused` | Start lowfi paused | | `-f`, `--fps` | FPS of the UI [default: 12] | -| `--timeout` | Timeout in seconds for music downloads [default: 3] | +| `--timeout` | Timeout in seconds for music downloads [default: 16] | | `-d`, `--debug` | Include ALSA & other logs meant for debugging | | `-w`, `--width ` | Width of the player, from 0 to 32 [default: 3] | | `-t`, `--track-list ` | Use a [custom track list](#custom-track-lists) | @@ -192,6 +192,52 @@ slightly tweak the UI or behavior of the menu. The flags can be viewed with `low If you need something even more specific, see [ENVIRONMENT_VARS](./docs/ENVIRONMENT_VARS.md). +### Configuration + +Lowfi also reads an optional `config.toml` from its platform data directory: +`~/.local/share/lowfi/config.toml` on Linux, `%APPDATA%\\lowfi\\config.toml` on +Windows, and `~/Library/Application Support/lowfi/config.toml` on macOS. It never +creates or overwrites this file. + +Settings are resolved in this order: built-in defaults, `config.toml`, `LOWFI_*` +environment variables, then explicitly supplied command-line flags. Environment +variables use `LOWFI_
__` names, such as `LOWFI_UI__FPS=20`, +`LOWFI_PLAYBACK__PAUSED=false`, or `LOWFI_BINDINGS__NEXT='["n", "x"]'`. + +```toml +[playback] +paused = false +track_list = "chillhop" +buffer_size = 5 +timeout = 16 +debug = false + +[ui] +alternate = false +minimalist = false +borderless = false +clock = false +fps = 12 +width = 3 + +[bindings] +play_pause = ["p", "Space"] +next = ["s", "n", "l"] +quit = ["q"] +bookmark = ["b"] +volume_up = ["+", "=", "k", "Up"] +volume_down = ["-", "_", "j", "Down"] +volume_up_fine = ["Right"] +volume_down_fine = ["Left"] +``` + +Bindings accept one printable character, `Space`, `Up`, `Down`, `Left`, and +`Right`; names are case-insensitive. Supplying a binding list replaces that +action's defaults, while an empty list disables that action's configurable keys. +`Ctrl+C` remains reserved for quitting. Invalid values, unknown fields, and +duplicate keys stop startup with an error that identifies the field and source. +The terminal's small control hints continue to show the default keys. + ### Extra Features lowfi uses cargo/rust's "feature" system to make certain parts of the program optional, diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..d0bb806 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,573 @@ +//! Loading and validating Lowfi's user configuration. + +use std::{ + collections::HashMap, + path::{Path, PathBuf}, +}; + +use crossterm::event::KeyCode; +use figment::{ + providers::{Env, Format, Serialized, Toml}, + Figment, +}; +use serde::{Deserialize, Serialize}; + +use crate::Message; + +/// Fully resolved application settings. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Settings { + pub playback: Playback, + pub ui: Ui, + pub bindings: Bindings, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Playback { + pub paused: bool, + pub track_list: String, + pub buffer_size: u32, + pub timeout: u64, + pub debug: bool, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Ui { + pub alternate: bool, + pub minimalist: bool, + pub borderless: bool, + pub clock: bool, + pub fps: u8, + pub width: usize, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Bindings { + pub play_pause: Vec, + pub next: Vec, + pub quit: Vec, + pub bookmark: Vec, + pub volume_up: Vec, + pub volume_down: Vec, + pub volume_up_fine: Vec, + pub volume_down_fine: Vec, +} + +impl Default for Settings { + fn default() -> Self { + Self { + playback: Playback { + paused: false, + track_list: "chillhop".into(), + buffer_size: 5, + timeout: 16, + debug: false, + }, + ui: Ui { + alternate: false, + minimalist: false, + borderless: false, + clock: false, + fps: 12, + width: 3, + }, + bindings: Bindings { + play_pause: vec!["p".into(), "Space".into()], + next: vec!["s".into(), "n".into(), "l".into()], + quit: vec!["q".into()], + bookmark: vec!["b".into()], + volume_up: vec!["+".into(), "=".into(), "k".into(), "Up".into()], + volume_down: vec!["-".into(), "_".into(), "j".into(), "Down".into()], + volume_up_fine: vec!["Right".into()], + volume_down_fine: vec!["Left".into()], + }, + } + } +} + +/// CLI values that were explicitly supplied, excluding Clap defaults. +#[derive(Default, Serialize)] +pub struct CliOverrides { + #[serde(skip_serializing_if = "Option::is_none")] + playback: Option, + #[serde(skip_serializing_if = "Option::is_none")] + ui: Option, +} + +#[derive(Default, Serialize)] +struct PlaybackOverrides { + #[serde(skip_serializing_if = "Option::is_none")] + paused: Option, + #[serde(skip_serializing_if = "Option::is_none")] + track_list: Option, + #[serde(skip_serializing_if = "Option::is_none")] + buffer_size: Option, + #[serde(skip_serializing_if = "Option::is_none")] + timeout: Option, + #[serde(skip_serializing_if = "Option::is_none")] + debug: Option, +} + +#[derive(Default, Serialize)] +struct UiOverrides { + #[serde(skip_serializing_if = "Option::is_none")] + alternate: Option, + #[serde(skip_serializing_if = "Option::is_none")] + minimalist: Option, + #[serde(skip_serializing_if = "Option::is_none")] + borderless: Option, + #[serde(skip_serializing_if = "Option::is_none")] + clock: Option, + #[serde(skip_serializing_if = "Option::is_none")] + fps: Option, + #[serde(skip_serializing_if = "Option::is_none")] + width: Option, +} + +impl CliOverrides { + pub fn from_args(args: &crate::Args, matches: &clap::ArgMatches) -> Self { + use clap::parser::ValueSource; + let supplied = |name| matches.value_source(name) == Some(ValueSource::CommandLine); + + let playback = PlaybackOverrides { + paused: supplied("paused").then_some(args.paused), + track_list: supplied("track_list").then(|| args.track_list.clone()), + buffer_size: supplied("buffer_size").then_some(args.buffer_size), + timeout: supplied("timeout").then_some(args.timeout), + debug: supplied("debug").then_some(args.debug), + }; + let ui = UiOverrides { + alternate: supplied("alternate").then_some(args.alternate), + minimalist: supplied("minimalist").then_some(args.minimalist), + borderless: supplied("borderless").then_some(args.borderless), + clock: supplied("clock").then_some(args.clock), + fps: supplied("fps").then_some(args.fps), + width: supplied("width").then_some(args.width), + }; + + Self { + playback: (playback.paused.is_some() + || playback.track_list.is_some() + || playback.buffer_size.is_some() + || playback.timeout.is_some() + || playback.debug.is_some()) + .then_some(playback), + ui: (ui.alternate.is_some() + || ui.minimalist.is_some() + || ui.borderless.is_some() + || ui.clock.is_some() + || ui.fps.is_some() + || ui.width.is_some()) + .then_some(ui), + } + } +} + +/// Maps terminal keys to their configured messages. +#[derive(Clone, Debug)] +pub struct BindingMap(HashMap); + +impl BindingMap { + pub fn message(&self, key: &KeyCode) -> Option { + self.0.get(key).copied() + } +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("could not read configuration {path}: {source}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("invalid configuration: {0}")] + Figment(#[from] figment::Error), + #[error("invalid configuration field `{field}` from {origin}: {reason}")] + Invalid { + field: String, + origin: String, + reason: String, + }, +} + +/// Loads settings from defaults, an optional exact TOML file, environment, and CLI overrides. +pub fn load(path: &Path, cli: CliOverrides) -> Result<(Settings, BindingMap), Error> { + let exists = path.try_exists().map_err(|source| Error::Read { + path: path.into(), + source, + })?; + if exists && !path.is_file() { + return Err(Error::Read { + path: path.into(), + source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a regular file"), + }); + } + + let mut figment = Figment::from(Serialized::defaults(Settings::default())); + if exists { + figment = figment.merge(Toml::file_exact(path)); + } + let figment = figment + .merge(Env::prefixed("LOWFI_").split("__")) + .merge(Serialized::defaults(cli)); + let settings: Settings = figment.extract()?; + + validate_settings(&settings, &figment, path)?; + let bindings = BindingMap::compile(&settings.bindings, &figment, path)?; + Ok((settings, bindings)) +} + +fn validate_settings(settings: &Settings, figment: &Figment, path: &Path) -> Result<(), Error> { + if settings.ui.fps == 0 { + return Err(invalid("ui.fps", "must be at least 1", figment, path)); + } + if settings.playback.buffer_size < 2 { + return Err(invalid( + "playback.buffer_size", + "must be at least 2", + figment, + path, + )); + } + Ok(()) +} + +impl BindingMap { + fn compile(bindings: &Bindings, figment: &Figment, path: &Path) -> Result { + let mut keys = HashMap::new(); + let groups = [ + ("play_pause", &bindings.play_pause, Message::PlayPause), + ("next", &bindings.next, Message::Next), + ("quit", &bindings.quit, Message::Quit), + ("bookmark", &bindings.bookmark, Message::Bookmark), + ("volume_up", &bindings.volume_up, Message::ChangeVolume(0.1)), + ( + "volume_down", + &bindings.volume_down, + Message::ChangeVolume(-0.1), + ), + ( + "volume_up_fine", + &bindings.volume_up_fine, + Message::ChangeVolume(0.01), + ), + ( + "volume_down_fine", + &bindings.volume_down_fine, + Message::ChangeVolume(-0.01), + ), + ]; + + for (action, values, message) in groups { + for value in values { + let key = parse_key(value).map_err(|reason| { + invalid(&format!("bindings.{action}"), reason, figment, path) + })?; + if let Some(existing) = keys.insert(key.clone(), message) { + let existing = action_for(existing); + return Err(Error::Invalid { + field: format!("bindings.{action}"), + origin: source_for(&format!("bindings.{action}"), figment, path), + reason: format!("duplicates `{value}` already assigned to `bindings.{existing}` from {}", source_for(&format!("bindings.{existing}"), figment, path)), + }); + } + } + } + Ok(Self(keys)) + } +} + +fn parse_key(value: &str) -> Result { + match value.to_ascii_lowercase().as_str() { + "space" => Ok(KeyCode::Char(' ')), + "up" => Ok(KeyCode::Up), + "down" => Ok(KeyCode::Down), + "left" => Ok(KeyCode::Left), + "right" => Ok(KeyCode::Right), + _ if value.chars().count() == 1 => { + let character = value.chars().next().unwrap(); + if character.is_control() { + Err("control keys and modifier chords are reserved".into()) + } else { + Ok(KeyCode::Char(character.to_ascii_lowercase())) + } + } + _ => Err("expected one printable character, Space, Up, Down, Left, or Right".into()), + } +} + +fn action_for(message: Message) -> &'static str { + match message { + Message::PlayPause => "play_pause", + Message::Next => "next", + Message::Quit => "quit", + Message::Bookmark => "bookmark", + Message::ChangeVolume(change) if change > 0.09 => "volume_up", + Message::ChangeVolume(change) if change < -0.09 => "volume_down", + Message::ChangeVolume(change) if change > 0.0 => "volume_up_fine", + Message::ChangeVolume(_) => "volume_down_fine", + _ => unreachable!("only terminal binding messages are compiled"), + } +} + +fn invalid(field: &str, reason: impl Into, figment: &Figment, path: &Path) -> Error { + Error::Invalid { + field: field.into(), + origin: source_for(field, figment, path), + reason: reason.into(), + } +} + +fn source_for(field: &str, figment: &Figment, path: &Path) -> String { + let metadata = figment.find_metadata(field); + match metadata.map(|metadata| metadata.name.as_ref()) { + Some(name) if name.contains("environment") => { + format!("LOWFI_{}", field.replace('.', "__").to_ascii_uppercase()) + } + Some(name) if name.contains("TOML") => path.display().to_string(), + Some(name) if name.contains("CliOverrides") => format!( + "CLI flag --{}", + field.rsplit('.').next().unwrap().replace('_', "-") + ), + _ => "built-in defaults".into(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::{CommandFactory, Parser}; + use figment::Jail; + + #[test] + fn defaults_preserve_every_existing_binding() { + let path = Path::new("missing.toml"); + let (settings, keys) = load(path, CliOverrides::default()).unwrap(); + assert_eq!(settings, Settings::default()); + assert!(!path.exists()); + for (key, message) in [ + ("p", Message::PlayPause), + (" ", Message::PlayPause), + ("s", Message::Next), + ("n", Message::Next), + ("l", Message::Next), + ("q", Message::Quit), + ("b", Message::Bookmark), + ("+", Message::ChangeVolume(0.1)), + ("=", Message::ChangeVolume(0.1)), + ("k", Message::ChangeVolume(0.1)), + ("-", Message::ChangeVolume(-0.1)), + ("_", Message::ChangeVolume(-0.1)), + ("j", Message::ChangeVolume(-0.1)), + ("Up", Message::ChangeVolume(0.1)), + ("Down", Message::ChangeVolume(-0.1)), + ("Right", Message::ChangeVolume(0.01)), + ("Left", Message::ChangeVolume(-0.01)), + ] { + assert_eq!(keys.message(&parse_key(key).unwrap()), Some(message)); + } + } + + #[test] + fn file_environment_and_cli_precedence() { + Jail::expect_with(|jail| { + jail.create_file("config.toml", "[ui]\nfps = 20\n")?; + assert_eq!( + load(Path::new("config.toml"), CliOverrides::default()) + .unwrap() + .0 + .ui + .fps, + 20 + ); + jail.set_env("LOWFI_UI__FPS", "30"); + assert_eq!( + load(Path::new("config.toml"), CliOverrides::default()) + .unwrap() + .0 + .ui + .fps, + 30 + ); + let cli = CliOverrides { + ui: Some(UiOverrides { + fps: Some(40), + ..UiOverrides::default() + }), + ..CliOverrides::default() + }; + assert_eq!(load(Path::new("config.toml"), cli).unwrap().0.ui.fps, 40); + Ok(()) + }); + } + + #[test] + fn invalid_and_duplicate_bindings_are_rejected() { + Jail::expect_with(|jail| { + jail.create_file("config.toml", "[bindings]\nnext = [\"q\"]\n")?; + let error = load(Path::new("config.toml"), CliOverrides::default()) + .unwrap_err() + .to_string(); + assert!(error.contains("duplicates")); + assert!(error.contains("config.toml")); + Ok(()) + }); + } + + #[test] + fn file_overrides_replace_individual_binding_lists() { + Jail::expect_with(|jail| { + jail.create_file("config.toml", "[bindings]\nnext = [\"x\"]\nbookmark = []\n")?; + let (_, keys) = load(Path::new("config.toml"), CliOverrides::default()).unwrap(); + assert_eq!(keys.message(&parse_key("x").unwrap()), Some(Message::Next)); + assert_eq!(keys.message(&parse_key("s").unwrap()), None); + assert_eq!(keys.message(&parse_key("b").unwrap()), None); + Ok(()) + }); + } + + #[test] + fn invalid_values_identify_their_source() { + Jail::expect_with(|jail| { + jail.create_file("config.toml", "[ui]\nfps = 0\n")?; + let error = load(Path::new("config.toml"), CliOverrides::default()) + .unwrap_err() + .to_string(); + assert!(error.contains("ui.fps")); + assert!(error.contains("config.toml")); + + jail.create_file("small-buffer.toml", "[playback]\nbuffer_size = 1\n")?; + let error = load(Path::new("small-buffer.toml"), CliOverrides::default()) + .unwrap_err() + .to_string(); + assert!(error.contains("playback.buffer_size")); + assert!(error.contains("small-buffer.toml")); + + jail.set_env("LOWFI_PLAYBACK__BUFFER_SIZE", "1"); + let error = load(Path::new("missing.toml"), CliOverrides::default()) + .unwrap_err() + .to_string(); + assert!(error.contains("LOWFI_PLAYBACK__BUFFER_SIZE")); + Ok(()) + }); + } + + #[test] + fn malformed_unknown_and_reserved_bindings_fail() { + Jail::expect_with(|jail| { + jail.create_file("bad.toml", "[ui\nfps = 10")?; + assert!(load(Path::new("bad.toml"), CliOverrides::default()).is_err()); + + jail.create_file("unknown.toml", "[ui]\nnot_a_setting = true")?; + assert!(load(Path::new("unknown.toml"), CliOverrides::default()).is_err()); + + jail.create_file("reserved.toml", "[bindings]\nquit = [\"Ctrl+C\"]")?; + assert!(load(Path::new("reserved.toml"), CliOverrides::default()).is_err()); + Ok(()) + }); + } + + #[test] + fn only_explicit_cli_values_override_configuration() { + Jail::expect_with(|jail| { + jail.create_file( + "config.toml", + "[playback]\npaused = false\ntrack_list = \"from-file\"\nbuffer_size = 2\ntimeout = 1\ndebug = false\n\n[ui]\nalternate = false\nminimalist = false\nborderless = false\nclock = false\nfps = 7\nwidth = 1\n", + )?; + + let args = crate::Args::try_parse_from(["lowfi"]).unwrap(); + let matches = crate::Args::command() + .try_get_matches_from(["lowfi"]) + .unwrap(); + let overrides = CliOverrides::from_args(&args, &matches); + assert_eq!( + load(Path::new("config.toml"), overrides).unwrap().0.ui.fps, + 7 + ); + + let load_cli = |arguments: &[&str]| { + let args = crate::Args::try_parse_from(arguments).unwrap(); + let matches = crate::Args::command() + .try_get_matches_from(arguments) + .unwrap(); + load( + Path::new("config.toml"), + CliOverrides::from_args(&args, &matches), + ) + .unwrap() + .0 + }; + + assert!(load_cli(&["lowfi", "--paused"]).playback.paused); + assert_eq!( + load_cli(&["lowfi", "--track-list", "from-cli"]) + .playback + .track_list, + "from-cli" + ); + assert_eq!( + load_cli(&["lowfi", "--buffer-size", "8"]) + .playback + .buffer_size, + 8 + ); + assert_eq!(load_cli(&["lowfi", "--timeout", "42"]).playback.timeout, 42); + assert!(load_cli(&["lowfi", "--debug"]).playback.debug); + assert!(load_cli(&["lowfi", "--alternate"]).ui.alternate); + assert!(load_cli(&["lowfi", "--minimalist"]).ui.minimalist); + assert!(load_cli(&["lowfi", "--borderless"]).ui.borderless); + assert!(load_cli(&["lowfi", "--clock"]).ui.clock); + assert_eq!(load_cli(&["lowfi", "--fps", "17"]).ui.fps, 17); + assert_eq!(load_cli(&["lowfi", "--width", "9"]).ui.width, 9); + Ok(()) + }); + } + + #[test] + fn binding_action_names_cover_every_binding_message() { + for (message, expected) in [ + (Message::PlayPause, "play_pause"), + (Message::Next, "next"), + (Message::Quit, "quit"), + (Message::Bookmark, "bookmark"), + (Message::ChangeVolume(0.1), "volume_up"), + (Message::ChangeVolume(0.09), "volume_up_fine"), + (Message::ChangeVolume(-0.1), "volume_down"), + (Message::ChangeVolume(-0.09), "volume_down_fine"), + (Message::ChangeVolume(0.01), "volume_up_fine"), + (Message::ChangeVolume(-0.01), "volume_down_fine"), + (Message::ChangeVolume(0.0), "volume_down_fine"), + ] { + assert_eq!(action_for(message), expected); + } + } + + #[test] + fn invalid_cli_values_identify_the_cli_flag_as_the_source() { + let args = crate::Args::try_parse_from(["lowfi", "--fps", "0"]).unwrap(); + let matches = crate::Args::command() + .try_get_matches_from(["lowfi", "--fps", "0"]) + .unwrap(); + let error = load( + Path::new("missing.toml"), + CliOverrides::from_args(&args, &matches), + ) + .unwrap_err() + .to_string(); + assert!(error.contains("CLI flag --fps")); + } + + #[test] + fn built_in_defaults_are_identified_as_the_source() { + let figment = Figment::from(Serialized::defaults(Settings::default())); + assert_eq!( + source_for("ui.fps", &figment, Path::new("missing.toml")), + "built-in defaults" + ); + } +} diff --git a/src/downloader.rs b/src/downloader.rs index 9891008..802c888 100644 --- a/src/downloader.rs +++ b/src/downloader.rs @@ -187,7 +187,7 @@ impl crate::Tasks { /// `tx` specifies the [`Sender`] to be notified with [`crate::Message::Loaded`]. pub fn downloader( &mut self, - args: &crate::Args, + settings: &crate::config::Settings, logger: Logger, tracks: tracks::List, ) -> crate::Result { @@ -197,12 +197,12 @@ impl crate::Tasks { "/", env!("CARGO_PKG_VERSION") )) - .timeout(Duration::from_secs(args.timeout)) + .timeout(Duration::from_secs(settings.playback.timeout)) .build()?; - let (qtx, qrx) = mpsc::channel(args.buffer_size as usize - 1); + let (qtx, qrx) = mpsc::channel(settings.playback.buffer_size as usize - 1); let downloader = Downloader { - debug: args.debug, + debug: settings.playback.debug, logger, queue: qtx, tx: self.tx(), diff --git a/src/main.rs b/src/main.rs index 971391c..1a085b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,12 @@ //! An extremely simple lofi player. use crate::player::Player; -use clap::{Parser, Subcommand}; +use clap::{CommandFactory, Parser, Subcommand}; use std::path::PathBuf; pub mod audio; pub mod bookmark; +pub mod config; pub mod downloader; pub mod error; pub mod message; @@ -127,9 +128,13 @@ async fn main() -> eyre::Result<()> { }; } + let config_path = data_dir()?.join("config.toml"); + let overrides = config::CliOverrides::from_args(&args, &Args::command().get_matches()); + let (settings, bindings) = config::load(&config_path, overrides)?; + let stream = audio::stream()?; - let environment = ui::Environment::ready(&args)?; - let (mut player, tasks) = Player::init(args, stream.mixer()) + let environment = ui::Environment::ready(&settings)?; + let (mut player, tasks) = Player::init(settings, bindings, stream.mixer()) .await .inspect_err(|_| environment.cleanup(false).unwrap())?; diff --git a/src/player.rs b/src/player.rs index 9e476c8..c2fdbce 100644 --- a/src/player.rs +++ b/src/player.rs @@ -93,17 +93,18 @@ impl Player { /// volume state. The function returns a fully constructed `Player` ready /// to be driven via `run`. pub async fn init( - args: crate::Args, + settings: crate::config::Settings, + bindings: crate::config::BindingMap, mixer: &rodio::mixer::Mixer, ) -> crate::Result<(Self, crate::Tasks)> { let (tx, rx) = mpsc::channel(8); let mut tasks = Tasks::new(tx.clone()); - if args.paused { + if settings.playback.paused { tx.send(Message::Pause).await?; } tx.send(Message::Init).await?; - let list = List::load(args.track_list.as_ref()).await?; + let list = List::load(settings.playback.track_list.as_ref()).await?; let sink = Arc::new(rodio::Player::connect_new(mixer)); let state = ui::State::initial(Arc::clone(&sink), list.name.clone()); @@ -111,9 +112,9 @@ impl Player { let volume = PersistentVolume::load().await?; sink.set_volume(volume.float()); - let ui = tasks.ui(state, &args).await?; + let ui = tasks.ui(state, &settings, bindings).await?; let player = Self { - downloader: tasks.downloader(&args, ui.logger(), list)?, + downloader: tasks.downloader(&settings, ui.logger(), list)?, ui, waiter: tasks.waiter(Arc::clone(&sink)), bookmarks: Bookmarks::load().await?, diff --git a/src/ui/environment.rs b/src/ui/environment.rs index bd3d669..8bc282f 100644 --- a/src/ui/environment.rs +++ b/src/ui/environment.rs @@ -26,12 +26,12 @@ pub struct Environment { impl Environment { /// This prepares the terminal, returning an [Environment] helpful /// for cleaning up afterwards. - pub fn ready(args: &crate::Args) -> super::Result { + pub fn ready(settings: &crate::config::Settings) -> super::Result { let enabled = !crate::env("LOWFI_DISABLE_UI"); if !enabled { return Ok(Self { enhancement: false, - alternate: args.alternate, + alternate: settings.ui.alternate, enabled, }); } @@ -39,7 +39,7 @@ impl Environment { let mut lock = stdout().lock(); crossterm::execute!(lock, Hide)?; - if args.alternate { + if settings.ui.alternate { crossterm::execute!(lock, EnterAlternateScreen, MoveTo(0, 0))?; } @@ -56,7 +56,7 @@ impl Environment { let environment = Self { enabled, enhancement, - alternate: args.alternate, + alternate: settings.ui.alternate, }; panic::set_hook(Box::new(move |info| { diff --git a/src/ui/init.rs b/src/ui/init.rs index 6b327b2..743f4d3 100644 --- a/src/ui/init.rs +++ b/src/ui/init.rs @@ -6,7 +6,12 @@ use tokio::sync::broadcast; impl crate::Tasks { /// Initializes the UI itself, along with all of the tasks that are related to it. #[allow(clippy::unused_async)] - pub async fn ui(&mut self, state: ui::State, args: &crate::Args) -> crate::Result { + pub async fn ui( + &mut self, + state: ui::State, + settings: &crate::config::Settings, + bindings: crate::config::BindingMap, + ) -> crate::Result { let (utx, urx) = broadcast::channel(8); #[cfg(feature = "mpris")] @@ -16,13 +21,13 @@ impl crate::Tasks { let media_controls = ui::media_controls::Server::try_new(state.clone(), self.tx(), urx.resubscribe()); - let params = interface::Params::try_from(args)?; + let params = interface::Params::try_from(settings)?; let interface = interface::Interface::new(params)?; let logger = interface.logger.clone(); if params.enabled { self.spawn(ui::run(urx, interface, state)); - self.spawn(input::listen(self.tx())); + self.spawn(input::listen(self.tx(), bindings)); } Ok(ui::Handle { @@ -34,4 +39,4 @@ impl crate::Tasks { media_controls, }) } -} \ No newline at end of file +} diff --git a/src/ui/input.rs b/src/ui/input.rs index 0ff04ef..2d32810 100644 --- a/src/ui/input.rs +++ b/src/ui/input.rs @@ -1,13 +1,13 @@ //! Responsible for specifically receiving terminal input //! using [`crossterm`]. -use crate::Message; +use crate::{config::BindingMap, Message}; use crossterm::event::{self, EventStream, KeyCode, KeyEventKind, KeyModifiers}; use futures_util::{FutureExt, StreamExt}; use tokio::sync::mpsc::Sender; /// Starts the listener to receive input from the terminal for various events. -pub async fn listen(sender: Sender) -> super::Result<()> { +pub async fn listen(sender: Sender, bindings: BindingMap) -> super::Result<()> { let mut reader = EventStream::new(); loop { @@ -19,49 +19,144 @@ pub async fn listen(sender: Sender) -> super::Result<()> { continue; } - let messages = match event.code { - // Arrow key volume controls. - KeyCode::Up => Message::ChangeVolume(0.1), - KeyCode::Right => Message::ChangeVolume(0.01), - KeyCode::Down => Message::ChangeVolume(-0.1), - KeyCode::Left => Message::ChangeVolume(-0.01), - KeyCode::Char(character) => match character.to_ascii_lowercase() { - // Ctrl+C - 'c' if event.modifiers == KeyModifiers::CONTROL => Message::Quit, - - // Quit - 'q' => Message::Quit, - - // Skip/Next - 's' | 'n' | 'l' => Message::Next, - - // Pause - 'p' | ' ' => Message::PlayPause, + let messages = match message_for(event.code, event.modifiers, &bindings) { + Some(message) => message, + None => continue, + }; + sender.send(messages).await?; + } +} - // Volume up & down - '+' | '=' | 'k' => Message::ChangeVolume(0.1), - '-' | '_' | 'j' => Message::ChangeVolume(-0.1), +fn message_for(code: KeyCode, modifiers: KeyModifiers, bindings: &BindingMap) -> Option { + match code { + KeyCode::Char('c') if modifiers == KeyModifiers::CONTROL => Some(Message::Quit), + KeyCode::Char(character) => { + bindings.message(&KeyCode::Char(character.to_ascii_lowercase())) + } + KeyCode::Up | KeyCode::Right | KeyCode::Down | KeyCode::Left => bindings.message(&code), + KeyCode::Media(media) => match media { + event::MediaKeyCode::Pause + | event::MediaKeyCode::Play + | event::MediaKeyCode::PlayPause => Some(Message::PlayPause), + event::MediaKeyCode::Stop => Some(Message::Pause), + event::MediaKeyCode::TrackNext => Some(Message::Next), + event::MediaKeyCode::LowerVolume => Some(Message::ChangeVolume(-0.1)), + event::MediaKeyCode::RaiseVolume => Some(Message::ChangeVolume(0.1)), + event::MediaKeyCode::MuteVolume => Some(Message::ChangeVolume(-1.0)), + _ => None, + }, + _ => None, + } +} - // Bookmark - 'b' => Message::Bookmark, +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; - _ => continue, - }, - // Media keys - KeyCode::Media(media) => match media { - event::MediaKeyCode::Pause - | event::MediaKeyCode::Play - | event::MediaKeyCode::PlayPause => Message::PlayPause, - event::MediaKeyCode::Stop => Message::Pause, - event::MediaKeyCode::TrackNext => Message::Next, - event::MediaKeyCode::LowerVolume => Message::ChangeVolume(-0.1), - event::MediaKeyCode::RaiseVolume => Message::ChangeVolume(0.1), - event::MediaKeyCode::MuteVolume => Message::ChangeVolume(-1.0), - _ => continue, - }, - _ => continue, - }; + #[test] + fn bindings_are_case_insensitive_and_ctrl_c_is_reserved() { + let (_, bindings) = crate::config::load( + Path::new("missing.toml"), + crate::config::CliOverrides::default(), + ) + .unwrap(); + assert_eq!( + message_for(KeyCode::Char('P'), KeyModifiers::NONE, &bindings), + Some(Message::PlayPause) + ); + assert_eq!( + message_for(KeyCode::Char('c'), KeyModifiers::CONTROL, &bindings), + Some(Message::Quit) + ); + assert_ne!( + message_for(KeyCode::Char('c'), KeyModifiers::NONE, &bindings), + Some(Message::Quit) + ); + assert_eq!( + message_for(KeyCode::Up, KeyModifiers::NONE, &bindings), + Some(Message::ChangeVolume(0.1)) + ); + assert_eq!( + message_for(KeyCode::Down, KeyModifiers::NONE, &bindings), + Some(Message::ChangeVolume(-0.1)) + ); + assert_eq!( + message_for(KeyCode::Right, KeyModifiers::NONE, &bindings), + Some(Message::ChangeVolume(0.01)) + ); + assert_eq!( + message_for(KeyCode::Left, KeyModifiers::NONE, &bindings), + Some(Message::ChangeVolume(-0.01)) + ); + } - sender.send(messages).await?; + #[test] + fn media_keys_and_unmapped_input_are_handled_explicitly() { + let (_, bindings) = crate::config::load( + Path::new("missing.toml"), + crate::config::CliOverrides::default(), + ) + .unwrap(); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::PlayPause), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::PlayPause) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::Stop), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::Pause) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::TrackNext), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::Next) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::RaiseVolume), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::ChangeVolume(0.1)) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::LowerVolume), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::ChangeVolume(-0.1)) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::MuteVolume), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::ChangeVolume(-1.0)) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::TrackPrevious), + KeyModifiers::NONE, + &bindings, + ), + None + ); + assert_eq!( + message_for(KeyCode::F(1), KeyModifiers::NONE, &bindings), + None + ); } } diff --git a/src/ui/interface.rs b/src/ui/interface.rs index 1170f75..8b62ddc 100644 --- a/src/ui/interface.rs +++ b/src/ui/interface.rs @@ -1,8 +1,8 @@ //! Responsible for the actual graphical interface of lowfi. use crate::{ + config::Settings, ui::{self, State}, - Args, }; use std::{io::stdout, time::Duration}; @@ -67,11 +67,11 @@ impl Default for Params { } } -impl TryFrom<&Args> for Params { +impl TryFrom<&Settings> for Params { type Error = ui::Error; - fn try_from(args: &Args) -> ui::Result { - let delta = 1.0 / f32::from(args.fps); + fn try_from(settings: &Settings) -> ui::Result { + let delta = 1.0 / f32::from(settings.ui.fps); let delta = Duration::from_secs_f32(delta); let disabled = crate::env("LOWFI_DISABLE_UI"); @@ -82,10 +82,10 @@ impl TryFrom<&Args> for Params { Ok(Self { delta, enabled: !disabled, - clock: args.clock, - width: 21 + args.width.min(32) * 2, - minimalist: args.minimalist, - borderless: args.borderless, + clock: settings.ui.clock, + width: 21 + settings.ui.width.min(32) * 2, + minimalist: settings.ui.minimalist, + borderless: settings.ui.borderless, }) } } From 392109720a57e829d5c6a5ae31ed6bed188a77c6 Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:24:46 -0400 Subject: [PATCH 02/12] fix: preserve legacy environment switches with structured settings --- src/config.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index d0bb806..4dc6100 100644 --- a/src/config.rs +++ b/src/config.rs @@ -213,7 +213,11 @@ pub fn load(path: &Path, cli: CliOverrides) -> Result<(Settings, BindingMap), Er figment = figment.merge(Toml::file_exact(path)); } let figment = figment - .merge(Env::prefixed("LOWFI_").split("__")) + .merge( + Env::prefixed("LOWFI_") + .ignore(&["disable_ui", "fixed_mpris_name"]) + .split("__"), + ) .merge(Serialized::defaults(cli)); let settings: Settings = figment.extract()?; @@ -570,4 +574,17 @@ mod tests { "built-in defaults" ); } + + #[test] + fn legacy_environment_switches_do_not_enter_structured_settings() { + Jail::expect_with(|jail| { + jail.set_env("LOWFI_DISABLE_UI", "1"); + jail.set_env("LOWFI_FIXED_MPRIS_NAME", "1"); + let (settings, _) = load(Path::new("missing.toml"), CliOverrides::default()).unwrap(); + assert_eq!(settings, Settings::default()); + jail.set_env("LOWFI_UI__NOT_A_SETTING", "1"); + assert!(load(Path::new("missing.toml"), CliOverrides::default()).is_err()); + Ok(()) + }); + } } From c57e462c2785c4acbadd4cbe62a9b8639b5643eb Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:30:45 -0400 Subject: [PATCH 03/12] test: isolate configuration reads from concurrent environment changes --- src/config.rs | 80 ++++++++++--------- src/ui/input.rs | 204 +++++++++++++++++++++++++----------------------- 2 files changed, 150 insertions(+), 134 deletions(-) diff --git a/src/config.rs b/src/config.rs index 4dc6100..321581b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -350,31 +350,35 @@ mod tests { #[test] fn defaults_preserve_every_existing_binding() { - let path = Path::new("missing.toml"); - let (settings, keys) = load(path, CliOverrides::default()).unwrap(); - assert_eq!(settings, Settings::default()); - assert!(!path.exists()); - for (key, message) in [ - ("p", Message::PlayPause), - (" ", Message::PlayPause), - ("s", Message::Next), - ("n", Message::Next), - ("l", Message::Next), - ("q", Message::Quit), - ("b", Message::Bookmark), - ("+", Message::ChangeVolume(0.1)), - ("=", Message::ChangeVolume(0.1)), - ("k", Message::ChangeVolume(0.1)), - ("-", Message::ChangeVolume(-0.1)), - ("_", Message::ChangeVolume(-0.1)), - ("j", Message::ChangeVolume(-0.1)), - ("Up", Message::ChangeVolume(0.1)), - ("Down", Message::ChangeVolume(-0.1)), - ("Right", Message::ChangeVolume(0.01)), - ("Left", Message::ChangeVolume(-0.01)), - ] { - assert_eq!(keys.message(&parse_key(key).unwrap()), Some(message)); - } + figment::Jail::expect_with(|_| { + let path = Path::new("missing.toml"); + let (settings, keys) = load(path, CliOverrides::default()).unwrap(); + assert_eq!(settings, Settings::default()); + assert!(!path.exists()); + for (key, message) in [ + ("p", Message::PlayPause), + (" ", Message::PlayPause), + ("s", Message::Next), + ("n", Message::Next), + ("l", Message::Next), + ("q", Message::Quit), + ("b", Message::Bookmark), + ("+", Message::ChangeVolume(0.1)), + ("=", Message::ChangeVolume(0.1)), + ("k", Message::ChangeVolume(0.1)), + ("-", Message::ChangeVolume(-0.1)), + ("_", Message::ChangeVolume(-0.1)), + ("j", Message::ChangeVolume(-0.1)), + ("Up", Message::ChangeVolume(0.1)), + ("Down", Message::ChangeVolume(-0.1)), + ("Right", Message::ChangeVolume(0.01)), + ("Left", Message::ChangeVolume(-0.01)), + ] { + assert_eq!(keys.message(&parse_key(key).unwrap()), Some(message)); + } + + Ok(()) + }); } #[test] @@ -553,17 +557,21 @@ mod tests { #[test] fn invalid_cli_values_identify_the_cli_flag_as_the_source() { - let args = crate::Args::try_parse_from(["lowfi", "--fps", "0"]).unwrap(); - let matches = crate::Args::command() - .try_get_matches_from(["lowfi", "--fps", "0"]) - .unwrap(); - let error = load( - Path::new("missing.toml"), - CliOverrides::from_args(&args, &matches), - ) - .unwrap_err() - .to_string(); - assert!(error.contains("CLI flag --fps")); + figment::Jail::expect_with(|_| { + let args = crate::Args::try_parse_from(["lowfi", "--fps", "0"]).unwrap(); + let matches = crate::Args::command() + .try_get_matches_from(["lowfi", "--fps", "0"]) + .unwrap(); + let error = load( + Path::new("missing.toml"), + CliOverrides::from_args(&args, &matches), + ) + .unwrap_err() + .to_string(); + assert!(error.contains("CLI flag --fps")); + + Ok(()) + }); } #[test] diff --git a/src/ui/input.rs b/src/ui/input.rs index 2d32810..c18f281 100644 --- a/src/ui/input.rs +++ b/src/ui/input.rs @@ -56,107 +56,115 @@ mod tests { #[test] fn bindings_are_case_insensitive_and_ctrl_c_is_reserved() { - let (_, bindings) = crate::config::load( - Path::new("missing.toml"), - crate::config::CliOverrides::default(), - ) - .unwrap(); - assert_eq!( - message_for(KeyCode::Char('P'), KeyModifiers::NONE, &bindings), - Some(Message::PlayPause) - ); - assert_eq!( - message_for(KeyCode::Char('c'), KeyModifiers::CONTROL, &bindings), - Some(Message::Quit) - ); - assert_ne!( - message_for(KeyCode::Char('c'), KeyModifiers::NONE, &bindings), - Some(Message::Quit) - ); - assert_eq!( - message_for(KeyCode::Up, KeyModifiers::NONE, &bindings), - Some(Message::ChangeVolume(0.1)) - ); - assert_eq!( - message_for(KeyCode::Down, KeyModifiers::NONE, &bindings), - Some(Message::ChangeVolume(-0.1)) - ); - assert_eq!( - message_for(KeyCode::Right, KeyModifiers::NONE, &bindings), - Some(Message::ChangeVolume(0.01)) - ); - assert_eq!( - message_for(KeyCode::Left, KeyModifiers::NONE, &bindings), - Some(Message::ChangeVolume(-0.01)) - ); + figment::Jail::expect_with(|_| { + let (_, bindings) = crate::config::load( + Path::new("missing.toml"), + crate::config::CliOverrides::default(), + ) + .unwrap(); + assert_eq!( + message_for(KeyCode::Char('P'), KeyModifiers::NONE, &bindings), + Some(Message::PlayPause) + ); + assert_eq!( + message_for(KeyCode::Char('c'), KeyModifiers::CONTROL, &bindings), + Some(Message::Quit) + ); + assert_ne!( + message_for(KeyCode::Char('c'), KeyModifiers::NONE, &bindings), + Some(Message::Quit) + ); + assert_eq!( + message_for(KeyCode::Up, KeyModifiers::NONE, &bindings), + Some(Message::ChangeVolume(0.1)) + ); + assert_eq!( + message_for(KeyCode::Down, KeyModifiers::NONE, &bindings), + Some(Message::ChangeVolume(-0.1)) + ); + assert_eq!( + message_for(KeyCode::Right, KeyModifiers::NONE, &bindings), + Some(Message::ChangeVolume(0.01)) + ); + assert_eq!( + message_for(KeyCode::Left, KeyModifiers::NONE, &bindings), + Some(Message::ChangeVolume(-0.01)) + ); + + Ok(()) + }); } #[test] fn media_keys_and_unmapped_input_are_handled_explicitly() { - let (_, bindings) = crate::config::load( - Path::new("missing.toml"), - crate::config::CliOverrides::default(), - ) - .unwrap(); - assert_eq!( - message_for( - KeyCode::Media(event::MediaKeyCode::PlayPause), - KeyModifiers::NONE, - &bindings, - ), - Some(Message::PlayPause) - ); - assert_eq!( - message_for( - KeyCode::Media(event::MediaKeyCode::Stop), - KeyModifiers::NONE, - &bindings, - ), - Some(Message::Pause) - ); - assert_eq!( - message_for( - KeyCode::Media(event::MediaKeyCode::TrackNext), - KeyModifiers::NONE, - &bindings, - ), - Some(Message::Next) - ); - assert_eq!( - message_for( - KeyCode::Media(event::MediaKeyCode::RaiseVolume), - KeyModifiers::NONE, - &bindings, - ), - Some(Message::ChangeVolume(0.1)) - ); - assert_eq!( - message_for( - KeyCode::Media(event::MediaKeyCode::LowerVolume), - KeyModifiers::NONE, - &bindings, - ), - Some(Message::ChangeVolume(-0.1)) - ); - assert_eq!( - message_for( - KeyCode::Media(event::MediaKeyCode::MuteVolume), - KeyModifiers::NONE, - &bindings, - ), - Some(Message::ChangeVolume(-1.0)) - ); - assert_eq!( - message_for( - KeyCode::Media(event::MediaKeyCode::TrackPrevious), - KeyModifiers::NONE, - &bindings, - ), - None - ); - assert_eq!( - message_for(KeyCode::F(1), KeyModifiers::NONE, &bindings), - None - ); + figment::Jail::expect_with(|_| { + let (_, bindings) = crate::config::load( + Path::new("missing.toml"), + crate::config::CliOverrides::default(), + ) + .unwrap(); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::PlayPause), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::PlayPause) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::Stop), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::Pause) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::TrackNext), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::Next) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::RaiseVolume), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::ChangeVolume(0.1)) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::LowerVolume), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::ChangeVolume(-0.1)) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::MuteVolume), + KeyModifiers::NONE, + &bindings, + ), + Some(Message::ChangeVolume(-1.0)) + ); + assert_eq!( + message_for( + KeyCode::Media(event::MediaKeyCode::TrackPrevious), + KeyModifiers::NONE, + &bindings, + ), + None + ); + assert_eq!( + message_for(KeyCode::F(1), KeyModifiers::NONE, &bindings), + None + ); + + Ok(()) + }); } } From 8bfcc70a76ff44bc945448d15ac820d67f39c4bb Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:58:13 -0400 Subject: [PATCH 04/12] docs(config): add configuration reference and clarify width cap --- README.md | 45 +++-------- docs/CONFIGURATION.md | 160 +++++++++++++++++++++++++++++++++++++++ docs/ENVIRONMENT_VARS.md | 8 ++ src/main.rs | 2 +- 4 files changed, 179 insertions(+), 36 deletions(-) create mode 100644 docs/CONFIGURATION.md diff --git a/README.md b/README.md index dacf6a6..96964f3 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,7 @@ slightly tweak the UI or behavior of the menu. The flags can be viewed with `low | `-f`, `--fps` | FPS of the UI [default: 12] | | `--timeout` | Timeout in seconds for music downloads [default: 16] | | `-d`, `--debug` | Include ALSA & other logs meant for debugging | -| `-w`, `--width ` | Width of the player, from 0 to 32 [default: 3] | +| `-w`, `--width ` | Player width, capped at 32 [default: 3] | | `-t`, `--track-list ` | Use a [custom track list](#custom-track-lists) | | `-s`, `--buffer-size ` | Internal song buffer size [default: 5] | @@ -194,49 +194,24 @@ If you need something even more specific, see [ENVIRONMENT_VARS](./docs/ENVIRONM ### Configuration -Lowfi also reads an optional `config.toml` from its platform data directory: -`~/.local/share/lowfi/config.toml` on Linux, `%APPDATA%\\lowfi\\config.toml` on -Windows, and `~/Library/Application Support/lowfi/config.toml` on macOS. It never -creates or overwrites this file. - -Settings are resolved in this order: built-in defaults, `config.toml`, `LOWFI_*` -environment variables, then explicitly supplied command-line flags. Environment -variables use `LOWFI_
__` names, such as `LOWFI_UI__FPS=20`, -`LOWFI_PLAYBACK__PAUSED=false`, or `LOWFI_BINDINGS__NEXT='["n", "x"]'`. +Save persistent settings in an optional `config.toml` in Lowfi's platform data +directory. Include only the values you want to change, for example: ```toml [playback] -paused = false -track_list = "chillhop" -buffer_size = 5 -timeout = 16 -debug = false +paused = true [ui] -alternate = false -minimalist = false -borderless = false -clock = false -fps = 12 -width = 3 +fps = 20 [bindings] -play_pause = ["p", "Space"] -next = ["s", "n", "l"] -quit = ["q"] -bookmark = ["b"] -volume_up = ["+", "=", "k", "Up"] -volume_down = ["-", "_", "j", "Down"] -volume_up_fine = ["Right"] -volume_down_fine = ["Left"] +next = ["x"] ``` -Bindings accept one printable character, `Space`, `Up`, `Down`, `Left`, and -`Right`; names are case-insensitive. Supplying a binding list replaces that -action's defaults, while an empty list disables that action's configurable keys. -`Ctrl+C` remains reserved for quitting. Invalid values, unknown fields, and -duplicate keys stop startup with an error that identifies the field and source. -The terminal's small control hints continue to show the default keys. +Settings resolve from defaults, then the file, then `LOWFI_*` environment +variables, then explicit CLI flags. Restart Lowfi to pick up file changes. +See [Configuration](docs/CONFIGURATION.md) for file locations, every option and +default, environment syntax, binding rules, and validation errors. ### Extra Features diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md new file mode 100644 index 0000000..e55b58f --- /dev/null +++ b/docs/CONFIGURATION.md @@ -0,0 +1,160 @@ +# Configuration + +Lowfi reads settings once at startup. You can combine an optional TOML file, +environment variables, and command-line flags. Restart Lowfi after editing the +file; settings are not reloaded while it runs. + +## File location and quick start + +Create `config.toml` in Lowfi's platform data directory: + +| Platform | Default path | +| --- | --- | +| Linux | `~/.local/share/lowfi/config.toml` | +| macOS | `~/Library/Application Support/lowfi/config.toml` | +| Windows | `%APPDATA%\lowfi\config.toml` (Roaming AppData) | + +On Linux, an absolute `XDG_DATA_HOME` overrides `~/.local/share`, so the path +becomes `$XDG_DATA_HOME/lowfi/config.toml`. Lowfi uses its **data** directory; +`XDG_CONFIG_HOME` does not select this file. + +Create the parent directory if needed, then save only the settings you want to +change. For example: + +```toml +[playback] +paused = true + +[ui] +fps = 20 + +[bindings] +next = ["x"] +``` + +This starts paused, renders at 20 FPS, and replaces the configurable Next keys +with `x`. Omitted fields keep their built-in defaults. A missing file is valid; +Lowfi never creates or overwrites it. Existing volume and bookmark persistence +is separate from this configuration file. + +## Precedence + +Later sources override earlier sources, one setting at a time: + +1. Built-in defaults +2. `config.toml` +3. `LOWFI_*` environment variables +4. Explicit command-line flags + +For example, a file with `ui.fps = 20` is overridden by `LOWFI_UI__FPS=24`, +and `--fps 30` overrides both. Omitting `--fps` preserves the file or environment +value; the CLI's displayed default does not override it. + +Boolean flags such as `--paused` set their option to `true`. To override a +file's `paused = true` with `false`, use `LOWFI_PLAYBACK__PAUSED=false`. +These flags do not accept `--paused=false` or have a `--no-paused` counterpart. + +Environment names use `LOWFI_
__` with a double underscore +between the section and field. Use `true` or `false` for structured booleans +and array syntax for bindings. For example, in a POSIX shell: + +```sh +LOWFI_PLAYBACK__PAUSED=false LOWFI_UI__FPS=24 lowfi --fps 30 +LOWFI_BINDINGS__NEXT='["x", "n"]' lowfi +``` + +In PowerShell: + +```powershell +$env:LOWFI_PLAYBACK__PAUSED = 'false' +$env:LOWFI_BINDINGS__NEXT = '["x", "n"]' +lowfi +``` + +The legacy `LOWFI_DISABLE_UI` and `LOWFI_FIXED_MPRIS_NAME` switches still use +`1` to enable them. They are handled separately from these structured settings; +see [Environment Variables](ENVIRONMENT_VARS.md). + +## Playback options + +These fields belong under `[playback]` in TOML. + +| Key | Purpose | Default / accepted values | Environment variable | CLI flag | +| --- | --- | --- | --- | --- | +| `paused` | Start playback paused | `false`; boolean | `LOWFI_PLAYBACK__PAUSED` | `-p`, `--paused` | +| `track_list` | Track list to play | `"chillhop"`; string | `LOWFI_PLAYBACK__TRACK_LIST` | `-t`, `--track-list` | +| `buffer_size` | Internal song buffer size | `5`; integer from 2 to 4294967295 | `LOWFI_PLAYBACK__BUFFER_SIZE` | `-s`, `--buffer-size` | +| `timeout` | Download timeout in seconds | `16`; nonnegative 64-bit integer | `LOWFI_PLAYBACK__TIMEOUT` | `--timeout` | +| `debug` | Include ALSA and downloader debug logs | `false`; boolean | `LOWFI_PLAYBACK__DEBUG` | `-d`, `--debug` | + +See [Custom track lists](../README.md#custom-track-lists) for track-list names +and file formats. Volume is stored separately and has no `[playback]` setting. + +## Terminal options + +These fields belong under `[ui]` in TOML. + +| Key | Purpose | Default / accepted values | Environment variable | CLI flag | +| --- | --- | --- | --- | --- | +| `alternate` | Use the alternate terminal screen | `false`; boolean | `LOWFI_UI__ALTERNATE` | `-a`, `--alternate` | +| `minimalist` | Hide the bottom control bar | `false`; boolean | `LOWFI_UI__MINIMALIST` | `-m`, `--minimalist` | +| `borderless` | Hide window borders | `false`; boolean | `LOWFI_UI__BORDERLESS` | `-b`, `--borderless` | +| `clock` | Show a clock | `false`; boolean | `LOWFI_UI__CLOCK` | `-c`, `--clock` | +| `fps` | Terminal frames per second | `12`; integer from 1 to 255 | `LOWFI_UI__FPS` | `-f`, `--fps` | +| `width` | Player width parameter | `3`; nonnegative platform-sized integer, capped at 32 for rendering | `LOWFI_UI__WIDTH` | `-w`, `--width` | + +`width` is a sizing parameter, not the final width in terminal columns. Values +above 32 are accepted and render identically to 32, matching the existing CLI +behavior. Negative values and values that do not fit the platform's unsigned +integer type are rejected. + +## Key bindings + +Each field under `[bindings]` is an array of key names. Its environment variable +is `LOWFI_BINDINGS__`, for example `LOWFI_BINDINGS__PLAY_PAUSE`. +Bindings have no CLI flags. + +| Key | Action | Default keys | +| --- | --- | --- | +| `play_pause` | Toggle playback | `["p", "Space"]` | +| `next` | Skip to the next track | `["s", "n", "l"]` | +| `quit` | Quit Lowfi | `["q"]` | +| `bookmark` | Toggle the current track's bookmark | `["b"]` | +| `volume_up` | Raise volume by 10 percentage points | `["+", "=", "k", "Up"]` | +| `volume_down` | Lower volume by 10 percentage points | `["-", "_", "j", "Down"]` | +| `volume_up_fine` | Raise volume by 1 percentage point | `["Right"]` | +| `volume_down_fine` | Lower volume by 1 percentage point | `["Left"]` | + +A list replaces that action's entire default list; it does not append keys. +Other actions keep their defaults. An empty list disables that action's +configurable keys: + +```toml +[bindings] +next = ["x"] +bookmark = [] +``` + +Key names accept one printable character or `Space`, `Up`, `Down`, `Left`, and +`Right`. ASCII letter keys and named keys are case-insensitive. Modifier chords +such as `Ctrl+X` are not supported. `Ctrl+C` always quits and cannot be remapped. +Duplicate keys, including duplicates within one action, are rejected. To move a +key between actions, remove it from its original action's list as well. + +Terminal media-key handling is separate from these lists. Disabling an action's +configurable keys does not disable its media-key handling. The terminal control +bar continues to show the default hints; custom bindings do not change its text. + +## Validation and troubleshooting + +Lowfi stops startup for an unreadable or malformed file, unknown fields, +incorrect types, invalid values, or invalid/duplicate bindings. Errors identify +the setting and its source where available: a file path, environment variable, +CLI flag, or built-in default. For example, `ui.fps = 0` fails validation and +identifies the configuration file. + +If a file change appears to have no effect, restart Lowfi and check for an +environment variable or explicit CLI flag overriding that setting. Check the +data-directory path above, especially `XDG_DATA_HOME` on Linux. Shells differ in +how they quote array values; preserve the double quotes inside the binding +array as shown in the examples. diff --git a/docs/ENVIRONMENT_VARS.md b/docs/ENVIRONMENT_VARS.md index 3d27569..3d613c7 100644 --- a/docs/ENVIRONMENT_VARS.md +++ b/docs/ENVIRONMENT_VARS.md @@ -2,6 +2,14 @@ [[Version française](./fr/ENVIRONMENT_VARS.md)] +For persistent playback/UI settings and key bindings, see +[Configuration](CONFIGURATION.md). That reference covers `config.toml`, +`LOWFI_
__` variables, and CLI precedence. + +The switches below are separate legacy options, enabled only when their value +is exactly `1` (for example, `LOWFI_FIXED_MPRIS_NAME=1`). They are not fields in +`config.toml`. + lowfi has some more specific options, usually as a result of minor feature requests, which are only documented here. If you have some behavior you'd like to change, which is quite specific, then see if one of these options suits you. diff --git a/src/main.rs b/src/main.rs index 1a085b3..de3d4d3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -62,7 +62,7 @@ pub struct Args { #[clap(long, short)] debug: bool, - /// Width of the player, from 0 to 32. + /// Width of the player, capped at 32. #[clap(long, short, default_value_t = 3)] width: usize, From 42579bc5c824a9cc0d784cb680ed3ab6c35555b7 Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:14:11 -0400 Subject: [PATCH 05/12] docs(config): explain resolution and binding contracts --- src/config.rs | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index 321581b..cc9bb65 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,7 @@ //! Loading and validating Lowfi's user configuration. +//! +//! Resolve settings through `load` before starting playback or terminal tasks. +//! The user-facing option reference is in `docs/CONFIGURATION.md`. use std::{ collections::HashMap, @@ -14,7 +17,10 @@ use serde::{Deserialize, Serialize}; use crate::Message; -/// Fully resolved application settings. +/// Application settings after deserialization. +/// +/// Use [`load`] to apply validation and compile key bindings. Deserializing this +/// type alone does not enforce cross-field or binding constraints. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Settings { @@ -28,6 +34,7 @@ pub struct Settings { pub struct Playback { pub paused: bool, pub track_list: String, + /// Song-buffer setting, including the current track; must be at least two. pub buffer_size: u32, pub timeout: u64, pub debug: bool, @@ -41,9 +48,15 @@ pub struct Ui { pub borderless: bool, pub clock: bool, pub fps: u8, + /// Sizing parameter, not terminal columns; the renderer caps it at 32. pub width: usize, } +/// Configurable terminal keys, grouped by action. +/// +/// Each supplied list replaces that action's defaults; an empty list removes its +/// configurable keys. Media keys and reserved Ctrl+C handling live in the input +/// layer and are not disabled by an empty list. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Bindings { @@ -129,6 +142,10 @@ struct UiOverrides { } impl CliOverrides { + /// Keeps only values explicitly supplied on the command line. + /// + /// `args` and `matches` must describe the same parse. Clap's default values + /// must stay absent here so they cannot overwrite file or environment values. pub fn from_args(args: &crate::Args, matches: &clap::ArgMatches) -> Self { use clap::parser::ValueSource; let supplied = |name| matches.value_source(name) == Some(ValueSource::CommandLine); @@ -167,11 +184,13 @@ impl CliOverrides { } } -/// Maps terminal keys to their configured messages. +/// Validated lookup of normalized terminal keys to their configured messages. #[derive(Clone, Debug)] pub struct BindingMap(HashMap); impl BindingMap { + /// Looks up an already-normalized key; ASCII character keys must be lowercase. + /// The input layer normalizes events and handles reserved/media keys separately. pub fn message(&self, key: &KeyCode) -> Option { self.0.get(key).copied() } @@ -195,7 +214,16 @@ pub enum Error { }, } -/// Loads settings from defaults, an optional exact TOML file, environment, and CLI overrides. +/// Resolves and validates settings, returning the compiled terminal bindings. +/// +/// Later sources win: defaults, the exact TOML path, `LOWFI_*` environment, then +/// explicit CLI values. Binding lists replace earlier lists rather than append. +/// A missing file is allowed; this function never creates or overwrites it. +/// +/// # Errors +/// Returns errors for unreadable or malformed configuration, unknown fields, +/// invalid values, or invalid/duplicate bindings. Diagnostics identify the field +/// and source where available. Legacy UI/MPRIS switches are handled separately. pub fn load(path: &Path, cli: CliOverrides) -> Result<(Settings, BindingMap), Error> { let exists = path.try_exists().map_err(|source| Error::Read { path: path.into(), @@ -215,6 +243,8 @@ pub fn load(path: &Path, cli: CliOverrides) -> Result<(Settings, BindingMap), Er let figment = figment .merge( Env::prefixed("LOWFI_") + // These process switches predate structured configuration. Feeding + // them into Settings would make deny_unknown_fields reject them. .ignore(&["disable_ui", "fixed_mpris_name"]) .split("__"), ) From 7838c2b62871357eea1afb96de63e29c0f83bb57 Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:17:23 -0400 Subject: [PATCH 06/12] test: add deterministic fixtures and native test tooling --- .cargo/mutants-media-controls.toml | 17 ++++ .cargo/mutants-mpris.toml | 12 +++ .cargo/mutants.toml | 20 +++++ .github/workflows/mutation.yml | 69 +++++++++++++++ .github/workflows/tooling.yml | 88 +++++++++++++++++++ .gitignore | 3 +- CONTRIBUTING.md | 49 +++++++++++ Cargo.lock | 7 ++ Cargo.toml | 39 +++++++++ src/scrapers.rs | 4 +- src/tests.rs | 2 + src/tests/fixture.rs | 130 +++++++++++++++++++++++++++++ src/tests/fixtures/README.md | 13 +++ src/tests/fixtures/test-tone.mp3 | Bin 0 -> 32643 bytes src/tests/tracks.rs | 43 ++++++---- src/tests/ui.rs | 13 ++- src/ui/input.rs | 1 + src/ui/media_controls.rs | 49 +++++++++-- src/ui/mpris.rs | 130 +++++++++++++++++++++++++++++ 19 files changed, 661 insertions(+), 28 deletions(-) create mode 100644 .cargo/mutants-media-controls.toml create mode 100644 .cargo/mutants-mpris.toml create mode 100644 .cargo/mutants.toml create mode 100644 .github/workflows/mutation.yml create mode 100644 .github/workflows/tooling.yml create mode 100644 src/tests/fixture.rs create mode 100644 src/tests/fixtures/README.md create mode 100644 src/tests/fixtures/test-tone.mp3 diff --git a/.cargo/mutants-media-controls.toml b/.cargo/mutants-media-controls.toml new file mode 100644 index 0000000..b030531 --- /dev/null +++ b/.cargo/mutants-media-controls.toml @@ -0,0 +1,17 @@ +# Windows media-controls pass. Only the pure event-to-command mapping is in +# scope; constructing or pumping native SMTC controls needs a Windows desktop. +examine_globs = ["src/ui/media_controls.rs"] +exclude_globs = ["packaging/**", "src/tests/**", "tests/**", "target/**"] +exclude_re = [ + "sync_metadata", + "sync_playback", + "try_new", + "Server::create", + "Server::handle", + "Drop for Server", + "windows::", +] +additional_cargo_args = ["--locked"] +test_tool = "nextest" +minimum_test_timeout = 20 +timeout_multiplier = 5 diff --git a/.cargo/mutants-mpris.toml b/.cargo/mutants-mpris.toml new file mode 100644 index 0000000..04e8eb1 --- /dev/null +++ b/.cargo/mutants-mpris.toml @@ -0,0 +1,12 @@ +# Linux MPRIS pass. This enables MPRIS and tests the in-process interface, +# command forwarding, and error conversion without requiring a D-Bus session. +examine_globs = ["src/ui/mpris.rs"] +exclude_globs = ["packaging/**", "src/tests/**", "tests/**", "target/**"] +# Server creates a real D-Bus service and publishes native properties. Those +# event-loop and bus interactions are covered by native feature CI, not mutation +# tests. The Player and Sender remain in scope. +exclude_re = ["Server::"] +additional_cargo_args = ["--locked"] +test_tool = "nextest" +minimum_test_timeout = 20 +timeout_multiplier = 5 diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml new file mode 100644 index 0000000..1f55c8b --- /dev/null +++ b/.cargo/mutants.toml @@ -0,0 +1,20 @@ +# Keep the default pass on deterministic, frontend-neutral behavior. Native +# adapters have dedicated configurations because their compiled feature sets +# and test boundaries differ by platform. +examine_globs = [ + "src/config.rs", + "src/ui/input.rs", +] +exclude_globs = [ + "packaging/**", + "src/tests/**", + "tests/**", + "target/**", +] +# EventStream owns a terminal event loop and cannot be exercised without a +# terminal. `message_for` below it remains in scope. +exclude_re = ["listen", "Player::close"] +additional_cargo_args = ["--locked"] +test_tool = "nextest" +minimum_test_timeout = 20 +timeout_multiplier = 5 diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml new file mode 100644 index 0000000..03e483d --- /dev/null +++ b/.github/workflows/mutation.yml @@ -0,0 +1,69 @@ +name: Mutation tests + +on: + workflow_dispatch: + workflow_call: + +jobs: + mutants: + name: ${{ matrix.name }} + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + include: + - name: Linux core + os: ubuntu-latest + features: default + config: .cargo/mutants.toml + install_alsa: true + - name: Linux MPRIS adapter + os: ubuntu-latest + features: mpris + config: .cargo/mutants-mpris.toml + install_alsa: true + - name: Windows core + os: windows-latest + features: default + config: .cargo/mutants.toml + install_alsa: false + - name: Windows media controls adapter + os: windows-latest + features: media-controls + config: .cargo/mutants-media-controls.toml + install_alsa: false + - name: macOS configuration and input + os: macos-latest + features: default + config: .cargo/mutants.toml + install_alsa: false + steps: + - uses: actions/checkout@v5 + - name: Install ALSA development headers + if: matrix.install_alsa + run: sudo apt-get update && sudo apt-get install -y libasound2-dev + - name: Set up Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + - name: Install mutation test tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-mutants@27.1.0 cargo-nextest@0.9.140 + - name: Write mutation inventory + if: always() + run: >- + cargo mutants --config ${{ matrix.config }} --list --no-times + --features ${{ matrix.features }} > mutants-inventory.txt + - name: Run mutation tests + run: >- + cargo mutants --config ${{ matrix.config }} --no-shuffle + --features ${{ matrix.features }} --output mutants.out + - name: Upload mutation report + if: always() + uses: actions/upload-artifact@v4 + with: + name: mutants-${{ matrix.name }} + path: | + mutants-inventory.txt + mutants.out + if-no-files-found: warn diff --git a/.github/workflows/tooling.yml b/.github/workflows/tooling.yml new file mode 100644 index 0000000..98fa2fa --- /dev/null +++ b/.github/workflows/tooling.yml @@ -0,0 +1,88 @@ +name: Test tooling + +on: + workflow_dispatch: + inputs: + run_mutations: + description: Run the manual native mutation suite + required: false + default: false + type: boolean + push: + branches: ['**'] + pull_request: + branches: ['**'] + +jobs: + linux: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - name: Install ALSA development headers + run: sudo apt-get update && sudo apt-get install -y libasound2-dev + - name: Set up Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + - name: Install test tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-nextest@0.9.140 cargo-feature-combinations@0.7.0 + - name: Check formatting + run: cargo fmt --check + - name: Run standard tests + run: cargo test --locked + - name: Run default tests with nextest + run: cargo nextest run --locked + - name: Run no-default-features tests with nextest + run: cargo nextest run --locked --no-default-features + - name: Run maximal Linux feature tests with nextest + run: cargo nextest run --locked --features mpris,scrape,extra-audio-formats + - name: Run maximal Linux no-default-features tests with nextest + run: cargo nextest run --locked --no-default-features --features mpris,scrape,extra-audio-formats + - name: Check curated Linux feature combinations + run: cargo fc check --locked --all-targets + + windows: + runs-on: windows-latest + steps: + - uses: actions/checkout@v5 + - name: Set up Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + - name: Install test tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-nextest@0.9.140 cargo-feature-combinations@0.7.0 + - name: Run default tests with nextest + run: cargo nextest run --locked + - name: Run no-default-features tests with nextest + run: cargo nextest run --locked --no-default-features + - name: Run maximal Windows feature tests with nextest + run: cargo nextest run --locked --features media-controls,scrape,extra-audio-formats + - name: Run maximal Windows no-default-features tests with nextest + run: cargo nextest run --locked --no-default-features --features media-controls,scrape,extra-audio-formats + - name: Check curated Windows feature combinations + run: cargo fc check --locked --all-targets + + macos: + runs-on: macos-latest + steps: + - uses: actions/checkout@v5 + - name: Set up Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + - name: Install test tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-nextest@0.9.140 cargo-feature-combinations@0.7.0 + - name: Run default tests with nextest + run: cargo nextest run --locked + - name: Run no-default-features tests with nextest + run: cargo nextest run --locked --no-default-features + - name: Run maximal macOS feature tests with nextest + run: cargo nextest run --locked --features scrape,extra-audio-formats + - name: Run maximal macOS no-default-features tests with nextest + run: cargo nextest run --locked --no-default-features --features scrape,extra-audio-formats + - name: Check curated macOS feature combinations + run: cargo fc check --locked --all-targets + + mutation: + if: github.event_name == 'workflow_dispatch' && inputs.run_mutations + uses: ./.github/workflows/mutation.yml diff --git a/.gitignore b/.gitignore index f5298cd..66bc073 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /target /cache -.DS_Store \ No newline at end of file +.DS_Store +mutants*.out diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 23a71c5..35b1a5b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,3 +28,52 @@ detracts from it's purpose. More complex features, like fancy colors or cover art, will not be accepted ever. Implementations of acceptable features should also be simple and not too obtrusive. Even if a feature is simple, if it is very complex to implement, then it won't be accepted. + +## Testing + +Install the pinned local tools: + +```sh +cargo install --locked cargo-nextest --version 0.9.140 +cargo install --locked cargo-feature-combinations --version 0.7.0 +cargo install --locked cargo-mutants --version 27.1.0 +``` + +Run `cargo fmt --check`, `cargo test --locked`, `cargo nextest run --locked`, +`cargo nextest run --locked --no-default-features`, and +`cargo fc check --locked --all-targets`. Linux needs ALSA development headers +(`libasound2-dev` on Ubuntu). The curated matrix includes only native platform +features: MPRIS on Linux and media controls on Windows. macOS uses the common +scraping and extra-audio features. + +The checked-in four-second MP3 and bounded localhost fixture make download and +decode tests independent of internet services and audio devices. Its generation +command and decoder tolerance are documented beside the fixture. + +Mutation inventories and passes are explicit: + +```sh +cargo mutants --list +cargo mutants +# Linux only +cargo mutants --config .cargo/mutants-mpris.toml --features mpris --list +cargo mutants --config .cargo/mutants-mpris.toml --features mpris +# Windows only +cargo mutants --config .cargo/mutants-media-controls.toml --features media-controls --list +cargo mutants --config .cargo/mutants-media-controls.toml --features media-controls +``` + +The default mutation scope covers configuration and terminal input mapping. +The terminal event loop is excluded with `mutants::skip`. The Linux scope covers +in-process MPRIS Player and Sender behavior; Server construction, D-Bus traffic, +and native property publication are excluded. The Windows scope covers event +mapping; native control construction, publication, teardown, and message pumping +are excluded. `sync_metadata` uses `mutants::skip` because struct-field mutants +cannot be excluded reliably by function-name regex. Packaging, fixtures, and +tests are outside mutation scopes. + +Treat surviving mutants as test gaps unless these boundaries explain them. +Inspect `mutants.out/missed.txt`, `timeout.txt`, `unviable.txt`, and +`outcomes.json`; timeouts and execution errors require investigation. Use +`cargo mutants --test-tool cargo` only when nextest is unavailable, and never +retry a failed nextest run automatically with another runner. diff --git a/Cargo.lock b/Cargo.lock index 210efa2..3b13d3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1567,6 +1567,7 @@ dependencies = [ "indicatif", "libc", "mpris-server", + "mutants", "reqwest", "rodio", "scraper", @@ -1655,6 +1656,12 @@ dependencies = [ "zbus", ] +[[package]] +name = "mutants" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc0287524726960e07b119cebd01678f852f147742ae0d925e6a520dca956126" + [[package]] name = "ndk" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index a02feda..095219c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,7 @@ html-escape = { version = "0.2.13", optional = true } indicatif = { version = "0.18.4", optional = true } [dev-dependencies] +mutants = "0.0.3" figment = { version = "0.10.19", default-features = false, features = ["env", "toml", "test"] } [target.'cfg(target_os = "linux")'.dependencies] @@ -80,3 +81,41 @@ windows = { version = "0.62", optional = true, features = [ "Win32_System_LibraryLoader", "Win32_UI_WindowsAndMessaging", ] } + +[package.metadata.cargo-fc] +# Curated rows keep feature-gate coverage useful without expanding to the full +# powerset. `default` is explicit because cargo-fc otherwise begins each row +# with `--no-default-features`. +allow_feature_sets = [ + [], + ["default"], + ["scrape"], + ["extra-audio-formats"], + ["default", "scrape", "extra-audio-formats"], +] + +[package.metadata.cargo-fc.target.'cfg(target_os = "linux")'] +allow_feature_sets = [ + [], + ["default"], + ["scrape"], + ["extra-audio-formats"], + ["default", "scrape", "extra-audio-formats"], + ["mpris"], + ["default", "mpris"], + ["mpris", "scrape", "extra-audio-formats"], + ["default", "mpris", "scrape", "extra-audio-formats"], +] + +[package.metadata.cargo-fc.target.'cfg(target_os = "windows")'] +allow_feature_sets = [ + [], + ["default"], + ["scrape"], + ["extra-audio-formats"], + ["default", "scrape", "extra-audio-formats"], + ["media-controls"], + ["default", "media-controls"], + ["media-controls", "scrape", "extra-audio-formats"], + ["default", "media-controls", "scrape", "extra-audio-formats"], +] diff --git a/src/scrapers.rs b/src/scrapers.rs index 0e28f5e..7708939 100644 --- a/src/scrapers.rs +++ b/src/scrapers.rs @@ -75,11 +75,11 @@ async fn get(client: &Client, path: &str, source: Source) -> eyre::Result Queued { + Queued::new( + format!("https://example.invalid/{name}.mp3"), + Bytes::from_static(TONE_MP3), + Some(name.to_owned()), + ) + .unwrap() +} + +pub fn http_client() -> Client { + Client::builder() + .no_proxy() + .connect_timeout(Duration::from_secs(1)) + .timeout(Duration::from_secs(2)) + .build() + .unwrap() +} + +pub struct Server { + base: String, + cancelled: Arc, + worker: Option>>, +} + +impl Server { + pub fn serve_once(body: &'static [u8]) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let base = format!("http://{}/", listener.local_addr().unwrap()); + let cancelled = Arc::new(AtomicBool::new(false)); + let cancelled_for_worker = cancelled.clone(); + let worker = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + if cancelled_for_worker.load(Ordering::Relaxed) { + return Ok(()); + } + match listener.accept() { + Ok((stream, _)) => return respond(stream, body), + Err(error) if error.kind() == io::ErrorKind::WouldBlock => { + if Instant::now() >= deadline { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "test client did not connect", + )); + } + thread::sleep(Duration::from_millis(10)); + } + Err(error) => return Err(error), + } + } + }); + Self { + base, + cancelled, + worker: Some(worker), + } + } + + pub fn base(&self) -> &str { + &self.base + } + + pub fn finish(mut self) -> io::Result<()> { + self.cancelled.store(true, Ordering::Relaxed); + self.worker.take().unwrap().join().unwrap() + } +} + +impl Drop for Server { + fn drop(&mut self) { + self.cancelled.store(true, Ordering::Relaxed); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +fn respond(mut stream: TcpStream, body: &[u8]) -> io::Result<()> { + stream.set_nonblocking(false)?; + stream.set_read_timeout(Some(Duration::from_secs(2)))?; + stream.set_write_timeout(Some(Duration::from_secs(2)))?; + let mut request = Vec::with_capacity(1024); + let mut chunk = [0; 512]; + while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") { + let read = stream.read(&mut chunk)?; + if read == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "incomplete request", + )); + } + request.extend_from_slice(&chunk[..read]); + if request.len() > 8 * 1024 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "request headers too large", + )); + } + } + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: audio/mpeg\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + )?; + stream.write_all(body)?; + stream.flush() +} diff --git a/src/tests/fixtures/README.md b/src/tests/fixtures/README.md new file mode 100644 index 0000000..fe38db6 --- /dev/null +++ b/src/tests/fixtures/README.md @@ -0,0 +1,13 @@ +# Test tone fixture + +`test-tone.mp3` is a checked-in, deterministic four-second 440 Hz sine wave. +It is mono, 44.1 kHz, and encoded as MP3 at 64 kb/s. The decoder test accepts +a reported duration from three to five seconds to allow MP3 encoder padding. + +Regenerate it with FFmpeg from the repository root: + +```sh +ffmpeg -f lavfi -i 'sine=frequency=440:sample_rate=44100:duration=4' \ + -ac 1 -c:a libmp3lame -b:a 64k -write_xing 1 \ + -y src/tests/fixtures/test-tone.mp3 +``` diff --git a/src/tests/fixtures/test-tone.mp3 b/src/tests/fixtures/test-tone.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..b6d5a693ebd5ec336948a7f8121c975460ce2aff GIT binary patch literal 32643 zcmZ^qWmJ=Y*vD6l8Xb<57Rk{eNcTXxgg+bIAt9xXu7OBMD4%{2O;Qnys?|WUhhO!6*aPwj_G%!%XT}c4|FcR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FGNE9-1 z6PWRE-i6V==@E)gOh2T@C=$|^n#o>QibsyumUMnQq8{d3HFs3*{BgX6zG=1A_3{a= z%WnLSQgDCKG0ITt#doP1?3`sdJW=PZ4PM%59@g za{GQ>n84?0+$5cLf_8@Ej`+hE&62?Dp&wf7jZLB|ur+@3naqxhMi{u0Cl!R&fDxgd zr{0jGg-KW&r2XfLJG&3PeUUE*hJ1DejHKKa>(U%Jv{Ge4=$JIkUBro+Nc&Gs(_IXi zB#lluJB*cv-^zacbfH6&7guT)SE}9^`dxvBg5;&C&h;pehaA=qy+eeV{9bW83|kE{ z`YYcSwnFOI+~qg@Fms}`Bcl3qBwSQ0jSNu77I!C$nb5R}$;v;4=YsqpZgGg7FB8JV z#?Y5HA#^ly?;`cnh2I3bdim|oTd%G~e*VGzQEPQs+R?D5aIdcAWz$5(@nz86%P}`c zCq>j7oDeLaD=;OgKUnCjc*qbp536FG;8yl#c-?{;BZ;=PU1YLVA@M?Og!SW}hvAe{ zb~;bQ9t@ zZ0>ARvDAI*-m67gv-GK9Fp?O=2*qP%!hmxXMz|;jN0btwqr$XOql$SlP##1KhGv5v zgM;G3Kyx`T#AqW7SepR~$t8e-HbCi4$KD^>!C)LjUML)dPefL|K2B(`Rw7ARK#=$K z+9>!4O!WDm&UhTCVgX(K2|`d8gj_yG@=w9MARSNWUL-{>j-_mq*z)-sk0Pe@?1DcA zZlD;mI)moN4}f)q@9sl@dPd&gJ;{m!fzbF&*@GF!C!2U3op!fNzkPLe{2LJ8X|M3t0x1aPs`T^{c+XGR;Er`X> u&|v$tviB0T;Q!Gl{xAPB7EoSTCkUsI31G8 = decoded.data.by_ref().take(2_048).collect(); + assert!(!samples.is_empty()); + assert!(samples.iter().all(|sample| sample.is_finite())); } } diff --git a/src/tests/ui.rs b/src/tests/ui.rs index 0be3aff..566bd10 100644 --- a/src/tests/ui.rs +++ b/src/tests/ui.rs @@ -83,8 +83,13 @@ mod window { let (render, height) = w.render(vec![String::from("abc")]).unwrap(); const MIDDLE: &str = "─────"; - assert_eq!(format!("┌{MIDDLE}┐\n{}\n└{MIDDLE}┘", sided("abc")), render); - assert_eq!(height, 3); + assert_eq!( + format!("┌{MIDDLE}┐\n{}\n└{MIDDLE}┘", sided("abc")).trim_end(), + render.trim_end() + ); + // Crossterm's Windows backend includes the final terminal row while + // its Unix backend does not; both renderings contain three lines. + assert_eq!(height, if cfg!(windows) { 4 } else { 3 }); } #[test] @@ -106,9 +111,9 @@ mod window { sided(" b "), sided("c "), ), - render + render.trim_end() ); - assert_eq!(height, 5); + assert_eq!(height, if cfg!(windows) { 6 } else { 5 }); } #[test] diff --git a/src/ui/input.rs b/src/ui/input.rs index c18f281..4031283 100644 --- a/src/ui/input.rs +++ b/src/ui/input.rs @@ -7,6 +7,7 @@ use futures_util::{FutureExt, StreamExt}; use tokio::sync::mpsc::Sender; /// Starts the listener to receive input from the terminal for various events. +#[cfg_attr(test, mutants::skip)] pub async fn listen(sender: Sender, bindings: BindingMap) -> super::Result<()> { let mut reader = EventStream::new(); diff --git a/src/ui/media_controls.rs b/src/ui/media_controls.rs index 2c72117..28fc7f8 100644 --- a/src/ui/media_controls.rs +++ b/src/ui/media_controls.rs @@ -4,9 +4,7 @@ use std::sync::Arc; use std::time::Duration; -use souvlaki::{ - MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, PlatformConfig, -}; +use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, PlatformConfig}; use tokio::sync::{broadcast, mpsc}; use crate::player::Current; @@ -137,6 +135,7 @@ impl Server { .map_err(|e| ui::Error::MediaControls(format!("{e:?}"))) } + #[cfg_attr(test, mutants::skip)] fn sync_metadata(&mut self) -> ui::Result<()> { let (title, duration) = match &self.current { Current::Loading(_) => ("Loading...", None), @@ -154,6 +153,44 @@ impl Server { } } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn media_events_map_without_initializing_native_controls() { + assert_eq!( + Server::map_event(MediaControlEvent::Play), + Some(Message::Play) + ); + assert_eq!( + Server::map_event(MediaControlEvent::Stop), + Some(Message::Pause) + ); + assert_eq!( + Server::map_event(MediaControlEvent::Pause), + Some(Message::Pause) + ); + assert_eq!( + Server::map_event(MediaControlEvent::Toggle), + Some(Message::PlayPause) + ); + assert_eq!( + Server::map_event(MediaControlEvent::Next), + Some(Message::Next) + ); + assert_eq!( + Server::map_event(MediaControlEvent::Quit), + Some(Message::Quit) + ); + assert_eq!( + Server::map_event(MediaControlEvent::SetVolume(0.25)), + Some(Message::SetVolume(0.25)) + ); + assert_eq!(Server::map_event(MediaControlEvent::Previous), None); + } +} + /// Minimal hidden window + Win32 message pump required by SMTC. mod windows { use std::io::Error; @@ -164,8 +201,8 @@ mod windows { use ::windows::Win32::System::LibraryLoader::GetModuleHandleW; use ::windows::Win32::UI::WindowsAndMessaging::{ CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, PeekMessageW, - RegisterClassExW, TranslateMessage, MSG, PM_REMOVE, WINDOW_EX_STYLE, WINDOW_STYLE, - WM_QUIT, WNDCLASSEXW, + RegisterClassExW, TranslateMessage, MSG, PM_REMOVE, WINDOW_EX_STYLE, WINDOW_STYLE, WM_QUIT, + WNDCLASSEXW, }; pub struct DummyWindow { @@ -242,4 +279,4 @@ mod windows { } } } -} \ No newline at end of file +} diff --git a/src/ui/mpris.rs b/src/ui/mpris.rs index 409a742..0a31c0b 100644 --- a/src/ui/mpris.rs +++ b/src/ui/mpris.rs @@ -361,3 +361,133 @@ impl Server { }) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{tests::fixture, tracks::Info}; + use rodio::queue::SourcesQueueOutput; + use std::{sync::Arc, time::Duration}; + + fn player( + _can_go_previous: bool, + ) -> ( + Player, + mpsc::Receiver, + Arc, + SourcesQueueOutput, + ) { + let (sink, output) = rodio::Player::new(); + let sink = Arc::new(sink); + let (sender, receiver) = mpsc::channel(1); + ( + Player { + sink: sink.clone(), + current: ArcSwap::new(Arc::new(Current::default())), + list: String::from("test"), + sender: Sender::new(sender), + }, + receiver, + sink, + output, + ) + } + + #[tokio::test] + async fn playback_commands_are_forwarded_to_the_command_channel() { + let (player, mut receiver, _, _) = player(false); + player.play().await.unwrap(); + assert_eq!(receiver.try_recv(), Ok(Message::Play)); + player.pause().await.unwrap(); + assert_eq!(receiver.try_recv(), Ok(Message::Pause)); + player.play_pause().await.unwrap(); + assert_eq!(receiver.try_recv(), Ok(Message::PlayPause)); + player.next().await.unwrap(); + assert_eq!(receiver.try_recv(), Ok(Message::Next)); + player.stop().await.unwrap(); + assert_eq!(receiver.try_recv(), Ok(Message::Quit)); + player.quit().await.unwrap(); + assert_eq!(receiver.try_recv(), Ok(Message::Quit)); + player.set_volume(0.25).await.unwrap(); + assert_eq!(receiver.try_recv(), Ok(Message::SetVolume(0.25))); + } + + #[tokio::test] + async fn closed_command_channel_returns_an_error() { + let (player, receiver, _, _) = player(false); + drop(receiver); + assert!(player.play().await.is_err()); + } + + #[tokio::test] + async fn player_properties_and_metadata_follow_playback_state() { + let (player, _, sink, mut output) = player(true); + assert!(player.raise().await.is_err()); + assert!(player.can_quit().await.unwrap()); + assert!(!player.fullscreen().await.unwrap()); + player.set_fullscreen(true).await.unwrap(); + assert!(!player.can_set_fullscreen().await.unwrap()); + assert!(!player.can_raise().await.unwrap()); + assert!(!player.has_track_list().await.unwrap()); + assert_eq!(player.identity().await.unwrap(), "lowfi"); + assert_eq!(player.desktop_entry().await.unwrap(), "dev.talwat.lowfi"); + assert_eq!( + player.supported_uri_schemes().await.unwrap(), + vec!["https".to_owned()] + ); + assert_eq!( + player.supported_mime_types().await.unwrap(), + vec!["audio/mpeg".to_owned()] + ); + assert_eq!( + player.playback_status().await.unwrap(), + PlaybackStatus::Stopped + ); + assert!(player.seek(Time::ZERO).await.is_err()); + assert!(player + .set_position(TrackId::NO_TRACK, Time::ZERO) + .await + .is_err()); + assert!(player + .open_uri("https://example.invalid".into()) + .await + .is_err()); + assert!(player.loop_status().await.is_err()); + player.set_loop_status(LoopStatus::None).await.unwrap(); + assert!(player.shuffle().await.unwrap()); + player.set_shuffle(false).await.unwrap(); + assert_eq!(player.volume().await.unwrap(), 1.0); + assert_eq!(player.rate().await.unwrap(), 1.0); + assert_eq!(player.position().await.unwrap(), Time::ZERO); + assert_eq!(player.minimum_rate().await.unwrap(), 0.2); + assert_eq!(player.maximum_rate().await.unwrap(), 3.0); + assert!(player.can_go_next().await.unwrap()); + assert!(!player.can_go_previous().await.unwrap()); + assert!(player.can_play().await.unwrap()); + assert!(player.can_pause().await.unwrap()); + assert!(!player.can_seek().await.unwrap()); + assert!(player.can_control().await.unwrap()); + + sink.append(fixture::queued("position").decode().unwrap().data); + for _ in 0..1_024 { + assert!(output.next().is_some_and(|sample| sample.is_finite())); + } + assert!(player.position().await.unwrap() > Time::ZERO); + + player.current.store(Arc::new(Current::Track(Info { + path: "https://example.invalid/tone.mp3".into(), + display: "Test Tone".into(), + width: 9, + duration: Some(Duration::from_secs(4)), + }))); + let metadata = player.metadata().await.unwrap(); + assert_eq!(metadata.title(), Some("Test Tone")); + assert_eq!(metadata.album(), Some("test")); + assert_eq!(metadata.length(), Some(Time::from_secs(4))); + assert!(metadata.trackid().is_some()); + assert_eq!( + player.playback_status().await.unwrap(), + PlaybackStatus::Playing + ); + } +} From 6e23a61d588bc2410023dbf216982bb6ed638479 Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:15:31 -0400 Subject: [PATCH 07/12] docs(testing): explain fixture contracts and repair rustdoc links --- .cargo/mutants-mpris.toml | 5 +++-- .github/workflows/tooling.yml | 2 ++ src/downloader.rs | 5 +++-- src/message.rs | 6 +++--- src/tests/fixture.rs | 16 ++++++++++++++++ src/tests/ui.rs | 4 ++-- src/tracks.rs | 21 ++++++++------------- src/tracks/format.rs | 7 +++---- src/ui.rs | 2 +- src/ui/interface/window.rs | 2 +- src/ui/media_controls.rs | 3 +++ src/ui/mpris.rs | 4 ++++ 12 files changed, 49 insertions(+), 28 deletions(-) diff --git a/.cargo/mutants-mpris.toml b/.cargo/mutants-mpris.toml index 04e8eb1..f76f0ab 100644 --- a/.cargo/mutants-mpris.toml +++ b/.cargo/mutants-mpris.toml @@ -3,8 +3,9 @@ examine_globs = ["src/ui/mpris.rs"] exclude_globs = ["packaging/**", "src/tests/**", "tests/**", "target/**"] # Server creates a real D-Bus service and publishes native properties. Those -# event-loop and bus interactions are covered by native feature CI, not mutation -# tests. The Player and Sender remain in scope. +# event-loop and bus interactions need live integration validation. Native CI +# builds the adapter and tests in-process behavior; it does not exercise a bus. +# The Player and Sender remain in scope. exclude_re = ["Server::"] additional_cargo_args = ["--locked"] test_tool = "nextest" diff --git a/.github/workflows/tooling.yml b/.github/workflows/tooling.yml index 98fa2fa..e53947e 100644 --- a/.github/workflows/tooling.yml +++ b/.github/workflows/tooling.yml @@ -83,6 +83,8 @@ jobs: - name: Check curated macOS feature combinations run: cargo fc check --locked --all-targets + # Each mutation rebuilds/tests changed code. Keep this deeper investigation + # opt-in so normal PR feedback stays bounded; reports still expose failures. mutation: if: github.event_name == 'workflow_dispatch' && inputs.run_mutations uses: ./.github/workflows/mutation.yml diff --git a/src/downloader.rs b/src/downloader.rs index 802c888..c86d261 100644 --- a/src/downloader.rs +++ b/src/downloader.rs @@ -62,7 +62,7 @@ pub struct Downloader { queue: mpsc::Sender, /// The [`mpsc::Sender`] which is used to inform the - /// [`crate::Player`] with [`crate::Message::Loaded`]. + /// [`crate::player::Player`] with [`crate::Message::Loaded`]. tx: mpsc::Sender, /// The list of tracks to download from. @@ -184,7 +184,8 @@ impl Handle { impl crate::Tasks { /// Initializes the downloader with a track list. /// - /// `tx` specifies the [`Sender`] to be notified with [`crate::Message::Loaded`]. + /// Uses the owning task group's command sender for [`crate::Message::Loaded`] + /// notifications when a track arrives after the player has entered loading. pub fn downloader( &mut self, settings: &crate::config::Settings, diff --git a/src/message.rs b/src/message.rs index 8535c72..8152b50 100644 --- a/src/message.rs +++ b/src/message.rs @@ -14,13 +14,13 @@ pub enum Message { /// Similar to Next, but specific to the first track. Init, - /// Unpause the [Sink]. + /// Resume playback. Play, - /// Pauses the [Sink]. + /// Pause playback. Pause, - /// Pauses the [Sink]. This will also unpause it if it is paused. + /// Toggle playback between paused and playing. PlayPause, /// Change the volume of playback. diff --git a/src/tests/fixture.rs b/src/tests/fixture.rs index 37dc2e2..16b8611 100644 --- a/src/tests/fixture.rs +++ b/src/tests/fixture.rs @@ -20,6 +20,7 @@ use crate::tracks::Queued; /// `ffmpeg -f lavfi -i sine=frequency=440:sample_rate=44100:duration=4 -ac 1 -c:a libmp3lame -b:a 64k -write_xing 1 test-tone.mp3`. pub const TONE_MP3: &[u8] = include_bytes!("fixtures/test-tone.mp3"); +/// Builds a queued fixture without downloading; its URL is only a track identifier. pub fn queued(name: &str) -> Queued { Queued::new( format!("https://example.invalid/{name}.mp3"), @@ -29,6 +30,8 @@ pub fn queued(name: &str) -> Queued { .unwrap() } +/// A bounded loopback-test client that ignores environment proxy settings. +/// Fixture requests must stay local even on machines with HTTP proxies configured. pub fn http_client() -> Client { Client::builder() .no_proxy() @@ -38,6 +41,10 @@ pub fn http_client() -> Client { .unwrap() } +/// Owns one loopback listener and its worker thread. +/// +/// Dropping the server cancels pending acceptance and joins the worker, discarding +/// worker failures. Use [`Self::finish`] when the test must inspect I/O errors. pub struct Server { base: String, cancelled: Arc, @@ -45,6 +52,10 @@ pub struct Server { } impl Server { + /// Serves at most one request on an OS-assigned port. + /// + /// Acceptance is bounded to five seconds; accepted-stream reads and writes + /// each have a two-second timeout. The fixture needs no internet service. pub fn serve_once(body: &'static [u8]) -> Self { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); @@ -83,6 +94,11 @@ impl Server { &self.base } + /// Cancels pending acceptance, joins the worker, and returns its I/O result. + /// + /// Success does not prove a request was served: cancellation before a client + /// connects also succeeds. Assert the HTTP result separately. Worker panics + /// propagate here, whereas `Drop` discards both I/O errors and worker panics. pub fn finish(mut self) -> io::Result<()> { self.cancelled.store(true, Ordering::Relaxed); self.worker.take().unwrap().join().unwrap() diff --git a/src/tests/ui.rs b/src/tests/ui.rs index 566bd10..c43e367 100644 --- a/src/tests/ui.rs +++ b/src/tests/ui.rs @@ -87,8 +87,8 @@ mod window { format!("┌{MIDDLE}┐\n{}\n└{MIDDLE}┘", sided("abc")).trim_end(), render.trim_end() ); - // Crossterm's Windows backend includes the final terminal row while - // its Unix backend does not; both renderings contain three lines. + // Lowfi's renderer adds a final row on Windows to avoid repeatedly + // writing to the terminal's last line; the visible content is identical. assert_eq!(height, if cfg!(windows) { 4 } else { 3 }); } diff --git a/src/tracks.rs b/src/tracks.rs index c2fa33f..58b7a4f 100644 --- a/src/tracks.rs +++ b/src/tracks.rs @@ -23,7 +23,7 @@ pub use error::{Error, Result}; use crate::tracks::error::WithTrackContext as _; -/// Just a shorthand for a decoded [Bytes]. +/// Lazy audio decoder backed by in-memory compressed [`Bytes`]. pub type DecodedData = Decoder>; /// Tracks which are still waiting in the queue, and can't be played yet. @@ -53,9 +53,8 @@ impl Debug for Queued { } impl Queued { - /// This will actually decode and format the track, - /// returning a [`DecodedTrack`] which can be played - /// and also has a duration & formatted name. + /// Decodes the stored audio and derives playback metadata in a [`Decoded`]. + /// Returns an error if the audio cannot be decoded. pub fn decode(self) -> Result { Decoded::new(self) } @@ -75,10 +74,8 @@ impl Queued { } } -/// The [`Info`] struct, which has the name and duration of a track. -/// -/// This is not included in [Track] as the duration has to be acquired -/// from the decoded data and not from the raw data. +/// Track metadata derived when compressed audio is prepared for playback. +/// Duration is discovered through the decoder, so it is not part of [`Queued`]. #[derive(Debug, Eq, PartialEq, Clone)] pub struct Info { /// The full downloadable path/url of the track. @@ -87,8 +84,7 @@ pub struct Info { /// This is a formatted name, so it doesn't include the full path. pub display: String, - /// This is the *actual* terminal width of the track name, used to make - /// the UI consistent. + /// Grapheme count used to size the track name in the terminal UI. pub width: usize, /// The duration of the track, this is an [Option] because there are @@ -117,8 +113,7 @@ impl Info { } } -/// This struct is separate from [Track] since it is generated lazily from -/// a track, and not when the track is first downloaded. +/// Audio decoder and metadata created from a [`Queued`] track at playback time. pub struct Decoded { /// Has both the formatted name and some information from the decoded data. pub info: Info, @@ -129,7 +124,7 @@ pub struct Decoded { impl Decoded { /// Creates a new track. - /// This is equivalent to [`QueuedTrack::decode`]. + /// This is equivalent to [`Queued::decode`]. pub fn new(track: Queued) -> Result { let (path, display) = (track.path.clone(), track.display.clone()); let data = Decoder::builder() diff --git a/src/tracks/format.rs b/src/tracks/format.rs index f59b223..761ff95 100644 --- a/src/tracks/format.rs +++ b/src/tracks/format.rs @@ -12,11 +12,10 @@ fn decode_url(text: &str) -> String { .collect() } -/// Formats a name with [`convert_case`]. +/// Derives a display name from the file stem and URL-decodes it. /// -/// This will also strip the first few numbers that are -/// usually present on most lofi tracks and do some other -/// formatting operations. +/// Leading ASCII digits, dots, and parentheses are stripped unless they make up +/// the whole decoded stem. Surrounding whitespace is trimmed. pub fn name(name: &str) -> super::Result { let path = Path::new(name); diff --git a/src/ui.rs b/src/ui.rs index 1d24f53..e8f3ff2 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -18,7 +18,7 @@ pub mod mpris; #[cfg(all(feature = "media-controls", windows))] pub mod media_controls; -/// Shorthand for a [`Result`] with a [`ui::Error`]. +/// UI-specific result type with [`Error`] as its error. type Result = std::result::Result; /// The error type for the UI, which is used to handle errors diff --git a/src/ui/interface/window.rs b/src/ui/interface/window.rs index cfae245..79c3a48 100644 --- a/src/ui/interface/window.rs +++ b/src/ui/interface/window.rs @@ -27,7 +27,7 @@ pub struct Window { /// Whether content items should be automatically padded (spaced). spaced: bool, - /// Whether to cautiously handle ANSI sequences by adding [`style::Attribute::Reset`] generously. + /// Whether to reset styling with [`crossterm::style::Attribute::Reset`]. fancy: bool, } diff --git a/src/ui/media_controls.rs b/src/ui/media_controls.rs index 28fc7f8..3fa3d31 100644 --- a/src/ui/media_controls.rs +++ b/src/ui/media_controls.rs @@ -155,6 +155,9 @@ impl Server { #[cfg(test)] mod tests { + //! Check event mapping without constructing SMTC or running a desktop pump. + //! Native registration, publication and teardown need separate integration checks. + use super::*; #[test] diff --git a/src/ui/mpris.rs b/src/ui/mpris.rs index 0a31c0b..adb7a61 100644 --- a/src/ui/mpris.rs +++ b/src/ui/mpris.rs @@ -364,6 +364,10 @@ impl Server { #[cfg(test)] mod tests { + //! Call the interface methods directly to test Lowfi's command/state contract. + //! No D-Bus service is registered; bus traffic and property signals need live + //! integration validation beyond these in-process checks. + use super::*; use crate::{tests::fixture, tracks::Info}; use rodio::queue::SourcesQueueOutput; From ce756af703c53aab299a6ea1d1ca153b7249412b Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:43:39 -0400 Subject: [PATCH 08/12] docs(testing): explain coordinated tool upgrades --- CONTRIBUTING.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 35b1a5b..56c865b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,6 +39,20 @@ cargo install --locked cargo-feature-combinations --version 0.7.0 cargo install --locked cargo-mutants --version 27.1.0 ``` +These versions match CI. `--version` selects the tool release; `--locked` uses +that release's packaged dependency lockfile. New releases are not installed +automatically. See the [Cargo installation reference](https://doc.rust-lang.org/cargo/commands/cargo-install.html#dealing-with-the-lockfile). + +To evaluate a newer release locally, replace its `--version` value above and +keep `--locked`. Review the release notes and required Rust version; test tools +may require a newer compiler than Lowfi itself. When adopting the release, +update the version here and wherever that tool is installed in +`.github/workflows/tooling.yml` and `.github/workflows/mutation.yml` together. +Verify default/no-default Nextest runs, curated feature checks, and mutation +inventories on the affected native platforms. Run targeted mutation passes if +the upgrade changes mutation behavior. Commit the version updates and validation +results together so contributors and CI use the same tested baseline. + Run `cargo fmt --check`, `cargo test --locked`, `cargo nextest run --locked`, `cargo nextest run --locked --no-default-features`, and `cargo fc check --locked --all-targets`. Linux needs ALSA development headers From 0bf3c9e6906a2831a2e48ddbd15fa43df8d4c6ac Mon Sep 17 00:00:00 2001 From: aRustyDev <36318507+aRustyDev@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:21:48 -0400 Subject: [PATCH 09/12] feat: add bounded playback history with generation-aware completion --- .cargo/mutants.toml | 4 +- CONTRIBUTING.md | 5 + README.md | 10 ++ src/audio/waiter.rs | 135 ++++++++++++--- src/config.rs | 19 +++ src/downloader.rs | 10 ++ src/history.rs | 116 +++++++++++++ src/main.rs | 1 + src/message.rs | 7 + src/player.rs | 402 ++++++++++++++++++++++++++++++++++++++------ src/tracks.rs | 2 +- src/ui.rs | 17 ++ src/ui/input.rs | 3 +- src/ui/interface.rs | 5 + src/ui/mpris.rs | 97 +++++++++-- 15 files changed, 731 insertions(+), 102 deletions(-) create mode 100644 src/history.rs diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 1f55c8b..7bb7b62 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -2,6 +2,8 @@ # adapters have dedicated configurations because their compiled feature sets # and test boundaries differ by platform. examine_globs = [ + "src/history.rs", + "src/player.rs", "src/config.rs", "src/ui/input.rs", ] @@ -13,7 +15,7 @@ exclude_globs = [ ] # EventStream owns a terminal event loop and cannot be exercised without a # terminal. `message_for` below it remains in scope. -exclude_re = ["listen", "Player::close"] +exclude_re = ["listen", "Player::close", "Player::init", "Player::run"] additional_cargo_args = ["--locked"] test_tool = "nextest" minimum_test_timeout = 20 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 56c865b..b9a0037 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -91,3 +91,8 @@ Inspect `mutants.out/missed.txt`, `timeout.txt`, `unviable.txt`, and `outcomes.json`; timeouts and execution errors require investigation. Use `cargo mutants --test-tool cargo` only when nextest is unavailable, and never retry a failed nextest run automatically with another runner. + +History mutation coverage includes the bounded model and player transitions. +Player initialization, persistence, and the native command loop are excluded; +dispatch tests use an in-memory terminal handle, and waiter tests render audio +without a device. MPRIS adapter tests need no session bus. diff --git a/README.md b/README.md index 96964f3..3926c33 100644 --- a/README.md +++ b/README.md @@ -329,3 +329,13 @@ file:///home/user/Other Music/second-file.mp3 ``` Further examples can be found in the [data](https://github.com/talwat/lowfi/tree/main/data) folder. + +### Playback history + +Lowfi retains the current track and ten previous tracks as compressed audio for +the current session. Press `h` (configurable as `bindings.previous`), use a +terminal Previous media key, or use Linux MPRIS Previous. At three seconds or +later Previous restarts the current track; earlier it selects a retained previous +track. Next traverses retained forward tracks before downloading again. During +loading, Previous returns to the retained current track. The terminal layout and +displayed control bar stay unchanged. Windows SMTC Previous remains unavailable. diff --git a/src/audio/waiter.rs b/src/audio/waiter.rs index 7e64ce3..d23fe73 100644 --- a/src/audio/waiter.rs +++ b/src/audio/waiter.rs @@ -1,52 +1,133 @@ -use std::{sync::Arc, time::Duration}; +//! Watches the current playback generation without owning an audio device. +use std::{sync::Arc, time::Duration}; use tokio::{ - sync::{mpsc, Notify}, + sync::{mpsc, watch}, time, }; -/// Background loop that waits for the sink to drain and then attempts -/// to send a `Message::Next` to the provided channel. async fn waiter( sink: Arc, tx: mpsc::Sender, - notify: Arc, + mut generations: watch::Receiver, ) -> crate::Result<()> { - loop { - notify.notified().await; - - while !sink.empty() { - time::sleep(Duration::from_millis(16)).await; - } - - if tx.try_send(crate::Message::Next).is_err() { - break Ok(()); + while generations.changed().await.is_ok() { + let mut generation = *generations.borrow_and_update(); + let mut previous_announced = false; + loop { + tokio::select! { + changed = generations.changed() => { + if changed.is_err() { return Ok(()); } + generation = *generations.borrow_and_update(); + previous_announced = false; + } + _ = time::sleep(Duration::from_millis(16)) => { + if !previous_announced && sink.get_pos() >= crate::history::History::RESTART_AFTER { + tx.send(crate::Message::PreviousAvailable(generation)).await?; + previous_announced = true; + } + if sink.empty() { + tx.send(crate::Message::Finished(generation)).await?; + break; + } + } + } } } + Ok(()) } -/// Lightweight helper that waits for the current sink to drain and then -/// notifies the player to advance to the next track. +/// Publishes the generation whose playback should be observed. pub struct Handle { - /// Notification primitive used to wake the waiter. - notify: Arc, + generations: watch::Sender, } impl Handle { - /// Notify the waiter that playback state may have changed and it should - /// re-check the sink emptiness condition. - pub fn notify(&self) { - self.notify.notify_one(); + #[cfg(test)] + pub(crate) fn idle() -> Self { + let (generations, _) = watch::channel(0); + Self { generations } + } + + pub fn notify(&self, generation: u64) { + self.generations.send_replace(generation); } } impl crate::Tasks { - /// Create a new `Handle` which watches the provided `sink` and sends - /// `Message::Next` down `tx` when the sink becomes empty. pub fn waiter(&mut self, sink: Arc) -> Handle { - let notify = Arc::new(Notify::new()); - self.spawn(waiter(sink, self.tx(), notify.clone())); + let (generations, receiver) = watch::channel(0); + self.spawn(waiter(sink, self.tx(), receiver)); + Handle { generations } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{tests::fixture, Message}; + + #[tokio::test] + async fn observes_restart_threshold_and_completion_from_real_playback() { + let (sink, mut output) = rodio::Player::new(); + let sink = Arc::new(sink); + sink.append(fixture::queued("waiter").decode().unwrap().data); + let (sender, mut messages) = mpsc::channel(8); + let (generations, receiver) = watch::channel(0); + let task = tokio::spawn(waiter(sink.clone(), sender, receiver)); + let handle = Handle { generations }; + handle.notify(7); + for _ in 0..160_000 { + output.next().unwrap(); + } + assert!(sink.get_pos() >= crate::history::History::RESTART_AFTER); + assert_eq!( + time::timeout(Duration::from_secs(1), messages.recv()) + .await + .unwrap(), + Some(Message::PreviousAvailable(7)) + ); + for _ in 0..100_000 { + output.next().unwrap(); + } + assert!(sink.empty()); + assert_eq!( + time::timeout(Duration::from_secs(1), messages.recv()) + .await + .unwrap(), + Some(Message::Finished(7)) + ); + assert!(messages.try_recv().is_err()); + drop(handle); + time::timeout(Duration::from_secs(1), task) + .await + .unwrap() + .unwrap() + .unwrap(); + } - Handle { notify } + #[tokio::test] + async fn replaces_pending_generations_and_closes_cleanly() { + let (sink, _) = rodio::Player::new(); + let (sender, mut messages) = mpsc::channel(8); + let (generations, receiver) = watch::channel(0); + let task = tokio::spawn(waiter(Arc::new(sink), sender, receiver)); + let handle = Handle { generations }; + handle.notify(1); + tokio::task::yield_now().await; + handle.notify(2); + assert_eq!( + time::timeout(Duration::from_secs(1), messages.recv()) + .await + .unwrap(), + Some(Message::Finished(2)) + ); + assert!(messages.try_recv().is_err()); + drop(handle); + time::timeout(Duration::from_secs(1), task) + .await + .unwrap() + .unwrap() + .unwrap(); } } diff --git a/src/config.rs b/src/config.rs index cc9bb65..ec88305 100644 --- a/src/config.rs +++ b/src/config.rs @@ -62,6 +62,7 @@ pub struct Ui { pub struct Bindings { pub play_pause: Vec, pub next: Vec, + pub previous: Vec, pub quit: Vec, pub bookmark: Vec, pub volume_up: Vec, @@ -91,6 +92,7 @@ impl Default for Settings { bindings: Bindings { play_pause: vec!["p".into(), "Space".into()], next: vec!["s".into(), "n".into(), "l".into()], + previous: vec!["h".into()], quit: vec!["q".into()], bookmark: vec!["b".into()], volume_up: vec!["+".into(), "=".into(), "k".into(), "Up".into()], @@ -277,6 +279,7 @@ impl BindingMap { let groups = [ ("play_pause", &bindings.play_pause, Message::PlayPause), ("next", &bindings.next, Message::Next), + ("previous", &bindings.previous, Message::Previous), ("quit", &bindings.quit, Message::Quit), ("bookmark", &bindings.bookmark, Message::Bookmark), ("volume_up", &bindings.volume_up, Message::ChangeVolume(0.1)), @@ -339,6 +342,7 @@ fn action_for(message: Message) -> &'static str { match message { Message::PlayPause => "play_pause", Message::Next => "next", + Message::Previous => "previous", Message::Quit => "quit", Message::Bookmark => "bookmark", Message::ChangeVolume(change) if change > 0.09 => "volume_up", @@ -571,6 +575,7 @@ mod tests { for (message, expected) in [ (Message::PlayPause, "play_pause"), (Message::Next, "next"), + (Message::Previous, "previous"), (Message::Quit, "quit"), (Message::Bookmark, "bookmark"), (Message::ChangeVolume(0.1), "volume_up"), @@ -613,6 +618,20 @@ mod tests { ); } + #[test] + fn previous_binding_has_a_default_and_can_be_reassigned() { + Jail::expect_with(|jail| { + let (_, keys) = load(Path::new("missing.toml"), CliOverrides::default()).unwrap(); + assert_eq!(keys.message(&KeyCode::Char('h')), Some(Message::Previous)); + jail.create_file("custom.toml", "[bindings]\nprevious = [\"x\"]\n")?; + let (_, keys) = load(Path::new("custom.toml"), CliOverrides::default()).unwrap(); + assert_eq!(keys.message(&KeyCode::Char('x')), Some(Message::Previous)); + assert_eq!(keys.message(&KeyCode::Char('h')), None); + jail.create_file("duplicate.toml", "[bindings]\nprevious = [\"q\"]\n")?; + assert!(load(Path::new("duplicate.toml"), CliOverrides::default()).is_err()); + Ok(()) + }); + } #[test] fn legacy_environment_switches_do_not_enter_structured_settings() { Jail::expect_with(|jail| { diff --git a/src/downloader.rs b/src/downloader.rs index c86d261..84930d2 100644 --- a/src/downloader.rs +++ b/src/downloader.rs @@ -169,6 +169,16 @@ pub enum Output { } impl Handle { + #[cfg(test)] + pub(crate) fn with_tracks(tracks: impl IntoIterator) -> Self { + let tracks: Vec<_> = tracks.into_iter().collect(); + let (sender, queue) = mpsc::channel(tracks.len().max(1)); + for track in tracks { + sender.try_send(track).unwrap(); + } + Self { queue } + } + /// Gets either a queued track, or a progress report, /// depending on the state of the internal download buffer. #[rustfmt::skip] diff --git a/src/history.rs b/src/history.rs new file mode 100644 index 0000000..59d3256 --- /dev/null +++ b/src/history.rs @@ -0,0 +1,116 @@ +//! Bounded session-local compressed track history. + +use crate::tracks; +use std::{collections::VecDeque, time::Duration}; + +/// Session-local, compressed track history. +#[derive(Default)] +pub(crate) struct History { + tracks: VecDeque, + current: Option, +} + +impl History { + pub(crate) const CAPACITY: usize = 11; + pub(crate) const RESTART_AFTER: Duration = Duration::from_secs(3); + pub(crate) fn current(&self) -> Option<&tracks::Queued> { + self.current.and_then(|index| self.tracks.get(index)) + } + pub(crate) fn previous(&mut self) -> Option<&tracks::Queued> { + let index = self.current?.checked_sub(1)?; + self.current = Some(index); + self.current() + } + pub(crate) fn next(&mut self) -> Option<&tracks::Queued> { + let index = self.current?.checked_add(1)?; + if index >= self.tracks.len() { + return None; + } + self.current = Some(index); + self.current() + } + pub(crate) fn push(&mut self, track: tracks::Queued) { + self.tracks.push_back(track); + self.current = Some(self.tracks.len() - 1); + if self.tracks.len() > Self::CAPACITY { + self.tracks.pop_front(); + self.current = self.current.map(|index| index - 1); + } + } + pub(crate) fn has_previous(&self) -> bool { + self.current.is_some_and(|index| index > 0) + } + pub(crate) fn should_restart(position: Duration) -> bool { + position >= Self::RESTART_AFTER + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tracks::Queued; + use bytes::Bytes; + + fn track(name: &str) -> Queued { + Queued::new(name.into(), Bytes::from_static(b"audio"), Some(name.into())).unwrap() + } + + #[test] + fn history_is_bounded_and_evicts_oldest_track() { + let mut history = History::default(); + for index in 0..=History::CAPACITY { + history.push(track(&index.to_string())); + } + assert_eq!(history.tracks.len(), History::CAPACITY); + assert_eq!( + history.current().unwrap().display, + History::CAPACITY.to_string() + ); + assert_eq!( + history.previous().unwrap().display, + (History::CAPACITY - 1).to_string() + ); + while history.previous().is_some() {} + assert_eq!(history.current().unwrap().display, "1"); + } + + #[test] + fn history_keeps_forward_entries_after_going_back() { + let mut history = History::default(); + history.push(track("one")); + history.push(track("two")); + history.push(track("three")); + assert_eq!(history.previous().unwrap().display, "two"); + assert_eq!(history.next().unwrap().display, "three"); + assert!(history.next().is_none()); + } + + #[test] + fn history_has_no_previous_at_startup() { + let mut history = History::default(); + assert!(history.current().is_none()); + assert!(history.previous().is_none()); + assert!(!history.has_previous()); + } + + #[test] + fn previous_restart_threshold_is_three_seconds() { + assert!(!History::should_restart(Duration::from_millis(2999))); + assert!(History::should_restart(Duration::from_secs(3))); + } + + #[test] + fn history_returns_to_skipped_track_before_downloading() { + let mut history = History::default(); + history.push(track("one")); + history.push(track("two")); + history.push(track("three")); + assert_eq!(history.previous().unwrap().display, "two"); + assert_eq!(history.previous().unwrap().display, "one"); + assert_eq!(history.next().unwrap().display, "two"); + assert_eq!(history.next().unwrap().display, "three"); + assert!(history.next().is_none()); + assert_eq!(history.current().unwrap().display, "three"); + assert_eq!(history.tracks.len(), 3); + } +} diff --git a/src/main.rs b/src/main.rs index de3d4d3..a0a622b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ pub mod bookmark; pub mod config; pub mod downloader; pub mod error; +mod history; pub mod message; pub mod player; #[cfg(feature = "scrape")] diff --git a/src/message.rs b/src/message.rs index 8152b50..98c3376 100644 --- a/src/message.rs +++ b/src/message.rs @@ -6,6 +6,13 @@ pub enum Message { /// song is over by the waiter. Next, + /// Previous retained track, or restart after the three-second threshold. + Previous, + /// Automatic completion tagged with its playback generation. + Finished(u64), + /// The restart threshold was reached for this playback generation. + PreviousAvailable(u64), + /// When a track is loaded after the caller previously being told to wait. /// If a track is taken from the queue, then there is no waiting, so this /// is never actually sent. diff --git a/src/player.rs b/src/player.rs index c2fdbce..c65ecf0 100644 --- a/src/player.rs +++ b/src/player.rs @@ -1,5 +1,6 @@ //! The player, which contains all of the core logic behind the music player. +use crate::history::History; use std::sync::Arc; use tokio::sync::mpsc::{self, Receiver}; @@ -48,6 +49,8 @@ impl Current { pub struct Player { /// Persistent bookmark storage used by the player. bookmarks: Bookmarks, + history: History, + generation: u64, /// Current playback state (loading or track). current: Current, @@ -119,6 +122,8 @@ impl Player { waiter: tasks.waiter(Arc::clone(&sink)), bookmarks: Bookmarks::load().await?, current: Current::default(), + history: History::default(), + generation: 0, rx, sink, }; @@ -128,6 +133,7 @@ impl Player { /// Close any outlying processes, as well as persist state that /// should survive such as bookmarks and volume. + #[cfg_attr(test, mutants::skip)] pub async fn close(self) -> crate::Result<()> { self.sink.stop(); self.bookmarks.save().await?; @@ -136,79 +142,367 @@ impl Player { Ok(()) } - /// Play a queued track by decoding, appending to the sink and notifying - /// other subsystems that playback has changed. - pub fn play(&mut self, queued: tracks::Queued) -> crate::Result<()> { + fn can_go_previous(&self) -> bool { + self.history.has_previous() + || matches!(self.current, Current::Track(_)) + && History::should_restart(self.sink.get_pos()) + || self.current.loading() && self.history.current().is_some() + } + + fn update_previous_capability(&mut self) -> crate::Result<()> { + self.ui + .update(ui::Update::CanGoPrevious(self.can_go_previous())) + } + + fn play(&mut self, queued: tracks::Queued) -> crate::Result<()> { let decoded = queued.decode()?; + let paused = self.sink.is_paused(); + // Rodio drains a stopped source through the mixer. Resume long enough for that + // drain when changing tracks from a paused state, then restore the user's pause. + if paused { + self.sink.play(); + } + self.sink.stop(); self.sink.append(decoded.data); + if paused { + self.sink.pause(); + } self.set_current(Current::Track(decoded.info))?; - self.waiter.notify(); + self.generation = self.generation.wrapping_add(1); + self.waiter.notify(self.generation); + self.update_previous_capability()?; + Ok(()) + } + fn play_current_history(&mut self) -> crate::Result { + let Some(track) = self.history.current().cloned() else { + return Ok(false); + }; + self.play(track)?; + Ok(true) + } + + fn advance(&mut self) -> crate::Result<()> { + if let Some(track) = self.history.next().cloned() { + return self.play(track); + } + match self.downloader.track() { + downloader::Output::Loading(progress) => { + self.sink.stop(); + self.set_current(Current::Loading(progress))?; + self.update_previous_capability()?; + } + downloader::Output::Queued(queued) => { + self.history.push(queued); + self.play_current_history()?; + } + } Ok(()) } - /// Drives the main message loop of the player. - /// - /// This will return when a `Message::Quit` is received. It handles commands - /// coming from the frontend and updates playback/UI state accordingly. - pub async fn run(&mut self) -> crate::Result<()> { - while let Some(message) = self.rx.recv().await { - match message { - Message::Next | Message::Init | Message::Loaded => { - if message == Message::Next && self.current.loading() { - continue; - } - - self.sink.stop(); - match self.downloader.track() { - downloader::Output::Loading(progress) => { - self.set_current(Current::Loading(progress))?; - } - downloader::Output::Queued(queued) => self.play(queued)?, - } - } - Message::Play => { + fn previous(&mut self) -> crate::Result<()> { + if self.current.loading() { + let _ = self.play_current_history()?; + } else if History::should_restart(self.sink.get_pos()) { + let _ = self.play_current_history()?; + self.ui.update(ui::Update::Restarted)?; + } else if let Some(track) = self.history.previous().cloned() { + self.play(track)?; + } + self.update_previous_capability() + } + + /// Applies one command and publishes its observable state updates. + fn apply(&mut self, message: Message) -> crate::Result { + match message { + Message::Next if self.current.loading() => return Ok(false), + Message::Next | Message::Init => self.advance()?, + Message::Loaded if self.current.loading() => self.advance()?, + Message::Loaded => return Ok(false), + Message::Finished(generation) if generation == self.generation => self.advance()?, + Message::Finished(_) => return Ok(false), + Message::Previous => self.previous()?, + Message::PreviousAvailable(generation) if generation == self.generation => { + self.update_previous_capability()? + } + Message::PreviousAvailable(_) => return Ok(false), + Message::Play => { + self.sink.play(); + } + Message::Pause => { + self.sink.pause(); + } + Message::PlayPause => { + if self.sink.is_paused() { self.sink.play(); - } - Message::Pause => { + } else { self.sink.pause(); } - Message::PlayPause => { - if self.sink.is_paused() { - self.sink.play(); - } else { - self.sink.pause(); - } - } - Message::ChangeVolume(change) => { - self.sink - .set_volume((self.sink.volume() + change).clamp(0.0, 1.0)); - self.ui.update(ui::Update::Volume)?; - } - Message::SetVolume(set) => { - self.sink.set_volume(set.clamp(0.0, 1.0)); - self.ui.update(ui::Update::Volume)?; - } - Message::Bookmark => { - let Current::Track(current) = &self.current else { - continue; - }; - - let bookmarked = self.bookmarks.bookmark(current)?; - self.ui.update(ui::Update::Bookmarked(bookmarked))?; - } - Message::Quit => break, } + Message::ChangeVolume(change) => { + self.sink + .set_volume((self.sink.volume() + change).clamp(0.0, 1.0)); + self.ui.update(ui::Update::Volume)?; + } + Message::SetVolume(volume) => { + self.sink.set_volume(volume.clamp(0.0, 1.0)); + self.ui.update(ui::Update::Volume)?; + } + Message::Bookmark => { + let Current::Track(current) = &self.current else { + return Ok(false); + }; + let bookmarked = self.bookmarks.bookmark(current)?; + self.ui.update(ui::Update::Bookmarked(bookmarked))?; + } + Message::Quit => return Ok(false), + } + Ok(true) + } + /// Drives the existing terminal and native-adapter command loop. + pub async fn run(&mut self) -> crate::Result<()> { + while let Some(message) = self.rx.recv().await { + if message == Message::Quit { + break; + } + if !self.apply(message)? { + continue; + } #[cfg(feature = "mpris")] self.ui.mpris.handle(&message).await?; - #[cfg(all(feature = "media-controls", windows))] if let Some(controls) = self.ui.media_controls.as_mut() { controls.handle(&message)?; } } - Ok(()) } } + +#[cfg(all(test, not(feature = "mpris")))] +mod tests { + use super::{Current, Player}; + use crate::ui::Update; + use crate::{ + audio::waiter, bookmark::Bookmarks, downloader, tests::fixture, tracks::Queued, Message, + }; + use rodio::queue::SourcesQueueOutput; + use std::time::Duration; + + fn player() -> (Player, tokio::sync::broadcast::Receiver) { + let (player, receiver, _) = player_with_tracks([]); + (player, receiver) + } + + fn player_with_tracks( + tracks: impl IntoIterator, + ) -> ( + Player, + tokio::sync::broadcast::Receiver, + SourcesQueueOutput, + ) { + let (ui, receiver) = crate::ui::Handle::for_test(); + let (_, rx) = tokio::sync::mpsc::channel(1); + let (sink, output) = rodio::Player::new(); + ( + Player { + bookmarks: Bookmarks { + entries: Vec::new(), + }, + current: Default::default(), + downloader: downloader::Handle::with_tracks(tracks), + sink: std::sync::Arc::new(sink), + ui, + rx, + waiter: waiter::Handle::idle(), + history: Default::default(), + generation: 0, + }, + receiver, + output, + ) + } + + fn current_name(player: &Player) -> &str { + match &player.current { + Current::Track(track) => &track.display, + Current::Loading(_) => panic!("expected a playing track"), + } + } + + fn render(output: &mut SourcesQueueOutput, samples: usize) { + for sample in output.by_ref().take(samples) { + assert!(sample.is_finite()); + } + } + + fn handle_while_rendering( + player: &mut Player, + output: &mut SourcesQueueOutput, + message: Message, + ) -> bool { + let (sender, receiver) = std::sync::mpsc::channel(); + std::thread::scope(|scope| { + let command = scope.spawn(|| sender.send(player.apply(message)).unwrap()); + for _ in 0..100_000 { + if let Ok(outcome) = receiver.try_recv() { + command.join().unwrap(); + return outcome.unwrap(); + } + assert!(output.next().is_some_and(|sample| sample.is_finite())); + std::thread::yield_now(); + } + panic!("playback command did not finish while rendering offline"); + }) + } + + #[test] + fn playback_commands_transition_valid_tracks_and_preserve_pause() { + let tracks = [fixture::queued("one"), fixture::queued("two")]; + let (mut player, mut updates, mut output) = player_with_tracks(tracks); + + assert_eq!(player.apply(Message::Init).unwrap(), true); + assert_eq!(current_name(&player), "one"); + assert_eq!(player.generation, 1); + render(&mut output, 1_024); + assert!(player.sink.get_pos() > Duration::ZERO); + assert!( + matches!(updates.try_recv(), Ok(Update::Track(Current::Track(track))) if track.display == "one") + ); + assert!(matches!(updates.try_recv(), Ok(Update::Bookmarked(false)))); + assert!(matches!( + updates.try_recv(), + Ok(Update::CanGoPrevious(false)) + )); + + player.apply(Message::Pause).unwrap(); + assert!(player.sink.is_paused()); + assert_eq!( + handle_while_rendering(&mut player, &mut output, Message::Next), + true + ); + assert_eq!(current_name(&player), "two"); + assert_eq!(player.generation, 2); + assert!(player.sink.is_paused()); + assert!( + matches!(updates.try_recv(), Ok(Update::Track(Current::Track(track))) if track.display == "two") + ); + assert!(matches!(updates.try_recv(), Ok(Update::Bookmarked(false)))); + assert!(matches!( + updates.try_recv(), + Ok(Update::CanGoPrevious(true)) + )); + + player.apply(Message::Play).unwrap(); + assert!(!player.sink.is_paused()); + assert_eq!( + handle_while_rendering(&mut player, &mut output, Message::Previous), + true + ); + assert_eq!(current_name(&player), "one"); + assert_eq!(player.generation, 3); + assert!( + matches!(updates.try_recv(), Ok(Update::Track(Current::Track(track))) if track.display == "one") + ); + assert!(matches!(updates.try_recv(), Ok(Update::Bookmarked(false)))); + assert!(matches!( + updates.try_recv(), + Ok(Update::CanGoPrevious(false)) + )); + + assert_eq!( + handle_while_rendering(&mut player, &mut output, Message::Next), + true + ); + assert_eq!(current_name(&player), "two"); + assert_eq!(player.generation, 4); + } + + #[test] + fn matching_generation_advances_and_stale_messages_preserve_transition_state() { + let tracks = [fixture::queued("one"), fixture::queued("two")]; + let (mut player, mut updates, mut output) = player_with_tracks(tracks); + player.apply(Message::Init).unwrap(); + render(&mut output, 1_024); + while updates.try_recv().is_ok() {} + let first_generation = player.generation; + + assert_eq!( + handle_while_rendering( + &mut player, + &mut output, + Message::Finished(first_generation) + ), + true + ); + assert_eq!(current_name(&player), "two"); + let second_generation = player.generation; + while updates.try_recv().is_ok() {} + + assert_eq!( + player.apply(Message::Finished(first_generation)).unwrap(), + false + ); + assert_eq!( + player + .apply(Message::PreviousAvailable(first_generation)) + .unwrap(), + false + ); + assert_eq!(current_name(&player), "two"); + assert_eq!(player.generation, second_generation); + assert!(updates.try_recv().is_err()); + + assert_eq!( + player + .apply(Message::PreviousAvailable(second_generation)) + .unwrap(), + true + ); + assert!(matches!( + updates.try_recv(), + Ok(Update::CanGoPrevious(true)) + )); + } + + #[test] + fn loaded_is_ignored_after_a_track_has_started() { + let (mut player, mut updates, _) = player_with_tracks([fixture::queued("one")]); + player.apply(Message::Init).unwrap(); + while updates.try_recv().is_ok() {} + + assert_eq!(player.apply(Message::Loaded).unwrap(), false); + assert_eq!(current_name(&player), "one"); + assert!(updates.try_recv().is_err()); + } + + #[test] + fn previous_restarts_a_rendered_track_after_three_seconds() { + let (mut player, mut updates, mut output) = player_with_tracks([fixture::queued("one")]); + player.apply(Message::Init).unwrap(); + while updates.try_recv().is_ok() {} + render(&mut output, 160_000); + assert!(player.sink.get_pos() >= Duration::from_secs(3)); + assert!(player.can_go_previous()); + + handle_while_rendering(&mut player, &mut output, Message::Previous); + assert_eq!(current_name(&player), "one"); + assert_eq!(player.generation, 2); + assert!( + matches!(updates.try_recv(), Ok(Update::Track(Current::Track(track))) if track.display == "one") + ); + assert!(matches!(updates.try_recv(), Ok(Update::Bookmarked(false)))); + assert!(matches!(updates.try_recv(), Ok(Update::CanGoPrevious(_)))); + assert!(matches!(updates.try_recv(), Ok(Update::Restarted))); + assert!(matches!(updates.try_recv(), Ok(Update::CanGoPrevious(_)))); + } + + #[test] + fn stale_generation_messages_are_ignored() { + let (mut player, mut receiver) = player(); + assert_eq!(player.apply(Message::Finished(1)).unwrap(), false); + assert_eq!(player.apply(Message::PreviousAvailable(1)).unwrap(), false); + assert!(receiver.try_recv().is_err()); + } +} diff --git a/src/tracks.rs b/src/tracks.rs index 58b7a4f..460b107 100644 --- a/src/tracks.rs +++ b/src/tracks.rs @@ -29,7 +29,7 @@ pub type DecodedData = Decoder>; /// Tracks which are still waiting in the queue, and can't be played yet. /// /// This means that only the data & track name are included. -#[derive(PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct Queued { /// Display name of the track. pub display: String, diff --git a/src/ui.rs b/src/ui.rs index e8f3ff2..44993d6 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -109,6 +109,8 @@ impl State { /// contains the new information about the track. #[derive(Debug, Clone)] pub enum Update { + CanGoPrevious(bool), + Restarted, Track(Current), Bookmarked(bool), Volume, @@ -134,6 +136,20 @@ pub struct Handle { } impl Handle { + #[cfg(all(test, not(feature = "mpris")))] + pub(crate) fn for_test() -> (Self, broadcast::Receiver) { + let (updater, receiver) = broadcast::channel(8); + ( + Self { + updater, + logger: interface::Logger::for_test(), + #[cfg(all(feature = "media-controls", windows))] + media_controls: None, + }, + receiver, + ) + } + /// Sends a `ui::Update` to the broadcast channel. pub fn update(&mut self, update: Update) -> crate::Result<()> { self.updater.send(update)?; @@ -166,6 +182,7 @@ pub async fn run( Update::Bookmarked(bookmarked) => state.bookmarked = bookmarked, Update::Volume => state.volume_timer = Some(Instant::now()), Update::Quit => break, + Update::CanGoPrevious(_) | Update::Restarted => {} } } diff --git a/src/ui/input.rs b/src/ui/input.rs index 4031283..6adb70a 100644 --- a/src/ui/input.rs +++ b/src/ui/input.rs @@ -41,6 +41,7 @@ fn message_for(code: KeyCode, modifiers: KeyModifiers, bindings: &BindingMap) -> | event::MediaKeyCode::PlayPause => Some(Message::PlayPause), event::MediaKeyCode::Stop => Some(Message::Pause), event::MediaKeyCode::TrackNext => Some(Message::Next), + event::MediaKeyCode::TrackPrevious => Some(Message::Previous), event::MediaKeyCode::LowerVolume => Some(Message::ChangeVolume(-0.1)), event::MediaKeyCode::RaiseVolume => Some(Message::ChangeVolume(0.1)), event::MediaKeyCode::MuteVolume => Some(Message::ChangeVolume(-1.0)), @@ -158,7 +159,7 @@ mod tests { KeyModifiers::NONE, &bindings, ), - None + Some(Message::Previous) ); assert_eq!( message_for(KeyCode::F(1), KeyModifiers::NONE, &bindings), diff --git a/src/ui/interface.rs b/src/ui/interface.rs index 8b62ddc..6a42978 100644 --- a/src/ui/interface.rs +++ b/src/ui/interface.rs @@ -21,6 +21,11 @@ pub use window::Window; pub struct Logger(mpsc::Sender); impl Logger { + #[cfg(all(test, not(feature = "mpris")))] + pub(super) fn for_test() -> Self { + Self(mpsc::channel(1).0) + } + /// Send an informational log. pub async fn info(&self, message: String) -> ui::Result<()> { self.0.send(message).await?; diff --git a/src/ui/mpris.rs b/src/ui/mpris.rs index adb7a61..4c44e36 100644 --- a/src/ui/mpris.rs +++ b/src/ui/mpris.rs @@ -3,18 +3,22 @@ use std::{ hash::{DefaultHasher, Hash, Hasher}, process, - sync::Arc, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, }; use arc_swap::ArcSwap; use mpris_server::{ zbus::{self, fdo, Result}, LoopStatus, Metadata, PlaybackRate, PlaybackStatus, PlayerInterface, Property, RootInterface, - Time, TrackId, Volume, + Signal, Time, TrackId, Volume, }; use tokio::sync::{broadcast, mpsc}; -use crate::{player::Current, ui::Update}; +use crate::player::Current; +use crate::ui::Update; use crate::{ui, Message}; const ERROR: fdo::Error = fdo::Error::Failed(String::new()); @@ -55,6 +59,7 @@ pub struct Player { current: ArcSwap, list: String, sender: Sender, + can_go_previous: Arc, } impl RootInterface for Player { @@ -113,7 +118,10 @@ impl PlayerInterface for Player { } async fn previous(&self) -> fdo::Result<()> { - Err(ERROR) + if self.can_go_previous.load(Ordering::Relaxed) { + self.sender.send(Message::Previous).await?; + } + Ok(()) } async fn pause(&self) -> fdo::Result<()> { @@ -163,7 +171,7 @@ impl PlayerInterface for Player { } async fn rate(&self) -> fdo::Result { - Ok(self.sink.speed().into()) + Ok(self.sink.rate().into()) } async fn set_rate(&self, rate: PlaybackRate) -> Result<()> { @@ -219,7 +227,7 @@ impl PlayerInterface for Player { } async fn position(&self) -> fdo::Result