CPU, round two: cheaper client captures, content-only redraws, damage-limited KMS and nested output
CI / test (push) Failing after 19s

Measured on the MoonBit host, 1080p, cloud container (two runs each, before -> after):
- full-screen (tiled) client redrawing at 60 fps: 43/39% -> 31/35%
- 800x600 floating client at 60 fps: 15.5/13.2% -> 10.4/11.9%
- client inside the nested window: nested 18% -> 12%, outer 17% -> 11.6%
- Alt+Tab open over two animating clients: 36.6% -> 25.4%
- idle (headless / nested): 0.2-0.6% -> 0.1-0.3%

wasmhost raster:
- capture keeps client pools mapped (keyed by dev/inode/size, dropped after 1 s unused) and
  reuses released surface buffers, swizzling a word at a time: 3.2 -> 2.1 ms per 1080p commit.
- a window whose only change is a new buffer damages just its client area, and the topmost
  opaque buffer that covers the damage is drawn first (no backdrop copy, desktop card, lower
  windows or its own decoration under it): submit 3.2 -> 0.8 ms per full-screen frame.
- the framebuffer tracks what changed since each output took it. The nested window's frames
  are a ring of three mapped memfds, each updated only where the screen changed, instead of
  a new memfd with a full 8 MB conversion and write every frame.
- KMS: present copies only the rows the back buffer is missing (this frame's change and the
  last one's), and kms_stub.c is compiled with -O2 (its stub-cc-flags dropped moon's default,
  so the per-frame copy ran unoptimised).
- images re-filled under the same handle (Alt+Tab previews) damage where the panel draws them:
  before, a live preview only repainted where it overlapped the window that redrew.

compositor:
- Alt+Tab previews of a window that keeps redrawing are remade at most every 100 ms (scaling a
  1080p buffer takes ~2 ms); the loop keeps its pace while one is pending.
- set-tokens is sent to the host only when the theme changes (it was 9 calls a frame).
- /proc is sampled only when a module imports `system`; a machine without a battery looks for
  one every 30 s instead of probing eight sysfs paths every second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkh3qygSXtftCTVhSZ
This commit is contained in:
Claude committed 2026-11-25 21:16:41 +00:00
1 parent 99c6c66726
commit 442f9477b4
11 files changed
+455 -61

No files matched your search

