Alt+Tab switcher: show a preview of each window
CI / test (push) Failing after 19s

The switcher is now a grid of cards: a scaled-down picture of each window's
last frame over its app icon and title, the selected card lit. Cards wrap
into rows and shrink to fit small screens.

- Previews keep the buffer's aspect ratio and are never enlarged.
- Minimized windows show the last frame they drew, dimmed, marked
  "minimized". A window with no buffer yet shows its app icon (or its
  initial) on a plain tile.
- Cheap: nothing is scaled while the switcher is closed. A preview is made
  when the switcher opens and again only when that window commits a new
  buffer (or its shown size changes), into the same image handle; handles
  of closed windows are reused. The native scaler samples at most 3x3
  points per preview pixel, so big windows cost about the same as small.
- Both hosts: native scales the wl_shm snapshot in the software renderer
  (renderer.shm_thumbnail + set_image); the wasm compositor asks the host
  with the new chandra:host/raster thumbnail(surface, w, h, reuse), which
  scales the captured surface natively, so no pixels cross the boundary.
- Frames the screenshot overlay held back mark previews stale too.

Tests: switcher_test (preview pixels, aspect, no-buffer, stale and
remade into the same handle, minimized), renderer shm_thumbnail/set_image,
host-wasm thumbnail scaling and handle reuse. Pre-existing failures on
main are unchanged (6 panel-module host tests, the screenshot panel
module test, host-wasm translucent_surfaces_blend).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjDvAsSQUdTTUGA3n5
This commit is contained in:
Claude committed 2026-11-25 19:14:30 +00:00
1 parent 8f88d93d9f
commit 51b914f6cf
16 files changed
+528 -50

No files matched your search

