Panel modules in the wasm compositor: the host runs them (moonplasma:host/plasmoids)
CI / test (push) Failing after 46s
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:
1 parent
5c3bebc7fd
commit
e769566d8f
23 files changed
+2001
-302
No files matched your search
+17
-11
@@ -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).
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user