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

+1
View File
@@ -7,3 +7,4 @@ node_modules/
*.log
host-native/target/
.pixi/
host-wasm/target/
+46
View File
@@ -0,0 +1,46 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub fn mbt_ffi_cabi_realloc(
src_offset : Int,
src_size : Int,
_dst_alignment : Int,
dst_size : Int,
) -> Int {
// malloc
if src_offset == 0 && src_size == 0 {
return mbt_ffi_malloc(dst_size)
}
// free
if dst_size == 0 {
mbt_ffi_free(src_offset)
return 0
}
// realloc
let dst = mbt_ffi_malloc(dst_size)
mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size })
mbt_ffi_free(src_offset)
dst
}
///|
extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) =
#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
#doc(hidden)
pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int {
@compositor.wasmExportRun(p0, p1)
}
+20
View File
@@ -0,0 +1,20 @@
import {
"moonplasma/desktop/components/compositor/gen/world/compositor" @compositor,
}
warnings = "-44"
pkgtype(kind: "foreign_library")
options(
link: {
"wasm": {
"export-memory-name": "memory",
"heap-start-address": 16,
"exports": [
"mbt_ffi_cabi_realloc:cabi_realloc",
"wasmExportRun:run"
],
},
},
)
@@ -0,0 +1,37 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int {
let array : Array[String] = [];
for index = 0; index < (p1); index = index + 1 {
let iter_base = (p0) + (index * 8)
let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4))
array.push(result)
}
mbt_ffi_free(p0)
let (result0) : (Int) = run(array);
let ret = result0
return ret
}
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
@@ -0,0 +1,5 @@
import {
"moonplasma/desktop/compositor/app" @app,
}
warnings = "-44"
@@ -0,0 +1,6 @@
///| The compositor component's entry point: everything lives in compositor/app.
///|
pub fn run(args : Array[String]) -> Int {
@app.run(args)
}
@@ -0,0 +1,5 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
/// Run the compositor until it exits. `args` are the command-line arguments (without argv[0]).
declare pub fn run(args : Array[String]) -> Int
+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"
+1168
View File
File diff suppressed because it is too large. Load diff
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "moon-plasma-host"
version = "0.1.0"
edition = "2021"
description = "Runs the moon-plasma compositor wasm component (build/components/compositor.wasm) and gives it the OS surface it imports (wit/host/sys.wit)."
[dependencies]
libc = "0.2"
wasmtime = { version = "50", default-features = false, features = ["component-model", "cranelift", "runtime", "std"] }
[profile.release]
opt-level = 2
+42
View File
@@ -0,0 +1,42 @@
# moon-plasma-host
Runs the compositor **as a WebAssembly component**.
```
just compositor-wasm # build/components/compositor.wasm (the compositor, a component)
just host-wasm # host-wasm/target/release/moon-plasma-host (this crate)
just run-wasm # both, then run in a window on your current Wayland session
```
The component (`components/compositor`, entry in `compositor/app`) imports exactly one interface,
`moonplasma:host/sys` ([`wit/host/sys.wit`](../wit/host/sys.wit)), and exports `run(args) -> s32`.
It is the same MoonBit code as the native compositor: the Wayland server, window manager, scene,
rasteriser and shell. Only `compositor/sys` differs per target (`sys_native.mbt` over a C shim,
`sys_wasm.mbt` over the WIT imports). The component holds integer handles and bytes only; every real
file descriptor lives in this host, which implements `sys` with libc (sockets and `SCM_RIGHTS`,
`memfd`, `poll`, spawn, files, clock).
```
moon-plasma-host build/components/compositor.wasm --socket PATH [--theme PATH] [--window]
moon-plasma-host build/components/compositor.wasm --socket PATH --gfx-out frame.png # one frame
moon-plasma-host build/components/compositor.wasm --socket PATH --gfx-out frame.png --serve # keep refreshing it
```
## Status
Working: Wayland server (real clients such as `foot` run and draw), window management, decorations,
the desktop card, input routing, the nested window on the host session.
Not yet in the component (the native compositor still has these):
- **Panel modules.** The panel is built from wasm modules, which the native build runs with wasmer.
A component can't embed another runtime, so this becomes a host import: the host instantiates the
modules with wasmtime and hands the compositor their draw ops (`compositor/wasm/wasm_unsupported.mbt`
is the placeholder; the panel is empty until then).
- **Real fonts.** `compositor/font` uses a C rasteriser; the component falls back to the bitmap font
until the host offers glyphs (`compositor/font/font_wasm.mbt`).
- **DRM/KMS and libinput** (`--drm`), the login-session backend.
Regenerating the host bindings: `wit-bindgen moonbit wit/host --world compositor --out-dir . --gen-dir
components/compositor/gen --project-name moonplasma/desktop --ignore-module-file --ignore-stub`, then
`scripts/gen-native-stubs.py interface/moonplasma/host/sys` (the imports are wasm-only; this restores
the native stand-ins and the per-file targets).
+430
View File
@@ -0,0 +1,430 @@
//! Native host for the moon-plasma compositor component.
//!
//! The compositor is a wasm component (build/components/compositor.wasm) that imports exactly one
//! interface, `moonplasma:host/sys` (wit/host/sys.wit): sockets, memfd, poll, spawn, files, time.
//! This program is the other side of that interface. The component only ever holds integer
//! handles; every real file descriptor lives here.
//!
//! moon-plasma-host [--component PATH] [-- compositor args...]
//! moon-plasma-host build/components/compositor.wasm --socket /run/user/1000/wayland-moon-0 --window
use std::ffi::CString;
use std::io::Read;
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use wasmtime::component::{Component, HasSelf, Linker};
use wasmtime::{Config, Engine, Result, Store};
wasmtime::component::bindgen!({
path: "../wit/host",
world: "compositor",
});
use moonplasma::host::sys::{Host, Received};
#[derive(Default)]
struct State {
/// Address of the private session bus launched apps use (started on first spawn).
private_bus: Option<String>,
bus_tried: bool,
started: Option<std::time::Instant>,
}
fn sockaddr_un(path: &str) -> (libc::sockaddr_un, libc::socklen_t) {
let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() };
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
let bytes = path.as_bytes();
let n = bytes.len().min(addr.sun_path.len() - 1);
for (i, b) in bytes[..n].iter().enumerate() {
addr.sun_path[i] = *b as libc::c_char;
}
(addr, std::mem::size_of::<libc::sockaddr_un>() as libc::socklen_t)
}
fn set_nonblock_cloexec(fd: i32) {
unsafe {
let fl = libc::fcntl(fd, libc::F_GETFL, 0);
if fl >= 0 {
libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
}
let fdfl = libc::fcntl(fd, libc::F_GETFD, 0);
if fdfl >= 0 {
libc::fcntl(fd, libc::F_SETFD, fdfl | libc::FD_CLOEXEC);
}
}
}
impl State {
/// A private session bus, so single-instance apps (Firefox, Kate, Dolphin...) don't forward
/// their launch to an instance on the host session. Dies with this process.
fn private_bus(&mut self) -> Option<String> {
if self.bus_tried {
return self.private_bus.clone();
}
self.bus_tried = true;
let mut cmd = Command::new("dbus-daemon");
cmd.args(["--session", "--nofork", "--print-address=1"])
.stdout(Stdio::piped())
.stderr(Stdio::null());
unsafe {
cmd.pre_exec(|| {
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
Ok(())
});
}
let mut child = cmd.spawn().ok()?;
let mut out = child.stdout.take()?;
let mut buf = [0u8; 256];
let n = out.read(&mut buf).unwrap_or(0);
std::mem::forget(child); // keep it running; PDEATHSIG ends it with us
std::mem::forget(out);
if n > 0 {
let s = String::from_utf8_lossy(&buf[..n]);
self.private_bus = s.lines().next().map(|l| l.to_string());
}
self.private_bus.clone()
}
}
impl Host for State {
fn unix_listen(&mut self, path: String) -> i32 {
let _ = std::fs::remove_file(&path);
unsafe {
let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0);
if fd < 0 {
return -1;
}
set_nonblock_cloexec(fd);
let (addr, len) = sockaddr_un(&path);
if libc::bind(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 || libc::listen(fd, 16) < 0 {
libc::close(fd);
return -1;
}
fd
}
}
fn unix_accept(&mut self, listen_fd: i32) -> i32 {
unsafe {
let fd = libc::accept(listen_fd, std::ptr::null_mut(), std::ptr::null_mut());
if fd < 0 {
return -1;
}
set_nonblock_cloexec(fd);
fd
}
}
fn unix_connect(&mut self, path: String) -> i32 {
unsafe {
let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0);
if fd < 0 {
return -1;
}
let (addr, len) = sockaddr_un(&path);
if libc::connect(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 {
libc::close(fd);
return -1;
}
fd
}
}
fn close_fd(&mut self, fd: i32) {
if fd >= 0 {
unsafe { libc::close(fd) };
}
}
fn unlink(&mut self, path: String) {
let _ = std::fs::remove_file(path);
}
fn poll_read(&mut self, fd: i32, timeout_ms: i32) -> i32 {
let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 };
let r = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
if r < 0 {
-1
} else if r == 0 {
0
} else if pfd.revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 {
1
} else {
0
}
}
fn recvmsg(&mut self, fd: i32, max_len: u32) -> Received {
let mut data = vec![0u8; max_len as usize];
if data.is_empty() {
return Received { count: 0, fd: -1, data };
}
unsafe {
let mut iov = libc::iovec { iov_base: data.as_mut_ptr() as *mut _, iov_len: data.len() };
let space = libc::CMSG_SPACE((std::mem::size_of::<i32>() * 4) as u32) as usize;
let mut cbuf = vec![0u8; space];
let mut msg: libc::msghdr = std::mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = cbuf.as_mut_ptr() as *mut _;
msg.msg_controllen = space as _;
let n = libc::recvmsg(fd, &mut msg, 0);
if n < 0 {
let e = *libc::__errno_location();
let c = if e == libc::EAGAIN || e == libc::EWOULDBLOCK { -1 } else { -2 };
return Received { count: c, fd: -1, data: Vec::new() };
}
let mut got = -1;
let mut cm = libc::CMSG_FIRSTHDR(&msg);
while !cm.is_null() {
if (*cm).cmsg_level == libc::SOL_SOCKET && (*cm).cmsg_type == libc::SCM_RIGHTS {
let n_fds = ((*cm).cmsg_len as usize - libc::CMSG_LEN(0) as usize) / std::mem::size_of::<i32>();
let fds = libc::CMSG_DATA(cm) as *const i32;
for i in 0..n_fds {
let f = *fds.add(i);
if i == 0 {
got = f;
} else {
libc::close(f);
}
}
}
cm = libc::CMSG_NXTHDR(&msg, cm);
}
data.truncate(n as usize);
Received { count: n as i32, fd: got, data }
}
}
fn sendmsg(&mut self, fd: i32, data: Vec<u8>, send_fd: i32) -> i32 {
if data.is_empty() {
return 0;
}
unsafe {
let mut total = 0usize;
let mut with_fd = send_fd >= 0;
while total < data.len() {
let mut iov = libc::iovec {
iov_base: data.as_ptr().add(total) as *mut _,
iov_len: data.len() - total,
};
let space = libc::CMSG_SPACE(std::mem::size_of::<i32>() as u32) as usize;
let mut cbuf = vec![0u8; space];
let mut msg: libc::msghdr = std::mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
if with_fd {
msg.msg_control = cbuf.as_mut_ptr() as *mut _;
msg.msg_controllen = space as _;
let cm = libc::CMSG_FIRSTHDR(&msg);
(*cm).cmsg_level = libc::SOL_SOCKET;
(*cm).cmsg_type = libc::SCM_RIGHTS;
(*cm).cmsg_len = libc::CMSG_LEN(std::mem::size_of::<i32>() as u32) as _;
std::ptr::copy_nonoverlapping(&send_fd as *const i32 as *const u8, libc::CMSG_DATA(cm), 4);
}
let sent = libc::sendmsg(fd, &msg, libc::MSG_NOSIGNAL);
if sent < 0 {
let e = *libc::__errno_location();
if e == libc::EAGAIN || e == libc::EWOULDBLOCK {
let mut pfd = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 };
libc::poll(&mut pfd, 1, 50);
continue;
}
return -1;
}
total += sent as usize;
with_fd = false; // ancillary data goes with the first chunk only
}
total as i32
}
}
fn memfd_create(&mut self, name: String, size: i32) -> i32 {
let Ok(cname) = CString::new(name) else { return -1 };
unsafe {
let fd = libc::memfd_create(cname.as_ptr(), libc::MFD_CLOEXEC);
if fd < 0 {
return -1;
}
if size > 0 && libc::ftruncate(fd, size as libc::off_t) < 0 {
libc::close(fd);
return -1;
}
fd
}
}
fn pwrite(&mut self, fd: i32, data: Vec<u8>, offset: i32) -> i32 {
let w = unsafe { libc::pwrite(fd, data.as_ptr() as *const _, data.len(), offset as libc::off_t) };
if w < 0 { -1 } else { w as i32 }
}
fn mmap_read(&mut self, fd: i32, size: i32) -> Vec<u8> {
if fd < 0 || size <= 0 {
return Vec::new();
}
unsafe {
let mut st: libc::stat = std::mem::zeroed();
if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < size as i64 {
return Vec::new();
}
let p = libc::mmap(std::ptr::null_mut(), size as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0);
if p == libc::MAP_FAILED {
return Vec::new();
}
let out = std::slice::from_raw_parts(p as *const u8, size as usize).to_vec();
libc::munmap(p, size as usize);
out
}
}
fn read_file(&mut self, path: String) -> Vec<u8> {
std::fs::read(path).unwrap_or_default()
}
fn write_file(&mut self, path: String, data: Vec<u8>) -> i32 {
match std::fs::write(path, &data) {
Ok(()) => 0,
Err(_) => -1,
}
}
fn read_proc(&mut self, path: String) -> Vec<u8> {
// /proc and /sys files report size 0: read to EOF, capped at 64 KiB.
let Ok(f) = std::fs::File::open(path) else { return Vec::new() };
let mut out = Vec::new();
let _ = f.take(65536).read_to_end(&mut out);
out
}
fn mkdir_p(&mut self, path: String) -> bool {
std::fs::create_dir_all(path).is_ok()
}
fn list_desktop_files(&mut self, dir: String) -> Vec<String> {
let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
rd.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".desktop"))
.collect()
}
fn sleep_ms(&mut self, ms: i32) {
if ms > 0 {
std::thread::sleep(std::time::Duration::from_millis(ms as u64));
}
}
fn monotonic_ms(&mut self) -> u64 {
self.started.get_or_insert_with(std::time::Instant::now).elapsed().as_millis() as u64
}
fn log(&mut self, message: String) {
eprintln!("{message}");
}
fn getpid(&mut self) -> i32 {
std::process::id() as i32
}
fn wall_time_field(&mut self, which: i32) -> i32 {
unsafe {
let t = libc::time(std::ptr::null_mut());
let mut tm: libc::tm = std::mem::zeroed();
libc::localtime_r(&t, &mut tm);
match which {
0 => tm.tm_year + 1900,
1 => tm.tm_mon + 1,
2 => tm.tm_mday,
3 => tm.tm_hour,
4 => tm.tm_min,
5 => tm.tm_sec,
6 => tm.tm_wday,
_ => 0,
}
}
}
fn getenv(&mut self, name: String) -> String {
std::env::var(name).unwrap_or_default()
}
fn has_exe(&mut self, name: String) -> bool {
let ok = |p: &std::path::Path| {
CString::new(p.as_os_str().as_encoded_bytes())
.map(|c| unsafe { libc::access(c.as_ptr(), libc::X_OK) == 0 })
.unwrap_or(false)
};
if name.contains('/') {
return ok(std::path::Path::new(&name));
}
std::env::var_os("PATH")
.map(|p| std::env::split_paths(&p).any(|d| ok(&d.join(&name))))
.unwrap_or(false)
}
fn spawn(&mut self, cmd: String, display: String) -> bool {
let bus = self.private_bus();
let mut c = Command::new("/bin/sh");
c.arg("-c").arg(&cmd);
// Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak on
// the real session bus, so they keep it; everything else gets the private bus.
if let Some(b) = bus {
if !cmd.contains("flatpak run") {
c.env("DBUS_SESSION_BUS_ADDRESS", b);
}
}
c.env("WAYLAND_DISPLAY", display)
.env_remove("DISPLAY")
// Make toolkits pick our Wayland socket, not X11 or the host session.
.env("XDG_SESSION_TYPE", "wayland")
.env("QT_QPA_PLATFORM", "wayland")
.env("GDK_BACKEND", "wayland")
.env("SDL_VIDEODRIVER", "wayland")
.env("MOZ_ENABLE_WAYLAND", "1")
.env("ELECTRON_OZONE_PLATFORM_HINT", "wayland")
.env("CLUTTER_BACKEND", "wayland")
.stdin(Stdio::null());
unsafe {
c.pre_exec(|| {
libc::setsid();
libc::signal(libc::SIGCHLD, libc::SIG_DFL);
Ok(())
});
}
c.spawn().is_ok()
}
}
fn main() -> Result<()> {
let mut args: Vec<String> = std::env::args().skip(1).collect();
// First argument may be the component path; otherwise use the default build location.
let component_path = if args.first().map(|a| a.ends_with(".wasm")).unwrap_or(false) {
args.remove(0)
} else {
"build/components/compositor.wasm".to_string()
};
if args.first().map(|a| a == "--").unwrap_or(false) {
args.remove(0);
}
// No zombies from launched apps.
unsafe { libc::signal(libc::SIGCHLD, libc::SIG_IGN) };
let mut config = Config::new();
config.wasm_component_model(true);
let engine = Engine::new(&config)?;
let component = match Component::from_file(&engine, &component_path) {
Ok(c) => c,
Err(e) => {
eprintln!("error: cannot load {component_path}: {e}\n build it with `just compositor-wasm`");
std::process::exit(1);
}
};
let mut linker: Linker<State> = Linker::new(&engine);
moonplasma::host::sys::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
let mut store = Store::new(&engine, State::default());
let compositor = Compositor::instantiate(&mut store, &component, &linker)?;
let code = compositor.call_run(&mut store, &args)?;
std::process::exit(code);
}
+3
View File
@@ -0,0 +1,3 @@
The operating-system surface the compositor component needs, nothing more. The native host
implements it with real syscalls; the component holds only integer handles (fds) and bytes.
Mirrors compositor/sys.
+113
View File
@@ -0,0 +1,113 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
fn wasmImportUnixListen(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "unix-listen"
///|
fn wasmImportUnixAccept(p0 : Int) -> Int = "moonplasma:host/sys@0.1.0" "unix-accept"
///|
fn wasmImportUnixConnect(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "unix-connect"
///|
fn wasmImportCloseFd(p0 : Int) = "moonplasma:host/sys@0.1.0" "close-fd"
///|
fn wasmImportUnlink(p0 : Int, p1 : Int) = "moonplasma:host/sys@0.1.0" "unlink"
///|
fn wasmImportPollRead(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "poll-read"
///|
fn wasmImportRecvmsg(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "recvmsg"
///|
fn wasmImportSendmsg(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "sendmsg"
///|
fn wasmImportMemfdCreate(p0 : Int, p1 : Int, p2 : Int) -> Int = "moonplasma:host/sys@0.1.0" "memfd-create"
///|
fn wasmImportPwrite(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "pwrite"
///|
fn wasmImportMmapRead(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "mmap-read"
///|
fn wasmImportReadFile(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "read-file"
///|
fn wasmImportWriteFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "write-file"
///|
fn wasmImportReadProc(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "read-proc"
///|
fn wasmImportMkdirP(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "mkdir-p"
///|
fn wasmImportListDesktopFiles(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "list-desktop-files"
///|
fn wasmImportSleepMs(p0 : Int) = "moonplasma:host/sys@0.1.0" "sleep-ms"
///|
fn wasmImportMonotonicMs() -> Int64 = "moonplasma:host/sys@0.1.0" "monotonic-ms"
///|
fn wasmImportLog(p0 : Int, p1 : Int) = "moonplasma:host/sys@0.1.0" "log"
///|
fn wasmImportGetpid() -> Int = "moonplasma:host/sys@0.1.0" "getpid"
///|
fn wasmImportWallTimeField(p0 : Int) -> Int = "moonplasma:host/sys@0.1.0" "wall-time-field"
///|
fn wasmImportGetenv(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "getenv"
///|
fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "has-exe"
///|
fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "spawn"
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array8
#| local.get 0)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
#owned(bytes)
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int =
#|(func (param i32) (result i32) local.get 0)
+9
View File
@@ -0,0 +1,9 @@
warnings = "-44"
// ffi.mbt is generated and wasm-only; native builds use native_stub.mbt (scripts/gen-native-stubs.py).
options(
targets: {
"ffi.mbt": ["wasm", "wasm-gc"],
"native_stub.mbt": ["native"],
},
)
@@ -0,0 +1,156 @@
// Generated by scripts/gen-native-stubs.py. Native stand-ins for the wasm-only ffi.mbt.
///|
fn wasmImportUnixListen(p0 : Int, p1 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportUnixAccept(p0 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportUnixConnect(p0 : Int, p1 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportCloseFd(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportUnlink(p0 : Int, p1 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportPollRead(p0 : Int, p1 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportRecvmsg(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportSendmsg(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportMemfdCreate(p0 : Int, p1 : Int, p2 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportPwrite(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportMmapRead(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportReadFile(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportWriteFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportReadProc(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportMkdirP(p0 : Int, p1 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportListDesktopFiles(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportSleepMs(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportMonotonicMs() -> Int64 {
abort("wasm-only host import")
}
///|
fn wasmImportLog(p0 : Int, p1 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportGetpid() -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportWallTimeField(p0 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportGetenv(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn mbt_ffi_str2ptr(str : String) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_malloc(size : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] {
abort("wasm-only")
}
///|
fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String {
abort("wasm-only")
}
///|
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only")
}
@@ -0,0 +1,60 @@
// Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/interface/moonplasma/host/sys"
// Values
pub fn close_fd(Int32) -> Unit
pub fn getenv(String) -> String
pub fn getpid() -> Int32
pub fn has_exe(String) -> Bool
pub fn list_desktop_files(String) -> Array[String]
pub fn memfd_create(String, Int32) -> Int32
pub fn mkdir_p(String) -> Bool
pub fn mmap_read(Int32, Int32) -> FixedArray[Byte]
pub fn poll_read(Int32, Int32) -> Int32
pub fn pwrite(Int32, FixedArray[Byte], Int32) -> Int32
pub fn read_file(String) -> FixedArray[Byte]
pub fn read_proc(String) -> FixedArray[Byte]
pub fn recvmsg(Int32, UInt32) -> Received
pub fn sendmsg(Int32, FixedArray[Byte], Int32) -> Int32
pub fn sleep_ms(Int32) -> Unit
pub fn spawn(String, String) -> Bool
pub fn unix_accept(Int32) -> Int32
pub fn unix_connect(String) -> Int32
pub fn unix_listen(String) -> Int32
pub fn unlink(String) -> Unit
pub fn wall_time_field(Int32) -> Int32
pub fn write_file(String, FixedArray[Byte]) -> Int32
// Errors
// Types and methods
pub(all) struct Received {
count : Int32
fd : Int32
data : FixedArray[Byte]
}
// Type aliases
// Traits
+274
View File
@@ -0,0 +1,274 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
/// Result of `recvmsg`: byte count (-1 would-block, -2 error, 0 EOF), an fd received over
/// SCM_RIGHTS (-1 when none), and the bytes read.
pub(all) struct Received {
count : Int; fd : Int; data : FixedArray[Byte]
}
///|
/// Listen on a unix socket at `path`; -1 on failure.
pub fn unix_listen(path : String) -> Int {
let ptr = mbt_ffi_str2ptr(path)
let result : Int = wasmImportUnixListen(ptr, path.length());
let ret = result
mbt_ffi_free(ptr)
return ret
}
///|
/// Accept a pending client (non-blocking); -1 when none.
pub fn unix_accept(listen_fd : Int) -> Int {
let result : Int = wasmImportUnixAccept(listen_fd);
let ret = result
return ret
}
///|
pub fn unix_connect(path : String) -> Int {
let ptr = mbt_ffi_str2ptr(path)
let result : Int = wasmImportUnixConnect(ptr, path.length());
let ret = result
mbt_ffi_free(ptr)
return ret
}
///|
pub fn close_fd(fd : Int) -> Unit {
wasmImportCloseFd(fd);
}
///|
pub fn unlink(path : String) -> Unit {
let ptr = mbt_ffi_str2ptr(path)
wasmImportUnlink(ptr, path.length());
mbt_ffi_free(ptr)
}
///|
/// 1 when `fd` is readable within `timeout-ms`, 0 on timeout, <0 on error.
pub fn poll_read(fd : Int, timeout_ms : Int) -> Int {
let result : Int = wasmImportPollRead(fd, timeout_ms);
let ret = result
return ret
}
///|
pub fn recvmsg(fd : Int, max_len : UInt) -> Received {
let return_area = mbt_ffi_malloc(16)
wasmImportRecvmsg(fd, (max_len).reinterpret_as_int(), return_area);
let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12))
let ret = Received::{count : mbt_ffi_load32((return_area) + 0), fd : mbt_ffi_load32((return_area) + 4), data : result}
mbt_ffi_free(return_area)
return ret
}
///|
/// Send `data`, with `send-fd` (or -1) as SCM_RIGHTS; bytes sent or <0.
pub fn sendmsg(fd : Int, data : FixedArray[Byte], send_fd : Int) -> Int {
let ptr = mbt_ffi_bytes2ptr(data)
let result : Int = wasmImportSendmsg(fd, ptr, data.length(), send_fd);
let ret = result
mbt_ffi_free(ptr)
return ret
}
///|
pub fn memfd_create(name : String, size : Int) -> Int {
let ptr = mbt_ffi_str2ptr(name)
let result : Int = wasmImportMemfdCreate(ptr, name.length(), size);
let ret = result
mbt_ffi_free(ptr)
return ret
}
///|
pub fn pwrite(fd : Int, data : FixedArray[Byte], offset : Int) -> Int {
let ptr = mbt_ffi_bytes2ptr(data)
let result : Int = wasmImportPwrite(fd, ptr, data.length(), offset);
let ret = result
mbt_ffi_free(ptr)
return ret
}
///|
/// Copy `size` bytes of the file behind `fd` (mapped read-only by the host).
pub fn mmap_read(fd : Int, size : Int) -> FixedArray[Byte] {
let return_area = mbt_ffi_malloc(8)
wasmImportMmapRead(fd, size, return_area);
let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4))
let ret = result
mbt_ffi_free(return_area)
return ret
}
///|
pub fn read_file(path : String) -> FixedArray[Byte] {
let ptr = mbt_ffi_str2ptr(path)
let return_area = mbt_ffi_malloc(8)
wasmImportReadFile(ptr, path.length(), return_area);
let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4))
let ret = result
mbt_ffi_free(ptr)
mbt_ffi_free(return_area)
return ret
}
///|
pub fn write_file(path : String, data : FixedArray[Byte]) -> Int {
let ptr = mbt_ffi_str2ptr(path)
let ptr0 = mbt_ffi_bytes2ptr(data)
let result : Int = wasmImportWriteFile(ptr, path.length(), ptr0, data.length());
let ret = result
mbt_ffi_free(ptr)
mbt_ffi_free(ptr0)
return ret
}
///|
/// Contents of a small /proc or /sys file ("" when unreadable).
pub fn read_proc(path : String) -> FixedArray[Byte] {
let ptr = mbt_ffi_str2ptr(path)
let return_area = mbt_ffi_malloc(8)
wasmImportReadProc(ptr, path.length(), return_area);
let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4))
let ret = result
mbt_ffi_free(ptr)
mbt_ffi_free(return_area)
return ret
}
///|
pub fn mkdir_p(path : String) -> Bool {
let ptr = mbt_ffi_str2ptr(path)
let result : Int = wasmImportMkdirP(ptr, path.length());
let ret = (result != 0)
mbt_ffi_free(ptr)
return ret
}
///|
/// Names of the *.desktop files directly in `dir`.
pub fn list_desktop_files(dir : String) -> Array[String] {
let ptr = mbt_ffi_str2ptr(dir)
let return_area = mbt_ffi_malloc(8)
wasmImportListDesktopFiles(ptr, dir.length(), return_area);
let array : Array[String] = [];
for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 {
let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 8)
let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4))
array.push(result)
}
mbt_ffi_free(mbt_ffi_load32((return_area) + 0))
let ret = array
mbt_ffi_free(ptr)
mbt_ffi_free(return_area)
return ret
}
///|
pub fn sleep_ms(ms : Int) -> Unit {
wasmImportSleepMs(ms);
}
///|
/// Milliseconds on a monotonic clock (event timestamps).
pub fn monotonic_ms() -> UInt64 {
let result : Int64 = wasmImportMonotonicMs();
let ret = (result).reinterpret_as_uint64()
return ret
}
///|
/// Print a line to the host's stderr.
pub fn log(message : String) -> Unit {
let ptr = mbt_ffi_str2ptr(message)
wasmImportLog(ptr, message.length());
mbt_ffi_free(ptr)
}
///|
pub fn getpid() -> Int {
let result : Int = wasmImportGetpid();
let ret = result
return ret
}
///|
/// 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 {
let result : Int = wasmImportWallTimeField(which);
let ret = result
return ret
}
///|
pub fn getenv(name : String) -> String {
let ptr = mbt_ffi_str2ptr(name)
let return_area = mbt_ffi_malloc(8)
wasmImportGetenv(ptr, name.length(), return_area);
let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4))
let ret = result
mbt_ffi_free(ptr)
mbt_ffi_free(return_area)
return ret
}
///|
pub fn has_exe(name : String) -> Bool {
let ptr = mbt_ffi_str2ptr(name)
let result : Int = wasmImportHasExe(ptr, name.length());
let ret = (result != 0)
mbt_ffi_free(ptr)
return ret
}
///|
/// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`.
pub fn spawn(cmd : String, display : String) -> Bool {
let ptr = mbt_ffi_str2ptr(cmd)
let ptr0 = mbt_ffi_str2ptr(display)
let result : Int = wasmImportSpawn(ptr, cmd.length(), ptr0, display.length());
let ret = (result != 0)
mbt_ffi_free(ptr)
mbt_ffi_free(ptr0)
return ret
}
+13
View File
@@ -117,3 +117,16 @@ clean:
clean-all:
rm -rf _build build
# Build the compositor as a wasm component (build/components/compositor.wasm): imports only moonplasma:host/sys.
compositor-wasm:
scripts/build-compositor-wasm.sh
# Build the native host that runs the compositor component (wasmtime; implements the sys imports).
host-wasm:
cd host-wasm && cargo build --release
# Run the wasm compositor in a window on your current Wayland session. Connect clients via `just client`.
run-wasm: compositor-wasm host-wasm
rm -f {{socket}}
host-wasm/target/release/moon-plasma-host build/components/compositor.wasm --socket {{socket}} --theme {{theme}} --window
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Build the compositor itself as a wasm component: build/components/compositor.wasm.
# It imports only moonplasma:host/sys (wit/host/sys.wit) and exports `run`; the native host in
# host-wasm/ provides the imports. Needs moon and wasm-tools.
# scripts/build-compositor-wasm.sh
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"
export PATH="$ROOT/.tools/bin:$HOME/.moon/bin:$PATH"
for t in moon wasm-tools; do
command -v "$t" >/dev/null || { echo "error: $t not found" >&2; exit 1; }
done
moon build --target wasm --release components/compositor/gen 2>&1 | grep -E '^Error' -A8 || true
[ "${PIPESTATUS[0]}" -eq 0 ] || { echo "error: moon build failed" >&2; exit 1; }
core="_build/wasm/release/build/components/compositor/gen/gen.wasm"
[ -f "$core" ] || { echo "error: $core missing" >&2; exit 1; }
mkdir -p build/components
wasm-tools component embed wit/host "$core" --world compositor --encoding utf16 -o build/components/compositor.embed.wasm
wasm-tools component new build/components/compositor.embed.wasm -o build/components/compositor.wasm
rm -f build/components/compositor.embed.wasm
wasm-tools validate --features component-model build/components/compositor.wasm
printf 'compositor.wasm %s bytes imports=[%s]\n' "$(stat -c %s build/components/compositor.wasm)" \
"$(wasm-tools component wit build/components/compositor.wasm | sed -n 's/^ import \(.*\);/\1/p' | paste -sd, -)"
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""Write native_stub.mbt next to a wit-bindgen generated ffi.mbt.
The generated imports are wasm-only (`extern "wasm"` / wasm import functions), so a package that
imports them can't build for the native target. This emits abort() bodies with the same
signatures, and rewrites moon.pkg to map ffi.mbt to wasm and native_stub.mbt to native.
scripts/gen-native-stubs.py interface/moonplasma/host/sys
"""
import re, sys, pathlib
d = pathlib.Path(sys.argv[1])
src = (d / "ffi.mbt").read_text()
out = ["// Generated by scripts/gen-native-stubs.py. Native stand-ins for the wasm-only ffi.mbt.", ""]
# import functions: fn wasmImportX(p0 : Int, ...) -> Int = "mod" "name"
for m in re.finditer(r'^fn (\w+)\(([^)]*)\)\s*(->\s*[\w\[\]]+)?\s*=\s*"[^"]*"\s*"[^"]*"\s*$', src, re.M):
name, params, ret = m.group(1), m.group(2), (m.group(3) or "-> Unit").strip()
out += ["///|", f"fn {name}({params}) {ret} {{", ' abort("wasm-only host import")', "}", ""]
# inline-wasm helpers: extern "wasm" fn mbt_ffi_x(params) -> T =
for m in re.finditer(r'^extern "wasm" fn (\w+)\(([^)]*)\)\s*(->\s*[^=\n]+?)?\s*=\s*$', src, re.M):
name, params, ret = m.group(1), m.group(2), (m.group(3) or "-> Unit").strip()
out += ["///|", f"fn {name}({params}) {ret} {{", ' abort("wasm-only")', "}", ""]
(d / "native_stub.mbt").write_text("\n".join(out))
# wit-bindgen rewrites moon.pkg on every run, so restore the per-file targets here.
(d / "moon.pkg").write_text("""warnings = "-44"
// ffi.mbt is generated and wasm-only; native builds use native_stub.mbt (scripts/gen-native-stubs.py).
options(
targets: {
"ffi.mbt": ["wasm", "wasm-gc"],
"native_stub.mbt": ["native"],
},
)
""")
print("wrote", d / "native_stub.mbt", "(%d stubs)" % sum(1 for l in out if l.startswith("fn ")))
+60
View File
@@ -0,0 +1,60 @@
package moonplasma:host@0.1.0;
/// The operating-system surface the compositor component needs, nothing more. The native host
/// implements it with real syscalls; the component holds only integer handles (fds) and bytes.
/// Mirrors compositor/sys.
interface sys {
/// Listen on a unix socket at `path`; -1 on failure.
unix-listen: func(path: string) -> s32;
/// Accept a pending client (non-blocking); -1 when none.
unix-accept: func(listen-fd: s32) -> s32;
unix-connect: func(path: string) -> s32;
close-fd: func(fd: s32);
unlink: func(path: string);
/// 1 when `fd` is readable within `timeout-ms`, 0 on timeout, <0 on error.
poll-read: func(fd: s32, timeout-ms: s32) -> s32;
/// Result of `recvmsg`: byte count (-1 would-block, -2 error, 0 EOF), an fd received over
/// SCM_RIGHTS (-1 when none), and the bytes read.
record received {
count: s32,
fd: s32,
data: list<u8>,
}
recvmsg: func(fd: s32, max-len: u32) -> received;
/// Send `data`, with `send-fd` (or -1) as SCM_RIGHTS; bytes sent or <0.
sendmsg: func(fd: s32, data: list<u8>, send-fd: s32) -> s32;
memfd-create: func(name: string, size: s32) -> s32;
pwrite: func(fd: s32, data: list<u8>, offset: s32) -> s32;
/// Copy `size` bytes of the file behind `fd` (mapped read-only by the host).
mmap-read: func(fd: s32, size: s32) -> list<u8>;
read-file: func(path: string) -> list<u8>;
write-file: func(path: string, data: list<u8>) -> s32;
/// Contents of a small /proc or /sys file ("" when unreadable).
read-proc: func(path: string) -> list<u8>;
mkdir-p: func(path: string) -> bool;
/// Names of the *.desktop files directly in `dir`.
list-desktop-files: func(dir: string) -> list<string>;
sleep-ms: func(ms: s32);
/// Milliseconds on a monotonic clock (event timestamps).
monotonic-ms: func() -> u64;
/// Print a line to the host's stderr.
log: func(message: string);
getpid: func() -> s32;
/// 0 year, 1 month (1-12), 2 day, 3 hour, 4 minute, 5 second, 6 weekday (0 = Sunday).
wall-time-field: func(which: s32) -> s32;
getenv: func(name: string) -> string;
has-exe: func(name: string) -> bool;
/// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`.
spawn: func(cmd: string, display: string) -> bool;
}
/// The compositor as one component: it imports the OS surface and exports its entry point.
world compositor {
import sys;
/// Run the compositor until it exits. `args` are the command-line arguments (without argv[0]).
export run: func(args: list<string>) -> s32;
}
+1
View File
@@ -0,0 +1 @@
The compositor as one component: it imports the OS surface and exports its entry point.
+2
View File
@@ -0,0 +1,2 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
+2
View File
@@ -0,0 +1,2 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
+1
View File
@@ -0,0 +1 @@
warnings = "-44"