Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

circular window switcher

oxydizer0d13e56a06c0
diff --git a/build/support.zig b/build/support.zig
index 40206fc..56b9449 100644
--- a/build/support.zig
+++ b/build/support.zig
@@ -94,6 +94,7 @@ pub fn addGlass(b: *std.Build, module: *std.Build.Module, damage_audit: bool) vo
module.addCSourceFile(.{ .file = b.path("src/scene_damage.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
module.addCSourceFile(.{ .file = b.path("src/glass.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra" } });
module.addCSourceFile(.{ .file = b.path("src/explicit_sync.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ module.addCSourceFile(.{ .file = b.path("src/switcher_preview.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
module.addCSourceFile(.{ .file = b.path("src/extra_protocols.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
}
diff --git a/build/tests.zig b/build/tests.zig
index 2e6afe6..d216e57 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -399,6 +399,18 @@ pub fn addC(ctx: Context, test_step: *std.Build.Step) void {
test_step.dependOn(&run_node_tests.step);
b.step("test-node", "Test the compositor's own scene nodes").dependOn(&run_node_tests.step);
+ const switcher_preview_tests = b.addExecutable(.{
+ .name = "switcher-preview-tests",
+ .root_module = b.createModule(.{ .target = target, .optimize = .debug, .link_libc = true }),
+ });
+ switcher_preview_tests.root_module.addCSourceFiles(.{ .files = &.{ "src/switcher_preview_test.c", "src/switcher_preview.c", "src/node.c" }, .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ inline for (.{ "wlroots-0.20", "wayland-server", "pixman-1" }) |lib| {
+ switcher_preview_tests.root_module.linkSystemLibrary(lib, .{});
+ }
+ const run_switcher_preview_tests = b.addRunArtifact(switcher_preview_tests);
+ test_step.dependOn(&run_switcher_preview_tests.step);
+ b.step("test-switcher-preview", "Test switcher preview fences and buffer lifetime").dependOn(&run_switcher_preview_tests.step);
+
const projection_tests = b.addExecutable(.{
.name = "projection-tests",
.root_module = b.createModule(.{ .target = target, .optimize = .debug, .link_libc = true }),
diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.md
index ab9011c..85ca521 100644
--- a/docs/agent-notes/rendering.md
+++ b/docs/agent-notes/rendering.md
@@ -30,6 +30,16 @@ chrome, capture, or retained panel painting. General rules remain in
`shaped_poly[_external]`, `rediwm_scene_renderer_enable_polygons`), built on the
first `chrome.polygonsReady()` from layout code (never inside a pass); a polygon
draw before that fails the pass, so draw and capture code reads `chrome.polygons`.
+ Circular switcher clips use an analytic annular `sector` instead of polygon
+ vertices (`scene_sector.h`/`.zig`): CPU picking and GPU coverage share its exact
+ distance function. The same optional programs render sectors; scale radii
+ uniformly and transform the center/axis with the output, so fractional snapping
+ never stretches a circle. Sector clips claim no opaque rectangular core.
+ A positive `sector_texture_height` opts a preview into radial texture mapping:
+ the source's top follows the outer arc, and its full height extends inward.
+ Changing that height damages the whole sector. Ordinary shapes keep rectangular
+ sampling; the radial path removes the output transform from source UVs because
+ the sector axis already carries it.
The taskbar uses the same clip on its tree (`Taskbar.applyClip`) with its raster
outer edge left hard (`taskbar/shape.zig` `paintPolygon`: row spans, a distance
only near an edge).
diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md
index 69c2670..20e37f1 100644
--- a/docs/wiki/Configuration.md
+++ b/docs/wiki/Configuration.md
@@ -169,7 +169,9 @@ time and date (`clock_bold` and `clock_italic` in `[theme]`, or
| `drag_feedback` | `true` | softly lift a window during a move drag; suppressed by reduced motion |
| `drag_scale` | `1.002` | drag lift multiplier, `1.000`–`1.100`; adjustable in Appearance |
| `files_single_click_open` | `true` | Files opens files and folders with one click on their icon in list or icons view |
+| `switcher_style` | `"linear"` | `linear` keeps the horizontal Alt+Tab strip; `circular` arranges app previews around a circle and stacks windows from the same app |
| `switcher_opacity`, `inactive_opacity` | `1.0` | |
+| `switcher_circle_bg` | `false` | `circular` style only: paint a disc behind the switcher, coloured by the window chrome's own opacity (`chrome_opacity`) and darkness (`chrome_darkness`) settings |
| `terminal_opacity` | unset | 0.0 to 1.0, background alpha of terminals RediWM launches: Foot, kitty, Alacritty, Ghostty and WezTerm (new windows only; text stays opaque). Konsole, GNOME Terminal and other VTE terminals take it only from their own profiles. Unset keeps the opacity of your own terminal configuration. Adjustable in Appearance |
| `inactive_dim` | `true` | windows that are not the focus lose a little brightness and colour; fullscreen windows never dim. Settings, Appearance has the switch |
| `inactive_dim_amount` | `0.08` | 0.0 to 0.5, the fraction of brightness and of colour an unfocused window loses |
diff --git a/docs/wiki/Using-RediWM.md b/docs/wiki/Using-RediWM.md
index f6197d2..f49356d 100644
--- a/docs/wiki/Using-RediWM.md
+++ b/docs/wiki/Using-RediWM.md
@@ -40,6 +40,29 @@ The mini map shows where you are and hides itself after a moment.
The volume/brightness OSD also shows the desktop zoom percentage.
+## Window switcher
+
+Alt+Tab cycles windows; Alt+Shift+Tab cycles backwards. Release Alt to focus
+the selected window, or press Escape to cancel.
+
+Choose **Settings → Appearance → Motion & feedback → Window switcher → Circular**,
+or set this in your configuration:
+
+```toml
+[compositor]
+switcher_style = "circular"
+```
+
+Windows from the same app share a stack around the circle, with a badge in the
+centre showing how many; stepping onto that app's stack fans it open. The
+selected window's title appears in the centre. Previews fan around the hub
+with their top edge at the outer rim; tall windows are cropped at the bottom.
+Up to three cards per app and eight apps per page are visible. Tab exhausts a
+stack's own windows, most recently used first, before moving to the next app;
+Shift+Tab mirrors that. Small outputs and renderers without polygon support
+use the horizontal strip. Set `switcher_style = "linear"` to use the default
+horizontal strip.
+
## Window switching zoom
Settings > Appearance, or `[compositor] focus_zoom`. Controls what Alt+Tab,
diff --git a/po/rediwm.pot b/po/rediwm.pot
index b010fbf..35dc202 100644
--- a/po/rediwm.pot
+++ b/po/rediwm.pot
@@ -1179,6 +1179,10 @@ msgstr ""
msgid "Choose your window layout"
msgstr ""
+#: src/control_center/sections/appearance_rows.zig
+msgid "Circular"
+msgstr ""
+
#: src/control_center/welcome.zig
msgid "Classic (stacking)"
msgstr ""
@@ -3287,6 +3291,10 @@ msgstr ""
msgid "Line {line}, Column {column} · UTF-8{bom} · {ending}"
msgstr ""
+#: src/control_center/sections/appearance_rows.zig
+msgid "Linear"
+msgstr ""
+
#: src/files/app_listing.zig
msgid "Link"
msgstr ""
@@ -6923,6 +6931,10 @@ msgstr ""
msgid "Window spacing"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "Window switcher"
+msgstr ""
+
#: src/control_center/sections/appearance_rows.zig
msgid "Window switching zoom"
msgstr ""
@@ -7083,6 +7095,10 @@ msgstr ""
msgid "accessibility animations"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "alt tab linear circular applications"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "application colours theme"
msgstr ""
diff --git a/src/Switcher.zig b/src/Switcher.zig
index 4c193ab..182f8e3 100644
--- a/src/Switcher.zig
+++ b/src/Switcher.zig
@@ -1,4 +1,4 @@
-//! Held-modifier window carousel. IDs freeze MRU order for the duration of a
+//! Held-modifier window switcher. IDs freeze MRU order for the duration of a
//! gesture; scene buffers retain preview storage independently of clients.
const std = @import("std");
const wlr = @import("wlroots");
@@ -12,22 +12,30 @@ const Anim = anim.Anim;
const gpa = @import("main.zig").gpa;
const Self = @This();
const theme = @import("ui").theme;
+const circular = @import("switcher/circular.zig");
+const preview_binding = @import("switcher/preview.zig");
const card_w = 224;
const card_h = 220;
const stride = 244;
const height = 284;
-const Card = struct {
+pub const Card = struct {
id: u64,
- label: *sn.Buffer,
- label_source: wlr.FBox,
+ label: ?*sn.Buffer = null,
+ label_source: wlr.FBox = undefined,
icon: *sn.Buffer,
+ icon_buffer: *wlr.Buffer,
icon_source: wlr.FBox,
icon_ready: bool = false,
preview: ?*sn.Buffer = null,
source: wlr.FBox = undefined,
pw: i32 = 0,
ph: i32 = 0,
+ aspect: f64 = 1,
+ tree: ?*sn.Tree = null,
+ fill: ?*sn.Rect = null,
+ group: usize = 0,
+ member: usize = 0,
};
pub const Trigger = enum { alt, ctrl };
@@ -41,6 +49,8 @@ selected: usize = 0,
scroll: Anim = .{},
width: i32 = 0,
scale: f32 = 1,
+style: @import("config").types.SwitcherStyle = .linear,
+circle: circular.State = .{},
pub fn active(self: *const Self) bool {
return self.tree != null;
@@ -69,6 +79,12 @@ pub fn step(self: *Self, server: *Server, reverse: bool, trigger: Trigger) void
};
}
if (self.cards.items.len == 0) return;
+ if (self.circle.enabled) {
+ circular.advance(self, reverse);
+ circular.select(self, opening);
+ self.output.?.wlr_output.scheduleFrame();
+ return;
+ }
const n = self.cards.items.len;
self.selected = if (reverse) (self.selected + n - 1) % n else (self.selected + 1) % n;
const target: f32 = @floatFromInt(self.selected * stride);
@@ -89,9 +105,16 @@ fn open(self: *Self, server: *Server) !void {
const box = output.usableBox();
if (box.width < 260 or box.height < height) return;
self.output = output;
- self.width = @min(1500, box.width - 32);
+ self.style = server.config.compositor.switcher_style;
+ self.circle.enabled = self.style == .circular and circular.layout.diameter(box.width, box.height) >= 360 and @import("chrome.zig").polygonsReady();
+ self.width = if (self.circle.enabled) circular.layout.diameter(box.width, box.height) else @min(1500, box.width - 32);
self.scale = output.wlr_output.scale;
self.tree = try server.overlay_tree.createSceneTree();
+ if (self.circle.enabled) {
+ try circular.open(self, server);
+ if (self.cards.items.len == 0) self.cancel();
+ return;
+ }
const bg = try PanelBuffer.create(self.width, height, self.scale);
defer bg.base.drop();
var r = Renderer.init(bg.pixels, bg.width, bg.height, self.scale);
@@ -114,7 +137,7 @@ 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_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) } };
+ 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;
@@ -136,7 +159,7 @@ fn open(self: *Self, server: *Server) !void {
_ = self.tick(output, @import("Taskbar.zig").nowMs());
}
-fn makeNode(self: *Self, buffer: *wlr.Buffer, w: i32, h: i32) !*sn.Buffer {
+pub fn makeNode(self: *Self, buffer: *wlr.Buffer, w: i32, h: i32) !*sn.Buffer {
// Keep storage alive for the entire gesture, including CPU buffers whose
// scene node releases its reference after the GLES2 texture upload.
try self.buffers.append(gpa, buffer);
@@ -166,7 +189,8 @@ fn place(node: *sn.Buffer, source: wlr.FBox, x: i32, y: i32, w: i32, h: i32, vie
pub fn tick(self: *Self, output: *Output, now: i64) bool {
if (!self.active() or self.output != output) return false;
const box = output.usableBox();
- if (output.server.locker != null or !output.isLogicallyEnabled() or output.idle_blanked or self.scale != output.wlr_output.scale or self.width != @min(1500, box.width - 32) or box.height < height) {
+ 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();
return false;
}
@@ -177,32 +201,15 @@ pub fn tick(self: *Self, output: *Output, now: i64) bool {
return false;
}
}
+ if (self.circle.enabled) return circular.tick(self, output, now);
self.background.?.setOpacity(output.server.config.compositor.switcher_opacity);
self.tree.?.node.setPosition(box.x + @divTrunc(box.width - self.width, 2), box.y + @divTrunc(box.height - height, 2));
const offset: i32 = @intFromFloat(@round(self.scroll.value(now)));
for (self.cards.items, 0..) |*card, i| {
- if (!card.icon_ready) if (output.server.findToplevelById(card.id)) |tl| {
- switch (output.server.iconLookup(tl.appId(), @intFromFloat(card.icon_source.width))) {
- .ready => |entry| {
- if (PanelBuffer.create(40, 40, self.scale)) |image| {
- defer image.base.drop();
- var r = Renderer.init(image.pixels, image.width, image.height, self.scale);
- r.fillRect(0, 0, 40, 40, .{ .color = theme.global.switcher_icon_bg, .radius = theme.global.switcher_icon_radius });
- const widget: @import("ui").layout.Widget = .{ .kind = .{ .image = .{ .pixels = entry.pixels, .width = entry.size, .height = entry.size } }, .computed_x = 3, .computed_y = 3, .computed_width = 34, .computed_height = 34 };
- @import("ui").paint.paint(&widget, &r);
- self.buffers.append(gpa, &image.base) catch continue;
- _ = image.base.lock();
- card.icon.setBuffer(&image.base);
- card.icon_ready = true;
- } else |_| {}
- },
- .missing => card.icon_ready = true,
- .pending => {},
- }
- };
+ refreshIcon(self, card);
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.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);
}
@@ -210,25 +217,50 @@ pub fn tick(self: *Self, output: *Output, now: i64) bool {
return !self.scroll.settled(now);
}
+pub fn refreshIcon(self: *Self, card: *Card) void {
+ const output = self.output orelse return;
+ if (!card.icon_ready) if (output.server.findToplevelById(card.id)) |tl| {
+ switch (output.server.iconLookup(tl.appId(), @intFromFloat(card.icon_source.width))) {
+ .ready => |entry| {
+ if (PanelBuffer.create(40, 40, self.scale)) |image| {
+ defer image.base.drop();
+ var r = Renderer.init(image.pixels, image.width, image.height, self.scale);
+ r.fillRect(0, 0, 40, 40, .{ .color = theme.global.switcher_icon_bg, .radius = theme.global.switcher_icon_radius });
+ const widget: @import("ui").layout.Widget = .{ .kind = .{ .image = .{ .pixels = entry.pixels, .width = entry.size, .height = entry.size } }, .computed_x = 3, .computed_y = 3, .computed_width = 34, .computed_height = 34 };
+ @import("ui").paint.paint(&widget, &r);
+ self.buffers.append(gpa, &image.base) catch return;
+ _ = image.base.lock();
+ card.icon.setBuffer(&image.base);
+ card.icon_buffer = &image.base;
+ card.icon_ready = true;
+ } else |_| {}
+ },
+ .missing => card.icon_ready = true,
+ .pending => {},
+ }
+ };
+}
+
// 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.
-fn updatePreview(card: *Card, tl: *@import("Toplevel.zig")) void {
+pub fn updatePreview(card: *Card, tl: *@import("Toplevel.zig")) void {
const preview = card.preview orelse return;
card.pw = 0;
if (tl.surface()) |surface| {
- if (surface.current.transform == .normal) if (surface.buffer) |buffer| {
+ if (surface.current.transform == .normal and surface.buffer != null) {
+ if (!preview_binding.setSurface(preview, surface)) return;
surface.getBufferSourceBox(&card.source);
const sw: f32 = @floatFromInt(@max(1, surface.current.width));
const sh: f32 = @floatFromInt(@max(1, surface.current.height));
+ card.aspect = sw / sh;
const fit = @min(208 / sw, 140 / sh);
card.pw = @max(1, @as(i32, @intFromFloat(@round(sw * fit))));
card.ph = @max(1, @as(i32, @intFromFloat(@round(sh * fit))));
- preview.setBuffer(&buffer.base);
return;
- };
+ }
}
- preview.setBuffer(null);
+ _ = preview_binding.setSurface(preview, null);
preview.node.setEnabled(false);
}
@@ -249,7 +281,7 @@ pub fn frameDone(self: *Self, output: *Output, when: *const std.posix.timespec)
// 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.enabled) 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);
}
@@ -268,12 +300,13 @@ pub fn accept(self: *Self, server: *Server) void {
pub fn cancel(self: *Self) void {
if (self.tree) |tree| tree.node.destroy();
+ self.circle.deinit();
for (self.buffers.items) |buffer| buffer.unlock();
self.buffers.deinit(gpa);
self.cards.deinit(gpa);
self.* = .{};
}
-fn ignoreInput(_: *sn.Buffer, _: *f64, _: *f64) callconv(.c) bool {
+pub fn ignoreInput(_: *sn.Buffer, _: *f64, _: *f64) callconv(.c) bool {
return false;
}
diff --git a/src/capture/window_source.zig b/src/capture/window_source.zig
index 80633d2..b82c649 100644
--- a/src/capture/window_source.zig
+++ b/src/capture/window_source.zig
@@ -48,6 +48,10 @@ const PassShape = extern struct {
radii: [4]f32,
poly_count: c_int = 0,
poly: [16][2]f32 = @splat(.{ 0, 0 }),
+ sector: @import("../scene_sector.zig").Device = .{},
+ sector_texture_height: f32 = 0,
+ sector_texture_flip: f32 = 0,
+ sector_texture_transform: c_int = 0,
border: f32 = 0,
border_color: [4]f32 = @splat(0),
glow_center: [2]f32 = .{ 0, 0 },
diff --git a/src/config/default.zig b/src/config/default.zig
index 6133f74..3b09c92 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -173,7 +173,9 @@ pub const source =
\\drag_scale = 1.002 # drag lift multiplier, 1.000-1.100
\\dodge_file_drags = true # a file manager slides aside while you drag a file out of it
\\files_single_click_open = true # Files: one click on an icon opens the file or folder
+ \\switcher_style = "linear" # linear or circular; circular stacks windows from the same app
\\switcher_opacity = 1.0 # 0.0-1.0, background only; previews stay opaque
+ \\switcher_circle_bg = false # circular style only: paint a disc behind it, using window chrome's opacity/darkness
\\inactive_opacity = 1.0 # 0.0-1.0, 1.0 = no change
\\# terminal_opacity = 0.9 # 0.0-1.0 terminal background (Foot, kitty, Alacritty, Ghostty, WezTerm); new windows only. Unset keeps their own
\\inactive_dim = true # windows that are not the focus lose a little brightness and colour
diff --git a/src/config/loader.zig b/src/config/loader.zig
index be9ce1c..44cecdf 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -239,7 +239,12 @@ pub const CompositorConfig = struct {
/// brightness and of its colour (`Toplevel.applyDim`).
inactive_dim: bool = true,
inactive_dim_amount: f32 = 0.08,
+ /// Alt+Tab layout; circular stacks windows belonging to the same app.
+ switcher_style: types.SwitcherStyle = .linear,
switcher_opacity: f32 = 1.0,
+ /// Circular style only: paint a disc behind it, coloured by the window
+ /// chrome's own opacity and darkness settings.
+ switcher_circle_bg: bool = false,
border_radius: u32 = 10,
allow_tearing: bool = false,
/// Start frames as late as the display allows instead of right after
diff --git a/src/config/loader_fields.zig b/src/config/loader_fields.zig
index 5664dca..69ebf44 100644
--- a/src/config/loader_fields.zig
+++ b/src/config/loader_fields.zig
@@ -152,7 +152,9 @@ pub const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(Composi
.terminal_opacity = .{ .float = .{ .min = 0, .max = 1 } },
.inactive_dim = .boolean,
.inactive_dim_amount = .{ .float = .{ .min = 0, .max = 0.5 } },
+ .switcher_style = .enumeration,
.switcher_opacity = .{ .float = .{ .min = 0, .max = 1 } },
+ .switcher_circle_bg = .boolean,
.border_radius = .{ .uint = .{ .min = 0, .max = 128 } },
.allow_tearing = .boolean,
.late_render = .boolean,
diff --git a/src/config/loader_fields_tests.zig b/src/config/loader_fields_tests.zig
index 49f8da8..7359ec9 100644
--- a/src/config/loader_fields_tests.zig
+++ b/src/config/loader_fields_tests.zig
@@ -193,6 +193,18 @@ test "config field parsing preserves ranges and derived zoom state" {
try applyCompositorKey(&c, a, "unknown", "ignored");
}
+test "switcher style defaults to linear and accepts only supported layouts" {
+ var defaults = try parse(std.testing.allocator, "", "mem");
+ defer defaults.deinit();
+ try std.testing.expectEqual(types.SwitcherStyle.linear, defaults.compositor.switcher_style);
+ inline for (.{ "linear", "circular" }) |style| {
+ var cfg = try parse(std.testing.allocator, "[compositor]\nswitcher_style = \"" ++ style ++ "\"\n", "mem");
+ defer cfg.deinit();
+ try std.testing.expectEqualStrings(style, @tagName(cfg.compositor.switcher_style));
+ }
+ try std.testing.expectError(error.InvalidValue, applyCompositorKey(&defaults.compositor, std.testing.allocator, "switcher_style", "\"unknown\""));
+}
+
test "idle field rules preserve optional enabled and strict unknown keys" {
const a = std.testing.allocator;
var idle = IdleConfig{};
diff --git a/src/config/types.zig b/src/config/types.zig
index 86a10f7..305a22f 100644
--- a/src/config/types.zig
+++ b/src/config/types.zig
@@ -96,6 +96,7 @@ pub const AccelCurve = struct {
};
pub const FocusZoom = enum { keep, boost, camera };
+pub const SwitcherStyle = enum { linear, circular };
pub const MiniMapPosition = enum { bottom_right, bottom_center, bottom_left };
diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zig
index f773a05..a711f7c 100644
--- a/src/control_center/search_index.zig
+++ b/src/control_center/search_index.zig
@@ -84,6 +84,7 @@ const source_entries = [_]SourceEntry{
.{ .page = .appearance, .title = i18n.msg("Animation speed"), .target = "anim_speed", .keywords = i18n.msg("motion duration") },
.{ .page = .appearance, .title = i18n.msg("Reduced motion"), .target = "reduced_motion", .keywords = i18n.msg("accessibility animations") },
.{ .page = .appearance, .title = i18n.msg("Focus zoom"), .target = "focus_zoom", .keywords = i18n.msg("window focus") },
+ .{ .page = .appearance, .title = i18n.msg("Window switcher"), .target = "switcher_style", .keywords = i18n.msg("alt tab linear circular applications") },
.{ .page = .appearance, .title = i18n.msg("Drag feedback"), .target = "drag_feedback", .keywords = i18n.msg("window moving") },
.{ .page = .appearance, .title = i18n.msg("Drag scale"), .target = "drag_scale", .keywords = i18n.msg("window moving size") },
.{ .page = .appearance, .title = i18n.msg("Font"), .target = "font", .keywords = i18n.msg("typeface text") },
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index 1e17d04..2c2a16b 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -100,6 +100,7 @@ pub const onWindowGapChanged = appearance_chrome.onWindowGapChanged;
pub const onTaskbarPositionChanged = appearance_chrome.onTaskbarPositionChanged;
pub const onTaskbarAlignmentChanged = appearance_chrome.onTaskbarAlignmentChanged;
pub const onFocusZoomChanged = appearance_chrome.onFocusZoomChanged;
+pub const onSwitcherStyleChanged = appearance_chrome.onSwitcherStyleChanged;
pub const onDragFeedbackChanged = appearance_chrome.onDragFeedbackChanged;
pub const onDragScaleChanged = appearance_chrome.onDragScaleChanged;
pub const onAnimationsEnabledChanged = appearance_chrome.onAnimationsEnabledChanged;
@@ -225,6 +226,7 @@ pub const Section = struct {
dock_trash_children: [2]Widget = undefined,
dock_group_children: [10]Widget = undefined,
focus_zoom_children: [3]Widget = undefined,
+ switcher_style_children: [2]Widget = undefined,
drag_feedback_children: [2]Widget = undefined,
drag_scale_header_children: [2]Widget = undefined,
drag_scale_children: [2]Widget = undefined,
@@ -509,6 +511,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.anim_speed_row_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.reduced_motion_row_children },
.{ .kind = .container, .direction = .column, .gap = 8, .children = &out.focus_zoom_children },
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.switcher_style_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.drag_feedback_children },
.{ .kind = .container, .direction = .column, .gap = 8, .children = &out.drag_scale_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.cursor_row_children },
@@ -581,6 +584,7 @@ pub const Row = enum {
animation_speed,
reduced_motion,
focus_zoom,
+ switcher_style,
drag_feedback,
drag_scale,
cursor,
@@ -607,7 +611,7 @@ pub const groups = [_]struct { title: ?i18n.Message, rows: []const Row }{
.{ .title = i18n.msg("Wallpaper"), .rows = &.{.wallpaper} },
.{ .title = i18n.msg("Fonts & cursor"), .rows = &.{ .font_family, .font_size, .cursor } },
.{ .title = i18n.msg("Windows"), .rows = &.{ .radius, .shadow, .edge_glow, .chrome_opacity, .window_tabs, .inactive_dim, .inactive_opacity, .terminal_opacity, .window_gap, .scrollbar_width } },
- .{ .title = i18n.msg("Motion & feedback"), .rows = &.{ .animations, .animation_speed, .reduced_motion, .focus_zoom, .drag_feedback, .drag_scale, .dodge_file_drags, .launch_splash } },
+ .{ .title = i18n.msg("Motion & feedback"), .rows = &.{ .animations, .animation_speed, .reduced_motion, .focus_zoom, .switcher_style, .drag_feedback, .drag_scale, .dodge_file_drags, .launch_splash } },
.{ .title = null, .rows = &.{.dock} },
.{ .title = null, .rows = &.{.taskbar} },
.{ .title = null, .rows = &.{.start_menu} },
diff --git a/src/control_center/sections/appearance_chrome.zig b/src/control_center/sections/appearance_chrome.zig
index 3647eaa..252ed81 100644
--- a/src/control_center/sections/appearance_chrome.zig
+++ b/src/control_center/sections/appearance_chrome.zig
@@ -214,6 +214,21 @@ pub fn onFocusZoomChanged(owner: ?*anyopaque, _: usize, index: usize) void {
s.focus_zoom_children[2].markDirty();
}
+pub fn onSwitcherStyleChanged(owner: ?*anyopaque, _: usize, index: usize) void {
+ if (index > 1) return;
+ const s = section(owner);
+ const server = s.cc.server;
+ const style: @TypeOf(server.config.compositor.switcher_style) = @enumFromInt(index);
+ if (style == server.config.compositor.switcher_style) return;
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "switcher_style", style) catch |err| {
+ std.log.warn("could not save switcher style: {}", .{err});
+ s.switcher_style_children[1].kind.segmented.selected = @intFromEnum(server.config.compositor.switcher_style);
+ s.switcher_style_children[1].markDirty();
+ return;
+ };
+ server.config.compositor.switcher_style = style;
+}
+
pub fn onDragFeedbackChanged(owner: ?*anyopaque, _: usize, on: bool) void {
const server = section(owner).cc.server;
setting_save.saveCompositor(main.gpa, server.io, server.config.path, "drag_feedback", on) catch |err| {
diff --git a/src/control_center/sections/appearance_rows.zig b/src/control_center/sections/appearance_rows.zig
index a8bad4d..7cc9bbe 100644
--- a/src/control_center/sections/appearance_rows.zig
+++ b/src/control_center/sections/appearance_rows.zig
@@ -212,6 +212,15 @@ pub fn buildBehaviorRows(out: *Section, pal: theme.Theme) void {
.{ .kind = .{ .text = .{ .content = focus_zoom_descriptions[@intFromEnum(focus_zoom)].get(), .font_size = theme.global.settings_description_size, .color = pal.dim } } },
};
+ out.switcher_style_children = .{
+ labelWidget(i18n.tr("Window switcher")),
+ .{
+ .name = "switcher_style",
+ .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&.{ i18n.msg("Linear"), i18n.msg("Circular") }), .selected = @intFromEnum(out.cc.server.config.compositor.switcher_style), .owner = out, .on_change = &appearance_chrome.onSwitcherStyleChanged } },
+ .width = .{ .fixed = segmented_width },
+ },
+ };
+
out.drag_feedback_children = .{
labelWidget(i18n.tr("Drag feedback")),
.{ .name = "drag_feedback", .kind = .{ .toggle = .{ .on = out.cc.server.config.compositor.drag_feedback, .owner = out, .on_change = &onDragFeedbackChanged } } },
diff --git a/src/projection.zig b/src/projection.zig
index 95f3d45..977edbe 100644
--- a/src/projection.zig
+++ b/src/projection.zig
@@ -81,6 +81,11 @@ pub const ClipSpec = extern struct {
glow_depth: f64 = 0,
glow_color: [4]f32 = .{ 0, 0, 0, 0 },
poly: [poly_max][2]f64 = @splat(.{ 0, 0 }),
+ /// An analytic annular sector instead of a polygon or rounded rectangle.
+ sector: @import("scene_sector.zig").Spec = .{},
+ /// Positive: map texture width around the outer arc, with this full source
+ /// height extending inward. Zero keeps ordinary rectangular sampling.
+ sector_texture_height: f64 = 0,
};
extern fn rediwm_projection_set_tree_clip(target: *node.Node, spec: ?*const ClipSpec) bool;
/// A null spec removes the clip. False for a size that is not positive or a
diff --git a/src/projection_present.c b/src/projection_present.c
index 4adee41..8178040 100644
--- a/src/projection_present.c
+++ b/src/projection_present.c
@@ -48,19 +48,20 @@ static struct rediwm_snap map_damage(const struct rediwm_item *item, const pixma
}
// What a commit's or a replaced buffer's damage changed: the event covers the
// bounding box of the buffer-local damage, the screen only the pieces of it (up to
-// a few). The whole box without damage, or under a transform (conservative, like
-// glass.c was).
+// a few). The whole box without damage, under a transform, or for polar sampling
+// whose source rectangles do not map to axis-aligned screen rectangles.
static void damage_event_for_buffer(struct leaf *l, const pixman_region32_t *damage,
int buffer_width, int buffer_height,
struct rediwm_snap snap) {
const struct rediwm_item *item = &l->item;
+ if (damage && !pixman_region32_not_empty((pixman_region32_t *)damage)) return;
if (!damage || item->content.transform != WL_OUTPUT_TRANSFORM_NORMAL ||
- buffer_width <= 0 || buffer_height <= 0) {
+ buffer_width <= 0 || buffer_height <= 0 ||
+ (item->clip && item->clip->sector_texture_height > 0)) {
emit_snap(l, snap);
damage_box(l, snap, true);
return;
}
- if (!pixman_region32_not_empty((pixman_region32_t *)damage)) return;
struct wlr_fbox src = item->content.src_box;
if (wlr_fbox_empty(&src)) src = (struct wlr_fbox){0, 0, buffer_width, buffer_height};
const struct rediwm_snap whole =
diff --git a/src/projection_props.c b/src/projection_props.c
index 2424ebf..9c864ff 100644
--- a/src/projection_props.c
+++ b/src/projection_props.c
@@ -63,6 +63,9 @@ static bool set_tree_clip(struct wlr_addon_set *set, void **slot,
}
if (spec->width <= 0 || spec->height <= 0 || !finite_at_least_zero(spec->border)) return false;
if (!valid_polygon(spec->poly, spec->poly_count, spec->width, spec->height)) return false;
+ if (!rediwm_sector_valid(&spec->sector) || (spec->sector.radii[1] > 0 && spec->poly_count != 0)) return false;
+ if (!finite_at_least_zero(spec->sector_texture_height) ||
+ (spec->sector_texture_height > 0 && spec->sector.radii[1] <= 0)) return false;
for (int i = 0; i < 4; i++)
if (!finite_at_least_zero(spec->radii[i]) || !isfinite(spec->border_color[i]) ||
!isfinite(spec->glow_color[i]))
diff --git a/src/projection_test.c b/src/projection_test.c
index bffa03a..60705d8 100644
--- a/src/projection_test.c
+++ b/src/projection_test.c
@@ -163,6 +163,7 @@ static bool probe_item(const struct rediwm_item *item, struct rediwm_node *trans
#include "projection_test_graph.c"
#include "projection_test_damage.c"
#include "projection_test_groups.c"
+#include "projection_test_sector.c"
int main(void) {
struct wl_display *display = wl_display_create();
@@ -314,6 +315,8 @@ int main(void) {
test_clean_sync(scene);
test_clip_geometry();
test_polygon_geometry();
+ test_sector_geometry();
+ test_sector_projection(scene, out);
test_clip_opaque();
test_clip_projection(scene);
test_clip_output(scene, out);
diff --git a/src/projection_test_sector.c b/src/projection_test_sector.c
new file mode 100644
index 0000000..e52d2b7
--- /dev/null
+++ b/src/projection_test_sector.c
@@ -0,0 +1,197 @@
+// Analytic circular clips: geometry remains smooth between old polygon vertices,
+// while picks, conservative covers and damage follow the same outline as GLES.
+static struct rediwm_clip_spec sector_spec(void) {
+ return (struct rediwm_clip_spec){
+ .width = 110, .height = 110, .border = 1,
+ .sector = {.center = {55, 55}, .radii = {20, 50}, .axis = {0, -1},
+ .half_angle = {sqrt(.5), sqrt(.5)}}};
+}
+
+static void test_sector_geometry(void) {
+ const double pi = acos(-1);
+ const struct rediwm_xform id = {1, 0, 0};
+ struct rediwm_clip_spec spec = sector_spec();
+ assert(rediwm_sector_valid(&spec.sector));
+ const struct rediwm_clip clip = rediwm_clip_resolve(id, 0, 0, &spec);
+ assert(near(rediwm_clip_distance(&clip, 55, 10), -5));
+ assert(near(rediwm_clip_distance(&clip, 55, 55), 20));
+ assert(near(rediwm_clip_distance(&clip, 55, 2), 3));
+ const double edge = 40 * sqrt(.5), normal = 2 * sqrt(.5);
+ assert(near(rediwm_clip_distance(&clip, 55 + edge + normal, 55 - edge + normal), 2));
+ assert(near(rediwm_clip_distance(&clip, 55 + edge - normal, 55 - edge - normal), -2));
+ // Past a corner, distance is to the finite side's endpoint, not its infinite line.
+ assert(near(rediwm_clip_distance(&clip, 55 + 55 * sqrt(.5), 55 - 49 * sqrt(.5)), sqrt(13)));
+ struct rediwm_snap cover[3];
+ assert(rediwm_clip_opaque(&clip, cover) == 0);
+ assert(near(clip.inset, 55));
+ // Every radial sample, including between the old eight arc vertices, has the
+ // exact circular distance. Rotation does not alter that distance.
+ for (int rotation = 0; rotation < 32; rotation++) {
+ const double angle = 2 * pi * rotation / 32;
+ spec.sector.axis[0] = sin(angle);
+ spec.sector.axis[1] = -cos(angle);
+ const struct rediwm_clip rotated = rediwm_clip_resolve(id, 0, 0, &spec);
+ for (int i = -9; i <= 9; i++) {
+ const double a = angle + pi / 4 * i / 10;
+ for (int radial = 0; radial < 2; radial++) {
+ const double radius = radial ? 49.9 : 20.1;
+ assert(near(rediwm_clip_distance(&rotated, 55 + sin(a) * radius, 55 - cos(a) * radius), -.1));
+ }
+ }
+ }
+ spec = sector_spec();
+ const struct rediwm_clip moved = rediwm_clip_resolve(id, 20, -10, &spec);
+ assert(rediwm_clip_outline_equal(&clip, &moved));
+ const struct rediwm_clip scaled = rediwm_clip_resolve((struct rediwm_xform){1.5, -3, 2}, 10, 20, &spec);
+ assert(near(scaled.sector.center[0], 94.5) && near(scaled.sector.center[1], 114.5));
+ assert(near(scaled.sector.radii[0], 30) && near(scaled.sector.radii[1], 75));
+ assert(near(rediwm_clip_distance(&scaled, 94.5, 47), -7.5));
+ assert(!rediwm_clip_outline_equal(&clip, &scaled));
+ spec.sector_texture_height = 120;
+ const struct rediwm_clip mapped = rediwm_clip_resolve(id, 0, 0, &spec);
+ const struct rediwm_clip mapped_scaled = rediwm_clip_resolve((struct rediwm_xform){1.5, -3, 2}, 10, 20, &spec);
+ assert(near(mapped.sector_texture_height, 120));
+ assert(near(mapped_scaled.sector_texture_height, 180));
+ assert(near(rediwm_clip_distance(&mapped, 55, 10), rediwm_clip_distance(&clip, 55, 10)));
+ assert(!rediwm_clip_outline_equal(&clip, &mapped));
+ const struct rediwm_clip mapped_moved = rediwm_clip_resolve(id, 20, -10, &spec);
+ assert(rediwm_clip_outline_equal(&mapped, &mapped_moved));
+ spec.sector.axis[0] = 1;
+ spec.sector.axis[1] = 0;
+ const struct rediwm_clip turned = rediwm_clip_resolve(id, 0, 0, &spec);
+ assert(!rediwm_clip_outline_equal(&clip, &turned));
+}
+
+static void test_sector_buffer_damage(struct rediwm_projection *p, struct rediwm_scene_output *out,
+ struct rediwm_buffer *body) {
+ const struct leaf *leaf = leaf_of(p, &body->node);
+ uint64_t cursor = rediwm_projection_damage_cursor(p);
+ pixman_region32_t damage, visible;
+ pixman_region32_init_rect(&damage, 20, 80, 1, 1);
+ pixman_region32_init_rect(&visible, 0, 0, 110, 110);
+ rediwm_projection_note_visible(p, &body->node, &visible);
+ // This tiny source patch would map near (11,73) with rectangular sampling.
+ // Polar mapping must conservatively repaint every visible preview pixel and
+ // attribute the full box to this leaf, so retained effects see the update too.
+ rediwm_projection_damage_buffer(p, &body->node, &damage);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(layout_damaged(out, 55, 10) && layout_damaged(out, 55, 25));
+ struct events_seen seen = events_since(p, &cursor, NULL);
+ assert(seen.count == 1 && event_is(&seen.last[0], leaf->item.id, 0, 0, 110, 110));
+ clear_damage(out);
+ pixman_region32_clear(&damage);
+ rediwm_projection_damage_buffer(p, &body->node, &damage);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(!pixman_region32_not_empty(&out->damage_ring.current));
+ assert(events_since(p, &cursor, NULL).count == 0); // Empty updates remain idle.
+
+ // Output damage is still cut to what was visible; the attribution event stays
+ // whole because its consumers apply their own region/order tests.
+ pixman_region32_clear(&visible);
+ pixman_region32_union_rect(&visible, &visible, 50, 5, 10, 25);
+ rediwm_projection_note_visible(p, &body->node, &visible);
+ pixman_region32_union_rect(&damage, &damage, 20, 80, 1, 1);
+ rediwm_projection_damage_buffer(p, &body->node, &damage);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(layout_damaged(out, 55, 25) && !layout_damaged(out, 10, 10));
+ seen = events_since(p, &cursor, NULL);
+ assert(seen.count == 1 && event_is(&seen.last[0], leaf->item.id, 0, 0, 110, 110));
+ clear_damage(out);
+ pixman_region32_union_rect(&visible, &visible, 0, 0, 110, 110);
+ rediwm_projection_note_visible(p, &body->node, &visible);
+ pixman_region32_fini(&visible);
+ pixman_region32_fini(&damage);
+}
+
+static void test_sector_projection(struct rediwm_scene_outputs *scene, struct rediwm_scene_output *out) {
+ struct rig rig = rig_create(scene);
+ struct rediwm_projection *p = rediwm_projection_create(rig.own, rig.world, scene);
+ assert(p);
+ struct rediwm_tree *frame = rediwm_tree_create(rig.world);
+ struct wlr_buffer *buffer = buffer_create();
+ struct rediwm_buffer *body = rediwm_buffer_create(frame, buffer);
+ assert(frame && body);
+ rediwm_buffer_set_dest_size(body, 110, 110);
+ struct rediwm_clip_spec spec = sector_spec();
+ assert(rediwm_projection_set_tree_clip(&frame->node, &spec));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(pick(p, 55, 10, NULL, NULL) == &body->node);
+ assert(!pick(p, 55, 55, NULL, NULL)); // The hub is a hole.
+ assert(!pick(p, 5, 5, NULL, NULL)); // Cut-away bounding-box corner.
+ clear_damage(out);
+ assert(rediwm_projection_set_tree_clip(&frame->node, &spec));
+ assert(!props_changed);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(!pixman_region32_not_empty(&out->damage_ring.current));
+
+ const struct rediwm_sector bad[] = {
+ {.radii = {-1, 50}, .axis = {0, -1}, .half_angle = {sqrt(.5), sqrt(.5)}},
+ {.radii = {50, 50}, .axis = {0, -1}, .half_angle = {sqrt(.5), sqrt(.5)}},
+ {.radii = {20, 50}, .axis = {0, -2}, .half_angle = {sqrt(.5), sqrt(.5)}},
+ {.radii = {20, 50}, .axis = {0, -1}, .half_angle = {1, 0}},
+ {.radii = {20, 50}, .axis = {0, -1}, .half_angle = {-sqrt(.5), sqrt(.5)}},
+ {.radii = {20, INFINITY}, .axis = {0, -1}, .half_angle = {sqrt(.5), sqrt(.5)}},
+ {.center = {NAN, 0}}, {.radii = {0, -1}}, {.axis = {0, -1}},
+ };
+ for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
+ struct rediwm_clip_spec invalid = spec;
+ invalid.sector = bad[i];
+ assert(!rediwm_projection_set_tree_clip(&frame->node, &invalid));
+ assert(!props_changed);
+ }
+ struct rediwm_clip_spec mixed = spec;
+ mixed.poly_count = 3;
+ memcpy(mixed.poly, (double[3][2]){{0, 0}, {110, 0}, {0, 110}}, 3 * sizeof(mixed.poly[0]));
+ assert(!rediwm_projection_set_tree_clip(&frame->node, &mixed));
+ assert(pick(p, 55, 10, NULL, NULL) == &body->node); // Invalid inputs preserved the old shape.
+
+ const double bad_heights[] = {-1, INFINITY, NAN};
+ for (size_t i = 0; i < sizeof(bad_heights) / sizeof(bad_heights[0]); i++) {
+ struct rediwm_clip_spec invalid = spec;
+ invalid.sector_texture_height = bad_heights[i];
+ assert(!rediwm_projection_set_tree_clip(&frame->node, &invalid));
+ assert(!props_changed);
+ }
+ struct rediwm_clip_spec without_sector = {.width = 110, .height = 110, .sector_texture_height = 70};
+ assert(!rediwm_projection_set_tree_clip(&frame->node, &without_sector));
+ assert(!props_changed);
+
+ // Radial framing changes the content without changing the outline or source
+ // buffer. Damage must include its interior, and repeating it must stay idle.
+ spec.sector_texture_height = 70;
+ assert(rediwm_projection_set_tree_clip(&frame->node, &spec));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(damaged(out, 55, 10) && damaged(out, 55, 25));
+ clear_damage(out);
+ assert(rediwm_projection_set_tree_clip(&frame->node, &spec));
+ assert(!props_changed);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(!pixman_region32_not_empty(&out->damage_ring.current));
+ test_sector_buffer_damage(p, out, body);
+ spec.sector_texture_height = 120;
+ assert(rediwm_projection_set_tree_clip(&frame->node, &spec));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(damaged(out, 55, 25));
+ clear_damage(out);
+ spec.sector_texture_height = 0;
+ assert(rediwm_projection_set_tree_clip(&frame->node, &spec));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(damaged(out, 55, 25));
+ clear_damage(out);
+
+ // A change of angle alters the outline without moving its box. The whole
+ // sector, including its old middle, must be damaged and picks must follow.
+ spec.sector.axis[0] = 1;
+ spec.sector.axis[1] = 0;
+ assert(rediwm_projection_set_tree_clip(&frame->node, &spec));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(damaged(out, 55, 10) && damaged(out, 100, 55));
+ assert(!pick(p, 55, 10, NULL, NULL));
+ assert(pick(p, 100, 55, NULL, NULL) == &body->node);
+ assert(rediwm_projection_set_tree_clip(&frame->node, NULL));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(pick(p, 55, 55, NULL, NULL) == &body->node);
+ rediwm_projection_destroy(p);
+ rig_destroy(&rig);
+ wlr_buffer_drop(buffer);
+}
diff --git a/src/scene_graph.h b/src/scene_graph.h
index cad96f5..ccba14a 100644
--- a/src/scene_graph.h
+++ b/src/scene_graph.h
@@ -16,6 +16,7 @@
#include <wlr/render/color.h>
#include <wlr/render/pass.h>
#include <wlr/util/box.h>
+#include "scene_sector.h"
// Source space to layout space: p -> scale * p + (tx, ty). Uniform scale only;
// a window zoom, an Xwayland 1/N scale and the camera all compose into one.
@@ -97,6 +98,12 @@ struct rediwm_clip_spec {
double glow_x, glow_y, glow_radius, glow_depth;
float glow_color[4];
double poly[REDIWM_POLY_MAX][2];
+ // A positive outer radius selects a true annular sector instead of radii/poly.
+ // Its centre is relative to the tree; the whole shape must fit width/height.
+ struct rediwm_sector sector;
+ // Full source-image height in source units when mapped radially from the
+ // outer rim toward the hub. Zero keeps ordinary rectangular texture mapping.
+ double sector_texture_height;
};
struct rediwm_clip {
struct rediwm_edges edges;
@@ -112,6 +119,9 @@ struct rediwm_clip {
// In layout space, like the edges.
double glow_x, glow_y, glow_radius, glow_depth;
float glow_color[4];
+ // Centre and radii in layout space; direction and angle remain dimensionless.
+ struct rediwm_sector sector;
+ double sector_texture_height; // layout units; zero disables radial mapping
};
// Signed distance, negative inside, to a simple polygon of `n` vertices: the
// nearest edge, signed by an even-odd crossing count, so either winding works.
@@ -179,7 +189,16 @@ static inline struct rediwm_clip rediwm_clip_resolve(struct rediwm_xform t, doub
struct rediwm_clip clip = {
.edges = rediwm_xform_rect(t, x, y, spec->width, spec->height),
.border = spec->border * t.scale};
- if (spec->poly_count >= 3 && spec->poly_count <= REDIWM_POLY_MAX) {
+ if (spec->sector.radii[1] > 0) {
+ clip.sector = spec->sector;
+ clip.sector_texture_height = spec->sector_texture_height * t.scale;
+ for (int i = 0; i < 2; i++) clip.sector.radii[i] *= t.scale;
+ clip.sector.center[0] = clip.edges.x1 + spec->sector.center[0] * t.scale;
+ clip.sector.center[1] = clip.edges.y1 + spec->sector.center[1] * t.scale;
+ // A sector may have an empty centre and two radial cuts. Do not claim an
+ // axis-aligned opaque core, or spare its centre from shape-change damage.
+ clip.inset = cap * t.scale;
+ } else if (spec->poly_count >= 3 && spec->poly_count <= REDIWM_POLY_MAX) {
clip.poly_count = spec->poly_count;
for (int i = 0; i < clip.poly_count; i++) {
clip.poly[i][0] = clip.edges.x1 + spec->poly[i][0] * t.scale;
@@ -220,6 +239,7 @@ static inline double rediwm_coverage(double d) {
}
static inline double rediwm_clip_distance(const struct rediwm_clip *clip, double px,
double py) {
+ if (clip->sector.radii[1] > 0) return rediwm_sd_sector(px, py, &clip->sector);
if (clip->poly_count) return rediwm_sd_polygon(px, py, clip->poly, clip->poly_count);
return rediwm_sd_rounded_box(px, py, clip->edges.x1, clip->edges.y1,
clip->edges.x2 - clip->edges.x1,
@@ -238,6 +258,7 @@ static inline double rediwm_clip_distance(const struct rediwm_clip *clip, double
enum { REDIWM_CLIP_OPAQUE_MARGIN = 2 };
static inline int rediwm_clip_opaque(const struct rediwm_clip *clip,
struct rediwm_snap out[3]) {
+ if (clip->sector.radii[1] > 0) return 0;
const struct rediwm_snap f = rediwm_edges_snap(clip->edges);
if (f.width <= 0 || f.height <= 0) return 0;
if (clip->poly_count) {
@@ -274,6 +295,16 @@ static inline int rediwm_clip_opaque(const struct rediwm_clip *clip,
// Whether two clips are the same outline: size apart, which callers compare
// with their own tolerance in mind.
static inline bool rediwm_clip_outline_equal(const struct rediwm_clip *a, const struct rediwm_clip *b) {
+ // Mapping changes move sampled pixels throughout the sector, even when its
+ // outline stays fixed. Sector inset covers the whole box for this damage path.
+ if (a->sector_texture_height != b->sector_texture_height) return false;
+ for (int i = 0; i < 2; i++) {
+ if (a->sector.radii[i] != b->sector.radii[i] || a->sector.axis[i] != b->sector.axis[i] ||
+ a->sector.half_angle[i] != b->sector.half_angle[i]) return false;
+ }
+ if (a->sector.radii[1] > 0 &&
+ (a->sector.center[0] - a->edges.x1 != b->sector.center[0] - b->edges.x1 ||
+ a->sector.center[1] - a->edges.y1 != b->sector.center[1] - b->edges.y1)) return false;
if (a->poly_count != b->poly_count) return false;
for (int i = 0; i < 4; i++)
if (a->radii[i] != b->radii[i]) return false;
diff --git a/src/scene_output_draw.c b/src/scene_output_draw.c
index 542e5d9..b8be6c6 100644
--- a/src/scene_output_draw.c
+++ b/src/scene_output_draw.c
@@ -34,6 +34,29 @@ static void device_points(float out[][2], const double in[][2], int n, struct re
out[i][1] = (float)(ex[1] * lx + ey[1] * ly + shift[1]);
}
}
+// Circles retain one uniform scale even when the enclosing quad's snapped
+// width and height differ by a pixel. Convert their exact layout-space centre
+// and unit axis through the output transform, then anchor at the device box.
+static void device_sector(struct rediwm_pass_sector *out, const struct rediwm_sector *in,
+ const struct wlr_box *box, const struct output_view *v) {
+ *out = (struct rediwm_pass_sector){0};
+ if (in->radii[1] <= 0) return;
+ enum { W = 3, H = 5 };
+ struct wlr_box px[3], at[3] = {{0, 0, 1, 1}, {1, 0, 1, 1}, {0, 1, 1, 1}};
+ for (int i = 0; i < 3; i++) wlr_box_transform(&px[i], &at[i], wlr_output_transform_invert(v->transform), W, H);
+ const int ex[2] = {px[1].x - px[0].x, px[1].y - px[0].y};
+ const int ey[2] = {px[2].x - px[0].x, px[2].y - px[0].y};
+ const double x = (in->center[0] - v->logical.x) * v->scale;
+ const double y = (in->center[1] - v->logical.y) * v->scale;
+ const int origin[2] = {box->x, box->y};
+ for (int i = 0; i < 2; i++) {
+ const double shift = (ex[i] < 0 ? v->trans_width : 0) + (ey[i] < 0 ? v->trans_height : 0);
+ out->center[i] = (float)(ex[i] * x + ey[i] * y + shift - origin[i]);
+ out->axis[i] = (float)(ex[i] * in->axis[0] + ey[i] * in->axis[1]);
+ out->radii[i] = (float)(in->radii[i] * v->scale);
+ out->half_angle[i] = (float)in->half_angle[i];
+ }
+}
// The pass's shape for a clip: the clip's box snapped in layout space like any
// item's, then taken to device pixels by the same function as the pieces that
// tile it, so the shape and the quads agree on every pixel column. A ring is
@@ -46,6 +69,10 @@ static void shape_for(struct rediwm_pass_shape *s, const struct rediwm_clip *c,
device_radii(s->radii, radii, v->transform);
s->poly_count = c->poly_count;
if (c->poly_count) device_points(s->poly, c->poly, c->poly_count, f, &s->box, v->transform);
+ device_sector(&s->sector, &c->sector, &s->box, v);
+ 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;
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;
@@ -212,7 +239,7 @@ bool scene_output_render_entry(struct rediwm_output_renderer *r, struct entry *e
// window for what a rim of a few shaded pixels costs far less than: draws
// dominated the output build in a drag.
float depth = fmaxf(fmaxf(shape.radii[0], shape.radii[1]), fmaxf(shape.radii[2], shape.radii[3]));
- if (shape.poly_count) depth = (float)(e->item.clip->inset * v->scale);
+ if (shape.poly_count || shape.sector.radii[1] > 0) depth = (float)(e->item.clip->inset * v->scale);
const int inset = (int)ceilf(fmaxf(depth, shape.border + shape.glow_depth)) + REDIWM_CLIP_OPAQUE_MARGIN;
if (shape.box.width > 2 * inset && shape.box.height > 2 * inset)
pixman_region32_intersect_rect(&core, &core, shape.box.x + inset, shape.box.y + inset,
diff --git a/src/scene_pass.c b/src/scene_pass.c
index 772be61..09962b9 100644
--- a/src/scene_pass.c
+++ b/src/scene_pass.c
@@ -95,16 +95,29 @@ 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];" \
+ "uniform float npoly; uniform vec2 poly[17], sector_map; uniform vec4 sector_coords[2];" \
"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));" \
"bool c0=p.y>=a.y, c1=p.y<b.y, c2=e.x*w.y>e.y*w.x;" \
"if((c0&&c1&&c2)||(!c0&&!c1&&!c2)) s=-s; }" \
"return s*sqrt(d); }" \
+ /* The same uniforms carry an analytic sector when npoly is -1. Fold */ \
+ /* across its centre line: one finite radial edge covers both sides. */ \
+ "float sdsector(vec2 p){ vec2 q=p-poly[0]; float r=length(q);" \
+ "vec2 v=vec2(abs(q.x*poly[2].y-q.y*poly[2].x),dot(q,poly[2]));" \
+ "vec2 e=poly[3].yx; float t=clamp(dot(v,e),poly[1].x,poly[1].y);" \
+ "float d=length(v-e*t); bool angle=v.y>=r*poly[3].x;" \
+ "if(angle)d=min(d,min(abs(r-poly[1].x),abs(r-poly[1].y)));" \
+ "return angle&&r>=poly[1].x&&r<=poly[1].y?-d:d; }" \
+ "vec2 sector_uv(vec2 p){ vec2 q=p-poly[0]; float r=length(q);" \
+ "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); }" \
"\n#endif\n" \
"float sdf(vec2 p, vec4 r){" \
"\n#ifdef POLY\n" \
+ "if(npoly<-.5) return sdsector(p);" \
"if(npoly>.5) return sdpoly(p);" \
"\n#endif\n" \
"vec2 q=p-size*.5;" \
@@ -146,7 +159,14 @@ 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){ c=texture2D(tex,uv); if(opaque>.5)c.a=1.; c*=alpha; }"
+ "vec4 c=color; if(mode<.5){ vec2 at=uv; float content=1.;"
+ "\n#ifdef POLY\n"
+ "if(use_shape>.5&&npoly<-.5&&sector_map.x>0.){ vec2 p=sector_uv(local);"
+ "content=clamp((1.-p.y)*sector_map.x+.5,0.,1.); 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; }"
// 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; }"
@@ -231,6 +251,8 @@ static bool program_init(struct program *p, unsigned bit, const char *vertex_sou
p->radii = glGetUniformLocation(p->id, "radii");
p->npoly = glGetUniformLocation(p->id, "npoly");
p->poly = glGetUniformLocation(p->id, "poly[0]");
+ p->sector_map = glGetUniformLocation(p->id, "sector_map");
+ p->sector_coords = glGetUniformLocation(p->id, "sector_coords[0]");
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.h
index 5763dc0..38f9bc2 100644
--- a/src/scene_pass.h
+++ b/src/scene_pass.h
@@ -28,6 +28,12 @@ struct wlr_render_pass *rediwm_scene_pass_begin(struct rediwm_scene_renderer *,
// rediwm_edges_snap in scene_graph.h) and scales the radii and border; nothing
// is rounded here, so a fractional radius or border is drawn as given.
enum { REDIWM_PASS_POLY_MAX = 16 };
+struct rediwm_pass_sector {
+ float center[2]; // device pixels from the shape box's corner
+ float radii[2]; // inner, outer; outer 0 disables the sector
+ float axis[2]; // unit direction of the sector's centre line
+ float half_angle[2]; // cosine, sine of half its span (0 < span <= pi)
+};
struct rediwm_pass_shape {
struct wlr_box box;
// Top-left, top-right, bottom-right, bottom-left. A radius larger than half
@@ -38,6 +44,15 @@ struct rediwm_pass_shape {
// Simple, no two neighbouring vertices the same, either winding.
int poly_count;
float poly[REDIWM_PASS_POLY_MAX][2];
+ // A circular annular sector instead of either outline above. Its outer and
+ // inner arcs are analytic circles, so no tessellation reaches the image.
+ struct rediwm_pass_sector sector;
+ // Opt-in polar texture framing: the source top follows the outer arc and
+ // source rows advance inward. Full source height in device pixels; 0 keeps
+ // ordinary rectangular texture coordinates. Output reflection and transform
+ // 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;
// 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,
@@ -73,7 +88,7 @@ bool rediwm_scene_renderer_enable_shapes(struct rediwm_scene_renderer *);
// outside a pass, before the first such draw; later calls return the first result.
// False when it did not build. Without it an external draw fails the pass.
bool rediwm_scene_renderer_enable_external(struct rediwm_scene_renderer *);
-// Builds the programs that draw a polygon shape (`poly_count` > 0), which are the
+// Builds the programs that draw polygons or circular sectors, which are the
// shaped ones with the polygon distance compiled in: another 280 KiB or so, so only
// on request, outside a pass, before the first such draw. False when they did not
// build; a polygon draw then fails the pass, so callers must not make one.
diff --git a/src/scene_pass_draw.c b/src/scene_pass_draw.c
index 64ea6a6..bc728a1 100644
--- a/src/scene_pass_draw.c
+++ b/src/scene_pass_draw.c
@@ -52,8 +52,18 @@ void scene_pass_set_shape(const struct pass *p, const struct program *g, const s
else glUniform2f(g->origin, s->box.x, s->box.y);
glUniform2f(g->size, s->box.width, s->box.height);
glUniform4f(g->radii, s->radii[0], s->radii[1], s->radii[2], s->radii[3]);
- if (g->npoly >= 0) glUniform1f(g->npoly, (float)s->poly_count);
- if (s->poly_count && g->poly >= 0) {
+ 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->npoly >= 0) glUniform1f(g->npoly, sector ? -1.f : (float)s->poly_count);
+ if (sector && g->poly >= 0) {
+ const float payload[4][2] = {
+ {s->sector.center[0], s->sector.center[1]},
+ {s->sector.radii[0], s->sector.radii[1]},
+ {s->sector.axis[0], s->sector.axis[1]},
+ {s->sector.half_angle[0], s->sector.half_angle[1]},
+ };
+ glUniform2fv(g->poly, 4, &payload[0][0]);
+ } else if (s->poly_count && g->poly >= 0) {
// The walk closes the outline on a copy of the first vertex.
float v[REDIWM_PASS_POLY_MAX + 1][2];
memcpy(v, s->poly, sizeof(float) * 2 * s->poly_count);
@@ -128,10 +138,16 @@ static void texture_draw(struct pass *p, const struct wlr_render_texture_options
glUniform1f(program->alpha, wlr_render_texture_options_get_alpha(o));
glUniform1f(program->opaque, !a.has_alpha);
GLfloat uv[8];
+ const bool polar = shape && shape->sector_texture_height > 0;
+ // Sector coordinates already follow the output's rotation/reflection.
+ // Remove that part from the source transform before applying its UV crop.
+ const enum wl_output_transform source_transform = polar ?
+ wlr_output_transform_compose(o->transform,
+ wlr_output_transform_invert(shape->sector_texture_transform)) : o->transform;
for (int i = 0; i < 4; i++) {
double x = positions[2 * i], y = positions[2 * i + 1], u, v;
// Map destination corners back to the untransformed source rectangle.
- switch (o->transform) {
+ switch (source_transform) {
case WL_OUTPUT_TRANSFORM_NORMAL: u = x; v = y; break;
case WL_OUTPUT_TRANSFORM_90: u = 1 - y; v = x; break;
case WL_OUTPUT_TRANSFORM_180: u = 1 - x; v = 1 - y; break;
@@ -146,6 +162,7 @@ static void texture_draw(struct pass *p, const struct wlr_render_texture_options
uv[2 * i + 1] = (src.y + v * src.height) / o->texture->height;
}
glUniform4fv(program->coords, 2, uv);
+ if (polar && program->sector_coords >= 0) glUniform4fv(program->sector_coords, 2, uv);
glUniform1f(program->mode, 0.f);
if (shape) scene_pass_set_shape(p, program, shape);
else glUniform1f(program->use_shape, 0.f);
diff --git a/src/scene_pass_internal.h b/src/scene_pass_internal.h
index 8f4827e..7b74dbf 100644
--- a/src/scene_pass_internal.h
+++ b/src/scene_pass_internal.h
@@ -21,6 +21,7 @@
#include <wlr/render/interface.h>
#include <wlr/types/wlr_buffer.h>
#include <wlr/util/log.h>
+#include <wlr/util/transform.h>
struct program {
GLuint id;
@@ -28,6 +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;
// 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.
@@ -110,7 +112,7 @@ static const GLfloat positions[] = {0, 0, 1, 0, 0, 1, 1, 1};
// The program a draw of `shape` (NULL: none) uses: the polygon variant for an outline.
static inline struct program *shaped_for(struct rediwm_scene_renderer *r,
const struct rediwm_pass_shape *shape, bool external) {
- const bool poly = shape && shape->poly_count > 0;
+ const bool poly = shape && (shape->poly_count > 0 || shape->sector.radii[1] > 0);
if (external) return poly ? &r->shaped_poly_external : &r->shaped_external;
return poly ? &r->shaped_poly : &r->shaped;
}
@@ -124,6 +126,21 @@ static inline bool shape_usable(const struct rediwm_pass_shape *s) {
const float *a = s->poly[i], *b = s->poly[i + 1 < s->poly_count ? i + 1 : 0];
if (!isfinite(a[0]) || !isfinite(a[1]) || (a[0] == b[0] && a[1] == b[1])) return false;
}
+ const struct rediwm_pass_sector *a = &s->sector;
+ for (int i = 0; i < 2; i++) {
+ if (!isfinite(a->center[i]) || !isfinite(a->radii[i]) ||
+ !isfinite(a->axis[i]) || !isfinite(a->half_angle[i])) return false;
+ }
+ if (a->radii[1] < 0) return false;
+ if (a->radii[1] > 0 && (s->poly_count || a->radii[0] < 0 || a->radii[0] >= a->radii[1] ||
+ fabsf(a->axis[0] * a->axis[0] + a->axis[1] * a->axis[1] - 1.f) > 1e-4f ||
+ a->half_angle[0] < 0 || a->half_angle[1] <= 0 ||
+ fabsf(a->half_angle[0] * a->half_angle[0] + a->half_angle[1] * a->half_angle[1] - 1.f) > 1e-4f)) return false;
+ if (!isfinite(s->sector_texture_height) || s->sector_texture_height < 0) return false;
+ if (s->sector_texture_height > 0 && (a->radii[1] <= 0 ||
+ (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->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.c b/src/scene_pass_test.c
index 2fa930d..18eb54c 100644
--- a/src/scene_pass_test.c
+++ b/src/scene_pass_test.c
@@ -93,6 +93,7 @@ static struct wlr_texture *texture_create(struct wlr_renderer *renderer, bool op
#include "scene_pass_test_parity.c"
#include "scene_pass_test_shapes.c"
+#include "scene_pass_test_sector.c"
#include "scene_pass_test_shading.c"
#include "scene_pass_test_backdrop.c"
diff --git a/src/scene_pass_test_sector.c b/src/scene_pass_test_sector.c
new file mode 100644
index 0000000..90d3ba7
--- /dev/null
+++ b/src/scene_pass_test_sector.c
@@ -0,0 +1,154 @@
+// Analytic circular switcher clips: pixel coverage and the border use exactly
+// the same circular arcs, including fractional scales and rotated sectors.
+static void gate_sector_texture(struct rediwm_scene_renderer *r, struct wlr_buffer *buf,
+ struct image *img);
+static void gate_sector(struct rediwm_scene_renderer *r, struct wlr_buffer *buf,
+ struct image *img) {
+ const float ring[4] = {0.f, .8f, .9f, 1.f};
+ const double pi = acos(-1.);
+ int worst = 0;
+ for (size_t scale = 0; scale < COUNT(SCALES); scale++) {
+ const float s = SCALES[scale];
+ for (int direction = 0; direction < 8; direction++) {
+ const double angle = direction * pi / 4 + .13;
+ struct rediwm_pass_shape shape = {
+ .box = {20, 20, (int)ceilf(196 * s), (int)ceilf(196 * s)},
+ .sector = {
+ .center = {98 * s + .3f, 98 * s + .7f},
+ .radii = {34.25f * s, 95.75f * s},
+ .axis = {(float)sin(angle), (float)-cos(angle)},
+ .half_angle = {(float)cos(pi / 5), (float)sin(pi / 5)},
+ },
+ .border = 2 * s,
+ };
+ memcpy(shape.border_color, ring, sizeof(ring));
+ struct rediwm_sector reference;
+ for (int i = 0; i < 2; i++) {
+ reference.center[i] = shape.sector.center[i];
+ reference.radii[i] = shape.sector.radii[i];
+ reference.axis[i] = shape.sector.axis[i];
+ reference.half_angle[i] = shape.sector.half_angle[i];
+ }
+ struct wlr_render_pass *pass = begin_fill(r, buf, BG, NULL);
+ piece(pass, &shape, shape.box, BODY, NULL);
+ finish(pass);
+ read_image(r, buf, img);
+ for (int y = 0; y < shape.box.height; y++) for (int x = 0; x < shape.box.width; x++) {
+ const double distance = rediwm_sd_sector(x + .5, y + .5, &reference);
+ const double coverage = rediwm_coverage(distance);
+ const double border = 1 - rediwm_coverage(distance + shape.border);
+ const uint8_t *pixel = at(img, shape.box.x + x, shape.box.y + y);
+ for (int ch = 0; ch < 3; ch++) {
+ const double color = (BODY[ch] * (1 - border) + ring[ch] * border) * coverage + BG[ch] * (1 - coverage);
+ const int error = diff(pixel[ch], (int)lround(color * 255));
+ if (error > worst) worst = error;
+ }
+ }
+ }
+ }
+ check(worst <= 2, "sector: GPU circular coverage/ring differs from analytic distance by %d levels", worst);
+
+ // Invalid shape data fails the pass without leaving GL state poisoned.
+ struct rediwm_pass_shape invalid = {.box = {20, 20, 100, 100},
+ .sector = {.center = {50, 50}, .radii = {40, 20}, .axis = {0, -1}, .half_angle = {.8, .6}}};
+ struct wlr_render_pass *pass = begin_fill(r, buf, BG, NULL);
+ piece(pass, &invalid, invalid.box, BODY, NULL);
+ check(!wlr_render_pass_submit(pass), "sector: inverted radii did not fail the pass");
+ pass = begin_fill(r, buf, BG, NULL);
+ finish(pass);
+ printf("PASS: circular sectors and borders match analytic coverage within %d levels at fractional scales and eight orientations\n", worst);
+ gate_sector_texture(r, buf, img);
+}
+
+// The source gradient makes both crop offsets and orientation observable:
+// red is the column, green the row. A polar window must preserve its entire
+// top row while consuming only the first part of a tall source's height.
+static void gate_sector_texture(struct rediwm_scene_renderer *r, struct wlr_buffer *buf,
+ struct image *img) {
+ enum { SIDE = 128 };
+ uint32_t pixels[SIDE * SIDE];
+ for (int y = 0; y < SIDE; y++) for (int x = 0; x < SIDE; x++)
+ pixels[y * SIDE + x] = 0xff000020u | (uint32_t)(2 * x) << 16 | (uint32_t)(2 * y) << 8;
+ struct wlr_texture *texture = wlr_texture_from_pixels(r->renderer,
+ DRM_FORMAT_ARGB8888, SIDE * 4, SIDE, SIDE, pixels);
+ check(texture != NULL, "sector texture creation failed");
+ const enum wl_output_transform source_transforms[] = {
+ WL_OUTPUT_TRANSFORM_NORMAL, WL_OUTPUT_TRANSFORM_90, WL_OUTPUT_TRANSFORM_FLIPPED,
+ };
+ const double half = .7;
+ int worst = 0;
+ for (int scale = 0; scale < 2; scale++) {
+ const float s = scale ? 1.5f : 1.f;
+ for (int output = 0; output < 8; output++) {
+ struct wlr_box probe[3], positions[3] = {{0, 0, 1, 1}, {1, 0, 1, 1}, {0, 1, 1, 1}};
+ for (int i = 0; i < 3; i++) wlr_box_transform(&probe[i], &positions[i],
+ wlr_output_transform_invert(output), 3, 5);
+ const double ex[2] = {probe[1].x - probe[0].x, probe[1].y - probe[0].y};
+ const double ey[2] = {probe[2].x - probe[0].x, probe[2].y - probe[0].y};
+ struct rediwm_pass_shape shape = {
+ .box = {20, 20, (int)ceilf(240 * s), (int)ceilf(240 * s)},
+ .sector = {
+ .center = {120 * s + .3f, 120 * s + .7f},
+ .radii = {30 * s, 110 * s},
+ .axis = {(float)(ex[0] * sin(.31) - ey[0] * cos(.31)),
+ (float)(ex[1] * sin(.31) - ey[1] * cos(.31))},
+ .half_angle = {(float)cos(half), (float)sin(half)},
+ },
+ .sector_texture_height = 160 * s,
+ .sector_texture_flip = output >= WL_OUTPUT_TRANSFORM_FLIPPED ? -1 : 1,
+ .sector_texture_transform = output,
+ };
+ for (size_t tr = 0; tr < COUNT(source_transforms); tr++) {
+ const enum wl_output_transform source = source_transforms[tr];
+ struct wlr_render_pass *pass = begin_fill(r, buf, BG, NULL);
+ rediwm_scene_pass_add_texture_shaped(pass, &(struct wlr_render_texture_options){
+ .texture = texture, .dst_box = shape.box,
+ .src_box = {16, 24, 96, 80}, .filter_mode = WLR_SCALE_FILTER_BILINEAR,
+ .transform = wlr_output_transform_compose(source, output),
+ }, &shape);
+ finish(pass);
+ read_image(r, buf, img);
+ for (int across = -3; across <= 3; across++) for (int row = 0; row < 3; row++) {
+ const double theta = across * .18, radius = (106 - row * 30) * s;
+ const double ax = shape.sector.axis[0], ay = shape.sector.axis[1];
+ const double tx = -ay * shape.sector_texture_flip, ty = ax * shape.sector_texture_flip;
+ const int x = (int)floor(shape.box.x + shape.sector.center[0] + radius * (ax * cos(theta) + tx * sin(theta)));
+ const int y = (int)floor(shape.box.y + shape.sector.center[1] + radius * (ay * cos(theta) + ty * sin(theta)));
+ const double dx = x + .5 - shape.box.x - shape.sector.center[0];
+ const double dy = y + .5 - shape.box.y - shape.sector.center[1];
+ const double u = .5 + atan2(dx * tx + dy * ty, dx * ax + dy * ay) / (2 * half);
+ const double v = (shape.sector.radii[1] - hypot(dx, dy)) / shape.sector_texture_height;
+ // Known source orientation, independent of output rotation.
+ const double su = source == WL_OUTPUT_TRANSFORM_90 ? 1 - v :
+ source == WL_OUTPUT_TRANSFORM_FLIPPED ? 1 - u : u;
+ const double sv = source == WL_OUTPUT_TRANSFORM_90 ? u : v;
+ const uint8_t *pixel = at(img, x, y);
+ const int red = (int)lround(2 * (16 + 96 * su - .5));
+ const int green = (int)lround(2 * (24 + 80 * sv - .5));
+ const int error = diff(pixel[0], red) > diff(pixel[1], green) ? diff(pixel[0], red) : diff(pixel[1], green);
+ if (error > worst) worst = error;
+ }
+ }
+ }
+ }
+ check(worst <= 2, "sector top framing/source crop/transform differs by %d levels", worst);
+
+ // A short source ends naturally, with no stretched last row below it.
+ const struct rediwm_pass_shape short_source = {
+ .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 = 20, .sector_texture_flip = 1,
+ };
+ struct wlr_render_pass *pass = begin_fill(r, buf, BG, NULL);
+ rediwm_scene_pass_add_texture_shaped(pass, &(struct wlr_render_texture_options){
+ .texture = texture, .dst_box = short_source.box,
+ }, &short_source);
+ finish(pass);
+ read_image(r, buf, img);
+ const 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");
+ 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/scene_pass_test_shading.c b/src/scene_pass_test_shading.c
index c64bfdc..d5271a5 100644
--- a/src/scene_pass_test_shading.c
+++ b/src/scene_pass_test_shading.c
@@ -266,6 +266,7 @@ static void shaped_gates(struct rediwm_scene_renderer *r, struct wlr_allocator *
gate_border_partition(r, buf, &img, &ref);
gate_premultiplied(r, buf, &img);
gate_polygon(r, buf, &img, &ref);
+ gate_sector(r, buf, &img);
gate_dim(r, buf, &img);
gate_opaque_cover(r, buf, &img, &ref);
gate_shadow(r, buf, &img);
diff --git a/src/scene_sector.h b/src/scene_sector.h
new file mode 100644
index 0000000..d6dafd2
--- /dev/null
+++ b/src/scene_sector.h
@@ -0,0 +1,48 @@
+// Analytic annular sectors used by circular switcher cards. The outer radius
+// activates the shape; a zeroed sector leaves the ordinary clip unchanged.
+#pragma once
+#include <math.h>
+#include <stdbool.h>
+
+struct rediwm_sector {
+ double center[2];
+ double radii[2]; // inner, outer
+ double axis[2]; // unit vector along the middle of the wedge
+ double half_angle[2]; // cosine, sine; a wedge spans no more than pi radians
+};
+
+static inline bool rediwm_sector_valid(const struct rediwm_sector *s) {
+ const double *fields[] = {s->center, s->radii, s->axis, s->half_angle};
+ bool zero = true;
+ for (int i = 0; i < 4; i++) for (int j = 0; j < 2; j++) {
+ if (!isfinite(fields[i][j])) return false;
+ if (fields[i][j] != 0) zero = false;
+ }
+ if (s->radii[1] == 0) return zero;
+ const double axis_length2 = s->axis[0] * s->axis[0] + s->axis[1] * s->axis[1];
+ const double angle_length2 = s->half_angle[0] * s->half_angle[0] + s->half_angle[1] * s->half_angle[1];
+ return s->radii[0] >= 0 && s->radii[1] > s->radii[0] &&
+ fabs(axis_length2 - 1) < 1e-6 && fabs(angle_length2 - 1) < 1e-6 &&
+ s->half_angle[0] >= 0 && s->half_angle[1] > 0;
+}
+
+// Exact signed distance to the two circular arcs and the finite radial sides.
+// Fold about the wedge's axis so the nearer straight side is always the same.
+// The shader's sdsector follows the same arithmetic in scene_pass.c.
+static inline double rediwm_sd_sector(double px, double py, const struct rediwm_sector *s) {
+ const double dx = px - s->center[0], dy = py - s->center[1];
+ const double x = fabs(dx * s->axis[1] - dy * s->axis[0]);
+ const double y = dx * s->axis[0] + dy * s->axis[1];
+ const double radius = sqrt(dx * dx + dy * dy);
+ const double cosine = s->half_angle[0], sine = s->half_angle[1];
+ double along = x * sine + y * cosine;
+ along = fmax(s->radii[0], fmin(s->radii[1], along));
+ const double edge_x = x - sine * along, edge_y = y - cosine * along;
+ double distance = sqrt(edge_x * edge_x + edge_y * edge_y);
+ const bool angular_inside = y >= radius * cosine;
+ if (angular_inside) {
+ distance = fmin(distance, fmin(fabs(radius - s->radii[0]), fabs(radius - s->radii[1])));
+ if (radius >= s->radii[0] && radius <= s->radii[1]) distance = -distance;
+ }
+ return distance;
+}
diff --git a/src/scene_sector.zig b/src/scene_sector.zig
new file mode 100644
index 0000000..7e7693e
--- /dev/null
+++ b/src/scene_sector.zig
@@ -0,0 +1,13 @@
+//! ABI shared with scene_sector.h and scene_pass.h. A zero outer radius disables
+//! the analytic annular sector; active sectors have a unit axis and half-angle.
+fn Sector(comptime Float: type) type {
+ return extern struct {
+ center: [2]Float = @splat(0),
+ radii: [2]Float = @splat(0), // inner, outer
+ axis: [2]Float = @splat(0),
+ half_angle: [2]Float = @splat(0), // cos, sin
+ };
+}
+
+pub const Spec = Sector(f64);
+pub const Device = Sector(f32);
diff --git a/src/switcher/circular.zig b/src/switcher/circular.zig
new file mode 100644
index 0000000..c0d98cf
--- /dev/null
+++ b/src/switcher/circular.zig
@@ -0,0 +1,320 @@
+//! Circular presentation of the switcher's frozen MRU list, grouped by app.
+//! Tab/Shift+Tab exhausts a multi-window group's own windows (`advance`,
+//! member by member in first-seen order) before moving to the next app; the
+//! linear style keeps the flat MRU order untouched. A group's stack fans open
+//! (`State.expand`) only while it holds the selection.
+const std = @import("std");
+const wlr = @import("wlroots");
+const sn = @import("../node.zig");
+const Switcher = @import("../Switcher.zig");
+const Server = @import("../Server.zig");
+const Output = @import("../Output.zig");
+const PanelBuffer = @import("../panel_buffer.zig").PanelBuffer;
+const projection = @import("../projection.zig");
+const col = @import("../color.zig");
+const ui = @import("ui");
+const theme = ui.theme;
+const Anim = ui.anim.Anim;
+const i18n = @import("i18n");
+const gpa = @import("../main.zig").gpa;
+pub const layout = @import("layout.zig");
+const tau = 2 * std.math.pi;
+const page_size = 8;
+
+const Group = struct { first: usize, front: usize, count: usize = 0, members: std.ArrayList(usize) = .empty };
+pub const State = struct {
+ enabled: bool = false,
+ groups: std.ArrayList(Group) = .empty,
+ page: usize = 0,
+ hub: ?*sn.Buffer = null,
+ hub_icon: ?*sn.Buffer = null,
+ hub_icon_source: ?*wlr.Buffer = null,
+ hub_storage: ?*wlr.Buffer = null,
+ hub_key: ?u64 = null,
+ /// The group the selected card belonged to last frame, so entering a
+ /// different group (including the very first selection) can be told
+ /// apart from cycling within the one already open.
+ current_group: ?usize = null,
+ /// 0 = idle stack, 1 = the selected group's windows fanned fully open.
+ /// Retargeted in `select` whenever `current_group` changes.
+ expand: Anim = .{},
+
+ pub fn deinit(self: *State) void {
+ if (self.hub_storage) |buffer| buffer.unlock();
+ for (self.groups.items) |*group| group.members.deinit(gpa);
+ self.groups.deinit(gpa);
+ }
+};
+
+pub fn open(self: *Switcher, server: *Server) !void {
+ _ = projection.setTreeInert(&self.tree.?.node, true);
+ var r: ui.paint.Renderer = undefined;
+ if (server.config.compositor.switcher_circle_bg) {
+ const diameter: f32 = @floatFromInt(self.width);
+ const bg = try PanelBuffer.create(self.width, self.width, self.scale);
+ defer bg.base.drop();
+ r = ui.paint.Renderer.init(bg.pixels, bg.width, bg.height, self.scale);
+ // Darkness and opacity come from the window chrome, not a switcher-local
+ // setting, so the disc matches whatever chrome look the user picked.
+ const chrome = theme.global.window_bg;
+ r.fillRect(4, 4, diameter - 8, diameter - 8, .{ .color = .{ chrome[0], chrome[1], chrome[2], 1 }, .radius = diameter / 2, .border_width = 1, .border_color = theme.global.switcher_border });
+ self.background = try self.makeNode(&bg.base, self.width, self.width);
+ }
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |tl| {
+ if (!tl.isMapped() or tl.tab_hidden or !@import("../workspaces.zig").visible(tl)) continue;
+ const index = self.cards.items.len;
+ const group_index = try groupFor(self, server, tl.appId(), index);
+ 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);
+ r.fillRect(0, 0, 40, 40, .{ .color = theme.global.switcher_icon_bg, .radius = theme.global.switcher_icon_radius });
+ r.drawIcon(5, 5, 30, 30, .{ .id = .generic, .color = theme.global.switcher_fg });
+ const icon = try self.makeNode(&icon_image.base, 40, 40);
+ // 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 = .{
+ .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);
+ try self.cards.append(gpa, card);
+ try group.members.append(gpa, index);
+ group.count += 1;
+ }
+ self.circle.hub = try self.tree.?.createSceneBuffer(null);
+ self.circle.hub.?.setFilterMode(.bilinear);
+ self.circle.hub.?.point_accepts_input = Switcher.ignoreInput;
+ self.circle.hub_icon = try self.tree.?.createSceneBuffer(null);
+ self.circle.hub_icon.?.setFilterMode(.bilinear);
+ self.circle.hub_icon.?.point_accepts_input = Switcher.ignoreInput;
+}
+
+fn groupFor(self: *Switcher, server: *Server, raw: []const u8, index: usize) !usize {
+ const identity = @import("../window_tabs.zig").identity;
+ const app = identity(raw);
+ // Unidentified clients need independent slots, not one anonymous stack.
+ if (app.len > 0) for (self.circle.groups.items, 0..) |group, i| {
+ const first = server.findToplevelById(self.cards.items[group.first].id) orelse continue;
+ if (std.mem.eql(u8, app, identity(first.appId()))) return i;
+ };
+ try self.circle.groups.append(gpa, .{ .first = index, .front = index });
+ return self.circle.groups.items.len - 1;
+}
+
+/// Replaces the flat `(selected ± 1) % n` step for the circular style: a
+/// multi-window group is exhausted member by member, in the order its
+/// windows were first seen, before the wheel moves on to the next group.
+/// Forward and backward are exact mirrors, so a full lap in either direction
+/// revisits every window exactly once, same as the flat styles.
+pub fn advance(self: *Switcher, reverse: bool) void {
+ const groups = self.circle.groups.items;
+ if (groups.len == 0) return;
+ const card = self.cards.items[self.selected];
+ const group = groups[card.group];
+ const next_member: ?usize = if (reverse)
+ (if (card.member == 0) null else card.member - 1)
+ else
+ (if (card.member + 1 >= group.count) null else card.member + 1);
+ if (next_member) |member| {
+ self.selected = group.members.items[member];
+ return;
+ }
+ const next_group = if (reverse) (card.group + groups.len - 1) % groups.len else (card.group + 1) % groups.len;
+ const entry: usize = if (reverse) groups[next_group].count - 1 else 0;
+ self.selected = groups[next_group].members.items[entry];
+}
+
+pub fn select(self: *Switcher, opening: bool) void {
+ const card = self.cards.items[self.selected];
+ const group = &self.circle.groups.items[card.group];
+ group.front = self.selected;
+ const entering_group = opening or self.circle.current_group != card.group;
+ if (entering_group) {
+ self.circle.current_group = card.group;
+ if (group.count > 1) {
+ self.circle.expand.cancel(0);
+ self.circle.expand.retargetTo(@import("../Taskbar.zig").nowMs(), 1, ui.anim.curveFor(.switcher_scroll));
+ } else {
+ self.circle.expand.cancel(0);
+ }
+ }
+ const page = card.group / page_size;
+ const slots = @min(page_size, self.circle.groups.items.len - page * page_size);
+ const target: f32 = @floatCast(@as(f64, @floatFromInt(card.group % page_size)) * tau / @as(f64, @floatFromInt(slots)));
+ if (opening or page != self.circle.page) {
+ self.scroll = .{ .to = target };
+ } else {
+ // Cross the twelve-o'clock seam by the shorter arc.
+ const delta = @mod(target - self.scroll.to + std.math.pi, tau) - std.math.pi;
+ self.scroll.retargetTo(@import("../Taskbar.zig").nowMs(), self.scroll.to + delta, ui.anim.curveFor(.switcher_scroll));
+ }
+ self.circle.page = page;
+ // Only restack on selection. Repeating this every frame would damage an
+ // otherwise idle switcher and keep its frame loop awake.
+ var depth: usize = 3;
+ while (depth > 0) {
+ depth -= 1;
+ for (self.cards.items) |*item| {
+ if (stackDepth(self, item) == depth) item.tree.?.node.raiseToTop();
+ }
+ }
+ self.circle.hub.?.node.raiseToTop();
+ self.circle.hub_icon.?.node.raiseToTop();
+}
+
+fn stackDepth(self: *const Switcher, card: *const Switcher.Card) usize {
+ const group = self.circle.groups.items[card.group];
+ const front = self.cards.items[group.front];
+ return (card.member + group.count - front.member) % group.count;
+}
+
+pub fn tick(self: *Switcher, output: *Output, now: i64) bool {
+ const box = output.usableBox();
+ self.tree.?.node.setPosition(box.x + @divTrunc(box.width - self.width, 2), box.y + @divTrunc(box.height - self.width, 2));
+ if (self.background) |bg| bg.setOpacity(theme.global.window_bg[3]);
+ const slots = @min(page_size, self.circle.groups.items.len - self.circle.page * page_size);
+ const arc = layout.span(slots);
+ const rotation: f64 = self.scroll.value(now);
+ const selected_group = self.cards.items[self.selected].group;
+ const expand: f64 = @floatCast(self.circle.expand.value(now));
+ for (self.cards.items) |*card| {
+ const depth = stackDepth(self, card);
+ const visible = card.group / page_size == self.circle.page and depth < 3;
+ card.tree.?.node.setEnabled(visible);
+ if (!visible) continue;
+ const angle = @as(f64, @floatFromInt(card.group % page_size)) * tau / @as(f64, @floatFromInt(slots)) - rotation;
+ const progress = if (card.group == selected_group) expand else 0;
+ const sector = layout.makeSector(self.width, angle, arc, depth, progress);
+ placeCard(self, card, sector, depth, progress);
+ if (card.id == self.cards.items[self.selected].id) self.refreshIcon(card);
+ }
+ paintHub(self, output.server) catch |err| std.log.warn("circular switcher label: {}", .{err});
+ _ = self.scroll.sampleChanged(now, ui.anim.quantum_px);
+ _ = self.circle.expand.sampleChanged(now, ui.anim.quantum_px);
+ return !self.scroll.settled(now) or !self.circle.expand.settled(now);
+}
+
+fn placeCard(self: *Switcher, card: *Switcher.Card, sector: layout.Sector, depth: usize, progress: f64) void {
+ const selected = self.cards.items[self.selected].id == card.id;
+ const color = if (selected) theme.global.switcher_selected_border else theme.global.switcher_item_border;
+ const tree = card.tree.?;
+ tree.node.setPosition(sector.x, sector.y);
+ card.fill.?.setSize(sector.width, sector.height);
+ _ = projection.setTreeClip(&tree.node, .{
+ .width = sector.width,
+ .height = sector.height,
+ .radii = @splat(0),
+ .border = if (selected) 2 else 1,
+ .border_color = col.Straight.fromRgba(color).premultiply().rgba,
+ .sector = sector.arc,
+ .sector_texture_height = if (card.pw > 0) layout.previewHeight(sector, card.aspect) else 0,
+ });
+ // A card behind the front of its stack dims less as the group opens, so a
+ // 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
+ // 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);
+}
+
+fn paintHub(self: *Switcher, server: *Server) !void {
+ const card = &self.cards.items[self.selected];
+ const tl = server.findToplevelById(card.id) orelse return;
+ const group = self.circle.groups.items[card.group];
+ const key = std.hash.Wyhash.hash(card.id, tl.title()) ^ (@as(u64, tl.workspace_id) << 32);
+ const size: i32 = @intFromFloat(@as(f32, @floatFromInt(self.width)) * 0.36 - 16);
+ const x = @divTrunc(self.width - size, 2);
+ const s: f32 = @min(1, @as(f32, @floatFromInt(size)) / 210);
+ const text_scale = @max(0.85, s);
+ const d: f32 = @floatFromInt(size);
+ const icon_size: i32 = @intFromFloat(52 * s);
+ const icon = self.circle.hub_icon.?;
+ if (self.circle.hub_icon_source != card.icon_buffer) {
+ icon.setBuffer(card.icon_buffer);
+ self.circle.hub_icon_source = card.icon_buffer;
+ }
+ icon.setDestSize(icon_size, icon_size);
+ // -78*s keeps the icon's vertical centre where it was before growing it,
+ // splitting the extra size between the title below and the arrow above.
+ icon.node.setPosition(@divTrunc(self.width - icon_size, 2), x + @as(i32, @intFromFloat(d / 2 - 78 * s)));
+ if (self.circle.hub_key != key) {
+ const image = try PanelBuffer.create(size, size, self.scale);
+ defer image.base.drop();
+ var r = ui.paint.Renderer.init(image.pixels, image.width, image.height, self.scale);
+ r.fillRect(0, 0, d, d, .{ .color = theme.global.switcher_item_bg, .radius = d / 2, .border_width = 1, .border_color = theme.global.switcher_border });
+ // The selected sector always settles at twelve o'clock (layout.zig),
+ // so a fixed upward arrow always points at it; no need to rotate it.
+ const arrow_size = 28 * s;
+ r.drawIcon(d / 2 - arrow_size / 2, 2 * s, arrow_size, arrow_size, .{ .id = .caret_up, .color = theme.global.switcher_selected_border });
+ centered(&r, d, d / 2 - 22 * s, tl.title(), theme.global.switcher_title_size * text_scale, theme.global.switcher_fg);
+ var workspace_buf: [128]u8 = undefined;
+ const workspace = if (server.world.workspaces.active)
+ i18n.fmt(&workspace_buf, i18n.tr("Workspace {n}"), .{ .n = tl.workspace_id }) catch ""
+ else
+ i18n.tr("Canvas");
+ centered(&r, d, d / 2 + 2 * s, workspace, theme.global.switcher_app_size * text_scale, theme.global.switcher_dim);
+ var count_buf: [64]u8 = undefined;
+ const count = std.fmt.bufPrint(&count_buf, "{d} / {d}", .{ card.member + 1, group.count }) catch "";
+ centered(&r, d, d / 2 + 24 * s, count, theme.global.switcher_app_size * text_scale, theme.global.switcher_fg);
+ // The stack's total window count, as a small badge inside the hub disc
+ // itself (up and to the right of centre) rather than floating outside
+ // the wheel next to the sector.
+ if (group.count > 1) {
+ const badge_d = 22 * s;
+ const reach = d / 2 * 0.72;
+ const badge_cx = d / 2 + reach * 0.7;
+ const badge_cy = d / 2 - reach * 0.7;
+ var badge_buf: [8]u8 = undefined;
+ const badge_text = std.fmt.bufPrint(&badge_buf, "{d}", .{group.count}) catch "";
+ const font_size = 11 * text_scale;
+ const text_width = ui.text.measureWidthF(badge_text, .manrope_heavy, font_size, self.scale) catch badge_d;
+ r.fillRect(badge_cx - badge_d / 2, badge_cy - badge_d / 2, badge_d, badge_d, .{ .color = theme.global.switcher_selected_border, .radius = badge_d / 2, .border_width = 1, .border_color = theme.global.switcher_item_bg });
+ r.drawText(badge_cx - text_width / 2, badge_cy - font_size / 2 - 1, text_width + 4, font_size + 6, .{ .content = badge_text, .font_size = font_size, .weight = 700, .color = theme.global.on_accent });
+ }
+ if (self.circle.groups.items.len > page_size) {
+ const pages = (self.circle.groups.items.len + page_size - 1) / page_size;
+ const shown = @min(5, pages);
+ const first = @min(self.circle.page -| 2, pages - shown);
+ for (0..shown) |i| {
+ const dot_x = d / 2 + (@as(f32, @floatFromInt(i)) - @as(f32, @floatFromInt(shown - 1)) / 2) * 10 - 2;
+ r.fillRect(dot_x, d / 2 + 52 * s, 4, 4, .{ .radius = 2, .color = if (first + i == self.circle.page) theme.global.switcher_selected_border else theme.global.switcher_dim });
+ }
+ }
+ self.circle.hub.?.setBuffer(&image.base);
+ _ = image.base.lock();
+ if (self.circle.hub_storage) |old| old.unlock();
+ self.circle.hub_storage = &image.base;
+ self.circle.hub.?.setDestSize(size, size);
+ self.circle.hub.?.node.setPosition(x, x);
+ self.circle.hub_key = key;
+ }
+}
+
+fn centered(r: *ui.paint.Renderer, width: f32, y: f32, value: []const u8, size: f32, color: [4]f32) void {
+ const x = @max(12, ui.paint.centeredTextX(0, width, value, size));
+ r.drawText(x, y, width - x - 12, size + 8, .{ .content = value, .font_size = size, .color = color });
+}
diff --git a/src/switcher/layout.zig b/src/switcher/layout.zig
new file mode 100644
index 0000000..0ec1211
--- /dev/null
+++ b/src/switcher/layout.zig
@@ -0,0 +1,84 @@
+//! Geometry for circular switcher cards. Angles start at twelve o'clock and
+//! increase clockwise. Both curved edges are exact, analytic circular arcs.
+const std = @import("std");
+const SectorSpec = @import("../scene_sector.zig").Spec;
+
+pub const Sector = struct {
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+ /// Relative to the bounding box. The circle's center can be outside it.
+ arc: SectorSpec,
+};
+
+pub fn diameter(width: i32, height: i32) i32 {
+ return @min(720, width - 32, height - 32);
+}
+
+pub fn span(group_count: usize) f64 {
+ const slot = 2 * std.math.pi / @as(f64, @floatFromInt(@max(4, group_count)));
+ return slot - @min(0.045, slot * 0.12);
+}
+
+/// `progress` is 0 for a group's ordinary idle stack (a thin 14px cascade)
+/// rising to 1 while the switcher eases the *selected* group open, so its
+/// windows fan out far enough to read individually. Callers pass 0 for any
+/// group that is not currently selected.
+pub fn makeSector(size: i32, angle: f64, arc: f64, depth: usize, progress: f64) Sector {
+ const center = @as(f64, @floatFromInt(size)) / 2;
+ const step = 14 + 46 * std.math.clamp(progress, 0, 1);
+ const offset = @as(f64, @floatFromInt(@min(depth, 2))) * step;
+ const inner = @as(f64, @floatFromInt(size)) * 0.18 + offset;
+ const outer = center - 36 + offset;
+ const axis: [2]f64 = .{ @sin(angle), -@cos(angle) };
+ const half: [2]f64 = .{ @cos(arc / 2), @sin(arc / 2) };
+ var left: f64 = std.math.inf(f64);
+ var top: f64 = std.math.inf(f64);
+ var right: f64 = -std.math.inf(f64);
+ var bottom: f64 = -std.math.inf(f64);
+ // Exact bounds come from the four arc endpoints and any cardinal extrema
+ // inside the angular span. Sampling a polygon would cut off the curve's peak.
+ const angles = [_]f64{ angle - arc / 2, angle + arc / 2, 0, std.math.pi / 2.0, std.math.pi, std.math.pi * 1.5 };
+ for (angles, 0..) |a, i| {
+ const sx = @sin(a);
+ const sy = -@cos(a);
+ if (i >= 2 and sx * axis[0] + sy * axis[1] < half[0] - 1e-12) continue;
+ for ([_]f64{ inner, outer }) |radius| {
+ const px = center + sx * radius;
+ const py = center + sy * radius;
+ left = @min(left, px);
+ top = @min(top, py);
+ right = @max(right, px);
+ bottom = @max(bottom, py);
+ }
+ }
+ const x: i32 = @intFromFloat(@floor(left) - 1);
+ const y: i32 = @intFromFloat(@floor(top) - 1);
+ const width = @as(i32, @intFromFloat(@ceil(right) + 1)) - x;
+ const height = @as(i32, @intFromFloat(@ceil(bottom) + 1)) - y;
+ return .{
+ .x = x,
+ .y = y,
+ .width = width,
+ .height = height,
+ .arc = .{
+ .center = .{ center - @as(f64, @floatFromInt(x)), center - @as(f64, @floatFromInt(y)) },
+ .radii = .{ inner, outer },
+ .axis = axis,
+ .half_angle = half,
+ },
+ };
+}
+
+/// Fit the full window width to the outer arc. Its top starts at that rim;
+/// natural-height content extends toward the hub, which may hide its bottom.
+/// This stays constant through rotation, unlike an upright bounding-box crop.
+pub fn previewHeight(sector: Sector, aspect: f64) f64 {
+ const arc = 2 * std.math.atan2(sector.arc.half_angle[1], sector.arc.half_angle[0]);
+ return sector.arc.radii[1] * arc / aspect;
+}
+
+test {
+ _ = @import("layout_tests.zig");
+}
diff --git a/src/switcher/layout_tests.zig b/src/switcher/layout_tests.zig
new file mode 100644
index 0000000..15c3d8d
--- /dev/null
+++ b/src/switcher/layout_tests.zig
@@ -0,0 +1,85 @@
+const std = @import("std");
+const testing = std.testing;
+const layout = @import("layout.zig");
+
+test "circular switcher fits usable output and keeps narrow sectors separated" {
+ try testing.expectEqual(@as(i32, 720), layout.diameter(1920, 1080));
+ try testing.expectEqual(@as(i32, 568), layout.diameter(800, 600));
+ try testing.expectEqual(@as(i32, 288), layout.diameter(320, 800));
+ try testing.expectEqual(layout.span(1), layout.span(4));
+ for ([_]usize{ 1, 4, 5, 8, 32, 256, 10000 }) |count| {
+ const slot = 2 * std.math.pi / @as(f64, @floatFromInt(@max(4, count)));
+ try testing.expect(layout.span(count) > 0);
+ try testing.expect(layout.span(count) < slot);
+ }
+}
+
+test "exact circular arcs stay within the preview bounds throughout rotation" {
+ for ([_]i32{ 260, 320, 568, 720 }) |size| {
+ const center = @as(f64, @floatFromInt(size)) / 2;
+ for ([_]usize{ 1, 2, 4, 5, 6, 8, 12, 32, 256 }) |count| {
+ for (0..3) |depth| {
+ for (0..32) |step| {
+ const angle = 2 * std.math.pi * @as(f64, @floatFromInt(step)) / 32;
+ const arc = layout.span(count);
+ const sector = layout.makeSector(size, angle, arc, depth, 0);
+ try testing.expect(sector.width > 0 and sector.height > 0);
+ try testing.expect(sector.x >= 0 and sector.y >= 0);
+ try testing.expect(sector.x + sector.width <= size);
+ try testing.expect(sector.y + sector.height <= size);
+ try testing.expectApproxEqAbs(center, sector.arc.center[0] + @as(f64, @floatFromInt(sector.x)), 1e-8);
+ try testing.expectApproxEqAbs(center, sector.arc.center[1] + @as(f64, @floatFromInt(sector.y)), 1e-8);
+ try testing.expect(sector.arc.radii[0] > 0 and sector.arc.radii[1] > sector.arc.radii[0]);
+ // Sample between the old polygon vertices, including exact
+ // cardinal peaks: none of the true curve may be clipped off.
+ for (0..101) |sample| {
+ const a = angle - arc / 2 + arc * @as(f64, @floatFromInt(sample)) / 100;
+ for (sector.arc.radii) |radius| {
+ const x = sector.arc.center[0] + @sin(a) * radius;
+ const y = sector.arc.center[1] - @cos(a) * radius;
+ try testing.expect(x >= 0.99 and x <= @as(f64, @floatFromInt(sector.width)) - 0.99);
+ try testing.expect(y >= 0.99 and y <= @as(f64, @floatFromInt(sector.height)) - 0.99);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+test "stack offsets remain concentric and stop at two layers" {
+ const front = layout.makeSector(720, 0.43, layout.span(5), 0, 0);
+ const back = layout.makeSector(720, 0.43, layout.span(5), 2, 0);
+ try testing.expectApproxEqAbs(@as(f64, 28), back.arc.radii[0] - front.arc.radii[0], 1e-8);
+ try testing.expectApproxEqAbs(@as(f64, 28), back.arc.radii[1] - front.arc.radii[1], 1e-8);
+ try testing.expectEqualDeep(back, layout.makeSector(720, 0.43, layout.span(5), 100, 0));
+}
+
+test "expand progress widens the stack without moving the front layer" {
+ const front = layout.makeSector(720, 0.43, layout.span(5), 0, 1);
+ const front_idle = layout.makeSector(720, 0.43, layout.span(5), 0, 0);
+ try testing.expectEqualDeep(front_idle, front);
+ const back_idle = layout.makeSector(720, 0.43, layout.span(5), 2, 0);
+ const back_open = layout.makeSector(720, 0.43, layout.span(5), 2, 1);
+ try testing.expectApproxEqAbs(@as(f64, 120), back_open.arc.radii[0] - front.arc.radii[0], 1e-8);
+ try testing.expect(back_open.arc.radii[0] - front.arc.radii[0] > back_idle.arc.radii[0] - front_idle.arc.radii[0]);
+}
+
+test "radial previews fit the full top edge and crop only below it" {
+ const arc = layout.span(4);
+ const front = layout.makeSector(720, 0, arc, 0, 0);
+ const height = layout.previewHeight(front, 0.2);
+ try testing.expectApproxEqAbs(front.arc.radii[1] * arc / 0.2, height, 1e-8);
+ const depth = front.arc.radii[1] - front.arc.radii[0];
+ // A tall window keeps its header: the whole visible band comes from its
+ // first tenth, rather than a centered crop around the source's midpoint.
+ try testing.expect(depth / height < 0.1);
+ for (0..32) |step| {
+ const angle = 2 * std.math.pi * @as(f64, @floatFromInt(step)) / 32;
+ const rotated = layout.makeSector(720, angle, arc, 0, 0);
+ try testing.expectApproxEqAbs(height, layout.previewHeight(rotated, 0.2), 1e-8);
+ }
+ // Shallow windows retain their natural height; empty space after their
+ // bottom is transparent rather than a repeated final row or vertical stretch.
+ try testing.expect(layout.previewHeight(front, 10) < depth);
+}
diff --git a/src/switcher/preview.zig b/src/switcher/preview.zig
new file mode 100644
index 0000000..9fb3632
--- /dev/null
+++ b/src/switcher/preview.zig
@@ -0,0 +1,10 @@
+//! Client-buffer synchronization for switcher thumbnails. Geometry and frame
+//! callbacks stay with Switcher; the binding never changes output/scale feedback.
+const sn = @import("../node.zig");
+const wlr = @import("wlroots");
+
+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.
+pub const setSurface = rediwm_switcher_preview_set_surface;
diff --git a/src/switcher_preview.c b/src/switcher_preview.c
new file mode 100644
index 0000000..4aac5df
--- /dev/null
+++ b/src/switcher_preview.c
@@ -0,0 +1,120 @@
+// Live switcher thumbnails share client buffers, acquire points and GPU releases,
+// but are not another surface view that changes preferred scale or output enters.
+#define WLR_USE_UNSTABLE
+#define WLR_PRIVATE private
+#include "switcher_preview.h"
+#include "node.h"
+#include "scene_outputs.h"
+#include <assert.h>
+#include <stdlib.h>
+#include <wlr/types/wlr_buffer.h>
+#include <wlr/types/wlr_compositor.h>
+#include <wlr/types/wlr_linux_drm_syncobj_v1.h>
+#include <wlr/types/wlr_output.h>
+#include <wlr/types/wlr_single_pixel_buffer_v1.h>
+
+struct preview_binding {
+ struct wlr_addon addon;
+ struct rediwm_buffer *preview;
+ struct wlr_surface *surface;
+ struct wlr_client_buffer *marked;
+ uint32_t commit_seq;
+ struct wl_listener node_destroy, surface_destroy, output_sample;
+};
+
+static void unmark_buffer(struct preview_binding *binding) {
+ if (!binding->marked) return;
+ assert(binding->marked->private.n_ignore_locks > 0);
+ binding->marked->private.n_ignore_locks--;
+ binding->marked = NULL;
+}
+
+static void destroy_binding(struct wlr_addon *addon) {
+ struct preview_binding *binding = wl_container_of(addon, binding, addon);
+ unmark_buffer(binding);
+ wl_list_remove(&binding->node_destroy.link);
+ wl_list_remove(&binding->surface_destroy.link);
+ wl_list_remove(&binding->output_sample.link);
+ wlr_addon_finish(addon);
+ free(binding);
+}
+
+static const struct wlr_addon_interface binding_impl = {
+ .name = "rediwm switcher preview", .destroy = destroy_binding,
+};
+
+static void handle_node_destroy(struct wl_listener *listener, void *data) {
+ (void)data;
+ struct preview_binding *binding = wl_container_of(listener, binding, node_destroy);
+ // The node emits destroy before releasing content: remove the ignore-lock mark
+ // now, while the client buffer is still alive, rather than during addon teardown.
+ destroy_binding(&binding->addon);
+}
+
+static void handle_surface_destroy(struct wl_listener *listener, void *data) {
+ (void)data;
+ struct preview_binding *binding = wl_container_of(listener, binding, surface_destroy);
+ rediwm_switcher_preview_set_surface(binding->preview, NULL);
+}
+
+static void handle_output_sample(struct wl_listener *listener, void *data) {
+ struct preview_binding *binding = wl_container_of(listener, binding, output_sample);
+ 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.
+ 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);
+ if (state) wlr_linux_drm_syncobj_v1_state_add_release_point(state,
+ event->release_timeline, event->release_point, event->output->output->event_loop);
+}
+
+bool rediwm_switcher_preview_set_surface(struct rediwm_buffer *preview,
+ struct wlr_surface *surface) {
+ struct wlr_addon *addon = wlr_addon_find(&preview->node.addons, NULL, &binding_impl);
+ struct preview_binding *binding = addon ? wl_container_of(addon, binding, addon) : NULL;
+ if (!binding) {
+ if (!surface) {
+ rediwm_buffer_set_buffer(preview, NULL);
+ return true;
+ }
+ binding = calloc(1, sizeof(*binding));
+ if (!binding) return false;
+ binding->preview = preview;
+ wlr_addon_init(&binding->addon, &preview->node.addons, NULL, &binding_impl);
+ wl_list_init(&binding->surface_destroy.link);
+ binding->node_destroy.notify = handle_node_destroy;
+ wl_signal_add(&preview->node.events.destroy, &binding->node_destroy);
+ binding->surface_destroy.notify = handle_surface_destroy;
+ binding->output_sample.notify = handle_output_sample;
+ wl_signal_add(&preview->events.output_sample, &binding->output_sample);
+ }
+ if (binding->surface != surface) {
+ wl_list_remove(&binding->surface_destroy.link);
+ wl_list_init(&binding->surface_destroy.link);
+ binding->surface = surface;
+ if (surface) wl_signal_add(&surface->events.destroy, &binding->surface_destroy);
+ }
+ 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);
+ return true;
+}
diff --git a/src/switcher_preview.h b/src/switcher_preview.h
new file mode 100644
index 0000000..56fb18a
--- /dev/null
+++ b/src/switcher_preview.h
@@ -0,0 +1,11 @@
+#pragma once
+#include <stdbool.h>
+
+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.
+bool rediwm_switcher_preview_set_surface(struct rediwm_buffer *, struct wlr_surface *);
diff --git a/src/switcher_preview_test.c b/src/switcher_preview_test.c
new file mode 100644
index 0000000..8756d99
--- /dev/null
+++ b/src/switcher_preview_test.c
@@ -0,0 +1,148 @@
+// Preview lifetime and synchronization with real scene nodes, buffers and addons.
+// Only the DRM timeline endpoints and client-buffer identification are mocked;
+// this noninstalled fixture needs no renderer, output backend or DRM device.
+#define WLR_USE_UNSTABLE
+#define WLR_PRIVATE private
+#include "node.h"
+#include "scene_outputs.h"
+#include "switcher_preview.h"
+#include <assert.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <wlr/interfaces/wlr_buffer.h>
+#include <wlr/render/drm_syncobj.h>
+#include <wlr/types/wlr_compositor.h>
+#include <wlr/types/wlr_linux_drm_syncobj_v1.h>
+#include <wlr/types/wlr_output.h>
+
+static struct wlr_surface a, b, implicit;
+static struct wlr_drm_syncobj_timeline acquire_a, acquire_b, release;
+static struct wlr_linux_drm_syncobj_surface_v1_state state_a, state_b;
+static int released, freed;
+static struct wlr_linux_drm_syncobj_surface_v1_state *last_state;
+static uint64_t last_point;
+static struct wl_event_loop *last_loop;
+struct wlr_linux_drm_syncobj_surface_v1_state *wlr_linux_drm_syncobj_v1_get_surface_state(struct wlr_surface *surface) {
+ if (surface == &implicit) return NULL;
+ assert(surface == &a || surface == &b);
+ return surface == &a ? &state_a : &state_b;
+}
+bool wlr_linux_drm_syncobj_v1_state_add_release_point(struct wlr_linux_drm_syncobj_surface_v1_state *state, struct wlr_drm_syncobj_timeline *timeline, uint64_t point, struct wl_event_loop *loop) {
+ assert(timeline == &release);
+ released++;
+ last_state = state;
+ last_point = point;
+ last_loop = loop;
+ return true;
+}
+struct wlr_drm_syncobj_timeline *wlr_drm_syncobj_timeline_ref(struct wlr_drm_syncobj_timeline *timeline) {
+ timeline->private.n_refs++;
+ return timeline;
+}
+void wlr_drm_syncobj_timeline_unref(struct wlr_drm_syncobj_timeline *timeline) {
+ if (!timeline) return;
+ assert(timeline->private.n_refs > 0);
+ timeline->private.n_refs--;
+}
+static void destroy_buffer(struct wlr_buffer *buffer) {
+ struct wlr_client_buffer *client = (struct wlr_client_buffer *)buffer;
+ assert(client->private.n_ignore_locks == 0);
+ wlr_buffer_finish(buffer);
+ freed++;
+ free(buffer);
+}
+static const struct wlr_buffer_impl client_impl = {.destroy = destroy_buffer};
+struct wlr_client_buffer *wlr_client_buffer_get(struct wlr_buffer *buffer) {
+ return buffer->impl == &client_impl ? (struct wlr_client_buffer *)buffer : NULL;
+}
+static struct wlr_client_buffer *new_client(void) {
+ struct wlr_client_buffer *client = calloc(1, sizeof(*client));
+ assert(client);
+ wlr_buffer_init(&client->base, &client_impl, 40, 30);
+ wlr_buffer_lock(&client->base);
+ wlr_buffer_drop(&client->base);
+ return client;
+}
+static void init_surface(struct wlr_surface *surface) {
+ wl_signal_init(&surface->events.destroy);
+ wl_list_init(&surface->current_outputs);
+ pixman_region32_init_rect(&surface->buffer_damage, 0, 0, 40, 30);
+ surface->buffer = new_client();
+ surface->current.seq = 1;
+}
+int main(void) {
+ init_surface(&a);
+ init_surface(&b);
+ init_surface(&implicit);
+ state_a.acquire_timeline = &acquire_a;
+ state_a.acquire_point = 11;
+ state_b.acquire_timeline = &acquire_b;
+ state_b.acquire_point = 22;
+ struct rediwm_scene *scene = rediwm_scene_create(NULL, NULL);
+ assert(scene);
+ struct rediwm_buffer *preview = rediwm_buffer_create(&scene->tree, NULL);
+ assert(preview);
+ assert(rediwm_switcher_preview_set_surface(preview, NULL));
+ assert(wl_list_empty(&preview->events.output_sample.listener_list));
+
+ // Updating a commit replaces acquire points without accumulating locks/refs.
+ assert(rediwm_switcher_preview_set_surface(preview, &a));
+ 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);
+ a.current.seq++;
+ state_a.acquire_point = 12;
+ assert(rediwm_switcher_preview_set_surface(preview, &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();
+ assert(loop);
+ struct wlr_output output = {.event_loop = loop};
+ struct rediwm_scene_output scene_output = {.output = &output};
+ struct rediwm_output_sample_event sample = {.output = &scene_output, .release_timeline = &release, .release_point = 30};
+ // Even an occluded source with no active outputs gets this GPU release fence.
+ wl_signal_emit_mutable(&preview->events.output_sample, &sample);
+ assert(released == 1 && last_state == &state_a && last_point == 30 && last_loop == loop);
+ assert(wl_list_empty(&a.current_outputs));
+ // Rebinding removes the old source's listener and releases its timeline/lock.
+ 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));
+ 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));
+ 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(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);
+ wlr_buffer_unlock(&b.buffer->base);
+ assert(freed == 2);
+
+ // The node may own the final client-buffer lock: its ignore mark must be
+ // removed before that lock destroys the buffer, not in late addon teardown.
+ preview = rediwm_buffer_create(&scene->tree, NULL);
+ assert(preview && rediwm_switcher_preview_set_surface(preview, &implicit));
+ assert(!preview->wait_timeline && implicit.buffer->private.n_ignore_locks == 1);
+ wl_signal_emit_mutable(&preview->events.output_sample, &sample);
+ assert(released == 2);
+ wlr_buffer_unlock(&implicit.buffer->base);
+ implicit.buffer = NULL;
+ rediwm_node_destroy(&preview->node);
+ assert(freed == 3 && wl_list_empty(&implicit.events.destroy.listener_list));
+ wl_signal_emit_mutable(&implicit.events.destroy, NULL);
+ rediwm_scene_destroy(scene);
+ pixman_region32_fini(&a.buffer_damage);
+ pixman_region32_fini(&b.buffer_damage);
+ pixman_region32_fini(&implicit.buffer_damage);
+ wl_event_loop_destroy(loop);
+ puts("preview binding lifecycle, acquire and release tests passed");
+}
diff --git a/src/ui/layout.zig b/src/ui/layout.zig
index a9b6c4b..abd8c4b 100644
--- a/src/ui/layout.zig
+++ b/src/ui/layout.zig
@@ -64,6 +64,9 @@ pub const IconId = enum {
search,
chevron_up,
chevron_down,
+ /// A filled triangle pointing up, distinct from the `chevron_up` stroke:
+ /// the circular switcher's hub points toward the selected sector with it.
+ caret_up,
close,
minimize,
maximize,
diff --git a/src/ui/paint_icons.zig b/src/ui/paint_icons.zig
index d0e8ef4..29921aa 100644
--- a/src/ui/paint_icons.zig
+++ b/src/ui/paint_icons.zig
@@ -46,6 +46,8 @@ pub fn iconDistance(id: IconId, px: f32, py: f32, cx: f32, cy: f32, half: f32, t
sdSegment(px, py, cx, cy - half * 0.5, cx + half, cy + half * 0.3, t),
),
.play => sdf.sdQuad(px, py, cx - half * 0.65, cy - half, cx + half, cy, cx - half * 0.65, cy + half, cx - half * 0.65, cy),
+ // `.play` rotated a quarter turn: same degenerate quad, tip at the top.
+ .caret_up => sdf.sdQuad(px, py, cx - half, cy + half * 0.65, cx, cy - half, cx + half, cy + half * 0.65, cx, cy + half * 0.65),
.pause => @min(sdBox(px, py, cx - half * 0.45, cy, half * 0.22, half), sdBox(px, py, cx + half * 0.45, cy, half * 0.22, half)),
.minimize => sdSegment(px, py, cx - half, cy, cx + half, cy, t),
.drag_handle => @min(
diff --git a/src/ui_tests.zig b/src/ui_tests.zig
index c51fd67..9d0861d 100644
--- a/src/ui_tests.zig
+++ b/src/ui_tests.zig
@@ -52,6 +52,7 @@ test {
_ = @import("resize.zig");
_ = @import("camera.zig");
_ = @import("mini_map_geometry.zig");
+ _ = @import("switcher/layout.zig");
_ = @import("calendar.zig");
_ = @import("start_menu/applications.zig");
_ = @import("start_menu/catalog_cache.zig");
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index 0cf9186..7bf2e10 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -215,6 +215,14 @@ def test_appearance_settings():
assert read_config()["compositor"]["focus_zoom"] == mode
assert ui.scroll_into_view("focus_zoom").get("selected_index") == index
+ assert ui.scroll_into_view("switcher_style").get("selected_index") == 0
+ for index, style in ((1, "circular"), (0, "linear"), (1, "circular")):
+ click_widget(ui.scroll_into_view("switcher_style"), fraction=(index + 0.5) / 2)
+ assert read_config()["compositor"]["switcher_style"] == style
+ ipc.reload_config()
+ ipc.wait_for_panel_settled("control_center")
+ assert ui.scroll_into_view("switcher_style").get("selected_index") == index
+
# --- 1. Window chrome opacity slider ---
chrome_slider = ui.scroll_into_view("chrome_opacity")
assert chrome_slider is not None
@@ -360,6 +368,7 @@ def test_appearance_settings():
# Verify speed is still 0.5x
assert ui.scroll_into_view("focus_zoom").get("selected_index") == 1
+ assert ui.scroll_into_view("switcher_style").get("selected_index") == 1
speed_seg = ui.scroll_into_view("anim_speed")
assert speed_seg.get("selected_index") == 0
diff --git a/tests/switcher.py b/tests/switcher.py
index a9c7574..22bd891 100644
--- a/tests/switcher.py
+++ b/tests/switcher.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Alt/Ctrl+Tab MRU carousel, input ownership and pixels on an isolated compositor."""
+"""Linear/circular Alt/Ctrl+Tab MRU switching and pixels on an isolated compositor."""
import os
from pathlib import Path
import subprocess
@@ -10,21 +10,32 @@ from desktop_zoom import build_client, wait_for
from ipc_client import IPCClient, spawn_compositor, stop_process
-def run(scale, modifier=56):
+def run(scale, modifier=56, style='linear'):
with tempfile.TemporaryDirectory(prefix='rediwm-switcher-') as directory:
tmp = Path(directory)
build_client(tmp)
- proc, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get('REDIWM_TEST_RENDERER', 'gles2'), config_content=f'[compositor]\nswitcher_opacity = {os.environ.get("REDIWM_TEST_SWITCHER_OPACITY", "1.0")}\n[input]\nkey_repeat_delay = 200\nkey_repeat_rate = 5\n[keybinds]\n\"alt+tab\" = \"focus_next\"\n\"alt+shift+tab\" = \"focus_prev\"\n')
+ wallpaper = tmp / 'wallpaper.png'
+ Image.new('RGB', (32, 32), (20, 24, 30)).save(wallpaper)
+ def config(layout):
+ return f'[compositor]\nwallpaper = "{wallpaper}"\nswitcher_style = "{layout}"\nswitcher_opacity = {os.environ.get("REDIWM_TEST_SWITCHER_OPACITY", "1.0")}\n[input]\nkey_repeat_delay = 200\nkey_repeat_rate = 5\n[keybinds]\n"alt+tab" = "focus_next"\n"alt+shift+tab" = "focus_prev"\n'
+ proc, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get('REDIWM_TEST_RENDERER', 'gles2'), config_content=config(style))
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'))
for i in range(7):
+ # One shared app: for circular this keeps every window in a
+ # single group, so Tab/Shift+Tab exhausting that group's
+ # members reduces to the same flat MRU sequence linear uses.
+ # Grouping's own stacking/expand/cross-group behavior is
+ # covered separately by run_group_cycle.
+ app_id = 'org.gnome.Nautilus'
with (tmp / f'client-{i}.log').open('w') as out:
- clients.append(subprocess.Popen([str(tmp / 'client'), '--title', f'Window {i}', '--app-id', 'org.gnome.Nautilus'], env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display), stdout=out, stderr=out))
+ clients.append(subprocess.Popen([str(tmp / 'client'), '--title', f'Window {i}', '--app-id', app_id], env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display), stdout=out, stderr=out))
wait_for(lambda: len(ipc.get_windows()) == i + 1, 'map fixture')
- ids = [w['id'] for w in ipc.get_windows()]
+ by_title = {w['title']: w['id'] for w in ipc.get_windows()}
+ ids = [by_title[f'Window {i}'] for i in range(7)]
def focused():
return next(w['id'] for w in ipc.get_windows() if w['is_focused'])
initial = focused()
@@ -39,13 +50,14 @@ def run(scale, modifier=56):
def capture(name):
time.sleep(.23)
path = tmp / (name + '.png')
+ path.unlink(missing_ok=True)
ipc.screenshot(path=str(path))
wait_for(path.exists, 'capture')
image = Image.open(path).convert('RGB')
dest = os.environ.get('REDIWM_SWITCHER_PREVIEW')
if dest:
Path(dest).mkdir(parents=True, exist_ok=True)
- image.save(Path(dest) / f'{name}-{scale}.png')
+ image.save(Path(dest) / f'{style}-{name}-{scale}.png')
return image
ipc.key(modifier, True)
tab()
@@ -58,21 +70,22 @@ def run(scale, modifier=56):
first = capture('first')
tab()
second = capture('second')
- # Red selection frame stays at exactly the same screen coordinates.
+ # Switching within the same app leaves the selection frame in
+ # place, while showing the selected window's title/preview.
def red_pixels(im):
return {(x, y) for y in range(im.height) for x in range(im.width)
if (lambda c: c[0] > 220 and 15 < c[1] < 65 and 35 < c[2] < 95)(im.getpixel((x, y)))}
red = red_pixels(first)
assert len(red) > 200, 'selection outline is visible'
assert red == red_pixels(second), 'center highlight moved'
- assert first.tobytes() != second.tobytes(), 'row did not scroll'
+ assert first.tobytes() != second.tobytes(), 'selected window did not change'
# Text beneath every fully visible preview must survive GPU
# compositing as well as movement, not just the red outline.
left = min(x for x, y in red)
right = max(x for x, y in red)
bottom = max(y for x, y in red)
density = float(scale)
- for offset in range(-2, 3):
+ for offset in range(-2, 3) if style == 'linear' else ():
x0 = int(left + (12 + offset * 244) * density)
x1 = int(right + (-12 + offset * 244) * density)
if x0 < 32 * density or x1 > second.width - 32 * density: continue
@@ -81,6 +94,31 @@ def run(scale, modifier=56):
ipc.key(modifier, False)
wait_for(lambda: focused() == ids[-3], 'release Alt activates selection')
+ if style == 'circular':
+ # Reload must actually select another renderer and allow
+ # switching back without restarting the compositor.
+ def reload_capture(layout):
+ (tmp / 'rediwm-config.toml').write_text(config(layout))
+ ipc.reload_config()
+ ipc.key(modifier, True)
+ tab()
+ shot = capture(f'reload-{layout}')
+ ipc.key_down_up(1)
+ ipc.key(modifier, False)
+ assert focused() == ids[-3], 'reload preview changed focus'
+ return red_pixels(shot)
+ circular_outline = reload_capture('circular')
+ ipc.key(modifier, True)
+ tab()
+ (tmp / 'rediwm-config.toml').write_text(config('linear'))
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ ipc.key(modifier, False)
+ assert focused() == ids[-3], 'changing style accepted a stale selection'
+ linear_outline = reload_capture('linear')
+ assert len(linear_outline) > 200
+ assert circular_outline != linear_outline, 'switcher_style reload did not change layout'
+ assert reload_capture('circular') == circular_outline, 'circular layout did not survive reload'
ipc.key(modifier, True)
tab()
ipc.key_down_up(1)
@@ -140,7 +178,7 @@ def run(scale, modifier=56):
tab()
ipc.key(modifier, False)
assert proc.poll() is None, 'empty carousel crashed'
- print(f'PASS switcher scale={scale} modifier={modifier}')
+ print(f'PASS switcher style={style} scale={scale} modifier={modifier}')
except Exception:
print((tmp / "compositor.log").read_text()[-6000:])
raise
@@ -150,6 +188,157 @@ def run(scale, modifier=56):
log.close()
+def run_group_cycle(scale):
+ """A multi-window app's circular sector stacks its windows; Tab exhausts
+ that app's own windows (most recent first) before moving to the next
+ app, Shift+Tab mirrors it, and the stack fans open while selected."""
+ with tempfile.TemporaryDirectory(prefix='rediwm-switcher-group-') 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 = "circular"\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'))
+ # alpha1..alpha4 share one app; Beta and Gamma are each alone.
+ specs = [('Alpha 1', 'org.rediwm.group.alpha'), ('Alpha 2', 'org.rediwm.group.alpha'),
+ ('Alpha 3', 'org.rediwm.group.alpha'), ('Alpha 4', 'org.rediwm.group.alpha'),
+ ('Beta', 'org.rediwm.group.beta'), ('Gamma', 'org.rediwm.group.gamma')]
+ for i, (title, app_id) in enumerate(specs):
+ clients.append(subprocess.Popen([str(tmp / 'client'), '--title', title, '--app-id', app_id],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
+ wait_for(lambda: len(ipc.get_windows()) == i + 1, 'map group-cycle fixture')
+ by_title = {w['title']: w['id'] for w in ipc.get_windows()}
+ ids = [by_title[t] for t, _ in specs] # alpha1, alpha2, alpha3, alpha4, beta, gamma
+
+ def establish_mru():
+ # Focusing in this order leaves Gamma most recent, Beta
+ # next, then Alpha 4..1 (Alpha 4 the most recently used
+ # of the group): cards = [gamma, beta, a4, a3, a2, a1].
+ for wid in ids:
+ ipc.action('focus_window', {'id': wid})
+
+ def focused():
+ return ipc.get_focused_window()['id']
+
+ def gesture(steps, reverse=False):
+ establish_mru()
+ ipc.key(56, True)
+ if reverse: ipc.key(42, True)
+ for _ in range(steps): ipc.key_down_up(15)
+ if reverse: ipc.key(42, False)
+ ipc.key(56, False)
+ return focused()
+
+ # Forward: leave Gamma's and Beta's singleton groups, then walk
+ # the Alpha group newest-to-oldest before completing the lap.
+ assert gesture(1) == ids[4], 'first Tab leaves the starting (singleton) group'
+ assert gesture(2) == ids[3], 'second Tab enters the app group at its most recent window'
+ assert gesture(3) == ids[2], 'third Tab stays inside the app'
+ assert gesture(4) == ids[1], 'fourth Tab is still inside the app'
+ assert gesture(5) == ids[0], "fifth Tab reaches the app's last window before leaving it"
+ assert gesture(6) == ids[5], 'sixth Tab leaves the exhausted group and completes the lap'
+ # Reverse is the exact mirror.
+ assert gesture(1, reverse=True) == ids[0], 'Shift+Tab enters the previous group at its last window'
+ assert gesture(4, reverse=True) == ids[3], 'reverse cycling mirrors forward order inside the group'
+
+ # The stack fans open only while its group holds the
+ # selection: a screenshot grabbed on the first frame after
+ # entering it must still be mid-animation, and a later one
+ # must have stopped changing.
+ establish_mru()
+ ipc.key(56, True)
+ ipc.key_down_up(15) # Beta
+ ipc.key_down_up(15) # Alpha 4: enters the stacked group
+ path = tmp / 'expand.png'
+ def shot(name):
+ 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'group-cycle-{name}-{scale}.png')
+ return image
+ ipc.wait_for_frame()
+ fast = shot('fast')
+ time.sleep(0.4)
+ settled = shot('settled')
+ time.sleep(0.2)
+ settled_again = shot('settled-again')
+ ipc.key_down_up(1) # Escape: close without accepting a selection
+ ipc.key(56, False)
+ assert fast.tobytes() != settled.tobytes(), 'stack did not animate open'
+ assert settled.tobytes() == settled_again.tobytes(), 'stack kept animating after it should have settled'
+ assert focused() == ids[5], 'Escape must preserve focus'
+ assert proc.poll() is None
+ print(f'PASS circular switcher group cycling 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()
+
+
+def run_pagination(scale):
+ """More app groups than visible sectors must not truncate the MRU list."""
+ with tempfile.TemporaryDirectory(prefix='rediwm-switcher-pages-') 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, config_content=f'[compositor]\nwallpaper = "{wallpaper}"\nswitcher_style = "circular"\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'))
+ ids = []
+ for i in range(10):
+ title = f'Group {i}'
+ clients.append(subprocess.Popen([str(tmp / 'client'), '--title', title, '--app-id', f'org.rediwm.switcher.group{i}'], env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
+ wait_for(lambda: len(ipc.get_windows()) == i + 1, 'map group')
+ windows = ipc.get_windows()
+ ids.append(next(w['id'] for w in windows if w['title'] == title))
+ for steps in range(1, len(ids) + 1):
+ for wid in ids:
+ ipc.action('focus_window', {'id': wid})
+ ipc.key(29, True)
+ for _ in range(steps):
+ ipc.key_down_up(15)
+ assert ipc.get_focused_window()['id'] == ids[-1], 'paged preview changed focus'
+ if steps == 9:
+ time.sleep(.25)
+ path = tmp / 'last-page.png'
+ ipc.screenshot(path=str(path))
+ wait_for(path.exists, 'capture last page')
+ image = Image.open(path).convert('RGB')
+ assert sum(r > 220 and 15 < g < 65 and 35 < b < 95 for r, g, b in image.getdata()) > 200, 'selected group outside visible page'
+ if dest := os.environ.get('REDIWM_SWITCHER_PREVIEW'):
+ Path(dest).mkdir(parents=True, exist_ok=True)
+ image.save(Path(dest) / f'circular-last-page-{scale}.png')
+ ipc.key(29, False)
+ expected = ids[(len(ids) - 1 - steps) % len(ids)]
+ wait_for(lambda: ipc.get_focused_window()['id'] == expected, 'every paged group remains selectable')
+ assert proc.poll() is None
+ print(f'PASS circular switcher pagination 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 modifier in (56, 29):
- for scale in ('1', '1.5'): run(scale, modifier)
+ 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)
diff --git a/tests/switcher_live.py b/tests/switcher_live.py
index d99e995..f1d38eb 100644
--- a/tests/switcher_live.py
+++ b/tests/switcher_live.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Panel-only opacity and frame-paced, minimized live previews; no host access."""
+import math
import os
from pathlib import Path
import subprocess
@@ -10,11 +11,38 @@ from desktop_zoom import build_client, wait_for
from ipc_client import IPCClient, spawn_compositor, stop_process
-def run(scale):
+def circular_geometry(output, taskbar):
+ scale = output['scale']
+ width = output['logical_width']
+ usable_height = taskbar['box']['y']
+ diameter = min(720, width - 32, usable_height - 32)
+ center_x = ((width - diameter) // 2 + diameter / 2) * scale
+ center_y = ((usable_height - diameter) // 2 + diameter / 2) * scale
+ return center_x, center_y, diameter * .18 * scale, (diameter / 2 - 36) * scale
+
+
+def assert_circular_arc(image, output, taskbar):
+ """The selected arc follows a circle even between the former polygon vertices."""
+ center_x, center_y, _, radius = circular_geometry(output, taskbar)
+ errors = []
+ for x in range(math.ceil(center_x - radius * .45), math.floor(center_x + radius * .45)):
+ expected = center_y - math.sqrt(radius ** 2 - (x + .5 - center_x) ** 2)
+ outline = [y for y in range(math.floor(expected) - 2, math.ceil(expected) + 7)
+ if (lambda c: c[0] > 220 and 15 < c[1] < 65 and 35 < c[2] < 95)(image.getpixel((x, y)))]
+ assert outline, ('missing circular outer edge', x, expected)
+ errors.append(min(outline) + .5 - expected)
+ # Allow the antialiasing threshold and pixel-center quantization, but not
+ # the 2–4px chord sag of the previous seven-segment outer arc.
+ assert errors and max(abs(error) for error in errors) <= 1.5, ('faceted circular edge', min(errors), max(errors))
+
+
+def run(scale, style='linear'):
with tempfile.TemporaryDirectory(prefix='rediwm-switcher-live-') as directory:
tmp = Path(directory)
build_client(tmp)
- proc, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get('REDIWM_TEST_RENDERER', 'gles2'))
+ 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:
@@ -35,13 +63,15 @@ def run(scale):
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'{name}-{scale}.png')
+ image.save(Path(dest) / f'{style}-{name}-{scale}.png')
return image
backdrop = capture('backdrop')
ipc.key(29, True)
ipc.key_down_up(15)
time.sleep(.25)
opaque = capture('opaque')
+ if style == 'circular':
+ assert_circular_arc(opaque, ipc.get_outputs()[0], ipc.get_shell_state()['taskbars'][0])
red = [(x, y) for y in range(opaque.height) for x in range(opaque.width)
if (lambda c: c[0] > 220 and 15 < c[1] < 65 and 35 < c[2] < 95)(opaque.getpixel((x, y)))]
assert red, 'missing outline'
@@ -57,8 +87,8 @@ def run(scale):
assert near(live.getpixel(center), (34, 204, 102)), live.getpixel(center)
assert near(opaque.getpixel(center), (34, 85, 221)), opaque.getpixel(center)
assert ipc.get_windows()[0]['is_minimized'], 'preview restored client'
- for opacity in (0.5, 0.0, 1.0):
- (tmp / 'rediwm-config.toml').write_text(f'[compositor]\nswitcher_opacity = {opacity}\n')
+ for opacity in (0.5, 0.0, 1.0) if style == 'linear' else ():
+ (tmp / 'rediwm-config.toml').write_text(f'[compositor]\nwallpaper = "{wallpaper}"\nswitcher_style = "{style}"\nswitcher_opacity = {opacity}\n')
ipc.reload_config()
time.sleep(.15)
image = capture(f'opacity-{opacity}')
@@ -71,7 +101,8 @@ def run(scale):
time.sleep(.25)
resized = capture('resized')
assert near(resized.getpixel(center), (204, 153, 34)), resized.getpixel(center)
- assert not near(resized.getpixel((int(center[0] + 70 * float(scale)), center[1])), (204, 153, 34)), 'preview aspect ratio did not update'
+ if style == 'linear':
+ assert not near(resized.getpixel((int(center[0] + 70 * float(scale)), center[1])), (204, 153, 34)), 'preview aspect ratio did not update'
ipc.key_down_up(1)
ipc.key(29, False)
time.sleep(.2)
@@ -79,7 +110,88 @@ def run(scale):
time.sleep(.2)
assert (tmp / 'client.log').read_text().count('frame ') == count, 'hidden minimized preview kept requesting frames'
assert proc.poll() is None
- print(f'PASS live switcher scale={scale}')
+ print(f'PASS live switcher style={style} scale={scale}')
+ except Exception:
+ print((tmp / 'compositor.log').read_text()[-4000:])
+ raise
+ finally:
+ for client in clients: stop_process(client)
+ stop_process(proc)
+ log.close()
+
+
+def run_radial_framing(scale):
+ """Each sector retains the source's top; tall windows crop at the hub."""
+ with tempfile.TemporaryDirectory(prefix='rediwm-switcher-radial-') 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 = "circular"\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'))
+ pattern = tmp / 'pattern'
+ # A zero live color asks the existing fixture for red above its
+ # midpoint and blue below. No production test hook is needed.
+ pattern.write_text('0 200 1000')
+ for i in range(4):
+ clients.append(subprocess.Popen([str(tmp / 'client'), '--title', f'Radial {i}',
+ '--app-id', f'rediwm.radial-fixture.{i}'],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display,
+ REDIWM_TEST_LIVE_FILE=str(pattern), REDIWM_TEST_NO_CHILD='1'),
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
+ wait_for(lambda: len(ipc.get_windows()) == i + 1, 'radial client map')
+ for window in ipc.get_windows():
+ ipc.action('minimize_window', {'id': window['id']})
+ wait_for(lambda: all(w['is_minimized'] for w in ipc.get_windows()), 'radial clients minimized')
+ ipc.key(29, True)
+ ipc.key_down_up(15)
+
+ def capture(name):
+ time.sleep(.25)
+ path = tmp / f'{name}.png'
+ ipc.screenshot(path=str(path))
+ wait_for(path.exists, 'radial 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'circular-{name}-{scale}.png')
+ return image
+
+ output = ipc.get_outputs()[0]
+ taskbar = ipc.get_shell_state()['taskbars'][0]
+ cx, cy, inner, outer = circular_geometry(output, taskbar)
+ inset = 6 * output['scale']
+
+ def check_radial_colors(image, inner_color):
+ for dx, dy in ((0, -1), (1, 0), (0, 1), (-1, 0)):
+ for radius, expected in ((outer - inset, (255, 0, 0)),
+ (inner + inset, inner_color)):
+ point = (round(cx + dx * radius), round(cy + dy * radius))
+ actual = image.getpixel(point)
+ assert all(abs(a - b) <= 3 for a, b in zip(actual, expected)), (
+ 'source top/bottom framing', (dx, dy), radius, actual, expected)
+
+ # Tall source bottoms must disappear behind the center, leaving
+ # the red upper half visible throughout all four radial views.
+ tall = capture('tall-top')
+ check_radial_colors(tall, (255, 0, 0))
+ assert_circular_arc(tall, output, taskbar)
+ # A shorter source reaches its blue lower half near the hub.
+ # This also checks orientation at right, bottom and left, where
+ # upright rectangular crops cannot keep the source top outside.
+ pattern.write_text('0 400 240')
+ check_radial_colors(capture('short-top'), (0, 0, 255))
+ assert all(w['is_minimized'] for w in ipc.get_windows()), 'radial preview restored a client'
+ ipc.key_down_up(1)
+ ipc.key(29, False)
+ assert proc.poll() is None
+ print(f'PASS radial switcher framing scale={scale}')
except Exception:
print((tmp / 'compositor.log').read_text()[-4000:])
raise
@@ -90,4 +202,6 @@ def run(scale):
if __name__ == '__main__':
- for scale in ('1', '1.5'): run(scale)
+ for style in ('linear', 'circular'):
+ for scale in ('1', '1.5'): run(scale, style)
+ for scale in ('1', '1.5'): run_radial_framing(scale)
diff --git a/tests/switcher_perf.py b/tests/switcher_perf.py
new file mode 100644
index 0000000..5419642
--- /dev/null
+++ b/tests/switcher_perf.py
@@ -0,0 +1,362 @@
+#!/usr/bin/env python3
+"""Isolated switcher CPU/frame-cost and retention audit; compare ReleaseSafe builds.
+
+Run comparable binaries serially, preferably in alternating order. Clean mode
+never requests compositor performance counters (those enable extra GPU timers).
+Stats mode uses a separate session. CPU100% means one core; frame_time_ms is
+commit cadence, not rendering cost. Headless results do not prove DRM latency.
+
+ python3 tests/switcher_perf.py --binary zig-out/release-safe/bin/rediwm \
+ --style circular --mode clean --out /tmp/circular-clean.json
+ python3 tests/switcher_perf.py --style linear --mode stats --out /tmp/linear-stats.json
+ python3 tests/switcher_perf.py --style circular --mode retention --cycles 50 \
+ --out /tmp/circular-retention.json
+"""
+import argparse
+import hashlib
+import json
+import math
+import os
+from pathlib import Path
+import statistics
+import subprocess
+import tempfile
+import time
+
+from PIL import Image
+
+from desktop_zoom import ROOT, build_client, wait_for
+from i18n import isolated_environment
+from ipc_client import IPCClient, spawn_compositor, stop_process
+from memory_retention import memory, scene_counts, summarize
+from scene_baseline import condense, power_state, thread_snapshot
+
+
+FIXTURE_VARS = ("REDIWM_TEST_PERF", "REDIWM_TEST_PERF_DAMAGE", "REDIWM_TEST_PERF_HZ",
+ "REDIWM_TEST_PERF_DAMAGE_RECT", "REDIWM_TEST_LIVE_FILE",
+ "REDIWM_TEST_EDGE", "REDIWM_TEST_COMMANDS", "REDIWM_TEST_INITIAL_STATE")
+
+
+def cpu_seconds(pid):
+ fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
+ return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK")
+
+
+def thread_delta(before, after, elapsed):
+ rows = []
+ for tid, (name, ns, voluntary, involuntary) in after.items():
+ old = before.get(tid, (name, 0, 0, 0))
+ rows.append({"tid": tid, "name": name, "cpu_ns": ns - old[1],
+ "voluntary": voluntary - old[2], "involuntary": involuntary - old[3]})
+ return {"cpu_percent": sum(r["cpu_ns"] for r in rows) / 1e9 / elapsed * 100,
+ "voluntary_switches_per_second": sum(r["voluntary"] for r in rows) / elapsed,
+ "involuntary_switches_per_second": sum(r["involuntary"] for r in rows) / elapsed,
+ "threads": sorted(rows, key=lambda r: -r["cpu_ns"]),
+ "exited_threads": sorted(set(before) - set(after))}
+
+
+class Session:
+ def __init__(self, args, tmp):
+ self.args, self.tmp = args, tmp
+ self.clients, self.client_logs, self.ids = [], [], []
+ self.held = False
+ self.phase_rows = {}
+ build_client(tmp)
+ env = isolated_environment(tmp)
+ # Prevent delayed autosave restore from moving fixtures during a sample.
+ no_state = tmp / "state-disabled"
+ no_state.write_text("isolated performance fixture")
+ env.update(XDG_STATE_HOME=str(no_state), PULSE_SERVER=f"unix:{tmp}/missing-pulse",
+ PIPEWIRE_RUNTIME_DIR=str(tmp), REDIWM_DESKTOP_DIR=str(tmp / "desktop"),
+ REDIWM_APP_SCOPES="0", REDIWM_SESSION_FD="", REDIWM_LOGIN_SESSION="",
+ DISPLAY="", XAUTHORITY="", WLR_RENDERER_ALLOW_SOFTWARE="1",
+ REDIWM_THEME=str(tmp / "rediwm-config.toml"))
+ if args.drm_device:
+ env["WLR_RENDER_DRM_DEVICE"] = args.drm_device
+ self.env = env
+ wallpaper = tmp / "wallpaper.png"
+ Image.new("RGB", (32, 32), (20, 24, 30)).save(wallpaper)
+ config = (f'[compositor]\nxwayland = false\nfocus_zoom = "keep"\n'
+ f'wallpaper = "{wallpaper}"\nswitcher_style = "{args.style}"\n'
+ '[desktop]\nenabled = false\n[polkit]\nenable = false\n'
+ '[keybinds]\n"ctrl+tab" = "focus_next"\n"ctrl+shift+tab" = "focus_prev"\n')
+ self.process, self.log = spawn_compositor(tmp, binary=args.binary, renderer=args.renderer,
+ scale=str(args.scale), config_content=config, env_extra=env)
+ self.ipc = None
+ try:
+ self.ipc = IPCClient(tmp, timeout=20).connect()
+ self.ipc.wait_for("wallpaper_presented", timeout_ms=15000)
+ self.display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ self.outputs = self.ipc.get_outputs()
+ self.ipc.move_cursor(0, 0)
+ if args.mode == "stats":
+ self.ipc.get_perf() # Instrumentation belongs to this session only.
+ except Exception:
+ self.close()
+ raise
+
+ def close(self):
+ for client in self.clients:
+ if client.poll() is None:
+ stop_process(client)
+ if self.ipc:
+ self.ipc.close()
+ if self.process.poll() is None:
+ stop_process(self.process)
+ self.log.close()
+
+ def callbacks(self):
+ return [path.read_text().count("frame ") for path in self.client_logs]
+
+ def settle(self, seconds=0.7):
+ self.ipc.wait_for_frame()
+ time.sleep(seconds)
+
+ def open_switcher(self, timed=False):
+ self.ipc.key(29, True)
+ self.held = True
+ started = time.monotonic()
+ self.ipc.key_down_up(15)
+ dispatched = time.monotonic()
+ if timed:
+ self.ipc.wait_for_frame()
+ return {"dispatch_ms": (dispatched - started) * 1000,
+ "dispatch_to_frame_ms": (time.monotonic() - dispatched) * 1000,
+ "total_to_frame_ms": (time.monotonic() - started) * 1000}
+
+ def cancel_switcher(self):
+ self.ipc.key_down_up(1)
+ self.ipc.key(29, False)
+ self.held = False
+
+ def fixtures(self, live=False):
+ if self.held:
+ self.cancel_switcher()
+ for client in self.clients:
+ if client.poll() is None:
+ stop_process(client)
+ self.clients, self.client_logs, self.ids = [], [], []
+ wait_for(lambda: not self.ipc.get_windows(), "old fixtures did not close")
+ self.settle()
+ for i in range(self.args.windows):
+ env = dict(os.environ, **self.env, XDG_RUNTIME_DIR=str(self.tmp),
+ WAYLAND_DISPLAY=self.display, REDIWM_TEST_NO_CHILD="1",
+ REDIWM_TEST_DECORATION="server", REDIWM_TEST_HIDE_CURSOR="1")
+ for name in FIXTURE_VARS:
+ env.pop(name, None)
+ if live:
+ env["REDIWM_TEST_PERF"] = "1"
+ env["REDIWM_TEST_PERF_HZ"] = str(self.args.fps)
+ if self.args.live_kind == "damage":
+ env["REDIWM_TEST_PERF_DAMAGE"] = "1"
+ if self.args.damage_rect and self.args.live_kind == "damage":
+ env["REDIWM_TEST_PERF_DAMAGE_RECT"] = self.args.damage_rect
+ title = f"Switcher performance {i}"
+ path = self.tmp / f"{'live' if live else 'static'}-{i}.log"
+ with path.open("w") as log:
+ client = subprocess.Popen([str(self.tmp / "client"), "--title", title,
+ "--app-id", f"rediwm.switcher-perf.{i % self.args.apps}"],
+ env=env, stdout=log, stderr=log)
+ self.clients.append(client)
+ self.client_logs.append(path)
+ window = wait_for(lambda: next((w for w in self.ipc.get_windows() if w["title"] == title), None),
+ "fixture did not map")
+ wid = window["id"]
+ self.ids.append(wid)
+ self.ipc.action("set_window_size", {"id": wid, "width": 640, "height": 420})
+ self.ipc.action("move_window_to", {"id": wid, "x": 120, "y": 80})
+ self.ipc.wait_for("window_geometry_settled", window_id=wid)
+ wait_for(lambda: path.read_text().count("frame ") >= 8, "fixture initial callbacks did not settle")
+ self.ipc.action("minimize_window", {"id": wid})
+ self.settle(1)
+ assert all(w["is_minimized"] for w in self.ipc.get_windows())
+
+ def warmup(self):
+ for _ in range(self.args.warmup):
+ self.open_switcher()
+ for _ in range(min(3, self.args.windows) - 1):
+ self.ipc.key_down_up(15)
+ self.ipc.wait_for_frame()
+ time.sleep(self.args.dwell)
+ self.cancel_switcher()
+ self.ipc.wait_for_frame()
+ self.settle(1)
+
+ def measure(self, name, cycling=False, expect_static=False, expect_live=False):
+ if self.args.mode == "stats":
+ self.ipc.reset_perf()
+ callbacks_before = self.callbacks()
+ mem_before = memory(self.process.pid)
+ threads_before = thread_snapshot(self.process.pid)
+ ticks_before = cpu_seconds(self.process.pid)
+ started = time.monotonic()
+ inputs = 0
+ if cycling:
+ while time.monotonic() - started < self.args.seconds:
+ self.ipc.key_down_up(15)
+ inputs += 1
+ time.sleep(max(0, started + inputs / self.args.rate - time.monotonic()))
+ else:
+ time.sleep(self.args.seconds)
+ elapsed = time.monotonic() - started
+ ticks_after = cpu_seconds(self.process.pid)
+ threads_after = thread_snapshot(self.process.pid)
+ callbacks = [a - b for a, b in zip(self.callbacks(), callbacks_before)]
+ row = {"seconds": elapsed, "input_steps": inputs, **thread_delta(threads_before, threads_after, elapsed),
+ "cpu_ticks_percent": (ticks_after - ticks_before) / elapsed * 100,
+ "client_callbacks": callbacks, "client_callbacks_per_second": sum(callbacks) / elapsed,
+ "memory_before": mem_before, "memory_after": memory(self.process.pid)}
+ if self.args.mode == "stats":
+ row["stats"] = condense(self.ipc.get_perf())
+ if expect_static:
+ assert sum(callbacks) == 0, (name, "supposedly static clients kept requesting callbacks", callbacks)
+ if expect_live:
+ assert sum(callbacks) > 0, (name, "live workload did not draw", callbacks)
+ self.phase_rows[name] = row
+ print(f"{name}: CPU {row['cpu_percent']:.3f}%, switches "
+ f"{row['voluntary_switches_per_second']:.1f}/s, callbacks "
+ f"{row['client_callbacks_per_second']:.1f}/s", flush=True)
+ assert self.process.poll() is None
+ return row
+
+ def performance(self):
+ self.fixtures()
+ cold_open = self.open_switcher(timed=True)
+ self.cancel_switcher()
+ self.warmup()
+ self.measure("closed_idle", expect_static=True)
+ self.open_switcher()
+ self.settle(1)
+ self.measure("held_static", expect_static=True)
+ self.measure("cycling_static", cycling=True, expect_static=True)
+ self.cancel_switcher()
+ self.settle(1)
+ self.measure("post_close_static_idle", expect_static=True)
+ self.fixtures(live=True)
+ self.ipc.restore(self.ids[-1])
+ self.ipc.wait_for("window_geometry_settled", window_id=self.ids[-1])
+ self.settle(1)
+ self.measure("ordinary_live_window", expect_live=True)
+ self.ipc.action("minimize_window", {"id": self.ids[-1]})
+ self.settle(1)
+ self.open_switcher()
+ self.settle(1)
+ self.measure("held_live_minimized", expect_live=True)
+ self.cancel_switcher()
+ self.settle(1)
+ self.measure("post_close_live_idle", expect_static=True)
+ return {"cold_open": cold_open, "phases": self.phase_rows}
+
+ def retention_snapshot(self):
+ counts = scene_counts(self.ipc)
+ return {**memory(self.process.pid), "scene_counts": counts, "scene_nodes": sum(counts.values())}
+
+ def retention(self):
+ self.fixtures()
+ cold = self.retention_snapshot()
+ cold_open = self.open_switcher(timed=True)
+ self.cancel_switcher()
+ self.warmup()
+ baseline = self.retention_snapshot()
+ rows = []
+ for cycle in range(self.args.cycles):
+ opened = self.open_switcher(timed=True)
+ for _ in range(min(3, self.args.windows) - 1):
+ self.ipc.key_down_up(15)
+ self.ipc.wait_for_frame()
+ time.sleep(self.args.dwell)
+ self.cancel_switcher()
+ self.settle(self.args.settle)
+ sample = self.retention_snapshot()
+ sample["cycle"] = cycle + 1
+ sample["open_timing"] = opened
+ assert sample["scene_counts"] == baseline["scene_counts"], ("scene nodes retained", cycle, sample, baseline)
+ assert sample["fds"] == baseline["fds"], ("file descriptors retained", cycle, sample, baseline)
+ rows.append(sample)
+ if (cycle + 1) % 10 == 0:
+ print(f"retention {cycle + 1}/{self.args.cycles}: private {sample['private_kib']} KiB, "
+ f"nodes {sample['scene_nodes']}, FDs {sample['fds']}", flush=True)
+ timing = {}
+ for key in ("dispatch_ms", "dispatch_to_frame_ms", "total_to_frame_ms"):
+ values = sorted(row["open_timing"][key] for row in rows)
+ timing[key] = {"p50": statistics.median(values),
+ "p95": values[math.ceil(len(values) * .95) - 1], "max": max(values)}
+ return {"cold": cold, "cold_open": cold_open, "warmed_baseline": baseline,
+ "cycles": rows, "open_timings_ms": timing, "summary": summarize(baseline, rows)}
+
+
+def run(args):
+ power = power_state()
+ if power["ac_online"] is False and not args.allow_battery:
+ raise SystemExit("Performance comparisons on battery are unreliable; use AC or --allow-battery.")
+ report = {"binary": str(args.binary), "sha256": hashlib.sha256(args.binary.read_bytes()).hexdigest(),
+ "mode": args.mode, "style": args.style, "scale": args.scale, "windows": args.windows,
+ "apps": args.apps, "fixture_size": [640, 420], "live_damage_rect": args.damage_rect,
+ "live_kind": args.live_kind,
+ "live_fps_limit": args.fps,
+ "seconds_per_phase": args.seconds, "cycling_rate": args.rate,
+ "warmup_cycles": args.warmup, "power_before": power,
+ "renderer": args.renderer, "drm_device": args.drm_device,
+ "renderer_environment": {name: os.environ.get(name) for name in
+ ("LIBGL_ALWAYS_SOFTWARE", "MESA_LOADER_DRIVER_OVERRIDE", "REDIWM_NO_GLASS")},
+ "cpu_affinity": sorted(os.sched_getaffinity(0)),
+ "notes": ["100% CPU is one core; clean mode never enables performance IPC.",
+ "Frame CPU/GPU costs overlap and must not be added.",
+ "Open timings measure IPC dispatch and a subsequent frame barrier, not scanout latency.",
+ "Headless results do not establish physical-display latency."]}
+ with tempfile.TemporaryDirectory(prefix="rediwm-switcher-perf-") as directory:
+ tmp = Path(directory)
+ tmp.chmod(0o700)
+ session = None
+ try:
+ session = Session(args, tmp)
+ report["outputs"] = session.outputs
+ report.update(session.retention() if args.mode == "retention" else session.performance())
+ report["power_after"] = power_state()
+ finally:
+ if session:
+ session.close()
+ log = tmp / "compositor.log"
+ if log.exists():
+ contents = log.read_text()
+ report["compositor_log_tail"] = contents[-12000:]
+ report["renderer_log"] = [line for line in contents.splitlines()
+ if any(word in line.lower() for word in ("egl", "opengl", "renderer", "drm"))][:40]
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(report, indent=2) + "\n")
+ print(f"Saved {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", type=Path, default=ROOT / "zig-out/release-safe/bin/rediwm")
+ parser.add_argument("--style", choices=("linear", "circular"), default="circular")
+ parser.add_argument("--mode", choices=("clean", "stats", "retention"), default="clean")
+ parser.add_argument("--scale", type=float, default=1)
+ parser.add_argument("--windows", type=int, default=8)
+ parser.add_argument("--apps", type=int, default=4)
+ parser.add_argument("--seconds", type=float, default=5)
+ parser.add_argument("--rate", type=float, default=6)
+ parser.add_argument("--fps", type=int, default=60, help="Live fixture cadence; 0 means unpaced")
+ parser.add_argument("--warmup", type=int, default=5)
+ parser.add_argument("--cycles", type=int, default=50)
+ parser.add_argument("--dwell", type=float, default=.15)
+ parser.add_argument("--settle", type=float, default=.25)
+ parser.add_argument("--renderer", default=os.environ.get("REDIWM_TEST_RENDERER", "gles2"))
+ parser.add_argument("--drm-device", default=os.environ.get("WLR_RENDER_DRM_DEVICE"))
+ parser.add_argument("--damage-rect", help="Live fixture surface-local x,y,w,h; absent means full damage")
+ parser.add_argument("--live-kind", choices=("empty", "damage"), default="damage",
+ help="Callback-only commits or buffer repaint commits in live phases")
+ parser.add_argument("--allow-battery", action="store_true")
+ parser.add_argument("--out", type=Path, required=True)
+ args = parser.parse_args()
+ args.binary = args.binary.resolve()
+ if not args.binary.is_file():
+ parser.error("--binary must exist")
+ if not all(math.isfinite(v) and v > 0 for v in (args.scale, args.seconds, args.rate, args.dwell, args.settle)):
+ parser.error("scale, seconds, rate, dwell and settle must be positive and finite")
+ if args.windows < 1 or not 1 <= args.apps <= args.windows or args.cycles < 1 or args.warmup < 1:
+ parser.error("require windows >= apps >=1, cycles >=1 and warmup >=1")
+ if not 0 <= args.fps <= 1000:
+ parser.error("fps must be between 0 and 1000")
+ run(args)
diff --git a/tests/zoom_client.c b/tests/zoom_client.c
index 4349ea1..0d8ee36 100644
--- a/tests/zoom_client.c
+++ b/tests/zoom_client.c
@@ -6,9 +6,11 @@
#include <poll.h>
#include <errno.h>
#include <stdio.h>
+#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
+#include <time.h>
#include <unistd.h>
#include <wayland-client.h>
@@ -42,6 +44,8 @@ static int edge_transform;
static int edge_mode;
static int perf_mode;
static int perf_damage;
+// Optional fixture pacing; 0 leaves the original callback-driven behavior.
+static int64_t perf_period_ns, perf_next_ns;
// REDIWM_TEST_PERF_DAMAGE_RECT="x,y,w,h": perf-damage frames report only this
// rectangle (a spinner-sized update) instead of the whole surface.
static int perf_rect[4], perf_rect_set, perf_rect_active;
@@ -156,6 +160,21 @@ static const struct wl_callback_listener frame_listener = {frame_done};
static void request_frame(void) {
wl_callback_add_listener(wl_surface_frame(surface), &frame_listener, NULL);
}
+static void pace_perf_frame(void) {
+ if (!perf_period_ns) return;
+ struct timespec now;
+ assert(clock_gettime(CLOCK_MONOTONIC, &now) == 0);
+ const int64_t ns = (int64_t)now.tv_sec * 1000000000LL + now.tv_nsec;
+ // After an occluded/minimized interval start from now, never replay missed
+ // deadlines in a burst. Ordinary callbacks share a steady absolute cadence.
+ const int64_t deadline = perf_next_ns > ns ? perf_next_ns : ns;
+ const struct timespec wake = {deadline / 1000000000LL, deadline % 1000000000LL};
+ int result;
+ do result = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &wake, NULL);
+ while (result == EINTR);
+ assert(result == 0);
+ perf_next_ns = deadline + perf_period_ns;
+}
static void frame_done(void *data, struct wl_callback *callback,
uint32_t time) {
(void)data;
@@ -188,6 +207,7 @@ static void frame_done(void *data, struct wl_callback *callback,
return;
}
if (perf_mode) {
+ pace_perf_frame();
request_frame();
if (perf_damage) {
perf_rect_active = perf_rect_set;
@@ -601,6 +621,13 @@ int main(int argc, char *argv[]) {
edge_mode = getenv("REDIWM_TEST_EDGE") != NULL;
perf_mode = getenv("REDIWM_TEST_PERF") != NULL;
perf_damage = getenv("REDIWM_TEST_PERF_DAMAGE") != NULL;
+ const char *perf_hz = getenv("REDIWM_TEST_PERF_HZ");
+ if (perf_hz) {
+ char *end;
+ const long hz = strtol(perf_hz, &end, 10);
+ assert(*perf_hz && !*end && hz >= 0 && hz <= 1000);
+ if (hz) perf_period_ns = 1000000000LL / hz;
+ }
test_opaque = getenv("REDIWM_TEST_OPAQUE") != NULL;
test_hide_cursor = getenv("REDIWM_TEST_HIDE_CURSOR") != NULL;
test_no_child = getenv("REDIWM_TEST_NO_CHILD") != NULL;