Files
chandra/compositor/wasm/wasm_stub.c
T
Claude 88915842c2
CI / test (push) Failing after 18s
Battery panel module: charge, charging state, time left, low-battery warning
- New `battery` panel module (components/battery, logic in lib/battery): a battery icon filled to
  the charge with the percentage and time remaining ("73% 2:05"; time to full while charging).
  The fill turns green when charging or full, amber at 20 % and below, and at 10 % the whole
  button turns red and a "Battery low" popup opens by itself, once per discharge spell. A click
  opens the details (charge, state, time left in words). Without a battery it shows a plug.
- Right-click "Module settings": Show percentage, Show time remaining, and Without a battery
  (Show a plug / Show nothing). Saved per module in state.edn like the clocks' settings.
- New `battery` capability (wit/capabilities.wit: read -> status {percent, charge-state,
  secs-left}). Served by the wasmer stub (host ints 7-9), host-wasm and wasmhost (publish-battery).
- Host side (compositor/shell/battery.mbt): reads /sys/class/power_supply, every battery
  together (energy_* / power_now, or charge_* / current_now; capacity when that is all there
  is; device-scope batteries like mice are skipped). The `system` snapshot the Power tab uses
  now reads the battery through the same code. Time left follows a running average of the
  rate, starting over when the state changes.
- A fresh panel gets the battery module before the clock only on a machine with a battery.
- wasm_stub: MAX_INST 512 -> 2048. The host test binary creates ~70 compositors without
  unloading their modules; at 512 the last tests' panels came up half empty.
- Tests: sysfs reading against a fake power supply (energy and charge units, two packs,
  charging, full, capacity only, no battery), the running average, the module in the panel
  (text, settings, click, the critical warning, the plug), the rendering logic, and a
  host-wasm test of the module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hky51dmaUqiYW746Gz
2026-11-25 19:53:42 +00:00

854 lines
34 KiB
C

