Add moonmix: pavucontrol-style PipeWire mixer in MoonBit (WirePlumber + GTK4) #1

Merged
nandi merged 11 commits from geordi/moonmix-v1 into main 2026-11-22 23:52:37 +00:00
36 changed files with 3789 additions and 1 deletions

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
name: CI
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
# Pure MoonBit: type-check every package and run the model tests.
# Needs no audio/GUI libraries, so it runs on the default runner image
# (node:20-bullseye-like).
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install MoonBit
run: |
curl -fsSL --retry 5 https://cli.moonbitlang.com/install/unix.sh | bash
echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
- name: moon check (all packages, no C compilation)
run: |
moon version --all
moon check --target native --deny-warn
moon fmt --check
# Native tests run in the trixie job: linking MoonBit's runtime needs
# -lpthread on bullseye's glibc 2.31.
- name: moon test (pure packages)
run: moon test --target wasm-gc
# Native build + headless smoke test. Debian bullseye (the default runner
# image) has no libwireplumber-0.5 and a too-old GTK4, so this job runs in
# a debian:trixie container (PipeWire 1.4, WirePlumber 0.5, GTK 4.18).
# The container has no Node, so actions/checkout cannot run; clone with git.
native:
runs-on: ubuntu-latest
container:
image: debian:trixie
steps:
- name: Install build and test dependencies
run: |
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
ca-certificates curl git build-essential pkg-config \
libpipewire-0.3-dev libwireplumber-0.5-dev libgtk-4-dev \
pipewire pipewire-bin wireplumber libgtk-4-bin \
adwaita-icon-theme fonts-dejavu-core
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git init -q .
git -c http.extraHeader="Authorization: token $TOKEN" \
fetch -q --depth 1 "${{ github.server_url }}/${{ github.repository }}.git" "${{ github.sha }}"
git checkout -q FETCH_HEAD
- name: Install MoonBit
run: |
curl -fsSL --retry 5 https://cli.moonbitlang.com/install/unix.sh | bash
echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
- name: Build (native, links PipeWire/WirePlumber/GTK4)
run: |
moon test --target native -p model
moon build --target native
ldd _build/native/debug/build/cmd/moonmix/moonmix.exe | grep -E 'wireplumber|pipewire|gtk-4'
- name: Smoke test (private PipeWire + WirePlumber, broadway screenshots)
run: |
mkdir -p screenshots
tools/smoke-test.sh "$PWD/screenshots/moonmix"
ls -l screenshots
+6
View File
@@ -0,0 +1,6 @@
_build/
target/
.mooncakes/
.moonagent/
*.o
/screenshots/tmp/
+15
View File
@@ -0,0 +1,15 @@
# Sweet repository configuration
types:
fix:
bump: patch
section: Fixes
feature:
bump: minor
section: Features
chore:
bump: none
refactor:
bump: none
performance:
bump: patch
section: Performance
+6
View File
@@ -0,0 +1,6 @@
# Sweet package configuration
name: moonmix
version: 0.1.0
version-files:
- path: moon.mod
format: annotated
+154 -1
View File
@@ -1,3 +1,156 @@
# moonmix
PipeWire/WirePlumber volume control GUI (pavucontrol-like) in MoonBit
A pavucontrol-style volume control for modern Linux audio (PipeWire with
WirePlumber), written in [MoonBit](https://www.moonbitlang.com) with a GTK4
GUI.
moonmix talks to the audio stack **through its libraries**: libwireplumber-0.5
on top of libpipewire-0.3. It never runs `wpctl`, `pactl`, `pw-cli`,
`pw-dump` or any other CLI tool.
| Playback | Output Devices |
| --- | --- |
| ![Playback tab](docs/screenshots/playback.png) | ![Output Devices tab](docs/screenshots/output-devices.png) |
| **Recording** | **Input Devices** |
| ![Recording tab](docs/screenshots/recording.png) | ![Input Devices tab](docs/screenshots/input-devices.png) |
*(Rendered headlessly against a private PipeWire with null sinks; see
[Testing](#testing).)*
## Features (v1)
- **Playback**: every application stream, with a volume slider, mute and the
output device it plays to (choose another to move it).
- **Recording**: capture streams, same controls, input device selector.
- **Output Devices** / **Input Devices**: sinks and sources with volume, mute
and a *Default* toggle that shows and sets the default device.
- Volumes in percent exactly like pavucontrol/wpctl: the cubic mapping of
PipeWire's linear `channelVolumes`, up to 150%, with the dB value next to
it. One slider moves all channels, keeping the channel balance.
- Live updates: devices and streams appearing, disappearing or changing
elsewhere (another mixer, keyboard volume keys, a new Bluetooth headset)
show up immediately.
Not yet included: the Configuration tab (card profiles), per-channel
sliders, peak meters, monitor sources in Input Devices.
## Architecture
```
cmd/moonmix GUI: builds tabs, reconciles widgets with view rows
cmd/moonmix-probe headless CLI over the same stack (smoke tests, debugging)
model/ pure MoonBit: volume curve, state reducer, view model
wp/ WirePlumber binding: wp_stub.c + wp.mbt
gtk/ minimal hand-written GTK4 binding: gtk_stub.c + gtk.mbt
tools/pkg-cc C compiler wrapper that adds pkg-config flags
```
```mermaid
flowchart LR
PW[(PipeWire)] <--> WP[libwireplumber<br/>mixer-api, default-nodes-api,<br/>object manager]
WP -- "(kind, id) events" --> WPB[wp package]
WPB -- "model.Event" --> S[model.State.apply]
S --> V[model.rows / diff_rows]
V --> G[GTK4 widgets]
G -- "set volume / mute / default / move" --> WPB
```
- **WirePlumber, not raw PipeWire.** The C layer (`wp/wp_stub.c`, about 460
lines) does what `wpctl` does internally. A `WpObjectManager` watches audio
nodes, links and the `default` metadata. The **mixer-api** plugin reads and
writes volume and mute; for hardware sinks it goes through the device's
route, which is where pavucontrol's numbers live. The **default-nodes-api**
plugin reads and sets the default sink and source. To move a stream,
moonmix sets `target.object` in the `default` metadata, as pipewire-pulse
does for pavucontrol. The C layer sends MoonBit one callback per change,
`(kind, id)`. MoonBit then pulls node properties and volumes through small
accessor functions, so no C structs cross the FFI boundary.
- **One main loop.** WirePlumber and GTK4 both run on the default GLib main
context, so events arrive on the GUI thread with no locking or polling.
- **Pure core.** Everything else is plain MoonBit in `model/`: the cubic and
linear conversions, dB formatting, linked-slider scaling, the reducer that
applies node, link and default events, the per-tab rows, and the row diff
the GUI applies. `moon test` covers it on any target.
- **GTK binding.** It is hand-written and minimal. Each widget gets a tag
when it is created, and signals come back as `(tag, value)` through a
single callback. While MoonBit updates widgets from the model, signals are
suppressed so model updates never echo back into PipeWire. For a short
time after the user moves a slider, remote updates to that slider are
ignored so it doesn't jump while being dragged.
## Building
### Dependencies
You need MoonBit (`curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash`,
then add `~/.moon/bin` to `PATH`), a C compiler, `pkg-config` and the
development files:
| Distro | Packages |
| --- | --- |
| Arch | `pipewire wireplumber gtk4 pkgconf base-devel` |
| Debian 13+ / Ubuntu 24.04+ | `build-essential pkg-config libpipewire-0.3-dev libwireplumber-0.5-dev libgtk-4-dev` |
| Fedora (untested) | `gcc pkgconf-pkg-config pipewire-devel wireplumber-devel gtk4-devel` |
You need WirePlumber **0.5** and GTK **4.12** or newer. Debian 11 and 12
ship WirePlumber 0.4, which is not supported.
### Build and run
```sh
moon build --target native --release
./_build/native/release/build/cmd/moonmix/moonmix.exe
```
To install it for your user:
```sh
install -Dm755 _build/native/release/build/cmd/moonmix/moonmix.exe ~/.local/bin/moonmix
install -Dm644 data/org.latha.moonmix.desktop ~/.local/share/applications/org.latha.moonmix.desktop
```
Pkg-config flags: moon does not expand `$(pkg-config ...)` in `moon.pkg`
link options. Instead, the packages point `link.native.stub-cc` and `cc` at
`tools/pkg-cc`, a wrapper that adds
`pkg-config --cflags --libs libpipewire-0.3 wireplumber-0.5 gtk4`. moon
derives the archiver name from the compiler name, so `tools/pkg-ar` is a
passthrough to `ar`. Set `MOONMIX_CC` or `MOONMIX_AR` to use another
compiler or archiver.
### Headless probe
`moonmix-probe` uses the same binding and model without a GUI:
```sh
P=./_build/native/debug/build/cmd/moonmix-probe/moonmix-probe.exe
$P # print what every tab shows
$P volume alsa_output.pci-0000_00_1f.3.analog-stereo 40
$P mute 57 1 # node id or node.name
$P default bluez_output.XX_XX.1
$P move <stream-id> <sink-id-or-name>
```
## Testing
```sh
moon test --target wasm-gc # pure model tests, no libraries needed
moon check --target native # type-check everything
tools/smoke-test.sh /tmp/shot # needs pipewire, wireplumber, pw-cat, gtk4-broadwayd
```
`tools/smoke-test.sh` starts a private PipeWire and WirePlumber in a temp
`XDG_RUNTIME_DIR`. The instance has two null sinks, a loopback virtual
microphone, and one playback and one capture stream created with `pw-cat`; the CLI is used only
by the test harness. The script runs every probe action and checks its effect,
then starts the GUI under GTK's broadway backend. With `MOONMIX_SCREENSHOT`
set, the GUI renders each tab offscreen to a PNG and exits.
CI (`.gitea/workflows/ci.yaml`) runs the pure checks on the default runner.
It runs the native build and the smoke test in a `debian:trixie` container,
because bullseye has no WirePlumber 0.5.
## Releases
Versioning uses [sweet](.sweet.yml): add a change note with `sweet change`
and prepare releases with `sweet bump`. The version lives in `moon.mod` (the
`// sweet-version` line).
+146
View File
@@ -0,0 +1,146 @@
// moonmix-probe: headless companion to the GUI. Connects through the same
// WirePlumber binding and model, prints what each tab would show, and can
// apply one action. Used for smoke tests and debugging without a display.
//
// moonmix-probe print all tabs
// <id> may be a numeric node id or a node.name.
//
// moonmix-probe volume <id> <pct> set linked volume (cubic %)
// moonmix-probe mute <id> <0|1>
// moonmix-probe default <id> make sink/source the default
// moonmix-probe move <stream> <dev> route a stream to a device
///|
extern "C" fn c_exit(code : Int32) = "exit"
///|
fn print_state(state : @model.State) -> Unit {
for tab in @model.Tab::all() {
println("== \{tab.label()}")
let rows = @model.rows(state, tab)
if rows.length() == 0 {
println(" (none)")
}
for r in rows {
let flags = []
if r.is_default {
flags.push("default")
}
if r.mute {
flags.push("muted")
}
if r.current_choice >= 0 {
flags.push("-> " + r.choices[r.current_choice].label)
}
let vol = if r.has_volume { r.volume_text } else { "(no volume)" }
let f = if flags.length() > 0 {
" [" + flags.join(", ") + "]"
} else {
""
}
println(" \{r.id}: \{r.title} | \{vol} | ch=\{r.volumes.length()}\{f}")
}
}
}
///|
fn parse(s : String) -> Double {
@string.parse_double(s) catch {
_ => {
println("moonmix-probe: not a number: \{s}")
c_exit(2)
0.0
}
}
}
///|
/// Node id from a number or a node.name.
fn resolve(state : @model.State, s : String) -> Int32 {
for id, n in state.nodes {
if n.name == s {
return id
}
}
parse(s).to_int()
}
///|
fn act(state : @model.State, args : Array[String]) -> Bool {
match args {
["volume", id, pct] => {
let id = resolve(state, id)
let vols = match state.nodes.get(id) {
Some(n) => n.volumes
None => []
}
@wp.set_volumes(id, @model.scale_linked(vols, parse(pct)))
}
["mute", id, on] => @wp.set_mute(resolve(state, id), on == "1")
["default", id] => {
let id = resolve(state, id)
match state.nodes.get(id).map(fn(n) { n.kind() }) {
Some(Sink) => @wp.set_default_sink(id)
Some(Source) => @wp.set_default_source(id)
_ => false
}
}
["move", stream, dev] =>
@wp.move_stream(resolve(state, stream), resolve(state, dev))
_ => {
println("moonmix-probe: unknown command")
false
}
}
}
///|
fn main {
let argv = @env.args()
let args = if argv.length() > 1 { argv[1:].to_owned() } else { [] }
let state = @model.State::new()
@wp.on_event(fn(ev) {
for e in @wp.to_model_events(ev) {
let _ = state.apply(e)
}
match ev {
// default-nodes-api reports defaults shortly after Ready: settle first.
Ready => @wp.timeout(300, 2)
Timeout(2) => {
print_state(state)
if args.length() > 0 {
let ok = act(state, args)
println(
"== action \{args.join(" ")}: \{if ok { "ok" } else { "FAILED" }}",
)
@wp.timeout(800, 1)
} else {
@wp.quit()
}
}
Timeout(1) => {
print_state(state)
@wp.quit()
}
PluginError => {
println("moonmix-probe: WirePlumber API modules failed to load")
c_exit(3)
}
Disconnected => {
println("moonmix-probe: disconnected")
c_exit(4)
}
Timeout(99) => {
println("moonmix-probe: timed out waiting for WirePlumber")
c_exit(5)
}
_ => ()
}
})
if !@wp.start() {
println("moonmix-probe: cannot connect to PipeWire")
c_exit(1)
}
@wp.timeout(10000, 99)
@wp.run()
}
+15
View File
@@ -0,0 +1,15 @@
// Headless probe: prints what each tab shows, can apply one action.
import {
"geordi/moonmix/model",
"geordi/moonmix/wp",
"moonbitlang/core/env",
"moonbitlang/core/string",
}
supported_targets = "-all+native"
pkgtype(kind: "executable")
options(
link: { "native": { "cc": "tools/pkg-cc" } },
)
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "geordi/moonmix/cmd/moonmix-probe"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+390
View File
@@ -0,0 +1,390 @@
// moonmix GUI: pavucontrol-style tabs over the WirePlumber state.
//
// Data flow: WirePlumber event -> @wp.to_model_events -> State::apply ->
// @model.rows per tab -> @model.diff_rows -> create/update/remove widgets.
// User actions go straight to @wp setters; the resulting change comes back
// as a normal event.
///|
extern "C" fn c_exit(code : Int32) = "exit"
///|
/// Widgets of one row (a stream or a device).
struct RowView {
root : @gtk.Widget
icon : @gtk.Widget
title : @gtk.Widget
subtitle : @gtk.Widget
scale : @gtk.Widget
volume_label : @gtk.Widget
mute : @gtk.Widget
default_btn : @gtk.Widget?
device : @gtk.Widget?
tags : Array[Int32]
mut row : @model.Row
mut last_local_us : Int64
}
///|
struct TabView {
tab : @model.Tab
list : @gtk.Widget
empty : @gtk.Widget
views : Map[Int32, RowView]
mut rows : Array[@model.Row]
}
///|
struct App {
state : @model.State
tabs : Array[TabView]
status : @gtk.Widget
window : @gtk.Widget
notebook : @gtk.Widget
}
///|
const CSS : String =
#|.mm-title { font-weight: bold; }
#|.mm-subtitle { opacity: 0.7; font-size: smaller; }
#|.mm-row { padding: 6px 12px; }
#|.mm-status { padding: 4px 8px; opacity: 0.8; font-size: smaller; }
///|
fn mute_icon(muted : Bool) -> String {
if muted {
"audio-volume-muted-symbolic"
} else {
"audio-volume-high-symbolic"
}
}
///|
fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
let id = row.id
let tags = []
let root = @gtk.vbox(4)
root.add_css_class("mm-row")
let header = @gtk.hbox(8)
let icon = @gtk.image(row.icon_name, 32)
let texts = @gtk.vbox(0)
texts.set_hexpand(true)
texts.set_valign_center()
let title = @gtk.label(row.title)
title.add_css_class("mm-title")
let subtitle = @gtk.label(row.subtitle)
subtitle.add_css_class("mm-subtitle")
texts.append(title)
texts.append(subtitle)
header.append(icon)
header.append(texts)
// Streams: device selector. Devices: "default" toggle.
let device = match tab {
Playback | Recording => {
let (dd, tag) = @gtk.dropdown(fn(idx) {
match app.find_view(tab, id) {
Some(v) =>
if idx >= 0 && idx < v.row.choices.length() {
let _ = @wp.move_stream(id, v.row.choices[idx].id)
}
None => ()
}
})
tags.push(tag)
dd.set_tooltip(
if tab is Playback {
"Output device"
} else {
"Input device"
},
)
header.append(dd)
Some(dd)
}
_ => None
}
let default_btn = match tab {
OutputDevices | InputDevices => {
let (b, tag) = @gtk.toggle("object-select-symbolic", "Default", fn(on) {
if on {
let _ = if tab is OutputDevices {
@wp.set_default_sink(id)
} else {
@wp.set_default_source(id)
}
}
// The button reflects the actual default; re-sync it.
app.sync_default_button(tab, id)
})
tags.push(tag)
b.set_tooltip("Set as default (fallback) device")
header.append(b)
Some(b)
}
_ => None
}
let (mute, mute_tag) = @gtk.toggle(mute_icon(row.mute), "", fn(on) {
let _ = @wp.set_mute(id, on)
})
tags.push(mute_tag)
mute.set_tooltip("Mute")
header.append(mute)
root.append(header)
let slider_row = @gtk.hbox(8)
let volume_label = @gtk.label(row.volume_text)
volume_label.set_width_chars(16)
let (scale, scale_tag) = @gtk.scale(@model.MAX_PERCENT, @model.NORM_PERCENT, fn(
percent,
) {
match app.find_view(tab, id) {
Some(v) => {
let vols = @model.scale_linked(v.row.volumes, percent)
v.last_local_us = @gtk.now_us()
v.volume_label.set_text(@model.format_volume(vols))
let _ = @wp.set_volumes(id, vols)
}
None => ()
}
})
tags.push(scale_tag)
slider_row.append(scale)
slider_row.append(volume_label)
root.append(slider_row)
let view = {
root,
icon,
title,
subtitle,
scale,
volume_label,
mute,
default_btn,
device,
tags,
row,
last_local_us: 0L,
}
apply_row(view, row, force=true)
view
}
///|
/// Push a row's data into its widgets (signals suppressed).
fn apply_row(view : RowView, row : @model.Row, force~ : Bool = false) -> Unit {
let old = view.row
view.row = row
@gtk.updating(fn() {
if force || old.title != row.title {
view.title.set_text(row.title)
}
if force || old.subtitle != row.subtitle {
view.subtitle.set_text(row.subtitle)
view.subtitle.set_visible(row.subtitle != "")
}
if force || old.icon_name != row.icon_name {
view.icon.set_icon(row.icon_name)
}
view.scale.set_sensitive(row.has_volume)
if force || @model.should_apply_remote(view.last_local_us, @gtk.now_us()) {
view.scale.set_value(row.percent)
view.volume_label.set_text(row.volume_text)
}
view.mute.set_active(row.mute)
view.mute.set_button_icon(mute_icon(row.mute))
match view.default_btn {
Some(b) => b.set_active(row.is_default)
None => ()
}
match view.device {
Some(dd) =>
if force ||
old.choices != row.choices ||
old.current_choice != row.current_choice {
dd.set_items(row.choices.map(fn(c) { c.label }), row.current_choice)
}
None => ()
}
})
}
///|
fn App::find_view(self : App, tab : @model.Tab, id : Int32) -> RowView? {
for t in self.tabs {
if t.tab == tab {
return t.views.get(id)
}
}
None
}
///|
fn App::sync_default_button(self : App, tab : @model.Tab, id : Int32) -> Unit {
match self.find_view(tab, id) {
Some({ default_btn: Some(b), row, .. }) =>
@gtk.updating(fn() { b.set_active(row.is_default) })
_ => ()
}
}
///|
fn App::render_tab(self : App, t : TabView) -> Unit {
let rows = @model.rows(self.state, t.tab)
let diff = @model.diff_rows(t.rows, rows)
for id in diff.removed {
match t.views.get(id) {
Some(v) => {
for tag in v.tags {
@gtk.unregister(tag)
}
t.list.remove(v.root)
t.views.remove(id)
}
None => ()
}
}
for row in rows {
match t.views.get(row.id) {
None => {
let v = new_row_view(self, t.tab, row)
t.list.append(v.root)
t.views.set(row.id, v)
}
Some(v) => if diff.updated.contains(row.id) { apply_row(v, row) }
}
}
// Keep widget order equal to row order.
let mut prev : @gtk.Widget? = Some(t.empty)
for row in rows {
match t.views.get(row.id) {
Some(v) => {
t.list.reorder_after(v.root, prev)
prev = Some(v.root)
}
None => ()
}
}
t.empty.set_visible(rows.length() == 0)
t.rows = rows
}
///|
fn App::render(self : App) -> Unit {
for t in self.tabs {
self.render_tab(t)
}
}
///|
fn App::select_tab(self : App, i : Int32) -> Unit {
self.notebook.set_page(i)
}
///|
fn App::set_status(self : App, text : String) -> Unit {
self.status.set_text(text)
}
///|
fn App::on_wp_event(self : App, ev : @wp.Event) -> Unit {
let mut changed = false
for e in @wp.to_model_events(ev) {
if self.state.apply(e) {
changed = true
}
}
match ev {
Ready => self.set_status("Connected to PipeWire via WirePlumber")
Disconnected => self.set_status("Disconnected from PipeWire")
PluginError =>
self.set_status(
"Could not load WirePlumber's mixer-api / default-nodes-api modules",
)
_ => ()
}
if changed {
self.render()
}
}
///|
fn build_ui() -> App {
@gtk.load_css(CSS)
let window = @gtk.window("Volume Control (moonmix)", 640, 480)
let outer = @gtk.vbox(0)
let nb = @gtk.notebook()
let tabs = []
for tab in @model.Tab::all() {
let list = @gtk.vbox(0)
let empty = @gtk.label(tab.empty_text())
empty.set_margins(24)
empty.add_css_class("dim-label")
list.append(empty)
nb.append_page(@gtk.scrolled(list), tab.label())
tabs.push({ tab, list, empty, views: Map([]), rows: [], })
}
outer.append(nb)
outer.append(@gtk.separator())
let status = @gtk.label("Connecting to PipeWire…")
status.add_css_class("mm-status")
outer.append(status)
window.set_child(outer)
{ state: @model.State::new(), tabs, status, window, notebook: nb, }
}
///|
/// Test hook: MOONMIX_SCREENSHOT=/path/prefix renders every tab to
/// <prefix>-<n>.png once connected, then exits. Used for headless CI/smoke
/// runs (GDK_BACKEND=broadway or x11 under Xvfb).
fn screenshot_mode(app : App, prefix : String) -> Unit {
let tab_count = app.tabs.length()
// Offscreen rendering occasionally yields an empty frame right after a tab
// switch, so retry a few times.
fn shoot(i : Int32, attempt : Int32) -> Unit {
if i >= tab_count {
@gtk.quit()
return
}
if attempt == 0 {
app.select_tab(i)
}
@gtk.timeout(400, fn() {
let path = "\{prefix}-\{i}.png"
if app.window.save_png(path) {
println("moonmix: wrote \{path}")
shoot(i + 1, 0)
} else if attempt < 4 {
shoot(i, attempt + 1)
} else {
println("moonmix: failed to render \{path}")
shoot(i + 1, 0)
}
})
}
@gtk.timeout(1500, fn() { shoot(0, 0) })
}
///|
fn env_var(name : String) -> String? {
@env.get_env_var(name)
}
///|
fn main {
if !@gtk.init_gtk() {
println("moonmix: cannot open a display (is WAYLAND_DISPLAY/DISPLAY set?)")
c_exit(1)
}
let app = build_ui()
@wp.on_event(fn(ev) { app.on_wp_event(ev) })
if !@wp.start() {
app.set_status("Cannot connect to PipeWire. Is pipewire running?")
}
app.window.present()
match env_var("MOONMIX_SCREENSHOT") {
Some(prefix) if prefix != "" => screenshot_mode(app, prefix)
_ => ()
}
@gtk.run()
}
+15
View File
@@ -0,0 +1,15 @@
// The GUI.
import {
"geordi/moonmix/model",
"geordi/moonmix/wp",
"geordi/moonmix/gtk",
"moonbitlang/core/env",
}
supported_targets = "-all+native"
pkgtype(kind: "executable")
options(
link: { "native": { "cc": "tools/pkg-cc" } },
)
+17
View File
@@ -0,0 +1,17 @@
// Generated using `moon info`, DON'T EDIT IT
package "geordi/moonmix/cmd/moonmix"
// Values
// Errors
// Types and methods
type App
type RowView
type TabView
// Type aliases
// Traits
+12
View File
@@ -0,0 +1,12 @@
[Desktop Entry]
Type=Application
Version=1.0
Name=moonmix
GenericName=Volume Control
Comment=Adjust volumes of PipeWire devices and applications
Exec=moonmix
Icon=multimedia-volume-control
Terminal=false
Categories=AudioVideo;Audio;Mixer;GTK;Settings;HardwareSettings;
Keywords=pipewire;wireplumber;volume;mixer;sound;audio;pavucontrol;
StartupNotify=true
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+478
View File
@@ -0,0 +1,478 @@
// Minimal hand-written GTK4 binding (see gtk_stub.c). Only what moonmix
// needs. Signals are dispatched through a tag -> handler table.
///|
#external
pub type Widget
///|
extern "C" fn ffi_set_handler(
call : FuncRef[((Int32, Double) -> Unit, Int32, Double) -> Unit],
closure : (Int32, Double) -> Unit,
) = "mm_gtk_set_handler"
///|
extern "C" fn ffi_init() -> Int32 = "mm_gtk_init"
///|
extern "C" fn ffi_run() = "mm_gtk_run"
///|
extern "C" fn ffi_quit() = "mm_gtk_quit"
///|
extern "C" fn ffi_now_us() -> Int64 = "mm_gtk_now_us"
///|
extern "C" fn ffi_begin_update() = "mm_gtk_begin_update"
///|
extern "C" fn ffi_end_update() = "mm_gtk_end_update"
///|
extern "C" fn ffi_timeout(ms : Int32, tag : Int32) = "mm_gtk_timeout"
///|
#borrow(css)
extern "C" fn ffi_load_css(css : Bytes) = "mm_gtk_load_css"
///|
#borrow(title)
extern "C" fn ffi_window_new(
title : Bytes,
w : Int32,
h : Int32,
tag : Int32,
) -> Widget = "mm_gtk_window_new"
///|
extern "C" fn ffi_window_set_child(win : Widget, child : Widget) = "mm_gtk_window_set_child"
///|
extern "C" fn ffi_window_present(win : Widget) = "mm_gtk_window_present"
///|
extern "C" fn ffi_box_new(vertical : Int32, spacing : Int32) -> Widget = "mm_gtk_box_new"
///|
extern "C" fn ffi_box_append(b : Widget, child : Widget) = "mm_gtk_box_append"
///|
extern "C" fn ffi_box_remove(b : Widget, child : Widget) = "mm_gtk_box_remove"
///|
extern "C" fn ffi_box_reorder_after(
b : Widget,
child : Widget,
sibling : Widget,
) = "mm_gtk_box_reorder_after"
///|
extern "C" fn ffi_null() -> Widget = "mm_gtk_null"
///|
extern "C" fn ffi_scrolled_new(child : Widget) -> Widget = "mm_gtk_scrolled_new"
///|
extern "C" fn ffi_notebook_new(tag : Int32) -> Widget = "mm_gtk_notebook_new"
///|
#borrow(label)
extern "C" fn ffi_notebook_append(nb : Widget, child : Widget, label : Bytes) = "mm_gtk_notebook_append"
///|
extern "C" fn ffi_notebook_set_page(nb : Widget, i : Int32) = "mm_gtk_notebook_set_page"
///|
extern "C" fn ffi_separator_new() -> Widget = "mm_gtk_separator_new"
///|
#borrow(text)
extern "C" fn ffi_label_new(text : Bytes) -> Widget = "mm_gtk_label_new"
///|
#borrow(text)
extern "C" fn ffi_label_set_text(l : Widget, text : Bytes) = "mm_gtk_label_set_text"
///|
extern "C" fn ffi_label_set_width_chars(l : Widget, n : Int32) = "mm_gtk_label_set_width_chars"
///|
#borrow(icon)
extern "C" fn ffi_image_new(icon : Bytes, size : Int32) -> Widget = "mm_gtk_image_new"
///|
#borrow(icon)
extern "C" fn ffi_image_set_icon(img : Widget, icon : Bytes) = "mm_gtk_image_set_icon"
///|
extern "C" fn ffi_scale_new(max : Double, norm : Double, tag : Int32) -> Widget = "mm_gtk_scale_new"
///|
extern "C" fn ffi_scale_set(sc : Widget, v : Double) = "mm_gtk_scale_set"
///|
extern "C" fn ffi_scale_get(sc : Widget) -> Double = "mm_gtk_scale_get"
///|
#borrow(icon, label)
extern "C" fn ffi_toggle_new(
icon : Bytes,
label : Bytes,
tag : Int32,
) -> Widget = "mm_gtk_toggle_new"
///|
extern "C" fn ffi_toggle_set(b : Widget, active : Int32) = "mm_gtk_toggle_set"
///|
#borrow(icon)
extern "C" fn ffi_button_set_icon(b : Widget, icon : Bytes) = "mm_gtk_button_set_icon"
///|
extern "C" fn ffi_dropdown_new(tag : Int32) -> Widget = "mm_gtk_dropdown_new"
///|
#borrow(items)
extern "C" fn ffi_dropdown_set(dd : Widget, items : Bytes, selected : Int32) = "mm_gtk_dropdown_set"
///|
#borrow(text)
extern "C" fn ffi_set_tooltip(w : Widget, text : Bytes) = "mm_gtk_widget_set_tooltip"
///|
extern "C" fn ffi_set_hexpand(w : Widget, v : Int32) = "mm_gtk_widget_set_hexpand"
///|
extern "C" fn ffi_set_margins(w : Widget, m : Int32) = "mm_gtk_widget_set_margins"
///|
#borrow(cls)
extern "C" fn ffi_add_css_class(w : Widget, cls : Bytes) = "mm_gtk_widget_add_css_class"
///|
extern "C" fn ffi_set_visible(w : Widget, v : Int32) = "mm_gtk_widget_set_visible"
///|
extern "C" fn ffi_set_sensitive(w : Widget, v : Int32) = "mm_gtk_widget_set_sensitive"
///|
extern "C" fn ffi_set_valign_center(w : Widget) = "mm_gtk_widget_set_valign_center"
///|
#borrow(path)
extern "C" fn ffi_save_png(w : Widget, path : Bytes) -> Int32 = "mm_gtk_save_png"
// ---- dispatch -------------------------------------------------------------
///|
let handlers : Map[Int32, (Double) -> Unit] = Map([])
///|
let next_tag : Ref[Int32] = { val: 1, }
///|
let dispatch_installed : Ref[Bool] = { val: false, }
///|
fn install_dispatch() -> Unit {
if !dispatch_installed.val {
dispatch_installed.val = true
ffi_set_handler(fn(g, tag, v) { g(tag, v) }, fn(tag, v) {
match handlers.get(tag) {
Some(h) => h(v)
None => ()
}
})
}
}
///|
/// Register a handler and return its tag.
fn register(h : (Double) -> Unit) -> Int32 {
install_dispatch()
let tag = next_tag.val
next_tag.val += 1
handlers.set(tag, h)
tag
}
///|
/// Forget a handler (when its widget is destroyed).
pub fn unregister(tag : Int32) -> Unit {
handlers.remove(tag)
}
///|
fn cstr(s : String) -> Bytes {
let b = @utf8.encode(s)
let n = b.length()
Bytes::makei(n + 1, fn(i) { if i < n { b[i] } else { b'\x00' } })
}
///|
fn int(b : Bool) -> Int32 {
if b {
1
} else {
0
}
}
// ---- public API ------------------------------------------------------------
///|
/// Initialise GTK. False if no display is available.
pub fn init_gtk() -> Bool {
install_dispatch()
ffi_init() != 0
}
///|
pub fn run() -> Unit {
ffi_run()
}
///|
pub fn quit() -> Unit {
ffi_quit()
}
///|
/// Monotonic clock in microseconds.
pub fn now_us() -> Int64 {
ffi_now_us()
}
///|
/// Run `f` with widget signals suppressed (programmatic updates).
pub fn updating(f : () -> Unit) -> Unit {
ffi_begin_update()
f()
ffi_end_update()
}
///|
pub fn timeout(ms : Int32, f : () -> Unit) -> Unit {
let tag_ref : Ref[Int32] = { val: 0, }
tag_ref.val = register(fn(_) {
unregister(tag_ref.val)
f()
})
ffi_timeout(ms, tag_ref.val)
}
///|
pub fn load_css(css : String) -> Unit {
ffi_load_css(cstr(css))
}
///|
pub fn window(
title : String,
width : Int32,
height : Int32,
on_close~ : () -> Unit = fn() { },
) -> Widget {
ffi_window_new(cstr(title), width, height, register(fn(_) { on_close() }))
}
///|
pub fn Widget::set_child(self : Widget, child : Widget) -> Unit {
ffi_window_set_child(self, child)
}
///|
pub fn Widget::present(self : Widget) -> Unit {
ffi_window_present(self)
}
///|
pub fn vbox(spacing : Int32) -> Widget {
ffi_box_new(1, spacing)
}
///|
pub fn hbox(spacing : Int32) -> Widget {
ffi_box_new(0, spacing)
}
///|
pub fn Widget::append(self : Widget, child : Widget) -> Unit {
ffi_box_append(self, child)
}
///|
pub fn Widget::remove(self : Widget, child : Widget) -> Unit {
ffi_box_remove(self, child)
}
///|
/// Move `child` right after `sibling` in a box (None = first).
pub fn Widget::reorder_after(
self : Widget,
child : Widget,
sibling : Widget?,
) -> Unit {
ffi_box_reorder_after(
self,
child,
match sibling {
Some(s) => s
None => ffi_null()
},
)
}
///|
pub fn scrolled(child : Widget) -> Widget {
ffi_scrolled_new(child)
}
///|
pub fn notebook(on_switch~ : (Int32) -> Unit = fn(_) { }) -> Widget {
ffi_notebook_new(register(fn(v) { on_switch(v.to_int()) }))
}
///|
pub fn Widget::append_page(
self : Widget,
child : Widget,
label : String,
) -> Unit {
ffi_notebook_append(self, child, cstr(label))
}
///|
pub fn Widget::set_page(self : Widget, i : Int32) -> Unit {
ffi_notebook_set_page(self, i)
}
///|
pub fn separator() -> Widget {
ffi_separator_new()
}
///|
pub fn label(text : String) -> Widget {
ffi_label_new(cstr(text))
}
///|
pub fn Widget::set_text(self : Widget, text : String) -> Unit {
ffi_label_set_text(self, cstr(text))
}
///|
pub fn Widget::set_width_chars(self : Widget, n : Int32) -> Unit {
ffi_label_set_width_chars(self, n)
}
///|
pub fn image(icon : String, size : Int32) -> Widget {
ffi_image_new(cstr(icon), size)
}
///|
pub fn Widget::set_icon(self : Widget, icon : String) -> Unit {
ffi_image_set_icon(self, cstr(icon))
}
///|
/// A slider from 0 to `max` with a mark at `norm`. Returns (widget, tag).
pub fn scale(
max : Double,
norm : Double,
on_change : (Double) -> Unit,
) -> (Widget, Int32) {
let tag = register(on_change)
(ffi_scale_new(max, norm, tag), tag)
}
///|
pub fn Widget::set_value(self : Widget, v : Double) -> Unit {
ffi_scale_set(self, v)
}
///|
pub fn Widget::value(self : Widget) -> Double {
ffi_scale_get(self)
}
///|
pub fn toggle(
icon : String,
label : String,
on_toggle : (Bool) -> Unit,
) -> (Widget, Int32) {
let tag = register(fn(v) { on_toggle(v != 0.0) })
(ffi_toggle_new(cstr(icon), cstr(label), tag), tag)
}
///|
pub fn Widget::set_active(self : Widget, active : Bool) -> Unit {
ffi_toggle_set(self, int(active))
}
///|
pub fn Widget::set_button_icon(self : Widget, icon : String) -> Unit {
ffi_button_set_icon(self, cstr(icon))
}
///|
pub fn dropdown(on_select : (Int32) -> Unit) -> (Widget, Int32) {
let tag = register(fn(v) { on_select(v.to_int()) })
(ffi_dropdown_new(tag), tag)
}
///|
pub fn Widget::set_items(
self : Widget,
items : Array[String],
selected : Int32,
) -> Unit {
// '\n' separates items on the C side, so strip it from labels.
let clean = items.map(fn(s) { s.replace_all(old="\n", new=" ") })
ffi_dropdown_set(self, cstr(clean.join("\n")), selected)
}
///|
pub fn Widget::set_tooltip(self : Widget, text : String) -> Unit {
ffi_set_tooltip(self, cstr(text))
}
///|
pub fn Widget::set_hexpand(self : Widget, v : Bool) -> Unit {
ffi_set_hexpand(self, int(v))
}
///|
pub fn Widget::set_margins(self : Widget, m : Int32) -> Unit {
ffi_set_margins(self, m)
}
///|
pub fn Widget::add_css_class(self : Widget, cls : String) -> Unit {
ffi_add_css_class(self, cstr(cls))
}
///|
pub fn Widget::set_visible(self : Widget, v : Bool) -> Unit {
ffi_set_visible(self, int(v))
}
///|
pub fn Widget::set_sensitive(self : Widget, v : Bool) -> Unit {
ffi_set_sensitive(self, int(v))
}
///|
pub fn Widget::set_valign_center(self : Widget) -> Unit {
ffi_set_valign_center(self)
}
///|
/// Render the widget offscreen to a PNG file (for headless screenshots).
pub fn Widget::save_png(self : Widget, path : String) -> Bool {
ffi_save_png(self, cstr(path)) != 0
}
+376
View File
@@ -0,0 +1,376 @@
/*
* moonmix: minimal hand-written GTK4 binding.
*
* Widgets are passed to MoonBit as opaque pointers. Every signal is reported
* through one MoonBit callback as (tag, value): MoonBit picks the tag when it
* creates the widget and keeps a tag -> handler table. While MoonBit updates
* widgets programmatically (mm_gtk_set_*), callbacks are suppressed so model
* updates never echo back into PipeWire.
*/
#include <string.h>
#include <gtk/gtk.h>
#include "moonbit.h"
typedef void (*mm_gcall_t)(void *closure, int32_t tag, double value);
static mm_gcall_t g_call;
static void *g_closure;
static int g_suppress;
static GMainLoop *g_loop;
static void emit(int32_t tag, double value) {
if (g_call && !g_suppress && tag > 0) {
moonbit_incref(g_closure);
g_call(g_closure, tag, value);
}
}
#define TAG_KEY "mm-tag"
static void set_tag(gpointer obj, int32_t tag) {
g_object_set_data(G_OBJECT(obj), TAG_KEY, GINT_TO_POINTER(tag));
}
static int32_t get_tag(gpointer obj) {
return GPOINTER_TO_INT(g_object_get_data(G_OBJECT(obj), TAG_KEY));
}
static const char *s(moonbit_bytes_t b) { return (const char *)b; }
MOONBIT_FFI_EXPORT void mm_gtk_set_handler(mm_gcall_t call, void *closure) {
if (g_closure)
moonbit_decref(g_closure);
g_call = call;
g_closure = closure;
}
MOONBIT_FFI_EXPORT int32_t mm_gtk_init(void) { return gtk_init_check(); }
MOONBIT_FFI_EXPORT void mm_gtk_run(void) {
if (!g_loop)
g_loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(g_loop);
}
MOONBIT_FFI_EXPORT void mm_gtk_quit(void) {
if (g_loop)
g_main_loop_quit(g_loop);
}
MOONBIT_FFI_EXPORT int64_t mm_gtk_now_us(void) {
return g_get_monotonic_time();
}
MOONBIT_FFI_EXPORT void mm_gtk_begin_update(void) { g_suppress++; }
MOONBIT_FFI_EXPORT void mm_gtk_end_update(void) {
if (g_suppress > 0)
g_suppress--;
}
static gboolean on_timeout(gpointer d) {
/* Timers are never suppressed. */
int saved = g_suppress;
g_suppress = 0;
emit(GPOINTER_TO_INT(d), 0);
g_suppress = saved;
return G_SOURCE_REMOVE;
}
MOONBIT_FFI_EXPORT void mm_gtk_timeout(int32_t ms, int32_t tag) {
g_timeout_add((guint)ms, on_timeout, GINT_TO_POINTER(tag));
}
MOONBIT_FFI_EXPORT void mm_gtk_load_css(moonbit_bytes_t css) {
GtkCssProvider *p = gtk_css_provider_new();
gtk_css_provider_load_from_string(p, s(css));
gtk_style_context_add_provider_for_display(
gdk_display_get_default(), GTK_STYLE_PROVIDER(p),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
g_object_unref(p);
}
/* ---- window ------------------------------------------------------------- */
static gboolean on_close(GtkWindow *w, gpointer d) {
(void)d;
emit(get_tag(w), 0);
mm_gtk_quit();
return FALSE;
}
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_window_new(moonbit_bytes_t title,
int32_t w, int32_t h,
int32_t tag) {
GtkWidget *win = gtk_window_new();
gtk_window_set_title(GTK_WINDOW(win), s(title));
gtk_window_set_default_size(GTK_WINDOW(win), w, h);
gtk_window_set_icon_name(GTK_WINDOW(win), "multimedia-volume-control");
set_tag(win, tag);
g_signal_connect(win, "close-request", G_CALLBACK(on_close), NULL);
return win;
}
MOONBIT_FFI_EXPORT void mm_gtk_window_set_child(GtkWidget *win,
GtkWidget *child) {
gtk_window_set_child(GTK_WINDOW(win), child);
}
MOONBIT_FFI_EXPORT void mm_gtk_window_present(GtkWidget *win) {
gtk_window_present(GTK_WINDOW(win));
}
/* ---- containers --------------------------------------------------------- */
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_box_new(int32_t vertical,
int32_t spacing) {
return gtk_box_new(vertical ? GTK_ORIENTATION_VERTICAL
: GTK_ORIENTATION_HORIZONTAL,
spacing);
}
MOONBIT_FFI_EXPORT void mm_gtk_box_append(GtkWidget *box, GtkWidget *child) {
gtk_box_append(GTK_BOX(box), child);
}
MOONBIT_FFI_EXPORT void mm_gtk_box_remove(GtkWidget *box, GtkWidget *child) {
gtk_box_remove(GTK_BOX(box), child);
}
/* Move `child` right after `sibling` (NULL = to the front). */
MOONBIT_FFI_EXPORT void mm_gtk_box_reorder_after(GtkWidget *box,
GtkWidget *child,
GtkWidget *sibling) {
gtk_box_reorder_child_after(GTK_BOX(box), child, sibling);
}
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_null(void) { return NULL; }
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_scrolled_new(GtkWidget *child) {
GtkWidget *sw = gtk_scrolled_window_new();
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw), GTK_POLICY_NEVER,
GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(sw), child);
gtk_widget_set_vexpand(sw, TRUE);
return sw;
}
static void on_switch_page(GtkNotebook *nb, GtkWidget *page, guint num,
gpointer d) {
(void)page;
(void)d;
emit(get_tag(nb), (double)num);
}
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_notebook_new(int32_t tag) {
GtkWidget *nb = gtk_notebook_new();
set_tag(nb, tag);
g_signal_connect(nb, "switch-page", G_CALLBACK(on_switch_page), NULL);
gtk_widget_set_vexpand(nb, TRUE);
return nb;
}
MOONBIT_FFI_EXPORT void mm_gtk_notebook_append(GtkWidget *nb, GtkWidget *child,
moonbit_bytes_t label) {
gtk_notebook_append_page(GTK_NOTEBOOK(nb), child, gtk_label_new(s(label)));
}
MOONBIT_FFI_EXPORT void mm_gtk_notebook_set_page(GtkWidget *nb, int32_t i) {
gtk_notebook_set_current_page(GTK_NOTEBOOK(nb), i);
}
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_separator_new(void) {
return gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
}
/* ---- leaf widgets ------------------------------------------------------- */
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_label_new(moonbit_bytes_t text) {
GtkWidget *l = gtk_label_new(s(text));
gtk_label_set_xalign(GTK_LABEL(l), 0.0f);
gtk_label_set_ellipsize(GTK_LABEL(l), PANGO_ELLIPSIZE_END);
return l;
}
MOONBIT_FFI_EXPORT void mm_gtk_label_set_text(GtkWidget *l,
moonbit_bytes_t text) {
gtk_label_set_text(GTK_LABEL(l), s(text));
}
MOONBIT_FFI_EXPORT void mm_gtk_label_set_width_chars(GtkWidget *l,
int32_t n) {
gtk_label_set_width_chars(GTK_LABEL(l), n);
gtk_label_set_xalign(GTK_LABEL(l), 1.0f);
}
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_image_new(moonbit_bytes_t icon,
int32_t size) {
GtkWidget *img = gtk_image_new_from_icon_name(s(icon));
gtk_image_set_pixel_size(GTK_IMAGE(img), size);
return img;
}
MOONBIT_FFI_EXPORT void mm_gtk_image_set_icon(GtkWidget *img,
moonbit_bytes_t icon) {
gtk_image_set_from_icon_name(GTK_IMAGE(img), s(icon));
}
static void on_value_changed(GtkRange *r, gpointer d) {
(void)d;
emit(get_tag(r), gtk_range_get_value(r));
}
/* Horizontal slider 0..max with a "100%" mark. */
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_scale_new(double max, double norm,
int32_t tag) {
GtkWidget *sc =
gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, 0.0, max, 1.0);
gtk_scale_set_draw_value(GTK_SCALE(sc), FALSE);
gtk_scale_add_mark(GTK_SCALE(sc), 0.0, GTK_POS_BOTTOM, NULL);
gtk_scale_add_mark(GTK_SCALE(sc), norm, GTK_POS_BOTTOM, "100%");
gtk_widget_set_hexpand(sc, TRUE);
set_tag(sc, tag);
g_signal_connect(sc, "value-changed", G_CALLBACK(on_value_changed), NULL);
return sc;
}
MOONBIT_FFI_EXPORT void mm_gtk_scale_set(GtkWidget *sc, double v) {
g_suppress++;
gtk_range_set_value(GTK_RANGE(sc), v);
g_suppress--;
}
MOONBIT_FFI_EXPORT double mm_gtk_scale_get(GtkWidget *sc) {
return gtk_range_get_value(GTK_RANGE(sc));
}
static void on_toggled(GtkToggleButton *b, gpointer d) {
(void)d;
emit(get_tag(b), gtk_toggle_button_get_active(b) ? 1.0 : 0.0);
}
/* Toggle button with an icon and/or a label (either may be ""). */
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_toggle_new(moonbit_bytes_t icon,
moonbit_bytes_t label,
int32_t tag) {
GtkWidget *b = gtk_toggle_button_new();
if (s(icon)[0] && s(label)[0]) {
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_append(GTK_BOX(box), gtk_image_new_from_icon_name(s(icon)));
gtk_box_append(GTK_BOX(box), gtk_label_new(s(label)));
gtk_button_set_child(GTK_BUTTON(b), box);
} else if (s(icon)[0]) {
gtk_button_set_icon_name(GTK_BUTTON(b), s(icon));
} else {
gtk_button_set_label(GTK_BUTTON(b), s(label));
}
gtk_widget_set_valign(b, GTK_ALIGN_CENTER);
set_tag(b, tag);
g_signal_connect(b, "toggled", G_CALLBACK(on_toggled), NULL);
return b;
}
MOONBIT_FFI_EXPORT void mm_gtk_toggle_set(GtkWidget *b, int32_t active) {
g_suppress++;
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(b), active != 0);
g_suppress--;
}
MOONBIT_FFI_EXPORT void mm_gtk_button_set_icon(GtkWidget *b,
moonbit_bytes_t icon) {
gtk_button_set_icon_name(GTK_BUTTON(b), s(icon));
}
static void on_selected(GObject *dd, GParamSpec *p, gpointer d) {
(void)p;
(void)d;
guint sel = gtk_drop_down_get_selected(GTK_DROP_DOWN(dd));
emit(get_tag(dd), sel == GTK_INVALID_LIST_POSITION ? -1.0 : (double)sel);
}
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_dropdown_new(int32_t tag) {
GtkStringList *model = gtk_string_list_new(NULL);
GtkWidget *dd = gtk_drop_down_new(G_LIST_MODEL(model), NULL);
gtk_widget_set_valign(dd, GTK_ALIGN_CENTER);
set_tag(dd, tag);
g_signal_connect(dd, "notify::selected", G_CALLBACK(on_selected), NULL);
return dd;
}
/* Replace the items with `items` ('\n'-separated) and select `selected`
* (-1 = none). */
MOONBIT_FFI_EXPORT void mm_gtk_dropdown_set(GtkWidget *dd,
moonbit_bytes_t items,
int32_t selected) {
g_suppress++;
GtkStringList *model = gtk_string_list_new(NULL);
if (s(items)[0]) {
gchar **parts = g_strsplit(s(items), "\n", -1);
for (gchar **p = parts; *p; p++)
gtk_string_list_append(model, *p);
g_strfreev(parts);
}
gtk_drop_down_set_model(GTK_DROP_DOWN(dd), G_LIST_MODEL(model));
g_object_unref(model);
gtk_drop_down_set_selected(GTK_DROP_DOWN(dd),
selected < 0 ? GTK_INVALID_LIST_POSITION
: (guint)selected);
g_suppress--;
}
/* ---- generic widget properties ------------------------------------------ */
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_tooltip(GtkWidget *w,
moonbit_bytes_t text) {
gtk_widget_set_tooltip_text(w, s(text)[0] ? s(text) : NULL);
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_hexpand(GtkWidget *w, int32_t v) {
gtk_widget_set_hexpand(w, v != 0);
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_margins(GtkWidget *w, int32_t m) {
gtk_widget_set_margin_start(w, m);
gtk_widget_set_margin_end(w, m);
gtk_widget_set_margin_top(w, m);
gtk_widget_set_margin_bottom(w, m);
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_add_css_class(GtkWidget *w,
moonbit_bytes_t cls) {
gtk_widget_add_css_class(w, s(cls));
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_visible(GtkWidget *w, int32_t v) {
gtk_widget_set_visible(w, v != 0);
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_sensitive(GtkWidget *w, int32_t v) {
gtk_widget_set_sensitive(w, v != 0);
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_valign_center(GtkWidget *w) {
gtk_widget_set_valign(w, GTK_ALIGN_CENTER);
}
/* ---- headless screenshots ------------------------------------------------ */
/* Render a realized widget (usually the window) to a PNG via GSK, without
* needing a screenshot tool. Returns 1 on success. */
MOONBIT_FFI_EXPORT int32_t mm_gtk_save_png(GtkWidget *w, moonbit_bytes_t path) {
int width = gtk_widget_get_width(w), height = gtk_widget_get_height(w);
GtkNative *native = gtk_widget_get_native(w);
if (width <= 0 || height <= 0 || !native)
return 0;
GdkPaintable *paintable = gtk_widget_paintable_new(w);
GtkSnapshot *snap = gtk_snapshot_new();
gdk_paintable_snapshot(paintable, snap, width, height);
GskRenderNode *node = gtk_snapshot_free_to_node(snap);
int ok = 0;
if (node) {
GskRenderer *r = gtk_native_get_renderer(native);
graphene_rect_t bounds = GRAPHENE_RECT_INIT(0, 0, width, height);
GdkTexture *tex = gsk_renderer_render_texture(r, node, &bounds);
ok = gdk_texture_save_to_png(tex, s(path));
g_object_unref(tex);
gsk_render_node_unref(node);
}
g_object_unref(paintable);
return ok;
}
+13
View File
@@ -0,0 +1,13 @@
// Minimal hand-written GTK4 binding (native only). See gtk_stub.c.
import {
"moonbitlang/core/encoding/utf8",
}
supported_targets = "-all+native"
options(
"native-stub": [ "gtk_stub.c" ],
// moon does not expand $(pkg-config ...) in flags; tools/pkg-cc appends
// `pkg-config --cflags --libs` for PipeWire, WirePlumber and GTK4.
link: { "native": { "stub-cc": "tools/pkg-cc" } },
)
+74
View File
@@ -0,0 +1,74 @@
// Generated using `moon info`, DON'T EDIT IT
package "geordi/moonmix/gtk"
// Values
pub fn dropdown((Int32) -> Unit) -> (Widget, Int32)
pub fn hbox(Int32) -> Widget
pub fn image(String, Int32) -> Widget
pub fn init_gtk() -> Bool
pub fn label(String) -> Widget
pub fn load_css(String) -> Unit
pub fn notebook(on_switch? : (Int32) -> Unit) -> Widget
pub fn now_us() -> Int64
pub fn quit() -> Unit
pub fn run() -> Unit
pub fn scale(Double, Double, (Double) -> Unit) -> (Widget, Int32)
pub fn scrolled(Widget) -> Widget
pub fn separator() -> Widget
pub fn timeout(Int32, () -> Unit) -> Unit
pub fn toggle(String, String, (Bool) -> Unit) -> (Widget, Int32)
pub fn unregister(Int32) -> Unit
pub fn updating(() -> Unit) -> Unit
pub fn vbox(Int32) -> Widget
pub fn window(String, Int32, Int32, on_close? : () -> Unit) -> Widget
// Errors
// Types and methods
#external
pub type Widget
pub fn Widget::add_css_class(Self, String) -> Unit
pub fn Widget::append(Self, Self) -> Unit
pub fn Widget::append_page(Self, Self, String) -> Unit
pub fn Widget::present(Self) -> Unit
pub fn Widget::remove(Self, Self) -> Unit
pub fn Widget::reorder_after(Self, Self, Self?) -> Unit
pub fn Widget::save_png(Self, String) -> Bool
pub fn Widget::set_active(Self, Bool) -> Unit
pub fn Widget::set_button_icon(Self, String) -> Unit
pub fn Widget::set_child(Self, Self) -> Unit
pub fn Widget::set_hexpand(Self, Bool) -> Unit
pub fn Widget::set_icon(Self, String) -> Unit
pub fn Widget::set_items(Self, Array[String], Int32) -> Unit
pub fn Widget::set_margins(Self, Int32) -> Unit
pub fn Widget::set_page(Self, Int32) -> Unit
pub fn Widget::set_sensitive(Self, Bool) -> Unit
pub fn Widget::set_text(Self, String) -> Unit
pub fn Widget::set_tooltip(Self, String) -> Unit
pub fn Widget::set_valign_center(Self) -> Unit
pub fn Widget::set_value(Self, Double) -> Unit
pub fn Widget::set_visible(Self, Bool) -> Unit
pub fn Widget::set_width_chars(Self, Int32) -> Unit
pub fn Widget::value(Self) -> Double
// Type aliases
// Traits
+5
View File
@@ -0,0 +1,5 @@
// Pure logic: volume curves, the audio-graph state reducer and the view
// model the GUI renders. No FFI, so `moon test` runs it on any target.
import {
"moonbitlang/core/math",
}
+139
View File
@@ -0,0 +1,139 @@
// Generated using `moon info`, DON'T EDIT IT
package "geordi/moonmix/model"
import {
"moonbitlang/core/debug",
}
// Values
pub const MAX_PERCENT : Double = 150.0
pub const NORM_PERCENT : Double = 100.0
pub fn clamp_percent(Double) -> Double
pub fn compare_text(String, String) -> Int32
pub fn diff_rows(Array[Row], Array[Row]) -> Diff
pub fn display_title(Node) -> String
pub fn format_db(Double) -> String
pub fn format_percent(Double) -> String
pub fn format_volume(Array[Double]) -> String
pub fn linear_to_db(Double) -> Double?
pub fn linear_to_percent(Double) -> Double
pub fn linked_percent(Array[Double]) -> Double
pub fn percent_to_linear(Double) -> Double
pub fn rows(State, Tab) -> Array[Row]
pub fn scale_linked(Array[Double], Double) -> Array[Double]
pub fn should_apply_remote(Int64, Int64, window_us? : Int64) -> Bool
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) struct DeviceChoice {
id : Int32
name : String
label : String
}
#derive(Eq, @debug.Debug)
pub(all) struct Diff {
removed : Array[Int32]
added : Array[Int32]
updated : Array[Int32]
}
#derive(@debug.Debug)
pub(all) enum Event {
Upsert(Node)
Remove(Int32)
Links(Array[Link])
Defaults(sink~ : Int32, source~ : Int32)
Reset
}
#derive(Eq, @debug.Debug)
pub(all) struct Link {
output_node : Int32
input_node : Int32
}
#derive(Eq, @debug.Debug)
pub(all) struct Node {
id : Int32
name : String
description : String
media_class : String
app_name : String
media_name : String
icon_name : String
volumes : Array[Double]
mute : Bool
}
pub fn Node::kind(Self) -> NodeKind
pub fn Node::new(Int32, String, name? : String, description? : String, app_name? : String, media_name? : String, icon_name? : String, volumes? : Array[Double], mute? : Bool) -> Self
#derive(Eq, @debug.Debug)
pub(all) enum NodeKind {
Sink
Source
PlaybackStream
RecordStream
Other
}
pub fn NodeKind::from_media_class(String) -> Self
#derive(Eq, @debug.Debug)
pub(all) struct Row {
id : Int32
title : String
subtitle : String
icon_name : String
volumes : Array[Double]
percent : Double
volume_text : String
mute : Bool
has_volume : Bool
is_default : Bool
choices : Array[DeviceChoice]
current_choice : Int32
}
pub(all) struct State {
nodes : Map[Int32, Node]
mut links : Array[Link]
mut default_sink : Int32
mut default_source : Int32
}
pub fn State::apply(Self, Event) -> Bool
pub fn State::new() -> Self
pub fn State::nodes_of(Self, NodeKind) -> Array[Node]
pub fn State::stream_device(Self, Int32) -> Int32?
#derive(Eq, @debug.Debug)
pub(all) enum Tab {
Playback
Recording
OutputDevices
InputDevices
}
pub fn Tab::all() -> Array[Self]
pub fn Tab::empty_text(Self) -> String
pub fn Tab::label(Self) -> String
pub fn Tab::node_kind(Self) -> NodeKind
// Type aliases
// Traits
+247
View File
@@ -0,0 +1,247 @@
// The audio graph as moonmix sees it, and a reducer that applies change
// events coming from WirePlumber (node added/changed/removed, links changed,
// default nodes changed).
///|
#derive(Eq, Debug)
pub(all) enum NodeKind {
Sink // Output device ("Audio/Sink")
Source // Input device ("Audio/Source", "Audio/Source/Virtual")
PlaybackStream // Application playing audio ("Stream/Output/Audio")
RecordStream // Application recording audio ("Stream/Input/Audio")
Other
}
///|
pub fn NodeKind::from_media_class(media_class : String) -> NodeKind {
match media_class {
"Audio/Sink" | "Audio/Duplex" => Sink
"Audio/Source" | "Audio/Source/Virtual" => Source
"Stream/Output/Audio" => PlaybackStream
"Stream/Input/Audio" => RecordStream
_ => Other
}
}
///|
/// One PipeWire node as reported by WirePlumber.
#derive(Eq, Debug)
pub(all) struct Node {
id : Int32 // PipeWire global (bound) id
name : String // node.name
description : String // node.description (devices) / node.nick
media_class : String
app_name : String // application.name (streams)
media_name : String // media.name (streams)
icon_name : String // application.icon-name / device.icon-name
volumes : Array[Double] // linear, one per channel; empty = no volume
mute : Bool
}
///|
pub fn Node::kind(self : Node) -> NodeKind {
NodeKind::from_media_class(self.media_class)
}
///|
pub fn Node::new(
id : Int32,
media_class : String,
name~ : String = "",
description~ : String = "",
app_name~ : String = "",
media_name~ : String = "",
icon_name~ : String = "",
volumes~ : Array[Double] = [],
mute~ : Bool = false,
) -> Node {
{
id,
name,
description,
media_class,
app_name,
media_name,
icon_name,
volumes,
mute,
}
}
///|
/// A PipeWire link between two nodes (ports are folded into nodes).
#derive(Eq, Debug)
pub(all) struct Link {
output_node : Int32
input_node : Int32
}
///|
#derive(Debug)
pub(all) enum Event {
/// Node appeared or one of its properties / volume / mute changed.
Upsert(Node)
/// Node disappeared.
Remove(Int32)
/// Complete current set of links.
Links(Array[Link])
/// Current default sink / source node ids (-1 = none).
Defaults(sink~ : Int32, source~ : Int32)
/// Connection to PipeWire lost: forget everything.
Reset
}
///|
pub(all) struct State {
nodes : Map[Int32, Node]
mut links : Array[Link]
mut default_sink : Int32
mut default_source : Int32
}
///|
pub fn State::new() -> State {
{ nodes: {}, links: [], default_sink: -1, default_source: -1, }
}
///|
/// Apply one event. Returns true if anything visible changed, so callers can
/// skip re-rendering for no-op updates (e.g. echoes of our own changes).
pub fn State::apply(self : State, ev : Event) -> Bool {
match ev {
Upsert(node) =>
match self.nodes.get(node.id) {
Some(old) if old == node => false
_ => {
self.nodes.set(node.id, node)
true
}
}
Remove(id) =>
if self.nodes.contains(id) {
self.nodes.remove(id)
self.links = self.links.filter(fn(l) {
l.output_node != id && l.input_node != id
})
true
} else {
false
}
Links(links) => {
let changed = links != self.links
self.links = links
changed
}
Defaults(sink~, source~) => {
let changed = sink != self.default_sink || source != self.default_source
self.default_sink = sink
self.default_source = source
changed
}
Reset => {
let changed = self.nodes.length() > 0 || self.links.length() > 0
self.nodes.clear()
self.links = []
self.default_sink = -1
self.default_source = -1
changed
}
}
}
///|
/// Nodes of one kind, sorted for stable display (devices by description,
/// streams by application then id).
pub fn State::nodes_of(self : State, kind : NodeKind) -> Array[Node] {
let out = []
for _, n in self.nodes {
if n.kind() == kind {
out.push(n)
}
}
out.sort_by(fn(a, b) {
let c = compare_text(display_title(a), display_title(b))
if c != 0 {
c
} else {
a.id.compare(b.id)
}
})
out
}
///|
/// The device a stream is currently routed to: for a playback stream the
/// sink it links into, for a record stream the source it reads from.
pub fn State::stream_device(self : State, stream_id : Int32) -> Int32? {
let kind = match self.nodes.get(stream_id) {
Some(n) => n.kind()
None => return None
}
for l in self.links {
match kind {
PlaybackStream =>
if l.output_node == stream_id && self.is_kind(l.input_node, Sink) {
return Some(l.input_node)
}
RecordStream =>
if l.input_node == stream_id && self.is_kind(l.output_node, Source) {
return Some(l.output_node)
}
_ => ()
}
}
None
}
///|
fn State::is_kind(self : State, id : Int32, kind : NodeKind) -> Bool {
match self.nodes.get(id) {
Some(n) => n.kind() == kind
None => false
}
}
///|
/// Human title of a node, falling back through the available properties.
pub fn display_title(n : Node) -> String {
match n.kind() {
PlaybackStream | RecordStream =>
first_non_empty([n.app_name, n.description, n.name, "Stream \{n.id}"])
_ => first_non_empty([n.description, n.name, "Node \{n.id}"])
}
}
///|
/// Case-insensitive lexicographic comparison for display ordering.
/// (MoonBit's built-in String compare orders by length first.)
pub fn compare_text(a : String, b : String) -> Int32 {
let n = if a.length() < b.length() { a.length() } else { b.length() }
for i in 0..<n {
let x = fold_case(a.code_unit_at(i).to_int())
let y = fold_case(b.code_unit_at(i).to_int())
if x != y {
return x.compare(y)
}
}
a.length().compare(b.length())
}
///|
fn fold_case(c : Int32) -> Int32 {
if c >= 'A'.to_int() && c <= 'Z'.to_int() {
c + 32
} else {
c
}
}
///|
fn first_non_empty(xs : Array[String]) -> String {
for x in xs {
if x != "" {
return x
}
}
""
}
+131
View File
@@ -0,0 +1,131 @@
///|
fn sample_state() -> @model.State {
let s = @model.State::new()
let _ = s.apply(
Upsert(
@model.Node::new(
40,
"Audio/Sink",
name="alsa_output.pci.analog-stereo",
description="Built-in Audio Analog Stereo",
volumes=[1.0, 1.0],
),
),
)
let _ = s.apply(
Upsert(
@model.Node::new(
41,
"Audio/Sink",
name="bluez_output.headphones",
description="Headphones",
volumes=[0.125, 0.125],
),
),
)
let _ = s.apply(
Upsert(
@model.Node::new(
50,
"Audio/Source",
name="alsa_input.pci.analog-stereo",
description="Built-in Audio Analog Stereo",
volumes=[0.5],
mute=true,
),
),
)
let _ = s.apply(
Upsert(
@model.Node::new(
60,
"Stream/Output/Audio",
name="firefox",
app_name="Firefox",
media_name="Big Buck Bunny",
volumes=[1.0, 1.0],
),
),
)
let _ = s.apply(
Upsert(
@model.Node::new(
70,
"Stream/Input/Audio",
app_name="OBS",
media_name="Mic capture",
volumes=[1.0],
),
),
)
let _ = s.apply(
Upsert(@model.Node::new(80, "Video/Source", name="v4l2_camera")),
)
let _ = s.apply(
Links([
{ output_node: 60, input_node: 41, },
{ output_node: 50, input_node: 70, },
]),
)
let _ = s.apply(Defaults(sink=40, source=50))
s
}
///|
test "media class mapping" {
assert_eq(@model.NodeKind::from_media_class("Audio/Sink"), Sink)
assert_eq(@model.NodeKind::from_media_class("Audio/Source/Virtual"), Source)
assert_eq(
@model.NodeKind::from_media_class("Stream/Output/Audio"),
PlaybackStream,
)
assert_eq(
@model.NodeKind::from_media_class("Stream/Input/Audio"),
RecordStream,
)
assert_eq(@model.NodeKind::from_media_class("Video/Source"), Other)
}
///|
test "upsert, no-op detection and remove" {
let s = sample_state()
assert_eq(s.nodes_of(Sink).length(), 2)
// identical upsert is not a change
let same = s.nodes.get(40).unwrap()
assert_false(s.apply(Upsert(same)))
// volume change is
assert_true(s.apply(Upsert({ ..same, volumes: [0.5, 0.5], })))
// removing a node drops its links too
assert_true(s.apply(Remove(41)))
assert_false(s.apply(Remove(41)))
assert_eq(s.links.length(), 1)
assert_eq(s.stream_device(60), None)
}
///|
test "defaults and reset" {
let s = sample_state()
assert_false(s.apply(Defaults(sink=40, source=50)))
assert_true(s.apply(Defaults(sink=41, source=50)))
assert_eq(s.default_sink, 41)
assert_true(s.apply(Reset))
assert_eq(s.nodes.length(), 0)
assert_eq(s.default_sink, -1)
assert_false(s.apply(Reset))
}
///|
test "stream routing follows links" {
let s = sample_state()
assert_eq(s.stream_device(60), Some(41))
assert_eq(s.stream_device(70), Some(50))
assert_eq(s.stream_device(40), None)
assert_eq(s.stream_device(999), None)
}
///|
test "sorting by display title" {
let s = sample_state()
let sinks = s.nodes_of(Sink).map(fn(n) { n.id })
assert_eq(sinks, [40, 41]) // "Built-in..." < "Headphones"
}
+197
View File
@@ -0,0 +1,197 @@
// View model: what each pavucontrol-style tab shows, derived from State.
// The GTK layer only reconciles widgets against these rows.
///|
#derive(Eq, Debug)
pub(all) enum Tab {
Playback
Recording
OutputDevices
InputDevices
}
///|
pub fn Tab::all() -> Array[Tab] {
[Playback, Recording, OutputDevices, InputDevices]
}
///|
pub fn Tab::label(self : Tab) -> String {
match self {
Playback => "Playback"
Recording => "Recording"
OutputDevices => "Output Devices"
InputDevices => "Input Devices"
}
}
///|
pub fn Tab::node_kind(self : Tab) -> NodeKind {
match self {
Playback => PlaybackStream
Recording => RecordStream
OutputDevices => Sink
InputDevices => Source
}
}
///|
pub fn Tab::empty_text(self : Tab) -> String {
match self {
Playback => "No application is currently playing audio."
Recording => "No application is currently recording audio."
OutputDevices => "No output devices available."
InputDevices => "No input devices available."
}
}
///|
/// A device choice offered in a stream's "output/input device" dropdown.
#derive(Eq, Debug)
pub(all) struct DeviceChoice {
id : Int32
name : String // node.name, used as the routing target
label : String
}
///|
#derive(Eq, Debug)
pub(all) struct Row {
id : Int32
title : String
subtitle : String
icon_name : String
volumes : Array[Double]
percent : Double // linked slider value (cubic %)
volume_text : String // "75% (-7.50 dB)"
mute : Bool
has_volume : Bool
/// Devices only: this is the current default sink/source.
is_default : Bool
/// Streams only: devices the stream can be moved to, and the index of the
/// current one in that list (-1 when unknown / not linked yet).
choices : Array[DeviceChoice]
current_choice : Int32
}
///|
pub fn rows(state : State, tab : Tab) -> Array[Row] {
let kind = tab.node_kind()
let device_kind = match tab {
Playback => Some(Sink)
Recording => Some(Source)
_ => None
}
let choices = match device_kind {
Some(dk) =>
state
.nodes_of(dk)
.map(fn(d) { { id: d.id, name: d.name, label: display_title(d), } })
None => []
}
state
.nodes_of(kind)
.map(fn(n) {
let is_stream = device_kind is Some(_)
let subtitle = if is_stream {
n.media_name
} else if n.name != display_title(n) {
n.name
} else {
""
}
let current_choice = if is_stream {
match state.stream_device(n.id) {
Some(dev) => {
let mut idx = -1
for i, c in choices {
if c.id == dev {
idx = i
}
}
idx
}
None => -1
}
} else {
-1
}
let is_default = match kind {
Sink => n.id == state.default_sink
Source => n.id == state.default_source
_ => false
}
{
id: n.id,
title: display_title(n),
subtitle,
icon_name: if n.icon_name != "" {
n.icon_name
} else {
default_icon(kind)
},
volumes: n.volumes,
percent: linked_percent(n.volumes),
volume_text: if n.volumes.length() > 0 {
format_volume(n.volumes)
} else {
""
},
mute: n.mute,
has_volume: n.volumes.length() > 0,
is_default,
choices: if is_stream {
choices
} else {
[]
},
current_choice,
}
})
}
///|
fn default_icon(kind : NodeKind) -> String {
match kind {
Sink => "audio-speakers-symbolic"
Source => "audio-input-microphone-symbolic"
PlaybackStream => "audio-x-generic-symbolic"
RecordStream => "audio-input-microphone-symbolic"
Other => "audio-x-generic-symbolic"
}
}
///|
/// Result of reconciling the rows shown on screen against new rows: which
/// row ids to remove, which to add (with their index) and which to update.
#derive(Eq, Debug)
pub(all) struct Diff {
removed : Array[Int32]
added : Array[Int32]
updated : Array[Int32]
}
///|
pub fn diff_rows(old : Array[Row], new : Array[Row]) -> Diff {
let old_by_id : Map[Int32, Row] = Map([])
for r in old {
old_by_id.set(r.id, r)
}
let new_ids : Map[Int32, Bool] = Map([])
let added = []
let updated = []
for r in new {
new_ids.set(r.id, true)
match old_by_id.get(r.id) {
None => added.push(r.id)
Some(o) => if o != r { updated.push(r.id) }
}
}
let removed = []
for r in old {
if !new_ids.contains(r.id) {
removed.push(r.id)
}
}
{ removed, added, updated, }
}
+77
View File
@@ -0,0 +1,77 @@
///|
test "playback rows" {
let s = sample_state()
let rows = @model.rows(s, Playback)
assert_eq(rows.length(), 1)
let r = rows[0]
assert_eq(r.title, "Firefox")
assert_eq(r.subtitle, "Big Buck Bunny")
assert_eq(r.volume_text, "100% (0.00 dB)")
assert_eq(r.choices.map(fn(c) { c.id }), [40, 41])
assert_eq(r.current_choice, 1)
assert_eq(r.choices[1].name, "bluez_output.headphones")
}
///|
test "recording rows route to sources" {
let s = sample_state()
let r = @model.rows(s, Recording)[0]
assert_eq(r.title, "OBS")
assert_eq(r.choices.map(fn(c) { c.id }), [50])
assert_eq(r.current_choice, 0)
}
///|
test "device rows" {
let s = sample_state()
let outs = @model.rows(s, OutputDevices)
assert_eq(outs.map(fn(r) { r.is_default }), [true, false])
assert_eq(outs[1].volume_text, "50% (-18.06 dB)")
assert_eq(outs[0].subtitle, "alsa_output.pci.analog-stereo")
assert_eq(outs[0].choices, [])
let ins = @model.rows(s, InputDevices)
assert_eq(ins.length(), 1)
assert_true(ins[0].mute)
assert_true(ins[0].is_default)
assert_eq(ins[0].icon_name, "audio-input-microphone-symbolic")
}
///|
test "stream without app name falls back" {
let s = @model.State::new()
let _ = s.apply(Upsert(@model.Node::new(7, "Stream/Output/Audio")))
let r = @model.rows(s, Playback)[0]
assert_eq(r.title, "Stream 7")
assert_eq(r.current_choice, -1)
assert_false(r.has_volume)
assert_eq(r.volume_text, "")
}
///|
test "diff rows" {
let s = sample_state()
let before = @model.rows(s, OutputDevices)
let _ = s.apply(Remove(41))
let _ = s.apply(
Upsert(@model.Node::new(42, "Audio/Sink", description="HDMI")),
)
let _ = s.apply(Upsert({ ..s.nodes.get(40).unwrap(), mute: true, }))
let after = @model.rows(s, OutputDevices)
assert_eq(@model.diff_rows(before, after), {
removed: [41],
added: [42],
updated: [40],
})
assert_eq(@model.diff_rows(after, after), {
removed: [],
added: [],
updated: [],
})
}
///|
test "tab labels" {
assert_eq(@model.Tab::all().map(fn(t) { t.label() }), [
"Playback", "Recording", "Output Devices", "Input Devices",
])
}
+139
View File
@@ -0,0 +1,139 @@
// Volume model.
//
// PipeWire stores per-channel volumes as *linear* amplitude factors
// (`channelVolumes` in SPA_PARAM_Props, 1.0 = 0 dB). PulseAudio, and thus
// pavucontrol, shows a *cubic* scale: percent = cbrt(linear) * 100. wpctl and
// pipewire-pulse use the same mapping, so 50% here equals 50% in pavucontrol.
///|
/// Highest percentage the sliders allow (pavucontrol's "amplified" range).
pub const MAX_PERCENT : Double = 150.0
///|
/// 100% in the cubic scale, i.e. linear 1.0 (0 dB).
pub const NORM_PERCENT : Double = 100.0
///|
/// Linear amplitude -> cubic percentage (0.0 ..).
pub fn linear_to_percent(linear : Double) -> Double {
if linear <= 0.0 {
0.0
} else {
@math.cbrt(linear) * 100.0
}
}
///|
/// Cubic percentage -> linear amplitude. Clamped to [0, MAX_PERCENT].
pub fn percent_to_linear(percent : Double) -> Double {
let p = clamp_percent(percent) / 100.0
p * p * p
}
///|
pub fn clamp_percent(percent : Double) -> Double {
if percent.is_nan() || percent < 0.0 {
0.0
} else if percent > MAX_PERCENT {
MAX_PERCENT
} else {
percent
}
}
///|
/// Linear amplitude -> decibels. `None` means silence (-inf dB).
pub fn linear_to_db(linear : Double) -> Double? {
if linear <= 0.0 {
None
} else {
Some(20.0 * @math.log10(linear))
}
}
///|
/// The value a linked (single) slider shows for a set of channels: the
/// loudest channel, as pavucontrol does.
pub fn linked_percent(volumes : Array[Double]) -> Double {
let mut max = 0.0
for v in volumes {
if v > max {
max = v
}
}
linear_to_percent(max)
}
///|
/// New linear channel volumes after moving the linked slider to `percent`.
/// Channel balance is preserved: every channel is scaled by the same factor
/// so the loudest one ends at `percent`. If all channels are silent they are
/// set to the same value.
pub fn scale_linked(volumes : Array[Double], percent : Double) -> Array[Double] {
let target = percent_to_linear(percent)
let mut max = 0.0
for v in volumes {
if v > max {
max = v
}
}
if volumes.length() == 0 {
[target]
} else if max <= 0.0 {
volumes.map(fn(_) { target })
} else {
let factor = target / max
volumes.map(fn(v) { v * factor })
}
}
///|
/// "75%" style label, rounded to the nearest whole percent.
pub fn format_percent(percent : Double) -> String {
let rounded = (percent + 0.5).floor().to_int()
"\{rounded}%"
}
///|
/// "-7.50 dB" style label; silence is "-∞ dB".
pub fn format_db(linear : Double) -> String {
match linear_to_db(linear) {
None => "-∞ dB"
Some(db) => {
let neg = db < 0.0
let hundredths = ((if neg { -db } else { db }) * 100.0 + 0.5)
.floor()
.to_int()
let whole = hundredths / 100
let frac = hundredths % 100
let frac_s = if frac < 10 { "0\{frac}" } else { "\{frac}" }
let sign = if neg && hundredths != 0 { "-" } else { "" }
"\{sign}\{whole}.\{frac_s} dB"
}
}
}
///|
/// Tooltip/label text pavucontrol-style: "75% (-7.50 dB)".
pub fn format_volume(volumes : Array[Double]) -> String {
let mut max = 0.0
for v in volumes {
if v > max {
max = v
}
}
"\{format_percent(linear_to_percent(max))} (\{format_db(max)})"
}
///|
/// Echo suppression for sliders: after the user moves a slider we push the
/// value to PipeWire, which echoes it back slightly later. Remote updates that
/// arrive within `window_us` of a local change are ignored so the slider does
/// not jump back while being dragged.
pub fn should_apply_remote(
last_local_us : Int64,
now_us : Int64,
window_us~ : Int64 = 250_000L,
) -> Bool {
now_us - last_local_us >= window_us
}
+70
View File
@@ -0,0 +1,70 @@
///|
fn approx(a : Double, b : Double) -> Bool {
(a - b).abs() < 1.0e-9
}
///|
test "linear <-> percent uses the cubic scale" {
assert_true(approx(@model.linear_to_percent(1.0), 100.0))
assert_true(approx(@model.linear_to_percent(0.125), 50.0))
assert_true(approx(@model.linear_to_percent(0.0), 0.0))
assert_true(approx(@model.linear_to_percent(-1.0), 0.0))
assert_true(approx(@model.percent_to_linear(50.0), 0.125))
assert_true(approx(@model.percent_to_linear(150.0), 3.375))
}
///|
test "percent_to_linear clamps to 0..150" {
assert_true(approx(@model.percent_to_linear(200.0), 3.375))
assert_true(approx(@model.percent_to_linear(-5.0), 0.0))
assert_true(approx(@model.percent_to_linear(0.0 / 0.0), 0.0))
}
///|
test "round trip" {
for p in [0.0, 1.0, 33.3, 64.0, 100.0, 123.4, 150.0] {
assert_true(
(@model.linear_to_percent(@model.percent_to_linear(p)) - p).abs() < 1.0e-9,
)
}
}
///|
test "decibels" {
assert_eq(@model.linear_to_db(0.0), None)
assert_true(approx(@model.linear_to_db(1.0).unwrap(), 0.0))
assert_eq(@model.format_db(1.0), "0.00 dB")
assert_eq(@model.format_db(0.0), "-∞ dB")
// 50% cubic = 0.125 linear = -18.06 dB
assert_eq(@model.format_db(0.125), "-18.06 dB")
assert_eq(@model.format_db(3.375), "10.57 dB")
}
///|
test "format percent rounds" {
assert_eq(@model.format_percent(74.5), "75%")
assert_eq(@model.format_percent(74.4), "74%")
assert_eq(@model.format_percent(0.0), "0%")
assert_eq(@model.format_volume([0.125, 0.0]), "50% (-18.06 dB)")
}
///|
test "linked slider follows the loudest channel and keeps balance" {
assert_true(approx(@model.linked_percent([0.125, 1.0]), 100.0))
assert_true(approx(@model.linked_percent([]), 0.0))
let scaled = @model.scale_linked([0.5, 1.0], 50.0)
assert_true(approx(scaled[0], 0.0625))
assert_true(approx(scaled[1], 0.125))
// all silent: every channel gets the target
let from_zero = @model.scale_linked([0.0, 0.0], 100.0)
assert_true(approx(from_zero[0], 1.0) && approx(from_zero[1], 1.0))
// no channel info: a single value
assert_eq(@model.scale_linked([], 100.0).length(), 1)
}
///|
test "echo suppression window" {
assert_false(@model.should_apply_remote(1_000_000L, 1_100_000L))
assert_true(@model.should_apply_remote(1_000_000L, 1_300_000L))
assert_true(@model.should_apply_remote(0L, 1_000_000L, window_us=0L))
}
+16
View File
@@ -0,0 +1,16 @@
// moonmix: a pavucontrol-like volume control for PipeWire + WirePlumber.
// https://docs.moonbitlang.com/en/latest/toolchain/moon/module.html
name = "geordi/moonmix"
version = "0.1.0" // sweet-version
readme = "README.md"
repository = "https://git.site.latha.org/geordi/moonmix"
keywords = [ "pipewire", "wireplumber", "gtk4", "audio", "mixer" ]
preferred_target = "native"
description = "pavucontrol-like volume control for PipeWire/WirePlumber, written in MoonBit"
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
# Archiver companion of tools/pkg-cc (moon derives its name from the cc name).
exec "${MOONMIX_AR:-ar}" "$@"
Executable
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# C compiler wrapper used by moon.pkg (link.native.stub-cc / cc): moon does
# not expand $(pkg-config ...) in flags, so append them here. Works for both
# compiling stubs and linking the final executable.
set -e
PKGS="${MOONMIX_PKGS:-libpipewire-0.3 wireplumber-0.5 gtk4}"
exec "${MOONMIX_CC:-cc}" "$@" $(pkg-config --cflags --libs $PKGS)
+153
View File
@@ -0,0 +1,153 @@
#!/bin/sh
# Headless smoke test: start a private PipeWire + WirePlumber (two null
# sinks, a loopback virtual microphone, a playback and a capture stream),
# run every moonmix-probe action and check its effect, then, if
# gtk4-broadwayd is available, render GUI screenshots.
#
# Only this *test harness* uses pw-cat (to create a playing stream); moonmix
# itself talks to PipeWire through libwireplumber.
#
# tools/smoke-test.sh [screenshot-prefix]
set -eu
ROOT=$(cd "$(dirname "$0")/.." && pwd)
BUILD="$ROOT/_build/native/debug/build/cmd"
PROBE="$BUILD/moonmix-probe/moonmix-probe.exe"
GUI="$BUILD/moonmix/moonmix.exe"
SHOTS="${1:-}"
export XDG_RUNTIME_DIR="$(mktemp -d)"
export PIPEWIRE_RUNTIME_DIR="$XDG_RUNTIME_DIR"
export XDG_CONFIG_HOME="$XDG_RUNTIME_DIR/config"
export XDG_STATE_HOME="$XDG_RUNTIME_DIR/state"
mkdir -p "$XDG_CONFIG_HOME/pipewire/pipewire.conf.d" "$XDG_STATE_HOME"
cat > "$XDG_CONFIG_HOME/pipewire/pipewire.conf.d/moonmix-test.conf" <<'CONF'
context.objects = [
{ factory = adapter
args = { factory.name = support.null-audio-sink
node.name = "test_speakers" node.description = "Test Speakers"
media.class = "Audio/Sink" audio.position = [ FL FR ]
monitor.channel-volumes = true object.linger = true } }
{ factory = adapter
args = { factory.name = support.null-audio-sink
node.name = "test_headphones" node.description = "Test Headphones"
media.class = "Audio/Sink" audio.position = [ FL FR ]
object.linger = true } }
]
# The microphone is a loopback virtual source, like echo-cancel creates.
context.modules = [
{ name = libpipewire-module-loopback
args = {
node.description = "Test Microphone"
capture.props = { node.name = "test_mic_capture" node.passive = true audio.position = [ MONO ] }
playback.props = { node.name = "test_mic" media.class = "Audio/Source" audio.position = [ MONO ] }
} }
]
CONF
# Ubuntu's WirePlumber asks snapd before granting clients access; there is
# no snapd in a sandbox/CI container, so turn that off for the test session.
mkdir -p "$XDG_CONFIG_HOME/wireplumber/wireplumber.conf.d"
cat > "$XDG_CONFIG_HOME/wireplumber/wireplumber.conf.d/moonmix-test.conf" <<'CONF'
wireplumber.profiles = {
main = {
support.snapd-permission-prompting = disabled
script.client.access-snap = disabled
}
}
CONF
PIDS=""
cleanup() { for p in $PIDS; do kill "$p" 2>/dev/null || true; done; [ -n "${KEEP:-}" ] || rm -rf "$XDG_RUNTIME_DIR"; }
trap cleanup EXIT INT TERM
pipewire >"$XDG_RUNTIME_DIR/pipewire.log" 2>&1 & PIDS="$PIDS $!"
sleep 1
wireplumber >"$XDG_RUNTIME_DIR/wireplumber.log" 2>&1 & PIDS="$PIDS $!"
# wait_for <pattern>: poll the probe (up to ~20 s) until it prints pattern.
wait_for() {
for _ in $(seq 1 40); do
"$PROBE" 2>/dev/null | grep -q -- "$1" && return 0
sleep 0.5
done
echo "timed out waiting for '$1'"
return 1
}
# Let WirePlumber finish its startup (it has picked a default sink) before
# any stream appears: streams that show up while it is still initialising
# can wedge its event queue, after which nothing gets linked.
wait_for '\[default'
LOGS="$XDG_RUNTIME_DIR"
# Two minutes of stereo s16 48 kHz silence as a WAV file (header written by
# hand: no python/sox needed). Reading raw audio from /dev/zero made older
# pw-cat (PipeWire 1.4) exit without creating a stream.
le32() { printf "\\$(printf %03o $(($1 & 255)))\\$(printf %03o $(($1 >> 8 & 255)))\\$(printf %03o $(($1 >> 16 & 255)))\\$(printf %03o $(($1 >> 24 & 255)))"; }
DATA=23040000
{ printf 'RIFF'; le32 $((DATA + 36)); printf 'WAVEfmt '; le32 16
printf '\001\000\002\000'; le32 48000; le32 192000; printf '\004\000\020\000'
printf 'data'; le32 $DATA; head -c $DATA /dev/zero; } > "$LOGS/silence.wav"
{ pw-play -P '{ application.name = "Test Player" media.name = "Smoke test tone" }' \
"$LOGS/silence.wav"; echo "pw-play exited with $?"; } >"$LOGS/play.log" 2>&1 & PIDS="$PIDS $!"
pw-cat --record --raw --rate 48000 --channels 1 --format s16 \
-P '{ application.name = "Test Recorder" media.name = "Mic capture" }' \
/dev/null >"$LOGS/record.log" 2>&1 & PIDS="$PIDS $!"
wait_for 'Test Player | .*-> ' || true
fail=0
OUT="$LOGS/probe.out"
# step <expected-pattern> <probe args...>: run the probe and require the
# pattern in what it prints after the action.
step() {
want=$1; shift
echo "### $* (expect: $want)"
if ! "$PROBE" "$@" >"$OUT" 2>&1; then
echo "FAIL: probe exited with an error"; fail=1
fi
cat "$OUT"
# After an action the probe prints the state again; check only that part.
if ! sed -n '/^== action/,$p' "$OUT" | grep -q -- "$want" && ! { [ $# -eq 0 ] && grep -q -- "$want" "$OUT"; }; then
echo "FAIL: expected '$want'"; fail=1
fi
}
step 'Test Player | 100%'
# Change the volume of the sink the test stream plays to: in CI (PipeWire
# 1.4) a volume set on an idle, suspended null sink was not applied.
step 'Test Speakers | 50% (-18.06 dB)' volume test_speakers 50
step 'Test Microphone | .*muted' mute test_mic 1
step 'Test Headphones | .*\[default\]' default test_headphones
STREAM=$("$PROBE" | awk -F: '/Test Player/ {gsub(/ /,"",$1); print $1; exit}')
step 'Test Player | .*-> Test Speakers' move "${STREAM:-0}" test_speakers
if [ "$fail" != 0 ]; then
echo "### diagnostics"
echo "--- pw-play playback:"; cat "$LOGS/play.log"
echo "--- pw-cat record:"; cat "$LOGS/record.log"
echo "--- wireplumber (warnings/errors):"
grep -E '^[EWC] ' "$LOGS/wireplumber.log" | grep -viE 'rtkit|d-?bus|bluez|camera|session bus|system bus' | tail -40
if command -v pw-dump >/dev/null; then
echo "--- nodes:"
pw-dump 2>/dev/null | python3 -c '
import json, sys
for o in json.load(sys.stdin):
t = o["type"].split(":")[-1]; i = o.get("info") or {}; p = i.get("props") or {}
if t == "Link": print("link", i.get("output-node-id"), "->", i.get("input-node-id"), i.get("state"))
if t == "Node":
props = (i.get("params") or {}).get("Props") or [{}]
print("node", o["id"], p.get("node.name"), p.get("media.class"), i.get("state"),
"vol", props[0].get("channelVolumes"), "mute", props[0].get("mute"))
' 2>/dev/null || true
fi
fi
if [ -n "$SHOTS" ] && [ -x "$GUI" ]; then
echo "### GUI screenshots -> $SHOTS-<tab>.png"
if command -v gtk4-broadwayd >/dev/null; then
gtk4-broadwayd :5 >/dev/null 2>&1 & PIDS="$PIDS $!"
sleep 1
GDK_BACKEND=broadway BROADWAY_DISPLAY=:5 MOONMIX_SCREENSHOT="$SHOTS" \
timeout 30 "$GUI" || fail=1
else
echo "gtk4-broadwayd not found; skipping GUI"
fi
fi
exit $fail
+14
View File
@@ -0,0 +1,14 @@
// WirePlumber/PipeWire binding (native only). See wp_stub.c.
import {
"geordi/moonmix/model",
"moonbitlang/core/encoding/utf8",
}
supported_targets = "-all+native"
options(
"native-stub": [ "wp_stub.c" ],
// moon does not expand $(pkg-config ...) in flags; tools/pkg-cc appends
// `pkg-config --cflags --libs` for PipeWire, WirePlumber and GTK4.
link: { "native": { "stub-cc": "tools/pkg-cc" } },
)
+58
View File
@@ -0,0 +1,58 @@
// Generated using `moon info`, DON'T EDIT IT
package "geordi/moonmix/wp"
import {
"geordi/moonmix/model",
}
// Values
pub fn move_stream(Int32, Int32) -> Bool
pub fn node_ids() -> Array[Int32]
pub fn node_prop(Int32, String) -> String
pub fn on_event((Event) -> Unit) -> Unit
pub fn quit() -> Unit
pub fn read_defaults() -> @model.Event
pub fn read_links() -> Array[@model.Link]
pub fn read_node(Int32) -> @model.Node?
pub fn run() -> Unit
pub fn set_default_sink(Int32) -> Bool
pub fn set_default_source(Int32) -> Bool
pub fn set_mute(Int32, Bool) -> Bool
pub fn set_volumes(Int32, Array[Double]) -> Bool
pub fn start() -> Bool
pub fn timeout(Int32, Int32) -> Unit
pub fn to_model_events(Event) -> Array[@model.Event]
// Errors
// Types and methods
pub(all) enum Event {
NodeAdded(Int32)
NodeChanged(Int32)
NodeRemoved(Int32)
LinksChanged
DefaultsChanged
Ready
Disconnected
PluginError
Timeout(Int32)
}
// Type aliases
// Traits
+266
View File
@@ -0,0 +1,266 @@
// MoonBit side of the WirePlumber binding (see wp_stub.c).
//
// `start` connects to PipeWire through libwireplumber and loads the
// mixer-api and default-nodes-api plugins. Every change arrives as an
// `Event` through the handler; `read_node`, `read_links` and
// `read_defaults` turn the current WirePlumber state into @model events.
///|
pub(all) enum Event {
NodeAdded(Int32)
NodeChanged(Int32)
NodeRemoved(Int32)
LinksChanged
DefaultsChanged
/// Plugins loaded and initial object set known: do a full sync.
Ready
Disconnected
/// A plugin failed to load (wireplumber modules missing?).
PluginError
/// One-shot timer from `timeout`, carrying its tag.
Timeout(Int32)
}
///|
fn decode_event(kind : Int32, id : Int32) -> Event? {
match kind {
1 => Some(NodeAdded(id))
2 => Some(NodeChanged(id))
3 => Some(NodeRemoved(id))
4 => Some(LinksChanged)
5 => Some(DefaultsChanged)
6 => Some(Ready)
7 => Some(Disconnected)
8 => Some(PluginError)
9 => Some(Timeout(id))
_ => None
}
}
///|
extern "C" fn ffi_set_handler(
call : FuncRef[((Int32, Int32) -> Unit, Int32, Int32) -> Unit],
closure : (Int32, Int32) -> Unit,
) = "mm_wp_set_handler"
///|
extern "C" fn ffi_start() -> Int32 = "mm_wp_start"
///|
extern "C" fn ffi_timeout(ms : Int32, tag : Int32) = "mm_wp_timeout"
///|
extern "C" fn ffi_run() = "mm_wp_run"
///|
extern "C" fn ffi_quit() = "mm_wp_quit"
///|
extern "C" fn ffi_node_count() -> Int32 = "mm_wp_node_count"
///|
extern "C" fn ffi_node_id_at(i : Int32) -> Int32 = "mm_wp_node_id_at"
///|
extern "C" fn ffi_node_exists(id : Int32) -> Int32 = "mm_wp_node_exists"
///|
#borrow(key)
extern "C" fn ffi_node_prop(id : Int32, key : Bytes) -> Bytes = "mm_wp_node_prop"
///|
extern "C" fn ffi_query_volume(id : Int32) -> Int32 = "mm_wp_query_volume"
///|
extern "C" fn ffi_volume_at(ch : Int32) -> Double = "mm_wp_volume_at"
///|
extern "C" fn ffi_mute() -> Int32 = "mm_wp_mute"
///|
extern "C" fn ffi_link_count() -> Int32 = "mm_wp_link_count"
///|
extern "C" fn ffi_link_end(i : Int32, input : Int32) -> Int32 = "mm_wp_link_end"
///|
extern "C" fn ffi_default_node(kind : Int32) -> Int32 = "mm_wp_default_node"
///|
#borrow(vols)
extern "C" fn ffi_set_volumes(
id : Int32,
vols : FixedArray[Double],
n : Int32,
) -> Int32 = "mm_wp_set_volumes"
///|
extern "C" fn ffi_set_mute(id : Int32, mute : Int32) -> Int32 = "mm_wp_set_mute"
///|
extern "C" fn ffi_set_default(kind : Int32, id : Int32) -> Int32 = "mm_wp_set_default"
///|
extern "C" fn ffi_move_stream(stream : Int32, device : Int32) -> Int32 = "mm_wp_move_stream"
///|
/// NUL-terminated UTF-8 for C.
fn cstr(s : String) -> Bytes {
let b = @utf8.encode(s)
let n = b.length()
Bytes::makei(n + 1, fn(i) { if i < n { b[i] } else { b'\x00' } })
}
///|
/// Register the single event handler. Call before `start`.
pub fn on_event(f : (Event) -> Unit) -> Unit {
ffi_set_handler(fn(g, kind, id) { g(kind, id) }, fn(kind, id) {
match decode_event(kind, id) {
Some(ev) => f(ev)
None => ()
}
})
}
///|
/// Connect to PipeWire. False if the daemon is not reachable.
pub fn start() -> Bool {
ffi_start() == 0
}
///|
pub fn timeout(ms : Int32, tag : Int32) -> Unit {
ffi_timeout(ms, tag)
}
///|
/// Run a plain GLib main loop (headless tools; the GUI runs GTK's loop).
pub fn run() -> Unit {
ffi_run()
}
///|
pub fn quit() -> Unit {
ffi_quit()
}
///|
pub fn node_ids() -> Array[Int32] {
let n = ffi_node_count()
Array::makei(n, fn(i) { ffi_node_id_at(i) })
}
///|
pub fn node_prop(id : Int32, key : String) -> String {
@utf8.decode_lossy(ffi_node_prop(id, cstr(key)))
}
///|
/// Current state of a node as a model node, or None if it is gone.
pub fn read_node(id : Int32) -> @model.Node? {
if ffi_node_exists(id) == 0 {
return None
}
let nch = ffi_query_volume(id)
let volumes = Array::makei(nch, fn(ch) { ffi_volume_at(ch) })
let mute = ffi_mute() != 0
let description = {
let d = node_prop(id, "node.description")
if d != "" {
d
} else {
node_prop(id, "node.nick")
}
}
let icon = {
let a = node_prop(id, "application.icon-name")
if a != "" {
a
} else {
node_prop(id, "device.icon-name")
}
}
Some(
@model.Node::new(
id,
node_prop(id, "media.class"),
name=node_prop(id, "node.name"),
description~,
app_name=node_prop(id, "application.name"),
media_name=node_prop(id, "media.name"),
icon_name=icon,
volumes~,
mute~,
),
)
}
///|
pub fn read_links() -> Array[@model.Link] {
let n = ffi_link_count()
Array::makei(n, fn(i) {
{ output_node: ffi_link_end(i, 0), input_node: ffi_link_end(i, 1), }
})
}
///|
pub fn read_defaults() -> @model.Event {
Defaults(sink=ffi_default_node(0), source=ffi_default_node(1))
}
///|
/// Translate a WirePlumber event into model events (pulling fresh data).
pub fn to_model_events(ev : Event) -> Array[@model.Event] {
match ev {
NodeAdded(id) | NodeChanged(id) =>
match read_node(id) {
Some(n) => [Upsert(n)]
None => []
}
NodeRemoved(id) => [Remove(id)]
LinksChanged => [Links(read_links())]
DefaultsChanged => [read_defaults()]
Ready => {
let evs : Array[@model.Event] = [Reset]
for id in node_ids() {
match read_node(id) {
Some(n) => evs.push(Upsert(n))
None => ()
}
}
evs.push(Links(read_links()))
evs.push(read_defaults())
evs
}
Disconnected => [Reset]
PluginError | Timeout(_) => []
}
}
///|
/// Set linear channel volumes.
pub fn set_volumes(id : Int32, volumes : Array[Double]) -> Bool {
let arr = FixedArray::makei(volumes.length(), fn(i) { volumes[i] })
ffi_set_volumes(id, arr, arr.length()) != 0
}
///|
pub fn set_mute(id : Int32, mute : Bool) -> Bool {
ffi_set_mute(id, if mute { 1 } else { 0 }) != 0
}
///|
pub fn set_default_sink(id : Int32) -> Bool {
ffi_set_default(0, id) != 0
}
///|
pub fn set_default_source(id : Int32) -> Bool {
ffi_set_default(1, id) != 0
}
///|
/// Route a playback/record stream to another sink/source.
pub fn move_stream(stream_id : Int32, device_id : Int32) -> Bool {
ffi_move_stream(stream_id, device_id) != 0
}
+462
View File
@@ -0,0 +1,462 @@
/*
* moonmix: thin C layer over libwireplumber-0.5.
*
* Exactly what wpctl does internally, without spawning wpctl:
* - a WpObjectManager watching audio WpNodes, WpLinks and the "default"
* WpMetadata;
* - the "mixer-api" plugin for per-channel volume and mute (it handles
* device routes for hardware sinks, so it is what pavucontrol's numbers
* correspond to);
* - the "default-nodes-api" plugin for the default sink/source.
*
* MoonBit gets a single callback (kind, id) for every change and pulls the
* details it needs through small accessor functions. All calls happen on the
* GLib default main context (shared with GTK), so no locking is needed.
*/
#include <string.h>
#include <wp/wp.h>
#include <pipewire/keys.h>
#include "moonbit.h"
enum {
MM_EV_NODE_ADDED = 1,
MM_EV_NODE_CHANGED = 2,
MM_EV_NODE_REMOVED = 3,
MM_EV_LINKS_CHANGED = 4,
MM_EV_DEFAULTS_CHANGED = 5,
MM_EV_READY = 6,
MM_EV_DISCONNECTED = 7,
MM_EV_ERROR = 8,
MM_EV_TIMEOUT = 9,
};
typedef void (*mm_call_t)(void *closure, int32_t kind, int32_t id);
static mm_call_t g_call;
static void *g_closure;
static WpCore *g_core;
static WpObjectManager *g_om;
static WpPlugin *g_mixer;
static WpPlugin *g_defaults;
static GMainLoop *g_loop;
static int g_pending;
static gboolean g_om_installed;
static gboolean g_ready_sent;
static void emit(int32_t kind, int32_t id) {
if (g_call) {
/* MoonBit functions take ownership of their arguments. */
moonbit_incref(g_closure);
g_call(g_closure, kind, id);
}
}
MOONBIT_FFI_EXPORT void mm_wp_set_handler(mm_call_t call, void *closure) {
if (g_closure)
moonbit_decref(g_closure);
g_call = call;
g_closure = closure; /* owned, kept for the program lifetime */
}
/* ---- helpers ------------------------------------------------------------ */
static moonbit_bytes_t to_bytes(const char *s) {
size_t n = s ? strlen(s) : 0;
moonbit_bytes_t b = moonbit_make_bytes((int32_t)n, 0);
if (n)
memcpy(b, s, n);
return b;
}
static WpNode *lookup_node(guint32 id) {
if (!g_om)
return NULL;
return wp_object_manager_lookup(g_om, WP_TYPE_NODE,
WP_CONSTRAINT_TYPE_G_PROPERTY, "bound-id",
"=u", id, NULL);
}
static WpMetadata *lookup_default_metadata(void) {
if (!g_om)
return NULL;
return wp_object_manager_lookup(g_om, WP_TYPE_METADATA,
WP_CONSTRAINT_TYPE_PW_GLOBAL_PROPERTY,
"metadata.name", "=s", "default", NULL);
}
static void maybe_ready(void) {
if (!g_ready_sent && g_pending == 0 && g_om_installed) {
g_ready_sent = TRUE;
emit(MM_EV_READY, 0);
}
}
/* ---- signal handlers ---------------------------------------------------- */
static void on_node_props(GObject *obj, GParamSpec *pspec, gpointer data) {
(void)pspec;
(void)data;
emit(MM_EV_NODE_CHANGED, (int32_t)wp_proxy_get_bound_id(WP_PROXY(obj)));
}
static void on_object_added(WpObjectManager *om, GObject *obj, gpointer d) {
(void)om;
(void)d;
if (WP_IS_NODE(obj)) {
g_signal_connect(obj, "notify::properties", G_CALLBACK(on_node_props),
NULL);
emit(MM_EV_NODE_ADDED, (int32_t)wp_proxy_get_bound_id(WP_PROXY(obj)));
} else if (WP_IS_LINK(obj)) {
emit(MM_EV_LINKS_CHANGED, 0);
}
}
static void on_object_removed(WpObjectManager *om, GObject *obj, gpointer d) {
(void)om;
(void)d;
if (WP_IS_NODE(obj)) {
g_signal_handlers_disconnect_by_func(obj, on_node_props, NULL);
emit(MM_EV_NODE_REMOVED, (int32_t)wp_proxy_get_bound_id(WP_PROXY(obj)));
} else if (WP_IS_LINK(obj)) {
emit(MM_EV_LINKS_CHANGED, 0);
}
}
static void on_installed(WpObjectManager *om, gpointer d) {
(void)om;
(void)d;
g_om_installed = TRUE;
maybe_ready();
}
static void on_mixer_changed(WpPlugin *p, guint id, gpointer d) {
(void)p;
(void)d;
emit(MM_EV_NODE_CHANGED, (int32_t)id);
}
static void on_defaults_changed(WpPlugin *p, gpointer d) {
(void)p;
(void)d;
emit(MM_EV_DEFAULTS_CHANGED, 0);
}
static void on_disconnected(WpCore *core, gpointer d) {
(void)core;
(void)d;
emit(MM_EV_DISCONNECTED, 0);
}
static void on_plugin_loaded(GObject *src, GAsyncResult *res, gpointer d) {
const char *plugin_name = d;
g_autoptr(GError) error = NULL;
if (!wp_core_load_component_finish(WP_CORE(src), res, &error)) {
g_warning("moonmix: failed to load %s: %s", plugin_name,
error ? error->message : "?");
emit(MM_EV_ERROR, 1);
return;
}
if (g_str_equal(plugin_name, "mixer-api")) {
g_mixer = wp_plugin_find(g_core, "mixer-api");
if (g_mixer) {
/* 0 = linear: report raw channelVolumes, the MoonBit side does the
* cubic (pavucontrol) mapping. */
g_object_set(g_mixer, "scale", 0, NULL);
g_signal_connect(g_mixer, "changed", G_CALLBACK(on_mixer_changed),
NULL);
}
} else {
g_defaults = wp_plugin_find(g_core, "default-nodes-api");
if (g_defaults)
g_signal_connect(g_defaults, "changed", G_CALLBACK(on_defaults_changed),
NULL);
}
g_pending--;
if (g_pending == 0) {
/* Install the object manager only after the plugins are up, like wpctl
* does, so the first full sync already has volumes and defaults. */
wp_core_install_object_manager(g_core, g_om);
}
maybe_ready();
}
/* ---- lifecycle ---------------------------------------------------------- */
/* Returns 0 on success, -1 if PipeWire is not reachable. Events follow on
* the main loop; MM_EV_READY once the initial state is known. */
MOONBIT_FFI_EXPORT int32_t mm_wp_start(void) {
if (g_core)
return 0;
wp_init(WP_INIT_PIPEWIRE | WP_INIT_SPA_TYPES | WP_INIT_SET_GLIB_LOG);
g_autoptr(WpProperties) props =
wp_properties_new(PW_KEY_APP_NAME, "moonmix", NULL);
g_core = wp_core_new(NULL, NULL, g_steal_pointer(&props));
if (!wp_core_connect(g_core)) {
g_clear_object(&g_core);
return -1;
}
g_signal_connect(g_core, "disconnected", G_CALLBACK(on_disconnected), NULL);
g_om = wp_object_manager_new();
wp_object_manager_add_interest(g_om, WP_TYPE_NODE,
WP_CONSTRAINT_TYPE_PW_PROPERTY, "media.class",
"#s", "*Audio*", NULL);
wp_object_manager_add_interest(g_om, WP_TYPE_LINK, NULL);
wp_object_manager_add_interest(g_om, WP_TYPE_METADATA,
WP_CONSTRAINT_TYPE_PW_GLOBAL_PROPERTY,
"metadata.name", "=s", "default", NULL);
wp_object_manager_request_object_features(
g_om, WP_TYPE_GLOBAL_PROXY, WP_PIPEWIRE_OBJECT_FEATURES_MINIMAL);
wp_object_manager_request_object_features(g_om, WP_TYPE_METADATA,
WP_OBJECT_FEATURES_ALL);
g_signal_connect(g_om, "object-added", G_CALLBACK(on_object_added), NULL);
g_signal_connect(g_om, "object-removed", G_CALLBACK(on_object_removed),
NULL);
g_signal_connect(g_om, "installed", G_CALLBACK(on_installed), NULL);
g_pending = 2;
wp_core_load_component(g_core, "libwireplumber-module-mixer-api", "module",
NULL, NULL, NULL,
(GAsyncReadyCallback)on_plugin_loaded,
(gpointer) "mixer-api");
wp_core_load_component(g_core, "libwireplumber-module-default-nodes-api",
"module", NULL, NULL, NULL,
(GAsyncReadyCallback)on_plugin_loaded,
(gpointer) "default-nodes-api");
return 0;
}
static gboolean on_timeout(gpointer d) {
emit(MM_EV_TIMEOUT, GPOINTER_TO_INT(d));
return G_SOURCE_REMOVE;
}
/* One-shot timer delivering MM_EV_TIMEOUT with `tag` as id. */
MOONBIT_FFI_EXPORT void mm_wp_timeout(int32_t ms, int32_t tag) {
g_timeout_add((guint)ms, on_timeout, GINT_TO_POINTER(tag));
}
/* Standalone main loop for the headless probe (the GUI uses GTK's). */
MOONBIT_FFI_EXPORT void mm_wp_run(void) {
if (!g_loop)
g_loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(g_loop);
}
MOONBIT_FFI_EXPORT void mm_wp_quit(void) {
if (g_loop)
g_main_loop_quit(g_loop);
}
/* ---- queries ------------------------------------------------------------ */
static GArray *g_ids; /* snapshot for mm_wp_node_count/mm_wp_node_id_at */
MOONBIT_FFI_EXPORT int32_t mm_wp_node_count(void) {
if (!g_ids)
g_ids = g_array_new(FALSE, FALSE, sizeof(guint32));
g_array_set_size(g_ids, 0);
if (!g_om)
return 0;
g_autoptr(WpIterator) it = wp_object_manager_new_filtered_iterator(
g_om, WP_TYPE_NODE, NULL);
g_auto(GValue) val = G_VALUE_INIT;
for (; wp_iterator_next(it, &val); g_value_unset(&val)) {
guint32 id = wp_proxy_get_bound_id(WP_PROXY(g_value_get_object(&val)));
g_array_append_val(g_ids, id);
}
return (int32_t)g_ids->len;
}
MOONBIT_FFI_EXPORT int32_t mm_wp_node_id_at(int32_t i) {
if (!g_ids || i < 0 || (guint)i >= g_ids->len)
return -1;
return (int32_t)g_array_index(g_ids, guint32, i);
}
MOONBIT_FFI_EXPORT int32_t mm_wp_node_exists(int32_t id) {
g_autoptr(WpNode) node = lookup_node((guint32)id);
return node != NULL;
}
/* A PipeWire property of a node ("node.name", "media.class", ...), "" if
* unset. `key` is NUL-terminated UTF-8. */
MOONBIT_FFI_EXPORT moonbit_bytes_t mm_wp_node_prop(int32_t id,
moonbit_bytes_t key) {
g_autoptr(WpNode) node = lookup_node((guint32)id);
const char *v = NULL;
if (node)
v = wp_pipewire_object_get_property(WP_PIPEWIRE_OBJECT(node),
(const char *)key);
return to_bytes(v);
}
/* Volume of the last queried node. */
#define MM_MAX_CH 64
static double g_vol[MM_MAX_CH];
static int g_nch;
static int g_mute;
/* Asks mixer-api for a node's volume. Returns the channel count (0 if the
* node has no volume control yet), then read mm_wp_volume_at / mm_wp_mute. */
MOONBIT_FFI_EXPORT int32_t mm_wp_query_volume(int32_t id) {
g_nch = 0;
g_mute = 0;
if (!g_mixer)
return 0;
GVariant *v = NULL;
g_signal_emit_by_name(g_mixer, "get-volume", (guint)id, &v);
if (!v)
return 0;
gboolean mute = FALSE;
g_variant_lookup(v, "mute", "b", &mute);
g_mute = mute;
g_autoptr(GVariant) chans =
g_variant_lookup_value(v, "channelVolumes", G_VARIANT_TYPE_VARDICT);
if (chans) {
GVariantIter iter;
const char *key;
GVariant *ch;
g_variant_iter_init(&iter, chans);
while (g_variant_iter_loop(&iter, "{&sv}", &key, &ch)) {
int idx = atoi(key);
double vol = 0;
if (idx >= 0 && idx < MM_MAX_CH && g_variant_lookup(ch, "volume", "d", &vol)) {
g_vol[idx] = vol;
if (idx + 1 > g_nch)
g_nch = idx + 1;
}
}
} else {
double vol;
if (g_variant_lookup(v, "volume", "d", &vol)) {
g_vol[0] = vol;
g_nch = 1;
}
}
g_variant_unref(v);
return g_nch;
}
MOONBIT_FFI_EXPORT double mm_wp_volume_at(int32_t ch) {
return (ch >= 0 && ch < g_nch) ? g_vol[ch] : 0.0;
}
MOONBIT_FFI_EXPORT int32_t mm_wp_mute(void) { return g_mute; }
/* Links snapshot. */
static GArray *g_links;
MOONBIT_FFI_EXPORT int32_t mm_wp_link_count(void) {
if (!g_links)
g_links = g_array_new(FALSE, FALSE, sizeof(guint32) * 2);
g_array_set_size(g_links, 0);
if (!g_om)
return 0;
g_autoptr(WpIterator) it = wp_object_manager_new_filtered_iterator(
g_om, WP_TYPE_LINK, NULL);
g_auto(GValue) val = G_VALUE_INIT;
for (; wp_iterator_next(it, &val); g_value_unset(&val)) {
guint32 pair[2] = {0, 0};
guint32 out_port, in_port;
wp_link_get_linked_object_ids(WP_LINK(g_value_get_object(&val)), &pair[0],
&out_port, &pair[1], &in_port);
g_array_append_val(g_links, pair);
}
return (int32_t)g_links->len;
}
MOONBIT_FFI_EXPORT int32_t mm_wp_link_end(int32_t i, int32_t input) {
if (!g_links || i < 0 || (guint)i >= g_links->len)
return -1;
guint32 *pair = &g_array_index(g_links, guint32, i * 2);
return (int32_t)pair[input ? 1 : 0];
}
static const char *class_for(int32_t kind) {
return kind == 0 ? "Audio/Sink" : "Audio/Source";
}
/* Default node id for kind 0 = sink, 1 = source; -1 if none. */
MOONBIT_FFI_EXPORT int32_t mm_wp_default_node(int32_t kind) {
if (!g_defaults)
return -1;
guint32 id = SPA_ID_INVALID;
g_signal_emit_by_name(g_defaults, "get-default-node", class_for(kind), &id);
return id == SPA_ID_INVALID ? -1 : (int32_t)id;
}
/* ---- actions ------------------------------------------------------------ */
/* Set linear per-channel volumes. */
MOONBIT_FFI_EXPORT int32_t mm_wp_set_volumes(int32_t id, double *vols,
int32_t n) {
if (!g_mixer || n <= 0)
return 0;
GVariantBuilder chans;
g_variant_builder_init(&chans, G_VARIANT_TYPE_VARDICT);
for (int i = 0; i < n; i++) {
GVariantBuilder ch;
g_variant_builder_init(&ch, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&ch, "{sv}", "volume", g_variant_new_double(vols[i]));
char key[16];
g_snprintf(key, sizeof key, "%d", i);
g_variant_builder_add(&chans, "{sv}", key, g_variant_builder_end(&ch));
}
GVariantBuilder b;
g_variant_builder_init(&b, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&b, "{sv}", "channelVolumes",
g_variant_builder_end(&chans));
gboolean ok = FALSE;
g_signal_emit_by_name(g_mixer, "set-volume", (guint)id,
g_variant_builder_end(&b), &ok);
return ok;
}
MOONBIT_FFI_EXPORT int32_t mm_wp_set_mute(int32_t id, int32_t mute) {
if (!g_mixer)
return 0;
GVariantBuilder b;
g_variant_builder_init(&b, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&b, "{sv}", "mute", g_variant_new_boolean(mute != 0));
gboolean ok = FALSE;
g_signal_emit_by_name(g_mixer, "set-volume", (guint)id,
g_variant_builder_end(&b), &ok);
return ok;
}
/* Make node `id` the configured default sink (kind 0) or source (kind 1). */
MOONBIT_FFI_EXPORT int32_t mm_wp_set_default(int32_t kind, int32_t id) {
if (!g_defaults)
return 0;
g_autoptr(WpNode) node = lookup_node((guint32)id);
if (!node)
return 0;
const char *name = wp_pipewire_object_get_property(WP_PIPEWIRE_OBJECT(node),
PW_KEY_NODE_NAME);
if (!name)
return 0;
gboolean ok = FALSE;
g_signal_emit_by_name(g_defaults, "set-default-configured-node-name",
class_for(kind), name, &ok);
return ok;
}
/* Route a stream to another device, the way pipewire-pulse implements
* pavucontrol's move: set "target.object" (the device's object.serial) on
* the stream in the "default" metadata; WirePlumber relinks it. */
MOONBIT_FFI_EXPORT int32_t mm_wp_move_stream(int32_t stream_id,
int32_t device_id) {
g_autoptr(WpMetadata) m = lookup_default_metadata();
g_autoptr(WpNode) dev = lookup_node((guint32)device_id);
if (!m || !dev)
return 0;
const char *serial = wp_pipewire_object_get_property(
WP_PIPEWIRE_OBJECT(dev), PW_KEY_OBJECT_SERIAL);
if (!serial)
return 0;
wp_metadata_set(m, (guint32)stream_id, "target.node", NULL, NULL);
wp_metadata_set(m, (guint32)stream_id, "target.object", "Spa:Id", serial);
return 1;
}