use std::str::FromStr; use toml_edit::{Array, DocumentMut, InlineTable, Item, Table, Value, value}; use crate::{ConfigError, Profile, SelectorField, TargetKind}; /// Match expression used when creating an application selector. #[derive(Clone, Debug, Eq, PartialEq)] pub enum SelectorPattern { Exact(String), Regex(String), } /// Editable selector input for a virtual application. #[derive(Clone, Debug, Eq, PartialEq)] pub struct SelectorDraft { pub field: SelectorField, pub pattern: SelectorPattern, } /// A comment-preserving profile edit that is revalidated before use. pub struct ProfileDocument { document: DocumentMut, } impl ProfileDocument { /// Parses both the editable TOML representation and semantic profile. pub fn parse(input: &str) -> Result { Profile::parse(input)?; let document = DocumentMut::from_str(input)?; Ok(Self { document }) } /// Changes one application's display label without rebuilding its table. pub fn set_application_label( &mut self, application_id: &str, label: &str, ) -> Result<(), ConfigError> { self.transaction(|document| { let applications = document .get_mut("applications") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| { ConfigError::validation("applications", "missing application array") })?; let Some(application) = applications.iter_mut().find(|table| { table .get("id") .and_then(Item::as_str) .is_some_and(|id| id == application_id) }) else { return Err(ConfigError::validation( "applications", format!("unknown application {application_id:?}"), )); }; let existing = application .get_mut("label") .and_then(Item::as_value_mut) .ok_or_else(|| { ConfigError::validation("applications.label", "missing string label") })?; let decor = existing.decor().clone(); let mut replacement = Value::from(label); *replacement.decor_mut() = decor; *existing = replacement; Ok(()) }) } /// Adds a virtual application and validates the whole resulting profile. pub fn add_application( &mut self, id: &str, label: &str, selectors: &[SelectorDraft], ) -> Result<(), ConfigError> { self.transaction(|document| { let applications = document .get_mut("applications") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| { ConfigError::validation("applications", "missing application array") })?; let mut table = Table::new(); table["id"] = value(id); table["label"] = value(label); let mut selector_values = Array::new(); for selector in selectors { let mut inline = InlineTable::new(); inline.insert("field", Value::from(selector.field.as_str())); match &selector.pattern { SelectorPattern::Exact(pattern) => { inline.insert("exact", Value::from(pattern.as_str())); } SelectorPattern::Regex(pattern) => { inline.insert("regex", Value::from(pattern.as_str())); } } selector_values.push(Value::InlineTable(inline)); } table["selectors"] = value(selector_values); applications.push(table); Ok(()) }) } /// Removes an application only when no remaining object references it. pub fn remove_application(&mut self, id: &str) -> Result<(), ConfigError> { self.transaction(|document| { let applications = document .get_mut("applications") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| { ConfigError::validation("applications", "missing application array") })?; let index = applications .iter() .position(|table| table.get("id").and_then(Item::as_str) == Some(id)) .ok_or_else(|| { ConfigError::validation("applications", format!("unknown application {id:?}")) })?; applications.remove(index); Ok(()) }) } /// Adds an absolute group and validates all member references. pub fn add_group( &mut self, id: &str, label: &str, members: &[&str], ) -> Result<(), ConfigError> { self.transaction(|document| { let groups = document .get_mut("groups") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| ConfigError::validation("groups", "missing group array"))?; let mut table = Table::new(); table["id"] = value(id); table["label"] = value(label); let mut member_values = Array::new(); for member in members { member_values.push(*member); } table["members"] = value(member_values); table["volume_mode"] = value("absolute"); groups.push(table); Ok(()) }) } /// Adds a logical fader and validates its target. pub fn add_fader( &mut self, id: &str, target_kind: TargetKind, target_id: &str, pickup: bool, pickup_tolerance: f64, ) -> Result<(), ConfigError> { self.transaction(|document| { let faders = document .get_mut("faders") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| ConfigError::validation("faders", "missing fader array"))?; let mut table = Table::new(); table["id"] = value(id); let mut target = InlineTable::new(); let kind = match target_kind { TargetKind::Application => "application", TargetKind::Group => "group", TargetKind::Output => "output", }; target.insert("kind", Value::from(kind)); target.insert("id", Value::from(target_id)); table["target"] = value(target); table["pickup"] = value(pickup); table["pickup_tolerance"] = value(pickup_tolerance); faders.push(table); Ok(()) }) } /// Returns the current source without consuming the draft. #[must_use] pub fn source(&self) -> String { self.document.to_string() } /// Builds a validated runtime profile without consuming the draft. pub fn preview(&self) -> Result { Profile::parse(&self.document.to_string()) } fn transaction( &mut self, edit: impl FnOnce(&mut DocumentMut) -> Result<(), ConfigError>, ) -> Result<(), ConfigError> { let mut candidate = self.document.clone(); edit(&mut candidate)?; Profile::parse(&candidate.to_string())?; self.document = candidate; Ok(()) } /// Returns edited TOML only if the complete result remains valid. pub fn finish(self) -> Result { let output = self.document.to_string(); Profile::parse(&output)?; Ok(output) } }