feat: implement M13.3d capability-aware media tab and guided editing
Verify: cargo test -p tui --quiet: 55 passed; cargo check --workspace --all-targets --all-features passed; workspace clippy -D warnings passed before final playlist-label addition; cargo fmt --all passed. Tests cover validation, discovery picker, advertised availability, gated commands and learn/unbind.
This commit is contained in:
parent
c7e33d45d2
commit
431669c994
|
|
@ -1484,6 +1484,7 @@ name = "tui"
|
|||
version = "0.1.0-rc.2"
|
||||
dependencies = [
|
||||
"fader-core",
|
||||
"media",
|
||||
"ratatui",
|
||||
]
|
||||
|
||||
|
|
|
|||
|
|
@ -198,8 +198,11 @@ actions, observed playback state, configuration entries and MIDI feedback rules.
|
|||
gate, and controls with stable IDs/actions/optional bindings. Configuration
|
||||
validates selectors, limits, references and input collisions with mixer bindings
|
||||
before activation. Entry editing is transactional; removing a surface unbinds its
|
||||
media controls without deleting entries. Runtime/UI integration follows this
|
||||
schema slice; it is not yet evidence of a functioning D-Bus adapter.
|
||||
media controls without deleting entries. The live server routes media MIDI press
|
||||
edges through the bounded worker and exposes discovery, capabilities and state
|
||||
over IPC. The optional Media tab edits draft entries and controls; Save activates
|
||||
them. Learn/unbind is scoped to a selected control and surface. Media commands
|
||||
are not retried by the client after ambiguous transport failures.
|
||||
|
||||
The MPRIS adapter uses pinned `dbus` 0.9.12 (MIT/Apache-2.0) and system
|
||||
libdbus-1; its upstream manifest does not declare an MSRV, so compatibility is
|
||||
|
|
|
|||
|
|
@ -113,6 +113,8 @@ impl IpcMixerClient {
|
|||
profile_id: snapshot.configuration.profile_id,
|
||||
profile_path: snapshot.configuration.profile_path,
|
||||
stream_metadata: snapshot.configuration.stream_metadata,
|
||||
media_entries: snapshot.configuration.media_entries,
|
||||
media_state: snapshot.configuration.media_state,
|
||||
available_profiles: snapshot.configuration.available_profiles,
|
||||
mixer_orientation: match snapshot.configuration.mixer_orientation {
|
||||
crate::ipc::MixerOrientation::Vertical => tui::MixerOrientation::Vertical,
|
||||
|
|
@ -328,6 +330,23 @@ impl MixerClient for IpcMixerClient {
|
|||
})
|
||||
}
|
||||
|
||||
fn media_action(&mut self, entry: String, control: String) -> io::Result<tui::MixerSnapshot> {
|
||||
self.send(RequestCommand::MediaAction { entry, control })
|
||||
}
|
||||
|
||||
fn start_media_learn(
|
||||
&mut self,
|
||||
surface: String,
|
||||
entry: String,
|
||||
control: String,
|
||||
) -> io::Result<tui::MixerSnapshot> {
|
||||
self.send(RequestCommand::StartMediaLearn {
|
||||
surface,
|
||||
entry,
|
||||
control,
|
||||
})
|
||||
}
|
||||
|
||||
fn start_midi_learn(
|
||||
&mut self,
|
||||
surface: String,
|
||||
|
|
@ -555,6 +574,17 @@ fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEd
|
|||
TuiConfigurationEdit::SetFeedbackEnabled { fader, enabled } => {
|
||||
IpcEdit::SetFeedbackEnabled { fader, enabled }
|
||||
}
|
||||
TuiConfigurationEdit::SetMediaEntry { entry } => IpcEdit::SetMediaEntry { entry },
|
||||
TuiConfigurationEdit::RemoveMediaEntry { id } => IpcEdit::RemoveMediaEntry { id },
|
||||
TuiConfigurationEdit::SetMediaBinding {
|
||||
entry,
|
||||
control,
|
||||
binding,
|
||||
} => IpcEdit::SetMediaBinding {
|
||||
entry,
|
||||
control,
|
||||
binding,
|
||||
},
|
||||
TuiConfigurationEdit::SetApplicationSelectorMode { id, match_all } => {
|
||||
IpcEdit::SetApplicationSelectorMode { id, match_all }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,4 +9,5 @@ publish.workspace = true
|
|||
|
||||
[dependencies]
|
||||
fader-core.workspace = true
|
||||
media.workspace = true
|
||||
ratatui.workspace = true
|
||||
|
|
|
|||
|
|
@ -137,6 +137,8 @@ fn snapshot(mixer_orientation: MixerOrientation) -> MixerSnapshot {
|
|||
}],
|
||||
discovered_midi_ports: Vec::new(),
|
||||
configuration: ConfigurationSnapshot {
|
||||
media_entries: Vec::new(),
|
||||
media_state: media::Snapshot::default(),
|
||||
revision: 7,
|
||||
dirty: false,
|
||||
applied_revision: 7,
|
||||
|
|
|
|||
178
tui/src/lib.rs
178
tui/src/lib.rs
|
|
@ -1,5 +1,6 @@
|
|||
//! Terminal user interface for fader_master.
|
||||
|
||||
mod media_ui;
|
||||
mod theme;
|
||||
|
||||
pub use theme::ThemeName;
|
||||
|
|
@ -92,6 +93,8 @@ pub struct DiscoveredMidiPort {
|
|||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ConfigurationSnapshot {
|
||||
pub media_entries: Vec<media::Entry>,
|
||||
pub media_state: media::Snapshot,
|
||||
pub feedback_disabled: bool,
|
||||
pub disabled_feedback_faders: Vec<String>,
|
||||
pub stream_metadata: Vec<String>,
|
||||
|
|
@ -356,6 +359,17 @@ pub struct ConfiguredBinding {
|
|||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ConfigurationEdit {
|
||||
SetMediaEntry {
|
||||
entry: media::Entry,
|
||||
},
|
||||
RemoveMediaEntry {
|
||||
id: String,
|
||||
},
|
||||
SetMediaBinding {
|
||||
entry: String,
|
||||
control: String,
|
||||
binding: Option<media::Binding>,
|
||||
},
|
||||
SetFeedbackEnabled {
|
||||
fader: Option<String>,
|
||||
enabled: bool,
|
||||
|
|
@ -502,6 +516,23 @@ pub struct MixerSnapshot {
|
|||
|
||||
/// Client boundary kept independent of sockets for deterministic TUI tests.
|
||||
pub trait MixerClient {
|
||||
fn media_action(&mut self, _entry: String, _control: String) -> io::Result<MixerSnapshot> {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"media controls unavailable",
|
||||
))
|
||||
}
|
||||
fn start_media_learn(
|
||||
&mut self,
|
||||
_surface: String,
|
||||
_entry: String,
|
||||
_control: String,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"media MIDI learn unavailable",
|
||||
))
|
||||
}
|
||||
fn snapshot(&mut self) -> io::Result<MixerSnapshot>;
|
||||
fn set_volume(
|
||||
&mut self,
|
||||
|
|
@ -563,6 +594,15 @@ pub trait MixerClient {
|
|||
|
||||
#[derive(Clone, Debug)]
|
||||
enum BufferedAction {
|
||||
MediaAction {
|
||||
entry: String,
|
||||
control: String,
|
||||
},
|
||||
StartMediaLearn {
|
||||
surface: String,
|
||||
entry: String,
|
||||
control: String,
|
||||
},
|
||||
SetVolume {
|
||||
id: MixerObjectId,
|
||||
gain: f64,
|
||||
|
|
@ -761,6 +801,21 @@ impl MixerClient for BufferedMixerClient {
|
|||
})
|
||||
}
|
||||
|
||||
fn media_action(&mut self, entry: String, control: String) -> io::Result<MixerSnapshot> {
|
||||
self.queue_configuration_action(BufferedAction::MediaAction { entry, control })
|
||||
}
|
||||
fn start_media_learn(
|
||||
&mut self,
|
||||
surface: String,
|
||||
entry: String,
|
||||
control: String,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.queue_configuration_action(BufferedAction::StartMediaLearn {
|
||||
surface,
|
||||
entry,
|
||||
control,
|
||||
})
|
||||
}
|
||||
fn cancel_midi_learn(&mut self) -> io::Result<MixerSnapshot> {
|
||||
self.queue_configuration_action(BufferedAction::CancelMidiLearn)
|
||||
}
|
||||
|
|
@ -893,6 +948,14 @@ fn execute_action<C: MixerClient>(
|
|||
const MAX_STALE_ATTEMPTS: usize = 8;
|
||||
|
||||
let execute = |client: &mut C, revision, configuration_revision| match action {
|
||||
BufferedAction::MediaAction { entry, control } => {
|
||||
client.media_action(entry.clone(), control.clone())
|
||||
}
|
||||
BufferedAction::StartMediaLearn {
|
||||
surface,
|
||||
entry,
|
||||
control,
|
||||
} => client.start_media_learn(surface.clone(), entry.clone(), control.clone()),
|
||||
BufferedAction::SetVolume { id, gain } => client.set_volume(id.clone(), *gain, revision),
|
||||
BufferedAction::ToggleMute { id } => client.toggle_mute(id.clone(), revision),
|
||||
BufferedAction::Refresh => client.snapshot(),
|
||||
|
|
@ -995,6 +1058,39 @@ fn publish_confirmed(state: &mut BufferedState, confirmed: &MixerSnapshot) {
|
|||
|
||||
fn apply_optimistic_configuration_edit(snapshot: &mut MixerSnapshot, edit: &ConfigurationEdit) {
|
||||
match edit {
|
||||
ConfigurationEdit::SetMediaEntry { entry } => {
|
||||
if let Some(old) = snapshot
|
||||
.configuration
|
||||
.media_entries
|
||||
.iter_mut()
|
||||
.find(|e| e.id == entry.id)
|
||||
{
|
||||
*old = entry.clone();
|
||||
} else {
|
||||
snapshot.configuration.media_entries.push(entry.clone());
|
||||
}
|
||||
snapshot.configuration.dirty = true;
|
||||
}
|
||||
ConfigurationEdit::RemoveMediaEntry { id } => {
|
||||
snapshot.configuration.media_entries.retain(|e| &e.id != id);
|
||||
snapshot.configuration.dirty = true;
|
||||
}
|
||||
ConfigurationEdit::SetMediaBinding {
|
||||
entry,
|
||||
control,
|
||||
binding,
|
||||
} => {
|
||||
if let Some(c) = snapshot
|
||||
.configuration
|
||||
.media_entries
|
||||
.iter_mut()
|
||||
.find(|e| &e.id == entry)
|
||||
.and_then(|e| e.controls.iter_mut().find(|c| &c.id == control))
|
||||
{
|
||||
c.binding = binding.clone();
|
||||
}
|
||||
snapshot.configuration.dirty = true;
|
||||
}
|
||||
ConfigurationEdit::SetFeedbackEnabled { fader, enabled } => {
|
||||
if let Some(fader) = fader {
|
||||
snapshot
|
||||
|
|
@ -1227,7 +1323,10 @@ fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) {
|
|||
}
|
||||
BufferedAction::Refresh => {}
|
||||
BufferedAction::EditConfiguration { .. } => {}
|
||||
BufferedAction::StartMidiLearn { .. } | BufferedAction::CancelMidiLearn => {}
|
||||
BufferedAction::StartMidiLearn { .. }
|
||||
| BufferedAction::CancelMidiLearn
|
||||
| BufferedAction::StartMediaLearn { .. }
|
||||
| BufferedAction::MediaAction { .. } => {}
|
||||
BufferedAction::SaveConfiguration => {}
|
||||
BufferedAction::ResetConfiguration => {}
|
||||
BufferedAction::SwitchProfile { .. } => {}
|
||||
|
|
@ -1281,6 +1380,7 @@ impl<F: FnOnce()> Drop for RestoreTerminal<F> {
|
|||
}
|
||||
|
||||
pub struct LiveTui<C> {
|
||||
media_ui: media_ui::MediaUi,
|
||||
client: C,
|
||||
snapshot: MixerSnapshot,
|
||||
selected: usize,
|
||||
|
|
@ -1316,6 +1416,7 @@ enum Tab {
|
|||
#[default]
|
||||
Mixer,
|
||||
Configuration,
|
||||
Media,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
|
|
@ -1733,6 +1834,7 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
reconcile_configured_midi_devices(&mut snapshot);
|
||||
Self {
|
||||
client,
|
||||
media_ui: media_ui::MediaUi::default(),
|
||||
snapshot,
|
||||
selected: 0,
|
||||
theme,
|
||||
|
|
@ -1790,6 +1892,7 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
}
|
||||
|
||||
fn replace_snapshot(&mut self, mut snapshot: MixerSnapshot) {
|
||||
self.media_ui.refresh(&snapshot.configuration);
|
||||
if self.snapshot.configuration.learning.is_some()
|
||||
&& snapshot.configuration.learning.is_none()
|
||||
{
|
||||
|
|
@ -1880,6 +1983,10 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
}
|
||||
|
||||
fn handle_key_event(&mut self, key_event: KeyEvent) {
|
||||
if self.media_ui.modal() {
|
||||
self.handle_media_key(key_event.code);
|
||||
return;
|
||||
}
|
||||
if self.device_delete_confirmation.is_some() {
|
||||
self.handle_device_delete_confirmation_key(key_event.code);
|
||||
return;
|
||||
|
|
@ -1981,7 +2088,11 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
KeyCode::Tab => {
|
||||
self.tab = match self.tab {
|
||||
Tab::Mixer => Tab::Configuration,
|
||||
Tab::Configuration if self.snapshot.configuration.media_state.available => {
|
||||
Tab::Media
|
||||
}
|
||||
Tab::Configuration => Tab::Mixer,
|
||||
Tab::Media => Tab::Mixer,
|
||||
};
|
||||
self.clamp_selection();
|
||||
}
|
||||
|
|
@ -1993,16 +2104,21 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
self.tab = Tab::Configuration;
|
||||
self.clamp_selection();
|
||||
}
|
||||
KeyCode::Char('3') if self.snapshot.configuration.media_state.available => {
|
||||
self.tab = Tab::Media
|
||||
}
|
||||
KeyCode::Char('q') => self.quit_confirmation = true,
|
||||
_ => match self.tab {
|
||||
Tab::Mixer => self.handle_mixer_key(key_event),
|
||||
Tab::Configuration => self.handle_settings_key(key_event.code),
|
||||
Tab::Media => self.handle_media_key(key_event.code),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn clamp_selection(&mut self) {
|
||||
match self.tab {
|
||||
Tab::Media => {}
|
||||
Tab::Mixer => {
|
||||
self.selected = self.selected.min(self.mixer_rows().len().saturating_sub(1));
|
||||
}
|
||||
|
|
@ -2014,6 +2130,33 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
}
|
||||
}
|
||||
|
||||
fn handle_media_key(&mut self, key: KeyCode) {
|
||||
for intent in self.media_ui.key(key, &self.snapshot.configuration) {
|
||||
let result = match intent {
|
||||
media_ui::Intent::Edit(edit) => self
|
||||
.client
|
||||
.edit_configuration(edit, self.snapshot.configuration.revision),
|
||||
media_ui::Intent::Action(entry, control) => {
|
||||
self.client.media_action(entry, control)
|
||||
}
|
||||
media_ui::Intent::Learn(surface, entry, control) => {
|
||||
self.client.start_media_learn(surface, entry, control)
|
||||
}
|
||||
media_ui::Intent::CancelLearn => self.client.cancel_midi_learn(),
|
||||
media_ui::Intent::Save => self
|
||||
.client
|
||||
.save_configuration(self.snapshot.configuration.revision),
|
||||
};
|
||||
match result {
|
||||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||||
Err(e) => {
|
||||
self.client_error = Some(e.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_mixer_key(&mut self, key_event: KeyEvent) {
|
||||
let horizontal =
|
||||
self.snapshot.configuration.mixer_orientation == MixerOrientation::Horizontal;
|
||||
|
|
@ -2406,6 +2549,19 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
.cloned()
|
||||
.map(SettingsRow::StreamMetadata),
|
||||
);
|
||||
rows.push(SettingsRow::StreamMetadata(format!(
|
||||
"MPRIS: {}",
|
||||
self.snapshot
|
||||
.configuration
|
||||
.media_state
|
||||
.error
|
||||
.as_deref()
|
||||
.unwrap_or(if self.snapshot.configuration.media_state.available {
|
||||
"available (Media tab)"
|
||||
} else {
|
||||
"unavailable (build feature or session bus)"
|
||||
})
|
||||
)));
|
||||
rows
|
||||
}
|
||||
|
||||
|
|
@ -3572,7 +3728,12 @@ impl<C: MixerClient> Widget for &LiveTui<C> {
|
|||
.bold(),
|
||||
" MASTER ".fg(theme.foreground).bold(),
|
||||
format!(
|
||||
" [1 Mixer] [2 Config] · {} · {} · rev {} · {} ",
|
||||
" [1 Mixer] [2 Config]{} · {} · {} · rev {} · {} ",
|
||||
if self.snapshot.configuration.media_state.available {
|
||||
" [3 Media]"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
self.snapshot.backend,
|
||||
self.snapshot.status,
|
||||
self.snapshot.revision,
|
||||
|
|
@ -3607,6 +3768,7 @@ impl<C: MixerClient> Widget for &LiveTui<C> {
|
|||
match self.tab {
|
||||
Tab::Mixer => " Live mixer objects ",
|
||||
Tab::Configuration => " Settings and status ",
|
||||
Tab::Media => " Media controls ",
|
||||
}
|
||||
.fg(theme.accent)
|
||||
.bold(),
|
||||
|
|
@ -3625,9 +3787,15 @@ impl<C: MixerClient> Widget for &LiveTui<C> {
|
|||
match self.tab {
|
||||
Tab::Mixer => self.render_streams(inner, buf),
|
||||
Tab::Configuration => self.render_configuration(inner, buf),
|
||||
Tab::Media => self
|
||||
.media_ui
|
||||
.render(inner, buf, &self.snapshot.configuration),
|
||||
}
|
||||
|
||||
let footer_line = match self.tab {
|
||||
Tab::Media => Line::from(
|
||||
"Enter send · L learn · A add · E edit · D delete · S save · Tab switch · H help",
|
||||
),
|
||||
Tab::Mixer => Line::from(vec![
|
||||
" M ".fg(theme.foreground),
|
||||
"mute".fg(theme.secondary),
|
||||
|
|
@ -3725,6 +3893,8 @@ impl<C: MixerClient> Widget for &LiveTui<C> {
|
|||
if self.snapshot.configuration.learning.is_some() {
|
||||
self.render_midi_learn_waiting(area, buf);
|
||||
}
|
||||
self.media_ui
|
||||
.render_modal(area, buf, &self.snapshot.configuration);
|
||||
if self.show_help {
|
||||
self.render_help(area, buf);
|
||||
}
|
||||
|
|
@ -4706,7 +4876,7 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
Line::from(" Reset setting Restore safe defaults after confirmation"),
|
||||
Line::from(""),
|
||||
Line::from("Global").fg(theme.accent).bold(),
|
||||
Line::from(" 1 / 2 / Tab Switch Mixer and Config views"),
|
||||
Line::from(" 1 / 2 / 3 / Tab Mixer / Config / Media (when available)"),
|
||||
Line::from(" T Cycle theme Q Confirm quit"),
|
||||
]))
|
||||
.wrap(Wrap { trim: false })
|
||||
|
|
@ -7384,6 +7554,8 @@ mod tests {
|
|||
let mut client = DemoClient::default();
|
||||
let mut snapshot = client.view();
|
||||
snapshot.configuration = ConfigurationSnapshot {
|
||||
media_entries: Vec::new(),
|
||||
media_state: media::Snapshot::default(),
|
||||
revision: 3,
|
||||
dirty: true,
|
||||
applied_revision: 2,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,976 @@
|
|||
use super::*;
|
||||
|
||||
pub(super) enum Intent {
|
||||
Edit(ConfigurationEdit),
|
||||
Action(String, String),
|
||||
Learn(String, String, String),
|
||||
CancelLearn,
|
||||
Save,
|
||||
}
|
||||
|
||||
enum Editor {
|
||||
Entry {
|
||||
entry: media::Entry,
|
||||
row: usize,
|
||||
text: Option<String>,
|
||||
},
|
||||
Control {
|
||||
entry: media::Entry,
|
||||
index: usize,
|
||||
row: usize,
|
||||
text: Option<String>,
|
||||
},
|
||||
Players {
|
||||
entry: media::Entry,
|
||||
selected: usize,
|
||||
},
|
||||
Delete(String),
|
||||
Learn {
|
||||
entry: String,
|
||||
control: String,
|
||||
selected: usize,
|
||||
started: bool,
|
||||
seen: bool,
|
||||
revision: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct MediaUi {
|
||||
selected: usize,
|
||||
editor: Option<Editor>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
fn new_entry(cfg: &ConfigurationSnapshot) -> media::Entry {
|
||||
let id = unique_id("media", cfg.media_entries.iter().map(|e| e.id.as_str()));
|
||||
media::Entry {
|
||||
label: "Media player".into(),
|
||||
id,
|
||||
selector: media::PlayerSelector {
|
||||
field: media::PlayerField::BusName,
|
||||
pattern: String::new(),
|
||||
regex: false,
|
||||
},
|
||||
feedback_enabled: true,
|
||||
controls: [
|
||||
media::Action::Play,
|
||||
media::Action::Pause,
|
||||
media::Action::Stop,
|
||||
media::Action::PlayPause,
|
||||
media::Action::Next,
|
||||
media::Action::Previous,
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, action)| media::Control {
|
||||
id: format!("control-{i}"),
|
||||
action,
|
||||
binding: None,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn unique_id<'a>(prefix: &str, ids: impl Iterator<Item = &'a str>) -> String {
|
||||
let ids: Vec<_> = ids.collect();
|
||||
(1..)
|
||||
.map(|n| format!("{prefix}-{n}"))
|
||||
.find(|id| !ids.contains(&id.as_str()))
|
||||
.unwrap_or_else(|| prefix.into())
|
||||
}
|
||||
|
||||
fn entry_editor(entry: media::Entry) -> Editor {
|
||||
Editor::Entry {
|
||||
entry,
|
||||
row: 0,
|
||||
text: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn actions() -> Vec<media::Action> {
|
||||
vec![
|
||||
media::Action::Play,
|
||||
media::Action::Pause,
|
||||
media::Action::Stop,
|
||||
media::Action::PlayPause,
|
||||
media::Action::Next,
|
||||
media::Action::Previous,
|
||||
media::Action::Seek { offset_ms: -10000 },
|
||||
media::Action::Seek { offset_ms: 10000 },
|
||||
media::Action::SetPosition { position_ms: 0 },
|
||||
media::Action::ShuffleToggle,
|
||||
media::Action::Shuffle { enabled: true },
|
||||
media::Action::Shuffle { enabled: false },
|
||||
media::Action::RepeatCycle,
|
||||
media::Action::Repeat {
|
||||
mode: media::Repeat::None,
|
||||
},
|
||||
media::Action::Repeat {
|
||||
mode: media::Repeat::Track,
|
||||
},
|
||||
media::Action::Repeat {
|
||||
mode: media::Repeat::Playlist,
|
||||
},
|
||||
media::Action::Playlist {
|
||||
id: "/playlist".into(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn cycle_action(action: &mut media::Action, forward: bool) {
|
||||
let choices = actions();
|
||||
let index = choices
|
||||
.iter()
|
||||
.position(|a| match (a, &*action) {
|
||||
(media::Action::Seek { offset_ms: a }, media::Action::Seek { offset_ms: b }) => {
|
||||
a.signum() == b.signum()
|
||||
}
|
||||
(media::Action::SetPosition { .. }, media::Action::SetPosition { .. })
|
||||
| (media::Action::Playlist { .. }, media::Action::Playlist { .. }) => true,
|
||||
_ => a == action,
|
||||
})
|
||||
.unwrap_or(0);
|
||||
let next = if forward {
|
||||
(index + 1) % choices.len()
|
||||
} else {
|
||||
(index + choices.len() - 1) % choices.len()
|
||||
};
|
||||
if let Some(choice) = choices.get(next) {
|
||||
*action = choice.clone();
|
||||
}
|
||||
}
|
||||
|
||||
fn parameter(action: &media::Action) -> String {
|
||||
match action {
|
||||
media::Action::Seek { offset_ms } => offset_ms.to_string(),
|
||||
media::Action::SetPosition { position_ms } => position_ms.to_string(),
|
||||
media::Action::Playlist { id } => id.clone(),
|
||||
_ => "—".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_parameter(action: &mut media::Action, text: &str) -> Result<(), String> {
|
||||
match action {
|
||||
media::Action::Seek { offset_ms } => {
|
||||
*offset_ms = text.parse().map_err(|_| "enter signed milliseconds")?
|
||||
}
|
||||
media::Action::SetPosition { position_ms } => {
|
||||
*position_ms = text.parse().map_err(|_| "enter nonnegative milliseconds")?
|
||||
}
|
||||
media::Action::Playlist { id } => *id = text.into(),
|
||||
_ => return Err("this action has no parameter".into()),
|
||||
}
|
||||
action.validate().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
impl MediaUi {
|
||||
pub fn modal(&self) -> bool {
|
||||
self.editor.is_some()
|
||||
}
|
||||
|
||||
pub fn refresh(&mut self, cfg: &ConfigurationSnapshot) {
|
||||
if let Some(Editor::Learn {
|
||||
started: true,
|
||||
seen,
|
||||
revision,
|
||||
entry,
|
||||
control,
|
||||
..
|
||||
}) = &mut self.editor
|
||||
{
|
||||
if cfg.learning.is_some() {
|
||||
*seen = true;
|
||||
} else if *seen
|
||||
|| (cfg.revision > *revision
|
||||
&& cfg.media_entries.iter().any(|e| {
|
||||
&e.id == entry
|
||||
&& e.controls
|
||||
.iter()
|
||||
.any(|c| &c.id == control && c.binding.is_some())
|
||||
}))
|
||||
{
|
||||
self.editor = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(&mut self, key: KeyCode, cfg: &ConfigurationSnapshot) -> Vec<Intent> {
|
||||
self.error = None;
|
||||
if let Some(editor) = self.editor.take() {
|
||||
return self.editor_key(editor, key, cfg);
|
||||
}
|
||||
let rows = media_rows(cfg);
|
||||
self.selected = self.selected.min(rows.len().saturating_sub(1));
|
||||
let target = rows.get(self.selected).copied();
|
||||
match key {
|
||||
KeyCode::Up => self.selected = self.selected.saturating_sub(1),
|
||||
KeyCode::Down => self.selected = (self.selected + 1).min(rows.len().saturating_sub(1)),
|
||||
KeyCode::Home => self.selected = 0,
|
||||
KeyCode::End => self.selected = rows.len().saturating_sub(1),
|
||||
KeyCode::Char('a' | 'A') => self.editor = Some(entry_editor(new_entry(cfg))),
|
||||
KeyCode::Char('e' | 'E') => {
|
||||
if let Some((entry, _)) = target {
|
||||
self.editor = Some(entry_editor(entry.clone()));
|
||||
}
|
||||
}
|
||||
KeyCode::Char('d' | 'D') => {
|
||||
if let Some((entry, _)) = target {
|
||||
self.editor = Some(Editor::Delete(entry.id.clone()));
|
||||
}
|
||||
}
|
||||
KeyCode::Char('s' | 'S') => return vec![Intent::Save],
|
||||
KeyCode::Char('l' | 'L') => {
|
||||
if let Some((entry, Some(control))) = target {
|
||||
if cfg.surfaces.is_empty() {
|
||||
self.error = Some("Add a MIDI device in Configuration first".into());
|
||||
} else {
|
||||
self.editor = Some(Editor::Learn {
|
||||
entry: entry.id.clone(),
|
||||
control: control.id.clone(),
|
||||
selected: 0,
|
||||
started: false,
|
||||
seen: false,
|
||||
revision: cfg.revision,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
if let Some((entry, Some(control))) = target {
|
||||
if cfg.dirty {
|
||||
self.error =
|
||||
Some("Save configuration before sending media commands".into());
|
||||
} else {
|
||||
match entry
|
||||
.selector
|
||||
.compile()
|
||||
.and_then(|m| m.resolve(&cfg.media_state.players))
|
||||
{
|
||||
Ok(player) if control.action.supported(player) => {
|
||||
return vec![Intent::Action(entry.id.clone(), control.id.clone())];
|
||||
}
|
||||
Ok(_) => self.error = Some("Unsupported by this player".into()),
|
||||
Err(e) => self.error = Some(e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn editor_key(
|
||||
&mut self,
|
||||
mut editor: Editor,
|
||||
key: KeyCode,
|
||||
cfg: &ConfigurationSnapshot,
|
||||
) -> Vec<Intent> {
|
||||
match &mut editor {
|
||||
Editor::Delete(id) => {
|
||||
if matches!(key, KeyCode::Char('y' | 'Y')) {
|
||||
return vec![Intent::Edit(ConfigurationEdit::RemoveMediaEntry {
|
||||
id: id.clone(),
|
||||
})];
|
||||
}
|
||||
if matches!(key, KeyCode::Esc | KeyCode::Char('n' | 'N')) {
|
||||
return vec![];
|
||||
}
|
||||
}
|
||||
Editor::Players { entry, selected } => {
|
||||
match key {
|
||||
KeyCode::Esc => {
|
||||
self.editor = Some(entry_editor(entry.clone()));
|
||||
return vec![];
|
||||
}
|
||||
KeyCode::Up => *selected = selected.saturating_sub(1),
|
||||
KeyCode::Down => {
|
||||
*selected =
|
||||
(*selected + 1).min(cfg.media_state.players.len().saturating_sub(1))
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
if let Some(player) = cfg.media_state.players.get(*selected) {
|
||||
// DesktopEntry is stable across instance-specific bus names; ambiguity remains an error.
|
||||
entry.selector = if let Some(desktop) =
|
||||
player.desktop_entry.as_ref().filter(|s| !s.is_empty())
|
||||
{
|
||||
media::PlayerSelector {
|
||||
field: media::PlayerField::DesktopEntry,
|
||||
pattern: desktop.clone(),
|
||||
regex: false,
|
||||
}
|
||||
} else {
|
||||
media::PlayerSelector {
|
||||
field: media::PlayerField::BusName,
|
||||
pattern: player.bus_name.clone(),
|
||||
regex: false,
|
||||
}
|
||||
};
|
||||
self.editor = Some(entry_editor(entry.clone()));
|
||||
return vec![];
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Editor::Learn {
|
||||
entry,
|
||||
control,
|
||||
selected,
|
||||
started,
|
||||
..
|
||||
} => match key {
|
||||
KeyCode::Esc => return vec![Intent::CancelLearn],
|
||||
KeyCode::Char('u' | 'U') => {
|
||||
return vec![
|
||||
Intent::CancelLearn,
|
||||
Intent::Edit(ConfigurationEdit::SetMediaBinding {
|
||||
entry: entry.clone(),
|
||||
control: control.clone(),
|
||||
binding: None,
|
||||
}),
|
||||
];
|
||||
}
|
||||
KeyCode::Up if !*started => *selected = selected.saturating_sub(1),
|
||||
KeyCode::Down if !*started => {
|
||||
*selected = (*selected + 1).min(cfg.surfaces.len().saturating_sub(1))
|
||||
}
|
||||
KeyCode::Enter if !*started => {
|
||||
if let Some(surface) = cfg.surfaces.get(*selected) {
|
||||
let intent =
|
||||
Intent::Learn(surface.id.clone(), entry.clone(), control.clone());
|
||||
*started = true;
|
||||
self.editor = Some(editor);
|
||||
return vec![intent];
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Editor::Entry { entry, row, text } => {
|
||||
if let Some(value) = text {
|
||||
match key {
|
||||
KeyCode::Esc => *text = None,
|
||||
KeyCode::Enter => {
|
||||
if *row == 0 {
|
||||
entry.label = value.clone();
|
||||
} else {
|
||||
entry.selector.pattern = value.clone();
|
||||
}
|
||||
*text = None;
|
||||
}
|
||||
KeyCode::Backspace => {
|
||||
value.pop();
|
||||
}
|
||||
KeyCode::Char(ch) if !ch.is_control() && value.len() < 256 => {
|
||||
value.push(ch)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
} else {
|
||||
match key {
|
||||
KeyCode::Esc => return vec![],
|
||||
KeyCode::Up => *row = row.saturating_sub(1),
|
||||
KeyCode::Down => *row = (*row + 1).min(5 + entry.controls.len()),
|
||||
KeyCode::Char('p' | 'P') => {
|
||||
self.editor = Some(Editor::Players {
|
||||
entry: entry.clone(),
|
||||
selected: 0,
|
||||
});
|
||||
return vec![];
|
||||
}
|
||||
KeyCode::Char('a' | 'A') if entry.controls.len() < 64 => {
|
||||
let id =
|
||||
unique_id("control", entry.controls.iter().map(|c| c.id.as_str()));
|
||||
entry.controls.push(media::Control {
|
||||
id,
|
||||
action: media::Action::PlayPause,
|
||||
binding: None,
|
||||
});
|
||||
*row = 5 + entry.controls.len();
|
||||
}
|
||||
KeyCode::Char('d' | 'D') if *row >= 6 => {
|
||||
let index = *row - 6;
|
||||
if index < entry.controls.len() {
|
||||
entry.controls.remove(index);
|
||||
}
|
||||
*row = (*row).min(5 + entry.controls.len());
|
||||
}
|
||||
KeyCode::Enter | KeyCode::Left | KeyCode::Right => match *row {
|
||||
0 => *text = Some(entry.label.clone()),
|
||||
1 => {
|
||||
entry.selector.field = match entry.selector.field {
|
||||
media::PlayerField::BusName => media::PlayerField::DesktopEntry,
|
||||
media::PlayerField::DesktopEntry => {
|
||||
media::PlayerField::Identity
|
||||
}
|
||||
media::PlayerField::Identity => media::PlayerField::BusName,
|
||||
}
|
||||
}
|
||||
2 => *text = Some(entry.selector.pattern.clone()),
|
||||
3 => entry.selector.regex = !entry.selector.regex,
|
||||
4 => entry.feedback_enabled = !entry.feedback_enabled,
|
||||
5 => match entry.validate() {
|
||||
Ok(()) => {
|
||||
return vec![Intent::Edit(ConfigurationEdit::SetMediaEntry {
|
||||
entry: entry.clone(),
|
||||
})];
|
||||
}
|
||||
Err(e) => self.error = Some(e.to_string()),
|
||||
},
|
||||
index => {
|
||||
self.editor = Some(Editor::Control {
|
||||
entry: entry.clone(),
|
||||
index: index - 6,
|
||||
row: 0,
|
||||
text: None,
|
||||
});
|
||||
return vec![];
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Editor::Control {
|
||||
entry,
|
||||
index,
|
||||
row,
|
||||
text,
|
||||
} => {
|
||||
let Some(control) = entry.controls.get_mut(*index) else {
|
||||
return vec![];
|
||||
};
|
||||
if let Some(value) = text {
|
||||
match key {
|
||||
KeyCode::Esc => *text = None,
|
||||
KeyCode::Backspace => {
|
||||
value.pop();
|
||||
}
|
||||
KeyCode::Char(ch) if !ch.is_control() && value.len() < 256 => {
|
||||
value.push(ch)
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
let result = if *row == 1 {
|
||||
set_parameter(&mut control.action, value)
|
||||
} else if let Some(feedback) =
|
||||
control.binding.as_mut().and_then(|b| b.feedback.as_mut())
|
||||
{
|
||||
value
|
||||
.parse::<u16>()
|
||||
.map_err(|_| "enter a MIDI number".to_string())
|
||||
.and_then(|n| {
|
||||
if (*row == 4 && (1..=16).contains(&n))
|
||||
|| (*row != 4 && n <= 127)
|
||||
{
|
||||
match *row {
|
||||
4 => feedback.message.channel = n,
|
||||
5 => feedback.message.number = n,
|
||||
6 => feedback.on = n as u8,
|
||||
7 => feedback.off = n as u8,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err("channel must be 1–16, data 0–127".into())
|
||||
}
|
||||
})
|
||||
} else {
|
||||
Err("learn an input and enable custom feedback first".into())
|
||||
};
|
||||
match result {
|
||||
Ok(()) => *text = None,
|
||||
Err(e) => self.error = Some(e),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
} else {
|
||||
match key {
|
||||
KeyCode::Esc => {
|
||||
self.editor = Some(entry_editor(entry.clone()));
|
||||
return vec![];
|
||||
}
|
||||
KeyCode::Up => *row = row.saturating_sub(1),
|
||||
KeyCode::Down => *row = (*row + 1).min(8),
|
||||
KeyCode::Enter | KeyCode::Left | KeyCode::Right => match *row {
|
||||
0 => cycle_action(&mut control.action, key != KeyCode::Left),
|
||||
1 => {
|
||||
if let media::Action::Playlist { id } = &mut control.action {
|
||||
if key != KeyCode::Enter {
|
||||
if let Ok(player) = entry
|
||||
.selector
|
||||
.compile()
|
||||
.and_then(|m| m.resolve(&cfg.media_state.players))
|
||||
{
|
||||
let i = player
|
||||
.playlists
|
||||
.iter()
|
||||
.position(|p| &p.id == id)
|
||||
.map_or(0, |i| {
|
||||
(i + 1) % player.playlists.len().max(1)
|
||||
});
|
||||
if let Some(playlist) = player.playlists.get(i) {
|
||||
*id = playlist.id.clone();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
*text = Some(id.clone());
|
||||
}
|
||||
} else {
|
||||
*text = Some(parameter(&control.action));
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
if let Some(binding) = &mut control.binding {
|
||||
binding.feedback = if binding.feedback.is_some() {
|
||||
None
|
||||
} else {
|
||||
Some(media::Feedback {
|
||||
message: binding.message.clone(),
|
||||
on: 127,
|
||||
off: 0,
|
||||
})
|
||||
};
|
||||
} else {
|
||||
self.error = Some(
|
||||
"Save entry, then L to learn this control first".into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
3 => {
|
||||
if let Some(feedback) =
|
||||
control.binding.as_mut().and_then(|b| b.feedback.as_mut())
|
||||
{
|
||||
feedback.message.kind = match feedback.message.kind {
|
||||
media::MessageKind::Note => media::MessageKind::Cc,
|
||||
media::MessageKind::Cc => media::MessageKind::Note,
|
||||
};
|
||||
}
|
||||
}
|
||||
4..=7 => {
|
||||
if let Some(f) =
|
||||
control.binding.as_ref().and_then(|b| b.feedback.as_ref())
|
||||
{
|
||||
*text = Some(match *row {
|
||||
4 => f.message.channel.to_string(),
|
||||
5 => f.message.number.to_string(),
|
||||
6 => f.on.to_string(),
|
||||
_ => f.off.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
8 => match entry.validate() {
|
||||
Ok(()) => {
|
||||
self.editor = Some(entry_editor(entry.clone()));
|
||||
return vec![];
|
||||
}
|
||||
Err(e) => self.error = Some(e.to_string()),
|
||||
},
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.editor = Some(editor);
|
||||
vec![]
|
||||
}
|
||||
|
||||
pub fn render(&self, area: Rect, buf: &mut Buffer, cfg: &ConfigurationSnapshot) {
|
||||
let rows = media_rows(cfg);
|
||||
let lines: Vec<String> = rows
|
||||
.iter()
|
||||
.map(|(entry, control)| {
|
||||
let player = entry
|
||||
.selector
|
||||
.compile()
|
||||
.and_then(|m| m.resolve(&cfg.media_state.players));
|
||||
if let Some(control) = control {
|
||||
let status = match &player {
|
||||
Ok(p) if !control.action.supported(p) => "unsupported",
|
||||
Ok(p) if control.action.feedback(Some(p)) => "active",
|
||||
Ok(_) => "ready",
|
||||
Err(_) => "offline/ambiguous",
|
||||
};
|
||||
let binding = control
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(|b| {
|
||||
format!(
|
||||
"{} {:?} ch{} #{}",
|
||||
b.surface, b.message.kind, b.message.channel, b.message.number
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| "unbound".into());
|
||||
format!(" {:?} [{status}] {binding}", control.action)
|
||||
} else {
|
||||
let status = player
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{:?} · {}",
|
||||
p.playback,
|
||||
p.identity.as_deref().unwrap_or(&p.bus_name)
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|e| e.to_string());
|
||||
format!(
|
||||
"{} · {:?}: {} · {status} · feedback {}",
|
||||
entry.label,
|
||||
entry.selector.field,
|
||||
entry.selector.pattern,
|
||||
if cfg.feedback_disabled || !entry.feedback_enabled {
|
||||
"off"
|
||||
} else {
|
||||
"on"
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let lines = if lines.is_empty() {
|
||||
vec!["No media entries. A adds one; players may be offline.".into()]
|
||||
} else {
|
||||
lines
|
||||
};
|
||||
draw_rows(
|
||||
area,
|
||||
buf,
|
||||
&lines,
|
||||
self.selected,
|
||||
"Media controls",
|
||||
self.error
|
||||
.as_deref()
|
||||
.or(cfg.media_state.error.as_deref())
|
||||
.unwrap_or("Enter send · L learn · A add · E edit · D delete · S save"),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn render_modal(&self, area: Rect, buf: &mut Buffer, cfg: &ConfigurationSnapshot) {
|
||||
let Some(editor) = &self.editor else {
|
||||
return;
|
||||
};
|
||||
let (title, rows, selected, text, help) = match editor {
|
||||
Editor::Entry { entry, row, text } => {
|
||||
let mut rows = vec![
|
||||
format!("Name: {}", entry.label),
|
||||
format!("Target field: {:?}", entry.selector.field),
|
||||
format!("Pattern: {}", entry.selector.pattern),
|
||||
format!("Regex: {}", entry.selector.regex),
|
||||
format!("Feedback: {}", entry.feedback_enabled),
|
||||
"Save and exit (draft)".into(),
|
||||
];
|
||||
rows.extend(
|
||||
entry
|
||||
.controls
|
||||
.iter()
|
||||
.map(|c| format!("Edit {}: {:?}", c.id, c.action)),
|
||||
);
|
||||
(
|
||||
"Edit media entry",
|
||||
rows,
|
||||
*row,
|
||||
text.as_deref(),
|
||||
"Enter edit · P discovered players · A add control · D remove control · Esc discard",
|
||||
)
|
||||
}
|
||||
Editor::Control {
|
||||
entry,
|
||||
index,
|
||||
row,
|
||||
text,
|
||||
} => {
|
||||
let Some(c) = entry.controls.get(*index) else {
|
||||
return;
|
||||
};
|
||||
let f = c.binding.as_ref().and_then(|b| b.feedback.as_ref());
|
||||
let playlist_name = match &c.action {
|
||||
media::Action::Playlist { id } => entry
|
||||
.selector
|
||||
.compile()
|
||||
.ok()
|
||||
.and_then(|m| m.resolve(&cfg.media_state.players).ok())
|
||||
.and_then(|p| p.playlists.iter().find(|v| &v.id == id))
|
||||
.map(|p| format!(" ({})", p.name))
|
||||
.unwrap_or_default(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let rows = vec![
|
||||
format!("Action: {:?}", c.action),
|
||||
format!(
|
||||
"Parameter (ms / playlist path): {}{}",
|
||||
parameter(&c.action),
|
||||
playlist_name
|
||||
),
|
||||
format!("Custom feedback: {}", f.is_some()),
|
||||
format!("Output kind: {:?}", f.map(|f| f.message.kind)),
|
||||
format!("Channel: {:?}", f.map(|f| f.message.channel)),
|
||||
format!("Number: {:?}", f.map(|f| f.message.number)),
|
||||
format!("On value/color: {:?}", f.map(|f| f.on)),
|
||||
format!("Off value/color: {:?}", f.map(|f| f.off)),
|
||||
"Save and return to entry".into(),
|
||||
];
|
||||
(
|
||||
"Edit media control",
|
||||
rows,
|
||||
*row,
|
||||
text.as_deref(),
|
||||
"←→ action / playlist · Enter edit · Esc return · Save entry to retain changes",
|
||||
)
|
||||
}
|
||||
Editor::Players { selected, .. } => (
|
||||
"Discovered players",
|
||||
cfg.media_state
|
||||
.players
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{} · {} · {}",
|
||||
p.identity.as_deref().unwrap_or("unknown"),
|
||||
p.desktop_entry.as_deref().unwrap_or("no desktop entry"),
|
||||
p.bus_name
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
*selected,
|
||||
None,
|
||||
"Enter select stable desktop entry or bus name · Esc manual input",
|
||||
),
|
||||
Editor::Delete(id) => (
|
||||
"Delete media entry?",
|
||||
vec![format!(
|
||||
"Delete {id} and all its controls? Y confirm / N cancel"
|
||||
)],
|
||||
0,
|
||||
None,
|
||||
"Change is a draft until configuration Save",
|
||||
),
|
||||
Editor::Learn {
|
||||
selected, started, ..
|
||||
} => (
|
||||
"Learn media MIDI input",
|
||||
if *started {
|
||||
vec![
|
||||
cfg.learning
|
||||
.clone()
|
||||
.unwrap_or_else(|| "Waiting for server / MIDI press…".into()),
|
||||
]
|
||||
} else {
|
||||
cfg.surfaces
|
||||
.iter()
|
||||
.map(|s| format!("{} ({})", s.label, s.id))
|
||||
.collect()
|
||||
},
|
||||
*selected,
|
||||
None,
|
||||
"Choose device, Enter learn · U unbind · Esc cancel · Save to activate",
|
||||
),
|
||||
};
|
||||
let modal = Rect::new(
|
||||
area.x + 1,
|
||||
area.y + 1,
|
||||
area.width.saturating_sub(2),
|
||||
area.height.saturating_sub(2),
|
||||
);
|
||||
Clear.render(modal, buf);
|
||||
let mut rows = rows;
|
||||
if let Some(text) = text
|
||||
&& let Some(row) = rows.get_mut(selected)
|
||||
{
|
||||
*row = format!("Editing: {text}▏ (Enter accept / Esc cancel)");
|
||||
}
|
||||
draw_rows(
|
||||
modal,
|
||||
buf,
|
||||
&rows,
|
||||
selected,
|
||||
title,
|
||||
self.error.as_deref().unwrap_or(help),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn media_rows(cfg: &ConfigurationSnapshot) -> Vec<(&media::Entry, Option<&media::Control>)> {
|
||||
cfg.media_entries
|
||||
.iter()
|
||||
.flat_map(|e| {
|
||||
std::iter::once((e, None)).chain(e.controls.iter().map(move |c| (e, Some(c))))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn draw_rows(
|
||||
area: Rect,
|
||||
buf: &mut Buffer,
|
||||
rows: &[String],
|
||||
selected: usize,
|
||||
title: &str,
|
||||
help: &str,
|
||||
) {
|
||||
let block = Block::bordered().title(title).title_bottom(help);
|
||||
let inner = block.inner(area);
|
||||
block.render(area, buf);
|
||||
let selected = selected.min(rows.len().saturating_sub(1));
|
||||
let start = selected.saturating_sub(usize::from(inner.height).saturating_sub(1));
|
||||
let lines: Vec<Line<'_>> = rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(start)
|
||||
.map(|(i, row)| {
|
||||
Line::from(format!("{} {row}", if i == selected { "›" } else { " " })).style(
|
||||
if i == selected {
|
||||
Style::default().reversed()
|
||||
} else {
|
||||
Style::default()
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Paragraph::new(lines).render(inner, buf);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn configured() -> ConfigurationSnapshot {
|
||||
let mut cfg = ConfigurationSnapshot::default();
|
||||
let mut entry = new_entry(&cfg);
|
||||
entry.selector.pattern = "org.mpris.MediaPlayer2.fixture".into();
|
||||
cfg.media_entries.push(entry);
|
||||
cfg.media_state.available = true;
|
||||
cfg.media_state.players.push(media::Player {
|
||||
bus_name: "org.mpris.MediaPlayer2.fixture".into(),
|
||||
desktop_entry: Some("fixture".into()),
|
||||
can_control: true,
|
||||
can_play: true,
|
||||
..media::Player::default()
|
||||
});
|
||||
cfg.surfaces.push(ConfiguredSurface {
|
||||
id: "buttons".into(),
|
||||
label: "Buttons".into(),
|
||||
});
|
||||
cfg
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_tab_is_advertised_by_server_even_with_no_players() {
|
||||
let client = DemoClient::default();
|
||||
let mut app = LiveTui::new(client).unwrap();
|
||||
app.handle_key_event(KeyEvent::from(KeyCode::Char('3')));
|
||||
assert_eq!(app.tab, Tab::Mixer);
|
||||
app.snapshot.configuration.media_state.available = true;
|
||||
app.handle_key_event(KeyEvent::from(KeyCode::Char('3')));
|
||||
assert_eq!(app.tab, Tab::Media);
|
||||
let mut buf = Buffer::empty(Rect::new(0, 0, 100, 30));
|
||||
(&app).render(buf.area, &mut buf);
|
||||
assert!(
|
||||
buf.content
|
||||
.iter()
|
||||
.map(|c| c.symbol())
|
||||
.collect::<String>()
|
||||
.contains("No media entries")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_require_unique_capable_saved_target() {
|
||||
let mut cfg = configured();
|
||||
let mut ui = MediaUi::default();
|
||||
ui.key(KeyCode::Down, &cfg);
|
||||
assert!(matches!(
|
||||
ui.key(KeyCode::Enter, &cfg).as_slice(),
|
||||
[Intent::Action(_, _)]
|
||||
));
|
||||
cfg.dirty = true;
|
||||
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
|
||||
cfg.dirty = false;
|
||||
cfg.media_state.players[0].can_play = false;
|
||||
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
|
||||
cfg.media_state
|
||||
.players
|
||||
.push(cfg.media_state.players[0].clone());
|
||||
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
|
||||
cfg.media_state.players.clear();
|
||||
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picker_prefers_desktop_entry_and_learn_unbinds_selected_control() {
|
||||
let cfg = configured();
|
||||
let mut ui = MediaUi::default();
|
||||
ui.key(KeyCode::Char('e'), &cfg);
|
||||
ui.key(KeyCode::Char('p'), &cfg);
|
||||
ui.key(KeyCode::Enter, &cfg);
|
||||
let Some(Editor::Entry { entry, .. }) = &ui.editor else {
|
||||
panic!("entry editor");
|
||||
};
|
||||
assert_eq!(entry.selector.field, media::PlayerField::DesktopEntry);
|
||||
assert_eq!(entry.selector.pattern, "fixture");
|
||||
ui.key(KeyCode::Esc, &cfg);
|
||||
ui.key(KeyCode::Down, &cfg);
|
||||
ui.key(KeyCode::Char('l'), &cfg);
|
||||
assert!(
|
||||
matches!(ui.key(KeyCode::Enter, &cfg).as_slice(), [Intent::Learn(surface, _, _)] if surface == "buttons")
|
||||
);
|
||||
assert!(matches!(
|
||||
ui.key(KeyCode::Char('u'), &cfg).as_slice(),
|
||||
[
|
||||
Intent::CancelLearn,
|
||||
Intent::Edit(ConfigurationEdit::SetMediaBinding { binding: None, .. })
|
||||
]
|
||||
));
|
||||
assert!(!ui.modal());
|
||||
ui.key(KeyCode::Char('d'), &cfg);
|
||||
assert!(ui.modal());
|
||||
assert!(matches!(
|
||||
ui.key(KeyCode::Char('y'), &cfg).as_slice(),
|
||||
[Intent::Edit(ConfigurationEdit::RemoveMediaEntry { .. })]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn learn_completion_can_arrive_before_learning_snapshot() {
|
||||
let mut cfg = configured();
|
||||
let mut ui = MediaUi::default();
|
||||
ui.key(KeyCode::Down, &cfg);
|
||||
ui.key(KeyCode::Char('l'), &cfg);
|
||||
ui.key(KeyCode::Enter, &cfg);
|
||||
cfg.media_entries[0].controls[0].binding = Some(media::Binding {
|
||||
surface: "buttons".into(),
|
||||
message: media::Message {
|
||||
kind: media::MessageKind::Note,
|
||||
channel: 1,
|
||||
number: 1,
|
||||
},
|
||||
feedback: None,
|
||||
});
|
||||
cfg.revision += 1;
|
||||
ui.refresh(&cfg);
|
||||
assert!(!ui.modal());
|
||||
}
|
||||
#[test]
|
||||
fn invalid_selector_cannot_leave_editor_and_save_is_explicit() {
|
||||
let mut ui = MediaUi::default();
|
||||
let cfg = ConfigurationSnapshot::default();
|
||||
ui.key(KeyCode::Char('a'), &cfg);
|
||||
assert!(ui.modal());
|
||||
if let Some(Editor::Entry { entry, row, .. }) = &mut ui.editor {
|
||||
entry.selector.pattern = "[".into();
|
||||
entry.selector.regex = true;
|
||||
*row = 5;
|
||||
}
|
||||
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
|
||||
assert!(ui.modal());
|
||||
assert!(ui.error.is_some());
|
||||
if let Some(Editor::Entry { entry, .. }) = &mut ui.editor {
|
||||
entry.selector.pattern = "qbz".into();
|
||||
}
|
||||
assert!(matches!(
|
||||
ui.key(KeyCode::Enter, &cfg).as_slice(),
|
||||
[Intent::Edit(ConfigurationEdit::SetMediaEntry { .. })]
|
||||
));
|
||||
assert!(!ui.modal());
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue