From c03d4c6c17a3862039094446ec6ca05b9f76c91c Mon Sep 17 00:00:00 2001 From: nandithebull Date: Wed, 25 Nov 2026 02:38:19 -0800 Subject: [PATCH] The wasm compositor as a login session: DRM/KMS + libinput through the host New moonplasma:host/display import (open, poll, present, cursor, input events, close). The wasmtime host implements it by compiling the compositor's own kms shim (libseat + DRM/KMS + libinput + xkbcommon) via build.rs (feature drm, default on), so the native and wasm backends share one implementation. compositor/kms gets a wasm backend with the same API, and the shared app loop gains --drm. - session: install.py installs the host, compositor.wasm, fonts, config, wit and modules and the display-manager entry (--native keeps the old native session); the launcher starts the host when installed. just run-drm / install-session use the wasm compositor; *-native keep the old. - compositor.wasm moves to build/ (out of build/components, where the module catalog scans). Verified: component builds with the new import, host instantiates it and renders frames, installed layout (fonts/modules/theme from the share dir) renders correctly in a sandbox, native build and tests unchanged. NOT exercised on a real login VT. Co-Authored-By: Claude Sonnet 5.5 --- .../compositor/gen/world/compositor/ffi.mbt | 14 +- compositor/app/app.mbt | 55 +++++++- compositor/app/moon.pkg | 1 + compositor/kms/{kms.mbt => kms_native.mbt} | 0 compositor/kms/kms_wasm.mbt | 66 +++++++++ compositor/kms/moon.pkg | 7 +- host-wasm/Cargo.lock | 1 + host-wasm/Cargo.toml | 9 ++ host-wasm/README.md | 18 ++- host-wasm/build.rs | 18 +++ host-wasm/csrc/fake/moonbit.h | 9 ++ host-wasm/csrc/kms.c | 19 +++ host-wasm/src/kms.rs | 92 ++++++++++++ host-wasm/src/main.rs | 57 +++++++- interface/moonplasma/host/display/ffi.mbt | 58 ++++++++ interface/moonplasma/host/display/moon.pkg | 9 ++ .../moonplasma/host/display/native_stub.mbt | 71 ++++++++++ .../host/display/pkg.generated.mbti | 54 ++++++++ interface/moonplasma/host/display/top.mbt | 131 ++++++++++++++++++ interface/moonplasma/host/font/ffi.mbt | 8 +- .../moonplasma/host/font/native_stub.mbt | 10 +- interface/moonplasma/host/plasmoids/ffi.mbt | 38 ++--- .../moonplasma/host/plasmoids/native_stub.mbt | 30 ++-- interface/moonplasma/host/sys/ffi.mbt | 38 ++--- interface/moonplasma/host/sys/native_stub.mbt | 32 ++--- justfile | 21 ++- scripts/build-compositor-wasm.sh | 16 +-- session/install.py | 44 ++++-- session/moon-plasma-session | 16 ++- session/moon-plasma.desktop | 2 +- wit/host/display.wit | 41 ++++++ wit/host/sys.wit | 1 + 32 files changed, 862 insertions(+), 124 deletions(-) rename compositor/kms/{kms.mbt => kms_native.mbt} (100%) create mode 100644 compositor/kms/kms_wasm.mbt create mode 100644 host-wasm/build.rs create mode 100644 host-wasm/csrc/fake/moonbit.h create mode 100644 host-wasm/csrc/kms.c create mode 100644 host-wasm/src/kms.rs create mode 100644 interface/moonplasma/host/display/ffi.mbt create mode 100644 interface/moonplasma/host/display/moon.pkg create mode 100644 interface/moonplasma/host/display/native_stub.mbt create mode 100644 interface/moonplasma/host/display/pkg.generated.mbti create mode 100644 interface/moonplasma/host/display/top.mbt create mode 100644 wit/host/display.wit diff --git a/components/compositor/gen/world/compositor/ffi.mbt b/components/compositor/gen/world/compositor/ffi.mbt index 77e1b5b..955dffa 100644 --- a/components/compositor/gen/world/compositor/ffi.mbt +++ b/components/compositor/gen/world/compositor/ffi.mbt @@ -20,13 +20,6 @@ pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int { } -///| -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) - ///| extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load) @@ -35,3 +28,10 @@ extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = extern "wasm" fn mbt_ffi_free(position : Int) = #|(func (param i32) local.get 0 call $moonbit.decref) +///| +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) + diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index 3be0e60..ae79f71 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -2,7 +2,8 @@ /// 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 +/// Arguments: --socket PATH --theme PATH --window --drm --gfx-out PNG --serve --size WxH +/// --drm runs as a login session: the host takes the display (DRM/KMS) and input (libinput). /// 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). @@ -46,6 +47,7 @@ pub fn run(args : Array[String]) -> Int { let mut gfx_out = "" let mut windowed = false let mut serve = false + let mut drm = false let mut width = 1280 let mut height = 720 @@ -61,6 +63,9 @@ pub fn run(args : Array[String]) -> Int { } else if a == "--window" { windowed = true i = i + 1 + } else if a == "--drm" { + drm = true + i = i + 1 } else if a == "--serve" { serve = true i = i + 1 @@ -95,11 +100,32 @@ pub fn run(args : Array[String]) -> Int { @scene.ThemeTokens::moon_night() } + // Login-session mode: take over the display and input, and size the desktop to the monitor. + let kms = if drm { + match @kms.Kms::open() { + Some(k) => { + width = k.width + height = k.height + Some(k) + } + None => { + @sys.log("failed to start the DRM backend (run from a login VT, not inside another session)") + return 1 + } + } + } else { + None + } + 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 => { + match kms { + Some(k) => k.close() + None => () + } @sys.log("failed to bind Wayland socket at " + socket_path) 1 } @@ -133,10 +159,33 @@ pub fn run(args : Array[String]) -> Int { } else { None } + match kms { + Some(k) => comp.server.set_keymap(k.keymap) + None => () + } @sys.log("moon-plasma compositor listening on " + socket_path) let mut frames = 0 while true { frames = frames + 1 + match kms { + Some(k) => { + if !k.poll() { + break + } + let now_ms = @sys.monotonic_ms().to_uint() + for ev in k.take_input() { + comp.handle_input(ev, now_ms) + } + comp.step() + k.set_cursor_shape(comp.desired_cursor()) + if k.frame_ready() { + k.present(comp.present_to_gfx(gfx_ctx)) + } + @sys.sleep_ms(8) + continue + } + None => () + } comp.step() match nested { Some(n) => { @@ -165,6 +214,10 @@ pub fn run(args : Array[String]) -> Int { } @sys.sleep_ms(16) } + match kms { + Some(k) => k.close() + None => () + } comp.close() 0 } diff --git a/compositor/app/moon.pkg b/compositor/app/moon.pkg index 7ba09f1..488579d 100644 --- a/compositor/app/moon.pkg +++ b/compositor/app/moon.pkg @@ -6,6 +6,7 @@ import { "moonplasma/desktop/compositor/gfx" @gfx, "moonplasma/desktop/compositor/host" @host, "moonplasma/desktop/compositor/nested" @nested, + "moonplasma/desktop/compositor/kms" @kms, } supported_targets = "+native+wasm" diff --git a/compositor/kms/kms.mbt b/compositor/kms/kms_native.mbt similarity index 100% rename from compositor/kms/kms.mbt rename to compositor/kms/kms_native.mbt diff --git a/compositor/kms/kms_wasm.mbt b/compositor/kms/kms_wasm.mbt new file mode 100644 index 0000000..f38f69b --- /dev/null +++ b/compositor/kms/kms_wasm.mbt @@ -0,0 +1,66 @@ +///| Wasm display backend: the same API as kms_native.mbt, but the host owns the display and the +/// seat (`moonplasma:host/display`). The component sends frames out and reads events in. + +///| +pub(all) struct Kms { + width : Int + height : Int + keymap : Bytes +} + +///| Take over the first connected output and the seat's input. None when this is not an active +/// login VT (the host prints why). +pub fn Kms::open() -> Kms? { + match @hostdisplay.open() { + None => None + Some(o) => + Some({ + width: o.width.reinterpret_as_int(), + height: o.height.reinterpret_as_int(), + keymap: Bytes::from_fixedarray(o.keymap), + }) + } +} + +///| Service the seat, DRM and input fds. False once Ctrl+Alt+Backspace was pressed. +pub fn Kms::poll(_self : Kms) -> Bool { + @hostdisplay.poll() +} + +///| True when a new frame can be presented (seat active, no page flip in flight). +pub fn Kms::frame_ready(_self : Kms) -> Bool { + @hostdisplay.frame_ready() +} + +///| Present a composed frame (its size must match the output mode). +pub fn Kms::present(_self : Kms, pixmap : @renderer.Pixmap) -> Unit { + @hostdisplay.present( + pixmap.data, + pixmap.width.reinterpret_as_uint(), + pixmap.height.reinterpret_as_uint(), + ) +} + +///| Show the cursor for a wp_cursor_shape_v1 value. +pub fn Kms::set_cursor_shape(_self : Kms, shape : UInt) -> Unit { + @hostdisplay.set_cursor_shape(shape) +} + +///| Input queued since the last call, in the compositor's event type. +pub fn Kms::take_input(_self : Kms) -> Array[@nested.InputEvent] { + let out : Array[@nested.InputEvent] = [] + for ev in @hostdisplay.take_input() { + match ev { + PointerMove(p) => out.push(PointerMove(p.x, p.y)) + PointerButton(k) => out.push(PointerButton(k.code, k.pressed)) + Key(k) => out.push(Key(k.code, k.pressed)) + Modifiers(m) => out.push(Modifiers(m.depressed, m.latched, m.locked, m.group)) + } + } + out +} + +///| Restore the previous video mode and release the seat. +pub fn Kms::close(_self : Kms) -> Unit { + @hostdisplay.close() +} diff --git a/compositor/kms/moon.pkg b/compositor/kms/moon.pkg index f839e9e..115ca1c 100644 --- a/compositor/kms/moon.pkg +++ b/compositor/kms/moon.pkg @@ -2,11 +2,16 @@ import { "moonbitlang/core/builtin", "moonplasma/desktop/compositor/renderer" @renderer, "moonplasma/desktop/compositor/nested" @nested, + "moonplasma/desktop/interface/moonplasma/host/display" @hostdisplay, } -supported_targets = "-all+native" +supported_targets = "+native+wasm" options( + targets: { + "kms_native.mbt": ["native"], + "kms_wasm.mbt": ["wasm"], + }, "native-stub": [ "kms_stub.c" ], link: { "native": { diff --git a/host-wasm/Cargo.lock b/host-wasm/Cargo.lock index 53f447f..d1675cc 100644 --- a/host-wasm/Cargo.lock +++ b/host-wasm/Cargo.lock @@ -570,6 +570,7 @@ version = "0.1.0" dependencies = [ "ab_glyph", "ab_glyph_rasterizer", + "cc", "libc", "wasmtime", ] diff --git a/host-wasm/Cargo.toml b/host-wasm/Cargo.toml index d64ffa6..9ab0ffa 100644 --- a/host-wasm/Cargo.toml +++ b/host-wasm/Cargo.toml @@ -4,6 +4,15 @@ 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)." +[features] +# Login-session display backend (DRM/KMS + libinput + libseat + xkbcommon). Needs those libraries' +# development files; build with --no-default-features to leave it out (--drm then reports it). +default = ["drm"] +drm = ["dep:cc"] + +[build-dependencies] +cc = { version = "1", optional = true } + [dependencies] ab_glyph = "0.2" ab_glyph_rasterizer = "0.1" diff --git a/host-wasm/README.md b/host-wasm/README.md index 3afbcd1..6253fb2 100644 --- a/host-wasm/README.md +++ b/host-wasm/README.md @@ -3,7 +3,7 @@ Runs the compositor **as a WebAssembly component**. ``` -just compositor-wasm # build/components/compositor.wasm (the compositor, a component) +just compositor-wasm # build/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 ``` @@ -17,9 +17,9 @@ file descriptor lives in this host, which implements `sys` with libc (sockets an `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 +moon-plasma-host build/compositor.wasm --socket PATH [--theme PATH] [--window] +moon-plasma-host build/compositor.wasm --socket PATH --gfx-out frame.png # one frame +moon-plasma-host build/compositor.wasm --socket PATH --gfx-out frame.png --serve # keep refreshing it ``` ## Status @@ -36,8 +36,14 @@ instantiates each module as a real component against one world, `plasmoid-host` ([`wit/worlds.wit`](../wit/worlds.wit)); a module imports the subset of host interfaces it needs and each is served here. `cargo test --release` loads the built modules (`just modules` first). -Not yet in the component (the native compositor still has these): -- **DRM/KMS and libinput** (`--drm`), the login-session backend. +**Login session** (`--drm`): the host takes the display and input through the seat +(`moonplasma:host/display`, [`wit/host/display.wit`](../wit/host/display.wit)): DRM/KMS output with page +flips and a hardware cursor, libinput keyboard and pointer, an xkb keymap, libseat for device access and +VT switching. It is the compositor's own C shim (`compositor/kms/kms_stub.c`) compiled into this host +by `build.rs` (feature `drm`, on by default; `--no-default-features` leaves it out), so the native and +wasm backends can't drift. Run `just run-drm` from a login VT, or `just install-session` to add Moon +Plasma to your display manager (`session/install.py`; `--native` installs the native compositor instead). +Not yet exercised on a real VT; it is only built and instantiated. Regenerating the host bindings (into a temp dir, then copy `interface/moonplasma/host`, `world/compositor` and `components/compositor/gen/{ffi.mbt,world}`; regenerating in place would diff --git a/host-wasm/build.rs b/host-wasm/build.rs new file mode 100644 index 0000000..33ab998 --- /dev/null +++ b/host-wasm/build.rs @@ -0,0 +1,18 @@ +// The login-session display backend (feature `drm`, on by default) compiles the compositor's own +// C shim for DRM/KMS + libinput + libseat + xkbcommon and links the libraries it uses. +fn main() { + #[cfg(feature = "drm")] + { + cc::Build::new() + .file("csrc/kms.c") + .include("csrc/fake") + .include("/usr/include/libdrm") + .warnings(false) + .compile("kms"); + for lib in ["drm", "input", "seat", "xkbcommon", "udev"] { + println!("cargo:rustc-link-lib={lib}"); + } + println!("cargo:rerun-if-changed=csrc/kms.c"); + println!("cargo:rerun-if-changed=../compositor/kms/kms_stub.c"); + } +} diff --git a/host-wasm/csrc/fake/moonbit.h b/host-wasm/csrc/fake/moonbit.h new file mode 100644 index 0000000..eb55086 --- /dev/null +++ b/host-wasm/csrc/fake/moonbit.h @@ -0,0 +1,9 @@ +/* Just enough of moonbit.h for compositor/kms/kms_stub.c to build outside the MoonBit runtime. + * The shim uses MoonBit only for the export macro and the length of byte arrays it is handed; + * csrc/kms.c supplies the length through kms_bytes_len. */ +#pragma once +#include +#define MOONBIT_FFI_EXPORT +typedef uint8_t *moonbit_bytes_t; +extern int32_t kms_bytes_len; +#define Moonbit_array_length(p) (kms_bytes_len) diff --git a/host-wasm/csrc/kms.c b/host-wasm/csrc/kms.c new file mode 100644 index 0000000..4e3320b --- /dev/null +++ b/host-wasm/csrc/kms.c @@ -0,0 +1,19 @@ +/* The login-session display backend for the wasm host: the same C file the native compositor uses + * (libseat + DRM/KMS dumb buffers + libinput + xkbcommon), compiled here against a stand-in + * moonbit.h, so the two backends can't drift. The mp_kms_* functions are called from Rust. */ +#include + +int32_t kms_bytes_len; + +#include "../../compositor/kms/kms_stub.c" + +/* The two shim functions that take a MoonBit byte array need its length. */ +int32_t hw_kms_present(uint8_t *pixels, int32_t w, int32_t h) { + kms_bytes_len = w * h * 4; + return mp_kms_present(pixels, w, h); +} + +int32_t hw_kms_keymap_copy(uint8_t *out, int32_t cap) { + kms_bytes_len = cap; + return mp_kms_keymap_copy(out); +} diff --git a/host-wasm/src/kms.rs b/host-wasm/src/kms.rs new file mode 100644 index 0000000..4aaa577 --- /dev/null +++ b/host-wasm/src/kms.rs @@ -0,0 +1,92 @@ +//! The login-session display backend: calls into compositor/kms/kms_stub.c (built by build.rs), +//! the same shim the native compositor uses. One display, one seat, global state. + +use crate::moonplasma::host::display::{KeyState, Modifiers, Output, PointerPos, SeatEvent}; + +extern "C" { + fn mp_kms_open() -> i32; + fn mp_kms_width() -> i32; + fn mp_kms_height() -> i32; + fn mp_kms_quit_requested() -> i32; + fn mp_kms_poll() -> i32; + fn mp_kms_frame_ready() -> i32; + fn mp_kms_set_cursor_shape(shape: i32); + fn mp_kms_next_event() -> i32; + fn mp_kms_arg(i: i32) -> i32; + fn mp_kms_keymap_len() -> i32; + fn mp_kms_close(); + fn hw_kms_present(pixels: *mut u8, w: i32, h: i32) -> i32; + fn hw_kms_keymap_copy(out: *mut u8, cap: i32) -> i32; +} + +/// Open the seat, the first connected output and libinput. None (the shim has said why on stderr) +/// when this is not an active login VT. +pub fn open() -> Option { + unsafe { + if mp_kms_open() != 0 { + mp_kms_close(); + return None; + } + let n = mp_kms_keymap_len(); + let mut keymap = vec![0u8; n.max(0) as usize]; + let got = if n > 0 { hw_kms_keymap_copy(keymap.as_mut_ptr(), n) } else { 0 }; + keymap.truncate(got.max(0) as usize); + Some(Output { width: mp_kms_width() as u32, height: mp_kms_height() as u32, keymap }) + } +} + +/// Service the seat, DRM and input fds. False once Ctrl+Alt+Backspace was pressed. +pub fn poll() -> bool { + unsafe { + mp_kms_poll(); + mp_kms_quit_requested() == 0 + } +} + +pub fn frame_ready() -> bool { + unsafe { mp_kms_frame_ready() != 0 } +} + +/// Present an RGBA8888 frame; ignored if the buffer is smaller than the stated size. +pub fn present(pixels: &[u8], width: u32, height: u32) { + if pixels.len() < (width as usize) * (height as usize) * 4 { + return; + } + // The shim only reads the pixels; it takes a non-const pointer for the MoonBit byte type. + unsafe { hw_kms_present(pixels.as_ptr() as *mut u8, width as i32, height as i32) }; +} + +pub fn set_cursor_shape(shape: u32) { + unsafe { mp_kms_set_cursor_shape(shape as i32) }; +} + +/// Input queued since the last call. +pub fn take_input() -> Vec { + let mut out = Vec::new(); + unsafe { + loop { + let t = mp_kms_next_event(); + if t == 0 { + break; + } + let (a, b) = (mp_kms_arg(1), mp_kms_arg(2)); + match t { + 1 => out.push(SeatEvent::PointerMove(PointerPos { x: a as f64, y: b as f64 })), + 2 => out.push(SeatEvent::PointerButton(KeyState { code: a as u32, pressed: b != 0 })), + 3 => out.push(SeatEvent::Key(KeyState { code: a as u32, pressed: b != 0 })), + 4 => out.push(SeatEvent::Modifiers(Modifiers { + depressed: a as u32, + latched: b as u32, + locked: mp_kms_arg(3) as u32, + group: mp_kms_arg(4) as u32, + })), + _ => {} + } + } + } + out +} + +pub fn close() { + unsafe { mp_kms_close() }; +} diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index f2dd3d0..b8f192b 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -1,12 +1,12 @@ //! Native host for the moon-plasma compositor component. //! -//! The compositor is a wasm component (build/components/compositor.wasm) that imports exactly one +//! The compositor is a wasm component (build/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 +//! moon-plasma-host build/compositor.wasm --socket /run/user/1000/wayland-moon-0 --window use std::ffi::CString; use std::io::Read; @@ -16,6 +16,8 @@ use wasmtime::component::{Component, HasSelf, Linker}; use wasmtime::{Config, Engine, Result, Store}; mod plasmoid; +#[cfg(feature = "drm")] +mod kms; wasmtime::component::bindgen!({ path: "../wit/host", @@ -227,6 +229,54 @@ impl moonplasma::host::plasmoids::Host for State { } } +impl moonplasma::host::display::Host for State { + fn open(&mut self) -> Option { + #[cfg(feature = "drm")] + { + kms::open() + } + #[cfg(not(feature = "drm"))] + { + eprintln!("this host was built without the `drm` feature (no login-session backend)"); + None + } + } + fn poll(&mut self) -> bool { + #[cfg(feature = "drm")] + return kms::poll(); + #[cfg(not(feature = "drm"))] + false + } + fn frame_ready(&mut self) -> bool { + #[cfg(feature = "drm")] + return kms::frame_ready(); + #[cfg(not(feature = "drm"))] + false + } + fn present(&mut self, pixels: Vec, width: u32, height: u32) { + #[cfg(feature = "drm")] + kms::present(&pixels, width, height); + #[cfg(not(feature = "drm"))] + let _ = (pixels, width, height); + } + fn set_cursor_shape(&mut self, shape: u32) { + #[cfg(feature = "drm")] + kms::set_cursor_shape(shape); + #[cfg(not(feature = "drm"))] + let _ = shape; + } + fn take_input(&mut self) -> Vec { + #[cfg(feature = "drm")] + return kms::take_input(); + #[cfg(not(feature = "drm"))] + Vec::new() + } + fn close(&mut self) { + #[cfg(feature = "drm")] + kms::close(); + } +} + impl moonplasma::host::font::Host for State { fn load(&mut self, slot: u32, path: String) -> bool { if slot as usize >= self.fonts.len() { @@ -592,7 +642,7 @@ fn main() -> Result<()> { 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() + "build/compositor.wasm".to_string() }; if args.first().map(|a| a == "--").unwrap_or(false) { args.remove(0); @@ -614,6 +664,7 @@ fn main() -> Result<()> { let mut linker: Linker = Linker::new(&engine); moonplasma::host::sys::add_to_linker::>(&mut linker, |s| s)?; moonplasma::host::font::add_to_linker::>(&mut linker, |s| s)?; + moonplasma::host::display::add_to_linker::>(&mut linker, |s| s)?; moonplasma::host::plasmoids::add_to_linker::>(&mut linker, |s| s)?; let mut store = Store::new(&engine, State::default()); store.data_mut().pl = Some(plasmoid::Runtime::new(&engine)?); diff --git a/interface/moonplasma/host/display/ffi.mbt b/interface/moonplasma/host/display/ffi.mbt new file mode 100644 index 0000000..62f0bf6 --- /dev/null +++ b/interface/moonplasma/host/display/ffi.mbt @@ -0,0 +1,58 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +fn wasmImportOpen(p0 : Int) = "moonplasma:host/display@0.1.0" "open" + +///| +fn wasmImportPoll() -> Int = "moonplasma:host/display@0.1.0" "poll" + +///| +fn wasmImportFrameReady() -> Int = "moonplasma:host/display@0.1.0" "frame-ready" + +///| +fn wasmImportPresent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) = "moonplasma:host/display@0.1.0" "present" + +///| +fn wasmImportSetCursorShape(p0 : Int) = "moonplasma:host/display@0.1.0" "set-cursor-shape" + +///| +fn wasmImportTakeInput(p0 : Int) = "moonplasma:host/display@0.1.0" "take-input" + +///| +fn wasmImportClose() = "moonplasma:host/display@0.1.0" "close" + +///| +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) + +///| +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_loadf64(offset : Int) -> Double = +#|(func (param i32) (result f64) local.get 0 f64.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) + +///| +#owned(bytes) +extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> 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) + diff --git a/interface/moonplasma/host/display/moon.pkg b/interface/moonplasma/host/display/moon.pkg new file mode 100644 index 0000000..615617d --- /dev/null +++ b/interface/moonplasma/host/display/moon.pkg @@ -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"], + }, +) diff --git a/interface/moonplasma/host/display/native_stub.mbt b/interface/moonplasma/host/display/native_stub.mbt new file mode 100644 index 0000000..c2a3eaf --- /dev/null +++ b/interface/moonplasma/host/display/native_stub.mbt @@ -0,0 +1,71 @@ +// Generated by scripts/gen-native-stubs.py. Native stand-ins for the wasm-only ffi.mbt. + +///| +fn wasmImportOpen(p0 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportPoll() -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportFrameReady() -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportPresent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportSetCursorShape(p0 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportTakeInput(p0 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportClose() -> Unit { + abort("wasm-only host import") +} + +///| +fn mbt_ffi_load8_u(offset : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { + abort("wasm-only") +} + +///| +fn mbt_ffi_loadf64(offset : Int) -> Double { + 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_bytes2ptr(bytes : FixedArray[Byte]) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_load32(offset : Int) -> Int { + abort("wasm-only") +} diff --git a/interface/moonplasma/host/display/pkg.generated.mbti b/interface/moonplasma/host/display/pkg.generated.mbti new file mode 100644 index 0000000..0740df7 --- /dev/null +++ b/interface/moonplasma/host/display/pkg.generated.mbti @@ -0,0 +1,54 @@ +// Generated using `moon info`, DON'T EDIT IT +package "moonplasma/desktop/interface/moonplasma/host/display" + +// Values +pub fn close() -> Unit + +pub fn frame_ready() -> Bool + +pub fn open() -> Output? + +pub fn poll() -> Bool + +pub fn present(FixedArray[Byte], UInt32, UInt32) -> Unit + +pub fn set_cursor_shape(UInt32) -> Unit + +pub fn take_input() -> Array[SeatEvent] + +// Errors + +// Types and methods +pub(all) struct KeyState { + code : UInt32 + pressed : Bool +} + +pub(all) struct Modifiers { + depressed : UInt32 + latched : UInt32 + locked : UInt32 + group : UInt32 +} + +pub(all) struct Output { + width : UInt32 + height : UInt32 + keymap : FixedArray[Byte] +} + +pub(all) struct PointerPos { + x : Double + y : Double +} + +pub(all) enum SeatEvent { + PointerMove(PointerPos) + PointerButton(KeyState) + Key(KeyState) + Modifiers(Modifiers) +} + +// Type aliases + +// Traits diff --git a/interface/moonplasma/host/display/top.mbt b/interface/moonplasma/host/display/top.mbt new file mode 100644 index 0000000..a7840bc --- /dev/null +++ b/interface/moonplasma/host/display/top.mbt @@ -0,0 +1,131 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +pub(all) struct Output { + width : UInt; height : UInt; keymap : FixedArray[Byte] +} +///| +pub(all) struct PointerPos { + x : Double; y : Double +} +///| +/// A button or key as an evdev code, pressed or released. +pub(all) struct KeyState { + code : UInt; pressed : Bool +} +///| +pub(all) struct Modifiers { + depressed : UInt; latched : UInt; locked : UInt; group : UInt +} +///| +pub(all) enum SeatEvent { + PointerMove(PointerPos) + PointerButton(KeyState) + Key(KeyState) + Modifiers(Modifiers) +} +///| +/// Take over the first connected output and the seat's input. None, with the reason on the +/// host's stderr, when this is not an active login VT. +pub fn open() -> Output? { + + let return_area = mbt_ffi_malloc(20) + wasmImportOpen(return_area); + + let lifted : Output? = match mbt_ffi_load8_u((return_area) + 0) { + 0 => Option::None + 1 => { + + let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 12), mbt_ffi_load32((return_area) + 16)) + + Option::Some(Output::{width : (mbt_ffi_load32((return_area) + 4)).reinterpret_as_uint(), height : (mbt_ffi_load32((return_area) + 8)).reinterpret_as_uint(), keymap : result}) + } + _ => panic() + } + let ret = lifted + mbt_ffi_free(return_area) + return ret + +} +///| +/// Service the seat, DRM and input fds without blocking. False once the user asked to quit +/// (Ctrl+Alt+Backspace). +pub fn poll() -> Bool { + + let result : Int = wasmImportPoll(); + let ret = (result != 0) + return ret + +} +///| +/// True when a new frame can be presented (seat active, no page flip in flight). +pub fn frame_ready() -> Bool { + + let result : Int = wasmImportFrameReady(); + let ret = (result != 0) + return ret + +} +///| +/// Show an RGBA8888 frame of `width` x `height` (it must match the output mode). +pub fn present(pixels : FixedArray[Byte], width : UInt, height : UInt) -> Unit { + + let ptr = mbt_ffi_bytes2ptr(pixels) + + wasmImportPresent(ptr, pixels.length(), (width).reinterpret_as_int(), (height).reinterpret_as_int()); + mbt_ffi_free(ptr) + +} +///| +/// Show the cursor for a wp_cursor_shape_v1 value. +pub fn set_cursor_shape(shape : UInt) -> Unit { + + wasmImportSetCursorShape((shape).reinterpret_as_int()); + +} +///| +/// Input queued since the last call. +pub fn take_input() -> Array[SeatEvent] { + + let return_area = mbt_ffi_malloc(8) + wasmImportTakeInput(return_area); + + let array : Array[SeatEvent] = []; + for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 { + let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 24) + + let lifted = match (mbt_ffi_load8_u((iter_base) + 0)) { + 0 => { + + SeatEvent::PointerMove(PointerPos::{x : mbt_ffi_loadf64((iter_base) + 8), y : mbt_ffi_loadf64((iter_base) + 16)}) + } + 1 => { + + SeatEvent::PointerButton(KeyState::{code : (mbt_ffi_load32((iter_base) + 8)).reinterpret_as_uint(), pressed : (mbt_ffi_load8_u((iter_base) + 12) != 0)}) + } + 2 => { + + SeatEvent::Key(KeyState::{code : (mbt_ffi_load32((iter_base) + 8)).reinterpret_as_uint(), pressed : (mbt_ffi_load8_u((iter_base) + 12) != 0)}) + } + 3 => { + + SeatEvent::Modifiers(Modifiers::{depressed : (mbt_ffi_load32((iter_base) + 8)).reinterpret_as_uint(), latched : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), locked : (mbt_ffi_load32((iter_base) + 16)).reinterpret_as_uint(), group : (mbt_ffi_load32((iter_base) + 20)).reinterpret_as_uint()}) + } + _ => panic() + } + + array.push(lifted) + } + mbt_ffi_free(mbt_ffi_load32((return_area) + 0)) + let ret = array + mbt_ffi_free(return_area) + return ret + +} +///| +/// Restore the previous video mode and release the seat. +pub fn close() -> Unit { + + wasmImportClose(); + +} + diff --git a/interface/moonplasma/host/font/ffi.mbt b/interface/moonplasma/host/font/ffi.mbt index f6ec82a..3a49083 100644 --- a/interface/moonplasma/host/font/ffi.mbt +++ b/interface/moonplasma/host/font/ffi.mbt @@ -13,6 +13,10 @@ extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = #| local.get 1 call $moonbit.init_array8 #| 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) @@ -29,7 +33,3 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = 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) - diff --git a/interface/moonplasma/host/font/native_stub.mbt b/interface/moonplasma/host/font/native_stub.mbt index 82bc2aa..903424e 100644 --- a/interface/moonplasma/host/font/native_stub.mbt +++ b/interface/moonplasma/host/font/native_stub.mbt @@ -15,6 +15,11 @@ fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { abort("wasm-only") } +///| +fn mbt_ffi_load32(offset : Int) -> Int { + abort("wasm-only") +} + ///| fn mbt_ffi_free(position : Int) -> Unit { abort("wasm-only") @@ -29,8 +34,3 @@ fn mbt_ffi_malloc(size : Int) -> Int { fn mbt_ffi_str2ptr(str : String) -> Int { abort("wasm-only") } - -///| -fn mbt_ffi_load32(offset : Int) -> Int { - abort("wasm-only") -} diff --git a/interface/moonplasma/host/plasmoids/ffi.mbt b/interface/moonplasma/host/plasmoids/ffi.mbt index b2bb621..5962a14 100644 --- a/interface/moonplasma/host/plasmoids/ffi.mbt +++ b/interface/moonplasma/host/plasmoids/ffi.mbt @@ -46,13 +46,25 @@ fn wasmImportPickerStart() -> Int = "moonplasma:host/plasmoids@0.1.0" "picker-st fn wasmImportPickerPoll(p0 : Int) = "moonplasma:host/plasmoids@0.1.0" "picker-poll" ///| -extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = -#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) +extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = +#|(func (param i32) (result i64) local.get 0 i64.load) ///| extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load8_u) +///| +extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) + ///| extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #|(func (param i32) (result i32) (local i32) @@ -60,10 +72,6 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #| 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) - ///| extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #|(func (param i32) (param i32) (result i32) @@ -72,12 +80,9 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #| 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_store32(offset : Int, value : Int) = -#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) +#owned(bytes) +extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = +#|(func (param i32) (result i32) local.get 0) ///| #owned(str) @@ -85,15 +90,10 @@ extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = #|(func (param i32) (result i32) local.get 0) ///| -#owned(bytes) -extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> 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_store64(offset : Int, value : Int64) = #|(func (param i32) (param i64) local.get 0 local.get 1 i64.store) -///| -extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = -#|(func (param i32) (result i64) local.get 0 i64.load) - diff --git a/interface/moonplasma/host/plasmoids/native_stub.mbt b/interface/moonplasma/host/plasmoids/native_stub.mbt index 1eb85b0..ed27fe4 100644 --- a/interface/moonplasma/host/plasmoids/native_stub.mbt +++ b/interface/moonplasma/host/plasmoids/native_stub.mbt @@ -76,7 +76,7 @@ fn wasmImportPickerPoll(p0 : Int) -> Unit { } ///| -fn mbt_ffi_store8(offset : Int, value : Int) -> Unit { +fn mbt_ffi_load64(offset : Int) -> Int64 { abort("wasm-only") } @@ -86,7 +86,7 @@ fn mbt_ffi_load8_u(offset : Int) -> Int { } ///| -fn mbt_ffi_malloc(size : Int) -> Int { +fn mbt_ffi_store8(offset : Int, value : Int) -> Unit { abort("wasm-only") } @@ -95,23 +95,18 @@ fn mbt_ffi_free(position : Int) -> Unit { abort("wasm-only") } -///| -fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { - abort("wasm-only") -} - -///| -fn mbt_ffi_load32(offset : Int) -> Int { - abort("wasm-only") -} - ///| fn mbt_ffi_store32(offset : Int, value : Int) -> Unit { abort("wasm-only") } ///| -fn mbt_ffi_str2ptr(str : String) -> Int { +fn mbt_ffi_malloc(size : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { abort("wasm-only") } @@ -121,11 +116,16 @@ fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { } ///| -fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit { +fn mbt_ffi_str2ptr(str : String) -> Int { abort("wasm-only") } ///| -fn mbt_ffi_load64(offset : Int) -> Int64 { +fn mbt_ffi_load32(offset : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit { abort("wasm-only") } diff --git a/interface/moonplasma/host/sys/ffi.mbt b/interface/moonplasma/host/sys/ffi.mbt index 3451b31..0c9c157 100644 --- a/interface/moonplasma/host/sys/ffi.mbt +++ b/interface/moonplasma/host/sys/ffi.mbt @@ -72,15 +72,6 @@ fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "ha ///| fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "spawn" -///| -extern "wasm" fn mbt_ffi_free(position : Int) = -#|(func (param i32) local.get 0 call $moonbit.decref) - -///| -#owned(str) -extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = -#|(func (param i32) (result i32) local.get 0) - ///| extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #|(func (param i32) (param i32) (result i32) @@ -89,16 +80,8 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #| local.get 0) ///| -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) - -///| -#owned(bytes) -extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = -#|(func (param i32) (result i32) local.get 0) +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 = @@ -111,3 +94,20 @@ extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = #| local.get 1 call $moonbit.init_array8 #| local.get 0) +///| +#owned(bytes) +extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = +#|(func (param i32) (result i32) local.get 0) + +///| +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) + +///| +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) + diff --git a/interface/moonplasma/host/sys/native_stub.mbt b/interface/moonplasma/host/sys/native_stub.mbt index 66eea6a..1ad04a2 100644 --- a/interface/moonplasma/host/sys/native_stub.mbt +++ b/interface/moonplasma/host/sys/native_stub.mbt @@ -120,28 +120,13 @@ fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { abort("wasm-only host import") } -///| -fn mbt_ffi_free(position : Int) -> Unit { - abort("wasm-only") -} - -///| -fn mbt_ffi_str2ptr(str : String) -> Int { - abort("wasm-only") -} - ///| fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { abort("wasm-only") } ///| -fn mbt_ffi_malloc(size : Int) -> Int { - abort("wasm-only") -} - -///| -fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { +fn mbt_ffi_free(position : Int) -> Unit { abort("wasm-only") } @@ -154,3 +139,18 @@ fn mbt_ffi_load32(offset : Int) -> Int { fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { abort("wasm-only") } + +///| +fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_str2ptr(str : String) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_malloc(size : Int) -> Int { + abort("wasm-only") +} diff --git a/justfile b/justfile index 23e30d5..c5d81e9 100644 --- a/justfile +++ b/justfile @@ -42,7 +42,7 @@ build-release: # Run the compositor, built as a wasm component, in a window on your current Wayland session (close the window or Ctrl-C to stop). Connect clients via `just client`. The panel is empty until panel modules run in the component; `just run-native` has them. run: compositor-wasm host-wasm rm -f {{socket}} - host-wasm/target/release/moon-plasma-host build/components/compositor.wasm --socket {{socket}} --theme {{theme}} --window + host-wasm/target/release/moon-plasma-host build/compositor.wasm --socket {{socket}} --theme {{theme}} --window # Run the native compositor (tcc debug build, with the wasm panel modules) in a window on your current Wayland session. run-native: build modules @@ -70,15 +70,24 @@ run-headless: build modules rm -f {{socket}} {{exe}} --socket {{socket}} --theme {{theme}} -# Run the compositor on the real display (DRM/KMS + libinput). Run from a login VT (Ctrl+Alt+F3), not inside another session. Ctrl+Alt+Backspace quits, Ctrl+Alt+F switches VT. -run-drm: build-release modules +# Run the wasm compositor on the real display (DRM/KMS + libinput, through the host). Run from a login VT (Ctrl+Alt+F3), not inside another session. Ctrl+Alt+Backspace quits, Ctrl+Alt+F switches VT. +run-drm: compositor-wasm host-wasm modules + rm -f {{socket}} + host-wasm/target/release/moon-plasma-host build/compositor.wasm --drm --socket {{socket}} --theme {{theme}} + +# The same on the native compositor (system-cc release build), for comparison. +run-drm-native: build-release modules rm -f {{socket}} {{release_exe}} --drm --socket {{socket}} --theme {{theme}} -# Install the Moon Plasma login session (display-manager entry); asks for root once. -install-session: build-release modules +# Install the Moon Plasma login session (display-manager entry): the wasm compositor + its host. Asks for root once. +install-session: compositor-wasm host-wasm modules run0 python3 session/install.py +# Install the login session with the native compositor instead. +install-session-native: build-release modules + run0 python3 session/install.py --native + # Remove the login session again. uninstall-session: run0 python3 session/install.py --remove @@ -122,7 +131,7 @@ clean: clean-all: rm -rf _build build -# Build the compositor as a wasm component (build/components/compositor.wasm): imports only moonplasma:host/sys. +# Build the compositor as a wasm component (build/compositor.wasm): imports only moonplasma:host/sys. compositor-wasm: scripts/build-compositor-wasm.sh diff --git a/scripts/build-compositor-wasm.sh b/scripts/build-compositor-wasm.sh index 1fe4ee6..ad6a2f1 100755 --- a/scripts/build-compositor-wasm.sh +++ b/scripts/build-compositor-wasm.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Build the compositor itself as a wasm component: build/components/compositor.wasm. +# Build the compositor itself as a wasm component: build/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 @@ -13,10 +13,10 @@ moon build --target wasm --release components/compositor/gen 2>&1 | grep -E '^Er [ "${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, -)" +mkdir -p build +wasm-tools component embed wit/host "$core" --world compositor --encoding utf16 -o build/compositor.embed.wasm +wasm-tools component new build/compositor.embed.wasm -o build/compositor.wasm +rm -f build/compositor.embed.wasm +wasm-tools validate --features component-model build/compositor.wasm +printf 'compositor.wasm %s bytes imports=[%s]\n' "$(stat -c %s build/compositor.wasm)" \ + "$(wasm-tools component wit build/compositor.wasm | sed -n 's/^ import \(.*\);/\1/p' | paste -sd, -)" diff --git a/session/install.py b/session/install.py index 56ab548..0b62e19 100755 --- a/session/install.py +++ b/session/install.py @@ -1,23 +1,30 @@ #!/usr/bin/env python3 """Install (or remove) the Moon Plasma login session. Run as root, once: - run0 python3 session/install.py # install + run0 python3 session/install.py # install: the compositor as a wasm component + run0 python3 session/install.py --native # install the native compositor instead run0 python3 session/install.py --remove # uninstall Installs: - /usr/local/bin/moon-plasma release compositor binary - /usr/local/bin/moon-plasma-session session launcher - /usr/local/share/moon-plasma/{config,wit}/ files the compositor reads at runtime + /usr/local/bin/moon-plasma-host wasmtime host that runs the compositor component + /usr/local/share/moon-plasma/compositor.wasm the compositor, as a WebAssembly component + /usr/local/bin/moon-plasma (--native) release native compositor binary + /usr/local/bin/moon-plasma-session session launcher (starts the host if installed) + /usr/local/share/moon-plasma/{config,wit,assets}/ files the compositor reads at runtime /usr/local/share/moon-plasma/modules/*.wasm the panel's wasm modules (build them first: just modules) /usr/share/wayland-sessions/moon-plasma.desktop display-manager entry """ import os, shutil, sys root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +native = "--native" in sys.argv exe = os.path.join(root, "_build/native/release/build/compositor/bin/bin.exe") +host = os.path.join(root, "host-wasm/target/release/moon-plasma-host") +component = os.path.join(root, "build/compositor.wasm") share = "/usr/local/share/moon-plasma" targets = [ "/usr/local/bin/moon-plasma", + "/usr/local/bin/moon-plasma-host", "/usr/local/bin/moon-plasma-session", "/usr/share/wayland-sessions/moon-plasma.desktop", ] @@ -34,8 +41,13 @@ if "--remove" in sys.argv: if os.geteuid() != 0: sys.exit("run as root: run0 python3 session/install.py") -if not os.path.exists(exe): - sys.exit("missing %s - run `just build-release` first" % exe) +if native: + if not os.path.exists(exe): + sys.exit("missing %s - run `just build-release` first" % exe) +else: + for f, how in ((host, "just host-wasm"), (component, "just compositor-wasm")): + if not os.path.exists(f): + sys.exit("missing %s - run `%s` first" % (f, how)) def put(src, dst, mode): os.makedirs(os.path.dirname(dst), exist_ok=True) @@ -44,14 +56,28 @@ def put(src, dst, mode): os.replace(dst + ".new", dst) # atomic: safe to reinstall over a running binary print("installed", dst) -put(exe, "/usr/local/bin/moon-plasma", 0o755) +def drop(path): + if os.path.exists(path): + os.remove(path) + print("removed", path) + +if native: + put(exe, "/usr/local/bin/moon-plasma", 0o755) + drop("/usr/local/bin/moon-plasma-host") # the launcher falls back to the native binary +else: + put(host, "/usr/local/bin/moon-plasma-host", 0o755) + drop("/usr/local/bin/moon-plasma") +os.makedirs(share, exist_ok=True) +if not native: + put(component, os.path.join(share, "compositor.wasm"), 0o644) put(os.path.join(root, "session/moon-plasma-session"), "/usr/local/bin/moon-plasma-session", 0o755) put(os.path.join(root, "session/moon-plasma.desktop"), "/usr/share/wayland-sessions/moon-plasma.desktop", 0o644) -for d in ("config", "wit"): +# Read at runtime relative to the working directory (the launcher cd's here): the Interface Explorer +# shows wit/, the theme comes from config/, and assets/fonts holds the Allo font. +for d in ("config", "wit", "assets"): dst = os.path.join(share, d) if os.path.isdir(dst): shutil.rmtree(dst) - os.makedirs(share, exist_ok=True) shutil.copytree(os.path.join(root, d), dst) print("installed", dst) mods = os.path.join(root, "build/components") diff --git a/session/moon-plasma-session b/session/moon-plasma-session index b495ef9..91bb08b 100755 --- a/session/moon-plasma-session +++ b/session/moon-plasma-session @@ -1,7 +1,9 @@ #!/bin/sh # Login-session entry point for Moon Plasma (started by the display manager). -# Runs the native compositor on the seat's display via DRM/KMS + libinput and -# logs to ~/.local/state/moon-plasma/session.log. +# Runs the compositor on the seat's display via DRM/KMS + libinput and logs to +# ~/.local/state/moon-plasma/session.log. By default that is the compositor as a +# WebAssembly component, run by moon-plasma-host; if only the native binary was installed +# (session/install.py --native), it runs that instead. share=/usr/local/share/moon-plasma export XDG_SESSION_TYPE=wayland @@ -20,9 +22,15 @@ cd "$share" || exit 1 sock="${XDG_RUNTIME_DIR:-/tmp}/wayland-moon-0" rm -f "$sock" +if [ -x /usr/local/bin/moon-plasma-host ]; then + set -- /usr/local/bin/moon-plasma-host "$share/compositor.wasm" +else + set -- /usr/local/bin/moon-plasma +fi + if [ -z "$DBUS_SESSION_BUS_ADDRESS" ] && command -v dbus-run-session >/dev/null 2>&1; then - exec dbus-run-session -- /usr/local/bin/moon-plasma --drm --socket "$sock" \ + exec dbus-run-session -- "$@" --drm --socket "$sock" \ --theme "$share/config/themes/moon-night.json" >"$log" 2>&1 fi -exec /usr/local/bin/moon-plasma --drm --socket "$sock" \ +exec "$@" --drm --socket "$sock" \ --theme "$share/config/themes/moon-night.json" >"$log" 2>&1 diff --git a/session/moon-plasma.desktop b/session/moon-plasma.desktop index 1afe287..c81ecce 100644 --- a/session/moon-plasma.desktop +++ b/session/moon-plasma.desktop @@ -1,6 +1,6 @@ [Desktop Entry] Name=Moon Plasma -Comment=Moon Plasma desktop (native MoonBit Wayland compositor) +Comment=Moon Plasma desktop (MoonBit Wayland compositor, a WebAssembly component) Exec=/usr/local/bin/moon-plasma-session TryExec=/usr/local/bin/moon-plasma-session Type=Application diff --git a/wit/host/display.wit b/wit/host/display.wit new file mode 100644 index 0000000..3e6a71e --- /dev/null +++ b/wit/host/display.wit @@ -0,0 +1,41 @@ +package moonplasma:host@0.1.0; + +/// The login-session backend: the host takes the display (DRM/KMS) and input devices (libinput) +/// through the seat (libseat) and the component only sees frames going out and events coming in. +/// Mirrors compositor/kms. With no other compositor underneath, this is what makes the wasm +/// compositor a real desktop. +interface display { + record output { + width: u32, + height: u32, + /// The xkb keymap (text format v1) the clients' keyboards are sent. + keymap: list, + } + /// Take over the first connected output and the seat's input. None, with the reason on the + /// host's stderr, when this is not an active login VT. + open: func() -> option; + /// Service the seat, DRM and input fds without blocking. False once the user asked to quit + /// (Ctrl+Alt+Backspace). + poll: func() -> bool; + /// True when a new frame can be presented (seat active, no page flip in flight). + frame-ready: func() -> bool; + /// Show an RGBA8888 frame of `width` x `height` (it must match the output mode). + present: func(pixels: list, width: u32, height: u32); + /// Show the cursor for a wp_cursor_shape_v1 value. + set-cursor-shape: func(shape: u32); + + record pointer-pos { x: f64, y: f64 } + /// A button or key as an evdev code, pressed or released. + record key-state { code: u32, pressed: bool } + record modifiers { depressed: u32, latched: u32, locked: u32, group: u32 } + variant seat-event { + pointer-move(pointer-pos), + pointer-button(key-state), + key(key-state), + modifiers(modifiers), + } + /// Input queued since the last call. + take-input: func() -> list; + /// Restore the previous video mode and release the seat. + close: func(); +} diff --git a/wit/host/sys.wit b/wit/host/sys.wit index fa0c2a8..f2ec4cb 100644 --- a/wit/host/sys.wit +++ b/wit/host/sys.wit @@ -76,6 +76,7 @@ world compositor { import sys; import font; import plasmoids; + import display; /// Run the compositor until it exits. `args` are the command-line arguments (without argv[0]). export run: func(args: list) -> s32; }