7555 lines
264 KiB
Rust
7555 lines
264 KiB
Rust
//! Terminal user interface for fader_master.
|
||
|
||
mod theme;
|
||
|
||
pub use theme::ThemeName;
|
||
|
||
use std::{
|
||
collections::{BTreeMap, VecDeque},
|
||
io,
|
||
sync::{
|
||
Arc, Condvar, Mutex,
|
||
mpsc::{self, Receiver, RecvTimeoutError},
|
||
},
|
||
thread::{self, JoinHandle},
|
||
time::Duration,
|
||
};
|
||
|
||
use ratatui::{
|
||
DefaultTerminal, Frame,
|
||
buffer::Buffer,
|
||
crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
|
||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||
style::{Style, Stylize},
|
||
symbols::border,
|
||
text::{Line, Span, Text},
|
||
widgets::{Block, Clear, Gauge, Paragraph, Widget, Wrap},
|
||
};
|
||
|
||
const VOLUME_STEP: f64 = 0.05;
|
||
const REFRESH_INTERVAL: Duration = Duration::from_millis(100);
|
||
const CLIENT_IDLE_REFRESH: Duration = Duration::from_millis(250);
|
||
const CLIENT_PENDING_REFRESH: Duration = Duration::from_millis(20);
|
||
const CLIENT_SHUTDOWN_GRACE: Duration = Duration::from_millis(25);
|
||
const MAX_BUFFERED_MUTE_EDGES: usize = 128;
|
||
|
||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||
pub enum MixerObjectKind {
|
||
Application,
|
||
Group,
|
||
Output,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||
pub enum PickupStatus {
|
||
Unavailable,
|
||
Waiting,
|
||
Tracking,
|
||
Mixed,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||
pub struct MixerObjectId {
|
||
pub kind: MixerObjectKind,
|
||
pub id: String,
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub struct MixerItem {
|
||
pub id: MixerObjectId,
|
||
pub label: String,
|
||
pub detail: String,
|
||
pub gain: Option<f64>,
|
||
pub gain_mixed: bool,
|
||
pub muted: Option<bool>,
|
||
pub mute_mixed: bool,
|
||
pub pending: bool,
|
||
pub pickup: Option<PickupStatus>,
|
||
pub writable: bool,
|
||
pub error: Option<String>,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
pub struct MidiDevice {
|
||
pub id: String,
|
||
pub label: String,
|
||
pub status: String,
|
||
pub backend_id: Option<String>,
|
||
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,
|
||
pub dirty: bool,
|
||
pub applied_revision: u64,
|
||
pub selection_saved: bool,
|
||
pub learning: Option<String>,
|
||
pub error: Option<String>,
|
||
pub profile_id: String,
|
||
pub available_profiles: Vec<String>,
|
||
pub mixer_orientation: MixerOrientation,
|
||
pub status_display: StatusDisplayMode,
|
||
pub default_controller: Option<String>,
|
||
pub theme: ThemeName,
|
||
pub applications: Vec<ConfiguredApplication>,
|
||
pub groups: Vec<ConfiguredGroup>,
|
||
pub faders: Vec<ConfiguredFader>,
|
||
pub mixer_layout: Vec<MixerLayoutEntry>,
|
||
pub bindings: Vec<ConfiguredBinding>,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||
pub enum MixerOrientation {
|
||
#[default]
|
||
Vertical,
|
||
Horizontal,
|
||
}
|
||
|
||
impl MixerOrientation {
|
||
const fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Vertical => "Vertical",
|
||
Self::Horizontal => "Horizontal",
|
||
}
|
||
}
|
||
|
||
const fn toggled(self) -> Self {
|
||
match self {
|
||
Self::Vertical => Self::Horizontal,
|
||
Self::Horizontal => Self::Vertical,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||
pub enum StatusDisplayMode {
|
||
#[default]
|
||
Detailed,
|
||
Compact,
|
||
Symbol,
|
||
Color,
|
||
Hidden,
|
||
}
|
||
|
||
impl StatusDisplayMode {
|
||
const fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Detailed => "Detailed",
|
||
Self::Compact => "Compact",
|
||
Self::Symbol => "Symbol",
|
||
Self::Color => "Color",
|
||
Self::Hidden => "Hidden",
|
||
}
|
||
}
|
||
|
||
const fn next(self) -> Self {
|
||
match self {
|
||
Self::Detailed => Self::Compact,
|
||
Self::Compact => Self::Symbol,
|
||
Self::Symbol => Self::Color,
|
||
Self::Color => Self::Hidden,
|
||
Self::Hidden => Self::Detailed,
|
||
}
|
||
}
|
||
|
||
const fn previous(self) -> Self {
|
||
match self {
|
||
Self::Detailed => Self::Hidden,
|
||
Self::Compact => Self::Detailed,
|
||
Self::Symbol => Self::Compact,
|
||
Self::Color => Self::Symbol,
|
||
Self::Hidden => Self::Color,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
pub enum MixerLayoutEntry {
|
||
Fader {
|
||
fader: String,
|
||
hidden: bool,
|
||
density: FaderDensity,
|
||
},
|
||
Separator {
|
||
id: String,
|
||
label: String,
|
||
size: SeparatorSize,
|
||
decoration: SeparatorDecoration,
|
||
},
|
||
}
|
||
|
||
/// Space reserved for a separator along the mixer layout axis.
|
||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||
pub enum SeparatorSize {
|
||
Slim,
|
||
#[default]
|
||
Standard,
|
||
Thick,
|
||
Fill,
|
||
}
|
||
|
||
/// Independent separator decoration.
|
||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||
pub enum SeparatorDecoration {
|
||
Plain,
|
||
#[default]
|
||
Line,
|
||
Double,
|
||
Box,
|
||
}
|
||
impl SeparatorSize {
|
||
const fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Slim => "Slim",
|
||
Self::Standard => "Standard",
|
||
Self::Thick => "Thick",
|
||
Self::Fill => "Fill",
|
||
}
|
||
}
|
||
|
||
const fn cycle(self, forward: bool) -> Self {
|
||
match (self, forward) {
|
||
(Self::Slim, true) => Self::Standard,
|
||
(Self::Slim, false) => Self::Fill,
|
||
(Self::Standard, true) => Self::Thick,
|
||
(Self::Standard, false) => Self::Slim,
|
||
(Self::Thick, true) => Self::Fill,
|
||
(Self::Thick, false) => Self::Standard,
|
||
(Self::Fill, true) => Self::Slim,
|
||
(Self::Fill, false) => Self::Thick,
|
||
}
|
||
}
|
||
}
|
||
impl SeparatorDecoration {
|
||
const fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Plain => "Plain",
|
||
Self::Line => "Line",
|
||
Self::Double => "Double line",
|
||
Self::Box => "Box",
|
||
}
|
||
}
|
||
|
||
const fn cycle(self, forward: bool) -> Self {
|
||
match (self, forward) {
|
||
(Self::Plain, true) => Self::Line,
|
||
(Self::Plain, false) => Self::Box,
|
||
(Self::Line, true) => Self::Double,
|
||
(Self::Line, false) => Self::Plain,
|
||
(Self::Double, true) => Self::Box,
|
||
(Self::Double, false) => Self::Line,
|
||
(Self::Box, true) => Self::Plain,
|
||
(Self::Box, false) => Self::Double,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||
pub enum FaderDensity {
|
||
Slim,
|
||
BorderedSlim,
|
||
#[default]
|
||
Standard,
|
||
Thick,
|
||
}
|
||
|
||
impl FaderDensity {
|
||
const fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Slim => "Slim",
|
||
Self::BorderedSlim => "Bordered slim",
|
||
Self::Standard => "Standard",
|
||
Self::Thick => "Thick",
|
||
}
|
||
}
|
||
|
||
const fn next(self) -> Self {
|
||
match self {
|
||
Self::Slim => Self::BorderedSlim,
|
||
Self::BorderedSlim => Self::Standard,
|
||
Self::Standard => Self::Thick,
|
||
Self::Thick => Self::Slim,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
pub struct ConfiguredApplication {
|
||
pub id: String,
|
||
pub label: String,
|
||
pub selectors: Vec<ConfiguredSelector>,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
pub struct ConfiguredSelector {
|
||
pub field: String,
|
||
pub pattern: String,
|
||
pub regex: bool,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||
pub enum GroupVolumeMode {
|
||
Absolute,
|
||
Relative,
|
||
}
|
||
|
||
impl GroupVolumeMode {
|
||
const fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Absolute => "Absolute",
|
||
Self::Relative => "Relative",
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
pub struct ConfiguredGroup {
|
||
pub id: String,
|
||
pub label: String,
|
||
pub members: Vec<String>,
|
||
pub volume_mode: GroupVolumeMode,
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub struct ConfiguredFader {
|
||
pub id: String,
|
||
pub target: MixerObjectId,
|
||
pub pickup: bool,
|
||
pub pickup_tolerance: f64,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
pub struct ConfiguredBinding {
|
||
pub surface: String,
|
||
pub fader: String,
|
||
pub action: String,
|
||
pub message: String,
|
||
pub kind: String,
|
||
pub channel: u16,
|
||
pub number: u16,
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub enum ConfigurationEdit {
|
||
AddApplicationFader {
|
||
application_id: String,
|
||
label: String,
|
||
field: String,
|
||
pattern: String,
|
||
regex: bool,
|
||
fader_id: String,
|
||
position: usize,
|
||
},
|
||
AddGroupFader {
|
||
group_id: String,
|
||
label: String,
|
||
fader_id: String,
|
||
position: usize,
|
||
},
|
||
RemoveMixerFader {
|
||
id: String,
|
||
},
|
||
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,
|
||
label: String,
|
||
field: String,
|
||
pattern: String,
|
||
regex: bool,
|
||
},
|
||
Group {
|
||
existing: bool,
|
||
id: String,
|
||
label: String,
|
||
members: Vec<String>,
|
||
},
|
||
Fader {
|
||
existing: bool,
|
||
id: String,
|
||
target: MixerObjectId,
|
||
pickup: bool,
|
||
pickup_tolerance: f64,
|
||
},
|
||
Remove {
|
||
kind: String,
|
||
id: String,
|
||
},
|
||
MoveLayoutEntry {
|
||
id: String,
|
||
position: usize,
|
||
},
|
||
SetFaderHidden {
|
||
id: String,
|
||
hidden: bool,
|
||
},
|
||
SetFaderDensity {
|
||
id: String,
|
||
density: FaderDensity,
|
||
},
|
||
SetMixerOrientation {
|
||
orientation: MixerOrientation,
|
||
},
|
||
SetStatusDisplay {
|
||
mode: StatusDisplayMode,
|
||
},
|
||
SetDefaultController {
|
||
surface: Option<String>,
|
||
},
|
||
SetTheme {
|
||
theme: ThemeName,
|
||
},
|
||
AddSeparator {
|
||
id: String,
|
||
label: String,
|
||
position: usize,
|
||
},
|
||
SetSeparatorLabel {
|
||
id: String,
|
||
label: String,
|
||
},
|
||
SetSeparatorPresentation {
|
||
id: String,
|
||
size: SeparatorSize,
|
||
decoration: SeparatorDecoration,
|
||
},
|
||
RemoveSeparator {
|
||
id: String,
|
||
},
|
||
SetApplicationSelector {
|
||
id: String,
|
||
index: usize,
|
||
field: String,
|
||
pattern: String,
|
||
regex: bool,
|
||
},
|
||
SetBinding {
|
||
surface: String,
|
||
fader: String,
|
||
action: String,
|
||
kind: String,
|
||
channel: u16,
|
||
number: u16,
|
||
},
|
||
RemoveBinding {
|
||
fader: String,
|
||
action: String,
|
||
},
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub struct MixerSnapshot {
|
||
pub revision: u64,
|
||
pub backend: String,
|
||
pub status: String,
|
||
/// Client/transport failure while the last confirmed items remain visible.
|
||
pub error: Option<String>,
|
||
pub items: Vec<MixerItem>,
|
||
pub devices: Vec<MidiDevice>,
|
||
pub discovered_midi_ports: Vec<DiscoveredMidiPort>,
|
||
pub configuration: ConfigurationSnapshot,
|
||
}
|
||
|
||
/// Client boundary kept independent of sockets for deterministic TUI tests.
|
||
pub trait MixerClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot>;
|
||
fn set_volume(
|
||
&mut self,
|
||
id: MixerObjectId,
|
||
gain: f64,
|
||
expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot>;
|
||
fn toggle_mute(
|
||
&mut self,
|
||
id: MixerObjectId,
|
||
expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot>;
|
||
fn edit_configuration(
|
||
&mut self,
|
||
_edit: ConfigurationEdit,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
Err(io::Error::new(
|
||
io::ErrorKind::Unsupported,
|
||
"configuration editing is unavailable",
|
||
))
|
||
}
|
||
fn start_midi_learn(
|
||
&mut self,
|
||
_surface: String,
|
||
_fader: String,
|
||
_action: String,
|
||
) -> io::Result<MixerSnapshot> {
|
||
Err(io::Error::new(
|
||
io::ErrorKind::Unsupported,
|
||
"MIDI learn is unavailable",
|
||
))
|
||
}
|
||
fn cancel_midi_learn(&mut self) -> io::Result<MixerSnapshot> {
|
||
Err(io::Error::new(
|
||
io::ErrorKind::Unsupported,
|
||
"MIDI learn is unavailable",
|
||
))
|
||
}
|
||
fn save_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||
Err(io::Error::new(
|
||
io::ErrorKind::Unsupported,
|
||
"configuration save is unavailable",
|
||
))
|
||
}
|
||
fn reset_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||
Err(io::Error::new(
|
||
io::ErrorKind::Unsupported,
|
||
"configuration reset is unavailable",
|
||
))
|
||
}
|
||
fn switch_profile(&mut self, _id: String) -> io::Result<MixerSnapshot> {
|
||
Err(io::Error::new(
|
||
io::ErrorKind::Unsupported,
|
||
"profile switching is unavailable",
|
||
))
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
enum BufferedAction {
|
||
SetVolume {
|
||
id: MixerObjectId,
|
||
gain: f64,
|
||
},
|
||
ToggleMute {
|
||
id: MixerObjectId,
|
||
},
|
||
Refresh,
|
||
EditConfiguration {
|
||
edit: ConfigurationEdit,
|
||
},
|
||
StartMidiLearn {
|
||
surface: String,
|
||
fader: String,
|
||
action: String,
|
||
},
|
||
CancelMidiLearn,
|
||
SaveConfiguration,
|
||
ResetConfiguration,
|
||
SwitchProfile {
|
||
id: String,
|
||
},
|
||
}
|
||
|
||
#[derive(Debug)]
|
||
struct BufferedState {
|
||
snapshot: MixerSnapshot,
|
||
desired_volumes: BTreeMap<MixerObjectId, f64>,
|
||
desired_mutes: BTreeMap<MixerObjectId, bool>,
|
||
volume_work: BTreeMap<MixerObjectId, f64>,
|
||
mute_work: VecDeque<MixerObjectId>,
|
||
configuration_work: VecDeque<BufferedAction>,
|
||
error: Option<String>,
|
||
shutdown: bool,
|
||
}
|
||
|
||
/// Nonblocking client facade backed by one joined IPC worker thread.
|
||
pub struct BufferedMixerClient {
|
||
shared: Arc<(Mutex<BufferedState>, Condvar)>,
|
||
worker: Option<JoinHandle<()>>,
|
||
worker_done: Receiver<()>,
|
||
}
|
||
|
||
impl BufferedMixerClient {
|
||
pub fn spawn<C>(mut client: C) -> io::Result<Self>
|
||
where
|
||
C: MixerClient + Send + 'static,
|
||
{
|
||
let initial = MixerSnapshot {
|
||
revision: 0,
|
||
backend: "local IPC".to_owned(),
|
||
status: "waiting for server".to_owned(),
|
||
error: None,
|
||
items: Vec::new(),
|
||
devices: Vec::new(),
|
||
discovered_midi_ports: Vec::new(),
|
||
configuration: ConfigurationSnapshot::default(),
|
||
};
|
||
let shared = Arc::new((
|
||
Mutex::new(BufferedState {
|
||
snapshot: initial.clone(),
|
||
desired_volumes: BTreeMap::new(),
|
||
desired_mutes: BTreeMap::new(),
|
||
volume_work: BTreeMap::new(),
|
||
mute_work: VecDeque::new(),
|
||
configuration_work: VecDeque::new(),
|
||
error: None,
|
||
shutdown: false,
|
||
}),
|
||
Condvar::new(),
|
||
));
|
||
let worker_shared = Arc::clone(&shared);
|
||
let (done_sender, worker_done) = mpsc::sync_channel(1);
|
||
let worker = thread::spawn(move || {
|
||
client_loop(&mut client, initial, &worker_shared);
|
||
let _ = done_sender.send(());
|
||
});
|
||
Ok(Self {
|
||
shared,
|
||
worker: Some(worker),
|
||
worker_done,
|
||
})
|
||
}
|
||
|
||
fn with_state<T>(&self, operation: impl FnOnce(&mut BufferedState) -> T) -> io::Result<T> {
|
||
let (state, _) = &*self.shared;
|
||
let mut state = state
|
||
.lock()
|
||
.map_err(|_| io::Error::other("buffered mixer client state is poisoned"))?;
|
||
Ok(operation(&mut state))
|
||
}
|
||
}
|
||
|
||
impl MixerClient for BufferedMixerClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
self.with_state(|state| {
|
||
let mut snapshot = state.snapshot.clone();
|
||
snapshot.error.clone_from(&state.error);
|
||
snapshot
|
||
})
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
id: MixerObjectId,
|
||
gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
let (state, wake) = &*self.shared;
|
||
let mut state = state
|
||
.lock()
|
||
.map_err(|_| io::Error::other("buffered mixer client state is poisoned"))?;
|
||
let item = state
|
||
.snapshot
|
||
.items
|
||
.iter_mut()
|
||
.find(|item| item.id == id)
|
||
.ok_or_else(|| io::Error::other("selected mixer object disappeared"))?;
|
||
if !item.writable {
|
||
return Err(io::Error::other("selected object is offline or read-only"));
|
||
}
|
||
item.gain = Some(gain);
|
||
item.pending = true;
|
||
state.desired_volumes.insert(id.clone(), gain);
|
||
state.volume_work.insert(id, gain);
|
||
state.error = None;
|
||
let snapshot = state.snapshot.clone();
|
||
wake.notify_one();
|
||
Ok(snapshot)
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
let (state, wake) = &*self.shared;
|
||
let mut state = state
|
||
.lock()
|
||
.map_err(|_| io::Error::other("buffered mixer client state is poisoned"))?;
|
||
if state.mute_work.len() >= MAX_BUFFERED_MUTE_EDGES {
|
||
return Err(io::Error::other("mute input buffer is full"));
|
||
}
|
||
let item = state
|
||
.snapshot
|
||
.items
|
||
.iter_mut()
|
||
.find(|item| item.id == id)
|
||
.ok_or_else(|| io::Error::other("selected mixer object disappeared"))?;
|
||
if !item.writable {
|
||
return Err(io::Error::other("selected object is offline or read-only"));
|
||
}
|
||
let muted = !item.muted.unwrap_or(false);
|
||
item.muted = Some(muted);
|
||
item.pending = true;
|
||
state.desired_mutes.insert(id.clone(), muted);
|
||
state.mute_work.push_back(id);
|
||
state.error = None;
|
||
let snapshot = state.snapshot.clone();
|
||
wake.notify_one();
|
||
Ok(snapshot)
|
||
}
|
||
|
||
fn edit_configuration(
|
||
&mut self,
|
||
edit: ConfigurationEdit,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
let (state, wake) = &*self.shared;
|
||
let mut state = state
|
||
.lock()
|
||
.map_err(|_| io::Error::other("buffered mixer client state is poisoned"))?;
|
||
if state.configuration_work.len() >= 64 {
|
||
return Err(io::Error::other("configuration edit buffer is full"));
|
||
}
|
||
apply_optimistic_configuration_edit(&mut state.snapshot, &edit);
|
||
state
|
||
.configuration_work
|
||
.push_back(BufferedAction::EditConfiguration { edit });
|
||
state.error = None;
|
||
let snapshot = state.snapshot.clone();
|
||
wake.notify_one();
|
||
Ok(snapshot)
|
||
}
|
||
|
||
fn start_midi_learn(
|
||
&mut self,
|
||
surface: String,
|
||
fader: String,
|
||
action: String,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.queue_configuration_action(BufferedAction::StartMidiLearn {
|
||
surface,
|
||
fader,
|
||
action,
|
||
})
|
||
}
|
||
|
||
fn cancel_midi_learn(&mut self) -> io::Result<MixerSnapshot> {
|
||
self.queue_configuration_action(BufferedAction::CancelMidiLearn)
|
||
}
|
||
|
||
fn save_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||
self.queue_configuration_action(BufferedAction::SaveConfiguration)
|
||
}
|
||
|
||
fn reset_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||
self.queue_configuration_action(BufferedAction::ResetConfiguration)
|
||
}
|
||
|
||
fn switch_profile(&mut self, id: String) -> io::Result<MixerSnapshot> {
|
||
self.queue_configuration_action(BufferedAction::SwitchProfile { id })
|
||
}
|
||
}
|
||
|
||
impl BufferedMixerClient {
|
||
fn queue_configuration_action(&self, action: BufferedAction) -> io::Result<MixerSnapshot> {
|
||
let (state, wake) = &*self.shared;
|
||
let mut state = state
|
||
.lock()
|
||
.map_err(|_| io::Error::other("buffered mixer client state is poisoned"))?;
|
||
if state.configuration_work.len() >= 64 {
|
||
return Err(io::Error::other("configuration action buffer is full"));
|
||
}
|
||
state.configuration_work.push_back(action);
|
||
state.error = None;
|
||
let snapshot = state.snapshot.clone();
|
||
wake.notify_one();
|
||
Ok(snapshot)
|
||
}
|
||
}
|
||
|
||
impl Drop for BufferedMixerClient {
|
||
fn drop(&mut self) {
|
||
let (state, wake) = &*self.shared;
|
||
if let Ok(mut state) = state.lock() {
|
||
state.shutdown = true;
|
||
wake.notify_one();
|
||
}
|
||
if let Some(worker) = self.worker.take() {
|
||
match self.worker_done.recv_timeout(CLIENT_SHUTDOWN_GRACE) {
|
||
Ok(()) | Err(RecvTimeoutError::Disconnected) => {
|
||
let _ = worker.join();
|
||
}
|
||
Err(RecvTimeoutError::Timeout) => {
|
||
// A wedged server request must not keep the terminal in raw mode.
|
||
// Dropping the handle detaches the worker; it observes `shutdown`
|
||
// and exits if the request ever returns.
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
fn client_loop<C>(
|
||
client: &mut C,
|
||
mut confirmed: MixerSnapshot,
|
||
shared: &Arc<(Mutex<BufferedState>, Condvar)>,
|
||
) where
|
||
C: MixerClient,
|
||
{
|
||
let mut first_refresh = true;
|
||
loop {
|
||
let action = {
|
||
let (state, wake) = &**shared;
|
||
let Ok(mut state) = state.lock() else {
|
||
return;
|
||
};
|
||
if !first_refresh
|
||
&& !state.shutdown
|
||
&& state.mute_work.is_empty()
|
||
&& state.volume_work.is_empty()
|
||
&& state.configuration_work.is_empty()
|
||
{
|
||
let refresh = if state.desired_volumes.is_empty() && state.desired_mutes.is_empty()
|
||
{
|
||
CLIENT_IDLE_REFRESH
|
||
} else {
|
||
CLIENT_PENDING_REFRESH
|
||
};
|
||
let Ok((next, _)) = wake.wait_timeout(state, refresh) else {
|
||
return;
|
||
};
|
||
state = next;
|
||
}
|
||
if state.shutdown {
|
||
return;
|
||
}
|
||
if first_refresh {
|
||
first_refresh = false;
|
||
BufferedAction::Refresh
|
||
} else if let Some(id) = state.mute_work.pop_front() {
|
||
BufferedAction::ToggleMute { id }
|
||
} else if let Some((id, gain)) = state.volume_work.pop_first() {
|
||
BufferedAction::SetVolume { id, gain }
|
||
} else if let Some(action) = state.configuration_work.pop_front() {
|
||
action
|
||
} else {
|
||
BufferedAction::Refresh
|
||
}
|
||
};
|
||
|
||
let result = execute_action(client, &mut confirmed, &action);
|
||
let (state, _) = &**shared;
|
||
let Ok(mut state) = state.lock() else {
|
||
return;
|
||
};
|
||
match result {
|
||
Ok(snapshot) => {
|
||
confirmed = snapshot;
|
||
publish_confirmed(&mut state, &confirmed);
|
||
state.error = None;
|
||
}
|
||
Err(error) => {
|
||
discard_failed_action(&mut state, &action);
|
||
publish_confirmed(&mut state, &confirmed);
|
||
state.error = Some(error.to_string());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
fn execute_action<C: MixerClient>(
|
||
client: &mut C,
|
||
confirmed: &mut MixerSnapshot,
|
||
action: &BufferedAction,
|
||
) -> io::Result<MixerSnapshot> {
|
||
const MAX_STALE_ATTEMPTS: usize = 8;
|
||
|
||
let execute = |client: &mut C, revision, configuration_revision| match action {
|
||
BufferedAction::SetVolume { id, gain } => client.set_volume(id.clone(), *gain, revision),
|
||
BufferedAction::ToggleMute { id } => client.toggle_mute(id.clone(), revision),
|
||
BufferedAction::Refresh => client.snapshot(),
|
||
BufferedAction::EditConfiguration { edit } => {
|
||
client.edit_configuration(edit.clone(), configuration_revision)
|
||
}
|
||
BufferedAction::StartMidiLearn {
|
||
surface,
|
||
fader,
|
||
action,
|
||
} => client.start_midi_learn(surface.clone(), fader.clone(), action.clone()),
|
||
BufferedAction::CancelMidiLearn => client.cancel_midi_learn(),
|
||
BufferedAction::SaveConfiguration => client.save_configuration(configuration_revision),
|
||
BufferedAction::ResetConfiguration => client.reset_configuration(configuration_revision),
|
||
BufferedAction::SwitchProfile { id } => client.switch_profile(id.clone()),
|
||
};
|
||
let can_retry_stale = matches!(
|
||
action,
|
||
BufferedAction::SetVolume { .. }
|
||
| BufferedAction::ToggleMute { .. }
|
||
| BufferedAction::EditConfiguration { .. }
|
||
| BufferedAction::SaveConfiguration
|
||
| BufferedAction::ResetConfiguration
|
||
);
|
||
let mut first_error = None;
|
||
for attempt in 0..MAX_STALE_ATTEMPTS {
|
||
match execute(client, confirmed.revision, confirmed.configuration.revision) {
|
||
Ok(snapshot) => return Ok(snapshot),
|
||
Err(error)
|
||
if can_retry_stale
|
||
&& is_revision_conflict(&error)
|
||
&& attempt + 1 < MAX_STALE_ATTEMPTS =>
|
||
{
|
||
first_error.get_or_insert_with(|| error.to_string());
|
||
*confirmed = client.snapshot()?;
|
||
}
|
||
Err(error) => {
|
||
return Err(match first_error {
|
||
Some(first) => {
|
||
io::Error::other(format!("{first}; retry after resync failed: {error}"))
|
||
}
|
||
None => error,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
unreachable!("bounded action retry loop always returns")
|
||
}
|
||
|
||
fn is_revision_conflict(error: &io::Error) -> bool {
|
||
is_revision_conflict_message(&error.to_string())
|
||
}
|
||
|
||
fn is_revision_conflict_message(message: &str) -> bool {
|
||
let message = message.to_ascii_lowercase();
|
||
message.contains("revision")
|
||
&& ["stale", "mismatch", "conflict", "changed"]
|
||
.iter()
|
||
.any(|marker| message.contains(marker))
|
||
}
|
||
|
||
fn publish_confirmed(state: &mut BufferedState, confirmed: &MixerSnapshot) {
|
||
state.snapshot = confirmed.clone();
|
||
for action in &state.configuration_work {
|
||
if let BufferedAction::EditConfiguration { edit } = action {
|
||
apply_optimistic_configuration_edit(&mut state.snapshot, edit);
|
||
}
|
||
}
|
||
let queued_volumes = state.volume_work.keys().cloned().collect::<Vec<_>>();
|
||
let queued_mutes = state.mute_work.iter().cloned().collect::<Vec<_>>();
|
||
state.desired_volumes.retain(|id, _| {
|
||
queued_volumes.contains(id)
|
||
|| confirmed
|
||
.items
|
||
.iter()
|
||
.find(|item| &item.id == id)
|
||
.is_some_and(|item| item.pending)
|
||
});
|
||
state.desired_mutes.retain(|id, _| {
|
||
queued_mutes.contains(id)
|
||
|| confirmed
|
||
.items
|
||
.iter()
|
||
.find(|item| &item.id == id)
|
||
.is_some_and(|item| item.pending)
|
||
});
|
||
for (id, gain) in &state.desired_volumes {
|
||
if let Some(item) = state.snapshot.items.iter_mut().find(|item| &item.id == id) {
|
||
item.gain = Some(*gain);
|
||
item.pending = true;
|
||
}
|
||
}
|
||
for (id, muted) in &state.desired_mutes {
|
||
if let Some(item) = state.snapshot.items.iter_mut().find(|item| &item.id == id) {
|
||
item.muted = Some(*muted);
|
||
item.pending = true;
|
||
}
|
||
}
|
||
}
|
||
|
||
fn apply_optimistic_configuration_edit(snapshot: &mut MixerSnapshot, edit: &ConfigurationEdit) {
|
||
match edit {
|
||
ConfigurationEdit::MoveLayoutEntry { id, position } => {
|
||
let Some(index) = snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.position(|entry| match entry {
|
||
MixerLayoutEntry::Fader { fader, .. } => fader == id,
|
||
MixerLayoutEntry::Separator { id: separator, .. } => separator == id,
|
||
})
|
||
else {
|
||
return;
|
||
};
|
||
let entry = snapshot.configuration.mixer_layout.remove(index);
|
||
let position = (*position).min(snapshot.configuration.mixer_layout.len());
|
||
snapshot.configuration.mixer_layout.insert(position, entry);
|
||
}
|
||
ConfigurationEdit::AddApplicationFader {
|
||
application_id,
|
||
label,
|
||
field,
|
||
pattern,
|
||
regex,
|
||
fader_id,
|
||
position,
|
||
} => {
|
||
snapshot
|
||
.configuration
|
||
.applications
|
||
.push(ConfiguredApplication {
|
||
id: application_id.clone(),
|
||
label: label.clone(),
|
||
selectors: vec![ConfiguredSelector {
|
||
field: field.clone(),
|
||
pattern: pattern.clone(),
|
||
regex: *regex,
|
||
}],
|
||
});
|
||
snapshot.configuration.faders.push(ConfiguredFader {
|
||
id: fader_id.clone(),
|
||
target: MixerObjectId {
|
||
kind: MixerObjectKind::Application,
|
||
id: application_id.clone(),
|
||
},
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
});
|
||
snapshot.configuration.mixer_layout.insert(
|
||
(*position).min(snapshot.configuration.mixer_layout.len()),
|
||
MixerLayoutEntry::Fader {
|
||
fader: fader_id.clone(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
);
|
||
snapshot.configuration.dirty = true;
|
||
}
|
||
ConfigurationEdit::AddGroupFader {
|
||
group_id,
|
||
label,
|
||
fader_id,
|
||
position,
|
||
} => {
|
||
snapshot.configuration.groups.push(ConfiguredGroup {
|
||
id: group_id.clone(),
|
||
label: label.clone(),
|
||
members: Vec::new(),
|
||
volume_mode: GroupVolumeMode::Absolute,
|
||
});
|
||
snapshot.configuration.faders.push(ConfiguredFader {
|
||
id: fader_id.clone(),
|
||
target: MixerObjectId {
|
||
kind: MixerObjectKind::Group,
|
||
id: group_id.clone(),
|
||
},
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
});
|
||
snapshot.configuration.mixer_layout.insert(
|
||
(*position).min(snapshot.configuration.mixer_layout.len()),
|
||
MixerLayoutEntry::Fader {
|
||
fader: fader_id.clone(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
);
|
||
snapshot.configuration.dirty = true;
|
||
}
|
||
ConfigurationEdit::RemoveMixerFader { id } => {
|
||
let target = snapshot
|
||
.configuration
|
||
.faders
|
||
.iter()
|
||
.find(|fader| fader.id == *id)
|
||
.map(|fader| fader.target.clone());
|
||
snapshot
|
||
.configuration
|
||
.faders
|
||
.retain(|fader| fader.id != *id);
|
||
snapshot.configuration.mixer_layout.retain(
|
||
|entry| !matches!(entry, MixerLayoutEntry::Fader { fader, .. } if fader == id),
|
||
);
|
||
snapshot
|
||
.configuration
|
||
.bindings
|
||
.retain(|binding| binding.fader != *id);
|
||
if let Some(target) = target
|
||
&& !snapshot
|
||
.configuration
|
||
.faders
|
||
.iter()
|
||
.any(|fader| fader.target == target)
|
||
{
|
||
match target.kind {
|
||
MixerObjectKind::Application
|
||
if !snapshot
|
||
.configuration
|
||
.groups
|
||
.iter()
|
||
.any(|group| group.members.contains(&target.id)) =>
|
||
{
|
||
snapshot
|
||
.configuration
|
||
.applications
|
||
.retain(|application| application.id != target.id);
|
||
}
|
||
MixerObjectKind::Group => snapshot
|
||
.configuration
|
||
.groups
|
||
.retain(|group| group.id != target.id),
|
||
_ => {}
|
||
}
|
||
}
|
||
snapshot.configuration.dirty = true;
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) {
|
||
match action {
|
||
BufferedAction::SetVolume { id, gain } => {
|
||
if state.desired_volumes.get(id) == Some(gain) {
|
||
state.desired_volumes.remove(id);
|
||
}
|
||
}
|
||
BufferedAction::ToggleMute { id } => {
|
||
if !state.mute_work.iter().any(|queued| queued == id) {
|
||
state.desired_mutes.remove(id);
|
||
}
|
||
}
|
||
BufferedAction::Refresh => {}
|
||
BufferedAction::EditConfiguration { .. } => {}
|
||
BufferedAction::StartMidiLearn { .. } | BufferedAction::CancelMidiLearn => {}
|
||
BufferedAction::SaveConfiguration => {}
|
||
BufferedAction::ResetConfiguration => {}
|
||
BufferedAction::SwitchProfile { .. } => {}
|
||
}
|
||
}
|
||
|
||
/// Runs the live terminal client and restores terminal state on every return.
|
||
pub fn run_live(client: impl MixerClient + Send + 'static) -> io::Result<()> {
|
||
let client = BufferedMixerClient::spawn(client)?;
|
||
let mut app = LiveTui::new(client)?;
|
||
let mut terminal = ratatui::init();
|
||
let result = with_terminal_restore(ratatui::restore, || app.run(&mut terminal));
|
||
drop(app);
|
||
result
|
||
}
|
||
|
||
/// Runs the live terminal client with a selected built-in color theme.
|
||
pub fn run_live_with_theme(
|
||
client: impl MixerClient + Send + 'static,
|
||
theme: ThemeName,
|
||
) -> io::Result<()> {
|
||
let client = BufferedMixerClient::spawn(client)?;
|
||
let mut app = LiveTui::with_theme(client, theme)?;
|
||
let mut terminal = ratatui::init();
|
||
let result = with_terminal_restore(ratatui::restore, || app.run(&mut terminal));
|
||
drop(app);
|
||
result
|
||
}
|
||
|
||
/// Retains the original preview example without opening audio or IPC.
|
||
pub fn run() -> io::Result<()> {
|
||
run_live(DemoClient::default())
|
||
}
|
||
|
||
fn with_terminal_restore<T>(
|
||
restore: impl FnOnce(),
|
||
operation: impl FnOnce() -> io::Result<T>,
|
||
) -> io::Result<T> {
|
||
let _guard = RestoreTerminal(Some(restore));
|
||
operation()
|
||
}
|
||
|
||
struct RestoreTerminal<F: FnOnce()>(Option<F>);
|
||
|
||
impl<F: FnOnce()> Drop for RestoreTerminal<F> {
|
||
fn drop(&mut self) {
|
||
if let Some(restore) = self.0.take() {
|
||
restore();
|
||
}
|
||
}
|
||
}
|
||
|
||
pub struct LiveTui<C> {
|
||
client: C,
|
||
snapshot: MixerSnapshot,
|
||
selected: usize,
|
||
theme: ThemeName,
|
||
theme_override: bool,
|
||
exit: bool,
|
||
quit_confirmation: bool,
|
||
reset_confirmation: bool,
|
||
add_picker: Option<AddPicker>,
|
||
new_item_editor: Option<NewItemEditor>,
|
||
delete_confirmation: Option<DeleteConfirmation>,
|
||
show_help: bool,
|
||
client_error: Option<String>,
|
||
tab: Tab,
|
||
editor: Option<EditorInput>,
|
||
settings_selected: usize,
|
||
fader_editor: Option<FaderEditor>,
|
||
capture_editor: Option<CaptureEditor>,
|
||
pattern_editor: Option<PatternEditor>,
|
||
controller_picker: Option<ControllerPicker>,
|
||
group_member_picker: Option<GroupMemberPicker>,
|
||
hidden_fader_picker: Option<HiddenFaderPicker>,
|
||
profile_picker: Option<ProfilePicker>,
|
||
midi_device_details: Option<String>,
|
||
controller_selections: BTreeMap<(String, String), String>,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||
enum Tab {
|
||
#[default]
|
||
Mixer,
|
||
Configuration,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||
struct EditorInput {
|
||
value: String,
|
||
target: Option<String>,
|
||
size: SeparatorSize,
|
||
decoration: SeparatorDecoration,
|
||
selected: usize,
|
||
}
|
||
|
||
enum SettingsRow {
|
||
Theme,
|
||
MixerOrientation,
|
||
StatusDisplay,
|
||
DefaultController,
|
||
HiddenFaders { count: usize },
|
||
ActiveProfile,
|
||
AddMasterFader,
|
||
CancelMidiLearn,
|
||
Save,
|
||
Reset,
|
||
MidiDevice { id: String },
|
||
DiscoveredMidiPort { backend_id: String },
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct FaderEditor {
|
||
fader: String,
|
||
selected: usize,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct CaptureEditor {
|
||
application: String,
|
||
selector: usize,
|
||
field: usize,
|
||
regex: bool,
|
||
pattern: String,
|
||
selected: usize,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct PatternEditor {
|
||
value: String,
|
||
cursor: usize,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct ControllerPicker {
|
||
fader: String,
|
||
action: String,
|
||
selected: usize,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct GroupMemberPicker {
|
||
group: String,
|
||
selected: usize,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct GroupMemberChoice {
|
||
application: String,
|
||
fader: String,
|
||
label: String,
|
||
included: bool,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct HiddenFaderPicker {
|
||
selected: usize,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct ProfilePicker {
|
||
selected: usize,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||
enum AddKind {
|
||
Fader,
|
||
Group,
|
||
Separator,
|
||
}
|
||
|
||
impl AddKind {
|
||
const ALL: [Self; 3] = [Self::Fader, Self::Group, Self::Separator];
|
||
|
||
const fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Fader => "Fader",
|
||
Self::Group => "Group",
|
||
Self::Separator => "Separator",
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct AddPicker {
|
||
selected: usize,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct NewItemEditor {
|
||
kind: AddKind,
|
||
label: String,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
struct DeleteConfirmation {
|
||
id: String,
|
||
label: String,
|
||
separator: bool,
|
||
}
|
||
|
||
enum FaderEditorRow {
|
||
Capture {
|
||
application: String,
|
||
selector: usize,
|
||
field: String,
|
||
pattern: String,
|
||
regex: bool,
|
||
},
|
||
GroupMembers {
|
||
group: String,
|
||
included: usize,
|
||
available: usize,
|
||
},
|
||
GroupMode {
|
||
mode: GroupVolumeMode,
|
||
},
|
||
BindingController {
|
||
action: &'static str,
|
||
label: &'static str,
|
||
value: String,
|
||
},
|
||
BindingLearn {
|
||
action: &'static str,
|
||
label: &'static str,
|
||
surface: Option<String>,
|
||
value: String,
|
||
},
|
||
BindingUnlearn {
|
||
action: &'static str,
|
||
label: &'static str,
|
||
configured: bool,
|
||
surface: Option<String>,
|
||
},
|
||
Visibility {
|
||
hidden: bool,
|
||
},
|
||
Density {
|
||
density: FaderDensity,
|
||
},
|
||
Save,
|
||
}
|
||
|
||
enum MixerRow<'a> {
|
||
Fader {
|
||
layout_id: Option<&'a str>,
|
||
item: &'a MixerItem,
|
||
density: FaderDensity,
|
||
},
|
||
Separator {
|
||
id: &'a str,
|
||
label: &'a str,
|
||
size: SeparatorSize,
|
||
decoration: SeparatorDecoration,
|
||
},
|
||
}
|
||
|
||
impl MixerRow<'_> {
|
||
fn id(&self) -> &str {
|
||
match self {
|
||
Self::Fader {
|
||
layout_id: Some(id),
|
||
..
|
||
}
|
||
| Self::Separator { id, .. } => id,
|
||
Self::Fader { item, .. } => &item.id.id,
|
||
}
|
||
}
|
||
|
||
const fn height(&self) -> u16 {
|
||
match self {
|
||
Self::Fader {
|
||
density: FaderDensity::Slim,
|
||
..
|
||
} => 1,
|
||
Self::Fader {
|
||
density: FaderDensity::BorderedSlim,
|
||
..
|
||
} => 3,
|
||
Self::Fader {
|
||
density: FaderDensity::Standard,
|
||
..
|
||
} => 4,
|
||
Self::Separator {
|
||
size, decoration, ..
|
||
} => match size {
|
||
SeparatorSize::Slim | SeparatorSize::Fill => {
|
||
if matches!(decoration, SeparatorDecoration::Box) {
|
||
3
|
||
} else {
|
||
1
|
||
}
|
||
}
|
||
SeparatorSize::Standard => 3,
|
||
SeparatorSize::Thick => 5,
|
||
},
|
||
Self::Fader {
|
||
density: FaderDensity::Thick,
|
||
..
|
||
} => 6,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Select a viewport using minimum extents, then share leftover cells between
|
||
/// Fill separators. Expanding a spacer must never push a fader out of view.
|
||
fn mixer_viewport(
|
||
rows: &[MixerRow<'_>],
|
||
selected: usize,
|
||
available: u16,
|
||
horizontal: bool,
|
||
) -> (usize, Vec<u16>) {
|
||
if rows.is_empty() || available == 0 {
|
||
return (0, Vec::new());
|
||
}
|
||
let extent = |row: &MixerRow<'_>| {
|
||
if !horizontal {
|
||
return row.height();
|
||
}
|
||
match row {
|
||
MixerRow::Fader { density, .. } => match density {
|
||
FaderDensity::Slim => 10,
|
||
FaderDensity::BorderedSlim => 13,
|
||
FaderDensity::Standard => 16,
|
||
FaderDensity::Thick => 22,
|
||
},
|
||
MixerRow::Separator { label, size, .. } => match size {
|
||
SeparatorSize::Slim | SeparatorSize::Fill => 3,
|
||
SeparatorSize::Standard => u16::try_from(label.chars().count())
|
||
.unwrap_or(u16::MAX)
|
||
.saturating_add(2)
|
||
.clamp(8, 18),
|
||
SeparatorSize::Thick => 22,
|
||
},
|
||
}
|
||
};
|
||
let selected = selected.min(rows.len() - 1);
|
||
let mut start = selected;
|
||
let mut used = extent(&rows[selected]).min(available);
|
||
while start > 0 && extent(&rows[start - 1]) <= available.saturating_sub(used) {
|
||
start -= 1;
|
||
used += extent(&rows[start]);
|
||
}
|
||
let mut end = selected + 1;
|
||
while end < rows.len() && extent(&rows[end]) <= available.saturating_sub(used) {
|
||
used += extent(&rows[end]);
|
||
end += 1;
|
||
}
|
||
let mut fills = rows[start..end]
|
||
.iter()
|
||
.filter(|row| {
|
||
matches!(
|
||
row,
|
||
MixerRow::Separator {
|
||
size: SeparatorSize::Fill,
|
||
..
|
||
}
|
||
)
|
||
})
|
||
.count();
|
||
let mut spare = available - used;
|
||
let extents = rows[start..end]
|
||
.iter()
|
||
.map(|row| {
|
||
let base = extent(row).min(available);
|
||
if matches!(
|
||
row,
|
||
MixerRow::Separator {
|
||
size: SeparatorSize::Fill,
|
||
..
|
||
}
|
||
) {
|
||
let extra = spare / u16::try_from(fills).unwrap_or(u16::MAX);
|
||
spare -= extra;
|
||
fills -= 1;
|
||
base + extra
|
||
} else {
|
||
base
|
||
}
|
||
})
|
||
.collect();
|
||
(start, extents)
|
||
}
|
||
|
||
impl<C: MixerClient> LiveTui<C> {
|
||
pub fn new(mut client: C) -> io::Result<Self> {
|
||
let snapshot = client.snapshot()?;
|
||
let theme = snapshot.configuration.theme;
|
||
Ok(Self::from_snapshot(client, snapshot, theme, false))
|
||
}
|
||
|
||
pub fn with_theme(mut client: C, theme: ThemeName) -> io::Result<Self> {
|
||
let snapshot = client.snapshot()?;
|
||
Ok(Self::from_snapshot(client, snapshot, theme, true))
|
||
}
|
||
|
||
fn from_snapshot(
|
||
client: C,
|
||
snapshot: MixerSnapshot,
|
||
theme: ThemeName,
|
||
theme_override: bool,
|
||
) -> Self {
|
||
Self {
|
||
client,
|
||
snapshot,
|
||
selected: 0,
|
||
theme,
|
||
theme_override,
|
||
exit: false,
|
||
quit_confirmation: false,
|
||
reset_confirmation: false,
|
||
add_picker: None,
|
||
new_item_editor: None,
|
||
delete_confirmation: None,
|
||
show_help: false,
|
||
client_error: None,
|
||
tab: Tab::Mixer,
|
||
editor: None,
|
||
settings_selected: 0,
|
||
fader_editor: None,
|
||
capture_editor: None,
|
||
pattern_editor: None,
|
||
controller_picker: None,
|
||
group_member_picker: None,
|
||
hidden_fader_picker: None,
|
||
profile_picker: None,
|
||
midi_device_details: None,
|
||
controller_selections: BTreeMap::new(),
|
||
}
|
||
}
|
||
|
||
#[must_use]
|
||
pub const fn theme(&self) -> ThemeName {
|
||
self.theme
|
||
}
|
||
|
||
pub fn run(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
|
||
while !self.exit {
|
||
self.refresh();
|
||
terminal.draw(|frame| self.draw(frame))?;
|
||
if event::poll(REFRESH_INTERVAL)?
|
||
&& let Event::Key(key_event) = event::read()?
|
||
&& key_event.kind == KeyEventKind::Press
|
||
{
|
||
self.handle_key_event(key_event);
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn refresh(&mut self) {
|
||
match self.client.snapshot() {
|
||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
|
||
fn replace_snapshot(&mut self, snapshot: MixerSnapshot) {
|
||
let selected_id = self.selected_layout_id();
|
||
self.client_error.clone_from(&snapshot.error);
|
||
if self.theme_override {
|
||
if snapshot.configuration.theme == self.theme {
|
||
self.theme_override = false;
|
||
}
|
||
} else {
|
||
self.theme = snapshot.configuration.theme;
|
||
}
|
||
self.snapshot = snapshot;
|
||
self.selected = selected_id
|
||
.and_then(|id| self.mixer_rows().iter().position(|row| row.id() == id))
|
||
.unwrap_or_else(|| self.selected.min(self.mixer_rows().len().saturating_sub(1)));
|
||
self.settings_selected = self
|
||
.settings_selected
|
||
.min(self.settings_rows().len().saturating_sub(1));
|
||
}
|
||
|
||
fn mixer_rows(&self) -> Vec<MixerRow<'_>> {
|
||
if self.snapshot.configuration.mixer_layout.is_empty() {
|
||
return self
|
||
.snapshot
|
||
.items
|
||
.iter()
|
||
.map(|item| MixerRow::Fader {
|
||
layout_id: None,
|
||
item,
|
||
density: FaderDensity::Standard,
|
||
})
|
||
.collect();
|
||
}
|
||
|
||
self.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.filter_map(|entry| match entry {
|
||
MixerLayoutEntry::Fader {
|
||
fader,
|
||
hidden: false,
|
||
density,
|
||
} => {
|
||
let target = self
|
||
.snapshot
|
||
.configuration
|
||
.faders
|
||
.iter()
|
||
.find(|configured| configured.id == *fader)
|
||
.map(|configured| &configured.target)?;
|
||
let item = self.snapshot.items.iter().find(|item| item.id == *target)?;
|
||
Some(MixerRow::Fader {
|
||
layout_id: Some(fader),
|
||
item,
|
||
density: *density,
|
||
})
|
||
}
|
||
MixerLayoutEntry::Separator {
|
||
id,
|
||
label,
|
||
size,
|
||
decoration,
|
||
} => Some(MixerRow::Separator {
|
||
id,
|
||
label,
|
||
size: *size,
|
||
decoration: *decoration,
|
||
}),
|
||
_ => None,
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
fn selected_layout_id(&self) -> Option<String> {
|
||
self.mixer_rows()
|
||
.get(self.selected)
|
||
.map(|row| row.id().to_owned())
|
||
}
|
||
|
||
fn draw(&self, frame: &mut Frame) {
|
||
frame.render_widget(self, frame.area());
|
||
}
|
||
|
||
fn handle_key_event(&mut self, key_event: KeyEvent) {
|
||
if self.delete_confirmation.is_some() {
|
||
self.handle_delete_confirmation_key(key_event.code);
|
||
return;
|
||
}
|
||
if self.new_item_editor.is_some() {
|
||
self.handle_new_item_editor_key(key_event.code);
|
||
return;
|
||
}
|
||
if self.add_picker.is_some() {
|
||
self.handle_add_picker_key(key_event.code);
|
||
return;
|
||
}
|
||
if self.reset_confirmation {
|
||
match key_event.code {
|
||
KeyCode::Char('y' | 'Y') => {
|
||
self.reset_confirmation = false;
|
||
match self
|
||
.client
|
||
.reset_configuration(self.snapshot.configuration.revision)
|
||
{
|
||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
KeyCode::Char('n' | 'N') | KeyCode::Esc => self.reset_confirmation = false,
|
||
_ => {}
|
||
}
|
||
return;
|
||
}
|
||
if self.quit_confirmation {
|
||
match key_event.code {
|
||
KeyCode::Char('y' | 'Y') => self.exit = true,
|
||
KeyCode::Char('n' | 'N') | KeyCode::Esc => self.quit_confirmation = false,
|
||
_ => {}
|
||
}
|
||
return;
|
||
}
|
||
if self.show_help {
|
||
if matches!(key_event.code, KeyCode::Esc | KeyCode::Char('h' | '?')) {
|
||
self.show_help = false;
|
||
}
|
||
return;
|
||
}
|
||
if self.snapshot.configuration.learning.is_some() {
|
||
if matches!(key_event.code, KeyCode::Esc | KeyCode::Char('c')) {
|
||
self.cancel_midi_learn();
|
||
}
|
||
return;
|
||
}
|
||
if self.pattern_editor.is_some() {
|
||
self.handle_pattern_key(key_event.code);
|
||
return;
|
||
}
|
||
if self.capture_editor.is_some() {
|
||
self.handle_capture_key(key_event.code);
|
||
return;
|
||
}
|
||
if self.controller_picker.is_some() {
|
||
self.handle_controller_picker_key(key_event.code);
|
||
return;
|
||
}
|
||
if self.group_member_picker.is_some() {
|
||
self.handle_group_member_picker_key(key_event.code);
|
||
return;
|
||
}
|
||
if self.hidden_fader_picker.is_some() {
|
||
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;
|
||
}
|
||
if self.fader_editor.is_some() {
|
||
self.handle_fader_editor_key(key_event.code);
|
||
return;
|
||
}
|
||
if self.editor.is_some() {
|
||
self.handle_editor_key(key_event.code);
|
||
return;
|
||
}
|
||
match key_event.code {
|
||
KeyCode::Char('h' | '?') => self.show_help = true,
|
||
KeyCode::Char('t') => self.change_theme(self.theme.next()),
|
||
KeyCode::Tab => {
|
||
self.tab = match self.tab {
|
||
Tab::Mixer => Tab::Configuration,
|
||
Tab::Configuration => Tab::Mixer,
|
||
};
|
||
self.clamp_selection();
|
||
}
|
||
KeyCode::Char('1') => {
|
||
self.tab = Tab::Mixer;
|
||
self.clamp_selection();
|
||
}
|
||
KeyCode::Char('2') => {
|
||
self.tab = Tab::Configuration;
|
||
self.clamp_selection();
|
||
}
|
||
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),
|
||
},
|
||
}
|
||
}
|
||
|
||
fn clamp_selection(&mut self) {
|
||
match self.tab {
|
||
Tab::Mixer => {
|
||
self.selected = self.selected.min(self.mixer_rows().len().saturating_sub(1));
|
||
}
|
||
Tab::Configuration => {
|
||
self.settings_selected = self
|
||
.settings_selected
|
||
.min(self.settings_rows().len().saturating_sub(1));
|
||
}
|
||
}
|
||
}
|
||
|
||
fn handle_mixer_key(&mut self, key_event: KeyEvent) {
|
||
let horizontal =
|
||
self.snapshot.configuration.mixer_orientation == MixerOrientation::Horizontal;
|
||
if key_event.modifiers.contains(KeyModifiers::SHIFT) {
|
||
match (horizontal, key_event.code) {
|
||
(_, KeyCode::Char('H' | 'h')) => self.toggle_selected_visibility(),
|
||
(_, KeyCode::Char('K' | 'k')) => self.move_selected_layout(-1),
|
||
(_, KeyCode::Char('J' | 'j')) => self.move_selected_layout(1),
|
||
(true, KeyCode::Left) | (false, KeyCode::Up) => {
|
||
self.move_selected_layout(-1);
|
||
}
|
||
(true, KeyCode::Right) | (false, KeyCode::Down) => {
|
||
self.move_selected_layout(1);
|
||
}
|
||
_ => {}
|
||
}
|
||
return;
|
||
}
|
||
|
||
match (horizontal, key_event.code) {
|
||
(true, KeyCode::Right) | (false, KeyCode::Down) => {
|
||
self.select_next_mixer_entry();
|
||
return;
|
||
}
|
||
(true, KeyCode::Left) | (false, KeyCode::Up) => {
|
||
self.select_previous_mixer_entry();
|
||
return;
|
||
}
|
||
(true, KeyCode::Up) | (false, KeyCode::Right) => {
|
||
self.change_volume(VOLUME_STEP);
|
||
return;
|
||
}
|
||
(true, KeyCode::Down) | (false, KeyCode::Left) => {
|
||
self.change_volume(-VOLUME_STEP);
|
||
return;
|
||
}
|
||
_ => {}
|
||
}
|
||
|
||
match key_event.code {
|
||
KeyCode::Char('j') => self.select_next_mixer_entry(),
|
||
KeyCode::Char('k') => self.select_previous_mixer_entry(),
|
||
KeyCode::Char('-') => self.change_volume(-VOLUME_STEP),
|
||
KeyCode::Char('+') | KeyCode::Char('=') => {
|
||
self.change_volume(VOLUME_STEP);
|
||
}
|
||
KeyCode::Home => self.set_selected_volume(0.0),
|
||
KeyCode::End => self.set_selected_volume(1.0),
|
||
KeyCode::Char('m') => self.toggle_selected_mute(),
|
||
KeyCode::Char('H') => self.toggle_selected_visibility(),
|
||
KeyCode::Char('a') => {
|
||
self.add_picker = Some(AddPicker { selected: 0 });
|
||
self.client_error = None;
|
||
}
|
||
KeyCode::Char('e') => self.edit_selected_entry(),
|
||
KeyCode::Char('d') => self.start_delete_selected_entry(),
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn select_next_mixer_entry(&mut self) {
|
||
self.selected = (self.selected + 1).min(self.mixer_rows().len().saturating_sub(1));
|
||
}
|
||
|
||
fn select_previous_mixer_entry(&mut self) {
|
||
self.selected = self.selected.saturating_sub(1);
|
||
}
|
||
|
||
fn start_separator_editor(&mut self) {
|
||
self.editor = Some(EditorInput {
|
||
value: String::new(),
|
||
target: None,
|
||
..EditorInput::default()
|
||
});
|
||
self.client_error = None;
|
||
}
|
||
|
||
fn handle_add_picker_key(&mut self, code: KeyCode) {
|
||
let Some(picker) = &mut self.add_picker else {
|
||
return;
|
||
};
|
||
match code {
|
||
KeyCode::Esc => self.add_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(AddKind::ALL.len() - 1);
|
||
}
|
||
KeyCode::Enter => {
|
||
let kind = AddKind::ALL[picker.selected];
|
||
self.add_picker = None;
|
||
if kind == AddKind::Separator {
|
||
self.start_separator_editor();
|
||
} else {
|
||
self.new_item_editor = Some(NewItemEditor {
|
||
kind,
|
||
label: String::new(),
|
||
});
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn handle_new_item_editor_key(&mut self, code: KeyCode) {
|
||
match code {
|
||
KeyCode::Esc => self.new_item_editor = None,
|
||
KeyCode::Backspace => {
|
||
if let Some(editor) = &mut self.new_item_editor {
|
||
editor.label.pop();
|
||
}
|
||
}
|
||
KeyCode::Enter => self.submit_new_item(),
|
||
KeyCode::Char(character) => {
|
||
if let Some(editor) = &mut self.new_item_editor {
|
||
editor.label.push(character);
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn submit_new_item(&mut self) {
|
||
let Some(editor) = &self.new_item_editor else {
|
||
return;
|
||
};
|
||
let label = editor.label.trim();
|
||
if label.is_empty() {
|
||
self.client_error = Some("a fader or group name is required".to_owned());
|
||
return;
|
||
}
|
||
let kind = editor.kind;
|
||
let base = mixer_object_id(label);
|
||
let position = self.layout_position_after_selected();
|
||
let fader_id = unique_configured_id(
|
||
&format!("{base}-fader"),
|
||
self.snapshot
|
||
.configuration
|
||
.faders
|
||
.iter()
|
||
.map(|fader| fader.id.as_str()),
|
||
);
|
||
let (edit, target_id) = match kind {
|
||
AddKind::Fader => {
|
||
let application_id = unique_configured_id(
|
||
&base,
|
||
self.snapshot
|
||
.configuration
|
||
.applications
|
||
.iter()
|
||
.map(|application| application.id.as_str()),
|
||
);
|
||
let pattern = format!("__fader_master_unconfigured_{application_id}__");
|
||
(
|
||
ConfigurationEdit::AddApplicationFader {
|
||
application_id: application_id.clone(),
|
||
label: label.to_owned(),
|
||
field: "application.name".to_owned(),
|
||
pattern,
|
||
regex: false,
|
||
fader_id: fader_id.clone(),
|
||
position,
|
||
},
|
||
application_id,
|
||
)
|
||
}
|
||
AddKind::Group => {
|
||
let group_id = unique_configured_id(
|
||
&base,
|
||
self.snapshot
|
||
.configuration
|
||
.groups
|
||
.iter()
|
||
.map(|group| group.id.as_str()),
|
||
);
|
||
(
|
||
ConfigurationEdit::AddGroupFader {
|
||
group_id: group_id.clone(),
|
||
label: label.to_owned(),
|
||
fader_id: fader_id.clone(),
|
||
position,
|
||
},
|
||
group_id,
|
||
)
|
||
}
|
||
AddKind::Separator => return,
|
||
};
|
||
match self
|
||
.client
|
||
.edit_configuration(edit, self.snapshot.configuration.revision)
|
||
{
|
||
Ok(snapshot) => {
|
||
self.new_item_editor = None;
|
||
self.replace_snapshot(snapshot);
|
||
self.selected = self
|
||
.mixer_rows()
|
||
.iter()
|
||
.position(|row| row.id() == fader_id)
|
||
.unwrap_or(self.selected);
|
||
self.fader_editor = Some(FaderEditor {
|
||
fader: fader_id,
|
||
selected: 0,
|
||
});
|
||
self.client_error = None;
|
||
}
|
||
Err(error) => {
|
||
self.client_error = Some(format!("could not add {target_id:?}: {error}"));
|
||
}
|
||
}
|
||
}
|
||
|
||
fn layout_position_after_selected(&self) -> usize {
|
||
let Some(id) = self.selected_layout_id() else {
|
||
return self.snapshot.configuration.mixer_layout.len();
|
||
};
|
||
self.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.position(|entry| match entry {
|
||
MixerLayoutEntry::Fader { fader, .. } => fader == &id,
|
||
MixerLayoutEntry::Separator { id: separator, .. } => separator == &id,
|
||
})
|
||
.map_or(self.snapshot.configuration.mixer_layout.len(), |index| {
|
||
index + 1
|
||
})
|
||
}
|
||
|
||
fn edit_selected_entry(&mut self) {
|
||
enum Selected {
|
||
Fader(String),
|
||
Separator(String, String, SeparatorSize, SeparatorDecoration),
|
||
}
|
||
let selected = self
|
||
.mixer_rows()
|
||
.get(self.selected)
|
||
.and_then(|row| match row {
|
||
MixerRow::Fader {
|
||
layout_id: Some(id),
|
||
..
|
||
} => Some(Selected::Fader((*id).to_owned())),
|
||
MixerRow::Separator {
|
||
id,
|
||
label,
|
||
size,
|
||
decoration,
|
||
} => Some(Selected::Separator(
|
||
(*id).to_owned(),
|
||
(*label).to_owned(),
|
||
*size,
|
||
*decoration,
|
||
)),
|
||
MixerRow::Fader {
|
||
layout_id: None, ..
|
||
} => None,
|
||
});
|
||
match selected {
|
||
Some(Selected::Fader(fader)) => {
|
||
self.fader_editor = Some(FaderEditor { fader, selected: 0 });
|
||
}
|
||
Some(Selected::Separator(id, label, size, decoration)) => {
|
||
self.editor = Some(EditorInput {
|
||
value: label,
|
||
target: Some(id),
|
||
size,
|
||
decoration,
|
||
selected: 0,
|
||
});
|
||
}
|
||
None => return,
|
||
}
|
||
self.client_error = None;
|
||
}
|
||
|
||
fn handle_editor_key(&mut self, code: KeyCode) {
|
||
if let Some(editor) = &mut self.editor {
|
||
match code {
|
||
KeyCode::Up => {
|
||
editor.selected = editor.selected.saturating_sub(1);
|
||
return;
|
||
}
|
||
KeyCode::Down | KeyCode::Tab => {
|
||
editor.selected = (editor.selected + 1) % 3;
|
||
return;
|
||
}
|
||
KeyCode::Left | KeyCode::Right if editor.selected > 0 => {
|
||
let forward = code == KeyCode::Right;
|
||
if editor.selected == 1 {
|
||
editor.size = editor.size.cycle(forward);
|
||
} else {
|
||
editor.decoration = editor.decoration.cycle(forward);
|
||
}
|
||
return;
|
||
}
|
||
KeyCode::Char(_) | KeyCode::Backspace if editor.selected != 0 => return,
|
||
_ => {}
|
||
}
|
||
}
|
||
match code {
|
||
KeyCode::Esc => self.editor = None,
|
||
KeyCode::Backspace => {
|
||
if let Some(editor) = &mut self.editor {
|
||
editor.value.pop();
|
||
}
|
||
}
|
||
KeyCode::Enter => self.submit_editor(),
|
||
KeyCode::Char(character) => {
|
||
if let Some(editor) = &mut self.editor {
|
||
editor.value.push(character);
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn submit_editor(&mut self) {
|
||
let Some(editor) = self.editor.take() else {
|
||
return;
|
||
};
|
||
let label = editor.value.trim();
|
||
let id = editor.target.clone().unwrap_or_else(|| {
|
||
unique_separator_id(label, &self.snapshot.configuration.mixer_layout)
|
||
});
|
||
let edit = editor.target.map_or_else(
|
||
|| ConfigurationEdit::AddSeparator {
|
||
id: id.clone(),
|
||
label: label.to_owned(),
|
||
position: self.selected.saturating_add(1),
|
||
},
|
||
|id| ConfigurationEdit::SetSeparatorLabel {
|
||
id,
|
||
label: label.to_owned(),
|
||
},
|
||
);
|
||
match self
|
||
.client
|
||
.edit_configuration(edit, self.snapshot.configuration.revision)
|
||
{
|
||
Ok(snapshot) => {
|
||
self.replace_snapshot(snapshot);
|
||
self.apply_layout_edit(ConfigurationEdit::SetSeparatorPresentation {
|
||
id,
|
||
size: editor.size,
|
||
decoration: editor.decoration,
|
||
});
|
||
}
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
|
||
fn settings_rows(&self) -> Vec<SettingsRow> {
|
||
let mut rows = vec![
|
||
SettingsRow::Theme,
|
||
SettingsRow::MixerOrientation,
|
||
SettingsRow::StatusDisplay,
|
||
SettingsRow::DefaultController,
|
||
SettingsRow::HiddenFaders {
|
||
count: self.hidden_faders().len(),
|
||
},
|
||
SettingsRow::ActiveProfile,
|
||
];
|
||
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.push(SettingsRow::Reset);
|
||
rows.extend(
|
||
self.snapshot
|
||
.devices
|
||
.iter()
|
||
.map(|device| SettingsRow::MidiDevice {
|
||
id: device.id.clone(),
|
||
}),
|
||
);
|
||
rows.extend(self.snapshot.discovered_midi_ports.iter().map(|port| {
|
||
SettingsRow::DiscoveredMidiPort {
|
||
backend_id: port.backend_id.clone(),
|
||
}
|
||
}));
|
||
rows
|
||
}
|
||
|
||
fn handle_settings_key(&mut self, code: KeyCode) {
|
||
let row_count = self.settings_rows().len();
|
||
match code {
|
||
KeyCode::Up | KeyCode::Char('k') => {
|
||
self.settings_selected = self.settings_selected.saturating_sub(1);
|
||
}
|
||
KeyCode::Down | KeyCode::Char('j') => {
|
||
self.settings_selected =
|
||
(self.settings_selected + 1).min(row_count.saturating_sub(1));
|
||
}
|
||
KeyCode::Left => self.activate_settings_row(false),
|
||
KeyCode::Right | KeyCode::Enter => self.activate_settings_row(true),
|
||
KeyCode::Char('c') if self.snapshot.configuration.learning.is_some() => {
|
||
self.cancel_midi_learn()
|
||
}
|
||
KeyCode::Char('s') => self.save_configuration(),
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn activate_settings_row(&mut self, forward: bool) {
|
||
let Some(row) = self.settings_rows().into_iter().nth(self.settings_selected) else {
|
||
return;
|
||
};
|
||
match row {
|
||
SettingsRow::Theme => {
|
||
let theme = if forward {
|
||
self.theme.next()
|
||
} else {
|
||
self.theme.previous()
|
||
};
|
||
self.change_theme(theme);
|
||
}
|
||
SettingsRow::MixerOrientation => {
|
||
self.apply_layout_edit(ConfigurationEdit::SetMixerOrientation {
|
||
orientation: self.snapshot.configuration.mixer_orientation.toggled(),
|
||
});
|
||
}
|
||
SettingsRow::StatusDisplay => {
|
||
let mode = if forward {
|
||
self.snapshot.configuration.status_display.next()
|
||
} else {
|
||
self.snapshot.configuration.status_display.previous()
|
||
};
|
||
self.apply_layout_edit(ConfigurationEdit::SetStatusDisplay { mode });
|
||
}
|
||
SettingsRow::DefaultController => {
|
||
let devices = &self.snapshot.devices;
|
||
let current = self.snapshot.configuration.default_controller.as_deref();
|
||
let next = if devices.is_empty() {
|
||
None
|
||
} else if forward {
|
||
current
|
||
.and_then(|id| devices.iter().position(|device| device.id == id))
|
||
.and_then(|index| devices.get(index + 1))
|
||
.map(|device| device.id.clone())
|
||
.or_else(|| current.is_none().then(|| devices[0].id.clone()))
|
||
} else {
|
||
current
|
||
.and_then(|id| devices.iter().position(|device| device.id == id))
|
||
.and_then(|index| index.checked_sub(1))
|
||
.and_then(|index| devices.get(index))
|
||
.map(|device| device.id.clone())
|
||
.or_else(|| {
|
||
current
|
||
.is_none()
|
||
.then(|| devices[devices.len() - 1].id.clone())
|
||
})
|
||
};
|
||
self.apply_layout_edit(ConfigurationEdit::SetDefaultController { surface: next });
|
||
}
|
||
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::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::Reset if forward => self.reset_confirmation = true,
|
||
SettingsRow::MidiDevice { id } if forward => {
|
||
self.midi_device_details = Some(id);
|
||
}
|
||
SettingsRow::DiscoveredMidiPort { backend_id } if forward => {
|
||
self.midi_device_details = Some(backend_id);
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn hidden_faders(&self) -> Vec<(String, String)> {
|
||
self.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.filter_map(|entry| match entry {
|
||
MixerLayoutEntry::Fader {
|
||
fader,
|
||
hidden: true,
|
||
..
|
||
} => {
|
||
let label = self
|
||
.snapshot
|
||
.configuration
|
||
.faders
|
||
.iter()
|
||
.find(|configured| configured.id == *fader)
|
||
.and_then(|configured| {
|
||
self.snapshot
|
||
.items
|
||
.iter()
|
||
.find(|item| item.id == configured.target)
|
||
})
|
||
.map_or_else(|| fader.clone(), |item| item.label.clone());
|
||
Some((fader.clone(), label))
|
||
}
|
||
_ => None,
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
fn handle_hidden_fader_picker_key(&mut self, code: KeyCode) {
|
||
let hidden_faders = self.hidden_faders();
|
||
let Some(picker) = &mut self.hidden_fader_picker else {
|
||
return;
|
||
};
|
||
if hidden_faders.is_empty() {
|
||
self.hidden_fader_picker = None;
|
||
return;
|
||
}
|
||
match code {
|
||
KeyCode::Esc => self.hidden_fader_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(hidden_faders.len().saturating_sub(1));
|
||
}
|
||
KeyCode::Enter => {
|
||
let Some((id, _)) = hidden_faders.get(picker.selected).cloned() else {
|
||
return;
|
||
};
|
||
self.apply_layout_edit(ConfigurationEdit::SetFaderHidden { id, hidden: false });
|
||
let remaining = self.hidden_faders().len();
|
||
if remaining == 0 {
|
||
self.hidden_fader_picker = None;
|
||
} else if let Some(picker) = &mut self.hidden_fader_picker {
|
||
picker.selected = picker.selected.min(remaining - 1);
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
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;
|
||
};
|
||
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;
|
||
}
|
||
return;
|
||
}
|
||
let is_default = self.snapshot.configuration.default_controller.as_deref() == Some(&id);
|
||
let make_default = match code {
|
||
KeyCode::Esc => {
|
||
self.midi_device_details = None;
|
||
return;
|
||
}
|
||
KeyCode::Left => false,
|
||
KeyCode::Right => true,
|
||
KeyCode::Enter => !is_default,
|
||
_ => return,
|
||
};
|
||
if make_default == is_default {
|
||
return;
|
||
}
|
||
self.apply_layout_edit(ConfigurationEdit::SetDefaultController {
|
||
surface: make_default.then_some(id),
|
||
});
|
||
}
|
||
|
||
fn cancel_midi_learn(&mut self) {
|
||
match self.client.cancel_midi_learn() {
|
||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
|
||
fn change_theme(&mut self, theme: ThemeName) {
|
||
self.theme = theme;
|
||
self.theme_override = true;
|
||
self.apply_layout_edit(ConfigurationEdit::SetTheme { theme });
|
||
}
|
||
|
||
fn save_configuration(&mut self) {
|
||
match self
|
||
.client
|
||
.save_configuration(self.snapshot.configuration.revision)
|
||
{
|
||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
|
||
fn fader_editor_rows(&self) -> Vec<FaderEditorRow> {
|
||
let Some(editor) = &self.fader_editor else {
|
||
return Vec::new();
|
||
};
|
||
let Some(fader) = self
|
||
.snapshot
|
||
.configuration
|
||
.faders
|
||
.iter()
|
||
.find(|fader| fader.id == editor.fader)
|
||
else {
|
||
return Vec::new();
|
||
};
|
||
let mut rows = Vec::new();
|
||
match fader.target.kind {
|
||
MixerObjectKind::Application => {
|
||
if let Some(application) = self
|
||
.snapshot
|
||
.configuration
|
||
.applications
|
||
.iter()
|
||
.find(|application| application.id == fader.target.id)
|
||
{
|
||
rows.extend(application.selectors.iter().enumerate().map(
|
||
|(selector, capture)| FaderEditorRow::Capture {
|
||
application: application.id.clone(),
|
||
selector,
|
||
field: capture.field.clone(),
|
||
pattern: capture.pattern.clone(),
|
||
regex: capture.regex,
|
||
},
|
||
));
|
||
}
|
||
}
|
||
MixerObjectKind::Group => {
|
||
if let Some(group) = self
|
||
.snapshot
|
||
.configuration
|
||
.groups
|
||
.iter()
|
||
.find(|group| group.id == fader.target.id)
|
||
{
|
||
let choices = self.group_member_choices(&group.id);
|
||
rows.push(FaderEditorRow::GroupMembers {
|
||
group: group.id.clone(),
|
||
included: choices.iter().filter(|choice| choice.included).count(),
|
||
available: choices.len(),
|
||
});
|
||
rows.push(FaderEditorRow::GroupMode {
|
||
mode: group.volume_mode,
|
||
});
|
||
}
|
||
}
|
||
MixerObjectKind::Output => {}
|
||
}
|
||
for (action, label) in [("volume", "volume"), ("toggle_mute", "mute")] {
|
||
let binding = self
|
||
.snapshot
|
||
.configuration
|
||
.bindings
|
||
.iter()
|
||
.find(|binding| binding.fader == editor.fader && binding.action == action);
|
||
let key = (editor.fader.clone(), action.to_owned());
|
||
let inherited_default = !self.controller_selections.contains_key(&key)
|
||
&& binding.is_none()
|
||
&& self.snapshot.configuration.default_controller.is_some();
|
||
let surface = self
|
||
.controller_selections
|
||
.get(&key)
|
||
.cloned()
|
||
.or_else(|| binding.map(|binding| binding.surface.clone()))
|
||
.or_else(|| self.snapshot.configuration.default_controller.clone());
|
||
let mut controller = surface.as_deref().map_or_else(
|
||
|| "Not selected".to_owned(),
|
||
|surface| {
|
||
self.snapshot
|
||
.devices
|
||
.iter()
|
||
.find(|device| device.id == surface)
|
||
.map_or_else(|| surface.to_owned(), |device| device.label.clone())
|
||
},
|
||
);
|
||
if inherited_default {
|
||
controller = format!("Default · {controller}");
|
||
}
|
||
let message = binding.map_or_else(
|
||
|| "Unassigned".to_owned(),
|
||
|binding| binding.message.clone(),
|
||
);
|
||
rows.push(FaderEditorRow::BindingController {
|
||
action,
|
||
label,
|
||
value: controller,
|
||
});
|
||
rows.push(FaderEditorRow::BindingLearn {
|
||
action,
|
||
label,
|
||
surface: surface.clone(),
|
||
value: message,
|
||
});
|
||
rows.push(FaderEditorRow::BindingUnlearn {
|
||
action,
|
||
label,
|
||
configured: binding.is_some(),
|
||
surface,
|
||
});
|
||
}
|
||
let (hidden, density) = self
|
||
.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.find_map(|entry| match entry {
|
||
MixerLayoutEntry::Fader {
|
||
fader: id,
|
||
hidden,
|
||
density,
|
||
} if id == &editor.fader => Some((*hidden, *density)),
|
||
_ => None,
|
||
})
|
||
.unwrap_or((false, FaderDensity::Standard));
|
||
rows.push(FaderEditorRow::Density { density });
|
||
rows.push(FaderEditorRow::Visibility { hidden });
|
||
if self.snapshot.configuration.dirty {
|
||
rows.push(FaderEditorRow::Save);
|
||
}
|
||
rows
|
||
}
|
||
|
||
fn group_member_choices(&self, group: &str) -> Vec<GroupMemberChoice> {
|
||
let members = self
|
||
.snapshot
|
||
.configuration
|
||
.groups
|
||
.iter()
|
||
.find(|candidate| candidate.id == group)
|
||
.map(|configured| configured.members.as_slice())
|
||
.unwrap_or_default();
|
||
let mut seen = std::collections::BTreeSet::new();
|
||
self.snapshot
|
||
.configuration
|
||
.faders
|
||
.iter()
|
||
.filter_map(|fader| {
|
||
if fader.target.kind != MixerObjectKind::Application
|
||
|| !seen.insert(fader.target.id.as_str())
|
||
{
|
||
return None;
|
||
}
|
||
let label = self
|
||
.snapshot
|
||
.configuration
|
||
.applications
|
||
.iter()
|
||
.find(|application| application.id == fader.target.id)
|
||
.map_or_else(
|
||
|| fader.target.id.clone(),
|
||
|application| application.label.clone(),
|
||
);
|
||
Some(GroupMemberChoice {
|
||
application: fader.target.id.clone(),
|
||
fader: fader.id.clone(),
|
||
label,
|
||
included: members.contains(&fader.target.id),
|
||
})
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
fn handle_fader_editor_key(&mut self, code: KeyCode) {
|
||
if code == KeyCode::Esc {
|
||
self.fader_editor = None;
|
||
return;
|
||
}
|
||
let row_count = self.fader_editor_rows().len();
|
||
let Some(editor) = &mut self.fader_editor else {
|
||
return;
|
||
};
|
||
match code {
|
||
KeyCode::Up | KeyCode::Char('k') => editor.selected = editor.selected.saturating_sub(1),
|
||
KeyCode::Down | KeyCode::Char('j') => {
|
||
editor.selected = (editor.selected + 1).min(row_count.saturating_sub(1));
|
||
}
|
||
KeyCode::Enter => self.activate_fader_editor_row(),
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn activate_fader_editor_row(&mut self) {
|
||
let Some(editor) = &self.fader_editor else {
|
||
return;
|
||
};
|
||
let fader = editor.fader.clone();
|
||
let Some(row) = self.fader_editor_rows().into_iter().nth(editor.selected) else {
|
||
return;
|
||
};
|
||
match row {
|
||
FaderEditorRow::Capture {
|
||
application,
|
||
selector,
|
||
field,
|
||
pattern,
|
||
regex,
|
||
} => {
|
||
self.capture_editor = Some(CaptureEditor {
|
||
application,
|
||
selector,
|
||
field: selector_field_index(&field),
|
||
regex,
|
||
pattern,
|
||
selected: 0,
|
||
});
|
||
}
|
||
FaderEditorRow::GroupMembers { group, .. } => {
|
||
self.group_member_picker = Some(GroupMemberPicker { group, selected: 0 });
|
||
}
|
||
FaderEditorRow::BindingController { action, .. } => {
|
||
if self.snapshot.devices.is_empty() {
|
||
self.client_error = Some("no configured MIDI surface is available".to_owned());
|
||
} else {
|
||
let selected = self
|
||
.controller_selections
|
||
.get(&(fader.clone(), action.to_owned()))
|
||
.or_else(|| {
|
||
self.snapshot
|
||
.configuration
|
||
.bindings
|
||
.iter()
|
||
.find(|binding| binding.fader == fader && binding.action == action)
|
||
.map(|binding| &binding.surface)
|
||
})
|
||
.and_then(|surface| {
|
||
self.snapshot
|
||
.devices
|
||
.iter()
|
||
.position(|device| device.id == *surface)
|
||
})
|
||
.unwrap_or(0);
|
||
self.controller_picker = Some(ControllerPicker {
|
||
fader,
|
||
action: action.to_owned(),
|
||
selected,
|
||
});
|
||
}
|
||
}
|
||
FaderEditorRow::BindingLearn {
|
||
action, surface, ..
|
||
} => {
|
||
let Some(surface) = surface else {
|
||
self.client_error = Some("choose a controller before learning MIDI".to_owned());
|
||
return;
|
||
};
|
||
match self
|
||
.client
|
||
.start_midi_learn(surface, fader, action.to_owned())
|
||
{
|
||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
FaderEditorRow::BindingUnlearn {
|
||
action,
|
||
configured: true,
|
||
surface,
|
||
..
|
||
} => {
|
||
if let Some(surface) = surface {
|
||
self.controller_selections
|
||
.insert((fader.clone(), action.to_owned()), surface);
|
||
}
|
||
self.apply_layout_edit(ConfigurationEdit::RemoveBinding {
|
||
fader,
|
||
action: action.to_owned(),
|
||
});
|
||
}
|
||
FaderEditorRow::Visibility { hidden } => {
|
||
self.apply_layout_edit(ConfigurationEdit::SetFaderHidden {
|
||
id: fader,
|
||
hidden: !hidden,
|
||
});
|
||
}
|
||
FaderEditorRow::Density { density } => {
|
||
self.apply_layout_edit(ConfigurationEdit::SetFaderDensity {
|
||
id: fader,
|
||
density: density.next(),
|
||
});
|
||
}
|
||
FaderEditorRow::Save => {
|
||
self.save_configuration();
|
||
if !self.snapshot.configuration.dirty {
|
||
self.fader_editor = None;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn handle_group_member_picker_key(&mut self, code: KeyCode) {
|
||
if code == KeyCode::Esc {
|
||
self.group_member_picker = None;
|
||
return;
|
||
}
|
||
let Some(picker) = &self.group_member_picker else {
|
||
return;
|
||
};
|
||
let group = picker.group.clone();
|
||
let choices = self.group_member_choices(&group);
|
||
let Some(picker) = &mut self.group_member_picker else {
|
||
return;
|
||
};
|
||
match code {
|
||
KeyCode::Up | KeyCode::Char('k') => {
|
||
picker.selected = picker.selected.saturating_sub(1);
|
||
}
|
||
KeyCode::Down | KeyCode::Char('j') => {
|
||
picker.selected = (picker.selected + 1).min(choices.len().saturating_sub(1));
|
||
}
|
||
KeyCode::Enter | KeyCode::Char(' ') => {
|
||
let Some(choice) = choices.get(picker.selected) else {
|
||
return;
|
||
};
|
||
self.toggle_group_member(&group, choice);
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn toggle_group_member(&mut self, group: &str, choice: &GroupMemberChoice) {
|
||
let Some(configured) = self
|
||
.snapshot
|
||
.configuration
|
||
.groups
|
||
.iter()
|
||
.find(|candidate| candidate.id == group)
|
||
else {
|
||
return;
|
||
};
|
||
let mut members = configured.members.clone();
|
||
if choice.included {
|
||
members.retain(|member| member != &choice.application);
|
||
} else {
|
||
members.push(choice.application.clone());
|
||
}
|
||
self.apply_layout_edit(ConfigurationEdit::Group {
|
||
existing: true,
|
||
id: configured.id.clone(),
|
||
label: configured.label.clone(),
|
||
members,
|
||
});
|
||
}
|
||
|
||
fn handle_capture_key(&mut self, code: KeyCode) {
|
||
if code == KeyCode::Esc {
|
||
self.capture_editor = None;
|
||
return;
|
||
}
|
||
let Some(editor) = &mut self.capture_editor else {
|
||
return;
|
||
};
|
||
match code {
|
||
KeyCode::Up => editor.selected = editor.selected.saturating_sub(1),
|
||
KeyCode::Down => editor.selected = (editor.selected + 1).min(2),
|
||
KeyCode::Left if editor.selected == 0 => editor.field = editor.field.saturating_sub(1),
|
||
KeyCode::Right if editor.selected == 0 => editor.field = (editor.field + 1).min(3),
|
||
KeyCode::Left | KeyCode::Right if editor.selected == 1 => editor.regex = !editor.regex,
|
||
KeyCode::Enter if editor.selected < 2 => editor.selected += 1,
|
||
KeyCode::Enter => {
|
||
self.pattern_editor = Some(PatternEditor {
|
||
cursor: editor.pattern.chars().count(),
|
||
value: editor.pattern.clone(),
|
||
});
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn handle_pattern_key(&mut self, code: KeyCode) {
|
||
if code == KeyCode::Esc {
|
||
self.pattern_editor = None;
|
||
return;
|
||
}
|
||
let Some(editor) = &mut self.pattern_editor else {
|
||
return;
|
||
};
|
||
let character_count = editor.value.chars().count();
|
||
match code {
|
||
KeyCode::Left => editor.cursor = editor.cursor.saturating_sub(1),
|
||
KeyCode::Right => editor.cursor = (editor.cursor + 1).min(character_count),
|
||
KeyCode::Home => editor.cursor = 0,
|
||
KeyCode::End => editor.cursor = character_count,
|
||
KeyCode::Backspace if editor.cursor > 0 => {
|
||
let previous = editor.cursor - 1;
|
||
remove_character(&mut editor.value, previous);
|
||
editor.cursor = previous;
|
||
}
|
||
KeyCode::Delete if editor.cursor < character_count => {
|
||
remove_character(&mut editor.value, editor.cursor);
|
||
}
|
||
KeyCode::Char(character) => {
|
||
let byte = character_byte_index(&editor.value, editor.cursor);
|
||
editor.value.insert(byte, character);
|
||
editor.cursor += 1;
|
||
}
|
||
KeyCode::Enter => {
|
||
let Some(pattern) = self.pattern_editor.take() else {
|
||
return;
|
||
};
|
||
if let Some(capture) = &mut self.capture_editor {
|
||
capture.pattern = pattern.value;
|
||
}
|
||
self.submit_capture_editor();
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn submit_capture_editor(&mut self) {
|
||
let Some(editor) = &self.capture_editor else {
|
||
return;
|
||
};
|
||
let edit = ConfigurationEdit::SetApplicationSelector {
|
||
id: editor.application.clone(),
|
||
index: editor.selector,
|
||
field: selector_field_name(editor.field).to_owned(),
|
||
pattern: editor.pattern.clone(),
|
||
regex: editor.regex,
|
||
};
|
||
match self
|
||
.client
|
||
.edit_configuration(edit, self.snapshot.configuration.revision)
|
||
{
|
||
Ok(snapshot) => {
|
||
self.capture_editor = None;
|
||
self.replace_snapshot(snapshot);
|
||
}
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
|
||
fn handle_controller_picker_key(&mut self, code: KeyCode) {
|
||
if code == KeyCode::Esc {
|
||
self.controller_picker = None;
|
||
return;
|
||
}
|
||
let Some(picker) = &mut self.controller_picker else {
|
||
return;
|
||
};
|
||
match code {
|
||
KeyCode::Up => picker.selected = picker.selected.saturating_sub(1),
|
||
KeyCode::Down => {
|
||
picker.selected =
|
||
(picker.selected + 1).min(self.snapshot.devices.len().saturating_sub(1));
|
||
}
|
||
KeyCode::Enter => {
|
||
let Some(surface) = self.snapshot.devices.get(picker.selected) else {
|
||
return;
|
||
};
|
||
let surface = surface.id.clone();
|
||
let fader = picker.fader.clone();
|
||
let action = picker.action.clone();
|
||
let binding = self
|
||
.snapshot
|
||
.configuration
|
||
.bindings
|
||
.iter()
|
||
.find(|binding| binding.fader == fader && binding.action == action)
|
||
.cloned();
|
||
self.controller_picker = None;
|
||
if let Some(binding) = binding {
|
||
self.apply_layout_edit(ConfigurationEdit::SetBinding {
|
||
surface,
|
||
fader,
|
||
action,
|
||
kind: binding.kind,
|
||
channel: binding.channel,
|
||
number: binding.number,
|
||
});
|
||
} else {
|
||
self.controller_selections.insert((fader, action), surface);
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn move_selected_layout(&mut self, direction: isize) {
|
||
let Some(id) = self.selected_layout_id() else {
|
||
return;
|
||
};
|
||
let indexed = self
|
||
.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.enumerate()
|
||
.filter(|(_, entry)| match entry {
|
||
MixerLayoutEntry::Fader { hidden, .. } => !hidden,
|
||
MixerLayoutEntry::Separator { .. } => true,
|
||
})
|
||
.map(|(index, entry)| {
|
||
let entry_id = match entry {
|
||
MixerLayoutEntry::Fader { fader, .. } => fader,
|
||
MixerLayoutEntry::Separator { id, .. } => id,
|
||
};
|
||
(index, entry_id.as_str())
|
||
})
|
||
.collect::<Vec<_>>();
|
||
let Some(position) = indexed.iter().position(|(_, entry_id)| *entry_id == id) else {
|
||
return;
|
||
};
|
||
let destination = if direction < 0 {
|
||
position.checked_sub(1)
|
||
} else {
|
||
(position + 1 < indexed.len()).then_some(position + 1)
|
||
};
|
||
let Some(destination) = destination else {
|
||
return;
|
||
};
|
||
self.apply_layout_edit(ConfigurationEdit::MoveLayoutEntry {
|
||
id,
|
||
position: indexed[destination].0,
|
||
});
|
||
}
|
||
|
||
fn toggle_selected_visibility(&mut self) {
|
||
let selected = self
|
||
.mixer_rows()
|
||
.get(self.selected)
|
||
.and_then(|row| match row {
|
||
MixerRow::Fader {
|
||
layout_id: Some(id),
|
||
..
|
||
} => Some((*id).to_owned()),
|
||
_ => None,
|
||
});
|
||
let Some(id) = selected else { return };
|
||
self.apply_layout_edit(ConfigurationEdit::SetFaderHidden { id, hidden: true });
|
||
}
|
||
|
||
fn start_delete_selected_entry(&mut self) {
|
||
let confirmation = self
|
||
.mixer_rows()
|
||
.get(self.selected)
|
||
.and_then(|row| match row {
|
||
MixerRow::Fader {
|
||
layout_id: Some(id),
|
||
item,
|
||
..
|
||
} => Some(DeleteConfirmation {
|
||
id: (*id).to_owned(),
|
||
label: item.label.clone(),
|
||
separator: false,
|
||
}),
|
||
MixerRow::Separator { id, label, .. } => Some(DeleteConfirmation {
|
||
id: (*id).to_owned(),
|
||
label: (*label).to_owned(),
|
||
separator: true,
|
||
}),
|
||
MixerRow::Fader {
|
||
layout_id: None, ..
|
||
} => None,
|
||
});
|
||
if confirmation.is_some() {
|
||
self.delete_confirmation = confirmation;
|
||
self.client_error = None;
|
||
}
|
||
}
|
||
|
||
fn handle_delete_confirmation_key(&mut self, code: KeyCode) {
|
||
match code {
|
||
KeyCode::Char('y' | 'Y') => {
|
||
let Some(confirmation) = self.delete_confirmation.take() else {
|
||
return;
|
||
};
|
||
let edit = if confirmation.separator {
|
||
ConfigurationEdit::RemoveSeparator {
|
||
id: confirmation.id,
|
||
}
|
||
} else {
|
||
ConfigurationEdit::RemoveMixerFader {
|
||
id: confirmation.id,
|
||
}
|
||
};
|
||
self.apply_layout_edit(edit);
|
||
}
|
||
KeyCode::Char('n' | 'N') | KeyCode::Esc => self.delete_confirmation = None,
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn apply_layout_edit(&mut self, edit: ConfigurationEdit) {
|
||
match self
|
||
.client
|
||
.edit_configuration(edit, self.snapshot.configuration.revision)
|
||
{
|
||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
|
||
fn change_volume(&mut self, delta: f64) {
|
||
let gain = match self.mixer_rows().get(self.selected) {
|
||
Some(MixerRow::Fader { item, .. }) => item.gain,
|
||
_ => None,
|
||
};
|
||
if let Some(gain) = gain {
|
||
self.set_selected_volume((gain + delta).clamp(0.0, 1.0));
|
||
}
|
||
}
|
||
|
||
fn set_selected_volume(&mut self, gain: f64) {
|
||
let Some((id, writable)) = self
|
||
.mixer_rows()
|
||
.get(self.selected)
|
||
.and_then(|row| match row {
|
||
MixerRow::Fader { item, .. } => Some((item.id.clone(), item.writable)),
|
||
MixerRow::Separator { .. } => None,
|
||
})
|
||
else {
|
||
return;
|
||
};
|
||
if !writable {
|
||
self.client_error = Some("selected object is offline or read-only".to_owned());
|
||
return;
|
||
}
|
||
match self.client.set_volume(id, gain, self.snapshot.revision) {
|
||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
|
||
fn toggle_selected_mute(&mut self) {
|
||
let Some((id, writable)) = self
|
||
.mixer_rows()
|
||
.get(self.selected)
|
||
.and_then(|row| match row {
|
||
MixerRow::Fader { item, .. } => Some((item.id.clone(), item.writable)),
|
||
MixerRow::Separator { .. } => None,
|
||
})
|
||
else {
|
||
return;
|
||
};
|
||
if !writable {
|
||
self.client_error = Some("selected object is offline or read-only".to_owned());
|
||
return;
|
||
}
|
||
match self.client.toggle_mute(id, self.snapshot.revision) {
|
||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||
Err(error) => self.client_error = Some(error.to_string()),
|
||
}
|
||
}
|
||
}
|
||
|
||
impl<C: MixerClient> Widget for &LiveTui<C> {
|
||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||
let theme = self.theme.palette();
|
||
buf.set_style(
|
||
area,
|
||
Style::default().fg(theme.foreground).bg(theme.background),
|
||
);
|
||
let [header, body, footer] = Layout::default()
|
||
.direction(Direction::Vertical)
|
||
.constraints([
|
||
Constraint::Length(3),
|
||
Constraint::Min(5),
|
||
Constraint::Length(3),
|
||
])
|
||
.areas(area);
|
||
|
||
Paragraph::new(Line::from(vec![
|
||
" FADER "
|
||
.fg(theme.header_foreground)
|
||
.bg(theme.accent)
|
||
.bold(),
|
||
" MASTER ".fg(theme.foreground).bold(),
|
||
format!(
|
||
" [1 Mixer] [2 Config] · {} · {} · rev {} · {} ",
|
||
self.snapshot.backend,
|
||
self.snapshot.status,
|
||
self.snapshot.revision,
|
||
self.theme.label()
|
||
)
|
||
.fg(theme.muted),
|
||
]))
|
||
.alignment(Alignment::Center)
|
||
.block(
|
||
Block::bordered()
|
||
.border_set(border::ROUNDED)
|
||
.border_style(Style::default().fg(theme.muted)),
|
||
)
|
||
.render(header, buf);
|
||
|
||
let client_warning = self
|
||
.client_error
|
||
.as_deref()
|
||
.is_some_and(is_revision_conflict_message);
|
||
let status_error = self.client_error.is_some() && !client_warning
|
||
|| self
|
||
.snapshot
|
||
.devices
|
||
.iter()
|
||
.any(|device| device.error.is_some() || device.status == "error");
|
||
let status = self.client_error.clone().unwrap_or_else(|| {
|
||
device_summary(&self.snapshot.devices)
|
||
.unwrap_or_else(|| "confirmed server state".to_owned())
|
||
});
|
||
let mixer = Block::bordered()
|
||
.title(
|
||
match self.tab {
|
||
Tab::Mixer => " Live mixer objects ",
|
||
Tab::Configuration => " Settings and status ",
|
||
}
|
||
.fg(theme.accent)
|
||
.bold(),
|
||
)
|
||
.title_bottom(if client_warning {
|
||
status.fg(theme.warning)
|
||
} else if status_error {
|
||
status.fg(theme.error)
|
||
} else {
|
||
status.fg(theme.muted)
|
||
})
|
||
.border_style(Style::default().fg(theme.muted))
|
||
.border_set(border::THICK);
|
||
let inner = mixer.inner(body);
|
||
mixer.render(body, buf);
|
||
match self.tab {
|
||
Tab::Mixer => self.render_streams(inner, buf),
|
||
Tab::Configuration => self.render_configuration(inner, buf),
|
||
}
|
||
|
||
let footer_line = match self.tab {
|
||
Tab::Mixer => Line::from(vec![
|
||
" M ".fg(theme.foreground),
|
||
"mute".fg(theme.secondary),
|
||
" A ".fg(theme.foreground),
|
||
"add".fg(theme.secondary),
|
||
" E ".fg(theme.foreground),
|
||
"edit".fg(theme.secondary),
|
||
" D ".fg(theme.foreground),
|
||
"delete".fg(theme.secondary),
|
||
" ⇧H ".fg(theme.foreground),
|
||
"hide".fg(theme.secondary),
|
||
" T ".fg(theme.foreground),
|
||
"theme".fg(theme.secondary),
|
||
" Tab ".fg(theme.foreground),
|
||
"config".fg(theme.secondary),
|
||
" Q ".fg(theme.foreground),
|
||
"quit".fg(theme.secondary),
|
||
" h ".fg(theme.foreground),
|
||
"help".fg(theme.secondary),
|
||
]),
|
||
Tab::Configuration => Line::from(vec![
|
||
" ←→ ".fg(theme.foreground),
|
||
"layout".fg(theme.secondary),
|
||
" S ".fg(theme.foreground),
|
||
"save".fg(theme.secondary),
|
||
" Tab ".fg(theme.foreground),
|
||
"mixer".fg(theme.secondary),
|
||
" T ".fg(theme.foreground),
|
||
"theme".fg(theme.secondary),
|
||
" Q ".fg(theme.foreground),
|
||
"quit".fg(theme.secondary),
|
||
" h ".fg(theme.foreground),
|
||
"help".fg(theme.secondary),
|
||
]),
|
||
};
|
||
Paragraph::new(footer_line)
|
||
.alignment(Alignment::Center)
|
||
.block(
|
||
Block::bordered()
|
||
.border_set(border::ROUNDED)
|
||
.border_style(Style::default().fg(theme.muted)),
|
||
)
|
||
.render(footer, buf);
|
||
|
||
if self.editor.is_some() {
|
||
self.render_separator_editor(area, buf);
|
||
}
|
||
if self.fader_editor.is_some() {
|
||
self.render_fader_editor(area, buf);
|
||
}
|
||
if self.capture_editor.is_some() {
|
||
self.render_capture_editor(area, buf);
|
||
}
|
||
if self.pattern_editor.is_some() {
|
||
self.render_pattern_editor(area, buf);
|
||
}
|
||
if self.controller_picker.is_some() {
|
||
self.render_controller_picker(area, buf);
|
||
}
|
||
if self.group_member_picker.is_some() {
|
||
self.render_group_member_picker(area, buf);
|
||
}
|
||
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);
|
||
}
|
||
if self.snapshot.configuration.learning.is_some() {
|
||
self.render_midi_learn_waiting(area, buf);
|
||
}
|
||
if self.show_help {
|
||
self.render_help(area, buf);
|
||
}
|
||
if let Some(picker) = &self.add_picker {
|
||
let popup = centered_rect(area, 42, 7);
|
||
Clear.render(popup, buf);
|
||
let lines = AddKind::ALL
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(index, kind)| {
|
||
let marker = if index == picker.selected { "▶" } else { " " };
|
||
Line::from(format!("{marker} {}", kind.label())).style(
|
||
if index == picker.selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.foreground)
|
||
},
|
||
)
|
||
})
|
||
.collect::<Vec<_>>();
|
||
Paragraph::new(Text::from(lines))
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Add to mixer ".fg(theme.accent).bold())
|
||
.title_bottom(" ↑↓ select · Enter choose · Esc cancel ".fg(theme.muted))
|
||
.border_set(border::DOUBLE)
|
||
.border_style(Style::default().fg(theme.accent))
|
||
.style(Style::default().bg(theme.background)),
|
||
)
|
||
.render(popup, buf);
|
||
}
|
||
if let Some(editor) = &self.new_item_editor {
|
||
let popup = centered_rect(area, 58, 6);
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from(format!("New {} name", editor.kind.label())).fg(theme.secondary),
|
||
Line::from(if editor.label.is_empty() {
|
||
" ".to_owned()
|
||
} else {
|
||
editor.label.clone()
|
||
})
|
||
.bold(),
|
||
]))
|
||
.block(
|
||
Block::bordered()
|
||
.title(
|
||
format!(" Add {} ", editor.kind.label())
|
||
.fg(theme.accent)
|
||
.bold(),
|
||
)
|
||
.title_bottom(" Enter create · Esc cancel ".fg(theme.muted))
|
||
.border_set(border::DOUBLE)
|
||
.border_style(Style::default().fg(theme.accent))
|
||
.style(Style::default().bg(theme.background)),
|
||
)
|
||
.render(popup, buf);
|
||
}
|
||
if let Some(confirmation) = &self.delete_confirmation {
|
||
let popup = centered_rect(area, 58, 7);
|
||
Clear.render(popup, buf);
|
||
let kind = if confirmation.separator {
|
||
"separator"
|
||
} else {
|
||
"fader and its owned target"
|
||
};
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from(format!("Delete {kind}? ")).bold(),
|
||
Line::from(format!("“{}”", confirmation.label)).fg(theme.secondary),
|
||
Line::from("Y delete N / Esc cancel"),
|
||
]))
|
||
.alignment(Alignment::Center)
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Confirm delete ".fg(theme.error).bold())
|
||
.border_set(border::DOUBLE)
|
||
.border_style(Style::default().fg(theme.error))
|
||
.style(Style::default().bg(theme.background)),
|
||
)
|
||
.render(popup, buf);
|
||
}
|
||
if self.quit_confirmation {
|
||
let width = area.width.min(46);
|
||
let height = area.height.min(5);
|
||
let popup = Rect::new(
|
||
area.x + area.width.saturating_sub(width) / 2,
|
||
area.y + area.height.saturating_sub(height) / 2,
|
||
width,
|
||
height,
|
||
);
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from("Quit fader_master?").bold(),
|
||
Line::from(vec![
|
||
" Y ".fg(theme.foreground).bold(),
|
||
"yes".fg(theme.secondary),
|
||
" N / Esc ".fg(theme.foreground).bold(),
|
||
"cancel".fg(theme.secondary),
|
||
]),
|
||
]))
|
||
.alignment(Alignment::Center)
|
||
.wrap(Wrap { trim: true })
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Confirm quit ".fg(theme.warning).bold())
|
||
.border_set(border::DOUBLE)
|
||
.border_style(Style::default().fg(theme.warning))
|
||
.style(Style::default().bg(theme.background)),
|
||
)
|
||
.render(popup, buf);
|
||
}
|
||
if self.reset_confirmation {
|
||
let width = area.width.min(60);
|
||
let height = area.height.min(7);
|
||
let popup = Rect::new(
|
||
area.x + area.width.saturating_sub(width) / 2,
|
||
area.y + area.height.saturating_sub(height) / 2,
|
||
width,
|
||
height,
|
||
);
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from("Reset the active profile to safe defaults?").bold(),
|
||
Line::from("The current file is preserved as <profile>.toml.reset.bak."),
|
||
Line::from(vec![
|
||
" Y ".fg(theme.foreground).bold(),
|
||
"reset".fg(theme.secondary),
|
||
" N / Esc ".fg(theme.foreground).bold(),
|
||
"cancel".fg(theme.secondary),
|
||
]),
|
||
]))
|
||
.alignment(Alignment::Center)
|
||
.wrap(Wrap { trim: true })
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Confirm profile reset ".fg(theme.error).bold())
|
||
.border_set(border::DOUBLE)
|
||
.border_style(Style::default().fg(theme.error))
|
||
.style(Style::default().bg(theme.background)),
|
||
)
|
||
.render(popup, buf);
|
||
}
|
||
}
|
||
}
|
||
|
||
fn device_summary(devices: &[MidiDevice]) -> Option<String> {
|
||
(!devices.is_empty()).then(|| {
|
||
devices
|
||
.iter()
|
||
.map(|device| {
|
||
let detail = if let Some(error) = &device.error {
|
||
format!("error — {error}")
|
||
} else {
|
||
match device.status.as_str() {
|
||
"missing" => "missing — connect device".to_owned(),
|
||
"ambiguous" => "ambiguous — select port".to_owned(),
|
||
"connected" => device.backend_id.as_ref().map_or_else(
|
||
|| "connected".to_owned(),
|
||
|backend| format!("connected ({backend})"),
|
||
),
|
||
"connecting" => "connecting…".to_owned(),
|
||
status => status.to_owned(),
|
||
}
|
||
};
|
||
format!("{}: {detail}", device.label)
|
||
})
|
||
.collect::<Vec<_>>()
|
||
.join(" | ")
|
||
})
|
||
}
|
||
|
||
struct PickupDisplay {
|
||
text: &'static str,
|
||
style: Style,
|
||
}
|
||
|
||
fn pickup_display(
|
||
status: Option<PickupStatus>,
|
||
mode: StatusDisplayMode,
|
||
theme: theme::ThemePalette,
|
||
) -> PickupDisplay {
|
||
let Some(status) = status else {
|
||
return PickupDisplay {
|
||
text: "",
|
||
style: Style::default(),
|
||
};
|
||
};
|
||
let text = match mode {
|
||
StatusDisplayMode::Detailed => match status {
|
||
PickupStatus::Unavailable => "pickup: unavailable",
|
||
PickupStatus::Waiting => "pickup: waiting",
|
||
PickupStatus::Tracking => "pickup: tracking",
|
||
PickupStatus::Mixed => "pickup: mixed",
|
||
},
|
||
StatusDisplayMode::Compact => match status {
|
||
PickupStatus::Unavailable => "OFFLINE",
|
||
PickupStatus::Waiting => "WAIT",
|
||
PickupStatus::Tracking => "LIVE",
|
||
PickupStatus::Mixed => "MIXED",
|
||
},
|
||
StatusDisplayMode::Symbol => match status {
|
||
PickupStatus::Unavailable => "×",
|
||
PickupStatus::Waiting => "○",
|
||
PickupStatus::Tracking => "●",
|
||
PickupStatus::Mixed => "◐",
|
||
},
|
||
StatusDisplayMode::Color => "●",
|
||
StatusDisplayMode::Hidden => "",
|
||
};
|
||
let color = if mode == StatusDisplayMode::Color {
|
||
match status {
|
||
PickupStatus::Unavailable => theme.error,
|
||
PickupStatus::Waiting => theme.warning,
|
||
PickupStatus::Tracking => theme.secondary,
|
||
PickupStatus::Mixed => theme.accent,
|
||
}
|
||
} else if mode == StatusDisplayMode::Symbol {
|
||
theme.foreground
|
||
} else {
|
||
theme.muted
|
||
};
|
||
PickupDisplay {
|
||
text,
|
||
style: Style::default().fg(color),
|
||
}
|
||
}
|
||
|
||
fn unique_separator_id(label: &str, layout: &[MixerLayoutEntry]) -> String {
|
||
let base = label
|
||
.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(48)
|
||
.collect::<String>()
|
||
.trim_matches('-')
|
||
.to_owned();
|
||
let base = if base.is_empty() {
|
||
"separator".to_owned()
|
||
} else {
|
||
base
|
||
};
|
||
let used = layout
|
||
.iter()
|
||
.map(|entry| match entry {
|
||
MixerLayoutEntry::Fader { fader, .. } => fader.as_str(),
|
||
MixerLayoutEntry::Separator { id, .. } => 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(|| "separator-id-exhausted".to_owned())
|
||
}
|
||
|
||
fn mixer_object_id(label: &str) -> String {
|
||
let id = label
|
||
.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(48)
|
||
.collect::<String>()
|
||
.trim_matches('-')
|
||
.to_owned();
|
||
if id.is_empty() {
|
||
"fader".to_owned()
|
||
} else {
|
||
id
|
||
}
|
||
}
|
||
|
||
fn unique_configured_id<'a>(base: &str, used: impl Iterator<Item = &'a str>) -> String {
|
||
let used = used.collect::<std::collections::BTreeSet<_>>();
|
||
if !used.contains(base) {
|
||
return base.to_owned();
|
||
}
|
||
(2..)
|
||
.map(|suffix| format!("{base}-{suffix}"))
|
||
.find(|candidate| !used.contains(candidate.as_str()))
|
||
.unwrap_or_else(|| "configured-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);
|
||
Rect::new(
|
||
area.x + area.width.saturating_sub(width) / 2,
|
||
area.y + area.height.saturating_sub(height) / 2,
|
||
width,
|
||
height,
|
||
)
|
||
}
|
||
|
||
const fn selector_field_name(index: usize) -> &'static str {
|
||
match index {
|
||
0 => "application.name",
|
||
1 => "application.id",
|
||
2 => "application.process.binary",
|
||
_ => "media.name",
|
||
}
|
||
}
|
||
|
||
fn capitalize(value: &str) -> String {
|
||
let mut characters = value.chars();
|
||
characters.next().map_or_else(String::new, |first| {
|
||
first.to_uppercase().chain(characters).collect()
|
||
})
|
||
}
|
||
|
||
fn selector_field_index(field: &str) -> usize {
|
||
match field {
|
||
"application.name" => 0,
|
||
"application.id" => 1,
|
||
"application.process.binary" => 2,
|
||
"media.name" => 3,
|
||
_ => 0,
|
||
}
|
||
}
|
||
|
||
fn character_byte_index(value: &str, character_index: usize) -> usize {
|
||
value
|
||
.char_indices()
|
||
.nth(character_index)
|
||
.map_or(value.len(), |(byte, _)| byte)
|
||
}
|
||
|
||
fn remove_character(value: &mut String, character_index: usize) {
|
||
let start = character_byte_index(value, character_index);
|
||
let end = character_byte_index(value, character_index.saturating_add(1));
|
||
if start < end {
|
||
value.drain(start..end);
|
||
}
|
||
}
|
||
|
||
impl<C: MixerClient> LiveTui<C> {
|
||
fn render_separator_editor(&self, area: Rect, buf: &mut Buffer) {
|
||
let Some(editor) = &self.editor else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let popup = centered_rect(area, 68, 9);
|
||
let title = if editor.target.is_some() {
|
||
" Edit separator "
|
||
} else {
|
||
" Add separator "
|
||
};
|
||
let guidance = "Name is optional. Use Plain + Fill for an empty spacer.";
|
||
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from(""),
|
||
Line::from(format!(
|
||
"{} Name {}{}",
|
||
if editor.selected == 0 { "▶" } else { " " },
|
||
editor.value,
|
||
if editor.selected == 0 { "▏" } else { "" }
|
||
))
|
||
.fg(theme.foreground)
|
||
.bold(),
|
||
Line::from(format!(
|
||
"{} Size {} [←→]",
|
||
if editor.selected == 1 { "▶" } else { " " },
|
||
editor.size.label()
|
||
)),
|
||
Line::from(format!(
|
||
"{} Decoration {} [←→]",
|
||
if editor.selected == 2 { "▶" } else { " " },
|
||
editor.decoration.label()
|
||
)),
|
||
Line::from(guidance).fg(theme.muted),
|
||
]))
|
||
.alignment(Alignment::Center)
|
||
.block(
|
||
Block::bordered()
|
||
.title(title.fg(theme.accent).bold())
|
||
.title_bottom(
|
||
" ↑↓/Tab select · ←→ change · Enter accept · Esc cancel ".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_fader_editor(&self, area: Rect, buf: &mut Buffer) {
|
||
let Some(editor) = &self.fader_editor else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let rows = self.fader_editor_rows();
|
||
let height = u16::try_from(rows.len().saturating_add(4))
|
||
.unwrap_or(u16::MAX)
|
||
.min(area.height);
|
||
let popup = centered_rect(area, 76, height.max(5));
|
||
let lines = rows
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(index, row)| {
|
||
let marker = if index == editor.selected { "▶" } else { " " };
|
||
let text = match row {
|
||
FaderEditorRow::Capture {
|
||
selector,
|
||
field,
|
||
pattern,
|
||
regex,
|
||
..
|
||
} => format!(
|
||
"{marker} Capture {} {} · {} · {}",
|
||
selector + 1,
|
||
field,
|
||
if *regex { "regex" } else { "exact" },
|
||
pattern
|
||
),
|
||
FaderEditorRow::GroupMembers {
|
||
included,
|
||
available,
|
||
..
|
||
} => format!(
|
||
"{marker} Members {included} of {available} selected [Enter to edit]"
|
||
),
|
||
FaderEditorRow::GroupMode { mode } => {
|
||
format!("{marker} Group mode {}", mode.label())
|
||
}
|
||
FaderEditorRow::BindingController { label, value, .. } => format!(
|
||
"{marker} {} controller {value} [Enter to change]",
|
||
capitalize(label)
|
||
),
|
||
FaderEditorRow::BindingLearn { label, value, .. } => {
|
||
format!("{marker} Learn {label} MIDI {value} [Enter]")
|
||
}
|
||
FaderEditorRow::BindingUnlearn {
|
||
label, configured, ..
|
||
} => format!(
|
||
"{marker} Unlearn {label} MIDI {}",
|
||
if *configured {
|
||
"[Enter]"
|
||
} else {
|
||
"not assigned"
|
||
}
|
||
),
|
||
FaderEditorRow::Visibility { hidden } => format!(
|
||
"{marker} Visibility {} [Enter to {}]",
|
||
if *hidden { "Hidden" } else { "Shown" },
|
||
if *hidden { "show" } else { "hide" }
|
||
),
|
||
FaderEditorRow::Density { density } => {
|
||
format!("{marker} Size {} [Enter to cycle]", density.label())
|
||
}
|
||
FaderEditorRow::Save => {
|
||
format!("{marker} Save changes [Enter to activate]")
|
||
}
|
||
};
|
||
Line::from(text).style(if index == editor.selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.foreground)
|
||
})
|
||
})
|
||
.collect::<Vec<_>>();
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(lines))
|
||
.block(
|
||
Block::bordered()
|
||
.title(
|
||
format!(" Edit fader: {} ", editor.fader)
|
||
.fg(theme.accent)
|
||
.bold(),
|
||
)
|
||
.title_bottom(" ↑↓ select · Enter edit/toggle · Esc back ".fg(theme.muted))
|
||
.border_set(border::DOUBLE)
|
||
.border_style(Style::default().fg(theme.accent))
|
||
.style(Style::default().bg(theme.background)),
|
||
)
|
||
.wrap(Wrap { trim: false })
|
||
.render(popup, buf);
|
||
}
|
||
|
||
fn render_group_member_picker(&self, area: Rect, buf: &mut Buffer) {
|
||
let Some(picker) = &self.group_member_picker else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let choices = self.group_member_choices(&picker.group);
|
||
let height = u16::try_from(choices.len().saturating_add(4))
|
||
.unwrap_or(u16::MAX)
|
||
.min(area.height);
|
||
let popup = centered_rect(area, 70, 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 = if choices.is_empty() {
|
||
vec![Line::from("No application faders are available.").fg(theme.muted)]
|
||
} else {
|
||
choices
|
||
.iter()
|
||
.enumerate()
|
||
.skip(first_visible)
|
||
.take(visible_rows)
|
||
.map(|(index, choice)| {
|
||
Line::from(format!(
|
||
"{} [{}] {} · {}",
|
||
if index == picker.selected { "▶" } else { " " },
|
||
if choice.included { "x" } else { " " },
|
||
choice.label,
|
||
choice.fader
|
||
))
|
||
.style(if index == picker.selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.foreground)
|
||
})
|
||
})
|
||
.collect::<Vec<_>>()
|
||
};
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(lines))
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Group members ".fg(theme.accent).bold())
|
||
.title_bottom(" ↑↓ select · Enter/Space toggle · Esc back ".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_capture_editor(&self, area: Rect, buf: &mut Buffer) {
|
||
let Some(editor) = &self.capture_editor else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let popup = centered_rect(area, 70, 9);
|
||
let values = [
|
||
format!("Field {}", selector_field_name(editor.field)),
|
||
format!("Match {}", if editor.regex { "Regex" } else { "Exact" }),
|
||
format!("Pattern {}", editor.pattern),
|
||
];
|
||
let lines = values
|
||
.into_iter()
|
||
.enumerate()
|
||
.map(|(index, value)| {
|
||
Line::from(format!(
|
||
"{} {value}",
|
||
if index == editor.selected { "▶" } else { " " }
|
||
))
|
||
.style(if index == editor.selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.foreground)
|
||
})
|
||
})
|
||
.collect::<Vec<_>>();
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(lines))
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Edit capture ".fg(theme.accent).bold())
|
||
.title_bottom(
|
||
" ↑↓ field · ←→ choice · Enter next/edit pattern · Esc back "
|
||
.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_pattern_editor(&self, area: Rect, buf: &mut Buffer) {
|
||
let Some(editor) = &self.pattern_editor else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let popup = centered_rect(area, 72, 7);
|
||
let characters = editor.value.chars().collect::<Vec<_>>();
|
||
let cursor = editor.cursor.min(characters.len());
|
||
let capacity = usize::from(popup.width.saturating_sub(4)).saturating_sub(1);
|
||
let mut start = cursor.saturating_sub(capacity / 2);
|
||
if characters.len().saturating_sub(start) < capacity {
|
||
start = characters.len().saturating_sub(capacity);
|
||
}
|
||
let end = start.saturating_add(capacity).min(characters.len());
|
||
let before = characters[start..cursor].iter().collect::<String>();
|
||
let after = characters[cursor..end].iter().collect::<String>();
|
||
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from("Pattern"),
|
||
Line::from(vec![
|
||
Span::raw(before),
|
||
"▏".fg(theme.accent).bold(),
|
||
Span::raw(after),
|
||
])
|
||
.style(Style::default().fg(theme.foreground)),
|
||
Line::from("Use the cursor to insert or remove individual characters.").fg(theme.muted),
|
||
]))
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Edit capture pattern ".fg(theme.accent).bold())
|
||
.title_bottom(
|
||
" ←→/Home/End move · Backspace/Delete edit · Enter apply · Esc cancel "
|
||
.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_controller_picker(&self, area: Rect, buf: &mut Buffer) {
|
||
let Some(picker) = &self.controller_picker else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let height = u16::try_from(self.snapshot.devices.len().saturating_add(4))
|
||
.unwrap_or(u16::MAX)
|
||
.min(area.height);
|
||
let popup = centered_rect(area, 64, height.max(5));
|
||
let lines = self
|
||
.snapshot
|
||
.devices
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(index, device)| {
|
||
Line::from(format!(
|
||
"{} {} · {}",
|
||
if index == picker.selected { "▶" } else { " " },
|
||
device.label,
|
||
device.status
|
||
))
|
||
.style(if index == picker.selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.foreground)
|
||
})
|
||
})
|
||
.collect::<Vec<_>>();
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(lines))
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Choose controller ".fg(theme.accent).bold())
|
||
.title_bottom(" Enter select · Esc back ".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_hidden_fader_picker(&self, area: Rect, buf: &mut Buffer) {
|
||
let Some(picker) = &self.hidden_fader_picker else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let hidden_faders = self.hidden_faders();
|
||
let height = u16::try_from(hidden_faders.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 = hidden_faders
|
||
.iter()
|
||
.enumerate()
|
||
.skip(first_visible)
|
||
.take(visible_rows)
|
||
.map(|(index, (id, label))| {
|
||
Line::from(format!(
|
||
"{} {label} · {id}",
|
||
if index == picker.selected { "▶" } else { " " }
|
||
))
|
||
.style(if index == picker.selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.foreground)
|
||
})
|
||
})
|
||
.collect::<Vec<_>>();
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(lines))
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Show hidden faders ".fg(theme.accent).bold())
|
||
.title_bottom(" ↑↓ select · Enter show · 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_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::<Vec<_>>();
|
||
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;
|
||
};
|
||
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;
|
||
};
|
||
let is_default = self.snapshot.configuration.default_controller.as_deref() == Some(id);
|
||
let backend = device.backend_id.as_deref().unwrap_or("Unavailable");
|
||
let error = device.error.as_deref().unwrap_or("None");
|
||
let popup = centered_rect(area, 68, 11);
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from(device.label.as_str()).bold(),
|
||
Line::from(format!("Device ID {}", device.id)),
|
||
Line::from(format!("Status {}", device.status)),
|
||
Line::from(format!("Backend port {backend}")),
|
||
Line::from(format!("Error {error}")),
|
||
Line::from(""),
|
||
Line::from(vec![
|
||
"▶ Default controller ".fg(theme.foreground),
|
||
is_default.to_string().fg(theme.accent).bold(),
|
||
" [←→/Enter]".fg(theme.muted),
|
||
]),
|
||
]))
|
||
.block(
|
||
Block::bordered()
|
||
.title(" MIDI device details ".fg(theme.accent).bold())
|
||
.title_bottom(" ← false · → true · Enter toggle · 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_learn_waiting(&self, area: Rect, buf: &mut Buffer) {
|
||
let theme = self.theme.palette();
|
||
let popup = centered_rect(area, 68, 7.min(area.height));
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from("Move a fader or press a button on the selected controller.")
|
||
.alignment(Alignment::Center),
|
||
Line::from("The next supported MIDI control will be assigned.")
|
||
.fg(theme.muted)
|
||
.alignment(Alignment::Center),
|
||
]))
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Learn MIDI control ".fg(theme.accent).bold())
|
||
.title_bottom(" Esc cancel ".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_help(&self, area: Rect, buf: &mut Buffer) {
|
||
let theme = self.theme.palette();
|
||
let (selection, volume, movement) = match self.snapshot.configuration.mixer_orientation {
|
||
MixerOrientation::Horizontal => {
|
||
("Left/Right", "Up/Down", "Shift+Left/Right or Shift+J/K")
|
||
}
|
||
MixerOrientation::Vertical => ("Up/Down", "Left/Right", "Shift+Up/Down or Shift+J/K"),
|
||
};
|
||
let popup = centered_rect(area, 78, 22);
|
||
Clear.render(popup, buf);
|
||
Paragraph::new(Text::from(vec![
|
||
Line::from("Mixer").fg(theme.accent).bold(),
|
||
Line::from(format!(" {selection:<18} Select a fader or separator")),
|
||
Line::from(format!(" {volume:<18} Change the selected fader volume")),
|
||
Line::from(" Home/End Set the selected fader to 0%/100%"),
|
||
Line::from(format!(" {movement:<18} Reorder the selected entry")),
|
||
Line::from(" J/K Select next/previous in either orientation"),
|
||
Line::from(" M Toggle mute"),
|
||
Line::from(" Shift+H Hide the selected fader"),
|
||
Line::from(" A Add a fader, group, or separator"),
|
||
Line::from(" E Edit the selected entry"),
|
||
Line::from(" D Delete the selected entry"),
|
||
Line::from(""),
|
||
Line::from("Configuration").fg(theme.accent).bold(),
|
||
Line::from(" Up/Down or J/K Select a setting or MIDI device"),
|
||
Line::from(" Left/Right/Enter Change a setting or open its popup"),
|
||
Line::from(" S Save the configuration"),
|
||
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(" T Cycle theme Q Confirm quit"),
|
||
]))
|
||
.wrap(Wrap { trim: false })
|
||
.block(
|
||
Block::bordered()
|
||
.title(" Keyboard help ".fg(theme.accent).bold())
|
||
.title_bottom(" Esc / h / ? 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_configuration(&self, area: Rect, buf: &mut Buffer) {
|
||
let theme = self.theme.palette();
|
||
let config = &self.snapshot.configuration;
|
||
let mut lines = vec![
|
||
Line::from(format!(
|
||
"Profile: {}{} · revision {}{}",
|
||
config.profile_id,
|
||
if config.selection_saved {
|
||
""
|
||
} else {
|
||
" · selection unsaved"
|
||
},
|
||
config.revision,
|
||
if config.dirty {
|
||
" · unsaved draft"
|
||
} else {
|
||
""
|
||
}
|
||
))
|
||
.bold(),
|
||
];
|
||
lines.push(Line::from(format!(
|
||
"Backend: {} · {} · mixer revision {}",
|
||
self.snapshot.backend, self.snapshot.status, self.snapshot.revision
|
||
)));
|
||
if let Some(learning) = &config.learning {
|
||
lines.push(
|
||
Line::from(format!(
|
||
"MIDI learn: {learning} — move or press one control"
|
||
))
|
||
.fg(theme.warning)
|
||
.bold(),
|
||
);
|
||
}
|
||
if let Some(error) = &config.error {
|
||
lines.push(Line::from(format!("Configuration error: {error}")).fg(theme.error));
|
||
}
|
||
lines.push(Line::from(""));
|
||
lines.push(Line::from("Settings").fg(theme.accent).bold());
|
||
let settings_rows = self.settings_rows();
|
||
let mut selected_line = None;
|
||
for (index, row) in settings_rows.iter().enumerate() {
|
||
if matches!(
|
||
row,
|
||
SettingsRow::MidiDevice { .. } | SettingsRow::DiscoveredMidiPort { .. }
|
||
) {
|
||
continue;
|
||
}
|
||
let marker = if index == self.settings_selected {
|
||
"▶"
|
||
} else {
|
||
" "
|
||
};
|
||
let value = match row {
|
||
SettingsRow::Theme => format!("Theme {} [←→]", self.theme.label()),
|
||
SettingsRow::MixerOrientation => {
|
||
format!("Mixer layout {} [←→]", config.mixer_orientation.label())
|
||
}
|
||
SettingsRow::StatusDisplay => {
|
||
format!("Pickup status {} [←→]", config.status_display.label())
|
||
}
|
||
SettingsRow::DefaultController => {
|
||
let controller = config.default_controller.as_deref().map_or_else(
|
||
|| "None".to_owned(),
|
||
|id| {
|
||
self.snapshot
|
||
.devices
|
||
.iter()
|
||
.find(|device| device.id == id)
|
||
.map_or_else(|| id.to_owned(), |device| device.label.clone())
|
||
},
|
||
);
|
||
format!("Default controller {controller} [←→]")
|
||
}
|
||
SettingsRow::HiddenFaders { count } if *count > 0 => {
|
||
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::AddMasterFader => "Add Master output fader [Enter]".to_owned(),
|
||
SettingsRow::Save => format!(
|
||
"Save changes {}",
|
||
if config.dirty {
|
||
"[Enter]"
|
||
} else {
|
||
"already saved"
|
||
}
|
||
),
|
||
SettingsRow::Reset => "Reset active profile to safe defaults [Enter]".to_owned(),
|
||
SettingsRow::MidiDevice { .. } | SettingsRow::DiscoveredMidiPort { .. } => {
|
||
continue;
|
||
}
|
||
};
|
||
if index == self.settings_selected {
|
||
selected_line = Some(lines.len());
|
||
}
|
||
lines.push(Line::from(format!("{marker} {value}")).style(
|
||
if index == self.settings_selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.foreground)
|
||
},
|
||
));
|
||
}
|
||
lines.push(Line::from(""));
|
||
lines.push(Line::from("MIDI devices").fg(theme.accent).bold());
|
||
if self.snapshot.devices.is_empty() {
|
||
lines.push(Line::from(" No configured MIDI devices").fg(theme.muted));
|
||
} else {
|
||
for (index, row) in settings_rows.iter().enumerate() {
|
||
let SettingsRow::MidiDevice { id } = row else {
|
||
continue;
|
||
};
|
||
let Some(device) = self.snapshot.devices.iter().find(|device| &device.id == id)
|
||
else {
|
||
continue;
|
||
};
|
||
let selected = index == self.settings_selected;
|
||
if selected {
|
||
selected_line = Some(lines.len());
|
||
}
|
||
lines.push(
|
||
Line::from(format!(
|
||
"{} {} — {} [Enter]",
|
||
if selected { "▶" } else { " " },
|
||
device.label,
|
||
device.status
|
||
))
|
||
.style(if selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.foreground)
|
||
}),
|
||
);
|
||
}
|
||
}
|
||
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)
|
||
.saturating_sub(usize::from(area.height));
|
||
Paragraph::new(Text::from(lines))
|
||
.style(Style::default().fg(theme.foreground))
|
||
.wrap(Wrap { trim: false })
|
||
.scroll((u16::try_from(scroll).unwrap_or(u16::MAX), 0))
|
||
.render(area, buf);
|
||
}
|
||
|
||
fn render_streams(&self, area: Rect, buf: &mut Buffer) {
|
||
let theme = self.theme.palette();
|
||
let rows = self.mixer_rows();
|
||
if rows.is_empty() {
|
||
Paragraph::new(
|
||
"No mixer faders are currently visible. Restore hidden faders in Config.",
|
||
)
|
||
.style(Style::default().fg(theme.muted))
|
||
.alignment(Alignment::Center)
|
||
.render(area, buf);
|
||
return;
|
||
}
|
||
if self.snapshot.configuration.mixer_orientation == MixerOrientation::Horizontal {
|
||
self.render_fader_strips(area, buf, &rows);
|
||
return;
|
||
}
|
||
self.render_vertical_streams(area, buf, &rows);
|
||
}
|
||
|
||
fn render_fader_strips(&self, area: Rect, buf: &mut Buffer, rows: &[MixerRow<'_>]) {
|
||
let (start, extents) = mixer_viewport(rows, self.selected, area.width, true);
|
||
let used = extents.iter().copied().sum::<u16>();
|
||
let mut x = area.x.saturating_add(area.width.saturating_sub(used) / 2);
|
||
for ((index, row), strip_width) in rows.iter().enumerate().skip(start).zip(extents) {
|
||
let strip_area = Rect::new(x, area.y, strip_width, area.height);
|
||
match row {
|
||
MixerRow::Fader { .. } => {
|
||
self.render_fader_strip(strip_area, buf, row, index == self.selected);
|
||
}
|
||
MixerRow::Separator { .. } => {
|
||
self.render_fader_strip_separator(strip_area, buf, row, index == self.selected);
|
||
}
|
||
}
|
||
x = x.saturating_add(strip_width);
|
||
}
|
||
}
|
||
|
||
fn render_fader_strip_separator(
|
||
&self,
|
||
area: Rect,
|
||
buf: &mut Buffer,
|
||
row: &MixerRow<'_>,
|
||
selected: bool,
|
||
) {
|
||
let MixerRow::Separator {
|
||
label, decoration, ..
|
||
} = row
|
||
else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let style = if selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.muted)
|
||
};
|
||
if *decoration == SeparatorDecoration::Box {
|
||
Block::bordered().border_style(style).render(area, buf);
|
||
} else if *decoration != SeparatorDecoration::Plain {
|
||
let divider_x = area.x.saturating_add(area.width / 2);
|
||
for y in area.y..area.bottom().saturating_sub(1) {
|
||
if let Some(cell) = buf.cell_mut((divider_x, y)) {
|
||
cell.set_symbol(if *decoration == SeparatorDecoration::Double {
|
||
"║"
|
||
} else {
|
||
"│"
|
||
});
|
||
cell.set_style(style);
|
||
}
|
||
}
|
||
}
|
||
if area.height > 0 {
|
||
Paragraph::new(*label)
|
||
.alignment(Alignment::Center)
|
||
.style(if selected {
|
||
Style::default()
|
||
.fg(theme.header_foreground)
|
||
.bg(theme.accent)
|
||
.bold()
|
||
} else {
|
||
style
|
||
})
|
||
.render(
|
||
Rect::new(area.x, area.bottom().saturating_sub(1), area.width, 1),
|
||
buf,
|
||
);
|
||
}
|
||
}
|
||
|
||
fn render_fader_strip(&self, area: Rect, buf: &mut Buffer, row: &MixerRow<'_>, selected: bool) {
|
||
let MixerRow::Fader { item, .. } = row else {
|
||
return;
|
||
};
|
||
let theme = self.theme.palette();
|
||
let percent = item
|
||
.gain
|
||
.map_or(0, |gain| (gain.clamp(0.0, 1.0) * 100.0).round() as u16);
|
||
let meter_color = if item.error.is_some() {
|
||
theme.error
|
||
} else if item.muted == Some(true) {
|
||
theme.warning
|
||
} else {
|
||
theme.secondary
|
||
};
|
||
let state = if item.error.is_some() {
|
||
"ERROR"
|
||
} else if item.gain.is_none() {
|
||
"OFFLINE"
|
||
} else if item.mute_mixed || item.gain_mixed {
|
||
"MIXED"
|
||
} else if item.muted == Some(true) {
|
||
"MUTED"
|
||
} else if !item.writable {
|
||
"READ ONLY"
|
||
} else if item.pending {
|
||
"PENDING"
|
||
} else {
|
||
"LIVE"
|
||
};
|
||
if area.height < 6 || area.width < 8 {
|
||
let label = if state == "LIVE" {
|
||
format!(
|
||
"{} {} {percent}%",
|
||
if selected { "▶" } else { " " },
|
||
item.label
|
||
)
|
||
} else {
|
||
format!("{state} {percent}%")
|
||
};
|
||
Gauge::default()
|
||
.gauge_style(Style::default().bg(theme.meter_track).fg(meter_color))
|
||
.percent(percent)
|
||
.label(label)
|
||
.render(area, buf);
|
||
return;
|
||
}
|
||
|
||
let pickup = pickup_display(
|
||
item.pickup,
|
||
self.snapshot.configuration.status_display,
|
||
theme,
|
||
);
|
||
let footer_height = if area.height >= 9 && !pickup.text.is_empty() {
|
||
4
|
||
} else {
|
||
3
|
||
};
|
||
let meter_height = area.height.saturating_sub(footer_height);
|
||
let meter_width = area.width.saturating_sub(4).clamp(3, 7);
|
||
let meter_area = Rect::new(
|
||
area.x + area.width.saturating_sub(meter_width) / 2,
|
||
area.y,
|
||
meter_width,
|
||
meter_height,
|
||
);
|
||
let meter_block = Block::bordered().border_style(if selected {
|
||
Style::default().fg(theme.accent)
|
||
} else {
|
||
Style::default().fg(theme.muted)
|
||
});
|
||
let inner = meter_block.inner(meter_area);
|
||
meter_block.render(meter_area, buf);
|
||
let filled = u32::from(inner.height)
|
||
.saturating_mul(u32::from(percent))
|
||
.div_ceil(100) as u16;
|
||
for y in inner.y..inner.bottom() {
|
||
let is_filled = inner.bottom().saturating_sub(y) <= filled;
|
||
for x in inner.x..inner.right() {
|
||
if let Some(cell) = buf.cell_mut((x, y)) {
|
||
cell.set_symbol(if is_filled { "█" } else { "░" });
|
||
cell.set_style(
|
||
Style::default()
|
||
.fg(if is_filled { meter_color } else { theme.muted })
|
||
.bg(theme.meter_track),
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
let footer_y = area.bottom().saturating_sub(footer_height);
|
||
if footer_height == 4 {
|
||
Paragraph::new(pickup.text)
|
||
.alignment(Alignment::Center)
|
||
.style(pickup.style)
|
||
.render(Rect::new(area.x, footer_y, area.width, 1), buf);
|
||
}
|
||
Paragraph::new(state)
|
||
.alignment(Alignment::Center)
|
||
.style(Style::default().fg(if state == "ERROR" {
|
||
theme.error
|
||
} else if state == "MUTED" {
|
||
theme.warning
|
||
} else {
|
||
theme.foreground
|
||
}))
|
||
.render(
|
||
Rect::new(area.x, area.bottom().saturating_sub(3), area.width, 1),
|
||
buf,
|
||
);
|
||
Paragraph::new(format!("{percent}%"))
|
||
.alignment(Alignment::Center)
|
||
.style(Style::default().fg(theme.foreground).bold())
|
||
.render(
|
||
Rect::new(area.x, area.bottom().saturating_sub(2), area.width, 1),
|
||
buf,
|
||
);
|
||
Paragraph::new(item.label.as_str())
|
||
.alignment(Alignment::Center)
|
||
.style(if selected {
|
||
Style::default()
|
||
.fg(theme.header_foreground)
|
||
.bg(theme.accent)
|
||
.bold()
|
||
} else {
|
||
Style::default().fg(theme.accent).bold()
|
||
})
|
||
.render(
|
||
Rect::new(area.x, area.bottom().saturating_sub(1), area.width, 1),
|
||
buf,
|
||
);
|
||
}
|
||
|
||
fn render_vertical_streams(&self, area: Rect, buf: &mut Buffer, rows: &[MixerRow<'_>]) {
|
||
let theme = self.theme.palette();
|
||
let (start, extents) = mixer_viewport(rows, self.selected, area.height, false);
|
||
let mut y = area.y;
|
||
for ((index, layout_row), extent) in rows.iter().enumerate().skip(start).zip(extents) {
|
||
let remaining = area.bottom().saturating_sub(y);
|
||
if remaining == 0 {
|
||
break;
|
||
}
|
||
let row_area = Rect::new(area.x, y, area.width, extent.min(remaining));
|
||
y = y.saturating_add(row_area.height);
|
||
let selected = index == self.selected;
|
||
let MixerRow::Fader { item, density, .. } = layout_row else {
|
||
let MixerRow::Separator {
|
||
label, decoration, ..
|
||
} = layout_row
|
||
else {
|
||
continue;
|
||
};
|
||
let style = if selected {
|
||
Style::default().fg(theme.accent).bold()
|
||
} else {
|
||
Style::default().fg(theme.muted)
|
||
};
|
||
if *decoration == SeparatorDecoration::Box {
|
||
Block::bordered().border_style(style).render(row_area, buf);
|
||
}
|
||
let line_area = Rect::new(
|
||
row_area.x,
|
||
row_area.y + row_area.height / 2,
|
||
row_area.width,
|
||
1,
|
||
);
|
||
if matches!(
|
||
decoration,
|
||
SeparatorDecoration::Line | SeparatorDecoration::Double
|
||
) {
|
||
let glyph = if *decoration == SeparatorDecoration::Double {
|
||
"═"
|
||
} else {
|
||
"─"
|
||
};
|
||
Paragraph::new(glyph.repeat(usize::from(row_area.width)))
|
||
.style(style)
|
||
.render(line_area, buf);
|
||
}
|
||
let label = if label.is_empty() || *decoration == SeparatorDecoration::Plain {
|
||
(*label).to_owned()
|
||
} else {
|
||
format!(" {label} ")
|
||
};
|
||
Paragraph::new(label)
|
||
.alignment(Alignment::Center)
|
||
.style(style)
|
||
.render(line_area, buf);
|
||
continue;
|
||
};
|
||
let percent = item
|
||
.gain
|
||
.map_or(0, |gain| (gain.clamp(0.0, 1.0) * 100.0).round() as u16);
|
||
let state = if item.gain.is_none() {
|
||
"OFFLINE"
|
||
} else if item.mute_mixed || item.gain_mixed {
|
||
"MIXED"
|
||
} else if item.muted == Some(true) {
|
||
"MUTED"
|
||
} else if !item.writable {
|
||
"READ ONLY"
|
||
} else {
|
||
""
|
||
};
|
||
let meter_style = Style::default()
|
||
.bg(theme.meter_track)
|
||
.fg(if item.error.is_some() {
|
||
theme.error
|
||
} else if item.muted == Some(true) {
|
||
theme.warning
|
||
} else {
|
||
theme.secondary
|
||
});
|
||
if *density == FaderDensity::Slim {
|
||
let status = item.error.as_deref().map_or_else(
|
||
|| format!("{percent}% {state}"),
|
||
|error| format!("ERROR: {error}"),
|
||
);
|
||
Gauge::default()
|
||
.gauge_style(meter_style)
|
||
.percent(percent)
|
||
.label(format!(
|
||
"{} {} {status}",
|
||
if selected { "▶" } else { " " },
|
||
item.label
|
||
))
|
||
.render(row_area, buf);
|
||
continue;
|
||
}
|
||
if row_area.height < 2 {
|
||
break;
|
||
}
|
||
let pickup = pickup_display(
|
||
item.pickup,
|
||
self.snapshot.configuration.status_display,
|
||
theme,
|
||
);
|
||
let title = Line::from(vec![
|
||
Span::raw(format!(
|
||
"{} {} [{} · {}]{}",
|
||
if selected { "▶" } else { " " },
|
||
item.label,
|
||
match item.id.kind {
|
||
MixerObjectKind::Application => "application",
|
||
MixerObjectKind::Group => "group",
|
||
MixerObjectKind::Output => "output",
|
||
},
|
||
item.detail,
|
||
if item.pending { " … pending" } else { "" },
|
||
)),
|
||
Span::styled(
|
||
if pickup.text.is_empty() {
|
||
String::new()
|
||
} else {
|
||
format!(" {}", pickup.text)
|
||
},
|
||
pickup.style,
|
||
),
|
||
]);
|
||
let block = Block::bordered().title(title).border_style(if selected {
|
||
Style::default().fg(theme.accent)
|
||
} else {
|
||
Style::default().fg(theme.muted)
|
||
});
|
||
let meter = block.inner(row_area);
|
||
block.render(row_area, buf);
|
||
let label = item.error.as_deref().map_or_else(
|
||
|| format!("{percent}% {state}"),
|
||
|error| format!("ERROR: {error}"),
|
||
);
|
||
Gauge::default()
|
||
.gauge_style(meter_style)
|
||
.percent(percent)
|
||
.label(label)
|
||
.render(meter, buf);
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Default)]
|
||
struct DemoClient {
|
||
revision: u64,
|
||
gain: f64,
|
||
muted: bool,
|
||
}
|
||
|
||
impl DemoClient {
|
||
fn view(&self) -> MixerSnapshot {
|
||
MixerSnapshot {
|
||
revision: self.revision,
|
||
backend: "demo".into(),
|
||
status: "preview".into(),
|
||
error: None,
|
||
items: vec![MixerItem {
|
||
id: MixerObjectId {
|
||
kind: MixerObjectKind::Application,
|
||
id: "desktop".into(),
|
||
},
|
||
label: "Desktop audio".into(),
|
||
detail: "1 stream".into(),
|
||
gain: Some(if self.revision == 0 { 0.65 } else { self.gain }),
|
||
gain_mixed: false,
|
||
muted: Some(self.muted),
|
||
mute_mixed: false,
|
||
pending: false,
|
||
pickup: None,
|
||
writable: true,
|
||
error: None,
|
||
}],
|
||
devices: Vec::new(),
|
||
discovered_midi_ports: Vec::new(),
|
||
configuration: ConfigurationSnapshot::default(),
|
||
}
|
||
}
|
||
}
|
||
|
||
impl MixerClient for DemoClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Ok(self.view())
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.revision += 1;
|
||
self.gain = gain;
|
||
Ok(self.view())
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.revision += 1;
|
||
self.muted = !self.muted;
|
||
Ok(self.view())
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use std::{
|
||
sync::{
|
||
Mutex,
|
||
atomic::{AtomicBool, Ordering},
|
||
},
|
||
time::Instant,
|
||
};
|
||
|
||
use super::*;
|
||
|
||
fn press(code: KeyCode) -> KeyEvent {
|
||
KeyEvent::new(code, ratatui::crossterm::event::KeyModifiers::NONE)
|
||
}
|
||
|
||
fn shift(code: KeyCode) -> KeyEvent {
|
||
KeyEvent::new(code, KeyModifiers::SHIFT)
|
||
}
|
||
|
||
struct LayoutClient {
|
||
snapshot: MixerSnapshot,
|
||
edits: Arc<Mutex<Vec<ConfigurationEdit>>>,
|
||
}
|
||
|
||
impl MixerClient for LayoutClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
id: MixerObjectId,
|
||
gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
if let Some(item) = self.snapshot.items.iter_mut().find(|item| item.id == id) {
|
||
item.gain = Some(gain);
|
||
}
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn edit_configuration(
|
||
&mut self,
|
||
edit: ConfigurationEdit,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
match &edit {
|
||
ConfigurationEdit::AddApplicationFader { .. }
|
||
| ConfigurationEdit::AddGroupFader { .. }
|
||
| ConfigurationEdit::RemoveMixerFader { .. } => {
|
||
apply_optimistic_configuration_edit(&mut self.snapshot, &edit);
|
||
}
|
||
ConfigurationEdit::MoveLayoutEntry { id, position } => {
|
||
let index = self
|
||
.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.position(|entry| match entry {
|
||
MixerLayoutEntry::Fader { fader, .. } => fader == id,
|
||
MixerLayoutEntry::Separator { id: separator, .. } => separator == id,
|
||
})
|
||
.unwrap();
|
||
let entry = self.snapshot.configuration.mixer_layout.remove(index);
|
||
let position = (*position)
|
||
.min(self.snapshot.configuration.mixer_layout.len());
|
||
self.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.insert(position, entry);
|
||
}
|
||
ConfigurationEdit::SetFaderHidden { id, hidden } => {
|
||
if let Some(MixerLayoutEntry::Fader {
|
||
hidden: current, ..
|
||
}) = self.snapshot.configuration.mixer_layout.iter_mut().find(
|
||
|entry| matches!(entry, MixerLayoutEntry::Fader { fader, .. } if fader == id),
|
||
) {
|
||
*current = *hidden;
|
||
}
|
||
}
|
||
ConfigurationEdit::SetFaderDensity { id, density } => {
|
||
if let Some(MixerLayoutEntry::Fader {
|
||
density: current, ..
|
||
}) = self.snapshot.configuration.mixer_layout.iter_mut().find(
|
||
|entry| matches!(entry, MixerLayoutEntry::Fader { fader, .. } if fader == id),
|
||
) {
|
||
*current = *density;
|
||
}
|
||
}
|
||
ConfigurationEdit::SetMixerOrientation { orientation } => {
|
||
self.snapshot.configuration.mixer_orientation = *orientation;
|
||
}
|
||
ConfigurationEdit::SetStatusDisplay { mode } => {
|
||
self.snapshot.configuration.status_display = *mode;
|
||
}
|
||
ConfigurationEdit::SetDefaultController { surface } => {
|
||
self.snapshot.configuration.default_controller.clone_from(surface);
|
||
}
|
||
ConfigurationEdit::SetTheme { theme } => {
|
||
self.snapshot.configuration.theme = *theme;
|
||
}
|
||
ConfigurationEdit::AddSeparator {
|
||
id,
|
||
label,
|
||
position,
|
||
} => self.snapshot.configuration.mixer_layout.insert(
|
||
(*position).min(self.snapshot.configuration.mixer_layout.len()),
|
||
MixerLayoutEntry::Separator {
|
||
id: id.clone(),
|
||
label: label.clone(),
|
||
size: SeparatorSize::default(),
|
||
decoration: SeparatorDecoration::default(),
|
||
},
|
||
),
|
||
ConfigurationEdit::SetSeparatorLabel { id, label } => {
|
||
if let Some(MixerLayoutEntry::Separator {
|
||
label: current, ..
|
||
}) = self.snapshot.configuration.mixer_layout.iter_mut().find(
|
||
|entry| matches!(entry, MixerLayoutEntry::Separator { id: separator, .. } if separator == id),
|
||
) {
|
||
current.clone_from(label);
|
||
}
|
||
}
|
||
ConfigurationEdit::SetSeparatorPresentation { id, size, decoration } => {
|
||
if let Some(MixerLayoutEntry::Separator { size: current_size, decoration: current_decoration, .. }) =
|
||
self.snapshot.configuration.mixer_layout.iter_mut().find(|entry| matches!(entry, MixerLayoutEntry::Separator { id: separator, .. } if separator == id)) {
|
||
*current_size = *size;
|
||
*current_decoration = *decoration;
|
||
}
|
||
}
|
||
ConfigurationEdit::RemoveSeparator { id } => self
|
||
.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.retain(|entry| {
|
||
!matches!(entry, MixerLayoutEntry::Separator { id: separator, .. } if separator == id)
|
||
}),
|
||
ConfigurationEdit::SetApplicationSelector {
|
||
id,
|
||
index,
|
||
field,
|
||
pattern,
|
||
regex,
|
||
} => {
|
||
if let Some(selector) = self
|
||
.snapshot
|
||
.configuration
|
||
.applications
|
||
.iter_mut()
|
||
.find(|application| application.id == *id)
|
||
.and_then(|application| application.selectors.get_mut(*index))
|
||
{
|
||
selector.field.clone_from(field);
|
||
selector.pattern.clone_from(pattern);
|
||
selector.regex = *regex;
|
||
}
|
||
}
|
||
ConfigurationEdit::Group { id, members, .. } => {
|
||
if let Some(group) = self
|
||
.snapshot
|
||
.configuration
|
||
.groups
|
||
.iter_mut()
|
||
.find(|group| group.id == *id)
|
||
{
|
||
group.members.clone_from(members);
|
||
}
|
||
}
|
||
ConfigurationEdit::RemoveBinding { fader, action } => self
|
||
.snapshot
|
||
.configuration
|
||
.bindings
|
||
.retain(|binding| binding.fader != *fader || binding.action != *action),
|
||
ConfigurationEdit::SetBinding {
|
||
surface,
|
||
fader,
|
||
action,
|
||
kind,
|
||
channel,
|
||
number,
|
||
} => {
|
||
if let Some(binding) = self
|
||
.snapshot
|
||
.configuration
|
||
.bindings
|
||
.iter_mut()
|
||
.find(|binding| binding.fader == *fader && binding.action == *action)
|
||
{
|
||
binding.surface.clone_from(surface);
|
||
binding.kind.clone_from(kind);
|
||
binding.channel = *channel;
|
||
binding.number = *number;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
self.snapshot.configuration.revision += 1;
|
||
self.edits.lock().unwrap().push(edit);
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn start_midi_learn(
|
||
&mut self,
|
||
surface: String,
|
||
fader: String,
|
||
action: String,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.snapshot.configuration.learning = Some(format!("{surface} -> {fader} ({action})"));
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn cancel_midi_learn(&mut self) -> io::Result<MixerSnapshot> {
|
||
self.snapshot.configuration.learning = None;
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn save_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||
self.snapshot.configuration.dirty = false;
|
||
self.snapshot.configuration.applied_revision = expected_revision;
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn switch_profile(&mut self, id: String) -> io::Result<MixerSnapshot> {
|
||
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]
|
||
fn volume_and_mute_keys_update_through_the_client() {
|
||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||
app.handle_key_event(press(KeyCode::End));
|
||
assert_eq!(app.snapshot.items[0].gain, Some(1.0));
|
||
app.handle_key_event(press(KeyCode::Char('m')));
|
||
assert_eq!(app.snapshot.items[0].muted, Some(true));
|
||
}
|
||
|
||
#[test]
|
||
fn horizontal_arrow_keys_select_across_and_adjust_volume_vertically() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
let mut second = snapshot.items[0].clone();
|
||
snapshot.items[0].id.id = "music".into();
|
||
second.id.id = "browser".into();
|
||
snapshot.items.push(second);
|
||
snapshot.configuration.mixer_orientation = MixerOrientation::Horizontal;
|
||
snapshot.configuration.faders = vec![
|
||
ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
ConfiguredFader {
|
||
id: "browser-fader".into(),
|
||
target: snapshot.items[1].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
];
|
||
snapshot.configuration.mixer_layout = vec![
|
||
MixerLayoutEntry::Fader {
|
||
fader: "music-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
MixerLayoutEntry::Fader {
|
||
fader: "browser-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
];
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
assert_eq!(app.selected, 1);
|
||
app.handle_key_event(press(KeyCode::Left));
|
||
assert_eq!(app.selected, 0);
|
||
|
||
app.handle_key_event(press(KeyCode::Up));
|
||
assert!((app.snapshot.items[0].gain.unwrap_or_default() - 0.7).abs() < f64::EPSILON);
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
assert!((app.snapshot.items[0].gain.unwrap_or_default() - 0.65).abs() < f64::EPSILON);
|
||
|
||
app.handle_key_event(shift(KeyCode::Right));
|
||
assert!(edits.lock().unwrap().iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::MoveLayoutEntry { id, position: 1 }
|
||
if id == "music-fader"
|
||
)));
|
||
assert_eq!(
|
||
app.mixer_rows()
|
||
.iter()
|
||
.map(|row| row.id())
|
||
.collect::<Vec<_>>(),
|
||
["browser-fader", "music-fader"]
|
||
);
|
||
|
||
app.handle_key_event(shift(KeyCode::Char('k')));
|
||
assert!(matches!(
|
||
edits.lock().unwrap().last(),
|
||
Some(ConfigurationEdit::MoveLayoutEntry { id, position: 0 })
|
||
if id == "music-fader"
|
||
));
|
||
assert_eq!(app.selected, 0);
|
||
assert_eq!(
|
||
app.mixer_rows()
|
||
.iter()
|
||
.map(|row| row.id())
|
||
.collect::<Vec<_>>(),
|
||
["music-fader", "browser-fader"]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn quit_requires_confirmation_and_escape_does_not_quit() {
|
||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
assert_eq!(app.selected, 0);
|
||
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
assert!(!app.exit);
|
||
|
||
app.handle_key_event(press(KeyCode::Char('q')));
|
||
assert!(!app.exit);
|
||
let area = Rect::new(0, 0, 80, 20);
|
||
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("Quit fader_master?"));
|
||
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
app.handle_key_event(press(KeyCode::Char('y')));
|
||
assert!(!app.exit);
|
||
|
||
app.handle_key_event(press(KeyCode::Char('q')));
|
||
app.handle_key_event(press(KeyCode::Char('n')));
|
||
app.handle_key_event(press(KeyCode::Char('y')));
|
||
assert!(!app.exit);
|
||
|
||
app.handle_key_event(press(KeyCode::Char('q')));
|
||
app.handle_key_event(press(KeyCode::Char('y')));
|
||
assert!(app.exit);
|
||
}
|
||
|
||
#[test]
|
||
fn profile_reset_requires_confirmation_and_can_be_cancelled() {
|
||
struct ResetClient {
|
||
reset: Arc<AtomicBool>,
|
||
}
|
||
|
||
impl MixerClient for ResetClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Ok(DemoClient::default().view())
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn reset_configuration(
|
||
&mut self,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.reset.store(true, Ordering::SeqCst);
|
||
Ok(DemoClient::default().view())
|
||
}
|
||
}
|
||
|
||
let reset = Arc::new(AtomicBool::new(false));
|
||
let mut app = LiveTui::new(ResetClient {
|
||
reset: Arc::clone(&reset),
|
||
})
|
||
.unwrap();
|
||
app.tab = Tab::Configuration;
|
||
app.settings_selected = app
|
||
.settings_rows()
|
||
.iter()
|
||
.position(|row| matches!(row, SettingsRow::Reset))
|
||
.unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let area = Rect::new(0, 0, 80, 20);
|
||
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("Reset the active profile to safe defaults?"));
|
||
assert!(!reset.load(Ordering::SeqCst));
|
||
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
app.handle_key_event(press(KeyCode::Char('y')));
|
||
assert!(!reset.load(Ordering::SeqCst));
|
||
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
app.handle_key_event(press(KeyCode::Char('y')));
|
||
assert!(reset.load(Ordering::SeqCst));
|
||
}
|
||
|
||
#[test]
|
||
fn help_keys_open_detailed_keyboard_help_without_hiding() {
|
||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||
app.handle_key_event(press(KeyCode::Char('h')));
|
||
|
||
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("Keyboard help"));
|
||
assert!(rendered.contains("Shift+H"));
|
||
assert!(rendered.contains("Add a fader, group, or separator"));
|
||
assert!(rendered.contains("Edit the selected entry"));
|
||
assert!(rendered.contains("Delete the selected entry"));
|
||
assert!(rendered.contains("Save the configuration"));
|
||
assert!(rendered.contains("Home/End"));
|
||
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
assert!(!app.exit);
|
||
app.handle_key_event(press(KeyCode::Char('?')));
|
||
let mut question_buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut question_buffer);
|
||
let question_rendered = question_buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(question_rendered.contains("Keyboard help"));
|
||
}
|
||
|
||
#[test]
|
||
fn quick_help_keeps_only_distinct_non_obvious_actions() {
|
||
let app = LiveTui::new(DemoClient::default()).unwrap();
|
||
let area = Rect::new(0, 0, 160, 20);
|
||
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(" A add"));
|
||
assert!(rendered.contains(" E edit"));
|
||
assert!(rendered.contains(" D delete"));
|
||
assert!(rendered.contains(" h help"));
|
||
assert!(!rendered.contains("Home/End"));
|
||
assert!(!rendered.contains("A/E/D"));
|
||
assert!(!rendered.contains("/jk"));
|
||
assert!(!rendered.contains("h/?"));
|
||
assert!(!rendered.contains("volume"));
|
||
assert!(!rendered.contains("move"));
|
||
}
|
||
|
||
#[test]
|
||
fn revision_conflicts_are_shown_as_recoverable_warnings() {
|
||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||
app.client_error = Some("stale configuration revision 4; current revision is 5".to_owned());
|
||
let area = Rect::new(0, 0, 100, 20);
|
||
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("stale configuration revision"));
|
||
let warning = app.theme().palette().warning;
|
||
assert!(
|
||
buffer
|
||
.content
|
||
.iter()
|
||
.filter(|cell| cell.fg == warning && cell.symbol() != " ")
|
||
.count()
|
||
>= "staleconfigurationrevision".len()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn add_chooses_fader_group_or_separator_and_opens_the_relevant_editor() {
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot: DemoClient::default().view(),
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Char('a')));
|
||
let area = Rect::new(0, 0, 90, 22);
|
||
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("Add to mixer"));
|
||
assert!(rendered.contains("Fader"));
|
||
assert!(rendered.contains("Group"));
|
||
assert!(rendered.contains("Separator"));
|
||
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
for character in "Chat".chars() {
|
||
app.handle_key_event(press(KeyCode::Char(character)));
|
||
}
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
assert!(app.fader_editor.is_some());
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
|
||
app.handle_key_event(press(KeyCode::Char('a')));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
for character in "Players".chars() {
|
||
app.handle_key_event(press(KeyCode::Char(character)));
|
||
}
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
assert!(app.fader_editor.is_some());
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
|
||
app.handle_key_event(press(KeyCode::Char('a')));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
for character in "Inputs".chars() {
|
||
app.handle_key_event(press(KeyCode::Char(character)));
|
||
}
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
|
||
let edits = edits.lock().unwrap();
|
||
assert!(matches!(
|
||
&edits[0],
|
||
ConfigurationEdit::AddApplicationFader {
|
||
application_id,
|
||
label,
|
||
fader_id,
|
||
..
|
||
} if application_id == "chat" && label == "Chat" && fader_id == "chat-fader"
|
||
));
|
||
assert!(matches!(
|
||
&edits[1],
|
||
ConfigurationEdit::AddGroupFader {
|
||
group_id,
|
||
label,
|
||
fader_id,
|
||
..
|
||
} if group_id == "players" && label == "Players" && fader_id == "players-fader"
|
||
));
|
||
assert!(matches!(
|
||
&edits[2],
|
||
ConfigurationEdit::AddSeparator { label, .. } if label == "Inputs"
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn delete_is_generic_and_requires_confirmation() {
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.configuration.applications = vec![ConfiguredApplication {
|
||
id: "desktop".into(),
|
||
label: "Desktop audio".into(),
|
||
selectors: vec![ConfiguredSelector {
|
||
field: "application.name".into(),
|
||
pattern: "Desktop audio".into(),
|
||
regex: false,
|
||
}],
|
||
}];
|
||
snapshot.configuration.faders = vec![ConfiguredFader {
|
||
id: "desktop-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
}];
|
||
snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader {
|
||
fader: "desktop-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
}];
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Char('d')));
|
||
assert!(app.delete_confirmation.is_some());
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
assert!(edits.lock().unwrap().is_empty());
|
||
|
||
app.handle_key_event(press(KeyCode::Char('d')));
|
||
app.handle_key_event(press(KeyCode::Char('y')));
|
||
assert!(matches!(
|
||
edits.lock().unwrap().as_slice(),
|
||
[ConfigurationEdit::RemoveMixerFader { id }] if id == "desktop-fader"
|
||
));
|
||
assert!(app.snapshot.configuration.faders.is_empty());
|
||
assert!(app.snapshot.configuration.applications.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn add_and_delete_popups_render_at_tiny_terminal_sizes() {
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.configuration.faders = vec![ConfiguredFader {
|
||
id: "master-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
}];
|
||
snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader {
|
||
fader: "master-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
}];
|
||
let mut app = LiveTui::new(LayoutClient { snapshot, edits }).unwrap();
|
||
|
||
for (width, height) in [(1, 1), (8, 3), (24, 7)] {
|
||
app.handle_key_event(press(KeyCode::Char('a')));
|
||
let area = Rect::new(0, 0, width, height);
|
||
let mut buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut buffer);
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let mut buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut buffer);
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
|
||
app.handle_key_event(press(KeyCode::Char('d')));
|
||
let mut buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut buffer);
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn unnamed_separators_are_accepted_with_unique_ids() {
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot: DemoClient::default().view(),
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
for _ in 0..2 {
|
||
app.handle_key_event(press(KeyCode::Char('a')));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
assert!(app.editor.is_none(), "blank name must be accepted");
|
||
}
|
||
let edits = edits.lock().unwrap();
|
||
let ids = edits
|
||
.iter()
|
||
.filter_map(|edit| match edit {
|
||
ConfigurationEdit::AddSeparator { id, label, .. } => {
|
||
assert!(label.is_empty());
|
||
Some(id)
|
||
}
|
||
_ => None,
|
||
})
|
||
.collect::<Vec<_>>();
|
||
assert_eq!(ids.len(), 2);
|
||
assert_ne!(ids[0], ids[1]);
|
||
}
|
||
|
||
#[test]
|
||
fn separator_popup_edits_size_and_decoration_and_cancel_discards_changes() {
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Separator {
|
||
id: "heading".into(),
|
||
label: "Heading".into(),
|
||
size: SeparatorSize::Standard,
|
||
decoration: SeparatorDecoration::Line,
|
||
}];
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
app.handle_key_event(press(KeyCode::Char('e')));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
assert!(matches!(
|
||
&app.snapshot.configuration.mixer_layout[0],
|
||
MixerLayoutEntry::Separator {
|
||
size: SeparatorSize::Fill,
|
||
decoration: SeparatorDecoration::Double,
|
||
..
|
||
}
|
||
));
|
||
let count = edits.lock().unwrap().len();
|
||
app.handle_key_event(press(KeyCode::Char('e')));
|
||
assert_eq!(app.editor.as_ref().unwrap().size, SeparatorSize::Fill);
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Left));
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
assert_eq!(edits.lock().unwrap().len(), count);
|
||
assert!(app.editor.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn fill_separators_share_leftover_space_without_displacing_faders() {
|
||
let snapshot = DemoClient::default().view();
|
||
let fader = || MixerRow::Fader {
|
||
layout_id: None,
|
||
item: &snapshot.items[0],
|
||
density: FaderDensity::Standard,
|
||
};
|
||
let spacer = || MixerRow::Separator {
|
||
id: "gap",
|
||
label: "Gap",
|
||
size: SeparatorSize::Fill,
|
||
decoration: SeparatorDecoration::Plain,
|
||
};
|
||
let rows = vec![fader(), spacer(), fader(), spacer()];
|
||
assert_eq!(
|
||
mixer_viewport(&rows, 0, 60, true),
|
||
(0, vec![16, 14, 16, 14])
|
||
);
|
||
assert_eq!(mixer_viewport(&rows, 0, 20, false), (0, vec![4, 6, 4, 6]));
|
||
for horizontal in [false, true] {
|
||
for available in 0..80 {
|
||
for selected in 0..rows.len() {
|
||
let (start, extents) = mixer_viewport(&rows, selected, available, horizontal);
|
||
assert!(extents.iter().copied().sum::<u16>() <= available);
|
||
if available > 0 {
|
||
assert!(start <= selected && selected < start + extents.len());
|
||
assert!(extents.iter().all(|extent| *extent > 0));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn separator_decorations_render_in_both_orientations_at_small_sizes() {
|
||
let app = LiveTui::new(DemoClient::default()).unwrap();
|
||
for horizontal in [false, true] {
|
||
for size in [
|
||
SeparatorSize::Slim,
|
||
SeparatorSize::Standard,
|
||
SeparatorSize::Thick,
|
||
SeparatorSize::Fill,
|
||
] {
|
||
for decoration in [
|
||
SeparatorDecoration::Plain,
|
||
SeparatorDecoration::Line,
|
||
SeparatorDecoration::Double,
|
||
SeparatorDecoration::Box,
|
||
] {
|
||
let rows = vec![MixerRow::Separator {
|
||
id: "heading",
|
||
label: "Heading",
|
||
size,
|
||
decoration,
|
||
}];
|
||
for (width, height) in [(1, 1), (8, 3), (60, 20)] {
|
||
let area = Rect::new(0, 0, width, height);
|
||
let mut buffer = Buffer::empty(area);
|
||
if horizontal {
|
||
app.render_fader_strips(area, &mut buffer, &rows);
|
||
} else {
|
||
app.render_vertical_streams(area, &mut buffer, &rows);
|
||
}
|
||
if width == 60 {
|
||
let rendered = buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
match decoration {
|
||
SeparatorDecoration::Plain => {
|
||
assert!(!rendered.contains(['│', '─', '║', '═', '┌']))
|
||
}
|
||
SeparatorDecoration::Line => {
|
||
assert!(rendered.contains(if horizontal {
|
||
'│'
|
||
} else {
|
||
'─'
|
||
}))
|
||
}
|
||
SeparatorDecoration::Double => {
|
||
assert!(rendered.contains(if horizontal {
|
||
'║'
|
||
} else {
|
||
'═'
|
||
}))
|
||
}
|
||
SeparatorDecoration::Box => assert!(rendered.contains('┌')),
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn separator_name_is_edited_in_a_centered_popup() {
|
||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||
app.handle_key_event(press(KeyCode::Char('a')));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
for character in "Music".chars() {
|
||
app.handle_key_event(press(KeyCode::Char(character)));
|
||
}
|
||
|
||
let area = Rect::new(0, 0, 80, 20);
|
||
let mut buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut buffer);
|
||
let rows = buffer
|
||
.content
|
||
.chunks(usize::from(area.width))
|
||
.map(|row| row.iter().map(|cell| cell.symbol()).collect::<String>())
|
||
.collect::<Vec<_>>();
|
||
|
||
assert!(rows[5..15].iter().any(|row| row.contains("Add separator")));
|
||
assert!(rows[6..14].iter().any(|row| row.contains("Name Music")));
|
||
assert!(rows[5..15].iter().any(|row| row.contains("Enter accept")));
|
||
assert!(!rows.iter().any(|row| row.contains("separator name:")));
|
||
|
||
app.editor = Some(EditorInput {
|
||
value: "Players".to_owned(),
|
||
target: Some("players".to_owned()),
|
||
..EditorInput::default()
|
||
});
|
||
let mut rename_buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut rename_buffer);
|
||
let renamed = rename_buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(renamed.contains("Edit separator"));
|
||
assert!(renamed.contains("Name Players"));
|
||
}
|
||
|
||
#[test]
|
||
fn terminal_restore_runs_when_client_initialization_fails() {
|
||
struct FailingClient;
|
||
|
||
impl MixerClient for FailingClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Err(io::Error::other("injected client failure"))
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
}
|
||
|
||
let restored = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||
let restore_flag = Arc::clone(&restored);
|
||
let result = with_terminal_restore(
|
||
move || restore_flag.store(true, std::sync::atomic::Ordering::Release),
|
||
|| LiveTui::new(FailingClient).map(|_| ()),
|
||
);
|
||
|
||
assert_eq!(result.unwrap_err().to_string(), "injected client failure");
|
||
assert!(restored.load(std::sync::atomic::Ordering::Acquire));
|
||
}
|
||
|
||
#[test]
|
||
fn theme_key_cycles_known_palettes_and_wraps() {
|
||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||
assert_eq!(app.theme(), ThemeName::Default);
|
||
for expected in [
|
||
ThemeName::Dracula,
|
||
ThemeName::Nord,
|
||
ThemeName::GruvboxDark,
|
||
ThemeName::CatppuccinMocha,
|
||
ThemeName::SolarizedDark,
|
||
ThemeName::Default,
|
||
] {
|
||
app.handle_key_event(press(KeyCode::Char('t')));
|
||
assert_eq!(app.theme(), expected);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn selected_theme_is_visible_and_changes_the_render_palette() {
|
||
let app = LiveTui::with_theme(DemoClient::default(), ThemeName::Dracula).unwrap();
|
||
let area = Rect::new(0, 0, 100, 20);
|
||
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("Dracula"));
|
||
assert!(buffer.content.iter().any(|cell| {
|
||
cell.fg == ratatui::style::Color::Rgb(189, 147, 249)
|
||
|| cell.bg == ratatui::style::Color::Rgb(40, 42, 54)
|
||
}));
|
||
}
|
||
|
||
#[test]
|
||
fn saved_profile_theme_is_used_without_a_cli_override() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.configuration.theme = ThemeName::Nord;
|
||
let app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::new(Mutex::new(Vec::new())),
|
||
})
|
||
.unwrap();
|
||
|
||
assert_eq!(app.theme(), ThemeName::Nord);
|
||
}
|
||
|
||
#[test]
|
||
fn live_mixer_renders_status_and_stream_at_typical_size() {
|
||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||
app.snapshot.items[0].pickup = Some(PickupStatus::Waiting);
|
||
app.snapshot.devices.push(MidiDevice {
|
||
id: "apc-mini".into(),
|
||
label: "APC MINI".into(),
|
||
status: "missing".into(),
|
||
backend_id: None,
|
||
error: None,
|
||
});
|
||
let area = Rect::new(0, 0, 100, 20);
|
||
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("FADER"));
|
||
assert!(rendered.contains("Desktop audio"));
|
||
assert!(rendered.contains("65%"));
|
||
assert!(rendered.contains("pickup: waiting"));
|
||
assert!(rendered.contains("APC MINI: missing — connect device"));
|
||
assert!(rendered.contains(" Q "));
|
||
assert!(!rendered.contains("Q/Esc"));
|
||
}
|
||
|
||
#[test]
|
||
fn pickup_status_display_modes_use_distinct_feedback() {
|
||
let theme = ThemeName::Default.palette();
|
||
|
||
assert_eq!(
|
||
pickup_display(
|
||
Some(PickupStatus::Tracking),
|
||
StatusDisplayMode::Detailed,
|
||
theme
|
||
)
|
||
.text,
|
||
"pickup: tracking"
|
||
);
|
||
assert_eq!(
|
||
pickup_display(
|
||
Some(PickupStatus::Tracking),
|
||
StatusDisplayMode::Compact,
|
||
theme
|
||
)
|
||
.text,
|
||
"LIVE"
|
||
);
|
||
assert_eq!(
|
||
pickup_display(
|
||
Some(PickupStatus::Waiting),
|
||
StatusDisplayMode::Symbol,
|
||
theme
|
||
)
|
||
.text,
|
||
"○"
|
||
);
|
||
|
||
let tracking = pickup_display(
|
||
Some(PickupStatus::Tracking),
|
||
StatusDisplayMode::Color,
|
||
theme,
|
||
);
|
||
let unavailable = pickup_display(
|
||
Some(PickupStatus::Unavailable),
|
||
StatusDisplayMode::Color,
|
||
theme,
|
||
);
|
||
assert_eq!(tracking.text, "●");
|
||
assert_eq!(unavailable.text, "●");
|
||
assert_ne!(tracking.style, unavailable.style);
|
||
assert_eq!(
|
||
pickup_display(Some(PickupStatus::Mixed), StatusDisplayMode::Hidden, theme).text,
|
||
""
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn mixer_layout_reorders_and_hides_while_settings_restores_faders() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.items[0].id.id = "music".into();
|
||
snapshot.items[0].label = "Music".into();
|
||
let mut hidden = snapshot.items[0].clone();
|
||
hidden.id.id = "browser".into();
|
||
hidden.label = "Browser".into();
|
||
snapshot.items.push(hidden);
|
||
snapshot.configuration.faders = vec![
|
||
ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
ConfiguredFader {
|
||
id: "browser-fader".into(),
|
||
target: snapshot.items[1].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
];
|
||
snapshot.configuration.mixer_layout = vec![
|
||
MixerLayoutEntry::Separator {
|
||
id: "players".into(),
|
||
label: "Players".into(),
|
||
size: SeparatorSize::Standard,
|
||
decoration: SeparatorDecoration::Line,
|
||
},
|
||
MixerLayoutEntry::Fader {
|
||
fader: "music-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
MixerLayoutEntry::Fader {
|
||
fader: "browser-fader".into(),
|
||
hidden: true,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
];
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
|
||
let area = Rect::new(0, 0, 100, 20);
|
||
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("Players"));
|
||
assert!(rendered.contains("Music"));
|
||
assert!(!rendered.contains("Browser"));
|
||
|
||
app.handle_key_event(shift(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Up));
|
||
app.handle_key_event(shift(KeyCode::Char('H')));
|
||
app.handle_key_event(press(KeyCode::Tab));
|
||
let mut hidden_buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut hidden_buffer);
|
||
let hidden_rendered = hidden_buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(hidden_rendered.contains("Show hidden faders 2 [Enter]"));
|
||
assert!(!hidden_rendered.contains("Show hidden fader Music"));
|
||
assert!(!hidden_rendered.contains("Show hidden fader Browser"));
|
||
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let mut popup_buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut popup_buffer);
|
||
let popup_rendered = popup_buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(popup_rendered.contains("Show hidden faders"));
|
||
assert!(popup_rendered.contains("Music"));
|
||
assert!(popup_rendered.contains("Browser"));
|
||
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let mut remaining_buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut remaining_buffer);
|
||
let remaining_rendered = remaining_buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(!remaining_rendered.contains("Music"));
|
||
assert!(remaining_rendered.contains("Browser"));
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
app.handle_key_event(press(KeyCode::Tab));
|
||
app.handle_key_event(press(KeyCode::Char('a')));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
for character in "Outputs".chars() {
|
||
app.handle_key_event(press(KeyCode::Char(character)));
|
||
}
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
|
||
let edits = edits.lock().unwrap();
|
||
assert!(matches!(
|
||
edits[0],
|
||
ConfigurationEdit::MoveLayoutEntry { ref id, position: 1 } if id == "players"
|
||
));
|
||
assert!(edits.iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::SetFaderHidden { id, hidden: true } if id == "music-fader"
|
||
)));
|
||
assert!(edits.iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::SetFaderHidden { id, hidden: false } if id == "music-fader"
|
||
)));
|
||
assert!(edits.iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::AddSeparator { label, .. } if label == "Outputs"
|
||
)));
|
||
}
|
||
|
||
#[test]
|
||
fn selected_fader_opens_guided_capture_binding_and_visibility_form() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.items[0].id.id = "music".into();
|
||
snapshot.items[0].label = "Music".into();
|
||
snapshot.configuration.applications = vec![ConfiguredApplication {
|
||
id: "music".into(),
|
||
label: "Music".into(),
|
||
selectors: vec![ConfiguredSelector {
|
||
field: "application.name".into(),
|
||
pattern: "Old Player".into(),
|
||
regex: false,
|
||
}],
|
||
}];
|
||
snapshot.configuration.faders = vec![ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
}];
|
||
snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader {
|
||
fader: "music-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
}];
|
||
snapshot.configuration.bindings = vec![ConfiguredBinding {
|
||
surface: "desk".into(),
|
||
fader: "music-fader".into(),
|
||
action: "volume".into(),
|
||
message: "cc ch1 #7".into(),
|
||
kind: "cc".into(),
|
||
channel: 1,
|
||
number: 7,
|
||
}];
|
||
snapshot.configuration.default_controller = Some("spare".into());
|
||
snapshot.devices = vec![
|
||
MidiDevice {
|
||
id: "desk".into(),
|
||
label: "Desk controller".into(),
|
||
status: "connected".into(),
|
||
backend_id: Some("20:0".into()),
|
||
error: None,
|
||
},
|
||
MidiDevice {
|
||
id: "spare".into(),
|
||
label: "Spare controller".into(),
|
||
status: "connected".into(),
|
||
backend_id: Some("21:0".into()),
|
||
error: None,
|
||
},
|
||
];
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Char('e')));
|
||
let area = Rect::new(0, 0, 100, 22);
|
||
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("Edit fader: music-fader"));
|
||
assert!(rendered.contains("Capture 1"));
|
||
assert!(rendered.contains("Volume controller"));
|
||
assert!(rendered.contains("Learn volume MIDI"));
|
||
assert!(rendered.contains("Unlearn volume MIDI"));
|
||
assert!(rendered.contains("Mute controller"));
|
||
assert!(rendered.contains("Mute controller Default · Spare controller"));
|
||
assert!(rendered.contains("Learn mute MIDI"));
|
||
assert!(rendered.contains("Unlearn mute MIDI"));
|
||
assert!(rendered.contains("Size Standard"));
|
||
assert!(rendered.contains("Visibility"));
|
||
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let mut pattern_editor = Buffer::empty(area);
|
||
(&app).render(area, &mut pattern_editor);
|
||
let pattern_rendered = pattern_editor
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(pattern_rendered.contains("Edit capture pattern"));
|
||
assert!(pattern_rendered.contains('▏'));
|
||
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
assert!(app.pattern_editor.is_none());
|
||
assert_eq!(
|
||
app.capture_editor
|
||
.as_ref()
|
||
.map(|editor| editor.pattern.as_str()),
|
||
Some("Old Player")
|
||
);
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
|
||
app.handle_key_event(press(KeyCode::Home));
|
||
for _ in 0..4 {
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
}
|
||
app.handle_key_event(press(KeyCode::Delete));
|
||
app.handle_key_event(press(KeyCode::Char('p')));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let mut picker = Buffer::empty(area);
|
||
(&app).render(area, &mut picker);
|
||
let picker_rendered = picker
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(picker_rendered.contains("Choose controller"));
|
||
assert!(picker_rendered.contains("Desk controller"));
|
||
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let mut waiting = Buffer::empty(area);
|
||
(&app).render(area, &mut waiting);
|
||
let waiting_rendered = waiting
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(waiting_rendered.contains("Learn MIDI control"));
|
||
assert!(waiting_rendered.contains("Move a fader or press a button"));
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
|
||
let edits = edits.lock().unwrap();
|
||
assert!(edits.iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::SetApplicationSelector {
|
||
id,
|
||
field,
|
||
pattern,
|
||
regex: true,
|
||
..
|
||
} if id == "music" && field == "application.id" && pattern == "Old player"
|
||
)));
|
||
assert!(edits.iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::SetBinding { surface, fader, action, .. }
|
||
if surface == "spare" && fader == "music-fader" && action == "volume"
|
||
)));
|
||
assert!(edits.iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::RemoveBinding { fader, action }
|
||
if fader == "music-fader" && action == "volume"
|
||
)));
|
||
}
|
||
|
||
#[test]
|
||
fn unassigned_midi_actions_learn_from_the_configured_default_controller() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.items[0].id.id = "music".into();
|
||
snapshot.configuration.applications = vec![ConfiguredApplication {
|
||
id: "music".into(),
|
||
label: "Music".into(),
|
||
selectors: Vec::new(),
|
||
}];
|
||
snapshot.configuration.faders = vec![ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
}];
|
||
snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader {
|
||
fader: "music-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
}];
|
||
snapshot.configuration.default_controller = Some("desk".into());
|
||
snapshot.devices = vec![MidiDevice {
|
||
id: "desk".into(),
|
||
label: "Desk controller".into(),
|
||
status: "connected".into(),
|
||
backend_id: Some("20:0".into()),
|
||
error: None,
|
||
}];
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient { snapshot, edits }).unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Char('e')));
|
||
let rows = app.fader_editor_rows();
|
||
assert!(matches!(
|
||
&rows[0],
|
||
FaderEditorRow::BindingController { value, .. }
|
||
if value == "Default · Desk controller"
|
||
));
|
||
app.fader_editor.as_mut().unwrap().selected = 1;
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
|
||
assert_eq!(
|
||
app.snapshot.configuration.learning.as_deref(),
|
||
Some("desk -> music-fader (volume)")
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn dirty_fader_editor_exposes_save_and_activates_the_draft() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.items[0].id.id = "music".into();
|
||
snapshot.configuration.faders = vec![ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
}];
|
||
snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader {
|
||
fader: "music-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
}];
|
||
snapshot.configuration.dirty = true;
|
||
snapshot.configuration.revision = 4;
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient { snapshot, edits }).unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Char('e')));
|
||
let area = Rect::new(0, 0, 100, 22);
|
||
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("Save changes"));
|
||
|
||
app.fader_editor.as_mut().unwrap().selected = app.fader_editor_rows().len() - 1;
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
|
||
assert!(!app.snapshot.configuration.dirty);
|
||
assert_eq!(app.snapshot.configuration.applied_revision, 4);
|
||
}
|
||
|
||
#[test]
|
||
fn fader_density_cycles_and_compact_rows_render_at_their_exact_heights() {
|
||
assert_eq!(FaderDensity::Slim.next(), FaderDensity::BorderedSlim);
|
||
assert_eq!(FaderDensity::BorderedSlim.next(), FaderDensity::Standard);
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.items[0].id.id = "music".into();
|
||
snapshot.items[0].label = "Music".into();
|
||
snapshot.configuration.applications = vec![ConfiguredApplication {
|
||
id: "music".into(),
|
||
label: "Music".into(),
|
||
selectors: Vec::new(),
|
||
}];
|
||
snapshot.configuration.faders = vec![ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
}];
|
||
snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader {
|
||
fader: "music-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
}];
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Char('e')));
|
||
for _ in 0..6 {
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
}
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
assert!(edits.lock().unwrap().iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::SetFaderDensity {
|
||
id,
|
||
density: FaderDensity::Thick
|
||
} if id == "music-fader"
|
||
)));
|
||
|
||
app.fader_editor = None;
|
||
if let MixerLayoutEntry::Fader { density, .. } =
|
||
&mut app.snapshot.configuration.mixer_layout[0]
|
||
{
|
||
*density = FaderDensity::Slim;
|
||
}
|
||
app.snapshot.configuration.mixer_orientation = MixerOrientation::Vertical;
|
||
let area = Rect::new(0, 0, 80, 1);
|
||
let mut buffer = Buffer::empty(area);
|
||
app.render_streams(area, &mut buffer);
|
||
let rendered = buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(rendered.contains("Music"));
|
||
assert!(rendered.contains("65%"));
|
||
|
||
if let MixerLayoutEntry::Fader { density, .. } =
|
||
&mut app.snapshot.configuration.mixer_layout[0]
|
||
{
|
||
*density = FaderDensity::BorderedSlim;
|
||
}
|
||
let area = Rect::new(0, 0, 80, 3);
|
||
let mut buffer = Buffer::empty(area);
|
||
app.render_streams(area, &mut buffer);
|
||
let rendered = buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(rendered.contains('┌'));
|
||
assert!(rendered.contains("Music"));
|
||
assert!(rendered.contains("65%"));
|
||
}
|
||
|
||
#[test]
|
||
fn vertical_mixer_keeps_stacked_fader_cards() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
let mut second = snapshot.items[0].clone();
|
||
snapshot.items[0].id.id = "music".into();
|
||
snapshot.items[0].label = "Music".into();
|
||
second.id.id = "browser".into();
|
||
second.label = "Browser".into();
|
||
snapshot.items.push(second);
|
||
snapshot.configuration.mixer_orientation = MixerOrientation::Vertical;
|
||
snapshot.configuration.faders = vec![
|
||
ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
ConfiguredFader {
|
||
id: "browser-fader".into(),
|
||
target: snapshot.items[1].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
];
|
||
snapshot.configuration.mixer_layout = vec![
|
||
MixerLayoutEntry::Fader {
|
||
fader: "music-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
MixerLayoutEntry::Fader {
|
||
fader: "browser-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
];
|
||
let app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::new(Mutex::new(Vec::new())),
|
||
})
|
||
.unwrap();
|
||
let area = Rect::new(0, 0, 80, 8);
|
||
let mut buffer = Buffer::empty(area);
|
||
app.render_streams(area, &mut buffer);
|
||
let rows = buffer
|
||
.content
|
||
.chunks(usize::from(area.width))
|
||
.map(|row| row.iter().map(|cell| cell.symbol()).collect::<String>())
|
||
.collect::<Vec<_>>();
|
||
let music_row = rows.iter().position(|row| row.contains("Music")).unwrap();
|
||
let browser_row = rows.iter().position(|row| row.contains("Browser")).unwrap();
|
||
assert_ne!(music_row, browser_row, "vertical cards remain stacked");
|
||
}
|
||
|
||
#[test]
|
||
fn horizontal_mixer_keeps_faders_and_separators_on_one_row() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
let mut second = snapshot.items[0].clone();
|
||
snapshot.items[0].id.id = "music".into();
|
||
snapshot.items[0].label = "Music".into();
|
||
second.id.id = "browser".into();
|
||
second.label = "Browser".into();
|
||
snapshot.items.push(second);
|
||
snapshot.configuration.mixer_orientation = MixerOrientation::Horizontal;
|
||
snapshot.configuration.faders = vec![
|
||
ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
ConfiguredFader {
|
||
id: "browser-fader".into(),
|
||
target: snapshot.items[1].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
];
|
||
snapshot.configuration.mixer_layout = vec![
|
||
MixerLayoutEntry::Fader {
|
||
fader: "music-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
MixerLayoutEntry::Separator {
|
||
id: "players".into(),
|
||
label: "Players".into(),
|
||
size: SeparatorSize::Standard,
|
||
decoration: SeparatorDecoration::Line,
|
||
},
|
||
MixerLayoutEntry::Fader {
|
||
fader: "browser-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
},
|
||
];
|
||
let app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::new(Mutex::new(Vec::new())),
|
||
})
|
||
.unwrap();
|
||
let area = Rect::new(0, 0, 50, 16);
|
||
let mut buffer = Buffer::empty(area);
|
||
app.render_streams(area, &mut buffer);
|
||
let rows = buffer
|
||
.content
|
||
.chunks(usize::from(area.width))
|
||
.map(|row| row.iter().map(|cell| cell.symbol()).collect::<String>())
|
||
.collect::<Vec<_>>();
|
||
|
||
let music_row = rows.iter().position(|row| row.contains("Music")).unwrap();
|
||
let separator_row = rows.iter().position(|row| row.contains("Players")).unwrap();
|
||
let browser_row = rows.iter().position(|row| row.contains("Browser")).unwrap();
|
||
assert_eq!(
|
||
music_row, browser_row,
|
||
"strip labels belong on one baseline"
|
||
);
|
||
assert_eq!(
|
||
separator_row, browser_row,
|
||
"inline separators must not start another horizontal row"
|
||
);
|
||
assert!(rows.iter().filter(|row| row.contains('█')).count() >= 3);
|
||
}
|
||
|
||
#[test]
|
||
fn group_fader_form_edits_application_faders_in_a_popup_and_shows_mode() {
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.items[0].id = MixerObjectId {
|
||
kind: MixerObjectKind::Group,
|
||
id: "media".into(),
|
||
};
|
||
snapshot.items[0].label = "Media".into();
|
||
snapshot.configuration.applications = vec![
|
||
ConfiguredApplication {
|
||
id: "music".into(),
|
||
label: "Music".into(),
|
||
selectors: Vec::new(),
|
||
},
|
||
ConfiguredApplication {
|
||
id: "browser".into(),
|
||
label: "Browser".into(),
|
||
selectors: Vec::new(),
|
||
},
|
||
];
|
||
snapshot.configuration.groups = vec![ConfiguredGroup {
|
||
id: "media".into(),
|
||
label: "Media".into(),
|
||
members: vec!["music".into()],
|
||
volume_mode: GroupVolumeMode::Relative,
|
||
}];
|
||
snapshot.configuration.faders = vec![
|
||
ConfiguredFader {
|
||
id: "media-fader".into(),
|
||
target: snapshot.items[0].id.clone(),
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
ConfiguredFader {
|
||
id: "music-fader".into(),
|
||
target: MixerObjectId {
|
||
kind: MixerObjectKind::Application,
|
||
id: "music".into(),
|
||
},
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
ConfiguredFader {
|
||
id: "browser-fader".into(),
|
||
target: MixerObjectId {
|
||
kind: MixerObjectKind::Application,
|
||
id: "browser".into(),
|
||
},
|
||
pickup: true,
|
||
pickup_tolerance: 0.02,
|
||
},
|
||
];
|
||
snapshot.configuration.mixer_layout = vec![MixerLayoutEntry::Fader {
|
||
fader: "media-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
}];
|
||
let edits = Arc::new(Mutex::new(Vec::new()));
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
|
||
app.handle_key_event(press(KeyCode::Char('e')));
|
||
let area = Rect::new(0, 0, 100, 22);
|
||
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("Members 1 of 2 selected"));
|
||
assert!(!rendered.contains("Group member Music"));
|
||
assert!(!rendered.contains("Group member Browser"));
|
||
assert!(rendered.contains("Group mode Relative"));
|
||
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let mut popup_buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut popup_buffer);
|
||
let popup = popup_buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(popup.contains("Group members"));
|
||
assert!(popup.contains("[x] Music · music-fader"));
|
||
assert!(popup.contains("[ ] Browser · browser-fader"));
|
||
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
assert!(edits.lock().unwrap().iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::Group { id, members, .. }
|
||
if id == "media" && members.is_empty()
|
||
)));
|
||
|
||
let mut toggled_buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut toggled_buffer);
|
||
let toggled = toggled_buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(toggled.contains("[ ] Music · music-fader"));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Char(' ')));
|
||
assert!(edits.lock().unwrap().iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::Group { id, members, .. }
|
||
if id == "media" && members == &["browser"]
|
||
)));
|
||
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
assert!(app.group_member_picker.is_none());
|
||
assert!(app.fader_editor.is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn configuration_tab_shows_settings_draft_state_and_diagnostics() {
|
||
let mut client = DemoClient::default();
|
||
let mut snapshot = client.view();
|
||
snapshot.configuration = ConfigurationSnapshot {
|
||
revision: 3,
|
||
dirty: true,
|
||
applied_revision: 2,
|
||
selection_saved: true,
|
||
learning: None,
|
||
error: None,
|
||
profile_id: "desktop".into(),
|
||
available_profiles: vec!["desktop".into(), "streaming".into()],
|
||
mixer_orientation: MixerOrientation::Vertical,
|
||
status_display: StatusDisplayMode::Detailed,
|
||
default_controller: Some("desk-left".into()),
|
||
theme: ThemeName::Dracula,
|
||
applications: vec![ConfiguredApplication {
|
||
id: "browser".into(),
|
||
label: "Browser".into(),
|
||
selectors: vec![ConfiguredSelector {
|
||
field: "application.process.binary".into(),
|
||
pattern: "firefox".into(),
|
||
regex: false,
|
||
}],
|
||
}],
|
||
groups: vec![ConfiguredGroup {
|
||
id: "media".into(),
|
||
label: "Media".into(),
|
||
members: vec!["browser".into()],
|
||
volume_mode: GroupVolumeMode::Absolute,
|
||
}],
|
||
faders: vec![ConfiguredFader {
|
||
id: "media-fader".into(),
|
||
target: MixerObjectId {
|
||
kind: MixerObjectKind::Group,
|
||
id: "media".into(),
|
||
},
|
||
pickup: true,
|
||
pickup_tolerance: 0.075,
|
||
}],
|
||
mixer_layout: vec![MixerLayoutEntry::Fader {
|
||
fader: "media-fader".into(),
|
||
hidden: false,
|
||
density: FaderDensity::Standard,
|
||
}],
|
||
bindings: vec![ConfiguredBinding {
|
||
surface: "desk-left".into(),
|
||
fader: "media-fader".into(),
|
||
action: "volume".into(),
|
||
message: "cc ch1 #49".into(),
|
||
kind: "cc".into(),
|
||
channel: 1,
|
||
number: 49,
|
||
}],
|
||
};
|
||
client.revision = snapshot.revision;
|
||
let mut app = LiveTui::new(client).unwrap();
|
||
app.snapshot = snapshot;
|
||
app.snapshot.devices.push(MidiDevice {
|
||
id: "desk-left".into(),
|
||
label: "Desk controller".into(),
|
||
status: "connected".into(),
|
||
backend_id: Some("20:0".into()),
|
||
error: None,
|
||
});
|
||
app.handle_key_event(press(KeyCode::Tab));
|
||
|
||
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("Profile: desktop"));
|
||
assert!(rendered.contains("unsaved draft"));
|
||
assert!(rendered.contains("Theme Default"));
|
||
assert!(rendered.contains("Pickup status Detailed"));
|
||
assert!(rendered.contains("Default controller Desk controller"));
|
||
assert!(rendered.contains("Show hidden faders none"));
|
||
assert!(!rendered.contains("Apply draft"));
|
||
assert!(rendered.contains("Save changes"));
|
||
assert!(rendered.contains("Desk controller — connected [Enter]"));
|
||
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..5 {
|
||
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::<String>();
|
||
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()));
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.configuration.default_controller = Some("desk-left".into());
|
||
snapshot.devices = vec![
|
||
MidiDevice {
|
||
id: "desk-left".into(),
|
||
label: "Left controller".into(),
|
||
status: "connected".into(),
|
||
backend_id: Some("20:0".into()),
|
||
error: None,
|
||
},
|
||
MidiDevice {
|
||
id: "desk-right".into(),
|
||
label: "Right controller".into(),
|
||
status: "missing".into(),
|
||
backend_id: None,
|
||
error: Some("connect the controller".into()),
|
||
},
|
||
];
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
app.handle_key_event(press(KeyCode::Tab));
|
||
app.settings_selected = app
|
||
.settings_rows()
|
||
.iter()
|
||
.position(|row| matches!(row, SettingsRow::MidiDevice { id } if id == "desk-left"))
|
||
.unwrap();
|
||
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("MIDI device details"));
|
||
assert!(rendered.contains("Left controller"));
|
||
assert!(rendered.contains("Device ID desk-left"));
|
||
assert!(rendered.contains("Backend port 20:0"));
|
||
assert!(rendered.contains("Default controller true"));
|
||
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
assert_eq!(app.snapshot.configuration.default_controller, None);
|
||
app.handle_key_event(press(KeyCode::Esc));
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Enter));
|
||
let mut second_buffer = Buffer::empty(area);
|
||
(&app).render(area, &mut second_buffer);
|
||
let second_rendered = second_buffer
|
||
.content
|
||
.iter()
|
||
.map(|cell| cell.symbol())
|
||
.collect::<String>();
|
||
assert!(second_rendered.contains("Right controller"));
|
||
assert!(second_rendered.contains("Status missing"));
|
||
assert!(second_rendered.contains("Error connect the controller"));
|
||
assert!(second_rendered.contains("Default controller false"));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
assert_eq!(
|
||
app.snapshot.configuration.default_controller.as_deref(),
|
||
Some("desk-right")
|
||
);
|
||
|
||
let edits = edits.lock().unwrap();
|
||
assert!(edits.iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::SetDefaultController { surface: None }
|
||
)));
|
||
assert!(edits.iter().any(|edit| matches!(
|
||
edit,
|
||
ConfigurationEdit::SetDefaultController { surface: Some(id) }
|
||
if id == "desk-right"
|
||
)));
|
||
}
|
||
|
||
#[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));
|
||
app.settings_selected = app
|
||
.settings_rows()
|
||
.iter()
|
||
.position(|row| matches!(row, SettingsRow::DiscoveredMidiPort { backend_id } if backend_id == "36:0"))
|
||
.unwrap();
|
||
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..6 {
|
||
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()));
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.devices.push(MidiDevice {
|
||
id: "desk".into(),
|
||
label: "Desk controller".into(),
|
||
status: "connected".into(),
|
||
backend_id: None,
|
||
error: None,
|
||
});
|
||
let mut app = LiveTui::new(LayoutClient {
|
||
snapshot,
|
||
edits: Arc::clone(&edits),
|
||
})
|
||
.unwrap();
|
||
app.handle_key_event(press(KeyCode::Char('2')));
|
||
let area = Rect::new(0, 0, 160, 20);
|
||
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(" ←→ layout"));
|
||
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
assert_eq!(app.theme(), ThemeName::Dracula);
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
assert_eq!(
|
||
app.snapshot.configuration.mixer_orientation,
|
||
MixerOrientation::Horizontal
|
||
);
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
assert_eq!(
|
||
app.snapshot.configuration.status_display,
|
||
StatusDisplayMode::Compact
|
||
);
|
||
app.handle_key_event(press(KeyCode::Down));
|
||
app.handle_key_event(press(KeyCode::Right));
|
||
assert_eq!(
|
||
app.snapshot.configuration.default_controller.as_deref(),
|
||
Some("desk")
|
||
);
|
||
|
||
app.handle_key_event(press(KeyCode::Char('g')));
|
||
app.handle_key_event(press(KeyCode::Char('a')));
|
||
assert!(app.editor.is_none());
|
||
assert_eq!(
|
||
edits.lock().unwrap().as_slice(),
|
||
&[
|
||
ConfigurationEdit::SetTheme {
|
||
theme: ThemeName::Dracula
|
||
},
|
||
ConfigurationEdit::SetMixerOrientation {
|
||
orientation: MixerOrientation::Horizontal
|
||
},
|
||
ConfigurationEdit::SetStatusDisplay {
|
||
mode: StatusDisplayMode::Compact
|
||
},
|
||
ConfigurationEdit::SetDefaultController {
|
||
surface: Some("desk".into())
|
||
}
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn configuration_tab_cancels_learning_and_saves_the_draft() {
|
||
struct LearnClient {
|
||
snapshot: MixerSnapshot,
|
||
calls: Arc<Mutex<Vec<String>>>,
|
||
}
|
||
impl MixerClient for LearnClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
fn set_volume(
|
||
&mut self,
|
||
_: MixerObjectId,
|
||
_: f64,
|
||
_: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
fn toggle_mute(&mut self, _: MixerObjectId, _: u64) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
fn start_midi_learn(
|
||
&mut self,
|
||
surface: String,
|
||
fader: String,
|
||
action: String,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.calls
|
||
.lock()
|
||
.unwrap()
|
||
.push(format!("start:{surface}:{fader}:{action}"));
|
||
self.snapshot.configuration.learning = Some("waiting".into());
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
fn cancel_midi_learn(&mut self) -> io::Result<MixerSnapshot> {
|
||
self.calls.lock().unwrap().push("cancel".into());
|
||
self.snapshot.configuration.learning = None;
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
fn save_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||
self.calls
|
||
.lock()
|
||
.unwrap()
|
||
.push(format!("save:{expected_revision}"));
|
||
self.snapshot.configuration.dirty = false;
|
||
self.snapshot.configuration.applied_revision = expected_revision;
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
}
|
||
|
||
let calls = Arc::new(Mutex::new(Vec::new()));
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.configuration.learning = Some("waiting".into());
|
||
let mut app = LiveTui::new(LearnClient {
|
||
snapshot,
|
||
calls: Arc::clone(&calls),
|
||
})
|
||
.unwrap();
|
||
app.handle_key_event(press(KeyCode::Char('c')));
|
||
assert!(app.snapshot.configuration.learning.is_none());
|
||
app.handle_key_event(press(KeyCode::Char('2')));
|
||
app.handle_key_event(press(KeyCode::Char('s')));
|
||
assert_eq!(calls.lock().unwrap().as_slice(), &["cancel", "save:0"]);
|
||
}
|
||
|
||
#[test]
|
||
fn device_status_summaries_include_recovery_actions_and_errors() {
|
||
let ambiguous = MidiDevice {
|
||
id: "left".into(),
|
||
label: "Left deck".into(),
|
||
status: "ambiguous".into(),
|
||
backend_id: None,
|
||
error: None,
|
||
};
|
||
assert_eq!(
|
||
device_summary(&[ambiguous]).as_deref(),
|
||
Some("Left deck: ambiguous — select port")
|
||
);
|
||
|
||
let failed = MidiDevice {
|
||
id: "right".into(),
|
||
label: "Right deck".into(),
|
||
status: "error".into(),
|
||
backend_id: Some("36:0".into()),
|
||
error: Some("permission denied".into()),
|
||
};
|
||
assert_eq!(
|
||
device_summary(&[failed]).as_deref(),
|
||
Some("Right deck: error — permission denied")
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn mixed_and_offline_objects_render_without_panicking_at_small_sizes() {
|
||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||
app.snapshot.items[0].gain_mixed = true;
|
||
app.snapshot.items.push(MixerItem {
|
||
id: MixerObjectId {
|
||
kind: MixerObjectKind::Group,
|
||
id: "offline".into(),
|
||
},
|
||
label: "Offline group".into(),
|
||
detail: "offline".into(),
|
||
gain: None,
|
||
gain_mixed: false,
|
||
muted: None,
|
||
mute_mixed: false,
|
||
pending: false,
|
||
pickup: None,
|
||
writable: false,
|
||
error: None,
|
||
});
|
||
let area = Rect::new(0, 0, 48, 11);
|
||
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("MIXED"));
|
||
}
|
||
|
||
struct SlowClient {
|
||
snapshot: MixerSnapshot,
|
||
writes: Arc<Mutex<Vec<f64>>>,
|
||
mutes: Arc<Mutex<Vec<bool>>>,
|
||
}
|
||
|
||
impl MixerClient for SlowClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.writes.lock().unwrap().push(gain);
|
||
thread::sleep(Duration::from_millis(100));
|
||
self.snapshot.revision += 1;
|
||
self.snapshot.items[0].gain = Some(gain);
|
||
self.snapshot.items[0].pending = false;
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
thread::sleep(Duration::from_millis(100));
|
||
self.snapshot.revision += 1;
|
||
let muted = !self.snapshot.items[0].muted.unwrap_or(false);
|
||
self.snapshot.items[0].muted = Some(muted);
|
||
self.mutes.lock().unwrap().push(muted);
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
}
|
||
|
||
fn wait_for_items(client: &mut impl MixerClient) -> MixerSnapshot {
|
||
let deadline = Instant::now() + Duration::from_secs(1);
|
||
loop {
|
||
if let Ok(snapshot) = client.snapshot()
|
||
&& !snapshot.items.is_empty()
|
||
{
|
||
return snapshot;
|
||
}
|
||
assert!(Instant::now() < deadline, "client did not publish items");
|
||
thread::sleep(Duration::from_millis(5));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn buffered_client_keeps_redraw_nonblocking_and_coalesces_volume() {
|
||
let writes = Arc::new(Mutex::new(Vec::new()));
|
||
let mut client = BufferedMixerClient::spawn(SlowClient {
|
||
snapshot: DemoClient::default().view(),
|
||
writes: Arc::clone(&writes),
|
||
mutes: Arc::new(Mutex::new(Vec::new())),
|
||
})
|
||
.unwrap();
|
||
let id = wait_for_items(&mut client).items[0].id.clone();
|
||
|
||
client
|
||
.set_volume(id.clone(), 0.1, 0)
|
||
.expect("queue first volume");
|
||
let started = Instant::now();
|
||
while writes.lock().unwrap().is_empty() && started.elapsed() < Duration::from_secs(1) {
|
||
thread::sleep(Duration::from_millis(5));
|
||
}
|
||
assert_eq!(writes.lock().unwrap().as_slice(), &[0.1]);
|
||
|
||
let redraw = Instant::now();
|
||
let _ = client.snapshot().unwrap();
|
||
assert!(redraw.elapsed() < Duration::from_millis(30));
|
||
client
|
||
.set_volume(id.clone(), 0.2, 0)
|
||
.expect("queue intermediate volume");
|
||
let optimistic = client
|
||
.set_volume(id, 0.3, 0)
|
||
.expect("replace intermediate volume");
|
||
assert_eq!(optimistic.items[0].gain, Some(0.3));
|
||
assert!(optimistic.items[0].pending);
|
||
|
||
let deadline = Instant::now() + Duration::from_secs(1);
|
||
while writes.lock().unwrap().last() != Some(&0.3) && Instant::now() < deadline {
|
||
thread::sleep(Duration::from_millis(5));
|
||
}
|
||
assert_eq!(writes.lock().unwrap().as_slice(), &[0.1, 0.3]);
|
||
}
|
||
|
||
#[test]
|
||
fn buffered_client_preserves_rapid_mute_edges() {
|
||
let mutes = Arc::new(Mutex::new(Vec::new()));
|
||
let mut client = BufferedMixerClient::spawn(SlowClient {
|
||
snapshot: DemoClient::default().view(),
|
||
writes: Arc::new(Mutex::new(Vec::new())),
|
||
mutes: Arc::clone(&mutes),
|
||
})
|
||
.unwrap();
|
||
let id = wait_for_items(&mut client).items[0].id.clone();
|
||
|
||
let first = client
|
||
.toggle_mute(id.clone(), 0)
|
||
.expect("queue first mute edge");
|
||
let second = client.toggle_mute(id, 0).expect("queue second mute edge");
|
||
assert_eq!(first.items[0].muted, Some(true));
|
||
assert_eq!(second.items[0].muted, Some(false));
|
||
|
||
let deadline = Instant::now() + Duration::from_secs(1);
|
||
while mutes.lock().unwrap().len() < 2 && Instant::now() < deadline {
|
||
thread::sleep(Duration::from_millis(5));
|
||
}
|
||
assert_eq!(mutes.lock().unwrap().as_slice(), &[true, false]);
|
||
}
|
||
|
||
#[test]
|
||
fn buffered_client_applies_rapid_layout_moves_in_order() {
|
||
struct SlowLayoutClient {
|
||
snapshot: MixerSnapshot,
|
||
positions: Arc<Mutex<Vec<usize>>>,
|
||
}
|
||
|
||
impl MixerClient for SlowLayoutClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn edit_configuration(
|
||
&mut self,
|
||
edit: ConfigurationEdit,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
thread::sleep(Duration::from_millis(100));
|
||
let ConfigurationEdit::MoveLayoutEntry { id, position } = edit else {
|
||
unreachable!()
|
||
};
|
||
let index = self
|
||
.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.position(|entry| match entry {
|
||
MixerLayoutEntry::Fader { fader, .. } => fader == &id,
|
||
MixerLayoutEntry::Separator { id: separator, .. } => separator == &id,
|
||
})
|
||
.unwrap();
|
||
let entry = self.snapshot.configuration.mixer_layout.remove(index);
|
||
let position = position.min(self.snapshot.configuration.mixer_layout.len());
|
||
self.snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.insert(position, entry);
|
||
self.snapshot.configuration.revision += 1;
|
||
self.positions.lock().unwrap().push(position);
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
}
|
||
|
||
let layout = |id: &str| MixerLayoutEntry::Separator {
|
||
id: id.to_owned(),
|
||
label: id.to_owned(),
|
||
size: SeparatorSize::Standard,
|
||
decoration: SeparatorDecoration::Line,
|
||
};
|
||
let mut snapshot = DemoClient::default().view();
|
||
snapshot.configuration.mixer_layout = vec![layout("a"), layout("b"), layout("c")];
|
||
let positions = Arc::new(Mutex::new(Vec::new()));
|
||
let mut client = BufferedMixerClient::spawn(SlowLayoutClient {
|
||
snapshot,
|
||
positions: Arc::clone(&positions),
|
||
})
|
||
.unwrap();
|
||
let deadline = Instant::now() + Duration::from_secs(1);
|
||
while client
|
||
.snapshot()
|
||
.unwrap()
|
||
.configuration
|
||
.mixer_layout
|
||
.is_empty()
|
||
{
|
||
assert!(Instant::now() < deadline, "client did not publish layout");
|
||
thread::sleep(Duration::from_millis(5));
|
||
}
|
||
|
||
let first = client
|
||
.edit_configuration(
|
||
ConfigurationEdit::MoveLayoutEntry {
|
||
id: "a".to_owned(),
|
||
position: 1,
|
||
},
|
||
0,
|
||
)
|
||
.unwrap();
|
||
assert_eq!(layout_ids(&first), ["b", "a", "c"]);
|
||
let second = client
|
||
.edit_configuration(
|
||
ConfigurationEdit::MoveLayoutEntry {
|
||
id: "a".to_owned(),
|
||
position: 2,
|
||
},
|
||
0,
|
||
)
|
||
.unwrap();
|
||
assert_eq!(layout_ids(&second), ["b", "c", "a"]);
|
||
|
||
let deadline = Instant::now() + Duration::from_secs(1);
|
||
while positions.lock().unwrap().len() < 2 {
|
||
assert!(Instant::now() < deadline, "layout edits did not drain");
|
||
thread::sleep(Duration::from_millis(5));
|
||
}
|
||
assert_eq!(positions.lock().unwrap().as_slice(), &[1, 2]);
|
||
}
|
||
|
||
fn layout_ids(snapshot: &MixerSnapshot) -> Vec<&str> {
|
||
snapshot
|
||
.configuration
|
||
.mixer_layout
|
||
.iter()
|
||
.map(|entry| match entry {
|
||
MixerLayoutEntry::Fader { fader, .. } => fader.as_str(),
|
||
MixerLayoutEntry::Separator { id, .. } => id.as_str(),
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
#[test]
|
||
fn buffered_client_starts_disconnected_and_recovers_in_the_background() {
|
||
struct RecoveringClient {
|
||
attempts: Arc<Mutex<usize>>,
|
||
}
|
||
|
||
impl MixerClient for RecoveringClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
let mut attempts = self.attempts.lock().unwrap();
|
||
*attempts += 1;
|
||
if *attempts == 1 {
|
||
thread::sleep(Duration::from_millis(100));
|
||
return Err(io::Error::new(
|
||
io::ErrorKind::NotFound,
|
||
"server socket is not available",
|
||
));
|
||
}
|
||
Ok(DemoClient::default().view())
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
}
|
||
|
||
let attempts = Arc::new(Mutex::new(0));
|
||
let started = Instant::now();
|
||
let mut client = BufferedMixerClient::spawn(RecoveringClient {
|
||
attempts: Arc::clone(&attempts),
|
||
})
|
||
.unwrap();
|
||
assert!(started.elapsed() < Duration::from_millis(30));
|
||
let initial = client.snapshot().unwrap();
|
||
assert_eq!(initial.status, "waiting for server");
|
||
assert!(initial.items.is_empty());
|
||
|
||
let deadline = Instant::now() + Duration::from_secs(2);
|
||
loop {
|
||
let snapshot = client.snapshot().unwrap();
|
||
if snapshot.error.is_some() {
|
||
assert!(snapshot.items.is_empty());
|
||
break;
|
||
}
|
||
assert!(Instant::now() < deadline, "client did not publish failure");
|
||
thread::sleep(Duration::from_millis(10));
|
||
}
|
||
loop {
|
||
let snapshot = client.snapshot().unwrap();
|
||
if snapshot.error.is_none() && !snapshot.items.is_empty() {
|
||
break;
|
||
}
|
||
assert!(Instant::now() < deadline, "client did not reconnect");
|
||
thread::sleep(Duration::from_millis(10));
|
||
}
|
||
assert!(*attempts.lock().unwrap() >= 2);
|
||
}
|
||
|
||
#[test]
|
||
fn buffered_client_drop_does_not_wait_for_a_hung_server_request() {
|
||
struct HungClient {
|
||
entered: Arc<AtomicBool>,
|
||
}
|
||
|
||
impl MixerClient for HungClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
self.entered.store(true, Ordering::Release);
|
||
thread::sleep(Duration::from_millis(300));
|
||
Err(io::Error::new(io::ErrorKind::TimedOut, "server hung"))
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_: MixerObjectId,
|
||
_: f64,
|
||
_: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn toggle_mute(&mut self, _: MixerObjectId, _: u64) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
}
|
||
|
||
let entered = Arc::new(AtomicBool::new(false));
|
||
let client = BufferedMixerClient::spawn(HungClient {
|
||
entered: Arc::clone(&entered),
|
||
})
|
||
.unwrap();
|
||
let deadline = Instant::now() + Duration::from_secs(1);
|
||
while !entered.load(Ordering::Acquire) {
|
||
assert!(
|
||
Instant::now() < deadline,
|
||
"worker did not start its request"
|
||
);
|
||
thread::yield_now();
|
||
}
|
||
|
||
let started = Instant::now();
|
||
drop(client);
|
||
assert!(started.elapsed() < Duration::from_millis(75));
|
||
}
|
||
|
||
#[test]
|
||
fn buffered_action_resnapshots_and_retries_a_stale_revision() {
|
||
struct RevisionClient {
|
||
snapshot: MixerSnapshot,
|
||
attempts: Vec<u64>,
|
||
}
|
||
|
||
impl MixerClient for RevisionClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
gain: f64,
|
||
expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.attempts.push(expected_revision);
|
||
if expected_revision != self.snapshot.revision {
|
||
return Err(io::Error::new(io::ErrorKind::InvalidData, "stale revision"));
|
||
}
|
||
self.snapshot.revision += 1;
|
||
self.snapshot.items[0].gain = Some(gain);
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
}
|
||
|
||
let stale = DemoClient::default().view();
|
||
let mut current = stale.clone();
|
||
current.revision = 5;
|
||
let id = current.items[0].id.clone();
|
||
let mut client = RevisionClient {
|
||
snapshot: current,
|
||
attempts: Vec::new(),
|
||
};
|
||
let mut confirmed = stale;
|
||
let result = execute_action(
|
||
&mut client,
|
||
&mut confirmed,
|
||
&BufferedAction::SetVolume { id, gain: 0.8 },
|
||
)
|
||
.unwrap();
|
||
|
||
assert_eq!(client.attempts, [0, 5]);
|
||
assert_eq!(result.revision, 6);
|
||
assert_eq!(result.items[0].gain, Some(0.8));
|
||
}
|
||
|
||
#[test]
|
||
fn buffered_configuration_edit_survives_consecutive_revision_races() {
|
||
struct RacingConfigurationClient {
|
||
snapshot: MixerSnapshot,
|
||
attempts: Vec<u64>,
|
||
}
|
||
|
||
impl MixerClient for RacingConfigurationClient {
|
||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
|
||
fn set_volume(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_gain: f64,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn toggle_mute(
|
||
&mut self,
|
||
_id: MixerObjectId,
|
||
_expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
unreachable!()
|
||
}
|
||
|
||
fn edit_configuration(
|
||
&mut self,
|
||
edit: ConfigurationEdit,
|
||
expected_revision: u64,
|
||
) -> io::Result<MixerSnapshot> {
|
||
self.attempts.push(expected_revision);
|
||
if self.attempts.len() <= 2 {
|
||
self.snapshot.configuration.revision += 1;
|
||
return Err(io::Error::other(format!(
|
||
"stale configuration revision {expected_revision}; current revision is {}",
|
||
self.snapshot.configuration.revision
|
||
)));
|
||
}
|
||
apply_optimistic_configuration_edit(&mut self.snapshot, &edit);
|
||
self.snapshot.configuration.revision += 1;
|
||
Ok(self.snapshot.clone())
|
||
}
|
||
}
|
||
|
||
let layout = |id: &str| MixerLayoutEntry::Separator {
|
||
id: id.to_owned(),
|
||
label: id.to_owned(),
|
||
size: SeparatorSize::Standard,
|
||
decoration: SeparatorDecoration::Line,
|
||
};
|
||
let mut confirmed = DemoClient::default().view();
|
||
confirmed.configuration.revision = 2;
|
||
confirmed.configuration.mixer_layout = vec![layout("a"), layout("b")];
|
||
let mut client = RacingConfigurationClient {
|
||
snapshot: confirmed.clone(),
|
||
attempts: Vec::new(),
|
||
};
|
||
|
||
let result = execute_action(
|
||
&mut client,
|
||
&mut confirmed,
|
||
&BufferedAction::EditConfiguration {
|
||
edit: ConfigurationEdit::MoveLayoutEntry {
|
||
id: "a".to_owned(),
|
||
position: 1,
|
||
},
|
||
},
|
||
)
|
||
.unwrap();
|
||
|
||
assert_eq!(client.attempts, [2, 3, 4]);
|
||
assert_eq!(layout_ids(&result), ["b", "a"]);
|
||
assert_eq!(result.configuration.revision, 5);
|
||
}
|
||
}
|