From b1f0965e02a6cd397cfeb9e68fc786802b559fdf Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sun, 22 Nov 2026 20:56:43 -0800 Subject: [PATCH] Add OCI image and container desktop launcher Build a release OCI image with runtime dependencies and a rootless Podman launcher for Wayland and PipeWire. Install the runner, app-menu entry, and icons per user without replacing the native executable. Use Ubuntu 26.04 and GTK 4.22 for linux-dmabuf v6 compatibility. Allow an explicit icon-theme override so the container uses its bundled Adwaita assets. Document installation and add runner/desktop regression tests. --- .containerignore | 8 ++ Containerfile | 51 +++++++++ README.md | 43 ++++++++ gtk/gtk_stub.c | 5 + tools/container-entrypoint | 6 ++ tools/install-container.py | 50 +++++++++ tools/moonmix-container | 48 +++++++++ tools/test-container.py | 205 +++++++++++++++++++++++++++++++++++++ 8 files changed, 416 insertions(+) create mode 100644 .containerignore create mode 100644 Containerfile create mode 100755 tools/container-entrypoint create mode 100755 tools/install-container.py create mode 100755 tools/moonmix-container create mode 100755 tools/test-container.py diff --git a/.containerignore b/.containerignore new file mode 100644 index 0000000..19e4b91 --- /dev/null +++ b/.containerignore @@ -0,0 +1,8 @@ +.git +_build +target +.mooncakes +.moonagent +**/.env +**/.env.* +screenshots diff --git a/Containerfile b/Containerfile new file mode 100644 index 0000000..d728124 --- /dev/null +++ b/Containerfile @@ -0,0 +1,51 @@ +# 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/ /usr/share/icons/ +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"] diff --git a/README.md b/README.md index 557fc3a..2f5eead 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,48 @@ 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=` 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), +plus `$XDG_RUNTIME_DIR/bus` when present for desktop appearance settings. +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 (such as Papirus) +does not cause missing icons; 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 moonmix-probe` to inspect the host audio +graph without changing it. + ### Icons Everything else uses the desktop's icon theme (Adwaita, Breeze, Papirus... @@ -209,6 +251,7 @@ $P meter # 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) ``` diff --git a/gtk/gtk_stub.c b/gtk/gtk_stub.c index e8198ec..6e028fc 100644 --- a/gtk/gtk_stub.c +++ b/gtk/gtk_stub.c @@ -49,6 +49,11 @@ MOONBIT_FFI_EXPORT int32_t mm_gtk_init(void) { 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 find data/icons/hicolor/... too: * $MOONMIX_ICON_DIR, then ./data/icons. */ GtkIconTheme *theme = gtk_icon_theme_get_for_display(gdk_display_get_default()); diff --git a/tools/container-entrypoint b/tools/container-entrypoint new file mode 100755 index 0000000..26e27c0 --- /dev/null +++ b/tools/container-entrypoint @@ -0,0 +1,6 @@ +#!/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 "$@" diff --git a/tools/install-container.py b/tools/install-container.py new file mode 100755 index 0000000..da0f5c5 --- /dev/null +++ b/tools/install-container.py @@ -0,0 +1,50 @@ +#!/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() diff --git a/tools/moonmix-container b/tools/moonmix-container new file mode 100755 index 0000000..a62a30a --- /dev/null +++ b/tools/moonmix-container @@ -0,0 +1,48 @@ +#!/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 + +exec "$@" "${MOONMIX_IMAGE:-localhost/moonmix:latest}" diff --git a/tools/test-container.py b/tools/test-container.py new file mode 100755 index 0000000..bdd2e45 --- /dev/null +++ b/tools/test-container.py @@ -0,0 +1,205 @@ +#!/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.environment = dict(os.environ) + for key in ("PIPEWIRE_RUNTIME_DIR", "PIPEWIRE_REMOTE", "MOONMIX_IMAGE"): + self.environment.pop(key, None) + self.environment.update( + PATH=f"{bin_dir}:/usr/bin:/bin", + XDG_RUNTIME_DIR=str(self.runtime), + WAYLAND_DISPLAY="wayland-test", + 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") + + +if __name__ == "__main__": + unittest.main()