/* Wasm plasmoid host: runs the core module of a chandra plasmoid component
* (or a bare core module) with wasmer's C API. Canonical-ABI marshalling stays in
* MoonBit; this file instantiates, provides the host imports (theme, clock) and
* exposes raw calls plus guest-memory reads. */
#include <fcntl.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <dirent.h>
#include <wasm.h>
#include "moonbit.h"
#define MAX_INST 2048
enum { EX_INFO, EX_RENDER, EX_ONEVENT, EX_POPUP, EX_POST_INFO, EX_POST_RENDER, EX_POST_POPUP, EX_REALLOC,
EX_CFG_ITEMS, EX_POST_CFG_ITEMS, EX_SET_CFG, EX_N };
static const char *ex_names[EX_N] = {
"chandra:desktop/plasmoid@0.1.0#info",
"chandra:desktop/plasmoid@0.1.0#render",
"chandra:desktop/plasmoid@0.1.0#on-event",
"chandra:desktop/plasmoid@0.1.0#popup",
"cabi_post_chandra:desktop/plasmoid@0.1.0#info",
"cabi_post_chandra:desktop/plasmoid@0.1.0#render",
"cabi_post_chandra:desktop/plasmoid@0.1.0#popup",
"cabi_realloc",
/* optional: chandra:desktop/module-config (the module's own right-click settings) */
"chandra:desktop/module-config@0.1.0#config-items",
"cabi_post_chandra:desktop/module-config@0.1.0#config-items",
"chandra:desktop/module-config@0.1.0#set-config",
};
typedef struct Inst {
int used;
wasm_module_t *module;
wasm_instance_t *instance;
wasm_memory_t *memory;
wasm_func_t *ex[EX_N];
uint8_t tokens[64];
int kind_n;
char imports[512]; /* newline-separated host interfaces this module imports (capabilities it uses) */
} Inst;
static wasm_engine_t *engine;
static wasm_store_t *store;
static Inst insts[MAX_INST];
/* Host imports a module can call. */
enum {
K_OTHER, K_TOKENS, K_CLOCK, K_APPS, K_LAUNCH, K_WINDOWS, K_FOCUS, K_LAYOUTS, K_LAYOUT_CUR, K_SET_LAYOUT,
K_INSPECT_IS_ON, K_INSPECT_SET, K_MOD_AVAILABLE, K_MOD_LOADED, K_MOD_LOAD, K_MOD_UNLOAD, K_MOD_BROWSE,
K_SYSTEM_READ, K_WIN_ALL, K_WIN_FOCUS_ID, K_LOGOUT, K_WALLPAPERS, K_WALLPAPER_CUR, K_SET_WALLPAPER,
K_SESSION_SETTINGS, K_SESSION_IS_ON, K_SESSION_SET,
K_APP_ICON,
K_SHOT_TAKE, K_SHOT_RECORD, K_SHOT_STOP, K_SHOT_IS_REC, K_SHOT_PTR, K_SHOT_SET_PTR,
K_PW_SCREEN, K_PW_SET_SCREEN, K_PW_SUSP, K_PW_SET_SUSP, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT,
K_BAT_READ
};
typedef struct Env { Inst *inst; int kind; } Env;
/* ---- host data the shell publishes before calling a guest ----
* A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS, T_N };
typedef struct { uint8_t *data; size_t len; } Blob;
static Blob tables[T_N];
static int32_t host_ints[12] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
4 screenshot state (bit 0 recording, bit 1 pointer in recordings),
5 screen-off minutes, 6 suspend minutes (0: never),
7 battery percent (-1: none), 8 battery charge-state, 9 battery seconds left */
/* ---- requests a guest made of the host (launch, focus, ...) ; drained by the shell after each call ---- */
typedef struct { int kind; int32_t n; char *s; } Req;
#define MAX_REQ 64
static Req reqs[MAX_REQ];
static int req_head, req_tail;
static Req cur_req;
static void push_req(int kind, int32_t n, const char *s) {
if (req_tail - req_head >= MAX_REQ) return;
Req *r = &reqs[req_tail % MAX_REQ];
r->kind = kind;
r->n = n;
r->s = s ? strdup(s) : NULL;
req_tail++;
}
/* Host state a widget may read through its granted interfaces. The compositor refreshes
* these (mp_wasm_set_system / mp_wasm_set_windows) before drawing; widgets never touch
* /proc or the window manager themselves. */
static uint8_t g_system[64]; /* canonical-ABI bytes of system.snapshot */
static uint8_t *g_windows; /* count u32, then per window: id u64, focused u32, tlen u32, title u16[], alen u32, app u16[] */
static size_t g_windows_len;
static int64_t g_focus_req = -1; /* window id a widget asked to raise, until the compositor takes it */
static void mem_write(Inst *in, int32_t off, const void *src, size_t n) {
if (!in->memory || off < 0) return;
byte_t *base = wasm_memory_data(in->memory);
size_t size = wasm_memory_data_size(in->memory);
if ((size_t)off + n > size) return;
memcpy(base + off, src, n);
}
static int mem_read(Inst *in, int32_t off, void *dst, size_t n) {
if (!in->memory || off < 0) return 0;
size_t size = wasm_memory_data_size(in->memory);
if ((size_t)off + n > size) return 0;
memcpy(dst, wasm_memory_data(in->memory) + off, n);
return 1;
}
static void w32(Inst *in, int32_t off, int32_t v) { mem_write(in, off, &v, 4); }
/* Allocate in the guest through its cabi_realloc; -1 on failure. */
static int32_t guest_alloc(Inst *in, int32_t size, int32_t align) {
if (!in->ex[EX_REALLOC]) return -1;
if (size < 4) size = 4; /* the guest frees every lowered buffer, even empty ones */
wasm_val_t av[4] = { WASM_I32_VAL(0), WASM_I32_VAL(0), WASM_I32_VAL(align), WASM_I32_VAL(size) };
wasm_val_t rv[1] = { WASM_INIT_VAL };
wasm_val_vec_t a = { 4, av };
wasm_val_vec_t r = { 1, rv };
wasm_trap_t *tr = wasm_func_call(in->ex[EX_REALLOC], &a, &r);
if (tr) { wasm_trap_delete(tr); return -1; }
return rv[0].of.i32;
}
/* UTF-8 -> UTF-16LE string in guest memory; writes ptr/len (code units) at `at` and `at+4`. */
static void put_str(Inst *in, int32_t at, const uint8_t *u8, size_t n) {
size_t units = 0;
for (size_t i = 0; i < n;) {
uint8_t c = u8[i];
int len = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;
units += len == 4 ? 2 : 1;
i += len;
}
int32_t ptr = guest_alloc(in, (int32_t)(units * 2), 2);
if (ptr < 0) { w32(in, at, 0); w32(in, at + 4, 0); return; }
uint16_t *buf = (uint16_t *)malloc(units * 2 + 2);
size_t k = 0;
for (size_t i = 0; i < n && k < units;) {
uint8_t c = u8[i];
uint32_t cp;
int len;
if (c < 0x80) { cp = c; len = 1; }
else if (c < 0xE0) { cp = c & 0x1F; len = 2; }
else if (c < 0xF0) { cp = c & 0x0F; len = 3; }
else { cp = c & 0x07; len = 4; }
for (int j = 1; j < len && i + j < n; j++) cp = (cp << 6) | (u8[i + j] & 0x3F);
i += len;
if (cp >= 0x10000) {
cp -= 0x10000;
buf[k++] = (uint16_t)(0xD800 + (cp >> 10));
if (k < units) buf[k++] = (uint16_t)(0xDC00 + (cp & 0x3FF));
} else {
buf[k++] = (uint16_t)cp;
}
}
mem_write(in, ptr, buf, units * 2);
free(buf);
w32(in, at, ptr);
w32(in, at + 4, (int32_t)units);
}
/* A guest UTF-16 string -> malloc'd UTF-8 (NUL-terminated). */
static char *guest_str(Inst *in, int32_t ptr, int32_t units) {
if (units < 0 || units > 4096) units = 0;
uint16_t *u = (uint16_t *)malloc((size_t)units * 2 + 2);
if (units > 0 && !mem_read(in, ptr, u, (size_t)units * 2)) units = 0;
char *out = (char *)malloc((size_t)units * 3 + 1);
size_t o = 0;
for (int i = 0; i < units; i++) {
uint32_t cp = u[i];
if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < units) { cp = 0x10000 + ((cp - 0xD800) << 10) + (u[i + 1] - 0xDC00); i++; }
if (cp < 0x80) out[o++] = (char)cp;
else if (cp < 0x800) { out[o++] = (char)(0xC0 | (cp >> 6)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
else if (cp < 0x10000) { out[o++] = (char)(0xE0 | (cp >> 12)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
else { out[o++] = (char)(0xF0 | (cp >> 18)); out[o++] = (char)(0x80 | ((cp >> 12) & 0x3F)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
}
out[o] = 0;
free(u);
return out;
}
static uint32_t rd_u32(const uint8_t *p) { uint32_t v; memcpy(&v, p, 4); return v; }
/* Lower table `t` (row layout `spec`: 'i' or 's' per field) as a list<record> and write (ptr,len) at `retptr`. */
static void build_list(Inst *in, int t, const char *spec, int32_t retptr) {
Blob *b = &tables[t];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t esz = 0;
for (const char *c = spec; *c; c++) esz += *c == 's' ? 8 : 4;
int32_t base = guest_alloc(in, (int32_t)(esz * (n ? n : 1)), 4);
if (base < 0) { w32(in, retptr, 0); w32(in, retptr + 4, 0); return; }
size_t pos = 4;
for (uint32_t r = 0; r < n; r++) {
int32_t off = base + (int32_t)(r * esz);
for (const char *c = spec; *c; c++) {
if (*c == 'i') {
if (pos + 4 > b->len) return;
w32(in, off, (int32_t)rd_u32(b->data + pos));
pos += 4;
off += 4;
} else {
if (pos + 4 > b->len) return;
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl > b->len) return;
put_str(in, off, b->data + pos, sl);
pos += sl;
off += 8;
}
}
}
w32(in, retptr, base);
w32(in, retptr + 4, (int32_t)n);
}
/* Does table `t` (first field a string) contain a row whose first string equals `id`? */
static int table_has_id(int t, const char *spec, const char *id) {
Blob *b = &tables[t];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t pos = 4;
size_t idl = strlen(id);
for (uint32_t r = 0; r < n; r++) {
for (const char *c = spec; *c; c++) {
if (pos + 4 > b->len) return 0;
if (*c == 'i') { pos += 4; continue; }
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl > b->len) return 0;
if (c == spec && sl == idl && memcmp(b->data + pos, id, sl) == 0) return 1;
pos += sl;
}
}
return 0;
}
/* The image handle table T_ICONS ("si": app id, handle) holds for `id`, or 0. */
static int32_t icon_for(const char *id) {
Blob *b = &tables[T_ICONS];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t pos = 4, idl = strlen(id);
for (uint32_t r = 0; r < n; r++) {
if (pos + 4 > b->len) return 0;
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl + 4 > b->len) return 0;
int hit = sl == idl && memcmp(b->data + pos, id, sl) == 0;
pos += sl;
int32_t h = (int32_t)rd_u32(b->data + pos);
pos += 4;
if (hit) return h;
}
return 0;
}
static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_vec_t *results) {
Env *e = (Env *)env;
Inst *in = e->inst;
int32_t a0 = args->size >= 1 ? args->data[0].of.i32 : 0;
int32_t a1 = args->size >= 2 ? args->data[1].of.i32 : 0;
int32_t a2 = args->size >= 3 ? args->data[2].of.i32 : 0;
switch (e->kind) {
case K_TOKENS:
if (args->size >= 1) {
uint8_t buf[64];
memcpy(buf, in->tokens, 64);
/* name: the guest lifts it as one of its own allocations, so give it a real (empty) one */
memset(buf, 0, 8);
int32_t p = guest_alloc(in, 0, 2);
if (p >= 0) memcpy(buf, &p, 4);
mem_write(in, a0, buf, 64);
}
break;
case K_CLOCK:
if (args->size >= 1) {
time_t t = time(NULL);
struct tm tmv;
localtime_r(&t, &tmv);
uint8_t buf[12];
memset(buf, 0, sizeof(buf));
int32_t year = tmv.tm_year + 1900;
memcpy(buf, &year, 4);
buf[4] = (uint8_t)(tmv.tm_mon + 1);
buf[5] = (uint8_t)tmv.tm_mday;
buf[6] = (uint8_t)tmv.tm_hour;
buf[7] = (uint8_t)tmv.tm_min;
buf[8] = (uint8_t)tmv.tm_sec;
buf[9] = (uint8_t)tmv.tm_wday;
mem_write(in, a0, buf, 12);
}
break;
case K_APPS: build_list(in, T_APPS, "sssss", a0); break; /* id name comment category glyph */
case K_WINDOWS: build_list(in, T_WINDOWS, "isii", a0); break;
case K_LAYOUTS: build_list(in, T_LAYOUTS, "s", a0); break;
case K_WALLPAPERS: build_list(in, T_WALLPAPERS, "s", a0); break;
case K_SESSION_SETTINGS: build_list(in, T_SESSION_SETTINGS, "s", a0); break;
case K_MOD_AVAILABLE: build_list(in, T_MODULES, "sssi", a0); break;
case K_MOD_LOADED: build_list(in, T_INSTANCES, "sss", a0); break;
case K_LAYOUT_CUR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[0]);
break;
case K_WALLPAPER_CUR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[2]);
break;
case K_SESSION_IS_ON:
if (results->size >= 1)
results->data[0] = (wasm_val_t)WASM_I32_VAL(a0 >= 0 && a0 < 32 ? (int32_t)(((uint32_t)host_ints[3] >> a0) & 1u) : 0);
break;
case K_INSPECT_IS_ON:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[1]);
break;
case K_SET_LAYOUT: push_req(3, a0, NULL); break;
case K_FOCUS: push_req(2, a0, NULL); break;
case K_LOGOUT: push_req(8, 0, NULL); break;
case K_SET_WALLPAPER: push_req(9, a0, NULL); break;
case K_SESSION_SET: push_req(a1 ? 11 : 10, a0, NULL); break; /* 10 off, 11 on */
/* Request 12 carries the screenshot code: 0-3 take, 10-12 record, 20 stop, 30/31 pointer. */
case K_SHOT_TAKE: if (a0 >= 0 && a0 <= 3) push_req(12, a0, NULL); break;
case K_SHOT_RECORD: if (a0 >= 0 && a0 <= 2) push_req(12, 10 + a0, NULL); break;
case K_SHOT_STOP: push_req(12, 20, NULL); break;
case K_SHOT_SET_PTR: push_req(12, a0 ? 31 : 30, NULL); break;
case K_PW_SCREEN:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[5]);
break;
case K_PW_SUSP:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[6]);
break;
case K_PW_SET_SCREEN: push_req(13, a0, NULL); break;
case K_PW_SET_SUSP: push_req(14, a0, NULL); break;
case K_PW_SUSPEND: push_req(15, 0, NULL); break; /* 15: power action n (0 suspend, 1 off, 2 restart) */
case K_PW_OFF: push_req(15, 1, NULL); break;
case K_PW_REBOOT: push_req(15, 2, NULL); break;
case K_SHOT_IS_REC:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[4] & 1);
break;
case K_SHOT_PTR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL((host_ints[4] >> 1) & 1);
break;
case K_INSPECT_SET: push_req(4, a0, NULL); break;
case K_MOD_BROWSE: push_req(7, 0, NULL); break;
case K_MOD_LOAD: { char *s = guest_str(in, a0, a1); push_req(5, 0, s); free(s); break; }
case K_MOD_UNLOAD: { char *s = guest_str(in, a0, a1); push_req(6, 0, s); free(s); break; }
case K_LAUNCH: {
/* launch(id) -> result<_, string>; (ptr, len, retptr). Known catalog ids succeed; the shell spawns after the call. */
char *id = guest_str(in, a0, a1);
if (table_has_id(T_APPS, "sssss", id)) {
push_req(1, 0, id);
w32(in, a2, 0);
} else {
w32(in, a2, 1);
const char *msg = "unknown application";
put_str(in, a2 + 4, (const uint8_t *)msg, strlen(msg));
}
free(id);
break;
}
case K_APP_ICON: {
/* app-icon(app-id) -> u32; (ptr, len) */
char *id = guest_str(in, a0, a1);
int32_t h = id ? icon_for(id) : 0;
free(id);
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(h);
break;
}
case K_BAT_READ: {
/* battery.status: percent s32 @0, charge-state u8 @4, secs-left u32 @8 */
uint8_t st[12] = {0};
int32_t state = host_ints[8] >= 0 && host_ints[8] <= 4 ? host_ints[8] : 0;
memcpy(st, &host_ints[7], 4);
st[4] = (uint8_t)state;
memcpy(st + 8, &host_ints[9], 4);
if (args->size >= 1) mem_write(in, a0, st, 12);
break;
}
case K_SYSTEM_READ:
if (args->size >= 1) mem_write(in, a0, g_system, 64);
break;
case K_WIN_ALL: {
int32_t ret = a0;
uint32_t count = 0;
if (g_windows && g_windows_len >= 4) memcpy(&count, g_windows, 4);
if (count > 64) count = 64;
/* always a real allocation, even for an empty list: the guest frees it after lifting */
int32_t arr = guest_alloc(in, (int32_t)((count ? count : 1) * 32), 8);
size_t pos = 4;
uint32_t written = 0;
for (uint32_t i = 0; arr >= 0 && i < count; i++) {
uint64_t id; uint32_t focused, tlen, alen;
if (pos + 16 > g_windows_len) break;
memcpy(&id, g_windows + pos, 8); memcpy(&focused, g_windows + pos + 8, 4); memcpy(&tlen, g_windows + pos + 12, 4);
pos += 16;
if (tlen > 512 || pos + tlen * 2 + 4 > g_windows_len) break;
const uint8_t *title = g_windows + pos;
pos += tlen * 2;
memcpy(&alen, g_windows + pos, 4);
pos += 4;
if (alen > 512 || pos + alen * 2 > g_windows_len) break;
const uint8_t *app = g_windows + pos;
pos += alen * 2;
int32_t tp = tlen ? guest_alloc(in, (int32_t)(tlen * 2), 2) : 0;
int32_t ap = alen ? guest_alloc(in, (int32_t)(alen * 2), 2) : 0;
if (tlen && tp > 0) mem_write(in, tp, title, tlen * 2);
if (alen && ap > 0) mem_write(in, ap, app, alen * 2);
uint8_t rec[32];
memset(rec, 0, sizeof(rec));
int32_t tl = tp > 0 ? (int32_t)tlen : 0, al = ap > 0 ? (int32_t)alen : 0;
if (tp < 0) tp = 0;
if (ap < 0) ap = 0;
memcpy(rec, &id, 8); memcpy(rec + 8, &tp, 4); memcpy(rec + 12, &tl, 4);
memcpy(rec + 16, &ap, 4); memcpy(rec + 20, &al, 4); rec[24] = focused ? 1 : 0;
mem_write(in, arr + (int32_t)(i * 32), rec, 32);
written++;
}
int32_t out[2] = { arr >= 0 ? arr : 0, arr >= 0 ? (int32_t)written : 0 };
mem_write(in, ret, out, 8);
break;
}
case K_WIN_FOCUS_ID:
if (args->size >= 1) g_focus_req = args->data[0].of.i64;
break;
default: break;
}
return NULL;
}
static int leb(const uint8_t *p, size_t n, size_t *pos, uint32_t *out) {
uint32_t v = 0; int shift = 0;
while (*pos < n) {
uint8_t b = p[(*pos)++];
v |= (uint32_t)(b & 0x7f) << shift;
if (!(b & 0x80)) { *out = v; return 1; }
shift += 7;
if (shift > 28) return 0;
}
return 0;
}
static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len);
/* Components wrap their core modules in type-1 sections; try each until one yields a plasmoid. */
static int load_bytes(Inst *in, const uint8_t *d, size_t n) {
if (n < 8 || memcmp(d, "\0asm", 4) != 0) return -1;
if (d[4] == 1) return try_instantiate(in, d, n) ? 0 : -3;
size_t pos = 8;
while (pos < n) {
uint8_t id = d[pos++];
uint32_t size;
if (!leb(d, n, &pos, &size) || pos + size > n) return -1;
if (id == 1 && size >= 8 && memcmp(d + pos, "\0asm", 4) == 0) {
if (try_instantiate(in, d + pos, size)) return 0;
}
pos += size;
}
return -4;
}
/* "chandra:desktop/<iface>@<ver>" -> <iface> (copied, NUL-terminated); "" for anything else. */
static void iface_of(const wasm_name_t *m, char *out, size_t cap) {
const char *pre = "chandra:desktop/";
size_t pl = strlen(pre);
out[0] = 0;
if (m->size <= pl || memcmp(m->data, pre, pl) != 0) return;
size_t n = 0;
while (pl + n < m->size && m->data[pl + n] != '@' && n + 1 < cap) { out[n] = m->data[pl + n]; n++; }
out[n] = 0;
}
static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
char iface[64], fn[64];
iface_of(m, iface, sizeof(iface));
size_t fl = f->size < sizeof(fn) - 1 ? f->size : sizeof(fn) - 1;
memcpy(fn, f->data, fl);
fn[fl] = 0;
if (!strcmp(iface, "theme") && !strcmp(fn, "get-tokens")) return K_TOKENS;
if (!strcmp(iface, "clock") && !strcmp(fn, "now")) return K_CLOCK;
if (!strcmp(iface, "app-catalog") && !strcmp(fn, "list-apps")) return K_APPS;
if (!strcmp(iface, "app-launch") && !strcmp(fn, "launch")) return K_LAUNCH;
if (!strcmp(iface, "windows") && !strcmp(fn, "list-windows")) return K_WINDOWS;
if (!strcmp(iface, "windows") && !strcmp(fn, "focus-window")) return K_FOCUS;
if (!strcmp(iface, "windows") && !strcmp(fn, "all")) return K_WIN_ALL;
if (!strcmp(iface, "windows") && !strcmp(fn, "focus")) return K_WIN_FOCUS_ID;
if (!strcmp(iface, "system") && !strcmp(fn, "read")) return K_SYSTEM_READ;
if (!strcmp(iface, "battery") && !strcmp(fn, "read")) return K_BAT_READ;
if (!strcmp(iface, "icons") && !strcmp(fn, "app-icon")) return K_APP_ICON;
if (!strcmp(iface, "session") && !strcmp(fn, "logout")) return K_LOGOUT;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "wallpapers")) return K_WALLPAPERS;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "current-wallpaper")) return K_WALLPAPER_CUR;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "set-wallpaper")) return K_SET_WALLPAPER;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "settings")) return K_SESSION_SETTINGS;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "is-on")) return K_SESSION_IS_ON;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "set-setting")) return K_SESSION_SET;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "take")) return K_SHOT_TAKE;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "start-recording")) return K_SHOT_RECORD;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "stop-recording")) return K_SHOT_STOP;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "is-recording")) return K_SHOT_IS_REC;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "records-pointer")) return K_SHOT_PTR;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "set-records-pointer")) return K_SHOT_SET_PTR;
if (!strcmp(iface, "power") && !strcmp(fn, "screen-off-minutes")) return K_PW_SCREEN;
if (!strcmp(iface, "power") && !strcmp(fn, "set-screen-off-minutes")) return K_PW_SET_SCREEN;
if (!strcmp(iface, "power") && !strcmp(fn, "suspend-minutes")) return K_PW_SUSP;
if (!strcmp(iface, "power") && !strcmp(fn, "set-suspend-minutes")) return K_PW_SET_SUSP;
if (!strcmp(iface, "power") && !strcmp(fn, "suspend")) return K_PW_SUSPEND;
if (!strcmp(iface, "power") && !strcmp(fn, "power-off")) return K_PW_OFF;
if (!strcmp(iface, "power") && !strcmp(fn, "reboot")) return K_PW_REBOOT;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "layout-modes")) return K_LAYOUTS;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "current-layout")) return K_LAYOUT_CUR;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT;
if (!strcmp(iface, "inspector") && !strcmp(fn, "is-on")) return K_INSPECT_IS_ON;
if (!strcmp(iface, "inspector") && !strcmp(fn, "set-on")) return K_INSPECT_SET;
if (!strcmp(iface, "modules") && !strcmp(fn, "available")) return K_MOD_AVAILABLE;
if (!strcmp(iface, "modules") && !strcmp(fn, "loaded")) return K_MOD_LOADED;
if (!strcmp(iface, "modules") && !strcmp(fn, "load-module")) return K_MOD_LOAD;
if (!strcmp(iface, "modules") && !strcmp(fn, "unload-instance")) return K_MOD_UNLOAD;
if (!strcmp(iface, "modules") && !strcmp(fn, "browse")) return K_MOD_BROWSE;
return K_OTHER;
}
/* Remember which host interfaces a module imports (its capabilities). */
static void note_import(Inst *in, const wasm_name_t *m) {
char iface[64];
iface_of(m, iface, sizeof(iface));
if (!iface[0] || !strcmp(iface, "types")) return;
size_t have = strlen(in->imports);
/* already listed? */
for (const char *p = in->imports; *p;) {
const char *nl = strchr(p, '\n');
size_t l = nl ? (size_t)(nl - p) : strlen(p);
if (l == strlen(iface) && !memcmp(p, iface, l)) return;
p += l + (nl ? 1 : 0);
}
if (have + strlen(iface) + 2 < sizeof(in->imports)) {
memcpy(in->imports + have, iface, strlen(iface));
in->imports[have + strlen(iface)] = '\n';
in->imports[have + strlen(iface) + 1] = 0;
}
}
static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len) {
wasm_byte_vec_t bin;
wasm_byte_vec_new(&bin, len, (const wasm_byte_t *)bytes);
wasm_module_t *mod = wasm_module_new(store, &bin);
wasm_byte_vec_delete(&bin);
if (!mod) return 0;
wasm_exporttype_vec_t ets;
wasm_module_exports(mod, &ets);
int has_render = 0;
for (size_t i = 0; i < ets.size; i++) {
const wasm_name_t *nm = wasm_exporttype_name(ets.data[i]);
if (nm->size == strlen(ex_names[EX_RENDER]) && memcmp(nm->data, ex_names[EX_RENDER], nm->size) == 0) has_render = 1;
}
if (!has_render) { wasm_exporttype_vec_delete(&ets); wasm_module_delete(mod); return 0; }
wasm_importtype_vec_t its;
wasm_module_imports(mod, &its);
wasm_extern_vec_t imports;
wasm_extern_vec_new_uninitialized(&imports, its.size);
for (size_t i = 0; i < its.size; i++) {
const wasm_name_t *m = wasm_importtype_module(its.data[i]);
const wasm_name_t *f = wasm_importtype_name(its.data[i]);
const wasm_externtype_t *et = wasm_importtype_type(its.data[i]);
Env *env = (Env *)calloc(1, sizeof(Env));
env->inst = in;
env->kind = classify_import(m, f);
note_import(in, m);
if (wasm_externtype_kind(et) == WASM_EXTERN_FUNC) {
wasm_func_t *fn = wasm_func_new_with_env(store, wasm_externtype_as_functype_const(et), host_import, env, NULL);
imports.data[i] = wasm_func_as_extern(fn);
} else {
/* tables/memories/globals are not expected from plasmoids */
wasm_extern_vec_delete(&imports);
wasm_importtype_vec_delete(&its);
wasm_exporttype_vec_delete(&ets);
wasm_module_delete(mod);
return 0;
}
}
wasm_trap_t *trap = NULL;
wasm_instance_t *inst = wasm_instance_new(store, mod, &imports, &trap);
wasm_extern_vec_delete(&imports);
wasm_importtype_vec_delete(&its);
if (!inst) {
if (trap) wasm_trap_delete(trap);
wasm_exporttype_vec_delete(&ets);
wasm_module_delete(mod);
return 0;
}
wasm_extern_vec_t exps;
wasm_instance_exports(inst, &exps);
for (size_t i = 0; i < ets.size && i < exps.size; i++) {
const wasm_name_t *nm = wasm_exporttype_name(ets.data[i]);
wasm_extern_t *x = exps.data[i];
if (wasm_extern_kind(x) == WASM_EXTERN_MEMORY && nm->size == 6 && memcmp(nm->data, "memory", 6) == 0) {
in->memory = wasm_extern_as_memory(x);
} else if (wasm_extern_kind(x) == WASM_EXTERN_FUNC) {
for (int k = 0; k < EX_N; k++) {
if (nm->size == strlen(ex_names[k]) && memcmp(nm->data, ex_names[k], nm->size) == 0) in->ex[k] = wasm_extern_as_func(x);
}
}
}
wasm_exporttype_vec_delete(&ets);
in->module = mod;
in->instance = inst;
return in->memory && in->ex[EX_INFO] && in->ex[EX_RENDER];
}
/* Load a plasmoid from `path`; returns a handle >= 0 or a negative error. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_load(moonbit_bytes_t path_bytes, moonbit_bytes_t tokens) {
char path[1024];
int32_t plen = Moonbit_array_length(path_bytes);
size_t pn = (size_t)plen < sizeof(path) - 1 ? (size_t)plen : sizeof(path) - 1;
memcpy(path, path_bytes, pn);
path[pn] = '\0';
if (!engine) {
engine = wasm_engine_new();
store = wasm_store_new(engine);
if (!store) return -10;
}
int h = -1;
for (int i = 0; i < MAX_INST; i++) if (!insts[i].used) { h = i; break; }
if (h < 0) return -11;
FILE *f = fopen(path, "rb");
if (!f) return -2;
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
if (sz <= 8) { fclose(f); return -1; }
uint8_t *buf = (uint8_t *)malloc((size_t)sz);
if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(buf); return -2; }
fclose(f);
Inst *in = &insts[h];
memset(in, 0, sizeof(*in));
int32_t tn = Moonbit_array_length(tokens);
memcpy(in->tokens, tokens, tn < 64 ? (size_t)tn : 64);
int rc = load_bytes(in, buf, (size_t)sz);
free(buf);
if (rc != 0) { memset(in, 0, sizeof(*in)); return rc; }
in->used = 1;
return h;
}
MOONBIT_FFI_EXPORT
void mp_wasm_set_tokens(int32_t h, moonbit_bytes_t tokens) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return;
int32_t tn = Moonbit_array_length(tokens);
memcpy(insts[h].tokens, tokens, tn < 64 ? (size_t)tn : 64);
}
MOONBIT_FFI_EXPORT
void mp_wasm_unload(int32_t h) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return;
if (insts[h].instance) wasm_instance_delete(insts[h].instance);
if (insts[h].module) wasm_module_delete(insts[h].module);
memset(&insts[h], 0, sizeof(Inst));
}
/* Call export `which` (EX_*) with up to 4 i32 args; returns the i32 result (0 for none), -1 on trap/missing. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_call(int32_t h, int32_t which, int32_t a0, int32_t a1, int32_t a2, int32_t a3) {
if (h < 0 || h >= MAX_INST || !insts[h].used || which < 0 || which >= EX_N) return -1;
wasm_func_t *fn = insts[h].ex[which];
if (!fn) return -1;
size_t np = wasm_func_param_arity(fn);
size_t nr = wasm_func_result_arity(fn);
wasm_val_t av[4] = { WASM_I32_VAL(a0), WASM_I32_VAL(a1), WASM_I32_VAL(a2), WASM_I32_VAL(a3) };
wasm_val_t rv[1] = { WASM_INIT_VAL };
wasm_val_vec_t args = { np > 4 ? 4 : np, av };
wasm_val_vec_t res = { nr > 1 ? 1 : nr, rv };
wasm_trap_t *trap = wasm_func_call(fn, &args, &res);
if (trap) {
if (getenv("MP_WASM_DEBUG")) { wasm_message_t m; wasm_trap_message(trap, &m); fprintf(stderr, "wasm trap: %.*s\n", (int)m.size, m.data); wasm_byte_vec_delete(&m); }
wasm_trap_delete(trap);
return -1;
}
return nr > 0 ? rv[0].of.i32 : 0;
}
/* Copy `len` bytes of guest memory at `off` into `out`. Returns 0 on success. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_read(int32_t h, int32_t off, int32_t len, moonbit_bytes_t out) {
if (h < 0 || h >= MAX_INST || !insts[h].used || off < 0 || len < 0) return -1;
size_t size = wasm_memory_data_size(insts[h].memory);
if ((size_t)off + (size_t)len > size || len > Moonbit_array_length(out)) return -1;
memcpy(out, wasm_memory_data(insts[h].memory) + off, (size_t)len);
return 0;
}
/* ---- native file picker: zenity on the host session, output read through a pipe ---- */
MOONBIT_FFI_EXPORT
int32_t mp_pick_start(void) {
int fds[2];
if (pipe(fds) != 0) return -1;
signal(SIGCHLD, SIG_IGN);
pid_t pid = fork();
if (pid < 0) { close(fds[0]); close(fds[1]); return -1; }
if (pid == 0) {
setsid();
dup2(fds[1], 1);
close(fds[0]);
close(fds[1]);
int dn = open("/dev/null", O_WRONLY);
if (dn >= 0) dup2(dn, 2);
execlp("zenity", "zenity", "--file-selection", "--title=Load widget (.wasm)",
"--file-filter=WebAssembly widgets | *.wasm", "--file-filter=All files | *", (char *)NULL);
_exit(127);
}
close(fds[1]);
fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL, 0) | O_NONBLOCK);
return fds[0];
}
/* Read from a pipe: bytes read, 0 at EOF, -1 when nothing is available yet. */
MOONBIT_FFI_EXPORT
int32_t mp_fd_read(int32_t fd, moonbit_bytes_t out) {
ssize_t n = read(fd, out, (size_t)Moonbit_array_length(out));
if (n < 0) return -1;
return (int32_t)n;
}
MOONBIT_FFI_EXPORT
void mp_fd_close(int32_t fd) { close(fd); }
/* ---- host state a widget can read, and the one action it can ask for ---- */
/* Replace the 64-byte system.snapshot the guest's system.read returns. */
MOONBIT_FFI_EXPORT
void mp_wasm_set_system(moonbit_bytes_t b) {
int32_t n = Moonbit_array_length(b);
memset(g_system, 0, sizeof(g_system));
memcpy(g_system, b, n < 64 ? (size_t)n : 64);
}
/* Replace the window list blob (see g_windows) served by windows.all. */
MOONBIT_FFI_EXPORT
void mp_wasm_set_windows(moonbit_bytes_t b) {
int32_t n = Moonbit_array_length(b);
free(g_windows);
g_windows = (uint8_t *)malloc(n > 0 ? (size_t)n : 1);
g_windows_len = g_windows ? (size_t)n : 0;
if (g_windows) memcpy(g_windows, b, (size_t)n);
}
/* Window id a widget asked to focus since the last call, or -1. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_take_focus(void) {
int64_t id = g_focus_req;
g_focus_req = -1;
return id < 0 || id > 0x7fffffff ? -1 : (int32_t)id;
}
/* ---- host data + requests (see the tables/Req definitions above) ---- */
MOONBIT_FFI_EXPORT
void mp_host_set_table(int32_t which, moonbit_bytes_t data) {
if (which < 0 || which >= T_N) return;
int32_t n = Moonbit_array_length(data);
free(tables[which].data);
tables[which].data = (uint8_t *)malloc((size_t)n + 1);
memcpy(tables[which].data, data, (size_t)n);
tables[which].len = (size_t)n;
}
MOONBIT_FFI_EXPORT
void mp_host_set_int(int32_t which, int32_t v) {
if (which >= 0 && which < 12) host_ints[which] = v;
}
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
MOONBIT_FFI_EXPORT
int32_t mp_host_req_pop(void) {
free(cur_req.s);
memset(&cur_req, 0, sizeof(cur_req));
if (req_head >= req_tail) return 0;
cur_req = reqs[req_head % MAX_REQ];
req_head++;
return cur_req.kind;
}
MOONBIT_FFI_EXPORT
int32_t mp_host_req_int(void) { return cur_req.n; }
MOONBIT_FFI_EXPORT
int32_t mp_host_req_str(moonbit_bytes_t out) {
if (!cur_req.s) return 0;
int32_t cap = Moonbit_array_length(out);
int32_t n = (int32_t)strlen(cur_req.s);
if (n > cap) n = cap;
memcpy(out, cur_req.s, (size_t)n);
return n;
}
/* Write `len` bytes into guest memory at `off`. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_write(int32_t h, int32_t off, moonbit_bytes_t src, int32_t len) {
if (h < 0 || h >= MAX_INST || !insts[h].used || off < 0 || len < 0 || len > Moonbit_array_length(src)) return -1;
size_t size = wasm_memory_data_size(insts[h].memory);
if ((size_t)off + (size_t)len > size) return -1;
memcpy(wasm_memory_data(insts[h].memory) + off, src, (size_t)len);
return 0;
}
/* Newline-separated host interfaces the module imports; returns the byte count copied into `out`. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_imports(int32_t h, moonbit_bytes_t out) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return 0;
int32_t n = (int32_t)strlen(insts[h].imports);
int32_t cap = Moonbit_array_length(out);
if (n > cap) n = cap;
memcpy(out, insts[h].imports, (size_t)n);
return n;
}
/* Names of "*.wasm" files in `dir`, newline-separated, sorted. */
static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
MOONBIT_FFI_EXPORT
moonbit_bytes_t mp_list_wasm(moonbit_bytes_t dir_bytes) {
char dir[1024];
int32_t dl = Moonbit_array_length(dir_bytes);
size_t dn = (size_t)dl < sizeof(dir) - 1 ? (size_t)dl : sizeof(dir) - 1;
memcpy(dir, dir_bytes, dn);
dir[dn] = 0;
DIR *d = opendir(dir);
if (!d) return moonbit_make_bytes_raw(0);
char **names = NULL;
size_t count = 0, cap = 0;
struct dirent *e;
while ((e = readdir(d)) != NULL) {
size_t n = strlen(e->d_name);
if (n < 6 || strcmp(e->d_name + n - 5, ".wasm") != 0) continue;
if (count == cap) { cap = cap ? cap * 2 : 16; names = (char **)realloc(names, cap * sizeof(char *)); }
names[count++] = strdup(e->d_name);
}
closedir(d);
if (count > 1) qsort(names, count, sizeof(char *), cmp_str);
size_t len = 0;
for (size_t i = 0; i < count; i++) len += strlen(names[i]) + 1;
moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)len);
size_t o = 0;
for (size_t i = 0; i < count; i++) {
size_t n = strlen(names[i]);
memcpy((char *)out + o, names[i], n);
o += n;
((char *)out)[o++] = '\n';
free(names[i]);
}
free(names);
return out;
}