Skip to main content

koan_core/
config.rs

1use std::collections::HashMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4use std::sync::{Arc, LazyLock, Once};
5use std::time::SystemTime;
6
7use figment::Figment;
8use figment::providers::{Env, Format, Serialized, Toml};
9use serde::{Deserialize, Serialize};
10use thiserror::Error;
11
12#[derive(Debug, Error)]
13pub enum ConfigError {
14    #[error("io error: {0}")]
15    Io(#[from] std::io::Error),
16    #[error("parse error: {0}")]
17    Parse(#[from] toml::de::Error),
18    #[error("serialize error: {0}")]
19    Serialize(#[from] toml::ser::Error),
20    #[error("config error: {0}")]
21    Figment(#[from] Box<figment::Error>),
22}
23
24#[derive(Debug, Clone, Default, Serialize, Deserialize)]
25#[serde(default)]
26pub struct Config {
27    pub library: LibraryConfig,
28    pub playback: PlaybackConfig,
29    pub remote: RemoteConfig,
30    pub organize: OrganizeConfig,
31    #[serde(alias = "visualiser")]
32    pub visualizer: VisualizerConfig,
33    pub graphql: GraphqlConfig,
34    pub subsonic: SubsonicConfig,
35    pub auth: AuthConfig,
36    pub sharing: SharingConfig,
37    pub mcp: McpConfig,
38    pub push: PushConfig,
39    pub devices: DevicesConfig,
40    pub dsp: DspConfig,
41    pub appearance: AppearanceConfig,
42}
43
44/// How the apps are drawn: Settings → Appearance.
45#[derive(Debug, Clone, Serialize, Deserialize)]
46#[serde(default)]
47pub struct AppearanceConfig {
48    /// `"koan"`, the site's look throughout (see `docs/design/koan-theme.md`),
49    /// or `"system"`, the platform's own look in koan's colours. Read at launch.
50    pub theme: String,
51    /// In the kōan theme, draw the app's icons beside navigation, tabs and
52    /// controls; off, labels alone.
53    pub theme_icons: bool,
54    /// Take colour from the record playing: the wash behind the window and
55    /// the accent. Off, there is no wash and the accent is koan's mint, in
56    /// either theme.
57    pub record_colours: bool,
58    /// On the Mac in the kōan theme, the wash runs under the whole window:
59    /// sidebar, toolbar, transport and lyrics drawn clear over it. Off, those
60    /// keep grounds of their own. Provisional: a way to live with both while
61    /// the look is decided, and expected to go once it is.
62    pub wash_window: bool,
63    /// An alternative palette for the accent, wash and indicators (see the
64    /// apps' `Rainbow.swift`). Per device, and not offered in Settings.
65    pub rainbow: bool,
66    /// Text size on the Mac, in percent of the theme's own (80–130, in steps
67    /// of 5). Spacing follows it at half the rate. Per device.
68    pub text_size: u16,
69}
70
71impl Default for AppearanceConfig {
72    fn default() -> Self {
73        Self {
74            theme: "koan".into(),
75            theme_icons: true,
76            record_colours: true,
77            wash_window: true,
78            rainbow: false,
79            text_size: 100,
80        }
81    }
82}
83
84/// Share links this koan serves itself.
85#[derive(Debug, Clone, Default, Serialize, Deserialize)]
86#[serde(default)]
87pub struct SharingConfig {
88    /// Where this server is reached from outside, e.g. `https://koan.example.com`.
89    /// Share links are built on it; without it a server makes no links, since
90    /// it cannot know which of its addresses a stranger can reach.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub public_url: Option<String>,
93}
94
95/// MCP clients signing in through this server's OAuth.
96#[derive(Debug, Clone, Default, Serialize, Deserialize)]
97#[serde(default)]
98pub struct McpConfig {
99    /// The only hosts an MCP client may register a redirect to, besides this
100    /// machine. Empty allows any HTTPS host: each approval then rests on the
101    /// user recognising the host the consent page names.
102    #[serde(default, skip_serializing_if = "Vec::is_empty")]
103    pub redirect_hosts: Vec<String>,
104}
105
106/// Push notifications to koan's iOS app, which reach a phone iOS has
107/// suspended. Apple accepts them only signed with the key of the team that
108/// ships the app, so only a server holding that key can send them; without one
109/// a server reaches phones only while they are linked.
110#[derive(Debug, Clone, Serialize, Deserialize)]
111#[serde(default)]
112pub struct PushConfig {
113    /// The APNs auth key (`AuthKey_XXXXXXXXXX.p8`).
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub key_path: Option<PathBuf>,
116    /// The key itself, PEM, for a deployment that hands secrets over as
117    /// environment (`KOAN_PUSH__KEY`) rather than files.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub key: Option<String>,
120    /// The key's ten-character id.
121    #[serde(skip_serializing_if = "String::is_empty")]
122    pub key_id: String,
123    /// The Apple developer team the key belongs to.
124    #[serde(skip_serializing_if = "String::is_empty")]
125    pub team_id: String,
126    /// The app's bundle id, which every push names.
127    pub topic: String,
128}
129
130impl Default for PushConfig {
131    fn default() -> Self {
132        Self {
133            key_path: None,
134            key: None,
135            key_id: String::new(),
136            team_id: String::new(),
137            topic: "cc.blit.koan".into(),
138        }
139    }
140}
141
142/// The folders koan indexes. None until someone chooses one: looking in
143/// `~/Music` unasked reads the Apple Music library inside it, and macOS asks
144/// the person whether koan may.
145#[derive(Debug, Clone, Default, Serialize, Deserialize)]
146#[serde(default)]
147pub struct LibraryConfig {
148    pub folders: Vec<PathBuf>,
149}
150
151/// The folder koan used to index when none was chosen, `~/Music`. Kept so a
152/// library built from it can be written into the config before the default
153/// it came from goes (`helpers::keep_former_default_folder`).
154pub fn former_default_folder() -> PathBuf {
155    dirs::audio_dir().unwrap_or_else(|| {
156        dirs::home_dir()
157            .map(|h| h.join("Music"))
158            .unwrap_or_else(|| PathBuf::from("/Music"))
159    })
160}
161
162#[derive(Debug, Clone, Serialize, Deserialize)]
163#[serde(default)]
164pub struct PlaybackConfig {
165    pub replaygain: ReplayGainMode,
166    /// UI render rate in frames-per-second (default: 60).
167    /// Controls how often the TUI redraws. 30, 60, or 120 are typical values.
168    pub target_fps: u8,
169    /// Show an FPS counter overlay in the top-right corner.
170    pub show_fps: bool,
171    /// ReplayGain pre-amplification in dB. Applied on top of track/album gain.
172    /// Positive values boost, negative values attenuate. Default: 0.0.
173    pub pre_amp_db: f64,
174    /// Fade out on pause and back in on resume, rather than cutting.
175    pub fade_on_pause: bool,
176    /// Output audio device name. None = system default.
177    /// Persisted by name (not ID) since IDs can change across reboots.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub output_device: Option<String>,
180    /// The UPnP renderer last picked as the output, by UDN, and its name for
181    /// showing. Gone back to at launch if it is on the network; otherwise the
182    /// music plays on `output_device`.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub renderer: Option<String>,
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub renderer_name: Option<String>,
187    /// Look for UPnP renderers on the network. Off, none is found, so none
188    /// can be played to.
189    pub renderers: bool,
190    /// Play silence: the output runs as usual, with every sample zeroed. For
191    /// automated runs on a machine someone is using.
192    pub muted: bool,
193    /// Album art width in terminal columns (default: 24).
194    /// Height is always width/2 (square via halfblock rendering).
195    pub art_size: u16,
196    /// Silence played after the output device changes sample rate, so the
197    /// start of the track is not lost while the device relocks its clock.
198    /// How long that takes is a property of the device.
199    pub rate_switch_lead_in_ms: u32,
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "lowercase")]
204pub enum ReplayGainMode {
205    Off,
206    Track,
207    Album,
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
211#[serde(default)]
212pub struct RemoteConfig {
213    pub enabled: bool,
214    pub url: String,
215    pub username: String,
216    /// Password — stored in config.local.toml (gitignored), not config.toml.
217    #[serde(default, skip_serializing_if = "String::is_empty")]
218    pub password: String,
219    /// An OpenSubsonic API key, signing in instead of the password. What
220    /// joining with a koan invite stores. config.local.toml, like the password.
221    #[serde(default, skip_serializing_if = "String::is_empty")]
222    pub api_key: String,
223    /// The keypair this device proves itself with to the account's other
224    /// devices on the local network: base64 of its Ed25519 PKCS#8. Made at
225    /// each sign-in with an API key and dropped at sign-out, so the server's
226    /// copy of the public key goes with the API key it is kept on. A secret,
227    /// kept with the credentials. See `remote::proof`.
228    #[serde(default, skip_serializing_if = "String::is_empty")]
229    pub device_key: String,
230    /// Defaults to config_dir()/cache if empty.
231    pub cache_dir: Option<PathBuf>,
232    /// Parallel download workers for remote tracks (default: 5).
233    pub download_workers: usize,
234    /// Maximum cache size on disk. Human-readable: "50GB", "500MB", etc.
235    /// None or empty = unlimited. Past it, whole albums are evicted, least
236    /// recently used first, at startup and as downloads land.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub cache_limit: Option<String>,
239    /// Sync the library from the server on startup, and on a timer for a server
240    /// that cannot say when it changes; a koan server tells its apps itself.
241    ///
242    /// Each run walks the library only if the server says it changed since the
243    /// last walk, so it is cheap enough to run unattended.
244    pub auto_sync: bool,
245    /// Minutes between automatic syncs. 0 runs one at startup and no more.
246    pub auto_sync_interval_mins: u64,
247    /// Keep this device's queue in the account's play queue on the server,
248    /// where Subsonic clients save theirs, so a queue can be picked up in
249    /// another client or on another kōan device after a restart. Off by
250    /// default: between kōan devices the queue already moves live over the
251    /// link. Per device.
252    pub play_queue: bool,
253}
254
255impl Default for PlaybackConfig {
256    fn default() -> Self {
257        Self {
258            replaygain: ReplayGainMode::Off,
259            target_fps: 60,
260            show_fps: false,
261            pre_amp_db: 0.0,
262            fade_on_pause: true,
263            output_device: None,
264            renderer: None,
265            renderer_name: None,
266            renderers: true,
267            muted: false,
268            art_size: 24,
269            rate_switch_lead_in_ms: 1000,
270        }
271    }
272}
273
274#[derive(Debug, Clone, Serialize, Deserialize)]
275#[serde(default)]
276pub struct VisualizerConfig {
277    pub enabled: bool,
278    pub fps: u8,
279    /// Visualizer mode by name: "bars" (default), or any name
280    /// `VisualizerMode::parse` in koan-tui accepts.
281    pub mode: String,
282    /// Frequency scale: "bark" (default), "mel", "log", "linear".
283    pub scale: String,
284    /// Amplitude scale: "aweight" (default, A-weighted), "perceptual" (A-weighted + gamma), "sqrt", "linear".
285    pub amplitude_scale: String,
286    /// Bar decay half-life in milliseconds (how fast bars drop).
287    pub bar_decay_ms: u32,
288    /// Peak decay half-life in milliseconds (how long peaks linger).
289    pub peak_decay_ms: u32,
290    /// Color palette: "spectrum" (default), "mono", "fire", "neon".
291    /// Controls the frequency-mapped color gradient on spectrum bars.
292    pub palette: String,
293    /// Reactivity multiplier (0.0..2.0, default 1.0).
294    /// Scales all beat/spectrum-driven animation coefficients.
295    /// 0.0 = static, 1.0 = normal, 2.0 = hypersensitive.
296    pub reactivity: f32,
297    /// Bass shake: camera jitter + scale pulse on bass hits.
298    /// Applies to braille-rendered modes (oscilloscope, radial, wireframe, starfield, etc.).
299    pub bass_shake: bool,
300    /// Matrix overlay: replace all rendered characters with random matrix glyphs in green.
301    /// Applies to any visualizer mode as a post-processing pass.
302    pub matrix_overlay: bool,
303    /// Beat-reactive background color on braille modes (starfield, wormhole, etc.).
304    pub reactive_bg: bool,
305}
306
307impl Default for VisualizerConfig {
308    fn default() -> Self {
309        Self {
310            enabled: true,
311            fps: 60,
312            mode: "bars".into(),
313            scale: "bark".into(),
314            amplitude_scale: "aweight".into(),
315            bar_decay_ms: 50,
316            peak_decay_ms: 180,
317            palette: "spectrum".into(),
318            reactivity: 1.0,
319            bass_shake: true,
320            matrix_overlay: false,
321            reactive_bg: false,
322        }
323    }
324}
325
326impl Default for RemoteConfig {
327    fn default() -> Self {
328        Self {
329            enabled: false,
330            url: String::new(),
331            username: String::new(),
332            password: String::new(),
333            api_key: String::new(),
334            device_key: String::new(),
335            cache_dir: None,
336            download_workers: 5,
337            cache_limit: None,
338            auto_sync: true,
339            auto_sync_interval_mins: 60,
340            play_queue: false,
341        }
342    }
343}
344
345/// Parse a human-readable size string like "50GB", "500 MB", "1.5TB" into bytes.
346/// Supports B, KB, MB, GB, TB (case-insensitive). Returns None for invalid input.
347pub fn parse_size_bytes(s: &str) -> Option<u64> {
348    let s = s.trim();
349    if s.is_empty() {
350        return None;
351    }
352
353    // Split into numeric part and suffix.
354    let mut num_end = 0;
355    for (i, c) in s.char_indices() {
356        if c.is_ascii_digit() || c == '.' {
357            num_end = i + c.len_utf8();
358        } else if !c.is_whitespace() {
359            break;
360        }
361    }
362
363    let num_str = s[..num_end].trim();
364    let suffix = s[num_end..].trim().to_ascii_uppercase();
365
366    let value: f64 = num_str.parse().ok()?;
367    let multiplier: u64 = match suffix.as_str() {
368        "" | "B" => 1,
369        "KB" | "K" => 1024,
370        "MB" | "M" => 1024 * 1024,
371        "GB" | "G" => 1024 * 1024 * 1024,
372        "TB" | "T" => 1024 * 1024 * 1024 * 1024,
373        _ => return None,
374    };
375
376    Some((value * multiplier as f64) as u64)
377}
378
379#[derive(Debug, Clone, Serialize, Deserialize)]
380#[serde(default)]
381pub struct OrganizeConfig {
382    /// Named pattern preselected when an organize sheet or modal opens.
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub default: Option<String>,
385    /// Named patterns — keys are names, values are format strings.
386    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
387    pub patterns: HashMap<String, String>,
388    /// Move cover art, cue sheets and logs alongside the music they belong to.
389    /// On by default: a folder's artwork is part of the release, and leaving it
390    /// behind turns one album into two half-albums.
391    #[serde(default = "default_true")]
392    pub move_ancillary: bool,
393}
394
395impl Default for OrganizeConfig {
396    fn default() -> Self {
397        Self {
398            default: None,
399            patterns: HashMap::new(),
400            move_ancillary: true,
401        }
402    }
403}
404
405/// GraphQL API server configuration.
406#[derive(Debug, Clone, Serialize, Deserialize)]
407#[serde(default)]
408pub struct GraphqlConfig {
409    /// Enable the GraphQL API server alongside the TUI (default: true).
410    /// Set to false for TUI-only mode (equivalent to --no-api).
411    pub enabled: bool,
412    /// GraphQL API port (default: 4000).
413    pub port: u16,
414    /// Bind address for the API server (default: 127.0.0.1).
415    /// Use "0.0.0.0" to listen on all interfaces (NOT RECOMMENDED without auth).
416    #[serde(default = "default_bind")]
417    pub bind: std::net::IpAddr,
418    /// Enable GraphiQL web IDE at GET /graphql.
419    pub playground: bool,
420    /// Require authentication for API access (default: true).
421    /// When false, all requests are treated as admin. When true, JWT auth is enforced.
422    pub auth_enabled: bool,
423    /// Access token TTL (default: "15m"). Supports: "15m", "1h", "3600s".
424    pub access_token_ttl: String,
425    /// Refresh token TTL (default: "30d"). Supports: "30d", "7d", "720h".
426    pub refresh_token_ttl: String,
427    /// Allowed CORS origins. Empty = no cross-origin browser access at all.
428    /// Example: ["https://music.example.com"]
429    pub cors_origins: Vec<String>,
430    /// Extra `Host:` values the server will answer to, beyond `localhost` and
431    /// bare IP literals. Requests carrying any other Host are refused, which is
432    /// what stops a DNS-rebinding page from reaching the API as same-origin.
433    pub allowed_hosts: Vec<String>,
434    /// Mark the session cookie `Secure`. Only set this when clients reach koan
435    /// over HTTPS — browsers silently discard `Secure` cookies sent over plain
436    /// `http://` to anything but localhost.
437    pub cookie_secure: bool,
438    /// A request header an authenticating reverse proxy (Authelia, Authentik,
439    /// oauth2-proxy) sets to the signed-in username, e.g. `Remote-User`. The
440    /// web UI signs that account in without asking for its password. Honoured
441    /// only on connections from `proxy_auth_from`; empty turns it off.
442    #[serde(default, skip_serializing_if = "String::is_empty")]
443    pub proxy_auth_header: String,
444    /// The addresses or CIDR ranges the authenticating proxy connects from.
445    /// The header is ignored on a connection from anywhere else.
446    #[serde(default, skip_serializing_if = "Vec::is_empty")]
447    pub proxy_auth_from: Vec<String>,
448    /// Expose the `organize*` mutations, which physically move files on disk.
449    pub allow_organize: bool,
450}
451
452fn default_true() -> bool {
453    true
454}
455
456fn default_bind() -> std::net::IpAddr {
457    std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
458}
459
460impl Default for GraphqlConfig {
461    fn default() -> Self {
462        Self {
463            enabled: true,
464            port: 4000,
465            bind: default_bind(),
466            playground: false,
467            auth_enabled: true,
468            access_token_ttl: "15m".into(),
469            refresh_token_ttl: "30d".into(),
470            cors_origins: Vec::new(),
471            allowed_hosts: Vec::new(),
472            cookie_secure: false,
473            proxy_auth_header: String::new(),
474            proxy_auth_from: Vec::new(),
475            allow_organize: false,
476        }
477    }
478}
479
480/// Subsonic-compatible REST API.
481///
482/// Credentials are deliberately separate from `[remote]`: the Subsonic protocol
483/// authenticates with `md5(password + salt)` over whatever transport the client
484/// picked, so the secret has to be recoverable and is exposed to anyone who can
485/// capture a request. Reusing the upstream Navidrome password would hand out
486/// that account too.
487#[derive(Debug, Clone, Serialize, Deserialize)]
488#[serde(default)]
489pub struct SubsonicConfig {
490    /// Serve `/rest/*`. Off unless explicitly enabled.
491    ///
492    /// The routes are mounted on the GraphQL port. `port` adds a second
493    /// listener for clients that expect Subsonic on one of its own.
494    pub enabled: bool,
495    /// Serve `/rest/*` on a dedicated port as well as the GraphQL one.
496    #[serde(default, skip_serializing_if = "Option::is_none")]
497    pub port: Option<u16>,
498    /// Username Subsonic clients authenticate as.
499    pub username: String,
500    /// Shared secret, written by `koan subsonic setup`. Lives in
501    /// config.local.toml, which is gitignored and `0600`.
502    #[serde(default, skip_serializing_if = "String::is_empty")]
503    pub password: String,
504    /// Transcode `stream` for clients that ask for a lower bitrate or another
505    /// format. Off, every client gets the original file.
506    pub transcode: bool,
507    /// The `ffmpeg` transcoding runs, by name on `PATH` or by path. Without
508    /// one, originals are served.
509    pub ffmpeg: String,
510}
511
512impl Default for SubsonicConfig {
513    fn default() -> Self {
514        Self {
515            enabled: false,
516            port: None,
517            username: "koan".into(),
518            password: String::new(),
519            transcode: true,
520            ffmpeg: "ffmpeg".into(),
521        }
522    }
523}
524
525/// Credentials for a remote koan server this machine signs in to.
526///
527/// The other direction from `GraphqlConfig`, which configures the server koan
528/// *is*. Written by `koan auth login` and cleared by `koan auth logout`.
529#[derive(Debug, Clone, Default, Serialize, Deserialize)]
530#[serde(default)]
531pub struct AuthConfig {
532    /// Server the token below belongs to. One at a time.
533    #[serde(skip_serializing_if = "String::is_empty")]
534    pub server: String,
535    /// Refresh token, exchanged for short-lived access tokens. Revocable at the
536    /// server, which is what separates it from a password.
537    #[serde(skip_serializing_if = "String::is_empty")]
538    pub refresh_token: String,
539}
540
541/// Controlling this device from others on the local network, and finding
542/// them. Devices on the same account reach each other through the server
543/// whatever this says.
544#[derive(Debug, Clone, Serialize, Deserialize)]
545#[serde(default)]
546pub struct DevicesConfig {
547    /// Take part in the local network at all: listen, announce, look for other
548    /// devices and dial them. Off, this device reaches others only through the
549    /// server. For a shared network, and for test runs that relaunch an app
550    /// over and over, which would otherwise announce it to every device in
551    /// the house each time.
552    pub nearby: bool,
553    /// Listen on the local network and announce this device there, so any
554    /// koan app on it can see what is playing and control it.
555    pub discoverable: bool,
556    /// The port listened on. Fixed so that an address typed into another
557    /// device (over Tailscale, where nothing is announced) keeps working.
558    pub port: u16,
559    /// Devices to connect to by address, `host:port`: for networks that do
560    /// not carry Bonjour, such as a tailnet.
561    pub addresses: Vec<String>,
562    /// What a kōan on the local network may have this device do, whoever is
563    /// signed in there.
564    pub nearby_control: NearbyControl,
565    /// Addresses whose connections to this device are hung up at once: a
566    /// stranger on the network, refused from Settings.
567    pub refused: Vec<String>,
568    /// Keep the Mac app running in the menu bar once its window is closed, so
569    /// other devices can still see and control this one. Quitting it then
570    /// means this Mac is out of reach until it is opened again.
571    pub keep_running: bool,
572}
573
574/// What devices on the local network may do with this one.
575#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
576#[serde(rename_all = "snake_case")]
577pub enum NearbyControl {
578    /// Play, the queue, the output, the preset and the volume, and moving the
579    /// music here or away: what a household network wants.
580    #[default]
581    Full,
582    /// Play and the queue only, and a hand-off that stays on the network: for
583    /// a network shared with strangers.
584    Playback,
585}
586
587impl Default for DevicesConfig {
588    fn default() -> Self {
589        Self {
590            nearby: true,
591            discoverable: true,
592            port: DEVICES_PORT,
593            addresses: Vec::new(),
594            nearby_control: NearbyControl::Full,
595            refused: Vec::new(),
596            keep_running: false,
597        }
598    }
599}
600
601/// "koan" on a phone keypad.
602pub const DEVICES_PORT: u16 = 5626;
603
604/// Equalisation and convolution for the listening setup: headphones, speakers,
605/// a room. Each profile names the output devices it is for, so plugging in the
606/// headphones selects their correction. A device no profile names plays
607/// bit-perfect, untouched.
608#[derive(Debug, Clone, Serialize, Deserialize)]
609#[serde(default)]
610pub struct DspConfig {
611    /// Off bypasses every profile without forgetting any of them.
612    pub enabled: bool,
613    pub profiles: Vec<DspProfile>,
614    /// Output devices whose AutoEQ suggestion was turned down. See
615    /// `audio::dsp::autoeq::suggest`.
616    #[serde(skip_serializing_if = "Vec::is_empty")]
617    pub autoeq_dismissed: Vec<String>,
618    /// The tuning each output plays on top of its correction, the profile
619    /// that lists it: its EQs, in the order listed, each switched on or off.
620    /// This device's, as which profile an output plays is.
621    #[serde(skip_serializing_if = "Vec::is_empty")]
622    pub tunings: Vec<DspOutputTuning>,
623    /// The preset each output's correction and tuning were last set from,
624    /// which they are compared with to say whether it was changed since.
625    #[serde(skip_serializing_if = "Vec::is_empty")]
626    pub presets: Vec<DspOutputPreset>,
627    /// Outputs that play filters alone: no headphone correction, and
628    /// nothing matched to a target. Speakers, mostly.
629    #[serde(skip_serializing_if = "Vec::is_empty")]
630    pub filters_only: Vec<String>,
631    /// The uids of profiles deleted here and not yet deleted on the account's
632    /// server. Sync deletes a profile everywhere only when it is listed here
633    /// or kept on this device by choice; one that is merely missing, after a
634    /// config that failed to load or an edit by hand, is not deleted.
635    #[serde(skip_serializing_if = "Vec::is_empty")]
636    pub removed: Vec<String>,
637}
638
639/// One EQ of an output's tuning.
640#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
641pub struct DspOutputTuning {
642    pub device: String,
643    pub tuning: String,
644    /// Switched off, it stays in the tuning and plays nothing.
645    #[serde(default = "on", skip_serializing_if = "is_on")]
646    pub on: bool,
647}
648
649fn on() -> bool {
650    true
651}
652
653fn is_on(on: &bool) -> bool {
654    *on
655}
656
657/// The preset an output was set from.
658#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
659pub struct DspOutputPreset {
660    pub device: String,
661    pub preset: String,
662}
663
664impl Default for DspConfig {
665    fn default() -> Self {
666        Self {
667            enabled: true,
668            profiles: Vec::new(),
669            autoeq_dismissed: Vec::new(),
670            tunings: Vec::new(),
671            presets: Vec::new(),
672            filters_only: Vec::new(),
673            removed: Vec::new(),
674        }
675    }
676}
677
678impl DspProfile {
679    /// The measurement and target a correction is built from: fitted, or
680    /// saved before kōan fitted bands.
681    pub fn measured(&self) -> Option<&DspMeasurement> {
682        self.fitted.as_ref().or(self.measurement.as_ref())
683    }
684}
685
686impl DspConfig {
687    /// The profile for the output device called `device`, if DSP is on and
688    /// one names it. None that corrects a headphone for an output playing
689    /// filters alone, however it came to name it.
690    pub fn profile_for(&self, device: &str) -> Option<&DspProfile> {
691        if !self.enabled {
692            return None;
693        }
694        let only = self.filters_only.iter().any(|d| d == device);
695        self.profiles
696            .iter()
697            .find(|p| p.devices.iter().any(|d| d == device))
698            .filter(|p| {
699                !only || !crate::audio::dsp::profiles::shown_role(p, &self.profiles).corrects()
700            })
701    }
702}
703
704#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
705#[serde(default)]
706pub struct DspProfile {
707    pub name: String,
708    /// Output devices, by name, that play through this profile.
709    pub devices: Vec<String>,
710    /// Gain before the filters. Unset, it is derived from the filters' peak
711    /// gain, so that no boost can push a sample past full scale.
712    #[serde(skip_serializing_if = "Option::is_none")]
713    pub preamp_db: Option<f64>,
714    /// Run in order, at the output rate, ahead of the impulse responses.
715    pub filters: Vec<DspFilter>,
716    /// Impulse responses as WAV files, one per sample rate the correction was
717    /// exported at; a relative path is read from beside the config. Each
718    /// file's own rate is the rate it applies to.
719    pub impulses: Vec<PathBuf>,
720    /// The files it was imported from, by name, for showing where it came
721    /// from. Nothing reads them again.
722    #[serde(default, skip_serializing_if = "Vec::is_empty")]
723    pub source: Vec<String>,
724    /// For a correction installed from AutoEQ: the target it was made for,
725    /// and another to move it to. See `audio::dsp::targets`.
726    #[serde(default, skip_serializing_if = "Option::is_none")]
727    pub target: Option<DspTarget>,
728    /// Other profiles played first, in order: a headphone's correction and
729    /// then taste on top of it, each switched on or off. A profile with
730    /// layers is a stack. See `audio::dsp::Setup::load`.
731    #[serde(default, skip_serializing_if = "Vec::is_empty")]
732    pub layers: Vec<DspLayer>,
733    /// A group rather than a stack of layers: exactly one of its layers
734    /// plays, the one switched on, chosen as one picks a radio button.
735    /// Whole presets imported together are a group: alternatives, not taste
736    /// to play together.
737    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
738    pub group: bool,
739    /// A preset: a correction and its tuning saved together, its layers the
740    /// correction first and then the tuning's EQs, each on or off. What an
741    /// output is set from, and what the quick EQ menu lists.
742    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
743    pub preset: bool,
744    /// For a preset: the output plays its filters alone, with no correction
745    /// (`DspConfig::filters_only`).
746    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
747    pub filters_only: bool,
748    /// Whether it is the account's, kept on every device signed in to its
749    /// kōan server, or this device's alone. Unset, it follows from what the
750    /// profile is: see `audio::dsp::profiles::scope`.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub scope: Option<DspScope>,
753    /// What every device calls it, made when it is first shared. Its name may
754    /// change; this does not.
755    #[serde(default, skip_serializing_if = "Option::is_none")]
756    pub uid: Option<String>,
757    /// The device that first shared it, by name: what tells two different
758    /// profiles of one name apart when they meet.
759    #[serde(default, skip_serializing_if = "Option::is_none")]
760    pub origin: Option<String>,
761    /// What it is for: correcting a headphone, or tuning on top of one.
762    /// Unset, it follows from what the profile is: see
763    /// `audio::dsp::profiles::role`.
764    #[serde(default, skip_serializing_if = "Option::is_none")]
765    pub role: Option<DspRole>,
766    /// A correction built from a headphone's measurement, kept as
767    /// `measurement.csv` in the profile's folder, to `target`, as kōan
768    /// saved one before it fitted bands: played as the bands squig.link's
769    /// auto-EQ fits to it, which are not written back. See `fitted`.
770    #[serde(default, skip_serializing_if = "Option::is_none")]
771    pub measurement: Option<DspMeasurement>,
772    /// A correction fitted to a headphone's measurement, kept as
773    /// `measurement.csv` in the profile's folder, and `target`: its filters
774    /// and preamp are the bands squig.link's auto-EQ fits, refitted when the
775    /// target changes. A key of its own rather than `measurement`, so a
776    /// build that knows only `measurement` plays the bands alone and not a
777    /// correction of its own after them.
778    #[serde(default, skip_serializing_if = "Option::is_none")]
779    pub fitted: Option<DspMeasurement>,
780    /// For a tuning: the target it was made against, by id. On a correction
781    /// to another target, the difference between the two plays first, so
782    /// the tuning sounds as it was made to.
783    #[serde(default, skip_serializing_if = "Option::is_none")]
784    pub tuned_for: Option<String>,
785    /// What an import made it, kept so an edit can be undone.
786    #[serde(default, skip_serializing_if = "Option::is_none")]
787    pub original: Option<DspOriginal>,
788}
789
790/// A profile as imported: its filters and preamp.
791#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
792pub struct DspOriginal {
793    pub filters: Vec<DspFilter>,
794    #[serde(default, skip_serializing_if = "Option::is_none")]
795    pub preamp_db: Option<f64>,
796}
797
798/// What a profile is for. A chain, a profile with its layers, corrects a
799/// headphone once: two corrections would each undo the same headphone.
800#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
801#[serde(rename_all = "snake_case")]
802pub enum DspRole {
803    /// Brings a headphone to a target: an AutoEQ install, a correction built
804    /// from a measurement, or a finished EQ made for the headphone.
805    Correction,
806    /// Taste on top: a bass shelf, a tilt, bands made by hand.
807    Tuning,
808    /// A correction with a tuning already in it, as most finished presets
809    /// are: Qudelix's "Lush", or a squig.link export to a target with a
810    /// preference. Counts as the chain's correction; a tuning on top would
811    /// add taste twice.
812    Baked,
813}
814
815impl DspRole {
816    /// Whether it brings a headphone to a target, so a chain has one.
817    pub fn corrects(self) -> bool {
818        matches!(self, Self::Correction | Self::Baked)
819    }
820}
821
822/// A headphone's measurement and the target it is corrected to.
823#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
824pub struct DspMeasurement {
825    pub ear: DspEar,
826    /// A target id: one that ships, or `added:<name>`.
827    pub target: String,
828}
829
830#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
831#[serde(rename_all = "snake_case")]
832pub enum DspEar {
833    In,
834    Over,
835    Speaker,
836}
837
838/// The bounds a profile must keep to be played: what any real correction
839/// asks, and nothing that would deafen a listener, starve the decode thread
840/// or exhaust memory. `DspProfile::sanitize` brings every profile within
841/// them, wherever it came from. The one place they are set.
842pub mod dsp_bounds {
843    use std::ops::RangeInclusive;
844    pub const FREQ_HZ: RangeInclusive<f64> = 1.0..=48_000.0;
845    pub const GAIN_DB: RangeInclusive<f64> = -30.0..=30.0;
846    pub const Q: RangeInclusive<f64> = 0.01..=100.0;
847    pub const DELAY_MS: RangeInclusive<f64> = 0.0..=2_000.0;
848    /// Two seconds at 384 kHz.
849    pub const DELAY_SAMPLES: RangeInclusive<f64> = 0.0..=768_000.0;
850    /// A mix's linear gain: ±30 dB.
851    pub const MIX_GAIN: f64 = 31.63;
852    pub const CHANNELS: u16 = 64;
853    /// Parametric bands applying to any one channel.
854    pub const BANDS_PER_CHANNEL: usize = 64;
855    pub const FILTERS: usize = 256;
856    pub const GRAPHIC_POINTS: usize = 2_048;
857    pub const LAYERS: usize = 32;
858    pub const NAME: usize = 128;
859
860    // What a whole chain, layers and target step included, may add up to:
861    // each value within bounds can still sum past what a device can hold
862    // or keep up with.
863
864    /// Delay on any one channel, every delay summed, in ms. A delay in
865    /// samples counts at 44.1 kHz, the lowest rate it could mean the most
866    /// time at.
867    pub const CHAIN_DELAY_MS: f64 = 2_000.0;
868    /// Graphic curves on any one channel: each is a minimum-phase FIR of up
869    /// to a second of taps at the output rate. Two is a target step and a
870    /// curve of the user's own.
871    pub const CHAIN_GRAPHICS: usize = 2;
872    /// Mixes in a chain.
873    pub const CHAIN_MIXES: usize = 8;
874    /// Taps of an impulse response, per route: the longest a shipped room
875    /// correction is known to need, Harman's 780 pack at 192 kHz, which is
876    /// over five seconds at 48 kHz, longer than any room's decay.
877    pub const IMPULSE_TAPS: usize = 262_145;
878}
879
880/// Bring a whole chain within the `dsp_bounds` budgets, saying what was
881/// changed: delays past the total on a channel shortened or dropped,
882/// graphic curves and mixes past their counts dropped.
883pub fn budget(filters: &mut Vec<DspFilter>) -> Vec<String> {
884    use dsp_bounds as b;
885    let mut notes = Vec::new();
886    let mut note = |n: String| {
887        if !notes.contains(&n) {
888            notes.push(n);
889        }
890    };
891    let channels = b::CHANNELS as usize;
892    let mut delay = vec![0.0f64; channels];
893    let mut graphics = vec![0usize; channels];
894    let mut mixes = 0;
895    let on = |cs: &[u16], c: usize| cs.is_empty() || cs.contains(&(c as u16));
896    filters.retain_mut(|f| match f {
897        DspFilter::Delay(d) => {
898            let ms = d.ms + d.samples / 44.1;
899            let room = (0..channels)
900                .filter(|c| on(&d.channels, *c))
901                .map(|c| b::CHAIN_DELAY_MS - delay[c])
902                .fold(b::CHAIN_DELAY_MS, f64::min)
903                .max(0.0);
904            if ms > room {
905                note(format!(
906                    "delays shortened to {} ms in all",
907                    b::CHAIN_DELAY_MS
908                ));
909                if room <= 0.0 {
910                    return false;
911                }
912                // Shortened in proportion, keeping how it was given.
913                let scale = room / ms;
914                d.ms *= scale;
915                d.samples = (d.samples * scale).floor();
916            }
917            let ms = d.ms + d.samples / 44.1;
918            for (c, total) in delay.iter_mut().enumerate() {
919                if on(&d.channels, c) {
920                    *total += ms;
921                }
922            }
923            true
924        }
925        DspFilter::Graphic(g) => {
926            let full =
927                (0..channels).any(|c| on(&g.channels, c) && graphics[c] == b::CHAIN_GRAPHICS);
928            if full {
929                note(format!(
930                    "graphic EQs past {} a channel dropped",
931                    b::CHAIN_GRAPHICS
932                ));
933                return false;
934            }
935            for (c, n) in graphics.iter_mut().enumerate() {
936                if on(&g.channels, c) {
937                    *n += 1;
938                }
939            }
940            true
941        }
942        DspFilter::Mix(_) => {
943            mixes += 1;
944            if mixes > b::CHAIN_MIXES {
945                note(format!("mixes past {} dropped", b::CHAIN_MIXES));
946                return false;
947            }
948            true
949        }
950        DspFilter::Band(_) => true,
951    });
952    notes
953}
954
955impl DspProfile {
956    /// Bring the profile within `dsp_bounds`, saying what was changed: values
957    /// past a bound are clamped to it, ones that are not finite are dropped
958    /// with what holds them, and filters, bands, layers and points past a
959    /// cap are cut off at it. Every profile is played as this leaves it,
960    /// wherever it came from, so one that would deafen a listener, starve
961    /// the decode thread or exhaust memory still plays, adjusted, and its
962    /// page says how.
963    pub fn sanitize(&mut self) -> Vec<String> {
964        use dsp_bounds as b;
965        let mut notes: Vec<String> = Vec::new();
966        let mut note = |n: String| {
967            if !notes.contains(&n) {
968                notes.push(n);
969            }
970        };
971        let mut clamp = |what: &str, v: &mut f64, r: &std::ops::RangeInclusive<f64>, unit: &str| {
972            let c = v.clamp(*r.start(), *r.end());
973            if c != *v {
974                note(format!(
975                    "{what} clamped to {}{unit}",
976                    if *v > *r.end() { r.end() } else { r.start() }
977                ));
978                *v = c;
979            }
980        };
981        let finite = |v: f64| v.is_finite();
982        let mut dropped = Vec::new();
983
984        let cleaned: String = self
985            .name
986            .chars()
987            .filter(|c| !c.is_control())
988            .take(b::NAME)
989            .collect();
990        let cleaned = if cleaned.trim().is_empty() {
991            "Profile".to_owned()
992        } else {
993            cleaned
994        };
995        if cleaned != self.name {
996            dropped.push("name shortened".to_owned());
997            self.name = cleaned;
998        }
999        if let Some(db) = self.preamp_db.as_mut() {
1000            if finite(*db) {
1001                clamp("preamp", db, &b::GAIN_DB, " dB");
1002            } else {
1003                self.preamp_db = None;
1004                dropped.push("preamp dropped".to_owned());
1005            }
1006        }
1007        let bad_channel = |cs: &[u16]| cs.iter().any(|c| *c >= b::CHANNELS);
1008        let mut per_channel = [0usize; b::CHANNELS as usize];
1009        let before = self.filters.len();
1010        let mut kept = Vec::with_capacity(before.min(b::FILTERS));
1011        for mut filter in std::mem::take(&mut self.filters) {
1012            if kept.len() == b::FILTERS {
1013                dropped.push(format!("filters past {} dropped", b::FILTERS));
1014                break;
1015            }
1016            let keep = match &mut filter {
1017                DspFilter::Band(f) => {
1018                    if ![f.freq, f.gain_db, f.q].into_iter().all(finite) || bad_channel(&f.channels)
1019                    {
1020                        false
1021                    } else {
1022                        let on =
1023                            |c: usize| f.channels.is_empty() || f.channels.contains(&(c as u16));
1024                        if (0..b::CHANNELS as usize)
1025                            .any(|c| on(c) && per_channel[c] == b::BANDS_PER_CHANNEL)
1026                        {
1027                            dropped.push(format!(
1028                                "bands past {} a channel dropped",
1029                                b::BANDS_PER_CHANNEL
1030                            ));
1031                            continue;
1032                        } else {
1033                            for (c, n) in per_channel.iter_mut().enumerate() {
1034                                if on(c) {
1035                                    *n += 1;
1036                                }
1037                            }
1038                            clamp("a band's frequency", &mut f.freq, &b::FREQ_HZ, " Hz");
1039                            clamp("a band's gain", &mut f.gain_db, &b::GAIN_DB, " dB");
1040                            clamp("a band's Q", &mut f.q, &b::Q, "");
1041                            true
1042                        }
1043                    }
1044                }
1045                DspFilter::Delay(d) => {
1046                    if !finite(d.ms) || !finite(d.samples) || bad_channel(&d.channels) {
1047                        false
1048                    } else {
1049                        clamp("delay", &mut d.ms, &b::DELAY_MS, " ms");
1050                        clamp("delay", &mut d.samples, &b::DELAY_SAMPLES, " samples");
1051                        true
1052                    }
1053                }
1054                DspFilter::Mix(m) => {
1055                    m.outputs.truncate(b::CHANNELS as usize);
1056                    for o in &mut m.outputs {
1057                        o.retain(|(c, g)| *c < b::CHANNELS && finite(*g));
1058                        o.truncate(b::CHANNELS as usize);
1059                        for (_, g) in o.iter_mut() {
1060                            clamp("a mix's gain", g, &(-b::MIX_GAIN..=b::MIX_GAIN), "");
1061                        }
1062                    }
1063                    true
1064                }
1065                DspFilter::Graphic(g) => {
1066                    if bad_channel(&g.channels) {
1067                        false
1068                    } else {
1069                        g.points.retain(|(hz, db)| finite(*hz) && finite(*db));
1070                        if g.points.len() > b::GRAPHIC_POINTS {
1071                            g.points.truncate(b::GRAPHIC_POINTS);
1072                            dropped.push(format!(
1073                                "graphic EQ points past {} dropped",
1074                                b::GRAPHIC_POINTS
1075                            ));
1076                        }
1077                        for (hz, db) in &mut g.points {
1078                            clamp(
1079                                "a graphic EQ's frequency",
1080                                hz,
1081                                &(0.0..=*b::FREQ_HZ.end()),
1082                                " Hz",
1083                            );
1084                            clamp("a graphic EQ's gain", db, &b::GAIN_DB, " dB");
1085                        }
1086                        true
1087                    }
1088                }
1089            };
1090            if keep {
1091                kept.push(filter);
1092            } else {
1093                dropped.push("a filter that could not play dropped".to_owned());
1094            }
1095        }
1096        self.filters = kept;
1097        for n in budget(&mut self.filters) {
1098            dropped.push(n);
1099        }
1100        if self.layers.len() > b::LAYERS {
1101            self.layers.truncate(b::LAYERS);
1102            dropped.push(format!("layers past {} dropped", b::LAYERS));
1103        }
1104        self.layers.retain(|l| l.profile.chars().count() <= b::NAME);
1105        if self
1106            .origin
1107            .as_ref()
1108            .is_some_and(|o| o.chars().count() > b::NAME)
1109        {
1110            self.origin = None;
1111        }
1112        if self
1113            .tuned_for
1114            .as_ref()
1115            .is_some_and(|t| t.chars().count() > b::NAME)
1116        {
1117            self.tuned_for = None;
1118            dropped.push("tuned-for target dropped".to_owned());
1119        }
1120        if self
1121            .measurement
1122            .as_ref()
1123            .is_some_and(|m| m.target.chars().count() > b::NAME)
1124        {
1125            self.measurement = None;
1126            dropped.push("measurement's target dropped".to_owned());
1127        }
1128        if self
1129            .fitted
1130            .as_ref()
1131            .is_some_and(|m| m.target.chars().count() > b::NAME)
1132        {
1133            self.fitted = None;
1134            dropped.push("measurement's target dropped".to_owned());
1135        }
1136        if let Some(t) = &mut self.target {
1137            let long = |s: &str| s.chars().count() > b::NAME;
1138            if long(&t.made_for) {
1139                self.target = None;
1140                dropped.push("target dropped".to_owned());
1141            } else if t.chosen.as_deref().is_some_and(long) {
1142                t.chosen = None;
1143                dropped.push("chosen target dropped".to_owned());
1144            }
1145        }
1146        // The original plays when reverted to: held to the same bounds.
1147        if let Some(o) = self.original.take() {
1148            let mut kept = DspProfile {
1149                filters: o.filters,
1150                preamp_db: o.preamp_db,
1151                ..Default::default()
1152            };
1153            kept.sanitize();
1154            self.original = Some(DspOriginal {
1155                filters: kept.filters,
1156                preamp_db: kept.preamp_db,
1157            });
1158        }
1159        for d in dropped {
1160            note(d);
1161        }
1162        notes
1163    }
1164
1165    /// As played: `sanitize`d, leaving this one as it is.
1166    pub fn sanitized(&self) -> Self {
1167        let mut p = self.clone();
1168        p.sanitize();
1169        p
1170    }
1171}
1172
1173/// Where a profile is kept.
1174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1175#[serde(rename_all = "snake_case")]
1176pub enum DspScope {
1177    /// The account's: synced through its kōan server to its other devices.
1178    Everywhere,
1179    /// This device's: never uploaded.
1180    Device,
1181}
1182
1183/// One profile played as part of another.
1184#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1185pub struct DspLayer {
1186    pub profile: String,
1187    #[serde(default = "layer_on")]
1188    pub on: bool,
1189}
1190
1191fn layer_on() -> bool {
1192    true
1193}
1194
1195/// The target a correction was made for, and the one chosen in its place.
1196#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1197pub struct DspTarget {
1198    /// One of the targets koan ships, by id.
1199    pub made_for: String,
1200    /// A target koan ships, or one added (`added:<name>`). Unset, or the same
1201    /// as `made_for`, the correction plays as it was made.
1202    #[serde(default, skip_serializing_if = "Option::is_none")]
1203    pub chosen: Option<String>,
1204}
1205
1206/// One step of a profile's processing. Bands on different channels commute;
1207/// a mix does not, which is why the steps are an ordered list.
1208#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1209#[serde(tag = "type", rename_all = "snake_case")]
1210pub enum DspFilter {
1211    Delay(Delay),
1212    Mix(Mix),
1213    Graphic(GraphicEq),
1214    #[serde(untagged)]
1215    Band(EqFilter),
1216}
1217
1218impl DspFilter {
1219    /// The channels it applies to, from 0. Empty is every channel; a mix
1220    /// names its own.
1221    pub fn channels(&self) -> &[u16] {
1222        match self {
1223            Self::Band(f) => &f.channels,
1224            Self::Delay(d) => &d.channels,
1225            Self::Graphic(g) => &g.channels,
1226            Self::Mix(_) => &[],
1227        }
1228    }
1229
1230    pub fn channels_mut(&mut self) -> Option<&mut Vec<u16>> {
1231        match self {
1232            Self::Band(f) => Some(&mut f.channels),
1233            Self::Delay(d) => Some(&mut d.channels),
1234            Self::Graphic(g) => Some(&mut g.channels),
1235            Self::Mix(_) => None,
1236        }
1237    }
1238}
1239
1240impl From<EqFilter> for DspFilter {
1241    fn from(f: EqFilter) -> Self {
1242        Self::Band(f)
1243    }
1244}
1245
1246/// A fixed delay: `ms` and `samples` added together, at the output rate.
1247#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1248#[serde(default)]
1249pub struct Delay {
1250    #[serde(skip_serializing_if = "is_zero")]
1251    pub ms: f64,
1252    #[serde(skip_serializing_if = "is_zero")]
1253    pub samples: f64,
1254    /// Keep the fraction of a sample, through an allpass, rather than round
1255    /// to the nearest whole one.
1256    #[serde(skip_serializing_if = "std::ops::Not::not")]
1257    pub subsample: bool,
1258    #[serde(skip_serializing_if = "Vec::is_empty")]
1259    pub channels: Vec<u16>,
1260}
1261
1262fn is_zero(v: &f64) -> bool {
1263    *v == 0.0
1264}
1265
1266/// Channels made from others. `outputs[o]` is what channel `o` becomes, as
1267/// `(input channel, linear gain)` pairs read before any is written; an empty
1268/// list is silence. Channels past the end of `outputs` pass through.
1269#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1270pub struct Mix {
1271    pub outputs: Vec<Vec<(u16, f64)>>,
1272}
1273
1274/// A curve of `(Hz, dB)` points, as Equalizer APO's `GraphicEQ:` gives one,
1275/// run as a minimum-phase FIR designed at the output rate. Between points the
1276/// gain is interpolated against log frequency; past the ends it holds.
1277#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1278pub struct GraphicEq {
1279    pub points: Vec<(f64, f64)>,
1280    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1281    pub channels: Vec<u16>,
1282}
1283
1284/// One parametric band, as AutoEQ and Equalizer APO describe it.
1285#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1286pub struct EqFilter {
1287    #[serde(rename = "type")]
1288    pub kind: EqFilterKind,
1289    /// Centre or corner frequency in Hz.
1290    pub freq: f64,
1291    #[serde(default)]
1292    pub gain_db: f64,
1293    #[serde(default = "default_q")]
1294    pub q: f64,
1295    /// The channels it applies to, from 0. Empty is every channel.
1296    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1297    pub channels: Vec<u16>,
1298}
1299
1300fn default_q() -> f64 {
1301    std::f64::consts::FRAC_1_SQRT_2
1302}
1303
1304#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1305#[serde(rename_all = "snake_case")]
1306pub enum EqFilterKind {
1307    Peaking,
1308    LowShelf,
1309    HighShelf,
1310    LowPass,
1311    HighPass,
1312    Notch,
1313    BandPass,
1314    AllPass,
1315    /// First-order sections, 6 dB per octave. The shelves are at half their
1316    /// gain at `freq`; `q` is not used.
1317    LowShelfFirstOrder,
1318    HighShelfFirstOrder,
1319    LowPassFirstOrder,
1320    HighPassFirstOrder,
1321    AllPassFirstOrder,
1322    /// Flat gain, `gain_db`: a channel's own preamp.
1323    Gain,
1324}
1325
1326impl EqFilterKind {
1327    /// As written in the config.
1328    pub fn name(self) -> &'static str {
1329        match self {
1330            Self::Peaking => "peaking",
1331            Self::LowShelf => "low_shelf",
1332            Self::HighShelf => "high_shelf",
1333            Self::LowPass => "low_pass",
1334            Self::HighPass => "high_pass",
1335            Self::Notch => "notch",
1336            Self::BandPass => "band_pass",
1337            Self::AllPass => "all_pass",
1338            Self::LowShelfFirstOrder => "low_shelf_first_order",
1339            Self::HighShelfFirstOrder => "high_shelf_first_order",
1340            Self::LowPassFirstOrder => "low_pass_first_order",
1341            Self::HighPassFirstOrder => "high_pass_first_order",
1342            Self::AllPassFirstOrder => "all_pass_first_order",
1343            Self::Gain => "gain",
1344        }
1345    }
1346}
1347
1348/// Which of the two files a setting is written to when koan changes it itself.
1349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1350pub enum Layer {
1351    /// `config.toml` — taste, meaningful on any machine, safe in a dotfiles repo.
1352    Shared,
1353    /// `config.local.toml` — belongs to this machine and nowhere else.
1354    Machine,
1355}
1356
1357/// Where the setting at a dotted path belongs.
1358///
1359/// `config.toml` is meant to be committed to a dotfiles repo, so three kinds of
1360/// setting have no business in it: secrets, anything naming this machine's
1361/// hardware, paths or account, and UI state that a keypress flips — the last
1362/// kind would rewrite the shared file every session and land on the next
1363/// machine as someone else's window size.
1364///
1365/// Anything not named here is taste, and taste travels.
1366pub fn layer_of(path: &str) -> Layer {
1367    match path {
1368        // Secrets.
1369        "remote.password"
1370        | "remote.api_key"
1371        | "remote.device_key"
1372        | "subsonic.password"
1373        | "auth.refresh_token"
1374        | "push.key"
1375        | "push.key_path"
1376        | "push.key_id"
1377        | "push.team_id"
1378        // This machine's paths, disk and account.
1379        | "library.folders"
1380        | "remote.enabled"
1381        | "remote.url"
1382        | "remote.username"
1383        | "remote.cache_dir"
1384        | "remote.cache_limit"
1385        // Whether this device follows the account's saved play queue.
1386        | "remote.play_queue"
1387        // This machine's hardware.
1388        | "playback.output_device"
1389        | "playback.renderer"
1390        | "playback.renderer_name"
1391        | "playback.renderers"
1392        | "playback.muted"
1393        | "playback.rate_switch_lead_in_ms"
1394        // Which machine serves Subsonic, and as whom. Enabling a REST API is a
1395        // decision about one host, and the secret guarding it is per-machine.
1396        | "subsonic.enabled"
1397        | "subsonic.port"
1398        | "subsonic.username"
1399        | "subsonic.transcode"
1400        | "subsonic.ffmpeg"
1401        // Whether this machine is open to its network, and where others are.
1402        | "devices.nearby"
1403        | "devices.discoverable"
1404        | "devices.port"
1405        | "devices.addresses"
1406        | "devices.nearby_control"
1407        | "devices.refused"
1408        | "devices.keep_running"
1409        // Which koan server this machine signs in to.
1410        | "auth.server"
1411        // Volatile: UI state behind a keybind or a mouse drag.
1412        | "playback.art_size"
1413        | "visualizer.enabled"
1414        | "visualizer.mode"
1415        | "visualizer.matrix_overlay"
1416        | "visualizer.bass_shake"
1417        | "appearance.rainbow"
1418        // How large this screen draws text, which is a matter of the screen.
1419        | "appearance.text_size" => Layer::Machine,
1420        // The listening setup: these headphones, this room.
1421        p if p == "dsp" || p.starts_with("dsp.") => Layer::Machine,
1422        _ => Layer::Shared,
1423    }
1424}
1425
1426/// Mtimes of the two files `figment()` layers. Keyed on these so a config
1427/// edited by hand is picked up without koan being told about it; `KOAN_*` env
1428/// vars are not tracked, since they are fixed for the life of the process.
1429/// Which directory, and its two files' mtimes. The directory is part of it:
1430/// two directories' files can share an mtime, and a read in one must never
1431/// be served what was read in the other.
1432type ConfigStamp = (PathBuf, Option<SystemTime>, Option<SystemTime>);
1433
1434type CachedConfig = Option<(ConfigStamp, Arc<Config>)>;
1435
1436static CONFIG_CACHE: LazyLock<parking_lot::RwLock<CachedConfig>> =
1437    LazyLock::new(|| parking_lot::RwLock::new(None));
1438
1439/// Moved by every invalidation. A read keeps what it loaded only if this has
1440/// not moved since it began: the stamp alone cannot tell a directory switched
1441/// away and back again mid-read, which leaves the stamp as it was and the
1442/// config loaded from the other directory.
1443static CONFIG_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1444
1445fn config_stamp() -> ConfigStamp {
1446    let (base, local) = stamp_of(&config_file_path(), &config_local_file_path());
1447    (config_dir(), base, local)
1448}
1449
1450/// A file that does not exist stamps as `None`, so creating one is a change.
1451fn stamp_of(base: &Path, local: &Path) -> (Option<SystemTime>, Option<SystemTime>) {
1452    let mtime = |p: &Path| fs::metadata(p).and_then(|m| m.modified()).ok();
1453    (mtime(base), mtime(local))
1454}
1455
1456impl Config {
1457    /// Build the figment provider chain:
1458    /// defaults → config.toml → config.local.toml → KOAN_* env vars.
1459    ///
1460    /// Env vars use `KOAN_` prefix with `__` as section separator:
1461    ///   KOAN_REMOTE__PASSWORD, KOAN_GRAPHQL__PORT, KOAN_PLAYBACK__TARGET_FPS, etc.
1462    fn figment() -> Figment {
1463        let base_path = config_file_path();
1464        let local_path = config_local_file_path();
1465
1466        Figment::from(Serialized::defaults(Config::default()))
1467            .merge(Toml::file(&base_path))
1468            .merge(Toml::file(&local_path))
1469            .merge(Env::prefixed("KOAN_").split("__"))
1470    }
1471
1472    /// Load config from all layers: defaults → config.toml → config.local.toml → KOAN_* env vars.
1473    pub fn load() -> Result<Self, ConfigError> {
1474        let cfg: Self = Self::figment()
1475            .extract()
1476            .map_err(|e| ConfigError::Figment(Box::new(e)))?;
1477
1478        // Security: refuse to start if config files containing secrets are
1479        // tracked by git.
1480        check_secrets_in_git();
1481
1482        Ok(cfg)
1483    }
1484
1485    /// Load config, logging and falling back to defaults on error.
1486    ///
1487    /// Served from the cache, so what this costs is a clone of the struct
1488    /// rather than two file reads and a figment merge.
1489    pub fn load_or_default() -> Self {
1490        (*Self::cached()).clone()
1491    }
1492
1493    /// The merged config, reloaded only when it changed on disk.
1494    ///
1495    /// `load()` re-reads both TOML files and re-runs the whole figment merge,
1496    /// and koan reaches it from paths that run per frame — `library_folders()`
1497    /// is read from a SwiftUI list body. Callers that want to avoid even the
1498    /// clone `load_or_default()` does can hold this `Arc`.
1499    pub fn cached() -> Arc<Config> {
1500        let generation = CONFIG_GENERATION.load(std::sync::atomic::Ordering::SeqCst);
1501        let stamp = config_stamp();
1502        if let Some((seen, cfg)) = CONFIG_CACHE.read().as_ref()
1503            && *seen == stamp
1504        {
1505            return cfg.clone();
1506        }
1507
1508        let cfg = Arc::new(Self::load().unwrap_or_else(|e| {
1509            log::warn!("failed to load config, using defaults: {}", e);
1510            Self::default()
1511        }));
1512        // Kept only if nothing moved while it was read: a switch of
1513        // directory or a write between the stamp and the load would keep one
1514        // directory's config under the other's stamp. Checked under the lock
1515        // a switch takes to drop the cache, so none slips in between.
1516        let mut cache = CONFIG_CACHE.write();
1517        if CONFIG_GENERATION.load(std::sync::atomic::Ordering::SeqCst) == generation
1518            && config_stamp() == stamp
1519        {
1520            *cache = Some((stamp, cfg.clone()));
1521        }
1522        cfg
1523    }
1524
1525    /// Drop the cached config. koan's own writes invalidate explicitly rather
1526    /// than relying on the mtime, which can land in the same filesystem tick as
1527    /// the read before it.
1528    pub fn invalidate_cache() {
1529        let mut cache = CONFIG_CACHE.write();
1530        CONFIG_GENERATION.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1531        *cache = None;
1532    }
1533
1534    /// Load from a specific TOML file (no env var overlay).
1535    pub fn load_from(path: &Path) -> Result<Self, ConfigError> {
1536        let contents = fs::read_to_string(path)?;
1537        let config: Config = toml::from_str(&contents)?;
1538        Ok(config)
1539    }
1540
1541    /// The two files merged, without the env layer.
1542    ///
1543    /// `persist` diffs against this rather than against `config.toml` alone, so
1544    /// a mutation setting a value the user already has writes nothing at all.
1545    /// `KOAN_*` is left out because there is no file to write it back to.
1546    fn from_files() -> Result<Self, ConfigError> {
1547        Figment::from(Serialized::defaults(Config::default()))
1548            .merge(Toml::file(config_file_path()))
1549            .merge(Toml::file(config_local_file_path()))
1550            .extract()
1551            .map_err(|e| ConfigError::Figment(Box::new(e)))
1552    }
1553
1554    /// Whether either config file sets the setting at a dotted path, as
1555    /// opposed to it taking its default.
1556    pub fn set_in_files(path: &str) -> bool {
1557        [config_file_path(), config_local_file_path()]
1558            .iter()
1559            .any(|file| {
1560                let Ok(doc) = read_document(file) else {
1561                    // Unreadable is not unset: assume it says something.
1562                    return true;
1563                };
1564                let mut item = doc.as_item();
1565                for key in path.split('.') {
1566                    match item.get(key) {
1567                        Some(next) => item = next,
1568                        None => return false,
1569                    }
1570                }
1571                true
1572            })
1573    }
1574
1575    /// Apply a mutation and write each changed setting to the file that owns it.
1576    ///
1577    /// Only what the closure actually changed is written, so comments, layout
1578    /// and every untouched key survive — including the commented-out defaults
1579    /// `koan config init` leaves as a reference. `layer_of` decides the file.
1580    ///
1581    /// A shared write also clears any copy of that key from
1582    /// `config.local.toml`: the local layer wins, so leaving one there would
1583    /// make the write silently do nothing. A machine write clears the key from
1584    /// `config.toml` for the same reason in reverse, which drains settings that
1585    /// older versions of koan wrongly wrote to the shared file.
1586    pub fn persist<F>(mutate: F) -> Result<(), ConfigError>
1587    where
1588        F: FnOnce(&mut Config),
1589    {
1590        // Each write reads both files and writes them back whole, so two at
1591        // once would lose whichever finished first: the player's volume and a
1592        // setting changed in the app, say.
1593        static ONE_AT_A_TIME: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
1594        let _one = ONE_AT_A_TIME.lock();
1595        let before = Self::from_files()?;
1596        let mut after = before.clone();
1597        mutate(&mut after);
1598
1599        let mut changes = Vec::new();
1600        diff_into(
1601            "",
1602            &toml::Value::try_from(&before)?,
1603            &toml::Value::try_from(&after)?,
1604            &mut changes,
1605        );
1606        if changes.is_empty() {
1607            return Ok(());
1608        }
1609
1610        let base_path = config_file_path();
1611        let local_path = config_local_file_path();
1612        let mut base = read_document(&base_path)?;
1613        let mut local = read_document(&local_path)?;
1614
1615        for (path, value) in &changes {
1616            let (target, other) = match layer_of(path) {
1617                Layer::Shared => (&mut base, &mut local),
1618                Layer::Machine => (&mut local, &mut base),
1619            };
1620            match value {
1621                Some(v) => doc_set(target, path, v),
1622                None => doc_remove(target, path),
1623            }
1624            doc_remove(other, path);
1625        }
1626
1627        write_document(&base_path, &base, false)?;
1628        write_document(&local_path, &local, true)?;
1629        Self::invalidate_cache();
1630        Ok(())
1631    }
1632
1633    /// Resolved cache directory — the explicit setting, or `default_cache_dir`.
1634    pub fn cache_dir(&self) -> PathBuf {
1635        self.remote
1636            .cache_dir
1637            .clone()
1638            .unwrap_or_else(default_cache_dir)
1639    }
1640
1641    /// Parsed cache limit in bytes, or None if unlimited.
1642    pub fn cache_limit_bytes(&self) -> Option<u64> {
1643        self.remote
1644            .cache_limit
1645            .as_deref()
1646            .and_then(parse_size_bytes)
1647    }
1648}
1649
1650/// Collect the leaf settings that differ between two serialized configs, as
1651/// `(dotted path, new value)`. `None` means the key is gone and should be
1652/// removed rather than written — which is how an emptied password or a cleared
1653/// output device reaches the file as an absent key rather than a blank one.
1654fn diff_into(
1655    prefix: &str,
1656    before: &toml::Value,
1657    after: &toml::Value,
1658    out: &mut Vec<(String, Option<toml::Value>)>,
1659) {
1660    let (b, a) = match (before.as_table(), after.as_table()) {
1661        (Some(b), Some(a)) => (b, a),
1662        _ => {
1663            if before != after {
1664                out.push((prefix.to_string(), Some(after.clone())));
1665            }
1666            return;
1667        }
1668    };
1669
1670    let empty = toml::Value::Table(toml::map::Map::new());
1671    for key in b
1672        .keys()
1673        .chain(a.keys())
1674        .collect::<std::collections::BTreeSet<_>>()
1675    {
1676        let path = if prefix.is_empty() {
1677            key.clone()
1678        } else {
1679            format!("{prefix}.{key}")
1680        };
1681        match (b.get(key), a.get(key)) {
1682            (Some(bv), Some(av)) => diff_into(&path, bv, av, out),
1683            // Newly present: recurse into tables so a new pattern writes one
1684            // key rather than replacing the whole table.
1685            (None, Some(av)) => diff_into(&path, &empty, av, out),
1686            (Some(_), None) => out.push((path, None)),
1687            (None, None) => unreachable!("key came from one of the two tables"),
1688        }
1689    }
1690}
1691
1692fn read_document(path: &Path) -> Result<toml_edit::DocumentMut, ConfigError> {
1693    let Ok(contents) = fs::read_to_string(path) else {
1694        return Ok(toml_edit::DocumentMut::new());
1695    };
1696    contents
1697        .parse::<toml_edit::DocumentMut>()
1698        .map_err(|e| ConfigError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, e)))
1699}
1700
1701/// Write a document, skipping files that would be created empty. `secret` marks
1702/// the file 0o600 — it is the one that holds passwords.
1703fn write_document(
1704    path: &Path,
1705    doc: &toml_edit::DocumentMut,
1706    secret: bool,
1707) -> Result<(), ConfigError> {
1708    let contents = doc.to_string();
1709    if contents.trim().is_empty() && !path.exists() {
1710        return Ok(());
1711    }
1712    if let Some(parent) = path.parent() {
1713        fs::create_dir_all(parent)?;
1714    }
1715    // Written beside the file and renamed over it, so a read never sees it
1716    // half written.
1717    let target = link_target(path);
1718    let temp = unique_beside(&target);
1719    let written = write_new(&temp, &target, contents.as_bytes(), secret)
1720        .and_then(|()| fs::rename(&temp, &target));
1721    if let Err(e) = written {
1722        let _ = fs::remove_file(&temp);
1723        return Err(e.into());
1724    }
1725    #[cfg(target_os = "tvos")]
1726    kept::written(path, contents.as_bytes());
1727    Ok(())
1728}
1729
1730/// Where a write to `path` lands: a symlink, as dotfiles keep, is followed
1731/// rather than replaced, even when what it points at does not exist yet.
1732fn link_target(path: &Path) -> PathBuf {
1733    let mut target = path.to_path_buf();
1734    for _ in 0..40 {
1735        let Ok(next) = fs::read_link(&target) else {
1736            break;
1737        };
1738        target = match target.parent() {
1739            Some(parent) if next.is_relative() => parent.join(next),
1740            _ => next,
1741        };
1742    }
1743    target
1744}
1745
1746/// A name beside `target` no other writer, in this process or another, is
1747/// using.
1748fn unique_beside(target: &Path) -> PathBuf {
1749    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1750    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1751    let name = target
1752        .file_name()
1753        .map(|n| n.to_string_lossy().into_owned())
1754        .unwrap_or_default();
1755    target.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id()))
1756}
1757
1758/// Create `temp` holding `contents`, never readable by more than `target`
1759/// already is: a secret file is 0600 from the moment it exists, any other
1760/// keeps the mode the file it replaces had.
1761fn write_new(temp: &Path, target: &Path, contents: &[u8], secret: bool) -> std::io::Result<()> {
1762    use std::io::Write as _;
1763    let mut options = fs::OpenOptions::new();
1764    options.write(true).create_new(true);
1765    #[cfg(unix)]
1766    let kept_mode = {
1767        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1768        let kept_mode = (!secret)
1769            .then(|| fs::metadata(target).ok())
1770            .flatten()
1771            .map(|m| m.permissions().mode() & 0o7777);
1772        options.mode(if secret {
1773            0o600
1774        } else {
1775            kept_mode.unwrap_or(0o666)
1776        });
1777        kept_mode
1778    };
1779    #[cfg(not(unix))]
1780    let _ = (target, secret);
1781    let mut file = options.open(temp)?;
1782    file.write_all(contents)?;
1783    // The umask can narrow the mode asked for at creation; the file being
1784    // replaced had what it had.
1785    #[cfg(unix)]
1786    if let Some(mode) = kept_mode {
1787        use std::os::unix::fs::PermissionsExt;
1788        file.set_permissions(fs::Permissions::from_mode(mode))?;
1789    }
1790    Ok(())
1791}
1792
1793fn implicit_table() -> toml_edit::Item {
1794    let mut table = toml_edit::Table::new();
1795    // Implicit: the header prints only if the table ends up holding something,
1796    // so writing a nested key never leaves a bare `[organize]` behind.
1797    table.set_implicit(true);
1798    toml_edit::Item::Table(table)
1799}
1800
1801fn doc_set(doc: &mut toml_edit::DocumentMut, path: &str, value: &toml::Value) {
1802    let segments: Vec<&str> = path.split('.').collect();
1803    let (last, parents) = segments.split_last().expect("a diffed path is never empty");
1804
1805    let mut table = doc.as_table_mut();
1806    for segment in parents {
1807        let item = table.entry(segment).or_insert_with(implicit_table);
1808        // A scalar sitting where a section belongs is malformed either way;
1809        // the setting koan is writing wins.
1810        if !item.is_table() {
1811            *item = implicit_table();
1812        }
1813        table = item.as_table_mut().expect("just ensured it is a table");
1814    }
1815    // Comments attach to the key, and `insert` replaces the key. Overwrite the
1816    // value in place where one already exists so the line keeps its notes.
1817    match table.get_mut(last) {
1818        Some(existing) => *existing = to_edit_item(value),
1819        None => {
1820            table.insert(last, to_edit_item(value));
1821        }
1822    }
1823}
1824
1825/// A list of tables — DSP profiles — is written as `[[sections]]`, and any list
1826/// of tables inside one a line per entry, so the file stays editable by hand.
1827fn to_edit_item(value: &toml::Value) -> toml_edit::Item {
1828    let toml::Value::Array(items) = value else {
1829        return toml_edit::value(to_edit_value(value));
1830    };
1831    if items.is_empty() || !items.iter().all(toml::Value::is_table) {
1832        return toml_edit::value(to_edit_value(value));
1833    }
1834    let mut sections = toml_edit::ArrayOfTables::new();
1835    for item in items {
1836        let mut section = toml_edit::Table::new();
1837        for (k, v) in item.as_table().expect("checked above") {
1838            let mut v = to_edit_value(v);
1839            if let toml_edit::Value::Array(list) = &mut v
1840                && list.iter().any(toml_edit::Value::is_inline_table)
1841            {
1842                for entry in list.iter_mut() {
1843                    entry.decor_mut().set_prefix("\n    ");
1844                    if let Some(t) = entry.as_inline_table_mut() {
1845                        t.sort_values_by(|a, _, b, _| key_rank(a).cmp(&key_rank(b)));
1846                    }
1847                }
1848                list.set_trailing("\n");
1849                list.set_trailing_comma(true);
1850            }
1851            section.insert(k, toml_edit::value(v));
1852        }
1853        section.sort_values_by(|a, _, b, _| key_rank(a).cmp(&key_rank(b)));
1854        sections.push(section);
1855    }
1856    toml_edit::Item::ArrayOfTables(sections)
1857}
1858
1859/// What an entry is reads first: a profile's name, a band's type.
1860fn key_rank(key: &toml_edit::Key) -> (u8, &str) {
1861    let k = key.get();
1862    (if k == "name" || k == "type" { 0 } else { 1 }, k)
1863}
1864
1865fn doc_remove(doc: &mut toml_edit::DocumentMut, path: &str) {
1866    let segments: Vec<&str> = path.split('.').collect();
1867    let (last, parents) = segments.split_last().expect("a diffed path is never empty");
1868
1869    let mut table = doc.as_table_mut();
1870    for segment in parents {
1871        match table.get_mut(segment).and_then(|i| i.as_table_mut()) {
1872            Some(child) => table = child,
1873            None => return,
1874        }
1875    }
1876    // An emptied table keeps its header: it still carries the commented-out
1877    // defaults `koan config init` wrote, and those are the reference.
1878    table.remove(last);
1879}
1880
1881fn to_edit_value(value: &toml::Value) -> toml_edit::Value {
1882    match value {
1883        toml::Value::String(s) => s.as_str().into(),
1884        toml::Value::Integer(i) => (*i).into(),
1885        toml::Value::Float(f) => (*f).into(),
1886        toml::Value::Boolean(b) => (*b).into(),
1887        toml::Value::Datetime(d) => d.to_string().into(),
1888        toml::Value::Array(items) => items
1889            .iter()
1890            .map(to_edit_value)
1891            .collect::<toml_edit::Array>()
1892            .into(),
1893        toml::Value::Table(t) => {
1894            let mut inline = toml_edit::InlineTable::new();
1895            for (k, v) in t {
1896                inline.insert(k, to_edit_value(v));
1897            }
1898            inline.into()
1899        }
1900    }
1901}
1902
1903/// Where koan keeps its configuration, library database and cache.
1904///
1905/// `~/.config/koan/` (on iOS, `Library/Application Support/koan`) unless
1906/// pointed elsewhere. `KOAN_CONFIG_DIR` is the
1907/// user-facing way to do that — one machine, more than one library — and
1908/// `set_config_dir` is the in-process one, which is what tests need: without
1909/// it they read whatever configuration belongs to whoever ran them, right down
1910/// to that person's server and their password.
1911pub fn config_dir() -> PathBuf {
1912    if let Some(dir) = CONFIG_DIR.read().clone() {
1913        return dir;
1914    }
1915    if let Some(dir) = std::env::var_os("KOAN_CONFIG_DIR") {
1916        return PathBuf::from(dir);
1917    }
1918    platform_config_dir()
1919}
1920
1921#[cfg(not(any(target_os = "ios", target_os = "tvos")))]
1922fn platform_config_dir() -> PathBuf {
1923    dirs::home_dir()
1924        .unwrap_or_else(|| PathBuf::from("."))
1925        .join(".config")
1926        .join("koan")
1927}
1928
1929/// An iOS app may write inside its container's `Documents`, `Library` and
1930/// `tmp`, and nowhere else: `~/.config` is refused on a device, though the
1931/// simulator allows it. Application Support is where an app's own state goes.
1932#[cfg(target_os = "ios")]
1933fn platform_config_dir() -> PathBuf {
1934    ios_library().join("Application Support").join("koan")
1935}
1936
1937/// A tvOS app has no persistent storage of its own: `Library/Caches` is the
1938/// one directory it can write, and the system empties it when space runs short.
1939/// The files live there, beside the download cache rather than inside it, which
1940/// is trimmed; `kept` holds a copy that survives a purge.
1941#[cfg(target_os = "tvos")]
1942fn platform_config_dir() -> PathBuf {
1943    let dir = ios_library().join("Caches").join("koan-config");
1944    kept::restore(&dir);
1945    dir
1946}
1947
1948/// The configuration files of a tvOS app, mirrored into its preferences.
1949///
1950/// tvOS keeps an app's preferences (up to 500 KB) when it purges
1951/// `Library/Caches`, and a purge would otherwise sign the television out and
1952/// forget its settings. Every write to the platform directory is copied here,
1953/// and the first look at the directory puts back a file that has gone. The
1954/// Keychain would also survive, and is deliberately not used for credentials.
1955/// The library database is not kept: the next sync rebuilds it.
1956#[cfg(target_os = "tvos")]
1957mod kept {
1958    use std::fs;
1959    use std::os::unix::fs::PermissionsExt;
1960    use std::path::Path;
1961    use std::sync::Once;
1962
1963    use core_foundation::base::TCFType;
1964    use core_foundation::data::{CFData, CFDataRef};
1965    use core_foundation::string::CFString;
1966    use core_foundation_sys::base::{CFGetTypeID, CFRelease};
1967    use core_foundation_sys::data::CFDataGetTypeID;
1968    use core_foundation_sys::preferences::{
1969        CFPreferencesAppSynchronize, CFPreferencesCopyAppValue, CFPreferencesSetAppValue,
1970        kCFPreferencesCurrentApplication,
1971    };
1972
1973    const FILES: [&str; 2] = ["config.toml", "config.local.toml"];
1974
1975    /// Once per process: a file that is missing comes back from the
1976    /// preferences, and one that is present is copied into them, which is how
1977    /// a configuration written before this existed starts being kept.
1978    pub(super) fn restore(dir: &Path) {
1979        static ONCE: Once = Once::new();
1980        ONCE.call_once(|| {
1981            for name in FILES {
1982                let path = dir.join(name);
1983                match fs::read(&path) {
1984                    Ok(contents) => save(name, &contents),
1985                    Err(_) => {
1986                        let Some(contents) = load(name) else { continue };
1987                        let _ = fs::create_dir_all(dir);
1988                        if fs::write(&path, &contents).is_ok() {
1989                            let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
1990                            log::info!("config: restored {name} after the system cleared it");
1991                        }
1992                    }
1993                }
1994            }
1995        });
1996    }
1997
1998    /// Mirror a write, if it went to the platform directory rather than one a
1999    /// test or `KOAN_CONFIG_DIR` chose.
2000    pub(super) fn written(path: &Path, contents: &[u8]) {
2001        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
2002            return;
2003        };
2004        if FILES.contains(&name) && path.parent() == Some(super::platform_config_dir().as_path()) {
2005            save(name, contents);
2006        }
2007    }
2008
2009    fn save(name: &str, contents: &[u8]) {
2010        let key = CFString::new(name);
2011        let data = CFData::from_buffer(contents);
2012        // SAFETY: both are live CF objects for the length of the call, and the
2013        // preferences retain what they keep.
2014        unsafe {
2015            CFPreferencesSetAppValue(
2016                key.as_concrete_TypeRef(),
2017                data.as_CFTypeRef(),
2018                kCFPreferencesCurrentApplication,
2019            );
2020            CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
2021        }
2022    }
2023
2024    fn load(name: &str) -> Option<Vec<u8>> {
2025        let key = CFString::new(name);
2026        // SAFETY: a Copy function returns an owned reference or null. Anything
2027        // but data is released here; data is owned by the wrapper.
2028        unsafe {
2029            let value = CFPreferencesCopyAppValue(
2030                key.as_concrete_TypeRef(),
2031                kCFPreferencesCurrentApplication,
2032            );
2033            if value.is_null() {
2034                return None;
2035            }
2036            if CFGetTypeID(value) != CFDataGetTypeID() {
2037                CFRelease(value);
2038                return None;
2039            }
2040            Some(
2041                CFData::wrap_under_create_rule(value as CFDataRef)
2042                    .bytes()
2043                    .to_vec(),
2044            )
2045        }
2046    }
2047}
2048
2049#[cfg(any(target_os = "ios", target_os = "tvos"))]
2050fn ios_library() -> PathBuf {
2051    dirs::home_dir()
2052        .unwrap_or_else(|| PathBuf::from("."))
2053        .join("Library")
2054}
2055
2056/// Where downloads are kept when the config names nowhere.
2057///
2058/// Beside the config everywhere but iOS. There it is `Library/Caches`, which
2059/// is not backed up to iCloud — a cache of lossless files would otherwise count
2060/// against someone's iCloud storage — and which iOS may clear when the device
2061/// is short of space, which is what a cache is for.
2062fn default_cache_dir() -> PathBuf {
2063    #[cfg(any(target_os = "ios", target_os = "tvos"))]
2064    if CONFIG_DIR.read().is_none() && std::env::var_os("KOAN_CONFIG_DIR").is_none() {
2065        return ios_library().join("Caches").join("koan");
2066    }
2067    config_dir().join("cache")
2068}
2069
2070/// Point koan's configuration at `dir` for the life of the process.
2071///
2072/// Takes precedence over `KOAN_CONFIG_DIR`, and drops the cached config, which
2073/// was keyed on the mtimes of files in a directory that is no longer the one
2074/// being read. Set it before anything spawns: background threads resolve the
2075/// directory when they run, not when they are created.
2076pub fn set_config_dir(dir: impl Into<PathBuf>) {
2077    *CONFIG_DIR.write() = Some(dir.into());
2078    Config::invalidate_cache();
2079}
2080
2081/// Point configuration at a directory belonging to this process alone.
2082///
2083/// Tests call this before anything reads configuration. Without it they read
2084/// whatever belongs to whoever ran them — that person's library folders, their
2085/// remote server, and their password — so the same test does
2086/// different things on different machines, and passes on CI only because it
2087/// finds nothing there at all.
2088///
2089/// Process-wide rather than per-test on purpose: the threads koan spawns
2090/// resolve the directory when they run, which is often after the test that
2091/// started them has finished.
2092///
2093/// It waits for a test that holds `SWITCHING` (koan-core's `PERSIST_LOCK`)
2094/// to finish before switching, so that test never has the directory moved
2095/// out from under it mid-way.
2096pub fn isolate_config_for_tests() {
2097    let _one = SWITCHING.lock().unwrap_or_else(|e| e.into_inner());
2098    let dir = std::env::temp_dir().join(format!("koan-test-config-{}", std::process::id()));
2099    let _ = fs::create_dir_all(&dir);
2100    set_config_dir(dir);
2101}
2102
2103/// Held by a test that points config at a directory of its own for its
2104/// whole run, and by `isolate_config_for_tests` while it switches, so no
2105/// test's directory changes under it.
2106#[doc(hidden)]
2107pub static SWITCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
2108
2109static CONFIG_DIR: LazyLock<parking_lot::RwLock<Option<PathBuf>>> =
2110    LazyLock::new(|| parking_lot::RwLock::new(None));
2111
2112/// Path to the base config TOML file (committable to dotfiles).
2113pub fn config_file_path() -> PathBuf {
2114    config_dir().join("config.toml")
2115}
2116
2117/// Path to the local override config (gitignored, machine-specific).
2118pub fn config_local_file_path() -> PathBuf {
2119    config_dir().join("config.local.toml")
2120}
2121
2122/// Path to the database file.
2123pub fn db_path() -> PathBuf {
2124    config_dir().join("koan.db")
2125}
2126
2127/// Above this, `koan.log` is moved aside to `koan.log.1`, replacing the one
2128/// before, so the log never holds more than twice it.
2129const LOG_LIMIT: u64 = 16 * 1024 * 1024;
2130/// How many lines go by between looks at the file's size: the app stays open
2131/// for days, so checking only when the file is opened is not enough.
2132const LOG_CHECK_EVERY: u32 = 4096;
2133
2134/// `koan.log`, kept to a size. Every logger writes through one of these.
2135#[derive(Default)]
2136pub struct LogFile {
2137    file: Option<fs::File>,
2138    lines: u32,
2139}
2140
2141impl LogFile {
2142    pub fn write(&mut self, line: std::fmt::Arguments) {
2143        use std::io::Write as _;
2144        if self.file.is_none() {
2145            self.file = open_log();
2146        }
2147        let Some(file) = self.file.as_mut() else {
2148            return;
2149        };
2150        let _ = writeln!(file, "{line}");
2151        self.lines = self.lines.wrapping_add(1);
2152        if self.lines.is_multiple_of(LOG_CHECK_EVERY)
2153            && file.metadata().is_ok_and(|m| m.len() > LOG_LIMIT)
2154        {
2155            self.file = open_log();
2156        }
2157    }
2158
2159    pub fn flush(&mut self) {
2160        if let Some(file) = self.file.as_mut() {
2161            let _ = std::io::Write::flush(file);
2162        }
2163    }
2164}
2165
2166/// Open `koan.log` for appending, creating the configuration directory first
2167/// and moving an oversized log aside.
2168///
2169/// A logger starts before anything else has had reason to create the
2170/// directory, so on a first launch it would otherwise find nowhere to write.
2171fn open_log() -> Option<fs::File> {
2172    let dir = config_dir();
2173    fs::create_dir_all(&dir).ok()?;
2174    let path = dir.join("koan.log");
2175    if fs::metadata(&path).is_ok_and(|m| m.len() > LOG_LIMIT) {
2176        let _ = fs::rename(&path, dir.join("koan.log.1"));
2177    }
2178    fs::OpenOptions::new()
2179        .create(true)
2180        .append(true)
2181        .open(path)
2182        .ok()
2183}
2184
2185/// Refuse to start when credentials are sitting in version control, which is a
2186/// security incident rather than a warning anyone would act on.
2187///
2188/// Runs once per process. It reads both config files and, when a password is
2189/// present, forks `git ls-files` — and `load()` is reached from UI paths that
2190/// run per frame.
2191fn check_secrets_in_git() {
2192    static ONCE: Once = Once::new();
2193    ONCE.call_once(scan_for_tracked_secrets);
2194}
2195
2196fn scan_for_tracked_secrets() {
2197    let sensitive_fields = ["password", "api_key", "refresh_token"];
2198
2199    for (label, path) in [
2200        ("config.toml", config_file_path()),
2201        ("config.local.toml", config_local_file_path()),
2202    ] {
2203        let Ok(contents) = std::fs::read_to_string(&path) else {
2204            continue;
2205        };
2206
2207        // Check if this file contains any sensitive fields with non-empty values.
2208        let has_secrets = sensitive_fields.iter().any(|field| {
2209            contents.lines().any(|line| {
2210                let line = line.trim();
2211                if let Some(rest) = line.strip_prefix(field) {
2212                    let rest = rest.trim_start();
2213                    if let Some(value) = rest.strip_prefix('=') {
2214                        let value = value.trim().trim_matches('"').trim_matches('\'');
2215                        return !value.is_empty();
2216                    }
2217                }
2218                false
2219            })
2220        });
2221
2222        if !has_secrets {
2223            continue;
2224        }
2225
2226        // Check if this file is tracked by git.
2227        if is_tracked_by_git(&path) {
2228            eprintln!();
2229            eprintln!("╔══════════════════════════════════════════════════════════════╗");
2230            eprintln!("║  SECURITY: {label} contains credentials and is tracked by git!  ║");
2231            eprintln!("╠══════════════════════════════════════════════════════════════╣");
2232            eprintln!("║                                                              ║");
2233            eprintln!("║  File: {:<52} ║", path.display());
2234            eprintln!("║                                                              ║");
2235            eprintln!("║  Your password is in version control. You should:            ║");
2236            eprintln!("║  1. Remove the file from git: git rm --cached <file>         ║");
2237            eprintln!("║  2. Add it to .gitignore                                     ║");
2238            eprintln!("║  3. Rotate your credentials immediately                      ║");
2239            eprintln!("║  4. Move secrets to config.local.toml (gitignored)           ║");
2240            eprintln!("║     `koan remote login` writes there for you                 ║");
2241            eprintln!("║                                                              ║");
2242            eprintln!("╚══════════════════════════════════════════════════════════════╝");
2243            eprintln!();
2244            panic!("Refusing to start: credentials tracked by git in {label}. See above.");
2245        }
2246    }
2247}
2248
2249/// Check if a file is tracked by git (staged or committed, not just in a repo).
2250fn is_tracked_by_git(path: &Path) -> bool {
2251    let Some(parent) = path.parent() else {
2252        return false;
2253    };
2254    // `git ls-files --error-unmatch <file>` exits 0 if tracked, 1 if not.
2255    std::process::Command::new("git")
2256        .args(["ls-files", "--error-unmatch"])
2257        .arg(path)
2258        .current_dir(parent)
2259        .stdout(std::process::Stdio::null())
2260        .stderr(std::process::Stdio::null())
2261        .status()
2262        .is_ok_and(|s| s.success())
2263}
2264
2265#[cfg(test)]
2266pub(crate) mod tests {
2267    use super::*;
2268    use std::fs;
2269
2270    fn tmp_dir() -> PathBuf {
2271        let dir = std::env::temp_dir().join(format!("koan-test-{}", std::process::id()));
2272        fs::create_dir_all(&dir).unwrap();
2273        dir
2274    }
2275
2276    #[test]
2277    fn test_defaults() {
2278        let cfg = Config::default();
2279        assert_eq!(cfg.playback.replaygain, ReplayGainMode::Off);
2280        assert!(!cfg.remote.enabled);
2281    }
2282
2283    #[test]
2284    fn test_roundtrip_toml() {
2285        let cfg = Config::default();
2286        let serialized = toml::to_string_pretty(&cfg).unwrap();
2287        let deserialized: Config = toml::from_str(&serialized).unwrap();
2288        assert_eq!(deserialized.playback.replaygain, cfg.playback.replaygain);
2289        assert_eq!(
2290            deserialized.remote.download_workers,
2291            cfg.remote.download_workers
2292        );
2293    }
2294
2295    #[test]
2296    fn test_load_from_file() {
2297        let dir = tempfile::tempdir().unwrap();
2298        let path = dir.path().join("config.toml");
2299        fs::write(
2300            &path,
2301            r#"
2302[library]
2303folders = ["/tmp/music"]
2304
2305[playback]
2306replaygain = "track"
2307"#,
2308        )
2309        .unwrap();
2310
2311        let cfg = Config::load_from(&path).unwrap();
2312        assert_eq!(cfg.library.folders, vec![PathBuf::from("/tmp/music")]);
2313        assert_eq!(cfg.playback.replaygain, ReplayGainMode::Track);
2314        assert!(!cfg.remote.enabled);
2315    }
2316
2317    #[test]
2318    fn test_partial_toml_uses_defaults() {
2319        let dir = tempfile::tempdir().unwrap();
2320        let path = dir.path().join("partial.toml");
2321        fs::write(&path, "[playback]\ntarget_fps = 30\n").unwrap();
2322
2323        let cfg = Config::load_from(&path).unwrap();
2324        assert_eq!(cfg.playback.target_fps, 30);
2325        assert_eq!(cfg.playback.replaygain, ReplayGainMode::Off);
2326    }
2327
2328    #[test]
2329    fn test_figment_layered_loading() {
2330        let dir = tempfile::tempdir().unwrap();
2331        let base_path = dir.path().join("config.toml");
2332        let local_path = dir.path().join("config.local.toml");
2333
2334        fs::write(
2335            &base_path,
2336            r#"
2337[remote]
2338url = "https://base.example.com"
2339"#,
2340        )
2341        .unwrap();
2342        fs::write(
2343            &local_path,
2344            r#"
2345[remote]
2346enabled = true
2347url = "https://local.example.com"
2348username = "admin"
2349password = "secret"
2350"#,
2351        )
2352        .unwrap();
2353
2354        // Build a figment with explicit paths (can't use load() since it reads from ~/.config).
2355        let cfg: Config = Figment::from(Serialized::defaults(Config::default()))
2356            .merge(Toml::file(&base_path))
2357            .merge(Toml::file(&local_path))
2358            .extract()
2359            .unwrap();
2360
2361        assert!(cfg.remote.enabled);
2362        assert_eq!(cfg.remote.url, "https://local.example.com");
2363        assert_eq!(cfg.remote.username, "admin");
2364        assert_eq!(cfg.remote.password, "secret");
2365    }
2366
2367    #[test]
2368    fn test_figment_missing_keys_preserved() {
2369        let dir = tempfile::tempdir().unwrap();
2370        let base_path = dir.path().join("config.toml");
2371        let local_path = dir.path().join("config.local.toml");
2372
2373        fs::write(
2374            &base_path,
2375            r#"
2376[remote]
2377url = "https://keep.me"
2378username = "keepuser"
2379"#,
2380        )
2381        .unwrap();
2382        fs::write(
2383            &local_path,
2384            r#"
2385[remote]
2386password = "secret"
2387"#,
2388        )
2389        .unwrap();
2390
2391        let cfg: Config = Figment::from(Serialized::defaults(Config::default()))
2392            .merge(Toml::file(&base_path))
2393            .merge(Toml::file(&local_path))
2394            .extract()
2395            .unwrap();
2396
2397        assert_eq!(cfg.remote.url, "https://keep.me");
2398        assert_eq!(cfg.remote.username, "keepuser");
2399        assert_eq!(cfg.remote.password, "secret");
2400    }
2401
2402    #[test]
2403    fn test_env_var_override() {
2404        let dir = tempfile::tempdir().unwrap();
2405        let base_path = dir.path().join("config.toml");
2406
2407        fs::write(
2408            &base_path,
2409            r#"
2410[remote]
2411url = "https://file.example.com"
2412"#,
2413        )
2414        .unwrap();
2415
2416        // SAFETY: test is single-threaded and vars are cleaned up immediately after.
2417        unsafe {
2418            std::env::set_var("KOAN_REMOTE__URL", "https://env.example.com");
2419            std::env::set_var("KOAN_REMOTE__PASSWORD", "env-secret");
2420            std::env::set_var("KOAN_GRAPHQL__PORT", "9999");
2421        }
2422
2423        let cfg: Config = Figment::from(Serialized::defaults(Config::default()))
2424            .merge(Toml::file(&base_path))
2425            .merge(Env::prefixed("KOAN_").split("__"))
2426            .extract()
2427            .unwrap();
2428
2429        assert_eq!(cfg.remote.url, "https://env.example.com");
2430        assert_eq!(cfg.remote.password, "env-secret");
2431        assert_eq!(cfg.graphql.port, 9999);
2432
2433        // Clean up env vars.
2434        unsafe {
2435            std::env::remove_var("KOAN_REMOTE__URL");
2436            std::env::remove_var("KOAN_REMOTE__PASSWORD");
2437            std::env::remove_var("KOAN_GRAPHQL__PORT");
2438        }
2439    }
2440
2441    #[test]
2442    fn test_cache_dir_default() {
2443        let cfg = Config::default();
2444        assert!(cfg.cache_dir().ends_with("cache"));
2445    }
2446
2447    #[test]
2448    fn test_cache_dir_explicit() {
2449        let mut cfg = Config::default();
2450        cfg.remote.cache_dir = Some(PathBuf::from("/custom/cache"));
2451        assert_eq!(cfg.cache_dir(), PathBuf::from("/custom/cache"));
2452    }
2453
2454    #[test]
2455    fn test_organize_config_defaults() {
2456        let cfg = Config::default();
2457        assert!(cfg.organize.default.is_none());
2458        assert!(cfg.organize.patterns.is_empty());
2459    }
2460
2461    #[test]
2462    fn test_organize_config_from_toml() {
2463        let dir = tmp_dir();
2464        let path = dir.join("organize.toml");
2465        fs::write(
2466            &path,
2467            r#"
2468[organize]
2469default = "standard"
2470
2471[organize.patterns]
2472standard = "%album artist%/(%date%) %album%/%tracknumber%. %title%"
2473va-aware = "%album artist%/$if($stricmp(%album artist%,Various Artists),,%album%)"
2474"#,
2475        )
2476        .unwrap();
2477
2478        let cfg = Config::load_from(&path).unwrap();
2479        assert_eq!(cfg.organize.default.as_deref(), Some("standard"));
2480        assert_eq!(cfg.organize.patterns.len(), 2);
2481        assert!(cfg.organize.patterns.contains_key("standard"));
2482        assert!(cfg.organize.patterns.contains_key("va-aware"));
2483
2484        fs::remove_dir_all(&dir).ok();
2485    }
2486
2487    #[test]
2488    fn test_figment_organize_patterns_merge() {
2489        let dir = tempfile::tempdir().unwrap();
2490        let base_path = dir.path().join("config.toml");
2491        let local_path = dir.path().join("config.local.toml");
2492
2493        fs::write(
2494            &base_path,
2495            r#"
2496[organize]
2497default = "standard"
2498
2499[organize.patterns]
2500standard = "base-pattern"
2501"#,
2502        )
2503        .unwrap();
2504        fs::write(
2505            &local_path,
2506            r#"
2507[organize]
2508default = "custom"
2509
2510[organize.patterns]
2511custom = "local-pattern"
2512"#,
2513        )
2514        .unwrap();
2515
2516        let cfg: Config = Figment::from(Serialized::defaults(Config::default()))
2517            .merge(Toml::file(&base_path))
2518            .merge(Toml::file(&local_path))
2519            .extract()
2520            .unwrap();
2521
2522        // Local default wins.
2523        assert_eq!(cfg.organize.default.as_deref(), Some("custom"));
2524        // Both patterns present (figment merges maps).
2525        assert_eq!(cfg.organize.patterns.len(), 2);
2526        assert_eq!(cfg.organize.patterns["standard"], "base-pattern");
2527        assert_eq!(cfg.organize.patterns["custom"], "local-pattern");
2528    }
2529
2530    #[test]
2531    fn test_output_device_config_roundtrip() {
2532        let mut cfg = Config::default();
2533        cfg.playback.output_device = Some("My DAC".into());
2534
2535        let serialized = toml::to_string_pretty(&cfg).unwrap();
2536        let deserialized: Config = toml::from_str(&serialized).unwrap();
2537        assert_eq!(
2538            deserialized.playback.output_device.as_deref(),
2539            Some("My DAC")
2540        );
2541    }
2542
2543    #[test]
2544    fn test_output_device_config_default_is_none() {
2545        let cfg = Config::default();
2546        assert!(cfg.playback.output_device.is_none());
2547
2548        // Roundtrip: None should not appear in serialized output.
2549        let serialized = toml::to_string_pretty(&cfg).unwrap();
2550        assert!(!serialized.contains("output_device"));
2551        let deserialized: Config = toml::from_str(&serialized).unwrap();
2552        assert!(deserialized.playback.output_device.is_none());
2553    }
2554
2555    #[test]
2556    fn test_output_device_config_from_toml() {
2557        let dir = tempfile::tempdir().unwrap();
2558        let path = dir.path().join("config.toml");
2559        fs::write(
2560            &path,
2561            r#"
2562[playback]
2563output_device = "External Speakers"
2564"#,
2565        )
2566        .unwrap();
2567
2568        let cfg = Config::load_from(&path).unwrap();
2569        assert_eq!(
2570            cfg.playback.output_device.as_deref(),
2571            Some("External Speakers")
2572        );
2573    }
2574
2575    #[test]
2576    fn test_graphql_bind_defaults_to_localhost() {
2577        let cfg = GraphqlConfig::default();
2578        assert_eq!(
2579            cfg.bind,
2580            std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
2581        );
2582    }
2583
2584    #[test]
2585    fn test_graphql_bind_from_toml() {
2586        let toml_str = r#"
2587[graphql]
2588bind = "0.0.0.0"
2589port = 5000
2590"#;
2591        let cfg: Config = toml::from_str(toml_str).unwrap();
2592        assert_eq!(
2593            cfg.graphql.bind,
2594            std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)
2595        );
2596        assert_eq!(cfg.graphql.port, 5000);
2597    }
2598
2599    #[test]
2600    fn test_graphql_bind_omitted_defaults_to_localhost() {
2601        let toml_str = r#"
2602[graphql]
2603port = 4000
2604"#;
2605        let cfg: Config = toml::from_str(toml_str).unwrap();
2606        assert_eq!(
2607            cfg.graphql.bind,
2608            std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
2609        );
2610    }
2611
2612    #[test]
2613    fn test_organize_config_roundtrip() {
2614        let mut cfg = Config::default();
2615        cfg.organize.default = Some("standard".into());
2616        cfg.organize
2617            .patterns
2618            .insert("standard".into(), "%artist%/%title%".into());
2619
2620        let serialized = toml::to_string_pretty(&cfg).unwrap();
2621        let deserialized: Config = toml::from_str(&serialized).unwrap();
2622        assert_eq!(deserialized.organize.default.as_deref(), Some("standard"));
2623        assert_eq!(
2624            deserialized.organize.patterns["standard"],
2625            "%artist%/%title%"
2626        );
2627    }
2628
2629    #[test]
2630    fn test_parse_size_bytes() {
2631        assert_eq!(parse_size_bytes("50GB"), Some(50 * 1024 * 1024 * 1024));
2632        assert_eq!(parse_size_bytes("500MB"), Some(500 * 1024 * 1024));
2633        assert_eq!(parse_size_bytes("1TB"), Some(1024 * 1024 * 1024 * 1024));
2634        assert_eq!(parse_size_bytes("100KB"), Some(100 * 1024));
2635        assert_eq!(parse_size_bytes("1024B"), Some(1024));
2636        assert_eq!(parse_size_bytes("1024"), Some(1024));
2637
2638        // Case insensitive.
2639        assert_eq!(parse_size_bytes("50gb"), Some(50 * 1024 * 1024 * 1024));
2640        assert_eq!(parse_size_bytes("50Gb"), Some(50 * 1024 * 1024 * 1024));
2641
2642        // Short suffixes.
2643        assert_eq!(parse_size_bytes("50G"), Some(50 * 1024 * 1024 * 1024));
2644        assert_eq!(parse_size_bytes("500M"), Some(500 * 1024 * 1024));
2645
2646        // Spaces.
2647        assert_eq!(parse_size_bytes("50 GB"), Some(50 * 1024 * 1024 * 1024));
2648        assert_eq!(parse_size_bytes(" 50GB "), Some(50 * 1024 * 1024 * 1024));
2649
2650        // Decimal.
2651        assert_eq!(
2652            parse_size_bytes("1.5GB"),
2653            Some((1.5 * 1024.0 * 1024.0 * 1024.0) as u64)
2654        );
2655
2656        // Invalid.
2657        assert_eq!(parse_size_bytes(""), None);
2658        assert_eq!(parse_size_bytes("abc"), None);
2659        assert_eq!(parse_size_bytes("50XB"), None);
2660    }
2661
2662    #[test]
2663    fn test_cache_limit_config_from_toml() {
2664        let toml_str = r#"
2665[remote]
2666cache_limit = "50GB"
2667"#;
2668        let cfg: Config = toml::from_str(toml_str).unwrap();
2669        assert_eq!(cfg.remote.cache_limit.as_deref(), Some("50GB"));
2670        assert_eq!(cfg.cache_limit_bytes(), Some(50 * 1024 * 1024 * 1024));
2671    }
2672
2673    #[test]
2674    fn test_cache_limit_none_by_default() {
2675        let cfg = Config::default();
2676        assert!(cfg.remote.cache_limit.is_none());
2677        assert!(cfg.cache_limit_bytes().is_none());
2678    }
2679
2680    #[test]
2681    fn test_cache_limit_not_serialized_when_none() {
2682        let cfg = Config::default();
2683        let serialized = toml::to_string_pretty(&cfg).unwrap();
2684        assert!(!serialized.contains("cache_limit"));
2685    }
2686
2687    #[test]
2688    fn player_uses_config_on_init() {
2689        // Verify that Config::load_from correctly picks up playback settings
2690        // that Player::new() would consume. This tests the contract between
2691        // config and player initialization without requiring audio hardware.
2692        let dir = tempfile::tempdir().unwrap();
2693        let path = dir.path().join("config.toml");
2694        fs::write(
2695            &path,
2696            r#"
2697[playback]
2698replaygain = "track"
2699output_device = "My Fancy DAC"
2700pre_amp_db = -3.5
2701target_fps = 30
2702art_size = 32
2703
2704[visualizer]
2705enabled = false
2706mode = "oscilloscope"
2707fps = 30
2708"#,
2709        )
2710        .unwrap();
2711
2712        let cfg = Config::load_from(&path).unwrap();
2713
2714        // These are the fields Player::new() reads from config.
2715        assert_eq!(
2716            cfg.playback.replaygain,
2717            ReplayGainMode::Track,
2718            "replaygain should be 'track'"
2719        );
2720        assert_eq!(
2721            cfg.playback.output_device.as_deref(),
2722            Some("My Fancy DAC"),
2723            "output_device should match config"
2724        );
2725        assert!(
2726            (cfg.playback.pre_amp_db - (-3.5)).abs() < f64::EPSILON,
2727            "pre_amp_db should be -3.5"
2728        );
2729        assert_eq!(cfg.playback.target_fps, 30, "target_fps should be 30");
2730        assert_eq!(cfg.playback.art_size, 32, "art_size should be 32");
2731
2732        // Visualizer config is also consumed at player init.
2733        assert!(!cfg.visualizer.enabled, "visualizer should be disabled");
2734        assert_eq!(cfg.visualizer.mode, "oscilloscope");
2735        assert_eq!(cfg.visualizer.fps, 30);
2736    }
2737
2738    #[test]
2739    fn a_missing_config_file_stamps_as_absent() {
2740        let dir = tempfile::tempdir().unwrap();
2741        let base = dir.path().join("config.toml");
2742        let local = dir.path().join("config.local.toml");
2743
2744        assert_eq!(stamp_of(&base, &local), (None, None));
2745
2746        fs::write(&base, "[remote]\nurl = \"https://example.com\"\n").unwrap();
2747        let (base_stamp, local_stamp) = stamp_of(&base, &local);
2748        assert!(base_stamp.is_some(), "creating the file must be a change");
2749        assert!(local_stamp.is_none());
2750    }
2751
2752    #[test]
2753    fn editing_a_config_file_changes_its_stamp() {
2754        let dir = tempfile::tempdir().unwrap();
2755        let base = dir.path().join("config.toml");
2756        let local = dir.path().join("config.local.toml");
2757        fs::write(&base, "[playback]\ntarget_fps = 60\n").unwrap();
2758
2759        let before = stamp_of(&base, &local);
2760        // Coarse-grained filesystems would otherwise stamp both writes alike.
2761        std::thread::sleep(std::time::Duration::from_millis(20));
2762        fs::write(&base, "[playback]\ntarget_fps = 30\n").unwrap();
2763
2764        assert_ne!(
2765            before,
2766            stamp_of(&base, &local),
2767            "a config edited by hand has to be picked up"
2768        );
2769    }
2770
2771    #[test]
2772    fn invalidating_forces_a_reload() {
2773        let first = Config::cached();
2774        Config::invalidate_cache();
2775        assert!(
2776            !Arc::ptr_eq(&first, &Config::cached()),
2777            "koan's own writes invalidate explicitly; the next read must re-parse"
2778        );
2779    }
2780
2781    // ---- persist: which file a setting lands in -------------------------
2782
2783    /// `persist` reads and writes process-global paths, so these run one at a
2784    /// time rather than racing each other through `set_config_dir`.
2785    pub(crate) static PERSIST_LOCK: &std::sync::Mutex<()> = &super::SWITCHING;
2786
2787    /// Point config at a fresh directory and hand back (base, local) paths.
2788    fn persist_sandbox(name: &str) -> (PathBuf, PathBuf) {
2789        let dir =
2790            std::env::temp_dir().join(format!("koan-persist-{}-{}", name, std::process::id()));
2791        let _ = fs::remove_dir_all(&dir);
2792        fs::create_dir_all(&dir).unwrap();
2793        set_config_dir(&dir);
2794        (config_file_path(), config_local_file_path())
2795    }
2796
2797    /// A write lands where a symlink points, even one pointing at nothing
2798    /// yet; the secret file is 0600, the other keeps its mode; nothing is left
2799    /// beside them.
2800    #[cfg(unix)]
2801    #[test]
2802    fn a_write_keeps_links_modes_and_no_leftovers() {
2803        use std::os::unix::fs::PermissionsExt;
2804        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2805        let dir = tempfile::tempdir().unwrap();
2806        let dotfiles = tempfile::tempdir().unwrap();
2807        std::os::unix::fs::symlink(
2808            dotfiles.path().join("config.toml"),
2809            dir.path().join("config.toml"),
2810        )
2811        .unwrap();
2812        set_config_dir(dir.path());
2813
2814        Config::persist(|c| c.graphql.port = 4100).unwrap();
2815        assert!(
2816            fs::symlink_metadata(config_file_path())
2817                .unwrap()
2818                .is_symlink()
2819        );
2820        assert!(
2821            fs::read_to_string(dotfiles.path().join("config.toml"))
2822                .unwrap()
2823                .contains("4100")
2824        );
2825
2826        fs::set_permissions(
2827            dotfiles.path().join("config.toml"),
2828            fs::Permissions::from_mode(0o640),
2829        )
2830        .unwrap();
2831        Config::persist(|c| {
2832            c.graphql.port = 4101;
2833            c.remote.password = "hunter2".into();
2834        })
2835        .unwrap();
2836        let mode = |p: PathBuf| fs::metadata(p).unwrap().permissions().mode() & 0o777;
2837        assert_eq!(mode(dotfiles.path().join("config.toml")), 0o640);
2838        assert_eq!(mode(config_local_file_path()), 0o600);
2839        assert!(
2840            fs::symlink_metadata(config_file_path())
2841                .unwrap()
2842                .is_symlink()
2843        );
2844
2845        let names = |d: &Path| -> Vec<String> {
2846            fs::read_dir(d)
2847                .unwrap()
2848                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2849                .collect()
2850        };
2851        assert!(!names(dir.path()).iter().any(|n| n.ends_with(".tmp")));
2852        assert_eq!(names(dotfiles.path()), vec!["config.toml".to_string()]);
2853    }
2854
2855    /// A read racing directory switches never caches one directory's config
2856    /// under the other's, even when the directory switches away and back
2857    /// while the read is loading.
2858    #[test]
2859    fn a_read_during_switches_is_never_kept_for_the_wrong_directory() {
2860        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2861        let dirs: Vec<tempfile::TempDir> = (0..2).map(|_| tempfile::tempdir().unwrap()).collect();
2862        for (dir, port) in dirs.iter().zip([4001, 4002]) {
2863            fs::write(
2864                dir.path().join("config.toml"),
2865                format!("[graphql]\nport = {port}\n"),
2866            )
2867            .unwrap();
2868        }
2869        let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
2870        let reader = std::thread::spawn({
2871            let done = done.clone();
2872            move || {
2873                while !done.load(std::sync::atomic::Ordering::Relaxed) {
2874                    Config::cached();
2875                }
2876            }
2877        });
2878        for i in 0..2000 {
2879            let (dir, port) = if i % 2 == 0 {
2880                (&dirs[0], 4001)
2881            } else {
2882                (&dirs[1], 4002)
2883            };
2884            set_config_dir(dir.path());
2885            for _ in 0..3 {
2886                assert_eq!(Config::cached().graphql.port, port, "switch {i}");
2887            }
2888        }
2889        done.store(true, std::sync::atomic::Ordering::Relaxed);
2890        reader.join().unwrap();
2891    }
2892
2893    #[test]
2894    fn persist_keeps_comments_and_untouched_keys() {
2895        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2896        let (base, _local) = persist_sandbox("comments");
2897        fs::write(
2898            &base,
2899            "# koan — shareable defaults\n\n[visualizer]\n# fps = 60\npalette = \"fire\"\n",
2900        )
2901        .unwrap();
2902
2903        Config::persist(|cfg| cfg.visualizer.palette = "neon".into()).unwrap();
2904
2905        let written = fs::read_to_string(&base).unwrap();
2906        assert!(
2907            written.contains("# koan — shareable defaults"),
2908            "the header comment must survive a write: {written}"
2909        );
2910        assert!(
2911            written.contains("# fps = 60"),
2912            "commented-out defaults are the template's whole point: {written}"
2913        );
2914        assert!(written.contains("palette = \"neon\""));
2915        assert!(
2916            !written.contains("[graphql]"),
2917            "an untouched section must not be invented: {written}"
2918        );
2919    }
2920
2921    #[test]
2922    fn persist_routes_machine_settings_to_the_local_file() {
2923        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2924        let (base, local) = persist_sandbox("routing");
2925
2926        Config::persist(|cfg| {
2927            cfg.playback.replaygain = ReplayGainMode::Album;
2928            cfg.playback.output_device = Some("My DAC".into());
2929            cfg.playback.art_size = 40;
2930            cfg.visualizer.mode = "starfield".into();
2931        })
2932        .unwrap();
2933
2934        let shared = fs::read_to_string(&base).unwrap();
2935        let machine = fs::read_to_string(&local).unwrap();
2936
2937        assert!(shared.contains("replaygain = \"album\""), "{shared}");
2938        for machine_only in ["output_device", "art_size", "starfield"] {
2939            assert!(
2940                !shared.contains(machine_only),
2941                "{machine_only} is this machine's, not the dotfiles repo's: {shared}"
2942            );
2943            assert!(machine.contains(machine_only), "{machine}");
2944        }
2945    }
2946
2947    #[test]
2948    fn persist_writes_dsp_profiles_to_the_local_file_as_sections() {
2949        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2950        let (base, local) = persist_sandbox("dsp");
2951
2952        let profile = DspProfile {
2953            name: "HD 600".into(),
2954            devices: vec!["Topping E30".into()],
2955            preamp_db: None,
2956            filters: vec![
2957                DspFilter::Band(EqFilter {
2958                    kind: EqFilterKind::Peaking,
2959                    freq: 20.0,
2960                    gain_db: -1.3,
2961                    q: 2.0,
2962                    channels: vec![],
2963                }),
2964                DspFilter::Band(EqFilter {
2965                    kind: EqFilterKind::HighShelfFirstOrder,
2966                    freq: 10000.0,
2967                    gain_db: 2.5,
2968                    q: 0.7,
2969                    channels: vec![],
2970                }),
2971                DspFilter::Delay(Delay {
2972                    ms: 1.5,
2973                    channels: vec![1],
2974                    ..Default::default()
2975                }),
2976                DspFilter::Mix(Mix {
2977                    outputs: vec![vec![(0, 0.5), (1, 0.5)], vec![]],
2978                }),
2979                DspFilter::Graphic(GraphicEq {
2980                    points: vec![(20.0, -1.0), (1000.0, 0.0)],
2981                    channels: vec![],
2982                }),
2983            ],
2984            impulses: vec![],
2985            source: vec![],
2986            target: None,
2987            layers: vec![],
2988            group: false,
2989            preset: false,
2990            filters_only: false,
2991            scope: None,
2992            uid: None,
2993            origin: None,
2994            role: None,
2995            measurement: None,
2996            fitted: None,
2997            tuned_for: None,
2998            original: None,
2999        };
3000        Config::persist(|cfg| cfg.dsp.profiles.push(profile.clone())).unwrap();
3001
3002        assert!(!base.exists() || !fs::read_to_string(&base).unwrap().contains("dsp"));
3003        let machine = fs::read_to_string(&local).unwrap();
3004        assert!(machine.contains("[[dsp.profiles]]"), "{machine}");
3005        assert!(
3006            machine.contains("\n    { type = \"peaking\""),
3007            "one band per line: {machine}"
3008        );
3009        assert_eq!(Config::from_files().unwrap().dsp.profiles, vec![profile]);
3010        assert_eq!(
3011            Config::from_files()
3012                .unwrap()
3013                .dsp
3014                .profile_for("Topping E30")
3015                .map(|p| p.name.as_str()),
3016            Some("HD 600")
3017        );
3018    }
3019
3020    /// Every bound holds, whatever a profile says: values clamped, ones
3021    /// that are not numbers dropped, counts cut off, each change noted.
3022    #[test]
3023    fn a_profile_is_played_within_bounds() {
3024        let band = |freq: f64, gain_db: f64, q: f64| {
3025            DspFilter::Band(EqFilter {
3026                kind: EqFilterKind::Peaking,
3027                freq,
3028                gain_db,
3029                q,
3030                channels: vec![],
3031            })
3032        };
3033        let mut p = DspProfile {
3034            name: "Loud\u{7}".into(),
3035            preamp_db: Some(60.0),
3036            filters: vec![
3037                DspFilter::Delay(Delay {
3038                    ms: 1e12,
3039                    ..Default::default()
3040                }),
3041                band(0.5, 200.0, 0.0),
3042                band(f64::NAN, 0.0, 1.0),
3043                DspFilter::Band(EqFilter {
3044                    kind: EqFilterKind::Peaking,
3045                    freq: 1000.0,
3046                    gain_db: 0.0,
3047                    q: 1.0,
3048                    channels: vec![99],
3049                }),
3050                DspFilter::Mix(Mix {
3051                    outputs: vec![vec![(0, 1e9), (1, f64::INFINITY)]],
3052                }),
3053                DspFilter::Graphic(GraphicEq {
3054                    points: (0..3000).map(|i| (i as f64, 1.0)).collect(),
3055                    channels: vec![],
3056                }),
3057            ],
3058            ..Default::default()
3059        };
3060        p.filters.extend((0..300).map(|_| band(1000.0, 1.0, 1.0)));
3061        let notes = p.sanitize();
3062        let has = |n: &str| notes.iter().any(|x| x == n);
3063        assert!(has("delay clamped to 2000 ms"), "{notes:?}");
3064        assert!(has("preamp clamped to 30 dB"), "{notes:?}");
3065        assert!(has("a band's gain clamped to 30 dB"), "{notes:?}");
3066        assert!(has("a band's frequency clamped to 1 Hz"), "{notes:?}");
3067        assert!(has("a filter that could not play dropped"), "{notes:?}");
3068        assert!(has("bands past 64 a channel dropped"), "{notes:?}");
3069        assert!(has("graphic EQ points past 2048 dropped"), "{notes:?}");
3070        assert_eq!(p.name, "Loud");
3071        assert_eq!(p.preamp_db, Some(30.0));
3072        assert_eq!(
3073            p.filters[0],
3074            DspFilter::Delay(Delay {
3075                ms: 2000.0,
3076                ..Default::default()
3077            })
3078        );
3079        assert_eq!(p.filters[1], band(1.0, 30.0, 0.01));
3080        let DspFilter::Mix(m) = &p.filters[2] else {
3081            panic!("{:?}", p.filters[2])
3082        };
3083        assert_eq!(m.outputs, vec![vec![(0, dsp_bounds::MIX_GAIN)]]);
3084        let bands = p
3085            .filters
3086            .iter()
3087            .filter(|f| matches!(f, DspFilter::Band(_)))
3088            .count();
3089        assert_eq!(bands, dsp_bounds::BANDS_PER_CHANNEL);
3090        assert!(p.clone().sanitize().is_empty(), "within bounds now");
3091    }
3092
3093    #[test]
3094    fn persist_never_writes_the_default_library_folder_into_the_shared_file() {
3095        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3096        let (base, _local) = persist_sandbox("folders");
3097
3098        // Toggling the visualiser used to serialise the whole struct, baking
3099        // the *default* music directory into the file people commit.
3100        Config::persist(|cfg| cfg.visualizer.enabled = false).unwrap();
3101
3102        let shared = fs::read_to_string(&base).unwrap_or_default();
3103        assert!(
3104            !shared.contains("folders"),
3105            "a visualiser toggle must not invent library folders: {shared}"
3106        );
3107    }
3108
3109    #[test]
3110    fn persist_drains_machine_settings_an_older_koan_left_in_the_shared_file() {
3111        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3112        let (base, local) = persist_sandbox("drain");
3113        fs::write(&base, "[playback]\nart_size = 24\ntarget_fps = 60\n").unwrap();
3114
3115        Config::persist(|cfg| cfg.playback.art_size = 48).unwrap();
3116
3117        let shared = fs::read_to_string(&base).unwrap();
3118        assert!(
3119            !shared.contains("art_size"),
3120            "the stale shared copy has to go, or dotfiles keep carrying it: {shared}"
3121        );
3122        assert!(shared.contains("target_fps"), "{shared}");
3123        assert!(
3124            fs::read_to_string(&local)
3125                .unwrap()
3126                .contains("art_size = 48")
3127        );
3128    }
3129
3130    #[test]
3131    fn persist_clears_the_local_copy_so_a_shared_write_takes_effect() {
3132        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3133        let (_base, local) = persist_sandbox("shadow");
3134        fs::write(&local, "[playback]\ntarget_fps = 30\n").unwrap();
3135
3136        Config::persist(|cfg| cfg.playback.target_fps = 120).unwrap();
3137
3138        assert_eq!(
3139            Config::from_files().unwrap().playback.target_fps,
3140            120,
3141            "local wins the merge, so a shared write over a local copy would \
3142             otherwise be silently ignored: {}",
3143            fs::read_to_string(&local).unwrap()
3144        );
3145    }
3146
3147    #[test]
3148    fn persist_writes_nothing_when_the_mutation_changes_nothing() {
3149        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3150        let (base, _local) = persist_sandbox("noop");
3151        fs::write(&base, "# untouched\n[playback]\ntarget_fps = 60\n").unwrap();
3152
3153        Config::persist(|cfg| cfg.playback.target_fps = 60).unwrap();
3154
3155        assert_eq!(
3156            fs::read_to_string(&base).unwrap(),
3157            "# untouched\n[playback]\ntarget_fps = 60\n"
3158        );
3159    }
3160
3161    #[test]
3162    fn persist_keeps_passwords_out_of_the_shared_file() {
3163        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3164        let (base, local) = persist_sandbox("secrets");
3165
3166        Config::persist(|cfg| {
3167            cfg.remote.password = "hunter2".into();
3168            cfg.subsonic.password = "s3cret".into();
3169            cfg.visualizer.palette = "mono".into();
3170        })
3171        .unwrap();
3172
3173        let shared = fs::read_to_string(&base).unwrap();
3174        assert!(!shared.contains("hunter2"), "{shared}");
3175        assert!(!shared.contains("s3cret"), "{shared}");
3176        assert!(shared.contains("mono"));
3177
3178        let machine = fs::read_to_string(&local).unwrap();
3179        assert!(machine.contains("hunter2") && machine.contains("s3cret"));
3180    }
3181
3182    #[test]
3183    fn persist_removes_a_cleared_password_rather_than_blanking_it() {
3184        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3185        let (_base, local) = persist_sandbox("clear-secret");
3186        fs::write(
3187            &local,
3188            "[remote]\nurl = \"https://a.example\"\npassword = \"old\"\n",
3189        )
3190        .unwrap();
3191
3192        Config::persist(|cfg| cfg.remote.password = String::new()).unwrap();
3193
3194        let machine = fs::read_to_string(&local).unwrap();
3195        assert!(
3196            !machine.contains("password"),
3197            "an emptied secret should leave no key behind: {machine}"
3198        );
3199        assert!(machine.contains("url"), "{machine}");
3200    }
3201
3202    #[test]
3203    fn persist_adds_one_organize_pattern_without_disturbing_the_others() {
3204        let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
3205        let (base, _local) = persist_sandbox("patterns");
3206        fs::write(
3207            &base,
3208            "[organize.patterns]\nflat = \"%artist% - %title%\"\n",
3209        )
3210        .unwrap();
3211
3212        Config::persist(|cfg| {
3213            cfg.organize
3214                .patterns
3215                .insert("standard".into(), "%album artist%/%album%".into());
3216        })
3217        .unwrap();
3218
3219        let cfg = Config::from_files().unwrap();
3220        assert_eq!(cfg.organize.patterns["flat"], "%artist% - %title%");
3221        assert_eq!(cfg.organize.patterns["standard"], "%album artist%/%album%");
3222    }
3223}