CI / test (push) Failing after 16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DPL5hinfszxuytSmkHXNjS
393 lines
23 KiB
Markdown
393 lines
23 KiB
Markdown
# `chandra` Compositor & Window Manager Architecture
|
||
|
||
> **Target repository:** [experiments/chandra](https://git.site.latha.org/experiments/chandra)
|
||
> **Scope:** Architectural design for evolving `chandra` 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.
|
||
|
||
`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 |
|
||
|
||
```mermaid
|
||
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
|
||
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 (`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`, `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.
|
||
- **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 `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`
|
||
```wit
|
||
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`
|
||
```wit
|
||
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):
|
||
```wit
|
||
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 with `moon test` on both `wasm` and `native`).
|
||
- `components/wm-hybrid/`: Hybrid BSP tiling / Floating / Monocle WM component implementing `chandra: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 `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 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.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
|
||
- `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
|
||
|
||
| 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 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).
|
||
- **`chandra:wm/decoration@0.2.0` Interface:**
|
||
```wit
|
||
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 (`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`), `chandra` 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`)
|
||
```moonbit
|
||
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](https://wasi-gfx.dev/) WIT specification (`wasi-gfx:surface@0.2.0` and `wasi-gfx:frame-buffer@0.2.0`):
|
||
|
||
1. **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` (`buffer` resource with `get-with-copy` / `set-with-copy`).
|
||
- `wit/gfx/deps/wasi-gfx-surface-0.2.0/surface.wit`: `wasi-gfx:surface/surface@0.2.0` (`surface` resource, `create-desc`, `resize-event`, `frame-event`, `pointer-event`, `key-event`, and `stream<...>` event channels).
|
||
- `wit/gfx/deps/wasi-gfx-surface-0.2.0/surface-frame-buffer.wit`: `wasi-gfx:surface/surface-frame-buffer@0.2.0` (`context` resource binding a `surface` to `get-current-buffer()` + `present()`).
|
||
- `wit/gfx/worlds.wit`: `chandra:gfx@0.2.0/gui-loader` world importing `wasi-gfx` and exporting `init-gui`, `render-frame`, `on-resize`, `on-pointer`, and `on-key`.
|
||
|
||
2. **MoonBit `wasi-gfx` GUI Component (`components/gfx-gui/`):**
|
||
- Built with `wit-bindgen moonbit wit/gfx --world gui-loader` and `scripts/build-gfx.sh`.
|
||
- Uses `@surface.Surface::surface`, `@sfb.Context::context`, `@scene.SceneGraph`, and `@renderer.render_scene` to render the desktop shell, Breeze-decorated windows, and launcher overlay into RGBA8888 pixel buffers and present them through `wasi-gfx`.
|
||
|
||
3. **Pure-MoonBit Native `wasi-gfx` Runtime (`compositor/gfx/`):**
|
||
- Implements `Surface`, `FrameBuffer`, `SurfaceFrameBufferContext`, `present_pixmap`, and `present_scene` in pure MoonBit.
|
||
- `ChandraCompositor::present_to_gfx` and `ChandraCompositor::handle_gfx_events` in `compositor/host/` connect the native Wayland compositor to `wasi-gfx` surfaces (also exposed via `--gfx-out <path.png>` in `compositor/bin/main.mbt`).
|
||
|
||
4. **JS / Browser `wasi-gfx` Host Adapter (`host/src/wasi-gfx.mjs`, `host/web/main.mjs`):**
|
||
- Provides `WasiGfxSurface`, `WasiGfxBuffer`, `WasiGfxFrameBufferContext`, and `createWasiGfxHost()` for both `jco`-transpiled `wasi-gfx` components and the browser desktop shell (`host/web/main.mjs`), routing input streams and presenting RGBA8888 frames onto the `<canvas>`.
|
||
|