From c6e31b4a8fb458a4fc805ac218351e5737e9bd9a Mon Sep 17 00:00:00 2001 From: nandithebull Date: Wed, 25 Nov 2026 04:39:40 -0800 Subject: [PATCH] Draw in the host: the wasm compositor sends draw ops, the host rasterises natively The wasm software renderer cost ~10-20 ns/pixel, so any changed frame took ~100+ ms at 1080p and the desktop swung between idle and very slow. The compositor still builds the scene (windows, decorations, panel, wallpaper) but a new moonplasma:host/raster interface turns it into pixels in the host: - host-wasm/src/raster.rs: a port of compositor/renderer (same blend arithmetic: fills, strokes, lines, circles, text, clips, shadows, surface blits), a wallpaper+desktop-card cache, and captured client surfaces (copied out of the shared memory once at commit, converted to RGBA, solid ones blit as row copies). 9 unit tests; a full frame matches the native software renderer except for text antialiasing (0.3% of pixels). - compositor/raster sends a SceneGraph as ops; compositor.compose_scene() returns it only when something changed. The login session shows the host framebuffer directly (display.present-frame), the nested window gets it as a memfd (raster.export-memfd), --gfx-out reads it (read-frame). - Client buffers never enter wasm: snapshot_shm_buffer captures in the host and keeps an id. - Loop pacing sleeps the rest of the frame budget instead of a fixed 16/8 ms. Full-screen terminal flooding output at 1080p: ~2 fps / 94% CPU -> ~57 fps; idle ~9%. The native build keeps the software renderer. Co-Authored-By: Claude Sonnet 5.5 --- .../compositor/gen/world/compositor/ffi.mbt | 8 +- compositor/app/app.mbt | 60 +- compositor/app/moon.pkg | 1 + compositor/host/compositor.mbt | 70 +- compositor/host/input_test.mbt | 32 + compositor/kms/kms_native.mbt | 6 + compositor/kms/kms_wasm.mbt | 6 + compositor/nested/nested.mbt | 24 +- compositor/raster/moon.pkg | 17 + compositor/raster/raster_native.mbt | 12 + compositor/raster/raster_wasm.mbt | 97 +++ compositor/renderer/fill_wbtest.mbt | 2 +- compositor/renderer/renderer_test.mbt | 1 + compositor/scene/scene.mbt | 3 + compositor/sys/moon.pkg | 1 + compositor/sys/sys_native.mbt | 21 + compositor/sys/sys_wasm.mbt | 22 + compositor/wayland/server.mbt | 19 +- host-wasm/README.md | 23 + host-wasm/src/main.rs | 113 ++- host-wasm/src/plasmoid.rs | 1 + host-wasm/src/raster.rs | 778 ++++++++++++++++++ interface/moonplasma/host/display/ffi.mbt | 37 +- .../moonplasma/host/display/native_stub.mbt | 29 +- interface/moonplasma/host/display/top.mbt | 7 + interface/moonplasma/host/font/ffi.mbt | 14 +- .../moonplasma/host/font/native_stub.mbt | 12 +- interface/moonplasma/host/plasmoids/ffi.mbt | 50 +- .../moonplasma/host/plasmoids/native_stub.mbt | 72 +- interface/moonplasma/host/raster/ffi.mbt | 52 ++ interface/moonplasma/host/raster/moon.pkg | 9 + .../moonplasma/host/raster/native_stub.mbt | 61 ++ interface/moonplasma/host/raster/top.mbt | 550 +++++++++++++ interface/moonplasma/host/sys/ffi.mbt | 46 +- interface/moonplasma/host/sys/native_stub.mbt | 40 +- wit/host/display.wit | 2 + wit/host/raster.wit | 62 ++ wit/host/sys.wit | 1 + 38 files changed, 2141 insertions(+), 220 deletions(-) create mode 100644 compositor/raster/moon.pkg create mode 100644 compositor/raster/raster_native.mbt create mode 100644 compositor/raster/raster_wasm.mbt create mode 100644 host-wasm/src/raster.rs create mode 100644 interface/moonplasma/host/raster/ffi.mbt create mode 100644 interface/moonplasma/host/raster/moon.pkg create mode 100644 interface/moonplasma/host/raster/native_stub.mbt create mode 100644 interface/moonplasma/host/raster/top.mbt create mode 100644 wit/host/raster.wit diff --git a/components/compositor/gen/world/compositor/ffi.mbt b/components/compositor/gen/world/compositor/ffi.mbt index e862d50..2d166db 100644 --- a/components/compositor/gen/world/compositor/ffi.mbt +++ b/components/compositor/gen/world/compositor/ffi.mbt @@ -20,10 +20,6 @@ pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int { } -///| -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) @@ -35,3 +31,7 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = 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) + diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index 0f777c1..fbbfc8c 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -122,7 +122,6 @@ pub fn run(args : Array[String]) -> Int { } 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 => { @@ -138,8 +137,11 @@ pub fn run(args : Array[String]) -> Int { comp.restore_state() // and the layout mode and recent apps from the last session 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))) + match comp.compose_scene() { + Some(sg) => @raster.submit(sg) + None => () + } + ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(@raster.read_frame(width, height)))) comp.close() @sys.log("frame written to " + gfx_out) return 0 @@ -192,10 +194,19 @@ pub fn run(args : Array[String]) -> Int { comp.step() let f1 = @sys.monotonic_ms() k.set_cursor_shape(comp.desired_cursor()) - let px = comp.compose_frame() - need_present = need_present || comp.frame_changed + // The host draws; only a changed desktop is sent, and the frame is shown by the host + // straight from its framebuffer. + match comp.compose_scene() { + Some(sg) => { + let r0 = @sys.monotonic_ms() + @raster.submit(sg) + comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0) + need_present = true + } + None => () + } if need_present && k.frame_ready() { - k.present(px) + k.present_frame() need_present = false } if profile { @@ -213,7 +224,9 @@ pub fn run(args : Array[String]) -> Int { comp.prof_raster_ms = 0UL } } - @sys.sleep_ms(8) + // Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work. + let spent = (@sys.monotonic_ms() - f0).to_int() + @sys.sleep_ms(if spent >= 8 { 1 } else { 8 - spent }) continue } None => () @@ -236,18 +249,35 @@ pub fn run(args : Array[String]) -> Int { comp.handle_input(ev, now_ms) } n.set_cursor_shape(comp.desired_cursor()) - let px = comp.compose_frame() - need_present = need_present || comp.frame_changed + match comp.compose_scene() { + Some(sg) => { + let r0 = @sys.monotonic_ms() + @raster.submit(sg) + comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0) + need_present = true + } + None => () + } if need_present && n.frame_ready() { - n.present(px) + n.present_frame(width, height) need_present = false } } 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))) + match comp.compose_scene() { + Some(sg) => { + let r0 = @sys.monotonic_ms() + @raster.submit(sg) + comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0) + need_present = true + } + None => () + } + // No display: --serve keeps a PNG of the latest frame for looking at a live compositor. + if serve && gfx_out.length() > 0 && frames % 30 == 0 && need_present { + ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(@raster.read_frame(width, height)))) + need_present = false } } } @@ -266,7 +296,9 @@ pub fn run(args : Array[String]) -> Int { comp.prof_raster_ms = 0UL } } - @sys.sleep_ms(16) + // About 60 frames a second: sleep what is left of 16 ms after the work. + let spent = (@sys.monotonic_ms() - f0).to_int() + @sys.sleep_ms(if spent >= 16 { 1 } else { 16 - spent }) } match kms { Some(k) => k.close() diff --git a/compositor/app/moon.pkg b/compositor/app/moon.pkg index 488579d..46c9881 100644 --- a/compositor/app/moon.pkg +++ b/compositor/app/moon.pkg @@ -7,6 +7,7 @@ import { "moonplasma/desktop/compositor/host" @host, "moonplasma/desktop/compositor/nested" @nested, "moonplasma/desktop/compositor/kms" @kms, + "moonplasma/desktop/compositor/raster" @raster, } supported_targets = "+native+wasm" diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index e7a2445..0303b27 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -129,10 +129,21 @@ pub fn MoonPlasmaCompositor::new( ///| pub fn MoonPlasmaCompositor::close(self : MoonPlasmaCompositor) -> Unit { + for _, win in self.windows { + release_snapshot(win.surface) + } self.shell.shutdown() self.server.close() } +///| Let the host forget a client surface it captured (a no-op without the host rasteriser). +fn release_snapshot(s : @scene.ShmBufferSnapshot?) -> Unit { + match s { + Some(snap) => if snap.host_id != 0U { @sys.surface_release(snap.host_id) } + None => () + } +} + ///| What a frame was drawn from, compared with the next frame's to see whether it changed. #derive(Eq) pub(all) struct FrameSig { @@ -284,6 +295,7 @@ pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit { Some(win) => { match snap { Some(s) => { + release_snapshot(win.surface) win.surface = Some(s) self.damage.mark_rect(win.geometry) } @@ -300,7 +312,10 @@ pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit { for p in self.popups { if p.id == wid { match snap { - Some(_) => p.surface = snap + Some(_) => { + release_snapshot(p.surface) + p.surface = snap + } None => () } self.damage.mark_full() @@ -309,6 +324,10 @@ pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit { @wayland.CompositorEvent::PopupClosed(wid) => self.close_popup(wid) @wayland.CompositorEvent::ToplevelClosed(wid) => { self.close_popup(wid) + match self.windows.get(wid) { + Some(win) => release_snapshot(win.surface) + None => () + } ignore(self.windows.remove(wid)) if self.ptr_win == Some(wid) { self.ptr_win = None @@ -379,9 +398,9 @@ pub fn MoonPlasmaCompositor::restore_state(self : MoonPlasmaCompositor) -> Unit } ///| -pub fn MoonPlasmaCompositor::compose_frame( +fn MoonPlasmaCompositor::build_scene( self : MoonPlasmaCompositor, -) -> @renderer.Pixmap { +) -> (@scene.SceneGraph, Bool) { self.flush_configures() let scene = @scene.SceneGraph::new(self.output_w, self.output_h) let order = self.wm.stacking_order() @@ -482,22 +501,46 @@ pub fn MoonPlasmaCompositor::compose_frame( wins: scene.windows.map(w => (w.id, w.geometry, w.focused, w.fullscreen, w.deco_ops)), popups: scene.popups.map(p => p.0), } - // Nothing changed since the last frame (no client commit, same shell and decoration ops): - // hand back the previous pixels instead of rasterising 2 million pixels again. - match (self.last_frame, self.last_sig) { - (Some(prev), Some(ps)) => - if !damaged && ps == sig { + // Unchanged since the last scene (no client commit, same shell and decoration ops)? + let unchanged = match self.last_sig { + Some(ps) => !damaged && ps == sig + None => false + } + if !unchanged { + self.last_sig = Some(sig) + } + self.prof_shell_ms = self.prof_shell_ms + (@sys.monotonic_ms() - t0) + (scene, !unchanged) +} + +///| Compose the desktop for the host rasteriser (the wasm compositor): the scene to draw, or None +/// when nothing changed since the last one, so an idle desktop costs nothing to draw or present. +pub fn MoonPlasmaCompositor::compose_scene( + self : MoonPlasmaCompositor, +) -> @scene.SceneGraph? { + let (scene, changed) = self.build_scene() + self.frame_changed = changed + if changed { Some(scene) } else { None } +} + +///| Compose the desktop and draw it with the software renderer (the native build and the tests). +/// An unchanged desktop hands back the previous pixels instead of rasterising them again. +pub fn MoonPlasmaCompositor::compose_frame( + self : MoonPlasmaCompositor, +) -> @renderer.Pixmap { + let (scene, changed) = self.build_scene() + match self.last_frame { + Some(prev) => + if !changed { self.frame_changed = false return prev } - _ => () + None => () } self.frame_changed = true - self.last_sig = Some(sig) let t1 = @sys.monotonic_ms() let px = @renderer.render_scene(scene) self.last_frame = Some(px) - self.prof_shell_ms = self.prof_shell_ms + (t1 - t0) self.prof_raster_ms = self.prof_raster_ms + (@sys.monotonic_ms() - t1) px } @@ -638,6 +681,11 @@ fn MoonPlasmaCompositor::close_popup(self : MoonPlasmaCompositor, wid : UInt64) return } let root = self.popup_root(wid) + for p in self.popups { + if p.id == wid { + release_snapshot(p.surface) + } + } let keep = self.popups.filter(p => p.id != wid) self.popups.clear() for p in keep { diff --git a/compositor/host/input_test.mbt b/compositor/host/input_test.mbt index 4d1639a..0174722 100644 --- a/compositor/host/input_test.mbt +++ b/compositor/host/input_test.mbt @@ -1030,3 +1030,35 @@ test "alt-tab switches to the previous window, tab again goes further back, esca key(15U, true, 30U) assert_false(comp.switcher_open()) } + +///| +test "compose_scene hands the host a scene only when something changed" { + let socket_path = "/tmp/wayland-moon-scene-" + @sys.getpid().to_string() + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap() + // The first scene is always drawn; the wallpaper and the desktop card are split out of it. + match comp.compose_scene() { + Some(sg) => { + assert_true(sg.wallpaper_ops.length() > 0) + assert_true(sg.panel_ops.length() > 0) + } + None => abort("the first scene must be drawn") + } + // Nothing happened: nothing to draw. + assert_true(comp.compose_scene() is None) + assert_false(comp.frame_changed) + // A new window changes the scene, then it settles again. + ignore(open_and_configure_client(comp, socket_path, "A", "a")) + match comp.compose_scene() { + Some(sg) => assert_eq(sg.windows.length(), 1) + None => abort("a new window must change the scene") + } + assert_true(comp.compose_scene() is None) + // The switcher overlay is part of the scene too. + comp.handle_input(@nested.InputEvent::Key(56U, true), 1U) + ignore(open_and_configure_client(comp, socket_path, "B", "b")) + ignore(comp.compose_scene()) + comp.handle_input(@nested.InputEvent::Key(15U, true), 2U) + assert_true(comp.switcher_open()) + assert_true(comp.compose_scene() is Some(_)) +} diff --git a/compositor/kms/kms_native.mbt b/compositor/kms/kms_native.mbt index d8a665d..5cf63e9 100644 --- a/compositor/kms/kms_native.mbt +++ b/compositor/kms/kms_native.mbt @@ -118,3 +118,9 @@ pub fn Kms::take_input(_self : Kms) -> Array[@nested.InputEvent] { pub fn Kms::close(_self : Kms) -> Unit { c_close() } + +///| The native build draws with the software renderer and uses `present`; there is no host +/// framebuffer to show. +pub fn Kms::present_frame(_self : Kms) -> Unit { + abort("present_frame is only available to the wasm compositor") +} diff --git a/compositor/kms/kms_wasm.mbt b/compositor/kms/kms_wasm.mbt index f38f69b..469af1f 100644 --- a/compositor/kms/kms_wasm.mbt +++ b/compositor/kms/kms_wasm.mbt @@ -41,6 +41,12 @@ pub fn Kms::present(_self : Kms, pixmap : @renderer.Pixmap) -> Unit { ) } +///| Show the host framebuffer (what the host rasteriser drew) on the output: nothing is copied +/// through this program. +pub fn Kms::present_frame(_self : Kms) -> Unit { + @hostdisplay.present_frame() +} + ///| Show the cursor for a wp_cursor_shape_v1 value. pub fn Kms::set_cursor_shape(_self : Kms, shape : UInt) -> Unit { @hostdisplay.set_cursor_shape(shape) diff --git a/compositor/nested/nested.mbt b/compositor/nested/nested.mbt index 7906a3c..98c6471 100644 --- a/compositor/nested/nested.mbt +++ b/compositor/nested/nested.mbt @@ -409,8 +409,7 @@ pub fn NestedWindow::present(self : NestedWindow, pixmap : @renderer.Pixmap) -> } let w = pixmap.width let h = pixmap.height - let stride = w * 4 - let len = stride * h + let len = w * 4 * h // RGBA -> little-endian ARGB8888 (B, G, R, A). let out : FixedArray[Byte] = FixedArray::make(len, b'\x00') for i = 0; i < w * h; i = i + 1 { @@ -425,6 +424,27 @@ pub fn NestedWindow::present(self : NestedWindow, pixmap : @renderer.Pixmap) -> return } ignore(@sys.pwrite_bytes(memfd, Bytes::from_fixedarray(out), 0)) + self.send_frame(memfd, w, h) +} + +///| Show the host's framebuffer (drawn by the host rasteriser) in the window: the host fills a +/// memfd with it and this hands that to the host compositor, so no pixels pass through here. +pub fn NestedWindow::present_frame(self : NestedWindow, w : Int, h : Int) -> Unit { + if self.frame_pending || self.closed { + return + } + let memfd = @sys.frame_memfd() + if memfd < 0 { + return + } + self.send_frame(memfd, w, h) +} + +///| Attach the ARGB8888 frame in `memfd` (w x h) to the window and ask for a frame callback. +/// Takes the descriptor: it is closed here once sent. +fn NestedWindow::send_frame(self : NestedWindow, memfd : Int, w : Int, h : Int) -> Unit { + let stride = w * 4 + let len = stride * h let pool = self.alloc() let wp = @wayland.WireWriter::new() wp.u32(pool) diff --git a/compositor/raster/moon.pkg b/compositor/raster/moon.pkg new file mode 100644 index 0000000..8402bb9 --- /dev/null +++ b/compositor/raster/moon.pkg @@ -0,0 +1,17 @@ +import { + "moonbitlang/core/builtin", + "moonplasma/desktop/compositor/scene" @scene, + "moonplasma/desktop/compositor/renderer" @renderer, + "moonplasma/desktop/interface/moonplasma/host/raster" @hostraster, +} + +supported_targets = "+native+wasm" + +// The wasm compositor hands its scene to the host to draw (`moonplasma:host/raster`); the native +// build has the software renderer instead, so this package only stubs the calls there. +options( + targets: { + "raster_wasm.mbt": ["wasm"], + "raster_native.mbt": ["native"], + }, +) diff --git a/compositor/raster/raster_native.mbt b/compositor/raster/raster_native.mbt new file mode 100644 index 0000000..715a35f --- /dev/null +++ b/compositor/raster/raster_native.mbt @@ -0,0 +1,12 @@ +///| The native build draws with the software renderer (`@renderer.render_scene`); there is no host +/// to send a scene to. + +///| +pub fn submit(_scene : @scene.SceneGraph) -> Unit { + abort("the host rasteriser is only available to the wasm compositor") +} + +///| +pub fn read_frame(_width : Int, _height : Int) -> @renderer.Pixmap { + abort("the host rasteriser is only available to the wasm compositor") +} diff --git a/compositor/raster/raster_wasm.mbt b/compositor/raster/raster_wasm.mbt new file mode 100644 index 0000000..440d34e --- /dev/null +++ b/compositor/raster/raster_wasm.mbt @@ -0,0 +1,97 @@ +///| Send a scene to the host to draw (`moonplasma:host/raster`). +/// +/// The scene is the same one the software renderer takes (`@scene.SceneGraph`); here it is turned +/// into the interface's records and handed over. The host owns the framebuffer and does the pixel +/// work natively; client window buffers are already there (captured at commit, by id). + +///| +fn conv_rect(r : @scene.Rect) -> @hostraster.Rect { + { x: r.x, y: r.y, w: r.w, h: r.h } +} + +///| +fn conv_color(c : @scene.Rgba) -> @hostraster.Color { + { r: c.r, g: c.g, b: c.b, a: c.a } +} + +///| +fn conv_align(a : @scene.TextAlign) -> Byte { + match a { + Left => b'\x00' + Center => b'\x01' + Right => b'\x02' + } +} + +///| +fn conv_op(op : @scene.DrawOp) -> @hostraster.Op { + match op { + FillRect(r, c, radius) => FillRect({ area: conv_rect(r), color: conv_color(c), radius }) + StrokeRect(r, c, width, radius) => StrokeRect({ area: conv_rect(r), color: conv_color(c), width, radius }) + Line(x0, y0, x1, y1, c, width) => DrawLine({ x0, y0, x1, y1, color: conv_color(c), width }) + Circle(cx, cy, radius, c, filled) => DrawCircle({ cx, cy, radius, color: conv_color(c), filled }) + Text(x, y, text, size, c, align, bold) => + DrawText({ x, y, text, size, color: conv_color(c), align: conv_align(align), bold, mono: false }) + MonoText(x, y, text, size, c, align, bold) => + DrawText({ x, y, text, size, color: conv_color(c), align: conv_align(align), bold, mono: true }) + PushClip(r) => PushClip(conv_rect(r)) + PopClip => PopClip + } +} + +///| +fn conv_ops(ops : Array[@scene.DrawOp]) -> Array[@hostraster.Op] { + ops.map(conv_op) +} + +///| The backdrop (wallpaper and the desktop card on it) the host last drew, and the size it was +/// drawn for. While neither changes the frame says "unchanged" and the host reuses its cached +/// pixels instead of being sent about two thousand ops again and drawing them. +let last_backdrop : Ref[Array[@scene.DrawOp]?] = { val: None } + +///| +let last_size : Ref[(Int, Int)] = { val: (0, 0) } + +///| Draw `scene` into the host framebuffer. +pub fn submit(scene : @scene.SceneGraph) -> Unit { + let backdrop = scene.wallpaper_ops + scene.background_ops + let same = match last_backdrop.val { + Some(prev) => prev == backdrop && last_size.val == (scene.output_w, scene.output_h) + None => false + } + if !same { + last_backdrop.val = Some(backdrop) + last_size.val = (scene.output_w, scene.output_h) + } + let windows : Array[@hostraster.Window] = scene.windows.map(w => { + let (top, right, bottom, left) = w.deco_insets + { + geometry: conv_rect(w.geometry), + inset_top: top, + inset_right: right, + inset_bottom: bottom, + inset_left: left, + deco: conv_ops(w.deco_ops), + fullscreen: w.fullscreen, + surface: match w.surface { + Some(s) => s.host_id + None => 0U + }, + } + }) + @hostraster.submit({ + width: scene.output_w, + height: scene.output_h, + wallpaper: if same { None } else { Some(conv_ops(backdrop)) }, + background: [], + windows, + panel: conv_ops(scene.panel_ops), + popups: scene.popups.map(p => { area: conv_rect(p.0), surface: p.1.host_id }), + }) +} + +///| The host framebuffer as a pixmap (screenshots and tests; the display path never needs it). +pub fn read_frame(width : Int, height : Int) -> @renderer.Pixmap { + let data = @hostraster.read_frame() + { width, height, data } +} diff --git a/compositor/renderer/fill_wbtest.mbt b/compositor/renderer/fill_wbtest.mbt index 80ff778..0025005 100644 --- a/compositor/renderer/fill_wbtest.mbt +++ b/compositor/renderer/fill_wbtest.mbt @@ -57,7 +57,7 @@ test "blitting a client buffer matches per-pixel blending, even partly off scree let raw = Bytes::from_fixedarray(bytes) for format in [0, 1] { for pos in [(0, 0), (5, 4), (-7, -3), (50, 40), (60, 30)] { - let buf : @scene.ShmBufferSnapshot = { width: w, height: h, stride: w * 4, format, bytes: raw } + let buf : @scene.ShmBufferSnapshot = { width: w, height: h, stride: w * 4, format, bytes: raw, host_id: 0U } let a = Pixmap::new(64, 48) let b = Pixmap::new(64, 48) for i = 0; i < a.data.length(); i = i + 1 { diff --git a/compositor/renderer/renderer_test.mbt b/compositor/renderer/renderer_test.mbt index 0506342..a3555be 100644 --- a/compositor/renderer/renderer_test.mbt +++ b/compositor/renderer/renderer_test.mbt @@ -44,6 +44,7 @@ test "software renderer alpha blending, rounded rect, shm blit, and png encoding stride: 400, format: 0, bytes: Bytes::from_array(buf_bytes), + host_id: 0U, }), }) diff --git a/compositor/scene/scene.mbt b/compositor/scene/scene.mbt index f64d823..66d92ab 100644 --- a/compositor/scene/scene.mbt +++ b/compositor/scene/scene.mbt @@ -239,6 +239,9 @@ pub(all) struct ShmBufferSnapshot { /// Wayland wl_shm format: 0 = ARGB8888, 1 = XRGB8888 format : Int bytes : Bytes + /// With the host rasteriser (the wasm compositor) the pixels live in the host, not in `bytes` + /// (empty): this is the host's surface id, 0 when there is none. + host_id : UInt } ///| diff --git a/compositor/sys/moon.pkg b/compositor/sys/moon.pkg index dd86adb..563f5d3 100644 --- a/compositor/sys/moon.pkg +++ b/compositor/sys/moon.pkg @@ -2,6 +2,7 @@ import { "moonbitlang/core/builtin", "moonbitlang/core/env" @env, "moonplasma/desktop/interface/moonplasma/host/sys" @hostsys, + "moonplasma/desktop/interface/moonplasma/host/raster" @hostraster, } supported_targets = "+native+wasm" diff --git a/compositor/sys/sys_native.mbt b/compositor/sys/sys_native.mbt index b34ee7b..19abe41 100644 --- a/compositor/sys/sys_native.mbt +++ b/compositor/sys/sys_native.mbt @@ -269,3 +269,24 @@ pub fn monotonic_ms() -> UInt64 { pub fn log(message : String) -> Unit { println(message) } + +///| Whether the host draws the screen (the wasm compositor): then client buffers are captured in +/// the host and the pixels never enter this program. Never on the native build. +pub fn host_raster() -> Bool { + false +} + +///| Copy a client buffer into a host surface; 0 (none) on the native build. +pub fn surface_capture(_fd : Int, _offset : Int, _stride : Int, _width : Int, _height : Int, _format : Int) -> UInt { + 0U +} + +///| +pub fn surface_release(_id : UInt) -> Unit { + () +} + +///| A memfd with the host framebuffer as ARGB8888; -1 on the native build. +pub fn frame_memfd() -> Int { + -1 +} diff --git a/compositor/sys/sys_wasm.mbt b/compositor/sys/sys_wasm.mbt index 6dd0f13..807dfd0 100644 --- a/compositor/sys/sys_wasm.mbt +++ b/compositor/sys/sys_wasm.mbt @@ -172,3 +172,25 @@ pub fn monotonic_ms() -> UInt64 { pub fn log(message : String) -> Unit { @hostsys.log(message) } + +///| The host draws the screen: client buffers are captured in the host (see `surface_capture`). +pub fn host_raster() -> Bool { + true +} + +///| Copy `stride * height` bytes at `offset` of the file behind `fd` into a host surface (a native +/// copy; the pixels never enter this program). `format`: 0 ARGB8888, 1 XRGB8888. 0 on failure. +pub fn surface_capture(fd : Int, offset : Int, stride : Int, width : Int, height : Int, format : Int) -> UInt { + @hostraster.capture(fd, offset, stride, width, height, format) +} + +///| Forget a captured surface. +pub fn surface_release(id : UInt) -> Unit { + @hostraster.release(id) +} + +///| A new memfd holding the host framebuffer as little-endian ARGB8888, for a wl_shm pool. The +/// caller closes it. -1 on failure. +pub fn frame_memfd() -> Int { + @hostraster.export_memfd() +} diff --git a/compositor/wayland/server.mbt b/compositor/wayland/server.mbt index 81cb3cb..d548018 100644 --- a/compositor/wayland/server.mbt +++ b/compositor/wayland/server.mbt @@ -385,8 +385,24 @@ fn snapshot_shm_buffer( if needed <= 0 || buf.width <= 0 || buf.height <= 0 { return None } - // Only this buffer's bytes: a pool can be hundreds of MB while a buffer is a few. let byte_len = buf.stride * buf.height + // With the host rasteriser the host copies the buffer itself and keeps the pixels: all this + // program holds is an id. + if @sys.host_raster() { + let id = @sys.surface_capture(pool.fd, buf.offset, buf.stride, buf.width, buf.height, buf.format) + if id == 0U { + return None + } + return Some({ + width: buf.width, + height: buf.height, + stride: buf.stride, + format: buf.format, + bytes: Bytes::make(0, b'\x00'), + host_id: id, + }) + } + // Only this buffer's bytes: a pool can be hundreds of MB while a buffer is a few. let slice = @sys.mmap_read_at(pool.fd, buf.offset, byte_len) if slice.length() < byte_len { return None @@ -397,6 +413,7 @@ fn snapshot_shm_buffer( stride: buf.stride, format: buf.format, bytes: slice, + host_id: 0U, }) } diff --git a/host-wasm/README.md b/host-wasm/README.md index 6253fb2..2968cd6 100644 --- a/host-wasm/README.md +++ b/host-wasm/README.md @@ -22,6 +22,29 @@ moon-plasma-host build/compositor.wasm --socket PATH --gfx-out frame.png moon-plasma-host build/compositor.wasm --socket PATH --gfx-out frame.png --serve # keep refreshing it ``` +## Drawing + +The compositor component decides what the screen shows and the host draws it +(`moonplasma:host/raster`, [`wit/host/raster.wit`](../wit/host/raster.wit)). Each frame the component +sends a list of draw operations (fill, stroke, line, circle, text, clip), the windows with their +decoration ops and a surface id, and the panel ops; `src/raster.rs` draws them natively into a +framebuffer it owns (a port of `compositor/renderer`, with the same blend arithmetic). The pixels never +cross the component boundary: + +- **Client windows:** at commit the host copies the buffer out of the client's shared memory into a + surface (`capture`, converted to RGBA once) and the component keeps only its id. Solid surfaces blit + as row copies. +- **Backdrop:** the wallpaper and the desktop card are cached as one layer and sent only when they change. +- **Showing it:** the login session shows the framebuffer straight from the host (`display.present-frame`); + the nested window gets it as a memfd (`raster.export-memfd`) that goes to the host compositor as a + `wl_shm` pool. `read-frame` returns the pixels for screenshots (`--gfx-out`). +- **Unchanged desktop:** if a scene is identical to the last one (no client damage, same ops) nothing is + sent or presented. +- `--profile` prints, every 3 s, frames, step, shell and draw (submit) time. + +The native compositor build keeps the software renderer (`compositor/renderer`); the two are tested +against each other's rules (`cargo test` here, `moon test` for the MoonBit side). + ## Status Working: Wayland server (real clients such as `foot` run and draw), window management, decorations, diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index 8ef4caf..61d89a5 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -16,6 +16,7 @@ use wasmtime::component::{Component, HasSelf, Linker}; use wasmtime::{Config, Engine, Result, Store}; mod plasmoid; +mod raster; #[cfg(feature = "drm")] mod kms; @@ -24,14 +25,14 @@ wasmtime::component::bindgen!({ world: "compositor", // The desktop value types are the same WIT the modules use: share the Rust types, so draw ops // flow from a module straight to the compositor without conversion. + // Draw operations are compared to reuse the cached wallpaper. + additional_derives: [PartialEq], with: { "moonplasma:desktop/types@0.1.0": plasmoid::ph::moonplasma::desktop::types, "moonplasma:desktop/theme@0.1.0": plasmoid::ph::moonplasma::desktop::theme, }, }); -use ab_glyph::{Font, FontVec, OutlineCurve}; -use ab_glyph_rasterizer::{point, Rasterizer}; use moonplasma::host::font::Glyph; use moonplasma::host::sys::{Host, Received}; @@ -41,8 +42,10 @@ struct State { private_bus: Option, bus_tried: bool, started: Option, - /// TTF faces loaded by the component (`font.load`), by slot. - fonts: [Option; 4], + /// TTF faces loaded by the component (`font.load`), by slot, and their glyph cache. + fonts: raster::Fonts, + /// The framebuffer and client surfaces behind `moonplasma:host/raster`. + raster: raster::Raster, /// Runs the panel modules; set once the engine exists. pl: Option, } @@ -254,6 +257,10 @@ impl moonplasma::host::display::Host for State { #[cfg(not(feature = "drm"))] false } + fn present_frame(&mut self) { + #[cfg(feature = "drm")] + kms::present(&self.raster.fb, self.raster.w as u32, self.raster.h as u32); + } fn present(&mut self, pixels: Vec, width: u32, height: u32) { #[cfg(feature = "drm")] kms::present(&pixels, width, height); @@ -280,50 +287,73 @@ impl moonplasma::host::display::Host for State { impl moonplasma::host::font::Host for State { fn load(&mut self, slot: u32, path: String) -> bool { - if slot as usize >= self.fonts.len() { - return false; + self.fonts.load(slot, &path) + } + + fn rasterise(&mut self, slot: u32, codepoint: u32, size: u32) -> Glyph { + let g = self.fonts.glyph(slot, codepoint, size); + Glyph { width: g.w, height: g.h, xoff: g.xoff, yoff: g.yoff, advance: g.advance, coverage: g.coverage.clone() } + } +} + +impl moonplasma::host::raster::Host for State { + fn capture(&mut self, fd: i32, offset: i32, stride: i32, width: i32, height: i32, format: i32) -> u32 { + if fd < 0 || offset < 0 || stride <= 0 || width <= 0 || height <= 0 { + return 0; } - match std::fs::read(path).ok().and_then(|d| FontVec::try_from_vec(d).ok()) { - Some(f) => { - self.fonts[slot as usize] = Some(f); - true + let len = stride as i64 * height as i64; + let end = offset as i64 + len; + unsafe { + let mut st: libc::stat = std::mem::zeroed(); + if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < end { + return 0; + } + // Mapping a large pool only reserves address space; just the pages copied are touched. + let p = libc::mmap(std::ptr::null_mut(), end as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0); + if p == libc::MAP_FAILED { + return 0; + } + let src = std::slice::from_raw_parts((p as *const u8).add(offset as usize), len as usize); + let surface = raster::Surface::from_bgra(src, stride as usize, width, height, format == 1); + libc::munmap(p, end as usize); + match surface { + Some(s) => self.raster.add_surface(s), + None => 0, } - None => false, } } - /// Same maths as stb_truetype in the native build: the size is an em size in pixels, the glyph - /// origin sits on the integer pixel grid, and the bitmap box is the outline's floor/ceil bounds. - fn rasterise(&mut self, slot: u32, codepoint: u32, size: u32) -> Glyph { - let blank = Glyph { width: 0, height: 0, xoff: 0, yoff: 0, advance: 0, coverage: Vec::new() }; - let Some(Some(font)) = self.fonts.get(slot as usize) else { return blank }; - let ch = char::from_u32(codepoint).unwrap_or('\u{fffd}'); - let id = font.glyph_id(ch); - let s = size as f32 / font.units_per_em().unwrap_or(1000.0); - let advance = (font.h_advance_unscaled(id) * s + 0.5) as i32; - let Some(outline) = font.outline(id) else { return Glyph { advance, ..blank } }; - // Font units grow upward, pixels downward; ab_glyph stores the outline's top edge as - // `min.y` and its bottom edge as `max.y`, both in font units. - let x0 = (outline.bounds.min.x * s).floor() as i32; - let x1 = (outline.bounds.max.x * s).ceil() as i32; - let y0 = (-outline.bounds.min.y * s).floor() as i32; - let y1 = (-outline.bounds.max.y * s).ceil() as i32; - let (w, h) = (x1 - x0, y1 - y0); - if w <= 0 || h <= 0 { - return Glyph { advance, ..blank }; - } - let tp = |p: ab_glyph::Point| point(p.x * s - x0 as f32, -p.y * s - y0 as f32); - let mut r = Rasterizer::new(w as usize, h as usize); - for c in &outline.curves { - match c { - OutlineCurve::Line(a, b) => r.draw_line(tp(*a), tp(*b)), - OutlineCurve::Quad(a, b, c) => r.draw_quad(tp(*a), tp(*b), tp(*c)), - OutlineCurve::Cubic(a, b, c, d) => r.draw_cubic(tp(*a), tp(*b), tp(*c), tp(*d)), + fn release(&mut self, id: u32) { + self.raster.release(id); + } + + fn submit(&mut self, f: moonplasma::host::raster::Frame) { + self.raster.submit(&f, &mut self.fonts); + } + + fn read_frame(&mut self) -> Vec { + self.raster.fb.clone() + } + + fn export_memfd(&mut self) -> i32 { + let data = self.raster.to_argb8888(); + let Ok(name) = CString::new("moon-plasma-frame") else { return -1 }; + unsafe { + let fd = libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC); + if fd < 0 { + return -1; } + let mut done = 0usize; + while done < data.len() { + let n = libc::write(fd, data[done..].as_ptr() as *const _, data.len() - done); + if n <= 0 { + libc::close(fd); + return -1; + } + done += n as usize; + } + fd } - let mut coverage = vec![0u8; (w * h) as usize]; - r.for_each_pixel(|i, a| coverage[i] = (a.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); - Glyph { width: w, height: h, xoff: x0, yoff: y0, advance, coverage } } } @@ -686,6 +716,7 @@ fn main() -> Result<()> { let mut linker: Linker = Linker::new(&engine); moonplasma::host::sys::add_to_linker::>(&mut linker, |s| s)?; moonplasma::host::font::add_to_linker::>(&mut linker, |s| s)?; + moonplasma::host::raster::add_to_linker::>(&mut linker, |s| s)?; moonplasma::host::display::add_to_linker::>(&mut linker, |s| s)?; moonplasma::host::plasmoids::add_to_linker::>(&mut linker, |s| s)?; let mut store = Store::new(&engine, State::default()); diff --git a/host-wasm/src/plasmoid.rs b/host-wasm/src/plasmoid.rs index d509a8e..fa61657 100644 --- a/host-wasm/src/plasmoid.rs +++ b/host-wasm/src/plasmoid.rs @@ -19,6 +19,7 @@ pub mod ph { wasmtime::component::bindgen!({ path: "../wit", world: "plasmoid-host", + additional_derives: [PartialEq], }); } use ph::exports::moonplasma::desktop as ex; diff --git a/host-wasm/src/raster.rs b/host-wasm/src/raster.rs new file mode 100644 index 0000000..e79e811 --- /dev/null +++ b/host-wasm/src/raster.rs @@ -0,0 +1,778 @@ +//! The host's rasteriser (`moonplasma:host/raster`). +//! +//! A direct port of compositor/renderer (the pure-MoonBit software renderer), so a frame comes out +//! pixel for pixel the same, but native: the compositor component sends draw operations and window +//! surface ids, and the pixels never cross the component boundary. Window buffers are copied out of +//! the client's shared memory once, at commit (`capture`), converted to RGBA, and kept here. + +use crate::moonplasma::host::raster as wt; +use ab_glyph::{Font, FontVec, OutlineCurve}; +use ab_glyph_rasterizer::{point, Rasterizer}; +use std::collections::HashMap; +use std::rc::Rc; + +// ---------------------------------------------------------------- fonts + +/// A rasterised glyph: an 8-bit coverage bitmap whose top-left sits at (`xoff`, `yoff`) from the +/// pen on the baseline (y grows downward), and the pen advance. +pub struct Glyph { + pub w: i32, + pub h: i32, + pub xoff: i32, + pub yoff: i32, + pub advance: i32, + pub coverage: Vec, +} + +/// TTF faces loaded by the component (`font.load`), by slot, and a cache of their glyphs. +#[derive(Default)] +pub struct Fonts { + faces: [Option; 4], + cache: HashMap<(u32, u32, u32), Rc>, +} + +impl Fonts { + pub fn load(&mut self, slot: u32, path: &str) -> bool { + if slot as usize >= self.faces.len() { + return false; + } + match std::fs::read(path).ok().and_then(|d| FontVec::try_from_vec(d).ok()) { + Some(f) => { + self.faces[slot as usize] = Some(f); + self.cache.retain(|k, _| k.0 != slot); + true + } + None => false, + } + } + + fn has(&self, slot: u32) -> bool { + self.faces.get(slot as usize).map_or(false, |f| f.is_some()) + } + + /// Same maths as stb_truetype in the native build: the size is an em size in pixels, the glyph + /// origin sits on the integer pixel grid, and the bitmap box is the outline's floor/ceil bounds. + pub fn glyph(&mut self, slot: u32, cp: u32, size: u32) -> Rc { + if let Some(g) = self.cache.get(&(slot, cp, size)) { + return g.clone(); + } + let g = Rc::new(self.rasterise(slot, cp, size)); + self.cache.insert((slot, cp, size), g.clone()); + g + } + + fn rasterise(&self, slot: u32, cp: u32, size: u32) -> Glyph { + let blank = Glyph { w: 0, h: 0, xoff: 0, yoff: 0, advance: 0, coverage: Vec::new() }; + let Some(Some(font)) = self.faces.get(slot as usize) else { return blank }; + let ch = char::from_u32(cp).unwrap_or('\u{fffd}'); + let id = font.glyph_id(ch); + let s = size as f32 / font.units_per_em().unwrap_or(1000.0); + let advance = (font.h_advance_unscaled(id) * s + 0.5) as i32; + let Some(outline) = font.outline(id) else { return Glyph { advance, ..blank } }; + // Font units grow upward, pixels downward; ab_glyph stores the outline's top edge as + // `min.y` and its bottom edge as `max.y`, both in font units. + let x0 = (outline.bounds.min.x * s).floor() as i32; + let x1 = (outline.bounds.max.x * s).ceil() as i32; + let y0 = (-outline.bounds.min.y * s).floor() as i32; + let y1 = (-outline.bounds.max.y * s).ceil() as i32; + let (w, h) = (x1 - x0, y1 - y0); + if w <= 0 || h <= 0 { + return Glyph { advance, ..blank }; + } + let tp = |p: ab_glyph::Point| point(p.x * s - x0 as f32, -p.y * s - y0 as f32); + let mut r = Rasterizer::new(w as usize, h as usize); + for c in &outline.curves { + match c { + OutlineCurve::Line(a, b) => r.draw_line(tp(*a), tp(*b)), + OutlineCurve::Quad(a, b, c) => r.draw_quad(tp(*a), tp(*b), tp(*c)), + OutlineCurve::Cubic(a, b, c, d) => r.draw_cubic(tp(*a), tp(*b), tp(*c), tp(*d)), + } + } + let mut coverage = vec![0u8; (w * h) as usize]; + r.for_each_pixel(|i, a| coverage[i] = (a.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + Glyph { w, h, xoff: x0, yoff: y0, advance, coverage } + } + + /// The glyph for `cp` in the face the UI uses for (bold, mono), and whether it must be + /// emboldened (a face with no bold instance gets its glyphs drawn a pixel wider). + /// Slots: 0 mono, 1 mono bold, 2 sans. None when no face is loaded at all. + fn pick(&mut self, cp: u32, size: u32, bold: bool, mono: bool) -> Option<(Rc, bool)> { + let has_mono = self.has(0); + let has_sans = self.has(2); + if !has_mono && !has_sans { + return None; + } + let has_bold = has_mono && self.has(1); + let (slot, embolden) = if mono && has_mono { + if bold && has_bold { (1, false) } else { (0, bold) } + } else if has_sans { + (2, bold) + } else { + (0, bold) + }; + Some((self.glyph(slot, cp, size), embolden)) + } +} + +// ---------------------------------------------------------------- canvas + +/// What every drawing function paints on: an RGBA8888 buffer. +pub struct Canvas<'a> { + pub w: i32, + pub h: i32, + pub data: &'a mut [u8], +} + +#[derive(Clone, Copy)] +struct R { + x: i32, + y: i32, + w: i32, + h: i32, +} + +impl From for R { + fn from(r: wt::Rect) -> R { + R { x: r.x, y: r.y, w: r.w, h: r.h } + } +} + +type Clip = Option; + +fn clamp_u8(v: i32) -> u8 { + v.clamp(0, 255) as u8 +} + +/// Blend one pixel; `clip` and the canvas bounds are checked. +fn blend_pixel(c: &mut Canvas, x: i32, y: i32, r: i32, g: i32, b: i32, a: i32, clip: Clip) { + if x < 0 || y < 0 || x >= c.w || y >= c.h || a <= 0 { + return; + } + if let Some(k) = clip { + if x < k.x || y < k.y || x >= k.x + k.w || y >= k.y + k.h { + return; + } + } + let off = ((y * c.w + x) * 4) as usize; + let d = &mut c.data[off..off + 4]; + if a >= 255 { + d[0] = r as u8; + d[1] = g as u8; + d[2] = b as u8; + d[3] = 0xff; + return; + } + let inv = 255 - a; + d[0] = ((r * a + d[0] as i32 * inv + 127) / 255) as u8; + d[1] = ((g * a + d[1] as i32 * inv + 127) / 255) as u8; + d[2] = ((b * a + d[2] as i32 * inv + 127) / 255) as u8; + d[3] = clamp_u8(a + (d[3] as i32 * inv + 127) / 255); +} + +/// Blend a colour over pixels [xa, xb) of row `y`; the span is already clipped. +fn blend_span(c: &mut Canvas, y: i32, xa: i32, xb: i32, r: i32, g: i32, b: i32, a: i32) { + if xa >= xb || a <= 0 { + return; + } + let row = &mut c.data[((y * c.w + xa) * 4) as usize..((y * c.w + xb) * 4) as usize]; + if a >= 255 { + for p in row.chunks_exact_mut(4) { + p[0] = r as u8; + p[1] = g as u8; + p[2] = b as u8; + p[3] = 0xff; + } + return; + } + let inv = 255 - a; + let (ra, ga, ba) = (r * a + 127, g * a + 127, b * a + 127); + for p in row.chunks_exact_mut(4) { + p[0] = ((ra + p[0] as i32 * inv) / 255) as u8; + p[1] = ((ga + p[1] as i32 * inv) / 255) as u8; + p[2] = ((ba + p[2] as i32 * inv) / 255) as u8; + p[3] = clamp_u8(a + (p[3] as i32 * inv + 127) / 255); + } +} + +/// True when (px, py) is inside the rectangle whose corners have radius `rad`. +fn in_rounded_rect(px: i32, py: i32, rx: i32, ry: i32, rw: i32, rh: i32, rad: i32) -> bool { + if px < rx || py < ry || px >= rx + rw || py >= ry + rh { + return false; + } + if rad <= 0 { + return true; + } + let max_r = rw.min(rh) / 2; + let r = rad.min(max_r); + if r <= 0 { + return true; + } + let (x_left, x_right) = (rx + r, rx + rw - r - 1); + let (y_top, y_bot) = (ry + r, ry + rh - r - 1); + let corner = |dx: i32, dy: i32| dx * dx + dy * dy <= r * r; + if px < x_left && py < y_top { + corner(x_left - px, y_top - py) + } else if px > x_right && py < y_top { + corner(px - x_right, y_top - py) + } else if px < x_left && py > y_bot { + corner(x_left - px, py - y_bot) + } else if px > x_right && py > y_bot { + corner(px - x_right, py - y_bot) + } else { + true + } +} + +/// The part of `rect` that is on the canvas and inside `clip`, as (x0, y0, x1, y1). +fn visible(c: &Canvas, rect: R, clip: Clip) -> Option<(i32, i32, i32, i32)> { + let (mut x0, mut y0) = (rect.x.max(0), rect.y.max(0)); + let (mut x1, mut y1) = ((rect.x + rect.w).min(c.w), (rect.y + rect.h).min(c.h)); + if let Some(k) = clip { + x0 = x0.max(k.x); + y0 = y0.max(k.y); + x1 = x1.min(k.x + k.w); + y1 = y1.min(k.y + k.h); + } + if x0 >= x1 || y0 >= y1 { None } else { Some((x0, y0, x1, y1)) } +} + +fn fill_rounded_rect(c: &mut Canvas, rect: R, col: wt::Color, radius: i32, clip: Clip) { + if rect.w <= 0 || rect.h <= 0 || col.a == 0 { + return; + } + let Some((x0, y0, x1, y1)) = visible(c, rect, clip) else { return }; + let (cr, cg, cb, ca) = (col.r as i32, col.g as i32, col.b as i32, col.a as i32); + if radius <= 0 { + for y in y0..y1 { + blend_span(c, y, x0, x1, cr, cg, cb, ca); + } + return; + } + let r = radius.min(rect.w.min(rect.h) / 2); + let (x_left, x_right) = (rect.x + r, rect.x + rect.w - r - 1); + let (y_top, y_bot) = (rect.y + r, rect.y + rect.h - r - 1); + for y in y0..y1 { + if y >= y_top && y <= y_bot { + blend_span(c, y, x0, x1, cr, cg, cb, ca); + continue; + } + let mut x = x0; + while x < x1 && x < x_left { + if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) { + blend_span(c, y, x, x + 1, cr, cg, cb, ca); + } + x += 1; + } + let (mid_a, mid_b) = (x_left.max(x0), (x_right + 1).min(x1)); + blend_span(c, y, mid_a, mid_b, cr, cg, cb, ca); + x = (x_right + 1).max(x0).max(mid_a); + while x < x1 { + if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) { + blend_span(c, y, x, x + 1, cr, cg, cb, ca); + } + x += 1; + } + } +} + +fn stroke_rounded_rect(c: &mut Canvas, rect: R, col: wt::Color, width: i32, radius: i32, clip: Clip) { + if rect.w <= 0 || rect.h <= 0 || width <= 0 || col.a == 0 { + return; + } + let (x0, y0) = (rect.x.max(0), rect.y.max(0)); + let (x1, y1) = ((rect.x + rect.w).min(c.w), (rect.y + rect.h).min(c.h)); + let (cr, cg, cb, ca) = (col.r as i32, col.g as i32, col.b as i32, col.a as i32); + let (inner_x, inner_y) = (rect.x + width, rect.y + width); + let (inner_w, inner_h) = (rect.w - width * 2, rect.h - width * 2); + let inner_r = if radius > width { radius - width } else { 0 }; + let (cx0, cx1, cy0, cy1) = match clip { + Some(k) => (k.x, k.x + k.w, k.y, k.y + k.h), + None => (0, c.w, 0, c.h), + }; + // Rows where the inner rectangle is full width only have the two side strips to draw. + let (mid_a, mid_b) = (inner_y + inner_r, inner_y + inner_h - inner_r); + for y in y0..y1 { + if inner_w > 0 && inner_h > 0 && y >= mid_a && y < mid_b { + if y >= cy0 && y < cy1 { + let l0 = x0.max(cx0); + let l1 = inner_x.min(x1).min(cx1); + blend_span(c, y, l0, l1, cr, cg, cb, ca); + let r0 = (inner_x + inner_w).max(x0).max(cx0); + blend_span(c, y, r0, x1.min(cx1), cr, cg, cb, ca); + } + continue; + } + for x in x0..x1 { + let in_outer = in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius); + let in_inner = inner_w > 0 + && inner_h > 0 + && in_rounded_rect(x, y, inner_x, inner_y, inner_w, inner_h, inner_r); + if in_outer && !in_inner { + blend_pixel(c, x, y, cr, cg, cb, ca, clip); + } + } + } +} + +fn draw_line(c: &mut Canvas, s: &wt::Segment, ox: i32, oy: i32, clip: Clip) { + let (cr, cg, cb, ca) = (s.color.r as i32, s.color.g as i32, s.color.b as i32, s.color.a as i32); + let half = if s.width <= 1 { 0 } else { s.width / 2 }; + let (mut x0, mut y0) = (s.x0 + ox, s.y0 + oy); + let (x1, y1) = (s.x1 + ox, s.y1 + oy); + let dx = (x1 - x0).abs(); + let sx = if x0 < x1 { 1 } else { -1 }; + let dy = -(y1 - y0).abs(); + let sy = if y0 < y1 { 1 } else { -1 }; + let mut err = dx + dy; + loop { + for oy2 in -half..=half { + for ox2 in -half..=half { + blend_pixel(c, x0 + ox2, y0 + oy2, cr, cg, cb, ca, clip); + } + } + if x0 == x1 && y0 == y1 { + break; + } + let e2 = 2 * err; + if e2 >= dy { + err += dy; + x0 += sx; + } + if e2 <= dx { + err += dx; + y0 += sy; + } + } +} + +fn draw_circle(c: &mut Canvas, d: &wt::Disc, ox: i32, oy: i32, clip: Clip) { + if d.radius <= 0 { + return; + } + let (cr, cg, cb, ca) = (d.color.r as i32, d.color.g as i32, d.color.b as i32, d.color.a as f64); + let rad = d.radius as f64; + let (cx, cy) = (d.cx + ox, d.cy + oy); + for dy in (-d.radius - 1)..=(d.radius + 1) { + for dx in (-d.radius - 1)..=(d.radius + 1) { + let dist = ((dx * dx + dy * dy) as f64).sqrt(); + let outer = rad + 0.5 - dist; + let mut cov = if outer > 1.0 { 1.0 } else { outer }; + if !d.filled { + let inner = dist - (rad - 1.0 - 0.5); + let ic = if inner > 1.0 { 1.0 } else { inner }; + if ic < cov { + cov = ic; + } + } + if cov > 0.02 { + blend_pixel(c, cx + dx, cy + dy, cr, cg, cb, (ca * cov).round() as i32, clip); + } + } + } +} + +fn draw_text(c: &mut Canvas, fonts: &mut Fonts, t: &wt::Label, ox: i32, oy: i32, clip: Clip) { + if t.text.is_empty() || t.color.a == 0 { + return; + } + let size = t.size.max(0) as u32; + let mut glyphs: Vec<(Rc, bool)> = Vec::new(); + let mut total_w = 0; + for ch in t.text.chars() { + match fonts.pick(ch as u32, size, t.bold, t.mono) { + Some((g, e)) => { + total_w += g.advance + if e { 1 } else { 0 }; + glyphs.push((g, e)); + } + None => return, // no face loaded: nothing to draw with + } + } + let x = t.x + ox; + let start_x = match t.align { + 1 => x - total_w / 2, + 2 => x - total_w, + _ => x, + }; + // `y` is the vertical centre of the text; centre the capital height ('H') on it. + let Some((cap, _)) = fonts.pick(72, size, false, t.mono) else { return }; + let baseline = t.y + oy + (-cap.yoff) / 2; + let (cr, cg, cb, ca) = (t.color.r as i32, t.color.g as i32, t.color.b as i32, t.color.a as i32); + let mut pen = start_x; + for (g, embolden) in &glyphs { + for row in 0..g.h { + for col in 0..g.w { + let cov = g.coverage[(row * g.w + col) as usize] as i32; + if cov > 0 { + let px = pen + g.xoff + col; + let py = baseline + g.yoff + row; + blend_pixel(c, px, py, cr, cg, cb, ca * cov / 255, clip); + if *embolden { + blend_pixel(c, px + 1, py, cr, cg, cb, ca * cov / 255, clip); + } + } + } + } + pen += g.advance + if *embolden { 1 } else { 0 }; + } +} + +/// Draw `ops` offset by (ox, oy), with the clip stack they push and pop. +fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, ops: &[wt::Op], ox: i32, oy: i32) { + let mut stack: Vec = Vec::new(); + for op in ops { + let clip = stack.last().copied(); + match op { + wt::Op::FillRect(f) => { + let r = R { x: f.area.x + ox, y: f.area.y + oy, w: f.area.w, h: f.area.h }; + fill_rounded_rect(c, r, f.color, f.radius, clip); + } + wt::Op::StrokeRect(s) => { + let r = R { x: s.area.x + ox, y: s.area.y + oy, w: s.area.w, h: s.area.h }; + stroke_rounded_rect(c, r, s.color, s.width, s.radius, clip); + } + wt::Op::DrawLine(l) => draw_line(c, l, ox, oy, clip), + wt::Op::DrawCircle(d) => draw_circle(c, d, ox, oy, clip), + wt::Op::DrawText(t) => draw_text(c, fonts, t, ox, oy, clip), + wt::Op::PushClip(r) => stack.push(R { x: r.x + ox, y: r.y + oy, w: r.w, h: r.h }), + wt::Op::PopClip => { + stack.pop(); + } + } + } +} + +// ---------------------------------------------------------------- surfaces + +/// A client window buffer, copied out of its shared memory and converted to RGBA8888. +pub struct Surface { + w: i32, + h: i32, + rgba: Vec, + /// Every pixel has alpha 255 (XRGB, or an ARGB buffer that happens to be solid): blits copy rows. + opaque: bool, +} + +impl Surface { + /// Build one from `h` rows of `stride` bytes of little-endian B, G, R, A (or X) pixels. + pub fn from_bgra(src: &[u8], stride: usize, w: i32, h: i32, xrgb: bool) -> Option { + if w <= 0 || h <= 0 || stride < w as usize * 4 || src.len() < stride * (h as usize - 1) + w as usize * 4 { + return None; + } + let mut rgba = vec![0u8; w as usize * h as usize * 4]; + let mut opaque = true; + for y in 0..h as usize { + let s = &src[y * stride..y * stride + w as usize * 4]; + let d = &mut rgba[y * w as usize * 4..(y + 1) * w as usize * 4]; + for (sp, dp) in s.chunks_exact(4).zip(d.chunks_exact_mut(4)) { + dp[0] = sp[2]; + dp[1] = sp[1]; + dp[2] = sp[0]; + dp[3] = if xrgb { 0xff } else { sp[3] }; + opaque &= dp[3] == 0xff; + } + } + Some(Surface { w, h, rgba, opaque }) + } +} + +/// Draw a client surface into `dst`. While the client catches up with a resize its buffer is smaller +/// than the window: the buffer's bottom-right colour is extended over the rest. +fn blit_surface(c: &mut Canvas, s: &Surface, dst: R) { + if s.w <= 0 || s.h <= 0 || dst.w <= 0 || dst.h <= 0 { + return; + } + if s.w < dst.w || s.h < dst.h { + let o = ((s.h - 1) * s.w + (s.w - 1)) as usize * 4; + let col = wt::Color { r: s.rgba[o], g: s.rgba[o + 1], b: s.rgba[o + 2], a: s.rgba[o + 3] }; + fill_rounded_rect(c, dst, col, 0, None); + } + let (copy_w, copy_h) = (s.w.min(dst.w), s.h.min(dst.h)); + let c0 = (-dst.x).max(0); + let c1 = copy_w.min(c.w - dst.x); + if c0 >= c1 { + return; + } + for row in 0..copy_h { + let dy = dst.y + row; + if dy < 0 || dy >= c.h { + continue; + } + let src = &s.rgba[((row * s.w + c0) * 4) as usize..((row * s.w + c1) * 4) as usize]; + let d0 = ((dy * c.w + dst.x + c0) * 4) as usize; + let dst_row = &mut c.data[d0..d0 + src.len()]; + if s.opaque { + dst_row.copy_from_slice(src); + } else { + for (sp, dp) in src.chunks_exact(4).zip(dst_row.chunks_exact_mut(4)) { + let a = sp[3] as i32; + if a >= 255 { + dp.copy_from_slice(sp); + } else if a > 0 { + let inv = 255 - a; + dp[0] = ((sp[0] as i32 * a + dp[0] as i32 * inv + 127) / 255) as u8; + dp[1] = ((sp[1] as i32 * a + dp[1] as i32 * inv + 127) / 255) as u8; + dp[2] = ((sp[2] as i32 * a + dp[2] as i32 * inv + 127) / 255) as u8; + dp[3] = clamp_u8(a + (dp[3] as i32 * inv + 127) / 255); + } + } + } + } +} + +// ---------------------------------------------------------------- the rasteriser + +/// The framebuffer, the wallpaper cache and the captured client surfaces. +#[derive(Default)] +pub struct Raster { + pub w: i32, + pub h: i32, + /// RGBA8888, `w * h * 4` bytes. + pub fb: Vec, + wallpaper: Option<(Vec, i32, i32, Vec)>, + surfaces: HashMap, + next_id: u32, +} + +impl Raster { + pub fn add_surface(&mut self, s: Surface) -> u32 { + self.next_id = self.next_id.wrapping_add(1).max(1); + self.surfaces.insert(self.next_id, s); + self.next_id + } + + pub fn release(&mut self, id: u32) { + self.surfaces.remove(&id); + } + + pub fn surface_count(&self) -> usize { + self.surfaces.len() + } + + /// Draw a frame into the framebuffer: wallpaper (cached), background, windows bottom to top, + /// panel, then client popups. The same layering as the software renderer's `render_scene`. + pub fn submit(&mut self, f: &wt::Frame, fonts: &mut Fonts) { + let (w, h) = (f.width.max(1), f.height.max(1)); + if w != self.w || h != self.h || self.fb.len() != (w * h * 4) as usize { + self.w = w; + self.h = h; + self.fb = vec![0u8; (w * h * 4) as usize]; + } else { + self.fb.fill(0); + } + let surfaces = &self.surfaces; + let mut c = Canvas { w, h, data: &mut self.fb }; + + // 1. Wallpaper: drawn once, copied back while unchanged. + match &f.wallpaper { + Some(ops) => { + let cached = matches!(&self.wallpaper, Some((o, cw, ch, _)) if *cw == w && *ch == h && o == ops); + if cached { + c.data.copy_from_slice(&self.wallpaper.as_ref().unwrap().3); + } else { + draw_ops(&mut c, fonts, ops, 0, 0); + self.wallpaper = Some((ops.clone(), w, h, c.data.to_vec())); + } + } + None => { + if let Some((_, cw, ch, px)) = &self.wallpaper { + if *cw == w && *ch == h { + c.data.copy_from_slice(px); + } + } + } + } + draw_ops(&mut c, fonts, &f.background, 0, 0); + + // 2. Windows, bottom to top. + for win in &f.windows { + let g = R::from(win.geometry); + if !win.fullscreen { + let (outer_x, outer_y) = (g.x - win.inset_left, g.y - win.inset_top); + let outer_w = g.w + win.inset_left + win.inset_right; + let outer_h = g.h + win.inset_top + win.inset_bottom; + // Subtle drop shadow: only the strips that stick out from under the window (and the + // part under the translucent title bar) are blended. + let shadow = R { x: outer_x + 4, y: outer_y + 6, w: outer_w, h: outer_h }; + let col = wt::Color { r: 0, g: 0, b: 0, a: 80 }; + let strips = [ + R { x: outer_x + outer_w, y: outer_y, w: 4, h: outer_h + 6 }, + R { x: outer_x, y: outer_y + outer_h, w: outer_w + 4, h: 6 }, + R { x: outer_x, y: outer_y, w: outer_w, h: win.inset_top + 2 }, + ]; + for s in strips { + fill_rounded_rect(&mut c, shadow, col, 8, Some(s)); + } + draw_ops(&mut c, fonts, &win.deco, outer_x, outer_y); + } + match surfaces.get(&win.surface) { + Some(s) => blit_surface(&mut c, s, g), + None => fill_rounded_rect(&mut c, g, wt::Color { r: 0x1e, g: 0x29, b: 0x3b, a: 0xff }, 0, None), + } + } + + // 3. Panel (and its popups, menus and notices), then 4. client popups above everything. + draw_ops(&mut c, fonts, &f.panel, 0, 0); + for p in &f.popups { + if let Some(s) = surfaces.get(&p.surface) { + blit_surface(&mut c, s, R::from(p.area)); + } + } + } + + /// The framebuffer as little-endian ARGB8888 (B, G, R, A=255), `stride = w * 4`. + pub fn to_argb8888(&self) -> Vec { + let mut out = vec![0u8; self.fb.len()]; + for (s, d) in self.fb.chunks_exact(4).zip(out.chunks_exact_mut(4)) { + d[0] = s[2]; + d[1] = s[1]; + d[2] = s[0]; + d[3] = 0xff; + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn color(r: u8, g: u8, b: u8, a: u8) -> wt::Color { + wt::Color { r, g, b, a } + } + fn rect(x: i32, y: i32, w: i32, h: i32) -> wt::Rect { + wt::Rect { x, y, w, h } + } + fn fill(x: i32, y: i32, w: i32, h: i32, c: wt::Color, radius: i32) -> wt::Op { + wt::Op::FillRect(wt::Fill { area: rect(x, y, w, h), color: c, radius }) + } + fn frame(w: i32, h: i32) -> wt::Frame { + wt::Frame { width: w, height: h, wallpaper: None, background: vec![], windows: vec![], panel: vec![], popups: vec![] } + } + fn px(r: &Raster, x: i32, y: i32) -> [u8; 4] { + let o = ((y * r.w + x) * 4) as usize; + [r.fb[o], r.fb[o + 1], r.fb[o + 2], r.fb[o + 3]] + } + + #[test] + fn fills_blend_with_the_same_arithmetic_as_the_software_renderer() { + let mut r = Raster::default(); + let mut f = frame(20, 10); + f.background = vec![fill(0, 0, 20, 10, color(10, 20, 30, 255), 0), fill(2, 2, 6, 6, color(200, 100, 0, 128), 0)]; + r.submit(&f, &mut Fonts::default()); + assert_eq!(px(&r, 0, 0), [10, 20, 30, 255]); + // (200*128 + 10*127 + 127) / 255 = 105, (100*128 + 20*127 + 127) / 255 = 60, (0 + 30*127 + 127) / 255 = 15 + assert_eq!(px(&r, 3, 3), [105, 60, 15, 255]); + } + + #[test] + fn rounded_corners_leave_the_corner_pixel_untouched() { + let mut r = Raster::default(); + let mut f = frame(40, 40); + f.background = vec![fill(4, 4, 30, 30, color(255, 255, 255, 255), 10)]; + r.submit(&f, &mut Fonts::default()); + assert_eq!(px(&r, 4, 4), [0, 0, 0, 0]); // outside the rounded corner + assert_eq!(px(&r, 19, 19), [255, 255, 255, 255]); + assert_eq!(px(&r, 19, 4), [255, 255, 255, 255]); // straight edge + } + + #[test] + fn stroke_draws_only_the_border() { + let mut r = Raster::default(); + let mut f = frame(30, 30); + f.background = vec![wt::Op::StrokeRect(wt::Stroke { area: rect(2, 2, 20, 20), color: color(9, 9, 9, 255), width: 2, radius: 0 })]; + r.submit(&f, &mut Fonts::default()); + assert_eq!(px(&r, 2, 10), [9, 9, 9, 255]); + assert_eq!(px(&r, 3, 10), [9, 9, 9, 255]); + assert_eq!(px(&r, 4, 10), [0, 0, 0, 0]); // interior + assert_eq!(px(&r, 21, 10), [9, 9, 9, 255]); + assert_eq!(px(&r, 10, 21), [9, 9, 9, 255]); + } + + #[test] + fn clip_ops_limit_drawing() { + let mut r = Raster::default(); + let mut f = frame(20, 20); + f.background = vec![ + wt::Op::PushClip(rect(5, 5, 5, 5)), + fill(0, 0, 20, 20, color(1, 2, 3, 255), 0), + wt::Op::PopClip, + fill(0, 0, 2, 2, color(7, 7, 7, 255), 0), + ]; + r.submit(&f, &mut Fonts::default()); + assert_eq!(px(&r, 6, 6), [1, 2, 3, 255]); + assert_eq!(px(&r, 2, 2), [0, 0, 0, 0]); + assert_eq!(px(&r, 10, 10), [0, 0, 0, 0]); + assert_eq!(px(&r, 1, 1), [7, 7, 7, 255]); + } + + #[test] + fn wallpaper_is_cached_and_reused_when_the_frame_says_unchanged() { + let mut r = Raster::default(); + let mut fonts = Fonts::default(); + let mut f = frame(16, 16); + f.wallpaper = Some(vec![fill(0, 0, 16, 16, color(50, 60, 70, 255), 0)]); + r.submit(&f, &mut fonts); + assert_eq!(px(&r, 8, 8), [50, 60, 70, 255]); + let mut g = frame(16, 16); + g.wallpaper = None; // unchanged: the cached pixels come back + g.background = vec![fill(0, 0, 2, 2, color(1, 1, 1, 255), 0)]; + r.submit(&g, &mut fonts); + assert_eq!(px(&r, 8, 8), [50, 60, 70, 255]); + assert_eq!(px(&r, 0, 0), [1, 1, 1, 255]); + // A different wallpaper is drawn afresh. + f.wallpaper = Some(vec![fill(0, 0, 16, 16, color(9, 8, 7, 255), 0)]); + r.submit(&f, &mut fonts); + assert_eq!(px(&r, 8, 8), [9, 8, 7, 255]); + } + + #[test] + fn windows_blit_their_surface_converted_from_bgra_and_shadow_only_sticks_out() { + let mut r = Raster::default(); + // A 4x2 XRGB buffer, every pixel B=10 G=20 R=30. + let bgra: Vec = (0..8).flat_map(|_| [10u8, 20, 30, 0]).collect(); + let id = r.add_surface(Surface::from_bgra(&bgra, 16, 4, 2, true).unwrap()); + let mut f = frame(40, 30); + f.background = vec![fill(0, 0, 40, 30, color(200, 200, 200, 255), 0)]; + f.windows = vec![wt::Window { + geometry: rect(10, 10, 4, 2), + inset_top: 0, + inset_right: 0, + inset_bottom: 0, + inset_left: 0, + deco: vec![], + fullscreen: false, + surface: id, + }]; + r.submit(&f, &mut Fonts::default()); + assert_eq!(px(&r, 10, 10), [30, 20, 10, 255]); // R, G, B order after conversion + assert_eq!(px(&r, 13, 11), [30, 20, 10, 255]); + // The shadow sits to the right of / below the window, not under it. + // The shadow rectangle is the window moved by (4, 6): (14..18, 16..18) here. + assert!(px(&r, 15, 17)[0] < 200, "shadow strip below and to the right"); + assert_eq!(px(&r, 15, 12)[0], 200, "no shadow where the offset rectangle does not reach"); + r.release(id); + assert_eq!(r.surface_count(), 0); + } + + #[test] + fn translucent_surfaces_blend_over_what_is_behind() { + let mut r = Raster::default(); + // One ARGB pixel: B=0 G=0 R=255 A=128, over a grey background. + let id = r.add_surface(Surface::from_bgra(&[0, 0, 255, 128], 4, 1, 1, false).unwrap()); + let mut f = frame(8, 8); + f.background = vec![fill(0, 0, 8, 8, color(100, 100, 100, 255), 0)]; + f.windows = vec![wt::Window { geometry: rect(2, 2, 1, 1), inset_top: 0, inset_right: 0, inset_bottom: 0, inset_left: 0, deco: vec![], fullscreen: true, surface: id }]; + r.submit(&f, &mut Fonts::default()); + // (255*128 + 100*127 + 127) / 255 = 178, (0 + 100*127 + 127) / 255 = 50 + assert_eq!(px(&r, 2, 2), [178, 50, 50, 255]); + } + + #[test] + fn argb_export_swaps_red_and_blue() { + let mut r = Raster::default(); + let mut f = frame(2, 1); + f.background = vec![fill(0, 0, 2, 1, color(1, 2, 3, 255), 0)]; + r.submit(&f, &mut Fonts::default()); + assert_eq!(&r.to_argb8888()[..4], &[3, 2, 1, 255]); + } +} diff --git a/interface/moonplasma/host/display/ffi.mbt b/interface/moonplasma/host/display/ffi.mbt index e8bb64e..978dc7f 100644 --- a/interface/moonplasma/host/display/ffi.mbt +++ b/interface/moonplasma/host/display/ffi.mbt @@ -12,6 +12,9 @@ fn wasmImportFrameReady() -> Int = "moonplasma:host/display@0.1.0" "frame-ready" ///| fn wasmImportPresent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) = "moonplasma:host/display@0.1.0" "present" +///| +fn wasmImportPresentFrame() = "moonplasma:host/display@0.1.0" "present-frame" + ///| fn wasmImportSetCursorShape(p0 : Int) = "moonplasma:host/display@0.1.0" "set-cursor-shape" @@ -21,26 +24,27 @@ fn wasmImportTakeInput(p0 : Int) = "moonplasma:host/display@0.1.0" "take-input" ///| fn wasmImportClose() = "moonplasma:host/display@0.1.0" "close" -///| -extern "wasm" fn mbt_ffi_loadf64(offset : Int) -> Double = -#|(func (param i32) (result f64) local.get 0 f64.load) - ///| extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load8_u) -///| -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) - ///| #owned(bytes) extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> 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_loadf64(offset : Int) -> Double = +#|(func (param i32) (result f64) local.get 0 f64.load) + ///| extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #|(func (param i32) (result i32) (local i32) @@ -49,10 +53,9 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #| local.get 1) ///| -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_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) diff --git a/interface/moonplasma/host/display/native_stub.mbt b/interface/moonplasma/host/display/native_stub.mbt index 9afbabb..79ef663 100644 --- a/interface/moonplasma/host/display/native_stub.mbt +++ b/interface/moonplasma/host/display/native_stub.mbt @@ -20,6 +20,11 @@ fn wasmImportPresent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Unit { abort("wasm-only host import") } +///| +fn wasmImportPresentFrame() -> Unit { + abort("wasm-only host import") +} + ///| fn wasmImportSetCursorShape(p0 : Int) -> Unit { abort("wasm-only host import") @@ -35,28 +40,18 @@ fn wasmImportClose() -> Unit { abort("wasm-only host import") } -///| -fn mbt_ffi_loadf64(offset : Int) -> Double { - abort("wasm-only") -} - ///| fn mbt_ffi_load8_u(offset : Int) -> Int { abort("wasm-only") } -///| -fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { - abort("wasm-only") -} - ///| fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { abort("wasm-only") } ///| -fn mbt_ffi_malloc(size : Int) -> Int { +fn mbt_ffi_load32(offset : Int) -> Int { abort("wasm-only") } @@ -66,6 +61,16 @@ fn mbt_ffi_free(position : Int) -> Unit { } ///| -fn mbt_ffi_load32(offset : Int) -> Int { +fn mbt_ffi_loadf64(offset : Int) -> Double { + 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") } diff --git a/interface/moonplasma/host/display/top.mbt b/interface/moonplasma/host/display/top.mbt index a7840bc..74e1558 100644 --- a/interface/moonplasma/host/display/top.mbt +++ b/interface/moonplasma/host/display/top.mbt @@ -74,6 +74,13 @@ pub fn present(pixels : FixedArray[Byte], width : UInt, height : UInt) -> Unit { wasmImportPresent(ptr, pixels.length(), (width).reinterpret_as_int(), (height).reinterpret_as_int()); mbt_ffi_free(ptr) +} +///| +/// Show the host framebuffer (what `raster.submit` drew) on the output. +pub fn present_frame() -> Unit { + + wasmImportPresentFrame(); + } ///| /// Show the cursor for a wp_cursor_shape_v1 value. diff --git a/interface/moonplasma/host/font/ffi.mbt b/interface/moonplasma/host/font/ffi.mbt index cb2c6ce..cd7368a 100644 --- a/interface/moonplasma/host/font/ffi.mbt +++ b/interface/moonplasma/host/font/ffi.mbt @@ -7,9 +7,8 @@ fn wasmImportLoad(p0 : Int, p1 : Int, p2 : Int) -> Int = "moonplasma:host/font@0 fn wasmImportRasterise(p0 : Int, p1 : Int, p2 : Int, p3 : Int) = "moonplasma:host/font@0.1.0" "rasterise" ///| -#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_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = @@ -18,6 +17,11 @@ extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = #| local.get 1 call $moonbit.init_array8 #| local.get 0) +///| +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) + ///| extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #|(func (param i32) (result i32) (local i32) @@ -29,7 +33,3 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = 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) - diff --git a/interface/moonplasma/host/font/native_stub.mbt b/interface/moonplasma/host/font/native_stub.mbt index af33cfd..8ed6a45 100644 --- a/interface/moonplasma/host/font/native_stub.mbt +++ b/interface/moonplasma/host/font/native_stub.mbt @@ -11,7 +11,7 @@ fn wasmImportRasterise(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Unit { } ///| -fn mbt_ffi_str2ptr(str : String) -> Int { +fn mbt_ffi_load32(offset : Int) -> Int { abort("wasm-only") } @@ -20,6 +20,11 @@ fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { abort("wasm-only") } +///| +fn mbt_ffi_str2ptr(str : String) -> Int { + abort("wasm-only") +} + ///| fn mbt_ffi_malloc(size : Int) -> Int { abort("wasm-only") @@ -29,8 +34,3 @@ fn mbt_ffi_malloc(size : Int) -> Int { fn mbt_ffi_free(position : Int) -> Unit { abort("wasm-only") } - -///| -fn mbt_ffi_load32(offset : Int) -> Int { - abort("wasm-only") -} diff --git a/interface/moonplasma/host/plasmoids/ffi.mbt b/interface/moonplasma/host/plasmoids/ffi.mbt index ec4454d..be739a9 100644 --- a/interface/moonplasma/host/plasmoids/ffi.mbt +++ b/interface/moonplasma/host/plasmoids/ffi.mbt @@ -46,21 +46,26 @@ fn wasmImportPickerStart() -> Int = "moonplasma:host/plasmoids@0.1.0" "picker-st fn wasmImportPickerPoll(p0 : Int) = "moonplasma:host/plasmoids@0.1.0" "picker-poll" ///| -extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = -#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) ///| -extern "wasm" fn mbt_ffi_free(position : Int) = -#|(func (param i32) local.get 0 call $moonbit.decref) - -///| -extern "wasm" fn mbt_ffi_store64(offset : Int, value : Int64) = -#|(func (param i32) (param i64) local.get 0 local.get 1 i64.store) +extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = +#|(func (param i32) (result i64) local.get 0 i64.load) ///| extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) +///| +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) + +///| +extern "wasm" fn mbt_ffi_store64(offset : Int, value : Int64) = +#|(func (param i32) (param i64) local.get 0 local.get 1 i64.store) + ///| extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #|(func (param i32) (result i32) (local i32) @@ -68,19 +73,6 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #| local.tee 1 i32.const 0 call $moonbit.init_array8 #| local.get 1) -///| -extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = -#|(func (param i32) (result i32) local.get 0 i32.load8_u) - -///| -extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = -#|(func (param i32) (result i32) local.get 0 i32.load) - -///| -#owned(bytes) -extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = -#|(func (param i32) (result i32) local.get 0) - ///| extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #|(func (param i32) (param i32) (result i32) @@ -89,11 +81,19 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #| local.get 0) ///| -extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = -#|(func (param i32) (result i64) local.get 0 i64.load) +extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) ///| -#owned(str) -extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +#owned(bytes) +extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> 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) + diff --git a/interface/moonplasma/host/plasmoids/native_stub.mbt b/interface/moonplasma/host/plasmoids/native_stub.mbt index 51ef5ce..077a47d 100644 --- a/interface/moonplasma/host/plasmoids/native_stub.mbt +++ b/interface/moonplasma/host/plasmoids/native_stub.mbt @@ -75,6 +75,41 @@ fn wasmImportPickerPoll(p0 : Int) -> Unit { abort("wasm-only host import") } +///| +fn mbt_ffi_load8_u(offset : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_load64(offset : Int) -> Int64 { + abort("wasm-only") +} + +///| +fn mbt_ffi_store32(offset : Int, value : Int) -> Unit { + abort("wasm-only") +} + +///| +fn mbt_ffi_str2ptr(str : String) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit { + abort("wasm-only") +} + +///| +fn mbt_ffi_malloc(size : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { + abort("wasm-only") +} + ///| fn mbt_ffi_store8(offset : Int, value : Int) -> Unit { abort("wasm-only") @@ -86,22 +121,7 @@ fn mbt_ffi_free(position : Int) -> Unit { } ///| -fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit { - abort("wasm-only") -} - -///| -fn mbt_ffi_store32(offset : Int, value : Int) -> Unit { - abort("wasm-only") -} - -///| -fn mbt_ffi_malloc(size : Int) -> Int { - abort("wasm-only") -} - -///| -fn mbt_ffi_load8_u(offset : Int) -> Int { +fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { abort("wasm-only") } @@ -109,23 +129,3 @@ fn mbt_ffi_load8_u(offset : Int) -> Int { fn mbt_ffi_load32(offset : Int) -> Int { abort("wasm-only") } - -///| -fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { - abort("wasm-only") -} - -///| -fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { - abort("wasm-only") -} - -///| -fn mbt_ffi_load64(offset : Int) -> Int64 { - abort("wasm-only") -} - -///| -fn mbt_ffi_str2ptr(str : String) -> Int { - abort("wasm-only") -} diff --git a/interface/moonplasma/host/raster/ffi.mbt b/interface/moonplasma/host/raster/ffi.mbt new file mode 100644 index 0000000..85912e8 --- /dev/null +++ b/interface/moonplasma/host/raster/ffi.mbt @@ -0,0 +1,52 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +fn wasmImportCapture(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int) -> Int = "moonplasma:host/raster@0.1.0" "capture" + +///| +fn wasmImportRelease(p0 : Int) = "moonplasma:host/raster@0.1.0" "release" + +///| +fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) = "moonplasma:host/raster@0.1.0" "submit" + +///| +fn wasmImportReadFrame(p0 : Int) = "moonplasma:host/raster@0.1.0" "read-frame" + +///| +fn wasmImportExportMemfd() -> Int = "moonplasma:host/raster@0.1.0" "export-memfd" + +///| +extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) + +///| +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) + +///| +#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_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_store32(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) + diff --git a/interface/moonplasma/host/raster/moon.pkg b/interface/moonplasma/host/raster/moon.pkg new file mode 100644 index 0000000..615617d --- /dev/null +++ b/interface/moonplasma/host/raster/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/raster/native_stub.mbt b/interface/moonplasma/host/raster/native_stub.mbt new file mode 100644 index 0000000..2642b09 --- /dev/null +++ b/interface/moonplasma/host/raster/native_stub.mbt @@ -0,0 +1,61 @@ +// Generated by scripts/gen-native-stubs.py. Native stand-ins for the wasm-only ffi.mbt. + +///| +fn wasmImportCapture(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportRelease(p0 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportReadFrame(p0 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportExportMemfd() -> Int { + abort("wasm-only host import") +} + +///| +fn mbt_ffi_store8(offset : Int, value : Int) -> Unit { + 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_str2ptr(str : String) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_load32(offset : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { + abort("wasm-only") +} + +///| +fn mbt_ffi_store32(offset : Int, value : Int) -> Unit { + abort("wasm-only") +} diff --git a/interface/moonplasma/host/raster/top.mbt b/interface/moonplasma/host/raster/top.mbt new file mode 100644 index 0000000..16d9a31 --- /dev/null +++ b/interface/moonplasma/host/raster/top.mbt @@ -0,0 +1,550 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +pub(all) struct Rect { + x : Int; y : Int; w : Int; h : Int +} +///| +pub(all) struct Color { + r : Byte; g : Byte; b : Byte; a : Byte +} +///| +pub(all) struct Fill { + area : Rect; color : Color; radius : Int +} +///| +pub(all) struct Stroke { + area : Rect; color : Color; width : Int; radius : Int +} +///| +pub(all) struct Segment { + x0 : Int; y0 : Int; x1 : Int; y1 : Int; color : Color; width : Int +} +///| +pub(all) struct Disc { + cx : Int; cy : Int; radius : Int; color : Color; filled : Bool +} +///| +/// `align`: 0 left, 1 centre, 2 right of `x`; `y` is the text's vertical centre. +pub(all) struct Label { + x : Int; y : Int; text : String; size : Int; color : Color; align : Byte; bold : Bool; mono : Bool +} +///| +pub(all) enum Op { + FillRect(Fill) + StrokeRect(Stroke) + DrawLine(Segment) + DrawCircle(Disc) + DrawText(Label) + PushClip(Rect) + PopClip +} +///| +/// A toplevel: its decoration (drawn at `geometry` minus the insets), then its client surface. +pub(all) struct Window { + geometry : Rect; inset_top : Int; inset_right : Int; inset_bottom : Int; inset_left : Int; deco : Array[Op]; fullscreen : Bool; surface : UInt +} +///| +pub(all) struct Popup { + area : Rect; surface : UInt +} +///| +pub(all) struct Frame { + width : Int; height : Int; wallpaper : Array[Op]?; background : Array[Op]; windows : Array[Window]; panel : Array[Op]; popups : Array[Popup] +} +///| +/// Copy a client buffer (`stride * height` bytes at `offset` of the file behind `fd`) into a +/// host surface. `format` is the wl_shm format (0 ARGB8888, 1 XRGB8888). 0 on failure. +pub fn capture(fd : Int, offset : Int, stride : Int, width : Int, height : Int, format : Int) -> UInt { + + let result : Int = wasmImportCapture(fd, offset, stride, width, height, format); + let ret = (result).reinterpret_as_uint() + return ret + +} +///| +pub fn release(id : UInt) -> Unit { + + wasmImportRelease((id).reinterpret_as_int()); + +} +///| +/// Draw a frame into the host framebuffer. +pub fn submit(f : Frame) -> Unit { + let cleanup_list : Array[Int] = [] + + let (lowered, lowered8, lowered9) = match ((f).wallpaper) { + None => { + + ((0), 0, 0) + } + Some(payload0) => { + + let address = mbt_ffi_malloc((payload0).length() * 32); + for index = 0; index < (payload0).length(); index = index + 1 { + let iter_elem : Op = (payload0)[(index)] + let iter_base = address + (index * 32); + + match iter_elem { + FillRect(payload1) => { + mbt_ffi_store8((iter_base) + 0, (0)) + mbt_ffi_store32((iter_base) + 4, ((payload1).area).x) + mbt_ffi_store32((iter_base) + 8, ((payload1).area).y) + mbt_ffi_store32((iter_base) + 12, ((payload1).area).w) + mbt_ffi_store32((iter_base) + 16, ((payload1).area).h) + mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload1).radius) + + () + } + StrokeRect(payload2) => { + mbt_ffi_store8((iter_base) + 0, (1)) + mbt_ffi_store32((iter_base) + 4, ((payload2).area).x) + mbt_ffi_store32((iter_base) + 8, ((payload2).area).y) + mbt_ffi_store32((iter_base) + 12, ((payload2).area).w) + mbt_ffi_store32((iter_base) + 16, ((payload2).area).h) + mbt_ffi_store8((iter_base) + 20, (((payload2).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload2).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload2).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload2).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload2).width) + mbt_ffi_store32((iter_base) + 28, (payload2).radius) + + () + } + DrawLine(payload3) => { + mbt_ffi_store8((iter_base) + 0, (2)) + mbt_ffi_store32((iter_base) + 4, (payload3).x0) + mbt_ffi_store32((iter_base) + 8, (payload3).y0) + mbt_ffi_store32((iter_base) + 12, (payload3).x1) + mbt_ffi_store32((iter_base) + 16, (payload3).y1) + mbt_ffi_store8((iter_base) + 20, (((payload3).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload3).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload3).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload3).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload3).width) + + () + } + DrawCircle(payload4) => { + mbt_ffi_store8((iter_base) + 0, (3)) + mbt_ffi_store32((iter_base) + 4, (payload4).cx) + mbt_ffi_store32((iter_base) + 8, (payload4).cy) + mbt_ffi_store32((iter_base) + 12, (payload4).radius) + mbt_ffi_store8((iter_base) + 16, (((payload4).color).r).to_int()) + mbt_ffi_store8((iter_base) + 17, (((payload4).color).g).to_int()) + mbt_ffi_store8((iter_base) + 18, (((payload4).color).b).to_int()) + mbt_ffi_store8((iter_base) + 19, (((payload4).color).a).to_int()) + mbt_ffi_store8((iter_base) + 20, (if (payload4).filled { 1 } else { 0 })) + + () + } + DrawText(payload5) => { + mbt_ffi_store8((iter_base) + 0, (4)) + mbt_ffi_store32((iter_base) + 4, (payload5).x) + mbt_ffi_store32((iter_base) + 8, (payload5).y) + + let ptr = mbt_ffi_str2ptr((payload5).text) + mbt_ffi_store32((iter_base) + 16, (payload5).text.length()) + mbt_ffi_store32((iter_base) + 12, ptr) + mbt_ffi_store32((iter_base) + 20, (payload5).size) + mbt_ffi_store8((iter_base) + 24, (((payload5).color).r).to_int()) + mbt_ffi_store8((iter_base) + 25, (((payload5).color).g).to_int()) + mbt_ffi_store8((iter_base) + 26, (((payload5).color).b).to_int()) + mbt_ffi_store8((iter_base) + 27, (((payload5).color).a).to_int()) + mbt_ffi_store8((iter_base) + 28, ((payload5).align).to_int()) + mbt_ffi_store8((iter_base) + 29, (if (payload5).bold { 1 } else { 0 })) + mbt_ffi_store8((iter_base) + 30, (if (payload5).mono { 1 } else { 0 })) + cleanup_list.push(ptr) + + () + } + PushClip(payload6) => { + mbt_ffi_store8((iter_base) + 0, (5)) + mbt_ffi_store32((iter_base) + 4, (payload6).x) + mbt_ffi_store32((iter_base) + 8, (payload6).y) + mbt_ffi_store32((iter_base) + 12, (payload6).w) + mbt_ffi_store32((iter_base) + 16, (payload6).h) + + () + } + PopClip => { + mbt_ffi_store8((iter_base) + 0, (6)) + + () + } + } + + } + cleanup_list.push(address) + + ((1), address, (payload0).length()) + } + } + + let address18 = mbt_ffi_malloc(((f).background).length() * 32); + for index19 = 0; index19 < ((f).background).length(); index19 = index19 + 1 { + let iter_elem : Op = ((f).background)[(index19)] + let iter_base = address18 + (index19 * 32); + + match iter_elem { + FillRect(payload10) => { + mbt_ffi_store8((iter_base) + 0, (0)) + mbt_ffi_store32((iter_base) + 4, ((payload10).area).x) + mbt_ffi_store32((iter_base) + 8, ((payload10).area).y) + mbt_ffi_store32((iter_base) + 12, ((payload10).area).w) + mbt_ffi_store32((iter_base) + 16, ((payload10).area).h) + mbt_ffi_store8((iter_base) + 20, (((payload10).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload10).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload10).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload10).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload10).radius) + + () + } + StrokeRect(payload11) => { + mbt_ffi_store8((iter_base) + 0, (1)) + mbt_ffi_store32((iter_base) + 4, ((payload11).area).x) + mbt_ffi_store32((iter_base) + 8, ((payload11).area).y) + mbt_ffi_store32((iter_base) + 12, ((payload11).area).w) + mbt_ffi_store32((iter_base) + 16, ((payload11).area).h) + mbt_ffi_store8((iter_base) + 20, (((payload11).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload11).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload11).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload11).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload11).width) + mbt_ffi_store32((iter_base) + 28, (payload11).radius) + + () + } + DrawLine(payload12) => { + mbt_ffi_store8((iter_base) + 0, (2)) + mbt_ffi_store32((iter_base) + 4, (payload12).x0) + mbt_ffi_store32((iter_base) + 8, (payload12).y0) + mbt_ffi_store32((iter_base) + 12, (payload12).x1) + mbt_ffi_store32((iter_base) + 16, (payload12).y1) + mbt_ffi_store8((iter_base) + 20, (((payload12).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload12).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload12).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload12).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload12).width) + + () + } + DrawCircle(payload13) => { + mbt_ffi_store8((iter_base) + 0, (3)) + mbt_ffi_store32((iter_base) + 4, (payload13).cx) + mbt_ffi_store32((iter_base) + 8, (payload13).cy) + mbt_ffi_store32((iter_base) + 12, (payload13).radius) + mbt_ffi_store8((iter_base) + 16, (((payload13).color).r).to_int()) + mbt_ffi_store8((iter_base) + 17, (((payload13).color).g).to_int()) + mbt_ffi_store8((iter_base) + 18, (((payload13).color).b).to_int()) + mbt_ffi_store8((iter_base) + 19, (((payload13).color).a).to_int()) + mbt_ffi_store8((iter_base) + 20, (if (payload13).filled { 1 } else { 0 })) + + () + } + DrawText(payload14) => { + mbt_ffi_store8((iter_base) + 0, (4)) + mbt_ffi_store32((iter_base) + 4, (payload14).x) + mbt_ffi_store32((iter_base) + 8, (payload14).y) + + let ptr15 = mbt_ffi_str2ptr((payload14).text) + mbt_ffi_store32((iter_base) + 16, (payload14).text.length()) + mbt_ffi_store32((iter_base) + 12, ptr15) + mbt_ffi_store32((iter_base) + 20, (payload14).size) + mbt_ffi_store8((iter_base) + 24, (((payload14).color).r).to_int()) + mbt_ffi_store8((iter_base) + 25, (((payload14).color).g).to_int()) + mbt_ffi_store8((iter_base) + 26, (((payload14).color).b).to_int()) + mbt_ffi_store8((iter_base) + 27, (((payload14).color).a).to_int()) + mbt_ffi_store8((iter_base) + 28, ((payload14).align).to_int()) + mbt_ffi_store8((iter_base) + 29, (if (payload14).bold { 1 } else { 0 })) + mbt_ffi_store8((iter_base) + 30, (if (payload14).mono { 1 } else { 0 })) + cleanup_list.push(ptr15) + + () + } + PushClip(payload16) => { + mbt_ffi_store8((iter_base) + 0, (5)) + mbt_ffi_store32((iter_base) + 4, (payload16).x) + mbt_ffi_store32((iter_base) + 8, (payload16).y) + mbt_ffi_store32((iter_base) + 12, (payload16).w) + mbt_ffi_store32((iter_base) + 16, (payload16).h) + + () + } + PopClip => { + mbt_ffi_store8((iter_base) + 0, (6)) + + () + } + } + + } + + let address30 = mbt_ffi_malloc(((f).windows).length() * 48); + for index31 = 0; index31 < ((f).windows).length(); index31 = index31 + 1 { + let iter_elem : Window = ((f).windows)[(index31)] + let iter_base = address30 + (index31 * 48); + mbt_ffi_store32((iter_base) + 0, ((iter_elem).geometry).x) + mbt_ffi_store32((iter_base) + 4, ((iter_elem).geometry).y) + mbt_ffi_store32((iter_base) + 8, ((iter_elem).geometry).w) + mbt_ffi_store32((iter_base) + 12, ((iter_elem).geometry).h) + mbt_ffi_store32((iter_base) + 16, (iter_elem).inset_top) + mbt_ffi_store32((iter_base) + 20, (iter_elem).inset_right) + mbt_ffi_store32((iter_base) + 24, (iter_elem).inset_bottom) + mbt_ffi_store32((iter_base) + 28, (iter_elem).inset_left) + + let address28 = mbt_ffi_malloc(((iter_elem).deco).length() * 32); + for index29 = 0; index29 < ((iter_elem).deco).length(); index29 = index29 + 1 { + let iter_elem : Op = ((iter_elem).deco)[(index29)] + let iter_base = address28 + (index29 * 32); + + match iter_elem { + FillRect(payload20) => { + mbt_ffi_store8((iter_base) + 0, (0)) + mbt_ffi_store32((iter_base) + 4, ((payload20).area).x) + mbt_ffi_store32((iter_base) + 8, ((payload20).area).y) + mbt_ffi_store32((iter_base) + 12, ((payload20).area).w) + mbt_ffi_store32((iter_base) + 16, ((payload20).area).h) + mbt_ffi_store8((iter_base) + 20, (((payload20).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload20).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload20).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload20).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload20).radius) + + () + } + StrokeRect(payload21) => { + mbt_ffi_store8((iter_base) + 0, (1)) + mbt_ffi_store32((iter_base) + 4, ((payload21).area).x) + mbt_ffi_store32((iter_base) + 8, ((payload21).area).y) + mbt_ffi_store32((iter_base) + 12, ((payload21).area).w) + mbt_ffi_store32((iter_base) + 16, ((payload21).area).h) + mbt_ffi_store8((iter_base) + 20, (((payload21).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload21).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload21).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload21).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload21).width) + mbt_ffi_store32((iter_base) + 28, (payload21).radius) + + () + } + DrawLine(payload22) => { + mbt_ffi_store8((iter_base) + 0, (2)) + mbt_ffi_store32((iter_base) + 4, (payload22).x0) + mbt_ffi_store32((iter_base) + 8, (payload22).y0) + mbt_ffi_store32((iter_base) + 12, (payload22).x1) + mbt_ffi_store32((iter_base) + 16, (payload22).y1) + mbt_ffi_store8((iter_base) + 20, (((payload22).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload22).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload22).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload22).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload22).width) + + () + } + DrawCircle(payload23) => { + mbt_ffi_store8((iter_base) + 0, (3)) + mbt_ffi_store32((iter_base) + 4, (payload23).cx) + mbt_ffi_store32((iter_base) + 8, (payload23).cy) + mbt_ffi_store32((iter_base) + 12, (payload23).radius) + mbt_ffi_store8((iter_base) + 16, (((payload23).color).r).to_int()) + mbt_ffi_store8((iter_base) + 17, (((payload23).color).g).to_int()) + mbt_ffi_store8((iter_base) + 18, (((payload23).color).b).to_int()) + mbt_ffi_store8((iter_base) + 19, (((payload23).color).a).to_int()) + mbt_ffi_store8((iter_base) + 20, (if (payload23).filled { 1 } else { 0 })) + + () + } + DrawText(payload24) => { + mbt_ffi_store8((iter_base) + 0, (4)) + mbt_ffi_store32((iter_base) + 4, (payload24).x) + mbt_ffi_store32((iter_base) + 8, (payload24).y) + + let ptr25 = mbt_ffi_str2ptr((payload24).text) + mbt_ffi_store32((iter_base) + 16, (payload24).text.length()) + mbt_ffi_store32((iter_base) + 12, ptr25) + mbt_ffi_store32((iter_base) + 20, (payload24).size) + mbt_ffi_store8((iter_base) + 24, (((payload24).color).r).to_int()) + mbt_ffi_store8((iter_base) + 25, (((payload24).color).g).to_int()) + mbt_ffi_store8((iter_base) + 26, (((payload24).color).b).to_int()) + mbt_ffi_store8((iter_base) + 27, (((payload24).color).a).to_int()) + mbt_ffi_store8((iter_base) + 28, ((payload24).align).to_int()) + mbt_ffi_store8((iter_base) + 29, (if (payload24).bold { 1 } else { 0 })) + mbt_ffi_store8((iter_base) + 30, (if (payload24).mono { 1 } else { 0 })) + cleanup_list.push(ptr25) + + () + } + PushClip(payload26) => { + mbt_ffi_store8((iter_base) + 0, (5)) + mbt_ffi_store32((iter_base) + 4, (payload26).x) + mbt_ffi_store32((iter_base) + 8, (payload26).y) + mbt_ffi_store32((iter_base) + 12, (payload26).w) + mbt_ffi_store32((iter_base) + 16, (payload26).h) + + () + } + PopClip => { + mbt_ffi_store8((iter_base) + 0, (6)) + + () + } + } + + } + mbt_ffi_store32((iter_base) + 36, ((iter_elem).deco).length()) + mbt_ffi_store32((iter_base) + 32, address28) + mbt_ffi_store8((iter_base) + 40, (if (iter_elem).fullscreen { 1 } else { 0 })) + mbt_ffi_store32((iter_base) + 44, ((iter_elem).surface).reinterpret_as_int()) + cleanup_list.push(address28) + + } + + let address40 = mbt_ffi_malloc(((f).panel).length() * 32); + for index41 = 0; index41 < ((f).panel).length(); index41 = index41 + 1 { + let iter_elem : Op = ((f).panel)[(index41)] + let iter_base = address40 + (index41 * 32); + + match iter_elem { + FillRect(payload32) => { + mbt_ffi_store8((iter_base) + 0, (0)) + mbt_ffi_store32((iter_base) + 4, ((payload32).area).x) + mbt_ffi_store32((iter_base) + 8, ((payload32).area).y) + mbt_ffi_store32((iter_base) + 12, ((payload32).area).w) + mbt_ffi_store32((iter_base) + 16, ((payload32).area).h) + mbt_ffi_store8((iter_base) + 20, (((payload32).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload32).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload32).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload32).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload32).radius) + + () + } + StrokeRect(payload33) => { + mbt_ffi_store8((iter_base) + 0, (1)) + mbt_ffi_store32((iter_base) + 4, ((payload33).area).x) + mbt_ffi_store32((iter_base) + 8, ((payload33).area).y) + mbt_ffi_store32((iter_base) + 12, ((payload33).area).w) + mbt_ffi_store32((iter_base) + 16, ((payload33).area).h) + mbt_ffi_store8((iter_base) + 20, (((payload33).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload33).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload33).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload33).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload33).width) + mbt_ffi_store32((iter_base) + 28, (payload33).radius) + + () + } + DrawLine(payload34) => { + mbt_ffi_store8((iter_base) + 0, (2)) + mbt_ffi_store32((iter_base) + 4, (payload34).x0) + mbt_ffi_store32((iter_base) + 8, (payload34).y0) + mbt_ffi_store32((iter_base) + 12, (payload34).x1) + mbt_ffi_store32((iter_base) + 16, (payload34).y1) + mbt_ffi_store8((iter_base) + 20, (((payload34).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload34).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload34).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload34).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, (payload34).width) + + () + } + DrawCircle(payload35) => { + mbt_ffi_store8((iter_base) + 0, (3)) + mbt_ffi_store32((iter_base) + 4, (payload35).cx) + mbt_ffi_store32((iter_base) + 8, (payload35).cy) + mbt_ffi_store32((iter_base) + 12, (payload35).radius) + mbt_ffi_store8((iter_base) + 16, (((payload35).color).r).to_int()) + mbt_ffi_store8((iter_base) + 17, (((payload35).color).g).to_int()) + mbt_ffi_store8((iter_base) + 18, (((payload35).color).b).to_int()) + mbt_ffi_store8((iter_base) + 19, (((payload35).color).a).to_int()) + mbt_ffi_store8((iter_base) + 20, (if (payload35).filled { 1 } else { 0 })) + + () + } + DrawText(payload36) => { + mbt_ffi_store8((iter_base) + 0, (4)) + mbt_ffi_store32((iter_base) + 4, (payload36).x) + mbt_ffi_store32((iter_base) + 8, (payload36).y) + + let ptr37 = mbt_ffi_str2ptr((payload36).text) + mbt_ffi_store32((iter_base) + 16, (payload36).text.length()) + mbt_ffi_store32((iter_base) + 12, ptr37) + mbt_ffi_store32((iter_base) + 20, (payload36).size) + mbt_ffi_store8((iter_base) + 24, (((payload36).color).r).to_int()) + mbt_ffi_store8((iter_base) + 25, (((payload36).color).g).to_int()) + mbt_ffi_store8((iter_base) + 26, (((payload36).color).b).to_int()) + mbt_ffi_store8((iter_base) + 27, (((payload36).color).a).to_int()) + mbt_ffi_store8((iter_base) + 28, ((payload36).align).to_int()) + mbt_ffi_store8((iter_base) + 29, (if (payload36).bold { 1 } else { 0 })) + mbt_ffi_store8((iter_base) + 30, (if (payload36).mono { 1 } else { 0 })) + cleanup_list.push(ptr37) + + () + } + PushClip(payload38) => { + mbt_ffi_store8((iter_base) + 0, (5)) + mbt_ffi_store32((iter_base) + 4, (payload38).x) + mbt_ffi_store32((iter_base) + 8, (payload38).y) + mbt_ffi_store32((iter_base) + 12, (payload38).w) + mbt_ffi_store32((iter_base) + 16, (payload38).h) + + () + } + PopClip => { + mbt_ffi_store8((iter_base) + 0, (6)) + + () + } + } + + } + + let address42 = mbt_ffi_malloc(((f).popups).length() * 20); + for index43 = 0; index43 < ((f).popups).length(); index43 = index43 + 1 { + let iter_elem : Popup = ((f).popups)[(index43)] + let iter_base = address42 + (index43 * 20); + mbt_ffi_store32((iter_base) + 0, ((iter_elem).area).x) + mbt_ffi_store32((iter_base) + 4, ((iter_elem).area).y) + mbt_ffi_store32((iter_base) + 8, ((iter_elem).area).w) + mbt_ffi_store32((iter_base) + 12, ((iter_elem).area).h) + mbt_ffi_store32((iter_base) + 16, ((iter_elem).surface).reinterpret_as_int()) + + } + wasmImportSubmit((f).width, (f).height, lowered, lowered8, lowered9, address18, ((f).background).length(), address30, ((f).windows).length(), address40, ((f).panel).length(), address42, ((f).popups).length()); + mbt_ffi_free(address18) + mbt_ffi_free(address30) + mbt_ffi_free(address40) + mbt_ffi_free(address42) + + cleanup_list.each(mbt_ffi_free) + +} +///| +/// The framebuffer as RGBA8888 (for screenshots and tests; the display path never needs it). +pub fn read_frame() -> FixedArray[Byte] { + + let return_area = mbt_ffi_malloc(8) + wasmImportReadFrame(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 + +} +///| +/// A new memfd holding the framebuffer as little-endian ARGB8888, ready to hand to a Wayland +/// compositor as a wl_shm pool. The caller closes it. -1 on failure. +pub fn export_memfd() -> Int { + + let result : Int = wasmImportExportMemfd(); + let ret = result + return ret + +} + diff --git a/interface/moonplasma/host/sys/ffi.mbt b/interface/moonplasma/host/sys/ffi.mbt index d45edee..0ea3b62 100644 --- a/interface/moonplasma/host/sys/ffi.mbt +++ b/interface/moonplasma/host/sys/ffi.mbt @@ -75,6 +75,29 @@ fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int = "moonplasma:host/sys@0.1.0" "ha ///| 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_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) @@ -86,31 +109,8 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = 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) - ///| #owned(bytes) extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = #|(func (param i32) (result i32) local.get 0) -///| -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) - -///| -#owned(str) -extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = -#|(func (param i32) (result i32) local.get 0) - -///| -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) - diff --git a/interface/moonplasma/host/sys/native_stub.mbt b/interface/moonplasma/host/sys/native_stub.mbt index bdd833a..c2dad6c 100644 --- a/interface/moonplasma/host/sys/native_stub.mbt +++ b/interface/moonplasma/host/sys/native_stub.mbt @@ -125,6 +125,26 @@ 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_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") @@ -135,27 +155,7 @@ fn mbt_ffi_free(position : Int) -> Unit { abort("wasm-only") } -///| -fn mbt_ffi_load32(offset : Int) -> Int { - abort("wasm-only") -} - ///| fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { abort("wasm-only") } - -///| -fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { - abort("wasm-only") -} - -///| -fn mbt_ffi_str2ptr(str : String) -> Int { - abort("wasm-only") -} - -///| -fn mbt_ffi_malloc(size : Int) -> Int { - abort("wasm-only") -} diff --git a/wit/host/display.wit b/wit/host/display.wit index 3e6a71e..fa72063 100644 --- a/wit/host/display.wit +++ b/wit/host/display.wit @@ -21,6 +21,8 @@ interface display { frame-ready: func() -> bool; /// Show an RGBA8888 frame of `width` x `height` (it must match the output mode). present: func(pixels: list, width: u32, height: u32); + /// Show the host framebuffer (what `raster.submit` drew) on the output. + present-frame: func(); /// Show the cursor for a wp_cursor_shape_v1 value. set-cursor-shape: func(shape: u32); diff --git a/wit/host/raster.wit b/wit/host/raster.wit new file mode 100644 index 0000000..f5f7c69 --- /dev/null +++ b/wit/host/raster.wit @@ -0,0 +1,62 @@ +package moonplasma:host@0.1.0; + +/// Drawing done by the host. The compositor component decides what the screen shows (windows, +/// panel, wallpaper, decorations) and sends it as a list of draw operations; the host keeps the +/// framebuffer and does the pixel work natively, so no pixels cross the component boundary. Client +/// window buffers are captured here too (a native copy out of the client's shared memory), and the +/// component only holds their ids. +interface raster { + record rect { x: s32, y: s32, w: s32, h: s32 } + record color { r: u8, g: u8, b: u8, a: u8 } + record fill { area: rect, color: color, radius: s32 } + record stroke { area: rect, color: color, width: s32, radius: s32 } + record segment { x0: s32, y0: s32, x1: s32, y1: s32, color: color, width: s32 } + record disc { cx: s32, cy: s32, radius: s32, color: color, filled: bool } + /// `align`: 0 left, 1 centre, 2 right of `x`; `y` is the text's vertical centre. + record label { x: s32, y: s32, text: string, size: s32, color: color, align: u8, bold: bool, mono: bool } + variant op { + fill-rect(fill), + stroke-rect(stroke), + draw-line(segment), + draw-circle(disc), + draw-text(label), + push-clip(rect), + pop-clip, + } + + /// A toplevel: its decoration (drawn at `geometry` minus the insets), then its client surface. + record window { + geometry: rect, + inset-top: s32, + inset-right: s32, + inset-bottom: s32, + inset-left: s32, + deco: list, + fullscreen: bool, + /// A surface id from `capture`; 0 when the client has not committed a buffer. + surface: u32, + } + record popup { area: rect, surface: u32 } + record frame { + width: s32, + height: s32, + /// The static backdrop (wallpaper and desktop card); none means "unchanged since the last submit" (the host keeps its pixels). + wallpaper: option>, + background: list, + windows: list, + panel: list, + popups: list, + } + + /// Copy a client buffer (`stride * height` bytes at `offset` of the file behind `fd`) into a + /// host surface. `format` is the wl_shm format (0 ARGB8888, 1 XRGB8888). 0 on failure. + capture: func(fd: s32, offset: s32, stride: s32, width: s32, height: s32, format: s32) -> u32; + release: func(id: u32); + /// Draw a frame into the host framebuffer. + submit: func(f: frame); + /// The framebuffer as RGBA8888 (for screenshots and tests; the display path never needs it). + read-frame: func() -> list; + /// A new memfd holding the framebuffer as little-endian ARGB8888, ready to hand to a Wayland + /// compositor as a wl_shm pool. The caller closes it. -1 on failure. + export-memfd: func() -> s32; +} diff --git a/wit/host/sys.wit b/wit/host/sys.wit index 160a7ae..02d1863 100644 --- a/wit/host/sys.wit +++ b/wit/host/sys.wit @@ -80,6 +80,7 @@ world compositor { import font; import plasmoids; import display; + import raster; /// Run the compositor until it exits. `args` are the command-line arguments (without argv[0]). export run: func(args: list) -> s32; }