Replace Rust host-native with 100% pure-MoonBit Wayland compositor
CI / test (push) Successful in 36s

This commit is contained in:
Antigravity committed 2026-11-25 01:18:46 +00:00
1 parent 17a8a46cfd
commit ae4f3fa93c
31 files changed
+3647 -4962

No files matched your search

+72 -116
View File
@@ -13,60 +13,51 @@ Traditional Wayland compositors (KWin, Sway, Mutter) bundle device management, W
| Layer | Responsibility | Implementation | Trust Level |
| :--- | :--- | :--- | :--- |
| **Host (Mechanism)** | `calloop` event loop, Wayland protocol server (Smithay), DRM/KMS & `libinput` (or nested `winit`), SHM/DMA-BUF memory, render-list & surface rasterizer, `wasmtime` engine + epoch/fuel supervision, capability broker | **Rust** (`host-native/`) | Trusted Computing Base (TCB) |
| **Components (Policy)** | Window placement, tiling/stacking, focus policy, hit-testing/input routing, window decorations, panel layout, desktop background, widgets, declarative scene effects | **MoonBit** (`wasm` linear-memory components via `wit-bindgen moonbit`) | Untrusted, capability-attenuated, hot-swappable |
| **Host (Mechanism)** | Event loop, Wayland binary wire protocol server (`wl_display`, `wl_registry`, `wl_compositor`, `wl_shm`, `xdg_wm_base`, `zxdg_decoration_manager_v1`, `wl_seat`, `wl_output`), SHM memory mapping, retained scene graph & damage tracker, ARGB8888 software rasterizer & PNG encoder, minimal POSIX C FFI (`compositor/sys/sys_stub.c`) | **MoonBit** (`compositor/` compiled with `--target native`) | Trusted Computing Base (TCB) |
| **Policy & Components** | Window placement, BSP tiling/floating/monocle layouts, focus policy, hit-testing/input routing, Breeze SSD decorations, panel layout, desktop background, widgets | **MoonBit** (`lib/wm/`, `lib/*`, and Wasm components `components/*` via `wit-bindgen moonbit`) | Modular policy packages & sandboxed Wasm components |
```mermaid
flowchart TB
subgraph clients["Foreign Wayland / XWayland Clients"]
c1["App A (xdg_toplevel, wl_shm / dmabuf)"]
c2["App B (xdg_toplevel + xdg_popup)"]
subgraph clients["Foreign Wayland Clients"]
c1["App A (xdg_toplevel, wl_shm)"]
c2["App B (xdg_toplevel + zxdg_toplevel_decoration_v1)"]
end
subgraph host["Trusted Host (Rust: smithay + wasmtime + calloop)"]
wl["Wayland Server (wl_compositor, xdg_wm_base, dmabuf, seat)"]
loop["calloop Event Loop + Epoch Watchdog"]
broker["Capability Broker & Component Supervisor"]
scene["Retained Scene Graph & Damage Tracker"]
ras["Dual-Path Rasterizer (GLES/wgpu + tiny-skia fallback)"]
be["Backend (Nested winit / DRM+KMS+libinput)"]
subgraph host["Pure MoonBit Compositor Host (compositor/ --target native)"]
wl["Wayland Wire Server (compositor/wayland/)"]
sys["POSIX C FFI Shim (compositor/sys/sys_stub.c: sockets, SCM_RIGHTS, memfd, mmap)"]
comp["Compositor Host (compositor/host/)"]
scene["Retained Scene Graph & Damage Tracker (compositor/scene/)"]
ras["ARGB8888 Software Rasterizer & PNG/PPM Encoder (compositor/renderer/)"]
end
subgraph comps["Sandboxed MoonBit Components (.wasm)"]
wm["window-manager (wm-policy, input-router)"]
deco["decoration (titlebars, hit-regions)"]
shell["shell (desktop-surface, panel-layout)"]
widgets["plasmoids (launcher, clock, tray)"]
fx["effects (declarative transforms)"]
subgraph policy["MoonBit Policy & Wasm Components"]
wm["lib/wm (BSP tiling, Floating, Monocle, focus, hit-testing)"]
deco["Breeze SSD Decorations (compositor/scene + components/decoration-breeze)"]
shell["Shell & Plasmoids (lib/shell, components/*)"]
end
clients -- "Wayland UNIX socket + fds" --> wl
wl -- "buffer-surface handles & events" --> loop
loop -- "bounded sync WIT calls" --> broker
broker <--> wm & deco & shell & widgets & fx
wm & deco & shell & widgets & fx -- "list&lt;draw-op&gt; + revision + actions" --> scene
wl -- "committed wl_surface buffers" --> scene
scene -- "damaged rects" --> ras --> be
clients -- "Wayland UNIX socket + SCM_RIGHTS fds" --> sys --> wl
wl -- "CompositorEvent" --> comp
comp <--> wm & deco & shell
comp -- "SceneGraph + DrawOps + ShmBufferSnapshot" --> scene --> ras
```
### Design Invariants Carried Forward from M0
1. **Components never touch raw pixels or GPU handles:** UI components emit `list<draw-op>` in local coordinates. Foreign Wayland clients write to host-owned `buffer-surface` resources; components only reference those opaque handles.
2. **Deny-by-default capabilities:** A component only receives the WIT imports declared in its world *and* explicitly granted in the session/desktop config.
3. **Fault isolation:** If `window-manager` or `decoration` traps or exceeds its frame time budget, `wasmtime` unwinds the call, the host logs a `ComponentFault`, renders a fallback tile / server-side border, and keeps scanning out at 60/120 Hz.
1. **100% MoonBit Stack (Zero Rust):** Both the native Wayland compositor host (`compositor/`) and the WM/decoration/shell/widget logic (`lib/*`, `components/*`) are written in MoonBit. Only a minimal POSIX C FFI shim (`compositor/sys/sys_stub.c`) wraps OS primitives (`AF_UNIX`, `poll`, `recvmsg`/`sendmsg` with `SCM_RIGHTS`, `memfd_create`, `mmap`/`munmap`).
2. **Components never touch raw pixels or GPU handles:** UI & decoration logic emit `DrawOp` lists in local coordinates; the MoonBit software rasterizer (`compositor/renderer/`) translates, clips, blends, and blits client `wl_shm` buffers.
3. **WIT Component Model Compatibility:** `components/*` continue to compile to WASI P2 `.wasm` components for `wit/` conformance and the JS/Wasm host (`host/`), while `lib/wm` runs natively inside `compositor/host/`.
---
## 2. Core Compositor Responsibilities
### 2.1 Wayland Protocol Handling (Host: `smithay`)
The host embeds Smithay to expose standard Wayland globals on `$XDG_RUNTIME_DIR/wayland-N`:
- **Core:** `wl_compositor` (v5+), `wl_subcompositor`, `wl_shm`, `wl_output`, `wl_seat` (pointer, keyboard, touch), `wl_data_device_manager` (clipboard & drag-and-drop).
### 2.1 Wayland Protocol Handling (`compositor/wayland/`)
The pure-MoonBit Wayland server implements the binary Wayland wire protocol directly over Unix domain sockets:
- **Core:** `wl_display`, `wl_registry`, `wl_callback`, `wl_compositor` (v5), `wl_surface`, `wl_region`, `wl_shm` (v1, `ARGB8888` / `XRGB8888` via `SCM_RIGHTS`), `wl_shm_pool`, `wl_buffer`, `wl_output` (v4), `wl_seat` (v7).
- **Desktop Shells:**
- `xdg_wm_base` (`xdg_surface`, `xdg_toplevel`, `xdg_popup`) for application windows.
- `zxdg_decoration_manager_v1` (server-side decoration negotiation, defaulting to SSD via the `decoration` component).
- `zwlr_layer_shell_v1` (optional for external bars/lockscreens, though native `moon-plasma` panels are MoonBit components).
- **Buffers & Sync:** `zwp_linux_dmabuf_v1` (v4 with scanout/renderer tranche feedback), `wp_viewporter`, `wp_presentation_time`.
- **XWayland (M6+):** Rootless `Xwayland` managed by the host, mapping X11 windows into the exact same `WindowRegistry` so the MoonBit WM treats them identically to native Wayland clients.
- `xdg_wm_base` (`xdg_surface`, `xdg_toplevel`, `xdg_popup`, `xdg_positioner`) for application windows.
- `zxdg_decoration_manager_v1` / `zxdg_toplevel_decoration_v1` (server-side decoration negotiation, enforcing `ServerSide` mode with Breeze-style SSD).
### 2.2 Window & Surface Management (Split Host/WM)
- **Host (`WindowRegistry`):** Owns the authoritative lifecycle of every `xdg_toplevel`, `xdg_popup`, and `Subsurface`, its committed `wl_buffer` (wrapped in a `buffer-surface` resource), its PID/app-id, and its pending `configure` serials.
@@ -199,121 +190,86 @@ The host passes `last-known-revision: u64` into `render(size, last-rev)`. Static
## 4. Module Breakdown & Key Data Structures
### 4.1 Native Host (`host-native/` in Rust)
### 4.1 Native MoonBit Compositor (`compositor/`)
```
host-native/
├── Cargo.toml
└── src/
├── main.rs # CLI, session.json bootstrap, backend selection
├── event_loop.rs # calloop integration (Wayland, input, vblank, timers)
├── wayland/
│ ├── mod.rs # Smithay State struct + delegate_*! macros
│ ├── xdg.rs # xdg_wm_base, toplevel/popup configure lifecycle
│ ├── dmabuf.rs # zwp_linux_dmabuf_v1 + EGL/wgpu import
│ └── seat.rs # wl_seat keyboard/pointer/clipboard forwarding
├── wasm/
│ ├── engine.rs # wasmtime::Engine (epoch interruption enabled)
│ ├── supervisor.rs # ComponentInstance, fault tracking, backoff restart
│ ├── broker.rs # Capability grants & WIT host trait impls
│ └── bindings.rs # wasmtime::component::bindgen! for moonplasma:*
├── scene/
│ ├── graph.rs # Layered SceneNode tree (BG -> Windows -> Panel -> Overlay)
│ ├── cache.rs # Revision-keyed compiled draw-op cache
│ └── damage.rs # Per-output dirty-region tracker
├── renderer/
│ ├── mod.rs # Renderer trait (render_scene, import_dmabuf, import_shm)
│ ├── gpu.rs # wgpu / Smithay GlowRenderer + vello/skia draw-op backend
│ └── software.rs # tiny-skia CPU fallback (CI / headless / dumb buffers)
└── backend/
├── nested.rs # winit window + EGL/software surface
└── drm.rs # udev + libseat + drm/gbm + libinput (M8)
compositor/
├── sys/ # Minimal POSIX C FFI shim (supported_targets = "-all+native")
│ ├── moon.pkg # "native-stub": [ "sys_stub.c" ]
│ ├── sys_stub.c # AF_UNIX, poll, recvmsg/sendmsg SCM_RIGHTS, memfd_create, mmap
│ └── sys.mbt # MoonBit FFI bindings
├── wayland/ # Pure MoonBit Wayland binary wire protocol & server
│ ├── wire.mbt # WireWriter / WireReader (u32, i32, str, array, msg framing)
│ └── server.mbt # WaylandServer, wl_shm, xdg_wm_base, zxdg_decoration_manager_v1
├── scene/ # Pure MoonBit retained scene graph & damage tracker
│ └── scene.mbt # ThemeTokens, SceneGraph, DamageTracker, Breeze SSD & shell ops
├── renderer/ # Pure MoonBit software rasterizer & encoders
│ ├── renderer.mbt # Pixmap, SrcOver blending, rounded rects, 5x7 font, shm blit, PNG/PPM
│ └── renderer_test.mbt # Unit tests (wasm + native)
├── host/ # Compositor host wiring WaylandServer + lib/wm + SceneGraph + Renderer
│ ├── compositor.mbt # MoonPlasmaCompositor
│ └── e2e_test.mbt # Native e2e Wayland client + SCM_RIGHTS + BSP/Floating + PNG test
└── bin/ # Standalone native compositor binary
└── main.mbt # CLI (--socket, --theme)
```
### 4.2 MoonBit Components & Pure Libraries
Following the existing `lib/*` + `components/*/gen/stub.mbt` split:
- `lib/wm/`: Pure MoonBit tiling/stacking/focus state machines (unit-tested with `moon test` using synthetic `WindowState`s, zero host dependencies).
- `lib/decoration/`: Pure MoonBit titlebar/border layout + hit-region math driven by `@theme.Tokens`.
- `components/wm-floating/` & `components/wm-tiling/`: Hot-swappable WM components implementing `moonplasma:wm/policy`.
- `lib/wm/`: Pure MoonBit tiling/stacking/focus state machines (unit-tested with `moon test` on both `wasm` and `native`).
- `components/wm-hybrid/`: Hybrid BSP tiling / Floating / Monocle WM component implementing `moonplasma:wm/policy`.
- `components/decoration-breeze/`: Default server-side decoration component.
---
## 5. Event Loop & Async Model
## 5. Event Loop & Concurrency Model
As documented in `docs/TOOLCHAIN.md`, `moonbitlang/async` targets native/JS runtimes and is **not** WASI P3 component-model async; moreover, `jco` and `wit-bindgen-moonbit` do not yet share a uniform async ABI.
Therefore, the compositor uses a **host-driven `calloop` event loop with epoch-bounded synchronous WIT calls**:
1. **Single-Threaded `calloop` Reactor:**
- **Wayland source:** Reads client requests, processes `wl_surface.commit`, updates `WindowRegistry` and surface damage regions.
- **Input source:** `winit` events (nested) or `libinput` fd (DRM).
- **VBlank / Frame timer:** Fires on output refresh (or on-demand when dirty).
- **Component tick source:** Periodic 1 Hz / animation-rate timer that polls components for state changes (e.g., clock second rollover) without busy-spinning.
2. **Watchdog Thread (Epoch Interruption):**
- A lightweight background thread increments `wasmtime::Engine::increment_epoch()` every 1 ms.
- Before every WIT call (`wm.on_pointer`, `plasmoid.render`, `shell.compute_layout`), the host sets `store.set_epoch_deadline(4)` (4 ms budget).
- If a buggy component loops infinitely, `wasmtime` traps with `Interrupt`, the supervisor records a `ComponentFault`, and the compositor continues rendering the frame.
As documented in `docs/TOOLCHAIN.md`, `moonbitlang/async` targets native/JS runtimes and is **not** WASI P3 component-model async. In the pure-MoonBit native compositor (`compositor/host/`), `MoonPlasmaCompositor::step()` drives a non-blocking poll loop over the listening Unix socket and connected Wayland client fds, dispatching `CompositorEvent`s into `@wm.WmState` and updating `SceneGraph` + `DamageTracker` synchronously with zero thread contention.
---
## 6. Scene Graph, Damage Tracking & Rendering
### 6.1 Layered Scene Graph
Each output renders a 6-layer tree evaluated bottom-to-top:
1. **`Background`**: `shell.desktop-surface.render-background(output_size)` (cached by revision).
2. **`Bottom`**: `zwlr_layer_shell_v1` bottom-layer surfaces.
3. **`Windows`**: Iterated in `wm-policy.stacking-order()` order. Each window node composes:
- Drop shadow / focus ring (`draw-op`s)
- `decoration` component `list<draw-op>` (titlebar + borders)
- `buffer-surface` (main `xdg_toplevel` surface, clipped to geometry + corner radius)
- Child `wl_subsurface`s and `xdg_popup`s
4. **`Panel`**: `shell.panel-layout.render-panel` + each `plasmoid.render` placed at its `layout.placements` rect.
5. **`Overlay`**: Active widget popups (`plasmoid.popup`), notification toasts, launcher overlay, lock screen.
6. **`Cursor`**: Hardware DRM cursor plane (when available) or software cursor `draw-op`.
Each output renders a layered tree evaluated bottom-to-top:
1. **`Background`**: Desktop gradient (`build_shell_ops`).
2. **`Windows`**: Iterated in `wm.stacking_order()` order. Each window node composes:
- Drop shadow (`FillRect` with alpha)
- Breeze SSD decoration `DrawOp`s (titlebar + borders + window controls)
- Client `wl_shm` `ShmBufferSnapshot` (`ARGB8888` / `XRGB8888`)
3. **`Panel`**: Bottom panel + launcher + layout badge + window pills.
4. **`Overlay`**: Active widget popups and overlays.
### 6.2 Damage Tracking
- **Client Surface Damage:** `wl_surface.damage_buffer` regions are transformed into output-logical coordinates and unioned into `OutputDamage`.
- **Component Damage:** When a component returns `ops: some(...)` with a new `revision`, the host diffs the node's bounding box (old rect ∪ new rect) and adds it to `OutputDamage`. If `ops: none`, zero damage is emitted.
- **Scanout / Present:** The renderer clips drawing to `OutputDamage` and passes damaged rects to `eglSwapBuffersWithDamageKHR` (nested) or `DRM_MODE_PAGE_FLIP` with `FB_DAMAGE_CLIPS` (standalone).
- **Client Surface Damage:** `wl_surface.commit` marks the window geometry dirty in `DamageTracker`.
- **Layout / Focus Damage:** `WmAction`s mark full output damage and re-emit `xdg_toplevel.configure` + `xdg_surface.configure`.
### 6.3 Buffer Management & Rasterization
| Buffer / Op Kind | GPU Path (`GlowRenderer` / `wgpu`) | Software Fallback (`tiny-skia`) |
| :--- | :--- | :--- |
| `wl_shm` (`ARGB8888` / `XRGB8888`) | Uploaded to cached `GlesTexture` on commit (partial upload via damage rect) | Direct zero-copy slice read in CPU memory |
| `zwp_linux_dmabuf_v1` | Imported as `EGLImage` / `wgpu::Texture` (zero-copy); **direct scanout** on fullscreen opaque windows in M8 | Not advertised in `wl_drm`/`dmabuf` globals (clients fall back to `wl_shm`) |
| `list<draw-op>` (`fill-rect`, `stroke-rect`, `line`, `circle`, `text`, `push-clip`) | Compiled to GPU path/SDF/glyph-atlas draw calls (cached per revision) | Rasterized via `tiny-skia` + `cosmic-text` / `fontdue` |
- `wl_shm` (`ARGB8888` / `XRGB8888`): Mapped via `compositor/sys/sys_stub.c` (`mmap` + `memcpy` into MoonBit `Bytes` + `munmap`) and blitted by `compositor/renderer`.
- `DrawOp`s (`FillRect`, `StrokeRect`, `Line`, `Circle`, `Text`, `PushClip`, `PopClip`): Rasterized in pure MoonBit with Porter-Duff `SrcOver` alpha blending and encoded to PNG/PPM in pure MoonBit.
---
## 7. Phased Implementation Roadmap
Aligned directly with `docs/ARCHITECTURE.md` §11 (M3–M8):
| Phase | Milestone | Deliverable | Verification Gate |
| :--- | :--- | :--- | :--- |
| **Phase 1** | **M3** | **Native Reference Host** (`host-native/` with `wasmtime` + `winit` + `tiny-skia`, fuel/epoch limits, supervisor). | Runs existing M0 components (`shell`, `launcher`, `clock-*`) and passes the same integration tests as `host/test/desktop.test.mjs`. |
| **Phase 2** | **M4** | **WM World & Synthetic Windows** (`moonplasma:wm/policy`, `decoration`, input routing in `wm`/`shell`). | Pure MoonBit `lib/wm` tests (`moon test`); hot-swap floating ↔ tiling WM on synthetic windows in both JS and Rust hosts. |
| **Phase 3** | **M5** | **Nested Wayland Compositor** (`smithay` `wl_shm` + `xdg_wm_base`, `buffer-surface` WIT resource, `composite-op`). | Launch real Wayland clients (`foot`, `weston-terminal`, `firefox`) inside nested `moon-plasma` window; verify focus, resize, popups, and fault isolation. |
| **Phase 4** | **M6–M7** | **GPU Rasterizer, DMA-BUF & Desktop Bridges** (`zwp_linux_dmabuf_v1`, damage-clipped GPU rendering, XWayland, `text` shaping interface, clipboard/D-Bus notification/tray bridges). | Hardware-accelerated video/WebGL clients at 60+ fps with zero-copy DMA-BUF; partial-damage redraws verified. |
| **Phase 5** | **M8** | **Standalone DRM/KMS Session** (`udev`, `libseat`, `drm`/`gbm`, `libinput`, `outputs` WIT interface, direct scanout, `login` world). | Boot directly from TTY into `moon-plasma`; multi-monitor hotplug and fullscreen direct scanout. |
| **Phase 1** | **M3** | **Pure MoonBit Native Compositor** (`compositor/` with Wayland wire server, `lib/wm`, Breeze SSD, software rasterizer, PNG encoder). | `moon test --target native compositor/renderer compositor/host` passes e2e Wayland client + `SCM_RIGHTS` + BSP/Floating + PNG verification. |
| **Phase 2** | **M4** | **WM World & Components** (`moonplasma:wm/policy`, `decoration`, `components/wm-hybrid`, `components/decoration-breeze`). | `moon test` passes on `lib/wm`; `scripts/build-wm.sh` builds Wasm components cleanly. |
| **Phase 3** | **M5+** | **Interactive Input & Live Display Backend** (`wl_pointer` / `wl_keyboard` forwarding, DRM/KMS or nested X11/Wayland scanout). | Launch real Wayland clients (`foot`, `weston-terminal`) interactively. |
---
## 8. Window Manager (WM) Architecture
In `moon-plasma`, the **Window Manager is a pure policy component** (`world window-manager`) written in MoonBit, completely decoupled from Wayland wire serialization and GPU/DRM state. Because the host owns `WindowRegistry` and `SeatState`, the entire WM can be **hot-swapped at runtime** (e.g., `wm-floating` ↔ `wm-tiling`) without closing any running Wayland applications.
In `moon-plasma`, the **Window Manager is pure MoonBit policy** (`lib/wm/` and `components/wm-hybrid/`), completely decoupled from Wayland wire serialization and pixel rendering.
### 8.1 Integration with the Compositor & Wayland Protocols
The host translates Wayland protocol events into typed `moonplasma:wm` calls and applies the returned `list<wm-action>` back to Smithay:
`MoonPlasmaCompositor` translates Wayland protocol events into `lib/wm` calls and applies the returned `Array[WmAction]` back to `WaylandServer`:
| Wayland / Shell Event | Host (`smithay`) Action | WM (`wm-policy`) Role |
| Wayland / Shell Event | Compositor (`compositor/wayland`) Action | WM (`lib/wm`) Role |
| :--- | :--- | :--- |
| `xdg_toplevel` first commit (mapped) | Creates `WindowId`, reads `app_id`, `title`, `min/max_size`, `parent` | `on-window-open(win, work_area)` → assigns workspace/output, computes initial geometry, sets focus |
| `xdg_toplevel` `set_maximized` / `set_fullscreen` / `move` / `resize` | Forwards request to WM | `on-window-request(id, req)` → approves/denies, updates state, emits `set-geometry` + `configure` |
| `xdg_popup` creation & grab | Host tracks `xdg_popup` parent chain & Wayland popup grab | WM stays unaware of transient popups; host clips/places them relative to parent window |
| `zwlr_layer_shell_v1` / `shell.panel-layout` | Host computes reserved `exclusive_zone`s per output | Host passes `work_area: rect` (output minus panels/layer-shell margins) to WM |
| `xdg_toplevel` unmap / destroy | Removes from `WindowRegistry` | `on-window-close(id)` → reflows tiling tree, promotes next MRU window to focus |
| `xdg_toplevel` first commit (mapped) | Assigns `win_id`, reads `app_id`, `title`, `min_size` | `open_window(rec, work_area)` → assigns workspace, computes BSP/floating geometry, sets focus |
| `xdg_toplevel` `set_maximized` / `set_fullscreen` / `set_minimized` | Forwards `Toplevel*Request` to host | `handle_request(id, req, work_area)` → updates state, emits `SetGeometry` + `configure` |
| `xdg_toplevel` unmap / destroy | Removes from `WindowRegistry` | `close_window(id, work_area)` → reflows BSP tree, promotes next MRU window to focus |
### 8.2 Hybrid Layout Engine (Tiling + Floating + Monocle)
The reference WM (`lib/wm/`) implements a **per-workspace hybrid layout engine** so a single component supports both KDE-style floating windows and Sway/Hyprland-style tiling:
@@ -409,4 +365,4 @@ pub struct WmState {
mut focused : UInt64?
}
```
All layout math (`compute_bsp_rects`, `insert_leaf`, `remove_leaf`, `focus_direction`, `hit_test_stack`) lives in `lib/wm/` as pure functions over `WmState`, unit-tested via `moon test` before any Rust host integration.
All layout math (`compute_bsp_rects`, `insert_leaf`, `remove_leaf`, `focus_direction`, `hit_test_stack`) lives in `lib/wm/` as pure functions over `WmState`, unit-tested via `moon test` and integrated directly into `compositor/host/`.