feat(M8.1): render an event-driven mixer
Replace the single demo gauge with a client-backed stream list, selection, volume and mute actions, pending/read-only/error indicators, periodic refresh, viewport handling, and terminal restoration on return. Tests: cargo test -p tui --all-targets --all-features Tests: cargo clippy -p tui --all-targets --all-features --locked -- -D warnings
This commit is contained in:
parent
3c164221b0
commit
ed46d3ae37
388
tui/src/lib.rs
388
tui/src/lib.rs
|
|
@ -1,84 +1,193 @@
|
|||
//! Terminal user interface for fader_master.
|
||||
|
||||
use std::io;
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use ratatui::{
|
||||
DefaultTerminal, Frame,
|
||||
buffer::Buffer,
|
||||
crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
|
||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||
style::{Color, Modifier, Style, Stylize},
|
||||
style::{Color, Style, Stylize},
|
||||
symbols::border,
|
||||
text::Line,
|
||||
widgets::{Block, Gauge, Paragraph, Widget},
|
||||
};
|
||||
|
||||
const VOLUME_STEP: u8 = 5;
|
||||
const VOLUME_STEP: f64 = 0.05;
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Runs the interactive terminal UI and restores the terminal before returning.
|
||||
pub fn run() -> io::Result<()> {
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct StreamId {
|
||||
pub epoch: u64,
|
||||
pub backend_id: u64,
|
||||
pub incarnation: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MixerItem {
|
||||
pub id: StreamId,
|
||||
pub label: String,
|
||||
pub process: Option<String>,
|
||||
pub gain: f64,
|
||||
pub muted: bool,
|
||||
pub pending: bool,
|
||||
pub writable: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MixerSnapshot {
|
||||
pub revision: u64,
|
||||
pub backend: String,
|
||||
pub status: String,
|
||||
pub items: Vec<MixerItem>,
|
||||
}
|
||||
|
||||
/// 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: StreamId,
|
||||
gain: f64,
|
||||
expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot>;
|
||||
fn toggle_mute(&mut self, id: StreamId, expected_revision: u64) -> io::Result<MixerSnapshot>;
|
||||
}
|
||||
|
||||
/// Runs the live terminal client and restores terminal state on every return.
|
||||
pub fn run_live(client: impl MixerClient) -> io::Result<()> {
|
||||
let mut terminal = ratatui::init();
|
||||
let result = Tui::default().run(&mut terminal);
|
||||
ratatui::restore();
|
||||
result
|
||||
let _guard = RestoreTerminal;
|
||||
LiveTui::new(client)?.run(&mut terminal)
|
||||
}
|
||||
|
||||
/// State for the initial interactive mixer shell.
|
||||
#[derive(Debug)]
|
||||
pub struct Tui {
|
||||
volume: u8,
|
||||
exit: bool,
|
||||
/// Retains the original preview example without opening audio or IPC.
|
||||
pub fn run() -> io::Result<()> {
|
||||
run_live(DemoClient::default())
|
||||
}
|
||||
|
||||
impl Default for Tui {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
volume: 65,
|
||||
exit: false,
|
||||
}
|
||||
struct RestoreTerminal;
|
||||
|
||||
impl Drop for RestoreTerminal {
|
||||
fn drop(&mut self) {
|
||||
ratatui::restore();
|
||||
}
|
||||
}
|
||||
|
||||
impl Tui {
|
||||
/// Runs the application's main loop until the user quits.
|
||||
pub struct LiveTui<C> {
|
||||
client: C,
|
||||
snapshot: MixerSnapshot,
|
||||
selected: usize,
|
||||
exit: bool,
|
||||
client_error: Option<String>,
|
||||
}
|
||||
|
||||
impl<C: MixerClient> LiveTui<C> {
|
||||
pub fn new(mut client: C) -> io::Result<Self> {
|
||||
let snapshot = client.snapshot()?;
|
||||
Ok(Self {
|
||||
client,
|
||||
snapshot,
|
||||
selected: 0,
|
||||
exit: false,
|
||||
client_error: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn run(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
|
||||
while !self.exit {
|
||||
self.refresh();
|
||||
terminal.draw(|frame| self.draw(frame))?;
|
||||
self.handle_events()?;
|
||||
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.snapshot.items.get(self.selected).map(|item| item.id);
|
||||
self.snapshot = snapshot;
|
||||
self.selected = selected_id
|
||||
.and_then(|id| self.snapshot.items.iter().position(|item| item.id == id))
|
||||
.unwrap_or_else(|| {
|
||||
self.selected
|
||||
.min(self.snapshot.items.len().saturating_sub(1))
|
||||
});
|
||||
self.client_error = None;
|
||||
}
|
||||
|
||||
fn draw(&self, frame: &mut Frame) {
|
||||
frame.render_widget(self, frame.area());
|
||||
}
|
||||
|
||||
fn handle_events(&mut self) -> io::Result<()> {
|
||||
if let Event::Key(key_event) = event::read()?
|
||||
&& key_event.kind == KeyEventKind::Press
|
||||
{
|
||||
self.handle_key_event(key_event);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_key_event(&mut self, key_event: KeyEvent) {
|
||||
match key_event.code {
|
||||
KeyCode::Left | KeyCode::Down => {
|
||||
self.volume = self.volume.saturating_sub(VOLUME_STEP);
|
||||
KeyCode::Char('j') | KeyCode::Down => {
|
||||
self.selected =
|
||||
(self.selected + 1).min(self.snapshot.items.len().saturating_sub(1));
|
||||
}
|
||||
KeyCode::Right | KeyCode::Up => {
|
||||
self.volume = self.volume.saturating_add(VOLUME_STEP).min(100);
|
||||
KeyCode::Char('k') | KeyCode::Up => {
|
||||
self.selected = self.selected.saturating_sub(1);
|
||||
}
|
||||
KeyCode::Home => self.volume = 0,
|
||||
KeyCode::End => self.volume = 100,
|
||||
KeyCode::Left | KeyCode::Char('-') => self.change_volume(-VOLUME_STEP),
|
||||
KeyCode::Right | 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::Esc | KeyCode::Char('q') => self.exit = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn change_volume(&mut self, delta: f64) {
|
||||
if let Some(item) = self.snapshot.items.get(self.selected) {
|
||||
self.set_selected_volume((item.gain + delta).clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn set_selected_volume(&mut self, gain: f64) {
|
||||
let Some(item) = self.snapshot.items.get(self.selected) else {
|
||||
return;
|
||||
};
|
||||
if !item.writable {
|
||||
self.client_error = Some("selected stream is read-only".to_owned());
|
||||
return;
|
||||
}
|
||||
match self
|
||||
.client
|
||||
.set_volume(item.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(item) = self.snapshot.items.get(self.selected) else {
|
||||
return;
|
||||
};
|
||||
match self.client.toggle_mute(item.id, self.snapshot.revision) {
|
||||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||||
Err(error) => self.client_error = Some(error.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for &Tui {
|
||||
impl<C> Widget for &LiveTui<C> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
let [header, body, footer] = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
|
|
@ -92,48 +201,38 @@ impl Widget for &Tui {
|
|||
Paragraph::new(Line::from(vec![
|
||||
" FADER ".fg(Color::Black).bg(Color::Cyan).bold(),
|
||||
" MASTER ".bold(),
|
||||
format!(
|
||||
" {} · {} · rev {} ",
|
||||
self.snapshot.backend, self.snapshot.status, self.snapshot.revision
|
||||
)
|
||||
.dark_gray(),
|
||||
]))
|
||||
.alignment(Alignment::Center)
|
||||
.block(Block::bordered().border_set(border::ROUNDED))
|
||||
.render(header, buf);
|
||||
|
||||
let mixer = Block::bordered()
|
||||
.title(" Mixer ".bold())
|
||||
.title_bottom(" demo state · live server connection follows in M7 ".dark_gray())
|
||||
.title(" Live application streams ".bold())
|
||||
.title_bottom(
|
||||
self.client_error
|
||||
.as_deref()
|
||||
.unwrap_or("confirmed server state")
|
||||
.dark_gray(),
|
||||
)
|
||||
.border_set(border::THICK);
|
||||
let inner = mixer.inner(body);
|
||||
mixer.render(body, buf);
|
||||
|
||||
let [label, meter, state] = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(2),
|
||||
Constraint::Length(3),
|
||||
Constraint::Min(1),
|
||||
])
|
||||
.margin(1)
|
||||
.areas(inner);
|
||||
|
||||
Paragraph::new("Desktop audio")
|
||||
.style(Style::default().add_modifier(Modifier::BOLD))
|
||||
.render(label, buf);
|
||||
Gauge::default()
|
||||
.block(Block::bordered())
|
||||
.gauge_style(Style::default().fg(Color::Cyan).bg(Color::DarkGray))
|
||||
.percent(u16::from(self.volume))
|
||||
.label(format!("{}%", self.volume))
|
||||
.render(meter, buf);
|
||||
Paragraph::new("● Adapter: demo ● MIDI: waiting ○ Mute: off")
|
||||
.style(Style::default().fg(Color::Gray))
|
||||
.render(state, buf);
|
||||
self.render_streams(inner, buf);
|
||||
|
||||
Paragraph::new(Line::from(vec![
|
||||
" ←/↓ ".into(),
|
||||
"volume down".cyan(),
|
||||
" →/↑ ".into(),
|
||||
"volume up".cyan(),
|
||||
" ↑/↓ or j/k ".into(),
|
||||
"select".cyan(),
|
||||
" ←/→ ".into(),
|
||||
"volume".cyan(),
|
||||
" M ".into(),
|
||||
"mute".cyan(),
|
||||
" Home/End ".into(),
|
||||
"min/max".cyan(),
|
||||
"0/100%".cyan(),
|
||||
" Q/Esc ".into(),
|
||||
"quit".cyan(),
|
||||
]))
|
||||
|
|
@ -143,6 +242,134 @@ impl Widget for &Tui {
|
|||
}
|
||||
}
|
||||
|
||||
impl<C> LiveTui<C> {
|
||||
fn render_streams(&self, area: Rect, buf: &mut Buffer) {
|
||||
if self.snapshot.items.is_empty() {
|
||||
Paragraph::new("No playback streams are currently visible.")
|
||||
.alignment(Alignment::Center)
|
||||
.render(area, buf);
|
||||
return;
|
||||
}
|
||||
let visible = usize::from(area.height / 4).max(1);
|
||||
let start = self.selected.saturating_sub(visible.saturating_sub(1));
|
||||
for (row, (index, item)) in self
|
||||
.snapshot
|
||||
.items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(start)
|
||||
.take(visible)
|
||||
.enumerate()
|
||||
{
|
||||
let y = area
|
||||
.y
|
||||
.saturating_add(u16::try_from(row * 4).unwrap_or(u16::MAX));
|
||||
let row_area = Rect::new(
|
||||
area.x,
|
||||
y,
|
||||
area.width,
|
||||
4.min(area.bottom().saturating_sub(y)),
|
||||
);
|
||||
if row_area.height < 2 {
|
||||
break;
|
||||
}
|
||||
let selected = index == self.selected;
|
||||
let title = format!(
|
||||
"{} {}{}{}",
|
||||
if selected { "▶" } else { " " },
|
||||
item.label,
|
||||
item.process
|
||||
.as_deref()
|
||||
.map(|process| format!(" [{process}]"))
|
||||
.unwrap_or_default(),
|
||||
if item.pending { " … pending" } else { "" }
|
||||
);
|
||||
let block = Block::bordered().title(title).border_style(if selected {
|
||||
Style::default().fg(Color::Cyan)
|
||||
} else {
|
||||
Style::default().fg(Color::DarkGray)
|
||||
});
|
||||
let meter = block.inner(row_area);
|
||||
block.render(row_area, buf);
|
||||
let percent = (item.gain.clamp(0.0, 1.0) * 100.0).round() as u16;
|
||||
let state = if item.muted {
|
||||
"MUTED"
|
||||
} else if !item.writable {
|
||||
"READ ONLY"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let label = item.error.as_deref().map_or_else(
|
||||
|| format!("{percent}% {state}"),
|
||||
|error| format!("ERROR: {error}"),
|
||||
);
|
||||
Gauge::default()
|
||||
.gauge_style(Style::default().fg(if item.muted {
|
||||
Color::Yellow
|
||||
} else {
|
||||
Color::Cyan
|
||||
}))
|
||||
.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(),
|
||||
items: vec![MixerItem {
|
||||
id: StreamId {
|
||||
epoch: 1,
|
||||
backend_id: 1,
|
||||
incarnation: 1,
|
||||
},
|
||||
label: "Desktop audio".into(),
|
||||
process: None,
|
||||
gain: if self.revision == 0 { 0.65 } else { self.gain },
|
||||
muted: self.muted,
|
||||
pending: false,
|
||||
writable: true,
|
||||
error: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MixerClient for DemoClient {
|
||||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||||
Ok(self.view())
|
||||
}
|
||||
|
||||
fn set_volume(
|
||||
&mut self,
|
||||
_id: StreamId,
|
||||
gain: f64,
|
||||
_expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.revision += 1;
|
||||
self.gain = gain;
|
||||
Ok(self.view())
|
||||
}
|
||||
|
||||
fn toggle_mute(&mut self, _id: StreamId, _expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||||
self.revision += 1;
|
||||
self.muted = !self.muted;
|
||||
Ok(self.view())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -152,30 +379,29 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn volume_keys_move_and_clamp_the_demo_fader() {
|
||||
let mut app = Tui::default();
|
||||
|
||||
fn volume_and_mute_keys_update_through_the_client() {
|
||||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||||
app.handle_key_event(press(KeyCode::End));
|
||||
app.handle_key_event(press(KeyCode::Right));
|
||||
assert_eq!(app.volume, 100);
|
||||
|
||||
app.handle_key_event(press(KeyCode::Home));
|
||||
app.handle_key_event(press(KeyCode::Left));
|
||||
assert_eq!(app.volume, 0);
|
||||
assert_eq!(app.snapshot.items[0].gain, 1.0);
|
||||
app.handle_key_event(press(KeyCode::Char('m')));
|
||||
assert!(app.snapshot.items[0].muted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quit_keys_request_exit() {
|
||||
let mut app = Tui::default();
|
||||
fn selection_clamps_and_quit_requests_exit() {
|
||||
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::Char('q')));
|
||||
assert!(app.exit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixer_shell_renders_at_a_typical_terminal_size() {
|
||||
fn live_mixer_renders_status_and_stream_at_typical_size() {
|
||||
let app = LiveTui::new(DemoClient::default()).unwrap();
|
||||
let area = Rect::new(0, 0, 100, 20);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
(&Tui::default()).render(area, &mut buffer);
|
||||
(&app).render(area, &mut buffer);
|
||||
let rendered = buffer
|
||||
.content
|
||||
.iter()
|
||||
|
|
|
|||
Loading…
Reference in New Issue