feat(M5.3): reconcile MIDI surface hotplug state
Tests: cargo test --locked -p midi --all-targets --all-features Tests: cargo test --locked -p midi --all-targets --no-default-features Lint: cargo clippy --locked -p midi --all-targets --all-features -- -D warnings
This commit is contained in:
parent
e8e810d1ff
commit
be4f592295
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
mod decode;
|
||||
mod identity;
|
||||
mod lifecycle;
|
||||
#[cfg(all(feature = "midir", target_os = "linux"))]
|
||||
mod linux_identity;
|
||||
mod router;
|
||||
|
|
@ -14,6 +15,9 @@ pub use decode::{ButtonEdge, DecodeError, MidiMessage, decode_message};
|
|||
pub use identity::{
|
||||
DeviceMatch, MatchBasis, PortIdentity, PortResolution, UsbDeviceIdentity, resolve_port,
|
||||
};
|
||||
pub use lifecycle::{
|
||||
SurfaceAction, SurfaceAssignment, SurfaceLifecycle, SurfaceLifecycleError, SurfaceStatus,
|
||||
};
|
||||
#[cfg(all(feature = "midir", target_os = "linux"))]
|
||||
pub use linux_identity::{LinuxIdentityCatalog, LinuxIdentityError};
|
||||
pub use router::{MidiIntent, MidiRouter};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,258 @@
|
|||
use std::collections::BTreeMap;
|
||||
|
||||
use fader_core::SurfaceId;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{DeviceMatch, MatchBasis, PortIdentity, PortResolution, resolve_port};
|
||||
|
||||
/// Durable matching policy for one configured surface.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct SurfaceAssignment {
|
||||
pub surface: SurfaceId,
|
||||
pub expected: DeviceMatch,
|
||||
pub manual_backend_id: Option<String>,
|
||||
}
|
||||
|
||||
/// User-visible connection state retained even while a surface is absent.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SurfaceStatus {
|
||||
Missing,
|
||||
Ambiguous {
|
||||
backend_ids: Vec<String>,
|
||||
},
|
||||
Connecting {
|
||||
backend_id: String,
|
||||
basis: MatchBasis,
|
||||
},
|
||||
Connected {
|
||||
backend_id: String,
|
||||
basis: MatchBasis,
|
||||
},
|
||||
Error {
|
||||
backend_id: String,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Native connection work requested by one reconciliation pass.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SurfaceAction {
|
||||
Connect {
|
||||
surface: SurfaceId,
|
||||
port_index: usize,
|
||||
backend_id: String,
|
||||
},
|
||||
Disconnect {
|
||||
surface: SurfaceId,
|
||||
backend_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Error, Eq, PartialEq)]
|
||||
pub enum SurfaceLifecycleError {
|
||||
#[error("duplicate configured surface {0}")]
|
||||
Duplicate(SurfaceId),
|
||||
#[error("surface {0} is not configured")]
|
||||
Unknown(SurfaceId),
|
||||
#[error("surface {surface} is not connecting to backend {backend_id:?}")]
|
||||
UnexpectedConnection {
|
||||
surface: SurfaceId,
|
||||
backend_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Entry {
|
||||
assignment: SurfaceAssignment,
|
||||
status: SurfaceStatus,
|
||||
current_backend: Option<String>,
|
||||
}
|
||||
|
||||
/// Deterministic hotplug reconciliation independent of native MIDI handles.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SurfaceLifecycle {
|
||||
entries: BTreeMap<SurfaceId, Entry>,
|
||||
}
|
||||
|
||||
impl SurfaceLifecycle {
|
||||
pub fn new(
|
||||
assignments: impl IntoIterator<Item = SurfaceAssignment>,
|
||||
) -> Result<Self, SurfaceLifecycleError> {
|
||||
let mut entries = BTreeMap::new();
|
||||
for assignment in assignments {
|
||||
let id = assignment.surface.clone();
|
||||
if entries
|
||||
.insert(
|
||||
id.clone(),
|
||||
Entry {
|
||||
assignment,
|
||||
status: SurfaceStatus::Missing,
|
||||
current_backend: None,
|
||||
},
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
return Err(SurfaceLifecycleError::Duplicate(id));
|
||||
}
|
||||
}
|
||||
Ok(Self { entries })
|
||||
}
|
||||
|
||||
/// Reconciles all surfaces independently and returns native work in stable
|
||||
/// surface-ID order. A port claimed by multiple surfaces is left ambiguous.
|
||||
pub fn reconcile(&mut self, ports: &[PortIdentity]) -> Vec<SurfaceAction> {
|
||||
let mut resolutions: BTreeMap<SurfaceId, PortResolution> = self
|
||||
.entries
|
||||
.iter()
|
||||
.map(|(id, entry)| {
|
||||
(
|
||||
id.clone(),
|
||||
resolve_port(
|
||||
&entry.assignment.expected,
|
||||
ports,
|
||||
entry.assignment.manual_backend_id.as_deref(),
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut claims = BTreeMap::<usize, usize>::new();
|
||||
for resolution in resolutions.values() {
|
||||
if let PortResolution::Matched { index, .. } = resolution {
|
||||
*claims.entry(*index).or_default() += 1;
|
||||
}
|
||||
}
|
||||
for resolution in resolutions.values_mut() {
|
||||
if let PortResolution::Matched { index, .. } = resolution
|
||||
&& claims.get(index).copied().unwrap_or_default() > 1
|
||||
{
|
||||
*resolution = PortResolution::Ambiguous {
|
||||
candidate_indices: vec![*index],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let mut actions = Vec::new();
|
||||
for (id, entry) in &mut self.entries {
|
||||
let resolution = resolutions.remove(id).unwrap_or(PortResolution::Missing);
|
||||
match resolution {
|
||||
PortResolution::Missing => {
|
||||
disconnect_current(id, entry, &mut actions);
|
||||
entry.status = SurfaceStatus::Missing;
|
||||
}
|
||||
PortResolution::Ambiguous { candidate_indices } => {
|
||||
disconnect_current(id, entry, &mut actions);
|
||||
entry.status = SurfaceStatus::Ambiguous {
|
||||
backend_ids: candidate_indices
|
||||
.into_iter()
|
||||
.filter_map(|index| ports.get(index))
|
||||
.map(|port| port.backend_id.clone())
|
||||
.collect(),
|
||||
};
|
||||
}
|
||||
PortResolution::Matched { index, basis } => {
|
||||
let Some(port) = ports.get(index) else {
|
||||
disconnect_current(id, entry, &mut actions);
|
||||
entry.status = SurfaceStatus::Missing;
|
||||
continue;
|
||||
};
|
||||
if entry.current_backend.as_deref() == Some(&port.backend_id) {
|
||||
continue;
|
||||
}
|
||||
if matches!(
|
||||
&entry.status,
|
||||
SurfaceStatus::Connecting { backend_id, .. }
|
||||
if backend_id == &port.backend_id
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
disconnect_current(id, entry, &mut actions);
|
||||
entry.status = SurfaceStatus::Connecting {
|
||||
backend_id: port.backend_id.clone(),
|
||||
basis,
|
||||
};
|
||||
actions.push(SurfaceAction::Connect {
|
||||
surface: id.clone(),
|
||||
port_index: index,
|
||||
backend_id: port.backend_id.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
actions
|
||||
}
|
||||
|
||||
pub fn connection_succeeded(
|
||||
&mut self,
|
||||
surface: &SurfaceId,
|
||||
backend_id: &str,
|
||||
) -> Result<(), SurfaceLifecycleError> {
|
||||
let entry = self
|
||||
.entries
|
||||
.get_mut(surface)
|
||||
.ok_or_else(|| SurfaceLifecycleError::Unknown(surface.clone()))?;
|
||||
let SurfaceStatus::Connecting {
|
||||
backend_id: expected,
|
||||
basis,
|
||||
} = &entry.status
|
||||
else {
|
||||
return Err(SurfaceLifecycleError::UnexpectedConnection {
|
||||
surface: surface.clone(),
|
||||
backend_id: backend_id.to_owned(),
|
||||
});
|
||||
};
|
||||
if expected != backend_id {
|
||||
return Err(SurfaceLifecycleError::UnexpectedConnection {
|
||||
surface: surface.clone(),
|
||||
backend_id: backend_id.to_owned(),
|
||||
});
|
||||
}
|
||||
let basis = *basis;
|
||||
entry.current_backend = Some(backend_id.to_owned());
|
||||
entry.status = SurfaceStatus::Connected {
|
||||
backend_id: backend_id.to_owned(),
|
||||
basis,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn connection_failed(
|
||||
&mut self,
|
||||
surface: &SurfaceId,
|
||||
backend_id: &str,
|
||||
message: impl Into<String>,
|
||||
) -> Result<(), SurfaceLifecycleError> {
|
||||
let entry = self
|
||||
.entries
|
||||
.get_mut(surface)
|
||||
.ok_or_else(|| SurfaceLifecycleError::Unknown(surface.clone()))?;
|
||||
if !matches!(
|
||||
&entry.status,
|
||||
SurfaceStatus::Connecting { backend_id: expected, .. } if expected == backend_id
|
||||
) {
|
||||
return Err(SurfaceLifecycleError::UnexpectedConnection {
|
||||
surface: surface.clone(),
|
||||
backend_id: backend_id.to_owned(),
|
||||
});
|
||||
}
|
||||
entry.current_backend = None;
|
||||
entry.status = SurfaceStatus::Error {
|
||||
backend_id: backend_id.to_owned(),
|
||||
message: message.into(),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn status(&self, surface: &SurfaceId) -> Option<&SurfaceStatus> {
|
||||
self.entries.get(surface).map(|entry| &entry.status)
|
||||
}
|
||||
}
|
||||
|
||||
fn disconnect_current(id: &SurfaceId, entry: &mut Entry, actions: &mut Vec<SurfaceAction>) {
|
||||
if let Some(backend_id) = entry.current_backend.take() {
|
||||
actions.push(SurfaceAction::Disconnect {
|
||||
surface: id.clone(),
|
||||
backend_id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
use fader_core::SurfaceId;
|
||||
use midi::{
|
||||
DeviceMatch, MatchBasis, PortIdentity, SurfaceAction, SurfaceAssignment, SurfaceLifecycle,
|
||||
SurfaceStatus, UsbDeviceIdentity,
|
||||
};
|
||||
|
||||
fn surface(id: &str, serial: Option<&str>, manual: Option<&str>) -> SurfaceAssignment {
|
||||
SurfaceAssignment {
|
||||
surface: SurfaceId::new(id).unwrap(),
|
||||
expected: DeviceMatch {
|
||||
port_name: "APC MINI MIDI 1".into(),
|
||||
vendor_id: Some("09e8".into()),
|
||||
product_id: Some("0028".into()),
|
||||
serial: serial.map(str::to_owned),
|
||||
path: None,
|
||||
},
|
||||
manual_backend_id: manual.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
fn port(backend_id: &str, serial: Option<&str>, path: &str) -> PortIdentity {
|
||||
PortIdentity {
|
||||
backend_id: backend_id.into(),
|
||||
name: "APC MINI MIDI 1".into(),
|
||||
usb: Some(UsbDeviceIdentity {
|
||||
vendor_id: "09e8".into(),
|
||||
product_id: "0028".into(),
|
||||
serial: serial.map(str::to_owned),
|
||||
path: Some(path.into()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unplug_replug_and_port_reorder_preserve_a_serial_assignment() {
|
||||
let id = SurfaceId::new("left").unwrap();
|
||||
let mut lifecycle = SurfaceLifecycle::new([surface("left", Some("SERIAL"), None)]).unwrap();
|
||||
let first = vec![port("36:0", Some("SERIAL"), "usb-1")];
|
||||
assert!(matches!(
|
||||
lifecycle.reconcile(&first).as_slice(),
|
||||
[SurfaceAction::Connect { backend_id, .. }] if backend_id == "36:0"
|
||||
));
|
||||
lifecycle.connection_succeeded(&id, "36:0").unwrap();
|
||||
assert!(matches!(
|
||||
lifecycle.status(&id),
|
||||
Some(SurfaceStatus::Connected {
|
||||
basis: MatchBasis::Serial,
|
||||
..
|
||||
})
|
||||
));
|
||||
|
||||
assert!(matches!(
|
||||
lifecycle.reconcile(&[]).as_slice(),
|
||||
[SurfaceAction::Disconnect { backend_id, .. }] if backend_id == "36:0"
|
||||
));
|
||||
assert_eq!(lifecycle.status(&id), Some(&SurfaceStatus::Missing));
|
||||
|
||||
let reordered = vec![
|
||||
port("40:0", Some("OTHER"), "usb-2"),
|
||||
port("42:0", Some("SERIAL"), "usb-3"),
|
||||
];
|
||||
assert!(matches!(
|
||||
lifecycle.reconcile(&reordered).as_slice(),
|
||||
[SurfaceAction::Connect { backend_id, .. }] if backend_id == "42:0"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_identical_devices_stay_unassigned_until_manually_selected() {
|
||||
let id = SurfaceId::new("left").unwrap();
|
||||
let ports = vec![port("36:0", None, "usb-1"), port("40:0", None, "usb-2")];
|
||||
let mut unresolved = SurfaceLifecycle::new([surface("left", None, None)]).unwrap();
|
||||
assert!(unresolved.reconcile(&ports).is_empty());
|
||||
assert!(matches!(
|
||||
unresolved.status(&id),
|
||||
Some(SurfaceStatus::Ambiguous { backend_ids }) if backend_ids == &["36:0", "40:0"]
|
||||
));
|
||||
|
||||
let mut manual = SurfaceLifecycle::new([surface("left", None, Some("40:0"))]).unwrap();
|
||||
assert!(matches!(
|
||||
manual.reconcile(&ports).as_slice(),
|
||||
[SurfaceAction::Connect { backend_id, .. }] if backend_id == "40:0"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_connection_failure_does_not_disconnect_another_surface() {
|
||||
let left = SurfaceId::new("left").unwrap();
|
||||
let right = SurfaceId::new("right").unwrap();
|
||||
let ports = vec![
|
||||
port("36:0", Some("LEFT"), "usb-1"),
|
||||
port("40:0", Some("RIGHT"), "usb-2"),
|
||||
];
|
||||
let mut lifecycle = SurfaceLifecycle::new([
|
||||
surface("left", Some("LEFT"), None),
|
||||
surface("right", Some("RIGHT"), None),
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(lifecycle.reconcile(&ports).len(), 2);
|
||||
lifecycle.connection_succeeded(&left, "36:0").unwrap();
|
||||
lifecycle
|
||||
.connection_failed(&right, "40:0", "device busy")
|
||||
.unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
lifecycle.status(&left),
|
||||
Some(SurfaceStatus::Connected { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
lifecycle.status(&right),
|
||||
Some(SurfaceStatus::Error { message, .. }) if message == "device busy"
|
||||
));
|
||||
assert!(matches!(
|
||||
lifecycle.reconcile(&ports).as_slice(),
|
||||
[SurfaceAction::Connect { surface, .. }] if surface == &right
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_configured_surfaces_cannot_claim_the_same_port() {
|
||||
let left = SurfaceId::new("left").unwrap();
|
||||
let right = SurfaceId::new("right").unwrap();
|
||||
let ports = vec![port("36:0", Some("SHARED"), "usb-1")];
|
||||
let assignment = surface("left", Some("SHARED"), None);
|
||||
let mut duplicate = assignment.clone();
|
||||
duplicate.surface = right.clone();
|
||||
let mut lifecycle = SurfaceLifecycle::new([assignment, duplicate]).unwrap();
|
||||
|
||||
assert!(lifecycle.reconcile(&ports).is_empty());
|
||||
assert!(matches!(
|
||||
lifecycle.status(&left),
|
||||
Some(SurfaceStatus::Ambiguous { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
lifecycle.status(&right),
|
||||
Some(SurfaceStatus::Ambiguous { .. })
|
||||
));
|
||||
}
|
||||
Loading…
Reference in New Issue