+1
View File
@@ -598,6 +598,7 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
self.shot_request is Some(_) ||
self.rec_request is Some(_) ||
self.shot_toast is Some(_) ||
self.thumbs_pending() ||
self.shell.animating()
}
+20 -2
View File
@@ -148,6 +148,18 @@ pub(all) struct SwitcherThumb {
mut w : Int
mut h : Int
mut stale : Bool
/// When it was last made (monotonic ms).
mut made_ms : UInt64
}
///| How often a preview of a window that keeps redrawing (a video) is made again: scaling a
/// full-screen buffer down takes a couple of ms, too much for every frame of every window.
const THUMB_REFRESH_MS : UInt64 = 100UL
///| True while the switcher is up and a preview waits for its next refresh (the main loop
/// keeps its frame pace for it).
fn ChandraCompositor::thumbs_pending(self : ChandraCompositor) -> Bool {
self.switcher_on && self.thumbs.values().any(t => t.stale)
}
///| The window committed a new buffer: its preview is made again the next time it is shown.
@@ -204,8 +216,10 @@ fn ChandraCompositor::switcher_thumb(self : ChandraCompositor, id : UInt64, box_
}
Some(buf) => {
let (tw, th) = thumb_fit(buf.width, buf.height, box_w, box_h)
let now = @sys.monotonic_ms()
match old {
Some(t) if !t.stale && t.w == tw && t.h == th => return (t.handle, tw, th)
Some(t) if t.w == tw && t.h == th && t.handle != 0U &&
(!t.stale || now - t.made_ms < THUMB_REFRESH_MS) => return (t.handle, tw, th)
_ => ()
}
let reuse = match old {
@@ -240,8 +254,12 @@ fn ChandraCompositor::switcher_thumb(self : ChandraCompositor, id : UInt64, box_
t.w = tw
t.h = th
t.stale = false
t.made_ms = now
// New pixels under the same handle: the frame must be drawn even when nothing else
// changed (the host finds where the preview is).
self.damage.mark_rect(@scene.Rect::new(0, 0, tw, th))
}
None => self.thumbs.set(id, { handle: h, w: tw, h: th, stale: false })
None => self.thumbs.set(id, { handle: h, w: tw, h: th, stale: false, made_ms: now })
}
(h, tw, th)
}
+5
View File
@@ -76,8 +76,13 @@ test "alt-tab shows a preview of each window's last frame, made only when needed
comp.step()
}
assert_true(comp.thumbs.get(1UL).unwrap().stale)
// It is remade at most every 100 ms (a video would otherwise cost a scale every frame); until
// then the main loop keeps its frame pace for it.
assert_true(comp.has_timed_work())
@sys.sleep_ms(110)
ignore(comp.compose_scene())
assert_false(comp.thumbs.get(1UL).unwrap().stale)
assert_false(comp.has_timed_work())
assert_eq(comp.thumbs.get(1UL).unwrap().handle, h1)
key(1U, true, 3U)
key(56U, false, 4U)
+53 -14
View File
@@ -32,6 +32,23 @@
#define KEY_F11_CODE 87
#define KEY_F12_CODE 88
/* ---- damage ---- */
/* What each scanout buffer is missing of the frame: the part changed since it was last written
* (x0, y0, x1, y1; empty when x0 >= x1). Both start (and after a seat switch, are) fully stale. */
static int g_stale[2][4];
static void stale_add(int x0, int y0, int x1, int y1) {
for (int i = 0; i < 2; i++) {
int *s = g_stale[i];
if (s[0] >= s[2] || s[1] >= s[3]) { s[0] = x0; s[1] = y0; s[2] = x1; s[3] = y1; continue; }
if (x0 < s[0]) s[0] = x0;
if (y0 < s[1]) s[1] = y0;
if (x1 > s[2]) s[2] = x1;
if (y1 > s[3]) s[3] = y1;
}
}
/* ---- seat ---------------------------------------------------------------- */
static struct libseat *g_seat;
@@ -42,6 +59,7 @@ static int g_suspended; /* VT switched away; resume when the seat is enabled aga
static void seat_enable(struct libseat *s, void *u) {
(void)s; (void)u;
g_seat_enabled = 1;
stale_add(0, 0, 1 << 16, 1 << 16); /* another session may have drawn in the buffers */
}
static void seat_disable(struct libseat *s, void *u) {
@@ -401,6 +419,7 @@ int32_t mp_kms_open(void) {
return -4;
}
g_front = 0;
stale_add(0, 0, 1 << 16, 1 << 16);
do_modeset();
/* Hardware cursor (optional: fall back to no cursor if unsupported). */
@@ -487,25 +506,40 @@ int32_t mp_kms_frame_ready(void) {
return g_seat_enabled && !g_flip_pending && !g_blank;
}
/* RGBA8888 rows -> the scanout buffer's XRGB8888 (B, G, R, X), one pixel as one 32-bit word. */
static void copy_rows(struct fbuf *b, const uint8_t *src, int w, int x0, int y0, int x1, int y1) {
for (int y = y0; y < y1; y++) {
uint32_t *d = (uint32_t *)(b->map + (size_t)y * b->pitch);
const uint32_t *s = (const uint32_t *)(src + (size_t)y * (size_t)w * 4);
for (int x = x0; x < x1; x++) {
uint32_t v = s[x];
d[x] = 0xff000000u | (v & 0x0000ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16);
}
}
}
/* Present an RGBA8888 frame of w x h (must match the mode). */
MOONBIT_FFI_EXPORT
int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h) {
int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h);
/* Show an RGBA8888 frame of which only (dx, dy, dw, dh) changed since the last call: only what the
* back buffer is missing is copied into it (the change now, and the one shown last time). */
MOONBIT_FFI_EXPORT
int32_t mp_kms_present_damage(moonbit_bytes_t pixels, int32_t w, int32_t h, int32_t dx, int32_t dy, int32_t dw,
int32_t dh) {
int cw = w < g_width ? w : g_width;
int ch = h < g_height ? h : g_height;
int x0 = dx < 0 ? 0 : dx, y0 = dy < 0 ? 0 : dy;
int x1 = dx + dw > cw ? cw : dx + dw, y1 = dy + dh > ch ? ch : dy + dh;
if (x0 < x1 && y0 < y1) stale_add(x0, y0, x1, y1);
if (!g_seat_enabled || g_flip_pending || g_blank) return 0;
int back = 1 - g_front;
struct fbuf *b = &g_fb[back];
int cw = w < g_width ? w : g_width;
int ch = h < g_height ? h : g_height;
const uint8_t *src = (const uint8_t *)pixels;
for (int y = 0; y < ch; y++) {
uint8_t *dst = b->map + (size_t)y * b->pitch;
const uint8_t *s = src + (size_t)y * (size_t)w * 4;
for (int x = 0; x < cw; x++) {
dst[x * 4 + 0] = s[x * 4 + 2]; /* B */
dst[x * 4 + 1] = s[x * 4 + 1]; /* G */
dst[x * 4 + 2] = s[x * 4 + 0]; /* R */
dst[x * 4 + 3] = 0xff;
}
}
int *s = g_stale[back];
int sx0 = s[0] < 0 ? 0 : s[0], sy0 = s[1] < 0 ? 0 : s[1];
int sx1 = s[2] > cw ? cw : s[2], sy1 = s[3] > ch ? ch : s[3];
if (sx0 < sx1 && sy0 < sy1) copy_rows(b, (const uint8_t *)pixels, w, sx0, sy0, sx1, sy1);
s[0] = s[1] = s[2] = s[3] = 0;
if (drmModePageFlip(g_drm, g_crtc, b->fb, DRM_MODE_PAGE_FLIP_EVENT, NULL) < 0) {
/* Fall back to a synchronous set. */
if (drmModeSetCrtc(g_drm, g_crtc, b->fb, 0, 0, &g_conn, 1, &g_mode) < 0) return -1;
@@ -516,6 +550,11 @@ int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h) {
return 1;
}
MOONBIT_FFI_EXPORT
int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h) {
return mp_kms_present_damage(pixels, w, h, 0, 0, w, h);
}
/* Cursor image by wp_cursor_shape_v1 value (4 pointer hand, 9 text, else arrow). */
MOONBIT_FFI_EXPORT
void mp_kms_set_cursor_shape(int32_t shape) {
+3 -1
View File
@@ -15,7 +15,9 @@ options(
"native-stub": [ "kms_stub.c" ],
link: {
"native": {
"stub-cc-flags": "-I/usr/include/libdrm",
// -O2: setting stub flags drops moon's default ones, and the per-frame pixel copy into the
// scanout buffer is several times slower unoptimised.
"stub-cc-flags": "-O2 -I/usr/include/libdrm",
},
},
)
+23 -1
View File
@@ -8,6 +8,28 @@ let power_supply_root : Ref[String] = { val: "/sys/class/power_supply" }
///| Read batteries from `dir` instead of /sys/class/power_supply (tests: a fake power supply).
pub fn set_power_supply_root(dir : String) -> Unit {
power_supply_root.val = dir
absent_since.val = None
}
///| When the last look found no battery (monotonic ms). A machine without one (most desktops)
/// would otherwise try all eight names every second, for nothing.
let absent_since : Ref[UInt64?] = { val: None }
///| How long "no battery" is believed before looking again (a battery plugged into a running
/// machine shows up within this).
const ABSENT_RECHECK_MS : UInt64 = 30000UL
///| `read_battery` of the configured tree for the once-a-second samplers: without a battery it
/// only looks again every 30 s.
fn read_battery_polled() -> BatteryInfo {
let now = @sys.monotonic_ms()
match absent_since.val {
Some(t) if now - t < ABSENT_RECHECK_MS => return no_battery
_ => ()
}
let b = read_battery()
absent_since.val = if b.state == 0 && b.percent < 0 { Some(now) } else { None }
b
}
///| Names Linux gives batteries (ACPI, Apple, Chromebooks, many ARM boards). The tree is not listed:
@@ -175,7 +197,7 @@ pub fn BatteryMeter::refresh(self : BatteryMeter) -> BatteryInfo {
let now = wall_secs()
if now != self.last_secs {
self.last_secs = now
self.feed(read_battery())
self.feed(read_battery_polled())
}
self.cur
}
+3 -1
View File
@@ -923,8 +923,10 @@ pub fn DesktopShell::render(
self.poll_picker()
self.publish_host_data()
// Machine state and the rich window list only matter to modules that import them.
if self.widgets.iter().any(w => w.has_cap("system")) {
self.sampler.refresh() // reads /proc once a second
}
if self.widgets.iter().any(w => w.has_cap("system") || w.has_cap("windows")) {
self.sampler.refresh()
@wasm.set_windows(self.win_list)
}
if self.widgets.iter().any(w => w.has_cap("icons")) {
+1 -1
View File
@@ -148,7 +148,7 @@ fn mem_kib() -> (Int64, Int64) {
///| (percent, plugged-in) for the machine's batteries (battery.mbt), or (-1, true) without one.
fn battery() -> (Int, Bool) {
let b = read_battery()
let b = read_battery_polled()
(b.percent, b.state != 1)
}
+42 -2
View File
@@ -34,6 +34,46 @@ pub fn pack_tokens(_t : @theme.Tokens) -> Bytes {
Bytes::make(0, b'\x00')
}
///|
fn color_eq(a : @types.Color, b : @types.Color) -> Bool {
a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a
}
///|
fn tokens_eq(a : @theme.Tokens, b : @theme.Tokens) -> Bool {
let (p, q) = (a.palette, b.palette)
a.name == b.name &&
a.font_size == b.font_size &&
a.radius == b.radius &&
a.spacing == b.spacing &&
a.panel_height == b.panel_height &&
color_eq(p.desktop_top, q.desktop_top) &&
color_eq(p.desktop_bottom, q.desktop_bottom) &&
color_eq(p.surface, q.surface) &&
color_eq(p.surface_hover, q.surface_hover) &&
color_eq(p.surface_popup, q.surface_popup) &&
color_eq(p.foreground, q.foreground) &&
color_eq(p.foreground_muted, q.foreground_muted) &&
color_eq(p.accent, q.accent) &&
color_eq(p.accent_foreground, q.accent_foreground) &&
color_eq(p.border, q.border)
}
///| The tokens last handed to the host: every module's render sets them, and the shell renders
/// every module every frame with the same theme, so the host call is skipped while they match.
let sent_tokens : Ref[@theme.Tokens?] = { val: None }
///|
fn send_tokens(t : @theme.Tokens) -> Unit {
match sent_tokens.val {
Some(prev) if physical_equal(prev, t) || tokens_eq(prev, t) => ()
_ => {
sent_tokens.val = Some(t)
@hostpl.set_tokens(t)
}
}
}
///| A loaded plasmoid instance.
pub(all) struct Plasmoid {
handle : Int
@@ -48,7 +88,7 @@ pub(all) struct Plasmoid {
///| Load a plasmoid component. Err carries a short reason.
pub fn load(path : String, tokens : @theme.Tokens) -> Result[Plasmoid, String] {
@hostpl.set_tokens(tokens)
send_tokens(tokens)
match @hostpl.load(path) {
Err(e) => Err(e)
Ok(l) => {
@@ -139,7 +179,7 @@ pub fn Plasmoid::render(
h : Int,
tokens : @theme.Tokens,
) -> Array[@types.DrawOp] {
@hostpl.set_tokens(tokens)
send_tokens(tokens)
@hostpl.render(self.handle.reinterpret_as_uint(), { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() })
}