diff --git a/compositor/bin/main.mbt b/compositor/bin/main.mbt new file mode 100644 index 0000000..4d76310 --- /dev/null +++ b/compositor/bin/main.mbt @@ -0,0 +1,48 @@ +///| Standalone native MoonBit Wayland compositor entrypoint. + +///| +fn main { + let args = @env.args() + let mut socket_path = "/tmp/wayland-moon-0" + let mut theme_path = "config/themes/moon-night.json" + let width = 1280 + let height = 720 + + let mut i = 1 + while i < args.length() { + let a = args[i] + if a == "--socket" && i + 1 < args.length() { + socket_path = args[i + 1] + i = i + 2 + } else if a == "--theme" && i + 1 < args.length() { + theme_path = args[i + 1] + i = i + 2 + } else { + i = i + 1 + } + } + + let raw_theme = @sys.read_file_bytes(theme_path) + let theme = if raw_theme.length() > 0 { + let sb = StringBuilder() + for j = 0; j < raw_theme.length(); j = j + 1 { + sb.write_char(Int::unsafe_to_char(raw_theme[j].to_int())) + } + @scene.ThemeTokens::from_json_string(sb.to_string()) + } else { + @scene.ThemeTokens::moon_night() + } + + match @host.MoonPlasmaCompositor::new(socket_path, theme, width, height) { + Some(comp) => { + println("moon-plasma compositor listening on " + socket_path) + while true { + comp.step() + @sys.sleep_ms(16) + } + } + None => { + println("failed to bind Wayland socket at " + socket_path) + } + } +} diff --git a/compositor/bin/moon.pkg b/compositor/bin/moon.pkg new file mode 100644 index 0000000..f89e078 --- /dev/null +++ b/compositor/bin/moon.pkg @@ -0,0 +1,11 @@ +import { + "moonbitlang/core/builtin", + "moonbitlang/core/env", + "moonplasma/desktop/compositor/sys" @sys, + "moonplasma/desktop/compositor/scene" @scene, + "moonplasma/desktop/compositor/host" @host, +} + +supported_targets = "-all+native" + +pkgtype(kind: "executable") diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt new file mode 100644 index 0000000..ccafd65 --- /dev/null +++ b/compositor/host/compositor.mbt @@ -0,0 +1,274 @@ +///| Pure-MoonBit Wayland compositor host wiring WaylandServer, lib/wm, Breeze SSD, SceneGraph, and SoftwareRenderer. + +///| +pub(all) struct HostWindow { + id : UInt64 + mut title : String + mut app_id : String + mut geometry : @scene.Rect + mut focused : Bool + mut maximized : Bool + mut fullscreen : Bool + mut surface : @scene.ShmBufferSnapshot? +} + +///| +pub(all) struct MoonPlasmaCompositor { + server : @wayland.WaylandServer + wm : @wm.WmState + theme : @scene.ThemeTokens + output_w : Int + output_h : Int + work_area : @wm.Rect + windows : Map[UInt64, HostWindow] + damage : @scene.DamageTracker + mut layout_mode : @wm.LayoutMode +} + +///| +pub fn MoonPlasmaCompositor::new( + socket_path : String, + theme : @scene.ThemeTokens, + output_w : Int, + output_h : Int, +) -> MoonPlasmaCompositor? { + let server = match @wayland.WaylandServer::listen(socket_path, output_w, output_h) { + Some(s) => s + None => return None + } + let wm = @wm.WmState::new( + inner_gap=8, + outer_gap=8, + titlebar_h=32, + border_w=2, + ) + let out_rect : @wm.Rect = { x: 0, y: 0, w: output_w, h: output_h } + let work_area = @wm.compute_work_area(out_rect, excl_bottom=theme.panel_height) + Some({ + server, + wm, + theme, + output_w, + output_h, + work_area, + windows: {}, + damage: @scene.DamageTracker::new(), + layout_mode: @wm.LayoutMode::Tiling, + }) +} + +///| +pub fn MoonPlasmaCompositor::close(self : MoonPlasmaCompositor) -> Unit { + self.server.close() +} + +///| +fn MoonPlasmaCompositor::apply_actions( + self : MoonPlasmaCompositor, + actions : Array[@wm.WmAction], +) -> Unit { + for act in actions { + match act { + @wm.WmAction::SetGeometry(wid, r) => + match self.windows.get(wid) { + Some(win) => { + win.geometry = @scene.Rect::new(r.x, r.y, r.w, r.h) + self.server.send_toplevel_configure( + wid, + r.w, + r.h, + win.focused, + win.maximized, + win.fullscreen, + ) + self.damage.mark_full() + } + None => () + } + @wm.WmAction::Focus(wid) => { + for id, w in self.windows { + w.focused = id == wid + } + self.damage.mark_full() + } + @wm.WmAction::Raise(_) => self.damage.mark_full() + @wm.WmAction::Close(wid) => self.server.send_toplevel_close(wid) + @wm.WmAction::SetMaximized(wid, m) => + match self.windows.get(wid) { + Some(win) => win.maximized = m + None => () + } + @wm.WmAction::SetFullscreen(wid, f) => + match self.windows.get(wid) { + Some(win) => win.fullscreen = f + None => () + } + } + } +} + +///| +pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit { + let events = self.server.poll_events() + for ev in events { + match ev { + @wayland.CompositorEvent::ToplevelOpened(wid, app_id, title, min_w, min_h) => { + let win : HostWindow = { + id: wid, + title, + app_id, + geometry: @scene.Rect::new(100, 100, 640, 480), + focused: true, + maximized: false, + fullscreen: false, + surface: None, + } + self.windows.set(wid, win) + let rec : @wm.WindowRecord = { + id: wid, + app_id, + title, + geometry: { x: 100, y: 100, w: 640, h: 480 }, + floating_geometry: { x: 100, y: 100, w: 640, h: 480 }, + min_size: { w: min_w, h: min_h }, + max_size: None, + focused: true, + maximized: false, + fullscreen: false, + minimized: false, + is_floating: false, + workspace: 0U, + can_move: true, + can_resize: true, + can_maximize: true, + can_minimize: true, + can_fullscreen: true, + } + let actions = self.wm.open_window(rec, self.work_area) + self.apply_actions(actions) + } + @wayland.CompositorEvent::ToplevelUpdated(wid, app_id, title) => + match self.windows.get(wid) { + Some(win) => { + if app_id.length() > 0 { + win.app_id = app_id + } + if title.length() > 0 { + win.title = title + } + self.damage.mark_full() + } + None => () + } + @wayland.CompositorEvent::ToplevelCommitted(wid, snap) => + match self.windows.get(wid) { + Some(win) => { + match snap { + Some(s) => { + win.surface = Some(s) + self.damage.mark_rect(win.geometry) + } + None => () + } + } + None => () + } + @wayland.CompositorEvent::ToplevelClosed(wid) => { + ignore(self.windows.remove(wid)) + let actions = self.wm.close_window(wid, self.work_area) + self.apply_actions(actions) + } + @wayland.CompositorEvent::ToplevelMaximizeRequest(wid, m) => { + let actions = self.wm.handle_request( + wid, + @wm.WindowRequest::Maximize(m), + self.work_area, + ) + self.apply_actions(actions) + } + @wayland.CompositorEvent::ToplevelFullscreenRequest(wid, f) => { + let actions = self.wm.handle_request( + wid, + @wm.WindowRequest::Fullscreen(f), + self.work_area, + ) + self.apply_actions(actions) + } + @wayland.CompositorEvent::ToplevelMinimizeRequest(wid, m) => { + let actions = self.wm.handle_request( + wid, + @wm.WindowRequest::Minimize(m), + self.work_area, + ) + self.apply_actions(actions) + } + @wayland.CompositorEvent::ToplevelMoveRequest(_) => () + } + } +} + +///| +pub fn MoonPlasmaCompositor::set_layout_mode( + self : MoonPlasmaCompositor, + mode : @wm.LayoutMode, +) -> Unit { + self.layout_mode = mode + let actions = self.wm.set_layout_mode(mode, self.work_area) + self.apply_actions(actions) +} + +///| +pub fn MoonPlasmaCompositor::compose_frame( + self : MoonPlasmaCompositor, +) -> @renderer.Pixmap { + let scene = @scene.SceneGraph::new(self.output_w, self.output_h) + let order = self.wm.stacking_order() + let titles : Array[String] = [] + + for wid in order { + match self.windows.get(wid) { + Some(win) => { + let label = if win.title.length() > 0 { win.title } else { win.app_id } + titles.push(label) + let (insets, deco_ops) = @scene.build_breeze_decoration( + win.title, + win.app_id, + win.focused, + win.fullscreen, + win.geometry.w + 4, + win.geometry.h + 34, + self.theme, + ) + scene.windows.push({ + id: win.id, + title: win.title, + app_id: win.app_id, + focused: win.focused, + fullscreen: win.fullscreen, + geometry: win.geometry, + deco_insets: insets, + deco_ops, + surface: win.surface, + }) + } + None => () + } + } + + let layout_label = match self.layout_mode { + @wm.LayoutMode::Tiling => "BSP Tiling" + @wm.LayoutMode::Floating => "Floating" + @wm.LayoutMode::Monocle => "Monocle" + } + let (bg_ops, panel_ops) = @scene.build_shell_ops( + self.output_w, + self.output_h, + self.theme, + layout_label, + titles, + ) + scene.background_ops = bg_ops + scene.panel_ops = panel_ops + ignore(self.damage.take_damage(self.output_w, self.output_h)) + @renderer.render_scene(scene) +} diff --git a/compositor/host/e2e_test.mbt b/compositor/host/e2e_test.mbt new file mode 100644 index 0000000..5867afc --- /dev/null +++ b/compositor/host/e2e_test.mbt @@ -0,0 +1,358 @@ +///| End-to-end native Wayland compositor test in pure MoonBit. +///| Connects real Wayland wire-protocol clients with SCM_RIGHTS wl_shm memfds, +///| verifies ServerSide decoration negotiation, lib/wm BSP tiling & Floating switch, +///| and composited pixel + PNG output. + +///| +struct TestWaylandClient { + fd : Int + mut next_id : UInt + rx_buf : Array[Byte] + globals : Map[String, (UInt, UInt)] + mut deco_mode : UInt? + mut configured_w : Int + mut configured_h : Int + mut configure_serial : UInt? +} + +///| +fn TestWaylandClient::connect(socket_path : String) -> TestWaylandClient? { + let fd = @sys.unix_connect(socket_path) + if fd < 0 { + return None + } + Some({ + fd, + next_id: 2U, + rx_buf: [], + globals: {}, + deco_mode: None, + configured_w: 0, + configured_h: 0, + configure_serial: None, + }) +} + +///| +fn TestWaylandClient::alloc_id(self : TestWaylandClient) -> UInt { + let id = self.next_id + self.next_id = self.next_id + 1U + id +} + +///| +fn TestWaylandClient::send( + self : TestWaylandClient, + msg : Bytes, + send_fd? : Int = -1, +) -> Unit { + ignore(@sys.sendmsg_fd(self.fd, msg, send_fd)) +} + +///| +fn TestWaylandClient::read_events( + self : TestWaylandClient, + xdg_surf_id : UInt, + toplevel_id : UInt, + deco_id : UInt, +) -> Unit { + let scratch : FixedArray[Byte] = FixedArray::make(8192, b'\x00') + while @sys.poll_read(self.fd, 5) > 0 { + let (n, rfd) = @sys.recvmsg_fd(self.fd, scratch, 8192) + if rfd >= 0 { + @sys.close_fd(rfd) + } + if n <= 0 { + break + } + for i = 0; i < n; i = i + 1 { + self.rx_buf.push(scratch[i]) + } + } + let mut off = 0 + while off + 8 <= self.rx_buf.length() { + let obj_id = @wayland.read_u32_le(self.rx_buf, off) + let word2 = @wayland.read_u32_le(self.rx_buf, off + 4) + let size = ((word2 >> 16) & 0xFFFFU).reinterpret_as_int() + let opcode = word2 & 0xFFFFU + if size < 8 || off + size > self.rx_buf.length() { + break + } + let reader = @wayland.WireReader::from_array(self.rx_buf, off + 8) + if obj_id == 2U && opcode == 0U { + // wl_registry.global(name, interface, version) + let name = reader.u32() + let iface = reader.str() + let ver = reader.u32() + self.globals.set(iface, (name, ver)) + } else if obj_id == deco_id && opcode == 0U { + // zxdg_toplevel_decoration_v1.configure(mode) + self.deco_mode = Some(reader.u32()) + } else if obj_id == toplevel_id && opcode == 0U { + // xdg_toplevel.configure(width, height, states) + let w = reader.i32() + let h = reader.i32() + let _states = reader.array() + if w > 0 && h > 0 { + self.configured_w = w + self.configured_h = h + } + } else if obj_id == xdg_surf_id && opcode == 0U { + // xdg_surface.configure(serial) + self.configure_serial = Some(reader.u32()) + } + off = off + size + } + if off > 0 { + let rem : Array[Byte] = [] + for i = off; i < self.rx_buf.length(); i = i + 1 { + rem.push(self.rx_buf[i]) + } + self.rx_buf.clear() + for b in rem { + self.rx_buf.push(b) + } + } +} + +///| +fn bind_global( + c : TestWaylandClient, + reg_id : UInt, + iface : String, + ver : UInt, +) -> UInt { + let (name, adv_ver) = match c.globals.get(iface) { + Some(v) => v + None => (0U, ver) + } + let use_ver = if ver < adv_ver { ver } else { adv_ver } + let id = c.alloc_id() + let w = @wayland.WireWriter::new() + w.u32(name) + w.str(iface) + w.u32(use_ver) + w.u32(id) + c.send(w.finish_msg(reg_id, 0U)) + id +} + +///| +fn open_and_configure_client( + comp : @host.MoonPlasmaCompositor, + socket_path : String, + title : String, + app_id : String, +) -> (TestWaylandClient, UInt, UInt, UInt, UInt, UInt) { + let c = TestWaylandClient::connect(socket_path).unwrap() + // 1. wl_display.get_registry(id=2) + let reg_id = c.alloc_id() // 2 + let w_reg = @wayland.WireWriter::new() + w_reg.u32(reg_id) + c.send(w_reg.finish_msg(1U, 1U)) + + for _i = 0; _i < 10; _i = _i + 1 { + comp.step() + c.read_events(0U, 0U, 0U) + if c.globals.contains("zxdg_decoration_manager_v1") { + break + } + @sys.sleep_ms(2) + } + + let comp_id = bind_global(c, reg_id, "wl_compositor", 5U) + let shm_id = bind_global(c, reg_id, "wl_shm", 1U) + let xdg_wm_id = bind_global(c, reg_id, "xdg_wm_base", 5U) + let deco_mgr_id = bind_global(c, reg_id, "zxdg_decoration_manager_v1", 1U) + + // create_surface + let surf_id = c.alloc_id() + let w_cs = @wayland.WireWriter::new() + w_cs.u32(surf_id) + c.send(w_cs.finish_msg(comp_id, 0U)) + + // get_xdg_surface + let xdg_surf_id = c.alloc_id() + let w_xs = @wayland.WireWriter::new() + w_xs.u32(xdg_surf_id) + w_xs.u32(surf_id) + c.send(w_xs.finish_msg(xdg_wm_id, 2U)) + + // get_toplevel + let toplevel_id = c.alloc_id() + let w_tl = @wayland.WireWriter::new() + w_tl.u32(toplevel_id) + c.send(w_tl.finish_msg(xdg_surf_id, 1U)) + + // set_title & set_app_id + let w_t = @wayland.WireWriter::new() + w_t.str(title) + c.send(w_t.finish_msg(toplevel_id, 2U)) + let w_a = @wayland.WireWriter::new() + w_a.str(app_id) + c.send(w_a.finish_msg(toplevel_id, 3U)) + + // get_toplevel_decoration + let deco_id = c.alloc_id() + let w_dc = @wayland.WireWriter::new() + w_dc.u32(deco_id) + w_dc.u32(toplevel_id) + c.send(w_dc.finish_msg(deco_mgr_id, 1U)) + + // initial commit + let w_cm = @wayland.WireWriter::new() + c.send(w_cm.finish_msg(surf_id, 6U)) + + for _i = 0; _i < 20; _i = _i + 1 { + comp.step() + c.read_events(xdg_surf_id, toplevel_id, deco_id) + if c.configure_serial is Some(_) && c.configured_w > 0 { + break + } + @sys.sleep_ms(2) + } + + (c, shm_id, surf_id, xdg_surf_id, toplevel_id, deco_id) +} + +///| +fn commit_shm_frame( + comp : @host.MoonPlasmaCompositor, + c : TestWaylandClient, + shm_id : UInt, + surf_id : UInt, + xdg_surf_id : UInt, + win_id : UInt64, +) -> Unit raise { + match c.configure_serial { + Some(ser) => { + let w_ack = @wayland.WireWriter::new() + w_ack.u32(ser) + c.send(w_ack.finish_msg(xdg_surf_id, 4U)) + } + None => () + } + let w = c.configured_w + let h = c.configured_h + let stride = w * 4 + let byte_len = stride * h + + let pixels : Array[Byte] = Array(capacity=byte_len) + for y = 0; y < h; y = y + 1 { + for x = 0; x < w; x = x + 1 { + let in_center = (x - w / 2).abs() < 40 && (y - h / 2).abs() < 40 + // Little-endian ARGB8888: [B, G, R, A] + if in_center { + pixels.push(b'\xf8') + pixels.push(b'\xbd') + pixels.push(b'\x38') + pixels.push(b'\xff') + } else { + pixels.push(b'\x3b') + pixels.push(b'\x29') + pixels.push(b'\x1e') + pixels.push(b'\xff') + } + } + } + let memfd = @sys.memfd_create("wl-shm-test", byte_len) + assert_true(memfd >= 0) + ignore(@sys.pwrite_bytes(memfd, Bytes::from_array(pixels), 0)) + + // wl_shm.create_pool(id, size) with SCM_RIGHTS memfd + let pool_id = c.alloc_id() + let w_pool = @wayland.WireWriter::new() + w_pool.u32(pool_id) + w_pool.i32(byte_len) + c.send(w_pool.finish_msg(shm_id, 0U), send_fd=memfd) + @sys.close_fd(memfd) + + // wl_shm_pool.create_buffer(id, offset, w, h, stride, format=0 ARGB8888) + let buf_id = c.alloc_id() + let w_buf = @wayland.WireWriter::new() + w_buf.u32(buf_id) + w_buf.i32(0) + w_buf.i32(w) + w_buf.i32(h) + w_buf.i32(stride) + w_buf.u32(0U) + c.send(w_buf.finish_msg(pool_id, 0U)) + + // wl_surface.attach(buf, 0, 0) + damage_buffer + commit + let w_att = @wayland.WireWriter::new() + w_att.u32(buf_id) + w_att.i32(0) + w_att.i32(0) + c.send(w_att.finish_msg(surf_id, 1U)) + + let w_dmg = @wayland.WireWriter::new() + w_dmg.i32(0) + w_dmg.i32(0) + w_dmg.i32(w) + w_dmg.i32(h) + c.send(w_dmg.finish_msg(surf_id, 9U)) + + let w_cmt = @wayland.WireWriter::new() + c.send(w_cmt.finish_msg(surf_id, 6U)) + + for _i = 0; _i < 20; _i = _i + 1 { + comp.step() + match comp.windows.get(win_id) { + Some(win) => if win.surface is Some(_) { break } + None => () + } + @sys.sleep_ms(2) + } +} + +///| +test "e2e pure-moonbit wayland compositor with lib/wm, ssd decorations, and shm blitting" { + let socket_path = "/tmp/wayland-moon-e2e-" + + @sys.getpid().to_string() + + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap() + + // Client 1: MoonTerm + let (c1, shm1, surf1, xdg1, _tl1, _deco1) = open_and_configure_client( + comp, socket_path, "MoonTerm", "org.moonplasma.term", + ) + assert_eq(c1.deco_mode, Some(2U)) // ServerSide + assert_true(c1.configured_w > 1200 && c1.configured_h > 600) + + commit_shm_frame(comp, c1, shm1, surf1, xdg1, 1UL) + let pixmap = comp.compose_frame() + + // Save PNG and verify PNG signature + let png_bytes = @renderer.encode_png(pixmap) + assert_true(png_bytes.length() > 100) + assert_eq(png_bytes[0], b'\x89') + assert_eq(png_bytes[1], b'\x50') + assert_eq(png_bytes[2], b'\x4e') + assert_eq(png_bytes[3], b'\x47') + assert_eq(@sys.write_file_bytes("_build/e2e_frame.png", png_bytes), 0) + + // Verify cyan (#38bdf8) center pixel landed inside WM-assigned geometry! + let win1 = comp.windows.get(1UL).unwrap() + let cx = win1.geometry.x + win1.geometry.w / 2 + let cy = win1.geometry.y + win1.geometry.h / 2 + let px = pixmap.pixel(cx, cy).unwrap() + assert_eq(px, @scene.Rgba::new(0x38, 0xbd, 0xf8, 0xff)) + + // Client 2: Files -> verify BSP tiling splits the screen! + let (c2, shm2, surf2, xdg2, _tl2, _deco2) = open_and_configure_client( + comp, socket_path, "Files", "org.moonplasma.files", + ) + assert_true(c2.configured_w > 0 && c2.configured_w < 700) + commit_shm_frame(comp, c2, shm2, surf2, xdg2, 2UL) + + // Switch to Floating layout mode and compose + comp.set_layout_mode(@wm.LayoutMode::Floating) + let float_pixmap = comp.compose_frame() + assert_eq(float_pixmap.width, 1280) + assert_eq(float_pixmap.height, 720) + + @sys.close_fd(c1.fd) + @sys.close_fd(c2.fd) + comp.close() +} diff --git a/compositor/host/moon.pkg b/compositor/host/moon.pkg new file mode 100644 index 0000000..f7e5889 --- /dev/null +++ b/compositor/host/moon.pkg @@ -0,0 +1,10 @@ +import { + "moonbitlang/core/builtin", + "moonplasma/desktop/lib/wm" @wm, + "moonplasma/desktop/compositor/sys" @sys, + "moonplasma/desktop/compositor/scene" @scene, + "moonplasma/desktop/compositor/renderer" @renderer, + "moonplasma/desktop/compositor/wayland" @wayland, +} + +supported_targets = "-all+native" diff --git a/compositor/renderer/moon.pkg b/compositor/renderer/moon.pkg new file mode 100644 index 0000000..39228ae --- /dev/null +++ b/compositor/renderer/moon.pkg @@ -0,0 +1,4 @@ +import { + "moonbitlang/core/builtin", + "moonplasma/desktop/compositor/scene" @scene, +} diff --git a/compositor/renderer/pkg.generated.mbti b/compositor/renderer/pkg.generated.mbti new file mode 100644 index 0000000..bf148ac --- /dev/null +++ b/compositor/renderer/pkg.generated.mbti @@ -0,0 +1,32 @@ +// Generated using `moon info`, DON'T EDIT IT +package "moonplasma/desktop/compositor/renderer" + +import { + "moonplasma/desktop/compositor/scene", +} + +// Values +pub fn blit_shm_surface(Pixmap, @scene.ShmBufferSnapshot, @scene.Rect) -> Unit + +pub fn draw_ops(Pixmap, Array[@scene.DrawOp], Int32, Int32) -> Unit + +pub fn encode_png(Pixmap) -> Bytes + +pub fn encode_ppm(Pixmap) -> Bytes + +pub fn render_scene(@scene.SceneGraph) -> Pixmap + +// Errors + +// Types and methods +pub(all) struct Pixmap { + width : Int32 + height : Int32 + data : FixedArray[Byte] +} +pub fn Pixmap::new(Int32, Int32) -> Self +pub fn Pixmap::pixel(Self, Int32, Int32) -> @scene.Rgba? + +// Type aliases + +// Traits diff --git a/compositor/renderer/renderer.mbt b/compositor/renderer/renderer.mbt new file mode 100644 index 0000000..8d3bca0 --- /dev/null +++ b/compositor/renderer/renderer.mbt @@ -0,0 +1,668 @@ +///| Pure MoonBit ARGB8888/RGBA8888 software rasterizer, wl_shm blitter, and PNG/PPM encoder. + +///| +pub(all) struct Pixmap { + width : Int + height : Int + /// RGBA8888 byte buffer (4 bytes per pixel: R, G, B, A) + data : FixedArray[Byte] +} + +///| +pub fn Pixmap::new(width : Int, height : Int) -> Pixmap { + let w = if width < 1 { 1 } else { width } + let h = if height < 1 { 1 } else { height } + { width: w, height: h, data: FixedArray::make(w * h * 4, b'\x00') } +} + +///| +pub fn Pixmap::pixel(self : Pixmap, x : Int, y : Int) -> @scene.Rgba? { + if x < 0 || y < 0 || x >= self.width || y >= self.height { + return None + } + let off = (y * self.width + x) * 4 + Some({ + r: self.data[off], + g: self.data[off + 1], + b: self.data[off + 2], + a: self.data[off + 3], + }) +} + +///| +fn blend_pixel( + dst : Pixmap, + x : Int, + y : Int, + r : Int, + g : Int, + b : Int, + a : Int, + clip : @scene.Rect?, +) -> Unit { + if x < 0 || y < 0 || x >= dst.width || y >= dst.height || a <= 0 { + return + } + match clip { + Some(c) => + if x < c.x || y < c.y || x >= c.x + c.w || y >= c.y + c.h { + return + } + None => () + } + let off = (y * dst.width + x) * 4 + if a >= 255 { + dst.data[off] = r.to_byte() + dst.data[off + 1] = g.to_byte() + dst.data[off + 2] = b.to_byte() + dst.data[off + 3] = b'\xff' + return + } + let inv = 255 - a + let dr = dst.data[off].to_int() + let dg = dst.data[off + 1].to_int() + let db = dst.data[off + 2].to_int() + let da = dst.data[off + 3].to_int() + dst.data[off] = ((r * a + dr * inv + 127) / 255).to_byte() + dst.data[off + 1] = ((g * a + dg * inv + 127) / 255).to_byte() + dst.data[off + 2] = ((b * a + db * inv + 127) / 255).to_byte() + dst.data[off + 3] = (a + (da * inv + 127) / 255).clamp(min=0, max=255).to_byte() +} + +///| +fn in_rounded_rect( + px : Int, + py : Int, + rx : Int, + ry : Int, + rw : Int, + rh : Int, + rad : Int, +) -> Bool { + if px < rx || py < ry || px >= rx + rw || py >= ry + rh { + return false + } + if rad <= 0 { + return true + } + let max_r = (if rw < rh { rw } else { rh }) / 2 + let r = if rad > max_r { max_r } else { rad } + if r <= 0 { + return true + } + let x_left = rx + r + let x_right = rx + rw - r - 1 + let y_top = ry + r + let y_bot = ry + rh - r - 1 + if px < x_left && py < y_top { + let dx = x_left - px + let dy = y_top - py + dx * dx + dy * dy <= r * r + } else if px > x_right && py < y_top { + let dx = px - x_right + let dy = y_top - py + dx * dx + dy * dy <= r * r + } else if px < x_left && py > y_bot { + let dx = x_left - px + let dy = py - y_bot + dx * dx + dy * dy <= r * r + } else if px > x_right && py > y_bot { + let dx = px - x_right + let dy = py - y_bot + dx * dx + dy * dy <= r * r + } else { + true + } +} + +///| +fn fill_rounded_rect( + dst : Pixmap, + rect : @scene.Rect, + color : @scene.Rgba, + radius : Int, + clip : @scene.Rect?, +) -> Unit { + if rect.w <= 0 || rect.h <= 0 || color.a.to_int() == 0 { + return + } + let x0 = if rect.x < 0 { 0 } else { rect.x } + let y0 = if rect.y < 0 { 0 } else { rect.y } + let x1 = if rect.x + rect.w > dst.width { dst.width } else { rect.x + rect.w } + let y1 = if rect.y + rect.h > dst.height { + dst.height + } else { + rect.y + rect.h + } + let cr = color.r.to_int() + let cg = color.g.to_int() + let cb = color.b.to_int() + let ca = color.a.to_int() + for y = y0; y < y1; y = y + 1 { + for x = x0; x < x1; x = x + 1 { + if radius == 0 || + in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) { + blend_pixel(dst, x, y, cr, cg, cb, ca, clip) + } + } + } +} + +///| +fn stroke_rounded_rect( + dst : Pixmap, + rect : @scene.Rect, + color : @scene.Rgba, + width : Int, + radius : Int, + clip : @scene.Rect?, +) -> Unit { + if rect.w <= 0 || rect.h <= 0 || width <= 0 || color.a.to_int() == 0 { + return + } + let x0 = if rect.x < 0 { 0 } else { rect.x } + let y0 = if rect.y < 0 { 0 } else { rect.y } + let x1 = if rect.x + rect.w > dst.width { dst.width } else { rect.x + rect.w } + let y1 = if rect.y + rect.h > dst.height { + dst.height + } else { + rect.y + rect.h + } + let cr = color.r.to_int() + let cg = color.g.to_int() + let cb = color.b.to_int() + let ca = color.a.to_int() + let inner_x = rect.x + width + let inner_y = rect.y + width + let inner_w = rect.w - width * 2 + let inner_h = rect.h - width * 2 + let inner_r = if radius > width { radius - width } else { 0 } + for y = y0; y < y1; y = y + 1 { + for x = x0; x < x1; x = x + 1 { + 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(dst, x, y, cr, cg, cb, ca, clip) + } + } + } +} + +///| +fn draw_line( + dst : Pixmap, + x0_in : Int, + y0_in : Int, + x1_in : Int, + y1_in : Int, + color : @scene.Rgba, + width : Int, + clip : @scene.Rect?, +) -> Unit { + let cr = color.r.to_int() + let cg = color.g.to_int() + let cb = color.b.to_int() + let ca = color.a.to_int() + let half = if width <= 1 { 0 } else { width / 2 } + let mut x0 = x0_in + let mut y0 = y0_in + let dx = (x1_in - x0_in).abs() + let sx = if x0_in < x1_in { 1 } else { -1 } + let dy = -(y1_in - y0_in).abs() + let sy = if y0_in < y1_in { 1 } else { -1 } + let mut err = dx + dy + while true { + for oy = -half; oy <= half; oy = oy + 1 { + for ox = -half; ox <= half; ox = ox + 1 { + blend_pixel(dst, x0 + ox, y0 + oy, cr, cg, cb, ca, clip) + } + } + if x0 == x1_in && y0 == y1_in { + break + } + let e2 = 2 * err + if e2 >= dy { + err = err + dy + x0 = x0 + sx + } + if e2 <= dx { + err = err + dx + y0 = y0 + sy + } + } +} + +///| +fn draw_circle( + dst : Pixmap, + cx : Int, + cy : Int, + radius : Int, + color : @scene.Rgba, + filled : Bool, + clip : @scene.Rect?, +) -> Unit { + if radius <= 0 { + return + } + let cr = color.r.to_int() + let cg = color.g.to_int() + let cb = color.b.to_int() + let ca = color.a.to_int() + let r2 = radius * radius + let inner_r2 = if radius > 1 { (radius - 1) * (radius - 1) } else { 0 } + for dy = -radius; dy <= radius; dy = dy + 1 { + for dx = -radius; dx <= radius; dx = dx + 1 { + let d2 = dx * dx + dy * dy + if d2 <= r2 && (filled || d2 >= inner_r2) { + blend_pixel(dst, cx + dx, cy + dy, cr, cg, cb, ca, clip) + } + } + } +} + +///| Minimal 5x7 ASCII bitmap glyph rows (5 bits wide, 7 rows). +fn glyph_rows(ch : Int) -> Array[Int] { + match ch { + // Space + 32 => [0, 0, 0, 0, 0, 0, 0] + // Digits 0-9 + 48 => [14, 17, 19, 21, 25, 17, 14] + 49 => [4, 12, 4, 4, 4, 4, 14] + 50 => [14, 17, 1, 2, 4, 8, 31] + 51 => [31, 2, 4, 2, 1, 17, 14] + 52 => [2, 6, 10, 18, 31, 2, 2] + 53 => [31, 16, 30, 1, 1, 17, 14] + 54 => [6, 8, 16, 30, 17, 17, 14] + 55 => [31, 1, 2, 4, 8, 8, 8] + 56 => [14, 17, 17, 14, 17, 17, 14] + 57 => [14, 17, 17, 15, 1, 2, 12] + // Uppercase A-Z (mapped for both A-Z and a-z fallback if needed, plus lowercase) + 65 => [14, 17, 17, 31, 17, 17, 17] // A + 66 => [30, 17, 17, 30, 17, 17, 30] // B + 67 => [14, 17, 16, 16, 16, 17, 14] // C + 68 => [28, 18, 17, 17, 17, 18, 28] // D + 69 => [31, 16, 16, 30, 16, 16, 31] // E + 70 => [31, 16, 16, 30, 16, 16, 16] // F + 71 => [14, 17, 16, 23, 17, 17, 15] // G + 72 => [17, 17, 17, 31, 17, 17, 17] // H + 73 => [14, 4, 4, 4, 4, 4, 14] // I + 74 => [7, 2, 2, 2, 2, 18, 12] // J + 75 => [17, 18, 20, 24, 20, 18, 17] // K + 76 => [16, 16, 16, 16, 16, 16, 31] // L + 77 => [17, 27, 21, 21, 17, 17, 17] // M + 78 => [17, 17, 25, 21, 19, 17, 17] // N + 79 => [14, 17, 17, 17, 17, 17, 14] // O + 80 => [30, 17, 17, 30, 16, 16, 16] // P + 81 => [14, 17, 17, 17, 21, 18, 13] // Q + 82 => [30, 17, 17, 30, 20, 18, 17] // R + 83 => [15, 16, 16, 14, 1, 1, 30] // S + 84 => [31, 4, 4, 4, 4, 4, 4] // T + 85 => [17, 17, 17, 17, 17, 17, 14] // U + 86 => [17, 17, 17, 17, 17, 10, 4] // V + 87 => [17, 17, 17, 21, 21, 27, 17] // W + 88 => [17, 17, 10, 4, 10, 17, 17] // X + 89 => [17, 17, 10, 4, 4, 4, 4] // Y + 90 => [31, 1, 2, 4, 8, 16, 31] // Z + // Lowercase a-z + 97 => [0, 0, 14, 1, 15, 17, 15] // a + 98 => [16, 16, 22, 25, 17, 17, 30] // b + 99 => [0, 0, 14, 16, 16, 17, 14] // c + 100 => [1, 1, 13, 19, 17, 17, 15] // d + 101 => [0, 0, 14, 17, 31, 16, 14] // e + 102 => [6, 9, 8, 28, 8, 8, 8] // f + 103 => [0, 0, 15, 17, 15, 1, 14] // g + 104 => [16, 16, 22, 25, 17, 17, 17] // h + 105 => [4, 0, 12, 4, 4, 4, 14] // i + 106 => [2, 0, 6, 2, 2, 18, 12] // j + 107 => [16, 16, 18, 20, 24, 20, 18] // k + 108 => [12, 4, 4, 4, 4, 4, 14] // l + 109 => [0, 0, 26, 21, 21, 17, 17] // m + 110 => [0, 0, 22, 25, 17, 17, 17] // n + 111 => [0, 0, 14, 17, 17, 17, 14] // o + 112 => [0, 0, 30, 17, 30, 16, 16] // p + 113 => [0, 0, 15, 17, 15, 1, 1] // q + 114 => [0, 0, 22, 25, 16, 16, 16] // r + 115 => [0, 0, 14, 16, 14, 1, 30] // s + 116 => [8, 8, 28, 8, 8, 9, 6] // t + 117 => [0, 0, 17, 17, 17, 19, 13] // u + 118 => [0, 0, 17, 17, 17, 10, 4] // v + 119 => [0, 0, 17, 17, 21, 21, 10] // w + 120 => [0, 0, 17, 10, 4, 10, 17] // x + 121 => [0, 0, 17, 17, 15, 1, 14] // y + 122 => [0, 0, 31, 2, 4, 8, 31] // z + // Punctuation + 45 => [0, 0, 0, 14, 0, 0, 0] // - + 46 => [0, 0, 0, 0, 0, 12, 12] // . + 58 => [0, 12, 12, 0, 12, 12, 0] // : + 47 => [1, 2, 2, 4, 8, 8, 16] // / + 95 => [0, 0, 0, 0, 0, 0, 31] // _ + _ => [31, 17, 21, 21, 21, 17, 31] + } +} + +///| +fn draw_text( + dst : Pixmap, + x : Int, + y : Int, + text : String, + size : Int, + color : @scene.Rgba, + align : @scene.TextAlign, + bold : Bool, + clip : @scene.Rect?, +) -> Unit { + if text.length() == 0 || color.a.to_int() == 0 { + return + } + let scale = if size >= 14 { 2 } else { 1 } + let char_w = 6 * scale + let total_w = text.length() * char_w + let start_x = match align { + Left => x + Center => x - total_w / 2 + Right => x - total_w + } + let start_y = y - 7 * scale / 2 + let cr = color.r.to_int() + let cg = color.g.to_int() + let cb = color.b.to_int() + let ca = color.a.to_int() + + let mut idx = 0 + for ch in text { + let rows = glyph_rows(ch.to_int()) + let gx = start_x + idx * char_w + for row = 0; row < 7; row = row + 1 { + let bits = rows[row] + for col = 0; col < 5; col = col + 1 { + if ((bits >> (4 - col)) & 1) != 0 { + for sy = 0; sy < scale; sy = sy + 1 { + for sx = 0; sx < scale; sx = sx + 1 { + let px = gx + col * scale + sx + let py = start_y + row * scale + sy + blend_pixel(dst, px, py, cr, cg, cb, ca, clip) + if bold { + blend_pixel(dst, px + 1, py, cr, cg, cb, ca, clip) + } + } + } + } + } + } + idx = idx + 1 + } +} + +///| +pub fn draw_ops( + dst : Pixmap, + ops : Array[@scene.DrawOp], + ox : Int, + oy : Int, +) -> Unit { + let clip_stack : Array[@scene.Rect] = [] + for op in ops { + let cur_clip : @scene.Rect? = if clip_stack.length() > 0 { + Some(clip_stack[clip_stack.length() - 1]) + } else { + None + } + match op { + FillRect(r, col, rad) => + fill_rounded_rect( + dst, + @scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h), + col, + rad, + cur_clip, + ) + StrokeRect(r, col, w, rad) => + stroke_rounded_rect( + dst, + @scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h), + col, + w, + rad, + cur_clip, + ) + Line(x0, y0, x1, y1, col, w) => + draw_line(dst, x0 + ox, y0 + oy, x1 + ox, y1 + oy, col, w, cur_clip) + Circle(cx, cy, rad, col, filled) => + draw_circle(dst, cx + ox, cy + oy, rad, col, filled, cur_clip) + Text(x, y, txt, sz, col, align, bold) => + draw_text(dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip) + PushClip(r) => + clip_stack.push(@scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h)) + PopClip => if clip_stack.length() > 0 { ignore(clip_stack.pop()) } + } + } +} + +///| Blit a Wayland wl_shm client buffer (ARGB8888=0, XRGB8888=1, little-endian [B,G,R,A]). +pub fn blit_shm_surface( + dst : Pixmap, + buf : @scene.ShmBufferSnapshot, + dst_rect : @scene.Rect, +) -> Unit { + if buf.width <= 0 || buf.height <= 0 || dst_rect.w <= 0 || dst_rect.h <= 0 { + return + } + let copy_w = if buf.width < dst_rect.w { buf.width } else { dst_rect.w } + let copy_h = if buf.height < dst_rect.h { buf.height } else { dst_rect.h } + let is_xrgb = buf.format == 1 + for row = 0; row < copy_h; row = row + 1 { + let dy = dst_rect.y + row + if dy < 0 || dy >= dst.height { + continue + } + for col = 0; col < copy_w; col = col + 1 { + let dx = dst_rect.x + col + if dx < 0 || dx >= dst.width { + continue + } + let src_off = row * buf.stride + col * 4 + if src_off + 3 >= buf.bytes.length() { + continue + } + let b = buf.bytes[src_off].to_int() + let g = buf.bytes[src_off + 1].to_int() + let r = buf.bytes[src_off + 2].to_int() + let a = if is_xrgb { 255 } else { buf.bytes[src_off + 3].to_int() } + blend_pixel(dst, dx, dy, r, g, b, a, None) + } + } +} + +///| +pub fn render_scene(scene : @scene.SceneGraph) -> Pixmap { + let pixmap = Pixmap::new(scene.output_w, scene.output_h) + + // 1. Background layer + draw_ops(pixmap, scene.background_ops, 0, 0) + + // 2. Windows layer (bottom-to-top) + for win in scene.windows { + if !win.fullscreen { + let (top, right, bottom, left) = win.deco_insets + let outer_x = win.geometry.x - left + let outer_y = win.geometry.y - top + let outer_w = win.geometry.w + left + right + let outer_h = win.geometry.h + top + bottom + + // Subtle drop shadow + fill_rounded_rect( + pixmap, + @scene.Rect::new(outer_x + 4, outer_y + 6, outer_w, outer_h), + @scene.Rgba::new(0, 0, 0, 80), + 8, + None, + ) + + // Breeze SSD decoration draw-ops + draw_ops(pixmap, win.deco_ops, outer_x, outer_y) + } + + // Client wl_shm surface + match win.surface { + Some(buf) => blit_shm_surface(pixmap, buf, win.geometry) + None => + fill_rounded_rect( + pixmap, + win.geometry, + @scene.Rgba::new(0x1e, 0x29, 0x3b, 0xff), + 0, + None, + ) + } + } + + // 3. Panel layer + draw_ops(pixmap, scene.panel_ops, 0, 0) + for widget in scene.widgets { + draw_ops(pixmap, widget.ops, widget.rect.x, widget.rect.y) + } + + // 4. Overlay layer + for widget in scene.widgets { + match widget.popup { + Some((pr, pops)) => draw_ops(pixmap, pops, pr.x, pr.y) + None => () + } + } + + pixmap +} + +///| Encode Pixmap as binary PPM (P6). +pub fn encode_ppm(p : Pixmap) -> Bytes { + let header = "P6\n" + + p.width.to_string() + + " " + + p.height.to_string() + + "\n255\n" + let out : Array[Byte] = [] + for ch in header { + out.push(ch.to_int().to_byte()) + } + let count = p.width * p.height + for i = 0; i < count; i = i + 1 { + let off = i * 4 + out.push(p.data[off]) + out.push(p.data[off + 1]) + out.push(p.data[off + 2]) + } + Bytes::from_array(out) +} + +///| +fn push_u32_be(out : Array[Byte], v : UInt) -> Unit { + out.push(((v >> 24) & 0xFFU).to_byte()) + out.push(((v >> 16) & 0xFFU).to_byte()) + out.push(((v >> 8) & 0xFFU).to_byte()) + out.push((v & 0xFFU).to_byte()) +} + +///| +fn crc32(bytes : Array[Byte], start : Int, len : Int) -> UInt { + let mut c = 0xFFFF_FFFFU + for i = 0; i < len; i = i + 1 { + c = c ^ bytes[start + i].to_uint() + for _b = 0; _b < 8; _b = _b + 1 { + if (c & 1U) != 0U { + c = (c >> 1) ^ 0xEDB8_8320U + } else { + c = c >> 1 + } + } + } + c ^ 0xFFFF_FFFFU +} + +///| +fn push_png_chunk(out : Array[Byte], tag : String, payload : Array[Byte]) -> Unit { + push_u32_be(out, payload.length().reinterpret_as_uint()) + let crc_start = out.length() + for ch in tag { + out.push(ch.to_int().to_byte()) + } + for b in payload { + out.push(b) + } + let crc = crc32(out, crc_start, 4 + payload.length()) + push_u32_be(out, crc) +} + +///| Encode Pixmap as a valid uncompressed RGBA PNG in pure MoonBit. +pub fn encode_png(p : Pixmap) -> Bytes { + let out : Array[Byte] = [ + b'\x89', b'\x50', b'\x4e', b'\x47', b'\x0d', b'\x0a', b'\x1a', b'\x0a', + ] + + // IHDR + let ihdr : Array[Byte] = [] + push_u32_be(ihdr, p.width.reinterpret_as_uint()) + push_u32_be(ihdr, p.height.reinterpret_as_uint()) + ihdr.push(b'\x08') // bit depth = 8 + ihdr.push(b'\x06') // color type = RGBA + ihdr.push(b'\x00') // compression = 0 + ihdr.push(b'\x00') // filter = 0 + ihdr.push(b'\x00') // interlace = 0 + push_png_chunk(out, "IHDR", ihdr) + + // Raw scanlines: 1 filter byte (0) + width * 4 bytes per row + let row_bytes = 1 + p.width * 4 + let raw : Array[Byte] = Array(capacity=row_bytes * p.height) + let mut s1 = 1U + let mut s2 = 0U + for y = 0; y < p.height; y = y + 1 { + raw.push(b'\x00') + s1 = (s1 + 0U) % 65521U + s2 = (s2 + s1) % 65521U + let row_off = y * p.width * 4 + for i = 0; i < p.width * 4; i = i + 1 { + let b = p.data[row_off + i] + raw.push(b) + s1 = (s1 + b.to_uint()) % 65521U + s2 = (s2 + s1) % 65521U + } + } + + // Zlib stream with stored (uncompressed) deflate blocks (max 65535 bytes each) + let idat : Array[Byte] = [b'\x78', b'\x01'] + let mut pos = 0 + let total = raw.length() + while pos < total { + let rem = total - pos + let blk = if rem > 65535 { 65535 } else { rem } + let is_last = pos + blk >= total + idat.push(if is_last { b'\x01' } else { b'\x00' }) + idat.push((blk & 0xFF).to_byte()) + idat.push(((blk >> 8) & 0xFF).to_byte()) + let nlen = blk ^ 0xFFFF + idat.push((nlen & 0xFF).to_byte()) + idat.push(((nlen >> 8) & 0xFF).to_byte()) + for i = 0; i < blk; i = i + 1 { + idat.push(raw[pos + i]) + } + pos = pos + blk + } + let adler = (s2 << 16) | s1 + push_u32_be(idat, adler) + push_png_chunk(out, "IDAT", idat) + + // IEND + push_png_chunk(out, "IEND", []) + Bytes::from_array(out) +} diff --git a/compositor/renderer/renderer_test.mbt b/compositor/renderer/renderer_test.mbt new file mode 100644 index 0000000..c1ae938 --- /dev/null +++ b/compositor/renderer/renderer_test.mbt @@ -0,0 +1,60 @@ +///| +test "software renderer alpha blending, rounded rect, shm blit, and png encoding" { + let theme = @scene.ThemeTokens::moon_night() + let scene = @scene.SceneGraph::new(320, 200) + let (bg, panel) = @scene.build_shell_ops( + 320, + 200, + theme, + "BSP Tiling", + ["MoonTerm"], + ) + scene.background_ops = bg + scene.panel_ops = panel + + let (insets, deco_ops) = @scene.build_breeze_decoration( + "MoonTerm", + "org.moonplasma.term", + true, + false, + 200, + 120, + theme, + ) + // 100x60 ARGB8888 cyan buffer + let buf_bytes : Array[Byte] = Array(capacity=100 * 60 * 4) + for _i = 0; _i < 100 * 60; _i = _i + 1 { + buf_bytes.push(b'\xf8') // B + buf_bytes.push(b'\xbd') // G + buf_bytes.push(b'\x38') // R + buf_bytes.push(b'\xff') // A + } + scene.windows.push({ + id: 1UL, + title: "MoonTerm", + app_id: "org.moonplasma.term", + focused: true, + fullscreen: false, + geometry: @scene.Rect::new(20, 40, 100, 60), + deco_insets: insets, + deco_ops, + surface: Some({ + width: 100, + height: 60, + stride: 400, + format: 0, + bytes: Bytes::from_array(buf_bytes), + }), + }) + + let pm = @renderer.render_scene(scene) + assert_eq(pm.pixel(70, 70), Some(@scene.Rgba::new(0x38, 0xbd, 0xf8, 0xff))) + let png = @renderer.encode_png(pm) + assert_eq(png[0], b'\x89') + assert_eq(png[1], b'\x50') + assert_eq(png[2], b'\x4e') + assert_eq(png[3], b'\x47') + let ppm = @renderer.encode_ppm(pm) + assert_eq(ppm[0], b'\x50') // 'P' + assert_eq(ppm[1], b'\x36') // '6' +} diff --git a/compositor/scene/moon.pkg b/compositor/scene/moon.pkg new file mode 100644 index 0000000..2828fc7 --- /dev/null +++ b/compositor/scene/moon.pkg @@ -0,0 +1,4 @@ +import { + "moonbitlang/core/builtin", + "moonbitlang/core/json", +} diff --git a/compositor/scene/pkg.generated.mbti b/compositor/scene/pkg.generated.mbti new file mode 100644 index 0000000..aa55013 --- /dev/null +++ b/compositor/scene/pkg.generated.mbti @@ -0,0 +1,127 @@ +// Generated using `moon info`, DON'T EDIT IT +package "moonplasma/desktop/compositor/scene" + +import { + "moonbitlang/core/debug", +} + +// Values +pub fn build_breeze_decoration(String, String, Bool, Bool, Int32, Int32, ThemeTokens) -> ((Int32, Int32, Int32, Int32), Array[DrawOp]) + +pub fn build_shell_ops(Int32, Int32, ThemeTokens, String, Array[String]) -> (Array[DrawOp], Array[DrawOp]) + +// Errors + +// Types and methods +pub(all) struct DamageTracker { + regions : Array[Rect] + mut full_damage : Bool +} +pub fn DamageTracker::mark_full(Self) -> Unit +pub fn DamageTracker::mark_rect(Self, Rect) -> Unit +pub fn DamageTracker::new() -> Self +pub fn DamageTracker::take_damage(Self, Int32, Int32) -> Array[Rect] + +pub(all) enum DrawOp { + FillRect(Rect, Rgba, Int32) + StrokeRect(Rect, Rgba, Int32, Int32) + Line(Int32, Int32, Int32, Int32, Rgba, Int32) + Circle(Int32, Int32, Int32, Rgba, Bool) + Text(Int32, Int32, String, Int32, Rgba, TextAlign, Bool) + PushClip(Rect) + PopClip +} + +pub(all) struct PanelWidgetNode { + id : String + rect : Rect + ops : Array[DrawOp] + popup : (Rect, Array[DrawOp])? +} + +#derive(Eq, @debug.Debug) +pub(all) struct Rect { + x : Int32 + y : Int32 + w : Int32 + h : Int32 +} +pub fn Rect::contains(Self, Int32, Int32) -> Bool +pub fn Rect::new(Int32, Int32, Int32, Int32) -> Self +pub fn Rect::union(Self, Self) -> Self + +#derive(Eq, @debug.Debug) +pub(all) struct Rgba { + r : Byte + g : Byte + b : Byte + a : Byte +} +pub fn Rgba::from_hex(String) -> Self +pub fn Rgba::new(Int32, Int32, Int32, Int32) -> Self +pub fn Rgba::with_alpha(Self, Int32) -> Self + +pub(all) struct SceneGraph { + output_w : Int32 + output_h : Int32 + mut background_ops : Array[DrawOp] + mut windows : Array[WindowSceneNode] + mut panel_ops : Array[DrawOp] + mut widgets : Array[PanelWidgetNode] +} +pub fn SceneGraph::new(Int32, Int32) -> Self + +pub(all) struct ShmBufferSnapshot { + width : Int32 + height : Int32 + stride : Int32 + format : Int32 + bytes : Bytes +} + +#derive(Eq, @debug.Debug) +pub(all) enum TextAlign { + Left + Center + Right +} + +pub(all) struct ThemePalette { + desktop_top : Rgba + desktop_bottom : Rgba + surface : Rgba + surface_hover : Rgba + surface_popup : Rgba + foreground : Rgba + foreground_muted : Rgba + accent : Rgba + accent_foreground : Rgba + border : Rgba +} + +pub(all) struct ThemeTokens { + name : String + palette : ThemePalette + font_size : Int32 + radius : Int32 + spacing : Int32 + panel_height : Int32 +} +pub fn ThemeTokens::from_json_string(String) -> Self +pub fn ThemeTokens::moon_night() -> Self + +pub(all) struct WindowSceneNode { + id : UInt64 + title : String + app_id : String + focused : Bool + fullscreen : Bool + geometry : Rect + deco_insets : (Int32, Int32, Int32, Int32) + deco_ops : Array[DrawOp] + surface : ShmBufferSnapshot? +} + +// Type aliases + +// Traits diff --git a/compositor/scene/scene.mbt b/compositor/scene/scene.mbt new file mode 100644 index 0000000..162add7 --- /dev/null +++ b/compositor/scene/scene.mbt @@ -0,0 +1,521 @@ +///| Scene graph, theme tokens, damage tracking, and Breeze-style SSD + shell draw-ops in pure MoonBit. + +///| +#derive(Eq, Debug) +pub(all) struct Rgba { + r : Byte + g : Byte + b : Byte + a : Byte +} + +///| +pub fn Rgba::new(r : Int, g : Int, b : Int, a : Int) -> Rgba { + { + r: r.clamp(min=0, max=255).to_byte(), + g: g.clamp(min=0, max=255).to_byte(), + b: b.clamp(min=0, max=255).to_byte(), + a: a.clamp(min=0, max=255).to_byte(), + } +} + +///| +pub fn Rgba::with_alpha(self : Rgba, a : Int) -> Rgba { + { r: self.r, g: self.g, b: self.b, a: a.clamp(min=0, max=255).to_byte() } +} + +///| +fn hex_nibble(c : Int) -> Int { + if c >= 48 && c <= 57 { + c - 48 + } else if c >= 97 && c <= 102 { + c - 97 + 10 + } else if c >= 65 && c <= 70 { + c - 65 + 10 + } else { + 0 + } +} + +///| +fn parse_hex_byte(s : String, idx : Int) -> Int { + let hi = hex_nibble(s[idx].to_int()) + let lo = hex_nibble(s[idx + 1].to_int()) + (hi << 4) | lo +} + +///| +pub fn Rgba::from_hex(s : String) -> Rgba { + let hex = if s.has_prefix("#") { + s.clamped_view(start=1, end=s.length()).to_owned() + } else { + s + } + if hex.length() == 6 { + Rgba::new( + parse_hex_byte(hex, 0), + parse_hex_byte(hex, 2), + parse_hex_byte(hex, 4), + 255, + ) + } else if hex.length() == 8 { + Rgba::new( + parse_hex_byte(hex, 0), + parse_hex_byte(hex, 2), + parse_hex_byte(hex, 4), + parse_hex_byte(hex, 6), + ) + } else { + Rgba::new(0, 0, 0, 255) + } +} + +///| +pub(all) struct ThemePalette { + desktop_top : Rgba + desktop_bottom : Rgba + surface : Rgba + surface_hover : Rgba + surface_popup : Rgba + foreground : Rgba + foreground_muted : Rgba + accent : Rgba + accent_foreground : Rgba + border : Rgba +} + +///| +pub(all) struct ThemeTokens { + name : String + palette : ThemePalette + font_size : Int + radius : Int + spacing : Int + panel_height : Int +} + +///| +pub fn ThemeTokens::moon_night() -> ThemeTokens { + { + name: "Moon Night", + palette: { + desktop_top: Rgba::from_hex("#16213e"), + desktop_bottom: Rgba::from_hex("#0b1020"), + surface: Rgba::from_hex("#1f2937f2"), + surface_hover: Rgba::from_hex("#374151"), + surface_popup: Rgba::from_hex("#111827f5"), + foreground: Rgba::from_hex("#f3f4f6"), + foreground_muted: Rgba::from_hex("#9ca3af"), + accent: Rgba::from_hex("#7c9cff"), + accent_foreground: Rgba::from_hex("#0b1020"), + border: Rgba::from_hex("#3b4658"), + }, + font_size: 14, + radius: 6, + spacing: 6, + panel_height: 44, + } +} + +///| +fn json_str(obj : Map[String, Json], key : String, fallback : String) -> String { + match obj.get(key) { + Some(String(s)) => s + _ => fallback + } +} + +///| +fn json_int(obj : Map[String, Json], key : String, fallback : Int) -> Int { + match obj.get(key) { + Some(Number(n, ..)) => n.to_int() + _ => fallback + } +} + +///| +pub fn ThemeTokens::from_json_string(text : String) -> ThemeTokens { + let def = ThemeTokens::moon_night() + let parsed = try { + @json.parse(text) + } catch { + _ => return def + } + guard parsed is Object(root) else { return def } + let pal_obj = match root.get("palette") { + Some(Object(m)) => m + _ => return def + } + { + name: json_str(root, "name", def.name), + palette: { + desktop_top: Rgba::from_hex(json_str(pal_obj, "desktop-top", "#16213e")), + desktop_bottom: Rgba::from_hex( + json_str(pal_obj, "desktop-bottom", "#0b1020"), + ), + surface: Rgba::from_hex(json_str(pal_obj, "surface", "#1f2937f2")), + surface_hover: Rgba::from_hex( + json_str(pal_obj, "surface-hover", "#374151"), + ), + surface_popup: Rgba::from_hex( + json_str(pal_obj, "surface-popup", "#111827f5"), + ), + foreground: Rgba::from_hex(json_str(pal_obj, "foreground", "#f3f4f6")), + foreground_muted: Rgba::from_hex( + json_str(pal_obj, "foreground-muted", "#9ca3af"), + ), + accent: Rgba::from_hex(json_str(pal_obj, "accent", "#7c9cff")), + accent_foreground: Rgba::from_hex( + json_str(pal_obj, "accent-foreground", "#0b1020"), + ), + border: Rgba::from_hex(json_str(pal_obj, "border", "#3b4658")), + }, + font_size: json_int(root, "font-size", def.font_size), + radius: json_int(root, "radius", def.radius), + spacing: json_int(root, "spacing", def.spacing), + panel_height: json_int(root, "panel-height", def.panel_height), + } +} + +///| +#derive(Eq, Debug) +pub(all) struct Rect { + x : Int + y : Int + w : Int + h : Int +} + +///| +pub fn Rect::new(x : Int, y : Int, w : Int, h : Int) -> Rect { + { x, y, w: if w < 0 { 0 } else { w }, h: if h < 0 { 0 } else { h } } +} + +///| +pub fn Rect::union(self : Rect, other : Rect) -> Rect { + let x0 = if self.x < other.x { self.x } else { other.x } + let y0 = if self.y < other.y { self.y } else { other.y } + let self_x1 = self.x + self.w + let other_x1 = other.x + other.w + let x1 = if self_x1 > other_x1 { self_x1 } else { other_x1 } + let self_y1 = self.y + self.h + let other_y1 = other.y + other.h + let y1 = if self_y1 > other_y1 { self_y1 } else { other_y1 } + Rect::new(x0, y0, x1 - x0, y1 - y0) +} + +///| +pub fn Rect::contains(self : Rect, px : Int, py : Int) -> Bool { + px >= self.x && py >= self.y && px < self.x + self.w && py < self.y + self.h +} + +///| +#derive(Eq, Debug) +pub(all) enum TextAlign { + Left + Center + Right +} + +///| +pub(all) enum DrawOp { + FillRect(Rect, Rgba, Int) + StrokeRect(Rect, Rgba, Int, Int) + Line(Int, Int, Int, Int, Rgba, Int) + Circle(Int, Int, Int, Rgba, Bool) + Text(Int, Int, String, Int, Rgba, TextAlign, Bool) + PushClip(Rect) + PopClip +} + +///| +pub(all) struct ShmBufferSnapshot { + width : Int + height : Int + stride : Int + /// Wayland wl_shm format: 0 = ARGB8888, 1 = XRGB8888 + format : Int + bytes : Bytes +} + +///| +pub(all) struct WindowSceneNode { + id : UInt64 + title : String + app_id : String + focused : Bool + fullscreen : Bool + geometry : Rect + /// (top, right, bottom, left) + deco_insets : (Int, Int, Int, Int) + deco_ops : Array[DrawOp] + surface : ShmBufferSnapshot? +} + +///| +pub(all) struct PanelWidgetNode { + id : String + rect : Rect + ops : Array[DrawOp] + popup : (Rect, Array[DrawOp])? +} + +///| +pub(all) struct DamageTracker { + regions : Array[Rect] + mut full_damage : Bool +} + +///| +pub fn DamageTracker::new() -> DamageTracker { + { regions: [], full_damage: true } +} + +///| +pub fn DamageTracker::mark_full(self : DamageTracker) -> Unit { + self.full_damage = true + self.regions.clear() +} + +///| +pub fn DamageTracker::mark_rect(self : DamageTracker, rect : Rect) -> Unit { + if self.full_damage || rect.w <= 0 || rect.h <= 0 { + return + } + self.regions.push(rect) +} + +///| +pub fn DamageTracker::take_damage( + self : DamageTracker, + output_w : Int, + output_h : Int, +) -> Array[Rect] { + if self.full_damage { + self.full_damage = false + self.regions.clear() + return [Rect::new(0, 0, output_w, output_h)] + } + let out : Array[Rect] = [] + for r in self.regions { + out.push(r) + } + self.regions.clear() + out +} + +///| +pub(all) struct SceneGraph { + output_w : Int + output_h : Int + mut background_ops : Array[DrawOp] + mut windows : Array[WindowSceneNode] + mut panel_ops : Array[DrawOp] + mut widgets : Array[PanelWidgetNode] +} + +///| +pub fn SceneGraph::new(output_w : Int, output_h : Int) -> SceneGraph { + { + output_w, + output_h, + background_ops: [], + windows: [], + panel_ops: [], + widgets: [], + } +} + +///| Generate Breeze-style Server-Side Decoration draw-ops for a window. +pub fn build_breeze_decoration( + title : String, + app_id : String, + focused : Bool, + fullscreen : Bool, + outer_w : Int, + outer_h : Int, + tokens : ThemeTokens, +) -> ((Int, Int, Int, Int), Array[DrawOp]) { + if fullscreen { + return ((0, 0, 0, 0), []) + } + let p = tokens.palette + let title_h = 32 + let border = 2 + let radius = tokens.radius + let title_bg = if focused { p.surface } else { p.surface.with_alpha(210) } + let border_col = if focused { p.accent } else { p.border } + let title_fg = if focused { p.foreground } else { p.foreground_muted } + + let ops : Array[DrawOp] = [ + FillRect(Rect::new(0, 0, outer_w, title_h), title_bg, radius), + StrokeRect(Rect::new(0, 0, outer_w, outer_h), border_col, border, radius), + Line(border, title_h - 1, outer_w - border, title_h - 1, p.border, 1), + ] + + let label = if title.length() > 0 { title } else { app_id } + ops.push( + Text( + 14, + title_h / 2, + label, + tokens.font_size, + title_fg, + Left, + focused, + ), + ) + + // Window control buttons on the right: [ _ ] [ [] ] [ X ] + let btn_size = 18 + let btn_y = (title_h - btn_size) / 2 + let close_x = outer_w - 10 - btn_size + let max_x = close_x - 8 - btn_size + let min_x = max_x - 8 - btn_size + + let close_bg = if focused { + Rgba::new(218, 68, 83, 255) + } else { + p.surface_hover + } + let btn_bg = p.surface_hover + + ops.push(FillRect(Rect::new(min_x, btn_y, btn_size, btn_size), btn_bg, 9)) + ops.push( + Line( + min_x + 5, + btn_y + btn_size - 6, + min_x + btn_size - 5, + btn_y + btn_size - 6, + title_fg, + 2, + ), + ) + + ops.push(FillRect(Rect::new(max_x, btn_y, btn_size, btn_size), btn_bg, 9)) + ops.push( + StrokeRect( + Rect::new(max_x + 5, btn_y + 5, btn_size - 10, btn_size - 10), + title_fg, + 1, + 0, + ), + ) + + ops.push(FillRect(Rect::new(close_x, btn_y, btn_size, btn_size), close_bg, 9)) + ops.push( + Line( + close_x + 5, + btn_y + 5, + close_x + btn_size - 5, + btn_y + btn_size - 5, + p.accent_foreground, + 2, + ), + ) + ops.push( + Line( + close_x + btn_size - 5, + btn_y + 5, + close_x + 5, + btn_y + btn_size - 5, + p.accent_foreground, + 2, + ), + ) + + ((title_h, border, border, border), ops) +} + +///| Generate desktop background gradient + bottom panel draw-ops. +pub fn build_shell_ops( + w : Int, + h : Int, + tokens : ThemeTokens, + layout_label : String, + window_titles : Array[String], +) -> (Array[DrawOp], Array[DrawOp]) { + let p = tokens.palette + let bg_ops : Array[DrawOp] = [] + let bands = 16 + let band_h = (h + bands - 1) / bands + for i = 0; i < bands; i = i + 1 { + let t_r = p.desktop_top.r.to_int() + let t_g = p.desktop_top.g.to_int() + let t_b = p.desktop_top.b.to_int() + let b_r = p.desktop_bottom.r.to_int() + let b_g = p.desktop_bottom.g.to_int() + let b_b = p.desktop_bottom.b.to_int() + let r = t_r + (b_r - t_r) * i / (bands - 1) + let g = t_g + (b_g - t_g) * i / (bands - 1) + let b = t_b + (b_b - t_b) * i / (bands - 1) + bg_ops.push( + FillRect( + Rect::new(0, i * band_h, w, band_h + 1), + Rgba::new(r, g, b, 255), + 0, + ), + ) + } + + let ph = tokens.panel_height + let py = h - ph + let panel_ops : Array[DrawOp] = [ + FillRect(Rect::new(0, py, w, ph), p.surface, 0), + Line(0, py, w, py, p.border, 1), + // Launcher pill + FillRect(Rect::new(8, py + 6, 92, ph - 12), p.accent, tokens.radius), + Text( + 54, + py + ph / 2, + "Moon", + tokens.font_size, + p.accent_foreground, + Center, + true, + ), + // Layout badge + FillRect( + Rect::new(108, py + 6, 96, ph - 12), + p.surface_hover, + tokens.radius, + ), + Text( + 156, + py + ph / 2, + layout_label, + tokens.font_size - 2, + p.foreground, + Center, + false, + ), + ] + + let mut tx = 216 + for title in window_titles { + let pill_w = 140 + if tx + pill_w < w - 100 { + panel_ops.push( + FillRect( + Rect::new(tx, py + 6, pill_w, ph - 12), + p.surface_hover, + tokens.radius, + ), + ) + panel_ops.push( + Text( + tx + 10, + py + ph / 2, + title, + tokens.font_size - 2, + p.foreground, + Left, + false, + ), + ) + tx = tx + pill_w + 6 + } + } + + (bg_ops, panel_ops) +} diff --git a/compositor/sys/moon.pkg b/compositor/sys/moon.pkg new file mode 100644 index 0000000..371a4eb --- /dev/null +++ b/compositor/sys/moon.pkg @@ -0,0 +1,9 @@ +import { + "moonbitlang/core/builtin", +} + +supported_targets = "-all+native" + +options( + "native-stub": [ "sys_stub.c" ], +) diff --git a/compositor/sys/sys.mbt b/compositor/sys/sys.mbt new file mode 100644 index 0000000..dd016b2 --- /dev/null +++ b/compositor/sys/sys.mbt @@ -0,0 +1,172 @@ +///| Minimal POSIX OS primitives for the pure-MoonBit Wayland compositor. + +///| +#borrow(path) +extern "C" fn c_unix_listen(path : Bytes) -> Int = "mp_unix_listen" + +///| +extern "C" fn c_unix_accept(listen_fd : Int) -> Int = "mp_unix_accept" + +///| +#borrow(path) +extern "C" fn c_unix_connect(path : Bytes) -> Int = "mp_unix_connect" + +///| +extern "C" fn c_close_fd(fd : Int) -> Int = "mp_close_fd" + +///| +#borrow(path) +extern "C" fn c_unlink(path : Bytes) -> Int = "mp_unlink" + +///| +extern "C" fn c_poll_read(fd : Int, timeout_ms : Int) -> Int = "mp_poll_read" + +///| +#borrow(buf, out_fd) +extern "C" fn c_recvmsg_fd( + fd : Int, + buf : FixedArray[Byte], + max_len : Int, + out_fd : FixedArray[Int], +) -> Int = "mp_recvmsg_fd" + +///| +#borrow(buf) +extern "C" fn c_sendmsg_fd( + fd : Int, + buf : Bytes, + len : Int, + send_fd : Int, +) -> Int = "mp_sendmsg_fd" + +///| +#borrow(name) +extern "C" fn c_memfd_create(name : Bytes, size : Int) -> Int = "mp_memfd_create" + +///| +#borrow(buf) +extern "C" fn c_pwrite_bytes( + fd : Int, + buf : Bytes, + len : Int, + offset : Int, +) -> Int = "mp_pwrite_bytes" + +///| +extern "C" fn c_mmap_read(fd : Int, size : Int) -> Bytes = "mp_mmap_read" + +///| +#borrow(path) +extern "C" fn c_read_file(path : Bytes) -> Bytes = "mp_read_file" + +///| +#borrow(path, buf) +extern "C" fn c_write_file(path : Bytes, buf : Bytes, len : Int) -> Int = "mp_write_file" + +///| +extern "C" fn c_sleep_ms(ms : Int) -> Unit = "mp_sleep_ms" + +///| +extern "C" fn c_getpid() -> Int = "mp_getpid" + +///| Encode ASCII/UTF-8 String into Bytes for C paths/names. +pub fn str_to_utf8_bytes(s : String) -> Bytes { + let buf : Array[Byte] = [] + for ch in s { + let code = ch.to_int() + if code < 0x80 { + buf.push(code.to_byte()) + } else if code < 0x800 { + buf.push((0xC0 | (code >> 6)).to_byte()) + buf.push((0x80 | (code & 0x3F)).to_byte()) + } else if code < 0x10000 { + buf.push((0xE0 | (code >> 12)).to_byte()) + buf.push((0x80 | ((code >> 6) & 0x3F)).to_byte()) + buf.push((0x80 | (code & 0x3F)).to_byte()) + } else { + buf.push((0xF0 | (code >> 18)).to_byte()) + buf.push((0x80 | ((code >> 12) & 0x3F)).to_byte()) + buf.push((0x80 | ((code >> 6) & 0x3F)).to_byte()) + buf.push((0x80 | (code & 0x3F)).to_byte()) + } + } + Bytes::from_array(buf) +} + +///| +pub fn unix_listen(path : String) -> Int { + c_unix_listen(str_to_utf8_bytes(path)) +} + +///| +pub fn unix_accept(listen_fd : Int) -> Int { + c_unix_accept(listen_fd) +} + +///| +pub fn unix_connect(path : String) -> Int { + c_unix_connect(str_to_utf8_bytes(path)) +} + +///| +pub fn close_fd(fd : Int) -> Unit { + ignore(c_close_fd(fd)) +} + +///| +pub fn unlink(path : String) -> Unit { + ignore(c_unlink(str_to_utf8_bytes(path))) +} + +///| +pub fn poll_read(fd : Int, timeout_ms : Int) -> Int { + c_poll_read(fd, timeout_ms) +} + +///| Receive bytes and optional SCM_RIGHTS fd. Returns (bytes_read, received_fd). +/// bytes_read == -1 means EAGAIN; -2 means error; 0 means EOF. +pub fn recvmsg_fd(fd : Int, buf : FixedArray[Byte], max_len : Int) -> (Int, Int) { + let out_fd : FixedArray[Int] = FixedArray::make(1, -1) + let n = c_recvmsg_fd(fd, buf, max_len, out_fd) + (n, out_fd[0]) +} + +///| +pub fn sendmsg_fd(fd : Int, buf : Bytes, send_fd : Int) -> Int { + c_sendmsg_fd(fd, buf, buf.length(), send_fd) +} + +///| +pub fn memfd_create(name : String, size : Int) -> Int { + c_memfd_create(str_to_utf8_bytes(name), size) +} + +///| +pub fn pwrite_bytes(fd : Int, buf : Bytes, offset : Int) -> Int { + c_pwrite_bytes(fd, buf, buf.length(), offset) +} + +///| +pub fn mmap_read(fd : Int, size : Int) -> Bytes { + c_mmap_read(fd, size) +} + +///| +pub fn read_file_bytes(path : String) -> Bytes { + c_read_file(str_to_utf8_bytes(path)) +} + +///| +pub fn write_file_bytes(path : String, data : Bytes) -> Int { + c_write_file(str_to_utf8_bytes(path), data, data.length()) +} + +///| +pub fn sleep_ms(ms : Int) -> Unit { + c_sleep_ms(ms) +} + +///| +pub fn getpid() -> Int { + c_getpid() +} diff --git a/compositor/sys/sys_stub.c b/compositor/sys/sys_stub.c new file mode 100644 index 0000000..9160918 --- /dev/null +++ b/compositor/sys/sys_stub.c @@ -0,0 +1,293 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "moonbit.h" + +static void bytes_to_cstr(moonbit_bytes_t b, char *out, size_t cap) { + int32_t len = Moonbit_array_length(b); + size_t n = (size_t)len < cap - 1 ? (size_t)len : cap - 1; + memcpy(out, b, n); + out[n] = '\0'; +} + +static int set_nonblock_cloexec(int fd) { + int flags = fcntl(fd, F_GETFL, 0); + if (flags >= 0) { + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } + int fdflags = fcntl(fd, F_GETFD, 0); + if (fdflags >= 0) { + fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC); + } + return 0; +} + +MOONBIT_FFI_EXPORT +int32_t mp_unix_listen(moonbit_bytes_t path_bytes) { + char path[108]; + bytes_to_cstr(path_bytes, path, sizeof(path)); + unlink(path); + + int fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) return -1; + set_nonblock_cloexec(fd); + + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); + + if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + close(fd); + return -1; + } + if (listen(fd, 16) < 0) { + close(fd); + return -1; + } + return fd; +} + +MOONBIT_FFI_EXPORT +int32_t mp_unix_accept(int32_t listen_fd) { + int fd = accept(listen_fd, NULL, NULL); + if (fd < 0) { + return -1; + } + set_nonblock_cloexec(fd); + return fd; +} + +MOONBIT_FFI_EXPORT +int32_t mp_unix_connect(moonbit_bytes_t path_bytes) { + char path[108]; + bytes_to_cstr(path_bytes, path, sizeof(path)); + + int fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) return -1; + + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); + + if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + close(fd); + return -1; + } + return fd; +} + +MOONBIT_FFI_EXPORT +int32_t mp_close_fd(int32_t fd) { + if (fd < 0) return 0; + return close(fd); +} + +MOONBIT_FFI_EXPORT +int32_t mp_unlink(moonbit_bytes_t path_bytes) { + char path[512]; + bytes_to_cstr(path_bytes, path, sizeof(path)); + return unlink(path); +} + +MOONBIT_FFI_EXPORT +int32_t mp_poll_read(int32_t fd, int32_t timeout_ms) { + struct pollfd pfd; + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + int r = poll(&pfd, 1, timeout_ms); + if (r < 0) return -1; + if (r == 0) return 0; + return (pfd.revents & (POLLIN | POLLHUP | POLLERR)) ? 1 : 0; +} + +MOONBIT_FFI_EXPORT +int32_t mp_recvmsg_fd(int32_t fd, moonbit_bytes_t buf, int32_t max_len, int32_t *out_fd) { + out_fd[0] = -1; + int32_t cap = Moonbit_array_length(buf); + int32_t n = max_len < cap ? max_len : cap; + if (n <= 0) return 0; + + struct iovec iov; + iov.iov_base = buf; + iov.iov_len = (size_t)n; + + char cmsg_buf[CMSG_SPACE(sizeof(int) * 4)]; + memset(cmsg_buf, 0, sizeof(cmsg_buf)); + + struct msghdr msg; + memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = cmsg_buf; + msg.msg_controllen = sizeof(cmsg_buf); + + ssize_t recvd = recvmsg(fd, &msg, 0); + if (recvd < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) return -1; + return -2; + } + + for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { + if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { + int *fds = (int *)CMSG_DATA(cmsg); + size_t num_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int); + if (num_fds > 0) { + out_fd[0] = fds[0]; + for (size_t i = 1; i < num_fds; i++) { + close(fds[i]); + } + } + } + } + return (int32_t)recvd; +} + +MOONBIT_FFI_EXPORT +int32_t mp_sendmsg_fd(int32_t fd, moonbit_bytes_t buf, int32_t len, int32_t send_fd) { + int32_t cap = Moonbit_array_length(buf); + int32_t n = len < cap ? len : cap; + if (n <= 0) return 0; + + struct iovec iov; + iov.iov_base = buf; + iov.iov_len = (size_t)n; + + char cmsg_buf[CMSG_SPACE(sizeof(int))]; + memset(cmsg_buf, 0, sizeof(cmsg_buf)); + + struct msghdr msg; + memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + + if (send_fd >= 0) { + msg.msg_control = cmsg_buf; + msg.msg_controllen = sizeof(cmsg_buf); + struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + memcpy(CMSG_DATA(cmsg), &send_fd, sizeof(int)); + } + + size_t total = 0; + while (total < (size_t)n) { + iov.iov_base = buf + total; + iov.iov_len = (size_t)n - total; + ssize_t sent = sendmsg(fd, &msg, MSG_NOSIGNAL); + if (sent < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 }; + poll(&pfd, 1, 50); + continue; + } + return -1; + } + total += (size_t)sent; + // Only send ancillary data on the first sendmsg call + msg.msg_control = NULL; + msg.msg_controllen = 0; + } + return (int32_t)total; +} + +MOONBIT_FFI_EXPORT +int32_t mp_memfd_create(moonbit_bytes_t name_bytes, int32_t size) { + char name[64]; + bytes_to_cstr(name_bytes, name, sizeof(name)); + int fd = memfd_create(name, MFD_CLOEXEC); + if (fd < 0) return -1; + if (size > 0 && ftruncate(fd, (off_t)size) < 0) { + close(fd); + return -1; + } + return fd; +} + +MOONBIT_FFI_EXPORT +int32_t mp_pwrite_bytes(int32_t fd, moonbit_bytes_t buf, int32_t len, int32_t offset) { + int32_t cap = Moonbit_array_length(buf); + int32_t n = len < cap ? len : cap; + ssize_t w = pwrite(fd, buf, (size_t)n, (off_t)offset); + return w < 0 ? -1 : (int32_t)w; +} + +MOONBIT_FFI_EXPORT +moonbit_bytes_t mp_mmap_read(int32_t fd, int32_t size) { + if (fd < 0 || size <= 0) { + return moonbit_make_bytes_raw(0); + } + struct stat st; + if (fstat(fd, &st) < 0 || st.st_size < (off_t)size) { + return moonbit_make_bytes_raw(0); + } + void *ptr = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED, fd, 0); + if (ptr == MAP_FAILED) { + return moonbit_make_bytes_raw(0); + } + moonbit_bytes_t out = moonbit_make_bytes_raw(size); + memcpy(out, ptr, (size_t)size); + munmap(ptr, (size_t)size); + return out; +} + +MOONBIT_FFI_EXPORT +moonbit_bytes_t mp_read_file(moonbit_bytes_t path_bytes) { + char path[512]; + bytes_to_cstr(path_bytes, path, sizeof(path)); + FILE *f = fopen(path, "rb"); + if (!f) return moonbit_make_bytes_raw(0); + fseek(f, 0, SEEK_END); + long sz = ftell(f); + if (sz <= 0) { + fclose(f); + return moonbit_make_bytes_raw(0); + } + fseek(f, 0, SEEK_SET); + moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)sz); + size_t rd = fread(out, 1, (size_t)sz, f); + fclose(f); + if (rd != (size_t)sz) { + return moonbit_make_bytes_raw(0); + } + return out; +} + +MOONBIT_FFI_EXPORT +int32_t mp_write_file(moonbit_bytes_t path_bytes, moonbit_bytes_t buf, int32_t len) { + char path[512]; + bytes_to_cstr(path_bytes, path, sizeof(path)); + int32_t cap = Moonbit_array_length(buf); + int32_t n = len < cap ? len : cap; + FILE *f = fopen(path, "wb"); + if (!f) return -1; + size_t wr = fwrite(buf, 1, (size_t)n, f); + fclose(f); + return wr == (size_t)n ? 0 : -1; +} + +MOONBIT_FFI_EXPORT +void mp_sleep_ms(int32_t ms) { + if (ms > 0) { + usleep((useconds_t)ms * 1000); + } +} + +MOONBIT_FFI_EXPORT +int32_t mp_getpid(void) { + return (int32_t)getpid(); +} diff --git a/compositor/wayland/moon.pkg b/compositor/wayland/moon.pkg new file mode 100644 index 0000000..de7c81b --- /dev/null +++ b/compositor/wayland/moon.pkg @@ -0,0 +1,7 @@ +import { + "moonbitlang/core/builtin", + "moonplasma/desktop/compositor/sys" @sys, + "moonplasma/desktop/compositor/scene" @scene, +} + +supported_targets = "-all+native" diff --git a/compositor/wayland/server.mbt b/compositor/wayland/server.mbt new file mode 100644 index 0000000..b2269df --- /dev/null +++ b/compositor/wayland/server.mbt @@ -0,0 +1,831 @@ +///| Pure-MoonBit Wayland server and protocol state machine. + +///| +pub(all) enum CompositorEvent { + ToplevelOpened(UInt64, String, String, Int, Int) + ToplevelUpdated(UInt64, String, String) + ToplevelCommitted(UInt64, @scene.ShmBufferSnapshot?) + ToplevelClosed(UInt64) + ToplevelMaximizeRequest(UInt64, Bool) + ToplevelFullscreenRequest(UInt64, Bool) + ToplevelMinimizeRequest(UInt64, Bool) + ToplevelMoveRequest(UInt64) +} + +///| +enum ObjKind { + ObjDisplay + ObjRegistry + ObjCompositor + ObjSurface(UInt) + ObjRegion + ObjShm + ObjShmPool(UInt) + ObjBuffer(UInt) + ObjXdgWmBase + ObjXdgPositioner + ObjXdgSurface(UInt) + ObjXdgToplevel(UInt64) + ObjXdgPopup + ObjDecoManager + ObjToplevelDeco(UInt64) + ObjSeat + ObjPointer + ObjKeyboard + ObjTouch + ObjOutput +} + +///| +struct ShmPoolState { + fd : Int + mut size : Int +} + +///| +struct ShmBufferState { + pool_id : UInt + offset : Int + width : Int + height : Int + stride : Int + format : Int +} + +///| +struct SurfaceState { + mut attached_buffer : UInt? + mut pending_frame_cb : UInt? + mut xdg_surface_id : UInt? + mut window_id : UInt64? +} + +///| +struct XdgSurfaceState { + wl_surface_id : UInt + mut window_id : UInt64? +} + +///| +struct ToplevelState { + win_id : UInt64 + wl_surface_id : UInt + xdg_surface_id : UInt + wl_toplevel_id : UInt + mut deco_obj_id : UInt? + mut title : String + mut app_id : String + mut min_w : Int + mut min_h : Int + mut opened_sent : Bool +} + +///| +struct ClientConn { + client_id : UInt + fd : Int + rx_buf : Array[Byte] + pending_fds : Array[Int] + objects : Map[UInt, ObjKind] + surfaces : Map[UInt, SurfaceState] + shm_pools : Map[UInt, ShmPoolState] + shm_buffers : Map[UInt, ShmBufferState] + xdg_surfaces : Map[UInt, XdgSurfaceState] + toplevels : Map[UInt64, ToplevelState] + mut alive : Bool +} + +///| +fn ClientConn::new(client_id : UInt, fd : Int) -> ClientConn { + let objects : Map[UInt, ObjKind] = {} + objects.set(1U, ObjDisplay) + { + client_id, + fd, + rx_buf: [], + pending_fds: [], + objects, + surfaces: {}, + shm_pools: {}, + shm_buffers: {}, + xdg_surfaces: {}, + toplevels: {}, + alive: true, + } +} + +///| +fn ClientConn::send_msg(self : ClientConn, msg : Bytes) -> Unit { + if self.alive { + let n = @sys.sendmsg_fd(self.fd, msg, -1) + if n < 0 { + self.alive = false + } + } +} + +///| +fn ClientConn::take_fd(self : ClientConn) -> Int { + if self.pending_fds.length() == 0 { + return -1 + } + self.pending_fds.remove(0) +} + +///| +fn ClientConn::close_all(self : ClientConn) -> Unit { + for _, pool in self.shm_pools { + @sys.close_fd(pool.fd) + } + for fd in self.pending_fds { + @sys.close_fd(fd) + } + @sys.close_fd(self.fd) +} + +///| +pub(all) struct WaylandServer { + socket_path : String + listen_fd : Int + output_w : Int + output_h : Int + clients : Array[ClientConn] + win_to_client : Map[UInt64, UInt] + mut next_client_id : UInt + mut next_win_id : UInt64 + mut next_serial : UInt +} + +///| +pub fn WaylandServer::listen( + socket_path : String, + output_w : Int, + output_h : Int, +) -> WaylandServer? { + let fd = @sys.unix_listen(socket_path) + if fd < 0 { + return None + } + Some({ + socket_path, + listen_fd: fd, + output_w, + output_h, + clients: [], + win_to_client: {}, + next_client_id: 1U, + next_win_id: 1UL, + next_serial: 100U, + }) +} + +///| +pub fn WaylandServer::close(self : WaylandServer) -> Unit { + for c in self.clients { + c.close_all() + } + self.clients.clear() + @sys.close_fd(self.listen_fd) + @sys.unlink(self.socket_path) +} + +///| +fn WaylandServer::next_serial(self : WaylandServer) -> UInt { + let s = self.next_serial + self.next_serial = self.next_serial + 1U + s +} + +///| +fn emit_registry_globals(c : ClientConn, reg_id : UInt) -> Unit { + let globals : Array[(UInt, String, UInt)] = [ + (1U, "wl_compositor", 5U), + (2U, "wl_shm", 1U), + (3U, "xdg_wm_base", 5U), + (4U, "zxdg_decoration_manager_v1", 1U), + (5U, "wl_seat", 7U), + (6U, "wl_output", 4U), + ] + for g in globals { + let w = WireWriter::new() + w.u32(g.0) + w.str(g.1) + w.u32(g.2) + c.send_msg(w.finish_msg(reg_id, 0U)) + } +} + +///| +fn emit_shm_formats(c : ClientConn, shm_id : UInt) -> Unit { + // ARGB8888 = 0, XRGB8888 = 1 + for fmt in [0U, 1U] { + let w = WireWriter::new() + w.u32(fmt) + c.send_msg(w.finish_msg(shm_id, 0U)) + } +} + +///| +fn emit_seat_info(c : ClientConn, seat_id : UInt) -> Unit { + let w1 = WireWriter::new() + w1.u32(3U) // pointer (1) | keyboard (2) + c.send_msg(w1.finish_msg(seat_id, 0U)) + + let w2 = WireWriter::new() + w2.str("seat0") + c.send_msg(w2.finish_msg(seat_id, 1U)) +} + +///| +fn emit_output_info( + c : ClientConn, + out_id : UInt, + w_px : Int, + h_px : Int, +) -> Unit { + let g = WireWriter::new() + g.i32(0) + g.i32(0) + g.i32(340) + g.i32(190) + g.i32(0) + g.str("MoonPlasma") + g.str("Virtual-1") + g.i32(0) + c.send_msg(g.finish_msg(out_id, 0U)) + + let m = WireWriter::new() + m.u32(3U) // current | preferred + m.i32(w_px) + m.i32(h_px) + m.i32(60000) + c.send_msg(m.finish_msg(out_id, 1U)) + + let s = WireWriter::new() + s.i32(1) + c.send_msg(s.finish_msg(out_id, 3U)) + + let d = WireWriter::new() + c.send_msg(d.finish_msg(out_id, 2U)) +} + +///| +fn send_delete_id(c : ClientConn, id : UInt) -> Unit { + let w = WireWriter::new() + w.u32(id) + c.send_msg(w.finish_msg(1U, 1U)) +} + +///| +fn send_decoration_mode(c : ClientConn, deco_id : UInt, mode : UInt) -> Unit { + let w = WireWriter::new() + w.u32(mode) // 2 = ServerSide + c.send_msg(w.finish_msg(deco_id, 0U)) +} + +///| +fn snapshot_shm_buffer( + c : ClientConn, + buf_id : UInt, +) -> @scene.ShmBufferSnapshot? { + let buf = match c.shm_buffers.get(buf_id) { + Some(b) => b + None => return None + } + let pool = match c.shm_pools.get(buf.pool_id) { + Some(p) => p + None => return None + } + let needed = buf.offset + buf.stride * buf.height + if needed <= 0 || buf.width <= 0 || buf.height <= 0 { + return None + } + let raw = @sys.mmap_read(pool.fd, needed) + if raw.length() < needed { + return None + } + let byte_len = buf.stride * buf.height + let slice = if buf.offset == 0 && raw.length() == byte_len { + raw + } else { + let arr : Array[Byte] = Array(capacity=byte_len) + for i = 0; i < byte_len; i = i + 1 { + arr.push(raw[buf.offset + i]) + } + Bytes::from_array(arr) + } + Some({ + width: buf.width, + height: buf.height, + stride: buf.stride, + format: buf.format, + bytes: slice, + }) +} + +///| +fn WaylandServer::dispatch_msg( + self : WaylandServer, + c : ClientConn, + obj_id : UInt, + opcode : UInt, + reader : WireReader, + events : Array[CompositorEvent], +) -> Unit { + let kind = match c.objects.get(obj_id) { + Some(k) => k + None => return + } + match kind { + ObjDisplay => + if opcode == 0U { + // sync(callback: new_id) + let cb_id = reader.u32() + let w = WireWriter::new() + w.u32(self.next_serial()) + c.send_msg(w.finish_msg(cb_id, 0U)) + send_delete_id(c, cb_id) + } else if opcode == 1U { + // get_registry(registry: new_id) + let reg_id = reader.u32() + c.objects.set(reg_id, ObjRegistry) + emit_registry_globals(c, reg_id) + } + ObjRegistry => + if opcode == 0U { + // bind(name: u32, interface: string, version: u32, id: new_id) + let _name = reader.u32() + let iface = reader.str() + let _ver = reader.u32() + let new_id = reader.u32() + if iface == "wl_compositor" { + c.objects.set(new_id, ObjCompositor) + } else if iface == "wl_shm" { + c.objects.set(new_id, ObjShm) + emit_shm_formats(c, new_id) + } else if iface == "xdg_wm_base" { + c.objects.set(new_id, ObjXdgWmBase) + } else if iface == "zxdg_decoration_manager_v1" { + c.objects.set(new_id, ObjDecoManager) + } else if iface == "wl_seat" { + c.objects.set(new_id, ObjSeat) + emit_seat_info(c, new_id) + } else if iface == "wl_output" { + c.objects.set(new_id, ObjOutput) + emit_output_info(c, new_id, self.output_w, self.output_h) + } + } + ObjCompositor => + if opcode == 0U { + // create_surface(id: new_id) + let sid = reader.u32() + c.objects.set(sid, ObjSurface(sid)) + c.surfaces.set(sid, { + attached_buffer: None, + pending_frame_cb: None, + xdg_surface_id: None, + window_id: None, + }) + } else if opcode == 1U { + let rid = reader.u32() + c.objects.set(rid, ObjRegion) + } + ObjSurface(sid) => + match c.surfaces.get(sid) { + None => () + Some(surf) => + if opcode == 0U { + // destroy + c.surfaces.remove(sid) + c.objects.remove(sid) + send_delete_id(c, sid) + } else if opcode == 1U { + // attach(buffer, x, y) + let buf_id = reader.u32() + let _x = reader.i32() + let _y = reader.i32() + surf.attached_buffer = if buf_id == 0U { + None + } else { + Some(buf_id) + } + } else if opcode == 3U { + // frame(callback) + let cb_id = reader.u32() + surf.pending_frame_cb = Some(cb_id) + } else if opcode == 6U { + // commit + match surf.window_id { + Some(wid) => + match c.toplevels.get(wid) { + Some(tl) => + if !tl.opened_sent { + tl.opened_sent = true + events.push( + ToplevelOpened( + wid, + tl.app_id, + tl.title, + tl.min_w, + tl.min_h, + ), + ) + } else { + let snap = match surf.attached_buffer { + Some(bid) => snapshot_shm_buffer(c, bid) + None => None + } + events.push(ToplevelCommitted(wid, snap)) + } + None => () + } + None => () + } + match surf.attached_buffer { + Some(bid) => { + // Notify client that compositor has copied/consumed the buffer + let rel = WireWriter::new() + c.send_msg(rel.finish_msg(bid, 0U)) + } + None => () + } + match surf.pending_frame_cb { + Some(cb_id) => { + surf.pending_frame_cb = None + let fw = WireWriter::new() + fw.u32(self.next_serial()) + c.send_msg(fw.finish_msg(cb_id, 0U)) + send_delete_id(c, cb_id) + } + None => () + } + } + } + ObjShm => + if opcode == 0U { + // create_pool(id: new_id, fd: out-of-band, size: i32) + let pool_id = reader.u32() + let size = reader.i32() + let fd = c.take_fd() + c.objects.set(pool_id, ObjShmPool(pool_id)) + if fd >= 0 { + c.shm_pools.set(pool_id, { fd, size }) + } + } + ObjShmPool(pool_id) => + if opcode == 0U { + // create_buffer(id, offset, width, height, stride, format) + let buf_id = reader.u32() + let offset = reader.i32() + let width = reader.i32() + let height = reader.i32() + let stride = reader.i32() + let format = reader.u32().reinterpret_as_int() + c.objects.set(buf_id, ObjBuffer(buf_id)) + c.shm_buffers.set(buf_id, { + pool_id, + offset, + width, + height, + stride, + format, + }) + } else if opcode == 1U { + // destroy + match c.shm_pools.get(pool_id) { + Some(p) => @sys.close_fd(p.fd) + None => () + } + c.shm_pools.remove(pool_id) + c.objects.remove(pool_id) + send_delete_id(c, pool_id) + } else if opcode == 2U { + // resize(size) + let new_sz = reader.i32() + match c.shm_pools.get(pool_id) { + Some(p) => p.size = new_sz + None => () + } + } + ObjBuffer(buf_id) => + if opcode == 0U { + c.shm_buffers.remove(buf_id) + c.objects.remove(buf_id) + send_delete_id(c, buf_id) + } + ObjXdgWmBase => + if opcode == 0U { + c.objects.remove(obj_id) + send_delete_id(c, obj_id) + } else if opcode == 1U { + let pos_id = reader.u32() + c.objects.set(pos_id, ObjXdgPositioner) + } else if opcode == 2U { + // get_xdg_surface(id, surface) + let xsid = reader.u32() + let wl_sid = reader.u32() + c.objects.set(xsid, ObjXdgSurface(xsid)) + c.xdg_surfaces.set(xsid, { wl_surface_id: wl_sid, window_id: None }) + match c.surfaces.get(wl_sid) { + Some(s) => s.xdg_surface_id = Some(xsid) + None => () + } + } + ObjXdgSurface(xsid) => + if opcode == 0U { + c.xdg_surfaces.remove(xsid) + c.objects.remove(xsid) + send_delete_id(c, xsid) + } else if opcode == 1U { + // get_toplevel(id) + let tl_id = reader.u32() + let wid = self.next_win_id + self.next_win_id = self.next_win_id + 1UL + let wl_sid = match c.xdg_surfaces.get(xsid) { + Some(xs) => { + xs.window_id = Some(wid) + xs.wl_surface_id + } + None => 0U + } + match c.surfaces.get(wl_sid) { + Some(s) => s.window_id = Some(wid) + None => () + } + c.objects.set(tl_id, ObjXdgToplevel(wid)) + c.toplevels.set(wid, { + win_id: wid, + wl_surface_id: wl_sid, + xdg_surface_id: xsid, + wl_toplevel_id: tl_id, + deco_obj_id: None, + title: "", + app_id: "", + min_w: 160, + min_h: 120, + opened_sent: false, + }) + self.win_to_client.set(wid, c.client_id) + } else if opcode == 2U { + let pid = reader.u32() + c.objects.set(pid, ObjXdgPopup) + } + ObjXdgToplevel(wid) => + match c.toplevels.get(wid) { + None => () + Some(tl) => + if opcode == 0U { + // destroy + c.toplevels.remove(wid) + self.win_to_client.remove(wid) + c.objects.remove(obj_id) + send_delete_id(c, obj_id) + events.push(ToplevelClosed(wid)) + } else if opcode == 2U { + // set_title + tl.title = reader.str() + if tl.opened_sent { + events.push(ToplevelUpdated(wid, tl.app_id, tl.title)) + } + } else if opcode == 3U { + // set_app_id + tl.app_id = reader.str() + if tl.opened_sent { + events.push(ToplevelUpdated(wid, tl.app_id, tl.title)) + } + } else if opcode == 5U { + // move + events.push(ToplevelMoveRequest(wid)) + } else if opcode == 8U { + // set_min_size + let mw = reader.i32() + let mh = reader.i32() + tl.min_w = if mw > 0 { mw } else { 160 } + tl.min_h = if mh > 0 { mh } else { 120 } + } else if opcode == 9U { + events.push(ToplevelMaximizeRequest(wid, true)) + } else if opcode == 10U { + events.push(ToplevelMaximizeRequest(wid, false)) + } else if opcode == 11U { + events.push(ToplevelFullscreenRequest(wid, true)) + } else if opcode == 12U { + events.push(ToplevelFullscreenRequest(wid, false)) + } else if opcode == 13U { + events.push(ToplevelMinimizeRequest(wid, true)) + } + } + ObjDecoManager => + if opcode == 0U { + c.objects.remove(obj_id) + send_delete_id(c, obj_id) + } else if opcode == 1U { + // get_toplevel_decoration(id, toplevel) + let deco_id = reader.u32() + let tl_obj = reader.u32() + let wid = match c.objects.get(tl_obj) { + Some(ObjXdgToplevel(w)) => w + _ => 0UL + } + c.objects.set(deco_id, ObjToplevelDeco(wid)) + match c.toplevels.get(wid) { + Some(tl) => tl.deco_obj_id = Some(deco_id) + None => () + } + // Negotiate Server-Side Decoration (2) + send_decoration_mode(c, deco_id, 2U) + } + ObjToplevelDeco(wid) => + if opcode == 0U { + c.objects.remove(obj_id) + send_delete_id(c, obj_id) + } else if opcode == 1U || opcode == 2U { + // Always enforce Server-Side Decoration (2) + ignore(wid) + send_decoration_mode(c, obj_id, 2U) + } + ObjSeat => + if opcode == 0U { + let pid = reader.u32() + c.objects.set(pid, ObjPointer) + } else if opcode == 1U { + let kid = reader.u32() + c.objects.set(kid, ObjKeyboard) + } else if opcode == 2U { + let tid = reader.u32() + c.objects.set(tid, ObjTouch) + } + _ => () + } +} + +///| Accept new clients, read incoming Wayland messages + SCM_RIGHTS fds, and emit CompositorEvents. +pub fn WaylandServer::poll_events( + self : WaylandServer, +) -> Array[CompositorEvent] { + let events : Array[CompositorEvent] = [] + + // Accept any pending connections + while true { + let cfd = @sys.unix_accept(self.listen_fd) + if cfd < 0 { + break + } + let cid = self.next_client_id + self.next_client_id = self.next_client_id + 1U + self.clients.push(ClientConn::new(cid, cfd)) + } + + // Read from each client + let scratch : FixedArray[Byte] = FixedArray::make(8192, b'\x00') + let disconnected : Array[Int] = [] + for idx = 0; idx < self.clients.length(); idx = idx + 1 { + let c = self.clients[idx] + while c.alive { + let (n, rfd) = @sys.recvmsg_fd(c.fd, scratch, 8192) + if rfd >= 0 { + c.pending_fds.push(rfd) + } + if n > 0 { + for i = 0; i < n; i = i + 1 { + c.rx_buf.push(scratch[i]) + } + } else if n == 0 { + c.alive = false + break + } else if n == -1 { + // EAGAIN + break + } else { + c.alive = false + break + } + } + + // Parse complete Wayland messages from rx_buf + let mut off = 0 + while off + 8 <= c.rx_buf.length() { + let obj_id = read_u32_le(c.rx_buf, off) + let word2 = read_u32_le(c.rx_buf, off + 4) + let size = ((word2 >> 16) & 0xFFFFU).reinterpret_as_int() + let opcode = word2 & 0xFFFFU + if size < 8 || off + size > c.rx_buf.length() { + break + } + let reader = WireReader::from_array(c.rx_buf, off + 8) + self.dispatch_msg(c, obj_id, opcode, reader, events) + off = off + size + } + if off > 0 { + let rem : Array[Byte] = [] + for i = off; i < c.rx_buf.length(); i = i + 1 { + rem.push(c.rx_buf[i]) + } + c.rx_buf.clear() + for b in rem { + c.rx_buf.push(b) + } + } + + if !c.alive { + disconnected.push(idx) + } + } + + // Clean up disconnected clients in reverse order + let mut j = disconnected.length() - 1 + while j >= 0 { + let idx = disconnected[j] + let c = self.clients.remove(idx) + for wid, _ in c.toplevels { + self.win_to_client.remove(wid) + events.push(ToplevelClosed(wid)) + } + c.close_all() + j = j - 1 + } + + events +} + +///| +fn WaylandServer::find_client(self : WaylandServer, cid : UInt) -> ClientConn? { + for c in self.clients { + if c.client_id == cid { + return Some(c) + } + } + None +} + +///| Send xdg_toplevel.configure + xdg_surface.configure to a client window. +pub fn WaylandServer::send_toplevel_configure( + self : WaylandServer, + win_id : UInt64, + width : Int, + height : Int, + activated : Bool, + maximized : Bool, + fullscreen : Bool, +) -> Unit { + let cid = match self.win_to_client.get(win_id) { + Some(id) => id + None => return + } + let c = match self.find_client(cid) { + Some(cc) => cc + None => return + } + let tl = match c.toplevels.get(win_id) { + Some(t) => t + None => return + } + + let states : Array[Byte] = [] + fn push_state(s : UInt) -> Unit { + states.push((s & 0xFFU).to_byte()) + states.push(((s >> 8) & 0xFFU).to_byte()) + states.push(((s >> 16) & 0xFFU).to_byte()) + states.push(((s >> 24) & 0xFFU).to_byte()) + } + if maximized { + push_state(1U) + } + if fullscreen { + push_state(2U) + } + if activated { + push_state(4U) + } + + let w1 = WireWriter::new() + w1.i32(width) + w1.i32(height) + w1.array(states) + c.send_msg(w1.finish_msg(tl.wl_toplevel_id, 0U)) + + let w2 = WireWriter::new() + w2.u32(self.next_serial()) + c.send_msg(w2.finish_msg(tl.xdg_surface_id, 0U)) +} + +///| +pub fn WaylandServer::send_toplevel_close( + self : WaylandServer, + win_id : UInt64, +) -> Unit { + let cid = match self.win_to_client.get(win_id) { + Some(id) => id + None => return + } + let c = match self.find_client(cid) { + Some(cc) => cc + None => return + } + match c.toplevels.get(win_id) { + Some(tl) => { + let w = WireWriter::new() + c.send_msg(w.finish_msg(tl.wl_toplevel_id, 1U)) + } + None => () + } +} diff --git a/compositor/wayland/wire.mbt b/compositor/wayland/wire.mbt new file mode 100644 index 0000000..9602c75 --- /dev/null +++ b/compositor/wayland/wire.mbt @@ -0,0 +1,143 @@ +///| Wayland binary wire protocol encoder and decoder in pure MoonBit. + +///| +pub(all) struct WireWriter { + buf : Array[Byte] +} + +///| +pub fn WireWriter::new() -> WireWriter { + { buf: [] } +} + +///| +pub fn WireWriter::u32(self : WireWriter, v : UInt) -> Unit { + self.buf.push((v & 0xFFU).to_byte()) + self.buf.push(((v >> 8) & 0xFFU).to_byte()) + self.buf.push(((v >> 16) & 0xFFU).to_byte()) + self.buf.push(((v >> 24) & 0xFFU).to_byte()) +} + +///| +pub fn WireWriter::i32(self : WireWriter, v : Int) -> Unit { + self.u32(v.reinterpret_as_uint()) +} + +///| +pub fn WireWriter::str(self : WireWriter, s : String) -> Unit { + let utf8 = @sys.str_to_utf8_bytes(s) + let len_with_nul = utf8.length() + 1 + self.u32(len_with_nul.reinterpret_as_uint()) + for i = 0; i < utf8.length(); i = i + 1 { + self.buf.push(utf8[i]) + } + self.buf.push(b'\x00') + while self.buf.length() % 4 != 0 { + self.buf.push(b'\x00') + } +} + +///| +pub fn WireWriter::array(self : WireWriter, data : Array[Byte]) -> Unit { + self.u32(data.length().reinterpret_as_uint()) + for b in data { + self.buf.push(b) + } + while self.buf.length() % 4 != 0 { + self.buf.push(b'\x00') + } +} + +///| +pub fn WireWriter::finish_msg(self : WireWriter, object_id : UInt, opcode : UInt) -> Bytes { + let total_len = 8 + self.buf.length() + let out : Array[Byte] = Array(capacity=total_len) + // object_id + out.push((object_id & 0xFFU).to_byte()) + out.push(((object_id >> 8) & 0xFFU).to_byte()) + out.push(((object_id >> 16) & 0xFFU).to_byte()) + out.push(((object_id >> 24) & 0xFFU).to_byte()) + // (size << 16) | opcode + let word2 = (total_len.reinterpret_as_uint() << 16) | (opcode & 0xFFFFU) + out.push((word2 & 0xFFU).to_byte()) + out.push(((word2 >> 8) & 0xFFU).to_byte()) + out.push(((word2 >> 16) & 0xFFU).to_byte()) + out.push(((word2 >> 24) & 0xFFU).to_byte()) + for b in self.buf { + out.push(b) + } + Bytes::from_array(out) +} + +///| +pub(all) struct WireReader { + data : Array[Byte] + mut pos : Int +} + +///| +pub fn WireReader::from_array(data : Array[Byte], start : Int) -> WireReader { + { data, pos: start } +} + +///| +pub fn WireReader::u32(self : WireReader) -> UInt { + if self.pos + 4 > self.data.length() { + return 0U + } + let b0 = self.data[self.pos].to_uint() + let b1 = self.data[self.pos + 1].to_uint() + let b2 = self.data[self.pos + 2].to_uint() + let b3 = self.data[self.pos + 3].to_uint() + self.pos = self.pos + 4 + b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) +} + +///| +pub fn WireReader::i32(self : WireReader) -> Int { + self.u32().reinterpret_as_int() +} + +///| +pub fn WireReader::str(self : WireReader) -> String { + let len = self.u32().reinterpret_as_int() + if len <= 0 || self.pos + len > self.data.length() { + return "" + } + let buf = StringBuilder::new() + // Exclude trailing NUL + let str_len = if len > 0 { len - 1 } else { 0 } + for i = 0; i < str_len; i = i + 1 { + let b = self.data[self.pos + i].to_int() + if b != 0 { + buf.write_char(Int::unsafe_to_char(b)) + } + } + let padded = (len + 3) / 4 * 4 + self.pos = self.pos + padded + buf.to_string() +} + +///| +pub fn WireReader::array(self : WireReader) -> Array[Byte] { + let len = self.u32().reinterpret_as_int() + let out : Array[Byte] = [] + if len <= 0 || self.pos + len > self.data.length() { + return out + } + for i = 0; i < len; i = i + 1 { + out.push(self.data[self.pos + i]) + } + let padded = (len + 3) / 4 * 4 + self.pos = self.pos + padded + out +} + +///| +pub fn read_u32_le(data : Array[Byte], off : Int) -> UInt { + let b0 = data[off].to_uint() + let b1 = data[off + 1].to_uint() + let b2 = data[off + 2].to_uint() + let b3 = data[off + 3].to_uint() + b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) +} diff --git a/docs/compositor-design.md b/docs/compositor-design.md index a818bcb..87df0d5 100644 --- a/docs/compositor-design.md +++ b/docs/compositor-design.md @@ -13,60 +13,51 @@ Traditional Wayland compositors (KWin, Sway, Mutter) bundle device management, W | Layer | Responsibility | Implementation | Trust Level | | :--- | :--- | :--- | :--- | -| **Host (Mechanism)** | `calloop` event loop, Wayland protocol server (Smithay), DRM/KMS & `libinput` (or nested `winit`), SHM/DMA-BUF memory, render-list & surface rasterizer, `wasmtime` engine + epoch/fuel supervision, capability broker | **Rust** (`host-native/`) | Trusted Computing Base (TCB) | -| **Components (Policy)** | Window placement, tiling/stacking, focus policy, hit-testing/input routing, window decorations, panel layout, desktop background, widgets, declarative scene effects | **MoonBit** (`wasm` linear-memory components via `wit-bindgen moonbit`) | Untrusted, capability-attenuated, hot-swappable | +| **Host (Mechanism)** | Event loop, Wayland binary wire protocol server (`wl_display`, `wl_registry`, `wl_compositor`, `wl_shm`, `xdg_wm_base`, `zxdg_decoration_manager_v1`, `wl_seat`, `wl_output`), SHM memory mapping, retained scene graph & damage tracker, ARGB8888 software rasterizer & PNG encoder, minimal POSIX C FFI (`compositor/sys/sys_stub.c`) | **MoonBit** (`compositor/` compiled with `--target native`) | Trusted Computing Base (TCB) | +| **Policy & Components** | Window placement, BSP tiling/floating/monocle layouts, focus policy, hit-testing/input routing, Breeze SSD decorations, panel layout, desktop background, widgets | **MoonBit** (`lib/wm/`, `lib/*`, and Wasm components `components/*` via `wit-bindgen moonbit`) | Modular policy packages & sandboxed Wasm components | ```mermaid flowchart TB - subgraph clients["Foreign Wayland / XWayland Clients"] - c1["App A (xdg_toplevel, wl_shm / dmabuf)"] - c2["App B (xdg_toplevel + xdg_popup)"] + subgraph clients["Foreign Wayland Clients"] + c1["App A (xdg_toplevel, wl_shm)"] + c2["App B (xdg_toplevel + zxdg_toplevel_decoration_v1)"] end - subgraph host["Trusted Host (Rust: smithay + wasmtime + calloop)"] - wl["Wayland Server (wl_compositor, xdg_wm_base, dmabuf, seat)"] - loop["calloop Event Loop + Epoch Watchdog"] - broker["Capability Broker & Component Supervisor"] - scene["Retained Scene Graph & Damage Tracker"] - ras["Dual-Path Rasterizer (GLES/wgpu + tiny-skia fallback)"] - be["Backend (Nested winit / DRM+KMS+libinput)"] + subgraph host["Pure MoonBit Compositor Host (compositor/ --target native)"] + wl["Wayland Wire Server (compositor/wayland/)"] + sys["POSIX C FFI Shim (compositor/sys/sys_stub.c: sockets, SCM_RIGHTS, memfd, mmap)"] + comp["Compositor Host (compositor/host/)"] + scene["Retained Scene Graph & Damage Tracker (compositor/scene/)"] + ras["ARGB8888 Software Rasterizer & PNG/PPM Encoder (compositor/renderer/)"] end - subgraph comps["Sandboxed MoonBit Components (.wasm)"] - wm["window-manager (wm-policy, input-router)"] - deco["decoration (titlebars, hit-regions)"] - shell["shell (desktop-surface, panel-layout)"] - widgets["plasmoids (launcher, clock, tray)"] - fx["effects (declarative transforms)"] + subgraph policy["MoonBit Policy & Wasm Components"] + wm["lib/wm (BSP tiling, Floating, Monocle, focus, hit-testing)"] + deco["Breeze SSD Decorations (compositor/scene + components/decoration-breeze)"] + shell["Shell & Plasmoids (lib/shell, components/*)"] end - clients -- "Wayland UNIX socket + fds" --> wl - wl -- "buffer-surface handles & events" --> loop - loop -- "bounded sync WIT calls" --> broker - broker <--> wm & deco & shell & widgets & fx - wm & deco & shell & widgets & fx -- "list<draw-op> + revision + actions" --> scene - wl -- "committed wl_surface buffers" --> scene - scene -- "damaged rects" --> ras --> be + clients -- "Wayland UNIX socket + SCM_RIGHTS fds" --> sys --> wl + wl -- "CompositorEvent" --> comp + comp <--> wm & deco & shell + comp -- "SceneGraph + DrawOps + ShmBufferSnapshot" --> scene --> ras ``` ### Design Invariants Carried Forward from M0 -1. **Components never touch raw pixels or GPU handles:** UI components emit `list` in local coordinates. Foreign Wayland clients write to host-owned `buffer-surface` resources; components only reference those opaque handles. -2. **Deny-by-default capabilities:** A component only receives the WIT imports declared in its world *and* explicitly granted in the session/desktop config. -3. **Fault isolation:** If `window-manager` or `decoration` traps or exceeds its frame time budget, `wasmtime` unwinds the call, the host logs a `ComponentFault`, renders a fallback tile / server-side border, and keeps scanning out at 60/120 Hz. +1. **100% MoonBit Stack (Zero Rust):** Both the native Wayland compositor host (`compositor/`) and the WM/decoration/shell/widget logic (`lib/*`, `components/*`) are written in MoonBit. Only a minimal POSIX C FFI shim (`compositor/sys/sys_stub.c`) wraps OS primitives (`AF_UNIX`, `poll`, `recvmsg`/`sendmsg` with `SCM_RIGHTS`, `memfd_create`, `mmap`/`munmap`). +2. **Components never touch raw pixels or GPU handles:** UI & decoration logic emit `DrawOp` lists in local coordinates; the MoonBit software rasterizer (`compositor/renderer/`) translates, clips, blends, and blits client `wl_shm` buffers. +3. **WIT Component Model Compatibility:** `components/*` continue to compile to WASI P2 `.wasm` components for `wit/` conformance and the JS/Wasm host (`host/`), while `lib/wm` runs natively inside `compositor/host/`. --- ## 2. Core Compositor Responsibilities -### 2.1 Wayland Protocol Handling (Host: `smithay`) -The host embeds Smithay to expose standard Wayland globals on `$XDG_RUNTIME_DIR/wayland-N`: -- **Core:** `wl_compositor` (v5+), `wl_subcompositor`, `wl_shm`, `wl_output`, `wl_seat` (pointer, keyboard, touch), `wl_data_device_manager` (clipboard & drag-and-drop). +### 2.1 Wayland Protocol Handling (`compositor/wayland/`) +The pure-MoonBit Wayland server implements the binary Wayland wire protocol directly over Unix domain sockets: +- **Core:** `wl_display`, `wl_registry`, `wl_callback`, `wl_compositor` (v5), `wl_surface`, `wl_region`, `wl_shm` (v1, `ARGB8888` / `XRGB8888` via `SCM_RIGHTS`), `wl_shm_pool`, `wl_buffer`, `wl_output` (v4), `wl_seat` (v7). - **Desktop Shells:** - - `xdg_wm_base` (`xdg_surface`, `xdg_toplevel`, `xdg_popup`) for application windows. - - `zxdg_decoration_manager_v1` (server-side decoration negotiation, defaulting to SSD via the `decoration` component). - - `zwlr_layer_shell_v1` (optional for external bars/lockscreens, though native `moon-plasma` panels are MoonBit components). -- **Buffers & Sync:** `zwp_linux_dmabuf_v1` (v4 with scanout/renderer tranche feedback), `wp_viewporter`, `wp_presentation_time`. -- **XWayland (M6+):** Rootless `Xwayland` managed by the host, mapping X11 windows into the exact same `WindowRegistry` so the MoonBit WM treats them identically to native Wayland clients. + - `xdg_wm_base` (`xdg_surface`, `xdg_toplevel`, `xdg_popup`, `xdg_positioner`) for application windows. + - `zxdg_decoration_manager_v1` / `zxdg_toplevel_decoration_v1` (server-side decoration negotiation, enforcing `ServerSide` mode with Breeze-style SSD). ### 2.2 Window & Surface Management (Split Host/WM) - **Host (`WindowRegistry`):** Owns the authoritative lifecycle of every `xdg_toplevel`, `xdg_popup`, and `Subsurface`, its committed `wl_buffer` (wrapped in a `buffer-surface` resource), its PID/app-id, and its pending `configure` serials. @@ -199,121 +190,86 @@ The host passes `last-known-revision: u64` into `render(size, last-rev)`. Static ## 4. Module Breakdown & Key Data Structures -### 4.1 Native Host (`host-native/` in Rust) +### 4.1 Native MoonBit Compositor (`compositor/`) ``` -host-native/ -├── Cargo.toml -└── src/ - ├── main.rs # CLI, session.json bootstrap, backend selection - ├── event_loop.rs # calloop integration (Wayland, input, vblank, timers) - ├── wayland/ - │ ├── mod.rs # Smithay State struct + delegate_*! macros - │ ├── xdg.rs # xdg_wm_base, toplevel/popup configure lifecycle - │ ├── dmabuf.rs # zwp_linux_dmabuf_v1 + EGL/wgpu import - │ └── seat.rs # wl_seat keyboard/pointer/clipboard forwarding - ├── wasm/ - │ ├── engine.rs # wasmtime::Engine (epoch interruption enabled) - │ ├── supervisor.rs # ComponentInstance, fault tracking, backoff restart - │ ├── broker.rs # Capability grants & WIT host trait impls - │ └── bindings.rs # wasmtime::component::bindgen! for moonplasma:* - ├── scene/ - │ ├── graph.rs # Layered SceneNode tree (BG -> Windows -> Panel -> Overlay) - │ ├── cache.rs # Revision-keyed compiled draw-op cache - │ └── damage.rs # Per-output dirty-region tracker - ├── renderer/ - │ ├── mod.rs # Renderer trait (render_scene, import_dmabuf, import_shm) - │ ├── gpu.rs # wgpu / Smithay GlowRenderer + vello/skia draw-op backend - │ └── software.rs # tiny-skia CPU fallback (CI / headless / dumb buffers) - └── backend/ - ├── nested.rs # winit window + EGL/software surface - └── drm.rs # udev + libseat + drm/gbm + libinput (M8) +compositor/ +├── sys/ # Minimal POSIX C FFI shim (supported_targets = "-all+native") +│ ├── moon.pkg # "native-stub": [ "sys_stub.c" ] +│ ├── sys_stub.c # AF_UNIX, poll, recvmsg/sendmsg SCM_RIGHTS, memfd_create, mmap +│ └── sys.mbt # MoonBit FFI bindings +├── wayland/ # Pure MoonBit Wayland binary wire protocol & server +│ ├── wire.mbt # WireWriter / WireReader (u32, i32, str, array, msg framing) +│ └── server.mbt # WaylandServer, wl_shm, xdg_wm_base, zxdg_decoration_manager_v1 +├── scene/ # Pure MoonBit retained scene graph & damage tracker +│ └── scene.mbt # ThemeTokens, SceneGraph, DamageTracker, Breeze SSD & shell ops +├── renderer/ # Pure MoonBit software rasterizer & encoders +│ ├── renderer.mbt # Pixmap, SrcOver blending, rounded rects, 5x7 font, shm blit, PNG/PPM +│ └── renderer_test.mbt # Unit tests (wasm + native) +├── host/ # Compositor host wiring WaylandServer + lib/wm + SceneGraph + Renderer +│ ├── compositor.mbt # MoonPlasmaCompositor +│ └── e2e_test.mbt # Native e2e Wayland client + SCM_RIGHTS + BSP/Floating + PNG test +└── bin/ # Standalone native compositor binary + └── main.mbt # CLI (--socket, --theme) ``` ### 4.2 MoonBit Components & Pure Libraries Following the existing `lib/*` + `components/*/gen/stub.mbt` split: -- `lib/wm/`: Pure MoonBit tiling/stacking/focus state machines (unit-tested with `moon test` using synthetic `WindowState`s, zero host dependencies). -- `lib/decoration/`: Pure MoonBit titlebar/border layout + hit-region math driven by `@theme.Tokens`. -- `components/wm-floating/` & `components/wm-tiling/`: Hot-swappable WM components implementing `moonplasma:wm/policy`. +- `lib/wm/`: Pure MoonBit tiling/stacking/focus state machines (unit-tested with `moon test` on both `wasm` and `native`). +- `components/wm-hybrid/`: Hybrid BSP tiling / Floating / Monocle WM component implementing `moonplasma:wm/policy`. - `components/decoration-breeze/`: Default server-side decoration component. --- -## 5. Event Loop & Async Model +## 5. Event Loop & Concurrency Model -As documented in `docs/TOOLCHAIN.md`, `moonbitlang/async` targets native/JS runtimes and is **not** WASI P3 component-model async; moreover, `jco` and `wit-bindgen-moonbit` do not yet share a uniform async ABI. - -Therefore, the compositor uses a **host-driven `calloop` event loop with epoch-bounded synchronous WIT calls**: - -1. **Single-Threaded `calloop` Reactor:** - - **Wayland source:** Reads client requests, processes `wl_surface.commit`, updates `WindowRegistry` and surface damage regions. - - **Input source:** `winit` events (nested) or `libinput` fd (DRM). - - **VBlank / Frame timer:** Fires on output refresh (or on-demand when dirty). - - **Component tick source:** Periodic 1 Hz / animation-rate timer that polls components for state changes (e.g., clock second rollover) without busy-spinning. -2. **Watchdog Thread (Epoch Interruption):** - - A lightweight background thread increments `wasmtime::Engine::increment_epoch()` every 1 ms. - - Before every WIT call (`wm.on_pointer`, `plasmoid.render`, `shell.compute_layout`), the host sets `store.set_epoch_deadline(4)` (4 ms budget). - - If a buggy component loops infinitely, `wasmtime` traps with `Interrupt`, the supervisor records a `ComponentFault`, and the compositor continues rendering the frame. +As documented in `docs/TOOLCHAIN.md`, `moonbitlang/async` targets native/JS runtimes and is **not** WASI P3 component-model async. In the pure-MoonBit native compositor (`compositor/host/`), `MoonPlasmaCompositor::step()` drives a non-blocking poll loop over the listening Unix socket and connected Wayland client fds, dispatching `CompositorEvent`s into `@wm.WmState` and updating `SceneGraph` + `DamageTracker` synchronously with zero thread contention. --- ## 6. Scene Graph, Damage Tracking & Rendering ### 6.1 Layered Scene Graph -Each output renders a 6-layer tree evaluated bottom-to-top: -1. **`Background`**: `shell.desktop-surface.render-background(output_size)` (cached by revision). -2. **`Bottom`**: `zwlr_layer_shell_v1` bottom-layer surfaces. -3. **`Windows`**: Iterated in `wm-policy.stacking-order()` order. Each window node composes: - - Drop shadow / focus ring (`draw-op`s) - - `decoration` component `list` (titlebar + borders) - - `buffer-surface` (main `xdg_toplevel` surface, clipped to geometry + corner radius) - - Child `wl_subsurface`s and `xdg_popup`s -4. **`Panel`**: `shell.panel-layout.render-panel` + each `plasmoid.render` placed at its `layout.placements` rect. -5. **`Overlay`**: Active widget popups (`plasmoid.popup`), notification toasts, launcher overlay, lock screen. -6. **`Cursor`**: Hardware DRM cursor plane (when available) or software cursor `draw-op`. +Each output renders a layered tree evaluated bottom-to-top: +1. **`Background`**: Desktop gradient (`build_shell_ops`). +2. **`Windows`**: Iterated in `wm.stacking_order()` order. Each window node composes: + - Drop shadow (`FillRect` with alpha) + - Breeze SSD decoration `DrawOp`s (titlebar + borders + window controls) + - Client `wl_shm` `ShmBufferSnapshot` (`ARGB8888` / `XRGB8888`) +3. **`Panel`**: Bottom panel + launcher + layout badge + window pills. +4. **`Overlay`**: Active widget popups and overlays. ### 6.2 Damage Tracking -- **Client Surface Damage:** `wl_surface.damage_buffer` regions are transformed into output-logical coordinates and unioned into `OutputDamage`. -- **Component Damage:** When a component returns `ops: some(...)` with a new `revision`, the host diffs the node's bounding box (old rect ∪ new rect) and adds it to `OutputDamage`. If `ops: none`, zero damage is emitted. -- **Scanout / Present:** The renderer clips drawing to `OutputDamage` and passes damaged rects to `eglSwapBuffersWithDamageKHR` (nested) or `DRM_MODE_PAGE_FLIP` with `FB_DAMAGE_CLIPS` (standalone). +- **Client Surface Damage:** `wl_surface.commit` marks the window geometry dirty in `DamageTracker`. +- **Layout / Focus Damage:** `WmAction`s mark full output damage and re-emit `xdg_toplevel.configure` + `xdg_surface.configure`. ### 6.3 Buffer Management & Rasterization -| Buffer / Op Kind | GPU Path (`GlowRenderer` / `wgpu`) | Software Fallback (`tiny-skia`) | -| :--- | :--- | :--- | -| `wl_shm` (`ARGB8888` / `XRGB8888`) | Uploaded to cached `GlesTexture` on commit (partial upload via damage rect) | Direct zero-copy slice read in CPU memory | -| `zwp_linux_dmabuf_v1` | Imported as `EGLImage` / `wgpu::Texture` (zero-copy); **direct scanout** on fullscreen opaque windows in M8 | Not advertised in `wl_drm`/`dmabuf` globals (clients fall back to `wl_shm`) | -| `list` (`fill-rect`, `stroke-rect`, `line`, `circle`, `text`, `push-clip`) | Compiled to GPU path/SDF/glyph-atlas draw calls (cached per revision) | Rasterized via `tiny-skia` + `cosmic-text` / `fontdue` | +- `wl_shm` (`ARGB8888` / `XRGB8888`): Mapped via `compositor/sys/sys_stub.c` (`mmap` + `memcpy` into MoonBit `Bytes` + `munmap`) and blitted by `compositor/renderer`. +- `DrawOp`s (`FillRect`, `StrokeRect`, `Line`, `Circle`, `Text`, `PushClip`, `PopClip`): Rasterized in pure MoonBit with Porter-Duff `SrcOver` alpha blending and encoded to PNG/PPM in pure MoonBit. --- ## 7. Phased Implementation Roadmap -Aligned directly with `docs/ARCHITECTURE.md` §11 (M3–M8): - | Phase | Milestone | Deliverable | Verification Gate | | :--- | :--- | :--- | :--- | -| **Phase 1** | **M3** | **Native Reference Host** (`host-native/` with `wasmtime` + `winit` + `tiny-skia`, fuel/epoch limits, supervisor). | Runs existing M0 components (`shell`, `launcher`, `clock-*`) and passes the same integration tests as `host/test/desktop.test.mjs`. | -| **Phase 2** | **M4** | **WM World & Synthetic Windows** (`moonplasma:wm/policy`, `decoration`, input routing in `wm`/`shell`). | Pure MoonBit `lib/wm` tests (`moon test`); hot-swap floating ↔ tiling WM on synthetic windows in both JS and Rust hosts. | -| **Phase 3** | **M5** | **Nested Wayland Compositor** (`smithay` `wl_shm` + `xdg_wm_base`, `buffer-surface` WIT resource, `composite-op`). | Launch real Wayland clients (`foot`, `weston-terminal`, `firefox`) inside nested `moon-plasma` window; verify focus, resize, popups, and fault isolation. | -| **Phase 4** | **M6–M7** | **GPU Rasterizer, DMA-BUF & Desktop Bridges** (`zwp_linux_dmabuf_v1`, damage-clipped GPU rendering, XWayland, `text` shaping interface, clipboard/D-Bus notification/tray bridges). | Hardware-accelerated video/WebGL clients at 60+ fps with zero-copy DMA-BUF; partial-damage redraws verified. | -| **Phase 5** | **M8** | **Standalone DRM/KMS Session** (`udev`, `libseat`, `drm`/`gbm`, `libinput`, `outputs` WIT interface, direct scanout, `login` world). | Boot directly from TTY into `moon-plasma`; multi-monitor hotplug and fullscreen direct scanout. | - +| **Phase 1** | **M3** | **Pure MoonBit Native Compositor** (`compositor/` with Wayland wire server, `lib/wm`, Breeze SSD, software rasterizer, PNG encoder). | `moon test --target native compositor/renderer compositor/host` passes e2e Wayland client + `SCM_RIGHTS` + BSP/Floating + PNG verification. | +| **Phase 2** | **M4** | **WM World & Components** (`moonplasma:wm/policy`, `decoration`, `components/wm-hybrid`, `components/decoration-breeze`). | `moon test` passes on `lib/wm`; `scripts/build-wm.sh` builds Wasm components cleanly. | +| **Phase 3** | **M5+** | **Interactive Input & Live Display Backend** (`wl_pointer` / `wl_keyboard` forwarding, DRM/KMS or nested X11/Wayland scanout). | Launch real Wayland clients (`foot`, `weston-terminal`) interactively. | --- ## 8. Window Manager (WM) Architecture -In `moon-plasma`, the **Window Manager is a pure policy component** (`world window-manager`) written in MoonBit, completely decoupled from Wayland wire serialization and GPU/DRM state. Because the host owns `WindowRegistry` and `SeatState`, the entire WM can be **hot-swapped at runtime** (e.g., `wm-floating` ↔ `wm-tiling`) without closing any running Wayland applications. +In `moon-plasma`, the **Window Manager is pure MoonBit policy** (`lib/wm/` and `components/wm-hybrid/`), completely decoupled from Wayland wire serialization and pixel rendering. ### 8.1 Integration with the Compositor & Wayland Protocols -The host translates Wayland protocol events into typed `moonplasma:wm` calls and applies the returned `list` back to Smithay: +`MoonPlasmaCompositor` translates Wayland protocol events into `lib/wm` calls and applies the returned `Array[WmAction]` back to `WaylandServer`: -| Wayland / Shell Event | Host (`smithay`) Action | WM (`wm-policy`) Role | +| Wayland / Shell Event | Compositor (`compositor/wayland`) Action | WM (`lib/wm`) Role | | :--- | :--- | :--- | -| `xdg_toplevel` first commit (mapped) | Creates `WindowId`, reads `app_id`, `title`, `min/max_size`, `parent` | `on-window-open(win, work_area)` → assigns workspace/output, computes initial geometry, sets focus | -| `xdg_toplevel` `set_maximized` / `set_fullscreen` / `move` / `resize` | Forwards request to WM | `on-window-request(id, req)` → approves/denies, updates state, emits `set-geometry` + `configure` | -| `xdg_popup` creation & grab | Host tracks `xdg_popup` parent chain & Wayland popup grab | WM stays unaware of transient popups; host clips/places them relative to parent window | -| `zwlr_layer_shell_v1` / `shell.panel-layout` | Host computes reserved `exclusive_zone`s per output | Host passes `work_area: rect` (output minus panels/layer-shell margins) to WM | -| `xdg_toplevel` unmap / destroy | Removes from `WindowRegistry` | `on-window-close(id)` → reflows tiling tree, promotes next MRU window to focus | +| `xdg_toplevel` first commit (mapped) | Assigns `win_id`, reads `app_id`, `title`, `min_size` | `open_window(rec, work_area)` → assigns workspace, computes BSP/floating geometry, sets focus | +| `xdg_toplevel` `set_maximized` / `set_fullscreen` / `set_minimized` | Forwards `Toplevel*Request` to host | `handle_request(id, req, work_area)` → updates state, emits `SetGeometry` + `configure` | +| `xdg_toplevel` unmap / destroy | Removes from `WindowRegistry` | `close_window(id, work_area)` → reflows BSP tree, promotes next MRU window to focus | ### 8.2 Hybrid Layout Engine (Tiling + Floating + Monocle) The reference WM (`lib/wm/`) implements a **per-workspace hybrid layout engine** so a single component supports both KDE-style floating windows and Sway/Hyprland-style tiling: @@ -409,4 +365,4 @@ pub struct WmState { mut focused : UInt64? } ``` -All layout math (`compute_bsp_rects`, `insert_leaf`, `remove_leaf`, `focus_direction`, `hit_test_stack`) lives in `lib/wm/` as pure functions over `WmState`, unit-tested via `moon test` before any Rust host integration. +All layout math (`compute_bsp_rects`, `insert_leaf`, `remove_leaf`, `focus_direction`, `hit_test_stack`) lives in `lib/wm/` as pure functions over `WmState`, unit-tested via `moon test` and integrated directly into `compositor/host/`. diff --git a/host-native/Cargo.lock b/host-native/Cargo.lock deleted file mode 100644 index 49a2bbd..0000000 --- a/host-native/Cargo.lock +++ /dev/null @@ -1,2012 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59317f77929f0e679d39364702289274de2f0f0b22cbf50b2b8cff2169a0b27a" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "allocator-api2" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anyhow" -version = "1.0.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" - -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" - -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bumpalo" -version = "3.20.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" -dependencies = [ - "allocator-api2", -] - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" - -[[package]] -name = "cc" -version = "1.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "cobs" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" -dependencies = [ - "thiserror", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - -[[package]] -name = "core_maths" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" -dependencies = [ - "libm", -] - -[[package]] -name = "cpp_demangle" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0667304c32ea56cb4cd6d2d7c0cfe9a2f8041229db8c033af7f8d69492429def" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cranelift-assembler-x64" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "222b23ccf36fe36ee1b99adff2510bd3762cb47e7332542dd4e1cb9c3c84cbbb" -dependencies = [ - "cranelift-assembler-x64-meta", -] - -[[package]] -name = "cranelift-assembler-x64-meta" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "952c71136beac218e5080b31797dcf74a0aa36a12d32eba4583606ed4825dfe5" -dependencies = [ - "cranelift-srcgen", -] - -[[package]] -name = "cranelift-bforest" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86ad6c0ef2b5f29d768c64107114579e53cbff031f73e7980460dd7b76be6cb3" -dependencies = [ - "cranelift-entity", - "wasmtime-internal-core", -] - -[[package]] -name = "cranelift-bitset" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f087c2d93f5f0a084213d61c1b3ba66530cbfc25a44dc9e9c058d6b542b110f" -dependencies = [ - "serde", - "serde_derive", - "wasmtime-internal-core", -] - -[[package]] -name = "cranelift-codegen" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c21e04ef21284a7e1ee65bc8440e78bc63a1b500964978902ab3b0b05969ae3" -dependencies = [ - "bumpalo", - "cranelift-assembler-x64", - "cranelift-bforest", - "cranelift-bitset", - "cranelift-codegen-meta", - "cranelift-codegen-shared", - "cranelift-control", - "cranelift-entity", - "cranelift-isle", - "gimli", - "hashbrown 0.17.2", - "libm", - "log", - "postcard", - "pulley-interpreter", - "regalloc2", - "rustc-hash", - "serde", - "serde_derive", - "sha2", - "smallvec", - "target-lexicon", - "wasmtime-internal-core", -] - -[[package]] -name = "cranelift-codegen-meta" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b3d4b111ce054571a6985bbff37c55aab40a04b968da00b3807675cec8c095" -dependencies = [ - "cranelift-assembler-x64-meta", - "cranelift-codegen-shared", - "cranelift-srcgen", - "heck", - "pulley-interpreter", -] - -[[package]] -name = "cranelift-codegen-shared" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e1aaed1dcf216d6eb0916982edd34403d21d5df9f360528e7a2b85203d760a7" - -[[package]] -name = "cranelift-control" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff1d071a686ae206a65ecc9a498d16d6926ecb6120f434c618de8cdccd255ae7" -dependencies = [ - "arbitrary", -] - -[[package]] -name = "cranelift-entity" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a51ab5d8ff3bbc6b7df0a3d3c6740e9af488fb5d38654ce1595f598d3da21456" -dependencies = [ - "cranelift-bitset", - "serde", - "serde_derive", - "wasmtime-internal-core", -] - -[[package]] -name = "cranelift-frontend" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e025bb120162a1b60d010bbc3237ac1b99b466702b5ae42a974e91afcb9725" -dependencies = [ - "cranelift-codegen", - "hashbrown 0.17.2", - "log", - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cranelift-isle" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bbcbc8f5ef440b5583ed19889b071cbac376b2b8f311d30fc95880876909df3" - -[[package]] -name = "cranelift-native" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "535c9b6e5695d2afc1e14c69003d67890b743f695ef23c14124d21b8b67603a7" -dependencies = [ - "cranelift-codegen", - "libc", - "mach2", - "target-lexicon", -] - -[[package]] -name = "cranelift-srcgen" -version = "0.138.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1f395483422e6a1961f5e07cc8e200391f3766a5b33b240303c65b301df857c" - -[[package]] -name = "crc32fast" -version = "1.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "debugid" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" -dependencies = [ - "uuid", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", -] - -[[package]] -name = "directories" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys", -] - -[[package]] -name = "downcast-rs" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" - -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" - -[[package]] -name = "embedded-io" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" - -[[package]] -name = "embedded-io" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" - -[[package]] -name = "encoding_rs" -version = "0.8.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" -dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", -] - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "errno" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" - -[[package]] -name = "fixedbitset" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" - -[[package]] -name = "flate2" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" -dependencies = [ - "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "fontdue" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e796cb6894e6418daacea84b28dd4f98d3b32c74d5bb452ba1ecfbf5ad8e84ca" -dependencies = [ - "hashbrown 0.15.5", - "ttf-parser", -] - -[[package]] -name = "futures" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "fxprof-processed-profile" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25234f20a3ec0a962a61770cfe39ecf03cb529a6e474ad8cff025ed497eda557" -dependencies = [ - "bitflags 2.13.2", - "debugid", - "rustc-hash", - "serde", - "serde_derive", - "serde_json", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "libc", - "r-efi", -] - -[[package]] -name = "gimli" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" -dependencies = [ - "fnv", - "hashbrown 0.16.1", - "indexmap", - "stable_deref_trait", -] - -[[package]] -name = "hashbrown" -version = "0.15.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash 0.1.5", -] - -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" - -[[package]] -name = "hashbrown" -version = "0.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" -dependencies = [ - "foldhash 0.2.0", - "serde", - "serde_core", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown 0.17.2", - "serde", - "serde_core", -] - -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - -[[package]] -name = "ittapi" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b996fe614c41395cdaedf3cf408a9534851090959d90d54a535f675550b64b1" -dependencies = [ - "anyhow", - "ittapi-sys", - "log", -] - -[[package]] -name = "ittapi-sys" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5385394064fa2c886205dba02598013ce83d3e92d33dbdc0c52fe0e7bf4fc" -dependencies = [ - "cc", -] - -[[package]] -name = "jobserver" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" -dependencies = [ - "getrandom", - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "libredox" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" -dependencies = [ - "libc", -] - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" - -[[package]] -name = "mach2" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "memfd" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" -dependencies = [ - "rustix", -] - -[[package]] -name = "memmap2" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" -dependencies = [ - "libc", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "moon-plasma-host" -version = "0.2.0" -dependencies = [ - "anyhow", - "chrono", - "fontdue", - "memmap2", - "png", - "serde", - "serde_json", - "tempfile", - "tiny-skia", - "wasmtime", - "wayland-client", - "wayland-protocols", - "wayland-server", -] - -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "object" -version = "0.40.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" -dependencies = [ - "crc32fast", - "hashbrown 0.17.2", - "indexmap", - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - -[[package]] -name = "petgraph" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" -dependencies = [ - "fixedbitset", - "indexmap", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" - -[[package]] -name = "pkg-config" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" - -[[package]] -name = "png" -version = "0.17.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "postcard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5431b3dcfdf6d1985c87d11f267a171c0dec0a8cd544c6727b747d36365f1fca" -dependencies = [ - "cobs", - "embedded-io 0.4.0", - "embedded-io 0.6.1", - "serde", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pulley-interpreter" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88041152fc3b051ca485e63b8d6af0b011a245db84b2825a37535eff8522ca71" -dependencies = [ - "cranelift-bitset", - "log", - "pulley-macros", - "wasmtime-internal-core", -] - -[[package]] -name = "pulley-macros" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "604be86dfb7018c1c487e683e495f07bc7a4eeb3e1d35bba27d294a4c74464b7" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "quick-xml" -version = "0.41.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" -dependencies = [ - "memchr", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rayon" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "redox_users" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" -dependencies = [ - "libredox", - "thiserror", -] - -[[package]] -name = "regalloc2" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34f923657880712029496c2e68bb40bef163806b2011adde559b28bbcedc82ea" -dependencies = [ - "allocator-api2", - "bumpalo", - "hashbrown 0.17.2", - "log", - "rustc-hash", - "serde", - "smallvec", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustix" -version = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys", - "windows-sys", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_spanned" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" -dependencies = [ - "serde_core", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" -dependencies = [ - "serde", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "strict-num" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "target-lexicon" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom", - "once_cell", - "rustix", - "windows-sys", -] - -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "thiserror" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "tiny-skia" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" -dependencies = [ - "arrayref", - "arrayvec", - "bytemuck", - "cfg-if", - "log", - "png", - "tiny-skia-path", -] - -[[package]] -name = "tiny-skia-path" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" -dependencies = [ - "arrayref", - "bytemuck", - "strict-num", -] - -[[package]] -name = "toml" -version = "1.2.2+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" -dependencies = [ - "indexmap", - "serde_core", - "serde_spanned", - "toml_datetime", - "toml_parser", - "toml_writer", - "winnow", -] - -[[package]] -name = "toml_datetime" -version = "1.1.3+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" -dependencies = [ - "serde_core", -] - -[[package]] -name = "toml_parser" -version = "1.1.6+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" -dependencies = [ - "winnow", -] - -[[package]] -name = "toml_writer" -version = "1.2.0+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" - -[[package]] -name = "ttf-parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" -dependencies = [ - "core_maths", -] - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "unicode-width" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" - -[[package]] -name = "uuid" -version = "1.29.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wasm-bindgen" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" -dependencies = [ - "cfg-if", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.10", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-compose" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "556cf3f0ea89f5944d254f94fcda920e3e6f79d892dc8558dfee493e52d775b4" -dependencies = [ - "anyhow", - "indexmap", - "log", - "petgraph", - "smallvec", - "wasm-encoder", - "wasmparser", - "wat", -] - -[[package]] -name = "wasm-encoder" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8997a297f42413bee775d73a750def062ee1ec4a6d904703cb08046c0296774d" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb" -dependencies = [ - "bitflags 2.13.2", - "hashbrown 0.17.2", - "indexmap", - "semver", - "serde", -] - -[[package]] -name = "wasmprinter" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b40c3aedc383a68866a7bae302578765c3f05c9e11ea6d242e5cc450f8300a26" -dependencies = [ - "anyhow", - "termcolor", - "wasmparser", -] - -[[package]] -name = "wasmtime" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d821735a5b127d45a1777bd8eeb8a97d5f66ea1e2c93b8d71f9037f6fd910ef2" -dependencies = [ - "addr2line", - "async-trait", - "bitflags 2.13.2", - "bumpalo", - "cc", - "encoding_rs", - "futures", - "fxprof-processed-profile", - "gimli", - "indexmap", - "ittapi", - "libc", - "log", - "mach2", - "memfd", - "object", - "once_cell", - "postcard", - "pulley-interpreter", - "rayon", - "rustix", - "semver", - "serde", - "serde_derive", - "serde_json", - "smallvec", - "target-lexicon", - "wasm-compose", - "wasm-encoder", - "wasmparser", - "wasmtime-environ", - "wasmtime-internal-cache", - "wasmtime-internal-component-macro", - "wasmtime-internal-component-util", - "wasmtime-internal-core", - "wasmtime-internal-cranelift", - "wasmtime-internal-fiber", - "wasmtime-internal-jit-debug", - "wasmtime-internal-jit-icache-coherence", - "wasmtime-internal-unwinder", - "wasmtime-internal-versioned-export-macros", - "wat", - "windows-sys", - "wit-parser", -] - -[[package]] -name = "wasmtime-environ" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c1bfdccfa80c735f83559a2dcad18b8510b2b49322151af5830f3ebcd3365e7" -dependencies = [ - "anyhow", - "cpp_demangle", - "cranelift-bforest", - "cranelift-bitset", - "cranelift-entity", - "gimli", - "hashbrown 0.17.2", - "indexmap", - "log", - "object", - "postcard", - "rustc-demangle", - "semver", - "serde", - "serde_derive", - "smallvec", - "target-lexicon", - "wasm-encoder", - "wasmparser", - "wasmprinter", - "wasmtime-internal-component-util", - "wasmtime-internal-core", -] - -[[package]] -name = "wasmtime-internal-cache" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9054eda7bf9f4db325851eacc2bf2b73afd14e5cb0fdf95910492ea0df384996" -dependencies = [ - "base64", - "directories", - "log", - "postcard", - "rustix", - "serde", - "serde_derive", - "sha2", - "toml", - "wasmtime-environ", - "windows-sys", - "zstd", -] - -[[package]] -name = "wasmtime-internal-component-macro" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46991631dcc41f74783fc8cf3fa1d6f5684a676fdc67ab5710731e48d4a4e183" -dependencies = [ - "anyhow", - "proc-macro2", - "quote", - "syn 3.0.10", - "wasmtime-internal-component-util", - "wasmtime-internal-wit-bindgen", - "wit-parser", -] - -[[package]] -name = "wasmtime-internal-component-util" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df5c080e39583056af5ed1a31d3909f35abc4d9b39b99dd90d944aae5e881844" - -[[package]] -name = "wasmtime-internal-core" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd7abb27d389eee2f4e477c25d40a47bb837a08571bf0262c07aebe634e28774" -dependencies = [ - "anyhow", - "hashbrown 0.17.2", - "libm", - "serde", -] - -[[package]] -name = "wasmtime-internal-cranelift" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54a3749d4a805123e309490126076aaa569cb4d1a14b8c5427c12581872b5dd9" -dependencies = [ - "cranelift-codegen", - "cranelift-control", - "cranelift-entity", - "cranelift-frontend", - "cranelift-native", - "gimli", - "itertools", - "log", - "object", - "pulley-interpreter", - "smallvec", - "target-lexicon", - "thiserror", - "wasmparser", - "wasmtime-environ", - "wasmtime-internal-core", - "wasmtime-internal-unwinder", - "wasmtime-internal-versioned-export-macros", -] - -[[package]] -name = "wasmtime-internal-fiber" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a8568765ad037ed2f932f973d07bcf2f8a9dfa4d3e8551f1b3316b89e2e234a" -dependencies = [ - "cc", - "libc", - "rustix", - "wasmtime-environ", - "wasmtime-internal-versioned-export-macros", - "windows-sys", -] - -[[package]] -name = "wasmtime-internal-jit-debug" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57b1160c1cf0a385348edc2aebaf68c12eedde551b3733d66c1d6ff92c4364e2" -dependencies = [ - "cc", - "object", - "rustix", - "wasmtime-internal-versioned-export-macros", -] - -[[package]] -name = "wasmtime-internal-jit-icache-coherence" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99bd6ba74430c9557a7ef8639f9b974cbdd52f8c1d07f2a61dc1b882e2d3b5be" -dependencies = [ - "libc", - "wasmtime-internal-core", - "windows-sys", -] - -[[package]] -name = "wasmtime-internal-unwinder" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0896123c430d063ba957dbe4c937740d3368c4877ecb208990d8f214cf1c4a9" -dependencies = [ - "cranelift-codegen", - "log", - "object", - "wasmtime-environ", -] - -[[package]] -name = "wasmtime-internal-versioned-export-macros" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "983bf354b2639caef97cce4cacd445298b3c5c1e1021c8dbc1a162d9085c04de" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "wasmtime-internal-wit-bindgen" -version = "51.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c48fd824219316d39b0fa67a21329ad8f8940bf851fd726641a0a7bf1fbb9b35" -dependencies = [ - "anyhow", - "bitflags 2.13.2", - "heck", - "indexmap", - "wit-component", - "wit-parser", -] - -[[package]] -name = "wast" -version = "263.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7" -dependencies = [ - "bumpalo", - "leb128fmt", - "memchr", - "unicode-width", - "wasm-encoder", -] - -[[package]] -name = "wat" -version = "1.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7" -dependencies = [ - "wast", -] - -[[package]] -name = "wayland-backend" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" -dependencies = [ - "cc", - "downcast-rs", - "rustix", - "smallvec", - "wayland-sys", -] - -[[package]] -name = "wayland-client" -version = "0.31.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" -dependencies = [ - "bitflags 2.13.2", - "rustix", - "wayland-backend", - "wayland-scanner", -] - -[[package]] -name = "wayland-protocols" -version = "0.32.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" -dependencies = [ - "bitflags 2.13.2", - "wayland-backend", - "wayland-client", - "wayland-scanner", - "wayland-server", -] - -[[package]] -name = "wayland-scanner" -version = "0.31.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" -dependencies = [ - "proc-macro2", - "quick-xml", - "quote", -] - -[[package]] -name = "wayland-server" -version = "0.31.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" -dependencies = [ - "bitflags 2.13.2", - "downcast-rs", - "rustix", - "wayland-backend", - "wayland-scanner", -] - -[[package]] -name = "wayland-sys" -version = "0.31.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" -dependencies = [ - "pkg-config", -] - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "winnow" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" - -[[package]] -name = "wit-component" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4189bd180353b942b788715519dff886517b540e648c6f6e5129f57429945bf7" -dependencies = [ - "anyhow", - "bitflags 2.13.2", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "874d6ce9db4261cb66980ab14f3da066b24292497b6f46f988c0d1b9b27913f3" -dependencies = [ - "anyhow", - "hashbrown 0.17.2", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-ident", - "wasmparser", -] - -[[package]] -name = "zlib-rs" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" - -[[package]] -name = "zstd" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" -dependencies = [ - "zstd-safe", -] - -[[package]] -name = "zstd-safe" -version = "8.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" -dependencies = [ - "zstd-sys", -] - -[[package]] -name = "zstd-sys" -version = "2.2.0+zstd.1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" -dependencies = [ - "cc", - "pkg-config", -] diff --git a/host-native/Cargo.toml b/host-native/Cargo.toml deleted file mode 100644 index dc2005b..0000000 --- a/host-native/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "moon-plasma-host" -version = "0.2.0" -edition = "2021" -description = "Native Rust Wayland compositor & wasmtime host for moon-plasma" - -[dependencies] -anyhow = "1.0" -chrono = "0.4" -fontdue = "0.9" -memmap2 = "0.9" -png = "0.17" -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -tiny-skia = "0.11" -wasmtime = { version = "51.0", features = ["component-model"] } -wayland-server = "0.31" -wayland-protocols = { version = "0.32", features = ["server", "staging", "unstable"] } - -[dev-dependencies] -tempfile = "3.14" -wayland-client = "0.31" -wayland-protocols = { version = "0.32", features = ["client", "server", "staging", "unstable"] } diff --git a/host-native/src/compositor.rs b/host-native/src/compositor.rs deleted file mode 100644 index 7e8e115..0000000 --- a/host-native/src/compositor.rs +++ /dev/null @@ -1,516 +0,0 @@ -use std::collections::HashMap; -use std::path::Path; - -use tiny_skia::Pixmap; - -use crate::renderer::SoftwareRenderer; -use crate::scene::{ - DamageTracker, DrawOp, PanelWidgetNode, Rect, SceneGraph, ShmBufferSnapshot, TextAlign, - WindowSceneNode, -}; -use crate::theme::{Rgba, ThemeTokens}; -use crate::wasm::{clock_wit, deco_wit, desktop_wit, launcher_wit, wm_wit, WasmSupervisor}; -use crate::wayland::{WaylandEvent, WaylandServer}; - -#[derive(Debug, Clone)] -pub struct HostWindow { - pub id: u64, - pub app_id: String, - pub title: String, - pub geometry: Rect, - pub min_size: (u32, u32), - pub max_size: Option<(u32, u32)>, - pub focused: bool, - pub maximized: bool, - pub fullscreen: bool, - pub workspace: u32, - pub surface: Option, -} - -pub struct MoonPlasmaCompositor { - pub output_size: (u32, u32), - pub wayland: WaylandServer, - pub wasm: WasmSupervisor, - pub renderer: SoftwareRenderer, - pub damage: DamageTracker, - pub windows: HashMap, - pub panel_rect: Rect, - pub work_area: Rect, -} - -impl MoonPlasmaCompositor { - pub fn new( - socket_path: &Path, - components_dir: &Path, - theme: ThemeTokens, - output_w: u32, - output_h: u32, - ) -> anyhow::Result { - let wayland = WaylandServer::bind(socket_path, output_w, output_h)?; - let wasm = WasmSupervisor::load_from_dir(components_dir, theme)?; - let renderer = SoftwareRenderer::new(); - let mut damage = DamageTracker::default(); - damage.mark_full(); - - let panel_h = 44; - let panel_rect = Rect::new(0, (output_h - panel_h) as i32, output_w, panel_h); - let work_area = Rect::new(0, 0, output_w, output_h - panel_h); - - Ok(Self { - output_size: (output_w, output_h), - wayland, - wasm, - renderer, - damage, - windows: HashMap::new(), - panel_rect, - work_area, - }) - } - - pub fn step(&mut self) -> anyhow::Result<()> { - self.wayland.dispatch()?; - let events: Vec = self.wayland.state.events.drain(..).collect(); - for evt in events { - match evt { - WaylandEvent::ToplevelOpened { - window_id, - app_id, - title, - min_w, - min_h, - max_w, - max_h, - } => { - let hw = HostWindow { - id: window_id, - app_id: app_id.clone(), - title: title.clone(), - geometry: Rect::new(0, 0, 0, 0), - min_size: (min_w, min_h), - max_size: max_w.zip(max_h), - focused: true, - maximized: false, - fullscreen: false, - workspace: 0, - surface: None, - }; - self.windows.insert(window_id, hw.clone()); - let wit_win = to_wm_window(&hw); - let wa = to_wm_rect(self.work_area); - self.wasm.wm_store.set_epoch_deadline(20); - match self - .wasm - .wm - .moonplasma_wm_policy() - .call_on_window_open(&mut self.wasm.wm_store, &wit_win, wa) - { - Ok(actions) => self.apply_wm_actions(&actions), - Err(e) => self.wasm.record_fault("wm-hybrid", "on_window_open", e), - } - self.damage.mark_full(); - } - WaylandEvent::ToplevelClosed { window_id } => { - self.windows.remove(&window_id); - self.wasm.wm_store.set_epoch_deadline(20); - match self - .wasm - .wm - .moonplasma_wm_policy() - .call_on_window_close(&mut self.wasm.wm_store, window_id) - { - Ok(actions) => self.apply_wm_actions(&actions), - Err(e) => self.wasm.record_fault("wm-hybrid", "on_window_close", e), - } - self.damage.mark_full(); - } - WaylandEvent::SurfaceCommitted { window_id, buffer } => { - if let Some(hw) = self.windows.get_mut(&window_id) { - hw.surface = buffer; - self.damage.add_rect(hw.geometry); - } - } - WaylandEvent::ToplevelRequest { - window_id, - maximize, - fullscreen, - } => { - let req = if let Some(m) = maximize { - Some(wm_wit::exports::moonplasma::wm::policy::WindowRequest::Maximize(m)) - } else { - fullscreen.map(wm_wit::exports::moonplasma::wm::policy::WindowRequest::Fullscreen) - }; - if let Some(r) = req { - let wa = to_wm_rect(self.work_area); - self.wasm.wm_store.set_epoch_deadline(20); - match self.wasm.wm.moonplasma_wm_policy().call_on_window_request( - &mut self.wasm.wm_store, - window_id, - r, - wa, - ) { - Ok(actions) => self.apply_wm_actions(&actions), - Err(e) => self.wasm.record_fault("wm-hybrid", "on_window_request", e), - } - self.damage.mark_full(); - } - } - } - } - Ok(()) - } - - pub fn set_layout_mode(&mut self, mode: wm_wit::exports::moonplasma::wm::policy::LayoutMode) { - let wa = to_wm_rect(self.work_area); - self.wasm.wm_store.set_epoch_deadline(20); - match self.wasm.wm.moonplasma_wm_policy().call_set_layout_mode( - &mut self.wasm.wm_store, - mode, - wa, - ) { - Ok(actions) => self.apply_wm_actions(&actions), - Err(e) => self.wasm.record_fault("wm-hybrid", "set_layout_mode", e), - } - self.damage.mark_full(); - } - - fn apply_wm_actions(&mut self, actions: &[wm_wit::exports::moonplasma::wm::policy::WmAction]) { - use wm_wit::exports::moonplasma::wm::policy::WmAction; - for action in actions { - match action { - WmAction::SetGeometry((id, r)) => { - let rect = Rect::new(r.x, r.y, r.w, r.h); - let mut focused = false; - if let Some(hw) = self.windows.get_mut(id) { - hw.geometry = rect; - focused = hw.focused; - } - self.wayland - .state - .configure_toplevel(*id, r.w, r.h, focused); - } - WmAction::Focus(id) => { - for (wid, hw) in self.windows.iter_mut() { - hw.focused = *wid == *id; - } - } - WmAction::Close(id) => { - self.wayland.state.close_toplevel(*id); - } - WmAction::SetMaximized((id, m)) => { - if let Some(hw) = self.windows.get_mut(id) { - hw.maximized = *m; - } - } - WmAction::SetFullscreen((id, fs)) => { - if let Some(hw) = self.windows.get_mut(id) { - hw.fullscreen = *fs; - } - } - WmAction::Raise(_) => {} - } - } - } - - pub fn compose_frame(&mut self) -> anyhow::Result { - let (sw, sh) = self.output_size; - let screen_desktop = desktop_wit::moonplasma::desktop::types::Size { w: sw, h: sh }; - let mut scene = SceneGraph::new(sw, sh); - - // 1. Background - self.wasm.shell_store.set_epoch_deadline(20); - match self - .wasm - .shell - .moonplasma_desktop_desktop_surface() - .call_render_background(&mut self.wasm.shell_store, screen_desktop) - { - Ok(ops) => scene.background_ops = ops.into_iter().map(from_desktop_op).collect(), - Err(e) => self.wasm.record_fault("shell", "render_background", e), - } - - // 2. Panel layout + widgets - self.wasm.launcher_store.set_epoch_deadline(20); - let launcher_info = self - .wasm - .launcher - .moonplasma_desktop_plasmoid() - .call_info(&mut self.wasm.launcher_store)?; - self.wasm.clock_store.set_epoch_deadline(20); - let clock_info = self - .wasm - .clock - .moonplasma_desktop_plasmoid() - .call_info(&mut self.wasm.clock_store)?; - - let slots = vec![ - desktop_wit::exports::moonplasma::desktop::panel_layout::Slot { - id: "launcher".into(), - preferred: desktop_wit::moonplasma::desktop::types::Size { - w: launcher_info.preferred.w, - h: launcher_info.preferred.h, - }, - min_width: launcher_info.min_width, - stretch: launcher_info.stretch, - align: desktop_wit::exports::moonplasma::desktop::panel_layout::Edge::Start, - }, - desktop_wit::exports::moonplasma::desktop::panel_layout::Slot { - id: "clock".into(), - preferred: desktop_wit::moonplasma::desktop::types::Size { - w: clock_info.preferred.w, - h: clock_info.preferred.h, - }, - min_width: clock_info.min_width, - stretch: clock_info.stretch, - align: desktop_wit::exports::moonplasma::desktop::panel_layout::Edge::End, - }, - ]; - - self.wasm.shell_store.set_epoch_deadline(20); - let layout = self - .wasm - .shell - .moonplasma_desktop_panel_layout() - .call_compute_layout(&mut self.wasm.shell_store, screen_desktop, &slots)?; - - let panel_rect = Rect::new(layout.panel.x, layout.panel.y, layout.panel.w, layout.panel.h); - scene.panel_rect = panel_rect; - self.panel_rect = panel_rect; - self.work_area = Rect::new(0, 0, sw, (layout.panel.y.max(0)) as u32); - - self.wasm.shell_store.set_epoch_deadline(20); - let panel_ops = self - .wasm - .shell - .moonplasma_desktop_panel_layout() - .call_render_panel(&mut self.wasm.shell_store, screen_desktop, layout.panel)?; - scene.panel_ops = panel_ops.into_iter().map(from_desktop_op).collect(); - - for placement in &layout.placements { - let r = Rect::new(placement.rect.x, placement.rect.y, placement.rect.w, placement.rect.h); - match placement.id.as_str() { - "launcher" => { - self.wasm.launcher_store.set_epoch_deadline(20); - let ops = self - .wasm - .launcher - .moonplasma_desktop_plasmoid() - .call_render( - &mut self.wasm.launcher_store, - launcher_wit::moonplasma::desktop::types::Size { w: r.w, h: r.h }, - )?; - scene.widgets.push(PanelWidgetNode { - id: placement.id.clone(), - rect: r, - ops: ops.into_iter().map(from_launcher_op).collect(), - popup: None, - }); - } - "clock" => { - self.wasm.clock_store.set_epoch_deadline(20); - let ops = self - .wasm - .clock - .moonplasma_desktop_plasmoid() - .call_render( - &mut self.wasm.clock_store, - clock_wit::moonplasma::desktop::types::Size { w: r.w, h: r.h }, - )?; - scene.widgets.push(PanelWidgetNode { - id: placement.id.clone(), - rect: r, - ops: ops.into_iter().map(from_clock_op).collect(), - popup: None, - }); - } - _ => {} - } - } - - // 3. Windows in WM stacking order + decoration-breeze - self.wasm.wm_store.set_epoch_deadline(20); - let order = self - .wasm - .wm - .moonplasma_wm_policy() - .call_stacking_order(&mut self.wasm.wm_store) - .unwrap_or_else(|_| self.windows.keys().copied().collect()); - - for wid in order { - if let Some(hw) = self.windows.get(&wid) { - let outer_size = deco_wit::moonplasma::desktop::types::Size { - w: hw.geometry.w + 4, - h: hw.geometry.h + 34, - }; - let deco_win = to_deco_window(hw); - self.wasm.deco_store.set_epoch_deadline(20); - let (insets, deco_ops) = match self - .wasm - .deco - .moonplasma_wm_decoration() - .call_render(&mut self.wasm.deco_store, &deco_win, outer_size) - { - Ok(frame) => ( - frame.insets, - frame.ops.into_iter().map(from_deco_op).collect(), - ), - Err(e) => { - self.wasm.record_fault("decoration-breeze", "render", e); - ((32, 2, 2, 2), Vec::new()) - } - }; - scene.windows.push(WindowSceneNode { - id: hw.id, - title: hw.title.clone(), - app_id: hw.app_id.clone(), - focused: hw.focused, - fullscreen: hw.fullscreen, - geometry: hw.geometry, - deco_insets: insets, - deco_ops, - surface: hw.surface.clone(), - }); - } - } - - let pixmap = self.renderer.render_scene(&scene)?; - self.wayland.state.flush_frame_callbacks(0); - self.wayland.display.flush_clients()?; - self.damage.clear(); - Ok(pixmap) - } -} - -fn to_wm_rect(r: Rect) -> wm_wit::moonplasma::desktop::types::Rect { - wm_wit::moonplasma::desktop::types::Rect { - x: r.x, - y: r.y, - w: r.w, - h: r.h, - } -} - -fn to_wm_window(hw: &HostWindow) -> wm_wit::exports::moonplasma::wm::policy::WindowState { - use wm_wit::exports::moonplasma::wm::policy::WindowCaps; - wm_wit::exports::moonplasma::wm::policy::WindowState { - id: hw.id, - app_id: hw.app_id.clone(), - title: hw.title.clone(), - geometry: to_wm_rect(hw.geometry), - min_size: wm_wit::moonplasma::desktop::types::Size { - w: hw.min_size.0, - h: hw.min_size.1, - }, - max_size: hw - .max_size - .map(|(w, h)| wm_wit::moonplasma::desktop::types::Size { w, h }), - focused: hw.focused, - maximized: hw.maximized, - fullscreen: hw.fullscreen, - workspace: hw.workspace, - caps: WindowCaps::CAN_MOVE - | WindowCaps::CAN_RESIZE - | WindowCaps::CAN_MAXIMIZE - | WindowCaps::CAN_MINIMIZE - | WindowCaps::CAN_FULLSCREEN, - } -} - -fn to_deco_window(hw: &HostWindow) -> deco_wit::moonplasma::wm::policy::WindowState { - use deco_wit::moonplasma::wm::policy::WindowCaps; - deco_wit::moonplasma::wm::policy::WindowState { - id: hw.id, - app_id: hw.app_id.clone(), - title: hw.title.clone(), - geometry: deco_wit::moonplasma::desktop::types::Rect { - x: hw.geometry.x, - y: hw.geometry.y, - w: hw.geometry.w, - h: hw.geometry.h, - }, - min_size: deco_wit::moonplasma::desktop::types::Size { - w: hw.min_size.0, - h: hw.min_size.1, - }, - max_size: hw - .max_size - .map(|(w, h)| deco_wit::moonplasma::desktop::types::Size { w, h }), - focused: hw.focused, - maximized: hw.maximized, - fullscreen: hw.fullscreen, - workspace: hw.workspace, - caps: WindowCaps::CAN_MOVE - | WindowCaps::CAN_RESIZE - | WindowCaps::CAN_MAXIMIZE - | WindowCaps::CAN_MINIMIZE - | WindowCaps::CAN_FULLSCREEN, - } -} - -macro_rules! impl_from_op { - ($fn_name:ident, $mod_path:ident) => { - fn $fn_name(op: $mod_path::moonplasma::desktop::types::DrawOp) -> DrawOp { - use $mod_path::moonplasma::desktop::types::{DrawOp as WOp, TextAlign as WAlign}; - let cvt_color = |c: $mod_path::moonplasma::desktop::types::Color| Rgba { - r: c.r, - g: c.g, - b: c.b, - a: c.a, - }; - let cvt_rect = |r: $mod_path::moonplasma::desktop::types::Rect| Rect { - x: r.x, - y: r.y, - w: r.w, - h: r.h, - }; - match op { - WOp::FillRect(o) => DrawOp::FillRect { - rect: cvt_rect(o.rect), - color: cvt_color(o.color), - radius: o.radius, - }, - WOp::StrokeRect(o) => DrawOp::StrokeRect { - rect: cvt_rect(o.rect), - color: cvt_color(o.color), - width: o.width, - radius: o.radius, - }, - WOp::Line(o) => DrawOp::Line { - x0: o.start.x, - y0: o.start.y, - x1: o.end.x, - y1: o.end.y, - color: cvt_color(o.color), - width: o.width, - }, - WOp::Circle(o) => DrawOp::Circle { - cx: o.center.x, - cy: o.center.y, - radius: o.radius, - color: cvt_color(o.color), - filled: o.filled, - }, - WOp::Text(o) => DrawOp::Text { - x: o.origin.x, - y: o.origin.y, - text: o.text, - size: o.style.size, - color: cvt_color(o.style.color), - align: match o.style.align { - WAlign::Left => TextAlign::Left, - WAlign::Center => TextAlign::Center, - WAlign::Right => TextAlign::Right, - }, - bold: o.style.bold, - }, - WOp::PushClip(r) => DrawOp::PushClip(cvt_rect(r)), - WOp::PopClip => DrawOp::PopClip, - } - } - }; -} - -impl_from_op!(from_desktop_op, desktop_wit); -impl_from_op!(from_launcher_op, launcher_wit); -impl_from_op!(from_clock_op, clock_wit); -impl_from_op!(from_deco_op, deco_wit); diff --git a/host-native/src/lib.rs b/host-native/src/lib.rs deleted file mode 100644 index 3d7c7ef..0000000 --- a/host-native/src/lib.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub mod compositor; -pub mod renderer; -pub mod scene; -pub mod theme; -pub mod wasm; -pub mod wayland; diff --git a/host-native/src/main.rs b/host-native/src/main.rs deleted file mode 100644 index 8750d23..0000000 --- a/host-native/src/main.rs +++ /dev/null @@ -1,55 +0,0 @@ -use std::path::PathBuf; - -use moon_plasma_host::compositor::MoonPlasmaCompositor; -use moon_plasma_host::renderer::SoftwareRenderer; -use moon_plasma_host::theme::ThemeTokens; - -fn main() -> anyhow::Result<()> { - let args: Vec = std::env::args().collect(); - let mut out_path = PathBuf::from("frame.png"); - let mut socket_path = PathBuf::from("/tmp/moon-plasma-wayland-0"); - let mut components_dir = PathBuf::from("../build/components"); - let mut theme_path = PathBuf::from("../config/themes/moon-night.json"); - - let mut i = 1; - while i < args.len() { - match args[i].as_str() { - "--out" if i + 1 < args.len() => { - out_path = PathBuf::from(&args[i + 1]); - i += 2; - } - "--socket" if i + 1 < args.len() => { - socket_path = PathBuf::from(&args[i + 1]); - i += 2; - } - "--components" if i + 1 < args.len() => { - components_dir = PathBuf::from(&args[i + 1]); - i += 2; - } - "--theme" if i + 1 < args.len() => { - theme_path = PathBuf::from(&args[i + 1]); - i += 2; - } - _ => i += 1, - } - } - - let theme = if theme_path.exists() { - ThemeTokens::load_file(&theme_path)? - } else { - ThemeTokens::moon_night_default() - }; - - let mut compositor = MoonPlasmaCompositor::new(&socket_path, &components_dir, theme, 1280, 720)?; - compositor.step()?; - let pixmap = compositor.compose_frame()?; - SoftwareRenderer::save_png(&pixmap, &out_path)?; - println!( - "moon-plasma-host: Wayland socket={}, rendered {}x{} frame to {}", - socket_path.display(), - pixmap.width(), - pixmap.height(), - out_path.display() - ); - Ok(()) -} diff --git a/host-native/src/renderer/mod.rs b/host-native/src/renderer/mod.rs deleted file mode 100644 index 9c8c7c1..0000000 --- a/host-native/src/renderer/mod.rs +++ /dev/null @@ -1,409 +0,0 @@ -use std::path::Path; - -use fontdue::{Font, FontSettings}; -use tiny_skia::{ - Color, FillRule, LineCap, Mask, Paint, PathBuilder, Pixmap, PixmapPaint, Rect as SkRect, - Stroke, Transform, -}; - -use crate::scene::{DrawOp, Rect, SceneGraph, ShmBufferSnapshot, TextAlign}; -use crate::theme::Rgba; - -pub struct SoftwareRenderer { - font_regular: Option, - font_bold: Option, -} - -impl SoftwareRenderer { - pub fn new() -> Self { - let load_font = |path: &str| -> Option { - let bytes = std::fs::read(path).ok()?; - Font::from_bytes(bytes, FontSettings::default()).ok() - }; - Self { - font_regular: load_font("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"), - font_bold: load_font("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf") - .or_else(|| load_font("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf")), - } - } - - pub fn render_scene(&self, scene: &SceneGraph) -> anyhow::Result { - let (w, h) = scene.output_size; - let mut pixmap = Pixmap::new(w.max(1), h.max(1)) - .ok_or_else(|| anyhow::anyhow!("failed to create pixmap {w}x{h}"))?; - - // 1. Background layer - self.draw_ops(&mut pixmap, &scene.background_ops, 0, 0); - - // 2. Windows layer (bottom-to-top) - for win in &scene.windows { - if !win.fullscreen { - let (top, right, bottom, left) = win.deco_insets; - let outer_x = win.geometry.x - left as i32; - let outer_y = win.geometry.y - top as i32; - let outer_w = win.geometry.w + left + right; - let outer_h = win.geometry.h + top + bottom; - - // Subtle drop shadow under window - let shadow_rect = Rect::new(outer_x + 4, outer_y + 6, outer_w, outer_h); - self.fill_rounded_rect( - &mut pixmap, - shadow_rect, - Rgba { r: 0, g: 0, b: 0, a: 80 }, - 8, - None, - ); - - // Decoration draw-ops (local to outer_x, outer_y) - self.draw_ops(&mut pixmap, &win.deco_ops, outer_x, outer_y); - } - - // Client buffer-surface - if let Some(buf) = &win.surface { - self.blit_shm_surface(&mut pixmap, buf, win.geometry); - } else { - // Fallback placeholder until client commits first buffer - self.fill_rounded_rect( - &mut pixmap, - win.geometry, - Rgba { r: 0x1e, g: 0x29, b: 0x3b, a: 0xff }, - 0, - None, - ); - } - } - - // 3. Panel layer - self.draw_ops(&mut pixmap, &scene.panel_ops, 0, 0); - for widget in &scene.widgets { - self.draw_ops(&mut pixmap, &widget.ops, widget.rect.x, widget.rect.y); - } - - // 4. Overlay layer (popups) - for widget in &scene.widgets { - if let Some((popup_rect, popup_ops)) = &widget.popup { - self.draw_ops(&mut pixmap, popup_ops, popup_rect.x, popup_rect.y); - } - } - - Ok(pixmap) - } - - pub fn save_png(pixmap: &Pixmap, path: &Path) -> anyhow::Result<()> { - pixmap.save_png(path)?; - Ok(()) - } - - fn blit_shm_surface(&self, dst: &mut Pixmap, buf: &ShmBufferSnapshot, dst_rect: Rect) { - if buf.width == 0 || buf.height == 0 || dst_rect.w == 0 || dst_rect.h == 0 { - return; - } - let mut src_pix = match Pixmap::new(buf.width, buf.height) { - Some(p) => p, - None => return, - }; - let dst_data = src_pix.data_mut(); - let copy_w = buf.width as usize; - let copy_h = buf.height as usize; - let stride = buf.stride as usize; - let is_xrgb = buf.format == 1; // WL_SHM_FORMAT_XRGB8888 = 1, ARGB8888 = 0 - - for y in 0..copy_h { - let row_off = y * stride; - if row_off + copy_w * 4 > buf.bytes.len() { - break; - } - for x in 0..copy_w { - let s = row_off + x * 4; - // Wayland little-endian ARGB8888/XRGB8888 is [B, G, R, A] in memory. - let b = buf.bytes[s]; - let g = buf.bytes[s + 1]; - let r = buf.bytes[s + 2]; - let a = if is_xrgb { 255 } else { buf.bytes[s + 3] }; - // Premultiply for tiny-skia RGBA - let d = (y * copy_w + x) * 4; - if a == 255 { - dst_data[d] = r; - dst_data[d + 1] = g; - dst_data[d + 2] = b; - dst_data[d + 3] = 255; - } else if a == 0 { - dst_data[d..d + 4].fill(0); - } else { - let af = a as f32 / 255.0; - dst_data[d] = (r as f32 * af) as u8; - dst_data[d + 1] = (g as f32 * af) as u8; - dst_data[d + 2] = (b as f32 * af) as u8; - dst_data[d + 3] = a; - } - } - } - - let mut clip_mask = Mask::new(dst.width(), dst.height()); - if let Some(mask) = clip_mask.as_mut() { - if let Some(sk_r) = SkRect::from_xywh( - dst_rect.x as f32, - dst_rect.y as f32, - dst_rect.w as f32, - dst_rect.h as f32, - ) { - let path = PathBuilder::from_rect(sk_r); - mask.fill_path(&path, FillRule::Winding, false, Transform::identity()); - } - } - - dst.draw_pixmap( - dst_rect.x, - dst_rect.y, - src_pix.as_ref(), - &PixmapPaint::default(), - Transform::identity(), - clip_mask.as_ref(), - ); - } - - fn draw_ops(&self, pixmap: &mut Pixmap, ops: &[DrawOp], ox: i32, oy: i32) { - let mut clip_stack: Vec = Vec::new(); - for op in ops { - let mask_ref = clip_stack.last(); - match op { - DrawOp::PushClip(r) => { - if let Some(mut m) = Mask::new(pixmap.width(), pixmap.height()) { - if let Some(sk_r) = SkRect::from_xywh( - (r.x + ox) as f32, - (r.y + oy) as f32, - r.w as f32, - r.h as f32, - ) { - let path = PathBuilder::from_rect(sk_r); - m.fill_path(&path, FillRule::Winding, false, Transform::identity()); - clip_stack.push(m); - } - } - } - DrawOp::PopClip => { - clip_stack.pop(); - } - DrawOp::FillRect { rect, color, radius } => { - let r = Rect::new(rect.x + ox, rect.y + oy, rect.w, rect.h); - self.fill_rounded_rect(pixmap, r, *color, *radius, mask_ref); - } - DrawOp::StrokeRect { - rect, - color, - width, - radius, - } => { - let r = Rect::new(rect.x + ox, rect.y + oy, rect.w, rect.h); - self.stroke_rounded_rect(pixmap, r, *color, *width, *radius, mask_ref); - } - DrawOp::Line { - x0, - y0, - x1, - y1, - color, - width, - } => { - let mut pb = PathBuilder::new(); - pb.move_to((x0 + ox) as f32, (y0 + oy) as f32); - pb.line_to((x1 + ox) as f32, (y1 + oy) as f32); - if let Some(path) = pb.finish() { - let mut paint = Paint::default(); - paint.set_color(Color::from_rgba8(color.r, color.g, color.b, color.a)); - paint.anti_alias = true; - let stroke = Stroke { - width: (*width).max(1) as f32, - line_cap: LineCap::Round, - ..Default::default() - }; - pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), mask_ref); - } - } - DrawOp::Circle { - cx, - cy, - radius, - color, - filled, - } => { - if let Some(path) = PathBuilder::from_circle((cx + ox) as f32, (cy + oy) as f32, *radius as f32) { - let mut paint = Paint::default(); - paint.set_color(Color::from_rgba8(color.r, color.g, color.b, color.a)); - paint.anti_alias = true; - if *filled { - pixmap.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), mask_ref); - } else { - let stroke = Stroke { - width: 1.5, - ..Default::default() - }; - pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), mask_ref); - } - } - } - DrawOp::Text { - x, - y, - text, - size, - color, - align, - bold, - } => { - self.draw_text( - pixmap, - x + ox, - y + oy, - text, - *size, - *color, - *align, - *bold, - mask_ref, - ); - } - } - } - } - - fn build_rounded_rect_path(&self, r: Rect, radius: u32) -> Option { - if r.w == 0 || r.h == 0 { - return None; - } - let x = r.x as f32; - let y = r.y as f32; - let w = r.w as f32; - let h = r.h as f32; - let rad = (radius as f32).min(w * 0.5).min(h * 0.5); - if rad <= 0.5 { - return SkRect::from_xywh(x, y, w, h).map(PathBuilder::from_rect); - } - let k = rad * 0.5522848; - let mut pb = PathBuilder::new(); - pb.move_to(x + rad, y); - pb.line_to(x + w - rad, y); - pb.cubic_to(x + w - rad + k, y, x + w, y + rad - k, x + w, y + rad); - pb.line_to(x + w, y + h - rad); - pb.cubic_to(x + w, y + h - rad + k, x + w - rad + k, y + h, x + w - rad, y + h); - pb.line_to(x + rad, y + h); - pb.cubic_to(x + rad - k, y + h, x, y + h - rad + k, x, y + h - rad); - pb.line_to(x, y + rad); - pb.cubic_to(x, y + rad - k, x + rad - k, y, x + rad, y); - pb.close(); - pb.finish() - } - - fn fill_rounded_rect(&self, pixmap: &mut Pixmap, r: Rect, color: Rgba, radius: u32, mask: Option<&Mask>) { - if let Some(path) = self.build_rounded_rect_path(r, radius) { - let mut paint = Paint::default(); - paint.set_color(Color::from_rgba8(color.r, color.g, color.b, color.a)); - paint.anti_alias = true; - pixmap.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), mask); - } - } - - fn stroke_rounded_rect( - &self, - pixmap: &mut Pixmap, - r: Rect, - color: Rgba, - width: u32, - radius: u32, - mask: Option<&Mask>, - ) { - if let Some(path) = self.build_rounded_rect_path(r, radius) { - let mut paint = Paint::default(); - paint.set_color(Color::from_rgba8(color.r, color.g, color.b, color.a)); - paint.anti_alias = true; - let stroke = Stroke { - width: width.max(1) as f32, - ..Default::default() - }; - pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), mask); - } - } - - #[allow(clippy::too_many_arguments)] - fn draw_text( - &self, - pixmap: &mut Pixmap, - x: i32, - y: i32, - text: &str, - size: u32, - color: Rgba, - align: TextAlign, - bold: bool, - mask: Option<&Mask>, - ) { - let font = match if bold { &self.font_bold } else { &self.font_regular } { - Some(f) => f, - None => return, - }; - let px_size = size.max(8) as f32; - - let mut total_w = 0.0f32; - let mut glyphs = Vec::with_capacity(text.len()); - for ch in text.chars() { - let (metrics, bitmap) = font.rasterize(ch, px_size); - total_w += metrics.advance_width; - glyphs.push((metrics, bitmap)); - } - - let mut pen_x = match align { - TextAlign::Left => x as f32, - TextAlign::Center => x as f32 - total_w * 0.5, - TextAlign::Right => x as f32 - total_w, - }; - // `y` is vertical middle of the line box per WIT spec. - let baseline_y = y as f32 + px_size * 0.35; - - let pw = pixmap.width() as i32; - let ph = pixmap.height() as i32; - let data = pixmap.data_mut(); - - for (metrics, bitmap) in glyphs { - let gx0 = (pen_x + metrics.xmin as f32).round() as i32; - let gy0 = (baseline_y - metrics.height as f32 - metrics.ymin as f32).round() as i32; - for row in 0..metrics.height { - let py = gy0 + row as i32; - if py < 0 || py >= ph { - continue; - } - for col in 0..metrics.width { - let px = gx0 + col as i32; - if px < 0 || px >= pw { - continue; - } - if let Some(m) = mask { - let midx = py as usize * m.width() as usize + px as usize; - if m.data().get(midx).copied().unwrap_or(0) == 0 { - continue; - } - } - let cov = bitmap[row * metrics.width + col]; - if cov == 0 { - continue; - } - let alpha = (cov as u32 * color.a as u32) / 255; - if alpha == 0 { - continue; - } - let sa = alpha as f32 / 255.0; - let inv = 1.0 - sa; - let idx = (py as usize * pw as usize + px as usize) * 4; - // Pixmap is premultiplied RGBA - let sr = color.r as f32 * sa; - let sg = color.g as f32 * sa; - let sb = color.b as f32 * sa; - data[idx] = (sr + data[idx] as f32 * inv).min(255.0) as u8; - data[idx + 1] = (sg + data[idx + 1] as f32 * inv).min(255.0) as u8; - data[idx + 2] = (sb + data[idx + 2] as f32 * inv).min(255.0) as u8; - data[idx + 3] = (alpha as f32 + data[idx + 3] as f32 * inv).min(255.0) as u8; - } - } - pen_x += metrics.advance_width; - } - } -} diff --git a/host-native/src/scene/mod.rs b/host-native/src/scene/mod.rs deleted file mode 100644 index 2f9de16..0000000 --- a/host-native/src/scene/mod.rs +++ /dev/null @@ -1,158 +0,0 @@ -use crate::theme::Rgba; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Rect { - pub x: i32, - pub y: i32, - pub w: u32, - pub h: u32, -} - -impl Rect { - pub fn new(x: i32, y: i32, w: u32, h: u32) -> Self { - Self { x, y, w, h } - } - - pub fn union(self, other: Self) -> Self { - let x0 = self.x.min(other.x); - let y0 = self.y.min(other.y); - let x1 = (self.x + self.w as i32).max(other.x + other.w as i32); - let y1 = (self.y + self.h as i32).max(other.y + other.h as i32); - Self { - x: x0, - y: y0, - w: (x1 - x0).max(0) as u32, - h: (y1 - y0).max(0) as u32, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TextAlign { - Left, - Center, - Right, -} - -#[derive(Debug, Clone)] -pub enum DrawOp { - FillRect { - rect: Rect, - color: Rgba, - radius: u32, - }, - StrokeRect { - rect: Rect, - color: Rgba, - width: u32, - radius: u32, - }, - Line { - x0: i32, - y0: i32, - x1: i32, - y1: i32, - color: Rgba, - width: u32, - }, - Circle { - cx: i32, - cy: i32, - radius: u32, - color: Rgba, - filled: bool, - }, - Text { - x: i32, - y: i32, - text: String, - size: u32, - color: Rgba, - align: TextAlign, - bold: bool, - }, - PushClip(Rect), - PopClip, -} - -#[derive(Debug, Clone)] -pub struct ShmBufferSnapshot { - pub width: u32, - pub height: u32, - pub stride: u32, - /// Wayland wl_shm format (0 = ARGB8888, 1 = XRGB8888) - pub format: u32, - pub bytes: Vec, -} - -#[derive(Debug, Clone)] -pub struct WindowSceneNode { - pub id: u64, - pub title: String, - pub app_id: String, - pub focused: bool, - pub fullscreen: bool, - pub geometry: Rect, - pub deco_insets: (u32, u32, u32, u32), - pub deco_ops: Vec, - pub surface: Option, -} - -#[derive(Debug, Clone)] -pub struct PanelWidgetNode { - pub id: String, - pub rect: Rect, - pub ops: Vec, - pub popup: Option<(Rect, Vec)>, -} - -#[derive(Debug, Clone, Default)] -pub struct DamageTracker { - pub regions: Vec, - pub full_damage: bool, -} - -impl DamageTracker { - pub fn mark_full(&mut self) { - self.full_damage = true; - self.regions.clear(); - } - - pub fn add_rect(&mut self, r: Rect) { - if !self.full_damage && r.w > 0 && r.h > 0 { - self.regions.push(r); - } - } - - pub fn clear(&mut self) { - self.full_damage = false; - self.regions.clear(); - } - - pub fn is_dirty(&self) -> bool { - self.full_damage || !self.regions.is_empty() - } -} - -#[derive(Debug, Clone)] -pub struct SceneGraph { - pub output_size: (u32, u32), - pub background_ops: Vec, - pub windows: Vec, - pub panel_rect: Rect, - pub panel_ops: Vec, - pub widgets: Vec, -} - -impl SceneGraph { - pub fn new(w: u32, h: u32) -> Self { - Self { - output_size: (w, h), - background_ops: Vec::new(), - windows: Vec::new(), - panel_rect: Rect::new(0, 0, 0, 0), - panel_ops: Vec::new(), - widgets: Vec::new(), - } - } -} diff --git a/host-native/src/theme.rs b/host-native/src/theme.rs deleted file mode 100644 index 0f76bb6..0000000 --- a/host-native/src/theme.rs +++ /dev/null @@ -1,140 +0,0 @@ -use serde::Deserialize; -use std::path::Path; - -#[derive(Debug, Clone, Copy)] -pub struct Rgba { - pub r: u8, - pub g: u8, - pub b: u8, - pub a: u8, -} - -impl Rgba { - pub fn from_hex(s: &str) -> anyhow::Result { - let hex = s.strip_prefix('#').unwrap_or(s); - let bytes = hex.as_bytes(); - let parse_byte = |i: usize| -> anyhow::Result { - let sub = std::str::from_utf8(&bytes[i..i + 2])?; - Ok(u8::from_str_radix(sub, 16)?) - }; - match bytes.len() { - 6 => Ok(Self { - r: parse_byte(0)?, - g: parse_byte(2)?, - b: parse_byte(4)?, - a: 255, - }), - 8 => Ok(Self { - r: parse_byte(0)?, - g: parse_byte(2)?, - b: parse_byte(4)?, - a: parse_byte(6)?, - }), - _ => anyhow::bail!("invalid hex color: {s}"), - } - } -} - -#[derive(Debug, Clone)] -pub struct ThemePalette { - pub desktop_top: Rgba, - pub desktop_bottom: Rgba, - pub surface: Rgba, - pub surface_hover: Rgba, - pub surface_popup: Rgba, - pub foreground: Rgba, - pub foreground_muted: Rgba, - pub accent: Rgba, - pub accent_foreground: Rgba, - pub border: Rgba, -} - -#[derive(Debug, Clone)] -pub struct ThemeTokens { - pub name: String, - pub palette: ThemePalette, - pub font_size: u32, - pub radius: u32, - pub spacing: u32, - pub panel_height: u32, -} - -#[derive(Deserialize)] -struct RawPalette { - #[serde(rename = "desktop-top")] - desktop_top: String, - #[serde(rename = "desktop-bottom")] - desktop_bottom: String, - surface: String, - #[serde(rename = "surface-hover")] - surface_hover: String, - #[serde(rename = "surface-popup")] - surface_popup: String, - foreground: String, - #[serde(rename = "foreground-muted")] - foreground_muted: String, - accent: String, - #[serde(rename = "accent-foreground")] - accent_foreground: String, - border: String, -} - -#[derive(Deserialize)] -struct RawTheme { - name: String, - palette: RawPalette, - #[serde(rename = "font-size")] - font_size: u32, - radius: u32, - spacing: u32, - #[serde(rename = "panel-height")] - panel_height: u32, -} - -impl ThemeTokens { - pub fn load_file(path: &Path) -> anyhow::Result { - let text = std::fs::read_to_string(path)?; - let raw: RawTheme = serde_json::from_str(&text)?; - Ok(Self { - name: raw.name, - palette: ThemePalette { - desktop_top: Rgba::from_hex(&raw.palette.desktop_top)?, - desktop_bottom: Rgba::from_hex(&raw.palette.desktop_bottom)?, - surface: Rgba::from_hex(&raw.palette.surface)?, - surface_hover: Rgba::from_hex(&raw.palette.surface_hover)?, - surface_popup: Rgba::from_hex(&raw.palette.surface_popup)?, - foreground: Rgba::from_hex(&raw.palette.foreground)?, - foreground_muted: Rgba::from_hex(&raw.palette.foreground_muted)?, - accent: Rgba::from_hex(&raw.palette.accent)?, - accent_foreground: Rgba::from_hex(&raw.palette.accent_foreground)?, - border: Rgba::from_hex(&raw.palette.border)?, - }, - font_size: raw.font_size, - radius: raw.radius, - spacing: raw.spacing, - panel_height: raw.panel_height, - }) - } - - pub fn moon_night_default() -> Self { - Self { - name: "Moon Night".to_string(), - palette: ThemePalette { - desktop_top: Rgba { r: 0x16, g: 0x21, b: 0x3e, a: 0xff }, - desktop_bottom: Rgba { r: 0x0b, g: 0x10, b: 0x20, a: 0xff }, - surface: Rgba { r: 0x1f, g: 0x29, b: 0x37, a: 0xf2 }, - surface_hover: Rgba { r: 0x37, g: 0x41, b: 0x51, a: 0xff }, - surface_popup: Rgba { r: 0x11, g: 0x18, b: 0x27, a: 0xf5 }, - foreground: Rgba { r: 0xf3, g: 0xf4, b: 0xf6, a: 0xff }, - foreground_muted: Rgba { r: 0x9c, g: 0xa3, b: 0xaf, a: 0xff }, - accent: Rgba { r: 0x7c, g: 0x9c, b: 0xff, a: 0xff }, - accent_foreground: Rgba { r: 0x0b, g: 0x10, b: 0x20, a: 0xff }, - border: Rgba { r: 0x3b, g: 0x46, b: 0x58, a: 0xff }, - }, - font_size: 14, - radius: 6, - spacing: 6, - panel_height: 44, - } - } -} diff --git a/host-native/src/wasm/mod.rs b/host-native/src/wasm/mod.rs deleted file mode 100644 index 8251c76..0000000 --- a/host-native/src/wasm/mod.rs +++ /dev/null @@ -1,471 +0,0 @@ -use std::collections::HashSet; -use std::path::Path; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use chrono::{Datelike, Timelike}; -use wasmtime::component::{Component, Linker}; -use wasmtime::{Config, Engine, Store}; - -use crate::theme::ThemeTokens; - -pub mod desktop_wit { - wasmtime::component::bindgen!({ - path: "../wit", - world: "shell", - }); -} - -pub mod clock_wit { - wasmtime::component::bindgen!({ - path: "../wit", - world: "clock-widget", - }); -} - -pub mod launcher_wit { - wasmtime::component::bindgen!({ - path: "../wit", - world: "launcher-widget", - }); -} - -pub mod wm_wit { - wasmtime::component::bindgen!({ - path: "../wit/wm", - world: "window-manager", - }); -} - -pub mod deco_wit { - wasmtime::component::bindgen!({ - path: "../wit/wm", - world: "decoration-provider", - }); -} - -#[derive(Debug, Clone)] -pub struct ComponentFault { - pub component: String, - pub phase: String, - pub message: String, -} - -#[derive(Clone)] -pub struct SharedHostState { - pub theme: Arc>, - pub launched_apps: Arc>>, - pub apps: Arc>, - pub faults: Arc>>, -} - -impl SharedHostState { - pub fn new(theme: ThemeTokens) -> Self { - use desktop_wit::moonplasma::desktop::types::AppEntry; - Self { - theme: Arc::new(Mutex::new(theme)), - launched_apps: Arc::new(Mutex::new(Vec::new())), - apps: Arc::new(vec![ - AppEntry { - id: "org.moonplasma.term".into(), - name: "MoonTerm".into(), - comment: "Terminal emulator".into(), - category: "System".into(), - glyph: ">_".into(), - }, - AppEntry { - id: "org.moonplasma.files".into(), - name: "Files".into(), - comment: "File manager".into(), - category: "System".into(), - glyph: "[]".into(), - }, - AppEntry { - id: "org.moonplasma.calc".into(), - name: "Calculator".into(), - comment: "Scientific calculator".into(), - category: "Utilities".into(), - glyph: "+=".into(), - }, - ]), - faults: Arc::new(Mutex::new(Vec::new())), - } - } -} - -pub struct ComponentCtx { - pub name: String, - pub grants: HashSet, - pub shared: SharedHostState, -} - -fn to_desktop_color(c: crate::theme::Rgba) -> desktop_wit::moonplasma::desktop::types::Color { - desktop_wit::moonplasma::desktop::types::Color { r: c.r, g: c.g, b: c.b, a: c.a } -} - -fn to_wm_color(c: crate::theme::Rgba) -> wm_wit::moonplasma::desktop::types::Color { - wm_wit::moonplasma::desktop::types::Color { r: c.r, g: c.g, b: c.b, a: c.a } -} - -fn to_deco_color(c: crate::theme::Rgba) -> deco_wit::moonplasma::desktop::types::Color { - deco_wit::moonplasma::desktop::types::Color { r: c.r, g: c.g, b: c.b, a: c.a } -} - -fn to_clock_color(c: crate::theme::Rgba) -> clock_wit::moonplasma::desktop::types::Color { - clock_wit::moonplasma::desktop::types::Color { r: c.r, g: c.g, b: c.b, a: c.a } -} - -fn to_launcher_color(c: crate::theme::Rgba) -> launcher_wit::moonplasma::desktop::types::Color { - launcher_wit::moonplasma::desktop::types::Color { r: c.r, g: c.g, b: c.b, a: c.a } -} - -// Implement theme::Host for each generated bindgen module so every component world links cleanly. -impl desktop_wit::moonplasma::desktop::types::Host for ComponentCtx {} -impl desktop_wit::moonplasma::desktop::theme::Host for ComponentCtx { - fn get_tokens(&mut self) -> desktop_wit::moonplasma::desktop::theme::Tokens { - let t = self.shared.theme.lock().unwrap(); - desktop_wit::moonplasma::desktop::theme::Tokens { - name: t.name.clone(), - palette: desktop_wit::moonplasma::desktop::theme::Palette { - desktop_top: to_desktop_color(t.palette.desktop_top), - desktop_bottom: to_desktop_color(t.palette.desktop_bottom), - surface: to_desktop_color(t.palette.surface), - surface_hover: to_desktop_color(t.palette.surface_hover), - surface_popup: to_desktop_color(t.palette.surface_popup), - foreground: to_desktop_color(t.palette.foreground), - foreground_muted: to_desktop_color(t.palette.foreground_muted), - accent: to_desktop_color(t.palette.accent), - accent_foreground: to_desktop_color(t.palette.accent_foreground), - border: to_desktop_color(t.palette.border), - }, - font_size: t.font_size, - radius: t.radius, - spacing: t.spacing, - panel_height: t.panel_height, - } - } -} - -impl clock_wit::moonplasma::desktop::types::Host for ComponentCtx {} -impl clock_wit::moonplasma::desktop::theme::Host for ComponentCtx { - fn get_tokens(&mut self) -> clock_wit::moonplasma::desktop::theme::Tokens { - let t = self.shared.theme.lock().unwrap(); - clock_wit::moonplasma::desktop::theme::Tokens { - name: t.name.clone(), - palette: clock_wit::moonplasma::desktop::theme::Palette { - desktop_top: to_clock_color(t.palette.desktop_top), - desktop_bottom: to_clock_color(t.palette.desktop_bottom), - surface: to_clock_color(t.palette.surface), - surface_hover: to_clock_color(t.palette.surface_hover), - surface_popup: to_clock_color(t.palette.surface_popup), - foreground: to_clock_color(t.palette.foreground), - foreground_muted: to_clock_color(t.palette.foreground_muted), - accent: to_clock_color(t.palette.accent), - accent_foreground: to_clock_color(t.palette.accent_foreground), - border: to_clock_color(t.palette.border), - }, - font_size: t.font_size, - radius: t.radius, - spacing: t.spacing, - panel_height: t.panel_height, - } - } -} - -impl clock_wit::moonplasma::desktop::clock::Host for ComponentCtx { - fn now(&mut self) -> clock_wit::moonplasma::desktop::types::Datetime { - let dt = chrono::Local::now(); - clock_wit::moonplasma::desktop::types::Datetime { - year: dt.year() as u32, - month: dt.month() as u8, - day: dt.day() as u8, - hour: dt.hour() as u8, - minute: dt.minute() as u8, - second: dt.second() as u8, - weekday: dt.weekday().num_days_from_sunday() as u8, - } - } -} - -impl launcher_wit::moonplasma::desktop::types::Host for ComponentCtx {} -impl launcher_wit::moonplasma::desktop::theme::Host for ComponentCtx { - fn get_tokens(&mut self) -> launcher_wit::moonplasma::desktop::theme::Tokens { - let t = self.shared.theme.lock().unwrap(); - launcher_wit::moonplasma::desktop::theme::Tokens { - name: t.name.clone(), - palette: launcher_wit::moonplasma::desktop::theme::Palette { - desktop_top: to_launcher_color(t.palette.desktop_top), - desktop_bottom: to_launcher_color(t.palette.desktop_bottom), - surface: to_launcher_color(t.palette.surface), - surface_hover: to_launcher_color(t.palette.surface_hover), - surface_popup: to_launcher_color(t.palette.surface_popup), - foreground: to_launcher_color(t.palette.foreground), - foreground_muted: to_launcher_color(t.palette.foreground_muted), - accent: to_launcher_color(t.palette.accent), - accent_foreground: to_launcher_color(t.palette.accent_foreground), - border: to_launcher_color(t.palette.border), - }, - font_size: t.font_size, - radius: t.radius, - spacing: t.spacing, - panel_height: t.panel_height, - } - } -} - -impl launcher_wit::moonplasma::desktop::app_catalog::Host for ComponentCtx { - fn list_apps(&mut self) -> Vec { - if !self.grants.contains("app-catalog") { - return Vec::new(); - } - self.shared - .apps - .iter() - .map(|a| launcher_wit::moonplasma::desktop::types::AppEntry { - id: a.id.clone(), - name: a.name.clone(), - comment: a.comment.clone(), - category: a.category.clone(), - glyph: a.glyph.clone(), - }) - .collect() - } -} - -impl launcher_wit::moonplasma::desktop::app_launch::Host for ComponentCtx { - fn launch(&mut self, id: String) -> Result<(), String> { - if !self.grants.contains("app-launch") { - return Err("capability app-launch not granted".into()); - } - self.shared.launched_apps.lock().unwrap().push(id); - Ok(()) - } -} - -impl wm_wit::moonplasma::desktop::types::Host for ComponentCtx {} -impl wm_wit::moonplasma::desktop::theme::Host for ComponentCtx { - fn get_tokens(&mut self) -> wm_wit::moonplasma::desktop::theme::Tokens { - let t = self.shared.theme.lock().unwrap(); - wm_wit::moonplasma::desktop::theme::Tokens { - name: t.name.clone(), - palette: wm_wit::moonplasma::desktop::theme::Palette { - desktop_top: to_wm_color(t.palette.desktop_top), - desktop_bottom: to_wm_color(t.palette.desktop_bottom), - surface: to_wm_color(t.palette.surface), - surface_hover: to_wm_color(t.palette.surface_hover), - surface_popup: to_wm_color(t.palette.surface_popup), - foreground: to_wm_color(t.palette.foreground), - foreground_muted: to_wm_color(t.palette.foreground_muted), - accent: to_wm_color(t.palette.accent), - accent_foreground: to_wm_color(t.palette.accent_foreground), - border: to_wm_color(t.palette.border), - }, - font_size: t.font_size, - radius: t.radius, - spacing: t.spacing, - panel_height: t.panel_height, - } - } -} - -impl deco_wit::moonplasma::desktop::types::Host for ComponentCtx {} -impl deco_wit::moonplasma::wm::policy::Host for ComponentCtx { - fn sync_windows( - &mut self, - _outputs: Vec, - _windows: Vec, - ) -> Vec { - Vec::new() - } - fn on_window_open( - &mut self, - _win: deco_wit::moonplasma::wm::policy::WindowState, - _work_area: deco_wit::moonplasma::desktop::types::Rect, - ) -> Vec { - Vec::new() - } - fn on_window_close(&mut self, _id: u64) -> Vec { - Vec::new() - } - fn on_window_request( - &mut self, - _id: u64, - _req: deco_wit::moonplasma::wm::policy::WindowRequest, - _work_area: deco_wit::moonplasma::desktop::types::Rect, - ) -> Vec { - Vec::new() - } - fn on_pointer( - &mut self, - _pos: deco_wit::moonplasma::desktop::types::Point, - _button: Option, - _pressed: bool, - ) -> deco_wit::moonplasma::wm::policy::InputTarget { - deco_wit::moonplasma::wm::policy::InputTarget::None - } - fn set_layout_mode( - &mut self, - _mode: deco_wit::moonplasma::wm::policy::LayoutMode, - _work_area: deco_wit::moonplasma::desktop::types::Rect, - ) -> Vec { - Vec::new() - } - fn stacking_order(&mut self) -> Vec { - Vec::new() - } -} -impl deco_wit::moonplasma::desktop::theme::Host for ComponentCtx { - fn get_tokens(&mut self) -> deco_wit::moonplasma::desktop::theme::Tokens { - let t = self.shared.theme.lock().unwrap(); - deco_wit::moonplasma::desktop::theme::Tokens { - name: t.name.clone(), - palette: deco_wit::moonplasma::desktop::theme::Palette { - desktop_top: to_deco_color(t.palette.desktop_top), - desktop_bottom: to_deco_color(t.palette.desktop_bottom), - surface: to_deco_color(t.palette.surface), - surface_hover: to_deco_color(t.palette.surface_hover), - surface_popup: to_deco_color(t.palette.surface_popup), - foreground: to_deco_color(t.palette.foreground), - foreground_muted: to_deco_color(t.palette.foreground_muted), - accent: to_deco_color(t.palette.accent), - accent_foreground: to_deco_color(t.palette.accent_foreground), - border: to_deco_color(t.palette.border), - }, - font_size: t.font_size, - radius: t.radius, - spacing: t.spacing, - panel_height: t.panel_height, - } - } -} - -pub struct WasmSupervisor { - pub engine: Engine, - pub shared: SharedHostState, - pub shell_store: Store, - pub shell: desktop_wit::Shell, - pub launcher_store: Store, - pub launcher: launcher_wit::LauncherWidget, - pub clock_store: Store, - pub clock: clock_wit::ClockWidget, - pub wm_store: Store, - pub wm: wm_wit::WindowManager, - pub deco_store: Store, - pub deco: deco_wit::DecorationProvider, -} - -impl WasmSupervisor { - pub fn load_from_dir(components_dir: &Path, theme: ThemeTokens) -> anyhow::Result { - let mut config = Config::new(); - config.wasm_component_model(true); - config.epoch_interruption(true); - let engine = Engine::new(&config)?; - - // Spawn 1ms epoch watchdog thread. - let engine_weak = engine.clone(); - std::thread::spawn(move || loop { - std::thread::sleep(Duration::from_millis(1)); - engine_weak.increment_epoch(); - }); - - let shared = SharedHostState::new(theme); - - // Shell - let mut shell_linker = Linker::new(&engine); - desktop_wit::Shell::add_to_linker::<_, wasmtime::component::HasSelf>(&mut shell_linker, |s| s)?; - let shell_comp = Component::from_file(&engine, components_dir.join("shell.wasm"))?; - let mut shell_store = Store::new( - &engine, - ComponentCtx { - name: "shell".into(), - grants: ["theme"].into_iter().map(String::from).collect(), - shared: shared.clone(), - }, - ); - shell_store.set_epoch_deadline(50); - let shell = desktop_wit::Shell::instantiate(&mut shell_store, &shell_comp, &shell_linker)?; - - // Launcher - let mut launcher_linker = Linker::new(&engine); - launcher_wit::LauncherWidget::add_to_linker::<_, wasmtime::component::HasSelf>(&mut launcher_linker, |s| s)?; - let launcher_comp = Component::from_file(&engine, components_dir.join("launcher.wasm"))?; - let mut launcher_store = Store::new( - &engine, - ComponentCtx { - name: "launcher".into(), - grants: ["theme", "app-catalog", "app-launch"].into_iter().map(String::from).collect(), - shared: shared.clone(), - }, - ); - launcher_store.set_epoch_deadline(50); - let launcher = launcher_wit::LauncherWidget::instantiate(&mut launcher_store, &launcher_comp, &launcher_linker)?; - - // Clock - let mut clock_linker = Linker::new(&engine); - clock_wit::ClockWidget::add_to_linker::<_, wasmtime::component::HasSelf>(&mut clock_linker, |s| s)?; - let clock_comp = Component::from_file(&engine, components_dir.join("clock-digital.wasm"))?; - let mut clock_store = Store::new( - &engine, - ComponentCtx { - name: "clock-digital".into(), - grants: ["theme", "clock"].into_iter().map(String::from).collect(), - shared: shared.clone(), - }, - ); - clock_store.set_epoch_deadline(50); - let clock = clock_wit::ClockWidget::instantiate(&mut clock_store, &clock_comp, &clock_linker)?; - - // WM - let mut wm_linker = Linker::new(&engine); - wm_wit::WindowManager::add_to_linker::<_, wasmtime::component::HasSelf>(&mut wm_linker, |s| s)?; - let wm_comp = Component::from_file(&engine, components_dir.join("wm-hybrid.wasm"))?; - let mut wm_store = Store::new( - &engine, - ComponentCtx { - name: "wm-hybrid".into(), - grants: ["theme"].into_iter().map(String::from).collect(), - shared: shared.clone(), - }, - ); - wm_store.set_epoch_deadline(50); - let wm = wm_wit::WindowManager::instantiate(&mut wm_store, &wm_comp, &wm_linker)?; - - // Decoration - let mut deco_linker = Linker::new(&engine); - deco_wit::DecorationProvider::add_to_linker::<_, wasmtime::component::HasSelf>(&mut deco_linker, |s| s)?; - let deco_comp = Component::from_file(&engine, components_dir.join("decoration-breeze.wasm"))?; - let mut deco_store = Store::new( - &engine, - ComponentCtx { - name: "decoration-breeze".into(), - grants: ["theme"].into_iter().map(String::from).collect(), - shared: shared.clone(), - }, - ); - deco_store.set_epoch_deadline(50); - let deco = deco_wit::DecorationProvider::instantiate(&mut deco_store, &deco_comp, &deco_linker)?; - - Ok(Self { - engine, - shared, - shell_store, - shell, - launcher_store, - launcher, - clock_store, - clock, - wm_store, - wm, - deco_store, - deco, - }) - } - - pub fn record_fault(&self, component: &str, phase: &str, err: impl std::fmt::Display) { - self.shared.faults.lock().unwrap().push(ComponentFault { - component: component.to_string(), - phase: phase.to_string(), - message: err.to_string(), - }); - } -} diff --git a/host-native/src/wayland/mod.rs b/host-native/src/wayland/mod.rs deleted file mode 100644 index f463673..0000000 --- a/host-native/src/wayland/mod.rs +++ /dev/null @@ -1,739 +0,0 @@ -use std::collections::HashMap; -use std::os::unix::net::UnixListener; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; - -use memmap2::Mmap; -use wayland_protocols::xdg::decoration::zv1::server::{ - zxdg_decoration_manager_v1::{self, ZxdgDecorationManagerV1}, - zxdg_toplevel_decoration_v1::{self, Mode as DecoMode, ZxdgToplevelDecorationV1}, -}; -use wayland_protocols::xdg::shell::server::{ - xdg_surface::{self, XdgSurface}, - xdg_toplevel::{self, XdgToplevel}, - xdg_wm_base::{self, XdgWmBase}, -}; -use wayland_server::protocol::{ - wl_buffer::{self, WlBuffer}, - wl_callback::WlCallback, - wl_compositor::{self, WlCompositor}, - wl_keyboard::{self, WlKeyboard}, - wl_output::{self, WlOutput}, - wl_pointer::{self, WlPointer}, - wl_seat::{self, Capability, WlSeat}, - wl_shm::{self, Format as ShmFormat, WlShm}, - wl_shm_pool::{self, WlShmPool}, - wl_surface::{self, WlSurface}, -}; -use wayland_server::{ - Client, DataInit, Dispatch, Display, DisplayHandle, GlobalDispatch, New, Resource, -}; - -use crate::scene::ShmBufferSnapshot; - -#[derive(Debug, Clone)] -pub enum WaylandEvent { - ToplevelOpened { - window_id: u64, - app_id: String, - title: String, - min_w: u32, - min_h: u32, - max_w: Option, - max_h: Option, - }, - ToplevelClosed { - window_id: u64, - }, - SurfaceCommitted { - window_id: u64, - buffer: Option, - }, - ToplevelRequest { - window_id: u64, - maximize: Option, - fullscreen: Option, - }, -} - -pub struct ShmPoolData { - pub mmap: Arc>, -} - -#[derive(Clone)] -pub struct BufferData { - pub mmap: Arc>, - pub offset: i32, - pub width: i32, - pub height: i32, - pub stride: i32, - pub format: u32, -} - -#[derive(Default)] -pub struct SurfaceState { - pub pending_buffer: Option, - pub current_buffer: Option, - pub frame_callbacks: Vec, - pub window_id: Option, -} - -pub struct ToplevelRecord { - pub window_id: u64, - pub surface: WlSurface, - pub xdg_surface: XdgSurface, - pub toplevel: XdgToplevel, - pub app_id: String, - pub title: String, - pub min_w: u32, - pub min_h: u32, - pub max_w: Option, - pub max_h: Option, - pub mapped: bool, - pub configured_once: bool, -} - -pub struct WaylandState { - pub next_window_id: u64, - pub next_serial: u32, - pub surfaces: HashMap, - pub xdg_surface_to_wl: HashMap, - pub toplevels: HashMap, - pub xdg_toplevel_to_win: HashMap, - pub pointers: Vec, - pub keyboards: Vec, - pub events: Vec, - pub output_size: (u32, u32), -} - -impl WaylandState { - pub fn new(output_w: u32, output_h: u32) -> Self { - Self { - next_window_id: 1, - next_serial: 1, - surfaces: HashMap::new(), - xdg_surface_to_wl: HashMap::new(), - toplevels: HashMap::new(), - xdg_toplevel_to_win: HashMap::new(), - pointers: Vec::new(), - keyboards: Vec::new(), - events: Vec::new(), - output_size: (output_w, output_h), - } - } - - pub fn next_serial(&mut self) -> u32 { - let s = self.next_serial; - self.next_serial = self.next_serial.wrapping_add(1); - s - } - - pub fn configure_toplevel(&mut self, window_id: u64, w: u32, h: u32, focused: bool) { - let serial = self.next_serial(); - if let Some(rec) = self.toplevels.get(&window_id) { - let mut states = Vec::new(); - if focused { - states.push(xdg_toplevel::State::Activated as u8); - } - // wayland-protocols expects native-endian u32 bytes for states array - let state_bytes: Vec = if focused { - (xdg_toplevel::State::Activated as u32).to_ne_bytes().to_vec() - } else { - Vec::new() - }; - let _ = states; - rec.toplevel.configure(w as i32, h as i32, state_bytes); - rec.xdg_surface.configure(serial); - } - } - - pub fn close_toplevel(&self, window_id: u64) { - if let Some(rec) = self.toplevels.get(&window_id) { - rec.toplevel.close(); - } - } - - pub fn flush_frame_callbacks(&mut self, time_ms: u32) { - for surf in self.surfaces.values_mut() { - for cb in surf.frame_callbacks.drain(..) { - cb.done(time_ms); - } - } - } -} - -pub struct ClientState; -impl wayland_server::backend::ClientData for ClientState { - fn initialized(&self, _client_id: wayland_server::backend::ClientId) {} - fn disconnected( - &self, - _client_id: wayland_server::backend::ClientId, - _reason: wayland_server::backend::DisconnectReason, - ) { - } -} - -// --- Globals & Dispatchers --- - -impl GlobalDispatch for WaylandState { - fn bind( - _state: &mut Self, - _handle: &DisplayHandle, - _client: &Client, - resource: New, - _global_data: &(), - data_init: &mut DataInit<'_, Self>, - ) { - data_init.init(resource, ()); - } -} - -impl Dispatch for WaylandState { - fn request( - state: &mut Self, - _client: &Client, - _resource: &WlCompositor, - request: wl_compositor::Request, - _data: &(), - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, Self>, - ) { - if let wl_compositor::Request::CreateSurface { id } = request { - let surf = data_init.init(id, ()); - state.surfaces.insert(surf.id().protocol_id(), SurfaceState::default()); - } - } -} - -impl Dispatch for WaylandState { - fn request( - state: &mut Self, - _client: &Client, - resource: &WlSurface, - request: wl_surface::Request, - _data: &(), - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, Self>, - ) { - let sid = resource.id().protocol_id(); - match request { - wl_surface::Request::Attach { buffer, .. } => { - if let Some(surf) = state.surfaces.get_mut(&sid) { - surf.pending_buffer = buffer.and_then(|b| b.data::().cloned()); - } - } - wl_surface::Request::Frame { callback } => { - let cb = data_init.init(callback, ()); - if let Some(surf) = state.surfaces.get_mut(&sid) { - surf.frame_callbacks.push(cb); - } - } - wl_surface::Request::Commit => { - let (win_id, snapshot) = { - let surf = match state.surfaces.get_mut(&sid) { - Some(s) => s, - None => return, - }; - if let Some(pending) = surf.pending_buffer.take() { - surf.current_buffer = Some(pending); - } - let snap = surf.current_buffer.as_ref().map(|b| { - let guard = b.mmap.lock().unwrap(); - let start = b.offset.max(0) as usize; - let len = (b.stride.max(0) as usize) * (b.height.max(0) as usize); - let end = (start + len).min(guard.len()); - ShmBufferSnapshot { - width: b.width.max(0) as u32, - height: b.height.max(0) as u32, - stride: b.stride.max(0) as u32, - format: b.format, - bytes: if start <= end { - guard[start..end].to_vec() - } else { - Vec::new() - }, - } - }); - (surf.window_id, snap) - }; - - if let Some(wid) = win_id { - let mut open_evt = None; - if let Some(rec) = state.toplevels.get_mut(&wid) { - if !rec.mapped { - rec.mapped = true; - open_evt = Some(WaylandEvent::ToplevelOpened { - window_id: wid, - app_id: rec.app_id.clone(), - title: rec.title.clone(), - min_w: rec.min_w, - min_h: rec.min_h, - max_w: rec.max_w, - max_h: rec.max_h, - }); - } - } - if let Some(evt) = open_evt { - state.events.push(evt); - } - if snapshot.is_some() { - state.events.push(WaylandEvent::SurfaceCommitted { - window_id: wid, - buffer: snapshot, - }); - } - } - } - wl_surface::Request::Destroy => { - state.surfaces.remove(&sid); - } - _ => {} - } - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - _resource: &WlCallback, - _request: wayland_server::protocol::wl_callback::Request, - _data: &(), - _dhandle: &DisplayHandle, - _data_init: &mut DataInit<'_, Self>, - ) { - } -} - -impl GlobalDispatch for WaylandState { - fn bind( - _state: &mut Self, - _handle: &DisplayHandle, - _client: &Client, - resource: New, - _global_data: &(), - data_init: &mut DataInit<'_, Self>, - ) { - let shm = data_init.init(resource, ()); - shm.format(ShmFormat::Argb8888); - shm.format(ShmFormat::Xrgb8888); - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - _resource: &WlShm, - request: wl_shm::Request, - _data: &(), - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, Self>, - ) { - if let wl_shm::Request::CreatePool { id, fd, size } = request { - let mmap = unsafe { - Mmap::map(&fd).expect("failed to mmap wl_shm_pool fd") - }; - let _ = size; - data_init.init( - id, - ShmPoolData { - mmap: Arc::new(Mutex::new(mmap)), - }, - ); - } - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - _resource: &WlShmPool, - request: wl_shm_pool::Request, - data: &ShmPoolData, - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, Self>, - ) { - if let wl_shm_pool::Request::CreateBuffer { - id, - offset, - width, - height, - stride, - format, - } = request - { - let fmt_u32 = match format { - wayland_server::WEnum::Value(f) => f as u32, - wayland_server::WEnum::Unknown(v) => v, - }; - data_init.init( - id, - BufferData { - mmap: data.mmap.clone(), - offset, - width, - height, - stride, - format: fmt_u32, - }, - ); - } - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - _resource: &WlBuffer, - _request: wl_buffer::Request, - _data: &BufferData, - _dhandle: &DisplayHandle, - _data_init: &mut DataInit<'_, Self>, - ) { - } -} - -impl GlobalDispatch for WaylandState { - fn bind( - _state: &mut Self, - _handle: &DisplayHandle, - _client: &Client, - resource: New, - _global_data: &(), - data_init: &mut DataInit<'_, Self>, - ) { - data_init.init(resource, ()); - } -} - -impl Dispatch for WaylandState { - fn request( - state: &mut Self, - _client: &Client, - _resource: &XdgWmBase, - request: xdg_wm_base::Request, - _data: &(), - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, Self>, - ) { - if let xdg_wm_base::Request::GetXdgSurface { id, surface } = request { - let sid = surface.id().protocol_id(); - let xdg_surf = data_init.init(id, surface); - state.xdg_surface_to_wl.insert(xdg_surf.id().protocol_id(), sid); - } - } -} - -impl Dispatch for WaylandState { - fn request( - state: &mut Self, - _client: &Client, - resource: &XdgSurface, - request: xdg_surface::Request, - wl_surface: &WlSurface, - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, Self>, - ) { - if let xdg_surface::Request::GetToplevel { id } = request { - let wid = state.next_window_id; - state.next_window_id += 1; - let toplevel = data_init.init(id, wid); - let sid = wl_surface.id().protocol_id(); - if let Some(s) = state.surfaces.get_mut(&sid) { - s.window_id = Some(wid); - } - state.xdg_toplevel_to_win.insert(toplevel.id().protocol_id(), wid); - state.toplevels.insert( - wid, - ToplevelRecord { - window_id: wid, - surface: wl_surface.clone(), - xdg_surface: resource.clone(), - toplevel: toplevel.clone(), - app_id: String::new(), - title: String::new(), - min_w: 120, - min_h: 80, - max_w: None, - max_h: None, - mapped: false, - configured_once: false, - }, - ); - } - } -} - -impl Dispatch for WaylandState { - fn request( - state: &mut Self, - _client: &Client, - _resource: &XdgToplevel, - request: xdg_toplevel::Request, - wid: &u64, - _dhandle: &DisplayHandle, - _data_init: &mut DataInit<'_, Self>, - ) { - let wid = *wid; - match request { - xdg_toplevel::Request::SetTitle { title } => { - if let Some(rec) = state.toplevels.get_mut(&wid) { - rec.title = title; - } - } - xdg_toplevel::Request::SetAppId { app_id } => { - if let Some(rec) = state.toplevels.get_mut(&wid) { - rec.app_id = app_id; - } - } - xdg_toplevel::Request::SetMinSize { width, height } => { - if let Some(rec) = state.toplevels.get_mut(&wid) { - rec.min_w = width.max(0) as u32; - rec.min_h = height.max(0) as u32; - } - } - xdg_toplevel::Request::SetMaxSize { width, height } => { - if let Some(rec) = state.toplevels.get_mut(&wid) { - rec.max_w = if width > 0 { Some(width as u32) } else { None }; - rec.max_h = if height > 0 { Some(height as u32) } else { None }; - } - } - xdg_toplevel::Request::SetMaximized => { - state.events.push(WaylandEvent::ToplevelRequest { - window_id: wid, - maximize: Some(true), - fullscreen: None, - }); - } - xdg_toplevel::Request::UnsetMaximized => { - state.events.push(WaylandEvent::ToplevelRequest { - window_id: wid, - maximize: Some(false), - fullscreen: None, - }); - } - xdg_toplevel::Request::SetFullscreen { .. } => { - state.events.push(WaylandEvent::ToplevelRequest { - window_id: wid, - maximize: None, - fullscreen: Some(true), - }); - } - xdg_toplevel::Request::UnsetFullscreen => { - state.events.push(WaylandEvent::ToplevelRequest { - window_id: wid, - maximize: None, - fullscreen: Some(false), - }); - } - xdg_toplevel::Request::Destroy => { - state.toplevels.remove(&wid); - state.events.push(WaylandEvent::ToplevelClosed { window_id: wid }); - } - _ => {} - } - } -} - -impl GlobalDispatch for WaylandState { - fn bind( - _state: &mut Self, - _handle: &DisplayHandle, - _client: &Client, - resource: New, - _global_data: &(), - data_init: &mut DataInit<'_, Self>, - ) { - data_init.init(resource, ()); - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - _resource: &ZxdgDecorationManagerV1, - request: zxdg_decoration_manager_v1::Request, - _data: &(), - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, Self>, - ) { - if let zxdg_decoration_manager_v1::Request::GetToplevelDecoration { id, .. } = request { - let deco = data_init.init(id, ()); - // Default to Server-Side Decoration (rendered by decoration-breeze.wasm) - deco.configure(DecoMode::ServerSide); - } - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - resource: &ZxdgToplevelDecorationV1, - request: zxdg_toplevel_decoration_v1::Request, - _data: &(), - _dhandle: &DisplayHandle, - _data_init: &mut DataInit<'_, Self>, - ) { - if let zxdg_toplevel_decoration_v1::Request::SetMode { .. } = request { - resource.configure(DecoMode::ServerSide); - } - } -} - -impl GlobalDispatch for WaylandState { - fn bind( - _state: &mut Self, - _handle: &DisplayHandle, - _client: &Client, - resource: New, - _global_data: &(), - data_init: &mut DataInit<'_, Self>, - ) { - let seat = data_init.init(resource, ()); - seat.capabilities(Capability::Pointer | Capability::Keyboard); - seat.name("seat0".into()); - } -} - -impl Dispatch for WaylandState { - fn request( - state: &mut Self, - _client: &Client, - _resource: &WlSeat, - request: wl_seat::Request, - _data: &(), - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, Self>, - ) { - match request { - wl_seat::Request::GetPointer { id } => { - state.pointers.push(data_init.init(id, ())); - } - wl_seat::Request::GetKeyboard { id } => { - state.keyboards.push(data_init.init(id, ())); - } - _ => {} - } - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - _resource: &WlPointer, - _request: wl_pointer::Request, - _data: &(), - _dhandle: &DisplayHandle, - _data_init: &mut DataInit<'_, Self>, - ) { - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - _resource: &WlKeyboard, - _request: wl_keyboard::Request, - _data: &(), - _dhandle: &DisplayHandle, - _data_init: &mut DataInit<'_, Self>, - ) { - } -} - -impl GlobalDispatch for WaylandState { - fn bind( - state: &mut Self, - _handle: &DisplayHandle, - _client: &Client, - resource: New, - _global_data: &(), - data_init: &mut DataInit<'_, Self>, - ) { - let out = data_init.init(resource, ()); - let (w, h) = state.output_size; - out.geometry( - 0, - 0, - w as i32 / 4, - h as i32 / 4, - wl_output::Subpixel::Unknown, - "moon-plasma".into(), - "virtual-output".into(), - wl_output::Transform::Normal, - ); - out.mode(wl_output::Mode::Current | wl_output::Mode::Preferred, w as i32, h as i32, 60000); - out.scale(1); - out.done(); - } -} - -impl Dispatch for WaylandState { - fn request( - _state: &mut Self, - _client: &Client, - _resource: &WlOutput, - _request: wl_output::Request, - _data: &(), - _dhandle: &DisplayHandle, - _data_init: &mut DataInit<'_, Self>, - ) { - } -} - -pub struct WaylandServer { - pub display: Display, - pub state: WaylandState, - pub listener: UnixListener, - pub socket_path: PathBuf, -} - -impl WaylandServer { - pub fn bind(socket_path: &Path, output_w: u32, output_h: u32) -> anyhow::Result { - if socket_path.exists() { - let _ = std::fs::remove_file(socket_path); - } - let listener = UnixListener::bind(socket_path)?; - listener.set_nonblocking(true)?; - - let display: Display = Display::new()?; - let dh = display.handle(); - dh.create_global::(5, ()); - dh.create_global::(1, ()); - dh.create_global::(5, ()); - dh.create_global::(1, ()); - dh.create_global::(7, ()); - dh.create_global::(4, ()); - - Ok(Self { - display, - state: WaylandState::new(output_w, output_h), - listener, - socket_path: socket_path.to_path_buf(), - }) - } - - pub fn dispatch(&mut self) -> anyhow::Result<()> { - loop { - match self.listener.accept() { - Ok((stream, _)) => { - self.display - .handle() - .insert_client(stream, Arc::new(ClientState))?; - } - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(e) => return Err(e.into()), - } - } - self.display.dispatch_clients(&mut self.state)?; - self.display.flush_clients()?; - Ok(()) - } -} diff --git a/host-native/tests/e2e_compositor.rs b/host-native/tests/e2e_compositor.rs deleted file mode 100644 index e32333d..0000000 --- a/host-native/tests/e2e_compositor.rs +++ /dev/null @@ -1,313 +0,0 @@ -use std::fs::File; -use std::os::fd::AsFd; -use std::os::unix::net::UnixStream; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; - -use moon_plasma_host::compositor::MoonPlasmaCompositor; -use moon_plasma_host::renderer::SoftwareRenderer; -use moon_plasma_host::theme::ThemeTokens; -use moon_plasma_host::wasm::wm_wit::exports::moonplasma::wm::policy::LayoutMode; - -use wayland_client::protocol::{ - wl_buffer::WlBuffer, - wl_compositor::WlCompositor, - wl_registry::{self, WlRegistry}, - wl_shm::{self, WlShm}, - wl_shm_pool::WlShmPool, - wl_surface::WlSurface, -}; -use wayland_client::{Connection, Dispatch, QueueHandle, WEnum}; -use wayland_protocols::xdg::decoration::zv1::client::{ - zxdg_decoration_manager_v1::ZxdgDecorationManagerV1, - zxdg_toplevel_decoration_v1::{self, Mode as DecoMode, ZxdgToplevelDecorationV1}, -}; -use wayland_protocols::xdg::shell::client::{ - xdg_surface::{self, XdgSurface}, - xdg_toplevel::{self, XdgToplevel}, - xdg_wm_base::{self, XdgWmBase}, -}; - -struct ClientData { - compositor: Option, - shm: Option, - xdg_wm_base: Option, - deco_mgr: Option, - configured_size: Arc>>, - deco_mode: Arc>>, - acked_serial: Option, -} - -impl Dispatch for ClientData { - fn event( - state: &mut Self, - registry: &WlRegistry, - event: wl_registry::Event, - _: &(), - _: &Connection, - qh: &QueueHandle, - ) { - if let wl_registry::Event::Global { name, interface, version } = event { - match interface.as_str() { - "wl_compositor" => { - state.compositor = Some(registry.bind::(name, version.min(5), qh, ())); - } - "wl_shm" => { - state.shm = Some(registry.bind::(name, 1, qh, ())); - } - "xdg_wm_base" => { - state.xdg_wm_base = Some(registry.bind::(name, version.min(5), qh, ())); - } - "zxdg_decoration_manager_v1" => { - state.deco_mgr = Some(registry.bind::(name, 1, qh, ())); - } - _ => {} - } - } - } -} - -impl Dispatch for ClientData { - fn event(_: &mut Self, _: &WlCompositor, _: wayland_client::protocol::wl_compositor::Event, _: &(), _: &Connection, _: &QueueHandle) {} -} -impl Dispatch for ClientData { - fn event(_: &mut Self, _: &WlSurface, _: wayland_client::protocol::wl_surface::Event, _: &(), _: &Connection, _: &QueueHandle) {} -} -impl Dispatch for ClientData { - fn event(_: &mut Self, _: &WlShm, _: wl_shm::Event, _: &(), _: &Connection, _: &QueueHandle) {} -} -impl Dispatch for ClientData { - fn event(_: &mut Self, _: &WlShmPool, _: wayland_client::protocol::wl_shm_pool::Event, _: &(), _: &Connection, _: &QueueHandle) {} -} -impl Dispatch for ClientData { - fn event(_: &mut Self, _: &WlBuffer, _: wayland_client::protocol::wl_buffer::Event, _: &(), _: &Connection, _: &QueueHandle) {} -} -impl Dispatch for ClientData { - fn event(_: &mut Self, wm: &XdgWmBase, event: xdg_wm_base::Event, _: &(), _: &Connection, _: &QueueHandle) { - if let xdg_wm_base::Event::Ping { serial } = event { - wm.pong(serial); - } - } -} -impl Dispatch for ClientData { - fn event(state: &mut Self, surf: &XdgSurface, event: xdg_surface::Event, _: &(), _: &Connection, _: &QueueHandle) { - if let xdg_surface::Event::Configure { serial } = event { - surf.ack_configure(serial); - state.acked_serial = Some(serial); - } - } -} -impl Dispatch for ClientData { - fn event(state: &mut Self, _: &XdgToplevel, event: xdg_toplevel::Event, _: &(), _: &Connection, _: &QueueHandle) { - if let xdg_toplevel::Event::Configure { width, height, .. } = event { - if width > 0 && height > 0 { - *state.configured_size.lock().unwrap() = Some((width, height)); - } - } - } -} -impl Dispatch for ClientData { - fn event(_: &mut Self, _: &ZxdgDecorationManagerV1, _: wayland_protocols::xdg::decoration::zv1::client::zxdg_decoration_manager_v1::Event, _: &(), _: &Connection, _: &QueueHandle) {} -} -impl Dispatch for ClientData { - fn event(state: &mut Self, _: &ZxdgToplevelDecorationV1, event: zxdg_toplevel_decoration_v1::Event, _: &(), _: &Connection, _: &QueueHandle) { - if let zxdg_toplevel_decoration_v1::Event::Configure { mode } = event { - if let WEnum::Value(m) = mode { - *state.deco_mode.lock().unwrap() = Some(m); - } - } - } -} - -fn spawn_wayland_test_client( - socket_path: PathBuf, - title: &'static str, - app_id: &'static str, - shm_dir: PathBuf, - idx: usize, -) -> ( - std::thread::JoinHandle<()>, - Arc>>, - Arc>>, -) { - let configured_size = Arc::new(Mutex::new(None)); - let deco_mode = Arc::new(Mutex::new(None)); - let cfg_clone = configured_size.clone(); - let deco_clone = deco_mode.clone(); - - let handle = std::thread::spawn(move || { - let stream = UnixStream::connect(&socket_path).expect("connect to wayland socket"); - let conn = Connection::from_socket(stream).expect("wayland Connection::from_socket"); - let mut queue = conn.new_event_queue(); - let qh = queue.handle(); - let display = conn.display(); - let mut data = ClientData { - compositor: None, - shm: None, - xdg_wm_base: None, - deco_mgr: None, - configured_size: cfg_clone.clone(), - deco_mode: deco_clone, - acked_serial: None, - }; - let _reg = display.get_registry(&qh, ()); - queue.roundtrip(&mut data).expect("roundtrip 1"); - - let comp = data.compositor.as_ref().expect("wl_compositor").clone(); - let shm = data.shm.as_ref().expect("wl_shm").clone(); - let wm_base = data.xdg_wm_base.as_ref().expect("xdg_wm_base").clone(); - let deco_mgr = data.deco_mgr.as_ref().expect("zxdg_decoration_manager_v1").clone(); - - let surface = comp.create_surface(&qh, ()); - let xdg_surf = wm_base.get_xdg_surface(&surface, &qh, ()); - let toplevel = xdg_surf.get_toplevel(&qh, ()); - toplevel.set_title(title.into()); - toplevel.set_app_id(app_id.into()); - let _deco = deco_mgr.get_toplevel_decoration(&toplevel, &qh, ()); - - // Initial commit triggers ToplevelOpened -> WM configure - surface.commit(); - conn.flush().unwrap(); - - let deadline = Instant::now() + Duration::from_secs(3); - while cfg_clone.lock().unwrap().is_none() && Instant::now() < deadline { - let _ = queue.dispatch_pending(&mut data); - if let Some(guard) = conn.prepare_read() { - let _ = guard.read(); - } - let _ = queue.dispatch_pending(&mut data); - std::thread::sleep(Duration::from_millis(5)); - } - - let (w, h) = cfg_clone.lock().unwrap().expect("received WM configure size"); - - // Create backing SHM file and fill with slate #1e293b + cyan #38bdf8 center square - let stride = w * 4; - let byte_len = (stride * h) as usize; - let shm_file_path = shm_dir.join(format!("client-{idx}.shm")); - let file = File::options() - .read(true) - .write(true) - .create(true) - .truncate(true) - .open(&shm_file_path) - .unwrap(); - file.set_len(byte_len as u64).unwrap(); - let mut pixels = vec![0u8; byte_len]; - for y in 0..h { - for x in 0..w { - let off = ((y * w + x) * 4) as usize; - let in_center = (x - w / 2).abs() < 40 && (y - h / 2).abs() < 40; - // Little-endian ARGB8888: [B, G, R, A] - if in_center { - pixels[off] = 0xf8; - pixels[off + 1] = 0xbd; - pixels[off + 2] = 0x38; - pixels[off + 3] = 0xff; - } else { - pixels[off] = 0x3b; - pixels[off + 1] = 0x29; - pixels[off + 2] = 0x1e; - pixels[off + 3] = 0xff; - } - } - } - use std::io::Write; - (&file).write_all(&pixels).unwrap(); - - let pool = shm.create_pool(file.as_fd(), byte_len as i32, &qh, ()); - let buffer = pool.create_buffer(0, w, h, stride, wl_shm::Format::Argb8888, &qh, ()); - surface.attach(Some(&buffer), 0, 0); - surface.damage_buffer(0, 0, w, h); - surface.commit(); - conn.flush().unwrap(); - - std::thread::sleep(Duration::from_millis(150)); - }); - - (handle, configured_size, deco_mode) -} - -#[test] -fn e2e_wayland_client_with_moonbit_wm_and_ssd_decorations() { - let tmp = tempfile::tempdir().unwrap(); - let socket_path = tmp.path().join("wayland-moon-0"); - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).parent().unwrap().to_path_buf(); - let components_dir = root.join("build/components"); - let theme = ThemeTokens::load_file(&root.join("config/themes/moon-night.json")).unwrap(); - - let mut comp = MoonPlasmaCompositor::new(&socket_path, &components_dir, theme, 1280, 720) - .expect("boot compositor"); - - let (c1, cfg1, deco1) = spawn_wayland_test_client( - socket_path.clone(), - "MoonTerm", - "org.moonplasma.term", - tmp.path().to_path_buf(), - 1, - ); - - let deadline = Instant::now() + Duration::from_secs(3); - while Instant::now() < deadline { - comp.step().unwrap(); - if comp.windows.get(&1).and_then(|w| w.surface.as_ref()).is_some() { - break; - } - std::thread::sleep(Duration::from_millis(5)); - } - - assert_eq!(*deco1.lock().unwrap(), Some(DecoMode::ServerSide)); - let (cw, ch) = cfg1.lock().unwrap().expect("client 1 configured"); - assert!(cw > 1200 && ch > 600, "unexpected tiled size: {cw}x{ch}"); - - let pixmap = comp.compose_frame().expect("compose frame"); - let out_png = root.join("host-native/target/e2e_frame.png"); - SoftwareRenderer::save_png(&pixmap, &out_png).unwrap(); - - // Verify client surface center pixel (#38bdf8) landed inside the WM-assigned geometry! - let win = comp.windows.get(&1).unwrap(); - let cx = win.geometry.x + (win.geometry.w as i32) / 2; - let cy = win.geometry.y + (win.geometry.h as i32) / 2; - let px = pixmap.pixel(cx as u32, cy as u32).unwrap(); - assert_eq!( - (px.red(), px.green(), px.blue(), px.alpha()), - (0x38, 0xbd, 0xf8, 0xff), - "expected cyan client pixel at ({cx}, {cy})" - ); - - // Verify 0 component faults - assert!( - comp.wasm.shared.faults.lock().unwrap().is_empty(), - "unexpected faults: {:?}", - comp.wasm.shared.faults.lock().unwrap() - ); - - // Now open a 2nd Wayland client and verify BSP tiling splits the screen! - let (c2, cfg2, _) = spawn_wayland_test_client( - socket_path.clone(), - "Files", - "org.moonplasma.files", - tmp.path().to_path_buf(), - 2, - ); - - let deadline2 = Instant::now() + Duration::from_secs(3); - while Instant::now() < deadline2 { - comp.step().unwrap(); - if comp.windows.get(&2).and_then(|w| w.surface.as_ref()).is_some() { - break; - } - std::thread::sleep(Duration::from_millis(5)); - } - - let (cw2, _) = cfg2.lock().unwrap().expect("client 2 configured"); - assert!(cw2 < 700, "expected BSP split width < 700, got {cw2}"); - - // Test layout mode switch to Floating - comp.set_layout_mode(LayoutMode::Floating); - let _ = comp.compose_frame().unwrap(); - - let _ = c1.join(); - let _ = c2.join(); -} diff --git a/scripts/test.sh b/scripts/test.sh index f986de2..8d130d3 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -32,7 +32,6 @@ fi step "host integration tests (jco + Node)" (cd host && npm test) -if command -v cargo >/dev/null; then - step "native Wayland compositor + wasmtime tests (host-native)" - (cd host-native && cargo test) -fi +step "pure-MoonBit native Wayland compositor + e2e tests (compositor/)" +moon test --target native --warn-list -a compositor/renderer compositor/host +moon build --target native --warn-list -a compositor/bin