25 KiB
moon-plasma Compositor & Window Manager Architecture
Target repository: experiments/moon-plasma
Scope: Architectural design for evolvingmoon-plasmafrom its M0 JS/Canvas2D proof-of-concept into a native Wayland compositor and hot-swappable Window Manager (M3–M8), preserving its core invariant: every policy is a sandboxed MoonBit WebAssembly component; the host only owns mechanism, devices, and scanout.
1. Architectural Thesis: Split Mechanism vs. Policy
Traditional Wayland compositors (KWin, Sway, Mutter) bundle device management, Wayland protocol state, GPU compositing, window management policy, decorations, and shell UI into a single privileged process. A crash or logic bug in a decoration or tiling script can bring down the entire display server.
moon-plasma inverts this by splitting the compositor along a typed WebAssembly Component Model (WIT) boundary:
| 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 |
flowchart TB
subgraph clients["Foreign Wayland / XWayland Clients"]
c1["App A (xdg_toplevel, wl_shm / dmabuf)"]
c2["App B (xdg_toplevel + xdg_popup)"]
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)"]
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)"]
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<draw-op> + revision + actions" --> scene
wl -- "committed wl_surface buffers" --> scene
scene -- "damaged rects" --> ras --> be
Design Invariants Carried Forward from M0
- Components never touch raw pixels or GPU handles: UI components emit
list<draw-op>in local coordinates. Foreign Wayland clients write to host-ownedbuffer-surfaceresources; components only reference those opaque handles. - Deny-by-default capabilities: A component only receives the WIT imports declared in its world and explicitly granted in the session/desktop config.
- Fault isolation: If
window-managerordecorationtraps or exceeds its frame time budget,wasmtimeunwinds the call, the host logs aComponentFault, renders a fallback tile / server-side border, and keeps scanning out at 60/120 Hz.
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). - 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 thedecorationcomponent).zwlr_layer_shell_v1(optional for external bars/lockscreens, though nativemoon-plasmapanels are MoonBit components).
- Buffers & Sync:
zwp_linux_dmabuf_v1(v4 with scanout/renderer tranche feedback),wp_viewporter,wp_presentation_time. - XWayland (M6+): Rootless
Xwaylandmanaged by the host, mapping X11 windows into the exact sameWindowRegistryso the MoonBit WM treats them identically to native Wayland clients.
2.2 Window & Surface Management (Split Host/WM)
- Host (
WindowRegistry): Owns the authoritative lifecycle of everyxdg_toplevel,xdg_popup, andSubsurface, its committedwl_buffer(wrapped in abuffer-surfaceresource), its PID/app-id, and its pendingconfigureserials. - WM Component (
wm-policy): Holds pure state (workspaces/virtual desktops, tiling tree or floating geometry, MRU focus stack, window rules). Onwindow-opened,window-closed, orwindow-request(maximize, fullscreen, interactive move/resize), the host callswm-policy, which returns a list ofwm-actioncommands (set-geometry,focus,raise,set-state). - Hot-Swap Support: Because
WindowRegistrylives in the host, the user can hot-swap a floating WM component for a tiling WM component at runtime; the host replays the currentlist<window-state>into the new component'ssync-windowsentrypoint.
2.3 Input Handling & Routing (M2 → M5)
In M0 (host/src/desktop.mjs), the host hardcodes hit-testing. In the compositor design:
- Global Grabs (Host): Secure attention keys (e.g.,
Ctrl+Alt+FnVT switch), global shortcut table (shortcutsinterface), and active compositor grabs (interactive window move/resize drag) are handled first by the host. - Routing (WM / Shell Component): Remaining pointer/keyboard events are passed to the routing component (
route-input), which inspects its stacking order, panel rects, and popup grabs, returning aninput-target:client-surface(window-id, surface-local-point)→ Host translates towl_pointer/wl_keyboardevents for that Wayland client.decoration(window-id, hit-region)→ Host forwards todecorationcomponent (or initiates WM move/resize).plasmoid(widget-id, surface, local-point)→ Host callsplasmoid.on-event(existing M0 contract).wm-consumed→ Event handled by WM (e.g., click-to-focus without passing through, or alt-drag).
2.4 Output & Backend Management
- Nested Backend (M5): Runs inside a
winitwindow on an existing Wayland/X11 host. Outputs are virtual; resizing thewinitwindow emitsoutput-resizedtoshellandwm-policy. - Standalone DRM/KMS Backend (M8): Uses
udevfor GPU/input discovery,libseatfor unprivileged TTY/DRM master access,drm+gbmfor atomic modesetting, andlibinputfor raw pointer/keyboard/touch/gesture events. Exposes anoutputsWIT interface (mode, scale, transform, logical position) so a KScreen-like KCM component can configure multi-monitor layouts.
3. WIT Interface Design (wit/ Extensions)
Building on moonplasma:desktop@0.1.0 (wit/types.wit, wit/plasmoid.wit, wit/shell.wit), the compositor introduces two new domain packages (per docs/ARCHITECTURE.md §7 versioning rules) while remaining compatible with wit-bindgen moonbit 0.63.0 (--encoding utf16).
3.1 moonplasma:compositor/surface@0.2.0
package moonplasma:compositor@0.2.0;
interface surface {
use moonplasma:desktop/types@0.1.0.{size, rect};
/// Unforgeable host handle to a committed client buffer (SHM or DMA-BUF).
/// Components cannot read pixels; they can only inspect metadata and
/// reference the handle in a `draw-surface` op.
resource buffer-surface {
id: func() -> u64;
size: func() -> size;
/// True if the buffer contains an alpha channel requiring blending.
has-alpha: func() -> bool;
}
/// Extended render-list op for compositing foreign surfaces & cached layers.
variant composite-op {
draw(moonplasma:desktop/types@0.1.0.draw-op),
draw-surface(surface-draw),
push-opacity(u8),
pop-opacity,
}
record surface-draw {
surface: borrow<buffer-surface>,
dst: rect,
src: option<rect>,
radius: u32,
}
}
3.2 moonplasma:wm/policy@0.2.0
package moonplasma:wm@0.2.0;
interface policy {
use moonplasma:desktop/types@0.1.0.{rect, size, point, input-event};
use moonplasma:compositor/surface@0.2.0.{buffer-surface, composite-op};
type window-id = u64;
flags window-caps {
can-move,
can-resize,
can-maximize,
can-minimize,
can-fullscreen,
}
record window-state {
id: window-id,
app-id: string,
title: string,
geometry: rect,
min-size: size,
max-size: option<size>,
focused: bool,
maximized: bool,
fullscreen: bool,
workspace: u32,
caps: window-caps,
}
variant wm-action {
set-geometry(tuple<window-id, rect>),
focus(window-id),
raise(window-id),
close(window-id),
set-maximized(tuple<window-id, bool>),
set-fullscreen(tuple<window-id, bool>),
}
variant input-target {
client(tuple<window-id, point>),
decoration(tuple<window-id, point>),
shell-panel(point),
none,
}
/// Called on startup or WM hot-swap to synchronize existing windows.
sync-windows: func(outputs: list<rect>, windows: list<window-state>) -> list<wm-action>;
on-window-open: func(win: window-state, work-area: rect) -> list<wm-action>;
on-window-close: func(id: window-id) -> list<wm-action>;
on-pointer: func(pos: point, button: option<u32>, pressed: bool) -> input-target;
/// Returns window IDs in bottom-to-top Z-order.
stacking-order: func() -> list<window-id>;
}
3.3 Revision-Based Caching for render
To avoid copying unchanged list<draw-op> across the WASM linear-memory boundary every frame (mitigating docs/ARCHITECTURE.md §4a):
record render-frame {
revision: u64,
/// `none` means identical to `revision` — host reuses cached display list.
ops: option<list<draw-op>>,
}
The host passes last-known-revision: u64 into render(size, last-rev). Static widgets (like a digital clock between second ticks) return none in O(1).
4. Module Breakdown & Key Data Structures
4.1 Native Host (host-native/ in Rust)
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)
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 withmoon testusing syntheticWindowStates, 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 implementingmoonplasma:wm/policy.components/decoration-breeze/: Default server-side decoration component.
5. Event Loop & Async 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:
- Single-Threaded
calloopReactor:- Wayland source: Reads client requests, processes
wl_surface.commit, updatesWindowRegistryand surface damage regions. - Input source:
winitevents (nested) orlibinputfd (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.
- Wayland source: Reads client requests, processes
- 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 setsstore.set_epoch_deadline(4)(4 ms budget). - If a buggy component loops infinitely,
wasmtimetraps withInterrupt, the supervisor records aComponentFault, and the compositor continues rendering the frame.
- A lightweight background thread increments
6. Scene Graph, Damage Tracking & Rendering
6.1 Layered Scene Graph
Each output renders a 6-layer tree evaluated bottom-to-top:
Background:shell.desktop-surface.render-background(output_size)(cached by revision).Bottom:zwlr_layer_shell_v1bottom-layer surfaces.Windows: Iterated inwm-policy.stacking-order()order. Each window node composes:- Drop shadow / focus ring (
draw-ops) decorationcomponentlist<draw-op>(titlebar + borders)buffer-surface(mainxdg_toplevelsurface, clipped to geometry + corner radius)- Child
wl_subsurfaces andxdg_popups
- Drop shadow / focus ring (
Panel:shell.panel-layout.render-panel+ eachplasmoid.renderplaced at itslayout.placementsrect.Overlay: Active widget popups (plasmoid.popup), notification toasts, launcher overlay, lock screen.Cursor: Hardware DRM cursor plane (when available) or software cursordraw-op.
6.2 Damage Tracking
- Client Surface Damage:
wl_surface.damage_bufferregions are transformed into output-logical coordinates and unioned intoOutputDamage. - Component Damage: When a component returns
ops: some(...)with a newrevision, the host diffs the node's bounding box (old rect ∪ new rect) and adds it toOutputDamage. Ifops: none, zero damage is emitted. - Scanout / Present: The renderer clips drawing to
OutputDamageand passes damaged rects toeglSwapBuffersWithDamageKHR(nested) orDRM_MODE_PAGE_FLIPwithFB_DAMAGE_CLIPS(standalone).
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 |
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. |
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.
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:
| Wayland / Shell Event | Host (smithay) Action |
WM (wm-policy) 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_zones 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 |
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:
Workspace
├── layout_mode: Tiling(BinarySpacePartition) | Floating | Monocle
├── tiled_tree: Option[BspNode] // Split(Horizontal|Vertical, ratio, left, right) | Leaf(WindowId)
├── floating: Array[WindowId] // Ordered bottom-to-top; always rendered above tiled_tree
└── fullscreen: Option[WindowId] // Overrides output work_area; hides panel/decorations
- Work Area Computation: For each
Output,work_area = output.logical_rect - panel_exclusive_zones. Tiled windows fillwork_areawith configurableinner_gapandouter_gap(read fromtheme.tokens.spacing). - Window Rules (
app_id/titlematching): Evaluated inon-window-openbefore layout insertion:- Dialogs (
parent != Noneormin_size == max_size) automatically enterfloatingand center over their parent. - User rules (from
config-store) can pin anapp_idto a specific workspace, force floating, or disable decorations.
- Dialogs (
- Interactive Move & Resize State Machine:
- Triggered by
decorationhit-test (TitlebarDrag,ResizeEdge(N|S|E|W|NE|...)) orMod + Left/Right Drag. - Host enters an active pointer grab (
DragSession { win_id, mode, start_ptr, start_rect }) and streams delta updates towm.on-drag(delta)at pointer rate, throttlingxdg_toplevel.configureto once per VBlank.
- Triggered by
8.3 Focus, Seat & Stacking Management
- Focus Policy (Configurable):
ClickToFocus(default) orFocusFollowsMouse(sloppy focus). - MRU Focus Stack: Each workspace maintains an MRU
Array[WindowId]. Closing or minimizing the focused window automatically focusesmru[0]. - Seat Integration: When
wm-policyemitswm-action::focus(id), the host:- Sends
wl_keyboard.leaveto the previous surface andwl_keyboard.enterto the newwl_surface. - Updates
window-state.focusedand triggers adecorationredraw (active vs. inactive titlebar colors). - Notifies the
task-managerplasmoid viawindow-list-changed.
- Sends
- Z-Order (
stacking-order()): Strictly layered bottom-to-top:TiledWindows→FloatingWindows(MRU order) →AlwaysOnTop / PictureInPicture→Fullscreen.
8.4 Decorations (SSD vs. CSD via zxdg_decoration_manager_v1)
- Negotiation: On
xdg_toplevelcreation, the host advertiseszxdg_decoration_manager_v1with default modeServerSide.- Clients that accept SSD (most Qt/GTK/terminal apps) omit client shadows/titlebars; the host invokes the
decorationMoonBit component. - Clients that insist on CSD (e.g., GTK4/libadwaita apps requesting
ClientSide) are honored and wrapped in a minimal0pxdecoration node (only focus ring if configured).
- Clients that accept SSD (most Qt/GTK/terminal apps) omit client shadows/titlebars; the host invokes the
moonplasma:wm/decoration@0.2.0Interface:interface decoration { use moonplasma:desktop/types@0.1.0.{rect, size, draw-op}; use policy.{window-state}; enum hit-role { none, titlebar, close, maximize, minimize, resize-n, resize-s, resize-e, resize-w, resize-nw, resize-ne, resize-sw, resize-se } record hit-region { rect: rect, role: hit-role } record decoration-frame { /// Insets reserved around the client surface: (top, right, bottom, left) insets: tuple<u32, u32, u32, u32>, ops: list<draw-op>, hit-regions: list<hit-region>, } render: func(win: window-state, outer-size: size) -> decoration-frame; }
8.5 Keybindings & IPC for Panels, Taskbars & Launchers
- Global Shortcuts (
shortcutsWIT capability):- On startup,
wm-policyregisters bindings (e.g.,Super+Return→ launch terminal,Super+Q→ close focused,Super+1..9→ switch workspace,Super+Space→ toggle floating/tiled,Alt+Tab→ cycle MRU). - The host matches raw
xkbcommonkeysyms + modifiers in the input hot-path before forwarding to the focused Wayland client, invokingwm.on-action(action_id)on match.
- On startup,
- Host-Mediated Shell/Taskbar IPC (
window-registryread-only grant):- Instead of an ad-hoc UNIX socket protocol (
plasma-shell/hyprctl),moon-plasmapanels, taskbars, and pager plasmoids import a capability-attenuatedwindow-registryWIT interface:list-windows() -> list<window-summary>(id, title, app-id, workspace, focused, minimized — never raw buffers or input).activate(id)/minimize(id)/close(id)→ routed by the host towm-policy.on-window-request(...).
- A
task-managerplasmoid on the panel can thus render live window buttons, show urgent badges, and switch focus using the exact sameplasmoid+draw-opmodel asclock-digitalandlauncher.
- Instead of an ad-hoc UNIX socket protocol (
8.6 MoonBit Data Structures (lib/wm/wm.mbt)
pub enum LayoutMode {
Floating
Tiling
Monocle
}
pub enum BspNode {
Leaf(UInt64) // WindowId
Split(horizontal~ : Bool, ratio~ : Double, left~ : BspNode, right~ : BspNode)
}
pub struct Workspace {
id : UInt
mode : LayoutMode
mut tree : BspNode?
floating : Array[UInt64]
mru : Array[UInt64]
mut fullscreen : UInt64?
}
pub struct WmState {
outputs : Array[OutputInfo]
workspaces : Array[Workspace]
windows : Map[UInt64, WindowRecord]
mut active_workspace : UInt
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.