From fa45944b79884e40ee8e8489b66f332b3d52bb79 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 15 Oct 2026 04:18:12 +0200 Subject: [PATCH] feat(M9.2): learn MIDI controls into server drafts Test: cargo test -p fader-config --all-targets --all-features Test: cargo test -p tui --all-targets --all-features Test: cargo test -p fader_master --all-targets --all-features Test: cargo clippy -p fader-config -p tui -p fader_master --all-targets --all-features -- -D warnings --- architecture.md | 5 + fader_master/src/editor.rs | 35 ++++++ fader_master/src/ipc.rs | 18 ++- fader_master/src/live.rs | 7 ++ fader_master/src/local.rs | 135 +++++++++++++++++++- fader_master/src/midi_runtime.rs | 150 +++++++++++++++++++++-- fader_master/src/tui_client.rs | 19 +++ task.md | 5 +- tui/src/lib.rs | 204 +++++++++++++++++++++++++++++-- 9 files changed, 555 insertions(+), 23 deletions(-) diff --git a/architecture.md b/architecture.md index 72e728f..07223ab 100644 --- a/architecture.md +++ b/architecture.md @@ -309,6 +309,11 @@ Draft edits are serialized by the server, require the caller's expected draft revision, and never mutate live routing or audio as a side effect. Successful draft edits are explicitly marked unsaved until a later apply/save command. +MIDI learn is scoped to one configured surface, logical fader, and action. While +armed, messages from that surface are withheld from normal routing; unrelated +surfaces continue normally. The first compatible CC or note press becomes a +validated draft binding, while cancellation restores routing immediately. + The implemented atomic writer checks that its parent and any existing target are owned by the effective user and are not symlinks. It creates mode-`0600` temporary files in the destination directory, streams and syncs their content, diff --git a/fader_master/src/editor.rs b/fader_master/src/editor.rs index 14f018d..c0a137d 100644 --- a/fader_master/src/editor.rs +++ b/fader_master/src/editor.rs @@ -109,6 +109,41 @@ impl ConfigurationEditor { pickup_tolerance, )?, ConfigurationEdit::RemoveFader { id } => self.document.remove_fader(&id)?, + ConfigurationEdit::AddBinding { + surface, + fader, + action, + kind, + channel, + number, + } => self.document.add_binding( + &surface, + &fader, + match action.as_str() { + "volume" => fader_config::Action::Volume, + "toggle_mute" => fader_config::Action::ToggleMute, + _ => { + return Err(ConfigError::Validation { + path: "binding.action".to_owned(), + message: format!("unsupported action {action:?}"), + } + .into()); + } + }, + match kind.as_str() { + "cc" => fader_config::MessageKind::Cc, + "note" => fader_config::MessageKind::Note, + _ => { + return Err(ConfigError::Validation { + path: "binding.message.kind".to_owned(), + message: format!("unsupported message kind {kind:?}"), + } + .into()); + } + }, + channel, + number, + )?, } self.revision = self.revision.saturating_add(1); self.dirty = true; diff --git a/fader_master/src/ipc.rs b/fader_master/src/ipc.rs index 5bdf081..856051f 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 = 6; +pub const PROTOCOL_VERSION: u16 = 7; pub const MAX_FRAME_BYTES: usize = 64 * 1024; /// Kind of mixer object addressed by a client. @@ -47,6 +47,12 @@ pub enum RequestCommand { expected_revision: u64, edit: ConfigurationEdit, }, + StartMidiLearn { + surface: String, + fader: String, + action: String, + }, + CancelMidiLearn, SetVolume { object: MixerObjectKey, gain: f64, @@ -106,6 +112,14 @@ pub enum ConfigurationEdit { RemoveFader { id: String, }, + AddBinding { + surface: String, + fader: String, + action: String, + kind: String, + channel: u16, + number: u16, + }, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] @@ -136,6 +150,8 @@ pub struct MixerSnapshot { pub struct ConfigurationSnapshot { pub revision: u64, pub dirty: bool, + pub learning: Option, + pub error: Option, pub profile_id: String, pub applications: Vec, pub groups: Vec, diff --git a/fader_master/src/live.rs b/fader_master/src/live.rs index c53e1c9..689726c 100644 --- a/fader_master/src/live.rs +++ b/fader_master/src/live.rs @@ -105,6 +105,8 @@ pub(crate) fn configuration_snapshot( ConfigurationSnapshot { revision, dirty, + learning: None, + error: None, profile_id: profile.id().to_string(), applications: profile .applications() @@ -570,6 +572,11 @@ impl LiveMixerState { "configuration edits must be handled by the server owner".to_owned(), )); } + RequestCommand::StartMidiLearn { .. } | RequestCommand::CancelMidiLearn => { + return Err(LiveMixerError::Profile( + "MIDI learn commands must be handled by the server owner".to_owned(), + )); + } RequestCommand::SetVolume { object, gain, diff --git a/fader_master/src/local.rs b/fader_master/src/local.rs index 644976f..1671035 100644 --- a/fader_master/src/local.rs +++ b/fader_master/src/local.rs @@ -10,7 +10,7 @@ use std::{ }; use fader_config::{ProfileDocument, XdgEnvironment, XdgPaths}; -use fader_core::{BackendEpoch, Gain}; +use fader_core::{BackendEpoch, FaderId, Gain, SurfaceId}; use thiserror::Error; use volume_lib::{AdapterQueue, Enqueue, PulseWorker, WorkerEvent}; @@ -216,7 +216,8 @@ impl LocalServer { } pub fn tick(&mut self) -> Result<(), LocalError> { - for intent in self.midi.tick() { + let midi_tick = self.midi.tick(); + for intent in midi_tick.intents { let sequence = self.midi_sequence; self.midi_sequence = self .midi_sequence @@ -225,6 +226,37 @@ impl LocalServer { let commands = self.mixer.midi_intent(intent, sequence)?; self.enqueue(commands)?; } + if let Some(binding) = midi_tick.learned { + let edit = crate::ipc::ConfigurationEdit::AddBinding { + surface: binding.surface, + fader: binding.fader, + action: match binding.action { + fader_config::Action::Volume => "volume", + fader_config::Action::ToggleMute => "toggle_mute", + } + .to_owned(), + kind: match binding.kind { + fader_config::MessageKind::Cc => "cc", + fader_config::MessageKind::Note => "note", + } + .to_owned(), + channel: binding.channel, + number: binding.number, + }; + match self + .configuration + .apply(self.configuration.revision(), edit) + { + Ok(profile) => self.publish_configuration(&profile, None), + Err(error) => { + let profile = self + .configuration + .profile() + .map_err(|error| crate::live::LiveMixerError::Profile(error.to_string()))?; + self.publish_configuration(&profile, Some(error.to_string())); + } + } + } self.mixer.set_devices(self.midi.snapshot()); self.flush_dispatch(); match self.worker.receive_timeout(self.poll_interval) { @@ -284,6 +316,75 @@ impl LocalServer { Err(error) => Err(crate::live::LiveMixerError::Profile(error.to_string())), } } + crate::ipc::RequestCommand::StartMidiLearn { + surface, + fader, + action, + } if request.version == PROTOCOL_VERSION => { + let profile = self + .configuration + .profile() + .map_err(|error| crate::live::LiveMixerError::Profile(error.to_string()))?; + if !profile.surfaces().iter().any(|item| item.id() == surface) { + return self.write_client_error( + stream, + request_id, + format!("unknown MIDI surface {surface:?}"), + ); + } + if !profile.faders().iter().any(|item| item.id() == fader) { + return self.write_client_error( + stream, + request_id, + format!("unknown fader {fader:?}"), + ); + } + let action = match action.as_str() { + "volume" => fader_config::Action::Volume, + "toggle_mute" => fader_config::Action::ToggleMute, + _ => { + return self.write_client_error( + stream, + request_id, + format!("unsupported MIDI learn action {action:?}"), + ); + } + }; + let surface_id = SurfaceId::new(&surface) + .map_err(|error| crate::live::LiveMixerError::Profile(error.to_string()))?; + let fader_id = FaderId::new(&fader) + .map_err(|error| crate::live::LiveMixerError::Profile(error.to_string()))?; + self.midi.start_learn(crate::midi_runtime::MidiLearn { + surface: surface_id, + fader: fader_id, + action, + }); + let mut configuration = configuration_snapshot( + &profile, + self.configuration.revision(), + self.configuration.dirty(), + ); + configuration.learning = Some(format!("{surface} -> {fader} ({action:?})")); + self.mixer.set_configuration(configuration); + self.mixer.request(ClientRequest { + version: request.version, + request_id, + command: crate::ipc::RequestCommand::Snapshot, + }) + } + crate::ipc::RequestCommand::CancelMidiLearn if request.version == PROTOCOL_VERSION => { + self.midi.cancel_learn(); + let profile = self + .configuration + .profile() + .map_err(|error| crate::live::LiveMixerError::Profile(error.to_string()))?; + self.publish_configuration(&profile, None); + self.mixer.request(ClientRequest { + version: request.version, + request_id, + command: crate::ipc::RequestCommand::Snapshot, + }) + } command => self.mixer.request(ClientRequest { version: request.version, request_id, @@ -308,6 +409,36 @@ impl LocalServer { Ok(()) } + fn publish_configuration(&mut self, profile: &fader_config::Profile, error: Option) { + let mut configuration = configuration_snapshot( + profile, + self.configuration.revision(), + self.configuration.dirty(), + ); + configuration.error = error; + self.mixer.set_configuration(configuration); + } + + fn write_client_error( + &self, + stream: &mut UnixStream, + request_id: u64, + message: String, + ) -> Result<(), LocalError> { + write_frame( + stream, + &ServerResponse { + version: PROTOCOL_VERSION, + request_id, + result: ResponseResult::Error { + message, + resync: false, + }, + }, + )?; + Ok(()) + } + fn enqueue(&mut self, commands: Vec) -> Result<(), LocalError> { for command in commands { let operation = match &command { diff --git a/fader_master/src/midi_runtime.rs b/fader_master/src/midi_runtime.rs index 800a228..4c47f93 100644 --- a/fader_master/src/midi_runtime.rs +++ b/fader_master/src/midi_runtime.rs @@ -10,8 +10,9 @@ use fader_core::{ MidiData, SurfaceId, }; use midi::{ - DeviceMatch, LinuxIdentityCatalog, MidiInputCatalog, MidiInputConnection, MidiInputEvent, - MidiIntent, MidiRouter, SurfaceAction, SurfaceAssignment, SurfaceLifecycle, SurfaceStatus, + ButtonEdge, DeviceMatch, LinuxIdentityCatalog, MidiInputCatalog, MidiInputConnection, + MidiInputEvent, MidiIntent, MidiMessage, MidiRouter, SurfaceAction, SurfaceAssignment, + SurfaceLifecycle, SurfaceStatus, }; use crate::ipc::MidiDevice; @@ -29,6 +30,30 @@ pub struct MidiRuntime { last_scan: Option, scan_error: Option, router: MidiRouter, + learn: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct MidiLearn { + pub surface: SurfaceId, + pub fader: FaderId, + pub action: fader_config::Action, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct LearnedBinding { + pub surface: String, + pub fader: String, + pub action: fader_config::Action, + pub kind: fader_config::MessageKind, + pub channel: u16, + pub number: u16, +} + +#[derive(Debug, Default)] +pub struct MidiTick { + pub intents: Vec, + pub learned: Option, } impl std::fmt::Debug for MidiRuntime { @@ -103,10 +128,11 @@ impl MidiRuntime { last_scan: None, scan_error: None, router, + learn: None, }) } - pub fn tick(&mut self) -> Vec { + pub fn tick(&mut self) -> MidiTick { if self .last_scan .is_none_or(|last| last.elapsed() >= SCAN_INTERVAL) @@ -114,15 +140,13 @@ impl MidiRuntime { self.scan(); self.last_scan = Some(Instant::now()); } - let mut intents = Vec::new(); + let mut result = MidiTick::default(); loop { match self.receiver.try_recv() { Ok(MidiInputEvent::Message { surface, message, .. }) => { - if let Some(intent) = self.router.route(&surface, message) { - intents.push(intent); - } + self.handle_message(surface, message, &mut result); } Ok(MidiInputEvent::Malformed { error, .. }) => { self.scan_error = Some(format!("malformed MIDI input: {error}")); @@ -137,7 +161,73 @@ impl MidiRuntime { { self.scan_error = Some("MIDI input queue overflowed; reconnect required".to_owned()); } - intents + result + } + + pub fn start_learn(&mut self, learn: MidiLearn) { + self.learn = Some(learn); + } + + pub fn cancel_learn(&mut self) { + self.learn = None; + } + + #[must_use] + pub fn learning(&self) -> Option<&MidiLearn> { + self.learn.as_ref() + } + + fn handle_message(&mut self, surface: SurfaceId, message: MidiMessage, result: &mut MidiTick) { + if self + .learn + .as_ref() + .is_some_and(|learn| learn.surface == surface) + { + let learned = self.learn.as_ref().and_then(|learn| { + let (kind, channel, number) = match (learn.action, message) { + ( + fader_config::Action::Volume, + MidiMessage::ControlChange { + channel, number, .. + }, + ) => (fader_config::MessageKind::Cc, channel, number), + ( + fader_config::Action::ToggleMute, + MidiMessage::Note { + channel, + number, + edge: ButtonEdge::Press, + .. + }, + ) => (fader_config::MessageKind::Note, channel, number), + ( + fader_config::Action::ToggleMute, + MidiMessage::ControlChange { + channel, + number, + value, + }, + ) if value.get() > 0 => (fader_config::MessageKind::Cc, channel, number), + _ => return None, + }; + Some(LearnedBinding { + surface: learn.surface.as_str().to_owned(), + fader: learn.fader.as_str().to_owned(), + action: learn.action, + kind, + channel: u16::from(channel.get()), + number: u16::from(number.get()), + }) + }); + if learned.is_some() { + self.learn = None; + result.learned = learned; + } + return; + } + if let Some(intent) = self.router.route(&surface, message) { + result.intents.push(intent); + } } #[must_use] @@ -326,4 +416,48 @@ mod tests { Some(MidiIntent::ToggleMute { fader, .. }) if fader.as_str() == "master-fader" )); } + + #[test] + fn midi_learn_is_surface_scoped_suppresses_routing_and_cancel_restores_it() { + let profile = + Profile::parse(include_str!("../../examples/profiles/arch-pipewire.toml")).unwrap(); + let mut runtime = MidiRuntime::new(&profile).unwrap(); + let surface = SurfaceId::new("apc-mini").unwrap(); + runtime.start_learn(MidiLearn { + surface: surface.clone(), + fader: FaderId::new("media-fader").unwrap(), + action: fader_config::Action::Volume, + }); + let message = MidiMessage::ControlChange { + channel: MidiChannel::new(1).unwrap(), + number: MidiData::new(48).unwrap(), + value: MidiData::new(100).unwrap(), + }; + let mut captured = MidiTick::default(); + runtime.handle_message( + SurfaceId::new("other-surface").unwrap(), + message, + &mut captured, + ); + assert!(captured.learned.is_none()); + assert!(runtime.learning().is_some()); + + runtime.handle_message(surface.clone(), message, &mut captured); + assert!(captured.intents.is_empty()); + assert_eq!(captured.learned.as_ref().unwrap().number, 48); + assert!(runtime.learning().is_none()); + + runtime.start_learn(MidiLearn { + surface: surface.clone(), + fader: FaderId::new("media-fader").unwrap(), + action: fader_config::Action::Volume, + }); + runtime.cancel_learn(); + let mut routed = MidiTick::default(); + runtime.handle_message(surface, message, &mut routed); + assert!(matches!( + routed.intents.as_slice(), + [MidiIntent::AbsoluteVolume { fader, .. }] if fader.as_str() == "music-fader" + )); + } } diff --git a/fader_master/src/tui_client.rs b/fader_master/src/tui_client.rs index c1ea58d..7a363e3 100644 --- a/fader_master/src/tui_client.rs +++ b/fader_master/src/tui_client.rs @@ -92,6 +92,8 @@ impl IpcMixerClient { configuration: tui::ConfigurationSnapshot { revision: snapshot.configuration.revision, dirty: snapshot.configuration.dirty, + learning: snapshot.configuration.learning, + error: snapshot.configuration.error, profile_id: snapshot.configuration.profile_id, applications: snapshot .configuration @@ -195,6 +197,23 @@ impl MixerClient for IpcMixerClient { edit: configuration_edit(edit), }) } + + fn start_midi_learn( + &mut self, + surface: String, + fader: String, + action: String, + ) -> io::Result { + self.send(RequestCommand::StartMidiLearn { + surface, + fader, + action, + }) + } + + fn cancel_midi_learn(&mut self) -> io::Result { + self.send(RequestCommand::CancelMidiLearn) + } } fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEdit { diff --git a/task.md b/task.md index 165e63f..b63a672 100644 --- a/task.md +++ b/task.md @@ -343,7 +343,10 @@ Dependencies: M8, M2, M1. 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. -- [ ] **M9.2 Surface bindings / MIDI learn:** select surface, listen for one supported control, preview conflicts and save binding. Tests: learning suppresses the normal action, other surfaces are not captured accidentally, cancellation restores routing, duplicate binding is rejected. +- [x] **M9.2 Surface bindings / MIDI learn:** select surface, listen for one supported control, preview conflicts and save binding. Tests: learning suppresses the normal action, other surfaces are not captured accidentally, cancellation restores routing, duplicate binding is rejected. + The Config tab starts surface/fader/action-scoped learning with `L` and + cancels with `C`. Captured CC/note identity is added to the validated server + draft; conflicts are shown without changing the draft revision. - [ ] **M9.3 Apply/save/conflict:** server-owned revisioned edits, separate live apply and persistence. Tests: stale edits conflict, external file edits are not overwritten, comments survive save, write failure is shown as unsaved and leaves previous disk config usable. ## M10 — Transactional profile swapping diff --git a/tui/src/lib.rs b/tui/src/lib.rs index 8dc2942..0e9b4c8 100644 --- a/tui/src/lib.rs +++ b/tui/src/lib.rs @@ -78,6 +78,8 @@ pub struct MidiDevice { pub struct ConfigurationSnapshot { pub revision: u64, pub dirty: bool, + pub learning: Option, + pub error: Option, pub profile_id: String, pub applications: Vec, pub groups: Vec, @@ -178,14 +180,44 @@ pub trait MixerClient { "configuration editing is unavailable", )) } + fn start_midi_learn( + &mut self, + _surface: String, + _fader: String, + _action: String, + ) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "MIDI learn is unavailable", + )) + } + fn cancel_midi_learn(&mut self) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "MIDI learn is unavailable", + )) + } } #[derive(Clone, Debug)] enum BufferedAction { - SetVolume { id: MixerObjectId, gain: f64 }, - ToggleMute { id: MixerObjectId }, + SetVolume { + id: MixerObjectId, + gain: f64, + }, + ToggleMute { + id: MixerObjectId, + }, Refresh, - EditConfiguration { edit: ConfigurationEdit }, + EditConfiguration { + edit: ConfigurationEdit, + }, + StartMidiLearn { + surface: String, + fader: String, + action: String, + }, + CancelMidiLearn, } #[derive(Debug)] @@ -195,7 +227,7 @@ struct BufferedState { desired_mutes: BTreeMap, volume_work: BTreeMap, mute_work: VecDeque, - configuration_work: VecDeque, + configuration_work: VecDeque, error: Option, shutdown: bool, } @@ -332,7 +364,43 @@ impl MixerClient for BufferedMixerClient { if state.configuration_work.len() >= 64 { return Err(io::Error::other("configuration edit buffer is full")); } - state.configuration_work.push_back(edit); + state + .configuration_work + .push_back(BufferedAction::EditConfiguration { edit }); + state.error = None; + let snapshot = state.snapshot.clone(); + wake.notify_one(); + Ok(snapshot) + } + + fn start_midi_learn( + &mut self, + surface: String, + fader: String, + action: String, + ) -> io::Result { + self.queue_configuration_action(BufferedAction::StartMidiLearn { + surface, + fader, + action, + }) + } + + fn cancel_midi_learn(&mut self) -> io::Result { + self.queue_configuration_action(BufferedAction::CancelMidiLearn) + } +} + +impl BufferedMixerClient { + fn queue_configuration_action(&self, action: BufferedAction) -> 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 action buffer is full")); + } + state.configuration_work.push_back(action); state.error = None; let snapshot = state.snapshot.clone(); wake.notify_one(); @@ -394,8 +462,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 if let Some(action) = state.configuration_work.pop_front() { + action } else { BufferedAction::Refresh } @@ -433,6 +501,12 @@ fn execute_action( BufferedAction::EditConfiguration { edit } => { client.edit_configuration(edit.clone(), configuration_revision) } + BufferedAction::StartMidiLearn { + surface, + fader, + action, + } => client.start_midi_learn(surface.clone(), fader.clone(), action.clone()), + BufferedAction::CancelMidiLearn => client.cancel_midi_learn(), }; match execute(client, confirmed.revision, confirmed.configuration.revision) { Ok(snapshot) => Ok(snapshot), @@ -500,6 +574,7 @@ fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) { } BufferedAction::Refresh => {} BufferedAction::EditConfiguration { .. } => {} + BufferedAction::StartMidiLearn { .. } | BufferedAction::CancelMidiLearn => {} } } @@ -567,6 +642,7 @@ enum EditorOperation { Group, Fader, Remove, + Learn, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -681,6 +757,15 @@ impl LiveTui { KeyCode::Char('d') if self.tab == Tab::Configuration => { self.start_editor(EditorOperation::Remove) } + KeyCode::Char('l') if self.tab == Tab::Configuration => { + self.start_editor(EditorOperation::Learn) + } + KeyCode::Char('c') if self.tab == Tab::Configuration => { + match self.client.cancel_midi_learn() { + Ok(snapshot) => self.replace_snapshot(snapshot), + Err(error) => self.client_error = Some(error.to_string()), + } + } KeyCode::Esc | KeyCode::Char('q') => self.exit = true, _ => {} } @@ -716,6 +801,22 @@ impl LiveTui { let Some(editor) = self.editor.take() else { return; }; + if editor.operation == EditorOperation::Learn { + let fields = editor.value.split('|').map(str::trim).collect::>(); + if fields.len() != 3 || !matches!(fields[2], "volume" | "toggle_mute") { + self.client_error = Some("expected surface|fader|volume/toggle_mute".to_owned()); + return; + } + match self.client.start_midi_learn( + fields[0].to_owned(), + fields[1].to_owned(), + fields[2].to_owned(), + ) { + Ok(snapshot) => self.replace_snapshot(snapshot), + Err(error) => self.client_error = Some(error.to_string()), + } + return; + } let edit = match self.parse_editor(&editor) { Ok(edit) => edit, Err(error) => { @@ -808,6 +909,7 @@ impl LiveTui { Err("expected id|application/group/output|target|pickup".to_owned()) } EditorOperation::Remove => Err("expected application/group/fader|id".to_owned()), + EditorOperation::Learn => Err("MIDI learn uses its own input".to_owned()), } } @@ -958,6 +1060,8 @@ impl Widget for &LiveTui { "fader".fg(theme.secondary), " D ".fg(theme.foreground), "delete".fg(theme.secondary), + " L/C ".fg(theme.foreground), + "learn".fg(theme.secondary), " Tab ".fg(theme.foreground), "mixer".fg(theme.secondary), " T ".fg(theme.foreground), @@ -1018,6 +1122,7 @@ const fn editor_prompt(operation: EditorOperation) -> &'static str { EditorOperation::Group => "group id|label|member1,member2", EditorOperation::Fader => "fader id|application/group/output|target|pickup", EditorOperation::Remove => "delete application/group/fader|id", + EditorOperation::Learn => "learn surface|fader|volume/toggle_mute", } } @@ -1038,12 +1143,22 @@ impl LiveTui { )) .bold(), ]; + if let Some(learning) = &config.learning { + lines.push( + Line::from(format!( + "MIDI learn: {learning} — move or press one control" + )) + .fg(theme.warning) + .bold(), + ); + } + if let Some(error) = &config.error { + lines.push(Line::from(format!("Configuration error: {error}")).fg(theme.error)); + } lines.push(Line::from("")); lines.push( - Line::from( - "A app · G group · F fader · D delete · Enter submit · Esc cancel", - ) - .fg(theme.muted), + Line::from("A app · G group · F fader · D delete · L learn · C cancel learn") + .fg(theme.muted), ); lines.push(Line::from("Applications").fg(theme.accent).bold()); lines.extend(config.applications.iter().map(|application| { @@ -1404,6 +1519,8 @@ mod tests { snapshot.configuration = ConfigurationSnapshot { revision: 3, dirty: true, + learning: None, + error: None, profile_id: "desktop".into(), applications: vec![ConfiguredApplication { id: "browser".into(), @@ -1524,6 +1641,71 @@ mod tests { assert!(app.editor.is_none()); } + #[test] + fn configuration_tab_starts_and_cancels_midi_learn() { + struct LearnClient { + snapshot: MixerSnapshot, + calls: Arc>>, + } + impl MixerClient for LearnClient { + fn snapshot(&mut self) -> io::Result { + Ok(self.snapshot.clone()) + } + fn set_volume( + &mut self, + _: MixerObjectId, + _: f64, + _: u64, + ) -> io::Result { + unreachable!() + } + fn toggle_mute(&mut self, _: MixerObjectId, _: u64) -> io::Result { + unreachable!() + } + fn start_midi_learn( + &mut self, + surface: String, + fader: String, + action: String, + ) -> io::Result { + self.calls + .lock() + .unwrap() + .push(format!("start:{surface}:{fader}:{action}")); + self.snapshot.configuration.learning = Some("waiting".into()); + Ok(self.snapshot.clone()) + } + fn cancel_midi_learn(&mut self) -> io::Result { + self.calls.lock().unwrap().push("cancel".into()); + self.snapshot.configuration.learning = None; + Ok(self.snapshot.clone()) + } + } + + let calls = Arc::new(Mutex::new(Vec::new())); + let mut app = LiveTui::new(LearnClient { + snapshot: DemoClient::default().view(), + calls: Arc::clone(&calls), + }) + .unwrap(); + app.handle_key_event(press(KeyCode::Char('2'))); + app.handle_key_event(press(KeyCode::Char('l'))); + for character in "apc-mini|media-fader|volume".chars() { + app.handle_key_event(press(KeyCode::Char(character))); + } + app.handle_key_event(press(KeyCode::Enter)); + assert_eq!( + app.snapshot.configuration.learning.as_deref(), + Some("waiting") + ); + app.handle_key_event(press(KeyCode::Char('c'))); + assert!(app.snapshot.configuration.learning.is_none()); + assert_eq!( + calls.lock().unwrap().as_slice(), + &["start:apc-mini:media-fader:volume", "cancel"] + ); + } + #[test] fn device_status_summaries_include_recovery_actions_and_errors() { let ambiguous = MidiDevice {