diff --git a/.gitignore b/.gitignore index 806b78e..b470e36 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ node_modules/ *.log host-native/target/ .pixi/ +host-wasm/target/ diff --git a/components/compositor/gen/ffi.mbt b/components/compositor/gen/ffi.mbt new file mode 100644 index 0000000..a8c249a --- /dev/null +++ b/components/compositor/gen/ffi.mbt @@ -0,0 +1,46 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +pub fn mbt_ffi_cabi_realloc( +src_offset : Int, +src_size : Int, +_dst_alignment : Int, +dst_size : Int, +) -> Int { + // malloc + if src_offset == 0 && src_size == 0 { + return mbt_ffi_malloc(dst_size) + } + // free + if dst_size == 0 { + mbt_ffi_free(src_offset) + return 0 + } + // realloc + let dst = mbt_ffi_malloc(dst_size) + mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size }) + mbt_ffi_free(src_offset) + dst +} + +///| +extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) = +#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +#doc(hidden) +pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int { + @compositor.wasmExportRun(p0, p1) +} + diff --git a/components/compositor/gen/moon.pkg b/components/compositor/gen/moon.pkg new file mode 100644 index 0000000..c4db55e --- /dev/null +++ b/components/compositor/gen/moon.pkg @@ -0,0 +1,20 @@ +import { + "moonplasma/desktop/components/compositor/gen/world/compositor" @compositor, +} + +warnings = "-44" + +pkgtype(kind: "foreign_library") + +options( + link: { + "wasm": { + "export-memory-name": "memory", + "heap-start-address": 16, + "exports": [ + "mbt_ffi_cabi_realloc:cabi_realloc", + "wasmExportRun:run" + ], + }, + }, +) diff --git a/components/compositor/gen/world/compositor/ffi.mbt b/components/compositor/gen/world/compositor/ffi.mbt new file mode 100644 index 0000000..ba7429b --- /dev/null +++ b/components/compositor/gen/world/compositor/ffi.mbt @@ -0,0 +1,37 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +#doc(hidden) +pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int { + + let array : Array[String] = []; + for index = 0; index < (p1); index = index + 1 { + let iter_base = (p0) + (index * 8) + + let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4)) + + array.push(result) + } + mbt_ffi_free(p0) + + let (result0) : (Int) = run(array); + let ret = result0 + return ret + +} + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load) + +///| +extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + diff --git a/components/compositor/gen/world/compositor/moon.pkg b/components/compositor/gen/world/compositor/moon.pkg new file mode 100644 index 0000000..9d3ce44 --- /dev/null +++ b/components/compositor/gen/world/compositor/moon.pkg @@ -0,0 +1,5 @@ +import { + "moonplasma/desktop/compositor/app" @app, +} + +warnings = "-44" diff --git a/components/compositor/gen/world/compositor/stub.mbt b/components/compositor/gen/world/compositor/stub.mbt new file mode 100644 index 0000000..65a2450 --- /dev/null +++ b/components/compositor/gen/world/compositor/stub.mbt @@ -0,0 +1,6 @@ +///| The compositor component's entry point: everything lives in compositor/app. + +///| +pub fn run(args : Array[String]) -> Int { + @app.run(args) +} diff --git a/components/compositor/gen/world/compositor/top.mbt b/components/compositor/gen/world/compositor/top.mbt new file mode 100644 index 0000000..50198b4 --- /dev/null +++ b/components/compositor/gen/world/compositor/top.mbt @@ -0,0 +1,5 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +/// Run the compositor until it exits. `args` are the command-line arguments (without argv[0]). +declare pub fn run(args : Array[String]) -> Int + diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt new file mode 100644 index 0000000..5179280 --- /dev/null +++ b/compositor/app/app.mbt @@ -0,0 +1,171 @@ +///| The compositor's entry point as a library: argument parsing and the main loop, with the +/// operating system reached only through `@sys`. The wasm component (components/compositor) +/// calls `run`; on the native side it is the same code with `@sys` backed by a C shim. +/// +/// Arguments: --socket PATH --theme PATH --window --gfx-out PNG --serve --size WxH +/// With --gfx-out alone one frame is written and the program exits; add --serve to keep running +/// and rewrite the PNG about twice a second (for looking at a live compositor without a display). + +///| Parse a decimal integer; None unless every character is a digit. +fn parse_dec(s : String) -> Int? { + if s.length() == 0 || s.length() > 6 { + return None + } + let mut n = 0 + for ch in s { + let d = ch.to_int() - 48 + if d < 0 || d > 9 { + return None + } + n = n * 10 + d + } + Some(n) +} + +///| "WxH" -> (W, H), both positive. +fn parse_size(s : String) -> (Int, Int)? { + let mut x = -1 + for i = 0; i < s.length(); i = i + 1 { + if s[i] == 'x' { + x = i + } + } + if x <= 0 { + return None + } + match (parse_dec(s[:x].to_string()), parse_dec(s[x + 1:].to_string())) { + (Some(w), Some(h)) if w > 0 && h > 0 => Some((w, h)) + _ => None + } +} + +///| Run the compositor until it exits. Returns the process exit code. +pub fn run(args : Array[String]) -> Int { + let mut socket_path = "/tmp/wayland-moon-0" + let mut theme_path = "config/themes/moon-night.json" + let mut gfx_out = "" + let mut windowed = false + let mut serve = false + let mut width = 1280 + let mut height = 720 + + let mut i = 0 + while i < args.length() { + let a = args[i] + if a == "--socket" && i + 1 < args.length() { + socket_path = args[i + 1] + i = i + 2 + } else if a == "--theme" && i + 1 < args.length() { + theme_path = args[i + 1] + i = i + 2 + } else if a == "--window" { + windowed = true + i = i + 1 + } else if a == "--serve" { + serve = true + i = i + 1 + } else if a == "--gfx-out" && i + 1 < args.length() { + gfx_out = args[i + 1] + i = i + 2 + } else if a == "--size" && i + 1 < args.length() { + match parse_size(args[i + 1]) { + Some((w, h)) => { + width = w + height = h + } + None => { + @sys.log("bad --size " + args[i + 1] + " (expected WxH)") + return 2 + } + } + i = i + 2 + } else { + i = i + 1 + } + } + + let raw_theme = @sys.read_file_bytes(theme_path) + let theme = if raw_theme.length() > 0 { + let sb = StringBuilder() + for j = 0; j < raw_theme.length(); j = j + 1 { + sb.write_char(Int::unsafe_to_char(raw_theme[j].to_int())) + } + @scene.ThemeTokens::from_json_string(sb.to_string()) + } else { + @scene.ThemeTokens::moon_night() + } + + let gfx_surface = @gfx.Surface::new({ width: Some(width), height: Some(height) }) + let gfx_ctx = @gfx.SurfaceFrameBufferContext::new(gfx_surface) + + match @host.MoonPlasmaCompositor::new(socket_path, theme, width, height) { + None => { + @sys.log("failed to bind Wayland socket at " + socket_path) + 1 + } + Some(comp) => { + comp.shell.screen_w = width + if gfx_out.length() > 0 && !serve { + let pixmap = comp.present_to_gfx(gfx_ctx) + ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(pixmap))) + comp.close() + @sys.log("frame written to " + gfx_out) + return 0 + } + let nested = if windowed { + let display = match @sys.getenv("WAYLAND_DISPLAY") { + "" => "wayland-0" + d => d + } + let rt = match @sys.getenv("XDG_RUNTIME_DIR") { + "" => "/tmp" + d => d + } + match @nested.NestedWindow::open(display, rt, "moon-plasma", "moon-plasma", width, height) { + Some(n) => Some(n) + None => { + @sys.log("failed to open a window on the host Wayland display") + comp.close() + return 1 + } + } + } else { + None + } + @sys.log("moon-plasma compositor listening on " + socket_path) + let mut frames = 0 + while true { + frames = frames + 1 + comp.step() + match nested { + Some(n) => { + if !n.poll() { + break + } + if n.keymap.length() > 0 { + comp.server.set_keymap(n.keymap) + } + let now_ms = @sys.monotonic_ms().to_uint() + for ev in n.take_input() { + comp.handle_input(ev, now_ms) + } + n.set_cursor_shape(comp.desired_cursor()) + if n.frame_ready() { + n.present(comp.present_to_gfx(gfx_ctx)) + } + } + None => { + comp.handle_gfx_events(gfx_surface) + let pixmap = comp.present_to_gfx(gfx_ctx) + if serve && gfx_out.length() > 0 && frames % 30 == 0 { + ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(pixmap))) + } + } + } + @sys.sleep_ms(16) + } + comp.close() + 0 + } + } +} diff --git a/compositor/app/moon.pkg b/compositor/app/moon.pkg new file mode 100644 index 0000000..7ba09f1 --- /dev/null +++ b/compositor/app/moon.pkg @@ -0,0 +1,11 @@ +import { + "moonbitlang/core/builtin", + "moonplasma/desktop/compositor/sys" @sys, + "moonplasma/desktop/compositor/scene" @scene, + "moonplasma/desktop/compositor/renderer" @renderer, + "moonplasma/desktop/compositor/gfx" @gfx, + "moonplasma/desktop/compositor/host" @host, + "moonplasma/desktop/compositor/nested" @nested, +} + +supported_targets = "+native+wasm" diff --git a/compositor/app/pkg.generated.mbti b/compositor/app/pkg.generated.mbti new file mode 100644 index 0000000..a67c0c1 --- /dev/null +++ b/compositor/app/pkg.generated.mbti @@ -0,0 +1,13 @@ +// Generated using `moon info`, DON'T EDIT IT +package "moonplasma/desktop/compositor/app" + +// Values +pub fn run(Array[String]) -> Int32 + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/compositor/font/font.mbt b/compositor/font/font_native.mbt similarity index 100% rename from compositor/font/font.mbt rename to compositor/font/font_native.mbt diff --git a/compositor/font/font_wasm.mbt b/compositor/font/font_wasm.mbt new file mode 100644 index 0000000..7731525 --- /dev/null +++ b/compositor/font/font_wasm.mbt @@ -0,0 +1,7 @@ +///| The compositor as a wasm component has no C rasteriser. Until the host offers glyphs through +/// an import, text uses the renderer's built-in bitmap font. + +///| Install real fonts; always false here, so the renderer keeps its bitmap font. +pub fn install() -> Bool { + false +} diff --git a/compositor/font/moon.pkg b/compositor/font/moon.pkg index 7199de4..40b8728 100644 --- a/compositor/font/moon.pkg +++ b/compositor/font/moon.pkg @@ -3,8 +3,12 @@ import { "moonplasma/desktop/compositor/renderer" @renderer, } -supported_targets = "-all+native" +supported_targets = "+native+wasm" options( + targets: { + "font_native.mbt": ["native"], + "font_wasm.mbt": ["wasm"], + }, "native-stub": [ "font_stub.c" ], ) diff --git a/compositor/host/moon.pkg b/compositor/host/moon.pkg index f9ffbe2..5957918 100644 --- a/compositor/host/moon.pkg +++ b/compositor/host/moon.pkg @@ -12,7 +12,7 @@ import { "moonplasma/desktop/compositor/gfx" @gfx, } -supported_targets = "-all+native" +supported_targets = "+native+wasm" options( link: { diff --git a/compositor/nested/moon.pkg b/compositor/nested/moon.pkg index 3507acb..2f92545 100644 --- a/compositor/nested/moon.pkg +++ b/compositor/nested/moon.pkg @@ -5,4 +5,4 @@ import { "moonplasma/desktop/compositor/wayland" @wayland, } -supported_targets = "-all+native" +supported_targets = "+native+wasm" diff --git a/compositor/nested/nested.mbt b/compositor/nested/nested.mbt index ec0640f..7906a3c 100644 --- a/compositor/nested/nested.mbt +++ b/compositor/nested/nested.mbt @@ -129,7 +129,7 @@ fn NestedWindow::dispatch( if op == 0U { let _id = r.u32() let _code = r.u32() - println("nested: host wl_display error: " + r.str()) + @sys.log("nested: host wl_display error: " + r.str()) self.closed = true } } else if obj == 2U { @@ -342,7 +342,7 @@ pub fn NestedWindow::open( self.seat_id = self.bind("wl_seat", 5U) self.shape_mgr_id = self.bind("wp_cursor_shape_manager_v1", 1U) if self.comp_id == 0U || self.shm_id == 0U || self.wm_id == 0U { - println("nested: host compositor lacks wl_compositor/wl_shm/xdg_wm_base") + @sys.log("nested: host compositor lacks wl_compositor/wl_shm/xdg_wm_base") return None } self.surf_id = self.alloc() @@ -381,7 +381,7 @@ pub fn NestedWindow::open( tries = tries + 1 } if !self.configured { - println("nested: host never sent xdg_surface.configure") + @sys.log("nested: host never sent xdg_surface.configure") return None } Some(self) diff --git a/compositor/shell/moon.pkg b/compositor/shell/moon.pkg index c93000b..fd00693 100644 --- a/compositor/shell/moon.pkg +++ b/compositor/shell/moon.pkg @@ -16,7 +16,7 @@ import { "moonplasma/desktop/compositor/wasm" @wasm, } -supported_targets = "-all+native" +supported_targets = "+native+wasm" options( link: { diff --git a/compositor/sys/moon.pkg b/compositor/sys/moon.pkg index 371a4eb..dd86adb 100644 --- a/compositor/sys/moon.pkg +++ b/compositor/sys/moon.pkg @@ -1,9 +1,17 @@ import { "moonbitlang/core/builtin", + "moonbitlang/core/env" @env, + "moonplasma/desktop/interface/moonplasma/host/sys" @hostsys, } -supported_targets = "-all+native" +supported_targets = "+native+wasm" +// Native: POSIX through a C shim. Wasm (the compositor as a component): the same API over the +// moonplasma:host/sys imports, implemented by the native host. options( + targets: { + "sys_native.mbt": ["native"], + "sys_wasm.mbt": ["wasm"], + }, "native-stub": [ "sys_stub.c" ], ) diff --git a/compositor/sys/sys.mbt b/compositor/sys/sys_native.mbt similarity index 96% rename from compositor/sys/sys.mbt rename to compositor/sys/sys_native.mbt index 0e25889..a391082 100644 --- a/compositor/sys/sys.mbt +++ b/compositor/sys/sys_native.mbt @@ -246,3 +246,13 @@ extern "C" fn c_read_proc(path : Bytes) -> Bytes = "mp_read_proc" pub fn read_proc_bytes(path : String) -> Bytes { c_read_proc(str_to_utf8_bytes(path)) } + +///| Milliseconds on a monotonic clock. +pub fn monotonic_ms() -> UInt64 { + @env.now() +} + +///| Print a line to stderr (stdout on native). +pub fn log(message : String) -> Unit { + println(message) +} diff --git a/compositor/sys/sys_wasm.mbt b/compositor/sys/sys_wasm.mbt new file mode 100644 index 0000000..6863468 --- /dev/null +++ b/compositor/sys/sys_wasm.mbt @@ -0,0 +1,169 @@ +///| The compositor as a wasm component: the same API as sys_native.mbt, with every operation +/// forwarded to the host through the `moonplasma:host/sys` imports. The component holds only +/// integer handles (fds) and bytes; the host owns the real descriptors. + +///| Encode a String into UTF-8 Bytes. +pub fn str_to_utf8_bytes(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) +} + +///| +fn to_fixed(b : Bytes) -> FixedArray[Byte] { + let out : FixedArray[Byte] = FixedArray::make(b.length(), b'\x00') + for i = 0; i < b.length(); i = i + 1 { + out[i] = b[i] + } + out +} + +///| +fn from_fixed(a : FixedArray[Byte]) -> Bytes { + Bytes::from_fixedarray(a) +} + +///| +pub fn unix_listen(path : String) -> Int { + @hostsys.unix_listen(path) +} + +///| +pub fn unix_accept(listen_fd : Int) -> Int { + @hostsys.unix_accept(listen_fd) +} + +///| +pub fn unix_connect(path : String) -> Int { + @hostsys.unix_connect(path) +} + +///| +pub fn close_fd(fd : Int) -> Unit { + @hostsys.close_fd(fd) +} + +///| +pub fn unlink(path : String) -> Unit { + @hostsys.unlink(path) +} + +///| +pub fn poll_read(fd : Int, timeout_ms : Int) -> Int { + @hostsys.poll_read(fd, timeout_ms) +} + +///| Receive bytes and an optional SCM_RIGHTS fd into `buf`. Returns (bytes_read, received_fd); +/// bytes_read == -1 means EAGAIN, -2 an error, 0 EOF. +pub fn recvmsg_fd(fd : Int, buf : FixedArray[Byte], max_len : Int) -> (Int, Int) { + let r = @hostsys.recvmsg(fd, max_len.reinterpret_as_uint()) + if r.count > 0 { + let n = if r.count < r.data.length() { r.count } else { r.data.length() } + for i = 0; i < n && i < buf.length(); i = i + 1 { + buf[i] = r.data[i] + } + } + (r.count, r.fd) +} + +///| +pub fn sendmsg_fd(fd : Int, buf : Bytes, send_fd : Int) -> Int { + @hostsys.sendmsg(fd, to_fixed(buf), send_fd) +} + +///| +pub fn memfd_create(name : String, size : Int) -> Int { + @hostsys.memfd_create(name, size) +} + +///| +pub fn pwrite_bytes(fd : Int, buf : Bytes, offset : Int) -> Int { + @hostsys.pwrite(fd, to_fixed(buf), offset) +} + +///| +pub fn mmap_read(fd : Int, size : Int) -> Bytes { + from_fixed(@hostsys.mmap_read(fd, size)) +} + +///| +pub fn read_file_bytes(path : String) -> Bytes { + from_fixed(@hostsys.read_file(path)) +} + +///| +pub fn write_file_bytes(path : String, data : Bytes) -> Int { + @hostsys.write_file(path, to_fixed(data)) +} + +///| +pub fn sleep_ms(ms : Int) -> Unit { + @hostsys.sleep_ms(ms) +} + +///| +pub fn getpid() -> Int { + @hostsys.getpid() +} + +///| Local wall clock: 0 year, 1 month (1-12), 2 day, 3 hour, 4 minute, 5 second, 6 weekday (0 = Sunday). +pub fn wall_time_field(which : Int) -> Int { + @hostsys.wall_time_field(which) +} + +///| Whether `name` is an executable on PATH. +pub fn has_exe(name : String) -> Bool { + @hostsys.has_exe(name) +} + +///| Launch `cmd` detached with WAYLAND_DISPLAY set to `display`. +pub fn spawn(cmd : String, display : String) -> Bool { + @hostsys.spawn(cmd, display) +} + +///| Names of the `*.desktop` files directly in `dir`. +pub fn list_desktop_files(dir : String) -> Array[String] { + @hostsys.list_desktop_files(dir) +} + +///| Environment variable, or "" when unset. +pub fn getenv(name : String) -> String { + @hostsys.getenv(name) +} + +///| Create `path` and any missing parents; true when it exists afterwards. +pub fn mkdir_p(path : String) -> Bool { + @hostsys.mkdir_p(path) +} + +///| Contents of a small /proc or /sys file ("" when unreadable). +pub fn read_proc_bytes(path : String) -> Bytes { + from_fixed(@hostsys.read_proc(path)) +} + +///| Milliseconds on the host's monotonic clock. +pub fn monotonic_ms() -> UInt64 { + @hostsys.monotonic_ms() +} + +///| Print a line to the host's stderr. +pub fn log(message : String) -> Unit { + @hostsys.log(message) +} diff --git a/compositor/wasm/moon.pkg b/compositor/wasm/moon.pkg index 105b3a2..2b1764a 100644 --- a/compositor/wasm/moon.pkg +++ b/compositor/wasm/moon.pkg @@ -4,9 +4,14 @@ import { "moonplasma/desktop/interface/moonplasma/desktop/theme" @theme, } -supported_targets = "-all+native" +supported_targets = "+native+wasm" options( + targets: { + "wasm_native.mbt": ["native"], + "wasm_unsupported.mbt": ["wasm"], + "wasm_test.mbt": ["native"], + }, "native-stub": [ "wasm_stub.c" ], link: { "native": { diff --git a/compositor/wasm/wasm.mbt b/compositor/wasm/wasm_native.mbt similarity index 100% rename from compositor/wasm/wasm.mbt rename to compositor/wasm/wasm_native.mbt diff --git a/compositor/wasm/wasm_unsupported.mbt b/compositor/wasm/wasm_unsupported.mbt new file mode 100644 index 0000000..9f78bd6 --- /dev/null +++ b/compositor/wasm/wasm_unsupported.mbt @@ -0,0 +1,233 @@ +///| 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 the module host will become a host import (the native side instantiating the +/// modules with wasmtime). Until that import exists, the same API is here with nothing loadable: +/// `load` fails, no requests ever arrive, and the panel stays empty. + +///| +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) +} + +///| +pub fn pack_tokens(_t : @theme.Tokens) -> Bytes { + Bytes::make(64, b'\x00') +} + +///| 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] +} + +///| Always fails in the component build (see the file comment). +pub fn load(_path : String, _tokens : @theme.Tokens) -> Result[Plasmoid, String] { + Err("panel modules are not available in the wasm compositor yet") +} + +///| +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 { + () +} + +///| +pub fn set_windows(_wins : Array[WindowEntry]) -> Unit { + () +} + +///| +pub fn take_focus_request() -> UInt64? { + None +} + +///| +pub fn Plasmoid::pointer_down(_self : Plasmoid, _x : Int, _y : Int) -> Bool { + false +} + +///| +pub fn Plasmoid::unload(_self : Plasmoid) -> Unit { + () +} + +///| +pub fn Plasmoid::render( + _self : Plasmoid, + _w : Int, + _h : Int, + _tokens : @theme.Tokens, +) -> Array[@types.DrawOp] { + [] +} + +///| 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? { + None +} + +///| 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 { + false +} + +///| +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 +} + +///| +pub fn publish(_which : HostTable, _t : Table) -> Unit { + () +} + +///| +pub fn publish_state(_layout_mode : Int, _inspector_on : Bool) -> Unit { + () +} + +///| 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) + +///| +pub fn next_request() -> HostRequest? { + None +} + +///| +pub fn list_wasm_files(_dir : String) -> Array[String] { + [] +} + +///| An in-flight native file-chooser dialog. +pub(all) struct Picker { + fd : Int + buf : Array[Byte] +} + +///| +pub fn Picker::start() -> Picker? { + None +} + +///| +pub fn Picker::poll(_self : Picker) -> String?? { + None +} diff --git a/compositor/wayland/moon.pkg b/compositor/wayland/moon.pkg index de7c81b..1c31745 100644 --- a/compositor/wayland/moon.pkg +++ b/compositor/wayland/moon.pkg @@ -4,4 +4,4 @@ import { "moonplasma/desktop/compositor/scene" @scene, } -supported_targets = "-all+native" +supported_targets = "+native+wasm" diff --git a/host-wasm/Cargo.lock b/host-wasm/Cargo.lock new file mode 100644 index 0000000..f481caf --- /dev/null +++ b/host-wasm/Cargo.lock @@ -0,0 +1,1168 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59317f77929f0e679d39364702289274de2f0f0b22cbf50b2b8cff2169a0b27a" +dependencies = [ + "gimli", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" +dependencies = [ + "allocator-api2", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpp_demangle" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0667304c32ea56cb4cd6d2d7c0cfe9a2f8041229db8c033af7f8d69492429def" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cranelift-assembler-x64" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147e998317ed418623afd8dc719b3413d391a3b2f048100f459a90dadfd4fd72" +dependencies = [ + "cranelift-assembler-x64-meta", +] + +[[package]] +name = "cranelift-assembler-x64-meta" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775c4e3222b290bc05e07e73e0cfab0b3b4c6510034f70585fa7cbf4feb9f0ea" +dependencies = [ + "cranelift-srcgen", +] + +[[package]] +name = "cranelift-bforest" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f64e582cbf252e01cbcf4c701b26a349fab461a9f0c327025995db64b1364a78" +dependencies = [ + "cranelift-entity", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-bitset" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba37434039b4cdc98d3178eefca3f5bd180b955e49c0787e9cc0eee3de182fcb" +dependencies = [ + "serde", + "serde_derive", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-codegen" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "028652607246c4117796ed9ab9e966994b4ee12146b329a91e85c8fd1335152f" +dependencies = [ + "bumpalo", + "cranelift-assembler-x64", + "cranelift-bforest", + "cranelift-bitset", + "cranelift-codegen-meta", + "cranelift-codegen-shared", + "cranelift-control", + "cranelift-entity", + "cranelift-isle", + "gimli", + "hashbrown 0.17.2", + "libm", + "log", + "postcard", + "pulley-interpreter", + "regalloc2", + "rustc-hash", + "serde", + "serde_derive", + "sha2", + "smallvec", + "target-lexicon", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-codegen-meta" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21ba849e90d3398951aef9a9a3d2fa1e7df6196836ae1d0723ec24b091215b84" +dependencies = [ + "cranelift-assembler-x64-meta", + "cranelift-codegen-shared", + "cranelift-srcgen", + "heck", + "pulley-interpreter", +] + +[[package]] +name = "cranelift-codegen-shared" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6116ab06dc15034ee1b4e3124371acb6742c189b438040837aeb0cfcf790e356" + +[[package]] +name = "cranelift-control" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33a932ab1cef0158e6b0f0360139d5d19bdf7a3bee0160f02865b1bdafb218c7" +dependencies = [ + "arbitrary", +] + +[[package]] +name = "cranelift-entity" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c048097f9ae9b7c23db66e6f35882f6e1fbcd522f3db2a520d5c7aaa0079a67" +dependencies = [ + "cranelift-bitset", + "serde", + "serde_derive", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-frontend" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b45328ff7bac253860079032352989eae50341e155ddd4c6cfb8f5d40c490fa" +dependencies = [ + "cranelift-codegen", + "hashbrown 0.17.2", + "log", + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cranelift-isle" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff643d297ee16c7a8a6aba6bf526b610879635275ec14e7ee75b94f0b46e9514" + +[[package]] +name = "cranelift-native" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b186c9de1edc598d055ff3f13918fc8f49d3e23811b99ab45a3cbf52dc2a7b" +dependencies = [ + "cranelift-codegen", + "libc", + "mach2", + "target-lexicon", +] + +[[package]] +name = "cranelift-srcgen" +version = "0.137.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e30dff68753c0933cb30eb445d75d6b3cdcc0f7f0121b9c5aaabbe4a8315617d" + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gimli" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" +dependencies = [ + "fnv", + "hashbrown 0.16.1", + "indexmap", + "stable_deref_trait", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", + "serde", + "serde_core", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "mach2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memfd" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" +dependencies = [ + "rustix", +] + +[[package]] +name = "moon-plasma-host" +version = "0.1.0" +dependencies = [ + "libc", + "wasmtime", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "object" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" +dependencies = [ + "crc32fast", + "hashbrown 0.17.2", + "indexmap", + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "postcard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5431b3dcfdf6d1985c87d11f267a171c0dec0a8cd544c6727b747d36365f1fca" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "serde", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pulley-interpreter" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb7ed128aa5734a9bbad079eede1861ffd6362745cb595967f9fb78e2eba3de" +dependencies = [ + "cranelift-bitset", + "log", + "pulley-macros", + "wasmtime-internal-core", +] + +[[package]] +name = "pulley-macros" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f56330a5820c87d062fe79e3e2fa68dd96d4f6f11a3e299dcf16df35acc02b19" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regalloc2" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34f923657880712029496c2e68bb40bef163806b2011adde559b28bbcedc82ea" +dependencies = [ + "allocator-api2", + "bumpalo", + "hashbrown 0.17.2", + "log", + "rustc-hash", + "serde", + "smallvec", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +dependencies = [ + "serde", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "target-lexicon" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-encoder" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2608e8bb6d67fd68f5a8d0eb1363d6e7bcbc1f8ded5a0bd3a1e382462b876b22" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b88de21560ecd49deb8d8f1616b9b695f66fc312c5eca503f43accdc5795339e" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" +dependencies = [ + "bitflags", + "hashbrown 0.17.2", + "indexmap", + "semver", + "serde", +] + +[[package]] +name = "wasmprinter" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7" +dependencies = [ + "anyhow", + "termcolor", + "wasmparser", +] + +[[package]] +name = "wasmtime" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3231d67bedf0f4849558b01ee5accd0283469cff7ee6746ce6a9742ddc178312" +dependencies = [ + "addr2line", + "async-trait", + "bitflags", + "bumpalo", + "cc", + "encoding_rs", + "futures", + "libc", + "log", + "mach2", + "memfd", + "object", + "once_cell", + "postcard", + "pulley-interpreter", + "rustix", + "semver", + "serde", + "serde_derive", + "smallvec", + "target-lexicon", + "wasmparser", + "wasmtime-environ", + "wasmtime-internal-component-macro", + "wasmtime-internal-component-util", + "wasmtime-internal-core", + "wasmtime-internal-cranelift", + "wasmtime-internal-fiber", + "wasmtime-internal-jit-debug", + "wasmtime-internal-jit-icache-coherence", + "wasmtime-internal-unwinder", + "wasmtime-internal-versioned-export-macros", + "windows-sys", +] + +[[package]] +name = "wasmtime-environ" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a24cca20d8f3525071fcc71c0de558c754894934c43fb5550b4d23ada3523e92" +dependencies = [ + "anyhow", + "cpp_demangle", + "cranelift-bforest", + "cranelift-bitset", + "cranelift-entity", + "gimli", + "hashbrown 0.17.2", + "indexmap", + "log", + "object", + "postcard", + "rustc-demangle", + "semver", + "serde", + "serde_derive", + "smallvec", + "target-lexicon", + "wasm-encoder", + "wasmparser", + "wasmprinter", + "wasmtime-internal-component-util", + "wasmtime-internal-core", +] + +[[package]] +name = "wasmtime-internal-component-macro" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3e7b4191a7e411836b8d34cfcd20360dc134d897e9583a3686262b422643036" +dependencies = [ + "anyhow", + "proc-macro2", + "quote", + "syn", + "wasmtime-internal-component-util", + "wasmtime-internal-wit-bindgen", + "wit-parser", +] + +[[package]] +name = "wasmtime-internal-component-util" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d58085475f745779eb5c2d5cd3d60695d280d9c2cf261f7e96e9949b293f7a82" + +[[package]] +name = "wasmtime-internal-core" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4668db5cde6343ae9c7c188741689d30bcefa40c70647b87be2afb2c14511aa" +dependencies = [ + "hashbrown 0.17.2", + "libm", + "serde", +] + +[[package]] +name = "wasmtime-internal-cranelift" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c5744433223d6dca55e8933510f73cf7e2aa06ca53e3f039fd3c309e315546a" +dependencies = [ + "cranelift-codegen", + "cranelift-control", + "cranelift-entity", + "cranelift-frontend", + "cranelift-native", + "gimli", + "itertools", + "log", + "object", + "pulley-interpreter", + "smallvec", + "target-lexicon", + "thiserror", + "wasmparser", + "wasmtime-environ", + "wasmtime-internal-core", + "wasmtime-internal-unwinder", + "wasmtime-internal-versioned-export-macros", +] + +[[package]] +name = "wasmtime-internal-fiber" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ead05f9d1428e98562bef6d3c42c5c9911ac25373e9d5f6d81fa26a3efb74ae3" +dependencies = [ + "cc", + "libc", + "rustix", + "wasmtime-environ", + "wasmtime-internal-versioned-export-macros", + "windows-sys", +] + +[[package]] +name = "wasmtime-internal-jit-debug" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ea96d3eac206f9e088ebfc13a27f6353bdaa6a9e467e0ba9b05e00c79cee27" +dependencies = [ + "cc", + "wasmtime-internal-versioned-export-macros", +] + +[[package]] +name = "wasmtime-internal-jit-icache-coherence" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62a0d73e89a065e74332c8651d27bbc9fa1e4c7357ff219c3929aa9c02b6a31e" +dependencies = [ + "libc", + "wasmtime-internal-core", + "windows-sys", +] + +[[package]] +name = "wasmtime-internal-unwinder" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b413aca82d92129c193752d8109c1101d2b49090ea8e3028d7c7514dbb9750c2" +dependencies = [ + "cranelift-codegen", + "log", + "object", + "wasmtime-environ", +] + +[[package]] +name = "wasmtime-internal-versioned-export-macros" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e084771993bee8dd7dd0af42f10b56e1f665d67c8adbef340991e268b03289d1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "wasmtime-internal-wit-bindgen" +version = "50.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735a94d76f9b7f34b3fdb3181ac1f4234b5b0c9916b1b54a840c399e209cccda" +dependencies = [ + "anyhow", + "bitflags", + "heck", + "indexmap", + "wit-component", + "wit-parser", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-component" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2818766842bd2321074c348fb5c15d8fdb105a9eb78374e6d77c7d4127e1f2f9" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "962e43c4db2da607b50839a531e5b63473268b40efdf8028d5c54b572ca4f6f6" +dependencies = [ + "anyhow", + "hashbrown 0.17.2", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/host-wasm/Cargo.toml b/host-wasm/Cargo.toml new file mode 100644 index 0000000..d12550c --- /dev/null +++ b/host-wasm/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "moon-plasma-host" +version = "0.1.0" +edition = "2021" +description = "Runs the moon-plasma compositor wasm component (build/components/compositor.wasm) and gives it the OS surface it imports (wit/host/sys.wit)." + +[dependencies] +libc = "0.2" +wasmtime = { version = "50", default-features = false, features = ["component-model", "cranelift", "runtime", "std"] } + +[profile.release] +opt-level = 2 diff --git a/host-wasm/README.md b/host-wasm/README.md new file mode 100644 index 0000000..892d879 --- /dev/null +++ b/host-wasm/README.md @@ -0,0 +1,42 @@ +# moon-plasma-host + +Runs the compositor **as a WebAssembly component**. + +``` +just compositor-wasm # build/components/compositor.wasm (the compositor, a component) +just host-wasm # host-wasm/target/release/moon-plasma-host (this crate) +just run-wasm # both, then run in a window on your current Wayland session +``` + +The component (`components/compositor`, entry in `compositor/app`) imports exactly one interface, +`moonplasma:host/sys` ([`wit/host/sys.wit`](../wit/host/sys.wit)), and exports `run(args) -> s32`. +It is the same MoonBit code as the native compositor: the Wayland server, window manager, scene, +rasteriser and shell. Only `compositor/sys` differs per target (`sys_native.mbt` over a C shim, +`sys_wasm.mbt` over the WIT imports). The component holds integer handles and bytes only; every real +file descriptor lives in this host, which implements `sys` with libc (sockets and `SCM_RIGHTS`, +`memfd`, `poll`, spawn, files, clock). + +``` +moon-plasma-host build/components/compositor.wasm --socket PATH [--theme PATH] [--window] +moon-plasma-host build/components/compositor.wasm --socket PATH --gfx-out frame.png # one frame +moon-plasma-host build/components/compositor.wasm --socket PATH --gfx-out frame.png --serve # keep refreshing it +``` + +## Status + +Working: Wayland server (real clients such as `foot` run and draw), window management, decorations, +the desktop card, input routing, the nested window on the host session. + +Not yet in the component (the native compositor still has these): +- **Panel modules.** The panel is built from wasm modules, which the native build runs with wasmer. + A component can't embed another runtime, so this becomes a host import: the host instantiates the + modules with wasmtime and hands the compositor their draw ops (`compositor/wasm/wasm_unsupported.mbt` + is the placeholder; the panel is empty until then). +- **Real fonts.** `compositor/font` uses a C rasteriser; the component falls back to the bitmap font + until the host offers glyphs (`compositor/font/font_wasm.mbt`). +- **DRM/KMS and libinput** (`--drm`), the login-session backend. + +Regenerating the host bindings: `wit-bindgen moonbit wit/host --world compositor --out-dir . --gen-dir +components/compositor/gen --project-name moonplasma/desktop --ignore-module-file --ignore-stub`, then +`scripts/gen-native-stubs.py interface/moonplasma/host/sys` (the imports are wasm-only; this restores +the native stand-ins and the per-file targets). diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs new file mode 100644 index 0000000..d6ed2ff --- /dev/null +++ b/host-wasm/src/main.rs @@ -0,0 +1,430 @@ +//! Native host for the moon-plasma compositor component. +//! +//! The compositor is a wasm component (build/components/compositor.wasm) that imports exactly one +//! interface, `moonplasma:host/sys` (wit/host/sys.wit): sockets, memfd, poll, spawn, files, time. +//! This program is the other side of that interface. The component only ever holds integer +//! handles; every real file descriptor lives here. +//! +//! moon-plasma-host [--component PATH] [-- compositor args...] +//! moon-plasma-host build/components/compositor.wasm --socket /run/user/1000/wayland-moon-0 --window + +use std::ffi::CString; +use std::io::Read; +use std::os::unix::process::CommandExt; +use std::process::{Command, Stdio}; +use wasmtime::component::{Component, HasSelf, Linker}; +use wasmtime::{Config, Engine, Result, Store}; + +wasmtime::component::bindgen!({ + path: "../wit/host", + world: "compositor", +}); + +use moonplasma::host::sys::{Host, Received}; + +#[derive(Default)] +struct State { + /// Address of the private session bus launched apps use (started on first spawn). + private_bus: Option, + bus_tried: bool, + started: Option, +} + +fn sockaddr_un(path: &str) -> (libc::sockaddr_un, libc::socklen_t) { + let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() }; + addr.sun_family = libc::AF_UNIX as libc::sa_family_t; + let bytes = path.as_bytes(); + let n = bytes.len().min(addr.sun_path.len() - 1); + for (i, b) in bytes[..n].iter().enumerate() { + addr.sun_path[i] = *b as libc::c_char; + } + (addr, std::mem::size_of::() as libc::socklen_t) +} + +fn set_nonblock_cloexec(fd: i32) { + unsafe { + let fl = libc::fcntl(fd, libc::F_GETFL, 0); + if fl >= 0 { + libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); + } + let fdfl = libc::fcntl(fd, libc::F_GETFD, 0); + if fdfl >= 0 { + libc::fcntl(fd, libc::F_SETFD, fdfl | libc::FD_CLOEXEC); + } + } +} + +impl State { + /// A private session bus, so single-instance apps (Firefox, Kate, Dolphin...) don't forward + /// their launch to an instance on the host session. Dies with this process. + fn private_bus(&mut self) -> Option { + if self.bus_tried { + return self.private_bus.clone(); + } + self.bus_tried = true; + let mut cmd = Command::new("dbus-daemon"); + cmd.args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + unsafe { + cmd.pre_exec(|| { + libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM); + Ok(()) + }); + } + let mut child = cmd.spawn().ok()?; + let mut out = child.stdout.take()?; + let mut buf = [0u8; 256]; + let n = out.read(&mut buf).unwrap_or(0); + std::mem::forget(child); // keep it running; PDEATHSIG ends it with us + std::mem::forget(out); + if n > 0 { + let s = String::from_utf8_lossy(&buf[..n]); + self.private_bus = s.lines().next().map(|l| l.to_string()); + } + self.private_bus.clone() + } +} + +impl Host for State { + fn unix_listen(&mut self, path: String) -> i32 { + let _ = std::fs::remove_file(&path); + unsafe { + let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0); + if fd < 0 { + return -1; + } + set_nonblock_cloexec(fd); + let (addr, len) = sockaddr_un(&path); + if libc::bind(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 || libc::listen(fd, 16) < 0 { + libc::close(fd); + return -1; + } + fd + } + } + + fn unix_accept(&mut self, listen_fd: i32) -> i32 { + unsafe { + let fd = libc::accept(listen_fd, std::ptr::null_mut(), std::ptr::null_mut()); + if fd < 0 { + return -1; + } + set_nonblock_cloexec(fd); + fd + } + } + + fn unix_connect(&mut self, path: String) -> i32 { + unsafe { + let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0); + if fd < 0 { + return -1; + } + let (addr, len) = sockaddr_un(&path); + if libc::connect(fd, &addr as *const _ as *const libc::sockaddr, len) < 0 { + libc::close(fd); + return -1; + } + fd + } + } + + fn close_fd(&mut self, fd: i32) { + if fd >= 0 { + unsafe { libc::close(fd) }; + } + } + + fn unlink(&mut self, path: String) { + let _ = std::fs::remove_file(path); + } + + fn poll_read(&mut self, fd: i32, timeout_ms: i32) -> i32 { + let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; + let r = unsafe { libc::poll(&mut pfd, 1, timeout_ms) }; + if r < 0 { + -1 + } else if r == 0 { + 0 + } else if pfd.revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 { + 1 + } else { + 0 + } + } + + fn recvmsg(&mut self, fd: i32, max_len: u32) -> Received { + let mut data = vec![0u8; max_len as usize]; + if data.is_empty() { + return Received { count: 0, fd: -1, data }; + } + unsafe { + let mut iov = libc::iovec { iov_base: data.as_mut_ptr() as *mut _, iov_len: data.len() }; + let space = libc::CMSG_SPACE((std::mem::size_of::() * 4) as u32) as usize; + let mut cbuf = vec![0u8; space]; + let mut msg: libc::msghdr = std::mem::zeroed(); + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = cbuf.as_mut_ptr() as *mut _; + msg.msg_controllen = space as _; + let n = libc::recvmsg(fd, &mut msg, 0); + if n < 0 { + let e = *libc::__errno_location(); + let c = if e == libc::EAGAIN || e == libc::EWOULDBLOCK { -1 } else { -2 }; + return Received { count: c, fd: -1, data: Vec::new() }; + } + let mut got = -1; + let mut cm = libc::CMSG_FIRSTHDR(&msg); + while !cm.is_null() { + if (*cm).cmsg_level == libc::SOL_SOCKET && (*cm).cmsg_type == libc::SCM_RIGHTS { + let n_fds = ((*cm).cmsg_len as usize - libc::CMSG_LEN(0) as usize) / std::mem::size_of::(); + let fds = libc::CMSG_DATA(cm) as *const i32; + for i in 0..n_fds { + let f = *fds.add(i); + if i == 0 { + got = f; + } else { + libc::close(f); + } + } + } + cm = libc::CMSG_NXTHDR(&msg, cm); + } + data.truncate(n as usize); + Received { count: n as i32, fd: got, data } + } + } + + fn sendmsg(&mut self, fd: i32, data: Vec, send_fd: i32) -> i32 { + if data.is_empty() { + return 0; + } + unsafe { + let mut total = 0usize; + let mut with_fd = send_fd >= 0; + while total < data.len() { + let mut iov = libc::iovec { + iov_base: data.as_ptr().add(total) as *mut _, + iov_len: data.len() - total, + }; + let space = libc::CMSG_SPACE(std::mem::size_of::() as u32) as usize; + let mut cbuf = vec![0u8; space]; + let mut msg: libc::msghdr = std::mem::zeroed(); + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + if with_fd { + msg.msg_control = cbuf.as_mut_ptr() as *mut _; + msg.msg_controllen = space as _; + let cm = libc::CMSG_FIRSTHDR(&msg); + (*cm).cmsg_level = libc::SOL_SOCKET; + (*cm).cmsg_type = libc::SCM_RIGHTS; + (*cm).cmsg_len = libc::CMSG_LEN(std::mem::size_of::() as u32) as _; + std::ptr::copy_nonoverlapping(&send_fd as *const i32 as *const u8, libc::CMSG_DATA(cm), 4); + } + let sent = libc::sendmsg(fd, &msg, libc::MSG_NOSIGNAL); + if sent < 0 { + let e = *libc::__errno_location(); + if e == libc::EAGAIN || e == libc::EWOULDBLOCK { + let mut pfd = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 }; + libc::poll(&mut pfd, 1, 50); + continue; + } + return -1; + } + total += sent as usize; + with_fd = false; // ancillary data goes with the first chunk only + } + total as i32 + } + } + + fn memfd_create(&mut self, name: String, size: i32) -> i32 { + let Ok(cname) = CString::new(name) else { return -1 }; + unsafe { + let fd = libc::memfd_create(cname.as_ptr(), libc::MFD_CLOEXEC); + if fd < 0 { + return -1; + } + if size > 0 && libc::ftruncate(fd, size as libc::off_t) < 0 { + libc::close(fd); + return -1; + } + fd + } + } + + fn pwrite(&mut self, fd: i32, data: Vec, offset: i32) -> i32 { + let w = unsafe { libc::pwrite(fd, data.as_ptr() as *const _, data.len(), offset as libc::off_t) }; + if w < 0 { -1 } else { w as i32 } + } + + fn mmap_read(&mut self, fd: i32, size: i32) -> Vec { + if fd < 0 || size <= 0 { + return Vec::new(); + } + unsafe { + let mut st: libc::stat = std::mem::zeroed(); + if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < size as i64 { + return Vec::new(); + } + let p = libc::mmap(std::ptr::null_mut(), size as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0); + if p == libc::MAP_FAILED { + return Vec::new(); + } + let out = std::slice::from_raw_parts(p as *const u8, size as usize).to_vec(); + libc::munmap(p, size as usize); + out + } + } + + fn read_file(&mut self, path: String) -> Vec { + std::fs::read(path).unwrap_or_default() + } + + fn write_file(&mut self, path: String, data: Vec) -> i32 { + match std::fs::write(path, &data) { + Ok(()) => 0, + Err(_) => -1, + } + } + + fn read_proc(&mut self, path: String) -> Vec { + // /proc and /sys files report size 0: read to EOF, capped at 64 KiB. + let Ok(f) = std::fs::File::open(path) else { return Vec::new() }; + let mut out = Vec::new(); + let _ = f.take(65536).read_to_end(&mut out); + out + } + + fn mkdir_p(&mut self, path: String) -> bool { + std::fs::create_dir_all(path).is_ok() + } + + fn list_desktop_files(&mut self, dir: String) -> Vec { + let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; + rd.filter_map(|e| e.ok()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.ends_with(".desktop")) + .collect() + } + + fn sleep_ms(&mut self, ms: i32) { + if ms > 0 { + std::thread::sleep(std::time::Duration::from_millis(ms as u64)); + } + } + + fn monotonic_ms(&mut self) -> u64 { + self.started.get_or_insert_with(std::time::Instant::now).elapsed().as_millis() as u64 + } + + fn log(&mut self, message: String) { + eprintln!("{message}"); + } + + fn getpid(&mut self) -> i32 { + std::process::id() as i32 + } + + fn wall_time_field(&mut self, which: i32) -> i32 { + unsafe { + let t = libc::time(std::ptr::null_mut()); + let mut tm: libc::tm = std::mem::zeroed(); + libc::localtime_r(&t, &mut tm); + match which { + 0 => tm.tm_year + 1900, + 1 => tm.tm_mon + 1, + 2 => tm.tm_mday, + 3 => tm.tm_hour, + 4 => tm.tm_min, + 5 => tm.tm_sec, + 6 => tm.tm_wday, + _ => 0, + } + } + } + + fn getenv(&mut self, name: String) -> String { + std::env::var(name).unwrap_or_default() + } + + fn has_exe(&mut self, name: String) -> bool { + let ok = |p: &std::path::Path| { + CString::new(p.as_os_str().as_encoded_bytes()) + .map(|c| unsafe { libc::access(c.as_ptr(), libc::X_OK) == 0 }) + .unwrap_or(false) + }; + if name.contains('/') { + return ok(std::path::Path::new(&name)); + } + std::env::var_os("PATH") + .map(|p| std::env::split_paths(&p).any(|d| ok(&d.join(&name)))) + .unwrap_or(false) + } + + fn spawn(&mut self, cmd: String, display: String) -> bool { + let bus = self.private_bus(); + let mut c = Command::new("/bin/sh"); + c.arg("-c").arg(&cmd); + // Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak on + // the real session bus, so they keep it; everything else gets the private bus. + if let Some(b) = bus { + if !cmd.contains("flatpak run") { + c.env("DBUS_SESSION_BUS_ADDRESS", b); + } + } + c.env("WAYLAND_DISPLAY", display) + .env_remove("DISPLAY") + // Make toolkits pick our Wayland socket, not X11 or the host session. + .env("XDG_SESSION_TYPE", "wayland") + .env("QT_QPA_PLATFORM", "wayland") + .env("GDK_BACKEND", "wayland") + .env("SDL_VIDEODRIVER", "wayland") + .env("MOZ_ENABLE_WAYLAND", "1") + .env("ELECTRON_OZONE_PLATFORM_HINT", "wayland") + .env("CLUTTER_BACKEND", "wayland") + .stdin(Stdio::null()); + unsafe { + c.pre_exec(|| { + libc::setsid(); + libc::signal(libc::SIGCHLD, libc::SIG_DFL); + Ok(()) + }); + } + c.spawn().is_ok() + } +} + +fn main() -> Result<()> { + let mut args: Vec = std::env::args().skip(1).collect(); + // First argument may be the component path; otherwise use the default build location. + let component_path = if args.first().map(|a| a.ends_with(".wasm")).unwrap_or(false) { + args.remove(0) + } else { + "build/components/compositor.wasm".to_string() + }; + if args.first().map(|a| a == "--").unwrap_or(false) { + args.remove(0); + } + + // No zombies from launched apps. + unsafe { libc::signal(libc::SIGCHLD, libc::SIG_IGN) }; + + let mut config = Config::new(); + config.wasm_component_model(true); + let engine = Engine::new(&config)?; + let component = match Component::from_file(&engine, &component_path) { + Ok(c) => c, + Err(e) => { + eprintln!("error: cannot load {component_path}: {e}\n build it with `just compositor-wasm`"); + std::process::exit(1); + } + }; + let mut linker: Linker = Linker::new(&engine); + moonplasma::host::sys::add_to_linker::>(&mut linker, |s| s)?; + let mut store = Store::new(&engine, State::default()); + let compositor = Compositor::instantiate(&mut store, &component, &linker)?; + let code = compositor.call_run(&mut store, &args)?; + std::process::exit(code); +} diff --git a/interface/moonplasma/host/sys/README.md b/interface/moonplasma/host/sys/README.md new file mode 100644 index 0000000..108a4c0 --- /dev/null +++ b/interface/moonplasma/host/sys/README.md @@ -0,0 +1,3 @@ +The operating-system surface the compositor component needs, nothing more. The native host +implements it with real syscalls; the component holds only integer handles (fds) and bytes. +Mirrors compositor/sys. \ No newline at end of file diff --git a/interface/moonplasma/host/sys/ffi.mbt b/interface/moonplasma/host/sys/ffi.mbt new file mode 100644 index 0000000..642fa31 --- /dev/null +++ b/interface/moonplasma/host/sys/ffi.mbt @@ -0,0 +1,113 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +fn wasmImportUnixListen(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "unix-listen" + +///| +fn wasmImportUnixAccept(p0 : Int) -> Int = "moonplasma:host/sys@0.1.0" "unix-accept" + +///| +fn wasmImportUnixConnect(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "unix-connect" + +///| +fn wasmImportCloseFd(p0 : Int) = "moonplasma:host/sys@0.1.0" "close-fd" + +///| +fn wasmImportUnlink(p0 : Int, p1 : Int) = "moonplasma:host/sys@0.1.0" "unlink" + +///| +fn wasmImportPollRead(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "poll-read" + +///| +fn wasmImportRecvmsg(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "recvmsg" + +///| +fn wasmImportSendmsg(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "sendmsg" + +///| +fn wasmImportMemfdCreate(p0 : Int, p1 : Int, p2 : Int) -> Int = "moonplasma:host/sys@0.1.0" "memfd-create" + +///| +fn wasmImportPwrite(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "pwrite" + +///| +fn wasmImportMmapRead(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "mmap-read" + +///| +fn wasmImportReadFile(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "read-file" + +///| +fn wasmImportWriteFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "write-file" + +///| +fn wasmImportReadProc(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "read-proc" + +///| +fn wasmImportMkdirP(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "mkdir-p" + +///| +fn wasmImportListDesktopFiles(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "list-desktop-files" + +///| +fn wasmImportSleepMs(p0 : Int) = "moonplasma:host/sys@0.1.0" "sleep-ms" + +///| +fn wasmImportMonotonicMs() -> Int64 = "moonplasma:host/sys@0.1.0" "monotonic-ms" + +///| +fn wasmImportLog(p0 : Int, p1 : Int) = "moonplasma:host/sys@0.1.0" "log" + +///| +fn wasmImportGetpid() -> Int = "moonplasma:host/sys@0.1.0" "getpid" + +///| +fn wasmImportWallTimeField(p0 : Int) -> Int = "moonplasma:host/sys@0.1.0" "wall-time-field" + +///| +fn wasmImportGetenv(p0 : Int, p1 : Int, p2 : Int) = "moonplasma:host/sys@0.1.0" "getenv" + +///| +fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "has-exe" + +///| +fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "moonplasma:host/sys@0.1.0" "spawn" + +///| +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) + +///| +extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array8 +#| local.get 0) + +///| +extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + +///| +#owned(bytes) +extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = +#|(func (param i32) (result i32) local.get 0) + diff --git a/interface/moonplasma/host/sys/moon.pkg b/interface/moonplasma/host/sys/moon.pkg new file mode 100644 index 0000000..615617d --- /dev/null +++ b/interface/moonplasma/host/sys/moon.pkg @@ -0,0 +1,9 @@ +warnings = "-44" + +// ffi.mbt is generated and wasm-only; native builds use native_stub.mbt (scripts/gen-native-stubs.py). +options( + targets: { + "ffi.mbt": ["wasm", "wasm-gc"], + "native_stub.mbt": ["native"], + }, +) diff --git a/interface/moonplasma/host/sys/native_stub.mbt b/interface/moonplasma/host/sys/native_stub.mbt new file mode 100644 index 0000000..69948c1 --- /dev/null +++ b/interface/moonplasma/host/sys/native_stub.mbt @@ -0,0 +1,156 @@ +// Generated by scripts/gen-native-stubs.py. Native stand-ins for the wasm-only ffi.mbt. + +///| +fn wasmImportUnixListen(p0 : Int, p1 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportUnixAccept(p0 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportUnixConnect(p0 : Int, p1 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportCloseFd(p0 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportUnlink(p0 : Int, p1 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportPollRead(p0 : Int, p1 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportRecvmsg(p0 : Int, p1 : Int, p2 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportSendmsg(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportMemfdCreate(p0 : Int, p1 : Int, p2 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportPwrite(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportMmapRead(p0 : Int, p1 : Int, p2 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportReadFile(p0 : Int, p1 : Int, p2 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportWriteFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportReadProc(p0 : Int, p1 : Int, p2 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportMkdirP(p0 : Int, p1 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportListDesktopFiles(p0 : Int, p1 : Int, p2 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportSleepMs(p0 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportMonotonicMs() -> Int64 { + abort("wasm-only host import") +} + +///| +fn wasmImportLog(p0 : Int, p1 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportGetpid() -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportWallTimeField(p0 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportGetenv(p0 : Int, p1 : Int, p2 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn mbt_ffi_str2ptr(str : String) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_load32(offset : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_free(position : Int) -> Unit { + abort("wasm-only") +} + +///| +fn mbt_ffi_malloc(size : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { + abort("wasm-only") +} + +///| +fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { + abort("wasm-only") +} + +///| +fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { + abort("wasm-only") +} diff --git a/interface/moonplasma/host/sys/pkg.generated.mbti b/interface/moonplasma/host/sys/pkg.generated.mbti new file mode 100644 index 0000000..c2dcebc --- /dev/null +++ b/interface/moonplasma/host/sys/pkg.generated.mbti @@ -0,0 +1,60 @@ +// Generated using `moon info`, DON'T EDIT IT +package "moonplasma/desktop/interface/moonplasma/host/sys" + +// Values +pub fn close_fd(Int32) -> Unit + +pub fn getenv(String) -> String + +pub fn getpid() -> Int32 + +pub fn has_exe(String) -> Bool + +pub fn list_desktop_files(String) -> Array[String] + +pub fn memfd_create(String, Int32) -> Int32 + +pub fn mkdir_p(String) -> Bool + +pub fn mmap_read(Int32, Int32) -> FixedArray[Byte] + +pub fn poll_read(Int32, Int32) -> Int32 + +pub fn pwrite(Int32, FixedArray[Byte], Int32) -> Int32 + +pub fn read_file(String) -> FixedArray[Byte] + +pub fn read_proc(String) -> FixedArray[Byte] + +pub fn recvmsg(Int32, UInt32) -> Received + +pub fn sendmsg(Int32, FixedArray[Byte], Int32) -> Int32 + +pub fn sleep_ms(Int32) -> Unit + +pub fn spawn(String, String) -> Bool + +pub fn unix_accept(Int32) -> Int32 + +pub fn unix_connect(String) -> Int32 + +pub fn unix_listen(String) -> Int32 + +pub fn unlink(String) -> Unit + +pub fn wall_time_field(Int32) -> Int32 + +pub fn write_file(String, FixedArray[Byte]) -> Int32 + +// Errors + +// Types and methods +pub(all) struct Received { + count : Int32 + fd : Int32 + data : FixedArray[Byte] +} + +// Type aliases + +// Traits diff --git a/interface/moonplasma/host/sys/top.mbt b/interface/moonplasma/host/sys/top.mbt new file mode 100644 index 0000000..98cdc69 --- /dev/null +++ b/interface/moonplasma/host/sys/top.mbt @@ -0,0 +1,274 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +/// Result of `recvmsg`: byte count (-1 would-block, -2 error, 0 EOF), an fd received over +/// SCM_RIGHTS (-1 when none), and the bytes read. +pub(all) struct Received { + count : Int; fd : Int; data : FixedArray[Byte] +} +///| +/// Listen on a unix socket at `path`; -1 on failure. +pub fn unix_listen(path : String) -> Int { + + let ptr = mbt_ffi_str2ptr(path) + let result : Int = wasmImportUnixListen(ptr, path.length()); + let ret = result + mbt_ffi_free(ptr) + return ret + +} +///| +/// Accept a pending client (non-blocking); -1 when none. +pub fn unix_accept(listen_fd : Int) -> Int { + + let result : Int = wasmImportUnixAccept(listen_fd); + let ret = result + return ret + +} +///| +pub fn unix_connect(path : String) -> Int { + + let ptr = mbt_ffi_str2ptr(path) + let result : Int = wasmImportUnixConnect(ptr, path.length()); + let ret = result + mbt_ffi_free(ptr) + return ret + +} +///| +pub fn close_fd(fd : Int) -> Unit { + + wasmImportCloseFd(fd); + +} +///| +pub fn unlink(path : String) -> Unit { + + let ptr = mbt_ffi_str2ptr(path) + wasmImportUnlink(ptr, path.length()); + mbt_ffi_free(ptr) + +} +///| +/// 1 when `fd` is readable within `timeout-ms`, 0 on timeout, <0 on error. +pub fn poll_read(fd : Int, timeout_ms : Int) -> Int { + + let result : Int = wasmImportPollRead(fd, timeout_ms); + let ret = result + return ret + +} +///| +pub fn recvmsg(fd : Int, max_len : UInt) -> Received { + + let return_area = mbt_ffi_malloc(16) + wasmImportRecvmsg(fd, (max_len).reinterpret_as_int(), return_area); + + let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12)) + let ret = Received::{count : mbt_ffi_load32((return_area) + 0), fd : mbt_ffi_load32((return_area) + 4), data : result} + mbt_ffi_free(return_area) + return ret + +} +///| +/// Send `data`, with `send-fd` (or -1) as SCM_RIGHTS; bytes sent or <0. +pub fn sendmsg(fd : Int, data : FixedArray[Byte], send_fd : Int) -> Int { + + let ptr = mbt_ffi_bytes2ptr(data) + + let result : Int = wasmImportSendmsg(fd, ptr, data.length(), send_fd); + let ret = result + mbt_ffi_free(ptr) + return ret + +} +///| +pub fn memfd_create(name : String, size : Int) -> Int { + + let ptr = mbt_ffi_str2ptr(name) + let result : Int = wasmImportMemfdCreate(ptr, name.length(), size); + let ret = result + mbt_ffi_free(ptr) + return ret + +} +///| +pub fn pwrite(fd : Int, data : FixedArray[Byte], offset : Int) -> Int { + + let ptr = mbt_ffi_bytes2ptr(data) + + let result : Int = wasmImportPwrite(fd, ptr, data.length(), offset); + let ret = result + mbt_ffi_free(ptr) + return ret + +} +///| +/// Copy `size` bytes of the file behind `fd` (mapped read-only by the host). +pub fn mmap_read(fd : Int, size : Int) -> FixedArray[Byte] { + + let return_area = mbt_ffi_malloc(8) + wasmImportMmapRead(fd, size, return_area); + + let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4)) + let ret = result + mbt_ffi_free(return_area) + return ret + +} +///| +pub fn read_file(path : String) -> FixedArray[Byte] { + + let ptr = mbt_ffi_str2ptr(path) + let return_area = mbt_ffi_malloc(8) + wasmImportReadFile(ptr, path.length(), return_area); + + let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4)) + let ret = result + mbt_ffi_free(ptr) + mbt_ffi_free(return_area) + return ret + +} +///| +pub fn write_file(path : String, data : FixedArray[Byte]) -> Int { + + let ptr = mbt_ffi_str2ptr(path) + + let ptr0 = mbt_ffi_bytes2ptr(data) + + let result : Int = wasmImportWriteFile(ptr, path.length(), ptr0, data.length()); + let ret = result + mbt_ffi_free(ptr) + mbt_ffi_free(ptr0) + return ret + +} +///| +/// Contents of a small /proc or /sys file ("" when unreadable). +pub fn read_proc(path : String) -> FixedArray[Byte] { + + let ptr = mbt_ffi_str2ptr(path) + let return_area = mbt_ffi_malloc(8) + wasmImportReadProc(ptr, path.length(), return_area); + + let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4)) + let ret = result + mbt_ffi_free(ptr) + mbt_ffi_free(return_area) + return ret + +} +///| +pub fn mkdir_p(path : String) -> Bool { + + let ptr = mbt_ffi_str2ptr(path) + let result : Int = wasmImportMkdirP(ptr, path.length()); + let ret = (result != 0) + mbt_ffi_free(ptr) + return ret + +} +///| +/// Names of the *.desktop files directly in `dir`. +pub fn list_desktop_files(dir : String) -> Array[String] { + + let ptr = mbt_ffi_str2ptr(dir) + let return_area = mbt_ffi_malloc(8) + wasmImportListDesktopFiles(ptr, dir.length(), return_area); + + let array : Array[String] = []; + for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 { + let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 8) + + let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4)) + + array.push(result) + } + mbt_ffi_free(mbt_ffi_load32((return_area) + 0)) + let ret = array + mbt_ffi_free(ptr) + mbt_ffi_free(return_area) + return ret + +} +///| +pub fn sleep_ms(ms : Int) -> Unit { + + wasmImportSleepMs(ms); + +} +///| +/// Milliseconds on a monotonic clock (event timestamps). +pub fn monotonic_ms() -> UInt64 { + + let result : Int64 = wasmImportMonotonicMs(); + let ret = (result).reinterpret_as_uint64() + return ret + +} +///| +/// Print a line to the host's stderr. +pub fn log(message : String) -> Unit { + + let ptr = mbt_ffi_str2ptr(message) + wasmImportLog(ptr, message.length()); + mbt_ffi_free(ptr) + +} +///| +pub fn getpid() -> Int { + + let result : Int = wasmImportGetpid(); + let ret = result + return ret + +} +///| +/// 0 year, 1 month (1-12), 2 day, 3 hour, 4 minute, 5 second, 6 weekday (0 = Sunday). +pub fn wall_time_field(which : Int) -> Int { + + let result : Int = wasmImportWallTimeField(which); + let ret = result + return ret + +} +///| +pub fn getenv(name : String) -> String { + + let ptr = mbt_ffi_str2ptr(name) + let return_area = mbt_ffi_malloc(8) + wasmImportGetenv(ptr, name.length(), return_area); + + let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4)) + let ret = result + mbt_ffi_free(ptr) + mbt_ffi_free(return_area) + return ret + +} +///| +pub fn has_exe(name : String) -> Bool { + + let ptr = mbt_ffi_str2ptr(name) + let result : Int = wasmImportHasExe(ptr, name.length()); + let ret = (result != 0) + mbt_ffi_free(ptr) + return ret + +} +///| +/// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`. +pub fn spawn(cmd : String, display : String) -> Bool { + + let ptr = mbt_ffi_str2ptr(cmd) + + let ptr0 = mbt_ffi_str2ptr(display) + let result : Int = wasmImportSpawn(ptr, cmd.length(), ptr0, display.length()); + let ret = (result != 0) + mbt_ffi_free(ptr) + mbt_ffi_free(ptr0) + return ret + +} + diff --git a/justfile b/justfile index 7426054..bf32e0f 100644 --- a/justfile +++ b/justfile @@ -117,3 +117,16 @@ clean: clean-all: rm -rf _build build +# Build the compositor as a wasm component (build/components/compositor.wasm): imports only moonplasma:host/sys. +compositor-wasm: + scripts/build-compositor-wasm.sh + +# Build the native host that runs the compositor component (wasmtime; implements the sys imports). +host-wasm: + cd host-wasm && cargo build --release + +# Run the wasm compositor in a window on your current Wayland session. Connect clients via `just client`. +run-wasm: compositor-wasm host-wasm + rm -f {{socket}} + host-wasm/target/release/moon-plasma-host build/components/compositor.wasm --socket {{socket}} --theme {{theme}} --window + diff --git a/scripts/build-compositor-wasm.sh b/scripts/build-compositor-wasm.sh new file mode 100755 index 0000000..1fe4ee6 --- /dev/null +++ b/scripts/build-compositor-wasm.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Build the compositor itself as a wasm component: build/components/compositor.wasm. +# It imports only moonplasma:host/sys (wit/host/sys.wit) and exports `run`; the native host in +# host-wasm/ provides the imports. Needs moon and wasm-tools. +# scripts/build-compositor-wasm.sh +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT" +export PATH="$ROOT/.tools/bin:$HOME/.moon/bin:$PATH" +for t in moon wasm-tools; do + command -v "$t" >/dev/null || { echo "error: $t not found" >&2; exit 1; } +done +moon build --target wasm --release components/compositor/gen 2>&1 | grep -E '^Error' -A8 || true +[ "${PIPESTATUS[0]}" -eq 0 ] || { echo "error: moon build failed" >&2; exit 1; } +core="_build/wasm/release/build/components/compositor/gen/gen.wasm" +[ -f "$core" ] || { echo "error: $core missing" >&2; exit 1; } +mkdir -p build/components +wasm-tools component embed wit/host "$core" --world compositor --encoding utf16 -o build/components/compositor.embed.wasm +wasm-tools component new build/components/compositor.embed.wasm -o build/components/compositor.wasm +rm -f build/components/compositor.embed.wasm +wasm-tools validate --features component-model build/components/compositor.wasm +printf 'compositor.wasm %s bytes imports=[%s]\n' "$(stat -c %s build/components/compositor.wasm)" \ + "$(wasm-tools component wit build/components/compositor.wasm | sed -n 's/^ import \(.*\);/\1/p' | paste -sd, -)" diff --git a/scripts/gen-native-stubs.py b/scripts/gen-native-stubs.py new file mode 100755 index 0000000..80e957f --- /dev/null +++ b/scripts/gen-native-stubs.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Write native_stub.mbt next to a wit-bindgen generated ffi.mbt. + +The generated imports are wasm-only (`extern "wasm"` / wasm import functions), so a package that +imports them can't build for the native target. This emits abort() bodies with the same +signatures, and rewrites moon.pkg to map ffi.mbt to wasm and native_stub.mbt to native. + scripts/gen-native-stubs.py interface/moonplasma/host/sys +""" +import re, sys, pathlib + +d = pathlib.Path(sys.argv[1]) +src = (d / "ffi.mbt").read_text() +out = ["// Generated by scripts/gen-native-stubs.py. Native stand-ins for the wasm-only ffi.mbt.", ""] +# import functions: fn wasmImportX(p0 : Int, ...) -> Int = "mod" "name" +for m in re.finditer(r'^fn (\w+)\(([^)]*)\)\s*(->\s*[\w\[\]]+)?\s*=\s*"[^"]*"\s*"[^"]*"\s*$', src, re.M): + name, params, ret = m.group(1), m.group(2), (m.group(3) or "-> Unit").strip() + out += ["///|", f"fn {name}({params}) {ret} {{", ' abort("wasm-only host import")', "}", ""] +# inline-wasm helpers: extern "wasm" fn mbt_ffi_x(params) -> T = +for m in re.finditer(r'^extern "wasm" fn (\w+)\(([^)]*)\)\s*(->\s*[^=\n]+?)?\s*=\s*$', src, re.M): + name, params, ret = m.group(1), m.group(2), (m.group(3) or "-> Unit").strip() + out += ["///|", f"fn {name}({params}) {ret} {{", ' abort("wasm-only")', "}", ""] +(d / "native_stub.mbt").write_text("\n".join(out)) +# wit-bindgen rewrites moon.pkg on every run, so restore the per-file targets here. +(d / "moon.pkg").write_text("""warnings = "-44" + +// ffi.mbt is generated and wasm-only; native builds use native_stub.mbt (scripts/gen-native-stubs.py). +options( + targets: { + "ffi.mbt": ["wasm", "wasm-gc"], + "native_stub.mbt": ["native"], + }, +) +""") +print("wrote", d / "native_stub.mbt", "(%d stubs)" % sum(1 for l in out if l.startswith("fn "))) diff --git a/wit/host/sys.wit b/wit/host/sys.wit new file mode 100644 index 0000000..0d1eea0 --- /dev/null +++ b/wit/host/sys.wit @@ -0,0 +1,60 @@ +package moonplasma:host@0.1.0; + +/// The operating-system surface the compositor component needs, nothing more. The native host +/// implements it with real syscalls; the component holds only integer handles (fds) and bytes. +/// Mirrors compositor/sys. +interface sys { + /// Listen on a unix socket at `path`; -1 on failure. + unix-listen: func(path: string) -> s32; + /// Accept a pending client (non-blocking); -1 when none. + unix-accept: func(listen-fd: s32) -> s32; + unix-connect: func(path: string) -> s32; + close-fd: func(fd: s32); + unlink: func(path: string); + /// 1 when `fd` is readable within `timeout-ms`, 0 on timeout, <0 on error. + poll-read: func(fd: s32, timeout-ms: s32) -> s32; + + /// Result of `recvmsg`: byte count (-1 would-block, -2 error, 0 EOF), an fd received over + /// SCM_RIGHTS (-1 when none), and the bytes read. + record received { + count: s32, + fd: s32, + data: list, + } + recvmsg: func(fd: s32, max-len: u32) -> received; + /// Send `data`, with `send-fd` (or -1) as SCM_RIGHTS; bytes sent or <0. + sendmsg: func(fd: s32, data: list, send-fd: s32) -> s32; + + memfd-create: func(name: string, size: s32) -> s32; + pwrite: func(fd: s32, data: list, offset: s32) -> s32; + /// Copy `size` bytes of the file behind `fd` (mapped read-only by the host). + mmap-read: func(fd: s32, size: s32) -> list; + + read-file: func(path: string) -> list; + write-file: func(path: string, data: list) -> s32; + /// Contents of a small /proc or /sys file ("" when unreadable). + read-proc: func(path: string) -> list; + mkdir-p: func(path: string) -> bool; + /// Names of the *.desktop files directly in `dir`. + list-desktop-files: func(dir: string) -> list; + + sleep-ms: func(ms: s32); + /// Milliseconds on a monotonic clock (event timestamps). + monotonic-ms: func() -> u64; + /// Print a line to the host's stderr. + log: func(message: string); + getpid: func() -> s32; + /// 0 year, 1 month (1-12), 2 day, 3 hour, 4 minute, 5 second, 6 weekday (0 = Sunday). + wall-time-field: func(which: s32) -> s32; + getenv: func(name: string) -> string; + has-exe: func(name: string) -> bool; + /// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`. + spawn: func(cmd: string, display: string) -> bool; +} + +/// The compositor as one component: it imports the OS surface and exports its entry point. +world compositor { + import sys; + /// Run the compositor until it exits. `args` are the command-line arguments (without argv[0]). + export run: func(args: list) -> s32; +} diff --git a/world/compositor/README.md b/world/compositor/README.md new file mode 100644 index 0000000..c40a31f --- /dev/null +++ b/world/compositor/README.md @@ -0,0 +1 @@ +The compositor as one component: it imports the OS surface and exports its entry point. \ No newline at end of file diff --git a/world/compositor/ffi_import.mbt b/world/compositor/ffi_import.mbt new file mode 100644 index 0000000..cdedbce --- /dev/null +++ b/world/compositor/ffi_import.mbt @@ -0,0 +1,2 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + diff --git a/world/compositor/import.mbt b/world/compositor/import.mbt new file mode 100644 index 0000000..cdedbce --- /dev/null +++ b/world/compositor/import.mbt @@ -0,0 +1,2 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + diff --git a/world/compositor/moon.pkg b/world/compositor/moon.pkg new file mode 100644 index 0000000..e2a6033 --- /dev/null +++ b/world/compositor/moon.pkg @@ -0,0 +1 @@ +warnings = "-44"