From ba82d3c59bcb24f7af7d173dd1dac9eadaeecb90 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:21:39 +0000 Subject: [PATCH] Idle desktop sleeps instead of redrawing; only changed parts of the screen are redrawn Measured headless and nested at 1080p (host-wasm), against main: - Idle: ~9.4% CPU per compositor -> ~0.35%. Idle frames cost ~1.3 ms, and the loop woke 60-125 times a second to find nothing had changed. - One 800x600 floating client animating at 60 fps: 33% -> 16% CPU; raster per frame ~4.5 ms -> ~0.9 ms. A full-screen tiled client: 65% -> 54% (its cost is now mostly copying the 8 MB buffer out of the client's shared memory). Changes: - shell: the wallpaper and desktop card ops (~1900, the moon disc is drawn per pixel) are kept and reused until what they are drawn from changes (size, theme, wallpaper, card position, date, hour:minute). This was ~75% of an idle frame. - FrameSig compares the background by identity first instead of op by op. - Host tables (windows, layouts, ...) are only sent to the host when their bytes change. - Main loop: a pass with no input, no changed frame and nothing waiting to be shown blocks in the new sys.wait-readable on the Wayland socket and clients (plus the nested host connection; the login session's seat, DRM and libinput fds are added by the host) until just before the wall clock's next second, then polls every 5 ms until it turns, so clocks still tick on time. Recording, pending screenshots and toasts keep the frame pace (ChandraCompositor::has_timed_work). - Host raster: works out what changed from the last frame. When only windows changed (a client drew, a window moved, focus moved) it redraws just their footprint (decoration and shadow included, old and new place), copying back only that part of the cached backdrop; anything else still redraws everything. A test checks the partial redraw is pixel-identical to a full one for a client redraw, a move and a focus change with stacking swapped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DPL5hku78wdzXtY9QsR9NW --- compositor/app/app.mbt | 74 +++++- compositor/host/compositor.mbt | 20 +- compositor/kms/kms_native.mbt | 15 ++ compositor/kms/kms_stub.c | 13 ++ compositor/kms/kms_wasm.mbt | 6 + compositor/scene/scene.mbt | 2 + compositor/shell/shell.mbt | 61 ++++- compositor/sys/sys_native.mbt | 10 + compositor/sys/sys_stub.c | 15 ++ compositor/sys/sys_wasm.mbt | 7 + compositor/wasm/wasm_host.mbt | 13 ++ compositor/wayland/server.mbt | 11 + host-wasm/src/kms.rs | 6 + host-wasm/src/main.rs | 12 +- host-wasm/src/raster.rs | 255 +++++++++++++++++++-- interface/chandra/host/sys/ffi.mbt | 32 ++- interface/chandra/host/sys/native_stub.mbt | 40 ++-- interface/chandra/host/sys/top.mbt | 14 ++ wit/host/sys.wit | 4 + 19 files changed, 542 insertions(+), 68 deletions(-) diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index 7094a59..5ab8edc 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -182,6 +182,7 @@ pub fn run(args : Array[String]) -> Int { ignore(comp.restore_session()) // reopen the windows the last session ended with } let mut frames = 0 + let idle = IdleClock::new() // 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. @@ -198,7 +199,8 @@ pub fn run(args : Array[String]) -> Int { break } let now_ms = @sys.monotonic_ms().to_uint() - for ev in k.take_input() { + let input = k.take_input() + for ev in input { comp.handle_input(ev, now_ms) } comp.step() @@ -206,14 +208,15 @@ pub fn run(args : Array[String]) -> Int { 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. - match comp.compose_scene() { + let changed = match comp.compose_scene() { Some(sg) => { let r0 = @sys.monotonic_ms() @raster.submit(sg) comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0) need_present = true + true } - None => () + None => false } if need_present && k.frame_ready() { k.present_frame() @@ -234,9 +237,16 @@ pub fn run(args : Array[String]) -> Int { comp.prof_raster_ms = 0UL } } - // 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 }) + if input.length() == 0 && !changed && !need_present && !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()) + ignore(@sys.wait_readable(fds, 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 => () @@ -246,6 +256,9 @@ pub fn run(args : Array[String]) -> Int { 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() match nested { Some(n) => { if !n.poll() { @@ -262,11 +275,13 @@ pub fn run(args : Array[String]) -> Int { height = nh comp.resize(nw, nh) need_present = true + busy = true } None => () } let now_ms = @sys.monotonic_ms().to_uint() - for ev in n.take_input() { + let input = n.take_input() + for ev in input { comp.handle_input(ev, now_ms) } n.set_cursor_shape(comp.desired_cursor()) @@ -276,6 +291,7 @@ pub fn run(args : Array[String]) -> Int { @raster.submit(sg) comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0) need_present = true + busy = true } None => () } @@ -283,6 +299,8 @@ pub fn run(args : Array[String]) -> Int { n.present_frame(width, height) need_present = false } + busy = busy || input.length() > 0 || need_present + wait_fds.push(n.fd) } None => { comp.handle_gfx_events(gfx_surface) @@ -291,7 +309,8 @@ pub fn run(args : Array[String]) -> Int { let r0 = @sys.monotonic_ms() @raster.submit(sg) comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0) - need_present = true + need_present = serve && gfx_out.length() > 0 + busy = true } None => () } @@ -300,6 +319,7 @@ pub fn run(args : Array[String]) -> Int { ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(@raster.read_frame(width, height)))) need_present = false } + busy = busy || need_present } } if profile { @@ -317,9 +337,13 @@ pub fn run(args : Array[String]) -> Int { comp.prof_raster_ms = 0UL } } - // 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 }) + 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, idle.timeout())) + } } comp.save_session() // what is open now is reopened at the next start match kms { @@ -331,3 +355,31 @@ pub fn run(args : Array[String]) -> Int { } } } + +///| 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 } +} diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 392c4d8..9908aaa 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -260,7 +260,6 @@ fn release_snapshot(s : @scene.ShmBufferSnapshot?) -> Unit { } ///| What a frame was drawn from, compared with the next frame's to see whether it changed. -#derive(Eq) pub(all) struct FrameSig { bg : Array[@scene.DrawOp] panel : Array[@scene.DrawOp] @@ -268,6 +267,15 @@ pub(all) struct FrameSig { popups : Array[@scene.Rect] } +///| The background ops are usually the very same (cached) array as last frame's: that is +/// checked first, instead of comparing its ~2000 ops one by one every frame. +pub impl Eq for FrameSig with equal(a, b) { + (physical_equal(a.bg, b.bg) || a.bg == b.bg) && + a.panel == b.panel && + a.wins == b.wins && + a.popups == b.popups +} + ///| fn ChandraCompositor::apply_actions( self : ChandraCompositor, @@ -529,6 +537,16 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit { self.recording_tick() } +///| True while something runs on a timer rather than on input or client messages (a recording, +/// a pending screenshot, a toast counting down): the main loop keeps its frame pace then instead +/// of sleeping until an fd wakes it. +pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool { + self.rec is Some(_) || + self.shot_request is Some(_) || + self.rec_request is Some(_) || + self.shot_toast is Some(_) +} + ///| pub fn ChandraCompositor::set_layout_mode( self : ChandraCompositor, diff --git a/compositor/kms/kms_native.mbt b/compositor/kms/kms_native.mbt index ebfd42c..1de472e 100644 --- a/compositor/kms/kms_native.mbt +++ b/compositor/kms/kms_native.mbt @@ -43,6 +43,9 @@ extern "C" fn c_keymap_copy(out : FixedArray[Byte]) -> Int = "mp_kms_keymap_copy ///| extern "C" fn c_close() = "mp_kms_close" +///| +extern "C" fn c_fd(i : Int) -> Int = "mp_kms_fd" + ///| pub(all) struct Kms { width : Int @@ -132,3 +135,15 @@ pub fn Kms::close(_self : Kms) -> Unit { pub fn Kms::present_frame(_self : Kms) -> Unit { abort("present_frame is only available to the wasm compositor") } + +///| The seat, DRM and input fds `poll` services, for an idle loop to block on. +pub fn Kms::wait_fds(_self : Kms) -> Array[Int] { + let out : Array[Int] = [] + for i = 0; i < 3; i = i + 1 { + let fd = c_fd(i) + if fd >= 0 { + out.push(fd) + } + } + out +} diff --git a/compositor/kms/kms_stub.c b/compositor/kms/kms_stub.c index 583d5c6..23849a6 100644 --- a/compositor/kms/kms_stub.c +++ b/compositor/kms/kms_stub.c @@ -434,6 +434,19 @@ int32_t mp_kms_poll(void) { return g_seat_enabled; } +/* The fds mp_kms_poll services (0 seat, 1 DRM, 2 libinput), for an idle loop to block on; + -1 when not open. */ +MOONBIT_FFI_EXPORT +int32_t mp_kms_fd(int32_t i) { + if (!g_seat) return -1; + switch (i) { + case 0: return libseat_get_fd(g_seat); + case 1: return g_drm; + case 2: return g_li ? libinput_get_fd(g_li) : -1; + default: return -1; + } +} + /* True when a new frame may be presented (seat active, no flip in flight). */ MOONBIT_FFI_EXPORT int32_t mp_kms_frame_ready(void) { diff --git a/compositor/kms/kms_wasm.mbt b/compositor/kms/kms_wasm.mbt index f8ad23b..42b5978 100644 --- a/compositor/kms/kms_wasm.mbt +++ b/compositor/kms/kms_wasm.mbt @@ -71,3 +71,9 @@ pub fn Kms::take_input(_self : Kms) -> Array[@nested.InputEvent] { pub fn Kms::close(_self : Kms) -> Unit { @hostdisplay.close() } + +///| The fds an idle loop blocks on for the display: none here, since the host's +/// `sys.wait-readable` adds its own seat, DRM and input fds while the display is open. +pub fn Kms::wait_fds(_self : Kms) -> Array[Int] { + [] +} diff --git a/compositor/scene/scene.mbt b/compositor/scene/scene.mbt index a3a92e9..81db2f7 100644 --- a/compositor/scene/scene.mbt +++ b/compositor/scene/scene.mbt @@ -71,6 +71,7 @@ pub fn Rgba::from_hex(s : String) -> Rgba { } ///| +#derive(Eq) pub(all) struct ThemePalette { desktop_top : Rgba desktop_bottom : Rgba @@ -85,6 +86,7 @@ pub(all) struct ThemePalette { } ///| +#derive(Eq) pub(all) struct ThemeTokens { name : String palette : ThemePalette diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index dce28c4..9c274c1 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -223,6 +223,10 @@ pub(all) struct DesktopShell { mut wallpaper_len : Int /// Which wallpaper is drawn (an index into `@libshell.wallpaper_names`); the wallpaper module sets it. mut wallpaper_sel : Int + /// The background ops (wallpaper + desktop card) and what they were built from: rebuilt only + /// when that changes (about once a minute), not every frame. + mut bg_cache : Array[@scene.DrawOp] + mut bg_key : BgKey? /// Session settings (the session settings module flips them; saved in state.edn): reopen the /// last session's windows at the next start, and remember where floating windows were left. mut restore_session : Bool @@ -326,6 +330,8 @@ pub fn DesktopShell::new(display : String) -> DesktopShell { screen_w: 0, wallpaper_len: 0, wallpaper_sel: 0, + bg_cache: [], + bg_key: None, restore_session: true, screenshot_state: 2, remember_windows: true, @@ -800,6 +806,55 @@ pub fn DesktopShell::take_actions(self : DesktopShell) -> Array[ShellAction] { out } +///| What the background (wallpaper + desktop card) is drawn from. +#derive(Eq) +struct BgKey { + w : Int + h : Int + theme : @scene.ThemeTokens + wallpaper : Int + x : Int + y : Int + date : (UInt, Byte, Byte, Byte) + hour : Byte + minute : Byte +} + +///| The wallpaper and the desktop card. Building them costs most of an idle frame (the card's +/// moon disc alone is ~1800 ops), so the last ops are kept, the same array, until something they +/// are drawn from changes: the card shows minutes, so that is about once a minute. +fn DesktopShell::background( + self : DesktopShell, + w : Int, + h : Int, + theme : @scene.ThemeTokens, + tokens : @theme.Tokens, +) -> Array[@scene.DrawOp] { + let at = now() + let (dx, dy) = self.desk_pos() + let key : BgKey = { + w, + h, + theme, + wallpaper: self.wallpaper_sel, + x: dx, + y: dy, + date: (at.year, at.month, at.day, at.weekday), + hour: at.hour, + minute: at.minute, + } + if self.bg_key == Some(key) { + return self.bg_cache + } + let bg : Array[@scene.DrawOp] = [] + translate(@libshell.render_wallpaper(@ui.size(w, h), tokens, self.wallpaper_sel), 0, 0, bg) + self.wallpaper_len = bg.length() + render_desktop_widget(dx, dy, tokens, at, bg) + self.bg_cache = bg + self.bg_key = Some(key) + bg +} + ///| Build the (background, panel) render-lists for the current frame. pub fn DesktopShell::render( self : DesktopShell, @@ -823,11 +878,7 @@ pub fn DesktopShell::render( if self.widgets.iter().any(w => w.has_cap("icons")) { self.publish_icons() } - let bg : Array[@scene.DrawOp] = [] - translate(@libshell.render_wallpaper(@ui.size(w, h), tokens, self.wallpaper_sel), 0, 0, bg) - self.wallpaper_len = bg.length() - let (dx, dy) = self.desk_pos() - render_desktop_widget(dx, dy, tokens, now(), bg) + let bg = self.background(w, h, theme, tokens) let panel_ops : Array[@scene.DrawOp] = [] self.comps.clear() diff --git a/compositor/sys/sys_native.mbt b/compositor/sys/sys_native.mbt index e2ddcb3..f44f7cf 100644 --- a/compositor/sys/sys_native.mbt +++ b/compositor/sys/sys_native.mbt @@ -133,6 +133,16 @@ pub fn poll_read(fd : Int, timeout_ms : Int) -> Int { c_poll_read(fd, timeout_ms) } +///| +#borrow(fds) +extern "C" fn c_wait_readable(fds : FixedArray[Int], n : Int, timeout_ms : Int) -> Int = "mp_wait_readable" + +///| Block until one of `fds` is readable or `timeout_ms` passes (how an idle loop sleeps). The +/// number of ready fds, 0 on timeout. +pub fn wait_readable(fds : Array[Int], timeout_ms : Int) -> Int { + c_wait_readable(FixedArray::from_array(fds), fds.length(), timeout_ms) +} + ///| Receive bytes and every SCM_RIGHTS fd that came with them, in order. Returns /// (bytes_read, fds); bytes_read == -1 means EAGAIN, -2 an error, 0 EOF. pub fn recvmsg_fds(fd : Int, buf : FixedArray[Byte], max_len : Int) -> (Int, Array[Int]) { diff --git a/compositor/sys/sys_stub.c b/compositor/sys/sys_stub.c index 5ed5c89..b2340d5 100644 --- a/compositor/sys/sys_stub.c +++ b/compositor/sys/sys_stub.c @@ -119,6 +119,21 @@ int32_t mp_poll_read(int32_t fd, int32_t timeout_ms) { return (pfd.revents & (POLLIN | POLLHUP | POLLERR)) ? 1 : 0; } +/* Block until one of fds[0..n) is readable or timeout_ms passes; poll(2)'s result. */ +MOONBIT_FFI_EXPORT +int32_t mp_wait_readable(int32_t *fds, int32_t n, int32_t timeout_ms) { + struct pollfd pfd[64]; + int k = 0; + for (int i = 0; i < n && k < 64; i++) { + if (fds[i] < 0) continue; + pfd[k].fd = fds[i]; + pfd[k].events = POLLIN; + pfd[k].revents = 0; + k++; + } + return poll(pfd, (nfds_t)k, timeout_ms); +} + 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] = number of fds received, out_fd[1..] the fds. A client flushes up to 28 fds diff --git a/compositor/sys/sys_wasm.mbt b/compositor/sys/sys_wasm.mbt index 550eb37..4d9b1ff 100644 --- a/compositor/sys/sys_wasm.mbt +++ b/compositor/sys/sys_wasm.mbt @@ -70,6 +70,13 @@ pub fn poll_read(fd : Int, timeout_ms : Int) -> Int { @hostsys.poll_read(fd, timeout_ms) } +///| Block until one of `fds` is readable or `timeout_ms` passes (how an idle loop sleeps). The +/// host also wakes on its login-session display's seat, DRM and input fds while that is open. +/// The number of ready fds, 0 on timeout. +pub fn wait_readable(fds : Array[Int], timeout_ms : Int) -> Int { + @hostsys.wait_readable(FixedArray::from_array(fds), timeout_ms) +} + ///| Receive bytes and an optional SCM_RIGHTS fd into `buf`. Returns (bytes_read, received_fd); /// bytes_read == -1 means EAGAIN, -2 an error, 0 EOF. pub fn recvmsg_fd(fd : Int, buf : FixedArray[Byte], max_len : Int) -> (Int, Int) { diff --git a/compositor/wasm/wasm_host.mbt b/compositor/wasm/wasm_host.mbt index 7da6e97..0e9e55e 100644 --- a/compositor/wasm/wasm_host.mbt +++ b/compositor/wasm/wasm_host.mbt @@ -282,9 +282,22 @@ pub fn publish(which : HostTable, t : Table) -> Unit { SessionSettings => 6U Icons => 7U } + // Most tables are republished every frame unchanged: skip the copy into the host then. + let slot = id.reinterpret_as_int() + while published.length() <= slot { + published.push(None) + } + match published[slot] { + Some(prev) => if prev == out { return } + None => () + } + published[slot] = Some(out) @hostpl.publish_table(id, out) } +///| The bytes last sent for each table, by table id. +let published : Array[FixedArray[Byte]?] = [] + ///| pub fn publish_state(layout_mode : Int, inspector_on : Bool) -> Unit { @hostpl.publish_state(layout_mode, inspector_on) diff --git a/compositor/wayland/server.mbt b/compositor/wayland/server.mbt index 3657cde..8bbc030 100644 --- a/compositor/wayland/server.mbt +++ b/compositor/wayland/server.mbt @@ -1135,6 +1135,17 @@ fn WaylandServer::dispatch_msg( } } +///| The listening socket and every connected client: what an idle compositor waits on. +pub fn WaylandServer::wait_fds(self : WaylandServer) -> Array[Int] { + let out = [self.listen_fd] + for c in self.clients { + if c.alive { + out.push(c.fd) + } + } + out +} + ///| Accept new clients, read incoming Wayland messages + SCM_RIGHTS fds, and emit CompositorEvents. pub fn WaylandServer::poll_events( self : WaylandServer, diff --git a/host-wasm/src/kms.rs b/host-wasm/src/kms.rs index e73e274..ba45bef 100644 --- a/host-wasm/src/kms.rs +++ b/host-wasm/src/kms.rs @@ -15,6 +15,7 @@ extern "C" { fn mp_kms_arg(i: i32) -> i32; fn mp_kms_keymap_len() -> i32; fn mp_kms_close(); + fn mp_kms_fd(i: i32) -> i32; fn hw_kms_present(pixels: *mut u8, w: i32, h: i32) -> i32; fn hw_kms_keymap_copy(out: *mut u8, cap: i32) -> i32; } @@ -43,6 +44,11 @@ pub fn poll() -> bool { } } +/// The seat, DRM and input fds while the display is open (empty otherwise), for an idle wait. +pub fn fds() -> Vec { + (0..3).map(|i| unsafe { mp_kms_fd(i) }).filter(|&fd| fd >= 0).collect() +} + pub fn frame_ready() -> bool { unsafe { mp_kms_frame_ready() != 0 } } diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index 2a6d185..444277c 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -378,7 +378,7 @@ impl chandra::host::raster::Host for State { } fn submit(&mut self, f: chandra::host::raster::Frame) { - self.raster.submit(&f, &mut self.fonts); + self.raster.submit_frame(f, &mut self.fonts); } fn read_frame(&mut self) -> Vec { @@ -481,6 +481,16 @@ impl Host for State { } } + fn wait_readable(&mut self, fds: Vec, timeout_ms: i32) -> i32 { + let mut pfds: Vec = fds + .into_iter() + .chain(kms::fds()) + .filter(|&fd| fd >= 0) + .map(|fd| libc::pollfd { fd, events: libc::POLLIN, revents: 0 }) + .collect(); + unsafe { libc::poll(pfds.as_mut_ptr(), pfds.len() as libc::nfds_t, timeout_ms) } + } + fn recvmsg(&mut self, fd: i32, max_len: u32) -> Received { // Fds from the previous read nobody took would leak: close them. if let Some(left) = self.extra_fds.remove(&fd) { diff --git a/host-wasm/src/raster.rs b/host-wasm/src/raster.rs index c6a1960..a109ffc 100644 --- a/host-wasm/src/raster.rs +++ b/host-wasm/src/raster.rs @@ -593,10 +593,27 @@ fn draw_image(c: &mut Canvas, imgs: &Images, p: &wt::Picture, ox: i32, oy: i32, } /// Draw `ops` offset by (ox, oy), with the clip stack they push and pop. -fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, imgs: &Images, ops: &[wt::Op], ox: i32, oy: i32) { +/// The overlap of two clips (None: no clip). +fn intersect(a: Clip, b: Clip) -> Clip { + match (a, b) { + (None, k) | (k, None) => k, + (Some(a), Some(b)) => { + let (x0, y0) = (a.x.max(b.x), a.y.max(b.y)); + let (x1, y1) = ((a.x + a.w).min(b.x + b.w), (a.y + a.h).min(b.y + b.h)); + Some(R { x: x0, y: y0, w: (x1 - x0).max(0), h: (y1 - y0).max(0) }) + } + } +} + +/// Draw `ops` offset by (ox, oy). `base` limits everything (the frame's damaged area); a push-clip +/// op replaces the clip within it. +fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, imgs: &Images, ops: &[wt::Op], ox: i32, oy: i32, base: Clip) { let mut stack: Vec = Vec::new(); for op in ops { - let clip = stack.last().copied(); + let clip = match stack.last() { + Some(k) => intersect(Some(*k), base), + None => base, + }; match op { wt::Op::FillRect(f) => { let r = R { x: f.area.x + ox, y: f.area.y + oy, w: f.area.w, h: f.area.h }; @@ -654,26 +671,30 @@ impl Surface { /// Draw a client surface into `dst`. While the client catches up with a resize its buffer is smaller /// than the window: the buffer's bottom-right colour is extended over the rest. -fn blit_surface(c: &mut Canvas, s: &Surface, dst: R) { +fn blit_surface(c: &mut Canvas, s: &Surface, dst: R, clip: Clip) { if s.w <= 0 || s.h <= 0 || dst.w <= 0 || dst.h <= 0 { return; } if s.w < dst.w || s.h < dst.h { let o = ((s.h - 1) * s.w + (s.w - 1)) as usize * 4; let col = wt::Color { r: s.rgba[o], g: s.rgba[o + 1], b: s.rgba[o + 2], a: s.rgba[o + 3] }; - fill_rounded_rect(c, dst, col, 0, None); + fill_rounded_rect(c, dst, col, 0, clip); } let (copy_w, copy_h) = (s.w.min(dst.w), s.h.min(dst.h)); - let c0 = (-dst.x).max(0); - let c1 = copy_w.min(c.w - dst.x); - if c0 >= c1 { + // Visible columns [c0, c1) and rows [r0, r1) of the buffer: on the canvas and inside the clip. + let (mut c0, mut c1) = ((-dst.x).max(0), copy_w.min(c.w - dst.x)); + let (mut r0, mut r1) = ((-dst.y).max(0), copy_h.min(c.h - dst.y)); + if let Some(k) = clip { + c0 = c0.max(k.x - dst.x); + c1 = c1.min(k.x + k.w - dst.x); + r0 = r0.max(k.y - dst.y); + r1 = r1.min(k.y + k.h - dst.y); + } + if c0 >= c1 || r0 >= r1 { return; } - for row in 0..copy_h { + for row in r0..r1 { let dy = dst.y + row; - if dy < 0 || dy >= c.h { - continue; - } let src = &s.rgba[((row * s.w + c0) * 4) as usize..((row * s.w + c1) * 4) as usize]; let d0 = ((dy * c.w + dst.x + c0) * 4) as usize; let dst_row = &mut c.data[d0..d0 + src.len()]; @@ -711,6 +732,70 @@ pub struct Raster { next_id: u32, /// Images for `draw-image` ops (app icons). pub images: Images, + /// The last frame drawn, to work out what the next one changes. + prev: Option, + /// Pixels redrawn by the last submit (for tests and profiling). + pub last_drawn: usize, +} + +/// Room around a window for its drop shadow (4 px right, 6 px down) and a little slack. +const SHADOW_PAD: i32 = 8; + +/// What a window covers on screen: its decoration and drop shadow, or just itself when fullscreen. +fn window_footprint(win: &wt::Window) -> R { + let g = R::from(win.geometry); + if win.fullscreen { + return g; + } + R { + x: g.x - win.inset_left - SHADOW_PAD, + y: g.y - win.inset_top - SHADOW_PAD, + w: g.w + win.inset_left + win.inset_right + 2 * SHADOW_PAD, + h: g.h + win.inset_top + win.inset_bottom + 2 * SHADOW_PAD, + } +} + +/// The bounding box of two rectangles (an empty one counts for nothing). +fn union(a: R, b: R) -> R { + if a.w <= 0 || a.h <= 0 { + return b; + } + if b.w <= 0 || b.h <= 0 { + return a; + } + let (x0, y0) = (a.x.min(b.x), a.y.min(b.y)); + let (x1, y1) = ((a.x + a.w).max(b.x + b.w), (a.y + a.h).max(b.y + b.h)); + R { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } +} + +/// The part of the screen `f` changes over `prev`, as one rectangle; None when all of it must be +/// redrawn. Only window changes are narrowed down (a client drawing, a window moving, focus moving): +/// any change to the wallpaper, desktop card, panel or the set of windows redraws everything. +fn damage(prev: &wt::Frame, f: &wt::Frame) -> Option { + if prev.width != f.width || prev.height != f.height || prev.windows.len() != f.windows.len() { + return None; + } + if f.background != prev.background || f.panel != prev.panel { + return None; + } + if let Some(ops) = &f.wallpaper { + if prev.wallpaper.as_ref() != Some(ops) { + return None; + } + } + let mut d = R { x: 0, y: 0, w: 0, h: 0 }; + for (a, b) in prev.windows.iter().zip(f.windows.iter()) { + if a == b { + continue; + } + d = union(d, union(window_footprint(a), window_footprint(b))); + } + if prev.popups != f.popups { + for p in prev.popups.iter().chain(f.popups.iter()) { + d = union(d, R::from(p.area)); + } + } + Some(d) } impl Raster { @@ -739,9 +824,17 @@ impl Raster { self.surfaces.len() } + /// `submit_frame` for a borrowed frame (tests). + #[cfg(test)] + pub fn submit(&mut self, f: &wt::Frame, fonts: &mut Fonts) { + self.submit_frame(f.clone(), fonts) + } + /// Draw a frame into the framebuffer: wallpaper (cached), background, windows bottom to top, /// panel, then client popups. The same layering as the software renderer's `render_scene`. - pub fn submit(&mut self, f: &wt::Frame, fonts: &mut Fonts) { + /// Only the part that differs from the last frame is redrawn (see `damage`): a client drawing + /// in its window costs that window's pixels, not the whole screen. + pub fn submit_frame(&mut self, f: wt::Frame, fonts: &mut Fonts) { let (w, h) = (f.width.max(1), f.height.max(1)); let resized = w != self.w || h != self.h || self.fb.len() != (w * h * 4) as usize; if resized { @@ -756,37 +849,71 @@ impl Raster { (Some(ops), Some((o, cw, ch, _))) => *cw == w && *ch == h && o == ops, _ => false, }; + let clip: Clip = match (&self.prev, resized || !backdrop_ready) { + (Some(prev), false) => match damage(prev, &f) { + Some(d) => match intersect(Some(d), Some(R { x: 0, y: 0, w, h })) { + Some(k) if k.w > 0 && k.h > 0 => Some(k), + _ => { + // Nothing on screen changed (a window off screen, say). + self.last_drawn = 0; + self.keep_prev(f); + return; + } + }, + None => None, + }, + _ => None, + }; if !resized && !backdrop_ready { self.fb.fill(0); } + self.last_drawn = match clip { + Some(k) => (k.w * k.h) as usize, + None => (w * h) as usize, + }; let surfaces = &self.surfaces; let imgs = &self.images; let mut c = Canvas { w, h, data: &mut self.fb }; - // 1. Wallpaper: drawn once, copied back while unchanged. + // 1. Wallpaper: drawn once, copied back while unchanged (only the damaged rows and columns). + let copy_backdrop = |c: &mut Canvas, px: &[u8]| match clip { + None => c.data.copy_from_slice(px), + Some(k) => { + for y in k.y..k.y + k.h { + let a = ((y * w + k.x) * 4) as usize; + let b = a + (k.w * 4) as usize; + c.data[a..b].copy_from_slice(&px[a..b]); + } + } + }; match &f.wallpaper { Some(ops) => { let cached = matches!(&self.wallpaper, Some((o, cw, ch, _)) if *cw == w && *ch == h && o == ops); if cached { - c.data.copy_from_slice(&self.wallpaper.as_ref().unwrap().3); + copy_backdrop(&mut c, &self.wallpaper.as_ref().unwrap().3); } else { - draw_ops(&mut c, fonts, imgs, ops, 0, 0); + draw_ops(&mut c, fonts, imgs, ops, 0, 0, None); self.wallpaper = Some((ops.clone(), w, h, c.data.to_vec())); } } None => { if let Some((_, cw, ch, px)) = &self.wallpaper { if *cw == w && *ch == h { - c.data.copy_from_slice(px); + copy_backdrop(&mut c, px); } } } } - draw_ops(&mut c, fonts, imgs, &f.background, 0, 0); + draw_ops(&mut c, fonts, imgs, &f.background, 0, 0, clip); // 2. Windows, bottom to top. for win in &f.windows { let g = R::from(win.geometry); + if let Some(k) = clip { + if intersect(Some(window_footprint(win)), Some(k)).map_or(true, |r| r.w <= 0 || r.h <= 0) { + continue; + } + } if !win.fullscreen { let (outer_x, outer_y) = (g.x - win.inset_left, g.y - win.inset_top); let outer_w = g.w + win.inset_left + win.inset_right; @@ -801,23 +928,37 @@ impl Raster { R { x: outer_x, y: outer_y, w: outer_w, h: win.inset_top + 2 }, ]; for s in strips { - fill_rounded_rect(&mut c, shadow, col, 8, Some(s)); + if let Some(k) = intersect(Some(s), clip) { + if k.w > 0 && k.h > 0 { + fill_rounded_rect(&mut c, shadow, col, 8, Some(k)); + } + } } - draw_ops(&mut c, fonts, imgs, &win.deco, outer_x, outer_y); + draw_ops(&mut c, fonts, imgs, &win.deco, outer_x, outer_y, clip); } match surfaces.get(&win.surface) { - Some(s) => blit_surface(&mut c, s, g), - None => fill_rounded_rect(&mut c, g, wt::Color { r: 0x1e, g: 0x29, b: 0x3b, a: 0xff }, 0, None), + Some(s) => blit_surface(&mut c, s, g, clip), + None => fill_rounded_rect(&mut c, g, wt::Color { r: 0x1e, g: 0x29, b: 0x3b, a: 0xff }, 0, clip), } } // 3. Panel (and its popups, menus and notices), then 4. client popups above everything. - draw_ops(&mut c, fonts, imgs, &f.panel, 0, 0); + draw_ops(&mut c, fonts, imgs, &f.panel, 0, 0, clip); for p in &f.popups { if let Some(s) = surfaces.get(&p.surface) { - blit_surface(&mut c, s, R::from(p.area)); + blit_surface(&mut c, s, R::from(p.area), clip); } } + self.keep_prev(f); + } + + /// Remember `f` as the last frame. Its wallpaper ops are kept from the frame that sent them, so + /// a later frame that resends the same wallpaper still compares equal. + fn keep_prev(&mut self, mut f: wt::Frame) { + if f.wallpaper.is_none() { + f.wallpaper = self.prev.as_mut().and_then(|p| p.wallpaper.take()); + } + self.prev = Some(f); } /// The framebuffer as little-endian ARGB8888 (B, G, R, A=255), `stride = w * 4`. @@ -955,6 +1096,74 @@ mod tests { assert_eq!(r.surface_count(), 0); } + /// A window with a title-bar decoration over a patterned backdrop and a panel. + fn scene_window(r: &mut Raster, x: i32, y: i32, shade: u8, focused: bool) -> wt::Window { + let bgra: Vec = (0..(30 * 20)).flat_map(|i| [shade, (i % 251) as u8, 40, if i % 7 == 0 { 90 } else { 255 }]).collect(); + let id = r.add_surface(Surface::from_bgra(&bgra, 30 * 4, 30, 20, false).unwrap()); + wt::Window { + geometry: rect(x, y, 30, 20), + inset_top: 8, + inset_right: 2, + inset_bottom: 2, + inset_left: 2, + deco: vec![fill(0, 0, 34, 30, if focused { color(60, 90, 200, 230) } else { color(90, 90, 90, 200) }, 3)], + fullscreen: false, + surface: id, + } + } + + fn scene_frame(windows: Vec) -> wt::Frame { + let mut f = frame(120, 90); + f.wallpaper = Some((0..12).map(|i| fill(i * 10, 0, 10, 90, color((i * 20) as u8, 100, 200 - (i * 10) as u8, 255), 0)).collect()); + f.windows = windows; + f.panel = vec![fill(0, 80, 120, 10, color(20, 20, 30, 220), 0), fill(4, 82, 6, 6, color(250, 250, 250, 255), 3)]; + f + } + + #[test] + fn redrawing_only_the_damage_gives_the_same_pixels_as_a_full_redraw() { + let mut fonts = Fonts::default(); + // Frame 1 (full), then steps that only change windows: a client redraw, a move, a focus change. + let mut inc = Raster::default(); + let w1 = scene_window(&mut inc, 10, 15, 10, false); + let w2 = scene_window(&mut inc, 30, 25, 200, true); + inc.submit(&scene_frame(vec![w1.clone(), w2.clone()]), &mut fonts); + assert_eq!(inc.last_drawn, 120 * 90); + let mut new_w1 = scene_window(&mut inc, 10, 15, 99, false); // the client drew a new buffer + let steps = vec![ + vec![new_w1.clone(), w2.clone()], + { + new_w1.geometry = rect(60, 40, 30, 20); // moved, now overlapping the panel + vec![new_w1.clone(), w2.clone()] + }, + { + let mut a = new_w1.clone(); + a.deco = vec![fill(0, 0, 34, 30, color(60, 90, 200, 230), 3)]; + let mut b = w2.clone(); + b.deco = vec![fill(0, 0, 34, 30, color(90, 90, 90, 200), 3)]; + vec![b, a] // focus moved and the stacking order swapped + }, + ]; + for (i, wins) in steps.into_iter().enumerate() { + let f = scene_frame(wins); + let mut f_inc = f.clone(); + f_inc.wallpaper = None; // the compositor sends an unchanged backdrop as None + inc.submit(&f_inc, &mut fonts); + assert!(inc.last_drawn < 120 * 90, "step {i}: only part of the screen is redrawn"); + // The same frame drawn from scratch, with the same surfaces. + let mut full = Raster::default(); + for (id, s) in &inc.surfaces { + full.surfaces.insert(*id, Surface { w: s.w, h: s.h, rgba: s.rgba.clone(), opaque: s.opaque }); + } + full.submit(&f, &mut fonts); + assert!(full.fb == inc.fb, "step {i}: partial redraw differs from a full one"); + } + // An unchanged frame draws nothing. + let f = inc.prev.clone().unwrap(); + inc.submit(&f, &mut fonts); + assert_eq!(inc.last_drawn, 0); + } + #[test] fn translucent_surfaces_blend_over_what_is_behind() { let mut r = Raster::default(); diff --git a/interface/chandra/host/sys/ffi.mbt b/interface/chandra/host/sys/ffi.mbt index a560945..6c44b88 100644 --- a/interface/chandra/host/sys/ffi.mbt +++ b/interface/chandra/host/sys/ffi.mbt @@ -19,11 +19,14 @@ fn wasmImportUnlink(p0 : Int, p1 : Int) = "chandra:host/sys@0.1.0" "unlink" fn wasmImportPollRead(p0 : Int, p1 : Int) -> Int = "chandra:host/sys@0.1.0" "poll-read" ///| -fn wasmImportTakeFd(p0 : Int) -> Int = "chandra:host/sys@0.1.0" "take-fd" +fn wasmImportWaitReadable(p0 : Int, p1 : Int, p2 : Int) -> Int = "chandra:host/sys@0.1.0" "wait-readable" ///| fn wasmImportRecvmsg(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/sys@0.1.0" "recvmsg" +///| +fn wasmImportTakeFd(p0 : Int) -> Int = "chandra:host/sys@0.1.0" "take-fd" + ///| fn wasmImportSendmsg(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "sendmsg" @@ -78,6 +81,17 @@ fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int = "chandra:host/sys@0.1.0" "has-e ///| fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "spawn" +///| +extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array8 +#| local.get 0) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + ///| #owned(str) extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = @@ -94,13 +108,6 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #| local.tee 1 i32.const 0 call $moonbit.init_array8 #| local.get 1) -///| -extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = -#|(func (param i32) (param i32) (result i32) -#| local.get 0 -#| local.get 1 call $moonbit.init_array8 -#| local.get 0) - ///| extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #|(func (param i32) (param i32) (result i32) @@ -108,12 +115,13 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #| local.get 1 call $moonbit.init_array16 #| local.get 0) -///| -extern "wasm" fn mbt_ffi_free(position : Int) = -#|(func (param i32) local.get 0 call $moonbit.decref) - ///| #owned(bytes) extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = #|(func (param i32) (result i32) local.get 0) +///| +#owned(array) +extern "wasm" fn mbt_ffi_int_array2ptr(array : FixedArray[Int]) -> Int = +#|(func (param i32) (result i32) local.get 0) + diff --git a/interface/chandra/host/sys/native_stub.mbt b/interface/chandra/host/sys/native_stub.mbt index fc8c044..55bc1dc 100644 --- a/interface/chandra/host/sys/native_stub.mbt +++ b/interface/chandra/host/sys/native_stub.mbt @@ -25,21 +25,26 @@ fn wasmImportUnlink(p0 : Int, p1 : Int) -> Unit { abort("wasm-only host import") } -///| -fn wasmImportTakeFd(p0 : Int) -> Int { - abort("wasm-only host import") -} - ///| fn wasmImportPollRead(p0 : Int, p1 : Int) -> Int { abort("wasm-only host import") } +///| +fn wasmImportWaitReadable(p0 : Int, p1 : Int, p2 : Int) -> Int { + abort("wasm-only host import") +} + ///| fn wasmImportRecvmsg(p0 : Int, p1 : Int, p2 : Int) -> Unit { abort("wasm-only host import") } +///| +fn wasmImportTakeFd(p0 : Int) -> Int { + abort("wasm-only host import") +} + ///| fn wasmImportSendmsg(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { abort("wasm-only host import") @@ -130,6 +135,16 @@ fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { abort("wasm-only host import") } +///| +fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { + abort("wasm-only") +} + +///| +fn mbt_ffi_free(position : Int) -> Unit { + abort("wasm-only") +} + ///| fn mbt_ffi_str2ptr(str : String) -> Int { abort("wasm-only") @@ -145,22 +160,17 @@ fn mbt_ffi_malloc(size : Int) -> Int { abort("wasm-only") } -///| -fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { - abort("wasm-only") -} - ///| fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { abort("wasm-only") } -///| -fn mbt_ffi_free(position : Int) -> Unit { - abort("wasm-only") -} - ///| fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { abort("wasm-only") } + +///| +fn mbt_ffi_int_array2ptr(array : FixedArray[Int]) -> Int { + abort("wasm-only") +} diff --git a/interface/chandra/host/sys/top.mbt b/interface/chandra/host/sys/top.mbt index 4f9bf5a..fad9065 100644 --- a/interface/chandra/host/sys/top.mbt +++ b/interface/chandra/host/sys/top.mbt @@ -57,6 +57,20 @@ pub fn poll_read(fd : Int, timeout_ms : Int) -> Int { let ret = result return ret +} +///| +/// Block until one of `fds` is readable or `timeout-ms` passes: how an idle compositor sleeps. +/// While the login-session display is open (display.open) its own seat, DRM and input fds are +/// waited on too. The number of ready fds, 0 on timeout, <0 on error. +pub fn wait_readable(fds : FixedArray[Int], timeout_ms : Int) -> Int { + + let ptr = mbt_ffi_int_array2ptr(fds) + + let result : Int = wasmImportWaitReadable(ptr, fds.length(), timeout_ms); + let ret = result + mbt_ffi_free(ptr) + return ret + } ///| pub fn recvmsg(fd : Int, max_len : UInt) -> Received { diff --git a/wit/host/sys.wit b/wit/host/sys.wit index 86fbbba..a81567c 100644 --- a/wit/host/sys.wit +++ b/wit/host/sys.wit @@ -13,6 +13,10 @@ interface sys { unlink: func(path: string); /// 1 when `fd` is readable within `timeout-ms`, 0 on timeout, <0 on error. poll-read: func(fd: s32, timeout-ms: s32) -> s32; + /// Block until one of `fds` is readable or `timeout-ms` passes: how an idle compositor sleeps. + /// While the login-session display is open (display.open) its own seat, DRM and input fds are + /// waited on too. The number of ready fds, 0 on timeout, <0 on error. + wait-readable: func(fds: list, timeout-ms: s32) -> s32; /// Result of `recvmsg`: byte count (-1 would-block, -2 error, 0 EOF), an fd received over /// SCM_RIGHTS (-1 when none), and the bytes read.