diff --git a/README.md b/README.md index 19d572f..1544afa 100644 --- a/README.md +++ b/README.md @@ -101,14 +101,18 @@ they do not represent a live hardware session. | Change volume | Left/Right | Up/Down | | Reorder | Shift+Up/Down or Shift+J/K | Shift+Left/Right or Shift+J/K | | Toggle mute | M | M | -| Edit fader or separator | E | E | -| Add/remove separator | A / D | A / D | +| Add fader, group, or separator | A | A | +| Edit selected entry | E | E | +| Delete selected entry | D | D | | Hide selected fader | Shift+H | Shift+H | | Help | h or ? | h or ? | Use `Tab` to open Config, `T` to cycle the theme, and `Q` to open the quit confirmation. Fader editing exposes capture rules, group membership, separate controller/Learn/Unlearn actions for volume and mute, size, and visibility. +Add opens a chooser for a new application fader, empty group, or separator. +New faders and groups open directly in the editor; delete asks for confirmation +and removes the selected fader and its unshared target, or the selected separator. Config → Active profile opens the profile switcher. Config → Reset active profile provides an emergency return to safe defaults; confirming it immediately saves and activates the reset and keeps a `.reset.bak` diff --git a/architecture.md b/architecture.md index b4ef6a8..5740580 100644 --- a/architecture.md +++ b/architecture.md @@ -517,9 +517,19 @@ The always-visible quick-help footer omits intuitive navigation, volume, and alternative bindings; it keeps compact non-obvious actions with Add, Edit, and Delete shown separately. The detailed popup documents J/K, `?`, and Home/End. -The selected main-list entry can be moved directly, and separators can be -added, renamed, moved, or removed. A centered separator dialog edits its name, -size, and decoration. Names may be empty; the stable ID still identifies each separator. Plain with +The selected main-list entry can be moved directly. `A` opens a chooser for an +application fader, group, or separator. Creating an application fader adds its +application target with a deliberately non-matching exact selector, while a new +group starts empty in absolute mode; both operations add a visible layout entry +and open the field-oriented fader editor. `D` confirms removal of either a +separator or a fader with its bindings and layout entry. A fader's application +or group target is also removed when no other fader owns it; applications still +referenced by a group are retained. These compound edits validate and publish as +one draft transaction, so no dangling intermediate configuration is observable. +The draft must still be saved before it becomes active. + +A centered separator dialog edits its name, size, and decoration. Names may be +empty; the stable ID still identifies each separator. Plain with an empty name creates a spacer, and an unnamed Line/Double separator draws an unbroken rule. Separator size is independent of fader density: `slim`, `standard` (default), `thick`, or `fill`. Size controls height in the diff --git a/config/src/document.rs b/config/src/document.rs index c8717e1..aaa71ec 100644 --- a/config/src/document.rs +++ b/config/src/document.rs @@ -402,6 +402,48 @@ pickup_tolerance = 0.02 }) } + /// Adds an offline application and its visible logical fader atomically. + pub fn add_application_fader( + &mut self, + application_id: &str, + label: &str, + selector: &SelectorDraft, + fader_id: &str, + position: usize, + ) -> Result<(), ConfigError> { + self.transaction(|document| { + let applications = array_of_tables_mut(document, "applications")?; + let mut application = Table::new(); + application["id"] = value(application_id); + application["label"] = value(label); + application["selectors"] = value(selector_array(std::slice::from_ref(selector))); + applications.push(application); + push_fader(document, fader_id, TargetKind::Application, application_id)?; + insert_fader_layout(document, fader_id, position) + }) + } + + /// Adds an empty absolute group and its visible logical fader atomically. + pub fn add_group_fader( + &mut self, + group_id: &str, + label: &str, + fader_id: &str, + position: usize, + ) -> Result<(), ConfigError> { + self.transaction(|document| { + let groups = array_of_tables_mut(document, "groups")?; + let mut group = Table::new(); + group["id"] = value(group_id); + group["label"] = value(label); + group["members"] = value(Array::new()); + group["volume_mode"] = value("absolute"); + groups.push(group); + push_fader(document, fader_id, TargetKind::Group, group_id)?; + insert_fader_layout(document, fader_id, position) + }) + } + /// Replaces a fader's target and pickup policy. pub fn set_fader( &mut self, @@ -425,6 +467,56 @@ pickup_tolerance = 0.02 self.remove_table("faders", id) } + /// Removes a mixer fader and its owned target when no other route needs it. + pub fn remove_mixer_fader(&mut self, id: &str) -> Result<(), ConfigError> { + self.transaction(|document| { + let (target_kind, target_id) = fader_target(document, id)?; + remove_table_entry(document, "faders", id)?; + if let Some(bindings) = document + .get_mut("bindings") + .and_then(Item::as_array_of_tables_mut) + { + bindings.retain(|table| table.get("fader").and_then(Item::as_str) != Some(id)); + } + if let Some(layout) = document + .get_mut("mixer_layout") + .and_then(Item::as_array_of_tables_mut) + { + layout.retain(|table| { + table.get("kind").and_then(Item::as_str) != Some("fader") + || table.get("fader").and_then(Item::as_str) != Some(id) + }); + } + let target_is_used = document + .get("faders") + .and_then(Item::as_array_of_tables) + .is_some_and(|faders| { + faders.iter().any(|table| { + table + .get("target") + .and_then(Item::as_value) + .and_then(Value::as_inline_table) + .is_some_and(|target| { + target.get("kind").and_then(Value::as_str) + == Some(target_kind.as_str()) + && target.get("id").and_then(Value::as_str) + == Some(target_id.as_str()) + }) + }) + }); + if !target_is_used { + match target_kind.as_str() { + "application" if !group_references_application(document, &target_id) => { + remove_table_entry(document, "applications", &target_id)?; + } + "group" => remove_table_entry(document, "groups", &target_id)?, + _ => {} + } + } + Ok(()) + }) + } + /// Adds a presentation-only separator at the requested layout position. pub fn add_separator( &mut self, @@ -729,6 +821,118 @@ fn find_table_mut<'a>( .ok_or_else(|| ConfigError::validation(section, format!("unknown {section} entry {id:?}"))) } +fn array_of_tables_mut<'a>( + document: &'a mut DocumentMut, + section: &str, +) -> Result<&'a mut ArrayOfTables, ConfigError> { + if document.get(section).is_none() { + document[section] = Item::ArrayOfTables(ArrayOfTables::new()); + } + document + .get_mut(section) + .and_then(Item::as_array_of_tables_mut) + .ok_or_else(|| ConfigError::validation(section, "must be an array of tables")) +} + +fn push_fader( + document: &mut DocumentMut, + id: &str, + target_kind: TargetKind, + target_id: &str, +) -> Result<(), ConfigError> { + let faders = array_of_tables_mut(document, "faders")?; + let mut fader = Table::new(); + fader["id"] = value(id); + fader["target"] = value(target_table(target_kind, target_id)); + fader["pickup"] = value(true); + fader["pickup_tolerance"] = value(0.02); + faders.push(fader); + Ok(()) +} + +fn insert_fader_layout( + document: &mut DocumentMut, + fader_id: &str, + position: usize, +) -> Result<(), ConfigError> { + let layout = materialize_mixer_layout(document)?; + let index = layout + .iter() + .position(|table| { + table.get("kind").and_then(Item::as_str) == Some("fader") + && table.get("fader").and_then(Item::as_str) == Some(fader_id) + }) + .ok_or_else(|| ConfigError::validation("mixer_layout", "new fader was not materialized"))?; + let mut ordered = layout.iter().cloned().collect::>(); + let table = ordered.remove(index); + let position = position.min(ordered.len()); + ordered.insert(position, table); + replace_layout_order(layout, ordered); + Ok(()) +} + +fn fader_target(document: &DocumentMut, id: &str) -> Result<(String, String), ConfigError> { + let table = document + .get("faders") + .and_then(Item::as_array_of_tables) + .and_then(|faders| { + faders + .iter() + .find(|table| table.get("id").and_then(Item::as_str) == Some(id)) + }) + .ok_or_else(|| ConfigError::validation("faders", format!("unknown fader {id:?}")))?; + let target = table + .get("target") + .and_then(Item::as_value) + .and_then(Value::as_inline_table) + .ok_or_else(|| ConfigError::validation("faders.target", "missing inline target"))?; + let kind = target + .get("kind") + .and_then(Value::as_str) + .ok_or_else(|| ConfigError::validation("faders.target.kind", "missing string kind"))?; + let target_id = target + .get("id") + .and_then(Value::as_str) + .ok_or_else(|| ConfigError::validation("faders.target.id", "missing string ID"))?; + Ok((kind.to_owned(), target_id.to_owned())) +} + +fn remove_table_entry( + document: &mut DocumentMut, + section: &str, + id: &str, +) -> Result<(), ConfigError> { + let tables = document + .get_mut(section) + .and_then(Item::as_array_of_tables_mut) + .ok_or_else(|| ConfigError::validation(section, "missing 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 entry {id:?}")))?; + tables.remove(index); + Ok(()) +} + +fn group_references_application(document: &DocumentMut, application: &str) -> bool { + document + .get("groups") + .and_then(Item::as_array_of_tables) + .is_some_and(|groups| { + groups.iter().any(|group| { + group + .get("members") + .and_then(Item::as_value) + .and_then(Value::as_array) + .is_some_and(|members| { + members + .iter() + .any(|member| member.as_str() == Some(application)) + }) + }) + }) +} + fn materialize_mixer_layout(document: &mut DocumentMut) -> Result<&mut ArrayOfTables, ConfigError> { let faders = document .get("faders") diff --git a/config/tests/editor.rs b/config/tests/editor.rs index a2e8de2..20b1bdb 100644 --- a/config/tests/editor.rs +++ b/config/tests/editor.rs @@ -5,6 +5,47 @@ use fader_config::{ const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml"); +#[test] +fn mixer_objects_are_created_and_removed_as_atomic_valid_units() { + let mut draft = ProfileDocument::empty("default").unwrap(); + draft + .add_application_fader( + "chat", + "Chat", + &SelectorDraft { + field: SelectorField::ApplicationName, + pattern: SelectorPattern::Exact("__unconfigured_chat__".into()), + }, + "chat-fader", + 0, + ) + .unwrap(); + draft + .add_group_fader("players", "Players", "players-fader", 1) + .unwrap(); + + let profile = draft.preview().unwrap(); + assert_eq!(profile.applications()[0].id(), "chat"); + assert!(profile.groups()[0].members().is_empty()); + assert_eq!(profile.faders().len(), 3); + assert!(matches!( + &profile.mixer_layout()[0], + MixerLayoutEntry::Fader { fader, .. } if fader == "chat-fader" + )); + assert!(matches!( + &profile.mixer_layout()[1], + MixerLayoutEntry::Fader { fader, .. } if fader == "players-fader" + )); + + draft.remove_mixer_fader("chat-fader").unwrap(); + draft.remove_mixer_fader("players-fader").unwrap(); + let profile = draft.preview().unwrap(); + assert!(profile.applications().is_empty()); + assert!(profile.groups().is_empty()); + assert_eq!(profile.faders().len(), 1); + assert_eq!(profile.faders()[0].id(), "master-fader"); +} + #[test] fn unnamed_separators_can_be_created_renamed_and_reloaded() { let mut draft = ProfileDocument::parse(PROFILE).unwrap(); diff --git a/docs/configuration.md b/docs/configuration.md index 361c381..96086f5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -184,10 +184,14 @@ Fader density is `slim`, `bordered_slim`, `standard`, or `thick`. Slim uses one terminal row; Bordered slim adds a border around one content row. Hidden faders retain their place and routing and can be restored from the Config tab. -Select a separator and press `E` to edit its name, size, and decoration in a -popup (`A` opens the same controls for a new separator). Use Up/Down or Tab to -choose a field, Left/Right to change its options, Enter to accept, and Escape -to cancel. Config → Save persists the draft. +Press `A` in the mixer to choose a new application fader, empty absolute group, +or separator. A new fader or group opens its guided editor immediately; its +placeholder capture or empty membership keeps it offline until configured. +Press `E` to edit the selected fader or separator, and `D` to delete it after +confirmation. Deleting a fader also removes its bindings and an application or +group target that is not shared or referenced elsewhere. Use Up/Down or Tab to +choose popup fields, Left/Right to change options, Enter to accept, and Escape +to cancel. Config → Save persists and activates the draft. Separator `size` is `slim`, `standard`, `thick`, or `fill`; `decoration` is `plain` (label only), `line`, `double`, or `box`. Existing separators diff --git a/fader_master/src/editor.rs b/fader_master/src/editor.rs index cfc9733..b06783b 100644 --- a/fader_master/src/editor.rs +++ b/fader_master/src/editor.rs @@ -71,6 +71,30 @@ impl ConfigurationEditor { }); } match edit { + ConfigurationEdit::AddApplicationFader { + application_id, + label, + field, + pattern, + regex, + fader_id, + position, + } => self.document.add_application_fader( + &application_id, + &label, + &selector(&field, pattern, regex)?, + &fader_id, + position, + )?, + ConfigurationEdit::AddGroupFader { + group_id, + label, + fader_id, + position, + } => self + .document + .add_group_fader(&group_id, &label, &fader_id, position)?, + ConfigurationEdit::RemoveMixerFader { id } => self.document.remove_mixer_fader(&id)?, ConfigurationEdit::AddSurface { id, label, @@ -469,6 +493,64 @@ mod tests { assert!(editor.dirty()); } + #[test] + fn mixer_object_edits_create_and_delete_complete_valid_units() { + let root = tempdir().unwrap(); + let path = root.path().join("default.toml"); + let document = ProfileDocument::empty("default").unwrap(); + fs::write(&path, document.source()).unwrap(); + let mut editor = ConfigurationEditor::new(document, path); + + let profile = editor + .apply( + 0, + ConfigurationEdit::AddApplicationFader { + application_id: "chat".into(), + label: "Chat".into(), + field: "application.name".into(), + pattern: "__fader_master_unconfigured_chat__".into(), + regex: false, + fader_id: "chat-fader".into(), + position: 1, + }, + ) + .unwrap(); + assert_eq!(profile.applications()[0].id(), "chat"); + assert_eq!(profile.faders()[1].id(), "chat-fader"); + + let profile = editor + .apply( + 1, + ConfigurationEdit::AddGroupFader { + group_id: "players".into(), + label: "Players".into(), + fader_id: "players-fader".into(), + position: 2, + }, + ) + .unwrap(); + assert_eq!(profile.groups()[0].id(), "players"); + assert_eq!(profile.faders()[2].id(), "players-fader"); + + let profile = editor + .apply( + 2, + ConfigurationEdit::RemoveMixerFader { + id: "chat-fader".into(), + }, + ) + .unwrap(); + assert!(profile.applications().is_empty()); + assert!( + profile + .faders() + .iter() + .all(|fader| fader.id() != "chat-fader") + ); + assert_eq!(editor.revision(), 3); + assert!(editor.dirty()); + } + #[test] fn accepted_edits_advance_revision_and_stale_or_invalid_edits_do_not() { let root = tempdir().unwrap(); diff --git a/fader_master/src/ipc.rs b/fader_master/src/ipc.rs index 96e8f24..dbdd8ac 100644 --- a/fader_master/src/ipc.rs +++ b/fader_master/src/ipc.rs @@ -3,7 +3,7 @@ use std::io::{self, Read, Write}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use thiserror::Error; -pub const PROTOCOL_VERSION: u16 = 20; +pub const PROTOCOL_VERSION: u16 = 21; pub const MAX_FRAME_BYTES: usize = 64 * 1024; /// Kind of mixer object addressed by a client. @@ -77,6 +77,24 @@ pub enum RequestCommand { #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(tag = "operation", rename_all = "snake_case")] pub enum ConfigurationEdit { + AddApplicationFader { + application_id: String, + label: String, + field: String, + pattern: String, + regex: bool, + fader_id: String, + position: usize, + }, + AddGroupFader { + group_id: String, + label: String, + fader_id: String, + position: usize, + }, + RemoveMixerFader { + id: String, + }, AddSurface { id: String, label: String, diff --git a/fader_master/src/tui_client.rs b/fader_master/src/tui_client.rs index 217ca70..d01eab6 100644 --- a/fader_master/src/tui_client.rs +++ b/fader_master/src/tui_client.rs @@ -347,6 +347,35 @@ impl MixerClient for IpcMixerClient { fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEdit { use crate::ipc::ConfigurationEdit as IpcEdit; match edit { + TuiConfigurationEdit::AddApplicationFader { + application_id, + label, + field, + pattern, + regex, + fader_id, + position, + } => IpcEdit::AddApplicationFader { + application_id, + label, + field, + pattern, + regex, + fader_id, + position, + }, + TuiConfigurationEdit::AddGroupFader { + group_id, + label, + fader_id, + position, + } => IpcEdit::AddGroupFader { + group_id, + label, + fader_id, + position, + }, + TuiConfigurationEdit::RemoveMixerFader { id } => IpcEdit::RemoveMixerFader { id }, TuiConfigurationEdit::AddSurface { id, label, diff --git a/task.md b/task.md index a827119..79769a2 100644 --- a/task.md +++ b/task.md @@ -443,7 +443,7 @@ Dependencies: M8, M2, M1. narrower strips for horizontal faders. Config stores a validated default controller; unassigned volume and mute learn actions inherit it while explicit bindings keep their selected surface. -- [ ] **M9.6 Single-screen configuration workflow:** remove the normalized +- [x] **M9.6 Single-screen configuration workflow:** remove the normalized Config table browser once all its operations are reachable from the mixer, keep Save and draft/durable status visible, and expose hidden-item restoration and device/backend diagnostics without a separate primary tab. @@ -464,8 +464,12 @@ Dependencies: M8, M2, M1. Master-output default. The server backs up the prior bytes as `.reset.bak`, atomically persists the replacement, and activates it without audio writes; editor, IPC/server, and confirmation/cancellation paths are regression-tested. - Keep this item open until any remaining required object-creation workflow is - available from the mixer and its small-terminal acceptance passes. + Mixer `A` now chooses a new application fader, empty absolute group, or + separator. Compound application/group creation adds the target, fader, and + visible layout entry atomically before opening its guided editor. Generic `D` + confirms removal of a fader and its unshared target or a separator. The new + chooser, name editor, and confirmation popup are covered at tiny terminal + sizes, completing the remaining object-creation acceptance. ## M10 — Transactional profile swapping diff --git a/tui/src/lib.rs b/tui/src/lib.rs index 22575f2..fc6fac7 100644 --- a/tui/src/lib.rs +++ b/tui/src/lib.rs @@ -342,6 +342,24 @@ pub struct ConfiguredBinding { #[derive(Clone, Debug, PartialEq)] pub enum ConfigurationEdit { + AddApplicationFader { + application_id: String, + label: String, + field: String, + pattern: String, + regex: bool, + fader_id: String, + position: usize, + }, + AddGroupFader { + group_id: String, + label: String, + fader_id: String, + position: usize, + }, + RemoveMixerFader { + id: String, + }, AddSurface { id: String, label: String, @@ -935,23 +953,143 @@ fn publish_confirmed(state: &mut BufferedState, confirmed: &MixerSnapshot) { } fn apply_optimistic_configuration_edit(snapshot: &mut MixerSnapshot, edit: &ConfigurationEdit) { - let ConfigurationEdit::MoveLayoutEntry { id, position } = edit else { - return; - }; - let Some(index) = snapshot - .configuration - .mixer_layout - .iter() - .position(|entry| match entry { - MixerLayoutEntry::Fader { fader, .. } => fader == id, - MixerLayoutEntry::Separator { id: separator, .. } => separator == id, - }) - else { - return; - }; - let entry = snapshot.configuration.mixer_layout.remove(index); - let position = (*position).min(snapshot.configuration.mixer_layout.len()); - snapshot.configuration.mixer_layout.insert(position, entry); + match edit { + ConfigurationEdit::MoveLayoutEntry { id, position } => { + let Some(index) = snapshot + .configuration + .mixer_layout + .iter() + .position(|entry| match entry { + MixerLayoutEntry::Fader { fader, .. } => fader == id, + MixerLayoutEntry::Separator { id: separator, .. } => separator == id, + }) + else { + return; + }; + let entry = snapshot.configuration.mixer_layout.remove(index); + let position = (*position).min(snapshot.configuration.mixer_layout.len()); + snapshot.configuration.mixer_layout.insert(position, entry); + } + ConfigurationEdit::AddApplicationFader { + application_id, + label, + field, + pattern, + regex, + fader_id, + position, + } => { + snapshot + .configuration + .applications + .push(ConfiguredApplication { + id: application_id.clone(), + label: label.clone(), + selectors: vec![ConfiguredSelector { + field: field.clone(), + pattern: pattern.clone(), + regex: *regex, + }], + }); + snapshot.configuration.faders.push(ConfiguredFader { + id: fader_id.clone(), + target: MixerObjectId { + kind: MixerObjectKind::Application, + id: application_id.clone(), + }, + pickup: true, + pickup_tolerance: 0.02, + }); + snapshot.configuration.mixer_layout.insert( + (*position).min(snapshot.configuration.mixer_layout.len()), + MixerLayoutEntry::Fader { + fader: fader_id.clone(), + hidden: false, + density: FaderDensity::Standard, + }, + ); + snapshot.configuration.dirty = true; + } + ConfigurationEdit::AddGroupFader { + group_id, + label, + fader_id, + position, + } => { + snapshot.configuration.groups.push(ConfiguredGroup { + id: group_id.clone(), + label: label.clone(), + members: Vec::new(), + volume_mode: GroupVolumeMode::Absolute, + }); + snapshot.configuration.faders.push(ConfiguredFader { + id: fader_id.clone(), + target: MixerObjectId { + kind: MixerObjectKind::Group, + id: group_id.clone(), + }, + pickup: true, + pickup_tolerance: 0.02, + }); + snapshot.configuration.mixer_layout.insert( + (*position).min(snapshot.configuration.mixer_layout.len()), + MixerLayoutEntry::Fader { + fader: fader_id.clone(), + hidden: false, + density: FaderDensity::Standard, + }, + ); + snapshot.configuration.dirty = true; + } + ConfigurationEdit::RemoveMixerFader { id } => { + let target = snapshot + .configuration + .faders + .iter() + .find(|fader| fader.id == *id) + .map(|fader| fader.target.clone()); + snapshot + .configuration + .faders + .retain(|fader| fader.id != *id); + snapshot.configuration.mixer_layout.retain( + |entry| !matches!(entry, MixerLayoutEntry::Fader { fader, .. } if fader == id), + ); + snapshot + .configuration + .bindings + .retain(|binding| binding.fader != *id); + if let Some(target) = target + && !snapshot + .configuration + .faders + .iter() + .any(|fader| fader.target == target) + { + match target.kind { + MixerObjectKind::Application + if !snapshot + .configuration + .groups + .iter() + .any(|group| group.members.contains(&target.id)) => + { + snapshot + .configuration + .applications + .retain(|application| application.id != target.id); + } + MixerObjectKind::Group => snapshot + .configuration + .groups + .retain(|group| group.id != target.id), + _ => {} + } + } + snapshot.configuration.dirty = true; + } + _ => {} + } } fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) { @@ -1030,6 +1168,9 @@ pub struct LiveTui { exit: bool, quit_confirmation: bool, reset_confirmation: bool, + add_picker: Option, + new_item_editor: Option, + delete_confirmation: Option, show_help: bool, client_error: Option, tab: Tab, @@ -1130,6 +1271,43 @@ struct ProfilePicker { selected: usize, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum AddKind { + Fader, + Group, + Separator, +} + +impl AddKind { + const ALL: [Self; 3] = [Self::Fader, Self::Group, Self::Separator]; + + const fn label(self) -> &'static str { + match self { + Self::Fader => "Fader", + Self::Group => "Group", + Self::Separator => "Separator", + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct AddPicker { + selected: usize, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct NewItemEditor { + kind: AddKind, + label: String, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct DeleteConfirmation { + id: String, + label: String, + separator: bool, +} + enum FaderEditorRow { Capture { application: String, @@ -1340,6 +1518,9 @@ impl LiveTui { exit: false, quit_confirmation: false, reset_confirmation: false, + add_picker: None, + new_item_editor: None, + delete_confirmation: None, show_help: false, client_error: None, tab: Tab::Mixer, @@ -1467,6 +1648,18 @@ impl LiveTui { } fn handle_key_event(&mut self, key_event: KeyEvent) { + if self.delete_confirmation.is_some() { + self.handle_delete_confirmation_key(key_event.code); + return; + } + if self.new_item_editor.is_some() { + self.handle_new_item_editor_key(key_event.code); + return; + } + if self.add_picker.is_some() { + self.handle_add_picker_key(key_event.code); + return; + } if self.reset_confirmation { match key_event.code { KeyCode::Char('y' | 'Y') => { @@ -1629,9 +1822,12 @@ impl LiveTui { KeyCode::End => self.set_selected_volume(1.0), KeyCode::Char('m') => self.toggle_selected_mute(), KeyCode::Char('H') => self.toggle_selected_visibility(), - KeyCode::Char('a') => self.start_separator_editor(), + KeyCode::Char('a') => { + self.add_picker = Some(AddPicker { selected: 0 }); + self.client_error = None; + } KeyCode::Char('e') => self.edit_selected_entry(), - KeyCode::Char('d') => self.remove_selected_separator(), + KeyCode::Char('d') => self.start_delete_selected_entry(), _ => {} } } @@ -1653,6 +1849,158 @@ impl LiveTui { self.client_error = None; } + fn handle_add_picker_key(&mut self, code: KeyCode) { + let Some(picker) = &mut self.add_picker else { + return; + }; + match code { + KeyCode::Esc => self.add_picker = None, + KeyCode::Up | KeyCode::Char('k') => { + picker.selected = picker.selected.saturating_sub(1); + } + KeyCode::Down | KeyCode::Char('j') => { + picker.selected = (picker.selected + 1).min(AddKind::ALL.len() - 1); + } + KeyCode::Enter => { + let kind = AddKind::ALL[picker.selected]; + self.add_picker = None; + if kind == AddKind::Separator { + self.start_separator_editor(); + } else { + self.new_item_editor = Some(NewItemEditor { + kind, + label: String::new(), + }); + } + } + _ => {} + } + } + + fn handle_new_item_editor_key(&mut self, code: KeyCode) { + match code { + KeyCode::Esc => self.new_item_editor = None, + KeyCode::Backspace => { + if let Some(editor) = &mut self.new_item_editor { + editor.label.pop(); + } + } + KeyCode::Enter => self.submit_new_item(), + KeyCode::Char(character) => { + if let Some(editor) = &mut self.new_item_editor { + editor.label.push(character); + } + } + _ => {} + } + } + + fn submit_new_item(&mut self) { + let Some(editor) = &self.new_item_editor else { + return; + }; + let label = editor.label.trim(); + if label.is_empty() { + self.client_error = Some("a fader or group name is required".to_owned()); + return; + } + let kind = editor.kind; + let base = mixer_object_id(label); + let position = self.layout_position_after_selected(); + let fader_id = unique_configured_id( + &format!("{base}-fader"), + self.snapshot + .configuration + .faders + .iter() + .map(|fader| fader.id.as_str()), + ); + let (edit, target_id) = match kind { + AddKind::Fader => { + let application_id = unique_configured_id( + &base, + self.snapshot + .configuration + .applications + .iter() + .map(|application| application.id.as_str()), + ); + let pattern = format!("__fader_master_unconfigured_{application_id}__"); + ( + ConfigurationEdit::AddApplicationFader { + application_id: application_id.clone(), + label: label.to_owned(), + field: "application.name".to_owned(), + pattern, + regex: false, + fader_id: fader_id.clone(), + position, + }, + application_id, + ) + } + AddKind::Group => { + let group_id = unique_configured_id( + &base, + self.snapshot + .configuration + .groups + .iter() + .map(|group| group.id.as_str()), + ); + ( + ConfigurationEdit::AddGroupFader { + group_id: group_id.clone(), + label: label.to_owned(), + fader_id: fader_id.clone(), + position, + }, + group_id, + ) + } + AddKind::Separator => return, + }; + match self + .client + .edit_configuration(edit, self.snapshot.configuration.revision) + { + Ok(snapshot) => { + self.new_item_editor = None; + self.replace_snapshot(snapshot); + self.selected = self + .mixer_rows() + .iter() + .position(|row| row.id() == fader_id) + .unwrap_or(self.selected); + self.fader_editor = Some(FaderEditor { + fader: fader_id, + selected: 0, + }); + self.client_error = None; + } + Err(error) => { + self.client_error = Some(format!("could not add {target_id:?}: {error}")); + } + } + } + + fn layout_position_after_selected(&self) -> usize { + let Some(id) = self.selected_layout_id() else { + return self.snapshot.configuration.mixer_layout.len(); + }; + self.snapshot + .configuration + .mixer_layout + .iter() + .position(|entry| match entry { + MixerLayoutEntry::Fader { fader, .. } => fader == &id, + MixerLayoutEntry::Separator { id: separator, .. } => separator == &id, + }) + .map_or(self.snapshot.configuration.mixer_layout.len(), |index| { + index + 1 + }) + } + fn edit_selected_entry(&mut self) { enum Selected { Fader(String), @@ -2642,16 +2990,55 @@ impl LiveTui { self.apply_layout_edit(ConfigurationEdit::SetFaderHidden { id, hidden: true }); } - fn remove_selected_separator(&mut self) { - let selected = self + fn start_delete_selected_entry(&mut self) { + let confirmation = self .mixer_rows() .get(self.selected) .and_then(|row| match row { - MixerRow::Separator { id, .. } => Some((*id).to_owned()), - _ => None, + MixerRow::Fader { + layout_id: Some(id), + item, + .. + } => Some(DeleteConfirmation { + id: (*id).to_owned(), + label: item.label.clone(), + separator: false, + }), + MixerRow::Separator { id, label, .. } => Some(DeleteConfirmation { + id: (*id).to_owned(), + label: (*label).to_owned(), + separator: true, + }), + MixerRow::Fader { + layout_id: None, .. + } => None, }); - let Some(id) = selected else { return }; - self.apply_layout_edit(ConfigurationEdit::RemoveSeparator { id }); + if confirmation.is_some() { + self.delete_confirmation = confirmation; + self.client_error = None; + } + } + + fn handle_delete_confirmation_key(&mut self, code: KeyCode) { + match code { + KeyCode::Char('y' | 'Y') => { + let Some(confirmation) = self.delete_confirmation.take() else { + return; + }; + let edit = if confirmation.separator { + ConfigurationEdit::RemoveSeparator { + id: confirmation.id, + } + } else { + ConfigurationEdit::RemoveMixerFader { + id: confirmation.id, + } + }; + self.apply_layout_edit(edit); + } + KeyCode::Char('n' | 'N') | KeyCode::Esc => self.delete_confirmation = None, + _ => {} + } } fn apply_layout_edit(&mut self, edit: ConfigurationEdit) { @@ -2865,6 +3252,83 @@ impl Widget for &LiveTui { if self.show_help { self.render_help(area, buf); } + if let Some(picker) = &self.add_picker { + let popup = centered_rect(area, 42, 7); + Clear.render(popup, buf); + let lines = AddKind::ALL + .iter() + .enumerate() + .map(|(index, kind)| { + let marker = if index == picker.selected { "▶" } else { " " }; + Line::from(format!("{marker} {}", kind.label())).style( + if index == picker.selected { + Style::default().fg(theme.accent).bold() + } else { + Style::default().fg(theme.foreground) + }, + ) + }) + .collect::>(); + Paragraph::new(Text::from(lines)) + .block( + Block::bordered() + .title(" Add to mixer ".fg(theme.accent).bold()) + .title_bottom(" ↑↓ select · Enter choose · Esc cancel ".fg(theme.muted)) + .border_set(border::DOUBLE) + .border_style(Style::default().fg(theme.accent)) + .style(Style::default().bg(theme.background)), + ) + .render(popup, buf); + } + if let Some(editor) = &self.new_item_editor { + let popup = centered_rect(area, 58, 6); + Clear.render(popup, buf); + Paragraph::new(Text::from(vec![ + Line::from(format!("New {} name", editor.kind.label())).fg(theme.secondary), + Line::from(if editor.label.is_empty() { + " ".to_owned() + } else { + editor.label.clone() + }) + .bold(), + ])) + .block( + Block::bordered() + .title( + format!(" Add {} ", editor.kind.label()) + .fg(theme.accent) + .bold(), + ) + .title_bottom(" Enter create · Esc cancel ".fg(theme.muted)) + .border_set(border::DOUBLE) + .border_style(Style::default().fg(theme.accent)) + .style(Style::default().bg(theme.background)), + ) + .render(popup, buf); + } + if let Some(confirmation) = &self.delete_confirmation { + let popup = centered_rect(area, 58, 7); + Clear.render(popup, buf); + let kind = if confirmation.separator { + "separator" + } else { + "fader and its owned target" + }; + Paragraph::new(Text::from(vec![ + Line::from(format!("Delete {kind}? ")).bold(), + Line::from(format!("“{}”", confirmation.label)).fg(theme.secondary), + Line::from("Y delete N / Esc cancel"), + ])) + .alignment(Alignment::Center) + .block( + Block::bordered() + .title(" Confirm delete ".fg(theme.error).bold()) + .border_set(border::DOUBLE) + .border_style(Style::default().fg(theme.error)) + .style(Style::default().bg(theme.background)), + ) + .render(popup, buf); + } if self.quit_confirmation { let width = area.width.min(46); let height = area.height.min(5); @@ -3048,6 +3512,40 @@ fn unique_separator_id(label: &str, layout: &[MixerLayoutEntry]) -> String { .unwrap_or_else(|| "separator-id-exhausted".to_owned()) } +fn mixer_object_id(label: &str) -> String { + let id = label + .chars() + .filter_map(|character| { + if character.is_ascii_alphanumeric() { + Some(character.to_ascii_lowercase()) + } else if character.is_ascii_whitespace() || matches!(character, '-' | '_') { + Some('-') + } else { + None + } + }) + .take(48) + .collect::() + .trim_matches('-') + .to_owned(); + if id.is_empty() { + "fader".to_owned() + } else { + id + } +} + +fn unique_configured_id<'a>(base: &str, used: impl Iterator) -> String { + let used = used.collect::>(); + if !used.contains(base) { + return base.to_owned(); + } + (2..) + .map(|suffix| format!("{base}-{suffix}")) + .find(|candidate| !used.contains(candidate.as_str())) + .unwrap_or_else(|| "configured-id-exhausted".to_owned()) +} + fn unique_surface_id(name: &str, devices: &[MidiDevice]) -> String { let base = name .chars() @@ -3662,9 +4160,9 @@ impl LiveTui { Line::from(" J/K Select next/previous in either orientation"), Line::from(" M Toggle mute"), Line::from(" Shift+H Hide the selected fader"), - Line::from(" E Edit the selected fader or separator"), - Line::from(" A Add a separator after the selection"), - Line::from(" D Remove the selected separator"), + Line::from(" A Add a fader, group, or separator"), + Line::from(" E Edit the selected entry"), + Line::from(" D Delete the selected entry"), Line::from(""), Line::from("Configuration").fg(theme.accent).bold(), Line::from(" Up/Down or J/K Select a setting or MIDI device"), @@ -4359,6 +4857,11 @@ mod tests { _expected_revision: u64, ) -> io::Result { match &edit { + ConfigurationEdit::AddApplicationFader { .. } + | ConfigurationEdit::AddGroupFader { .. } + | ConfigurationEdit::RemoveMixerFader { .. } => { + apply_optimistic_configuration_edit(&mut self.snapshot, &edit); + } ConfigurationEdit::MoveLayoutEntry { id, position } => { let index = self .snapshot @@ -4754,7 +5257,9 @@ mod tests { .collect::(); assert!(rendered.contains("Keyboard help")); assert!(rendered.contains("Shift+H")); - assert!(rendered.contains("Add a separator")); + assert!(rendered.contains("Add a fader, group, or separator")); + assert!(rendered.contains("Edit the selected entry")); + assert!(rendered.contains("Delete the selected entry")); assert!(rendered.contains("Save the configuration")); assert!(rendered.contains("Home/End")); @@ -4796,6 +5301,160 @@ mod tests { assert!(!rendered.contains("move")); } + #[test] + fn add_chooses_fader_group_or_separator_and_opens_the_relevant_editor() { + let edits = Arc::new(Mutex::new(Vec::new())); + let mut app = LiveTui::new(LayoutClient { + snapshot: DemoClient::default().view(), + edits: Arc::clone(&edits), + }) + .unwrap(); + + app.handle_key_event(press(KeyCode::Char('a'))); + let area = Rect::new(0, 0, 90, 22); + let mut buffer = Buffer::empty(area); + (&app).render(area, &mut buffer); + let rendered = buffer + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(rendered.contains("Add to mixer")); + assert!(rendered.contains("Fader")); + assert!(rendered.contains("Group")); + assert!(rendered.contains("Separator")); + + app.handle_key_event(press(KeyCode::Enter)); + for character in "Chat".chars() { + app.handle_key_event(press(KeyCode::Char(character))); + } + app.handle_key_event(press(KeyCode::Enter)); + assert!(app.fader_editor.is_some()); + app.handle_key_event(press(KeyCode::Esc)); + + app.handle_key_event(press(KeyCode::Char('a'))); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Enter)); + for character in "Players".chars() { + app.handle_key_event(press(KeyCode::Char(character))); + } + app.handle_key_event(press(KeyCode::Enter)); + assert!(app.fader_editor.is_some()); + app.handle_key_event(press(KeyCode::Esc)); + + app.handle_key_event(press(KeyCode::Char('a'))); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Enter)); + for character in "Inputs".chars() { + app.handle_key_event(press(KeyCode::Char(character))); + } + app.handle_key_event(press(KeyCode::Enter)); + + let edits = edits.lock().unwrap(); + assert!(matches!( + &edits[0], + ConfigurationEdit::AddApplicationFader { + application_id, + label, + fader_id, + .. + } if application_id == "chat" && label == "Chat" && fader_id == "chat-fader" + )); + assert!(matches!( + &edits[1], + ConfigurationEdit::AddGroupFader { + group_id, + label, + fader_id, + .. + } if group_id == "players" && label == "Players" && fader_id == "players-fader" + )); + assert!(matches!( + &edits[2], + ConfigurationEdit::AddSeparator { label, .. } if label == "Inputs" + )); + } + + #[test] + fn delete_is_generic_and_requires_confirmation() { + let edits = Arc::new(Mutex::new(Vec::new())); + let mut snapshot = DemoClient::default().view(); + snapshot.configuration.applications = vec![ConfiguredApplication { + id: "desktop".into(), + label: "Desktop audio".into(), + selectors: vec![ConfiguredSelector { + field: "application.name".into(), + pattern: "Desktop audio".into(), + regex: false, + }], + }]; + snapshot.configuration.faders = vec![ConfiguredFader { + id: "desktop-fader".into(), + target: snapshot.items[0].id.clone(), + pickup: true, + pickup_tolerance: 0.02, + }]; + snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader { + fader: "desktop-fader".into(), + hidden: false, + density: FaderDensity::Standard, + }]; + let mut app = LiveTui::new(LayoutClient { + snapshot, + edits: Arc::clone(&edits), + }) + .unwrap(); + + app.handle_key_event(press(KeyCode::Char('d'))); + assert!(app.delete_confirmation.is_some()); + app.handle_key_event(press(KeyCode::Esc)); + assert!(edits.lock().unwrap().is_empty()); + + app.handle_key_event(press(KeyCode::Char('d'))); + app.handle_key_event(press(KeyCode::Char('y'))); + assert!(matches!( + edits.lock().unwrap().as_slice(), + [ConfigurationEdit::RemoveMixerFader { id }] if id == "desktop-fader" + )); + assert!(app.snapshot.configuration.faders.is_empty()); + assert!(app.snapshot.configuration.applications.is_empty()); + } + + #[test] + fn add_and_delete_popups_render_at_tiny_terminal_sizes() { + let edits = Arc::new(Mutex::new(Vec::new())); + let mut snapshot = DemoClient::default().view(); + snapshot.configuration.faders = vec![ConfiguredFader { + id: "master-fader".into(), + target: snapshot.items[0].id.clone(), + pickup: true, + pickup_tolerance: 0.02, + }]; + snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader { + fader: "master-fader".into(), + hidden: false, + density: FaderDensity::Standard, + }]; + let mut app = LiveTui::new(LayoutClient { snapshot, edits }).unwrap(); + + for (width, height) in [(1, 1), (8, 3), (24, 7)] { + app.handle_key_event(press(KeyCode::Char('a'))); + let area = Rect::new(0, 0, width, height); + let mut buffer = Buffer::empty(area); + (&app).render(area, &mut buffer); + app.handle_key_event(press(KeyCode::Enter)); + let mut buffer = Buffer::empty(area); + (&app).render(area, &mut buffer); + app.handle_key_event(press(KeyCode::Esc)); + + app.handle_key_event(press(KeyCode::Char('d'))); + let mut buffer = Buffer::empty(area); + (&app).render(area, &mut buffer); + app.handle_key_event(press(KeyCode::Esc)); + } + } + #[test] fn unnamed_separators_are_accepted_with_unique_ids() { let edits = Arc::new(Mutex::new(Vec::new())); @@ -4806,6 +5465,9 @@ mod tests { .unwrap(); for _ in 0..2 { app.handle_key_event(press(KeyCode::Char('a'))); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Enter)); app.handle_key_event(press(KeyCode::Enter)); assert!(app.editor.is_none(), "blank name must be accepted"); } @@ -4965,6 +5627,9 @@ mod tests { fn separator_name_is_edited_in_a_centered_popup() { let mut app = LiveTui::new(DemoClient::default()).unwrap(); app.handle_key_event(press(KeyCode::Char('a'))); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Enter)); for character in "Music".chars() { app.handle_key_event(press(KeyCode::Char(character))); } @@ -5270,6 +5935,9 @@ mod tests { app.handle_key_event(press(KeyCode::Esc)); app.handle_key_event(press(KeyCode::Tab)); app.handle_key_event(press(KeyCode::Char('a'))); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Enter)); for character in "Outputs".chars() { app.handle_key_event(press(KeyCode::Char(character))); }