RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Switcher: show subsurface content, keep the cursor visible, idle when held
oxydizercc653544e3b9
diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.mdindex a15c1d2..01fcadc 100644--- a/docs/agent-notes/rendering.md+++ b/docs/agent-notes/rendering.md@@ -41,7 +41,11 @@ chrome, capture, or retained panel painting. General rules remain inthe source's top follows the outer arc, and its full height extends inward.Changing that height damages the whole sector. Ordinary shapes keep rectangularsampling; the radial path removes the output transform from source UVs because- the sector axis already carries it.+ the sector axis already carries it. Several buffers can share one radial image+ (a switcher thumbnail's surface and its subsurfaces): each covers the sector's+ box and names its part with `Buffer.setSectorRect` (fractions of the image),+ which reaches the shader as `sector_texture_rect`; nothing of that draw, ring+ included, lands outside its part.The taskbar uses the same clip on its tree (`Taskbar.applyClip`) with its rasterouter edge left hard (`taskbar/shape.zig` `paintPolygon`: row spans, a distanceonly near an edge).diff --git a/src/Switcher.zig b/src/Switcher.zigindex b4b53e4..26c5648 100644--- a/src/Switcher.zig+++ b/src/Switcher.zig@@ -27,8 +27,9 @@ pub const Card = struct {icon_buffer: *wlr.Buffer,icon_source: wlr.FBox,icon_ready: bool = false,- preview: ?*sn.Buffer = null,- source: wlr.FBox = undefined,+ /// The window's content: its surface and any subsurfaces, or a `.shell`+ /// window's body. `pw` is zero while there is nothing to show.+ content: preview_binding.Stack = .{},pw: i32 = 0,ph: i32 = 0,aspect: f64 = 1,@@ -102,6 +103,7 @@ pub fn step(self: *Self, server: *Server, reverse: bool, trigger: Trigger) voidself.cancel();return;};+ if (self.active()) takePointer(server);}if (self.cards.items.len == 0) return;if (self.circle.enabled) {@@ -123,6 +125,28 @@ pub fn step(self: *Self, server: *Server, reverse: bool, trigger: Trigger) voidself.output.?.wlr_output.scheduleFrame();}+/// The switcher owns the pointer while it is up. The client under it would+/// otherwise keep pointer focus without hearing any motion, and with it the+/// cursor it last set: hidden by a terminal or a player since the last key or+/// frame, a text beam, and nothing would bring the arrow back over the cards.+/// A press or a grab in progress is left alone; it ends where it started.+fn takePointer(server: *Server) void {+ const input = &server.input;+ if (input.active_buttons != 0 or input.seat.drag != null or input.cursor_mode != .passthrough) return;+ input.seat.pointerClearFocus();+ input.pointer_constraints.sync();+ input.setDefaultCursor();+}++/// The gesture is over: tear down, then let the pointer find what is under it+/// again (a client sets its own cursor on that enter). Only for ends that come+/// from the user or the frame loop; forced teardowns call `cancel` alone, from+/// places where input may already be shutting down or locked.+pub fn close(self: *Self, server: *Server) void {+ self.cancel();+ server.input.processCursorMotion(0);+}+/// Circular style only: the key above Tab or Up/Down steps through the/// selected app's own windows while the switcher is held open.pub fn stepWindow(self: *Self, reverse: bool) void {@@ -175,13 +199,13 @@ fn open(self: *Self, server: *Server) !void {ir.fillRect(0, 0, 40, 40, .{ .color = theme.global.switcher_icon_bg, .radius = theme.global.switcher_icon_radius });ir.drawIcon(5, 5, 30, 30, .{ .id = .generic, .color = theme.global.switcher_fg });const icon = try self.makeNode(&icon_image.base, 40, 40);- var card: Card = .{ .icon = icon, .icon_buffer = &icon_image.base, .icon_source = .{ .x = 0, .y = 0, .width = @floatFromInt(icon_image.width), .height = @floatFromInt(icon_image.height) }, .id = tl.id, .label = label, .label_source = .{ .x = 0, .y = 0, .width = @floatFromInt(image.width), .height = @floatFromInt(image.height) } };- card.preview = try self.tree.?.createSceneBuffer(null);- card.preview.?.setFilterMode(.bilinear);- card.preview.?.point_accepts_input = ignoreInput;- updatePreview(&card, tl);- icon.node.raiseToTop();+ const card: Card = .{ .icon = icon, .icon_buffer = &icon_image.base, .icon_source = .{ .x = 0, .y = 0, .width = @floatFromInt(icon_image.width), .height = @floatFromInt(icon_image.height) }, .id = tl.id, .label = label, .label_source = .{ .x = 0, .y = 0, .width = @floatFromInt(image.width), .height = @floatFromInt(image.height) } };+ // Stored first: `cancel` then owns the card's content on any error.try self.cards.append(gpa, card);+ const stored = &self.cards.items[self.cards.items.len - 1];+ _ = try stored.content.addNode(self.tree.?, ignoreInput);+ updatePreview(stored, tl);+ icon.node.raiseToTop();}if (self.cards.items.len == 0) {self.cancel();@@ -232,20 +256,55 @@ fn place(node: *sn.Buffer, source: wlr.FBox, x: i32, y: i32, w: i32, h: i32, vienode.node.setPosition(left, y);}+/// Linear style: the window's surfaces inside its thumbnail at (x, y), each+/// cut to the window's own bounds like the scene cuts a real one.+fn placeContent(card: *Card, x: i32, y: i32, viewport: i32) void {+ const stack = &card.content;+ const fx = @as(f64, @floatFromInt(card.pw)) / @as(f64, @floatFromInt(stack.width));+ const fy = @as(f64, @floatFromInt(card.ph)) / @as(f64, @floatFromInt(stack.height));+ for (stack.active()) |layer| {+ const x1 = @max(layer.x, 0);+ const y1 = @max(layer.y, 0);+ const x2 = @min(layer.x + layer.width, stack.width);+ const y2 = @min(layer.y + layer.height, stack.height);+ const left: i32 = @intFromFloat(@round(@as(f64, @floatFromInt(x1)) * fx));+ const top: i32 = @intFromFloat(@round(@as(f64, @floatFromInt(y1)) * fy));+ const right: i32 = @intFromFloat(@round(@as(f64, @floatFromInt(x2)) * fx));+ const bottom: i32 = @intFromFloat(@round(@as(f64, @floatFromInt(y2)) * fy));+ if (right <= left or bottom <= top) {+ layer.node.node.setEnabled(false);+ continue;+ }+ const w: f64 = @floatFromInt(layer.width);+ const h: f64 = @floatFromInt(layer.height);+ const crop: wlr.FBox = .{+ .x = layer.source.x + layer.source.width * @as(f64, @floatFromInt(x1 - layer.x)) / w,+ .y = layer.source.y + layer.source.height * @as(f64, @floatFromInt(y1 - layer.y)) / h,+ .width = layer.source.width * @as(f64, @floatFromInt(x2 - x1)) / w,+ .height = layer.source.height * @as(f64, @floatFromInt(y2 - y1)) / h,+ };+ place(layer.node, crop, x + left, y + top, right - left, bottom - top, viewport);+ }+}+pub fn tick(self: *Self, output: *Output, now: i64) bool {if (!self.active() or self.output != output) return false;const box = output.usableBox();const expected_width = if (self.circle.enabled) circular.layout.diameter(box.width, box.height) else @min(1500, box.width - 32);if (output.server.locker != null or !output.isLogicallyEnabled() or output.idle_blanked or self.scale != output.wlr_output.scale or self.width != expected_width or box.height < height or self.style != output.server.config.compositor.switcher_style) {- self.cancel();+ self.close(output.server);return false;}// Never leave dead client pointers or a stale selectable preview behind.- for (self.cards.items) |card| {- if (output.server.findToplevelById(card.id) == null) {- self.cancel();+ for (self.cards.items) |*card| {+ const tl = output.server.findToplevelById(card.id) orelse {+ self.close(output.server);return false;- }+ };+ // A subsurface maps, moves or resizes on commits its toplevel never+ // makes: what the window is made of is read again every frame. A+ // `.shell` body is shared again only when it is presented (`committed`).+ if (tl.backend != .shell) updatePreview(card, tl);}// Recomputed every frame (not just on pointer motion) so Tab reflowing// the layout under a stationary mouse still tracks the right card.@@ -262,7 +321,7 @@ pub fn tick(self: *Self, output: *Output, now: i64) bool {const x = @divTrunc(self.width - card_w, 2) + @as(i32, @intCast(i * stride)) - offset;place(card.label.?, card.label_source, x, 28, card_w, card_h, self.width);place(card.icon, card.icon_source, x + 92, 156, 40, 40, self.width);- if (card.pw > 0) if (card.preview) |preview| place(preview, card.source, x + @divTrunc(card_w - card.pw, 2), 36 + @divTrunc(140 - card.ph, 2), card.pw, card.ph, self.width);+ if (card.pw > 0) placeContent(card, x + @divTrunc(card_w - card.pw, 2), 36 + @divTrunc(140 - card.ph, 2), self.width);// The fixed selection outline already marks this card; a second ring// on top of it would just look like a doubled border.if (self.hovered == i and i != self.selected) {@@ -299,36 +358,29 @@ pub fn refreshIcon(self: *Self, card: *Card) void {};}-// Replace the scene reference on every commit, including same-buffer damage.-// Old client buffers are released immediately; the gesture never accumulates-// video frames in the CPU buffer retention list.+/// What the card shows of its window, read from the window as it is now. The+/// nodes follow their surfaces' commits themselves (old client buffers are+/// released at once, so a gesture never accumulates video frames); this keeps+/// which surfaces there are, where they sit and the thumbnail's size.pub fn updatePreview(card: *Card, tl: *@import("Toplevel.zig")) void {- const preview = card.preview orelse return;+ const stack = &card.content;card.pw = 0;if (tl.backend == .shell) {// Settings has no wl_surface: share the body it presents instead.- const cc = tl.backend.shell.control_center orelse return clearPreview(preview);+ const cc = tl.backend.shell.control_center orelse return stack.clear();const body = cc.buffer_node;- if (body.buffer_width <= 0 or body.buffer_height <= 0 or cc.panel_box.width <= 0 or cc.panel_box.height <= 0) return clearPreview(preview);- if (!preview_binding.setOwned(preview, body)) return clearPreview(preview);- card.source = .{ .x = 0, .y = 0, .width = @floatFromInt(body.buffer_width), .height = @floatFromInt(body.buffer_height) };+ if (stack.layers.items.len == 0 or body.buffer_width <= 0 or body.buffer_height <= 0 or cc.panel_box.width <= 0 or cc.panel_box.height <= 0) return stack.clear();+ const layer = &stack.layers.items[0];+ if (!preview_binding.setOwned(layer.node, body)) return stack.clear();+ layer.* = .{ .node = layer.node, .width = cc.panel_box.width, .height = cc.panel_box.height, .source = .{ .x = 0, .y = 0, .width = @floatFromInt(body.buffer_width), .height = @floatFromInt(body.buffer_height) } };+ stack.shown = 1;+ stack.width = cc.panel_box.width;+ stack.height = cc.panel_box.height;fit(card, @floatFromInt(cc.panel_box.width), @floatFromInt(cc.panel_box.height));return;}- if (tl.surface()) |surface| {- if (surface.current.transform == .normal and surface.buffer != null) {- if (!preview_binding.setSurface(preview, surface)) return;- surface.getBufferSourceBox(&card.source);- fit(card, @floatFromInt(@max(1, surface.current.width)), @floatFromInt(@max(1, surface.current.height)));- return;- }- }- clearPreview(preview);-}--fn clearPreview(preview: *sn.Buffer) void {- _ = preview_binding.setSurface(preview, null);- preview.node.setEnabled(false);+ const surface = tl.surface() orelse return stack.clear();+ if (stack.follow(surface)) fit(card, @floatFromInt(stack.width), @floatFromInt(stack.height));}/// Size the linear card's thumbnail for content of `sw`×`sh` logical pixels.@@ -354,11 +406,14 @@ pub fn frameDone(self: *Self, output: *Output, when: *const std.posix.timespec)// The main scene may cull an occluded/minimized window. Visible previews// still pace that client's animation, using the same presentation clock.// Sending twice is harmless: wlroots consumes each callback only once.- for (self.cards.items) |card| {- const preview = card.preview orelse continue;- if (card.pw == 0 or !preview.node.visible()) continue;- const tl = output.server.findToplevelById(card.id) orelse continue;- if (tl.surface()) |surface| surface.sendFrameDone(when);+ for (self.cards.items) |*card| {+ if (card.pw == 0) continue;+ // Each surface paces itself: a browser's content subsurface asks for+ // its own callbacks, not its toplevel's.+ for (card.content.active()) |layer| {+ if (!layer.node.node.visible()) continue;+ if (preview_binding.getSurface(layer.node)) |surface| surface.sendFrameDone(when);+ }}}@@ -421,6 +476,9 @@ pub fn accept(self: *Self, server: *Server) void {if (tl.minimized) tl.restore() else server.world.focus(tl);if (output) |out| server.world.navigateTo(tl, out);}+ // The chosen window may now be the one under the pointer. An animated+ // close does this when it settles (`circular.tick`).+ if (!self.active()) server.input.processCursorMotion(0);}/// Ends the switcher the way the user asked for it to end: releasing the@@ -433,14 +491,15 @@ pub fn accept(self: *Self, server: *Server) void {/// gone, ...) must stay instant and calls `cancel` directly instead.pub fn dismiss(self: *Self) void {if (!self.active()) return;+ const server = self.output.?.server;if (self.circle.closing or !self.circle.enabled) {- self.cancel();+ self.close(server);return;}const now = @import("Taskbar.zig").nowMs();circular.beginClose(self, now);if (self.circle.appear.settled(now)) {- self.cancel();+ self.close(server);return;}self.output.?.wlr_output.scheduleFrame();@@ -451,6 +510,7 @@ pub fn cancel(self: *Self) void {self.circle.deinit();for (self.buffers.items) |buffer| buffer.unlock();self.buffers.deinit(gpa);+ for (self.cards.items) |*card| card.content.deinit();self.cards.deinit(gpa);self.* = .{};}diff --git a/src/capture/window_source.zig b/src/capture/window_source.zigindex b82c649..63246f9 100644--- a/src/capture/window_source.zig+++ b/src/capture/window_source.zig@@ -52,6 +52,7 @@ const PassShape = extern struct {sector_texture_height: f32 = 0,sector_texture_flip: f32 = 0,sector_texture_transform: c_int = 0,+ sector_texture_rect: [4]f32 = @splat(0),border: f32 = 0,border_color: [4]f32 = @splat(0),glow_center: [2]f32 = .{ 0, 0 },diff --git a/src/input/AGENTS.md b/src/input/AGENTS.mdindex 6e27b5c..a3575bc 100644--- a/src/input/AGENTS.md+++ b/src/input/AGENTS.md@@ -37,6 +37,11 @@focus; new compositor input modes go in `motionReachesClient` or`candidate`. `sendDeactivated` destroys oneshots synchronously: clear`active` first.+* **The switcher owns the pointer** while it is up: opening it clears pointer+ focus and shows the arrow (a client's hidden or text cursor would otherwise+ stay, since no motion reaches it), unless a press or grab is in progress.+ User-driven ends go through `Switcher.close`, which re-runs+ `processCursorMotion`; forced teardowns call `cancel` alone.* **Shortcuts inhibit** gates only the switcher, screenshot shortcuts andfinal dispatch; hardware keys, VT switching, System Monitor and open panelsstill win. System Monitor dismisses transient input owners and revokes thediff --git a/src/node.c b/src/node.cindex 49aa723..1e2f640 100644--- a/src/node.c+++ b/src/node.c@@ -379,6 +379,15 @@ void rediwm_buffer_set_transform(struct rediwm_buffer *b, enum wl_output_transfochanged(&b->node);}+void rediwm_buffer_set_sector_rect(struct rediwm_buffer *b, const float rect[4]) {+ const float none[4] = {0};+ const float *next = rect ? rect : none;+ if (next[0] == b->sector_rect[0] && next[1] == b->sector_rect[1] &&+ next[2] == b->sector_rect[2] && next[3] == b->sector_rect[3]) return;+ for (int i = 0; i < 4; i++) b->sector_rect[i] = next[i];+ changed(&b->node);+}+void rediwm_buffer_set_opaque_region(struct rediwm_buffer *b, const pixman_region32_t *region) {if (!region) {if (!pixman_region32_not_empty(&b->opaque_region)) return;diff --git a/src/node.h b/src/node.hindex 7fd9585..8025050 100644--- a/src/node.h+++ b/src/node.h@@ -83,6 +83,10 @@ struct rediwm_buffer {struct wlr_fbox src_box;int dst_width, dst_height;enum wl_output_transform transform;+ // Under a tree clip that maps its texture radially (`sector_texture_height`): the+ // part of the mapped image this node fills, as fractions of it (x, y, width,+ // height). A zero width is all of it. Elsewhere it is not used.+ float sector_rect[4];pixman_region32_t opaque_region;// The size of the buffer as last set, kept for when the renderer releases it.int buffer_width, buffer_height;@@ -204,6 +208,8 @@ void rediwm_buffer_set_source_box(struct rediwm_buffer *, const struct wlr_fboxvoid rediwm_buffer_set_opacity(struct rediwm_buffer *, float opacity);void rediwm_buffer_set_filter_mode(struct rediwm_buffer *, enum wlr_scale_filter_mode);void rediwm_buffer_set_transform(struct rediwm_buffer *, enum wl_output_transform);+// See `sector_rect`; NULL is the whole image.+void rediwm_buffer_set_sector_rect(struct rediwm_buffer *, const float rect[4]);// A copy of the region, in buffer-local units; NULL clears it.void rediwm_buffer_set_opaque_region(struct rediwm_buffer *, const pixman_region32_t *);// The size the buffer node is shown at when nothing sets one: the destination, elsediff --git a/src/node.zig b/src/node.zigindex f977253..83b0d41 100644--- a/src/node.zig+++ b/src/node.zig@@ -171,6 +171,7 @@ pub const Buffer = extern struct {dst_width: c_int,dst_height: c_int,transform: wl.Output.Transform,+ sector_rect: [4]f32,opaque_region: pixman.Region32,buffer_width: c_int,buffer_height: c_int,@@ -214,6 +215,10 @@ pub const Buffer = extern struct {pub const setFilterMode = rediwm_buffer_set_filter_mode;extern fn rediwm_buffer_set_transform(buffer: *Buffer, transform: wl.Output.Transform) void;pub const setTransform = rediwm_buffer_set_transform;+ extern fn rediwm_buffer_set_sector_rect(buffer: *Buffer, rect: ?*const [4]f32) void;+ /// Under a radially mapped tree clip: the part of the mapped image this+ /// node fills (x, y, width, height as fractions); null is all of it.+ pub const setSectorRect = rediwm_buffer_set_sector_rect;extern fn rediwm_buffer_set_opaque_region(buffer: *Buffer, region: ?*const pixman.Region32) void;pub const setOpaqueRegion = rediwm_buffer_set_opaque_region;diff --git a/src/projection_resolve.c b/src/projection_resolve.cindex 43632f4..7382646 100644--- a/src/projection_resolve.c+++ b/src/projection_resolve.c@@ -181,6 +181,7 @@ static void resolve_leaf(struct rediwm_projection *p, struct group *g, struct re}struct rediwm_content *content = &item->content;content->src_box = b->src_box;+ memcpy(content->sector_rect, b->sector_rect, sizeof(content->sector_rect));content->transform = b->transform;content->opacity = b->opacity;content->filter_mode = rediwm_filter_at_scale(w->t.scale, b->filter_mode);diff --git a/src/scene_graph.h b/src/scene_graph.hindex 65b1a99..20c054d 100644--- a/src/scene_graph.h+++ b/src/scene_graph.h@@ -378,6 +378,8 @@ struct rediwm_content {float dim_brightness, dim_saturation;float color[4];struct wlr_fbox src_box;+ // `rediwm_buffer.sector_rect`: a zero width is the whole radially mapped image.+ float sector_rect[4];enum wl_output_transform transform;enum wlr_scale_filter_mode filter_mode;enum wlr_color_transfer_function transfer_function;@@ -395,6 +397,8 @@ static inline bool rediwm_content_equal(const struct rediwm_content *a,a->color[3] == b->color[3] && a->src_box.x == b->src_box.x &&a->src_box.y == b->src_box.y && a->src_box.width == b->src_box.width &&a->src_box.height == b->src_box.height && a->transform == b->transform &&+ a->sector_rect[0] == b->sector_rect[0] && a->sector_rect[1] == b->sector_rect[1] &&+ a->sector_rect[2] == b->sector_rect[2] && a->sector_rect[3] == b->sector_rect[3] &&a->filter_mode == b->filter_mode &&a->transfer_function == b->transfer_function &&a->primaries == b->primaries && a->color_encoding == b->color_encoding &&diff --git a/src/scene_output_draw.c b/src/scene_output_draw.cindex abd205a..6fd9c9a 100644--- a/src/scene_output_draw.c+++ b/src/scene_output_draw.c@@ -73,6 +73,7 @@ static void shape_for(struct rediwm_pass_shape *s, const struct rediwm_clip *c,s->sector_texture_height = (float)(c->sector_texture_height * v->scale);s->sector_texture_flip = v->transform >= WL_OUTPUT_TRANSFORM_FLIPPED ? -1.f : 1.f;s->sector_texture_transform = v->transform;+ memset(s->sector_texture_rect, 0, sizeof(s->sector_texture_rect));s->border = c->border > 0 ? fmaxf(1.f, roundf((float)(c->border * v->scale))) : 0.f;for (int i = 0; i < 4; i++) s->border_color[i] = c->border_color[i];s->glow_radius = s->glow_depth = 0;@@ -254,6 +255,7 @@ bool scene_output_render_entry(struct rediwm_output_renderer *r, struct entry *epixman_region32_subtract(&clip, &clip, &core);}const struct rediwm_content *c = &e->item.content;+ if (shaped) memcpy(shape.sector_texture_rect, c->sector_rect, sizeof(shape.sector_texture_rect));// A window that is not the focus is drawn dimmed, whole: the pass grades each// draw (the interior, the rim and the ring alike) until it is reset below.graded = c->dim_brightness > 0 || c->dim_saturation > 0;diff --git a/src/scene_pass.c b/src/scene_pass.cindex 4e098a2..64756cd 100644--- a/src/scene_pass.c+++ b/src/scene_pass.c@@ -95,7 +95,7 @@ static const char shaped_vertex[] =/* Only the polygon programs (POLY, built on demand) carry it: the others */ \/* compile to what they did before polygons existed. */ \"\n#ifdef POLY\n" \- "uniform float npoly; uniform vec2 poly[17], sector_map; uniform vec4 sector_coords[2];" \+ "uniform float npoly; uniform vec2 poly[17], sector_map; uniform vec4 sector_coords[2], sector_rect;" \"float sdpoly(vec2 p){ float d=dot(p-poly[0],p-poly[0]); float s=1.;" \"for(int i=0;i<16;i++){ if(float(i)>=npoly) break; vec2 a=poly[i], b=poly[i+1];" \"vec2 e=b-a, w=p-a; float h=clamp(dot(w,e)/max(dot(e,e),1e-4),0.,1.); vec2 q=w-e*h; d=min(d,dot(q,q));" \@@ -114,6 +114,12 @@ static const char shaped_vertex[] ="float across=dot(q,vec2(-poly[2].y,poly[2].x))*sector_map.y;" \"float angle=r>.00001?atan(across,dot(q,poly[2])):0.;" \"return vec2(.5+angle/(2.*atan(poly[3].y,poly[3].x)),(poly[1].y-r)/sector_map.x); }" \+ /* A draw that fills only sector_rect of the polar image: its coverage at `p`, */ \+ /* in units of that part. The edges are softened over a device pixel: one */ \+ /* unit across is the arc at this radius, one unit down the mapped height. */ \+ "float sector_part(vec2 p){" \+ "vec2 px=vec2(length(local-poly[0])*2.*atan(poly[3].y,poly[3].x),sector_map.x)*sector_rect.zw;" \+ "vec2 e=clamp(p*px+.5,0.,1.)*clamp((1.-p)*px+.5,0.,1.); return e.x*e.y; }" \"\n#endif\n" \"float sdf(vec2 p, vec4 r){" \"\n#ifdef POLY\n" \@@ -159,14 +165,28 @@ static const char shaped_fragment[] = SHAPED_HEAD"float a=f>=.99999?0.:clamp((c-f)/(1.-f),0.,1.); gl_FragColor=vec4(rgb*a,a); return; }""if(mode>1.5){ float s=clamp(1.-sdf(local-offset,radii)/softness,0.,1.); s=s*s*(3.-2.*s);""if(hide>.5)s*=1.-cov(sdf(local,radii)); gl_FragColor=color*s; return; }"- "vec4 c=color; if(mode<.5){ vec2 at=uv; float content=1.;"+ "vec4 c=color;"+ "\n#ifdef POLY\n"+ // How much of this fragment a draw that fills only part of a polar image+ // (sector_rect) takes part in: the body and the ring over it alike.+ "float part=1.;"+ "\n#endif\n"+ "if(mode<.5){ vec2 at=uv; float content=1.;""\n#ifdef POLY\n""if(use_shape>.5&&npoly<-.5&§or_map.x>0.){ vec2 p=sector_uv(local);"- "content=clamp((1.-p.y)*sector_map.x+.5,0.,1.); p=clamp(p,0.,1.);"+ "content=clamp((1.-p.y)*sector_map.x+.5,0.,1.);"+ "if(sector_rect.z>0.){ p=(p-sector_rect.xy)/sector_rect.zw; part=sector_part(p); }"+ "p=clamp(p,0.,1.);""at=mix(mix(sector_coords[0].xy,sector_coords[0].zw,p.x),""mix(sector_coords[1].xy,sector_coords[1].zw,p.x),p.y); }""\n#endif\n""c=texture2D(tex,at); if(opaque>.5)c.a=1.; c*=alpha*content; }"+ // A colour standing for such a part (a single-pixel buffer) ends with the+ // image and the part too. One that stands for the whole image is unchanged.+ "\n#ifdef POLY\n"+ "else if(mode<1.5&&use_shape>.5&&npoly<-.5&§or_map.x>0.&§or_rect.z>0.){ vec2 p=sector_uv(local);"+ "c*=clamp((1.-p.y)*sector_map.x+.5,0.,1.); part=sector_part((p-sector_rect.xy)/sector_rect.zw); }"+ "\n#endif\n"// Without a shape (every plain draw) the colour is written as it is: the// plain programs are gone (stage 5, D4), and this costs one uniform branch."if(use_shape<.5){ gl_FragColor=vec4(grade(c.rgb),c.a); return; }"@@ -178,7 +198,11 @@ static const char shaped_fragment[] = SHAPED_HEAD"if(glow.z>0.){ float g=clamp(1.-length(local-glow.xy)/glow.z,0.,1.); g=g*g*(3.-2.*g);""float t=glow.w>0.?1.-smoothstep(0.,1.,(-d-border)/glow.w):w;""o=o*(1.-gcolor.a*g*t)+gcolor*(g*t); }"- "o.rgb=grade(o.rgb); gl_FragColor=o*cov(d); }";+ "o.rgb=grade(o.rgb); gl_FragColor=o*cov(d);"+ "\n#ifdef POLY\n"+ "gl_FragColor*=part;"+ "\n#endif\n"+ "}";// The backdrop blur (stage 5b): glass.c's kernel, 49 taps, sigma in texels of the// target, reading a source texture that may be larger than the region (scratch),@@ -253,6 +277,7 @@ bool scene_pass_program_init(struct program *p, unsigned bit, const char *vertexp->poly = glGetUniformLocation(p->id, "poly[0]");p->sector_map = glGetUniformLocation(p->id, "sector_map");p->sector_coords = glGetUniformLocation(p->id, "sector_coords[0]");+ p->sector_rect = glGetUniformLocation(p->id, "sector_rect");p->border = glGetUniformLocation(p->id, "border");p->bcolor = glGetUniformLocation(p->id, "bcolor");p->glow = glGetUniformLocation(p->id, "glow");diff --git a/src/scene_pass.h b/src/scene_pass.hindex fbe73c0..f3f49af 100644--- a/src/scene_pass.h+++ b/src/scene_pass.h@@ -57,6 +57,11 @@ struct rediwm_pass_shape {// are tracked separately so the source is never rotated or mirrored twice.float sector_texture_height, sector_texture_flip;enum wl_output_transform sector_texture_transform;+ // With polar framing: the part of that image this texture fills, as fractions+ // of it (x, y, width, height), so several textures share one framing (a+ // window and its subsurfaces). Nothing is drawn outside it, the ring+ // included. A zero width is the whole image.+ float sector_texture_rect[4];// Width of the ring just inside the edge. The same fragment that draws the body// composites the ring over it, then applies the shape's coverage, so a// translucent border tints the fill beneath it, as the legacy border rects do,diff --git a/src/scene_pass_draw.c b/src/scene_pass_draw.cindex bc728a1..64dbd96 100644--- a/src/scene_pass_draw.c+++ b/src/scene_pass_draw.c@@ -54,6 +54,7 @@ void scene_pass_set_shape(const struct pass *p, const struct program *g, const sglUniform4f(g->radii, s->radii[0], s->radii[1], s->radii[2], s->radii[3]);const bool sector = s->sector.radii[1] > 0;if (g->sector_map >= 0) glUniform2f(g->sector_map, s->sector_texture_height, s->sector_texture_flip);+ if (g->sector_rect >= 0) glUniform4fv(g->sector_rect, 1, s->sector_texture_rect);if (g->npoly >= 0) glUniform1f(g->npoly, sector ? -1.f : (float)s->poly_count);if (sector && g->poly >= 0) {const float payload[4][2] = {diff --git a/src/scene_pass_internal.h b/src/scene_pass_internal.hindex 144fc81..cffea7c 100644--- a/src/scene_pass_internal.h+++ b/src/scene_pass_internal.h@@ -29,7 +29,7 @@ struct program {GLint target, dst, color, alpha, opaque, sampler, coords;// Shaped programs only (-1 elsewhere): the shape, and the shadow's own terms.GLint mode, origin, size, radii, npoly, poly, border, bcolor, glow, gcolor, offset, softness, hide, use_shape, dim;- GLint sector_map, sector_coords;+ GLint sector_map, sector_coords, sector_rect;// What `dim` holds now (a uniform keeps its value between draws and passes).float dim_brightness, dim_saturation;// The backdrop composite (shaped mode 3) and the blur program.@@ -143,6 +143,9 @@ static inline bool shape_usable(const struct rediwm_pass_shape *s) {(s->sector_texture_flip != 1 && s->sector_texture_flip != -1) ||s->sector_texture_transform < WL_OUTPUT_TRANSFORM_NORMAL ||s->sector_texture_transform > WL_OUTPUT_TRANSFORM_FLIPPED_270)) return false;+ for (int i = 0; i < 4; i++) if (!isfinite(s->sector_texture_rect[i])) return false;+ if (s->sector_texture_rect[2] < 0 || s->sector_texture_rect[3] < 0 ||+ (s->sector_texture_rect[2] > 0 && s->sector_texture_rect[3] <= 0)) return false;for (int i = 0; i < 4; i++) if (!isfinite(s->border_color[i]) || !isfinite(s->glow_color[i])) return false;return isfinite(s->glow_radius) && isfinite(s->glow_depth) && s->glow_radius >= 0 && s->glow_depth >= 0 &&isfinite(s->glow_center[0]) && isfinite(s->glow_center[1]);diff --git a/src/scene_pass_test_sector.c b/src/scene_pass_test_sector.cindex 90d3ba7..1755a32 100644--- a/src/scene_pass_test_sector.c+++ b/src/scene_pass_test_sector.c@@ -149,6 +149,36 @@ static void gate_sector_texture(struct rediwm_scene_renderer *r, struct wlr_buffconst uint8_t *empty = at(img, 140, 90);for (int ch = 0; ch < 3; ch++)check(diff(empty[ch], (int)lround(BG[ch] * 255)) <= 1, "sector short source smeared its bottom row");+ // A part of the image (a subsurface of the previewed window): the texture's+ // whole source lands in its part, and nothing of the draw outside it.+ struct rediwm_pass_shape part = {+ .box = {20, 20, 240, 240},+ .sector = {.center = {120, 120}, .radii = {30, 110}, .axis = {0, -1},+ .half_angle = {(float)cos(half), (float)sin(half)}},+ .sector_texture_height = 80, .sector_texture_flip = 1,+ .sector_texture_rect = {.25f, .25f, .5f, .5f},+ .border = 2, .border_color = {0.f, .8f, .9f, 1.f},+ };+ pass = begin_fill(r, buf, BG, NULL);+ rediwm_scene_pass_add_texture_shaped(pass, &(struct wlr_render_texture_options){+ .texture = texture, .dst_box = part.box,+ .src_box = {16, 24, 96, 80}, .filter_mode = WLR_SCALE_FILTER_BILINEAR,+ }, &part);+ finish(pass);+ read_image(r, buf, img);+ // Image row v sits at radius 110 - 80 v along the axis (straight up): the+ // part spans rows .25 to .75, radii 90 down to 50.+ const uint8_t *inside = at(img, 140, 140 - 70), *above = at(img, 140, 140 - 100),+ *below = at(img, 140, 140 - 40), *rim = at(img, 140, 140 - 109);+ // That pixel's centre is half a pixel right of the axis, at radius 69.5.+ const double part_u = (.5 + atan2(.5, 69.5) / (2 * half) - .25) / .5, part_v = ((110 - hypot(.5, 69.5)) / 80 - .25) / .5;+ check(diff(inside[0], (int)lround(2 * (16 + 96 * part_u - .5))) <= 2 &&+ diff(inside[1], (int)lround(2 * (24 + 80 * part_v - .5))) <= 2, "sector part does not show its source's middle at its own");+ for (int ch = 0; ch < 3; ch++) {+ check(diff(above[ch], (int)lround(BG[ch] * 255)) <= 1 && diff(below[ch], (int)lround(BG[ch] * 255)) <= 1,+ "sector part drew outside its rows");+ check(diff(rim[ch], (int)lround(BG[ch] * 255)) <= 1, "sector part drew the ring outside itself");+ }wlr_texture_destroy(texture);printf("PASS: sector previews retain top rows, crop only the bottom and preserve source/output transforms (max diff %d)\n", worst);}diff --git a/src/switcher/circular.zig b/src/switcher/circular.zigindex e399a76..692169b 100644--- a/src/switcher/circular.zig+++ b/src/switcher/circular.zig@@ -92,9 +92,6 @@ pub fn open(self: *Switcher, server: *Server) !void {const group = &self.circle.groups.items[group_index];const tree = try self.tree.?.createSceneTree();const fill = try col.createRect(tree, 1, 1, col.Straight.fromRgba(theme.global.switcher_item_bg).premultiply());- const preview = try tree.createSceneBuffer(null);- preview.setFilterMode(.bilinear);- preview.point_accepts_input = Switcher.ignoreInput;const icon_image = try PanelBuffer.create(40, 40, self.scale);defer icon_image.base.drop();r = ui.paint.Renderer.init(icon_image.pixels, icon_image.width, icon_image.height, self.scale);@@ -104,21 +101,23 @@ pub fn open(self: *Switcher, server: *Server) !void {// Only the hub presents an icon. Keep this node as the shared icon// loader's storage while the sector itself shows uninterrupted content.icon.node.setEnabled(false);- var card: Switcher.Card = .{+ const card: Switcher.Card = .{.id = tl.id,.icon = icon,.icon_buffer = &icon_image.base,.icon_source = .{ .x = 0, .y = 0, .width = @floatFromInt(icon_image.width), .height = @floatFromInt(icon_image.height) },.tree = tree,.fill = fill,- .preview = preview,.group = group_index,.member = group.count,};- Switcher.updatePreview(&card, tl);+ // Stored first: `cancel` then owns the card's content on any error.try self.cards.append(gpa, card);try group.members.append(gpa, index);group.count += 1;+ const stored = &self.cards.items[index];+ _ = try stored.content.addNode(tree, Switcher.ignoreInput);+ Switcher.updatePreview(stored, tl);}// Seed every card's animated stack slot at its resting depth so an// unselected group's cascade renders correctly without having to wait@@ -298,7 +297,7 @@ pub fn tick(self: *Switcher, output: *Output, now: i64) bool {// it needs a frame boundary to keep sampling `appear` against, and this// is the one place already called every frame while the switcher lives.if (self.circle.closing and self.circle.appear.settled(now)) {- self.cancel();+ self.close(output.server);return false;}const box = output.usableBox();@@ -371,17 +370,32 @@ fn placeCard(self: *Switcher, card: *Switcher.Card, sector: layout.Sector, depth// fully fanned-out stack reads clearly instead of staying half-shadowed.const dim: f32 = if (depth > 0) @floatCast(0.18 * (1 - 0.7 * progress)) else 0;_ = projection.setTreeDim(&tree.node, dim, 0);- const preview = card.preview.?;// A full-size preview supplies the shape's body and ring itself. Drawing// the fallback underneath it would apply edge coverage and border twice.card.fill.?.node.setEnabled(card.pw <= 0);- preview.node.setEnabled(card.pw > 0);if (card.pw <= 0) return;- // The shader fans the complete source width around the outer arc, keeping+ // The shader fans the complete window width around the outer arc, keeping// its header visible. The hub crops the bottom of tall windows. Live client// buffers still pass straight through, without CPU readback or copies.- preview.setSourceBox(&card.source);- preview.setDestSize(sector.width, sector.height);+ // Every surface of the window covers the sector's box and names the part+ // of the fanned window it fills; the shader draws it nowhere else.+ const stack = &card.content;+ const w: f32 = @floatFromInt(stack.width);+ const h: f32 = @floatFromInt(stack.height);+ for (stack.active()) |layer| {+ const node = layer.node;+ const whole = layer.x == 0 and layer.y == 0 and layer.width == stack.width and layer.height == stack.height;+ const part: [4]f32 = .{+ @as(f32, @floatFromInt(layer.x)) / w,+ @as(f32, @floatFromInt(layer.y)) / h,+ @as(f32, @floatFromInt(layer.width)) / w,+ @as(f32, @floatFromInt(layer.height)) / h,+ };+ node.setSectorRect(if (whole) null else &part);+ node.setSourceBox(&layer.source);+ node.setDestSize(sector.width, sector.height);+ node.node.setEnabled(true);+ }}/// The window-count badge for a multi-window group, held over the focused@@ -497,7 +511,11 @@ fn updateArrow(self: *Switcher, now: i64) void {// uses for the wheel's own rotation.const current: f64 = self.circle.arrow_angle.to;const delta = @mod(target - current + std.math.pi, tau) - std.math.pi;- self.circle.arrow_angle.retargetTo(now, @floatCast(current + delta), ui.anim.curveFor(.switcher_scroll));+ // Only a new target: an arrow that has never moved is not an animation yet,+ // and committing its resting angle again every frame would report a fresh+ // sample each time, repainting it and keeping a held switcher drawing.+ const next: f32 = @floatCast(current + delta);+ if (next != self.circle.arrow_angle.to) self.circle.arrow_angle.retargetTo(now, next, ui.anim.curveFor(.switcher_scroll));// The orbit is much wider than the glyph: sample at subpixel arc steps.if (!self.circle.arrow_angle.sampleChanged(now, 0.003)) return;diff --git a/src/switcher/preview.zig b/src/switcher/preview.zigindex e85609d..ec2eef6 100644--- a/src/switcher/preview.zig+++ b/src/switcher/preview.zig@@ -1,16 +1,149 @@-//! Client-buffer synchronization for switcher thumbnails. Geometry and frame-//! callbacks stay with Switcher; the binding never changes output/scale feedback.+//! Switcher thumbnails: client-buffer synchronization and the stack of surfaces+//! one window is made of. Placement and frame callbacks stay with Switcher; a+//! binding never changes output/scale feedback.+const std = @import("std");const sn = @import("../node.zig");const wlr = @import("wlroots");+const gpa = @import("../main.zig").gpa;extern fn rediwm_switcher_preview_set_surface(preview: *sn.Buffer, surface: ?*wlr.Surface) bool;-/// Refresh on every source commit, and pass null to clear. The preview node owns-/// the binding; its destruction or the source's destruction detaches it safely.+/// Bind once: the node then follows every commit of the surface by itself.+/// Null clears. The preview node owns the binding; its destruction or the+/// source's destruction detaches it safely.pub const setSurface = rediwm_switcher_preview_set_surface;+extern fn rediwm_switcher_preview_get_surface(preview: *sn.Buffer) ?*wlr.Surface;++/// The surface the node follows; null once that surface is gone.+pub const getSurface = rediwm_switcher_preview_get_surface;+extern fn rediwm_switcher_preview_set_owned(preview: *sn.Buffer, source: *sn.Buffer) bool;/// Mirror a compositor-owned buffer node (a `.shell` window's body). Call after/// each present; false when the source has no buffer to share.pub const setOwned = rediwm_switcher_preview_set_owned;++/// A client that nests deeper or stacks more than this shows its first layers.+const max_depth = 8;+const max_layers = 32;++/// One surface of a window, shown by its own node: the toplevel's surface or a+/// mapped subsurface. Browsers of the Firefox family, video players and GTK's+/// graphics offload draw their content into subsurfaces; the toplevel's own+/// buffer is then little more than a background.+pub const Layer = struct {+ node: *sn.Buffer,+ /// Where the surface sits in the toplevel surface's coordinates.+ x: i32 = 0,+ y: i32 = 0,+ width: i32 = 0,+ height: i32 = 0,+ /// The part of its buffer the surface shows.+ source: wlr.FBox = .{ .x = 0, .y = 0, .width = 0, .height = 0 },+};++/// A window's layers, bottom to top. Nodes are made once, in stacking order,+/// and kept: when the client restacks, adds or removes subsurfaces the nodes+/// are bound again in order instead of being moved.+pub const Stack = struct {+ /// Every node made so far; the first `shown` hold the window's surfaces.+ layers: std.ArrayList(Layer) = .empty,+ shown: usize = 0,+ /// The toplevel surface's size, the space `Layer` positions are in.+ width: i32 = 0,+ height: i32 = 0,++ pub fn deinit(self: *Stack) void {+ self.layers.deinit(gpa);+ }++ pub fn active(self: *const Stack) []Layer {+ return self.layers.items[0..self.shown];+ }++ /// A node above the ones already made. `open` makes the first while it+ /// builds the card, so later ones can be stacked right above it.+ pub fn addNode(self: *Stack, parent: *sn.Tree, accepts_input: @FieldType(sn.Buffer, "point_accepts_input")) !*sn.Buffer {+ try self.layers.ensureUnusedCapacity(gpa, 1);+ const node = try parent.createSceneBuffer(null);+ node.setFilterMode(.bilinear);+ node.point_accepts_input = accepts_input;+ node.node.setEnabled(false);+ if (self.layers.items.len > 0) node.node.placeAbove(&self.layers.items[self.layers.items.len - 1].node.node);+ self.layers.appendAssumeCapacity(.{ .node = node });+ return node;+ }++ /// Show nothing: every node lets go of its surface.+ pub fn clear(self: *Stack) void {+ self.release(0);+ self.width = 0;+ self.height = 0;+ }++ /// Only the nodes in use: this runs every frame, and clearing an idle node+ /// again would report a change and keep a settled switcher drawing.+ fn release(self: *Stack, from: usize) void {+ if (from >= self.shown) return;+ for (self.layers.items[from..self.shown]) |layer| {+ _ = setSurface(layer.node, null);+ layer.node.node.setEnabled(false);+ }+ self.shown = from;+ }++ /// Follow `root` and its mapped subsurfaces. False (and nothing shown)+ /// when the toplevel surface itself cannot be shown.+ pub fn follow(self: *Stack, root: *wlr.Surface) bool {+ if (!showable(root) or self.layers.items.len == 0) {+ self.clear();+ return false;+ }+ var count: usize = 0;+ self.collect(root, 0, 0, 0, &count);+ self.release(count);+ self.shown = count;+ self.width = @max(1, root.current.width);+ self.height = @max(1, root.current.height);+ return true;+ }++ /// The compositor's stacking order: subsurfaces below their parent, the+ /// parent, the ones above, each with its own children around it.+ fn collect(self: *Stack, surface: *wlr.Surface, x: i32, y: i32, depth: usize, count: *usize) void {+ self.collectChildren(&surface.current.subsurfaces_below, x, y, depth, count);+ if (showable(surface) and count.* < max_layers) add: {+ if (count.* == self.layers.items.len) {+ const below = self.layers.items[count.* - 1].node;+ const parent = below.node.parent orelse break :add;+ _ = self.addNode(parent, below.point_accepts_input) catch break :add;+ }+ const layer = &self.layers.items[count.*];+ if (getSurface(layer.node) != surface and !setSurface(layer.node, surface)) break :add;+ layer.x = x;+ layer.y = y;+ layer.width = surface.current.width;+ layer.height = surface.current.height;+ surface.getBufferSourceBox(&layer.source);+ count.* += 1;+ }+ self.collectChildren(&surface.current.subsurfaces_above, x, y, depth, count);+ }++ fn collectChildren(self: *Stack, list: anytype, x: i32, y: i32, depth: usize, count: *usize) void {+ if (depth >= max_depth) return;+ var it = list.iterator(.forward);+ while (it.next()) |state| {+ const sub: *wlr.Subsurface = @fieldParentPtr("current", state);+ if (!sub.surface.mapped) continue;+ self.collect(sub.surface, x + state.x, y + state.y, depth + 1, count);+ }+ }+};++/// A rotated or flipped buffer is left out, as it always was for the toplevel.+fn showable(surface: *wlr.Surface) bool {+ return surface.buffer != null and surface.current.transform == .normal and+ surface.current.width > 0 and surface.current.height > 0;+}diff --git a/src/switcher_preview.c b/src/switcher_preview.cindex 505860c..55d874d 100644--- a/src/switcher_preview.c+++ b/src/switcher_preview.c@@ -19,7 +19,7 @@ struct preview_binding {struct wlr_surface *surface;struct wlr_client_buffer *marked;uint32_t commit_seq;- struct wl_listener node_destroy, surface_destroy, output_sample;+ struct wl_listener node_destroy, surface_destroy, surface_commit, output_sample;};static void unmark_buffer(struct preview_binding *binding) {@@ -34,6 +34,7 @@ static void destroy_binding(struct wlr_addon *addon) {unmark_buffer(binding);wl_list_remove(&binding->node_destroy.link);wl_list_remove(&binding->surface_destroy.link);+ wl_list_remove(&binding->surface_commit.link);wl_list_remove(&binding->output_sample.link);wlr_addon_finish(addon);free(binding);@@ -62,7 +63,7 @@ static void handle_output_sample(struct wl_listener *listener, void *data) {const struct rediwm_output_sample_event *event = data;if (!binding->surface || !event->release_timeline) return;// Commits and output rendering run synchronously on the Wayland event loop.- // The caller updates the binding on each commit, before the next pass starts.+ // The binding follows each commit itself, before the next pass starts.assert(binding->commit_seq == binding->surface->current.seq);struct wlr_linux_drm_syncobj_surface_v1_state *state =wlr_linux_drm_syncobj_v1_get_surface_state(binding->surface);@@ -76,12 +77,46 @@ static struct preview_binding *find_binding(struct rediwm_buffer *preview) {return addon ? wl_container_of(addon, binding, addon) : NULL;}+// Show the bound surface's current buffer, with what its last commit damaged and+// its acquire point.+static void refresh(struct preview_binding *binding) {+ struct wlr_surface *surface = binding->surface;+ unmark_buffer(binding);+ struct wlr_client_buffer *buffer = surface ? surface->buffer : NULL;+ struct rediwm_buffer_options options = {0};+ if (surface) {+ binding->commit_seq = surface->current.seq;+ options.damage = &surface->buffer_damage;+ struct wlr_linux_drm_syncobj_surface_v1_state *state =+ wlr_linux_drm_syncobj_v1_get_surface_state(surface);+ if (state) {+ options.wait_timeline = state->acquire_timeline;+ options.wait_point = state->acquire_point;+ }+ }+ if (buffer && (!buffer->source ||+ !wlr_single_pixel_buffer_v1_try_from_buffer(buffer->source))) {+ // Just like a surface node: a live thumbnail sees in-place shm updates.+ buffer->private.n_ignore_locks++;+ binding->marked = buffer;+ }+ rediwm_buffer_set_buffer_with_options(binding->preview, buffer ? &buffer->base : NULL, &options);+}++static void handle_surface_commit(struct wl_listener *listener, void *data) {+ (void)data;+ struct preview_binding *binding = wl_container_of(listener, binding, surface_commit);+ refresh(binding);+}+static struct preview_binding *create_binding(struct rediwm_buffer *preview) {struct preview_binding *binding = calloc(1, sizeof(*binding));if (!binding) return NULL;binding->preview = preview;wlr_addon_init(&binding->addon, &preview->node.addons, NULL, &binding_impl);wl_list_init(&binding->surface_destroy.link);+ wl_list_init(&binding->surface_commit.link);+ binding->surface_commit.notify = handle_surface_commit;binding->node_destroy.notify = handle_node_destroy;wl_signal_add(&preview->node.events.destroy, &binding->node_destroy);binding->surface_destroy.notify = handle_surface_destroy;@@ -94,8 +129,12 @@ static void follow_surface(struct preview_binding *binding, struct wlr_surface *if (binding->surface == surface) return;wl_list_remove(&binding->surface_destroy.link);wl_list_init(&binding->surface_destroy.link);+ wl_list_remove(&binding->surface_commit.link);+ wl_list_init(&binding->surface_commit.link);binding->surface = surface;- if (surface) wl_signal_add(&surface->events.destroy, &binding->surface_destroy);+ if (!surface) return;+ wl_signal_add(&surface->events.destroy, &binding->surface_destroy);+ wl_signal_add(&surface->events.commit, &binding->surface_commit);}bool rediwm_switcher_preview_set_owned(struct rediwm_buffer *preview,@@ -132,25 +171,11 @@ bool rediwm_switcher_preview_set_surface(struct rediwm_buffer *preview,if (!binding) return false;}follow_surface(binding, surface);- unmark_buffer(binding);- struct wlr_client_buffer *buffer = surface ? surface->buffer : NULL;- struct rediwm_buffer_options options = {0};- if (surface) {- binding->commit_seq = surface->current.seq;- options.damage = &surface->buffer_damage;- struct wlr_linux_drm_syncobj_surface_v1_state *state =- wlr_linux_drm_syncobj_v1_get_surface_state(surface);- if (state) {- options.wait_timeline = state->acquire_timeline;- options.wait_point = state->acquire_point;- }- }- if (buffer && (!buffer->source ||- !wlr_single_pixel_buffer_v1_try_from_buffer(buffer->source))) {- // Just like a surface node: a live thumbnail sees in-place shm updates.- buffer->private.n_ignore_locks++;- binding->marked = buffer;- }- rediwm_buffer_set_buffer_with_options(preview, buffer ? &buffer->base : NULL, &options);+ refresh(binding);return true;}++struct wlr_surface *rediwm_switcher_preview_get_surface(struct rediwm_buffer *preview) {+ struct preview_binding *binding = find_binding(preview);+ return binding ? binding->surface : NULL;+}diff --git a/src/switcher_preview.h b/src/switcher_preview.hindex e85d1f0..4662edb 100644--- a/src/switcher_preview.h+++ b/src/switcher_preview.h@@ -5,10 +5,13 @@ struct rediwm_buffer;struct wlr_surface;// Follow the surface's current buffer without changing its output/scale feedback-// or frame pacing. Call on every surface commit; NULL clears the binding. Once-// bound, replace/clear content only through this helper. Geometry stays caller-owned.-// The node owns the binding and a destroyed surface clears its content.+// or frame pacing: bound once, the node shows every later commit by itself. NULL+// clears the binding. Once bound, replace/clear content only through this helper.+// Geometry stays caller-owned. The node owns the binding and a destroyed surface+// clears its content. Any wl_surface can be followed, a subsurface included.bool rediwm_switcher_preview_set_surface(struct rediwm_buffer *, struct wlr_surface *);+// The surface the node follows, NULL when none (never bound, cleared, destroyed).+struct wlr_surface *rediwm_switcher_preview_get_surface(struct rediwm_buffer *);// Show what a compositor-owned buffer node (`rediwm_projection_present_owned`)// presents, keeping its in-place texture updates possible. Call after eachdiff --git a/src/switcher_preview_test.c b/src/switcher_preview_test.cindex 8756d99..9e77db5 100644--- a/src/switcher_preview_test.c+++ b/src/switcher_preview_test.c@@ -65,6 +65,7 @@ static struct wlr_client_buffer *new_client(void) {}static void init_surface(struct wlr_surface *surface) {wl_signal_init(&surface->events.destroy);+ wl_signal_init(&surface->events.commit);wl_list_init(&surface->current_outputs);pixman_region32_init_rect(&surface->buffer_damage, 0, 0, 40, 30);surface->buffer = new_client();@@ -90,9 +91,11 @@ int main(void) {assert(preview->buffer == &a.buffer->base);assert(preview->wait_timeline == &acquire_a && preview->wait_point == 11);assert(a.buffer->private.n_ignore_locks == 1 && acquire_a.private.n_refs == 1);+ assert(rediwm_switcher_preview_get_surface(preview) == &a);+ // A commit is followed without the caller: the binding listens for it.a.current.seq++;state_a.acquire_point = 12;- assert(rediwm_switcher_preview_set_surface(preview, &a));+ wl_signal_emit_mutable(&a.events.commit, &a);assert(a.buffer->private.n_ignore_locks == 1 && acquire_a.private.n_refs == 1);assert(preview->wait_point == 12);struct wl_event_loop *loop = wl_event_loop_create();@@ -108,19 +111,20 @@ int main(void) {assert(rediwm_switcher_preview_set_surface(preview, &b));assert(a.buffer->private.n_ignore_locks == 0 && b.buffer->private.n_ignore_locks == 1);assert(acquire_a.private.n_refs == 0 && acquire_b.private.n_refs == 1);- assert(wl_list_empty(&a.events.destroy.listener_list));+ assert(wl_list_empty(&a.events.destroy.listener_list) && wl_list_empty(&a.events.commit.listener_list));wl_signal_emit_mutable(&preview->events.output_sample, &sample);assert(released == 2 && last_state == &state_b);// Source-first teardown clears content but leaves the preview safe to reuse.wl_signal_emit_mutable(&b.events.destroy, NULL);assert(!preview->buffer && !preview->wait_timeline && b.buffer->private.n_ignore_locks == 0);- assert(wl_list_empty(&b.events.destroy.listener_list));+ assert(wl_list_empty(&b.events.destroy.listener_list) && wl_list_empty(&b.events.commit.listener_list));+ assert(!rediwm_switcher_preview_get_surface(preview));wl_signal_emit_mutable(&preview->events.output_sample, &sample);assert(released == 2);assert(rediwm_switcher_preview_set_surface(preview, &a));// Node-first teardown must detach the source listener before freeing the node.rediwm_node_destroy(&preview->node);- assert(wl_list_empty(&a.events.destroy.listener_list));+ assert(wl_list_empty(&a.events.destroy.listener_list) && wl_list_empty(&a.events.commit.listener_list));assert(a.buffer->private.n_ignore_locks == 0 && acquire_a.private.n_refs == 0);wl_signal_emit_mutable(&a.events.destroy, NULL);wlr_buffer_unlock(&a.buffer->base);diff --git a/tests/switcher.py b/tests/switcher.pyindex e2fa229..0b99dc0 100644--- a/tests/switcher.py+++ b/tests/switcher.py@@ -365,9 +365,95 @@ def run_pagination(scale):log.close()+def run_content_and_pointer(scale, style):+ """A window's subsurfaces are part of its thumbnail (browsers of the Firefox+ family and video players draw their content into one), and the switcher+ owns the pointer: a cursor the client under it had hidden shows again."""+ with tempfile.TemporaryDirectory(prefix='rediwm-switcher-content-') as directory:+ tmp = Path(directory)+ build_client(tmp)+ wallpaper = tmp / 'wallpaper.png'+ Image.new('RGB', (32, 32), (20, 24, 30)).save(wallpaper)+ proc, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get('REDIWM_TEST_RENDERER', 'gles2'), config_content=f'[compositor]\nwallpaper = "{wallpaper}"\nswitcher_style = "{style}"\n')+ clients = []+ try:+ with IPCClient(tmp) as ipc:+ ipc.wait_for('wallpaper_presented', timeout_ms=10000)+ display = next(p.name for p in tmp.glob('wayland-*') if not p.name.endswith('.lock'))+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display)+ # "Hider" hides the cursor whenever the pointer enters it, like+ # a terminal after a key press or a player during playback.+ for i, (title, extra) in enumerate((('Plain', {}), ('Hider', {'REDIWM_TEST_HIDE_CURSOR': '1'}))):+ clients.append(subprocess.Popen([str(tmp / 'client'), '--title', title, '--app-id', f'org.rediwm.switcher.{title.lower()}'],+ env=dict(env, **extra), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))+ wait_for(lambda: len(ipc.get_windows()) == i + 1, 'map content fixture')+ ids = {w['title']: w['id'] for w in ipc.get_windows()}+ for wid in ids.values(): ipc.wait_for('window_geometry_settled', window_id=wid, timeout_ms=5000)++ def pointer():+ state = ipc.get_input_state()+ return state['cursor_source'], state['pointer_focused_window_id']++ ipc.action('focus_window', {'id': ids['Hider']})+ box = ipc.get_window_debug(ids['Hider'])['client_box']+ # Away from the green child surface, on the window's own.+ ipc.move_cursor(box['x'] + 300, box['y'] + 200)+ wait_for(lambda: pointer() == ('hidden', ids['Hider']), 'the fixture hides its cursor')+ ipc.key(56, True)+ ipc.key_down_up(15)+ assert pointer() == ('default', None), ('the switcher left the pointer with the client', pointer())+ ipc.move_cursor(box['x'] + 310, box['y'] + 210)+ assert pointer() == ('default', None), ('motion over the switcher lost the arrow', pointer())+ ipc.key_down_up(1) # Escape keeps focus where it was+ ipc.key(56, False)+ # Without any motion the pointer is back in the window under it.+ wait_for(lambda: pointer() == ('hidden', ids['Hider']), 'closing the switcher returns the pointer')+ # Accepting hands it to whatever is under the pointer afterwards.+ ipc.key(56, True)+ ipc.key_down_up(15)+ ipc.key(56, False)+ wait_for(lambda: ipc.get_focused_window()['id'] == ids['Plain'], 'switch to the other window')+ wait_for(lambda: pointer()[1] is not None, 'accepting returns the pointer')++ # Nothing but the switcher can show the fixture's green child+ # surface once both windows are minimized.+ def green():+ path = tmp / 'content.png'+ path.unlink(missing_ok=True)+ ipc.screenshot(path=str(path))+ wait_for(path.exists, 'capture')+ image = Image.open(path).convert('RGB')+ if dest := os.environ.get('REDIWM_SWITCHER_PREVIEW'):+ Path(dest).mkdir(parents=True, exist_ok=True)+ image.save(Path(dest) / f'{style}-content-{scale}.png')+ return sum(g > 200 and r < 60 and b < 60 for r, g, b in image.getdata())+ for wid in ids.values(): ipc.minimize(wid)+ time.sleep(.5)+ assert green() == 0, 'a minimized fixture is still on screen'+ ipc.key(29, True)+ ipc.key_down_up(15)+ time.sleep(.6)+ shown = green()+ ipc.key_down_up(1)+ ipc.key(29, False)+ # Two thumbnails, each with the 60x40 child of a 400x260 window.+ assert shown > 60 * float(scale) ** 2, ('subsurfaces missing from the thumbnails', shown)+ assert proc.poll() is None+ print(f'PASS switcher subsurface content and pointer style={style} scale={scale}')+ except Exception:+ print((tmp / 'compositor.log').read_text()[-6000:])+ raise+ finally:+ for client in clients: stop_process(client)+ stop_process(proc)+ log.close()++if __name__ == '__main__':for style in ('linear', 'circular'):for modifier in (56, 29):for scale in ('1', '1.5'): run(scale, modifier, style)for scale in ('1', '1.5'): run_pagination(scale)for scale in ('1', '1.5'): run_group_cycle(scale)+ for style in ('linear', 'circular'):+ for scale in ('1', '1.5'): run_content_and_pointer(scale, style)