feat: add combined and dedicated launchers
Make fader_master default to an all-in-one TUI that reuses a responding server or starts and owns an embedded one. Add fader_master_server and fader_master_client binaries, preserve serve/tui compatibility, and give embedded servers cancellable joined shutdown.\n\nTests: cargo fmt --all -- --check\nTests: cargo check --workspace --all-targets --all-features\nTests: cargo test --workspace --all-targets --all-features\nTests: cargo test --workspace --doc --all-features\nTests: cargo clippy --workspace --all-targets --all-features -- -D warnings\nTests: cargo build --workspace --release --all-features\nTests: cargo check --workspace\nTests: cargo check --workspace --no-default-features\nTests: cargo check -p midi --no-default-features --features midir\nTests: cargo check -p volume_lib --no-default-features --features pulse\nTests: cargo run --locked -p fader_master -- --version\nTests: cargo run --locked -p fader_master --bin fader_master_server -- --version\nTests: cargo run --locked -p fader_master --bin fader_master_client -- --version
This commit is contained in:
parent
563a8e34ba
commit
28c2d6ce90
23
README.md
23
README.md
|
|
@ -23,19 +23,36 @@ backlog:
|
|||
|
||||
## Run the live TUI
|
||||
|
||||
Start the server in one terminal:
|
||||
For normal interactive use, launch the combined executable. It connects to an
|
||||
existing per-user server when one is available; otherwise it starts an embedded
|
||||
server for the lifetime of the TUI:
|
||||
|
||||
```sh
|
||||
cargo run --locked -p fader_master -- serve \
|
||||
cargo run --locked -p fader_master -- \
|
||||
--config examples/profiles/arch-pipewire.toml --audio pulse
|
||||
```
|
||||
|
||||
Installed builds provide three executable names: `fader_master` for this
|
||||
combined mode, `fader_master_server` for a persistent standalone server, and
|
||||
`fader_master_client` for the reconnecting TUI client. Server-only options are
|
||||
used by combined mode only when it actually needs to start a server.
|
||||
|
||||
For separate processes, start the server in one terminal:
|
||||
|
||||
```sh
|
||||
cargo run --locked -p fader_master --bin fader_master_server -- \
|
||||
--config examples/profiles/arch-pipewire.toml --audio pulse
|
||||
```
|
||||
|
||||
Then start the client in another:
|
||||
|
||||
```sh
|
||||
cargo run --locked -p fader_master -- tui
|
||||
cargo run --locked -p fader_master --bin fader_master_client
|
||||
```
|
||||
|
||||
The compatible `fader_master serve` and `fader_master tui` subcommands remain
|
||||
available for scripts and existing workflows.
|
||||
|
||||
Use Up/Down or J/K to select a configured fader or separator, Left/Right to
|
||||
change its volume, M to toggle mute, T to cycle the profile's theme draft, and Q
|
||||
to open the quit confirmation. Escape cancels the active editor or dialog and
|
||||
|
|
|
|||
|
|
@ -362,7 +362,21 @@ new-stream policy is `restore`.
|
|||
|
||||
## CLI, IPC, and TUI
|
||||
|
||||
Plan `fader_master serve`, `tui`, `validate --config PATH`, `devices`, `status`, and `profile switch ID`. Run one server per user/runtime namespace with an owned Unix socket and lock; TUI disconnect must not stop MIDI control. No network listener. Bound IPC message size and queue sizes, enforce socket permissions/peer identity, negotiate protocol version, use request IDs and revisioned snapshots, and resnapshot after missed deltas. Length-prefixed UTF-8 TOML messages reuse Serde schemas initially; cap frames before allocation.
|
||||
Provide `fader_master_server` as the persistent server,
|
||||
`fader_master_client` as the reconnecting TUI, and `fader_master` as an all-in-one
|
||||
launcher. Combined mode probes the authenticated/versioned local server first
|
||||
and starts an in-process server only when none responds. A startup race is
|
||||
resolved by the socket's one-instance ownership rather than creating a second
|
||||
authority. An embedded server receives an orderly cancellation and is joined
|
||||
when its TUI exits; a reused external server is left running. The compatible
|
||||
`fader_master serve`, `tui`, `validate --config PATH`, `devices`, `status`, and
|
||||
`profile switch ID` commands remain available. Run one server per user/runtime
|
||||
namespace with an owned Unix socket and lock; TUI disconnect must not stop an
|
||||
external server's MIDI control. No network listener. Bound IPC message size and
|
||||
queue sizes, enforce socket permissions/peer identity, negotiate protocol
|
||||
version, use request IDs and revisioned snapshots, and resnapshot after missed
|
||||
deltas. Length-prefixed UTF-8 TOML messages reuse Serde schemas initially; cap
|
||||
frames before allocation.
|
||||
|
||||
The TUI owns blocking IPC on a background thread. Its render/input thread reads
|
||||
a shared local snapshot only, applies optimistic volume/mute changes, and queues
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ rust-version.workspace = true
|
|||
license-file.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
default-run = "fader_master"
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
|
|
|
|||
|
|
@ -0,0 +1,351 @@
|
|||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use fader_config::{ActiveConfig, Profile, ProfileDocument, XdgEnvironment, XdgPaths};
|
||||
use fader_core::Gain;
|
||||
use midi::{LinuxIdentityCatalog, MidiInputCatalog};
|
||||
use volume_lib::{AudioBackend, CompiledAdapterProbe, TargetRequirements, select_adapter};
|
||||
|
||||
use crate::{
|
||||
audio_selection_policy,
|
||||
cli::{Cli, ClientCli, Command, LaunchOptions, ProfileCommand, ServerCli, ThemeArgument},
|
||||
ipc::{ClientRequest, PROTOCOL_VERSION, RequestCommand, ResponseResult},
|
||||
local::{LocalError, LocalServer, client_request, default_socket_path},
|
||||
tui_client::IpcMixerClient,
|
||||
};
|
||||
|
||||
/// Runs the multipurpose executable. With no subcommand it starts the combined
|
||||
/// server/client mode; existing subcommands remain compatible.
|
||||
pub fn run(cli: Cli) -> Result<()> {
|
||||
match cli.command {
|
||||
None => run_combined(cli.launch),
|
||||
Some(Command::Tui { socket, theme }) => run_client(ClientCli { socket, theme }),
|
||||
Some(Command::Validate { config }) => {
|
||||
let profile = load_profile(&config)?;
|
||||
println!("profile {:?} is valid", profile.id().as_str());
|
||||
Ok(())
|
||||
}
|
||||
Some(Command::Serve {
|
||||
config,
|
||||
audio,
|
||||
socket,
|
||||
}) => run_server(ServerCli {
|
||||
config,
|
||||
audio,
|
||||
socket,
|
||||
}),
|
||||
Some(Command::Status { socket }) => status(socket.as_deref()),
|
||||
Some(Command::Devices) => devices(),
|
||||
Some(Command::Profile {
|
||||
command:
|
||||
ProfileCommand::Switch {
|
||||
id,
|
||||
restore,
|
||||
socket,
|
||||
},
|
||||
}) => switch_profile(&id, restore, socket.as_deref()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the dedicated persistent server.
|
||||
pub fn run_server(arguments: ServerCli) -> Result<()> {
|
||||
let mut server = build_server(
|
||||
arguments.config.as_deref(),
|
||||
arguments.audio.map(|value| value.choice()),
|
||||
arguments.socket.as_deref(),
|
||||
)?;
|
||||
server.run()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs the dedicated terminal client. It retains the existing reconnecting
|
||||
/// behavior when no server is currently available.
|
||||
pub fn run_client(arguments: ClientCli) -> Result<()> {
|
||||
let socket = arguments.socket.map_or_else(default_socket_path, Ok)?;
|
||||
run_tui(socket, arguments.theme)
|
||||
}
|
||||
|
||||
fn run_combined(arguments: LaunchOptions) -> Result<()> {
|
||||
let socket = arguments
|
||||
.socket
|
||||
.clone()
|
||||
.map_or_else(default_socket_path, Ok)?;
|
||||
let running = server_responds(&socket);
|
||||
let server = start_if_missing(running, || {
|
||||
build_server(
|
||||
arguments.config.as_deref(),
|
||||
arguments.audio.map(|value| value.choice()),
|
||||
Some(&socket),
|
||||
)
|
||||
});
|
||||
let embedded = match server {
|
||||
Ok(Some(server)) => Some(EmbeddedServer::spawn(server)),
|
||||
Ok(None) => None,
|
||||
Err(error)
|
||||
if error
|
||||
.downcast_ref::<LocalError>()
|
||||
.is_some_and(|error| matches!(error, LocalError::AlreadyRunning(_))) =>
|
||||
{
|
||||
// Another process won the startup race after the initial probe.
|
||||
None
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
|
||||
let client_result = run_tui(socket, arguments.theme);
|
||||
let server_result = embedded.map(EmbeddedServer::stop).transpose();
|
||||
client_result.and(server_result.map(|_| ()))
|
||||
}
|
||||
|
||||
fn start_if_missing<T, E>(
|
||||
running: bool,
|
||||
start: impl FnOnce() -> Result<T, E>,
|
||||
) -> Result<Option<T>, E> {
|
||||
if running { Ok(None) } else { start().map(Some) }
|
||||
}
|
||||
|
||||
fn server_responds(socket: &Path) -> bool {
|
||||
client_request(
|
||||
socket,
|
||||
&ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 1,
|
||||
command: RequestCommand::Snapshot,
|
||||
},
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn run_tui(socket: PathBuf, theme: Option<ThemeArgument>) -> Result<()> {
|
||||
if let Some(theme) = theme {
|
||||
tui::run_live_with_theme(IpcMixerClient::new(socket), theme.theme())
|
||||
.context("terminal UI failed")
|
||||
} else {
|
||||
tui::run_live(IpcMixerClient::new(socket)).context("terminal UI failed")
|
||||
}
|
||||
}
|
||||
|
||||
struct EmbeddedServer {
|
||||
shutdown: Arc<AtomicBool>,
|
||||
thread: JoinHandle<Result<(), LocalError>>,
|
||||
}
|
||||
|
||||
impl EmbeddedServer {
|
||||
fn spawn(mut server: LocalServer) -> Self {
|
||||
let shutdown = Arc::new(AtomicBool::new(false));
|
||||
let server_shutdown = Arc::clone(&shutdown);
|
||||
let thread = thread::spawn(move || server.run_until(&server_shutdown));
|
||||
Self { shutdown, thread }
|
||||
}
|
||||
|
||||
fn stop(self) -> Result<()> {
|
||||
self.shutdown.store(true, Ordering::Release);
|
||||
self.thread
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("embedded server thread panicked"))??;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn load_profile(path: &Path) -> Result<Profile> {
|
||||
let input = fs::read_to_string(path)
|
||||
.with_context(|| format!("could not read profile {}", path.display()))?;
|
||||
Profile::parse(&input).with_context(|| format!("profile {} is invalid", path.display()))
|
||||
}
|
||||
|
||||
fn load_profile_document(path: &Path) -> Result<ProfileDocument> {
|
||||
let input = fs::read_to_string(path)
|
||||
.with_context(|| format!("could not read profile {}", path.display()))?;
|
||||
ProfileDocument::parse(&input).with_context(|| format!("profile {} is invalid", path.display()))
|
||||
}
|
||||
|
||||
fn build_server(
|
||||
config: Option<&Path>,
|
||||
override_choice: Option<volume_lib::AdapterChoice>,
|
||||
socket_override: Option<&Path>,
|
||||
) -> Result<LocalServer> {
|
||||
let environment = XdgEnvironment::from_process()?;
|
||||
let paths = XdgPaths::resolve(&environment)?;
|
||||
let config = match config {
|
||||
Some(path) => path.to_owned(),
|
||||
None => {
|
||||
let active_source = fs::read_to_string(paths.config_file()).with_context(|| {
|
||||
format!(
|
||||
"--config was omitted and active selection {} could not be read",
|
||||
paths.config_file().display()
|
||||
)
|
||||
})?;
|
||||
let active = ActiveConfig::parse(&active_source)
|
||||
.context("active profile selection is invalid")?;
|
||||
paths.profile_file(active.active_profile().as_str())?
|
||||
}
|
||||
};
|
||||
let document = load_profile_document(&config)?;
|
||||
let profile = document.preview()?;
|
||||
let policy = audio_selection_policy(&profile, override_choice)?;
|
||||
let selected = select_adapter(
|
||||
&policy,
|
||||
TargetRequirements::APPLICATION_MIXER,
|
||||
&mut CompiledAdapterProbe::default(),
|
||||
)?;
|
||||
if selected.backend != AudioBackend::Pulse {
|
||||
bail!("selected backend {} is not implemented", selected.backend);
|
||||
}
|
||||
|
||||
paths.create_layout()?;
|
||||
let socket = match socket_override {
|
||||
Some(path) => {
|
||||
prepare_private_parent(path)?;
|
||||
path.to_owned()
|
||||
}
|
||||
None => default_socket_path()?,
|
||||
};
|
||||
let server = LocalServer::pulse(
|
||||
socket,
|
||||
Gain::new(profile.max_gain())?,
|
||||
document,
|
||||
config,
|
||||
paths.config_file(),
|
||||
paths.state_file(),
|
||||
)?;
|
||||
println!(
|
||||
"serving profile={} backend={} poll={}ms socket={}",
|
||||
profile.id(),
|
||||
selected.backend,
|
||||
profile.poll_interval().as_millis(),
|
||||
server.socket_path().display()
|
||||
);
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
fn prepare_private_parent(socket: &Path) -> Result<()> {
|
||||
let parent = socket
|
||||
.parent()
|
||||
.context("socket override must have a parent directory")?;
|
||||
fs::create_dir_all(parent)
|
||||
.with_context(|| format!("could not create socket directory {}", parent.display()))?;
|
||||
fs::set_permissions(parent, fs::Permissions::from_mode(0o700))
|
||||
.with_context(|| format!("could not secure socket directory {}", parent.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn status(socket_override: Option<&Path>) -> Result<()> {
|
||||
let socket = socket_override.map_or_else(default_socket_path, |path| Ok(path.to_owned()))?;
|
||||
let response = client_request(
|
||||
&socket,
|
||||
&ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 1,
|
||||
command: RequestCommand::Snapshot,
|
||||
},
|
||||
)?;
|
||||
match response.result {
|
||||
ResponseResult::Snapshot { snapshot } => {
|
||||
println!(
|
||||
"backend={} status={} revision={} objects={}",
|
||||
snapshot.backend,
|
||||
snapshot.status,
|
||||
snapshot.revision,
|
||||
snapshot.objects.len()
|
||||
);
|
||||
for object in snapshot.objects {
|
||||
println!(
|
||||
"kind={:?} id={:?} label={:?} detail={:?} gain={:?} gain_mixed={} muted={:?} mute_mixed={} pending={} writable={} error={:?}",
|
||||
object.object.kind,
|
||||
object.object.id,
|
||||
object.label,
|
||||
object.detail,
|
||||
object.gain,
|
||||
object.gain_mixed,
|
||||
object.muted,
|
||||
object.mute_mixed,
|
||||
object.pending,
|
||||
object.writable,
|
||||
object.error
|
||||
);
|
||||
}
|
||||
for device in snapshot.devices {
|
||||
println!(
|
||||
"device={} label={:?} status={} backend_id={:?} error={:?}",
|
||||
device.id, device.label, device.status, device.backend_id, device.error
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
ResponseResult::Error { message, .. } => bail!(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn switch_profile(id: &str, restore: bool, socket_override: Option<&Path>) -> Result<()> {
|
||||
let socket = socket_override.map_or_else(default_socket_path, |path| Ok(path.to_owned()))?;
|
||||
let response = client_request(
|
||||
&socket,
|
||||
&ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 1,
|
||||
command: RequestCommand::SwitchProfile {
|
||||
id: id.to_owned(),
|
||||
restore,
|
||||
},
|
||||
},
|
||||
)?;
|
||||
match response.result {
|
||||
ResponseResult::Snapshot { snapshot } => {
|
||||
println!(
|
||||
"active profile={} status={}",
|
||||
snapshot.configuration.profile_id, snapshot.status
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
ResponseResult::Error { message, .. } => bail!(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn devices() -> Result<()> {
|
||||
let catalog = MidiInputCatalog::new("fader_master devices")?;
|
||||
let ports = catalog.ports()?;
|
||||
let identities = LinuxIdentityCatalog::new()?;
|
||||
for (index, port) in ports.iter().enumerate() {
|
||||
println!("index={index} identity={:?}", identities.inspect(port)?);
|
||||
}
|
||||
if ports.is_empty() {
|
||||
println!("no MIDI input ports found");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
|
||||
use super::start_if_missing;
|
||||
|
||||
#[test]
|
||||
fn combined_mode_only_starts_a_server_when_probe_did_not_find_one() {
|
||||
let starts = Cell::new(0);
|
||||
let reused = start_if_missing(true, || {
|
||||
starts.set(starts.get() + 1);
|
||||
Ok::<_, ()>("started")
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(reused, None);
|
||||
assert_eq!(starts.get(), 0);
|
||||
|
||||
let started = start_if_missing(false, || {
|
||||
starts.set(starts.get() + 1);
|
||||
Ok::<_, ()>("started")
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(started, Some("started"));
|
||||
assert_eq!(starts.get(), 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use fader_master::{application, cli::ClientCli};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
application::run_client(ClientCli::parse())
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use fader_master::{application, cli::ServerCli};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
application::run_server(ServerCli::parse())
|
||||
}
|
||||
|
|
@ -1,14 +1,60 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use volume_lib::{AdapterChoice, AudioBackend};
|
||||
|
||||
/// fader_master server, diagnostics, and terminal client.
|
||||
/// Combined fader_master server and terminal client, plus diagnostics.
|
||||
#[derive(Clone, Debug, Parser, PartialEq)]
|
||||
#[command(version, about)]
|
||||
pub struct Cli {
|
||||
/// Combined-mode options used when no subcommand is given.
|
||||
#[command(flatten)]
|
||||
pub launch: LaunchOptions,
|
||||
#[command(subcommand)]
|
||||
pub command: Command,
|
||||
pub command: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Args)]
|
||||
pub struct LaunchOptions {
|
||||
/// Validated profile to activate if a server must be started.
|
||||
#[arg(long)]
|
||||
pub config: Option<PathBuf>,
|
||||
/// Session-only audio backend override if a server must be started.
|
||||
#[arg(long, value_enum)]
|
||||
pub audio: Option<AudioArgument>,
|
||||
/// Override the XDG runtime socket path.
|
||||
#[arg(long)]
|
||||
pub socket: Option<PathBuf>,
|
||||
/// Session-only initial color theme override.
|
||||
#[arg(long, value_enum)]
|
||||
pub theme: Option<ThemeArgument>,
|
||||
}
|
||||
|
||||
/// Dedicated persistent-server launcher.
|
||||
#[derive(Clone, Debug, Parser, PartialEq)]
|
||||
#[command(version, about)]
|
||||
pub struct ServerCli {
|
||||
/// Validated profile to activate.
|
||||
#[arg(long)]
|
||||
pub config: Option<PathBuf>,
|
||||
/// Session-only audio backend override.
|
||||
#[arg(long, value_enum)]
|
||||
pub audio: Option<AudioArgument>,
|
||||
/// Override the XDG runtime socket path.
|
||||
#[arg(long)]
|
||||
pub socket: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Dedicated terminal-client launcher.
|
||||
#[derive(Clone, Debug, Parser, PartialEq)]
|
||||
#[command(version, about)]
|
||||
pub struct ClientCli {
|
||||
/// Override the XDG runtime socket path.
|
||||
#[arg(long)]
|
||||
pub socket: Option<PathBuf>,
|
||||
/// Session-only initial color theme override.
|
||||
#[arg(long, value_enum)]
|
||||
pub theme: Option<ThemeArgument>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Subcommand)]
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod application;
|
||||
pub mod cli;
|
||||
mod editor;
|
||||
pub mod ipc;
|
||||
|
|
|
|||
|
|
@ -5,7 +5,10 @@ use std::{
|
|||
net::{UnixListener, UnixStream},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
sync::mpsc::RecvTimeoutError,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc::RecvTimeoutError,
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
|
|
@ -226,6 +229,12 @@ impl LocalServer {
|
|||
})
|
||||
}
|
||||
|
||||
/// Path owned by this server's local IPC listener.
|
||||
#[must_use]
|
||||
pub fn socket_path(&self) -> &Path {
|
||||
self.listener.path()
|
||||
}
|
||||
|
||||
/// Runs until process termination or a fatal worker/socket error.
|
||||
pub fn run(&mut self) -> Result<(), LocalError> {
|
||||
loop {
|
||||
|
|
@ -233,6 +242,14 @@ impl LocalServer {
|
|||
}
|
||||
}
|
||||
|
||||
/// Runs until the caller requests an orderly in-process shutdown.
|
||||
pub fn run_until(&mut self, shutdown: &AtomicBool) -> Result<(), LocalError> {
|
||||
while !shutdown.load(Ordering::Acquire) {
|
||||
self.tick()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn tick(&mut self) -> Result<(), LocalError> {
|
||||
let midi_tick = self.midi.tick();
|
||||
for intent in midi_tick.intents {
|
||||
|
|
|
|||
|
|
@ -1,221 +1,7 @@
|
|||
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use fader_config::{ActiveConfig, Profile, ProfileDocument, XdgEnvironment, XdgPaths};
|
||||
use fader_core::Gain;
|
||||
use fader_master::{
|
||||
audio_selection_policy,
|
||||
cli::{Cli, Command},
|
||||
ipc::{ClientRequest, PROTOCOL_VERSION, RequestCommand, ResponseResult},
|
||||
local::{LocalServer, client_request, default_socket_path},
|
||||
tui_client::IpcMixerClient,
|
||||
};
|
||||
use midi::{LinuxIdentityCatalog, MidiInputCatalog};
|
||||
use volume_lib::{AudioBackend, CompiledAdapterProbe, TargetRequirements, select_adapter};
|
||||
use fader_master::{application, cli::Cli};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
match Cli::parse().command {
|
||||
Command::Tui { socket, theme } => {
|
||||
let socket = socket.map_or_else(default_socket_path, Ok)?;
|
||||
if let Some(theme) = theme {
|
||||
tui::run_live_with_theme(IpcMixerClient::new(socket), theme.theme())
|
||||
.context("terminal UI failed")
|
||||
} else {
|
||||
tui::run_live(IpcMixerClient::new(socket)).context("terminal UI failed")
|
||||
}
|
||||
}
|
||||
Command::Validate { config } => {
|
||||
let profile = load_profile(&config)?;
|
||||
println!("profile {:?} is valid", profile.id().as_str());
|
||||
Ok(())
|
||||
}
|
||||
Command::Serve {
|
||||
config,
|
||||
audio,
|
||||
socket,
|
||||
} => serve(
|
||||
config.as_deref(),
|
||||
audio.map(|value| value.choice()),
|
||||
socket.as_deref(),
|
||||
),
|
||||
Command::Status { socket } => status(socket.as_deref()),
|
||||
Command::Devices => devices(),
|
||||
Command::Profile {
|
||||
command:
|
||||
fader_master::cli::ProfileCommand::Switch {
|
||||
id,
|
||||
restore,
|
||||
socket,
|
||||
},
|
||||
} => switch_profile(&id, restore, socket.as_deref()),
|
||||
}
|
||||
}
|
||||
|
||||
fn load_profile(path: &Path) -> Result<Profile> {
|
||||
let input = fs::read_to_string(path)
|
||||
.with_context(|| format!("could not read profile {}", path.display()))?;
|
||||
Profile::parse(&input).with_context(|| format!("profile {} is invalid", path.display()))
|
||||
}
|
||||
|
||||
fn load_profile_document(path: &Path) -> Result<ProfileDocument> {
|
||||
let input = fs::read_to_string(path)
|
||||
.with_context(|| format!("could not read profile {}", path.display()))?;
|
||||
ProfileDocument::parse(&input).with_context(|| format!("profile {} is invalid", path.display()))
|
||||
}
|
||||
|
||||
fn serve(
|
||||
config: Option<&Path>,
|
||||
override_choice: Option<volume_lib::AdapterChoice>,
|
||||
socket_override: Option<&Path>,
|
||||
) -> Result<()> {
|
||||
let environment = XdgEnvironment::from_process()?;
|
||||
let paths = XdgPaths::resolve(&environment)?;
|
||||
paths.create_layout()?;
|
||||
let config = match config {
|
||||
Some(path) => path.to_owned(),
|
||||
None => {
|
||||
let active_source = fs::read_to_string(paths.config_file()).with_context(|| {
|
||||
format!(
|
||||
"--config was omitted and active selection {} could not be read",
|
||||
paths.config_file().display()
|
||||
)
|
||||
})?;
|
||||
let active = ActiveConfig::parse(&active_source)
|
||||
.context("active profile selection is invalid")?;
|
||||
paths.profile_file(active.active_profile().as_str())?
|
||||
}
|
||||
};
|
||||
let document = load_profile_document(&config)?;
|
||||
let profile = document.preview()?;
|
||||
let policy = audio_selection_policy(&profile, override_choice)?;
|
||||
let selected = select_adapter(
|
||||
&policy,
|
||||
TargetRequirements::APPLICATION_MIXER,
|
||||
&mut CompiledAdapterProbe::default(),
|
||||
)?;
|
||||
if selected.backend != AudioBackend::Pulse {
|
||||
bail!("selected backend {} is not implemented", selected.backend);
|
||||
}
|
||||
|
||||
let socket = match socket_override {
|
||||
Some(path) => {
|
||||
prepare_private_parent(path)?;
|
||||
path.to_owned()
|
||||
}
|
||||
None => default_socket_path()?,
|
||||
};
|
||||
println!(
|
||||
"serving profile={} backend={} poll={}ms socket={}",
|
||||
profile.id(),
|
||||
selected.backend,
|
||||
profile.poll_interval().as_millis(),
|
||||
socket.display()
|
||||
);
|
||||
LocalServer::pulse(
|
||||
socket,
|
||||
Gain::new(profile.max_gain())?,
|
||||
document,
|
||||
config,
|
||||
paths.config_file(),
|
||||
paths.state_file(),
|
||||
)?
|
||||
.run()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prepare_private_parent(socket: &Path) -> Result<()> {
|
||||
let parent = socket
|
||||
.parent()
|
||||
.context("socket override must have a parent directory")?;
|
||||
fs::create_dir_all(parent)
|
||||
.with_context(|| format!("could not create socket directory {}", parent.display()))?;
|
||||
fs::set_permissions(parent, fs::Permissions::from_mode(0o700))
|
||||
.with_context(|| format!("could not secure socket directory {}", parent.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn status(socket_override: Option<&Path>) -> Result<()> {
|
||||
let socket = socket_override.map_or_else(default_socket_path, |path| Ok(path.to_owned()))?;
|
||||
let response = client_request(
|
||||
&socket,
|
||||
&ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 1,
|
||||
command: RequestCommand::Snapshot,
|
||||
},
|
||||
)?;
|
||||
match response.result {
|
||||
ResponseResult::Snapshot { snapshot } => {
|
||||
println!(
|
||||
"backend={} status={} revision={} objects={}",
|
||||
snapshot.backend,
|
||||
snapshot.status,
|
||||
snapshot.revision,
|
||||
snapshot.objects.len()
|
||||
);
|
||||
for object in snapshot.objects {
|
||||
println!(
|
||||
"kind={:?} id={:?} label={:?} detail={:?} gain={:?} gain_mixed={} muted={:?} mute_mixed={} pending={} writable={} error={:?}",
|
||||
object.object.kind,
|
||||
object.object.id,
|
||||
object.label,
|
||||
object.detail,
|
||||
object.gain,
|
||||
object.gain_mixed,
|
||||
object.muted,
|
||||
object.mute_mixed,
|
||||
object.pending,
|
||||
object.writable,
|
||||
object.error
|
||||
);
|
||||
}
|
||||
for device in snapshot.devices {
|
||||
println!(
|
||||
"device={} label={:?} status={} backend_id={:?} error={:?}",
|
||||
device.id, device.label, device.status, device.backend_id, device.error
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
ResponseResult::Error { message, .. } => bail!(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn switch_profile(id: &str, restore: bool, socket_override: Option<&Path>) -> Result<()> {
|
||||
let socket = socket_override.map_or_else(default_socket_path, |path| Ok(path.to_owned()))?;
|
||||
let response = client_request(
|
||||
&socket,
|
||||
&ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 1,
|
||||
command: RequestCommand::SwitchProfile {
|
||||
id: id.to_owned(),
|
||||
restore,
|
||||
},
|
||||
},
|
||||
)?;
|
||||
match response.result {
|
||||
ResponseResult::Snapshot { snapshot } => {
|
||||
println!(
|
||||
"active profile={} status={}",
|
||||
snapshot.configuration.profile_id, snapshot.status
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
ResponseResult::Error { message, .. } => bail!(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn devices() -> Result<()> {
|
||||
let catalog = MidiInputCatalog::new("fader_master devices")?;
|
||||
let ports = catalog.ports()?;
|
||||
let identities = LinuxIdentityCatalog::new()?;
|
||||
for (index, port) in ports.iter().enumerate() {
|
||||
println!("index={index} identity={:?}", identities.inspect(port)?);
|
||||
}
|
||||
if ports.is_empty() {
|
||||
println!("no MIDI input ports found");
|
||||
}
|
||||
Ok(())
|
||||
application::run(Cli::parse())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use clap::{CommandFactory, Parser};
|
||||
use fader_master::cli::{AudioArgument, Cli, Command, ProfileCommand, ThemeArgument};
|
||||
use fader_master::cli::{
|
||||
AudioArgument, Cli, ClientCli, Command, ProfileCommand, ServerCli, ThemeArgument,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn every_planned_command_is_present_in_help() {
|
||||
|
|
@ -17,11 +19,11 @@ fn serve_accepts_durable_selection_or_config_and_parses_session_override() {
|
|||
Cli::try_parse_from(["fader_master", "serve"])
|
||||
.unwrap()
|
||||
.command,
|
||||
Command::Serve {
|
||||
Some(Command::Serve {
|
||||
config: None,
|
||||
audio: None,
|
||||
socket: None,
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
Cli::try_parse_from([
|
||||
|
|
@ -34,10 +36,51 @@ fn serve_accepts_durable_selection_or_config_and_parses_session_override() {
|
|||
])
|
||||
.unwrap()
|
||||
.command,
|
||||
Command::Serve {
|
||||
Some(Command::Serve {
|
||||
config: Some(PathBuf::from("profile.toml")),
|
||||
audio: Some(AudioArgument::Pulse),
|
||||
socket: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_subcommand_selects_all_in_one_and_dedicated_binaries_take_direct_options() {
|
||||
let combined = Cli::try_parse_from([
|
||||
"fader_master",
|
||||
"--config",
|
||||
"profile.toml",
|
||||
"--audio",
|
||||
"pulse",
|
||||
"--theme",
|
||||
"nord",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(combined.command, None);
|
||||
assert_eq!(combined.launch.config, Some(PathBuf::from("profile.toml")));
|
||||
assert_eq!(combined.launch.audio, Some(AudioArgument::Pulse));
|
||||
assert_eq!(combined.launch.theme, Some(ThemeArgument::Nord));
|
||||
|
||||
assert_eq!(
|
||||
ServerCli::try_parse_from([
|
||||
"fader_master_server",
|
||||
"--config",
|
||||
"profile.toml",
|
||||
"--socket",
|
||||
"/tmp/fader.sock",
|
||||
])
|
||||
.unwrap(),
|
||||
ServerCli {
|
||||
config: Some(PathBuf::from("profile.toml")),
|
||||
audio: None,
|
||||
socket: Some(PathBuf::from("/tmp/fader.sock")),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
ClientCli::try_parse_from(["fader_master_client", "--theme", "dracula"]).unwrap(),
|
||||
ClientCli {
|
||||
socket: None,
|
||||
theme: Some(ThemeArgument::Dracula),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
@ -64,19 +107,19 @@ fn tui_accepts_known_themes_and_rejects_unknown_names() {
|
|||
Cli::try_parse_from(["fader_master", "tui"])
|
||||
.unwrap()
|
||||
.command,
|
||||
Command::Tui {
|
||||
Some(Command::Tui {
|
||||
socket: None,
|
||||
theme: None,
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
Cli::try_parse_from(["fader_master", "tui", "--theme", "catppuccin-mocha"])
|
||||
.unwrap()
|
||||
.command,
|
||||
Command::Tui {
|
||||
Some(Command::Tui {
|
||||
socket: None,
|
||||
theme: Some(ThemeArgument::CatppuccinMocha),
|
||||
}
|
||||
})
|
||||
);
|
||||
assert!(Cli::try_parse_from(["fader_master", "tui", "--theme", "hot-dog-stand"]).is_err());
|
||||
}
|
||||
|
|
@ -94,12 +137,12 @@ fn profile_switch_accepts_an_id_and_socket_override() {
|
|||
])
|
||||
.unwrap()
|
||||
.command,
|
||||
Command::Profile {
|
||||
Some(Command::Profile {
|
||||
command: ProfileCommand::Switch {
|
||||
id: "gaming".into(),
|
||||
restore: false,
|
||||
socket: Some("/run/user/1000/fader_master/control.sock".into()),
|
||||
},
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,22 @@
|
|||
use std::{fs, process::Command};
|
||||
|
||||
#[test]
|
||||
fn dedicated_server_and_client_binaries_expose_direct_help() {
|
||||
let server = Command::new(env!("CARGO_BIN_EXE_fader_master_server"))
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(server.status.success());
|
||||
assert!(String::from_utf8_lossy(&server.stdout).contains("--config"));
|
||||
|
||||
let client = Command::new(env!("CARGO_BIN_EXE_fader_master_client"))
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(client.status.success());
|
||||
assert!(String::from_utf8_lossy(&client.stdout).contains("--theme"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_serve_profile_fails_before_socket_or_audio_side_effects() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
8
task.md
8
task.md
|
|
@ -264,6 +264,14 @@ Dependencies: M3, M2; may proceed after the fake-adapter slice.
|
|||
observations still re-arm it. Profiles may tune the shared server/native
|
||||
polling interval from 1 through 100 ms (`10` by default) without changing
|
||||
bounded latest-value coalescing.
|
||||
- [x] **M7.5 Combined and dedicated launchers:** provide
|
||||
`fader_master_server`, `fader_master_client`, and an all-in-one `fader_master`
|
||||
default mode. Combined mode reuses a responding per-user server, starts one
|
||||
only when absent, resolves startup races through the owned socket, and stops
|
||||
and joins only the server it created. Existing `serve` and `tui` subcommands
|
||||
remain compatible. Tests: CLI parsing and binary help cover all three entry
|
||||
points; the launch decision never invokes server startup after a successful
|
||||
probe.
|
||||
|
||||
## M8 — Live TUI
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue