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 1/5] 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 2/5] 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 3/5] 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 4/5] 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 5/5] 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("__"), )