Files
chandra/compositor/nested/nested.mbt
T
VandClaude Opus 5.5 af774d76fe
CI / test (push) Failing after 16s
Rename the project to Chandra
moon-plasma / moonplasma / MoonPlasma / Moon Plasma become chandra / Chandra
everywhere: the WIT package (chandra:desktop, chandra:host, chandra:wm), the
MoonBit module (chandra/desktop) and generated bindings, the Rust host,
identifiers (ChandraCompositor), the session script (chandra-session) and
desktop entry (chandra.desktop), config and data paths
($XDG_CONFIG_HOME/chandra, share/chandra/modules), env vars (CHANDRA_*),
UI strings, docs and tests. The test fixture components are rebuilt against
the renamed WIT.

Saved panel.edn and state.edn are still read from the old
$XDG_CONFIG_HOME/moon-plasma until the first save writes the new copy.

The remote repository keeps its experiments/moon-plasma name for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hi3L9oVBoRd373Qr4n
2026-11-25 17:12:57 +00:00

592 lines
17 KiB
MoonBit

///| Nested backend: shows the compositor's frames in a window of the host
/// Wayland session. The compositor is a plain Wayland *client* here (wl_shm
/// buffers over SCM_RIGHTS + xdg_toplevel), reusing the same wire code and C
/// shim as the server side, and queues host pointer/keyboard input for the compositor.
///| Input forwarded from the host session (pointer in window pixels; key = evdev code).
pub(all) enum InputEvent {
PointerMove(Double, Double)
PointerButton(UInt, Bool)
/// Wheel/touchpad scroll: axis (0 vertical, 1 horizontal), distance in surface pixels
/// (positive = down/right) and wheel notches (0 when not from a wheel, e.g. a touchpad).
Scroll(UInt, Double, Int)
Key(UInt, Bool)
Modifiers(UInt, UInt, UInt, UInt)
}
///|
pub(all) struct NestedWindow {
input : Array[InputEvent]
fds : Array[Int]
mut keymap : Bytes
mut keyboard_id : UInt
mut shape_mgr_id : UInt
mut shape_dev_id : UInt
mut enter_serial : UInt
mut shape_applied : UInt
fd : Int
rx : Array[Byte]
globals : Map[String, (UInt, UInt)]
live_buffers : Map[UInt, Bool]
mut next_id : UInt
mut comp_id : UInt
mut shm_id : UInt
mut wm_id : UInt
mut seat_id : UInt
mut surf_id : UInt
mut xdg_surf_id : UInt
mut toplevel_id : UInt
mut pointer_id : UInt
/// wl_pointer.axis_discrete steps waiting for their axis event (vertical, horizontal).
mut discrete_v : Int
mut discrete_h : Int
mut sync_cb : UInt
mut sync_done : Bool
mut frame_cb : UInt
mut frame_pending : Bool
mut configured : Bool
mut closed : Bool
mut px : Double
mut py : Double
/// Current window size: what the compositor draws at and what each frame is attached as.
mut width : Int
mut height : Int
/// Size from the latest xdg_toplevel.configure (0 = the host leaves it to us), applied when
/// the xdg_surface.configure that ends the sequence arrives.
mut cfg_w : Int
mut cfg_h : Int
/// Largest size the host suggests for a window (xdg_toplevel.configure_bounds: the screen
/// minus its panels); 0 = unknown. The first size is fitted inside it.
mut bound_w : Int
mut bound_h : Int
/// Set when the host resized the window; cleared by take_resize.
mut resized : Bool
/// The first configure was handled.
mut mapped : Bool
}
///| Smallest size the window may be resized to (the panel and a window or two still fit).
pub let min_width : Int = 640
///|
pub let min_height : Int = 400
///|
fn NestedWindow::alloc(self : NestedWindow) -> UInt {
let id = self.next_id
self.next_id = id + 1U
id
}
///|
fn NestedWindow::send(self : NestedWindow, msg : Bytes, send_fd? : Int = -1) -> Unit {
ignore(@sys.sendmsg_fd(self.fd, msg, send_fd))
}
///|
fn NestedWindow::bind(self : NestedWindow, iface : String, ver : UInt) -> UInt {
match self.globals.get(iface) {
None => 0U
Some((name, adv)) => {
let id = self.alloc()
let w = @wayland.WireWriter::new()
w.u32(name)
w.str(iface)
w.u32(if ver < adv { ver } else { adv })
w.u32(id)
self.send(w.finish_msg(2U, 0U))
id
}
}
}
///| Read and dispatch everything pending on the host socket (non-blocking).
fn NestedWindow::pump_events(self : NestedWindow) -> Unit {
let scratch : FixedArray[Byte] = FixedArray::make(16384, b'\x00')
while @sys.poll_read(self.fd, 0) > 0 {
let (n, rfd) = @sys.recvmsg_fd(self.fd, scratch, 16384)
if rfd >= 0 {
self.fds.push(rfd)
}
if n <= 0 {
self.closed = true
return
}
for i = 0; i < n; i = i + 1 {
self.rx.push(scratch[i])
}
}
let mut off = 0
while off + 8 <= self.rx.length() {
let obj = @wayland.read_u32_le(self.rx, off)
let word2 = @wayland.read_u32_le(self.rx, off + 4)
let size = ((word2 >> 16) & 0xFFFFU).reinterpret_as_int()
let op = word2 & 0xFFFFU
if size < 8 || off + size > self.rx.length() {
break
}
let r = @wayland.WireReader::from_array(self.rx, off + 8)
self.dispatch(obj, op, r)
off = off + size
}
if off > 0 {
let rest : Array[Byte] = []
for i = off; i < self.rx.length(); i = i + 1 {
rest.push(self.rx[i])
}
self.rx.clear()
for b in rest {
self.rx.push(b)
}
}
}
///|
fn NestedWindow::dispatch(
self : NestedWindow,
obj : UInt,
op : UInt,
r : @wayland.WireReader,
) -> Unit {
if obj == 1U {
if op == 0U {
let _id = r.u32()
let _code = r.u32()
@sys.log("nested: host wl_display error: " + r.str())
self.closed = true
}
} else if obj == 2U {
if op == 0U {
let name = r.u32()
let iface = r.str()
let ver = r.u32()
self.globals.set(iface, (name, ver))
}
} else if self.sync_cb != 0U && obj == self.sync_cb {
self.sync_done = true
} else if self.frame_cb != 0U && obj == self.frame_cb {
self.frame_pending = false
self.frame_cb = 0U
} else if obj == self.wm_id {
if op == 0U {
// xdg_wm_base.ping(serial) -> pong
let serial = r.u32()
let w = @wayland.WireWriter::new()
w.u32(serial)
self.send(w.finish_msg(self.wm_id, 3U))
}
} else if obj == self.xdg_surf_id {
if op == 0U {
// configure(serial) -> ack_configure
let serial = r.u32()
let w = @wayland.WireWriter::new()
w.u32(serial)
self.send(w.finish_msg(self.xdg_surf_id, 4U))
self.configured = true
// The host chose a size (resized, maximized, tiled or fullscreen): draw at that size, so
// the desktop is never cropped to a window smaller than our buffer.
// Left to us, the first size still has to fit the screen the host has room for.
let fit_w = if !self.mapped && self.bound_w > 0 && self.width > self.bound_w {
clamp_min(self.bound_w, min_width)
} else {
self.width
}
let fit_h = if !self.mapped && self.bound_h > 0 && self.height > self.bound_h {
clamp_min(self.bound_h, min_height)
} else {
self.height
}
self.mapped = true
let nw = if self.cfg_w > 0 { clamp_min(self.cfg_w, min_width) } else { fit_w }
let nh = if self.cfg_h > 0 { clamp_min(self.cfg_h, min_height) } else { fit_h }
if nw != self.width || nh != self.height {
self.width = nw
self.height = nh
self.resized = true
}
}
} else if obj == self.toplevel_id {
if op == 0U {
// configure(width, height, states): 0 x 0 means "pick your own size".
self.cfg_w = r.i32()
self.cfg_h = r.i32()
} else if op == 1U {
self.closed = true
} else if op == 2U {
// configure_bounds(width, height), xdg_wm_base v4+
self.bound_w = r.i32()
self.bound_h = r.i32()
}
} else if obj == self.seat_id {
if op == 0U {
let caps = r.u32()
if (caps & 1U) != 0U && self.pointer_id == 0U {
let id = self.alloc()
let w = @wayland.WireWriter::new()
w.u32(id)
self.send(w.finish_msg(self.seat_id, 0U))
self.pointer_id = id
if self.shape_mgr_id != 0U {
let dev = self.alloc()
let wd = @wayland.WireWriter::new()
wd.u32(dev)
wd.u32(id)
self.send(wd.finish_msg(self.shape_mgr_id, 1U))
self.shape_dev_id = dev
}
}
if (caps & 2U) != 0U && self.keyboard_id == 0U {
let id = self.alloc()
let w = @wayland.WireWriter::new()
w.u32(id)
self.send(w.finish_msg(self.seat_id, 1U))
self.keyboard_id = id
}
}
} else if self.keyboard_id != 0U && obj == self.keyboard_id {
match op {
0U => {
// keymap(format, fd, size)
let _format = r.u32()
let size = r.u32().reinterpret_as_int()
if self.fds.length() > 0 {
let fd = self.fds.remove(0)
self.keymap = @sys.mmap_read(fd, size)
@sys.close_fd(fd)
}
}
3U => {
let _serial = r.u32()
let _time = r.u32()
let key = r.u32()
let state = r.u32()
self.input.push(Key(key, state == 1U))
}
4U => {
let _serial = r.u32()
let dep = r.u32()
let lat = r.u32()
let lock = r.u32()
let group = r.u32()
self.input.push(Modifiers(dep, lat, lock, group))
}
_ => ()
}
} else if self.pointer_id != 0U && obj == self.pointer_id {
match op {
0U => {
self.enter_serial = r.u32()
self.shape_applied = 0U // host resets the cursor on enter
let _surf = r.u32()
self.px = r.i32().to_double() / 256.0
self.py = r.i32().to_double() / 256.0
self.input.push(PointerMove(self.px, self.py))
}
2U => {
let _time = r.u32()
self.px = r.i32().to_double() / 256.0
self.py = r.i32().to_double() / 256.0
self.input.push(PointerMove(self.px, self.py))
}
3U => {
let _serial = r.u32()
let _time = r.u32()
let button = r.u32()
let state = r.u32()
self.input.push(PointerButton(button, state == 1U))
}
4U => {
let _time = r.u32()
let axis = r.u32()
let value = r.i32().to_double() / 256.0
if axis == 0U {
self.input.push(Scroll(0U, value, self.discrete_v))
self.discrete_v = 0
} else if axis == 1U {
self.input.push(Scroll(1U, value, self.discrete_h))
self.discrete_h = 0
}
}
8U => {
// axis_discrete (seat v5+): sent before the axis event of the same frame.
let axis = r.u32()
let steps = r.i32()
if axis == 0U {
self.discrete_v = steps
} else if axis == 1U {
self.discrete_h = steps
}
}
_ => ()
}
} else if self.live_buffers.contains(obj) {
if op == 0U {
// wl_buffer.release -> destroy it
self.live_buffers.remove(obj)
let w = @wayland.WireWriter::new()
self.send(w.finish_msg(obj, 0U))
}
}
}
///| wl_display.sync and wait for the callback.
fn NestedWindow::roundtrip(self : NestedWindow) -> Unit {
let cb = self.alloc()
self.sync_cb = cb
self.sync_done = false
let w = @wayland.WireWriter::new()
w.u32(cb)
self.send(w.finish_msg(1U, 0U))
let mut tries = 0
while !self.sync_done && !self.closed && tries < 500 {
ignore(@sys.poll_read(self.fd, 10))
self.pump_events()
tries = tries + 1
}
self.sync_cb = 0U
}
///| Connect to the host compositor and open a window of `width` x `height`.
/// `display` is a socket name (relative to `runtime_dir`) or an absolute path.
pub fn NestedWindow::open(
display : String,
runtime_dir : String,
title : String,
app_id : String,
width : Int,
height : Int,
) -> NestedWindow? {
let path = if display.length() > 0 && display[0] == '/' {
display
} else {
runtime_dir + "/" + display
}
let fd = @sys.unix_connect(path)
if fd < 0 {
return None
}
let self : NestedWindow = {
fd,
input: [],
fds: [],
keymap: Bytes::from_array([]),
keyboard_id: 0U,
shape_mgr_id: 0U,
shape_dev_id: 0U,
enter_serial: 0U,
shape_applied: 0U,
rx: [],
globals: {},
live_buffers: {},
next_id: 3U,
comp_id: 0U,
shm_id: 0U,
wm_id: 0U,
seat_id: 0U,
surf_id: 0U,
xdg_surf_id: 0U,
toplevel_id: 0U,
pointer_id: 0U,
discrete_v: 0,
discrete_h: 0,
sync_cb: 0U,
sync_done: false,
frame_cb: 0U,
frame_pending: false,
configured: false,
closed: false,
px: 0.0,
py: 0.0,
width,
height,
cfg_w: 0,
cfg_h: 0,
bound_w: 0,
bound_h: 0,
resized: false,
mapped: false,
}
let w = @wayland.WireWriter::new()
w.u32(2U)
self.send(w.finish_msg(1U, 1U)) // get_registry
self.roundtrip()
self.comp_id = self.bind("wl_compositor", 4U)
self.shm_id = self.bind("wl_shm", 1U)
self.wm_id = self.bind("xdg_wm_base", 4U) // v4: configure_bounds
self.seat_id = self.bind("wl_seat", 5U)
self.shape_mgr_id = self.bind("wp_cursor_shape_manager_v1", 1U)
if self.comp_id == 0U || self.shm_id == 0U || self.wm_id == 0U {
@sys.log("nested: host compositor lacks wl_compositor/wl_shm/xdg_wm_base")
return None
}
self.surf_id = self.alloc()
let w1 = @wayland.WireWriter::new()
w1.u32(self.surf_id)
self.send(w1.finish_msg(self.comp_id, 0U))
self.xdg_surf_id = self.alloc()
let w2 = @wayland.WireWriter::new()
w2.u32(self.xdg_surf_id)
w2.u32(self.surf_id)
self.send(w2.finish_msg(self.wm_id, 2U))
self.toplevel_id = self.alloc()
let w3 = @wayland.WireWriter::new()
w3.u32(self.toplevel_id)
self.send(w3.finish_msg(self.xdg_surf_id, 1U))
let w4 = @wayland.WireWriter::new()
w4.str(title)
self.send(w4.finish_msg(self.toplevel_id, 2U))
let w5 = @wayland.WireWriter::new()
w5.str(app_id)
self.send(w5.finish_msg(self.toplevel_id, 3U))
// Resizable: the host may give us any size from the minimum up (no max size), and the
// compositor follows it (see take_resize).
let w7 = @wayland.WireWriter::new()
w7.i32(min_width)
w7.i32(min_height)
self.send(w7.finish_msg(self.toplevel_id, 8U)) // set_min_size
self.send(@wayland.WireWriter::new().finish_msg(self.surf_id, 6U)) // commit
let mut tries = 0
while !self.configured && !self.closed && tries < 500 {
ignore(@sys.poll_read(self.fd, 10))
self.pump_events()
tries = tries + 1
}
if !self.configured {
@sys.log("nested: host never sent xdg_surface.configure")
return None
}
Some(self)
}
///| Pump host events (input is queued; see take_input). False once the
/// window was closed or the host went away.
pub fn NestedWindow::poll(self : NestedWindow) -> Bool {
self.pump_events()
!self.closed
}
///|
fn clamp_min(v : Int, lo : Int) -> Int {
if v < lo { lo } else { v }
}
///| The new window size if the host resized the window since the last call. The caller resizes
/// the desktop to it before presenting the next frame.
pub fn NestedWindow::take_resize(self : NestedWindow) -> (Int, Int)? {
if !self.resized {
return None
}
self.resized = false
Some((self.width, self.height))
}
///| Take all input received since the last call.
pub fn NestedWindow::take_input(self : NestedWindow) -> Array[InputEvent] {
let out = self.input.copy()
self.input.clear()
out
}
///| Show `pixmap` (RGBA8888) in the window. Skipped while the host has not yet
/// consumed the previous frame, so a slow host never builds a backlog.
pub fn NestedWindow::present(self : NestedWindow, pixmap : @renderer.Pixmap) -> Unit {
if self.frame_pending || self.closed {
return
}
let w = pixmap.width
let h = pixmap.height
let len = w * 4 * h
// RGBA -> little-endian ARGB8888 (B, G, R, A).
let out : FixedArray[Byte] = FixedArray::make(len, b'\x00')
for i = 0; i < w * h; i = i + 1 {
let o = i * 4
out[o] = pixmap.data[o + 2]
out[o + 1] = pixmap.data[o + 1]
out[o + 2] = pixmap.data[o]
out[o + 3] = b'\xff'
}
let memfd = @sys.memfd_create("chandra-frame", len)
if memfd < 0 {
return
}
ignore(@sys.pwrite_bytes(memfd, Bytes::from_fixedarray(out), 0))
self.send_frame(memfd, w, h)
}
///| Show the host's framebuffer (drawn by the host rasteriser) in the window: the host fills a
/// memfd with it and this hands that to the host compositor, so no pixels pass through here.
pub fn NestedWindow::present_frame(self : NestedWindow, w : Int, h : Int) -> Unit {
if self.frame_pending || self.closed {
return
}
let memfd = @sys.frame_memfd()
if memfd < 0 {
return
}
self.send_frame(memfd, w, h)
}
///| Attach the ARGB8888 frame in `memfd` (w x h) to the window and ask for a frame callback.
/// Takes the descriptor: it is closed here once sent.
fn NestedWindow::send_frame(self : NestedWindow, memfd : Int, w : Int, h : Int) -> Unit {
let stride = w * 4
let len = stride * h
let pool = self.alloc()
let wp = @wayland.WireWriter::new()
wp.u32(pool)
wp.i32(len)
self.send(wp.finish_msg(self.shm_id, 0U), send_fd=memfd)
@sys.close_fd(memfd)
let buf = self.alloc()
let wb = @wayland.WireWriter::new()
wb.u32(buf)
wb.i32(0)
wb.i32(w)
wb.i32(h)
wb.i32(stride)
wb.u32(0U)
self.send(wb.finish_msg(pool, 0U))
self.send(@wayland.WireWriter::new().finish_msg(pool, 1U)) // pool.destroy
self.live_buffers.set(buf, true)
let wa = @wayland.WireWriter::new()
wa.u32(buf)
wa.i32(0)
wa.i32(0)
self.send(wa.finish_msg(self.surf_id, 1U))
let wd = @wayland.WireWriter::new()
wd.i32(0)
wd.i32(0)
wd.i32(w)
wd.i32(h)
self.send(wd.finish_msg(self.surf_id, 9U))
self.frame_cb = self.alloc()
let wf = @wayland.WireWriter::new()
wf.u32(self.frame_cb)
self.send(wf.finish_msg(self.surf_id, 3U))
self.frame_pending = true
self.send(@wayland.WireWriter::new().finish_msg(self.surf_id, 6U))
}
///|
pub fn NestedWindow::close(self : NestedWindow) -> Unit {
@sys.close_fd(self.fd)
}
///| True when the host is ready for a new frame (avoids rendering frames that would be dropped).
pub fn NestedWindow::frame_ready(self : NestedWindow) -> Bool {
!self.frame_pending && !self.closed
}
///| Ask the host to show cursor `shape` (wp_cursor_shape_v1 enum value) over our
/// window. No-op if unchanged, unsupported by the host, or the pointer is outside.
pub fn NestedWindow::set_cursor_shape(self : NestedWindow, shape : UInt) -> Unit {
if self.shape_dev_id == 0U || self.enter_serial == 0U || shape == self.shape_applied {
return
}
let w = @wayland.WireWriter::new()
w.u32(self.enter_serial)
w.u32(shape)
self.send(w.finish_msg(self.shape_dev_id, 1U))
self.shape_applied = shape
}