use std::collections::BTreeSet; use fader_core::{ApplicationId, ChannelGains, Gain, ProfileId, SurfaceId}; use serde::{Deserialize, Serialize}; use crate::{ConfigError, SCHEMA_VERSION, profile::parse_id}; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct ObservedObject { object: String, gain: Vec, muted: bool, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct DesiredObject { object: String, #[serde(skip_serializing_if = "Option::is_none")] gain: Option, #[serde(skip_serializing_if = "Option::is_none")] muted: Option, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Assignment { surface: String, input_port: String, #[serde(skip_serializing_if = "Option::is_none")] output_port: Option, } /// Last selected TUI view for a profile. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum UiView { /// Mixer overview. Mixer, /// MIDI surface assignment and status. Devices, /// Runtime diagnostics. Status, /// Configuration editor. Editor, } /// Durable state for one stable profile; observed values are cache-only. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileState { id: String, last_view: UiView, #[serde(default)] observed: Vec, #[serde(default)] desired: Vec, #[serde(default)] assignments: Vec, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct RawState { schema_version: u16, #[serde(default)] profiles: Vec, } /// Strict durable state without runtime handles, generations, or operations. #[derive(Clone, Debug, PartialEq)] pub struct PersistedState { raw: RawState, } impl PersistedState { /// Parses and validates cached observations, desired state, and assignments. pub fn parse(input: &str) -> Result { let raw: RawState = toml::from_str(input)?; if raw.schema_version != SCHEMA_VERSION { return Err(ConfigError::validation( "schema_version", format!( "unsupported version {}; expected {SCHEMA_VERSION}", raw.schema_version ), )); } validate_profiles(&raw.profiles)?; Ok(Self { raw }) } /// Serializes a canonical representation. pub fn to_toml(&self) -> Result { Ok(toml::to_string_pretty(&self.raw)?) } /// Per-profile state in stable order. pub fn profiles(&self) -> &[ProfileState] { &self.raw.profiles } /// Records the latest durable object intent independently of observations. pub fn set_desired( &mut self, profile_id: &str, object_id: &str, gain: Option, muted: Option, ) -> Result<(), ConfigError> { parse_id::(object_id, "desired.object")?; if gain.is_none() && muted.is_none() { return Err(ConfigError::validation( "desired", "at least one desired gain or mute value is required", )); } if let Some(value) = gain { Gain::new(value) .map_err(|error| ConfigError::validation("desired.gain", error.to_string()))?; } let profile = self .raw .profiles .iter_mut() .find(|profile| profile.id == profile_id) .ok_or_else(|| { ConfigError::validation("profile", format!("unknown profile {profile_id:?}")) })?; if let Some(desired) = profile .desired .iter_mut() .find(|desired| desired.object == object_id) { desired.gain = gain; desired.muted = muted; } else { profile.desired.push(DesiredObject { object: object_id.to_owned(), gain, muted, }); } Ok(()) } /// Records a confirmed per-channel observation without a runtime handle. pub fn set_observed( &mut self, profile_id: &str, object_id: &str, channels: &[f64], muted: bool, ) -> Result<(), ConfigError> { parse_id::(object_id, "observed.object")?; let gains = channels .iter() .copied() .map(Gain::new) .collect::, _>>() .map_err(|error| ConfigError::validation("observed.gain", error.to_string()))?; let validated = ChannelGains::new(gains) .map_err(|error| ConfigError::validation("observed.gain", error.to_string()))?; let profile = find_profile_mut(&mut self.raw.profiles, profile_id)?; let gain = validated.as_slice().iter().map(|gain| gain.get()).collect(); if let Some(observed) = profile .observed .iter_mut() .find(|observed| observed.object == object_id) { observed.gain = gain; observed.muted = muted; } else { profile.observed.push(ObservedObject { object: object_id.to_owned(), gain, muted, }); } Ok(()) } /// Remembers stable surface-to-port assignment hints for one profile. pub fn set_surface_assignment( &mut self, profile_id: &str, surface_id: &str, input_port: &str, output_port: Option<&str>, ) -> Result<(), ConfigError> { parse_id::(surface_id, "assignment.surface")?; if input_port.is_empty() || output_port.is_some_and(str::is_empty) { return Err(ConfigError::validation( "assignment.port", "configured port names must not be empty", )); } let profile = find_profile_mut(&mut self.raw.profiles, profile_id)?; let output_port = output_port.map(str::to_owned); if let Some(assignment) = profile .assignments .iter_mut() .find(|assignment| assignment.surface == surface_id) { assignment.input_port = input_port.to_owned(); assignment.output_port = output_port; } else { profile.assignments.push(Assignment { surface: surface_id.to_owned(), input_port: input_port.to_owned(), output_port, }); } Ok(()) } /// Updates the remembered UI view for one profile. pub fn set_last_view(&mut self, profile_id: &str, view: UiView) -> Result<(), ConfigError> { find_profile_mut(&mut self.raw.profiles, profile_id)?.last_view = view; Ok(()) } /// Creates restart state whose observations are always explicitly stale. pub fn startup( &self, profile_id: &str, policy: crate::StartupPolicy, write_ceiling: f64, ) -> Result { let write_ceiling = Gain::new(write_ceiling) .map_err(|error| ConfigError::validation("write_ceiling", error.to_string()))?; let profile = self .raw .profiles .iter() .find(|profile| profile.id == profile_id) .ok_or_else(|| { ConfigError::validation("profile", format!("unknown profile {profile_id:?}")) })?; let cached_observations = profile .observed .iter() .map(|observation| CachedObservation { object: observation.object.clone(), gain: observation.gain.clone(), muted: observation.muted, stale: true, }) .collect(); let desired = profile .desired .iter() .enumerate() .map(|(index, intent)| { if intent.gain.is_some_and(|gain| gain > write_ceiling.get()) { return Err(ConfigError::validation( format!("profiles.desired[{index}].gain"), format!("exceeds write ceiling {}", write_ceiling.get()), )); } Ok(DesiredWrite { object: intent.object.clone(), gain: intent.gain, muted: intent.muted, }) }) .collect::, _>>()?; Ok(StartupState { policy, cached_observations, desired, }) } } /// A restart-only observation that cannot be mistaken for current backend data. #[derive(Clone, Debug, PartialEq)] pub struct CachedObservation { object: String, gain: Vec, muted: bool, stale: bool, } impl CachedObservation { /// Stable virtual object identifier. pub fn object(&self) -> &str { &self.object } /// Cached per-channel gains retained for display only. pub fn gain(&self) -> &[f64] { &self.gain } /// Cached mute observation. pub const fn muted(&self) -> bool { self.muted } /// Cached observations are always stale until live discovery replaces them. pub const fn is_stale(&self) -> bool { self.stale } } /// A validated desired object write, with absent properties left unchanged. #[derive(Clone, Debug, PartialEq)] pub struct DesiredWrite { object: String, gain: Option, muted: Option, } impl DesiredWrite { /// Stable virtual object identifier. pub fn object(&self) -> &str { &self.object } /// Desired scalar gain, when one was saved. pub const fn gain(&self) -> Option { self.gain } /// Desired mute state, when one was saved. pub const fn muted(&self) -> Option { self.muted } } /// Validated restart data with an explicit adopt/restore policy. #[derive(Clone, Debug, PartialEq)] pub struct StartupState { policy: crate::StartupPolicy, cached_observations: Vec, desired: Vec, } impl StartupState { /// Observations retained for display but never treated as fresh. pub fn cached_observations(&self) -> &[CachedObservation] { &self.cached_observations } /// Saved intents remain visible even when startup adopts live state. pub fn desired_intents(&self) -> &[DesiredWrite] { &self.desired } /// Returns the explicit write for a newly discovered application only when /// the profile selected restore policy. pub fn application_joined(&self, application_id: &str) -> Vec { if self.policy != crate::StartupPolicy::Restore { return Vec::new(); } self.desired .iter() .filter(|intent| intent.object == application_id) .cloned() .collect() } } fn validate_profiles(profiles: &[ProfileState]) -> Result<(), ConfigError> { let mut profile_ids = BTreeSet::new(); for (profile_index, profile) in profiles.iter().enumerate() { parse_id::(&profile.id, &format!("profiles[{profile_index}].id"))?; if !profile_ids.insert(&profile.id) { return Err(ConfigError::validation( format!("profiles[{profile_index}].id"), "duplicate profile state", )); } validate_observed(profile_index, &profile.observed)?; validate_desired(profile_index, &profile.desired)?; validate_assignments(profile_index, &profile.assignments)?; } Ok(()) } fn validate_observed(profile: usize, objects: &[ObservedObject]) -> Result<(), ConfigError> { let mut ids = BTreeSet::new(); for (index, object) in objects.iter().enumerate() { let base = format!("profiles[{profile}].observed[{index}]"); parse_id::(&object.object, &format!("{base}.object"))?; if !ids.insert(&object.object) { return Err(ConfigError::validation( format!("{base}.object"), "duplicate observed object", )); } let gains = object .gain .iter() .copied() .map(Gain::new) .collect::, _>>() .map_err(|error| ConfigError::validation(format!("{base}.gain"), error.to_string()))?; ChannelGains::new(gains) .map_err(|error| ConfigError::validation(format!("{base}.gain"), error.to_string()))?; } Ok(()) } fn validate_desired(profile: usize, objects: &[DesiredObject]) -> Result<(), ConfigError> { let mut ids = BTreeSet::new(); for (index, object) in objects.iter().enumerate() { let base = format!("profiles[{profile}].desired[{index}]"); parse_id::(&object.object, &format!("{base}.object"))?; if !ids.insert(&object.object) { return Err(ConfigError::validation( format!("{base}.object"), "duplicate desired object", )); } if object.gain.is_none() && object.muted.is_none() { return Err(ConfigError::validation( base, "at least one desired gain or mute value is required", )); } if let Some(gain) = object.gain { Gain::new(gain).map_err(|error| { ConfigError::validation(format!("{base}.gain"), error.to_string()) })?; } } Ok(()) } fn validate_assignments(profile: usize, assignments: &[Assignment]) -> Result<(), ConfigError> { let mut ids = BTreeSet::new(); for (index, assignment) in assignments.iter().enumerate() { let base = format!("profiles[{profile}].assignments[{index}]"); parse_id::(&assignment.surface, &format!("{base}.surface"))?; if !ids.insert(&assignment.surface) { return Err(ConfigError::validation( format!("{base}.surface"), "duplicate surface assignment", )); } if assignment.input_port.is_empty() { return Err(ConfigError::validation( format!("{base}.input_port"), "must not be empty", )); } if assignment.output_port.as_deref().is_some_and(str::is_empty) { return Err(ConfigError::validation( format!("{base}.output_port"), "must not be empty when present", )); } } Ok(()) } fn find_profile_mut<'a>( profiles: &'a mut [ProfileState], profile_id: &str, ) -> Result<&'a mut ProfileState, ConfigError> { profiles .iter_mut() .find(|profile| profile.id == profile_id) .ok_or_else(|| { ConfigError::validation("profile", format!("unknown profile {profile_id:?}")) }) }