+8
View File
@@ -75,6 +75,10 @@ pub(all) struct ChandraCompositor {
mut switcher_on : Bool mut switcher_on : Bool
mut switcher : Array[UInt64] mut switcher : Array[UInt64]
mut switcher_sel : Int mut switcher_sel : Int
/// The switcher's window previews (switcher.mbt), by window; kept while the window lives.
thumbs : Map[UInt64, SwitcherThumb]
/// Preview image handles of closed windows, reused for the next ones.
thumb_free : Array[UInt]
mut alt_down : Bool mut alt_down : Bool
/// Milliseconds spent so far in the shell (panel modules) and in the rasteriser, for --profile. /// Milliseconds spent so far in the shell (panel modules) and in the rasteriser, for --profile.
/// The last composed frame and what it was made from: an unchanged desktop is not redrawn. /// The last composed frame and what it was made from: an unchanged desktop is not redrawn.
@@ -169,6 +173,8 @@ pub fn ChandraCompositor::new(
switcher_on: false, switcher_on: false,
switcher: [], switcher: [],
switcher_sel: 0, switcher_sel: 0,
thumbs: {},
thumb_free: [],
alt_down: false, alt_down: false,
last_frame: None, last_frame: None,
last_sig: None, last_sig: None,
@@ -413,6 +419,7 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
} else { } else {
release_snapshot(win.surface) release_snapshot(win.surface)
win.surface = Some(s) win.surface = Some(s)
self.thumb_stale(wid)
self.damage.mark_rect(win.geometry) self.damage.mark_rect(win.geometry)
} }
None => () None => ()
@@ -476,6 +483,7 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
Some(win) => release_snapshot(win.surface) Some(win) => release_snapshot(win.surface)
None => () None => ()
} }
self.thumb_forget(wid)
ignore(self.windows.remove(wid)) ignore(self.windows.remove(wid))
release_snapshot(self.shot_frozen.get(wid)) release_snapshot(self.shot_frozen.get(wid))
self.shot_frozen.remove(wid) self.shot_frozen.remove(wid)
+1
View File
@@ -318,6 +318,7 @@ fn ChandraCompositor::close_overlay(self : ChandraCompositor) -> Unit {
Some(win) => { Some(win) => {
release_snapshot(win.surface) release_snapshot(win.surface)
win.surface = Some(snap) win.surface = Some(snap)
self.thumb_stale(wid)
} }
None => release_snapshot(Some(snap)) None => release_snapshot(Some(snap))
} }
+183 -13
View File
@@ -123,7 +123,138 @@ fn ChandraCompositor::switcher_key(self : ChandraCompositor, code : UInt, presse
false false
} }
///| The switcher's draw ops: a centred list, the selected row lit. Empty when closed. ///| A window's preview in the switcher: an image handle (renderer or host image) of its last
/// buffer scaled to `w`x`h`, made again only when the window committed a new buffer (`stale`) or
/// the size it is shown at changed, and only while the switcher is up.
pub(all) struct SwitcherThumb {
mut handle : UInt
mut w : Int
mut h : Int
mut stale : Bool
}
///| The window committed a new buffer: its preview is made again the next time it is shown.
fn ChandraCompositor::thumb_stale(self : ChandraCompositor, id : UInt64) -> Unit {
match self.thumbs.get(id) {
Some(t) => t.stale = true
None => ()
}
}
///| The window is gone: keep its preview's image handle for the next window's.
fn ChandraCompositor::thumb_forget(self : ChandraCompositor, id : UInt64) -> Unit {
match self.thumbs.get(id) {
Some(t) => {
if t.handle != 0U {
self.thumb_free.push(t.handle)
}
ignore(self.thumbs.remove(id))
}
None => ()
}
}
///| `bw`x`bh` fitted inside `box_w`x`box_h` with its aspect ratio kept, never enlarged.
pub fn thumb_fit(bw : Int, bh : Int, box_w : Int, box_h : Int) -> (Int, Int) {
if bw <= 0 || bh <= 0 || box_w <= 0 || box_h <= 0 {
return (0, 0)
}
if bw <= box_w && bh <= box_h {
return (bw, bh)
}
if bw * box_h >= bh * box_w {
let h = bh * box_w / bw
(box_w, if h < 1 { 1 } else { h })
} else {
let w = bw * box_h / bh
(if w < 1 { 1 } else { w }, box_h)
}
}
///| The preview of window `id` fitted in `box_w`x`box_h`: (image handle, w, h), handle 0 when the
/// window has no buffer yet. A minimized window keeps the last buffer it showed.
fn ChandraCompositor::switcher_thumb(self : ChandraCompositor, id : UInt64, box_w : Int, box_h : Int) -> (UInt, Int, Int) {
let snap = match self.windows.get(id) {
Some(win) => win.surface
None => None
}
let old = self.thumbs.get(id)
match snap {
None =>
match old {
Some(t) => (t.handle, t.w, t.h)
None => (0U, 0, 0)
}
Some(buf) => {
let (tw, th) = thumb_fit(buf.width, buf.height, box_w, box_h)
match old {
Some(t) if !t.stale && t.w == tw && t.h == th => return (t.handle, tw, th)
_ => ()
}
let reuse = match old {
Some(t) => t.handle
None => self.thumb_free.pop().unwrap_or(0U)
}
let h = if tw <= 0 {
0U
} else if buf.host_id != 0U {
@sys.surface_thumbnail(buf.host_id, tw, th, reuse)
} else {
match @renderer.shm_thumbnail(buf, tw, th) {
Some(px) => @renderer.set_image(reuse, px)
None => 0U
}
}
if h == 0U {
// Couldn't make one: show the previous preview if there is one, and try again next time.
match old {
Some(t) => (t.handle, t.w, t.h)
None => {
if reuse != 0U {
self.thumb_free.push(reuse)
}
(0U, 0, 0)
}
}
} else {
match old {
Some(t) => {
t.handle = h
t.w = tw
t.h = th
t.stale = false
}
None => self.thumbs.set(id, { handle: h, w: tw, h: th, stale: false })
}
(h, tw, th)
}
}
}
}
///| Where the switcher's cards go: (columns, preview box width, preview box height). Cards wrap
/// into rows, and shrink when the screen is too small for them.
fn switcher_grid(n : Int, out_w : Int, out_h : Int) -> (Int, Int, Int) {
let mut bw = 220
let mut bh = 138
while true {
let card_w = bw + 16
let card_h = bh + 46
let fit = (out_w - 60 + 8) / (card_w + 8)
let cols = if fit < 1 { 1 } else if fit > n { n } else { fit }
let rows = (n + cols - 1) / cols
if (rows * (card_h + 8) + 40 <= out_h && cols * (card_w + 8) + 52 <= out_w) || bw <= 64 {
return (cols, bw, bh)
}
bw = bw * 4 / 5
bh = bh * 4 / 5
}
(1, bw, bh)
}
///| The switcher's draw ops: a centred grid of cards, each a preview of the window (its last
/// frame, also for minimized windows) over its app icon and title; the selected card lit.
/// Empty when closed.
fn ChandraCompositor::switcher_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] { fn ChandraCompositor::switcher_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
let ops : Array[@scene.DrawOp] = [] let ops : Array[@scene.DrawOp] = []
if !self.switcher_on { if !self.switcher_on {
@@ -131,21 +262,28 @@ fn ChandraCompositor::switcher_ops(self : ChandraCompositor) -> Array[@scene.Dra
} }
let p = self.theme.palette let p = self.theme.palette
let n = self.switcher.length() let n = self.switcher.length()
let row_h = 38 let (cols, bw, bh) = switcher_grid(n, self.output_w, self.output_h)
let pad = 10 let rows = (n + cols - 1) / cols
let w = if self.output_w < 560 { self.output_w - 20 } else { 520 } let cp = 8 // card padding
let h = n * row_h + pad * 2 let gap = 8
let pad = 12
let label_h = 30
let card_w = bw + cp * 2
let card_h = cp + bh + label_h + cp
let w = cols * card_w + (cols - 1) * gap + pad * 2
let h = rows * card_h + (rows - 1) * gap + pad * 2
let x = (self.output_w - w) / 2 let x = (self.output_w - w) / 2
let y = (self.output_h - h) / 2 let y = (self.output_h - h) / 2
let r = self.theme.radius + 4 let r = self.theme.radius + 4
let fs = self.theme.font_size + 1 let fs = self.theme.font_size
// Dim everything behind it a little, then the card. // Dim everything behind it a little, then the panel.
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, self.output_w, self.output_h), @scene.Rgba::new(0, 0, 0, 90), 0)) ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, self.output_w, self.output_h), @scene.Rgba::new(0, 0, 0, 90), 0))
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x, y, w, h), p.surface_popup, r)) ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x, y, w, h), p.surface_popup, r))
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(x, y, w, h), p.border, 1, r)) ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(x, y, w, h), p.border, 1, r))
for i = 0; i < n; i = i + 1 { for i = 0; i < n; i = i + 1 {
let id = self.switcher[i] let id = self.switcher[i]
let ry = y + pad + i * row_h let cx = x + pad + i % cols * (card_w + gap)
let cy = y + pad + i / cols * (card_h + gap)
let sel = i == self.switcher_sel let sel = i == self.switcher_sel
let (title, app, minimized) = match self.windows.get(id) { let (title, app, minimized) = match self.windows.get(id) {
Some(win) => { Some(win) => {
@@ -158,15 +296,47 @@ fn ChandraCompositor::switcher_ops(self : ChandraCompositor) -> Array[@scene.Dra
None => ("", "", false) None => ("", "", false)
} }
if sel { if sel {
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x + pad, ry, w - pad * 2, row_h - 4), p.accent, self.theme.radius)) ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(cx, cy, card_w, card_h), p.accent, self.theme.radius + 2))
}
let icon = self.shell.window_icon(app)
// The preview, centred in its box; without a buffer yet, the app icon on a plain tile.
let (thumb, tw, th) = self.switcher_thumb(id, bw, bh)
let bx = cx + cp
let by = cy + cp
if thumb != 0U {
let tr = @scene.Rect::new(bx + (bw - tw) / 2, by + (bh - th) / 2, tw, th)
ops.push(@scene.DrawOp::Image(tr, thumb))
ops.push(@scene.DrawOp::StrokeRect(tr, p.border, 1, 0))
if minimized {
ops.push(@scene.DrawOp::FillRect(tr, @scene.Rgba::new(0, 0, 0, 120), 0))
}
} else {
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(bx, by, bw, bh), p.surface, self.theme.radius))
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(bx, by, bw, bh), p.border, 1, self.theme.radius))
let big = if bh / 2 < 48 { bh / 2 } else { 48 }
if icon != 0U {
ops.push(@scene.DrawOp::Image(@scene.Rect::new(bx + (bw - big) / 2, by + (bh - big) / 2, big, big), icon))
} else {
let letter = if app.length() > 0 { app[:1].to_string().to_upper() } else if title.length() > 0 { title[:1].to_string().to_upper() } else { "?" }
ops.push(@scene.DrawOp::Text(bx + bw / 2, by + bh / 2, letter, big * 2 / 3, p.foreground_muted, @scene.TextAlign::Center, true))
}
}
if minimized {
ops.push(@scene.DrawOp::Text(bx + bw / 2, by + bh / 2, "minimized", fs - 1, @scene.Rgba::new(255, 255, 255, 230), @scene.TextAlign::Center, true))
}
// The label: app icon, then the title cut to fit.
let ly = by + bh + label_h / 2
let isz = 18
let mut tx = bx + 2
if icon != 0U {
ops.push(@scene.DrawOp::Image(@scene.Rect::new(tx, ly - isz / 2, isz, isz), icon))
tx = tx + isz + 6
} }
let fg = if sel { p.accent_foreground } else if minimized { p.foreground_muted } else { p.foreground } let fg = if sel { p.accent_foreground } else if minimized { p.foreground_muted } else { p.foreground }
let cw = (fs * 11 + 19) / 20 let cw = (fs * 11 + 19) / 20
let max_chars = (w - pad * 2 - 150) / cw let max_chars = (bx + bw - tx) / cw
let shown = if title.length() > max_chars && max_chars > 1 { title[:max_chars - 1].to_string() + "…" } else { title } let shown = if title.length() > max_chars && max_chars > 1 { title[:max_chars - 1].to_string() + "…" } else { title }
ops.push(@scene.DrawOp::Text(x + pad + 12, ry + (row_h - 4) / 2, shown, fs, fg, @scene.TextAlign::Left, sel)) ops.push(@scene.DrawOp::Text(tx, ly, shown, fs, fg, @scene.TextAlign::Left, sel))
let tag = if minimized { app + " (minimized)" } else { app }
ops.push(@scene.DrawOp::Text(x + w - pad - 12, ry + (row_h - 4) / 2, tag, fs - 2, if sel { p.accent_foreground } else { p.foreground_muted }, @scene.TextAlign::Right, false))
} }
ops ops
} }
+99
View File
@@ -0,0 +1,99 @@
///|
test "thumb_fit keeps the aspect ratio and never enlarges" {
assert_eq(@host.thumb_fit(1280, 720, 220, 138), (220, 123))
assert_eq(@host.thumb_fit(600, 1200, 220, 138), (69, 138))
assert_eq(@host.thumb_fit(100, 50, 220, 138), (100, 50))
assert_eq(@host.thumb_fit(4000, 1, 220, 138), (220, 1))
assert_eq(@host.thumb_fit(0, 50, 220, 138), (0, 0))
}
///|
fn find_image(ops : Array[@scene.DrawOp], handle : UInt) -> @scene.Rect? {
for op in ops {
match op {
Image(r, h) if h == handle => return Some(r)
_ => ()
}
}
None
}
///|
fn has_text(ops : Array[@scene.DrawOp], s : String) -> Bool {
ops.iter().any(op => op is Text(_, _, t, _, _, _, _) && t == s)
}
///|
test "alt-tab shows a preview of each window's last frame, made only when needed" {
let socket_path = "/tmp/wayland-moon-thumb-" + @sys.getpid().to_string() + ".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.ChandraCompositor::new(socket_path, theme, 1280, 720).unwrap()
let (c1, shm1, surf1, xdg1, _, _) = open_and_configure_client(comp, socket_path, "A", "a")
commit_shm_frame(comp, c1, shm1, surf1, xdg1, 1UL)
let (c2, shm2, surf2, xdg2, _, _) = open_and_configure_client(comp, socket_path, "B", "b")
commit_shm_frame(comp, c2, shm2, surf2, xdg2, 2UL)
// C maps no buffer at all.
ignore(open_and_configure_client(comp, socket_path, "C", "c"))
for _i = 0; _i < 10; _i = _i + 1 {
comp.step()
}
ignore(comp.compose_scene())
// Nothing is scaled while the switcher is closed.
assert_eq(comp.thumbs.length(), 0)
let key = fn(code : UInt, down : Bool, t : UInt) {
comp.handle_input(@nested.InputEvent::Key(code, down), t)
}
key(56U, true, 1U)
key(15U, true, 2U)
assert_true(comp.switcher_open())
let sg = comp.compose_scene().unwrap()
let t1 = comp.thumbs.get(1UL).unwrap()
assert_true(t1.handle != 0U)
assert_false(t1.stale)
// The aspect ratio of the window's buffer is kept.
let buf = comp.windows.get(1UL).unwrap().surface.unwrap()
assert_true((t1.w * buf.height - t1.h * buf.width).abs() <= buf.width)
assert_true(comp.thumbs.get(2UL).unwrap().handle != 0U)
assert_true(comp.thumbs.get(1UL).unwrap().handle != comp.thumbs.get(2UL).unwrap().handle)
// No buffer yet: no preview (an icon or letter tile stands in).
assert_true(comp.thumbs.get(3UL) is None)
// The preview shows the window's pixels: the test frame has a bright square in its middle.
let r = find_image(sg.panel_ops, t1.handle).unwrap()
assert_eq((r.w, r.h), (t1.w, t1.h))
let px = @renderer.render_scene(sg)
match px.pixel(r.x + r.w / 2, r.y + r.h / 2) {
Some(c) => assert_eq((c.r, c.g, c.b), (b'\x38', b'\xbd', b'\xf8'))
None => abort("no pixel")
}
match px.pixel(r.x + 2, r.y + 2) {
Some(c) => assert_eq((c.r, c.g, c.b), (b'\x1e', b'\x29', b'\x3b'))
None => abort("no pixel")
}
// A new frame from the window marks its preview stale; it's remade into the same handle.
let h1 = t1.handle
commit_shm_frame(comp, c1, shm1, surf1, xdg1, 1UL)
for _i = 0; _i < 5; _i = _i + 1 {
comp.step()
}
assert_true(comp.thumbs.get(1UL).unwrap().stale)
ignore(comp.compose_scene())
assert_false(comp.thumbs.get(1UL).unwrap().stale)
assert_eq(comp.thumbs.get(1UL).unwrap().handle, h1)
key(1U, true, 3U)
key(56U, false, 4U)
assert_false(comp.switcher_open())
// Minimize everything (Super+D): minimized windows keep their last frame as the preview.
key(125U, true, 10U)
key(32U, true, 11U)
key(32U, false, 12U)
key(125U, false, 13U)
assert_true(comp.wm.windows.get(1UL).unwrap().minimized)
key(56U, true, 20U)
key(15U, true, 21U)
assert_true(comp.switcher_open())
let sg = comp.compose_scene().unwrap()
assert_true(find_image(sg.panel_ops, h1) is Some(_))
assert_true(has_text(sg.panel_ops, "minimized"))
key(1U, true, 22U)
key(56U, false, 23U)
}
+63
View File
@@ -12,6 +12,69 @@ pub fn add_image(p : Pixmap) -> UInt {
images.length().reinterpret_as_uint() images.length().reinterpret_as_uint()
} }
///| Put `p` in place of image `handle` (from `add_image`), dropping its cached sizes; a handle that
/// isn't one gets `p` added instead. Returns the handle `p` is under.
pub fn set_image(handle : UInt, p : Pixmap) -> UInt {
let i = handle.reinterpret_as_int() - 1
if i < 0 || i >= images.length() {
return add_image(p)
}
images[i] = p
let stale = scaled.keys().filter(k => k.0 == handle).collect()
for k in stale {
scaled.remove(k)
}
handle
}
///| A `w`x`h` preview of a client buffer (wl_shm ARGB8888/XRGB8888, little-endian B, G, R, A).
/// Each target pixel averages a few points spread over the source pixels it covers (at most 3x3),
/// so a big window costs about the same as a small one: this runs on commits while the Alt+Tab
/// switcher is up, not once per source pixel.
pub fn shm_thumbnail(buf : @scene.ShmBufferSnapshot, w : Int, h : Int) -> Pixmap? {
if w <= 0 || h <= 0 || buf.width <= 0 || buf.height <= 0 || buf.stride < buf.width * 4 ||
buf.bytes.length() < buf.stride * (buf.height - 1) + buf.width * 4 {
return None
}
let out = Pixmap::new(w, h)
let xrgb = buf.format == 1
let src = buf.bytes
for y = 0; y < h; y = y + 1 {
let y0 = y * buf.height / h
let y1 = { let e = (y + 1) * buf.height / h; if e > y0 { e } else { y0 + 1 } }
let ny = if y1 - y0 < 3 { y1 - y0 } else { 3 }
for x = 0; x < w; x = x + 1 {
let x0 = x * buf.width / w
let x1 = { let e = (x + 1) * buf.width / w; if e > x0 { e } else { x0 + 1 } }
let nx = if x1 - x0 < 3 { x1 - x0 } else { 3 }
let mut r = 0
let mut g = 0
let mut b = 0
let mut a = 0
for j = 0; j < ny; j = j + 1 {
let sy = y0 + (y1 - y0) * (2 * j + 1) / (2 * ny)
for i = 0; i < nx; i = i + 1 {
let sx = x0 + (x1 - x0) * (2 * i + 1) / (2 * nx)
let o = sy * buf.stride + sx * 4
let pa = if xrgb { 255 } else { src[o + 3].to_int() }
r = r + src[o + 2].to_int() * pa
g = g + src[o + 1].to_int() * pa
b = b + src[o].to_int() * pa
a = a + pa
}
}
let o = (y * w + x) * 4
if a > 0 {
out.data[o] = (r / a).to_byte()
out.data[o + 1] = (g / a).to_byte()
out.data[o + 2] = (b / a).to_byte()
out.data[o + 3] = (a / (nx * ny)).to_byte()
}
}
}
Some(out)
}
///| Scale `src` to `w`x`h`: each target pixel averages the source pixels it covers (alpha ///| Scale `src` to `w`x`h`: each target pixel averages the source pixels it covers (alpha
/// weighted, so transparent edges don't darken), or takes the nearest one when enlarging. /// weighted, so transparent edges don't darken), or takes the nearest one when enlarging.
pub fn scale_pixmap(src : Pixmap, w : Int, h : Int) -> Pixmap { pub fn scale_pixmap(src : Pixmap, w : Int, h : Int) -> Pixmap {
+4
View File
@@ -24,8 +24,12 @@ pub fn render_scene(@scene.SceneGraph) -> Pixmap
pub fn scale_pixmap(Pixmap, Int32, Int32) -> Pixmap pub fn scale_pixmap(Pixmap, Int32, Int32) -> Pixmap
pub fn set_image(UInt32, Pixmap) -> UInt32
pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit
pub fn shm_thumbnail(@scene.ShmBufferSnapshot, Int32, Int32) -> Pixmap?
pub fn text_width(String, Int32, Bool, Bool) -> Int32 pub fn text_width(String, Int32, Bool, Bool) -> Int32
pub fn zlib_compress(FixedArray[Byte]) -> Array[Byte] pub fn zlib_compress(FixedArray[Byte]) -> Array[Byte]
+37
View File
@@ -100,3 +100,40 @@ test "a compressed PNG is far smaller than the stored one for a desktop-like pic
assert_eq(back.height, 200) assert_eq(back.height, 200)
assert_true(back.data == pm.data) assert_true(back.data == pm.data)
} }
///|
test "shm_thumbnail scales a client buffer; set_image swaps an image in place" {
// 4x2 XRGB buffer (B, G, R, X): left half red, right half blue.
let px : Array[Byte] = []
for _y = 0; _y < 2; _y = _y + 1 {
for x = 0; x < 4; x = x + 1 {
if x < 2 {
px.push(b'\x00'); px.push(b'\x00'); px.push(b'\xff'); px.push(b'\x00')
} else {
px.push(b'\xff'); px.push(b'\x00'); px.push(b'\x00'); px.push(b'\x00')
}
}
}
let buf : @scene.ShmBufferSnapshot = { width: 4, height: 2, stride: 16, format: 1, bytes: Bytes::from_array(px), host_id: 0U }
let t = @renderer.shm_thumbnail(buf, 2, 1).unwrap()
assert_eq(t.pixel(0, 0), Some(@scene.Rgba::new(255, 0, 0, 255)))
assert_eq(t.pixel(1, 0), Some(@scene.Rgba::new(0, 0, 255, 255)))
// A buffer shorter than its stride says is refused, not read past.
assert_true(@renderer.shm_thumbnail({ ..buf, bytes: Bytes::from_array(px[:20]) }, 2, 1) is None)
let h = @renderer.set_image(0U, t)
assert_true(h != 0U)
let dst = @renderer.Pixmap::new(2, 1)
@renderer.draw_ops(dst, [@scene.DrawOp::Image(@scene.Rect::new(0, 0, 2, 1), h)], 0, 0)
assert_eq(dst.pixel(0, 0), Some(@scene.Rgba::new(255, 0, 0, 255)))
// Swapped: the old size cached for the handle is not drawn again.
assert_eq(@renderer.set_image(h, @renderer.shm_thumbnail(buf, 1, 1).unwrap()), h)
let blue = @renderer.Pixmap::new(2, 1)
for i = 0; i < 2; i = i + 1 {
blue.data[i * 4 + 2] = b'\xff'
blue.data[i * 4 + 3] = b'\xff'
}
ignore(@renderer.set_image(h, blue))
let dst = @renderer.Pixmap::new(2, 1)
@renderer.draw_ops(dst, [@scene.DrawOp::Image(@scene.Rect::new(0, 0, 2, 1), h)], 0, 0)
assert_eq(dst.pixel(0, 0), Some(@scene.Rgba::new(0, 0, 255, 255)))
}
+6
View File
@@ -110,6 +110,12 @@ fn DesktopShell::app_icon(self : DesktopShell, app_id : String) -> UInt {
h h
} }
///| The image handle of the app icon for a window with `app_id` (0: none), for the compositor's
/// own UI (the Alt+Tab switcher).
pub fn DesktopShell::window_icon(self : DesktopShell, app_id : String) -> UInt {
if app_id.length() == 0 { 0U } else { self.app_icon(app_id) }
}
///| Publish the icons table (app id -> image handle) for the windows' apps. ///| Publish the icons table (app id -> image handle) for the windows' apps.
fn DesktopShell::publish_icons(self : DesktopShell) -> Unit { fn DesktopShell::publish_icons(self : DesktopShell) -> Unit {
let t = @wasm.Table::new() let t = @wasm.Table::new()
+6
View File
@@ -321,6 +321,12 @@ pub fn surface_release(_id : UInt) -> Unit {
() ()
} }
///| A scaled copy of a host surface as an image handle; 0 (none) on the native build, which
/// scales the snapshot's own pixels instead (`@renderer.shm_thumbnail`).
pub fn surface_thumbnail(_id : UInt, _w : Int, _h : Int, _reuse : UInt) -> UInt {
0U
}
///| A memfd with the host framebuffer as ARGB8888; -1 on the native build. ///| A memfd with the host framebuffer as ARGB8888; -1 on the native build.
pub fn frame_memfd() -> Int { pub fn frame_memfd() -> Int {
-1 -1
+7
View File
@@ -221,6 +221,13 @@ pub fn surface_release(id : UInt) -> Unit {
@hostraster.release(id) @hostraster.release(id)
} }
///| A `w` x `h` scaled copy of captured surface `id` as an image handle for `Image` draw ops (the
/// copy is made in the host). `reuse`: an earlier thumbnail handle to overwrite, 0 for a new one.
/// 0 when the surface is unknown.
pub fn surface_thumbnail(id : UInt, w : Int, h : Int, reuse : UInt) -> UInt {
@hostraster.thumbnail(id, w, h, reuse)
}
///| A new memfd holding the host framebuffer as little-endian ARGB8888, for a wl_shm pool. The ///| A new memfd holding the host framebuffer as little-endian ARGB8888, for a wl_shm pool. The
/// caller closes it. -1 on failure. /// caller closes it. -1 on failure.
pub fn frame_memfd() -> Int { pub fn frame_memfd() -> Int {
+4
View File
@@ -373,6 +373,10 @@ impl chandra::host::raster::Host for State {
self.raster.images.load(&path) self.raster.images.load(&path)
} }
fn thumbnail(&mut self, surface: u32, w: i32, h: i32, reuse: u32) -> u32 {
self.raster.thumbnail(surface, w, h, reuse)
}
fn submit(&mut self, f: chandra::host::raster::Frame) { fn submit(&mut self, f: chandra::host::raster::Frame) {
self.raster.submit(&f, &mut self.fonts); self.raster.submit(&f, &mut self.fonts);
} }
+50
View File
@@ -548,6 +548,19 @@ impl Images {
h h
} }
/// Store `w` x `h` RGBA pixels as an image: overwrite `reuse` when it is a handle from an earlier
/// call (its cached sizes are dropped), else add a new one. Returns the handle.
pub fn put_pixels(&mut self, reuse: u32, w: i32, h: i32, rgba: Vec<u8>) -> u32 {
let src = ImageSrc::Pixels { w, h, rgba };
if reuse > 0 && (reuse as usize) <= self.srcs.len() && !self.by_path.values().any(|&v| v == reuse) {
self.srcs[reuse as usize - 1] = src;
self.sized.borrow_mut().retain(|k, _| k.0 != reuse);
return reuse;
}
self.srcs.push(src);
self.srcs.len() as u32
}
/// Image `handle` at `w` x `h` (cached), or None for an unknown handle or a silly size. /// Image `handle` at `w` x `h` (cached), or None for an unknown handle or a silly size.
fn sized(&self, handle: u32, w: i32, h: i32) -> Option<Rc<Vec<u8>>> { fn sized(&self, handle: u32, w: i32, h: i32) -> Option<Rc<Vec<u8>>> {
if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE { if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE {
@@ -711,6 +724,17 @@ impl Raster {
self.surfaces.remove(&id); self.surfaces.remove(&id);
} }
/// A `w` x `h` scaled copy of surface `id` as an image (see `Images::put_pixels` for `reuse`).
/// 0 for an unknown surface or a silly size.
pub fn thumbnail(&mut self, id: u32, w: i32, h: i32, reuse: u32) -> u32 {
if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE {
return 0;
}
let Some(s) = self.surfaces.get(&id) else { return 0 };
let px = scale_rgba(&s.rgba, s.w, s.h, w, h);
self.images.put_pixels(reuse, w, h, px)
}
pub fn surface_count(&self) -> usize { pub fn surface_count(&self) -> usize {
self.surfaces.len() self.surfaces.len()
} }
@@ -953,6 +977,32 @@ mod tests {
assert_eq!(&r.to_argb8888()[..4], &[3, 2, 1, 255]); assert_eq!(&r.to_argb8888()[..4], &[3, 2, 1, 255]);
} }
#[test]
fn thumbnails_scale_a_surface_and_reuse_their_handle() {
let mut r = Raster::default();
// A 4x2 surface: left half red, right half blue (BGRA in, RGBA out).
let mut src = Vec::new();
for _ in 0..2 {
for x in 0..4 {
src.extend_from_slice(if x < 2 { &[0, 0, 255, 255] } else { &[255, 0, 0, 255] });
}
}
let s = r.add_surface(Surface::from_bgra(&src, 16, 4, 2, true).unwrap());
assert_eq!(r.thumbnail(999, 2, 1, 0), 0);
assert_eq!(r.thumbnail(s, 0, 1, 0), 0);
let t = r.thumbnail(s, 2, 1, 0);
assert_ne!(t, 0);
r.submit(&wt::Frame { panel: vec![wt::Op::DrawImage(wt::Picture { area: rect(0, 0, 2, 1), image: t })], ..frame(4, 4) }, &mut Fonts::default());
assert_eq!(px(&r, 0, 0), [255, 0, 0, 255]);
assert_eq!(px(&r, 1, 0), [0, 0, 255, 255]);
// Refreshing overwrites the same handle, and the old pixels are not served from the cache.
let blue = [255u8, 0, 0, 255].repeat(8);
let s2 = r.add_surface(Surface::from_bgra(&blue, 16, 4, 2, true).unwrap());
assert_eq!(r.thumbnail(s2, 2, 1, t), t);
r.submit(&wt::Frame { panel: vec![wt::Op::DrawImage(wt::Picture { area: rect(0, 0, 2, 1), image: t })], ..frame(4, 4) }, &mut Fonts::default());
assert_eq!(px(&r, 0, 0), [0, 0, 255, 255]);
}
#[test] #[test]
fn images_load_once_by_path_and_draw_scaled_png_and_svg() { fn images_load_once_by_path_and_draw_scaled_png_and_svg() {
let dir = std::env::temp_dir().join(format!("chandra-img-{}", std::process::id())); let dir = std::env::temp_dir().join(format!("chandra-img-{}", std::process::id()));
+20 -17
View File
@@ -9,6 +9,9 @@ fn wasmImportRelease(p0 : Int) = "chandra:host/raster@0.1.0" "release"
///| ///|
fn wasmImportLoadImage(p0 : Int, p1 : Int) -> Int = "chandra:host/raster@0.1.0" "load-image" fn wasmImportLoadImage(p0 : Int, p1 : Int) -> Int = "chandra:host/raster@0.1.0" "load-image"
///|
fn wasmImportThumbnail(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/raster@0.1.0" "thumbnail"
///| ///|
fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) = "chandra:host/raster@0.1.0" "submit" fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) = "chandra:host/raster@0.1.0" "submit"
@@ -18,6 +21,23 @@ fn wasmImportReadFrame(p0 : Int) = "chandra:host/raster@0.1.0" "read-frame"
///| ///|
fn wasmImportExportMemfd() -> Int = "chandra:host/raster@0.1.0" "export-memfd" fn wasmImportExportMemfd() -> Int = "chandra:host/raster@0.1.0" "export-memfd"
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///| ///|
extern "wasm" fn mbt_ffi_free(position : Int) = extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref) #|(func (param i32) local.get 0 call $moonbit.decref)
@@ -36,20 +56,3 @@ extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] =
#| local.get 1 call $moonbit.init_array8 #| local.get 1 call $moonbit.init_array8
#| local.get 0) #| local.get 0)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
+25 -20
View File
@@ -15,6 +15,11 @@ fn wasmImportLoadImage(p0 : Int, p1 : Int) -> Int {
abort("wasm-only host import") abort("wasm-only host import")
} }
///|
fn wasmImportThumbnail(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import")
}
///| ///|
fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) -> Unit { fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) -> Unit {
abort("wasm-only host import") abort("wasm-only host import")
@@ -30,6 +35,26 @@ fn wasmImportExportMemfd() -> Int {
abort("wasm-only host import") abort("wasm-only host import")
} }
///|
fn mbt_ffi_str2ptr(str : String) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_store8(offset : Int, value : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_store32(offset : Int, value : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only")
}
///| ///|
fn mbt_ffi_free(position : Int) -> Unit { fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only") abort("wasm-only")
@@ -44,23 +69,3 @@ fn mbt_ffi_malloc(size : Int) -> Int {
fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] {
abort("wasm-only") abort("wasm-only")
} }
///|
fn mbt_ffi_store32(offset : Int, value : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_str2ptr(str : String) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_store8(offset : Int, value : Int) -> Unit {
abort("wasm-only")
}
+11
View File
@@ -84,6 +84,17 @@ pub fn load_image(path : String) -> UInt {
mbt_ffi_free(ptr) mbt_ffi_free(ptr)
return ret return ret
}
///|
/// A scaled-down copy of captured surface `surface`, `w` x `h`, as an image for `draw-image`
/// (the Alt+Tab switcher's window previews). `reuse`: an earlier thumbnail handle to overwrite
/// in place, 0 for a new one. 0 when the surface is unknown or the size is silly.
pub fn thumbnail(surface : UInt, w : Int, h : Int, reuse : UInt) -> UInt {
let result : Int = wasmImportThumbnail((surface).reinterpret_as_int(), w, h, (reuse).reinterpret_as_int());
let ret = (result).reinterpret_as_uint()
return ret
} }
///| ///|
/// Draw a frame into the host framebuffer. /// Draw a frame into the host framebuffer.
+4
View File
@@ -58,6 +58,10 @@ interface raster {
/// Decode the PNG or SVG file at `path` into a host image (an app icon), for `draw-image`. /// Decode the PNG or SVG file at `path` into a host image (an app icon), for `draw-image`.
/// Loading the same path again returns the same handle. 0 when it can't be read or decoded. /// Loading the same path again returns the same handle. 0 when it can't be read or decoded.
load-image: func(path: string) -> u32; load-image: func(path: string) -> u32;
/// A scaled-down copy of captured surface `surface`, `w` x `h`, as an image for `draw-image`
/// (the Alt+Tab switcher's window previews). `reuse`: an earlier thumbnail handle to overwrite
/// in place, 0 for a new one. 0 when the surface is unknown or the size is silly.
thumbnail: func(surface: u32, w: s32, h: s32, reuse: u32) -> u32;
/// Draw a frame into the host framebuffer. /// Draw a frame into the host framebuffer.
submit: func(f: frame); submit: func(f: frame);
/// The framebuffer as RGBA8888 (for screenshots and tests; the display path never needs it). /// The framebuffer as RGBA8888 (for screenshots and tests; the display path never needs it).