Files
chandra/docs/compositor-design.md
T

25 KiB
Raw Blame History

moon-plasma Compositor & Window Manager Architecture

Target repository: experiments/moon-plasma
Scope: Architectural design for evolving moon-plasma from 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&lt;draw-op&gt; + revision + actions" --> scene
  wl -- "committed wl_surface buffers" --> scene
  scene -- "damaged rects" --> ras --> be

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.

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 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.

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.
  • WM Component (wm-policy): Holds pure state (workspaces/virtual desktops, tiling tree or floating geometry, MRU focus stack, window rules). On window-opened, window-closed, or window-request (maximize, fullscreen, interactive move/resize), the host calls wm-policy, which returns a list of wm-action commands (set-geometry, focus, raise, set-state).
  • Hot-Swap Support: Because WindowRegistry lives in the host, the user can hot-swap a floating WM component for a tiling WM component at runtime; the host replays the current list<window-state> into the new component's sync-windows entrypoint.

2.3 Input Handling & Routing (M2 → M5)

In M0 (host/src/desktop.mjs), the host hardcodes hit-testing. In the compositor design:

  1. Global Grabs (Host): Secure attention keys (e.g., Ctrl+Alt+Fn VT switch), global shortcut table (shortcuts interface), and active compositor grabs (interactive window move/resize drag) are handled first by the host.
  2. 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 an input-target:
    • client-surface(window-id, surface-local-point) → Host translates to wl_pointer / wl_keyboard events for that Wayland client.
    • decoration(window-id, hit-region) → Host forwards to decoration component (or initiates WM move/resize).
    • plasmoid(widget-id, surface, local-point) → Host calls plasmoid.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 winit window on an existing Wayland/X11 host. Outputs are virtual; resizing the winit window emits output-resized to shell and wm-policy.
  • Standalone DRM/KMS Backend (M8): Uses udev for GPU/input discovery, libseat for unprivileged TTY/DRM master access, drm + gbm for atomic modesetting, and libinput for raw pointer/keyboard/touch/gesture events. Exposes an outputs WIT 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 with moon test using synthetic WindowStates, 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.
  • 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:

  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.

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-ops)
    • decoration component list<draw-op> (titlebar + borders)
    • buffer-surface (main xdg_toplevel surface, clipped to geometry + corner radius)
    • Child wl_subsurfaces and xdg_popups
  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.

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).

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 fill work_area with configurable inner_gap and outer_gap (read from theme.tokens.spacing).
  • Window Rules (app_id / title matching): Evaluated in on-window-open before layout insertion:
    • Dialogs (parent != None or min_size == max_size) automatically enter floating and center over their parent.
    • User rules (from config-store) can pin an app_id to a specific workspace, force floating, or disable decorations.
  • Interactive Move & Resize State Machine:
    • Triggered by decoration hit-test (TitlebarDrag, ResizeEdge(N|S|E|W|NE|...)) or Mod + Left/Right Drag.
    • Host enters an active pointer grab (DragSession { win_id, mode, start_ptr, start_rect }) and streams delta updates to wm.on-drag(delta) at pointer rate, throttling xdg_toplevel.configure to once per VBlank.

8.3 Focus, Seat & Stacking Management

  • Focus Policy (Configurable): ClickToFocus (default) or FocusFollowsMouse (sloppy focus).
  • MRU Focus Stack: Each workspace maintains an MRU Array[WindowId]. Closing or minimizing the focused window automatically focuses mru[0].
  • Seat Integration: When wm-policy emits wm-action::focus(id), the host:
    1. Sends wl_keyboard.leave to the previous surface and wl_keyboard.enter to the new wl_surface.
    2. Updates window-state.focused and triggers a decoration redraw (active vs. inactive titlebar colors).
    3. Notifies the task-manager plasmoid via window-list-changed.
  • 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_toplevel creation, the host advertises zxdg_decoration_manager_v1 with default mode ServerSide.
    • Clients that accept SSD (most Qt/GTK/terminal apps) omit client shadows/titlebars; the host invokes the decoration MoonBit component.
    • Clients that insist on CSD (e.g., GTK4/libadwaita apps requesting ClientSide) are honored and wrapped in a minimal 0px decoration node (only focus ring if configured).
  • moonplasma:wm/decoration@0.2.0 Interface:
    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 (shortcuts WIT capability):
    • On startup, wm-policy registers 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 xkbcommon keysyms + modifiers in the input hot-path before forwarding to the focused Wayland client, invoking wm.on-action(action_id) on match.
  • Host-Mediated Shell/Taskbar IPC (window-registry read-only grant):
    • Instead of an ad-hoc UNIX socket protocol (plasma-shell / hyprctl), moon-plasma panels, taskbars, and pager plasmoids import a capability-attenuated window-registry WIT 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 to wm-policy.on-window-request(...).
    • A task-manager plasmoid on the panel can thus render live window buttons, show urgent badges, and switch focus using the exact same plasmoid + draw-op model as clock-digital and launcher.

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.