Author SHA1 Message Date
SpriteandClaude Opus 5.5 bbef4b8ef7 fix: play a WAV file with pw-play in the smoke test
CI / check (pull_request) Successful in 9s
CI / native (pull_request) Successful in 1m3s
In CI (PipeWire 1.4) pw-cat playing raw audio never created a stream,
from /dev/zero or from a regular file, so the Playback tab and the move
action could not be tested. Play a generated WAV file with pw-play
instead (header written in shell; the container has no python) and log
the player's exit status for diagnosis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:14:00 +00:00
SpriteandClaude Opus 5.5 4147eaeaa4 fix: let WirePlumber settle before the smoke test starts streams
CI / check (pull_request) Successful in 10s
CI / native (pull_request) Failing after 1m33s
Streams that appear while WirePlumber is still starting up can wedge its
event queue: no default sink is chosen, nothing is linked and volume
changes are dropped. This made the smoke test fail intermittently
locally and in CI. The test now polls moonmix-probe until a default sink
exists before starting the streams, then until the playback stream is
linked; four local runs in a row pass.

Also play a regular file instead of /dev/zero (PipeWire 1.4's pw-cat
exited silently on it in CI) and change the volume of the active sink,
since CI's PipeWire 1.4 did not apply a volume set on a suspended
null sink.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:03:55 +00:00
SpriteandClaude Opus 5.5 6c7f45d5f9 fix: make the smoke test check results and avoid a WirePlumber stall
CI / check (pull_request) Successful in 9s
CI / native (pull_request) Failing after 1m4s
The smoke test only checked exit codes, so CI passed the probe steps
even though volume and mute never changed. Each step now asserts the
expected state after the action and prints pw-cat, WirePlumber and node
diagnostics on failure.

