Compile the compositor to a wasm component, run by a small wasmtime host
CI / test (push) Failing after 22s

The whole compositor (Wayland server, window manager, scene, rasteriser, shell) now builds as
build/components/compositor.wasm: a component that imports only moonplasma:host/sys
(wit/host/sys.wit: sockets + SCM_RIGHTS, memfd, poll, spawn, files, clock) and exports run().
host-wasm/ is the native side: a wasmtime program implementing that interface with libc.

- compositor/sys: per-target backends (sys_native.mbt over the C shim, sys_wasm.mbt over the WIT
  imports) behind one API; wayland/nested/host/shell/scene/renderer/gfx build for wasm unchanged.
- compositor/app: the entry point (arg parsing + main loop) as a library for both targets;
  --serve keeps refreshing a PNG so a live compositor can be inspected without a display.
- compositor/font, compositor/wasm: wasm-side placeholders (bitmap font; no panel modules yet,
  since a component can't embed a second wasm runtime: that becomes a host import).
- scripts/gen-native-stubs.py: native stand-ins for wasm-only generated imports.
- just compositor-wasm / host-wasm / run-wasm.

Verified: foot connects to the component's socket and renders into it; native build and
tests unchanged (16/23, the same 7 need unbuilt panel modules).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-25 01:41:31 -08:00
1 parent 92d2b29889
commit 6aba9b6a4f
42 files changed
+3163 -10

No files matched your search

+171
View File
@@ -0,0 +1,171 @@
///| The compositor's entry point as a library: argument parsing and the main loop, with the
/// operating system reached only through `@sys`. The wasm component (components/compositor)
/// calls `run`; on the native side it is the same code with `@sys` backed by a C shim.
///
/// Arguments: --socket PATH --theme PATH --window --gfx-out PNG --serve --size WxH
/// With --gfx-out alone one frame is written and the program exits; add --serve to keep running
/// and rewrite the PNG about twice a second (for looking at a live compositor without a display).
///| Parse a decimal integer; None unless every character is a digit.
fn parse_dec(s : String) -> Int? {
if s.length() == 0 || s.length() > 6 {
return None
}
let mut n = 0
for ch in s {
let d = ch.to_int() - 48
if d < 0 || d > 9 {
return None
}
n = n * 10 + d
}
Some(n)
}
///| "WxH" -> (W, H), both positive.
fn parse_size(s : String) -> (Int, Int)? {
let mut x = -1
for i = 0; i < s.length(); i = i + 1 {
if s[i] == 'x' {
x = i
}
}
if x <= 0 {
return None
}
match (parse_dec(s[:x].to_string()), parse_dec(s[x + 1:].to_string())) {
(Some(w), Some(h)) if w > 0 && h > 0 => Some((w, h))
_ => None
}
}
///| Run the compositor until it exits. Returns the process exit code.
pub fn run(args : Array[String]) -> Int {
let mut socket_path = "/tmp/wayland-moon-0"
let mut theme_path = "config/themes/moon-night.json"
let mut gfx_out = ""
let mut windowed = false
let mut serve = false
let mut width = 1280
let mut height = 720
let mut i = 0
while i < args.length() {
let a = args[i]
if a == "--socket" && i + 1 < args.length() {
socket_path = args[i + 1]
i = i + 2
} else if a == "--theme" && i + 1 < args.length() {
theme_path = args[i + 1]
i = i + 2
} else if a == "--window" {
windowed = true
i = i + 1
} else if a == "--serve" {
serve = true
i = i + 1
} else if a == "--gfx-out" && i + 1 < args.length() {
gfx_out = args[i + 1]
i = i + 2
} else if a == "--size" && i + 1 < args.length() {
match parse_size(args[i + 1]) {
Some((w, h)) => {
width = w
height = h
}
None => {
@sys.log("bad --size " + args[i + 1] + " (expected WxH)")
return 2
}
}
i = i + 2
} else {
i = i + 1
}
}
let raw_theme = @sys.read_file_bytes(theme_path)
let theme = if raw_theme.length() > 0 {
let sb = StringBuilder()
for j = 0; j < raw_theme.length(); j = j + 1 {
sb.write_char(Int::unsafe_to_char(raw_theme[j].to_int()))
}
@scene.ThemeTokens::from_json_string(sb.to_string())
} else {
@scene.ThemeTokens::moon_night()
}
let gfx_surface = @gfx.Surface::new({ width: Some(width), height: Some(height) })
let gfx_ctx = @gfx.SurfaceFrameBufferContext::new(gfx_surface)
match @host.MoonPlasmaCompositor::new(socket_path, theme, width, height) {
None => {
@sys.log("failed to bind Wayland socket at " + socket_path)
1
}
Some(comp) => {
comp.shell.screen_w = width
if gfx_out.length() > 0 && !serve {
let pixmap = comp.present_to_gfx(gfx_ctx)
ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(pixmap)))
comp.close()
@sys.log("frame written to " + gfx_out)
return 0
}
let nested = if windowed {
let display = match @sys.getenv("WAYLAND_DISPLAY") {
"" => "wayland-0"
d => d
}
let rt = match @sys.getenv("XDG_RUNTIME_DIR") {
"" => "/tmp"
d => d
}
match @nested.NestedWindow::open(display, rt, "moon-plasma", "moon-plasma", width, height) {
Some(n) => Some(n)
None => {
@sys.log("failed to open a window on the host Wayland display")
comp.close()
return 1
}
}
} else {
None
}
@sys.log("moon-plasma compositor listening on " + socket_path)
let mut frames = 0
while true {
frames = frames + 1
comp.step()
match nested {
Some(n) => {
if !n.poll() {
break
}
if n.keymap.length() > 0 {
comp.server.set_keymap(n.keymap)
}
let now_ms = @sys.monotonic_ms().to_uint()
for ev in n.take_input() {
comp.handle_input(ev, now_ms)
}
n.set_cursor_shape(comp.desired_cursor())
if n.frame_ready() {
n.present(comp.present_to_gfx(gfx_ctx))
}
}
None => {
comp.handle_gfx_events(gfx_surface)
let pixmap = comp.present_to_gfx(gfx_ctx)
if serve && gfx_out.length() > 0 && frames % 30 == 0 {
ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(pixmap)))
}
}
}
@sys.sleep_ms(16)
}
comp.close()
0
}
}
}
+11
View File
@@ -0,0 +1,11 @@
import {
"moonbitlang/core/builtin",
"moonplasma/desktop/compositor/sys" @sys,
"moonplasma/desktop/compositor/scene" @scene,
"moonplasma/desktop/compositor/renderer" @renderer,
"moonplasma/desktop/compositor/gfx" @gfx,
"moonplasma/desktop/compositor/host" @host,
"moonplasma/desktop/compositor/nested" @nested,
}
supported_targets = "+native+wasm"
+13
View File
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/compositor/app"
// Values
pub fn run(Array[String]) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
File renamed without changes.
+7
View File
@@ -0,0 +1,7 @@
///| The compositor as a wasm component has no C rasteriser. Until the host offers glyphs through
/// an import, text uses the renderer's built-in bitmap font.
///| Install real fonts; always false here, so the renderer keeps its bitmap font.
pub fn install() -> Bool {
false
}
+5 -1
View File
@@ -3,8 +3,12 @@ import {
"moonplasma/desktop/compositor/renderer" @renderer,
}
supported_targets = "-all+native"
supported_targets = "+native+wasm"
options(
targets: {
"font_native.mbt": ["native"],
"font_wasm.mbt": ["wasm"],
},
"native-stub": [ "font_stub.c" ],
)
+1 -1
View File
@@ -12,7 +12,7 @@ import {
"moonplasma/desktop/compositor/gfx" @gfx,
}
supported_targets = "-all+native"
supported_targets = "+native+wasm"
options(
link: {
+1 -1
View File
@@ -5,4 +5,4 @@ import {
"moonplasma/desktop/compositor/wayland" @wayland,
}
supported_targets = "-all+native"
supported_targets = "+native+wasm"
+3 -3
View File
@@ -129,7 +129,7 @@ fn NestedWindow::dispatch(
if op == 0U {
let _id = r.u32()
let _code = r.u32()
println("nested: host wl_display error: " + r.str())
@sys.log("nested: host wl_display error: " + r.str())
self.closed = true
}
} else if obj == 2U {
@@ -342,7 +342,7 @@ pub fn NestedWindow::open(
self.seat_id = self.bind("wl_seat", 5U)
self.shape_mgr_id = self.bind("wp_cursor_shape_manager_v1", 1U)
if self.comp_id == 0U || self.shm_id == 0U || self.wm_id == 0U {
println("nested: host compositor lacks wl_compositor/wl_shm/xdg_wm_base")
@sys.log("nested: host compositor lacks wl_compositor/wl_shm/xdg_wm_base")
return None
}
self.surf_id = self.alloc()
@@ -381,7 +381,7 @@ pub fn NestedWindow::open(
tries = tries + 1
}
if !self.configured {
println("nested: host never sent xdg_surface.configure")
@sys.log("nested: host never sent xdg_surface.configure")
return None
}
Some(self)
+1 -1
View File
@@ -16,7 +16,7 @@ import {
"moonplasma/desktop/compositor/wasm" @wasm,
}
supported_targets = "-all+native"
supported_targets = "+native+wasm"
options(
link: {
+9 -1
View File
@@ -1,9 +1,17 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/env" @env,
"moonplasma/desktop/interface/moonplasma/host/sys" @hostsys,
}
supported_targets = "-all+native"
supported_targets = "+native+wasm"
// Native: POSIX through a C shim. Wasm (the compositor as a component): the same API over the
// moonplasma:host/sys imports, implemented by the native host.
options(
targets: {
"sys_native.mbt": ["native"],
"sys_wasm.mbt": ["wasm"],
},
"native-stub": [ "sys_stub.c" ],
)
@@ -246,3 +246,13 @@ extern "C" fn c_read_proc(path : Bytes) -> Bytes = "mp_read_proc"
pub fn read_proc_bytes(path : String) -> Bytes {
c_read_proc(str_to_utf8_bytes(path))
}
///| Milliseconds on a monotonic clock.
pub fn monotonic_ms() -> UInt64 {
@env.now()
}
///| Print a line to stderr (stdout on native).
pub fn log(message : String) -> Unit {
println(message)
}
+169
View File
@@ -0,0 +1,169 @@
///| The compositor as a wasm component: the same API as sys_native.mbt, with every operation
/// forwarded to the host through the `moonplasma:host/sys` imports. The component holds only
/// integer handles (fds) and bytes; the host owns the real descriptors.
///| Encode a String into UTF-8 Bytes.
pub fn str_to_utf8_bytes(s : String) -> Bytes {
let buf : Array[Byte] = []
for ch in s {
let code = ch.to_int()
if code < 0x80 {
buf.push(code.to_byte())
} else if code < 0x800 {
buf.push((0xC0 | (code >> 6)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
} else if code < 0x10000 {
buf.push((0xE0 | (code >> 12)).to_byte())
buf.push((0x80 | ((code >> 6) & 0x3F)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
} else {
buf.push((0xF0 | (code >> 18)).to_byte())
buf.push((0x80 | ((code >> 12) & 0x3F)).to_byte())
buf.push((0x80 | ((code >> 6) & 0x3F)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
}
}
Bytes::from_array(buf)
}
///|
fn to_fixed(b : Bytes) -> FixedArray[Byte] {
let out : FixedArray[Byte] = FixedArray::make(b.length(), b'\x00')
for i = 0; i < b.length(); i = i + 1 {
out[i] = b[i]
}
out
}
///|
fn from_fixed(a : FixedArray[Byte]) -> Bytes {
Bytes::from_fixedarray(a)
}
///|
pub fn unix_listen(path : String) -> Int {
@hostsys.unix_listen(path)
}
///|
pub fn unix_accept(listen_fd : Int) -> Int {
@hostsys.unix_accept(listen_fd)
}
///|
pub fn unix_connect(path : String) -> Int {
@hostsys.unix_connect(path)
}
///|
pub fn close_fd(fd : Int) -> Unit {
@hostsys.close_fd(fd)
}
///|
pub fn unlink(path : String) -> Unit {
@hostsys.unlink(path)
}
///|
pub fn poll_read(fd : Int, timeout_ms : Int) -> Int {
@hostsys.poll_read(fd, timeout_ms)
}
///| Receive bytes and an optional SCM_RIGHTS fd into `buf`. Returns (bytes_read, received_fd);
/// bytes_read == -1 means EAGAIN, -2 an error, 0 EOF.
pub fn recvmsg_fd(fd : Int, buf : FixedArray[Byte], max_len : Int) -> (Int, Int) {
let r = @hostsys.recvmsg(fd, max_len.reinterpret_as_uint())
if r.count > 0 {
let n = if r.count < r.data.length() { r.count } else { r.data.length() }
for i = 0; i < n && i < buf.length(); i = i + 1 {
buf[i] = r.data[i]
}
}
(r.count, r.fd)
}
///|
pub fn sendmsg_fd(fd : Int, buf : Bytes, send_fd : Int) -> Int {
@hostsys.sendmsg(fd, to_fixed(buf), send_fd)
}
///|
pub fn memfd_create(name : String, size : Int) -> Int {
@hostsys.memfd_create(name, size)
}
///|
pub fn pwrite_bytes(fd : Int, buf : Bytes, offset : Int) -> Int {
@hostsys.pwrite(fd, to_fixed(buf), offset)
}
///|
pub fn mmap_read(fd : Int, size : Int) -> Bytes {
from_fixed(@hostsys.mmap_read(fd, size))
}
///|
pub fn read_file_bytes(path : String) -> Bytes {
from_fixed(@hostsys.read_file(path))
}
///|
pub fn write_file_bytes(path : String, data : Bytes) -> Int {
@hostsys.write_file(path, to_fixed(data))
}
///|
pub fn sleep_ms(ms : Int) -> Unit {
@hostsys.sleep_ms(ms)
}
///|
pub fn getpid() -> Int {
@hostsys.getpid()
}
///| Local wall clock: 0 year, 1 month (1-12), 2 day, 3 hour, 4 minute, 5 second, 6 weekday (0 = Sunday).
pub fn wall_time_field(which : Int) -> Int {
@hostsys.wall_time_field(which)
}
///| Whether `name` is an executable on PATH.
pub fn has_exe(name : String) -> Bool {
@hostsys.has_exe(name)
}
///| Launch `cmd` detached with WAYLAND_DISPLAY set to `display`.
pub fn spawn(cmd : String, display : String) -> Bool {
@hostsys.spawn(cmd, display)
}
///| Names of the `*.desktop` files directly in `dir`.
pub fn list_desktop_files(dir : String) -> Array[String] {
@hostsys.list_desktop_files(dir)
}
///| Environment variable, or "" when unset.
pub fn getenv(name : String) -> String {
@hostsys.getenv(name)
}
///| Create `path` and any missing parents; true when it exists afterwards.
pub fn mkdir_p(path : String) -> Bool {
@hostsys.mkdir_p(path)
}
///| Contents of a small /proc or /sys file ("" when unreadable).
pub fn read_proc_bytes(path : String) -> Bytes {
from_fixed(@hostsys.read_proc(path))
}
///| Milliseconds on the host's monotonic clock.
pub fn monotonic_ms() -> UInt64 {
@hostsys.monotonic_ms()
}
///| Print a line to the host's stderr.
pub fn log(message : String) -> Unit {
@hostsys.log(message)
}
+6 -1
View File
@@ -4,9 +4,14 @@ import {
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
}
supported_targets = "-all+native"
supported_targets = "+native+wasm"
options(
targets: {
"wasm_native.mbt": ["native"],
"wasm_unsupported.mbt": ["wasm"],
"wasm_test.mbt": ["native"],
},
"native-stub": [ "wasm_stub.c" ],
link: {
"native": {
File renamed without changes.
+233
View File
@@ -0,0 +1,233 @@
///| Plasmoid host for the compositor-as-a-wasm-component build.
///
/// The native build runs panel modules itself through wasmer. A component can't embed a second
/// wasm runtime, so the module host will become a host import (the native side instantiating the
/// modules with wasmtime). Until that import exists, the same API is here with nothing loadable:
/// `load` fails, no requests ever arrive, and the panel stays empty.
///|
fn utf8(s : String) -> Bytes {
let buf : Array[Byte] = []
for ch in s {
let code = ch.to_int()
if code < 0x80 {
buf.push(code.to_byte())
} else if code < 0x800 {
buf.push((0xC0 | (code >> 6)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
} else if code < 0x10000 {
buf.push((0xE0 | (code >> 12)).to_byte())
buf.push((0x80 | ((code >> 6) & 0x3F)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
} else {
buf.push((0xF0 | (code >> 18)).to_byte())
buf.push((0x80 | ((code >> 12) & 0x3F)).to_byte())
buf.push((0x80 | ((code >> 6) & 0x3F)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
}
}
Bytes::from_array(buf)
}
///|
pub fn pack_tokens(_t : @theme.Tokens) -> Bytes {
Bytes::make(64, b'\x00')
}
///| A loaded plasmoid instance.
pub(all) struct Plasmoid {
handle : Int
id : String
name : String
pref_w : Int
pref_h : Int
min_w : Int
stretch : Bool
imports : Array[String]
}
///| Always fails in the component build (see the file comment).
pub fn load(_path : String, _tokens : @theme.Tokens) -> Result[Plasmoid, String] {
Err("panel modules are not available in the wasm compositor yet")
}
///|
pub(all) struct SystemSnapshot {
cpu_permille : Int
mem_used_kib : Int64
mem_total_kib : Int64
battery_percent : Int
charging : Bool
uptime_secs : Int64
rx_bps : Int64
tx_bps : Int64
load_centi : Int
}
///|
pub(all) struct WindowEntry {
id : UInt64
title : String
app_id : String
focused : Bool
}
///|
pub fn set_system(_s : SystemSnapshot) -> Unit {
()
}
///|
pub fn set_windows(_wins : Array[WindowEntry]) -> Unit {
()
}
///|
pub fn take_focus_request() -> UInt64? {
None
}
///|
pub fn Plasmoid::pointer_down(_self : Plasmoid, _x : Int, _y : Int) -> Bool {
false
}
///|
pub fn Plasmoid::unload(_self : Plasmoid) -> Unit {
()
}
///|
pub fn Plasmoid::render(
_self : Plasmoid,
_w : Int,
_h : Int,
_tokens : @theme.Tokens,
) -> Array[@types.DrawOp] {
[]
}
///| A popup surface a plasmoid wants shown next to its panel widget.
pub(all) struct PopupSurface {
w : Int
h : Int
ops : Array[@types.DrawOp]
}
///|
pub fn Plasmoid::popup(_self : Plasmoid) -> PopupSurface? {
None
}
///| An input event for a plasmoid (mirrors the WIT `input-event`).
pub(all) enum PlasmoidEvent {
PointerMove(Int, Int)
PointerDown(Int, Int)
PointerUp(Int, Int)
PointerLeave
FocusLost
KeyDown(String)
}
///|
pub fn Plasmoid::on_event(_self : Plasmoid, _popup : Bool, _ev : PlasmoidEvent) -> Bool {
false
}
///|
pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] {
self.imports
}
///| Rows of host data a module can read through its capability imports.
pub(all) struct Table {
rows : Array[Byte]
mut n : Int
}
///|
pub fn Table::new() -> Table {
{ rows: [], n: 0 }
}
///|
fn Table::push32(self : Table, v : Int) -> Unit {
for k = 0; k < 4; k = k + 1 {
self.rows.push(((v >> (8 * k)) & 0xFF).to_byte())
}
}
///| An i32 field.
pub fn Table::int(self : Table, v : Int) -> Unit {
self.push32(v)
}
///| A string field.
pub fn Table::str(self : Table, s : String) -> Unit {
let b = utf8(s)
self.push32(b.length())
for i = 0; i < b.length(); i = i + 1 {
self.rows.push(b[i])
}
}
///| Finish one row.
pub fn Table::end_row(self : Table) -> Unit {
self.n = self.n + 1
}
///|
pub(all) enum HostTable {
Apps
Windows
Layouts
Modules
Instances
}
///|
pub fn publish(_which : HostTable, _t : Table) -> Unit {
()
}
///|
pub fn publish_state(_layout_mode : Int, _inspector_on : Bool) -> Unit {
()
}
///| Something a module asked the host to do during a call.
pub(all) enum HostRequest {
Launch(String)
FocusWindow(Int)
SetLayout(Int)
SetInspector(Bool)
LoadModule(String)
UnloadInstance(String)
Browse
} derive(Eq, Debug)
///|
pub fn next_request() -> HostRequest? {
None
}
///|
pub fn list_wasm_files(_dir : String) -> Array[String] {
[]
}
///| An in-flight native file-chooser dialog.
pub(all) struct Picker {
fd : Int
buf : Array[Byte]
}
///|
pub fn Picker::start() -> Picker? {
None
}
///|
pub fn Picker::poll(_self : Picker) -> String?? {
None
}
+1 -1
View File
@@ -4,4 +4,4 @@ import {
"moonplasma/desktop/compositor/scene" @scene,
}
supported_targets = "-all+native"
supported_targets = "+native+wasm"