diff --git a/fader_master/src/tui_client.rs b/fader_master/src/tui_client.rs index 17c161d..c1ea58d 100644 --- a/fader_master/src/tui_client.rs +++ b/fader_master/src/tui_client.rs @@ -1,8 +1,8 @@ use std::{io, path::PathBuf}; use tui::{ - MixerClient, MixerItem, MixerObjectId, MixerObjectKind, MixerSnapshot, - PickupStatus as TuiPickupStatus, + ConfigurationEdit as TuiConfigurationEdit, MixerClient, MixerItem, MixerObjectId, + MixerObjectKind, MixerSnapshot, PickupStatus as TuiPickupStatus, }; use crate::{ @@ -143,7 +143,9 @@ impl IpcMixerClient { }, }), ResponseResult::Error { message, .. } => { - let kind = if message.contains("stale revision") { + let kind = if message.contains("stale revision") + || message.contains("stale configuration revision") + { io::ErrorKind::InvalidData } else { io::ErrorKind::Other @@ -182,6 +184,91 @@ impl MixerClient for IpcMixerClient { expected_revision, }) } + + fn edit_configuration( + &mut self, + edit: TuiConfigurationEdit, + expected_revision: u64, + ) -> io::Result { + self.send(RequestCommand::EditConfiguration { + expected_revision, + edit: configuration_edit(edit), + }) + } +} + +fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEdit { + use crate::ipc::ConfigurationEdit as IpcEdit; + match edit { + TuiConfigurationEdit::Application { + existing, + id, + label, + field, + pattern, + regex, + } => { + if existing { + IpcEdit::SetApplication { + id, + label, + field, + pattern, + regex, + } + } else { + IpcEdit::AddApplication { + id, + label, + field, + pattern, + regex, + } + } + } + TuiConfigurationEdit::Group { + existing, + id, + label, + members, + } => { + if existing { + IpcEdit::SetGroup { id, label, members } + } else { + IpcEdit::AddGroup { id, label, members } + } + } + TuiConfigurationEdit::Fader { + existing, + id, + target, + pickup, + pickup_tolerance, + } => { + let target = key(target); + if existing { + IpcEdit::SetFader { + id, + target, + pickup, + pickup_tolerance, + } + } else { + IpcEdit::AddFader { + id, + target, + pickup, + pickup_tolerance, + } + } + } + TuiConfigurationEdit::Remove { kind, id } => match kind.as_str() { + "application" => IpcEdit::RemoveApplication { id }, + "group" => IpcEdit::RemoveGroup { id }, + "fader" => IpcEdit::RemoveFader { id }, + _ => IpcEdit::RemoveApplication { id }, + }, + } } fn key(id: MixerObjectId) -> MixerObjectKey { diff --git a/task.md b/task.md index b5167ff..165e63f 100644 --- a/task.md +++ b/task.md @@ -332,12 +332,14 @@ regression-tested profile fix then matched it into the two-stream media group. Dependencies: M8, M2, M1. -- [ ] **M9.1 Editor drafts:** separate tab to create/edit/delete applications, groups and faders; target/member selection, matcher preview, validation errors and referenced-delete handling. Tests: invalid regex/dangling member rejected; Cancel has no side effects; creating a group/fader produces the expected semantic TOML. +- [x] **M9.1 Editor drafts:** separate tab to create/edit/delete applications, groups and faders; target/member selection, matcher preview, validation errors and referenced-delete handling. Tests: invalid regex/dangling member rejected; Cancel has no side effects; creating a group/fader produces the expected semantic TOML. Transactional, comment-preserving draft primitives now create applications, absolute groups and faders, and roll back invalid regexes or referenced deletes. A separate Config tab now shows the server-owned applications, group membership, logical fader targets, pickup policy, and MIDI assignments. The - selection controls, matcher preview, and full edit/delete surface remain. + keyboard editor accepts explicit target/member IDs, previews live matcher + results, and provides the full create/update/delete surface with inline + validation errors and cancellation. The server now owns the validated draft and its independent revision; stale or invalid edit requests are rejected without advancing or altering it, and accepted edits are exposed as an unsaved draft in the Config tab. diff --git a/tui/src/lib.rs b/tui/src/lib.rs index 4ba79b5..8dc2942 100644 --- a/tui/src/lib.rs +++ b/tui/src/lib.rs @@ -113,6 +113,35 @@ pub struct ConfiguredBinding { pub message: String, } +#[derive(Clone, Debug, PartialEq)] +pub enum ConfigurationEdit { + Application { + existing: bool, + id: String, + label: String, + field: String, + pattern: String, + regex: bool, + }, + Group { + existing: bool, + id: String, + label: String, + members: Vec, + }, + Fader { + existing: bool, + id: String, + target: MixerObjectId, + pickup: bool, + pickup_tolerance: f64, + }, + Remove { + kind: String, + id: String, + }, +} + #[derive(Clone, Debug, PartialEq)] pub struct MixerSnapshot { pub revision: u64, @@ -139,6 +168,16 @@ pub trait MixerClient { id: MixerObjectId, expected_revision: u64, ) -> io::Result; + fn edit_configuration( + &mut self, + _edit: ConfigurationEdit, + _expected_revision: u64, + ) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "configuration editing is unavailable", + )) + } } #[derive(Clone, Debug)] @@ -146,6 +185,7 @@ enum BufferedAction { SetVolume { id: MixerObjectId, gain: f64 }, ToggleMute { id: MixerObjectId }, Refresh, + EditConfiguration { edit: ConfigurationEdit }, } #[derive(Debug)] @@ -155,6 +195,7 @@ struct BufferedState { desired_mutes: BTreeMap, volume_work: BTreeMap, mute_work: VecDeque, + configuration_work: VecDeque, error: Option, shutdown: bool, } @@ -186,6 +227,7 @@ impl BufferedMixerClient { desired_mutes: BTreeMap::new(), volume_work: BTreeMap::new(), mute_work: VecDeque::new(), + configuration_work: VecDeque::new(), error: None, shutdown: false, }), @@ -277,6 +319,25 @@ impl MixerClient for BufferedMixerClient { wake.notify_one(); Ok(snapshot) } + + fn edit_configuration( + &mut self, + edit: ConfigurationEdit, + _expected_revision: u64, + ) -> io::Result { + let (state, wake) = &*self.shared; + let mut state = state + .lock() + .map_err(|_| io::Error::other("buffered mixer client state is poisoned"))?; + if state.configuration_work.len() >= 64 { + return Err(io::Error::other("configuration edit buffer is full")); + } + state.configuration_work.push_back(edit); + state.error = None; + let snapshot = state.snapshot.clone(); + wake.notify_one(); + Ok(snapshot) + } } impl Drop for BufferedMixerClient { @@ -310,6 +371,7 @@ fn client_loop( && !state.shutdown && state.mute_work.is_empty() && state.volume_work.is_empty() + && state.configuration_work.is_empty() { let refresh = if state.desired_volumes.is_empty() && state.desired_mutes.is_empty() { @@ -332,6 +394,8 @@ fn client_loop( BufferedAction::ToggleMute { id } } else if let Some((id, gain)) = state.volume_work.pop_first() { BufferedAction::SetVolume { id, gain } + } else if let Some(edit) = state.configuration_work.pop_front() { + BufferedAction::EditConfiguration { edit } } else { BufferedAction::Refresh } @@ -362,22 +426,27 @@ fn execute_action( confirmed: &mut MixerSnapshot, action: &BufferedAction, ) -> io::Result { - let execute = |client: &mut C, revision| match action { + let execute = |client: &mut C, revision, configuration_revision| match action { BufferedAction::SetVolume { id, gain } => client.set_volume(id.clone(), *gain, revision), BufferedAction::ToggleMute { id } => client.toggle_mute(id.clone(), revision), BufferedAction::Refresh => client.snapshot(), + BufferedAction::EditConfiguration { edit } => { + client.edit_configuration(edit.clone(), configuration_revision) + } }; - match execute(client, confirmed.revision) { + match execute(client, confirmed.revision, confirmed.configuration.revision) { Ok(snapshot) => Ok(snapshot), Err(first) if matches!(action, BufferedAction::SetVolume { .. }) + || (matches!(action, BufferedAction::EditConfiguration { .. }) + && first.kind() == io::ErrorKind::InvalidData) || (matches!(action, BufferedAction::ToggleMute { .. }) && first.kind() == io::ErrorKind::InvalidData) => { *confirmed = client.snapshot()?; - execute(client, confirmed.revision).map_err(|second| { - io::Error::other(format!("{first}; retry after resync failed: {second}")) - }) + execute(client, confirmed.revision, confirmed.configuration.revision).map_err( + |second| io::Error::other(format!("{first}; retry after resync failed: {second}")), + ) } Err(error) => Err(error), } @@ -430,6 +499,7 @@ fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) { } } BufferedAction::Refresh => {} + BufferedAction::EditConfiguration { .. } => {} } } @@ -481,6 +551,7 @@ pub struct LiveTui { exit: bool, client_error: Option, tab: Tab, + editor: Option, } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] @@ -490,6 +561,20 @@ enum Tab { Configuration, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum EditorOperation { + Application, + Group, + Fader, + Remove, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct EditorInput { + operation: EditorOperation, + value: String, +} + impl LiveTui { pub fn new(client: C) -> io::Result { Self::with_theme(client, ThemeName::Default) @@ -505,6 +590,7 @@ impl LiveTui { exit: false, client_error: None, tab: Tab::Mixer, + editor: None, }) } @@ -555,6 +641,10 @@ impl LiveTui { } fn handle_key_event(&mut self, key_event: KeyEvent) { + if self.editor.is_some() { + self.handle_editor_key(key_event.code); + return; + } match key_event.code { KeyCode::Char('j') | KeyCode::Down => { self.selected = @@ -579,11 +669,148 @@ impl LiveTui { } KeyCode::Char('1') => self.tab = Tab::Mixer, KeyCode::Char('2') => self.tab = Tab::Configuration, + KeyCode::Char('a') if self.tab == Tab::Configuration => { + self.start_editor(EditorOperation::Application) + } + KeyCode::Char('g') if self.tab == Tab::Configuration => { + self.start_editor(EditorOperation::Group) + } + KeyCode::Char('f') if self.tab == Tab::Configuration => { + self.start_editor(EditorOperation::Fader) + } + KeyCode::Char('d') if self.tab == Tab::Configuration => { + self.start_editor(EditorOperation::Remove) + } KeyCode::Esc | KeyCode::Char('q') => self.exit = true, _ => {} } } + fn start_editor(&mut self, operation: EditorOperation) { + self.editor = Some(EditorInput { + operation, + value: String::new(), + }); + self.client_error = None; + } + + fn handle_editor_key(&mut self, code: KeyCode) { + match code { + KeyCode::Esc => self.editor = None, + KeyCode::Backspace => { + if let Some(editor) = &mut self.editor { + editor.value.pop(); + } + } + KeyCode::Enter => self.submit_editor(), + KeyCode::Char(character) => { + if let Some(editor) = &mut self.editor { + editor.value.push(character); + } + } + _ => {} + } + } + + fn submit_editor(&mut self) { + let Some(editor) = self.editor.take() else { + return; + }; + let edit = match self.parse_editor(&editor) { + Ok(edit) => edit, + Err(error) => { + self.client_error = Some(error); + return; + } + }; + match self + .client + .edit_configuration(edit, self.snapshot.configuration.revision) + { + Ok(snapshot) => self.replace_snapshot(snapshot), + Err(error) => self.client_error = Some(error.to_string()), + } + } + + fn parse_editor(&self, editor: &EditorInput) -> Result { + let fields = editor.value.split('|').map(str::trim).collect::>(); + match editor.operation { + EditorOperation::Application if fields.len() == 5 => { + Ok(ConfigurationEdit::Application { + existing: self + .snapshot + .configuration + .applications + .iter() + .any(|item| item.id == fields[0]), + id: fields[0].to_owned(), + label: fields[1].to_owned(), + field: fields[2].to_owned(), + regex: match fields[3] { + "exact" => false, + "regex" => true, + _ => return Err("matcher mode must be exact or regex".to_owned()), + }, + pattern: fields[4].to_owned(), + }) + } + EditorOperation::Group if fields.len() == 3 => Ok(ConfigurationEdit::Group { + existing: self + .snapshot + .configuration + .groups + .iter() + .any(|item| item.id == fields[0]), + id: fields[0].to_owned(), + label: fields[1].to_owned(), + members: fields[2] + .split(',') + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_owned) + .collect(), + }), + EditorOperation::Fader if fields.len() == 4 => Ok(ConfigurationEdit::Fader { + existing: self + .snapshot + .configuration + .faders + .iter() + .any(|item| item.id == fields[0]), + id: fields[0].to_owned(), + target: MixerObjectId { + kind: parse_kind(fields[1])?, + id: fields[2].to_owned(), + }, + pickup: match fields[3] { + "yes" | "true" => true, + "no" | "false" => false, + _ => return Err("pickup must be yes/no or true/false".to_owned()), + }, + pickup_tolerance: 0.02, + }), + EditorOperation::Remove + if fields.len() == 2 && matches!(fields[0], "application" | "group" | "fader") => + { + Ok(ConfigurationEdit::Remove { + kind: fields[0].to_owned(), + id: fields[1].to_owned(), + }) + } + EditorOperation::Remove if fields.len() == 2 => { + Err("delete kind must be application, group, or fader".to_owned()) + } + EditorOperation::Application => { + Err("expected id|label|field|exact/regex|pattern".to_owned()) + } + EditorOperation::Group => Err("expected id|label|member1,member2".to_owned()), + EditorOperation::Fader => { + Err("expected id|application/group/output|target|pickup".to_owned()) + } + EditorOperation::Remove => Err("expected application/group/fader|id".to_owned()), + } + } + fn change_volume(&mut self, delta: f64) { if let Some(item) = self.snapshot.items.get(self.selected) { if let Some(gain) = item.gain { @@ -666,16 +893,22 @@ impl Widget for &LiveTui { ) .render(header, buf); - let status_error = self.client_error.is_some() - || self - .snapshot - .devices - .iter() - .any(|device| device.error.is_some() || device.status == "error"); - let status = self.client_error.clone().unwrap_or_else(|| { - device_summary(&self.snapshot.devices) - .unwrap_or_else(|| "confirmed server state".to_owned()) - }); + let status_error = self.editor.is_none() + && (self.client_error.is_some() + || self + .snapshot + .devices + .iter() + .any(|device| device.error.is_some() || device.status == "error")); + let status = self.editor.as_ref().map_or_else( + || { + self.client_error.clone().unwrap_or_else(|| { + device_summary(&self.snapshot.devices) + .unwrap_or_else(|| "confirmed server state".to_owned()) + }) + }, + |editor| format!("{}: {}", editor_prompt(editor.operation), editor.value), + ); let mixer = Block::bordered() .title( match self.tab { @@ -699,29 +932,48 @@ impl Widget for &LiveTui { Tab::Configuration => self.render_configuration(inner, buf), } - Paragraph::new(Line::from(vec![ - " ↑/↓ or j/k ".fg(theme.foreground), - "select".fg(theme.secondary), - " ←/→ ".fg(theme.foreground), - "volume".fg(theme.secondary), - " M ".fg(theme.foreground), - "mute".fg(theme.secondary), - " Home/End ".fg(theme.foreground), - "0/100%".fg(theme.secondary), - " T ".fg(theme.foreground), - "theme".fg(theme.secondary), - " Tab/1/2 ".fg(theme.foreground), - "view".fg(theme.secondary), - " Q/Esc ".fg(theme.foreground), - "quit".fg(theme.secondary), - ])) - .alignment(Alignment::Center) - .block( - Block::bordered() - .border_set(border::ROUNDED) - .border_style(Style::default().fg(theme.muted)), - ) - .render(footer, buf); + let footer_line = match self.tab { + Tab::Mixer => Line::from(vec![ + " ↑↓/jk ".fg(theme.foreground), + "select".fg(theme.secondary), + " ←→ ".fg(theme.foreground), + "volume".fg(theme.secondary), + " M ".fg(theme.foreground), + "mute".fg(theme.secondary), + " Home/End ".fg(theme.foreground), + "0/100%".fg(theme.secondary), + " T ".fg(theme.foreground), + "theme".fg(theme.secondary), + " Tab ".fg(theme.foreground), + "config".fg(theme.secondary), + " Q/Esc ".fg(theme.foreground), + "quit".fg(theme.secondary), + ]), + Tab::Configuration => Line::from(vec![ + " A ".fg(theme.foreground), + "app".fg(theme.secondary), + " G ".fg(theme.foreground), + "group".fg(theme.secondary), + " F ".fg(theme.foreground), + "fader".fg(theme.secondary), + " D ".fg(theme.foreground), + "delete".fg(theme.secondary), + " Tab ".fg(theme.foreground), + "mixer".fg(theme.secondary), + " T ".fg(theme.foreground), + "theme".fg(theme.secondary), + " Q/Esc ".fg(theme.foreground), + "quit".fg(theme.secondary), + ]), + }; + Paragraph::new(footer_line) + .alignment(Alignment::Center) + .block( + Block::bordered() + .border_set(border::ROUNDED) + .border_style(Style::default().fg(theme.muted)), + ) + .render(footer, buf); } } @@ -751,6 +1003,24 @@ fn device_summary(devices: &[MidiDevice]) -> Option { }) } +fn parse_kind(value: &str) -> Result { + match value { + "application" => Ok(MixerObjectKind::Application), + "group" => Ok(MixerObjectKind::Group), + "output" => Ok(MixerObjectKind::Output), + _ => Err("target kind must be application, group, or output".to_owned()), + } +} + +const fn editor_prompt(operation: EditorOperation) -> &'static str { + match operation { + EditorOperation::Application => "app id|label|field|exact/regex|pattern", + EditorOperation::Group => "group id|label|member1,member2", + EditorOperation::Fader => "fader id|application/group/output|target|pickup", + EditorOperation::Remove => "delete application/group/fader|id", + } +} + impl LiveTui { fn render_configuration(&self, area: Rect, buf: &mut Buffer) { let theme = self.theme.palette(); @@ -769,9 +1039,27 @@ impl LiveTui { .bold(), ]; lines.push(Line::from("")); + lines.push( + Line::from( + "A app · G group · F fader · D delete · Enter submit · Esc cancel", + ) + .fg(theme.muted), + ); lines.push(Line::from("Applications").fg(theme.accent).bold()); lines.extend(config.applications.iter().map(|application| { - Line::from(format!(" {} — {}", application.id, application.label)) + let matched = self + .snapshot + .items + .iter() + .find(|item| { + item.id.kind == MixerObjectKind::Application && item.id.id == application.id + }) + .map(|item| item.detail.as_str()) + .unwrap_or("not in live snapshot"); + Line::from(format!( + " {} — {} · matcher preview: {}", + application.id, application.label, matched + )) })); lines.push(Line::from("Groups").fg(theme.accent).bold()); lines.extend(config.groups.iter().map(|group| { @@ -1162,6 +1450,80 @@ mod tests { assert!(rendered.contains("desk-left · volume · cc ch1 #49")); } + #[test] + fn configuration_editor_submits_valid_input_and_cancel_has_no_side_effect() { + struct EditingClient { + snapshot: MixerSnapshot, + edits: Arc>>, + } + + impl MixerClient for EditingClient { + fn snapshot(&mut self) -> io::Result { + Ok(self.snapshot.clone()) + } + + fn set_volume( + &mut self, + _id: MixerObjectId, + _gain: f64, + _expected_revision: u64, + ) -> io::Result { + unreachable!() + } + + fn toggle_mute( + &mut self, + _id: MixerObjectId, + _expected_revision: u64, + ) -> io::Result { + unreachable!() + } + + fn edit_configuration( + &mut self, + edit: ConfigurationEdit, + expected_revision: u64, + ) -> io::Result { + assert_eq!(expected_revision, 0); + self.edits.lock().unwrap().push(edit); + self.snapshot.configuration.revision += 1; + self.snapshot.configuration.dirty = true; + Ok(self.snapshot.clone()) + } + } + + let edits = Arc::new(Mutex::new(Vec::new())); + let mut app = LiveTui::new(EditingClient { + snapshot: DemoClient::default().view(), + edits: Arc::clone(&edits), + }) + .unwrap(); + app.handle_key_event(press(KeyCode::Char('2'))); + app.handle_key_event(press(KeyCode::Char('g'))); + for character in "comms|Communications|browser,music".chars() { + app.handle_key_event(press(KeyCode::Char(character))); + } + app.handle_key_event(press(KeyCode::Enter)); + assert_eq!(app.snapshot.configuration.revision, 1); + assert_eq!( + edits.lock().unwrap().as_slice(), + &[ConfigurationEdit::Group { + existing: false, + id: "comms".into(), + label: "Communications".into(), + members: vec!["browser".into(), "music".into()], + }] + ); + + app.handle_key_event(press(KeyCode::Char('a'))); + for character in "discarded".chars() { + app.handle_key_event(press(KeyCode::Char(character))); + } + app.handle_key_event(press(KeyCode::Esc)); + assert_eq!(edits.lock().unwrap().len(), 1); + assert!(app.editor.is_none()); + } + #[test] fn device_status_summaries_include_recovery_actions_and_errors() { let ambiguous = MidiDevice {