use std::str::FromStr; use toml_edit::{Array, ArrayOfTables, DocumentMut, InlineTable, Item, Table, Value, value}; use crate::{ Action, ConfigError, FaderDensity, MessageKind, MixerOrientation, Profile, SelectorField, SeparatorDecoration, SeparatorSize, StatusDisplayMode, TargetKind, UiTheme, }; /// 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 { /// Builds a safe first-run profile with a default-output fader and no MIDI surfaces. pub fn empty(id: &str) -> Result { Self::parse(&format!( r#"schema_version = 1 id = {id:?} startup = "adopt" new_stream = "adopt" [audio] adapter = "auto" preference = ["pulse", "pipewire"] max_gain = 1.0 [[faders]] id = "master-fader" target = {{ kind = "output", id = "default" }} pickup = true pickup_tolerance = 0.02 "# )) } /// Builds a safe replacement for this profile while retaining runtime timing. /// /// Runtime timing cannot be changed while the native worker is running, so an /// emergency reset clears user routing and presentation data but carries that /// one process-level setting into the replacement document. pub fn safe_defaults(&self) -> Result { let profile = self.preview()?; let mut replacement = Self::empty(profile.id().as_str())?; if let Some(runtime) = self.document.get("runtime") { replacement.document["runtime"] = runtime.clone(); } replacement.preview()?; Ok(replacement) } /// 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 how pickup state is represented on mixer faders. pub fn set_status_display(&mut self, mode: StatusDisplayMode) -> 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["status_display"] = value(match mode { StatusDisplayMode::Detailed => "detailed", StatusDisplayMode::Compact => "compact", StatusDisplayMode::Symbol => "symbol", StatusDisplayMode::Color => "color", StatusDisplayMode::Hidden => "hidden", }); Ok(()) }) } /// Selects the configured surface inherited by new MIDI assignments. pub fn set_default_controller(&mut self, surface: Option<&str>) -> 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"))?; if let Some(surface) = surface { ui["default_controller"] = value(surface); } else { ui.remove("default_controller"); } Ok(()) }) } /// Changes the saved terminal palette. pub fn set_theme(&mut self, theme: UiTheme) -> 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["theme"] = value(match theme { UiTheme::Default => "default", UiTheme::Dracula => "dracula", UiTheme::Nord => "nord", UiTheme::GruvboxDark => "gruvbox-dark", UiTheme::CatppuccinMocha => "catppuccin-mocha", UiTheme::SolarizedDark => "solarized-dark", }); Ok(()) }) } /// Adds a discovered MIDI input as a durable control surface. #[allow(clippy::too_many_arguments)] pub fn add_surface( &mut self, id: &str, label: &str, input_port: &str, output_port: Option<&str>, usb_vendor_id: Option<&str>, usb_product_id: Option<&str>, usb_serial: Option<&str>, usb_path: Option<&str>, manual_backend_id: Option<&str>, ) -> Result<(), ConfigError> { self.transaction(|document| { if document.get("surfaces").is_none() { document["surfaces"] = Item::ArrayOfTables(ArrayOfTables::new()); } let surfaces = document .get_mut("surfaces") .and_then(Item::as_array_of_tables_mut) .ok_or_else(|| ConfigError::validation("surfaces", "must be an array of tables"))?; let mut table = Table::new(); table["id"] = value(id); table["label"] = value(label); table["input_port"] = value(input_port); if let Some(output_port) = output_port { table["output_port"] = value(output_port); } if let Some(vendor) = usb_vendor_id { table["usb_vendor_id"] = value(vendor); } if let Some(product) = usb_product_id { table["usb_product_id"] = value(product); } if let Some(serial) = usb_serial { table["usb_serial"] = value(serial); } if let Some(path) = usb_path { table["usb_path"] = value(path); } if let Some(backend_id) = manual_backend_id { table["manual_backend_id"] = value(backend_id); } table["identity_policy"] = value(if manual_backend_id.is_some() { "manual" } else { "require_unique" }); table["motorized"] = value(false); surfaces.push(table); 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); replace_layout_order(tables, ordered); 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(()) }) } /// Updates separator spacing and decoration without changing its order. pub fn set_separator_presentation( &mut self, id: &str, size: SeparatorSize, decoration: SeparatorDecoration, ) -> Result<(), ConfigError> { self.transaction(|document| { let table = find_table_mut(document, "mixer_layout", id)?; if table.get("kind").and_then(Item::as_str) != Some("separator") { return Err(ConfigError::validation( "mixer_layout", "expected separator", )); } table["size"] = value(match size { SeparatorSize::Slim => "slim", SeparatorSize::Standard => "standard", SeparatorSize::Thick => "thick", SeparatorSize::Fill => "fill", }); table["decoration"] = value(match decoration { SeparatorDecoration::Plain => "plain", SeparatorDecoration::Line => "line", SeparatorDecoration::Double => "double", SeparatorDecoration::Box => "box", }); 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::BorderedSlim => "bordered_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); replace_layout_order(tables, ordered); 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 replace_layout_order(tables: &mut ArrayOfTables, mut ordered: Vec) { // Parsed tables carry source positions, and toml_edit sorts by those when // serializing. Reordering the vector alone therefore undoes a move on // save/preview. Give this flat layout array one common source anchor so // stable serialization follows its new order, retaining each table's decor. if let Some(anchor) = ordered.iter().filter_map(Table::position).min() { for table in &mut ordered { table.set_position(anchor); } } *tables = ordered.into_iter().collect(); } 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, ) { let feedback_follows_message = table .get("message") .and_then(Item::as_inline_table) .zip(table.get("feedback").and_then(Item::as_inline_table)) .is_some_and(|(message, feedback)| { message.get("kind").and_then(Value::as_str) == feedback.get("kind").and_then(Value::as_str) && message.get("channel").and_then(Value::as_integer) == feedback.get("channel").and_then(Value::as_integer) && message.get("number").and_then(Value::as_integer) == feedback.get("number").and_then(Value::as_integer) }); 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); if feedback_follows_message && let Some(feedback) = table .get_mut("feedback") .and_then(Item::as_inline_table_mut) { feedback.insert( "kind", Value::from(match kind { MessageKind::Cc => "cc", MessageKind::Note => "note", }), ); feedback.insert("channel", Value::from(i64::from(channel))); feedback.insert("number", Value::from(i64::from(number))); } } 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 }