RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Serve org.freedesktop.ScreenSaver idle inhibition
oxydizerdf54781d7785
diff --git a/build/tests.zig b/build/tests.zigindex 131a2d3..efb99e5 100644--- a/build/tests.zig+++ b/build/tests.zig@@ -250,6 +250,10 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {settings_portal_integration.addFileArg(b.path("tests/settings_portal.py"));const settings_portal_step = b.step("test-settings-portal", "Test the dark_mode Settings portal backend on a private bus");settings_portal_step.dependOn(&settings_portal_integration.step);+ const screensaver_integration = b.addSystemCommand(&.{"python3"});+ screensaver_integration.addFileArg(b.path("tests/screensaver_inhibit.py"));+ screensaver_integration.step.dependOn(b.getInstallStep());+ b.step("test-screensaver", "Test org.freedesktop.ScreenSaver idle inhibition on a private bus").dependOn(&screensaver_integration.step);const power_integration = b.addSystemCommand(&.{"python3"});power_integration.addFileArg(b.path("tests/power.py"));diff --git a/src/ipc/handlers_queries.zig b/src/ipc/handlers_queries.zigindex 7c920a9..c61c62e 100644--- a/src/ipc/handlers_queries.zig+++ b/src/ipc/handlers_queries.zig@@ -86,6 +86,15 @@ pub fn getIdleState(server: *Server, allocator: std.mem.Allocator) !protocol.Res.reason = if (tracked.reason.len > 0) try allocator.dupe(u8, tracked.reason) else null,});}+ for (im.bus_inhibitors.items) |inhibitor| {+ try list.append(allocator, .{+ .surface_ptr = 0,+ .app_id = try allocator.dupe(u8, inhibitor.app),+ .title = try allocator.dupe(u8, inhibitor.reason),+ .is_active = true,+ .reason = try std.fmt.allocPrint(allocator, "D-Bus ScreenSaver {s}", .{inhibitor.owner}),+ });+ }const now = im.clock.nowMs();const elapsed = now - im.last_activity_ms;diff --git a/src/notifications/manager.zig b/src/notifications/manager.zigindex a1c638d..e77840c 100644--- a/src/notifications/manager.zig+++ b/src/notifications/manager.zig@@ -96,6 +96,7 @@ pub const Manager = struct {try conn.register(.{ .path = bus_path, .interface = bus_interface, .member = "CloseNotification", .owner = self, .callback = handleCloseNotification });try settings_portal.register(conn, self.server);try @import("../session/file_manager_service.zig").register(conn, self.server);+ try @import("../session/screensaver_service.zig").register(conn, self.server);self.file_chooser = try @import("../session/file_chooser.zig").Manager.create(self.server, conn);_ = try conn.hello(self, onHello);@@ -619,6 +620,7 @@ fn onHello(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connection.Fif (mgr.file_chooser) |chooser| chooser.start();settings_portal.requestName(conn);@import("../session/file_manager_service.zig").requestName(conn);+ @import("../session/screensaver_service.zig").start(conn, mgr.server);settings_portal.startWatching(conn, mgr.server);_ = @import("../tray.zig").Tray.create(mgr.server, conn) catch |err| {log.warn("could not initialize application tray: {}", .{err});diff --git a/src/session/AGENTS.md b/src/session/AGENTS.mdindex 0cca16f..4ba200c 100644--- a/src/session/AGENTS.md+++ b/src/session/AGENTS.md@@ -27,6 +27,14 @@ ext-session-lock) are in the root `AGENTS.md`.a user's config or discover packs in the greeter. Account changes resetthe palette and wallpaper before loading the next snapshot.+* **Idle inhibitors** come from two places: idle-inhibit-v1 surfaces count+ only while visible (re-checked on map, move, minimize, camera and output+ changes); `org.freedesktop.ScreenSaver` (`screensaver_service.zig`, on the+ notifications bus connection, so never in the greeter) counts regardless of+ visibility until UnInhibit or its sender leaves the bus. Chromium makes its+ surface inhibitor only on a window with pointer or keyboard focus and never+ retries, so the bus path is what keeps videos awake.+* `Lock.covered()` releases the lock-before-sleep inhibitor; the builtin lockalso sets `Output.lock_commit_pending`.diff --git a/src/session/idle.zig b/src/session/idle.zigindex 637e947..a7db6fe 100644--- a/src/session/idle.zig+++ b/src/session/idle.zig@@ -66,6 +66,21 @@ pub const SurfaceVisibility = struct {reason: []const u8 = "",};+/// An org.freedesktop.ScreenSaver Inhibit call: no surface, so it counts+/// regardless of visibility (as on GNOME and KDE) until its sender calls+/// UnInhibit or leaves the bus. Strings are owned by the manager.+pub const BusInhibitor = struct {+ cookie: u32,+ /// The caller's unique bus name.+ owner: []u8,+ app: []u8,+ reason: []u8,+};++/// Bounds memory a misbehaving session client can pin.+pub const max_bus_inhibitors = 256;+const max_bus_text = 256;+pub const IdleManager = struct {server: ?*Server = null,config: IdleConfig,@@ -81,6 +96,9 @@ pub const IdleManager = struct {new_inhibitor_listener: wl.Listener(*wlr.IdleInhibitorV1) = .init(handleNewInhibitor),inhibitors: wl.list.Head(TrackedInhibitor, .link) = undefined,+ bus_inhibitors: std.ArrayList(BusInhibitor) = .empty,+ last_bus_cookie: u32 = 0,+is_inhibited: bool = false,effective_inhibitor_count: usize = 0,@@ -146,6 +164,7 @@ pub const IdleManager = struct {tracked.link.remove();gpa.destroy(tracked);}+ self.clearBusInhibitors(gpa);gpa.destroy(self);}@@ -440,6 +459,7 @@ pub const IdleManager = struct {tracked.reason = vis.reason;if (vis.visible) effective_count += 1;}+ effective_count += self.bus_inhibitors.items.len;self.effective_inhibitor_count = effective_count;const now_inhibited = (effective_count > 0);@@ -469,7 +489,77 @@ pub const IdleManager = struct {var count: usize = 0;var it = self.inhibitors.iterator(.forward);while (it.next()) |_| count += 1;- return count;+ return count + self.bus_inhibitors.items.len;+ }++ /// Adds a D-Bus inhibitor for `owner` and returns its nonzero cookie.+ pub fn addBusInhibitor(self: *IdleManager, allocator: std.mem.Allocator, owner: []const u8, app: []const u8, reason: []const u8) !u32 {+ if (self.bus_inhibitors.items.len >= max_bus_inhibitors) return error.TooManyInhibitors;+ var cookie = self.last_bus_cookie;+ while (true) {+ cookie +%= 1;+ if (cookie != 0 and self.findBusInhibitor(cookie) == null) break;+ }+ const owned_owner = try allocator.dupe(u8, owner);+ errdefer allocator.free(owned_owner);+ const owned_app = try allocator.dupe(u8, clip(app));+ errdefer allocator.free(owned_app);+ const owned_reason = try allocator.dupe(u8, clip(reason));+ errdefer allocator.free(owned_reason);+ try self.bus_inhibitors.append(allocator, .{ .cookie = cookie, .owner = owned_owner, .app = owned_app, .reason = owned_reason });+ self.last_bus_cookie = cookie;+ log.info("idle inhibited over D-Bus by {s} ({s}): {s}", .{ owned_app, owned_owner, owned_reason });+ self.recheckInhibitors();+ return cookie;+ }++ /// Removes `cookie` if `owner` holds it; another client's cookie is left alone.+ pub fn removeBusInhibitor(self: *IdleManager, allocator: std.mem.Allocator, owner: []const u8, cookie: u32) bool {+ const index = self.findBusInhibitor(cookie) orelse return false;+ if (!std.mem.eql(u8, self.bus_inhibitors.items[index].owner, owner)) return false;+ freeBusInhibitor(allocator, self.bus_inhibitors.orderedRemove(index));+ self.recheckInhibitors();+ return true;+ }++ /// Drops every inhibitor of a client that left the bus.+ pub fn dropBusOwner(self: *IdleManager, allocator: std.mem.Allocator, owner: []const u8) void {+ var removed = false;+ var i: usize = 0;+ while (i < self.bus_inhibitors.items.len) {+ if (std.mem.eql(u8, self.bus_inhibitors.items[i].owner, owner)) {+ freeBusInhibitor(allocator, self.bus_inhibitors.orderedRemove(i));+ removed = true;+ } else i += 1;+ }+ if (removed) self.recheckInhibitors();+ }++ pub fn clearBusInhibitors(self: *IdleManager, allocator: std.mem.Allocator) void {+ for (self.bus_inhibitors.items) |inhibitor| freeBusInhibitor(allocator, inhibitor);+ self.bus_inhibitors.deinit(allocator);+ self.bus_inhibitors = .empty;+ }++ fn findBusInhibitor(self: *const IdleManager, cookie: u32) ?usize {+ for (self.bus_inhibitors.items, 0..) |inhibitor, i| {+ if (inhibitor.cookie == cookie) return i;+ }+ return null;+ }++ fn freeBusInhibitor(allocator: std.mem.Allocator, inhibitor: BusInhibitor) void {+ allocator.free(inhibitor.owner);+ allocator.free(inhibitor.app);+ allocator.free(inhibitor.reason);+ }++ /// Bus strings are valid UTF-8; cut on a character boundary.+ fn clip(text: []const u8) []const u8 {+ if (text.len <= max_bus_text) return text;+ var end: usize = max_bus_text;+ while (end > 0 and (text[end] & 0xC0) == 0x80) end -= 1;+ return text[0..end];}pub fn applyConfig(self: *IdleManager, new_cfg: IdleConfig) void {diff --git a/src/session/idle_tests.zig b/src/session/idle_tests.zigindex 24058ab..2d83bc6 100644--- a/src/session/idle_tests.zig+++ b/src/session/idle_tests.zig@@ -190,3 +190,60 @@ test "an unsuccessful sleep attempt does not cancel later display blanking" {try std.testing.expect(!im.isBlanked());try std.testing.expect(!im.suspend_requested);}++test "D-Bus inhibitors hold off blanking until uninhibited or their client leaves" {+ const allocator = std.testing.allocator;+ var im: IdleManager = .{+ .config = .{ .enabled = true, .blank_after_seconds = 10 },+ .clock = .{ .mock_now_ms = 1000 },+ .last_activity_ms = 1000,+ };+ im.inhibitors.init();+ defer im.clearBusInhibitors(allocator);++ const video = try im.addBusInhibitor(allocator, ":1.7", "brave", "Playing video");+ const audio = try im.addBusInhibitor(allocator, ":1.7", "brave", "Playing audio");+ const portal = try im.addBusInhibitor(allocator, ":1.9", "firefox", "Inhibit");+ try std.testing.expect(video != 0 and video != audio and audio != portal);+ try std.testing.expect(im.is_inhibited);+ try std.testing.expectEqual(@as(usize, 3), im.inhibitorCount());++ im.clock.mock_now_ms = 60_000;+ im.tickTimer();+ try std.testing.expectEqual(State.active, im.state);++ // Another client cannot release a cookie it does not hold.+ try std.testing.expect(!im.removeBusInhibitor(allocator, ":1.9", video));+ try std.testing.expect(im.removeBusInhibitor(allocator, ":1.7", video));+ try std.testing.expect(!im.removeBusInhibitor(allocator, ":1.7", video));+ im.dropBusOwner(allocator, ":1.7");+ try std.testing.expect(im.is_inhibited);+ try std.testing.expect(im.removeBusInhibitor(allocator, ":1.9", portal));+ try std.testing.expect(!im.is_inhibited);++ // Releasing the last inhibitor starts a full timeout from now.+ try std.testing.expectEqual(@as(i64, 60_000), im.last_activity_ms);+ im.clock.mock_now_ms = 65_000;+ im.tickTimer();+ try std.testing.expectEqual(State.active, im.state);+ im.clock.mock_now_ms = 70_000;+ im.tickTimer();+ try std.testing.expectEqual(State.blanked, im.state);+}++test "D-Bus inhibitors are bounded and clip long text" {+ const allocator = std.testing.allocator;+ var im: IdleManager = .{ .config = .{ .enabled = true, .blank_after_seconds = 10 } };+ im.inhibitors.init();+ defer im.clearBusInhibitors(allocator);++ const long: [400]u8 = @bitCast(@as([200][2]u8, @splat("é".*)));+ _ = try im.addBusInhibitor(allocator, ":1.3", &long, &long);+ const kept = im.bus_inhibitors.items[0].app;+ try std.testing.expect(kept.len <= 256 and std.unicode.utf8ValidateSlice(kept));+ for (1..idle.max_bus_inhibitors) |_| _ = try im.addBusInhibitor(allocator, ":1.3", "a", "b");+ try std.testing.expectError(error.TooManyInhibitors, im.addBusInhibitor(allocator, ":1.3", "a", "b"));+ im.dropBusOwner(allocator, ":1.3");+ try std.testing.expectEqual(@as(usize, 0), im.inhibitorCount());+ try std.testing.expect(!im.is_inhibited);+}diff --git a/src/session/screensaver_service.zig b/src/session/screensaver_service.zignew file mode 100644index 0000000..c0961ab--- /dev/null+++ b/src/session/screensaver_service.zig@@ -0,0 +1,126 @@+//! org.freedesktop.ScreenSaver: idle inhibition over the session bus.+//!+//! Chromium creates its idle-inhibit-v1 inhibitor only on a window that has+//! pointer or keyboard focus when playback starts, and never retries, so a+//! video that resumes while the pointer is elsewhere would let the display+//! blank. It also calls this interface when the name has an owner, as do SDL,+//! mpv, VLC and xdg-desktop-portal-gtk's Inhibit backend (Firefox, Flatpak).+//! Inhibitors live in the IdleManager and go when their sender leaves the bus.+const std = @import("std");+const dbus = @import("dbus");+const wire = dbus.wire;+const Server = @import("../Server.zig");+const IdleManager = @import("idle.zig").IdleManager;+const gpa = @import("../main.zig").gpa;+const log = std.log.scoped(.screensaver_service);++const bus_name = "org.freedesktop.ScreenSaver";+/// KDE serves both; older clients use the short path.+const object_paths = .{ "/org/freedesktop/ScreenSaver", "/ScreenSaver" };+const dbus_name = "org.freedesktop.DBus";+const dbus_path = "/org/freedesktop/DBus";++pub fn register(conn: *dbus.Connection, server: *Server) !void {+ const im = server.idle orelse return;+ inline for (object_paths) |path| {+ inline for (.{+ .{ "Inhibit", inhibit },+ .{ "UnInhibit", uninhibit },+ .{ "SimulateUserActivity", simulateUserActivity },+ .{ "GetActive", getActive },+ }) |method| {+ try conn.register(.{ .path = path, .interface = bus_name, .member = method[0], .owner = im, .callback = method[1] });+ }+ }+}++/// After Hello: follow departing clients, then take the name.+pub fn start(conn: *dbus.Connection, server: *Server) void {+ const im = server.idle orelse return;+ _ = conn.subscribe(.{ .sender = dbus_name, .path = dbus_path, .interface = dbus_name, .member = "NameOwnerChanged", .owner = im, .callback = nameOwnerChanged }, null, null) catch |err| {+ // Without departures an inhibitor could outlive its client.+ log.warn("cannot follow bus clients ({}); not serving {s}", .{ err, bus_name });+ return;+ };+ // A restarted compositor takes the name over from the instance it replaces.+ _ = conn.requestName(bus_name, 7, null, onRequestName) catch |err| {+ log.warn("RequestName {s} failed: {}", .{ bus_name, err });+ };+}++fn onRequestName(_: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {+ const msg = result catch |err| {+ log.warn("RequestName {s} reply failed: {}", .{ bus_name, err });+ return;+ };+ if (msg.headers.error_name) |name| {+ log.warn("RequestName {s} refused: {s}", .{ bus_name, name });+ return;+ }+ var body = msg.body;+ const code = body.uint32() catch return;+ // 1 primary owner, 4 already owner; 3 = exists (DO_NOT_QUEUE).+ if (code != 1 and code != 4) log.info("{s} is served by another process", .{bus_name});+}++fn manager(owner: ?*anyopaque) *IdleManager {+ return @ptrCast(@alignCast(owner.?));+}++fn inhibit(owner: ?*anyopaque, conn: *dbus.Connection, msg: wire.Message) !void {+ const im = manager(owner);+ if (!std.mem.eql(u8, msg.headers.signature, "ss")) return error.InvalidArguments;+ const sender = msg.headers.sender orelse return error.InvalidArguments;+ var reader = msg.body;+ const app = try reader.string();+ const reason = try reader.string();+ try reader.done();+ const cookie = im.addBusInhibitor(gpa, sender, app, reason) catch |err| switch (err) {+ error.TooManyInhibitors => {+ try conn.replyError(msg, "org.freedesktop.DBus.Error.LimitsExceeded", "Too many inhibitors");+ return;+ },+ else => return err,+ };+ var body: wire.Writer = .{ .allocator = gpa };+ defer body.deinit();+ try body.uint32(cookie);+ try conn.reply(msg, "u", &body);+}++fn uninhibit(owner: ?*anyopaque, conn: *dbus.Connection, msg: wire.Message) !void {+ const im = manager(owner);+ if (!std.mem.eql(u8, msg.headers.signature, "u")) return error.InvalidArguments;+ const sender = msg.headers.sender orelse return error.InvalidArguments;+ var reader = msg.body;+ const cookie = try reader.uint32();+ try reader.done();+ // Unknown or foreign cookies succeed silently, as on KDE.+ _ = im.removeBusInhibitor(gpa, sender, cookie);+ const empty: wire.Writer = .{ .allocator = gpa };+ try conn.reply(msg, "", &empty);+}++fn simulateUserActivity(owner: ?*anyopaque, conn: *dbus.Connection, msg: wire.Message) !void {+ if (msg.headers.signature.len != 0) return error.InvalidArguments;+ manager(owner).notifyActivity(.virtual);+ const empty: wire.Writer = .{ .allocator = gpa };+ try conn.reply(msg, "", &empty);+}++fn getActive(owner: ?*anyopaque, conn: *dbus.Connection, msg: wire.Message) !void {+ if (msg.headers.signature.len != 0) return error.InvalidArguments;+ var body: wire.Writer = .{ .allocator = gpa };+ defer body.deinit();+ try body.boolean(manager(owner).isBlanked());+ try conn.reply(msg, "b", &body);+}++fn nameOwnerChanged(owner: ?*anyopaque, _: *dbus.Connection, msg: wire.Message) anyerror!void {+ if (!std.mem.eql(u8, msg.headers.signature, "sss")) return;+ var reader = msg.body;+ const name = try reader.string();+ _ = try reader.string();+ const new_owner = try reader.string();+ if (new_owner.len == 0 and name.len > 0 and name[0] == ':') manager(owner).dropBusOwner(gpa, name);+}diff --git a/tests/screensaver_inhibit.py b/tests/screensaver_inhibit.pynew file mode 100644index 0000000..ffdcd7c--- /dev/null+++ b/tests/screensaver_inhibit.py@@ -0,0 +1,95 @@+#!/usr/bin/env python3+"""org.freedesktop.ScreenSaver idle inhibition on a private session bus."""+import os+from pathlib import Path+import subprocess+import sys+import tempfile++if __name__ == '__main__' and '--private' not in sys.argv:+ raise SystemExit(subprocess.call(['dbus-run-session', '--', sys.executable, __file__, '--private']))++from gi.repository import Gio, GLib+from desktop_zoom import wait_for+from ipc_client import IPCClient, spawn_compositor, stop_process++BUS = 'org.freedesktop.DBus'+NAME = 'org.freedesktop.ScreenSaver'+PATH = '/org/freedesktop/ScreenSaver'+++def connect():+ return Gio.DBusConnection.new_for_address_sync(os.environ['DBUS_SESSION_BUS_ADDRESS'],+ Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None)+++def call(conn, dest, path, iface, member, signature=None, args=None):+ params = GLib.Variant(signature, args) if signature else None+ reply = conn.call_sync(dest, path, iface, member, params, None, Gio.DBusCallFlags.NONE, 3000, None)+ return reply.unpack() if reply else ()+++def saver(conn, member, signature=None, args=None, path=PATH):+ return call(conn, NAME, path, NAME, member, signature, args)+++def main():+ conn = connect()+ with tempfile.TemporaryDirectory(prefix='rediwm-screensaver-') as directory:+ tmp = Path(directory)+ proc, log = spawn_compositor(tmp, config_content=(+ '[compositor]\nxwayland = false\n\n[idle]\nenabled = true\nblank_after_seconds = 10\nsuspend_after_seconds = 0\n'),+ env_extra={'REDIWM_FORCE_DBUS': '1', 'XDG_CACHE_HOME': str(tmp / 'cache'),+ 'XDG_STATE_HOME': str(tmp / 'state'), 'GIO_USE_VFS': 'local'})+ try:+ with IPCClient(tmp) as ipc:+ def state():+ return ipc.request(query='get_idle_state')++ wait_for(lambda: call(conn, BUS, '/org/freedesktop/DBus', BUS, 'NameHasOwner', '(s)', (NAME,))[0],+ 'compositor did not take org.freedesktop.ScreenSaver')+ assert saver(conn, 'GetActive') == (False,)++ # An inhibitor holds off blanking however long the session idles.+ (cookie,) = saver(conn, 'Inhibit', '(ss)', ('brave', 'Playing video'))+ assert cookie != 0+ s = state()+ assert s['is_inhibited'] is True and s['inhibitor_count'] == 1, s+ entry = s['inhibitors'][0]+ assert entry['app_id'] == 'brave' and entry['title'] == 'Playing video' and entry['is_active'], entry+ ipc.action('advance_idle_time', {'seconds': 60})+ assert state()['state'] == 'active'++ # Another client cannot release it; the holder can.+ other = connect()+ saver(other, 'UnInhibit', '(u)', (cookie,))+ assert state()['is_inhibited'] is True+ saver(conn, 'UnInhibit', '(u)', (cookie,))+ s = state()+ assert s['is_inhibited'] is False and s['inhibitor_count'] == 0, s++ # Released: the full timeout runs again, then the displays blank.+ ipc.action('advance_idle_time', {'seconds': 5})+ assert state()['state'] == 'active'+ ipc.action('advance_idle_time', {'seconds': 6})+ wait_for(lambda: state()['state'] == 'blanked', 'displays did not blank after release')+ assert saver(conn, 'GetActive') == (True,)+ saver(conn, 'SimulateUserActivity')+ wait_for(lambda: state()['state'] == 'active', 'SimulateUserActivity did not wake')++ # The short path works too, and a client that leaves the bus loses its inhibitors.+ saver(other, 'Inhibit', '(ss)', ('mpv', 'video'), path='/ScreenSaver')+ saver(other, 'Inhibit', '(ss)', ('mpv', 'audio'))+ assert state()['inhibitor_count'] == 2+ other.close_sync(None)+ wait_for(lambda: state()['inhibitor_count'] == 0, 'departed client kept its inhibitors')+ assert state()['is_inhibited'] is False+ finally:+ stop_process(proc)+ log.close()+ conn.close_sync(None)+ print('PASS: ScreenSaver Inhibit/UnInhibit, owner checks, blank after release, GetActive, departure cleanup')+++if __name__ == '__main__':+ main()