Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DPL5hinfszxuytSmkHXNjS
23 KiB
chandra Compositor & Window Manager Architecture
Target repository: experiments/chandra
Scope: Architectural design for evolvingchandrafrom 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.
chandra inverts this by splitting the compositor along a typed WebAssembly Component Model (WIT) boundary:
| Layer | Responsibility | Implementation | Trust Level |
|---|---|---|---|
| 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 |
flowchart TB
subgraph clients["Foreign Wayland Clients"]
c1["App A (xdg_toplevel, wl_shm)"]
c2["App B (xdg_toplevel + zxdg_toplevel_decoration_v1)"]
end
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 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 + SCM_RIGHTS fds" --> sys --> wl
wl -- "CompositorEvent" --> comp
comp <--> wm & deco & shell
comp -- "SceneGraph + DrawOps + ShmBufferSnapshot" --> scene --> ras
Design Invariants Carried Forward from M0
- 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/sendmsgwithSCM_RIGHTS,memfd_create,mmap/munmap). - Components never touch raw pixels or GPU handles: UI & decoration logic emit
DrawOplists in local coordinates; the MoonBit software rasterizer (compositor/renderer/) translates, clips, blends, and blits clientwl_shmbuffers. - WIT Component Model Compatibility:
components/*continue to compile to WASI P2.wasmcomponents forwit/conformance and the JS/Wasm host (host/), whilelib/wmruns natively insidecompositor/host/.
2. Core Compositor Responsibilities
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/XRGB8888viaSCM_RIGHTS),wl_shm_pool,wl_buffer,wl_output(v4),wl_seat(v7). - Desktop Shells:
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, enforcingServerSidemode with Breeze-style SSD).
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 chandra: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 chandra:compositor/surface@0.2.0
package chandra:compositor@0.2.0;
interface surface {
use chandra: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(chandra: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 chandra:wm/policy@0.2.0
package chandra:wm@0.2.0;
interface policy {
use chandra:desktop/types@0.1.0.{rect, size, point, input-event};
use chandra: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 MoonBit Compositor (compositor/)
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 # ChandraCompositor
│ └── 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 withmoon teston bothwasmandnative).components/wm-hybrid/: Hybrid BSP tiling / Floating / Monocle WM component implementingchandra:wm/policy.components/decoration-breeze/: Default server-side decoration component.
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. In the pure-MoonBit native compositor (compositor/host/), ChandraCompositor::step() drives a non-blocking poll loop over the listening Unix socket and connected Wayland client fds, dispatching CompositorEvents 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 layered tree evaluated bottom-to-top:
Background: Desktop gradient (build_shell_ops).Windows: Iterated inwm.stacking_order()order. Each window node composes:- Drop shadow (
FillRectwith alpha) - Breeze SSD decoration
DrawOps (titlebar + borders + window controls) - Client
wl_shmShmBufferSnapshot(ARGB8888/XRGB8888)
- Drop shadow (
Panel: Bottom panel + launcher + layout badge + window pills.Overlay: Active widget popups and overlays.
6.2 Damage Tracking
- Client Surface Damage:
wl_surface.commitmarks the window geometry dirty inDamageTracker. - Layout / Focus Damage:
WmActions mark full output damage and re-emitxdg_toplevel.configure+xdg_surface.configure.
6.3 Buffer Management & Rasterization
wl_shm(ARGB8888/XRGB8888): Mapped viacompositor/sys/sys_stub.c(mmap+memcpyinto MoonBitBytes+munmap) and blitted bycompositor/renderer.DrawOps (FillRect,StrokeRect,Line,Circle,Text,PushClip,PopClip): Rasterized in pure MoonBit with Porter-DuffSrcOveralpha blending and encoded to PNG/PPM in pure MoonBit.
7. Phased Implementation Roadmap
| Phase | Milestone | Deliverable | Verification Gate |
|---|---|---|---|
| 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 (chandra: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 chandra, 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
ChandraCompositor translates Wayland protocol events into lib/wm calls and applies the returned Array[WmAction] back to WaylandServer:
| Wayland / Shell Event | Compositor (compositor/wayland) Action |
WM (lib/wm) Role |
|---|---|---|
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:
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
chandra:wm/decoration@0.2.0Interface:interface decoration { use chandra: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),chandrapanels, 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 and integrated directly into compositor/host/.
9. wasi-gfx GUI Loading & Presentation Architecture
To load and present the chandra GUI portably across both the native MoonBit compositor and WebAssembly/browser hosts, chandra integrates the wasi-gfx WIT specification (wasi-gfx:surface@0.2.0 and wasi-gfx:frame-buffer@0.2.0):
-
WIT Contracts (
wit/gfx/):wit/gfx/deps/wasi-gfx-frame-buffer-0.2.0/frame-buffer.wit:wasi-gfx:frame-buffer/frame-buffer@0.2.0(bufferresource withget-with-copy/set-with-copy).wit/gfx/deps/wasi-gfx-surface-0.2.0/surface.wit:wasi-gfx:surface/surface@0.2.0(surfaceresource,create-desc,resize-event,frame-event,pointer-event,key-event, andstream<...>event channels).wit/gfx/deps/wasi-gfx-surface-0.2.0/surface-frame-buffer.wit:wasi-gfx:surface/surface-frame-buffer@0.2.0(contextresource binding asurfacetoget-current-buffer()+present()).wit/gfx/worlds.wit:chandra:gfx@0.2.0/gui-loaderworld importingwasi-gfxand exportinginit-gui,render-frame,on-resize,on-pointer, andon-key.
-
MoonBit
wasi-gfxGUI Component (components/gfx-gui/):- Built with
wit-bindgen moonbit wit/gfx --world gui-loaderandscripts/build-gfx.sh. - Uses
@surface.Surface::surface,@sfb.Context::context,@scene.SceneGraph, and@renderer.render_sceneto render the desktop shell, Breeze-decorated windows, and launcher overlay into RGBA8888 pixel buffers and present them throughwasi-gfx.
- Built with
-
Pure-MoonBit Native
wasi-gfxRuntime (compositor/gfx/):- Implements
Surface,FrameBuffer,SurfaceFrameBufferContext,present_pixmap, andpresent_scenein pure MoonBit. ChandraCompositor::present_to_gfxandChandraCompositor::handle_gfx_eventsincompositor/host/connect the native Wayland compositor towasi-gfxsurfaces (also exposed via--gfx-out <path.png>incompositor/bin/main.mbt).
- Implements
-
JS / Browser
wasi-gfxHost Adapter (host/src/wasi-gfx.mjs,host/web/main.mjs):- Provides
WasiGfxSurface,WasiGfxBuffer,WasiGfxFrameBufferContext, andcreateWasiGfxHost()for bothjco-transpiledwasi-gfxcomponents and the browser desktop shell (host/web/main.mjs), routing input streams and presenting RGBA8888 frames onto the<canvas>.
- Provides