Files
chandra/compositor/app/app.mbt
T
Claude d521d0d840
CI / test (push) Successful in 4m10s
Kiosk mode: --kiosk CMD runs one fullscreen app, locked down, restarted when it exits
No panel, no compositor shortcuts or desktop menus, the focused window
fullscreen (dialogs float), CMD restarted with backoff. Ctrl+Alt+Shift+Escape
or chandra-ctl kiosk lock|unlock|status for admin work. --app-id sets the X11
WM_CLASS / Wayland app id of Chandra's own window. scripts/gamerig-kiosk.sh
runs Chandra as a gamerig rig's library window on its NVIDIA Xorg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgvjzw8hHirxRsXSsE
2026-11-26 02:22:03 +00:00

553 lines
20 KiB
MoonBit

///| The compositor's entry point as a library: argument parsing and the main loop, with the
/// operating system reached only through `@sys`. The wasm component (components/compositor)
/// calls `run`; on the native side it is the same code with `@sys` backed by a C shim.
///
/// Arguments: --socket PATH --theme PATH --window --drm --x11 --fullscreen --gfx-out PNG --serve
/// --size WxH. --x11 shows the desktop on the X server in $DISPLAY (a window, or the whole screen
/// when no window manager runs there); --fullscreen asks a window manager for a fullscreen window;
/// --login-session makes it the user's desktop session as --drm does (power actions, the polkit
/// agent, apps' dark/light preference), for chandra-session --x11.
/// --drm runs as a login session: the host takes the display (DRM/KMS) and input (libinput).
/// With --gfx-out alone one frame is written and the program exits; add --serve to keep running
/// and rewrite the PNG about twice a second (for looking at a live compositor without a display).
/// --kiosk CMD: kiosk mode (docs/kiosk.md): no panel, no shortcuts or desktop menus, every window
/// fullscreen, CMD started and started again when its window goes ("" starts nothing);
/// Ctrl+Alt+Shift+Escape unlocks it for admin work. --app-id NAME: the X11 WM_CLASS / Wayland app
/// id of Chandra's own window (--x11, --window), so a window manager or wmctrl can find it.
///| Parse a decimal integer; None unless every character is a digit.
fn parse_dec(s : String) -> Int? {
if s.length() == 0 || s.length() > 6 {
return None
}
let mut n = 0
for ch in s {
let d = ch.to_int() - 48
if d < 0 || d > 9 {
return None
}
n = n * 10 + d
}
Some(n)
}
///| "WxH" -> (W, H), both positive.
fn parse_size(s : String) -> (Int, Int)? {
let mut x = -1
for i = 0; i < s.length(); i = i + 1 {
if s[i] == 'x' {
x = i
}
}
if x <= 0 {
return None
}
match (parse_dec(s[:x].to_string()), parse_dec(s[x + 1:].to_string())) {
(Some(w), Some(h)) if w > 0 && h > 0 => Some((w, h))
_ => None
}
}
///| Run the compositor until it exits. Returns the process exit code.
pub fn run(args : Array[String]) -> Int {
let mut socket_path = "/tmp/wayland-moon-0"
let mut theme_path = "config/themes/moon-night.json"
let mut gfx_out = ""
let mut windowed = false
let mut serve = false
let mut profile = false
let mut drm = false
let mut x11 = false
let mut fullscreen = false
let mut login = false
let mut restore = true
let mut kiosk : String? = None
let mut app_id = "chandra"
let mut width = 1280
let mut height = 720
let mut i = 0
while i < args.length() {
let a = args[i]
if a == "--socket" && i + 1 < args.length() {
socket_path = args[i + 1]
i = i + 2
} else if a == "--theme" && i + 1 < args.length() {
theme_path = args[i + 1]
i = i + 2
} else if a == "--window" {
windowed = true
i = i + 1
} else if a == "--drm" {
drm = true
i = i + 1
} else if a == "--x11" {
x11 = true // a window (or, with no window manager, the whole screen) on $DISPLAY
i = i + 1
} else if a == "--login-session" {
login = true // this is the user's desktop session (as --drm is): power, polkit, system theme
i = i + 1
} else if a == "--fullscreen" {
fullscreen = true // --x11 under a window manager: ask it for a fullscreen window
i = i + 1
} else if a == "--no-restore" {
restore = false // don't reopen the apps of the last session
i = i + 1
} else if a == "--kiosk" && i + 1 < args.length() {
kiosk = Some(args[i + 1]) // one fullscreen app, locked down
restore = false
i = i + 2
} else if a == "--app-id" && i + 1 < args.length() {
app_id = args[i + 1]
i = i + 2
} else if a == "--profile" {
profile = true
i = i + 1
} else if a == "--serve" {
serve = true
i = i + 1
} else if a == "--gfx-out" && i + 1 < args.length() {
gfx_out = args[i + 1]
i = i + 2
} else if a == "--size" && i + 1 < args.length() {
match parse_size(args[i + 1]) {
Some((w, h)) => {
width = w
height = h
}
None => {
@sys.log("bad --size " + args[i + 1] + " (expected WxH)")
return 2
}
}
i = i + 2
} else {
i = i + 1
}
}
let raw_theme = @sys.read_file_bytes(theme_path)
let theme = if raw_theme.length() > 0 {
let sb = StringBuilder()
for j = 0; j < raw_theme.length(); j = j + 1 {
sb.write_char(Int::unsafe_to_char(raw_theme[j].to_int()))
}
@scene.ThemeTokens::from_json_string(sb.to_string())
} else {
@scene.ThemeTokens::moon_night()
}
// Login-session mode: take over the display and input, and size the desktop to the monitor.
let kms = if drm {
match @kms.Kms::open() {
Some(k) => {
width = k.width
height = k.height
Some(k)
}
None => {
@sys.log("failed to start the DRM backend (run from a login VT, not inside another session)")
return 1
}
}
} else {
None
}
// X11 mode: a window on an X server (NVIDIA's Xorg driver has no usable KMS path for us), or
// the whole screen when no window manager runs there. Opened first so the desktop gets its size.
let xwin = if x11 && !drm {
let display = match @sys.getenv("DISPLAY") {
"" => ":0"
d => d
}
match @x11.X11Window::open(display, "Chandra", app_id, width, height, fullscreen) {
Some(x) => {
width = x.width
height = x.height
Some(x)
}
None => {
@sys.log("failed to open a window on the X display " + display)
return 1
}
}
} else {
None
}
let gfx_surface = @gfx.Surface::new({ width: Some(width), height: Some(height) })
match @host.ChandraCompositor::new(socket_path, theme, width, height) {
None => {
match kms {
Some(k) => k.close()
None => ()
}
@sys.log("failed to bind Wayland socket at " + socket_path)
1
}
Some(comp) => {
comp.shell.persist = true // remember which modules are loaded in the panel
let login = drm || login
comp.sync_system_theme = login // the login session sets apps' dark/light preference
comp.login_session = login // and power actions (suspend, power off) act on the machine
// GPU or not (CHANDRA_RENDER overrides): without one the desktop asks less of the CPU.
let (rmode, rwhy) = @shell.detect_render_mode()
comp.shell.set_render_detected(rmode, rwhy)
comp.restore_state() // and the layout mode and recent apps from the last session
@sys.log(comp.shell.render_summary())
comp.shell.screen_w = width
// Screenshots and recordings read the host's framebuffer (it draws the desktop).
comp.frame_source = Some(fn() { Some(@raster.read_frame(comp.output_w, comp.output_h)) })
// Recording streams frames from the host straight to the encoder.
comp.frame_recorder = Some({
grab: fn(r, pointer, px, py) { @raster.grab_recording_frame(r, pointer, px, py) },
send: fn(fd) { @raster.send_recording_frame(fd) },
})
// And screenshots crop and encode the frozen screen there.
comp.frame_shots = Some({
snapshot: fn() { @raster.snapshot_frame() },
png: fn(r) { @raster.snapshot_png(r) },
pixels: fn(r, w, h) { @raster.snapshot_pixels(r, w, h) },
})
if gfx_out.length() > 0 && !serve {
match comp.compose_scene() {
Some(sg) => @raster.submit(sg)
None => ()
}
ignore(@raster.write_frame_png(gfx_out))
comp.close()
@sys.log("frame written to " + gfx_out)
return 0
}
let nested = if windowed {
let display = match @sys.getenv("WAYLAND_DISPLAY") {
"" => "wayland-0"
d => d
}
let rt = match @sys.getenv("XDG_RUNTIME_DIR") {
"" => "/tmp"
d => d
}
match @nested.NestedWindow::open(display, rt, "chandra", app_id, width, height) {
Some(n) => Some(n)
None => {
@sys.log("failed to open a window on the host Wayland display")
comp.close()
return 1
}
}
} else {
None
}
match kms {
Some(k) => comp.server.set_keymap(k.keymap)
None => ()
}
@sys.log("chandra compositor listening on " + socket_path)
// chandra-ctl's socket (reload panel modules from a script); SIGUSR1 reloads too.
ignore(comp.start_control(@host.control_socket_path(@sys.getenv("XDG_RUNTIME_DIR"), socket_path)))
match kiosk {
Some(cmd) => {
@sys.log("kiosk mode" + (if cmd.length() > 0 { ": " + cmd } else { "" }))
comp.start_kiosk(cmd)
}
None => ()
}
if login {
comp.start_auth_agent() // polkit's password prompts (run0, pkexec): Chandra's dialog
}
if restore {
ignore(comp.restore_session()) // reopen the windows the last session ended with
}
let mut frames = 0
let idle = IdleClock::new()
// CHANDRA_FRAME_TRACE=1: one log line per drawn frame (when, and how long composing and
// rasterising took), for measuring how smooth animations are.
let trace = @sys.getenv("CHANDRA_FRAME_TRACE").length() > 0
let pacer = Pacer::{ last_ms: 0UL }
// A changed frame waits here until the display can take it (no page flip in flight).
let mut need_present = true
// --profile: every 3 s print how long each frame part took on average.
let mut p_t0 = @sys.monotonic_ms()
let mut p_n = 0
let mut p_step = 0UL
let mut p_comp = 0UL
while true {
frames = frames + 1
let f0 = @sys.monotonic_ms()
match kms {
Some(k) => {
if !k.poll() || comp.quit_requested {
break
}
let now_ms = @sys.monotonic_ms().to_uint()
let input = k.take_input()
for ev in input {
comp.handle_input(ev, now_ms)
}
// Idle timeouts (power.mbt): screen off / on, suspend.
match comp.power_tick(@sys.monotonic_ms()) {
ScreenOff => k.set_power(false)
ScreenOn => {
k.set_power(true)
need_present = true
}
Suspend => comp.system_power(0)
NoChange => ()
}
comp.step()
let f1 = @sys.monotonic_ms()
k.set_cursor_shape(comp.desired_cursor())
// The host draws; only a changed desktop is sent, and the frame is shown by the host
// straight from its framebuffer.
// Draw only when the display can take the frame (no page flip in flight): a frame
// drawn meanwhile would never be seen, and drawing it costs a whole frame's CPU.
let changed = if k.frame_ready() || comp.screen_off || pacer.overdue() {
draw_frame(comp, trace, pacer)
} else {
false
}
if changed {
need_present = true
}
if need_present && k.frame_ready() {
k.present_frame()
need_present = false
}
if profile {
p_n = p_n + 1
p_step = p_step + (f1 - f0)
p_comp = p_comp + (@sys.monotonic_ms() - f1)
let now = @sys.monotonic_ms()
if now - p_t0 >= 3000UL {
@sys.log("profile: " + p_n.to_string() + " frames/3s step " + p_step.to_string() + " ms compose+present " + p_comp.to_string() + " ms (shell " + comp.prof_shell_ms.to_string() + " ms, raster " + comp.prof_raster_ms.to_string() + " ms)")
p_t0 = now
p_n = 0
p_step = 0UL
p_comp = 0UL
comp.prof_shell_ms = 0UL
comp.prof_raster_ms = 0UL
}
}
// With the screen off nothing can be shown, so a waiting frame doesn't keep the loop busy.
let waiting = need_present && !comp.screen_off
if input.length() == 0 && !changed && !waiting && !comp.has_timed_work() {
// Idle: sleep until a client, the seat or the clock has something.
let fds = comp.server.wait_fds()
fds.append(k.wait_fds())
fds.append(comp.control_fds()) // chandra-ctl
let pfd = comp.portal_fd() // apps asking the dark/light preference
if pfd >= 0 {
fds.push(pfd)
}
fds.append(comp.auth_fds()) // polkit asking for a password, and its helper
ignore(@sys.wait_readable(fds, comp.wake_timeout(idle.timeout())))
} else {
// Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work.
let spent = (@sys.monotonic_ms() - f0).to_int()
@sys.sleep_ms(if spent >= 8 { 1 } else { 8 - spent })
}
continue
}
None => ()
}
comp.step()
let f1 = @sys.monotonic_ms()
if comp.quit_requested {
break
}
// Whether this pass had anything to do; an idle pass sleeps on the fds instead of a frame.
let mut busy = false
let wait_fds = comp.server.wait_fds()
wait_fds.append(comp.control_fds()) // chandra-ctl
wait_fds.append(comp.auth_fds()) // polkit asking for a password, and its helper
match nested {
Some(n) => {
if !n.poll() {
break
}
if n.keymap.length() > 0 {
comp.server.set_keymap(n.keymap)
}
// The window was resized (or maximized / made fullscreen): follow it, or the
// desktop stays drawn at the old size and is cropped by the smaller window.
match n.take_resize() {
Some((nw, nh)) => {
width = nw
height = nh
comp.resize(nw, nh)
need_present = true
busy = true
}
None => ()
}
let now_ms = @sys.monotonic_ms().to_uint()
let input = n.take_input()
for ev in input {
comp.handle_input(ev, now_ms)
}
n.set_cursor_shape(comp.desired_cursor())
// As on a display: draw when the host compositor can take the frame.
if (n.frame_ready() || pacer.overdue()) && draw_frame(comp, trace, pacer) {
need_present = true
busy = true
}
if need_present && n.frame_ready() {
n.present_frame(width, height)
need_present = false
}
busy = busy || input.length() > 0 || need_present
wait_fds.push(n.fd)
}
None =>
match xwin {
Some(x) => {
if !x.poll() {
break
}
if x.keymap.length() > 0 {
comp.server.set_keymap(x.keymap)
}
// The window or the screen (xrandr) changed size: draw the desktop at the new size.
match x.take_resize() {
Some((nw, nh)) => {
width = nw
height = nh
comp.resize(nw, nh)
need_present = true
busy = true
}
None => ()
}
if x.take_redraw() {
need_present = true // exposed: the X server has no copy of what was there
}
let now_ms = @sys.monotonic_ms().to_uint()
let input = x.take_input()
for ev in input {
comp.handle_input(ev, now_ms)
}
x.set_cursor_shape(comp.desired_cursor())
if (x.frame_ready() || pacer.overdue()) && draw_frame(comp, trace, pacer) {
need_present = true
busy = true
}
if need_present && x.frame_ready() {
x.present_frame(width, height)
need_present = false
}
busy = busy || input.length() > 0 || need_present
wait_fds.append(x.wait_fds())
}
None => {
comp.handle_gfx_events(gfx_surface)
if draw_frame(comp, trace, pacer) {
need_present = serve && gfx_out.length() > 0
busy = true
}
// No display: --serve keeps a PNG of the latest frame for looking at a live compositor.
if serve && gfx_out.length() > 0 && frames % 30 == 0 && need_present {
ignore(@raster.write_frame_png(gfx_out))
need_present = false
}
busy = busy || need_present
}
}
}
if profile {
p_n = p_n + 1
p_step = p_step + (f1 - f0)
p_comp = p_comp + (@sys.monotonic_ms() - f1)
let now = @sys.monotonic_ms()
if now - p_t0 >= 3000UL {
@sys.log("profile: " + p_n.to_string() + " frames/3s step " + p_step.to_string() + " ms compose+present " + p_comp.to_string() + " ms (shell " + comp.prof_shell_ms.to_string() + " ms, raster " + comp.prof_raster_ms.to_string() + " ms)")
p_t0 = now
p_n = 0
p_step = 0UL
p_comp = 0UL
comp.prof_shell_ms = 0UL
comp.prof_raster_ms = 0UL
}
}
if busy || comp.has_timed_work() {
// About 60 frames a second: sleep what is left of 16 ms after the work.
let spent = (@sys.monotonic_ms() - f0).to_int()
@sys.sleep_ms(if spent >= 16 { 1 } else { 16 - spent })
} else {
ignore(@sys.wait_readable(wait_fds, comp.wake_timeout(idle.timeout())))
}
}
if kiosk is None {
comp.save_session() // what is open now is reopened at the next start
}
match kms {
Some(k) => k.close()
None => ()
}
comp.close()
0
}
}
}
///| When the last frame was drawn: an output that never says it is ready again (a hidden nested
/// window gets no frame callbacks) still gets a frame now and then, so screenshots, recordings
/// and clients waiting on frame callbacks carry on.
struct Pacer {
mut last_ms : UInt64
}
///|
fn Pacer::overdue(self : Pacer) -> Bool {
@sys.monotonic_ms() - self.last_ms >= 250UL
}
///| Compose the desktop and hand a changed frame to the host to draw. True when it changed.
fn draw_frame(comp : @host.ChandraCompositor, trace : Bool, pacer : Pacer) -> Bool {
let c0 = @sys.monotonic_ms()
pacer.last_ms = c0
match comp.compose_scene() {
Some(sg) => {
let r0 = @sys.monotonic_ms()
@raster.submit(sg)
let r1 = @sys.monotonic_ms()
comp.prof_raster_ms = comp.prof_raster_ms + (r1 - r0)
if trace {
@sys.log("frame " + r1.to_string() + " compose " + (r0 - c0).to_string() + " raster " + (r1 - r0).to_string())
}
true
}
None => false
}
}
///| How long an idle main loop may sleep. Nothing on screen changes without a client, the seat or
/// the display waking the loop, except what follows the wall clock (clocks, the desktop card,
/// system stats, notices), which changes on whole seconds. So an idle loop sleeps until just
/// before the next second turns, then checks every few ms until it has: one or two wakeups a
/// second instead of 60-125, and a clock that turns within a few tens of ms of the real one.
struct IdleClock {
/// The wall clock's seconds field last seen, and the monotonic time it was first seen.
mut sec : Int
mut sec_at : UInt64
}
///|
fn IdleClock::new() -> IdleClock {
{ sec: -1, sec_at: 0UL }
}
///| Milliseconds to sleep from now.
fn IdleClock::timeout(self : IdleClock) -> Int {
let now = @sys.monotonic_ms()
let s = @sys.wall_time_field(5)
if s != self.sec {
self.sec = s
self.sec_at = now
}
let since = (now - self.sec_at).to_int()
if since < 980 { 980 - since } else { 5 }
}