Files
chandra/compositor/wasm/wasm_native.mbt
T
Claude f2e870c251
CI / test (push) Failing after 16s
Task manager: draw each app's real icon from its .desktop file
Each pill now shows the icon the app's .desktop file names (Icon=), looked up in the
freedesktop icon themes, instead of the letter tile. The tile stays as the fallback for
windows with no app id, no desktop file or no icon the host can read.

- WIT: a new `icons` capability (`app-icon(app-id) -> u32`, a handle, never a path or pixels)
  and an `image(image-op)` draw op (appended, so existing modules keep their ABI).
  taskbar-widget and plasmoid-host import `icons`. Host raster gains `load-image(path)` and a
  `draw-image` op; the plasmoids host gets an icons table (6: app id, handle).
- Compositor (shell/icons.mbt): window app id -> desktop file (resolve_app_id, so StartupWMClass
  and last-dotted-part matches work) -> Icon= -> theme lookup (XDG data dirs, ~/.icons,
  flatpak exports; hicolor, Adwaita, breeze; 48/64/32 px PNG first, then scalable SVG when the
  host can draw it, then other sizes, then /usr/share/pixmaps). Absolute Icon= paths are used as
  they are. Results are cached per app id; the table is published only when a module imports
  `icons`.
- wasm host (host-wasm): PNG via the png crate, SVG via resvg (rendered sharp at each size),
  PNGs area-averaged to the drawn size; loads cached by path.
- Native build: a small PNG decoder (compositor/renderer/png.mbt: inflate + filters, 1-16 bit,
  palettes with tRNS) and the Image op in the software renderer. SVG-only icons fall back to the
  tile there. The wasmer stub serves `icons.app-icon` from the same table.
- Tests: PNG decoder fixtures (all filters, fixed/dynamic/stored blocks, palette), image scaling
  and drawing, icon lookup order, Icon= parsing, task module icon-or-tile (native and wasmtime),
  host raster PNG+SVG loading and drawing. Checked end to end with the wasm host: foot's
  hicolor icon shows on its pill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhmtDt52EjaW8jevGU
2026-11-25 18:52:58 +00:00

750 lines
21 KiB
MoonBit

///| 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 (chandra: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 chandra 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)))
7 => out.push(Image({ rect: rect(o + 4), image: rd32(b, o + 20).reinterpret_as_uint() }))
_ => 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
Wallpapers
SessionSettings
/// App id -> image handle (`raster.load-image`), served by `icons.app-icon`.
Icons
}
///| 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
Wallpapers => 5
SessionSettings => 6
Icons => 7
}
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 })
}
///| Publish which wallpaper (an index into the Wallpapers table) is on the desktop.
pub fn publish_wallpaper(current : Int) -> Unit {
c_host_set_int(2, current)
}
///| Publish which session settings are on: bit i for row i of the SessionSettings table.
pub fn publish_session_settings(on : Int) -> Unit {
c_host_set_int(3, on)
}
///| Something a module asked the host to do during a call.
pub(all) enum HostRequest {
Launch(String)
FocusWindow(Int)
SetLayout(Int)
SetInspector(Bool)
LoadModule(String)
UnloadInstance(String)
Browse
Logout
SetWallpaper(Int)
/// Turn session setting `index` on or off.
SetSessionSetting(Int, Bool)
} 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)
8 => Some(Logout)
9 => Some(SetWallpaper(c_host_req_int()))
10 => Some(SetSessionSetting(c_host_req_int(), false))
11 => Some(SetSessionSetting(c_host_req_int(), true))
_ => 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
}