Replace Rust host-native with 100% pure-MoonBit Wayland compositor
CI / test (push) Successful in 36s

This commit is contained in:
Antigravity committed 2026-11-25 01:18:46 +00:00
1 parent 17a8a46cfd
commit ae4f3fa93c
31 files changed
+3647 -4962

No files matched your search

+48
View File
@@ -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)
}
}
}
+11
View File
@@ -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")
+274
View File
@@ -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)
}
+358
View File
@@ -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()
}
+10
View File
@@ -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"
+4
View File
@@ -0,0 +1,4 @@
import {
"moonbitlang/core/builtin",
"moonplasma/desktop/compositor/scene" @scene,
}
+32
View File
@@ -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
+668
View File
@@ -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)
}
+60
View File
@@ -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'
}
+4
View File
@@ -0,0 +1,4 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/json",
}
+127
View File
@@ -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
+521
View File
@@ -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)
}
+9
View File
@@ -0,0 +1,9 @@
import {
"moonbitlang/core/builtin",
}
supported_targets = "-all+native"
options(
"native-stub": [ "sys_stub.c" ],
)
+172
View File
@@ -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()
}
+293
View File
@@ -0,0 +1,293 @@
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
#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();
}
+7
View File
@@ -0,0 +1,7 @@
import {
"moonbitlang/core/builtin",
"moonplasma/desktop/compositor/sys" @sys,
"moonplasma/desktop/compositor/scene" @scene,
}
supported_targets = "-all+native"
+831
View File
@@ -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 => ()
}
}
+143
View File
@@ -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)
}