Author SHA1 Message Date
SpriteandClaude Sonnet 5.5 bc675459d9 Fix deprecated StringView to_string warning (CI --deny-warn)
CI / check (pull_request) Successful in 10s
CI / native (pull_request) Successful in 1m9s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 01:05:12 +00:00
SpriteandClaude Sonnet 5.5 3ac96fea35 Merge origin/main into better-icons
CI / check (pull_request) Failing after 10s
CI / native (pull_request) Successful in 1m9s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 00:48:27 +00:00
SpriteandClaude Sonnet 5.5 cf8bab0d36 Use real icons: per-device/app icon chains, volume icons, app icon
CI / check (pull_request) Failing after 9s
CI / native (pull_request) Successful in 1m5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 00:43:28 +00:00
56 changed files with 190 additions and 3011 deletions

No files matched your search

-8
View File
@@ -1,8 +0,0 @@
.git
_build
target
.mooncakes
.moonagent
**/.env
**/.env.*
screenshots
+11 -15
View File
@@ -6,16 +6,12 @@ on:
pull_request:
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
# Pure MoonBit: type-check every package and run the portable model tests
# directly on the Depot Ubuntu 24.04 runner.
# Pure MoonBit: type-check every package and run the model tests.
# Needs no audio/GUI libraries, so it runs on the default runner image
# (node:20-bullseye-like).
check:
runs-on: depot-ubuntu-24.04-4
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -30,18 +26,19 @@ jobs:
moon check --target native --deny-warn
moon fmt --check
# Native tests run in the trixie job: linking MoonBit's runtime needs
# -lpthread on bullseye's glibc 2.31.
- name: moon test (pure packages)
run: moon test --target wasm-gc
# Native build + headless smoke test. Ubuntu 24.04 (the Depot host image)
# only ships WirePlumber 0.4, so this job runs in a debian:trixie container
# (PipeWire 1.4, WirePlumber 0.5, GTK 4.18).
# Native build + headless smoke test. Debian bullseye (the default runner
# image) has no libwireplumber-0.5 and a too-old GTK4, so this job runs in
# a debian:trixie container (PipeWire 1.4, WirePlumber 0.5, GTK 4.18).
# The container has no Node, so actions/checkout cannot run; clone with git.
native:
runs-on: depot-ubuntu-24.04-4
runs-on: ubuntu-latest
container:
image: debian:trixie
timeout-minutes: 30
steps:
- name: Install build and test dependencies
run: |
@@ -50,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:
-5
View File
@@ -1,5 +0,0 @@
---
type: fix
---
Smoother wheel and touchpad scrolling: scrolling the stream and device lists no longer stops (or changes a volume) when a slider passes under the pointer, and a wheel over a resting pointer changes the volume in fine 2% steps (high-resolution and tilt wheels included) instead of 10% jumps; touchpad swipes are routed by direction.
-5
View File
@@ -1,5 +0,0 @@
---
type: feature
---
Overhaul icons with bundled Lucide symbolic vectors, soft rounded icon tiles, redesigned mixer-fader app icon, and read-only host app icons in the OCI container.
-52
View File
@@ -1,52 +0,0 @@
# GTK >= 4.20 avoids linux-dmabuf v6 startup crashes on modern compositors.
ARG BASE_IMAGE=docker.io/library/ubuntu:26.04
FROM ${BASE_IMAGE} AS build
ARG MOONBIT_VERSION=latest
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
ca-certificates curl build-essential pkg-config \
libpipewire-0.3-dev libwireplumber-0.5-dev libgtk-4-dev \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSL --retry 5 https://cli.moonbitlang.com/install/unix.sh -o /tmp/moonbit-install.sh \
&& bash /tmp/moonbit-install.sh "$MOONBIT_VERSION" \
&& rm /tmp/moonbit-install.sh
ENV PATH="/root/.moon/bin:${PATH}"
WORKDIR /src
COPY moon.mod ./
COPY cmd/ cmd/
COPY model/ model/
COPY wp/ wp/
COPY gtk/ gtk/
COPY tools/pkg-cc tools/pkg-ar tools/
RUN moon build --target native --release \
&& install -Dm755 _build/native/release/build/cmd/moonmix/moonmix.exe /out/usr/local/bin/moonmix \
&& install -Dm755 _build/native/release/build/cmd/moonmix-probe/moonmix-probe.exe /out/usr/local/bin/moonmix-probe
FROM ${BASE_IMAGE}
LABEL org.opencontainers.image.title="moonmix" \
org.opencontainers.image.description="GTK4 volume control for the host PipeWire session" \
org.opencontainers.image.source="https://git.site.latha.org/geordi/moonmix"
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
libgtk-4-1 libwireplumber-0.5-0 pipewire-bin \
libpipewire-0.3-modules libspa-0.2-modules \
librsvg2-common adwaita-icon-theme fonts-dejavu-core \
&& rm -rf /var/lib/apt/lists/* \
&& test -r /usr/share/pipewire/client.conf
COPY --from=build /out/ /
COPY data/org.latha.moonmix.desktop /usr/share/applications/org.latha.moonmix.desktop
COPY data/icons/hicolor/ /usr/share/icons/hicolor/
COPY data/icons/LICENSE.lucide /usr/share/doc/moonmix/LICENSE.lucide
COPY --chmod=755 tools/container-entrypoint /usr/local/bin/moonmix-entrypoint
RUN gtk-update-icon-cache -f -t /usr/share/icons/hicolor
# Software rendering needs neither host GPU devices nor matching GPU drivers.
ENV GDK_BACKEND=wayland GSK_RENDERER=cairo HOME=/tmp XDG_RUNTIME_DIR=/tmp/moonmix-runtime
# Do not select an icon theme advertised by the host but absent from the image.
ENV MOONMIX_ICON_THEME=Adwaita
USER 65532:65532
ENTRYPOINT ["/usr/local/bin/moonmix-entrypoint"]
CMD ["/usr/local/bin/moonmix"]
+28 -159
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)
@@ -35,14 +31,6 @@ on top of libpipewire-0.3. It never runs `wpctl`, `pactl`, `pw-cli`,
- 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.
- **Scrolling that does what you mean.** The mouse wheel scrolls the list
even when a slider passes under the pointer; with the pointer resting on a
slider it changes that volume by 2% per detent (high-resolution wheels in
proportion, a tilt wheel too). On a touchpad a vertical swipe always
scrolls the list, with kinetic momentum, and a horizontal swipe over a
slider moves its knob with your fingers.
- **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.
@@ -90,8 +78,7 @@ flowchart LR
- **One main loop.** WirePlumber and GTK4 both run on the default GLib main
context, so events arrive on the GUI thread with no locking or polling.
- **Pure core.** Everything else is plain MoonBit in `model/`: the cubic and
linear conversions, dB formatting, linked-slider scaling, wheel routing
over sliders, the reducer that
linear conversions, dB formatting, linked-slider scaling, the reducer that
applies node, link and default events, the per-tab rows, and the row diff
the GUI applies. `moon test` covers it on any target.
- **GTK binding.** It is hand-written and minimal. Each widget gets a tag
@@ -99,61 +86,10 @@ flowchart LR
single callback. While MoonBit updates widgets from the model, signals are
suppressed so model updates never echo back into PipeWire. For a short
time after the user moves a slider, remote updates to that slider are
ignored so it doesn't jump while being dragged. Sliders replace GtkRange's
scroll handling (10% per detent, swallowing every scroll) with one that
asks MoonBit synchronously whether the slider or the list gets the event.
## 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`.
ignored so it doesn't jump while being dragged.
## Building
### Task runner (optional)
With [just](https://just.systems) installed, run `just` to list the available
recipes:
```sh
just # show commands; does not build or install anything
just build # native release build
just run # build and run the native GUI
just test # portable model and container/desktop tests
just check # native type-check and MoonBit formatting check
just install # build and install the native app for your user
just container-install # build the OCI image and install its desktop launcher
just container-run # build and run the OCI image without installing it
```
There are also `fmt`, `probe`, `test-container` and `smoke [prefix]`
recipes. Native installation respects `XDG_DATA_HOME`; container recipes
respect `MOONMIX_IMAGE`. The equivalent commands and dependencies are
documented below.
### Dependencies
You need MoonBit (`curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash`,
@@ -183,94 +119,34 @@ install -Dm755 _build/native/release/build/cmd/moonmix/moonmix.exe ~/.local/bin/
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
install -Dm644 -t ~/.local/share/icons/hicolor/scalable/actions data/icons/hicolor/scalable/actions/moonmix-*.svg
gtk-update-icon-cache -f -t ~/.local/share/icons/hicolor # optional
```
The app icon is `org.latha.moonmix` (a dark-slate 2.5D mixer deck with a
crescent moon and stereo peak LEDs above three sky-blue faders), 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`.
### OCI container and desktop launcher (Wayland)
With **rootless Podman**, Python 3, a Wayland desktop and a running host
PipeWire session, no host MoonBit toolchain or audio/GTK development
packages are needed:
```sh
podman build --format=oci -t localhost/moonmix:latest .
python3 tools/install-container.py
~/.local/bin/moonmix-container
```
The multi-stage `Containerfile` builds a release executable, then installs
only runtime dependencies, icons and fonts in the final Ubuntu 26.04 LTS
image. Its GTK 4.22 avoids GTK 4.18's startup crash on compositors advertising
linux-dmabuf v6, including recent KDE Plasma. Set
`--build-arg MOONBIT_VERSION=<version>` to select a particular MoonBit
toolchain. The image stays local; it is not published to a registry.
The installer adds **moonmix** to the application menu, using an absolute
path to `~/.local/bin/moonmix-container`, and installs the app icons. It
replaces the per-user native `.desktop` entry, if present, but leaves the
native `~/.local/bin/moonmix` executable untouched. The installed runner
does not depend on this checkout. Rebuild the image after source changes;
set `MOONMIX_IMAGE` to run a different local tag.
The runner maps your user ID and mounts only the Wayland and PipeWire
sockets (including `PIPEWIRE_RUNTIME_DIR` / `PIPEWIRE_REMOTE` overrides),
`$XDG_RUNTIME_DIR/bus` when present for desktop appearance settings, and
whichever standard host icon, pixmap and `.desktop` directories exist
(`/usr/share/{icons,pixmaps,applications}`, Flatpak exports and
`$XDG_DATA_HOME/{icons,applications}`) read-only under `/run/moonmix/host/`.
Setting `XDG_DATA_DIRS` inside the container lets GIO and `GtkIconTheme`
resolve full-colour host application icons (such as Firefox, Spotify or
Flatpaks) while bundled Lucide symbolic icons in `/usr/share/icons/hicolor`
remain used for devices and controls. It has no network, GPU devices,
home-directory mount or elevated privileges; the root filesystem is
read-only and temporary files disappear on exit. Software rendering avoids
depending on the host's GPU drivers. The image sets
`MOONMIX_ICON_THEME=Adwaita` so a host-only icon theme does not leave
symbolic fallback icons missing; native runs keep the desktop's icon theme.
This is packaging, **not a sandbox for untrusted apps**: the sockets still
grant access to your audio session, display and, when mounted, session
D-Bus. X11 sessions are not supported by this runner.
The image also includes `moonmix-probe` for diagnostics; run it with
`podman exec <running-container> moonmix-probe` to inspect the host audio
graph without changing it.
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
UI controls, tabs, devices and fallback streams use bundled crisp 24×24
[Lucide](https://lucide.dev) symbolic SVGs (`data/icons/hicolor/scalable/actions/moonmix-*.svg`,
under the ISC License — see [LICENSE.lucide](data/icons/LICENSE.lucide)),
which GTK4 recolours automatically to match light, dark and accent-tinted
surfaces, with standard freedesktop icon names as secondary fallbacks.
Row icons sit inside a 36×36 px soft rounded tile (20 px for symbolic icons,
26 px for full-colour app icons, and accent-tinted for the default device);
button and tab icons are 16 px.
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`:
The chains are chosen in `model/icons.mbt` and tested with `moon test`;
the GTK layer checks `has_icon` (or `"file:<path>"` for absolute icon paths):
- **Devices**: bundled `moonmix-device-*-symbolic` icons matched from
`device.form-factor` (speaker, headphones, headset, microphone, webcam,
phone, tv/hdmi display), HDMI/DisplayPort/webcam/Bluetooth/USB hints and
sink/source direction, falling back to freedesktop names (`audio-card-symbolic`,
`audio-x-generic-symbolic`).
- **Streams**: full-colour application icons first (`application.icon-name` /
`media.icon-name`, `.desktop` lookup via `GDesktopAppInfo` including `GFileIcon`
file paths, and direct theme names from `app_id` / binary), then any
symbolic hints, then `moonmix-device-mic-symbolic` for recording streams and
`moonmix-app-fallback-symbolic`.
- **Mute button & tabs**: `moonmix-volume-high/medium/low/muted-symbolic` and
`moonmix-tab-{playback,recording,output,input}-symbolic` (with freedesktop
fallbacks).
- **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
@@ -299,9 +175,7 @@ $P meter <id> # peak over ~1.5 s; exit 6 if silent
```sh
moon test --target wasm-gc # pure model tests, no libraries needed
moon check --target native # type-check everything
python3 tools/test-container.py # runner/desktop tests, no image build needed
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
@@ -310,16 +184,11 @@ microphone, one playback stream of noise and one capture stream created with `pw
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,
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 on Depot (`depot-ubuntu-24.04-4`) runners:
pure checks run directly on Ubuntu 24.04, and the native build and smoke test
run in a `debian:trixie` container because Ubuntu 24.04 only ships WirePlumber
0.4.
CI (`.gitea/workflows/ci.yaml`) runs the pure checks on the default runner.
It runs the native build and the smoke test in a `debian:trixie` container,
because bullseye has no WirePlumber 0.5.
## Releases
+33 -179
View File
@@ -15,7 +15,6 @@ extern "C" fn c_exit(code : Int32) = "exit"
/// Widgets of one row (a stream or a device).
struct RowView {
root : @gtk.Widget
icon_tile : @gtk.Widget
icon : @gtk.Widget
title : @gtk.Widget
subtitle : @gtk.Widget
@@ -56,12 +55,8 @@ struct App {
}
///|
/// Symbolic device / fallback icons render at 20 px inside a 36×36 soft tile;
/// full-colour application icons render larger at 26 px. Buttons use 16 px.
const ROW_SYMBOLIC_ICON_SIZE : Int32 = 20
///|
const ROW_APP_ICON_SIZE : Int32 = 26
/// Device / application icon in each row; buttons use 16 px icons.
const ROW_ICON_SIZE : Int32 = 32
///|
const METER_INTERVAL_MS : Int32 = 40
@@ -70,69 +65,19 @@ 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: 8px 12px; }
#|.mm-row { padding: 6px 12px; }
#|.mm-status { padding: 4px 8px; opacity: 0.8; font-size: smaller; }
#|.mm-icon-tile {
#| min-width: 36px;
#| min-height: 36px;
#| border-radius: 10px;
#| background-color: alpha(currentColor, 0.08);
#| box-shadow: inset 0 0 0 1px alpha(currentColor, 0.08);
#|}
#|.mm-icon-tile.mm-app-tile {
#| background-color: alpha(currentColor, 0.05);
#|}
#|.mm-icon-tile.mm-default-tile {
#| background-color: alpha(@theme_selected_bg_color, 0.14);
#| box-shadow: inset 0 0 0 1px alpha(@theme_selected_bg_color, 0.34);
#| color: @theme_selected_bg_color;
#|}
#|levelbar.mm-meter trough, levelbar.mm-meter block { min-height: 4px; }
#|levelbar.mm-meter { margin: 0 10px; }
///|
fn set_row_icon(
tile : @gtk.Widget,
icon : @gtk.Widget,
icons : Array[String],
) -> Unit {
let resolved = @gtk.resolve_icon(icons)
let sym = @model.is_symbolic_icon(resolved)
icon.set_icon(resolved)
icon.set_pixel_size(
if sym {
ROW_SYMBOLIC_ICON_SIZE
} else {
ROW_APP_ICON_SIZE
},
)
if sym {
icon.remove_css_class("mm-icon-app")
tile.remove_css_class("mm-app-tile")
} else {
icon.add_css_class("mm-icon-app")
tile.add_css_class("mm-app-tile")
}
}
///|
fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
let id = row.id
let tags = []
let root = @gtk.vbox(4)
root.add_css_class("mm-row")
let header = @gtk.hbox(10)
let icon_tile = @gtk.hbox(0)
icon_tile.add_css_class("mm-icon-tile")
icon_tile.set_hexpand(false)
icon_tile.set_vexpand(false)
icon_tile.set_valign_center()
let icon = @gtk.image("", ROW_SYMBOLIC_ICON_SIZE)
icon.set_hexpand(true)
icon.set_vexpand(true)
icon.set_halign_center()
icon.set_valign_center()
icon_tile.append(icon)
let header = @gtk.hbox(8)
let icon = @gtk.image(@gtk.resolve_icon(row.icons), ROW_ICON_SIZE)
let texts = @gtk.vbox(0)
texts.set_hexpand(true)
texts.set_valign_center()
@@ -142,7 +87,7 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
subtitle.add_css_class("mm-subtitle")
texts.append(title)
texts.append(subtitle)
header.append(icon_tile)
header.append(icon)
header.append(texts)
// Streams: device selector. Devices: "default" toggle.
@@ -189,15 +134,13 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
)
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(@model.volume_icon_chain(row.percent, row.mute)),
@gtk.resolve_icon([row.volume_icon, "audio-volume-high"]),
"",
fn(on) { let _ = @wp.set_mute(id, on) },
)
@@ -208,44 +151,19 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
let slider_row = @gtk.hbox(8)
let volume_label = @gtk.label(row.volume_text)
volume_label.set_width_chars(16)
// Wheel/touchpad over the slider: see @model.SliderWheel.
let wheel = @model.SliderWheel::new()
let (scale, scale_tag) = @gtk.scale(
@model.MAX_PERCENT,
@model.NORM_PERCENT,
fn(percent) {
match app.find_view(tab, id) {
Some(v) => {
let vols = @model.scale_linked(v.row.volumes, percent)
v.last_local_us = @gtk.now_us()
v.volume_label.set_text(@model.format_volume(vols))
let _ = @wp.set_volumes(id, vols)
}
None => ()
let (scale, scale_tag) = @gtk.scale(@model.MAX_PERCENT, @model.NORM_PERCENT, fn(
percent,
) {
match app.find_view(tab, id) {
Some(v) => {
let vols = @model.scale_linked(v.row.volumes, percent)
v.last_local_us = @gtk.now_us()
v.volume_label.set_text(@model.format_volume(vols))
let _ = @wp.set_volumes(id, vols)
}
},
on_scroll=fn(ev) {
match ev.phase {
Begin | End => {
wheel.reset()
None
}
Scroll =>
wheel.scroll(
if ev.pixels {
Pixels
} else {
Wheel
},
ev.dx,
ev.dy,
ev.since_list_us,
ev.value,
ev.extent,
)
}
},
)
None => ()
}
})
tags.push(scale_tag)
// Peak meter under the slider, as wide as it.
let meter = @gtk.level_bar()
@@ -260,7 +178,6 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
root.append(slider_row)
let view = {
root,
icon_tile,
icon,
title,
subtitle,
@@ -293,14 +210,7 @@ fn apply_row(view : RowView, row : @model.Row, force~ : Bool = false) -> Unit {
view.subtitle.set_visible(row.subtitle != "")
}
if force || old.icons != row.icons {
set_row_icon(view.icon_tile, view.icon, row.icons)
}
if force || old.is_default != row.is_default {
if row.is_default {
view.icon_tile.add_css_class("mm-default-tile")
} else {
view.icon_tile.remove_css_class("mm-default-tile")
}
view.icon.set_icon(@gtk.resolve_icon(row.icons))
}
view.scale.set_sensitive(row.has_volume)
if force || @model.should_apply_remote(view.last_local_us, @gtk.now_us()) {
@@ -308,11 +218,9 @@ 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)
if force || old.volume_icon != row.volume_icon {
view.mute.set_button_icon(
@gtk.resolve_icon(@model.volume_icon_chain(row.percent, row.mute)),
)
}
view.mute.set_button_icon(
@gtk.resolve_icon([row.volume_icon, "audio-volume-high"]),
)
match view.default_btn {
Some(b) => b.set_active(row.is_default)
None => ()
@@ -534,7 +442,11 @@ fn build_ui() -> App {
nb.append_page(
@gtk.scrolled(list),
tab.label(),
icon=@gtk.resolve_icon(tab.icon_chain()),
icon=@gtk.resolve_icon([
tab.icon(),
"audio-card-symbolic",
"audio-x-generic",
]),
)
tabs.push({ tab, list, empty, views: Map([]), rows: [], })
}
@@ -558,52 +470,10 @@ fn build_ui() -> App {
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" }}")
}
})
}
///|
/// 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
@@ -634,19 +504,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) })
}
///|
@@ -660,11 +518,6 @@ 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() {
@@ -672,8 +525,9 @@ fn main {
}
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()
}
-43
View File
@@ -1,43 +0,0 @@
ISC License
Copyright (c) 2026 Lucide Icons and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---
The following Lucide icons are derived from the Feather project:
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
The MIT License (MIT) (for the icons listed above)
Copyright (c) 2013-present Cole Bemis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M2 13a2 2 0 0 0 2-2V7a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0V4a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0v-4a2 2 0 0 1 2-2"/>
</svg>

Before

Width:  |  Height:  |  Size: 386 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M20 6 9 17l-5-5"/>
</svg>

Before

Width:  |  Height:  |  Size: 299 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M10 5H3"/><path class="transparent-fill foreground-stroke" d="M12 19H3"/><path class="transparent-fill foreground-stroke" d="M14 3v4"/><path class="transparent-fill foreground-stroke" d="M16 17v4"/><path class="transparent-fill foreground-stroke" d="M21 12h-9"/><path class="transparent-fill foreground-stroke" d="M21 19h-5"/><path class="transparent-fill foreground-stroke" d="M21 5h-7"/><path class="transparent-fill foreground-stroke" d="M8 10v4"/><path class="transparent-fill foreground-stroke" d="M8 12H3"/>
</svg>

Before

Width:  |  Height:  |  Size: 794 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="m7 7 10 10-5 5V2l5 5L7 17"/>
</svg>

Before

Width:  |  Height:  |  Size: 309 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<rect class="transparent-fill foreground-stroke" width="20" height="14" x="2" y="3" rx="2"/><line class="transparent-fill foreground-stroke" x1="8" x2="16" y1="21" y2="21"/><line class="transparent-fill foreground-stroke" x1="12" x2="12" y1="17" y2="21"/>
</svg>

Before

Width:  |  Height:  |  Size: 484 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"/>
</svg>

Before

Width:  |  Height:  |  Size: 407 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M3 11h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Zm0 0a9 9 0 1 1 18 0m0 0v5a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3Z"/><path class="transparent-fill foreground-stroke" d="M21 16v2a4 4 0 0 1-4 4h-5"/>
</svg>

Before

Width:  |  Height:  |  Size: 497 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M12 19v3"/><path class="transparent-fill foreground-stroke" d="M19 10v2a7 7 0 0 1-14 0v-2"/><rect class="transparent-fill foreground-stroke" x="9" y="2" width="6" height="13" rx="3"/>
</svg>

Before

Width:  |  Height:  |  Size: 464 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<rect class="transparent-fill foreground-stroke" width="14" height="20" x="5" y="2" rx="2" ry="2"/><path class="transparent-fill foreground-stroke" d="M12 18h.01"/>
</svg>

Before

Width:  |  Height:  |  Size: 393 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<rect class="transparent-fill foreground-stroke" width="16" height="20" x="4" y="2" rx="2"/><path class="transparent-fill foreground-stroke" d="M12 6h.01"/><circle class="transparent-fill foreground-stroke" cx="12" cy="14" r="4"/><path class="transparent-fill foreground-stroke" d="M12 14h.01"/>
</svg>

Before

Width:  |  Height:  |  Size: 524 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<circle class="transparent-fill foreground-stroke" cx="10" cy="7" r="1"/><circle class="transparent-fill foreground-stroke" cx="4" cy="20" r="1"/><path class="transparent-fill foreground-stroke" d="M4.7 19.3 19 5"/><path class="transparent-fill foreground-stroke" d="m21 3-3 1 2 2Z"/><path class="transparent-fill foreground-stroke" d="M9.26 7.68 5 12l2 5"/><path class="transparent-fill foreground-stroke" d="m10 14 5 2 3.5-3.5"/><path class="transparent-fill foreground-stroke" d="m18 12 1-1 1 1-1 1Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 734 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<circle class="transparent-fill foreground-stroke" cx="12" cy="10" r="8"/><circle class="transparent-fill foreground-stroke" cx="12" cy="10" r="3"/><path class="transparent-fill foreground-stroke" d="M7 22h10"/><path class="transparent-fill foreground-stroke" d="M12 22v-4"/>
</svg>

Before

Width:  |  Height:  |  Size: 504 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M12 19v3"/><path class="transparent-fill foreground-stroke" d="M19 10v2a7 7 0 0 1-14 0v-2"/><rect class="transparent-fill foreground-stroke" x="9" y="2" width="6" height="13" rx="3"/>
</svg>

Before

Width:  |  Height:  |  Size: 464 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<rect class="transparent-fill foreground-stroke" width="16" height="20" x="4" y="2" rx="2"/><path class="transparent-fill foreground-stroke" d="M12 6h.01"/><circle class="transparent-fill foreground-stroke" cx="12" cy="14" r="4"/><path class="transparent-fill foreground-stroke" d="M12 14h.01"/>
</svg>

Before

Width:  |  Height:  |  Size: 524 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M21 16V3a1 1 0 0 0-1.28-.96l-10 2.917a1 1 0 0 0-.72.96V19"/><circle class="transparent-fill foreground-stroke" cx="18" cy="16" r="3"/><circle class="transparent-fill foreground-stroke" cx="6" cy="19" r="3"/>
</svg>

Before

Width:  |  Height:  |  Size: 488 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M16.247 7.761a6 6 0 0 1 0 8.478"/><path class="transparent-fill foreground-stroke" d="M19.075 4.933a10 10 0 0 1 0 14.134"/><path class="transparent-fill foreground-stroke" d="M4.925 19.067a10 10 0 0 1 0-14.134"/><path class="transparent-fill foreground-stroke" d="M7.753 16.239a6 6 0 0 1 0-8.478"/><circle class="transparent-fill foreground-stroke" cx="12" cy="12" r="2"/>
</svg>

Before

Width:  |  Height:  |  Size: 653 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path class="transparent-fill foreground-stroke" d="M16 9a5 5 0 0 1 0 6"/><path class="transparent-fill foreground-stroke" d="M19.364 18.364a9 9 0 0 0 0-12.728"/>
</svg>

Before

Width:  |  Height:  |  Size: 614 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/>
</svg>

Before

Width:  |  Height:  |  Size: 452 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path class="transparent-fill foreground-stroke" d="M16 9a5 5 0 0 1 0 6"/>
</svg>

Before

Width:  |  Height:  |  Size: 526 B

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#2e3436" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path class="transparent-fill foreground-stroke" d="M11 4.702a.7.7 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.7.7 0 0 0 11 19.298z"/><path class="transparent-fill foreground-stroke" d="m16.5 14.5 5-5"/><path class="transparent-fill foreground-stroke" d="m16.5 9.5 5 5"/>
</svg>

Before

Width:  |  Height:  |  Size: 581 B

@@ -1,122 +1,18 @@
<?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="edge" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#2c3144"/>
<stop offset="0.1" stop-color="#171a25"/>
<stop offset="0.5" stop-color="#131620"/>
<stop offset="0.9" stop-color="#171a25"/>
<stop offset="1" stop-color="#2a2f42"/>
</linearGradient>
<linearGradient id="face" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#414860"/>
<stop offset="0.5" stop-color="#2d3244"/>
<stop offset="1" stop-color="#222635"/>
</linearGradient>
<linearGradient id="rim" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ffffff" stop-opacity="0.34"/>
<stop offset="0.24" stop-color="#ffffff" stop-opacity="0.03"/>
<stop offset="0.88" stop-color="#000000" stop-opacity="0.08"/>
<stop offset="1" stop-color="#000000" stop-opacity="0.32"/>
</linearGradient>
<linearGradient id="screen" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#090c14"/>
<stop offset="1" stop-color="#131929"/>
</linearGradient>
<radialGradient id="moon-bloom" cx="50%" cy="50%" r="50%">
<stop offset="0" stop-color="#f8d26a" stop-opacity="0.32"/>
<stop offset="1" stop-color="#f8d26a" stop-opacity="0"/>
</radialGradient>
<linearGradient id="moon" x1="0.1" y1="0" x2="0.9" y2="1">
<stop offset="0" stop-color="#fff8dd"/>
<stop offset="0.55" stop-color="#f9d267"/>
<stop offset="1" stop-color="#df9a20"/>
</linearGradient>
<linearGradient id="glass" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#ffffff" stop-opacity="0.11"/>
<stop offset="0.55" stop-color="#ffffff" stop-opacity="0.02"/>
<stop offset="1" stop-color="#ffffff" stop-opacity="0"/>
</linearGradient>
<linearGradient id="track" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#76d0ff"/>
<stop offset="0.45" stop-color="#3c92f0"/>
<stop offset="1" stop-color="#2668cc"/>
</linearGradient>
<linearGradient id="cap" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ffffff"/>
<stop offset="0.18" stop-color="#eef2f8"/>
<stop offset="0.46" stop-color="#cdd4e2"/>
<stop offset="0.54" stop-color="#b7c0d2"/>
<stop offset="0.86" stop-color="#e3e8f2"/>
<stop offset="1" stop-color="#cbd2e0"/>
<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>
<!-- Extruded 2.5D mixer console chassis -->
<rect x="14" y="20" width="100" height="98" rx="18" fill="url(#edge)"/>
<rect x="14" y="10" width="100" height="100" rx="18" fill="url(#face)"/>
<rect x="14.75" y="10.75" width="98.5" height="98.5" rx="17.25" fill="none" stroke="url(#rim)" stroke-width="1.5"/>
<!-- Recessed OLED display window -->
<rect x="23" y="19.5" width="82" height="27" rx="8" fill="#06080f" opacity="0.55"/>
<rect x="23.5" y="20" width="81" height="26" rx="7.5" fill="url(#screen)"/>
<path d="M 31 46.4 L 97 46.4" stroke="#ffffff" stroke-opacity="0.16" stroke-width="1" stroke-linecap="round"/>
<!-- Backlit crescent moon -->
<circle cx="38.5" cy="33" r="11" fill="url(#moon-bloom)"/>
<path d="M 41.6 26.4 A 7.1 7.1 0 1 0 41.6 39.6 A 5.6 5.6 0 1 1 41.6 26.4 Z" fill="url(#moon)"/>
<!-- Stereo peak-meter LEDs -->
<rect x="52" y="26.5" width="7.2" height="4.8" rx="1.5" fill="#34d399"/>
<rect x="61.2" y="26.5" width="7.2" height="4.8" rx="1.5" fill="#34d399"/>
<rect x="70.4" y="26.5" width="7.2" height="4.8" rx="1.5" fill="#38bdf8"/>
<rect x="79.6" y="26.5" width="7.2" height="4.8" rx="1.5" fill="#f7be42"/>
<rect x="88.8" y="26.5" width="7.2" height="4.8" rx="1.5" fill="#232b40"/>
<rect x="52" y="34.5" width="7.2" height="4.8" rx="1.5" fill="#34d399"/>
<rect x="61.2" y="34.5" width="7.2" height="4.8" rx="1.5" fill="#34d399"/>
<rect x="70.4" y="34.5" width="7.2" height="4.8" rx="1.5" fill="#38bdf8"/>
<rect x="79.6" y="34.5" width="7.2" height="4.8" rx="1.5" fill="#232b40"/>
<rect x="88.8" y="34.5" width="7.2" height="4.8" rx="1.5" fill="#232b40"/>
<!-- Subtle glass reflection -->
<path d="M 31 20 H 97 A 7.5 7.5 0 0 1 104.5 27.5 V 30 L 68 20 Z" fill="url(#glass)"/>
<!-- Etched dB scale ticks -->
<g stroke="#ffffff" stroke-opacity="0.17" stroke-width="1.2" stroke-linecap="round">
<line x1="23.5" y1="61" x2="26.5" y2="61"/>
<line x1="23.5" y1="76" x2="26.5" y2="76"/>
<line x1="23.5" y1="91" x2="26.5" y2="91"/>
<line x1="101.5" y1="61" x2="104.5" y2="61"/>
<line x1="101.5" y1="76" x2="104.5" y2="76"/>
<line x1="101.5" y1="91" x2="104.5" y2="91"/>
</g>
<!-- Recessed fader troughs -->
<rect x="33.5" y="53" width="7.5" height="48" rx="3.75" fill="#0b0e16" stroke="#ffffff" stroke-opacity="0.07" stroke-width="0.8"/>
<rect x="60.25" y="53" width="7.5" height="48" rx="3.75" fill="#0b0e16" stroke="#ffffff" stroke-opacity="0.07" stroke-width="0.8"/>
<rect x="87" y="53" width="7.5" height="48" rx="3.75" fill="#0b0e16" stroke="#ffffff" stroke-opacity="0.07" stroke-width="0.8"/>
<!-- Illuminated sky-blue level fills -->
<rect x="33.5" y="75" width="7.5" height="26" rx="3.75" fill="url(#track)"/>
<rect x="60.25" y="64" width="7.5" height="37" rx="3.75" fill="url(#track)"/>
<rect x="87" y="84" width="7.5" height="17" rx="3.75" fill="url(#track)"/>
<!-- Left fader cap -->
<rect x="26.25" y="71.8" width="22" height="13.5" rx="3.5" fill="#06080e" opacity="0.58"/>
<rect x="26.25" y="69" width="22" height="13.5" rx="3.5" fill="url(#cap)"/>
<rect x="29.25" y="74.8" width="16" height="1.6" rx="0.8" fill="#1d2233" opacity="0.72"/>
<rect x="29.25" y="76.4" width="16" height="0.8" rx="0.4" fill="#ffffff" opacity="0.7"/>
<!-- Center fader cap -->
<rect x="53" y="60.8" width="22" height="13.5" rx="3.5" fill="#06080e" opacity="0.58"/>
<rect x="53" y="58" width="22" height="13.5" rx="3.5" fill="url(#cap)"/>
<rect x="56" y="63.8" width="16" height="1.6" rx="0.8" fill="#1d2233" opacity="0.72"/>
<rect x="56" y="65.4" width="16" height="0.8" rx="0.4" fill="#ffffff" opacity="0.7"/>
<!-- Right fader cap -->
<rect x="79.75" y="80.8" width="22" height="13.5" rx="3.5" fill="#06080e" opacity="0.58"/>
<rect x="79.75" y="78" width="22" height="13.5" rx="3.5" fill="url(#cap)"/>
<rect x="82.75" y="83.8" width="16" height="1.6" rx="0.8" fill="#1d2233" opacity="0.72"/>
<rect x="82.75" y="85.4" width="16" height="0.8" rx="0.4" fill="#ffffff" opacity="0.7"/>
<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: 6.4 KiB

After

Width:  |  Height:  |  Size: 947 B

@@ -1,17 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Console housing frame (pure filled path for clean GTK symbolic recolouring) -->
<path fill="#2e3436" fill-rule="evenodd" d="M 3.75 0.55 H 12.25 A 3.2 3.2 0 0 1 15.45 3.75 V 12.25 A 3.2 3.2 0 0 1 12.25 15.45 H 3.75 A 3.2 3.2 0 0 1 0.55 12.25 V 3.75 A 3.2 3.2 0 0 1 3.75 0.55 Z M 3.75 1.95 A 1.8 1.8 0 0 0 1.95 3.75 V 12.25 A 1.8 1.8 0 0 0 3.75 14.05 H 12.25 A 1.8 1.8 0 0 0 14.05 12.25 V 3.75 A 1.8 1.8 0 0 0 12.25 1.95 Z"/>
<!-- Crescent moon and stereo meter bars -->
<path d="M 6.0 3.2 A 1.75 1.75 0 1 0 6.0 6.4 A 1.35 1.35 0 1 1 6.0 3.2 Z" fill="#2e3436"/>
<rect x="7.8" y="3.5" width="4.5" height="1.1" rx="0.55" fill="#2e3436" opacity="0.65"/>
<rect x="7.8" y="5.1" width="3.2" height="1.1" rx="0.55" fill="#2e3436" opacity="0.45"/>
<!-- Three fader tracks -->
<rect x="3.9" y="7.8" width="1.2" height="5" rx="0.6" fill="#2e3436" opacity="0.45"/>
<rect x="7.4" y="7.8" width="1.2" height="5" rx="0.6" fill="#2e3436" opacity="0.45"/>
<rect x="10.9" y="7.8" width="1.2" height="5" rx="0.6" fill="#2e3436" opacity="0.45"/>
<!-- Staggered fader caps -->
<rect x="3.0" y="9.4" width="3.0" height="1.8" rx="0.7" fill="#2e3436"/>
<rect x="6.5" y="8.0" width="3.0" height="1.8" rx="0.7" fill="#2e3436"/>
<rect x="10.0" y="10.6" width="3.0" height="1.8" rx="0.7" fill="#2e3436"/>
<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: 1.4 KiB

After

Width:  |  Height:  |  Size: 609 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 40 KiB

+2 -183
View File
@@ -11,24 +11,6 @@ extern "C" fn ffi_set_handler(
closure : (Int32, Double) -> Unit,
) = "mm_gtk_set_handler"
///|
extern "C" fn ffi_set_scroll_handler(
call : FuncRef[
(
(Int32, Int32, Int32, Double, Double, Int64, Double, Double) -> Double,
Int32,
Int32,
Int32,
Double,
Double,
Int64,
Double,
Double,
) -> Double,
],
closure : (Int32, Int32, Int32, Double, Double, Int64, Double, Double) -> Double,
) = "mm_gtk_set_scroll_handler"
///|
extern "C" fn ffi_init() -> Int32 = "mm_gtk_init"
@@ -128,9 +110,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"
///|
extern "C" fn ffi_image_set_pixel_size(img : Widget, size : Int32) = "mm_gtk_image_set_pixel_size"
///|
#borrow(name)
extern "C" fn ffi_has_icon(name : Bytes) -> Int32 = "mm_gtk_has_icon"
@@ -190,10 +169,6 @@ extern "C" fn ffi_set_margins(w : Widget, m : Int32) = "mm_gtk_widget_set_margin
#borrow(cls)
extern "C" fn ffi_add_css_class(w : Widget, cls : Bytes) = "mm_gtk_widget_add_css_class"
///|
#borrow(cls)
extern "C" fn ffi_remove_css_class(w : Widget, cls : Bytes) = "mm_gtk_widget_remove_css_class"
///|
extern "C" fn ffi_set_visible(w : Widget, v : Int32) = "mm_gtk_widget_set_visible"
@@ -203,12 +178,6 @@ extern "C" fn ffi_set_sensitive(w : Widget, v : Int32) = "mm_gtk_widget_set_sens
///|
extern "C" fn ffi_set_valign_center(w : Widget) = "mm_gtk_widget_set_valign_center"
///|
extern "C" fn ffi_set_halign_center(w : Widget) = "mm_gtk_widget_set_halign_center"
///|
extern "C" fn ffi_set_vexpand(w : Widget, v : Int32) = "mm_gtk_widget_set_vexpand"
///|
#borrow(path)
extern "C" fn ffi_save_png(w : Widget, path : Bytes) -> Int32 = "mm_gtk_save_png"
@@ -218,10 +187,6 @@ extern "C" fn ffi_save_png(w : Widget, path : Bytes) -> Int32 = "mm_gtk_save_png
///|
let handlers : Map[Int32, (Double) -> Unit] = Map([])
///|
/// Scroll handlers of sliders, by the slider's tag.
let scroll_handlers : Map[Int32, (ScrollEvent) -> Double?] = Map([])
///|
let next_tag : Ref[Int32] = { val: 1, }
@@ -238,35 +203,6 @@ fn install_dispatch() -> Unit {
None => ()
}
})
ffi_set_scroll_handler(
fn(g, tag, phase, unit, dx, dy, since, value, extent) {
g(tag, phase, unit, dx, dy, since, value, extent)
},
fn(tag, phase, unit, dx, dy, since, value, extent) {
match scroll_handlers.get(tag) {
Some(h) => {
let ev = {
phase: match phase {
0 => Begin
2 => End
_ => Scroll
},
pixels: unit == 1,
dx,
dy,
since_list_us: since,
value,
extent,
}
match h(ev) {
Some(v) => v
None => -1.0
}
}
None => -1.0
}
},
)
}
}
@@ -284,7 +220,6 @@ fn register(h : (Double) -> Unit) -> Int32 {
/// Forget a handler (when its widget is destroyed).
pub fn unregister(tag : Int32) -> Unit {
handlers.remove(tag)
scroll_handlers.remove(tag)
}
///|
@@ -351,68 +286,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,
@@ -525,52 +398,14 @@ pub fn Widget::set_icon(self : Widget, icon : String) -> Unit {
ffi_image_set_icon(self, cstr(icon))
}
///|
pub fn Widget::set_pixel_size(self : Widget, size : Int32) -> Unit {
ffi_image_set_pixel_size(self, size)
}
///|
#derive(Eq, Debug)
pub(all) enum ScrollPhase {
/// A scroll gesture (touchpad sequence) starts.
Begin
Scroll
/// The gesture ends.
End
}
///|
/// A scroll event over a slider.
pub(all) struct ScrollEvent {
phase : ScrollPhase
/// Deltas in surface pixels (touchpad), else in wheel detents.
pixels : Bool
/// Physical direction: dx > 0 right, dy > 0 down. 0 for Begin/End.
dx : Double
dy : Double
/// Microseconds since a list last scrolled.
since_list_us : Int64
/// The slider's value and width (px).
value : Double
extent : Double
}
///|
/// A slider from 0 to `max` with a mark at `norm`. Returns (widget, tag).
///
/// Scroll events over it go to `on_scroll`: it returns the slider's new
/// value (which then reaches `on_change`) to take the event, or `None` to
/// leave it to the scrolled list around the slider. By default sliders never
/// take scroll events.
pub fn scale(
max : Double,
norm : Double,
on_change : (Double) -> Unit,
on_scroll~ : (ScrollEvent) -> Double? = fn(_) { None },
) -> (Widget, Int32) {
let tag = register(on_change)
scroll_handlers.set(tag, on_scroll)
(ffi_scale_new(max, norm, tag), tag)
}
@@ -652,11 +487,6 @@ pub fn Widget::add_css_class(self : Widget, cls : String) -> Unit {
ffi_add_css_class(self, cstr(cls))
}
///|
pub fn Widget::remove_css_class(self : Widget, cls : String) -> Unit {
ffi_remove_css_class(self, cstr(cls))
}
///|
pub fn Widget::set_visible(self : Widget, v : Bool) -> Unit {
ffi_set_visible(self, int(v))
@@ -672,16 +502,6 @@ pub fn Widget::set_valign_center(self : Widget) -> Unit {
ffi_set_valign_center(self)
}
///|
pub fn Widget::set_halign_center(self : Widget) -> Unit {
ffi_set_halign_center(self)
}
///|
pub fn Widget::set_vexpand(self : Widget, v : Bool) -> Unit {
ffi_set_vexpand(self, int(v))
}
///|
/// Render the widget offscreen to a PNG file (for headless screenshots).
pub fn Widget::save_png(self : Widget, path : String) -> Bool {
@@ -703,9 +523,8 @@ pub fn app_icon(key : String) -> String {
///|
/// First entry of an icon chain (see @model.device_icon_chain) that the theme
/// has or that resolves on disk. "app:<key>" entries are looked up in the
/// .desktop files (and may resolve to a theme icon name or "file:<path>").
/// The last entry is returned if nothing matches, so the result is never empty.
/// 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:") {
+17 -425
View File
@@ -43,145 +43,47 @@ MOONBIT_FFI_EXPORT void mm_gtk_set_handler(mm_gcall_t call, void *closure) {
g_closure = closure;
}
/* Scroll events over sliders are decided synchronously by MoonBit:
* (tag, phase 0 begin / 1 scroll / 2 end, unit 0 wheel / 1 pixels, dx, dy,
* microseconds since the list last scrolled, slider value, slider width)
* -> new slider value, or < 0 to leave the event to the scrolled list. */
typedef double (*mm_scall_t)(void *closure, int32_t tag, int32_t phase,
int32_t unit, double dx, double dy,
int64_t since_list_us, double value,
double extent);
static mm_scall_t g_scroll_call;
static void *g_scroll_closure;
MOONBIT_FFI_EXPORT void mm_gtk_set_scroll_handler(mm_scall_t call,
void *closure) {
if (g_scroll_closure)
moonbit_decref(g_scroll_closure);
g_scroll_call = call;
g_scroll_closure = closure;
}
static void add_icon_search_path_if_new(GtkIconTheme *theme, const char *dir) {
if (!dir || !*dir)
return;
char **paths = gtk_icon_theme_get_search_path(theme);
int found = 0;
for (char **p = paths; p && *p; p++) {
if (strcmp(*p, dir) == 0) {
found = 1;
break;
}
}
g_strfreev(paths);
if (!found)
gtk_icon_theme_add_search_path(theme, dir);
}
static char *resolve_icon_file_path(const char *path) {
if (!path || !*path)
return NULL;
if (g_file_test(path, G_FILE_TEST_IS_REGULAR))
return g_strdup(path);
static const struct {
const char *host_prefix;
const char *container_prefix;
} remaps[] = {
{"/usr/share/pixmaps/", "/run/moonmix/host/usr/pixmaps/"},
{"/usr/share/icons/", "/run/moonmix/host/usr/icons/"},
{"/var/lib/flatpak/exports/share/icons/",
"/run/moonmix/host/flatpak-sys/icons/"},
};
for (size_t i = 0; i < sizeof(remaps) / sizeof(remaps[0]); i++) {
if (g_str_has_prefix(path, remaps[i].host_prefix)) {
const char *rest = path + strlen(remaps[i].host_prefix);
char *mapped = g_strconcat(remaps[i].container_prefix, rest, NULL);
if (g_file_test(mapped, G_FILE_TEST_IS_REGULAR))
return mapped;
g_free(mapped);
}
}
return NULL;
}
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;
/* A container may not ship the icon theme advertised by the host portal.
* Override only when requested; native installations keep the desktop theme. */
const char *icon_theme = g_getenv("MOONMIX_ICON_THEME");
if (icon_theme && *icon_theme)
g_object_set(gtk_settings_get_default(), "gtk-icon-theme-name", icon_theme, NULL);
/* Let an uninstalled checkout and standard local/container prefixes find
* bundled moonmix-* icons and host pixmaps. */
/* 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());
add_icon_search_path_if_new(theme, g_getenv("MOONMIX_ICON_DIR"));
add_icon_search_path_if_new(theme, "data/icons");
char *user_icons = g_build_filename(g_get_user_data_dir(), "icons", NULL);
add_icon_search_path_if_new(theme, user_icons);
g_free(user_icons);
add_icon_search_path_if_new(theme, "/usr/local/share/icons");
if (g_file_test("/run/moonmix/host/usr/pixmaps", G_FILE_TEST_IS_DIR))
add_icon_search_path_if_new(theme, "/run/moonmix/host/usr/pixmaps");
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` or a "file:<path>" icon exists. */
/* 1 if the icon theme has `name`. */
MOONBIT_FFI_EXPORT int32_t mm_gtk_has_icon(moonbit_bytes_t name) {
const char *n = s(name);
if (!n || !*n)
return 0;
if (g_str_has_prefix(n, "file:")) {
char *resolved = resolve_icon_file_path(n + 5);
int ok = resolved != NULL;
g_free(resolved);
return ok;
}
GdkDisplay *d = gdk_display_get_default();
if (!d)
return 0;
return gtk_icon_theme_has_icon(gtk_icon_theme_get_for_display(d), n);
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)
return 0;
if (G_IS_THEMED_ICON(icon)) {
if (icon && G_IS_THEMED_ICON(icon)) {
const char *const *names = g_themed_icon_get_names(G_THEMED_ICON(icon));
/* Prefer full-colour non-symbolic icons before falling back to -symbolic. */
for (int pass = 0; pass < 2; pass++) {
for (int i = 0; names && names[i]; i++) {
int is_sym = g_str_has_suffix(names[i], "-symbolic");
if ((pass == 0) == !is_sym &&
gtk_icon_theme_has_icon(theme, names[i])) {
*out = g_strdup(names[i]);
return 1;
}
for (int i = 0; names && names[i]; i++)
if (gtk_icon_theme_has_icon(theme, names[i])) {
*out = g_strdup(names[i]);
return 1;
}
}
} else if (G_IS_FILE_ICON(icon)) {
GFile *f = g_file_icon_get_file(G_FILE_ICON(icon));
char *path = f ? g_file_get_path(f) : NULL;
char *resolved = resolve_icon_file_path(path);
g_free(path);
if (resolved) {
*out = g_strconcat("file:", resolved, NULL);
g_free(resolved);
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 (or "file:<path>") if available. "" if none. */
* ("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;
@@ -213,7 +115,7 @@ MOONBIT_FFI_EXPORT moonbit_bytes_t mm_gtk_app_icon(moonbit_bytes_t key) {
}
}
size_t n = found ? strlen(found) : 0;
moonbit_bytes_t out = moonbit_make_bytes((int32_t)n, 0);
moonbit_bytes_t out = moonbit_make_bytes(n + 1, 0);
if (found)
memcpy(out, found, n);
g_free(found);
@@ -263,196 +165,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) {
@@ -509,25 +221,10 @@ MOONBIT_FFI_EXPORT void mm_gtk_box_reorder_after(GtkWidget *box,
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_null(void) { return NULL; }
/* When a list last moved (any scrolled window: only the visible tab's can
* move) or was handed a scroll event by a slider. */
static gint64 g_list_scrolled_us = G_MININT64 / 2;
static void on_list_scrolled(GtkAdjustment *adj, gpointer d) {
(void)adj;
(void)d;
g_list_scrolled_us = g_get_monotonic_time();
}
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_scrolled_new(GtkWidget *child) {
GtkWidget *sw = gtk_scrolled_window_new();
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw), GTK_POLICY_NEVER,
GTK_POLICY_AUTOMATIC);
/* Includes kinetic deceleration and scrollbar drags: while the list
* moves, wheel events over sliders keep scrolling it. */
g_signal_connect(
gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(sw)),
"value-changed", G_CALLBACK(on_list_scrolled), NULL);
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(sw), child);
gtk_widget_set_vexpand(sw, TRUE);
return sw;
@@ -589,40 +286,16 @@ MOONBIT_FFI_EXPORT void mm_gtk_label_set_width_chars(GtkWidget *l,
gtk_label_set_xalign(GTK_LABEL(l), 1.0f);
}
static void image_apply_icon(GtkImage *img, const char *icon) {
if (!icon || !*icon) {
gtk_image_clear(img);
return;
}
if (g_str_has_prefix(icon, "file:")) {
char *resolved = resolve_icon_file_path(icon + 5);
if (resolved) {
gtk_image_set_from_file(img, resolved);
g_free(resolved);
} else {
gtk_image_set_from_file(img, icon + 5);
}
} else {
gtk_image_set_from_icon_name(img, icon);
}
}
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_image_new(moonbit_bytes_t icon,
int32_t size) {
GtkWidget *img = gtk_image_new();
image_apply_icon(GTK_IMAGE(img), s(icon));
GtkWidget *img = gtk_image_new_from_icon_name(s(icon));
gtk_image_set_pixel_size(GTK_IMAGE(img), size);
return img;
}
MOONBIT_FFI_EXPORT void mm_gtk_image_set_icon(GtkWidget *img,
moonbit_bytes_t icon) {
image_apply_icon(GTK_IMAGE(img), s(icon));
}
MOONBIT_FFI_EXPORT void mm_gtk_image_set_pixel_size(GtkWidget *img,
int32_t size) {
gtk_image_set_pixel_size(GTK_IMAGE(img), size);
gtk_image_set_from_icon_name(GTK_IMAGE(img), s(icon));
}
static void on_value_changed(GtkRange *r, gpointer d) {
@@ -630,73 +303,6 @@ static void on_value_changed(GtkRange *r, gpointer d) {
emit(get_tag(r), gtk_range_get_value(r));
}
static double scale_scroll_call(GtkEventController *c, int32_t phase,
double dx, double dy) {
GtkWidget *sc = gtk_event_controller_get_widget(c);
if (!g_scroll_call)
return -1;
int32_t unit = gtk_event_controller_scroll_get_unit(
GTK_EVENT_CONTROLLER_SCROLL(c)) == GDK_SCROLL_UNIT_SURFACE;
moonbit_incref(g_scroll_closure);
return g_scroll_call(g_scroll_closure, get_tag(sc), phase, unit, dx, dy,
g_get_monotonic_time() - g_list_scrolled_us,
gtk_range_get_value(GTK_RANGE(sc)),
(double)gtk_widget_get_width(sc));
}
static void on_scale_scroll_begin(GtkEventControllerScroll *c, gpointer d) {
(void)d;
scale_scroll_call(GTK_EVENT_CONTROLLER(c), 0, 0, 0);
}
static void on_scale_scroll_end(GtkEventControllerScroll *c, gpointer d) {
(void)d;
scale_scroll_call(GTK_EVENT_CONTROLLER(c), 2, 0, 0);
}
static gboolean on_scale_scroll(GtkEventControllerScroll *c, double dx,
double dy, gpointer d) {
(void)d;
double v = scale_scroll_call(GTK_EVENT_CONTROLLER(c), 1, dx, dy);
if (v < 0) {
/* The scrolled window's own handler (further up) takes it. */
g_list_scrolled_us = g_get_monotonic_time();
return GDK_EVENT_PROPAGATE;
}
GtkRange *r =
GTK_RANGE(gtk_event_controller_get_widget(GTK_EVENT_CONTROLLER(c)));
if (v != gtk_range_get_value(r))
gtk_range_set_value(r, v); /* value-changed -> volume */
return GDK_EVENT_STOP;
}
/* GtkRange's built-in scroll handling moves by the page increment (10%) per
* wheel detent, ignores horizontal wheels and swallows every scroll event, so
* a list scrolled with the pointer over a slider stops and changes a volume.
* Replace it with one routed by @model.SliderWheel. */
static void scale_replace_scroll_controller(GtkWidget *sc) {
GListModel *controllers = gtk_widget_observe_controllers(sc);
for (guint i = g_list_model_get_n_items(controllers); i-- > 0;) {
GtkEventController *c = g_list_model_get_item(controllers, i);
if (GTK_IS_EVENT_CONTROLLER_SCROLL(c))
gtk_widget_remove_controller(sc, c);
g_object_unref(c);
}
g_object_unref(controllers);
GtkEventControllerScrollFlags flags = GTK_EVENT_CONTROLLER_SCROLL_BOTH_AXES;
#if GTK_CHECK_VERSION(4, 20, 0)
/* The knob follows the fingers whether or not natural scrolling is on. */
flags |= GTK_EVENT_CONTROLLER_SCROLL_PHYSICAL_DIRECTION;
#endif
GtkEventController *scroll = gtk_event_controller_scroll_new(flags);
g_signal_connect(scroll, "scroll-begin", G_CALLBACK(on_scale_scroll_begin),
NULL);
g_signal_connect(scroll, "scroll", G_CALLBACK(on_scale_scroll), NULL);
g_signal_connect(scroll, "scroll-end", G_CALLBACK(on_scale_scroll_end),
NULL);
gtk_widget_add_controller(sc, scroll);
}
/* Horizontal slider 0..max with a "100%" mark. */
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_scale_new(double max, double norm,
int32_t tag) {
@@ -708,7 +314,6 @@ MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_scale_new(double max, double norm,
gtk_widget_set_hexpand(sc, TRUE);
set_tag(sc, tag);
g_signal_connect(sc, "value-changed", G_CALLBACK(on_value_changed), NULL);
scale_replace_scroll_controller(sc);
return sc;
}
@@ -842,11 +447,6 @@ MOONBIT_FFI_EXPORT void mm_gtk_widget_add_css_class(GtkWidget *w,
gtk_widget_add_css_class(w, s(cls));
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_remove_css_class(GtkWidget *w,
moonbit_bytes_t cls) {
gtk_widget_remove_css_class(w, s(cls));
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_visible(GtkWidget *w, int32_t v) {
gtk_widget_set_visible(w, v != 0);
}
@@ -859,14 +459,6 @@ MOONBIT_FFI_EXPORT void mm_gtk_widget_set_valign_center(GtkWidget *w) {
gtk_widget_set_valign(w, GTK_ALIGN_CENTER);
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_halign_center(GtkWidget *w) {
gtk_widget_set_halign(w, GTK_ALIGN_CENTER);
}
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_vexpand(GtkWidget *w, int32_t v) {
gtk_widget_set_vexpand(w, v != 0);
}
/* ---- headless screenshots ------------------------------------------------ */
/* Render a realized widget (usually the window) to a PNG via GSK, without
+1 -39
View File
@@ -1,10 +1,6 @@
// Generated using `moon info`, DON'T EDIT IT
package "geordi/moonmix/gtk"
import {
"moonbitlang/core/debug",
}
// Values
pub fn app_icon(String) -> String
@@ -28,24 +24,18 @@ 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, on_scroll? : (ScrollEvent) -> Double?) -> (Widget, Int32)
pub fn scale(Double, Double, (Double) -> Unit) -> (Widget, Int32)
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)
@@ -56,35 +46,11 @@ 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
}
pub(all) struct ScrollEvent {
phase : ScrollPhase
pixels : Bool
dx : Double
dy : Double
since_list_us : Int64
value : Double
extent : Double
}
#derive(Eq, @debug.Debug)
pub(all) enum ScrollPhase {
Begin
Scroll
End
}
#external
pub type Widget
pub fn Widget::add_css_class(Self, String) -> Unit
@@ -92,26 +58,22 @@ pub fn Widget::append(Self, Self) -> Unit
pub fn Widget::append_page(Self, Self, String, icon? : String) -> Unit
pub fn Widget::present(Self) -> Unit
pub fn Widget::remove(Self, Self) -> Unit
pub fn Widget::remove_css_class(Self, String) -> Unit
pub fn Widget::reorder_after(Self, Self, Self?) -> Unit
pub fn Widget::save_png(Self, String) -> Bool
pub fn Widget::set_active(Self, Bool) -> Unit
pub fn Widget::set_button_icon(Self, String) -> Unit
pub fn Widget::set_child(Self, Self) -> Unit
pub fn Widget::set_halign_center(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_pixel_size(Self, Int32) -> Unit
pub fn Widget::set_sensitive(Self, Bool) -> Unit
pub fn Widget::set_text(Self, String) -> Unit
pub fn Widget::set_tooltip(Self, String) -> Unit
pub fn Widget::set_valign_center(Self) -> Unit
pub fn Widget::set_value(Self, Double) -> Unit
pub fn Widget::set_vexpand(Self, Bool) -> Unit
pub fn Widget::set_visible(Self, Bool) -> Unit
pub fn Widget::set_width_chars(Self, Int32) -> Unit
pub fn Widget::value(Self) -> Double
-70
View File
@@ -1,70 +0,0 @@
set shell := ["sh", "-eu", "-c"]
# List available recipes.
default:
@just --list
# Build the native release binaries.
build:
moon build --target native --release
# Build and run the native GUI.
run: build
./_build/native/release/build/cmd/moonmix/moonmix.exe
# Build and install the native app, desktop entry and icons for your user.
install: build
#!/bin/sh
set -eu
data_home=${XDG_DATA_HOME:-"$HOME/.local/share"}
install -Dm755 _build/native/release/build/cmd/moonmix/moonmix.exe "$HOME/.local/bin/moonmix"
install -Dm644 data/org.latha.moonmix.desktop "$data_home/applications/org.latha.moonmix.desktop"
install -Dm644 data/icons/hicolor/scalable/apps/org.latha.moonmix.svg "$data_home/icons/hicolor/scalable/apps/org.latha.moonmix.svg"
install -Dm644 data/icons/hicolor/symbolic/apps/org.latha.moonmix-symbolic.svg "$data_home/icons/hicolor/symbolic/apps/org.latha.moonmix-symbolic.svg"
install -Dm644 -t "$data_home/icons/hicolor/scalable/actions" data/icons/hicolor/scalable/actions/moonmix-*.svg
install -Dm644 data/icons/LICENSE.lucide "$data_home/doc/moonmix/LICENSE.lucide"
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
gtk-update-icon-cache -f -t "$data_home/icons/hicolor"
fi
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database "$data_home/applications"
fi
# Type-check all native packages and check MoonBit formatting.
check:
moon check --target native
moon fmt --check
# Format the MoonBit sources.
fmt:
moon fmt
# Run the portable model tests and container/desktop packaging tests.
test: test-container
moon test --target wasm-gc
# Test the container runner and installer without building an image.
test-container:
python3 tools/test-container.py
# Build and print the current audio graph without changing it.
probe: build
./_build/native/release/build/cmd/moonmix-probe/moonmix-probe.exe
# Build debug binaries and run the private audio/GUI smoke test.
smoke prefix="_build/screenshots/moonmix":
moon build --target native
mkdir -p "$(dirname -- {{ quote(prefix) }})"
tools/smoke-test.sh {{ quote(prefix) }}
# Build the local OCI image (override its tag with MOONMIX_IMAGE).
container-build:
podman build --format=oci -t "${MOONMIX_IMAGE:-localhost/moonmix:latest}" .
# Build and run the OCI image using the checkout's current launcher.
container-run: container-build
./tools/moonmix-container
# Build the OCI image and install its per-user desktop launcher.
container-install: container-build
python3 tools/install-container.py
-258
View File
@@ -1,258 +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}; }",
".mm-icon-tile.mm-default-tile { background-color: alpha(\{bg}, 0.16); box-shadow: inset 0 0 0 1px alpha(\{bg}, 0.36); color: \{text}; }",
"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
}
}
-121
View File
@@ -1,121 +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"))
assert_true(css.contains(".mm-icon-tile.mm-default-tile"))
// 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)
}
+31 -209
View File
@@ -5,21 +5,16 @@
//
// 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. Entries starting with `FILE_ICON_PREFIX` ("file:<path>")
// point to an icon file directly.
// launcher's icon.
///|
pub fn icon_fallback_device() -> Array[String] {
[
"moonmix-device-audio-symbolic", "audio-card-symbolic", "audio-x-generic-symbolic",
]
["audio-card-symbolic", "audio-x-generic-symbolic"]
}
///|
pub fn icon_fallback_stream() -> Array[String] {
[
"moonmix-app-fallback-symbolic", "application-x-executable-symbolic", "audio-x-generic-symbolic",
]
["application-x-executable-symbolic", "audio-x-generic-symbolic"]
}
///|
@@ -29,22 +24,10 @@ pub const ICON_MISSING : String = "image-missing"
///|
pub const APP_LOOKUP_PREFIX : String = "app:"
///|
pub const FILE_ICON_PREFIX : String = "file:"
///|
/// True if a resolved icon name or path is a symbolic monochrome asset.
pub fn is_symbolic_icon(name : String) -> Bool {
name == ICON_MISSING ||
name.has_suffix("-symbolic") ||
name.has_suffix("-symbolic.svg") ||
name.has_suffix("-symbolic.png")
}
///|
/// "Default" toggle: first icon the theme has.
pub fn default_button_icons() -> Array[String] {
["moonmix-default-symbolic", "emblem-ok-symbolic", "object-select-symbolic"]
["emblem-ok-symbolic", "object-select-symbolic", "emblem-default-symbolic"]
}
///|
@@ -81,61 +64,7 @@ fn has_any(haystack : String, needles : Array[String]) -> Bool {
}
///|
/// Bundled Lucide symbolic icon name for a `device.form-factor` value, "" if unknown.
pub fn bundled_form_factor_icon(
form_factor : String,
kind : NodeKind,
) -> String {
match form_factor {
"headphone" => "moonmix-device-headphones-symbolic"
"headset" => "moonmix-device-headset-symbolic"
"speaker" | "hifi" => "moonmix-device-speaker-symbolic"
"microphone" => "moonmix-device-mic-symbolic"
"webcam" => "moonmix-device-webcam-symbolic"
"handset" | "hands-free" | "portable" => "moonmix-device-phone-symbolic"
"tv" | "hdmi" | "computer" => "moonmix-device-display-symbolic"
"car" =>
if kind is Source {
"moonmix-device-mic-symbolic"
} else {
"moonmix-device-speaker-symbolic"
}
_ => ""
}
}
///|
/// Map a freedesktop/PipeWire device icon hint to one of our bundled Lucide icons.
fn bundled_hint_icon(hint : String) -> String {
let h = hint.to_lower()
if h.contains("headset") {
"moonmix-device-headset-symbolic"
} else if h.contains("headphone") {
"moonmix-device-headphones-symbolic"
} else if h.contains("webcam") || h.contains("camera") {
"moonmix-device-webcam-symbolic"
} else if h.contains("display") ||
h.contains("monitor") ||
h.contains("hdmi") ||
h.contains("tv") {
"moonmix-device-display-symbolic"
} else if h.contains("phone") {
"moonmix-device-phone-symbolic"
} else if h.contains("microphone") {
"moonmix-device-mic-symbolic"
} else if h.contains("speaker") {
"moonmix-device-speaker-symbolic"
} else if h.contains("bluetooth") {
"moonmix-device-bluetooth-symbolic"
} else if h.contains("usb") {
"moonmix-device-usb-symbolic"
} else {
""
}
}
///|
/// Standard freedesktop icon (without suffix) for a `device.form-factor` value, "" if unknown.
/// 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"
@@ -177,58 +106,26 @@ pub fn device_bus(n : Node) -> String {
}
///|
/// Icon chain for a sink or source: bundled crisp Lucide symbolic icons first,
/// keeping standard freedesktop names as secondary fallbacks.
/// Icon chain for a sink or source.
pub fn device_icon_chain(n : Node) -> Array[String] {
let kind = n.kind()
let out : Array[String] = []
let text = n.name + " " + n.description
let bus = device_bus(n)
let is_hdmi = has_any(text, ["hdmi", "displayport", "display port"])
let is_webcam = kind is Source &&
(
has_any(n.description, ["webcam", "camera"]) ||
(bus == "usb" && n.description.to_lower().contains("cam"))
)
// Phase 1: bundled Lucide symbolic icons
push_unique(out, bundled_form_factor_icon(n.form_factor, kind))
if is_hdmi {
push_unique(out, "moonmix-device-display-symbolic")
}
if is_webcam {
push_unique(out, "moonmix-device-webcam-symbolic")
}
for h in n.icon_hints {
push_unique(out, bundled_hint_icon(h))
}
if has_any(text, ["headset"]) {
push_unique(out, "moonmix-device-headset-symbolic")
}
if has_any(text, ["headphone", "earbud"]) {
push_unique(out, "moonmix-device-headphones-symbolic")
}
if bus == "bluetooth" {
push_unique(out, "moonmix-device-bluetooth-symbolic")
} else if bus == "usb" {
push_unique(out, "moonmix-device-usb-symbolic")
}
match kind {
Source => push_unique(out, "moonmix-device-mic-symbolic")
Sink => push_unique(out, "moonmix-device-speaker-symbolic")
_ => push_unique(out, "moonmix-device-audio-symbolic")
}
push_unique(out, "moonmix-device-audio-symbolic")
// Phase 2: freedesktop secondary fallbacks
// 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))
if is_hdmi {
let text = n.name + " " + n.description
if has_any(text, ["hdmi", "displayport", "display port"]) {
push_symbolic_first(out, "video-display")
}
if is_webcam {
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) {
@@ -236,10 +133,12 @@ pub fn device_icon_chain(n : Node) -> Array[String] {
("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)
}
@@ -248,56 +147,31 @@ pub fn device_icon_chain(n : Node) -> Array[String] {
}
///|
/// Icon chain for an application stream: prefer real full-colour host app
/// icons first (non-symbolic hints, .desktop lookup, direct binary/app_id),
/// then any symbolic hints, then crisp bundled fallbacks.
/// 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] = []
// 1. Non-symbolic icon hints (including absolute file paths).
for h in n.icon_hints {
if h.has_prefix("/") {
if !is_symbolic_icon(h) {
push_unique(out, FILE_ICON_PREFIX + h)
}
} else if !h.has_suffix("-symbolic") {
push_unique(out, h)
}
push_unique(out, h)
}
// 2. Installed .desktop lookup (prefers full-colour icons on the GTK side).
for key in [n.app_id, n.app_binary, n.app_name] {
if key != "" {
push_unique(out, APP_LOOKUP_PREFIX + key)
}
}
// 3. Direct non-symbolic icon-theme lookup by app id / binary / lower name.
for key in [n.app_id, n.app_binary, n.app_name.to_lower()] {
if key != "" &&
!key.contains(" ") &&
!key.contains("/") &&
!key.has_suffix("-symbolic") {
// Many apps ship an icon named after their binary or app id.
if key != "" && !key.contains(" ") && !key.contains("/") {
push_unique(out, key)
}
}
// 4. Symbolic hints only if no full-colour app icon was found.
for h in n.icon_hints {
if h.has_prefix("/") {
if is_symbolic_icon(h) {
push_unique(out, FILE_ICON_PREFIX + h)
}
} else if h.has_suffix("-symbolic") {
push_unique(out, h)
}
}
// 5-8. Record-stream mic, bundled fallback, freedesktop fallback, placeholder.
if n.kind() is RecordStream {
push_unique(out, "moonmix-device-mic-symbolic")
push_unique(out, "audio-input-microphone-symbolic")
}
for f in icon_fallback_stream() {
push_unique(out, f)
}
if n.kind() is RecordStream {
push_unique(out, "audio-input-microphone-symbolic")
}
push_unique(out, ICON_MISSING)
out
}
@@ -306,36 +180,13 @@ pub fn stream_icon_chain(n : Node) -> Array[String] {
/// 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 {
"moonmix-volume-muted-symbolic"
"audio-volume-muted-symbolic"
} else if percent < 34.0 {
"moonmix-volume-low-symbolic"
"audio-volume-low-symbolic"
} else if percent < 67.0 {
"moonmix-volume-medium-symbolic"
"audio-volume-medium-symbolic"
} else {
"moonmix-volume-high-symbolic"
}
}
///|
/// Volume icon resolution chain: bundled Lucide symbolic first, then
/// standard freedesktop fallbacks.
pub fn volume_icon_chain(percent : Double, mute : Bool) -> Array[String] {
if mute || percent <= 0.0 {
[
"moonmix-volume-muted-symbolic", "audio-volume-muted-symbolic", "audio-volume-muted",
]
} else if percent < 34.0 {
[
"moonmix-volume-low-symbolic", "audio-volume-low-symbolic", "audio-volume-low",
]
} else if percent < 67.0 {
[
"moonmix-volume-medium-symbolic", "audio-volume-medium-symbolic", "audio-volume-medium",
]
} else {
[
"moonmix-volume-high-symbolic", "audio-volume-high-symbolic", "audio-volume-high",
]
"audio-volume-high-symbolic"
}
}
@@ -343,36 +194,7 @@ pub fn volume_icon_chain(percent : Double, mute : Bool) -> Array[String] {
/// Small symbolic icon next to a tab's label.
pub fn Tab::icon(self : Tab) -> String {
match self {
Playback => "moonmix-tab-playback-symbolic"
Recording => "moonmix-tab-recording-symbolic"
OutputDevices => "moonmix-tab-output-symbolic"
InputDevices => "moonmix-tab-input-symbolic"
}
}
///|
/// Tab icon resolution chain: bundled Lucide symbolic first, then
/// standard freedesktop fallbacks.
pub fn Tab::icon_chain(self : Tab) -> Array[String] {
match self {
Playback =>
[
"moonmix-tab-playback-symbolic", "multimedia-volume-control-symbolic", "audio-speakers-symbolic",
"audio-x-generic",
]
Recording =>
[
"moonmix-tab-recording-symbolic", "audio-input-microphone-symbolic", "audio-x-generic",
]
OutputDevices =>
[
"moonmix-tab-output-symbolic", "audio-speakers-symbolic", "audio-card-symbolic",
"audio-x-generic",
]
InputDevices =>
[
"moonmix-tab-input-symbolic", "audio-input-microphone-symbolic", "audio-card-symbolic",
"audio-x-generic",
]
Playback | OutputDevices => "audio-speakers-symbolic"
Recording | InputDevices => "audio-input-microphone-symbolic"
}
}
+41 -94
View File
@@ -19,41 +19,34 @@ fn dev(
}
///|
test "device bundled icon beats form factor/hint freedesktop fallback" {
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], "moonmix-device-headphones-symbolic")
assert_true(c.contains("audio-card-pci-symbolic"))
assert_true(c.contains("audio-headphones-symbolic"))
let card_idx = c.search("audio-card-pci-symbolic").unwrap()
let hp_idx = c.search("audio-headphones-symbolic").unwrap()
assert_true(card_idx < hp_idx)
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 prefer bundled lucide icons" {
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"), "moonmix-device-headset-symbolic")
assert_eq(first("headset", "Audio/Sink"), "audio-headset-symbolic")
assert_eq(first("speaker", "Audio/Sink"), "audio-speakers-symbolic")
assert_eq(
first("headphone", "Audio/Sink"),
"moonmix-device-headphones-symbolic",
first("microphone", "Audio/Source"),
"audio-input-microphone-symbolic",
)
assert_eq(first("speaker", "Audio/Sink"), "moonmix-device-speaker-symbolic")
assert_eq(first("hifi", "Audio/Sink"), "moonmix-device-speaker-symbolic")
assert_eq(first("microphone", "Audio/Source"), "moonmix-device-mic-symbolic")
assert_eq(first("webcam", "Audio/Source"), "moonmix-device-webcam-symbolic")
assert_eq(first("handset", "Audio/Sink"), "moonmix-device-phone-symbolic")
assert_eq(first("tv", "Audio/Sink"), "moonmix-device-display-symbolic")
assert_eq(first("hdmi", "Audio/Sink"), "moonmix-device-display-symbolic")
assert_eq(first("car", "Audio/Source"), "moonmix-device-mic-symbolic")
assert_eq(first("car", "Audio/Sink"), "moonmix-device-speaker-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, bluetooth and usb heuristics" {
test "hdmi, webcam and bluetooth heuristics" {
let hdmi = @model.device_icon_chain(
dev(
"Audio/Sink",
@@ -61,8 +54,7 @@ test "hdmi, webcam, bluetooth and usb heuristics" {
description="HDMI / DisplayPort",
),
)
assert_eq(hdmi[0], "moonmix-device-display-symbolic")
assert_true(hdmi.contains("video-display-symbolic"))
assert_eq(hdmi[0], "video-display-symbolic")
let cam = @model.device_icon_chain(
dev(
"Audio/Source",
@@ -70,106 +62,61 @@ test "hdmi, webcam, bluetooth and usb heuristics" {
description="EMEET SmartCam C960 Mono",
),
)
assert_eq(cam[0], "moonmix-device-webcam-symbolic")
assert_true(cam.contains("camera-web-symbolic"))
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], "moonmix-device-bluetooth-symbolic")
assert_true(bt.contains("audio-headphones-symbolic"))
let usb = @model.device_icon_chain(
dev("Audio/Sink", name="alsa_output.usb-Focusrite_Scarlett.analog-stereo"),
assert_eq(bt[0], "audio-headphones-symbolic")
assert_eq(
@model.device_bus(dev("Audio/Sink", name="alsa_output.usb-X.analog-stereo")),
"usb",
)
assert_eq(usb[0], "moonmix-device-usb-symbolic")
assert_eq(@model.device_bus(usb_dev()), "usb")
}
///|
fn usb_dev() -> @model.Node {
dev("Audio/Sink", name="alsa_output.usb-X.analog-stereo")
}
///|
test "device chain always ends in bundled and freedesktop fallbacks" {
test "device chain always ends in fallbacks" {
let c = @model.device_icon_chain(dev("Audio/Sink"))
assert_eq(c[0], "moonmix-device-speaker-symbolic")
assert_true(c.contains("moonmix-device-audio-symbolic"))
assert_true(c.contains("audio-speakers-symbolic"))
assert_true(c.contains("audio-card-symbolic"))
assert_eq(c[c.length() - 1], "image-missing")
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], "moonmix-device-mic-symbolic")
assert_eq(s[0], "audio-input-microphone-symbolic")
assert_eq(s[s.length() - 1], "image-missing")
}
///|
test "stream chain prefers full-colour app icons before symbolic hints" {
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=["applications-multimedia-symbolic", "firefox-esr"],
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", "applications-multimedia-symbolic", "moonmix-app-fallback-symbolic",
"application-x-executable-symbolic", "audio-x-generic-symbolic", "image-missing",
"firefox", "application-x-executable-symbolic", "audio-x-generic-symbolic", "image-missing",
])
let with_path = @model.Node::new(
11,
"Stream/Output/Audio",
app_name="Player",
icon_hints=["/usr/share/pixmaps/player.png"],
)
assert_eq(
@model.stream_icon_chain(with_path)[0],
"file:/usr/share/pixmaps/player.png",
)
let bare_play = @model.Node::new(12, "Stream/Output/Audio")
assert_eq(@model.stream_icon_chain(bare_play), [
"moonmix-app-fallback-symbolic", "application-x-executable-symbolic", "audio-x-generic-symbolic",
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",
])
let bare_rec = @model.Node::new(10, "Stream/Input/Audio")
assert_eq(@model.stream_icon_chain(bare_rec), [
"moonmix-device-mic-symbolic", "moonmix-app-fallback-symbolic", "application-x-executable-symbolic",
"audio-x-generic-symbolic", "audio-input-microphone-symbolic", "image-missing",
])
}
///|
test "volume icon and chain follow volume and mute" {
assert_eq(@model.volume_icon(100.0, false), "moonmix-volume-high-symbolic")
assert_eq(@model.volume_icon(50.0, false), "moonmix-volume-medium-symbolic")
assert_eq(@model.volume_icon(10.0, false), "moonmix-volume-low-symbolic")
assert_eq(@model.volume_icon(0.0, false), "moonmix-volume-muted-symbolic")
assert_eq(@model.volume_icon(100.0, true), "moonmix-volume-muted-symbolic")
assert_eq(@model.volume_icon_chain(100.0, false), [
"moonmix-volume-high-symbolic", "audio-volume-high-symbolic", "audio-volume-high",
])
assert_eq(@model.volume_icon_chain(0.0, false), [
"moonmix-volume-muted-symbolic", "audio-volume-muted-symbolic", "audio-volume-muted",
])
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 "default button, tab icons, and symbolic check" {
assert_eq(@model.default_button_icons(), [
"moonmix-default-symbolic", "emblem-ok-symbolic", "object-select-symbolic",
])
assert_eq(@model.Tab::Playback.icon(), "moonmix-tab-playback-symbolic")
assert_eq(@model.Tab::Recording.icon(), "moonmix-tab-recording-symbolic")
assert_eq(@model.Tab::OutputDevices.icon(), "moonmix-tab-output-symbolic")
assert_eq(@model.Tab::InputDevices.icon(), "moonmix-tab-input-symbolic")
assert_eq(
@model.Tab::Playback.icon_chain()[0],
"moonmix-tab-playback-symbolic",
)
assert_true(@model.is_symbolic_icon("moonmix-device-speaker-symbolic"))
assert_true(@model.is_symbolic_icon("file:/tmp/foo-symbolic.svg"))
assert_true(@model.is_symbolic_icon("image-missing"))
assert_false(@model.is_symbolic_icon("firefox"))
assert_false(@model.is_symbolic_icon("file:/usr/share/pixmaps/vlc.png"))
test "tab icons" {
assert_eq(@model.Tab::Playback.icon(), "audio-speakers-symbolic")
assert_eq(@model.Tab::InputDevices.icon(), "audio-input-microphone-symbolic")
}
-82
View File
@@ -8,38 +8,18 @@ import {
// Values
pub const APP_LOOKUP_PREFIX : String = "app:"
pub const FILE_ICON_PREFIX : String = "file:"
pub const ICON_MISSING : String = "image-missing"
pub const LIST_LATCH_US : Int64 = 600_000
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 const WHEEL_STEP_PERCENT : Double = 2.0
pub fn accent_css(Rgb, Bool) -> String
pub fn accent_text_color(Rgb, Bool) -> Rgb
pub let black : Rgb
pub fn bundled_form_factor_icon(String, NodeKind) -> String
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
@@ -62,8 +42,6 @@ pub fn icon_fallback_device() -> Array[String]
pub fn icon_fallback_stream() -> Array[String]
pub fn is_symbolic_icon(String) -> Bool
pub fn linear_to_db(Double) -> Double?
pub fn linear_to_percent(Double) -> Double
@@ -76,8 +54,6 @@ 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]
@@ -90,34 +66,9 @@ pub fn symbolic(String) -> String
pub fn volume_icon(Double, Bool) -> String
pub fn volume_icon_chain(Double, Bool) -> Array[String]
pub fn wheel_delta_percent(ScrollUnit, Double, Double, Double) -> Double
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
@@ -176,18 +127,6 @@ 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
@@ -205,20 +144,6 @@ pub(all) struct Row {
current_choice : Int32
}
#derive(Eq, @debug.Debug)
pub(all) enum ScrollUnit {
Wheel
Pixels
}
pub struct SliderWheel {
// private fields
}
pub fn SliderWheel::new() -> Self
pub fn SliderWheel::reset(Self) -> Unit
pub fn SliderWheel::route(Self, ScrollUnit, Double, Double, Int64) -> WheelRoute
pub fn SliderWheel::scroll(Self, ScrollUnit, Double, Double, Int64, Double, Double) -> Double?
pub(all) struct State {
nodes : Map[Int32, Node]
mut links : Array[Link]
@@ -240,16 +165,9 @@ 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::icon_chain(Self) -> Array[String]
pub fn Tab::label(Self) -> String
pub fn Tab::node_kind(Self) -> NodeKind
#derive(Eq, @debug.Debug)
pub(all) enum WheelRoute {
Slider
List
}
// Type aliases
// Traits
+2 -2
View File
@@ -33,8 +33,8 @@ 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], "moonmix-device-mic-symbolic")
assert_eq(ins[0].volume_icon, "moonmix-volume-muted-symbolic")
assert_eq(ins[0].icons[0], "audio-input-microphone-symbolic")
assert_eq(ins[0].volume_icon, "audio-volume-muted-symbolic")
}
///|
-134
View File
@@ -1,134 +0,0 @@
// Scrolling over a volume slider: does it scroll the list or change the
// volume, and by how much?
//
// GTK's own GtkRange handler moves a slider by its page increment (10% here)
// per wheel detent, ignores a horizontal wheel and swallows every scroll
// event, including a touchpad's vertical swipe it does nothing with. So a
// list scroll that passes over a slider stops dead and changes that stream's
// volume instead. moonmix replaces that handler with this policy:
//
// - While the list is scrolling (it moved, or was sent a scroll, less than
// `LIST_LATCH_US` ago), scrolling stays with the list, sliders or not.
// - Otherwise a mouse wheel over a slider changes the volume by
// `WHEEL_STEP_PERCENT` per detent, proportionally for high-resolution
// wheels' partial detents (no rounding). Up or right is louder.
// - A touchpad gesture is decided once, at its first movement: a mainly
// horizontal swipe moves the slider (the knob follows the fingers), a
// mainly vertical one scrolls the list. Touchpad scrolling never gets a
// kinetic tail on a slider.
///|
/// Volume change per mouse-wheel detent, in percent (GNOME Shell's sliders
/// also step 2% per detent).
pub const WHEEL_STEP_PERCENT : Double = 2.0
///|
/// How long after the list last moved (or was sent a scroll) scroll events
/// over a slider still go to the list.
pub const LIST_LATCH_US : Int64 = 600_000L
///|
/// The unit of a scroll event's deltas (GdkScrollUnit).
#derive(Eq, Debug)
pub(all) enum ScrollUnit {
/// Wheel detents; high-resolution wheels report fractions of one.
Wheel
/// Surface pixels, from touchpads and other smooth devices.
Pixels
}
///|
#derive(Eq, Debug)
pub(all) enum WheelRoute {
/// Change the slider's value.
Slider
/// Leave the event to the scrolled list.
List
}
///|
/// Routing state of one slider. A touchpad gesture keeps the route of its
/// first movement until it ends.
pub struct SliderWheel {
priv mut gesture : WheelRoute?
}
///|
pub fn SliderWheel::new() -> SliderWheel {
{ gesture: None, }
}
///|
/// A scroll gesture (touchpad sequence) begins or ends.
pub fn SliderWheel::reset(self : SliderWheel) -> Unit {
self.gesture = None
}
///|
/// Where one scroll event over the slider goes. `since_list_us` is the time
/// since the list last scrolled.
pub fn SliderWheel::route(
self : SliderWheel,
unit : ScrollUnit,
dx : Double,
dy : Double,
since_list_us : Int64,
) -> WheelRoute {
let latched = since_list_us < LIST_LATCH_US
match unit {
// A mouse wheel has no gesture: every detent is decided on its own.
Wheel => if latched { List } else { Slider }
Pixels =>
match self.gesture {
Some(route) => route
None => {
let route = if latched || dy.abs() >= dx.abs() {
List
} else {
Slider
}
self.gesture = Some(route)
route
}
}
}
}
///|
/// Volume change (percent) for one scroll event routed to a slider that is
/// `extent_px` wide. Deltas are in GTK's convention (dy > 0 is down, dx > 0
/// is right, in physical direction).
pub fn wheel_delta_percent(
unit : ScrollUnit,
dx : Double,
dy : Double,
extent_px : Double,
) -> Double {
match unit {
Wheel => (dx - dy) * WHEEL_STEP_PERCENT
Pixels => {
// Move the knob with the fingers; the slider spans 0..MAX_PERCENT.
let extent = if extent_px > 1.0 { extent_px } else { 300.0 }
dx * MAX_PERCENT / extent
}
}
}
///|
/// Handle one scroll event over a slider showing `value` percent: the new
/// value if the slider takes it, `None` if it belongs to the list.
pub fn SliderWheel::scroll(
self : SliderWheel,
unit : ScrollUnit,
dx : Double,
dy : Double,
since_list_us : Int64,
value : Double,
extent_px : Double,
) -> Double? {
match self.route(unit, dx, dy, since_list_us) {
List => None
Slider =>
Some(clamp_percent(value + wheel_delta_percent(unit, dx, dy, extent_px)))
}
}
-88
View File
@@ -1,88 +0,0 @@
///|
/// Long enough that the list is not scrolling any more.
const IDLE : Int64 = 10_000_000L
///|
test "a mouse wheel over an idle list changes the volume 2% per detent" {
let w = @model.SliderWheel::new()
// GTK: dy < 0 is up.
assert_eq(w.scroll(Wheel, 0.0, -1.0, IDLE, 50.0, 400.0), Some(52.0))
assert_eq(w.scroll(Wheel, 0.0, 1.0, IDLE, 50.0, 400.0), Some(48.0))
// Tilt wheel: right is louder.
assert_eq(w.scroll(Wheel, 1.0, 0.0, IDLE, 50.0, 400.0), Some(52.0))
}
///|
test "high-resolution wheels move by fractions of a step, unrounded" {
let w = @model.SliderWheel::new()
let mut v = 50.0
// One detent reported as eight 1/8 events (value120 = 15 each).
for _ in 0..<8 {
v = w.scroll(Wheel, 0.0, -0.125, IDLE, v, 400.0).unwrap()
}
assert_true((v - 52.0).abs() < 1.0e-9)
assert_eq(w.scroll(Wheel, 0.0, -0.125, IDLE, 50.0, 400.0), Some(50.25))
}
///|
test "the wheel keeps scrolling the list while it is moving" {
let w = @model.SliderWheel::new()
assert_eq(w.scroll(Wheel, 0.0, 1.0, 0L, 50.0, 400.0), None)
assert_eq(
w.scroll(Wheel, 0.0, 1.0, @model.LIST_LATCH_US - 1L, 50.0, 400.0),
None,
)
assert_eq(
w.scroll(Wheel, 0.0, 1.0, @model.LIST_LATCH_US, 50.0, 400.0),
Some(48.0),
)
}
///|
test "volume is clamped to the slider range" {
let w = @model.SliderWheel::new()
assert_eq(w.scroll(Wheel, 0.0, 1.0, IDLE, 1.0, 400.0), Some(0.0))
assert_eq(
w.scroll(Wheel, 0.0, -1.0, IDLE, @model.MAX_PERCENT - 1.0, 400.0),
Some(@model.MAX_PERCENT),
)
}
///|
test "a vertical touchpad swipe over a slider scrolls the list" {
let w = @model.SliderWheel::new()
w.reset()
assert_eq(w.scroll(Pixels, 0.4, 6.0, IDLE, 50.0, 300.0), None)
// Locked for the whole gesture, even if it turns sideways.
assert_eq(w.scroll(Pixels, 9.0, 0.0, IDLE, 50.0, 300.0), None)
w.reset()
}
///|
test "a horizontal touchpad swipe moves the knob with the fingers" {
let w = @model.SliderWheel::new()
w.reset()
// 300 px wide slider spanning 0..150%: 2 px = 1%.
assert_eq(w.scroll(Pixels, 10.0, 1.0, IDLE, 50.0, 300.0), Some(55.0))
// Vertical drift in the same gesture does not hand it to the list and
// does not change the volume.
assert_eq(w.scroll(Pixels, 0.0, 8.0, IDLE, 55.0, 300.0), Some(55.0))
assert_eq(w.scroll(Pixels, -3.0, 0.0, IDLE, 55.0, 300.0), Some(53.5))
w.reset()
// A new gesture is decided afresh.
assert_eq(w.scroll(Pixels, 0.0, 5.0, IDLE, 53.5, 300.0), None)
}
///|
test "a touchpad gesture starting while the list moves stays with the list" {
let w = @model.SliderWheel::new()
w.reset()
assert_eq(w.scroll(Pixels, 12.0, 0.0, 1_000L, 50.0, 300.0), None)
assert_eq(w.scroll(Pixels, 12.0, 0.0, IDLE, 50.0, 300.0), None)
}
///|
test "wheel_delta_percent tolerates an unallocated slider" {
assert_eq(@model.wheel_delta_percent(Pixels, 2.0, 0.0, 0.0), 1.0)
assert_eq(@model.wheel_delta_percent(Wheel, 0.0, -0.5, 0.0), 1.0)
}
-6
View File
@@ -1,6 +0,0 @@
#!/bin/sh
# Create the runtime directory as the actual container user, not namespace root.
set -eu
mkdir -p "$XDG_RUNTIME_DIR"
chmod 700 "$XDG_RUNTIME_DIR"
exec "$@"
-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()
-50
View File
@@ -1,50 +0,0 @@
#!/usr/bin/env python3
"""Install the container runner, app-menu entry and icons for the current user."""
import os
from pathlib import Path
import shutil
def desktop_exec(path):
"""Quote one Exec argument at both desktop-entry escaping layers."""
value = str(path).replace("%", "%%")
value = "".join("\\" + char if char in '\\"`$' else char for char in value)
return ('"' + value + '"').replace("\\", "\\\\")
def main():
root = Path(__file__).resolve().parent.parent
runner = Path.home() / ".local/bin/moonmix-container"
data_home = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share")
runner.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(root / "tools/moonmix-container", runner)
runner.chmod(0o755)
# Reuse the native entry's app id and metadata so Wayland associates the
# container window with this launcher. An absolute Exec avoids GUI PATH issues.
desktop = data_home / "applications/org.latha.moonmix.desktop"
desktop.parent.mkdir(parents=True, exist_ok=True)
template = (root / "data/org.latha.moonmix.desktop").read_text()
# GIO checks the executable before expanding %% field codes. Using env
# also supports a literal percent sign in the runner's absolute path.
desktop.write_text("".join(
f"Exec=/usr/bin/env {desktop_exec(runner)}\n" if line.startswith("Exec=") else line
for line in template.splitlines(keepends=True)
))
desktop.chmod(0o644)
for variant in ("scalable", "symbolic"):
name = "org.latha.moonmix" + ("-symbolic" if variant == "symbolic" else "") + ".svg"
relative = Path("icons/hicolor") / variant / "apps" / name
destination = data_home / relative
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(root / "data" / relative, destination)
destination.chmod(0o644)
print(f"Installed runner: {runner}")
print(f"Installed desktop launcher: {desktop}")
if __name__ == "__main__":
main()
-109
View File
@@ -1,109 +0,0 @@
#!/bin/sh
# Run the local OCI image against the current user's Wayland/PipeWire session.
set -eu
fail() { printf 'moonmix-container: %s\n' "$*" >&2; exit 1; }
command -v podman >/dev/null 2>&1 || fail "install rootless Podman first"
[ "$#" -eq 0 ] || fail "this launcher does not take arguments"
[ -n "${XDG_RUNTIME_DIR:-}" ] || fail "XDG_RUNTIME_DIR is not set"
[ -n "${WAYLAND_DISPLAY:-}" ] || fail "a Wayland session is required"
uid=$(id -u)
gid=$(id -g)
[ "$uid" -ne 0 ] || fail "run this as your desktop user, not root"
case "$WAYLAND_DISPLAY" in
/*) wayland_socket=$WAYLAND_DISPLAY ;;
*) wayland_socket=$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY ;;
esac
case "${PIPEWIRE_REMOTE:-pipewire-0}" in
/*) pipewire_socket=$PIPEWIRE_REMOTE ;;
*) pipewire_socket=${PIPEWIRE_RUNTIME_DIR:-$XDG_RUNTIME_DIR}/${PIPEWIRE_REMOTE:-pipewire-0} ;;
esac
[ -S "$wayland_socket" ] || fail "Wayland socket not found: $wayland_socket"
[ -S "$pipewire_socket" ] || fail "PipeWire socket not found: $pipewire_socket"
set -- podman run --rm --pull=never \
--userns=keep-id --user "$uid:$gid" \
--network=none --cap-drop=all --security-opt=no-new-privileges \
--read-only \
--tmpfs /tmp:rw,nosuid,nodev \
--env XDG_ACTIVATION_TOKEN --env DESKTOP_STARTUP_ID \
--env XDG_RUNTIME_DIR=/tmp/moonmix-runtime \
--env PIPEWIRE_RUNTIME_DIR=/run/moonmix \
--env PIPEWIRE_REMOTE=pipewire-0 \
--env WAYLAND_DISPLAY=/run/moonmix/wayland-0 \
--mount "type=bind,src=$wayland_socket,dst=/run/moonmix/wayland-0,ro" \
--mount "type=bind,src=$pipewire_socket,dst=/run/moonmix/pipewire-0,ro"
# The portal supplies desktop appearance settings. Do not expose the rest of
# XDG_RUNTIME_DIR (which can contain credentials and unrelated service sockets).
if [ -S "$XDG_RUNTIME_DIR/bus" ]; then
set -- "$@" \
--mount "type=bind,src=$XDG_RUNTIME_DIR/bus,dst=/run/moonmix/bus,ro" \
--env DBUS_SESSION_BUS_ADDRESS=unix:path=/run/moonmix/bus
else
set -- "$@" --env DBUS_SESSION_BUS_ADDRESS=unix:path=/run/moonmix/no-bus
fi
# Mount only existing host icon / .desktop directories read-only so GIO and
# GtkIconTheme can resolve real full-colour host app icons without exposing $HOME.
host_root=${MOONMIX_HOST_ROOT:-}
if [ -n "${XDG_DATA_HOME:-}" ]; then
data_home=$XDG_DATA_HOME
elif [ -n "${HOME:-}" ]; then
data_home=$HOME/.local/share
else
data_home=
fi
host_xdg_dirs=
add_xdg_prefix() {
case ":$host_xdg_dirs:" in
*":$1:"*) ;;
*) host_xdg_dirs=${host_xdg_dirs:+$host_xdg_dirs:}$1 ;;
esac
}
if [ -n "$data_home" ]; then
if [ -d "$data_home/icons" ]; then
set -- "$@" --mount "type=bind,src=$data_home/icons,dst=/run/moonmix/host/user/icons,ro"
add_xdg_prefix /run/moonmix/host/user
fi
if [ -d "$data_home/applications" ]; then
set -- "$@" --mount "type=bind,src=$data_home/applications,dst=/run/moonmix/host/user/applications,ro"
add_xdg_prefix /run/moonmix/host/user
fi
if [ -d "$data_home/flatpak/exports/share/icons" ]; then
set -- "$@" --mount "type=bind,src=$data_home/flatpak/exports/share/icons,dst=/run/moonmix/host/flatpak-user/icons,ro"
add_xdg_prefix /run/moonmix/host/flatpak-user
fi
if [ -d "$data_home/flatpak/exports/share/applications" ]; then
set -- "$@" --mount "type=bind,src=$data_home/flatpak/exports/share/applications,dst=/run/moonmix/host/flatpak-user/applications,ro"
add_xdg_prefix /run/moonmix/host/flatpak-user
fi
fi
if [ -d "$host_root/var/lib/flatpak/exports/share/icons" ]; then
set -- "$@" --mount "type=bind,src=$host_root/var/lib/flatpak/exports/share/icons,dst=/run/moonmix/host/flatpak-sys/icons,ro"
add_xdg_prefix /run/moonmix/host/flatpak-sys
fi
if [ -d "$host_root/var/lib/flatpak/exports/share/applications" ]; then
set -- "$@" --mount "type=bind,src=$host_root/var/lib/flatpak/exports/share/applications,dst=/run/moonmix/host/flatpak-sys/applications,ro"
add_xdg_prefix /run/moonmix/host/flatpak-sys
fi
if [ -d "$host_root/usr/share/icons" ]; then
set -- "$@" --mount "type=bind,src=$host_root/usr/share/icons,dst=/run/moonmix/host/usr/icons,ro"
add_xdg_prefix /run/moonmix/host/usr
fi
if [ -d "$host_root/usr/share/pixmaps" ]; then
set -- "$@" --mount "type=bind,src=$host_root/usr/share/pixmaps,dst=/run/moonmix/host/usr/pixmaps,ro"
add_xdg_prefix /run/moonmix/host/usr
fi
if [ -d "$host_root/usr/share/applications" ]; then
set -- "$@" --mount "type=bind,src=$host_root/usr/share/applications,dst=/run/moonmix/host/usr/applications,ro"
add_xdg_prefix /run/moonmix/host/usr
fi
set -- "$@" --env "XDG_DATA_DIRS=${host_xdg_dirs:+$host_xdg_dirs:}/usr/local/share:/usr/share"
exec "$@" "${MOONMIX_IMAGE:-localhost/moonmix:latest}"
+6 -67
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.
@@ -61,7 +60,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
@@ -90,39 +89,10 @@ 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"
# Synthetic desktop app with a full-colour icon so we verify .desktop lookup
# alongside unmapped stream fallbacks.
TEST_XDG="$XDG_RUNTIME_DIR/xdg-data"
mkdir -p "$TEST_XDG/icons/hicolor/scalable/apps" "$TEST_XDG/applications"
cat > "$TEST_XDG/icons/hicolor/scalable/apps/org.example.TestPlayer.svg" <<'SVG'
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#3b82f6"/>
<stop offset="1" stop-color="#8b5cf6"/>
</linearGradient>
</defs>
<rect x="2" y="2" width="44" height="44" rx="12" fill="url(#g)"/>
<path d="M31 30V13a1.5 1.5 0 0 0-1.9-1.44l-11 3.2A1.5 1.5 0 0 0 17 16.2V33" fill="none" stroke="#ffffff" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="27.5" cy="30" r="3.5" fill="#ffffff"/>
<circle cx="13.5" cy="33" r="3.5" fill="#ffffff"/>
</svg>
SVG
cat > "$TEST_XDG/applications/org.example.TestPlayer.desktop" <<'DESK'
[Desktop Entry]
Type=Application
Name=Test Player
Exec=pw-play
Icon=org.example.TestPlayer
DESK
{ pw-play -P '{ application.name = "Test Player" application.id = "org.example.TestPlayer" media.name = "Smoke test tone" }' \
{ 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 $!"
{ pw-play -P '{ application.name = "Fallback Stream" media.name = "Unmapped app stream" }' \
"$LOGS/noise.wav"; echo "pw-play fallback exited with $?"; } >"$LOGS/play-fallback.log" 2>&1 & PIDS="$PIDS $!"
pw-cat --record --raw --rate 48000 --channels 1 --format s16 \
-P '{ application.name = "Test Recorder" media.name = "Mic capture" }' \
-P '{ application.name = "Test Recorder" application.icon-name = "audio-input-microphone" media.name = "Mic capture" }' \
/dev/null >"$LOGS/record.log" 2>&1 & PIDS="$PIDS $!"
wait_for 'Test Player | .*-> ' || true
@@ -186,39 +156,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() { XDG_DATA_DIRS="$TEST_XDG:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}" 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
MOONMIX_ICON_DIR="$ROOT/data/icons" GDK_BACKEND=broadway BROADWAY_DISPLAY=:5 MOONMIX_SCREENSHOT="$SHOTS" \
timeout 30 "$GUI" || fail=1
else
echo "gtk4-broadwayd not found; skipping GUI"
fi
-284
View File
@@ -1,284 +0,0 @@
#!/usr/bin/env python3
"""Exercise container/desktop packaging without building or running an image."""
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import unittest
ROOT = Path(__file__).resolve().parent.parent
class ContainerTests(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.directory = Path(temporary.name)
self.runtime = self.directory / "runtime"
self.runtime.mkdir(mode=0o700)
self.bind_socket(self.runtime / "wayland-test")
self.bind_socket(self.runtime / "pipewire-0")
self.arguments = self.directory / "podman-arguments"
bin_dir = self.directory / "bin"
bin_dir.mkdir()
for name, body in {
"podman": 'printf "%s\\n" "$@" > "$MOONMIX_TEST_ARGUMENTS"\n',
"id": 'printf "%s\\n" "${MOONMIX_TEST_UID:-1000}"\n',
}.items():
program = bin_dir / name
program.write_text("#!/bin/sh\n" + body)
program.chmod(0o755)
self.host = self.directory / "host"
self.host.mkdir()
self.empty_home = self.directory / "empty-home"
self.empty_home.mkdir()
self.environment = dict(os.environ)
for key in (
"PIPEWIRE_RUNTIME_DIR",
"PIPEWIRE_REMOTE",
"MOONMIX_IMAGE",
"XDG_DATA_HOME",
"MOONMIX_HOST_ROOT",
):
self.environment.pop(key, None)
self.environment.update(
PATH=f"{bin_dir}:/usr/bin:/bin",
HOME=str(self.empty_home),
XDG_RUNTIME_DIR=str(self.runtime),
WAYLAND_DISPLAY="wayland-test",
MOONMIX_HOST_ROOT=str(self.host),
MOONMIX_TEST_ARGUMENTS=str(self.arguments),
)
def bind_socket(self, path):
connection = socket.socket(socket.AF_UNIX)
self.addCleanup(connection.close)
connection.bind(str(path))
def launch(self, *arguments):
return subprocess.run(
["sh", str(ROOT / "tools/moonmix-container"), *arguments],
env=self.environment, capture_output=True, text=True,
)
def podman_arguments(self):
return self.arguments.read_text().splitlines()
def mounts(self):
arguments = self.podman_arguments()
return [arguments[i + 1] for i, value in enumerate(arguments) if value == "--mount"]
def test_rootless_read_only_local_image_and_narrow_socket_mounts(self):
result = self.launch()
self.assertEqual(result.returncode, 0, result.stderr)
arguments = self.podman_arguments()
for option in (
"--rm", "--pull=never", "--userns=keep-id", "--read-only",
"--network=none", "--cap-drop=all", "--security-opt=no-new-privileges",
):
self.assertIn(option, arguments)
self.assertEqual(arguments[arguments.index("--user") + 1], "1000:1000")
self.assertEqual(arguments[-1], "localhost/moonmix:latest")
self.assertIn("XDG_RUNTIME_DIR=/tmp/moonmix-runtime", arguments)
self.assertIn("WAYLAND_DISPLAY=/run/moonmix/wayland-0", arguments)
self.assertIn("XDG_ACTIVATION_TOKEN", arguments)
self.assertIn("DESKTOP_STARTUP_ID", arguments)
self.assertEqual(self.mounts(), [
f"type=bind,src={self.runtime}/wayland-test,dst=/run/moonmix/wayland-0,ro",
f"type=bind,src={self.runtime}/pipewire-0,dst=/run/moonmix/pipewire-0,ro",
])
self.assertIn("DBUS_SESSION_BUS_ADDRESS=unix:path=/run/moonmix/no-bus", arguments)
def test_session_bus_is_optional_and_mounted_individually(self):
self.bind_socket(self.runtime / "bus")
self.assertEqual(self.launch().returncode, 0)
self.assertIn(
f"type=bind,src={self.runtime}/bus,dst=/run/moonmix/bus,ro",
self.mounts(),
)
self.assertIn(
"DBUS_SESSION_BUS_ADDRESS=unix:path=/run/moonmix/bus",
self.podman_arguments(),
)
def test_absolute_wayland_and_pipewire_socket_paths(self):
wayland = self.directory / "display"
pipewire = self.directory / "audio"
self.bind_socket(wayland)
self.bind_socket(pipewire)
self.environment.update(WAYLAND_DISPLAY=str(wayland), PIPEWIRE_REMOTE=str(pipewire))
self.assertEqual(self.launch().returncode, 0)
self.assertEqual(self.mounts(), [
f"type=bind,src={wayland},dst=/run/moonmix/wayland-0,ro",
f"type=bind,src={pipewire},dst=/run/moonmix/pipewire-0,ro",
])
def test_pipewire_runtime_remote_and_image_overrides(self):
self.bind_socket(self.directory / "pipewire-custom")
self.environment.update(
PIPEWIRE_RUNTIME_DIR=str(self.directory),
PIPEWIRE_REMOTE="pipewire-custom",
MOONMIX_IMAGE="localhost/moonmix:test",
)
self.assertEqual(self.launch().returncode, 0)
self.assertIn(
f"type=bind,src={self.directory}/pipewire-custom,dst=/run/moonmix/pipewire-0,ro",
self.mounts(),
)
self.assertEqual(self.podman_arguments()[-1], "localhost/moonmix:test")
def test_missing_session_or_socket_fails_before_podman(self):
for key, value, message in (
("XDG_RUNTIME_DIR", "", "XDG_RUNTIME_DIR is not set"),
("WAYLAND_DISPLAY", "", "Wayland session is required"),
("WAYLAND_DISPLAY", "missing", "Wayland socket not found"),
("PIPEWIRE_REMOTE", "missing", "PipeWire socket not found"),
):
with self.subTest(key=key, value=value):
environment = self.environment.copy()
self.environment[key] = value
result = self.launch()
self.environment = environment
self.assertNotEqual(result.returncode, 0)
self.assertIn(message, result.stderr)
self.assertFalse(self.arguments.exists())
def test_root_and_unexpected_arguments_are_rejected(self):
self.environment["MOONMIX_TEST_UID"] = "0"
self.assertIn("not root", self.launch().stderr)
self.assertIn("does not take arguments", self.launch("--privileged").stderr)
self.assertFalse(self.arguments.exists())
def test_entrypoint_creates_a_private_user_owned_runtime_directory(self):
runtime = self.directory / "container-runtime"
environment = dict(self.environment, XDG_RUNTIME_DIR=str(runtime))
result = subprocess.run(
["sh", str(ROOT / "tools/container-entrypoint"), "sh", "-c", "exit 17"],
env=environment, capture_output=True, text=True,
)
self.assertEqual(result.returncode, 17, result.stderr)
self.assertEqual(runtime.stat().st_mode & 0o777, 0o700)
self.assertEqual(runtime.stat().st_uid, os.getuid())
def install(self):
# Exercise spaces, Exec field codes, and characters requiring both
# desktop-entry escaping layers. No shell expansion should take place.
home = self.directory / 'home with spaces $dollar % "quote" \\slash'
native = home / ".local/bin/moonmix"
native.parent.mkdir(parents=True)
native.write_text("existing native installation")
data_home = self.directory / "custom-data"
self.environment.update(HOME=str(home), XDG_DATA_HOME=str(data_home))
result = subprocess.run(
[sys.executable, str(ROOT / "tools/install-container.py")],
env=self.environment, capture_output=True, text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(native.read_text(), "existing native installation")
runner = home / ".local/bin/moonmix-container"
self.assertTrue(os.access(runner, os.X_OK))
self.assertEqual(runner.read_bytes(), (ROOT / "tools/moonmix-container").read_bytes())
return data_home
def test_installer_reuses_desktop_identity_and_installs_icons(self):
data_home = self.install()
desktop = data_home / "applications/org.latha.moonmix.desktop"
self.assertIn("StartupWMClass=org.latha.moonmix\n", desktop.read_text())
self.assertIn(f'Exec=/usr/bin/env "{self.directory}/', desktop.read_text())
self.assertNotIn("Exec=moonmix\n", desktop.read_text())
self.assertTrue((data_home / "icons/hicolor/scalable/apps/org.latha.moonmix.svg").is_file())
self.assertTrue((data_home / "icons/hicolor/symbolic/apps/org.latha.moonmix-symbolic.svg").is_file())
if shutil.which("desktop-file-validate"):
subprocess.run(["desktop-file-validate", str(desktop)], check=True)
@unittest.skipUnless(shutil.which("gio"), "GIO is not installed")
def test_desktop_exec_round_trips_paths_without_shell_expansion(self):
desktop = self.install() / "applications/org.latha.moonmix.desktop"
result = subprocess.run(
["gio", "launch", str(desktop)],
env=self.environment, capture_output=True, text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
for _ in range(40):
if self.arguments.exists():
break
time.sleep(0.05)
self.assertTrue(self.arguments.exists(), result.stderr)
self.assertEqual(self.podman_arguments()[-1], "localhost/moonmix:latest")
def env_value(self, name):
arguments = self.podman_arguments()
prefix = f"{name}="
for i, arg in enumerate(arguments):
if arg == "--env" and i + 1 < len(arguments) and arguments[i + 1].startswith(prefix):
return arguments[i + 1][len(prefix):]
self.fail(f"missing --env {name}=... in {arguments}")
def test_no_host_icon_mounts_when_directories_missing(self):
self.assertEqual(self.launch().returncode, 0)
self.assertFalse(any("/run/moonmix/host" in m for m in self.mounts()))
self.assertEqual(self.env_value("XDG_DATA_DIRS"), "/usr/local/share:/usr/share")
def test_host_icon_and_desktop_directories_are_mounted_read_only(self):
home = self.directory / "home"
secret = home / ".ssh/id_rsa"
secret.parent.mkdir(parents=True)
secret.write_text("do not mount")
data_home = self.directory / "xdg-data"
expected = [
(data_home / "icons", "/run/moonmix/host/user/icons"),
(data_home / "applications", "/run/moonmix/host/user/applications"),
(data_home / "flatpak/exports/share/icons", "/run/moonmix/host/flatpak-user/icons"),
(data_home / "flatpak/exports/share/applications", "/run/moonmix/host/flatpak-user/applications"),
(self.host / "var/lib/flatpak/exports/share/icons", "/run/moonmix/host/flatpak-sys/icons"),
(self.host / "var/lib/flatpak/exports/share/applications", "/run/moonmix/host/flatpak-sys/applications"),
(self.host / "usr/share/icons", "/run/moonmix/host/usr/icons"),
(self.host / "usr/share/pixmaps", "/run/moonmix/host/usr/pixmaps"),
(self.host / "usr/share/applications", "/run/moonmix/host/usr/applications"),
]
for path, _ in expected:
path.mkdir(parents=True)
self.environment.update(HOME=str(home), XDG_DATA_HOME=str(data_home))
result = self.launch()
self.assertEqual(result.returncode, 0, result.stderr)
mounts = self.mounts()
for src, dst in expected:
self.assertIn(f"type=bind,src={src},dst={dst},ro", mounts)
self.assertFalse(any(str(home) in m for m in mounts))
self.assertEqual(
self.env_value("XDG_DATA_DIRS"),
"/run/moonmix/host/user:/run/moonmix/host/flatpak-user:/run/moonmix/host/flatpak-sys:/run/moonmix/host/usr:/usr/local/share:/usr/share",
)
def test_partial_host_icon_mounts_and_home_fallback(self):
home = self.directory / "home-fallback"
user_icons = home / ".local/share/icons"
sys_pixmaps = self.host / "usr/share/pixmaps"
sys_apps = self.host / "usr/share/applications"
for path in (user_icons, sys_pixmaps, sys_apps):
path.mkdir(parents=True)
self.environment["HOME"] = str(home)
result = self.launch()
self.assertEqual(result.returncode, 0, result.stderr)
mounts = self.mounts()
self.assertEqual(mounts, [
f"type=bind,src={self.runtime}/wayland-test,dst=/run/moonmix/wayland-0,ro",
f"type=bind,src={self.runtime}/pipewire-0,dst=/run/moonmix/pipewire-0,ro",
f"type=bind,src={user_icons},dst=/run/moonmix/host/user/icons,ro",
f"type=bind,src={sys_pixmaps},dst=/run/moonmix/host/usr/pixmaps,ro",
f"type=bind,src={sys_apps},dst=/run/moonmix/host/usr/applications,ro",
])
self.assertEqual(
self.env_value("XDG_DATA_DIRS"),
"/run/moonmix/host/user:/run/moonmix/host/usr:/usr/local/share:/usr/share",
)
if __name__ == "__main__":
unittest.main()