use std::str::FromStr; use toml_edit::{Array, ArrayOfTables, DocumentMut, InlineTable, Item, Table, Value, value}; use crate::{ Action, ConfigError, FaderDensity, MessageKind, MixerOrientation, 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. #[derive(Debug)] 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 the direction used to arrange faders in the mixer. pub fn set_mixer_orientation( &mut self, orientation: MixerOrientation, ) -> Result<(), ConfigError> { self.transaction(|document| { if document.get("ui").is_none() { document["ui"] = Item::Table(Table::new()); } let ui = document .get_mut("ui") .and_then(Item::as_table_mut) .ok_or_else(|| ConfigError::validation("ui", "must be a table"))?; ui["mixer_orientation"] = value(match orientation { MixerOrientation::Vertical => "vertical", MixerOrientation::Horizontal => "horizontal", }); Ok(()) }) } /// 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); table["selectors"] = value(selector_array(selectors)); applications.push(table); Ok(()) }) } /// Replaces an application's editable fields while retaining table comments. pub fn set_application( &mut self, id: &str, label: &str, selectors: &[SelectorDraft], ) -> Result<(), ConfigError> { self.transaction(|document| { let table = find_table_mut(document, "applications", id)?; table["label"] = value(label); table["selectors"] = value(selector_array(selectors)); Ok(()) }) } /// Replaces one capture selector while retaining every other selector. pub fn set_application_selector( &mut self, id: &str, index: usize, selector: &SelectorDraft, ) -> Result<(), ConfigError> { self.transaction(|document| { let table = find_table_mut(document, "applications", id)?; let selectors = table .get_mut("selectors") .and_then(Item::as_value_mut) .and_then(Value::as_array_mut) .ok_or_else(|| { ConfigError::validation("applications.selectors", "missing selector array") })?; let value = selectors.get_mut(index).ok_or_else(|| { ConfigError::validation( "applications.selectors", format!("unknown selector index {index}"), ) })?; let decor = value.decor().clone(); let mut replacement = Value::InlineTable(selector_table(selector)); *replacement.decor_mut() = decor; *value = replacement; 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); table["members"] = value(string_array(members)); table["volume_mode"] = value("absolute"); groups.push(table); Ok(()) }) } /// Replaces a group's label and member set without changing its mode. pub fn set_group( &mut self, id: &str, label: &str, members: &[&str], ) -> Result<(), ConfigError> { self.transaction(|document| { let table = find_table_mut(document, "groups", id)?; table["label"] = value(label); table["members"] = value(string_array(members)); Ok(()) }) } /// Removes an unreferenced group. pub fn remove_group(&mut self, id: &str) -> Result<(), ConfigError> { self.remove_table("groups", id) } /// 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); table["target"] = value(target_table(target_kind, target_id)); table["pickup"] = value(pickup); table["pickup_tolerance"] = value(pickup_tolerance); faders.push(table); Ok(()) }) } /// Replaces a fader's target and pickup policy. pub fn set_fader( &mut self, id: &str, target_kind: TargetKind, target_id: &str, pickup: bool, pickup_tolerance: f64, ) -> Result<(), ConfigError> { self.transaction(|document| { let table = find_table_mut(document, "faders", id)?; table["target"] = value(target_table(target_kind, target_id)); table["pickup"] = value(pickup); table["pickup_tolerance"] = value(pickup_tolerance); Ok(()) }) } /// Removes a fader only when no binding references it. pub fn remove_fader(&mut self, id: &str) -> Result<(), ConfigError> { self.remove_table("faders", id) } /// Adds a presentation-only separator at the requested layout position. pub fn add_separator( &mut self, id: &str, label: &str, position: usize, ) -> Result<(), ConfigError> { self.transaction(|document| { let tables = materialize_mixer_layout(document)?; let mut ordered = tables.iter().cloned().collect::>(); let mut separator = Table::new(); separator["kind"] = value("separator"); separator["id"] = value(id); separator["label"] = value(label); ordered.insert(position.min(ordered.len()), separator); *tables = ordered.into_iter().collect(); Ok(()) }) } /// Changes a separator label without rebuilding unrelated layout entries. pub fn set_separator_label(&mut self, id: &str, label: &str) -> Result<(), ConfigError> { self.transaction(|document| { let tables = materialize_mixer_layout(document)?; let table = tables .iter_mut() .find(|table| { table.get("kind").and_then(Item::as_str) == Some("separator") && table.get("id").and_then(Item::as_str) == Some(id) }) .ok_or_else(|| { ConfigError::validation("mixer_layout", format!("unknown separator {id:?}")) })?; table["label"] = value(label); Ok(()) }) } /// Removes only the selected presentation separator. pub fn remove_separator(&mut self, id: &str) -> Result<(), ConfigError> { self.transaction(|document| { let tables = materialize_mixer_layout(document)?; let index = tables .iter() .position(|table| { table.get("kind").and_then(Item::as_str) == Some("separator") && table.get("id").and_then(Item::as_str) == Some(id) }) .ok_or_else(|| { ConfigError::validation("mixer_layout", format!("unknown separator {id:?}")) })?; tables.remove(index); Ok(()) }) } /// Hides or restores a fader without changing its target or bindings. pub fn set_fader_hidden(&mut self, id: &str, hidden: bool) -> Result<(), ConfigError> { self.transaction(|document| { let tables = materialize_mixer_layout(document)?; let table = tables .iter_mut() .find(|table| { table.get("kind").and_then(Item::as_str) == Some("fader") && table.get("fader").and_then(Item::as_str) == Some(id) }) .ok_or_else(|| { ConfigError::validation("mixer_layout", format!("unknown fader {id:?}")) })?; table["hidden"] = value(hidden); Ok(()) }) } /// Changes one fader's vertical presentation density. pub fn set_fader_density( &mut self, id: &str, density: FaderDensity, ) -> Result<(), ConfigError> { self.transaction(|document| { let tables = materialize_mixer_layout(document)?; let table = tables .iter_mut() .find(|table| { table.get("kind").and_then(Item::as_str) == Some("fader") && table.get("fader").and_then(Item::as_str) == Some(id) }) .ok_or_else(|| { ConfigError::validation("mixer_layout", format!("unknown fader {id:?}")) })?; table["density"] = value(match density { FaderDensity::Slim => "slim", FaderDensity::Standard => "standard", FaderDensity::Thick => "thick", }); Ok(()) }) } /// Moves a fader or separator, preserving the complete table and its comments. pub fn move_layout_entry(&mut self, id: &str, position: usize) -> Result<(), ConfigError> { self.transaction(|document| { let tables = materialize_mixer_layout(document)?; let mut ordered = tables.iter().cloned().collect::>(); let index = ordered .iter() .position(|table| layout_entry_id(table) == Some(id)) .ok_or_else(|| { ConfigError::validation("mixer_layout", format!("unknown layout entry {id:?}")) })?; let entry = ordered.remove(index); ordered.insert(position.min(ordered.len()), entry); *tables = ordered.into_iter().collect(); Ok(()) }) } /// Adds one validated surface control assignment. pub fn add_binding( &mut self, surface: &str, fader: &str, action: Action, kind: MessageKind, channel: u16, number: u16, ) -> Result<(), ConfigError> { self.transaction(|document| { let bindings = document .get_mut("bindings") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| ConfigError::validation("bindings", "missing binding array"))?; let mut table = Table::new(); table["surface"] = value(surface); table["fader"] = value(fader); table["action"] = value(match action { Action::Volume => "volume", Action::ToggleMute => "toggle_mute", }); if action == Action::ToggleMute { table["edge"] = value("press"); } let mut message = InlineTable::new(); message.insert( "kind", Value::from(match kind { MessageKind::Cc => "cc", MessageKind::Note => "note", }), ); message.insert("channel", Value::from(i64::from(channel))); message.insert("number", Value::from(i64::from(number))); table["message"] = value(message); bindings.push(table); Ok(()) }) } /// Replaces all assignments for one fader action with one validated control. pub fn set_binding( &mut self, surface: &str, fader: &str, action: Action, kind: MessageKind, channel: u16, number: u16, ) -> Result<(), ConfigError> { self.transaction(|document| { let bindings = document .get_mut("bindings") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| ConfigError::validation("bindings", "missing binding array"))?; let matching = bindings .iter() .enumerate() .filter_map(|(index, table)| binding_matches(table, fader, action).then_some(index)) .collect::>(); if let Some(first) = matching.first().copied() { let table = bindings.get_mut(first).ok_or_else(|| { ConfigError::validation("bindings", "binding disappeared during edit") })?; update_binding_table(table, surface, fader, action, kind, channel, number); for index in matching.into_iter().skip(1).rev() { bindings.remove(index); } } else { bindings.push(binding_table(surface, fader, action, kind, channel, number)); } Ok(()) }) } /// Removes only the selected fader action assignments. pub fn remove_bindings(&mut self, fader: &str, action: Action) -> Result<(), ConfigError> { self.transaction(|document| { let bindings = document .get_mut("bindings") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| ConfigError::validation("bindings", "missing binding array"))?; bindings.retain(|table| !binding_matches(table, fader, action)); 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(()) } fn remove_table(&mut self, section: &str, id: &str) -> Result<(), ConfigError> { self.transaction(|document| { let tables = document .get_mut(section) .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| ConfigError::validation(section, "missing table array"))?; let index = tables .iter() .position(|table| table.get("id").and_then(Item::as_str) == Some(id)) .ok_or_else(|| { ConfigError::validation(section, format!("unknown {section} entry {id:?}")) })?; tables.remove(index); 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) } } fn find_table_mut<'a>( document: &'a mut DocumentMut, section: &str, id: &str, ) -> Result<&'a mut Table, ConfigError> { document .get_mut(section) .and_then(Item::as_array_of_tables_mut) .and_then(|tables| { tables.iter_mut().find(|table| { table .get("id") .and_then(Item::as_str) .is_some_and(|candidate| candidate == id) }) }) .ok_or_else(|| ConfigError::validation(section, format!("unknown {section} entry {id:?}"))) } fn materialize_mixer_layout(document: &mut DocumentMut) -> Result<&mut ArrayOfTables, ConfigError> { let faders = document .get("faders") .and_then(Item::as_array_of_tables) .ok_or_else(|| ConfigError::validation("faders", "missing fader array"))? .iter() .filter_map(|table| table.get("id").and_then(Item::as_str).map(str::to_owned)) .collect::>(); if document.get("mixer_layout").is_none() { document["mixer_layout"] = Item::ArrayOfTables(ArrayOfTables::new()); } let tables = document .get_mut("mixer_layout") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| ConfigError::validation("mixer_layout", "must be an array of tables"))?; let present = tables .iter() .filter(|table| table.get("kind").and_then(Item::as_str) == Some("fader")) .filter_map(|table| table.get("fader").and_then(Item::as_str).map(str::to_owned)) .collect::>(); for fader in faders { if !present.contains(&fader) { let mut table = Table::new(); table["kind"] = value("fader"); table["fader"] = value(fader); table["hidden"] = value(false); table["density"] = value("standard"); tables.push(table); } } Ok(tables) } fn layout_entry_id(table: &Table) -> Option<&str> { match table.get("kind").and_then(Item::as_str) { Some("fader") => table.get("fader").and_then(Item::as_str), Some("separator") => table.get("id").and_then(Item::as_str), _ => None, } } fn selector_array(selectors: &[SelectorDraft]) -> Array { let mut values = Array::new(); for selector in selectors { values.push(Value::InlineTable(selector_table(selector))); } values } fn selector_table(selector: &SelectorDraft) -> InlineTable { 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())); } } inline } fn binding_matches(table: &Table, fader: &str, action: Action) -> bool { table.get("fader").and_then(Item::as_str) == Some(fader) && table.get("action").and_then(Item::as_str) == Some(match action { Action::Volume => "volume", Action::ToggleMute => "toggle_mute", }) } fn binding_table( surface: &str, fader: &str, action: Action, kind: MessageKind, channel: u16, number: u16, ) -> Table { let mut table = Table::new(); update_binding_table(&mut table, surface, fader, action, kind, channel, number); table } fn update_binding_table( table: &mut Table, surface: &str, fader: &str, action: Action, kind: MessageKind, channel: u16, number: u16, ) { table["surface"] = value(surface); table["fader"] = value(fader); table["action"] = value(match action { Action::Volume => "volume", Action::ToggleMute => "toggle_mute", }); if action == Action::ToggleMute { table["edge"] = value("press"); } else { table.remove("edge"); } let mut message = InlineTable::new(); message.insert( "kind", Value::from(match kind { MessageKind::Cc => "cc", MessageKind::Note => "note", }), ); message.insert("channel", Value::from(i64::from(channel))); message.insert("number", Value::from(i64::from(number))); table["message"] = value(message); } fn string_array(values: &[&str]) -> Array { let mut array = Array::new(); for item in values { array.push(*item); } array } fn target_table(kind: TargetKind, id: &str) -> InlineTable { let mut target = InlineTable::new(); target.insert( "kind", Value::from(match kind { TargetKind::Application => "application", TargetKind::Group => "group", TargetKind::Output => "output", }), ); target.insert("id", Value::from(id)); target }