Skip to content

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

layout autosave: restore from a startup snapshot, once per window

oxydizer6f3b21b8ef90
diff --git a/docs/plans/scene-graph-baseline.md b/docs/plans/scene-graph-baseline.md
index ddf56d8..312f5b2 100644
--- a/docs/plans/scene-graph-baseline.md
+++ b/docs/plans/scene-graph-baseline.md
@@ -233,14 +233,19 @@ The same binary, twice in a row on the same session of the machine (scenario-lev
level, between two runs, so `--compare` can use a tolerance of 0-2 levels
locally. Other GPUs or Mesa versions will differ (GLES2 at a fractional
scale can move one level with render history).
-10. **The layout autosave can move a window back within 37 s of start.**
- `session/layout_autosave.zig` writes the layout every 10 s and restores
- from that same file at about 2, 7, 17 and 37 s after start. A window moved,
- resized or made fullscreen shortly before a restore tick is put back at its
- previous saved position; a fullscreen window kept its fullscreen size but
- was moved to its old origin (seen: `client_box` jumped from (0,0) to
- (700,40) while `fullscreen` stayed true). Not investigated further; the
- harness avoids it by giving the compositor an uncreatable state directory.
+10. **The layout autosave could move a window back within 37 s of start.**
+ `session/layout_autosave.zig` wrote the layout every 10 s and restored from
+ that same file at about 2, 7, 17 and 37 s after start, so a window moved,
+ resized or made fullscreen shortly before a restore tick was put back where
+ it had been up to 10 s earlier; a fullscreen window kept its fullscreen
+ size but was moved to its old origin (`client_box` jumped from (0,0) to
+ (700,40) while `fullscreen` stayed true). **Fixed**: the attempts now share
+ one snapshot taken at startup (`FlatRestore`), each saved row is claimed by
+ one window, each window is placed once, fullscreen and maximized windows
+ are left alone, and the periodic save waits while rows are unclaimed.
+ `layout_autosave.py` moves the window between the 10 s save and the 17 s
+ attempt (it snapped back before). The harness still gives the compositor an
+ uncreatable state directory so runs never read or write real state.
## What `wlr_scene_output` does today
diff --git a/src/config/workspace_layout.zig b/src/config/workspace_layout.zig
index fc6e8a8..f3d7adb 100644
--- a/src/config/workspace_layout.zig
+++ b/src/config/workspace_layout.zig
@@ -163,6 +163,96 @@ pub fn parseLegacy(a: std.mem.Allocator, bytes: []const u8) ![]const LegacyWindo
return list.toOwnedSlice(a);
}
+/// The saved rows of a flat (non-workspace) layout, each claimable by one window.
+/// Reads both the legacy `[[window]]` TOML and the canvas rows of a workspace
+/// snapshot. No compositor dependencies: the startup restore keeps one of these
+/// for its whole run (session/layout_autosave.zig).
+pub const Flat = struct {
+ rows: []Row,
+
+ pub const Row = struct {
+ app_id: []const u8,
+ x: i32,
+ y: i32,
+ /// Only canvas rows of a workspace snapshot carry a size; legacy rows
+ /// restore position and zoom.
+ geometry: ?Geometry = null,
+ zoom_index: usize = 0,
+ claimed: bool = false,
+ };
+
+ /// `a` owns the result (it is meant to be an arena).
+ pub fn fromBytes(a: std.mem.Allocator, bytes: []const u8) !Flat {
+ var rows: std.ArrayList(Row) = .empty;
+ if (std.mem.startsWith(u8, std.mem.trimStart(u8, bytes, " \t\r\n"), "{")) {
+ var saved = try parse(a, bytes);
+ defer saved.deinit();
+ for (saved.value.windows) |window| {
+ const canvas = window.canvas orelse continue;
+ try rows.append(a, .{
+ .app_id = try a.dupe(u8, window.app_id),
+ .x = canvas.geometry.x,
+ .y = canvas.geometry.y,
+ .geometry = canvas.geometry,
+ .zoom_index = canvas.zoom_index,
+ });
+ }
+ } else for (try parseLegacy(a, bytes)) |window| {
+ try rows.append(a, .{ .app_id = window.app_id, .x = window.x, .y = window.y, .zoom_index = window.zoom_index });
+ }
+ return .{ .rows = try rows.toOwnedSlice(a) };
+ }
+
+ /// The first unclaimed row for `app_id`, marked claimed: separate windows of
+ /// one app get their rows in saved order, and never the same row twice.
+ pub fn claim(self: *Flat, app_id: []const u8) ?*const Row {
+ for (self.rows) |*row| {
+ if (row.claimed or !std.mem.eql(u8, row.app_id, app_id)) continue;
+ row.claimed = true;
+ return row;
+ }
+ return null;
+ }
+
+ /// Whether some row has not found its window yet.
+ pub fn pending(self: *const Flat) bool {
+ for (self.rows) |row| if (!row.claimed) return true;
+ return false;
+ }
+};
+
+test "flat layout rows are claimed once, in order, per app" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ var flat = try Flat.fromBytes(arena.allocator(), "[[window]]\napp_id = \"a\"\nx = 1\n[[window]]\napp_id = \"b\"\nx = 2\n[[window]]\napp_id = \"a\"\nx = 3\n");
+ try std.testing.expectEqual(@as(usize, 3), flat.rows.len);
+ try std.testing.expect(flat.pending());
+ try std.testing.expectEqual(@as(i32, 1), flat.claim("a").?.x);
+ try std.testing.expectEqual(@as(i32, 3), flat.claim("a").?.x);
+ try std.testing.expect(flat.claim("a") == null);
+ try std.testing.expect(flat.claim("missing") == null);
+ try std.testing.expect(flat.pending());
+ try std.testing.expectEqual(@as(i32, 2), flat.claim("b").?.x);
+ try std.testing.expect(!flat.pending());
+}
+
+test "flat layout reads canvas rows of a workspace snapshot and skips the rest" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const json =
+ \\{"workspaces":[{"id":1,"nodes":[]}],"windows":[
+ \\{"app_id":"x","workspace":1,"order":1,"geometry":{"x":0,"y":0,"width":9,"height":9},
+ \\ "canvas":{"geometry":{"x":10,"y":20,"width":300,"height":200},"zoom_index":2}},
+ \\{"app_id":"y","workspace":1,"order":2,"geometry":{"x":0,"y":0,"width":9,"height":9}}]}
+ ;
+ var flat = try Flat.fromBytes(arena.allocator(), json);
+ try std.testing.expectEqual(@as(usize, 1), flat.rows.len);
+ const row = flat.claim("x").?;
+ try std.testing.expectEqual(@as(i32, 20), row.y);
+ try std.testing.expectEqual(@as(i32, 300), row.geometry.?.width);
+ try std.testing.expectEqual(@as(usize, 2), row.zoom_index);
+}
+
test "legacy layout keeps separate occurrences of an app" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
diff --git a/src/config_runtime/actions.zig b/src/config_runtime/actions.zig
index 5c2fab5..5c63b8d 100644
--- a/src/config_runtime/actions.zig
+++ b/src/config_runtime/actions.zig
@@ -425,6 +425,61 @@ pub fn restoreLayoutFromPath(server: *Server, path: []const u8) !void {
}
}
}
+/// The startup restore of a flat (non-workspace) desktop, kept across the
+/// several delayed attempts (session/layout_autosave.zig).
+///
+/// It works from one snapshot of the saved layout, not from the file: the
+/// periodic autosave rewrites the file with the *current* layout every 10 s,
+/// so re-reading it at each attempt put windows back wherever they had been up
+/// to 10 s earlier (and moved a full-screen window to its old origin). Each
+/// saved row is claimed by at most one window and each window is placed at most
+/// once, so a window the user has moved since is never touched again.
+pub const FlatRestore = struct {
+ arena: std.heap.ArenaAllocator,
+ layout: @import("config").workspace_layout.Flat,
+ placed: std.AutoHashMapUnmanaged(u64, void) = .empty,
+
+ pub fn load(server: *Server, path: []const u8) !FlatRestore {
+ const bytes = try IoDir.cwd().readFileAlloc(server.io, path, gpa, .limited(1 << 20));
+ defer gpa.free(bytes);
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ errdefer arena.deinit();
+ const layout = try @import("config").workspace_layout.Flat.fromBytes(arena.allocator(), bytes);
+ return .{ .arena = arena, .layout = layout };
+ }
+
+ pub fn deinit(self: *FlatRestore) void {
+ self.arena.deinit();
+ }
+
+ /// Whether some saved row has not found its window yet.
+ pub fn pending(self: *const FlatRestore) bool {
+ return self.layout.pending();
+ }
+
+ pub fn apply(self: *FlatRestore, server: *Server) void {
+ const applying = server.undo.applying;
+ server.undo.applying = true;
+ defer server.undo.applying = applying;
+ var it = server.world.toplevels.iterator(.reverse);
+ while (it.next()) |top| {
+ if (top.tab_hidden or self.placed.contains(top.id)) continue;
+ const row = self.layout.claim(top.appId()) orelse continue;
+ self.placed.put(self.arena.allocator(), top.id, {}) catch continue;
+ // Claimed even when skipped, so a later attempt cannot move it. A
+ // window that is already full-screen or maximized keeps its own geometry.
+ if (top.isFullscreen() or top.isMaximized()) continue;
+ if (row.geometry) |g| {
+ top.restoreGeometryNow(.{ .x = g.x, .y = g.y, .width = g.width, .height = g.height });
+ top.setZoomOrigin(@min(row.zoom_index, camera_mod.zoom_levels.len - 1));
+ } else {
+ top.setPosition(row.x, row.y);
+ top.setZoom(@min(row.zoom_index, camera_mod.zoom_levels.len - 1), server.input.cursor.x, server.input.cursor.y);
+ }
+ }
+ }
+};
+
fn matchSavedWindow(server: *Server, app_id: []const u8, used: *std.AutoHashMapUnmanaged(u64, void), a: std.mem.Allocator) ?*Toplevel {
var it = server.world.toplevels.iterator(.reverse);
while (it.next()) |top| {
diff --git a/src/session/layout_autosave.zig b/src/session/layout_autosave.zig
index 0f1ce07..571dce4 100644
--- a/src/session/layout_autosave.zig
+++ b/src/session/layout_autosave.zig
@@ -6,17 +6,21 @@
//!
//! This has nothing to do with detecting whether the previous shutdown was
//! clean or a crash — matching is by app_id against whatever toplevels
-//! happen to exist (see `applySavedWindow`), so reapplying a saved position
-//! to a window that's already there, or finding nothing to match at all, is
-//! harmless. That's true on every normal startup, not just after a crash;
-//! this is what makes `data/rediwm-session`'s crash-restart loop useful
-//! instead of just reopening every app in the top-left corner.
+//! happen to exist, and finding nothing to match at all is harmless. That's
+//! true on every normal startup, not just after a crash; this is what makes
+//! `data/rediwm-session`'s crash-restart loop useful instead of just
+//! reopening every app in the top-left corner.
//!
//! Restoring is retried on a few delays rather than once, because a slow
//! launching app (a browser, say) may not have mapped its first window yet
-//! at the first attempt — restore_layout has the same "only affects windows
-//! open right now" limitation when a human presses it, so this doesn't
-//! introduce a new one.
+//! at the first attempt. The attempts share one snapshot of the file taken at
+//! startup (`FlatRestore`): each saved row is claimed by one window and each
+//! window is placed once. Re-reading the file at every attempt was wrong, since
+//! the periodic save below rewrites it with the current layout, so a later
+//! attempt moved windows back to where they were up to 10 s before. For the
+//! same reason the periodic save waits while rows are still unclaimed: it
+//! would overwrite the previous session's layout with a partial one before
+//! slow apps have mapped, and a crash then would lose their positions.
const std = @import("std");
const wl = @import("wayland").server.wl;
@@ -35,6 +39,9 @@ pub const Autosave = struct {
save_timer: ?*wl.EventSource = null,
restore_timer: ?*wl.EventSource = null,
restore_attempt: usize = 0,
+ /// The startup snapshot of a flat (non-workspace) layout, claimed window by
+ /// window across the restore attempts; null once they are over.
+ flat_restore: ?actions.FlatRestore = null,
/// Hash of the layout this process last wrote; unchanged ticks skip I/O.
last_saved_hash: ?u64 = null,
workspace_hash: ?u64 = null,
@@ -55,6 +62,13 @@ pub const Autosave = struct {
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
+ // Taken before the first periodic save (10 s) can replace the file.
+ if (autosavePath(arena.allocator(), server)) |path| {
+ self.flat_restore = actions.FlatRestore.load(server, path) catch |err| blk: {
+ if (err != error.FileNotFound) log.warn("autosave snapshot: {s}", .{@errorName(err)});
+ break :blk null;
+ };
+ }
if (workspacePath(arena.allocator(), server)) |path| {
self.workspace_restore = @import("../workspace_persistence.zig").Restore.load(server, path) catch |err| blk: {
if (err != error.FileNotFound) log.warn("workspace restore: {s}", .{@errorName(err)});
@@ -68,6 +82,7 @@ pub const Autosave = struct {
if (self.save_timer) |t| t.remove();
if (self.restore_timer) |t| t.remove();
if (self.workspace_restore) |*restore| restore.deinit();
+ if (self.flat_restore) |*restore| restore.deinit();
gpa.destroy(self);
}
@@ -117,8 +132,10 @@ pub const Autosave = struct {
fn onSaveTimer(self: *Autosave) c_int {
// Keep the original snapshot on disk while slow startup clients can
// still claim it. Explicit saves and shutdown retain saveNow semantics.
- const pending = self.server.world.workspaces.active and
- (if (self.workspace_restore) |*restore| restore.pending() else false);
+ const pending = if (self.server.world.workspaces.active)
+ (if (self.workspace_restore) |*restore| restore.pending() else false)
+ else
+ (if (self.flat_restore) |*restore| restore.pending() else false);
if (!pending) self.saveNow();
self.save_timer.?.timerUpdate(autosave_interval_ms) catch {};
return 0;
@@ -126,17 +143,15 @@ pub const Autosave = struct {
fn onRestoreTimer(self: *Autosave) c_int {
if (self.workspace_restore) |*restore| restore.prepare(self.server);
- var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
- defer arena.deinit();
- if (autosavePath(arena.allocator(), self.server)) |path| {
- if (!self.server.world.workspaces.active) actions.restoreLayoutFromPath(self.server, path) catch |err| {
- if (err != error.FileNotFound) log.warn("autosave restore: {}", .{err});
- };
- }
+ if (!self.server.world.workspaces.active) if (self.flat_restore) |*restore| restore.apply(self.server);
self.restore_attempt += 1;
if (self.restore_attempt < restore_delays_ms.len) {
self.restore_timer.?.timerUpdate(restore_delays_ms[self.restore_attempt]) catch {};
- } else self.cancelWorkspaceRestore();
+ } else {
+ self.cancelWorkspaceRestore();
+ if (self.flat_restore) |*restore| restore.deinit();
+ self.flat_restore = null;
+ }
return 0;
}
};
diff --git a/tests/layout_autosave.py b/tests/layout_autosave.py
index 29b803b..1e2f8e9 100644
--- a/tests/layout_autosave.py
+++ b/tests/layout_autosave.py
@@ -21,6 +21,8 @@ from xwayland import wayland_display_name
APP_ID = "rediwm.zoom-fixture"
SAVED_X = 321
SAVED_Y = 87
+MOVED_X = 500
+MOVED_Y = 260
def wait_for(check, message, timeout=15):
@@ -90,6 +92,7 @@ def run():
print("layout autosave: periodic save records the moved window's position")
# Phase 2: fresh compositor and fixture, same state dir: restore on startup.
+ started = time.monotonic()
process, log = spawn_compositor(run2, env_extra={"XDG_STATE_HOME": str(state_dir)})
client = client_log = None
try:
@@ -103,11 +106,21 @@ def run():
"startup restore did not reposition the fixture",
timeout=25,
)
+ print("layout autosave: startup restore repositions a matching window from the autosave")
+ # The restore is retried at about 2, 7, 17 and 37 s. The periodic save rewrites the
+ # file every 10 s, so a retry that re-read it moved the window back to where it
+ # was up to 10 s earlier. Move it after the 10 s save and before the 17 s retry:
+ # it has to stay where it was put.
+ time.sleep(max(0.0, started + 13.5 - time.monotonic()))
+ ipc.action('move_window_to', {"id": win["id"], "x": MOVED_X, "y": MOVED_Y})
+ time.sleep(max(0.0, started + 23.0 - time.monotonic()))
+ win = fixture_window(ipc)
+ assert (win["x"], win["y"]) == (MOVED_X, MOVED_Y), ("later restore attempt moved the window back", win["x"], win["y"])
finally:
stop_client(client, client_log)
stop_process(process)
log.close()
- print("layout autosave: startup restore repositions a matching window from the autosave")
+ print("layout autosave: a window moved after the restore is not put back by later attempts")
if __name__ == "__main__":