feat: bootstrap controllers from MIDI discovery

Adopt a sole MIDI input when creating a managed profile, publish other unclaimed inputs to Config, and let the user add them as durable surfaces. Legacy empty profiles can add a safe Master fader, then Save and use the existing MIDI Learn flow without editing TOML.

Tests: cargo test --workspace --all-targets --all-features; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; default/no-default/midir/pulse cargo checks
This commit is contained in:
Dandaedre 2026-10-16 19:05:29 +02:00
parent e5239e3243
commit c1f3377914
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
14 changed files with 689 additions and 13 deletions

View File

@ -440,6 +440,13 @@ backend IDs/errors. The compact mixer status line distinguishes connected,
connecting, missing, ambiguous, and failed devices, adding a connect/select
action where the user can resolve the state.
Unclaimed MIDI input ports are also published with their current backend ID,
stable port name, and available USB identity. Config can add one as a durable
surface draft; the first added surface becomes the default controller, and Save
rebuilds the MIDI runtime before Learn is enabled. On creation of a missing
managed profile, exactly one discovered input is adopted automatically. No
choice is guessed when discovery returns zero or multiple inputs.
Terminal restoration is guarded around all fallible client/run work after
terminal initialization. The restore action is injectable for failure-path
tests; client and transport diagnostics stay in the rendered status area rather

View File