The test microphone was a null-audio-sink with a Source media class.
WirePlumber's event dispatcher intermittently stalls on such a node and
then links nothing and ignores volume changes, which is what failed in
CI. It is now a loopback virtual source, like echo-cancel; three local
runs in a row pass. Screenshots are re-rendered from the new setup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:58:18 +00:00
SpriteandClaude Opus 5.5 b18ab7aed1 fix: run native model tests in the trixie CI job
Linking MoonBit's native runtime on the bullseye runner fails with
undefined pthread symbols (glibc 2.31 needs -lpthread), so the check
job now only runs the wasm-gc tests and the native model tests move to
the debian:trixie job that already builds natively.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:58:12 +00:00
SpriteandClaude Opus 5.5 5d74201d0c chore: Gitea Actions CI
CI / check (pull_request) Failing after 11s
CI / native (pull_request) Failing after 1m38s
Pure check and test job on the default runner; native build and
headless smoke test in a debian:trixie container (bullseye lacks
WirePlumber 0.5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:29:58 +00:00
SpriteandClaude Opus 5.5 6dd89a3559 chore: README with architecture, dependencies and build steps
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:29:58 +00:00
SpriteandClaude Opus 5.5 169fb542df chore: headless smoke test and screenshots
tools/smoke-test.sh starts a private PipeWire + WirePlumber with null
sinks/source and test streams, exercises every action through
moonmix-probe and renders the GUI offscreen under broadway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:28:51 +00:00
SpriteandClaude Opus 5.5 91d3bb68bb feature: GTK4 GUI with pavucontrol-style tabs
Hand-written minimal GTK4 binding (one dispatch callback, tag table,
signal suppression during programmatic updates) and the GUI: Playback,
Recording, Output Devices and Input Devices tabs with linked volume
sliders up to 150%, mute, default-device toggle and per-stream device
selector, updated live by diffing view rows. Includes a .desktop file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:28:51 +00:00
SpriteandClaude Opus 5.5 c55883b8ad feature: WirePlumber binding and headless probe
Thin C layer over libwireplumber-0.5: an object manager for audio
nodes, links and the default metadata, plus the mixer-api and
default-nodes-api plugins (what wpctl uses internally) for volume, mute
and defaults. Streams are moved by setting target.object in the default
metadata, as pipewire-pulse does. No CLI tools are spawned.

tools/pkg-cc wraps the C compiler to append pkg-config flags because
moon does not expand $(pkg-config ...) in moon.pkg link options.

moonmix-probe prints what each tab shows and can apply one action.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:28:50 +00:00
SpriteandClaude Opus 5.5 c7314f4188 chore: add sweet release configuration
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:05:41 +00:00
SpriteandClaude Opus 5.5 7b2b45067f feature: pure volume model, graph state reducer and view model
Cubic percent <-> linear channelVolumes conversions (pavucontrol scale,
up to 150%), dB formatting, balance-preserving linked slider, a reducer
applying WirePlumber node/link/default events and per-tab view rows,
all covered by moon tests that run on any target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 21:59:55 +00:00
34 changed files with 99 additions and 2107 deletions

No files matched your search

+1 -2
View File
@@ -47,8 +47,7 @@ jobs:
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 \
dbus-daemon python3-gi gir1.2-glib-2.0
adwaita-icon-theme fonts-dejavu-core
- name: Checkout
env:
+7 -87
View File
@@ -15,11 +15,7 @@ on top of libpipewire-0.3. It never runs `wpctl`, `pactl`, `pw-cli`,
| ![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).)* With an orange system accent colour:
| Playback | Output Devices |
| --- | --- |
| ![Playback tab, orange accent](docs/screenshots/accent-playback.png) | ![Output Devices tab, orange accent](docs/screenshots/accent-output-devices.png) |
[Testing](#testing).)*
## Features (v1)
@@ -28,21 +24,15 @@ on top of libpipewire-0.3. It never runs `wpctl`, `pactl`, `pw-cli`,
- **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.
- **Live peak meters** under each slider on Playback, Output Devices and
Input Devices, on the same cubic scale as the slider. Only the visible
tab is metered; meters on outputs and app streams are passive, so they
never keep an idle device running.
- 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.
- **Follows the desktop's accent colour and dark/light style**, live (see
[Appearance](#appearance)).
- 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, monitor sources in Input Devices, meters for recording streams.
sliders, peak meters, monitor sources in Input Devices.
## Architecture
@@ -72,13 +62,7 @@ flowchart LR
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. Peak meters are small capture `pw_stream`s on
WirePlumber's own `pw_core`, created with the properties pipewire-pulse
gives pavucontrol's peak streams (`stream.monitor`, `target.object`,
`stream.capture.sink` for sinks); their `process` callback only folds
samples into a peak value that a 40 ms GUI timer reads and resets. Nodes
with `stream.monitor` (ours and pavucontrol's) are hidden from the tabs.
The C layer sends MoonBit one callback per change,
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
@@ -94,34 +78,6 @@ flowchart LR
time after the user moves a slider, remote updates to that slider are
ignored so it doesn't jump while being dragged.
## Appearance
moonmix reads the desktop's **accent colour** and **colour scheme** from the
XDG Desktop Portal (`org.freedesktop.portal.Settings`, namespace
`org.freedesktop.appearance`: `accent-color` and `color-scheme`), which GNOME
47+, KDE Plasma 6 and others implement, over GDBus in `gtk/gtk_stub.c`, and
follows `SettingChanged`, so changing them in the system settings applies at
once. The selected tab, the volume sliders, the peak meters and the checked
*Default* button take the accent colour; a dark/light preference switches the
theme's variant (`gtk-application-prefer-dark-theme`, and
`gtk-interface-color-scheme` on GTK 4.20+).
The colours come from `model/accent.mbt` (unit-tested): text and icons on
accent backgrounds are white while that reaches a 3:1 WCAG contrast, else
whichever of white and black contrasts more (black on orange or yellow); the
accent used as a text colour is darkened or lightened until it reaches 4.5:1
on the window background. They are applied by a `GtkCssProvider` at
application priority that sets the accent named colours (`accent_bg_color`,
`accent_fg_color`, `accent_color`, `theme_selected_bg_color`, and the
`--accent-*` variables) for themes that use them, plus explicit rules, since
GTK's built-in Default theme hardcodes its blue.
Without a portal, or when no accent is set, the theme's own accent stays.
moonmix uses the portal directly rather than libadwaita (whose
`AdwStyleManager` does the same on 1.6+) to keep GTK's standard look and
avoid a dependency and a move to `AdwApplication`.
## Building
### Dependencies
@@ -151,41 +107,12 @@ 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
install -Dm644 data/icons/hicolor/scalable/apps/org.latha.moonmix.svg ~/.local/share/icons/hicolor/scalable/apps/org.latha.moonmix.svg
install -Dm644 data/icons/hicolor/symbolic/apps/org.latha.moonmix-symbolic.svg ~/.local/share/icons/hicolor/symbolic/apps/org.latha.moonmix-symbolic.svg
gtk-update-icon-cache -f -t ~/.local/share/icons/hicolor # optional
```
The app icon is `org.latha.moonmix` (a speaker with a volume slider), shipped
as scalable and symbolic SVGs under `data/icons/hicolor/`. The window uses it
as its icon and the program name is `org.latha.moonmix`, which matches the
`.desktop` file so Wayland shells show it too. Run from a checkout, moonmix
also searches `./data/icons` and `$MOONMIX_ICON_DIR`.
### Icons
Everything else uses the desktop's icon theme (Adwaita, Breeze, Papirus...
any theme with the standard freedesktop names; install `adwaita-icon-theme`
if icons are missing). The names are chosen in `model/icons.mbt` and tested
with `moon test`; the GTK layer only asks the theme `has_icon`:
- **Devices**: the device's own `device.icon-name` / `node.icon-name`, then
`device.form-factor` (headphone, headset, speaker, microphone, webcam,
handset, tv, hdmi...), HDMI/webcam/Bluetooth/USB hints, then the direction
(speakers or microphone), then `audio-card-symbolic` and
`audio-x-generic-symbolic`. Symbolic variants are tried first so they follow
the theme's foreground colour. `image-missing` is the very last resort.
- **Streams**: `application.icon-name` / `media.icon-name`, then the app's
launcher icon found in the installed `.desktop` files (by
`pipewire.access.portal.app_id`, `application.process.binary` or
`application.name`), then `application-x-executable-symbolic`.
- **Mute button**: `audio-volume-high/medium/low/muted-symbolic` following the
volume and mute state. Row icons are 32 px, button and tab icons 16 px.
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 gio-unix-2.0`. moon
`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.
@@ -201,7 +128,6 @@ $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>
$P meter <id> # peak over ~1.5 s; exit 6 if silent
```
## Testing
@@ -210,20 +136,14 @@ $P meter <id> # peak over ~1.5 s; exit 6 if silent
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
# (+ python3-gi, dbus-daemon for the accent shots)
```
`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, one playback stream of noise 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, checks that peak
meters on the stream and its sink see the signal,
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. If `python3`
with PyGObject and `dbus-daemon` are available, it then starts a private
session bus with a fake portal (`tools/fake-portal.py`) that reports a green
accent, switches it to orange while moonmix runs, and renders the tabs again
(`<prefix>-accent-<n>.png`) once the change has been applied.
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,
+1 -26
View File
@@ -9,8 +9,6 @@
// 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
// moonmix-probe meter <id> peak level of a sink/source/playback
// stream over ~1.5 s (exit 6 if silent)
///|
extern "C" fn c_exit(code : Int32) = "exit"
@@ -101,7 +99,6 @@ fn main {
let argv = @env.args()
let args = if argv.length() > 1 { argv[1:].to_owned() } else { [] }
let state = @model.State::new()
let meter_id : Ref[Int32] = { val: -1, }
@wp.on_event(fn(ev) {
for e in @wp.to_model_events(ev) {
let _ = state.apply(e)
@@ -111,20 +108,7 @@ fn main {
Ready => @wp.timeout(300, 2)
Timeout(2) => {
print_state(state)
if args is ["meter", id] {
let id = resolve(state, id)
let kind = match state.nodes.get(id) {
Some(n) => n.kind()
None => Other
}
meter_id.val = id
let ok = @wp.meter_start(id, kind)
println("== meter \{id}: \{if ok { "started" } else { "FAILED" }}")
if !ok {
c_exit(6)
}
@wp.timeout(1500, 3)
} else if args.length() > 0 {
if args.length() > 0 {
let ok = act(state, args)
println(
"== action \{args.join(" ")}: \{if ok { "ok" } else { "FAILED" }}",
@@ -134,15 +118,6 @@ fn main {
@wp.quit()
}
}
Timeout(3) => {
let peak = @wp.meter_take(meter_id.val).unwrap_or(0.0)
println("== meter \{meter_id.val}: peak \{peak}")
@wp.meter_stop(meter_id.val)
if peak <= 0.0 {
c_exit(6)
}
@wp.quit()
}
Timeout(1) => {
print_state(state)
@wp.quit()
+37 -240
View File
@@ -4,9 +4,6 @@
// @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.
//
// Peak meters run only for the visible tab: switching tabs starts capture
// streams for its rows and stops the others, and a 40 ms timer moves the bars.
///|
extern "C" fn c_exit(code : Int32) = "exit"
@@ -20,8 +17,6 @@ struct RowView {
subtitle : @gtk.Widget
scale : @gtk.Widget
volume_label : @gtk.Widget
meter : @gtk.Widget
mut shown_level : Double
mute : @gtk.Widget
default_btn : @gtk.Widget?
device : @gtk.Widget?
@@ -46,29 +41,23 @@ struct App {
status : @gtk.Widget
window : @gtk.Widget
notebook : @gtk.Widget
/// Index of the visible tab.
current : Ref[Int32]
/// Nodes with a running peak meter.
metered : Map[Int32, Bool]
/// Screenshot mode: hold the bars still so the window can be captured.
meters_paused : Ref[Bool]
}
///|
/// Device / application icon in each row; buttons use 16 px icons.
const ROW_ICON_SIZE : Int32 = 32
///|
const METER_INTERVAL_MS : Int32 = 40
///|
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; }
#|levelbar.mm-meter trough, levelbar.mm-meter block { min-height: 4px; }
#|levelbar.mm-meter { margin: 0 10px; }
///|
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 {
@@ -77,7 +66,7 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
let root = @gtk.vbox(4)
root.add_css_class("mm-row")
let header = @gtk.hbox(8)
let icon = @gtk.image(@gtk.resolve_icon(row.icons), ROW_ICON_SIZE)
let icon = @gtk.image(row.icon_name, 32)
let texts = @gtk.vbox(0)
texts.set_hexpand(true)
texts.set_valign_center()
@@ -117,35 +106,27 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
}
let default_btn = match tab {
OutputDevices | InputDevices => {
let (b, tag) = @gtk.toggle(
@gtk.resolve_icon(@model.default_button_icons()),
"Default",
fn(on) {
if on {
let _ = if tab is OutputDevices {
@wp.set_default_sink(id)
} else {
@wp.set_default_source(id)
}
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)
},
)
}
// 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")
// Shown in the accent colour when checked (see @model.accent_css).
b.add_css_class("mm-default")
header.append(b)
Some(b)
}
_ => None
}
let (mute, mute_tag) = @gtk.toggle(
@gtk.resolve_icon([row.volume_icon, "audio-volume-high"]),
"",
fn(on) { let _ = @wp.set_mute(id, on) },
)
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)
@@ -167,15 +148,7 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
}
})
tags.push(scale_tag)
// Peak meter under the slider, as wide as it.
let meter = @gtk.level_bar()
meter.add_css_class("mm-meter")
meter.set_visible(tab.has_meter())
let column = @gtk.vbox(2)
column.set_hexpand(true)
column.append(scale)
column.append(meter)
slider_row.append(column)
slider_row.append(scale)
slider_row.append(volume_label)
root.append(slider_row)
let view = {
@@ -185,8 +158,6 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
subtitle,
scale,
volume_label,
meter,
shown_level: 0.0,
mute,
default_btn,
device,
@@ -211,8 +182,8 @@ fn apply_row(view : RowView, row : @model.Row, force~ : Bool = false) -> Unit {
view.subtitle.set_text(row.subtitle)
view.subtitle.set_visible(row.subtitle != "")
}
if force || old.icons != row.icons {
view.icon.set_icon(@gtk.resolve_icon(row.icons))
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()) {
@@ -220,9 +191,7 @@ fn apply_row(view : RowView, row : @model.Row, force~ : Bool = false) -> Unit {
view.volume_label.set_text(row.volume_text)
}
view.mute.set_active(row.mute)
view.mute.set_button_icon(
@gtk.resolve_icon([row.volume_icon, "audio-volume-high"]),
)
view.mute.set_button_icon(mute_icon(row.mute))
match view.default_btn {
Some(b) => b.set_active(row.is_default)
None => ()
@@ -304,87 +273,6 @@ fn App::render(self : App) -> Unit {
for t in self.tabs {
self.render_tab(t)
}
self.sync_meters()
}
///|
fn @model.Tab::has_meter(self : @model.Tab) -> Bool {
// Like pavucontrol: a capture stream has no output of its own to meter.
!(self is Recording)
}
///|
/// Run peak meters for exactly the rows of the visible tab.
fn App::sync_meters(self : App) -> Unit {
let want : Map[Int32, @model.NodeKind] = Map([])
match self.tabs.get(self.current.val) {
Some(t) =>
if t.tab.has_meter() {
for row in t.rows {
want.set(row.id, t.tab.node_kind())
}
}
None => ()
}
let stale = []
for id, _ in self.metered {
if !want.contains(id) {
stale.push(id)
}
}
for id in stale {
@wp.meter_stop(id)
self.metered.remove(id)
for t in self.tabs {
match t.views.get(id) {
Some(v) => {
v.shown_level = 0.0
v.meter.set_level(0.0)
}
None => ()
}
}
}
for id, kind in want {
if !self.metered.contains(id) && @wp.meter_start(id, kind) {
self.metered.set(id, true)
}
}
}
///|
/// Move the bars of the visible tab to the latest peaks.
fn App::tick_meters(self : App) -> Unit {
if self.meters_paused.val {
return
}
match self.tabs.get(self.current.val) {
Some(t) =>
for id, v in t.views {
match @wp.meter_take(id) {
Some(peak) => {
let next = @model.meter_step(
v.shown_level,
@model.meter_level(peak),
)
if next != v.shown_level {
v.shown_level = next
v.meter.set_level(next)
}
}
None => ()
}
}
None => ()
}
}
///|
fn App::start_meter_timer(self : App) -> Unit {
@gtk.timeout(METER_INTERVAL_MS, fn() {
self.tick_meters()
self.start_meter_timer()
})
}
///|
@@ -407,11 +295,7 @@ fn App::on_wp_event(self : App, ev : @wp.Event) -> Unit {
}
match ev {
Ready => self.set_status("Connected to PipeWire via WirePlumber")
Disconnected => {
// The streams died with the connection.
self.metered.clear()
self.set_status("Disconnected from PipeWire")
}
Disconnected => self.set_status("Disconnected from PipeWire")
PluginError =>
self.set_status(
"Could not load WirePlumber's mixer-api / default-nodes-api modules",
@@ -428,12 +312,7 @@ fn build_ui() -> App {
@gtk.load_css(CSS)
let window = @gtk.window("Volume Control (moonmix)", 640, 480)
let outer = @gtk.vbox(0)
let current : Ref[Int32] = { val: 0, }
let on_switch : Ref[(Int32) -> Unit] = { val: fn(_) { }, }
let nb = @gtk.notebook(on_switch=fn(i) {
current.val = i
(on_switch.val)(i)
})
let nb = @gtk.notebook()
let tabs = []
for tab in @model.Tab::all() {
let list = @gtk.vbox(0)
@@ -441,15 +320,7 @@ fn build_ui() -> App {
empty.set_margins(24)
empty.add_css_class("dim-label")
list.append(empty)
nb.append_page(
@gtk.scrolled(list),
tab.label(),
icon=@gtk.resolve_icon([
tab.icon(),
"audio-card-symbolic",
"audio-x-generic",
]),
)
nb.append_page(@gtk.scrolled(list), tab.label())
tabs.push({ tab, list, empty, views: Map([]), rows: [], })
}
outer.append(nb)
@@ -458,66 +329,13 @@ fn build_ui() -> App {
status.add_css_class("mm-status")
outer.append(status)
window.set_child(outer)
let app = {
state: @model.State::new(),
tabs,
status,
window,
notebook: nb,
current,
metered: Map([]),
meters_paused: { val: false, },
}
on_switch.val = fn(_) { app.sync_meters() }
app
}
///|
/// Follow the desktop's accent colour and dark/light preference (XDG Desktop
/// Portal). Without a portal, or with no accent set, the theme's own accent
/// stays.
///|
/// The accent applied last ("#rrggbb", or "" for the theme's own).
let applied_accent : Ref[String] = { val: "", }
///|
fn follow_appearance(log~ : Bool = false) -> Unit {
let _ = @gtk.watch_appearance(fn(a) {
let scheme = @model.ColorScheme::from_portal(a.color_scheme)
@gtk.set_color_scheme(a.color_scheme)
let dark = match scheme {
Dark => true
Light => false
NoPreference => @gtk.prefers_dark()
}
let (r, g, b) = a.accent
let accent = @model.Rgb::from_portal(r, g, b)
match accent {
Some(c) => @gtk.set_accent_css(@model.accent_css(c, dark))
None => @gtk.set_accent_css("")
}
applied_accent.val = match accent {
Some(c) => c.to_hex()
None => ""
}
if log {
// The smoke test checks these lines to see live updates arrive.
let name = match accent {
Some(c) => c.to_hex()
None => "theme default"
}
println("moonmix: accent \{name}, \{if dark { "dark" } else { "light" }}")
}
})
{ 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). With
/// MOONMIX_SCREENSHOT_ACCENT=#rrggbb it first waits (up to 20 s) until the
/// portal has delivered that accent colour.
/// 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
@@ -530,11 +348,7 @@ fn screenshot_mode(app : App, prefix : String) -> Unit {
if attempt == 0 {
app.select_tab(i)
}
// Let the meters run, then hold them still: a window that redraws every
// tick never has a finished frame to capture under broadway.
app.meters_paused.val = false
@gtk.timeout(400, fn() { app.meters_paused.val = true })
@gtk.timeout(600, fn() {
@gtk.timeout(400, fn() {
let path = "\{prefix}-\{i}.png"
if app.window.save_png(path) {
println("moonmix: wrote \{path}")
@@ -548,19 +362,7 @@ fn screenshot_mode(app : App, prefix : String) -> Unit {
})
}
let want = env_var("MOONMIX_SCREENSHOT_ACCENT").unwrap_or("")
fn start(waited : Int32) -> Unit {
if want == "" || applied_accent.val == want || waited >= 200 {
if waited >= 200 {
println("moonmix: accent \{want} never arrived")
}
shoot(0, 0)
} else {
@gtk.timeout(100, fn() { start(waited + 1) })
}
}
@gtk.timeout(1500, fn() { start(0) })
@gtk.timeout(1500, fn() { shoot(0, 0) })
}
///|
@@ -574,20 +376,15 @@ fn main {
println("moonmix: cannot open a display (is WAYLAND_DISPLAY/DISPLAY set?)")
c_exit(1)
}
let screenshot = match env_var("MOONMIX_SCREENSHOT") {
Some(prefix) if prefix != "" => Some(prefix)
_ => None
}
follow_appearance(log=screenshot is Some(_))
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()
app.start_meter_timer()
if screenshot is Some(prefix) {
screenshot_mode(app, prefix)
match env_var("MOONMIX_SCREENSHOT") {
Some(prefix) if prefix != "" => screenshot_mode(app, prefix)
_ => ()
}
@gtk.run()
}
@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#4b5fc8"/>
<stop offset="1" stop-color="#2a2f6b"/>
</linearGradient>
</defs>
<rect x="8" y="8" width="112" height="112" rx="26" fill="url(#bg)"/>
<!-- speaker -->
<path d="M26 54h16l20-16v52L42 74H26z" fill="#ffffff"/>
<path d="M74 52c5 6 5 18 0 24" fill="none" stroke="#ffffff" stroke-width="6" stroke-linecap="round"/>
<path d="M84 42c10 13 10 31 0 44" fill="none" stroke="#ffffff" stroke-width="6" stroke-linecap="round" opacity=".7"/>
<!-- slider -->
<rect x="26" y="98" width="76" height="8" rx="4" fill="#ffffff" opacity=".3"/>
<rect x="26" y="98" width="50" height="8" rx="4" fill="#f5c542"/>
<circle cx="76" cy="102" r="9" fill="#f5c542" stroke="#ffffff" stroke-width="3"/>
</svg>

Before

Width:  |  Height:  |  Size: 947 B

@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<path d="M1 5h2.5L7 2v8L3.5 7H1z" fill="#bebebe"/>
<path d="M9 4.5c1.2 1.6 1.2 2.4 0 4" fill="none" stroke="#bebebe" stroke-width="1.2" stroke-linecap="round"/>
<path d="M11 3c2 2.6 2 5.4 0 8" fill="none" stroke="#bebebe" stroke-width="1.2" stroke-linecap="round"/>
<rect x="1" y="12.2" width="14" height="1.6" rx=".8" fill="#bebebe" opacity=".5"/>
<rect x="1" y="12.2" width="9" height="1.6" rx=".8" fill="#bebebe"/>
<circle cx="10" cy="13" r="1.8" fill="#bebebe"/>
</svg>

Before

Width:  |  Height:  |  Size: 609 B

+1 -2
View File
@@ -5,9 +5,8 @@ Name=moonmix
GenericName=Volume Control
Comment=Adjust volumes of PipeWire devices and applications
Exec=moonmix
Icon=org.latha.moonmix
Icon=multimedia-volume-control
Terminal=false
Categories=AudioVideo;Audio;Mixer;GTK;Settings;HardwareSettings;
Keywords=pipewire;wireplumber;volume;mixer;sound;audio;pavucontrol;
StartupNotify=true
StartupWMClass=org.latha.moonmix
Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

+3 -130
View File
@@ -77,13 +77,8 @@ 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, icon)
extern "C" fn ffi_notebook_append(
nb : Widget,
child : Widget,
label : Bytes,
icon : Bytes,
) = "mm_gtk_notebook_append"
#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"
@@ -110,14 +105,6 @@ extern "C" fn ffi_image_new(icon : Bytes, size : Int32) -> Widget = "mm_gtk_imag
#borrow(icon)
extern "C" fn ffi_image_set_icon(img : Widget, icon : Bytes) = "mm_gtk_image_set_icon"
///|
#borrow(name)
extern "C" fn ffi_has_icon(name : Bytes) -> Int32 = "mm_gtk_has_icon"
///|
#borrow(key)
extern "C" fn ffi_app_icon(key : Bytes) -> Bytes = "mm_gtk_app_icon"
///|
extern "C" fn ffi_scale_new(max : Double, norm : Double, tag : Int32) -> Widget = "mm_gtk_scale_new"
@@ -149,12 +136,6 @@ 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"
///|
extern "C" fn ffi_levelbar_new() -> Widget = "mm_gtk_levelbar_new"
///|
extern "C" fn ffi_levelbar_set(lb : Widget, v : Double) = "mm_gtk_levelbar_set"
///|
#borrow(text)
extern "C" fn ffi_set_tooltip(w : Widget, text : Bytes) = "mm_gtk_widget_set_tooltip"
@@ -286,68 +267,6 @@ pub fn load_css(css : String) -> Unit {
ffi_load_css(cstr(css))
}
///|
extern "C" fn ffi_portal_watch(tag : Int32) -> Int32 = "mm_gtk_portal_watch"
///|
extern "C" fn ffi_portal_accent(i : Int32) -> Double = "mm_gtk_portal_accent"
///|
extern "C" fn ffi_portal_color_scheme() -> Int32 = "mm_gtk_portal_color_scheme"
///|
#borrow(css)
extern "C" fn ffi_set_accent_css(css : Bytes) = "mm_gtk_set_accent_css"
///|
extern "C" fn ffi_prefers_dark() -> Int32 = "mm_gtk_prefers_dark"
///|
extern "C" fn ffi_set_color_scheme(scheme : Int32) = "mm_gtk_set_color_scheme"
///|
/// The desktop's appearance settings, from the XDG Desktop Portal.
pub(all) struct Appearance {
/// accent-color as reported (each channel -1 when unset).
accent : (Double, Double, Double)
/// color-scheme: 0 no preference, 1 dark, 2 light.
color_scheme : Int32
}
///|
/// Follow org.freedesktop.appearance (accent-color, color-scheme) through
/// the portal's Settings interface: `f` runs once with the current values
/// and again on every change. Never runs without a portal. False without a
/// session bus.
pub fn watch_appearance(f : (Appearance) -> Unit) -> Bool {
let tag = register(fn(_) {
f({
accent: (ffi_portal_accent(0), ffi_portal_accent(1), ffi_portal_accent(2)),
color_scheme: ffi_portal_color_scheme(),
})
})
ffi_portal_watch(tag) != 0
}
///|
/// Replace the accent stylesheet (APPLICATION priority); "" removes it.
pub fn set_accent_css(css : String) -> Unit {
ffi_set_accent_css(cstr(css))
}
///|
/// Apply a color-scheme preference (0 none: back to the configured theme
/// variant, 1 dark, 2 light).
pub fn set_color_scheme(scheme : Int32) -> Unit {
ffi_set_color_scheme(scheme)
}
///|
/// Whether the theme is in its dark variant.
pub fn prefers_dark() -> Bool {
ffi_prefers_dark() != 0
}
///|
pub fn window(
title : String,
@@ -420,9 +339,8 @@ pub fn Widget::append_page(
self : Widget,
child : Widget,
label : String,
icon~ : String = "",
) -> Unit {
ffi_notebook_append(self, child, cstr(label), cstr(icon))
ffi_notebook_append(self, child, cstr(label))
}
///|
@@ -518,17 +436,6 @@ pub fn Widget::set_items(
ffi_dropdown_set(self, cstr(clean.join("\n")), selected)
}
///|
/// A 0..1 level bar (peak meter).
pub fn level_bar() -> Widget {
ffi_levelbar_new()
}
///|
pub fn Widget::set_level(self : Widget, v : Double) -> Unit {
ffi_levelbar_set(self, v)
}
///|
pub fn Widget::set_tooltip(self : Widget, text : String) -> Unit {
ffi_set_tooltip(self, cstr(text))
@@ -569,37 +476,3 @@ pub fn Widget::set_valign_center(self : Widget) -> Unit {
pub fn Widget::save_png(self : Widget, path : String) -> Bool {
ffi_save_png(self, cstr(path)) != 0
}
///|
/// Does the current icon theme have this icon?
pub fn has_icon(name : String) -> Bool {
ffi_has_icon(cstr(name)) != 0
}
///|
/// Icon of the installed application matching `key` (desktop id, binary or
/// name) per its .desktop file, "" if there is none or the theme lacks it.
pub fn app_icon(key : String) -> String {
@utf8.decode_lossy(ffi_app_icon(cstr(key)))
}
///|
/// First entry of an icon chain (see @model.device_icon_chain) that the theme
/// has. "app:<key>" entries are looked up in the .desktop files. The last
/// entry is returned if nothing matches, so the result is never empty.
pub fn resolve_icon(chain : Array[String]) -> String {
for name in chain {
if name.has_prefix("app:") {
let icon = app_icon(name[4:].to_owned())
if icon != "" {
return icon
}
} else if has_icon(name) {
return name
}
}
match chain.last() {
Some(n) => n
None => "image-missing"
}
}
+7 -311
View File
@@ -7,10 +7,8 @@
* widgets programmatically (mm_gtk_set_*), callbacks are suppressed so model
* updates never echo back into PipeWire.
*/
#include <stdio.h>
#include <string.h>
#include <gtk/gtk.h>
#include <gio/gdesktopappinfo.h>
#include "moonbit.h"
typedef void (*mm_gcall_t)(void *closure, int32_t tag, double value);
@@ -43,84 +41,7 @@ MOONBIT_FFI_EXPORT void mm_gtk_set_handler(mm_gcall_t call, void *closure) {
g_closure = closure;
}
MOONBIT_FFI_EXPORT int32_t mm_gtk_init(void) {
/* The Wayland app id comes from the program name; match the .desktop file
* so the compositor shows the app icon. */
g_set_prgname("org.latha.moonmix");
if (!gtk_init_check())
return 0;
/* Let an uninstalled checkout find data/icons/hicolor/... too:
* $MOONMIX_ICON_DIR, then ./data/icons. */
GtkIconTheme *theme = gtk_icon_theme_get_for_display(gdk_display_get_default());
const char *dir = g_getenv("MOONMIX_ICON_DIR");
if (dir && *dir)
gtk_icon_theme_add_search_path(theme, dir);
gtk_icon_theme_add_search_path(theme, "data/icons");
gtk_window_set_default_icon_name("org.latha.moonmix");
return 1;
}
/* 1 if the icon theme has `name`. */
MOONBIT_FFI_EXPORT int32_t mm_gtk_has_icon(moonbit_bytes_t name) {
GdkDisplay *d = gdk_display_get_default();
if (!d)
return 0;
return gtk_icon_theme_has_icon(gtk_icon_theme_get_for_display(d), s(name));
}
static int theme_icon_of(GAppInfo *info, GtkIconTheme *theme, char **out) {
GIcon *icon = g_app_info_get_icon(info);
if (icon && G_IS_THEMED_ICON(icon)) {
const char *const *names = g_themed_icon_get_names(G_THEMED_ICON(icon));
for (int i = 0; names && names[i]; i++)
if (gtk_icon_theme_has_icon(theme, names[i])) {
*out = g_strdup(names[i]);
return 1;
}
}
return 0;
}
/* Look an application up in the installed .desktop files by desktop id
* ("org.mozilla.firefox"), executable basename ("firefox") or display name
* ("Firefox"), and return its icon name if the theme has it. "" if none. */
MOONBIT_FFI_EXPORT moonbit_bytes_t mm_gtk_app_icon(moonbit_bytes_t key) {
const char *k = s(key);
char *found = NULL;
GdkDisplay *d = gdk_display_get_default();
if (d && *k) {
GtkIconTheme *theme = gtk_icon_theme_get_for_display(d);
char *id = g_strconcat(k, ".desktop", NULL);
GDesktopAppInfo *di = g_desktop_app_info_new(id);
g_free(id);
if (di) {
theme_icon_of(G_APP_INFO(di), theme, &found);
g_object_unref(di);
}
if (!found) {
GList *all = g_app_info_get_all();
for (GList *l = all; l && !found; l = l->next) {
GAppInfo *info = l->data;
if (!g_app_info_should_show(info))
continue;
const char *exe = g_app_info_get_executable(info);
char *base = exe ? g_path_get_basename(exe) : NULL;
const char *nm = g_app_info_get_name(info);
if ((base && g_ascii_strcasecmp(base, k) == 0) ||
(nm && g_ascii_strcasecmp(nm, k) == 0))
theme_icon_of(info, theme, &found);
g_free(base);
}
g_list_free_full(all, g_object_unref);
}
}
size_t n = found ? strlen(found) : 0;
moonbit_bytes_t out = moonbit_make_bytes(n + 1, 0);
if (found)
memcpy(out, found, n);
g_free(found);
return out;
}
MOONBIT_FFI_EXPORT int32_t mm_gtk_init(void) { return gtk_init_check(); }
MOONBIT_FFI_EXPORT void mm_gtk_run(void) {
if (!g_loop)
@@ -165,196 +86,6 @@ MOONBIT_FFI_EXPORT void mm_gtk_load_css(moonbit_bytes_t css) {
g_object_unref(p);
}
/* ---- desktop appearance (XDG Desktop Portal Settings) -------------------
*
* Reads org.freedesktop.appearance accent-color ((ddd), sRGB 0..1; outside
* that range means unset) and color-scheme (u: 0 none, 1 dark, 2 light) from
* org.freedesktop.portal.Settings on the session bus, and follows
* SettingChanged. Every change is reported to MoonBit as emit(tag, 0); it
* then reads the values with mm_gtk_portal_accent / _color_scheme. Without
* a session bus or portal nothing is ever reported: the theme stays as is. */
#define PORTAL_NAME "org.freedesktop.portal.Desktop"
#define PORTAL_PATH "/org/freedesktop/portal/desktop"
#define PORTAL_IFACE "org.freedesktop.portal.Settings"
#define APPEARANCE_NS "org.freedesktop.appearance"
static GDBusConnection *g_portal_bus;
static int32_t g_portal_tag;
static double g_accent[3] = {-1, -1, -1};
static int32_t g_color_scheme;
static GtkCssProvider *g_accent_provider;
/* Store one appearance setting; 1 if it is one we track. */
static int portal_store(const char *key, GVariant *value) {
GVariant *v = g_variant_ref(value);
while (g_variant_is_of_type(v, G_VARIANT_TYPE_VARIANT)) {
GVariant *inner = g_variant_get_variant(v);
g_variant_unref(v);
v = inner;
}
int known = 1;
if (strcmp(key, "accent-color") == 0 &&
g_variant_is_of_type(v, G_VARIANT_TYPE("(ddd)")))
g_variant_get(v, "(ddd)", &g_accent[0], &g_accent[1], &g_accent[2]);
else if (strcmp(key, "color-scheme") == 0 &&
g_variant_is_of_type(v, G_VARIANT_TYPE_UINT32))
g_color_scheme = (int32_t)g_variant_get_uint32(v);
else
known = 0;
g_variant_unref(v);
return known;
}
static void on_portal_setting_changed(GDBusConnection *c, const char *sender,
const char *path, const char *iface,
const char *signal, GVariant *params,
gpointer d) {
(void)c; (void)sender; (void)path; (void)iface; (void)signal; (void)d;
const char *ns, *key;
GVariant *value;
if (!g_variant_is_of_type(params, G_VARIANT_TYPE("(ssv)")))
return;
g_variant_get(params, "(&s&sv)", &ns, &key, &value);
int known = strcmp(ns, APPEARANCE_NS) == 0 && portal_store(key, value);
g_variant_unref(value);
if (known)
emit(g_portal_tag, 0);
}
static void on_portal_read_all(GObject *src, GAsyncResult *res, gpointer d) {
(void)d;
GError *err = NULL;
GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src), res, &err);
if (!ret) {
/* No portal (or no Settings interface): keep the theme's accent. */
g_debug("moonmix: no desktop portal settings: %s", err->message);
g_error_free(err);
return;
}
GVariantIter *namespaces;
const char *ns;
GVariant *entries;
g_variant_get(ret, "(a{sa{sv}})", &namespaces);
while (g_variant_iter_next(namespaces, "{&s@a{sv}}", &ns, &entries)) {
if (strcmp(ns, APPEARANCE_NS) == 0) {
GVariantIter it;
const char *key;
GVariant *value;
g_variant_iter_init(&it, entries);
while (g_variant_iter_next(&it, "{&sv}", &key, &value)) {
portal_store(key, value);
g_variant_unref(value);
}
}
g_variant_unref(entries);
}
g_variant_iter_free(namespaces);
g_variant_unref(ret);
emit(g_portal_tag, 0);
}
/* Start following the portal's appearance settings. 0 without a session
* bus. */
MOONBIT_FFI_EXPORT int32_t mm_gtk_portal_watch(int32_t tag) {
g_portal_tag = tag;
if (g_portal_bus)
return 1;
GError *err = NULL;
g_portal_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &err);
if (!g_portal_bus) {
g_debug("moonmix: no session bus: %s", err->message);
g_error_free(err);
return 0;
}
/* Subscribe first so no change between the read and the subscription is
* lost. */
g_dbus_connection_signal_subscribe(
g_portal_bus, PORTAL_NAME, PORTAL_IFACE, "SettingChanged", PORTAL_PATH,
APPEARANCE_NS, G_DBUS_SIGNAL_FLAGS_NONE, on_portal_setting_changed, NULL,
NULL);
const char *namespaces[] = {APPEARANCE_NS, NULL};
g_dbus_connection_call(
g_portal_bus, PORTAL_NAME, PORTAL_PATH, PORTAL_IFACE, "ReadAll",
g_variant_new("(^as)", namespaces), G_VARIANT_TYPE("(a{sa{sv}})"),
G_DBUS_CALL_FLAGS_NONE, 5000, NULL, on_portal_read_all, NULL);
return 1;
}
/* Channel i (0 r, 1 g, 2 b) of the portal accent colour; -1 when unset. */
MOONBIT_FFI_EXPORT double mm_gtk_portal_accent(int32_t i) {
return i >= 0 && i < 3 ? g_accent[i] : -1;
}
MOONBIT_FFI_EXPORT int32_t mm_gtk_portal_color_scheme(void) {
return g_color_scheme;
}
/* Replace the accent stylesheet ("" removes it, restoring the theme's). */
MOONBIT_FFI_EXPORT void mm_gtk_set_accent_css(moonbit_bytes_t css) {
GdkDisplay *d = gdk_display_get_default();
if (!d)
return;
if (!*s(css)) {
if (g_accent_provider) {
gtk_style_context_remove_provider_for_display(
d, GTK_STYLE_PROVIDER(g_accent_provider));
g_clear_object(&g_accent_provider);
}
return;
}
if (!g_accent_provider) {
g_accent_provider = gtk_css_provider_new();
gtk_style_context_add_provider_for_display(
d, GTK_STYLE_PROVIDER(g_accent_provider),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
}
gtk_css_provider_load_from_string(g_accent_provider, s(css));
}
/* 1 if the theme is in its dark variant now. */
MOONBIT_FFI_EXPORT int32_t mm_gtk_prefers_dark(void) {
GtkSettings *st = gtk_settings_get_default();
gboolean dark = FALSE;
if (st)
g_object_get(st, "gtk-application-prefer-dark-theme", &dark, NULL);
return dark;
}
/* Apply the color-scheme preference: 1 dark, 2 light, else whatever was set
* before moonmix first touched it (settings.ini, GTK_THEME...). */
MOONBIT_FFI_EXPORT void mm_gtk_set_color_scheme(int32_t scheme) {
static int saved = -1;
#if GTK_CHECK_VERSION(4, 20, 0)
static int saved_scheme = -1;
#endif
GtkSettings *st = gtk_settings_get_default();
if (!st)
return;
if (saved < 0) {
gboolean dark = FALSE;
g_object_get(st, "gtk-application-prefer-dark-theme", &dark, NULL);
saved = dark;
}
gboolean dark = scheme == 1 ? TRUE : scheme == 2 ? FALSE : saved;
g_object_set(st, "gtk-application-prefer-dark-theme", dark, NULL);
#if GTK_CHECK_VERSION(4, 20, 0)
/* Also drives CSS prefers-color-scheme on GTK 4.20+. */
if (g_object_class_find_property(G_OBJECT_GET_CLASS(st),
"gtk-interface-color-scheme")) {
int cur;
g_object_get(st, "gtk-interface-color-scheme", &cur, NULL);
if (saved_scheme < 0)
saved_scheme = cur;
int want = scheme == 1 ? GTK_INTERFACE_COLOR_SCHEME_DARK
: scheme == 2 ? GTK_INTERFACE_COLOR_SCHEME_LIGHT
: saved_scheme;
if (want != cur)
g_object_set(st, "gtk-interface-color-scheme", want, NULL);
}
#endif
}
/* ---- window ------------------------------------------------------------- */
static gboolean on_close(GtkWindow *w, gpointer d) {
@@ -370,7 +101,7 @@ MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_window_new(moonbit_bytes_t title,
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), "org.latha.moonmix");
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;
@@ -436,16 +167,8 @@ MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_notebook_new(int32_t tag) {
}
MOONBIT_FFI_EXPORT void mm_gtk_notebook_append(GtkWidget *nb, GtkWidget *child,
moonbit_bytes_t label,
moonbit_bytes_t icon) {
GtkWidget *tab = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
if (s(icon)[0]) {
GtkWidget *img = gtk_image_new_from_icon_name(s(icon));
gtk_image_set_pixel_size(GTK_IMAGE(img), 16);
gtk_box_append(GTK_BOX(tab), img);
}
gtk_box_append(GTK_BOX(tab), gtk_label_new(s(label)));
gtk_notebook_append_page(GTK_NOTEBOOK(nb), child, tab);
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) {
@@ -529,10 +252,7 @@ MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_toggle_new(moonbit_bytes_t icon,
GtkWidget *b = gtk_toggle_button_new();
if (s(icon)[0] && s(label)[0]) {
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
GtkWidget *img = gtk_image_new_from_icon_name(s(icon));
gtk_image_set_pixel_size(GTK_IMAGE(img), 16);
g_object_set_data(G_OBJECT(b), "mm-img", img);
gtk_box_append(GTK_BOX(box), img);
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]) {
@@ -554,11 +274,7 @@ MOONBIT_FFI_EXPORT void mm_gtk_toggle_set(GtkWidget *b, int32_t active) {
MOONBIT_FFI_EXPORT void mm_gtk_button_set_icon(GtkWidget *b,
moonbit_bytes_t icon) {
GtkWidget *img = g_object_get_data(G_OBJECT(b), "mm-img");
if (img)
gtk_image_set_from_icon_name(GTK_IMAGE(img), s(icon));
else
gtk_button_set_icon_name(GTK_BUTTON(b), s(icon));
gtk_button_set_icon_name(GTK_BUTTON(b), s(icon));
}
static void on_selected(GObject *dd, GParamSpec *p, gpointer d) {
@@ -598,22 +314,6 @@ MOONBIT_FFI_EXPORT void mm_gtk_dropdown_set(GtkWidget *dd,
g_suppress--;
}
/* Thin 0..1 level bar for peak meters, without GTK's low/high/full colour
* offsets (a quiet signal is not a warning). */
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_levelbar_new(void) {
GtkWidget *lb = gtk_level_bar_new_for_interval(0.0, 1.0);
GtkLevelBar *l = GTK_LEVEL_BAR(lb);
gtk_level_bar_remove_offset_value(l, GTK_LEVEL_BAR_OFFSET_LOW);
gtk_level_bar_remove_offset_value(l, GTK_LEVEL_BAR_OFFSET_HIGH);
gtk_level_bar_remove_offset_value(l, GTK_LEVEL_BAR_OFFSET_FULL);
gtk_widget_set_hexpand(lb, TRUE);
return lb;
}
MOONBIT_FFI_EXPORT void mm_gtk_levelbar_set(GtkWidget *lb, double v) {
gtk_level_bar_set_value(GTK_LEVEL_BAR(lb), v);
}
/* ---- generic widget properties ------------------------------------------ */
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_tooltip(GtkWidget *w,
@@ -656,10 +356,8 @@ MOONBIT_FFI_EXPORT void mm_gtk_widget_set_valign_center(GtkWidget *w) {
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) {
fprintf(stderr, "moonmix: save_png: not realized (%dx%d)\n", width, height);
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);
@@ -670,8 +368,6 @@ MOONBIT_FFI_EXPORT int32_t mm_gtk_save_png(GtkWidget *w, moonbit_bytes_t path) {
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));
if (!ok)
fprintf(stderr, "moonmix: save_png: writing %s failed\n", s(path));
g_object_unref(tex);
gsk_render_node_unref(node);
}
+1 -23
View File
@@ -2,12 +2,8 @@
package "geordi/moonmix/gtk"
// Values
pub fn app_icon(String) -> String
pub fn dropdown((Int32) -> Unit) -> (Widget, Int32)
pub fn has_icon(String) -> Bool
pub fn hbox(Int32) -> Widget
pub fn image(String, Int32) -> Widget
@@ -16,20 +12,14 @@ pub fn init_gtk() -> Bool
pub fn label(String) -> Widget
pub fn level_bar() -> Widget
pub fn load_css(String) -> Unit
pub fn notebook(on_switch? : (Int32) -> Unit) -> Widget
pub fn now_us() -> Int64
pub fn prefers_dark() -> Bool
pub fn quit() -> Unit
pub fn resolve_icon(Array[String]) -> String
pub fn run() -> Unit
pub fn scale(Double, Double, (Double) -> Unit) -> (Widget, Int32)
@@ -38,10 +28,6 @@ pub fn scrolled(Widget) -> Widget
pub fn separator() -> Widget
pub fn set_accent_css(String) -> Unit
pub fn set_color_scheme(Int32) -> Unit
pub fn timeout(Int32, () -> Unit) -> Unit
pub fn toggle(String, String, (Bool) -> Unit) -> (Widget, Int32)
@@ -52,23 +38,16 @@ pub fn updating(() -> Unit) -> Unit
pub fn vbox(Int32) -> Widget
pub fn watch_appearance((Appearance) -> Unit) -> Bool
pub fn window(String, Int32, Int32, on_close? : () -> Unit) -> Widget
// Errors
// Types and methods
pub(all) struct Appearance {
accent : (Double, Double, Double)
color_scheme : Int32
}
#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, icon? : String) -> 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
@@ -79,7 +58,6 @@ 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_level(Self, Double) -> 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
-257
View File
@@ -1,257 +0,0 @@
// System accent colour: conversion of the XDG Desktop Portal value
// (org.freedesktop.appearance accent-color, an (ddd) sRGB tuple in 0..1),
// WCAG contrast checks, and the CSS that recolours moonmix with it.
///|
/// An sRGB colour, each channel 0..1.
#derive(Eq, Debug)
pub(all) struct Rgb {
r : Double
g : Double
b : Double
}
///|
pub let white : Rgb = { r: 1.0, g: 1.0, b: 1.0, }
///|
pub let black : Rgb = { r: 0.0, g: 0.0, b: 0.0, }
///|
/// The portal's accent colour, or None when it is unset. The spec says a
/// value outside 0..1 means "no accent colour" (GNOME sends that before the
/// user picks one); NaN counts as unset too.
pub fn Rgb::from_portal(r : Double, g : Double, b : Double) -> Rgb? {
fn ok(x : Double) -> Bool {
x >= 0.0 && x <= 1.0 // false for NaN
}
if ok(r) && ok(g) && ok(b) {
Some({ r, g, b, })
} else {
None
}
}
///|
fn byte(x : Double) -> Int32 {
let v = (x * 255.0 + 0.5).to_int()
if v < 0 {
0
} else if v > 255 {
255
} else {
v
}
}
///|
/// Parse "#rrggbb" or "#rgb" (case-insensitive).
pub fn Rgb::parse_hex(s : String) -> Rgb? {
fn nib(c : Char) -> Int32? {
match c {
'0'..<='9' => Some(c.to_int() - '0'.to_int())
'a'..<='f' => Some(c.to_int() - 'a'.to_int() + 10)
'A'..<='F' => Some(c.to_int() - 'A'.to_int() + 10)
_ => None
}
}
let cs = s.to_array()
if cs.length() == 0 || cs[0] != '#' {
return None
}
let ds = []
for c in cs[1:] {
match nib(c) {
Some(d) => ds.push(d)
None => return None
}
}
let (r, g, b) = match ds.length() {
6 => (ds[0] * 16 + ds[1], ds[2] * 16 + ds[3], ds[4] * 16 + ds[5])
3 => (ds[0] * 17, ds[1] * 17, ds[2] * 17)
_ => return None
}
Some({
r: r.to_double() / 255.0,
g: g.to_double() / 255.0,
b: b.to_double() / 255.0,
})
}
///|
/// "#rrggbb", for CSS.
pub fn Rgb::to_hex(self : Rgb) -> String {
let digits = "0123456789abcdef".to_array()
let out = StringBuilder()
out.write_char('#')
for x in [self.r, self.g, self.b] {
let v = byte(x)
out.write_char(digits[v / 16])
out.write_char(digits[v % 16])
}
out.to_string()
}
///|
/// Linear interpolation: t = 0 is self, t = 1 is other.
pub fn Rgb::mix(self : Rgb, other : Rgb, t : Double) -> Rgb {
{
r: self.r + (other.r - self.r) * t,
g: self.g + (other.g - self.g) * t,
b: self.b + (other.b - self.b) * t,
}
}
///|
/// WCAG 2 relative luminance (of the colour as it will be shown, i.e.
/// rounded to 8 bits).
pub fn Rgb::luminance(self : Rgb) -> Double {
fn lin(x : Double) -> Double {
let c = byte(x).to_double() / 255.0
if c <= 0.04045 {
c / 12.92
} else {
@math.pow((c + 0.055) / 1.055, 2.4)
}
}
0.2126 * lin(self.r) + 0.7152 * lin(self.g) + 0.0722 * lin(self.b)
}
///|
/// WCAG 2 contrast ratio, 1..21.
pub fn contrast_ratio(a : Rgb, b : Rgb) -> Double {
let la = a.luminance()
let lb = b.luminance()
let (hi, lo) = if la > lb { (la, lb) } else { (lb, la) }
(hi + 0.05) / (lo + 0.05)
}
///|
/// WCAG AA contrast for normal text.
pub const MIN_TEXT_CONTRAST : Double = 4.5
///|
/// WCAG AA contrast for bold/large text and UI components (the checked
/// "default" button's icon, selected rows' text).
pub const MIN_UI_CONTRAST : Double = 3.0
///|
/// Foreground for text and icons on an accent background: white, as GTK and
/// libadwaita use, while it reaches MIN_UI_CONTRAST; otherwise whichever of
/// white and black contrasts more (black on yellow, light green, orange…).
pub fn readable_fg(bg : Rgb) -> Rgb {
let on_white = contrast_ratio(bg, white)
if on_white >= MIN_UI_CONTRAST || on_white >= contrast_ratio(bg, black) {
white
} else {
black
}
}
///|
/// Window background of GTK's Default theme (theme_bg_color).
pub fn window_bg(dark : Bool) -> Rgb {
if dark {
{ r: 53.0 / 255.0, g: 53.0 / 255.0, b: 53.0 / 255.0, } // #353535
} else {
{ r: 246.0 / 255.0, g: 245.0 / 255.0, b: 244.0 / 255.0, } // #f6f5f4
}
}
///|
/// The accent as a text/link colour on the window background: the accent
/// itself if it is readable there, else darkened (light scheme) or lightened
/// (dark scheme) just enough to be.
pub fn accent_text_color(accent : Rgb, dark : Bool) -> Rgb {
let bg = window_bg(dark)
let toward = if dark { white } else { black }
for i in 0..<=20 {
let c = accent.mix(toward, i.to_double() * 0.05)
if contrast_ratio(c, bg) >= MIN_TEXT_CONTRAST {
return c
}
}
toward
}
///|
/// The colours derived from one accent.
#derive(Eq, Debug)
pub(all) struct AccentColors {
/// Backgrounds: selected tab underline, slider fill, level bar, the
/// checked "default" button.
bg : Rgb
/// Text and icons on `bg`.
fg : Rgb
/// Accent used as a text colour on the window background.
text : Rgb
/// Outline of filled buttons and checks: a slightly darker accent, as the
/// theme does.
border : Rgb
}
///|
pub fn AccentColors::new(accent : Rgb, dark : Bool) -> AccentColors {
{
bg: accent,
fg: readable_fg(accent),
text: accent_text_color(accent, dark),
border: accent.mix(black, 0.15),
}
}
///|
/// CSS (for a provider at APPLICATION priority) that makes the theme use
/// the accent. Overrides the accent named colours and CSS variables (for
/// Adwaita-style themes and GTK 3-style themes that use
/// theme_selected_bg_color), plus explicit rules for the widgets moonmix
/// uses, because GTK's built-in Default theme hardcodes its blue.
pub fn accent_css(accent : Rgb, dark : Bool) -> String {
let c = AccentColors::new(accent, dark)
let bg = c.bg.to_hex()
let fg = c.fg.to_hex()
let text = c.text.to_hex()
let border = c.border.to_hex()
let lines = [
"@define-color accent_bg_color \{bg};",
"@define-color accent_fg_color \{fg};",
"@define-color accent_color \{text};",
"@define-color theme_selected_bg_color \{bg};",
"@define-color theme_selected_fg_color \{fg};",
":root { --accent-bg-color: \{bg}; --accent-fg-color: \{fg}; --accent-color: \{text}; }",
"scale > trough > highlight { background-color: \{bg}; border-color: \{bg}; }",
"levelbar > trough > block.high, levelbar > trough > block:not(.empty):not(.low):not(.full) { background-color: \{bg}; border-color: \{bg}; }",
"notebook > header.top > tabs > tab:checked { box-shadow: inset 0 -4px \{bg}; }",
"notebook > header.bottom > tabs > tab:checked { box-shadow: inset 0 4px \{bg}; }",
"notebook > header.left > tabs > tab:checked { box-shadow: inset -4px 0 \{bg}; }",
"notebook > header.right > tabs > tab:checked { box-shadow: inset 4px 0 \{bg}; }",
"button.mm-default:checked { background-image: none; background-color: \{bg}; border-color: \{border}; color: \{fg}; }",
"check:checked, radio:checked, switch:checked { background-image: none; background-color: \{bg}; border-color: \{border}; color: \{fg}; }",
"row:selected, .view:selected { background-color: \{bg}; color: \{fg}; }",
"link, button.link { color: \{text}; }",
":focus-visible { outline-color: alpha(\{bg}, 0.5); }",
]
lines.join("\n") + "\n"
}
///|
/// The portal's color-scheme preference.
#derive(Eq, Debug)
pub(all) enum ColorScheme {
NoPreference
Dark
Light
}
///|
/// org.freedesktop.appearance color-scheme: 1 dark, 2 light, else none.
pub fn ColorScheme::from_portal(v : Int32) -> ColorScheme {
match v {
1 => Dark
2 => Light
_ => NoPreference
}
}
-120
View File
@@ -1,120 +0,0 @@
///|
fn hex(s : String) -> @model.Rgb {
@model.Rgb::parse_hex(s).unwrap()
}
///|
test "from_portal accepts 0..1 and rejects unset values" {
assert_eq(
@model.Rgb::from_portal(1.0, 0.5, 0.0),
Some({ r: 1.0, g: 0.5, b: 0.0, }),
)
assert_eq(@model.Rgb::from_portal(0.0, 0.0, 0.0), Some(@model.black))
// GNOME reports (-1, -1, -1) before an accent is chosen.
assert_eq(@model.Rgb::from_portal(-1.0, -1.0, -1.0), None)
assert_eq(@model.Rgb::from_portal(0.2, 1.5, 0.2), None)
assert_eq(@model.Rgb::from_portal(0.0 / 0.0, 0.2, 0.2), None)
}
///|
test "hex round trip" {
assert_eq(hex("#3584e4").to_hex(), "#3584e4")
assert_eq(hex("#ED5B00").to_hex(), "#ed5b00")
assert_eq(hex("#fff"), @model.white)
assert_eq(hex("#000000"), @model.black)
assert_eq(@model.Rgb::parse_hex("3584e4"), None)
assert_eq(@model.Rgb::parse_hex("#3584e"), None)
assert_eq(@model.Rgb::parse_hex("#zzzzzz"), None)
// Portal doubles are rounded to the nearest byte.
assert_eq(
@model.Rgb::from_portal(1.0, 0.471, 0.0).unwrap().to_hex(),
"#ff7800",
)
}
///|
test "contrast ratio" {
assert_eq(@model.contrast_ratio(@model.white, @model.black), 21.0)
assert_eq(@model.contrast_ratio(@model.black, @model.black), 1.0)
// GTK's blue against white (well known: ~3.76).
let r = @model.contrast_ratio(hex("#3584e4"), @model.white)
assert_true(r > 3.7 && r < 3.8)
// Symmetric.
assert_eq(@model.contrast_ratio(@model.white, hex("#3584e4")), r)
}
///|
test "readable foreground on accent backgrounds" {
// Dark accents keep white text.
assert_eq(@model.readable_fg(hex("#1c71d8")), @model.white)
assert_eq(@model.readable_fg(hex("#9141ac")), @model.white)
assert_eq(@model.readable_fg(hex("#c01c28")), @model.white)
// GTK's blue: below 4.5 with white (black would contrast more), but
// above 3, so it keeps white like GTK does.
assert_eq(@model.readable_fg(hex("#3584e4")), @model.white)
// Bright accents get black text.
assert_eq(@model.readable_fg(hex("#ff7800")), @model.black)
assert_eq(@model.readable_fg(hex("#f6d32d")), @model.black)
assert_eq(@model.readable_fg(hex("#33d17a")), @model.black)
// Whatever is chosen beats the alternative or meets AA.
for c in ["#3584e4", "#ff7800", "#2190a4", "#c88800", "#6f8396", "#ffffff"] {
let bg = hex(c)
let fg = @model.readable_fg(bg)
let other = if fg == @model.white { @model.black } else { @model.white }
assert_true(
@model.contrast_ratio(bg, fg) >= @model.MIN_UI_CONTRAST ||
@model.contrast_ratio(bg, fg) >= @model.contrast_ratio(bg, other),
)
}
}
///|
test "accent text colour is readable on the window background" {
for
c in [
"#3584e4", "#ff7800", "#f6d32d", "#33d17a", "#1c71d8", "#000000", "#ffffff",
] {
for dark in [false, true] {
let t = @model.accent_text_color(hex(c), dark)
assert_true(
@model.contrast_ratio(t, @model.window_bg(dark)) >=
@model.MIN_TEXT_CONTRAST,
)
}
}
// Already readable: unchanged.
assert_eq(@model.accent_text_color(hex("#1a5fb4"), false), hex("#1a5fb4"))
// Yellow on a light window is darkened, on a dark one kept.
assert_true(
@model.accent_text_color(hex("#f6d32d"), false).luminance() <
hex("#f6d32d").luminance(),
)
assert_eq(@model.accent_text_color(hex("#f6d32d"), true), hex("#f6d32d"))
}
///|
test "accent css overrides named colours and widget fills" {
let css = @model.accent_css(hex("#ff7800"), false)
assert_true(css.contains("@define-color accent_bg_color #ff7800;"))
assert_true(css.contains("@define-color accent_fg_color #000000;"))
assert_true(css.contains("@define-color theme_selected_bg_color #ff7800;"))
assert_true(css.contains("--accent-bg-color: #ff7800;"))
assert_true(
css.contains("scale > trough > highlight { background-color: #ff7800;"),
)
assert_true(css.contains("levelbar > trough > block.high"))
assert_true(css.contains("tab:checked { box-shadow: inset 0 -4px #ff7800; }"))
assert_true(css.contains("button.mm-default:checked"))
// The text colour is the darkened accent, not the raw one.
let text = @model.accent_text_color(hex("#ff7800"), false).to_hex()
assert_true(text != "#ff7800")
assert_true(css.contains("@define-color accent_color \{text};"))
}
///|
test "color scheme from portal" {
assert_eq(@model.ColorScheme::from_portal(0), @model.NoPreference)
assert_eq(@model.ColorScheme::from_portal(1), @model.Dark)
assert_eq(@model.ColorScheme::from_portal(2), @model.Light)
assert_eq(@model.ColorScheme::from_portal(7), @model.NoPreference)
}
-200
View File
@@ -1,200 +0,0 @@
// Icon selection, kept pure: PipeWire properties -> an ordered chain of
// icon-theme names. The GTK layer walks a chain and takes the first name the
// theme has (`gtk_icon_theme_has_icon`), so it never shows the broken-image
// placeholder unless even the last resort is missing.
//
// Chain entries starting with `APP_LOOKUP_PREFIX` ("app:<key>") ask the GUI
// to look the application up in the installed .desktop files and use that
// launcher's icon.
///|
pub fn icon_fallback_device() -> Array[String] {
["audio-card-symbolic", "audio-x-generic-symbolic"]
}
///|
pub fn icon_fallback_stream() -> Array[String] {
["application-x-executable-symbolic", "audio-x-generic-symbolic"]
}
///|
/// Absolute last resort, only used when the theme lacks everything above.
pub const ICON_MISSING : String = "image-missing"
///|
pub const APP_LOOKUP_PREFIX : String = "app:"
///|
/// "Default" toggle: first icon the theme has.
pub fn default_button_icons() -> Array[String] {
["emblem-ok-symbolic", "object-select-symbolic", "emblem-default-symbolic"]
}
///|
pub fn symbolic(name : String) -> String {
if name.has_suffix("-symbolic") {
name
} else {
name + "-symbolic"
}
}
///|
fn push_unique(out : Array[String], name : String) -> Unit {
if name != "" && !out.contains(name) {
out.push(name)
}
}
///|
/// `name` as a themed icon, symbolic variant first (it follows the theme's
/// foreground colour).
fn push_symbolic_first(out : Array[String], name : String) -> Unit {
if name == "" {
return
}
push_unique(out, symbolic(name))
push_unique(out, name)
}
///|
fn has_any(haystack : String, needles : Array[String]) -> Bool {
let h = haystack.to_lower()
needles.any(fn(n) { h.contains(n) })
}
///|
/// Icon (without suffix) for a `device.form-factor` value, "" if unknown.
pub fn form_factor_icon(form_factor : String, kind : NodeKind) -> String {
match form_factor {
"headphone" => "audio-headphones"
"headset" => "audio-headset"
"speaker" | "hifi" => "audio-speakers"
"microphone" => "audio-input-microphone"
"webcam" => "camera-web"
"handset" | "hands-free" => "phone"
"portable" => "multimedia-player"
"car" =>
if kind is Source {
"audio-input-microphone"
} else {
"audio-speakers"
}
"computer" => "computer"
"tv" | "hdmi" => "video-display"
_ => ""
}
}
///|
/// The bus of a device, from `device.bus` or else guessed from the
/// node.name prefix ("alsa_input.usb-...", "bluez_output...").
pub fn device_bus(n : Node) -> String {
if n.bus != "" {
return n.bus
}
let name = n.name
if name.has_prefix("bluez_") {
"bluetooth"
} else if has_any(name, [".usb-"]) {
"usb"
} else if has_any(name, [".pci-"]) {
"pci"
} else {
""
}
}
///|
/// Icon chain for a sink or source.
pub fn device_icon_chain(n : Node) -> Array[String] {
let kind = n.kind()
let out : Array[String] = []
// 1. what the device itself says
for h in n.icon_hints {
push_symbolic_first(out, h)
}
// 2. form factor, then HDMI / webcam heuristics, then bus
push_symbolic_first(out, form_factor_icon(n.form_factor, kind))
let text = n.name + " " + n.description
if has_any(text, ["hdmi", "displayport", "display port"]) {
push_symbolic_first(out, "video-display")
}
let bus = device_bus(n)
if kind is Source &&
(
has_any(n.description, ["webcam", "camera"]) ||
(bus == "usb" && n.description.to_lower().contains("cam"))
) {
push_symbolic_first(out, "camera-web")
}
match (bus, kind) {
("bluetooth", Source) => push_symbolic_first(out, "audio-headset")
("bluetooth", _) => push_symbolic_first(out, "audio-headphones")
_ => ()
}
// 3. by direction
match kind {
Source => push_symbolic_first(out, "audio-input-microphone")
_ => push_symbolic_first(out, "audio-speakers")
}
// 4. generic cards, then the placeholder
for f in icon_fallback_device() {
push_unique(out, f)
}
push_unique(out, ICON_MISSING)
out
}
///|
/// Icon chain for an application stream: the icons the app announces, its
/// launcher's icon from the installed .desktop files, names derived from the
/// binary / app name, then generic ones.
pub fn stream_icon_chain(n : Node) -> Array[String] {
let out : Array[String] = []
for h in n.icon_hints {
push_unique(out, h)
}
for key in [n.app_id, n.app_binary, n.app_name] {
if key != "" {
push_unique(out, APP_LOOKUP_PREFIX + key)
}
}
for key in [n.app_id, n.app_binary, n.app_name.to_lower()] {
// Many apps ship an icon named after their binary or app id.
if key != "" && !key.contains(" ") && !key.contains("/") {
push_unique(out, key)
}
}
if n.kind() is RecordStream {
push_unique(out, "audio-input-microphone-symbolic")
}
for f in icon_fallback_stream() {
push_unique(out, f)
}
push_unique(out, ICON_MISSING)
out
}
///|
/// Speaker icon for a volume (linked percent, 100 = 0 dB) and mute state.
pub fn volume_icon(percent : Double, mute : Bool) -> String {
if mute || percent <= 0.0 {
"audio-volume-muted-symbolic"
} else if percent < 34.0 {
"audio-volume-low-symbolic"
} else if percent < 67.0 {
"audio-volume-medium-symbolic"
} else {
"audio-volume-high-symbolic"
}
}
///|
/// Small symbolic icon next to a tab's label.
pub fn Tab::icon(self : Tab) -> String {
match self {
Playback | OutputDevices => "audio-speakers-symbolic"
Recording | InputDevices => "audio-input-microphone-symbolic"
}
}
-122
View File
@@ -1,122 +0,0 @@
///|
fn dev(
media_class : String,
name~ : String = "",
description~ : String = "",
form_factor~ : String = "",
bus~ : String = "",
hints~ : Array[String] = [],
) -> @model.Node {
@model.Node::new(
1,
media_class,
name~,
description~,
form_factor~,
bus~,
icon_hints=hints,
)
}
///|
test "device hint comes first, symbolic variant before plain" {
let c = @model.device_icon_chain(
dev("Audio/Sink", hints=["audio-card-pci"], form_factor="headphone"),
)
assert_eq(c[0], "audio-card-pci-symbolic")
assert_eq(c[1], "audio-card-pci")
assert_eq(c[2], "audio-headphones-symbolic")
}
///|
test "device form factors" {
let first = fn(ff, cls) {
@model.device_icon_chain(dev(cls, form_factor=ff))[0]
}
assert_eq(first("headset", "Audio/Sink"), "audio-headset-symbolic")
assert_eq(first("speaker", "Audio/Sink"), "audio-speakers-symbolic")
assert_eq(
first("microphone", "Audio/Source"),
"audio-input-microphone-symbolic",
)
assert_eq(first("webcam", "Audio/Source"), "camera-web-symbolic")
assert_eq(first("handset", "Audio/Sink"), "phone-symbolic")
assert_eq(first("tv", "Audio/Sink"), "video-display-symbolic")
assert_eq(first("car", "Audio/Source"), "audio-input-microphone-symbolic")
}
///|
test "hdmi, webcam and bluetooth heuristics" {
let hdmi = @model.device_icon_chain(
dev(
"Audio/Sink",
name="alsa_output.pci-0000_01_00.1.hdmi-stereo",
description="HDMI / DisplayPort",
),
)
assert_eq(hdmi[0], "video-display-symbolic")
let cam = @model.device_icon_chain(
dev(
"Audio/Source",
name="alsa_input.usb-EMEET_SmartCam_C960.mono-fallback",
description="EMEET SmartCam C960 Mono",
),
)
assert_eq(cam[0], "camera-web-symbolic")
let bt = @model.device_icon_chain(
dev("Audio/Sink", name="bluez_output.AA_BB.1"),
)
assert_eq(bt[0], "audio-headphones-symbolic")
assert_eq(
@model.device_bus(dev("Audio/Sink", name="alsa_output.usb-X.analog-stereo")),
"usb",
)
}
///|
test "device chain always ends in fallbacks" {
let c = @model.device_icon_chain(dev("Audio/Sink"))
assert_eq(c, [
"audio-speakers-symbolic", "audio-speakers", "audio-card-symbolic", "audio-x-generic-symbolic",
"image-missing",
])
let s = @model.device_icon_chain(dev("Audio/Source"))
assert_eq(s[0], "audio-input-microphone-symbolic")
assert_eq(s[s.length() - 1], "image-missing")
}
///|
test "stream chain: hints, desktop lookup, binary, fallbacks" {
let n = @model.Node::new(
9,
"Stream/Output/Audio",
app_name="Firefox",
app_binary="firefox",
app_id="org.mozilla.firefox",
icon_hints=["firefox-esr"],
)
assert_eq(@model.stream_icon_chain(n), [
"firefox-esr", "app:org.mozilla.firefox", "app:firefox", "app:Firefox", "org.mozilla.firefox",
"firefox", "application-x-executable-symbolic", "audio-x-generic-symbolic", "image-missing",
])
let bare = @model.Node::new(10, "Stream/Input/Audio")
assert_eq(@model.stream_icon_chain(bare), [
"audio-input-microphone-symbolic", "application-x-executable-symbolic", "audio-x-generic-symbolic",
"image-missing",
])
}
///|
test "volume icon follows volume and mute" {
assert_eq(@model.volume_icon(100.0, false), "audio-volume-high-symbolic")
assert_eq(@model.volume_icon(50.0, false), "audio-volume-medium-symbolic")
assert_eq(@model.volume_icon(10.0, false), "audio-volume-low-symbolic")
assert_eq(@model.volume_icon(0.0, false), "audio-volume-muted-symbolic")
assert_eq(@model.volume_icon(100.0, true), "audio-volume-muted-symbolic")
}
///|
test "tab icons" {
assert_eq(@model.Tab::Playback.icon(), "audio-speakers-symbolic")
assert_eq(@model.Tab::InputDevices.icon(), "audio-input-microphone-symbolic")
}
-36
View File
@@ -1,36 +0,0 @@
// Peak meter display: maps a linear sample peak to the bar position and
// lets the bar fall back smoothly instead of flickering.
///|
/// How much of the full bar a falling meter drops per update (~25 updates
/// per second, so silence empties a full bar in about a second).
pub const METER_DECAY : Double = 0.04
///|
/// Bar position 0..1 for a linear peak. Uses the same cubic curve as the
/// volume sliders, so a full-scale signal at 50% volume shows at half the bar
/// and quiet sounds are still visible.
pub fn meter_level(linear_peak : Double) -> Double {
if linear_peak <= 0.0 {
0.0
} else if linear_peak >= 1.0 {
1.0
} else {
@math.cbrt(linear_peak)
}
}
///|
/// Next bar position: jump up at once, fall by at most METER_DECAY.
pub fn meter_step(shown : Double, level : Double) -> Double {
if level >= shown {
level
} else {
let fallen = shown - METER_DECAY
if fallen > level {
fallen
} else {
level
}
}
}
-18
View File
@@ -1,18 +0,0 @@
///|
test "meter_level uses the cubic volume curve and clamps" {
assert_eq(@model.meter_level(0.0), 0.0)
assert_eq(@model.meter_level(-0.5), 0.0)
assert_eq(@model.meter_level(1.0), 1.0)
assert_eq(@model.meter_level(1.7), 1.0)
assert_true((@model.meter_level(0.125) - 0.5).abs() < 1.0e-9)
}
///|
test "meter_step rises at once and decays slowly" {
assert_eq(@model.meter_step(0.2, 0.9), 0.9)
assert_true(
(@model.meter_step(0.9, 0.0) - (0.9 - @model.METER_DECAY)).abs() < 1.0e-9,
)
assert_eq(@model.meter_step(0.5, 0.48), 0.48)
assert_eq(@model.meter_step(0.01, 0.0), 0.0)
}
+3 -84
View File
@@ -6,104 +6,41 @@ import {
}
// Values
pub const APP_LOOKUP_PREFIX : String = "app:"
pub const ICON_MISSING : String = "image-missing"
pub const MAX_PERCENT : Double = 150.0
pub const METER_DECAY : Double = 0.04
pub const MIN_TEXT_CONTRAST : Double = 4.5
pub const MIN_UI_CONTRAST : Double = 3.0
pub const NORM_PERCENT : Double = 100.0
pub fn accent_css(Rgb, Bool) -> String
pub fn accent_text_color(Rgb, Bool) -> Rgb
pub let black : Rgb
pub fn clamp_percent(Double) -> Double
pub fn compare_text(String, String) -> Int32
pub fn contrast_ratio(Rgb, Rgb) -> Double
pub fn default_button_icons() -> Array[String]
pub fn device_bus(Node) -> String
pub fn device_icon_chain(Node) -> Array[String]
pub fn diff_rows(Array[Row], Array[Row]) -> Diff
pub fn display_title(Node) -> String
pub fn form_factor_icon(String, NodeKind) -> String
pub fn format_db(Double) -> String
pub fn format_percent(Double) -> String
pub fn format_volume(Array[Double]) -> String
pub fn icon_fallback_device() -> Array[String]
pub fn icon_fallback_stream() -> Array[String]
pub fn linear_to_db(Double) -> Double?
pub fn linear_to_percent(Double) -> Double
pub fn linked_percent(Array[Double]) -> Double
pub fn meter_level(Double) -> Double
pub fn meter_step(Double, Double) -> Double
pub fn percent_to_linear(Double) -> Double
pub fn readable_fg(Rgb) -> Rgb
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
pub fn stream_icon_chain(Node) -> Array[String]
pub fn symbolic(String) -> String
pub fn volume_icon(Double, Bool) -> String
pub let white : Rgb
pub fn window_bg(Bool) -> Rgb
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) struct AccentColors {
bg : Rgb
fg : Rgb
text : Rgb
border : Rgb
}
pub fn AccentColors::new(Rgb, Bool) -> Self
#derive(Eq, @debug.Debug)
pub(all) enum ColorScheme {
NoPreference
Dark
Light
}
pub fn ColorScheme::from_portal(Int32) -> Self
#derive(Eq, @debug.Debug)
pub(all) struct DeviceChoice {
id : Int32
@@ -141,16 +78,12 @@ pub(all) struct Node {
media_class : String
app_name : String
media_name : String
icon_hints : Array[String]
form_factor : String
bus : String
app_binary : String
app_id : 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_hints? : Array[String], form_factor? : String, bus? : String, app_binary? : String, app_id? : String, volumes? : Array[Double], mute? : Bool) -> Self
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 {
@@ -162,25 +95,12 @@ pub(all) enum NodeKind {
}
pub fn NodeKind::from_media_class(String) -> Self
#derive(Eq, @debug.Debug)
pub(all) struct Rgb {
r : Double
g : Double
b : Double
}
pub fn Rgb::from_portal(Double, Double, Double) -> Self?
pub fn Rgb::luminance(Self) -> Double
pub fn Rgb::mix(Self, Self, Double) -> Self
pub fn Rgb::parse_hex(String) -> Self?
pub fn Rgb::to_hex(Self) -> String
#derive(Eq, @debug.Debug)
pub(all) struct Row {
id : Int32
title : String
subtitle : String
icons : Array[String]
volume_icon : String
icon_name : String
volumes : Array[Double]
percent : Double
volume_text : String
@@ -211,7 +131,6 @@ pub(all) enum Tab {
}
pub fn Tab::all() -> Array[Self]
pub fn Tab::empty_text(Self) -> String
pub fn Tab::icon(Self) -> String
pub fn Tab::label(Self) -> String
pub fn Tab::node_kind(Self) -> NodeKind
+3 -17
View File
@@ -33,13 +33,7 @@ pub(all) struct Node {
media_class : String
app_name : String // application.name (streams)
media_name : String // media.name (streams)
/// Icon names PipeWire/the app suggested, best first (application.icon-name,
/// media.icon-name for streams; device.icon-name, node.icon-name for devices).
icon_hints : Array[String]
form_factor : String // device.form-factor: "headset", "webcam", ...
bus : String // device.bus: "usb", "bluetooth", "pci", ...
app_binary : String // application.process.binary
app_id : String // pipewire.access.portal.app_id / application.id
icon_name : String // application.icon-name / device.icon-name
volumes : Array[Double] // linear, one per channel; empty = no volume
mute : Bool
}
@@ -57,11 +51,7 @@ pub fn Node::new(
description~ : String = "",
app_name~ : String = "",
media_name~ : String = "",
icon_hints~ : Array[String] = [],
form_factor~ : String = "",
bus~ : String = "",
app_binary~ : String = "",
app_id~ : String = "",
icon_name~ : String = "",
volumes~ : Array[Double] = [],
mute~ : Bool = false,
) -> Node {
@@ -72,11 +62,7 @@ pub fn Node::new(
media_class,
app_name,
media_name,
icon_hints,
form_factor,
bus,
app_binary,
app_id,
icon_name,
volumes,
mute,
}
+15 -7
View File
@@ -60,9 +60,7 @@ pub(all) struct Row {
id : Int32
title : String
subtitle : String
/// Icon-theme names to try in order (see icons.mbt).
icons : Array[String]
volume_icon : String // speaker icon matching volume + mute
icon_name : String
volumes : Array[Double]
percent : Double // linked slider value (cubic %)
volume_text : String // "75% (-7.50 dB)"
@@ -127,12 +125,11 @@ pub fn rows(state : State, tab : Tab) -> Array[Row] {
id: n.id,
title: display_title(n),
subtitle,
icons: if is_stream {
stream_icon_chain(n)
icon_name: if n.icon_name != "" {
n.icon_name
} else {
device_icon_chain(n)
default_icon(kind)
},
volume_icon: volume_icon(linked_percent(n.volumes), n.mute),
volumes: n.volumes,
percent: linked_percent(n.volumes),
volume_text: if n.volumes.length() > 0 {
@@ -153,6 +150,17 @@ pub fn rows(state : State, tab : Tab) -> Array[Row] {
})
}
///|
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.
+1 -2
View File
@@ -33,8 +33,7 @@ test "device rows" {
assert_eq(ins.length(), 1)
assert_true(ins[0].mute)
assert_true(ins[0].is_default)
assert_eq(ins[0].icons[0], "audio-input-microphone-symbolic")
assert_eq(ins[0].volume_icon, "audio-volume-muted-symbolic")
assert_eq(ins[0].icon_name, "audio-input-microphone-symbolic")
}
///|
-114
View File
@@ -1,114 +0,0 @@
#!/usr/bin/env python3
"""Fake org.freedesktop.portal.Settings for the smoke test.
Owns org.freedesktop.portal.Desktop on the session bus and serves the
org.freedesktop.appearance namespace with a fixed accent colour and colour
scheme, like GNOME 47+ / KDE Plasma 6 do.
fake-portal.py R G B [COLOR_SCHEME] (channels 0..1; scheme 0/1/2)
Writing a line "R G B [SCHEME]" to stdin changes the values and emits
SettingChanged, to exercise live updates.
"""
import sys
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
from gi.repository import Gio, GLib
XML = """
<node>
<interface name="org.freedesktop.portal.Settings">
<method name="ReadAll">
<arg type="as" name="namespaces" direction="in"/>
<arg type="a{sa{sv}}" name="value" direction="out"/>
</method>
<method name="Read">
<arg type="s" name="namespace" direction="in"/>
<arg type="s" name="key" direction="in"/>
<arg type="v" name="value" direction="out"/>
</method>
<method name="ReadOne">
<arg type="s" name="namespace" direction="in"/>
<arg type="s" name="key" direction="in"/>
<arg type="v" name="value" direction="out"/>
</method>
<signal name="SettingChanged">
<arg type="s" name="namespace"/>
<arg type="s" name="key"/>
<arg type="v" name="value"/>
</signal>
<property name="version" type="u" access="read"/>
</interface>
</node>
"""
NS = "org.freedesktop.appearance"
PATH = "/org/freedesktop/portal/desktop"
IFACE = "org.freedesktop.portal.Settings"
state = {}
def values():
return {
"accent-color": GLib.Variant("(ddd)", state["accent"]),
"color-scheme": GLib.Variant("u", state["scheme"]),
}
def parse(args):
r, g, b = (float(x) for x in args[:3])
return (r, g, b), int(args[3]) if len(args) > 3 else 0
def on_call(conn, sender, path, iface, method, params, inv):
if method == "ReadAll":
(namespaces,) = params.unpack()
want = not namespaces or any(
n == NS or (n.endswith("*") and NS.startswith(n[:-1])) or n == ""
for n in namespaces
)
inv.return_value(GLib.Variant("(a{sa{sv}})", ({NS: values()} if want else {},)))
return
ns, key = params.unpack()
v = values().get(key) if ns == NS else None
if v is None:
inv.return_dbus_error("org.freedesktop.portal.Error.NotFound", "no such setting")
elif method == "Read": # version 1 wraps the value in another variant
inv.return_value(GLib.Variant("(v)", (GLib.Variant("v", v),)))
else:
inv.return_value(GLib.Variant("(v)", (v,)))
def on_get(conn, sender, path, iface, prop):
return GLib.Variant("u", 2)
def main():
state["accent"], state["scheme"] = parse(sys.argv[1:])
loop = GLib.MainLoop()
bus = Gio.bus_get_sync(Gio.BusType.SESSION)
info = Gio.DBusNodeInfo.new_for_xml(XML).interfaces[0]
bus.register_object(PATH, info, on_call, on_get, None)
def on_stdin(ch, cond):
line = ch.readline()
if not line:
return False
state["accent"], state["scheme"] = parse(line.split())
for key, v in values().items():
bus.emit_signal(None, PATH, IFACE, "SettingChanged",
GLib.Variant("(ssv)", (NS, key, v)))
return True
GLib.io_add_watch(GLib.IOChannel.unix_new(0), GLib.IO_IN | GLib.IO_HUP, on_stdin)
Gio.bus_own_name_on_connection(
bus, "org.freedesktop.portal.Desktop", Gio.BusNameOwnerFlags.NONE,
lambda *_: print("fake portal: ready", flush=True),
lambda *_: (print("fake portal: name lost", flush=True), loop.quit()))
loop.run()
if __name__ == "__main__":
main()
+1 -1
View File
@@ -3,5 +3,5 @@
# 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 gio-unix-2.0}"
PKGS="${MOONMIX_PKGS:-libpipewire-0.3 wireplumber-0.5 gtk4}"
exec "${MOONMIX_CC:-cc}" "$@" $(pkg-config --cflags --libs $PKGS)
+12 -56
View File
@@ -2,8 +2,7 @@
# 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: with the theme's
# accent and, through a fake XDG Desktop Portal, with a system accent colour.
# 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.
@@ -26,13 +25,11 @@ context.objects = [
{ factory = adapter
args = { factory.name = support.null-audio-sink
node.name = "test_speakers" node.description = "Test Speakers"
device.form-factor = "speaker"
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"
device.form-factor = "headphone"
media.class = "Audio/Sink" audio.position = [ FL FR ]
object.linger = true } }
]
@@ -42,7 +39,7 @@ context.modules = [
args = {
node.description = "Test Microphone"
capture.props = { node.name = "test_mic_capture" node.passive = true audio.position = [ MONO ] }
playback.props = { node.name = "test_mic" device.form-factor = "microphone" media.class = "Audio/Source" audio.position = [ MONO ] }
playback.props = { node.name = "test_mic" media.class = "Audio/Source" audio.position = [ MONO ] }
} }
]
CONF
@@ -61,7 +58,7 @@ 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 PIPE
trap cleanup EXIT INT TERM
pipewire >"$XDG_RUNTIME_DIR/pipewire.log" 2>&1 & PIDS="$PIDS $!"
sleep 1
@@ -81,19 +78,18 @@ wait_for() {
# can wedge its event queue, after which nothing gets linked.
wait_for '\[default'
LOGS="$XDG_RUNTIME_DIR"
# Two minutes of stereo s16 48 kHz noise as a WAV file (header written by
# hand: no python/sox needed), so the peak meters have a signal; it only
# plays into the private null sinks. Reading raw audio from a device made
# older pw-cat (PipeWire 1.4) exit without creating a stream, so it is a file.
# 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/urandom; } > "$LOGS/noise.wav"
{ pw-play -P '{ application.name = "Test Player" application.icon-name = "applications-multimedia-symbolic" media.name = "Smoke test tone" }' \
"$LOGS/noise.wav"; echo "pw-play exited with $?"; } >"$LOGS/play.log" 2>&1 & PIDS="$PIDS $!"
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" application.icon-name = "audio-input-microphone" media.name = "Mic capture" }' \
-P '{ application.name = "Test Recorder" media.name = "Mic capture" }' \
/dev/null >"$LOGS/record.log" 2>&1 & PIDS="$PIDS $!"
wait_for 'Test Player | .*-> ' || true
@@ -122,15 +118,6 @@ 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
# meter <node>: a peak meter on it must see the noise.
meter() {
echo "### meter $1"
"$PROBE" meter "$1" >"$OUT" 2>&1 || { echo "FAIL: no signal on $1's meter"; fail=1; }
grep '^== meter' "$OUT"
}
meter "${STREAM:-0}"
meter test_speakers
if [ "$fail" != 0 ]; then
echo "### diagnostics"
echo "--- pw-play playback:"; cat "$LOGS/play.log"
@@ -157,39 +144,8 @@ if [ -n "$SHOTS" ] && [ -x "$GUI" ]; then
if command -v gtk4-broadwayd >/dev/null; then
gtk4-broadwayd :5 >/dev/null 2>&1 & PIDS="$PIDS $!"
sleep 1
gui() { MOONMIX_ICON_DIR="$ROOT/data/icons" GDK_BACKEND=broadway BROADWAY_DISPLAY=:5 timeout 30 stdbuf -oL "$GUI"; }
# Default look: no session bus, so no portal and the theme's own accent.
DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/no-bus" MOONMIX_SCREENSHOT="$SHOTS" gui || fail=1
# System accent: a fake org.freedesktop.portal.Settings on a private
# session bus reports a green accent, then switches to orange while
# moonmix runs (SettingChanged); it takes the shots once orange is applied.
PY=""
for p in python3 /usr/bin/python3; do
if "$p" -c 'from gi.repository import Gio' 2>/dev/null; then PY=$p; break; fi
done
if [ -n "$PY" ] && command -v dbus-daemon >/dev/null; then
echo "### system accent colour (fake portal) -> $SHOTS-accent-<tab>.png"
dbus-daemon --session --nofork --address="unix:path=$XDG_RUNTIME_DIR/bus" \
>/dev/null 2>&1 & PIDS="$PIDS $!"
export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"
for _ in $(seq 1 40); do [ -S "$XDG_RUNTIME_DIR/bus" ] && break; sleep 0.25; done
mkfifo "$LOGS/portal.in"
"$PY" "$ROOT/tools/fake-portal.py" 0.2 0.82 0.48 0 <"$LOGS/portal.in" >"$LOGS/portal.log" 2>&1 & PIDS="$PIDS $!"
exec 4>"$LOGS/portal.in"
for _ in $(seq 1 40); do grep -q ready "$LOGS/portal.log" 2>/dev/null && break; sleep 0.25; done
MOONMIX_SCREENSHOT="$SHOTS-accent" MOONMIX_SCREENSHOT_ACCENT="#ff7800" gui >"$LOGS/accent.log" 2>&1 & GUIPID=$!
for _ in $(seq 1 40); do grep -q 'accent #33d17a' "$LOGS/accent.log" && break; sleep 0.25; done
echo "1 0.471 0 0" >&4 || true
wait "$GUIPID" || fail=1
exec 4>&-
cat "$LOGS/accent.log"
if ! grep -q 'accent #33d17a, light' "$LOGS/accent.log" || ! grep -q 'accent #ff7800, light' "$LOGS/accent.log"; then
echo "FAIL: accent colour not read from the portal or not updated live"
cat "$LOGS/portal.log"; fail=1
fi
else
echo "python3 with gi or dbus-daemon not found; skipping the accent colour screenshots"
fi
GDK_BACKEND=broadway BROADWAY_DISPLAY=:5 MOONMIX_SCREENSHOT="$SHOTS" \
timeout 30 "$GUI" || fail=1
else
echo "gtk4-broadwayd not found; skipping GUI"
fi
-8
View File
@@ -6,14 +6,6 @@ import {
}
// Values
pub fn meter_start(Int32, @model.NodeKind) -> Bool
pub fn meter_stop(Int32) -> Unit
pub fn meter_stop_all() -> Unit
pub fn meter_take(Int32) -> Double?
pub fn move_stream(Int32, Int32) -> Bool
pub fn node_ids() -> Array[Int32]
+5 -68
View File
@@ -103,18 +103,6 @@ extern "C" fn ffi_set_default(kind : Int32, id : Int32) -> Int32 = "mm_wp_set_de
///|
extern "C" fn ffi_move_stream(stream : Int32, device : Int32) -> Int32 = "mm_wp_move_stream"
///|
extern "C" fn ffi_meter_start(id : Int32, kind : Int32) -> Int32 = "mm_wp_meter_start"
///|
extern "C" fn ffi_meter_stop(id : Int32) = "mm_wp_meter_stop"
///|
extern "C" fn ffi_meter_stop_all() = "mm_wp_meter_stop_all"
///|
extern "C" fn ffi_meter_take(id : Int32) -> Double = "mm_wp_meter_take"
///|
/// NUL-terminated UTF-8 for C.
fn cstr(s : String) -> Bytes {
@@ -170,9 +158,7 @@ pub fn node_prop(id : Int32, key : String) -> String {
///|
/// Current state of a node as a model node, or None if it is gone.
pub fn read_node(id : Int32) -> @model.Node? {
// Peak-meter streams (ours, pavucontrol's via pipewire-pulse) are not
// something to show or control.
if ffi_node_exists(id) == 0 || node_prop(id, "stream.monitor") == "true" {
if ffi_node_exists(id) == 0 {
return None
}
let nch = ffi_query_volume(id)
@@ -186,22 +172,12 @@ pub fn read_node(id : Int32) -> @model.Node? {
node_prop(id, "node.nick")
}
}
let icon_hints = []
for
key in [
"application.icon-name", "media.icon-name", "node.icon-name", "device.icon-name",
] {
let v = node_prop(id, key)
if v != "" && !icon_hints.contains(v) {
icon_hints.push(v)
}
}
let app_id = {
let a = node_prop(id, "pipewire.access.portal.app_id")
let icon = {
let a = node_prop(id, "application.icon-name")
if a != "" {
a
} else {
node_prop(id, "application.id")
node_prop(id, "device.icon-name")
}
}
Some(
@@ -212,11 +188,7 @@ pub fn read_node(id : Int32) -> @model.Node? {
description~,
app_name=node_prop(id, "application.name"),
media_name=node_prop(id, "media.name"),
icon_hints~,
form_factor=node_prop(id, "device.form-factor"),
bus=node_prop(id, "device.bus"),
app_binary=node_prop(id, "application.process.binary"),
app_id~,
icon_name=icon,
volumes~,
mute~,
),
@@ -292,38 +264,3 @@ pub fn set_default_source(id : Int32) -> Bool {
pub fn move_stream(stream_id : Int32, device_id : Int32) -> Bool {
ffi_move_stream(stream_id, device_id) != 0
}
///|
/// Start a live peak meter on a sink, source or playback stream (other
/// kinds have nothing to meter). True if one is running for `id`.
pub fn meter_start(id : Int32, kind : @model.NodeKind) -> Bool {
let k = match kind {
Sink => 0
Source => 1
PlaybackStream => 2
RecordStream | Other => return false
}
ffi_meter_start(id, k) != 0
}
///|
pub fn meter_stop(id : Int32) -> Unit {
ffi_meter_stop(id)
}
///|
pub fn meter_stop_all() -> Unit {
ffi_meter_stop_all()
}
///|
/// Linear peak (0..1, may exceed 1 when clipping) since the last call, or
/// None if `id` has no meter.
pub fn meter_take(id : Int32) -> Double? {
let p = ffi_meter_take(id)
if p < 0.0 {
None
} else {
Some(p)
}
}
+1 -149
View File
@@ -7,10 +7,7 @@
* - 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;
* - peak meters: a small capture pw_stream per monitored node, created on
* WirePlumber's own pw_core (the same connection), like the peak streams
* pipewire-pulse creates for pavucontrol.
* - 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
@@ -19,8 +16,6 @@
#include <string.h>
#include <wp/wp.h>
#include <pipewire/keys.h>
#include <pipewire/stream.h>
#include <spa/param/audio/format-utils.h>
#include "moonbit.h"
enum {
@@ -146,12 +141,9 @@ static void on_defaults_changed(WpPlugin *p, gpointer d) {
emit(MM_EV_DEFAULTS_CHANGED, 0);
}
static void forget_meters(void);
static void on_disconnected(WpCore *core, gpointer d) {
(void)core;
(void)d;
forget_meters();
emit(MM_EV_DISCONNECTED, 0);
}
@@ -468,143 +460,3 @@ MOONBIT_FFI_EXPORT int32_t mm_wp_move_stream(int32_t stream_id,
wp_metadata_set(m, (guint32)stream_id, "target.object", "Spa:Id", serial);
return 1;
}
/* ---- peak meters ---------------------------------------------------------- */
/* One capture stream per monitored node. Not RT_PROCESS, so `process` runs
* on the main loop; it only folds the buffer into `peak`, which the GUI reads
* (and resets) from a timer. */
typedef struct {
struct pw_stream *stream;
struct spa_hook listener;
float peak;
} MmMeter;
static GHashTable *g_meters; /* node id -> MmMeter* */
static void meter_process(void *data) {
MmMeter *m = data;
struct pw_buffer *b = pw_stream_dequeue_buffer(m->stream);
if (!b)
return;
struct spa_buffer *buf = b->buffer;
if (buf->n_datas > 0 && buf->datas[0].data) {
struct spa_data *d = &buf->datas[0];
uint32_t off = SPA_MIN(d->chunk->offset, d->maxsize);
uint32_t size = SPA_MIN(d->chunk->size, d->maxsize - off);
const float *f = SPA_PTROFF(d->data, off, const float);
float peak = m->peak;
for (uint32_t i = 0; i < size / sizeof(float); i++) {
float v = f[i] < 0 ? -f[i] : f[i];
if (v > peak)
peak = v;
}
m->peak = peak;
}
pw_stream_queue_buffer(m->stream, b);
}
static const struct pw_stream_events meter_events = {
PW_VERSION_STREAM_EVENTS,
.process = meter_process,
};
static void meter_free(gpointer p) {
MmMeter *m = p;
if (m->stream)
pw_stream_destroy(m->stream);
g_free(m);
}
/* Start a peak meter on node `id`. `kind`: 0 = sink (captures its monitor),
* 1 = source, 2 = playback stream. Returns 1 if a meter runs (or already
* ran) for it. */
MOONBIT_FFI_EXPORT int32_t mm_wp_meter_start(int32_t id, int32_t kind) {
if (!g_core || !wp_core_is_connected(g_core))
return 0;
if (!g_meters)
g_meters = g_hash_table_new_full(NULL, NULL, NULL, meter_free);
if (g_hash_table_contains(g_meters, GINT_TO_POINTER(id)))
return 1;
g_autoptr(WpNode) node = lookup_node((guint32)id);
if (!node)
return 0;
const char *serial = wp_pipewire_object_get_property(
WP_PIPEWIRE_OBJECT(node), PW_KEY_OBJECT_SERIAL);
struct pw_core *pwc = wp_core_get_pw_core(g_core);
if (!serial || !pwc)
return 0;
struct pw_properties *props = pw_properties_new(
PW_KEY_MEDIA_TYPE, "Audio", PW_KEY_MEDIA_CATEGORY, "Capture",
PW_KEY_MEDIA_ROLE, "DSP", PW_KEY_NODE_NAME, "moonmix-peak",
PW_KEY_APP_NAME, "moonmix", PW_KEY_STREAM_MONITOR, "true",
PW_KEY_TARGET_OBJECT, serial, PW_KEY_NODE_DONT_RECONNECT, "true",
NULL);
if (kind == 0)
pw_properties_set(props, PW_KEY_STREAM_CAPTURE_SINK, "true");
/* Don't keep outputs running just to meter them; a source is opened so
* its level shows, like pavucontrol does. */
if (kind != 1)
pw_properties_set(props, PW_KEY_NODE_PASSIVE, "true");
MmMeter *m = g_new0(MmMeter, 1);
m->stream = pw_stream_new(pwc, "moonmix peak meter", props);
if (!m->stream) {
g_free(m);
return 0;
}
pw_stream_add_listener(m->stream, &m->listener, &meter_events, m);
uint8_t buffer[512];
struct spa_pod_builder pb = SPA_POD_BUILDER_INIT(buffer, sizeof buffer);
struct spa_audio_info_raw info = {.format = SPA_AUDIO_FORMAT_F32,
.channels = 1};
const struct spa_pod *params[1] = {
spa_format_audio_raw_build(&pb, SPA_PARAM_EnumFormat, &info)};
if (pw_stream_connect(m->stream, PW_DIRECTION_INPUT, PW_ID_ANY,
PW_STREAM_FLAG_AUTOCONNECT |
PW_STREAM_FLAG_MAP_BUFFERS |
PW_STREAM_FLAG_DONT_RECONNECT,
params, 1) < 0) {
meter_free(m);
return 0;
}
g_hash_table_insert(g_meters, GINT_TO_POINTER(id), m);
return 1;
}
/* The streams belong to the pw_core, which libpipewire tears down (with
* them) on disconnect: drop our records without touching the streams. */
static void forget_meters(void) {
if (!g_meters)
return;
GHashTableIter it;
gpointer v;
g_hash_table_iter_init(&it, g_meters);
while (g_hash_table_iter_next(&it, NULL, &v))
((MmMeter *)v)->stream = NULL;
g_hash_table_remove_all(g_meters);
}
MOONBIT_FFI_EXPORT void mm_wp_meter_stop(int32_t id) {
if (g_meters)
g_hash_table_remove(g_meters, GINT_TO_POINTER(id));
}
MOONBIT_FFI_EXPORT void mm_wp_meter_stop_all(void) {
if (g_meters)
g_hash_table_remove_all(g_meters);
}
/* Highest absolute sample since the last call (linear, 0..1+), then resets;
* -1 if node `id` has no meter. */
MOONBIT_FFI_EXPORT double mm_wp_meter_take(int32_t id) {
MmMeter *m = g_meters ? g_hash_table_lookup(g_meters, GINT_TO_POINTER(id))
: NULL;
if (!m)
return -1.0;
double p = m->peak;
m->peak = 0;
return p;
}