diff --git a/README.md b/README.md index 9de78ac..884bd02 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ same profile can switch to a compact stacked layout for narrow terminals: clients come and go. - Edit a validated draft from the TUI and persist it with one explicit Save. Malformed or conflicting edits never replace the active configuration. +- Switch among valid managed profiles from a popup in the Config view; the + default switch adopts live audio without writing saved volume state. ## Quick start @@ -64,6 +66,7 @@ safe empty `default` profile on first use, which can then be edited in the TUI. 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. +Config → Active profile opens the profile switcher. ## Documentation diff --git a/architecture.md b/architecture.md index 914d635..42e4e02 100644 --- a/architecture.md +++ b/architecture.md @@ -400,6 +400,11 @@ version, use request IDs and revisioned snapshots, and resnapshot after missed deltas. Length-prefixed UTF-8 TOML messages reuse Serde schemas initially; cap frames before allocation. +Configuration snapshots include the valid sibling profile IDs discovered by +the server. The Config view presents them in a modal selector and requests the +same adopt-mode transactional switch as `profile switch ID`; invalid profile +documents are not advertised, and activation errors retain the current profile. + The TUI owns blocking IPC on a background thread. Its render/input thread reads a shared local snapshot only, applies optimistic volume/mute changes, and queues work without waiting for a socket response. Pending volume work is diff --git a/docs/configuration.md b/docs/configuration.md index db70cfd..3c889a9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -56,6 +56,10 @@ Switch an existing server to another managed profile with: fader_master profile switch PROFILE_ID ``` +The same adopt-mode switch is available in the TUI under Config → Active +profile. The popup lists valid TOML profiles from the managed profile directory; +malformed files are omitted. + Profile IDs are stable identifiers, not paths. Use `--restore` only when the saved desired state should deliberately be written after activation; the safe default adopts live audio without changing it. diff --git a/fader_master/src/ipc.rs b/fader_master/src/ipc.rs index 7d820a7..0e19414 100644 --- a/fader_master/src/ipc.rs +++ b/fader_master/src/ipc.rs @@ -214,6 +214,8 @@ pub struct ConfigurationSnapshot { pub learning: Option, pub error: Option, pub profile_id: String, + #[serde(default)] + pub available_profiles: Vec, pub mixer_orientation: MixerOrientation, pub default_controller: Option, pub theme: String, diff --git a/fader_master/src/live.rs b/fader_master/src/live.rs index 351abe9..5381cb8 100644 --- a/fader_master/src/live.rs +++ b/fader_master/src/live.rs @@ -116,6 +116,7 @@ pub(crate) fn configuration_snapshot( learning: None, error: None, profile_id: profile.id().to_string(), + available_profiles: vec![profile.id().to_string()], mixer_orientation: match profile.mixer_orientation() { fader_config::MixerOrientation::Vertical => crate::ipc::MixerOrientation::Vertical, fader_config::MixerOrientation::Horizontal => crate::ipc::MixerOrientation::Horizontal, diff --git a/fader_master/src/local.rs b/fader_master/src/local.rs index d1d0d4e..daa893f 100644 --- a/fader_master/src/local.rs +++ b/fader_master/src/local.rs @@ -206,7 +206,7 @@ impl LocalServer { message: "profile path has no parent directory".to_owned(), })? .to_owned(); - Ok(Self { + let mut server = Self { listener: OwnedListener::bind(socket)?, // One waiting native command keeps round-trip backpressure at the // state-owner boundary, where unsent volume motion can coalesce. @@ -226,7 +226,9 @@ impl LocalServer { profile_directory, active_config_path, state_path, - }) + }; + server.publish_configuration(&profile, None); + Ok(server) } /// Path owned by this server's local IPC listener. @@ -347,12 +349,7 @@ impl LocalServer { }; match self.configuration.apply(expected_revision, edit) { Ok(profile) => { - self.mixer.set_configuration(configuration_snapshot( - &profile, - self.configuration.revision(), - self.configuration.dirty(), - self.applied_configuration_revision, - )); + self.publish_configuration(&profile, None); self.mixer.request(ClientRequest { version: request.version, request_id, @@ -405,6 +402,8 @@ impl LocalServer { self.configuration.dirty(), self.applied_configuration_revision, ); + configuration.available_profiles = + available_profile_ids(&self.profile_directory, profile.id().as_str()); configuration.learning = Some(format!("{surface} -> {fader} ({action:?})")); self.mixer.set_configuration(configuration); self.mixer.request(ClientRequest { @@ -460,6 +459,11 @@ impl LocalServer { crate::ipc::RequestCommand::SwitchProfile { id, restore } if request.version == PROTOCOL_VERSION => { + if self.configuration.dirty() { + return Err(crate::live::LiveMixerError::Profile( + "save the current profile changes before switching profiles".to_owned(), + )); + } let profile_id = fader_core::ProfileId::new(&id) .map_err(|error| crate::live::LiveMixerError::Profile(error.to_string()))?; if !self.dispatch.is_empty() @@ -610,6 +614,8 @@ impl LocalServer { self.configuration.dirty(), self.applied_configuration_revision, ); + configuration.available_profiles = + available_profile_ids(&self.profile_directory, profile.id().as_str()); configuration.error = error; self.mixer.set_configuration(configuration); } @@ -664,6 +670,30 @@ impl LocalServer { } } +fn available_profile_ids(directory: &Path, active: &str) -> Vec { + let mut profiles = fs::read_dir(directory) + .into_iter() + .flatten() + .filter_map(Result::ok) + .filter_map(|entry| { + let path = entry.path(); + if path.extension().and_then(|extension| extension.to_str()) != Some("toml") { + return None; + } + let id = path.file_stem()?.to_str()?; + let source = fs::read_to_string(&path).ok()?; + let profile = ProfileDocument::parse(&source).ok()?.preview().ok()?; + (profile.id().as_str() == id).then(|| id.to_owned()) + }) + .collect::>(); + if !profiles.iter().any(|profile| profile == active) { + profiles.push(active.to_owned()); + } + profiles.sort(); + profiles.dedup(); + profiles +} + fn validate_peer(stream: &UnixStream) -> Result<(), LocalError> { let peer = rustix::net::sockopt::socket_peercred(stream).map_err(|source| LocalError::Socket { @@ -764,6 +794,37 @@ mod tests { ) .unwrap(); + assert_eq!( + server.mixer.snapshot().configuration.available_profiles, + ["desktop", "native", "secondary"] + ); + + let edited = direct_request( + &mut server, + RequestCommand::EditConfiguration { + expected_revision: 0, + edit: crate::ipc::ConfigurationEdit::SetTheme { + theme: "dracula".into(), + }, + }, + ); + assert!(matches!(edited.result, ResponseResult::Snapshot { .. })); + let dirty_switch = direct_request( + &mut server, + RequestCommand::SwitchProfile { + id: "secondary".into(), + restore: false, + }, + ); + assert!(matches!(dirty_switch.result, ResponseResult::Error { .. })); + let saved = direct_request( + &mut server, + RequestCommand::SaveConfiguration { + expected_revision: 1, + }, + ); + assert!(matches!(saved.result, ResponseResult::Snapshot { .. })); + let response = direct_request( &mut server, RequestCommand::SwitchProfile { diff --git a/fader_master/src/tui_client.rs b/fader_master/src/tui_client.rs index 55e7455..48f7cbb 100644 --- a/fader_master/src/tui_client.rs +++ b/fader_master/src/tui_client.rs @@ -97,6 +97,7 @@ impl IpcMixerClient { learning: snapshot.configuration.learning, error: snapshot.configuration.error, profile_id: snapshot.configuration.profile_id, + available_profiles: snapshot.configuration.available_profiles, mixer_orientation: match snapshot.configuration.mixer_orientation { crate::ipc::MixerOrientation::Vertical => tui::MixerOrientation::Vertical, crate::ipc::MixerOrientation::Horizontal => { @@ -286,6 +287,10 @@ impl MixerClient for IpcMixerClient { fn save_configuration(&mut self, expected_revision: u64) -> io::Result { self.send(RequestCommand::SaveConfiguration { expected_revision }) } + + fn switch_profile(&mut self, id: String) -> io::Result { + self.send(RequestCommand::SwitchProfile { id, restore: false }) + } } fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEdit { diff --git a/task.md b/task.md index 7ff49be..628a499 100644 --- a/task.md +++ b/task.md @@ -446,7 +446,9 @@ Dependencies: M9, M6, M7. `profile switch ID` now prepares a sibling profile, rejects invalid/native-only candidates and runtime timing changes, waits for pending audio reconciliation, then publishes matching, groups, faders, pickup, and MIDI together. Activation - advances the mixer view revision so pre-switch client commands are stale. + advances the mixer view revision so pre-switch client commands are stale. The + Config view lists valid sibling profiles and switches through a popup using + the same safe adopt-mode transaction. - [ ] **M10.2 Restore/adopt policy:** default switch adopts live state; explicit restore uses saved object intents and deterministic overlap ordering. Tests: no surprise startup/switch write, restore limits enforced, offline/new members follow configured policy, pickup/feedback resync happens on every surface. Default switching is write-free. `profile switch ID --restore` now validates the saved state before activation, restores online applications in profile diff --git a/tui/examples/doc_screenshots.rs b/tui/examples/doc_screenshots.rs index 7f8c17a..46b71f9 100644 --- a/tui/examples/doc_screenshots.rs +++ b/tui/examples/doc_screenshots.rs @@ -141,6 +141,7 @@ fn snapshot(mixer_orientation: MixerOrientation) -> MixerSnapshot { learning: None, error: None, profile_id: "desktop".to_owned(), + available_profiles: vec!["desktop".to_owned()], mixer_orientation, default_controller: Some("apc-mini".to_owned()), theme: ThemeName::CatppuccinMocha, diff --git a/tui/src/lib.rs b/tui/src/lib.rs index 2f7f53d..9372438 100644 --- a/tui/src/lib.rs +++ b/tui/src/lib.rs @@ -87,6 +87,7 @@ pub struct ConfigurationSnapshot { pub learning: Option, pub error: Option, pub profile_id: String, + pub available_profiles: Vec, pub mixer_orientation: MixerOrientation, pub default_controller: Option, pub theme: ThemeName, @@ -358,6 +359,12 @@ pub trait MixerClient { "configuration save is unavailable", )) } + fn switch_profile(&mut self, _id: String) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "profile switching is unavailable", + )) + } } #[derive(Clone, Debug)] @@ -380,6 +387,9 @@ enum BufferedAction { }, CancelMidiLearn, SaveConfiguration, + SwitchProfile { + id: String, + }, } #[derive(Debug)] @@ -562,6 +572,10 @@ impl MixerClient for BufferedMixerClient { fn save_configuration(&mut self, _expected_revision: u64) -> io::Result { self.queue_configuration_action(BufferedAction::SaveConfiguration) } + + fn switch_profile(&mut self, id: String) -> io::Result { + self.queue_configuration_action(BufferedAction::SwitchProfile { id }) + } } impl BufferedMixerClient { @@ -692,6 +706,7 @@ fn execute_action( } => client.start_midi_learn(surface.clone(), fader.clone(), action.clone()), BufferedAction::CancelMidiLearn => client.cancel_midi_learn(), BufferedAction::SaveConfiguration => client.save_configuration(configuration_revision), + BufferedAction::SwitchProfile { id } => client.switch_profile(id.clone()), }; let can_retry_stale = matches!( action, @@ -800,6 +815,7 @@ fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) { BufferedAction::EditConfiguration { .. } => {} BufferedAction::StartMidiLearn { .. } | BufferedAction::CancelMidiLearn => {} BufferedAction::SaveConfiguration => {} + BufferedAction::SwitchProfile { .. } => {} } } @@ -868,6 +884,7 @@ pub struct LiveTui { controller_picker: Option, group_member_picker: Option, hidden_fader_picker: Option, + profile_picker: Option, midi_device_details: Option, controller_selections: BTreeMap<(String, String), String>, } @@ -890,6 +907,7 @@ enum SettingsRow { MixerOrientation, DefaultController, HiddenFaders { count: usize }, + ActiveProfile, CancelMidiLearn, Save, MidiDevice { id: String }, @@ -943,6 +961,11 @@ struct HiddenFaderPicker { selected: usize, } +#[derive(Clone, Debug, Eq, PartialEq)] +struct ProfilePicker { + selected: usize, +} + enum FaderEditorRow { Capture { application: String, @@ -1069,6 +1092,7 @@ impl LiveTui { controller_picker: None, group_member_picker: None, hidden_fader_picker: None, + profile_picker: None, midi_device_details: None, controller_selections: BTreeMap::new(), } @@ -1216,6 +1240,10 @@ impl LiveTui { self.handle_hidden_fader_picker_key(key_event.code); return; } + if self.profile_picker.is_some() { + self.handle_profile_picker_key(key_event.code); + return; + } if self.midi_device_details.is_some() { self.handle_midi_device_details_key(key_event.code); return; @@ -1431,6 +1459,7 @@ impl LiveTui { SettingsRow::HiddenFaders { count: self.hidden_faders().len(), }, + SettingsRow::ActiveProfile, ]; if self.snapshot.configuration.learning.is_some() { rows.push(SettingsRow::CancelMidiLearn); @@ -1513,6 +1542,22 @@ impl LiveTui { SettingsRow::HiddenFaders { count } if forward && count > 0 => { self.hidden_fader_picker = Some(HiddenFaderPicker { selected: 0 }); } + SettingsRow::ActiveProfile if forward => { + if self.snapshot.configuration.dirty { + self.client_error = Some( + "save the current profile changes before switching profiles".to_owned(), + ); + return; + } + let selected = self + .snapshot + .configuration + .available_profiles + .iter() + .position(|profile| profile == &self.snapshot.configuration.profile_id) + .unwrap_or_default(); + self.profile_picker = Some(ProfilePicker { selected }); + } SettingsRow::CancelMidiLearn if forward => self.cancel_midi_learn(), SettingsRow::Save if forward => self.save_configuration(), SettingsRow::MidiDevice { id } if forward => { @@ -1586,6 +1631,40 @@ impl LiveTui { } } + fn handle_profile_picker_key(&mut self, code: KeyCode) { + let profiles = &self.snapshot.configuration.available_profiles; + let Some(picker) = &mut self.profile_picker else { + return; + }; + match code { + KeyCode::Esc => self.profile_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(profiles.len().saturating_sub(1)); + } + KeyCode::Enter => { + let Some(profile) = profiles.get(picker.selected).cloned() else { + return; + }; + if profile == self.snapshot.configuration.profile_id { + self.profile_picker = None; + return; + } + match self.client.switch_profile(profile) { + Ok(snapshot) => { + self.profile_picker = None; + self.controller_selections.clear(); + self.replace_snapshot(snapshot); + } + Err(error) => self.client_error = Some(error.to_string()), + } + } + _ => {} + } + } + fn handle_midi_device_details_key(&mut self, code: KeyCode) { let Some(id) = self.midi_device_details.clone() else { return; @@ -2420,6 +2499,9 @@ impl Widget for &LiveTui { if self.hidden_fader_picker.is_some() { self.render_hidden_fader_picker(area, buf); } + if self.profile_picker.is_some() { + self.render_profile_picker(area, buf); + } if self.midi_device_details.is_some() { self.render_midi_device_details(area, buf); } @@ -2935,6 +3017,53 @@ impl LiveTui { .render(popup, buf); } + fn render_profile_picker(&self, area: Rect, buf: &mut Buffer) { + let Some(picker) = &self.profile_picker else { + return; + }; + let theme = self.theme.palette(); + let profiles = &self.snapshot.configuration.available_profiles; + let height = u16::try_from(profiles.len().saturating_add(4)) + .unwrap_or(u16::MAX) + .min(area.height); + let popup = centered_rect(area, 64, height.max(5)); + let visible_rows = usize::from(popup.height.saturating_sub(2)).max(1); + let first_visible = picker + .selected + .saturating_add(1) + .saturating_sub(visible_rows); + let lines = profiles + .iter() + .enumerate() + .skip(first_visible) + .take(visible_rows) + .map(|(index, profile)| { + let active = profile == &self.snapshot.configuration.profile_id; + Line::from(format!( + "{} {profile}{}", + if index == picker.selected { "▶" } else { " " }, + if active { " · active" } else { "" } + )) + .style(if index == picker.selected { + Style::default().fg(theme.accent).bold() + } else { + Style::default().fg(theme.foreground) + }) + }) + .collect::>(); + Clear.render(popup, buf); + Paragraph::new(Text::from(lines)) + .block( + Block::bordered() + .title(" Switch profile ".fg(theme.accent).bold()) + .title_bottom(" ↑↓ select · Enter switch · Esc close ".fg(theme.muted)) + .border_set(border::DOUBLE) + .border_style(Style::default().fg(theme.accent)) + .style(Style::default().bg(theme.background)), + ) + .render(popup, buf); + } + fn render_midi_device_details(&self, area: Rect, buf: &mut Buffer) { let Some(id) = &self.midi_device_details else { return; @@ -3109,6 +3238,9 @@ impl LiveTui { format!("Show hidden faders {count} [Enter]") } SettingsRow::HiddenFaders { .. } => "Show hidden faders none".to_owned(), + SettingsRow::ActiveProfile => { + format!("Active profile {} [Enter]", config.profile_id) + } SettingsRow::CancelMidiLearn => "Cancel MIDI learn [Enter]".to_owned(), SettingsRow::Save => format!( "Save changes {}", @@ -3825,6 +3957,20 @@ mod tests { self.snapshot.configuration.applied_revision = expected_revision; Ok(self.snapshot.clone()) } + + fn switch_profile(&mut self, id: String) -> io::Result { + if !self.snapshot.configuration.available_profiles.contains(&id) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unknown profile", + )); + } + self.snapshot.configuration.profile_id = id; + self.snapshot.configuration.revision = 0; + self.snapshot.configuration.applied_revision = 0; + self.snapshot.configuration.dirty = false; + Ok(self.snapshot.clone()) + } } #[test] @@ -4853,6 +4999,7 @@ mod tests { learning: None, error: None, profile_id: "desktop".into(), + available_profiles: vec!["desktop".into(), "streaming".into()], mixer_orientation: MixerOrientation::Vertical, default_controller: Some("desk-left".into()), theme: ThemeName::Dracula, @@ -4927,6 +5074,39 @@ mod tests { assert!(!rendered.contains("Applications")); } + #[test] + fn configuration_tab_switches_profiles_from_a_popup() { + let mut snapshot = DemoClient::default().view(); + snapshot.configuration.profile_id = "desktop".into(); + snapshot.configuration.available_profiles = vec!["desktop".into(), "streaming".into()]; + let edits = Arc::new(Mutex::new(Vec::new())); + let mut app = LiveTui::new(LayoutClient { snapshot, edits }).unwrap(); + + app.handle_key_event(press(KeyCode::Char('2'))); + for _ in 0..4 { + app.handle_key_event(press(KeyCode::Down)); + } + app.handle_key_event(press(KeyCode::Enter)); + + let area = Rect::new(0, 0, 90, 20); + let mut buffer = Buffer::empty(area); + (&app).render(area, &mut buffer); + let rendered = buffer + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(rendered.contains("Switch profile")); + assert!(rendered.contains("desktop · active")); + assert!(rendered.contains("streaming")); + + app.handle_key_event(press(KeyCode::Down)); + app.handle_key_event(press(KeyCode::Enter)); + + assert_eq!(app.snapshot.configuration.profile_id, "streaming"); + assert!(app.profile_picker.is_none()); + } + #[test] fn midi_device_details_popup_assigns_the_default_controller() { let edits = Arc::new(Mutex::new(Vec::new())); @@ -4954,7 +5134,7 @@ mod tests { }) .unwrap(); app.handle_key_event(press(KeyCode::Tab)); - for _ in 0..5 { + for _ in 0..6 { app.handle_key_event(press(KeyCode::Down)); } app.handle_key_event(press(KeyCode::Enter));