Skip to content

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

Add optional flame effects and their Appearance toggles

oxydizered04652e75a6
diff --git a/build/support.zig b/build/support.zig
index 56b9449..11a528f 100644
--- a/build/support.zig
+++ b/build/support.zig
@@ -79,7 +79,7 @@ pub fn addBassDsp(b: *std.Build, target: std.Build.ResolvedTarget) void {
pub const projection_sources = [_][]const u8{ "src/projection.c", "src/projection_props.c", "src/projection_resolve.c", "src/projection_present.c", "src/projection_pass.c", "src/projection_pick.c" };
/// scene_output.c and its parts (scene_output_internal.h).
-pub const scene_output_sources = [_][]const u8{ "src/scene_output.c", "src/scene_output_collect.c", "src/scene_output_effects.c", "src/scene_output_draw.c" };
+pub const scene_output_sources = [_][]const u8{ "src/scene_output.c", "src/scene_output_collect.c", "src/scene_output_effects.c", "src/scene_output_draw.c", "src/scene_output_ribbon.c", "src/scene_output_snapshot.c" };
pub fn addGlass(b: *std.Build, module: *std.Build.Module, damage_audit: bool) void {
module.linkSystemLibrary("wlroots-0.20", .{});
@@ -89,9 +89,10 @@ pub fn addGlass(b: *std.Build, module: *std.Build.Module, damage_audit: bool) vo
module.addCSourceFile(.{ .file = b.path("src/node.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
module.addCSourceFiles(.{ .files = &.{ "src/node_surface.c", "src/node_subsurface_tree.c", "src/node_xdg_shell.c" }, .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
module.addCSourceFile(.{ .file = b.path("src/scene_outputs.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
- module.addCSourceFiles(.{ .files = &.{ "src/scene_pass.c", "src/scene_pass_draw.c", "src/scene_pass_backdrop.c" }, .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ module.addCSourceFiles(.{ .files = &.{ "src/scene_pass.c", "src/scene_pass_draw.c", "src/scene_pass_backdrop.c", "src/scene_pass_ribbon.c" }, .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
module.addCSourceFiles(.{ .files = &scene_output_sources, .flags = if (damage_audit) &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-DREDIWM_DAMAGE_AUDIT" } else &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
module.addCSourceFile(.{ .file = b.path("src/scene_damage.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ module.addCSourceFile(.{ .file = b.path("src/ribbon.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" } });
diff --git a/build/tests.zig b/build/tests.zig
index d216e57..4382cd6 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -418,6 +418,7 @@ pub fn addC(ctx: Context, test_step: *std.Build.Step) void {
projection_tests.root_module.addCSourceFile(.{ .file = b.path("src/projection_test.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
projection_tests.root_module.addCSourceFile(.{ .file = b.path("src/scene_damage.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
projection_tests.root_module.addCSourceFile(.{ .file = b.path("src/scene_outputs.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ projection_tests.root_module.addCSourceFile(.{ .file = b.path("src/ribbon.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
projection_tests.root_module.addCSourceFile(.{ .file = b.path("src/node.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
inline for (.{ "wlroots-0.20", "wayland-server", "pixman-1" }) |lib| {
projection_tests.root_module.linkSystemLibrary(lib, .{});
@@ -437,6 +438,7 @@ pub fn addC(ctx: Context, test_step: *std.Build.Step) void {
glass_tests.root_module.addCSourceFiles(.{ .files = &support.projection_sources, .flags = &.{ "-std=c11", "-Wall", "-Wextra" } });
glass_tests.root_module.addCSourceFile(.{ .file = b.path("src/scene_damage.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
glass_tests.root_module.addCSourceFile(.{ .file = b.path("src/scene_outputs.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ glass_tests.root_module.addCSourceFile(.{ .file = b.path("src/ribbon.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
glass_tests.root_module.addCSourceFile(.{ .file = b.path("src/node.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
const run_glass_tests = b.addRunArtifact(glass_tests);
run_glass_tests.setEnvironmentVariable("WLR_RENDERER", "gles2");
diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.md
index e93ea24..309bb1b 100644
--- a/docs/agent-notes/map.md
+++ b/docs/agent-notes/map.md
@@ -74,7 +74,15 @@ Also in `src/`: `Shell.zig` (xdg-shell and decorations), `Popup.zig`,
output pass); `glass.zig`/`.c`; `chrome.zig`
(+ `chrome_paint.zig`, `chrome_tabs.zig`) for window frames; `panel_buffer`,
`panel_paint` and `panel_present.zig` for compositor-drawn panels;
-`camera.zig`, `geometry.zig`, `color.zig`.
+`camera.zig`, `geometry.zig`, `color.zig`. Optional movement ribbons use
+`effects/ribbon.zig` (bounded path/mesh), `effects/border.zig` (frame halo),
+`effects/window_move.zig` (movement/resize lifecycle), `effects/window_resize.zig`
+and `effects/resize_mesh.zig` (filled resize membranes), `effects/resize_outline.zig`
+(elastic perimeter), `effects/resize_follow.zig`
+(bounded size lag), `effects/window_minimize.zig`
+and `effects/minimize_mesh.zig` (minimize snapshots and deformation),
+`scene_output_snapshot.c` (shaped window capture), `ribbon.c` (scene nodes), `scene_pass_ribbon.c` and
+`scene_output_ribbon.c` (drawing), and `config/effects.zig` (presets).
## Compositor-drawn UI
diff --git a/po/rediwm.pot b/po/rediwm.pot
index 35dc202..755169e 100644
--- a/po/rediwm.pot
+++ b/po/rediwm.pot
@@ -2307,6 +2307,10 @@ msgstr ""
msgid "Edits undone."
msgstr ""
+#: src/control_center/sections/appearance.zig
+msgid "Effects"
+msgstr ""
+
#: src/files/app_model.zig
msgid "Eject"
msgstr ""
@@ -2667,6 +2671,18 @@ msgstr ""
msgid "Fixed desktop icons"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "Flames when minimizing windows"
+msgstr ""
+
+#: src/control_center/search_index.zig
+msgid "Flames while moving windows"
+msgstr ""
+
+#: src/control_center/search_index.zig
+msgid "Flames while resizing windows"
+msgstr ""
+
#: src/control_center/sections/display.zig
msgid "Flipped"
msgstr ""
@@ -3679,6 +3695,10 @@ msgstr ""
msgid "Natural scroll"
msgstr ""
+#: src/control_center/sections/appearance_rows.zig
+msgid "Needs Animations to be on"
+msgstr ""
+
#: src/control_center/sections/printers_tools.zig
msgid "Neither test produced output: check the backend, connection, printer and loaded paper."
msgstr ""
@@ -6879,6 +6899,10 @@ msgstr ""
msgid "Wi-Fi request failed. Check credentials and permissions."
msgstr ""
+#: src/switcher/circular.zig
+msgid "Window"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Window Management"
msgstr ""
@@ -7219,6 +7243,14 @@ msgstr ""
msgid "edge pan transitions"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "effects fire trail ribbon animation"
+msgstr ""
+
+#: src/control_center/search_index.zig
+msgid "effects fire trail ribbon drag animation"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "effects motion"
msgstr ""
diff --git a/src/Server.zig b/src/Server.zig
index b147c85..0e0f051 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -112,6 +112,9 @@ scene_outputs: *scene_outputs_mod.SceneOutputs,
/// The compositor's own scene: its layers are the trees below, bottom to top.
nodes: *sn.Scene,
glass_engine: ?*glass.Engine = null,
+ribbons_ready: bool = false,
+window_ribbons: ?*@import("effects/window_move.zig") = null,
+minimize_ribbons: ?*@import("effects/window_minimize.zig") = null,
output_renderer: *scene_output_mod.Renderer = undefined,
// Set when wp_linux_drm_syncobj_v1 is advertised: release points for client
// buffers the glass and window capture passes read (see explicit_sync.c).
diff --git a/src/config/default.zig b/src/config/default.zig
index 3b09c92..81d7249 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -205,6 +205,31 @@ pub const source =
\\# ───────────────────────────────────────────────
\\# Animations — springs by default; hot-reload keeps in-flight velocity
\\# ───────────────────────────────────────────────
+ \\# Optional soft flame trails while dragging windows. No effect resources or
+ \\# animation wakeups while disabled. Respects animations/reduced motion.
+ \\# Settings → Appearance → Effects switches each one on and off.
+ \\# [effects.window_move]
+ \\# enabled = false
+ \\# preset = "soft_flame"
+ \\# Minimizing follows window_move unless configured separately:
+ \\# [effects.window_minimize]
+ \\# enabled = true
+ \\# preset = "soft_flame"
+ \\# Resizing also follows window_move unless configured separately:
+ \\# [effects.window_resize]
+ \\# enabled = true
+ \\# preset = "soft_flame"
+ \\# [effects.presets.soft_flame]
+ \\# type = "flame_ribbon"
+ \\# color = "#ff1820"
+ \\# core_color = "#ffe0c0"
+ \\# opacity = 0.9
+ \\# width_px = 56
+ \\# max_length_px = 420
+ \\# lifetime_ms = 3000 # 50–10000; linger after movement
+ \\# turbulence = 0.3
+ \\# quality = "balanced" # low | balanced | high
+ \\#
\\# [animations]
\\# enabled = true
\\# speed = 1.0 # 0 = jump to the target; 0.5 = half speed
diff --git a/src/config/effects.zig b/src/config/effects.zig
new file mode 100644
index 0000000..e010b63
--- /dev/null
+++ b/src/config/effects.zig
@@ -0,0 +1,135 @@
+//! Optional visual effects. Appearance presets are independent of their users.
+const std = @import("std");
+const theme = @import("ui").theme;
+const fields = @import("loader_fields.zig");
+
+pub const Quality = enum { low, balanced, high };
+pub const Preset = struct {
+ color: [4]f32 = .{ 1, 24.0 / 255.0, 32.0 / 255.0, 1 },
+ core_color: [4]f32 = .{ 1, 224.0 / 255.0, 192.0 / 255.0, 1 },
+ opacity: f32 = 0.9,
+ width_px: f32 = 56,
+ max_length_px: f32 = 420,
+ lifetime_ms: u32 = 3000,
+ turbulence: f32 = 0.3,
+ quality: Quality = .balanced,
+};
+pub const NamedPreset = struct { name: []const u8, value: Preset = .{} };
+pub const Binding = struct { enabled: bool = false, preset: []const u8 = "soft_flame" };
+pub const Target = enum { window_move, window_minimize, window_resize };
+pub const Config = struct {
+ window_move: Binding = .{},
+ window_minimize: ?Binding = null,
+ window_resize: ?Binding = null,
+ presets: std.ArrayListUnmanaged(NamedPreset) = .empty,
+
+ pub fn minimize(self: Config) Binding {
+ return self.window_minimize orelse self.window_move;
+ }
+
+ pub fn resize(self: Config) Binding {
+ return self.window_resize orelse self.window_move;
+ }
+
+ /// The settings toggles: they are independent, so turning one on or off must
+ /// not drag along a binding that was only following `window_move`. Those keep
+ /// the look they have now and are returned so the caller can persist them.
+ pub const Pinned = struct { window_minimize: bool = false, window_resize: bool = false };
+
+ pub fn setEnabled(self: *Config, kind: Target, on: bool) Pinned {
+ const was_minimize = self.minimize();
+ const was_resize = self.resize();
+ var pinned: Pinned = .{};
+ switch (kind) {
+ .window_move => self.window_move.enabled = on,
+ .window_minimize => {
+ pinned.window_minimize = self.window_minimize == null;
+ self.window_minimize = .{ .enabled = on, .preset = was_minimize.preset };
+ },
+ .window_resize => {
+ pinned.window_resize = self.window_resize == null;
+ self.window_resize = .{ .enabled = on, .preset = was_resize.preset };
+ },
+ }
+ if (kind == .window_move) {
+ if (self.window_minimize == null) {
+ self.window_minimize = was_minimize;
+ pinned.window_minimize = true;
+ }
+ if (self.window_resize == null) {
+ self.window_resize = was_resize;
+ pinned.window_resize = true;
+ }
+ }
+ return pinned;
+ }
+
+ pub fn find(self: Config, name: []const u8) ?Preset {
+ for (self.presets.items) |p| if (std.mem.eql(u8, p.name, name)) return p.value;
+ return if (std.mem.eql(u8, name, "soft_flame")) .{} else null;
+ }
+
+ pub fn validate(self: Config) !void {
+ if (self.find(self.window_move.preset) == null) return error.InvalidConfig;
+ if (self.find(self.minimize().preset) == null) return error.InvalidConfig;
+ if (self.find(self.resize().preset) == null) return error.InvalidConfig;
+ }
+
+ pub fn binding(self: *Config, a: std.mem.Allocator, kind: Target, key: []const u8, value: []const u8) !void {
+ const target = switch (kind) {
+ .window_move => &self.window_move,
+ .window_minimize => blk: {
+ if (self.window_minimize == null) self.window_minimize = .{};
+ break :blk &self.window_minimize.?;
+ },
+ .window_resize => blk: {
+ if (self.window_resize == null) self.window_resize = .{};
+ break :blk &self.window_resize.?;
+ },
+ };
+ if (std.mem.eql(u8, key, "enabled")) {
+ target.enabled = try fields.parseBool(value);
+ } else if (std.mem.eql(u8, key, "preset")) {
+ target.preset = try a.dupe(u8, try theme.unquote(value));
+ } else return error.InvalidConfig;
+ }
+
+ pub fn declare(self: *Config, a: std.mem.Allocator, name: []const u8) !void {
+ if (name.len == 0 or name.len > 64 or self.presets.items.len >= 32) return error.InvalidConfig;
+ for (name) |c| if (!std.ascii.isAlphanumeric(c) and c != '_' and c != '-') return error.InvalidConfig;
+ for (self.presets.items) |p| if (std.mem.eql(u8, p.name, name)) return error.InvalidConfig;
+ try self.presets.append(a, .{ .name = try a.dupe(u8, name) });
+ }
+
+ pub fn apply(self: *Config, key: []const u8, value: []const u8) !void {
+ const p = &self.presets.items[self.presets.items.len - 1].value;
+ if (std.mem.eql(u8, key, "type")) {
+ if (!std.mem.eql(u8, try theme.unquote(value), "flame_ribbon")) return error.InvalidConfig;
+ } else if (std.mem.eql(u8, key, "color")) {
+ p.color = try theme.parseColor(try theme.unquote(value));
+ } else if (std.mem.eql(u8, key, "core_color")) {
+ p.core_color = try theme.parseColor(try theme.unquote(value));
+ } else if (std.mem.eql(u8, key, "quality")) {
+ p.quality = std.meta.stringToEnum(Quality, try theme.unquote(value)) orelse return error.InvalidConfig;
+ } else if (std.mem.eql(u8, key, "lifetime_ms")) {
+ p.lifetime_ms = std.fmt.parseInt(u32, value, 10) catch return error.InvalidConfig;
+ if (p.lifetime_ms < 50 or p.lifetime_ms > 10000) return error.InvalidConfig;
+ } else {
+ const v = std.fmt.parseFloat(f32, value) catch return error.InvalidConfig;
+ if (!std.math.isFinite(v)) return error.InvalidConfig;
+ if (std.mem.eql(u8, key, "opacity")) {
+ if (v < 0 or v > 1) return error.InvalidConfig;
+ p.opacity = v;
+ } else if (std.mem.eql(u8, key, "width_px")) {
+ if (v < 1 or v > 128) return error.InvalidConfig;
+ p.width_px = v;
+ } else if (std.mem.eql(u8, key, "max_length_px")) {
+ if (v < 8 or v > 1024) return error.InvalidConfig;
+ p.max_length_px = v;
+ } else if (std.mem.eql(u8, key, "turbulence")) {
+ if (v < 0 or v > 1) return error.InvalidConfig;
+ p.turbulence = v;
+ } else return error.InvalidConfig;
+ }
+ }
+};
diff --git a/src/config/loader.zig b/src/config/loader.zig
index 44cecdf..081d5d9 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -389,6 +389,7 @@ pub const Config = struct {
notification_rules: []NotificationRule = &.{},
sandbox_allow: []SandboxAllowRule = &.{},
animations: anim.Settings = .{},
+ effects: @import("effects.zig").Config = .{},
path: []const u8 = "",
arena: std.heap.ArenaAllocator,
diff --git a/src/config/loader_parse.zig b/src/config/loader_parse.zig
index 42bcff3..5e77ebb 100644
--- a/src/config/loader_parse.zig
+++ b/src/config/loader_parse.zig
@@ -194,6 +194,14 @@ const ParseState = struct {
return error.InvalidConfig;
};
},
+ .effect_binding => |kind| cfg.effects.binding(cfg.arena.allocator(), kind, key, value) catch |err| {
+ fail(path, line_no, "invalid effect binding field '{s}': {s}", .{ key, @errorName(err) });
+ return error.InvalidConfig;
+ },
+ .effect_preset => cfg.effects.apply(key, value) catch |err| {
+ fail(path, line_no, "invalid effect preset field '{s}': {s}", .{ key, @errorName(err) });
+ return error.InvalidConfig;
+ },
.animations => anim_cfg.applyGlobalKey(&cfg.animations, key, value) catch |err| {
fail(path, line_no, "invalid animations field '{s}': {s}", .{ key, @errorName(err) });
return error.InvalidConfig;
@@ -277,6 +285,7 @@ const ParseState = struct {
cfg.window_rules = state.rule_list.items;
cfg.notification_rules = state.notif_rule_list.items;
cfg.sandbox_allow = state.sandbox_allow_list.items;
+ try cfg.effects.validate();
try rebuildLookup(cfg);
finishCompositor(cfg);
// An explicit [animations.camera_desktop] table wins over the settings value.
@@ -315,6 +324,10 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config
}
return error.InvalidConfig;
};
+ switch (state.section) {
+ .effect_preset => |name| try cfg.effects.declare(cfg.arena.allocator(), name),
+ else => {},
+ }
if (state.section == .keybinds) state.seen_keybinds = true;
// Its presence alone chooses a taskbar theme, even with no keys.
if (state.section == .taskbar_theme and cfg.taskbar_theme == null) cfg.taskbar_theme = .{};
@@ -368,6 +381,8 @@ pub const Section = union(enum) {
ipc,
animations,
animation_target: anim.Target,
+ effect_binding: @import("effects.zig").Target,
+ effect_preset: []const u8,
};
pub fn flushArrayTables(
@@ -437,6 +452,11 @@ pub fn parseSection(line: []const u8) !Section {
inline for (.{ .theme, .taskbar_theme, .input, .input_method, .compositor, .region, .keybinds, .polkit, .idle, .power, .night_light, .notifications, .desktop, .ipc, .animations }) |tag| {
if (std.mem.eql(u8, name, @tagName(tag))) return tag;
}
+ if (std.mem.eql(u8, name, "effects.window_move")) return .{ .effect_binding = .window_move };
+ if (std.mem.eql(u8, name, "effects.window_minimize")) return .{ .effect_binding = .window_minimize };
+ if (std.mem.eql(u8, name, "effects.window_resize")) return .{ .effect_binding = .window_resize };
+ if (std.mem.startsWith(u8, name, "effects.presets.")) return .{ .effect_preset = name["effects.presets.".len..] };
+ if (std.mem.eql(u8, name, "effects") or std.mem.startsWith(u8, name, "effects.")) return error.InvalidConfig;
if (std.mem.startsWith(u8, name, "animations.")) {
const rest = name["animations.".len..];
return .{ .animation_target = anim.Target.parse(rest) orelse return error.UnknownAnimationTarget };
diff --git a/src/config/loader_sections_tests.zig b/src/config/loader_sections_tests.zig
index 44ab25f..8f29fe3 100644
--- a/src/config/loader_sections_tests.zig
+++ b/src/config/loader_sections_tests.zig
@@ -156,7 +156,7 @@ test "animations config defaults and overlay" {
try std.testing.expect(empty.animations.enabled);
try std.testing.expectEqual(@as(f32, 1.0), empty.animations.speed);
try std.testing.expectEqual(anim.ReducedMotion.auto, empty.animations.reduced_motion);
- const panel = empty.animations.targets[@intFromEnum(anim.Target.panel_slide)];
+ const panel = empty.animations.targets[@backingInt(anim.Target.panel_slide)];
try std.testing.expectEqual(anim.springs.panel_slide.stiffness, panel.curve.spring.stiffness);
var cfg = try parse(std.testing.allocator,
@@ -182,18 +182,18 @@ test "animations config defaults and overlay" {
defer cfg.deinit();
try std.testing.expectEqual(@as(f32, 0.5), cfg.animations.speed);
try std.testing.expectEqual(anim.ReducedMotion.on, cfg.animations.reduced_motion);
- const slide = cfg.animations.targets[@intFromEnum(anim.Target.panel_slide)].curve.spring;
+ const slide = cfg.animations.targets[@backingInt(anim.Target.panel_slide)].curve.spring;
try std.testing.expectEqual(@as(f32, 0.9), slide.damping_ratio);
try std.testing.expectEqual(@as(f32, 400), slide.stiffness);
try std.testing.expectEqual(@as(f32, 0.001), slide.epsilon);
- const press = cfg.animations.targets[@intFromEnum(anim.Target.taskbar_press)].curve.duration;
+ const press = cfg.animations.targets[@backingInt(anim.Target.taskbar_press)].curve.duration;
try std.testing.expectEqual(@as(i64, 120), press.ms);
try std.testing.expectEqual(anim.Ease.flip_bezier, press.ease);
- const pan = cfg.animations.targets[@intFromEnum(anim.Target.camera_pan)];
+ const pan = cfg.animations.targets[@backingInt(anim.Target.camera_pan)];
try std.testing.expectEqual(@as(f32, 300), pan.curve.spring.stiffness);
try std.testing.expectEqual(@as(f32, 0.5), pan.curve.spring.epsilon);
try std.testing.expectEqual(@as(f32, 0.99), pan.decay.rate);
- try std.testing.expect(cfg.animations.targets[@intFromEnum(anim.Target.window_open)].curve == .off);
+ try std.testing.expect(cfg.animations.targets[@backingInt(anim.Target.window_open)].curve == .off);
}
test "animations config rejects unknown targets and illegal combinations" {
@@ -252,7 +252,7 @@ test "canvas screen counts default to three and reject values outside one to ten
test "desktop switch duration sets the camera_desktop curve unless animations override it" {
const a = std.testing.allocator;
- const idx = @intFromEnum(anim.Target.camera_desktop);
+ const idx = @backingInt(anim.Target.camera_desktop);
var defaults = try parse(a, "", "mem");
defer defaults.deinit();
try std.testing.expectEqual(anim.desktopSwitchCurve(anim.default_desktop_switch_ms), defaults.animations.targets[idx].curve);
@@ -412,3 +412,44 @@ test "external overlay wins over a referenced pack without pinning inherited tok
defer a.free(saved);
try std.testing.expectEqualStrings("[theme]\nfont_size = 17\n", saved);
}
+
+test "optional ribbon presets default off, parse and reject invalid settings" {
+ const a = std.testing.allocator;
+ var defaults = try parse(a, "", "test");
+ defer defaults.deinit();
+ try std.testing.expect(!defaults.effects.window_move.enabled);
+ try std.testing.expect(!defaults.effects.minimize().enabled);
+ try std.testing.expect(!defaults.effects.resize().enabled);
+ try std.testing.expectEqual(@as(u32, 3000), defaults.effects.find("soft_flame").?.lifetime_ms);
+ var custom = try parse(a, "[effects.window_move]\nenabled = true\npreset = \"blue\"\n" ++
+ "[effects.presets.blue]\ntype = \"flame_ribbon\"\ncolor = \"#0088ff\"\n" ++
+ "lifetime_ms = 10000\nquality = \"high\"\nwidth_px = 12\n", "test");
+ defer custom.deinit();
+ try std.testing.expect(custom.effects.window_move.enabled);
+ try std.testing.expect(custom.effects.minimize().enabled);
+ try std.testing.expectEqualStrings("blue", custom.effects.minimize().preset);
+ try std.testing.expect(custom.effects.resize().enabled);
+ try std.testing.expectEqualStrings("blue", custom.effects.resize().preset);
+ var separate = try parse(a, "[effects.window_move]\nenabled = true\n" ++
+ "[effects.window_minimize]\nenabled = false\n[effects.window_resize]\nenabled = false\n", "test");
+ defer separate.deinit();
+ try std.testing.expect(!separate.effects.minimize().enabled);
+ try std.testing.expect(!separate.effects.resize().enabled);
+ var resize_only = try parse(a, "[effects.window_resize]\nenabled = true\n", "test");
+ defer resize_only.deinit();
+ try std.testing.expect(resize_only.effects.resize().enabled and !resize_only.effects.window_move.enabled);
+ try std.testing.expectEqual(@as(u32, 10000), custom.effects.find("blue").?.lifetime_ms);
+ try std.testing.expectEqual(@as(f32, 12), custom.effects.find("blue").?.width_px);
+ for ([_][]const u8{
+ "[effects.window_move]\npreset = \"missing\"\n",
+ "[effects.window_minimize]\npreset = \"missing\"\n",
+ "[effects.window_resize]\npreset = \"missing\"\n",
+ "[effects.window_mvoe]\nenabled = true\n",
+ "[effects.presets.bad]\nwidth_px = nan\n",
+ "[effects.presets.bad]\nlifetime_ms = 100000\n",
+ "[effects.presets.bad]\nlifetime_ms = 10001\n",
+ "[effects.presets.bad]\nquality = \"ultra\"\n",
+ "[effects.presets.bad]\nunknown = 1\n",
+ "[effects.presets.a]\n[effects.presets.a]\n",
+ }) |bad| try std.testing.expectError(error.InvalidConfig, parse(a, bad, "test"));
+}
diff --git a/src/config/mod.zig b/src/config/mod.zig
index e748ef5..12098f0 100644
--- a/src/config/mod.zig
+++ b/src/config/mod.zig
@@ -1,4 +1,5 @@
//! Configuration data, parsing and persistence. Runtime application lives in config_runtime/.
+pub const effects = @import("effects.zig");
pub const animations = @import("animations.zig");
pub const app_theme = @import("app_theme.zig");
pub const default = @import("default.zig");
diff --git a/src/config/setting_save.zig b/src/config/setting_save.zig
index 4b80b97..d60c431 100644
--- a/src/config/setting_save.zig
+++ b/src/config/setting_save.zig
@@ -3,6 +3,7 @@
const std = @import("std");
const Io = std.Io;
const loader = @import("loader.zig");
+const effects = @import("effects.zig");
const theme = @import("ui").theme;
pub const saveInputDevice = @import("input_device_save.zig").save;
pub const resetInputDevice = @import("input_device_save.zig").reset;
@@ -98,6 +99,49 @@ pub fn saveAnimations(allocator: std.mem.Allocator, io: Io, path: []const u8, co
try save(allocator, io, path, "animations", key, value);
}
+/// Writes the toggled effect's `enabled`; a binding that stopped following
+/// `window_move` with it also gets its `preset`, so reloading reads back what
+/// was running. One validated write.
+pub fn saveEffect(allocator: std.mem.Allocator, io: Io, path: []const u8, cfg: effects.Config, kind: effects.Target, pinned: effects.Config.Pinned) !void {
+ if (path.len == 0) return error.NoConfigPath;
+ const original = try Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(1 << 20));
+ defer allocator.free(original);
+ var old = try loader.parse(allocator, original, path);
+ defer old.deinit();
+ const result = try patchEffect(allocator, original, cfg, kind, pinned);
+ defer allocator.free(result);
+ try writeValidated(allocator, io, path, result);
+}
+
+fn patchEffect(allocator: std.mem.Allocator, original: []const u8, cfg: effects.Config, kind: effects.Target, pinned: effects.Config.Pinned) ![]u8 {
+ var text = try allocator.dupe(u8, original);
+ errdefer allocator.free(text);
+ inline for (.{ effects.Target.window_move, effects.Target.window_minimize, effects.Target.window_resize }) |target| {
+ const binding = switch (target) {
+ .window_move => cfg.window_move,
+ .window_minimize => cfg.minimize(),
+ .window_resize => cfg.resize(),
+ };
+ const pin = switch (target) {
+ .window_move => false,
+ .window_minimize => pinned.window_minimize,
+ .window_resize => pinned.window_resize,
+ };
+ if (kind == target or pin) {
+ const section = "effects." ++ @tagName(target);
+ const enabled = try patch(allocator, text, section, "enabled", binding.enabled);
+ allocator.free(text);
+ text = enabled;
+ if (pin) {
+ const preset = try patch(allocator, text, section, "preset", binding.preset);
+ allocator.free(text);
+ text = preset;
+ }
+ }
+ }
+ return text;
+}
+
fn save(allocator: std.mem.Allocator, io: Io, path: []const u8, comptime section: []const u8, comptime key: []const u8, value: anytype) !void {
if (path.len == 0) return error.NoConfigPath;
const original = try Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(1 << 20));
@@ -417,3 +461,35 @@ test "region preferences preserve unrelated settings and reject invalid weekdays
try std.testing.expectError(error.InvalidConfig, loader.parse(a, "[region]\nclock_show_seconds = 1\n", "invalid"));
try std.testing.expectError(error.InvalidConfig, loader.parse(a, "[region]\nclock_show_day = \"yes\"\n", "invalid"));
}
+
+test "effect toggles are independent and read back as they were running" {
+ const a = std.testing.allocator;
+ const original = "[effects.window_move]\nenabled = true # trails\npreset = \"calm\"\n[effects.presets.calm]\ntype = \"flame_ribbon\"\nopacity = 0.5\n";
+ var cfg = try loader.parse(a, original, "test");
+ defer cfg.deinit();
+ // Minimizing and resizing follow window_move, preset included, until a toggle is touched.
+ try std.testing.expect(cfg.effects.minimize().enabled and cfg.effects.resize().enabled);
+ const pinned = cfg.effects.setEnabled(.window_move, false);
+ try std.testing.expect(pinned.window_minimize and pinned.window_resize);
+ try std.testing.expect(!cfg.effects.window_move.enabled and cfg.effects.minimize().enabled and cfg.effects.resize().enabled);
+ const text = try patchEffect(a, original, cfg.effects, .window_move, pinned);
+ defer a.free(text);
+ var reloaded = try loader.parse(a, text, "test");
+ defer reloaded.deinit();
+ try std.testing.expect(!reloaded.effects.window_move.enabled and reloaded.effects.minimize().enabled and reloaded.effects.resize().enabled);
+ try std.testing.expectEqualStrings("calm", reloaded.effects.minimize().preset);
+ try std.testing.expect(std.mem.indexOf(u8, text, "# trails") != null);
+
+ // A binding that already follows nothing is only touched for `enabled`.
+ var fresh = try loader.parse(a, "", "test");
+ defer fresh.deinit();
+ try std.testing.expect(!fresh.effects.window_move.enabled and !fresh.effects.minimize().enabled and !fresh.effects.resize().enabled);
+ const resize_only = fresh.effects.setEnabled(.window_resize, true);
+ try std.testing.expect(resize_only.window_resize and !resize_only.window_minimize);
+ const only = try patchEffect(a, "", fresh.effects, .window_resize, resize_only);
+ defer a.free(only);
+ try std.testing.expect(std.mem.indexOf(u8, only, "window_move") == null and std.mem.indexOf(u8, only, "window_minimize") == null);
+ var only_cfg = try loader.parse(a, only, "test");
+ defer only_cfg.deinit();
+ try std.testing.expect(!only_cfg.effects.window_move.enabled and !only_cfg.effects.minimize().enabled and only_cfg.effects.resize().enabled);
+}
diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zig
index 5383d6f..b346c2b 100644
--- a/src/config_runtime/apply.zig
+++ b/src/config_runtime/apply.zig
@@ -186,6 +186,14 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
if (server.input.open_control_center) |cc| cc.refresh();
}
+ if (old.effects.window_move.enabled != new.effects.window_move.enabled or
+ old.effects.minimize().enabled != new.effects.minimize().enabled or
+ old.effects.resize().enabled != new.effects.resize().enabled or
+ !std.meta.eql(old.effects.find(old.effects.window_move.preset), new.effects.find(new.effects.window_move.preset)) or
+ !std.meta.eql(old.effects.find(old.effects.minimize().preset), new.effects.find(new.effects.minimize().preset)) or
+ !std.meta.eql(old.effects.find(old.effects.resize().preset), new.effects.find(new.effects.resize().preset)))
+ @import("../effects/window_move.zig").configure(server);
+
const theme_changed = pack_changed or !themeEql(old.theme, new.theme) or old.compositor.border_radius != new.compositor.border_radius;
const taskbar_theme_changed = !theme_mod.taskbarOverrideEql(old.taskbar_theme, new.taskbar_theme);
if (theme_changed) {
diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.md
index 9b04f39..c8eca64 100644
--- a/src/control_center/AGENTS.md
+++ b/src/control_center/AGENTS.md
@@ -59,6 +59,13 @@ helpers (and `panel.ControlCenter`); `sections/` one file per page.
over locked storage, clears it on submit/cancel/hide, and never stores passwords
in the section arena. Hiding also cancels any native authentication wait.
+* **The Appearance flame-effect toggles are independent** though `window_minimize`
+ and `window_resize` follow `window_move` in the file. `Config.setEnabled` pins
+ a following binding to what it showed before the change and `setting_save.saveEffect`
+ writes it (with its `preset`) so a reload reads back what was running; the handler
+ then calls `window_move.configure` (a reload's diff cannot, the live config
+ already changed). Off by default: nothing is written until a toggle is touched.
+
* Global search uses `search_index.zig` destinations (widget names or `@` plus
visible label text), without building hidden sections. Add an index entry
with new settings. Typing navigates to the highest-ranked match; the sidebar
diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zig
index a711f7c..cc421b6 100644
--- a/src/control_center/search_index.zig
+++ b/src/control_center/search_index.zig
@@ -150,6 +150,9 @@ const source_entries = [_]SourceEntry{
.{ .page = .appearance, .title = i18n.msg("Apply GTK colors"), .target = "apply_gtk_colors", .keywords = i18n.msg("application colours theme") },
.{ .page = .appearance, .title = i18n.msg("Apply Qt colors"), .target = "apply_qt_colors", .keywords = i18n.msg("application colours theme") },
.{ .page = .appearance, .title = i18n.msg("Launch splash"), .target = "launch_splash", .keywords = i18n.msg("startup welcome animation") },
+ .{ .page = .appearance, .title = i18n.msg("Flames while moving windows"), .target = "effect_window_move", .keywords = i18n.msg("effects fire trail ribbon drag animation") },
+ .{ .page = .appearance, .title = i18n.msg("Flames while resizing windows"), .target = "effect_window_resize", .keywords = i18n.msg("effects fire trail ribbon animation") },
+ .{ .page = .appearance, .title = i18n.msg("Flames when minimizing windows"), .target = "effect_window_minimize", .keywords = i18n.msg("effects fire trail ribbon animation") },
.{ .page = .appearance, .title = i18n.msg("Dodge file drags"), .target = "dodge_file_drags", .keywords = i18n.msg("drag drop windows") },
.{ .page = .appearance, .title = i18n.msg("Dim inactive windows"), .target = "inactive_dim", .keywords = i18n.msg("unfocused darkness") },
.{ .page = .appearance, .title = i18n.msg("Window tabs"), .target = "window_tabs", .keywords = i18n.msg("applications titlebar grouping") },
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index 2c2a16b..3fec82f 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -271,6 +271,8 @@ pub const Section = struct {
anim_enabled_label_children: [2]Widget = undefined,
anim_speed_row_children: [2]Widget = undefined,
reduced_motion_row_children: [2]Widget = undefined,
+ effect_row_children: [3][2]Widget = undefined,
+ effect_label_children: [3][2]Widget = undefined,
font_row_children: [2]Widget = undefined,
radius_row_children: [2]Widget = undefined,
shadow_row_children: [2]Widget = undefined,
@@ -479,6 +481,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
buildColorRows(out, arena, pal);
buildBehaviorRows(out, pal);
+ buildEffectRows(out, pal);
buildFontRows(out, arena, t, pal);
@@ -514,6 +517,9 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .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.effect_row_children[0] },
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.effect_row_children[1] },
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.effect_row_children[2] },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.cursor_row_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.family_row_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.font_row_children },
@@ -556,6 +562,7 @@ const appearance_rows = @import("appearance_rows.zig");
const buildThemeRows = appearance_rows.buildThemeRows;
const buildColorRows = appearance_rows.buildColorRows;
const buildBehaviorRows = appearance_rows.buildBehaviorRows;
+const buildEffectRows = appearance_rows.buildEffectRows;
const buildFontRows = appearance_rows.buildFontRows;
const buildChromeRow = appearance_rows.buildChromeRow;
const inactiveOpacityRow = appearance_rows.inactiveOpacityRow;
@@ -587,6 +594,9 @@ pub const Row = enum {
switcher_style,
drag_feedback,
drag_scale,
+ effect_window_move,
+ effect_window_resize,
+ effect_window_minimize,
cursor,
font_family,
font_size,
@@ -612,6 +622,7 @@ pub const groups = [_]struct { title: ?i18n.Message, rows: []const Row }{
.{ .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, .switcher_style, .drag_feedback, .drag_scale, .dodge_file_drags, .launch_splash } },
+ .{ .title = i18n.msg("Effects"), .rows = &.{ .effect_window_move, .effect_window_resize, .effect_window_minimize } },
.{ .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 252ed81..2ed570f 100644
--- a/src/control_center/sections/appearance_chrome.zig
+++ b/src/control_center/sections/appearance_chrome.zig
@@ -21,6 +21,28 @@ const focus_zoom_labels = @import("appearance.zig").focus_zoom_labels;
const focus_zoom_descriptions = @import("appearance.zig").focus_zoom_descriptions;
const px_window_gap = @import("appearance.zig").px_window_gap;
+/// A flame-effect toggle. Live first (reconfiguring drops any running effect),
+/// then saved; the other two effects keep their state (`Config.setEnabled`).
+pub fn EffectToggle(comptime kind: @import("config").effects.Target) type {
+ return struct {
+ pub fn changed(owner: ?*anyopaque, _: usize, on: bool) void {
+ const server = section(owner).cc.server;
+ const effects = &server.config.effects;
+ const now = switch (kind) {
+ .window_move => effects.window_move,
+ .window_minimize => effects.minimize(),
+ .window_resize => effects.resize(),
+ };
+ if (now.enabled == on) return;
+ const pinned = effects.setEnabled(kind, on);
+ @import("../../effects/window_move.zig").configure(server);
+ setting_save.saveEffect(main.gpa, server.io, server.config.path, effects.*, kind, pinned) catch |err| {
+ std.log.warn("could not save {s} effect: {}", .{ @tagName(kind), err });
+ };
+ }
+ };
+}
+
pub fn ClockStyle(comptime key: []const u8) type {
return struct {
pub fn changed(owner: ?*anyopaque, _: usize, on: bool) void {
diff --git a/src/control_center/sections/appearance_rows.zig b/src/control_center/sections/appearance_rows.zig
index 7cc9bbe..5d0cb47 100644
--- a/src/control_center/sections/appearance_rows.zig
+++ b/src/control_center/sections/appearance_rows.zig
@@ -36,6 +36,7 @@ const onCursorThemePicked = appearance_chrome.onCursorThemePicked;
const onDarkModeChanged = appearance_chrome.onDarkModeChanged;
const onSplashStartupChanged = appearance_chrome.onSplashStartupChanged;
const onDodgeFileDragsChanged = appearance_chrome.onDodgeFileDragsChanged;
+const EffectToggle = appearance_chrome.EffectToggle;
const appearance = @import("appearance.zig");
const segmented_width = appearance.segmented_width;
const font_values = appearance.font_values;
@@ -241,6 +242,27 @@ pub fn buildBehaviorRows(out: *Section, pal: theme.Theme) void {
};
}
+/// Optional flame effects: three independent toggles, off by default. They
+/// only run while Animations are on (and Reduced motion is not).
+pub fn buildEffectRows(out: *Section, pal: theme.Theme) void {
+ const effects = out.cc.server.config.effects;
+ const rows = .{
+ .{ "effect_window_move", i18n.msg("Flames while moving windows"), effects.window_move.enabled, &EffectToggle(.window_move).changed },
+ .{ "effect_window_resize", i18n.msg("Flames while resizing windows"), effects.resize().enabled, &EffectToggle(.window_resize).changed },
+ .{ "effect_window_minimize", i18n.msg("Flames when minimizing windows"), effects.minimize().enabled, &EffectToggle(.window_minimize).changed },
+ };
+ inline for (rows, 0..) |row, i| {
+ out.effect_label_children[i] = .{
+ .{ .kind = .{ .text = .{ .content = row[1].get(), .font_size = theme.global.app_text_size, .weight = 600, .color = pal.fg } } },
+ .{ .kind = .{ .text = .{ .content = i18n.tr("Needs Animations to be on"), .font_size = theme.global.settings_description_size, .color = pal.dim } } },
+ };
+ out.effect_row_children[i] = .{
+ .{ .kind = .container, .direction = .column, .gap = 2, .width = .{ .flex = 1 }, .children = &out.effect_label_children[i] },
+ .{ .name = row[0], .kind = .{ .toggle = .{ .on = row[2], .owner = out, .on_change = row[3] } } },
+ };
+ }
+}
+
/// The UI font, cursor theme, font size, radius, shadow and edge glow rows.
pub fn buildFontRows(out: *Section, arena: std.mem.Allocator, t: theme.Theme, pal: theme.Theme) void {
if (out.font_families == null) {
diff --git a/src/effects/border.zig b/src/effects/border.zig
new file mode 100644
index 0000000..21e0035
--- /dev/null
+++ b/src/effects/border.zig
@@ -0,0 +1,111 @@
+//! Outward glow following the frame outline, using the optional ribbon pass.
+const std = @import("std");
+const ribbon = @import("ribbon.zig");
+const shape = @import("ui").window_shape;
+
+pub fn mesh(width: f32, height: f32, radius: f32, polygon: ?shape.Resolved, reach: f32, strength: f32, preset: ribbon.Preset) ribbon.Geometry {
+ var result: ribbon.Geometry = .{};
+ if (width <= 0 or height <= 0 or reach <= 0 or strength <= 0) return result;
+ result.mesh.edge = 1;
+ result.mesh.color = preset.color;
+ result.mesh.core_color = preset.core_color;
+ result.mesh.color[3] *= preset.opacity;
+ result.mesh.core_color[3] *= preset.opacity;
+ if (polygon) |poly| {
+ var area: f64 = 0;
+ for (poly.points[0..poly.count], 0..) |p, i| {
+ const next = poly.points[(i + 1) % poly.count];
+ area += p[0] * next[1] - next[0] * p[1];
+ }
+ const winding: f32 = if (area >= 0) 1 else -1;
+ for (poly.points[0..poly.count], 0..) |p, i| {
+ const prev = poly.points[(i + poly.count - 1) % poly.count];
+ const next = poly.points[(i + 1) % poly.count];
+ const a = normal(p[0] - prev[0], p[1] - prev[1], winding);
+ const b = normal(next[0] - p[0], next[1] - p[1], winding);
+ // Bound miters at acute corners so glow and damage stay local.
+ const divisor = @max(0.5, 1 + a[0] * b[0] + a[1] * b[1]);
+ pair(&result, @floatCast(p[0]), @floatCast(p[1]), (a[0] + b[0]) / divisor, (a[1] + b[1]) / divisor, reach, strength);
+ }
+ } else {
+ const r = std.math.clamp(radius, 0, @min(width, height) / 2);
+ const centers = [4][2]f32{ .{ width - r, r }, .{ width - r, height - r }, .{ r, height - r }, .{ r, r } };
+ for (centers, 0..) |center, corner| {
+ for (0..9) |step| {
+ const angle = (@as(f32, @floatFromInt(corner)) - 1 + @as(f32, @floatFromInt(step)) / 8) * (std.math.pi / 2.0);
+ const nx = @cos(angle);
+ const ny = @sin(angle);
+ pair(&result, center[0] + nx * r, center[1] + ny * r, nx, ny, reach, strength);
+ }
+ }
+ }
+ // Close the strip with exactly the first pair, avoiding a seam at the join.
+ result.mesh.vertices[result.mesh.count] = result.mesh.vertices[0];
+ result.mesh.vertices[result.mesh.count + 1] = result.mesh.vertices[1];
+ result.mesh.count += 2;
+ result.enclose();
+ return result;
+}
+
+fn normal(dx: f64, dy: f64, winding: f32) [2]f32 {
+ const length = @max(0.001, std.math.hypot(dx, dy));
+ return .{ @as(f32, @floatCast(dy / length)) * winding, -@as(f32, @floatCast(dx / length)) * winding };
+}
+
+/// A glow centred on the fill's outer perimeter, with a small inward overlap.
+/// Unlike a window frame this edge has no solid ring underneath its glow.
+pub fn path(source: []const ribbon.Point, reach: f32, strength: f32, preset: ribbon.Preset) ribbon.Geometry {
+ var result: ribbon.Geometry = .{};
+ if (source.len < 3 or source.len > 63 or reach <= 0 or strength <= 0) return result;
+ var unique: [63]ribbon.Point = undefined;
+ var len: usize = 0;
+ for (source) |point| {
+ if (len > 0 and near(unique[len - 1], point)) continue;
+ unique[len] = point;
+ len += 1;
+ }
+ if (len > 1 and near(unique[0], unique[len - 1])) len -= 1;
+ if (len < 3) return result;
+ const points = unique[0..len];
+ result.mesh.edge = 1;
+ result.mesh.color = preset.color;
+ result.mesh.core_color = preset.core_color;
+ result.mesh.color[3] *= preset.opacity;
+ result.mesh.core_color[3] *= preset.opacity;
+ var area: f64 = 0;
+ for (points, 0..) |p, i| {
+ const next = points[(i + 1) % points.len];
+ area += @as(f64, p.x) * next.y - @as(f64, next.x) * p.y;
+ }
+ const winding: f32 = if (area >= 0) 1 else -1;
+ for (points, 0..) |p, i| {
+ const prev = points[(i + points.len - 1) % points.len];
+ const next = points[(i + 1) % points.len];
+ const a = normal(p.x - prev.x, p.y - prev.y, winding);
+ const b = normal(next.x - p.x, next.y - p.y, winding);
+ const divisor = @max(0.5, 1 + a[0] * b[0] + a[1] * b[1]);
+ const nx = (a[0] + b[0]) / divisor;
+ const ny = (a[1] + b[1]) / divisor;
+ const inward = @min(3, reach * 0.15);
+ const at = result.mesh.count;
+ result.mesh.vertices[at] = .{ p.x - nx * inward, p.y - ny * inward, -inward / reach, strength };
+ result.mesh.vertices[at + 1] = .{ p.x + nx * reach, p.y + ny * reach, 1, strength };
+ result.mesh.count += 2;
+ }
+ result.mesh.vertices[result.mesh.count] = result.mesh.vertices[0];
+ result.mesh.vertices[result.mesh.count + 1] = result.mesh.vertices[1];
+ result.mesh.count += 2;
+ result.enclose();
+ return result;
+}
+
+fn near(a: ribbon.Point, b: ribbon.Point) bool {
+ return @abs(a.x - b.x) < 0.001 and @abs(a.y - b.y) < 0.001;
+}
+
+fn pair(result: *ribbon.Geometry, x: f32, y: f32, nx: f32, ny: f32, reach: f32, strength: f32) void {
+ const i = result.mesh.count;
+ result.mesh.vertices[i] = .{ x, y, 0, strength };
+ result.mesh.vertices[i + 1] = .{ x + nx * reach, y + ny * reach, 1, strength };
+ result.mesh.count += 2;
+}
diff --git a/src/effects/minimize_mesh.zig b/src/effects/minimize_mesh.zig
new file mode 100644
index 0000000..2a3965e
--- /dev/null
+++ b/src/effects/minimize_mesh.zig
@@ -0,0 +1,53 @@
+//! A sheet pulled from its near edge into a narrow, curved tongue. UVs stay
+//! attached to the sheet, so the actual window bends with the flame.
+const std = @import("std");
+const ribbon = @import("ribbon.zig");
+pub const Box = struct { x: f32, y: f32, width: f32, height: f32 };
+
+pub fn mesh(source: Box, target: ribbon.Point, progress: f32, preset: ribbon.Preset) ribbon.Geometry {
+ const p = std.math.clamp(progress, 0, 1);
+ var result: ribbon.Geometry = .{};
+ if (p >= 1) return result;
+ result.mesh.edge = 2;
+ result.mesh.color = preset.color;
+ result.mesh.color[3] *= preset.opacity;
+ result.mesh.core_color = preset.core_color;
+ result.mesh.core_color[3] *= preset.opacity;
+ const above = target.y < source.y + source.height / 2;
+ result.mesh.fade = .{ p, if (above) 1 else 0 };
+ const rows: usize = switch (preset.quality) {
+ .low => 24,
+ .balanced => 48,
+ .high => 64,
+ };
+ for (0..rows) |row| {
+ const v = @as(f32, @floatFromInt(row)) / @as(f32, @floatFromInt(rows - 1));
+ const uv_y = if (above) 1 - v else v;
+ const pull = smooth((p * 1.5 - (1 - v) * 0.58) / 0.92);
+ const remaining = 1 - pull;
+ const original_y = source.y + source.height * uv_y;
+ const y = original_y + (target.y - original_y) * pull;
+ const center = source.x + source.width / 2;
+ const curl = @sin(pull * 2 * std.math.pi) * @sin(p * std.math.pi) *
+ @min(source.width * 0.28, 160) * (0.7 + preset.turbulence);
+ const x = center + (target.x - center) * pull + curl;
+ // The vertex shader uses this width ratio for perspective-correct UVs.
+ const width = source.width * (remaining * remaining + 0.015 * pull * (1 - p));
+ for (0..2) |side| {
+ const u: f32 = if (side == 0) -0.035 else 1.035;
+ result.mesh.vertices[result.mesh.count] = .{ x + (u - 0.5) * width, y, u, uv_y };
+ result.mesh.count += 1;
+ }
+ }
+ result.enclose();
+ return result;
+}
+
+fn smooth(value: f32) f32 {
+ const t = std.math.clamp(value, 0, 1);
+ return t * t * (3 - 2 * t);
+}
+
+test {
+ _ = @import("minimize_mesh_tests.zig");
+}
diff --git a/src/effects/minimize_mesh_tests.zig b/src/effects/minimize_mesh_tests.zig
new file mode 100644
index 0000000..4018ce7
--- /dev/null
+++ b/src/effects/minimize_mesh_tests.zig
@@ -0,0 +1,37 @@
+const std = @import("std");
+const geometry = @import("minimize_mesh.zig");
+const ribbon = @import("ribbon.zig");
+
+test "minimize sheet preserves its initial window and converges to either screen edge" {
+ const source: geometry.Box = .{ .x = -200, .y = 120, .width = 640, .height = 480 };
+ for ([_]ribbon.Point{ .{ .x = 40, .y = 900 }, .{ .x = -80, .y = 20 } }) |target| {
+ for ([_]@import("config").effects.Quality{ .low, .balanced, .high }) |quality| {
+ const initial = geometry.mesh(source, target, 0, .{ .quality = quality });
+ for (initial.mesh.vertices[0..initial.mesh.count]) |v| {
+ const x = @as(f32, @floatFromInt(initial.x)) + v[0] * @as(f32, @floatFromInt(initial.width));
+ const y = @as(f32, @floatFromInt(initial.y)) + v[1] * @as(f32, @floatFromInt(initial.height));
+ try std.testing.expectApproxEqAbs(source.x + v[2] * source.width, x, 0.001);
+ try std.testing.expectApproxEqAbs(source.y + v[3] * source.height, y, 0.001);
+ }
+ const final = geometry.mesh(source, target, 0.999, .{ .quality = quality });
+ for (final.mesh.vertices[0..final.mesh.count]) |v| {
+ try std.testing.expect(v[0] >= 0 and v[0] <= 1 and v[1] >= 0 and v[1] <= 1);
+ const x = @as(f32, @floatFromInt(final.x)) + v[0] * @as(f32, @floatFromInt(final.width));
+ const y = @as(f32, @floatFromInt(final.y)) + v[1] * @as(f32, @floatFromInt(final.height));
+ try std.testing.expectApproxEqAbs(target.x, x, 1);
+ try std.testing.expectApproxEqAbs(target.y, y, 1);
+ }
+ }
+ }
+ try std.testing.expectEqual(@as(u32, 0), geometry.mesh(source, .{ .x = 0, .y = 900 }, 1, .{}).mesh.count);
+}
+
+test "minimize flame pulls the near edge first while retaining the upper body" {
+ const source: geometry.Box = .{ .x = 100, .y = 100, .width = 600, .height = 400 };
+ const geo = geometry.mesh(source, .{ .x = 200, .y = 900 }, 0.4, .{});
+ const v = geo.mesh.vertices;
+ const upper_width = (v[1][0] - v[0][0]) * @as(f32, @floatFromInt(geo.width));
+ const lower_width = (v[geo.mesh.count - 1][0] - v[geo.mesh.count - 2][0]) * @as(f32, @floatFromInt(geo.width));
+ try std.testing.expect(upper_width > 600);
+ try std.testing.expect(lower_width < 100);
+}
diff --git a/src/effects/move_heading.zig b/src/effects/move_heading.zig
new file mode 100644
index 0000000..b531866
--- /dev/null
+++ b/src/effects/move_heading.zig
@@ -0,0 +1,33 @@
+//! Stable trailing-side selection. Small diagonal changes must not reset trails.
+const std = @import("std");
+const Self = @This();
+
+value: u2 = 0,
+x: f32 = 0,
+y: f32 = 0,
+initialized: bool = false,
+
+pub fn update(self: *Self, dx: f32, dy: f32) bool {
+ const distance = std.math.hypot(dx, dy);
+ if (distance < 0.5) return false;
+ // Average over a short distance, independent of event and refresh rates.
+ // No clock advances this filter when the pointer is stationary.
+ const blend = if (self.initialized) 1 - @exp(-distance / 12) else 1;
+ self.x += (dx / distance - self.x) * blend;
+ self.y += (dy / distance - self.y) * blend;
+ const horizontal = @abs(self.x) >= @abs(self.y);
+ const next: u2 = if (horizontal) (if (self.x >= 0) @as(u2, 0) else 1) else (if (self.y >= 0) @as(u2, 2) else 3);
+ if (self.initialized and horizontal != (self.value < 2)) {
+ const previous_axis = if (self.value < 2) @abs(self.x) else @abs(self.y);
+ const next_axis = if (horizontal) @abs(self.x) else @abs(self.y);
+ if (next_axis < previous_axis * 1.4) return false;
+ }
+ self.initialized = true;
+ const changed = self.value != next;
+ self.value = next;
+ return changed;
+}
+
+test {
+ _ = @import("move_heading_tests.zig");
+}
diff --git a/src/effects/move_heading_tests.zig b/src/effects/move_heading_tests.zig
new file mode 100644
index 0000000..23bc732
--- /dev/null
+++ b/src/effects/move_heading_tests.zig
@@ -0,0 +1,22 @@
+const std = @import("std");
+const Heading = @import("move_heading.zig");
+
+test "drag heading stays attached through diagonal jitter but follows deliberate turns" {
+ var heading: Heading = .{};
+ _ = heading.update(10, 9);
+ for (0..30) |i| {
+ const dx: f32 = if (i % 2 == 0) 9 else 10;
+ const dy: f32 = if (i % 2 == 0) 10 else 9;
+ try std.testing.expect(!heading.update(dx, dy));
+ try std.testing.expectEqual(@as(u2, 0), heading.value);
+ }
+ for (0..6) |_| _ = heading.update(0, 10);
+ try std.testing.expectEqual(@as(u2, 2), heading.value);
+ for (0..6) |_| _ = heading.update(-10, 0);
+ try std.testing.expectEqual(@as(u2, 1), heading.value);
+ for (0..6) |_| _ = heading.update(0, -10);
+ try std.testing.expectEqual(@as(u2, 3), heading.value);
+ const stopped = heading;
+ try std.testing.expect(!heading.update(0, 0));
+ try std.testing.expectEqualDeep(stopped, heading);
+}
diff --git a/src/effects/move_trail.zig b/src/effects/move_trail.zig
new file mode 100644
index 0000000..5f25ec1
--- /dev/null
+++ b/src/effects/move_trail.zig
@@ -0,0 +1,32 @@
+//! A faint sheet joining the two drag flames, sharing their folds and fade.
+const ribbon = @import("ribbon.zig");
+
+pub fn between(trails: *const [2]ribbon.Geometry) ribbon.Geometry {
+ const count = trails[0].mesh.count;
+ if (count < 4 or count != trails[1].mesh.count) return .{};
+ var result: ribbon.Geometry = .{};
+ result.mesh = .{
+ .count = count,
+ .edge = 4,
+ .color = trails[0].mesh.color,
+ .core_color = trails[0].mesh.core_color,
+ .fade = trails[0].mesh.fade,
+ };
+ // Both paths use the same history and row count. Join their row centres
+ // in host coordinates so the sheet follows turns, flutter and soft caps.
+ var row: usize = 0;
+ while (row < count) : (row += 2) {
+ for (trails, 0..) |*trail, side| {
+ const a = trail.mesh.vertices[row];
+ const b = trail.mesh.vertices[row + 1];
+ result.mesh.vertices[row + side] = .{
+ @as(f32, @floatFromInt(trail.x)) + (a[0] + b[0]) * 0.5 * @as(f32, @floatFromInt(trail.width)),
+ @as(f32, @floatFromInt(trail.y)) + (a[1] + b[1]) * 0.5 * @as(f32, @floatFromInt(trail.height)),
+ if (side == 0) -1 else 1,
+ a[3],
+ };
+ }
+ }
+ result.enclose();
+ return result;
+}
diff --git a/src/effects/resize_follow.zig b/src/effects/resize_follow.zig
new file mode 100644
index 0000000..87ea6bd
--- /dev/null
+++ b/src/effects/resize_follow.zig
@@ -0,0 +1,40 @@
+//! A bounded, monotonic follower for interactive client sizes. Sampling is
+//! analytic, so refresh rate and configure acknowledgements do not change it.
+const std = @import("std");
+const Size = @import("../resize.zig").ClientSize;
+const Self = @This();
+
+from: [2]f64,
+target: Size,
+started: i64,
+
+pub fn init(size: Size, now: i64) Self {
+ return .{ .from = .{ @floatFromInt(size.width), @floatFromInt(size.height) }, .target = size, .started = now };
+}
+
+pub fn retarget(self: *Self, size: Size, now: i64, speed: f32) void {
+ if (std.meta.eql(self.target, size)) return;
+ self.from = self.sample(now, speed);
+ self.target = size;
+ self.started = now;
+}
+
+fn sample(self: Self, now: i64, speed: f32) [2]f64 {
+ const elapsed = @as(f64, @floatFromInt(@max(0, now - self.started))) * speed;
+ const remaining = if (speed <= 0 or elapsed >= 800) 0 else @exp(-elapsed / 110);
+ const goal = [2]f64{ @floatFromInt(self.target.width), @floatFromInt(self.target.height) };
+ return .{ goal[0] + (self.from[0] - goal[0]) * remaining, goal[1] + (self.from[1] - goal[1]) * remaining };
+}
+
+pub fn value(self: Self, now: i64, speed: f32) Size {
+ const size = self.sample(now, speed);
+ return .{ .width = @intFromFloat(@round(size[0])), .height = @intFromFloat(@round(size[1])) };
+}
+
+pub fn pending(self: Self, now: i64, speed: f32) bool {
+ return !std.meta.eql(self.value(now, speed), self.target);
+}
+
+test {
+ _ = @import("resize_follow_tests.zig");
+}
diff --git a/src/effects/resize_follow_tests.zig b/src/effects/resize_follow_tests.zig
new file mode 100644
index 0000000..1573ac3
--- /dev/null
+++ b/src/effects/resize_follow_tests.zig
@@ -0,0 +1,30 @@
+const std = @import("std");
+const Follow = @import("resize_follow.zig");
+
+test "resize follows behind, finishes exactly and never overshoots on reversal" {
+ var follow = Follow.init(.{ .width = 400, .height = 300 }, 1000);
+ follow.retarget(.{ .width = 600, .height = 400 }, 1000, 1);
+ try std.testing.expectEqual(@as(i32, 400), follow.value(1000, 1).width);
+ const middle = follow.value(1055, 1);
+ try std.testing.expect(middle.width > 400 and middle.width < 500);
+ try std.testing.expect(follow.pending(1055, 1));
+ follow.retarget(.{ .width = 320, .height = 240 }, 1055, 1);
+ try std.testing.expectEqual(middle, follow.value(1055, 1));
+ for (0..9) |i| {
+ const size = follow.value(1055 + @as(i64, @intCast(i)) * 100, 1);
+ try std.testing.expect(size.width >= 320 and size.width <= middle.width);
+ try std.testing.expect(size.height >= 240 and size.height <= middle.height);
+ }
+ try std.testing.expectEqual(follow.target, follow.value(1855, 1));
+ try std.testing.expect(!follow.pending(1855, 1));
+ try std.testing.expectEqual(follow.target, follow.value(1055, 0));
+}
+
+test "resize sampling is independent of frame rate and respects animation speed" {
+ var a = Follow.init(.{ .width = 400, .height = 300 }, 0);
+ a.retarget(.{ .width = 800, .height = 500 }, 0, 1);
+ const b = a;
+ for (0..100) |i| _ = a.value(@intCast(i * 2), 1);
+ try std.testing.expectEqual(b.value(200, 1), a.value(200, 1));
+ try std.testing.expectEqual(a.value(200, 1), a.value(100, 2));
+}
diff --git a/src/effects/resize_mesh.zig b/src/effects/resize_mesh.zig
new file mode 100644
index 0000000..b21f227
--- /dev/null
+++ b/src/effects/resize_mesh.zig
@@ -0,0 +1,40 @@
+//! A filled elastic membrane and its glow, built from the same paired outlines.
+const ribbon = @import("ribbon.zig");
+const border = @import("border.zig");
+const outline = @import("resize_outline.zig");
+const Polygon = @import("ui").window_shape.Resolved;
+pub const Box = outline.Box;
+pub const Pull = outline.Pull;
+pub const Meshes = struct { fill: ribbon.Geometry = .{}, edge: ribbon.Geometry = .{} };
+
+pub fn build(width: f32, height: f32, target: Box, radius: f32, current_polygon: ?Polygon, target_polygon: ?Polygon, pull: Pull, reach: f32, strength: f32, phase: f32, preset: ribbon.Preset) Meshes {
+ var result: Meshes = .{};
+ if (strength <= 0 or width <= 0 or height <= 0 or target.width <= 0 or target.height <= 0) return result;
+ if (@abs(target.x) < 0.25 and @abs(target.y) < 0.25 and
+ @abs(target.width - width) < 0.25 and @abs(target.height - height) < 0.25) return result;
+ const points = outline.resolve(width, height, target, radius, current_polygon, target_polygon, pull, preset.quality);
+ if (points.len < 3) return result;
+ const band = &result.fill;
+ band.mesh.edge = 3;
+ band.mesh.fade = .{ strength, phase };
+ band.mesh.color = preset.color;
+ band.mesh.core_color = preset.core_color;
+ band.mesh.color[3] *= preset.opacity;
+ band.mesh.core_color[3] *= preset.opacity;
+ for (0..points.len + 1) |i| {
+ const index = i % points.len;
+ const t = @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(points.len));
+ const p = points.current[index];
+ const q = points.leading[index];
+ band.mesh.vertices[i * 2] = .{ p.x, p.y, -1, t };
+ band.mesh.vertices[i * 2 + 1] = .{ q.x, q.y, 1, t };
+ }
+ band.mesh.count = @intCast((points.len + 1) * 2);
+ band.enclose();
+ result.edge = border.path(points.leading[0..points.len], reach, strength, preset);
+ return result;
+}
+
+test {
+ _ = @import("resize_mesh_tests.zig");
+}
diff --git a/src/effects/resize_mesh_tests.zig b/src/effects/resize_mesh_tests.zig
new file mode 100644
index 0000000..9c71dcd
--- /dev/null
+++ b/src/effects/resize_mesh_tests.zig
@@ -0,0 +1,96 @@
+const std = @import("std");
+const mesh = @import("resize_mesh.zig");
+const outline = @import("resize_outline.zig");
+const ribbon = @import("ribbon.zig");
+const Edges = @import("../resize.zig").Edges;
+
+fn position(geo: ribbon.Geometry, i: usize) ribbon.Point {
+ const v = geo.mesh.vertices[i];
+ return .{ .x = @as(f32, @floatFromInt(geo.x)) + v[0] * @as(f32, @floatFromInt(geo.width)), .y = @as(f32, @floatFromInt(geo.y)) + v[1] * @as(f32, @floatFromInt(geo.height)) };
+}
+
+test "elastic resize fill and glow share a closed boundary at all corners, edges and qualities" {
+ const cases = [_]Edges{
+ .{ .right = true, .bottom = true }, .{ .left = true, .bottom = true },
+ .{ .right = true, .top = true }, .{ .left = true, .top = true },
+ .{ .right = true }, .{ .left = true },
+ .{ .top = true }, .{ .bottom = true },
+ };
+ for (cases) |edges| for ([_]f32{ -1, 1 }) |direction| {
+ const dx: f32 = if (edges.right or edges.left) 100 * direction else 0;
+ const dy: f32 = if (edges.bottom or edges.top) 60 * direction else 0;
+ const target: mesh.Box = .{ .x = if (edges.left) -dx else 0, .y = if (edges.top) -dy else 0, .width = 400 + dx, .height = 300 + dy };
+ for ([_]@import("config").effects.Quality{ .low, .balanced, .high }) |quality| {
+ const result = mesh.build(400, 300, target, 12, null, null, .{ .edges = edges, .anchor = .{ .x = 0.25, .y = 0.75 } }, 18, 1, 0, .{ .quality = quality });
+ try std.testing.expect(result.fill.mesh.count > 4 and result.fill.mesh.count <= 128);
+ try std.testing.expect(result.edge.mesh.count > 4 and result.edge.mesh.count <= result.fill.mesh.count);
+ for ([_]ribbon.Geometry{ result.fill, result.edge }) |geo| {
+ for (geo.mesh.vertices[0..geo.mesh.count]) |v| {
+ try std.testing.expect(v[0] >= 0 and v[0] <= 1 and v[1] >= 0 and v[1] <= 1);
+ }
+ for (0..2) |side| for (0..2) |axis|
+ try std.testing.expectApproxEqAbs(geo.mesh.vertices[side][axis], geo.mesh.vertices[geo.mesh.count - 2 + side][axis], 0.0001);
+ }
+ var i: usize = 0;
+ while (i < result.fill.mesh.count) : (i += 2) {
+ const fill_edge = position(result.fill, i + 1);
+ var joined = false;
+ var j: usize = 0;
+ while (j < result.edge.mesh.count) : (j += 2) {
+ const a = position(result.edge, j);
+ const b = position(result.edge, j + 1);
+ const from = result.edge.mesh.vertices[j][2];
+ const t = -from / (1 - from);
+ const x = a.x + (b.x - a.x) * t;
+ const y = a.y + (b.y - a.y) * t;
+ if (@abs(fill_edge.x - x) < 0.001 and @abs(fill_edge.y - y) < 0.001) joined = true;
+ }
+ try std.testing.expect(joined);
+ try std.testing.expect(fill_edge.x >= @min(0, target.x) - 0.001 and fill_edge.x <= @max(400, target.x + target.width) + 0.001);
+ try std.testing.expect(fill_edge.y >= @min(0, target.y) - 0.001 and fill_edge.y <= @max(300, target.y + target.height) + 0.001);
+ }
+ }
+ };
+}
+
+test "corner pull stays attached at the far ends and stretches both adjacent edges" {
+ const points = outline.resolve(400, 300, .{ .x = 0, .y = 0, .width = 600, .height = 330 }, 12, null, null, .{ .edges = .{ .right = true, .bottom = true } }, .balanced);
+ var side = false;
+ var bottom = false;
+ var tip = false;
+ for (points.current[0..points.len], points.leading[0..points.len]) |p, q| {
+ if (p.y <= 12 or p.x <= 12) {
+ try std.testing.expectApproxEqAbs(p.x, q.x, 0.001);
+ try std.testing.expectApproxEqAbs(p.y, q.y, 0.001);
+ }
+ if (@abs(p.x - 400) < 0.001 and @abs(p.y - 150) < 0.001) {
+ side = true;
+ try std.testing.expectApproxEqAbs(@as(f32, 450), q.x, 0.001);
+ try std.testing.expectApproxEqAbs(@as(f32, 171), q.y, 0.001);
+ }
+ if (@abs(p.x - 200) < 0.001 and @abs(p.y - 300) < 0.001) {
+ bottom = true;
+ try std.testing.expectApproxEqAbs(@as(f32, 306), q.x, 0.001);
+ try std.testing.expectApproxEqAbs(@as(f32, 307.5), q.y, 0.001);
+ }
+ if (@abs(p.x - 400) < 0.001 and @abs(p.y - 288) < 0.001) {
+ tip = true;
+ try std.testing.expectApproxEqAbs(@as(f32, 600), q.x, 0.001);
+ try std.testing.expectApproxEqAbs(@as(f32, 330), q.y, 0.001);
+ }
+ }
+ try std.testing.expect(side and bottom and tip);
+}
+
+test "polygon outlines are supported and a caught-up resize has no membrane" {
+ const shape = @import("ui").window_shape;
+ const spec = (try shape.parse("0 16, 16 0, -0 0, -0 -0, 0 -0")).?;
+ const a = shape.resolve(spec, 400, 300, 1);
+ const b = shape.resolve(spec, 500, 350, 1);
+ const pull: mesh.Pull = .{ .edges = .{ .right = true, .bottom = true } };
+ const result = mesh.build(400, 300, .{ .x = 0, .y = 0, .width = 500, .height = 350 }, 12, a, b, pull, 18, 1, 0, .{});
+ try std.testing.expect(result.fill.mesh.count > 4 and result.fill.mesh.count <= 128);
+ const idle = mesh.build(400, 300, .{ .x = 0, .y = 0, .width = 400, .height = 300 }, 12, null, null, pull, 18, 1, 0, .{});
+ try std.testing.expectEqual(@as(u32, 0), idle.fill.mesh.count);
+ try std.testing.expectEqual(@as(u32, 0), idle.edge.mesh.count);
+}
diff --git a/src/effects/resize_outline.zig b/src/effects/resize_outline.zig
new file mode 100644
index 0000000..f994a7c
--- /dev/null
+++ b/src/effects/resize_outline.zig
@@ -0,0 +1,148 @@
+//! An elastic perimeter: fixed edges stay on the live window, while the grabbed
+//! corner (or point on an edge) pulls the adjacent sides toward the target.
+const std = @import("std");
+const ribbon = @import("ribbon.zig");
+const Polygon = @import("ui").window_shape.Resolved;
+const Point = ribbon.Point;
+pub const Box = struct { x: f32, y: f32, width: f32, height: f32 };
+pub const Pull = struct {
+ edges: @import("../resize.zig").Edges,
+ // Fractional grab position on the original window, for a single-edge drag.
+ anchor: Point = .{ .x = 0.5, .y = 0.5 },
+};
+pub const Outline = struct {
+ current: [63]Point = undefined,
+ leading: [63]Point = undefined,
+ len: usize = 0,
+
+ fn append(self: *Outline, p: Point, q: Point, width: f32, height: f32, radius: f32, pull: Pull) void {
+ const u = fraction(p.x, width, radius);
+ const v = fraction(p.y, height, radius);
+ const e = pull.edges;
+ const horizontal = e.left or e.right;
+ const vertical = e.top or e.bottom;
+ // Use the transverse coordinate for the pull, not a shared XY weight:
+ // this keeps motion along an edge monotonic even during a deep shrink.
+ const wx = if (!horizontal) 0 else if (vertical)
+ square(if (e.top) 1 - v else v)
+ else
+ bell(v, fraction(pull.anchor.y * height, height, radius));
+ const wy = if (!vertical) 0 else if (horizontal)
+ square(if (e.left) 1 - u else u)
+ else
+ bell(u, fraction(pull.anchor.x * width, width, radius));
+ const leading: Point = .{ .x = p.x + (q.x - p.x) * wx, .y = p.y + (q.y - p.y) * wy };
+ if (self.len > 0 and std.meta.eql(self.current[self.len - 1], p) and std.meta.eql(self.leading[self.len - 1], leading)) return;
+ std.debug.assert(self.len < self.current.len);
+ self.current[self.len] = p;
+ self.leading[self.len] = leading;
+ self.len += 1;
+ }
+};
+
+pub fn resolve(width: f32, height: f32, target: Box, radius: f32, current_polygon: ?Polygon, target_polygon: ?Polygon, pull: Pull, quality: @import("config").effects.Quality) Outline {
+ var result: Outline = .{};
+ if ((pull.edges.left and pull.edges.right) or (pull.edges.top and pull.edges.bottom)) return result;
+ if (current_polygon) |a| {
+ const b = target_polygon orelse return result;
+ if (a.count != b.count or a.count < 3) return result;
+ const budget: usize = switch (quality) {
+ .low => 31,
+ .balanced => 59,
+ .high => 63,
+ };
+ const steps = @max(1, budget / a.count);
+ for (0..a.count) |i| {
+ const next = (i + 1) % a.count;
+ for (0..steps) |j| {
+ const t = @as(f32, @floatFromInt(j)) / @as(f32, @floatFromInt(steps));
+ const p = mix(polyPoint(a, i), polyPoint(a, next), t);
+ var q = mix(polyPoint(b, i), polyPoint(b, next), t);
+ q.x += target.x;
+ q.y += target.y;
+ result.append(p, q, width, height, 0, pull);
+ }
+ }
+ } else rounded(&result, width, height, target, radius, pull, quality);
+ return result;
+}
+
+fn rounded(result: *Outline, width: f32, height: f32, target: Box, radius: f32, pull: Pull, quality: @import("config").effects.Quality) void {
+ const r = std.math.clamp(radius, 0, @min(width, height) / 2);
+ const tr = std.math.clamp(radius, 0, @min(target.width, target.height) / 2);
+ const arc_steps: usize = switch (quality) {
+ .low => 2,
+ .balanced => 4,
+ .high => 5,
+ };
+ const corner_grab = (pull.edges.left or pull.edges.right) and (pull.edges.top or pull.edges.bottom);
+ var target_radii: [4]f32 = @splat(tr);
+ if (corner_grab) {
+ const dx = target.x + (if (pull.edges.right) target.width - width else 0);
+ const dy = target.y + (if (pull.edges.bottom) target.height - height else 0);
+ const strain = std.math.clamp(std.math.hypot(dx, dy) / @max(1, r * 4), 0, 1);
+ const corner: usize = if (pull.edges.right) (if (pull.edges.top) @as(usize, 0) else 1) else (if (pull.edges.bottom) @as(usize, 2) else 3);
+ // The pulled corner becomes a point under tension, returning to the
+ // window's radius as the real size catches up.
+ target_radii[corner] *= 1 - strain * strain * (3 - 2 * strain);
+ }
+ const curve_steps: usize = (if (quality == .low) @as(usize, 10) else 20) * (if (corner_grab) @as(usize, 1) else 2);
+ const curved = [4]bool{ pull.edges.right, pull.edges.bottom, pull.edges.left, pull.edges.top };
+ for (0..4) |corner| {
+ for (0..arc_steps + 1) |step| {
+ const angle = (@as(f32, @floatFromInt(corner)) - 1 + @as(f32, @floatFromInt(step)) / @as(f32, @floatFromInt(arc_steps))) * std.math.pi / 2;
+ const p = arc(width, height, r, corner, angle);
+ const q = translated(arc(target.width, target.height, target_radii[corner], corner, angle), target);
+ result.append(p, q, width, height, r, pull);
+ }
+ const angle = @as(f32, @floatFromInt(corner)) * std.math.pi / 2;
+ const next = (corner + 1) % 4;
+ const a = arc(width, height, r, corner, angle);
+ const b = arc(width, height, r, next, angle);
+ const ta = translated(arc(target.width, target.height, target_radii[corner], corner, angle), target);
+ const tb = translated(arc(target.width, target.height, target_radii[next], next, angle), target);
+ const steps: usize = if (curved[corner]) curve_steps else 1;
+ for (1..steps) |step| {
+ var t = @as(f32, @floatFromInt(step)) / @as(f32, @floatFromInt(steps));
+ if (!corner_grab) {
+ // Include the exact grab point, even if it is off-centre.
+ const at = switch (corner) {
+ 0 => fraction(pull.anchor.y * height, height, r),
+ 1 => 1 - fraction(pull.anchor.x * width, width, r),
+ 2 => 1 - fraction(pull.anchor.y * height, height, r),
+ else => fraction(pull.anchor.x * width, width, r),
+ };
+ t = if (t <= 0.5) at * t * 2 else at + (1 - at) * (t - 0.5) * 2;
+ }
+ result.append(mix(a, b, t), mix(ta, tb, t), width, height, r, pull);
+ }
+ }
+}
+
+fn arc(width: f32, height: f32, radius: f32, corner: usize, angle: f32) Point {
+ return .{ .x = (if (corner < 2) width - radius else radius) + @cos(angle) * radius, .y = (if (corner == 0 or corner == 3) radius else height - radius) + @sin(angle) * radius };
+}
+
+fn polyPoint(poly: Polygon, i: usize) Point {
+ return .{ .x = @floatCast(poly.points[i][0]), .y = @floatCast(poly.points[i][1]) };
+}
+
+fn translated(p: Point, target: Box) Point {
+ return .{ .x = p.x + target.x, .y = p.y + target.y };
+}
+
+fn mix(a: Point, b: Point, t: f32) Point {
+ return .{ .x = a.x + (b.x - a.x) * t, .y = a.y + (b.y - a.y) * t };
+}
+
+fn fraction(value: f32, extent: f32, radius: f32) f32 {
+ return std.math.clamp((value - radius) / @max(1, extent - 2 * radius), 0, 1);
+}
+
+fn square(x: f32) f32 {
+ return x * x;
+}
+
+fn bell(value: f32, at: f32) f32 {
+ return square(if (value <= at) value / @max(0.001, at) else (1 - value) / @max(0.001, 1 - at));
+}
diff --git a/src/effects/ribbon.zig b/src/effects/ribbon.zig
new file mode 100644
index 0000000..3797c32
--- /dev/null
+++ b/src/effects/ribbon.zig
@@ -0,0 +1,251 @@
+//! Bounded, time-based trail geometry, reusable by any point/edge/path emitter.
+//! Samples use the caller's coordinate space; mesh() maps them into a scene node.
+const std = @import("std");
+pub const Preset = @import("config").effects.Preset;
+pub const Point = struct { x: f32, y: f32 };
+// Keep the moving history long; a stopped trail clears quickly from its tail.
+pub const stop_fade_ms: u32 = 450;
+const Sample = struct { p: Point, time: i64, travel: f32 };
+pub const Mesh = extern struct {
+ count: u32 = 0,
+ vertices: [128][4]f32 = @splat(@splat(0)),
+ color: [4]f32 = @splat(0),
+ core_color: [4]f32 = @splat(0),
+ edge: u32 = 0,
+ fade: [2]f32 = .{ 1, 1 },
+};
+pub const Geometry = struct {
+ mesh: Mesh = .{},
+ x: i32 = 0,
+ y: i32 = 0,
+ width: i32 = 1,
+ height: i32 = 1,
+
+ /// Enclose every vertex (including the glow) before publishing damage.
+ pub fn enclose(self: *Geometry) void {
+ if (self.mesh.count == 0) return;
+ var low: Point = .{ .x = std.math.inf(f32), .y = std.math.inf(f32) };
+ var high: Point = .{ .x = -std.math.inf(f32), .y = -std.math.inf(f32) };
+ for (self.mesh.vertices[0..self.mesh.count]) |v| {
+ low.x = @min(low.x, v[0]);
+ low.y = @min(low.y, v[1]);
+ high.x = @max(high.x, v[0]);
+ high.y = @max(high.y, v[1]);
+ }
+ self.x = @intFromFloat(@floor(low.x) - 1);
+ self.y = @intFromFloat(@floor(low.y) - 1);
+ self.width = @intFromFloat(@ceil(high.x) + 1 - @as(f32, @floatFromInt(self.x)));
+ self.height = @intFromFloat(@ceil(high.y) + 1 - @as(f32, @floatFromInt(self.y)));
+ for (self.mesh.vertices[0..self.mesh.count]) |*v| {
+ v[0] = (v[0] - @as(f32, @floatFromInt(self.x))) / @as(f32, @floatFromInt(self.width));
+ v[1] = (v[1] - @as(f32, @floatFromInt(self.y))) / @as(f32, @floatFromInt(self.height));
+ }
+ }
+};
+pub const Path = struct {
+ samples: [64]Sample = undefined,
+ len: usize = 0,
+ last: ?Point = null,
+ travel: f32 = 0,
+ flutter_phase: f32 = 0,
+ flutter_tick: ?i64 = null,
+
+ /// Advance the wind once per presented frame with real drag movement.
+ /// Stationary frames remember the time without advancing the folds, so
+ /// resuming does not jump through the paused interval.
+ pub fn tickFlutter(self: *Path, now: i64, moving: bool) void {
+ if (self.len < 2) {
+ self.flutter_tick = null;
+ return;
+ }
+ if (moving) if (self.flutter_tick) |last| {
+ const elapsed: f32 = @floatFromInt(@max(0, now - last));
+ // Both wave frequencies (1 and 1.7) repeat after 20 pi.
+ self.flutter_phase = @mod(self.flutter_phase + elapsed * 0.004, 20 * std.math.pi);
+ };
+ self.flutter_tick = now;
+ }
+
+ pub fn push(self: *Path, p: Point, now: i64, preset: Preset) void {
+ if (self.last) |last| {
+ const distance = std.math.hypot(p.x - last.x, p.y - last.y);
+ if (distance < 0.5) return;
+ self.expire(now, preset.lifetime_ms);
+ // Teleports and restored geometry must never make a screen-wide streak.
+ if (distance > preset.max_length_px) {
+ self.len = 0;
+ self.travel = 0;
+ } else self.travel += distance;
+ }
+ self.last = p;
+ const cap: usize = switch (preset.quality) {
+ .low => 16,
+ .balanced => 32,
+ .high => 64,
+ };
+ // Coalesce high-rate input into time buckets without extending the
+ // history on a stationary pointer. Quality changes detail, not lifetime.
+ // Reserve both endpoints so capacity does not discard a live tail.
+ const quantum: i64 = @max(1, std.math.divCeil(i64, preset.lifetime_ms, @intCast(cap - 2)) catch unreachable);
+ self.trimTime(now - preset.lifetime_ms);
+ // Keep the first point: even a long-lived preset must start drawing on
+ // the first motion rather than waiting for its next history bucket.
+ if (self.len > 1 and @divFloor(self.samples[self.len - 1].time, quantum) == @divFloor(now, quantum)) self.len -= 1;
+ if (self.len == cap) self.dropFirst();
+ self.samples[self.len] = .{ .p = p, .time = now, .travel = self.travel };
+ self.len += 1;
+ var distance: f32 = 0;
+ var i = self.len - 1;
+ while (i > 0) {
+ const segment = std.math.hypot(self.samples[i].p.x - self.samples[i - 1].p.x, self.samples[i].p.y - self.samples[i - 1].p.y);
+ if (distance + segment >= preset.max_length_px) {
+ self.startAt(i - 1, 1 - (preset.max_length_px - distance) / segment);
+ break;
+ }
+ distance += segment;
+ i -= 1;
+ }
+ }
+
+ fn dropFirst(self: *Path) void {
+ self.len -= 1;
+ std.mem.copyForwards(Sample, self.samples[0..self.len], self.samples[1 .. self.len + 1]);
+ }
+
+ pub fn expire(self: *Path, now: i64, lifetime: u32) void {
+ // At rest the whole shape stays fixed while its opacity fades. Dropping
+ // individual samples here would shorten and re-shape a stationary tail.
+ if (self.len > 0 and now - self.samples[self.len - 1].time >= @min(lifetime, stop_fade_ms)) self.* = .{};
+ }
+
+ fn trimTime(self: *Path, cutoff: i64) void {
+ while (self.len > 1 and self.samples[1].time <= cutoff) self.dropFirst();
+ if (self.len < 2 or self.samples[0].time >= cutoff) return;
+ const a = self.samples[0].time;
+ const b = self.samples[1].time;
+ self.startAt(0, @as(f32, @floatFromInt(cutoff - a)) / @as(f32, @floatFromInt(b - a)));
+ }
+
+ fn startAt(self: *Path, index: usize, t: f32) void {
+ const a = self.samples[index];
+ const b = self.samples[index + 1];
+ self.len -= index;
+ std.mem.copyForwards(Sample, self.samples[0..self.len], self.samples[index .. index + self.len]);
+ self.samples[0] = .{
+ .p = .{ .x = a.p.x + (b.p.x - a.p.x) * t, .y = a.p.y + (b.p.y - a.p.y) * t },
+ .time = a.time + @as(i64, @intFromFloat(@as(f32, @floatFromInt(b.time - a.time)) * t)),
+ .travel = a.travel + (b.travel - a.travel) * t,
+ };
+ }
+
+ pub fn mesh(self: *const Path, now: i64, preset: Preset, origin: Point, scale: f32, seed: f32, source_half: ?Point) Geometry {
+ var result: Geometry = .{};
+ if (self.len < 2 or scale <= 0) return result;
+ result.mesh.color = preset.color;
+ result.mesh.core_color = preset.core_color;
+ result.mesh.color[3] *= preset.opacity;
+ result.mesh.core_color[3] *= preset.opacity;
+ const first = self.samples[0].time;
+ const last = self.samples[self.len - 1].time;
+ const lifetime: f32 = @floatFromInt(preset.lifetime_ms);
+ const fade_time: f32 = @floatFromInt(@min(preset.lifetime_ms, stop_fade_ms));
+ if (@as(f32, @floatFromInt(now - last)) >= fade_time) return .{};
+ // x retains the history's tail opacity; y drives a tail-to-head wipe.
+ result.mesh.fade = .{
+ std.math.clamp(1 - @as(f32, @floatFromInt(now - first)) / lifetime, 0, 1),
+ std.math.clamp(1 - @as(f32, @floatFromInt(now - last)) / fade_time, 0, 1),
+ };
+ const count: usize = switch (preset.quality) {
+ .low => 16,
+ .balanced => 48,
+ .high => 63, // reserve the last pair for the head's soft cap
+ };
+ // Distance sampling keeps existing folds stable when a history bucket
+ // gains a point; sample-count spacing used to redistribute every row.
+ var lengths: [64]f32 = undefined;
+ lengths[0] = 0;
+ for (1..self.len) |i| {
+ const a = self.samples[i - 1].p;
+ const b = self.samples[i].p;
+ lengths[i] = lengths[i - 1] + std.math.hypot(b.x - a.x, b.y - a.y);
+ }
+ const total = lengths[self.len - 1];
+ if (total < 0.001) return .{};
+ var index: usize = 0;
+ for (0..count) |i| {
+ const progress = @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(count - 1));
+ const along = progress * total;
+ while (index + 2 < self.len and lengths[index + 1] < along) index += 1;
+ const span = @max(0.001, lengths[index + 1] - lengths[index]);
+ const t = std.math.clamp((along - lengths[index]) / span, 0, 1);
+ const a = self.samples[index];
+ const b = self.samples[index + 1];
+ // Resample the path and its tangent, keeping both endpoints exact.
+ // Chord-length tangents handle uneven input spacing without the
+ // overshoot caused by treating a short segment like a long one.
+ const before = self.samples[index -| 1].p;
+ const after = self.samples[@min(index + 2, self.len - 1)].p;
+ const before_span = span / @max(0.001, lengths[index + 1] - lengths[index -| 1]);
+ const after_span = span / @max(0.001, lengths[@min(index + 2, self.len - 1)] - lengths[index]);
+ const x_curve = curve(a.p.x, b.p.x, (b.p.x - before.x) * before_span, (after.x - a.p.x) * after_span, t);
+ const y_curve = curve(a.p.y, b.p.y, (b.p.y - before.y) * before_span, (after.y - a.p.y) * after_span, t);
+ const point: Point = .{ .x = x_curve[0], .y = y_curve[0] };
+ const dx = x_curve[1];
+ const dy = y_curve[1];
+ const length = @max(0.001, std.math.hypot(dx, dy));
+ const nx = -dy / length;
+ const ny = dx / length;
+ // Material coordinates depend on distance, not current age.
+ // Fading cannot collapse the two sources or slide the merge point.
+ // Wind advances independently of drag distance. The material
+ // coordinate keeps the spatial folds stable as history changes.
+ const travel = a.travel + (b.travel - a.travel) * t;
+ const phase = self.flutter_phase + travel * 0.02 + seed;
+ const wave = (@sin(phase) + 0.3 * @sin(phase * 1.7 + seed)) * preset.width_px * 2 * preset.turbulence * (1 - progress);
+ const half = preset.width_px * (0.65 + 0.35 * progress);
+ const sources = source_half orelse Point{ .x = nx * preset.width_px * source_across, .y = ny * preset.width_px * source_across };
+ const attach = std.math.clamp((progress - 0.65) / 0.35, 0, 1);
+ const blend = attach * attach * (3 - 2 * attach);
+ // At the head, the two bright creases land exactly on the source
+ // points even when the motion tangent differs from the window edge.
+ const hx = nx * half * (1 - blend) + sources.x / source_across * blend;
+ const hy = ny * half * (1 - blend) + sources.y / source_across * blend;
+ for (0..2) |side| {
+ const across: f32 = if (side == 0) -1 else 1;
+ const x = (point.x - origin.x + nx * wave + across * hx) / scale;
+ const y = (point.y - origin.y + ny * wave + across * hy) / scale;
+ result.mesh.vertices[i * 2 + side] = .{ x, y, across, progress };
+ }
+ if (i + 1 == count) {
+ // A diagonal source pair straddles a corner, exposing the end
+ // of the glow outside the frame. Extend it along the tangent
+ // and fade this cap rather than leaving a straight cut there.
+ const cap = @min(24, preset.width_px * 0.4) / scale;
+ for (0..2) |side| {
+ var v = result.mesh.vertices[i * 2 + side];
+ v[0] += dx / length * cap;
+ v[1] += dy / length * cap;
+ v[3] = 2;
+ result.mesh.vertices[count * 2 + side] = v;
+ }
+ }
+ }
+ result.mesh.count = @intCast((count + 1) * 2);
+ result.enclose();
+ return result;
+ }
+};
+
+// Keep in step with the two source creases in scene_pass_ribbon.c.
+pub const source_across: f32 = 0.55;
+
+/// Hermite position and derivative with chord-length tangents.
+fn curve(b: f32, c: f32, v: f32, w: f32, t: f32) [2]f32 {
+ const p = 3 * (c - b) - 2 * v - w;
+ const q = 2 * (b - c) + v + w;
+ return .{ b + t * (v + t * (p + t * q)), v + t * (2 * p + 3 * t * q) };
+}
+
+test {
+ _ = @import("ribbon_tests.zig");
+}
diff --git a/src/effects/ribbon_scene.zig b/src/effects/ribbon_scene.zig
new file mode 100644
index 0000000..2c2cbf1
--- /dev/null
+++ b/src/effects/ribbon_scene.zig
@@ -0,0 +1,13 @@
+//! Scene transport for ribbon.Geometry. The caller owns the returned node and
+//! its parent/lifecycle. Put it in an unclipped subtree when it extends outside
+//! a clipped host. The renderer's optional ribbon program must be enabled first.
+const sn = @import("../node.zig");
+const ribbon = @import("ribbon.zig");
+
+extern fn rediwm_ribbon_create(parent: *sn.Tree) ?*sn.Buffer;
+pub const create = rediwm_ribbon_create;
+extern fn rediwm_ribbon_update(node: *sn.Buffer, mesh: *const ribbon.Mesh, x: c_int, y: c_int, width: c_int, height: c_int) void;
+
+pub fn present(node: *sn.Buffer, geometry: *const ribbon.Geometry) void {
+ rediwm_ribbon_update(node, &geometry.mesh, geometry.x, geometry.y, geometry.width, geometry.height);
+}
diff --git a/src/effects/ribbon_tests.zig b/src/effects/ribbon_tests.zig
new file mode 100644
index 0000000..336734f
--- /dev/null
+++ b/src/effects/ribbon_tests.zig
@@ -0,0 +1,144 @@
+const std = @import("std");
+const ribbon = @import("ribbon.zig");
+
+test "ribbons stop at idle, bound history and do not join teleports" {
+ var path: ribbon.Path = .{};
+ const preset: ribbon.Preset = .{ .lifetime_ms = 400 };
+ for (0..100) |i| path.push(.{ .x = @as(f32, @floatFromInt(i)) * 4, .y = 20 }, @intCast(i * 4), preset);
+ try std.testing.expect(path.len <= 32);
+ const mesh = path.mesh(400, preset, .{ .x = 396, .y = 20 }, 1.5, 0, null);
+ try std.testing.expect(mesh.mesh.count >= 4);
+ for (mesh.mesh.vertices[0..mesh.mesh.count]) |v| {
+ try std.testing.expect(v[0] >= 0 and v[0] <= 1 and v[1] >= 0 and v[1] <= 1);
+ try std.testing.expect(v[3] >= 0 and v[3] <= 2);
+ }
+ path.push(.{ .x = 396, .y = 20 }, 800, preset);
+ path.expire(800, preset.lifetime_ms);
+ try std.testing.expectEqual(@as(usize, 0), path.len);
+ path.push(.{ .x = 400, .y = 20 }, 804, preset);
+ path.push(.{ .x = 10000, .y = 20 }, 808, preset);
+ try std.testing.expectEqual(@as(usize, 1), path.len);
+}
+
+test "trail length stays bounded independently of sample capacity" {
+ var path: ribbon.Path = .{};
+ const preset: ribbon.Preset = .{ .max_length_px = 40, .lifetime_ms = 400 };
+ for (0..30) |i| path.push(.{ .x = @as(f32, @floatFromInt(i)) * 10, .y = 0 }, @intCast(i * 20), preset);
+ try std.testing.expectEqual(@as(usize, 5), path.len);
+}
+
+test "forks keep their frozen shape and sources during a short stop fade" {
+ var path: ribbon.Path = .{};
+ const preset: ribbon.Preset = .{};
+ path.push(.{ .x = 0, .y = 20 }, 0, preset);
+ path.push(.{ .x = 100, .y = 20 }, 20, preset);
+ try std.testing.expectEqual(@as(usize, 2), path.len);
+ const half: ribbon.Point = .{ .x = -16, .y = 30 };
+ const origin: ribbon.Point = .{ .x = 100, .y = 20 };
+ const fresh = path.mesh(20, preset, origin, 1.5, 0, half);
+ const lingering = path.mesh(220, preset, origin, 1.5, 0, half);
+ try std.testing.expect(lingering.mesh.fade[1] >= 0.5);
+ try std.testing.expect(lingering.mesh.fade[1] < fresh.mesh.fade[1]);
+ // The erasing front must not move the surviving folds or their sources.
+ path.expire(469, preset.lifetime_ms);
+ const almost_gone = path.mesh(469, preset, origin, 1.5, 0, half);
+ for ([_]ribbon.Geometry{ lingering, almost_gone }) |geo| {
+ try std.testing.expectEqual(fresh.x, geo.x);
+ try std.testing.expectEqual(fresh.y, geo.y);
+ try std.testing.expectEqual(fresh.width, geo.width);
+ try std.testing.expectEqual(fresh.height, geo.height);
+ try std.testing.expectEqualSlices([4]f32, fresh.mesh.vertices[0..fresh.mesh.count], geo.mesh.vertices[0..geo.mesh.count]);
+ }
+ for ([_]ribbon.Geometry{ fresh, lingering }) |geo| {
+ const a = geo.mesh.vertices[geo.mesh.count - 4];
+ const b = geo.mesh.vertices[geo.mesh.count - 3];
+ for ([_]f32{ -1, 1 }) |side| {
+ const t = (1 + side * ribbon.source_across) / 2;
+ const x = (@as(f32, @floatFromInt(geo.x)) + (a[0] * (1 - t) + b[0] * t) * @as(f32, @floatFromInt(geo.width))) * 1.5;
+ const y = (@as(f32, @floatFromInt(geo.y)) + (a[1] * (1 - t) + b[1] * t) * @as(f32, @floatFromInt(geo.height))) * 1.5;
+ try std.testing.expectApproxEqAbs(side * half.x, x, 0.001);
+ try std.testing.expectApproxEqAbs(side * half.y, y, 0.001);
+ }
+ }
+ try std.testing.expectEqual(@as(u32, 0), path.mesh(470, preset, origin, 1.5, 0, half).mesh.count);
+ path.expire(470, preset.lifetime_ms);
+ try std.testing.expectEqual(@as(usize, 0), path.len);
+}
+
+test "small drag steps keep folds continuous across history buckets and length limits" {
+ for ([_]@import("config").effects.Quality{ .low, .balanced, .high }) |quality| {
+ const preset: ribbon.Preset = .{ .max_length_px = 100, .quality = quality };
+ var path: ribbon.Path = .{};
+ path.push(.{ .x = 0, .y = 20 }, 0, preset);
+ path.push(.{ .x = 99, .y = 20 }, 90, preset);
+ var previous = path.mesh(90, preset, .{ .x = 0, .y = 0 }, 1, 0, null);
+ for (100..120) |x| {
+ const now: i64 = @intCast(100 + (x - 100) * 10);
+ path.push(.{ .x = @floatFromInt(x), .y = 20 }, now, preset);
+ const current = path.mesh(now, preset, .{ .x = 0, .y = 0 }, 1, 0, null);
+ try std.testing.expectEqual(previous.mesh.count, current.mesh.count);
+ for (previous.mesh.vertices[0..previous.mesh.count], current.mesh.vertices[0..current.mesh.count]) |a, b| {
+ const dx = @as(f32, @floatFromInt(current.x - previous.x)) + b[0] * @as(f32, @floatFromInt(current.width)) - a[0] * @as(f32, @floatFromInt(previous.width));
+ const dy = @as(f32, @floatFromInt(current.y - previous.y)) + b[1] * @as(f32, @floatFromInt(current.height)) - a[1] * @as(f32, @floatFromInt(previous.height));
+ try std.testing.expect(std.math.hypot(dx, dy) < 3);
+ }
+ previous = current;
+ }
+ }
+}
+
+test "wind ripples independently of drag distance and freezes without an idle jump" {
+ const preset: ribbon.Preset = .{};
+ const origin: ribbon.Point = .{ .x = 0, .y = 0 };
+ var path: ribbon.Path = .{};
+ path.push(.{ .x = 0, .y = 20 }, 0, preset);
+ path.push(.{ .x = 200, .y = 20 }, 20, preset);
+ path.tickFlutter(20, true);
+ const first = path.mesh(20, preset, origin, 1, 0, null);
+ // Keep the same path to isolate wind from changes to the window position.
+ path.tickFlutter(120, true);
+ const fluttering = path.mesh(120, preset, origin, 1, 0, null);
+ var largest_shift: f32 = 0;
+ for (first.mesh.vertices[0..first.mesh.count], fluttering.mesh.vertices[0..fluttering.mesh.count]) |a, b| {
+ const dy = @as(f32, @floatFromInt(fluttering.y - first.y)) + b[1] * @as(f32, @floatFromInt(fluttering.height)) - a[1] * @as(f32, @floatFromInt(first.height));
+ largest_shift = @max(largest_shift, @abs(dy));
+ }
+ try std.testing.expect(largest_shift > 4);
+ var uninterrupted = path;
+ for ([_]i64{ 220, 440 }) |now| {
+ path.tickFlutter(now, false);
+ const stopped = path.mesh(now, preset, origin, 1, 0, null);
+ try expectSameShape(fluttering, stopped);
+ }
+ // Only the new moving frame contributes time after the pause.
+ path.tickFlutter(460, true);
+ uninterrupted.tickFlutter(140, true);
+ try expectSameShape(path.mesh(460, preset, origin, 1, 0, null), uninterrupted.mesh(140, preset, origin, 1, 0, null));
+}
+
+fn expectSameShape(a: ribbon.Geometry, b: ribbon.Geometry) !void {
+ try std.testing.expectEqual(a.x, b.x);
+ try std.testing.expectEqual(a.y, b.y);
+ try std.testing.expectEqual(a.width, b.width);
+ try std.testing.expectEqual(a.height, b.height);
+ try std.testing.expectEqualSlices([4]f32, a.mesh.vertices[0..a.mesh.count], b.mesh.vertices[0..b.mesh.count]);
+}
+
+test "border halo encloses and closes rounded and polygon frames" {
+ const border = @import("border.zig");
+ const shape = @import("ui").window_shape;
+ const outline = (try shape.parse("0 16, 16 0, -0 0, -0 -0, 0 -0")).?;
+ const polygon = shape.resolve(outline, 400, 300, 1);
+ for ([_]?shape.Resolved{ null, polygon }) |poly| {
+ const geo = border.mesh(400, 300, 12, poly, 18, 0.8, .{});
+ try std.testing.expectEqual(@as(u32, 1), geo.mesh.edge);
+ try std.testing.expect(geo.mesh.count <= geo.mesh.vertices.len);
+ try std.testing.expect(geo.x < 0 and geo.y < 0 and geo.width > 400 and geo.height > 300);
+ try std.testing.expectEqual(geo.mesh.vertices[0], geo.mesh.vertices[geo.mesh.count - 2]);
+ try std.testing.expectEqual(geo.mesh.vertices[1], geo.mesh.vertices[geo.mesh.count - 1]);
+ for (geo.mesh.vertices[0..geo.mesh.count]) |v| {
+ try std.testing.expect(v[0] >= 0 and v[0] <= 1 and v[1] >= 0 and v[1] <= 1);
+ }
+ }
+ try std.testing.expectEqual(@as(u32, 0), border.mesh(400, 300, 12, null, 18, 0, .{}).mesh.count);
+}
diff --git a/src/effects/window_minimize.zig b/src/effects/window_minimize.zig
new file mode 100644
index 0000000..5a0ed1d
--- /dev/null
+++ b/src/effects/window_minimize.zig
@@ -0,0 +1,150 @@
+//! Bounded, input-transparent snapshots; the real window minimizes immediately.
+const std = @import("std");
+const wlr = @import("wlroots");
+const sn = @import("../node.zig");
+const Server = @import("../Server.zig");
+const Top = @import("../Toplevel.zig");
+const Output = @import("../Output.zig");
+const anim = @import("ui").anim;
+const ribbon = @import("ribbon.zig");
+const geometry = @import("minimize_mesh.zig");
+const mesh_scene = @import("ribbon_scene.zig");
+const gpa = @import("../main.zig").gpa;
+const Self = @This();
+
+next: ?*Self,
+id: u64,
+tree: *sn.Tree,
+node: *sn.Buffer,
+source: geometry.Box,
+target: ribbon.Point,
+preset: ribbon.Preset,
+started: i64,
+duration: f32,
+last_tick: i64 = -1,
+bounds: wlr.Box,
+
+extern fn rediwm_output_snapshot(renderer: *@import("../scene_output.zig").Renderer, projection: *@import("../projection.zig").Projection, output: *@import("../scene_outputs.zig").SceneOutput, root: *sn.Node, box: wlr.Box, scale: f32, buffer: *wlr.Buffer, fence: ?*@import("../explicit_sync.zig").ReadFence, dest: *sn.Buffer) bool;
+
+pub fn cancelAll(server: *Server) void {
+ while (server.minimize_ribbons) |self| remove(&server.minimize_ribbons, self);
+}
+
+pub fn cancelFor(server: *Server, id: u64) void {
+ var link = &server.minimize_ribbons;
+ while (link.*) |self| {
+ if (self.id == id) remove(link, self) else link = &self.next;
+ }
+}
+
+fn remove(link: *?*Self, self: *Self) void {
+ link.* = self.next;
+ self.tree.node.destroy();
+ gpa.destroy(self);
+}
+
+pub fn start(top: *Top) void {
+ const server = top.server;
+ const binding = server.config.effects.minimize();
+ if (!binding.enabled or !server.ribbons_ready or !anim.enabled() or anim.reducedMotion() or
+ anim.speed() <= 0 or server.locker != null or top.closing or !top.frame_tree.node.enabled or
+ !@import("../workspaces.zig").visible(top)) return;
+ const preset = server.config.effects.find(binding.preset) orelse return;
+ if (preset.opacity <= 0) return;
+ var count: usize = 0;
+ var it = server.minimize_ribbons;
+ while (it) |entry| : (it = entry.next) count += 1;
+ if (count >= 8) return;
+ create(top, preset) catch |err| std.log.debug("minimize ribbon unavailable: {}", .{err});
+}
+
+fn create(top: *Top, preset: ribbon.Preset) !void {
+ const server = top.server;
+ const output = top.currentOutput() orelse return error.NoOutput;
+ const out = server.scene_outputs.get(output.wlr_output) orelse return error.NoOutput;
+ const a = top.frameWorld(0, 0);
+ const b = top.frameWorld(@floatFromInt(top.chrome_width), @floatFromInt(top.chrome_height));
+ const tl = server.world.toLayout(a.x, a.y);
+ const br = server.world.toLayout(b.x, b.y);
+ const box: wlr.Box = .{ .x = @intFromFloat(@round(tl.x)), .y = @intFromFloat(@round(tl.y)), .width = @intFromFloat(@round(br.x) - @round(tl.x)), .height = @intFromFloat(@round(br.y) - @round(tl.y)) };
+ if (box.width <= 0 or box.height <= 0) return error.NoGeometry;
+ // At most 8 Mi pixels per snapshot; oversized windows use a smaller raster.
+ const area = @as(f32, @floatFromInt(box.width)) * @as(f32, @floatFromInt(box.height));
+ const scale = @min(output.wlr_output.scale, @sqrt(8 * 1024 * 1024 / area));
+ const width: i32 = @max(1, @as(i32, @intFromFloat(@round(@as(f32, @floatFromInt(box.width)) * scale))));
+ const height: i32 = @max(1, @as(i32, @intFromFloat(@round(@as(f32, @floatFromInt(box.height)) * scale))));
+ const formats = server.renderer.getTextureFormats(server.renderer.render_buffer_caps) orelse return error.NoFormat;
+ const format = formats.get(0x34325241) orelse return error.NoFormat;
+ const swapchain = try wlr.Swapchain.create(server.allocator, width, height, @constCast(format));
+ defer swapchain.destroy();
+ const buffer = try swapchain.acquire();
+ defer buffer.unlock();
+ const self = try gpa.create(Self);
+ errdefer gpa.destroy(self);
+ const tree = try server.nodes.tree.createSceneTree();
+ errdefer tree.node.destroy();
+ tree.node.placeBelow(&server.taskbar_tree.node);
+ const node = mesh_scene.create(tree) orelse return error.OutOfMemory;
+ node.node.setEnabled(false);
+ server.world.syncPresentation();
+ if (!rediwm_output_snapshot(server.output_renderer, server.world.projection, out, &top.frame_tree.node, box, scale, buffer, server.read_fence, node)) return error.SnapshotFailed;
+ self.* = .{ .next = server.minimize_ribbons, .id = top.id, .tree = tree, .node = node, .source = .{ .x = @floatFromInt(box.x), .y = @floatFromInt(box.y), .width = @floatFromInt(box.width), .height = @floatFromInt(box.height) }, .target = destination(top, output), .preset = preset, .started = anim.nowMs(), .duration = 720 / anim.speed(), .bounds = box };
+ server.minimize_ribbons = self;
+ self.update(self.started);
+ server.scheduleFrames();
+}
+
+fn destination(top: *Top, output: *Output) ribbon.Point {
+ if (output.taskbar) |bar| {
+ for (bar.chips.items) |chip| if (chip.toplevel == top) return .{
+ .x = @as(f32, @floatFromInt(bar.box.x)) + chip.renderX(anim.nowMs()) + chip.width / 2,
+ .y = @floatFromInt(bar.box.y + @divTrunc(bar.box.height, 2)),
+ };
+ }
+ const dock = &output.dock;
+ if (dock.visible) for (dock.ids[0..dock.count], 0..) |id, i| {
+ if (id == top.id) {
+ const icon = dock.iconBox(i, 1, 36);
+ return .{ .x = @as(f32, @floatFromInt(dock.box.x)) + icon.x + icon.w / 2, .y = @as(f32, @floatFromInt(dock.box.y)) + icon.y + icon.h / 2 };
+ }
+ };
+ var box: wlr.Box = undefined;
+ top.server.output_layout.getBox(output.wlr_output, &box);
+ return .{ .x = @floatFromInt(box.x + @divTrunc(box.width, 2)), .y = @floatFromInt(box.y + box.height - 2) };
+}
+
+fn update(self: *Self, now: i64) void {
+ const p = @as(f32, @floatFromInt(@max(0, now - self.started))) / self.duration;
+ const geo = geometry.mesh(self.source, self.target, p, self.preset);
+ mesh_scene.present(self.node, &geo);
+ self.bounds = .{ .x = geo.x, .y = geo.y, .width = geo.width, .height = geo.height };
+ self.last_tick = now;
+ anim.observeNoteChanged();
+}
+
+pub fn tick(output: *Output, now: i64) bool {
+ const server = output.server;
+ if (server.locker != null or !anim.enabled() or anim.reducedMotion()) {
+ cancelAll(server);
+ return false;
+ }
+ var box: wlr.Box = undefined;
+ server.output_layout.getBox(output.wlr_output, &box);
+ var live = false;
+ var link = &server.minimize_ribbons;
+ while (link.*) |self| {
+ const top = server.findToplevelById(self.id);
+ if (top == null or !top.?.minimized or !@import("../workspaces.zig").visible(top.?) or
+ @as(f32, @floatFromInt(now - self.started)) >= self.duration)
+ {
+ remove(link, self);
+ continue;
+ }
+ if (self.last_tick != now) self.update(now);
+ const b = self.bounds;
+ live = live or (b.x < box.x + box.width and b.y < box.y + box.height and
+ b.x + b.width > box.x and b.y + b.height > box.y);
+ link = &self.next;
+ }
+ return live;
+}
diff --git a/src/effects/window_move.zig b/src/effects/window_move.zig
new file mode 100644
index 0000000..7fa2127
--- /dev/null
+++ b/src/effects/window_move.zig
@@ -0,0 +1,226 @@
+//! Window adapter for the reusable ribbon geometry and scene mesh nodes.
+const std = @import("std");
+const Server = @import("../Server.zig");
+const Top = @import("../Toplevel.zig");
+const Output = @import("../Output.zig");
+const sn = @import("../node.zig");
+const projection = @import("../projection.zig");
+const anim = @import("ui").anim;
+const ribbon = @import("ribbon.zig");
+const border = @import("border.zig");
+const mesh_scene = @import("ribbon_scene.zig");
+const gpa = @import("../main.zig").gpa;
+const Self = @This();
+const Resize = @import("window_resize.zig");
+const Heading = @import("move_heading.zig");
+const move_trail = @import("move_trail.zig");
+
+id: u64,
+resizing: ?Resize = null,
+tree: *sn.Tree,
+nodes: [4]*sn.Buffer,
+paths: [2]ribbon.Path = @splat(.{}),
+preset: ribbon.Preset,
+previous: ribbon.Point,
+previous_position: ribbon.Point,
+heading: Heading = .{},
+last_tick: i64 = -1,
+last_move: ?i64 = null,
+emitting: bool = true,
+visible: bool = false,
+// Last world-space bounds, for pacing only the outputs the ribbons intersect.
+bounds: [4]struct { x: f64 = 0, y: f64 = 0, w: f64 = 0, h: f64 = 0 } = @splat(.{}),
+
+pub fn configure(server: *Server) void {
+ cancel(server);
+ @import("window_minimize.zig").cancelAll(server);
+ const enabled = !server.greeter_mode and (server.config.effects.window_move.enabled or server.config.effects.minimize().enabled or server.config.effects.resize().enabled);
+ server.ribbons_ready = enabled and server.output_renderer.setRibbons(true);
+ if (!enabled) _ = server.output_renderer.setRibbons(false);
+ if (enabled and !server.ribbons_ready) std.log.warn("flame ribbons: shader unavailable; effect disabled", .{});
+}
+
+pub fn cancel(server: *Server) void {
+ const self = server.window_ribbons orelse return;
+ server.window_ribbons = null;
+ self.tree.node.destroy();
+ gpa.destroy(self);
+}
+
+pub fn cancelFor(server: *Server, id: u64) void {
+ if (server.window_ribbons) |self| if (self.id == id) cancel(server);
+}
+
+pub fn start(top: *Top) void {
+ startWith(top, top.server.config.effects.window_move, null);
+}
+
+pub fn startResize(top: *Top) void {
+ startWith(top, top.server.config.effects.resize(), Resize.init(top));
+}
+
+fn startWith(top: *Top, binding: @import("config").effects.Binding, resizing: ?Resize) void {
+ const server = top.server;
+ cancel(server);
+ if (!binding.enabled or !server.ribbons_ready or !anim.enabled() or anim.reducedMotion() or server.locker != null) return;
+ const preset = server.config.effects.find(binding.preset) orelse return;
+ if (preset.opacity == 0) return;
+ const self = gpa.create(Self) catch return;
+ const tree = top.frame_tree.createSceneTree() catch {
+ gpa.destroy(self);
+ return;
+ };
+ var nodes: [4]*sn.Buffer = undefined;
+ for (&nodes) |*node| {
+ node.* = mesh_scene.create(tree) orelse {
+ tree.node.destroy();
+ gpa.destroy(self);
+ return;
+ };
+ node.*.node.setEnabled(false);
+ }
+ nodes[3].node.lowerToBottom();
+ if (!projection.setTreeUnclipped(&tree.node, true)) {
+ tree.node.destroy();
+ gpa.destroy(self);
+ return;
+ }
+ tree.node.placeAbove(&top.shadow_tree.node);
+ if (resizing != null) tree.node.raiseToTop();
+ self.* = .{
+ .id = top.id,
+ .resizing = resizing,
+ .tree = tree,
+ .nodes = nodes,
+ .preset = preset,
+ .previous = .{ .x = @floatFromInt(top.frame_tree.node.x), .y = @floatFromInt(top.frame_tree.node.y) },
+ .previous_position = .{ .x = @floatFromInt(top.x), .y = @floatFromInt(top.y) },
+ };
+ server.window_ribbons = self;
+}
+
+pub fn stop(server: *Server) void {
+ if (server.window_ribbons) |self| {
+ self.emitting = false;
+ if (self.resizing) |*state| state.released = anim.nowMs();
+ }
+}
+
+pub fn resizeMotion(top: *Top) void {
+ const self = top.server.window_ribbons orelse return;
+ if (self.id != top.id or !self.emitting) return;
+ if (self.resizing) |*state| state.motion(top);
+}
+
+pub fn resizeSize(top: *Top, now: i64, requested: @import("../resize.zig").ClientSize) @import("../resize.zig").ClientSize {
+ if (!anim.enabled() or anim.reducedMotion()) return requested;
+ const self = top.server.window_ribbons orelse return requested;
+ if (self.id != top.id) return requested;
+ if (self.resizing) |*state| return state.follow.value(now, anim.speed());
+ return requested;
+}
+
+fn anchors(direction: u2, w: f32, h: f32, width: f32) struct { points: [2]ribbon.Point, spreads: [2]ribbon.Point } {
+ const inset = @min(16, @min(w, h) * 0.1);
+ const half = @min(width * ribbon.source_across, @max(0, (if (direction < 2) h else w) - 2 * inset) * 0.2);
+ // Straddle each trailing corner: one source on the trailing side, the
+ // other partway along the adjacent edge. The midpoint feeds the path;
+ // each ribbon's diagonal half-vector places its two bright tips exactly.
+ const center = (inset + 2 * half) / 2;
+ const along = @min(@max(inset, width * 0.6), (if (direction < 2) w else h) * 0.25) / 2;
+ const points: [2]ribbon.Point = switch (direction) {
+ 0 => .{ .{ .x = along, .y = center }, .{ .x = along, .y = h - center } },
+ 1 => .{ .{ .x = w - along, .y = center }, .{ .x = w - along, .y = h - center } },
+ 2 => .{ .{ .x = center, .y = along }, .{ .x = w - center, .y = along } },
+ 3 => .{ .{ .x = center, .y = h - along }, .{ .x = w - center, .y = h - along } },
+ };
+ const spreads: [2]ribbon.Point = switch (direction) {
+ 0 => .{ .{ .x = -along, .y = center }, .{ .x = along, .y = center } },
+ 1 => .{ .{ .x = -along, .y = -center }, .{ .x = along, .y = -center } },
+ 2 => .{ .{ .x = -center, .y = along }, .{ .x = -center, .y = -along } },
+ 3 => .{ .{ .x = center, .y = along }, .{ .x = center, .y = -along } },
+ };
+ return .{ .points = points, .spreads = spreads };
+}
+
+pub fn tick(self: *Self, output: *Output, now: i64) bool {
+ const server = output.server;
+ const top = server.findToplevelById(self.id) orelse {
+ cancel(server);
+ return false;
+ };
+ if (server.locker != null or !anim.enabled() or anim.reducedMotion() or !top.in_world or
+ top.minimized or top.closing or top.switch_leaving or !top.frame_tree.node.enabled)
+ {
+ cancel(server);
+ return false;
+ }
+ const following = if (self.resizing) |*state| state.pending(now) else false;
+ if (now != self.last_tick or (if (self.resizing) |*state| state.needsUpdate(top) else false)) {
+ self.last_tick = now;
+ if (self.resizing) |*state| state.update(self, top, now) else self.update(top, now);
+ if (!self.emitting and !self.visible and !following) {
+ cancel(server);
+ return false;
+ }
+ }
+ if (following) if (server.input.resize_session) |session| {
+ if (session.toplevel == top and (session.pacing_output == null or session.pacing_output == output)) return true;
+ };
+ if (!self.visible) return false;
+ var box: @import("wlroots").Box = undefined;
+ server.output_layout.getBox(output.wlr_output, &box);
+ for (self.bounds) |b| {
+ const p = server.world.toLayout(b.x, b.y);
+ const z = server.world.camera.zoom();
+ if (p.x < @as(f64, @floatFromInt(box.x + box.width)) and p.y < @as(f64, @floatFromInt(box.y + box.height)) and
+ p.x + b.w * z > @as(f64, @floatFromInt(box.x)) and p.y + b.h * z > @as(f64, @floatFromInt(box.y))) return true;
+ }
+ return false;
+}
+
+fn update(self: *Self, top: *Top, now: i64) void {
+ const origin: ribbon.Point = .{ .x = @floatFromInt(top.frame_tree.node.x), .y = @floatFromInt(top.frame_tree.node.y) };
+ const scale: f32 = @floatCast(top.worldScale() * top.drag_lift_value);
+ // Lift/settlement moves the presentation tree too; only a real drag feeds
+ // the trails or chooses a trailing side.
+ const position: ribbon.Point = .{ .x = @floatFromInt(top.x), .y = @floatFromInt(top.y) };
+ const dx = position.x - self.previous_position.x;
+ const dy = position.y - self.previous_position.y;
+ const moved = @abs(dx) >= 0.5 or @abs(dy) >= 0.5;
+ // Clear a finished fade before seeding a resumed drag's first segment.
+ for (&self.paths) |*path| path.expire(now, self.preset.lifetime_ms);
+ if (self.emitting and moved) {
+ self.last_move = now;
+ if (self.heading.update(dx, dy)) self.paths = @splat(.{});
+ const sources = anchors(self.heading.value, @as(f32, @floatFromInt(top.chrome_width)) * scale, @as(f32, @floatFromInt(top.chrome_height)) * scale, self.preset.width_px);
+ for (&self.paths, sources.points) |*path, p| {
+ if (path.len == 0) path.push(.{ .x = self.previous.x + p.x, .y = self.previous.y + p.y }, now - 1, self.preset);
+ path.push(.{ .x = origin.x + p.x, .y = origin.y + p.y }, now, self.preset);
+ }
+ }
+ self.previous = origin;
+ self.previous_position = position;
+ self.visible = false;
+ const sources = anchors(self.heading.value, @as(f32, @floatFromInt(top.chrome_width)) * scale, @as(f32, @floatFromInt(top.chrome_height)) * scale, self.preset.width_px);
+ var trails: [2]ribbon.Geometry = undefined;
+ for (&self.paths, 0..) |*path, i| {
+ path.tickFlutter(now, self.emitting and moved);
+ trails[i] = path.mesh(now, self.preset, origin, scale, @as(f32, @floatFromInt(i)) * std.math.pi, sources.spreads[i]);
+ self.present(i, trails[i], origin, scale);
+ }
+ self.present(3, move_trail.between(&trails), origin, scale);
+ const age = if (self.last_move) |last| std.math.clamp(@as(f32, @floatFromInt(now - last)) / @as(f32, @floatFromInt(@min(self.preset.lifetime_ms, ribbon.stop_fade_ms))), 0, 1) else 1;
+ const decorated = top.hasServerDecorations() and @import("../chrome.zig").shapes;
+ const halo = border.mesh(@floatFromInt(top.chrome_width), @floatFromInt(top.chrome_height), if (decorated) top.cornerRadius() else 0, if (decorated) top.shapePolygon(top.chrome_width, top.chrome_height) else null, std.math.clamp(self.preset.width_px * 0.4, 6, 24) / scale, (1 - age) * (1 - age), self.preset);
+ self.present(2, halo, origin, scale);
+}
+
+pub fn present(self: *Self, i: usize, geo: ribbon.Geometry, origin: ribbon.Point, scale: f32) void {
+ const node = self.nodes[i];
+ if (geo.mesh.count == 0 and !node.node.enabled) return;
+ anim.observeNoteChanged();
+ mesh_scene.present(node, &geo);
+ self.bounds[i] = .{ .x = origin.x + @as(f32, @floatFromInt(geo.x)) * scale, .y = origin.y + @as(f32, @floatFromInt(geo.y)) * scale, .w = @as(f32, @floatFromInt(geo.width)) * scale, .h = @as(f32, @floatFromInt(geo.height)) * scale };
+ self.visible = self.visible or geo.mesh.count >= 4;
+}
diff --git a/src/effects/window_resize.zig b/src/effects/window_resize.zig
new file mode 100644
index 0000000..d5f95b5
--- /dev/null
+++ b/src/effects/window_resize.zig
@@ -0,0 +1,90 @@
+//! The pointer pulls an elastic outline while the real client size follows
+//! smoothly. One membrane fills the gap from the window to the curved boundary.
+const std = @import("std");
+const Top = @import("../Toplevel.zig");
+const Host = @import("window_move.zig");
+const anim = @import("ui").anim;
+const ribbon = @import("ribbon.zig");
+const resize = @import("../resize.zig");
+const Follow = @import("resize_follow.zig");
+const geometry = @import("resize_mesh.zig");
+const border = @import("border.zig");
+const Self = @This();
+
+snapshot: resize.ResizeSnapshot,
+follow: Follow,
+last_motion: ?i64 = null,
+released: ?i64 = null,
+last_geometry: ?[5]f64 = null,
+dirty: bool = true,
+
+pub fn init(top: *Top) Self {
+ const session = top.server.input.resize_session.?;
+ return .{ .snapshot = session.snapshot, .follow = Follow.init(session.latest_desired_size, anim.nowMs()) };
+}
+
+pub fn motion(self: *Self, top: *Top) void {
+ const session = top.server.input.resize_session orelse return;
+ if (std.meta.eql(self.follow.target, session.latest_desired_size)) return;
+ const now = anim.nowMs();
+ self.follow.retarget(session.latest_desired_size, now, anim.speed());
+ self.last_motion = now;
+ self.dirty = true;
+ top.server.scheduleFrames();
+}
+
+pub fn pending(self: *const Self, now: i64) bool {
+ return self.follow.pending(now, anim.speed());
+}
+
+fn frame(top: *Top) [5]f64 {
+ return .{ @floatFromInt(top.frame_tree.node.x), @floatFromInt(top.frame_tree.node.y), @floatFromInt(top.chrome_width), @floatFromInt(top.chrome_height), top.worldScale() * top.drag_lift_value };
+}
+
+pub fn needsUpdate(self: *const Self, top: *Top) bool {
+ return self.dirty or self.last_geometry == null or !std.meta.eql(self.last_geometry.?, frame(top));
+}
+
+pub fn update(self: *Self, host: *Host, top: *Top, now: i64) void {
+ self.last_geometry = frame(top);
+ self.dirty = false;
+ const origin: ribbon.Point = .{ .x = @floatFromInt(top.frame_tree.node.x), .y = @floatFromInt(top.frame_tree.node.y) };
+ const scale: f32 = @floatCast(top.worldScale() * top.drag_lift_value);
+ const age = if (self.last_motion) |last|
+ std.math.clamp(@as(f32, @floatFromInt(@max(0, now - last))) / @as(f32, @floatFromInt(host.preset.lifetime_ms)), 0, 1)
+ else
+ 1;
+ const following = self.pending(now);
+ const release_age = if (self.released) |at|
+ (if (following) 0 else std.math.clamp(@as(f32, @floatFromInt(@max(0, now - at))) / @as(f32, @floatFromInt(@min(450, host.preset.lifetime_ms))), 0, 1))
+ else
+ 0;
+ const strength = @max(if (following) @as(f32, 0.65) else 0, (1 - age) * (1 - age)) * (1 - release_age) * (1 - release_age);
+ const desired = self.follow.target;
+ const pos = resize.computeFramePosition(self.snapshot, desired.width, desired.height);
+ const x = self.snapshot.initial_frame_x + @as(i32, @intFromFloat(@round(@as(f64, @floatFromInt(pos.x - self.snapshot.initial_frame_x)) * top.worldScale())));
+ const y = self.snapshot.initial_frame_y + @as(i32, @intFromFloat(@round(@as(f64, @floatFromInt(pos.y - self.snapshot.initial_frame_y)) * top.worldScale())));
+ const target: geometry.Box = .{
+ .x = (@as(f32, @floatFromInt(x)) - origin.x) / scale,
+ .y = (@as(f32, @floatFromInt(y)) - origin.y) / scale,
+ .width = @floatFromInt(desired.width + 2 * self.snapshot.frame_border),
+ .height = @floatFromInt(desired.height + self.snapshot.titlebar_height + self.snapshot.footer_height),
+ };
+ const decorated = top.hasServerDecorations() and @import("../chrome.zig").shapes;
+ const radius = if (decorated) top.cornerRadius() else 0;
+ const polygon = if (decorated) top.shapePolygon(top.chrome_width, top.chrome_height) else null;
+ const target_polygon = if (decorated) top.shapePolygon(@intFromFloat(target.width), @intFromFloat(target.height)) else null;
+ const phase = @as(f32, @floatFromInt(@mod(now, 100000))) * 0.003 * host.preset.turbulence;
+ const reach = std.math.clamp(host.preset.width_px * 0.4, 6, 24) / scale;
+ const pull: geometry.Pull = .{ .edges = self.snapshot.edges, .anchor = .{
+ .x = @floatCast((self.snapshot.initial_cursor_x - @as(f64, @floatFromInt(self.snapshot.initial_frame_x)) / top.worldScale()) /
+ @as(f64, @floatFromInt(self.snapshot.initial_client_width + 2 * self.snapshot.frame_border))),
+ .y = @floatCast((self.snapshot.initial_cursor_y - @as(f64, @floatFromInt(self.snapshot.initial_frame_y)) / top.worldScale()) /
+ @as(f64, @floatFromInt(self.snapshot.initial_client_height + self.snapshot.titlebar_height + self.snapshot.footer_height))),
+ } };
+ const meshes = geometry.build(@floatFromInt(top.chrome_width), @floatFromInt(top.chrome_height), target, radius, polygon, target_polygon, pull, reach, strength, phase, host.preset);
+ host.visible = false;
+ host.present(0, meshes.fill, origin, scale);
+ host.present(1, meshes.edge, origin, scale);
+ host.present(2, border.mesh(@floatFromInt(top.chrome_width), @floatFromInt(top.chrome_height), radius, polygon, reach, strength, host.preset), origin, scale);
+}
diff --git a/src/input/grabs.zig b/src/input/grabs.zig
index 0e85fde..2158827 100644
--- a/src/input/grabs.zig
+++ b/src/input/grabs.zig
@@ -37,6 +37,7 @@ pub fn startMove(input: *Input, toplevel: *Toplevel) void {
const origin = geometry.toLocal(wx, wy, toplevel.x, toplevel.y);
input.grabbed_toplevel = toplevel;
input.cursor_mode = .move;
+ @import("../effects/window_move.zig").start(toplevel);
// The window is held until release; its client gets the pointer back
// (and sets its own cursor) on the re-enter after the move.
input.setHover(null, null);
@@ -59,6 +60,7 @@ pub fn startMove(input: *Input, toplevel: *Toplevel) void {
/// Ends a move grab, dropping the window into the snap zone under the
/// pointer when `apply_snap` (a button release rather than a cancel).
pub fn endMove(input: *Input, apply_snap: bool) void {
+ @import("../effects/window_move.zig").stop(input.server);
// The release frame refreshes a held titlebar blur (see heldGlass).
input.server.scheduleFrames();
const target = input.move_snap.target;
@@ -252,6 +254,7 @@ pub fn startResize(
.dirty = false,
.pacing_output = pacing_output,
};
+ @import("../effects/window_move.zig").startResize(toplevel);
toplevel.setResizing(true);
const wait = toplevel.requestSize(client_w, client_h);
@@ -272,12 +275,18 @@ pub fn startResize(
pub fn finishResize(input: *Input) void {
const session = &(input.resize_session orelse return);
const toplevel = session.toplevel;
+ @import("../effects/window_move.zig").stop(input.server);
+ input.server.scheduleFrames();
toplevel.setResizing(false);
const final_size = session.latest_desired_size;
- session.outstanding_configure = toplevel.requestSize(final_size.width, final_size.height);
- session.last_sent_width = final_size.width;
- session.last_sent_height = final_size.height;
+ const shown = @import("../effects/window_move.zig").resizeSize(toplevel, Toplevel.nowMs(), final_size);
+ session.dirty = !std.meta.eql(shown, final_size);
+ if (!session.dirty) {
+ session.outstanding_configure = toplevel.requestSize(final_size.width, final_size.height);
+ session.last_sent_width = final_size.width;
+ session.last_sent_height = final_size.height;
+ }
input.cursor_mode = .passthrough;
input.grabbed_toplevel = null;
@@ -298,13 +307,14 @@ pub fn finishResize(input: *Input) void {
// Compositor-owned windows have already applied the final size and
// position; no client commit will arrive to finish their resize session.
- if (session.outstanding_configure == .none) input.finishSettlement(session.generation);
+ if (!session.dirty and session.outstanding_configure == .none) input.finishSettlement(session.generation);
input.processCursorMotion(0);
}
pub fn cancelResize(input: *Input) void {
const session = input.resize_session orelse return;
const toplevel = session.toplevel;
+ @import("../effects/window_move.zig").cancelFor(input.server, toplevel.id);
input.resize_session = null;
input.cursor_mode = .passthrough;
@@ -325,22 +335,24 @@ pub fn cancelResize(input: *Input) void {
pub fn flushResizeConfigure(input: *Input, output: *Output) void {
const session = &(input.resize_session orelse return);
if (session.pacing_output != null and session.pacing_output != output) return;
- if (session.settling) return;
if (!session.dirty) return;
if (session.outstanding_configure != .none) return;
const toplevel = session.toplevel;
- const desired = session.latest_desired_size;
+ const desired = @import("../effects/window_move.zig").resizeSize(toplevel, Toplevel.nowMs(), session.latest_desired_size);
+ const following = !std.meta.eql(desired, session.latest_desired_size);
if (desired.width == session.last_sent_width and desired.height == session.last_sent_height) {
- session.dirty = false;
+ session.dirty = following;
+ if (session.settling and !following) input.finishSettlement(session.generation);
return;
}
session.outstanding_configure = toplevel.requestSize(desired.width, desired.height);
session.last_sent_width = desired.width;
session.last_sent_height = desired.height;
- session.dirty = false;
+ session.dirty = following;
+ if (session.settling and !following and session.outstanding_configure == .none) input.finishSettlement(session.generation);
}
pub fn finishSettlement(input: *Input, generation: u64) void {
diff --git a/src/input/motion.zig b/src/input/motion.zig
index 96d2706..eaac7a9 100644
--- a/src/input/motion.zig
+++ b/src/input/motion.zig
@@ -539,10 +539,10 @@ pub fn processResize(input: *Input) void {
cursor_wy,
constraints,
);
-
if (desired.width != session.latest_desired_size.width or desired.height != session.latest_desired_size.height) {
session.latest_desired_size = desired;
session.dirty = true;
+ @import("../effects/window_move.zig").resizeMotion(toplevel);
if (session.pacing_output) |out| {
out.wlr_output.scheduleFrame();
} else {
diff --git a/src/output/frame.zig b/src/output/frame.zig
index cf2a9c6..40e2457 100644
--- a/src/output/frame.zig
+++ b/src/output/frame.zig
@@ -292,6 +292,8 @@ pub fn runFrame(output: *Output) void {
return;
};
const reveal_animating = output.server.reveal.tick(output, now_ms);
+ const ribbons_animating = if (output.server.window_ribbons) |ribbons| ribbons.tick(output, now_ms) else false;
+ const minimize_animating = @import("../effects/window_minimize.zig").tick(output, now_ms);
const projection_started = if (observing) stats.nowNs() else 0;
output.server.world.refreshBounds();
output.server.world.syncPresentation();
@@ -395,7 +397,7 @@ pub fn runFrame(output: *Output) void {
// Keep repainting every refresh interval until the last hover/press/FLIP
// animation settles; otherwise chrome and the bar only redraw when a
// client does.
- const keep_going = mini_map_animating or switcher_animating or osd_animating or dock_animating or bar_animating or chrome_animating or cc_animating or sm_animating or pm_animating or taskbar_popup_animating or notif_animating or desktop_animating or lock_animating or polkit_animating or reveal_animating;
+ const keep_going = minimize_animating or ribbons_animating or mini_map_animating or switcher_animating or osd_animating or dock_animating or bar_animating or chrome_animating or cc_animating or sm_animating or pm_animating or taskbar_popup_animating or notif_animating or desktop_animating or lock_animating or polkit_animating or reveal_animating;
output.late_animating = keep_going;
// A pinned clock is advanced explicitly by IPC, which schedules its own
// frame. Global window/taskbar springs must not spin between those steps.
diff --git a/src/projection.c b/src/projection.c
index f41a561..13c8585 100644
--- a/src/projection.c
+++ b/src/projection.c
@@ -168,7 +168,11 @@ struct leaf *projection_get_leaf(struct rediwm_projection *p, struct rediwm_node
wl_list_insert(&p->leaves, &l->link);
wlr_addon_init(&l->source_lookup, &source->addons, p, &source_lookup_impl);
source->leaf = l;
- l->effect = source->type == REDIWM_NODE_BUFFER && rediwm_glass_is_effect_node(source);
+ if (source->type == REDIWM_NODE_BUFFER) {
+ l->item.ribbon = rediwm_ribbon_get(source);
+ l->intrinsic_kind = l->item.ribbon ? REDIWM_ITEM_RIBBON :
+ rediwm_glass_is_effect_node(source) ? REDIWM_ITEM_EFFECT : REDIWM_ITEM_BUFFER;
+ }
l->destroy.notify = source_destroy;
wl_signal_add(&source->events.destroy, &l->destroy);
if (source->type == REDIWM_NODE_BUFFER) {
diff --git a/src/projection_internal.h b/src/projection_internal.h
index dbbe14e..07b1506 100644
--- a/src/projection_internal.h
+++ b/src/projection_internal.h
@@ -9,6 +9,7 @@
#define WLR_PRIVATE private
#include "projection.h"
#include "glass.h"
+#include "ribbon.h"
#include "node.h"
#include "scene_graph.h"
#include "scene_damage.h"
@@ -104,8 +105,9 @@ struct leaf {
struct rediwm_node *own;
// The group the last resolve() put it in.
struct group *group;
- // A glass effect: decided when the leaf is made, as an effect is its own node.
- bool effect;
+ // Intrinsic kind, cached once: optional nodes add no lookup/branch to resolve.
+ // BUFFER still follows the surface binding; tree shadows override at resolve.
+ enum rediwm_item_kind intrinsic_kind;
struct wl_listener destroy, commit;
struct wlr_addon source_lookup;
struct rediwm_surface *surface;
diff --git a/src/projection_pick.c b/src/projection_pick.c
index 056b3a0..bdc0a16 100644
--- a/src/projection_pick.c
+++ b/src/projection_pick.c
@@ -15,7 +15,7 @@ static bool pick_leaf(struct rediwm_projection *p, const struct group *only, dou
struct leaf *l = wl_container_of(ll, l, paint);
const struct rediwm_item *item = &l->item;
// An effect takes no input, and a leaf with no pixels once rounded is not shown.
- if (!item->enabled || item->kind == REDIWM_ITEM_EFFECT || l->inert) continue;
+ if (!item->enabled || item->kind == REDIWM_ITEM_EFFECT || item->kind == REDIWM_ITEM_RIBBON || l->inert) continue;
const struct rediwm_snap s = rediwm_edges_snap(item->edges);
if (s.width <= 0 || s.height <= 0 || px < s.x || px >= s.x + s.width || py < s.y ||
py >= s.y + s.height)
diff --git a/src/projection_present.c b/src/projection_present.c
index 8178040..3a815f6 100644
--- a/src/projection_present.c
+++ b/src/projection_present.c
@@ -94,6 +94,8 @@ static void present_leaf(struct leaf *l) {
bool paints = enabled;
if (item->kind == REDIWM_ITEM_RECT) {
paints = paints && item->content.color[3] > 0;
+ } else if (item->kind == REDIWM_ITEM_RIBBON) {
+ paints = paints && item->content.opacity > 0 && item->ribbon->count >= 4;
} else if (item->kind == REDIWM_ITEM_EFFECT || item->kind == REDIWM_ITEM_SHADOW) {
paints = false;
} else {
diff --git a/src/projection_resolve.c b/src/projection_resolve.c
index ec48d8f..43632f4 100644
--- a/src/projection_resolve.c
+++ b/src/projection_resolve.c
@@ -158,10 +158,9 @@ static void resolve_leaf(struct rediwm_projection *p, struct group *g, struct re
memcpy(item->content.color, r->color, sizeof(item->content.color));
} else {
struct rediwm_buffer *b = rediwm_buffer_from_node(node);
- if (l->effect) g->has_effect = true;
- item->kind = l->effect ? REDIWM_ITEM_EFFECT
- : l->surface ? REDIWM_ITEM_SURFACE
- : REDIWM_ITEM_BUFFER;
+ if (l->intrinsic_kind == REDIWM_ITEM_EFFECT) g->has_effect = true;
+ item->kind = l->intrinsic_kind != REDIWM_ITEM_BUFFER ? l->intrinsic_kind
+ : l->surface ? REDIWM_ITEM_SURFACE : REDIWM_ITEM_BUFFER;
item->width = b->dst_width;
item->height = b->dst_height;
if (item->kind == REDIWM_ITEM_EFFECT) {
@@ -194,11 +193,11 @@ static void resolve_leaf(struct rediwm_projection *p, struct group *g, struct re
item->content.dim_brightness = w->dim->brightness;
item->content.dim_saturation = w->dim->saturation;
}
- if (w->shadow && node->type == REDIWM_NODE_BUFFER) {
+ if (w->shadow && node->type == REDIWM_NODE_BUFFER && item->kind != REDIWM_ITEM_RIBBON) {
item->kind = REDIWM_ITEM_SHADOW;
l->shadow = *w->shadow;
item->shadow = &l->shadow;
- } else if (item->shadow) {
+ } else if (item->kind != REDIWM_ITEM_RIBBON && item->shadow) {
item->shadow = NULL;
}
item->edges = rediwm_xform_rect(w->t, x, y, item->width, item->height);
diff --git a/src/projection_test.c b/src/projection_test.c
index 60705d8..c231913 100644
--- a/src/projection_test.c
+++ b/src/projection_test.c
@@ -162,6 +162,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_ribbon.c"
#include "projection_test_groups.c"
#include "projection_test_sector.c"
@@ -321,6 +322,7 @@ int main(void) {
test_clip_projection(scene);
test_clip_output(scene, out);
test_shadow_output(scene, out);
+ test_ribbon_output(scene, out);
test_damage_events(scene);
test_dim(scene);
test_graph_damage(scene, out);
diff --git a/src/projection_test_ribbon.c b/src/projection_test_ribbon.c
new file mode 100644
index 0000000..0f92b1e
--- /dev/null
+++ b/src/projection_test_ribbon.c
@@ -0,0 +1,37 @@
+static void test_ribbon_output(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 rediwm_buffer *node = rediwm_ribbon_create(frame);
+ assert(node);
+ struct rediwm_ribbon mesh = {.count = 4, .color = {1, 0, 0, 1}};
+ rediwm_ribbon_update(node, &mesh, 100, 100, 80, 40);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ struct leaf *l = leaf_of(p, &node->node);
+ assert(l->item.kind == REDIWM_ITEM_RIBBON);
+ assert(layout_damaged(out, 110, 110));
+ struct rediwm_hit hit;
+ assert(!rediwm_projection_node_at(p, 110, 110, &hit));
+ clear_damage(out);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(!pixman_region32_not_empty(&out->damage_ring.current));
+ // A fading ribbon has no backing buffer, but still changes its own pixels.
+ uint64_t cursor = rediwm_projection_damage_cursor(p);
+ mesh.color[3] = .5f;
+ rediwm_ribbon_update(node, &mesh, 100, 100, 80, 40);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(layout_damaged(out, 110, 110));
+ struct events_seen events = events_since(p, &cursor, NULL);
+ assert(events.count == 1 && events.last[0].leaf == l->item.id);
+ clear_damage(out);
+ rediwm_ribbon_update(node, &mesh, 200, 100, 80, 40);
+ rediwm_projection_sync(p, 1.5, 0, 0, 0, 0);
+ assert(layout_damaged(out, 110, 110) && layout_damaged(out, 310, 160));
+ clear_damage(out);
+ rediwm_node_destroy(&node->node);
+ assert(layout_damaged(out, 310, 160));
+ rediwm_projection_destroy(p);
+ rig_destroy(&rig);
+ puts("PASS: ribbon content, move, fractional damage, input transparency and destruction");
+}
diff --git a/src/ribbon.c b/src/ribbon.c
new file mode 100644
index 0000000..519e838
--- /dev/null
+++ b/src/ribbon.c
@@ -0,0 +1,48 @@
+#define WLR_USE_UNSTABLE
+#include "ribbon.h"
+#include "node.h"
+#include <stdlib.h>
+#include <string.h>
+
+struct ribbon_node {
+ struct wlr_addon addon;
+ struct rediwm_ribbon mesh;
+};
+static void destroy(struct wlr_addon *addon) {
+ struct ribbon_node *r = wl_container_of(addon, r, addon);
+ wlr_addon_finish(addon);
+ free(r);
+}
+static const struct wlr_addon_interface impl = {"rediwm-ribbon", destroy};
+static bool no_input(struct rediwm_buffer *b, double *x, double *y) {
+ (void)b; (void)x; (void)y;
+ return false;
+}
+struct rediwm_buffer *rediwm_ribbon_create(struct rediwm_tree *parent) {
+ struct ribbon_node *r = calloc(1, sizeof(*r));
+ if (!r) return NULL;
+ struct rediwm_buffer *b = rediwm_buffer_create(parent, NULL);
+ if (!b) { free(r); return NULL; }
+ b->point_accepts_input = no_input;
+ wlr_addon_init(&r->addon, &b->node.addons, NULL, &impl);
+ return b;
+}
+const struct rediwm_ribbon *rediwm_ribbon_get(struct rediwm_node *node) {
+ struct wlr_addon *addon = wlr_addon_find(&node->addons, NULL, &impl);
+ struct ribbon_node *r;
+ return addon ? (r = wl_container_of(addon, r, addon), &r->mesh) : NULL;
+}
+void rediwm_ribbon_update(struct rediwm_buffer *b, const struct rediwm_ribbon *mesh,
+ int x, int y, int width, int height) {
+ struct rediwm_ribbon *dst = (struct rediwm_ribbon *)rediwm_ribbon_get(&b->node);
+ if (!dst || mesh->count > REDIWM_RIBBON_VERTICES) return;
+ *dst = *mesh;
+ rediwm_node_set_position(&b->node, x, y);
+ rediwm_buffer_set_dest_size(b, width, height);
+ rediwm_node_set_enabled(&b->node, mesh->count >= 4);
+ // Content can animate without moving the node. Attribute damage to this
+ // painted leaf so retained glass above it sees the change.
+ if (b->node.scene->buffer_damaged)
+ b->node.scene->buffer_damaged(b->node.scene->changed_data, b, NULL);
+ rediwm_node_touch(&b->node);
+}
diff --git a/src/ribbon.h b/src/ribbon.h
new file mode 100644
index 0000000..797b8f9
--- /dev/null
+++ b/src/ribbon.h
@@ -0,0 +1,20 @@
+// A reusable, input-transparent ribbon mesh. Positions are normalized to the
+// node's box; z is signed distance across the ribbon, w its time coordinate
+// (tail 0, head 1, end of soft cap 2), or the opacity of a border halo.
+#pragma once
+#include <stdbool.h>
+#include <stdint.h>
+#define REDIWM_RIBBON_VERTICES 128
+struct rediwm_node;
+struct rediwm_tree;
+struct rediwm_ribbon {
+ uint32_t count;
+ float vertices[REDIWM_RIBBON_VERTICES][4];
+ float color[4], core_color[4]; // straight RGBA, premultiplied by the shader
+ uint32_t edge; // 0: folded trail, 1: border halo, 2: textured minimize, 3: resize sheet, 4: drag sheet
+ float fade[2]; // opacity at the oldest/newest sample, separate from geometry
+};
+struct rediwm_buffer *rediwm_ribbon_create(struct rediwm_tree *parent);
+const struct rediwm_ribbon *rediwm_ribbon_get(struct rediwm_node *node);
+void rediwm_ribbon_update(struct rediwm_buffer *node, const struct rediwm_ribbon *mesh,
+ int x, int y, int width, int height);
diff --git a/src/scene_graph.h b/src/scene_graph.h
index ccba14a..65b1a99 100644
--- a/src/scene_graph.h
+++ b/src/scene_graph.h
@@ -367,6 +367,7 @@ enum rediwm_item_kind {
// The analytic shadow of `item.shadow`; the leaf transports input, opacity and
// the footprint (its edges), never pixels.
REDIWM_ITEM_SHADOW,
+ REDIWM_ITEM_RIBBON, // an input-transparent procedural ribbon mesh
};
// What a leaf draws, apart from where. `color` is premultiplied.
struct rediwm_content {
@@ -424,6 +425,10 @@ struct rediwm_item {
// The shape clipping this item with the rest of its tree, or NULL. Owned by the
// leaf the item belongs to: valid for the callback, until the next resolve.
const struct rediwm_clip *clip;
- // Set exactly for REDIWM_ITEM_SHADOW, with the same lifetime as `clip`.
- const struct rediwm_shadow *shadow;
+ // Exclusive procedural payload. Shadows have the lifetime of `clip`;
+ // ribbons belong to their transport node. Ordinary items keep this NULL.
+ union {
+ const struct rediwm_shadow *shadow;
+ const struct rediwm_ribbon *ribbon; // node-owned; normalized to edges
+ }; // exclusive procedural kinds; ordinary items do not grow for optional effects
};
diff --git a/src/scene_output.c b/src/scene_output.c
index 47ea6f9..3f7568a 100644
--- a/src/scene_output.c
+++ b/src/scene_output.c
@@ -29,6 +29,9 @@ bool rediwm_output_renderer_enable_backdrops(struct rediwm_output_renderer *r) {
r->has_backdrops = rediwm_scene_renderer_enable_backdrops(r->pass);
return r->has_backdrops;
}
+bool rediwm_output_renderer_set_ribbons(struct rediwm_output_renderer *r, bool enabled) {
+ return rediwm_scene_renderer_set_ribbons(r->pass, enabled);
+}
static void cache_destroy(struct rediwm_output_renderer *r, struct effect_cache *c) {
rediwm_scene_renderer_destroy_backdrop(r->pass, c->backdrop);
wl_list_remove(&c->link);
diff --git a/src/scene_output.h b/src/scene_output.h
index 4548de5..f73cf8f 100644
--- a/src/scene_output.h
+++ b/src/scene_output.h
@@ -1,5 +1,9 @@
#pragma once
#include <stdbool.h>
+#include <wlr/util/box.h>
+struct rediwm_node;
+struct rediwm_buffer;
+struct rediwm_read_fence;
struct wlr_renderer;
struct rediwm_scene_output;
struct wlr_output_state;
@@ -33,3 +37,6 @@ bool rediwm_scene_output_build_state(struct rediwm_output_renderer *,
// above every effect. Direct scan-out waits until it is 0. False only when the
// state for a nonzero veil could not be allocated.
bool rediwm_scene_output_set_veil(struct rediwm_output_renderer *, struct rediwm_scene_output *, float alpha);
+bool rediwm_output_snapshot(struct rediwm_output_renderer *, struct rediwm_projection *,
+ struct rediwm_scene_output *, struct rediwm_node *, struct wlr_box, float,
+ struct wlr_buffer *, struct rediwm_read_fence *, struct rediwm_buffer *);
diff --git a/src/scene_output.zig b/src/scene_output.zig
index 3a84963..c8932a5 100644
--- a/src/scene_output.zig
+++ b/src/scene_output.zig
@@ -7,6 +7,8 @@ extern var rediwm_scene_output_reblurs: u64;
pub const reblurs: *u64 = &rediwm_scene_output_reblurs;
pub const Renderer = opaque {
+ extern fn rediwm_output_renderer_set_ribbons(renderer: *Renderer, enabled: bool) bool;
+ pub const setRibbons = rediwm_output_renderer_set_ribbons;
extern fn rediwm_output_renderer_create(renderer: *wlr.Renderer) ?*Renderer;
pub const create = rediwm_output_renderer_create;
extern fn rediwm_output_renderer_enable_shapes(renderer: *Renderer) bool;
diff --git a/src/scene_output_collect.c b/src/scene_output_collect.c
index 355f302..bb200d5 100644
--- a/src/scene_output_collect.c
+++ b/src/scene_output_collect.c
@@ -66,6 +66,8 @@ bool scene_output_collect(const struct rediwm_item *item, struct rediwm_node *tr
// and the surface's own tint shows, as glass.c's fallback did.
skip = !here || !r->has_backdrops || item->content.opacity == 0 ||
!rediwm_glass_effect_info(transport, &glass) || glass.opacity <= 0;
+ } else if (item->kind == REDIWM_ITEM_RIBBON) {
+ skip = item->content.opacity == 0 || item->ribbon->count < 4;
} else if (item->kind == REDIWM_ITEM_SHADOW) {
// No buffer: the pixels are the shadow's, and never opaque.
skip = item->content.opacity == 0 || item->shadow->color[3] == 0;
@@ -100,7 +102,7 @@ bool scene_output_collect(const struct rediwm_item *item, struct rediwm_node *tr
return true;
}
bool full = item->kind == REDIWM_ITEM_RECT && item->content.color[3] == 1;
- if (item->kind != REDIWM_ITEM_RECT && item->kind != REDIWM_ITEM_SHADOW) {
+ if (item->kind != REDIWM_ITEM_RECT && item->kind != REDIWM_ITEM_SHADOW && item->kind != REDIWM_ITEM_RIBBON) {
struct rediwm_buffer *b = rediwm_buffer_from_node(transport);
// Match the surface adapter's opacity policy. A cached raster whose
// buffer was released must not suddenly hide previously visible peers.
diff --git a/src/scene_output_draw.c b/src/scene_output_draw.c
index b8be6c6..abd205a 100644
--- a/src/scene_output_draw.c
+++ b/src/scene_output_draw.c
@@ -225,6 +225,10 @@ bool scene_output_render_entry(struct rediwm_output_renderer *r, struct entry *e
goto done;
}
if (!pixman_region32_not_empty(&clip)) goto done;
+ if (e->item.kind == REDIWM_ITEM_RIBBON) {
+ scene_output_render_ribbon(e, pass, v, dst, &clip);
+ goto done;
+ }
// A clipped item is drawn in two parts: `core` (its interior, which the model
// proves fully covered and opaque) as before, without the shape, and the rest
// (corners, ring, anything translucent) through the shape.
diff --git a/src/scene_output_internal.h b/src/scene_output_internal.h
index 7f57c46..e77d883 100644
--- a/src/scene_output_internal.h
+++ b/src/scene_output_internal.h
@@ -13,6 +13,7 @@
#include "scene_graph.h"
#include "projection.h"
#include "glass.h"
+#include "ribbon.h"
#include "node.h"
#include <math.h>
#include <stdlib.h>
@@ -123,6 +124,8 @@ struct collector {
};
// Shared between the parts (scene_output_*.c).
+void scene_output_render_ribbon(struct entry *, struct wlr_render_pass *,
+ const struct output_view *, struct wlr_box, const pixman_region32_t *);
extern uint64_t rediwm_scene_output_reblurs;
bool scene_output_collect(const struct rediwm_item *item, struct rediwm_node *transport, void *data);
void scene_output_clear_entries(struct rediwm_output_renderer *r);
diff --git a/src/scene_output_ribbon.c b/src/scene_output_ribbon.c
new file mode 100644
index 0000000..c346b93
--- /dev/null
+++ b/src/scene_output_ribbon.c
@@ -0,0 +1,23 @@
+#include "scene_output_internal.h"
+#include "ribbon.h"
+
+void scene_output_render_ribbon(struct entry *e, struct wlr_render_pass *pass,
+ const struct output_view *v, struct wlr_box dst, const pixman_region32_t *clip) {
+ struct rediwm_ribbon mesh = *e->item.ribbon;
+ // The same affine corner transform as shapes, preserving subpixel vertices.
+ 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 float w = (v->transform & 1) ? dst.height : dst.width;
+ const float h = (v->transform & 1) ? dst.width : dst.height;
+ for (uint32_t j = 0; j < mesh.count; j++) {
+ const float x = mesh.vertices[j][0] * w, y = mesh.vertices[j][1] * h;
+ for (int i = 0; i < 2; i++)
+ mesh.vertices[j][i] = ex[i] * x + ey[i] * y + (ex[i] < 0 ? w : 0) + (ey[i] < 0 ? h : 0);
+ }
+ struct rediwm_buffer *buffer = rediwm_buffer_from_node(e->transport);
+ rediwm_scene_pass_add_ribbon(pass, dst, &mesh, clip, e->item.content.opacity,
+ mesh.edge == 2 ? buffer->texture : NULL);
+}
diff --git a/src/scene_output_snapshot.c b/src/scene_output_snapshot.c
new file mode 100644
index 0000000..02c704e
--- /dev/null
+++ b/src/scene_output_snapshot.c
@@ -0,0 +1,64 @@
+// A frozen, shaped window for the minimize ribbon. Reuse resolved geometry and
+// the ordinary draw path, without changing output visibility or surface feedback.
+#include "scene_output_internal.h"
+#include "explicit_sync.h"
+#include "node_surface.h"
+
+struct snapshot {
+ struct rediwm_output_renderer *renderer;
+ struct rediwm_scene_output *out;
+ struct rediwm_node *root;
+ struct rediwm_read_fence *fence;
+ struct wlr_render_pass *pass;
+ struct output_view view;
+ pixman_region32_t damage;
+ unsigned count;
+};
+
+static bool snapshot_item(const struct rediwm_item *item, struct rediwm_node *node, void *data) {
+ struct snapshot *s = data;
+ if (item->kind == REDIWM_ITEM_EFFECT || item->kind == REDIWM_ITEM_SHADOW ||
+ item->kind == REDIWM_ITEM_RIBBON) return true;
+ struct rediwm_node *ancestor = node;
+ while (ancestor && ancestor != s->root)
+ ancestor = ancestor->parent ? &ancestor->parent->node : NULL;
+ if (!ancestor) return true;
+ struct rediwm_buffer *buffer = rediwm_buffer_from_node(node);
+ if (item->content.opacity == 0 || (item->kind == REDIWM_ITEM_RECT && item->content.color[3] == 0) ||
+ (buffer && !buffer->buffer && !buffer->texture && !buffer->is_single_pixel_buffer)) return true;
+ struct rediwm_snap b = rediwm_edges_snap(item->edges);
+ struct entry e = {.item = *item, .transport = node, .box = {b.x, b.y, b.width, b.height}};
+ pixman_region32_init_rect(&e.visible, b.x, b.y, b.width, b.height);
+ pixman_region32_init(&e.opaque);
+ if (buffer && buffer->surface) rediwm_read_fence_note(s->fence, buffer->surface->surface);
+ bool ok = scene_output_render_entry(s->renderer, &e, s->out, s->pass, &s->view, &s->damage, false);
+ pixman_region32_fini(&e.opaque);
+ pixman_region32_fini(&e.visible);
+ s->count++;
+ return ok;
+}
+
+bool rediwm_output_snapshot(struct rediwm_output_renderer *r, struct rediwm_projection *projection,
+ struct rediwm_scene_output *out, struct rediwm_node *root, struct wlr_box box, float scale,
+ struct wlr_buffer *buffer, struct rediwm_read_fence *fence, struct rediwm_buffer *dest) {
+ struct wlr_buffer_pass_options options = {0};
+ rediwm_read_fence_begin(fence, &options);
+ struct wlr_render_pass *pass = rediwm_output_begin_pass(r, buffer, &options);
+ if (!pass) { rediwm_read_fence_end(fence, false); return false; }
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {0, 0, buffer->width, buffer->height}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ struct snapshot s = {.renderer = r, .out = out, .root = root, .pass = pass, .fence = fence,
+ .view = {.logical = box, .scale = scale, .width = buffer->width, .height = buffer->height,
+ .trans_width = buffer->width, .trans_height = buffer->height}};
+ pixman_region32_init_rect(&s.damage, 0, 0, buffer->width, buffer->height);
+ bool ok = rediwm_projection_for_each_item(projection, false, snapshot_item, &s);
+ bool submitted = wlr_render_pass_submit(pass);
+ rediwm_read_fence_end(fence, submitted);
+ pixman_region32_fini(&s.damage);
+ if (!ok || !submitted || !s.count) return false;
+ struct wlr_texture *texture = wlr_texture_from_buffer(out->output->renderer, buffer);
+ if (!texture) return false;
+ rediwm_buffer_set_buffer(dest, buffer);
+ rediwm_buffer_set_texture(dest, texture);
+ return true;
+}
diff --git a/src/scene_pass.c b/src/scene_pass.c
index 09962b9..4e098a2 100644
--- a/src/scene_pass.c
+++ b/src/scene_pass.c
@@ -212,7 +212,7 @@ static GLuint shader(GLenum type, const char *prefix, const char *source) {
}
return id;
}
-static bool program_init(struct program *p, unsigned bit, const char *vertex_source,
+bool scene_pass_program_init(struct program *p, unsigned bit, const char *vertex_source,
const char *prefix, const char *source) {
p->bit = bit;
GLuint vs = shader(GL_VERTEX_SHADER, "", vertex_source);
@@ -304,7 +304,7 @@ struct rediwm_scene_renderer *rediwm_scene_renderer_create(struct wlr_renderer *
// Every draw goes through the shaped programs; one without a shape costs a
// uniform branch. A GL program costs the driver 130-150 KiB however small,
// so the plain ones are gone (stage 5, D4 of docs/plans/scene-graph-stage5.md).
- bool ok = program_init(&r->shaped, 8, shaped_vertex, "uniform sampler2D tex;\n", shaped_fragment);
+ bool ok = scene_pass_program_init(&r->shaped, 8, shaped_vertex, "uniform sampler2D tex;\n", shaped_fragment);
r->has_shapes = r->shapes_tried = ok;
if (ok && r->has_vao) {
r->gen_vertex_arrays(1, &r->vertex_array);
@@ -337,6 +337,8 @@ void rediwm_scene_renderer_destroy(struct rediwm_scene_renderer *r) {
glDeleteProgram(r->shaped_external.id);
glDeleteProgram(r->shaped_poly.id);
glDeleteProgram(r->shaped_poly_external.id);
+ glDeleteProgram(r->ribbon.id);
+ glDeleteBuffers(1, &r->ribbon_vertices);
glDeleteProgram(r->blur.id);
glDeleteTextures(1, &r->prefix_tex);
glDeleteFramebuffers(1, &r->prefix_fbo);
@@ -361,7 +363,7 @@ bool rediwm_scene_renderer_enable_external(struct rediwm_scene_renderer *r) {
if (!r->has_external) return r->external_ok = true;
struct gl_state state;
if (!scene_pass_enter(r, &state)) return false;
- r->external_ok = program_init(&r->shaped_external, 16, shaped_vertex, ext_prefix, shaped_fragment);
+ r->external_ok = scene_pass_program_init(&r->shaped_external, 16, shaped_vertex, ext_prefix, shaped_fragment);
scene_pass_leave(r, &state);
return r->external_ok;
}
@@ -374,8 +376,8 @@ bool rediwm_scene_renderer_enable_polygons(struct rediwm_scene_renderer *r) {
if (!r->has_shapes) return false;
struct gl_state state;
if (!scene_pass_enter(r, &state)) return false;
- r->has_polys = program_init(&r->shaped_poly, 64, shaped_vertex, "#define POLY 1\nuniform sampler2D tex;\n", shaped_fragment) &&
- (!r->has_external || program_init(&r->shaped_poly_external, 128, shaped_vertex,
+ r->has_polys = scene_pass_program_init(&r->shaped_poly, 64, shaped_vertex, "#define POLY 1\nuniform sampler2D tex;\n", shaped_fragment) &&
+ (!r->has_external || scene_pass_program_init(&r->shaped_poly_external, 128, shaped_vertex,
"#extension GL_OES_EGL_image_external : require\n#define POLY 1\nuniform samplerExternalOES tex;\n", shaped_fragment));
if (!r->has_polys) {
wlr_log(WLR_ERROR, "scene pass: polygon programs failed to build, outlines are not drawn");
@@ -394,7 +396,7 @@ bool rediwm_scene_renderer_enable_backdrops(struct rediwm_scene_renderer *r) {
if (!r->has_shapes) return false;
struct gl_state state;
if (!scene_pass_enter(r, &state)) return false;
- r->has_backdrops = program_init(&r->blur, 32, blur_vertex, "", blur_fragment);
+ r->has_backdrops = scene_pass_program_init(&r->blur, 32, blur_vertex, "", blur_fragment);
if (!r->has_backdrops) {
wlr_log(WLR_ERROR, "scene pass: blur program failed to build, glass is a plain tint");
glDeleteProgram(r->blur.id);
diff --git a/src/scene_pass.h b/src/scene_pass.h
index 38f9bc2..fbe73c0 100644
--- a/src/scene_pass.h
+++ b/src/scene_pass.h
@@ -7,6 +7,10 @@
#include <wlr/util/box.h>
struct rediwm_scene_renderer;
+struct rediwm_ribbon;
+bool rediwm_scene_renderer_set_ribbons(struct rediwm_scene_renderer *, bool);
+void rediwm_scene_pass_add_ribbon(struct wlr_render_pass *, struct wlr_box,
+ const struct rediwm_ribbon *, const pixman_region32_t *, float, struct wlr_texture *);
// The renderer must be GLES2 and outlive this object and all its passes.
struct rediwm_scene_renderer *rediwm_scene_renderer_create(struct wlr_renderer *);
void rediwm_scene_renderer_destroy(struct rediwm_scene_renderer *);
diff --git a/src/scene_pass_internal.h b/src/scene_pass_internal.h
index 7b74dbf..144fc81 100644
--- a/src/scene_pass_internal.h
+++ b/src/scene_pass_internal.h
@@ -72,7 +72,9 @@ struct rediwm_scene_renderer {
bool polys_tried, has_polys;
// Backdrops (stage 5b), built by enable_backdrops: the blur, and scratch the
// size of the largest region so far: the copy, and the horizontal pass.
- struct program blur;
+ struct program blur, ribbon;
+ GLuint ribbon_vertices;
+ GLint ribbon_fade;
GLuint prefix_tex, prefix_fbo, small_tex, small_fbo;
int small_w, small_h;
bool has_backdrops, backdrops_tried;
@@ -163,6 +165,7 @@ static inline struct pass *owned_pass(struct wlr_render_pass *base) {
}
// Shared between the parts (scene_pass_*.c).
+bool scene_pass_program_init(struct program *, unsigned, const char *, const char *, const char *);
// Makes the renderer's EGL context current, saving the caller's context and GL
// state in `s`.
bool scene_pass_enter(struct rediwm_scene_renderer *r, struct gl_state *s);
diff --git a/src/scene_pass_ribbon.c b/src/scene_pass_ribbon.c
new file mode 100644
index 0000000..285873b
--- /dev/null
+++ b/src/scene_pass_ribbon.c
@@ -0,0 +1,192 @@
+// Optional ribbon program: never built or visited by ordinary window draws.
+#include "scene_pass_internal.h"
+#include "ribbon.h"
+
+static const char ribbon_vertex[] =
+ "attribute vec4 position; uniform vec2 target; uniform vec4 dst;"
+ "uniform mediump int mode; uniform mediump vec2 fade;"
+ "varying vec2 ribbon; void main(){"
+ "vec2 p=dst.xy+position.xy;"
+ // A strip is a sequence of trapezoids. Perspective-correct interpolation
+ // with reciprocal row width prevents each triangle shearing the text in
+ // opposite directions (visible as a zipper along every vertical edge).
+ "float w=1.; if(mode==2){"
+ "float along=mix(position.w,1.-position.w,fade.y);"
+ "float pull=smoothstep(0.,1.,(fade.x*1.5-(1.-along)*.58)/.92);"
+ "float remain=1.-pull;"
+ "w=1./max(.0001,remain*remain+.015*pull*(1.-fade.x));"
+ "}"
+ "gl_Position=vec4((p/target*2.-1.)*w,0.,w); ribbon=position.zw; }";
+static const char ribbon_fragment[] =
+ "#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n"
+ "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n"
+ "varying vec2 ribbon; uniform vec4 color, bcolor;"
+ "uniform mediump int mode; uniform mediump vec2 fade; uniform sampler2D tex; uniform float alpha;"
+ // Thin luminous creases over translucent sheets, with dark space between
+ // folds. The Gaussian halo stays coloured; only the finest cores go hot.
+ // Divide before squaring so the finest widths do not underflow on mediump.
+ "float ridge(float x,float w){ float q=min(abs(x)/w,8.); return exp(-q*q); }"
+ // Approximate pixel coverage without fattening subpixel creases into tubes.
+ "float filament(float x,float w){\n"
+ "#ifdef GL_OES_standard_derivatives\n"
+ "float pixel=length(vec2(dFdx(x),dFdy(x)));"
+ "float filtered=sqrt(w*w+pixel*pixel/6.);"
+ "return ridge(x,filtered)*w/filtered;\n"
+ "#else\nreturn ridge(x,w);\n#endif\n}"
+ // Both the flames and their connecting sheet erase from tail to sources.
+ "float trailOpacity(float t){"
+ "float front=mix(-.12,1.12,1.-fade.y);"
+ "return mix(fade.x,1.,t)*smoothstep(front-.10,front+.10,t)*smoothstep(0.,.14,t)"
+ "*(1.-smoothstep(1.,2.,ribbon.y));"
+ "}"
+ "void main(){ float x=ribbon.x, d=abs(x), t=clamp(ribbon.y,0.,1.);"
+ "if(mode==2){"
+ "vec2 uv=ribbon; float p=fade.x;"
+ "float along=mix(uv.y,1.-uv.y,fade.y);"
+ "float wave=.018*sin(uv.x*23.+p*17.)+.012*sin(uv.x*51.-p*11.);"
+ // Consume the full sheet while it still has width, before the pull
+ // collapses it into the destination. Both side creases ignite with it.
+ "float front=1.04-1.85*p+wave*sin(p*3.141593);"
+ "float burn=along-front;"
+ "float alive=1.-smoothstep(-.035,.035,burn);"
+ "float inside=step(0.,uv.x)*step(uv.x,1.);"
+ "vec4 body=texture2D(tex,clamp(uv,0.,1.))*inside;"
+ "float edge=min(abs(uv.x),abs(1.-uv.x));"
+ "float lit=smoothstep(-.10,.02,burn);"
+ "float hot=filament(edge,.0028)*lit+filament(burn,.006)*inside;"
+ "float glow=.42*ridge(edge,.018)*lit+.48*ridge(burn,.045)*inside;"
+ "float light=clamp(hot+glow,0.,1.)*smoothstep(0.,.12,p)*(1.-smoothstep(.82,1.,p));"
+ "vec4 fire=mix(color,bcolor,clamp(hot,0.,1.)*.92);"
+ "float a=light*fire.a;"
+ "float fold=.12*sin(along*15.-p*9.)*sin(p*3.141593);"
+ "float ghost=.10*(1.-alive)*(1.-smoothstep(.04,.20,burn));"
+ "body*=(alive+ghost)*(1.-smoothstep(.78,1.,p))*(1.-.38*smoothstep(.15,.85,along)*p)*alpha;"
+ "body.rgb*=1.+fold; body.rgb=min(body.rgb,vec3(body.a));"
+ "gl_FragColor=vec4(fire.rgb*a,a)+body*(1.-a); return;"
+ "}"
+ "float core, light, opacity=t;"
+ "if(mode==1){"
+ "core=ridge(d,.055);"
+ "light=.56*exp(-5.*d)+.44*ridge(d,.19)+core;"
+ "}else if(mode==3){"
+ "float rim=d-.90;"
+ "float f=.40*sin(t*12.566371+fade.y);"
+ "core=.35*filament(rim,.009)+.16*filament(x-f,.007);"
+ // The resize band joins two outlines. Keep a continuous translucent
+ // sheet across its full width, including the window and target edges.
+ "light=core+.22+.18*ridge(rim,.045)+.12*ridge(x,.65)"
+ "+.16*ridge(x-f,.10)+.09*ridge(x+f*.7,.20);"
+ "opacity=fade.x;"
+ "}else if(mode==4){"
+ // A low-opacity colour wash, stronger near the window and softly
+ // feathered into the two flames. No hot creases in the middle.
+ "core=0.;"
+ "light=.10*(.55+.45*d*d)*smoothstep(0.,1.,t);"
+ "opacity=trailOpacity(t);"
+ "}else{"
+ // Two attachment points (x = +/- .55) feed the edges of one sheet.
+ // The edges meet farther down the trail, retaining a single bright tail.
+ "float split=smoothstep(.30,.92,t);"
+ "float center=.16*sin(t*7.)*(1.-t);"
+ "float spread=.55*split;"
+ "float a=x-center-spread,b=x-center+spread;"
+ // Fine roots and a hairline tail, swelling gently through the fold.
+ // Different profiles keep the two creases from reading as parallel tubes.
+ "float swell=sin(t*3.141593);"
+ "float wa=.009+.015*swell*swell;"
+ "float wb=.008+.012*swell*(.7+.3*sin(t*5.+.6));"
+ "core=.45*clamp(filament(a,wa)+.82*filament(b,wb),0.,1.);"
+ "float sheet=.28*ridge(x-center,.12+spread);"
+ "float fold=.13*ridge(x-center-.12*sin(t*9.)*(1.-t),.045);"
+ "light=.09*ridge(x-center,.70)+sheet+fold"
+ "+.20*ridge(a,wa*2.8+.015)+.18*ridge(b,wb*2.8+.015)+core;"
+ // Advance a soft erasing front from the frozen tail to its sources.
+ // At rest only coverage changes; the surviving folds stay in place.
+ "opacity=trailOpacity(t);"
+ "}"
+ "float coverage=mode==3?1.:1.-smoothstep(.78,1.,d);"
+ "float a=opacity*clamp(light,0.,1.)*coverage;"
+ "vec4 c=mix(color,bcolor,core*.92);"
+ "gl_FragColor=vec4(c.rgb*c.a*a,c.a*a); }";
+
+bool rediwm_scene_renderer_set_ribbons(struct rediwm_scene_renderer *r, bool enabled) {
+ assert(!r->active);
+ if (enabled == (r->ribbon.id != 0)) return true;
+ struct gl_state state;
+ if (!scene_pass_enter(r, &state)) return false;
+ bool ok = true;
+ if (enabled) {
+ ok = scene_pass_program_init(&r->ribbon, 256, ribbon_vertex, "", ribbon_fragment);
+ if (ok) {
+ r->ribbon_fade = glGetUniformLocation(r->ribbon.id, "fade");
+ glGenBuffers(1, &r->ribbon_vertices);
+ ok = r->ribbon_vertices && glGetError() == GL_NO_ERROR;
+ }
+ }
+ if (!enabled || !ok) {
+ glDeleteProgram(r->ribbon.id);
+ glDeleteBuffers(1, &r->ribbon_vertices);
+ r->ribbon = (struct program){0};
+ r->ribbon_vertices = 0;
+ }
+ scene_pass_leave(r, &state);
+ return ok;
+}
+
+void rediwm_scene_pass_add_ribbon(struct wlr_render_pass *base, struct wlr_box box,
+ const struct rediwm_ribbon *mesh, const pixman_region32_t *clip, float opacity,
+ struct wlr_texture *texture) {
+ struct pass *p = owned_pass(base);
+ struct rediwm_scene_renderer *r = p->renderer;
+ if (p->failed || mesh->count < 4 || !pixman_region32_not_empty((pixman_region32_t *)clip)) return;
+ if (!r->ribbon.id || mesh->count > REDIWM_RIBBON_VERTICES) { p->failed = true; return; }
+ scene_pass_setup(p, &r->ribbon, box, WLR_RENDER_BLEND_MODE_PREMULTIPLIED);
+ glUniform1i(r->ribbon.mode, mesh->edge);
+ glUniform1f(r->ribbon.alpha, opacity);
+ if (mesh->edge == 2) {
+ if (!texture || !wlr_texture_is_gles2(texture)) { p->failed = true; return; }
+ struct wlr_gles2_texture_attribs a;
+ wlr_gles2_texture_get_attribs(texture, &a);
+ if (a.target != GL_TEXTURE_2D) { p->failed = true; return; }
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture(GL_TEXTURE_2D, a.tex);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glUniform1i(r->ribbon.sampler, 0);
+ }
+ glUniform2fv(r->ribbon_fade, 1, mesh->fade);
+ glUniform4f(r->ribbon.color, mesh->color[0], mesh->color[1], mesh->color[2], mesh->color[3] * opacity);
+ glUniform4f(r->ribbon.bcolor, mesh->core_color[0], mesh->core_color[1], mesh->core_color[2], mesh->core_color[3] * opacity);
+ glBindBuffer(GL_ARRAY_BUFFER, r->ribbon_vertices);
+ float vertices[REDIWM_RIBBON_VERTICES][4];
+ const void *data = mesh->vertices;
+ if (p->redirected) {
+ // Backdrop captures have already scaled dst; their mesh offsets must
+ // follow it into the reduced image as well.
+ for (uint32_t i = 0; i < mesh->count; i++) {
+ for (int j = 0; j < 4; j++) vertices[i][j] = mesh->vertices[i][j];
+ vertices[i][0] /= p->factor;
+ vertices[i][1] /= p->factor;
+ }
+ data = vertices;
+ }
+ glBufferData(GL_ARRAY_BUFFER, mesh->count * sizeof(mesh->vertices[0]), data, GL_STREAM_DRAW);
+ glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
+ glEnableVertexAttribArray(0);
+ int n;
+ const pixman_box32_t *boxes = pixman_region32_rectangles((pixman_region32_t *)clip, &n);
+ glEnable(GL_SCISSOR_TEST);
+ for (int i = 0; i < n; i++) {
+ if (p->redirected) {
+ const int x1 = floorf((boxes[i].x1 - p->region.x) / p->factor);
+ const int y1 = floorf((boxes[i].y1 - p->region.y) / p->factor);
+ const int x2 = ceilf((boxes[i].x2 - p->region.x) / p->factor);
+ const int y2 = ceilf((boxes[i].y2 - p->region.y) / p->factor);
+ glScissor(x1, y1, x2 - x1, y2 - y1);
+ } else glScissor(boxes[i].x1, boxes[i].y1, boxes[i].x2 - boxes[i].x1, boxes[i].y2 - boxes[i].y1);
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, mesh->count);
+ }
+ // Restore the quad VAO/attribute used by every subsequent owned draw.
+ glBindBuffer(GL_ARRAY_BUFFER, r->has_vao ? r->vertices : 0);
+ glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, r->has_vao ? NULL : positions);
+}
diff --git a/src/scene_pass_test.c b/src/scene_pass_test.c
index 18eb54c..eadafe4 100644
--- a/src/scene_pass_test.c
+++ b/src/scene_pass_test.c
@@ -3,6 +3,7 @@
#include "scene_pass.c"
#include "scene_pass_draw.c"
#include "scene_pass_backdrop.c"
+#include "scene_pass_ribbon.c"
#include "scene_graph.h"
#include <math.h>
#include <stdarg.h>
@@ -96,6 +97,7 @@ static struct wlr_texture *texture_create(struct wlr_renderer *renderer, bool op
#include "scene_pass_test_sector.c"
#include "scene_pass_test_shading.c"
#include "scene_pass_test_backdrop.c"
+#include "scene_pass_test_ribbon.c"
int main(void) {
wlr_log_init(WLR_ERROR, NULL);
@@ -119,6 +121,7 @@ int main(void) {
parity(r, actual, expected, true);
damage(r, actual, expected);
state_restoration(r, actual);
+ ribbon_gate(r, actual);
external_texture(r, allocator, actual, expected);
external_yuv(r, actual, expected);
synchronization(r, actual);
@@ -134,6 +137,7 @@ int main(void) {
parity(r, actual, expected, false);
parity(r, actual, expected, true);
state_restoration(r, actual);
+ ribbon_gate(r, actual);
r->has_vao = true;
}
rediwm_scene_renderer_destroy(r);
diff --git a/src/scene_pass_test_ribbon.c b/src/scene_pass_test_ribbon.c
new file mode 100644
index 0000000..81e8f63
--- /dev/null
+++ b/src/scene_pass_test_ribbon.c
@@ -0,0 +1,209 @@
+// Use a flat sheet to observe the consuming front independently of its pull.
+static void ribbon_minimize(struct rediwm_scene_renderer *r, struct wlr_buffer *buf,
+ const pixman_region32_t *clip) {
+ const uint32_t blue = 0xff2040c0;
+ struct wlr_texture *texture = wlr_texture_from_pixels(r->renderer, DRM_FORMAT_ARGB8888, 4, 1, 1, &blue);
+ assert(texture);
+ struct rediwm_ribbon mesh = {.edge = 2, .count = 96,
+ .color = {1, 0, 0, 1}, .core_color = {1, .7, .5, 1}};
+ for (int i = 0; i < 96; i++) {
+ mesh.vertices[i][0] = (i % 2) * 80;
+ mesh.vertices[i][1] = (i / 2) * 60.f / 47;
+ mesh.vertices[i][2] = i % 2;
+ mesh.vertices[i][3] = (i / 2) / 47.f;
+ }
+ const float progress[] = {0, .18, .4, .68};
+ for (int direction = 0; direction < 2; direction++) {
+ mesh.fade[1] = direction;
+ for (size_t frame = 0; frame < sizeof(progress) / sizeof(progress[0]); frame++) {
+ mesh.fade[0] = progress[frame];
+ struct wlr_render_pass *pass = rediwm_scene_pass_begin(r, buf, NULL);
+ assert(pass);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {0, 0, WIDTH, HEIGHT}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ rediwm_scene_pass_add_ribbon(pass, (struct wlr_box){10, 10, 80, 60}, &mesh, clip, 1, texture);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {100, 70, 20, 15}, .color = {0, 1, 0, 1}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ assert(wlr_render_pass_submit(pass));
+ uint8_t pixels[WIDTH * HEIGHT * 4];
+ read_pixels(r, buf, pixels);
+ const int far = direction ? 59 : 20, near = direction ? 20 : 59;
+ if (frame == 0) {
+ assert(pixels[(far * WIDTH + 50) * 4 + 2] == 192);
+ assert(pixels[(near * WIDTH + 50) * 4 + 2] == 192);
+ } else if (frame < 3) {
+ assert(pixels[(far * WIDTH + 50) * 4 + 2] > 120);
+ assert(pixels[(near * WIDTH + 50) * 4 + 3] < 25);
+ // Both vertical sides light from the consuming edge only.
+ for (int x = 10; x <= 89; x += 79) {
+ assert(pixels[(far * WIDTH + x) * 4] < 60);
+ assert(pixels[(near * WIDTH + x) * 4] > 100);
+ }
+ } else {
+ // The front eats the entire body before the final collapse;
+ // only the lit sides may remain outside this interior region.
+ for (int y = 10; y < 70; y++)
+ for (int x = 20; x < 80; x++) assert(pixels[(y * WIDTH + x) * 4 + 3] < 8);
+ for (int x = 10; x <= 89; x += 79) assert(pixels[(far * WIDTH + x) * 4] > 100);
+ }
+ assert(pixels[(75 * WIDTH + 110) * 4 + 1] == 255);
+ for (size_t i = 0; i < sizeof(pixels); i += 4)
+ for (int c = 0; c < 3; c++) assert(pixels[i + c] <= pixels[i + 3]);
+ }
+ }
+ wlr_texture_destroy(texture);
+ puts("PASS: minimize consumes the whole sheet and lights both sides with the advancing front");
+}
+
+static void ribbon_drag_sheet(struct rediwm_scene_renderer *r, struct wlr_buffer *buf,
+ const pixman_region32_t *clip, struct rediwm_ribbon mesh) {
+ mesh.edge = 4;
+ mesh.fade[1] = 1;
+ for (int frame = 0; frame < 2; frame++) {
+ struct wlr_render_pass *pass = rediwm_scene_pass_begin(r, buf, NULL);
+ assert(pass);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {0, 0, WIDTH, HEIGHT}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ rediwm_scene_pass_add_ribbon(pass, (struct wlr_box){10, 10, 80, 60}, &mesh, clip, 1, NULL);
+ assert(wlr_render_pass_submit(pass));
+ uint8_t pixels[WIDTH * HEIGHT * 4];
+ read_pixels(r, buf, pixels);
+ int head = pixels[(40 * WIDTH + 85) * 4 + 3];
+ int tail = pixels[(40 * WIDTH + 35) * 4 + 3];
+ assert(frame == 0 ? (head > tail && tail > 0 && head < 25) : head == 0);
+ for (size_t i = 0; i < sizeof(pixels); i += 4)
+ for (int c = 0; c < 3; c++) assert(pixels[i + c] <= pixels[i + 3]);
+ mesh.fade[1] = 0;
+ }
+ puts("PASS: drag sheet is faint, graded towards its sources and fades completely");
+}
+
+// The optional program must respect damage and leave subsequent quad draws intact.
+static void ribbon_gate(struct rediwm_scene_renderer *r, struct wlr_buffer *buf) {
+ assert(!r->ribbon.id && !r->ribbon_vertices);
+ assert(rediwm_scene_renderer_set_ribbons(r, true));
+ assert(rediwm_scene_renderer_set_ribbons(r, true));
+ struct rediwm_ribbon mesh = {.count = 4,
+ .vertices = {{0, 0, -1, .6}, {0, 20, 1, .6}, {80, 0, -1, .6}, {80, 20, 1, .6}},
+ .color = {1, 0, 0, 1}, .core_color = {1, .7, .5, 1}, .fade = {1, 1}};
+ pixman_region32_t clip;
+ pixman_region32_init_rect(&clip, 30, 0, 10, HEIGHT);
+ struct wlr_render_pass *pass = rediwm_scene_pass_begin(r, buf, NULL);
+ assert(pass);
+ clear(pass);
+ rediwm_scene_pass_add_ribbon(pass, (struct wlr_box){10, 10, 80, 20}, &mesh, &clip, 1, NULL);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {50, 50, 30, 20}, .color = {0, 1, 0, 1}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ assert(wlr_render_pass_submit(pass));
+ uint8_t pixels[WIDTH * HEIGHT * 4];
+ read_pixels(r, buf, pixels);
+ int peak = 0;
+ for (int y = 10; y < 30; y++) {
+ int red = pixels[(y * WIDTH + 35) * 4];
+ if (red > peak) peak = red;
+ }
+ assert(peak > 100); // a folded core, not necessarily at the strip's centre
+ assert(abs(pixels[(20 * WIDTH + 25) * 4] - 28) <= 1); // outside damage
+ assert(pixels[(60 * WIDTH + 65) * 4 + 1] == 255); // ordinary quad after mesh
+ // The border profile has a hot edge and a soft outward halo. Read it over
+ // transparency to catch non-premultiplied highlights as well as hard cuts.
+ mesh.edge = 1;
+ for (int i = 0; i < 4; i++) {
+ mesh.vertices[i][2] = i % 2;
+ mesh.vertices[i][3] = 1;
+ }
+ pass = rediwm_scene_pass_begin(r, buf, NULL);
+ assert(pass);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {0, 0, WIDTH, HEIGHT}, .color = {0, 0, 0, 0}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ rediwm_scene_pass_add_ribbon(pass, (struct wlr_box){10, 10, 80, 20}, &mesh, &clip, .8, NULL);
+ assert(wlr_render_pass_submit(pass));
+ read_pixels(r, buf, pixels);
+ int rim = pixels[(10 * WIDTH + 35) * 4];
+ int halo = pixels[(16 * WIDTH + 35) * 4];
+ int far = pixels[(29 * WIDTH + 35) * 4];
+ assert(rim > 150 && halo > 10 && halo < rim && far < 3);
+ for (size_t i = 0; i < sizeof(pixels); i += 4) {
+ assert(pixels[i] <= pixels[i + 3] && pixels[i + 1] <= pixels[i + 3] && pixels[i + 2] <= pixels[i + 3]);
+ }
+ // Two separated, softened sources at the head become one core downstream.
+ mesh.edge = 0;
+ for (int i = 0; i < 4; i++) {
+ mesh.vertices[i][1] = (i % 2) * 60;
+ mesh.vertices[i][2] = (i % 2) * 2 - 1;
+ mesh.vertices[i][3] = i / 2;
+ }
+ pixman_region32_union_rect(&clip, &clip, 0, 0, WIDTH, HEIGHT);
+ pass = rediwm_scene_pass_begin(r, buf, NULL);
+ assert(pass);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {0, 0, WIDTH, HEIGHT}, .color = {0, 0, 0, 0}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ rediwm_scene_pass_add_ribbon(pass, (struct wlr_box){10, 10, 80, 60}, &mesh, &clip, 1, NULL);
+ assert(wlr_render_pass_submit(pass));
+ read_pixels(r, buf, pixels);
+ const int columns[] = {35, 85};
+ for (int i = 0; i < 2; i++) {
+ int peaks = 0;
+ bool previous = false;
+ for (int y = 10; y < 70; y++) {
+ bool hot = pixels[(y * WIDTH + columns[i]) * 4 + 1] > 12;
+ if (hot && !previous) peaks++;
+ previous = hot;
+ }
+ assert(peaks == i + 1);
+ }
+ // A stopped trail erases from its tail (left) towards its sources (right),
+ // keeping the surviving head bright until the front reaches it.
+ for (int frame = 0; frame < 2; frame++) {
+ mesh.fade[1] = frame == 0 ? .5 : 0;
+ pass = rediwm_scene_pass_begin(r, buf, NULL);
+ assert(pass);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {0, 0, WIDTH, HEIGHT}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ rediwm_scene_pass_add_ribbon(pass, (struct wlr_box){10, 10, 80, 60}, &mesh, &clip, 1, NULL);
+ assert(wlr_render_pass_submit(pass));
+ read_pixels(r, buf, pixels);
+ int head = 0;
+ for (int y = 10; y < 70; y++) {
+ assert(pixels[(y * WIDTH + 35) * 4 + 3] == 0);
+ int alpha = pixels[(y * WIDTH + 85) * 4 + 3];
+ if (alpha > head) head = alpha;
+ }
+ assert(frame == 0 ? head > 100 : head == 0);
+ }
+ puts("PASS: stopped ribbons erase from tail to head");
+ ribbon_drag_sheet(r, buf, &clip, mesh);
+ ribbon_minimize(r, buf, &clip);
+ mesh.edge = 3;
+ mesh.count = 4;
+ mesh.fade[0] = 1;
+ mesh.fade[1] = 0;
+ for (int i = 0; i < 4; i++) {
+ mesh.vertices[i][0] = (i % 2) * 80;
+ mesh.vertices[i][1] = (i / 2) * 60;
+ mesh.vertices[i][2] = (i % 2) * 2 - 1;
+ mesh.vertices[i][3] = i / 2;
+ }
+ pass = rediwm_scene_pass_begin(r, buf, NULL);
+ assert(pass);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
+ .box = {0, 0, WIDTH, HEIGHT}, .blend_mode = WLR_RENDER_BLEND_MODE_NONE});
+ rediwm_scene_pass_add_ribbon(pass, (struct wlr_box){10, 10, 80, 60}, &mesh, &clip, 1, NULL);
+ assert(wlr_render_pass_submit(pass));
+ read_pixels(r, buf, pixels);
+ assert(pixels[(40 * WIDTH + 50) * 4] > 15); // translucent rectangular band
+ // The resize sheet must reach BOTH outlines. The trail's edge fade used
+ // to leave transparent gutters here, increasingly wide on large resizes.
+ for (int y = 10; y < 70; y++) {
+ for (int x = 10; x < 90; x++) {
+ assert(pixels[(y * WIDTH + x) * 4 + 3] >= 50);
+ }
+ }
+ for (size_t i = 0; i < sizeof(pixels); i += 4)
+ for (int c = 0; c < 3; c++) assert(pixels[i + c] <= pixels[i + 3]);
+ assert(rediwm_scene_renderer_set_ribbons(r, false));
+ assert(!r->ribbon.id && !r->ribbon_vertices);
+ assert(rediwm_scene_renderer_set_ribbons(r, false));
+ pixman_region32_fini(&clip);
+ puts("PASS: two ribbon sources merge, respect damage, restore quad state and release GPU resources");
+}
diff --git a/src/server/setup.zig b/src/server/setup.zig
index ac93ae4..b22a410 100644
--- a/src/server/setup.zig
+++ b/src/server/setup.zig
@@ -198,6 +198,7 @@ fn initSession(server: *Server, world_tree: *sn.Tree) CompositorError!void {
errdefer glass.Engine.destroy(server.glass_engine);
server.output_renderer = scene_output_mod.Renderer.create(renderer) orelse return error.RendererInitFailed;
errdefer scene_output_mod.Renderer.destroy(server.output_renderer);
+ @import("../effects/window_move.zig").configure(server);
if (!greeter and !server.output_renderer.enableExternal()) return error.RendererInitFailed;
log.info("scene renderer: owned GLES2 output pass", .{});
// The window shapes: rounded clip, ring and shadow. Built here, before any
diff --git a/src/server/teardown.zig b/src/server/teardown.zig
index 2cff29d..0236790 100644
--- a/src/server/teardown.zig
+++ b/src/server/teardown.zig
@@ -8,6 +8,8 @@ const log = std.log.scoped(.compositor);
const Server = @import("../Server.zig");
pub fn deinit(server: *Server) void {
+ @import("../effects/window_move.zig").cancel(server);
+ @import("../effects/window_minimize.zig").cancelAll(server);
if (server.theme_job) |job| job.deinit();
server.theme_job = null;
server.undo.clear();
diff --git a/src/toplevel/appearance.zig b/src/toplevel/appearance.zig
index db04fe6..228ee3a 100644
--- a/src/toplevel/appearance.zig
+++ b/src/toplevel/appearance.zig
@@ -16,6 +16,8 @@ const log = std.log.scoped(.toplevel);
const chip_slot_px = Toplevel.chip_slot_px;
pub fn detachInput(toplevel: *Toplevel) void {
+ @import("../effects/window_minimize.zig").cancelFor(toplevel.server, toplevel.id);
+ @import("../effects/window_move.zig").cancelFor(toplevel.server, toplevel.id);
toplevel.server.input.detachToplevel(toplevel);
toplevel.clearDragLift();
toplevel.clearDodge();
diff --git a/src/toplevel/chrome_actions.zig b/src/toplevel/chrome_actions.zig
index cba4389..23595f6 100644
--- a/src/toplevel/chrome_actions.zig
+++ b/src/toplevel/chrome_actions.zig
@@ -55,9 +55,10 @@ pub fn minimize(toplevel: *Toplevel) void {
// X11 clients can ask for this while withdrawn; the stack reorder below
// needs the window to be in it.
if (toplevel.minimized or !toplevel.in_world) return;
- toplevel.minimized = true;
toplevel.detachInput();
toplevel.finishSwitch();
+ @import("../effects/window_minimize.zig").start(toplevel);
+ toplevel.minimized = true;
toplevel.frame_tree.node.setEnabled(false);
const server = toplevel.server;
@@ -111,6 +112,7 @@ pub fn restore(toplevel: *Toplevel) void {
toplevel.server.window_tabs.select(toplevel);
defer if (toplevel.tab_group != 0) @import("../window_tabs.zig").refreshVisibility(toplevel.server);
if (!toplevel.minimized or !toplevel.in_world) return;
+ @import("../effects/window_minimize.zig").cancelFor(toplevel.server, toplevel.id);
toplevel.minimized = false;
toplevel.frame_tree.node.setEnabled(@import("../window_tabs.zig").visible(toplevel));
switch (toplevel.backend) {
diff --git a/src/toplevel/lifecycle.zig b/src/toplevel/lifecycle.zig
index f62a041..24c8bf8 100644
--- a/src/toplevel/lifecycle.zig
+++ b/src/toplevel/lifecycle.zig
@@ -34,9 +34,15 @@ pub fn handleSurfaceCommit(toplevel: *Toplevel) void {
toplevel.positionDuringResize();
+ // An acknowledgement can carry no pixel damage. Pending resize
+ // work still needs a frame, even after the flame has faded away.
+ if (session.dirty and session.outstanding_configure == .none) {
+ if (session.pacing_output) |output| output.wlr_output.scheduleFrame() else toplevel.server.scheduleFrames();
+ }
+
// A queued pre-release commit must not discard the fixed-edge
// snapshot before the client acknowledges the final resize size.
- if (session.settling and session.outstanding_configure == .none) {
+ if (session.settling and !session.dirty and session.outstanding_configure == .none) {
const gen = session.generation;
toplevel.server.input.finishSettlement(gen);
}
diff --git a/src/ui_tests.zig b/src/ui_tests.zig
index 9d0861d..cd70616 100644
--- a/src/ui_tests.zig
+++ b/src/ui_tests.zig
@@ -1,6 +1,11 @@
// Compositor integration/unit-test root. Shared modules have separate test
// targets in build.zig; their roots cannot import compositor code.
test {
+ _ = @import("effects/ribbon.zig");
+ _ = @import("effects/move_heading.zig");
+ _ = @import("effects/minimize_mesh.zig");
+ _ = @import("effects/resize_mesh.zig");
+ _ = @import("effects/resize_follow.zig");
_ = @import("calculator/model.zig");
_ = @import("control_center/search_index.zig");
_ = @import("auto_layout.zig");
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index 7bf2e10..1109243 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Appearance settings: window chrome opacity, inactive window opacity, file-drag dodge, animations controls, Start button logo preview and Start menu size.
+"""Appearance settings: window chrome opacity, inactive window opacity, file-drag dodge, flame effect toggles, animations controls, Start button logo preview and Start menu size.
Verifies UI controls, live compositor updates, and persistence to config.toml.
"""
@@ -319,6 +319,32 @@ def test_appearance_settings():
assert read_config()["compositor"]["inactive_dim"] is True
assert ui.scroll_into_view("inactive_dim").get("on") is True
+ # --- 3d. Flame effects: off by default, independent, saved as they run ---
+ names = ("effect_window_move", "effect_window_resize", "effect_window_minimize")
+ for name in names:
+ toggle = ui.scroll_into_view(name)
+ assert toggle is not None, name
+ assert toggle.get("on") is False, f"{name} should default to off"
+ assert "effects" not in read_config(), "untouched defaults are not written"
+ click_widget(ui.scroll_into_view("effect_window_resize"))
+ effects = read_config()["effects"]
+ assert effects["window_resize"]["enabled"] is True
+ assert "window_move" not in effects and "window_minimize" not in effects, effects
+ assert [ui.scroll_into_view(n).get("on") for n in names] == [False, True, False]
+ # Turning movement on must not drag minimizing along with it.
+ click_widget(ui.scroll_into_view("effect_window_move"))
+ effects = read_config()["effects"]
+ assert effects["window_move"]["enabled"] is True
+ assert effects["window_resize"]["enabled"] is True
+ assert effects["window_minimize"]["enabled"] is False, effects
+ assert [ui.scroll_into_view(n).get("on") for n in names] == [True, True, False]
+ for name in names:
+ if ui.scroll_into_view(name).get("on"):
+ click_widget(ui.scroll_into_view(name))
+ effects = read_config()["effects"]
+ assert not any(effects[k]["enabled"] for k in ("window_move", "window_resize", "window_minimize")), effects
+ assert [ui.scroll_into_view(n).get("on") for n in names] == [False, False, False]
+
# --- 4. Animation speed segmented control ---
# Options: 0.5× (idx 0), 1.0× (idx 1), 1.5× (idx 2), 2.0× (idx 3)
speed_seg = ui.scroll_into_view("anim_speed")
diff --git a/tests/window_ribbons.py b/tests/window_ribbons.py
new file mode 100644
index 0000000..5ed285b
--- /dev/null
+++ b/tests/window_ribbons.py
@@ -0,0 +1,469 @@
+#!/usr/bin/env python3
+"""Optional window trails: pixels, fade, reload, input and idle. Private GLES session."""
+import os
+import signal
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+
+from PIL import Image, ImageChops, ImageDraw
+from desktop_zoom import build_client, wait_for
+from ipc_client import IPCClient, spawn_compositor, stop_process
+
+BASE = '[compositor]\nxwayland = false\n[desktop]\nenabled = false\n'
+ON = BASE + '[effects.window_move]\nenabled = true\n'
+
+
+def assert_idle(ipc, reason):
+ # The taskbar clock legitimately repaints on a wall-clock minute tick.
+ # Keep the short no-animation-wakeups measurement away from that deadline.
+ phase = time.time() % 60
+ if phase >= 58:
+ time.sleep(60.25 - phase)
+ elif phase < .25:
+ time.sleep(.25 - phase)
+ ipc.wait_for_frame()
+ ipc.reset_perf()
+ time.sleep(.4)
+ idle = ipc.get_perf()
+ assert idle["output_commits"] == 0, (reason, idle)
+
+
+def check_move_fade(ipc, shot, moving, box):
+ # Pausing with the button held must freeze the folds as well as releasing
+ # it. A fixed fading sheet can only lose contrast against the background.
+ ipc.action("set_anim_time", {"ms": 1600})
+ ipc.wait_for_frame()
+ held = shot("move-held")
+ ipc.action("set_anim_time", {"ms": 1700})
+ ipc.wait_for_frame()
+ held_later = shot("move-held-later")
+ ipc.pointer_button(272, False)
+ ipc.action("set_anim_time", {"ms": 1800})
+ ipc.wait_for_frame()
+ lingering = shot("lingering")
+ ipc.action("set_anim_time", {"ms": 1850})
+ ipc.wait_for_frame()
+ lingering_later = shot("lingering-later")
+ ipc.action("set_anim_time", {"ms": 2000})
+ ipc.wait_for_frame()
+ cleared = shot("move-cleared-quickly")
+ ipc.action("set_anim_time", {"ms": 5000})
+ ipc.wait_for_frame()
+ faded_frame = shot("faded", None)
+ faded = faded_frame.crop(box)
+ assert ImageChops.difference(moving, faded).getbbox(), "enabled ribbon drew no pixels"
+ assert ImageChops.difference(held, faded).getbbox(), "paused ribbon vanished instead of fading"
+ assert ImageChops.difference(lingering, faded).getbbox(), "released ribbon vanished instead of fading"
+ assert ImageChops.difference(cleared, faded).getbbox() is None, "stopped ribbon lingered beyond half a second"
+ for earlier, later in ((held, held_later), (lingering, lingering_later)):
+ before = ImageChops.difference(earlier, faded)
+ after = ImageChops.difference(later, faded)
+ gained = ImageChops.subtract(after, before)
+ assert max(peak for _, peak in gained.getextrema()) <= 3, "stationary drag flame changed shape instead of just fading"
+ return faded_frame, faded
+
+
+def check_minimize(ipc, win, shot, tmp, mixed, scale):
+ ipc.action("set_anim_time", {"ms": 11000})
+ ipc.minimize(win["id"])
+ assert ipc.get_windows()[0]["is_minimized"]
+ first = shot("minimize-start", None)
+ ipc.action("set_anim_time", {"ms": 11320})
+ ipc.wait_for_frame()
+ middle = shot("minimize-middle", None)
+ ipc.action("set_anim_time", {"ms": 12000})
+ ipc.wait_for_frame()
+ finished = shot("minimize-finished", None)
+ body = tuple(round(v * scale) for v in (win["x"], win["y"], win["x"] + win["width"], win["y"] + win["height"]))
+ assert ImageChops.difference(first.crop(body), finished.crop(body)).getbbox(), "minimize lost its snapshot"
+ assert ImageChops.difference(middle.crop(body), finished.crop(body)).getbbox(), "minimize ribbon vanished before completion"
+ assert ImageChops.difference(first, middle).getbbox(), "window did not deform"
+ # No stale pixels or live effect frames after the real-time clock resumes.
+ ipc.action("set_anim_time", {"ms": None})
+ time.sleep(1)
+ assert_idle(ipc, "minimize did not return to idle")
+ ipc.restore(win["id"])
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ time.sleep(.3)
+ # Restore while the snapshot is alive: no second ghost of the window.
+ ipc.action("set_anim_time", {"ms": 13000})
+ ipc.minimize(win["id"])
+ ipc.action("set_anim_time", {"ms": 13300})
+ ipc.wait_for_frame()
+ ipc.restore(win["id"])
+ ipc.action("set_anim_time", {"ms": 15000})
+ ipc.wait_for_frame()
+ restored = shot("minimize-restored", None)
+ (tmp / "rediwm-config.toml").write_text(BASE + mixed)
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ assert ImageChops.difference(restored, shot("minimize-restored-clean", None)).getbbox() is None
+ # Independent opt-out and reduced motion both suppress the snapshot.
+ for index, suffix in enumerate(('[effects.window_minimize]\nenabled = false\n',
+ '[animations]\nreduced_motion = "on"\n')):
+ (tmp / "rediwm-config.toml").write_text(ON + mixed + suffix)
+ ipc.reload_config()
+ ipc.action("set_anim_time", {"ms": 16000})
+ ipc.minimize(win["id"])
+ ipc.action("set_anim_time", {"ms": 16320})
+ ipc.wait_for_frame()
+ disabled = shot(f"minimize-suppressed-{index}", None)
+ ipc.action("set_anim_time", {"ms": 18000})
+ ipc.wait_for_frame()
+ assert ImageChops.difference(disabled, shot(f"minimize-suppressed-later-{index}", None)).getbbox() is None
+ ipc.restore(win["id"])
+ # Minimizing can own the shader by itself, and reload erases a live sheet.
+ (tmp / "rediwm-config.toml").write_text(BASE + mixed + '[effects.window_minimize]\nenabled = true\n')
+ ipc.reload_config()
+ ipc.action("set_anim_time", {"ms": 20000})
+ ipc.minimize(win["id"])
+ ipc.action("set_anim_time", {"ms": 20320})
+ ipc.wait_for_frame()
+ separate = shot("minimize-only", None)
+ (tmp / "rediwm-config.toml").write_text(BASE + mixed)
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ erased = shot("minimize-cancelled", None)
+ assert ImageChops.difference(separate.crop(body), erased.crop(body)).getbbox()
+ ipc.action("set_anim_time", {"ms": 22000})
+ ipc.wait_for_frame()
+ assert ImageChops.difference(erased, shot("minimize-cancelled-later", None)).getbbox() is None
+ ipc.restore(win["id"])
+ (tmp / "rediwm-config.toml").write_text(ON + mixed)
+ ipc.reload_config()
+ ipc.action("set_anim_time", {"ms": None})
+
+
+def check_resize(ipc, win, shot, move, tmp, mixed, scale, process):
+ ipc.action("move_window_to", {"id": win["id"], "x": 120, "y": 80})
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ config = BASE + mixed + '[effects.window_resize]\nenabled = true\n'
+ for index, (edge, dx, dy) in enumerate((("se", 50, 30), ("nw", -35, -25), ("e", 60, 0), ("se", -45, -35))):
+ (tmp / "rediwm-config.toml").write_text(config)
+ ipc.reload_config()
+ win = ipc.get_windows()[0]
+ target_w = win["width"] + (-dx if edge == "nw" else dx)
+ target_h = win["height"] + (-dy if edge == "nw" else dy)
+ x = win["x"] - 2 if edge == "nw" else win["x"] + win["width"] + 2
+ y = win["y"] - 2 if edge == "nw" else win["y"] + (win["height"] + 2 if edge == "se" else win["height"] / 2)
+ start = 30000 + index * 6000
+ ipc.action("set_anim_time", {"ms": start})
+ move(x, y)
+ ipc.pointer_button(272, True)
+ assert ipc.get_input_state()["cursor_mode"] == "resize", edge
+ ipc.action("set_anim_time", {"ms": start + 100})
+ move(x + dx, y + dy)
+ ipc.wait_for_frame()
+ assert ipc.get_windows()[0]["width"] == win["width"], "window jumped to the pointer"
+ ipc.action("set_anim_time", {"ms": start + 140})
+ resized = wait_for(lambda: current if abs((current := ipc.get_windows()[0])["width"] - win["width"]) > 2 else None,
+ "lagging resize did not advance")
+ assert min(win["width"], target_w) + 2 < resized["width"] < max(win["width"], target_w) - 2, "resize has no visible lag"
+ ipc.wait_for_frame()
+ active = shot(f"resize-{edge}-{index}", None)
+ # Release during the lag must keep easing, including fixed top/left edges.
+ ipc.pointer_button(272, False)
+ assert abs(ipc.get_windows()[0]["width"] - target_w) > 2
+ ipc.action("set_anim_time", {"ms": start + 2000})
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ final = ipc.get_windows()[0]
+ assert final["width"] == target_w
+ assert final["height"] == target_h
+ if edge == "nw":
+ assert final["x"] + final["width"] == win["x"] + win["width"]
+ assert final["y"] + final["height"] == win["y"] + win["height"]
+ (tmp / "rediwm-config.toml").write_text(BASE + mixed)
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ clean = shot(f"resize-{edge}-{index}-clean", None)
+ diff = ImageChops.difference(active, clean)
+ assert diff.getbbox(), (edge, "no elastic resize membrane")
+
+ # Fade while still held, resume on motion, then cancel through window detach.
+ (tmp / "rediwm-config.toml").write_text(config)
+ ipc.reload_config()
+ win = ipc.get_windows()[0]
+ x, y = win["x"] + win["width"] + 2, win["y"] + win["height"] + 2
+ ipc.action("set_anim_time", {"ms": 50000})
+ move(x, y)
+ ipc.pointer_button(272, True)
+ ipc.action("set_anim_time", {"ms": 50100})
+ move(x + 20, y + 15)
+ ipc.wait_for_frame()
+ ipc.action("set_anim_time", {"ms": 54000})
+ ipc.wait_for_frame()
+ held = shot("resize-held-idle", None)
+ ipc.action("set_anim_time", {"ms": None})
+ time.sleep(.8)
+ assert_idle(ipc, "stationary resize kept waking")
+ ipc.action("set_anim_time", {"ms": 54100})
+ move(x + 35, y + 20)
+ ipc.wait_for_frame()
+ ipc.minimize(win["id"])
+ assert ipc.get_input_state()["cursor_mode"] == "passthrough"
+ ipc.pointer_button(272, False)
+ ipc.restore(win["id"])
+ ipc.action("set_anim_time", {"ms": 56000})
+ ipc.wait_for_frame()
+ cancelled = shot("resize-cancelled", None)
+ (tmp / "rediwm-config.toml").write_text(BASE + mixed)
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ assert ImageChops.difference(cancelled, shot("resize-cancelled-clean", None)).getbbox() is None
+ assert held.size == cancelled.size
+ # Releasing a fresh resize fades the sheet and stops output wakeups.
+ (tmp / "rediwm-config.toml").write_text(ON + mixed)
+ ipc.reload_config()
+ win = ipc.get_windows()[0]
+ x, y = win["x"] + win["width"] + 2, win["y"] + win["height"] / 2
+ ipc.action("set_anim_time", {"ms": 57000})
+ move(x, y)
+ ipc.pointer_button(272, True)
+ ipc.action("set_anim_time", {"ms": 57100})
+ move(x + 20, y)
+ ipc.wait_for_frame()
+ ipc.pointer_button(272, False)
+ ipc.action("set_anim_time", {"ms": 57200})
+ ipc.wait_for_frame()
+ release = shot("resize-release", None)
+ ipc.action("set_anim_time", {"ms": 59000})
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ assert ImageChops.difference(release, shot("resize-release-faded", None)).getbbox()
+ assert ipc.get_windows()[0]["width"] == win["width"] + 20
+
+ check_resize_settlement(ipc, move, tmp, mixed, config, process)
+
+
+def check_resize_settlement(ipc, move, tmp, mixed, config, process):
+ # A late pre-release ack must not discard the pending final size/anchor.
+ win = ipc.get_windows()[0]
+ x, y = win["x"] - 2, win["y"] - 2
+ ipc.action("set_anim_time", {"ms": 60000})
+ move(x, y)
+ ipc.pointer_button(272, True)
+ process.send_signal(signal.SIGSTOP)
+ try:
+ ipc.action("set_anim_time", {"ms": 60100})
+ move(x - 25, y - 20)
+ ipc.action("set_anim_time", {"ms": 60150})
+ ipc.wait_for_frame()
+ ipc.pointer_button(272, False)
+ ipc.action("set_anim_time", {"ms": 65000})
+ ipc.wait_for_frame()
+ finally:
+ process.send_signal(signal.SIGCONT)
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ final = ipc.get_windows()[0]
+ assert final["width"] == win["width"] + 25 and final["height"] == win["height"] + 20
+ assert final["x"] + final["width"] == win["x"] + win["width"]
+ assert final["y"] + final["height"] == win["y"] + win["height"]
+ # Reloading during a lag immediately releases the final requested size;
+ # reduced motion starts with ordinary, immediate resize behavior.
+ for index, reduced in enumerate((False, True)):
+ (tmp / "rediwm-config.toml").write_text(config + ('[animations]\nreduced_motion = "on"\n' if reduced else ''))
+ ipc.reload_config()
+ win = ipc.get_windows()[0]
+ x, y = win["x"] + win["width"] + 2, win["y"] + win["height"] / 2
+ stamp = 70000 + index * 4000
+ ipc.action("set_anim_time", {"ms": stamp})
+ move(x, y)
+ ipc.pointer_button(272, True)
+ move(x + 15, y)
+ ipc.wait_for_frame()
+ if not reduced:
+ assert ipc.get_windows()[0]["width"] == win["width"]
+ (tmp / "rediwm-config.toml").write_text(BASE + mixed)
+ ipc.reload_config()
+ wait_for(lambda: ipc.get_windows()[0]["width"] == win["width"] + 15, "resize opt-out retained lag")
+ ipc.pointer_button(272, False)
+ ipc.action("set_anim_time", {"ms": stamp + 1000})
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ (tmp / "rediwm-config.toml").write_text(ON + mixed)
+ ipc.reload_config()
+ ipc.action("set_anim_time", {"ms": None})
+ time.sleep(1)
+ assert_idle(ipc, "resize effect kept waking after release")
+
+
+def check_shell_resize(ipc, move):
+ # Settings applies its size synchronously and has no client ack to finish
+ # settlement. It must use the same lag and preserve the fixed right edge.
+ ipc.open_control_center()
+ win = wait_for(lambda: next((w for w in ipc.get_windows() if w.get("app_id") == "rediwm-settings"), None), "Settings did not map")
+ ipc.action("move_window_to", {"id": win["id"], "x": 40, "y": 20})
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ win = next(w for w in ipc.get_windows() if w["id"] == win["id"])
+ ipc.action("set_anim_time", {"ms": 80000})
+ move(win["x"] - 2, win["y"] + 80)
+ ipc.pointer_button(272, True)
+ assert ipc.get_input_state()["cursor_mode"] == "resize"
+ ipc.action("set_anim_time", {"ms": 80100})
+ move(win["x"] - 17, win["y"] + 80)
+ ipc.wait_for_frame()
+ current = next(w for w in ipc.get_windows() if w["id"] == win["id"])
+ assert current["width"] == win["width"], "shell resize skipped lag"
+ ipc.action("set_anim_time", {"ms": 80140})
+ ipc.wait_for_frame()
+ current = next(w for w in ipc.get_windows() if w["id"] == win["id"])
+ assert win["width"] < current["width"] < win["width"] + 15
+ ipc.pointer_button(272, False)
+ ipc.action("set_anim_time", {"ms": 82000})
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ current = next(w for w in ipc.get_windows() if w["id"] == win["id"])
+ assert current["width"] == win["width"] + 15
+ assert current["x"] + current["width"] == win["x"] + win["width"]
+ ipc.action("close_window", {"id": win["id"]})
+ ipc.action("set_anim_time", {"ms": 84000})
+ wait_for(lambda: all(w["id"] != win["id"] for w in ipc.get_windows()), "Settings did not close")
+ ipc.action("set_anim_time", {"ms": None})
+
+
+def run():
+ scale = float(os.environ.get("REDIWM_TEST_SCALE", "1"))
+ with tempfile.TemporaryDirectory(prefix="rediwm-ribbons-") as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ outputs = os.environ.get("REDIWM_TEST_OUTPUTS", "1")
+ mixed = ('[[outputs]]\nname = "HEADLESS-1"\nscale = 1\n' +
+ '[[outputs]]\nname = "HEADLESS-2"\nscale = 1.5\n') if outputs == "2" else ""
+ process, log = spawn_compositor(tmp, scale="auto" if mixed else str(scale), outputs=outputs,
+ config_content=ON + mixed, binary=os.environ.get("REDIWM_TEST_BINARY"), env_extra={
+ "HOME": str(tmp), "XDG_CONFIG_HOME": str(tmp / "config"),
+ "XDG_DATA_HOME": str(tmp / "data"), "XDG_CACHE_HOME": str(tmp / "cache"),
+ "DBUS_SESSION_BUS_ADDRESS": "", "WLR_RENDERER_ALLOW_SOFTWARE": "1",
+ })
+ client = None
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ # Headless output creation order can put HEADLESS-2 on the
+ # left. Crop using the selected output's actual raster scale.
+ capture_output = min(ipc.get_outputs(), key=lambda out: out["x"])
+ scale = capture_output["scale"]
+
+ def move(x, y):
+ for out in ipc.get_outputs():
+ if out["x"] <= x < out["x"] + out["logical_width"] and out["y"] <= y < out["y"] + out["logical_height"]:
+ return ipc.move_cursor(round(x - out["x"]), round(y - out["y"]), output=out["name"])
+ raise AssertionError(("pointer outside layout", x, y))
+ display = wait_for(lambda: next((p.name for p in tmp.glob("wayland-*")
+ if not p.name.endswith(".lock")), None), "display unavailable")
+ client = subprocess.Popen([str(tmp / "client")], env=dict(os.environ,
+ XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display, REDIWM_TEST_DECORATION="server"),
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ win = wait_for(lambda: next(iter(ipc.get_windows()), None), "window unavailable")
+ ipc.action("move_window_to", {"id": win["id"], "x": 100, "y": 140})
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ time.sleep(.4)
+ ipc.action("set_anim_time", {"ms": 1000})
+ move(180, 160)
+ ipc.action("pointer_button", {"button": 272, "pressed": True})
+ for step in range(1, 25):
+ ipc.action("set_anim_time", {"ms": 1000 + step * 20})
+ move(180 + step * 10, 160)
+ ipc.wait_for_frame()
+ win = ipc.get_windows()[0]
+ assert win["x"] > 300, ("ribbon intercepted the move", win)
+ # Exclude the frame/shadow: only the trail to its left may differ.
+ box = tuple(round(v * scale) for v in (max(0, win["x"] - 420),
+ max(0, win["y"] - 60), win["x"] - 35, win["y"] + win["height"] + 60))
+
+ def shot(name, region=box):
+ path = tmp / f"{name}.png"
+ ipc.screenshot(path=str(path), output=capture_output["name"])
+ if os.environ.get("REDIWM_TEST_ARTIFACT_DIR"):
+ dest = Path(os.environ["REDIWM_TEST_ARTIFACT_DIR"])
+ dest.mkdir(parents=True, exist_ok=True)
+ (dest / f"ribbon-{name}-{scale}.png").write_bytes(path.read_bytes())
+ frame = Image.open(path).convert("RGB")
+ if region is None:
+ # The taskbar clock uses wall time, independently of the
+ # pinned animation clock. Keep minute ticks out of diffs.
+ ImageDraw.Draw(frame).rectangle((frame.width - round(120 * scale),
+ frame.height - round(44 * scale), frame.width, frame.height), fill=(0, 0, 0))
+ return frame.crop(region)
+
+ moving_frame = shot("moving", None)
+ moving = moving_frame.crop(box)
+ faded_frame, faded = check_move_fade(ipc, shot, moving, box)
+ # The middle of the trailing edge carries a faint wash too,
+ # well away from both corner flames and the window's shadow.
+ middle_box = tuple(round(v * scale) for v in (win["x"] - 100,
+ win["y"] + win["height"] * .36, win["x"] - 60,
+ win["y"] + win["height"] * .64))
+ middle = ImageChops.difference(moving_frame.crop(middle_box), faded_frame.crop(middle_box))
+ assert 2 < middle.getextrema()[0][1] < 25, "drag sheet is missing or too bright"
+ # Opposite the trails, away from the titlebar and pointer: the
+ # exterior frame halo must light up here too, then disappear.
+ edge_box = tuple(round(v * scale) for v in (win["x"] + win["width"] + 2,
+ win["y"] + 80, win["x"] + win["width"] + 18, win["y"] + win["height"] - 30))
+ edge = ImageChops.difference(moving_frame.crop(edge_box), faded_frame.crop(edge_box))
+ assert edge.getextrema()[0][1] > 20, "dragged frame has no visible border glow"
+ check_minimize(ipc, win, shot, tmp, mixed, scale)
+ (tmp / "rediwm-config.toml").write_text(BASE + mixed)
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ disabled = shot("disabled")
+ assert ImageChops.difference(faded, disabled).getbbox() is None, "trail left stale pixels"
+ ipc.action("pointer_button", {"button": 272, "pressed": False})
+ ipc.action("set_anim_time", {"ms": None})
+ time.sleep(1)
+ assert_idle(ipc, "disabled effect kept rendering")
+
+ # Re-enable and destroy during a move: no retained window pointers.
+ (tmp / "rediwm-config.toml").write_text(ON + mixed)
+ ipc.reload_config()
+ if mixed:
+ boundary = sorted(ipc.get_outputs(), key=lambda out: out["x"])[1]["x"]
+ ipc.action("move_window_to", {"id": win["id"], "x": boundary - 180, "y": 140})
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ win = ipc.get_windows()[0]
+ ipc.action("set_anim_time", {"ms": 6000})
+ move(win["x"] + 80, win["y"] + 20)
+ ipc.action("pointer_button", {"button": 272, "pressed": True})
+ move(win["x"] + 160, win["y"] + 20)
+ ipc.wait_for_frame()
+ ipc.action("set_anim_time", {"ms": 6300})
+ ipc.wait_for_frame()
+ # Disable while pixels are still live, then verify complete erasure.
+ (tmp / "rediwm-config.toml").write_text(BASE + mixed)
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ live_disabled = shot("live-disabled")
+ ipc.action("set_anim_time", {"ms": 10000})
+ ipc.wait_for_frame()
+ assert ImageChops.difference(live_disabled, shot("live-disabled-later")).getbbox() is None
+ ipc.action("set_anim_time", {"ms": None})
+ (tmp / "rediwm-config.toml").write_text(ON + mixed)
+ ipc.reload_config()
+ ipc.action("pointer_button", {"button": 272, "pressed": False})
+ check_resize(ipc, ipc.get_windows()[0], shot, move, tmp, mixed, scale, client)
+ check_shell_resize(ipc, move)
+ win = ipc.get_windows()[0]
+ move(win["x"] + 80, win["y"] + 20)
+ ipc.action("pointer_button", {"button": 272, "pressed": True})
+ move(win["x"] + 160, win["y"] + 20)
+ ipc.wait_for_frame()
+ stop_process(client)
+ client = None
+ wait_for(lambda: not ipc.get_windows(), "window did not disappear")
+ ipc.action("pointer_button", {"button": 272, "pressed": False})
+ ipc.wait_for_frame()
+ assert process.poll() is None
+ assert ipc.get_perf()["output_failed_commits"] == 0
+ print(f"PASS: movement, minimize and resize ribbons draw, cancel, reload and return to idle at scale {scale}")
+ except Exception:
+ log.flush()
+ print(Path(log.name).read_text()[-6000:])
+ raise
+ finally:
+ if client and client.poll() is None:
+ stop_process(client)
+ stop_process(process)
+ log.close()
+
+
+if __name__ == "__main__":
+ run()