Compare commits
183 Commits
implementa
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
814c87cc6e | |
|
|
31a2fa338a | |
|
|
e11e537e12 | |
|
|
0f59b25fc9 | |
|
|
a31929ec08 | |
|
|
6ee082673b | |
|
|
f7acaf3ba4 | |
|
|
195f3974c6 | |
|
|
431669c994 | |
|
|
c7e33d45d2 | |
|
|
5d0126abff | |
|
|
fb937ef6ae | |
|
|
618c3d7b07 | |
|
|
e0d17d735a | |
|
|
0e224c664b | |
|
|
64f08e9db0 | |
|
|
002570a848 | |
|
|
59fe7f9efc | |
|
|
9b7ebb4bb1 | |
|
|
2b725ca82f | |
|
|
dc27b764fc | |
|
|
704bb3aeaa | |
|
|
8ac222b501 | |
|
|
dd397eb681 | |
|
|
1b32efec9f | |
|
|
7a0e8840ed | |
|
|
e64195e783 | |
|
|
4d17d98809 | |
|
|
af3b460375 | |
|
|
5983b1cfb5 | |
|
|
d12dfb8f27 | |
|
|
34c738847f | |
|
|
1863f82f15 | |
|
|
a967cc30ea | |
|
|
86a12fbfe4 | |
|
|
69975e57dd | |
|
|
7b18fe5030 | |
|
|
b422018a89 | |
|
|
832a04cb67 | |
|
|
db41daaaf8 | |
|
|
54149c3302 | |
|
|
a03c8c4d8d | |
|
|
3a3f68706e | |
|
|
50d3097ff6 | |
|
|
ff84f167ab | |
|
|
8add95df3f | |
|
|
33798eeb6e | |
|
|
2e03e8f60c | |
|
|
a7587d45de | |
|
|
4e0d3e99a7 | |
|
|
c1f3377914 | |
|
|
e5239e3243 | |
|
|
944e005914 | |
|
|
51565940a9 | |
|
|
041f40db5e | |
|
|
164be169f0 | |
|
|
51b23b8b25 | |
|
|
a464735f54 | |
|
|
c7d2450efb | |
|
|
a48dcab234 | |
|
|
6d44716144 | |
|
|
a47e1452bd | |
|
|
9464944634 | |
|
|
eeb69ae944 | |
|
|
ef917e1071 | |
|
|
c30b361fd0 | |
|
|
564fca9001 | |
|
|
f37e16fa7d | |
|
|
488cb200df | |
|
|
4f3a70d1ef | |
|
|
8348e2efe1 | |
|
|
e371abea4b | |
|
|
28c2d6ce90 | |
|
|
563a8e34ba | |
|
|
a90a38b89e | |
|
|
556e0bdfe1 | |
|
|
c0129cecfa | |
|
|
16e724b7c8 | |
|
|
a6d9dc558f | |
|
|
acb0f609cb | |
|
|
2fe7824203 | |
|
|
bcba3e96eb | |
|
|
e55ed59f5b | |
|
|
6a8db551a9 | |
|
|
6fa9bf2a57 | |
|
|
93506e0a67 | |
|
|
1da6da5da2 | |
|
|
6156700927 | |
|
|
b9d52a3d5e | |
|
|
7790951c22 | |
|
|
ef60da3953 | |
|
|
fbea588e67 | |
|
|
661b0b105a | |
|
|
184cec90c7 | |
|
|
d028cf26f0 | |
|
|
1129cc9730 | |
|
|
cbaf2a9694 | |
|
|
8e1c504478 | |
|
|
fa45944b79 | |
|
|
9941a79231 | |
|
|
5daa06100b | |
|
|
102f233980 | |
|
|
b5d7ac9c5f | |
|
|
3452fee880 | |
|
|
9493183365 | |
|
|
44582036c5 | |
|
|
e7a0254b38 | |
|
|
a286e4258e | |
|
|
69a49cdbfd | |
|
|
c812af52ee | |
|
|
3a75e24003 | |
|
|
9b3cc9c9a2 | |
|
|
7d58204ab1 | |
|
|
f029304cf4 | |
|
|
f673b313a7 | |
|
|
b1a1f0769b | |
|
|
1fae9bef73 | |
|
|
ce88a5ee6a | |
|
|
977f7452b1 | |
|
|
95282c6222 | |
|
|
fda38f6f17 | |
|
|
9648fdf5db | |
|
|
8b5df92d3e | |
|
|
5721a713a0 | |
|
|
51d1e5bd25 | |
|
|
ff2e39e135 | |
|
|
6004d8cf8d | |
|
|
be4f592295 | |
|
|
e8e810d1ff | |
|
|
ad71ef4161 | |
|
|
8aef74f271 | |
|
|
25e61c2138 | |
|
|
e57c8812bf | |
|
|
b5a24160ae | |
|
|
a7e75da771 | |
|
|
0a0be30651 | |
|
|
d21a57f4d5 | |
|
|
86b6c0ee41 | |
|
|
6ae361c595 | |
|
|
472625301e | |
|
|
ed46d3ae37 | |
|
|
3c164221b0 | |
|
|
3b318256bf | |
|
|
a01e451643 | |
|
|
b4870a67b9 | |
|
|
e1fe9b2733 | |
|
|
d5229e5eca | |
|
|
a5e98c8182 | |
|
|
8b1bf03744 | |
|
|
ef4b63d4f8 | |
|
|
ce31b6b0fb | |
|
|
eff5fece91 | |
|
|
ff23a1aa7b | |
|
|
35a50e06e4 | |
|
|
efc1981c03 | |
|
|
e9fdd8c124 | |
|
|
5411550cf7 | |
|
|
bb12fb14b1 | |
|
|
e7067e277f | |
|
|
90ba84a802 | |
|
|
4f3eb4f279 | |
|
|
58e08f3741 | |
|
|
4e115b8562 | |
|
|
013ff0de9f | |
|
|
6c0c8be2d0 | |
|
|
7d24fbda62 | |
|
|
81241452fb | |
|
|
7bb15ec039 | |
|
|
5a14b46a39 | |
|
|
11b588f606 | |
|
|
df8ed342cc | |
|
|
51c4dd9e97 | |
|
|
3aae565c24 | |
|
|
6a3198d0e9 | |
|
|
e0a309b565 | |
|
|
0beaee783c | |
|
|
1eaeaf81e2 | |
|
|
616ae07217 | |
|
|
123a67732f | |
|
|
bccc948ebd | |
|
|
9711e6024c | |
|
|
567aa13262 | |
|
|
bfbd42f9bd |
|
|
@ -8,6 +8,7 @@ target/
|
|||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
# CI-generated badge files, markers, and coverage reports.
|
||||
/coverage/
|
||||
/dist/
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
|
|
|||
12
AGENTS.md
12
AGENTS.md
|
|
@ -5,11 +5,15 @@ Act as the Rust project steward for fader_master: a Linux MIDI-to-application-vo
|
|||
## Working method and commits
|
||||
|
||||
- Read the architecture, task dependencies, repository status, and affected code before changing behavior. Select the smallest independently testable acceptance criterion.
|
||||
- For behavior changes, write a meaningful failing test, implement the behavior, and refactor with tests green. Use one commit per tested behavior or tightly coupled acceptance-test group; do not combine unrelated milestones or commit a deliberately failing intermediate state.
|
||||
- Include the test and implementation in the same commit. Record the test command and result in the commit body. Documentation-only commits should record document validation rather than inventing runtime tests.
|
||||
- Treat each selected backlog task or independently testable acceptance criterion as an atomic commit boundary. Finish and commit that boundary before starting the next one. If a backlog task contains independent behaviors, use multiple ordered commits; never combine separate tasks or milestones merely because they were requested together.
|
||||
- A request to implement a task authorizes the local commits needed for that task. Do not ask again before each commit. An explicit user instruction not to commit overrides this default. Never push, publish, or create tags unless the user separately authorizes that action.
|
||||
- For behavior changes, write a meaningful failing test, implement the behavior, and refactor with tests green. Keep the test and implementation in the same commit, and never commit a deliberately failing intermediate state.
|
||||
- Record the test command and result in the commit body. Documentation-only commits should record document validation rather than inventing runtime tests.
|
||||
- Before each commit inspect the staged diff and run relevant tests. Before completing a milestone run the workspace gates below. If a gate is blocked, report its exact cause; never describe it as passing or mark an unverified implementation task complete.
|
||||
- Update task checkboxes only when their acceptance criteria pass. Keep design decisions, configuration examples, and user documentation consistent with implementation.
|
||||
- Preserve user edits. Stage specific files. Do not amend, reset, force-push, or publish without authorization. Local incremental commits are requested for this project.
|
||||
- At the start of every task, inventory the dirty worktree and identify changes that predate the task. Preserve those changes, stage explicit paths or hunks, and exclude unrelated work from the task commit. If safe separation is impossible, stop and ask rather than absorbing someone else's edits.
|
||||
- When multiple agents share the worktree, give them non-overlapping task boundaries. Subagents report their changed files and verification results; the coordinating agent stages and creates the atomic commits so concurrent agents never race on the shared Git index.
|
||||
- Use a task-specific imperative commit subject, referencing the backlog ID when one exists. Do not amend, reset, force-push, or publish without authorization. Local incremental commits are required for completed implementation tasks.
|
||||
- Keep research spikes bounded. Verify current dependency APIs, licenses, MSRV, and native prerequisites before adding a crate. Explain material tradeoffs in the architecture.
|
||||
|
||||
## Rust standards
|
||||
|
|
@ -39,4 +43,4 @@ cargo build --workspace --release --all-features
|
|||
|
||||
Also test the default build, no-default-features build, and each optional backend independently once feature flags exist. Provision native development libraries in CI. Hardware-free domain, fake-adapter, config, and TUI tests must run without an audio daemon or USB device. Keep real audio/hardware checks separately opt-in and document their fixtures and prerequisites. Add property tests for numerical conversions and state invariants; use a fake clock for retries and coalescing. Test observable behavior, including failure paths, rather than private implementation details.
|
||||
|
||||
Current baseline: the workspace is a scaffold, not an implementation of the architecture. Its Jenkinsfile lacks doctests and Clippy warning enforcement; Cargo.lock is currently ignored. Fix these deliberately in the foundation milestone.
|
||||
Current baseline (2026-10-16): Rust 1.88.0 is pinned. Native MIDI/Pulse workers, live IPC/TUI, managed profiles, MIDI learn/feedback, and persisted mixer editing are implemented. The `implementation-start` tag marks the original CI coverage/badge baseline. Follow unchecked acceptance criteria in `task.md`; do not restart completed foundation work. M0.2 still awaits provisioned Linux Jenkins verification, and native PipeWire and runtime relative groups remain unfinished. Keep save/reload/server-restart coverage for layout order and preserve user-edited example profiles.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Add Any/All application selectors and bounded process/Steam metadata with
|
||||
normalized diagnostics in Config.
|
||||
- Add the optional MPRIS Media tab: exact/regex player selection, discovery
|
||||
picker, persisted entry/control editing, MIDI learn/unbind, transport, seeking,
|
||||
shuffle, repeat and playlist activation.
|
||||
- Add confirmed media feedback, custom note/CC color mappings, and global,
|
||||
per-fader and per-media-entry feedback switches.
|
||||
- Bound media discovery and configuration; expand bounded IPC frames for playlist
|
||||
snapshots. Rebuild and restart both server and client. Real-controller/player
|
||||
checks remain opt-in; see the hands-on checklist.
|
||||
|
||||
## 0.1.0-rc.2 — 2026-10-18
|
||||
|
||||
- Fix persistent stale-revision failures from MIDI volume/mute after saving
|
||||
configuration; retain revision protection for external clients.
|
||||
- Default mute feedback to the same MIDI note/channel on any configured output,
|
||||
with alternate protocols and values supplied by explicit feedback settings.
|
||||
- Add generic mixer add/edit/delete actions, fader renaming, MIDI device removal,
|
||||
confirmed configuration reset, and the loaded configuration path in Config.
|
||||
- Simplify quick help, expose layout switching, preserve empty feedback space,
|
||||
and materialize omitted optional config arrays during editing.
|
||||
- Align regression tests with the updated Arch PipeWire example bindings.
|
||||
|
||||
Restart both server and client when upgrading; the IPC protocol has changed.
|
||||
Artifacts target x86-64 GNU/Linux with an Ubuntu 24.04-based build environment.
|
||||
Native PipeWire, relative groups, and full hardware/release qualification remain
|
||||
unfinished. Use PulseAudio or pipewire-pulse; this is a prerelease.
|
||||
|
||||
## 0.1.0-rc.1 — 2026-10-16
|
||||
|
||||
First [published release candidate](https://proxy.dandaedre.com/gitea/MadGobblins/fader_master/releases/tag/v0.1.0-rc.1).
|
||||
All three x86-64 GNU/Linux executables are available individually and together
|
||||
in a `.tgz` archive, with checksums. See the [build provenance](docs/releasing.md#published-rc-build).
|
||||
|
||||
- Linux MIDI control of application, group and default-output volume through
|
||||
PulseAudio or pipewire-pulse, with MIDI learn, pickup and mute feedback.
|
||||
- Combined launcher plus separate server and client executables; reconnecting
|
||||
TUI, managed profiles, safe first-run setup and persisted editing.
|
||||
- Horizontal and vertical mixers, themes, configurable fader sizes,
|
||||
separators/spacers, hidden faders and pickup status presentation.
|
||||
|
||||
Known limits: native PipeWire and runtime relative groups are unfinished.
|
||||
Hardware coverage, Linux CI provisioning and the remaining M12 release gates
|
||||
must still be completed; see [the backlog](task.md).
|
||||
File diff suppressed because it is too large
Load Diff
34
Cargo.toml
34
Cargo.toml
|
|
@ -1,14 +1,38 @@
|
|||
# cargo-features = ["codegen-backend"]
|
||||
|
||||
[workspace]
|
||||
members = [ "tui", "sound" , "fader_master", "midi"]
|
||||
members = ["config", "core", "fader_master", "media", "midi", "sound", "tui"]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
version = "0.1.0-rc.2"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
license-file = "LICENSE"
|
||||
repository = "https://proxy.dandaedre.com/gitea/MadGobblins/fader_master"
|
||||
publish = false
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[workspace.dependencies]
|
||||
dbus = "=0.9.12"
|
||||
media = { path = "media" }
|
||||
alsa = "0.12.1"
|
||||
anyhow = "1.0.104"
|
||||
clap = { version = "4.6.7", features = ["derive"] }
|
||||
fader-config = { path = "config" }
|
||||
fader-core = { path = "core" }
|
||||
midi = { path = "midi" }
|
||||
libpulse-binding = "2.30.1"
|
||||
midir = "0.11.1"
|
||||
proptest = "1.11.0"
|
||||
ratatui = { version = "0.29.0", features = ["all-widgets", "serde"] }
|
||||
regex = "1.13.1"
|
||||
rustix = { version = "1.1.5", features = ["net", "process"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
tempfile = "3.27.0"
|
||||
thiserror = "2.0.21"
|
||||
toml = "0.8.23"
|
||||
toml_edit = "0.22.27"
|
||||
tui = { path = "tui" }
|
||||
udev = "0.9.3"
|
||||
volume_lib = { path = "sound" }
|
||||
|
||||
[profile.dev]
|
||||
debug = true
|
||||
|
|
|
|||
|
|
@ -0,0 +1,6 @@
|
|||
[build.env]
|
||||
passthrough = ["RUSTUP_TOOLCHAIN"]
|
||||
|
||||
[target.x86_64-unknown-linux-gnu]
|
||||
image = "ghcr.io/cross-rs/x86_64-unknown-linux-gnu:0.2.5"
|
||||
pre-build = ["apt-get update && apt-get install --assume-yes --no-install-recommends pkg-config libasound2-dev libpulse-dev libudev-dev libdbus-1-dev"]
|
||||
|
|
@ -11,7 +11,16 @@ pipeline {
|
|||
timestamps()
|
||||
}
|
||||
|
||||
parameters {
|
||||
booleanParam(
|
||||
name: 'ENABLE_NATIVE_BACKENDS',
|
||||
defaultValue: false,
|
||||
description: 'Run Linux-only MIDI/Pulse gates after the worker has been migrated and provisioned.'
|
||||
)
|
||||
}
|
||||
|
||||
environment {
|
||||
ENABLE_NATIVE_BACKENDS = "${params.ENABLE_NATIVE_BACKENDS ?: false}"
|
||||
CARGO_TERM_COLOR = 'never'
|
||||
RUST_BACKTRACE = '1'
|
||||
CARGO_TARGET_DIR = "${WORKSPACE}/target-ci"
|
||||
|
|
@ -22,6 +31,7 @@ pipeline {
|
|||
BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
|
||||
COVERAGE_MIN_LINES = '20'
|
||||
CARGO_LLVM_COV_VERSION = '0.9.1'
|
||||
RUSTUP_TOOLCHAIN = '1.88.0'
|
||||
}
|
||||
|
||||
stages {
|
||||
|
|
@ -51,25 +61,37 @@ pipeline {
|
|||
exit 1
|
||||
fi
|
||||
|
||||
rustup toolchain install stable \
|
||||
--profile minimal \
|
||||
--component rustfmt \
|
||||
--component clippy \
|
||||
--component llvm-tools-preview
|
||||
rustup default stable
|
||||
if [ "${ENABLE_NATIVE_BACKENDS}" = true ]; then
|
||||
rustup toolchain install "${RUSTUP_TOOLCHAIN}" \
|
||||
--profile minimal \
|
||||
--component rustfmt \
|
||||
--component clippy \
|
||||
--component llvm-tools-preview
|
||||
else
|
||||
rustup toolchain install "${RUSTUP_TOOLCHAIN}" \
|
||||
--profile minimal \
|
||||
--component rustfmt \
|
||||
--component clippy
|
||||
fi
|
||||
|
||||
if ! cargo llvm-cov --version 2>/dev/null \
|
||||
| grep -F "cargo-llvm-cov ${CARGO_LLVM_COV_VERSION}" >/dev/null; then
|
||||
cargo install cargo-llvm-cov \
|
||||
--version "${CARGO_LLVM_COV_VERSION}" \
|
||||
--locked
|
||||
if [ "${ENABLE_NATIVE_BACKENDS}" = true ]; then
|
||||
if ! cargo llvm-cov --version 2>/dev/null \
|
||||
| grep -F "cargo-llvm-cov ${CARGO_LLVM_COV_VERSION}" >/dev/null; then
|
||||
cargo install cargo-llvm-cov \
|
||||
--version "${CARGO_LLVM_COV_VERSION}" \
|
||||
--locked
|
||||
fi
|
||||
fi
|
||||
|
||||
rustc --version
|
||||
cargo --version
|
||||
rustfmt --version
|
||||
cargo clippy --version
|
||||
cargo llvm-cov --version
|
||||
if [ "${ENABLE_NATIVE_BACKENDS}" = true ]; then
|
||||
cargo llvm-cov --version
|
||||
else
|
||||
echo 'Native backend and coverage gates are disabled for this portable build.'
|
||||
fi
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
|
@ -93,25 +115,60 @@ pipeline {
|
|||
}
|
||||
|
||||
stage('Check') {
|
||||
when { expression { params.ENABLE_NATIVE_BACKENDS } }
|
||||
steps {
|
||||
sh '''
|
||||
set -eu
|
||||
pkg-config --exists alsa libpulse libudev dbus-1
|
||||
command -v dbus-run-session
|
||||
cargo check --workspace --all-targets --locked
|
||||
cargo check --workspace --all-targets --no-default-features --locked
|
||||
cargo check --workspace --all-targets --all-features --locked
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Tests') {
|
||||
when { expression { params.ENABLE_NATIVE_BACKENDS } }
|
||||
steps {
|
||||
sh '''
|
||||
set -eu
|
||||
cargo test --workspace --all-targets --locked
|
||||
cargo test --workspace --all-targets --no-default-features --locked
|
||||
cargo test --workspace --all-targets --all-features --locked
|
||||
dbus-run-session -- cargo test -p fader_master private_bus --locked -- --ignored
|
||||
: >"coverage/.tests-passed-${BUILD_NUMBER}"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Portable Rust Gates') {
|
||||
when { expression { !params.ENABLE_NATIVE_BACKENDS } }
|
||||
steps {
|
||||
sh '''
|
||||
set -eu
|
||||
|
||||
cargo check -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
|
||||
--all-targets --no-default-features --locked
|
||||
cargo test -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
|
||||
--all-targets --no-default-features --locked
|
||||
cargo test -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
|
||||
--doc --no-default-features --locked
|
||||
RUSTDOCFLAGS='-D warnings' \
|
||||
cargo doc -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
|
||||
--no-deps --no-default-features --locked
|
||||
cargo clippy -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
|
||||
--all-targets --no-default-features --locked -- -D warnings
|
||||
cargo build -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
|
||||
--release --no-default-features --locked
|
||||
|
||||
: >"coverage/.tests-passed-${BUILD_NUMBER}"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Coverage') {
|
||||
when { expression { params.ENABLE_NATIVE_BACKENDS } }
|
||||
steps {
|
||||
sh '''
|
||||
scripts/ci-run-coverage.sh \
|
||||
|
|
@ -124,6 +181,7 @@ pipeline {
|
|||
}
|
||||
|
||||
stage('Documentation') {
|
||||
when { expression { params.ENABLE_NATIVE_BACKENDS } }
|
||||
steps {
|
||||
sh '''
|
||||
set -eu
|
||||
|
|
@ -135,6 +193,7 @@ pipeline {
|
|||
}
|
||||
|
||||
stage('Clippy') {
|
||||
when { expression { params.ENABLE_NATIVE_BACKENDS } }
|
||||
steps {
|
||||
sh '''
|
||||
set -eu
|
||||
|
|
@ -150,9 +209,11 @@ pipeline {
|
|||
}
|
||||
|
||||
stage('Build Release') {
|
||||
when { expression { params.ENABLE_NATIVE_BACKENDS } }
|
||||
steps {
|
||||
sh '''
|
||||
set -eu
|
||||
cargo build --workspace --locked
|
||||
cargo build --workspace --release --all-features --locked
|
||||
|
||||
BINARY="${CARGO_TARGET_DIR}/release/fader_master"
|
||||
|
|
@ -205,18 +266,24 @@ pipeline {
|
|||
echo 'Not publishing mutable badges: BRANCH_NAME and GIT_BRANCH are unavailable.'
|
||||
}
|
||||
|
||||
def nativeBackends = params.ENABLE_NATIVE_BACKENDS
|
||||
def coverageStatus = fileExists('coverage/coverage-status.txt')
|
||||
? readFile('coverage/coverage-status.txt').trim()
|
||||
: "Line coverage: unavailable; required minimum: ${env.COVERAGE_MIN_LINES}%; reason: the coverage stage did not produce a status"
|
||||
: nativeBackends
|
||||
? "Line coverage: unavailable; required minimum: ${env.COVERAGE_MIN_LINES}%; reason: the coverage stage did not produce a status"
|
||||
: 'Line coverage: unavailable; portable FreeBSD gates intentionally exclude the Linux-only executable and native backends'
|
||||
def passed = currentBuild.currentResult == 'SUCCESS'
|
||||
def gateSummary = nativeBackends
|
||||
? 'Full Linux/native formatting, checks, tests, coverage, documentation, Clippy, and release gates were evaluated.'
|
||||
: 'Portable formatting, checks, tests, documentation, Clippy, and release-library gates were evaluated; Linux-only executable and native backend gates were skipped.'
|
||||
publishChecks(
|
||||
conclusion: passed ? 'SUCCESS' : 'FAILURE',
|
||||
name: 'Rust CI',
|
||||
summary: passed ? 'fader_master passed CI.' : 'fader_master failed CI.',
|
||||
text: "Formatting, checks, tests, coverage, documentation, warning-strict Clippy, release build, and badge generation were evaluated. ${coverageStatus}",
|
||||
title: passed ? 'Build Successful' : 'Build Failed'
|
||||
summary: passed ? 'fader_master passed its selected CI mode.' : 'fader_master failed CI.',
|
||||
text: "${gateSummary} ${coverageStatus}",
|
||||
title: passed ? (nativeBackends ? 'Native Build Successful' : 'Portable Build Successful') : 'Build Failed'
|
||||
)
|
||||
echo "${passed ? 'fader_master passed CI.' : 'fader_master CI failed.'} ${coverageStatus}"
|
||||
echo "${passed ? 'fader_master passed its selected CI mode.' : 'fader_master CI failed.'} ${gateSummary} ${coverageStatus}"
|
||||
|
||||
sh 'rm -f coverage/coverage-status.txt'
|
||||
}
|
||||
|
|
|
|||
145
README.md
145
README.md
|
|
@ -4,19 +4,140 @@
|
|||

|
||||

|
||||
|
||||
Linux application volume and mute control from one or more USB MIDI surfaces.
|
||||
Control Linux application volume and mute from a USB MIDI controller. One
|
||||
fader can follow an application, a group of applications, or the default audio
|
||||
output, while the terminal UI remains useful as a complete software mixer.
|
||||
|
||||
This repository currently contains an early Rust workspace and TUI prototype.
|
||||
The server, audio adapters, persistent bindings, and configuration editor are
|
||||
planned in the following documents:
|
||||

|
||||
|
||||
- [Architecture and library research](architecture.md)
|
||||
- [Implementation tasks and acceptance tests](task.md)
|
||||
- [Project-agent instructions and test/commit workflow](AGENTS.md)
|
||||
- [CI coverage and badge lifecycle](docs/ci-coverage.md)
|
||||
The horizontal layout puts bottom-up faders side by side, with dividers and
|
||||
flexible spacers between sections. Switch to Vertical in Config for stacked
|
||||
cards, including one-row Slim and Bordered slim faders:
|
||||
|
||||
# References
|
||||

|
||||
|
||||
* [pwvucontrol](https://github.com/saivert/pwvucontrol/blob/main/src/backend/pwnodeobject/mixerapi.rs)
|
||||
* [ratatui](https://ratatui.rs/)
|
||||
* [midir](https://github.com/Boddlnagg/midir)
|
||||
## Features
|
||||
|
||||
- Match PulseAudio or `pipewire-pulse` streams by application metadata, with
|
||||
exact and regular-expression capture rules, Any/All composition, and available
|
||||
executable/working-directory and Steam IDs.
|
||||
- Target MPRIS players directly from the Media tab or MIDI: transport, seeking,
|
||||
shuffle, repeat and playlists, with confirmed-state feedback and global/local
|
||||
feedback switches. See [media configuration](docs/configuration.md#media-controls-mpris).
|
||||
- Control individual applications, non-nesting application groups, and the
|
||||
default output without changing live audio during discovery.
|
||||
- Learn volume and mute controls from MIDI, reflect confirmed mute state on
|
||||
control-surface LEDs, use pickup to prevent jumps, and
|
||||
keep independently identified controllers from colliding.
|
||||
- Arrange faders, separators, and empty spacers directly in the mixer. Choose Slim,
|
||||
Bordered slim, Standard, or Thick faders, and hide detail faders behind a
|
||||
group when useful.
|
||||
- Size separators independently and choose Plain, Line, Double line, or Box.
|
||||
Fill separators share spare space; names are optional.
|
||||
- Use horizontal or vertical layouts and six built-in terminal themes.
|
||||
- Choose Detailed, Compact, Symbol, Color, or Hidden pickup feedback in Config.
|
||||
Hiding the indicator keeps pickup protection active.
|
||||
- Run as one command, or keep a standalone server alive while reconnecting TUI
|
||||
clients come and go.
|
||||
- Edit a validated draft from the TUI and persist it with one explicit Save.
|
||||
Malformed or conflicting edits never replace the active configuration.
|
||||
- Switch among valid managed profiles from a popup in the Config view; the
|
||||
default switch adopts live audio without writing saved volume state.
|
||||
- Reset the active profile from Config after an explicit confirmation. The TUI
|
||||
preserves the previous file as `<profile>.toml.reset.bak` before installing
|
||||
and activating a safe Master-output profile.
|
||||
|
||||
## Quick start
|
||||
|
||||
### Install a prebuilt release (recommended)
|
||||
|
||||
With [cargo-binstall](https://github.com/cargo-bins/cargo-binstall#installation)
|
||||
installed, download the current release candidate without compiling:
|
||||
|
||||
```sh
|
||||
cargo binstall --git https://proxy.dandaedre.com/gitea/MadGobblins/fader_master \
|
||||
--version '=0.1.0-rc.2' --strategies crate-meta-data fader_master
|
||||
fader_master
|
||||
```
|
||||
|
||||
This installs the combined launcher plus `fader_master_server` and
|
||||
`fader_master_client`. Ensure Cargo's binary directory (usually `~/.cargo/bin`)
|
||||
is on your `PATH`. No repository checkout or sample configuration is needed.
|
||||
|
||||
Prebuilt binaries currently target **x86-64 GNU/Linux** and require ALSA,
|
||||
libpulse and libudev runtime libraries, plus PulseAudio or `pipewire-pulse`.
|
||||
They are built with an Ubuntu 24.04-based image; older distributions are not
|
||||
yet qualified. This is an RC, not a stable release.
|
||||
|
||||
Without cargo-binstall, download the archive containing all three executables
|
||||
from the [release page](https://proxy.dandaedre.com/gitea/MadGobblins/fader_master/releases/tag/v0.1.0-rc.2),
|
||||
verify it against the accompanying `SHA256SUMS`, and extract the executables
|
||||
into a directory on your `PATH`.
|
||||
|
||||
### First launch
|
||||
|
||||
The combined executable connects to an existing per-user server when possible
|
||||
and starts an embedded one otherwise. Running without `--config` creates
|
||||
a `default` profile with a Master-output fader. A sole detected MIDI input is
|
||||
adopted as the default controller; otherwise choose a detected input in Config,
|
||||
add it, and Save. Edit the Master fader with `E` to learn volume and mute controls.
|
||||
Configured controllers can be removed with `D` in Config; confirmation also
|
||||
removes their bindings, and Save activates the change.
|
||||
|
||||
### Build from source (alternative)
|
||||
|
||||
For development or systems without compatible prebuilt binaries, follow the
|
||||
[build prerequisites](docs/build.md). From a source checkout, run:
|
||||
|
||||
```sh
|
||||
cargo run --locked -p fader_master
|
||||
```
|
||||
|
||||
See [advanced configuration](docs/configuration.md) for explicit profiles and
|
||||
separate server/client operation.
|
||||
|
||||
The screenshots use reproducible example state rendered by the actual TUI;
|
||||
they do not represent a live hardware session.
|
||||
|
||||
## Everyday controls
|
||||
|
||||
| Action | Vertical | Horizontal |
|
||||
|---|---|---|
|
||||
| Select | Up/Down or J/K | Left/Right or J/K |
|
||||
| Change volume | Left/Right | Up/Down |
|
||||
| Reorder | Shift+Up/Down or Shift+J/K | Shift+Left/Right or Shift+J/K |
|
||||
| Toggle mute | M | M |
|
||||
| Add fader, group, or separator | A | A |
|
||||
| Edit selected entry | E | E |
|
||||
| Delete selected entry | D | D |
|
||||
| Hide selected fader | Shift+H | Shift+H |
|
||||
| Help | h or ? | h or ? |
|
||||
|
||||
Use `Tab` to open Config, select Mixer layout and use Left/Right to switch its
|
||||
orientation, `T` to cycle the theme, and `Q` to open the quit confirmation.
|
||||
Fader editing exposes the application/group display name, capture rules, group membership, separate
|
||||
controller/Learn/Unlearn actions for volume and mute, size, and visibility.
|
||||
Add opens a chooser for a new application fader, empty group, or separator.
|
||||
New faders and groups open directly in the editor and remain visible as offline
|
||||
`DRAFT` rows until Save activates them. Delete asks for confirmation and removes
|
||||
the selected fader and its unshared target, or the selected separator.
|
||||
Config → Active profile opens the profile switcher.
|
||||
Config → Reset active profile provides an emergency return to safe defaults;
|
||||
confirming it immediately saves and activates the reset and keeps a `.reset.bak`
|
||||
copy beside the profile.
|
||||
Separator editing offers an optional name, size, and decoration; an empty
|
||||
name with Plain + Fill creates flexible blank space. Press Enter to accept
|
||||
popup edits, then use Config → Save to persist the draft.
|
||||
|
||||
After updating the binaries, restart the server as well as the client. The
|
||||
combined launcher reuses an already-running server.
|
||||
|
||||
## Documentation
|
||||
|
||||
The [documentation index](docs/README.md) contains installation instructions,
|
||||
advanced configuration and process layouts, examples, troubleshooting notes,
|
||||
architecture, project status, and related projects.
|
||||
|
||||
## License
|
||||
|
||||
See [LICENSE](LICENSE).
|
||||
|
|
|
|||
574
architecture.md
574
architecture.md
|
|
@ -1,12 +1,93 @@
|
|||
# fader_master architecture
|
||||
|
||||
Status: proposed implementation design, researched 2026-10-05. The current workspace contains placeholder MIDI/audio libraries, a Hello World executable, and a basic Ratatui example. Features below are planned, not shipped.
|
||||
Status as of 2026-10-16: the Linux server runs native MIDI and Pulse-compatible
|
||||
audio workers, a reconnecting live TUI, managed profiles, MIDI learn and mute
|
||||
feedback, and a persisted mixer/configuration editor. The combined launcher
|
||||
starts a server only when none is available. Layouts include horizontal strips,
|
||||
stacked faders, configurable separators/spacers, themes, and pickup indicators.
|
||||
Native PipeWire, runtime relative groups, and the unchecked acceptance work in
|
||||
`task.md` remain unfinished.
|
||||
|
||||
## Foundation and implementation history
|
||||
|
||||
Release preparation uses a project-local POSIX wrapper around `rust_realease`,
|
||||
with Cargo metadata as the version authority and an exact SSH-to-public-HTTPS
|
||||
repository mapping. The initial artifact target is x86-64 GNU/Linux because
|
||||
the executable requires native ALSA, Pulse and udev libraries. All three binary
|
||||
entry points share one archive; standalone downloads are also planned. Cross
|
||||
supplies native build prerequisites; publication remains a separate explicit
|
||||
operation. See [release contract and outstanding qualification](docs/releasing.md).
|
||||
|
||||
The following foundation notes describe the original milestone boundaries;
|
||||
the runtime and UI contracts later in this document describe the current system.
|
||||
|
||||
Rust 1.88.0 is the pinned toolchain and tested MSRV. The workspace inherits
|
||||
package metadata, including the existing custom `LICENSE` through `license-file`.
|
||||
`core` contains typed IDs, finite gain/channel vectors, normalized selectors,
|
||||
stream identities, logical routing, device-scoped bindings, group gain planning,
|
||||
and serial mute intent planning. `config` contains strict version-1 profile,
|
||||
device-capability, and persisted-state schemas. Parsing validates stable IDs,
|
||||
selectors, references, duplicate IDs and physical bindings, audio/MIDI bounds,
|
||||
and feedback/output capabilities before returning a document. It serializes a
|
||||
canonical semantic round trip. XDG resolution, private directory/file modes,
|
||||
owner/symlink checks, same-directory atomic replacement with file and directory
|
||||
sync, recoverable state loads, comment-preserving application-label edits, and
|
||||
forward-migration backups are implemented. A pure monotonic checkpoint
|
||||
coordinator owns the 500 ms debounce, two-second maximum dirty interval, and
|
||||
shutdown flush. Restart views force cached observations stale and retain desired
|
||||
intent separately; adopt produces no audio write, while restore checks the
|
||||
profile write ceiling before yielding application-join intent. MIDI/audio crates
|
||||
are adapter boundaries without native handles or transport behavior yet.
|
||||
|
||||
Stable IDs contain 1–64 ASCII bytes, start with an alphanumeric character, and
|
||||
otherwise allow alphanumerics, `_`, and `-`. Selector patterns contain 1–256
|
||||
bytes; regex compilation has a 1 MiB size limit. Missing normalized properties
|
||||
never fall back to raw metadata. Group references cannot nest. Logical routing
|
||||
validates references and returns ordered, deduplicated stream sets. Physical
|
||||
binding lookup includes surface, channel, message kind, and control number.
|
||||
|
||||
Group gain plans clip each stream at the explicit write ceiling, preserve channel
|
||||
ratios, and leave observations unchanged. Relative scaling divides a stream's
|
||||
maximum by the aggregate maximum before multiplication to avoid intermediate
|
||||
overflow. Partial confirmations and late members are represented by supplying
|
||||
updated observations to the next plan; asynchronous dispatch belongs to M3.
|
||||
Mute planning stores accepted per-stream intent so rapid toggles and overlapping
|
||||
targets compose. The future reducer must clear intent only after checking that
|
||||
an operation completion is current, or on removal/disconnect. Display state is
|
||||
always derived from observations.
|
||||
|
||||
Added dependencies were verified from their downloaded package manifests:
|
||||
`thiserror 2.0.21` requires Rust 1.77, `regex 1.13.1` requires 1.65, and the
|
||||
test-only `proptest 1.11.0` requires 1.85. Each offers MIT OR Apache-2.0 and
|
||||
requires no audio/MIDI development library. All compile on the pinned 1.88.0
|
||||
toolchain. Regex provides bounded compiled matching, thiserror implements typed
|
||||
library errors, and proptest exercises numerical invariants. Cargo.lock records
|
||||
the resolved versions; dependency versions are workspace-managed.
|
||||
|
||||
M2.1 adds `serde 1.0.229` (Rust 1.56) and `toml 0.8.23` / `toml_edit
|
||||
0.22.27` (Rust 1.66), each MIT OR Apache-2.0 with no native prerequisite.
|
||||
Serde defines strict data shapes and TOML supplies parsing and canonical
|
||||
serialization; the resolved `toml_edit` dependency will also underpin M2.2
|
||||
comment-preserving edits. These versions compile on the pinned Rust 1.88.0.
|
||||
|
||||
M2.2 directly uses `rustix 1.1.5` (Rust 1.65, Apache-2.0 WITH
|
||||
LLVM-exception OR Apache-2.0 OR MIT) for safe effective-user checks and
|
||||
`tempfile 3.27.0` (Rust 1.63, MIT OR Apache-2.0) for collision-safe
|
||||
same-directory temporary files. Neither adds a native system-library
|
||||
prerequisite, and both compile on the pinned toolchain.
|
||||
|
||||
M4 begins with `libpulse-binding 2.30.1` and `libpulse-sys 1.23.0`. Both
|
||||
declare Rust 1.63 and MIT OR Apache-2.0, compile on the pinned Rust 1.88.0,
|
||||
and require libpulse development files through pkg-config. The default
|
||||
compatibility feature targets PulseAudio 8 or newer. The adapter uses the
|
||||
asynchronous protocol API on an owned mainloop, deep-copies callback data, and
|
||||
converts software volumes through `VolumeLinear`; it does not parse `pactl`.
|
||||
|
||||
## Purpose and scope
|
||||
|
||||
Run a per-user Linux server that receives controls from multiple USB MIDI surfaces, records requested state, resolves virtual application/group targets, and dispatches volume/mute commands through one selected audio adapter. Observe external audio changes and send confirmed state to every relevant TUI and MIDI output.
|
||||
Run a per-user Linux server that receives controls from multiple USB MIDI surfaces, records requested state, resolves virtual application/group/default-output targets, and dispatches volume/mute commands through one selected audio adapter. Observe external audio changes and send confirmed state to every relevant TUI and MIDI output.
|
||||
|
||||
The MVP controls application playback streams, not microphone capture, routing, DSP, or audio samples. An application may have zero, one, or many streams. ALSA hardware mixer targets are an explicit extension, not a substitute for application control.
|
||||
The MVP controls application playback streams and the selected backend's default output sink, not microphone capture, routing, DSP, or audio samples. An application may have zero, one, or many streams. The output target follows the server's current default sink and remains distinct from ALSA hardware mixer elements, which are an explicit extension rather than a substitute for application control.
|
||||
|
||||
## Structure
|
||||
|
||||
|
|
@ -31,8 +112,8 @@ Only the server mutates domain state. Virtual objects resolve commands; they do
|
|||
|
||||
| Workspace location | Planned responsibility |
|
||||
| --- | --- |
|
||||
| New `core` directory, package `fader-core` | Pure domain types, target resolution, commands/events, reducer, audio adapter contract |
|
||||
| New `config` directory, package `fader-config` | TOML schemas, validation, migration, atomic persistence |
|
||||
| Existing `core` directory, package `fader-core` | Pure domain types and target resolution; commands/events, reducer and adapter contract follow in M3 |
|
||||
| Existing `config` directory, package `fader-config` | Empty boundary; TOML schemas, validation, migration, atomic persistence follow in M2 |
|
||||
| Existing `sound`, currently package `volume_lib` | Audio workers; `pulse`, `pipewire`, `alsa-mixer` features; fake adapter |
|
||||
| Existing `midi` | MIDI transport, parsing, device identity, bindings, feedback, pickup |
|
||||
| Existing `tui` | Mixer/editor/devices/status tabs and IPC client; no native audio access |
|
||||
|
|
@ -43,13 +124,104 @@ All outer crates depend inward on domain contracts; core depends on none of them
|
|||
## Domain model and matching
|
||||
|
||||
- `SurfaceId`, `FaderId`, `ApplicationId`, `GroupId`, and `ProfileId` are stable persisted user IDs. Renaming a display label preserves its ID.
|
||||
- A physical binding is `(surface ID, MIDI channel, message kind, control number) -> fader ID + action`. A logical fader targets exactly one `Application` or `Group` (later `HardwareMixer`). Several faders/surfaces may target the same object.
|
||||
- A physical binding is `(surface ID, MIDI channel, message kind, control number) -> fader ID + action`. A logical fader targets exactly one `Application`, `Group`, or the `default` output (later, an explicit `HardwareMixer`). Several faders/surfaces may target the same object.
|
||||
- An application object has selectors on explicit normalized fields: `application.name`, `application.id`, `application.process.binary`, or `media.name`. Preserve raw backend metadata for inspection. Never silently substitute one field for another.
|
||||
- Matchers are `exact` (case-sensitive whole-string equality) or `regex` (Rust regex syntax, substring search unless anchored). Multiple selectors for an application are ORed. Missing properties do not match. Compile patterns once at config validation, with length/complexity limits; show actual matches in the editor.
|
||||
- Matchers are `exact` (case-sensitive whole-string equality) or `regex` (Rust regex syntax, substring search unless anchored). Application `selector_mode` defaults to `any` (OR); `all` requires every selector (AND). Missing properties do not match. Empty lists and unknown modes are rejected. Compile patterns once at config validation, with length/complexity limits; show actual matches in the editor.
|
||||
- A matching application controls all its current playback streams. Stopped applications remain configured and display offline; new streams are discovered dynamically. Runtime handles include backend connection epoch plus object ID and an incarnation where needed to prevent ID-reuse bugs. PIDs, backend indices, and discovery order are never durable identity.
|
||||
- Groups reference application IDs only in v1; no nested groups or cycles. Overlapping selectors/groups are allowed: deduplicate resolved streams within each command and show overlap in the editor. Separate commands are serialized by server arrival order; the last accepted command touching a stream wins. Overlap is shared control, not multiple multiplicative gain layers.
|
||||
- Maintain requested state, observed per-stream/per-channel state, pending operation IDs, errors, and availability separately. A write acknowledgment means accepted by the adapter; success requires observation/readback. Derived objects can be `mixed`, `offline`, `pending`, or `partially failed`.
|
||||
|
||||
### Matching and media-control extensions
|
||||
|
||||
The agreed stretch-goal order is AND selectors and richer process metadata,
|
||||
then targeted MPRIS media controls (M13 in `task.md`). Selector composition is
|
||||
implemented in the domain/configuration layer and the fader editor's Match
|
||||
captures toggle (Any/OR or All/AND). Process metadata uses bounded Pulse-worker
|
||||
enrichment; MPRIS controls are implemented on the development branch after RC2.
|
||||
|
||||
The existing `media.name` regex `(?i) - YouTube$` is sufficient for YouTube
|
||||
streams whose reported title has that suffix. Do not couple this use case to
|
||||
browser identity, window-title concatenation, or the AND matcher.
|
||||
|
||||
AND composition must preserve the meaning of existing OR selector lists and
|
||||
keep field matching explicit, validated, and visible in the editor. Process
|
||||
enrichment belongs in an adapter, not the domain matcher: resolve available
|
||||
executable/working-directory and Steam launch metadata from the reported PID,
|
||||
with bounded reads, process-reuse checks, and unavailable values on failure.
|
||||
Read only relevant environment keys; do not expose entire environments or
|
||||
command lines in diagnostics. Steam IDs and launch context are evidence;
|
||||
`steamapps` paths are a fallback installation hint, not proof of launch origin.
|
||||
The implemented process fields are `application.process.executable`,
|
||||
`application.process.working_directory`, `steam.app_id` and `steam.game_id`.
|
||||
Pulse callbacks copy only reported PID/machine ID; enrichment runs afterward on
|
||||
the adapter worker. Require the reported machine ID to equal the local one,
|
||||
read start time before/after inspection, and discard values if the process
|
||||
changes or disappears. Reads are bounded (stat 4 KiB, environment 64 KiB), and
|
||||
only nonzero numeric SteamAppId/SteamGameId values leave the environment parser.
|
||||
Missing/oversized/inaccessible values remain absent; paths are not launch proof.
|
||||
Reported PIDs are best-effort hints, not authenticated identities; remote and
|
||||
namespace-restricted applications may be unavailable. No command lines or full
|
||||
environments enter diagnostics. The start-time check follows Linux
|
||||
[/proc/pid/stat](https://man7.org/linux/man-pages/man5/proc_pid_stat.5.html).
|
||||
|
||||
MPRIS controls address matched player instances over D-Bus using identity,
|
||||
desktop ID or bus-name selectors, with Play, Pause and PlayPause actions. Keep
|
||||
media-player discovery independent of active audio streams so paused players
|
||||
remain controllable. Extend MIDI learn, capability/state reporting and TUI
|
||||
editing through the server owner; use confirmed playback state for feedback.
|
||||
Resolve multiple matches explicitly rather than choosing an arbitrary player.
|
||||
This controls players such as QBZ directly, without synthetic keyboard input.
|
||||
The approved Media tab lists configured player/control sets with stable IDs,
|
||||
labels, explicit exact/regex selectors and observed state. Discovery supplies a
|
||||
picker without a builtin player catalogue; manual selectors remain available.
|
||||
Multiple matches are ambiguous and block commands. The server advertises session
|
||||
bus availability to the client: no running players is an empty list, not a reason
|
||||
to hide the tab; a later disconnect retains the tab with an unavailable status.
|
||||
The scope includes Stop/Next/Previous, relative and absolute seeking, shuffle,
|
||||
repeat and playlist discovery/activation, gated by player capabilities. Playlist
|
||||
content editing is not included. Learn/unbind, validated editing and persisted
|
||||
configuration follow the mixer conventions.
|
||||
Feedback uses confirmed state, with exclusive Play/Pause/Stop indicators and
|
||||
explicit device-specific colour mappings; default note output is same-note 127/0.
|
||||
Global and per-fader/per-media-entry switches gate MIDI output. Global off sends
|
||||
no messages (even clearing messages), so existing lights may remain lit until
|
||||
feedback is re-enabled and resynchronized. Save activates feedback-gate changes.
|
||||
Global and per-fader gates now use `feedback_enabled` (default true) at root and
|
||||
fader-table scope, applied on configuration Save, including explicit mappings.
|
||||
The protocol boundary follows the
|
||||
[MPRIS Player interface](https://specifications.freedesktop.org/mpris/latest/Player_Interface.html).
|
||||
|
||||
The hardware-free `media` crate defines player selectors, capability-aware
|
||||
actions, observed playback state, configuration entries and MIDI feedback rules.
|
||||
`[[media]]` entries have stable IDs, labels, a selector, a default-enabled feedback
|
||||
gate, and controls with stable IDs/actions/optional bindings. Configuration
|
||||
validates selectors, limits, references and input collisions with mixer bindings
|
||||
before activation. Entry editing is transactional; removing a surface unbinds its
|
||||
media controls without deleting entries. The live server routes media MIDI press
|
||||
edges through the bounded worker and exposes discovery, capabilities and state
|
||||
over IPC. The optional Media tab edits draft entries and controls; Save activates
|
||||
them. Learn/unbind is scoped to a selected control and surface. Media commands
|
||||
are not retried by the client after ambiguous transport failures.
|
||||
IPC frames are limited to 1 MiB (oversized lengths are rejected before allocation).
|
||||
Media configuration and discovery each have a 256 KiB serialized budget, so a
|
||||
256-playlist response does not exceed the previous 64 KiB frame limit. Discovery
|
||||
fails closed instead of publishing an incomplete set that could hide ambiguity.
|
||||
|
||||
The MPRIS adapter uses pinned `dbus` 0.9.12 (MIT/Apache-2.0) and system
|
||||
libdbus-1; its upstream manifest does not declare an MSRV, so compatibility is
|
||||
verified by building with the repository's Rust 1.88 toolchain. A dedicated
|
||||
joined thread owns the blocking connection. Calls have 200 ms timeouts, polling
|
||||
uses 250 ms intervals, and the command queue holds at most 32 requests. Discovery
|
||||
limits player count to 32 and lists the first 256 playlist choices per player.
|
||||
Exhausted player-discovery bounds fail closed rather than selecting from an
|
||||
incomplete player set. Polling (rather than signal subscriptions) also observes
|
||||
external playback/capability changes and replacement owners; it trades a bounded
|
||||
delay and extra reads for a small, recoverable worker without a second event loop.
|
||||
Commands resolve a fresh snapshot and address a unique bus owner, not a reusable
|
||||
well-known name; feedback comes only from readback. Missing optional properties
|
||||
remain unavailable. Connection failure triggers reconnect; configuration
|
||||
activation fences queued and in-flight work before replacing the active profile.
|
||||
|
||||
## Volume and mute semantics
|
||||
|
||||
The core stores finite, non-negative linear amplitude gain; `1.0` is unity, `0.0` is silence. Adapters convert native representations explicitly; PulseAudio volume numbers and PipeWire linear gain must not be treated as interchangeable percentages. Preserve per-channel balance by scaling channel gains relative to their maximum. If all channels are zero, an explicit nonzero command initializes them equally. Tests cover silence, clipping, NaN/infinity rejection, and round trips.
|
||||
|
|
@ -58,14 +230,30 @@ The initial physical fader curve maps its normalized position linearly to gain i
|
|||
|
||||
For an application or group, display maximum member stream gain as the aggregate fader position plus a mixed indicator when gains differ. Display mute as `all-muted`, `all-unmuted`, `mixed`, or `unavailable`. A toggle mutes all when any member is unmuted; otherwise it unmutes all. Unmute leaves volumes untouched and clears mute on all members, including independently muted members; there is no hidden pre-group mute restore in v1.
|
||||
|
||||
Support two explicit group volume modes:
|
||||
Recognize two group volume models, but enable only sync groups in the current
|
||||
runtime:
|
||||
|
||||
1. `absolute` (default): a move to `g` sets each resolved stream's scalar gain to `g`, preserving each stream's channel balance. This is predictable for absolute USB faders.
|
||||
2. `relative`: derive `g / old_max` from the latest member snapshot and scale members together, preserving relative gains until a limit clips. If `old_max == 0`, set all to `g`. External edits rebase the next move. A move to zero loses cross-stream ratios; recovery uses the defined equal-gain fallback. Document this in the editor.
|
||||
1. `absolute` (also called **sync**, current default and only accepted profile
|
||||
mode): a move to `g` sets each resolved stream's scalar gain to `g`,
|
||||
preserving each stream's channel balance. This is predictable for absolute
|
||||
USB faders.
|
||||
2. `relative` (reserved): each member remembers the channel vector from its
|
||||
last independent application-fader or external edit as that member's
|
||||
maximum. A normalized group position `p` scales the member between silence
|
||||
and that maximum (`p * member_max`), preserving channel balance. A group
|
||||
write or its confirmation never rebases the remembered maximum; a later
|
||||
independent/external edit rebases only that member. Moving to zero therefore
|
||||
remains reversible. Newly resolved members adopt their live state as their
|
||||
initial maximum, and removed members lose their anchor.
|
||||
|
||||
The pure domain planner for the reserved relative model exists and is tested,
|
||||
but profile validation rejects `volume_mode = "relative"` until the runtime can
|
||||
track write origin and lifecycle for those anchors. Examples and live routing
|
||||
use `volume_mode = "absolute"` only.
|
||||
|
||||
Group dispatch is best effort because audio APIs do not offer a transaction across arbitrary streams. Track results per stream, keep successful changes, show failures, and refresh observations. Do not pretend to roll back atomically. Backend workers preserve server write ordering per stream and per property; volume and mute can be tracked independently.
|
||||
|
||||
Default startup, reconnect, profile switching, and new-stream discovery adopt live state without writes. A deliberate command while an application is offline stores pending intent for display but is not replayed on launch by default. An explicit `restore` policy may apply saved object intents to newly matched streams after full discovery, with validated bounds and visible status; conflicting restored targets use documented profile order, last matching target wins. Persist that order and test it. Never resurrect backend handles or pending operation IDs from disk.
|
||||
Default startup, reconnect, profile switching, and new-stream discovery adopt live state without writes. Live MIDI/TUI input against an offline or read-only target is a visible, nonfatal no-op and is never replayed when the target appears. A future explicit saved-intent workflow may retain a deliberate offline command for display, but only an explicit `restore` policy may apply saved object intents to newly matched streams after full discovery, with validated bounds and visible status; conflicting restored targets use documented profile order, last matching target wins. Persist that order and test it. Never resurrect backend handles or pending operation IDs from disk.
|
||||
|
||||
## Server state transitions and concurrency
|
||||
|
||||
|
|
@ -79,8 +267,24 @@ Use a Tokio event task as the single domain owner. MIDI, IPC, persistence, and a
|
|||
|
||||
PulseAudio and native PipeWire event loops run on their own owner threads. In particular, PipeWire Rust objects are not generally Send/Sync; transfer commands and copied data, not handles. [PipeWire Rust threading documentation](https://pipewire.pages.freedesktop.org/pipewire-rs/pipewire/index.html)
|
||||
|
||||
Pulse subscription notifications caused by the server's own confirmed writes
|
||||
retain their originating operation when their copied volume/mute state matches
|
||||
the expected echo. They remain observations, but must not masquerade as
|
||||
external edits and repeatedly re-arm a non-motorized fader during motion. A
|
||||
different observed state clears the echo expectation and remains an external
|
||||
change that re-arms pickup.
|
||||
|
||||
Use bounded `mpsc` for ordered work and `watch` for latest display snapshots. Keep button edges and lifecycle events separate from coalescible fader motion. A MIDI callback only parses/copies bounded input and tries to enqueue; on overflow set an explicit fault/resync flag rather than silently losing mute edges. A dropped button edge cannot be reconstructed from an audio snapshot: report the fault and require a new user press, never guess a toggle. Dedicate output workers to rate-limited MIDI feedback. [Tokio synchronization primitives](https://docs.rs/tokio/latest/tokio/sync/index.html)
|
||||
|
||||
The production audio dispatcher retains a bounded server-owned queue in front
|
||||
of a one-slot native worker **command** lane. Its independent event lane remains
|
||||
large enough for a complete startup snapshot; command backpressure must never
|
||||
shrink snapshot capacity. Replace unsent volume commands for the same stream
|
||||
with their newest value and explicitly supersede the older operation; never
|
||||
coalesce mute edges. A full non-coalescible queue or event lane is a visible
|
||||
fault, not permission to drop an action. Drain copied worker events in batches
|
||||
so native round-trip latency cannot starve MIDI input or local clients.
|
||||
|
||||
On shutdown stop accepting commands, stop callbacks, drain with deadlines, checkpoint confirmed state, close native connections, and join workers. Reconnect with bounded exponential backoff and cancellation; resnapshot before accepting writes. Keep other surfaces working when one disconnects. Stale backend/config generations cannot update current state.
|
||||
|
||||
## Audio adapter selection and contract
|
||||
|
|
@ -91,7 +295,7 @@ Subscribe before enumeration, buffer intervening events, and reconcile using an
|
|||
|
||||
| Adapter | Scope and selection |
|
||||
| --- | --- |
|
||||
| `pulse` | First implementation. Enumerate playback sink inputs, read properties/channel volumes/mute, change volume/mute, subscribe to changes. Supports PulseAudio and PipeWire's PulseAudio-compatible service. Native PipeWire-only stream coverage needs explicit testing; do not claim completeness. |
|
||||
| `pulse` | First implementation. Enumerate playback sink inputs plus the current default output sink; read channel volumes/mute, change them, and subscribe to both stream and default-output changes. Supports PulseAudio and PipeWire's PulseAudio-compatible service. Native PipeWire-only stream coverage needs explicit testing; do not claim completeness. |
|
||||
| `pipewire` | Native playback stream discovery and SPA parameter control/observation. Implement after a spike proves writable parameters, correct linear gain/mute handling, metadata, and reconnect behavior with the active session manager. |
|
||||
| `alsa-mixer` | Optional explicit hardware mixer targets only; report playback switch/mute support per element. Reject application/group targets requiring application discovery. Never silently fall back to system Master volume. |
|
||||
|
||||
|
|
@ -103,14 +307,35 @@ PulseAudio compatibility is provided by `pipewire-pulse`; ALSA's mixer API expos
|
|||
|
||||
Use `midir` for input/output connections. A device profile maps CC/note/pitch-bend messages to controls and output messages; v1 supports 7-bit absolute CC and note/CC mute buttons, then 14-bit pairs, pitch bend, and declared relative encoder dialects. Channel values in TOML are 1–16 and translate once at the transport boundary. Note-on velocity zero is release. Toggle actions fire on press only; validate malformed lengths and data bytes. Ignore unrelated clock/active-sensing traffic; arbitrary SysEx protocols are deferred.
|
||||
|
||||
Persist a user surface ID plus matching hints: backend port identifier where usable, input/output port names, USB VID/PID, serial when available, and optional physical path. MIDI port indices and names alone are not durable identity. Linux identity enrichment may require ALSA sequencer-to-device mapping and udev; verify this bridge in a spike, since midir alone does not guarantee USB serial metadata. Identical serial-less devices cannot always be distinguished after moving USB ports: require explicit assignment when ambiguous and retain a disconnected placeholder rather than binding arbitrarily.
|
||||
Persist a user surface ID plus matching hints: backend port identifier where usable, input/output port names, USB VID/PID, serial when available, and optional physical path. MIDI port indices and names alone are not durable identity. On Linux, bridge midir's ALSA `client:port` through the sequencer client's card number to the udev `sound/cardN` device; user/virtual clients legitimately have no card. Match USB devices by serial first, physical `ID_PATH` second, and unique VID/PID/port-name last. Identical serial-less devices without a retained path require explicit current-port assignment and remain unresolved when ambiguous after topology changes. See the [identity spike](docs/midi-identity.md).
|
||||
|
||||
Keep bindings for absent surfaces. Re-enumerate ports on hotplug notifications or a bounded periodic scan, reconnect matching input/output ports independently, and resynchronize output from current observed state. Missing output does not disable input. Two devices may send the same channel/CC without collision because the surface ID is part of the key. [midir input/connection API](https://docs.rs/midir/latest/midir/struct.MidiInput.html), [udev discovery/monitoring](https://docs.rs/udev/latest/udev/)
|
||||
|
||||
Output capabilities are explicit: mute LED, value display, motorized fader, or none. Non-motorized devices may still receive supported LED/display feedback; never assume every surface has LEDs. Mixed mute uses a declared mixed indicator, otherwise LED on only for all-muted and the TUI shows mixed. Send full supported state on attach and incremental changes thereafter. Device feedback failures are separate from audio operation failures.
|
||||
Note-based mute bindings default to same-note feedback when an output port is configured. Other output capabilities (CC LEDs, value displays, motors) require explicit configuration. Mixed mute uses a declared mixed indicator, otherwise LED on only for all-muted and the TUI shows mixed. Send full supported state on attach and incremental changes thereafter. Device feedback failures are separate from audio operation failures.
|
||||
|
||||
The first implemented output slice is binding-level mute feedback. A binding
|
||||
with `feedback` sends its declared note or CC `on` value only for a uniformly
|
||||
confirmed muted target, sends `off` for uniformly unmuted or mixed state, and
|
||||
sends nothing for an unavailable target. Successful messages are deduplicated;
|
||||
an independently reconnected output invalidates that cache and receives a full
|
||||
current refresh. Pending intent is never treated as confirmation.
|
||||
When learning a new mute binding, the editor may copy `on`/`off` values only
|
||||
from an unambiguous convention already used by feedback of the same message kind
|
||||
on that surface; the new feedback address follows the learned control. Missing
|
||||
or conflicting conventions leave the explicit mapping absent. The runtime
|
||||
defaults every note-based mute binding to its input channel and note, with
|
||||
on=127/off=0, when its surface has an output port. No device identity or note
|
||||
whitelist is required. Explicit `feedback` settings override kind, channel,
|
||||
number, and on/off values for alternate device protocols. CC input bindings
|
||||
still require explicit feedback. Defaults are resolved without rewriting TOML
|
||||
and reflect confirmed mute state, not an immediate echo of every input event.
|
||||
|
||||
Non-motorized absolute controls default to pickup: after startup, external changes, another surface's move, or profile switch, wait until the physical value crosses or enters a configured tolerance around the observed target before sending volume commands. First input establishes position; an out-of-range external volume uses the nearest physical endpoint. Relative encoders do not need pickup. Reset pickup on disconnect/rebind. For motors, add touch-aware inhibition before enabling motor output; unsupported touch means no claimed touch protection.
|
||||
|
||||
At startup, apply already-queued audio snapshot events before MIDI messages
|
||||
collected in the same server turn. This gives pickup a live target for the
|
||||
controller's first sweep without replaying input or issuing a startup write.
|
||||
|
||||
Avoid feedback loops with direction/origin tracking, quantization-aware equality, rate limiting, and device-specific echo suppression. MIDI has no universal request IDs: generic time-window byte suppression can swallow real input, so only enable it for documented echoing device profiles and test it. Server observations never themselves generate audio commands.
|
||||
|
||||
## TOML configuration, persistence, and switching
|
||||
|
|
@ -122,7 +347,18 @@ All durable application data is TOML: profiles, device profiles/bindings, active
|
|||
- `~/.config/fader_master/devices/<id>.toml`: reusable MIDI output/input protocol profiles when needed.
|
||||
- `~/.local/state/fader_master/state.toml`: schema version, per-profile confirmed object/channel state and separately validated desired object volume/mute, remembered assignments, last selected UI view. No ephemeral backend handles or pending operation IDs; cached observations are marked stale until refreshed. Desired values may include commands issued offline, but are applied after restart only under explicit restore policy.
|
||||
|
||||
The following proposed profile is syntactically valid TOML, not a claim that a parser is implemented. Sample application and MIDI names must be selected from actual discovery. CLI overrides apply for the session; persist them only on explicit Save.
|
||||
When no explicit profile path is supplied, a missing active selection creates a
|
||||
safe `default` profile with a pickup-enabled default-output fader before
|
||||
atomically publishing its active pointer. This provides a useful keyboard mixer
|
||||
and a target for MIDI Learn without guessing application identities. A
|
||||
missing profile named by an existing valid active pointer is initialized with
|
||||
that stable ID. Existing files, malformed selections, and explicit missing
|
||||
paths are never overwritten by this first-run recovery.
|
||||
|
||||
The following profile is parsed and semantically validated by an automated test
|
||||
and mirrored at `examples/profiles/desktop.toml`. Sample application and MIDI
|
||||
names must still be selected from actual discovery. CLI overrides apply for the
|
||||
session; persist them only on explicit Save.
|
||||
|
||||
```toml
|
||||
schema_version = 1
|
||||
|
|
@ -130,6 +366,14 @@ id = "desktop"
|
|||
startup = "adopt"
|
||||
new_stream = "adopt"
|
||||
|
||||
[ui]
|
||||
default_controller = "desk-left"
|
||||
theme = "default"
|
||||
status_display = "detailed"
|
||||
|
||||
[runtime]
|
||||
poll_interval_ms = 10
|
||||
|
||||
[audio]
|
||||
adapter = "auto"
|
||||
preference = ["pulse", "pipewire"]
|
||||
|
|
@ -180,21 +424,309 @@ message = { kind = "note", channel = 1, number = 32 }
|
|||
feedback = { kind = "note", channel = 1, number = 32, on = 127, off = 0 }
|
||||
```
|
||||
|
||||
`runtime.poll_interval_ms` controls how long both the server state owner and the
|
||||
native audio worker may wait between MIDI/IPC/command/notification polls. It
|
||||
defaults to 10 ms when omitted and is validated within `1..=100`. Lower values
|
||||
can reduce worst-case control latency at the cost of more wake-ups; higher
|
||||
values reduce wake-ups but make physical control and external-state updates less
|
||||
responsive. It does not change the bounded coalescing policy or cause every
|
||||
intermediate fader sample to be written.
|
||||
|
||||
Reject unknown schema versions/fields, duplicate IDs/physical bindings, dangling references, invalid matchers/ranges, unsupported capability requirements, and unsafe profile paths. Use forward migrations with backups; never downgrade silently. Validate the whole candidate before changing live mappings or files.
|
||||
|
||||
Write same-directory temporary files, flush/fsync, rename atomically, then sync the directory. Debounce state writes (initial target: 500 ms after changes, maximum 2 s between dirty checkpoints), flush on orderly shutdown, and document the corresponding crash-loss window. Permission/disk-full errors leave the old file usable and show an unsaved state. Preserve user comments in profile edits with `toml_edit`. The server is the sole writer; TUI edits carry a base revision and conflict if stale. Detect out-of-process file edits before saving rather than overwriting them.
|
||||
|
||||
Editor mutations are first applied to a cloned, comment-preserving document and
|
||||
the complete candidate profile is semantically validated before the draft is
|
||||
replaced. Invalid matchers, duplicate IDs, and referenced deletes therefore
|
||||
leave the prior draft unchanged. The v1 editor creates absolute groups; relative
|
||||
group controls remain a reserved future mode. Schema arrays that default empty,
|
||||
including bindings, applications, groups, and faders, may be omitted from valid
|
||||
TOML; creation edits materialize them lazily and removal from an omitted empty
|
||||
array is a no-op. A present malformed section is rejected during startup.
|
||||
|
||||
The live mixer revision and configuration-draft revision are independent.
|
||||
The public mixer revision also includes a routing-generation offset advanced
|
||||
on Save/reset/profile switch, while the audio reducer keeps its own revision.
|
||||
Validate public revisions only at the external client request boundary. MIDI
|
||||
intents run synchronously under the server's state owner against current routing
|
||||
and must not pass reducer revisions to that check. Mixing these revisions made
|
||||
every MIDI volume/mute action fail after reconfiguration, propagating a stale
|
||||
revision error out of the server loop. Genuine stale client requests still
|
||||
resnapshot and retry; they must not bypass the public revision check.
|
||||
Draft edits are serialized by the server, require the caller's expected draft
|
||||
revision, and never mutate live routing or audio as a side effect. Successful
|
||||
draft edits are explicitly marked unsaved until a later Save command. A layout
|
||||
move names one stable entry and an absolute destination, so the server may
|
||||
rebase that operation onto a newer shared draft instead of flashing the
|
||||
optimistic order and rejecting it solely because another draft edit landed.
|
||||
|
||||
MIDI learn is scoped to one configured surface, logical fader, and action. While
|
||||
armed, messages from that surface are withheld from normal routing; unrelated
|
||||
surfaces continue normally. The first compatible CC or note press becomes a
|
||||
validated draft binding, while cancellation restores routing immediately.
|
||||
|
||||
Save is the only editor commit action. It first validates and prepares the
|
||||
profile-derived matching, groups, faders, pickup, and MIDI routing, compares the
|
||||
exact on-disk bytes with the server's load/save baseline, and uses the atomic
|
||||
writer. Save commits the server's latest validated shared draft even when the
|
||||
requester's displayed revision is older; a future revision remains invalid.
|
||||
After persistence succeeds, the server activates the prepared routing
|
||||
while retaining confirmed audio observations and issuing no audio write.
|
||||
Conflicts or persistence failures retain the previous file, live configuration,
|
||||
and dirty draft.
|
||||
|
||||
The implemented atomic writer checks that its parent and any existing target
|
||||
are owned by the effective user and are not symlinks. It creates mode-`0600`
|
||||
temporary files in the destination directory, streams and syncs their content,
|
||||
renames over the destination, and syncs the parent directory. Application
|
||||
directories are mode `0700`. Missing state and malformed readable state are
|
||||
distinct recoverable load outcomes; malformed bytes are retained for diagnosis.
|
||||
Profile migration accepts only versions below the current schema, validates the
|
||||
replacement first, and durably backs up the original bytes before replacement.
|
||||
Server startup invokes the registered migration for pre-versioned/schema-0
|
||||
profiles, preserving TOML comments and reporting the `.v0.bak` path. A malformed
|
||||
document, invalid migrated candidate, unknown future schema, or existing backup
|
||||
aborts without replacing the profile. Validation-only commands never migrate.
|
||||
Checkpoint changes are written after 500 ms without another change and at least
|
||||
every two seconds during sustained input, then flushed once more on orderly
|
||||
shutdown. A process or machine crash can therefore lose up to the latest
|
||||
unflushed interval; atomic replacement protects the preceding checkpoint.
|
||||
Revision conflict handling belongs to the server/editor boundary in M9.3.
|
||||
|
||||
Profile switch: parse/validate candidate, prepare/probe required resources without writes, pause input briefly, drain old writes with a deadline, obtain fresh state, then commit a new config generation and publish bindings/feedback together. Abort on prepare failure and retain the old profile. If an old in-flight call cannot be safely drained, close/reconnect and reconcile before activation; generation tags alone do not cancel native writes. In-flight group membership is fixed at command acceptance. Re-arm pickup, invalidate stale queued commands, and adopt live volumes by default. Persist the active profile pointer only after successful activation; disk failure leaves the active runtime profile clearly marked unsaved. Durable crash-atomic multi-file transactions are not claimed.
|
||||
|
||||
The Pulse implementation accepts a profile switch only when its bounded dispatch
|
||||
queue and published objects have no pending operation. A busy switch is rejected
|
||||
for retry after readback/reconciliation rather than publishing over in-flight
|
||||
native work. The committed mapping generation advances the public mixer revision,
|
||||
invalidating commands created from the prior profile.
|
||||
|
||||
The active pointer is a strict versioned TOML document containing one validated
|
||||
profile ID. A successful runtime switch writes it atomically after activation.
|
||||
Failure does not roll back the running generation, but marks the selection
|
||||
unsaved; startup without `--config` accepts only this pointer and never guesses
|
||||
another profile when it is absent or corrupt.
|
||||
|
||||
Profile switching adopts confirmed live state unless the caller explicitly
|
||||
requests restore. Explicit restore validates the selected profile's saved
|
||||
desired values and gain ceiling before activation, applies online application
|
||||
intents in profile order, and retains offline intents only when the candidate's
|
||||
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.
|
||||
|
||||
TUI tabs:
|
||||
Configuration snapshots include the valid sibling profile IDs discovered by
|
||||
the server. The Config view presents them in a modal selector and requests the
|
||||
same adopt-mode transactional switch as `profile switch ID`; invalid profile
|
||||
documents are not advertised, and activation errors retain the current profile.
|
||||
|
||||
- **Mixer:** faders, resolved applications/streams, volume, mute, mixed/offline/pending/errors, pickup status.
|
||||
- **Editor:** create/edit/delete application selectors, groups, faders, surface bindings, and MIDI learn; preview matches and conflicts. Draft changes do not affect audio; Validate, Apply, Save, Cancel are distinct. Referenced deletion requires reassignment or explicit cascade confirmation in the UI.
|
||||
- **Devices / status:** MIDI assignments and ambiguity resolution, manual/auto backend choice, capability/probe errors, active profile and persistence errors.
|
||||
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
|
||||
work without waiting for a socket response. Pending volume work is
|
||||
latest-value-per-object; mute presses remain a bounded FIFO. Confirmed snapshots
|
||||
replace the local base and retain optimistic overlays until observation settles
|
||||
them. Poll quickly while writes are pending, slowly while idle, and resnapshot
|
||||
then retry a bounded number of times after stale mutations so consecutive
|
||||
server revisions cannot roll an optimistic edit back. Revision conflicts are
|
||||
recognized from their protocol message rather than a transport-specific I/O
|
||||
kind and are presented as recoverable warnings. Start immediately with a
|
||||
disconnected placeholder when the socket is absent, retain the last confirmed items across
|
||||
transport failures, surface the connection error inside the terminal, and keep
|
||||
retrying so starting or restarting the server reconnects without restarting the
|
||||
TUI.
|
||||
|
||||
Quit and terminal restoration are local operations. Terminal state is restored
|
||||
before client teardown; teardown requests worker cancellation and joins within a
|
||||
short grace period, but detaches a worker whose in-flight server request remains
|
||||
wedged. That worker exits after the request returns and observes cancellation,
|
||||
so a crashed or hung server can never trap the terminal in raw mode.
|
||||
|
||||
Mixer-object snapshots also aggregate pickup state across configured physical
|
||||
volume bindings. They expose `unavailable`, `waiting`, `tracking`, or `mixed`;
|
||||
controls are instantiated from the profile before discovery so the first live
|
||||
observation can arm them without waiting for an initial MIDI packet.
|
||||
|
||||
The same client snapshot retains configured MIDI-device placeholders and their
|
||||
backend IDs/errors. The compact mixer status line distinguishes connected,
|
||||
connecting, missing, ambiguous, and failed devices, adding a connect/select
|
||||
action where the user can resolve the state.
|
||||
|
||||
Unclaimed MIDI input ports are also published with their current backend ID,
|
||||
stable port name, and available USB identity. Config can add one as a durable
|
||||
surface draft; the first added surface becomes the default controller, and Save
|
||||
rebuilds the MIDI runtime before Learn is enabled. On creation of a missing
|
||||
managed profile, exactly one discovered input is adopted automatically. No
|
||||
choice is guessed when discovery returns zero or multiple inputs.
|
||||
|
||||
Terminal restoration is guarded around all fallible client/run work after
|
||||
terminal initialization. The restore action is injectable for failure-path
|
||||
tests; client and transport diagnostics stay in the rendered status area rather
|
||||
than being printed over the alternate screen.
|
||||
|
||||
Terminal colors come from semantic theme palettes rather than renderer-local
|
||||
literals. The built-ins are Default, Dracula, Nord, Gruvbox Dark, Catppuccin
|
||||
Mocha, and Solarized Dark. `ui.theme` stores the profile palette, `t` cycles its
|
||||
draft value, and Save persists it. `tui --theme NAME` remains a session-only
|
||||
startup override. Theme selection never changes audio. Each palette defines
|
||||
background, foreground, accent/selection, secondary meter, muted, warning,
|
||||
error, and meter track colors so status meaning remains consistent across
|
||||
themes.
|
||||
|
||||
`ui.status_display` controls pickup feedback without changing pickup behavior.
|
||||
The persisted modes are `detailed` (`pickup: tracking`), `compact` (`LIVE`),
|
||||
`symbol` (a state-specific Unicode glyph), `color` (one fixed glyph using the
|
||||
semantic status color), and `hidden` (no pickup indicator). Detailed is the
|
||||
backward-compatible default. Both mixer orientations use the same mapping;
|
||||
horizontal mode reserves the pickup footer row even when the indicator is
|
||||
hidden or the fader has no MIDI assignment, keeping every meter the same height.
|
||||
|
||||
The TUI is mixer-first rather than exposing the profile's normalized tables as
|
||||
separate tabs. Its main list is an ordered presentation of logical faders and
|
||||
named separators. A layout entry references a stable fader ID or defines a
|
||||
stable separator ID and label. Fader entries retain their position while
|
||||
hidden; hiding is presentation-only and never deletes the target, selectors,
|
||||
MIDI bindings, or saved state. Profiles without an explicit layout synthesize
|
||||
one visible entry for every declared fader in declaration order. Validation
|
||||
rejects duplicate layout IDs, duplicate fader references, and dangling fader
|
||||
references. Each fader layout entry also stores a `slim`, `standard`, or `thick`
|
||||
density. Layout moves and separator insertion normalize the TOML tables' source
|
||||
positions to a shared layout anchor before serialization. Parsed tables retain
|
||||
their old source positions, so vector order alone does not survive serialization;
|
||||
the normalized anchor preserves the requested order and each entry's comments
|
||||
across Save and server restart.
|
||||
Omitted density defaults to `standard` for existing profiles. Vertical
|
||||
mode keeps the stacked card layout: Slim is a single terminal row while the
|
||||
other sizes retain progressively more detail. Horizontal mode uses side-by-side
|
||||
console-style fader strips with bottom-up meters, state, percentage, pickup
|
||||
status when enabled, and a label at the bottom; density controls strip width.
|
||||
Horizontal separators are labeled inline divider columns so every layout entry
|
||||
stays in a single row, with the selected entry kept inside the width-bounded viewport.
|
||||
Vertical separators remain full-width rows between stacked cards.
|
||||
Arrow-key controls follow that spatial model: vertical mode selects entries
|
||||
with Up/Down and changes volume with Left/Right, while horizontal mode selects
|
||||
with Left/Right and changes volume with Up/Down. Holding Shift reorders entries
|
||||
along the active selection axis; J/K remain orientation-independent selection
|
||||
aliases, and Shift+J/K provides an orientation-independent reorder path for
|
||||
terminals that do not distinguish Shift+Arrow.
|
||||
Lowercase `h` and `?` open an orientation-aware keyboard-help popup with mixer,
|
||||
configuration, and global controls. Hiding is deliberately assigned to Shift+H
|
||||
so the common help key does not perform a destructive presentation edit.
|
||||
The always-visible quick-help footer omits intuitive navigation, volume, and
|
||||
alternative bindings; it keeps compact non-obvious actions with Add, Edit, and
|
||||
Delete shown separately. The detailed popup documents J/K, `?`, and Home/End.
|
||||
|
||||
The selected main-list entry can be moved directly. `A` opens a chooser for an
|
||||
application fader, group, or separator. Creating an application fader adds its
|
||||
application target with a deliberately non-matching exact selector, while a new
|
||||
group starts empty in absolute mode; both operations add a visible layout entry
|
||||
and open the field-oriented fader editor. Because draft targets do not exist in
|
||||
the active runtime yet, the TUI synthesizes a non-writable `DRAFT` row labeled
|
||||
"save to activate" until Save publishes the real online or offline object. `D`
|
||||
confirms removal of either a separator or a fader with its bindings and layout
|
||||
entry. A fader's application or group target is also removed when no other fader
|
||||
owns it; applications still referenced by a group are retained. These compound
|
||||
edits validate and publish as one draft transaction, so no dangling intermediate
|
||||
configuration is observable.
|
||||
The draft must still be saved before it becomes active.
|
||||
|
||||
A centered separator dialog edits its name, size, and decoration. Names may be
|
||||
empty; the stable ID still identifies each separator. Plain with
|
||||
an empty name creates a spacer, and an unnamed Line/Double separator draws an
|
||||
unbroken rule. Separator size is independent of fader density:
|
||||
`slim`, `standard` (default), `thick`, or `fill`. Size controls height in the
|
||||
stacked layout and width in the side-by-side layout. Decorations are `plain`,
|
||||
`line` (default), `double`, or `box`. A slim stacked separator occupies one
|
||||
row, or three for a box. Viewports fit entries using their minimum extents
|
||||
before distributing remaining space evenly among visible Fill separators;
|
||||
expansion never evicts a fader or wraps the horizontal row. Editing a fader
|
||||
presents domain fields rather than a serialized command:
|
||||
|
||||
- **Name:** rename the application or group display label while retaining its
|
||||
stable target and fader IDs. Default-output labels remain backend-owned.
|
||||
- **Capture:** application selector field, exact/regex mode, and pattern. Pattern
|
||||
values open in a cursor-aware modal with insertion, Backspace, Delete,
|
||||
Home/End, accept, and cancel controls; group faders instead present a member
|
||||
summary that opens a multi-select popup, plus the currently available group
|
||||
mode.
|
||||
Capture also has a Save and exit row to submit field/mode changes without
|
||||
reopening Pattern. Both submission paths validate the current selector using
|
||||
the domain's bounded exact/regex rules before queueing the draft edit; invalid
|
||||
input retains the form and an inline error. Configuration Save remains the
|
||||
separate persistence/activation operation.
|
||||
- **Volume control:** controller selection and Learn MIDI. The learn prompt
|
||||
offers `U` to unbind the current volume assignment and `Esc` to cancel.
|
||||
- **Mute control:** controller selection and Learn MIDI, with the same prompt
|
||||
shortcuts scoped to the mute assignment. Unbinding cancels capture first,
|
||||
preserves the other action, and retains the selected controller for relearning.
|
||||
- **Size:** Slim, Bordered slim, Standard, or Thick vertical presentation for
|
||||
this fader.
|
||||
- **Visibility:** Hide from mixer or Show in mixer without changing routing.
|
||||
|
||||
Groups select application-targeting faders in a checked multi-select popup; the
|
||||
server stores their deduplicated application IDs because group membership is an
|
||||
audio-domain relationship, not a dependency on a particular physical control.
|
||||
The popup shows this translation and prevents group or output faders from being
|
||||
chosen as members. Absolute remains the only selectable group mode until the
|
||||
reserved relative-mode runtime work is complete.
|
||||
|
||||
The secondary Config tab is not an alternative object editor. It presents
|
||||
profile theme, mixer orientation and pickup-status selection, a popup listing
|
||||
all hidden faders for individual restoration, unsaved and Save state, active
|
||||
profile/backend status, the server-resolved loaded configuration path, MIDI-learn
|
||||
cancellation, and MIDI device diagnostics. Object and layout edits stay on the
|
||||
main mixer. Its quick-help footer calls out Left/Right layout switching
|
||||
alongside Save and navigation. There is no separate hidden-fader mode: hidden
|
||||
rows disappear from the mixer and are restored from this popup at their retained
|
||||
layout positions.
|
||||
MIDI devices are selectable settings rows. Their details popup shows stable and
|
||||
backend identity, connection status, and errors, and sets or clears the same
|
||||
profile-backed default controller used by MIDI learn. Removing a device is a
|
||||
confirmed draft edit that atomically removes its surface, bindings, and any
|
||||
default-controller reference; the running MIDI topology changes on Save.
|
||||
|
||||
Config also exposes a confirmed emergency reset for the active profile. The
|
||||
server, never the TUI process, preserves the current on-disk bytes beside the
|
||||
profile as `<profile>.toml.reset.bak`, atomically replaces the profile with the
|
||||
safe default-output configuration, and activates it without issuing audio writes.
|
||||
The reset clears drafts, routing, MIDI assignments, and presentation settings,
|
||||
while retaining process-level runtime timing that cannot change under a live
|
||||
native worker. It does not delete sibling profiles, the active-profile pointer,
|
||||
or checkpoint state.
|
||||
|
||||
Every value presented as configuration is read from the server-owned validated
|
||||
profile draft and every edit targets that same profile field. The TUI must not
|
||||
invent parallel configuration defaults or overwrite unrelated fields; local
|
||||
state is limited to clearly transient navigation and presentation choices such
|
||||
as selection, open dialogs, and an explicit CLI theme override.
|
||||
`ui.default_controller` references a configured MIDI surface. Unassigned volume
|
||||
and mute controls use that surface for MIDI learn; an explicit binding continues
|
||||
to name its own surface. The Config tab shows and changes this persisted
|
||||
default.
|
||||
|
||||
Draft changes do not affect live routing or audio. Save is the single
|
||||
server-owned revisioned commit: it persists the validated profile and activates
|
||||
its routing and MIDI configuration. Validation or persistence errors preserve
|
||||
the draft and the prior live configuration. MIDI learn reserves the selected
|
||||
action and suppresses its normal action, and Unset removes only that
|
||||
fader/action binding. Device/backend status remains available from the mixer
|
||||
without requiring a separate configuration table browser.
|
||||
|
||||
MIDI learn reserves the selected control and suppresses its normal action while learning. Save sends a revisioned request to the server; it never writes files from the TUI. Restore terminal state on errors and exit. Use logs away from the active terminal display.
|
||||
|
||||
|
|
@ -204,7 +736,7 @@ These are fit-for-purpose recommendations based on primary documentation, not be
|
|||
|
||||
| Concern | Recommendation and tradeoff | Primary source |
|
||||
| --- | --- | --- |
|
||||
| USB MIDI | `midir`; owns input/output connections, Linux transport support. Prefer this to hand-written ALSA MIDI FFI; supplement persistent identity separately. | [midir](https://docs.rs/midir/latest/midir/) |
|
||||
| USB MIDI | `midir` 0.11.1 (MIT); owns input/output connections and uses ALSA on Linux. Prefer this to hand-written ALSA MIDI FFI; supplement persistent identity separately. It declares no MSRV, so the locked release is compiled in the Rust 1.88 gate. | [midir](https://docs.rs/midir/0.11.1/midir/) |
|
||||
| Pulse protocol | `libpulse-binding`; exposes asynchronous introspection/control. Keep callbacks on an owned loop. Prefer this to parsing `pactl` output; simple playback APIs do not provide the control plane. | [libpulse-binding](https://docs.rs/libpulse-binding/latest/libpulse_binding/) |
|
||||
| Native PipeWire | Official `pipewire` Rust bindings; full native object access, with more SPA/graph complexity. Keep behind a feature and capability spike. | [pipewire-rs](https://pipewire.pages.freedesktop.org/pipewire-rs/pipewire/index.html) |
|
||||
| Hardware mixer | `alsa` for mixer controls and optional MIDI identity enrichment; feature-gated. No promise of application volume control. | [alsa::mixer](https://docs.rs/alsa/latest/alsa/mixer/index.html) |
|
||||
|
|
|
|||
|
|
@ -0,0 +1,132 @@
|
|||
# fader_master hands-on checklist (Arch + PipeWire)
|
||||
|
||||
Automated tests cover validation, buffering, IPC, rollback, rendering, and
|
||||
atomic persistence. This checklist records manual acceptance with your real
|
||||
PipeWire session, APC MINI, applications, and terminal. Existing checked items
|
||||
are historical observations; the new unchecked items still need manual testing.
|
||||
|
||||
## Setup
|
||||
|
||||
Use a disposable profile directory so editor Save does not modify tracked
|
||||
examples:
|
||||
|
||||
```sh
|
||||
work=$(mktemp -d /tmp/fader-master-check.XXXXXX)
|
||||
cp examples/profiles/{arch-pipewire,desktop}.toml "$work/"
|
||||
cargo run --locked -p fader_master -- serve \
|
||||
--config "$work/arch-pipewire.toml" --audio pulse
|
||||
```
|
||||
|
||||
In another terminal:
|
||||
|
||||
```sh
|
||||
cargo run --locked -p fader_master -- tui
|
||||
```
|
||||
|
||||
Restart the server too after rebuilding. A new client or all-in-one launcher
|
||||
can reconnect to an old server process; it cannot replace its implementation.
|
||||
|
||||
Known mappings: Music `CC48/Note64`, Browser `CC49/Note65`, Media sync
|
||||
`CC50/Note66`, and Master `CC56/Note98`. The profile polling interval is 10 ms
|
||||
and accepts 1–100 ms.
|
||||
|
||||
## MPRIS/QBZ opt-in checks (new, not yet hardware-qualified)
|
||||
|
||||
Use a disposable profile, build with default `mpris` support and restart both
|
||||
processes. Start QBZ in the same user's desktop session; leave it paused and
|
||||
start a second, different MPRIS player to check targeting. Configure the real
|
||||
controller input/output ports (do not overwrite the checked-in examples).
|
||||
|
||||
- [ ] Media appears even with no audio stream; P discovers paused QBZ. A manual
|
||||
exact bus-name selector reaches QBZ only. A broad regex matching both players
|
||||
reports ambiguity and sends no command.
|
||||
- [ ] A/E/D, rename, control action/parameter editing and Save/exit survive Save,
|
||||
server restart and client reconnect. Unsupported controls show unsupported.
|
||||
- [ ] Learn Play/Pause/Stop, release/hold buttons and U-unbind. Only presses act;
|
||||
bindings persist after Save/restart. Removing the surface unbinds controls.
|
||||
- [ ] Only the confirmed Play/Pause/Stop state lights. External player changes
|
||||
update LEDs. Verify controller-specific on/off colors; reconnect resynchronizes.
|
||||
- [ ] Global, per-fader and per-entry feedback switches send no output while off,
|
||||
including no clearing messages. Re-enable/Save restores observed indicators.
|
||||
- [ ] Seek forward/back and absolute position, shuffle, repeat and playlist
|
||||
activation work where QBZ reports support. Unsupported properties stay disabled.
|
||||
- [ ] Quit/restart QBZ, switch profiles and unplug/replug the controller. Errors
|
||||
recover; expired commands are not replayed against a replacement player.
|
||||
|
||||
Hardware-free D-Bus qualification (creates its own bus and fake players, never
|
||||
controls desktop applications):
|
||||
|
||||
```sh
|
||||
dbus-run-session -- cargo test -p fader_master private_bus -- --ignored
|
||||
```
|
||||
|
||||
## Mixer smoke test
|
||||
|
||||
- [x] TUI shows Music, Browser, Media, Master, and the APC backend ID; startup
|
||||
does not change any live volume or mute.
|
||||
- [x] CC48/49 control only their applications; CC50 sets both Media members to
|
||||
one absolute value; CC56/Note98 affect only the default output.
|
||||
- [x] Pickup starts `waiting`, becomes `tracking` only after crossing the live
|
||||
value, and returns to `waiting` after an external volume change.
|
||||
- [x] A rapid fader sweep stays responsive and converges to its last position;
|
||||
rapid double mute presses preserve both edges.
|
||||
- [x] With Browser offline, its controls are nonfatal and are not replayed when
|
||||
Browser starts.
|
||||
|
||||
|
||||
## Profile switching and recovery
|
||||
|
||||
Both disposable profiles are siblings, so while the server is running:
|
||||
|
||||
```sh
|
||||
cargo run --locked -p fader_master -- profile switch desktop
|
||||
cargo run --locked -p fader_master -- profile switch arch-pipewire
|
||||
```
|
||||
|
||||
- [x] Each successful switch changes the profile shown in Config, preserves
|
||||
observed live audio without a write, and requires pickup again.
|
||||
- [x] A missing/invalid profile reports an error and leaves the old profile
|
||||
active. A switch attempted during pending fader work returns an actionable
|
||||
retry error instead of crossing generations.
|
||||
- [x] Stop the server while TUI remains open: rows stay visible, the error is
|
||||
internal to the TUI, and restart reconnects without replaying input.
|
||||
local socket operation failed for /run/user/1000/fader_master/control.sock: Connection refused (os error 111)
|
||||
error is smooth but unhelpful, log the actual error and show a helpful one ?
|
||||
- [x] Unplug/replug APC MINI: server/TUI stay alive, status changes to
|
||||
`missing — connect device`, and reconnection rearms pickup.
|
||||
- [x] Start TUI before the server and confirm it recovers automatically when the
|
||||
socket appears.
|
||||
|
||||
## Polling and report
|
||||
|
||||
- [x] Compare `poll_interval_ms = 10`, `5`, and `2` (restart between values).
|
||||
Record responsiveness, CPU impact, and the lowest useful value.
|
||||
About the same, cpu usage a little on the higer end of what I would like tho
|
||||
- [ ] Run `cargo run --locked -p fader_master -- status`; confirm `status=ready`
|
||||
and expected final values.
|
||||
- [ ] Report any pre-pickup jump, wrong target, rough sweep, stale/pending value,
|
||||
lost mute edge, failed Save diagnostic, reconnect over one second,
|
||||
terminal corruption, or process exit.
|
||||
|
||||
Explicit `profile switch --restore` remains optional for manual testing because
|
||||
it deliberately writes saved state. Mute LED feedback is implemented; verify
|
||||
the configured on/off values against the particular surface.
|
||||
|
||||
## Layout, settings, and persistence
|
||||
|
||||
- [ ] Move a fader in both directions, Save, restart the server, and move it
|
||||
again. Verify that selection follows it and the order never snaps back.
|
||||
- [ ] Add and rename separators with both nonempty and empty names. Create two
|
||||
unnamed separators and verify they remain independently editable/movable.
|
||||
- [ ] Try separator Slim/Standard/Thick/Fill and all four decorations in both
|
||||
orientations. Plain + empty name should be blank space; unnamed lines should
|
||||
be continuous. Multiple Fill separators should share leftover space.
|
||||
- [ ] Try Slim, Bordered slim, Standard, and Thick faders. Resize the terminal:
|
||||
horizontal entries should stay on one row, and selection should stay visible.
|
||||
- [ ] Change theme, orientation, and each pickup-status mode in Config. Save
|
||||
and restart; all choices should persist. Hidden pickup status must not disable
|
||||
the hardware pickup behavior.
|
||||
- [ ] Hide an application fader used by a group, then restore it from the
|
||||
Config popup. Verify that its MIDI binding and group membership still work.
|
||||
- [ ] Relearn a mute button, Save, and confirm only the new button controls it
|
||||
and receives feedback. Open Help with h/?; Escape closes popups, Q confirms quit.
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
[package]
|
||||
name = "fader-config"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
media.workspace = true
|
||||
fader-core.workspace = true
|
||||
rustix.workspace = true
|
||||
serde.workspace = true
|
||||
tempfile.workspace = true
|
||||
thiserror.workspace = true
|
||||
toml.workspace = true
|
||||
toml_edit.workspace = true
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
use fader_core::ProfileId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{ConfigError, SCHEMA_VERSION};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RawActiveConfig {
|
||||
schema_version: u16,
|
||||
active_profile: String,
|
||||
}
|
||||
|
||||
/// Durable pointer to the profile selected for the next server start.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ActiveConfig {
|
||||
active_profile: ProfileId,
|
||||
}
|
||||
|
||||
impl ActiveConfig {
|
||||
pub fn new(active_profile: &str) -> Result<Self, ConfigError> {
|
||||
let active_profile = ProfileId::new(active_profile)
|
||||
.map_err(|error| ConfigError::validation("active_profile", error.to_string()))?;
|
||||
Ok(Self { active_profile })
|
||||
}
|
||||
|
||||
pub fn parse(input: &str) -> Result<Self, ConfigError> {
|
||||
let raw: RawActiveConfig = toml::from_str(input)?;
|
||||
if raw.schema_version != SCHEMA_VERSION {
|
||||
return Err(ConfigError::validation(
|
||||
"schema_version",
|
||||
format!(
|
||||
"unsupported version {}; expected {SCHEMA_VERSION}",
|
||||
raw.schema_version
|
||||
),
|
||||
));
|
||||
}
|
||||
Self::new(&raw.active_profile)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn active_profile(&self) -> &ProfileId {
|
||||
&self.active_profile
|
||||
}
|
||||
|
||||
pub fn to_toml(&self) -> Result<String, ConfigError> {
|
||||
Ok(toml::to_string_pretty(&RawActiveConfig {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
active_profile: self.active_profile.as_str().to_owned(),
|
||||
})?)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crate::{AtomicFile, PersistedState, PersistenceError};
|
||||
|
||||
const DEBOUNCE: Duration = Duration::from_millis(500);
|
||||
const MAX_DIRTY_AGE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Monotonic time source used by checkpoint scheduling.
|
||||
pub trait Clock {
|
||||
/// Elapsed monotonic time in an arbitrary clock-local epoch.
|
||||
fn now(&self) -> Duration;
|
||||
}
|
||||
|
||||
/// Production monotonic clock.
|
||||
pub struct SystemClock {
|
||||
origin: Instant,
|
||||
}
|
||||
|
||||
impl Default for SystemClock {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
origin: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for SystemClock {
|
||||
fn now(&self) -> Duration {
|
||||
self.origin.elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
/// Destination for validated checkpoint snapshots.
|
||||
pub trait CheckpointSink {
|
||||
/// Durably writes one complete snapshot.
|
||||
fn write(&mut self, state: &PersistedState) -> Result<(), PersistenceError>;
|
||||
}
|
||||
|
||||
/// Atomic state-file checkpoint destination.
|
||||
pub struct StateFileSink {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl StateFileSink {
|
||||
/// Creates a sink for an already initialized private state directory.
|
||||
pub fn new(path: impl Into<PathBuf>) -> Self {
|
||||
Self { path: path.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl CheckpointSink for StateFileSink {
|
||||
fn write(&mut self, state: &PersistedState) -> Result<(), PersistenceError> {
|
||||
let document = state
|
||||
.to_toml()
|
||||
.map_err(|error| PersistenceError::serialization(&self.path, error.to_string()))?;
|
||||
AtomicFile::write(&self.path, document.as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure debounce/max-latency coordinator retaining the newest complete state.
|
||||
pub struct CheckpointCoordinator<C, S> {
|
||||
clock: C,
|
||||
sink: S,
|
||||
pending: Option<PersistedState>,
|
||||
dirty_since: Option<Duration>,
|
||||
last_change: Option<Duration>,
|
||||
}
|
||||
|
||||
impl<C: Clock, S: CheckpointSink> CheckpointCoordinator<C, S> {
|
||||
/// Starts clean with the documented 500ms debounce and 2s maximum delay.
|
||||
pub fn new(clock: C, sink: S) -> Self {
|
||||
Self {
|
||||
clock,
|
||||
sink,
|
||||
pending: None,
|
||||
dirty_since: None,
|
||||
last_change: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces any pending snapshot with the newest validated state.
|
||||
pub fn mark_dirty(&mut self, state: PersistedState) {
|
||||
let now = self.clock.now();
|
||||
self.dirty_since.get_or_insert(now);
|
||||
self.last_change = Some(now);
|
||||
self.pending = Some(state);
|
||||
}
|
||||
|
||||
/// Flushes after a quiet debounce or once continuous changes reach 2s.
|
||||
pub fn poll(&mut self) -> Result<bool, PersistenceError> {
|
||||
let now = self.clock.now();
|
||||
let due = self
|
||||
.last_change
|
||||
.is_some_and(|last| now.saturating_sub(last) >= DEBOUNCE)
|
||||
|| self
|
||||
.dirty_since
|
||||
.is_some_and(|first| now.saturating_sub(first) >= MAX_DIRTY_AGE);
|
||||
if due { self.flush() } else { Ok(false) }
|
||||
}
|
||||
|
||||
/// Flushes the final dirty snapshot during orderly shutdown.
|
||||
pub fn shutdown(&mut self) -> Result<bool, PersistenceError> {
|
||||
self.flush()
|
||||
}
|
||||
|
||||
/// Exposes the sink for diagnostics and deterministic tests.
|
||||
pub const fn sink(&self) -> &S {
|
||||
&self.sink
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<bool, PersistenceError> {
|
||||
let Some(state) = self.pending.as_ref() else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.sink.write(state)?;
|
||||
self.pending = None;
|
||||
self.dirty_since = None;
|
||||
self.last_change = None;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
use fader_core::SurfaceId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{ConfigError, SCHEMA_VERSION, profile::parse_id};
|
||||
|
||||
/// Output and motion features explicitly supported by a device profile.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DeviceCapabilities {
|
||||
/// A mute indicator can be driven.
|
||||
pub mute_led: bool,
|
||||
/// A numeric or bar-style value display can be driven.
|
||||
pub value_display: bool,
|
||||
/// A motorized fader can accept position feedback.
|
||||
pub motorized_fader: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RawDeviceProfile {
|
||||
schema_version: u16,
|
||||
id: String,
|
||||
label: String,
|
||||
capabilities: DeviceCapabilities,
|
||||
}
|
||||
|
||||
/// A reusable, validated MIDI device capability document.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DeviceProfile {
|
||||
raw: RawDeviceProfile,
|
||||
id: SurfaceId,
|
||||
}
|
||||
|
||||
impl DeviceProfile {
|
||||
/// Parses and validates a device profile.
|
||||
pub fn parse(input: &str) -> Result<Self, ConfigError> {
|
||||
let raw: RawDeviceProfile = toml::from_str(input)?;
|
||||
if raw.schema_version != SCHEMA_VERSION {
|
||||
return Err(ConfigError::validation(
|
||||
"schema_version",
|
||||
format!(
|
||||
"unsupported version {}; expected {SCHEMA_VERSION}",
|
||||
raw.schema_version
|
||||
),
|
||||
));
|
||||
}
|
||||
let id = parse_id(&raw.id, "device.id")?;
|
||||
if raw.label.trim().is_empty() {
|
||||
return Err(ConfigError::validation("device.label", "must not be empty"));
|
||||
}
|
||||
Ok(Self { raw, id })
|
||||
}
|
||||
|
||||
/// Serializes a canonical representation.
|
||||
pub fn to_toml(&self) -> Result<String, ConfigError> {
|
||||
Ok(toml::to_string_pretty(&self.raw)?)
|
||||
}
|
||||
|
||||
/// Stable device-profile identifier.
|
||||
pub fn id(&self) -> &SurfaceId {
|
||||
&self.id
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,32 @@
|
|||
use thiserror::Error;
|
||||
|
||||
/// A TOML syntax/schema error or a semantic validation failure.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ConfigError {
|
||||
/// The TOML document did not conform to its strict structural schema.
|
||||
#[error("TOML schema error: {0}")]
|
||||
Toml(#[from] toml::de::Error),
|
||||
/// Editable TOML could not be represented while retaining formatting.
|
||||
#[error("editable TOML error: {0}")]
|
||||
Edit(#[from] toml_edit::TomlError),
|
||||
/// A field was structurally valid TOML but violated a domain invariant.
|
||||
#[error("validation error at {path}: {message}")]
|
||||
Validation {
|
||||
/// Stable, editor-friendly field path.
|
||||
path: String,
|
||||
/// Human-readable reason.
|
||||
message: String,
|
||||
},
|
||||
/// A validated document unexpectedly failed serialization.
|
||||
#[error("could not serialize validated TOML: {0}")]
|
||||
Serialize(#[from] toml::ser::Error),
|
||||
}
|
||||
|
||||
impl ConfigError {
|
||||
pub(crate) fn validation(path: impl Into<String>, message: impl Into<String>) -> Self {
|
||||
Self::Validation {
|
||||
path: path.into(),
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,306 @@
|
|||
use std::{
|
||||
fs::{self, File},
|
||||
io::{self, Cursor, Read, Write},
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use tempfile::NamedTempFile;
|
||||
use thiserror::Error;
|
||||
use toml_edit::{DocumentMut, value};
|
||||
|
||||
use crate::{ConfigError, PersistedState, Profile, SCHEMA_VERSION};
|
||||
|
||||
/// A filesystem persistence failure with operation and path context.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum PersistenceError {
|
||||
/// An operating-system operation failed.
|
||||
#[error("could not {action} at {path}: {source}")]
|
||||
Io {
|
||||
/// Operation being attempted.
|
||||
action: &'static str,
|
||||
/// Relevant file or directory.
|
||||
path: PathBuf,
|
||||
/// Operating-system error.
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
/// A path is a symlink where ownership must be unambiguous.
|
||||
#[error("refusing symlink at {0}")]
|
||||
Symlink(PathBuf),
|
||||
/// A path belongs to a different Unix user.
|
||||
#[error("refusing path {path}: owner uid {actual} does not match current uid {expected}")]
|
||||
WrongOwner {
|
||||
/// Rejected path.
|
||||
path: PathBuf,
|
||||
/// Owner found on disk.
|
||||
actual: u32,
|
||||
/// Effective user running the process.
|
||||
expected: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl PersistenceError {
|
||||
pub(crate) fn io(action: &'static str, path: impl Into<PathBuf>, source: io::Error) -> Self {
|
||||
Self::Io {
|
||||
action,
|
||||
path: path.into(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn serialization(path: &Path, message: String) -> Self {
|
||||
Self::io(
|
||||
"serialize checkpoint",
|
||||
path,
|
||||
io::Error::new(io::ErrorKind::InvalidData, message),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of reading cache-like state; malformed data can be ignored by startup.
|
||||
#[derive(Debug)]
|
||||
pub enum StateLoad {
|
||||
/// No checkpoint has been written yet.
|
||||
Missing,
|
||||
/// A fully validated persisted-state document.
|
||||
Loaded(PersistedState),
|
||||
/// Bytes were readable but invalid; they remain untouched for diagnosis.
|
||||
Malformed {
|
||||
/// Validation or TOML parsing failure.
|
||||
error: ConfigError,
|
||||
},
|
||||
}
|
||||
|
||||
/// Secure same-directory atomic file replacement.
|
||||
pub struct AtomicFile;
|
||||
|
||||
impl AtomicFile {
|
||||
/// Writes mode `0600`, syncs content, renames, then syncs the directory.
|
||||
///
|
||||
/// The destination is untouched until the temporary file is complete and
|
||||
/// durable. Temporary files are removed automatically on pre-rename errors.
|
||||
pub fn write(path: &Path, contents: &[u8]) -> Result<(), PersistenceError> {
|
||||
Self::write_from(path, &mut Cursor::new(contents))
|
||||
}
|
||||
|
||||
/// Streams content into a same-directory temporary file before replacement.
|
||||
///
|
||||
/// This variant keeps memory bounded for larger documents and makes source
|
||||
/// read failures obey the same no-replacement guarantee as disk failures.
|
||||
pub fn write_from(path: &Path, source: &mut dyn Read) -> Result<(), PersistenceError> {
|
||||
let parent = path.parent().ok_or_else(|| {
|
||||
PersistenceError::io(
|
||||
"resolve parent directory",
|
||||
path,
|
||||
io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"),
|
||||
)
|
||||
})?;
|
||||
check_owned_not_symlink(parent)?;
|
||||
check_owner_writable_directory(parent)?;
|
||||
if path.exists() {
|
||||
check_owned_not_symlink(path)?;
|
||||
}
|
||||
|
||||
let mut temporary = NamedTempFile::new_in(parent)
|
||||
.map_err(|source| PersistenceError::io("create temporary file", parent, source))?;
|
||||
temporary
|
||||
.as_file()
|
||||
.set_permissions(fs::Permissions::from_mode(0o600))
|
||||
.map_err(|source| PersistenceError::io("set temporary permissions", path, source))?;
|
||||
io::copy(source, &mut temporary)
|
||||
.map_err(|source| PersistenceError::io("write temporary file", path, source))?;
|
||||
temporary
|
||||
.as_file_mut()
|
||||
.flush()
|
||||
.map_err(|source| PersistenceError::io("flush temporary file", path, source))?;
|
||||
temporary
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|source| PersistenceError::io("sync temporary file", path, source))?;
|
||||
temporary.persist(path).map_err(|error| {
|
||||
PersistenceError::io("atomically replace destination", path, error.error)
|
||||
})?;
|
||||
File::open(parent)
|
||||
.and_then(|directory| directory.sync_all())
|
||||
.map_err(|source| PersistenceError::io("sync parent directory", parent, source))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn check_owned_not_symlink(path: &Path) -> Result<(), PersistenceError> {
|
||||
let metadata = fs::symlink_metadata(path)
|
||||
.map_err(|source| PersistenceError::io("inspect ownership", path, source))?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
return Err(PersistenceError::Symlink(path.to_owned()));
|
||||
}
|
||||
let expected = rustix::process::geteuid().as_raw();
|
||||
let actual = metadata.uid();
|
||||
if actual != expected {
|
||||
return Err(PersistenceError::WrongOwner {
|
||||
path: path.to_owned(),
|
||||
actual,
|
||||
expected,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_owner_writable_directory(path: &Path) -> Result<(), PersistenceError> {
|
||||
let metadata = fs::metadata(path)
|
||||
.map_err(|source| PersistenceError::io("inspect directory permissions", path, source))?;
|
||||
if metadata.permissions().mode() & 0o200 == 0 {
|
||||
return Err(PersistenceError::io(
|
||||
"create temporary file",
|
||||
path,
|
||||
io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"owner-write permission is not set on the directory",
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn load_state(path: &Path) -> Result<StateLoad, PersistenceError> {
|
||||
let contents = match fs::read_to_string(path) {
|
||||
Ok(contents) => contents,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(StateLoad::Missing),
|
||||
Err(source) => return Err(PersistenceError::io("read state", path, source)),
|
||||
};
|
||||
Ok(match PersistedState::parse(&contents) {
|
||||
Ok(state) => StateLoad::Loaded(state),
|
||||
Err(error) => StateLoad::Malformed { error },
|
||||
})
|
||||
}
|
||||
|
||||
/// Why a profile migration could not be committed.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum MigrationError {
|
||||
/// Only strictly forward migrations to the current version are allowed.
|
||||
#[error("incompatible migration from schema {from} to schema {to}")]
|
||||
Incompatible {
|
||||
/// Existing schema version.
|
||||
from: u16,
|
||||
/// Current schema version.
|
||||
to: u16,
|
||||
},
|
||||
/// The proposed migrated profile is invalid.
|
||||
#[error(transparent)]
|
||||
Config(#[from] ConfigError),
|
||||
/// Reading, backing up, or replacing the file failed.
|
||||
#[error(transparent)]
|
||||
Persistence(#[from] PersistenceError),
|
||||
}
|
||||
|
||||
/// Result of checking and, when supported, upgrading a profile document.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ProfileUpgrade {
|
||||
/// The profile already uses the current schema and was only validated.
|
||||
Current {
|
||||
/// Current schema version.
|
||||
version: u16,
|
||||
},
|
||||
/// An older profile was validated, backed up, and atomically replaced.
|
||||
Upgraded {
|
||||
/// Durable backup containing the exact original bytes.
|
||||
backup: PathBuf,
|
||||
/// Original schema version.
|
||||
from: u16,
|
||||
/// Installed schema version.
|
||||
to: u16,
|
||||
},
|
||||
}
|
||||
|
||||
/// Upgrades a known older profile schema without discarding comments.
|
||||
///
|
||||
/// A missing schema marker is treated as the pre-versioned schema `0`. The
|
||||
/// migrated candidate must pass complete current validation before either the
|
||||
/// backup or destination is written.
|
||||
pub fn upgrade_profile(path: &Path) -> Result<ProfileUpgrade, MigrationError> {
|
||||
let source = fs::read_to_string(path)
|
||||
.map_err(|error| PersistenceError::io("read profile for upgrade", path, error))?;
|
||||
let mut document = DocumentMut::from_str(&source).map_err(ConfigError::from)?;
|
||||
let from = profile_schema_version(&document)?;
|
||||
if from == SCHEMA_VERSION {
|
||||
Profile::parse(&source)?;
|
||||
return Ok(ProfileUpgrade::Current { version: from });
|
||||
}
|
||||
if from != 0 {
|
||||
return Err(MigrationError::Incompatible {
|
||||
from,
|
||||
to: SCHEMA_VERSION,
|
||||
});
|
||||
}
|
||||
|
||||
document["schema_version"] = value(i64::from(SCHEMA_VERSION));
|
||||
let migrated = document.to_string();
|
||||
Profile::parse(&migrated)?;
|
||||
let backup = migrate_profile(path, from, &migrated)?;
|
||||
Ok(ProfileUpgrade::Upgraded {
|
||||
backup,
|
||||
from,
|
||||
to: SCHEMA_VERSION,
|
||||
})
|
||||
}
|
||||
|
||||
fn profile_schema_version(document: &DocumentMut) -> Result<u16, ConfigError> {
|
||||
let Some(item) = document.get("schema_version") else {
|
||||
return Ok(0);
|
||||
};
|
||||
let Some(version) = item.as_integer() else {
|
||||
return Err(ConfigError::validation(
|
||||
"schema_version",
|
||||
"must be a non-negative integer",
|
||||
));
|
||||
};
|
||||
u16::try_from(version).map_err(|_| {
|
||||
ConfigError::validation(
|
||||
"schema_version",
|
||||
"must be within the supported integer range",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Validates and atomically installs a forward migration after backing up bytes.
|
||||
pub fn migrate_profile(
|
||||
path: &Path,
|
||||
from_version: u16,
|
||||
migrated: &str,
|
||||
) -> Result<PathBuf, MigrationError> {
|
||||
if from_version >= SCHEMA_VERSION {
|
||||
return Err(MigrationError::Incompatible {
|
||||
from: from_version,
|
||||
to: SCHEMA_VERSION,
|
||||
});
|
||||
}
|
||||
Profile::parse(migrated)?;
|
||||
let old = fs::read(path)
|
||||
.map_err(|source| PersistenceError::io("read pre-migration profile", path, source))?;
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| {
|
||||
PersistenceError::io(
|
||||
"construct migration backup",
|
||||
path,
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"non-UTF-8 or missing file name",
|
||||
),
|
||||
)
|
||||
})?;
|
||||
let backup = path.with_file_name(format!("{file_name}.v{from_version}.bak"));
|
||||
if backup.exists() {
|
||||
return Err(PersistenceError::io(
|
||||
"create migration backup",
|
||||
&backup,
|
||||
io::Error::new(io::ErrorKind::AlreadyExists, "backup already exists"),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
AtomicFile::write(&backup, &old)?;
|
||||
AtomicFile::write(path, migrated.as_bytes())?;
|
||||
Ok(backup)
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
//! Strict TOML schemas and semantic validation for fader_master.
|
||||
//!
|
||||
//! Parsing produces validated documents: callers cannot accidentally activate
|
||||
//! a profile whose identifiers, references, MIDI ranges, or capabilities are
|
||||
//! invalid. Persistence and migration live in separate modules in later M2
|
||||
//! increments.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod active;
|
||||
mod checkpoint;
|
||||
mod device;
|
||||
mod document;
|
||||
mod error;
|
||||
mod files;
|
||||
mod paths;
|
||||
mod profile;
|
||||
mod state;
|
||||
|
||||
pub use checkpoint::{CheckpointCoordinator, CheckpointSink, Clock, StateFileSink, SystemClock};
|
||||
pub use device::{DeviceCapabilities, DeviceProfile};
|
||||
pub use document::{ProfileDocument, SelectorDraft, SelectorPattern};
|
||||
pub use error::ConfigError;
|
||||
pub use files::{
|
||||
AtomicFile, MigrationError, PersistenceError, ProfileUpgrade, StateLoad, migrate_profile,
|
||||
upgrade_profile,
|
||||
};
|
||||
pub use paths::{XdgEnvironment, XdgPaths};
|
||||
pub use profile::{
|
||||
Action, Adapter, Application, Audio, Binding, Fader, FaderDensity, Group, MessageKind,
|
||||
MixerLayoutEntry, MixerOrientation, NewStreamPolicy, Profile, Selector, SelectorField,
|
||||
SelectorMode, SeparatorDecoration, SeparatorSize, StartupPolicy, StatusDisplayMode, Surface,
|
||||
TargetKind, UiTheme,
|
||||
};
|
||||
pub use state::{
|
||||
CachedObservation, DesiredWrite, PersistedState, ProfileState, StartupState, UiView,
|
||||
};
|
||||
|
||||
pub(crate) const SCHEMA_VERSION: u16 = 1;
|
||||
pub use active::ActiveConfig;
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
|
||||
|
||||
use fader_core::ProfileId;
|
||||
|
||||
use crate::{ConfigError, PersistenceError, StateLoad, files::load_state};
|
||||
|
||||
/// Relevant XDG environment values, separated from process globals for tests.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct XdgEnvironment {
|
||||
/// User home used only for XDG fallbacks.
|
||||
pub home: PathBuf,
|
||||
/// `$XDG_CONFIG_HOME`; relative values are ignored by the XDG specification.
|
||||
pub config_home: Option<PathBuf>,
|
||||
/// `$XDG_STATE_HOME`; relative values are ignored by the XDG specification.
|
||||
pub state_home: Option<PathBuf>,
|
||||
/// `$XDG_RUNTIME_DIR`; no shared temporary-directory fallback is invented.
|
||||
pub runtime_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl XdgEnvironment {
|
||||
/// Captures relevant process environment without applying path policy yet.
|
||||
pub fn from_process() -> Result<Self, ConfigError> {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| {
|
||||
ConfigError::validation("HOME", "is required when resolving XDG fallbacks")
|
||||
})?;
|
||||
Ok(Self {
|
||||
home,
|
||||
config_home: std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from),
|
||||
state_home: std::env::var_os("XDG_STATE_HOME").map(PathBuf::from),
|
||||
runtime_dir: std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved per-user configuration, state, and optional runtime paths.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct XdgPaths {
|
||||
config_dir: PathBuf,
|
||||
state_dir: PathBuf,
|
||||
runtime_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl XdgPaths {
|
||||
/// Resolves absolute XDG roots and specification-defined home fallbacks.
|
||||
pub fn resolve(environment: &XdgEnvironment) -> Result<Self, ConfigError> {
|
||||
if !environment.home.is_absolute() {
|
||||
return Err(ConfigError::validation("HOME", "must be an absolute path"));
|
||||
}
|
||||
let config_root = absolute_or(&environment.config_home, || {
|
||||
environment.home.join(".config")
|
||||
});
|
||||
let state_root = absolute_or(&environment.state_home, || {
|
||||
environment.home.join(".local/state")
|
||||
});
|
||||
let runtime_dir = environment
|
||||
.runtime_dir
|
||||
.as_ref()
|
||||
.filter(|path| path.is_absolute())
|
||||
.map(|path| path.join("fader_master"));
|
||||
Ok(Self {
|
||||
config_dir: config_root.join("fader_master"),
|
||||
state_dir: state_root.join("fader_master"),
|
||||
runtime_dir,
|
||||
})
|
||||
}
|
||||
|
||||
/// Root containing the global config, profiles, and device documents.
|
||||
pub fn config_dir(&self) -> &std::path::Path {
|
||||
&self.config_dir
|
||||
}
|
||||
|
||||
/// Global active-profile configuration document.
|
||||
pub fn config_file(&self) -> PathBuf {
|
||||
self.config_dir.join("config.toml")
|
||||
}
|
||||
|
||||
/// Durable state checkpoint document.
|
||||
pub fn state_file(&self) -> PathBuf {
|
||||
self.state_dir.join("state.toml")
|
||||
}
|
||||
|
||||
/// Optional private runtime directory; absent when XDG provides none.
|
||||
pub fn runtime_dir(&self) -> Option<&std::path::Path> {
|
||||
self.runtime_dir.as_deref()
|
||||
}
|
||||
|
||||
/// Resolves a validated stable profile ID without accepting path syntax.
|
||||
pub fn profile_file(&self, id: &str) -> Result<PathBuf, ConfigError> {
|
||||
let id = ProfileId::new(id).map_err(|error| {
|
||||
ConfigError::validation("profile ID", format!("unsafe profile ID: {error}"))
|
||||
})?;
|
||||
Ok(self
|
||||
.config_dir
|
||||
.join("profiles")
|
||||
.join(format!("{}.toml", id.as_str())))
|
||||
}
|
||||
|
||||
/// Creates application-owned directories with mode `0700`.
|
||||
pub fn create_layout(&self) -> Result<(), PersistenceError> {
|
||||
for directory in [
|
||||
self.config_dir.clone(),
|
||||
self.config_dir.join("profiles"),
|
||||
self.config_dir.join("devices"),
|
||||
self.state_dir.clone(),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(self.runtime_dir.iter().cloned())
|
||||
{
|
||||
create_private_dir(&directory)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads state without treating absence or malformed cached data as fatal.
|
||||
pub fn load_state(&self) -> Result<StateLoad, PersistenceError> {
|
||||
load_state(&self.state_file())
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute_or(value: &Option<PathBuf>, fallback: impl FnOnce() -> PathBuf) -> PathBuf {
|
||||
value
|
||||
.as_ref()
|
||||
.filter(|path| path.is_absolute())
|
||||
.cloned()
|
||||
.unwrap_or_else(fallback)
|
||||
}
|
||||
|
||||
fn create_private_dir(path: &std::path::Path) -> Result<(), PersistenceError> {
|
||||
fs::create_dir_all(path)
|
||||
.map_err(|source| PersistenceError::io("create directory", path, source))?;
|
||||
super::files::check_owned_not_symlink(path)?;
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o700))
|
||||
.map_err(|source| PersistenceError::io("set directory permissions", path, source))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,470 @@
|
|||
use std::collections::BTreeSet;
|
||||
|
||||
use fader_core::{ApplicationId, ChannelGains, Gain, ProfileId, SurfaceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{ConfigError, SCHEMA_VERSION, profile::parse_id};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ObservedObject {
|
||||
object: String,
|
||||
gain: Vec<f64>,
|
||||
muted: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct DesiredObject {
|
||||
object: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
gain: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
muted: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Assignment {
|
||||
surface: String,
|
||||
input_port: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
output_port: Option<String>,
|
||||
}
|
||||
|
||||
/// Last selected TUI view for a profile.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UiView {
|
||||
/// Mixer overview.
|
||||
Mixer,
|
||||
/// MIDI surface assignment and status.
|
||||
Devices,
|
||||
/// Runtime diagnostics.
|
||||
Status,
|
||||
/// Configuration editor.
|
||||
Editor,
|
||||
}
|
||||
|
||||
/// Durable state for one stable profile; observed values are cache-only.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProfileState {
|
||||
id: String,
|
||||
last_view: UiView,
|
||||
#[serde(default)]
|
||||
observed: Vec<ObservedObject>,
|
||||
#[serde(default)]
|
||||
desired: Vec<DesiredObject>,
|
||||
#[serde(default)]
|
||||
assignments: Vec<Assignment>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RawState {
|
||||
schema_version: u16,
|
||||
#[serde(default)]
|
||||
profiles: Vec<ProfileState>,
|
||||
}
|
||||
|
||||
/// Strict durable state without runtime handles, generations, or operations.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PersistedState {
|
||||
raw: RawState,
|
||||
}
|
||||
|
||||
impl PersistedState {
|
||||
/// Parses and validates cached observations, desired state, and assignments.
|
||||
pub fn parse(input: &str) -> Result<Self, ConfigError> {
|
||||
let raw: RawState = toml::from_str(input)?;
|
||||
if raw.schema_version != SCHEMA_VERSION {
|
||||
return Err(ConfigError::validation(
|
||||
"schema_version",
|
||||
format!(
|
||||
"unsupported version {}; expected {SCHEMA_VERSION}",
|
||||
raw.schema_version
|
||||
),
|
||||
));
|
||||
}
|
||||
validate_profiles(&raw.profiles)?;
|
||||
Ok(Self { raw })
|
||||
}
|
||||
|
||||
/// Serializes a canonical representation.
|
||||
pub fn to_toml(&self) -> Result<String, ConfigError> {
|
||||
Ok(toml::to_string_pretty(&self.raw)?)
|
||||
}
|
||||
|
||||
/// Per-profile state in stable order.
|
||||
pub fn profiles(&self) -> &[ProfileState] {
|
||||
&self.raw.profiles
|
||||
}
|
||||
|
||||
/// Records the latest durable object intent independently of observations.
|
||||
pub fn set_desired(
|
||||
&mut self,
|
||||
profile_id: &str,
|
||||
object_id: &str,
|
||||
gain: Option<f64>,
|
||||
muted: Option<bool>,
|
||||
) -> Result<(), ConfigError> {
|
||||
parse_id::<ApplicationId>(object_id, "desired.object")?;
|
||||
if gain.is_none() && muted.is_none() {
|
||||
return Err(ConfigError::validation(
|
||||
"desired",
|
||||
"at least one desired gain or mute value is required",
|
||||
));
|
||||
}
|
||||
if let Some(value) = gain {
|
||||
Gain::new(value)
|
||||
.map_err(|error| ConfigError::validation("desired.gain", error.to_string()))?;
|
||||
}
|
||||
let profile = self
|
||||
.raw
|
||||
.profiles
|
||||
.iter_mut()
|
||||
.find(|profile| profile.id == profile_id)
|
||||
.ok_or_else(|| {
|
||||
ConfigError::validation("profile", format!("unknown profile {profile_id:?}"))
|
||||
})?;
|
||||
if let Some(desired) = profile
|
||||
.desired
|
||||
.iter_mut()
|
||||
.find(|desired| desired.object == object_id)
|
||||
{
|
||||
desired.gain = gain;
|
||||
desired.muted = muted;
|
||||
} else {
|
||||
profile.desired.push(DesiredObject {
|
||||
object: object_id.to_owned(),
|
||||
gain,
|
||||
muted,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records a confirmed per-channel observation without a runtime handle.
|
||||
pub fn set_observed(
|
||||
&mut self,
|
||||
profile_id: &str,
|
||||
object_id: &str,
|
||||
channels: &[f64],
|
||||
muted: bool,
|
||||
) -> Result<(), ConfigError> {
|
||||
parse_id::<ApplicationId>(object_id, "observed.object")?;
|
||||
let gains = channels
|
||||
.iter()
|
||||
.copied()
|
||||
.map(Gain::new)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|error| ConfigError::validation("observed.gain", error.to_string()))?;
|
||||
let validated = ChannelGains::new(gains)
|
||||
.map_err(|error| ConfigError::validation("observed.gain", error.to_string()))?;
|
||||
let profile = find_profile_mut(&mut self.raw.profiles, profile_id)?;
|
||||
let gain = validated.as_slice().iter().map(|gain| gain.get()).collect();
|
||||
if let Some(observed) = profile
|
||||
.observed
|
||||
.iter_mut()
|
||||
.find(|observed| observed.object == object_id)
|
||||
{
|
||||
observed.gain = gain;
|
||||
observed.muted = muted;
|
||||
} else {
|
||||
profile.observed.push(ObservedObject {
|
||||
object: object_id.to_owned(),
|
||||
gain,
|
||||
muted,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remembers stable surface-to-port assignment hints for one profile.
|
||||
pub fn set_surface_assignment(
|
||||
&mut self,
|
||||
profile_id: &str,
|
||||
surface_id: &str,
|
||||
input_port: &str,
|
||||
output_port: Option<&str>,
|
||||
) -> Result<(), ConfigError> {
|
||||
parse_id::<SurfaceId>(surface_id, "assignment.surface")?;
|
||||
if input_port.is_empty() || output_port.is_some_and(str::is_empty) {
|
||||
return Err(ConfigError::validation(
|
||||
"assignment.port",
|
||||
"configured port names must not be empty",
|
||||
));
|
||||
}
|
||||
let profile = find_profile_mut(&mut self.raw.profiles, profile_id)?;
|
||||
let output_port = output_port.map(str::to_owned);
|
||||
if let Some(assignment) = profile
|
||||
.assignments
|
||||
.iter_mut()
|
||||
.find(|assignment| assignment.surface == surface_id)
|
||||
{
|
||||
assignment.input_port = input_port.to_owned();
|
||||
assignment.output_port = output_port;
|
||||
} else {
|
||||
profile.assignments.push(Assignment {
|
||||
surface: surface_id.to_owned(),
|
||||
input_port: input_port.to_owned(),
|
||||
output_port,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Updates the remembered UI view for one profile.
|
||||
pub fn set_last_view(&mut self, profile_id: &str, view: UiView) -> Result<(), ConfigError> {
|
||||
find_profile_mut(&mut self.raw.profiles, profile_id)?.last_view = view;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates restart state whose observations are always explicitly stale.
|
||||
pub fn startup(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
policy: crate::StartupPolicy,
|
||||
write_ceiling: f64,
|
||||
) -> Result<StartupState, ConfigError> {
|
||||
let write_ceiling = Gain::new(write_ceiling)
|
||||
.map_err(|error| ConfigError::validation("write_ceiling", error.to_string()))?;
|
||||
let profile = self
|
||||
.raw
|
||||
.profiles
|
||||
.iter()
|
||||
.find(|profile| profile.id == profile_id)
|
||||
.ok_or_else(|| {
|
||||
ConfigError::validation("profile", format!("unknown profile {profile_id:?}"))
|
||||
})?;
|
||||
let cached_observations = profile
|
||||
.observed
|
||||
.iter()
|
||||
.map(|observation| CachedObservation {
|
||||
object: observation.object.clone(),
|
||||
gain: observation.gain.clone(),
|
||||
muted: observation.muted,
|
||||
stale: true,
|
||||
})
|
||||
.collect();
|
||||
let desired = profile
|
||||
.desired
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, intent)| {
|
||||
if intent.gain.is_some_and(|gain| gain > write_ceiling.get()) {
|
||||
return Err(ConfigError::validation(
|
||||
format!("profiles.desired[{index}].gain"),
|
||||
format!("exceeds write ceiling {}", write_ceiling.get()),
|
||||
));
|
||||
}
|
||||
Ok(DesiredWrite {
|
||||
object: intent.object.clone(),
|
||||
gain: intent.gain,
|
||||
muted: intent.muted,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(StartupState {
|
||||
policy,
|
||||
cached_observations,
|
||||
desired,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A restart-only observation that cannot be mistaken for current backend data.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CachedObservation {
|
||||
object: String,
|
||||
gain: Vec<f64>,
|
||||
muted: bool,
|
||||
stale: bool,
|
||||
}
|
||||
|
||||
impl CachedObservation {
|
||||
/// Stable virtual object identifier.
|
||||
pub fn object(&self) -> &str {
|
||||
&self.object
|
||||
}
|
||||
|
||||
/// Cached per-channel gains retained for display only.
|
||||
pub fn gain(&self) -> &[f64] {
|
||||
&self.gain
|
||||
}
|
||||
|
||||
/// Cached mute observation.
|
||||
pub const fn muted(&self) -> bool {
|
||||
self.muted
|
||||
}
|
||||
|
||||
/// Cached observations are always stale until live discovery replaces them.
|
||||
pub const fn is_stale(&self) -> bool {
|
||||
self.stale
|
||||
}
|
||||
}
|
||||
|
||||
/// A validated desired object write, with absent properties left unchanged.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DesiredWrite {
|
||||
object: String,
|
||||
gain: Option<f64>,
|
||||
muted: Option<bool>,
|
||||
}
|
||||
|
||||
impl DesiredWrite {
|
||||
/// Stable virtual object identifier.
|
||||
pub fn object(&self) -> &str {
|
||||
&self.object
|
||||
}
|
||||
|
||||
/// Desired scalar gain, when one was saved.
|
||||
pub const fn gain(&self) -> Option<f64> {
|
||||
self.gain
|
||||
}
|
||||
|
||||
/// Desired mute state, when one was saved.
|
||||
pub const fn muted(&self) -> Option<bool> {
|
||||
self.muted
|
||||
}
|
||||
}
|
||||
|
||||
/// Validated restart data with an explicit adopt/restore policy.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct StartupState {
|
||||
policy: crate::StartupPolicy,
|
||||
cached_observations: Vec<CachedObservation>,
|
||||
desired: Vec<DesiredWrite>,
|
||||
}
|
||||
|
||||
impl StartupState {
|
||||
/// Observations retained for display but never treated as fresh.
|
||||
pub fn cached_observations(&self) -> &[CachedObservation] {
|
||||
&self.cached_observations
|
||||
}
|
||||
|
||||
/// Saved intents remain visible even when startup adopts live state.
|
||||
pub fn desired_intents(&self) -> &[DesiredWrite] {
|
||||
&self.desired
|
||||
}
|
||||
|
||||
/// Returns the explicit write for a newly discovered application only when
|
||||
/// the profile selected restore policy.
|
||||
pub fn application_joined(&self, application_id: &str) -> Vec<DesiredWrite> {
|
||||
if self.policy != crate::StartupPolicy::Restore {
|
||||
return Vec::new();
|
||||
}
|
||||
self.desired
|
||||
.iter()
|
||||
.filter(|intent| intent.object == application_id)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_profiles(profiles: &[ProfileState]) -> Result<(), ConfigError> {
|
||||
let mut profile_ids = BTreeSet::new();
|
||||
for (profile_index, profile) in profiles.iter().enumerate() {
|
||||
parse_id::<ProfileId>(&profile.id, &format!("profiles[{profile_index}].id"))?;
|
||||
if !profile_ids.insert(&profile.id) {
|
||||
return Err(ConfigError::validation(
|
||||
format!("profiles[{profile_index}].id"),
|
||||
"duplicate profile state",
|
||||
));
|
||||
}
|
||||
validate_observed(profile_index, &profile.observed)?;
|
||||
validate_desired(profile_index, &profile.desired)?;
|
||||
validate_assignments(profile_index, &profile.assignments)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_observed(profile: usize, objects: &[ObservedObject]) -> Result<(), ConfigError> {
|
||||
let mut ids = BTreeSet::new();
|
||||
for (index, object) in objects.iter().enumerate() {
|
||||
let base = format!("profiles[{profile}].observed[{index}]");
|
||||
parse_id::<ApplicationId>(&object.object, &format!("{base}.object"))?;
|
||||
if !ids.insert(&object.object) {
|
||||
return Err(ConfigError::validation(
|
||||
format!("{base}.object"),
|
||||
"duplicate observed object",
|
||||
));
|
||||
}
|
||||
let gains = object
|
||||
.gain
|
||||
.iter()
|
||||
.copied()
|
||||
.map(Gain::new)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|error| ConfigError::validation(format!("{base}.gain"), error.to_string()))?;
|
||||
ChannelGains::new(gains)
|
||||
.map_err(|error| ConfigError::validation(format!("{base}.gain"), error.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_desired(profile: usize, objects: &[DesiredObject]) -> Result<(), ConfigError> {
|
||||
let mut ids = BTreeSet::new();
|
||||
for (index, object) in objects.iter().enumerate() {
|
||||
let base = format!("profiles[{profile}].desired[{index}]");
|
||||
parse_id::<ApplicationId>(&object.object, &format!("{base}.object"))?;
|
||||
if !ids.insert(&object.object) {
|
||||
return Err(ConfigError::validation(
|
||||
format!("{base}.object"),
|
||||
"duplicate desired object",
|
||||
));
|
||||
}
|
||||
if object.gain.is_none() && object.muted.is_none() {
|
||||
return Err(ConfigError::validation(
|
||||
base,
|
||||
"at least one desired gain or mute value is required",
|
||||
));
|
||||
}
|
||||
if let Some(gain) = object.gain {
|
||||
Gain::new(gain).map_err(|error| {
|
||||
ConfigError::validation(format!("{base}.gain"), error.to_string())
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_assignments(profile: usize, assignments: &[Assignment]) -> Result<(), ConfigError> {
|
||||
let mut ids = BTreeSet::new();
|
||||
for (index, assignment) in assignments.iter().enumerate() {
|
||||
let base = format!("profiles[{profile}].assignments[{index}]");
|
||||
parse_id::<SurfaceId>(&assignment.surface, &format!("{base}.surface"))?;
|
||||
if !ids.insert(&assignment.surface) {
|
||||
return Err(ConfigError::validation(
|
||||
format!("{base}.surface"),
|
||||
"duplicate surface assignment",
|
||||
));
|
||||
}
|
||||
if assignment.input_port.is_empty() {
|
||||
return Err(ConfigError::validation(
|
||||
format!("{base}.input_port"),
|
||||
"must not be empty",
|
||||
));
|
||||
}
|
||||
if assignment.output_port.as_deref().is_some_and(str::is_empty) {
|
||||
return Err(ConfigError::validation(
|
||||
format!("{base}.output_port"),
|
||||
"must not be empty when present",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_profile_mut<'a>(
|
||||
profiles: &'a mut [ProfileState],
|
||||
profile_id: &str,
|
||||
) -> Result<&'a mut ProfileState, ConfigError> {
|
||||
profiles
|
||||
.iter_mut()
|
||||
.find(|profile| profile.id == profile_id)
|
||||
.ok_or_else(|| {
|
||||
ConfigError::validation("profile", format!("unknown profile {profile_id:?}"))
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
use std::{cell::Cell, rc::Rc, time::Duration};
|
||||
|
||||
use fader_config::{
|
||||
CheckpointCoordinator, CheckpointSink, Clock, PersistedState, PersistenceError, StartupPolicy,
|
||||
UiView,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn sustained_movement_has_bounded_writes_and_shutdown_persists_the_final_value() {
|
||||
let clock = FakeClock::default();
|
||||
let sink = RecordingSink::default();
|
||||
let mut checkpoints = CheckpointCoordinator::new(clock.clone(), sink);
|
||||
let mut state = state_with_observation();
|
||||
|
||||
for step in 0..50 {
|
||||
state
|
||||
.set_desired("desktop", "music", Some(f64::from(step) / 50.0), None)
|
||||
.unwrap();
|
||||
checkpoints.mark_dirty(state.clone());
|
||||
checkpoints.poll().unwrap();
|
||||
clock.advance(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
checkpoints.sink().documents.len(),
|
||||
2,
|
||||
"2s maximum bounds writes"
|
||||
);
|
||||
checkpoints.shutdown().unwrap();
|
||||
assert_eq!(checkpoints.sink().documents.len(), 3);
|
||||
let final_state = PersistedState::parse(checkpoints.sink().documents.last().unwrap()).unwrap();
|
||||
let startup = final_state
|
||||
.startup("desktop", StartupPolicy::Restore, 1.0)
|
||||
.unwrap();
|
||||
let writes = startup.application_joined("music");
|
||||
assert_eq!(writes.len(), 1);
|
||||
assert_eq!(writes[0].gain(), Some(0.98));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quiet_period_flushes_after_debounce_not_before() {
|
||||
let clock = FakeClock::default();
|
||||
let mut checkpoints = CheckpointCoordinator::new(clock.clone(), RecordingSink::default());
|
||||
checkpoints.mark_dirty(state_with_observation());
|
||||
|
||||
clock.advance(Duration::from_millis(499));
|
||||
checkpoints.poll().unwrap();
|
||||
assert!(checkpoints.sink().documents.is_empty());
|
||||
clock.advance(Duration::from_millis(1));
|
||||
checkpoints.poll().unwrap();
|
||||
assert_eq!(checkpoints.sink().documents.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_marks_cached_observations_stale_and_has_no_ephemeral_state() {
|
||||
let state = state_with_observation();
|
||||
let encoded = state.to_toml().unwrap();
|
||||
assert!(!encoded.contains("backend_id"));
|
||||
assert!(!encoded.contains("pending"));
|
||||
assert!(!encoded.contains("operation"));
|
||||
|
||||
let restarted = PersistedState::parse(&encoded).unwrap();
|
||||
let startup = restarted
|
||||
.startup("desktop", StartupPolicy::Adopt, 1.0)
|
||||
.unwrap();
|
||||
assert_eq!(startup.cached_observations().len(), 1);
|
||||
assert!(startup.cached_observations()[0].is_stale());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_intent_survives_but_only_explicit_restore_emits_a_join_write() {
|
||||
let mut state = state_with_observation();
|
||||
state
|
||||
.set_desired("desktop", "music", Some(0.7), Some(true))
|
||||
.unwrap();
|
||||
let restarted = PersistedState::parse(&state.to_toml().unwrap()).unwrap();
|
||||
|
||||
let adopt = restarted
|
||||
.startup("desktop", StartupPolicy::Adopt, 1.0)
|
||||
.unwrap();
|
||||
assert!(adopt.application_joined("music").is_empty());
|
||||
assert_eq!(adopt.desired_intents().len(), 1, "intent remains visible");
|
||||
|
||||
let restore = restarted
|
||||
.startup("desktop", StartupPolicy::Restore, 1.0)
|
||||
.unwrap();
|
||||
let writes = restore.application_joined("music");
|
||||
assert_eq!(writes.len(), 1);
|
||||
assert_eq!(writes[0].gain(), Some(0.7));
|
||||
assert_eq!(writes[0].muted(), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkpoint_mutations_validate_observations_assignments_views_and_restore_bounds() {
|
||||
let mut state = state_with_observation();
|
||||
state
|
||||
.set_observed("desktop", "music", &[0.8, 0.4], true)
|
||||
.unwrap();
|
||||
state
|
||||
.set_surface_assignment("desktop", "desk-left", "input:1", Some("output:1"))
|
||||
.unwrap();
|
||||
state.set_last_view("desktop", UiView::Devices).unwrap();
|
||||
state
|
||||
.set_desired("desktop", "music", Some(1.5), None)
|
||||
.unwrap();
|
||||
|
||||
let encoded = state.to_toml().unwrap();
|
||||
assert!(encoded.contains("last_view = \"devices\""));
|
||||
assert!(encoded.contains("surface = \"desk-left\""));
|
||||
let error = state
|
||||
.startup("desktop", StartupPolicy::Restore, 1.0)
|
||||
.expect_err("restore must enforce the profile write ceiling");
|
||||
assert!(error.to_string().contains("write ceiling"));
|
||||
}
|
||||
|
||||
fn state_with_observation() -> PersistedState {
|
||||
PersistedState::parse(
|
||||
r#"
|
||||
schema_version = 1
|
||||
[[profiles]]
|
||||
id = "desktop"
|
||||
last_view = "mixer"
|
||||
[[profiles.observed]]
|
||||
object = "music"
|
||||
gain = [0.5, 0.25]
|
||||
muted = false
|
||||
"#,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct FakeClock(Rc<Cell<Duration>>);
|
||||
|
||||
impl FakeClock {
|
||||
fn advance(&self, duration: Duration) {
|
||||
self.0.set(self.0.get() + duration);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for FakeClock {
|
||||
fn now(&self) -> Duration {
|
||||
self.0.get()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RecordingSink {
|
||||
documents: Vec<String>,
|
||||
}
|
||||
|
||||
impl CheckpointSink for RecordingSink {
|
||||
fn write(&mut self, state: &PersistedState) -> Result<(), PersistenceError> {
|
||||
self.documents.push(state.to_toml().expect("valid state"));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,832 @@
|
|||
use fader_config::{
|
||||
Action, MessageKind, MixerLayoutEntry, ProfileDocument, SelectorDraft, SelectorField,
|
||||
SelectorPattern, TargetKind,
|
||||
};
|
||||
|
||||
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
|
||||
|
||||
#[test]
|
||||
fn selector_mode_edit_survives_serialization_without_replacing_selectors() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
let original = draft.preview().unwrap().applications()[0]
|
||||
.selectors()
|
||||
.to_vec();
|
||||
draft
|
||||
.set_application_selector_mode("music", fader_config::SelectorMode::All)
|
||||
.unwrap();
|
||||
let saved = draft.source();
|
||||
let restored = ProfileDocument::parse(&saved).unwrap().preview().unwrap();
|
||||
assert_eq!(
|
||||
restored.applications()[0].selector_mode(),
|
||||
fader_config::SelectorMode::All
|
||||
);
|
||||
assert_eq!(restored.applications()[0].selectors(), original);
|
||||
assert!(
|
||||
draft
|
||||
.set_application_selector_mode("missing", fader_config::SelectorMode::Any)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(draft.source(), saved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_surface_clears_its_bindings_and_default_controller_atomically() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
|
||||
draft.remove_surface("desk-left").unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
assert!(profile.surfaces().is_empty());
|
||||
assert!(profile.bindings().is_empty());
|
||||
assert_eq!(profile.default_controller(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_labels_can_be_renamed_without_changing_routing() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
|
||||
draft.set_application_label("music", "Listening").unwrap();
|
||||
draft.set_group_label("media", "Entertainment").unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
assert_eq!(profile.applications()[0].label(), "Listening");
|
||||
assert_eq!(profile.groups()[0].label(), "Entertainment");
|
||||
assert_eq!(profile.groups()[0].members(), &["music", "browser"]);
|
||||
assert_eq!(profile.faders()[0].target_id(), "media");
|
||||
assert_eq!(profile.bindings().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binding_edits_materialize_an_omitted_optional_binding_array() {
|
||||
let source = PROFILE.split("[[bindings]]").next().unwrap();
|
||||
assert!(ProfileDocument::parse(&format!("{source}\n[bindings]\n")).is_err());
|
||||
let mut draft = ProfileDocument::parse(source).unwrap();
|
||||
|
||||
draft
|
||||
.remove_bindings("media-fader", Action::Volume)
|
||||
.unwrap();
|
||||
draft
|
||||
.set_binding(
|
||||
"desk-left",
|
||||
"media-fader",
|
||||
Action::Volume,
|
||||
MessageKind::Cc,
|
||||
1,
|
||||
7,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
assert_eq!(profile.bindings().len(), 1);
|
||||
assert_eq!(profile.bindings()[0].fader(), "media-fader");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_edits_materialize_omitted_optional_arrays() {
|
||||
let mut draft = ProfileDocument::parse(
|
||||
r#"schema_version = 1
|
||||
id = "minimal"
|
||||
startup = "adopt"
|
||||
new_stream = "adopt"
|
||||
|
||||
[audio]
|
||||
adapter = "auto"
|
||||
preference = ["pulse", "pipewire"]
|
||||
max_gain = 1.0
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
draft
|
||||
.add_application(
|
||||
"music",
|
||||
"Music",
|
||||
&[SelectorDraft {
|
||||
field: SelectorField::ApplicationName,
|
||||
pattern: SelectorPattern::Exact("Music Player".into()),
|
||||
}],
|
||||
)
|
||||
.unwrap();
|
||||
draft.add_group("media", "Media", &["music"]).unwrap();
|
||||
draft
|
||||
.add_fader("media-fader", TargetKind::Group, "media", true, 0.02)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
assert_eq!(profile.applications()[0].id(), "music");
|
||||
assert_eq!(profile.groups()[0].id(), "media");
|
||||
assert_eq!(profile.faders()[0].id(), "media-fader");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixer_objects_are_created_and_removed_as_atomic_valid_units() {
|
||||
let mut draft = ProfileDocument::empty("default").unwrap();
|
||||
draft
|
||||
.add_application_fader(
|
||||
"chat",
|
||||
"Chat",
|
||||
&SelectorDraft {
|
||||
field: SelectorField::ApplicationName,
|
||||
pattern: SelectorPattern::Exact("__unconfigured_chat__".into()),
|
||||
},
|
||||
"chat-fader",
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
draft
|
||||
.add_group_fader("players", "Players", "players-fader", 1)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
assert_eq!(profile.applications()[0].id(), "chat");
|
||||
assert!(profile.groups()[0].members().is_empty());
|
||||
assert_eq!(profile.faders().len(), 3);
|
||||
assert!(matches!(
|
||||
&profile.mixer_layout()[0],
|
||||
MixerLayoutEntry::Fader { fader, .. } if fader == "chat-fader"
|
||||
));
|
||||
assert!(matches!(
|
||||
&profile.mixer_layout()[1],
|
||||
MixerLayoutEntry::Fader { fader, .. } if fader == "players-fader"
|
||||
));
|
||||
|
||||
draft.remove_mixer_fader("chat-fader").unwrap();
|
||||
draft.remove_mixer_fader("players-fader").unwrap();
|
||||
let profile = draft.preview().unwrap();
|
||||
assert!(profile.applications().is_empty());
|
||||
assert!(profile.groups().is_empty());
|
||||
assert_eq!(profile.faders().len(), 1);
|
||||
assert_eq!(profile.faders()[0].id(), "master-fader");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unnamed_separators_can_be_created_renamed_and_reloaded() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft.add_separator("spacer", "", 0).unwrap();
|
||||
draft.add_separator("divider", "Divider", 1).unwrap();
|
||||
draft.set_separator_label("divider", "").unwrap();
|
||||
let reloaded = ProfileDocument::parse(&draft.finish().unwrap()).unwrap();
|
||||
let profile = reloaded.preview().unwrap();
|
||||
for entry in &profile.mixer_layout()[..2] {
|
||||
assert!(matches!(entry, MixerLayoutEntry::Separator { label, .. } if label.is_empty()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separator_presentation_round_trips_without_changing_order() {
|
||||
use fader_config::{SeparatorDecoration, SeparatorSize};
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft.add_separator("heading", "Heading", 0).unwrap();
|
||||
draft
|
||||
.set_separator_presentation("heading", SeparatorSize::Fill, SeparatorDecoration::Double)
|
||||
.unwrap();
|
||||
let draft = ProfileDocument::parse(&draft.finish().unwrap()).unwrap();
|
||||
assert!(matches!(
|
||||
&draft.preview().unwrap().mixer_layout()[0],
|
||||
MixerLayoutEntry::Separator {
|
||||
size: SeparatorSize::Fill,
|
||||
decoration: SeparatorDecoration::Double,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(
|
||||
fader_config::Profile::parse(&draft.source().replace("size = \"fill\"", "size = \"huge\""))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_note_feedback_preserves_address_and_allows_configured_protocols() {
|
||||
let mut draft = ProfileDocument::empty("fresh").unwrap();
|
||||
draft
|
||||
.add_surface(
|
||||
"controller",
|
||||
"Controller",
|
||||
"Controller MIDI",
|
||||
Some("Controller MIDI"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
for (kind, channel, number, supported) in [
|
||||
(MessageKind::Note, 1, 0, true),
|
||||
(MessageKind::Note, 1, 64, true),
|
||||
(MessageKind::Note, 1, 71, true),
|
||||
(MessageKind::Note, 1, 72, true),
|
||||
(MessageKind::Note, 1, 82, true),
|
||||
(MessageKind::Note, 1, 89, true),
|
||||
(MessageKind::Note, 1, 98, true),
|
||||
(MessageKind::Note, 2, 64, true),
|
||||
(MessageKind::Note, 16, 127, true),
|
||||
(MessageKind::Cc, 1, 64, false),
|
||||
] {
|
||||
draft
|
||||
.set_binding(
|
||||
"controller",
|
||||
"master-fader",
|
||||
Action::ToggleMute,
|
||||
kind,
|
||||
channel,
|
||||
number,
|
||||
)
|
||||
.unwrap();
|
||||
let profile = draft.preview().unwrap();
|
||||
let feedback = profile.effective_feedback(&profile.bindings()[0]);
|
||||
assert_eq!(feedback.is_some(), supported);
|
||||
if let Some(feedback) = feedback {
|
||||
assert_eq!(
|
||||
(
|
||||
feedback.channel(),
|
||||
feedback.number(),
|
||||
feedback.on(),
|
||||
feedback.off()
|
||||
),
|
||||
(channel, number, 127, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
draft
|
||||
.set_binding(
|
||||
"controller",
|
||||
"master-fader",
|
||||
Action::ToggleMute,
|
||||
MessageKind::Note,
|
||||
1,
|
||||
64,
|
||||
)
|
||||
.unwrap();
|
||||
let source = draft.source();
|
||||
for unsupported in [
|
||||
source.replace("output_port = \"Controller MIDI\"", ""),
|
||||
source
|
||||
.replace("action = \"toggle_mute\"", "action = \"volume\"")
|
||||
.replace("kind = \"note\"", "kind = \"cc\"")
|
||||
.replace("edge = \"press\"", ""),
|
||||
] {
|
||||
let profile = fader_config::Profile::parse(&unsupported).unwrap();
|
||||
assert!(profile.effective_feedback(&profile.bindings()[0]).is_none());
|
||||
}
|
||||
let explicit = format!(
|
||||
"{source}\nfeedback = {{ kind = \"cc\", channel = 3, number = 65, on = 3, off = 2 }}\n"
|
||||
);
|
||||
let profile = fader_config::Profile::parse(&explicit).unwrap();
|
||||
let feedback = profile.effective_feedback(&profile.bindings()[0]).unwrap();
|
||||
assert_eq!((feedback.number(), feedback.on()), (65, 3));
|
||||
assert_eq!(
|
||||
(feedback.message_kind(), feedback.channel(), feedback.off()),
|
||||
(MessageKind::Cc, 3, 2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_adds_a_discovered_midi_surface_with_durable_identity() {
|
||||
let mut draft = ProfileDocument::empty("default").unwrap();
|
||||
draft
|
||||
.add_surface(
|
||||
"apc-mini",
|
||||
"APC MINI",
|
||||
"APC MINI:APC MINI MIDI 1",
|
||||
Some("APC MINI:APC MINI MIDI 1"),
|
||||
Some("09e8"),
|
||||
Some("0028"),
|
||||
Some("Ver00.10"),
|
||||
Some("pci-0000:00:14.0-usb-0:1"),
|
||||
Some("36:0"),
|
||||
)
|
||||
.unwrap();
|
||||
draft.set_default_controller(Some("apc-mini")).unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
let surface = &profile.surfaces()[0];
|
||||
assert_eq!(surface.id(), "apc-mini");
|
||||
assert_eq!(surface.input_port(), "APC MINI:APC MINI MIDI 1");
|
||||
assert_eq!(surface.output_port(), Some("APC MINI:APC MINI MIDI 1"));
|
||||
assert_eq!(surface.usb_serial(), Some("Ver00.10"));
|
||||
assert_eq!(surface.manual_backend_id(), Some("36:0"));
|
||||
assert_eq!(profile.default_controller(), Some("apc-mini"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_creates_an_application_group_and_fader_as_valid_toml() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft
|
||||
.add_application(
|
||||
"chat",
|
||||
"Chat",
|
||||
&[SelectorDraft {
|
||||
field: SelectorField::ProcessBinary,
|
||||
pattern: SelectorPattern::Exact("signal-desktop".to_owned()),
|
||||
}],
|
||||
)
|
||||
.unwrap();
|
||||
draft
|
||||
.add_group("communications", "Communications", &["chat", "browser"])
|
||||
.unwrap();
|
||||
draft
|
||||
.add_fader(
|
||||
"communications-fader",
|
||||
TargetKind::Group,
|
||||
"communications",
|
||||
true,
|
||||
0.02,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
assert!(
|
||||
profile
|
||||
.applications()
|
||||
.iter()
|
||||
.any(|item| item.id() == "chat")
|
||||
);
|
||||
assert!(
|
||||
profile
|
||||
.groups()
|
||||
.iter()
|
||||
.any(|item| item.id() == "communications")
|
||||
);
|
||||
assert!(
|
||||
profile
|
||||
.faders()
|
||||
.iter()
|
||||
.any(|item| item.id() == "communications-fader")
|
||||
);
|
||||
ProfileDocument::parse(&draft.finish().unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_edits_and_referenced_deletes_roll_back_the_draft() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
let original = draft.source();
|
||||
|
||||
let invalid = draft
|
||||
.add_application(
|
||||
"broken",
|
||||
"Broken",
|
||||
&[SelectorDraft {
|
||||
field: SelectorField::ApplicationName,
|
||||
pattern: SelectorPattern::Regex("(".to_owned()),
|
||||
}],
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(invalid.to_string().contains("regex"));
|
||||
assert_eq!(draft.source(), original);
|
||||
|
||||
let referenced = draft.remove_application("browser").unwrap_err();
|
||||
assert!(referenced.to_string().contains("unknown application"));
|
||||
assert_eq!(draft.source(), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_applications_groups_and_faders_can_be_edited_and_deleted() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft
|
||||
.set_application(
|
||||
"browser",
|
||||
"Web",
|
||||
&[SelectorDraft {
|
||||
field: SelectorField::ProcessBinary,
|
||||
pattern: SelectorPattern::Exact("waterfox-bin".to_owned()),
|
||||
}],
|
||||
)
|
||||
.unwrap();
|
||||
draft.set_group("media", "Players", &["browser"]).unwrap();
|
||||
draft
|
||||
.set_fader(
|
||||
"media-fader",
|
||||
TargetKind::Application,
|
||||
"browser",
|
||||
false,
|
||||
0.05,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
assert_eq!(profile.applications()[1].label(), "Web");
|
||||
assert_eq!(profile.groups()[0].members(), &["browser"]);
|
||||
assert_eq!(profile.faders()[0].target_kind(), TargetKind::Application);
|
||||
assert!(!profile.faders()[0].pickup());
|
||||
|
||||
draft.remove_group("media").unwrap();
|
||||
draft.remove_fader("media-fader").unwrap_err();
|
||||
assert!(draft.source().contains("media-fader"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_group_members_preserves_the_configured_volume_mode_field() {
|
||||
let source = PROFILE.replace(
|
||||
"volume_mode = \"absolute\"",
|
||||
"volume_mode = \"absolute\" # user-owned group mode",
|
||||
);
|
||||
let mut draft = ProfileDocument::parse(&source).unwrap();
|
||||
|
||||
draft.set_group("media", "Players", &["browser"]).unwrap();
|
||||
|
||||
assert!(
|
||||
draft
|
||||
.source()
|
||||
.contains("volume_mode = \"absolute\" # user-owned group mode")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_sets_and_unsets_the_default_controller() {
|
||||
let source = PROFILE.replace("default_controller = \"desk-left\"\n", "");
|
||||
let mut draft = ProfileDocument::parse(&source).unwrap();
|
||||
draft.set_default_controller(Some("desk-left")).unwrap();
|
||||
assert_eq!(
|
||||
draft.preview().unwrap().default_controller(),
|
||||
Some("desk-left")
|
||||
);
|
||||
|
||||
let before_invalid = draft.source();
|
||||
let error = draft.set_default_controller(Some("missing")).unwrap_err();
|
||||
assert!(error.to_string().contains("unknown surface"));
|
||||
assert_eq!(draft.source(), before_invalid);
|
||||
|
||||
draft.set_default_controller(None).unwrap();
|
||||
assert_eq!(draft.preview().unwrap().default_controller(), None);
|
||||
assert!(!draft.source().contains("default_controller"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_theme_edit_is_profile_backed() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft.set_theme(fader_config::UiTheme::Nord).unwrap();
|
||||
assert_eq!(
|
||||
draft.preview().unwrap().theme(),
|
||||
fader_config::UiTheme::Nord
|
||||
);
|
||||
assert!(draft.source().contains("theme = \"nord\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_status_display_edit_is_profile_backed() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft
|
||||
.set_status_display(fader_config::StatusDisplayMode::Color)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
draft.preview().unwrap().status_display(),
|
||||
fader_config::StatusDisplayMode::Color
|
||||
);
|
||||
assert!(draft.source().contains("status_display = \"color\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_adds_bindings_and_rejects_duplicate_physical_controls() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft
|
||||
.add_binding(
|
||||
"desk-left",
|
||||
"media-fader",
|
||||
Action::Volume,
|
||||
MessageKind::Cc,
|
||||
1,
|
||||
49,
|
||||
)
|
||||
.unwrap();
|
||||
let before_duplicate = draft.source();
|
||||
let error = draft
|
||||
.add_binding(
|
||||
"desk-left",
|
||||
"media-fader",
|
||||
Action::ToggleMute,
|
||||
MessageKind::Cc,
|
||||
1,
|
||||
49,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("duplicate physical binding"));
|
||||
assert_eq!(draft.source(), before_duplicate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixer_layout_draft_reorders_separators_and_retains_hidden_faders() {
|
||||
let source = PROFILE.replacen(
|
||||
"[[bindings]]",
|
||||
"# separator comment must move with its entry\n[[mixer_layout]]\nkind = \"separator\"\nid = \"outputs\"\nlabel = \"Outputs\"\n\n[[bindings]]",
|
||||
1,
|
||||
);
|
||||
let mut draft = ProfileDocument::parse(&source).unwrap();
|
||||
draft
|
||||
.set_mixer_orientation(fader_config::MixerOrientation::Horizontal)
|
||||
.expect("mixer orientation must be editable");
|
||||
draft
|
||||
.set_fader_hidden("media-fader", true)
|
||||
.expect("fader must be hidden without deletion");
|
||||
draft
|
||||
.set_fader_density("media-fader", fader_config::FaderDensity::Thick)
|
||||
.expect("fader density must be editable");
|
||||
// Real sessions reopen a saved layout: parsed tables retain source positions.
|
||||
let saved = draft.finish().unwrap();
|
||||
let mut draft = ProfileDocument::parse(&saved).unwrap();
|
||||
draft
|
||||
.move_layout_entry("media-fader", 0)
|
||||
.expect("hidden fader must remain reorderable");
|
||||
draft
|
||||
.set_separator_label("outputs", "Main outputs")
|
||||
.expect("separator label must be editable");
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
assert_eq!(
|
||||
profile.mixer_orientation(),
|
||||
fader_config::MixerOrientation::Horizontal
|
||||
);
|
||||
assert_eq!(
|
||||
profile.mixer_layout(),
|
||||
[
|
||||
MixerLayoutEntry::Fader {
|
||||
fader: "media-fader".to_owned(),
|
||||
hidden: true,
|
||||
density: fader_config::FaderDensity::Thick,
|
||||
},
|
||||
MixerLayoutEntry::Separator {
|
||||
id: "outputs".to_owned(),
|
||||
label: "Main outputs".to_owned(),
|
||||
size: fader_config::SeparatorSize::Standard,
|
||||
decoration: fader_config::SeparatorDecoration::Line,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(profile.faders().len(), 1, "hiding must not delete routing");
|
||||
assert!(
|
||||
draft
|
||||
.source()
|
||||
.contains("# separator comment must move with its entry")
|
||||
);
|
||||
|
||||
draft.remove_separator("outputs").unwrap();
|
||||
draft.set_fader_hidden("media-fader", false).unwrap();
|
||||
assert_eq!(
|
||||
draft.preview().unwrap().mixer_layout(),
|
||||
[MixerLayoutEntry::Fader {
|
||||
fader: "media-fader".to_owned(),
|
||||
hidden: false,
|
||||
density: fader_config::FaderDensity::Thick,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_layout_moves_and_insertions_survive_repeated_reloads() {
|
||||
let source = format!(
|
||||
"{PROFILE}\n\
|
||||
[[faders]]\nid = \"other-fader\"\ntarget = {{ kind = \"group\", id = \"media\" }}\npickup = true\npickup_tolerance = 0.02\n\
|
||||
# first fader comment\n[[mixer_layout]]\nkind = \"fader\"\nfader = \"media-fader\"\ndensity = \"slim\"\n\
|
||||
# separator comment\n[[mixer_layout]]\nkind = \"separator\"\nid = \"heading\"\nlabel = \"Heading\"\n\
|
||||
# hidden fader comment\n[[mixer_layout]]\nkind = \"fader\"\nfader = \"other-fader\"\nhidden = true\n"
|
||||
);
|
||||
let mut draft = ProfileDocument::parse(&source).unwrap();
|
||||
let ids = |draft: &ProfileDocument| {
|
||||
draft
|
||||
.preview()
|
||||
.unwrap()
|
||||
.mixer_layout()
|
||||
.iter()
|
||||
.map(|entry| match entry {
|
||||
MixerLayoutEntry::Fader { fader, .. } => fader.clone(),
|
||||
MixerLayoutEntry::Separator { id, .. } => id.clone(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for (id, position, expected) in [
|
||||
("media-fader", 2, ["heading", "other-fader", "media-fader"]),
|
||||
("media-fader", 0, ["media-fader", "heading", "other-fader"]),
|
||||
("other-fader", 0, ["other-fader", "media-fader", "heading"]),
|
||||
("heading", 1, ["other-fader", "heading", "media-fader"]),
|
||||
] {
|
||||
draft.move_layout_entry(id, position).unwrap();
|
||||
assert_eq!(ids(&draft), expected);
|
||||
draft = ProfileDocument::parse(&draft.finish().unwrap()).unwrap();
|
||||
assert_eq!(ids(&draft), expected);
|
||||
}
|
||||
draft
|
||||
.add_separator("new-heading", "New heading", 0)
|
||||
.unwrap();
|
||||
draft = ProfileDocument::parse(&draft.finish().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
ids(&draft),
|
||||
["new-heading", "other-fader", "heading", "media-fader"]
|
||||
);
|
||||
let saved = draft.source();
|
||||
for comment in [
|
||||
"first fader comment",
|
||||
"separator comment",
|
||||
"hidden fader comment",
|
||||
] {
|
||||
assert_eq!(saved.matches(comment).count(), 1);
|
||||
}
|
||||
let profile = draft.preview().unwrap();
|
||||
assert!(matches!(
|
||||
&profile.mixer_layout()[1],
|
||||
MixerLayoutEntry::Fader { hidden: true, .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
&profile.mixer_layout()[3],
|
||||
MixerLayoutEntry::Fader {
|
||||
density: fader_config::FaderDensity::Slim,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_eq!(
|
||||
profile.bindings(),
|
||||
fader_config::Profile::parse(PROFILE).unwrap().bindings()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selector_and_binding_edits_preserve_unrelated_capture_and_actions() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft
|
||||
.add_application(
|
||||
"multi",
|
||||
"Multi",
|
||||
&[
|
||||
SelectorDraft {
|
||||
field: SelectorField::ApplicationName,
|
||||
pattern: SelectorPattern::Exact("Old".to_owned()),
|
||||
},
|
||||
SelectorDraft {
|
||||
field: SelectorField::MediaName,
|
||||
pattern: SelectorPattern::Regex("keep-me".to_owned()),
|
||||
},
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
draft
|
||||
.set_application_selector(
|
||||
"multi",
|
||||
0,
|
||||
&SelectorDraft {
|
||||
field: SelectorField::ProcessBinary,
|
||||
pattern: SelectorPattern::Exact("player-bin".to_owned()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
draft
|
||||
.set_binding(
|
||||
"desk-left",
|
||||
"media-fader",
|
||||
Action::Volume,
|
||||
MessageKind::Cc,
|
||||
1,
|
||||
7,
|
||||
)
|
||||
.unwrap();
|
||||
let before_conflict = draft.source();
|
||||
let conflict = draft
|
||||
.set_binding(
|
||||
"desk-left",
|
||||
"media-fader",
|
||||
Action::ToggleMute,
|
||||
MessageKind::Cc,
|
||||
1,
|
||||
7,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(conflict.to_string().contains("duplicate physical binding"));
|
||||
assert_eq!(draft.source(), before_conflict);
|
||||
draft
|
||||
.remove_bindings("media-fader", Action::ToggleMute)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
let multi = profile
|
||||
.applications()
|
||||
.iter()
|
||||
.find(|application| application.id() == "multi")
|
||||
.unwrap();
|
||||
assert_eq!(multi.selectors().len(), 2);
|
||||
assert_eq!(multi.selectors()[0].pattern(), ("player-bin", false));
|
||||
assert_eq!(multi.selectors()[1].pattern(), ("keep-me", true));
|
||||
assert!(profile.bindings().iter().any(|binding| {
|
||||
binding.fader() == "media-fader"
|
||||
&& binding.action() == Action::Volume
|
||||
&& binding.number() == 7
|
||||
}));
|
||||
assert!(!profile.bindings().iter().any(|binding| {
|
||||
binding.fader() == "media-fader" && binding.action() == Action::ToggleMute
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_a_mute_binding_moves_its_feedback_to_the_new_control() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft
|
||||
.set_binding(
|
||||
"desk-left",
|
||||
"media-fader",
|
||||
Action::ToggleMute,
|
||||
MessageKind::Note,
|
||||
1,
|
||||
41,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
let binding = profile
|
||||
.bindings()
|
||||
.iter()
|
||||
.find(|binding| binding.action() == Action::ToggleMute)
|
||||
.unwrap();
|
||||
assert_eq!(binding.number(), 41);
|
||||
let feedback = binding.feedback().expect("existing feedback is retained");
|
||||
assert_eq!(feedback.number(), 41);
|
||||
assert_eq!((feedback.on(), feedback.off()), (127, 0));
|
||||
|
||||
let independently_mapped = PROFILE.replace(
|
||||
"feedback = { kind = \"note\", channel = 1, number = 32, on = 127, off = 0 }",
|
||||
"feedback = { kind = \"note\", channel = 1, number = 33, on = 127, off = 0 }",
|
||||
);
|
||||
let mut draft = ProfileDocument::parse(&independently_mapped).unwrap();
|
||||
draft
|
||||
.set_binding(
|
||||
"desk-left",
|
||||
"media-fader",
|
||||
Action::ToggleMute,
|
||||
MessageKind::Note,
|
||||
1,
|
||||
41,
|
||||
)
|
||||
.unwrap();
|
||||
let profile = draft.preview().unwrap();
|
||||
let feedback = profile
|
||||
.bindings()
|
||||
.iter()
|
||||
.find(|binding| binding.action() == Action::ToggleMute)
|
||||
.and_then(|binding| binding.feedback())
|
||||
.unwrap();
|
||||
assert_eq!(feedback.number(), 33);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_mute_binding_inherits_unambiguous_surface_feedback_values() {
|
||||
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
|
||||
draft
|
||||
.add_fader("second-media-fader", TargetKind::Group, "media", true, 0.02)
|
||||
.unwrap();
|
||||
draft
|
||||
.set_binding(
|
||||
"desk-left",
|
||||
"second-media-fader",
|
||||
Action::ToggleMute,
|
||||
MessageKind::Note,
|
||||
1,
|
||||
42,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
let feedback = profile
|
||||
.bindings()
|
||||
.iter()
|
||||
.find(|binding| binding.fader() == "second-media-fader")
|
||||
.and_then(|binding| binding.feedback())
|
||||
.expect("the established surface feedback convention is inherited");
|
||||
assert_eq!(feedback.number(), 42);
|
||||
assert_eq!((feedback.on(), feedback.off()), (127, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_mute_binding_does_not_guess_between_conflicting_feedback_values() {
|
||||
let source = format!(
|
||||
"{PROFILE}\n\
|
||||
[[faders]]\n\
|
||||
id = \"alternate-media-fader\"\n\
|
||||
target = {{ kind = \"group\", id = \"media\" }}\n\
|
||||
pickup = true\n\
|
||||
pickup_tolerance = 0.02\n\n\
|
||||
[[bindings]]\n\
|
||||
surface = \"desk-left\"\n\
|
||||
fader = \"alternate-media-fader\"\n\
|
||||
action = \"toggle_mute\"\n\
|
||||
edge = \"press\"\n\
|
||||
message = {{ kind = \"note\", channel = 1, number = 33 }}\n\
|
||||
feedback = {{ kind = \"note\", channel = 1, number = 33, on = 1, off = 0 }}\n"
|
||||
);
|
||||
let mut draft = ProfileDocument::parse(&source).unwrap();
|
||||
draft
|
||||
.add_fader("third-media-fader", TargetKind::Group, "media", true, 0.02)
|
||||
.unwrap();
|
||||
draft
|
||||
.set_binding(
|
||||
"desk-left",
|
||||
"third-media-fader",
|
||||
Action::ToggleMute,
|
||||
MessageKind::Note,
|
||||
1,
|
||||
42,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let profile = draft.preview().unwrap();
|
||||
let binding = profile
|
||||
.bindings()
|
||||
.iter()
|
||||
.find(|binding| binding.fader() == "third-media-fader")
|
||||
.unwrap();
|
||||
assert!(binding.feedback().is_none());
|
||||
}
|
||||
|
|
@ -0,0 +1,278 @@
|
|||
use std::{
|
||||
fs,
|
||||
io::{self, Read},
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use fader_config::{
|
||||
ActiveConfig, AtomicFile, ConfigError, MigrationError, PersistenceError, ProfileDocument,
|
||||
ProfileUpgrade, StateLoad, XdgEnvironment, XdgPaths, migrate_profile, upgrade_profile,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn active_profile_pointer_is_strict_and_round_trips() {
|
||||
let active = ActiveConfig::new("desktop").unwrap();
|
||||
let encoded = active.to_toml().unwrap();
|
||||
assert_eq!(
|
||||
ActiveConfig::parse(&encoded)
|
||||
.unwrap()
|
||||
.active_profile()
|
||||
.as_str(),
|
||||
"desktop"
|
||||
);
|
||||
assert!(ActiveConfig::parse("schema_version = 1\nactive_profile = '../escape'").is_err());
|
||||
assert!(
|
||||
ActiveConfig::parse("schema_version = 1\nactive_profile = 'desktop'\nunknown = true")
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
use tempfile::tempdir;
|
||||
|
||||
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
|
||||
|
||||
#[test]
|
||||
fn xdg_paths_use_absolute_overrides_and_reject_unsafe_profile_names() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let home = root.path().join("home");
|
||||
let config = root.path().join("configuration");
|
||||
let state = root.path().join("state");
|
||||
let runtime = root.path().join("runtime");
|
||||
let paths = XdgPaths::resolve(&XdgEnvironment {
|
||||
home: home.clone(),
|
||||
config_home: Some(config.clone()),
|
||||
state_home: Some(state.clone()),
|
||||
runtime_dir: Some(runtime.clone()),
|
||||
})
|
||||
.expect("absolute XDG paths");
|
||||
|
||||
assert_eq!(paths.config_file(), config.join("fader_master/config.toml"));
|
||||
assert_eq!(paths.state_file(), state.join("fader_master/state.toml"));
|
||||
assert_eq!(
|
||||
paths.runtime_dir(),
|
||||
Some(runtime.join("fader_master").as_path())
|
||||
);
|
||||
assert_eq!(
|
||||
paths.profile_file("desktop").unwrap(),
|
||||
config.join("fader_master/profiles/desktop.toml")
|
||||
);
|
||||
assert_error_contains(paths.profile_file("../escape"), "profile ID");
|
||||
assert_error_contains(paths.profile_file("nested/name"), "profile ID");
|
||||
|
||||
let fallback = XdgPaths::resolve(&XdgEnvironment {
|
||||
home: home.clone(),
|
||||
config_home: Some(Path::new("relative").to_path_buf()),
|
||||
state_home: None,
|
||||
runtime_dir: None,
|
||||
})
|
||||
.expect("relative XDG override falls back according to the specification");
|
||||
assert_eq!(
|
||||
fallback.config_file(),
|
||||
home.join(".config/fader_master/config.toml")
|
||||
);
|
||||
assert_eq!(
|
||||
fallback.state_file(),
|
||||
home.join(".local/state/fader_master/state.toml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_layout_and_atomic_replacement_use_restrictive_modes() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().expect("secure application layout");
|
||||
assert_eq!(
|
||||
fs::metadata(paths.config_dir())
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode()
|
||||
& 0o777,
|
||||
0o700
|
||||
);
|
||||
|
||||
let target = paths.config_file();
|
||||
AtomicFile::write(&target, b"old").expect("initial write");
|
||||
AtomicFile::write(&target, b"new").expect("replacement write");
|
||||
assert_eq!(fs::read(&target).unwrap(), b"new");
|
||||
assert_eq!(
|
||||
fs::metadata(&target).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
assert!(
|
||||
fs::read_dir(target.parent().unwrap())
|
||||
.unwrap()
|
||||
.all(|entry| !entry
|
||||
.unwrap()
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.contains(".tmp")),
|
||||
"successful writes must not leave temporary files"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permission_failure_leaves_the_old_document_readable() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.config_file();
|
||||
AtomicFile::write(&target, b"old").unwrap();
|
||||
let directory = target.parent().unwrap();
|
||||
fs::set_permissions(directory, fs::Permissions::from_mode(0o500)).unwrap();
|
||||
let error = AtomicFile::write(&target, b"replacement").expect_err("directory is read-only");
|
||||
fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
PersistenceError::Io { source, .. }
|
||||
if source.kind() == io::ErrorKind::PermissionDenied
|
||||
));
|
||||
assert_eq!(fs::read(&target).unwrap(), b"old");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_write_failure_leaves_the_old_document_readable() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.config_file();
|
||||
AtomicFile::write(&target, b"old").unwrap();
|
||||
let mut failing = FailingReader { emitted: false };
|
||||
|
||||
assert!(AtomicFile::write_from(&target, &mut failing).is_err());
|
||||
assert_eq!(fs::read(&target).unwrap(), b"old");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_and_malformed_state_are_recoverable_without_rewriting_disk() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
assert!(matches!(paths.load_state().unwrap(), StateLoad::Missing));
|
||||
|
||||
AtomicFile::write(&paths.state_file(), b"not = [valid").unwrap();
|
||||
let malformed = paths.load_state().expect("malformed cache is recoverable");
|
||||
assert!(matches!(malformed, StateLoad::Malformed { .. }));
|
||||
assert_eq!(
|
||||
fs::read_to_string(paths.state_file()).unwrap(),
|
||||
"not = [valid"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_edits_preserve_comments_and_revalidate_the_result() {
|
||||
let source = PROFILE.replace("label = \"Music\"", "# favorite player\nlabel = \"Music\"");
|
||||
let mut document = ProfileDocument::parse(&source).expect("valid editable profile");
|
||||
document
|
||||
.set_application_label("music", "Listening")
|
||||
.expect("known application");
|
||||
let edited = document.finish().expect("edited profile remains valid");
|
||||
assert!(edited.contains("# favorite player"));
|
||||
assert!(edited.contains("label = \"Listening\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_keeps_a_backup_and_rejects_downgrades() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.profile_file("desktop").unwrap();
|
||||
AtomicFile::write(&target, b"legacy profile").unwrap();
|
||||
|
||||
let backup = migrate_profile(&target, 0, PROFILE).expect("forward migration");
|
||||
assert_eq!(fs::read_to_string(&backup).unwrap(), "legacy profile");
|
||||
assert!(fader_config::Profile::parse(&fs::read_to_string(&target).unwrap()).is_ok());
|
||||
|
||||
let result = migrate_profile(&target, 1, PROFILE);
|
||||
assert!(matches!(result, Err(MigrationError::Incompatible { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_upgrade_preserves_comments_and_backs_up_old_schema() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.profile_file("desktop").unwrap();
|
||||
let legacy = PROFILE
|
||||
.replace("schema_version = 1", "schema_version = 0")
|
||||
.replace("id = \"desktop\"", "# keep this comment\nid = \"desktop\"");
|
||||
AtomicFile::write(&target, legacy.as_bytes()).unwrap();
|
||||
|
||||
let outcome = upgrade_profile(&target).expect("known old schema upgrades");
|
||||
|
||||
let ProfileUpgrade::Upgraded { backup, from, to } = outcome else {
|
||||
panic!("old profile was not upgraded");
|
||||
};
|
||||
assert_eq!((from, to), (0, 1));
|
||||
assert_eq!(fs::read_to_string(backup).unwrap(), legacy);
|
||||
let upgraded = fs::read_to_string(target).unwrap();
|
||||
assert!(upgraded.contains("# keep this comment"));
|
||||
assert!(fader_config::Profile::parse(&upgraded).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_upgrade_never_rewrites_an_invalid_candidate() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.profile_file("broken").unwrap();
|
||||
let invalid = "schema_version = 0\nid = 'broken'\nunknown = true\n";
|
||||
AtomicFile::write(&target, invalid.as_bytes()).unwrap();
|
||||
|
||||
assert!(upgrade_profile(&target).is_err());
|
||||
assert_eq!(fs::read_to_string(&target).unwrap(), invalid);
|
||||
assert!(!target.with_file_name("broken.toml.v0.bak").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_upgrade_accepts_a_pre_versioned_document() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.profile_file("desktop").unwrap();
|
||||
let legacy = PROFILE.replacen("schema_version = 1\n", "", 1);
|
||||
AtomicFile::write(&target, legacy.as_bytes()).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
upgrade_profile(&target).unwrap(),
|
||||
ProfileUpgrade::Upgraded { from: 0, to: 1, .. }
|
||||
));
|
||||
assert!(fader_config::Profile::parse(&fs::read_to_string(target).unwrap()).is_ok());
|
||||
}
|
||||
|
||||
fn test_paths(root: &Path) -> XdgPaths {
|
||||
XdgPaths::resolve(&XdgEnvironment {
|
||||
home: root.join("home"),
|
||||
config_home: Some(root.join("config")),
|
||||
state_home: Some(root.join("state")),
|
||||
runtime_dir: Some(root.join("runtime")),
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn assert_error_contains<T>(result: Result<T, ConfigError>, needle: &str) {
|
||||
let error = result.err().expect("operation should fail").to_string();
|
||||
assert!(
|
||||
error.contains(needle),
|
||||
"expected {error:?} to contain {needle:?}"
|
||||
);
|
||||
}
|
||||
|
||||
struct FailingReader {
|
||||
emitted: bool,
|
||||
}
|
||||
|
||||
impl Read for FailingReader {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
if self.emitted {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::StorageFull,
|
||||
"injected full disk",
|
||||
));
|
||||
}
|
||||
self.emitted = true;
|
||||
let bytes = b"partial";
|
||||
buffer[..bytes.len()].copy_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,555 @@
|
|||
use fader_config::{DeviceProfile, MixerLayoutEntry, PersistedState, Profile, StartupPolicy};
|
||||
use fader_core::{StreamMetadata, VolumeMode};
|
||||
use std::time::Duration;
|
||||
|
||||
const EXAMPLE: &str = include_str!("../../examples/profiles/desktop.toml");
|
||||
const ARCH_PIPEWIRE: &str = include_str!("../../examples/profiles/arch-pipewire.toml");
|
||||
const ARCHITECTURE: &str = include_str!("../../architecture.md");
|
||||
|
||||
#[test]
|
||||
fn documented_media_profile_validates_and_round_trips_all_action_kinds() {
|
||||
let source = include_str!("../../examples/profiles/media-qbz.toml");
|
||||
let profile = Profile::parse(source).unwrap();
|
||||
assert_eq!(profile.media()[0].controls.len(), 14);
|
||||
assert_eq!(
|
||||
profile,
|
||||
Profile::parse(&profile.to_toml().unwrap()).unwrap()
|
||||
);
|
||||
let mut document = fader_config::ProfileDocument::parse(source).unwrap();
|
||||
document.set_media_entry(&profile.media()[0]).unwrap();
|
||||
assert_eq!(document.preview().unwrap().media(), profile.media());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_configuration_has_a_bounded_ipc_budget() {
|
||||
let mut source = EXAMPLE.to_owned();
|
||||
for n in 0..8 {
|
||||
source.push_str(&format!("\n[[media]]\nid = 'entry-{n}'\nlabel = 'Player'\nselector = {{ field = 'identity', pattern = 'Player' }}\n"));
|
||||
for c in 0..64 {
|
||||
source.push_str(&format!("[[media.controls]]\nid = 'control-{c}'\naction = {{ kind = 'playlist', id = '/{}' }}\n", "x".repeat(1000)));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
Profile::parse(&source)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("256 KiB")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_entries_round_trip_and_validate_selectors_and_midi_collisions() {
|
||||
let extra = r#"
|
||||
[[media]]
|
||||
id = "qbz"
|
||||
label = "QBZ"
|
||||
feedback_enabled = false
|
||||
selector = { field = "bus_name", pattern = "org.mpris.MediaPlayer2.com.blitzfc.qbz" }
|
||||
controls = [{ id = "play", action = { kind = "play" }, binding = { surface = "desk-left", message = { kind = "note", channel = 1, number = 40 } } }]
|
||||
"#;
|
||||
let source = format!("{EXAMPLE}\n{extra}");
|
||||
let profile = Profile::parse(&source).unwrap();
|
||||
let mut document = fader_config::ProfileDocument::parse(&source).unwrap();
|
||||
let mut entry = profile.media()[0].clone();
|
||||
entry.label = "Renamed QBZ".into();
|
||||
document.set_media_entry(&entry).unwrap();
|
||||
assert_eq!(document.preview().unwrap().media()[0].label, "Renamed QBZ");
|
||||
document.remove_surface("desk-left").unwrap();
|
||||
assert!(
|
||||
document.preview().unwrap().media()[0].controls[0]
|
||||
.binding
|
||||
.is_none()
|
||||
);
|
||||
document.remove_media_entry("qbz").unwrap();
|
||||
assert!(document.preview().unwrap().media().is_empty());
|
||||
assert_eq!(
|
||||
profile,
|
||||
Profile::parse(&profile.to_toml().unwrap()).unwrap()
|
||||
);
|
||||
assert!(Profile::parse(&source.replace("number = 40", "number = 32")).is_err());
|
||||
assert!(
|
||||
Profile::parse(&source.replace("field = \"bus_name\"", "field = \"unknown\"")).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_switches_override_explicit_and_default_output() {
|
||||
for source in [
|
||||
format!("feedback_enabled = false\n{EXAMPLE}"),
|
||||
EXAMPLE.replace("pickup = true", "pickup = true\nfeedback_enabled = false"),
|
||||
] {
|
||||
let profile = Profile::parse(&source).unwrap();
|
||||
assert!(
|
||||
profile
|
||||
.bindings()
|
||||
.iter()
|
||||
.all(|binding| profile.effective_feedback(binding).is_none())
|
||||
);
|
||||
}
|
||||
let profile = Profile::parse(EXAMPLE).unwrap();
|
||||
assert!(profile.effective_feedback(&profile.bindings()[1]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enriched_process_fields_match_only_available_values() {
|
||||
let metadata = StreamMetadata::new().with_process_metadata(
|
||||
Some("/games/Game/game.exe".into()),
|
||||
Some("/games/Game".into()),
|
||||
Some("123".into()),
|
||||
Some("456".into()),
|
||||
);
|
||||
for (field, pattern) in [
|
||||
("application.process.executable", "/games/Game/game.exe"),
|
||||
("application.process.working_directory", "/games/Game"),
|
||||
("steam.app_id", "123"),
|
||||
("steam.game_id", "456"),
|
||||
] {
|
||||
let source = EXAMPLE.replace(
|
||||
"field = \"application.name\", exact = \"Music Player\"",
|
||||
&format!("field = {field:?}, exact = {pattern:?}"),
|
||||
);
|
||||
let profile = Profile::parse(&source).unwrap();
|
||||
let matcher = profile.applications()[0].matcher().unwrap();
|
||||
assert!(matcher.matches(&metadata));
|
||||
assert!(!matcher.matches(&StreamMetadata::new()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selector_composition_defaults_to_any_and_all_requires_every_field() {
|
||||
let source = EXAMPLE.replace(
|
||||
"selectors = [{ field = \"application.name\", exact = \"Music Player\" }]",
|
||||
"selectors = [{ field = \"application.name\", exact = \"Music Player\" }, { field = \"media.name\", regex = '(?i) - YouTube$' }]",
|
||||
);
|
||||
let partial = StreamMetadata::new().with_application_name("Music Player");
|
||||
let complete = partial.clone().with_media_name("A song - YouTube");
|
||||
let legacy = Profile::parse(&source).unwrap();
|
||||
assert!(
|
||||
legacy.applications()[0]
|
||||
.matcher()
|
||||
.unwrap()
|
||||
.matches(&partial)
|
||||
);
|
||||
let source = source.replacen(
|
||||
"label = \"Music\"",
|
||||
"label = \"Music\"\nselector_mode = \"all\"",
|
||||
1,
|
||||
);
|
||||
let profile = Profile::parse(&source).unwrap();
|
||||
let matcher = profile.applications()[0].matcher().unwrap();
|
||||
assert!(!matcher.matches(&partial));
|
||||
assert!(matcher.matches(&complete));
|
||||
assert!(!matcher.matches(&complete.with_application_name("Other Player")));
|
||||
assert_eq!(
|
||||
profile,
|
||||
Profile::parse(&profile.to_toml().unwrap()).unwrap()
|
||||
);
|
||||
assert!(
|
||||
Profile::parse(&source.replace("selector_mode = \"all\"", "selector_mode = \"xor\""))
|
||||
.is_err()
|
||||
);
|
||||
assert!(Profile::parse(&source.replace("regex = '(?i) - YouTube$'", "regex = '['")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn architecture_profile_parses_and_round_trips_semantically() {
|
||||
let marker = "The following profile";
|
||||
let documented = ARCHITECTURE
|
||||
.split_once(marker)
|
||||
.and_then(|(_, remainder)| remainder.split_once("```toml"))
|
||||
.and_then(|(_, remainder)| remainder.split_once("```"))
|
||||
.map(|(toml, _)| toml.trim())
|
||||
.expect("architecture must contain its profile example");
|
||||
assert_eq!(documented, EXAMPLE.trim(), "checked-in example drifted");
|
||||
|
||||
let profile = Profile::parse(documented).expect("architecture profile must validate");
|
||||
assert_eq!(profile.id().as_str(), "desktop");
|
||||
assert_eq!(profile.startup(), StartupPolicy::Adopt);
|
||||
assert_eq!(profile.applications().len(), 2);
|
||||
assert_eq!(profile.groups().len(), 1);
|
||||
assert_eq!(profile.bindings().len(), 2);
|
||||
|
||||
let encoded = profile.to_toml().expect("validated profile must serialize");
|
||||
let reparsed = Profile::parse(&encoded).expect("serialized profile must validate");
|
||||
assert_eq!(profile, reparsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validated_profile_exposes_compiled_runtime_application_and_group_views() {
|
||||
let profile = Profile::parse(EXAMPLE).expect("example profile must validate");
|
||||
let music = &profile.applications()[0];
|
||||
assert_eq!(music.id(), "music");
|
||||
assert_eq!(music.label(), "Music");
|
||||
assert!(
|
||||
music
|
||||
.matcher()
|
||||
.expect("validated selector compiles")
|
||||
.matches(&StreamMetadata::new().with_application_name("Music Player"))
|
||||
);
|
||||
|
||||
let media = &profile.groups()[0];
|
||||
assert_eq!(media.id(), "media");
|
||||
assert_eq!(media.label(), "Media");
|
||||
assert_eq!(media.members(), ["music", "browser"]);
|
||||
assert_eq!(media.volume_mode(), VolumeMode::Absolute);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixer_layout_defaults_to_declared_faders_and_validates_explicit_entries() {
|
||||
let profile = Profile::parse(EXAMPLE).expect("legacy profile must synthesize its layout");
|
||||
assert_eq!(
|
||||
profile.mixer_orientation(),
|
||||
fader_config::MixerOrientation::Vertical
|
||||
);
|
||||
assert_eq!(
|
||||
profile.mixer_layout(),
|
||||
[MixerLayoutEntry::Fader {
|
||||
fader: "media-fader".to_owned(),
|
||||
hidden: false,
|
||||
density: fader_config::FaderDensity::Standard,
|
||||
}]
|
||||
);
|
||||
|
||||
let explicit = EXAMPLE.replacen(
|
||||
"[[bindings]]",
|
||||
"[[mixer_layout]]\nkind = \"separator\"\nid = \"media\"\nlabel = \"Media\"\n\n[[mixer_layout]]\nkind = \"fader\"\nfader = \"media-fader\"\nhidden = true\n\n[[bindings]]",
|
||||
1,
|
||||
);
|
||||
let profile = Profile::parse(&explicit).expect("explicit layout must validate");
|
||||
assert_eq!(profile.mixer_layout().len(), 2);
|
||||
assert!(matches!(
|
||||
&profile.mixer_layout()[1],
|
||||
MixerLayoutEntry::Fader { fader, hidden, density }
|
||||
if fader == "media-fader"
|
||||
&& *hidden
|
||||
&& *density == fader_config::FaderDensity::Standard
|
||||
));
|
||||
|
||||
let slim = explicit.replace("hidden = true", "hidden = true\ndensity = \"slim\"");
|
||||
assert!(matches!(
|
||||
&Profile::parse(&slim).unwrap().mixer_layout()[1],
|
||||
MixerLayoutEntry::Fader {
|
||||
density: fader_config::FaderDensity::Slim,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
let bordered_slim = explicit.replace(
|
||||
"hidden = true",
|
||||
"hidden = true\ndensity = \"bordered_slim\"",
|
||||
);
|
||||
assert!(matches!(
|
||||
&Profile::parse(&bordered_slim).unwrap().mixer_layout()[1],
|
||||
MixerLayoutEntry::Fader {
|
||||
density: fader_config::FaderDensity::BorderedSlim,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
let duplicate = explicit.replace(
|
||||
"kind = \"fader\"\nfader = \"media-fader\"\nhidden = true",
|
||||
"kind = \"fader\"\nfader = \"media-fader\"\nhidden = true\n\n[[mixer_layout]]\nkind = \"fader\"\nfader = \"media-fader\"",
|
||||
);
|
||||
assert_error_contains(Profile::parse(&duplicate), "duplicate fader");
|
||||
|
||||
let dangling = explicit.replace("fader = \"media-fader\"", "fader = \"missing\"");
|
||||
assert_error_contains(Profile::parse(&dangling), "unknown fader");
|
||||
|
||||
let horizontal = EXAMPLE.replace(
|
||||
"[ui]\ndefault_controller = \"desk-left\"",
|
||||
"[ui]\ndefault_controller = \"desk-left\"\nmixer_orientation = \"horizontal\"",
|
||||
);
|
||||
assert_eq!(
|
||||
Profile::parse(&horizontal).unwrap().mixer_orientation(),
|
||||
fader_config::MixerOrientation::Horizontal
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_controller_is_optional_and_must_reference_a_surface() {
|
||||
let profile = Profile::parse(EXAMPLE).expect("configured default controller must validate");
|
||||
assert_eq!(profile.default_controller(), Some("desk-left"));
|
||||
|
||||
let missing = EXAMPLE.replace(
|
||||
"default_controller = \"desk-left\"",
|
||||
"default_controller = \"missing\"",
|
||||
);
|
||||
assert_error_contains(Profile::parse(&missing), "unknown surface \"missing\"");
|
||||
|
||||
let without_default = EXAMPLE.replace("default_controller = \"desk-left\"\n", "");
|
||||
let profile =
|
||||
Profile::parse(&without_default).expect("the default controller remains optional");
|
||||
assert_eq!(profile.default_controller(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_is_profile_backed_and_rejects_unknown_values() {
|
||||
let configured = EXAMPLE.replace("theme = \"default\"", "theme = \"dracula\"");
|
||||
assert_eq!(
|
||||
Profile::parse(&configured).unwrap().theme(),
|
||||
fader_config::UiTheme::Dracula
|
||||
);
|
||||
|
||||
let invalid = configured.replace("theme = \"dracula\"", "theme = \"hot_dog\"");
|
||||
assert!(Profile::parse(&invalid).is_err());
|
||||
assert_eq!(
|
||||
Profile::parse(EXAMPLE).unwrap().theme(),
|
||||
fader_config::UiTheme::Default
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pickup_status_display_defaults_and_validates_named_modes() {
|
||||
assert_eq!(
|
||||
Profile::parse(&EXAMPLE.replace("status_display = \"detailed\"\n", ""))
|
||||
.unwrap()
|
||||
.status_display(),
|
||||
fader_config::StatusDisplayMode::Detailed
|
||||
);
|
||||
let configured = EXAMPLE.replace(
|
||||
"status_display = \"detailed\"",
|
||||
"status_display = \"symbol\"",
|
||||
);
|
||||
assert_eq!(
|
||||
Profile::parse(&configured).unwrap().status_display(),
|
||||
fader_config::StatusDisplayMode::Symbol
|
||||
);
|
||||
assert!(
|
||||
Profile::parse(
|
||||
&configured.replace("status_display = \"symbol\"", "status_display = \"raw\"")
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_poll_interval_defaults_and_validates_safe_overrides() {
|
||||
let without_runtime = EXAMPLE.replace("[runtime]\npoll_interval_ms = 10\n\n", "");
|
||||
let default = Profile::parse(&without_runtime).expect("omitted runtime settings must validate");
|
||||
assert_eq!(default.poll_interval(), Duration::from_millis(10));
|
||||
|
||||
let configured = EXAMPLE.replace("poll_interval_ms = 10", "poll_interval_ms = 4");
|
||||
let configured = Profile::parse(&configured).expect("poll override must validate");
|
||||
assert_eq!(configured.poll_interval(), Duration::from_millis(4));
|
||||
assert_eq!(
|
||||
Profile::parse(&configured.to_toml().unwrap())
|
||||
.unwrap()
|
||||
.poll_interval(),
|
||||
Duration::from_millis(4)
|
||||
);
|
||||
|
||||
for value in [0, 101] {
|
||||
let invalid = EXAMPLE.replace(
|
||||
"poll_interval_ms = 10",
|
||||
&format!("poll_interval_ms = {value}"),
|
||||
);
|
||||
assert_error_contains(Profile::parse(&invalid), "runtime.poll_interval_ms");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arch_pipewire_profile_matches_reported_qobuz_metadata() {
|
||||
let profile = Profile::parse(ARCH_PIPEWIRE).expect("Arch profile must validate");
|
||||
let music = profile.applications()[0]
|
||||
.matcher()
|
||||
.expect("validated music selector compiles");
|
||||
assert!(
|
||||
music.matches(
|
||||
&StreamMetadata::new()
|
||||
.with_application_name("PipeWire ALSA [qbz]")
|
||||
.with_media_name("ALSA Playback")
|
||||
)
|
||||
);
|
||||
assert!(!music.matches(&StreamMetadata::new().with_application_name("Firefox")));
|
||||
|
||||
let browser = profile.applications()[1]
|
||||
.matcher()
|
||||
.expect("validated browser selector compiles");
|
||||
assert!(
|
||||
browser.matches(
|
||||
&StreamMetadata::new()
|
||||
.with_application_name("Waterfox")
|
||||
.with_process_binary("waterfox-bin")
|
||||
)
|
||||
);
|
||||
|
||||
let surface = &profile.surfaces()[0];
|
||||
assert_eq!(surface.id(), "apc-mini-apc-mini-midi-1");
|
||||
assert_eq!(surface.input_port(), "APC MINI:APC MINI MIDI 1");
|
||||
assert_eq!(surface.usb_vendor_id(), Some("09e8"));
|
||||
assert_eq!(surface.usb_product_id(), Some("0028"));
|
||||
assert_eq!(surface.usb_serial(), Some("Ver00.10"));
|
||||
assert_eq!(profile.faders().len(), 5);
|
||||
assert_eq!(profile.bindings().len(), 4);
|
||||
assert_eq!(profile.bindings()[0].number(), 48);
|
||||
assert_eq!(profile.bindings()[3].number(), 89);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_fields_versions_and_bad_ids_with_context() {
|
||||
let unknown = EXAMPLE.replace("schema_version = 1", "schema_version = 1\nsurprise = true");
|
||||
assert_error_contains(Profile::parse(&unknown), "surprise");
|
||||
|
||||
let version = EXAMPLE.replace("schema_version = 1", "schema_version = 7");
|
||||
assert_error_contains(Profile::parse(&version), "schema_version");
|
||||
|
||||
let bad_id = EXAMPLE.replace("id = \"desktop\"", "id = \"bad/profile\"");
|
||||
assert_error_contains(Profile::parse(&bad_id), "profile.id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_dangling_references_and_duplicate_physical_bindings() {
|
||||
let missing_member = EXAMPLE.replace(
|
||||
"members = [\"music\", \"browser\"]",
|
||||
"members = [\"music\", \"missing\"]",
|
||||
);
|
||||
assert_error_contains(Profile::parse(&missing_member), "groups[0].members[1]");
|
||||
|
||||
let missing_target = EXAMPLE.replace("id = \"media\" }", "id = \"missing\" }");
|
||||
assert_error_contains(Profile::parse(&missing_target), "faders[0].target.id");
|
||||
|
||||
let unknown_output = ARCH_PIPEWIRE.replace(
|
||||
"target = { kind = \"output\", id = \"default\" }",
|
||||
"target = { kind = \"output\", id = \"headphones\" }",
|
||||
);
|
||||
assert_error_contains(Profile::parse(&unknown_output), "faders[3].target.id");
|
||||
|
||||
let duplicate = EXAMPLE.replace(
|
||||
"kind = \"note\", channel = 1, number = 32",
|
||||
"kind = \"cc\", channel = 1, number = 0",
|
||||
);
|
||||
assert_error_contains(Profile::parse(&duplicate), "bindings[1].message");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_groups_are_reserved_but_not_runtime_selectable() {
|
||||
let relative = EXAMPLE.replace("volume_mode = \"absolute\"", "volume_mode = \"relative\"");
|
||||
assert_error_contains(Profile::parse(&relative), "groups[0].volume_mode");
|
||||
assert_error_contains(Profile::parse(&relative), "use absolute");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_incomplete_or_malformed_usb_surface_hints() {
|
||||
let missing_product = ARCH_PIPEWIRE.replace("usb_product_id = \"0028\"\n", "");
|
||||
assert_error_contains(Profile::parse(&missing_product), "provided together");
|
||||
|
||||
let malformed_vendor =
|
||||
ARCH_PIPEWIRE.replace("usb_vendor_id = \"09e8\"", "usb_vendor_id = \"9e8\"");
|
||||
assert_error_contains(Profile::parse(&malformed_vendor), "four hexadecimal digits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_all_midi_data_ranges_and_action_capabilities() {
|
||||
for (needle, replacement, path) in [
|
||||
(
|
||||
"channel = 1, number = 0",
|
||||
"channel = 0, number = 0",
|
||||
"channel",
|
||||
),
|
||||
(
|
||||
"channel = 1, number = 0",
|
||||
"channel = 17, number = 0",
|
||||
"channel",
|
||||
),
|
||||
(
|
||||
"channel = 1, number = 32",
|
||||
"channel = 1, number = 128",
|
||||
"number",
|
||||
),
|
||||
("on = 127, off = 0", "on = 128, off = 0", "feedback.on"),
|
||||
("on = 127, off = 0", "on = 127, off = 128", "feedback.off"),
|
||||
] {
|
||||
assert_error_contains(
|
||||
Profile::parse(&EXAMPLE.replacen(needle, replacement, 1)),
|
||||
path,
|
||||
);
|
||||
}
|
||||
|
||||
let volume_on_note = EXAMPLE.replace(
|
||||
"action = \"volume\"\nmessage = { kind = \"cc\"",
|
||||
"action = \"volume\"\nmessage = { kind = \"note\"",
|
||||
);
|
||||
assert_error_contains(Profile::parse(&volume_on_note), "requires a cc message");
|
||||
|
||||
let feedback_on_input_only =
|
||||
EXAMPLE.replace("output_port = \"Example Controller MIDI 1\"\n", "");
|
||||
assert_error_contains(Profile::parse(&feedback_on_input_only), "output_port");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_and_state_documents_are_strict_and_validated() {
|
||||
let device = DeviceProfile::parse(
|
||||
r#"
|
||||
schema_version = 1
|
||||
id = "nano"
|
||||
label = "Nano controller"
|
||||
[capabilities]
|
||||
mute_led = true
|
||||
value_display = false
|
||||
motorized_fader = false
|
||||
"#,
|
||||
)
|
||||
.expect("device profile must validate");
|
||||
assert_eq!(device.id().as_str(), "nano");
|
||||
assert_eq!(
|
||||
device
|
||||
.to_toml()
|
||||
.and_then(|text| DeviceProfile::parse(&text))
|
||||
.unwrap(),
|
||||
device
|
||||
);
|
||||
|
||||
let state = PersistedState::parse(
|
||||
r#"
|
||||
schema_version = 1
|
||||
|
||||
[[profiles]]
|
||||
id = "desktop"
|
||||
last_view = "mixer"
|
||||
|
||||
[[profiles.observed]]
|
||||
object = "music"
|
||||
gain = [0.5, 0.25]
|
||||
muted = false
|
||||
|
||||
[[profiles.desired]]
|
||||
object = "music"
|
||||
gain = 0.7
|
||||
muted = true
|
||||
|
||||
[[profiles.assignments]]
|
||||
surface = "desk-left"
|
||||
input_port = "hw:1"
|
||||
output_port = "hw:1"
|
||||
"#,
|
||||
)
|
||||
.expect("state must validate");
|
||||
assert_eq!(state.profiles().len(), 1);
|
||||
assert_eq!(
|
||||
state
|
||||
.to_toml()
|
||||
.and_then(|text| PersistedState::parse(&text))
|
||||
.unwrap(),
|
||||
state
|
||||
);
|
||||
|
||||
assert_error_contains(
|
||||
PersistedState::parse("schema_version = 1\npending_operation = 4"),
|
||||
"pending_operation",
|
||||
);
|
||||
assert_error_contains(
|
||||
PersistedState::parse("schema_version = 2\nprofiles = []"),
|
||||
"schema_version",
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_error_contains<T>(result: Result<T, fader_config::ConfigError>, needle: &str) {
|
||||
let error = result
|
||||
.err()
|
||||
.expect("document should be rejected")
|
||||
.to_string();
|
||||
assert!(
|
||||
error.contains(needle),
|
||||
"expected {error:?} to contain {needle:?}"
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
[package]
|
||||
name = "fader-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
regex.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
proptest.workspace = true
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
//! Device-scoped control bindings without native MIDI handles.
|
||||
use crate::{FaderId, SurfaceId};
|
||||
use std::collections::{BTreeMap, btree_map::Entry};
|
||||
use thiserror::Error;
|
||||
|
||||
/// Invalid channel or data range.
|
||||
#[derive(Clone, Debug, Error, Eq, PartialEq)]
|
||||
pub enum MidiRangeError {
|
||||
/// Human-facing channels are numbered 1 through 16.
|
||||
#[error("MIDI channel {0} is outside 1..=16")]
|
||||
Channel(u16),
|
||||
/// MIDI data bytes contain seven bits.
|
||||
#[error("MIDI data {0} is outside 0..=127")]
|
||||
Data(u16),
|
||||
}
|
||||
|
||||
/// Validated human-facing MIDI channel number.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub struct MidiChannel(u8);
|
||||
impl MidiChannel {
|
||||
/// Validates a channel before conversion to wire indexing.
|
||||
pub fn new(value: u16) -> Result<Self, MidiRangeError> {
|
||||
match value {
|
||||
1..=16 => Ok(Self(value as u8)),
|
||||
_ => Err(MidiRangeError::Channel(value)),
|
||||
}
|
||||
}
|
||||
/// The human-facing channel number.
|
||||
pub const fn get(self) -> u8 {
|
||||
self.0
|
||||
}
|
||||
/// Zero-based channel for the MIDI status nibble.
|
||||
pub const fn wire_index(self) -> u8 {
|
||||
self.0 - 1
|
||||
}
|
||||
}
|
||||
|
||||
/// A seven-bit MIDI data value or control number.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub struct MidiData(u8);
|
||||
impl MidiData {
|
||||
/// Rejects data values containing status bits before narrowing.
|
||||
pub fn new(value: u16) -> Result<Self, MidiRangeError> {
|
||||
if value <= 127 {
|
||||
Ok(Self(value as u8))
|
||||
} else {
|
||||
Err(MidiRangeError::Data(value))
|
||||
}
|
||||
}
|
||||
/// Returns the validated data byte.
|
||||
pub const fn get(self) -> u8 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Supported initial control namespaces.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub enum MessageKind {
|
||||
/// Seven-bit control change.
|
||||
ControlChange,
|
||||
/// Note on/off button pair.
|
||||
Note,
|
||||
}
|
||||
|
||||
/// A physical control, including its stable surface identity.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub struct BindingKey {
|
||||
/// Configured surface identity.
|
||||
pub surface: SurfaceId,
|
||||
/// Channel, independent of other connected surfaces.
|
||||
pub channel: MidiChannel,
|
||||
/// Message namespace.
|
||||
pub kind: MessageKind,
|
||||
/// CC or note number.
|
||||
pub number: MidiData,
|
||||
}
|
||||
|
||||
/// Logical intent for a bound control.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum BindingAction {
|
||||
/// Absolute normalized volume.
|
||||
Volume,
|
||||
/// Toggle mute on a press edge.
|
||||
ToggleMute,
|
||||
}
|
||||
|
||||
/// A control's logical destination and action.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Binding {
|
||||
/// Configured fader destination.
|
||||
pub fader: FaderId,
|
||||
/// Requested logical operation.
|
||||
pub action: BindingAction,
|
||||
}
|
||||
|
||||
/// Duplicate physical controls would route ambiguously.
|
||||
#[derive(Clone, Debug, Error, Eq, PartialEq)]
|
||||
#[error("duplicate physical binding: {0:?}")]
|
||||
pub struct BindingError(pub BindingKey);
|
||||
|
||||
/// An unambiguous device-scoped lookup table.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Bindings(BTreeMap<BindingKey, Binding>);
|
||||
impl Bindings {
|
||||
/// Builds the table, rejecting duplicate keys even if destinations agree.
|
||||
pub fn new(
|
||||
entries: impl IntoIterator<Item = (BindingKey, Binding)>,
|
||||
) -> Result<Self, BindingError> {
|
||||
let mut table = BTreeMap::new();
|
||||
for (key, binding) in entries {
|
||||
match table.entry(key) {
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(binding);
|
||||
}
|
||||
Entry::Occupied(entry) => return Err(BindingError(entry.key().clone())),
|
||||
}
|
||||
}
|
||||
Ok(Self(table))
|
||||
}
|
||||
/// Unknown controls are left unbound.
|
||||
pub fn get(&self, key: &BindingKey) -> Option<&Binding> {
|
||||
self.0.get(key)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
//! Pure plans over current observations; creating a plan never confirms a write.
|
||||
use crate::{ChannelGainError, ChannelGains, Gain, StreamHandle};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Application group gain semantics.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub enum VolumeMode {
|
||||
/// Sync group: each stream reaches the requested scalar gain.
|
||||
#[default]
|
||||
Absolute,
|
||||
/// Reserved VCA-style group backed by [`RelativeGroupState`].
|
||||
Relative,
|
||||
}
|
||||
|
||||
/// Prepared state for a future VCA-style relative group.
|
||||
///
|
||||
/// Each member's last independently controlled or externally observed channel
|
||||
/// vector is its maximum. A normalized group position scales every member from
|
||||
/// silence to that remembered maximum. Group-generated confirmations must not
|
||||
/// be passed to [`Self::observe_independent`], because moving the group does not
|
||||
/// redefine a member's maximum.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RelativeGroupState {
|
||||
maxima: BTreeMap<StreamHandle, ChannelGains>,
|
||||
}
|
||||
|
||||
impl RelativeGroupState {
|
||||
/// Creates an empty relative group state.
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
maxima: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a member's latest independent fader or external position.
|
||||
pub fn observe_independent(&mut self, stream: StreamHandle, channels: ChannelGains) {
|
||||
self.maxima.insert(stream, channels);
|
||||
}
|
||||
|
||||
/// Forgets a member that is no longer resolved by this group.
|
||||
pub fn remove(&mut self, stream: StreamHandle) {
|
||||
self.maxima.remove(&stream);
|
||||
}
|
||||
|
||||
/// Plans member gains at a normalized group position in `0..=1`.
|
||||
///
|
||||
/// The stored maxima are not mutated, so lowering and raising the group is
|
||||
/// reversible until an independent member edit explicitly rebases one.
|
||||
pub fn plan(
|
||||
&self,
|
||||
position: Gain,
|
||||
ceiling: Gain,
|
||||
) -> Result<BTreeMap<StreamHandle, ChannelGains>, ChannelGainError> {
|
||||
if position > Gain::UNITY {
|
||||
return Err(ChannelGainError::AboveWriteCeiling {
|
||||
target: position.get(),
|
||||
ceiling: Gain::UNITY.get(),
|
||||
});
|
||||
}
|
||||
self.maxima
|
||||
.iter()
|
||||
.map(|(handle, maximum)| {
|
||||
let desired =
|
||||
Gain::new((maximum.maximum().get() * position.get()).min(ceiling.get()))?;
|
||||
Ok((*handle, maximum.scaled_to(desired, ceiling)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggregate gain view; absence of this value means no stream is observable.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct VolumeView {
|
||||
/// Maximum channel gain across all resolved streams.
|
||||
pub maximum: Gain,
|
||||
/// Whether stream maxima disagree.
|
||||
pub mixed: bool,
|
||||
}
|
||||
|
||||
/// Aggregates stream maxima without manufacturing a zero for offline targets.
|
||||
pub fn volume_view(live: &BTreeMap<StreamHandle, ChannelGains>) -> Option<VolumeView> {
|
||||
let mut maxima = live.values().map(ChannelGains::maximum);
|
||||
let first = maxima.next()?;
|
||||
let mut view = VolumeView {
|
||||
maximum: first,
|
||||
mixed: false,
|
||||
};
|
||||
for maximum in maxima {
|
||||
view.mixed |= maximum != first;
|
||||
if maximum > view.maximum {
|
||||
view.maximum = maximum;
|
||||
}
|
||||
}
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// Computes one bounded channel-vector command per resolved stream.
|
||||
///
|
||||
/// This is the active sync/absolute group planner. Every member reaches the
|
||||
/// target while retaining its channel balance. Requests above the configured
|
||||
/// ceiling are clipped; no observation is modified. Successful and failed
|
||||
/// writes must later be reconciled separately.
|
||||
pub fn plan_volume(
|
||||
live: &BTreeMap<StreamHandle, ChannelGains>,
|
||||
target: Gain,
|
||||
ceiling: Gain,
|
||||
) -> Result<BTreeMap<StreamHandle, ChannelGains>, ChannelGainError> {
|
||||
let bounded = Gain::new(target.get().min(ceiling.get()))?;
|
||||
live.iter()
|
||||
.map(|(handle, channels)| Ok((*handle, channels.scaled_to(bounded, ceiling)?)))
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
use std::{fmt, str::FromStr};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
const MAX_ID_LENGTH: usize = 64;
|
||||
|
||||
/// Why a stable user-defined identifier was rejected.
|
||||
#[derive(Clone, Debug, Error, Eq, PartialEq)]
|
||||
pub enum IdError {
|
||||
/// The identifier was empty.
|
||||
#[error("identifier must not be empty")]
|
||||
Empty,
|
||||
/// The identifier exceeded the stable storage limit.
|
||||
#[error("identifier length {actual} exceeds the maximum {maximum}")]
|
||||
TooLong {
|
||||
/// Actual byte length.
|
||||
actual: usize,
|
||||
/// Maximum allowed byte length.
|
||||
maximum: usize,
|
||||
},
|
||||
/// The first character was not ASCII alphanumeric.
|
||||
#[error("identifier must start with an ASCII letter or digit, found {found:?}")]
|
||||
InvalidStart {
|
||||
/// Invalid first character.
|
||||
found: char,
|
||||
},
|
||||
/// A later character was outside the durable identifier alphabet.
|
||||
#[error("identifier contains invalid character {found:?} at position {position}")]
|
||||
InvalidCharacter {
|
||||
/// Zero-based character position.
|
||||
position: usize,
|
||||
/// Invalid character.
|
||||
found: char,
|
||||
},
|
||||
}
|
||||
|
||||
fn validate(value: &str) -> Result<(), IdError> {
|
||||
if value.is_empty() {
|
||||
return Err(IdError::Empty);
|
||||
}
|
||||
if value.len() > MAX_ID_LENGTH {
|
||||
return Err(IdError::TooLong {
|
||||
actual: value.len(),
|
||||
maximum: MAX_ID_LENGTH,
|
||||
});
|
||||
}
|
||||
|
||||
let mut characters = value.chars();
|
||||
let Some(first) = characters.next() else {
|
||||
return Err(IdError::Empty);
|
||||
};
|
||||
if !first.is_ascii_alphanumeric() {
|
||||
return Err(IdError::InvalidStart { found: first });
|
||||
}
|
||||
for (offset, character) in characters.enumerate() {
|
||||
if !(character.is_ascii_alphanumeric() || matches!(character, '-' | '_')) {
|
||||
return Err(IdError::InvalidCharacter {
|
||||
position: offset + 1,
|
||||
found: character,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
macro_rules! stable_id {
|
||||
($name:ident, $description:literal) => {
|
||||
#[doc = $description]
|
||||
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct $name(String);
|
||||
|
||||
impl $name {
|
||||
/// Validates and constructs an identifier.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`IdError`] when `value` is empty, too long, or outside
|
||||
/// the portable `[A-Za-z0-9_-]` identifier alphabet.
|
||||
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
|
||||
let value = value.into();
|
||||
validate(&value)?;
|
||||
Ok(Self(value))
|
||||
}
|
||||
|
||||
/// Returns the persisted string representation.
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for $name {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for $name {
|
||||
type Err = IdError;
|
||||
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
stable_id!(
|
||||
ApplicationId,
|
||||
"Stable identifier for a virtual application."
|
||||
);
|
||||
stable_id!(FaderId, "Stable identifier for a logical fader.");
|
||||
stable_id!(GroupId, "Stable identifier for an application group.");
|
||||
stable_id!(ProfileId, "Stable identifier for a configuration profile.");
|
||||
stable_id!(SurfaceId, "Stable identifier for a physical MIDI surface.");
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::any::TypeId;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accepts_portable_stable_ids() {
|
||||
let id = ApplicationId::new("music-player_2").expect("valid application ID");
|
||||
assert_eq!(id.as_str(), "music-player_2");
|
||||
assert_eq!(id.to_string(), "music-player_2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_ids_with_a_precise_reason() {
|
||||
assert_eq!(GroupId::new(""), Err(IdError::Empty));
|
||||
assert_eq!(
|
||||
GroupId::new("-group"),
|
||||
Err(IdError::InvalidStart { found: '-' })
|
||||
);
|
||||
assert_eq!(
|
||||
GroupId::new("group/name"),
|
||||
Err(IdError::InvalidCharacter {
|
||||
position: 5,
|
||||
found: '/',
|
||||
})
|
||||
);
|
||||
assert!(matches!(
|
||||
GroupId::new("a".repeat(MAX_ID_LENGTH + 1)),
|
||||
Err(IdError::TooLong { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_id_types_cannot_be_interchanged() {
|
||||
assert_ne!(TypeId::of::<ApplicationId>(), TypeId::of::<GroupId>());
|
||||
assert_ne!(TypeId::of::<FaderId>(), TypeId::of::<SurfaceId>());
|
||||
assert_ne!(TypeId::of::<ProfileId>(), TypeId::of::<ApplicationId>());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
//! Pure domain contracts for fader_master.
|
||||
//!
|
||||
//! Domain logic has no runtime, terminal, filesystem, or native audio/MIDI
|
||||
//! dependencies. Stable IDs are distinct types:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use fader_core::{ApplicationId, GroupId};
|
||||
//! let application = ApplicationId::new("music").unwrap();
|
||||
//! let group: GroupId = application;
|
||||
//! ```
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod bindings;
|
||||
mod group;
|
||||
mod id;
|
||||
mod matching;
|
||||
mod mute;
|
||||
mod pickup;
|
||||
mod revision;
|
||||
mod routing;
|
||||
mod server;
|
||||
mod state;
|
||||
mod volume;
|
||||
|
||||
pub use bindings::{
|
||||
Binding, BindingAction, BindingError, BindingKey, Bindings, MessageKind, MidiChannel, MidiData,
|
||||
MidiRangeError,
|
||||
};
|
||||
pub use group::{RelativeGroupState, VolumeMode, VolumeView, plan_volume, volume_view};
|
||||
pub use id::{ApplicationId, FaderId, GroupId, IdError, ProfileId, SurfaceId};
|
||||
pub use matching::{
|
||||
ApplicationMatcher, ApplicationRuntime, ApplicationSelector, MetadataField, SelectorError,
|
||||
SelectorKind, SelectorMode, StreamHandle, StreamMetadata,
|
||||
};
|
||||
pub use mute::{MuteIntent, MutePlanner, mute_view};
|
||||
pub use pickup::{Pickup, PickupError, PickupState};
|
||||
pub use revision::{BackendEpoch, Revision};
|
||||
pub use routing::{Routing, RoutingError, Target};
|
||||
pub use server::{
|
||||
AdapterCommand, AdapterEvent, CommandOrigin, OperationId, ReducerError, ServerCommand,
|
||||
ServerReducer, StreamView, Transition,
|
||||
};
|
||||
pub use state::{Availability, Mute, ValueState};
|
||||
pub use volume::{ChannelGainError, ChannelGains, Gain, GainError};
|
||||
|
|
@ -0,0 +1,548 @@
|
|||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use regex::{Regex, RegexBuilder};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{ApplicationId, BackendEpoch};
|
||||
|
||||
const MAX_PATTERN_LENGTH: usize = 256;
|
||||
const REGEX_SIZE_LIMIT: usize = 1 << 20;
|
||||
|
||||
/// Explicit normalized stream metadata fields supported by application selectors.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub enum MetadataField {
|
||||
/// Backend `application.name`.
|
||||
ApplicationName,
|
||||
/// Backend `application.id`.
|
||||
ApplicationId,
|
||||
/// Backend `application.process.binary`.
|
||||
ProcessBinary,
|
||||
/// Backend `media.name`.
|
||||
MediaName,
|
||||
/// Locally observed executable path, not merely a reported binary name.
|
||||
ProcessExecutable,
|
||||
/// Locally observed working directory.
|
||||
ProcessWorkingDirectory,
|
||||
/// SteamAppId launch-environment evidence (not proof of launch origin).
|
||||
SteamAppId,
|
||||
/// SteamGameId launch-environment evidence, including non-Steam shortcuts.
|
||||
SteamGameId,
|
||||
}
|
||||
|
||||
/// Normalized fields plus untouched backend metadata for diagnostics.
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct StreamMetadata {
|
||||
application_name: Option<String>,
|
||||
application_id: Option<String>,
|
||||
process_binary: Option<String>,
|
||||
media_name: Option<String>,
|
||||
process_executable: Option<String>,
|
||||
process_working_directory: Option<String>,
|
||||
steam_app_id: Option<String>,
|
||||
steam_game_id: Option<String>,
|
||||
raw: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl StreamMetadata {
|
||||
/// Creates an empty metadata snapshot.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Sets normalized `application.name`.
|
||||
#[must_use]
|
||||
pub fn with_application_name(mut self, value: impl Into<String>) -> Self {
|
||||
self.application_name = Some(value.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets normalized `application.id`.
|
||||
#[must_use]
|
||||
pub fn with_application_id(mut self, value: impl Into<String>) -> Self {
|
||||
self.application_id = Some(value.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets normalized `application.process.binary`.
|
||||
#[must_use]
|
||||
pub fn with_process_binary(mut self, value: impl Into<String>) -> Self {
|
||||
self.process_binary = Some(value.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets normalized `media.name`.
|
||||
#[must_use]
|
||||
pub fn with_media_name(mut self, value: impl Into<String>) -> Self {
|
||||
self.media_name = Some(value.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Attaches adapter-observed process metadata. Missing values stay unknown.
|
||||
#[must_use]
|
||||
pub fn with_process_metadata(
|
||||
mut self,
|
||||
executable: Option<String>,
|
||||
working_directory: Option<String>,
|
||||
steam_app_id: Option<String>,
|
||||
steam_game_id: Option<String>,
|
||||
) -> Self {
|
||||
self.process_executable = executable;
|
||||
self.process_working_directory = working_directory;
|
||||
self.steam_app_id = steam_app_id;
|
||||
self.steam_game_id = steam_game_id;
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds an untouched backend property for inspection.
|
||||
#[must_use]
|
||||
pub fn with_raw_property(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.raw.insert(key.into(), value.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns a normalized field, preserving absence rather than substituting another field.
|
||||
#[must_use]
|
||||
pub fn value(&self, field: MetadataField) -> Option<&str> {
|
||||
match field {
|
||||
MetadataField::ApplicationName => self.application_name.as_deref(),
|
||||
MetadataField::ApplicationId => self.application_id.as_deref(),
|
||||
MetadataField::ProcessBinary => self.process_binary.as_deref(),
|
||||
MetadataField::MediaName => self.media_name.as_deref(),
|
||||
MetadataField::ProcessExecutable => self.process_executable.as_deref(),
|
||||
MetadataField::ProcessWorkingDirectory => self.process_working_directory.as_deref(),
|
||||
MetadataField::SteamAppId => self.steam_app_id.as_deref(),
|
||||
MetadataField::SteamGameId => self.steam_game_id.as_deref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns untouched backend metadata.
|
||||
#[must_use]
|
||||
pub fn raw(&self) -> &BTreeMap<String, String> {
|
||||
&self.raw
|
||||
}
|
||||
}
|
||||
|
||||
/// Selector comparison mode.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub enum SelectorKind {
|
||||
/// Case-sensitive whole-string equality.
|
||||
Exact,
|
||||
/// Rust regex substring search unless the pattern is anchored.
|
||||
Regex,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Expression {
|
||||
Exact(String),
|
||||
Regex { pattern: String, compiled: Regex },
|
||||
}
|
||||
|
||||
/// Why an application selector was rejected.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum SelectorError {
|
||||
/// Applications must declare at least one selector.
|
||||
#[error("application {application} must have at least one selector")]
|
||||
NoSelectors {
|
||||
/// Application missing selectors.
|
||||
application: ApplicationId,
|
||||
},
|
||||
/// Empty patterns are too easy to match accidentally.
|
||||
#[error("selector pattern must not be empty")]
|
||||
EmptyPattern,
|
||||
/// Patterns are bounded before regex compilation.
|
||||
#[error("selector pattern length {actual} exceeds maximum {maximum}")]
|
||||
PatternTooLong {
|
||||
/// Actual byte length.
|
||||
actual: usize,
|
||||
/// Maximum allowed byte length.
|
||||
maximum: usize,
|
||||
},
|
||||
/// Rust regex compilation failed.
|
||||
#[error("invalid selector regex {pattern:?}: {source}")]
|
||||
InvalidRegex {
|
||||
/// Rejected source pattern.
|
||||
pattern: String,
|
||||
/// Regex parser/compiler error.
|
||||
#[source]
|
||||
source: regex::Error,
|
||||
},
|
||||
}
|
||||
|
||||
/// One explicit field matcher for a virtual application.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ApplicationSelector {
|
||||
field: MetadataField,
|
||||
expression: Expression,
|
||||
}
|
||||
|
||||
impl ApplicationSelector {
|
||||
/// Creates a case-sensitive exact selector.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`SelectorError`] when the pattern is empty or too long.
|
||||
pub fn exact(field: MetadataField, pattern: impl Into<String>) -> Result<Self, SelectorError> {
|
||||
let pattern = pattern.into();
|
||||
validate_pattern(&pattern)?;
|
||||
Ok(Self {
|
||||
field,
|
||||
expression: Expression::Exact(pattern),
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a bounded Rust regex selector.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`SelectorError`] when the pattern is empty, too long, or not a
|
||||
/// valid Rust regular expression.
|
||||
pub fn regex(field: MetadataField, pattern: impl Into<String>) -> Result<Self, SelectorError> {
|
||||
let pattern = pattern.into();
|
||||
validate_pattern(&pattern)?;
|
||||
let compiled = RegexBuilder::new(&pattern)
|
||||
.size_limit(REGEX_SIZE_LIMIT)
|
||||
.build()
|
||||
.map_err(|source| SelectorError::InvalidRegex {
|
||||
pattern: pattern.clone(),
|
||||
source,
|
||||
})?;
|
||||
Ok(Self {
|
||||
field,
|
||||
expression: Expression::Regex { pattern, compiled },
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the selected normalized field.
|
||||
#[must_use]
|
||||
pub const fn field(&self) -> MetadataField {
|
||||
self.field
|
||||
}
|
||||
|
||||
/// Returns the selector mode.
|
||||
#[must_use]
|
||||
pub const fn kind(&self) -> SelectorKind {
|
||||
match self.expression {
|
||||
Expression::Exact(_) => SelectorKind::Exact,
|
||||
Expression::Regex { .. } => SelectorKind::Regex,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the configured source pattern.
|
||||
#[must_use]
|
||||
pub fn pattern(&self) -> &str {
|
||||
match &self.expression {
|
||||
Expression::Exact(pattern) | Expression::Regex { pattern, .. } => pattern,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests only the configured normalized field.
|
||||
#[must_use]
|
||||
pub fn matches(&self, metadata: &StreamMetadata) -> bool {
|
||||
let Some(candidate) = metadata.value(self.field) else {
|
||||
return false;
|
||||
};
|
||||
match &self.expression {
|
||||
Expression::Exact(pattern) => candidate == pattern,
|
||||
Expression::Regex { compiled, .. } => compiled.is_match(candidate),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_pattern(pattern: &str) -> Result<(), SelectorError> {
|
||||
if pattern.is_empty() {
|
||||
return Err(SelectorError::EmptyPattern);
|
||||
}
|
||||
if pattern.len() > MAX_PATTERN_LENGTH {
|
||||
return Err(SelectorError::PatternTooLong {
|
||||
actual: pattern.len(),
|
||||
maximum: MAX_PATTERN_LENGTH,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How the nonempty selector list is combined.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub enum SelectorMode {
|
||||
/// At least one selector must match (legacy behavior).
|
||||
#[default]
|
||||
Any,
|
||||
/// Every selector must match; absent fields fail their selector.
|
||||
All,
|
||||
}
|
||||
|
||||
/// Immutable combination of selectors for one virtual application.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ApplicationMatcher {
|
||||
id: ApplicationId,
|
||||
selectors: Vec<ApplicationSelector>,
|
||||
mode: SelectorMode,
|
||||
}
|
||||
|
||||
impl ApplicationMatcher {
|
||||
/// Constructs a matcher with at least one selector.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`SelectorError::NoSelectors`] for an empty selector list.
|
||||
pub fn new(
|
||||
id: ApplicationId,
|
||||
selectors: Vec<ApplicationSelector>,
|
||||
) -> Result<Self, SelectorError> {
|
||||
Self::with_mode(id, selectors, SelectorMode::Any)
|
||||
}
|
||||
|
||||
/// Constructs an explicitly combined matcher.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`SelectorError::NoSelectors`] for an empty selector list,
|
||||
/// including All mode (an empty conjunction must not match everything).
|
||||
pub fn with_mode(
|
||||
id: ApplicationId,
|
||||
selectors: Vec<ApplicationSelector>,
|
||||
mode: SelectorMode,
|
||||
) -> Result<Self, SelectorError> {
|
||||
if selectors.is_empty() {
|
||||
return Err(SelectorError::NoSelectors { application: id });
|
||||
}
|
||||
Ok(Self {
|
||||
id,
|
||||
selectors,
|
||||
mode,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the stable application identifier.
|
||||
#[must_use]
|
||||
pub fn id(&self) -> &ApplicationId {
|
||||
&self.id
|
||||
}
|
||||
|
||||
/// Returns whether the configured selector combination matches.
|
||||
#[must_use]
|
||||
pub fn matches(&self, metadata: &StreamMetadata) -> bool {
|
||||
match self.mode {
|
||||
SelectorMode::Any => self
|
||||
.selectors
|
||||
.iter()
|
||||
.any(|selector| selector.matches(metadata)),
|
||||
SelectorMode::All => self
|
||||
.selectors
|
||||
.iter()
|
||||
.all(|selector| selector.matches(metadata)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ephemeral stream identity protected against backend ID reuse.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct StreamHandle {
|
||||
epoch: BackendEpoch,
|
||||
backend_id: u64,
|
||||
incarnation: u64,
|
||||
}
|
||||
|
||||
impl StreamHandle {
|
||||
/// Creates a handle scoped to a connection epoch and incarnation.
|
||||
#[must_use]
|
||||
pub const fn new(epoch: BackendEpoch, backend_id: u64, incarnation: u64) -> Self {
|
||||
Self {
|
||||
epoch,
|
||||
backend_id,
|
||||
incarnation,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the owning backend epoch.
|
||||
#[must_use]
|
||||
pub const fn epoch(self) -> BackendEpoch {
|
||||
self.epoch
|
||||
}
|
||||
|
||||
/// Returns the adapter-local object ID.
|
||||
#[must_use]
|
||||
pub const fn backend_id(self) -> u64 {
|
||||
self.backend_id
|
||||
}
|
||||
|
||||
/// Returns the object incarnation within the epoch.
|
||||
#[must_use]
|
||||
pub const fn incarnation(self) -> u64 {
|
||||
self.incarnation
|
||||
}
|
||||
}
|
||||
|
||||
/// Live matching membership for one virtual application.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ApplicationRuntime {
|
||||
matcher: ApplicationMatcher,
|
||||
matching_streams: BTreeSet<StreamHandle>,
|
||||
}
|
||||
|
||||
impl ApplicationRuntime {
|
||||
/// Starts an application offline with no stream membership.
|
||||
#[must_use]
|
||||
pub fn new(matcher: ApplicationMatcher) -> Self {
|
||||
Self {
|
||||
matcher,
|
||||
matching_streams: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-evaluates one stream and returns its current membership.
|
||||
pub fn upsert(&mut self, handle: StreamHandle, metadata: &StreamMetadata) -> bool {
|
||||
if self.matcher.matches(metadata) {
|
||||
self.matching_streams.insert(handle);
|
||||
true
|
||||
} else {
|
||||
self.matching_streams.remove(&handle);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes exactly one stream incarnation.
|
||||
pub fn remove(&mut self, handle: StreamHandle) -> bool {
|
||||
self.matching_streams.remove(&handle)
|
||||
}
|
||||
|
||||
/// Returns matching live stream identities in deterministic order.
|
||||
#[must_use]
|
||||
pub fn matching_streams(&self) -> &BTreeSet<StreamHandle> {
|
||||
&self.matching_streams
|
||||
}
|
||||
|
||||
/// Returns whether the configured application currently has no stream.
|
||||
#[must_use]
|
||||
pub fn is_offline(&self) -> bool {
|
||||
self.matching_streams.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn application_id() -> ApplicationId {
|
||||
ApplicationId::new("browser").expect("valid application ID")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_matching_is_whole_string_and_case_sensitive() {
|
||||
let selector = ApplicationSelector::exact(MetadataField::ApplicationName, "Firefox")
|
||||
.expect("valid selector");
|
||||
|
||||
assert!(selector.matches(&StreamMetadata::new().with_application_name("Firefox")));
|
||||
assert!(!selector.matches(&StreamMetadata::new().with_application_name("firefox")));
|
||||
assert!(!selector.matches(&StreamMetadata::new().with_application_name("Firefox Beta")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_searches_substrings_unless_anchored() {
|
||||
let substring = ApplicationSelector::regex(MetadataField::ProcessBinary, "firefox")
|
||||
.expect("valid regex");
|
||||
let anchored = ApplicationSelector::regex(MetadataField::ProcessBinary, "^firefox$")
|
||||
.expect("valid regex");
|
||||
let metadata = StreamMetadata::new().with_process_binary("firefox-beta");
|
||||
|
||||
assert!(substring.matches(&metadata));
|
||||
assert!(!anchored.matches(&metadata));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_field_does_not_fall_back_to_raw_or_another_field() {
|
||||
let selector = ApplicationSelector::exact(MetadataField::ApplicationName, "Player")
|
||||
.expect("valid selector");
|
||||
let metadata = StreamMetadata::new()
|
||||
.with_media_name("Player")
|
||||
.with_raw_property("application.name", "Player");
|
||||
|
||||
assert!(!selector.matches(&metadata));
|
||||
assert_eq!(
|
||||
metadata.raw().get("application.name").map(String::as_str),
|
||||
Some("Player")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_selectors_are_ored() {
|
||||
let matcher = ApplicationMatcher::new(
|
||||
application_id(),
|
||||
vec![
|
||||
ApplicationSelector::exact(MetadataField::ApplicationName, "Firefox")
|
||||
.expect("valid selector"),
|
||||
ApplicationSelector::regex(MetadataField::ProcessBinary, "^(firefox|librewolf)$")
|
||||
.expect("valid selector"),
|
||||
],
|
||||
)
|
||||
.expect("application has selectors");
|
||||
|
||||
assert!(matcher.matches(&StreamMetadata::new().with_process_binary("librewolf")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_conjunction_is_rejected_instead_of_matching_everything() {
|
||||
assert!(matches!(
|
||||
ApplicationMatcher::with_mode(application_id(), vec![], SelectorMode::All),
|
||||
Err(SelectorError::NoSelectors { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_and_unbounded_patterns_are_rejected() {
|
||||
assert!(matches!(
|
||||
ApplicationSelector::regex(MetadataField::ApplicationName, "("),
|
||||
Err(SelectorError::InvalidRegex { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
ApplicationSelector::exact(MetadataField::ApplicationName, "x".repeat(257)),
|
||||
Err(SelectorError::PatternTooLong { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_tracks_multiple_streams_and_remains_configured_offline() {
|
||||
let matcher = ApplicationMatcher::new(
|
||||
application_id(),
|
||||
vec![
|
||||
ApplicationSelector::exact(MetadataField::ApplicationId, "org.mozilla.firefox")
|
||||
.expect("valid selector"),
|
||||
],
|
||||
)
|
||||
.expect("application has selectors");
|
||||
let mut runtime = ApplicationRuntime::new(matcher);
|
||||
let metadata = StreamMetadata::new().with_application_id("org.mozilla.firefox");
|
||||
let first = StreamHandle::new(BackendEpoch::new(1), 7, 1);
|
||||
let second = StreamHandle::new(BackendEpoch::new(1), 8, 1);
|
||||
|
||||
assert!(runtime.is_offline());
|
||||
assert!(runtime.upsert(first, &metadata));
|
||||
assert!(runtime.upsert(second, &metadata));
|
||||
assert_eq!(runtime.matching_streams().len(), 2);
|
||||
assert!(runtime.remove(first));
|
||||
assert!(runtime.remove(second));
|
||||
assert!(runtime.is_offline());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backend_id_reuse_cannot_remove_a_new_incarnation() {
|
||||
let matcher = ApplicationMatcher::new(
|
||||
application_id(),
|
||||
vec![
|
||||
ApplicationSelector::exact(MetadataField::ApplicationName, "Browser")
|
||||
.expect("valid selector"),
|
||||
],
|
||||
)
|
||||
.expect("application has selectors");
|
||||
let mut runtime = ApplicationRuntime::new(matcher);
|
||||
let metadata = StreamMetadata::new().with_application_name("Browser");
|
||||
let old = StreamHandle::new(BackendEpoch::new(3), 42, 1);
|
||||
let replacement = StreamHandle::new(BackendEpoch::new(3), 42, 2);
|
||||
|
||||
assert!(runtime.upsert(old, &metadata));
|
||||
assert!(runtime.remove(old));
|
||||
assert!(runtime.upsert(replacement, &metadata));
|
||||
assert!(!runtime.remove(old));
|
||||
assert_eq!(runtime.matching_streams(), &BTreeSet::from([replacement]));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
//! Mute intent planning independent of gain and native audio state.
|
||||
use crate::{Mute, StreamHandle, ValueState};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Explicit mute actions or a toggle resolved at command acceptance time.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MuteIntent {
|
||||
/// Apply one value to every resolved stream.
|
||||
Set(Mute),
|
||||
/// Mute if any member is unmuted; otherwise unmute.
|
||||
Toggle,
|
||||
}
|
||||
|
||||
/// Aggregates observed mute values, preserving mixed and unavailable states.
|
||||
pub fn mute_view(values: impl IntoIterator<Item = Mute>) -> ValueState<Mute> {
|
||||
let mut values = values.into_iter();
|
||||
let Some(first) = values.next() else {
|
||||
return ValueState::Unavailable;
|
||||
};
|
||||
if values.any(|value| value != first) {
|
||||
ValueState::Mixed
|
||||
} else {
|
||||
ValueState::Uniform(first)
|
||||
}
|
||||
}
|
||||
|
||||
/// Serial command intent shared by overlapping targets.
|
||||
///
|
||||
/// Pending intent affects subsequent toggles, never the observed mute view.
|
||||
/// The state owner clears a stream when its latest operation settles or is
|
||||
/// cancelled, and on removal/disconnect. Older operation completions must not
|
||||
/// clear a newer intent; operation correlation belongs to the server reducer.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct MutePlanner {
|
||||
pending: BTreeMap<StreamHandle, Mute>,
|
||||
}
|
||||
|
||||
impl MutePlanner {
|
||||
/// Resolves an action into one explicit mute command per stream.
|
||||
/// No channel gain is accepted or modified by this API.
|
||||
pub fn plan(
|
||||
&mut self,
|
||||
observed: &BTreeMap<StreamHandle, Mute>,
|
||||
intent: MuteIntent,
|
||||
) -> BTreeMap<StreamHandle, Mute> {
|
||||
let value = match intent {
|
||||
MuteIntent::Set(value) => value,
|
||||
MuteIntent::Toggle => {
|
||||
let any_unmuted = observed.iter().any(|(handle, value)| {
|
||||
self.pending.get(handle).unwrap_or(value) == &Mute::Unmuted
|
||||
});
|
||||
if any_unmuted {
|
||||
Mute::Muted
|
||||
} else {
|
||||
Mute::Unmuted
|
||||
}
|
||||
}
|
||||
};
|
||||
let commands: BTreeMap<_, _> = observed.keys().map(|handle| (*handle, value)).collect();
|
||||
self.pending
|
||||
.extend(commands.iter().map(|(handle, value)| (*handle, *value)));
|
||||
commands
|
||||
}
|
||||
|
||||
/// Releases intent only after the owner has checked operation freshness.
|
||||
pub fn clear(&mut self, handle: StreamHandle) {
|
||||
self.pending.remove(&handle);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
use crate::Gain;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Observable state of one non-motorized absolute control.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum PickupState {
|
||||
/// No live target is available, such as while offline or disconnected.
|
||||
Unavailable,
|
||||
/// Input is inhibited until the physical position reaches the live target.
|
||||
Waiting,
|
||||
/// Physical movement is allowed to emit volume commands.
|
||||
Tracking,
|
||||
}
|
||||
|
||||
/// Invalid pickup tolerance.
|
||||
#[derive(Clone, Copy, Debug, Error, PartialEq)]
|
||||
#[error("pickup tolerance {0} must be finite and within 0..=1")]
|
||||
pub struct PickupError(f64);
|
||||
|
||||
/// Pickup state for one non-motorized absolute control.
|
||||
///
|
||||
/// Arming deliberately forgets the prior physical sample. This prevents an
|
||||
/// external change, reconnect, rebind, or another surface's write from using a
|
||||
/// stale position to cross a new target.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Pickup {
|
||||
tolerance: f64,
|
||||
target: Option<Gain>,
|
||||
previous: Option<Gain>,
|
||||
state: PickupState,
|
||||
}
|
||||
|
||||
impl Pickup {
|
||||
/// Constructs pickup with a normalized crossing tolerance.
|
||||
pub fn new(tolerance: f64) -> Result<Self, PickupError> {
|
||||
if !tolerance.is_finite() || !(0.0..=1.0).contains(&tolerance) {
|
||||
return Err(PickupError(tolerance));
|
||||
}
|
||||
Ok(Self {
|
||||
tolerance,
|
||||
target: None,
|
||||
previous: None,
|
||||
state: PickupState::Unavailable,
|
||||
})
|
||||
}
|
||||
|
||||
/// Arms against the newest observed target without emitting a command.
|
||||
/// Targets above the physical range are reachable at its upper endpoint.
|
||||
pub fn arm(&mut self, observed: Gain) {
|
||||
self.target = Some(if observed > Gain::UNITY {
|
||||
Gain::UNITY
|
||||
} else {
|
||||
observed
|
||||
});
|
||||
self.previous = None;
|
||||
self.state = PickupState::Waiting;
|
||||
}
|
||||
|
||||
/// Makes input unavailable and discards all physical history.
|
||||
pub fn disconnect(&mut self) {
|
||||
self.target = None;
|
||||
self.previous = None;
|
||||
self.state = PickupState::Unavailable;
|
||||
}
|
||||
|
||||
/// Processes one normalized physical position.
|
||||
///
|
||||
/// Returns a command value only after entering the tolerance window or
|
||||
/// crossing the target between two consecutive samples.
|
||||
pub fn input(&mut self, position: Gain) -> Option<Gain> {
|
||||
match self.state {
|
||||
PickupState::Unavailable => None,
|
||||
PickupState::Tracking => Some(position),
|
||||
PickupState::Waiting => {
|
||||
let target = self.target?;
|
||||
let within = (position.get() - target.get()).abs() <= self.tolerance;
|
||||
let crossed = self.previous.is_some_and(|previous| {
|
||||
(previous < target && position > target)
|
||||
|| (previous > target && position < target)
|
||||
});
|
||||
self.previous = Some(position);
|
||||
if within || crossed {
|
||||
self.state = PickupState::Tracking;
|
||||
Some(position)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Current pickup state for TUI and feedback views.
|
||||
#[must_use]
|
||||
pub const fn state(&self) -> PickupState {
|
||||
self.state
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
/// Monotonic revision of domain-visible state.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct Revision(u64);
|
||||
|
||||
impl Revision {
|
||||
/// Initial revision before any accepted state change.
|
||||
pub const INITIAL: Self = Self(0);
|
||||
|
||||
/// Creates a revision from its persisted/wire representation.
|
||||
#[must_use]
|
||||
pub const fn new(value: u64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
/// Returns the numeric wire representation.
|
||||
#[must_use]
|
||||
pub const fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Advances the revision, returning `None` rather than wrapping.
|
||||
#[must_use]
|
||||
pub const fn checked_next(self) -> Option<Self> {
|
||||
match self.0.checked_add(1) {
|
||||
Some(next) => Some(Self(next)),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Connection generation used to reject events from an obsolete backend.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct BackendEpoch(u64);
|
||||
|
||||
impl BackendEpoch {
|
||||
/// Initial epoch before the first connection is established.
|
||||
pub const INITIAL: Self = Self(0);
|
||||
|
||||
/// Creates an epoch from its numeric representation.
|
||||
#[must_use]
|
||||
pub const fn new(value: u64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
/// Returns the numeric representation.
|
||||
#[must_use]
|
||||
pub const fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Advances the epoch, returning `None` rather than wrapping.
|
||||
#[must_use]
|
||||
pub const fn checked_next(self) -> Option<Self> {
|
||||
match self.0.checked_add(1) {
|
||||
Some(next) => Some(Self(next)),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn counters_advance_without_wrapping() {
|
||||
assert_eq!(Revision::INITIAL.checked_next(), Some(Revision::new(1)));
|
||||
assert_eq!(Revision::new(u64::MAX).checked_next(), None);
|
||||
assert_eq!(
|
||||
BackendEpoch::INITIAL.checked_next(),
|
||||
Some(BackendEpoch::new(1))
|
||||
);
|
||||
assert_eq!(BackendEpoch::new(u64::MAX).checked_next(), None);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
//! Validated logical targets and deterministic stream resolution.
|
||||
|
||||
use crate::{ApplicationId, FaderId, GroupId, StreamHandle};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use thiserror::Error;
|
||||
|
||||
/// A logical target; group nesting is deliberately not representable.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum Target {
|
||||
/// Every stream belonging to one configured application.
|
||||
Application(ApplicationId),
|
||||
/// The union of the streams belonging to member applications.
|
||||
Group(GroupId),
|
||||
}
|
||||
|
||||
/// A dangling configuration reference or unknown command target.
|
||||
#[derive(Clone, Debug, Error, Eq, PartialEq)]
|
||||
pub enum RoutingError {
|
||||
/// Application is absent from the configured application set.
|
||||
#[error("unknown application {0}")]
|
||||
Application(ApplicationId),
|
||||
/// Group is absent from the configured group map.
|
||||
#[error("unknown group {0}")]
|
||||
Group(GroupId),
|
||||
/// Fader is absent from the configured fader map.
|
||||
#[error("unknown fader {0}")]
|
||||
Fader(FaderId),
|
||||
}
|
||||
|
||||
/// Immutable, validated configuration graph. Live membership is supplied separately.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Routing {
|
||||
groups: BTreeMap<GroupId, Vec<ApplicationId>>,
|
||||
faders: BTreeMap<FaderId, Target>,
|
||||
}
|
||||
|
||||
impl Routing {
|
||||
/// Validates all references before accepting the configuration graph.
|
||||
pub fn new(
|
||||
applications: BTreeSet<ApplicationId>,
|
||||
groups: BTreeMap<GroupId, Vec<ApplicationId>>,
|
||||
faders: BTreeMap<FaderId, Target>,
|
||||
) -> Result<Self, RoutingError> {
|
||||
for member in groups.values().flatten() {
|
||||
if !applications.contains(member) {
|
||||
return Err(RoutingError::Application(member.clone()));
|
||||
}
|
||||
}
|
||||
for target in faders.values() {
|
||||
match target {
|
||||
Target::Application(id) if !applications.contains(id) => {
|
||||
return Err(RoutingError::Application(id.clone()));
|
||||
}
|
||||
Target::Group(id) if !groups.contains_key(id) => {
|
||||
return Err(RoutingError::Group(id.clone()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Self { groups, faders })
|
||||
}
|
||||
|
||||
/// Resolves one command to a deduplicated, deterministic stream set.
|
||||
/// Missing live membership means offline, while unknown faders are errors.
|
||||
pub fn resolve(
|
||||
&self,
|
||||
fader: &FaderId,
|
||||
live: &BTreeMap<ApplicationId, BTreeSet<StreamHandle>>,
|
||||
) -> Result<BTreeSet<StreamHandle>, RoutingError> {
|
||||
let target = self
|
||||
.faders
|
||||
.get(fader)
|
||||
.ok_or_else(|| RoutingError::Fader(fader.clone()))?;
|
||||
match target {
|
||||
Target::Application(id) => Ok(live.get(id).cloned().unwrap_or_default()),
|
||||
Target::Group(id) => {
|
||||
let members = self
|
||||
.groups
|
||||
.get(id)
|
||||
.ok_or_else(|| RoutingError::Group(id.clone()))?;
|
||||
Ok(members
|
||||
.iter()
|
||||
.filter_map(|member| live.get(member))
|
||||
.flatten()
|
||||
.copied()
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,417 @@
|
|||
//! Pure server reducer and adapter effects.
|
||||
|
||||
use crate::{ChannelGainError, ChannelGains, Gain, Mute, Revision, StreamHandle};
|
||||
use std::collections::BTreeMap;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Monotonic identifier for one accepted adapter operation.
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub struct OperationId(u64);
|
||||
|
||||
impl OperationId {
|
||||
/// Creates an identifier at an adapter or wire boundary.
|
||||
#[must_use]
|
||||
pub const fn new(value: u64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Source of a command accepted by the state owner.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum CommandOrigin {
|
||||
Midi { surface: String, sequence: u64 },
|
||||
Client { request: u64 },
|
||||
Restore,
|
||||
}
|
||||
|
||||
/// A validated command addressed to one resolved stream.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ServerCommand {
|
||||
SetVolume {
|
||||
origin: CommandOrigin,
|
||||
expected_revision: Revision,
|
||||
stream: StreamHandle,
|
||||
target: Gain,
|
||||
},
|
||||
SetMute {
|
||||
origin: CommandOrigin,
|
||||
expected_revision: Revision,
|
||||
stream: StreamHandle,
|
||||
muted: Mute,
|
||||
},
|
||||
}
|
||||
|
||||
/// Commands emitted to an audio adapter.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AdapterCommand {
|
||||
SetVolume {
|
||||
operation: OperationId,
|
||||
stream: StreamHandle,
|
||||
channels: ChannelGains,
|
||||
},
|
||||
SetMute {
|
||||
operation: OperationId,
|
||||
stream: StreamHandle,
|
||||
muted: Mute,
|
||||
},
|
||||
Readback {
|
||||
operation: OperationId,
|
||||
stream: StreamHandle,
|
||||
},
|
||||
}
|
||||
|
||||
/// Events copied from an audio adapter into the state owner.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AdapterEvent {
|
||||
Observed {
|
||||
stream: StreamHandle,
|
||||
channels: ChannelGains,
|
||||
muted: Mute,
|
||||
operation: Option<OperationId>,
|
||||
},
|
||||
WriteAccepted {
|
||||
operation: OperationId,
|
||||
},
|
||||
WriteFailed {
|
||||
operation: OperationId,
|
||||
message: String,
|
||||
},
|
||||
WriteSuperseded {
|
||||
operation: OperationId,
|
||||
},
|
||||
StreamRemoved {
|
||||
stream: StreamHandle,
|
||||
},
|
||||
}
|
||||
|
||||
/// Immutable state published to clients and feedback workers.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct StreamView {
|
||||
pub stream: StreamHandle,
|
||||
pub revision: Revision,
|
||||
pub channels: ChannelGains,
|
||||
pub muted: Mute,
|
||||
pub desired_gain: Option<Gain>,
|
||||
pub desired_mute: Option<Mute>,
|
||||
pub pending: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Effects produced by one deterministic reducer step.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Transition {
|
||||
pub adapter: Vec<AdapterCommand>,
|
||||
pub confirmed: Vec<StreamView>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum Property {
|
||||
Volume,
|
||||
Mute,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Pending {
|
||||
stream: StreamHandle,
|
||||
property: Property,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct StreamState {
|
||||
channels: ChannelGains,
|
||||
muted: Mute,
|
||||
desired_gain: Option<Gain>,
|
||||
desired_mute: Option<Mute>,
|
||||
volume_operation: Option<OperationId>,
|
||||
mute_operation: Option<OperationId>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// Errors that reject a command before dispatch.
|
||||
#[derive(Debug, Error, PartialEq)]
|
||||
pub enum ReducerError {
|
||||
#[error("stale revision {actual:?}; current revision is {current:?}")]
|
||||
StaleRevision { actual: Revision, current: Revision },
|
||||
#[error("stream {0:?} is not currently observed")]
|
||||
Offline(StreamHandle),
|
||||
#[error(transparent)]
|
||||
Channels(#[from] ChannelGainError),
|
||||
#[error("revision counter exhausted")]
|
||||
RevisionExhausted,
|
||||
#[error("operation counter exhausted")]
|
||||
OperationExhausted,
|
||||
}
|
||||
|
||||
/// Single owner of desired, pending, and observed stream state.
|
||||
#[derive(Debug)]
|
||||
pub struct ServerReducer {
|
||||
revision: Revision,
|
||||
next_operation: u64,
|
||||
write_ceiling: Gain,
|
||||
streams: BTreeMap<StreamHandle, StreamState>,
|
||||
operations: BTreeMap<OperationId, Pending>,
|
||||
active_epoch: Option<crate::BackendEpoch>,
|
||||
}
|
||||
|
||||
impl ServerReducer {
|
||||
#[must_use]
|
||||
pub fn new(write_ceiling: Gain) -> Self {
|
||||
Self {
|
||||
revision: Revision::INITIAL,
|
||||
next_operation: 1,
|
||||
write_ceiling,
|
||||
streams: BTreeMap::new(),
|
||||
operations: BTreeMap::new(),
|
||||
active_epoch: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn revision(&self) -> Revision {
|
||||
self.revision
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn view(&self, stream: StreamHandle) -> Option<StreamView> {
|
||||
self.streams
|
||||
.get(&stream)
|
||||
.map(|state| self.stream_view(stream, state))
|
||||
}
|
||||
|
||||
pub fn command(&mut self, command: ServerCommand) -> Result<Transition, ReducerError> {
|
||||
let expected = match &command {
|
||||
ServerCommand::SetVolume {
|
||||
expected_revision, ..
|
||||
}
|
||||
| ServerCommand::SetMute {
|
||||
expected_revision, ..
|
||||
} => *expected_revision,
|
||||
};
|
||||
if expected != self.revision {
|
||||
return Err(ReducerError::StaleRevision {
|
||||
actual: expected,
|
||||
current: self.revision,
|
||||
});
|
||||
}
|
||||
match command {
|
||||
ServerCommand::SetVolume { stream, target, .. } => {
|
||||
let channels = self
|
||||
.streams
|
||||
.get(&stream)
|
||||
.ok_or(ReducerError::Offline(stream))?
|
||||
.channels
|
||||
.scaled_to(target, self.write_ceiling)?;
|
||||
let operation = self.operation(stream, Property::Volume)?;
|
||||
let state = self
|
||||
.streams
|
||||
.get_mut(&stream)
|
||||
.ok_or(ReducerError::Offline(stream))?;
|
||||
state.desired_gain = Some(target);
|
||||
state.volume_operation = Some(operation);
|
||||
state.error = None;
|
||||
self.advance_revision()?;
|
||||
Ok(Transition {
|
||||
adapter: vec![AdapterCommand::SetVolume {
|
||||
operation,
|
||||
stream,
|
||||
channels,
|
||||
}],
|
||||
confirmed: Vec::new(),
|
||||
})
|
||||
}
|
||||
ServerCommand::SetMute { stream, muted, .. } => {
|
||||
let operation = self.operation(stream, Property::Mute)?;
|
||||
let state = self
|
||||
.streams
|
||||
.get_mut(&stream)
|
||||
.ok_or(ReducerError::Offline(stream))?;
|
||||
state.desired_mute = Some(muted);
|
||||
state.mute_operation = Some(operation);
|
||||
state.error = None;
|
||||
self.advance_revision()?;
|
||||
Ok(Transition {
|
||||
adapter: vec![AdapterCommand::SetMute {
|
||||
operation,
|
||||
stream,
|
||||
muted,
|
||||
}],
|
||||
confirmed: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn event(&mut self, event: AdapterEvent) -> Result<Transition, ReducerError> {
|
||||
match event {
|
||||
AdapterEvent::Observed {
|
||||
stream,
|
||||
channels,
|
||||
muted,
|
||||
operation,
|
||||
} => {
|
||||
if self.event_is_stale(stream) {
|
||||
return Ok(Transition::default());
|
||||
}
|
||||
self.adopt_epoch_and_incarnation(stream);
|
||||
if let Some(operation) = operation {
|
||||
self.settle_if_current(operation);
|
||||
}
|
||||
let state = self.streams.entry(stream).or_insert_with(|| StreamState {
|
||||
channels: channels.clone(),
|
||||
muted,
|
||||
desired_gain: None,
|
||||
desired_mute: None,
|
||||
volume_operation: None,
|
||||
mute_operation: None,
|
||||
error: None,
|
||||
});
|
||||
state.channels = channels;
|
||||
state.muted = muted;
|
||||
state.error = None;
|
||||
self.advance_revision()?;
|
||||
let view = self.view(stream).ok_or(ReducerError::Offline(stream))?;
|
||||
Ok(Transition {
|
||||
adapter: Vec::new(),
|
||||
confirmed: vec![view],
|
||||
})
|
||||
}
|
||||
AdapterEvent::WriteAccepted { operation } => {
|
||||
let Some(pending) = self.operations.get(&operation) else {
|
||||
return Ok(Transition::default());
|
||||
};
|
||||
Ok(Transition {
|
||||
adapter: vec![AdapterCommand::Readback {
|
||||
operation,
|
||||
stream: pending.stream,
|
||||
}],
|
||||
confirmed: Vec::new(),
|
||||
})
|
||||
}
|
||||
AdapterEvent::WriteFailed { operation, message } => {
|
||||
let stream = self
|
||||
.operations
|
||||
.get(&operation)
|
||||
.map(|pending| pending.stream);
|
||||
if let Some(stream) = stream
|
||||
&& self.settle_if_current(operation)
|
||||
&& let Some(state) = self.streams.get_mut(&stream)
|
||||
{
|
||||
state.error = Some(message);
|
||||
self.advance_revision()?;
|
||||
let view = self.view(stream).ok_or(ReducerError::Offline(stream))?;
|
||||
return Ok(Transition {
|
||||
adapter: Vec::new(),
|
||||
confirmed: vec![view],
|
||||
});
|
||||
}
|
||||
Ok(Transition::default())
|
||||
}
|
||||
AdapterEvent::WriteSuperseded { operation } => {
|
||||
self.operations.remove(&operation);
|
||||
Ok(Transition::default())
|
||||
}
|
||||
AdapterEvent::StreamRemoved { stream } => {
|
||||
self.streams.remove(&stream);
|
||||
self.operations
|
||||
.retain(|_, pending| pending.stream != stream);
|
||||
self.advance_revision()?;
|
||||
Ok(Transition::default())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn operation(
|
||||
&mut self,
|
||||
stream: StreamHandle,
|
||||
property: Property,
|
||||
) -> Result<OperationId, ReducerError> {
|
||||
if !self.streams.contains_key(&stream) {
|
||||
return Err(ReducerError::Offline(stream));
|
||||
}
|
||||
let operation = OperationId(self.next_operation);
|
||||
self.next_operation = self
|
||||
.next_operation
|
||||
.checked_add(1)
|
||||
.ok_or(ReducerError::OperationExhausted)?;
|
||||
self.operations
|
||||
.insert(operation, Pending { stream, property });
|
||||
Ok(operation)
|
||||
}
|
||||
|
||||
fn event_is_stale(&self, stream: StreamHandle) -> bool {
|
||||
if self
|
||||
.active_epoch
|
||||
.is_some_and(|epoch| stream.epoch() < epoch)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
self.streams.keys().any(|known| {
|
||||
known.epoch() == stream.epoch()
|
||||
&& known.backend_id() == stream.backend_id()
|
||||
&& known.incarnation() > stream.incarnation()
|
||||
})
|
||||
}
|
||||
|
||||
fn adopt_epoch_and_incarnation(&mut self, stream: StreamHandle) {
|
||||
if self.active_epoch.is_none_or(|epoch| stream.epoch() > epoch) {
|
||||
self.active_epoch = Some(stream.epoch());
|
||||
self.streams.clear();
|
||||
self.operations.clear();
|
||||
}
|
||||
self.streams.retain(|known, _| {
|
||||
known.epoch() != stream.epoch()
|
||||
|| known.backend_id() != stream.backend_id()
|
||||
|| known.incarnation() >= stream.incarnation()
|
||||
});
|
||||
self.operations.retain(|_, pending| {
|
||||
pending.stream.epoch() != stream.epoch()
|
||||
|| pending.stream.backend_id() != stream.backend_id()
|
||||
|| pending.stream.incarnation() >= stream.incarnation()
|
||||
});
|
||||
}
|
||||
|
||||
fn settle_if_current(&mut self, operation: OperationId) -> bool {
|
||||
let Some(pending) = self.operations.remove(&operation) else {
|
||||
return false;
|
||||
};
|
||||
let Some(state) = self.streams.get_mut(&pending.stream) else {
|
||||
return false;
|
||||
};
|
||||
let slot = match pending.property {
|
||||
Property::Volume => &mut state.volume_operation,
|
||||
Property::Mute => &mut state.mute_operation,
|
||||
};
|
||||
if *slot == Some(operation) {
|
||||
*slot = None;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn advance_revision(&mut self) -> Result<(), ReducerError> {
|
||||
self.revision = self
|
||||
.revision
|
||||
.checked_next()
|
||||
.ok_or(ReducerError::RevisionExhausted)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stream_view(&self, stream: StreamHandle, state: &StreamState) -> StreamView {
|
||||
StreamView {
|
||||
stream,
|
||||
revision: self.revision,
|
||||
channels: state.channels.clone(),
|
||||
muted: state.muted,
|
||||
desired_gain: state.desired_gain,
|
||||
desired_mute: state.desired_mute,
|
||||
pending: state.volume_operation.is_some() || state.mute_operation.is_some(),
|
||||
error: state.error.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
/// Per-stream mute value, independent from gain.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub enum Mute {
|
||||
/// Audio is muted.
|
||||
Muted,
|
||||
/// Audio is not muted, even when its gain is zero.
|
||||
Unmuted,
|
||||
}
|
||||
|
||||
/// Whether a configured object currently resolves to live resources.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub enum Availability {
|
||||
/// At least one live resource is available.
|
||||
Online,
|
||||
/// No live resource is currently available.
|
||||
Offline,
|
||||
}
|
||||
|
||||
/// Aggregate state that preserves unavailable and heterogeneous values.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ValueState<T> {
|
||||
/// No value is currently observable.
|
||||
Unavailable,
|
||||
/// Every resolved member has the same value.
|
||||
Uniform(T),
|
||||
/// Resolved members have different values.
|
||||
Mixed,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zero_gain_does_not_imply_mute() {
|
||||
let gain_state = ValueState::Uniform(0_u8);
|
||||
let mute_state = ValueState::Uniform(Mute::Unmuted);
|
||||
|
||||
assert_eq!(gain_state, ValueState::Uniform(0));
|
||||
assert_eq!(mute_state, ValueState::Uniform(Mute::Unmuted));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,218 @@
|
|||
use thiserror::Error;
|
||||
|
||||
/// Why a scalar gain was rejected.
|
||||
#[derive(Clone, Copy, Debug, Error, PartialEq)]
|
||||
pub enum GainError {
|
||||
/// NaN and infinities cannot represent observable audio state.
|
||||
#[error("gain must be finite, found {0}")]
|
||||
NonFinite(f64),
|
||||
/// Negative amplitude is outside the domain.
|
||||
#[error("gain must be non-negative, found {0}")]
|
||||
Negative(f64),
|
||||
}
|
||||
|
||||
/// Finite, non-negative linear amplitude gain.
|
||||
///
|
||||
/// `1.0` is unity and `0.0` is silence. Values above unity are representable
|
||||
/// so external observations are not silently clamped; write paths apply their
|
||||
/// configured ceiling separately.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
|
||||
pub struct Gain(f64);
|
||||
|
||||
impl Gain {
|
||||
/// Silence.
|
||||
pub const SILENCE: Self = Self(0.0);
|
||||
/// Unity gain.
|
||||
pub const UNITY: Self = Self(1.0);
|
||||
|
||||
/// Validates a linear amplitude value.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`GainError`] for negative, NaN, or infinite values.
|
||||
pub fn new(value: f64) -> Result<Self, GainError> {
|
||||
if !value.is_finite() {
|
||||
return Err(GainError::NonFinite(value));
|
||||
}
|
||||
if value < 0.0 {
|
||||
return Err(GainError::Negative(value));
|
||||
}
|
||||
Ok(Self(value))
|
||||
}
|
||||
|
||||
/// Returns the linear amplitude value.
|
||||
#[must_use]
|
||||
pub const fn get(self) -> f64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Returns whether this value represents silence.
|
||||
#[must_use]
|
||||
pub fn is_silent(self) -> bool {
|
||||
self == Self::SILENCE
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a vector of channel gains or a balance-preserving operation failed.
|
||||
#[derive(Clone, Debug, Error, PartialEq)]
|
||||
pub enum ChannelGainError {
|
||||
/// A stream must expose at least one channel.
|
||||
#[error("channel gain vector must not be empty")]
|
||||
Empty,
|
||||
/// The requested maximum exceeds the configured write ceiling.
|
||||
#[error("target gain {target} exceeds write ceiling {ceiling}")]
|
||||
AboveWriteCeiling {
|
||||
/// Requested output maximum.
|
||||
target: f64,
|
||||
/// Configured maximum write gain.
|
||||
ceiling: f64,
|
||||
},
|
||||
/// A calculated scalar failed gain validation.
|
||||
#[error(transparent)]
|
||||
InvalidGain(#[from] GainError),
|
||||
}
|
||||
|
||||
/// Non-empty per-channel gain snapshot.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ChannelGains(Vec<Gain>);
|
||||
|
||||
impl ChannelGains {
|
||||
/// Constructs a non-empty channel vector.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`ChannelGainError::Empty`] when no channels are provided.
|
||||
pub fn new(channels: Vec<Gain>) -> Result<Self, ChannelGainError> {
|
||||
if channels.is_empty() {
|
||||
return Err(ChannelGainError::Empty);
|
||||
}
|
||||
Ok(Self(channels))
|
||||
}
|
||||
|
||||
/// Returns the channel values.
|
||||
#[must_use]
|
||||
pub fn as_slice(&self) -> &[Gain] {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Consumes the snapshot and returns its channel values.
|
||||
#[must_use]
|
||||
pub fn into_vec(self) -> Vec<Gain> {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Returns the loudest channel.
|
||||
#[must_use]
|
||||
pub fn maximum(&self) -> Gain {
|
||||
self.0
|
||||
.iter()
|
||||
.copied()
|
||||
.fold(Gain::SILENCE, |maximum, channel| {
|
||||
if channel > maximum { channel } else { maximum }
|
||||
})
|
||||
}
|
||||
|
||||
/// Scales every channel so the loudest reaches `target`.
|
||||
///
|
||||
/// Existing balance is preserved. An all-silent vector has no balance to
|
||||
/// preserve, so every channel is initialized to `target`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`ChannelGainError::AboveWriteCeiling`] when `target` exceeds
|
||||
/// `write_ceiling`.
|
||||
pub fn scaled_to(&self, target: Gain, write_ceiling: Gain) -> Result<Self, ChannelGainError> {
|
||||
if target > write_ceiling {
|
||||
return Err(ChannelGainError::AboveWriteCeiling {
|
||||
target: target.get(),
|
||||
ceiling: write_ceiling.get(),
|
||||
});
|
||||
}
|
||||
|
||||
let old_maximum = self.maximum();
|
||||
if old_maximum.is_silent() {
|
||||
return Ok(Self(vec![target; self.0.len()]));
|
||||
}
|
||||
|
||||
let channels = self
|
||||
.0
|
||||
.iter()
|
||||
.map(|channel| Gain::new((channel.get() / old_maximum.get()) * target.get()))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(Self(channels))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use proptest::prelude::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn gain(value: f64) -> Gain {
|
||||
Gain::new(value).expect("test gain must be valid")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_finite_and_negative_gain() {
|
||||
assert!(matches!(Gain::new(f64::NAN), Err(GainError::NonFinite(_))));
|
||||
assert!(matches!(
|
||||
Gain::new(f64::INFINITY),
|
||||
Err(GainError::NonFinite(_))
|
||||
));
|
||||
assert_eq!(Gain::new(-0.01), Err(GainError::Negative(-0.01)));
|
||||
assert_eq!(Gain::new(-0.0), Ok(Gain::SILENCE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initializes_silent_channels_equally() {
|
||||
let channels = ChannelGains::new(vec![Gain::SILENCE, Gain::SILENCE])
|
||||
.expect("non-empty channel vector");
|
||||
let scaled = channels
|
||||
.scaled_to(gain(0.75), Gain::UNITY)
|
||||
.expect("target is below ceiling");
|
||||
|
||||
assert_eq!(scaled.as_slice(), &[gain(0.75), gain(0.75)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_writes_above_the_explicit_ceiling() {
|
||||
let channels = ChannelGains::new(vec![Gain::UNITY]).expect("non-empty channel vector");
|
||||
assert_eq!(
|
||||
channels.scaled_to(gain(1.5), Gain::UNITY),
|
||||
Err(ChannelGainError::AboveWriteCeiling {
|
||||
target: 1.5,
|
||||
ceiling: 1.0,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn valid_gain_round_trips(value in 0.0_f64..=32.0) {
|
||||
let value = Gain::new(value).expect("generated gain is valid");
|
||||
prop_assert!(value.get().is_finite());
|
||||
prop_assert!(value.get() >= 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scaling_preserves_balance(
|
||||
left in 0.000_001_f64..=8.0,
|
||||
right in 0.000_001_f64..=8.0,
|
||||
target in 0.0_f64..=4.0,
|
||||
) {
|
||||
let original = ChannelGains::new(vec![gain(left), gain(right)])
|
||||
.expect("generated vector is non-empty");
|
||||
let scaled = original
|
||||
.scaled_to(gain(target), gain(4.0))
|
||||
.expect("generated target is within ceiling");
|
||||
|
||||
prop_assert!((scaled.maximum().get() - target).abs() <= f64::EPSILON * 8.0);
|
||||
if target > 0.0 {
|
||||
let original_ratio = left / right;
|
||||
let scaled_ratio = scaled.as_slice()[0].get() / scaled.as_slice()[1].get();
|
||||
prop_assert!((original_ratio - scaled_ratio).abs() <= original_ratio.abs() * 1e-12 + 1e-12);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
use fader_core::{
|
||||
Binding, BindingAction, BindingKey, Bindings, FaderId, MessageKind, MidiChannel, MidiData,
|
||||
SurfaceId,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn identical_controls_on_different_surfaces_are_independent() {
|
||||
let key = |surface| BindingKey {
|
||||
surface: SurfaceId::new(surface).unwrap(),
|
||||
channel: MidiChannel::new(1).unwrap(),
|
||||
kind: MessageKind::ControlChange,
|
||||
number: MidiData::new(7).unwrap(),
|
||||
};
|
||||
let left = Binding {
|
||||
fader: FaderId::new("left").unwrap(),
|
||||
action: BindingAction::Volume,
|
||||
};
|
||||
let right = Binding {
|
||||
fader: FaderId::new("right").unwrap(),
|
||||
action: BindingAction::ToggleMute,
|
||||
};
|
||||
let bindings =
|
||||
Bindings::new([(key("desk"), left.clone()), (key("stage"), right.clone())]).unwrap();
|
||||
assert_eq!(bindings.get(&key("desk")), Some(&left));
|
||||
assert_eq!(bindings.get(&key("stage")), Some(&right));
|
||||
assert_eq!(bindings.get(&key("absent")), None);
|
||||
assert!(Bindings::new([(key("desk"), left), (key("desk"), right)]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midi_ranges_validate_before_narrowing_or_index_conversion() {
|
||||
for channel in 1..=16 {
|
||||
assert_eq!(
|
||||
MidiChannel::new(channel).unwrap().wire_index(),
|
||||
(channel - 1) as u8
|
||||
);
|
||||
}
|
||||
for channel in [0, 17, 256, u16::MAX] {
|
||||
assert!(MidiChannel::new(channel).is_err());
|
||||
}
|
||||
assert_eq!(MidiData::new(127).unwrap().get(), 127);
|
||||
for data in [128, 256, u16::MAX] {
|
||||
assert!(MidiData::new(data).is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
use fader_core::{
|
||||
BackendEpoch, ChannelGains, Gain, RelativeGroupState, StreamHandle, plan_volume, volume_view,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn gain(value: f64) -> Gain {
|
||||
Gain::new(value).unwrap()
|
||||
}
|
||||
fn channels(values: &[f64]) -> ChannelGains {
|
||||
ChannelGains::new(values.iter().copied().map(gain).collect()).unwrap()
|
||||
}
|
||||
fn handle(id: u64) -> StreamHandle {
|
||||
StreamHandle::new(BackendEpoch::new(1), id, 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_plan_preserves_channel_balance_without_mutation() {
|
||||
let live = BTreeMap::from([
|
||||
(handle(1), channels(&[0.8, 0.4])),
|
||||
(handle(2), channels(&[0.2])),
|
||||
]);
|
||||
let before = live.clone();
|
||||
let absolute = plan_volume(&live, gain(0.4), Gain::UNITY).unwrap();
|
||||
assert_eq!(absolute[&handle(1)], channels(&[0.4, 0.2]));
|
||||
assert_eq!(absolute[&handle(2)], channels(&[0.4]));
|
||||
let clipped = plan_volume(&live, gain(2.0), Gain::UNITY).unwrap();
|
||||
assert_eq!(clipped[&handle(1)], channels(&[1.0, 0.5]));
|
||||
assert_eq!(clipped[&handle(2)], channels(&[1.0]));
|
||||
assert_eq!(live, before);
|
||||
assert!(volume_view(&live).unwrap().mixed);
|
||||
assert_eq!(volume_view(&live).unwrap().maximum, gain(0.8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_absolute_groups_have_explicit_behavior() {
|
||||
let empty = BTreeMap::new();
|
||||
assert_eq!(volume_view(&empty), None);
|
||||
assert!(
|
||||
plan_volume(&empty, Gain::UNITY, Gain::UNITY)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_group_scales_zero_to_each_members_remembered_maximum() {
|
||||
let mut group = RelativeGroupState::new();
|
||||
group.observe_independent(handle(1), channels(&[0.8, 0.4]));
|
||||
group.observe_independent(handle(2), channels(&[0.2]));
|
||||
|
||||
let half = group.plan(gain(0.5), Gain::UNITY).unwrap();
|
||||
assert_eq!(half[&handle(1)], channels(&[0.4, 0.2]));
|
||||
assert_eq!(half[&handle(2)], channels(&[0.1]));
|
||||
|
||||
let silent = group.plan(Gain::SILENCE, Gain::UNITY).unwrap();
|
||||
assert_eq!(silent[&handle(1)], channels(&[0.0, 0.0]));
|
||||
assert_eq!(silent[&handle(2)], channels(&[0.0]));
|
||||
|
||||
let restored = group.plan(Gain::UNITY, Gain::UNITY).unwrap();
|
||||
assert_eq!(restored[&handle(1)], channels(&[0.8, 0.4]));
|
||||
assert_eq!(restored[&handle(2)], channels(&[0.2]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_group_position_is_normalized() {
|
||||
let group = RelativeGroupState::new();
|
||||
let error = group.plan(gain(1.01), Gain::UNITY).unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
fader_core::ChannelGainError::AboveWriteCeiling {
|
||||
target: 1.01,
|
||||
ceiling: 1.0
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_or_external_changes_rebase_only_that_relative_member() {
|
||||
let mut group = RelativeGroupState::new();
|
||||
group.observe_independent(handle(1), channels(&[0.8]));
|
||||
group.observe_independent(handle(2), channels(&[0.2]));
|
||||
let _ = group.plan(gain(0.5), Gain::UNITY).unwrap();
|
||||
|
||||
group.observe_independent(handle(2), channels(&[0.6]));
|
||||
let next = group.plan(gain(0.5), Gain::UNITY).unwrap();
|
||||
assert_eq!(next[&handle(1)], channels(&[0.4]));
|
||||
assert_eq!(next[&handle(2)], channels(&[0.3]));
|
||||
|
||||
group.remove(handle(1));
|
||||
assert!(
|
||||
!group
|
||||
.plan(Gain::UNITY, Gain::UNITY)
|
||||
.unwrap()
|
||||
.contains_key(&handle(1))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_confirmation_and_new_members_do_not_change_absolute_semantics() {
|
||||
let mut live = BTreeMap::from([(handle(1), channels(&[0.8])), (handle(2), channels(&[0.2]))]);
|
||||
let plan = plan_volume(&live, gain(0.4), Gain::UNITY).unwrap();
|
||||
// Only the first stream confirms; the failed second stream stays truthful.
|
||||
live.insert(handle(1), plan[&handle(1)].clone());
|
||||
assert!(volume_view(&live).unwrap().mixed);
|
||||
assert_eq!(live[&handle(2)], channels(&[0.2]));
|
||||
// New streams are adopted without replaying the previous absolute intent.
|
||||
live.insert(handle(3), channels(&[1.0]));
|
||||
let next = plan_volume(&live, gain(0.5), Gain::UNITY).unwrap();
|
||||
assert_eq!(next[&handle(1)], channels(&[0.5]));
|
||||
assert_eq!(next[&handle(2)], channels(&[0.5]));
|
||||
assert_eq!(next[&handle(3)], channels(&[0.5]));
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
use fader_core::{
|
||||
BackendEpoch, Mute, MuteIntent, MutePlanner, StreamHandle, ValueState, mute_view,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn handle(id: u64) -> StreamHandle {
|
||||
StreamHandle::new(BackendEpoch::new(1), id, 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_toggles_mute_all_and_rapid_second_toggle_unmutes_all() {
|
||||
let observed = BTreeMap::from([(handle(1), Mute::Muted), (handle(2), Mute::Unmuted)]);
|
||||
let mut planner = MutePlanner::default();
|
||||
assert_eq!(mute_view(observed.values().copied()), ValueState::Mixed);
|
||||
let first = planner.plan(&observed, MuteIntent::Toggle);
|
||||
assert!(first.values().all(|value| *value == Mute::Muted));
|
||||
let second = planner.plan(&observed, MuteIntent::Toggle);
|
||||
assert!(second.values().all(|value| *value == Mute::Unmuted));
|
||||
// Intent does not change the reported observation.
|
||||
assert_eq!(mute_view(observed.values().copied()), ValueState::Mixed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_groups_share_pending_intent_and_set_unmute_clears_every_member() {
|
||||
let observed = BTreeMap::from([(handle(1), Mute::Unmuted), (handle(2), Mute::Muted)]);
|
||||
let mut planner = MutePlanner::default();
|
||||
planner.plan(&observed, MuteIntent::Set(Mute::Muted));
|
||||
let subset = BTreeMap::from([(handle(1), Mute::Unmuted)]);
|
||||
assert_eq!(
|
||||
planner.plan(&subset, MuteIntent::Toggle)[&handle(1)],
|
||||
Mute::Unmuted
|
||||
);
|
||||
assert!(
|
||||
planner
|
||||
.plan(&observed, MuteIntent::Set(Mute::Unmuted))
|
||||
.values()
|
||||
.all(|value| *value == Mute::Unmuted)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_has_no_commands_and_settled_or_removed_streams_use_observations() {
|
||||
let mut planner = MutePlanner::default();
|
||||
assert_eq!(mute_view([]), ValueState::Unavailable);
|
||||
assert!(
|
||||
planner
|
||||
.plan(&BTreeMap::new(), MuteIntent::Toggle)
|
||||
.is_empty()
|
||||
);
|
||||
let observed = BTreeMap::from([(handle(1), Mute::Unmuted)]);
|
||||
planner.plan(&observed, MuteIntent::Toggle);
|
||||
planner.clear(handle(1));
|
||||
assert_eq!(
|
||||
planner.plan(&observed, MuteIntent::Toggle)[&handle(1)],
|
||||
Mute::Muted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_muted_toggle_unmutes_and_uniform_observations_stay_explicit() {
|
||||
let observed = BTreeMap::from([(handle(1), Mute::Muted), (handle(2), Mute::Muted)]);
|
||||
assert_eq!(
|
||||
mute_view(observed.values().copied()),
|
||||
ValueState::Uniform(Mute::Muted)
|
||||
);
|
||||
assert!(
|
||||
MutePlanner::default()
|
||||
.plan(&observed, MuteIntent::Toggle)
|
||||
.values()
|
||||
.all(|value| *value == Mute::Unmuted)
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
use fader_core::{Gain, Pickup, PickupState};
|
||||
|
||||
fn gain(value: f64) -> Gain {
|
||||
Gain::new(value).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_position_cannot_jump_audio_until_the_target_is_crossed() {
|
||||
let mut pickup = Pickup::new(0.02).unwrap();
|
||||
pickup.arm(gain(0.7));
|
||||
|
||||
assert_eq!(pickup.input(gain(0.1)), None);
|
||||
assert_eq!(pickup.input(gain(0.6)), None);
|
||||
assert_eq!(pickup.input(gain(0.71)), Some(gain(0.71)));
|
||||
assert_eq!(pickup.state(), PickupState::Tracking);
|
||||
assert_eq!(pickup.input(gain(0.4)), Some(gain(0.4)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_activates_even_when_no_sample_lands_inside_tolerance() {
|
||||
let mut pickup = Pickup::new(0.01).unwrap();
|
||||
pickup.arm(gain(0.5));
|
||||
|
||||
assert_eq!(pickup.input(gain(0.3)), None);
|
||||
assert_eq!(pickup.input(gain(0.8)), Some(gain(0.8)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_change_and_reconnect_discard_the_old_physical_position() {
|
||||
let mut pickup = Pickup::new(0.02).unwrap();
|
||||
pickup.arm(gain(0.5));
|
||||
assert_eq!(pickup.input(gain(0.5)), Some(gain(0.5)));
|
||||
|
||||
pickup.arm(gain(0.8));
|
||||
assert_eq!(pickup.input(gain(0.4)), None);
|
||||
assert_eq!(pickup.input(gain(0.81)), Some(gain(0.81)));
|
||||
|
||||
pickup.disconnect();
|
||||
assert_eq!(pickup.state(), PickupState::Unavailable);
|
||||
assert_eq!(pickup.input(gain(0.2)), None);
|
||||
pickup.arm(gain(0.3));
|
||||
assert_eq!(pickup.input(gain(0.2)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_surface_move_rearms_pickup_and_amplified_targets_use_the_endpoint() {
|
||||
let mut left = Pickup::new(0.02).unwrap();
|
||||
let mut right = Pickup::new(0.02).unwrap();
|
||||
left.arm(gain(0.4));
|
||||
right.arm(gain(0.4));
|
||||
assert_eq!(left.input(gain(0.4)), Some(gain(0.4)));
|
||||
|
||||
right.arm(gain(0.8));
|
||||
assert_eq!(right.input(gain(0.1)), None);
|
||||
assert_eq!(right.input(gain(0.8)), Some(gain(0.8)));
|
||||
left.arm(gain(0.8));
|
||||
assert_eq!(left.input(gain(0.4)), None);
|
||||
|
||||
left.arm(gain(1.5));
|
||||
assert_eq!(left.input(Gain::UNITY), Some(Gain::UNITY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tolerance_must_be_a_finite_normalized_distance() {
|
||||
assert!(Pickup::new(-0.1).is_err());
|
||||
assert!(Pickup::new(1.1).is_err());
|
||||
assert!(Pickup::new(f64::NAN).is_err());
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use fader_core::{ApplicationId, BackendEpoch, FaderId, GroupId, Routing, StreamHandle, Target};
|
||||
|
||||
#[test]
|
||||
fn overlapping_applications_resolve_once_and_offline_members_remain_valid() {
|
||||
let browser = ApplicationId::new("browser").unwrap();
|
||||
let music = ApplicationId::new("music").unwrap();
|
||||
let group = GroupId::new("media").unwrap();
|
||||
let fader = FaderId::new("master").unwrap();
|
||||
let shared = StreamHandle::new(BackendEpoch::new(1), 9, 1);
|
||||
let routing = Routing::new(
|
||||
BTreeSet::from([browser.clone(), music.clone()]),
|
||||
BTreeMap::from([(group.clone(), vec![browser.clone(), music.clone()])]),
|
||||
BTreeMap::from([(fader.clone(), Target::Group(group))]),
|
||||
)
|
||||
.unwrap();
|
||||
let mut live = BTreeMap::from([
|
||||
(browser, BTreeSet::from([shared])),
|
||||
(music.clone(), BTreeSet::from([shared])),
|
||||
]);
|
||||
assert_eq!(
|
||||
routing.resolve(&fader, &live).unwrap(),
|
||||
BTreeSet::from([shared])
|
||||
);
|
||||
live.remove(&music);
|
||||
assert_eq!(
|
||||
routing.resolve(&fader, &live).unwrap(),
|
||||
BTreeSet::from([shared])
|
||||
);
|
||||
live.clear();
|
||||
assert!(routing.resolve(&fader, &live).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dangling_targets_are_rejected_before_routing() {
|
||||
assert!(
|
||||
Routing::new(
|
||||
BTreeSet::new(),
|
||||
BTreeMap::new(),
|
||||
BTreeMap::from([(
|
||||
FaderId::new("f").unwrap(),
|
||||
Target::Application(ApplicationId::new("missing").unwrap())
|
||||
)]),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_faders_can_share_one_target() {
|
||||
let app = ApplicationId::new("music").unwrap();
|
||||
let first = FaderId::new("first").unwrap();
|
||||
let second = FaderId::new("second").unwrap();
|
||||
let handle = StreamHandle::new(BackendEpoch::new(2), 3, 1);
|
||||
let routing = Routing::new(
|
||||
BTreeSet::from([app.clone()]),
|
||||
BTreeMap::new(),
|
||||
BTreeMap::from([
|
||||
(first.clone(), Target::Application(app.clone())),
|
||||
(second.clone(), Target::Application(app.clone())),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let live = BTreeMap::from([(app, BTreeSet::from([handle]))]);
|
||||
assert_eq!(
|
||||
routing.resolve(&first, &live),
|
||||
routing.resolve(&second, &live)
|
||||
);
|
||||
assert!(
|
||||
routing
|
||||
.resolve(&FaderId::new("unknown").unwrap(), &live)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
use fader_core::{
|
||||
AdapterCommand, AdapterEvent, BackendEpoch, ChannelGains, CommandOrigin, Gain, Mute, Revision,
|
||||
ServerCommand, ServerReducer, StreamHandle,
|
||||
};
|
||||
|
||||
fn stream() -> StreamHandle {
|
||||
StreamHandle::new(BackendEpoch::new(1), 7, 1)
|
||||
}
|
||||
fn channels(left: f64, right: f64) -> ChannelGains {
|
||||
ChannelGains::new(vec![Gain::new(left).unwrap(), Gain::new(right).unwrap()]).unwrap()
|
||||
}
|
||||
fn observe(reducer: &mut ServerReducer, gain: ChannelGains, muted: Mute) {
|
||||
reducer
|
||||
.event(AdapterEvent::Observed {
|
||||
stream: stream(),
|
||||
channels: gain,
|
||||
muted,
|
||||
operation: None,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intent_is_recorded_before_dispatch_and_only_observation_confirms_it() {
|
||||
let mut reducer = ServerReducer::new(Gain::UNITY);
|
||||
observe(&mut reducer, channels(0.25, 0.5), Mute::Unmuted);
|
||||
let transition = reducer
|
||||
.command(ServerCommand::SetVolume {
|
||||
origin: CommandOrigin::Client { request: 9 },
|
||||
expected_revision: reducer.revision(),
|
||||
stream: stream(),
|
||||
target: Gain::new(0.8).unwrap(),
|
||||
})
|
||||
.unwrap();
|
||||
let AdapterCommand::SetVolume { operation, .. } = &transition.adapter[0] else {
|
||||
panic!("volume effect expected");
|
||||
};
|
||||
let pending = reducer.view(stream()).unwrap();
|
||||
assert_eq!(pending.desired_gain, Some(Gain::new(0.8).unwrap()));
|
||||
assert_eq!(pending.channels, channels(0.25, 0.5));
|
||||
assert!(pending.pending);
|
||||
let accepted = reducer
|
||||
.event(AdapterEvent::WriteAccepted {
|
||||
operation: *operation,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
accepted.adapter.as_slice(),
|
||||
[AdapterCommand::Readback { .. }]
|
||||
));
|
||||
assert_eq!(
|
||||
reducer.view(stream()).unwrap().channels,
|
||||
channels(0.25, 0.5)
|
||||
);
|
||||
reducer
|
||||
.event(AdapterEvent::Observed {
|
||||
stream: stream(),
|
||||
channels: channels(0.4, 0.8),
|
||||
muted: Mute::Unmuted,
|
||||
operation: Some(*operation),
|
||||
})
|
||||
.unwrap();
|
||||
let confirmed = reducer.view(stream()).unwrap();
|
||||
assert_eq!(confirmed.channels, channels(0.4, 0.8));
|
||||
assert!(!confirmed.pending);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_keeps_observed_state_truthful() {
|
||||
let mut reducer = ServerReducer::new(Gain::UNITY);
|
||||
observe(&mut reducer, channels(0.3, 0.6), Mute::Unmuted);
|
||||
let transition = reducer
|
||||
.command(ServerCommand::SetMute {
|
||||
origin: CommandOrigin::Midi {
|
||||
surface: "desk".into(),
|
||||
sequence: 1,
|
||||
},
|
||||
expected_revision: reducer.revision(),
|
||||
stream: stream(),
|
||||
muted: Mute::Muted,
|
||||
})
|
||||
.unwrap();
|
||||
let AdapterCommand::SetMute { operation, .. } = transition.adapter[0] else {
|
||||
panic!("mute effect expected");
|
||||
};
|
||||
reducer
|
||||
.event(AdapterEvent::WriteFailed {
|
||||
operation,
|
||||
message: "adapter rejected write".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let view = reducer.view(stream()).unwrap();
|
||||
assert_eq!(view.muted, Mute::Unmuted);
|
||||
assert_eq!(view.desired_mute, Some(Mute::Muted));
|
||||
assert!(!view.pending);
|
||||
assert_eq!(view.error.as_deref(), Some("adapter rejected write"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_observation_updates_views_without_an_audio_effect() {
|
||||
let mut reducer = ServerReducer::new(Gain::UNITY);
|
||||
let transition = reducer
|
||||
.event(AdapterEvent::Observed {
|
||||
stream: stream(),
|
||||
channels: channels(0.2, 0.4),
|
||||
muted: Mute::Muted,
|
||||
operation: None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(transition.adapter.is_empty());
|
||||
assert_eq!(transition.confirmed.len(), 1);
|
||||
assert_eq!(transition.confirmed[0].revision, Revision::new(1));
|
||||
assert_eq!(transition.confirmed[0].muted, Mute::Muted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_completion_cannot_clear_newer_pending_intent() {
|
||||
let mut reducer = ServerReducer::new(Gain::UNITY);
|
||||
observe(&mut reducer, channels(0.2, 0.4), Mute::Unmuted);
|
||||
let first = reducer
|
||||
.command(ServerCommand::SetVolume {
|
||||
origin: CommandOrigin::Client { request: 1 },
|
||||
expected_revision: reducer.revision(),
|
||||
stream: stream(),
|
||||
target: Gain::new(0.5).unwrap(),
|
||||
})
|
||||
.unwrap();
|
||||
let second = reducer
|
||||
.command(ServerCommand::SetVolume {
|
||||
origin: CommandOrigin::Client { request: 2 },
|
||||
expected_revision: reducer.revision(),
|
||||
stream: stream(),
|
||||
target: Gain::new(0.8).unwrap(),
|
||||
})
|
||||
.unwrap();
|
||||
let AdapterCommand::SetVolume {
|
||||
operation: first, ..
|
||||
} = first.adapter[0]
|
||||
else {
|
||||
panic!("first volume operation");
|
||||
};
|
||||
let AdapterCommand::SetVolume {
|
||||
operation: second, ..
|
||||
} = second.adapter[0]
|
||||
else {
|
||||
panic!("second volume operation");
|
||||
};
|
||||
|
||||
reducer
|
||||
.event(AdapterEvent::Observed {
|
||||
stream: stream(),
|
||||
channels: channels(0.25, 0.5),
|
||||
muted: Mute::Unmuted,
|
||||
operation: Some(first),
|
||||
})
|
||||
.unwrap();
|
||||
assert!(reducer.view(stream()).unwrap().pending);
|
||||
reducer
|
||||
.event(AdapterEvent::Observed {
|
||||
stream: stream(),
|
||||
channels: channels(0.4, 0.8),
|
||||
muted: Mute::Unmuted,
|
||||
operation: Some(second),
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!reducer.view(stream()).unwrap().pending);
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
# Documentation
|
||||
|
||||
## Use and configuration
|
||||
|
||||
- [Build prerequisites](build.md) — Linux packages, Rust toolchain, feature
|
||||
combinations, and the current FreeBSD CI mode.
|
||||
- [Advanced configuration](configuration.md) — process layouts, managed
|
||||
profiles, TOML concepts, migration, validation, and operational commands.
|
||||
- [Example PipeWire/APC MINI profile](../examples/profiles/arch-pipewire.toml)
|
||||
- [Example desktop profile](../examples/profiles/desktop.toml)
|
||||
- [MPRIS controls and editing](configuration.md#media-controls-mpris)
|
||||
- [Example QBZ media profile](../examples/profiles/media-qbz.toml)
|
||||
- [Hands-on functional checklist](../checklist.md)
|
||||
|
||||
For everyday layout editing: select a fader or separator and press `E`.
|
||||
Separators accept empty names, independent size and decoration, and Fill space.
|
||||
Config contains theme/orientation/pickup display, hidden-fader restoration,
|
||||
profile switching, MIDI devices, and Save. See the
|
||||
[mixer presentation reference](configuration.md#mixer-presentation).
|
||||
|
||||
## Design and development
|
||||
|
||||
- [Architecture and library research](../architecture.md)
|
||||
- [Implementation tasks and acceptance tests](../task.md)
|
||||
- [Project-agent and commit workflow](../AGENTS.md)
|
||||
- [MIDI identity design](midi-identity.md)
|
||||
- [Pulse-compatible daemon fixture](pulse-daemon-fixture.md)
|
||||
- [CI coverage and badge lifecycle](ci-coverage.md)
|
||||
- [Release preparation and publication](releasing.md)
|
||||
- [Changelog](../CHANGELOG.md)
|
||||
|
||||
## Ecosystem
|
||||
|
||||
- [Related projects and libraries](related-projects.md)
|
||||
|
||||
## Screenshot maintenance
|
||||
|
||||
Both README screenshots are deterministic renders of the real TUI using
|
||||
example state, not captures of a live audio session:
|
||||
|
||||
- [Horizontal mixer](images/mixer-horizontal.svg): five side-by-side faders,
|
||||
a double divider, an unnamed Fill spacer, mute and group-mixed state.
|
||||
- [Vertical mixer](images/mixer-vertical.svg): section labels, Standard,
|
||||
Slim and Bordered slim rows, and the default output.
|
||||
|
||||
Regenerate all screenshots after presentation changes:
|
||||
|
||||
```sh
|
||||
cargo run --locked -p tui --example doc_screenshots
|
||||
```
|
||||
|
||||
The generator lives in [doc_screenshots.rs](../tui/examples/doc_screenshots.rs).
|
||||
It places text on the terminal cell grid and draws box/block glyphs to cell
|
||||
edges so font differences do not break borders or meters. Inspect both SVGs
|
||||
in a browser or rasterize with `rsvg-convert` for review; confirm every fader,
|
||||
label and keyboard hint is visible. Do not hand-edit the generated SVG files.
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
# Build prerequisites
|
||||
|
||||
`fader_master` targets Linux and uses Rust 2024. Rust 1.88.0 is the selected
|
||||
minimum supported Rust version (MSRV) and the repository-pinned development
|
||||
toolchain. `rustup` reads `rust-toolchain.toml` and installs the required
|
||||
`rustfmt`, Clippy, and LLVM tools components.
|
||||
|
||||
The default build includes the PulseAudio protocol adapter and links to
|
||||
libpulse. MPRIS is enabled by default and also links to libdbus-1. On a Debian-family Linux system, install:
|
||||
|
||||
```sh
|
||||
sudo apt-get install build-essential pkg-config libasound2-dev libpulse-dev libudev-dev libdbus-1-dev dbus
|
||||
rustup toolchain install 1.88.0 \
|
||||
--profile minimal \
|
||||
--component rustfmt \
|
||||
--component clippy \
|
||||
--component llvm-tools-preview
|
||||
```
|
||||
|
||||
On Arch Linux with PipeWire, install the client library, build tools, and the
|
||||
PulseAudio-compatible PipeWire service:
|
||||
|
||||
```sh
|
||||
sudo pacman -S --needed base-devel pkgconf alsa-lib libpulse systemd-libs dbus pipewire-audio pipewire-pulse wireplumber
|
||||
pactl info
|
||||
```
|
||||
|
||||
The executable's `mpris` feature can be omitted with
|
||||
`cargo build -p fader_master --no-default-features`; this disables only MPRIS,
|
||||
not the existing audio/MIDI backends. MPRIS runtime requires access to the user's
|
||||
session bus, not playerctl. CI native runners need libdbus development files too.
|
||||
The hardware-free protocol fixture runs with:
|
||||
|
||||
```sh
|
||||
dbus-run-session -- cargo test -p fader_master private_bus -- --ignored
|
||||
```
|
||||
|
||||
The `Server Name` reported by `pactl info` should contain `PulseAudio (on
|
||||
PipeWire ...)`. Arch packages the headers with `libpulse`, rather than in a
|
||||
separate development package. The application communicates with PipeWire
|
||||
through `pipewire-pulse`; it does not require the standalone PulseAudio server.
|
||||
|
||||
The Pulse adapter works with PulseAudio and PipeWire's pipewire-pulse
|
||||
compatibility service. MIDI input uses ALSA's sequencer API through `midir`, and
|
||||
Linux identity enrichment uses libudev. PipeWire does not replace the
|
||||
`alsa-lib` build dependency. To exclude native audio and MIDI dependencies,
|
||||
build the portable library/TUI subset used on FreeBSD and explicitly omit the
|
||||
Linux executable:
|
||||
|
||||
```sh
|
||||
cargo build --locked --no-default-features \
|
||||
-p fader-core -p fader-config -p midi -p volume_lib -p tui
|
||||
```
|
||||
|
||||
`--workspace --no-default-features` alone is not a native-free build: the
|
||||
executable's dependencies still enable the native MIDI and Pulse features.
|
||||
|
||||
The normal Linux release build produces all three entry points:
|
||||
|
||||
```sh
|
||||
cargo build --locked --workspace --release --all-features
|
||||
./target/release/fader_master
|
||||
# Or run separately, in two terminals:
|
||||
./target/release/fader_master_server
|
||||
./target/release/fader_master_client
|
||||
```
|
||||
|
||||
Restart both server and client when upgrading, including an external server
|
||||
that the all-in-one launcher might reuse. First-run configuration and MIDI
|
||||
setup are described in [Advanced configuration](configuration.md).
|
||||
|
||||
Future native PipeWire and ALSA mixer adapters will add their own feature-gated
|
||||
development packages. The MIDI crate can also be checked without its native
|
||||
transport and identity discovery while retaining byte decoding and routing:
|
||||
|
||||
```sh
|
||||
cargo check -p midi --no-default-features --locked
|
||||
```
|
||||
|
||||
From a fresh checkout, use the tracked lockfile for reproducible resolution:
|
||||
|
||||
```sh
|
||||
cargo build --workspace --locked
|
||||
cargo test --workspace --all-targets --all-features --locked
|
||||
```
|
||||
|
||||
Verify the MSRV explicitly without allowing `rust-toolchain.toml` to select a
|
||||
newer installed toolchain:
|
||||
|
||||
```sh
|
||||
cargo +1.88.0 check --workspace --all-targets --all-features --locked
|
||||
cargo +1.88.0 test --workspace --all-targets --all-features --locked
|
||||
```
|
||||
|
||||
## Jenkins backend modes
|
||||
|
||||
The current Jenkins worker is FreeBSD, so the job parameter
|
||||
`ENABLE_NATIVE_BACKENDS` defaults to false. In that mode CI checks, tests,
|
||||
documents, lints, and release-builds the portable `fader-core`, `fader-config`,
|
||||
`midi`, `volume_lib`, and `tui` packages with native features disabled. It does
|
||||
not build or test the Linux-only `fader_master` executable, MIDI transport,
|
||||
udev identity adapter, or Pulse adapter, and it publishes unavailable coverage
|
||||
rather than presenting partial coverage as the workspace measurement.
|
||||
|
||||
After Jenkins moves to a provisioned Linux worker, enable
|
||||
`ENABLE_NATIVE_BACKENDS` on the build (and change its default only after that
|
||||
build passes). This restores the complete default/no-default/all-feature
|
||||
workspace matrix, workspace coverage, doctests, strict documentation and
|
||||
Clippy, and the release executable assertion without changing the pipeline.
|
||||
|
|
@ -1,5 +1,11 @@
|
|||
# CI coverage and badge lifecycle
|
||||
|
||||
See [Build prerequisites](build.md) for the native and portable build commands.
|
||||
TUI rendering, separator presentation, and configuration round-trip tests are
|
||||
part of the portable suites. Unix-socket/server-restart tests require the
|
||||
Linux executable test suite; real audio fixtures remain separately opt-in.
|
||||
README screenshots are generated documentation assets, not coverage badges.
|
||||
|
||||
The generic renderer in `scripts/ci-coverage-badges.sh` is copied unchanged
|
||||
from `Dandaedre/agent-tasks` revision
|
||||
`fb9d8f7d16f100c2d1377f23394a2302eac9ab18`.
|
||||
|
|
@ -20,6 +26,12 @@ is not excluded. A valid current-build report is marked ready even when it is
|
|||
below the floor; missing or invalid reports fail with an unavailable diagnostic
|
||||
and cannot reuse an older value.
|
||||
|
||||
Coverage runs only when the Jenkins `ENABLE_NATIVE_BACKENDS` parameter is true.
|
||||
The temporary FreeBSD-compatible mode deliberately emits the neutral/unavailable
|
||||
coverage badge because its portable package subset would not be comparable to
|
||||
the full workspace measurement. Enabling the parameter on a provisioned Linux
|
||||
worker restores the existing coverage command and threshold.
|
||||
|
||||
The authoritative version is `[workspace.package].version` in the root
|
||||
`Cargo.toml`. During Jenkins cleanup, the current build's test marker determines
|
||||
the test badge, a ready marker preserves current measured coverage, and the
|
||||
|
|
|
|||
|
|
@ -0,0 +1,492 @@
|
|||
# Advanced configuration and operation
|
||||
|
||||
The TUI is the preferred interface for normal layout and binding changes. This
|
||||
document covers process topology, profile storage, hand-written TOML, and
|
||||
recovery workflows.
|
||||
|
||||
## Process layouts
|
||||
|
||||
For normal use, start the combined executable:
|
||||
|
||||
```sh
|
||||
fader_master --config /path/to/profile.toml --audio pulse
|
||||
```
|
||||
|
||||
It probes the per-user socket first. If a server is already available, only a
|
||||
client is started; otherwise an embedded server is kept alive for the lifetime
|
||||
of the TUI.
|
||||
|
||||
Installed builds also provide dedicated executables:
|
||||
|
||||
```sh
|
||||
fader_master_server --config /path/to/profile.toml --audio pulse
|
||||
fader_master_client
|
||||
```
|
||||
|
||||
The compatible `fader_master serve` and `fader_master tui` subcommands are
|
||||
available for scripts. Use `--socket PATH` on both sides only when deliberately
|
||||
running outside the normal XDG runtime location. `--theme THEME` is a client
|
||||
session override; changing the theme in the TUI updates the profile draft, and
|
||||
Config → Save persists it.
|
||||
|
||||
When connecting to an existing server, its active profile and audio backend
|
||||
remain authoritative. Restart both processes after a binary update; a new
|
||||
client cannot update the code inside an already-running server.
|
||||
|
||||
## Managed profiles and files
|
||||
|
||||
Without `--config`, fader_master uses the XDG layout:
|
||||
|
||||
| Purpose | Default path |
|
||||
|---|---|
|
||||
| Active profile selection | `~/.config/fader_master/config.toml` |
|
||||
| Profiles | `~/.config/fader_master/profiles/NAME.toml` |
|
||||
| Device documents | `~/.config/fader_master/devices/` |
|
||||
| Durable state | `~/.local/state/fader_master/state.toml` |
|
||||
| Local socket | `$XDG_RUNTIME_DIR/fader_master/control.sock` |
|
||||
|
||||
`XDG_CONFIG_HOME` and `XDG_STATE_HOME` replace their home-directory defaults
|
||||
when they are absolute. A runtime directory is required for the standalone
|
||||
local socket; no shared `/tmp` fallback is invented.
|
||||
|
||||
On first managed startup, a valid `default` profile and active selection are
|
||||
created. The profile starts with a safe Master-output fader. If exactly one MIDI
|
||||
input is visible, its port and available USB identity are adopted as the default
|
||||
controller; zero or multiple inputs are left for the user to choose. Config
|
||||
lists unconfigured inputs under **Detected MIDI ports**: open one, choose **Add
|
||||
as controller**, Save, then edit the Master fader and use Learn MIDI for volume
|
||||
and mute. This is enough to get a new installation working without editing TOML.
|
||||
Profiles created by an older version with no faders expose **Add Master output
|
||||
fader** in Config and can use the same setup path.
|
||||
|
||||
If the active selection names a missing managed profile, the same first-run
|
||||
profile is recreated with that validated ID. An explicitly supplied missing
|
||||
`--config` path remains an error so a typo cannot silently create a new file.
|
||||
|
||||
Switch an existing server to another managed profile with:
|
||||
|
||||
```sh
|
||||
fader_master profile switch PROFILE_ID
|
||||
```
|
||||
|
||||
The same adopt-mode switch is available in the TUI under Config → Active
|
||||
profile. The popup lists valid TOML profiles from the managed profile directory;
|
||||
malformed files are omitted.
|
||||
|
||||
Profile IDs are stable identifiers, not paths. Use `--restore` only when the
|
||||
saved desired state should deliberately be written after activation; the safe
|
||||
default adopts live audio without changing it.
|
||||
|
||||
## Profile model
|
||||
|
||||
Start from one of the tracked, validated examples:
|
||||
|
||||
- [`arch-pipewire.toml`](../examples/profiles/arch-pipewire.toml) demonstrates
|
||||
multiple applications, a group, APC MINI identity, volume/mute bindings, and
|
||||
green mute-button feedback.
|
||||
- [`desktop.toml`](../examples/profiles/desktop.toml) is a smaller profile with
|
||||
MIDI output feedback.
|
||||
|
||||
A profile contains these sections:
|
||||
|
||||
| TOML section | Purpose |
|
||||
|---|---|
|
||||
| Root fields | Schema version, stable profile ID, startup policy, and new-stream policy |
|
||||
| `[runtime]` | Poll interval from 1–100 ms; the default is 10 ms |
|
||||
| `[audio]` | `auto`, `pulse`, or reserved `pipewire` adapter selection, probe preference, and maximum gain |
|
||||
| `[ui]` | Mixer orientation, pickup-status presentation, default controller, and theme |
|
||||
| `[[applications]]` | A label and one or more metadata selectors |
|
||||
| `[[groups]]` | Application IDs combined under one logical target |
|
||||
| `[[surfaces]]` | Stable controller identity and MIDI input/output ports |
|
||||
| `[[faders]]` | Logical controls targeting an application, group, or output |
|
||||
| `[[mixer_layout]]` | Durable order, separators, visibility, and fader density |
|
||||
| `[[bindings]]` | Surface messages assigned to volume or mute actions |
|
||||
|
||||
The array sections default to empty and may be omitted. The TUI creates a
|
||||
missing section when the first corresponding object or MIDI binding is added;
|
||||
an omitted `[[bindings]]` section is therefore a valid profile, not corruption.
|
||||
If a section is present with the wrong shape or invalid contents, startup fails
|
||||
before activating the profile unless a supported schema migration can upgrade it.
|
||||
|
||||
### Application capture
|
||||
|
||||
MIDI feedback defaults to enabled. Set root-level `feedback_enabled = false`
|
||||
to disable all feedback, or put the same setting in a `[[faders]]` table to
|
||||
disable only that fader. Config and Edit fader expose these switches. Save the
|
||||
configuration to apply them. Disabled feedback sends nothing, even light-off
|
||||
messages; lights may retain their previous state until re-enabled and refreshed.
|
||||
|
||||
Selectors are ORed by default. Each selector chooses exactly one supported metadata field
|
||||
and exactly one matching mode:
|
||||
|
||||
```toml
|
||||
[[applications]]
|
||||
id = "browser"
|
||||
label = "Browser"
|
||||
selectors = [
|
||||
{ field = "application.process.binary", regex = "^(firefox|chromium)$" },
|
||||
{ field = "application.name", exact = "Web Browser" },
|
||||
]
|
||||
```
|
||||
|
||||
Supported fields are `application.name`, `application.id`,
|
||||
`application.process.binary`, `media.name`, `application.process.executable`,
|
||||
`application.process.working_directory`, `steam.app_id`, and `steam.game_id`.
|
||||
Exact matches are whole-string
|
||||
and case-sensitive. Regexes use Rust's bounded `regex` syntax.
|
||||
|
||||
The last four fields are best-effort Linux process observations, currently
|
||||
provided by the Pulse adapter (including PipeWire's Pulse compatibility server).
|
||||
Enrichment requires a reported PID and a machine ID matching `/etc/machine-id`.
|
||||
Executable and working-directory values come from `/proc`; Steam IDs come only
|
||||
from numeric, nonzero `SteamAppId` / `SteamGameId` environment entries. These
|
||||
are launch-context evidence, not authenticated proof that Steam launched the
|
||||
process. A path containing `steamapps` never creates a Steam ID.
|
||||
|
||||
Unavailable fields do not match. Processes that exit or change start time during
|
||||
inspection, restricted `/proc`, remote
|
||||
servers, container/PID namespace differences, and large environments can prevent
|
||||
enrichment. Environment reads are limited to 64 KiB; only the two allowlisted IDs
|
||||
are retained, never complete environment contents or command lines. Proton may
|
||||
report a Wine executable while its working directory identifies the game.
|
||||
The Config tab lists normalized fields for each observed stream, including
|
||||
`unavailable` values. Navigate down through Settings to inspect them; raw
|
||||
environment contents and command lines are never included.
|
||||
|
||||
Applications may set `selector_mode = "all"` to require every selector to
|
||||
match (AND). The default `"any"` preserves OR matching for existing profiles.
|
||||
The fader editor's **Match captures** row toggles **Any (OR)** / **All (AND)**
|
||||
for the application; save the configuration to activate the change. Individual
|
||||
Capture rows continue to edit their respective selectors without replacing the
|
||||
rest of the list.
|
||||
Missing fields fail their selector; empty selector lists and unknown modes are
|
||||
rejected. For example, requiring a particular application ID and media title:
|
||||
|
||||
```toml
|
||||
[[applications]]
|
||||
id = "music-video"
|
||||
label = "Music video"
|
||||
selector_mode = "all"
|
||||
selectors = [
|
||||
{ field = "application.id", exact = "example.player" },
|
||||
{ field = "media.name", regex = '(?i) - YouTube$' },
|
||||
]
|
||||
```
|
||||
|
||||
For the original YouTube-only capture use case, the single `media.name` selector
|
||||
below remains sufficient; no additional application condition is needed.
|
||||
|
||||
The capture editor's **Save and exit** row validates and saves the current
|
||||
field, match mode and pattern to the draft without reopening the pattern popup.
|
||||
Invalid patterns leave the editor open with an error. **Esc** cancels local
|
||||
capture changes; use the configuration **Save** action to persist and activate
|
||||
accepted draft changes.
|
||||
|
||||
To capture YouTube playback by its reported media title, use:
|
||||
|
||||
```toml
|
||||
selectors = [
|
||||
{ field = "media.name", regex = '(?i) - YouTube$' },
|
||||
]
|
||||
```
|
||||
|
||||
This already works when the browser exposes a title ending in ` - YouTube`
|
||||
(as observed with Waterfox). The media-title selector alone is sufficient;
|
||||
no browser-name condition or combined window-title matching is required.
|
||||
Applications must expose this metadata for it to match.
|
||||
|
||||
AND selectors, richer process metadata and direct MPRIS controls are implemented
|
||||
on the development branch after RC2; rebuild and restart both server and client.
|
||||
They are not required for the YouTube selector above.
|
||||
|
||||
### Media controls (MPRIS)
|
||||
|
||||
The **Media** tab (`3`, or `Tab`) appears when the server has MPRIS support and
|
||||
can connect to the user's session bus. No running players is a valid empty state.
|
||||
A later disconnect keeps the tab and configured entries visible. Config reports
|
||||
why support is unavailable. No keyboard emulation or `playerctl` is used; paused
|
||||
players are discoverable without an audio stream.
|
||||
|
||||
In Media, `A` adds an entry, `E` edits its name/selector/feedback/controls, and
|
||||
`D` asks before deleting the entry. Select a control and press `Enter` to send it.
|
||||
Unsupported, offline or ambiguous targets cannot be invoked. Draft edits must be
|
||||
saved with `S` before commands use them. Entries remain configured while offline.
|
||||
|
||||
In the entry editor, `P` lists discovered players. Selecting one prefers its
|
||||
stable DesktopEntry, falling back to its bus name. You can manually choose
|
||||
`bus_name`, `desktop_entry` or `identity`, and exact or regex matching. Regexes
|
||||
use substring matching unless anchored; `(?i)` enables case-insensitivity.
|
||||
Multiple matches block commands—narrow the selector to an exact instance when
|
||||
necessary. Instance-specific bus-name suffixes may change across restarts.
|
||||
Failed identity reads also block identity-based selection until discovery recovers.
|
||||
|
||||
`A` inside the editor adds a control, and `D` removes the selected control from
|
||||
the local edit. Enter a control row to edit its action; use left/right to choose
|
||||
the action. Seek offsets and positions are milliseconds, bounded to one day.
|
||||
For playlists, left/right cycles observed playlist IDs and displays their names;
|
||||
Enter permits manual object-path input. Absolute position uses the observed track
|
||||
ID and requires a known track length. Shuffle and repeat require the player to
|
||||
report those properties; playlists require the optional Playlists interface.
|
||||
Playlist-content editing is not supported. Choose **Save and return to entry**,
|
||||
then **Save and exit (draft)**, and `S` to persist/activate. Entry validation runs
|
||||
again at Save and exit; Esc discards the entry edit.
|
||||
|
||||
Select a control in the list and press `L` to choose a MIDI device and learn its
|
||||
input. `U` in that prompt unbinds the selected control; Esc cancels learning.
|
||||
Save to activate the learned binding. Notes trigger on presses, CCs on zero to
|
||||
nonzero transitions; releases and repeated held values do not repeat commands.
|
||||
One physical input cannot also be bound to another media or mixer action.
|
||||
|
||||
See the validated [complete media profile](../examples/profiles/media-qbz.toml).
|
||||
An entry uses this shape (append to a profile containing the `buttons` surface):
|
||||
|
||||
```toml
|
||||
[[media]]
|
||||
id = "qbz"
|
||||
label = "QBZ"
|
||||
feedback_enabled = true
|
||||
selector = { field = "bus_name", pattern = "org.mpris.MediaPlayer2.com.blitzfc.qbz", regex = false }
|
||||
controls = [
|
||||
{ id = "play", action = { kind = "play" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 40 } } },
|
||||
{ id = "pause", action = { kind = "pause" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 41 } } },
|
||||
]
|
||||
```
|
||||
|
||||
Actions are `play`, `pause`, `stop`, `play_pause`, `next`, `previous`,
|
||||
`seek` (`offset_ms`), `set_position` (`position_ms`), `shuffle_toggle`,
|
||||
`shuffle` (`enabled`), `repeat_cycle`, `repeat` (`mode = "None"`, `"Track"` or
|
||||
`"Playlist"`) and `playlist` (`id`, a player-reported D-Bus object path).
|
||||
All actions may have a MIDI binding. Unbound actions remain usable from the TUI.
|
||||
|
||||
Feedback defaults to the same learned note/channel, with 127 on and 0 off, when
|
||||
the surface has an output port. CC inputs have no implicit feedback. Play, Pause
|
||||
and Stop lights follow the mutually exclusive **observed** playback state, not
|
||||
the last button pressed. PlayPause follows Playing; shuffle, repeat and playlist
|
||||
lights follow the properties the player reports. Seek/next/previous have no
|
||||
latched indicator. Polling picks up external changes; an accepted command is not
|
||||
proof that a player changed state. Unavailable/ambiguous state clears enabled
|
||||
indicators. Successful output is deduplicated and reconnects resynchronize it.
|
||||
|
||||
For device-specific colors or CC output, learn first, then edit the control's
|
||||
Custom feedback fields. The equivalent binding field is:
|
||||
|
||||
```toml
|
||||
feedback = { message = { kind = "note", channel = 1, number = 40 }, on = 3, off = 0 }
|
||||
```
|
||||
|
||||
Color values depend on the controller. Root `feedback_enabled = false` overrides
|
||||
both per-fader and per-media-entry switches, including explicit mappings. Disabled
|
||||
feedback sends **nothing**, not even a clearing message; old LEDs may remain lit.
|
||||
Re-enable and Save to resynchronize. Removing a MIDI device unbinds media controls
|
||||
without deleting entries.
|
||||
|
||||
Limits: 128 entries, 64 controls per entry, 256-byte selectors, 256 KiB of media
|
||||
configuration; discovery handles up to 32 players and lists the first 256 playlists
|
||||
per player. Oversized/incomplete player discovery fails closed. Calls time out and
|
||||
errors are reported; missing players are rediscovered automatically. Timed-out
|
||||
commands are not replayed. Restart both processes after upgrading the IPC build.
|
||||
|
||||
### Groups and faders
|
||||
|
||||
Groups contain application IDs, never other groups. The TUI presents eligible
|
||||
application faders in a checked popup but stores deduplicated application IDs:
|
||||
|
||||
```toml
|
||||
[[groups]]
|
||||
id = "media"
|
||||
label = "Media"
|
||||
members = ["music", "browser"]
|
||||
volume_mode = "absolute"
|
||||
|
||||
[[faders]]
|
||||
id = "media-fader"
|
||||
target = { kind = "group", id = "media" }
|
||||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
```
|
||||
|
||||
Application and `output` targets use the same fader shape. `absolute` is the
|
||||
currently selectable group mode; relative behavior remains reserved for later
|
||||
runtime work.
|
||||
|
||||
### Mixer presentation
|
||||
|
||||
Global mixer presentation is stored in `[ui]`:
|
||||
|
||||
```toml
|
||||
[ui]
|
||||
mixer_orientation = "horizontal"
|
||||
status_display = "compact"
|
||||
theme = "nord"
|
||||
```
|
||||
|
||||
`status_display` accepts `detailed`, `compact`, `symbol`, `color`, or `hidden`.
|
||||
Detailed shows the full pickup state, compact uses short words such as `LIVE`
|
||||
and `WAIT`, symbol uses a distinct Unicode glyph per state, color uses one dot
|
||||
whose semantic color carries the state, and hidden removes pickup feedback.
|
||||
This only changes presentation; pickup protection remains active. Existing
|
||||
profiles default to `detailed`. The Config page cycles and saves this value.
|
||||
|
||||
The TUI normally manages layout entries. Their TOML representation is useful
|
||||
for review and bulk editing:
|
||||
|
||||
```toml
|
||||
[[mixer_layout]]
|
||||
kind = "separator"
|
||||
id = "applications"
|
||||
label = "Applications"
|
||||
size = "slim"
|
||||
decoration = "double"
|
||||
|
||||
[[mixer_layout]]
|
||||
kind = "fader"
|
||||
fader = "music-fader"
|
||||
density = "slim"
|
||||
hidden = false
|
||||
```
|
||||
|
||||
Fader density is `slim`, `bordered_slim`, `standard`, or `thick`. Slim uses one
|
||||
terminal row; Bordered slim adds a border around one content row. Hidden faders
|
||||
retain their place and routing and can be restored from the Config tab.
|
||||
|
||||
Press `A` in the mixer to choose a new application fader, empty absolute group,
|
||||
or separator. A new fader or group opens its guided editor immediately; its
|
||||
placeholder capture or empty membership keeps it offline until configured.
|
||||
Press `E` to edit the selected fader or separator, and `D` to delete it after
|
||||
confirmation. Deleting a fader also removes its bindings and an application or
|
||||
group target that is not shared or referenced elsewhere. The fader editor's
|
||||
Name row renames an application or group label without changing stable IDs,
|
||||
capture, membership, bindings, or layout; default-output labels come from the
|
||||
audio backend. Use Up/Down or Tab to choose popup fields, Left/Right to change
|
||||
options, Enter to accept, and Escape to cancel. Config → Save persists and
|
||||
activates the draft.
|
||||
|
||||
Separator `size` is `slim`, `standard`, `thick`, or `fill`; `decoration`
|
||||
is `plain` (label only), `line`, `double`, or `box`. Existing separators
|
||||
default to Standard with Line decoration. Size controls height in Vertical
|
||||
mode and width in Horizontal mode. Slim uses one row in Vertical mode (three
|
||||
with Box); Standard uses three and Thick uses five. Horizontal Slim uses three
|
||||
columns, Standard fits the label within 8–18 columns, and Thick uses 22.
|
||||
Fill shares unused viewport space with other Fill separators after faders
|
||||
have been fitted, so it does not force faders off-screen or cause wrapping.
|
||||
|
||||
Separator names are optional. Keep a stable nonempty `id`, but use `label = ""`
|
||||
for an unlabelled rule, box, or spacer:
|
||||
|
||||
```toml
|
||||
[[mixer_layout]]
|
||||
kind = "separator"
|
||||
id = "before-master"
|
||||
label = ""
|
||||
size = "fill"
|
||||
decoration = "plain"
|
||||
```
|
||||
|
||||
Size and decoration are independent. An unnamed Line or Double separator
|
||||
draws an uninterrupted rule; Plain draws only empty space. Reordering keeps
|
||||
the entry's ID, appearance, and comments, including after Save and restart.
|
||||
|
||||
### MIDI surfaces and bindings
|
||||
|
||||
Use `fader_master devices` to inspect available ports and durable USB identity
|
||||
metadata. Prefer a serial number, then a physical USB path, for identical
|
||||
controllers. Ambiguous serial-less controllers remain unassigned unless a
|
||||
manual backend ID is explicitly selected.
|
||||
|
||||
Messages use 1-based MIDI channels and 0–127 data numbers:
|
||||
|
||||
```toml
|
||||
[[bindings]]
|
||||
surface = "apc-mini"
|
||||
fader = "music-fader"
|
||||
action = "volume"
|
||||
message = { kind = "cc", channel = 1, number = 48 }
|
||||
|
||||
[[bindings]]
|
||||
surface = "apc-mini"
|
||||
fader = "music-fader"
|
||||
action = "toggle_mute"
|
||||
edge = "press"
|
||||
message = { kind = "note", channel = 1, number = 64 }
|
||||
feedback = { kind = "note", channel = 1, number = 64, on = 127, off = 0 }
|
||||
```
|
||||
|
||||
The TUI can choose a controller, learn the next supported movement or button
|
||||
press, and remove an assignment independently for volume and mute. Unassigned
|
||||
actions inherit `[ui].default_controller` for learning.
|
||||
Learn opens a modal waiting for a movement or button press; Escape cancels it.
|
||||
Changing controller, learning, and unlearning are separate actions. In Config,
|
||||
open a MIDI device to see its connection details and set its default-controller
|
||||
flag. Press `D` on the device row or in its details popup to remove it after
|
||||
confirmation. Removal also clears that device's bindings and default-controller
|
||||
selection; Save activates the draft. Hidden faders remain bound and continue
|
||||
contributing to groups; restore them from Config → Show hidden faders.
|
||||
|
||||
`feedback` is optional and requires the binding's surface to define
|
||||
`output_port`. After that output attaches, the server sends `on` when the
|
||||
fader's target is uniformly and observably muted and `off` when it is unmuted
|
||||
or a group has mixed mute state. Offline targets emit no guess. Only confirmed
|
||||
audio observations drive feedback, so a pending or failed mute write never
|
||||
lights an LED as if it succeeded. Reconnect sends the current state again;
|
||||
unchanged states are deduplicated. Both note and CC feedback use 1-based
|
||||
channels and values from 0–127.
|
||||
|
||||
In the fader editor, open **Learn volume MIDI** or **Learn mute MIDI** to change
|
||||
that assignment. Press `U` in the learn prompt to unbind it, or `Esc` to cancel
|
||||
without changing it. Unbinding leaves the other action intact and keeps the
|
||||
controller selected for relearning. Save the draft to persist and activate it.
|
||||
|
||||
LED values are device-specific: a note velocity can mean a color or animation,
|
||||
so 127 is not a universal “on” value. The APC MINI example uses its configured
|
||||
green value. Relearning a mute binding moves its feedback assignment to the new
|
||||
control. A new mute binding inherits `on`/`off` values only when existing
|
||||
feedback entries on the same surface and message kind establish one unambiguous
|
||||
convention; its feedback address follows the newly learned control. Conflicting
|
||||
or absent conventions leave the explicit mapping unset.
|
||||
|
||||
By default, every note-based mute binding sends the same note back on the same
|
||||
channel: Note On velocity 127 for confirmed mute, and velocity 0 for unmuted or
|
||||
mixed state. This requires `output_port`, but no device identity or predefined
|
||||
note map. Missing mappings use these defaults after Save or server restart.
|
||||
This reports confirmed state; it does not echo each press/release immediately.
|
||||
|
||||
Configure alternate protocols per binding with `feedback`. For example, use
|
||||
on=1/off=0 for a device-specific LED value, or override the message address and
|
||||
kind for a controller whose feedback uses CC:
|
||||
|
||||
```toml
|
||||
feedback = { kind = "cc", channel = 3, number = 65, on = 3, off = 0 }
|
||||
```
|
||||
|
||||
Explicit mappings always take precedence. CC input bindings require an explicit
|
||||
feedback mapping; volume bindings do not automatically drive motors.
|
||||
|
||||
## Validation, migration, and Save
|
||||
|
||||
Validate a file without opening MIDI/audio devices or changing live audio:
|
||||
|
||||
```sh
|
||||
fader_master validate --config /path/to/profile.toml
|
||||
```
|
||||
|
||||
Profiles are strict: unknown fields, unsafe IDs, invalid MIDI ranges, duplicate
|
||||
physical bindings, and dangling references are rejected before side effects.
|
||||
The TUI edits a server-owned validated draft. Config → Save atomically persists
|
||||
and activates that draft; there is no separate Apply operation.
|
||||
|
||||
Server startup safely recognizes the pre-versioned/schema-0 format. After full
|
||||
validation, it adds the schema marker, preserves comments, writes the original
|
||||
bytes to `NAME.toml.v0.bak`, and atomically installs the upgraded document.
|
||||
Unknown newer schemas and malformed profiles are never rewritten.
|
||||
|
||||
## Diagnostics and recovery
|
||||
|
||||
```sh
|
||||
fader_master status
|
||||
fader_master devices
|
||||
```
|
||||
|
||||
The reconnecting client keeps the last confirmed mixer state visible if the
|
||||
server disappears. Restarting the server refreshes the snapshot without
|
||||
replaying stale input. Hardware-dependent checks and expected recovery behavior
|
||||
are documented in the [hands-on checklist](../checklist.md).
|
||||
File diff suppressed because it is too large
Load Diff
|
After Width: | Height: | Size: 132 KiB |
File diff suppressed because it is too large
Load Diff
|
After Width: | Height: | Size: 268 KiB |
|
|
@ -0,0 +1,50 @@
|
|||
# Linux MIDI discovery and identity
|
||||
|
||||
Run `fader_master devices` to inspect discovered ports. Config lists unclaimed
|
||||
ports under Detected MIDI ports; open one to add it to the profile, then Save.
|
||||
Configured MIDI devices have a details popup with connection status, backend
|
||||
port, errors, and a default-controller toggle. Only a sole detected input is
|
||||
automatically adopted when a managed profile is first created.
|
||||
|
||||
`midir` 0.11.1 exposes Linux ports as ALSA sequencer `client:port` addresses and
|
||||
human-readable names. Neither value is a durable USB identity: client numbers
|
||||
can change with connection and discovery order, while identical controllers can
|
||||
publish identical names.
|
||||
|
||||
For a kernel sequencer client, ALSA reports its sound-card number. The MIDI
|
||||
identity probe opens that card's udev `sound/cardN` device and copies:
|
||||
|
||||
- `ID_VENDOR_ID` and `ID_MODEL_ID` as the controller model key;
|
||||
- `ID_SERIAL_SHORT` when the USB device supplies a serial;
|
||||
- `ID_PATH` as the physical connection fallback.
|
||||
|
||||
User and virtual ALSA clients return no card number and therefore no USB
|
||||
metadata. They may be selected by a unique port name, but duplicate names remain
|
||||
ambiguous.
|
||||
|
||||
## Matching policy
|
||||
|
||||
1. Match the configured port name and, for USB devices, VID/PID.
|
||||
2. Prefer an exact serial when one was observed.
|
||||
3. Without a serial, prefer the retained physical path.
|
||||
4. A unique remaining model/name is safe to select.
|
||||
5. Multiple remaining candidates stay unassigned. An explicit backend-port
|
||||
choice may resolve the current topology, but the ephemeral ALSA address is
|
||||
not treated as durable evidence after reconnect or reboot.
|
||||
|
||||
This means two identical serial-less devices can remain attached to stable USB
|
||||
sockets and be distinguished by path. If they move between sockets, software
|
||||
cannot prove which physical unit is which; silently binding by enumeration order
|
||||
would risk controlling the wrong applications.
|
||||
|
||||
## Recorded host observation
|
||||
|
||||
On 2026-10-14, the Arch Linux host exposed only
|
||||
`PortIdentity { backend_id: "14:0", name: "Midi Through:Midi Through Port-0 14:0", usb: None }`.
|
||||
This validates the virtual-client fallback but is not physical-controller
|
||||
acceptance. A later APC MINI observation on 2026-10-15 recorded USB
|
||||
`09e8:0028`, serial `Ver00.10`, and backend port `36:0`; the serial stayed
|
||||
stable when the USB socket changed. Two-identical-device ambiguity checks
|
||||
remain open in [the backlog](../task.md) and
|
||||
[hands-on checklist](../checklist.md). These are recorded observations, not
|
||||
guarantees that every controller exposes a unique serial.
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
# Real Pulse daemon fixture
|
||||
|
||||
The M4.4 fixture is opt-in because it connects to the current user's real audio
|
||||
session. Its normal phase creates a uniquely named, silent stereo stream with
|
||||
`paplay`, changes only that stream, and always terminates the child process.
|
||||
It never parses shell output in the production adapter.
|
||||
|
||||
This fixture tests audio behavior, not screenshots or the separator editor.
|
||||
Layout, blank-name, save/reload, and rendering tests run in the ordinary
|
||||
hardware-free suite. For interactive layout/MIDI checks, use the
|
||||
[hands-on checklist](../checklist.md); for deterministic screenshots, see
|
||||
[the documentation index](README.md).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A reachable PulseAudio-compatible server. This can be PulseAudio itself or
|
||||
PipeWire's `pipewire-pulse` service.
|
||||
- The `paplay` executable and libpulse development/runtime files. On Arch these
|
||||
are supplied by `libpulse`.
|
||||
- Permission to access the user audio socket. Sandboxed test runners must expose
|
||||
that socket deliberately.
|
||||
|
||||
Run the non-disruptive phase with:
|
||||
|
||||
```sh
|
||||
cargo test --locked -p volume_lib --test pulse_daemon --all-features \
|
||||
real_stream_commands_external_edits_and_churn_converge -- \
|
||||
--ignored --exact --nocapture
|
||||
```
|
||||
|
||||
It verifies discovery of the isolated stream, worker volume and mute commands,
|
||||
readback, changes made by an independent Pulse client, removal, and a replacement
|
||||
stream with a fresh handle. Existing desktop streams are observed but never
|
||||
selected for writes. The fixture fails rather than silently passing when the
|
||||
daemon, `paplay`, expected notifications, or cleanup behavior is unavailable.
|
||||
|
||||
Set `PULSE_SERVER` before the command to target an explicitly isolated daemon.
|
||||
This is the intended way to run the same fixture against a standalone PulseAudio
|
||||
CI instance without touching the desktop session.
|
||||
|
||||
## Disruptive PipeWire restart phase
|
||||
|
||||
This phase intentionally restarts the current user's PipeWire, pipewire-pulse,
|
||||
and WirePlumber services. It interrupts all desktop audio and must not run in the
|
||||
ordinary test suite. Close or pause important audio applications first, then
|
||||
acknowledge the interruption explicitly:
|
||||
|
||||
```sh
|
||||
FADER_MASTER_RESTART_PIPEWIRE=1 \
|
||||
cargo test --locked -p volume_lib --test pulse_daemon --all-features \
|
||||
pipewire_restart_disconnects_and_a_new_epoch_resnapshots -- \
|
||||
--ignored --exact --nocapture
|
||||
```
|
||||
|
||||
The fixture requires a visible disconnect diagnostic, retries with bounded
|
||||
backoff, reconnects under a new backend epoch, and waits for a complete fresh
|
||||
snapshot. Without the acknowledgement variable it fails before restarting
|
||||
anything.
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
# Related projects and libraries
|
||||
|
||||
These projects informed the implementation or provide the core integration
|
||||
layers used by fader_master:
|
||||
|
||||
- [pwvucontrol](https://github.com/saivert/pwvucontrol) — PipeWire volume-control
|
||||
UI and a useful reference for node/mixer behavior.
|
||||
- [Ratatui](https://ratatui.rs/) — terminal rendering and widgets.
|
||||
- [Crossterm](https://docs.rs/crossterm/latest/crossterm/) — portable terminal
|
||||
input and output used by Ratatui.
|
||||
- [midir](https://github.com/Boddlnagg/midir) — cross-platform MIDI I/O with an
|
||||
ALSA backend on Linux.
|
||||
- [libpulse-binding](https://docs.rs/libpulse-binding/latest/libpulse_binding/)
|
||||
— PulseAudio protocol introspection and control, including `pipewire-pulse`.
|
||||
- [pipewire-rs](https://pipewire.pages.freedesktop.org/pipewire-rs/pipewire/)
|
||||
— reference bindings for the reserved native PipeWire adapter.
|
||||
|
||||
The detailed dependency choices, constraints, and licenses are recorded in the
|
||||
[architecture research table](../architecture.md#library-research-and-choices).
|
||||
|
||||
Only the Pulse-compatible audio adapter is currently available at runtime;
|
||||
PipeWire users connect through `pipewire-pulse`. The interface screenshots
|
||||
are generated from fader_master's own Ratatui renderer. See
|
||||
[configuration](configuration.md) for supported behavior and
|
||||
[build instructions](build.md) for the pinned dependency/toolchain setup.
|
||||
|
|
@ -0,0 +1,206 @@
|
|||
# Preparing and publishing releases
|
||||
|
||||
Publication is a separate, deliberate maintainer operation. Preparing this
|
||||
integration does not create tags, push commits, or publish assets.
|
||||
|
||||
## Release contract
|
||||
|
||||
- Package: `fader_master`, with binaries `fader_master`,
|
||||
`fader_master_client`, and `fader_master_server` (all included together).
|
||||
- Version: inherited from `[workspace.package].version` in the root manifest;
|
||||
currently `0.1.0-rc.2`, expected tag `v0.1.0-rc.2`. Keep [CHANGELOG](../CHANGELOG.md)
|
||||
aligned when changing the version. No independent script version constant.
|
||||
- Target: `x86_64-unknown-linux-gnu`, release profile, locked dependencies.
|
||||
This initial target deliberately excludes Windows and musl: the application
|
||||
uses Linux ALSA, libudev, libpulse and Unix sockets. ARM is not yet qualified.
|
||||
- Artifacts: both `.tgz` archives and standalone binaries, plus `SHA256SUMS`.
|
||||
Archive: `fader_master-x86_64-unknown-linux-gnu-v0.1.0-rc.2.tgz`, containing
|
||||
a directory of the same stem with all three executables. Raw names are
|
||||
`<binary>-x86_64-unknown-linux-gnu-v0.1.0-rc.2`.
|
||||
- Public Gitea repository: [MadGobblins/fader_master](https://proxy.dandaedre.com/gitea/MadGobblins/fader_master).
|
||||
Release URL: `https://proxy.dandaedre.com/gitea/MadGobblins/fader_master/releases/tag/v0.1.0-rc.2`.
|
||||
Development origin: `git@git.dandaedre.com:MadGobblins/fader_master.git`.
|
||||
The exact mapping in [rust-release.toml](../rust-release.toml) directs the
|
||||
publisher to HTTPS without rewriting Git's origin.
|
||||
- Cargo-binstall metadata is present for public archive verification. Crates
|
||||
remain `publish = false`; this workflow does not publish to crates.io. Use
|
||||
`cargo binstall --git https://proxy.dandaedre.com/gitea/MadGobblins/fader_master fader_master`
|
||||
only after a release actually exists, not a registry-only install command.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Install the [Linux build prerequisites](build.md), the pinned Rust toolchain,
|
||||
Git, jq, Cross, a working Docker or Podman backend, and cargo-binstall.
|
||||
Python 3 is needed only for the wrapper tests. ShellCheck is recommended.
|
||||
Install the intentionally spelled `rust_realease` separately, with maintainer
|
||||
approval; the wrapper never installs or upgrades tools:
|
||||
|
||||
```sh
|
||||
cargo binstall --git https://proxy.dandaedre.com/gitea/idle-org/rust_realease rust_realease
|
||||
rust_realease --version
|
||||
rust_realease --help
|
||||
```
|
||||
|
||||
Use a publisher built from upstream commit `ed2ce6e` or a later release
|
||||
containing its Cross `pre-build` fix. The prebuilt `0.1.6-rc.2` executable
|
||||
tested here still rejected that option; its version string alone is not
|
||||
sufficient. The RC was published using a temporary build of that exact fix.
|
||||
Rerun all dry-run/packaging checks before publishing. See the
|
||||
[publisher guide](https://proxy.dandaedre.com/gitea/idle-org/rust_realease/src/branch/main/docs/advanced-usage.md).
|
||||
|
||||
[Cross.toml](../Cross.toml) uses the `0.2.5` x86-64 GNU image and installs ALSA,
|
||||
Pulse and udev development packages inside the build container. That image's
|
||||
ALSA library is too old for this application: use the digest-pinned override
|
||||
under [Published RC build](#published-rc-build). The pinned
|
||||
Rust toolchain and Cargo.lock constrain Rust builds. The container tag and apt
|
||||
repositories are not digest/snapshot pinned, so bit-for-bit reproducibility
|
||||
and the minimum supported runtime glibc version are not yet established.
|
||||
Artifacts are dynamically linked: recipient systems need ALSA, libpulse and
|
||||
libudev runtime libraries and a running Pulse-compatible audio service. Builds
|
||||
with the default MPRIS feature also require libdbus-1 and a user session bus.
|
||||
|
||||
## Credentials and invocation
|
||||
|
||||
Store a token outside the checkout in a readable, regular file with restrictive
|
||||
permissions (for example mode 600). Grant repository read and release write
|
||||
permissions. Pass the file path, never the token value. Do not commit the file
|
||||
or its path; do not run the wrapper under shell tracing (`sh -x`).
|
||||
|
||||
```sh
|
||||
./release.sh /path/outside/checkout/token --dry-run
|
||||
./release.sh /path/outside/checkout/token --compile-only
|
||||
# Separately authorized publication, only after the checks below:
|
||||
./release.sh /path/outside/checkout/token
|
||||
```
|
||||
|
||||
The first line becomes `GITEA_TOKEN` only for the publisher; empty first lines
|
||||
are rejected. Remaining lines are ignored. All extra arguments are forwarded
|
||||
exactly, so review them: preparation/push/replacement options are powerful and
|
||||
are never added automatically. Invocation from another directory works.
|
||||
Cargo metadata resolves the selected member's workspace-inherited version;
|
||||
a hyphenated version automatically adds `--prerelease`. Stable versions do not.
|
||||
The wrapper neither changes Git nor repairs metadata on its own.
|
||||
|
||||
For a token-free preview or local packaging, invoke the publisher directly:
|
||||
|
||||
```sh
|
||||
rust_realease . --package fader_master --artifact-format both --dry-run
|
||||
rust_realease . --package fader_master --artifact-format both --compile-only
|
||||
```
|
||||
|
||||
## Verification and publication checklist
|
||||
|
||||
1. Preserve and resolve outstanding work intentionally; publication requires a
|
||||
clean checkout. Check `git status --short`, branch, HEAD and origin. Update
|
||||
the version/changelog together and review the custom license and dependency
|
||||
advisories. Finish the applicable [M12 gates](../task.md); the wrapper alone
|
||||
is not a release-quality certification.
|
||||
2. Run all [workspace gates](../AGENTS.md#verification), including default,
|
||||
portable and optional-backend builds described in [build.md](build.md).
|
||||
Jenkins currently exercises the portable FreeBSD subset by default, not
|
||||
the complete Linux application.
|
||||
3. Run `python3 scripts/test-release.py`, `sh -n release.sh` and
|
||||
`shellcheck -s sh release.sh` when available. Tests use only fake tokens and
|
||||
a fake publisher; they never contact Gitea.
|
||||
4. Check the expected local and remote tag without changing either:
|
||||
`git show-ref --verify refs/tags/v0.1.0-rc.2` and
|
||||
`git ls-remote --tags origin refs/tags/v0.1.0-rc.2 'refs/tags/v0.1.0-rc.2^{}'`.
|
||||
Before publication both must resolve to the intended HEAD. Creating/pushing
|
||||
the tag is a separate authorized step, not part of the wrapper.
|
||||
5. Run the dry run with the real token file. It must report the contract above
|
||||
and no metadata/prerequisite errors. Independently inspect the Gitea
|
||||
`/api/v1/repos/MadGobblins/fader_master/releases/tags/v0.1.0-rc.2` endpoint.
|
||||
A confirmed 404 means absent only when the repository is accessible; do not
|
||||
treat authentication/network/server failures as absence.
|
||||
6. If a release exists, inspect draft/prerelease status and **all asset names**,
|
||||
including `SHA256SUMS`. Any planned-name collision blocks publication.
|
||||
Existing releases without collisions can be reused after review. Never use
|
||||
`--replace-assets` without explicit approval of the exact assets; replacement
|
||||
is not transactional. Recheck remote tags/releases immediately before a
|
||||
separately authorized live run.
|
||||
7. Run `--compile-only`, inspect the resulting ignored `dist/release-*/`
|
||||
directory, run `sha256sum -c SHA256SUMS` there, inspect `tar -tzf` for the
|
||||
documented archive layout and `file`/`readelf -d` on all executables. Verify
|
||||
their runtime dependencies and smoke-test on a clean supported Linux system.
|
||||
Public cargo-binstall/download verification is required after publication.
|
||||
|
||||
## Preparation audit — 2026-10-16
|
||||
|
||||
Discovery HEAD: `8add95df3f52b2cb3a7bed679f3b28bf48801d47`, branch `main`.
|
||||
Pre-existing changes to `examples/profiles/arch-pipewire.toml` were preserved.
|
||||
Git 2.56.0, Cargo 1.88.0, rust_realease 0.1.3, Cross 0.2.5,
|
||||
cargo-binstall 1.24.0 and Podman 6.1.3 were found. Podman works outside the
|
||||
filesystem sandbox. ShellCheck was unavailable.
|
||||
|
||||
The repository API returned 200/public, the release-by-tag API returned 404,
|
||||
and neither local nor remote `v0.1.0` existed. No assets/collisions were found;
|
||||
these are point-in-time observations, not permission to publish later.
|
||||
|
||||
The configured dry run resolves all three binaries, valid binstall metadata,
|
||||
the GNU/Linux assets and the correct HTTPS destination. It remains blocked by
|
||||
the installed publisher rejecting `pre-build` and the absent tag. No real token
|
||||
file was supplied, so authenticated wrapper verification remains outstanding.
|
||||
Packaging/checksum/archive qualification is blocked by publisher compatibility.
|
||||
No tool was upgraded and nothing was tagged, pushed or published.
|
||||
|
||||
### Release-candidate follow-up
|
||||
|
||||
The workspace and lockfile now identify `0.1.0-rc.1`; the wrapper automatically
|
||||
marks it as a prerelease. The RC release API returned 404 and the remote RC tag
|
||||
was absent at preparation time. Publication is pending: the supplied token
|
||||
file was not found, and the installed publisher still needs upgrading for
|
||||
Cross `pre-build` support. Existing local profile edits must stay out of the
|
||||
release; use a clean checkout of the RC tag when packaging and publishing.
|
||||
|
||||
### Published RC build
|
||||
|
||||
Published on 2026-10-16: [v0.1.0-rc.1](https://proxy.dandaedre.com/gitea/MadGobblins/fader_master/releases/tag/v0.1.0-rc.1),
|
||||
marked prerelease, not draft. Source commit:
|
||||
`50d3097ff69f0cd3ec0ef15a0b74aa51d9c07de6`. The existing remote tag was verified
|
||||
and was not moved. User profile edits were excluded using a clean worktree.
|
||||
|
||||
Publisher source commit: `ed2ce6e86cab274d8f1350701605a3d0c6e2ac34`, built
|
||||
temporarily without replacing the globally installed publisher. Its native
|
||||
pre-build regression test passed. The original Cross image reached linking
|
||||
but lacked ALSA's `snd_seq_client_info_get_card`. The successful packaging and
|
||||
publication commands used this explicit override without changing tagged code:
|
||||
|
||||
```sh
|
||||
export CROSS_TARGET_X86_64_UNKNOWN_LINUX_GNU_IMAGE=ghcr.io/cross-rs/x86_64-unknown-linux-gnu@sha256:5e4193b02eaf85b64ae1545ceb942f380284a9760c005a6d04805af5221ee669
|
||||
```
|
||||
|
||||
This image is Ubuntu 24.04 based; older Linux distributions are not qualified
|
||||
for these artifacts. Recipient systems need the runtime libraries listed
|
||||
above. Rust remained pinned to 1.88.0 with the tagged Cargo.lock.
|
||||
|
||||
Authenticated preview and compile-only packaging passed. The archive contains
|
||||
exactly the three executables; all four artifact checksums passed locally and
|
||||
all three binaries ran `--help` successfully without audio side effects.
|
||||
Publication uploaded those four artifacts plus `SHA256SUMS`. The publisher
|
||||
downloaded and verified every asset anonymously, checked archive layout, and
|
||||
completed an isolated cargo-binstall installation for x86-64 GNU/Linux.
|
||||
The API confirmed `prerelease = true`, `draft = false` and the five assets.
|
||||
No existing assets were replaced. Real hardware qualification remains pending.
|
||||
|
||||
### Published RC2 build
|
||||
|
||||
Published on 2026-10-18: [v0.1.0-rc.2](https://proxy.dandaedre.com/gitea/MadGobblins/fader_master/releases/tag/v0.1.0-rc.2),
|
||||
marked prerelease, not draft. Source commit:
|
||||
`8ac222b501cb5bc4fbd5fc5ec52feb4a94301039`; main and the annotated tag were pushed
|
||||
before packaging. The publisher was built temporarily from the same `ed2ce6e`
|
||||
fix and used the same digest-pinned Ubuntu 24.04 Cross image documented above.
|
||||
No globally installed publisher was replaced.
|
||||
|
||||
All workspace formatting/check/Clippy/doctest/release gates, default/no-default
|
||||
tests and independent MIDI/Pulse feature tests passed on Rust 1.88.0. The four
|
||||
old Arch fixture assertions were aligned with the committed example bindings.
|
||||
All eight release-wrapper tests passed; ShellCheck was unavailable. Two hardware
|
||||
tests remain opt-in, and the outstanding M12 qualifications remain open.
|
||||
|
||||
Authenticated preview and compile-only packaging passed. Local checks verified
|
||||
all checksums, the three-binary archive, runtime dependencies and CLI smoke tests.
|
||||
Publication reused that completed source build and uploaded three binaries,
|
||||
the archive and `SHA256SUMS`, without replacing assets. The publisher verified
|
||||
all public downloads/checksums, archive layout and an isolated cargo-binstall
|
||||
installation. The public API confirmed all five assets, `prerelease = true` and
|
||||
`draft = false`. Restart both server and client when upgrading.
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
schema_version = 1
|
||||
id = "arch-pipewire"
|
||||
startup = "adopt"
|
||||
new_stream = "adopt"
|
||||
|
||||
[ui]
|
||||
theme = "catppuccin-mocha"
|
||||
mixer_orientation = "horizontal"
|
||||
status_display = "color"
|
||||
default_controller = "apc-mini-apc-mini-midi-1"
|
||||
|
||||
[runtime]
|
||||
poll_interval_ms = 10
|
||||
|
||||
[audio]
|
||||
adapter = "pulse"
|
||||
max_gain = 1.0
|
||||
|
||||
[[applications]]
|
||||
id = "music"
|
||||
label = "Music"
|
||||
selectors = [
|
||||
{ field = "application.name", regex = '(?i)(qobuz|qbz|spotify|music)' },
|
||||
{ field = "application.process.binary", regex = '(?i)(qobuz|qbz|spotify)' },
|
||||
]
|
||||
|
||||
[[applications]]
|
||||
id = "browser"
|
||||
label = "Browser"
|
||||
selectors = [
|
||||
{ field = "application.name", regex = '(?i)(firefox|waterfox|chromium|chrome|brave|librewolf)' },
|
||||
{ field = "application.process.binary", regex = '(?i)^(firefox|waterfox|chromium|chrome|brave|librewolf)(-.*)?$' },
|
||||
]
|
||||
|
||||
[[applications]]
|
||||
id = "steam"
|
||||
label = "Steam"
|
||||
selectors = [{ field = "application.name", regex = "Ravenswatch.*" }]
|
||||
|
||||
[[groups]]
|
||||
id = "media"
|
||||
label = "Media group"
|
||||
members = ["browser", "music"]
|
||||
volume_mode = "absolute"
|
||||
|
||||
[[surfaces]]
|
||||
id = "apc-mini-apc-mini-midi-1"
|
||||
label = "APC MINI:APC MINI MIDI 1"
|
||||
input_port = "APC MINI:APC MINI MIDI 1"
|
||||
output_port = "APC MINI:APC MINI MIDI 1"
|
||||
usb_vendor_id = "09e8"
|
||||
usb_product_id = "0028"
|
||||
usb_serial = "Ver00.10"
|
||||
usb_path = "pci-0000:0f:00.4-usb-0:1.4.4:1.0"
|
||||
manual_backend_id = "32:0"
|
||||
identity_policy = "manual"
|
||||
motorized = false
|
||||
|
||||
[[faders]]
|
||||
id = "music-fader"
|
||||
target = { kind = "application", id = "music" }
|
||||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
|
||||
[[faders]]
|
||||
id = "browser-fader"
|
||||
target = { kind = "application", id = "browser" }
|
||||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
|
||||
[[faders]]
|
||||
id = "media-fader"
|
||||
target = { kind = "group", id = "media" }
|
||||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
|
||||
[[faders]]
|
||||
id = "master-fader"
|
||||
target = { kind = "output", id = "default" }
|
||||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
|
||||
[[faders]]
|
||||
id = "steam-fader"
|
||||
target = { kind = "application", id = "steam" }
|
||||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
|
||||
[[bindings]]
|
||||
surface = "apc-mini-apc-mini-midi-1"
|
||||
fader = "media-fader"
|
||||
action = "volume"
|
||||
message = { kind = "cc", channel = 1, number = 48 }
|
||||
|
||||
[[bindings]]
|
||||
surface = "apc-mini-apc-mini-midi-1"
|
||||
fader = "media-fader"
|
||||
action = "toggle_mute"
|
||||
edge = "press"
|
||||
message = { kind = "note", channel = 1, number = 64 }
|
||||
|
||||
[[bindings]]
|
||||
surface = "apc-mini-apc-mini-midi-1"
|
||||
fader = "master-fader"
|
||||
action = "volume"
|
||||
message = { kind = "cc", channel = 1, number = 56 }
|
||||
|
||||
[[bindings]]
|
||||
surface = "apc-mini-apc-mini-midi-1"
|
||||
fader = "master-fader"
|
||||
action = "toggle_mute"
|
||||
edge = "press"
|
||||
message = { kind = "note", channel = 1, number = 89 }
|
||||
|
||||
[[mixer_layout]]
|
||||
kind = "fader"
|
||||
fader = "music-fader"
|
||||
hidden = true
|
||||
density = "standard"
|
||||
|
||||
[[mixer_layout]]
|
||||
kind = "fader"
|
||||
fader = "browser-fader"
|
||||
hidden = true
|
||||
density = "standard"
|
||||
|
||||
[[mixer_layout]]
|
||||
kind = "fader"
|
||||
fader = "media-fader"
|
||||
hidden = false
|
||||
density = "slim"
|
||||
|
||||
[[mixer_layout]]
|
||||
kind = "fader"
|
||||
fader = "steam-fader"
|
||||
hidden = false
|
||||
density = "slim"
|
||||
|
||||
[[mixer_layout]]
|
||||
kind = "separator"
|
||||
id = "master"
|
||||
label = "Master"
|
||||
|
||||
[[mixer_layout]]
|
||||
kind = "fader"
|
||||
fader = "master-fader"
|
||||
hidden = false
|
||||
density = "standard"
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
schema_version = 1
|
||||
id = "desktop"
|
||||
startup = "adopt"
|
||||
new_stream = "adopt"
|
||||
|
||||
[ui]
|
||||
default_controller = "desk-left"
|
||||
theme = "default"
|
||||
status_display = "detailed"
|
||||
|
||||
[runtime]
|
||||
poll_interval_ms = 10
|
||||
|
||||
[audio]
|
||||
adapter = "auto"
|
||||
preference = ["pulse", "pipewire"]
|
||||
max_gain = 1.0
|
||||
|
||||
[[applications]]
|
||||
id = "music"
|
||||
label = "Music"
|
||||
selectors = [{ field = "application.name", exact = "Music Player" }]
|
||||
|
||||
[[applications]]
|
||||
id = "browser"
|
||||
label = "Browser"
|
||||
selectors = [{ field = "application.process.binary", regex = '^(firefox|chromium)$' }]
|
||||
|
||||
[[groups]]
|
||||
id = "media"
|
||||
label = "Media"
|
||||
members = ["music", "browser"]
|
||||
volume_mode = "absolute"
|
||||
|
||||
[[surfaces]]
|
||||
id = "desk-left"
|
||||
label = "Left controller"
|
||||
input_port = "Example Controller MIDI 1"
|
||||
output_port = "Example Controller MIDI 1"
|
||||
identity_policy = "require_unique"
|
||||
motorized = false
|
||||
|
||||
[[faders]]
|
||||
id = "media-fader"
|
||||
target = { kind = "group", id = "media" }
|
||||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
|
||||
[[bindings]]
|
||||
surface = "desk-left"
|
||||
fader = "media-fader"
|
||||
action = "volume"
|
||||
message = { kind = "cc", channel = 1, number = 0 }
|
||||
|
||||
[[bindings]]
|
||||
surface = "desk-left"
|
||||
fader = "media-fader"
|
||||
action = "toggle_mute"
|
||||
edge = "press"
|
||||
message = { kind = "note", channel = 1, number = 32 }
|
||||
feedback = { kind = "note", channel = 1, number = 32, on = 127, off = 0 }
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
# Replace port names with your controller's ports, or learn from the TUI.
|
||||
schema_version = 1
|
||||
id = "media-qbz"
|
||||
startup = "adopt"
|
||||
new_stream = "adopt"
|
||||
feedback_enabled = true
|
||||
bindings = []
|
||||
|
||||
[audio]
|
||||
adapter = "auto"
|
||||
max_gain = 1.0
|
||||
|
||||
[[surfaces]]
|
||||
id = "buttons"
|
||||
label = "Media buttons"
|
||||
input_port = "Example Controller MIDI 1"
|
||||
output_port = "Example Controller MIDI 1"
|
||||
identity_policy = "require_unique"
|
||||
motorized = false
|
||||
|
||||
[[media]]
|
||||
id = "qbz"
|
||||
label = "QBZ"
|
||||
feedback_enabled = true
|
||||
selector = { field = "bus_name", pattern = "org.mpris.MediaPlayer2.com.blitzfc.qbz", regex = false }
|
||||
controls = [
|
||||
{ id = "play", action = { kind = "play" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 40 } } },
|
||||
{ id = "pause", action = { kind = "pause" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 41 } } },
|
||||
{ id = "stop", action = { kind = "stop" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 42 } } },
|
||||
{ id = "toggle", action = { kind = "play_pause" } },
|
||||
{ id = "next", action = { kind = "next" } },
|
||||
{ id = "previous", action = { kind = "previous" } },
|
||||
{ id = "back", action = { kind = "seek", offset_ms = -10000 } },
|
||||
{ id = "forward", action = { kind = "seek", offset_ms = 10000 } },
|
||||
{ id = "beginning", action = { kind = "set_position", position_ms = 0 } },
|
||||
{ id = "shuffle", action = { kind = "shuffle_toggle" } },
|
||||
{ id = "shuffle-off", action = { kind = "shuffle", enabled = false } },
|
||||
{ id = "repeat", action = { kind = "repeat_cycle" } },
|
||||
{ id = "repeat-track", action = { kind = "repeat", mode = "Track" } },
|
||||
# Select an actual playlist from the player in the editor; this is a placeholder.
|
||||
{ id = "favorites", action = { kind = "playlist", id = "/playlist/favorites" } },
|
||||
]
|
||||
|
|
@ -2,5 +2,35 @@
|
|||
name = "fader_master"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
default-run = "fader_master"
|
||||
|
||||
[package.metadata.binstall]
|
||||
pkg-url = "{ repo }/releases/download/v{ version }/{ name }-{ target }-v{ version }.tgz"
|
||||
pkg-fmt = "tgz"
|
||||
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
|
||||
|
||||
[dependencies]
|
||||
media.workspace = true
|
||||
dbus = { workspace = true, optional = true }
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
fader-config.workspace = true
|
||||
fader-core.workspace = true
|
||||
midi.workspace = true
|
||||
rustix.workspace = true
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
toml.workspace = true
|
||||
tui.workspace = true
|
||||
volume_lib.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["mpris"]
|
||||
mpris = ["dep:dbus"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,615 @@
|
|||
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, AtomicFile, Profile, ProfileDocument, ProfileUpgrade, XdgEnvironment, XdgPaths,
|
||||
upgrade_profile,
|
||||
};
|
||||
use fader_core::Gain;
|
||||
use midi::{LinuxIdentityCatalog, MidiInputCatalog, PortIdentity};
|
||||
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()))?;
|
||||
match ProfileDocument::parse(&input) {
|
||||
Ok(document) => Ok(document),
|
||||
Err(original_error) => match upgrade_profile(path) {
|
||||
Ok(ProfileUpgrade::Upgraded { backup, from, to }) => {
|
||||
eprintln!(
|
||||
"upgraded profile {} from schema {} to {}; backup: {}",
|
||||
path.display(),
|
||||
from,
|
||||
to,
|
||||
backup.display()
|
||||
);
|
||||
let upgraded = fs::read_to_string(path).with_context(|| {
|
||||
format!("could not read upgraded profile {}", path.display())
|
||||
})?;
|
||||
ProfileDocument::parse(&upgraded)
|
||||
.with_context(|| format!("upgraded profile {} is invalid", path.display()))
|
||||
}
|
||||
Ok(ProfileUpgrade::Current { .. }) => Err(original_error)
|
||||
.with_context(|| format!("profile {} is invalid", path.display())),
|
||||
Err(upgrade_error) => Err(original_error).with_context(|| {
|
||||
format!(
|
||||
"profile {} is invalid and could not be safely upgraded: {upgrade_error}",
|
||||
path.display()
|
||||
)
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_managed_profile(paths: &XdgPaths) -> Result<PathBuf> {
|
||||
const DEFAULT_PROFILE: &str = "default";
|
||||
|
||||
paths
|
||||
.create_layout()
|
||||
.context("could not initialize the fader_master configuration directories")?;
|
||||
let active = match fs::read_to_string(paths.config_file()) {
|
||||
Ok(source) => {
|
||||
ActiveConfig::parse(&source).context("active profile selection is invalid")?
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
let active = ActiveConfig::new(DEFAULT_PROFILE)?;
|
||||
let profile_path = paths.profile_file(DEFAULT_PROFILE)?;
|
||||
initialize_missing_profile(&profile_path, DEFAULT_PROFILE)?;
|
||||
AtomicFile::write(&paths.config_file(), active.to_toml()?.as_bytes())
|
||||
.context("could not initialize the active profile selection")?;
|
||||
active
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(error).with_context(|| {
|
||||
format!(
|
||||
"--config was omitted and active selection {} could not be read",
|
||||
paths.config_file().display()
|
||||
)
|
||||
});
|
||||
}
|
||||
};
|
||||
let profile_path = paths.profile_file(active.active_profile().as_str())?;
|
||||
initialize_missing_profile(&profile_path, active.active_profile().as_str())?;
|
||||
Ok(profile_path)
|
||||
}
|
||||
|
||||
fn initialize_missing_profile(path: &Path, id: &str) -> Result<()> {
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => {
|
||||
return Err(error)
|
||||
.with_context(|| format!("could not inspect profile {}", path.display()));
|
||||
}
|
||||
}
|
||||
let mut document = ProfileDocument::empty(id)?;
|
||||
if let Some(identity) = discover_single_midi_surface() {
|
||||
add_discovered_surface(&mut document, &identity)?;
|
||||
}
|
||||
let source = document.finish()?;
|
||||
AtomicFile::write(path, source.as_bytes())
|
||||
.with_context(|| format!("could not initialize profile {}", path.display()))
|
||||
}
|
||||
|
||||
fn discover_single_midi_surface() -> Option<PortIdentity> {
|
||||
let catalog = MidiInputCatalog::new("fader_master first-run discovery").ok()?;
|
||||
let ports = catalog.ports().ok()?;
|
||||
if ports.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let identities = LinuxIdentityCatalog::new().ok()?;
|
||||
identities.inspect(&ports[0]).ok()
|
||||
}
|
||||
|
||||
fn add_discovered_surface(document: &mut ProfileDocument, identity: &PortIdentity) -> Result<()> {
|
||||
let name = stable_midi_port_name(&identity.name);
|
||||
let id = midi_surface_id(name);
|
||||
let usb = identity.usb.as_ref();
|
||||
document.add_surface(
|
||||
&id,
|
||||
name,
|
||||
name,
|
||||
Some(name),
|
||||
usb.map(|value| value.vendor_id.as_str()),
|
||||
usb.map(|value| value.product_id.as_str()),
|
||||
usb.and_then(|value| value.serial.as_deref()),
|
||||
usb.and_then(|value| value.path.as_deref()),
|
||||
Some(&identity.backend_id),
|
||||
)?;
|
||||
document.set_default_controller(Some(&id))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stable_midi_port_name(name: &str) -> &str {
|
||||
let Some((prefix, suffix)) = name.rsplit_once(' ') else {
|
||||
return name;
|
||||
};
|
||||
let Some((client, port)) = suffix.split_once(':') else {
|
||||
return name;
|
||||
};
|
||||
if !client.is_empty()
|
||||
&& !port.is_empty()
|
||||
&& client.bytes().all(|byte| byte.is_ascii_digit())
|
||||
&& port.bytes().all(|byte| byte.is_ascii_digit())
|
||||
{
|
||||
prefix
|
||||
} else {
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
fn midi_surface_id(name: &str) -> String {
|
||||
let mut id = String::new();
|
||||
let mut separator = false;
|
||||
for character in name.chars() {
|
||||
if character.is_ascii_alphanumeric() {
|
||||
if separator && !id.is_empty() && id.len() < 63 {
|
||||
id.push('-');
|
||||
}
|
||||
separator = false;
|
||||
if id.len() < 64 {
|
||||
id.push(character.to_ascii_lowercase());
|
||||
}
|
||||
} else {
|
||||
separator = true;
|
||||
}
|
||||
}
|
||||
if id.is_empty() {
|
||||
"midi-controller".to_owned()
|
||||
} else {
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
fn build_server(
|
||||
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 => resolve_managed_profile(&paths)?,
|
||||
};
|
||||
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, fs};
|
||||
|
||||
use fader_config::{ActiveConfig, ProfileDocument, XdgEnvironment, XdgPaths};
|
||||
use midi::{PortIdentity, UsbDeviceIdentity};
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::{
|
||||
add_discovered_surface, load_profile_document, midi_surface_id, resolve_managed_profile,
|
||||
stable_midi_port_name, start_if_missing,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn first_run_guess_uses_one_discovered_controller_and_durable_identity() {
|
||||
let mut document = ProfileDocument::empty("default").unwrap();
|
||||
add_discovered_surface(
|
||||
&mut document,
|
||||
&PortIdentity {
|
||||
backend_id: "36:0".to_owned(),
|
||||
name: "APC MINI:APC MINI MIDI 1 36:0".to_owned(),
|
||||
usb: Some(UsbDeviceIdentity {
|
||||
vendor_id: "09e8".to_owned(),
|
||||
product_id: "0028".to_owned(),
|
||||
serial: Some("Ver00.10".to_owned()),
|
||||
path: Some("pci-usb-0:1".to_owned()),
|
||||
}),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let profile = document.preview().unwrap();
|
||||
assert_eq!(
|
||||
profile.default_controller(),
|
||||
Some("apc-mini-apc-mini-midi-1")
|
||||
);
|
||||
assert_eq!(profile.surfaces()[0].label(), "APC MINI:APC MINI MIDI 1");
|
||||
assert_eq!(profile.surfaces()[0].usb_serial(), Some("Ver00.10"));
|
||||
assert_eq!(profile.surfaces()[0].manual_backend_id(), Some("36:0"));
|
||||
assert_eq!(profile.faders()[0].id(), "master-fader");
|
||||
assert_eq!(
|
||||
stable_midi_port_name("Controller Port 24:3"),
|
||||
"Controller Port"
|
||||
);
|
||||
assert_eq!(midi_surface_id(" !!! "), "midi-controller");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combined_mode_only_starts_a_server_when_probe_did_not_find_one() {
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_startup_initializes_missing_active_selection_and_profile() {
|
||||
let root = tempdir().unwrap();
|
||||
let paths = XdgPaths::resolve(&XdgEnvironment {
|
||||
home: root.path().join("home"),
|
||||
config_home: Some(root.path().join("config")),
|
||||
state_home: Some(root.path().join("state")),
|
||||
runtime_dir: Some(root.path().join("runtime")),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let profile_path = resolve_managed_profile(&paths).unwrap();
|
||||
|
||||
assert_eq!(profile_path, paths.profile_file("default").unwrap());
|
||||
let active =
|
||||
ActiveConfig::parse(&fs::read_to_string(paths.config_file()).unwrap()).unwrap();
|
||||
assert_eq!(active.active_profile().as_str(), "default");
|
||||
let document = ProfileDocument::parse(&fs::read_to_string(&profile_path).unwrap()).unwrap();
|
||||
let profile = document.preview().unwrap();
|
||||
assert_eq!(profile.id().as_str(), "default");
|
||||
assert_eq!(profile.faders().len(), 1);
|
||||
assert_eq!(profile.faders()[0].id(), "master-fader");
|
||||
assert_eq!(
|
||||
profile.faders()[0].target_kind(),
|
||||
fader_config::TargetKind::Output
|
||||
);
|
||||
assert_eq!(profile.faders()[0].target_id(), "default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_startup_recreates_only_a_missing_selected_profile() {
|
||||
let root = tempdir().unwrap();
|
||||
let paths = XdgPaths::resolve(&XdgEnvironment {
|
||||
home: root.path().join("home"),
|
||||
config_home: Some(root.path().join("config")),
|
||||
state_home: Some(root.path().join("state")),
|
||||
runtime_dir: Some(root.path().join("runtime")),
|
||||
})
|
||||
.unwrap();
|
||||
paths.create_layout().unwrap();
|
||||
let active = ActiveConfig::new("arch-pipewire").unwrap();
|
||||
fs::write(paths.config_file(), active.to_toml().unwrap()).unwrap();
|
||||
|
||||
let profile_path = resolve_managed_profile(&paths).unwrap();
|
||||
|
||||
assert_eq!(profile_path, paths.profile_file("arch-pipewire").unwrap());
|
||||
let document = ProfileDocument::parse(&fs::read_to_string(&profile_path).unwrap()).unwrap();
|
||||
assert_eq!(document.preview().unwrap().id().as_str(), "arch-pipewire");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_load_upgrades_an_old_profile_with_a_backup() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("legacy.toml");
|
||||
let legacy = ProfileDocument::empty("legacy")
|
||||
.unwrap()
|
||||
.finish()
|
||||
.unwrap()
|
||||
.replace("schema_version = 1", "schema_version = 0");
|
||||
fs::write(&path, &legacy).unwrap();
|
||||
|
||||
let document = load_profile_document(&path).unwrap();
|
||||
|
||||
assert_eq!(document.preview().unwrap().id().as_str(), "legacy");
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.path().join("legacy.toml.v0.bak")).unwrap(),
|
||||
legacy
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_load_does_not_rewrite_a_malformed_profile() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("broken.toml");
|
||||
let malformed = "schema_version = 0\nid = [not valid";
|
||||
fs::write(&path, malformed).unwrap();
|
||||
|
||||
let error = load_profile_document(&path).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("could not be safely upgraded"));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), malformed);
|
||||
assert!(!root.path().join("broken.toml.v0.bak").exists());
|
||||
}
|
||||
}
|
||||
|
|
@ -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())
|
||||
}
|
||||
|
|
@ -0,0 +1,158 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use volume_lib::{AdapterChoice, AudioBackend};
|
||||
|
||||
/// 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: 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)]
|
||||
pub enum Command {
|
||||
/// Run the persistent audio/MIDI server.
|
||||
Serve {
|
||||
/// Validated profile to activate.
|
||||
#[arg(long)]
|
||||
config: Option<PathBuf>,
|
||||
/// Session-only audio backend override.
|
||||
#[arg(long, value_enum)]
|
||||
audio: Option<AudioArgument>,
|
||||
/// Override the XDG runtime socket path.
|
||||
#[arg(long)]
|
||||
socket: Option<PathBuf>,
|
||||
},
|
||||
/// Open the terminal mixer connected to the running server.
|
||||
Tui {
|
||||
/// Override the XDG runtime socket path.
|
||||
#[arg(long)]
|
||||
socket: Option<PathBuf>,
|
||||
/// Session-only initial color theme override.
|
||||
#[arg(long, value_enum)]
|
||||
theme: Option<ThemeArgument>,
|
||||
},
|
||||
/// Validate a profile without opening devices or changing audio.
|
||||
Validate {
|
||||
#[arg(long)]
|
||||
config: PathBuf,
|
||||
},
|
||||
/// List MIDI ports and durable identity metadata.
|
||||
Devices,
|
||||
/// Print a snapshot from the running server.
|
||||
Status {
|
||||
/// Override the XDG runtime socket path.
|
||||
#[arg(long)]
|
||||
socket: Option<PathBuf>,
|
||||
},
|
||||
/// Manage the active profile.
|
||||
Profile {
|
||||
#[command(subcommand)]
|
||||
command: ProfileCommand,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Subcommand)]
|
||||
pub enum ProfileCommand {
|
||||
/// Request activation of a validated profile ID.
|
||||
Switch {
|
||||
id: String,
|
||||
/// Explicitly apply saved desired application state after activation.
|
||||
#[arg(long)]
|
||||
restore: bool,
|
||||
/// Override the XDG runtime socket path.
|
||||
#[arg(long)]
|
||||
socket: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
|
||||
pub enum AudioArgument {
|
||||
Auto,
|
||||
Pulse,
|
||||
Pipewire,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
|
||||
pub enum ThemeArgument {
|
||||
#[default]
|
||||
Default,
|
||||
Dracula,
|
||||
Nord,
|
||||
GruvboxDark,
|
||||
CatppuccinMocha,
|
||||
SolarizedDark,
|
||||
}
|
||||
|
||||
impl ThemeArgument {
|
||||
#[must_use]
|
||||
pub const fn theme(self) -> tui::ThemeName {
|
||||
match self {
|
||||
Self::Default => tui::ThemeName::Default,
|
||||
Self::Dracula => tui::ThemeName::Dracula,
|
||||
Self::Nord => tui::ThemeName::Nord,
|
||||
Self::GruvboxDark => tui::ThemeName::GruvboxDark,
|
||||
Self::CatppuccinMocha => tui::ThemeName::CatppuccinMocha,
|
||||
Self::SolarizedDark => tui::ThemeName::SolarizedDark,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioArgument {
|
||||
#[must_use]
|
||||
pub const fn choice(self) -> AdapterChoice {
|
||||
match self {
|
||||
Self::Auto => AdapterChoice::Auto,
|
||||
Self::Pulse => AdapterChoice::Manual(AudioBackend::Pulse),
|
||||
Self::Pipewire => AdapterChoice::Manual(AudioBackend::PipeWire),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,955 @@
|
|||
use std::{
|
||||
fs, io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use fader_config::{
|
||||
AtomicFile, ConfigError, PersistenceError, Profile, ProfileDocument, SelectorDraft,
|
||||
SelectorField, SelectorPattern, TargetKind,
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::ipc::{ConfigurationEdit, MixerObjectKind};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub(crate) enum EditorError {
|
||||
#[error("stale configuration revision {actual}; current revision is {current}")]
|
||||
StaleRevision { actual: u64, current: u64 },
|
||||
#[error(transparent)]
|
||||
Config(#[from] ConfigError),
|
||||
#[error("profile file changed outside fader_master; refusing to overwrite {0}")]
|
||||
ExternalConflict(PathBuf),
|
||||
#[error("could not read profile file {path}: {source}")]
|
||||
Read {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error(transparent)]
|
||||
Persistence(#[from] PersistenceError),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ConfigurationEditor {
|
||||
document: ProfileDocument,
|
||||
revision: u64,
|
||||
dirty: bool,
|
||||
path: PathBuf,
|
||||
baseline_source: String,
|
||||
}
|
||||
|
||||
impl ConfigurationEditor {
|
||||
pub(crate) fn new(document: ProfileDocument, path: PathBuf) -> Self {
|
||||
let baseline_source = document.source();
|
||||
Self {
|
||||
document,
|
||||
revision: 0,
|
||||
dirty: false,
|
||||
path,
|
||||
baseline_source,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
pub(crate) const fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
|
||||
pub(crate) const fn dirty(&self) -> bool {
|
||||
self.dirty
|
||||
}
|
||||
|
||||
pub(crate) fn profile(&self) -> Result<Profile, EditorError> {
|
||||
Ok(self.document.preview()?)
|
||||
}
|
||||
|
||||
pub(crate) fn apply(
|
||||
&mut self,
|
||||
expected_revision: u64,
|
||||
edit: ConfigurationEdit,
|
||||
) -> Result<Profile, EditorError> {
|
||||
if expected_revision != self.revision {
|
||||
return Err(EditorError::StaleRevision {
|
||||
actual: expected_revision,
|
||||
current: self.revision,
|
||||
});
|
||||
}
|
||||
match edit {
|
||||
ConfigurationEdit::AddApplicationFader {
|
||||
application_id,
|
||||
label,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
fader_id,
|
||||
position,
|
||||
} => self.document.add_application_fader(
|
||||
&application_id,
|
||||
&label,
|
||||
&selector(&field, pattern, regex)?,
|
||||
&fader_id,
|
||||
position,
|
||||
)?,
|
||||
ConfigurationEdit::AddGroupFader {
|
||||
group_id,
|
||||
label,
|
||||
fader_id,
|
||||
position,
|
||||
} => self
|
||||
.document
|
||||
.add_group_fader(&group_id, &label, &fader_id, position)?,
|
||||
ConfigurationEdit::RemoveMixerFader { id } => self.document.remove_mixer_fader(&id)?,
|
||||
ConfigurationEdit::SetTargetLabel { target, label } => match target.kind {
|
||||
MixerObjectKind::Application => {
|
||||
self.document.set_application_label(&target.id, &label)?
|
||||
}
|
||||
MixerObjectKind::Group => self.document.set_group_label(&target.id, &label)?,
|
||||
MixerObjectKind::Output => {
|
||||
return Err(ConfigError::Validation {
|
||||
path: "faders.target".to_owned(),
|
||||
message: "the backend-owned output label cannot be renamed".to_owned(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
},
|
||||
ConfigurationEdit::AddSurface {
|
||||
id,
|
||||
label,
|
||||
input_port,
|
||||
output_port,
|
||||
usb_vendor_id,
|
||||
usb_product_id,
|
||||
usb_serial,
|
||||
usb_path,
|
||||
manual_backend_id,
|
||||
} => {
|
||||
self.document.add_surface(
|
||||
&id,
|
||||
&label,
|
||||
&input_port,
|
||||
output_port.as_deref(),
|
||||
usb_vendor_id.as_deref(),
|
||||
usb_product_id.as_deref(),
|
||||
usb_serial.as_deref(),
|
||||
usb_path.as_deref(),
|
||||
manual_backend_id.as_deref(),
|
||||
)?;
|
||||
if self.document.preview()?.default_controller().is_none() {
|
||||
self.document.set_default_controller(Some(&id))?;
|
||||
}
|
||||
}
|
||||
ConfigurationEdit::RemoveSurface { id } => self.document.remove_surface(&id)?,
|
||||
ConfigurationEdit::AddApplication {
|
||||
id,
|
||||
label,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
} => {
|
||||
self.document
|
||||
.add_application(&id, &label, &[selector(&field, pattern, regex)?])?
|
||||
}
|
||||
ConfigurationEdit::SetApplication {
|
||||
id,
|
||||
label,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
} => {
|
||||
self.document
|
||||
.set_application(&id, &label, &[selector(&field, pattern, regex)?])?
|
||||
}
|
||||
ConfigurationEdit::SetMediaEntry { entry } => self.document.set_media_entry(&entry)?,
|
||||
ConfigurationEdit::RemoveMediaEntry { id } => self.document.remove_media_entry(&id)?,
|
||||
ConfigurationEdit::SetMediaBinding {
|
||||
entry,
|
||||
control,
|
||||
binding,
|
||||
} => {
|
||||
let profile = self.document.preview()?;
|
||||
let mut entry = profile
|
||||
.media()
|
||||
.iter()
|
||||
.find(|e| e.id == entry)
|
||||
.cloned()
|
||||
.ok_or_else(|| ConfigError::Validation {
|
||||
path: "media".into(),
|
||||
message: "unknown entry".into(),
|
||||
})?;
|
||||
let target = entry
|
||||
.controls
|
||||
.iter_mut()
|
||||
.find(|c| c.id == control)
|
||||
.ok_or_else(|| ConfigError::Validation {
|
||||
path: "media".into(),
|
||||
message: "unknown control".into(),
|
||||
})?;
|
||||
target.binding = binding;
|
||||
self.document.set_media_entry(&entry)?;
|
||||
}
|
||||
ConfigurationEdit::SetFeedbackEnabled { fader, enabled } => self
|
||||
.document
|
||||
.set_feedback_enabled(fader.as_deref(), enabled)?,
|
||||
ConfigurationEdit::SetApplicationSelectorMode { id, match_all } => {
|
||||
self.document.set_application_selector_mode(
|
||||
&id,
|
||||
if match_all {
|
||||
fader_config::SelectorMode::All
|
||||
} else {
|
||||
fader_config::SelectorMode::Any
|
||||
},
|
||||
)?;
|
||||
}
|
||||
ConfigurationEdit::SetApplicationSelector {
|
||||
id,
|
||||
index,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
} => self.document.set_application_selector(
|
||||
&id,
|
||||
index,
|
||||
&selector(&field, pattern, regex)?,
|
||||
)?,
|
||||
ConfigurationEdit::RemoveApplication { id } => self.document.remove_application(&id)?,
|
||||
ConfigurationEdit::AddGroup { id, label, members } => {
|
||||
let members = members.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
self.document.add_group(&id, &label, &members)?;
|
||||
}
|
||||
ConfigurationEdit::SetGroup { id, label, members } => {
|
||||
let members = members.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
self.document.set_group(&id, &label, &members)?;
|
||||
}
|
||||
ConfigurationEdit::RemoveGroup { id } => self.document.remove_group(&id)?,
|
||||
ConfigurationEdit::AddFader {
|
||||
id,
|
||||
target,
|
||||
pickup,
|
||||
pickup_tolerance,
|
||||
} => self.document.add_fader(
|
||||
&id,
|
||||
target_kind(target.kind),
|
||||
&target.id,
|
||||
pickup,
|
||||
pickup_tolerance,
|
||||
)?,
|
||||
ConfigurationEdit::SetFader {
|
||||
id,
|
||||
target,
|
||||
pickup,
|
||||
pickup_tolerance,
|
||||
} => self.document.set_fader(
|
||||
&id,
|
||||
target_kind(target.kind),
|
||||
&target.id,
|
||||
pickup,
|
||||
pickup_tolerance,
|
||||
)?,
|
||||
ConfigurationEdit::RemoveFader { id } => self.document.remove_fader(&id)?,
|
||||
ConfigurationEdit::AddBinding {
|
||||
surface,
|
||||
fader,
|
||||
action,
|
||||
kind,
|
||||
channel,
|
||||
number,
|
||||
} => self.document.add_binding(
|
||||
&surface,
|
||||
&fader,
|
||||
match action.as_str() {
|
||||
"volume" => fader_config::Action::Volume,
|
||||
"toggle_mute" => fader_config::Action::ToggleMute,
|
||||
_ => {
|
||||
return Err(ConfigError::Validation {
|
||||
path: "binding.action".to_owned(),
|
||||
message: format!("unsupported action {action:?}"),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
},
|
||||
match kind.as_str() {
|
||||
"cc" => fader_config::MessageKind::Cc,
|
||||
"note" => fader_config::MessageKind::Note,
|
||||
_ => {
|
||||
return Err(ConfigError::Validation {
|
||||
path: "binding.message.kind".to_owned(),
|
||||
message: format!("unsupported message kind {kind:?}"),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
},
|
||||
channel,
|
||||
number,
|
||||
)?,
|
||||
ConfigurationEdit::SetBinding {
|
||||
surface,
|
||||
fader,
|
||||
action,
|
||||
kind,
|
||||
channel,
|
||||
number,
|
||||
} => self.document.set_binding(
|
||||
&surface,
|
||||
&fader,
|
||||
binding_action(&action)?,
|
||||
binding_kind(&kind)?,
|
||||
channel,
|
||||
number,
|
||||
)?,
|
||||
ConfigurationEdit::RemoveBinding { fader, action } => self
|
||||
.document
|
||||
.remove_bindings(&fader, binding_action(&action)?)?,
|
||||
ConfigurationEdit::MoveLayoutEntry { id, position } => {
|
||||
self.document.move_layout_entry(&id, position)?
|
||||
}
|
||||
ConfigurationEdit::SetFaderHidden { id, hidden } => {
|
||||
self.document.set_fader_hidden(&id, hidden)?
|
||||
}
|
||||
ConfigurationEdit::SetFaderDensity { id, density } => self.document.set_fader_density(
|
||||
&id,
|
||||
match density {
|
||||
crate::ipc::FaderDensity::Slim => fader_config::FaderDensity::Slim,
|
||||
crate::ipc::FaderDensity::BorderedSlim => {
|
||||
fader_config::FaderDensity::BorderedSlim
|
||||
}
|
||||
crate::ipc::FaderDensity::Standard => fader_config::FaderDensity::Standard,
|
||||
crate::ipc::FaderDensity::Thick => fader_config::FaderDensity::Thick,
|
||||
},
|
||||
)?,
|
||||
ConfigurationEdit::SetMixerOrientation { orientation } => {
|
||||
self.document.set_mixer_orientation(match orientation {
|
||||
crate::ipc::MixerOrientation::Vertical => {
|
||||
fader_config::MixerOrientation::Vertical
|
||||
}
|
||||
crate::ipc::MixerOrientation::Horizontal => {
|
||||
fader_config::MixerOrientation::Horizontal
|
||||
}
|
||||
})?
|
||||
}
|
||||
ConfigurationEdit::SetStatusDisplay { mode } => {
|
||||
self.document.set_status_display(match mode {
|
||||
crate::ipc::StatusDisplayMode::Detailed => {
|
||||
fader_config::StatusDisplayMode::Detailed
|
||||
}
|
||||
crate::ipc::StatusDisplayMode::Compact => {
|
||||
fader_config::StatusDisplayMode::Compact
|
||||
}
|
||||
crate::ipc::StatusDisplayMode::Symbol => {
|
||||
fader_config::StatusDisplayMode::Symbol
|
||||
}
|
||||
crate::ipc::StatusDisplayMode::Color => fader_config::StatusDisplayMode::Color,
|
||||
crate::ipc::StatusDisplayMode::Hidden => {
|
||||
fader_config::StatusDisplayMode::Hidden
|
||||
}
|
||||
})?
|
||||
}
|
||||
ConfigurationEdit::SetDefaultController { surface } => {
|
||||
self.document.set_default_controller(surface.as_deref())?
|
||||
}
|
||||
ConfigurationEdit::SetTheme { theme } => {
|
||||
self.document.set_theme(match theme.as_str() {
|
||||
"default" => fader_config::UiTheme::Default,
|
||||
"dracula" => fader_config::UiTheme::Dracula,
|
||||
"nord" => fader_config::UiTheme::Nord,
|
||||
"gruvbox-dark" => fader_config::UiTheme::GruvboxDark,
|
||||
"catppuccin-mocha" => fader_config::UiTheme::CatppuccinMocha,
|
||||
"solarized-dark" => fader_config::UiTheme::SolarizedDark,
|
||||
_ => {
|
||||
return Err(ConfigError::Validation {
|
||||
path: "ui.theme".to_owned(),
|
||||
message: format!("unsupported theme {theme:?}"),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
})?
|
||||
}
|
||||
ConfigurationEdit::AddSeparator {
|
||||
id,
|
||||
label,
|
||||
position,
|
||||
} => self.document.add_separator(&id, &label, position)?,
|
||||
ConfigurationEdit::SetSeparatorLabel { id, label } => {
|
||||
self.document.set_separator_label(&id, &label)?
|
||||
}
|
||||
ConfigurationEdit::RemoveSeparator { id } => self.document.remove_separator(&id)?,
|
||||
ConfigurationEdit::SetSeparatorPresentation {
|
||||
id,
|
||||
size,
|
||||
decoration,
|
||||
} => {
|
||||
self.document.set_separator_presentation(
|
||||
&id,
|
||||
match size {
|
||||
crate::ipc::SeparatorSize::Slim => fader_config::SeparatorSize::Slim,
|
||||
crate::ipc::SeparatorSize::Standard => {
|
||||
fader_config::SeparatorSize::Standard
|
||||
}
|
||||
crate::ipc::SeparatorSize::Thick => fader_config::SeparatorSize::Thick,
|
||||
crate::ipc::SeparatorSize::Fill => fader_config::SeparatorSize::Fill,
|
||||
},
|
||||
match decoration {
|
||||
crate::ipc::SeparatorDecoration::Plain => {
|
||||
fader_config::SeparatorDecoration::Plain
|
||||
}
|
||||
crate::ipc::SeparatorDecoration::Line => {
|
||||
fader_config::SeparatorDecoration::Line
|
||||
}
|
||||
crate::ipc::SeparatorDecoration::Double => {
|
||||
fader_config::SeparatorDecoration::Double
|
||||
}
|
||||
crate::ipc::SeparatorDecoration::Box => {
|
||||
fader_config::SeparatorDecoration::Box
|
||||
}
|
||||
},
|
||||
)?;
|
||||
}
|
||||
}
|
||||
self.revision = self.revision.saturating_add(1);
|
||||
self.dirty = true;
|
||||
self.profile()
|
||||
}
|
||||
|
||||
pub(crate) fn save(&mut self, expected_revision: u64) -> Result<(), EditorError> {
|
||||
if expected_revision != self.revision {
|
||||
return Err(EditorError::StaleRevision {
|
||||
actual: expected_revision,
|
||||
current: self.revision,
|
||||
});
|
||||
}
|
||||
let disk = fs::read_to_string(&self.path).map_err(|source| EditorError::Read {
|
||||
path: self.path.clone(),
|
||||
source,
|
||||
})?;
|
||||
if disk != self.baseline_source {
|
||||
return Err(EditorError::ExternalConflict(self.path.clone()));
|
||||
}
|
||||
let source = self.document.source();
|
||||
AtomicFile::write(&self.path, source.as_bytes())?;
|
||||
self.baseline_source = source;
|
||||
self.dirty = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&mut self, expected_revision: u64) -> Result<Profile, EditorError> {
|
||||
if expected_revision != self.revision {
|
||||
return Err(EditorError::StaleRevision {
|
||||
actual: expected_revision,
|
||||
current: self.revision,
|
||||
});
|
||||
}
|
||||
let disk = fs::read(&self.path).map_err(|source| EditorError::Read {
|
||||
path: self.path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let replacement = self.document.safe_defaults()?;
|
||||
let source = replacement.source();
|
||||
let file_name = self
|
||||
.path
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy())
|
||||
.unwrap_or_default();
|
||||
let backup = self.path.with_file_name(format!("{file_name}.reset.bak"));
|
||||
AtomicFile::write(&backup, &disk)?;
|
||||
AtomicFile::write(&self.path, source.as_bytes())?;
|
||||
self.document = replacement;
|
||||
self.baseline_source = source;
|
||||
self.revision = self.revision.saturating_add(1);
|
||||
self.dirty = false;
|
||||
self.profile()
|
||||
}
|
||||
}
|
||||
|
||||
fn binding_action(action: &str) -> Result<fader_config::Action, ConfigError> {
|
||||
match action {
|
||||
"volume" => Ok(fader_config::Action::Volume),
|
||||
"toggle_mute" => Ok(fader_config::Action::ToggleMute),
|
||||
_ => Err(ConfigError::Validation {
|
||||
path: "binding.action".to_owned(),
|
||||
message: format!("unsupported action {action:?}"),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn binding_kind(kind: &str) -> Result<fader_config::MessageKind, ConfigError> {
|
||||
match kind {
|
||||
"cc" => Ok(fader_config::MessageKind::Cc),
|
||||
"note" => Ok(fader_config::MessageKind::Note),
|
||||
_ => Err(ConfigError::Validation {
|
||||
path: "binding.message.kind".to_owned(),
|
||||
message: format!("unsupported message kind {kind:?}"),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn selector(field: &str, pattern: String, regex: bool) -> Result<SelectorDraft, ConfigError> {
|
||||
let field = match field {
|
||||
"application.name" => SelectorField::ApplicationName,
|
||||
"application.id" => SelectorField::ApplicationId,
|
||||
"application.process.binary" => SelectorField::ProcessBinary,
|
||||
"media.name" => SelectorField::MediaName,
|
||||
"application.process.executable" => SelectorField::ProcessExecutable,
|
||||
"application.process.working_directory" => SelectorField::ProcessWorkingDirectory,
|
||||
"steam.app_id" => SelectorField::SteamAppId,
|
||||
"steam.game_id" => SelectorField::SteamGameId,
|
||||
_ => {
|
||||
return Err(ConfigError::Validation {
|
||||
path: "application.selector.field".to_owned(),
|
||||
message: format!("unsupported selector field {field:?}"),
|
||||
});
|
||||
}
|
||||
};
|
||||
Ok(SelectorDraft {
|
||||
field,
|
||||
pattern: if regex {
|
||||
SelectorPattern::Regex(pattern)
|
||||
} else {
|
||||
SelectorPattern::Exact(pattern)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const fn target_kind(kind: MixerObjectKind) -> TargetKind {
|
||||
match kind {
|
||||
MixerObjectKind::Application => TargetKind::Application,
|
||||
MixerObjectKind::Group => TargetKind::Group,
|
||||
MixerObjectKind::Output => TargetKind::Output,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
use super::*;
|
||||
use crate::ipc::MixerObjectKey;
|
||||
use tempfile::tempdir;
|
||||
|
||||
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
|
||||
|
||||
#[test]
|
||||
fn discovered_surface_edit_bootstraps_the_default_controller() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("default.toml");
|
||||
let document = ProfileDocument::empty("default").unwrap();
|
||||
fs::write(&path, document.source()).unwrap();
|
||||
let mut editor = ConfigurationEditor::new(document, path);
|
||||
|
||||
let profile = editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::AddSurface {
|
||||
id: "apc-mini".into(),
|
||||
label: "APC MINI".into(),
|
||||
input_port: "APC MINI:APC MINI MIDI 1".into(),
|
||||
output_port: Some("APC MINI:APC MINI MIDI 1".into()),
|
||||
usb_vendor_id: Some("09e8".into()),
|
||||
usb_product_id: Some("0028".into()),
|
||||
usb_serial: Some("Ver00.10".into()),
|
||||
usb_path: None,
|
||||
manual_backend_id: Some("36:0".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(profile.surfaces()[0].id(), "apc-mini");
|
||||
assert_eq!(profile.default_controller(), Some("apc-mini"));
|
||||
assert!(editor.dirty());
|
||||
|
||||
let profile = editor
|
||||
.apply(
|
||||
1,
|
||||
ConfigurationEdit::RemoveSurface {
|
||||
id: "apc-mini".into(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(profile.surfaces().is_empty());
|
||||
assert_eq!(profile.default_controller(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_label_edits_preserve_stable_routing_ids() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("desktop.toml");
|
||||
let document = ProfileDocument::parse(PROFILE).unwrap();
|
||||
fs::write(&path, document.source()).unwrap();
|
||||
let mut editor = ConfigurationEditor::new(document, path);
|
||||
|
||||
let profile = editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::SetTargetLabel {
|
||||
target: MixerObjectKey {
|
||||
kind: MixerObjectKind::Application,
|
||||
id: "music".into(),
|
||||
},
|
||||
label: "Listening".into(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.applications()[0].id(), "music");
|
||||
assert_eq!(profile.applications()[0].label(), "Listening");
|
||||
|
||||
let profile = editor
|
||||
.apply(
|
||||
1,
|
||||
ConfigurationEdit::SetTargetLabel {
|
||||
target: MixerObjectKey {
|
||||
kind: MixerObjectKind::Group,
|
||||
id: "media".into(),
|
||||
},
|
||||
label: "Entertainment".into(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.groups()[0].id(), "media");
|
||||
assert_eq!(profile.groups()[0].label(), "Entertainment");
|
||||
assert_eq!(profile.faders()[0].target_id(), "media");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixer_object_edits_create_and_delete_complete_valid_units() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("default.toml");
|
||||
let document = ProfileDocument::empty("default").unwrap();
|
||||
fs::write(&path, document.source()).unwrap();
|
||||
let mut editor = ConfigurationEditor::new(document, path);
|
||||
|
||||
let profile = editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::AddApplicationFader {
|
||||
application_id: "chat".into(),
|
||||
label: "Chat".into(),
|
||||
field: "application.name".into(),
|
||||
pattern: "__fader_master_unconfigured_chat__".into(),
|
||||
regex: false,
|
||||
fader_id: "chat-fader".into(),
|
||||
position: 1,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.applications()[0].id(), "chat");
|
||||
assert_eq!(profile.faders()[1].id(), "chat-fader");
|
||||
|
||||
let profile = editor
|
||||
.apply(
|
||||
1,
|
||||
ConfigurationEdit::AddGroupFader {
|
||||
group_id: "players".into(),
|
||||
label: "Players".into(),
|
||||
fader_id: "players-fader".into(),
|
||||
position: 2,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.groups()[0].id(), "players");
|
||||
assert_eq!(profile.faders()[2].id(), "players-fader");
|
||||
|
||||
let profile = editor
|
||||
.apply(
|
||||
2,
|
||||
ConfigurationEdit::RemoveMixerFader {
|
||||
id: "chat-fader".into(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(profile.applications().is_empty());
|
||||
assert!(
|
||||
profile
|
||||
.faders()
|
||||
.iter()
|
||||
.all(|fader| fader.id() != "chat-fader")
|
||||
);
|
||||
assert_eq!(editor.revision(), 3);
|
||||
assert!(editor.dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepted_edits_advance_revision_and_stale_or_invalid_edits_do_not() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("desktop.toml");
|
||||
fs::write(&path, PROFILE).unwrap();
|
||||
let document = ProfileDocument::parse(PROFILE).unwrap();
|
||||
let mut editor = ConfigurationEditor::new(document, path);
|
||||
let profile = editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::AddFader {
|
||||
id: "browser-fader".into(),
|
||||
target: MixerObjectKey {
|
||||
kind: MixerObjectKind::Application,
|
||||
id: "browser".into(),
|
||||
},
|
||||
pickup: true,
|
||||
pickup_tolerance: 0.02,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.faders().len(), 2);
|
||||
assert_eq!(editor.revision(), 1);
|
||||
assert!(editor.dirty());
|
||||
|
||||
let stale = editor
|
||||
.apply(0, ConfigurationEdit::RemoveGroup { id: "media".into() })
|
||||
.unwrap_err();
|
||||
assert!(matches!(stale, EditorError::StaleRevision { .. }));
|
||||
let invalid = editor
|
||||
.apply(
|
||||
1,
|
||||
ConfigurationEdit::SetApplication {
|
||||
id: "browser".into(),
|
||||
label: "Browser".into(),
|
||||
field: "application.process.binary".into(),
|
||||
pattern: "(".into(),
|
||||
regex: true,
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(invalid.to_string().contains("regex"));
|
||||
assert_eq!(editor.revision(), 1);
|
||||
assert_eq!(editor.profile().unwrap().faders().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separator_presentation_is_saved_and_published_after_reload() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("desktop.toml");
|
||||
fs::write(&path, PROFILE).unwrap();
|
||||
let mut editor =
|
||||
ConfigurationEditor::new(ProfileDocument::parse(PROFILE).unwrap(), path.clone());
|
||||
editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::AddSeparator {
|
||||
id: "heading".into(),
|
||||
label: "Heading".into(),
|
||||
position: 0,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
editor
|
||||
.apply(
|
||||
1,
|
||||
ConfigurationEdit::SetSeparatorPresentation {
|
||||
id: "heading".into(),
|
||||
size: crate::ipc::SeparatorSize::Fill,
|
||||
decoration: crate::ipc::SeparatorDecoration::Box,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
editor.save(2).unwrap();
|
||||
let profile = fader_config::Profile::parse(&fs::read_to_string(path).unwrap()).unwrap();
|
||||
let snapshot = crate::live::configuration_snapshot(&profile, 0, false, 0);
|
||||
assert!(matches!(
|
||||
&snapshot.mixer_layout[0],
|
||||
crate::ipc::MixerLayoutEntry::Separator {
|
||||
size: crate::ipc::SeparatorSize::Fill,
|
||||
decoration: crate::ipc::SeparatorDecoration::Box,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selector_mode_is_saved_reloaded_and_published_to_clients() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("desktop.toml");
|
||||
fs::write(&path, PROFILE).unwrap();
|
||||
let mut editor =
|
||||
ConfigurationEditor::new(ProfileDocument::parse(PROFILE).unwrap(), path.clone());
|
||||
editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::SetApplicationSelectorMode {
|
||||
id: "music".into(),
|
||||
match_all: true,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
editor.save(1).unwrap();
|
||||
let document = ProfileDocument::parse(&fs::read_to_string(&path).unwrap()).unwrap();
|
||||
let profile = document.preview().unwrap();
|
||||
let snapshot = crate::live::configuration_snapshot(&profile, 0, false, 0);
|
||||
assert!(snapshot.applications[0].match_all);
|
||||
assert!(!snapshot.applications[1].match_all);
|
||||
let mut restarted = ConfigurationEditor::new(document, path);
|
||||
let profile = restarted
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::SetApplicationSelectorMode {
|
||||
id: "music".into(),
|
||||
match_all: false,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
profile.applications()[0].selector_mode(),
|
||||
fader_config::SelectorMode::Any
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_edits_are_revisioned_without_changing_fader_routing() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("desktop.toml");
|
||||
fs::write(&path, PROFILE).unwrap();
|
||||
let document = ProfileDocument::parse(PROFILE).unwrap();
|
||||
let mut editor = ConfigurationEditor::new(document, path);
|
||||
|
||||
editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::AddSeparator {
|
||||
id: "media-heading".into(),
|
||||
label: "Media".into(),
|
||||
position: 0,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
editor
|
||||
.apply(
|
||||
1,
|
||||
ConfigurationEdit::SetFaderHidden {
|
||||
id: "media-fader".into(),
|
||||
hidden: true,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
editor
|
||||
.apply(
|
||||
2,
|
||||
ConfigurationEdit::SetFaderDensity {
|
||||
id: "media-fader".into(),
|
||||
density: crate::ipc::FaderDensity::Slim,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
editor
|
||||
.apply(
|
||||
3,
|
||||
ConfigurationEdit::SetMixerOrientation {
|
||||
orientation: crate::ipc::MixerOrientation::Horizontal,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let profile = editor
|
||||
.apply(
|
||||
4,
|
||||
ConfigurationEdit::SetDefaultController {
|
||||
surface: Some("desk-left".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.faders().len(), 1);
|
||||
assert_eq!(profile.mixer_layout().len(), 2);
|
||||
assert!(matches!(
|
||||
&profile.mixer_layout()[1],
|
||||
fader_config::MixerLayoutEntry::Fader {
|
||||
density: fader_config::FaderDensity::Slim,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_eq!(
|
||||
profile.mixer_orientation(),
|
||||
fader_config::MixerOrientation::Horizontal
|
||||
);
|
||||
assert_eq!(profile.default_controller(), Some("desk-left"));
|
||||
assert_eq!(editor.revision(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_is_atomic_and_refuses_external_changes() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("desktop.toml");
|
||||
fs::write(&path, PROFILE).unwrap();
|
||||
let document = ProfileDocument::parse(PROFILE).unwrap();
|
||||
let mut editor = ConfigurationEditor::new(document, path.clone());
|
||||
editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::SetGroup {
|
||||
id: "media".into(),
|
||||
label: "Players".into(),
|
||||
members: vec!["music".into(), "browser".into()],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
editor.save(1).unwrap();
|
||||
assert!(!editor.dirty());
|
||||
assert!(fs::read_to_string(&path).unwrap().contains("Players"));
|
||||
|
||||
editor
|
||||
.apply(
|
||||
1,
|
||||
ConfigurationEdit::SetGroup {
|
||||
id: "media".into(),
|
||||
label: "Media again".into(),
|
||||
members: vec!["music".into(), "browser".into()],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(&path, "external edit").unwrap();
|
||||
assert!(matches!(
|
||||
editor.save(2),
|
||||
Err(EditorError::ExternalConflict(_))
|
||||
));
|
||||
assert!(editor.dirty());
|
||||
assert_eq!(fs::read_to_string(path).unwrap(), "external edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_failure_keeps_previous_file_and_unsaved_draft() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("desktop.toml");
|
||||
fs::write(&path, PROFILE).unwrap();
|
||||
let document = ProfileDocument::parse(PROFILE).unwrap();
|
||||
let mut editor = ConfigurationEditor::new(document, path.clone());
|
||||
editor
|
||||
.apply(
|
||||
0,
|
||||
ConfigurationEdit::SetGroup {
|
||||
id: "media".into(),
|
||||
label: "Unsaved".into(),
|
||||
members: vec!["music".into(), "browser".into()],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o500)).unwrap();
|
||||
let result = editor.save(1);
|
||||
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
|
||||
assert!(matches!(result, Err(EditorError::Persistence(_))));
|
||||
assert!(editor.dirty());
|
||||
assert_eq!(fs::read_to_string(path).unwrap(), PROFILE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_backs_up_the_profile_and_installs_safe_defaults() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("desktop.toml");
|
||||
fs::write(&path, PROFILE).unwrap();
|
||||
let document = ProfileDocument::parse(PROFILE).unwrap();
|
||||
let original_poll_interval = document.preview().unwrap().poll_interval();
|
||||
let mut editor = ConfigurationEditor::new(document, path.clone());
|
||||
fs::write(&path, "not = [valid").unwrap();
|
||||
|
||||
let profile = editor.reset(0).unwrap();
|
||||
|
||||
assert_eq!(profile.id().as_str(), "desktop");
|
||||
assert_eq!(profile.poll_interval(), original_poll_interval);
|
||||
assert!(profile.applications().is_empty());
|
||||
assert!(profile.groups().is_empty());
|
||||
assert!(profile.surfaces().is_empty());
|
||||
assert_eq!(profile.faders()[0].id(), "master-fader");
|
||||
assert_eq!(editor.revision(), 1);
|
||||
assert!(!editor.dirty());
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.path().join("desktop.toml.reset.bak")).unwrap(),
|
||||
"not = [valid"
|
||||
);
|
||||
assert!(ProfileDocument::parse(&fs::read_to_string(path).unwrap()).is_ok());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,533 @@
|
|||
use std::io::{self, Read, Write};
|
||||
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const PROTOCOL_VERSION: u16 = 24;
|
||||
// Bounded playlist/discovery snapshots can legitimately exceed 64 KiB.
|
||||
pub const MAX_FRAME_BYTES: usize = 1024 * 1024;
|
||||
|
||||
/// Kind of mixer object addressed by a client.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MixerObjectKind {
|
||||
Application,
|
||||
Group,
|
||||
Output,
|
||||
}
|
||||
|
||||
/// Aggregate pickup state for physical controls mapped to one mixer object.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PickupStatus {
|
||||
Unavailable,
|
||||
Waiting,
|
||||
Tracking,
|
||||
Mixed,
|
||||
}
|
||||
|
||||
/// Stable configured mixer-object identity.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
pub struct MixerObjectKey {
|
||||
pub kind: MixerObjectKind,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub struct ClientRequest {
|
||||
pub version: u16,
|
||||
pub request_id: u64,
|
||||
pub command: RequestCommand,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum RequestCommand {
|
||||
MediaAction {
|
||||
entry: String,
|
||||
control: String,
|
||||
},
|
||||
StartMediaLearn {
|
||||
surface: String,
|
||||
entry: String,
|
||||
control: String,
|
||||
},
|
||||
Snapshot,
|
||||
EditConfiguration {
|
||||
expected_revision: u64,
|
||||
edit: ConfigurationEdit,
|
||||
},
|
||||
StartMidiLearn {
|
||||
surface: String,
|
||||
fader: String,
|
||||
action: String,
|
||||
},
|
||||
CancelMidiLearn,
|
||||
SaveConfiguration {
|
||||
expected_revision: u64,
|
||||
},
|
||||
ResetConfiguration {
|
||||
expected_revision: u64,
|
||||
},
|
||||
SwitchProfile {
|
||||
id: String,
|
||||
restore: bool,
|
||||
},
|
||||
SetVolume {
|
||||
object: MixerObjectKey,
|
||||
gain: f64,
|
||||
expected_revision: u64,
|
||||
},
|
||||
ToggleMute {
|
||||
object: MixerObjectKey,
|
||||
expected_revision: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(tag = "operation", rename_all = "snake_case")]
|
||||
pub enum ConfigurationEdit {
|
||||
SetMediaEntry {
|
||||
entry: media::Entry,
|
||||
},
|
||||
RemoveMediaEntry {
|
||||
id: String,
|
||||
},
|
||||
SetMediaBinding {
|
||||
entry: String,
|
||||
control: String,
|
||||
binding: Option<media::Binding>,
|
||||
},
|
||||
SetFeedbackEnabled {
|
||||
fader: Option<String>,
|
||||
enabled: bool,
|
||||
},
|
||||
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,
|
||||
},
|
||||
SetTargetLabel {
|
||||
target: MixerObjectKey,
|
||||
label: 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>,
|
||||
},
|
||||
RemoveSurface {
|
||||
id: String,
|
||||
},
|
||||
AddApplication {
|
||||
id: String,
|
||||
label: String,
|
||||
field: String,
|
||||
pattern: String,
|
||||
regex: bool,
|
||||
},
|
||||
SetApplication {
|
||||
id: String,
|
||||
label: String,
|
||||
field: String,
|
||||
pattern: String,
|
||||
regex: bool,
|
||||
},
|
||||
SetApplicationSelectorMode {
|
||||
id: String,
|
||||
match_all: bool,
|
||||
},
|
||||
SetApplicationSelector {
|
||||
id: String,
|
||||
index: usize,
|
||||
field: String,
|
||||
pattern: String,
|
||||
regex: bool,
|
||||
},
|
||||
RemoveApplication {
|
||||
id: String,
|
||||
},
|
||||
AddGroup {
|
||||
id: String,
|
||||
label: String,
|
||||
members: Vec<String>,
|
||||
},
|
||||
SetGroup {
|
||||
id: String,
|
||||
label: String,
|
||||
members: Vec<String>,
|
||||
},
|
||||
RemoveGroup {
|
||||
id: String,
|
||||
},
|
||||
AddFader {
|
||||
id: String,
|
||||
target: MixerObjectKey,
|
||||
pickup: bool,
|
||||
pickup_tolerance: f64,
|
||||
},
|
||||
SetFader {
|
||||
id: String,
|
||||
target: MixerObjectKey,
|
||||
pickup: bool,
|
||||
pickup_tolerance: f64,
|
||||
},
|
||||
RemoveFader {
|
||||
id: String,
|
||||
},
|
||||
AddBinding {
|
||||
surface: String,
|
||||
fader: String,
|
||||
action: String,
|
||||
kind: String,
|
||||
channel: u16,
|
||||
number: u16,
|
||||
},
|
||||
SetBinding {
|
||||
surface: String,
|
||||
fader: String,
|
||||
action: String,
|
||||
kind: String,
|
||||
channel: u16,
|
||||
number: u16,
|
||||
},
|
||||
RemoveBinding {
|
||||
fader: String,
|
||||
action: 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: String,
|
||||
},
|
||||
AddSeparator {
|
||||
id: String,
|
||||
label: String,
|
||||
position: usize,
|
||||
},
|
||||
SetSeparatorLabel {
|
||||
id: String,
|
||||
label: String,
|
||||
},
|
||||
SetSeparatorPresentation {
|
||||
id: String,
|
||||
size: SeparatorSize,
|
||||
decoration: SeparatorDecoration,
|
||||
},
|
||||
RemoveSeparator {
|
||||
id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub struct ServerResponse {
|
||||
pub version: u16,
|
||||
pub request_id: u64,
|
||||
pub result: ResponseResult,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ResponseResult {
|
||||
Snapshot { snapshot: Box<MixerSnapshot> },
|
||||
Error { message: String, resync: bool },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub struct MixerSnapshot {
|
||||
pub revision: u64,
|
||||
pub backend: String,
|
||||
pub status: String,
|
||||
pub objects: Vec<MixerObject>,
|
||||
pub devices: Vec<MidiDevice>,
|
||||
#[serde(default)]
|
||||
pub discovered_midi_ports: Vec<DiscoveredMidiPort>,
|
||||
pub configuration: ConfigurationSnapshot,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
|
||||
pub struct ConfigurationSnapshot {
|
||||
#[serde(default)]
|
||||
pub media_entries: Vec<media::Entry>,
|
||||
#[serde(default)]
|
||||
pub media_state: media::Snapshot,
|
||||
#[serde(default)]
|
||||
pub feedback_disabled: bool,
|
||||
#[serde(default)]
|
||||
pub disabled_feedback_faders: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub stream_metadata: Vec<String>,
|
||||
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,
|
||||
#[serde(default)]
|
||||
pub profile_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub available_profiles: Vec<String>,
|
||||
pub mixer_orientation: MixerOrientation,
|
||||
pub status_display: StatusDisplayMode,
|
||||
pub default_controller: Option<String>,
|
||||
pub theme: String,
|
||||
#[serde(default)]
|
||||
pub surfaces: Vec<ConfiguredSurface>,
|
||||
pub applications: Vec<ConfiguredApplication>,
|
||||
pub groups: Vec<ConfiguredGroup>,
|
||||
pub faders: Vec<ConfiguredFader>,
|
||||
pub mixer_layout: Vec<MixerLayoutEntry>,
|
||||
pub bindings: Vec<ConfiguredBinding>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct ConfiguredSurface {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MixerOrientation {
|
||||
#[default]
|
||||
Vertical,
|
||||
Horizontal,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum StatusDisplayMode {
|
||||
#[default]
|
||||
Detailed,
|
||||
Compact,
|
||||
Symbol,
|
||||
Color,
|
||||
Hidden,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
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, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SeparatorSize {
|
||||
Slim,
|
||||
#[default]
|
||||
Standard,
|
||||
Thick,
|
||||
Fill,
|
||||
}
|
||||
|
||||
/// Independent separator decoration.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SeparatorDecoration {
|
||||
Plain,
|
||||
#[default]
|
||||
Line,
|
||||
Double,
|
||||
Box,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FaderDensity {
|
||||
Slim,
|
||||
BorderedSlim,
|
||||
Standard,
|
||||
Thick,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct ConfiguredApplication {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
#[serde(default)]
|
||||
pub match_all: bool,
|
||||
pub selectors: Vec<ConfiguredSelector>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct ConfiguredSelector {
|
||||
pub field: String,
|
||||
pub pattern: String,
|
||||
pub regex: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GroupVolumeMode {
|
||||
Absolute,
|
||||
Relative,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct ConfiguredGroup {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub members: Vec<String>,
|
||||
pub volume_mode: GroupVolumeMode,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub struct ConfiguredFader {
|
||||
pub id: String,
|
||||
pub target: MixerObjectKey,
|
||||
pub pickup: bool,
|
||||
pub pickup_tolerance: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
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, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct MidiDevice {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub status: String,
|
||||
pub backend_id: Option<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct DiscoveredMidiPort {
|
||||
pub backend_id: String,
|
||||
pub name: String,
|
||||
pub usb_vendor_id: Option<String>,
|
||||
pub usb_product_id: Option<String>,
|
||||
pub usb_serial: Option<String>,
|
||||
pub usb_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub struct MixerObject {
|
||||
pub object: MixerObjectKey,
|
||||
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(Debug, Error)]
|
||||
pub enum FrameError {
|
||||
#[error("IPC frame length {actual} exceeds maximum {maximum}")]
|
||||
TooLarge { actual: usize, maximum: usize },
|
||||
#[error("IPC frame is truncated: {0}")]
|
||||
Truncated(io::Error),
|
||||
#[error("could not encode IPC TOML: {0}")]
|
||||
Encode(toml::ser::Error),
|
||||
#[error("could not decode IPC TOML: {0}")]
|
||||
Decode(toml::de::Error),
|
||||
#[error("IPC frame is not UTF-8: {0}")]
|
||||
Utf8(std::str::Utf8Error),
|
||||
#[error("could not write IPC frame: {0}")]
|
||||
Write(io::Error),
|
||||
}
|
||||
|
||||
pub fn write_frame<T: Serialize>(writer: &mut impl Write, value: &T) -> Result<(), FrameError> {
|
||||
let payload = toml::to_string(value).map_err(FrameError::Encode)?;
|
||||
if payload.len() > MAX_FRAME_BYTES {
|
||||
return Err(FrameError::TooLarge {
|
||||
actual: payload.len(),
|
||||
maximum: MAX_FRAME_BYTES,
|
||||
});
|
||||
}
|
||||
let length = u32::try_from(payload.len()).map_err(|_| FrameError::TooLarge {
|
||||
actual: payload.len(),
|
||||
maximum: MAX_FRAME_BYTES,
|
||||
})?;
|
||||
writer
|
||||
.write_all(&length.to_be_bytes())
|
||||
.and_then(|()| writer.write_all(payload.as_bytes()))
|
||||
.map_err(FrameError::Write)
|
||||
}
|
||||
|
||||
pub fn read_frame<T: DeserializeOwned>(reader: &mut impl Read) -> Result<T, FrameError> {
|
||||
let mut length = [0_u8; 4];
|
||||
reader
|
||||
.read_exact(&mut length)
|
||||
.map_err(FrameError::Truncated)?;
|
||||
let length = usize::try_from(u32::from_be_bytes(length)).map_err(|_| FrameError::TooLarge {
|
||||
actual: usize::MAX,
|
||||
maximum: MAX_FRAME_BYTES,
|
||||
})?;
|
||||
if length > MAX_FRAME_BYTES {
|
||||
return Err(FrameError::TooLarge {
|
||||
actual: length,
|
||||
maximum: MAX_FRAME_BYTES,
|
||||
});
|
||||
}
|
||||
let mut payload = vec![0_u8; length];
|
||||
reader
|
||||
.read_exact(&mut payload)
|
||||
.map_err(FrameError::Truncated)?;
|
||||
let payload = std::str::from_utf8(&payload).map_err(FrameError::Utf8)?;
|
||||
toml::from_str(payload).map_err(FrameError::Decode)
|
||||
}
|
||||
|
|
@ -0,0 +1,242 @@
|
|||
//! Hardware-free server lifecycle used by the first vertical slice.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod application;
|
||||
pub mod cli;
|
||||
mod editor;
|
||||
pub mod ipc;
|
||||
pub mod live;
|
||||
pub mod local;
|
||||
pub mod media_runtime;
|
||||
pub mod midi_runtime;
|
||||
pub mod tui_client;
|
||||
|
||||
use std::{collections::BTreeMap, error::Error, fmt};
|
||||
|
||||
use fader_core::{
|
||||
AdapterEvent, ChannelGains, CommandOrigin, Gain, Mute, ReducerError, ServerCommand,
|
||||
ServerReducer, StreamHandle, StreamView, Transition,
|
||||
};
|
||||
use volume_lib::{AdapterQueue, Enqueue, FakeAdapter};
|
||||
|
||||
use fader_config::{Adapter as ConfigAdapter, Profile};
|
||||
use volume_lib::{AdapterChoice, AudioBackend, SelectionPolicy, SelectionPolicyError};
|
||||
|
||||
/// Translates a validated profile and optional CLI/session override into the
|
||||
/// runtime audio selection policy without mutating the profile.
|
||||
pub fn audio_selection_policy(
|
||||
profile: &Profile,
|
||||
session_override: Option<AdapterChoice>,
|
||||
) -> Result<SelectionPolicy, SelectionPolicyError> {
|
||||
let configured = map_adapter(profile.audio().adapter());
|
||||
let preference = profile
|
||||
.audio()
|
||||
.preference()
|
||||
.iter()
|
||||
.filter_map(|adapter| match map_adapter(*adapter) {
|
||||
AdapterChoice::Auto => None,
|
||||
AdapterChoice::Manual(backend) => Some(backend),
|
||||
})
|
||||
.collect();
|
||||
SelectionPolicy::new(configured, preference, session_override)
|
||||
}
|
||||
|
||||
const fn map_adapter(adapter: ConfigAdapter) -> AdapterChoice {
|
||||
match adapter {
|
||||
ConfigAdapter::Auto => AdapterChoice::Auto,
|
||||
ConfigAdapter::Pulse => AdapterChoice::Manual(AudioBackend::Pulse),
|
||||
ConfigAdapter::Pipewire => AdapterChoice::Manual(AudioBackend::PipeWire),
|
||||
}
|
||||
}
|
||||
|
||||
/// Failure surfaced by the simulated server boundary.
|
||||
#[derive(Debug)]
|
||||
pub enum SliceError {
|
||||
Reducer(ReducerError),
|
||||
DispatchOverflow,
|
||||
SnapshotInProgress,
|
||||
}
|
||||
|
||||
/// Observable lifecycle state of the fake-backed server.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ServerStatus {
|
||||
Ready,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
impl fmt::Display for SliceError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Reducer(error) => error.fmt(formatter),
|
||||
Self::DispatchOverflow => formatter.write_str("bounded adapter queue overflowed"),
|
||||
Self::SnapshotInProgress => formatter.write_str("adapter snapshot is already active"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for SliceError {}
|
||||
|
||||
impl From<ReducerError> for SliceError {
|
||||
fn from(value: ReducerError) -> Self {
|
||||
Self::Reducer(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// In-process M3 server using the same effects as future native workers.
|
||||
#[derive(Debug)]
|
||||
pub struct VerticalSlice {
|
||||
reducer: ServerReducer,
|
||||
adapter: FakeAdapter,
|
||||
dispatch: AdapterQueue,
|
||||
confirmed: BTreeMap<StreamHandle, StreamView>,
|
||||
status: ServerStatus,
|
||||
}
|
||||
|
||||
impl VerticalSlice {
|
||||
#[must_use]
|
||||
pub fn new(adapter: FakeAdapter, queue_capacity: usize, write_ceiling: Gain) -> Self {
|
||||
Self {
|
||||
reducer: ServerReducer::new(write_ceiling),
|
||||
adapter,
|
||||
dispatch: AdapterQueue::new(queue_capacity),
|
||||
confirmed: BTreeMap::new(),
|
||||
status: ServerStatus::Ready,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn status(&self) -> ServerStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
/// Returns the latest observation confirmed by adapter readback.
|
||||
#[must_use]
|
||||
pub fn confirmed(&self, stream: StreamHandle) -> Option<&StreamView> {
|
||||
self.confirmed.get(&stream)
|
||||
}
|
||||
|
||||
/// Adds a discovered stream by adopting its live state without a write.
|
||||
pub fn adopt(
|
||||
&mut self,
|
||||
stream: StreamHandle,
|
||||
channels: ChannelGains,
|
||||
muted: Mute,
|
||||
) -> Result<StreamView, SliceError> {
|
||||
let event = self
|
||||
.adapter
|
||||
.upsert(stream, channels, muted)
|
||||
.ok_or(SliceError::SnapshotInProgress)?;
|
||||
self.reduce_event(event)?;
|
||||
self.confirmed
|
||||
.get(&stream)
|
||||
.cloned()
|
||||
.ok_or(SliceError::SnapshotInProgress)
|
||||
}
|
||||
|
||||
/// Runs a simulated MIDI volume command through dispatch and readback.
|
||||
pub fn midi_volume(
|
||||
&mut self,
|
||||
surface: impl Into<String>,
|
||||
sequence: u64,
|
||||
stream: StreamHandle,
|
||||
target: Gain,
|
||||
) -> Result<StreamView, SliceError> {
|
||||
let transition = self.reducer.command(ServerCommand::SetVolume {
|
||||
origin: CommandOrigin::Midi {
|
||||
surface: surface.into(),
|
||||
sequence,
|
||||
},
|
||||
expected_revision: self.reducer.revision(),
|
||||
stream,
|
||||
target,
|
||||
})?;
|
||||
self.enqueue(transition)?;
|
||||
self.drain()?;
|
||||
self.confirmed
|
||||
.get(&stream)
|
||||
.cloned()
|
||||
.ok_or(SliceError::SnapshotInProgress)
|
||||
}
|
||||
|
||||
/// Invalidates current handles and pending operations.
|
||||
pub fn disconnect(&mut self) -> Result<(), SliceError> {
|
||||
let streams = self.confirmed.keys().copied().collect::<Vec<_>>();
|
||||
for stream in streams {
|
||||
self.adapter.remove(stream);
|
||||
self.reduce_event(AdapterEvent::StreamRemoved { stream })?;
|
||||
self.confirmed.remove(&stream);
|
||||
}
|
||||
self.status = ServerStatus::Unavailable;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replaces a disconnected worker and adopts its complete fresh snapshot.
|
||||
pub fn reconnect(
|
||||
&mut self,
|
||||
adapter: FakeAdapter,
|
||||
observations: Vec<(StreamHandle, ChannelGains, Mute)>,
|
||||
) -> Result<(), SliceError> {
|
||||
self.adapter = adapter;
|
||||
self.status = ServerStatus::Ready;
|
||||
for (stream, channels, muted) in observations {
|
||||
self.adopt(stream, channels, muted)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies explicit restore entries in profile order; the last overlap wins.
|
||||
pub fn restore_volumes(&mut self, entries: &[(StreamHandle, Gain)]) -> Result<(), SliceError> {
|
||||
for (stream, target) in entries {
|
||||
let transition = self.reducer.command(ServerCommand::SetVolume {
|
||||
origin: CommandOrigin::Restore,
|
||||
expected_revision: self.reducer.revision(),
|
||||
stream: *stream,
|
||||
target: *target,
|
||||
})?;
|
||||
self.enqueue(transition)?;
|
||||
}
|
||||
self.drain()
|
||||
}
|
||||
|
||||
/// Drains accepted work and gives the final confirmed view to persistence.
|
||||
pub fn shutdown(mut self, checkpoint: impl FnOnce(&[StreamView])) -> Result<(), SliceError> {
|
||||
self.drain()?;
|
||||
let views = self.confirmed.into_values().collect::<Vec<_>>();
|
||||
checkpoint(&views);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reduce_event(&mut self, event: AdapterEvent) -> Result<(), SliceError> {
|
||||
let transition = self.reducer.event(event)?;
|
||||
self.enqueue(transition)
|
||||
}
|
||||
|
||||
fn enqueue(&mut self, transition: Transition) -> Result<(), SliceError> {
|
||||
for view in transition.confirmed {
|
||||
self.confirmed.insert(view.stream, view);
|
||||
}
|
||||
for command in transition.adapter {
|
||||
match self.dispatch.push(command) {
|
||||
Enqueue::Queued => {}
|
||||
Enqueue::Coalesced { superseded } => {
|
||||
self.reducer.event(AdapterEvent::WriteSuperseded {
|
||||
operation: superseded,
|
||||
})?;
|
||||
}
|
||||
Enqueue::Overflow => return Err(SliceError::DispatchOverflow),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drain(&mut self) -> Result<(), SliceError> {
|
||||
while let Some(command) = self.dispatch.pop() {
|
||||
for event in self.adapter.execute(command) {
|
||||
let transition = self.reducer.event(event)?;
|
||||
self.enqueue(transition)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -1,3 +1,7 @@
|
|||
fn main() {
|
||||
println!("Hello, world!");
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use fader_master::{application, cli::Cli};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
application::run(Cli::parse())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,239 @@
|
|||
//! Bounded MPRIS worker. Native connection ownership never leaves its thread.
|
||||
use media::{Action, Player, PlayerSelector, Snapshot};
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
mpsc::{self, SyncSender},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
trait Adapter {
|
||||
fn available(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn discover(&mut self) -> Result<Vec<Player>, String>;
|
||||
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String>;
|
||||
}
|
||||
|
||||
fn execute_selected(
|
||||
adapter: &mut impl Adapter,
|
||||
selector: &PlayerSelector,
|
||||
action: &Action,
|
||||
) -> Result<Vec<Player>, String> {
|
||||
action.validate().map_err(|e| e.to_string())?;
|
||||
let players = adapter.discover()?;
|
||||
let matcher = selector.compile().map_err(|e| e.to_string())?;
|
||||
let player = matcher.resolve(&players).map_err(|e| e.to_string())?;
|
||||
if !action.supported(player) {
|
||||
return Err(media::MediaError::Unsupported.to_string());
|
||||
}
|
||||
adapter.execute(player, action)?;
|
||||
adapter.discover()
|
||||
}
|
||||
|
||||
struct Command {
|
||||
generation: u64,
|
||||
selector: PlayerSelector,
|
||||
action: Action,
|
||||
expires: Instant,
|
||||
}
|
||||
|
||||
enum Work {
|
||||
Action(Command),
|
||||
Fence(SyncSender<()>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MediaRuntime {
|
||||
sender: SyncSender<Work>,
|
||||
generation: Arc<AtomicU64>,
|
||||
snapshot: Arc<Mutex<Snapshot>>,
|
||||
stop: Arc<AtomicBool>,
|
||||
worker: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl MediaRuntime {
|
||||
pub fn start() -> std::io::Result<Self> {
|
||||
let (sender, receiver) = mpsc::sync_channel::<Work>(32);
|
||||
let generation = Arc::new(AtomicU64::new(0));
|
||||
let current_generation = Arc::clone(&generation);
|
||||
let snapshot = Arc::new(Mutex::new(Snapshot {
|
||||
error: Some("MPRIS initializing".into()),
|
||||
..Snapshot::default()
|
||||
}));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let latest = Arc::clone(&snapshot);
|
||||
let cancelled = Arc::clone(&stop);
|
||||
let worker = thread::Builder::new().name("mpris".into()).spawn(move || {
|
||||
#[cfg(feature = "mpris")]
|
||||
let mut adapter = native::DbusAdapter::default();
|
||||
#[cfg(not(feature = "mpris"))]
|
||||
let mut adapter = Disabled;
|
||||
let mut command_error = None;
|
||||
while !cancelled.load(Ordering::Acquire) {
|
||||
let command = receiver.recv_timeout(Duration::from_millis(250));
|
||||
let is_command = command.is_ok();
|
||||
if cancelled.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
let result = match command {
|
||||
Ok(Work::Fence(done)) => {
|
||||
let _ = done.try_send(());
|
||||
continue;
|
||||
}
|
||||
Ok(Work::Action(command))
|
||||
if command.generation != current_generation.load(Ordering::Acquire) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Ok(Work::Action(command)) if Instant::now() <= command.expires => {
|
||||
execute_selected(&mut adapter, &command.selector, &command.action)
|
||||
}
|
||||
Ok(_) => Err("media command expired; press again".into()),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => adapter.discover(),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
};
|
||||
if let Ok(mut state) = latest.lock() {
|
||||
state.available |= adapter.available();
|
||||
match result {
|
||||
Ok(players) => {
|
||||
if is_command {
|
||||
command_error = None;
|
||||
}
|
||||
state.available = true;
|
||||
state.players = players;
|
||||
state.error = command_error.clone();
|
||||
}
|
||||
Err(error) => {
|
||||
if is_command {
|
||||
command_error = Some(error.clone());
|
||||
}
|
||||
// Do not retain stale observed states after any failed read/write.
|
||||
state.players.clear();
|
||||
state.error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Self {
|
||||
sender,
|
||||
generation,
|
||||
snapshot,
|
||||
stop,
|
||||
worker: Some(worker),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
self.snapshot
|
||||
.lock()
|
||||
.map(|s| s.clone())
|
||||
.unwrap_or_else(|_| Snapshot {
|
||||
error: Some("MPRIS state unavailable".into()),
|
||||
..Snapshot::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn command(&self, selector: PlayerSelector, action: Action) -> Result<(), String> {
|
||||
self.sender
|
||||
.try_send(Work::Action(Command {
|
||||
generation: self.generation.load(Ordering::Acquire),
|
||||
selector,
|
||||
action,
|
||||
expires: Instant::now() + Duration::from_secs(2),
|
||||
}))
|
||||
.map_err(|e| format!("MPRIS queue unavailable: {e}"))
|
||||
}
|
||||
|
||||
/// Invalidate queued work and drain the one in-flight call before changing
|
||||
/// profiles. A failed barrier must abort activation rather than race a write.
|
||||
pub fn fence(&self) -> Result<(), String> {
|
||||
self.generation.fetch_add(1, Ordering::AcqRel);
|
||||
let (done, wait) = mpsc::sync_channel(1);
|
||||
self.sender
|
||||
.try_send(Work::Fence(done))
|
||||
.map_err(|e| e.to_string())?;
|
||||
wait.recv_timeout(Duration::from_secs(10))
|
||||
.map_err(|e| format!("MPRIS drain failed: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MediaRuntime {
|
||||
fn drop(&mut self) {
|
||||
self.stop.store(true, Ordering::Release);
|
||||
if let Some(worker) = self.worker.take() {
|
||||
let _ = worker.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "mpris"))]
|
||||
struct Disabled;
|
||||
#[cfg(not(feature = "mpris"))]
|
||||
impl Adapter for Disabled {
|
||||
fn discover(&mut self) -> Result<Vec<Player>, String> {
|
||||
Err("MPRIS support not compiled in".into())
|
||||
}
|
||||
fn execute(&mut self, _: &Player, _: &Action) -> Result<(), String> {
|
||||
Err("MPRIS support not compiled in".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mpris")]
|
||||
mod native;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
struct Fake {
|
||||
players: Vec<Player>,
|
||||
calls: Vec<(String, Action)>,
|
||||
fail: bool,
|
||||
}
|
||||
impl Adapter for Fake {
|
||||
fn discover(&mut self) -> Result<Vec<Player>, String> {
|
||||
Ok(self.players.clone())
|
||||
}
|
||||
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String> {
|
||||
self.calls.push((player.owner.clone(), action.clone()));
|
||||
if self.fail {
|
||||
Err("timed out".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn targeted_commands_never_select_ambiguous_or_unsupported_players() {
|
||||
let selector = PlayerSelector {
|
||||
field: media::PlayerField::Identity,
|
||||
pattern: "QBZ".into(),
|
||||
regex: false,
|
||||
};
|
||||
let p = Player {
|
||||
identity: Some("QBZ".into()),
|
||||
owner: ":1.42".into(),
|
||||
can_control: true,
|
||||
can_play: true,
|
||||
..Player::default()
|
||||
};
|
||||
let mut adapter = Fake {
|
||||
players: vec![p.clone(), p.clone()],
|
||||
calls: vec![],
|
||||
fail: false,
|
||||
};
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_err());
|
||||
assert!(adapter.calls.is_empty());
|
||||
adapter.players.pop();
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Pause).is_err());
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_ok());
|
||||
assert_eq!(adapter.calls[0].0, ":1.42");
|
||||
adapter.fail = true;
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_err());
|
||||
assert_eq!(adapter.players[0].playback, None);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,601 @@
|
|||
use super::*;
|
||||
use dbus::{
|
||||
Path,
|
||||
arg::{PropMap, RefArg},
|
||||
blocking::{Connection, stdintf::org_freedesktop_dbus::Properties},
|
||||
};
|
||||
use media::{Playback, Playlist, Repeat};
|
||||
|
||||
const PLAYER: &str = "org.mpris.MediaPlayer2.Player";
|
||||
const ROOT: &str = "org.mpris.MediaPlayer2";
|
||||
const PLAYLISTS: &str = "org.mpris.MediaPlayer2.Playlists";
|
||||
const PATH: &str = "/org/mpris/MediaPlayer2";
|
||||
const TIMEOUT: Duration = Duration::from_millis(200);
|
||||
type WirePlaylist = (Path<'static>, String, String);
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct DbusAdapter {
|
||||
connection: Option<Connection>,
|
||||
}
|
||||
|
||||
fn text(properties: &PropMap, key: &str) -> Option<String> {
|
||||
properties
|
||||
.get(key)?
|
||||
.0
|
||||
.as_str()
|
||||
.map(|s| s.chars().filter(|c| !c.is_control()).take(1024).collect())
|
||||
}
|
||||
fn flag(properties: &PropMap, key: &str) -> Option<bool> {
|
||||
properties.get(key)?.0.as_u64().map(|value| value != 0)
|
||||
}
|
||||
|
||||
impl DbusAdapter {
|
||||
fn connection(&mut self) -> Result<&Connection, String> {
|
||||
if self.connection.is_none() {
|
||||
self.connection = Some(Connection::new_session().map_err(|e| e.to_string())?);
|
||||
}
|
||||
self.connection
|
||||
.as_ref()
|
||||
.ok_or_else(|| "session bus unavailable".into())
|
||||
}
|
||||
|
||||
fn read_player(
|
||||
connection: &Connection,
|
||||
bus_name: String,
|
||||
owner: String,
|
||||
) -> Result<Player, String> {
|
||||
let proxy = connection.with_proxy(owner.clone(), PATH, TIMEOUT);
|
||||
let root = proxy.get_all(ROOT).map_err(|e| e.to_string())?;
|
||||
let props = proxy.get_all(PLAYER).map_err(|e| e.to_string())?;
|
||||
let playback = match text(&props, "PlaybackStatus").as_deref() {
|
||||
Some("Playing") => Some(Playback::Playing),
|
||||
Some("Paused") => Some(Playback::Paused),
|
||||
Some("Stopped") => Some(Playback::Stopped),
|
||||
_ => None,
|
||||
};
|
||||
let repeat = match text(&props, "LoopStatus").as_deref() {
|
||||
Some("None") => Some(Repeat::None),
|
||||
Some("Track") => Some(Repeat::Track),
|
||||
Some("Playlist") => Some(Repeat::Playlist),
|
||||
_ => None,
|
||||
};
|
||||
let metadata: PropMap = proxy.get(PLAYER, "Metadata").unwrap_or_default();
|
||||
let duration_ms = metadata
|
||||
.get("mpris:length")
|
||||
.and_then(|v| v.0.as_i64())
|
||||
.and_then(|n| u64::try_from(n).ok())
|
||||
.map(|n| n / 1000);
|
||||
let position_ms = props
|
||||
.get("Position")
|
||||
.and_then(|v| v.0.as_i64())
|
||||
.and_then(|n| u64::try_from(n).ok())
|
||||
.map(|n| n / 1000);
|
||||
let track_id = text(&metadata, "mpris:trackid")
|
||||
.filter(|id| id != "/org/mpris/MediaPlayer2/TrackList/NoTrack");
|
||||
let mut playlists = Vec::new();
|
||||
let mut active_playlist = None;
|
||||
if let Ok(playlist_props) = proxy.get_all(PLAYLISTS) {
|
||||
let count = playlist_props
|
||||
.get("PlaylistCount")
|
||||
.and_then(|v| v.0.as_u64())
|
||||
.unwrap_or(0)
|
||||
.min(256) as u32;
|
||||
let orderings: Vec<String> = proxy.get(PLAYLISTS, "Orderings").unwrap_or_default();
|
||||
if let Some(order) = orderings.first() {
|
||||
let result: Result<(Vec<WirePlaylist>,), _> = proxy.method_call(
|
||||
PLAYLISTS,
|
||||
"GetPlaylists",
|
||||
(0u32, count, order.as_str(), false),
|
||||
);
|
||||
if let Ok((items,)) = result {
|
||||
playlists = items
|
||||
.into_iter()
|
||||
.take(256)
|
||||
.map(|(id, name, _)| Playlist {
|
||||
id: id.to_string(),
|
||||
name: name.chars().filter(|c| !c.is_control()).take(256).collect(),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
let active: Result<(bool, WirePlaylist), _> = proxy.get(PLAYLISTS, "ActivePlaylist");
|
||||
if let Ok((true, (id, _, _))) = active {
|
||||
active_playlist = Some(id.to_string());
|
||||
}
|
||||
}
|
||||
Ok(Player {
|
||||
bus_name,
|
||||
owner,
|
||||
identity: text(&root, "Identity"),
|
||||
desktop_entry: text(&root, "DesktopEntry"),
|
||||
playback,
|
||||
can_control: flag(&props, "CanControl").unwrap_or(false),
|
||||
can_play: flag(&props, "CanPlay").unwrap_or(false),
|
||||
can_pause: flag(&props, "CanPause").unwrap_or(false),
|
||||
can_next: flag(&props, "CanGoNext").unwrap_or(false),
|
||||
can_previous: flag(&props, "CanGoPrevious").unwrap_or(false),
|
||||
can_seek: flag(&props, "CanSeek").unwrap_or(false),
|
||||
position_ms,
|
||||
duration_ms,
|
||||
track_id,
|
||||
shuffle: flag(&props, "Shuffle"),
|
||||
repeat,
|
||||
playlists,
|
||||
active_playlist,
|
||||
error: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Adapter for DbusAdapter {
|
||||
fn available(&self) -> bool {
|
||||
self.connection.is_some()
|
||||
}
|
||||
|
||||
fn discover(&mut self) -> Result<Vec<Player>, String> {
|
||||
let connection = self.connection()?;
|
||||
let bus = connection.with_proxy("org.freedesktop.DBus", "/org/freedesktop/DBus", TIMEOUT);
|
||||
let names: Result<(Vec<String>,), _> =
|
||||
bus.method_call("org.freedesktop.DBus", "ListNames", ());
|
||||
let (names,) = match names {
|
||||
Ok(names) => names,
|
||||
Err(error) => {
|
||||
self.connection = None;
|
||||
return Err(error.to_string());
|
||||
}
|
||||
};
|
||||
let names = names
|
||||
.into_iter()
|
||||
.filter(|name| name.starts_with("org.mpris.MediaPlayer2."))
|
||||
.collect::<Vec<_>>();
|
||||
if names.len() > 32 {
|
||||
return Err("more than 32 MPRIS players; refusing incomplete discovery".into());
|
||||
}
|
||||
let started = Instant::now();
|
||||
let mut players = Vec::new();
|
||||
for name in names {
|
||||
if started.elapsed() > Duration::from_secs(2) {
|
||||
return Err("MPRIS discovery timed out".into());
|
||||
}
|
||||
let owner: Result<(String,), _> =
|
||||
bus.method_call("org.freedesktop.DBus", "GetNameOwner", (name.as_str(),));
|
||||
let Ok((owner,)) = owner else {
|
||||
continue;
|
||||
};
|
||||
match Self::read_player(connection, name.clone(), owner.clone()) {
|
||||
Ok(player) => players.push(player),
|
||||
Err(error) => players.push(Player {
|
||||
bus_name: name,
|
||||
owner,
|
||||
error: Some(error),
|
||||
..Player::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
#[derive(serde::Serialize)]
|
||||
struct DiscoverySize<'a> {
|
||||
players: &'a [Player],
|
||||
}
|
||||
if toml::to_string(&DiscoverySize { players: &players })
|
||||
.map_err(|e| e.to_string())?
|
||||
.len()
|
||||
> 256 * 1024
|
||||
{
|
||||
return Err("MPRIS discovery exceeds 256 KiB; refusing incomplete state".into());
|
||||
}
|
||||
Ok(players)
|
||||
}
|
||||
|
||||
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String> {
|
||||
let proxy = self
|
||||
.connection()?
|
||||
.with_proxy(player.owner.clone(), PATH, TIMEOUT);
|
||||
let result: Result<(), dbus::Error> = match action {
|
||||
Action::Play => proxy.method_call(PLAYER, "Play", ()),
|
||||
Action::Pause => proxy.method_call(PLAYER, "Pause", ()),
|
||||
Action::Stop => proxy.method_call(PLAYER, "Stop", ()),
|
||||
Action::PlayPause => proxy.method_call(PLAYER, "PlayPause", ()),
|
||||
Action::Next => proxy.method_call(PLAYER, "Next", ()),
|
||||
Action::Previous => proxy.method_call(PLAYER, "Previous", ()),
|
||||
Action::Seek { offset_ms } => {
|
||||
proxy.method_call(PLAYER, "Seek", (offset_ms.saturating_mul(1000),))
|
||||
}
|
||||
Action::SetPosition { position_ms } => {
|
||||
let track = player
|
||||
.track_id
|
||||
.as_deref()
|
||||
.ok_or("track identity unavailable")?;
|
||||
let path = Path::new(track).map_err(|e| e.to_string())?;
|
||||
let position = i64::try_from(*position_ms)
|
||||
.map_err(|e| e.to_string())?
|
||||
.saturating_mul(1000);
|
||||
proxy.method_call(PLAYER, "SetPosition", (path, position))
|
||||
}
|
||||
Action::Shuffle { enabled } => proxy.set(PLAYER, "Shuffle", *enabled),
|
||||
Action::ShuffleToggle => proxy.set(
|
||||
PLAYER,
|
||||
"Shuffle",
|
||||
!player.shuffle.ok_or("shuffle unavailable")?,
|
||||
),
|
||||
Action::Repeat { mode } => proxy.set(PLAYER, "LoopStatus", format!("{mode:?}")),
|
||||
Action::RepeatCycle => {
|
||||
let next = match player.repeat.ok_or("repeat unavailable")? {
|
||||
Repeat::None => "Track",
|
||||
Repeat::Track => "Playlist",
|
||||
Repeat::Playlist => "None",
|
||||
};
|
||||
proxy.set(PLAYER, "LoopStatus", next)
|
||||
}
|
||||
Action::Playlist { id } => proxy.method_call(
|
||||
PLAYLISTS,
|
||||
"ActivatePlaylist",
|
||||
(Path::new(id.clone()).map_err(|e| e.to_string())?,),
|
||||
),
|
||||
};
|
||||
result.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dbus::{
|
||||
arg::Variant,
|
||||
channel::{MatchingReceiver, Sender},
|
||||
message::MatchRule,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct ExtendedState {
|
||||
shuffle: bool,
|
||||
repeat: String,
|
||||
position: i64,
|
||||
active: bool,
|
||||
deny_seek: bool,
|
||||
silent: bool,
|
||||
calls: Vec<String>,
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
state: Arc<Mutex<ExtendedState>>,
|
||||
stop: Arc<AtomicBool>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn start() -> Self {
|
||||
let state = Arc::new(Mutex::new(ExtendedState {
|
||||
repeat: "None".into(),
|
||||
..ExtendedState::default()
|
||||
}));
|
||||
let owned = state.clone();
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let cancelled = stop.clone();
|
||||
let (ready, wait) = mpsc::sync_channel(1);
|
||||
let thread = thread::spawn(move || {
|
||||
let connection = Connection::new_session().unwrap();
|
||||
connection
|
||||
.request_name(
|
||||
"org.mpris.MediaPlayer2.extended_fixture",
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
connection.start_receive(
|
||||
MatchRule::new_method_call(),
|
||||
Box::new(move |message, connection| {
|
||||
let mut state = owned.lock().unwrap();
|
||||
if state.silent {
|
||||
return true;
|
||||
}
|
||||
let member = message.member().unwrap().to_string();
|
||||
let mut reply = message.method_return();
|
||||
let playlist = || {
|
||||
(
|
||||
Path::new("/playlist/one").unwrap(),
|
||||
"Favorites".to_owned(),
|
||||
String::new(),
|
||||
)
|
||||
};
|
||||
match member.as_str() {
|
||||
"GetAll" => {
|
||||
let interface: String = message.read1().unwrap();
|
||||
let mut props = PropMap::new();
|
||||
if interface == ROOT {
|
||||
props.insert(
|
||||
"Identity".into(),
|
||||
Variant(Box::new("Extended fixture".to_owned())),
|
||||
);
|
||||
props.insert(
|
||||
"DesktopEntry".into(),
|
||||
Variant(Box::new("extended_fixture".to_owned())),
|
||||
);
|
||||
} else if interface == PLAYER {
|
||||
props.insert(
|
||||
"PlaybackStatus".into(),
|
||||
Variant(Box::new("Paused".to_owned())),
|
||||
);
|
||||
props
|
||||
.insert("Shuffle".into(), Variant(Box::new(state.shuffle)));
|
||||
props.insert(
|
||||
"LoopStatus".into(),
|
||||
Variant(Box::new(state.repeat.clone())),
|
||||
);
|
||||
props.insert(
|
||||
"Position".into(),
|
||||
Variant(Box::new(state.position)),
|
||||
);
|
||||
for key in [
|
||||
"CanControl",
|
||||
"CanPlay",
|
||||
"CanPause",
|
||||
"CanGoNext",
|
||||
"CanGoPrevious",
|
||||
] {
|
||||
props.insert(key.into(), Variant(Box::new(true)));
|
||||
}
|
||||
props.insert(
|
||||
"CanSeek".into(),
|
||||
Variant(Box::new(!state.deny_seek)),
|
||||
);
|
||||
} else if interface == PLAYLISTS {
|
||||
props.insert("PlaylistCount".into(), Variant(Box::new(1u32)));
|
||||
}
|
||||
reply = reply.append1(props);
|
||||
}
|
||||
"Get" => {
|
||||
let (_, property): (String, String) = message.read2().unwrap();
|
||||
reply = match property.as_str() {
|
||||
"Metadata" => {
|
||||
let mut metadata = PropMap::new();
|
||||
metadata.insert(
|
||||
"mpris:trackid".into(),
|
||||
Variant(Box::new(Path::new("/track/one").unwrap())),
|
||||
);
|
||||
metadata.insert(
|
||||
"mpris:length".into(),
|
||||
Variant(Box::new(300_000_000i64)),
|
||||
);
|
||||
reply.append1(Variant(metadata))
|
||||
}
|
||||
"Orderings" => {
|
||||
reply.append1(Variant(vec!["Alphabetical".to_owned()]))
|
||||
}
|
||||
"ActivePlaylist" => {
|
||||
reply.append1(Variant((state.active, playlist())))
|
||||
}
|
||||
_ => panic!("unexpected property {property}"),
|
||||
};
|
||||
}
|
||||
"GetPlaylists" => {
|
||||
let (start, count, order, reverse): (u32, u32, String, bool) =
|
||||
message.read4().unwrap();
|
||||
assert_eq!(
|
||||
(start, count, order.as_str(), reverse),
|
||||
(0, 1, "Alphabetical", false)
|
||||
);
|
||||
reply = reply.append1(vec![playlist()]);
|
||||
}
|
||||
"Set" => {
|
||||
let (_, property): (String, String) = message.read2().unwrap();
|
||||
if property == "Shuffle" {
|
||||
let (_, _, value): (String, String, Variant<bool>) =
|
||||
message.read3().unwrap();
|
||||
state.shuffle = value.0;
|
||||
} else {
|
||||
let (_, _, value): (String, String, Variant<String>) =
|
||||
message.read3().unwrap();
|
||||
state.repeat = value.0;
|
||||
}
|
||||
state.calls.push(property);
|
||||
}
|
||||
"Seek" => {
|
||||
let offset: i64 = message.read1().unwrap();
|
||||
state.position += offset;
|
||||
state.calls.push(member);
|
||||
}
|
||||
"SetPosition" => {
|
||||
let (track, position): (Path<'static>, i64) =
|
||||
message.read2().unwrap();
|
||||
assert_eq!(track.to_string(), "/track/one");
|
||||
state.position = position;
|
||||
state.calls.push(member);
|
||||
}
|
||||
"ActivatePlaylist" => {
|
||||
let id: Path<'static> = message.read1().unwrap();
|
||||
assert_eq!(id.to_string(), "/playlist/one");
|
||||
state.active = true;
|
||||
state.calls.push(member);
|
||||
}
|
||||
_ => state.calls.push(member),
|
||||
}
|
||||
connection.send(reply).unwrap();
|
||||
true
|
||||
}),
|
||||
);
|
||||
ready.send(()).unwrap();
|
||||
while !cancelled.load(Ordering::Acquire) {
|
||||
connection.process(Duration::from_millis(10)).unwrap();
|
||||
}
|
||||
});
|
||||
wait.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||
Self {
|
||||
state,
|
||||
stop,
|
||||
thread: Some(thread),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
self.stop.store(true, Ordering::Release);
|
||||
if let Some(thread) = self.thread.take() {
|
||||
thread.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "run inside dbus-run-session; fake player only"]
|
||||
fn private_bus_extended_controls_capabilities_timeouts_and_owner_changes() {
|
||||
let fixture = Fixture::start();
|
||||
let mut adapter = DbusAdapter::default();
|
||||
let selector = PlayerSelector {
|
||||
field: media::PlayerField::BusName,
|
||||
pattern: "org.mpris.MediaPlayer2.extended_fixture".into(),
|
||||
regex: false,
|
||||
};
|
||||
let matcher = selector.compile().unwrap();
|
||||
let initial = adapter.discover().unwrap();
|
||||
let player = matcher.resolve(&initial).unwrap().clone();
|
||||
assert_eq!(player.duration_ms, Some(300_000));
|
||||
assert_eq!(player.playlists[0].name, "Favorites");
|
||||
for action in [
|
||||
Action::Seek { offset_ms: 5000 },
|
||||
Action::Seek { offset_ms: -2000 },
|
||||
Action::SetPosition { position_ms: 12000 },
|
||||
Action::ShuffleToggle,
|
||||
Action::RepeatCycle,
|
||||
Action::Playlist {
|
||||
id: "/playlist/one".into(),
|
||||
},
|
||||
Action::Next,
|
||||
Action::Previous,
|
||||
] {
|
||||
execute_selected(&mut adapter, &selector, &action).unwrap();
|
||||
}
|
||||
let observed = adapter.discover().unwrap();
|
||||
let observed = matcher.resolve(&observed).unwrap();
|
||||
assert_eq!(observed.position_ms, Some(12000));
|
||||
assert_eq!(observed.shuffle, Some(true));
|
||||
assert_eq!(observed.repeat, Some(Repeat::Track));
|
||||
assert_eq!(observed.active_playlist.as_deref(), Some("/playlist/one"));
|
||||
assert!(Action::ShuffleToggle.feedback(Some(observed)));
|
||||
fixture.state.lock().unwrap().deny_seek = true;
|
||||
let count = fixture.state.lock().unwrap().calls.len();
|
||||
assert!(
|
||||
execute_selected(&mut adapter, &selector, &Action::Seek { offset_ms: 10 }).is_err()
|
||||
);
|
||||
assert_eq!(fixture.state.lock().unwrap().calls.len(), count);
|
||||
fixture.state.lock().unwrap().silent = true;
|
||||
let started = Instant::now();
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_err());
|
||||
assert!(adapter.available()); // A broken player does not mean D-Bus support is absent.
|
||||
assert!(started.elapsed() < Duration::from_secs(3));
|
||||
fixture.state.lock().unwrap().silent = false;
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_ok());
|
||||
drop(fixture);
|
||||
assert!(matcher.resolve(&adapter.discover().unwrap()).is_err());
|
||||
let replacement = Fixture::start();
|
||||
let current = adapter.discover().unwrap();
|
||||
assert_ne!(matcher.resolve(¤t).unwrap().owner, player.owner);
|
||||
assert!(adapter.execute(&player, &Action::Play).is_err()); // Never retarget an old owner.
|
||||
assert!(replacement.state.lock().unwrap().calls.is_empty());
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "run inside dbus-run-session; uses only a fake player"]
|
||||
fn private_bus_discovers_paused_player_and_confirms_play() {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let worker_stop = Arc::clone(&stop);
|
||||
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
|
||||
let worker = thread::spawn(move || {
|
||||
let connection = Connection::new_session().unwrap();
|
||||
connection
|
||||
.request_name("org.mpris.MediaPlayer2.fader_fixture", false, true, false)
|
||||
.unwrap();
|
||||
let playing = Arc::new(AtomicBool::new(false));
|
||||
connection.start_receive(
|
||||
MatchRule::new_method_call(),
|
||||
Box::new(move |message, connection| {
|
||||
let reply = message.method_return();
|
||||
let member = message.member().map(|m| m.to_string()).unwrap_or_default();
|
||||
let interface = message
|
||||
.interface()
|
||||
.map(|m| m.to_string())
|
||||
.unwrap_or_default();
|
||||
let reply = if member == "GetAll" {
|
||||
let requested: String = message.read1().unwrap();
|
||||
let mut props: PropMap = PropMap::new();
|
||||
if requested == ROOT {
|
||||
props
|
||||
.insert("Identity".into(), Variant(Box::new("Fixture".to_owned())));
|
||||
}
|
||||
if requested == PLAYER {
|
||||
props.insert(
|
||||
"PlaybackStatus".into(),
|
||||
Variant(Box::new(
|
||||
if playing.load(Ordering::Relaxed) {
|
||||
"Playing"
|
||||
} else {
|
||||
"Paused"
|
||||
}
|
||||
.to_owned(),
|
||||
)),
|
||||
);
|
||||
for name in ["CanControl", "CanPlay", "CanPause"] {
|
||||
props.insert(name.into(), Variant(Box::new(true)));
|
||||
}
|
||||
}
|
||||
reply.append1(props)
|
||||
} else if member == "Get" {
|
||||
let (_, name): (String, String) = message.read2().unwrap();
|
||||
if name == "Metadata" {
|
||||
reply.append1(Variant(PropMap::new()))
|
||||
} else if name == "Orderings" {
|
||||
reply.append1(Variant(Vec::<String>::new()))
|
||||
} else {
|
||||
reply.append1(Variant((
|
||||
false,
|
||||
(Path::new("/").unwrap(), String::new(), String::new()),
|
||||
)))
|
||||
}
|
||||
} else {
|
||||
if interface == PLAYER && member == "Play" {
|
||||
playing.store(true, Ordering::Relaxed);
|
||||
}
|
||||
reply
|
||||
};
|
||||
connection.send(reply).unwrap();
|
||||
true
|
||||
}),
|
||||
);
|
||||
ready_tx.send(()).unwrap();
|
||||
while !worker_stop.load(Ordering::Acquire) {
|
||||
connection.process(Duration::from_millis(10)).unwrap();
|
||||
}
|
||||
});
|
||||
ready_rx.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||
let mut adapter = DbusAdapter::default();
|
||||
let selector = PlayerSelector {
|
||||
field: media::PlayerField::BusName,
|
||||
pattern: "org.mpris.MediaPlayer2.fader_fixture".into(),
|
||||
regex: false,
|
||||
};
|
||||
let before = adapter.discover();
|
||||
let after = execute_selected(&mut adapter, &selector, &Action::Play);
|
||||
stop.store(true, Ordering::Release);
|
||||
worker.join().unwrap();
|
||||
assert_eq!(
|
||||
selector
|
||||
.compile()
|
||||
.unwrap()
|
||||
.resolve(&before.unwrap())
|
||||
.unwrap()
|
||||
.playback,
|
||||
Some(Playback::Paused)
|
||||
);
|
||||
assert_eq!(
|
||||
selector
|
||||
.compile()
|
||||
.unwrap()
|
||||
.resolve(&after.unwrap())
|
||||
.unwrap()
|
||||
.playback,
|
||||
Some(Playback::Playing)
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,634 @@
|
|||
use std::{io, path::PathBuf};
|
||||
|
||||
use tui::{
|
||||
ConfigurationEdit as TuiConfigurationEdit, MixerClient, MixerItem, MixerObjectId,
|
||||
MixerObjectKind, MixerSnapshot, PickupStatus as TuiPickupStatus,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
ipc::{
|
||||
ClientRequest, MixerObjectKey, MixerObjectKind as IpcObjectKind, PROTOCOL_VERSION,
|
||||
RequestCommand, ResponseResult,
|
||||
},
|
||||
local::client_request,
|
||||
};
|
||||
|
||||
/// Short-lived request client used by the refresh-driven terminal UI.
|
||||
pub struct IpcMixerClient {
|
||||
socket: PathBuf,
|
||||
next_request: u64,
|
||||
}
|
||||
|
||||
impl IpcMixerClient {
|
||||
#[must_use]
|
||||
pub fn new(socket: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
socket: socket.into(),
|
||||
next_request: 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&mut self, command: RequestCommand) -> io::Result<MixerSnapshot> {
|
||||
let request_id = self.next_request;
|
||||
self.next_request = self
|
||||
.next_request
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| io::Error::other("TUI request counter exhausted"))?;
|
||||
let response = client_request(
|
||||
&self.socket,
|
||||
&ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id,
|
||||
command,
|
||||
},
|
||||
)
|
||||
.map_err(io::Error::other)?;
|
||||
match response.result {
|
||||
ResponseResult::Snapshot { snapshot } => Ok(MixerSnapshot {
|
||||
revision: snapshot.revision,
|
||||
backend: snapshot.backend,
|
||||
status: snapshot.status,
|
||||
error: None,
|
||||
items: snapshot
|
||||
.objects
|
||||
.into_iter()
|
||||
.map(|object| MixerItem {
|
||||
id: MixerObjectId {
|
||||
kind: match object.object.kind {
|
||||
IpcObjectKind::Application => MixerObjectKind::Application,
|
||||
IpcObjectKind::Group => MixerObjectKind::Group,
|
||||
IpcObjectKind::Output => MixerObjectKind::Output,
|
||||
},
|
||||
id: object.object.id,
|
||||
},
|
||||
label: object.label,
|
||||
detail: object.detail,
|
||||
gain: object.gain,
|
||||
gain_mixed: object.gain_mixed,
|
||||
muted: object.muted,
|
||||
mute_mixed: object.mute_mixed,
|
||||
pending: object.pending,
|
||||
pickup: object.pickup.map(|pickup| match pickup {
|
||||
crate::ipc::PickupStatus::Unavailable => TuiPickupStatus::Unavailable,
|
||||
crate::ipc::PickupStatus::Waiting => TuiPickupStatus::Waiting,
|
||||
crate::ipc::PickupStatus::Tracking => TuiPickupStatus::Tracking,
|
||||
crate::ipc::PickupStatus::Mixed => TuiPickupStatus::Mixed,
|
||||
}),
|
||||
writable: object.writable,
|
||||
error: object.error,
|
||||
})
|
||||
.collect(),
|
||||
devices: snapshot
|
||||
.devices
|
||||
.into_iter()
|
||||
.map(|device| tui::MidiDevice {
|
||||
id: device.id,
|
||||
label: device.label,
|
||||
status: device.status,
|
||||
backend_id: device.backend_id,
|
||||
error: device.error,
|
||||
})
|
||||
.collect(),
|
||||
discovered_midi_ports: snapshot
|
||||
.discovered_midi_ports
|
||||
.into_iter()
|
||||
.map(|port| tui::DiscoveredMidiPort {
|
||||
backend_id: port.backend_id,
|
||||
name: port.name,
|
||||
usb_vendor_id: port.usb_vendor_id,
|
||||
usb_product_id: port.usb_product_id,
|
||||
usb_serial: port.usb_serial,
|
||||
usb_path: port.usb_path,
|
||||
})
|
||||
.collect(),
|
||||
configuration: tui::ConfigurationSnapshot {
|
||||
feedback_disabled: snapshot.configuration.feedback_disabled,
|
||||
disabled_feedback_faders: snapshot.configuration.disabled_feedback_faders,
|
||||
revision: snapshot.configuration.revision,
|
||||
dirty: snapshot.configuration.dirty,
|
||||
applied_revision: snapshot.configuration.applied_revision,
|
||||
selection_saved: snapshot.configuration.selection_saved,
|
||||
learning: snapshot.configuration.learning,
|
||||
error: snapshot.configuration.error,
|
||||
profile_id: snapshot.configuration.profile_id,
|
||||
profile_path: snapshot.configuration.profile_path,
|
||||
stream_metadata: snapshot.configuration.stream_metadata,
|
||||
media_entries: snapshot.configuration.media_entries,
|
||||
media_state: snapshot.configuration.media_state,
|
||||
available_profiles: snapshot.configuration.available_profiles,
|
||||
mixer_orientation: match snapshot.configuration.mixer_orientation {
|
||||
crate::ipc::MixerOrientation::Vertical => tui::MixerOrientation::Vertical,
|
||||
crate::ipc::MixerOrientation::Horizontal => {
|
||||
tui::MixerOrientation::Horizontal
|
||||
}
|
||||
},
|
||||
status_display: match snapshot.configuration.status_display {
|
||||
crate::ipc::StatusDisplayMode::Detailed => tui::StatusDisplayMode::Detailed,
|
||||
crate::ipc::StatusDisplayMode::Compact => tui::StatusDisplayMode::Compact,
|
||||
crate::ipc::StatusDisplayMode::Symbol => tui::StatusDisplayMode::Symbol,
|
||||
crate::ipc::StatusDisplayMode::Color => tui::StatusDisplayMode::Color,
|
||||
crate::ipc::StatusDisplayMode::Hidden => tui::StatusDisplayMode::Hidden,
|
||||
},
|
||||
default_controller: snapshot.configuration.default_controller,
|
||||
theme: tui::ThemeName::from_config_name(&snapshot.configuration.theme)
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"server returned unknown theme {:?}",
|
||||
snapshot.configuration.theme
|
||||
),
|
||||
)
|
||||
})?,
|
||||
surfaces: snapshot
|
||||
.configuration
|
||||
.surfaces
|
||||
.into_iter()
|
||||
.map(|surface| tui::ConfiguredSurface {
|
||||
id: surface.id,
|
||||
label: surface.label,
|
||||
})
|
||||
.collect(),
|
||||
applications: snapshot
|
||||
.configuration
|
||||
.applications
|
||||
.into_iter()
|
||||
.map(|application| tui::ConfiguredApplication {
|
||||
id: application.id,
|
||||
label: application.label,
|
||||
match_all: application.match_all,
|
||||
selectors: application
|
||||
.selectors
|
||||
.into_iter()
|
||||
.map(|selector| tui::ConfiguredSelector {
|
||||
field: selector.field,
|
||||
pattern: selector.pattern,
|
||||
regex: selector.regex,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect(),
|
||||
groups: snapshot
|
||||
.configuration
|
||||
.groups
|
||||
.into_iter()
|
||||
.map(|group| tui::ConfiguredGroup {
|
||||
id: group.id,
|
||||
label: group.label,
|
||||
members: group.members,
|
||||
volume_mode: match group.volume_mode {
|
||||
crate::ipc::GroupVolumeMode::Absolute => {
|
||||
tui::GroupVolumeMode::Absolute
|
||||
}
|
||||
crate::ipc::GroupVolumeMode::Relative => {
|
||||
tui::GroupVolumeMode::Relative
|
||||
}
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
faders: snapshot
|
||||
.configuration
|
||||
.faders
|
||||
.into_iter()
|
||||
.map(|fader| tui::ConfiguredFader {
|
||||
id: fader.id,
|
||||
target: MixerObjectId {
|
||||
kind: match fader.target.kind {
|
||||
IpcObjectKind::Application => MixerObjectKind::Application,
|
||||
IpcObjectKind::Group => MixerObjectKind::Group,
|
||||
IpcObjectKind::Output => MixerObjectKind::Output,
|
||||
},
|
||||
id: fader.target.id,
|
||||
},
|
||||
pickup: fader.pickup,
|
||||
pickup_tolerance: fader.pickup_tolerance,
|
||||
})
|
||||
.collect(),
|
||||
mixer_layout: snapshot
|
||||
.configuration
|
||||
.mixer_layout
|
||||
.into_iter()
|
||||
.map(|entry| match entry {
|
||||
crate::ipc::MixerLayoutEntry::Fader {
|
||||
fader,
|
||||
hidden,
|
||||
density,
|
||||
} => tui::MixerLayoutEntry::Fader {
|
||||
fader,
|
||||
hidden,
|
||||
density: match density {
|
||||
crate::ipc::FaderDensity::Slim => tui::FaderDensity::Slim,
|
||||
crate::ipc::FaderDensity::BorderedSlim => {
|
||||
tui::FaderDensity::BorderedSlim
|
||||
}
|
||||
crate::ipc::FaderDensity::Standard => {
|
||||
tui::FaderDensity::Standard
|
||||
}
|
||||
crate::ipc::FaderDensity::Thick => tui::FaderDensity::Thick,
|
||||
},
|
||||
},
|
||||
crate::ipc::MixerLayoutEntry::Separator {
|
||||
id,
|
||||
label,
|
||||
size,
|
||||
decoration,
|
||||
} => tui::MixerLayoutEntry::Separator {
|
||||
id,
|
||||
label,
|
||||
size: match size {
|
||||
crate::ipc::SeparatorSize::Slim => tui::SeparatorSize::Slim,
|
||||
crate::ipc::SeparatorSize::Standard => {
|
||||
tui::SeparatorSize::Standard
|
||||
}
|
||||
crate::ipc::SeparatorSize::Thick => tui::SeparatorSize::Thick,
|
||||
crate::ipc::SeparatorSize::Fill => tui::SeparatorSize::Fill,
|
||||
},
|
||||
decoration: match decoration {
|
||||
crate::ipc::SeparatorDecoration::Plain => {
|
||||
tui::SeparatorDecoration::Plain
|
||||
}
|
||||
crate::ipc::SeparatorDecoration::Line => {
|
||||
tui::SeparatorDecoration::Line
|
||||
}
|
||||
crate::ipc::SeparatorDecoration::Double => {
|
||||
tui::SeparatorDecoration::Double
|
||||
}
|
||||
crate::ipc::SeparatorDecoration::Box => {
|
||||
tui::SeparatorDecoration::Box
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
bindings: snapshot
|
||||
.configuration
|
||||
.bindings
|
||||
.into_iter()
|
||||
.map(|binding| tui::ConfiguredBinding {
|
||||
surface: binding.surface,
|
||||
fader: binding.fader,
|
||||
action: binding.action,
|
||||
message: binding.message,
|
||||
kind: binding.kind,
|
||||
channel: binding.channel,
|
||||
number: binding.number,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
}),
|
||||
ResponseResult::Error { message, .. } => {
|
||||
let kind = if message.contains("stale revision")
|
||||
|| message.contains("stale configuration revision")
|
||||
{
|
||||
io::ErrorKind::InvalidData
|
||||
} else {
|
||||
io::ErrorKind::Other
|
||||
};
|
||||
Err(io::Error::new(kind, message))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MixerClient for IpcMixerClient {
|
||||
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::Snapshot)
|
||||
}
|
||||
|
||||
fn set_volume(
|
||||
&mut self,
|
||||
id: MixerObjectId,
|
||||
gain: f64,
|
||||
expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::SetVolume {
|
||||
object: key(id),
|
||||
gain,
|
||||
expected_revision,
|
||||
})
|
||||
}
|
||||
|
||||
fn toggle_mute(
|
||||
&mut self,
|
||||
id: MixerObjectId,
|
||||
expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::ToggleMute {
|
||||
object: key(id),
|
||||
expected_revision,
|
||||
})
|
||||
}
|
||||
|
||||
fn edit_configuration(
|
||||
&mut self,
|
||||
edit: TuiConfigurationEdit,
|
||||
expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::EditConfiguration {
|
||||
expected_revision,
|
||||
edit: configuration_edit(edit),
|
||||
})
|
||||
}
|
||||
|
||||
fn media_action(&mut self, entry: String, control: String) -> io::Result<tui::MixerSnapshot> {
|
||||
self.send(RequestCommand::MediaAction { entry, control })
|
||||
}
|
||||
|
||||
fn start_media_learn(
|
||||
&mut self,
|
||||
surface: String,
|
||||
entry: String,
|
||||
control: String,
|
||||
) -> io::Result<tui::MixerSnapshot> {
|
||||
self.send(RequestCommand::StartMediaLearn {
|
||||
surface,
|
||||
entry,
|
||||
control,
|
||||
})
|
||||
}
|
||||
|
||||
fn start_midi_learn(
|
||||
&mut self,
|
||||
surface: String,
|
||||
fader: String,
|
||||
action: String,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::StartMidiLearn {
|
||||
surface,
|
||||
fader,
|
||||
action,
|
||||
})
|
||||
}
|
||||
|
||||
fn cancel_midi_learn(&mut self) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::CancelMidiLearn)
|
||||
}
|
||||
|
||||
fn save_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::SaveConfiguration { expected_revision })
|
||||
}
|
||||
|
||||
fn reset_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::ResetConfiguration { expected_revision })
|
||||
}
|
||||
|
||||
fn switch_profile(&mut self, id: String) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::SwitchProfile { id, restore: false })
|
||||
}
|
||||
}
|
||||
|
||||
fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEdit {
|
||||
use crate::ipc::ConfigurationEdit as IpcEdit;
|
||||
match edit {
|
||||
TuiConfigurationEdit::AddApplicationFader {
|
||||
application_id,
|
||||
label,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
fader_id,
|
||||
position,
|
||||
} => IpcEdit::AddApplicationFader {
|
||||
application_id,
|
||||
label,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
fader_id,
|
||||
position,
|
||||
},
|
||||
TuiConfigurationEdit::AddGroupFader {
|
||||
group_id,
|
||||
label,
|
||||
fader_id,
|
||||
position,
|
||||
} => IpcEdit::AddGroupFader {
|
||||
group_id,
|
||||
label,
|
||||
fader_id,
|
||||
position,
|
||||
},
|
||||
TuiConfigurationEdit::RemoveMixerFader { id } => IpcEdit::RemoveMixerFader { id },
|
||||
TuiConfigurationEdit::SetTargetLabel { target, label } => IpcEdit::SetTargetLabel {
|
||||
target: key(target),
|
||||
label,
|
||||
},
|
||||
TuiConfigurationEdit::AddSurface {
|
||||
id,
|
||||
label,
|
||||
input_port,
|
||||
output_port,
|
||||
usb_vendor_id,
|
||||
usb_product_id,
|
||||
usb_serial,
|
||||
usb_path,
|
||||
manual_backend_id,
|
||||
} => IpcEdit::AddSurface {
|
||||
id,
|
||||
label,
|
||||
input_port,
|
||||
output_port,
|
||||
usb_vendor_id,
|
||||
usb_product_id,
|
||||
usb_serial,
|
||||
usb_path,
|
||||
manual_backend_id,
|
||||
},
|
||||
TuiConfigurationEdit::RemoveSurface { id } => IpcEdit::RemoveSurface { id },
|
||||
TuiConfigurationEdit::Application {
|
||||
existing,
|
||||
id,
|
||||
label,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
} => {
|
||||
if existing {
|
||||
IpcEdit::SetApplication {
|
||||
id,
|
||||
label,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
}
|
||||
} else {
|
||||
IpcEdit::AddApplication {
|
||||
id,
|
||||
label,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
}
|
||||
}
|
||||
}
|
||||
TuiConfigurationEdit::Group {
|
||||
existing,
|
||||
id,
|
||||
label,
|
||||
members,
|
||||
} => {
|
||||
if existing {
|
||||
IpcEdit::SetGroup { id, label, members }
|
||||
} else {
|
||||
IpcEdit::AddGroup { id, label, members }
|
||||
}
|
||||
}
|
||||
TuiConfigurationEdit::Fader {
|
||||
existing,
|
||||
id,
|
||||
target,
|
||||
pickup,
|
||||
pickup_tolerance,
|
||||
} => {
|
||||
let target = key(target);
|
||||
if existing {
|
||||
IpcEdit::SetFader {
|
||||
id,
|
||||
target,
|
||||
pickup,
|
||||
pickup_tolerance,
|
||||
}
|
||||
} else {
|
||||
IpcEdit::AddFader {
|
||||
id,
|
||||
target,
|
||||
pickup,
|
||||
pickup_tolerance,
|
||||
}
|
||||
}
|
||||
}
|
||||
TuiConfigurationEdit::Remove { kind, id } => match kind.as_str() {
|
||||
"application" => IpcEdit::RemoveApplication { id },
|
||||
"group" => IpcEdit::RemoveGroup { id },
|
||||
"fader" => IpcEdit::RemoveFader { id },
|
||||
_ => IpcEdit::RemoveApplication { id },
|
||||
},
|
||||
TuiConfigurationEdit::MoveLayoutEntry { id, position } => {
|
||||
IpcEdit::MoveLayoutEntry { id, position }
|
||||
}
|
||||
TuiConfigurationEdit::SetFaderHidden { id, hidden } => {
|
||||
IpcEdit::SetFaderHidden { id, hidden }
|
||||
}
|
||||
TuiConfigurationEdit::SetFaderDensity { id, density } => IpcEdit::SetFaderDensity {
|
||||
id,
|
||||
density: match density {
|
||||
tui::FaderDensity::Slim => crate::ipc::FaderDensity::Slim,
|
||||
tui::FaderDensity::BorderedSlim => crate::ipc::FaderDensity::BorderedSlim,
|
||||
tui::FaderDensity::Standard => crate::ipc::FaderDensity::Standard,
|
||||
tui::FaderDensity::Thick => crate::ipc::FaderDensity::Thick,
|
||||
},
|
||||
},
|
||||
TuiConfigurationEdit::SetMixerOrientation { orientation } => IpcEdit::SetMixerOrientation {
|
||||
orientation: match orientation {
|
||||
tui::MixerOrientation::Vertical => crate::ipc::MixerOrientation::Vertical,
|
||||
tui::MixerOrientation::Horizontal => crate::ipc::MixerOrientation::Horizontal,
|
||||
},
|
||||
},
|
||||
TuiConfigurationEdit::SetStatusDisplay { mode } => IpcEdit::SetStatusDisplay {
|
||||
mode: match mode {
|
||||
tui::StatusDisplayMode::Detailed => crate::ipc::StatusDisplayMode::Detailed,
|
||||
tui::StatusDisplayMode::Compact => crate::ipc::StatusDisplayMode::Compact,
|
||||
tui::StatusDisplayMode::Symbol => crate::ipc::StatusDisplayMode::Symbol,
|
||||
tui::StatusDisplayMode::Color => crate::ipc::StatusDisplayMode::Color,
|
||||
tui::StatusDisplayMode::Hidden => crate::ipc::StatusDisplayMode::Hidden,
|
||||
},
|
||||
},
|
||||
TuiConfigurationEdit::SetDefaultController { surface } => {
|
||||
IpcEdit::SetDefaultController { surface }
|
||||
}
|
||||
TuiConfigurationEdit::SetTheme { theme } => IpcEdit::SetTheme {
|
||||
theme: theme.config_name().to_owned(),
|
||||
},
|
||||
TuiConfigurationEdit::AddSeparator {
|
||||
id,
|
||||
label,
|
||||
position,
|
||||
} => IpcEdit::AddSeparator {
|
||||
id,
|
||||
label,
|
||||
position,
|
||||
},
|
||||
TuiConfigurationEdit::SetSeparatorLabel { id, label } => {
|
||||
IpcEdit::SetSeparatorLabel { id, label }
|
||||
}
|
||||
TuiConfigurationEdit::RemoveSeparator { id } => IpcEdit::RemoveSeparator { id },
|
||||
TuiConfigurationEdit::SetSeparatorPresentation {
|
||||
id,
|
||||
size,
|
||||
decoration,
|
||||
} => IpcEdit::SetSeparatorPresentation {
|
||||
id,
|
||||
size: match size {
|
||||
tui::SeparatorSize::Slim => crate::ipc::SeparatorSize::Slim,
|
||||
tui::SeparatorSize::Standard => crate::ipc::SeparatorSize::Standard,
|
||||
tui::SeparatorSize::Thick => crate::ipc::SeparatorSize::Thick,
|
||||
tui::SeparatorSize::Fill => crate::ipc::SeparatorSize::Fill,
|
||||
},
|
||||
decoration: match decoration {
|
||||
tui::SeparatorDecoration::Plain => crate::ipc::SeparatorDecoration::Plain,
|
||||
tui::SeparatorDecoration::Line => crate::ipc::SeparatorDecoration::Line,
|
||||
tui::SeparatorDecoration::Double => crate::ipc::SeparatorDecoration::Double,
|
||||
tui::SeparatorDecoration::Box => crate::ipc::SeparatorDecoration::Box,
|
||||
},
|
||||
},
|
||||
TuiConfigurationEdit::SetFeedbackEnabled { fader, enabled } => {
|
||||
IpcEdit::SetFeedbackEnabled { fader, enabled }
|
||||
}
|
||||
TuiConfigurationEdit::SetMediaEntry { entry } => IpcEdit::SetMediaEntry { entry },
|
||||
TuiConfigurationEdit::RemoveMediaEntry { id } => IpcEdit::RemoveMediaEntry { id },
|
||||
TuiConfigurationEdit::SetMediaBinding {
|
||||
entry,
|
||||
control,
|
||||
binding,
|
||||
} => IpcEdit::SetMediaBinding {
|
||||
entry,
|
||||
control,
|
||||
binding,
|
||||
},
|
||||
TuiConfigurationEdit::SetApplicationSelectorMode { id, match_all } => {
|
||||
IpcEdit::SetApplicationSelectorMode { id, match_all }
|
||||
}
|
||||
TuiConfigurationEdit::SetApplicationSelector {
|
||||
id,
|
||||
index,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
} => IpcEdit::SetApplicationSelector {
|
||||
id,
|
||||
index,
|
||||
field,
|
||||
pattern,
|
||||
regex,
|
||||
},
|
||||
TuiConfigurationEdit::SetBinding {
|
||||
surface,
|
||||
fader,
|
||||
action,
|
||||
kind,
|
||||
channel,
|
||||
number,
|
||||
} => IpcEdit::SetBinding {
|
||||
surface,
|
||||
fader,
|
||||
action,
|
||||
kind,
|
||||
channel,
|
||||
number,
|
||||
},
|
||||
TuiConfigurationEdit::RemoveBinding { fader, action } => {
|
||||
IpcEdit::RemoveBinding { fader, action }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key(id: MixerObjectId) -> MixerObjectKey {
|
||||
MixerObjectKey {
|
||||
kind: match id.kind {
|
||||
MixerObjectKind::Application => IpcObjectKind::Application,
|
||||
MixerObjectKind::Group => IpcObjectKind::Group,
|
||||
MixerObjectKind::Output => IpcObjectKind::Output,
|
||||
},
|
||||
id: id.id,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
use fader_config::Profile;
|
||||
use fader_master::audio_selection_policy;
|
||||
use volume_lib::{AdapterChoice, AudioBackend};
|
||||
|
||||
fn profile(adapter: &str, preference: &str) -> Profile {
|
||||
Profile::parse(&format!(
|
||||
r#"
|
||||
schema_version = 1
|
||||
id = "policy-test"
|
||||
startup = "adopt"
|
||||
new_stream = "adopt"
|
||||
|
||||
[audio]
|
||||
adapter = "{adapter}"
|
||||
preference = {preference}
|
||||
max_gain = 1.0
|
||||
"#
|
||||
))
|
||||
.expect("valid policy fixture")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_auto_order_reaches_the_runtime_policy() {
|
||||
let profile = profile("auto", r#"["pipewire", "pulse"]"#);
|
||||
let policy = audio_selection_policy(&profile, None).unwrap();
|
||||
|
||||
assert_eq!(policy.effective_choice(), AdapterChoice::Auto);
|
||||
assert_eq!(
|
||||
policy.preference(),
|
||||
&[AudioBackend::PipeWire, AudioBackend::Pulse]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_override_wins_for_the_session_without_changing_the_profile() {
|
||||
let profile = profile("pulse", "[]");
|
||||
let policy = audio_selection_policy(
|
||||
&profile,
|
||||
Some(AdapterChoice::Manual(AudioBackend::PipeWire)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
policy.effective_choice(),
|
||||
AdapterChoice::Manual(AudioBackend::PipeWire)
|
||||
);
|
||||
assert_eq!(profile.audio().adapter(), fader_config::Adapter::Pulse);
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use clap::{CommandFactory, Parser};
|
||||
use fader_master::cli::{
|
||||
AudioArgument, Cli, ClientCli, Command, ProfileCommand, ServerCli, ThemeArgument,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn every_planned_command_is_present_in_help() {
|
||||
let help = Cli::command().render_long_help().to_string();
|
||||
for command in ["serve", "tui", "validate", "devices", "status", "profile"] {
|
||||
assert!(help.contains(command), "missing {command:?} in help");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_accepts_durable_selection_or_config_and_parses_session_override() {
|
||||
assert_eq!(
|
||||
Cli::try_parse_from(["fader_master", "serve"])
|
||||
.unwrap()
|
||||
.command,
|
||||
Some(Command::Serve {
|
||||
config: None,
|
||||
audio: None,
|
||||
socket: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
Cli::try_parse_from([
|
||||
"fader_master",
|
||||
"serve",
|
||||
"--config",
|
||||
"profile.toml",
|
||||
"--audio",
|
||||
"pulse",
|
||||
])
|
||||
.unwrap()
|
||||
.command,
|
||||
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),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_commands_and_adapter_values_are_rejected() {
|
||||
assert!(Cli::try_parse_from(["fader_master", "unknown"]).is_err());
|
||||
assert!(
|
||||
Cli::try_parse_from([
|
||||
"fader_master",
|
||||
"serve",
|
||||
"--config",
|
||||
"profile.toml",
|
||||
"--audio",
|
||||
"alsa-master",
|
||||
])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tui_accepts_known_themes_and_rejects_unknown_names() {
|
||||
assert_eq!(
|
||||
Cli::try_parse_from(["fader_master", "tui"])
|
||||
.unwrap()
|
||||
.command,
|
||||
Some(Command::Tui {
|
||||
socket: None,
|
||||
theme: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
Cli::try_parse_from(["fader_master", "tui", "--theme", "catppuccin-mocha"])
|
||||
.unwrap()
|
||||
.command,
|
||||
Some(Command::Tui {
|
||||
socket: None,
|
||||
theme: Some(ThemeArgument::CatppuccinMocha),
|
||||
})
|
||||
);
|
||||
assert!(Cli::try_parse_from(["fader_master", "tui", "--theme", "hot-dog-stand"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_switch_accepts_an_id_and_socket_override() {
|
||||
assert_eq!(
|
||||
Cli::try_parse_from([
|
||||
"fader_master",
|
||||
"profile",
|
||||
"switch",
|
||||
"gaming",
|
||||
"--socket",
|
||||
"/run/user/1000/fader_master/control.sock",
|
||||
])
|
||||
.unwrap()
|
||||
.command,
|
||||
Some(Command::Profile {
|
||||
command: ProfileCommand::Switch {
|
||||
id: "gaming".into(),
|
||||
restore: false,
|
||||
socket: Some("/run/user/1000/fader_master/control.sock".into()),
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
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();
|
||||
let config = directory.path().join("invalid.toml");
|
||||
let socket = directory.path().join("runtime/control.sock");
|
||||
fs::write(&config, "schema_version = 999\nid = 'broken'\n").unwrap();
|
||||
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_fader_master"))
|
||||
.args([
|
||||
"serve",
|
||||
"--config",
|
||||
config.to_str().unwrap(),
|
||||
"--socket",
|
||||
socket.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(!socket.exists());
|
||||
assert!(!socket.parent().unwrap().exists());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("profile"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_active_selection_cannot_silently_choose_a_profile() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let home = directory.path().join("home");
|
||||
let config_home = directory.path().join("config");
|
||||
let state_home = directory.path().join("state");
|
||||
let runtime = directory.path().join("runtime");
|
||||
let app_config = config_home.join("fader_master");
|
||||
fs::create_dir_all(&app_config).unwrap();
|
||||
fs::write(
|
||||
app_config.join("config.toml"),
|
||||
"active_profile = '../escape'",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_fader_master"))
|
||||
.arg("serve")
|
||||
.env("HOME", home)
|
||||
.env("XDG_CONFIG_HOME", config_home)
|
||||
.env("XDG_STATE_HOME", state_home)
|
||||
.env("XDG_RUNTIME_DIR", runtime)
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stderr).contains("active profile selection is invalid")
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
use std::io::Cursor;
|
||||
|
||||
use fader_master::ipc::{
|
||||
ClientRequest, FrameError, MAX_FRAME_BYTES, MixerObjectKey, MixerObjectKind, PROTOCOL_VERSION,
|
||||
RequestCommand, read_frame, write_frame,
|
||||
};
|
||||
|
||||
fn request() -> ClientRequest {
|
||||
ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 42,
|
||||
command: RequestCommand::SetVolume {
|
||||
object: MixerObjectKey {
|
||||
kind: MixerObjectKind::Application,
|
||||
id: "music".to_owned(),
|
||||
},
|
||||
gain: 0.25,
|
||||
expected_revision: 7,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_toml_frame_round_trips_request_identity_and_revision() {
|
||||
let expected = request();
|
||||
let mut bytes = Vec::new();
|
||||
write_frame(&mut bytes, &expected).unwrap();
|
||||
assert!(bytes.len() <= MAX_FRAME_BYTES + 4);
|
||||
assert_eq!(
|
||||
read_frame::<ClientRequest>(&mut Cursor::new(bytes)).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_media_playlist_snapshot_round_trips_over_ipc() {
|
||||
let snapshot = media::Snapshot {
|
||||
available: true,
|
||||
error: None,
|
||||
players: vec![media::Player {
|
||||
bus_name: "org.mpris.MediaPlayer2.fixture".into(),
|
||||
playlists: (0..256)
|
||||
.map(|n| media::Playlist {
|
||||
id: format!("/playlist/{n}"),
|
||||
name: "X".repeat(256),
|
||||
})
|
||||
.collect(),
|
||||
..media::Player::default()
|
||||
}],
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
write_frame(&mut bytes, &snapshot).unwrap();
|
||||
assert_eq!(
|
||||
read_frame::<media::Snapshot>(&mut Cursor::new(bytes)).unwrap(),
|
||||
snapshot
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_length_is_rejected_before_payload_allocation_or_read() {
|
||||
let length = u32::try_from(MAX_FRAME_BYTES + 1).unwrap().to_be_bytes();
|
||||
assert!(matches!(
|
||||
read_frame::<ClientRequest>(&mut Cursor::new(length)),
|
||||
Err(FrameError::TooLarge { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_malformed_frames_are_explicit_errors() {
|
||||
let mut truncated = Vec::from(10_u32.to_be_bytes());
|
||||
truncated.extend_from_slice(b"short");
|
||||
assert!(matches!(
|
||||
read_frame::<ClientRequest>(&mut Cursor::new(truncated)),
|
||||
Err(FrameError::Truncated(_))
|
||||
));
|
||||
|
||||
let invalid = b"not = [valid";
|
||||
let mut malformed = Vec::from(u32::try_from(invalid.len()).unwrap().to_be_bytes());
|
||||
malformed.extend_from_slice(invalid);
|
||||
assert!(matches!(
|
||||
read_frame::<ClientRequest>(&mut Cursor::new(malformed)),
|
||||
Err(FrameError::Decode(_))
|
||||
));
|
||||
}
|
||||
|
|
@ -0,0 +1,418 @@
|
|||
use fader_config::Profile;
|
||||
use fader_core::{
|
||||
AdapterEvent, BackendEpoch, ChannelGains, FaderId, Gain, Mute, StreamHandle, StreamMetadata,
|
||||
SurfaceId,
|
||||
};
|
||||
use fader_master::{
|
||||
ipc::{
|
||||
ClientRequest, MidiDevice, MixerObjectKey, MixerObjectKind, PROTOCOL_VERSION, PickupStatus,
|
||||
RequestCommand, ResponseResult,
|
||||
},
|
||||
live::LiveMixerState,
|
||||
};
|
||||
use midi::MidiIntent;
|
||||
use volume_lib::WorkerEvent;
|
||||
|
||||
fn gain(value: f64) -> Gain {
|
||||
Gain::new(value).unwrap()
|
||||
}
|
||||
|
||||
fn stream() -> StreamHandle {
|
||||
StreamHandle::new(BackendEpoch::new(1), 12, 1)
|
||||
}
|
||||
|
||||
fn observed_for(
|
||||
stream: StreamHandle,
|
||||
gain_values: [f64; 2],
|
||||
muted: Mute,
|
||||
operation: Option<fader_core::OperationId>,
|
||||
) -> WorkerEvent {
|
||||
WorkerEvent::Adapter(AdapterEvent::Observed {
|
||||
stream,
|
||||
channels: ChannelGains::new(gain_values.into_iter().map(gain).collect()).unwrap(),
|
||||
muted,
|
||||
operation,
|
||||
})
|
||||
}
|
||||
|
||||
fn observed(operation: Option<fader_core::OperationId>) -> WorkerEvent {
|
||||
observed_for(stream(), [0.4, 0.2], Mute::Unmuted, operation)
|
||||
}
|
||||
|
||||
fn ready_state() -> LiveMixerState {
|
||||
let profile = Profile::parse(include_str!("../../examples/profiles/desktop.toml")).unwrap();
|
||||
let mut state = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap();
|
||||
state
|
||||
.worker_event(WorkerEvent::StreamMetadata {
|
||||
stream: stream(),
|
||||
metadata: StreamMetadata::new()
|
||||
.with_application_name("Music Player")
|
||||
.with_process_binary("player"),
|
||||
volume_writable: true,
|
||||
})
|
||||
.unwrap();
|
||||
state.worker_event(observed(None)).unwrap();
|
||||
state
|
||||
.worker_event(WorkerEvent::SnapshotEnd(BackendEpoch::new(1)))
|
||||
.unwrap();
|
||||
state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observations_publish_configured_objects_and_offline_state() {
|
||||
let state = ready_state();
|
||||
let snapshot = state.snapshot();
|
||||
assert_eq!(snapshot.status, "ready");
|
||||
assert_eq!(snapshot.objects.len(), 3);
|
||||
assert_eq!(snapshot.objects[0].label, "Music");
|
||||
assert_eq!(snapshot.objects[0].gain, Some(0.4));
|
||||
assert_eq!(snapshot.objects[0].muted, Some(false));
|
||||
assert_eq!(snapshot.objects[1].label, "Browser");
|
||||
assert_eq!(snapshot.objects[1].gain, None);
|
||||
assert_eq!(snapshot.objects[1].detail, "offline");
|
||||
assert_eq!(snapshot.objects[2].label, "Media");
|
||||
assert_eq!(snapshot.objects[2].gain, Some(0.4));
|
||||
assert!(snapshot.revision > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midi_input_for_an_offline_application_is_a_nonfatal_noop() {
|
||||
let profile =
|
||||
Profile::parse(include_str!("../../examples/profiles/arch-pipewire.toml")).unwrap();
|
||||
let mut state = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap();
|
||||
let surface = SurfaceId::new("apc-mini").unwrap();
|
||||
let fader = FaderId::new("browser-fader").unwrap();
|
||||
|
||||
assert!(
|
||||
state
|
||||
.midi_intent(
|
||||
MidiIntent::AbsoluteVolume {
|
||||
surface: surface.clone(),
|
||||
fader: fader.clone(),
|
||||
gain: gain(0.75),
|
||||
},
|
||||
1,
|
||||
)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
state
|
||||
.midi_intent(MidiIntent::ToggleMute { surface, fader }, 2)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(state.snapshot().objects[1].detail, "offline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_volume_is_pending_until_correlated_readback() {
|
||||
let mut state = ready_state();
|
||||
let snapshot = state.snapshot();
|
||||
let object = snapshot.objects[0].object.clone();
|
||||
let request = ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 8,
|
||||
command: RequestCommand::SetVolume {
|
||||
object,
|
||||
gain: 0.75,
|
||||
expected_revision: snapshot.revision,
|
||||
},
|
||||
};
|
||||
let (response, commands) = state.request(request).unwrap();
|
||||
assert_eq!(commands.len(), 1);
|
||||
assert!(matches!(response.result, ResponseResult::Snapshot { .. }));
|
||||
assert!(state.snapshot().objects[0].pending);
|
||||
|
||||
let operation = match commands[0] {
|
||||
fader_core::AdapterCommand::SetVolume { operation, .. } => operation,
|
||||
_ => panic!("expected volume command"),
|
||||
};
|
||||
let readback = state
|
||||
.worker_event(WorkerEvent::Adapter(AdapterEvent::WriteAccepted {
|
||||
operation,
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
readback.as_slice(),
|
||||
[fader_core::AdapterCommand::Readback { .. }]
|
||||
));
|
||||
state.worker_event(observed(Some(operation))).unwrap();
|
||||
assert!(!state.snapshot().objects[0].pending);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_client_revision_is_rejected_for_resnapshot() {
|
||||
let mut state = ready_state();
|
||||
let error = state
|
||||
.request(ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 9,
|
||||
command: RequestCommand::ToggleMute {
|
||||
object: MixerObjectKey {
|
||||
kind: MixerObjectKind::Application,
|
||||
id: "music".to_owned(),
|
||||
},
|
||||
expected_revision: 0,
|
||||
},
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("stale revision"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_aggregates_mixed_members_and_fans_out_one_action() {
|
||||
let mut state = ready_state();
|
||||
let browser = StreamHandle::new(BackendEpoch::new(1), 13, 1);
|
||||
state
|
||||
.worker_event(WorkerEvent::StreamMetadata {
|
||||
stream: browser,
|
||||
metadata: StreamMetadata::new().with_process_binary("firefox"),
|
||||
volume_writable: true,
|
||||
})
|
||||
.unwrap();
|
||||
state
|
||||
.worker_event(observed_for(browser, [0.7, 0.7], Mute::Muted, None))
|
||||
.unwrap();
|
||||
|
||||
let snapshot = state.snapshot();
|
||||
let group = &snapshot.objects[2];
|
||||
assert_eq!(group.detail, "2 streams");
|
||||
assert_eq!(group.gain, Some(0.7));
|
||||
assert!(group.gain_mixed);
|
||||
assert_eq!(group.muted, None);
|
||||
assert!(group.mute_mixed);
|
||||
|
||||
let (_, volume_commands) = state
|
||||
.request(ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 10,
|
||||
command: RequestCommand::SetVolume {
|
||||
object: group.object.clone(),
|
||||
gain: 0.6,
|
||||
expected_revision: snapshot.revision,
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(volume_commands.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lagging_client_cannot_overwrite_an_edit_and_can_resnapshot() {
|
||||
let mut state = ready_state();
|
||||
let attached = state.snapshot();
|
||||
let object = attached.objects[0].object.clone();
|
||||
|
||||
state
|
||||
.request(ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 20,
|
||||
command: RequestCommand::SetVolume {
|
||||
object: object.clone(),
|
||||
gain: 0.5,
|
||||
expected_revision: attached.revision,
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
let stale = state
|
||||
.request(ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 21,
|
||||
command: RequestCommand::ToggleMute {
|
||||
object,
|
||||
expected_revision: attached.revision,
|
||||
},
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(stale.to_string().contains("stale revision"));
|
||||
|
||||
let (response, commands) = state
|
||||
.request(ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 22,
|
||||
command: RequestCommand::Snapshot,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(commands.is_empty());
|
||||
let ResponseResult::Snapshot { snapshot } = response.result else {
|
||||
panic!("resync request must return a complete snapshot");
|
||||
};
|
||||
assert!(snapshot.revision > attached.revision);
|
||||
assert!(snapshot.objects[0].pending);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midi_volume_waits_for_pickup_crossing_before_dispatch() {
|
||||
let mut state = ready_state();
|
||||
let surface = SurfaceId::new("desk-left").unwrap();
|
||||
let fader = FaderId::new("media-fader").unwrap();
|
||||
let intent = |value| MidiIntent::AbsoluteVolume {
|
||||
surface: surface.clone(),
|
||||
fader: fader.clone(),
|
||||
gain: gain(value),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
state.snapshot().objects[2].pickup,
|
||||
Some(PickupStatus::Waiting)
|
||||
);
|
||||
assert!(state.midi_intent(intent(0.1), 1).unwrap().is_empty());
|
||||
assert_eq!(
|
||||
state.snapshot().objects[2].pickup,
|
||||
Some(PickupStatus::Waiting)
|
||||
);
|
||||
assert!(state.midi_intent(intent(0.3), 2).unwrap().is_empty());
|
||||
let commands = state.midi_intent(intent(0.5), 3).unwrap();
|
||||
assert_eq!(commands.len(), 1);
|
||||
assert!(matches!(
|
||||
commands[0],
|
||||
fader_core::AdapterCommand::SetVolume { .. }
|
||||
));
|
||||
assert_eq!(
|
||||
state.snapshot().objects[2].pickup,
|
||||
Some(PickupStatus::Tracking)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_volume_change_rearms_midi_pickup() {
|
||||
let mut state = ready_state();
|
||||
let surface = SurfaceId::new("desk-left").unwrap();
|
||||
let fader = FaderId::new("media-fader").unwrap();
|
||||
let intent = |value| MidiIntent::AbsoluteVolume {
|
||||
surface: surface.clone(),
|
||||
fader: fader.clone(),
|
||||
gain: gain(value),
|
||||
};
|
||||
|
||||
assert!(state.midi_intent(intent(0.4), 1).unwrap().len() == 1);
|
||||
state
|
||||
.worker_event(observed_for(stream(), [0.8, 0.8], Mute::Unmuted, None))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
state.snapshot().objects[2].pickup,
|
||||
Some(PickupStatus::Waiting)
|
||||
);
|
||||
assert!(state.midi_intent(intent(0.5), 2).unwrap().is_empty());
|
||||
assert_eq!(state.midi_intent(intent(0.8), 3).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn correlated_write_echo_keeps_midi_pickup_tracking() {
|
||||
let mut state = ready_state();
|
||||
let surface = SurfaceId::new("desk-left").unwrap();
|
||||
let fader = FaderId::new("media-fader").unwrap();
|
||||
let intent = |value| MidiIntent::AbsoluteVolume {
|
||||
surface: surface.clone(),
|
||||
fader: fader.clone(),
|
||||
gain: gain(value),
|
||||
};
|
||||
|
||||
let first = state.midi_intent(intent(0.4), 1).unwrap();
|
||||
let operation = match first.as_slice() {
|
||||
[fader_core::AdapterCommand::SetVolume { operation, .. }] => *operation,
|
||||
commands => panic!("expected one volume command, got {commands:?}"),
|
||||
};
|
||||
state
|
||||
.worker_event(observed_for(
|
||||
stream(),
|
||||
[0.4, 0.2],
|
||||
Mute::Unmuted,
|
||||
Some(operation),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(state.midi_intent(intent(0.8), 2).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controller_disconnect_forgets_the_tracked_physical_position() {
|
||||
let mut state = ready_state();
|
||||
let surface = SurfaceId::new("desk-left").unwrap();
|
||||
let fader = FaderId::new("media-fader").unwrap();
|
||||
let intent = |value| MidiIntent::AbsoluteVolume {
|
||||
surface: surface.clone(),
|
||||
fader: fader.clone(),
|
||||
gain: gain(value),
|
||||
};
|
||||
let device = |status: &str, backend_id: Option<&str>| MidiDevice {
|
||||
id: "desk-left".to_owned(),
|
||||
label: "Left controller".to_owned(),
|
||||
status: status.to_owned(),
|
||||
backend_id: backend_id.map(str::to_owned),
|
||||
error: None,
|
||||
};
|
||||
|
||||
state.set_devices(vec![device("connected", Some("36:0"))]);
|
||||
assert_eq!(state.midi_intent(intent(0.4), 1).unwrap().len(), 1);
|
||||
state.set_devices(vec![device("missing", None)]);
|
||||
|
||||
assert!(state.midi_intent(intent(0.2), 2).unwrap().is_empty());
|
||||
assert_eq!(state.midi_intent(intent(0.4), 3).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_output_is_visible_and_master_fader_uses_pickup() {
|
||||
let profile =
|
||||
Profile::parse(include_str!("../../examples/profiles/arch-pipewire.toml")).unwrap();
|
||||
let mut state = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap();
|
||||
let output = StreamHandle::new(BackendEpoch::new(1), 1_u64 << 63, 1);
|
||||
state
|
||||
.worker_event(WorkerEvent::OutputMetadata {
|
||||
stream: output,
|
||||
label: "Scarlett Solo".to_owned(),
|
||||
volume_writable: true,
|
||||
})
|
||||
.unwrap();
|
||||
state
|
||||
.worker_event(observed_for(output, [0.6, 0.4], Mute::Unmuted, None))
|
||||
.unwrap();
|
||||
|
||||
let snapshot = state.snapshot();
|
||||
let master = snapshot.objects.last().unwrap();
|
||||
assert_eq!(master.object.kind, MixerObjectKind::Output);
|
||||
assert_eq!(master.label, "Master");
|
||||
assert_eq!(master.detail, "Scarlett Solo");
|
||||
assert_eq!(master.gain, Some(0.6));
|
||||
|
||||
let surface = SurfaceId::new("apc-mini").unwrap();
|
||||
let fader = FaderId::new("master-fader").unwrap();
|
||||
let intent = |value| MidiIntent::AbsoluteVolume {
|
||||
surface: surface.clone(),
|
||||
fader: fader.clone(),
|
||||
gain: gain(value),
|
||||
};
|
||||
assert!(state.midi_intent(intent(0.2), 1).unwrap().is_empty());
|
||||
let commands = state.midi_intent(intent(0.6), 2).unwrap();
|
||||
assert!(matches!(
|
||||
commands.as_slice(),
|
||||
[fader_core::AdapterCommand::SetVolume { stream, .. }] if *stream == output
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rapid_mute_edges_toggle_against_pending_intent() {
|
||||
let mut state = ready_state();
|
||||
let intent = MidiIntent::ToggleMute {
|
||||
surface: SurfaceId::new("desk-left").unwrap(),
|
||||
fader: FaderId::new("media-fader").unwrap(),
|
||||
};
|
||||
|
||||
let first = state.midi_intent(intent.clone(), 1).unwrap();
|
||||
let second = state.midi_intent(intent, 2).unwrap();
|
||||
assert!(matches!(
|
||||
first.as_slice(),
|
||||
[fader_core::AdapterCommand::SetMute {
|
||||
muted: Mute::Muted,
|
||||
..
|
||||
}]
|
||||
));
|
||||
assert!(matches!(
|
||||
second.as_slice(),
|
||||
[fader_core::AdapterCommand::SetMute {
|
||||
muted: Mute::Unmuted,
|
||||
..
|
||||
}]
|
||||
));
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
use std::{
|
||||
fs,
|
||||
os::unix::fs::{FileTypeExt, PermissionsExt},
|
||||
thread,
|
||||
};
|
||||
|
||||
use fader_master::{
|
||||
ipc::{ClientRequest, PROTOCOL_VERSION, RequestCommand, ResponseResult, ServerResponse},
|
||||
local::{LocalError, OwnedListener, client_request},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn listener_is_private_and_prevents_a_second_server() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("control.sock");
|
||||
let listener = OwnedListener::bind(&path).unwrap();
|
||||
let metadata = fs::metadata(&path).unwrap();
|
||||
assert!(metadata.file_type().is_socket());
|
||||
assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
|
||||
assert!(matches!(
|
||||
OwnedListener::bind(&path),
|
||||
Err(LocalError::AlreadyRunning(_))
|
||||
));
|
||||
drop(listener);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_rejects_a_socket_with_wrong_permissions() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("control.sock");
|
||||
let listener = OwnedListener::bind(&path).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o666)).unwrap();
|
||||
let request = ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 1,
|
||||
command: RequestCommand::Snapshot,
|
||||
};
|
||||
assert!(matches!(
|
||||
client_request(&path, &request),
|
||||
Err(LocalError::UnsafeSocket { .. })
|
||||
));
|
||||
drop(listener);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_validates_correlated_versioned_response() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("control.sock");
|
||||
let listener = OwnedListener::bind(&path).unwrap();
|
||||
let request = ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 77,
|
||||
command: RequestCommand::Snapshot,
|
||||
};
|
||||
let server = thread::spawn(move || {
|
||||
loop {
|
||||
if let Some(mut stream) = listener.accept().unwrap() {
|
||||
let received: ClientRequest = fader_master::ipc::read_frame(&mut stream).unwrap();
|
||||
fader_master::ipc::write_frame(
|
||||
&mut stream,
|
||||
&ServerResponse {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: received.request_id,
|
||||
result: ResponseResult::Error {
|
||||
message: "fixture".into(),
|
||||
resync: false,
|
||||
},
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
break;
|
||||
}
|
||||
thread::yield_now();
|
||||
}
|
||||
});
|
||||
let response = client_request(&path, &request).unwrap();
|
||||
assert_eq!(response.request_id, 77);
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use fader_core::{BackendEpoch, ChannelGains, Gain, Mute, StreamHandle};
|
||||
use fader_master::{ServerStatus, VerticalSlice};
|
||||
use volume_lib::{FakeAdapter, RetrySchedule};
|
||||
|
||||
fn channels(left: f64, right: f64) -> ChannelGains {
|
||||
ChannelGains::new(vec![Gain::new(left).unwrap(), Gain::new(right).unwrap()]).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnect_resnapshots_and_restore_overlap_uses_profile_order() {
|
||||
let first_epoch = BackendEpoch::new(1);
|
||||
let old = StreamHandle::new(first_epoch, 3, 1);
|
||||
let mut server = VerticalSlice::new(FakeAdapter::new(first_epoch), 4, Gain::UNITY);
|
||||
server
|
||||
.adopt(old, channels(0.2, 0.4), Mute::Unmuted)
|
||||
.unwrap();
|
||||
server.disconnect().unwrap();
|
||||
assert_eq!(server.status(), ServerStatus::Unavailable);
|
||||
|
||||
let next_epoch = BackendEpoch::new(2);
|
||||
let current = StreamHandle::new(next_epoch, 3, 1);
|
||||
server
|
||||
.reconnect(
|
||||
FakeAdapter::new(next_epoch),
|
||||
vec![(current, channels(0.3, 0.6), Mute::Unmuted)],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(server.status(), ServerStatus::Ready);
|
||||
server
|
||||
.restore_volumes(&[
|
||||
(current, Gain::new(0.5).unwrap()),
|
||||
(current, Gain::new(0.9).unwrap()),
|
||||
])
|
||||
.unwrap();
|
||||
let feedback = server.confirmed(current).unwrap();
|
||||
assert_eq!(feedback.channels.maximum(), Gain::new(0.9).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnect_backoff_is_bounded_and_resets_after_success() {
|
||||
let mut retries = RetrySchedule::new(100, 800);
|
||||
assert_eq!(
|
||||
(0..5).map(|_| retries.next_delay_ms()).collect::<Vec<_>>(),
|
||||
vec![100, 200, 400, 800, 800]
|
||||
);
|
||||
retries.reset();
|
||||
assert_eq!(retries.next_delay_ms(), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_adopts_then_simulated_midi_converges_on_confirmed_feedback() {
|
||||
let epoch = BackendEpoch::new(1);
|
||||
let stream = StreamHandle::new(epoch, 8, 1);
|
||||
let mut server = VerticalSlice::new(FakeAdapter::new(epoch), 8, Gain::UNITY);
|
||||
let startup = server
|
||||
.adopt(stream, channels(0.25, 0.5), Mute::Unmuted)
|
||||
.unwrap();
|
||||
assert_eq!(startup.channels, channels(0.25, 0.5));
|
||||
assert!(!startup.pending);
|
||||
assert_eq!(startup.desired_gain, None);
|
||||
|
||||
let feedback = server
|
||||
.midi_volume("desk", 1, stream, Gain::new(0.8).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(feedback.channels, channels(0.4, 0.8));
|
||||
assert_eq!(feedback.desired_gain, Some(Gain::new(0.8).unwrap()));
|
||||
assert!(!feedback.pending);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnect_expires_state_and_shutdown_checkpoints_after_drain() {
|
||||
let epoch = BackendEpoch::new(4);
|
||||
let stream = StreamHandle::new(epoch, 2, 1);
|
||||
let mut server = VerticalSlice::new(FakeAdapter::new(epoch), 4, Gain::UNITY);
|
||||
server
|
||||
.adopt(stream, channels(0.3, 0.6), Mute::Muted)
|
||||
.unwrap();
|
||||
server.disconnect().unwrap();
|
||||
|
||||
let checkpointed = Rc::new(RefCell::new(None));
|
||||
let output = Rc::clone(&checkpointed);
|
||||
server
|
||||
.shutdown(move |views| *output.borrow_mut() = Some(views.to_vec()))
|
||||
.unwrap();
|
||||
assert_eq!(checkpointed.borrow().as_deref(), Some([].as_slice()));
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
[package]
|
||||
name = "media"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
fader-core.workspace = true
|
||||
serde.workspace = true
|
||||
regex.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
|
@ -0,0 +1,446 @@
|
|||
//! Hardware-free MPRIS matching, action and feedback contracts.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum MediaError {
|
||||
#[error("player offline")]
|
||||
Offline,
|
||||
#[error("selector matches multiple players; narrow the selector")]
|
||||
Ambiguous,
|
||||
#[error("unsupported player action")]
|
||||
Unsupported,
|
||||
#[error("player discovery incomplete: {0}")]
|
||||
Unavailable(String),
|
||||
#[error("invalid media configuration: {0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PlayerField {
|
||||
#[default]
|
||||
BusName,
|
||||
DesktopEntry,
|
||||
Identity,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PlayerSelector {
|
||||
pub field: PlayerField,
|
||||
pub pattern: String,
|
||||
#[serde(default)]
|
||||
pub regex: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PlayerMatcher {
|
||||
selector: PlayerSelector,
|
||||
regex: Option<regex::Regex>,
|
||||
}
|
||||
|
||||
impl PlayerSelector {
|
||||
pub fn compile(&self) -> Result<PlayerMatcher, MediaError> {
|
||||
if self.pattern.is_empty() || self.pattern.len() > 256 {
|
||||
return Err(MediaError::Invalid(
|
||||
"selector must contain 1–256 bytes".into(),
|
||||
));
|
||||
}
|
||||
let regex = if self.regex {
|
||||
Some(
|
||||
regex::RegexBuilder::new(&self.pattern)
|
||||
.size_limit(1 << 20)
|
||||
.build()
|
||||
.map_err(|e| MediaError::Invalid(e.to_string()))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(PlayerMatcher {
|
||||
selector: self.clone(),
|
||||
regex,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl PlayerMatcher {
|
||||
pub fn matches(&self, player: &Player) -> bool {
|
||||
let value = match self.selector.field {
|
||||
PlayerField::BusName => Some(player.bus_name.as_str()),
|
||||
PlayerField::DesktopEntry => player.desktop_entry.as_deref(),
|
||||
PlayerField::Identity => player.identity.as_deref(),
|
||||
};
|
||||
value.is_some_and(|value| {
|
||||
self.regex
|
||||
.as_ref()
|
||||
.map_or_else(|| value == self.selector.pattern, |re| re.is_match(value))
|
||||
})
|
||||
}
|
||||
pub fn resolve<'a>(&self, players: &'a [Player]) -> Result<&'a Player, MediaError> {
|
||||
if self.selector.field != PlayerField::BusName
|
||||
&& let Some(error) = players.iter().find_map(|p| p.error.as_ref())
|
||||
{
|
||||
return Err(MediaError::Unavailable(error.clone()));
|
||||
}
|
||||
let mut matches = players.iter().filter(|p| self.matches(p));
|
||||
let first = matches.next().ok_or(MediaError::Offline)?;
|
||||
if matches.next().is_some() {
|
||||
return Err(MediaError::Ambiguous);
|
||||
}
|
||||
if let Some(error) = &first.error {
|
||||
return Err(MediaError::Unavailable(error.clone()));
|
||||
}
|
||||
Ok(first)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub enum Playback {
|
||||
Playing,
|
||||
Paused,
|
||||
Stopped,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub enum Repeat {
|
||||
#[default]
|
||||
None,
|
||||
Track,
|
||||
Playlist,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Action {
|
||||
Play,
|
||||
Pause,
|
||||
Stop,
|
||||
PlayPause,
|
||||
Next,
|
||||
Previous,
|
||||
Seek { offset_ms: i64 },
|
||||
SetPosition { position_ms: u64 },
|
||||
ShuffleToggle,
|
||||
Shuffle { enabled: bool },
|
||||
RepeatCycle,
|
||||
Repeat { mode: Repeat },
|
||||
Playlist { id: String },
|
||||
}
|
||||
|
||||
impl Action {
|
||||
pub fn validate(&self) -> Result<(), MediaError> {
|
||||
match self {
|
||||
Self::Seek { offset_ms } if offset_ms.unsigned_abs() > 86_400_000 => {
|
||||
Err(MediaError::Invalid("seek offset exceeds one day".into()))
|
||||
}
|
||||
Self::SetPosition { position_ms } if *position_ms > 86_400_000 => {
|
||||
Err(MediaError::Invalid("position exceeds one day".into()))
|
||||
}
|
||||
Self::Playlist { id } if !valid_object_path(id) => {
|
||||
Err(MediaError::Invalid("invalid playlist object path".into()))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
pub fn supported(&self, p: &Player) -> bool {
|
||||
if !p.can_control {
|
||||
return false;
|
||||
}
|
||||
match self {
|
||||
Self::Play => p.can_play,
|
||||
Self::Pause => p.can_pause,
|
||||
Self::PlayPause => {
|
||||
p.can_pause
|
||||
&& match p.playback {
|
||||
Some(Playback::Playing) => p.can_pause,
|
||||
Some(_) => p.can_play,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
Self::Stop => true,
|
||||
Self::Next => p.can_next,
|
||||
Self::Previous => p.can_previous,
|
||||
Self::Seek { .. } => p.can_seek,
|
||||
Self::SetPosition { position_ms } => {
|
||||
p.can_seek
|
||||
&& p.track_id.is_some()
|
||||
&& p.duration_ms.is_some_and(|length| *position_ms <= length)
|
||||
}
|
||||
Self::ShuffleToggle | Self::Shuffle { .. } => p.shuffle.is_some(),
|
||||
Self::RepeatCycle | Self::Repeat { .. } => p.repeat.is_some(),
|
||||
Self::Playlist { id } => p.playlists.iter().any(|playlist| &playlist.id == id),
|
||||
}
|
||||
}
|
||||
/// State indicators are observations, never acknowledgements of a command.
|
||||
pub fn feedback(&self, player: Option<&Player>) -> bool {
|
||||
let Some(p) = player else {
|
||||
return false;
|
||||
};
|
||||
match self {
|
||||
Self::Play | Self::PlayPause => p.playback == Some(Playback::Playing),
|
||||
Self::Pause => p.playback == Some(Playback::Paused),
|
||||
Self::Stop => p.playback == Some(Playback::Stopped),
|
||||
Self::ShuffleToggle => p.shuffle == Some(true),
|
||||
Self::Shuffle { enabled } => p.shuffle == Some(*enabled),
|
||||
Self::RepeatCycle => matches!(p.repeat, Some(Repeat::Track | Repeat::Playlist)),
|
||||
Self::Repeat { mode } => p.repeat == Some(*mode),
|
||||
Self::Playlist { id } => p.active_playlist.as_ref() == Some(id),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_object_path(value: &str) -> bool {
|
||||
value == "/"
|
||||
|| (value.len() <= 1024
|
||||
&& value.starts_with('/')
|
||||
&& value.split('/').skip(1).all(|part| {
|
||||
!part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct Player {
|
||||
pub bus_name: String,
|
||||
/// Unique D-Bus owner; commands must never jump to a replacement instance.
|
||||
pub owner: String,
|
||||
pub identity: Option<String>,
|
||||
pub desktop_entry: Option<String>,
|
||||
pub playback: Option<Playback>,
|
||||
pub can_control: bool,
|
||||
pub can_play: bool,
|
||||
pub can_pause: bool,
|
||||
pub can_next: bool,
|
||||
pub can_previous: bool,
|
||||
pub can_seek: bool,
|
||||
pub position_ms: Option<u64>,
|
||||
pub duration_ms: Option<u64>,
|
||||
pub track_id: Option<String>,
|
||||
pub shuffle: Option<bool>,
|
||||
pub repeat: Option<Repeat>,
|
||||
pub playlists: Vec<Playlist>,
|
||||
pub active_playlist: Option<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct Playlist {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct Snapshot {
|
||||
pub available: bool,
|
||||
pub error: Option<String>,
|
||||
pub players: Vec<Player>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MessageKind {
|
||||
Note,
|
||||
Cc,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Message {
|
||||
pub kind: MessageKind,
|
||||
pub channel: u16,
|
||||
pub number: u16,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn validate(&self) -> Result<(), MediaError> {
|
||||
fader_core::MidiChannel::new(self.channel)
|
||||
.map_err(|e| MediaError::Invalid(e.to_string()))?;
|
||||
fader_core::MidiData::new(self.number).map_err(|e| MediaError::Invalid(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn bytes(&self, value: u8) -> Option<[u8; 3]> {
|
||||
self.validate().ok()?;
|
||||
let status = match self.kind {
|
||||
MessageKind::Note => 0x90,
|
||||
MessageKind::Cc => 0xb0,
|
||||
};
|
||||
Some([
|
||||
status | u8::try_from(self.channel - 1).ok()?,
|
||||
u8::try_from(self.number).ok()?,
|
||||
value,
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Feedback {
|
||||
pub message: Message,
|
||||
pub on: u8,
|
||||
pub off: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Binding {
|
||||
pub surface: String,
|
||||
pub message: Message,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub feedback: Option<Feedback>,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
pub fn feedback_bytes(&self, on: bool) -> Option<[u8; 3]> {
|
||||
if let Some(feedback) = &self.feedback {
|
||||
feedback
|
||||
.message
|
||||
.bytes(if on { feedback.on } else { feedback.off })
|
||||
} else if self.message.kind == MessageKind::Note {
|
||||
self.message.bytes(if on { 127 } else { 0 })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Control {
|
||||
pub id: String,
|
||||
pub action: Action,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub binding: Option<Binding>,
|
||||
}
|
||||
|
||||
const fn enabled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Entry {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub selector: PlayerSelector,
|
||||
#[serde(default = "enabled")]
|
||||
pub feedback_enabled: bool,
|
||||
#[serde(default)]
|
||||
pub controls: Vec<Control>,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub fn validate(&self) -> Result<(), MediaError> {
|
||||
fader_core::ApplicationId::new(&self.id).map_err(|e| MediaError::Invalid(e.to_string()))?;
|
||||
if self.label.trim().is_empty()
|
||||
|| self.label.len() > 128
|
||||
|| self.label.chars().any(char::is_control)
|
||||
{
|
||||
return Err(MediaError::Invalid("invalid media label".into()));
|
||||
}
|
||||
self.selector.compile()?;
|
||||
if self.controls.len() > 64 {
|
||||
return Err(MediaError::Invalid("at most 64 controls per entry".into()));
|
||||
}
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
for control in &self.controls {
|
||||
fader_core::FaderId::new(&control.id)
|
||||
.map_err(|e| MediaError::Invalid(e.to_string()))?;
|
||||
if !ids.insert(&control.id) {
|
||||
return Err(MediaError::Invalid("duplicate control ID".into()));
|
||||
}
|
||||
control.action.validate()?;
|
||||
if let Some(binding) = &control.binding {
|
||||
binding.message.validate()?;
|
||||
if let Some(feedback) = &binding.feedback {
|
||||
feedback.message.validate()?;
|
||||
if feedback.on > 127 || feedback.off > 127 {
|
||||
return Err(MediaError::Invalid("feedback values must be 0–127".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn failed_identity_reads_cannot_hide_an_ambiguous_target() {
|
||||
let matcher = PlayerSelector {
|
||||
field: PlayerField::Identity,
|
||||
pattern: "QBZ".into(),
|
||||
regex: false,
|
||||
}
|
||||
.compile()
|
||||
.unwrap();
|
||||
let players = [
|
||||
Player {
|
||||
identity: Some("QBZ".into()),
|
||||
..Player::default()
|
||||
},
|
||||
Player {
|
||||
error: Some("timed out".into()),
|
||||
..Player::default()
|
||||
},
|
||||
];
|
||||
assert!(matcher.resolve(&players).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_pause_requires_the_protocol_pause_capability() {
|
||||
let player = Player {
|
||||
playback: Some(Playback::Paused),
|
||||
can_control: true,
|
||||
can_play: true,
|
||||
can_pause: false,
|
||||
..Player::default()
|
||||
};
|
||||
assert!(!Action::PlayPause.supported(&player));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_is_explicit_and_never_picks_an_ambiguous_player() {
|
||||
let selector = PlayerSelector {
|
||||
field: PlayerField::BusName,
|
||||
pattern: "org.mpris.MediaPlayer2.com.blitzfc.qbz".into(),
|
||||
regex: false,
|
||||
};
|
||||
let matcher = selector.compile().unwrap();
|
||||
let qbz = Player {
|
||||
bus_name: selector.pattern.clone(),
|
||||
owner: ":1.4".into(),
|
||||
..Player::default()
|
||||
};
|
||||
assert!(matches!(matcher.resolve(&[]), Err(MediaError::Offline)));
|
||||
assert_eq!(
|
||||
matcher.resolve(std::slice::from_ref(&qbz)).unwrap().owner,
|
||||
":1.4"
|
||||
);
|
||||
assert!(matches!(
|
||||
matcher.resolve(&[qbz.clone(), qbz]),
|
||||
Err(MediaError::Ambiguous)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_tracks_observation_not_intent() {
|
||||
for status in [Playback::Playing, Playback::Paused, Playback::Stopped] {
|
||||
let player = Player {
|
||||
playback: Some(status),
|
||||
..Player::default()
|
||||
};
|
||||
let on = [Action::Play, Action::Pause, Action::Stop]
|
||||
.iter()
|
||||
.filter(|a| a.feedback(Some(&player)))
|
||||
.count();
|
||||
assert_eq!(on, 1);
|
||||
}
|
||||
assert!(!Action::Play.feedback(None));
|
||||
}
|
||||
}
|
||||
|
|
@ -2,5 +2,22 @@
|
|||
name = "midi"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["midir"]
|
||||
midir = ["dep:alsa", "dep:midir", "dep:udev"]
|
||||
|
||||
[dependencies]
|
||||
alsa = { workspace = true, optional = true }
|
||||
fader-core.workspace = true
|
||||
midir = { workspace = true, optional = true }
|
||||
thiserror.workspace = true
|
||||
udev = { workspace = true, optional = true }
|
||||
|
||||
[[example]]
|
||||
name = "midi_monitor"
|
||||
required-features = ["midir"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,65 @@
|
|||
use std::{
|
||||
error::Error,
|
||||
io,
|
||||
sync::mpsc::{self, RecvTimeoutError},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use fader_core::SurfaceId;
|
||||
use midi::{LinuxIdentityCatalog, MidiInputCatalog};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut arguments = std::env::args().skip(1);
|
||||
let command = arguments.next().unwrap_or_else(|| "list".to_owned());
|
||||
let catalog = MidiInputCatalog::new("fader_master monitor")?;
|
||||
let ports = catalog.ports()?;
|
||||
if command == "list" {
|
||||
let identities = LinuxIdentityCatalog::new()?;
|
||||
for (index, port) in ports.iter().enumerate() {
|
||||
println!("index={index} identity={:?}", identities.inspect(port)?);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if command != "watch" {
|
||||
return Err(invalid_input(
|
||||
"usage: midi_monitor [list|watch INDEX [SECONDS]]",
|
||||
));
|
||||
}
|
||||
let index = arguments
|
||||
.next()
|
||||
.ok_or_else(|| invalid_input("missing port index"))?
|
||||
.parse::<usize>()?;
|
||||
let seconds = arguments.next().as_deref().unwrap_or("30").parse::<u64>()?;
|
||||
let port = ports
|
||||
.get(index)
|
||||
.ok_or_else(|| invalid_input("port index is out of range"))?;
|
||||
println!("watching id={:?} name={:?}", port.id(), port.name());
|
||||
|
||||
let (sender, receiver) = mpsc::sync_channel(128);
|
||||
let connection = catalog.connect(
|
||||
port,
|
||||
"fader_master monitor input",
|
||||
SurfaceId::new("monitor")?,
|
||||
sender,
|
||||
)?;
|
||||
let deadline = Instant::now() + Duration::from_secs(seconds);
|
||||
while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
|
||||
match receiver.recv_timeout(remaining.min(Duration::from_millis(250))) {
|
||||
Ok(event) => println!("{event:?}"),
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
return Err(invalid_input("MIDI input callback disconnected"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if connection.overflowed() {
|
||||
return Err(invalid_input(
|
||||
"MIDI input queue overflowed; events require resync",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalid_input(message: &str) -> Box<dyn Error> {
|
||||
Box::new(io::Error::new(io::ErrorKind::InvalidInput, message))
|
||||
}
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
use fader_core::{MidiChannel, MidiData};
|
||||
use thiserror::Error;
|
||||
|
||||
/// Press/release semantics normalized across note and CC buttons.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ButtonEdge {
|
||||
Press,
|
||||
Release,
|
||||
}
|
||||
|
||||
/// Supported MIDI 1.0 channel messages.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MidiMessage {
|
||||
ControlChange {
|
||||
channel: MidiChannel,
|
||||
number: MidiData,
|
||||
value: MidiData,
|
||||
},
|
||||
Note {
|
||||
channel: MidiChannel,
|
||||
number: MidiData,
|
||||
velocity: MidiData,
|
||||
edge: ButtonEdge,
|
||||
},
|
||||
}
|
||||
|
||||
/// Malformed bytes for a message type that fader_master otherwise supports.
|
||||
#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
|
||||
pub enum DecodeError {
|
||||
#[error("empty MIDI message")]
|
||||
Empty,
|
||||
#[error("MIDI message starts with data byte 0x{0:02x}; running status is unsupported")]
|
||||
MissingStatus(u8),
|
||||
#[error("MIDI status 0x{status:02x} requires {expected} bytes, received {actual}")]
|
||||
Length {
|
||||
status: u8,
|
||||
expected: usize,
|
||||
actual: usize,
|
||||
},
|
||||
#[error("MIDI byte {position} contains a status bit: 0x{value:02x}")]
|
||||
InvalidData { position: usize, value: u8 },
|
||||
#[error("unsupported MIDI status reached the channel decoder: 0x{0:02x}")]
|
||||
UnsupportedStatus(u8),
|
||||
}
|
||||
|
||||
/// Decodes supported channel messages and ignores unrelated MIDI traffic.
|
||||
///
|
||||
/// Clock, active-sensing, SysEx, program-change, pressure, and pitch messages
|
||||
/// are deliberately outside the first controller profile and return `None`.
|
||||
pub fn decode_message(bytes: &[u8]) -> Result<Option<MidiMessage>, DecodeError> {
|
||||
let Some(&status) = bytes.first() else {
|
||||
return Err(DecodeError::Empty);
|
||||
};
|
||||
if status & 0x80 == 0 {
|
||||
return Err(DecodeError::MissingStatus(status));
|
||||
}
|
||||
|
||||
match status & 0xf0 {
|
||||
0x80 | 0x90 | 0xb0 => decode_three_byte(status, bytes).map(Some),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_three_byte(status: u8, bytes: &[u8]) -> Result<MidiMessage, DecodeError> {
|
||||
if bytes.len() != 3 {
|
||||
return Err(DecodeError::Length {
|
||||
status,
|
||||
expected: 3,
|
||||
actual: bytes.len(),
|
||||
});
|
||||
}
|
||||
let first = data_byte(bytes[1], 1)?;
|
||||
let second = data_byte(bytes[2], 2)?;
|
||||
let channel = MidiChannel::new(u16::from(status & 0x0f) + 1)
|
||||
.map_err(|_| DecodeError::MissingStatus(status))?;
|
||||
match status & 0xf0 {
|
||||
0x80 => Ok(MidiMessage::Note {
|
||||
channel,
|
||||
number: first,
|
||||
velocity: second,
|
||||
edge: ButtonEdge::Release,
|
||||
}),
|
||||
0x90 => Ok(MidiMessage::Note {
|
||||
channel,
|
||||
number: first,
|
||||
velocity: second,
|
||||
edge: if second.get() == 0 {
|
||||
ButtonEdge::Release
|
||||
} else {
|
||||
ButtonEdge::Press
|
||||
},
|
||||
}),
|
||||
0xb0 => Ok(MidiMessage::ControlChange {
|
||||
channel,
|
||||
number: first,
|
||||
value: second,
|
||||
}),
|
||||
_ => Err(DecodeError::UnsupportedStatus(status)),
|
||||
}
|
||||
}
|
||||
|
||||
fn data_byte(value: u8, position: usize) -> Result<MidiData, DecodeError> {
|
||||
if value & 0x80 != 0 {
|
||||
return Err(DecodeError::InvalidData { position, value });
|
||||
}
|
||||
MidiData::new(u16::from(value)).map_err(|_| DecodeError::InvalidData { position, value })
|
||||
}
|
||||
|
|
@ -0,0 +1,155 @@
|
|||
/// USB metadata copied from udev for durable controller matching.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct UsbDeviceIdentity {
|
||||
pub vendor_id: String,
|
||||
pub product_id: String,
|
||||
pub serial: Option<String>,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
/// One currently visible MIDI port and any durable metadata available for it.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct PortIdentity {
|
||||
pub backend_id: String,
|
||||
pub name: String,
|
||||
pub usb: Option<UsbDeviceIdentity>,
|
||||
}
|
||||
|
||||
/// Persisted hints used to find a configured surface without relying on order.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DeviceMatch {
|
||||
pub port_name: String,
|
||||
pub vendor_id: Option<String>,
|
||||
pub product_id: Option<String>,
|
||||
pub serial: Option<String>,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
/// Evidence that made one current port unambiguous.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MatchBasis {
|
||||
Serial,
|
||||
PhysicalPath,
|
||||
UniqueModel,
|
||||
Manual,
|
||||
}
|
||||
|
||||
/// Result of matching one configured surface against current ports.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum PortResolution {
|
||||
Matched { index: usize, basis: MatchBasis },
|
||||
Missing,
|
||||
Ambiguous { candidate_indices: Vec<usize> },
|
||||
}
|
||||
|
||||
/// Resolves durable hints, optionally accepting an explicit current backend ID.
|
||||
#[must_use]
|
||||
pub fn resolve_port(
|
||||
expected: &DeviceMatch,
|
||||
ports: &[PortIdentity],
|
||||
manual_backend_id: Option<&str>,
|
||||
) -> PortResolution {
|
||||
let candidates: Vec<usize> = ports
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, port)| model_matches(expected, port).then_some(index))
|
||||
.collect();
|
||||
|
||||
if let Some(serial) = expected.serial.as_deref() {
|
||||
let serial_matches = candidates_matching(&candidates, ports, |usb| {
|
||||
usb.serial.as_deref() == Some(serial)
|
||||
});
|
||||
return finish(serial_matches, ports, manual_backend_id, MatchBasis::Serial);
|
||||
}
|
||||
if let Some(path) = expected.path.as_deref() {
|
||||
let path_matches =
|
||||
candidates_matching(&candidates, ports, |usb| usb.path.as_deref() == Some(path));
|
||||
return finish(
|
||||
path_matches,
|
||||
ports,
|
||||
manual_backend_id,
|
||||
MatchBasis::PhysicalPath,
|
||||
);
|
||||
}
|
||||
finish(
|
||||
candidates,
|
||||
ports,
|
||||
manual_backend_id,
|
||||
MatchBasis::UniqueModel,
|
||||
)
|
||||
}
|
||||
|
||||
fn model_matches(expected: &DeviceMatch, port: &PortIdentity) -> bool {
|
||||
if stable_port_name(&port.name) != stable_port_name(&expected.port_name) {
|
||||
return false;
|
||||
}
|
||||
match (&expected.vendor_id, &expected.product_id) {
|
||||
(Some(vendor), Some(product)) => port.usb.as_ref().is_some_and(|usb| {
|
||||
usb.vendor_id.eq_ignore_ascii_case(vendor)
|
||||
&& usb.product_id.eq_ignore_ascii_case(product)
|
||||
}),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn stable_port_name(name: &str) -> &str {
|
||||
let Some((prefix, suffix)) = name.rsplit_once(' ') else {
|
||||
return name;
|
||||
};
|
||||
let Some((client, port)) = suffix.split_once(':') else {
|
||||
return name;
|
||||
};
|
||||
if !client.is_empty()
|
||||
&& !port.is_empty()
|
||||
&& client.bytes().all(|byte| byte.is_ascii_digit())
|
||||
&& port.bytes().all(|byte| byte.is_ascii_digit())
|
||||
{
|
||||
prefix
|
||||
} else {
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
fn candidates_matching(
|
||||
candidates: &[usize],
|
||||
ports: &[PortIdentity],
|
||||
predicate: impl Fn(&UsbDeviceIdentity) -> bool,
|
||||
) -> Vec<usize> {
|
||||
candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|index| ports[*index].usb.as_ref().is_some_and(&predicate))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn finish(
|
||||
candidates: Vec<usize>,
|
||||
ports: &[PortIdentity],
|
||||
manual_backend_id: Option<&str>,
|
||||
automatic_basis: MatchBasis,
|
||||
) -> PortResolution {
|
||||
match candidates.as_slice() {
|
||||
[] => PortResolution::Missing,
|
||||
[index] => PortResolution::Matched {
|
||||
index: *index,
|
||||
basis: automatic_basis,
|
||||
},
|
||||
_ => manual_backend_id
|
||||
.and_then(|selected| {
|
||||
candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|index| ports[*index].backend_id == selected)
|
||||
})
|
||||
.map_or_else(
|
||||
|| PortResolution::Ambiguous {
|
||||
candidate_indices: candidates,
|
||||
},
|
||||
|index| PortResolution::Matched {
|
||||
index,
|
||||
basis: MatchBasis::Manual,
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,28 @@
|
|||
pub fn add(left: u64, right: u64) -> u64 {
|
||||
left + right
|
||||
}
|
||||
//! MIDI transport, device identity, bindings, and feedback adapters.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
}
|
||||
}
|
||||
mod decode;
|
||||
mod identity;
|
||||
mod lifecycle;
|
||||
#[cfg(all(feature = "midir", target_os = "linux"))]
|
||||
mod linux_identity;
|
||||
mod router;
|
||||
#[cfg(feature = "midir")]
|
||||
mod transport;
|
||||
|
||||
pub use decode::{ButtonEdge, DecodeError, MidiMessage, decode_message};
|
||||
pub use identity::{
|
||||
DeviceMatch, MatchBasis, PortIdentity, PortResolution, UsbDeviceIdentity, resolve_port,
|
||||
};
|
||||
pub use lifecycle::{
|
||||
SurfaceAction, SurfaceAssignment, SurfaceLifecycle, SurfaceLifecycleError, SurfaceStatus,
|
||||
};
|
||||
#[cfg(all(feature = "midir", target_os = "linux"))]
|
||||
pub use linux_identity::{LinuxIdentityCatalog, LinuxIdentityError};
|
||||
pub use router::{MidiIntent, MidiRouter};
|
||||
#[cfg(feature = "midir")]
|
||||
pub use transport::{
|
||||
InputPort, MidiInputCatalog, MidiInputConnection, MidiInputEvent, MidiOutputCatalog,
|
||||
MidiOutputConnection, MidiTransportError, OutputPort,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,263 @@
|
|||
use std::collections::BTreeMap;
|
||||
|
||||
use fader_core::SurfaceId;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{DeviceMatch, MatchBasis, PortIdentity, PortResolution, resolve_port};
|
||||
|
||||
/// Durable matching policy for one configured surface.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct SurfaceAssignment {
|
||||
pub surface: SurfaceId,
|
||||
pub expected: DeviceMatch,
|
||||
pub manual_backend_id: Option<String>,
|
||||
}
|
||||
|
||||
/// User-visible connection state retained even while a surface is absent.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SurfaceStatus {
|
||||
Missing,
|
||||
Ambiguous {
|
||||
backend_ids: Vec<String>,
|
||||
},
|
||||
Connecting {
|
||||
backend_id: String,
|
||||
basis: MatchBasis,
|
||||
},
|
||||
Connected {
|
||||
backend_id: String,
|
||||
basis: MatchBasis,
|
||||
},
|
||||
Error {
|
||||
backend_id: String,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Native connection work requested by one reconciliation pass.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SurfaceAction {
|
||||
Connect {
|
||||
surface: SurfaceId,
|
||||
port_index: usize,
|
||||
backend_id: String,
|
||||
},
|
||||
Disconnect {
|
||||
surface: SurfaceId,
|
||||
backend_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Error, Eq, PartialEq)]
|
||||
pub enum SurfaceLifecycleError {
|
||||
#[error("duplicate configured surface {0}")]
|
||||
Duplicate(SurfaceId),
|
||||
#[error("surface {0} is not configured")]
|
||||
Unknown(SurfaceId),
|
||||
#[error("surface {surface} is not connecting to backend {backend_id:?}")]
|
||||
UnexpectedConnection {
|
||||
surface: SurfaceId,
|
||||
backend_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Entry {
|
||||
assignment: SurfaceAssignment,
|
||||
status: SurfaceStatus,
|
||||
current_backend: Option<String>,
|
||||
}
|
||||
|
||||
/// Deterministic hotplug reconciliation independent of native MIDI handles.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SurfaceLifecycle {
|
||||
entries: BTreeMap<SurfaceId, Entry>,
|
||||
}
|
||||
|
||||
impl SurfaceLifecycle {
|
||||
pub fn new(
|
||||
assignments: impl IntoIterator<Item = SurfaceAssignment>,
|
||||
) -> Result<Self, SurfaceLifecycleError> {
|
||||
let mut entries = BTreeMap::new();
|
||||
for assignment in assignments {
|
||||
let id = assignment.surface.clone();
|
||||
if entries
|
||||
.insert(
|
||||
id.clone(),
|
||||
Entry {
|
||||
assignment,
|
||||
status: SurfaceStatus::Missing,
|
||||
current_backend: None,
|
||||
},
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
return Err(SurfaceLifecycleError::Duplicate(id));
|
||||
}
|
||||
}
|
||||
Ok(Self { entries })
|
||||
}
|
||||
|
||||
/// Reconciles all surfaces independently and returns native work in stable
|
||||
/// surface-ID order. A port claimed by multiple surfaces is left ambiguous.
|
||||
pub fn reconcile(&mut self, ports: &[PortIdentity]) -> Vec<SurfaceAction> {
|
||||
let mut resolutions: BTreeMap<SurfaceId, PortResolution> = self
|
||||
.entries
|
||||
.iter()
|
||||
.map(|(id, entry)| {
|
||||
(
|
||||
id.clone(),
|
||||
resolve_port(
|
||||
&entry.assignment.expected,
|
||||
ports,
|
||||
entry.assignment.manual_backend_id.as_deref(),
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut claims = BTreeMap::<usize, usize>::new();
|
||||
for resolution in resolutions.values() {
|
||||
if let PortResolution::Matched { index, .. } = resolution {
|
||||
*claims.entry(*index).or_default() += 1;
|
||||
}
|
||||
}
|
||||
for resolution in resolutions.values_mut() {
|
||||
if let PortResolution::Matched { index, .. } = resolution
|
||||
&& claims.get(index).copied().unwrap_or_default() > 1
|
||||
{
|
||||
*resolution = PortResolution::Ambiguous {
|
||||
candidate_indices: vec![*index],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let mut actions = Vec::new();
|
||||
for (id, entry) in &mut self.entries {
|
||||
let resolution = resolutions.remove(id).unwrap_or(PortResolution::Missing);
|
||||
match resolution {
|
||||
PortResolution::Missing => {
|
||||
disconnect_current(id, entry, &mut actions);
|
||||
entry.status = SurfaceStatus::Missing;
|
||||
}
|
||||
PortResolution::Ambiguous { candidate_indices } => {
|
||||
disconnect_current(id, entry, &mut actions);
|
||||
entry.status = SurfaceStatus::Ambiguous {
|
||||
backend_ids: candidate_indices
|
||||
.into_iter()
|
||||
.filter_map(|index| ports.get(index))
|
||||
.map(|port| port.backend_id.clone())
|
||||
.collect(),
|
||||
};
|
||||
}
|
||||
PortResolution::Matched { index, basis } => {
|
||||
let Some(port) = ports.get(index) else {
|
||||
disconnect_current(id, entry, &mut actions);
|
||||
entry.status = SurfaceStatus::Missing;
|
||||
continue;
|
||||
};
|
||||
if entry.current_backend.as_deref() == Some(&port.backend_id) {
|
||||
continue;
|
||||
}
|
||||
if matches!(
|
||||
&entry.status,
|
||||
SurfaceStatus::Connecting { backend_id, .. }
|
||||
if backend_id == &port.backend_id
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
disconnect_current(id, entry, &mut actions);
|
||||
entry.status = SurfaceStatus::Connecting {
|
||||
backend_id: port.backend_id.clone(),
|
||||
basis,
|
||||
};
|
||||
actions.push(SurfaceAction::Connect {
|
||||
surface: id.clone(),
|
||||
port_index: index,
|
||||
backend_id: port.backend_id.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
actions
|
||||
}
|
||||
|
||||
pub fn connection_succeeded(
|
||||
&mut self,
|
||||
surface: &SurfaceId,
|
||||
backend_id: &str,
|
||||
) -> Result<(), SurfaceLifecycleError> {
|
||||
let entry = self
|
||||
.entries
|
||||
.get_mut(surface)
|
||||
.ok_or_else(|| SurfaceLifecycleError::Unknown(surface.clone()))?;
|
||||
let SurfaceStatus::Connecting {
|
||||
backend_id: expected,
|
||||
basis,
|
||||
} = &entry.status
|
||||
else {
|
||||
return Err(SurfaceLifecycleError::UnexpectedConnection {
|
||||
surface: surface.clone(),
|
||||
backend_id: backend_id.to_owned(),
|
||||
});
|
||||
};
|
||||
if expected != backend_id {
|
||||
return Err(SurfaceLifecycleError::UnexpectedConnection {
|
||||
surface: surface.clone(),
|
||||
backend_id: backend_id.to_owned(),
|
||||
});
|
||||
}
|
||||
let basis = *basis;
|
||||
entry.current_backend = Some(backend_id.to_owned());
|
||||
entry.status = SurfaceStatus::Connected {
|
||||
backend_id: backend_id.to_owned(),
|
||||
basis,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn connection_failed(
|
||||
&mut self,
|
||||
surface: &SurfaceId,
|
||||
backend_id: &str,
|
||||
message: impl Into<String>,
|
||||
) -> Result<(), SurfaceLifecycleError> {
|
||||
let entry = self
|
||||
.entries
|
||||
.get_mut(surface)
|
||||
.ok_or_else(|| SurfaceLifecycleError::Unknown(surface.clone()))?;
|
||||
if !matches!(
|
||||
&entry.status,
|
||||
SurfaceStatus::Connecting { backend_id: expected, .. } if expected == backend_id
|
||||
) {
|
||||
return Err(SurfaceLifecycleError::UnexpectedConnection {
|
||||
surface: surface.clone(),
|
||||
backend_id: backend_id.to_owned(),
|
||||
});
|
||||
}
|
||||
entry.current_backend = None;
|
||||
entry.status = SurfaceStatus::Error {
|
||||
backend_id: backend_id.to_owned(),
|
||||
message: message.into(),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn status(&self, surface: &SurfaceId) -> Option<&SurfaceStatus> {
|
||||
self.entries.get(surface).map(|entry| &entry.status)
|
||||
}
|
||||
|
||||
/// All configured surface states in stable ID order.
|
||||
pub fn statuses(&self) -> impl Iterator<Item = (&SurfaceId, &SurfaceStatus)> {
|
||||
self.entries.iter().map(|(id, entry)| (id, &entry.status))
|
||||
}
|
||||
}
|
||||
|
||||
fn disconnect_current(id: &SurfaceId, entry: &mut Entry, actions: &mut Vec<SurfaceAction>) {
|
||||
if let Some(backend_id) = entry.current_backend.take() {
|
||||
actions.push(SurfaceAction::Disconnect {
|
||||
surface: id.clone(),
|
||||
backend_id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
use alsa::Seq;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{InputPort, PortIdentity, UsbDeviceIdentity};
|
||||
|
||||
/// ALSA-sequencer to udev bridge used only for Linux device discovery.
|
||||
pub struct LinuxIdentityCatalog {
|
||||
sequence: Seq,
|
||||
}
|
||||
|
||||
/// Failure while inspecting the live Linux MIDI topology.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum LinuxIdentityError {
|
||||
#[error("could not open the ALSA sequencer for identity discovery: {0}")]
|
||||
OpenSequencer(String),
|
||||
#[error("MIDI backend identifier {0:?} is not an ALSA client:port address")]
|
||||
InvalidBackendId(String),
|
||||
#[error("could not query ALSA client {client}: {message}")]
|
||||
QueryClient { client: i32, message: String },
|
||||
#[error("could not inspect udev sound device card{card}: {message}")]
|
||||
InspectUdev { card: i32, message: String },
|
||||
}
|
||||
|
||||
impl LinuxIdentityCatalog {
|
||||
pub fn new() -> Result<Self, LinuxIdentityError> {
|
||||
let sequence = Seq::open(None, None, true)
|
||||
.map_err(|error| LinuxIdentityError::OpenSequencer(error.to_string()))?;
|
||||
Ok(Self { sequence })
|
||||
}
|
||||
|
||||
/// Copies the current port identity and enriches kernel clients with USB
|
||||
/// metadata. Virtual/user clients legitimately have no associated card.
|
||||
pub fn inspect(&self, port: &InputPort) -> Result<PortIdentity, LinuxIdentityError> {
|
||||
let client = parse_alsa_client(port.id())?;
|
||||
let client_info = self.sequence.get_any_client_info(client).map_err(|error| {
|
||||
LinuxIdentityError::QueryClient {
|
||||
client,
|
||||
message: error.to_string(),
|
||||
}
|
||||
})?;
|
||||
let usb = match client_info.get_card() {
|
||||
Ok(card) if card >= 0 => inspect_usb_card(card)?,
|
||||
Ok(_) | Err(_) => None,
|
||||
};
|
||||
Ok(PortIdentity {
|
||||
backend_id: port.id().to_owned(),
|
||||
name: port.name().to_owned(),
|
||||
usb,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_alsa_client(backend_id: &str) -> Result<i32, LinuxIdentityError> {
|
||||
let Some((client, port)) = backend_id.split_once(':') else {
|
||||
return Err(LinuxIdentityError::InvalidBackendId(backend_id.to_owned()));
|
||||
};
|
||||
if port.parse::<u8>().is_err() {
|
||||
return Err(LinuxIdentityError::InvalidBackendId(backend_id.to_owned()));
|
||||
}
|
||||
client
|
||||
.parse::<i32>()
|
||||
.map_err(|_| LinuxIdentityError::InvalidBackendId(backend_id.to_owned()))
|
||||
}
|
||||
|
||||
fn inspect_usb_card(card: i32) -> Result<Option<UsbDeviceIdentity>, LinuxIdentityError> {
|
||||
let device = udev::Device::from_subsystem_sysname("sound".to_owned(), format!("card{card}"))
|
||||
.map_err(|error| LinuxIdentityError::InspectUdev {
|
||||
card,
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
if property(&device, "ID_BUS").as_deref() != Some("usb") {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(vendor_id), Some(product_id)) = (
|
||||
property(&device, "ID_VENDOR_ID"),
|
||||
property(&device, "ID_MODEL_ID"),
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(UsbDeviceIdentity {
|
||||
vendor_id,
|
||||
product_id,
|
||||
serial: property(&device, "ID_SERIAL_SHORT"),
|
||||
path: property(&device, "ID_PATH"),
|
||||
}))
|
||||
}
|
||||
|
||||
fn property(device: &udev::Device, name: &str) -> Option<String> {
|
||||
device
|
||||
.property_value(name)
|
||||
.map(|value| value.to_string_lossy().into_owned())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_the_alsa_client_from_midir_backend_ids() {
|
||||
assert_eq!(parse_alsa_client("24:3").unwrap(), 24);
|
||||
assert!(matches!(
|
||||
parse_alsa_client("not-an-address"),
|
||||
Err(LinuxIdentityError::InvalidBackendId(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_alsa_client("24:port"),
|
||||
Err(LinuxIdentityError::InvalidBackendId(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
use std::collections::BTreeSet;
|
||||
|
||||
use fader_core::{BindingAction, BindingKey, Bindings, FaderId, Gain, MessageKind, SurfaceId};
|
||||
|
||||
use crate::{ButtonEdge, MidiMessage};
|
||||
|
||||
/// Logical action emitted from one configured physical MIDI control.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum MidiIntent {
|
||||
AbsoluteVolume {
|
||||
surface: SurfaceId,
|
||||
fader: FaderId,
|
||||
gain: Gain,
|
||||
},
|
||||
ToggleMute {
|
||||
surface: SurfaceId,
|
||||
fader: FaderId,
|
||||
},
|
||||
}
|
||||
|
||||
/// Surface-scoped binding lookup with duplicate-press suppression.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MidiRouter {
|
||||
bindings: Bindings,
|
||||
pressed: BTreeSet<BindingKey>,
|
||||
}
|
||||
|
||||
impl MidiRouter {
|
||||
#[must_use]
|
||||
pub fn new(bindings: Bindings) -> Self {
|
||||
Self {
|
||||
bindings,
|
||||
pressed: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Routes a decoded message. Unknown controls, releases, and repeated
|
||||
/// button presses intentionally emit no logical action.
|
||||
pub fn route(&mut self, surface: &SurfaceId, message: MidiMessage) -> Option<MidiIntent> {
|
||||
let (channel, kind, number) = match message {
|
||||
MidiMessage::ControlChange {
|
||||
channel, number, ..
|
||||
} => (channel, MessageKind::ControlChange, number),
|
||||
MidiMessage::Note {
|
||||
channel, number, ..
|
||||
} => (channel, MessageKind::Note, number),
|
||||
};
|
||||
let key = BindingKey {
|
||||
surface: surface.clone(),
|
||||
channel,
|
||||
kind,
|
||||
number,
|
||||
};
|
||||
let binding = self.bindings.get(&key)?.clone();
|
||||
match (binding.action, message) {
|
||||
(BindingAction::Volume, MidiMessage::ControlChange { value, .. }) => {
|
||||
let gain = Gain::new(f64::from(value.get()) / 127.0).ok()?;
|
||||
Some(MidiIntent::AbsoluteVolume {
|
||||
surface: surface.clone(),
|
||||
fader: binding.fader,
|
||||
gain,
|
||||
})
|
||||
}
|
||||
(BindingAction::ToggleMute, MidiMessage::Note { edge, .. }) => {
|
||||
self.route_button(surface, binding.fader, key, edge)
|
||||
}
|
||||
(BindingAction::ToggleMute, MidiMessage::ControlChange { value, .. }) => {
|
||||
let edge = if value.get() == 0 {
|
||||
ButtonEdge::Release
|
||||
} else {
|
||||
ButtonEdge::Press
|
||||
};
|
||||
self.route_button(surface, binding.fader, key, edge)
|
||||
}
|
||||
(BindingAction::Volume, MidiMessage::Note { .. }) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn route_button(
|
||||
&mut self,
|
||||
surface: &SurfaceId,
|
||||
fader: FaderId,
|
||||
key: BindingKey,
|
||||
edge: ButtonEdge,
|
||||
) -> Option<MidiIntent> {
|
||||
match edge {
|
||||
ButtonEdge::Press => self.pressed.insert(key).then(|| MidiIntent::ToggleMute {
|
||||
surface: surface.clone(),
|
||||
fader,
|
||||
}),
|
||||
ButtonEdge::Release => {
|
||||
self.pressed.remove(&key);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,292 @@
|
|||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc::{SyncSender, TrySendError},
|
||||
};
|
||||
|
||||
use fader_core::SurfaceId;
|
||||
use midir::{
|
||||
Ignore, MidiInput, MidiInputConnection as NativeInputConnection, MidiInputPort, MidiOutput,
|
||||
MidiOutputConnection as NativeOutputConnection, MidiOutputPort,
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{DecodeError, MidiMessage, decode_message};
|
||||
|
||||
/// One port reported by midir, retaining its opaque backend handle.
|
||||
pub struct InputPort {
|
||||
id: String,
|
||||
name: String,
|
||||
native: MidiInputPort,
|
||||
}
|
||||
|
||||
impl InputPort {
|
||||
#[must_use]
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for InputPort {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("InputPort")
|
||||
.field("id", &self.id)
|
||||
.field("name", &self.name)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Copied result of one midir callback invocation.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum MidiInputEvent {
|
||||
Message {
|
||||
surface: SurfaceId,
|
||||
timestamp_micros: u64,
|
||||
message: MidiMessage,
|
||||
},
|
||||
Malformed {
|
||||
surface: SurfaceId,
|
||||
timestamp_micros: u64,
|
||||
error: DecodeError,
|
||||
},
|
||||
}
|
||||
|
||||
/// Initialization, discovery, or connection failure at the midir boundary.
|
||||
#[derive(Clone, Debug, Error, Eq, PartialEq)]
|
||||
pub enum MidiTransportError {
|
||||
#[error("could not initialize MIDI input: {0}")]
|
||||
Initialize(String),
|
||||
#[error("could not read MIDI port information: {0}")]
|
||||
PortInfo(String),
|
||||
#[error("could not connect MIDI input: {0}")]
|
||||
Connect(String),
|
||||
#[error("could not initialize MIDI output: {0}")]
|
||||
OutputInitialize(String),
|
||||
#[error("could not read MIDI output port information: {0}")]
|
||||
OutputPortInfo(String),
|
||||
#[error("could not connect MIDI output: {0}")]
|
||||
OutputConnect(String),
|
||||
#[error("could not send MIDI output: {0}")]
|
||||
OutputSend(String),
|
||||
}
|
||||
|
||||
/// One-use midir catalog; connecting consumes it because midir transfers input ownership.
|
||||
pub struct MidiInputCatalog {
|
||||
input: MidiInput,
|
||||
}
|
||||
|
||||
impl MidiInputCatalog {
|
||||
pub fn new(client_name: &str) -> Result<Self, MidiTransportError> {
|
||||
let mut input = MidiInput::new(client_name)
|
||||
.map_err(|error| MidiTransportError::Initialize(error.to_string()))?;
|
||||
input.ignore(Ignore::None);
|
||||
Ok(Self { input })
|
||||
}
|
||||
|
||||
pub fn ports(&self) -> Result<Vec<InputPort>, MidiTransportError> {
|
||||
self.input
|
||||
.ports()
|
||||
.into_iter()
|
||||
.map(|native| {
|
||||
let id = native.id();
|
||||
let name = self
|
||||
.input
|
||||
.port_name(&native)
|
||||
.map_err(|error| MidiTransportError::PortInfo(error.to_string()))?;
|
||||
Ok(InputPort { id, name, native })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Opens one device callback that only parses and nonblockingly enqueues.
|
||||
pub fn connect(
|
||||
self,
|
||||
port: &InputPort,
|
||||
connection_name: &str,
|
||||
surface: SurfaceId,
|
||||
sender: SyncSender<MidiInputEvent>,
|
||||
) -> Result<MidiInputConnection, MidiTransportError> {
|
||||
let overflowed = Arc::new(AtomicBool::new(false));
|
||||
let callback_overflowed = Arc::clone(&overflowed);
|
||||
let connection = self
|
||||
.input
|
||||
.connect(
|
||||
&port.native,
|
||||
connection_name,
|
||||
move |timestamp_micros, bytes, _| {
|
||||
enqueue_bytes(
|
||||
&sender,
|
||||
&callback_overflowed,
|
||||
&surface,
|
||||
timestamp_micros,
|
||||
bytes,
|
||||
);
|
||||
},
|
||||
(),
|
||||
)
|
||||
.map_err(|error| MidiTransportError::Connect(error.to_string()))?;
|
||||
Ok(MidiInputConnection {
|
||||
_connection: connection,
|
||||
overflowed,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn enqueue_bytes(
|
||||
sender: &SyncSender<MidiInputEvent>,
|
||||
overflowed: &AtomicBool,
|
||||
surface: &SurfaceId,
|
||||
timestamp_micros: u64,
|
||||
bytes: &[u8],
|
||||
) {
|
||||
let event = match decode_message(bytes) {
|
||||
Ok(Some(message)) => MidiInputEvent::Message {
|
||||
surface: surface.clone(),
|
||||
timestamp_micros,
|
||||
message,
|
||||
},
|
||||
Ok(None) => return,
|
||||
Err(error) => MidiInputEvent::Malformed {
|
||||
surface: surface.clone(),
|
||||
timestamp_micros,
|
||||
error,
|
||||
},
|
||||
};
|
||||
if matches!(sender.try_send(event), Err(TrySendError::Full(_))) {
|
||||
overflowed.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a midir input open and exposes callback overflow as an explicit fault.
|
||||
pub struct MidiInputConnection {
|
||||
_connection: NativeInputConnection<()>,
|
||||
overflowed: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
/// One MIDI output port reported by midir.
|
||||
pub struct OutputPort {
|
||||
id: String,
|
||||
name: String,
|
||||
native: MidiOutputPort,
|
||||
}
|
||||
|
||||
impl OutputPort {
|
||||
#[must_use]
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
/// One-use midir output catalog.
|
||||
pub struct MidiOutputCatalog {
|
||||
output: MidiOutput,
|
||||
}
|
||||
|
||||
impl MidiOutputCatalog {
|
||||
pub fn new(client_name: &str) -> Result<Self, MidiTransportError> {
|
||||
MidiOutput::new(client_name)
|
||||
.map(|output| Self { output })
|
||||
.map_err(|error| MidiTransportError::OutputInitialize(error.to_string()))
|
||||
}
|
||||
|
||||
pub fn ports(&self) -> Result<Vec<OutputPort>, MidiTransportError> {
|
||||
self.output
|
||||
.ports()
|
||||
.into_iter()
|
||||
.map(|native| {
|
||||
let id = native.id();
|
||||
let name = self
|
||||
.output
|
||||
.port_name(&native)
|
||||
.map_err(|error| MidiTransportError::OutputPortInfo(error.to_string()))?;
|
||||
Ok(OutputPort { id, name, native })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn connect(
|
||||
self,
|
||||
port: &OutputPort,
|
||||
connection_name: &str,
|
||||
) -> Result<MidiOutputConnection, MidiTransportError> {
|
||||
self.output
|
||||
.connect(&port.native, connection_name)
|
||||
.map(|connection| MidiOutputConnection { connection })
|
||||
.map_err(|error| MidiTransportError::OutputConnect(error.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a native MIDI output open for synchronous, short-message writes.
|
||||
pub struct MidiOutputConnection {
|
||||
connection: NativeOutputConnection,
|
||||
}
|
||||
|
||||
impl MidiOutputConnection {
|
||||
pub fn send(&mut self, message: &[u8]) -> Result<(), MidiTransportError> {
|
||||
self.connection
|
||||
.send(message)
|
||||
.map_err(|error| MidiTransportError::OutputSend(error.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl MidiInputConnection {
|
||||
#[must_use]
|
||||
pub fn overflowed(&self) -> bool {
|
||||
self.overflowed.load(Ordering::Acquire)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::mpsc;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn callback_path_never_blocks_and_marks_bounded_overflow() {
|
||||
let (sender, receiver) = mpsc::sync_channel(1);
|
||||
let overflowed = AtomicBool::new(false);
|
||||
let surface = SurfaceId::new("fixture").unwrap();
|
||||
|
||||
enqueue_bytes(&sender, &overflowed, &surface, 10, &[0xb0, 7, 64]);
|
||||
enqueue_bytes(&sender, &overflowed, &surface, 11, &[0x90, 32, 127]);
|
||||
assert!(overflowed.load(Ordering::Acquire));
|
||||
assert!(matches!(
|
||||
receiver.try_recv(),
|
||||
Ok(MidiInputEvent::Message {
|
||||
timestamp_micros: 10,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_reports_malformed_and_discards_clock_traffic() {
|
||||
let (sender, receiver) = mpsc::sync_channel(2);
|
||||
let overflowed = AtomicBool::new(false);
|
||||
let surface = SurfaceId::new("fixture").unwrap();
|
||||
|
||||
enqueue_bytes(&sender, &overflowed, &surface, 20, &[0xb0, 7]);
|
||||
enqueue_bytes(&sender, &overflowed, &surface, 21, &[0xf8]);
|
||||
assert!(matches!(
|
||||
receiver.try_recv(),
|
||||
Ok(MidiInputEvent::Malformed {
|
||||
timestamp_micros: 20,
|
||||
..
|
||||
})
|
||||
));
|
||||
assert!(receiver.try_recv().is_err());
|
||||
assert!(!overflowed.load(Ordering::Acquire));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,242 @@
|
|||
use fader_core::{
|
||||
Binding, BindingAction, BindingKey, Bindings, FaderId, Gain, MessageKind, MidiChannel,
|
||||
MidiData, SurfaceId,
|
||||
};
|
||||
use midi::{ButtonEdge, DecodeError, MidiIntent, MidiMessage, MidiRouter, decode_message};
|
||||
|
||||
fn channel(value: u16) -> MidiChannel {
|
||||
MidiChannel::new(value).unwrap()
|
||||
}
|
||||
|
||||
fn data(value: u16) -> MidiData {
|
||||
MidiData::new(value).unwrap()
|
||||
}
|
||||
|
||||
fn key(surface: &str, kind: MessageKind, number: u16) -> BindingKey {
|
||||
BindingKey {
|
||||
surface: SurfaceId::new(surface).unwrap(),
|
||||
channel: channel(1),
|
||||
kind,
|
||||
number: data(number),
|
||||
}
|
||||
}
|
||||
|
||||
fn binding(fader: &str, action: BindingAction) -> Binding {
|
||||
Binding {
|
||||
fader: FaderId::new(fader).unwrap(),
|
||||
action,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_absolute_cc_across_all_channels_and_endpoints() {
|
||||
for wire_channel in 0_u8..16 {
|
||||
let message = decode_message(&[0xb0 | wire_channel, 7, 127]).unwrap();
|
||||
assert_eq!(
|
||||
message,
|
||||
Some(MidiMessage::ControlChange {
|
||||
channel: channel(u16::from(wire_channel) + 1),
|
||||
number: data(7),
|
||||
value: data(127),
|
||||
})
|
||||
);
|
||||
}
|
||||
assert!(matches!(
|
||||
decode_message(&[0xb0, 0, 0]).unwrap(),
|
||||
Some(MidiMessage::ControlChange { number, value, .. })
|
||||
if number == data(0) && value == data(0)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_on_zero_and_note_off_are_release_edges() {
|
||||
assert!(matches!(
|
||||
decode_message(&[0x90, 32, 100]).unwrap(),
|
||||
Some(MidiMessage::Note {
|
||||
edge: ButtonEdge::Press,
|
||||
..
|
||||
})
|
||||
));
|
||||
for bytes in [[0x90, 32, 0], [0x80, 32, 64]] {
|
||||
assert!(matches!(
|
||||
decode_message(&bytes).unwrap(),
|
||||
Some(MidiMessage::Note {
|
||||
edge: ButtonEdge::Release,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_supported_messages_are_rejected_precisely() {
|
||||
assert_eq!(decode_message(&[]), Err(DecodeError::Empty));
|
||||
assert_eq!(
|
||||
decode_message(&[7, 1, 2]),
|
||||
Err(DecodeError::MissingStatus(7))
|
||||
);
|
||||
assert_eq!(
|
||||
decode_message(&[0xb0, 7]),
|
||||
Err(DecodeError::Length {
|
||||
status: 0xb0,
|
||||
expected: 3,
|
||||
actual: 2,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
decode_message(&[0x90, 0x80, 1]),
|
||||
Err(DecodeError::InvalidData {
|
||||
position: 1,
|
||||
value: 0x80,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
decode_message(&[0xb0, 1, 0xff]),
|
||||
Err(DecodeError::InvalidData {
|
||||
position: 2,
|
||||
value: 0xff,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_and_clock_traffic_is_ignored() {
|
||||
for bytes in [
|
||||
&[0xf8][..],
|
||||
&[0xfe][..],
|
||||
&[0xf0, 1, 2, 0xf7][..],
|
||||
&[0xc0, 3][..],
|
||||
&[0xd0, 4][..],
|
||||
&[0xe0, 0, 64][..],
|
||||
] {
|
||||
assert_eq!(decode_message(bytes).unwrap(), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_routes_to_the_bound_surface_and_normalizes_seven_bits() {
|
||||
let bindings = Bindings::new([
|
||||
(
|
||||
key("left", MessageKind::ControlChange, 7),
|
||||
binding("left-volume", BindingAction::Volume),
|
||||
),
|
||||
(
|
||||
key("right", MessageKind::ControlChange, 7),
|
||||
binding("right-volume", BindingAction::Volume),
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
let mut router = MidiRouter::new(bindings);
|
||||
let message = MidiMessage::ControlChange {
|
||||
channel: channel(1),
|
||||
number: data(7),
|
||||
value: data(127),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
router.route(&SurfaceId::new("left").unwrap(), message),
|
||||
Some(MidiIntent::AbsoluteVolume {
|
||||
surface: SurfaceId::new("left").unwrap(),
|
||||
fader: FaderId::new("left-volume").unwrap(),
|
||||
gain: Gain::UNITY,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
router.route(
|
||||
&SurfaceId::new("right").unwrap(),
|
||||
MidiMessage::ControlChange {
|
||||
channel: channel(1),
|
||||
number: data(7),
|
||||
value: data(0),
|
||||
}
|
||||
),
|
||||
Some(MidiIntent::AbsoluteVolume {
|
||||
surface: SurfaceId::new("right").unwrap(),
|
||||
fader: FaderId::new("right-volume").unwrap(),
|
||||
gain: Gain::SILENCE,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_and_cc_buttons_emit_once_per_press_until_release() {
|
||||
let bindings = Bindings::new([
|
||||
(
|
||||
key("desk", MessageKind::Note, 32),
|
||||
binding("note-mute", BindingAction::ToggleMute),
|
||||
),
|
||||
(
|
||||
key("desk", MessageKind::ControlChange, 33),
|
||||
binding("cc-mute", BindingAction::ToggleMute),
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
let mut router = MidiRouter::new(bindings);
|
||||
let surface = SurfaceId::new("desk").unwrap();
|
||||
let note = |edge| MidiMessage::Note {
|
||||
channel: channel(1),
|
||||
number: data(32),
|
||||
velocity: data(if edge == ButtonEdge::Press { 127 } else { 0 }),
|
||||
edge,
|
||||
};
|
||||
assert!(matches!(
|
||||
router.route(&surface, note(ButtonEdge::Press)),
|
||||
Some(MidiIntent::ToggleMute { .. })
|
||||
));
|
||||
assert_eq!(router.route(&surface, note(ButtonEdge::Press)), None);
|
||||
assert_eq!(router.route(&surface, note(ButtonEdge::Release)), None);
|
||||
assert!(matches!(
|
||||
router.route(&surface, note(ButtonEdge::Press)),
|
||||
Some(MidiIntent::ToggleMute { .. })
|
||||
));
|
||||
|
||||
let cc = |value| MidiMessage::ControlChange {
|
||||
channel: channel(1),
|
||||
number: data(33),
|
||||
value: data(value),
|
||||
};
|
||||
assert!(matches!(
|
||||
router.route(&surface, cc(127)),
|
||||
Some(MidiIntent::ToggleMute { .. })
|
||||
));
|
||||
assert_eq!(router.route(&surface, cc(64)), None);
|
||||
assert_eq!(router.route(&surface, cc(0)), None);
|
||||
assert!(matches!(
|
||||
router.route(&surface, cc(1)),
|
||||
Some(MidiIntent::ToggleMute { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_controls_and_incompatible_bindings_emit_nothing() {
|
||||
let bindings = Bindings::new([(
|
||||
key("desk", MessageKind::Note, 1),
|
||||
binding("invalid-note-volume", BindingAction::Volume),
|
||||
)])
|
||||
.unwrap();
|
||||
let mut router = MidiRouter::new(bindings);
|
||||
let surface = SurfaceId::new("desk").unwrap();
|
||||
assert_eq!(
|
||||
router.route(
|
||||
&surface,
|
||||
MidiMessage::ControlChange {
|
||||
channel: channel(1),
|
||||
number: data(99),
|
||||
value: data(100),
|
||||
}
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
router.route(
|
||||
&surface,
|
||||
MidiMessage::Note {
|
||||
channel: channel(1),
|
||||
number: data(1),
|
||||
velocity: data(100),
|
||||
edge: ButtonEdge::Press,
|
||||
}
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
use midi::{
|
||||
DeviceMatch, MatchBasis, PortIdentity, PortResolution, UsbDeviceIdentity, resolve_port,
|
||||
};
|
||||
|
||||
fn usb(serial: Option<&str>, path: &str) -> UsbDeviceIdentity {
|
||||
UsbDeviceIdentity {
|
||||
vendor_id: "1234".into(),
|
||||
product_id: "5678".into(),
|
||||
serial: serial.map(str::to_owned),
|
||||
path: Some(path.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn port(id: &str, serial: Option<&str>, path: &str) -> PortIdentity {
|
||||
PortIdentity {
|
||||
backend_id: id.into(),
|
||||
name: "Controller MIDI 1".into(),
|
||||
usb: Some(usb(serial, path)),
|
||||
}
|
||||
}
|
||||
|
||||
fn expected(serial: Option<&str>, path: Option<&str>) -> DeviceMatch {
|
||||
DeviceMatch {
|
||||
port_name: "Controller MIDI 1".into(),
|
||||
vendor_id: Some("1234".into()),
|
||||
product_id: Some("5678".into()),
|
||||
serial: serial.map(str::to_owned),
|
||||
path: path.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serial_distinguishes_identical_models_independent_of_port_order() {
|
||||
let ports = vec![
|
||||
port("28:0", Some("RIGHT"), "usb-0:2"),
|
||||
port("24:0", Some("LEFT"), "usb-0:1"),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
resolve_port(&expected(Some("LEFT"), None), &ports, None),
|
||||
PortResolution::Matched {
|
||||
index: 1,
|
||||
basis: MatchBasis::Serial,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physical_path_distinguishes_identical_serialless_models() {
|
||||
let ports = vec![
|
||||
port("28:0", None, "pci-1-usb-0:2"),
|
||||
port("24:0", None, "pci-1-usb-0:1"),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
resolve_port(&expected(None, Some("pci-1-usb-0:2")), &ports, None),
|
||||
PortResolution::Matched {
|
||||
index: 0,
|
||||
basis: MatchBasis::PhysicalPath,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialless_same_model_stays_ambiguous_until_explicitly_selected() {
|
||||
let ports = vec![port("24:0", None, "usb-0:1"), port("28:0", None, "usb-0:2")];
|
||||
let hints = expected(None, None);
|
||||
assert_eq!(
|
||||
resolve_port(&hints, &ports, None),
|
||||
PortResolution::Ambiguous {
|
||||
candidate_indices: vec![0, 1],
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_port(&hints, &ports, Some("28:0")),
|
||||
PortResolution::Matched {
|
||||
index: 1,
|
||||
basis: MatchBasis::Manual,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_selection_cannot_override_model_or_usb_mismatch() {
|
||||
let mut wrong = port("30:0", None, "usb-0:3");
|
||||
wrong.name = "Other Controller".into();
|
||||
assert_eq!(
|
||||
resolve_port(&expected(None, None), &[wrong], Some("30:0")),
|
||||
PortResolution::Missing
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unique_virtual_port_can_fall_back_to_its_name() {
|
||||
let port = PortIdentity {
|
||||
backend_id: "128:0".into(),
|
||||
name: "DAW bridge".into(),
|
||||
usb: None,
|
||||
};
|
||||
let hints = DeviceMatch {
|
||||
port_name: "DAW bridge".into(),
|
||||
vendor_id: None,
|
||||
product_id: None,
|
||||
serial: None,
|
||||
path: None,
|
||||
};
|
||||
assert_eq!(
|
||||
resolve_port(&hints, &[port], None),
|
||||
PortResolution::Matched {
|
||||
index: 0,
|
||||
basis: MatchBasis::UniqueModel,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alsa_numeric_suffix_does_not_defeat_stable_usb_identity() {
|
||||
let actual = PortIdentity {
|
||||
backend_id: "36:0".into(),
|
||||
name: "APC MINI:APC MINI MIDI 1 36:0".into(),
|
||||
usb: Some(UsbDeviceIdentity {
|
||||
vendor_id: "09e8".into(),
|
||||
product_id: "0028".into(),
|
||||
serial: Some("Ver00.10".into()),
|
||||
path: Some("pci-usb-1".into()),
|
||||
}),
|
||||
};
|
||||
let hints = DeviceMatch {
|
||||
port_name: "APC MINI:APC MINI MIDI 1".into(),
|
||||
vendor_id: Some("09e8".into()),
|
||||
product_id: Some("0028".into()),
|
||||
serial: Some("Ver00.10".into()),
|
||||
path: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
resolve_port(&hints, &[actual], None),
|
||||
PortResolution::Matched {
|
||||
index: 0,
|
||||
basis: MatchBasis::Serial,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
use fader_core::SurfaceId;
|
||||
use midi::{
|
||||
DeviceMatch, MatchBasis, PortIdentity, SurfaceAction, SurfaceAssignment, SurfaceLifecycle,
|
||||
SurfaceStatus, UsbDeviceIdentity,
|
||||
};
|
||||
|
||||
fn surface(id: &str, serial: Option<&str>, manual: Option<&str>) -> SurfaceAssignment {
|
||||
SurfaceAssignment {
|
||||
surface: SurfaceId::new(id).unwrap(),
|
||||
expected: DeviceMatch {
|
||||
port_name: "APC MINI MIDI 1".into(),
|
||||
vendor_id: Some("09e8".into()),
|
||||
product_id: Some("0028".into()),
|
||||
serial: serial.map(str::to_owned),
|
||||
path: None,
|
||||
},
|
||||
manual_backend_id: manual.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
fn port(backend_id: &str, serial: Option<&str>, path: &str) -> PortIdentity {
|
||||
PortIdentity {
|
||||
backend_id: backend_id.into(),
|
||||
name: "APC MINI MIDI 1".into(),
|
||||
usb: Some(UsbDeviceIdentity {
|
||||
vendor_id: "09e8".into(),
|
||||
product_id: "0028".into(),
|
||||
serial: serial.map(str::to_owned),
|
||||
path: Some(path.into()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unplug_replug_and_port_reorder_preserve_a_serial_assignment() {
|
||||
let id = SurfaceId::new("left").unwrap();
|
||||
let mut lifecycle = SurfaceLifecycle::new([surface("left", Some("SERIAL"), None)]).unwrap();
|
||||
let first = vec![port("36:0", Some("SERIAL"), "usb-1")];
|
||||
assert!(matches!(
|
||||
lifecycle.reconcile(&first).as_slice(),
|
||||
[SurfaceAction::Connect { backend_id, .. }] if backend_id == "36:0"
|
||||
));
|
||||
lifecycle.connection_succeeded(&id, "36:0").unwrap();
|
||||
assert!(matches!(
|
||||
lifecycle.status(&id),
|
||||
Some(SurfaceStatus::Connected {
|
||||
basis: MatchBasis::Serial,
|
||||
..
|
||||
})
|
||||
));
|
||||
|
||||
assert!(matches!(
|
||||
lifecycle.reconcile(&[]).as_slice(),
|
||||
[SurfaceAction::Disconnect { backend_id, .. }] if backend_id == "36:0"
|
||||
));
|
||||
assert_eq!(lifecycle.status(&id), Some(&SurfaceStatus::Missing));
|
||||
|
||||
let reordered = vec![
|
||||
port("40:0", Some("OTHER"), "usb-2"),
|
||||
port("42:0", Some("SERIAL"), "usb-3"),
|
||||
];
|
||||
assert!(matches!(
|
||||
lifecycle.reconcile(&reordered).as_slice(),
|
||||
[SurfaceAction::Connect { backend_id, .. }] if backend_id == "42:0"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_identical_devices_stay_unassigned_until_manually_selected() {
|
||||
let id = SurfaceId::new("left").unwrap();
|
||||
let ports = vec![port("36:0", None, "usb-1"), port("40:0", None, "usb-2")];
|
||||
let mut unresolved = SurfaceLifecycle::new([surface("left", None, None)]).unwrap();
|
||||
assert!(unresolved.reconcile(&ports).is_empty());
|
||||
assert!(matches!(
|
||||
unresolved.status(&id),
|
||||
Some(SurfaceStatus::Ambiguous { backend_ids }) if backend_ids == &["36:0", "40:0"]
|
||||
));
|
||||
|
||||
let mut manual = SurfaceLifecycle::new([surface("left", None, Some("40:0"))]).unwrap();
|
||||
assert!(matches!(
|
||||
manual.reconcile(&ports).as_slice(),
|
||||
[SurfaceAction::Connect { backend_id, .. }] if backend_id == "40:0"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_connection_failure_does_not_disconnect_another_surface() {
|
||||
let left = SurfaceId::new("left").unwrap();
|
||||
let right = SurfaceId::new("right").unwrap();
|
||||
let ports = vec![
|
||||
port("36:0", Some("LEFT"), "usb-1"),
|
||||
port("40:0", Some("RIGHT"), "usb-2"),
|
||||
];
|
||||
let mut lifecycle = SurfaceLifecycle::new([
|
||||
surface("left", Some("LEFT"), None),
|
||||
surface("right", Some("RIGHT"), None),
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(lifecycle.reconcile(&ports).len(), 2);
|
||||
lifecycle.connection_succeeded(&left, "36:0").unwrap();
|
||||
lifecycle
|
||||
.connection_failed(&right, "40:0", "device busy")
|
||||
.unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
lifecycle.status(&left),
|
||||
Some(SurfaceStatus::Connected { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
lifecycle.status(&right),
|
||||
Some(SurfaceStatus::Error { message, .. }) if message == "device busy"
|
||||
));
|
||||
assert!(matches!(
|
||||
lifecycle.reconcile(&ports).as_slice(),
|
||||
[SurfaceAction::Connect { surface, .. }] if surface == &right
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_configured_surfaces_cannot_claim_the_same_port() {
|
||||
let left = SurfaceId::new("left").unwrap();
|
||||
let right = SurfaceId::new("right").unwrap();
|
||||
let ports = vec![port("36:0", Some("SHARED"), "usb-1")];
|
||||
let assignment = surface("left", Some("SHARED"), None);
|
||||
let mut duplicate = assignment.clone();
|
||||
duplicate.surface = right.clone();
|
||||
let mut lifecycle = SurfaceLifecycle::new([assignment, duplicate]).unwrap();
|
||||
|
||||
assert!(lifecycle.reconcile(&ports).is_empty());
|
||||
assert!(matches!(
|
||||
lifecycle.status(&left),
|
||||
Some(SurfaceStatus::Ambiguous { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
lifecycle.status(&right),
|
||||
Some(SurfaceStatus::Ambiguous { .. })
|
||||
));
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
fail() {
|
||||
echo "$*" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
[ "$#" -ge 1 ] || fail "usage: $0 <gitea-token-file> [rust_realease options...]"
|
||||
token_file=$1
|
||||
shift
|
||||
[ -f "$token_file" ] && [ -r "$token_file" ] || fail "token file must be a readable regular file"
|
||||
for tool in rust_realease cargo jq; do
|
||||
command -v "$tool" >/dev/null 2>&1 || fail "$tool is not installed or not available in PATH"
|
||||
done
|
||||
|
||||
unset GITEA_TOKEN
|
||||
GITEA_TOKEN=
|
||||
IFS= read -r GITEA_TOKEN <"$token_file" || :
|
||||
[ -n "$GITEA_TOKEN" ] || fail "token file has an empty first line"
|
||||
|
||||
repository_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
# Query the member's resolved version, including workspace inheritance. Keep the
|
||||
# token unexported until Cargo has finished; it belongs only to the publisher.
|
||||
metadata=$(cargo metadata --offline --no-deps --format-version 1 \
|
||||
--manifest-path "$repository_dir/Cargo.toml") || fail "could not read Cargo metadata"
|
||||
manifest_version=$(printf '%s\n' "$metadata" | jq -er \
|
||||
'[.packages[] | select(.name == "fader_master") | .version] |
|
||||
if length == 1 and (.[0] | type == "string" and length > 0)
|
||||
then .[0] else error("unresolved package version") end') \
|
||||
|| fail "could not determine fader_master package version"
|
||||
|
||||
set -- "$repository_dir" --package fader_master --artifact-format both "$@"
|
||||
case "$manifest_version" in
|
||||
*-*) set -- "$@" --prerelease ;;
|
||||
esac
|
||||
export GITEA_TOKEN
|
||||
exec rust_realease "$@"
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
[release]
|
||||
tag-prefix = "v"
|
||||
|
||||
[build]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
profile = "release"
|
||||
locked = true
|
||||
|
||||
[package]
|
||||
format = "both"
|
||||
|
||||
[[repository.fallbacks]]
|
||||
origin = "git@git.dandaedre.com:MadGobblins/fader_master.git"
|
||||
fallback-url = "https://proxy.dandaedre.com/gitea/MadGobblins/fader_master"
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
[toolchain]
|
||||
channel = "1.88.0"
|
||||
profile = "minimal"
|
||||
components = ["clippy", "llvm-tools-preview", "rustfmt"]
|
||||
|
|
@ -54,7 +54,12 @@ for badge in $expected; do
|
|||
exit 1
|
||||
}
|
||||
done
|
||||
actual_count=$(find coverage -maxdepth 1 -name '*.svg' | wc -l)
|
||||
actual_count=0
|
||||
for candidate in coverage/*.svg; do
|
||||
if [ -e "$candidate" ] || [ -L "$candidate" ]; then
|
||||
actual_count=$((actual_count + 1))
|
||||
fi
|
||||
done
|
||||
[ "$actual_count" -eq 3 ] || {
|
||||
echo "expected exactly three SVG badges, found $actual_count" >&2
|
||||
exit 1
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ fail() {
|
|||
assert_contains() {
|
||||
file=$1
|
||||
expected=$2
|
||||
grep -F "$expected" "$file" >/dev/null || fail "$file does not contain: $expected"
|
||||
grep -F -- "$expected" "$file" >/dev/null || fail "$file does not contain: $expected"
|
||||
}
|
||||
|
||||
assert_fails() {
|
||||
|
|
@ -22,6 +22,36 @@ assert_fails() {
|
|||
fi
|
||||
}
|
||||
|
||||
file_mode() {
|
||||
if stat -c '%a' "$1" >/dev/null 2>&1; then
|
||||
stat -c '%a' "$1"
|
||||
else
|
||||
stat -f '%Lp' "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
assert_contains "$repository/Jenkinsfile" "name: 'ENABLE_NATIVE_BACKENDS'"
|
||||
assert_contains "$repository/Jenkinsfile" 'defaultValue: false'
|
||||
assert_contains "$repository/Jenkinsfile" 'ENABLE_NATIVE_BACKENDS = "${params.ENABLE_NATIVE_BACKENDS ?: false}"'
|
||||
assert_contains "$repository/Jenkinsfile" "stage('Portable Rust Gates')"
|
||||
assert_contains "$repository/Jenkinsfile" '!params.ENABLE_NATIVE_BACKENDS'
|
||||
assert_contains "$repository/Jenkinsfile" 'params.ENABLE_NATIVE_BACKENDS'
|
||||
assert_contains "$repository/Jenkinsfile" 'cargo test -p fader-core -p fader-config -p midi -p volume_lib -p tui'
|
||||
assert_contains "$repository/Jenkinsfile" 'dbus-run-session -- cargo test -p fader_master private_bus --locked -- --ignored'
|
||||
assert_contains "$repository/Jenkinsfile" 'pkg-config --exists alsa libpulse libudev dbus-1'
|
||||
assert_contains "$repository/Jenkinsfile" '-p tui -p media'
|
||||
|
||||
svg_count() {
|
||||
directory=$1
|
||||
count=0
|
||||
for candidate in "$directory"/*.svg; do
|
||||
if [ -e "$candidate" ] || [ -L "$candidate" ]; then
|
||||
count=$((count + 1))
|
||||
fi
|
||||
done
|
||||
printf '%s\n' "$count"
|
||||
}
|
||||
|
||||
renderer="$repository/scripts/ci-coverage-badges.sh"
|
||||
render_dir="$workspace/render"
|
||||
mkdir "$render_dir"
|
||||
|
|
@ -153,7 +183,7 @@ assert_contains "$finalize_work/coverage/coverage.svg" '#9f9f9f'
|
|||
assert_contains "$finalize_work/coverage/test.svg" 'passing'
|
||||
assert_contains "$finalize_work/coverage/version.svg" '1.2.3'
|
||||
[ ! -e "$finalize_work/coverage/.tests-passed-local" ] || fail 'test marker survived finalization'
|
||||
[ "$(find "$finalize_work/coverage" -maxdepth 1 -name '*.svg' | wc -l)" -eq 3 ] \
|
||||
[ "$(svg_count "$finalize_work/coverage")" -eq 3 ] \
|
||||
|| fail 'finalization did not leave exactly three SVG files'
|
||||
|
||||
printf '<svg>fresh measurement</svg>\n' >"$finalize_work/coverage/coverage.svg"
|
||||
|
|
@ -178,11 +208,11 @@ done
|
|||
"$repository/scripts/ci-publish-badges.sh" "$publish_root" MadGobblins fader_master main coverage test version
|
||||
)
|
||||
destination="$publish_root/MadGobblins/fader_master/main"
|
||||
[ "$(stat -c '%a' "$publish_root/MadGobblins")" = 755 ] || fail 'owner mode is not 0755'
|
||||
[ "$(stat -c '%a' "$publish_root/MadGobblins/fader_master")" = 755 ] || fail 'project mode is not 0755'
|
||||
[ "$(stat -c '%a' "$destination")" = 755 ] || fail 'branch mode is not 0755'
|
||||
[ "$(file_mode "$publish_root/MadGobblins")" = 755 ] || fail 'owner mode is not 0755'
|
||||
[ "$(file_mode "$publish_root/MadGobblins/fader_master")" = 755 ] || fail 'project mode is not 0755'
|
||||
[ "$(file_mode "$destination")" = 755 ] || fail 'branch mode is not 0755'
|
||||
for badge_name in coverage test version; do
|
||||
[ "$(stat -c '%a' "$destination/$badge_name.svg")" = 644 ] || fail "$badge_name mode is not 0644"
|
||||
[ "$(file_mode "$destination/$badge_name.svg")" = 644 ] || fail "$badge_name mode is not 0644"
|
||||
done
|
||||
|
||||
assert_fails sh -c "cd '$publish_work' && '$repository/scripts/ci-publish-badges.sh' '$publish_root' MadGobblins fader_master main coverage coverage"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,130 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Offline contract tests: never invoke the real publisher or use real tokens."""
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ReleaseWrapper(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="fader release tests ")
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.repo = self.base / "repository with spaces"
|
||||
self.repo.mkdir()
|
||||
shutil.copy(ROOT / "release.sh", self.repo)
|
||||
shutil.copy(ROOT / "rust-release.toml", self.repo)
|
||||
self.bin = self.base / "bin"
|
||||
self.bin.mkdir()
|
||||
# Restricted PATH also makes the missing-publisher case deterministic.
|
||||
for command in ("dirname", "jq"):
|
||||
(self.bin / command).symlink_to(shutil.which(command))
|
||||
self.script("cargo", '''#!/bin/sh
|
||||
test "${GITEA_TOKEN+x}" != x || exit 98
|
||||
test "$*" = "metadata --offline --no-deps --format-version 1 --manifest-path $EXPECTED_REPO/Cargo.toml" || exit 99
|
||||
printf '{"packages":[{"name":"fader_master","version":"%s"}]}\n' "$TEST_VERSION"
|
||||
''')
|
||||
self.script("rust_realease", '''#!/bin/sh
|
||||
test "$GITEA_TOKEN" = "fixture-secret" || exit 91
|
||||
test "$1" = "$EXPECTED_REPO" || exit 92
|
||||
test "$2" = --package && test "$3" = fader_master || exit 93
|
||||
test "$4" = --artifact-format && test "$5" = both || exit 94
|
||||
test -f "$1/rust-release.toml" || exit 95
|
||||
shift 5
|
||||
printf '<%s>\n' "$@"
|
||||
exit "$TEST_EXIT"
|
||||
''')
|
||||
self.token = self.base / "token with spaces"
|
||||
self.token.write_text("fixture-secret\nignored second line\n")
|
||||
self.env = dict(os.environ, PATH=str(self.bin), EXPECTED_REPO=str(self.repo),
|
||||
TEST_VERSION="0.1.0", TEST_EXIT="0", GITEA_TOKEN="inherited-token")
|
||||
|
||||
def script(self, name, content):
|
||||
path = self.bin / name
|
||||
path.write_text(content)
|
||||
path.chmod(0o755)
|
||||
|
||||
def run_wrapper(self, *args):
|
||||
result = subprocess.run(["/bin/sh", str(self.repo / "release.sh"), *map(str, args)],
|
||||
cwd=self.base, env=self.env, text=True, capture_output=True)
|
||||
self.assertNotIn("fixture-secret", result.stdout + result.stderr)
|
||||
return result
|
||||
|
||||
def test_stable_and_exact_forwarding(self):
|
||||
result = self.run_wrapper(self.token, "--dry-run", "option with spaces", "*literal*")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, "<--dry-run>\n<option with spaces>\n<*literal*>\n")
|
||||
|
||||
def test_prerelease_and_exit_status(self):
|
||||
self.env.update(TEST_VERSION="0.2.0-rc.1", TEST_EXIT="37")
|
||||
result = self.run_wrapper(self.token, "--dry-run")
|
||||
self.assertEqual(result.returncode, 37)
|
||||
self.assertEqual(result.stdout, "<--dry-run>\n<--prerelease>\n")
|
||||
|
||||
def test_invalid_token(self):
|
||||
self.assertEqual(self.run_wrapper().returncode, 2)
|
||||
self.assertEqual(self.run_wrapper(self.base / "missing").returncode, 2)
|
||||
self.assertEqual(self.run_wrapper(self.base).returncode, 2)
|
||||
self.token.write_text("")
|
||||
self.assertEqual(self.run_wrapper(self.token).returncode, 2)
|
||||
self.token.write_text("\nsecond line")
|
||||
self.assertEqual(self.run_wrapper(self.token).returncode, 2)
|
||||
self.token.write_text("fixture-secret")
|
||||
self.token.chmod(0)
|
||||
if os.geteuid() != 0:
|
||||
self.assertEqual(self.run_wrapper(self.token).returncode, 2)
|
||||
|
||||
def test_no_trailing_newline(self):
|
||||
self.token.write_text("fixture-secret")
|
||||
self.assertEqual(self.run_wrapper(self.token, "--dry-run").returncode, 0)
|
||||
|
||||
def test_missing_publisher(self):
|
||||
(self.bin / "rust_realease").unlink()
|
||||
self.assertEqual(self.run_wrapper(self.token).returncode, 2)
|
||||
|
||||
def test_unresolved_version(self):
|
||||
self.env["TEST_VERSION"] = ""
|
||||
self.assertEqual(self.run_wrapper(self.token).returncode, 2)
|
||||
self.script("cargo", "#!/bin/sh\nexit 1\n")
|
||||
self.assertEqual(self.run_wrapper(self.token).returncode, 2)
|
||||
|
||||
def test_fallback_does_not_change_origin(self):
|
||||
git = shutil.which("git")
|
||||
subprocess.run([git, "init", "-q", self.repo], check=True)
|
||||
origin = "git@git.dandaedre.com:MadGobblins/fader_master.git"
|
||||
subprocess.run([git, "-C", self.repo, "remote", "add", "origin", origin], check=True)
|
||||
self.assertEqual(self.run_wrapper(self.token, "--dry-run").returncode, 0)
|
||||
actual = subprocess.check_output([git, "-C", self.repo, "remote", "get-url", "origin"], text=True)
|
||||
self.assertEqual(actual.strip(), origin)
|
||||
config = (self.repo / "rust-release.toml").read_text()
|
||||
self.assertIn('origin = "' + origin + '"', config)
|
||||
self.assertIn('fallback-url = "https://proxy.dandaedre.com/gitea/MadGobblins/fader_master"', config)
|
||||
|
||||
def test_real_workspace_version_query(self):
|
||||
(self.bin / "cargo").unlink()
|
||||
env = dict(self.env, PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
|
||||
EXPECTED_REPO=str(ROOT))
|
||||
result = subprocess.run([str(ROOT / "release.sh"), str(self.token), "--dry-run"],
|
||||
cwd=self.base, env=env, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
metadata = json.loads(subprocess.check_output(
|
||||
["cargo", "metadata", "--offline", "--no-deps", "--format-version", "1"],
|
||||
cwd=ROOT, text=True))
|
||||
version = next(package["version"] for package in metadata["packages"]
|
||||
if package["name"] == "fader_master")
|
||||
expected = "<--dry-run>\n"
|
||||
if "-" in version:
|
||||
expected += "<--prerelease>\n"
|
||||
self.assertEqual(result.stdout, expected)
|
||||
self.assertNotIn("fixture-secret", result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -1,6 +1,21 @@
|
|||
[package]
|
||||
name = "volume_lib"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["pulse"]
|
||||
pulse = ["dep:libpulse-binding"]
|
||||
|
||||
[dependencies]
|
||||
fader-core.workspace = true
|
||||
libpulse-binding = { workspace = true, optional = true }
|
||||
thiserror.workspace = true
|
||||
|
||||
[[example]]
|
||||
name = "pulse_fixture"
|
||||
required-features = ["pulse"]
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue