diff --git a/.gitignore b/.gitignore index ad1e447..c761a70 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,6 @@ node_modules/ *.log host-native/target/ .pixi/ -host-wasm/target/ # moon rewrites these for whichever target was built last, so they differ run to run. A few # (app, gfx, renderer, scene) were committed early and stay tracked; the rest are not. diff --git a/README.md b/README.md index f2a95c0..e4382bc 100644 --- a/README.md +++ b/README.md @@ -38,16 +38,14 @@ hosts). Toolchain notes: [docs/TOOLCHAIN.md](docs/TOOLCHAIN.md). Dark mode and t ``` build/compositor.wasm the compositor, a wasm component (components/compositor, code in compositor/) -build/wasmhost the host that runs it: MoonBit, linked to the prebuilt wasmtime C API (default) -host-wasm/ the same host in Rust on the wasmtime crate (fallback) +build/wasmhost the host that runs it: MoonBit, linked to the prebuilt wasmtime C API build/components/*.wasm panel modules, loaded by the host and drawn by the compositor ``` -The **MoonBit host** ([wasmhost/](wasmhost/README.md)) is the default. It links +The **MoonBit host** ([wasmhost/](wasmhost/README.md)) is the only host. It links `libwasmtime` from the upstream C API release instead of compiling wasmtime, so a cold build takes -about 4 seconds (the Rust host takes about 2 minutes). The **Rust host** -([host-wasm/](host-wasm/README.md)) serves the same `wit/host` interfaces and is kept as a -fallback until it is removed; any host change goes into both. A **native build** of the same +about 4 seconds. (An earlier host in Rust on the wasmtime crate, `host-wasm/`, was removed on +2026-11-26.) A **native build** of the same compositor code (no wasm, `just run-native`) is used by the test suite. The compositor runs **nested**, as a window on your current Wayland session, as a **login @@ -77,12 +75,11 @@ just client # start foot inside it (or: just client konsol | `just run` | Nested in a window on your Wayland session, MoonBit host | | `just run-drm` | As a login session on the real screen (from a text console, as yourself) | | `just run-x11` | On the X server in `$DISPLAY` (NVIDIA on Xorg; the whole screen when no window manager runs) | -| `just install` | Install everything: the "Chandra" display-manager session, "Chandra (X11)" for Xorg, and face unlock (asks for root once). `--link` symlinks into this checkout (later just rebuild), `--rust` / `--native` pick the Rust host / native compositor, `--pam` turns face unlock on, `--no-face` skips it | +| `just install` | Install everything: the "Chandra" display-manager session, "Chandra (X11)" for Xorg, and face unlock (asks for root once). `--link` symlinks into this checkout (later just rebuild), `--native` picks the native compositor, `--pam` turns face unlock on, `--no-face` skips it | | `just uninstall` | Remove it all again (`--purge` also deletes enrolled faces) | | `just reload` | Reload the running session's panel modules from disk (`chandra-ctl reload [NAME]`) | -| `just run-rust`, `run-drm-rust` | The same with the Rust host | | `just run-native`, `run-drm-native` | The native (non-wasm) build | -| `just compositor-wasm`, `wasmhost`, `host-wasm`, `modules` | Build one piece | +| `just compositor-wasm`, `wasmhost`, `modules` | Build one piece | | `just test` | Native compositor tests and lib tests | | `just frame` | Render one composed frame to `_build/e2e_frame.png` | | `just remote-build` | Build on a sprites.dev sprite (`CHANDRA_SPRITE`) and pull the artifacts back | @@ -225,8 +222,7 @@ wit/ WIT packages: chandra:desktop (components) and chandra:hos compositor/ the compositor in MoonBit: wayland/, shell/, scene/, raster/, kms/, network/, portal/, host/, ... components// one wasm component each: compositor, shell, panel modules (gen/ bindings + thin stub.mbt) lib/ pure, unit-tested logic (panel layout, clock, launcher, battery, task pills, ...) -wasmhost/ the default host (MoonBit + wasmtime C API) -host-wasm/ the fallback host (Rust + wasmtime) +wasmhost/ the host (MoonBit + wasmtime C API) host/ the original M0 browser/Node host (jco), kept for the component demos session/ chandra-session, chandra-root, chandra-ctl, chandra.desktop, chandra.portal, install.py config/ desktop configs, themes, app list diff --git a/compositor/host/recorder.mbt b/compositor/host/recorder.mbt index 3ed55d1..253128d 100644 --- a/compositor/host/recorder.mbt +++ b/compositor/host/recorder.mbt @@ -455,7 +455,7 @@ fn ascii(s : String) -> Array[Byte] { ///| The start of the Matroska stream sent to ffmpeg: the EBML header, a Segment of unknown size /// (it is a live stream), millisecond timestamps, and one video track of uncompressed RGBA -/// `w` x `h` frames. The hosts' writers (wasmhost raster_stub.c, host-wasm main.rs) then send +/// `w` x `h` frames. The host's writer (wasmhost raster_stub.c) then sends /// each frame as a Cluster made by `mkv_frame_header`. pub fn mkv_stream_header(w : Int, h : Int) -> Bytes { let out : Array[Byte] = [] diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0c16f05..cf81e32 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -219,7 +219,7 @@ using the **same WIT and the same build outputs** (the components are standard; only `host/` changes), then (c) from M5 as the path to real windows. The WIT stays host-agnostic: nothing in `wit/` mentions JS, a browser or a window system. What does **not** transfer is `host/src/desktop.mjs`; it is intentionally small -(~200 lines) and is the executable spec for the Rust host. +(~200 lines) and was the executable spec for the native host (now the MoonBit `wasmhost/`). ## 9. Interface catalogue @@ -255,8 +255,8 @@ Designed next (no WIT yet): `window-registry`/`wm-policy`/`decoration`, `search- ## 11. Roadmap -> Status as of 2026-11-25: M0 is done; the native host (M3) exists as the MoonBit wasmhost -> (default) and the Rust host-wasm; the compositor hosts real Wayland clients (M5, in MoonBit +> Status as of 2026-11-26: M0 is done; the native host (M3) is the MoonBit wasmhost on the +> wasmtime C API (a Rust host on the wasmtime crate came first and was removed on 2026-11-26); the compositor hosts real Wayland clients (M5, in MoonBit > rather than smithay) and runs as a DRM/KMS + libinput login session (M8). Settings, power and > clipboard from M6 are in; notifications, tray, vfs and packaging are not. @@ -274,7 +274,7 @@ Designed next (no WIT yet): `window-registry`/`wm-policy`/`decoration`, `search- ## 12. Open design questions (with recommendations) -1. **Host language/long-term host** — Rust+wasmtime native host vs trying to keep even the host in MoonBit. *Recommend Rust+wasmtime for M3; revisit MoonBit-native host only if wasmtime's C API gains full component embedding.* +1. **Host language/long-term host** — Rust+wasmtime native host vs trying to keep even the host in MoonBit. *Recommend Rust+wasmtime for M3; revisit MoonBit-native host only if wasmtime's C API gains full component embedding.* Resolved: the host is MoonBit (`wasmhost/`) on the wasmtime C API, whose component model support turned out to be enough; the Rust host was removed on 2026-11-26. 2. **Render-list vs textures** — *Recommend render-list as the default, `buffer-surface` resource only for non-vector content (§4).* 3. **UI toolkit inside components** — adopt `moon-gpui` or a tiny immediate-mode helper (`lib/ui`)? *Recommend `lib/ui` until moon-gpui has a stable scene package and a flatten-to-draw-op adapter, then migrate widget internals; keep the WIT draw-op vocabulary as the stable boundary.* 4. **Text and fonts** — host-provided shaping (`text` interface) vs components bundling a shaper. *Recommend host-provided: layout needs metrics from the same engine that rasterises.* diff --git a/docs/TOOLCHAIN.md b/docs/TOOLCHAIN.md index b33ed1c..8188bf3 100644 --- a/docs/TOOLCHAIN.md +++ b/docs/TOOLCHAIN.md @@ -1,9 +1,9 @@ # Toolchain: what works today (verified 2026-11-24) > This page records the M0 toolchain proof (browser/Node host via jco). Since then the -> components also run natively under wasmtime: the default host is the MoonBit -> [wasmhost](../wasmhost/README.md) on the wasmtime C API, with the Rust -> [host-wasm](../host-wasm/README.md) as a fallback. For the current build see the +> components also run natively under wasmtime: the host is the MoonBit +> [wasmhost](../wasmhost/README.md) on the wasmtime C API (an earlier Rust host on the +> wasmtime crate was removed on 2026-11-26). For the current build see the > [README](../README.md). Pinned versions live in `scripts/versions.env`. Everything here was run on x86_64 Linux (glibc 2.43 locally; CI uses diff --git a/docs/desktop-modules.md b/docs/desktop-modules.md index c005ac4..d60a749 100644 --- a/docs/desktop-modules.md +++ b/docs/desktop-modules.md @@ -97,9 +97,8 @@ is reported and the running instance stays (see [reloading.md](reloading.md)). ## Hosts -All three module hosts serve desktop modules: the native compositor and the MoonBit -`build/wasmhost` (both through `compositor/wasm/wasm_stub.c`) and the Rust `host-wasm` -(`src/plasmoid.rs`, bound with the `desktop-export` world). The compositor-as-wasm reaches them +Both module hosts serve desktop modules: the native compositor and the MoonBit +`build/wasmhost`, both through `compositor/wasm/wasm_stub.c`. The compositor-as-wasm reaches them through `desktop-backdrop`, `desktop-scroll`, `desktop-tick` and `publish-desktop` in `wit/host/plasmoids.wit`. The settings module reads the list through the `wallpaper` capability's `desktops`, `current-desktop` and `set-desktop` (`wit/capabilities.wit`). @@ -115,5 +114,5 @@ XDG_CONFIG_HOME=$(mktemp -d) CHANDRA_TEST_CONFIG=1 \ moon test --target native --warn-list -a -p chandra/desktop/compositor/host --filter "*desktop*" ``` -Also checked headless on `build/wasmhost` and `host-wasm` (`--gfx-out`) with `:desktop` set in +Also checked headless on `build/wasmhost` (`--gfx-out`) with `:desktop` set in state.edn. diff --git a/docs/gamerig-library.md b/docs/gamerig-library.md index c1f172e..849ba85 100644 --- a/docs/gamerig-library.md +++ b/docs/gamerig-library.md @@ -61,8 +61,8 @@ capability (`wit/capabilities.wit`): rig's X server through server.py, exactly as from the web library, and Openbox stacks them over Chandra's window. -Served by every host: the wasmer/wasmtime stub (`compositor/wasm/wasm_stub.c`), the MoonBit -wasmhost and the Rust `host-wasm`. +Served by every host: the wasmer/wasmtime stub (`compositor/wasm/wasm_stub.c`), and the MoonBit +wasmhost. Code: `components/gamerig-library` (bindings and a thin stub), `lib/gamelib` (model, JSON, layout, drawing, input; tests in `lib/gamelib/gamelib_test.mbt`), `compositor/shell/gamelib.mbt` diff --git a/docs/install.md b/docs/install.md index cb69b12..2677878 100644 --- a/docs/install.md +++ b/docs/install.md @@ -26,7 +26,6 @@ for a new compositor or host; `just reload` picks up new panel modules in a runn | Flag | What it changes | |---|---| | `--link` | Symlink the session into this checkout instead of copying: after that, rebuilding (`just compositor-wasm wasmhost modules`) is all the next login needs, no root. The checkout must stay where it is. Face unlock is copied either way. | -| `--rust` | Use the Rust host (`host-wasm`, about 2 minutes to build cold) instead of the MoonBit one | | `--native` | Install the native compositor (system-cc release build) instead of the wasm one | | `--pam` | Also turn face unlock on for `polkit-1` and `sudo` (Settings > Session can do it later) | | `--no-face` | Leave face unlock out | diff --git a/docs/reloading.md b/docs/reloading.md index 27efe23..0ff94df 100644 --- a/docs/reloading.md +++ b/docs/reloading.md @@ -113,7 +113,7 @@ starting with `ok` or `error`. Several commands may be sent on one connection. The compositor handles the socket in its main loop (`compositor/host/control.mbt`, from `ChandraCompositor::step`), and the listening socket and its clients are among the fds the idle loop waits on, so an idle desktop still sleeps (about 0.4% CPU, unchanged) and wakes for a -command. It is the same code on the MoonBit host, the Rust host and the native build. +command. It is the same code on the MoonBit host and the native build. ## Not reloadable @@ -125,7 +125,7 @@ WM, portal backend or host need a new session: log out and back in. ## Status -Tested headless on both hosts (`build/wasmhost` and `host-wasm`) with the modules from -`build/components`: `ping`, `list`, `reload`, `reload NAME`, a module replaced by a broken file +Tested headless on `build/wasmhost` (and on the Rust host, since removed) with the modules +from `build/components`: `ping`, `list`, `reload`, `reload NAME`, a module replaced by a broken file (reported, old instance kept), SIGUSR1, and idle CPU before and after. Tests: `compositor/host/control_test.mbt`. Not yet run against an installed login session. diff --git a/docs/rendering.md b/docs/rendering.md index dbe12d9..d1d1835 100644 --- a/docs/rendering.md +++ b/docs/rendering.md @@ -1,7 +1,7 @@ # Rendering, animations and machines without a GPU -Chandra draws the desktop on the CPU on every machine: the host (build/wasmhost, or the Rust -host) rasterises each frame into its own framebuffer and hands it to the display (KMS, X11, a +Chandra draws the desktop on the CPU on every machine: the host (build/wasmhost) +rasterises each frame into its own framebuffer and hands it to the display (KMS, X11, a nested Wayland window). A GPU never makes Chandra's own frames cheaper. What it changes is how much CPU is left: with a GPU, apps (browsers, video, games) draw there; without one they draw with llvmpipe or their own software paths on the same cores as Chandra. diff --git a/docs/run0.md b/docs/run0.md index 7713b25..6cb1c2b 100644 --- a/docs/run0.md +++ b/docs/run0.md @@ -15,7 +15,7 @@ Everything below works with sudo, doas or pkexec too; run0 is only preferred whe ## Installing the login session ```bash -just install # flags: --link, --rust, --native, --pam, --no-face; and `just uninstall` +just install # flags: --link, --native, --pam, --no-face; and `just uninstall` ``` These go through `scripts/as-root`, which uses run0 if systemd is PID 1 and run0 is installed, diff --git a/docs/window-frames.md b/docs/window-frames.md index e6e16a1..7740d3e 100644 --- a/docs/window-frames.md +++ b/docs/window-frames.md @@ -52,8 +52,7 @@ right and 6px down. Hover and pressed show as a ring around the button. - `compositor/scene/scene.mbt`: `WindowStyle` (frame sizes, button layout and hit test, `button_at`) and `build_window_decoration`, which returns the frame as draw ops in the frame's own coordinates, shadow included. Every host draws them as they are: the software renderer - (compositor/renderer), the MoonBit host (wasmhost/bin/raster.mbt) and the Rust host - (host-wasm/src/raster.rs) have no shadow of their own and redraw `SHADOW_PAD` (18px) around a + (compositor/renderer) and the MoonBit host (wasmhost/bin/raster.mbt) have no shadow of their own and redraw `SHADOW_PAD` (18px) around a window that changed. - `compositor/host/compositor.mbt`: `window_style` (the style in use; `frame_top()`, `frame_side()`, `frame_rect()`), `sync_window_style` (applies the setting: the work area, the diff --git a/host-wasm/Cargo.lock b/host-wasm/Cargo.lock deleted file mode 100644 index 9882c98..0000000 --- a/host-wasm/Cargo.lock +++ /dev/null @@ -1,1493 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "ab_glyph" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" -dependencies = [ - "ab_glyph_rasterizer", - "owned_ttf_parser", -] - -[[package]] -name = "ab_glyph_rasterizer" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" - -[[package]] -name = "addr2line" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59317f77929f0e679d39364702289274de2f0f0b22cbf50b2b8cff2169a0b27a" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "allocator-api2" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" - -[[package]] -name = "anyhow" -version = "1.0.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" - -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" - -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bumpalo" -version = "3.20.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" -dependencies = [ - "allocator-api2", -] - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" - -[[package]] -name = "cc" -version = "1.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "chandra-host" -version = "0.1.0" -dependencies = [ - "ab_glyph", - "ab_glyph_rasterizer", - "cc", - "libc", - "png 0.17.16", - "resvg", - "wasmtime", -] - -[[package]] -name = "cobs" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" -dependencies = [ - "thiserror", -] - -[[package]] -name = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - -[[package]] -name = "cpp_demangle" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0667304c32ea56cb4cd6d2d7c0cfe9a2f8041229db8c033af7f8d69492429def" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cranelift-assembler-x64" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147e998317ed418623afd8dc719b3413d391a3b2f048100f459a90dadfd4fd72" -dependencies = [ - "cranelift-assembler-x64-meta", -] - -[[package]] -name = "cranelift-assembler-x64-meta" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775c4e3222b290bc05e07e73e0cfab0b3b4c6510034f70585fa7cbf4feb9f0ea" -dependencies = [ - "cranelift-srcgen", -] - -[[package]] -name = "cranelift-bforest" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f64e582cbf252e01cbcf4c701b26a349fab461a9f0c327025995db64b1364a78" -dependencies = [ - "cranelift-entity", - "wasmtime-internal-core", -] - -[[package]] -name = "cranelift-bitset" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba37434039b4cdc98d3178eefca3f5bd180b955e49c0787e9cc0eee3de182fcb" -dependencies = [ - "serde", - "serde_derive", - "wasmtime-internal-core", -] - -[[package]] -name = "cranelift-codegen" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028652607246c4117796ed9ab9e966994b4ee12146b329a91e85c8fd1335152f" -dependencies = [ - "bumpalo", - "cranelift-assembler-x64", - "cranelift-bforest", - "cranelift-bitset", - "cranelift-codegen-meta", - "cranelift-codegen-shared", - "cranelift-control", - "cranelift-entity", - "cranelift-isle", - "gimli", - "hashbrown 0.17.2", - "libm", - "log", - "postcard", - "pulley-interpreter", - "regalloc2", - "rustc-hash", - "serde", - "serde_derive", - "sha2", - "smallvec", - "target-lexicon", - "wasmtime-internal-core", -] - -[[package]] -name = "cranelift-codegen-meta" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21ba849e90d3398951aef9a9a3d2fa1e7df6196836ae1d0723ec24b091215b84" -dependencies = [ - "cranelift-assembler-x64-meta", - "cranelift-codegen-shared", - "cranelift-srcgen", - "heck", - "pulley-interpreter", -] - -[[package]] -name = "cranelift-codegen-shared" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6116ab06dc15034ee1b4e3124371acb6742c189b438040837aeb0cfcf790e356" - -[[package]] -name = "cranelift-control" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33a932ab1cef0158e6b0f0360139d5d19bdf7a3bee0160f02865b1bdafb218c7" -dependencies = [ - "arbitrary", -] - -[[package]] -name = "cranelift-entity" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c048097f9ae9b7c23db66e6f35882f6e1fbcd522f3db2a520d5c7aaa0079a67" -dependencies = [ - "cranelift-bitset", - "serde", - "serde_derive", - "wasmtime-internal-core", -] - -[[package]] -name = "cranelift-frontend" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b45328ff7bac253860079032352989eae50341e155ddd4c6cfb8f5d40c490fa" -dependencies = [ - "cranelift-codegen", - "hashbrown 0.17.2", - "log", - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cranelift-isle" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff643d297ee16c7a8a6aba6bf526b610879635275ec14e7ee75b94f0b46e9514" - -[[package]] -name = "cranelift-native" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66b186c9de1edc598d055ff3f13918fc8f49d3e23811b99ab45a3cbf52dc2a7b" -dependencies = [ - "cranelift-codegen", - "libc", - "mach2", - "target-lexicon", -] - -[[package]] -name = "cranelift-srcgen" -version = "0.137.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e30dff68753c0933cb30eb445d75d6b3cdcc0f7f0121b9c5aaabbe4a8315617d" - -[[package]] -name = "crc32fast" -version = "1.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "data-url" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", -] - -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" - -[[package]] -name = "embedded-io" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" - -[[package]] -name = "embedded-io" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" - -[[package]] -name = "encoding_rs" -version = "0.8.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" -dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", -] - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "errno" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "euclid" -version = "0.22.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" -dependencies = [ - "num-traits", -] - -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" - -[[package]] -name = "flate2" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" -dependencies = [ - "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", -] - -[[package]] -name = "float-cmp" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "futures" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "gimli" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" -dependencies = [ - "fnv", - "hashbrown 0.16.1", - "indexmap", - "stable_deref_trait", -] - -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" - -[[package]] -name = "hashbrown" -version = "0.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" -dependencies = [ - "foldhash", - "serde", - "serde_core", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - -[[package]] -name = "imagesize" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown 0.17.2", - "serde", - "serde_core", -] - -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - -[[package]] -name = "kurbo" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" -dependencies = [ - "arrayvec", - "euclid", - "polycool", - "smallvec", -] - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" - -[[package]] -name = "mach2" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "memfd" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" -dependencies = [ - "rustix", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "object" -version = "0.40.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" -dependencies = [ - "crc32fast", - "hashbrown 0.17.2", - "indexmap", - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "owned_ttf_parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" -dependencies = [ - "ttf-parser", -] - -[[package]] -name = "pico-args" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" - -[[package]] -name = "pin-project-lite" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" - -[[package]] -name = "png" -version = "0.17.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "png" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" -dependencies = [ - "bitflags 2.13.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "polycool" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" -dependencies = [ - "arrayvec", -] - -[[package]] -name = "postcard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5431b3dcfdf6d1985c87d11f267a171c0dec0a8cd544c6727b747d36365f1fca" -dependencies = [ - "cobs", - "embedded-io 0.4.0", - "embedded-io 0.6.1", - "serde", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pulley-interpreter" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aeb7ed128aa5734a9bbad079eede1861ffd6362745cb595967f9fb78e2eba3de" -dependencies = [ - "cranelift-bitset", - "log", - "pulley-macros", - "wasmtime-internal-core", -] - -[[package]] -name = "pulley-macros" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f56330a5820c87d062fe79e3e2fa68dd96d4f6f11a3e299dcf16df35acc02b19" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "regalloc2" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34f923657880712029496c2e68bb40bef163806b2011adde559b28bbcedc82ea" -dependencies = [ - "allocator-api2", - "bumpalo", - "hashbrown 0.17.2", - "log", - "rustc-hash", - "serde", - "smallvec", -] - -[[package]] -name = "resvg" -version = "0.50.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77bb4b284cf8a5c8ae721594af53387fb755d2196fddb32b2acfb4fa9251fa0c" -dependencies = [ - "bytemuck", - "log", - "pico-args", - "rgb", - "svgtypes", - "tiny-skia", - "usvg", -] - -[[package]] -name = "rgb" -version = "0.8.53" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "roxmltree" -version = "0.21.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" -dependencies = [ - "memchr", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustix" -version = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys", - "windows-sys", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "simplecss" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" -dependencies = [ - "log", -] - -[[package]] -name = "siphasher" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" -dependencies = [ - "serde", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "strict-num" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" -dependencies = [ - "float-cmp", -] - -[[package]] -name = "svgtypes" -version = "0.16.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" -dependencies = [ - "kurbo", - "siphasher", -] - -[[package]] -name = "syn" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "target-lexicon" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" - -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "thiserror" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tiny-skia" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" -dependencies = [ - "arrayref", - "arrayvec", - "bytemuck", - "cfg-if", - "log", - "png 0.18.1", - "tiny-skia-path", -] - -[[package]] -name = "tiny-skia-path" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9" -dependencies = [ - "arrayref", - "bytemuck", - "strict-num", -] - -[[package]] -name = "ttf-parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "usvg" -version = "0.50.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdb896f04730b97805bbc3191fc57e4bf03face0f14577dd42e783c4d8c98802" -dependencies = [ - "data-url", - "imagesize", - "kurbo", - "log", - "pico-args", - "roxmltree", - "simplecss", - "siphasher", - "strict-num", - "svgtypes", - "tiny-skia-path", -] - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wasm-encoder" -version = "0.261.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2608e8bb6d67fd68f5a8d0eb1363d6e7bcbc1f8ded5a0bd3a1e382462b876b22" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.261.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b88de21560ecd49deb8d8f1616b9b695f66fc312c5eca503f43accdc5795339e" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.261.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" -dependencies = [ - "bitflags 2.13.2", - "hashbrown 0.17.2", - "indexmap", - "semver", - "serde", -] - -[[package]] -name = "wasmprinter" -version = "0.261.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7" -dependencies = [ - "anyhow", - "termcolor", - "wasmparser", -] - -[[package]] -name = "wasmtime" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3231d67bedf0f4849558b01ee5accd0283469cff7ee6746ce6a9742ddc178312" -dependencies = [ - "addr2line", - "async-trait", - "bitflags 2.13.2", - "bumpalo", - "cc", - "encoding_rs", - "futures", - "libc", - "log", - "mach2", - "memfd", - "object", - "once_cell", - "postcard", - "pulley-interpreter", - "rustix", - "semver", - "serde", - "serde_derive", - "smallvec", - "target-lexicon", - "wasmparser", - "wasmtime-environ", - "wasmtime-internal-component-macro", - "wasmtime-internal-component-util", - "wasmtime-internal-core", - "wasmtime-internal-cranelift", - "wasmtime-internal-fiber", - "wasmtime-internal-jit-debug", - "wasmtime-internal-jit-icache-coherence", - "wasmtime-internal-unwinder", - "wasmtime-internal-versioned-export-macros", - "windows-sys", -] - -[[package]] -name = "wasmtime-environ" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a24cca20d8f3525071fcc71c0de558c754894934c43fb5550b4d23ada3523e92" -dependencies = [ - "anyhow", - "cpp_demangle", - "cranelift-bforest", - "cranelift-bitset", - "cranelift-entity", - "gimli", - "hashbrown 0.17.2", - "indexmap", - "log", - "object", - "postcard", - "rustc-demangle", - "semver", - "serde", - "serde_derive", - "smallvec", - "target-lexicon", - "wasm-encoder", - "wasmparser", - "wasmprinter", - "wasmtime-internal-component-util", - "wasmtime-internal-core", -] - -[[package]] -name = "wasmtime-internal-component-macro" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3e7b4191a7e411836b8d34cfcd20360dc134d897e9583a3686262b422643036" -dependencies = [ - "anyhow", - "proc-macro2", - "quote", - "syn", - "wasmtime-internal-component-util", - "wasmtime-internal-wit-bindgen", - "wit-parser", -] - -[[package]] -name = "wasmtime-internal-component-util" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d58085475f745779eb5c2d5cd3d60695d280d9c2cf261f7e96e9949b293f7a82" - -[[package]] -name = "wasmtime-internal-core" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4668db5cde6343ae9c7c188741689d30bcefa40c70647b87be2afb2c14511aa" -dependencies = [ - "hashbrown 0.17.2", - "libm", - "serde", -] - -[[package]] -name = "wasmtime-internal-cranelift" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c5744433223d6dca55e8933510f73cf7e2aa06ca53e3f039fd3c309e315546a" -dependencies = [ - "cranelift-codegen", - "cranelift-control", - "cranelift-entity", - "cranelift-frontend", - "cranelift-native", - "gimli", - "itertools", - "log", - "object", - "pulley-interpreter", - "smallvec", - "target-lexicon", - "thiserror", - "wasmparser", - "wasmtime-environ", - "wasmtime-internal-core", - "wasmtime-internal-unwinder", - "wasmtime-internal-versioned-export-macros", -] - -[[package]] -name = "wasmtime-internal-fiber" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ead05f9d1428e98562bef6d3c42c5c9911ac25373e9d5f6d81fa26a3efb74ae3" -dependencies = [ - "cc", - "libc", - "rustix", - "wasmtime-environ", - "wasmtime-internal-versioned-export-macros", - "windows-sys", -] - -[[package]] -name = "wasmtime-internal-jit-debug" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ea96d3eac206f9e088ebfc13a27f6353bdaa6a9e467e0ba9b05e00c79cee27" -dependencies = [ - "cc", - "wasmtime-internal-versioned-export-macros", -] - -[[package]] -name = "wasmtime-internal-jit-icache-coherence" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62a0d73e89a065e74332c8651d27bbc9fa1e4c7357ff219c3929aa9c02b6a31e" -dependencies = [ - "libc", - "wasmtime-internal-core", - "windows-sys", -] - -[[package]] -name = "wasmtime-internal-unwinder" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b413aca82d92129c193752d8109c1101d2b49090ea8e3028d7c7514dbb9750c2" -dependencies = [ - "cranelift-codegen", - "log", - "object", - "wasmtime-environ", -] - -[[package]] -name = "wasmtime-internal-versioned-export-macros" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e084771993bee8dd7dd0af42f10b56e1f665d67c8adbef340991e268b03289d1" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "wasmtime-internal-wit-bindgen" -version = "50.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "735a94d76f9b7f34b3fdb3181ac1f4234b5b0c9916b1b54a840c399e209cccda" -dependencies = [ - "anyhow", - "bitflags 2.13.2", - "heck", - "indexmap", - "wit-component", - "wit-parser", -] - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "wit-component" -version = "0.261.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2818766842bd2321074c348fb5c15d8fdb105a9eb78374e6d77c7d4127e1f2f9" -dependencies = [ - "anyhow", - "bitflags 2.13.2", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.261.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "962e43c4db2da607b50839a531e5b63473268b40efdf8028d5c54b572ca4f6f6" -dependencies = [ - "anyhow", - "hashbrown 0.17.2", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-ident", - "wasmparser", -] - -[[package]] -name = "zlib-rs" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/host-wasm/Cargo.toml b/host-wasm/Cargo.toml deleted file mode 100644 index 335d492..0000000 --- a/host-wasm/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "chandra-host" -version = "0.1.0" -edition = "2021" -description = "Runs the chandra compositor wasm component (build/components/compositor.wasm) and gives it the OS surface it imports (wit/host/sys.wit)." - -[features] -# Login-session display backend (DRM/KMS + libinput + libseat + xkbcommon). Needs those libraries' -# development files; build with --no-default-features to leave it out (--drm then reports it). -default = ["drm"] -drm = ["dep:cc"] - -[build-dependencies] -cc = { version = "1", optional = true } - -[dependencies] -ab_glyph = "0.2" -ab_glyph_rasterizer = "0.1" -libc = "0.2" -png = "0.17" -resvg = { version = "0.50.0", default-features = false } -wasmtime = { version = "50", default-features = false, features = ["component-model", "cranelift", "runtime", "std"] } - -[profile.release] -opt-level = 2 -# Recompile only what changed in this crate (dependencies are unaffected): an edit to main.rs or -# raster.rs rebuilds in about 3 s instead of 6.5 s. The cold build is dominated by wasmtime and -# cranelift (about 2 min on 4 cores), which this does not change. -incremental = true diff --git a/host-wasm/README.md b/host-wasm/README.md deleted file mode 100644 index c8abb4a..0000000 --- a/host-wasm/README.md +++ /dev/null @@ -1,82 +0,0 @@ -# chandra-host (Rust, fallback) - -Runs the compositor **as a WebAssembly component**. The default host is now the MoonBit one in -[`wasmhost/`](../wasmhost/README.md), which builds in seconds; this crate compiles wasmtime (about -2 minutes cold) and is kept as a fallback until it is removed. Both serve the same `wit/host`. - -``` -just compositor-wasm # build/compositor.wasm (the compositor, a component) -just host-wasm # host-wasm/target/release/chandra-host (this crate) -just run-rust # both, then run in a window on your current Wayland session -``` - -The component (`components/compositor`, entry in `compositor/app`) imports exactly one interface, -`chandra:host/sys` ([`wit/host/sys.wit`](../wit/host/sys.wit)), and exports `run(args) -> s32`. -It is the same MoonBit code as the native compositor: the Wayland server, window manager, scene, -rasteriser and shell. Only `compositor/sys` differs per target (`sys_native.mbt` over a C shim, -`sys_wasm.mbt` over the WIT imports). The component holds integer handles and bytes only; every real -file descriptor lives in this host, which implements `sys` with libc (sockets and `SCM_RIGHTS`, -`memfd`, `poll`, spawn, files, clock). - -``` -chandra-host build/compositor.wasm --socket PATH [--theme PATH] [--window] -chandra-host build/compositor.wasm --socket PATH --gfx-out frame.png # one frame -chandra-host build/compositor.wasm --socket PATH --gfx-out frame.png --serve # keep refreshing it -``` - -## Drawing - -The compositor component decides what the screen shows and the host draws it -(`chandra:host/raster`, [`wit/host/raster.wit`](../wit/host/raster.wit)). Each frame the component -sends a list of draw operations (fill, stroke, line, circle, text, clip), the windows with their -decoration ops and a surface id, and the panel ops; `src/raster.rs` draws them natively into a -framebuffer it owns (a port of `compositor/renderer`, with the same blend arithmetic). The pixels never -cross the component boundary: - -- **Client windows:** at commit the host copies the buffer out of the client's shared memory into a - surface (`capture`, converted to RGBA once) and the component keeps only its id. Solid surfaces blit - as row copies. -- **Backdrop:** the wallpaper and the desktop card are cached as one layer and sent only when they change. -- **Showing it:** the login session shows the framebuffer straight from the host (`display.present-frame`); - the nested window gets it as a memfd (`raster.export-memfd`) that goes to the host compositor as a - `wl_shm` pool. `read-frame` returns the pixels for screenshots (`--gfx-out`). -- **Unchanged desktop:** if a scene is identical to the last one (no client damage, same ops) nothing is - sent or presented. -- `--profile` prints, every 3 s, frames, step, shell and draw (submit) time. -- **Session restore:** the windows open when a session ends are kept in `state.edn` (`:session`) and - their apps are started again at the next start. `--no-restore`, or `:restore-session false` in - `state.edn`, starts with an empty desktop instead. - -The native compositor build keeps the software renderer (`compositor/renderer`); the two are tested -against each other's rules (`cargo test` here, `moon test` for the MoonBit side). - -## Status - -Working: Wayland server (real clients such as `foot` run and draw), window management, decorations, -the desktop card, input routing, the nested window on the host session, real fonts (Allo Variable, -Adwaita Mono: the host rasterises glyphs, `chandra:host/font`) and the panel modules. - -**Panel modules** run in this host. A component can't embed a second runtime, so the compositor -drives them through `chandra:host/plasmoids` ([`wit/host/plasmoids.wit`](../wit/host/plasmoids.wit)): -load, render, popup, on-event, plus the data they read (apps, windows, layouts, modules, system -snapshot) and the requests they make (launch, focus, set layout, load/unload). `src/plasmoid.rs` -instantiates each module as a real component against one world, `plasmoid-host` -([`wit/worlds.wit`](../wit/worlds.wit)); a module imports the subset of host interfaces it needs and -each is served here. `cargo test --release` loads the built modules (`just modules` first). - -**Login session** (`--drm`): the host takes the display and input through the seat -(`chandra:host/display`, [`wit/host/display.wit`](../wit/host/display.wit)): DRM/KMS output with page -flips and a hardware cursor, libinput keyboard and pointer, an xkb keymap, libseat for device access and -VT switching. It is the compositor's own C shim (`compositor/kms/kms_stub.c`) compiled into this host -by `build.rs` (feature `drm`, on by default; `--no-default-features` leaves it out), so the native and -wasm backends can't drift. Run `just run-drm` from a login VT, or `just install` to add Moon -Plasma to your display manager (`session/install.py`; `--native` installs the native compositor instead). -Not yet exercised on a real VT; it is only built and instantiated. - -Regenerating the host bindings (into a temp dir, then copy `interface/chandra/host`, -`world/compositor` and `components/compositor/gen/{ffi.mbt,world}`; regenerating in place would -overwrite the hand-fixed `desktop/theme` package): -`wit-bindgen moonbit wit/host --world compositor --out-dir $T --gen-dir components/compositor/gen ---project-name chandra/desktop --ignore-module-file --ignore-stub`, then -`scripts/gen-native-stubs.py interface/chandra/host/` (the imports are -wasm-only; this restores the native stand-ins and the per-file targets). diff --git a/host-wasm/build.rs b/host-wasm/build.rs deleted file mode 100644 index 6398e5e..0000000 --- a/host-wasm/build.rs +++ /dev/null @@ -1,25 +0,0 @@ -// The login-session display backend (feature `drm`, on by default) compiles the compositor's own -// C shim for DRM/KMS + libinput + libseat + xkbcommon and links the libraries it uses. -fn main() { - #[cfg(feature = "drm")] - { - cc::Build::new() - .file("csrc/kms.c") - .include("csrc/fake") - .include("/usr/include/libdrm") - .warnings(false) - .compile("kms"); - for lib in ["drm", "input", "seat", "xkbcommon", "udev"] { - println!("cargo:rustc-link-lib={lib}"); - } - // libseat comes from the pixi env (see pixi.toml). Record its lib dir in the binary so - // the login session finds it without LD_LIBRARY_PATH, which apps started by the - // compositor would inherit. - let pixi_lib = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.pixi/envs/default/lib"); - if let Ok(dir) = pixi_lib.canonicalize() { - println!("cargo:rustc-link-arg-bins=-Wl,-rpath,{}", dir.display()); - } - println!("cargo:rerun-if-changed=csrc/kms.c"); - println!("cargo:rerun-if-changed=../compositor/kms/kms_stub.c"); - } -} diff --git a/host-wasm/csrc/fake/moonbit.h b/host-wasm/csrc/fake/moonbit.h deleted file mode 100644 index eb55086..0000000 --- a/host-wasm/csrc/fake/moonbit.h +++ /dev/null @@ -1,9 +0,0 @@ -/* Just enough of moonbit.h for compositor/kms/kms_stub.c to build outside the MoonBit runtime. - * The shim uses MoonBit only for the export macro and the length of byte arrays it is handed; - * csrc/kms.c supplies the length through kms_bytes_len. */ -#pragma once -#include -#define MOONBIT_FFI_EXPORT -typedef uint8_t *moonbit_bytes_t; -extern int32_t kms_bytes_len; -#define Moonbit_array_length(p) (kms_bytes_len) diff --git a/host-wasm/csrc/kms.c b/host-wasm/csrc/kms.c deleted file mode 100644 index 4e3320b..0000000 --- a/host-wasm/csrc/kms.c +++ /dev/null @@ -1,19 +0,0 @@ -/* The login-session display backend for the wasm host: the same C file the native compositor uses - * (libseat + DRM/KMS dumb buffers + libinput + xkbcommon), compiled here against a stand-in - * moonbit.h, so the two backends can't drift. The mp_kms_* functions are called from Rust. */ -#include - -int32_t kms_bytes_len; - -#include "../../compositor/kms/kms_stub.c" - -/* The two shim functions that take a MoonBit byte array need its length. */ -int32_t hw_kms_present(uint8_t *pixels, int32_t w, int32_t h) { - kms_bytes_len = w * h * 4; - return mp_kms_present(pixels, w, h); -} - -int32_t hw_kms_keymap_copy(uint8_t *out, int32_t cap) { - kms_bytes_len = cap; - return mp_kms_keymap_copy(out); -} diff --git a/host-wasm/src/kms.rs b/host-wasm/src/kms.rs deleted file mode 100644 index 76ac209..0000000 --- a/host-wasm/src/kms.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! The login-session display backend: calls into compositor/kms/kms_stub.c (built by build.rs), -//! the same shim the native compositor uses. One display, one seat, global state. - -use crate::chandra::host::display::{KeyState, Modifiers, Output, PointerPos, ScrollDelta, SeatEvent}; - -extern "C" { - fn mp_kms_open() -> i32; - fn mp_kms_width() -> i32; - fn mp_kms_height() -> i32; - fn mp_kms_quit_requested() -> i32; - fn mp_kms_poll() -> i32; - fn mp_kms_frame_ready() -> i32; - fn mp_kms_set_cursor_shape(shape: i32); - fn mp_kms_next_event() -> i32; - fn mp_kms_arg(i: i32) -> i32; - fn mp_kms_keymap_len() -> i32; - fn mp_kms_close(); - fn mp_kms_fd(i: i32) -> i32; - fn mp_kms_set_power(on: i32); - fn hw_kms_present(pixels: *mut u8, w: i32, h: i32) -> i32; - fn hw_kms_keymap_copy(out: *mut u8, cap: i32) -> i32; -} - -/// Open the seat, the first connected output and libinput. None (the shim has said why on stderr) -/// when this is not an active login VT. -pub fn open() -> Option { - unsafe { - if mp_kms_open() != 0 { - mp_kms_close(); - return None; - } - let n = mp_kms_keymap_len(); - let mut keymap = vec![0u8; n.max(0) as usize]; - let got = if n > 0 { hw_kms_keymap_copy(keymap.as_mut_ptr(), n) } else { 0 }; - keymap.truncate(got.max(0) as usize); - Some(Output { width: mp_kms_width() as u32, height: mp_kms_height() as u32, keymap }) - } -} - -/// Service the seat, DRM and input fds. False once Ctrl+Alt+Backspace was pressed. -pub fn poll() -> bool { - unsafe { - mp_kms_poll(); - mp_kms_quit_requested() == 0 - } -} - -/// The seat, DRM and input fds while the display is open (empty otherwise), for an idle wait. -pub fn fds() -> Vec { - (0..3).map(|i| unsafe { mp_kms_fd(i) }).filter(|&fd| fd >= 0).collect() -} - -pub fn frame_ready() -> bool { - unsafe { mp_kms_frame_ready() != 0 } -} - -/// Present an RGBA8888 frame; ignored if the buffer is smaller than the stated size. -pub fn present(pixels: &[u8], width: u32, height: u32) { - if pixels.len() < (width as usize) * (height as usize) * 4 { - return; - } - // The shim only reads the pixels; it takes a non-const pointer for the MoonBit byte type. - unsafe { hw_kms_present(pixels.as_ptr() as *mut u8, width as i32, height as i32) }; -} - -/// Turn the screen on or off (DPMS). -pub fn set_power(on: bool) { - unsafe { mp_kms_set_power(on as i32) }; -} - -pub fn set_cursor_shape(shape: u32) { - unsafe { mp_kms_set_cursor_shape(shape as i32) }; -} - -/// Input queued since the last call. -pub fn take_input() -> Vec { - let mut out = Vec::new(); - unsafe { - loop { - let t = mp_kms_next_event(); - if t == 0 { - break; - } - let (a, b) = (mp_kms_arg(1), mp_kms_arg(2)); - match t { - 1 => out.push(SeatEvent::PointerMove(PointerPos { x: a as f64, y: b as f64 })), - 2 => out.push(SeatEvent::PointerButton(KeyState { code: a as u32, pressed: b != 0 })), - 3 => out.push(SeatEvent::Key(KeyState { code: a as u32, pressed: b != 0 })), - 4 => out.push(SeatEvent::Modifiers(Modifiers { - depressed: a as u32, - latched: b as u32, - locked: mp_kms_arg(3) as u32, - group: mp_kms_arg(4) as u32, - })), - 5 => out.push(SeatEvent::Scroll(ScrollDelta { - axis: a as u32, - value: b as f64 / 256.0, - discrete: mp_kms_arg(3), - })), - _ => {} - } - } - } - out -} - -pub fn close() { - unsafe { mp_kms_close() }; -} diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs deleted file mode 100644 index a6fa0e6..0000000 --- a/host-wasm/src/main.rs +++ /dev/null @@ -1,1232 +0,0 @@ -//! Native host for the chandra compositor component. -//! -//! The compositor is a wasm component (build/compositor.wasm) that imports exactly one -//! interface, `chandra:host/sys` (wit/host/sys.wit): sockets, memfd, poll, spawn, files, time. -//! This program is the other side of that interface. The component only ever holds integer -//! handles; every real file descriptor lives here. -//! -//! chandra-host [--component PATH] [-- compositor args...] -//! chandra-host build/compositor.wasm --socket /run/user/1000/wayland-moon-0 --window - -use std::ffi::CString; -use std::sync::atomic::AtomicBool; -use std::io::Read; -use std::os::unix::process::CommandExt; -use std::process::{Command, Stdio}; -use wasmtime::component::{Component, HasSelf, Linker}; -use wasmtime::{Config, Engine, Result, Store}; - -mod plasmoid; -mod raster; -#[cfg(feature = "drm")] -mod kms; - -wasmtime::component::bindgen!({ - path: "../wit/host", - world: "compositor", - // The desktop value types are the same WIT the modules use: share the Rust types, so draw ops - // flow from a module straight to the compositor without conversion. - // Draw operations are compared to reuse the cached wallpaper. - additional_derives: [PartialEq], - with: { - "chandra:desktop/types@0.1.0": plasmoid::ph::chandra::desktop::types, - "chandra:desktop/theme@0.1.0": plasmoid::ph::chandra::desktop::theme, - }, -}); - -use chandra::host::font::Glyph; -use chandra::host::sys::{Host, Received}; - -/// SIGUSR1 (reload the panel modules) arrived and not yet taken by sys.take-sigusr1; whether -/// its handler is installed. -static SIGUSR1_SEEN: AtomicBool = AtomicBool::new(false); -static SIGUSR1_INSTALLED: AtomicBool = AtomicBool::new(false); - -#[derive(Default)] -struct State { - /// Address of the private session bus launched apps use (started on first spawn). - private_bus: Option, - bus_tried: bool, - started: Option, - /// TTF faces loaded by the component (`font.load`), by slot, and their glyph cache. - fonts: raster::Fonts, - /// The framebuffer and client surfaces behind `chandra:host/raster`. - raster: raster::Raster, - /// Runs the panel modules; set once the engine exists. - pl: Option, - /// Fds beyond the first that arrived with the last `recvmsg` on a socket, for `take-fd`. - extra_fds: std::collections::HashMap>, - /// The screen recording's frame queue and writer thread (`grab-recording-frame`, - /// `send-recording-frame`). - rec: Recorder, - /// The frozen screen of a screenshot (`snapshot-frame`): RGBA8888, its width and height. - snap: Vec, - snap_w: i32, - snap_h: i32, -} - -fn sockaddr_un(path: &str) -> (libc::sockaddr_un, libc::socklen_t) { - let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() }; - addr.sun_family = libc::AF_UNIX as libc::sa_family_t; - let bytes = path.as_bytes(); - let n = bytes.len().min(addr.sun_path.len() - 1); - for (i, b) in bytes[..n].iter().enumerate() { - addr.sun_path[i] = *b as libc::c_char; - } - (addr, std::mem::size_of::() as libc::socklen_t) -} - -fn set_nonblock_cloexec(fd: i32) { - unsafe { - let fl = libc::fcntl(fd, libc::F_GETFL, 0); - if fl >= 0 { - libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); - } - let fdfl = libc::fcntl(fd, libc::F_GETFD, 0); - if fdfl >= 0 { - libc::fcntl(fd, libc::F_SETFD, fdfl | libc::FD_CLOEXEC); - } - } -} - -impl State { - /// A private session bus, so single-instance apps (Firefox, Kate, Dolphin...) don't forward - /// their launch to an instance on the host session. Dies with this process. - /// - /// Only when nested inside another graphical session (WAYLAND_DISPLAY or DISPLAY set). As a - /// login session (--drm from a VT or the display manager) the session bus *is* ours, and it is - /// where the PAM-unlocked gnome-keyring (org.freedesktop.secrets), portals and notifications - /// live: a private bus would hide them, so apps D-Bus-activate a fresh, locked keyring on it. - fn private_bus(&mut self) -> Option { - if self.bus_tried { - return self.private_bus.clone(); - } - self.bus_tried = true; - let nested = ["WAYLAND_DISPLAY", "DISPLAY"] - .iter() - .any(|v| std::env::var_os(v).map(|x| !x.is_empty()).unwrap_or(false)); - if !nested { - return None; - } - let mut cmd = Command::new("dbus-daemon"); - cmd.args(["--session", "--nofork", "--print-address=1"]) - .stdout(Stdio::piped()) - .stderr(Stdio::null()); - unsafe { - cmd.pre_exec(|| { - libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM); - Ok(()) - }); - } - let mut child = cmd.spawn().ok()?; - let mut out = child.stdout.take()?; - let mut buf = [0u8; 256]; - let n = out.read(&mut buf).unwrap_or(0); - std::mem::forget(child); // keep it running; PDEATHSIG ends it with us - std::mem::forget(out); - if n > 0 { - let s = String::from_utf8_lossy(&buf[..n]); - self.private_bus = s.lines().next().map(|l| l.to_string()); - } - self.private_bus.clone() - } -} - -impl State { - fn pl(&mut self) -> &mut plasmoid::Runtime { - self.pl.as_mut().expect("plasmoid runtime is set before the component runs") - } -} - -impl chandra::host::plasmoids::Host for State { - fn load(&mut self, path: String) -> Result { - let l = self.pl().load(&path)?; - Ok(chandra::host::plasmoids::Loaded { - handle: l.handle, - id: l.info.id, - name: l.info.name, - preferred: l.info.preferred, - min_width: l.info.min_width, - stretch: l.info.stretch, - imports: l.imports, - }) - } - - fn unload(&mut self, handle: u32) { - self.pl().unload(handle); - } - - fn set_tokens(&mut self, t: plasmoid::ph::chandra::desktop::theme::Tokens) { - self.pl().shared.borrow_mut().tokens = Some(t); - } - - fn render( - &mut self, - handle: u32, - box_: plasmoid::ph::chandra::desktop::types::Size, - ) -> Vec { - self.pl().render(handle, box_) - } - - fn popup(&mut self, handle: u32) -> Option { - self.pl().popup(handle).map(|p| chandra::host::plasmoids::PopupSurface { box_: p.size, ops: p.ops }) - } - - fn on_event( - &mut self, - handle: u32, - on_popup: bool, - event: plasmoid::ph::chandra::desktop::types::InputEvent, - ) -> bool { - self.pl().on_event(handle, on_popup, event) - } - - fn config_items(&mut self, handle: u32) -> Vec { - self.pl() - .config_items(handle) - .into_iter() - .map(|c| chandra::host::plasmoids::ConfigItem { key: c.key, label: c.label, choices: c.choices, value: c.value }) - .collect() - } - - fn set_config(&mut self, handle: u32, key: String, value: String) -> bool { - self.pl().set_config(handle, &key, &value) - } - - fn desktop_backdrop(&mut self, handle: u32) -> i32 { - self.pl().desktop_backdrop(handle) - } - - fn desktop_scroll(&mut self, handle: u32, x: i32, y: i32, dx: i32, dy: i32) -> bool { - self.pl().desktop_scroll(handle, x, y, dx, dy) - } - - fn desktop_tick(&mut self, handle: u32, now_ms: u32) -> u32 { - self.pl().desktop_tick(handle, now_ms) - } - - fn publish_table(&mut self, which: u32, rows: Vec) { - if let Some(t) = self.pl().shared.borrow_mut().tables.get_mut(which as usize) { - *t = rows; - } - } - - fn publish_state(&mut self, layout_mode: i32, inspector_on: bool) { - let sh = &self.pl().shared; - let mut sh = sh.borrow_mut(); - sh.layout_mode = layout_mode; - sh.inspector_on = inspector_on; - } - - fn publish_wallpaper(&mut self, current: i32) { - self.pl().shared.borrow_mut().wallpaper = current; - } - - fn publish_desktop(&mut self, current: i32) { - self.pl().shared.borrow_mut().desktop = current; - } - - fn publish_session_settings(&mut self, on: u32) { - self.pl().shared.borrow_mut().session_settings = on; - } - - fn publish_screenshot(&mut self, state: u32) { - self.pl().shared.borrow_mut().screenshot = state; - } - - fn publish_power(&mut self, screen_off: u32, suspend: u32) { - let mut sh = self.pl().shared.borrow_mut(); - sh.screen_off_min = screen_off; - sh.suspend_min = suspend; - } - - fn publish_battery(&mut self, percent: i32, state: u32, secs_left: u32) { - self.pl().shared.borrow_mut().battery = (percent, state, secs_left); - } - - fn publish_system(&mut self, s: chandra::host::plasmoids::SystemSnapshot) { - use plasmoid::ph::chandra::desktop::system::Snapshot; - self.pl().shared.borrow_mut().system = Some(Snapshot { - cpu_permille: s.cpu_permille, - mem_used_kib: s.mem_used_kib, - mem_total_kib: s.mem_total_kib, - battery_percent: s.battery_percent, - charging: s.charging, - uptime_secs: s.uptime_secs, - net_rx_bytes_per_sec: s.net_rx_bytes_per_sec, - net_tx_bytes_per_sec: s.net_tx_bytes_per_sec, - load_centi: s.load_centi, - }); - } - - fn publish_windows(&mut self, wins: Vec) { - self.pl().shared.borrow_mut().windows = - wins.into_iter().map(|w| (w.id, w.title, w.app_id, w.focused)).collect(); - } - - fn next_request(&mut self) -> Option { - use chandra::host::plasmoids::Request as R; - use plasmoid::Req; - let r = self.pl().shared.borrow_mut().requests.pop_front()?; - Some(match r { - Req::Launch(s) => R::Launch(s), - Req::FocusWindow(n) => R::FocusWindow(n), - Req::SetLayout(n) => R::SetLayout(n), - Req::SetInspector(b) => R::SetInspector(b), - Req::LoadModule(s) => R::LoadModule(s), - Req::UnloadInstance(s) => R::UnloadInstance(s), - Req::MoveInstance(slot, delta) => { - R::MoveInstance(chandra::host::plasmoids::InstanceMove { slot, delta }) - } - Req::Browse => R::Browse, - Req::Logout => R::Logout, - Req::ReloadSession => R::ReloadSession, - Req::SetWallpaper(n) => R::SetWallpaper(n), - Req::SetSessionSetting(index, on) => { - R::SetSessionSetting(chandra::host::plasmoids::SettingChange { index, on }) - } - Req::Screenshot(code) => R::Screenshot(code), - Req::SetScreenOff(m) => R::SetScreenOff(m), - Req::SetSuspendAfter(m) => R::SetSuspendAfter(m), - Req::PowerAction(a) => R::PowerAction(a), - Req::Network(action, ssid, password) => { - R::Network(chandra::host::plasmoids::NetworkRequest { action, ssid, password }) - } - Req::Shortcut(code) => R::Shortcut(code), - Req::DefaultApp(code) => R::DefaultApp(code), - Req::SetDesktop(i) => R::SetDesktop(i), - Req::FaceUnlock(code) => R::FaceUnlock(code), - Req::GameLibrary(action, game, mode) => { - R::GameLibrary(chandra::host::plasmoids::GameRequest { action, game, mode }) - } - }) - } - - fn take_focus_request(&mut self) -> Option { - self.pl().shared.borrow_mut().focus_req.take() - } - - fn list_wasm_files(&mut self, dir: String) -> Vec { - let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; - let mut v: Vec = rd - .filter_map(|e| e.ok()) - .map(|e| e.file_name().to_string_lossy().into_owned()) - .filter(|n| n.ends_with(".wasm")) - .collect(); - v.sort(); - v - } - - fn picker_start(&mut self) -> bool { - self.pl().picker_start() - } - - fn picker_poll(&mut self) -> chandra::host::plasmoids::PickerState { - use chandra::host::plasmoids::PickerState as P; - match self.pl().picker_poll() { - None => P::Open, - Some(None) => P::Cancelled, - Some(Some(path)) => P::Chosen(path), - } - } -} - -impl chandra::host::display::Host for State { - fn open(&mut self) -> Option { - #[cfg(feature = "drm")] - { - kms::open() - } - #[cfg(not(feature = "drm"))] - { - eprintln!("this host was built without the `drm` feature (no login-session backend)"); - None - } - } - fn poll(&mut self) -> bool { - #[cfg(feature = "drm")] - return kms::poll(); - #[cfg(not(feature = "drm"))] - false - } - fn frame_ready(&mut self) -> bool { - #[cfg(feature = "drm")] - return kms::frame_ready(); - #[cfg(not(feature = "drm"))] - false - } - fn present_frame(&mut self) { - #[cfg(feature = "drm")] - kms::present(&self.raster.fb, self.raster.w as u32, self.raster.h as u32); - } - fn present(&mut self, pixels: Vec, width: u32, height: u32) { - #[cfg(feature = "drm")] - kms::present(&pixels, width, height); - #[cfg(not(feature = "drm"))] - let _ = (pixels, width, height); - } - fn set_power(&mut self, on: bool) { - #[cfg(feature = "drm")] - kms::set_power(on); - #[cfg(not(feature = "drm"))] - let _ = on; - } - fn set_cursor_shape(&mut self, shape: u32) { - #[cfg(feature = "drm")] - kms::set_cursor_shape(shape); - #[cfg(not(feature = "drm"))] - let _ = shape; - } - fn take_input(&mut self) -> Vec { - #[cfg(feature = "drm")] - return kms::take_input(); - #[cfg(not(feature = "drm"))] - Vec::new() - } - fn close(&mut self) { - #[cfg(feature = "drm")] - kms::close(); - } -} - -impl chandra::host::font::Host for State { - fn load(&mut self, slot: u32, path: String) -> bool { - self.fonts.load(slot, &path) - } - - fn rasterise(&mut self, slot: u32, codepoint: u32, size: u32) -> Glyph { - let g = self.fonts.glyph(slot, codepoint, size); - Glyph { width: g.w, height: g.h, xoff: g.xoff, yoff: g.yoff, advance: g.advance, coverage: g.coverage.clone() } - } -} - -impl chandra::host::raster::Host for State { - fn capture(&mut self, fd: i32, offset: i32, stride: i32, width: i32, height: i32, format: i32) -> u32 { - if fd < 0 || offset < 0 || stride <= 0 || width <= 0 || height <= 0 { - return 0; - } - let len = stride as i64 * height as i64; - let end = offset as i64 + len; - unsafe { - let mut st: libc::stat = std::mem::zeroed(); - if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < end { - return 0; - } - // Mapping a large pool only reserves address space; just the pages copied are touched. - let p = libc::mmap(std::ptr::null_mut(), end as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0); - if p == libc::MAP_FAILED { - return 0; - } - let src = std::slice::from_raw_parts((p as *const u8).add(offset as usize), len as usize); - let surface = raster::Surface::from_bgra(src, stride as usize, width, height, format == 1); - libc::munmap(p, end as usize); - match surface { - Some(s) => self.raster.add_surface(s), - None => 0, - } - } - } - - fn release(&mut self, id: u32) { - self.raster.release(id); - } - - fn load_image(&mut self, path: String) -> u32 { - self.raster.images.load(&path) - } - - fn thumbnail(&mut self, surface: u32, w: i32, h: i32, reuse: u32) -> u32 { - self.raster.thumbnail(surface, w, h, reuse) - } - - fn image_pixels(&mut self, w: i32, h: i32, rgba: Vec, reuse: u32) -> u32 { - self.raster.image_pixels(w, h, rgba, reuse) - } - - fn submit(&mut self, f: chandra::host::raster::Frame) { - self.raster.submit_frame(f, &mut self.fonts); - } - - fn read_frame(&mut self) -> Vec { - self.raster.fb.clone() - } - - fn export_memfd(&mut self) -> i32 { - let data = self.raster.to_argb8888(); - let Ok(name) = CString::new("chandra-frame") else { return -1 }; - unsafe { - let fd = libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC); - if fd < 0 { - return -1; - } - let mut done = 0usize; - while done < data.len() { - let n = libc::write(fd, data[done..].as_ptr() as *const _, data.len() - done); - if n <= 0 { - libc::close(fd); - return -1; - } - done += n as usize; - } - fd - } - } - - fn write_frame_png(&mut self, path: String) -> bool { - let (w, h) = (self.raster.w, self.raster.h); - if w <= 0 || h <= 0 { - return false; - } - let Ok(file) = std::fs::File::create(&path) else { return false }; - let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w as u32, h as u32); - enc.set_color(png::ColorType::Rgba); - enc.set_depth(png::BitDepth::Eight); - enc.set_compression(png::Compression::Fast); - match enc.write_header() { - Ok(mut wr) => wr.write_image_data(&self.raster.fb).is_ok(), - Err(_) => false, - } - } - - fn grab_recording_frame(&mut self, x: i32, y: i32, w: i32, h: i32, pointer: bool, px: i32, py: i32) -> bool { - let (fw, fh) = (self.raster.w, self.raster.h); - if w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fw || y + h > fh { - return false; - } - let Some(mut out) = self.rec.free_slot() else { return false }; - let (w, h) = (w as usize, h as usize); - out.clear(); - out.reserve(REC_HEAD + w * h * 4); - rec_frame_header(&mut out, rec_now_ms(), w * h * 4); - for row in 0..h { - let at = ((y as usize + row) * fw as usize + x as usize) * 4; - out.extend_from_slice(&self.raster.fb[at..at + w * 4]); - } - for a in out[REC_HEAD..].iter_mut().skip(3).step_by(4) { - *a = 255; - } - if pointer { - draw_record_pointer(&mut out[REC_HEAD..], w as i32, h as i32, px - x, py - y); - } - self.rec.queue(out); - true - } - - fn send_recording_frame(&mut self, fd: i32) -> i32 { - if fd >= 0 { self.rec.run(fd) } else { self.rec.finish() } - } - - fn snapshot_frame(&mut self) -> bool { - if self.raster.w <= 0 || self.raster.h <= 0 { - return false; - } - self.snap.clear(); - self.snap.extend_from_slice(&self.raster.fb); - (self.snap_w, self.snap_h) = (self.raster.w, self.raster.h); - true - } - - fn snapshot_png(&mut self, x: i32, y: i32, w: i32, h: i32) -> Vec { - let (x0, y0) = (x.max(0), y.max(0)); - let (x1, y1) = (x.saturating_add(w).min(self.snap_w), y.saturating_add(h).min(self.snap_h)); - if x1 <= x0 || y1 <= y0 { - return Vec::new(); - } - let (w, h) = (x1 - x0, y1 - y0); - let px = self.snapshot_pixels(x0, y0, w, h, w, h); - let mut out = Vec::new(); - let mut enc = png::Encoder::new(&mut out, w as u32, h as u32); - enc.set_color(png::ColorType::Rgba); - enc.set_depth(png::BitDepth::Eight); - let ok = match enc.write_header() { - Ok(mut wr) => wr.write_image_data(&px).is_ok(), - Err(_) => false, - }; - if ok { out } else { Vec::new() } - } - - fn snapshot_pixels(&mut self, x: i32, y: i32, w: i32, h: i32, out_w: i32, out_h: i32) -> Vec { - if out_w <= 0 || out_h <= 0 || out_w > 16384 || out_h > 16384 { - return Vec::new(); - } - let mut out = vec![0u8; out_w as usize * out_h as usize * 4]; - for ty in 0..out_h { - let sy = y as i64 + ty as i64 * h as i64 / out_h as i64; - for tx in 0..out_w { - let sx = x as i64 + tx as i64 * w as i64 / out_w as i64; - let d = (ty as usize * out_w as usize + tx as usize) * 4; - if sx >= 0 && sy >= 0 && sx < self.snap_w as i64 && sy < self.snap_h as i64 { - let s = (sy as usize * self.snap_w as usize + sx as usize) * 4; - out[d..d + 3].copy_from_slice(&self.snap[s..s + 3]); - } - out[d + 3] = 255; - } - } - out - } -} - -/// Frames queued for the recording at most: when ffmpeg is this far behind, a drawn frame is -/// not taken (the next one is, with its own time). -const REC_SLOTS: usize = 3; -/// The Matroska Cluster header before each frame's pixels, as recorder.mbt's mkv_frame_header. -const REC_HEAD: usize = 42; - -/// The screen recording's writer: frames (each a Cluster header with the time it was taken, then -/// the pixels) go through a channel to a thread that writes them to ffmpeg's socket in order, so -/// a frame never waits on the main loop. Sent buffers come back for reuse. -#[derive(Default)] -struct Recorder { - fd: i32, - tx: Option>>, - rx: Option>>, - back: Option>>, - back_tx: Option>>, - queued: std::sync::Arc, - failed: std::sync::Arc, - thread: Option>, -} - -impl Recorder { - fn channels(&mut self) { - if self.tx.is_none() { - let (tx, rx) = std::sync::mpsc::channel(); - let (back_tx, back) = std::sync::mpsc::channel(); - (self.tx, self.rx, self.back, self.back_tx) = (Some(tx), Some(rx), Some(back), Some(back_tx)); - self.queued.store(0, std::sync::atomic::Ordering::SeqCst); - self.failed.store(false, std::sync::atomic::Ordering::SeqCst); - } - } - - /// A buffer to fill, or None when the queue is full or the writer failed. - fn free_slot(&mut self) -> Option> { - use std::sync::atomic::Ordering::SeqCst; - self.channels(); - if self.failed.load(SeqCst) || self.queued.load(SeqCst) >= REC_SLOTS { - return None; - } - Some(self.back.as_ref().and_then(|b| b.try_recv().ok()).unwrap_or_default()) - } - - fn queue(&mut self, buf: Vec) { - self.queued.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - if let Some(tx) = &self.tx { - if tx.send(buf).is_err() { - self.failed.store(true, std::sync::atomic::Ordering::SeqCst); - } - } - } - - /// Start the writer on `fd` (once): the frames still queued, or -1 once a write failed. - fn run(&mut self, fd: i32) -> i32 { - use std::sync::atomic::Ordering::SeqCst; - self.channels(); - if self.thread.is_none() { - self.fd = fd; - unsafe { - let fl = libc::fcntl(fd, libc::F_GETFL); - if fl >= 0 && fl & libc::O_NONBLOCK == 0 { - libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); - } - } - let rx = self.rx.take().expect("recording channel"); - let back = self.back_tx.clone().expect("recording channel"); - let (queued, failed) = (self.queued.clone(), self.failed.clone()); - self.thread = Some(std::thread::spawn(move || { - for buf in rx { - if let Err(e) = rec_write_all(fd, &buf) { - eprintln!("recording: writing to ffmpeg failed: {e}"); - failed.store(true, SeqCst); - break; - } - queued.fetch_sub(1, SeqCst); - let _ = back.send(buf); // the main side may be gone: nothing to reuse it for then - } - })); - } else if fd != self.fd { - eprintln!("recording: a second stream while one is running"); - return -1; - } - if self.failed.load(SeqCst) { -1 } else { self.queued.load(SeqCst) as i32 } - } - - /// Send what is queued and stop the writer: 0, or -1 when a write failed. - fn finish(&mut self) -> i32 { - self.tx = None; // ends the writer's loop once the queue is empty - if let Some(t) = self.thread.take() { - if t.join().is_err() { - eprintln!("recording: the writer thread panicked"); - self.failed.store(true, std::sync::atomic::Ordering::SeqCst); - } - } - let failed = self.failed.load(std::sync::atomic::Ordering::SeqCst); - *self = Recorder::default(); - if failed { -1 } else { 0 } - } -} - -fn rec_now_ms() -> u64 { - let mut ts: libc::timespec = unsafe { std::mem::zeroed() }; - unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) }; - ts.tv_sec as u64 * 1000 + ts.tv_nsec as u64 / 1_000_000 -} - -/// An EBML ID and an 8-byte size. -fn rec_id_size(out: &mut Vec, id: &[u8], n: u64) { - out.extend_from_slice(id); - out.push(0x01); - out.extend_from_slice(&n.to_be_bytes()[1..]); -} - -/// A Cluster at `ms` holding one SimpleBlock of `n` bytes of pixels (track 1, a keyframe). -fn rec_frame_header(out: &mut Vec, ms: u64, n: usize) { - rec_id_size(out, &[0x1f, 0x43, 0xb6, 0x75], 30 + n as u64); - rec_id_size(out, &[0xe7], 8); - out.extend_from_slice(&ms.to_be_bytes()); - rec_id_size(out, &[0xa3], 4 + n as u64); - out.extend_from_slice(&[0x81, 0x00, 0x00, 0x80]); -} - -/// Write all of `buf` to the non-blocking `fd`; ffmpeg taking nothing for 5 s is an error (so -/// stopping never hangs on a stuck encoder). -fn rec_write_all(fd: i32, buf: &[u8]) -> std::io::Result<()> { - let mut done = 0; - while done < buf.len() { - let rest = &buf[done..]; - let n = unsafe { libc::send(fd, rest.as_ptr() as *const _, rest.len(), libc::MSG_NOSIGNAL) }; - if n < 0 { - let e = std::io::Error::last_os_error(); - match e.raw_os_error() { - Some(libc::EINTR) => continue, - Some(libc::EAGAIN) => { - let mut p = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 }; - let r = unsafe { libc::poll(&mut p, 1, 5000) }; - if r == 0 { - return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "ffmpeg took nothing for 5 s")); - } - if r < 0 && std::io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) { - return Err(std::io::Error::last_os_error()); - } - continue; - } - _ => return Err(e), - } - } - done += n as usize; - } - Ok(()) -} - -/// The arrow pointer with its tip at (x, y) in an RGBA `w` x `h` frame, as the compositor's -/// recorder draws it: a black body widening over 13 rows and a short tail, then the white inside. -fn draw_record_pointer(px: &mut [u8], w: i32, h: i32, x: i32, y: i32) { - let mut fill = |rx: i32, ry: i32, rw: i32, rh: i32, v: u8| { - for j in ry.max(0)..(ry + rh).min(h) { - for i in rx.max(0)..(rx + rw).min(w) { - let at = ((j * w + i) * 4) as usize; - px[at..at + 4].copy_from_slice(&[v, v, v, 255]); - } - } - }; - for i in 0..17 { - let (l, bw) = if i < 13 { (0, i * 2 / 3 + 1) } else { (3 + (i - 13), 3) }; - fill(x + l - 1, y + i - 1, bw + 2, 3, 0); - } - for i in 1..16 { - let (l, bw) = if i < 13 { (0, i * 2 / 3 - 1) } else { (4 + (i - 13), 1) }; - if bw > 0 { - fill(x + l + 1, y + i, bw, 1, 255); - } - } -} - -impl Host for State { - fn unix_listen(&mut self, path: String) -> i32 { - let _ = std::fs::remove_file(&path); - unsafe { - let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0); - if fd < 0 { - return -1; - } - set_nonblock_cloexec(fd); - let (addr, len) = sockaddr_un(&path); - if libc::bind(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 || libc::listen(fd, 16) < 0 { - libc::close(fd); - return -1; - } - fd - } - } - - fn unix_accept(&mut self, listen_fd: i32) -> i32 { - unsafe { - let fd = libc::accept(listen_fd, std::ptr::null_mut(), std::ptr::null_mut()); - if fd < 0 { - return -1; - } - set_nonblock_cloexec(fd); - fd - } - } - - fn unix_connect(&mut self, path: String) -> i32 { - unsafe { - let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0); - if fd < 0 { - return -1; - } - let (addr, len) = sockaddr_un(&path); - if libc::connect(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 { - libc::close(fd); - return -1; - } - fd - } - } - - fn close_fd(&mut self, fd: i32) { - if fd >= 0 { - // A closed client socket's number is reused by the next one: drop what it left. - if let Some(left) = self.extra_fds.remove(&fd) { - for f in left { - unsafe { libc::close(f) }; - } - } - unsafe { libc::close(fd) }; - } - } - - fn unlink(&mut self, path: String) { - let _ = std::fs::remove_file(path); - } - - fn poll_read(&mut self, fd: i32, timeout_ms: i32) -> i32 { - let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; - let r = unsafe { libc::poll(&mut pfd, 1, timeout_ms) }; - if r < 0 { - -1 - } else if r == 0 { - 0 - } else if pfd.revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 { - 1 - } else { - 0 - } - } - - fn wait_readable(&mut self, fds: Vec, timeout_ms: i32) -> i32 { - let mut pfds: Vec = fds - .into_iter() - .chain(kms::fds()) - .filter(|&fd| fd >= 0) - .map(|fd| libc::pollfd { fd, events: libc::POLLIN, revents: 0 }) - .collect(); - unsafe { libc::poll(pfds.as_mut_ptr(), pfds.len() as libc::nfds_t, timeout_ms) } - } - - fn recvmsg(&mut self, fd: i32, max_len: u32) -> Received { - // Fds from the previous read nobody took would leak: close them. - if let Some(left) = self.extra_fds.remove(&fd) { - for f in left { - unsafe { libc::close(f) }; - } - } - let mut data = vec![0u8; max_len as usize]; - if data.is_empty() { - return Received { count: 0, fd: -1, data }; - } - unsafe { - let mut iov = libc::iovec { iov_base: data.as_mut_ptr() as *mut _, iov_len: data.len() }; - // A client flushes up to 28 fds (libwayland's limit) in one sendmsg, e.g. a Vulkan - // swapchain making a wl_shm_pool per image: every one is needed, in order. - let space = libc::CMSG_SPACE((std::mem::size_of::() * 32) as u32) as usize; - let mut cbuf = vec![0u8; space]; - let mut msg: libc::msghdr = std::mem::zeroed(); - msg.msg_iov = &mut iov; - msg.msg_iovlen = 1; - msg.msg_control = cbuf.as_mut_ptr() as *mut _; - msg.msg_controllen = space as _; - let n = libc::recvmsg(fd, &mut msg, libc::MSG_CMSG_CLOEXEC); - if n < 0 { - let e = *libc::__errno_location(); - let c = if e == libc::EAGAIN || e == libc::EWOULDBLOCK { -1 } else { -2 }; - return Received { count: c, fd: -1, data: Vec::new() }; - } - let mut got = -1; - let mut cm = libc::CMSG_FIRSTHDR(&msg); - while !cm.is_null() { - if (*cm).cmsg_level == libc::SOL_SOCKET && (*cm).cmsg_type == libc::SCM_RIGHTS { - let n_fds = ((*cm).cmsg_len as usize - libc::CMSG_LEN(0) as usize) / std::mem::size_of::(); - let fds = libc::CMSG_DATA(cm) as *const i32; - for i in 0..n_fds { - let f = *fds.add(i); - if got < 0 { - got = f; - } else { - self.extra_fds.entry(fd).or_default().push_back(f); - } - } - } - cm = libc::CMSG_NXTHDR(&msg, cm); - } - data.truncate(n as usize); - Received { count: n as i32, fd: got, data } - } - } - - fn take_fd(&mut self, sock: i32) -> i32 { - let q = match self.extra_fds.get_mut(&sock) { - Some(q) => q, - None => return -1, - }; - let f = q.pop_front().unwrap_or(-1); - if q.is_empty() { - self.extra_fds.remove(&sock); - } - f - } - - fn sendmsg(&mut self, fd: i32, data: Vec, send_fd: i32) -> i32 { - if data.is_empty() { - return 0; - } - unsafe { - let mut total = 0usize; - let mut with_fd = send_fd >= 0; - while total < data.len() { - let mut iov = libc::iovec { - iov_base: data.as_ptr().add(total) as *mut _, - iov_len: data.len() - total, - }; - let space = libc::CMSG_SPACE(std::mem::size_of::() as u32) as usize; - let mut cbuf = vec![0u8; space]; - let mut msg: libc::msghdr = std::mem::zeroed(); - msg.msg_iov = &mut iov; - msg.msg_iovlen = 1; - if with_fd { - msg.msg_control = cbuf.as_mut_ptr() as *mut _; - msg.msg_controllen = space as _; - let cm = libc::CMSG_FIRSTHDR(&msg); - (*cm).cmsg_level = libc::SOL_SOCKET; - (*cm).cmsg_type = libc::SCM_RIGHTS; - (*cm).cmsg_len = libc::CMSG_LEN(std::mem::size_of::() as u32) as _; - std::ptr::copy_nonoverlapping(&send_fd as *const i32 as *const u8, libc::CMSG_DATA(cm), 4); - } - let sent = libc::sendmsg(fd, &msg, libc::MSG_NOSIGNAL); - if sent < 0 { - let e = *libc::__errno_location(); - if e == libc::EAGAIN || e == libc::EWOULDBLOCK { - let mut pfd = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 }; - libc::poll(&mut pfd, 1, 50); - continue; - } - return -1; - } - total += sent as usize; - with_fd = false; // ancillary data goes with the first chunk only - } - total as i32 - } - } - - fn memfd_create(&mut self, name: String, size: i32) -> i32 { - let Ok(cname) = CString::new(name) else { return -1 }; - unsafe { - let fd = libc::memfd_create(cname.as_ptr(), libc::MFD_CLOEXEC); - if fd < 0 { - return -1; - } - if size > 0 && libc::ftruncate(fd, size as libc::off_t) < 0 { - libc::close(fd); - return -1; - } - fd - } - } - - fn pwrite(&mut self, fd: i32, data: Vec, offset: i32) -> i32 { - if offset < 0 { - // A pipe or socket (clipboard paste, screen recording): write what fits now. 0 when it - // is full, -1 on error. (Rust already ignores SIGPIPE, so a gone reader is just EPIPE.) - unsafe { - let fl = libc::fcntl(fd, libc::F_GETFL); - if fl >= 0 && fl & libc::O_NONBLOCK == 0 { - libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); - } - let w = libc::write(fd, data.as_ptr() as *const _, data.len()); - if w < 0 { - let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - return if e == libc::EAGAIN || e == libc::EWOULDBLOCK || e == libc::EINTR { 0 } else { -1 }; - } - return w as i32; - } - } - let w = unsafe { libc::pwrite(fd, data.as_ptr() as *const _, data.len(), offset as libc::off_t) }; - if w < 0 { -1 } else { w as i32 } - } - - fn mmap_read(&mut self, fd: i32, size: i32) -> Vec { - if fd < 0 || size <= 0 { - return Vec::new(); - } - unsafe { - let mut st: libc::stat = std::mem::zeroed(); - if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < size as i64 { - return Vec::new(); - } - let p = libc::mmap(std::ptr::null_mut(), size as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0); - if p == libc::MAP_FAILED { - return Vec::new(); - } - let out = std::slice::from_raw_parts(p as *const u8, size as usize).to_vec(); - libc::munmap(p, size as usize); - out - } - } - - fn mmap_read_at(&mut self, fd: i32, offset: i32, len: i32) -> Vec { - if fd < 0 || offset < 0 || len <= 0 { - return Vec::new(); - } - let end = offset as i64 + len as i64; - unsafe { - let mut st: libc::stat = std::mem::zeroed(); - if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < end { - return Vec::new(); - } - // Mapping a large pool only reserves address space; just the pages copied are touched. - let p = libc::mmap(std::ptr::null_mut(), end as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0); - if p == libc::MAP_FAILED { - return Vec::new(); - } - let out = std::slice::from_raw_parts((p as *const u8).add(offset as usize), len as usize).to_vec(); - libc::munmap(p, end as usize); - out - } - } - - fn read_file(&mut self, path: String) -> Vec { - std::fs::read(path).unwrap_or_default() - } - - fn write_file(&mut self, path: String, data: Vec) -> i32 { - match std::fs::write(path, &data) { - Ok(()) => 0, - Err(_) => -1, - } - } - - fn append_file(&mut self, path: String, data: Vec) -> i32 { - use std::io::Write; - let f = std::fs::OpenOptions::new().append(true).create(true).open(path); - match f.and_then(|mut f| f.write_all(&data)) { - Ok(()) => 0, - Err(_) => -1, - } - } - - fn read_proc(&mut self, path: String) -> Vec { - // /proc and /sys files report size 0: read to EOF, capped at 64 KiB. - let Ok(f) = std::fs::File::open(path) else { return Vec::new() }; - let mut out = Vec::new(); - let _ = f.take(65536).read_to_end(&mut out); - out - } - - fn mkdir_p(&mut self, path: String) -> bool { - std::fs::create_dir_all(path).is_ok() - } - - fn list_desktop_files(&mut self, dir: String) -> Vec { - let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; - rd.filter_map(|e| e.ok()) - .map(|e| e.file_name().to_string_lossy().into_owned()) - .filter(|n| n.ends_with(".desktop")) - .collect() - } - - fn sleep_ms(&mut self, ms: i32) { - if ms > 0 { - std::thread::sleep(std::time::Duration::from_millis(ms as u64)); - } - } - - fn monotonic_ms(&mut self) -> u64 { - self.started.get_or_insert_with(std::time::Instant::now).elapsed().as_millis() as u64 - } - - fn log(&mut self, message: String) { - eprintln!("{message}"); - } - - fn getpid(&mut self) -> i32 { - std::process::id() as i32 - } - - fn take_sigusr1(&mut self) -> bool { - // The handler only sets a flag. No SA_RESTART: a blocked poll() in wait-readable returns - // EINTR, so an idle compositor runs a pass and sees the request. - extern "C" fn on_sigusr1(_: libc::c_int) { - SIGUSR1_SEEN.store(true, std::sync::atomic::Ordering::SeqCst); - } - if !SIGUSR1_INSTALLED.swap(true, std::sync::atomic::Ordering::SeqCst) { - unsafe { - let mut sa: libc::sigaction = std::mem::zeroed(); - sa.sa_sigaction = on_sigusr1 as extern "C" fn(libc::c_int) as usize; - libc::sigemptyset(&mut sa.sa_mask); - sa.sa_flags = 0; - libc::sigaction(libc::SIGUSR1, &sa, std::ptr::null_mut()); - } - } - SIGUSR1_SEEN.swap(false, std::sync::atomic::Ordering::SeqCst) - } - - fn wall_time_field(&mut self, which: i32) -> i32 { - unsafe { - let t = libc::time(std::ptr::null_mut()); - let mut tm: libc::tm = std::mem::zeroed(); - libc::localtime_r(&t, &mut tm); - match which { - 0 => tm.tm_year + 1900, - 1 => tm.tm_mon + 1, - 2 => tm.tm_mday, - 3 => tm.tm_hour, - 4 => tm.tm_min, - 5 => tm.tm_sec, - 6 => tm.tm_wday, - _ => 0, - } - } - } - - fn getenv(&mut self, name: String) -> String { - std::env::var(name).unwrap_or_default() - } - - fn has_exe(&mut self, name: String) -> bool { - let ok = |p: &std::path::Path| { - CString::new(p.as_os_str().as_encoded_bytes()) - .map(|c| unsafe { libc::access(c.as_ptr(), libc::X_OK) == 0 }) - .unwrap_or(false) - }; - if name.contains('/') { - return ok(std::path::Path::new(&name)); - } - std::env::var_os("PATH") - .map(|p| std::env::split_paths(&p).any(|d| ok(&d.join(&name)))) - .unwrap_or(false) - } - - fn spawn(&mut self, cmd: String, display: String) -> bool { - let bus = self.private_bus(); - let mut c = Command::new("/bin/sh"); - c.arg("-c").arg(&cmd); - // Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak on - // the real session bus, so they keep it; everything else gets the private bus. - if let Some(b) = bus { - if !cmd.contains("flatpak run") { - c.env("DBUS_SESSION_BUS_ADDRESS", b); - } - } - c.env("WAYLAND_DISPLAY", display) - .env_remove("DISPLAY") - // Make toolkits pick our Wayland socket, not X11 or the host session. - .env("XDG_SESSION_TYPE", "wayland") - .env("QT_QPA_PLATFORM", "wayland") - .env("GDK_BACKEND", "wayland") - .env("SDL_VIDEODRIVER", "wayland") - .env("MOZ_ENABLE_WAYLAND", "1") - .env("ELECTRON_OZONE_PLATFORM_HINT", "wayland") - .env("CLUTTER_BACKEND", "wayland") - .stdin(Stdio::null()); - unsafe { - c.pre_exec(|| { - libc::setsid(); - libc::signal(libc::SIGCHLD, libc::SIG_DFL); - Ok(()) - }); - } - c.spawn().is_ok() - } - - fn spawn_socket(&mut self, argv: String) -> i32 { - use std::os::fd::{FromRawFd, IntoRawFd, OwnedFd}; - let args: Vec<&str> = argv.split('\n').filter(|a| !a.is_empty()).collect(); - if args.is_empty() || !args[0].starts_with('/') { - return -1; - } - let mut sv = [-1i32; 2]; - if unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0, sv.as_mut_ptr()) } != 0 { - return -1; - } - let child_end = unsafe { OwnedFd::from_raw_fd(sv[1]) }; - let out = match child_end.try_clone() { - Ok(f) => f, - Err(_) => { - unsafe { libc::close(sv[0]) }; - return -1; - } - }; - let mut c = Command::new(args[0]); - c.args(&args[1..]).stdin(Stdio::from(child_end)).stdout(Stdio::from(out)); - unsafe { - c.pre_exec(|| { - libc::signal(libc::SIGCHLD, libc::SIG_DFL); - libc::signal(libc::SIGPIPE, libc::SIG_DFL); - Ok(()) - }); - } - match c.spawn() { - Ok(mut child) => { - // Reap it when it exits, so it never lingers as a zombie. - std::thread::spawn(move || { - let _ = child.wait(); - }); - let fd = unsafe { OwnedFd::from_raw_fd(sv[0]) }; - fd.into_raw_fd() - } - Err(_) => { - unsafe { libc::close(sv[0]) }; - -1 - } - } - } -} - -fn main() -> Result<()> { - let mut args: Vec = std::env::args().skip(1).collect(); - // First argument may be the component path; otherwise use the default build location. - let component_path = if args.first().map(|a| a.ends_with(".wasm")).unwrap_or(false) { - args.remove(0) - } else { - "build/compositor.wasm".to_string() - }; - if args.first().map(|a| a == "--").unwrap_or(false) { - args.remove(0); - } - - // No zombies from launched apps. - unsafe { libc::signal(libc::SIGCHLD, libc::SIG_IGN) }; - - let mut config = Config::new(); - config.wasm_component_model(true); - let engine = Engine::new(&config)?; - let component = match Component::from_file(&engine, &component_path) { - Ok(c) => c, - Err(e) => { - eprintln!("error: cannot load {component_path}: {e}\n build it with `just compositor-wasm`"); - std::process::exit(1); - } - }; - let mut linker: Linker = Linker::new(&engine); - chandra::host::sys::add_to_linker::>(&mut linker, |s| s)?; - chandra::host::font::add_to_linker::>(&mut linker, |s| s)?; - chandra::host::raster::add_to_linker::>(&mut linker, |s| s)?; - chandra::host::display::add_to_linker::>(&mut linker, |s| s)?; - chandra::host::plasmoids::add_to_linker::>(&mut linker, |s| s)?; - let mut store = Store::new(&engine, State::default()); - store.data_mut().pl = Some(plasmoid::Runtime::new(&engine)?); - let compositor = Compositor::instantiate(&mut store, &component, &linker)?; - let code = compositor.call_run(&mut store, &args)?; - std::process::exit(code); -} diff --git a/host-wasm/src/plasmoid.rs b/host-wasm/src/plasmoid.rs deleted file mode 100644 index 0f927e4..0000000 --- a/host-wasm/src/plasmoid.rs +++ /dev/null @@ -1,1340 +0,0 @@ -//! Runs panel modules (plasmoids) for the compositor component. -//! -//! The native compositor embeds wasmer and marshals the canonical ABI by hand. A component can't -//! embed a second runtime, so the compositor asks this host (wit/host/plasmoids.wit) and gets draw -//! ops back. Each module is instantiated as a real component with typed bindings against one world, -//! `plasmoid-host` (wit/worlds.wit): it imports the subset of host interfaces it uses, and every one -//! of them is served here from the data the compositor publishes. - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::io::Read; -use std::os::unix::process::CommandExt; -use std::process::{Child, Command, Stdio}; -use std::rc::Rc; -use wasmtime::component::{Component, HasSelf, Linker}; -use wasmtime::{Engine, Store}; - -pub mod ph { - wasmtime::component::bindgen!({ - path: "../wit", - world: "plasmoid-host", - additional_derives: [PartialEq], - }); -} -/// The optional `module-config` export (wit/worlds.wit `configurable`): a module's own settings -/// for its right-click menu. Bound separately so modules without it still instantiate. -pub mod cfg { - wasmtime::component::bindgen!({ - path: "../wit", - world: "configurable", - }); -} -pub use cfg::exports::chandra::desktop::module_config::ConfigItem; -/// The optional `desktop-module` export (wit/desktop.wit, world `desktop-export`): a module that -/// fills the desktop. Bound separately, like `module-config`. -pub mod desk { - wasmtime::component::bindgen!({ - path: "../wit", - world: "desktop-export", - }); -} -use ph::exports::chandra::desktop as ex; -use ph::chandra::desktop as d; - -/// What a module asked of the compositor during a call. -pub enum Req { - Launch(String), - FocusWindow(i32), - SetLayout(i32), - SetInspector(bool), - LoadModule(String), - UnloadInstance(String), - /// Move a panel instance `delta` places (negative: towards the start). - MoveInstance(String, i32), - Browse, - Logout, - /// `session.reload`: reload every loaded panel module from disk. - ReloadSession, - SetWallpaper(i32), - SetSessionSetting(i32, bool), - /// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on. - Screenshot(i32), - SetScreenOff(i32), - SetSuspendAfter(i32), - /// 0 suspend, 1 power off, 2 restart. - PowerAction(i32), - /// A network action (0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode off/on, - /// 6 connect, 7 forget), the network's name and the password. - Network(i32, String, String), - /// A shortcuts request: action * 1000 + index (0 capture, 1 reset, 2 reset all, 3 cancel). - Shortcut(i32), - /// A default-apps request: category * 1000 + app sets a default, -1 scans again. - DefaultApp(i32), - /// `wallpaper.set-desktop`: an index into the desktops table. - SetDesktop(i32), - /// A face-unlock request: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop / - /// start using it. - FaceUnlock(i32), - /// A game-library action (0 launch, 1 stop, 2 focus, 3 refresh), the game and the mode. - GameLibrary(i32, String, String), -} - -pub const T_APPS: usize = 0; -pub const T_WINDOWS: usize = 1; -pub const T_LAYOUTS: usize = 2; -pub const T_MODULES: usize = 3; -pub const T_INSTANCES: usize = 4; -pub const T_WALLPAPERS: usize = 5; -pub const T_SESSION_SETTINGS: usize = 6; -/// App id -> raster image handle (`raster.load-image`), behind `icons.app-icon`. -pub const T_ICONS: usize = 7; -/// One row (iissiiii): state signal name message wifi-enabled airplane can-manage has-wifi. -pub const T_NET_STATUS: usize = 8; -/// Wi-Fi networks in range (siiii): ssid signal secured active saved. -pub const T_NET_NETWORKS: usize = 9; -/// Keyboard shortcuts (ssssi): name binding default-binding conflict capturing. -pub const T_SHORTCUTS: usize = 10; -/// Default-app categories (sss): name current missing. -pub const T_APP_CATS: usize = 11; -/// Default-app choices (issii): category id name icon current. -pub const T_APP_CHOICES: usize = 12; -/// What can fill the desktop (s): name, behind `wallpaper.desktops`. -pub const T_DESKTOPS: usize = 20; -/// Face unlock status, one row (sssiii): problem howdy message installed in-use busy. -pub const T_FACE_STATUS: usize = 24; -/// Enrolled faces (ss): label added. -pub const T_FACES: usize = 25; -/// Game library status, one row (ssssssii): error gpu resolution display audio hostname connected -/// audio-ok. -pub const T_GL_STATUS: usize = 26; -/// Games (ssssssiii): id name category description icon install-hint featured installed running. -pub const T_GL_GAMES: usize = 27; -/// Extra launch modes (sss): game id label. -pub const T_GL_MODES: usize = 28; - -/// Host data every module reads from, shared by all loaded modules. -#[derive(Default)] -pub struct Shared { - pub tables: [Vec; 29], - pub layout_mode: i32, - pub wallpaper: i32, - /// What fills the desktop (an index into the desktops table). - pub desktop: i32, - /// Which session settings are on: bit i for row i of the session settings table. - pub session_settings: u32, - /// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer. - pub screenshot: u32, - /// Power timeouts in minutes (0: never). - pub screen_off_min: u32, - pub suspend_min: u32, - pub inspector_on: bool, - pub system: Option, - /// The battery (`battery.read`): percent (-1: none), charge-state index, seconds left. - pub battery: (i32, u32, u32), - /// (id, title, app id, focused) - pub windows: Vec<(u64, String, String, bool)>, - pub requests: VecDeque, - pub focus_req: Option, - pub tokens: Option, -} -pub type SharedRef = Rc>; - -pub struct PState { - shared: SharedRef, -} - -enum Field { - I(i32), - S(String), -} - -/// Parse a table (LE u32 row count, then rows) by its field spec: 'i' = LE i32, 's' = LE u32 length + UTF-8. -fn parse_table(bytes: &[u8], spec: &str) -> Vec> { - let rd = |p: usize| -> Option { bytes.get(p..p + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) }; - let Some(n) = rd(0) else { return Vec::new() }; - let mut pos = 4; - let mut rows = Vec::new(); - 'rows: for _ in 0..n { - let mut row = Vec::new(); - for c in spec.chars() { - let Some(v) = rd(pos) else { break 'rows }; - pos += 4; - if c == 'i' { - row.push(Field::I(v as i32)); - } else { - let end = pos + v as usize; - let Some(s) = bytes.get(pos..end) else { break 'rows }; - row.push(Field::S(String::from_utf8_lossy(s).into_owned())); - pos = end; - } - } - rows.push(row); - } - rows -} - -fn s(f: &Field) -> String { - match f { - Field::S(x) => x.clone(), - Field::I(i) => i.to_string(), - } -} -fn i(f: &Field) -> i32 { - match f { - Field::I(x) => *x, - Field::S(_) => 0, - } -} - -fn default_tokens() -> d::theme::Tokens { - let c = |r, g, b| d::types::Color { r, g, b, a: 255 }; - d::theme::Tokens { - name: String::new(), - palette: d::theme::Palette { - desktop_top: c(20, 28, 48), - desktop_bottom: c(10, 14, 28), - surface: c(30, 36, 50), - surface_hover: c(50, 58, 76), - surface_popup: c(24, 30, 44), - foreground: c(240, 244, 250), - foreground_muted: c(150, 160, 180), - accent: c(120, 150, 255), - accent_foreground: c(255, 255, 255), - border: c(70, 80, 100), - }, - font_size: 14, - radius: 6, - spacing: 6, - panel_height: 40, - } -} - -impl PState { - fn rows(&self, t: usize, spec: &str) -> Vec> { - parse_table(&self.shared.borrow().tables[t], spec) - } -} - -impl d::types::Host for PState {} - -impl d::theme::Host for PState { - fn get_tokens(&mut self) -> d::theme::Tokens { - self.shared.borrow().tokens.clone().unwrap_or_else(default_tokens) - } -} - -impl d::clock::Host for PState { - fn now(&mut self) -> d::types::Datetime { - unsafe { - let t = libc::time(std::ptr::null_mut()); - let mut tm: libc::tm = std::mem::zeroed(); - libc::localtime_r(&t, &mut tm); - d::types::Datetime { - year: (tm.tm_year + 1900) as u32, - month: (tm.tm_mon + 1) as u8, - day: tm.tm_mday as u8, - hour: tm.tm_hour as u8, - minute: tm.tm_min as u8, - second: tm.tm_sec as u8, - weekday: tm.tm_wday as u8, - } - } - } -} - -impl d::app_catalog::Host for PState { - fn list_apps(&mut self) -> Vec { - self.rows(T_APPS, "sssss") - .iter() - .map(|r| d::types::AppEntry { - id: s(&r[0]), - name: s(&r[1]), - comment: s(&r[2]), - category: s(&r[3]), - glyph: s(&r[4]), - }) - .collect() - } -} - -impl d::app_launch::Host for PState { - /// Known catalog ids succeed; the compositor spawns after the call returns. - fn launch(&mut self, id: String) -> Result<(), String> { - if self.rows(T_APPS, "sssss").iter().any(|r| s(&r[0]) == id) { - self.shared.borrow_mut().requests.push_back(Req::Launch(id)); - Ok(()) - } else { - Err("unknown application".to_string()) - } - } -} - -impl d::windows::Host for PState { - fn list_windows(&mut self) -> Vec { - self.rows(T_WINDOWS, "isii") - .iter() - .map(|r| d::windows::WindowInfo { - id: i(&r[0]) as u32, - title: s(&r[1]), - focused: i(&r[2]) as u32, - minimized: i(&r[3]) as u32, - }) - .collect() - } - fn focus_window(&mut self, id: u32) { - self.shared.borrow_mut().requests.push_back(Req::FocusWindow(id as i32)); - } - fn all(&mut self) -> Vec { - self.shared - .borrow() - .windows - .iter() - .take(64) - .map(|(id, title, app, focused)| d::windows::WindowDetail { - id: *id, - title: title.clone(), - app_id: app.clone(), - focused: *focused, - }) - .collect() - } - fn focus(&mut self, id: u64) { - self.shared.borrow_mut().focus_req = Some(id); - } -} - -impl d::layout_control::Host for PState { - fn layout_modes(&mut self) -> Vec { - self.rows(T_LAYOUTS, "s").iter().map(|r| s(&r[0])).collect() - } - fn current_layout(&mut self) -> u32 { - self.shared.borrow().layout_mode as u32 - } - fn set_layout(&mut self, mode: u32) { - self.shared.borrow_mut().requests.push_back(Req::SetLayout(mode as i32)); - } -} - -impl d::inspector::Host for PState { - fn is_on(&mut self) -> bool { - self.shared.borrow().inspector_on - } - fn set_on(&mut self, on: bool) { - self.shared.borrow_mut().requests.push_back(Req::SetInspector(on)); - } -} - -impl d::modules::Host for PState { - fn available(&mut self) -> Vec { - self.rows(T_MODULES, "sssi") - .iter() - .map(|r| d::modules::ModuleInfo { id: s(&r[0]), name: s(&r[1]), path: s(&r[2]), loaded: i(&r[3]) as u32 }) - .collect() - } - fn loaded(&mut self) -> Vec { - self.rows(T_INSTANCES, "sss") - .iter() - .map(|r| d::modules::InstanceInfo { slot: s(&r[0]), module: s(&r[1]), name: s(&r[2]) }) - .collect() - } - fn load_module(&mut self, path: String) { - self.shared.borrow_mut().requests.push_back(Req::LoadModule(path)); - } - fn unload_instance(&mut self, slot: String) { - self.shared.borrow_mut().requests.push_back(Req::UnloadInstance(slot)); - } - fn move_instance(&mut self, slot: String, delta: i32) { - self.shared.borrow_mut().requests.push_back(Req::MoveInstance(slot, delta)); - } - fn browse(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::Browse); - } -} - -impl d::session::Host for PState { - fn logout(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::Logout); - } - fn reload(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::ReloadSession); - } -} - -impl d::wallpaper::Host for PState { - fn wallpapers(&mut self) -> Vec { - self.rows(T_WALLPAPERS, "s").iter().map(|r| s(&r[0])).collect() - } - fn current_wallpaper(&mut self) -> u32 { - self.shared.borrow().wallpaper.max(0) as u32 - } - fn set_wallpaper(&mut self, index: u32) { - self.shared.borrow_mut().requests.push_back(Req::SetWallpaper(index as i32)); - } - fn desktops(&mut self) -> Vec { - self.rows(T_DESKTOPS, "s").iter().map(|r| s(&r[0])).collect() - } - fn current_desktop(&mut self) -> u32 { - self.shared.borrow().desktop.max(0) as u32 - } - fn set_desktop(&mut self, index: u32) { - self.shared.borrow_mut().requests.push_back(Req::SetDesktop(index as i32)); - } -} - -impl d::face_unlock::Host for PState { - fn status(&mut self) -> d::face_unlock::FaceStatus { - let rows = self.rows(T_FACE_STATUS, "sssiii"); - match rows.first() { - Some(r) if r.len() == 6 => d::face_unlock::FaceStatus { - problem: s(&r[0]), - howdy: s(&r[1]), - message: s(&r[2]), - installed: i(&r[3]) != 0, - in_use: i(&r[4]) != 0, - busy: i(&r[5]) != 0, - }, - _ => d::face_unlock::FaceStatus { - problem: String::new(), - howdy: String::new(), - message: String::new(), - installed: false, - in_use: false, - busy: false, - }, - } - } - fn faces(&mut self) -> Vec { - self.rows(T_FACES, "ss") - .iter() - .filter(|r| r.len() == 2) - .map(|r| d::face_unlock::Face { label: s(&r[0]), added: s(&r[1]) }) - .collect() - } - fn enroll(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::FaceUnlock(-2)); - } - fn remove(&mut self, index: u32) { - if index < 1000 { - self.shared.borrow_mut().requests.push_back(Req::FaceUnlock(index as i32)); - } - } - fn set_in_use(&mut self, on: bool) { - self.shared.borrow_mut().requests.push_back(Req::FaceUnlock(if on { -4 } else { -3 })); - } - fn refresh(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::FaceUnlock(-1)); - } -} - -impl d::game_library::Host for PState { - fn status(&mut self) -> d::game_library::RigStatus { - let rows = self.rows(T_GL_STATUS, "ssssssii"); - match rows.first() { - Some(r) if r.len() == 8 => d::game_library::RigStatus { - error: s(&r[0]), - gpu: s(&r[1]), - resolution: s(&r[2]), - display: s(&r[3]), - audio: s(&r[4]), - hostname: s(&r[5]), - connected: i(&r[6]) != 0, - audio_ok: i(&r[7]) != 0, - }, - _ => d::game_library::RigStatus { - error: String::new(), - gpu: String::new(), - resolution: String::new(), - display: String::new(), - audio: String::new(), - hostname: String::new(), - connected: false, - audio_ok: false, - }, - } - } - fn games(&mut self) -> Vec { - self.rows(T_GL_GAMES, "ssssssiii") - .iter() - .filter(|r| r.len() == 9) - .map(|r| d::game_library::Game { - id: s(&r[0]), - name: s(&r[1]), - category: s(&r[2]), - description: s(&r[3]), - icon: s(&r[4]), - install_hint: s(&r[5]), - featured: i(&r[6]) != 0, - installed: i(&r[7]) != 0, - running: i(&r[8]) != 0, - }) - .collect() - } - fn launch_modes(&mut self) -> Vec { - self.rows(T_GL_MODES, "sss") - .iter() - .filter(|r| r.len() == 3) - .map(|r| d::game_library::LaunchMode { game: s(&r[0]), id: s(&r[1]), label: s(&r[2]) }) - .collect() - } - fn launch(&mut self, game: String, mode: String) { - self.shared.borrow_mut().requests.push_back(Req::GameLibrary(0, game, mode)); - } - fn stop(&mut self, game: String) { - self.shared.borrow_mut().requests.push_back(Req::GameLibrary(1, game, String::new())); - } - fn focus(&mut self, game: String) { - self.shared.borrow_mut().requests.push_back(Req::GameLibrary(2, game, String::new())); - } - fn refresh(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::GameLibrary(3, String::new(), String::new())); - } -} - -impl d::power::Host for PState { - fn screen_off_minutes(&mut self) -> u32 { - self.shared.borrow().screen_off_min - } - fn set_screen_off_minutes(&mut self, minutes: u32) { - self.shared.borrow_mut().requests.push_back(Req::SetScreenOff(minutes as i32)); - } - fn suspend_minutes(&mut self) -> u32 { - self.shared.borrow().suspend_min - } - fn set_suspend_minutes(&mut self, minutes: u32) { - self.shared.borrow_mut().requests.push_back(Req::SetSuspendAfter(minutes as i32)); - } - fn suspend(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::PowerAction(0)); - } - fn power_off(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::PowerAction(1)); - } - fn reboot(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::PowerAction(2)); - } -} - -impl d::shortcuts::Host for PState { - fn shortcuts(&mut self) -> Vec { - self.rows(T_SHORTCUTS, "ssssi") - .iter() - .filter(|r| r.len() == 5) - .map(|r| d::shortcuts::Shortcut { - name: s(&r[0]), - binding: s(&r[1]), - default_binding: s(&r[2]), - conflict: s(&r[3]), - capturing: i(&r[4]) != 0, - }) - .collect() - } - fn capture(&mut self, index: u32) { - if index < 1000 { - self.shared.borrow_mut().requests.push_back(Req::Shortcut(index as i32)); - } - } - fn cancel_capture(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::Shortcut(3000)); - } - fn reset(&mut self, index: u32) { - if index < 1000 { - self.shared.borrow_mut().requests.push_back(Req::Shortcut(1000 + index as i32)); - } - } - fn reset_all(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::Shortcut(2000)); - } -} - -impl d::default_apps::Host for PState { - fn categories(&mut self) -> Vec { - self.rows(T_APP_CATS, "sss") - .iter() - .filter(|r| r.len() == 3) - .map(|r| d::default_apps::AppCategory { - name: s(&r[0]), - current: s(&r[1]), - missing: s(&r[2]), - }) - .collect() - } - fn apps(&mut self) -> Vec { - self.rows(T_APP_CHOICES, "issii") - .iter() - .filter(|r| r.len() == 5) - .map(|r| d::default_apps::AppChoice { - category: i(&r[0]) as u32, - id: s(&r[1]), - name: s(&r[2]), - icon: i(&r[3]) as u32, - current: i(&r[4]) != 0, - }) - .collect() - } - fn set_default(&mut self, category: u32, app: u32) { - if category < 1000 && app < 1000 { - let code = (category * 1000 + app) as i32; - self.shared.borrow_mut().requests.push_back(Req::DefaultApp(code)); - } - } - fn refresh(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::DefaultApp(-1)); - } -} - -impl d::screenshot::Host for PState { - fn take(&mut self, mode: u32) { - if mode <= 3 { - self.shared.borrow_mut().requests.push_back(Req::Screenshot(mode as i32)); - } - } - fn start_recording(&mut self, mode: u32) { - if mode <= 2 { - self.shared.borrow_mut().requests.push_back(Req::Screenshot(10 + mode as i32)); - } - } - fn stop_recording(&mut self) { - self.shared.borrow_mut().requests.push_back(Req::Screenshot(20)); - } - fn is_recording(&mut self) -> bool { - self.shared.borrow().screenshot & 1 == 1 - } - fn records_pointer(&mut self) -> bool { - self.shared.borrow().screenshot & 2 == 2 - } - fn set_records_pointer(&mut self, on: bool) { - self.shared.borrow_mut().requests.push_back(Req::Screenshot(if on { 31 } else { 30 })); - } -} - -impl d::network::Host for PState { - fn status(&mut self) -> d::network::NetStatus { - let rows = self.rows(T_NET_STATUS, "iissiiii"); - match rows.first() { - Some(r) if r.len() == 8 => d::network::NetStatus { - state: i(&r[0]) as u32, - signal: i(&r[1]) as u32, - name: s(&r[2]), - message: s(&r[3]), - wifi_enabled: i(&r[4]) != 0, - airplane: i(&r[5]) != 0, - can_manage: i(&r[6]) != 0, - has_wifi: i(&r[7]) != 0, - }, - _ => d::network::NetStatus { - state: 0, - signal: 0, - name: String::new(), - message: String::new(), - wifi_enabled: false, - airplane: false, - can_manage: false, - has_wifi: false, - }, - } - } - fn wifi_networks(&mut self) -> Vec { - self.rows(T_NET_NETWORKS, "siiii") - .iter() - .filter(|r| r.len() == 5) - .map(|r| d::network::WifiNetwork { - ssid: s(&r[0]), - signal: i(&r[1]) as u32, - secured: i(&r[2]) != 0, - active: i(&r[3]) != 0, - saved: i(&r[4]) != 0, - }) - .collect() - } - fn scan(&mut self) { - self.net(0, String::new(), String::new()); - } - fn connect(&mut self, ssid: String, password: String) { - self.net(6, ssid, password); - } - fn disconnect(&mut self) { - self.net(1, String::new(), String::new()); - } - fn forget(&mut self, ssid: String) { - self.net(7, ssid, String::new()); - } - fn set_wifi_enabled(&mut self, on: bool) { - self.net(if on { 3 } else { 2 }, String::new(), String::new()); - } - fn set_airplane_mode(&mut self, on: bool) { - self.net(if on { 5 } else { 4 }, String::new(), String::new()); - } -} - -impl PState { - fn net(&mut self, action: i32, ssid: String, password: String) { - self.shared.borrow_mut().requests.push_back(Req::Network(action, ssid, password)); - } -} - -impl d::session_settings::Host for PState { - fn settings(&mut self) -> Vec { - self.rows(T_SESSION_SETTINGS, "s").iter().map(|r| s(&r[0])).collect() - } - fn is_on(&mut self, index: u32) -> bool { - index < 32 && (self.shared.borrow().session_settings >> index) & 1 == 1 - } - fn set_setting(&mut self, index: u32, on: bool) { - self.shared.borrow_mut().requests.push_back(Req::SetSessionSetting(index as i32, on)); - } -} - -impl d::icons::Host for PState { - /// The handle the compositor published for this app id: it found the app's .desktop file and - /// its themed icon, and had the rasteriser load it. Modules never see the path. - fn app_icon(&mut self, app_id: String) -> u32 { - self.rows(T_ICONS, "si") - .iter() - .find(|r| s(&r[0]) == app_id) - .map(|r| i(&r[1]) as u32) - .unwrap_or(0) - } -} - -impl d::battery::Host for PState { - fn read(&mut self) -> d::battery::Status { - use d::battery::ChargeState as C; - let (percent, state, secs_left) = self.shared.borrow().battery; - let state = match state { - 1 => C::Discharging, - 2 => C::Charging, - 3 => C::Full, - 4 => C::NotCharging, - _ => C::None, - }; - d::battery::Status { percent: if state == C::None { -1 } else { percent }, state, secs_left } - } -} - -impl d::system::Host for PState { - fn read(&mut self) -> d::system::Snapshot { - self.shared.borrow().system.clone().unwrap_or(d::system::Snapshot { - cpu_permille: 0, - mem_used_kib: 0, - mem_total_kib: 0, - battery_percent: -1, - charging: false, - uptime_secs: 0, - net_rx_bytes_per_sec: 0, - net_tx_bytes_per_sec: 0, - load_centi: 0, - }) - } -} - -struct Loaded { - store: Store, - inst: ph::PlasmoidHost, - /// Present when the module exports `module-config`. - cfg: Option, - /// Present when it exports `desktop-module` (a desktop module). - desk: Option, -} - -/// A file-chooser dialog in flight (zenity on the host session). -struct Picker { - child: Child, -} - -pub struct Runtime { - engine: Engine, - linker: Linker, - pub shared: SharedRef, - slots: Vec>, - picker: Option, -} - -pub struct LoadedInfo { - pub handle: u32, - pub info: ex::plasmoid::PlasmoidInfo, - pub imports: Vec, -} - -impl Runtime { - pub fn new(engine: &Engine) -> wasmtime::Result { - let mut linker: Linker = Linker::new(engine); - ph::PlasmoidHost::add_to_linker::>(&mut linker, |s| s)?; - Ok(Runtime { - engine: engine.clone(), - linker, - shared: Rc::new(RefCell::new(Shared::default())), - slots: Vec::new(), - picker: None, - }) - } - - pub fn load(&mut self, path: &str) -> Result { - let bytes = std::fs::read(path).map_err(|_| "cannot read file".to_string())?; - if bytes.len() < 8 || &bytes[..4] != b"\0asm" { - return Err("not a wasm file".to_string()); - } - let component = Component::new(&self.engine, &bytes) - .map_err(|_| "no plasmoid (chandra:desktop/plasmoid) in this module".to_string())?; - // The capability grant: the host interfaces the binary imports, besides the base ones. - let mut imports: Vec = Vec::new(); - for (name, _) in component.component_type().imports(&self.engine) { - if let Some(rest) = name.strip_prefix("chandra:desktop/") { - let iface = rest.split('@').next().unwrap_or(rest).to_string(); - if iface != "types" && !imports.contains(&iface) { - imports.push(iface); - } - } - } - let mut store = Store::new(&self.engine, PState { shared: self.shared.clone() }); - let instance = - self.linker.instantiate(&mut store, &component).map_err(|_| "wasm runtime error".to_string())?; - let inst = ph::PlasmoidHost::new(&mut store, &instance) - .map_err(|_| "no plasmoid (chandra:desktop/plasmoid) in this module".to_string())?; - let cfg = cfg::Configurable::new(&mut store, &instance).ok(); - let desk = desk::DesktopExport::new(&mut store, &instance).ok(); - let info = inst - .chandra_desktop_plasmoid() - .call_info(&mut store) - .map_err(|_| "widget trapped in info()".to_string())?; - let l = Loaded { store, inst, cfg, desk }; - let handle = match self.slots.iter().position(|s| s.is_none()) { - Some(h) => { - self.slots[h] = Some(l); - h - } - None => { - self.slots.push(Some(l)); - self.slots.len() - 1 - } - }; - Ok(LoadedInfo { handle: handle as u32, info, imports }) - } - - pub fn unload(&mut self, handle: u32) { - if let Some(slot) = self.slots.get_mut(handle as usize) { - *slot = None; - } - } - - fn get(&mut self, handle: u32) -> Option<&mut Loaded> { - self.slots.get_mut(handle as usize).and_then(|s| s.as_mut()) - } - - /// A trapping module yields no ops. - pub fn render(&mut self, handle: u32, size: d::types::Size) -> Vec { - let Some(l) = self.get(handle) else { return Vec::new() }; - l.inst.chandra_desktop_plasmoid().call_render(&mut l.store, size).unwrap_or_default() - } - - pub fn popup(&mut self, handle: u32) -> Option { - let l = self.get(handle)?; - l.inst.chandra_desktop_plasmoid().call_popup(&mut l.store).ok().flatten() - } - - /// The module's settings; empty without `module-config` (or when it traps). - pub fn config_items(&mut self, handle: u32) -> Vec { - let Some(l) = self.get(handle) else { return Vec::new() }; - let Some(c) = &l.cfg else { return Vec::new() }; - c.chandra_desktop_module_config().call_config_items(&mut l.store).unwrap_or_default() - } - - /// Set one of the module's settings; true when it wants a redraw. - pub fn set_config(&mut self, handle: u32, key: &str, value: &str) -> bool { - let Some(l) = self.get(handle) else { return false }; - let Some(c) = &l.cfg else { return false }; - c.chandra_desktop_module_config().call_set_config(&mut l.store, key, value).unwrap_or(false) - } - - /// A desktop module's backdrop: 0 over the wallpaper, 1 replacing it; -1 for a panel module. - pub fn desktop_backdrop(&mut self, handle: u32) -> i32 { - use desk::exports::chandra::desktop::desktop_module::WallpaperMode; - let Some(l) = self.get(handle) else { return -1 }; - let Some(dm) = &l.desk else { return -1 }; - match dm.chandra_desktop_desktop_module().call_backdrop(&mut l.store) { - Ok(WallpaperMode::OverWallpaper) => 0, - Ok(WallpaperMode::ReplaceWallpaper) => 1, - Err(_) => -1, - } - } - - /// Scroll over a desktop module; true when it wants a redraw. - pub fn desktop_scroll(&mut self, handle: u32, x: i32, y: i32, dx: i32, dy: i32) -> bool { - let Some(l) = self.get(handle) else { return false }; - let Some(dm) = &l.desk else { return false }; - let at = desk::chandra::desktop::types::Point { x, y }; - dm.chandra_desktop_desktop_module().call_on_scroll(&mut l.store, at, dx, dy).unwrap_or(false) - } - - /// A desktop module's animation clock: ms until its next frame, 0 for none (or a trap). - pub fn desktop_tick(&mut self, handle: u32, now_ms: u32) -> u32 { - let Some(l) = self.get(handle) else { return 0 }; - let Some(dm) = &l.desk else { return 0 }; - dm.chandra_desktop_desktop_module().call_tick(&mut l.store, now_ms).unwrap_or(0) - } - - pub fn on_event(&mut self, handle: u32, on_popup: bool, ev: d::types::InputEvent) -> bool { - let Some(l) = self.get(handle) else { return false }; - let target = if on_popup { ex::plasmoid::Surface::Popup } else { ex::plasmoid::Surface::Widget }; - l.inst.chandra_desktop_plasmoid().call_on_event(&mut l.store, target, &ev).unwrap_or(false) - } - - pub fn picker_start(&mut self) -> bool { - if self.picker.is_some() { - return true; - } - let mut cmd = Command::new("zenity"); - cmd.args([ - "--file-selection", - "--title=Load widget (.wasm)", - "--file-filter=WebAssembly widgets | *.wasm", - "--file-filter=All files | *", - ]) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .stdin(Stdio::null()); - unsafe { - cmd.pre_exec(|| { - libc::setsid(); - Ok(()) - }); - } - match cmd.spawn() { - Ok(child) => { - self.picker = Some(Picker { child }); - true - } - Err(_) => false, - } - } - - /// None while the dialog is open; Some(None) when cancelled; Some(Some(path)) when chosen. - pub fn picker_poll(&mut self) -> Option> { - let p = self.picker.as_mut()?; - // With SIGCHLD ignored the child is reaped for us, so an error here also means "finished". - if let Ok(None) = p.child.try_wait() { - return None; - } - let mut out = String::new(); - if let Some(mut so) = p.child.stdout.take() { - let _ = so.read_to_string(&mut out); - } - self.picker = None; - let t = out.trim_end_matches(['\n', '\r']).to_string(); - Some(if t.is_empty() { None } else { Some(t) }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use d::types::{InputEvent, Point, Size}; - - fn runtime() -> Runtime { - let mut cfg = wasmtime::Config::new(); - cfg.wasm_component_model(true); - Runtime::new(&Engine::new(&cfg).unwrap()).unwrap() - } - - /// A table: LE u32 row count, then fields as LE u32 length + UTF-8. - fn apps_table(apps: &[(&str, &str)]) -> Vec { - let mut b = (apps.len() as u32).to_le_bytes().to_vec(); - for (id, name) in apps { - for f in [id, name, &"comment", &"System", &"T"] { - b.extend((f.len() as u32).to_le_bytes()); - b.extend(f.as_bytes()); - } - } - b - } - - fn texts(ops: &[d::types::DrawOp]) -> Vec { - ops.iter() - .filter_map(|o| if let d::types::DrawOp::Text(t) = o { Some(t.text.clone()) } else { None }) - .collect() - } - - fn module(name: &str) -> String { - for p in [format!("../build/components/{name}.wasm"), format!("build/components/{name}.wasm")] { - if std::path::Path::new(&p).exists() { - return p; - } - } - panic!("build/components/{name}.wasm is missing: run `just modules`"); - } - - #[test] - fn launcher_reads_the_catalog_filters_typed_keys_and_launches() { - let mut rt = runtime(); - rt.shared.borrow_mut().tables[T_APPS] = apps_table(&[("a.term", "Terminal"), ("b.files", "Files")]); - let l = rt.load(&module("launcher")).expect("launcher loads"); - // Its capability grant is what the binary imports (the MoonBit side drops the base `theme`). - let mut imports = l.imports.clone(); - imports.sort(); - assert_eq!(imports, ["app-catalog", "app-launch", "power", "session", "theme"]); - let h = l.handle; - // It draws its button. - assert!(!rt.render(h, Size { w: 190, h: 36 }).is_empty()); - // Clicking opens the popup; typing narrows it to Files; Enter launches it. - assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 1, y: 1 }))); - assert!(rt.popup(h).is_some()); - for k in ["f", "i", "l", "e", "s"] { - rt.on_event(h, true, InputEvent::KeyDown(k.to_string())); - } - assert!(texts(&rt.popup(h).expect("popup open").ops).contains(&"Files".to_string())); - assert!(rt.on_event(h, true, InputEvent::KeyDown("Enter".to_string()))); - match rt.shared.borrow_mut().requests.pop_front() { - Some(Req::Launch(id)) => assert_eq!(id, "b.files"), - _ => panic!("expected a launch request"), - } - assert!(rt.popup(h).is_none()); - rt.unload(h); - } - - #[test] - fn modules_are_rejected_cleanly() { - let mut rt = runtime(); - assert!(rt.load("/nonexistent.wasm").is_err()); - let junk = std::env::temp_dir().join("chandra-junk.wasm"); - std::fs::write(&junk, b"not wasm at all").unwrap(); - assert!(rt.load(junk.to_str().unwrap()).is_err()); - } - - #[test] - fn module_settings_are_listed_and_set_when_the_module_exports_them() { - let mut rt = runtime(); - let c = rt.load(&module("clock-digital")).expect("clock loads"); - let items = rt.config_items(c.handle); - assert_eq!(items.len(), 2); - assert_eq!(items[0].key, "format"); - assert_eq!(items[0].choices, vec!["24-hour".to_string(), "12-hour".to_string()]); - assert_eq!(items[0].value, "24-hour"); - assert!(rt.set_config(c.handle, "format", "12-hour")); - assert!(!rt.set_config(c.handle, "bogus", "x")); - assert_eq!(rt.config_items(c.handle)[0].value, "12-hour"); - let ops = rt.render(c.handle, d::types::Size { w: 120, h: 36 }); - assert!(texts(&ops).iter().any(|t| t.ends_with("AM") || t.ends_with("PM"))); - // A module without the export: no settings, and setting one does nothing. - let l = rt.load(&module("layout")).expect("layout loads"); - assert!(rt.config_items(l.handle).is_empty()); - assert!(!rt.set_config(l.handle, "format", "12-hour")); - } - - #[test] - fn layout_module_follows_the_published_mode_and_sets_it() { - let mut rt = runtime(); - let l = rt.load(&module("layout")).expect("layout loads"); - assert!(l.imports.contains(&"layout-control".to_string())); - // layouts table: one string field per row - let mut t = 3u32.to_le_bytes().to_vec(); - for n in ["Tiling (BSP)", "Monocle", "Floating"] { - t.extend((n.len() as u32).to_le_bytes()); - t.extend(n.as_bytes()); - } - rt.shared.borrow_mut().tables[T_LAYOUTS] = t; - rt.shared.borrow_mut().layout_mode = 0; - let ops = rt.render(l.handle, Size { w: 120, h: 36 }); - assert!(!texts(&ops).is_empty()); - rt.unload(l.handle); - } - - #[test] - fn launcher_session_row_reloads_and_logs_out_after_confirming() { - let mut rt = runtime(); - let l = rt.load(&module("launcher")).expect("launcher loads"); - assert!(l.imports.contains(&"session".to_string())); - assert!(l.imports.contains(&"power".to_string())); - let h = l.handle; - // Open the menu; its last row is the session row. - assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); - let p = rt.popup(h).expect("popup open"); - let t = texts(&p.ops); - for b in ["Reload", "Log out", "Suspend", "Restart", "Power off"] { - assert!(t.contains(&b.to_string()), "{b} missing from {t:?}"); - } - // Button i's centre: 5 buttons across 340 px with 8 px margins and 4 px gaps, in a - // 44 px row at the bottom (lib/launcher). - let button = |i: i32, ph: i32| Point { x: 8 + i * 65 + 30, y: ph - 44 + 6 + 15 }; - let ph = p.size.h as i32; - // Log out: the first click only arms it, the second requests it. - assert!(rt.on_event(h, true, InputEvent::PointerDown(button(1, ph)))); - assert!(rt.shared.borrow().requests.is_empty()); - let p = rt.popup(h).expect("still open"); - assert!(texts(&p.ops).contains(&"Click Log out again to confirm".to_string())); - let ph = p.size.h as i32; - assert!(rt.on_event(h, true, InputEvent::PointerDown(button(1, ph)))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Logout))); - assert!(rt.popup(h).is_none()); - // Reload acts at once. - rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })); - let ph = rt.popup(h).expect("open").size.h as i32; - assert!(rt.on_event(h, true, InputEvent::PointerDown(button(0, ph)))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::ReloadSession))); - // Suspend acts at once too, through the power capability. - rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })); - let ph = rt.popup(h).expect("open").size.h as i32; - assert!(rt.on_event(h, true, InputEvent::PointerDown(button(2, ph)))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::PowerAction(0)))); - rt.unload(h); - } - - #[test] - fn settings_module_shows_switches_and_wallpapers_and_requests_changes() { - let mut rt = runtime(); - let l = rt.load(&module("session-settings")).expect("session-settings loads"); - assert!(l.imports.contains(&"session-settings".to_string())); - let h = l.handle; - assert!(l.imports.contains(&"wallpaper".to_string())); - let table = |names: &[&str]| { - let mut t = (names.len() as u32).to_le_bytes().to_vec(); - for n in names { - t.extend((n.len() as u32).to_le_bytes()); - t.extend(n.as_bytes()); - } - t - }; - let names = ["Reopen windows at login", "Remember window positions", "Dark mode"]; - let walls = ["Plasma glow", "Aurora", "Starfield"]; - rt.shared.borrow_mut().tables[T_SESSION_SETTINGS] = table(&names); - rt.shared.borrow_mut().tables[T_WALLPAPERS] = table(&walls); - rt.shared.borrow_mut().session_settings = 0b101; // reopen on, remember off, dark on - rt.shared.borrow_mut().wallpaper = 1; - assert!(texts(&rt.render(h, Size { w: 92, h: 34 })).contains(&"Settings".to_string())); - // A click opens the list of every setting; nothing is requested yet. - assert!(rt.popup(h).is_none()); - assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); - let p = rt.popup(h).expect("popup open"); - for n in names.iter().chain(["Session", "Desktop", "Panel"].iter()) { - assert!(texts(&p.ops).contains(&n.to_string()), "{n} listed"); - } - assert!(rt.shared.borrow().requests.is_empty()); - // First row is on: a click asks to turn it off. Second row is off: a click asks for on. - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 13 }))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSessionSetting(0, false)))); - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 28 + 13 }))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSessionSetting(1, true)))); - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 2 * 28 + 13 }))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSessionSetting(2, false)))); - // The Desktop tab (second of four 72 px tabs): row 0 is the "Wallpaper" heading - // (nothing), rows 1.. the wallpapers: Starfield. - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 6 + 72 + 36, y: 6 + 14 }))); - assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Starfield".to_string())); - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 13 }))); - assert!(rt.shared.borrow().requests.is_empty()); - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 3 * 28 + 13 }))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetWallpaper(2)))); - // The list stays open; Escape closes it without another request. - assert!(rt.popup(h).is_some()); - assert!(rt.on_event(h, true, InputEvent::KeyDown("Escape".to_string()))); - assert!(rt.popup(h).is_none()); - assert!(rt.shared.borrow().requests.is_empty()); - rt.unload(h); - } - - #[test] - fn screenshot_module_offers_the_modes_and_asks_for_them() { - let mut rt = runtime(); - let l = rt.load(&module("screenshot")).expect("screenshot loads"); - assert!(l.imports.contains(&"screenshot".to_string())); - let h = l.handle; - rt.shared.borrow_mut().screenshot = 0b10; // not recording, pointer shown - assert!(texts(&rt.render(h, Size { w: 110, h: 34 })).contains(&"Screenshot".to_string())); - assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); - let p = rt.popup(h).expect("popup open"); - for n in ["Rectangular Region", "Full Screen", "Record a Region", "Show pointer in recordings"] { - assert!(texts(&p.ops).contains(&n.to_string()), "{n} listed"); - } - // Row 2 (Full Screen): the popup closes and a full-screen shot is asked for. - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 6 + 2 * 30 + 5 }))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(1)))); - assert!(rt.popup(h).is_none()); - // Reopen; Record the Screen (row 7). - assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 6 + 7 * 30 + 5 }))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(11)))); - // While recording the button reads Stop, and a click stops it. - rt.shared.borrow_mut().screenshot = 0b11; - assert!(texts(&rt.render(h, Size { w: 110, h: 34 })).contains(&"Stop".to_string())); - assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(20)))); - assert!(rt.popup(h).is_none()); - rt.unload(h); - } - - #[test] - fn settings_power_tab_steps_timeouts_and_confirms_power_off() { - let mut rt = runtime(); - let l = rt.load(&module("session-settings")).expect("session-settings loads"); - assert!(l.imports.contains(&"power".to_string())); - let h = l.handle; - rt.shared.borrow_mut().screen_off_min = 10; - rt.shared.borrow_mut().suspend_min = 0; - assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); - assert!(rt.on_event(h, true, InputEvent::KeyDown("4".to_string()))); // the Power tab - let ts = texts(&rt.popup(h).expect("popup open").ops); - for want in ["Turn screen off after", "10 min", "Suspend after", "Never", "Power off"] { - assert!(ts.contains(&want.to_string()), "{want} shown"); - } - // No battery: rows of 28 below the tab bar (40) are When idle, screen off, suspend, Now, - // Suspend, Restart, Power off. - let row = |i: i32| Point { x: 20, y: 40 + i * 28 + 13 }; - assert!(rt.on_event(h, true, InputEvent::PointerDown(row(1)))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetScreenOff(15)))); - assert!(rt.on_event(h, true, InputEvent::PointerDown(row(2)))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSuspendAfter(5)))); - // Power off takes two clicks. - assert!(rt.on_event(h, true, InputEvent::PointerDown(row(6)))); - assert!(rt.shared.borrow().requests.is_empty()); - assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Click again to power off".to_string())); - assert!(rt.on_event(h, true, InputEvent::PointerDown(row(6)))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::PowerAction(1)))); - rt.unload(h); - } - - #[test] - fn battery_module_shows_charge_time_left_and_warns() { - let mut rt = runtime(); - let l = rt.load(&module("battery")).expect("battery loads"); - assert!(l.imports.contains(&"battery".to_string())); - let h = l.handle; - let size = Size { w: 104, h: 34 }; - // No battery: a plug and no text. - assert!(!rt.render(h, size).is_empty()); - assert!(texts(&rt.render(h, size)).is_empty()); - rt.shared.borrow_mut().battery = (64, 1, 2 * 3600 + 5 * 60); - assert_eq!(texts(&rt.render(h, size)), vec!["64% 2:05".to_string()]); - assert!(rt.set_config(h, "time", "off")); - assert_eq!(texts(&rt.render(h, size)), vec!["64%".to_string()]); - // Critical: the warning opens by itself; a click on it closes it. - rt.shared.borrow_mut().battery = (7, 1, 600); - rt.render(h, size); - let ts = texts(&rt.popup(h).expect("warning open").ops); - assert!(ts.contains(&"Battery low: 7%".to_string())); - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 5, y: 5 }))); - assert!(rt.popup(h).is_none()); - rt.unload(h); - } - /// Table bytes from rows of fields ('i' a number, 's' a string). - enum F<'a> { - I(i32), - S(&'a str), - } - fn rows_table(rows: &[Vec]) -> Vec { - let mut t = (rows.len() as u32).to_le_bytes().to_vec(); - for r in rows { - for f in r { - match f { - F::I(v) => t.extend(v.to_le_bytes()), - F::S(s) => { - t.extend((s.len() as u32).to_le_bytes()); - t.extend(s.as_bytes()); - } - } - } - } - t - } - - #[test] - fn network_module_shows_the_connection_and_connects_with_a_password() { - let mut rt = runtime(); - let l = rt.load(&module("network")).expect("network loads"); - assert!(l.imports.contains(&"network".to_string())); - let h = l.handle; - { - let mut sh = rt.shared.borrow_mut(); - // Wi-Fi "Home" at 72%, NetworkManager there, Wi-Fi on. - sh.tables[T_NET_STATUS] = rows_table(&[vec![ - F::I(2), - F::I(72), - F::S("Home"), - F::S(""), - F::I(1), - F::I(0), - F::I(1), - F::I(1), - ]]); - sh.tables[T_NET_NETWORKS] = rows_table(&[ - vec![F::S("Home"), F::I(72), F::I(1), F::I(1), F::I(1)], - vec![F::S("Office"), F::I(55), F::I(1), F::I(0), F::I(0)], - ]); - } - assert!(texts(&rt.render(h, Size { w: 130, h: 34 })).contains(&"Home".to_string())); - // Opening the popup asks for a scan. - assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Network(0, _, _)))); - let p = rt.popup(h).expect("popup open"); - for n in ["Connected to Home (72%)", "Wi-Fi", "Airplane mode", "Office", "Secured"] { - assert!(texts(&p.ops).contains(&n.to_string()), "{n} listed"); - } - // Row 5 (Office) opens the password field; typing and Enter connects. - let row = |i: i32| Point { x: 60, y: 6 + i * 30 + 14 }; - assert!(rt.on_event(h, true, InputEvent::PointerDown(row(5)))); - assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Password|".to_string())); - for k in ["p", "w", "Enter"] { - rt.on_event(h, true, InputEvent::KeyDown(k.to_string())); - } - match rt.shared.borrow_mut().requests.pop_front() { - Some(Req::Network(6, ssid, pw)) => assert_eq!((ssid.as_str(), pw.as_str()), ("Office", "pw")), - _ => panic!("connect asked for"), - } - // The Wi-Fi switch (row 1). - assert!(rt.on_event(h, true, InputEvent::PointerDown(row(1)))); - assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Network(2, _, _)))); - rt.unload(h); - } - - #[test] - fn gamerig_library_shows_the_daemons_games_and_launches_big_picture() { - let mut rt = runtime(); - let l = rt.load(&module("gamerig-library")).expect("gamerig-library loads"); - assert!(l.imports.contains(&"game-library".to_string())); - let h = l.handle; - { - let mut sh = rt.shared.borrow_mut(); - sh.tables[T_GL_STATUS] = rows_table(&[vec![ - F::S(""), - F::S("NVIDIA GeForce GTX 1650"), - F::S("1280x720"), - F::S(":0"), - F::S("PulseAudio"), - F::S("rig"), - F::I(1), - F::I(1), - ]]); - sh.tables[T_GL_GAMES] = rows_table(&[vec![ - F::S("steam"), - F::S("Steam"), - F::S("games"), - F::S("Your Steam library."), - F::S("Play"), - F::S(""), - F::I(1), - F::I(1), - F::I(0), - ]]); - sh.tables[T_GL_MODES] = rows_table(&[vec![F::S("steam"), F::S("bigpicture"), F::S("Big Picture")]]); - } - let ops = rt.render(h, Size { w: 1280, h: 720 }); - let t = texts(&ops); - for n in ["Gamerig", "Steam", "Big Picture", "Rig Status", "PulseAudio"] { - assert!(t.contains(&n.to_string()), "{n} shown"); - } - // Click Big Picture: a launch request with its mode. - let at = ops - .iter() - .find_map(|o| match o { - d::types::DrawOp::Text(t) if t.text == "Big Picture" => Some(t.origin), - _ => None, - }) - .expect("Big Picture button"); - let p = Point { x: at.x + 4, y: at.y }; - rt.on_event(h, false, InputEvent::PointerDown(p)); - rt.on_event(h, false, InputEvent::PointerUp(p)); - match rt.shared.borrow_mut().requests.pop_front() { - Some(Req::GameLibrary(0, game, mode)) => assert_eq!((game.as_str(), mode.as_str()), ("steam", "bigpicture")), - other => panic!("expected a launch, got {:?}", other.is_some()), - } - rt.unload(h); - } -} \ No newline at end of file diff --git a/host-wasm/src/raster.rs b/host-wasm/src/raster.rs deleted file mode 100644 index 54ed240..0000000 --- a/host-wasm/src/raster.rs +++ /dev/null @@ -1,1401 +0,0 @@ -//! The host's rasteriser (`chandra:host/raster`). -//! -//! A direct port of compositor/renderer (the pure-MoonBit software renderer), so a frame comes out -//! pixel for pixel the same, but native: the compositor component sends draw operations and window -//! surface ids, and the pixels never cross the component boundary. Window buffers are copied out of -//! the client's shared memory once, at commit (`capture`), converted to RGBA, and kept here. - -use crate::chandra::host::raster as wt; -use ab_glyph::{Font, FontVec, OutlineCurve}; -use ab_glyph_rasterizer::{point, Rasterizer}; -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; - -// ---------------------------------------------------------------- fonts - -/// A rasterised glyph: an 8-bit coverage bitmap whose top-left sits at (`xoff`, `yoff`) from the -/// pen on the baseline (y grows downward), and the pen advance. -pub struct Glyph { - pub w: i32, - pub h: i32, - pub xoff: i32, - pub yoff: i32, - pub advance: i32, - pub coverage: Vec, -} - -/// TTF faces loaded by the component (`font.load`), by slot, and a cache of their glyphs. -#[derive(Default)] -pub struct Fonts { - faces: [Option; 4], - cache: HashMap<(u32, u32, u32), Rc>, -} - -impl Fonts { - pub fn load(&mut self, slot: u32, path: &str) -> bool { - if slot as usize >= self.faces.len() { - return false; - } - match std::fs::read(path).ok().and_then(|d| FontVec::try_from_vec(d).ok()) { - Some(f) => { - self.faces[slot as usize] = Some(f); - self.cache.retain(|k, _| k.0 != slot); - true - } - None => false, - } - } - - fn has(&self, slot: u32) -> bool { - self.faces.get(slot as usize).map_or(false, |f| f.is_some()) - } - - /// Same maths as stb_truetype in the native build: the size is an em size in pixels, the glyph - /// origin sits on the integer pixel grid, and the bitmap box is the outline's floor/ceil bounds. - pub fn glyph(&mut self, slot: u32, cp: u32, size: u32) -> Rc { - if let Some(g) = self.cache.get(&(slot, cp, size)) { - return g.clone(); - } - let g = Rc::new(self.rasterise(slot, cp, size)); - self.cache.insert((slot, cp, size), g.clone()); - g - } - - fn rasterise(&self, slot: u32, cp: u32, size: u32) -> Glyph { - let blank = Glyph { w: 0, h: 0, xoff: 0, yoff: 0, advance: 0, coverage: Vec::new() }; - let Some(Some(font)) = self.faces.get(slot as usize) else { return blank }; - let ch = char::from_u32(cp).unwrap_or('\u{fffd}'); - let id = font.glyph_id(ch); - let s = size as f32 / font.units_per_em().unwrap_or(1000.0); - let advance = (font.h_advance_unscaled(id) * s + 0.5) as i32; - let Some(outline) = font.outline(id) else { return Glyph { advance, ..blank } }; - // Font units grow upward, pixels downward; ab_glyph stores the outline's top edge as - // `min.y` and its bottom edge as `max.y`, both in font units. - let x0 = (outline.bounds.min.x * s).floor() as i32; - let x1 = (outline.bounds.max.x * s).ceil() as i32; - let y0 = (-outline.bounds.min.y * s).floor() as i32; - let y1 = (-outline.bounds.max.y * s).ceil() as i32; - let (w, h) = (x1 - x0, y1 - y0); - if w <= 0 || h <= 0 { - return Glyph { advance, ..blank }; - } - let tp = |p: ab_glyph::Point| point(p.x * s - x0 as f32, -p.y * s - y0 as f32); - let mut r = Rasterizer::new(w as usize, h as usize); - for c in &outline.curves { - match c { - OutlineCurve::Line(a, b) => r.draw_line(tp(*a), tp(*b)), - OutlineCurve::Quad(a, b, c) => r.draw_quad(tp(*a), tp(*b), tp(*c)), - OutlineCurve::Cubic(a, b, c, d) => r.draw_cubic(tp(*a), tp(*b), tp(*c), tp(*d)), - } - } - let mut coverage = vec![0u8; (w * h) as usize]; - r.for_each_pixel(|i, a| coverage[i] = (a.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); - Glyph { w, h, xoff: x0, yoff: y0, advance, coverage } - } - - /// The glyph for `cp` in the face the UI uses for (bold, mono), and whether it must be - /// emboldened (a face with no bold instance gets its glyphs drawn a pixel wider). - /// Slots: 0 mono, 1 mono bold, 2 sans. None when no face is loaded at all. - fn pick(&mut self, cp: u32, size: u32, bold: bool, mono: bool) -> Option<(Rc, bool)> { - let has_mono = self.has(0); - let has_sans = self.has(2); - if !has_mono && !has_sans { - return None; - } - let has_bold = has_mono && self.has(1); - let (slot, embolden) = if mono && has_mono { - if bold && has_bold { (1, false) } else { (0, bold) } - } else if has_sans { - (2, bold) - } else { - (0, bold) - }; - Some((self.glyph(slot, cp, size), embolden)) - } -} - -// ---------------------------------------------------------------- canvas - -/// What every drawing function paints on: an RGBA8888 buffer. -pub struct Canvas<'a> { - pub w: i32, - pub h: i32, - pub data: &'a mut [u8], -} - -#[derive(Clone, Copy)] -struct R { - x: i32, - y: i32, - w: i32, - h: i32, -} - -impl From for R { - fn from(r: wt::Rect) -> R { - R { x: r.x, y: r.y, w: r.w, h: r.h } - } -} - -type Clip = Option; - -fn clamp_u8(v: i32) -> u8 { - v.clamp(0, 255) as u8 -} - -/// Blend one pixel; `clip` and the canvas bounds are checked. -fn blend_pixel(c: &mut Canvas, x: i32, y: i32, r: i32, g: i32, b: i32, a: i32, clip: Clip) { - if x < 0 || y < 0 || x >= c.w || y >= c.h || a <= 0 { - return; - } - if let Some(k) = clip { - if x < k.x || y < k.y || x >= k.x + k.w || y >= k.y + k.h { - return; - } - } - let off = ((y * c.w + x) * 4) as usize; - let d = &mut c.data[off..off + 4]; - if a >= 255 { - d[0] = r as u8; - d[1] = g as u8; - d[2] = b as u8; - d[3] = 0xff; - return; - } - let inv = 255 - a; - d[0] = ((r * a + d[0] as i32 * inv + 127) / 255) as u8; - d[1] = ((g * a + d[1] as i32 * inv + 127) / 255) as u8; - d[2] = ((b * a + d[2] as i32 * inv + 127) / 255) as u8; - d[3] = clamp_u8(a + (d[3] as i32 * inv + 127) / 255); -} - -/// Blend a colour over pixels [xa, xb) of row `y`; the span is already clipped. -fn blend_span(c: &mut Canvas, y: i32, xa: i32, xb: i32, r: i32, g: i32, b: i32, a: i32) { - if xa >= xb || a <= 0 { - return; - } - let row = &mut c.data[((y * c.w + xa) * 4) as usize..((y * c.w + xb) * 4) as usize]; - if a >= 255 { - for p in row.chunks_exact_mut(4) { - p[0] = r as u8; - p[1] = g as u8; - p[2] = b as u8; - p[3] = 0xff; - } - return; - } - // Two channels at a time in 16-bit lanes with an exact floor(v / 255): the same pixels as - // c' = (c * a + d * (255 - a) + 127) / 255 per channel, and alpha a + (d * (255 - a) + 127) / 255 - // (the alpha lane adds a * 255 before dividing, which is the same). - let inv = (255 - a) as u32; - let rbadd = (((b * a + 127) as u32) << 16) | (r * a + 127) as u32; - let agadd = (((255 * a + 127) as u32) << 16) | (g * a + 127) as u32; - for p in row.chunks_exact_mut(4) { - let px = u32::from_le_bytes([p[0], p[1], p[2], p[3]]); - let mut rb = (px & 0x00FF_00FF) * inv + rbadd; - let mut ag = ((px >> 8) & 0x00FF_00FF) * inv + agadd; - rb = ((rb + ((rb >> 8) & 0x00FF_00FF) + 0x0001_0001) >> 8) & 0x00FF_00FF; - ag = (ag + ((ag >> 8) & 0x00FF_00FF) + 0x0001_0001) & 0xFF00_FF00; - p.copy_from_slice(&(rb | ag).to_le_bytes()); - } -} - -/// True when (px, py) is inside the rectangle whose corners have radius `rad`. -fn in_rounded_rect(px: i32, py: i32, rx: i32, ry: i32, rw: i32, rh: i32, rad: i32) -> bool { - if px < rx || py < ry || px >= rx + rw || py >= ry + rh { - return false; - } - if rad <= 0 { - return true; - } - let max_r = rw.min(rh) / 2; - let r = rad.min(max_r); - if r <= 0 { - return true; - } - let (x_left, x_right) = (rx + r, rx + rw - r - 1); - let (y_top, y_bot) = (ry + r, ry + rh - r - 1); - let corner = |dx: i32, dy: i32| dx * dx + dy * dy <= r * r; - if px < x_left && py < y_top { - corner(x_left - px, y_top - py) - } else if px > x_right && py < y_top { - corner(px - x_right, y_top - py) - } else if px < x_left && py > y_bot { - corner(x_left - px, py - y_bot) - } else if px > x_right && py > y_bot { - corner(px - x_right, py - y_bot) - } else { - true - } -} - -/// The part of `rect` that is on the canvas and inside `clip`, as (x0, y0, x1, y1). -fn visible(c: &Canvas, rect: R, clip: Clip) -> Option<(i32, i32, i32, i32)> { - let (mut x0, mut y0) = (rect.x.max(0), rect.y.max(0)); - let (mut x1, mut y1) = ((rect.x + rect.w).min(c.w), (rect.y + rect.h).min(c.h)); - if let Some(k) = clip { - x0 = x0.max(k.x); - y0 = y0.max(k.y); - x1 = x1.min(k.x + k.w); - y1 = y1.min(k.y + k.h); - } - if x0 >= x1 || y0 >= y1 { None } else { Some((x0, y0, x1, y1)) } -} - -fn fill_rounded_rect(c: &mut Canvas, rect: R, col: wt::Color, radius: i32, clip: Clip) { - if rect.w <= 0 || rect.h <= 0 || col.a == 0 { - return; - } - let Some((x0, y0, x1, y1)) = visible(c, rect, clip) else { return }; - let (cr, cg, cb, ca) = (col.r as i32, col.g as i32, col.b as i32, col.a as i32); - if radius <= 0 { - for y in y0..y1 { - blend_span(c, y, x0, x1, cr, cg, cb, ca); - } - return; - } - let r = radius.min(rect.w.min(rect.h) / 2); - let (x_left, x_right) = (rect.x + r, rect.x + rect.w - r - 1); - let (y_top, y_bot) = (rect.y + r, rect.y + rect.h - r - 1); - for y in y0..y1 { - if y >= y_top && y <= y_bot { - blend_span(c, y, x0, x1, cr, cg, cb, ca); - continue; - } - let mut x = x0; - while x < x1 && x < x_left { - if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) { - blend_span(c, y, x, x + 1, cr, cg, cb, ca); - } - x += 1; - } - let (mid_a, mid_b) = (x_left.max(x0), (x_right + 1).min(x1)); - blend_span(c, y, mid_a, mid_b, cr, cg, cb, ca); - x = (x_right + 1).max(x0).max(mid_a); - while x < x1 { - if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) { - blend_span(c, y, x, x + 1, cr, cg, cb, ca); - } - x += 1; - } - } -} - -fn stroke_rounded_rect(c: &mut Canvas, rect: R, col: wt::Color, width: i32, radius: i32, clip: Clip) { - if rect.w <= 0 || rect.h <= 0 || width <= 0 || col.a == 0 { - return; - } - let (x0, y0) = (rect.x.max(0), rect.y.max(0)); - let (x1, y1) = ((rect.x + rect.w).min(c.w), (rect.y + rect.h).min(c.h)); - let (cr, cg, cb, ca) = (col.r as i32, col.g as i32, col.b as i32, col.a as i32); - let (inner_x, inner_y) = (rect.x + width, rect.y + width); - let (inner_w, inner_h) = (rect.w - width * 2, rect.h - width * 2); - let inner_r = if radius > width { radius - width } else { 0 }; - let (cx0, cx1, cy0, cy1) = match clip { - Some(k) => (k.x, k.x + k.w, k.y, k.y + k.h), - None => (0, c.w, 0, c.h), - }; - // Rows where the inner rectangle is full width only have the two side strips to draw. - let (mid_a, mid_b) = (inner_y + inner_r, inner_y + inner_h - inner_r); - for y in y0..y1 { - if inner_w > 0 && inner_h > 0 && y >= mid_a && y < mid_b { - if y >= cy0 && y < cy1 { - let l0 = x0.max(cx0); - let l1 = inner_x.min(x1).min(cx1); - blend_span(c, y, l0, l1, cr, cg, cb, ca); - let r0 = (inner_x + inner_w).max(x0).max(cx0); - blend_span(c, y, r0, x1.min(cx1), cr, cg, cb, ca); - } - continue; - } - for x in x0..x1 { - let in_outer = in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius); - let in_inner = inner_w > 0 - && inner_h > 0 - && in_rounded_rect(x, y, inner_x, inner_y, inner_w, inner_h, inner_r); - if in_outer && !in_inner { - blend_pixel(c, x, y, cr, cg, cb, ca, clip); - } - } - } -} - -fn draw_line(c: &mut Canvas, s: &wt::Segment, ox: i32, oy: i32, clip: Clip) { - let (cr, cg, cb, ca) = (s.color.r as i32, s.color.g as i32, s.color.b as i32, s.color.a as i32); - let half = if s.width <= 1 { 0 } else { s.width / 2 }; - let (mut x0, mut y0) = (s.x0 + ox, s.y0 + oy); - let (x1, y1) = (s.x1 + ox, s.y1 + oy); - let dx = (x1 - x0).abs(); - let sx = if x0 < x1 { 1 } else { -1 }; - let dy = -(y1 - y0).abs(); - let sy = if y0 < y1 { 1 } else { -1 }; - let mut err = dx + dy; - loop { - for oy2 in -half..=half { - for ox2 in -half..=half { - blend_pixel(c, x0 + ox2, y0 + oy2, cr, cg, cb, ca, clip); - } - } - if x0 == x1 && y0 == y1 { - break; - } - let e2 = 2 * err; - if e2 >= dy { - err += dy; - x0 += sx; - } - if e2 <= dx { - err += dx; - y0 += sy; - } - } -} - -fn draw_circle(c: &mut Canvas, d: &wt::Disc, ox: i32, oy: i32, clip: Clip) { - if d.radius <= 0 { - return; - } - let (cr, cg, cb, ca) = (d.color.r as i32, d.color.g as i32, d.color.b as i32, d.color.a as f64); - let rad = d.radius as f64; - let (cx, cy) = (d.cx + ox, d.cy + oy); - // Row by row: the antialiased edge pixel by pixel, a filled disc's solid middle (dist <= rad - // - 0.5, full coverage) as one span and a ring's empty middle (dist <= rad - 2) skipped. The - // same pixels as testing every pixel of the bounding box. - let solid = if d.filled { - (rad - 0.5) * (rad - 0.5) - } else if rad >= 2.0 { - (rad - 2.0) * (rad - 2.0) - } else { - -1.0 - }; - for dy in (-d.radius - 1)..=(d.radius + 1) { - let y = cy + dy; - if y < 0 || y >= c.h || clip.is_some_and(|k| y < k.y || y >= k.y + k.h) { - continue; - } - let left = solid - (dy * dy) as f64; - let mut m: i32 = -1; - if left >= 0.0 { - m = left.sqrt() as i32; - while ((m + 1) * (m + 1)) as f64 <= left { - m += 1; - } - while m >= 0 && (m * m) as f64 > left { - m -= 1; - } - } - let mut dx = -d.radius - 1; - while dx <= d.radius + 1 { - if m >= 0 && dx == -m { - if d.filled { - let (mut xa, mut xb) = ((cx - m).max(0), (cx + m + 1).min(c.w)); - if let Some(k) = clip { - xa = xa.max(k.x); - xb = xb.min(k.x + k.w); - } - blend_span(c, y, xa, xb, cr, cg, cb, ca as i32); - } - dx = m + 1; - continue; - } - let dist = ((dx * dx + dy * dy) as f64).sqrt(); - let outer = rad + 0.5 - dist; - let mut cov = if outer > 1.0 { 1.0 } else { outer }; - if !d.filled { - let inner = dist - (rad - 1.0 - 0.5); - let ic = if inner > 1.0 { 1.0 } else { inner }; - if ic < cov { - cov = ic; - } - } - if cov > 0.02 { - blend_pixel(c, cx + dx, y, cr, cg, cb, (ca * cov).round() as i32, clip); - } - dx += 1; - } - } -} - -fn draw_text(c: &mut Canvas, fonts: &mut Fonts, t: &wt::Label, ox: i32, oy: i32, clip: Clip) { - if t.text.is_empty() || t.color.a == 0 { - return; - } - let size = t.size.max(0) as u32; - let mut glyphs: Vec<(Rc, bool)> = Vec::new(); - let mut total_w = 0; - for ch in t.text.chars() { - match fonts.pick(ch as u32, size, t.bold, t.mono) { - Some((g, e)) => { - total_w += g.advance + if e { 1 } else { 0 }; - glyphs.push((g, e)); - } - None => return, // no face loaded: nothing to draw with - } - } - let x = t.x + ox; - let start_x = match t.align { - 1 => x - total_w / 2, - 2 => x - total_w, - _ => x, - }; - // `y` is the vertical centre of the text; centre the capital height ('H') on it. - let Some((cap, _)) = fonts.pick(72, size, false, t.mono) else { return }; - let baseline = t.y + oy + (-cap.yoff) / 2; - let (cr, cg, cb, ca) = (t.color.r as i32, t.color.g as i32, t.color.b as i32, t.color.a as i32); - let mut pen = start_x; - for (g, embolden) in &glyphs { - for row in 0..g.h { - for col in 0..g.w { - let cov = g.coverage[(row * g.w + col) as usize] as i32; - if cov > 0 { - let px = pen + g.xoff + col; - let py = baseline + g.yoff + row; - blend_pixel(c, px, py, cr, cg, cb, ca * cov / 255, clip); - if *embolden { - blend_pixel(c, px + 1, py, cr, cg, cb, ca * cov / 255, clip); - } - } - } - } - pen += g.advance + if *embolden { 1 } else { 0 }; - } -} - -// ---------------------------------------------------------------- images - -/// An image loaded with `load-image` (an app icon). An SVG keeps its tree, so it is rendered sharp at -/// each size it is drawn at; a PNG is kept as RGBA8888 and scaled. -enum ImageSrc { - Pixels { w: i32, h: i32, rgba: Vec }, - Svg(resvg::usvg::Tree), -} - -/// Loaded images by handle (`index + 1`), the handle of each path, and each image at the sizes it -/// has been drawn at (RGBA8888, not premultiplied). -#[derive(Default)] -pub struct Images { - srcs: Vec, - by_path: HashMap, - sized: RefCell>>>, - /// Window previews (`Raster::thumbnail`): made at the size they settle at, so at any other - /// size (gliding in the overview) they are sampled straight from their pixels, not scaled - /// and kept. - previews: std::collections::HashSet, -} - -/// Biggest image side accepted from a file, and drawn. -const MAX_IMAGE: i32 = 1024; -/// The largest size an image is drawn at (a window preview gliding to its window's size). -const MAX_DRAW: i32 = 4096; - -/// Sizes past which only one scaled copy of an image is cached (icons are drawn at a few small -/// sizes; previews at one large one, or a new one each frame while they move). -fn big_size(w: i32, h: i32) -> bool { - w * h > 128 * 128 -} - -fn decode_png(bytes: &[u8]) -> Option { - let mut dec = png::Decoder::new(std::io::Cursor::new(bytes)); - // Palette, grey and 16-bit images come out as 8-bit grey/GA/RGB/RGBA. - dec.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); - let mut reader = dec.read_info().ok()?; - let (w, h) = (reader.info().width as i32, reader.info().height as i32); - if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE { - return None; - } - let mut buf = vec![0u8; reader.output_buffer_size()]; - let info = reader.next_frame(&mut buf).ok()?; - let n = (w * h) as usize; - let mut rgba = Vec::with_capacity(n * 4); - let px = &buf[..info.buffer_size()]; - match info.color_type { - png::ColorType::Rgba => rgba.extend_from_slice(&px[..n * 4]), - png::ColorType::Rgb => px.chunks_exact(3).take(n).for_each(|p| rgba.extend_from_slice(&[p[0], p[1], p[2], 255])), - png::ColorType::GrayscaleAlpha => px.chunks_exact(2).take(n).for_each(|p| rgba.extend_from_slice(&[p[0], p[0], p[0], p[1]])), - png::ColorType::Grayscale => px.iter().take(n).for_each(|&v| rgba.extend_from_slice(&[v, v, v, 255])), - png::ColorType::Indexed => return None, - } - (rgba.len() == n * 4).then_some(ImageSrc::Pixels { w, h, rgba }) -} - -fn decode_svg(bytes: &[u8]) -> Option { - let tree = resvg::usvg::Tree::from_data(bytes, &resvg::usvg::Options::default()).ok()?; - let s = tree.size(); - (s.width() > 0.0 && s.height() > 0.0).then_some(ImageSrc::Svg(tree)) -} - -/// Scale RGBA `src` (`sw` x `sh`) to `w` x `h`: each target pixel averages the source pixels it -/// covers (alpha weighted), or takes the nearest one when enlarging. Same as the software renderer. -fn scale_rgba(src: &[u8], sw: i32, sh: i32, w: i32, h: i32) -> Vec { - let mut out = vec![0u8; (w * h * 4) as usize]; - for y in 0..h { - let y0 = y * sh / h; - let y1 = ((y + 1) * sh / h).max(y0 + 1); - for x in 0..w { - let x0 = x * sw / w; - let x1 = ((x + 1) * sw / w).max(x0 + 1); - let (mut r, mut g, mut b, mut a, mut n) = (0i64, 0i64, 0i64, 0i64, 0i64); - for sy in y0..y1 { - for sx in x0..x1 { - let o = ((sy * sw + sx) * 4) as usize; - let pa = src[o + 3] as i64; - r += src[o] as i64 * pa; - g += src[o + 1] as i64 * pa; - b += src[o + 2] as i64 * pa; - a += pa; - n += 1; - } - } - if a > 0 { - let o = ((y * w + x) * 4) as usize; - out[o] = (r / a) as u8; - out[o + 1] = (g / a) as u8; - out[o + 2] = (b / a) as u8; - out[o + 3] = (a / n) as u8; - } - } - } - out -} - -/// Render an SVG tree into a `w` x `h` RGBA8888 (not premultiplied) buffer, aspect kept and centred. -fn render_svg(tree: &resvg::usvg::Tree, w: i32, h: i32) -> Option> { - let mut pm = resvg::tiny_skia::Pixmap::new(w as u32, h as u32)?; - let s = tree.size(); - let k = (w as f32 / s.width()).min(h as f32 / s.height()); - let (dx, dy) = ((w as f32 - s.width() * k) / 2.0, (h as f32 - s.height() * k) / 2.0); - let t = resvg::tiny_skia::Transform::from_row(k, 0.0, 0.0, k, dx, dy); - resvg::render(tree, t, &mut pm.as_mut()); - let mut out = pm.take(); - for p in out.chunks_exact_mut(4) { - let a = p[3] as u32; - if a > 0 && a < 255 { - for c in &mut p[..3] { - *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8; - } - } - } - Some(out) -} - -impl Images { - /// Load the PNG or SVG at `path`; the same path gives the same handle. 0 on failure. - pub fn load(&mut self, path: &str) -> u32 { - if let Some(h) = self.by_path.get(path) { - return *h; - } - let src = std::fs::read(path).ok().and_then(|b| { - if b.starts_with(b"\x89PNG") { - decode_png(&b) - } else if path.ends_with(".svg") || path.ends_with(".svgz") { - decode_svg(&b) - } else { - None - } - }); - let h = match src { - Some(s) => { - self.srcs.push(s); - self.srcs.len() as u32 - } - None => 0, - }; - self.by_path.insert(path.to_string(), h); - h - } - - /// Store `w` x `h` RGBA pixels as an image: overwrite `reuse` when it is a handle from an earlier - /// call (its cached sizes are dropped), else add a new one. Returns the handle. - pub fn put_pixels(&mut self, reuse: u32, w: i32, h: i32, rgba: Vec) -> u32 { - let src = ImageSrc::Pixels { w, h, rgba }; - if reuse > 0 && (reuse as usize) <= self.srcs.len() && !self.by_path.values().any(|&v| v == reuse) { - self.srcs[reuse as usize - 1] = src; - self.sized.borrow_mut().retain(|k, _| k.0 != reuse); - self.previews.remove(&reuse); - return reuse; - } - self.srcs.push(src); - self.srcs.len() as u32 - } - - /// The pixels of preview `handle` when it is one and isn't `w` x `h`: (its w, h, pixels). - fn preview_at_other_size(&self, handle: u32, w: i32, h: i32) -> Option<(i32, i32, &[u8])> { - if !self.previews.contains(&handle) { - return None; - } - match self.srcs.get((handle as usize).checked_sub(1)?)? { - ImageSrc::Pixels { w: sw, h: sh, rgba } if (*sw, *sh) != (w, h) => Some((*sw, *sh, rgba)), - _ => None, - } - } - - /// Image `handle` at `w` x `h` (cached), or None for an unknown handle or a silly size. - fn sized(&self, handle: u32, w: i32, h: i32) -> Option>> { - if w <= 0 || h <= 0 || w > MAX_DRAW || h > MAX_DRAW { - return None; - } - let src = self.srcs.get((handle as usize).checked_sub(1)?)?; - if let Some(px) = self.sized.borrow().get(&(handle, w, h)) { - return Some(px.clone()); - } - let px = Rc::new(match src { - ImageSrc::Pixels { w: sw, h: sh, rgba } if *sw == w && *sh == h => rgba.clone(), - ImageSrc::Pixels { w: sw, h: sh, rgba } => scale_rgba(rgba, *sw, *sh, w, h), - ImageSrc::Svg(tree) => render_svg(tree, w, h)?, - }); - let mut sized = self.sized.borrow_mut(); - // A large image is kept at one large size only: a window preview that glides (the - // overview) is drawn at a new size every frame. - if big_size(w, h) { - sized.retain(|k, _| k.0 != handle || !big_size(k.1, k.2)); - } - sized.insert((handle, w, h), px.clone()); - Some(px) - } -} - -fn draw_image(c: &mut Canvas, imgs: &Images, p: &wt::Picture, ox: i32, oy: i32, clip: Clip) { - let (w, h) = (p.area.w, p.area.h); - if w > 0 && h > 0 && w <= MAX_DRAW && h <= MAX_DRAW { - if let Some((sw, sh, src)) = imgs.preview_at_other_size(p.image, w, h) { - // A moving preview: each pixel from the nearest source pixel, nothing kept. - let (x0, y0) = (p.area.x + ox, p.area.y + oy); - let sx: Vec = (0..w).map(|x| ((x as i64 * 2 + 1) * sw as i64 / (2 * w as i64)) as usize).collect(); - for y in 0..h { - let row = ((y as i64 * 2 + 1) * sh as i64 / (2 * h as i64)) as usize * sw as usize; - for (x, &cx) in sx.iter().enumerate() { - let o = (row + cx) * 4; - blend_pixel(c, x0 + x as i32, y0 + y, src[o] as i32, src[o + 1] as i32, src[o + 2] as i32, src[o + 3] as i32, clip); - } - } - return; - } - } - let Some(px) = imgs.sized(p.image, w, h) else { return }; - let (x0, y0) = (p.area.x + ox, p.area.y + oy); - for y in 0..h { - for x in 0..w { - let o = ((y * w + x) * 4) as usize; - blend_pixel(c, x0 + x, y0 + y, px[o] as i32, px[o + 1] as i32, px[o + 2] as i32, px[o + 3] as i32, clip); - } - } -} - -/// Draw `ops` offset by (ox, oy), with the clip stack they push and pop. -/// The overlap of two clips (None: no clip). -fn intersect(a: Clip, b: Clip) -> Clip { - match (a, b) { - (None, k) | (k, None) => k, - (Some(a), Some(b)) => { - let (x0, y0) = (a.x.max(b.x), a.y.max(b.y)); - let (x1, y1) = ((a.x + a.w).min(b.x + b.w), (a.y + a.h).min(b.y + b.h)); - Some(R { x: x0, y: y0, w: (x1 - x0).max(0), h: (y1 - y0).max(0) }) - } - } -} - -/// Draw `ops` offset by (ox, oy). `base` limits everything (the frame's damaged area); a push-clip -/// op replaces the clip within it. -fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, imgs: &Images, ops: &[wt::Op], ox: i32, oy: i32, base: Clip) { - let mut stack: Vec = Vec::new(); - for op in ops { - let clip = match stack.last() { - Some(k) => intersect(Some(*k), base), - None => base, - }; - match op { - wt::Op::FillRect(f) => { - let r = R { x: f.area.x + ox, y: f.area.y + oy, w: f.area.w, h: f.area.h }; - fill_rounded_rect(c, r, f.color, f.radius, clip); - } - wt::Op::StrokeRect(s) => { - let r = R { x: s.area.x + ox, y: s.area.y + oy, w: s.area.w, h: s.area.h }; - stroke_rounded_rect(c, r, s.color, s.width, s.radius, clip); - } - wt::Op::DrawLine(l) => draw_line(c, l, ox, oy, clip), - wt::Op::DrawCircle(d) => draw_circle(c, d, ox, oy, clip), - wt::Op::DrawText(t) => draw_text(c, fonts, t, ox, oy, clip), - wt::Op::PushClip(r) => stack.push(R { x: r.x + ox, y: r.y + oy, w: r.w, h: r.h }), - wt::Op::PopClip => { - stack.pop(); - } - wt::Op::DrawImage(p) => draw_image(c, imgs, p, ox, oy, clip), - } - } -} - -// ---------------------------------------------------------------- surfaces - -/// A client window buffer, copied out of its shared memory and converted to RGBA8888. -pub struct Surface { - w: i32, - h: i32, - rgba: Vec, - /// Every pixel has alpha 255 (XRGB, or an ARGB buffer that happens to be solid): blits copy rows. - opaque: bool, -} - -impl Surface { - /// Build one from `h` rows of `stride` bytes of little-endian B, G, R, A (or X) pixels. - pub fn from_bgra(src: &[u8], stride: usize, w: i32, h: i32, xrgb: bool) -> Option { - if w <= 0 || h <= 0 || stride < w as usize * 4 || src.len() < stride * (h as usize - 1) + w as usize * 4 { - return None; - } - let mut rgba = vec![0u8; w as usize * h as usize * 4]; - let mut opaque = true; - for y in 0..h as usize { - let s = &src[y * stride..y * stride + w as usize * 4]; - let d = &mut rgba[y * w as usize * 4..(y + 1) * w as usize * 4]; - for (sp, dp) in s.chunks_exact(4).zip(d.chunks_exact_mut(4)) { - dp[0] = sp[2]; - dp[1] = sp[1]; - dp[2] = sp[0]; - dp[3] = if xrgb { 0xff } else { sp[3] }; - opaque &= dp[3] == 0xff; - } - } - Some(Surface { w, h, rgba, opaque }) - } -} - -/// Draw a client surface into `dst`. While the client catches up with a resize its buffer is smaller -/// than the window: the buffer's bottom-right colour is extended over the rest. -fn blit_surface(c: &mut Canvas, s: &Surface, dst: R, clip: Clip) { - if s.w <= 0 || s.h <= 0 || dst.w <= 0 || dst.h <= 0 { - return; - } - if s.w < dst.w || s.h < dst.h { - let o = ((s.h - 1) * s.w + (s.w - 1)) as usize * 4; - let col = wt::Color { r: s.rgba[o], g: s.rgba[o + 1], b: s.rgba[o + 2], a: s.rgba[o + 3] }; - fill_rounded_rect(c, dst, col, 0, clip); - } - let (copy_w, copy_h) = (s.w.min(dst.w), s.h.min(dst.h)); - // Visible columns [c0, c1) and rows [r0, r1) of the buffer: on the canvas and inside the clip. - let (mut c0, mut c1) = ((-dst.x).max(0), copy_w.min(c.w - dst.x)); - let (mut r0, mut r1) = ((-dst.y).max(0), copy_h.min(c.h - dst.y)); - if let Some(k) = clip { - c0 = c0.max(k.x - dst.x); - c1 = c1.min(k.x + k.w - dst.x); - r0 = r0.max(k.y - dst.y); - r1 = r1.min(k.y + k.h - dst.y); - } - if c0 >= c1 || r0 >= r1 { - return; - } - for row in r0..r1 { - let dy = dst.y + row; - let src = &s.rgba[((row * s.w + c0) * 4) as usize..((row * s.w + c1) * 4) as usize]; - let d0 = ((dy * c.w + dst.x + c0) * 4) as usize; - let dst_row = &mut c.data[d0..d0 + src.len()]; - if s.opaque { - dst_row.copy_from_slice(src); - } else { - for (sp, dp) in src.chunks_exact(4).zip(dst_row.chunks_exact_mut(4)) { - let a = sp[3] as i32; - if a >= 255 { - dp.copy_from_slice(sp); - } else if a > 0 { - // wl_shm ARGB8888 is premultiplied: the colour already carries its alpha. - let inv = 255 - a; - dp[0] = clamp_u8(sp[0] as i32 + (dp[0] as i32 * inv + 127) / 255); - dp[1] = clamp_u8(sp[1] as i32 + (dp[1] as i32 * inv + 127) / 255); - dp[2] = clamp_u8(sp[2] as i32 + (dp[2] as i32 * inv + 127) / 255); - dp[3] = clamp_u8(a + (dp[3] as i32 * inv + 127) / 255); - } - } - } - } -} - -// ---------------------------------------------------------------- the rasteriser - -/// The framebuffer, the wallpaper cache and the captured client surfaces. -#[derive(Default)] -pub struct Raster { - pub w: i32, - pub h: i32, - /// RGBA8888, `w * h * 4` bytes. - pub fb: Vec, - wallpaper: Option<(Vec, i32, i32, Vec)>, - surfaces: HashMap, - next_id: u32, - /// Images for `draw-image` ops (app icons). - pub images: Images, - /// The last frame drawn, to work out what the next one changes. - prev: Option, - /// Pixels redrawn by the last submit (for tests and profiling). - pub last_drawn: usize, -} - -/// Room around a window's frame for its shadow, which the decoration ops draw (up to 16 px all -/// round for the flat frame, `decoration_shadow_reach` in compositor/scene). -const SHADOW_PAD: i32 = 18; - -/// What a window covers on screen: its decoration and drop shadow, or just itself when fullscreen. -fn window_footprint(win: &wt::Window) -> R { - let g = R::from(win.geometry); - if win.fullscreen { - return g; - } - R { - x: g.x - win.inset_left - SHADOW_PAD, - y: g.y - win.inset_top - SHADOW_PAD, - w: g.w + win.inset_left + win.inset_right + 2 * SHADOW_PAD, - h: g.h + win.inset_top + win.inset_bottom + 2 * SHADOW_PAD, - } -} - -/// The bounding box of two rectangles (an empty one counts for nothing). -fn union(a: R, b: R) -> R { - if a.w <= 0 || a.h <= 0 { - return b; - } - if b.w <= 0 || b.h <= 0 { - return a; - } - let (x0, y0) = (a.x.min(b.x), a.y.min(b.y)); - let (x1, y1) = ((a.x + a.w).max(b.x + b.w), (a.y + a.h).max(b.y + b.h)); - R { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } -} - -/// The part of the screen `f` changes over `prev`, as one rectangle; None when all of it must be -/// redrawn. Only window changes are narrowed down (a client drawing, a window moving, focus moving): -/// any change to the wallpaper, desktop card, panel or the set of windows redraws everything. -fn damage(prev: &wt::Frame, f: &wt::Frame) -> Option { - if prev.width != f.width || prev.height != f.height || prev.windows.len() != f.windows.len() { - return None; - } - if f.background != prev.background || f.panel != prev.panel { - return None; - } - if let Some(ops) = &f.wallpaper { - if prev.wallpaper.as_ref() != Some(ops) { - return None; - } - } - let mut d = R { x: 0, y: 0, w: 0, h: 0 }; - for (a, b) in prev.windows.iter().zip(f.windows.iter()) { - if a == b { - continue; - } - d = union(d, union(window_footprint(a), window_footprint(b))); - } - if prev.popups != f.popups { - for p in prev.popups.iter().chain(f.popups.iter()) { - d = union(d, R::from(p.area)); - } - } - Some(d) -} - -impl Raster { - pub fn add_surface(&mut self, s: Surface) -> u32 { - self.next_id = self.next_id.wrapping_add(1).max(1); - self.surfaces.insert(self.next_id, s); - self.next_id - } - - pub fn release(&mut self, id: u32) { - self.surfaces.remove(&id); - } - - /// A `w` x `h` scaled copy of surface `id` as an image (see `Images::put_pixels` for `reuse`). - /// 0 for an unknown surface or a silly size. - pub fn thumbnail(&mut self, id: u32, w: i32, h: i32, reuse: u32) -> u32 { - if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE { - return 0; - } - let Some(s) = self.surfaces.get(&id) else { return 0 }; - let px = scale_rgba(&s.rgba, s.w, s.h, w, h); - let handle = self.images.put_pixels(reuse, w, h, px); - self.images.previews.insert(handle); - handle - } - - /// `w` x `h` RGBA pixels as an image (see `Images::put_pixels` for `reuse`); 0 for a silly - /// size or too few pixels. - pub fn image_pixels(&mut self, w: i32, h: i32, mut rgba: Vec, reuse: u32) -> u32 { - if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE || rgba.len() < (w * h * 4) as usize { - return 0; - } - rgba.truncate((w * h * 4) as usize); - self.images.put_pixels(reuse, w, h, rgba) - } - - pub fn surface_count(&self) -> usize { - self.surfaces.len() - } - - /// `submit_frame` for a borrowed frame (tests). - #[cfg(test)] - pub fn submit(&mut self, f: &wt::Frame, fonts: &mut Fonts) { - self.submit_frame(f.clone(), fonts) - } - - /// Draw a frame into the framebuffer: wallpaper (cached), background, windows bottom to top, - /// panel, then client popups. The same layering as the software renderer's `render_scene`. - /// Only the part that differs from the last frame is redrawn (see `damage`): a client drawing - /// in its window costs that window's pixels, not the whole screen. - pub fn submit_frame(&mut self, f: wt::Frame, fonts: &mut Fonts) { - let (w, h) = (f.width.max(1), f.height.max(1)); - let resized = w != self.w || h != self.h || self.fb.len() != (w * h * 4) as usize; - if resized { - self.w = w; - self.h = h; - self.fb = vec![0u8; (w * h * 4) as usize]; - } - // The frame starts from the cached backdrop (which covers every pixel), so the buffer is - // only cleared when there is none: no point zeroing 8 MB that is overwritten at once. - let backdrop_ready = match (&f.wallpaper, &self.wallpaper) { - (None, Some((_, cw, ch, _))) => *cw == w && *ch == h, - (Some(ops), Some((o, cw, ch, _))) => *cw == w && *ch == h && o == ops, - _ => false, - }; - let clip: Clip = match (&self.prev, resized || !backdrop_ready) { - (Some(prev), false) => match damage(prev, &f) { - Some(d) => match intersect(Some(d), Some(R { x: 0, y: 0, w, h })) { - Some(k) if k.w > 0 && k.h > 0 => Some(k), - _ => { - // Nothing on screen changed (a window off screen, say). - self.last_drawn = 0; - self.keep_prev(f); - return; - } - }, - None => None, - }, - _ => None, - }; - if !resized && !backdrop_ready { - self.fb.fill(0); - } - self.last_drawn = match clip { - Some(k) => (k.w * k.h) as usize, - None => (w * h) as usize, - }; - let surfaces = &self.surfaces; - let imgs = &self.images; - let mut c = Canvas { w, h, data: &mut self.fb }; - - // 1. Wallpaper: drawn once, copied back while unchanged (only the damaged rows and columns). - let copy_backdrop = |c: &mut Canvas, px: &[u8]| match clip { - None => c.data.copy_from_slice(px), - Some(k) => { - for y in k.y..k.y + k.h { - let a = ((y * w + k.x) * 4) as usize; - let b = a + (k.w * 4) as usize; - c.data[a..b].copy_from_slice(&px[a..b]); - } - } - }; - match &f.wallpaper { - Some(ops) => { - let cached = matches!(&self.wallpaper, Some((o, cw, ch, _)) if *cw == w && *ch == h && o == ops); - if cached { - copy_backdrop(&mut c, &self.wallpaper.as_ref().unwrap().3); - } else { - draw_ops(&mut c, fonts, imgs, ops, 0, 0, None); - self.wallpaper = Some((ops.clone(), w, h, c.data.to_vec())); - } - } - None => { - if let Some((_, cw, ch, px)) = &self.wallpaper { - if *cw == w && *ch == h { - copy_backdrop(&mut c, px); - } - } - } - } - draw_ops(&mut c, fonts, imgs, &f.background, 0, 0, clip); - - // 2. Windows, bottom to top. - for win in &f.windows { - let g = R::from(win.geometry); - if let Some(k) = clip { - if intersect(Some(window_footprint(win)), Some(k)).map_or(true, |r| r.w <= 0 || r.h <= 0) { - continue; - } - } - if !win.fullscreen { - // The frame, shadow included, is all in the decoration ops. - let (outer_x, outer_y) = (g.x - win.inset_left, g.y - win.inset_top); - draw_ops(&mut c, fonts, imgs, &win.deco, outer_x, outer_y, clip); - } - match surfaces.get(&win.surface) { - Some(s) => blit_surface(&mut c, s, g, clip), - None => fill_rounded_rect(&mut c, g, wt::Color { r: 0x1e, g: 0x29, b: 0x3b, a: 0xff }, 0, clip), - } - } - - // 3. Panel (and its popups, menus and notices), then 4. client popups above everything. - draw_ops(&mut c, fonts, imgs, &f.panel, 0, 0, clip); - for p in &f.popups { - if let Some(s) = surfaces.get(&p.surface) { - blit_surface(&mut c, s, R::from(p.area), clip); - } - } - self.keep_prev(f); - } - - /// Remember `f` as the last frame. Its wallpaper ops are kept from the frame that sent them, so - /// a later frame that resends the same wallpaper still compares equal. - fn keep_prev(&mut self, mut f: wt::Frame) { - if f.wallpaper.is_none() { - f.wallpaper = self.prev.as_mut().and_then(|p| p.wallpaper.take()); - } - self.prev = Some(f); - } - - /// The framebuffer as little-endian ARGB8888 (B, G, R, A=255), `stride = w * 4`. - pub fn to_argb8888(&self) -> Vec { - let mut out = vec![0u8; self.fb.len()]; - for (s, d) in self.fb.chunks_exact(4).zip(out.chunks_exact_mut(4)) { - d[0] = s[2]; - d[1] = s[1]; - d[2] = s[0]; - d[3] = 0xff; - } - out - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn color(r: u8, g: u8, b: u8, a: u8) -> wt::Color { - wt::Color { r, g, b, a } - } - fn rect(x: i32, y: i32, w: i32, h: i32) -> wt::Rect { - wt::Rect { x, y, w, h } - } - fn fill(x: i32, y: i32, w: i32, h: i32, c: wt::Color, radius: i32) -> wt::Op { - wt::Op::FillRect(wt::Fill { area: rect(x, y, w, h), color: c, radius }) - } - fn frame(w: i32, h: i32) -> wt::Frame { - wt::Frame { width: w, height: h, wallpaper: None, background: vec![], windows: vec![], panel: vec![], popups: vec![] } - } - fn px(r: &Raster, x: i32, y: i32) -> [u8; 4] { - let o = ((y * r.w + x) * 4) as usize; - [r.fb[o], r.fb[o + 1], r.fb[o + 2], r.fb[o + 3]] - } - - #[test] - fn fills_blend_with_the_same_arithmetic_as_the_software_renderer() { - let mut r = Raster::default(); - let mut f = frame(20, 10); - f.background = vec![fill(0, 0, 20, 10, color(10, 20, 30, 255), 0), fill(2, 2, 6, 6, color(200, 100, 0, 128), 0)]; - r.submit(&f, &mut Fonts::default()); - assert_eq!(px(&r, 0, 0), [10, 20, 30, 255]); - // (200*128 + 10*127 + 127) / 255 = 105, (100*128 + 20*127 + 127) / 255 = 60, (0 + 30*127 + 127) / 255 = 15 - assert_eq!(px(&r, 3, 3), [105, 60, 15, 255]); - } - - #[test] - fn rounded_corners_leave_the_corner_pixel_untouched() { - let mut r = Raster::default(); - let mut f = frame(40, 40); - f.background = vec![fill(4, 4, 30, 30, color(255, 255, 255, 255), 10)]; - r.submit(&f, &mut Fonts::default()); - assert_eq!(px(&r, 4, 4), [0, 0, 0, 0]); // outside the rounded corner - assert_eq!(px(&r, 19, 19), [255, 255, 255, 255]); - assert_eq!(px(&r, 19, 4), [255, 255, 255, 255]); // straight edge - } - - #[test] - fn stroke_draws_only_the_border() { - let mut r = Raster::default(); - let mut f = frame(30, 30); - f.background = vec![wt::Op::StrokeRect(wt::Stroke { area: rect(2, 2, 20, 20), color: color(9, 9, 9, 255), width: 2, radius: 0 })]; - r.submit(&f, &mut Fonts::default()); - assert_eq!(px(&r, 2, 10), [9, 9, 9, 255]); - assert_eq!(px(&r, 3, 10), [9, 9, 9, 255]); - assert_eq!(px(&r, 4, 10), [0, 0, 0, 0]); // interior - assert_eq!(px(&r, 21, 10), [9, 9, 9, 255]); - assert_eq!(px(&r, 10, 21), [9, 9, 9, 255]); - } - - #[test] - fn clip_ops_limit_drawing() { - let mut r = Raster::default(); - let mut f = frame(20, 20); - f.background = vec![ - wt::Op::PushClip(rect(5, 5, 5, 5)), - fill(0, 0, 20, 20, color(1, 2, 3, 255), 0), - wt::Op::PopClip, - fill(0, 0, 2, 2, color(7, 7, 7, 255), 0), - ]; - r.submit(&f, &mut Fonts::default()); - assert_eq!(px(&r, 6, 6), [1, 2, 3, 255]); - assert_eq!(px(&r, 2, 2), [0, 0, 0, 0]); - assert_eq!(px(&r, 10, 10), [0, 0, 0, 0]); - assert_eq!(px(&r, 1, 1), [7, 7, 7, 255]); - } - - #[test] - fn wallpaper_is_cached_and_reused_when_the_frame_says_unchanged() { - let mut r = Raster::default(); - let mut fonts = Fonts::default(); - let mut f = frame(16, 16); - f.wallpaper = Some(vec![fill(0, 0, 16, 16, color(50, 60, 70, 255), 0)]); - r.submit(&f, &mut fonts); - assert_eq!(px(&r, 8, 8), [50, 60, 70, 255]); - let mut g = frame(16, 16); - g.wallpaper = None; // unchanged: the cached pixels come back - g.background = vec![fill(0, 0, 2, 2, color(1, 1, 1, 255), 0)]; - r.submit(&g, &mut fonts); - assert_eq!(px(&r, 8, 8), [50, 60, 70, 255]); - assert_eq!(px(&r, 0, 0), [1, 1, 1, 255]); - // A different wallpaper is drawn afresh. - f.wallpaper = Some(vec![fill(0, 0, 16, 16, color(9, 8, 7, 255), 0)]); - r.submit(&f, &mut fonts); - assert_eq!(px(&r, 8, 8), [9, 8, 7, 255]); - } - - #[test] - fn windows_blit_their_surface_converted_from_bgra_and_the_host_draws_no_shadow() { - let mut r = Raster::default(); - // A 4x2 XRGB buffer, every pixel B=10 G=20 R=30. - let bgra: Vec = (0..8).flat_map(|_| [10u8, 20, 30, 0]).collect(); - let id = r.add_surface(Surface::from_bgra(&bgra, 16, 4, 2, true).unwrap()); - let mut f = frame(40, 30); - f.background = vec![fill(0, 0, 40, 30, color(200, 200, 200, 255), 0)]; - f.windows = vec![wt::Window { - geometry: rect(10, 10, 4, 2), - inset_top: 0, - inset_right: 0, - inset_bottom: 0, - inset_left: 0, - deco: vec![], - fullscreen: false, - surface: id, - }]; - r.submit(&f, &mut Fonts::default()); - assert_eq!(px(&r, 10, 10), [30, 20, 10, 255]); // R, G, B order after conversion - assert_eq!(px(&r, 13, 11), [30, 20, 10, 255]); - // The shadow is the decoration's to draw (compositor/scene): none without its ops. - assert_eq!(px(&r, 15, 17)[0], 200, "no shadow of the host's own"); - assert_eq!(px(&r, 9, 10)[0], 200); - r.release(id); - assert_eq!(r.surface_count(), 0); - } - - /// A window with a title-bar decoration over a patterned backdrop and a panel. - fn scene_window(r: &mut Raster, x: i32, y: i32, shade: u8, focused: bool) -> wt::Window { - let bgra: Vec = (0..(30 * 20)).flat_map(|i| [shade, (i % 251) as u8, 40, if i % 7 == 0 { 90 } else { 255 }]).collect(); - let id = r.add_surface(Surface::from_bgra(&bgra, 30 * 4, 30, 20, false).unwrap()); - wt::Window { - geometry: rect(x, y, 30, 20), - inset_top: 8, - inset_right: 2, - inset_bottom: 2, - inset_left: 2, - deco: vec![fill(0, 0, 34, 30, if focused { color(60, 90, 200, 230) } else { color(90, 90, 90, 200) }, 3)], - fullscreen: false, - surface: id, - } - } - - fn scene_frame(windows: Vec) -> wt::Frame { - let mut f = frame(120, 90); - f.wallpaper = Some((0..12).map(|i| fill(i * 10, 0, 10, 90, color((i * 20) as u8, 100, 200 - (i * 10) as u8, 255), 0)).collect()); - f.windows = windows; - f.panel = vec![fill(0, 80, 120, 10, color(20, 20, 30, 220), 0), fill(4, 82, 6, 6, color(250, 250, 250, 255), 3)]; - f - } - - #[test] - fn redrawing_only_the_damage_gives_the_same_pixels_as_a_full_redraw() { - let mut fonts = Fonts::default(); - // Frame 1 (full), then steps that only change windows: a client redraw, a move, a focus change. - let mut inc = Raster::default(); - let w1 = scene_window(&mut inc, 10, 15, 10, false); - let w2 = scene_window(&mut inc, 30, 25, 200, true); - inc.submit(&scene_frame(vec![w1.clone(), w2.clone()]), &mut fonts); - assert_eq!(inc.last_drawn, 120 * 90); - let mut new_w1 = scene_window(&mut inc, 10, 15, 99, false); // the client drew a new buffer - let steps = vec![ - vec![new_w1.clone(), w2.clone()], - { - new_w1.geometry = rect(60, 40, 30, 20); // moved, now overlapping the panel - vec![new_w1.clone(), w2.clone()] - }, - { - let mut a = new_w1.clone(); - a.deco = vec![fill(0, 0, 34, 30, color(60, 90, 200, 230), 3)]; - let mut b = w2.clone(); - b.deco = vec![fill(0, 0, 34, 30, color(90, 90, 90, 200), 3)]; - vec![b, a] // focus moved and the stacking order swapped - }, - ]; - for (i, wins) in steps.into_iter().enumerate() { - let f = scene_frame(wins); - let mut f_inc = f.clone(); - f_inc.wallpaper = None; // the compositor sends an unchanged backdrop as None - inc.submit(&f_inc, &mut fonts); - assert!(inc.last_drawn < 120 * 90, "step {i}: only part of the screen is redrawn"); - // The same frame drawn from scratch, with the same surfaces. - let mut full = Raster::default(); - for (id, s) in &inc.surfaces { - full.surfaces.insert(*id, Surface { w: s.w, h: s.h, rgba: s.rgba.clone(), opaque: s.opaque }); - } - full.submit(&f, &mut fonts); - assert!(full.fb == inc.fb, "step {i}: partial redraw differs from a full one"); - } - // An unchanged frame draws nothing. - let f = inc.prev.clone().unwrap(); - inc.submit(&f, &mut fonts); - assert_eq!(inc.last_drawn, 0); - } - - #[test] - fn translucent_surfaces_blend_over_what_is_behind() { - let mut r = Raster::default(); - // One ARGB pixel: B=0 G=0 R=255 A=128, over a grey background. - let id = r.add_surface(Surface::from_bgra(&[0, 0, 255, 128], 4, 1, 1, false).unwrap()); - let mut f = frame(8, 8); - f.background = vec![fill(0, 0, 8, 8, color(100, 100, 100, 255), 0)]; - f.windows = vec![wt::Window { geometry: rect(2, 2, 1, 1), inset_top: 0, inset_right: 0, inset_bottom: 0, inset_left: 0, deco: vec![], fullscreen: true, surface: id }]; - r.submit(&f, &mut Fonts::default()); - // (255*128 + 100*127 + 127) / 255 = 178, (0 + 100*127 + 127) / 255 = 50 - assert_eq!(px(&r, 2, 2), [178, 50, 50, 255]); - } - - #[test] - fn argb_export_swaps_red_and_blue() { - let mut r = Raster::default(); - let mut f = frame(2, 1); - f.background = vec![fill(0, 0, 2, 1, color(1, 2, 3, 255), 0)]; - r.submit(&f, &mut Fonts::default()); - assert_eq!(&r.to_argb8888()[..4], &[3, 2, 1, 255]); - } - - #[test] - fn thumbnails_scale_a_surface_and_reuse_their_handle() { - let mut r = Raster::default(); - // A 4x2 surface: left half red, right half blue (BGRA in, RGBA out). - let mut src = Vec::new(); - for _ in 0..2 { - for x in 0..4 { - src.extend_from_slice(if x < 2 { &[0, 0, 255, 255] } else { &[255, 0, 0, 255] }); - } - } - let s = r.add_surface(Surface::from_bgra(&src, 16, 4, 2, true).unwrap()); - assert_eq!(r.thumbnail(999, 2, 1, 0), 0); - assert_eq!(r.thumbnail(s, 0, 1, 0), 0); - let t = r.thumbnail(s, 2, 1, 0); - assert_ne!(t, 0); - r.submit(&wt::Frame { panel: vec![wt::Op::DrawImage(wt::Picture { area: rect(0, 0, 2, 1), image: t })], ..frame(4, 4) }, &mut Fonts::default()); - assert_eq!(px(&r, 0, 0), [255, 0, 0, 255]); - assert_eq!(px(&r, 1, 0), [0, 0, 255, 255]); - // Refreshing overwrites the same handle, and the old pixels are not served from the cache. - let blue = [255u8, 0, 0, 255].repeat(8); - let s2 = r.add_surface(Surface::from_bgra(&blue, 16, 4, 2, true).unwrap()); - assert_eq!(r.thumbnail(s2, 2, 1, t), t); - r.submit(&wt::Frame { panel: vec![wt::Op::DrawImage(wt::Picture { area: rect(0, 0, 2, 1), image: t })], ..frame(4, 4) }, &mut Fonts::default()); - assert_eq!(px(&r, 0, 0), [0, 0, 255, 255]); - } - - /// The old way: every pixel of the bounding box. - fn circle_reference(c: &mut Canvas, d: &wt::Disc, clip: Clip) { - let (cr, cg, cb, ca) = (d.color.r as i32, d.color.g as i32, d.color.b as i32, d.color.a as f64); - let rad = d.radius as f64; - for dy in (-d.radius - 1)..=(d.radius + 1) { - for dx in (-d.radius - 1)..=(d.radius + 1) { - let dist = ((dx * dx + dy * dy) as f64).sqrt(); - let outer = rad + 0.5 - dist; - let mut cov = if outer > 1.0 { 1.0 } else { outer }; - if !d.filled { - let inner = dist - (rad - 1.0 - 0.5); - let ic = if inner > 1.0 { 1.0 } else { inner }; - if ic < cov { - cov = ic; - } - } - if cov > 0.02 { - blend_pixel(c, d.cx + dx, d.cy + dy, cr, cg, cb, (ca * cov).round() as i32, clip); - } - } - } - } - - #[test] - fn circles_drawn_by_rows_match_the_per_pixel_reference() { - let clips = [None, Some(R { x: 13, y: 40, w: 50, h: 31 })]; - for radius in [1, 2, 3, 5, 17, 40, 70] { - for filled in [true, false] { - for alpha in [255u8, 200, 6] { - for (ci, clip) in clips.iter().enumerate() { - let d = wt::Disc { cx: 45, cy: 52, radius, color: color(250, 120, 30, alpha), filled }; - let mut a: Vec = (0..100 * 90 * 4).map(|i| (i * 7 % 251) as u8).collect(); - let mut b = a.clone(); - draw_circle(&mut Canvas { w: 100, h: 90, data: &mut a }, &d, 0, 0, *clip); - circle_reference(&mut Canvas { w: 100, h: 90, data: &mut b }, &d, *clip); - assert!(a == b, "radius {radius} filled {filled} alpha {alpha} clip {ci}"); - } - } - } - } - } - - #[test] - fn a_preview_glides_sampled_and_keeps_no_scaled_copy() { - let mut r = Raster::default(); - let src = [199u8, 99, 9, 255].repeat(16); // BGRA - let s = r.add_surface(Surface::from_bgra(&src, 16, 4, 4, true).unwrap()); - let t = r.thumbnail(s, 2, 2, 0); - assert_ne!(t, 0); - r.submit(&wt::Frame { panel: vec![wt::Op::DrawImage(wt::Picture { area: rect(0, 0, 200, 150), image: t })], ..frame(300, 300) }, &mut Fonts::default()); - assert_eq!(px(&r, 0, 0), [9, 99, 199, 255]); - assert_eq!(px(&r, 199, 149), [9, 99, 199, 255]); - assert_eq!(px(&r, 200, 150), [0, 0, 0, 0]); - assert!(r.images.sized.borrow().is_empty()); - } - - #[test] - fn a_large_image_is_cached_at_one_large_size_only() { - let mut imgs = Images::default(); - let h = imgs.put_pixels(0, 2, 2, [200u8; 16].to_vec()); - // Small sizes (icons) stay cached side by side. - assert!(imgs.sized(h, 16, 16).is_some()); - assert!(imgs.sized(h, 48, 48).is_some()); - // A preview gliding through sizes keeps one large copy (up to the draw limit). - for w in [300, 400, 500, 2000] { - assert!(imgs.sized(h, w, w / 2).is_some()); - } - let keys: Vec<_> = imgs.sized.borrow().keys().cloned().collect(); - assert_eq!(keys.len(), 3); - assert!(keys.contains(&(h, 2000, 1000))); - assert!(imgs.sized(h, 5000, 10).is_none()); - } - - #[test] - fn images_load_once_by_path_and_draw_scaled_png_and_svg() { - let dir = std::env::temp_dir().join(format!("chandra-img-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let png_path = dir.join("half.png"); - std::fs::write(&png_path, b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x04\x00\x00\x00\x04\x08\x06\x00\x00\x00\xa9\xf1\x9e\x7e\x00\x00\x00\x13\x49\x44\x41\x54\x78\x9c\x63\xf8\xcf\xc0\xf0\x1f\x84\x19\x60\x80\x74\x01\x00\x5e\x02\x0f\xf1\x64\xf6\x7e\x7c\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82").unwrap(); - let svg_path = dir.join("blue.svg"); - std::fs::write(&svg_path, br##""##).unwrap(); - let mut r = Raster::default(); - let p = r.images.load(png_path.to_str().unwrap()); - assert!(p != 0); - assert_eq!(r.images.load(png_path.to_str().unwrap()), p); - let s = r.images.load(svg_path.to_str().unwrap()); - assert!(s != 0 && s != p); - assert_eq!(r.images.load("/nonexistent/icon.png"), 0); - let pic = |x: i32, w: i32, image: u32| wt::Op::DrawImage(wt::Picture { area: rect(x, 0, w, w), image }); - let mut f = frame(40, 20); - f.panel = vec![pic(0, 8, p), pic(10, 20, s), pic(30, 4, 999)]; - r.submit(&f, &mut Fonts::default()); - // The PNG doubled: left half red, right half untouched. - assert_eq!(px(&r, 1, 1), [255, 0, 0, 255]); - assert_eq!(px(&r, 6, 1), [0, 0, 0, 0]); - // The SVG rendered at 20px fills its square. - assert_eq!(px(&r, 20, 10), [0, 0, 255, 255]); - // An unknown handle draws nothing. - assert_eq!(px(&r, 31, 1), [0, 0, 0, 0]); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/justfile b/justfile index 9dcf0c2..d7ebf73 100644 --- a/justfile +++ b/justfile @@ -49,11 +49,6 @@ run-x11: compositor-wasm wasmhost modules rm -f {{socket}} build/wasmhost build/compositor.wasm --socket {{socket}} --theme {{theme}} --x11 -# The same on the Rust host (host-wasm), kept as a fallback while the MoonBit host settles in. -run-rust: compositor-wasm host-wasm modules - rm -f {{socket}} - host-wasm/target/release/chandra-host build/compositor.wasm --socket {{socket}} --theme {{theme}} --window - # Run the native compositor (tcc debug build, with the wasm panel modules) in a window on your current Wayland session. run-native: build modules rm -f {{socket}} @@ -87,19 +82,13 @@ run-drm: compositor-wasm wasmhost modules -dbus-update-activation-environment --systemd WAYLAND_DISPLAY=$(basename {{socket}}) XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=chandra 2>/dev/null build/wasmhost build/compositor.wasm --drm --socket {{socket}} --theme {{theme}} -# The same on the Rust host (host-wasm). -run-drm-rust: compositor-wasm host-wasm modules - rm -f {{socket}} - -dbus-update-activation-environment --systemd WAYLAND_DISPLAY=$(basename {{socket}}) XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=chandra 2>/dev/null - host-wasm/target/release/chandra-host build/compositor.wasm --drm --socket {{socket}} --theme {{theme}} - # The same on the native compositor (system-cc release build), for comparison. run-drm-native: build-release modules rm -f {{socket}} -dbus-update-activation-environment --systemd WAYLAND_DISPLAY=$(basename {{socket}}) XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=chandra 2>/dev/null {{release_exe}} --drm --socket {{socket}} --theme {{theme}} -# Install everything (login session, panel modules, KDE colors, portal, face unlock); builds as you, then asks for root once. Flags: --link, --rust, --native, --pam, --no-face (docs/install.md). +# Install everything (login session, panel modules, KDE colors, portal, face unlock); builds as you, then asks for root once. Flags: --link, --native, --pam, --no-face (docs/install.md). install *flags: #!/usr/bin/env bash set -euo pipefail @@ -107,13 +96,11 @@ install *flags: face=1 for f in {{flags}}; do case "$f" in - --rust|--native) - [ -z "${host:-}" ] || [ "$host" = "$f" ] || { echo "just install: --rust and --native exclude each other" >&2; exit 2; } - host=$f - if [ "$f" = --rust ]; then builds="compositor-wasm host-wasm modules"; else builds="build-release modules"; fi ;; + --native) builds="build-release modules" ;; + --rust) echo "just install: --rust is gone: the Rust host was removed (2026-11-26); the MoonBit host is the only one" >&2; exit 2 ;; --no-face) face=0 ;; --link|--pam|--no-models) ;; - *) echo "just install: unknown flag $f (--link, --rust, --native, --pam, --no-face, --no-models)" >&2; exit 2 ;; + *) echo "just install: unknown flag $f (--link, --native, --pam, --no-face, --no-models)" >&2; exit 2 ;; esac done {{just_executable()}} --justfile "{{justfile()}}" $builds @@ -197,7 +184,4 @@ compositor-wasm: wasmhost: scripts/build-wasmhost.sh -# Build the Rust host (host-wasm/target/release/chandra-host): the fallback, compiles wasmtime (about 2 minutes cold). -host-wasm: - cd host-wasm && cargo build --release diff --git a/scripts/build-compositor-wasm.sh b/scripts/build-compositor-wasm.sh index 550d906..8745f9d 100755 --- a/scripts/build-compositor-wasm.sh +++ b/scripts/build-compositor-wasm.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Build the compositor itself as a wasm component: build/compositor.wasm. # It imports the chandra:host interfaces (wit/host) and exports `run`; the host (wasmhost/, -# build/wasmhost; or the Rust host-wasm/) provides the imports. Needs moon and wasm-tools. +# build/wasmhost) provides the imports. Needs moon and wasm-tools. # scripts/build-compositor-wasm.sh set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT" diff --git a/scripts/remote-build.sh b/scripts/remote-build.sh index 3e65173..3be4902 100755 --- a/scripts/remote-build.sh +++ b/scripts/remote-build.sh @@ -1,14 +1,14 @@ #!/usr/bin/env bash # Build on a sprites.dev sprite instead of locally, then pull the artifacts back: -# build/compositor.wasm, build/components/ and host-wasm/target/release/chandra-host. -# The sprite checks the tree out at the same absolute path as here, because host-wasm/build.rs -# bakes /.pixi/envs/default/lib into the host's rpath. +# build/compositor.wasm, build/components/ and build/wasmhost. +# The sprite checks the tree out at the same absolute path as here, so paths in the build match +# (build/wasmhost's rpath points at the checkout's .pixi/envs/default/lib, relative to the binary). # One-off sprite setup (apt dev libs, pixi, moon, wasm-tools, moon update): scripts/sprite-setup.sh. -# scripts/remote-build.sh [just-target ...] (default: host-wasm compositor-wasm modules) +# scripts/remote-build.sh [just-target ...] (default: wasmhost compositor-wasm modules) set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT" SPRITE="${CHANDRA_SPRITE:-chandra-build}" -targets=("$@"); [ ${#targets[@]} -gt 0 ] || targets=(host-wasm compositor-wasm modules) +targets=("$@"); [ ${#targets[@]} -gt 0 ] || targets=(wasmhost compositor-wasm modules) sp() { sprite exec -s "$SPRITE" "$@"; } echo "== sync source to $SPRITE" @@ -23,11 +23,11 @@ sp --no-stdin --dir "$ROOT" -- bash -c \ echo "== pull artifacts" # `sprite file pull` rather than a tar stream over exec: a streamed binary can break on reconnect. # -r on a directory fails, so pull build/components/ file by file. -mkdir -p build/components host-wasm/target/release +mkdir -p build/components pull() { sprite file pull -s "$SPRITE" -p "$@"; } pull "$ROOT/build/compositor.wasm" build/ -pull "$ROOT/host-wasm/target/release/chandra-host" host-wasm/target/release/ +pull "$ROOT/build/wasmhost" build/ mods=(); while IFS= read -r f; do mods+=("$ROOT/build/components/$f"); done \ < <(sp --no-stdin --dir "$ROOT" -- ls build/components | grep -E '\.(wasm|json)$') pull "${mods[@]}" build/components/ -ls -la build/compositor.wasm host-wasm/target/release/chandra-host +ls -la build/compositor.wasm build/wasmhost diff --git a/scripts/sprite-setup.sh b/scripts/sprite-setup.sh index 5f9694b..03dd8e8 100755 --- a/scripts/sprite-setup.sh +++ b/scripts/sprite-setup.sh @@ -15,4 +15,4 @@ install /tmp/wasm-tools-1.258.0-x86_64-linux/wasm-tools ~/.local/bin/ # moon curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash >/dev/null 2>&1 || true export PATH=$HOME/.pixi/bin:$HOME/.moon/bin:$HOME/.local/bin:$PATH -pixi -V; wasm-tools -V; moon version | head -1; cargo -V; ls /usr/include/libseat.h +pixi -V; wasm-tools -V; moon version | head -1; ls /usr/include/libseat.h diff --git a/session/install.py b/session/install.py index 7a7438c..71da7b0 100755 --- a/session/install.py +++ b/session/install.py @@ -5,7 +5,6 @@ run0 and falls back to sudo, doas or pkexec). Running it is idempotent: it repla just install # the compositor as a wasm component on the MoonBit host just install --link # dev: symlink into this checkout (see below) - just install --rust # the wasm compositor on the Rust host (host-wasm) just install --native # the native compositor instead just install --pam # also turn face unlock on for polkit-1 and sudo just install --no-face # leave face unlock out @@ -45,11 +44,12 @@ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) native = "--native" in sys.argv linked = "--link" in sys.argv exe = os.path.join(root, "_build/native/release/build/compositor/bin/bin.exe") -rust_host = "--rust" in sys.argv or "--rust-host" in sys.argv -# The host that runs the compositor component: the MoonBit one (just wasmhost), or the Rust -# one (just host-wasm) with --rust. Either is installed as chandra-host. -host_build = "just host-wasm" if rust_host else "just wasmhost" -host = os.path.join(root, "host-wasm/target/release/chandra-host" if rust_host else "build/wasmhost") +if "--rust" in sys.argv or "--rust-host" in sys.argv: + sys.exit("install.py: --rust is gone: the Rust host (host-wasm) was removed on 2026-11-26; " + "the MoonBit host (build/wasmhost) is the only one, so drop the flag") +# The host that runs the compositor component (just wasmhost), installed as chandra-host. +host_build = "just wasmhost" +host = os.path.join(root, "build/wasmhost") component = os.path.join(root, "build/compositor.wasm") share = "/usr/local/share/chandra" targets = [ diff --git a/wasmhost/README.md b/wasmhost/README.md index 99717c7..f3ab186 100644 --- a/wasmhost/README.md +++ b/wasmhost/README.md @@ -1,13 +1,12 @@ # wasmhost The host that runs the compositor component (`build/compositor.wasm`): `just run`, `just run-drm` -and `just install` use it. It replaces the Rust `host-wasm/`, which stays as a fallback -(`just run-rust`, `just run-drm-rust`, `just install --rust`). +and `just install` use it. It is the only host: it replaced the Rust `host-wasm/` (on the wasmtime +crate), which was removed on 2026-11-26. It links wasmtime as the prebuilt C API library (`libwasmtime.a` from the upstream `wasmtime-v$WASMTIME_VERSION-x86_64-linux-c-api` release, fetched by `scripts/setup-toolchain.sh` -into `.tools/wasmtime-c-api`) instead of compiling wasmtime, so a cold build takes about 4 s -instead of about 2 minutes. +into `.tools/wasmtime-c-api`) instead of compiling wasmtime, so a cold build takes about 4 s. ``` scripts/build-wasmhost.sh # or: just wasmhost -> build/wasmhost @@ -23,14 +22,12 @@ build/wasmhost build/compositor.wasm --socket PATH --gfx-out frame.png (`snapshot-*`, `*-recording-frame`, `write-frame-png` in `wit/host/raster.wit`). - `bin/`: the interfaces of `wit/host`. Most of it is the native compositor's own packages: `sys` is compositor/sys, glyphs come from compositor/font (stb_truetype). The rasteriser - (`raster.mbt`, pixel work in `raster_stub.c`) is a port of `host-wasm/src/raster.rs`; SVG icons - use nanosvg (`third_party/nanosvg`, patched for clip paths and masks) where the Rust host used - resvg. `plasmoids.mbt` runs panel modules through compositor/wasm (wasm.h, which libwasmtime - provides); `display.mbt` is the login session's DRM/KMS output and input (compositor/kms). + (`raster.mbt`, pixel work in `raster_stub.c`) is a port of compositor/renderer; SVG icons + use nanosvg (`third_party/nanosvg`, patched for clip paths and masks). `plasmoids.mbt` runs + panel modules through compositor/wasm (wasm.h, which libwasmtime provides); `display.mbt` is the login session's DRM/KMS output and input (compositor/kms). -Every interface of `wit/host` is served, so a host change goes in both hosts until host-wasm is -removed. `--gfx-out` frames match the Rust host's except for text anti-aliasing (stb_truetype -against ab_glyph). CPU matches it in use: about 1 s at start to compile the component, then idle. +Every interface of `wit/host` is served here. CPU in use: about 1 s at start to compile the +component, then idle. `WASMHOST_TRACE=1` logs every host call; `WASMHOST_PROFILE=1` prints the time spent in each host function every 5 s. diff --git a/wasmhost/bin/raster.mbt b/wasmhost/bin/raster.mbt index d909e97..b570139 100644 --- a/wasmhost/bin/raster.mbt +++ b/wasmhost/bin/raster.mbt @@ -1,7 +1,6 @@ ///| `chandra:host/raster` and `chandra:host/font`: the compositor sends draw operations and window /// surface ids; the pixels live here (raster_stub.c) and never cross the component boundary. -/// What to draw where (layers, the wallpaper cache, damage) is decided here, as in -/// host-wasm/src/raster.rs. +/// What to draw where (layers, the wallpaper cache, damage) is decided here. ///| extern "C" fn rs_resize(w : Int, h : Int) -> Int = "rs_resize" diff --git a/wasmhost/bin/raster_stub.c b/wasmhost/bin/raster_stub.c index ddc86f6..dade7ef 100644 --- a/wasmhost/bin/raster_stub.c +++ b/wasmhost/bin/raster_stub.c @@ -1,7 +1,6 @@ /* The host's rasteriser (chandra:host/raster), pixel work in C. * - * A port of host-wasm/src/raster.rs, itself a port of compositor/renderer, so a frame comes out - * pixel for pixel the same. raster.mbt decides what to draw (layers, damage, the wallpaper cache); + * A port of compositor/renderer, so a frame comes out pixel for pixel the same. raster.mbt decides what to draw (layers, damage, the wallpaper cache); * this file owns the framebuffer, the captured client surfaces, the images and the glyph cache, * and draws one primitive per call, inside the current clip. * diff --git a/wit/worlds.wit b/wit/worlds.wit index 937af00..e25eda3 100644 --- a/wit/worlds.wit +++ b/wit/worlds.wit @@ -13,13 +13,13 @@ world clock-widget { } /// The optional `module-config` export on its own. A module of any world may add it to get its own -/// settings in its right-click menu; hosts look it up separately (host-wasm binds it with this world). +/// settings in its right-click menu; hosts look it up separately. world configurable { export module-config; } /// The optional `desktop-module` export on its own (wit/desktop.wit): what makes a module a -/// desktop module. Hosts look it up by name like `module-config` (host-wasm binds this world). +/// desktop module. Hosts look it up by name like `module-config`. world desktop-export { export desktop-module; }