Files
chandra/compositor/wasm/wasm_host.mbt
T
Claude bb7c9b947f
CI / test (push) Failing after 45s
Settings > Apps: choose the default browser, email, files, terminal, editor, viewers and players
- A sixth Settings tab, Apps (key 6, SettingsTab::Apps; the popup is 390 px wide for it): Web
  browser, Email, File manager, Terminal, Text editor, Image viewer, Video player, Music player,
  PDF and documents, Archive manager. Each row shows the current default with its real icon (the
  icon-theme lookup the task manager uses; a letter tile when there is none). Click a row to list
  the installed apps that can take it, click one to make it the default. A chosen app that has
  been uninstalled since is named in red under its row ("gthumb is not installed any more").
- Installed apps come from the .desktop files in the XDG data dirs (and flatpak's exports), with
  MimeType= and Categories= (desktop_entry_keys, now shared with the launcher's parse_desktop).
  A kind lists the shown apps that handle one of its MIME types; the terminal lists
  TerminalEmulator apps; browsers are only offered as browsers.
- Reading follows the mimeapps.list spec: $XDG_CONFIG_HOME/[chandra-]mimeapps.list, then
  $XDG_CONFIG_DIRS (/etc/xdg), then $XDG_DATA_HOME and $XDG_DATA_DIRS applications/; the first
  installed [Default Applications] entry wins, else [Added Associations], else mimeinfo.cache
  (minus [Removed Associations]), else the first installed app that handles the type. A hidden
  (NoDisplay) default still counts and its name is shown.
- Setting writes [Default Applications] in ~/.config/mimeapps.list for each of the kind's MIME
  types the app handles (always the main one: http/https/text/html for browsers, mailto,
  inode/directory, text/plain, image/png..., video/mp4..., audio/mpeg..., application/pdf...,
  application/zip...), as xdg-mime default / xdg-settings do, without running them. Every other
  section, entry, comment and blank line is kept; the app leaves those types' [Removed
  Associations]; a chandra-mimeapps.list that already names one of those types is updated too.
- The terminal has no MIME type: state.edn :terminal "kitty" (desktop id), also written first in
  ~/.config/xdg-terminals.list (xdg-terminal-exec). Terminal=true apps from the launcher (and
  session restore) now start in it (foot -e, kgx/gnome-terminal/ptyxis --, kitty <cmd>, wezterm
  start --) instead of always foot; with no choice: xdg-terminals.list, then foot, then any
  installed terminal. Terminal apps are listed when any terminal emulator is installed, not only
  foot.
- New `default-apps` capability (categories, apps, set-default, refresh): host tables 11 (sss:
  name current missing) and 12 (issii: category id name icon current), request 19 (category *
  1000 + app, -1 rescans) in the wasmer/wasmtime stub, host-wasm and the MoonBit wasmhost
  (chandra:host/plasmoids default-app(s32)). Nothing is scanned until the tab opens (refresh).
- Tests with a temporary XDG tree: categories and current defaults (user file, system file,
  Added Associations, mimeinfo.cache, missing apps, hidden defaults), writing that keeps other
  entries, desktop-specific files, the terminal list and commands, the Apps tab end to end, and
  the :terminal round trip through state.edn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgywj7RPmFdFhpzGZj
2026-11-25 21:27:30 +00:00

475 lines
13 KiB
MoonBit

///| Plasmoid host for the compositor-as-a-wasm-component build.
///
/// The native build runs panel modules itself through wasmer. A component can't embed a second
/// wasm runtime, so here the same API is a thin client of the `chandra:host/plasmoids` import:
/// the host (wasmtime) instantiates the modules, serves their capability imports from the data
/// published below, and hands back draw ops and requests.
///|
fn utf8(s : String) -> Bytes {
let buf : Array[Byte] = []
for ch in s {
let code = ch.to_int()
if code < 0x80 {
buf.push(code.to_byte())
} else if code < 0x800 {
buf.push((0xC0 | (code >> 6)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
} else if code < 0x10000 {
buf.push((0xE0 | (code >> 12)).to_byte())
buf.push((0x80 | ((code >> 6) & 0x3F)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
} else {
buf.push((0xF0 | (code >> 18)).to_byte())
buf.push((0x80 | ((code >> 12) & 0x3F)).to_byte())
buf.push((0x80 | ((code >> 6) & 0x3F)).to_byte())
buf.push((0x80 | (code & 0x3F)).to_byte())
}
}
Bytes::from_array(buf)
}
///| The native build hands tokens to modules as packed bytes; here they cross as a typed record.
pub fn pack_tokens(_t : @theme.Tokens) -> Bytes {
Bytes::make(0, b'\x00')
}
///|
fn color_eq(a : @types.Color, b : @types.Color) -> Bool {
a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a
}
///|
fn tokens_eq(a : @theme.Tokens, b : @theme.Tokens) -> Bool {
let (p, q) = (a.palette, b.palette)
a.name == b.name &&
a.font_size == b.font_size &&
a.radius == b.radius &&
a.spacing == b.spacing &&
a.panel_height == b.panel_height &&
color_eq(p.desktop_top, q.desktop_top) &&
color_eq(p.desktop_bottom, q.desktop_bottom) &&
color_eq(p.surface, q.surface) &&
color_eq(p.surface_hover, q.surface_hover) &&
color_eq(p.surface_popup, q.surface_popup) &&
color_eq(p.foreground, q.foreground) &&
color_eq(p.foreground_muted, q.foreground_muted) &&
color_eq(p.accent, q.accent) &&
color_eq(p.accent_foreground, q.accent_foreground) &&
color_eq(p.border, q.border)
}
///| The tokens last handed to the host: every module's render sets them, and the shell renders
/// every module every frame with the same theme, so the host call is skipped while they match.
let sent_tokens : Ref[@theme.Tokens?] = { val: None }
///|
fn send_tokens(t : @theme.Tokens) -> Unit {
match sent_tokens.val {
Some(prev) if physical_equal(prev, t) || tokens_eq(prev, t) => ()
_ => {
sent_tokens.val = Some(t)
@hostpl.set_tokens(t)
}
}
}
///| A loaded plasmoid instance.
pub(all) struct Plasmoid {
handle : Int
id : String
name : String
pref_w : Int
pref_h : Int
min_w : Int
stretch : Bool
imports : Array[String]
}
///| Load a plasmoid component. Err carries a short reason.
pub fn load(path : String, tokens : @theme.Tokens) -> Result[Plasmoid, String] {
send_tokens(tokens)
match @hostpl.load(path) {
Err(e) => Err(e)
Ok(l) => {
let imports : Array[String] = []
for i in l.imports {
if i != "theme" {
imports.push(i)
}
}
Ok({
handle: l.handle.reinterpret_as_int(),
id: l.id,
name: l.name,
pref_w: l.preferred.w.reinterpret_as_int(),
pref_h: l.preferred.h.reinterpret_as_int(),
min_w: l.min_width.reinterpret_as_int(),
stretch: l.stretch,
imports,
})
}
}
}
///|
pub(all) struct SystemSnapshot {
cpu_permille : Int
mem_used_kib : Int64
mem_total_kib : Int64
battery_percent : Int
charging : Bool
uptime_secs : Int64
rx_bps : Int64
tx_bps : Int64
load_centi : Int
}
///|
pub(all) struct WindowEntry {
id : UInt64
title : String
app_id : String
focused : Bool
}
///|
pub fn set_system(s : SystemSnapshot) -> Unit {
@hostpl.publish_system({
cpu_permille: s.cpu_permille.reinterpret_as_uint(),
mem_used_kib: s.mem_used_kib.reinterpret_as_uint64(),
mem_total_kib: s.mem_total_kib.reinterpret_as_uint64(),
battery_percent: s.battery_percent,
charging: s.charging,
uptime_secs: s.uptime_secs.reinterpret_as_uint64(),
net_rx_bytes_per_sec: s.rx_bps.reinterpret_as_uint64(),
net_tx_bytes_per_sec: s.tx_bps.reinterpret_as_uint64(),
load_centi: s.load_centi.reinterpret_as_uint(),
})
}
///|
pub fn set_windows(wins : Array[WindowEntry]) -> Unit {
let out : Array[@hostpl.WindowEntry] = []
for w in wins {
out.push({ id: w.id, title: w.title, app_id: w.app_id, focused: w.focused })
}
@hostpl.publish_windows(out)
}
///|
pub fn take_focus_request() -> UInt64? {
@hostpl.take_focus_request()
}
///|
pub fn Plasmoid::pointer_down(self : Plasmoid, x : Int, y : Int) -> Bool {
self.on_event(false, PointerDown(x, y))
}
///|
pub fn Plasmoid::unload(self : Plasmoid) -> Unit {
@hostpl.unload(self.handle.reinterpret_as_uint())
}
///|
pub fn Plasmoid::render(
self : Plasmoid,
w : Int,
h : Int,
tokens : @theme.Tokens,
) -> Array[@types.DrawOp] {
send_tokens(tokens)
@hostpl.render(self.handle.reinterpret_as_uint(), { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() })
}
///| A popup surface a plasmoid wants shown next to its panel widget.
pub(all) struct PopupSurface {
w : Int
h : Int
ops : Array[@types.DrawOp]
}
///|
pub fn Plasmoid::popup(self : Plasmoid) -> PopupSurface? {
match @hostpl.popup(self.handle.reinterpret_as_uint()) {
None => None
Some(p) =>
Some({ w: p.box.w.reinterpret_as_int(), h: p.box.h.reinterpret_as_int(), ops: p.ops })
}
}
///| An input event for a plasmoid (mirrors the WIT `input-event`).
pub(all) enum PlasmoidEvent {
PointerMove(Int, Int)
PointerDown(Int, Int)
PointerUp(Int, Int)
PointerLeave
FocusLost
KeyDown(String)
}
///|
pub fn Plasmoid::on_event(self : Plasmoid, popup : Bool, ev : PlasmoidEvent) -> Bool {
let e : @types.InputEvent = match ev {
PointerMove(x, y) => PointerMove({ x, y })
PointerDown(x, y) => PointerDown({ x, y })
PointerUp(x, y) => PointerUp({ x, y })
PointerLeave => PointerLeave
FocusLost => FocusLost
KeyDown(k) => KeyDown(k)
}
@hostpl.on_event(self.handle.reinterpret_as_uint(), popup, e)
}
///| One of a module's own settings (the WIT `module-config.config-item`): `choices` empty means
/// an on/off switch whose value is "on" or "off".
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
} derive(Eq, Debug)
///| The module's settings for its right-click menu; empty when it doesn't export `module-config`.
pub fn Plasmoid::config_items(self : Plasmoid) -> Array[ConfigItem] {
@hostpl.config_items(self.handle.reinterpret_as_uint()).map(c => {
key: c.key,
label: c.label,
choices: c.choices,
value: c.value,
})
}
///| Set one of the module's settings. True when the widget asks for a redraw.
pub fn Plasmoid::set_config(self : Plasmoid, key : String, value : String) -> Bool {
@hostpl.set_config(self.handle.reinterpret_as_uint(), key, value)
}
///|
pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] {
self.imports
}
///| Rows of host data a module can read through its capability imports.
pub(all) struct Table {
rows : Array[Byte]
mut n : Int
}
///|
pub fn Table::new() -> Table {
{ rows: [], n: 0 }
}
///|
fn Table::push32(self : Table, v : Int) -> Unit {
for k = 0; k < 4; k = k + 1 {
self.rows.push(((v >> (8 * k)) & 0xFF).to_byte())
}
}
///| An i32 field.
pub fn Table::int(self : Table, v : Int) -> Unit {
self.push32(v)
}
///| A string field.
pub fn Table::str(self : Table, s : String) -> Unit {
let b = utf8(s)
self.push32(b.length())
for i = 0; i < b.length(); i = i + 1 {
self.rows.push(b[i])
}
}
///| Finish one row.
pub fn Table::end_row(self : Table) -> Unit {
self.n = self.n + 1
}
///|
pub(all) enum HostTable {
Apps
Windows
Layouts
Modules
Instances
Wallpapers
SessionSettings
/// App id -> image handle (`raster.load-image`), served by `icons.app-icon`.
Icons
/// One row (iissiiii): the network status `network.status` returns.
NetStatus
/// Wi-Fi networks in range (siiii: ssid signal secured active saved).
NetNetworks
/// Keyboard shortcuts (ssssi: name binding default-binding conflict capturing).
Shortcuts
/// Default-app categories (sss: name current missing).
AppCategories
/// Default-app choices (issii: category id name icon current).
AppChoices
}
///|
pub fn publish(which : HostTable, t : Table) -> Unit {
// [u32 row count][rows], the encoding the host parses.
let n = t.n
let out : FixedArray[Byte] = FixedArray::make(4 + t.rows.length(), b'\x00')
for k = 0; k < 4; k = k + 1 {
out[k] = ((n >> (8 * k)) & 0xFF).to_byte()
}
for i = 0; i < t.rows.length(); i = i + 1 {
out[4 + i] = t.rows[i]
}
let id = match which {
Apps => 0U
Windows => 1U
Layouts => 2U
Modules => 3U
Instances => 4U
Wallpapers => 5U
SessionSettings => 6U
Icons => 7U
NetStatus => 8U
NetNetworks => 9U
Shortcuts => 10U
AppCategories => 11U
AppChoices => 12U
}
// Most tables are republished every frame unchanged: skip the copy into the host then.
let slot = id.reinterpret_as_int()
while published.length() <= slot {
published.push(None)
}
match published[slot] {
Some(prev) => if prev == out { return }
None => ()
}
published[slot] = Some(out)
@hostpl.publish_table(id, out)
}
///| The bytes last sent for each table, by table id.
let published : Array[FixedArray[Byte]?] = []
///|
pub fn publish_state(layout_mode : Int, inspector_on : Bool) -> Unit {
@hostpl.publish_state(layout_mode, inspector_on)
}
///|
pub fn publish_wallpaper(current : Int) -> Unit {
@hostpl.publish_wallpaper(current)
}
///| Which session settings are on: bit i for row i of the SessionSettings table.
pub fn publish_session_settings(on : Int) -> Unit {
@hostpl.publish_session_settings(on.reinterpret_as_uint())
}
///| Publish the screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer.
pub fn publish_screenshot(state : Int) -> Unit {
@hostpl.publish_screenshot(state.reinterpret_as_uint())
}
///| The power timeouts, in minutes (0: never).
pub fn publish_power(screen_off : Int, suspend : Int) -> Unit {
@hostpl.publish_power(screen_off.reinterpret_as_uint(), suspend.reinterpret_as_uint())
}
///| The battery (the `battery` capability): percent (-1: none), charge-state index, seconds left.
pub fn publish_battery(percent : Int, state : Int, secs_left : Int) -> Unit {
@hostpl.publish_battery(percent, state.reinterpret_as_uint(), secs_left.reinterpret_as_uint())
}
///| 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)
/// Move a panel instance `delta` places (negative: towards the start of the panel).
MoveInstance(String, Int)
Browse
Logout
SetWallpaper(Int)
/// Turn session setting `index` on or off.
SetSessionSetting(Int, Bool)
/// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on.
Screenshot(Int)
/// Power: screen-off / suspend timeouts in minutes (0: never), an action now (0 suspend,
/// 1 power off, 2 restart).
SetScreenOff(Int)
SetSuspendAfter(Int)
PowerAction(Int)
/// A network module's action (0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode
/// off/on, 6 connect, 7 forget), with the network name and password where it needs them.
Network(Int, String, String)
/// The shortcuts capability: action * 1000 + index (0 capture, 1 reset, 2 reset all, 3 cancel
/// the capture).
Shortcut(Int)
/// The default-apps capability: category * 1000 + app sets that category's default, -1 scans
/// the apps and defaults again.
DefaultApp(Int)
/// The session capability's `reload`: reload every loaded panel module from disk.
ReloadSession
} derive(Eq, Debug)
///|
pub fn next_request() -> HostRequest? {
match @hostpl.next_request() {
None => None
Some(Launch(id)) => Some(Launch(id))
Some(FocusWindow(n)) => Some(FocusWindow(n))
Some(SetLayout(m)) => Some(SetLayout(m))
Some(SetInspector(on)) => Some(SetInspector(on))
Some(LoadModule(p)) => Some(LoadModule(p))
Some(UnloadInstance(s)) => Some(UnloadInstance(s))
Some(MoveInstance(m)) => Some(MoveInstance(m.slot, m.delta))
Some(Browse) => Some(Browse)
Some(Logout) => Some(Logout)
Some(SetWallpaper(i)) => Some(SetWallpaper(i))
Some(SetSessionSetting(c)) => Some(SetSessionSetting(c.index, c.on))
Some(Screenshot(code)) => Some(Screenshot(code))
Some(SetScreenOff(m)) => Some(SetScreenOff(m))
Some(SetSuspendAfter(m)) => Some(SetSuspendAfter(m))
Some(PowerAction(a)) => Some(PowerAction(a))
Some(Network(r)) => Some(Network(r.action, r.ssid, r.password))
Some(Shortcut(code)) => Some(Shortcut(code))
Some(DefaultApp(code)) => Some(DefaultApp(code))
Some(ReloadSession) => Some(ReloadSession)
}
}
///|
pub fn list_wasm_files(dir : String) -> Array[String] {
@hostpl.list_wasm_files(dir)
}
///| An in-flight native file-chooser dialog.
pub(all) struct Picker {
fd : Int
buf : Array[Byte]
}
///|
pub fn Picker::start() -> Picker? {
if @hostpl.picker_start() {
Some({ fd: 0, buf: [] })
} else {
None
}
}
///|
pub fn Picker::poll(_self : Picker) -> String?? {
match @hostpl.picker_poll() {
Open => None
Cancelled => Some(None)
Chosen(path) => Some(Some(path))
}
}