Panel modules in the wasm compositor: the host runs them (moonplasma:host/plasmoids)
CI / test (push) Failing after 46s

A component can't embed a second wasm runtime, so the compositor drives panel modules through a
host import and the wasmtime host instantiates them: load, render, popup, on-event, plus the data
they read (apps, windows, layouts, modules, system) and the requests they make (launch, focus
window, set layout, load/unload, browse), with a zenity file chooser for 'Add widget'.

- wit/worlds.wit: world plasmoid-host, every capability a module can import + the plasmoid export.
  The host instantiates any module against it; a module imports the subset it uses.
- wit/host/plasmoids.wit + generated MoonBit bindings; compositor/wasm gets a wasm backend
  (wasm_host.mbt) with the same public API as the native wasmer one.
- host-wasm/src/plasmoid.rs: typed component bindings, one Store per module, shared host data.
  Tests load the built launcher/layout modules and drive them (typed filter, Enter, launch request).
- scripts/gen-native-stubs.py keeps a package's imports when it rewrites moon.pkg.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-25 02:09:57 -08:00
1 parent 5c3bebc7fd
commit e769566d8f
23 files changed
+2001 -302

No files matched your search

@@ -20,14 +20,6 @@ pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int {
}
///|
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)
@@ -35,3 +27,11 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#| 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)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
+1
View File
@@ -104,6 +104,7 @@ pub fn run(args : Array[String]) -> Int {
1
}
Some(comp) => {
comp.shell.persist = true // remember which modules are loaded in the panel
comp.shell.screen_w = width
if gfx_out.length() > 0 && !serve {
let pixmap = comp.present_to_gfx(gfx_ctx)
+2 -1
View File
@@ -2,6 +2,7 @@ import {
"moonbitlang/core/builtin",
"moonplasma/desktop/interface/moonplasma/desktop/types" @types,
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
"moonplasma/desktop/interface/moonplasma/host/plasmoids" @hostpl,
}
supported_targets = "+native+wasm"
@@ -9,7 +10,7 @@ supported_targets = "+native+wasm"
options(
targets: {
"wasm_native.mbt": ["native"],
"wasm_unsupported.mbt": ["wasm"],
"wasm_host.mbt": ["wasm"],
"wasm_test.mbt": ["native"],
},
"native-stub": [ "wasm_stub.c" ],
+314
View File
@@ -0,0 +1,314 @@
///| 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 here the same API is a thin client of the `moonplasma:host/plasmoids` import:
/// the host (wasmtime) instantiates the modules, serves their capability imports from the data
/// published below, and hands back draw ops and requests.
///|
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)
}
///| The native build hands tokens to modules as packed bytes; here they cross as a typed record.
pub fn pack_tokens(_t : @theme.Tokens) -> Bytes {
Bytes::make(0, 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]
}
///| Load a plasmoid component. Err carries a short reason.
pub fn load(path : String, tokens : @theme.Tokens) -> Result[Plasmoid, String] {
@hostpl.set_tokens(tokens)
match @hostpl.load(path) {
Err(e) => Err(e)
Ok(l) => {
let imports : Array[String] = []
for i in l.imports {
if i != "theme" {
imports.push(i)
}
}
Ok({
handle: l.handle.reinterpret_as_int(),
id: l.id,
name: l.name,
pref_w: l.preferred.w.reinterpret_as_int(),
pref_h: l.preferred.h.reinterpret_as_int(),
min_w: l.min_width.reinterpret_as_int(),
stretch: l.stretch,
imports,
})
}
}
}
///|
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 {
@hostpl.publish_system({
cpu_permille: s.cpu_permille.reinterpret_as_uint(),
mem_used_kib: s.mem_used_kib.reinterpret_as_uint64(),
mem_total_kib: s.mem_total_kib.reinterpret_as_uint64(),
battery_percent: s.battery_percent,
charging: s.charging,
uptime_secs: s.uptime_secs.reinterpret_as_uint64(),
net_rx_bytes_per_sec: s.rx_bps.reinterpret_as_uint64(),
net_tx_bytes_per_sec: s.tx_bps.reinterpret_as_uint64(),
load_centi: s.load_centi.reinterpret_as_uint(),
})
}
///|
pub fn set_windows(wins : Array[WindowEntry]) -> Unit {
let out : Array[@hostpl.WindowEntry] = []
for w in wins {
out.push({ id: w.id, title: w.title, app_id: w.app_id, focused: w.focused })
}
@hostpl.publish_windows(out)
}
///|
pub fn take_focus_request() -> UInt64? {
@hostpl.take_focus_request()
}
///|
pub fn Plasmoid::pointer_down(self : Plasmoid, x : Int, y : Int) -> Bool {
self.on_event(false, PointerDown(x, y))
}
///|
pub fn Plasmoid::unload(self : Plasmoid) -> Unit {
@hostpl.unload(self.handle.reinterpret_as_uint())
}
///|
pub fn Plasmoid::render(
self : Plasmoid,
w : Int,
h : Int,
tokens : @theme.Tokens,
) -> Array[@types.DrawOp] {
@hostpl.set_tokens(tokens)
@hostpl.render(self.handle.reinterpret_as_uint(), { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() })
}
///| 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? {
match @hostpl.popup(self.handle.reinterpret_as_uint()) {
None => None
Some(p) =>
Some({ w: p.box.w.reinterpret_as_int(), h: p.box.h.reinterpret_as_int(), ops: p.ops })
}
}
///| 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 {
let e : @types.InputEvent = match ev {
PointerMove(x, y) => PointerMove({ x, y })
PointerDown(x, y) => PointerDown({ x, y })
PointerUp(x, y) => PointerUp({ x, y })
PointerLeave => PointerLeave
FocusLost => FocusLost
KeyDown(k) => KeyDown(k)
}
@hostpl.on_event(self.handle.reinterpret_as_uint(), popup, e)
}
///|
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 {
// [u32 row count][rows], the encoding the host parses.
let n = t.n
let out : FixedArray[Byte] = FixedArray::make(4 + t.rows.length(), b'\x00')
for k = 0; k < 4; k = k + 1 {
out[k] = ((n >> (8 * k)) & 0xFF).to_byte()
}
for i = 0; i < t.rows.length(); i = i + 1 {
out[4 + i] = t.rows[i]
}
let id = match which {
Apps => 0U
Windows => 1U
Layouts => 2U
Modules => 3U
Instances => 4U
}
@hostpl.publish_table(id, out)
}
///|
pub fn publish_state(layout_mode : Int, inspector_on : Bool) -> Unit {
@hostpl.publish_state(layout_mode, inspector_on)
}
///| 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? {
match @hostpl.next_request() {
None => None
Some(Launch(id)) => Some(Launch(id))
Some(FocusWindow(n)) => Some(FocusWindow(n))
Some(SetLayout(m)) => Some(SetLayout(m))
Some(SetInspector(on)) => Some(SetInspector(on))
Some(LoadModule(p)) => Some(LoadModule(p))
Some(UnloadInstance(s)) => Some(UnloadInstance(s))
Some(Browse) => Some(Browse)
}
}
///|
pub fn list_wasm_files(dir : String) -> Array[String] {
@hostpl.list_wasm_files(dir)
}
///| An in-flight native file-chooser dialog.
pub(all) struct Picker {
fd : Int
buf : Array[Byte]
}
///|
pub fn Picker::start() -> Picker? {
if @hostpl.picker_start() {
Some({ fd: 0, buf: [] })
} else {
None
}
}
///|
pub fn Picker::poll(_self : Picker) -> String?? {
match @hostpl.picker_poll() {
Open => None
Cancelled => Some(None)
Chosen(path) => Some(Some(path))
}
}
-233
View File
@@ -1,233 +0,0 @@
///| 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
}
+17 -11
View File
@@ -25,18 +25,24 @@ moon-plasma-host build/components/compositor.wasm --socket PATH --gfx-out frame.
## 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.
the desktop card, input routing, the nested window on the host session, real fonts (Allo Variable,
Adwaita Mono: the host rasterises glyphs, `moonplasma:host/font`) and the panel modules.
**Panel modules** run in this host. A component can't embed a second runtime, so the compositor
drives them through `moonplasma:host/plasmoids` ([`wit/host/plasmoids.wit`](../wit/host/plasmoids.wit)):
load, render, popup, on-event, plus the data they read (apps, windows, layouts, modules, system
snapshot) and the requests they make (launch, focus, set layout, load/unload). `src/plasmoid.rs`
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):
- **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).
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
overwrite the hand-fixed `desktop/theme` package):
`wit-bindgen moonbit wit/host --world compositor --out-dir $T --gen-dir components/compositor/gen
--project-name moonplasma/desktop --ignore-module-file --ignore-stub`, then
`scripts/gen-native-stubs.py interface/moonplasma/host/<sys|font|plasmoids>` (the imports are
wasm-only; this restores the native stand-ins and the per-file targets).
+138
View File
@@ -15,9 +15,17 @@ use std::process::{Command, Stdio};
use wasmtime::component::{Component, HasSelf, Linker};
use wasmtime::{Config, Engine, Result, Store};
mod plasmoid;
wasmtime::component::bindgen!({
path: "../wit/host",
world: "compositor",
// The desktop value types are the same WIT the modules use: share the Rust types, so draw ops
// flow from a module straight to the compositor without conversion.
with: {
"moonplasma:desktop/types@0.1.0": plasmoid::ph::moonplasma::desktop::types,
"moonplasma:desktop/theme@0.1.0": plasmoid::ph::moonplasma::desktop::theme,
},
});
use ab_glyph::{Font, FontVec, OutlineCurve};
@@ -33,6 +41,8 @@ struct State {
started: Option<std::time::Instant>,
/// TTF faces loaded by the component (`font.load`), by slot.
fonts: [Option<FontVec>; 4],
/// Runs the panel modules; set once the engine exists.
pl: Option<plasmoid::Runtime>,
}
fn sockaddr_un(path: &str) -> (libc::sockaddr_un, libc::socklen_t) {
@@ -91,6 +101,132 @@ impl State {
}
}
impl State {
fn pl(&mut self) -> &mut plasmoid::Runtime {
self.pl.as_mut().expect("plasmoid runtime is set before the component runs")
}
}
impl moonplasma::host::plasmoids::Host for State {
fn load(&mut self, path: String) -> Result<moonplasma::host::plasmoids::Loaded, String> {
let l = self.pl().load(&path)?;
Ok(moonplasma::host::plasmoids::Loaded {
handle: l.handle,
id: l.info.id,
name: l.info.name,
preferred: l.info.preferred,
min_width: l.info.min_width,
stretch: l.info.stretch,
imports: l.imports,
})
}
fn unload(&mut self, handle: u32) {
self.pl().unload(handle);
}
fn set_tokens(&mut self, t: plasmoid::ph::moonplasma::desktop::theme::Tokens) {
self.pl().shared.borrow_mut().tokens = Some(t);
}
fn render(
&mut self,
handle: u32,
box_: plasmoid::ph::moonplasma::desktop::types::Size,
) -> Vec<plasmoid::ph::moonplasma::desktop::types::DrawOp> {
self.pl().render(handle, box_)
}
fn popup(&mut self, handle: u32) -> Option<moonplasma::host::plasmoids::PopupSurface> {
self.pl().popup(handle).map(|p| moonplasma::host::plasmoids::PopupSurface { box_: p.size, ops: p.ops })
}
fn on_event(
&mut self,
handle: u32,
on_popup: bool,
event: plasmoid::ph::moonplasma::desktop::types::InputEvent,
) -> bool {
self.pl().on_event(handle, on_popup, event)
}
fn publish_table(&mut self, which: u32, rows: Vec<u8>) {
if let Some(t) = self.pl().shared.borrow_mut().tables.get_mut(which as usize) {
*t = rows;
}
}
fn publish_state(&mut self, layout_mode: i32, inspector_on: bool) {
let sh = &self.pl().shared;
let mut sh = sh.borrow_mut();
sh.layout_mode = layout_mode;
sh.inspector_on = inspector_on;
}
fn publish_system(&mut self, s: moonplasma::host::plasmoids::SystemSnapshot) {
use plasmoid::ph::moonplasma::desktop::system::Snapshot;
self.pl().shared.borrow_mut().system = Some(Snapshot {
cpu_permille: s.cpu_permille,
mem_used_kib: s.mem_used_kib,
mem_total_kib: s.mem_total_kib,
battery_percent: s.battery_percent,
charging: s.charging,
uptime_secs: s.uptime_secs,
net_rx_bytes_per_sec: s.net_rx_bytes_per_sec,
net_tx_bytes_per_sec: s.net_tx_bytes_per_sec,
load_centi: s.load_centi,
});
}
fn publish_windows(&mut self, wins: Vec<moonplasma::host::plasmoids::WindowEntry>) {
self.pl().shared.borrow_mut().windows =
wins.into_iter().map(|w| (w.id, w.title, w.app_id, w.focused)).collect();
}
fn next_request(&mut self) -> Option<moonplasma::host::plasmoids::Request> {
use moonplasma::host::plasmoids::Request as R;
use plasmoid::Req;
let r = self.pl().shared.borrow_mut().requests.pop_front()?;
Some(match r {
Req::Launch(s) => R::Launch(s),
Req::FocusWindow(n) => R::FocusWindow(n),
Req::SetLayout(n) => R::SetLayout(n),
Req::SetInspector(b) => R::SetInspector(b),
Req::LoadModule(s) => R::LoadModule(s),
Req::UnloadInstance(s) => R::UnloadInstance(s),
Req::Browse => R::Browse,
})
}
fn take_focus_request(&mut self) -> Option<u64> {
self.pl().shared.borrow_mut().focus_req.take()
}
fn list_wasm_files(&mut self, dir: String) -> Vec<String> {
let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
let mut v: Vec<String> = rd
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".wasm"))
.collect();
v.sort();
v
}
fn picker_start(&mut self) -> bool {
self.pl().picker_start()
}
fn picker_poll(&mut self) -> moonplasma::host::plasmoids::PickerState {
use moonplasma::host::plasmoids::PickerState as P;
match self.pl().picker_poll() {
None => P::Open,
Some(None) => P::Cancelled,
Some(Some(path)) => P::Chosen(path),
}
}
}
impl moonplasma::host::font::Host for State {
fn load(&mut self, slot: u32, path: String) -> bool {
if slot as usize >= self.fonts.len() {
@@ -478,7 +614,9 @@ fn main() -> Result<()> {
let mut linker: Linker<State> = Linker::new(&engine);
moonplasma::host::sys::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
moonplasma::host::font::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
moonplasma::host::plasmoids::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
let mut store = Store::new(&engine, State::default());
store.data_mut().pl = Some(plasmoid::Runtime::new(&engine)?);
let compositor = Compositor::instantiate(&mut store, &component, &linker)?;
let code = compositor.call_run(&mut store, &args)?;
std::process::exit(code);
+524
View File
@@ -0,0 +1,524 @@
//! Runs panel modules (plasmoids) for the compositor component.
//!
//! The native compositor embeds wasmer and marshals the canonical ABI by hand. A component can't
//! embed a second runtime, so the compositor asks this host (wit/host/plasmoids.wit) and gets draw
//! ops back. Each module is instantiated as a real component with typed bindings against one world,
//! `plasmoid-host` (wit/worlds.wit): it imports the subset of host interfaces it uses, and every one
//! of them is served here from the data the compositor publishes.
use std::cell::RefCell;
use std::collections::VecDeque;
use std::io::Read;
use std::os::unix::process::CommandExt;
use std::process::{Child, Command, Stdio};
use std::rc::Rc;
use wasmtime::component::{Component, HasSelf, Linker};
use wasmtime::{Engine, Store};
pub mod ph {
wasmtime::component::bindgen!({
path: "../wit",
world: "plasmoid-host",
});
}
use ph::exports::moonplasma::desktop as ex;
use ph::moonplasma::desktop as d;
/// What a module asked of the compositor during a call.
pub enum Req {
Launch(String),
FocusWindow(i32),
SetLayout(i32),
SetInspector(bool),
LoadModule(String),
UnloadInstance(String),
Browse,
}
pub const T_APPS: usize = 0;
pub const T_WINDOWS: usize = 1;
pub const T_LAYOUTS: usize = 2;
pub const T_MODULES: usize = 3;
pub const T_INSTANCES: usize = 4;
/// Host data every module reads from, shared by all loaded modules.
#[derive(Default)]
pub struct Shared {
pub tables: [Vec<u8>; 5],
pub layout_mode: i32,
pub inspector_on: bool,
pub system: Option<d::system::Snapshot>,
/// (id, title, app id, focused)
pub windows: Vec<(u64, String, String, bool)>,
pub requests: VecDeque<Req>,
pub focus_req: Option<u64>,
pub tokens: Option<d::theme::Tokens>,
}
pub type SharedRef = Rc<RefCell<Shared>>;
pub struct PState {
shared: SharedRef,
}
enum Field {
I(i32),
S(String),
}
/// Parse a table (LE u32 row count, then rows) by its field spec: 'i' = LE i32, 's' = LE u32 length + UTF-8.
fn parse_table(bytes: &[u8], spec: &str) -> Vec<Vec<Field>> {
let rd = |p: usize| -> Option<u32> { bytes.get(p..p + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) };
let Some(n) = rd(0) else { return Vec::new() };
let mut pos = 4;
let mut rows = Vec::new();
'rows: for _ in 0..n {
let mut row = Vec::new();
for c in spec.chars() {
let Some(v) = rd(pos) else { break 'rows };
pos += 4;
if c == 'i' {
row.push(Field::I(v as i32));
} else {
let end = pos + v as usize;
let Some(s) = bytes.get(pos..end) else { break 'rows };
row.push(Field::S(String::from_utf8_lossy(s).into_owned()));
pos = end;
}
}
rows.push(row);
}
rows
}
fn s(f: &Field) -> String {
match f {
Field::S(x) => x.clone(),
Field::I(i) => i.to_string(),
}
}
fn i(f: &Field) -> i32 {
match f {
Field::I(x) => *x,
Field::S(_) => 0,
}
}
fn default_tokens() -> d::theme::Tokens {
let c = |r, g, b| d::types::Color { r, g, b, a: 255 };
d::theme::Tokens {
name: String::new(),
palette: d::theme::Palette {
desktop_top: c(20, 28, 48),
desktop_bottom: c(10, 14, 28),
surface: c(30, 36, 50),
surface_hover: c(50, 58, 76),
surface_popup: c(24, 30, 44),
foreground: c(240, 244, 250),
foreground_muted: c(150, 160, 180),
accent: c(120, 150, 255),
accent_foreground: c(255, 255, 255),
border: c(70, 80, 100),
},
font_size: 14,
radius: 6,
spacing: 6,
panel_height: 40,
}
}
impl PState {
fn rows(&self, t: usize, spec: &str) -> Vec<Vec<Field>> {
parse_table(&self.shared.borrow().tables[t], spec)
}
}
impl d::types::Host for PState {}
impl d::theme::Host for PState {
fn get_tokens(&mut self) -> d::theme::Tokens {
self.shared.borrow().tokens.clone().unwrap_or_else(default_tokens)
}
}
impl d::clock::Host for PState {
fn now(&mut self) -> d::types::Datetime {
unsafe {
let t = libc::time(std::ptr::null_mut());
let mut tm: libc::tm = std::mem::zeroed();
libc::localtime_r(&t, &mut tm);
d::types::Datetime {
year: (tm.tm_year + 1900) as u32,
month: (tm.tm_mon + 1) as u8,
day: tm.tm_mday as u8,
hour: tm.tm_hour as u8,
minute: tm.tm_min as u8,
second: tm.tm_sec as u8,
weekday: tm.tm_wday as u8,
}
}
}
}
impl d::app_catalog::Host for PState {
fn list_apps(&mut self) -> Vec<d::types::AppEntry> {
self.rows(T_APPS, "sssss")
.iter()
.map(|r| d::types::AppEntry {
id: s(&r[0]),
name: s(&r[1]),
comment: s(&r[2]),
category: s(&r[3]),
glyph: s(&r[4]),
})
.collect()
}
}
impl d::app_launch::Host for PState {
/// Known catalog ids succeed; the compositor spawns after the call returns.
fn launch(&mut self, id: String) -> Result<(), String> {
if self.rows(T_APPS, "sssss").iter().any(|r| s(&r[0]) == id) {
self.shared.borrow_mut().requests.push_back(Req::Launch(id));
Ok(())
} else {
Err("unknown application".to_string())
}
}
}
impl d::windows::Host for PState {
fn list_windows(&mut self) -> Vec<d::windows::WindowInfo> {
self.rows(T_WINDOWS, "isii")
.iter()
.map(|r| d::windows::WindowInfo {
id: i(&r[0]) as u32,
title: s(&r[1]),
focused: i(&r[2]) as u32,
minimized: i(&r[3]) as u32,
})
.collect()
}
fn focus_window(&mut self, id: u32) {
self.shared.borrow_mut().requests.push_back(Req::FocusWindow(id as i32));
}
fn all(&mut self) -> Vec<d::windows::WindowDetail> {
self.shared
.borrow()
.windows
.iter()
.take(64)
.map(|(id, title, app, focused)| d::windows::WindowDetail {
id: *id,
title: title.clone(),
app_id: app.clone(),
focused: *focused,
})
.collect()
}
fn focus(&mut self, id: u64) {
self.shared.borrow_mut().focus_req = Some(id);
}
}
impl d::layout_control::Host for PState {
fn layout_modes(&mut self) -> Vec<String> {
self.rows(T_LAYOUTS, "s").iter().map(|r| s(&r[0])).collect()
}
fn current_layout(&mut self) -> u32 {
self.shared.borrow().layout_mode as u32
}
fn set_layout(&mut self, mode: u32) {
self.shared.borrow_mut().requests.push_back(Req::SetLayout(mode as i32));
}
}
impl d::inspector::Host for PState {
fn is_on(&mut self) -> bool {
self.shared.borrow().inspector_on
}
fn set_on(&mut self, on: bool) {
self.shared.borrow_mut().requests.push_back(Req::SetInspector(on));
}
}
impl d::modules::Host for PState {
fn available(&mut self) -> Vec<d::modules::ModuleInfo> {
self.rows(T_MODULES, "sssi")
.iter()
.map(|r| d::modules::ModuleInfo { id: s(&r[0]), name: s(&r[1]), path: s(&r[2]), loaded: i(&r[3]) as u32 })
.collect()
}
fn loaded(&mut self) -> Vec<d::modules::InstanceInfo> {
self.rows(T_INSTANCES, "sss")
.iter()
.map(|r| d::modules::InstanceInfo { slot: s(&r[0]), module: s(&r[1]), name: s(&r[2]) })
.collect()
}
fn load_module(&mut self, path: String) {
self.shared.borrow_mut().requests.push_back(Req::LoadModule(path));
}
fn unload_instance(&mut self, slot: String) {
self.shared.borrow_mut().requests.push_back(Req::UnloadInstance(slot));
}
fn browse(&mut self) {
self.shared.borrow_mut().requests.push_back(Req::Browse);
}
}
impl d::system::Host for PState {
fn read(&mut self) -> d::system::Snapshot {
self.shared.borrow().system.clone().unwrap_or(d::system::Snapshot {
cpu_permille: 0,
mem_used_kib: 0,
mem_total_kib: 0,
battery_percent: -1,
charging: false,
uptime_secs: 0,
net_rx_bytes_per_sec: 0,
net_tx_bytes_per_sec: 0,
load_centi: 0,
})
}
}
struct Loaded {
store: Store<PState>,
inst: ph::PlasmoidHost,
}
/// A file-chooser dialog in flight (zenity on the host session).
struct Picker {
child: Child,
}
pub struct Runtime {
engine: Engine,
linker: Linker<PState>,
pub shared: SharedRef,
slots: Vec<Option<Loaded>>,
picker: Option<Picker>,
}
pub struct LoadedInfo {
pub handle: u32,
pub info: ex::plasmoid::PlasmoidInfo,
pub imports: Vec<String>,
}
impl Runtime {
pub fn new(engine: &Engine) -> wasmtime::Result<Self> {
let mut linker: Linker<PState> = Linker::new(engine);
ph::PlasmoidHost::add_to_linker::<PState, HasSelf<PState>>(&mut linker, |s| s)?;
Ok(Runtime {
engine: engine.clone(),
linker,
shared: Rc::new(RefCell::new(Shared::default())),
slots: Vec::new(),
picker: None,
})
}
pub fn load(&mut self, path: &str) -> Result<LoadedInfo, String> {
let bytes = std::fs::read(path).map_err(|_| "cannot read file".to_string())?;
if bytes.len() < 8 || &bytes[..4] != b"\0asm" {
return Err("not a wasm file".to_string());
}
let component = Component::new(&self.engine, &bytes)
.map_err(|_| "no plasmoid (moonplasma:desktop/plasmoid) in this module".to_string())?;
// The capability grant: the host interfaces the binary imports, besides the base ones.
let mut imports: Vec<String> = Vec::new();
for (name, _) in component.component_type().imports(&self.engine) {
if let Some(rest) = name.strip_prefix("moonplasma:desktop/") {
let iface = rest.split('@').next().unwrap_or(rest).to_string();
if iface != "types" && !imports.contains(&iface) {
imports.push(iface);
}
}
}
let mut store = Store::new(&self.engine, PState { shared: self.shared.clone() });
let inst = ph::PlasmoidHost::instantiate(&mut store, &component, &self.linker)
.map_err(|_| "wasm runtime error".to_string())?;
let info = inst
.moonplasma_desktop_plasmoid()
.call_info(&mut store)
.map_err(|_| "widget trapped in info()".to_string())?;
let l = Loaded { store, inst };
let handle = match self.slots.iter().position(|s| s.is_none()) {
Some(h) => {
self.slots[h] = Some(l);
h
}
None => {
self.slots.push(Some(l));
self.slots.len() - 1
}
};
Ok(LoadedInfo { handle: handle as u32, info, imports })
}
pub fn unload(&mut self, handle: u32) {
if let Some(slot) = self.slots.get_mut(handle as usize) {
*slot = None;
}
}
fn get(&mut self, handle: u32) -> Option<&mut Loaded> {
self.slots.get_mut(handle as usize).and_then(|s| s.as_mut())
}
/// A trapping module yields no ops.
pub fn render(&mut self, handle: u32, size: d::types::Size) -> Vec<d::types::DrawOp> {
let Some(l) = self.get(handle) else { return Vec::new() };
l.inst.moonplasma_desktop_plasmoid().call_render(&mut l.store, size).unwrap_or_default()
}
pub fn popup(&mut self, handle: u32) -> Option<ex::plasmoid::PopupSurface> {
let l = self.get(handle)?;
l.inst.moonplasma_desktop_plasmoid().call_popup(&mut l.store).ok().flatten()
}
pub fn on_event(&mut self, handle: u32, on_popup: bool, ev: d::types::InputEvent) -> bool {
let Some(l) = self.get(handle) else { return false };
let target = if on_popup { ex::plasmoid::Surface::Popup } else { ex::plasmoid::Surface::Widget };
l.inst.moonplasma_desktop_plasmoid().call_on_event(&mut l.store, target, &ev).unwrap_or(false)
}
pub fn picker_start(&mut self) -> bool {
if self.picker.is_some() {
return true;
}
let mut cmd = Command::new("zenity");
cmd.args([
"--file-selection",
"--title=Load widget (.wasm)",
"--file-filter=WebAssembly widgets | *.wasm",
"--file-filter=All files | *",
])
.stdout(Stdio::piped())
.stderr(Stdio::null())
.stdin(Stdio::null());
unsafe {
cmd.pre_exec(|| {
libc::setsid();
Ok(())
});
}
match cmd.spawn() {
Ok(child) => {
self.picker = Some(Picker { child });
true
}
Err(_) => false,
}
}
/// None while the dialog is open; Some(None) when cancelled; Some(Some(path)) when chosen.
pub fn picker_poll(&mut self) -> Option<Option<String>> {
let p = self.picker.as_mut()?;
// With SIGCHLD ignored the child is reaped for us, so an error here also means "finished".
if let Ok(None) = p.child.try_wait() {
return None;
}
let mut out = String::new();
if let Some(mut so) = p.child.stdout.take() {
let _ = so.read_to_string(&mut out);
}
self.picker = None;
let t = out.trim_end_matches(['\n', '\r']).to_string();
Some(if t.is_empty() { None } else { Some(t) })
}
}
#[cfg(test)]
mod tests {
use super::*;
use d::types::{InputEvent, Point, Size};
fn runtime() -> Runtime {
let mut cfg = wasmtime::Config::new();
cfg.wasm_component_model(true);
Runtime::new(&Engine::new(&cfg).unwrap()).unwrap()
}
/// A table: LE u32 row count, then fields as LE u32 length + UTF-8.
fn apps_table(apps: &[(&str, &str)]) -> Vec<u8> {
let mut b = (apps.len() as u32).to_le_bytes().to_vec();
for (id, name) in apps {
for f in [id, name, &"comment", &"System", &"T"] {
b.extend((f.len() as u32).to_le_bytes());
b.extend(f.as_bytes());
}
}
b
}
fn texts(ops: &[d::types::DrawOp]) -> Vec<String> {
ops.iter()
.filter_map(|o| if let d::types::DrawOp::Text(t) = o { Some(t.text.clone()) } else { None })
.collect()
}
fn module(name: &str) -> String {
for p in [format!("../build/components/{name}.wasm"), format!("build/components/{name}.wasm")] {
if std::path::Path::new(&p).exists() {
return p;
}
}
panic!("build/components/{name}.wasm is missing: run `just modules`");
}
#[test]
fn launcher_reads_the_catalog_filters_typed_keys_and_launches() {
let mut rt = runtime();
rt.shared.borrow_mut().tables[T_APPS] = apps_table(&[("a.term", "Terminal"), ("b.files", "Files")]);
let l = rt.load(&module("launcher")).expect("launcher loads");
// Its capability grant is what the binary imports (the MoonBit side drops the base `theme`).
let mut imports = l.imports.clone();
imports.sort();
assert_eq!(imports, ["app-catalog", "app-launch", "theme"]);
let h = l.handle;
// It draws its button.
assert!(!rt.render(h, Size { w: 190, h: 36 }).is_empty());
// Clicking opens the popup; typing narrows it to Files; Enter launches it.
assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 1, y: 1 })));
assert!(rt.popup(h).is_some());
for k in ["f", "i", "l", "e", "s"] {
rt.on_event(h, true, InputEvent::KeyDown(k.to_string()));
}
assert!(texts(&rt.popup(h).expect("popup open").ops).contains(&"Files".to_string()));
assert!(rt.on_event(h, true, InputEvent::KeyDown("Enter".to_string())));
match rt.shared.borrow_mut().requests.pop_front() {
Some(Req::Launch(id)) => assert_eq!(id, "b.files"),
_ => panic!("expected a launch request"),
}
assert!(rt.popup(h).is_none());
rt.unload(h);
}
#[test]
fn modules_are_rejected_cleanly() {
let mut rt = runtime();
assert!(rt.load("/nonexistent.wasm").is_err());
let junk = std::env::temp_dir().join("moon-plasma-junk.wasm");
std::fs::write(&junk, b"not wasm at all").unwrap();
assert!(rt.load(junk.to_str().unwrap()).is_err());
}
#[test]
fn layout_module_follows_the_published_mode_and_sets_it() {
let mut rt = runtime();
let l = rt.load(&module("layout")).expect("layout loads");
assert!(l.imports.contains(&"layout-control".to_string()));
// layouts table: one string field per row
let mut t = 3u32.to_le_bytes().to_vec();
for n in ["Tiling (BSP)", "Monocle", "Floating"] {
t.extend((n.len() as u32).to_le_bytes());
t.extend(n.as_bytes());
}
rt.shared.borrow_mut().tables[T_LAYOUTS] = t;
rt.shared.borrow_mut().layout_mode = 0;
let ops = rt.render(l.handle, Size { w: 120, h: 36 });
assert!(!texts(&ops).is_empty());
rt.unload(l.handle);
}
}
+9 -9
View File
@@ -6,11 +6,6 @@ fn wasmImportLoad(p0 : Int, p1 : Int, p2 : Int) -> Int = "moonplasma:host/font@0
///|
fn wasmImportRasterise(p0 : Int, p1 : Int, p2 : Int, p3 : Int) = "moonplasma:host/font@0.1.0" "rasterise"
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] =
#|(func (param i32) (param i32) (result i32)
@@ -19,8 +14,8 @@ extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] =
#| 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 =
@@ -30,6 +25,11 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#| local.get 1)
///|
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_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
@@ -10,18 +10,13 @@ fn wasmImportRasterise(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn mbt_ffi_str2ptr(str : String) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only")
}
@@ -31,6 +26,11 @@ fn mbt_ffi_malloc(size : Int) -> Int {
}
///|
fn mbt_ffi_free(position : Int) -> Unit {
fn mbt_ffi_str2ptr(str : String) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only")
}
@@ -0,0 +1,99 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
fn wasmImportLoad(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/plasmoids@0.1.0" "load"
///|
fn wasmImportUnload(p0 : Int) = "moonplasma:host/plasmoids@0.1.0" "unload"
///|
fn wasmImportSetTokens(p0 : Int) = "moonplasma:host/plasmoids@0.1.0" "set-tokens"
///|
fn wasmImportRender(p0 : Int, p1 : Int, p2 : Int, p3 : Int) = "moonplasma:host/plasmoids@0.1.0" "render"
///|
fn wasmImportPopup(p0 : Int, p1 : Int) = "moonplasma:host/plasmoids@0.1.0" "popup"
///|
fn wasmImportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "moonplasma:host/plasmoids@0.1.0" "on-event"
///|
fn wasmImportPublishTable(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/plasmoids@0.1.0" "publish-table"
///|
fn wasmImportPublishState(p0 : Int, p1 : Int) = "moonplasma:host/plasmoids@0.1.0" "publish-state"
///|
fn wasmImportPublishSystem(p0 : Int, p1 : Int64, p2 : Int64, p3 : Int, p4 : Int, p5 : Int64, p6 : Int64, p7 : Int64, p8 : Int) = "moonplasma:host/plasmoids@0.1.0" "publish-system"
///|
fn wasmImportPublishWindows(p0 : Int, p1 : Int) = "moonplasma:host/plasmoids@0.1.0" "publish-windows"
///|
fn wasmImportNextRequest(p0 : Int) = "moonplasma:host/plasmoids@0.1.0" "next-request"
///|
fn wasmImportTakeFocusRequest(p0 : Int) = "moonplasma:host/plasmoids@0.1.0" "take-focus-request"
///|
fn wasmImportListWasmFiles(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/plasmoids@0.1.0" "list-wasm-files"
///|
fn wasmImportPickerStart() -> Int = "moonplasma:host/plasmoids@0.1.0" "picker-start"
///|
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_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
///|
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)
///|
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)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
#owned(str)
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_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)
@@ -0,0 +1,14 @@
import {
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
"moonplasma/desktop/interface/moonplasma/desktop/types" @types,
}
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,131 @@
// Generated by scripts/gen-native-stubs.py. Native stand-ins for the wasm-only ffi.mbt.
///|
fn wasmImportLoad(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportUnload(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportSetTokens(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportRender(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportPopup(p0 : Int, p1 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportPublishTable(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportPublishState(p0 : Int, p1 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportPublishSystem(p0 : Int, p1 : Int64, p2 : Int64, p3 : Int, p4 : Int, p5 : Int64, p6 : Int64, p7 : Int64, p8 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportPublishWindows(p0 : Int, p1 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportNextRequest(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportTakeFocusRequest(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportListWasmFiles(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportPickerStart() -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportPickerPoll(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn mbt_ffi_store8(offset : Int, value : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_load8_u(offset : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_malloc(size : Int) -> Int {
abort("wasm-only")
}
///|
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 {
abort("wasm-only")
}
///|
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_load64(offset : Int) -> Int64 {
abort("wasm-only")
}
@@ -0,0 +1,95 @@
// Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/interface/moonplasma/host/plasmoids"
import {
"moonplasma/desktop/interface/moonplasma/desktop/theme",
"moonplasma/desktop/interface/moonplasma/desktop/types",
}
// Values
pub fn list_wasm_files(String) -> Array[String]
pub fn load(String) -> Result[Loaded, String]
pub fn next_request() -> Request?
pub fn on_event(UInt32, Bool, @types.InputEvent) -> Bool
pub fn picker_poll() -> PickerState
pub fn picker_start() -> Bool
pub fn popup(UInt32) -> PopupSurface?
pub fn publish_state(Int32, Bool) -> Unit
pub fn publish_system(SystemSnapshot) -> Unit
pub fn publish_table(UInt32, FixedArray[Byte]) -> Unit
pub fn publish_windows(Array[WindowEntry]) -> Unit
pub fn render(UInt32, @types.Size) -> Array[@types.DrawOp]
pub fn set_tokens(@theme.Tokens) -> Unit
pub fn take_focus_request() -> UInt64?
pub fn unload(UInt32) -> Unit
// Errors
// Types and methods
pub(all) struct Loaded {
handle : UInt32
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
imports : Array[String]
}
pub(all) enum PickerState {
Open
Cancelled
Chosen(String)
}
pub(all) struct PopupSurface {
box : @types.Size
ops : Array[@types.DrawOp]
}
pub(all) enum Request {
Launch(String)
FocusWindow(Int32)
SetLayout(Int32)
SetInspector(Bool)
LoadModule(String)
UnloadInstance(String)
Browse
}
pub(all) struct SystemSnapshot {
cpu_permille : UInt32
mem_used_kib : UInt64
mem_total_kib : UInt64
battery_percent : Int32
charging : Bool
uptime_secs : UInt64
net_rx_bytes_per_sec : UInt64
net_tx_bytes_per_sec : UInt64
load_centi : UInt32
}
pub(all) struct WindowEntry {
id : UInt64
title : String
app_id : String
focused : Bool
}
// Type aliases
// Traits
+489
View File
@@ -0,0 +1,489 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
/// A loaded module. `imports` is its capability grant: the host interfaces its binary imports
/// (besides theme), e.g. ["clock"] or ["windows", "system"].
pub(all) struct Loaded {
handle : UInt; id : String; name : String; preferred : @types.Size; min_width : UInt; stretch : Bool; imports : Array[String]
}
///|
pub(all) struct PopupSurface {
box : @types.Size; ops : Array[@types.DrawOp]
}
///|
pub(all) struct SystemSnapshot {
cpu_permille : UInt; mem_used_kib : UInt64; mem_total_kib : UInt64; battery_percent : Int; charging : Bool; uptime_secs : UInt64; net_rx_bytes_per_sec : UInt64; net_tx_bytes_per_sec : UInt64; load_centi : UInt
}
///|
pub(all) struct WindowEntry {
id : UInt64; title : String; app_id : String; focused : Bool
}
///|
/// ---- what modules asked of the host ----
pub(all) enum Request {
Launch(String)
FocusWindow(Int)
SetLayout(Int)
SetInspector(Bool)
LoadModule(String)
UnloadInstance(String)
Browse
}
///|
/// A native file-chooser dialog (zenity on the host session) for "Add widget".
pub(all) enum PickerState {
Open
Cancelled
Chosen(String)
}
///|
/// Load the plasmoid component at `path`. The error is a short reason.
pub fn load(path : String) -> Result[Loaded, String] {
let ptr = mbt_ffi_str2ptr(path)
let return_area = mbt_ffi_malloc(48)
wasmImportLoad(ptr, path.length(), return_area);
let lifted = match (mbt_ffi_load8_u((return_area) + 0)) {
0 => {
let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12))
let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 16), mbt_ffi_load32((return_area) + 20))
let array : Array[String] = [];
for index = 0; index < (mbt_ffi_load32((return_area) + 44)); index = index + 1 {
let iter_base = (mbt_ffi_load32((return_area) + 40)) + (index * 8)
let result1 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4))
array.push(result1)
}
mbt_ffi_free(mbt_ffi_load32((return_area) + 40))
Result::Ok(Loaded::{handle : (mbt_ffi_load32((return_area) + 4)).reinterpret_as_uint(), id : result, name : result0, preferred : @types.Size::{w : (mbt_ffi_load32((return_area) + 24)).reinterpret_as_uint(), h : (mbt_ffi_load32((return_area) + 28)).reinterpret_as_uint()}, min_width : (mbt_ffi_load32((return_area) + 32)).reinterpret_as_uint(), stretch : (mbt_ffi_load8_u((return_area) + 36) != 0), imports : array})
}
1 => {
let result2 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 4), mbt_ffi_load32((return_area) + 8))
Result::Err(result2)
}
_ => panic()
}
let ret = lifted
mbt_ffi_free(ptr)
mbt_ffi_free(return_area)
return ret
}
///|
pub fn unload(handle : UInt) -> Unit {
wasmImportUnload((handle).reinterpret_as_int());
}
///|
/// The theme the modules see through `theme.get-tokens` (set before drawing so a swap shows at once).
pub fn set_tokens(t : @theme.Tokens) -> Unit {
let return_area = mbt_ffi_malloc(64)
let ptr = mbt_ffi_str2ptr((t).name)
mbt_ffi_store32((return_area) + 4, (t).name.length())
mbt_ffi_store32((return_area) + 0, ptr)
mbt_ffi_store8((return_area) + 8, ((((t).palette).desktop_top).r).to_int())
mbt_ffi_store8((return_area) + 9, ((((t).palette).desktop_top).g).to_int())
mbt_ffi_store8((return_area) + 10, ((((t).palette).desktop_top).b).to_int())
mbt_ffi_store8((return_area) + 11, ((((t).palette).desktop_top).a).to_int())
mbt_ffi_store8((return_area) + 12, ((((t).palette).desktop_bottom).r).to_int())
mbt_ffi_store8((return_area) + 13, ((((t).palette).desktop_bottom).g).to_int())
mbt_ffi_store8((return_area) + 14, ((((t).palette).desktop_bottom).b).to_int())
mbt_ffi_store8((return_area) + 15, ((((t).palette).desktop_bottom).a).to_int())
mbt_ffi_store8((return_area) + 16, ((((t).palette).surface).r).to_int())
mbt_ffi_store8((return_area) + 17, ((((t).palette).surface).g).to_int())
mbt_ffi_store8((return_area) + 18, ((((t).palette).surface).b).to_int())
mbt_ffi_store8((return_area) + 19, ((((t).palette).surface).a).to_int())
mbt_ffi_store8((return_area) + 20, ((((t).palette).surface_hover).r).to_int())
mbt_ffi_store8((return_area) + 21, ((((t).palette).surface_hover).g).to_int())
mbt_ffi_store8((return_area) + 22, ((((t).palette).surface_hover).b).to_int())
mbt_ffi_store8((return_area) + 23, ((((t).palette).surface_hover).a).to_int())
mbt_ffi_store8((return_area) + 24, ((((t).palette).surface_popup).r).to_int())
mbt_ffi_store8((return_area) + 25, ((((t).palette).surface_popup).g).to_int())
mbt_ffi_store8((return_area) + 26, ((((t).palette).surface_popup).b).to_int())
mbt_ffi_store8((return_area) + 27, ((((t).palette).surface_popup).a).to_int())
mbt_ffi_store8((return_area) + 28, ((((t).palette).foreground).r).to_int())
mbt_ffi_store8((return_area) + 29, ((((t).palette).foreground).g).to_int())
mbt_ffi_store8((return_area) + 30, ((((t).palette).foreground).b).to_int())
mbt_ffi_store8((return_area) + 31, ((((t).palette).foreground).a).to_int())
mbt_ffi_store8((return_area) + 32, ((((t).palette).foreground_muted).r).to_int())
mbt_ffi_store8((return_area) + 33, ((((t).palette).foreground_muted).g).to_int())
mbt_ffi_store8((return_area) + 34, ((((t).palette).foreground_muted).b).to_int())
mbt_ffi_store8((return_area) + 35, ((((t).palette).foreground_muted).a).to_int())
mbt_ffi_store8((return_area) + 36, ((((t).palette).accent).r).to_int())
mbt_ffi_store8((return_area) + 37, ((((t).palette).accent).g).to_int())
mbt_ffi_store8((return_area) + 38, ((((t).palette).accent).b).to_int())
mbt_ffi_store8((return_area) + 39, ((((t).palette).accent).a).to_int())
mbt_ffi_store8((return_area) + 40, ((((t).palette).accent_foreground).r).to_int())
mbt_ffi_store8((return_area) + 41, ((((t).palette).accent_foreground).g).to_int())
mbt_ffi_store8((return_area) + 42, ((((t).palette).accent_foreground).b).to_int())
mbt_ffi_store8((return_area) + 43, ((((t).palette).accent_foreground).a).to_int())
mbt_ffi_store8((return_area) + 44, ((((t).palette).border).r).to_int())
mbt_ffi_store8((return_area) + 45, ((((t).palette).border).g).to_int())
mbt_ffi_store8((return_area) + 46, ((((t).palette).border).b).to_int())
mbt_ffi_store8((return_area) + 47, ((((t).palette).border).a).to_int())
mbt_ffi_store32((return_area) + 48, ((t).font_size).reinterpret_as_int())
mbt_ffi_store32((return_area) + 52, ((t).radius).reinterpret_as_int())
mbt_ffi_store32((return_area) + 56, ((t).spacing).reinterpret_as_int())
mbt_ffi_store32((return_area) + 60, ((t).panel_height).reinterpret_as_int())
wasmImportSetTokens(return_area);
mbt_ffi_free(return_area)
mbt_ffi_free(ptr)
}
///|
pub fn render(handle : UInt, box : @types.Size) -> Array[@types.DrawOp] {
let return_area = mbt_ffi_malloc(8)
wasmImportRender((handle).reinterpret_as_int(), ((box).w).reinterpret_as_int(), ((box).h).reinterpret_as_int(), return_area);
let array : Array[@types.DrawOp] = [];
for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 {
let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 32)
let lifted = match (mbt_ffi_load8_u((iter_base) + 0)) {
0 => {
@types.DrawOp::FillRect(@types.FillRectOp::{rect : @types.Rect::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8), w : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), h : (mbt_ffi_load32((iter_base) + 16)).reinterpret_as_uint()}, color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 20)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 21)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 22)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 23)).to_byte()}, radius : (mbt_ffi_load32((iter_base) + 24)).reinterpret_as_uint()})
}
1 => {
@types.DrawOp::StrokeRect(@types.StrokeRectOp::{rect : @types.Rect::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8), w : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), h : (mbt_ffi_load32((iter_base) + 16)).reinterpret_as_uint()}, color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 20)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 21)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 22)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 23)).to_byte()}, width : (mbt_ffi_load32((iter_base) + 24)).reinterpret_as_uint(), radius : (mbt_ffi_load32((iter_base) + 28)).reinterpret_as_uint()})
}
2 => {
@types.DrawOp::Line(@types.LineOp::{start : @types.Point::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8)}, end : @types.Point::{x : mbt_ffi_load32((iter_base) + 12), y : mbt_ffi_load32((iter_base) + 16)}, color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 20)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 21)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 22)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 23)).to_byte()}, width : (mbt_ffi_load32((iter_base) + 24)).reinterpret_as_uint()})
}
3 => {
@types.DrawOp::Circle(@types.CircleOp::{center : @types.Point::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8)}, radius : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 16)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 17)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 18)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 19)).to_byte()}, filled : (mbt_ffi_load8_u((iter_base) + 20) != 0)})
}
4 => {
let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 12), mbt_ffi_load32((iter_base) + 16))
@types.DrawOp::Text(@types.TextOp::{origin : @types.Point::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8)}, text : result, style : @types.TextStyle::{size : (mbt_ffi_load32((iter_base) + 20)).reinterpret_as_uint(), color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 24)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 25)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 26)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 27)).to_byte()}, align : @types.TextAlign::from(mbt_ffi_load8_u((iter_base) + 28)), bold : (mbt_ffi_load8_u((iter_base) + 29) != 0)}})
}
5 => {
@types.DrawOp::PushClip(@types.Rect::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8), w : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), h : (mbt_ffi_load32((iter_base) + 16)).reinterpret_as_uint()})
}
6 => {
@types.DrawOp::PopClip
}
_ => panic()
}
array.push(lifted)
}
mbt_ffi_free(mbt_ffi_load32((return_area) + 0))
let ret = array
mbt_ffi_free(return_area)
return ret
}
///|
pub fn popup(handle : UInt) -> PopupSurface? {
let return_area = mbt_ffi_malloc(20)
wasmImportPopup((handle).reinterpret_as_int(), return_area);
let lifted0 : PopupSurface? = match mbt_ffi_load8_u((return_area) + 0) {
0 => Option::None
1 => {
let array : Array[@types.DrawOp] = [];
for index = 0; index < (mbt_ffi_load32((return_area) + 16)); index = index + 1 {
let iter_base = (mbt_ffi_load32((return_area) + 12)) + (index * 32)
let lifted = match (mbt_ffi_load8_u((iter_base) + 0)) {
0 => {
@types.DrawOp::FillRect(@types.FillRectOp::{rect : @types.Rect::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8), w : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), h : (mbt_ffi_load32((iter_base) + 16)).reinterpret_as_uint()}, color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 20)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 21)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 22)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 23)).to_byte()}, radius : (mbt_ffi_load32((iter_base) + 24)).reinterpret_as_uint()})
}
1 => {
@types.DrawOp::StrokeRect(@types.StrokeRectOp::{rect : @types.Rect::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8), w : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), h : (mbt_ffi_load32((iter_base) + 16)).reinterpret_as_uint()}, color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 20)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 21)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 22)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 23)).to_byte()}, width : (mbt_ffi_load32((iter_base) + 24)).reinterpret_as_uint(), radius : (mbt_ffi_load32((iter_base) + 28)).reinterpret_as_uint()})
}
2 => {
@types.DrawOp::Line(@types.LineOp::{start : @types.Point::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8)}, end : @types.Point::{x : mbt_ffi_load32((iter_base) + 12), y : mbt_ffi_load32((iter_base) + 16)}, color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 20)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 21)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 22)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 23)).to_byte()}, width : (mbt_ffi_load32((iter_base) + 24)).reinterpret_as_uint()})
}
3 => {
@types.DrawOp::Circle(@types.CircleOp::{center : @types.Point::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8)}, radius : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 16)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 17)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 18)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 19)).to_byte()}, filled : (mbt_ffi_load8_u((iter_base) + 20) != 0)})
}
4 => {
let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 12), mbt_ffi_load32((iter_base) + 16))
@types.DrawOp::Text(@types.TextOp::{origin : @types.Point::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8)}, text : result, style : @types.TextStyle::{size : (mbt_ffi_load32((iter_base) + 20)).reinterpret_as_uint(), color : @types.Color::{r : (mbt_ffi_load8_u((iter_base) + 24)).to_byte(), g : (mbt_ffi_load8_u((iter_base) + 25)).to_byte(), b : (mbt_ffi_load8_u((iter_base) + 26)).to_byte(), a : (mbt_ffi_load8_u((iter_base) + 27)).to_byte()}, align : @types.TextAlign::from(mbt_ffi_load8_u((iter_base) + 28)), bold : (mbt_ffi_load8_u((iter_base) + 29) != 0)}})
}
5 => {
@types.DrawOp::PushClip(@types.Rect::{x : mbt_ffi_load32((iter_base) + 4), y : mbt_ffi_load32((iter_base) + 8), w : (mbt_ffi_load32((iter_base) + 12)).reinterpret_as_uint(), h : (mbt_ffi_load32((iter_base) + 16)).reinterpret_as_uint()})
}
6 => {
@types.DrawOp::PopClip
}
_ => panic()
}
array.push(lifted)
}
mbt_ffi_free(mbt_ffi_load32((return_area) + 12))
Option::Some(PopupSurface::{box : @types.Size::{w : (mbt_ffi_load32((return_area) + 4)).reinterpret_as_uint(), h : (mbt_ffi_load32((return_area) + 8)).reinterpret_as_uint()}, ops : array})
}
_ => panic()
}
let ret = lifted0
mbt_ffi_free(return_area)
return ret
}
///|
/// Deliver an event to the module (`on-popup`: to its popup surface). True when it wants a redraw.
pub fn on_event(handle : UInt, on_popup : Bool, event : @types.InputEvent) -> Bool {
let cleanup_list : Array[Int] = []
let (lowered,lowered5,lowered6) = match event {
PointerMove(payload) => {
((0), (payload).x, (payload).y)
}
PointerDown(payload0) => {
((1), (payload0).x, (payload0).y)
}
PointerUp(payload1) => {
((2), (payload1).x, (payload1).y)
}
PointerLeave => {
((3), 0, 0)
}
FocusLost => {
((4), 0, 0)
}
KeyDown(payload4) => {
let ptr = mbt_ffi_str2ptr(payload4)
cleanup_list.push(ptr)
((5), ptr, payload4.length())
}
}
let result : Int = wasmImportOnEvent((handle).reinterpret_as_int(), (if on_popup { 1 } else { 0 }), lowered, lowered5, lowered6);
let ret = (result != 0)
cleanup_list.each(mbt_ffi_free)
return ret
}
///|
/// ---- host data modules read through their capabilities ----
/// Row tables, as built by compositor/wasm: a LE u32 row count, then per row each field as a LE
/// i32 ('i') or a LE u32 byte length + UTF-8 ('s'). `which`: 0 apps (sssss: id name comment
/// category glyph), 1 windows (isii: id title focused minimized), 2 layouts (s), 3 modules
/// (sssi: id name path loaded), 4 instances (sss: slot module name).
pub fn publish_table(which : UInt, rows : FixedArray[Byte]) -> Unit {
let ptr = mbt_ffi_bytes2ptr(rows)
wasmImportPublishTable((which).reinterpret_as_int(), ptr, rows.length());
mbt_ffi_free(ptr)
}
///|
/// Layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on.
pub fn publish_state(layout_mode : Int, inspector_on : Bool) -> Unit {
wasmImportPublishState(layout_mode, (if inspector_on { 1 } else { 0 }));
}
///|
pub fn publish_system(s : SystemSnapshot) -> Unit {
wasmImportPublishSystem(((s).cpu_permille).reinterpret_as_int(), ((s).mem_used_kib).reinterpret_as_int64(), ((s).mem_total_kib).reinterpret_as_int64(), (s).battery_percent, (if (s).charging { 1 } else { 0 }), ((s).uptime_secs).reinterpret_as_int64(), ((s).net_rx_bytes_per_sec).reinterpret_as_int64(), ((s).net_tx_bytes_per_sec).reinterpret_as_int64(), ((s).load_centi).reinterpret_as_int());
}
///|
pub fn publish_windows(wins : Array[WindowEntry]) -> Unit {
let cleanup_list : Array[Int] = []
let address = mbt_ffi_malloc((wins).length() * 32);
for index = 0; index < (wins).length(); index = index + 1 {
let iter_elem : WindowEntry = (wins)[(index)]
let iter_base = address + (index * 32);
mbt_ffi_store64((iter_base) + 0, ((iter_elem).id).reinterpret_as_int64())
let ptr = mbt_ffi_str2ptr((iter_elem).title)
mbt_ffi_store32((iter_base) + 12, (iter_elem).title.length())
mbt_ffi_store32((iter_base) + 8, ptr)
let ptr0 = mbt_ffi_str2ptr((iter_elem).app_id)
mbt_ffi_store32((iter_base) + 20, (iter_elem).app_id.length())
mbt_ffi_store32((iter_base) + 16, ptr0)
mbt_ffi_store8((iter_base) + 24, (if (iter_elem).focused { 1 } else { 0 }))
cleanup_list.push(ptr)
cleanup_list.push(ptr0)
}
wasmImportPublishWindows(address, (wins).length());
mbt_ffi_free(address)
cleanup_list.each(mbt_ffi_free)
}
///|
/// The next pending request, oldest first.
pub fn next_request() -> Request? {
let return_area = mbt_ffi_malloc(16)
wasmImportNextRequest(return_area);
let lifted2 : Request? = match mbt_ffi_load8_u((return_area) + 0) {
0 => Option::None
1 => {
let lifted = match (mbt_ffi_load8_u((return_area) + 4)) {
0 => {
let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12))
Request::Launch(result)
}
1 => {
Request::FocusWindow(mbt_ffi_load32((return_area) + 8))
}
2 => {
Request::SetLayout(mbt_ffi_load32((return_area) + 8))
}
3 => {
Request::SetInspector((mbt_ffi_load8_u((return_area) + 8) != 0))
}
4 => {
let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12))
Request::LoadModule(result0)
}
5 => {
let result1 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12))
Request::UnloadInstance(result1)
}
6 => {
Request::Browse
}
_ => panic()
}
Option::Some(lifted)
}
_ => panic()
}
let ret = lifted2
mbt_ffi_free(return_area)
return ret
}
///|
/// A window a module asked to focus through `windows.focus` (64-bit id), since the last call.
pub fn take_focus_request() -> UInt64? {
let return_area = mbt_ffi_malloc(16)
wasmImportTakeFocusRequest(return_area);
let lifted : UInt64? = match mbt_ffi_load8_u((return_area) + 0) {
0 => Option::None
1 => {
Option::Some((mbt_ffi_load64((return_area) + 8)).reinterpret_as_uint64())
}
_ => panic()
}
let ret = lifted
mbt_ffi_free(return_area)
return ret
}
///|
/// Names of the `*.wasm` files directly in `dir`, sorted.
pub fn list_wasm_files(dir : String) -> Array[String] {
let ptr = mbt_ffi_str2ptr(dir)
let return_area = mbt_ffi_malloc(8)
wasmImportListWasmFiles(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 picker_start() -> Bool {
let result : Int = wasmImportPickerStart();
let ret = (result != 0)
return ret
}
///|
pub fn picker_poll() -> PickerState {
let return_area = mbt_ffi_malloc(12)
wasmImportPickerPoll(return_area);
let lifted = match (mbt_ffi_load8_u((return_area) + 0)) {
0 => {
PickerState::Open
}
1 => {
PickerState::Cancelled
}
2 => {
let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 4), mbt_ffi_load32((return_area) + 8))
PickerState::Chosen(result)
}
_ => panic()
}
let ret = lifted
mbt_ffi_free(return_area)
return ret
}
+19 -19
View File
@@ -73,8 +73,12 @@ 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"
///|
#owned(bytes)
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int =
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)
///|
@@ -85,10 +89,21 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#| local.get 0)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
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)
///|
extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] =
#|(func (param i32) (param i32) (result i32)
@@ -96,18 +111,3 @@ 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_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)
+13 -13
View File
@@ -121,12 +121,7 @@ fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
}
///|
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String {
fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only")
}
@@ -136,12 +131,7 @@ fn mbt_ffi_str2ptr(str : String) -> Int {
}
///|
fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String {
abort("wasm-only")
}
@@ -151,6 +141,16 @@ fn mbt_ffi_malloc(size : Int) -> Int {
}
///|
fn mbt_ffi_free(position : Int) -> Unit {
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] {
abort("wasm-only")
}
+6 -1
View File
@@ -21,7 +21,12 @@ for m in re.finditer(r'^extern "wasm" fn (\w+)\(([^)]*)\)\s*(->\s*[^=\n]+?)?\s*=
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"
# Keep the package's imports (generated types it refers to) when it has any.
old = (d / "moon.pkg").read_text() if (d / "moon.pkg").exists() else ""
imports = ""
if old.lstrip().startswith("import {"):
imports = old[: old.index("}") + 1] + "\n\n"
(d / "moon.pkg").write_text(imports + """warnings = "-44"
// ffi.mbt is generated and wasm-only; native builds use native_stub.mbt (scripts/gen-native-stubs.py).
options(
+1
View File
@@ -0,0 +1 @@
../../../theme.wit
+1
View File
@@ -0,0 +1 @@
../../../types.wit
+96
View File
@@ -0,0 +1,96 @@
package moonplasma:host@0.1.0;
/// Panel modules (plasmoids) for a compositor that is itself a component. A component can't embed
/// a second wasm runtime, so the host runs the modules (wasmtime) and the compositor drives them
/// through this interface. It mirrors compositor/wasm: load, draw, events, plus the host data a
/// module may read and the requests it may make.
interface plasmoids {
use moonplasma:desktop/types@0.1.0.{draw-op, input-event, size};
use moonplasma:desktop/theme@0.1.0.{tokens};
/// A loaded module. `imports` is its capability grant: the host interfaces its binary imports
/// (besides theme), e.g. ["clock"] or ["windows", "system"].
record loaded {
handle: u32,
id: string,
name: string,
preferred: size,
min-width: u32,
stretch: bool,
imports: list<string>,
}
/// Load the plasmoid component at `path`. The error is a short reason.
load: func(path: string) -> result<loaded, string>;
unload: func(handle: u32);
/// The theme the modules see through `theme.get-tokens` (set before drawing so a swap shows at once).
set-tokens: func(t: tokens);
render: func(handle: u32, box: size) -> list<draw-op>;
record popup-surface {
box: size,
ops: list<draw-op>,
}
popup: func(handle: u32) -> option<popup-surface>;
/// Deliver an event to the module (`on-popup`: to its popup surface). True when it wants a redraw.
on-event: func(handle: u32, on-popup: bool, event: input-event) -> bool;
// ---- host data modules read through their capabilities ----
/// Row tables, as built by compositor/wasm: a LE u32 row count, then per row each field as a LE
/// i32 ('i') or a LE u32 byte length + UTF-8 ('s'). `which`: 0 apps (sssss: id name comment
/// category glyph), 1 windows (isii: id title focused minimized), 2 layouts (s), 3 modules
/// (sssi: id name path loaded), 4 instances (sss: slot module name).
publish-table: func(which: u32, rows: list<u8>);
/// Layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on.
publish-state: func(layout-mode: s32, inspector-on: bool);
record system-snapshot {
cpu-permille: u32,
mem-used-kib: u64,
mem-total-kib: u64,
battery-percent: s32,
charging: bool,
uptime-secs: u64,
net-rx-bytes-per-sec: u64,
net-tx-bytes-per-sec: u64,
load-centi: u32,
}
publish-system: func(s: system-snapshot);
record window-entry {
id: u64,
title: string,
app-id: string,
focused: bool,
}
publish-windows: func(wins: list<window-entry>);
// ---- what modules asked of the host ----
variant request {
launch(string),
focus-window(s32),
set-layout(s32),
set-inspector(bool),
load-module(string),
unload-instance(string),
browse,
}
/// The next pending request, oldest first.
next-request: func() -> option<request>;
/// A window a module asked to focus through `windows.focus` (64-bit id), since the last call.
take-focus-request: func() -> option<u64>;
/// Names of the `*.wasm` files directly in `dir`, sorted.
list-wasm-files: func(dir: string) -> list<string>;
/// A native file-chooser dialog (zenity on the host session) for "Add widget".
variant picker-state {
open,
cancelled,
chosen(string),
}
picker-start: func() -> bool;
picker-poll: func() -> picker-state;
}
+1
View File
@@ -75,6 +75,7 @@ interface font {
world compositor {
import sys;
import font;
import plasmoids;
/// Run the compositor until it exits. `args` are the command-line arguments (without argv[0]).
export run: func(args: list<string>) -> s32;
}
+16
View File
@@ -59,3 +59,19 @@ world module-manager-widget {
include widget;
import modules;
}
/// Everything a panel module can be granted. The native host instantiates any module against this
/// one world (a module simply imports the subset it uses) and serves each import from the data the
/// compositor publishes (wit/host/plasmoids.wit).
world plasmoid-host {
import theme;
import clock;
import app-catalog;
import app-launch;
import windows;
import layout-control;
import inspector;
import modules;
import system;
export plasmoid;
}