@ -119,6 +119,61 @@ pickup_tolerance = 0.02
})
}
/// Adds a discovered MIDI input as a durable control surface.
#[allow(clippy::too_many_arguments)]
pub fn add_surface(
&mut self,
id: &str,
label: &str,
input_port: &str,
output_port: Option<&str>,
usb_vendor_id: Option<&str>,
usb_product_id: Option<&str>,
usb_serial: Option<&str>,
usb_path: Option<&str>,
manual_backend_id: Option<&str>,
) -> Result<(), ConfigError> {
self.transaction(|document| {
if document.get("surfaces").is_none() {
document["surfaces"] = Item::ArrayOfTables(ArrayOfTables::new());
}
let surfaces = document
.get_mut("surfaces")
.and_then(Item::as_array_of_tables_mut)
.ok_or_else(|| ConfigError::validation("surfaces", "must be an array of tables"))?;
let mut table = Table::new();
table["id"] = value(id);
table["label"] = value(label);
table["input_port"] = value(input_port);
if let Some(output_port) = output_port {
table["output_port"] = value(output_port);
}
if let Some(vendor) = usb_vendor_id {
table["usb_vendor_id"] = value(vendor);
}
if let Some(product) = usb_product_id {
table["usb_product_id"] = value(product);
}
if let Some(serial) = usb_serial {
table["usb_serial"] = value(serial);
}
if let Some(path) = usb_path {
table["usb_path"] = value(path);
}
if let Some(backend_id) = manual_backend_id {
table["manual_backend_id"] = value(backend_id);
}
table["identity_policy"] = value(if manual_backend_id.is_some() {
"manual"
} else {
"require_unique"
});
table["motorized"] = value(false);
surfaces.push(table);
Ok(())
})
}
/// Changes one application's display label without rebuilding its table.
pub fn set_application_label(
&mut self,

View File

@ -5,6 +5,34 @@ use fader_config::{
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
#[test]
fn draft_adds_a_discovered_midi_surface_with_durable_identity() {
let mut draft = ProfileDocument::empty("default").unwrap();
draft
.add_surface(
"apc-mini",
"APC MINI",
"APC MINI:APC MINI MIDI 1",
Some("APC MINI:APC MINI MIDI 1"),
Some("09e8"),
Some("0028"),
Some("Ver00.10"),
Some("pci-0000:00:14.0-usb-0:1"),
Some("36:0"),
)
.unwrap();
draft.set_default_controller(Some("apc-mini")).unwrap();
let profile = draft.preview().unwrap();
let surface = &profile.surfaces()[0];
assert_eq!(surface.id(), "apc-mini");
assert_eq!(surface.input_port(), "APC MINI:APC MINI MIDI 1");
assert_eq!(surface.output_port(), Some("APC MINI:APC MINI MIDI 1"));
assert_eq!(surface.usb_serial(), Some("Ver00.10"));
assert_eq!(surface.manual_backend_id(), Some("36:0"));
assert_eq!(profile.default_controller(), Some("apc-mini"));
}
#[test]
fn draft_creates_an_application_group_and_fader_as_valid_toml() {
let mut draft = ProfileDocument::parse(PROFILE).unwrap();

View File

@ -45,9 +45,18 @@ Without `--config`, fader_master uses the XDG layout:
when they are absolute. A runtime directory is required for the standalone
local socket; no shared `/tmp` fallback is invented.
On first managed startup, a valid empty `default` profile and active selection
are created. If the active selection names a missing managed profile, an empty
profile with that validated ID is recreated. An explicitly supplied missing
On first managed startup, a valid `default` profile and active selection are
created. The profile starts with a safe Master-output fader. If exactly one MIDI
input is visible, its port and available USB identity are adopted as the default
controller; zero or multiple inputs are left for the user to choose. Config
lists unconfigured inputs under **Detected MIDI ports**: open one, choose **Add
as controller**, Save, then edit the Master fader and use Learn MIDI for volume
and mute. This is enough to get a new installation working without editing TOML.
Profiles created by an older version with no faders expose **Add Master output
fader** in Config and can use the same setup path.
If the active selection names a missing managed profile, the same first-run
profile is recreated with that validated ID. An explicitly supplied missing
`--config` path remains an error so a typo cannot silently create a new file.
Switch an existing server to another managed profile with:

View File

@ -15,7 +15,7 @@ use fader_config::{
upgrade_profile,
};
use fader_core::Gain;
use midi::{LinuxIdentityCatalog, MidiInputCatalog};
use midi::{LinuxIdentityCatalog, MidiInputCatalog, PortIdentity};
use volume_lib::{AudioBackend, CompiledAdapterProbe, TargetRequirements, select_adapter};
use crate::{
@ -238,9 +238,83 @@ fn initialize_missing_profile(path: &Path, id: &str) -> Result<()> {
.with_context(|| format!("could not inspect profile {}", path.display()));
}
}
let source = ProfileDocument::empty(id)?.finish()?;
let mut document = ProfileDocument::empty(id)?;
if let Some(identity) = discover_single_midi_surface() {
add_discovered_surface(&mut document, &identity)?;
}
let source = document.finish()?;
AtomicFile::write(path, source.as_bytes())
.with_context(|| format!("could not initialize empty profile {}", path.display()))
.with_context(|| format!("could not initialize profile {}", path.display()))
}
fn discover_single_midi_surface() -> Option<PortIdentity> {
let catalog = MidiInputCatalog::new("fader_master first-run discovery").ok()?;
let ports = catalog.ports().ok()?;
if ports.len() != 1 {
return None;
}
let identities = LinuxIdentityCatalog::new().ok()?;
identities.inspect(&ports[0]).ok()
}
fn add_discovered_surface(document: &mut ProfileDocument, identity: &PortIdentity) -> Result<()> {
let name = stable_midi_port_name(&identity.name);
let id = midi_surface_id(name);
let usb = identity.usb.as_ref();
document.add_surface(
&id,
name,
name,
Some(name),
usb.map(|value| value.vendor_id.as_str()),
usb.map(|value| value.product_id.as_str()),
usb.and_then(|value| value.serial.as_deref()),
usb.and_then(|value| value.path.as_deref()),
Some(&identity.backend_id),
)?;
document.set_default_controller(Some(&id))?;
Ok(())
}
fn stable_midi_port_name(name: &str) -> &str {
let Some((prefix, suffix)) = name.rsplit_once(' ') else {
return name;
};
let Some((client, port)) = suffix.split_once(':') else {
return name;
};
if !client.is_empty()
&& !port.is_empty()
&& client.bytes().all(|byte| byte.is_ascii_digit())
&& port.bytes().all(|byte| byte.is_ascii_digit())
{
prefix
} else {
name
}
}
fn midi_surface_id(name: &str) -> String {
let mut id = String::new();
let mut separator = false;
for character in name.chars() {
if character.is_ascii_alphanumeric() {
if separator && !id.is_empty() && id.len() < 63 {
id.push('-');
}
separator = false;
if id.len() < 64 {
id.push(character.to_ascii_lowercase());
}
} else {
separator = true;
}
}
if id.is_empty() {
"midi-controller".to_owned()
} else {
id
}
}
fn build_server(
@ -393,9 +467,47 @@ mod tests {
use std::{cell::Cell, fs};
use fader_config::{ActiveConfig, ProfileDocument, XdgEnvironment, XdgPaths};
use midi::{PortIdentity, UsbDeviceIdentity};
use tempfile::tempdir;
use super::{load_profile_document, resolve_managed_profile, start_if_missing};
use super::{
add_discovered_surface, load_profile_document, midi_surface_id, resolve_managed_profile,
stable_midi_port_name, start_if_missing,
};
#[test]
fn first_run_guess_uses_one_discovered_controller_and_durable_identity() {
let mut document = ProfileDocument::empty("default").unwrap();
add_discovered_surface(
&mut document,
&PortIdentity {
backend_id: "36:0".to_owned(),
name: "APC MINI:APC MINI MIDI 1 36:0".to_owned(),
usb: Some(UsbDeviceIdentity {
vendor_id: "09e8".to_owned(),
product_id: "0028".to_owned(),
serial: Some("Ver00.10".to_owned()),
path: Some("pci-usb-0:1".to_owned()),
}),
},
)
.unwrap();
let profile = document.preview().unwrap();
assert_eq!(
profile.default_controller(),
Some("apc-mini-apc-mini-midi-1")
);
assert_eq!(profile.surfaces()[0].label(), "APC MINI:APC MINI MIDI 1");
assert_eq!(profile.surfaces()[0].usb_serial(), Some("Ver00.10"));
assert_eq!(profile.surfaces()[0].manual_backend_id(), Some("36:0"));
assert_eq!(profile.faders()[0].id(), "master-fader");
assert_eq!(
stable_midi_port_name("Controller Port 24:3"),
"Controller Port"
);
assert_eq!(midi_surface_id(" !!! "), "midi-controller");
}
#[test]
fn combined_mode_only_starts_a_server_when_probe_did_not_find_one() {

View File

@ -71,6 +71,32 @@ impl ConfigurationEditor {
});
}
match edit {
ConfigurationEdit::AddSurface {
id,
label,
input_port,
output_port,
usb_vendor_id,
usb_product_id,
usb_serial,
usb_path,
manual_backend_id,
} => {
self.document.add_surface(
&id,
&label,
&input_port,
output_port.as_deref(),
usb_vendor_id.as_deref(),
usb_product_id.as_deref(),
usb_serial.as_deref(),
usb_path.as_deref(),
manual_backend_id.as_deref(),
)?;
if self.document.preview()?.default_controller().is_none() {
self.document.set_default_controller(Some(&id))?;
}
}
ConfigurationEdit::AddApplication {
id,
label,
@ -337,6 +363,36 @@ mod tests {
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
#[test]
fn discovered_surface_edit_bootstraps_the_default_controller() {
let root = tempdir().unwrap();
let path = root.path().join("default.toml");
let document = ProfileDocument::empty("default").unwrap();
fs::write(&path, document.source()).unwrap();
let mut editor = ConfigurationEditor::new(document, path);
let profile = editor
.apply(
0,
ConfigurationEdit::AddSurface {
id: "apc-mini".into(),
label: "APC MINI".into(),
input_port: "APC MINI:APC MINI MIDI 1".into(),
output_port: Some("APC MINI:APC MINI MIDI 1".into()),
usb_vendor_id: Some("09e8".into()),
usb_product_id: Some("0028".into()),
usb_serial: Some("Ver00.10".into()),
usb_path: None,
manual_backend_id: Some("36:0".into()),
},
)
.unwrap();
assert_eq!(profile.surfaces()[0].id(), "apc-mini");
assert_eq!(profile.default_controller(), Some("apc-mini"));
assert!(editor.dirty());
}
#[test]
fn accepted_edits_advance_revision_and_stale_or_invalid_edits_do_not() {
let root = tempdir().unwrap();

View File

@ -3,7 +3,7 @@ use std::io::{self, Read, Write};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;
pub const PROTOCOL_VERSION: u16 = 16;
pub const PROTOCOL_VERSION: u16 = 17;
pub const MAX_FRAME_BYTES: usize = 64 * 1024;
/// Kind of mixer object addressed by a client.
@ -74,6 +74,17 @@ pub enum RequestCommand {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "operation", rename_all = "snake_case")]
pub enum ConfigurationEdit {
AddSurface {
id: String,
label: String,
input_port: String,
output_port: Option<String>,
usb_vendor_id: Option<String>,
usb_product_id: Option<String>,
usb_serial: Option<String>,
usb_path: Option<String>,
manual_backend_id: Option<String>,
},
AddApplication {
id: String,
label: String,
@ -202,6 +213,8 @@ pub struct MixerSnapshot {
pub status: String,
pub objects: Vec<MixerObject>,
pub devices: Vec<MidiDevice>,
#[serde(default)]
pub discovered_midi_ports: Vec<DiscoveredMidiPort>,
pub configuration: ConfigurationSnapshot,
}
@ -314,6 +327,16 @@ pub struct MidiDevice {
pub error: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DiscoveredMidiPort {
pub backend_id: String,
pub name: String,
pub usb_vendor_id: Option<String>,
pub usb_product_id: Option<String>,
pub usb_serial: Option<String>,
pub usb_path: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct MixerObject {
pub object: MixerObjectKey,

View File

@ -64,6 +64,7 @@ pub struct LiveMixerState {
faders: BTreeMap<FaderId, ConfiguredFader>,
pickups: BTreeMap<(SurfaceId, FaderId), Pickup>,
devices: Vec<MidiDevice>,
discovered_midi_ports: Vec<crate::ipc::DiscoveredMidiPort>,
write_ceiling: Gain,
backend: String,
status: String,
@ -340,6 +341,7 @@ impl LiveMixerState {
faders,
pickups,
devices: Vec::new(),
discovered_midi_ports: Vec::new(),
write_ceiling,
backend: backend.into(),
status: "connecting".to_owned(),
@ -481,6 +483,7 @@ impl LiveMixerState {
status: self.status.clone(),
objects,
devices: self.devices.clone(),
discovered_midi_ports: self.discovered_midi_ports.clone(),
configuration: self.configuration.clone(),
}
}
@ -506,6 +509,10 @@ impl LiveMixerState {
self.devices = devices;
}
pub fn set_discovered_midi_ports(&mut self, ports: Vec<crate::ipc::DiscoveredMidiPort>) {
self.discovered_midi_ports = ports;
}
pub(crate) fn set_configuration(&mut self, configuration: ConfigurationSnapshot) {
self.configuration = configuration;
}
@ -523,6 +530,10 @@ impl LiveMixerState {
std::mem::swap(&mut replacement.output, &mut self.output);
std::mem::swap(&mut replacement.status, &mut self.status);
std::mem::swap(&mut replacement.devices, &mut self.devices);
std::mem::swap(
&mut replacement.discovered_midi_ports,
&mut self.discovered_midi_ports,
);
replacement.configuration = self.configuration.clone();
replacement.revision_offset =
next_revision.saturating_sub(replacement.reducer.revision().get());

View File

@ -312,6 +312,8 @@ impl LocalServer {
self.flush_dispatch();
self.midi.sync_feedback(&self.mixer.snapshot());
self.mixer.set_devices(self.midi.snapshot());
self.mixer
.set_discovered_midi_ports(self.midi.discovered_ports());
while let Some(mut client) = self.listener.accept()? {
let _ = client.set_read_timeout(Some(SERVER_CLIENT_TIMEOUT));
let _ = client.set_write_timeout(Some(SERVER_CLIENT_TIMEOUT));

View File

@ -12,10 +12,10 @@ use fader_core::{
use midi::{
ButtonEdge, DeviceMatch, LinuxIdentityCatalog, MidiInputCatalog, MidiInputConnection,
MidiInputEvent, MidiIntent, MidiMessage, MidiOutputCatalog, MidiOutputConnection, MidiRouter,
SurfaceAction, SurfaceAssignment, SurfaceLifecycle, SurfaceStatus,
PortIdentity, SurfaceAction, SurfaceAssignment, SurfaceLifecycle, SurfaceStatus,
};
use crate::ipc::{MidiDevice, MixerObjectKey, MixerObjectKind, MixerSnapshot};
use crate::ipc::{DiscoveredMidiPort, MidiDevice, MixerObjectKey, MixerObjectKind, MixerSnapshot};
const SCAN_INTERVAL: Duration = Duration::from_secs(1);
const EVENT_CAPACITY: usize = 256;
@ -29,6 +29,7 @@ pub struct MidiRuntime {
output_connections: BTreeMap<SurfaceId, MidiOutputConnection>,
output_backend_ids: BTreeMap<SurfaceId, String>,
output_errors: BTreeMap<SurfaceId, String>,
discovered_ports: Vec<PortIdentity>,
sender: SyncSender<MidiInputEvent>,
receiver: Receiver<MidiInputEvent>,
last_scan: Option<Instant>,
@ -254,6 +255,7 @@ impl MidiRuntime {
output_connections: BTreeMap::new(),
output_backend_ids: BTreeMap::new(),
output_errors: BTreeMap::new(),
discovered_ports: Vec::new(),
sender,
receiver,
last_scan: None,
@ -398,6 +400,21 @@ impl MidiRuntime {
.collect()
}
#[must_use]
pub fn discovered_ports(&self) -> Vec<DiscoveredMidiPort> {
self.discovered_ports
.iter()
.map(|port| DiscoveredMidiPort {
backend_id: port.backend_id.clone(),
name: stable_port_name(&port.name).to_owned(),
usb_vendor_id: port.usb.as_ref().map(|usb| usb.vendor_id.clone()),
usb_product_id: port.usb.as_ref().map(|usb| usb.product_id.clone()),
usb_serial: port.usb.as_ref().and_then(|usb| usb.serial.clone()),
usb_path: port.usb.as_ref().and_then(|usb| usb.path.clone()),
})
.collect()
}
fn scan(&mut self) {
let input_error = self.discover_and_reconcile().err();
if let Err(error) = self.discover_and_reconcile_outputs() {
@ -431,6 +448,7 @@ impl MidiRuntime {
}
}
}
self.discovered_ports = unclaimed_ports(visible, &self.lifecycle);
Ok(())
}
@ -571,6 +589,22 @@ impl MidiRuntime {
}
}
fn unclaimed_ports(visible: Vec<PortIdentity>, lifecycle: &SurfaceLifecycle) -> Vec<PortIdentity> {
let claimed = lifecycle
.statuses()
.filter_map(|(_, status)| match status {
SurfaceStatus::Connecting { backend_id, .. }
| SurfaceStatus::Connected { backend_id, .. }
| SurfaceStatus::Error { backend_id, .. } => Some(backend_id),
SurfaceStatus::Missing | SurfaceStatus::Ambiguous { .. } => None,
})
.collect::<BTreeSet<_>>();
visible
.into_iter()
.filter(|port| !claimed.contains(&port.backend_id))
.collect()
}
fn stable_port_name(name: &str) -> &str {
let Some((prefix, suffix)) = name.rsplit_once(' ') else {
return name;
@ -597,6 +631,41 @@ mod tests {
use fader_core::{MidiChannel, MidiData};
use midi::{ButtonEdge, MidiMessage};
#[test]
fn discovery_exposes_only_ports_not_claimed_by_configured_surfaces() {
let surface = SurfaceId::new("configured").unwrap();
let mut lifecycle = SurfaceLifecycle::new([SurfaceAssignment {
surface,
expected: DeviceMatch {
port_name: "Configured Controller".into(),
vendor_id: None,
product_id: None,
serial: None,
path: None,
},
manual_backend_id: None,
}])
.unwrap();
let visible = vec![
PortIdentity {
backend_id: "20:0".into(),
name: "Configured Controller".into(),
usb: None,
},
PortIdentity {
backend_id: "36:0".into(),
name: "New Controller".into(),
usb: None,
},
];
lifecycle.reconcile(&visible);
let available = unclaimed_ports(visible, &lifecycle);
assert_eq!(available.len(), 1);
assert_eq!(available[0].backend_id, "36:0");
}
#[test]
fn configured_surfaces_exist_as_missing_before_native_discovery() {
let profile =

View File

@ -89,6 +89,18 @@ impl IpcMixerClient {
error: device.error,
})
.collect(),
discovered_midi_ports: snapshot
.discovered_midi_ports
.into_iter()
.map(|port| tui::DiscoveredMidiPort {
backend_id: port.backend_id,
name: port.name,
usb_vendor_id: port.usb_vendor_id,
usb_product_id: port.usb_product_id,
usb_serial: port.usb_serial,
usb_path: port.usb_path,
})
.collect(),
configuration: tui::ConfigurationSnapshot {
revision: snapshot.configuration.revision,
dirty: snapshot.configuration.dirty,
@ -296,6 +308,27 @@ impl MixerClient for IpcMixerClient {
fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEdit {
use crate::ipc::ConfigurationEdit as IpcEdit;
match edit {
TuiConfigurationEdit::AddSurface {
id,
label,
input_port,
output_port,
usb_vendor_id,
usb_product_id,
usb_serial,
usb_path,
manual_backend_id,
} => IpcEdit::AddSurface {
id,
label,
input_port,
output_port,
usb_vendor_id,
usb_product_id,
usb_serial,
usb_path,
manual_backend_id,
},
TuiConfigurationEdit::Application {
existing,
id,

View File

@ -484,6 +484,11 @@ Dependencies: all required feature milestones; hardware-only ALSA remains an exp
an exact `.v0.bak` backup, and atomic replacement.
New managed profiles include a safe default-output fader so first-run setup
has an editable mixer target before any application or controller is known.
Exactly one discoverable MIDI input is adopted with its durable identity;
ambiguous first-run discovery remains unchanged. Unconfigured inputs are
otherwise listed in Config and can be added, saved, and assigned through the
existing MIDI Learn workflow without editing TOML. Config also repairs legacy
empty profiles by offering a safe Master-output fader.
- [ ] **M12.4 Release gates:** all workspace/default/feature/MSRV checks, reproducible lockfile, license review and dependency advisory review using maintained tooling selected at implementation time. Measure/control latency under multi-surface load and publish the tested envelope.
## User requirement coverage

View File

@ -133,6 +133,7 @@ fn snapshot(mixer_orientation: MixerOrientation) -> MixerSnapshot {
backend_id: Some("24:0".to_owned()),
error: None,
}],
discovered_midi_ports: Vec::new(),
configuration: ConfigurationSnapshot {
revision: 7,
dirty: false,

View File

@ -78,6 +78,16 @@ pub struct MidiDevice {
pub error: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DiscoveredMidiPort {
pub backend_id: String,
pub name: String,
pub usb_vendor_id: Option<String>,
pub usb_product_id: Option<String>,
pub usb_serial: Option<String>,
pub usb_path: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ConfigurationSnapshot {
pub revision: u64,
@ -221,6 +231,17 @@ pub struct ConfiguredBinding {
#[derive(Clone, Debug, PartialEq)]
pub enum ConfigurationEdit {
AddSurface {
id: String,
label: String,
input_port: String,
output_port: Option<String>,
usb_vendor_id: Option<String>,
usb_product_id: Option<String>,
usb_serial: Option<String>,
usb_path: Option<String>,
manual_backend_id: Option<String>,
},
Application {
existing: bool,
id: String,
@ -309,6 +330,7 @@ pub struct MixerSnapshot {
pub error: Option<String>,
pub items: Vec<MixerItem>,
pub devices: Vec<MidiDevice>,
pub discovered_midi_ports: Vec<DiscoveredMidiPort>,
pub configuration: ConfigurationSnapshot,
}
@ -423,6 +445,7 @@ impl BufferedMixerClient {
error: None,
items: Vec::new(),
devices: Vec::new(),
discovered_midi_ports: Vec::new(),
configuration: ConfigurationSnapshot::default(),
};
let shared = Arc::new((
@ -908,9 +931,11 @@ enum SettingsRow {
DefaultController,
HiddenFaders { count: usize },
ActiveProfile,
AddMasterFader,
CancelMidiLearn,
Save,
MidiDevice { id: String },
DiscoveredMidiPort { backend_id: String },
}
#[derive(Clone, Debug, Eq, PartialEq)]
@ -1464,6 +1489,9 @@ impl<C: MixerClient> LiveTui<C> {
if self.snapshot.configuration.learning.is_some() {
rows.push(SettingsRow::CancelMidiLearn);
}
if self.snapshot.configuration.faders.is_empty() {
rows.push(SettingsRow::AddMasterFader);
}
rows.push(SettingsRow::Save);
rows.extend(
self.snapshot
@ -1473,6 +1501,11 @@ impl<C: MixerClient> LiveTui<C> {
id: device.id.clone(),
}),
);
rows.extend(self.snapshot.discovered_midi_ports.iter().map(|port| {
SettingsRow::DiscoveredMidiPort {
backend_id: port.backend_id.clone(),
}
}));
rows
}
@ -1559,10 +1592,25 @@ impl<C: MixerClient> LiveTui<C> {
self.profile_picker = Some(ProfilePicker { selected });
}
SettingsRow::CancelMidiLearn if forward => self.cancel_midi_learn(),
SettingsRow::AddMasterFader if forward => {
self.apply_layout_edit(ConfigurationEdit::Fader {
existing: false,
id: "master-fader".to_owned(),
target: MixerObjectId {
kind: MixerObjectKind::Output,
id: "default".to_owned(),
},
pickup: true,
pickup_tolerance: 0.02,
});
}
SettingsRow::Save if forward => self.save_configuration(),
SettingsRow::MidiDevice { id } if forward => {
self.midi_device_details = Some(id);
}
SettingsRow::DiscoveredMidiPort { backend_id } if forward => {
self.midi_device_details = Some(backend_id);
}
_ => {}
}
}
@ -1669,6 +1717,34 @@ impl<C: MixerClient> LiveTui<C> {
let Some(id) = self.midi_device_details.clone() else {
return;
};
if let Some(port) = self
.snapshot
.discovered_midi_ports
.iter()
.find(|port| port.backend_id == id)
.cloned()
{
match code {
KeyCode::Esc => self.midi_device_details = None,
KeyCode::Enter => {
let surface_id = unique_surface_id(&port.name, &self.snapshot.devices);
self.apply_layout_edit(ConfigurationEdit::AddSurface {
id: surface_id,
label: port.name.clone(),
input_port: port.name.clone(),
output_port: Some(port.name),
usb_vendor_id: port.usb_vendor_id,
usb_product_id: port.usb_product_id,
usb_serial: port.usb_serial,
usb_path: port.usb_path,
manual_backend_id: Some(port.backend_id),
});
self.midi_device_details = None;
}
_ => {}
}
return;
}
if !self.snapshot.devices.iter().any(|device| device.id == id) {
if code == KeyCode::Esc {
self.midi_device_details = None;
@ -2607,6 +2683,40 @@ fn unique_separator_id(label: &str, layout: &[MixerLayoutEntry]) -> String {
.unwrap_or_else(|| "separator-id-exhausted".to_owned())
}
fn unique_surface_id(name: &str, devices: &[MidiDevice]) -> String {
let base = name
.chars()
.filter_map(|character| {
if character.is_ascii_alphanumeric() {
Some(character.to_ascii_lowercase())
} else if character.is_ascii_whitespace() || matches!(character, '-' | '_' | ':') {
Some('-')
} else {
None
}
})
.take(56)
.collect::<String>()
.trim_matches('-')
.to_owned();
let base = if base.is_empty() {
"midi-controller".to_owned()
} else {
base
};
let used = devices
.iter()
.map(|device| device.id.as_str())
.collect::<std::collections::BTreeSet<_>>();
if !used.contains(base.as_str()) {
return base;
}
(2..)
.map(|suffix| format!("{base}-{suffix}"))
.find(|candidate| !used.contains(candidate.as_str()))
.unwrap_or_else(|| "midi-controller-id-exhausted".to_owned())
}
fn centered_rect(area: Rect, width: u16, height: u16) -> Rect {
let width = width.min(area.width);
let height = height.min(area.height);
@ -3069,6 +3179,43 @@ impl<C: MixerClient> LiveTui<C> {
return;
};
let theme = self.theme.palette();
if let Some(port) = self
.snapshot
.discovered_midi_ports
.iter()
.find(|port| &port.backend_id == id)
{
let usb = match (&port.usb_vendor_id, &port.usb_product_id) {
(Some(vendor), Some(product)) => format!("{vendor}:{product}"),
_ => "Unavailable".to_owned(),
};
let popup = centered_rect(area, 68, 10);
Clear.render(popup, buf);
Paragraph::new(Text::from(vec![
Line::from(port.name.as_str()).bold(),
Line::from("Not configured"),
Line::from(format!("Backend port {}", port.backend_id)),
Line::from(format!("USB identity {usb}")),
Line::from(format!(
"Serial {}",
port.usb_serial.as_deref().unwrap_or("Unavailable")
)),
Line::from(""),
Line::from("▶ Add as controller [Enter]")
.fg(theme.accent)
.bold(),
]))
.block(
Block::bordered()
.title(" Detected MIDI port ".fg(theme.accent).bold())
.title_bottom(" Enter add · 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);
return;
}
let Some(device) = self.snapshot.devices.iter().find(|device| &device.id == id) else {
return;
};
@ -3208,7 +3355,10 @@ impl<C: MixerClient> LiveTui<C> {
let settings_rows = self.settings_rows();
let mut selected_line = None;
for (index, row) in settings_rows.iter().enumerate() {
if matches!(row, SettingsRow::MidiDevice { .. }) {
if matches!(
row,
SettingsRow::MidiDevice { .. } | SettingsRow::DiscoveredMidiPort { .. }
) {
continue;
}
let marker = if index == self.settings_selected {
@ -3242,6 +3392,7 @@ impl<C: MixerClient> LiveTui<C> {
format!("Active profile {} [Enter]", config.profile_id)
}
SettingsRow::CancelMidiLearn => "Cancel MIDI learn [Enter]".to_owned(),
SettingsRow::AddMasterFader => "Add Master output fader [Enter]".to_owned(),
SettingsRow::Save => format!(
"Save changes {}",
if config.dirty {
@ -3250,7 +3401,9 @@ impl<C: MixerClient> LiveTui<C> {
"already saved"
}
),
SettingsRow::MidiDevice { .. } => continue,
SettingsRow::MidiDevice { .. } | SettingsRow::DiscoveredMidiPort { .. } => {
continue;
}
};
if index == self.settings_selected {
selected_line = Some(lines.len());
@ -3295,6 +3448,39 @@ impl<C: MixerClient> LiveTui<C> {
);
}
}
if !self.snapshot.discovered_midi_ports.is_empty() {
lines.push(Line::from(""));
lines.push(Line::from("Detected MIDI ports").fg(theme.accent).bold());
for (index, row) in settings_rows.iter().enumerate() {
let SettingsRow::DiscoveredMidiPort { backend_id } = row else {
continue;
};
let Some(port) = self
.snapshot
.discovered_midi_ports
.iter()
.find(|port| &port.backend_id == backend_id)
else {
continue;
};
let selected = index == self.settings_selected;
if selected {
selected_line = Some(lines.len());
}
lines.push(
Line::from(format!(
"{} {} — available [Enter]",
if selected { "▶" } else { " " },
port.name
))
.style(if selected {
Style::default().fg(theme.accent).bold()
} else {
Style::default().fg(theme.foreground)
}),
);
}
}
let scroll = selected_line
.unwrap_or_default()
.saturating_add(1)
@ -3712,6 +3898,7 @@ impl DemoClient {
error: None,
}],
devices: Vec::new(),
discovered_midi_ports: Vec::new(),
configuration: ConfigurationSnapshot::default(),
}
}
@ -5134,7 +5321,7 @@ mod tests {
})
.unwrap();
app.handle_key_event(press(KeyCode::Tab));
for _ in 0..6 {
for _ in 0..7 {
app.handle_key_event(press(KeyCode::Down));
}
app.handle_key_event(press(KeyCode::Enter));
@ -5187,6 +5374,84 @@ mod tests {
)));
}
#[test]
fn detected_midi_port_can_be_added_from_settings() {
let edits = Arc::new(Mutex::new(Vec::new()));
let mut snapshot = DemoClient::default().view();
snapshot.discovered_midi_ports.push(DiscoveredMidiPort {
backend_id: "36:0".into(),
name: "APC MINI:APC MINI MIDI 1".into(),
usb_vendor_id: Some("09e8".into()),
usb_product_id: Some("0028".into()),
usb_serial: Some("Ver00.10".into()),
usb_path: Some("pci-usb-0:1".into()),
});
let mut app = LiveTui::new(LayoutClient {
snapshot,
edits: Arc::clone(&edits),
})
.unwrap();
app.handle_key_event(press(KeyCode::Tab));
for _ in 0..7 {
app.handle_key_event(press(KeyCode::Down));
}
app.handle_key_event(press(KeyCode::Enter));
let area = Rect::new(0, 0, 100, 24);
let mut buffer = Buffer::empty(area);
(&app).render(area, &mut buffer);
let rendered = buffer
.content
.iter()
.map(|cell| cell.symbol())
.collect::<String>();
assert!(rendered.contains("Detected MIDI port"));
assert!(rendered.contains("Add as controller"));
app.handle_key_event(press(KeyCode::Enter));
assert!(matches!(
edits.lock().unwrap().as_slice(),
[ConfigurationEdit::AddSurface {
id,
input_port,
manual_backend_id: Some(backend),
..
}] if id == "apc-mini-apc-mini-midi-1"
&& input_port == "APC MINI:APC MINI MIDI 1"
&& backend == "36:0"
));
}
#[test]
fn legacy_empty_profile_can_add_a_master_fader_from_settings() {
let edits = Arc::new(Mutex::new(Vec::new()));
let snapshot = DemoClient::default().view();
let mut app = LiveTui::new(LayoutClient {
snapshot,
edits: Arc::clone(&edits),
})
.unwrap();
app.handle_key_event(press(KeyCode::Tab));
for _ in 0..5 {
app.handle_key_event(press(KeyCode::Down));
}
app.handle_key_event(press(KeyCode::Enter));
assert!(matches!(
edits.lock().unwrap().as_slice(),
[ConfigurationEdit::Fader {
existing: false,
id,
target: MixerObjectId {
kind: MixerObjectKind::Output,
id: target,
},
pickup: true,
..
}] if id == "master-fader" && target == "default"
));
}
#[test]
fn configuration_tab_changes_theme_without_raw_object_editors() {
let edits = Arc::new(Mutex::new(Vec::new()));