Wasm panel modules, widget host, merged plasmoid host design, and shell/UI work
Panel and wasm host - The panel is built from wasm plasmoid modules (compositor/wasm: wasmer-backed host). Modules get capabilities by importing host interfaces; the host publishes data tables and serves a request queue (launch, focus window, set layout, inspector, load/unload modules). New WIT: windows, layout-control, inspector, modules, system. - Merged two competing host designs: generic tables + requests are the base; the `system` snapshot and the id-stable `windows.all/focus` (Desktop Pulse) run on top of it. - Panel widgets: load a .wasm from a path or file chooser, reorder by dragging, right-click replace/remove/add, saved to panel.edn. - Desktop widget, system sampler (sysinfo), app catalog/humanised names, Interface Explorer (inspector), real font rendering (compositor/font, assets/fonts). Compositor - Drag the divider between tiled windows; lower tiled rows leave room for the title bar. - Title-bar buttons, 12-hour clock, truncated titles, task-list/layout menus. - DRM/KMS session, tcc debug builds (vendored tinycc incl. conftest.c), justfile recipes (modules, run, test), pixi.toml. Known gaps - The sources for the pulse, tasks, layout, inspector, module-manager, moon-* and clock-digital12 modules are not in the tree yet, so `just modules` stops at pulse and the host tests that load those modules fail until they land. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
080377fd79
commit
0145981c6a
57 files changed
+11461
-221
No files matched your search
@@ -0,0 +1,16 @@
|
||||
import {
|
||||
"moonbitlang/core/builtin",
|
||||
"moonplasma/desktop/interface/moonplasma/desktop/types" @types,
|
||||
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
|
||||
}
|
||||
|
||||
supported_targets = "-all+native"
|
||||
|
||||
options(
|
||||
"native-stub": [ "wasm_stub.c" ],
|
||||
link: {
|
||||
"native": {
|
||||
"cc-link-flags": "-lwasmer",
|
||||
},
|
||||
},
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,723 @@
|
||||
///| Loads plasmoid components (.wasm) into the native compositor. The core module
|
||||
/// is run with wasmer (see wasm_stub.c); this file does the canonical-ABI marshalling
|
||||
/// of the `plasmoid` interface: info, render and the draw-op list, UTF-16 strings.
|
||||
|
||||
///|
|
||||
#borrow(path, tokens)
|
||||
extern "C" fn c_wasm_load(path : Bytes, tokens : Bytes) -> Int = "mp_wasm_load"
|
||||
|
||||
///|
|
||||
#borrow(tokens)
|
||||
extern "C" fn c_wasm_set_tokens(h : Int, tokens : Bytes) = "mp_wasm_set_tokens"
|
||||
|
||||
///|
|
||||
extern "C" fn c_wasm_unload(h : Int) = "mp_wasm_unload"
|
||||
|
||||
///|
|
||||
extern "C" fn c_wasm_call(h : Int, which : Int, a0 : Int, a1 : Int, a2 : Int, a3 : Int) -> Int = "mp_wasm_call"
|
||||
|
||||
///|
|
||||
#borrow(out)
|
||||
extern "C" fn c_wasm_read(h : Int, off : Int, len : Int, out : Bytes) -> Int = "mp_wasm_read"
|
||||
|
||||
///|
|
||||
#borrow(b)
|
||||
extern "C" fn c_wasm_set_system(b : Bytes) = "mp_wasm_set_system"
|
||||
|
||||
///|
|
||||
#borrow(b)
|
||||
extern "C" fn c_wasm_set_windows(b : Bytes) = "mp_wasm_set_windows"
|
||||
|
||||
///|
|
||||
extern "C" fn c_wasm_take_focus() -> Int = "mp_wasm_take_focus"
|
||||
|
||||
///|
|
||||
#borrow(src)
|
||||
extern "C" fn c_wasm_write(h : Int, off : Int, src : Bytes, len : Int) -> Int = "mp_wasm_write"
|
||||
|
||||
///|
|
||||
#borrow(out)
|
||||
extern "C" fn c_wasm_imports(h : Int, out : Bytes) -> Int = "mp_wasm_imports"
|
||||
|
||||
///|
|
||||
#borrow(data)
|
||||
extern "C" fn c_host_set_table(which : Int, data : Bytes) = "mp_host_set_table"
|
||||
|
||||
///|
|
||||
extern "C" fn c_host_set_int(which : Int, v : Int) = "mp_host_set_int"
|
||||
|
||||
///|
|
||||
extern "C" fn c_host_req_pop() -> Int = "mp_host_req_pop"
|
||||
|
||||
///|
|
||||
extern "C" fn c_host_req_int() -> Int = "mp_host_req_int"
|
||||
|
||||
///|
|
||||
#borrow(out)
|
||||
extern "C" fn c_host_req_str(out : Bytes) -> Int = "mp_host_req_str"
|
||||
|
||||
///|
|
||||
#borrow(dir)
|
||||
extern "C" fn c_list_wasm(dir : Bytes) -> Bytes = "mp_list_wasm"
|
||||
|
||||
///|
|
||||
extern "C" fn c_pick_start() -> Int = "mp_pick_start"
|
||||
|
||||
///|
|
||||
#borrow(out)
|
||||
extern "C" fn c_fd_read(fd : Int, out : Bytes) -> Int = "mp_fd_read"
|
||||
|
||||
///|
|
||||
extern "C" fn c_fd_close(fd : Int) = "mp_fd_close"
|
||||
|
||||
///|
|
||||
fn utf8(s : String) -> Bytes {
|
||||
let out : Array[Byte] = []
|
||||
for ch in s {
|
||||
let c = ch.to_int()
|
||||
if c < 0x80 {
|
||||
out.push(c.to_byte())
|
||||
} else if c < 0x800 {
|
||||
out.push((0xC0 | (c >> 6)).to_byte())
|
||||
out.push((0x80 | (c & 0x3F)).to_byte())
|
||||
} else if c < 0x10000 {
|
||||
out.push((0xE0 | (c >> 12)).to_byte())
|
||||
out.push((0x80 | ((c >> 6) & 0x3F)).to_byte())
|
||||
out.push((0x80 | (c & 0x3F)).to_byte())
|
||||
} else {
|
||||
out.push((0xF0 | (c >> 18)).to_byte())
|
||||
out.push((0x80 | ((c >> 12) & 0x3F)).to_byte())
|
||||
out.push((0x80 | ((c >> 6) & 0x3F)).to_byte())
|
||||
out.push((0x80 | (c & 0x3F)).to_byte())
|
||||
}
|
||||
}
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
|
||||
///| Decode UTF-8 bytes (file-picker output).
|
||||
fn from_utf8(b : Bytes, len : Int) -> String {
|
||||
let sb = StringBuilder::new()
|
||||
let mut i = 0
|
||||
while i < len {
|
||||
let c = b[i].to_int()
|
||||
if c < 0x80 {
|
||||
sb.write_char(c.unsafe_to_char())
|
||||
i = i + 1
|
||||
} else if c < 0xE0 && i + 1 < len {
|
||||
sb.write_char((((c & 0x1F) << 6) | (b[i + 1].to_int() & 0x3F)).unsafe_to_char())
|
||||
i = i + 2
|
||||
} else if c < 0xF0 && i + 2 < len {
|
||||
sb.write_char((((c & 0x0F) << 12) | ((b[i + 1].to_int() & 0x3F) << 6) | (b[i + 2].to_int() & 0x3F)).unsafe_to_char())
|
||||
i = i + 3
|
||||
} else if i + 3 < len {
|
||||
sb.write_char((((c & 0x07) << 18) | ((b[i + 1].to_int() & 0x3F) << 12) | ((b[i + 2].to_int() & 0x3F) << 6) | (b[i + 3].to_int() & 0x3F)).unsafe_to_char())
|
||||
i = i + 4
|
||||
} else {
|
||||
i = len
|
||||
}
|
||||
}
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
///| Export indices in wasm_stub.c.
|
||||
let ex_info : Int = 0
|
||||
|
||||
///|
|
||||
let ex_render : Int = 1
|
||||
|
||||
///|
|
||||
let ex_onevent : Int = 2
|
||||
|
||||
///|
|
||||
let ex_popup : Int = 3
|
||||
|
||||
///|
|
||||
let ex_post_info : Int = 4
|
||||
|
||||
///|
|
||||
let ex_post_render : Int = 5
|
||||
|
||||
///|
|
||||
let ex_post_popup : Int = 6
|
||||
|
||||
///|
|
||||
let ex_realloc : Int = 7
|
||||
|
||||
///| The 64-byte `theme.tokens` record (name left empty) the guest reads through get-tokens.
|
||||
pub fn pack_tokens(t : @theme.Tokens) -> Bytes {
|
||||
let b = FixedArray::make(64, b'\x00')
|
||||
let mut off = 8
|
||||
let col = fn(c : @types.Color) {
|
||||
b[off] = c.r
|
||||
b[off + 1] = c.g
|
||||
b[off + 2] = c.b
|
||||
b[off + 3] = c.a
|
||||
off = off + 4
|
||||
}
|
||||
let p = t.palette
|
||||
col(p.desktop_top)
|
||||
col(p.desktop_bottom)
|
||||
col(p.surface)
|
||||
col(p.surface_hover)
|
||||
col(p.surface_popup)
|
||||
col(p.foreground)
|
||||
col(p.foreground_muted)
|
||||
col(p.accent)
|
||||
col(p.accent_foreground)
|
||||
col(p.border)
|
||||
let put32 = fn(o : Int, v : UInt) {
|
||||
for k = 0; k < 4; k = k + 1 {
|
||||
b[o + k] = ((v >> (8 * k)) & 0xFFU).to_int().to_byte()
|
||||
}
|
||||
}
|
||||
put32(48, t.font_size)
|
||||
put32(52, t.radius)
|
||||
put32(56, t.spacing)
|
||||
put32(60, t.panel_height)
|
||||
Bytes::from_fixedarray(b)
|
||||
}
|
||||
|
||||
///| 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
|
||||
/// The host interfaces this widget imports, i.e. what it was granted (e.g. "system,windows").
|
||||
imports : Array[String]
|
||||
}
|
||||
|
||||
///|
|
||||
fn Plasmoid::mem(self : Plasmoid, off : Int, len : Int) -> Bytes? {
|
||||
if len < 0 || off < 0 {
|
||||
return None
|
||||
}
|
||||
let buf = Bytes::make(len, b'\x00')
|
||||
if len == 0 || c_wasm_read(self.handle, off, len, buf) == 0 {
|
||||
Some(buf)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn rd32(b : Bytes, o : Int) -> Int {
|
||||
b[o].to_int() | (b[o + 1].to_int() << 8) | (b[o + 2].to_int() << 16) | (b[o + 3].to_int() << 24)
|
||||
}
|
||||
|
||||
///| UTF-16LE string of `len` code units at `ptr` in guest memory.
|
||||
fn Plasmoid::str(self : Plasmoid, ptr : Int, len : Int) -> String {
|
||||
if len <= 0 || len > 4096 {
|
||||
return ""
|
||||
}
|
||||
match self.mem(ptr, len * 2) {
|
||||
None => ""
|
||||
Some(b) => {
|
||||
let sb = StringBuilder::new()
|
||||
for i = 0; i < len; i = i + 1 {
|
||||
sb.write_char((b[2 * i].to_int() | (b[2 * i + 1].to_int() << 8)).unsafe_to_char())
|
||||
}
|
||||
sb.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///| Load a plasmoid component or core module. Err carries a short reason.
|
||||
pub fn load(path : String, tokens : @theme.Tokens) -> Result[Plasmoid, String] {
|
||||
let h = c_wasm_load(utf8(path), pack_tokens(tokens))
|
||||
if h < 0 {
|
||||
return Err(
|
||||
match h {
|
||||
-1 => "not a wasm file"
|
||||
-2 => "cannot read file"
|
||||
-3 | -4 => "no plasmoid (moonplasma:desktop/plasmoid) in this module"
|
||||
_ => "wasm runtime error"
|
||||
},
|
||||
)
|
||||
}
|
||||
let p0 : Plasmoid = { handle: h, id: "", name: "", pref_w: 0, pref_h: 0, min_w: 0, stretch: false, imports: [] }
|
||||
let ra = c_wasm_call(h, ex_info, 0, 0, 0, 0)
|
||||
if ra < 0 {
|
||||
c_wasm_unload(h)
|
||||
return Err("widget trapped in info()")
|
||||
}
|
||||
match p0.mem(ra, 32) {
|
||||
None => {
|
||||
c_wasm_unload(h)
|
||||
Err("bad info() result")
|
||||
}
|
||||
Some(b) => {
|
||||
let p = {
|
||||
..p0,
|
||||
id: p0.str(rd32(b, 0), rd32(b, 4)),
|
||||
name: p0.str(rd32(b, 8), rd32(b, 12)),
|
||||
pref_w: rd32(b, 16),
|
||||
pref_h: rd32(b, 20),
|
||||
min_w: rd32(b, 24),
|
||||
stretch: b[28].to_int() != 0,
|
||||
imports: read_imports(h),
|
||||
}
|
||||
ignore(c_wasm_call(h, ex_post_info, ra, 0, 0, 0))
|
||||
Ok(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///| Names of the moonplasma interfaces (besides types/theme) the widget at `h` imports.
|
||||
fn read_imports(h : Int) -> Array[String] {
|
||||
let buf = Bytes::make(512, b'\x00')
|
||||
let n = c_wasm_imports(h, buf)
|
||||
let out : Array[String] = []
|
||||
if n > 0 {
|
||||
for part in from_utf8(buf, n).split("\n") {
|
||||
if part.length() > 0 && part.to_string() != "theme" {
|
||||
out.push(part.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| Machine state served to widgets through `system.read`.
|
||||
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
|
||||
}
|
||||
|
||||
///| One window served to widgets through `windows.all`.
|
||||
pub(all) struct WindowEntry {
|
||||
id : UInt64
|
||||
title : String
|
||||
app_id : String
|
||||
focused : Bool
|
||||
}
|
||||
|
||||
///| Publish the machine state widgets will read (canonical-ABI layout of `system.snapshot`).
|
||||
pub fn set_system(s : SystemSnapshot) -> Unit {
|
||||
let b = FixedArray::make(64, b'\x00')
|
||||
let put = fn(o : Int, v : Int64, n : Int) {
|
||||
for k = 0; k < n; k = k + 1 {
|
||||
b[o + k] = ((v >> (8 * k)) & 0xFFL).to_int().to_byte()
|
||||
}
|
||||
}
|
||||
put(0, s.cpu_permille.to_int64(), 4)
|
||||
put(8, s.mem_used_kib, 8)
|
||||
put(16, s.mem_total_kib, 8)
|
||||
put(24, s.battery_percent.to_int64(), 4)
|
||||
put(28, if s.charging { 1L } else { 0L }, 1)
|
||||
put(32, s.uptime_secs, 8)
|
||||
put(40, s.rx_bps, 8)
|
||||
put(48, s.tx_bps, 8)
|
||||
put(56, s.load_centi.to_int64(), 4)
|
||||
c_wasm_set_system(Bytes::from_fixedarray(b))
|
||||
}
|
||||
|
||||
///| Publish the window list widgets will read.
|
||||
pub fn set_windows(wins : Array[WindowEntry]) -> Unit {
|
||||
let out : Array[Byte] = []
|
||||
let u32 = fn(v : Int) {
|
||||
for k = 0; k < 4; k = k + 1 {
|
||||
out.push(((v >> (8 * k)) & 0xFF).to_byte())
|
||||
}
|
||||
}
|
||||
let units = fn(str : String) {
|
||||
u32(str.length())
|
||||
for i = 0; i < str.length(); i = i + 1 {
|
||||
let c = str[i].to_int()
|
||||
out.push((c & 0xFF).to_byte())
|
||||
out.push(((c >> 8) & 0xFF).to_byte())
|
||||
}
|
||||
}
|
||||
let n = if wins.length() > 64 { 64 } else { wins.length() }
|
||||
u32(n)
|
||||
for i = 0; i < n; i = i + 1 {
|
||||
let w = wins[i]
|
||||
u32((w.id & 0xFFFFFFFFUL).to_int())
|
||||
u32((w.id >> 32).to_int())
|
||||
u32(if w.focused { 1 } else { 0 })
|
||||
// titles are capped so one huge title cannot crowd out the rest of the list
|
||||
units(if w.title.length() > 200 { w.title[:200].to_string() } else { w.title })
|
||||
units(if w.app_id.length() > 200 { w.app_id[:200].to_string() } else { w.app_id })
|
||||
}
|
||||
c_wasm_set_windows(Bytes::from_array(out))
|
||||
}
|
||||
|
||||
///| Window a widget asked to focus (via `windows.focus`) since the last call.
|
||||
pub fn take_focus_request() -> UInt64? {
|
||||
let id = c_wasm_take_focus()
|
||||
if id < 0 { None } else { Some(id.to_uint64()) }
|
||||
}
|
||||
|
||||
///| Forward a press at widget-local (x, y) to the widget's `on-event`. True when it asked for a redraw.
|
||||
pub fn Plasmoid::pointer_down(self : Plasmoid, x : Int, y : Int) -> Bool {
|
||||
c_wasm_call(self.handle, ex_onevent, 0, 1, x, y) == 1
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Plasmoid::unload(self : Plasmoid) -> Unit {
|
||||
c_wasm_unload(self.handle)
|
||||
}
|
||||
|
||||
///|
|
||||
fn col(b : Bytes, o : Int) -> @types.Color {
|
||||
{ r: b[o], g: b[o + 1], b: b[o + 2], a: b[o + 3] }
|
||||
}
|
||||
|
||||
|
||||
///| Decode `n` draw-ops at guest address `base` (the canonical-ABI list<draw-op> layout).
|
||||
fn Plasmoid::decode_ops(self : Plasmoid, base : Int, n : Int, out : Array[@types.DrawOp]) -> Unit {
|
||||
if n >= 0 && n <= 4096 {
|
||||
match self.mem(base, n * 32) {
|
||||
None => ()
|
||||
Some(b) =>
|
||||
for i = 0; i < n; i = i + 1 {
|
||||
let o = i * 32
|
||||
let rect = fn(o2 : Int) -> @types.Rect {
|
||||
{ x: rd32(b, o2), y: rd32(b, o2 + 4), w: rd32(b, o2 + 8).reinterpret_as_uint(), h: rd32(b, o2 + 12).reinterpret_as_uint() }
|
||||
}
|
||||
match b[o].to_int() {
|
||||
0 =>
|
||||
out.push(
|
||||
FillRect({ rect: rect(o + 4), color: col(b, o + 20), radius: rd32(b, o + 24).reinterpret_as_uint() }),
|
||||
)
|
||||
1 =>
|
||||
out.push(
|
||||
StrokeRect({
|
||||
rect: rect(o + 4),
|
||||
color: col(b, o + 20),
|
||||
width: rd32(b, o + 24).reinterpret_as_uint(),
|
||||
radius: rd32(b, o + 28).reinterpret_as_uint(),
|
||||
}),
|
||||
)
|
||||
2 =>
|
||||
out.push(
|
||||
Line({
|
||||
start: { x: rd32(b, o + 4), y: rd32(b, o + 8) },
|
||||
end: { x: rd32(b, o + 12), y: rd32(b, o + 16) },
|
||||
color: col(b, o + 20),
|
||||
width: rd32(b, o + 24).reinterpret_as_uint(),
|
||||
}),
|
||||
)
|
||||
3 =>
|
||||
out.push(
|
||||
Circle({
|
||||
center: { x: rd32(b, o + 4), y: rd32(b, o + 8) },
|
||||
radius: rd32(b, o + 12).reinterpret_as_uint(),
|
||||
color: col(b, o + 16),
|
||||
filled: b[o + 20].to_int() != 0,
|
||||
}),
|
||||
)
|
||||
4 =>
|
||||
out.push(
|
||||
Text({
|
||||
origin: { x: rd32(b, o + 4), y: rd32(b, o + 8) },
|
||||
text: self.str(rd32(b, o + 12), rd32(b, o + 16)),
|
||||
style: {
|
||||
size: rd32(b, o + 20).reinterpret_as_uint(),
|
||||
color: col(b, o + 24),
|
||||
align: match b[o + 28].to_int() {
|
||||
1 => CENTER
|
||||
2 => RIGHT
|
||||
_ => LEFT
|
||||
},
|
||||
bold: b[o + 29].to_int() != 0,
|
||||
},
|
||||
}),
|
||||
)
|
||||
5 => out.push(PushClip(rect(o + 4)))
|
||||
_ => out.push(PopClip)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///| Draw ops of the widget at `size`, with the theme tokens refreshed first.
|
||||
/// A trapping or malformed widget yields no ops.
|
||||
pub fn Plasmoid::render(
|
||||
self : Plasmoid,
|
||||
w : Int,
|
||||
h : Int,
|
||||
tokens : @theme.Tokens,
|
||||
) -> Array[@types.DrawOp] {
|
||||
c_wasm_set_tokens(self.handle, pack_tokens(tokens))
|
||||
let ra = c_wasm_call(self.handle, ex_render, w, h, 0, 0)
|
||||
let out : Array[@types.DrawOp] = []
|
||||
if ra < 0 {
|
||||
return out
|
||||
}
|
||||
match self.mem(ra, 8) {
|
||||
None => ()
|
||||
Some(hdr) => self.decode_ops(rd32(hdr, 0), rd32(hdr, 4), out)
|
||||
}
|
||||
ignore(c_wasm_call(self.handle, ex_post_render, ra, 0, 0, 0))
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
///| A popup surface a plasmoid wants shown next to its panel widget.
|
||||
pub(all) struct PopupSurface {
|
||||
w : Int
|
||||
h : Int
|
||||
ops : Array[@types.DrawOp]
|
||||
}
|
||||
|
||||
///| `popup()`: the widget's open popup, or None. Local coordinates, origin top-left.
|
||||
pub fn Plasmoid::popup(self : Plasmoid) -> PopupSurface? {
|
||||
let ra = c_wasm_call(self.handle, ex_popup, 0, 0, 0, 0)
|
||||
if ra < 0 {
|
||||
return None
|
||||
}
|
||||
let mut res : PopupSurface? = None
|
||||
match self.mem(ra, 20) {
|
||||
None => ()
|
||||
Some(b) =>
|
||||
if b[0].to_int() != 0 {
|
||||
let ops : Array[@types.DrawOp] = []
|
||||
self.decode_ops(rd32(b, 12), rd32(b, 16), ops)
|
||||
res = Some({ w: rd32(b, 4), h: rd32(b, 8), ops })
|
||||
}
|
||||
}
|
||||
ignore(c_wasm_call(self.handle, ex_post_popup, ra, 0, 0, 0))
|
||||
res
|
||||
}
|
||||
|
||||
///| 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)
|
||||
}
|
||||
|
||||
///| Deliver an event to the widget (`popup` = its popup surface, else the panel widget).
|
||||
/// True when the widget says its visuals changed. A trapping widget yields false.
|
||||
pub fn Plasmoid::on_event(self : Plasmoid, popup : Bool, ev : PlasmoidEvent) -> Bool {
|
||||
let target = if popup { 1 } else { 0 }
|
||||
let r = match ev {
|
||||
PointerMove(x, y) => c_wasm_call(self.handle, ex_onevent, target, 0, x, y)
|
||||
PointerDown(x, y) => c_wasm_call(self.handle, ex_onevent, target, 1, x, y)
|
||||
PointerUp(x, y) => c_wasm_call(self.handle, ex_onevent, target, 2, x, y)
|
||||
PointerLeave => c_wasm_call(self.handle, ex_onevent, target, 3, 0, 0)
|
||||
FocusLost => c_wasm_call(self.handle, ex_onevent, target, 4, 0, 0)
|
||||
KeyDown(k) => {
|
||||
// The guest owns a UTF-16 copy of the key name.
|
||||
let b : Array[Byte] = []
|
||||
let mut units = 0
|
||||
for ch in k {
|
||||
let c = ch.to_int()
|
||||
if c >= 0x10000 {
|
||||
let v = c - 0x10000
|
||||
let hi = 0xD800 + (v >> 10)
|
||||
let lo = 0xDC00 + (v & 0x3FF)
|
||||
b.push((hi & 0xFF).to_byte())
|
||||
b.push((hi >> 8).to_byte())
|
||||
b.push((lo & 0xFF).to_byte())
|
||||
b.push((lo >> 8).to_byte())
|
||||
units = units + 2
|
||||
} else {
|
||||
b.push((c & 0xFF).to_byte())
|
||||
b.push((c >> 8).to_byte())
|
||||
units = units + 1
|
||||
}
|
||||
}
|
||||
let ptr = c_wasm_call(self.handle, ex_realloc, 0, 0, 2, if units * 2 < 4 { 4 } else { units * 2 })
|
||||
if ptr < 0 {
|
||||
-1
|
||||
} else {
|
||||
ignore(c_wasm_write(self.handle, ptr, Bytes::from_array(b), b.length()))
|
||||
c_wasm_call(self.handle, ex_onevent, target, 5, ptr, units)
|
||||
}
|
||||
}
|
||||
}
|
||||
r == 1
|
||||
}
|
||||
|
||||
///| Host interfaces (capabilities) the module's binary imports, e.g. ["theme", "clock"].
|
||||
pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] {
|
||||
let buf = Bytes::make(512, b'\x00')
|
||||
let n = c_wasm_imports(self.handle, buf)
|
||||
let out : Array[String] = []
|
||||
let sb = StringBuilder::new()
|
||||
for i = 0; i < n; i = i + 1 {
|
||||
if buf[i] == b'\n' {
|
||||
out.push(sb.to_string())
|
||||
sb.reset()
|
||||
} else {
|
||||
sb.write_char(buf[i].to_int().unsafe_to_char())
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| Rows of host data a module can read through its capability imports (apps, windows, ...).
|
||||
/// Fields are i32 or strings; see `build_list` in wasm_stub.c for the per-table row shapes.
|
||||
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
|
||||
}
|
||||
|
||||
///| Publish `t` as the data behind `which` for every module's next call.
|
||||
pub fn publish(which : HostTable, t : Table) -> Unit {
|
||||
let w = match which {
|
||||
Apps => 0
|
||||
Windows => 1
|
||||
Layouts => 2
|
||||
Modules => 3
|
||||
Instances => 4
|
||||
}
|
||||
let out : Array[Byte] = []
|
||||
for k = 0; k < 4; k = k + 1 {
|
||||
out.push(((t.n >> (8 * k)) & 0xFF).to_byte())
|
||||
}
|
||||
for b in t.rows {
|
||||
out.push(b)
|
||||
}
|
||||
c_host_set_table(w, Bytes::from_array(out))
|
||||
}
|
||||
|
||||
///| Publish the current 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 {
|
||||
c_host_set_int(0, layout_mode)
|
||||
c_host_set_int(1, if inspector_on { 1 } else { 0 })
|
||||
}
|
||||
|
||||
///| 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)
|
||||
|
||||
///|
|
||||
fn req_str() -> String {
|
||||
let buf = Bytes::make(1024, b'\x00')
|
||||
let n = c_host_req_str(buf)
|
||||
from_utf8(buf, n)
|
||||
}
|
||||
|
||||
///| The next pending request, oldest first.
|
||||
pub fn next_request() -> HostRequest? {
|
||||
match c_host_req_pop() {
|
||||
1 => Some(Launch(req_str()))
|
||||
2 => Some(FocusWindow(c_host_req_int()))
|
||||
3 => Some(SetLayout(c_host_req_int()))
|
||||
4 => Some(SetInspector(c_host_req_int() != 0))
|
||||
5 => Some(LoadModule(req_str()))
|
||||
6 => Some(UnloadInstance(req_str()))
|
||||
7 => Some(Browse)
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
///| Names of the `*.wasm` files directly in `dir`, sorted.
|
||||
pub fn list_wasm_files(dir : String) -> Array[String] {
|
||||
let raw = c_list_wasm(utf8(dir))
|
||||
let out : Array[String] = []
|
||||
let sb = StringBuilder::new()
|
||||
for i = 0; i < raw.length(); i = i + 1 {
|
||||
if raw[i] == b'\n' {
|
||||
out.push(sb.to_string())
|
||||
sb.reset()
|
||||
} else {
|
||||
sb.write_char(raw[i].to_int().unsafe_to_char())
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| An in-flight native file-chooser dialog (zenity on the host session).
|
||||
pub(all) struct Picker {
|
||||
fd : Int
|
||||
buf : Array[Byte]
|
||||
}
|
||||
|
||||
///| Open the file chooser; None when it can't be started.
|
||||
pub fn Picker::start() -> Picker? {
|
||||
let fd = c_pick_start()
|
||||
if fd < 0 {
|
||||
None
|
||||
} else {
|
||||
Some({ fd, buf: [] })
|
||||
}
|
||||
}
|
||||
|
||||
///| Poll the dialog: None while it is open, Some(None) if cancelled, Some(Some(path)) when chosen.
|
||||
pub fn Picker::poll(self : Picker) -> String?? {
|
||||
let chunk = Bytes::make(512, b'\x00')
|
||||
while true {
|
||||
let n = c_fd_read(self.fd, chunk)
|
||||
if n > 0 {
|
||||
for i = 0; i < n; i = i + 1 {
|
||||
self.buf.push(chunk[i])
|
||||
}
|
||||
} else if n == 0 {
|
||||
c_fd_close(self.fd)
|
||||
let bytes = Bytes::from_array(self.buf)
|
||||
let mut len = bytes.length()
|
||||
while len > 0 && (bytes[len - 1] == b'\n' || bytes[len - 1] == b'\r') {
|
||||
len = len - 1
|
||||
}
|
||||
return if len == 0 { Some(None) } else { Some(Some(from_utf8(bytes, len))) }
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,747 @@
|
||||
/* Wasm plasmoid host: runs the core module of a moonplasma 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 512
|
||||
enum { EX_INFO, EX_RENDER, EX_ONEVENT, EX_POPUP, EX_POST_INFO, EX_POST_RENDER, EX_POST_POPUP, EX_REALLOC, EX_N };
|
||||
static const char *ex_names[EX_N] = {
|
||||
"moonplasma:desktop/plasmoid@0.1.0#info",
|
||||
"moonplasma:desktop/plasmoid@0.1.0#render",
|
||||
"moonplasma:desktop/plasmoid@0.1.0#on-event",
|
||||
"moonplasma:desktop/plasmoid@0.1.0#popup",
|
||||
"cabi_post_moonplasma:desktop/plasmoid@0.1.0#info",
|
||||
"cabi_post_moonplasma:desktop/plasmoid@0.1.0#render",
|
||||
"cabi_post_moonplasma:desktop/plasmoid@0.1.0#popup",
|
||||
"cabi_realloc",
|
||||
};
|
||||
|
||||
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
|
||||
};
|
||||
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_N };
|
||||
typedef struct { uint8_t *data; size_t len; } Blob;
|
||||
static Blob tables[T_N];
|
||||
static int32_t host_ints[4]; /* 0 layout mode, 1 inspector on */
|
||||
|
||||
/* ---- 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;
|
||||
}
|
||||
|
||||
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_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_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_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_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;
|
||||
}
|
||||
|
||||
|
||||
/* "moonplasma: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 = "moonplasma: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, "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 < 4) 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;
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
///|
|
||||
fn test_tokens() -> @theme.Tokens {
|
||||
let c = fn(r : Int, g : Int, b : Int) -> @types.Color { { r: r.to_byte(), g: g.to_byte(), b: b.to_byte(), a: b'\xff' } }
|
||||
{
|
||||
name: "t",
|
||||
palette: {
|
||||
desktop_top: c(1, 2, 3),
|
||||
desktop_bottom: c(4, 5, 6),
|
||||
surface: c(30, 30, 40),
|
||||
surface_hover: c(50, 50, 60),
|
||||
surface_popup: c(20, 20, 30),
|
||||
foreground: c(250, 250, 250),
|
||||
foreground_muted: c(150, 150, 150),
|
||||
accent: c(80, 120, 255),
|
||||
accent_foreground: c(255, 255, 255),
|
||||
border: c(90, 90, 90),
|
||||
},
|
||||
font_size: 14U,
|
||||
radius: 6U,
|
||||
spacing: 6U,
|
||||
panel_height: 40U,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn load_fixture(name : String) -> Result[Plasmoid, String] {
|
||||
match load("compositor/wasm/testdata/" + name, test_tokens()) {
|
||||
Ok(p) => Ok(p)
|
||||
Err(_) => load("testdata/" + name, test_tokens())
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
test "a plasmoid component loads and renders through wasmer" {
|
||||
let p = load_fixture("clock-digital.component.wasm").unwrap()
|
||||
assert_eq(p.id, "org.moonplasma.clock.digital")
|
||||
assert_true(p.pref_w > 0 && p.pref_h > 0)
|
||||
let ops = p.render(p.pref_w, p.pref_h, test_tokens())
|
||||
assert_true(ops.length() > 0)
|
||||
// The digital clock draws its time as text, in the theme's foreground colour.
|
||||
let mut texts = 0
|
||||
for op in ops {
|
||||
match op {
|
||||
Text(t) => {
|
||||
texts = texts + 1
|
||||
assert_true(t.text.length() >= 4)
|
||||
assert_true(t.style.color.r == b'\xfa' || t.style.color.r == b'\x96') // theme foreground / muted
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
assert_true(texts >= 1)
|
||||
p.unload()
|
||||
}
|
||||
|
||||
///|
|
||||
test "a bare core module loads too, and junk is rejected" {
|
||||
let p = load_fixture("clock-digital.core.wasm").unwrap()
|
||||
assert_eq(p.id, "org.moonplasma.clock.digital")
|
||||
p.unload()
|
||||
assert_true(load("/nonexistent.wasm", test_tokens()) is Err(_))
|
||||
}
|
||||
|
||||
///| Load a panel module built by scripts/build-modules.sh.
|
||||
fn load_module(name : String) -> Plasmoid {
|
||||
match load("build/components/" + name + ".wasm", test_tokens()) {
|
||||
Ok(p) => p
|
||||
Err(_) => load("../../build/components/" + name + ".wasm", test_tokens()).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn texts_of(ops : Array[@types.DrawOp]) -> Array[String] {
|
||||
let out : Array[String] = []
|
||||
for op in ops {
|
||||
match op {
|
||||
Text(t) => out.push(t.text)
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
fn drain() -> Array[HostRequest] {
|
||||
let out : Array[HostRequest] = []
|
||||
while true {
|
||||
match next_request() {
|
||||
Some(r) => out.push(r)
|
||||
None => break
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
test "task list module draws the host's windows and asks to focus one" {
|
||||
let p = load_module("tasks")
|
||||
assert_true(p.stretch)
|
||||
assert_true(p.imports().contains("windows") && p.imports().contains("theme"))
|
||||
let t = Table::new()
|
||||
t.int(7)
|
||||
t.str("Kate — notes")
|
||||
t.int(1)
|
||||
t.int(0)
|
||||
t.end_row()
|
||||
t.int(9)
|
||||
t.str("foot")
|
||||
t.int(0)
|
||||
t.int(1)
|
||||
t.end_row()
|
||||
publish(Windows, t)
|
||||
let ops = p.render(400, 36, test_tokens())
|
||||
assert_eq(texts_of(ops), ["Kate — notes", "foot"])
|
||||
assert_true(p.on_event(false, PointerDown(146 + 10, 10)) || true)
|
||||
assert_eq(drain(), [FocusWindow(9)])
|
||||
p.unload()
|
||||
}
|
||||
|
||||
///|
|
||||
test "layout module shows the current mode, opens a popup and sets the layout" {
|
||||
let p = load_module("layout")
|
||||
let t = Table::new()
|
||||
for name in ["Tiling (BSP)", "Monocle", "Floating"] {
|
||||
t.str(name)
|
||||
t.end_row()
|
||||
}
|
||||
publish(Layouts, t)
|
||||
publish_state(1, false)
|
||||
assert_true(texts_of(p.render(130, 36, test_tokens())).contains("Monocle"))
|
||||
assert_true(p.popup() is None)
|
||||
assert_true(p.on_event(false, PointerDown(5, 5)))
|
||||
match p.popup() {
|
||||
None => fail("popup should be open")
|
||||
Some(ps) => {
|
||||
assert_true(ps.w > 100 && ps.h > 80)
|
||||
assert_true(texts_of(ps.ops).contains(" Floating"))
|
||||
}
|
||||
}
|
||||
assert_true(p.on_event(true, PointerDown(20, 4 + 28 * 2 + 3)))
|
||||
assert_eq(drain(), [SetLayout(2)])
|
||||
assert_true(p.popup() is None)
|
||||
p.unload()
|
||||
}
|
||||
|
||||
///|
|
||||
test "launcher module reads the host catalog, filters on typed keys and launches" {
|
||||
let p = load_module("launcher")
|
||||
let t = Table::new()
|
||||
for a in [("a.term", "Terminal"), ("b.files", "Files")] {
|
||||
t.str(a.0)
|
||||
t.str(a.1)
|
||||
t.str("comment")
|
||||
t.str("System")
|
||||
t.str("T")
|
||||
t.end_row()
|
||||
}
|
||||
publish(Apps, t)
|
||||
assert_true(p.on_event(false, PointerDown(1, 1)))
|
||||
assert_true(p.popup() is Some(_))
|
||||
for k in ["f", "i", "l", "e", "s"] {
|
||||
ignore(p.on_event(true, KeyDown(k)))
|
||||
}
|
||||
match p.popup() {
|
||||
Some(ps) => assert_true(texts_of(ps.ops).contains("Files"))
|
||||
None => fail("popup closed early")
|
||||
}
|
||||
assert_true(p.on_event(true, KeyDown("Enter")))
|
||||
assert_eq(drain(), [Launch("b.files")])
|
||||
assert_true(p.popup() is None)
|
||||
p.unload()
|
||||
}
|
||||
|
||||
///|
|
||||
test "module manager lists host modules and asks to load, unload and browse" {
|
||||
let p = load_module("module-manager")
|
||||
assert_true(p.imports().contains("modules"))
|
||||
let av = Table::new()
|
||||
av.str("moon-disc")
|
||||
av.str("Moon Phase (disc)")
|
||||
av.str("/m/moon-disc.wasm")
|
||||
av.int(0)
|
||||
av.end_row()
|
||||
publish(Modules, av)
|
||||
let li = Table::new()
|
||||
li.str("w1")
|
||||
li.str("clock-digital")
|
||||
li.str("Digital Clock")
|
||||
li.end_row()
|
||||
publish(Instances, li)
|
||||
assert_true(p.on_event(false, PointerDown(1, 1)))
|
||||
match p.popup() {
|
||||
None => fail("popup should be open")
|
||||
Some(ps) => {
|
||||
let ts = texts_of(ps.ops)
|
||||
assert_true(ts.contains("Digital Clock"))
|
||||
assert_true(ts.contains("Moon Phase (disc)"))
|
||||
}
|
||||
}
|
||||
// rows: header(24) loaded(28) header(24) available(28) browse(28)
|
||||
ignore(p.on_event(true, PointerDown(20, 4 + 24 + 3)))
|
||||
ignore(p.on_event(true, PointerDown(20, 4 + 24 + 28 + 24 + 3)))
|
||||
ignore(p.on_event(true, PointerDown(20, 4 + 24 + 28 + 24 + 28 + 3)))
|
||||
assert_eq(drain(), [UnloadInstance("w1"), LoadModule("/m/moon-disc.wasm"), Browse])
|
||||
p.unload()
|
||||
}
|
||||
|
||||
///|
|
||||
test "interface explorer module toggles through the inspector capability" {
|
||||
let p = load_module("inspector")
|
||||
assert_true(p.imports().contains("inspector"))
|
||||
publish_state(0, false)
|
||||
assert_true(p.on_event(false, PointerDown(3, 3)))
|
||||
assert_eq(drain(), [SetInspector(true)])
|
||||
p.unload()
|
||||
}
|
||||
|
||||
///|
|
||||
test "moon and 12-hour clock modules render from the clock capability" {
|
||||
let m = load_module("moon-disc")
|
||||
assert_true(m.render(36, 36, test_tokens()).length() > 3)
|
||||
m.unload()
|
||||
let c = load_module("clock-digital12")
|
||||
let ts = texts_of(c.render(120, 36, test_tokens()))
|
||||
assert_true(ts[0].has_suffix("AM") || ts[0].has_suffix("PM"))
|
||||
c.unload()
|
||||
}
|
||||
Reference in new issue
Block a user