Skip to content

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

fixes

oxydizer21283f3c7295
diff --git a/TESTING.md b/TESTING.md
index da72cbc..f66d028 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -112,6 +112,12 @@ disabling without closing clients, close-confirmation dialogs, fullscreen and
failed launches. It supports `REDIWM_TEST_SCALE`,
`REDIWM_TEST_RENDERER`, and `REDIWM_TABS_PREVIEW`.
+`appearance_settings.py --app-colors-only` exercises the GTK/Qt apply buttons,
+configuration preservation and backups, failure reporting, and the persisted
+launch environment. When development packages are available it also compiles
+small GTK3, GTK4, libadwaita, Qt5 and Qt6 clients to check the actual loaded
+colors. All configuration, clients and displays stay in temporary directories.
+
`kde_decorations.py` covers KDE decoration startup ordering, mode changes,
window rules, fullscreen/remapping, lifetime and titlebar controls. To also
check the installed Ghostty in a private D-Bus session, run
@@ -171,6 +177,12 @@ never uses the host `DISPLAY`), `xwayland_fractional.py`,
`xwayland_hardening.py` (extreme/invalid client size hints and recovery; needs
Xwayland and libxcb).
+`xwayland.py` checks actual GTK click delivery on negative-origin outputs and
+after panning beyond the physical display in either direction, including 1.5x
+X11 rendering and clicking an already-open menu after another pan. X11 root
+coordinates follow the camera viewport; scene and native Wayland coordinates
+remain in world space.
+
**File dialogs**: `zig build test-file-chooser` (private D-Bus; OpenFile,
SaveFile, SaveFiles, filters, multiple selection, breadcrumbs, overwrite
confirmation, cancellation and Settings portal preferences). The chooser can
diff --git a/docs/wiki/Theme.md b/docs/wiki/Theme.md
index a819caf..4b9f06e 100644
--- a/docs/wiki/Theme.md
+++ b/docs/wiki/Theme.md
@@ -23,6 +23,40 @@ defaults, not the main theme's. The section's presence selects the taskbar
theme (an empty one is the built-in colours); without it the taskbar follows
`[theme]`. Sizes, gaps and radii always come from `[theme]`.
+## GTK and Qt app colors
+
+In **Settings → Appearance**, **Apply GTK colors** and **Apply Qt colors**
+sit below the Theme and Taskbar theme selectors. They export the current
+main theme's app backgrounds, toolbar, sidebar, text and shell accent.
+The taskbar override does not affect app colors. Exports are snapshots:
+apply again after selecting or editing a theme, then restart the apps.
+
+GTK colors are written to `gtk-3.0/rediwm-colors.css` and
+`gtk-4.0/rediwm-colors.css` under `$XDG_CONFIG_HOME` (otherwise `~/.config`).
+A marked import is added to each `gtk.css`, preserving existing rules and
+their precedence. GTK3 includes common widget color overrides; GTK4 also
+gets the CSS variables used by recent libadwaita. No theme package is patched
+and the dark-mode preference is never briefly flipped to force a refresh.
+
+Qt colors require **qt5ct** for Qt 5 apps and **qt6ct** for Qt 6 apps. The
+installed toolkit configurations select native `colors/rediwm.conf` palettes
+and the palette-aware Fusion style. Other preferences are preserved.
+RediWM launches receive the selected platform theme and style immediately;
+sign in again to update the environment for apps activated by D-Bus or
+launched elsewhere. This opt-in is recorded in `rediwm/app-colors.conf`.
+Bundled Qt runtimes, sandboxed apps, and apps with their own styles may need
+their own configuration.
+
+The first existing user configuration is backed up beside its original as
+`<filename>.rediwm-backup`; later applications keep that first backup.
+Managed symlinks are left alone and reported in Settings. To undo GTK colors,
+remove the marked RediWM import blocks from both `gtk.css` files (or restore
+their backups). To undo Qt colors, restore the qt5ct/qt6ct configuration
+backups (or delete configurations created by the export if no backup exists),
+remove `rediwm/app-colors.conf`, and sign in again.
+
+## Color tokens
+
Colors accept `"#rrggbb"`, `"#rrggbbaa"`, or `"rgba(r,g,b,a)"` with RGB
channels from 0 to 255 and alpha from 0 to 1. Numbers must be finite and
nonnegative. Sizes are logical pixels. The tables describe appearance tokens;
diff --git a/src/Server.zig b/src/Server.zig
index 7ecb32e..cb398ee 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -231,6 +231,7 @@ app_scopes: ?*@import("session/app_scope.zig").Scopes = null,
network: ?*@import("network/manager.zig").Manager = null,
bluetooth: ?*@import("bluetooth.zig").Manager = null,
services: ?*services_mod.Manager = null,
+qt_app_colors: bool = false,
pending_launches: std.ArrayList(*@import("start_menu/launch.zig").Pending) = .empty,
layout_autosave: ?*layout_autosave_mod.Autosave = null,
session: ?*wlr.Session = null,
@@ -428,6 +429,18 @@ pub fn init(server: *Server, scale: ?f32, icon_theme_cfg: icon_theme.Config, io:
.greeter_mode = greeter,
};
+ if (!greeter) {
+ const app_theme = @import("config").app_theme;
+ const a = @import("main.zig").gpa;
+ if (app_theme.configHome(a, environ)) |home| {
+ defer a.free(home);
+ server.qt_app_colors = app_theme.qtEnabled(a, io, home) catch |err| blk: {
+ log.warn("could not load app colors preference: {}", .{err});
+ break :blk false;
+ };
+ } else |_| {}
+ }
+
if (!greeter) @import("config_runtime/region.zig").applyTimezone(@import("main.zig").gpa, loaded.region.timezone, environ.getPosix("TZ")) catch |err| {
log.warn("could not apply personal timezone: {}", .{err});
};
@@ -682,6 +695,7 @@ pub fn applyChildEnvWithToken(server: *Server, map: *child_env.Map, token: ?[]co
try map.put("PATH", path);
try child_env.apply(map, .{
+ .qt_app_colors = !server.greeter_mode and server.qt_app_colors,
.region = server.config.region,
.input_method = server.config.input_method.env,
.wayland_display = server.wl_server_socket_name,
diff --git a/src/World.zig b/src/World.zig
index 075485e..00b1023 100644
--- a/src/World.zig
+++ b/src/World.zig
@@ -465,6 +465,7 @@ pub fn deinit(world: *World) void {
Projection.destroy(world.projection);
}
pub fn syncPresentation(world: *World) void {
+ if (world.server.xwayland) |xwayland| xwayland.syncGeometry();
const now = anim.nowMs();
var it = world.toplevels.iterator(.forward);
while (it.next()) |toplevel| {
diff --git a/src/Xwayland.zig b/src/Xwayland.zig
index 0709e57..bb1fab1 100644
--- a/src/Xwayland.zig
+++ b/src/Xwayland.zig
@@ -9,6 +9,7 @@ const wlr = @import("wlroots");
const Server = @import("Server.zig");
const XwaylandOutputManager = @import("xwayland_output.zig").XwaylandOutputManager;
const gpa = @import("main.zig").gpa;
+const xscale = @import("xwayland_scale.zig");
const Xwayland = @This();
const log = std.log.scoped(.xwayland);
@@ -20,6 +21,9 @@ scale: f64 = 1,
native_scaling: bool = false,
scale_locked: bool = false,
ready: bool = false,
+root_x: i32 = 0,
+root_y: i32 = 0,
+root_zoom: f64 = 1,
stop_source: ?*wl.EventSource = null,
on_ready: wl.Listener(void) = .init(handleReady),
@@ -54,13 +58,10 @@ pub fn create(server: *Server) ?*Xwayland {
return null;
};
const scale = server.computeXwaylandScale();
- var output_manager: ?*XwaylandOutputManager = null;
- if (native_scaling) {
- output_manager = XwaylandOutputManager.create(server) catch |err| blk: {
- log.err("failed to create xwayland xdg-output manager: {}", .{err});
- break :blk null;
- };
- }
+ const output_manager = XwaylandOutputManager.create(server) catch |err| blk: {
+ log.err("failed to create xwayland xdg-output manager: {}", .{err});
+ break :blk null;
+ };
xwayland.* = .{
.server = server,
.wlr_xwayland = wlr_xwayland,
@@ -97,6 +98,41 @@ pub fn displayName(xwayland: *const Xwayland) []const u8 {
return std.mem.span(xwayland.wlr_xwayland.display_name);
}
+/// X11 pointer events are clipped to its nonnegative root rectangle. Keep
+/// that rectangle over the camera's viewport, while scene geometry stays in
+/// world coordinates. Surface sizes and surface-local input stay unscaled.
+pub fn syncGeometry(self: *Xwayland) void {
+ const world = &self.server.world;
+ const x: i32 = @intFromFloat(@round((world.bounds.origin_x + world.camera.offset_x) * self.scale));
+ const y: i32 = @intFromFloat(@round((world.bounds.origin_y + world.camera.offset_y) * self.scale));
+ const zoom = world.camera.zoom();
+ if (x == self.root_x and y == self.root_y and zoom == self.root_zoom) return;
+ const dx = self.root_x - x;
+ const dy = self.root_y - y;
+ self.root_x = x;
+ self.root_y = y;
+ self.root_zoom = zoom;
+ if (self.output_manager) |mgr| mgr.refreshAll();
+ var it = world.toplevels.iterator(.forward);
+ while (it.next()) |toplevel| {
+ if (toplevel.backend != .xwayland or toplevel.backend_gone) continue;
+ const adapter = &toplevel.backend.xwayland;
+ const surface = adapter.xsurface;
+ const px = xscale.surfacePosition(toplevel.x + toplevel.borderWidth(), self.scale) - x;
+ const py = xscale.surfacePosition(toplevel.y + toplevel.titlebarHeight(), self.scale) - y;
+ if (px != surface.x or py != surface.y) {
+ surface.configure(@import("xwayland_surface.zig").clampPos(px), @import("xwayland_surface.zig").clampPos(py), surface.width, surface.height);
+ }
+ }
+ if (dx != 0 or dy != 0) {
+ var nodes = world.tree.children.iterator(.forward);
+ while (nodes.next()) |node| {
+ const data = @import("scene_data.zig").SceneData.fromNode(node) orelse continue;
+ if (data.role == .xwayland_unmanaged) data.role.xwayland_unmanaged.rebase(dx, dy);
+ }
+ }
+}
+
/// Stop the compositor-owned wrapper through wlroots' supported teardown
/// path. This is useful for logout/administrative cleanup and deterministic
/// lifecycle testing, and cannot affect an X server belonging to the host.
@@ -308,7 +344,7 @@ pub fn globalVisible(xwayland: *const Xwayland, client: *const wl.Client, global
if (global == xwayland.wlr_xwayland.shell_v1.global) {
return is_xwayland;
}
- if (xwayland.native_scaling) {
+ if (xwayland.output_manager != null) {
if (xwayland.server.xdg_output_manager) |mgr| {
if (global == mgr.global) {
if (is_xwayland) return false;
diff --git a/src/child_env.zig b/src/child_env.zig
index a91657d..c9057e3 100644
--- a/src/child_env.zig
+++ b/src/child_env.zig
@@ -13,6 +13,7 @@ pub const session_type = "wayland";
pub const InputMethod = @import("config").types.InputMethod;
pub const Spec = struct {
+ qt_app_colors: bool = false,
region: @import("config").loader.RegionConfig = .{},
input_method: InputMethod = .none,
wayland_display: ?[]const u8 = null,
@@ -31,6 +32,11 @@ pub const Spec = struct {
pub fn apply(map: *Map, spec: Spec) !void {
try applyRegion(map, spec.region);
+ if (spec.qt_app_colors) {
+ try map.put("QT_QPA_PLATFORMTHEME", @import("config").app_theme.qt_platform);
+ try map.put("QT_QPA_PLATFORMTHEME_QT6", "qt6ct");
+ try map.put("QT_STYLE_OVERRIDE", "Fusion");
+ }
// Private supervisor authority must never escape to descendant launches.
inline for (.{ "REDIWM_SESSION_FD", "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY" }) |key| _ = map.swapRemove(key);
switch (spec.input_method) {
@@ -218,3 +224,17 @@ test "private session authority and stale activation tokens never reach children
try apply(&map, .{});
inline for (.{ "REDIWM_SESSION_FD", "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY", "XDG_ACTIVATION_TOKEN", "DESKTOP_STARTUP_ID" }) |key| try std.testing.expect(map.get(key) == null);
}
+
+test "Qt app colors override inherited theming only after explicit opt in" {
+ var map = Map.init(std.testing.allocator);
+ defer map.deinit();
+ try map.put("QT_QPA_PLATFORMTHEME", "gtk3");
+ try map.put("QT_STYLE_OVERRIDE", "kvantum");
+ try apply(&map, .{});
+ try std.testing.expectEqualStrings("gtk3", map.get("QT_QPA_PLATFORMTHEME").?);
+ try std.testing.expectEqualStrings("kvantum", map.get("QT_STYLE_OVERRIDE").?);
+ try apply(&map, .{ .qt_app_colors = true });
+ try std.testing.expectEqualStrings("qt5ct", map.get("QT_QPA_PLATFORMTHEME").?);
+ try std.testing.expectEqualStrings("qt6ct", map.get("QT_QPA_PLATFORMTHEME_QT6").?);
+ try std.testing.expectEqualStrings("Fusion", map.get("QT_STYLE_OVERRIDE").?);
+}
diff --git a/src/config/app_theme.zig b/src/config/app_theme.zig
new file mode 100644
index 0000000..7b02a67
--- /dev/null
+++ b/src/config/app_theme.zig
@@ -0,0 +1,462 @@
+//! Explicit palette exports. User styles and toolkit preferences are merged;
+//! the first originals are kept beside them as .rediwm-backup files.
+const std = @import("std");
+const theme = @import("ui").theme;
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+
+pub const Toolkit = enum { gtk, qt };
+pub const QtSupport = struct { qt5: bool, qt6: bool };
+pub const qt_platform = "qt5ct"; // qt6ct also advertises this plugin key.
+
+pub fn configHome(a: Allocator, env: std.process.Environ) ![]u8 {
+ if (env.getPosix("XDG_CONFIG_HOME")) |path| if (std.fs.path.isAbsolute(path)) return a.dupe(u8, path);
+ const home = env.getPosix("HOME") orelse return error.NoHome;
+ if (!std.fs.path.isAbsolute(home)) return error.NoHome;
+ return std.fs.path.join(a, &.{ home, ".config" });
+}
+
+pub fn executable(a: Allocator, io: Io, env: std.process.Environ, name: []const u8) !?[]u8 {
+ var dirs = std.mem.splitScalar(u8, env.getPosix("PATH") orelse "/usr/local/bin:/usr/bin:/bin", ':');
+ while (dirs.next()) |dir| {
+ if (!std.fs.path.isAbsolute(dir)) continue;
+ const path = try std.fs.path.join(a, &.{ dir, name });
+ const stat = Io.Dir.cwd().statFile(io, path, .{}) catch {
+ a.free(path);
+ continue;
+ };
+ if (stat.kind == .file and stat.permissions.toMode() & 0o111 != 0) return path;
+ a.free(path);
+ }
+ return null;
+}
+
+pub fn qtEnabled(a: Allocator, io: Io, home: []const u8) !bool {
+ const path = try std.fs.path.join(a, &.{ home, "rediwm/app-colors.conf" });
+ defer a.free(path);
+ const content = try readOptional(a, io, path) orelse return false;
+ defer a.free(content);
+ return std.mem.eql(u8, iniValue(content, "Applications", "qt") orelse "false", "true");
+}
+
+const Color = [3]u8;
+pub const Palette = struct {
+ bg: Color,
+ fg: Color,
+ toolbar: Color,
+ sidebar: Color,
+ item: Color,
+ hover: Color,
+ border: Color,
+ accent: Color,
+ on_accent: Color,
+ danger: Color,
+ dim: Color,
+
+ pub fn fromTheme(t: theme.Theme) Palette {
+ const bg = composite(t.app_bg, .{ 255, 255, 255 });
+ const fg = composite(t.window_fg, bg);
+ const accent = composite(t.shell_accent orelse t.start_menu_selected_marker, bg);
+ return .{
+ .bg = bg,
+ .fg = fg,
+ .toolbar = composite(t.app_toolbar, bg),
+ .sidebar = composite(t.app_sidebar, bg),
+ .item = composite(t.app_item, bg),
+ .hover = composite(t.app_item_hover, bg),
+ .border = composite(t.app_item_border, bg),
+ .accent = accent,
+ .on_accent = if (t.shell_on_accent) |c| composite(c, accent) else contrast(accent),
+ .danger = composite(t.danger, bg),
+ .dim = blend(fg, bg, 0.5),
+ };
+ }
+};
+
+fn composite(c: [4]f32, bg: Color) Color {
+ var out: Color = undefined;
+ const alpha = std.math.clamp(c[3], 0, 1);
+ for (&out, bg, c[0..3]) |*v, base, channel| v.* = @intFromFloat(@round(std.math.clamp(channel, 0, 1) * 255 * alpha + @as(f32, @floatFromInt(base)) * (1 - alpha)));
+ return out;
+}
+
+fn blend(fg: Color, bg: Color, alpha: f32) Color {
+ var result: Color = undefined;
+ for (&result, fg, bg) |*v, f, b| v.* = @intFromFloat(@round(@as(f32, @floatFromInt(f)) * alpha + @as(f32, @floatFromInt(b)) * (1 - alpha)));
+ return result;
+}
+
+fn contrast(c: Color) Color {
+ var luminance: f32 = 0;
+ for (c, [_]f32{ 0.2126, 0.7152, 0.0722 }) |byte, weight| {
+ const v = @as(f32, @floatFromInt(byte)) / 255;
+ luminance += weight * (if (v <= 0.04045) v / 12.92 else std.math.pow(f32, (v + 0.055) / 1.055, 2.4));
+ }
+ return if (luminance > 0.179) .{ 0, 0, 0 } else .{ 255, 255, 255 };
+}
+
+fn hex(c: Color) [7]u8 {
+ const digits = "0123456789abcdef";
+ var result: [7]u8 = undefined;
+ result[0] = '#';
+ for (c, 0..) |v, i| {
+ result[1 + 2 * i] = digits[v >> 4];
+ result[2 + 2 * i] = digits[v & 15];
+ }
+ return result;
+}
+
+fn appendFmt(list: *std.ArrayList(u8), a: Allocator, comptime fmt: []const u8, args: anytype) !void {
+ const text = try std.fmt.allocPrint(a, fmt, args);
+ defer a.free(text);
+ try list.appendSlice(a, text);
+}
+
+pub fn gtkColors(a: Allocator, p: Palette, gtk4: bool) ![]u8 {
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ try out.appendSlice(a, "/* Generated by RediWM. Apply GTK colors again after changing the theme. */\n");
+ const names = [_][]const u8{
+ "window_bg_color", "window_fg_color", "view_bg_color", "view_fg_color",
+ "headerbar_bg_color", "headerbar_fg_color", "headerbar_backdrop_color", "sidebar_bg_color",
+ "sidebar_fg_color", "sidebar_backdrop_color", "secondary_sidebar_bg_color", "secondary_sidebar_fg_color",
+ "card_bg_color", "card_fg_color", "dialog_bg_color", "dialog_fg_color",
+ "popover_bg_color", "popover_fg_color", "accent_bg_color", "accent_fg_color",
+ "accent_color", "borders", "theme_bg_color", "theme_fg_color",
+ "theme_base_color", "theme_text_color", "theme_selected_bg_color", "theme_selected_fg_color",
+ "theme_unfocused_bg_color", "theme_unfocused_fg_color", "theme_unfocused_base_color", "theme_unfocused_text_color",
+ "theme_unfocused_selected_bg_color", "theme_unfocused_selected_fg_color", "insensitive_fg_color",
+ };
+ const colors = [_]Color{
+ p.bg, p.fg, p.bg, p.fg, p.toolbar, p.fg, p.toolbar,
+ p.sidebar, p.fg, p.sidebar, p.sidebar, p.fg, p.item, p.fg,
+ p.bg, p.fg, p.toolbar, p.fg, p.accent, p.on_accent, p.accent,
+ p.border, p.bg, p.fg, p.bg, p.fg, p.accent, p.on_accent,
+ p.bg, p.fg, p.bg, p.fg, p.accent, p.on_accent, p.dim,
+ };
+ for (names, colors) |name, color| try appendFmt(&out, a, "@define-color {s} {s};\n", .{ name, hex(color) });
+ try appendFmt(&out, a, "@define-color destructive_bg_color {s};\n@define-color destructive_fg_color {s};\n", .{ hex(p.danger), hex(contrast(p.danger)) });
+ try appendFmt(&out, a, "@define-color button_hover_color {s};\n", .{hex(p.hover)});
+ if (gtk4) {
+ try out.appendSlice(a, ":root {\n");
+ for (names[0..21], colors[0..21]) |name, color| {
+ const variable = try a.dupe(u8, name);
+ defer a.free(variable);
+ std.mem.replaceScalar(u8, variable, '_', '-');
+ try appendFmt(&out, a, " --{s}: {s};\n", .{ variable, hex(color) });
+ }
+ try appendFmt(&out, a, " --destructive-bg-color: {s};\n --destructive-fg-color: {s};\n}}\n", .{ hex(p.danger), hex(contrast(p.danger)) });
+ }
+ // GTK3's built-in Adwaita uses literal colors. Named colors alone cannot
+ // recolor it; override common surfaces without replacing widget geometry.
+ try out.appendSlice(a,
+ \\.background { color: @window_fg_color; background-color: @window_bg_color; }
+ \\headerbar, headerbar:backdrop { color: @headerbar_fg_color; background-color: @headerbar_bg_color; background-image: none; }
+ \\.sidebar, .sidebar:backdrop { color: @sidebar_fg_color; background-color: @sidebar_bg_color; }
+ \\.view, .view:backdrop, textview text, textview text:backdrop, treeview, treeview:backdrop { color: @view_fg_color; background-color: @view_bg_color; }
+ \\entry, entry:backdrop, spinbutton:not(.vertical) { color: @view_fg_color; background-color: @view_bg_color; border-color: @borders; }
+ \\button, button:backdrop { color: @window_fg_color; background-color: @card_bg_color; background-image: none; border-color: @borders; }
+ \\button:hover { background-color: @button_hover_color; }
+ \\button.suggested-action, button.suggested-action:backdrop, selection, :selected { color: @accent_fg_color; background-color: @accent_bg_color; }
+ \\button.destructive-action { color: @destructive_fg_color; background-color: @destructive_bg_color; }
+ \\menu, .menu, popover > contents { color: @popover_fg_color; background-color: @popover_bg_color; }
+ \\*:disabled { color: @insensitive_fg_color; }
+ \\
+ );
+ return out.toOwnedSlice(a);
+}
+
+pub fn qtColors(a: Allocator, p: Palette) ![]u8 {
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ try out.appendSlice(a, "[ColorScheme]\n");
+ // QPalette::ColorRole order, including NoRole, PlaceholderText and Qt6's
+ // Accent. Extra roles are ignored by Qt5 and older Qt6.
+ const active = [_]Color{ p.fg, p.item, blend(p.item, .{ 255, 255, 255 }, 0.7), p.hover, p.border, p.border, p.fg, p.fg, p.fg, p.bg, p.bg, p.border, p.accent, p.on_accent, p.accent, p.accent, p.sidebar, p.bg, p.toolbar, p.fg, p.dim, p.accent };
+ for ([_][]const u8{ "active_colors", "inactive_colors", "disabled_colors" }, 0..) |name, group| {
+ try appendFmt(&out, a, "{s}=", .{name});
+ for (active, 0..) |color, role| {
+ const dimmed = group == 2 and switch (role) {
+ 0, 6, 7, 8, 13, 14, 15, 19, 20 => true,
+ else => false,
+ };
+ try appendFmt(&out, a, "{s}{s}", .{ if (role == 0) "" else ", ", hex(if (dimmed) blend(color, p.bg, 0.5) else color) });
+ }
+ try out.append(a, '\n');
+ }
+ return out.toOwnedSlice(a);
+}
+
+pub fn iniValue(content: []const u8, section: []const u8, key: []const u8) ?[]const u8 {
+ var lines = std.mem.splitScalar(u8, content, '\n');
+ var inside = false;
+ var result: ?[]const u8 = null;
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0 or line[0] == '#' or line[0] == ';') continue;
+ if (line[0] == '[') {
+ inside = std.mem.eql(u8, std.mem.trim(u8, line, "[]"), section);
+ continue;
+ }
+ if (!inside) continue;
+ const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;
+ if (std.mem.eql(u8, std.mem.trim(u8, line[0..eq], " \t"), key)) result = std.mem.trim(u8, line[eq + 1 ..], " \t\r");
+ }
+ return result;
+}
+
+pub fn patchIni(a: Allocator, content: []const u8, section: []const u8, key: []const u8, value: []const u8) ![]u8 {
+ if (std.mem.indexOfAny(u8, value, "\n\r\x00") != null) return error.InvalidValue;
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ var inside = false;
+ var inserted = false;
+ var lines = std.mem.splitScalar(u8, content, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (std.mem.startsWith(u8, line, "[")) {
+ inside = std.mem.eql(u8, std.mem.trim(u8, line, "[]"), section);
+ try appendFmt(&out, a, "{s}\n", .{raw});
+ if (inside and !inserted) {
+ try appendFmt(&out, a, "{s}={s}\n", .{ key, value });
+ inserted = true;
+ }
+ continue;
+ }
+ if (inside) if (std.mem.indexOfScalar(u8, line, '=')) |eq| {
+ if (std.mem.eql(u8, std.mem.trim(u8, line[0..eq], " \t"), key)) continue;
+ };
+ if (raw.len == 0 and lines.index == null) break;
+ try appendFmt(&out, a, "{s}\n", .{raw});
+ }
+ if (!inserted) try appendFmt(&out, a, "[{s}]\n{s}={s}\n", .{ section, key, value });
+ return out.toOwnedSlice(a);
+}
+
+const css_begin = "/* BEGIN REDIWM APP COLORS */";
+const css_end = "/* END REDIWM APP COLORS */";
+pub fn patchCss(a: Allocator, content: []const u8) ![]u8 {
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ var rest = content;
+ while (std.mem.indexOf(u8, rest, css_begin)) |begin| {
+ try out.appendSlice(a, rest[0..begin]);
+ const end = std.mem.indexOf(u8, rest[begin + css_begin.len ..], css_end) orelse return error.InvalidManagedCss;
+ rest = rest[begin + css_begin.len + end + css_end.len ..];
+ if (std.mem.startsWith(u8, rest, "\n")) rest = rest[1..];
+ }
+ if (std.mem.indexOf(u8, rest, css_end) != null) return error.InvalidManagedCss;
+ try out.appendSlice(a, rest);
+ if (out.items.len > 0 and out.items[out.items.len - 1] != '\n') try out.append(a, '\n');
+ // Imports precede user rules, so their own CSS keeps its precedence.
+ const result = try std.fmt.allocPrint(a, css_begin ++ "\n@import url(\"rediwm-colors.css\");\n" ++ css_end ++ "\n{s}", .{out.items});
+ out.deinit(a);
+ return result;
+}
+
+fn readOptional(a: Allocator, io: Io, path: []const u8) !?[]u8 {
+ const stat = Io.Dir.cwd().statFile(io, path, .{ .follow_symlinks = false }) catch |err| switch (err) {
+ error.FileNotFound => return null,
+ else => return err,
+ };
+ if (stat.kind == .sym_link) return error.ManagedSymlink;
+ if (stat.kind != .file) return error.InvalidFile;
+ return try Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 20));
+}
+
+const Change = struct { path: []const u8, data: []const u8, original: ?[]const u8, temp: []const u8, permissions: Io.File.Permissions };
+const Transaction = struct {
+ a: Allocator,
+ io: Io,
+ changes: std.ArrayList(Change) = .empty,
+
+ fn add(self: *Transaction, path: []const u8, data: []const u8, backup: bool) !void {
+ var parent = std.fs.path.dirname(path);
+ while (parent) |dir| : (parent = std.fs.path.dirname(dir)) {
+ if (dir.len <= 1) break;
+ const stat = Io.Dir.cwd().statFile(self.io, dir, .{ .follow_symlinks = false }) catch |err| switch (err) {
+ error.FileNotFound => continue,
+ else => return err,
+ };
+ if (stat.kind == .sym_link) return error.ManagedSymlink;
+ }
+ const original = try readOptional(self.a, self.io, path);
+ if (original) |old| {
+ if (std.mem.eql(u8, old, data)) return;
+ if (backup) {
+ const saved = try std.fmt.allocPrint(self.a, "{s}.rediwm-backup", .{path});
+ if (try readOptional(self.a, self.io, saved) == null) try self.add(saved, old, false);
+ }
+ }
+ const permissions = if (original != null) (try Io.Dir.cwd().statFile(self.io, path, .{})).permissions else Io.File.Permissions.fromMode(0o600);
+ try self.changes.append(self.a, .{ .path = path, .data = data, .original = original, .temp = try std.fmt.allocPrint(self.a, "{s}.rediwm-tmp", .{path}), .permissions = permissions });
+ }
+
+ fn commit(self: *Transaction) !void {
+ var staged: usize = 0;
+ defer for (self.changes.items[0..staged]) |change| Io.Dir.cwd().deleteFile(self.io, change.temp) catch {};
+ // Stage every file before publishing any; failure on a later target
+ // must not leave GTK3 updated while GTK4 still has the old palette.
+ for (self.changes.items) |change| {
+ try Io.Dir.cwd().createDirPath(self.io, std.fs.path.dirname(change.path).?);
+ const file = try Io.Dir.cwd().createFile(self.io, change.temp, .{ .exclusive = true, .permissions = change.permissions });
+ staged += 1;
+ defer file.close(self.io);
+ try file.writeStreamingAll(self.io, change.data);
+ try file.sync(self.io);
+ }
+ var published: usize = 0;
+ errdefer {
+ var rollback_failed = false;
+ for (self.changes.items[0..published]) |change| {
+ if (change.original) |original| {
+ const file = Io.Dir.cwd().createFile(self.io, change.temp, .{ .exclusive = true, .permissions = change.permissions }) catch {
+ rollback_failed = true;
+ continue;
+ };
+ defer file.close(self.io);
+ file.writeStreamingAll(self.io, original) catch {
+ rollback_failed = true;
+ continue;
+ };
+ Io.Dir.rename(.cwd(), change.temp, .cwd(), change.path, self.io) catch {
+ rollback_failed = true;
+ };
+ } else Io.Dir.cwd().deleteFile(self.io, change.path) catch {
+ rollback_failed = true;
+ };
+ }
+ if (rollback_failed) std.log.err("app colors rollback failed; restore the .rediwm-backup files", .{});
+ }
+ for (self.changes.items) |change| {
+ try Io.Dir.rename(.cwd(), change.temp, .cwd(), change.path, self.io);
+ published += 1;
+ }
+ }
+};
+
+pub fn apply(a: Allocator, io: Io, home: []const u8, toolkit: Toolkit, p: Palette, support: QtSupport) !void {
+ var arena: std.heap.ArenaAllocator = .init(a);
+ defer arena.deinit();
+ const alloc = arena.allocator();
+ var tx = Transaction{ .a = alloc, .io = io };
+ switch (toolkit) {
+ .gtk => for ([_][]const u8{ "gtk-3.0", "gtk-4.0" }, 0..) |version, i| {
+ const css = try std.fs.path.join(alloc, &.{ home, version, "gtk.css" });
+ const colors = try std.fs.path.join(alloc, &.{ home, version, "rediwm-colors.css" });
+ try tx.add(colors, try gtkColors(alloc, p, i == 1), false);
+ try tx.add(css, try patchCss(alloc, try readOptional(alloc, io, css) orelse ""), true);
+ },
+ .qt => {
+ if (!support.qt5 and !support.qt6) return error.QtToolsMissing;
+ const colors = try qtColors(alloc, p);
+ for ([_][]const u8{ "qt5ct", "qt6ct" }, [_]bool{ support.qt5, support.qt6 }) |version, installed| {
+ if (!installed) continue;
+ const scheme = try std.fs.path.join(alloc, &.{ home, version, "colors/rediwm.conf" });
+ const config = try std.fmt.allocPrint(alloc, "{s}/{s}/{s}.conf", .{ home, version, version });
+ var content: []const u8 = try readOptional(alloc, io, config) orelse "";
+ content = try patchIni(alloc, content, "Appearance", "custom_palette", "true");
+ content = try patchIni(alloc, content, "Appearance", "color_scheme_path", try quotedPath(alloc, scheme));
+ content = try patchIni(alloc, content, "Appearance", "style", "Fusion");
+ try tx.add(scheme, colors, false);
+ try tx.add(config, content, true);
+ }
+ const state = try std.fs.path.join(alloc, &.{ home, "rediwm/app-colors.conf" });
+ try tx.add(state, try patchIni(alloc, try readOptional(alloc, io, state) orelse "", "Applications", "qt", "true"), true);
+ },
+ }
+ try tx.commit();
+}
+
+fn quotedPath(a: Allocator, path: []const u8) ![]u8 {
+ if (std.mem.indexOfAny(u8, path, "\n\r\x00") != null) return error.InvalidValue;
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ try out.append(a, '"');
+ for (path) |c| {
+ if (c == '\\' or c == '"') try out.append(a, '\\');
+ try out.append(a, c);
+ }
+ try out.append(a, '"');
+ return out.toOwnedSlice(a);
+}
+
+test "app palettes composite straight alpha and choose readable accent text" {
+ var t = theme.Theme{};
+ t.app_bg = .{ 0, 0, 0, 1 };
+ t.app_toolbar = .{ 1, 0, 0, 0.5 };
+ t.shell_accent = .{ 1, 1, 1, 1 };
+ var p = Palette.fromTheme(t);
+ try std.testing.expectEqual(Color{ 128, 0, 0 }, p.toolbar);
+ try std.testing.expectEqual(Color{ 0, 0, 0 }, p.on_accent);
+ t.shell_accent = .{ 0, 0, 0, 1 };
+ p = Palette.fromTheme(t);
+ try std.testing.expectEqual(Color{ 255, 255, 255 }, p.on_accent);
+}
+
+test "app colors edits are idempotent and scoped to their INI section" {
+ const a = std.testing.allocator;
+ const original = "# keep\n[Other]\ncustom_palette=false\n[Appearance]\nstyle=Old\ncustom_palette=false\n[Fonts]\ngeneral=Example\n";
+ const first = try patchIni(a, original, "Appearance", "custom_palette", "true");
+ defer a.free(first);
+ const second = try patchIni(a, first, "Appearance", "custom_palette", "true");
+ defer a.free(second);
+ try std.testing.expectEqualStrings(first, second);
+ try std.testing.expectEqualStrings("false", iniValue(second, "Other", "custom_palette").?);
+ try std.testing.expectEqualStrings("Example", iniValue(second, "Fonts", "general").?);
+ const css = try patchCss(a, "/* user */\nbutton { color: red; }\n");
+ defer a.free(css);
+ const again = try patchCss(a, css);
+ defer a.free(again);
+ try std.testing.expectEqualStrings(css, again);
+ try std.testing.expect(std.mem.endsWith(u8, again, "button { color: red; }\n"));
+ try std.testing.expectError(error.InvalidManagedCss, patchCss(a, css_begin));
+}
+
+test "app colors publishes both GTK versions and keeps the first backup" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const home = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(home);
+ try tmp.dir.createDirPath(io, "gtk-3.0");
+ try tmp.dir.writeFile(io, .{ .sub_path = "gtk-3.0/gtk.css", .data = "/* user */\n" });
+ const p = Palette.fromTheme(.{});
+ try apply(a, io, home, .gtk, p, .{ .qt5 = false, .qt6 = false });
+ try apply(a, io, home, .gtk, p, .{ .qt5 = false, .qt6 = false });
+ const backup = try tmp.dir.readFileAlloc(io, "gtk-3.0/gtk.css.rediwm-backup", a, .limited(1024));
+ defer a.free(backup);
+ try std.testing.expectEqualStrings("/* user */\n", backup);
+ const gtk4 = try tmp.dir.readFileAlloc(io, "gtk-4.0/rediwm-colors.css", a, .limited(16384));
+ defer a.free(gtk4);
+ try std.testing.expect(std.mem.indexOf(u8, gtk4, "--window-bg-color: #181c22;") != null);
+ try tmp.dir.createDirPath(io, "qt6ct/qt6ct.conf");
+ try std.testing.expectError(error.InvalidFile, apply(a, io, home, .qt, p, .{ .qt5 = true, .qt6 = true }));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.access(io, "qt5ct/qt5ct.conf", .{}));
+}
+
+test "app colors rejects symlinks and staging failures before publishing" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const home = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(home);
+ try tmp.dir.createDirPath(io, "gtk-4.0");
+ try tmp.dir.writeFile(io, .{ .sub_path = "user.css", .data = "/* owned elsewhere */\n" });
+ try tmp.dir.symLink(io, "../user.css", "gtk-4.0/gtk.css", .{});
+ const p = Palette.fromTheme(.{});
+ try std.testing.expectError(error.ManagedSymlink, apply(a, io, home, .gtk, p, .{ .qt5 = false, .qt6 = false }));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.access(io, "gtk-3.0/gtk.css", .{}));
+ try tmp.dir.deleteFile(io, "gtk-4.0/gtk.css");
+ try tmp.dir.writeFile(io, .{ .sub_path = "gtk-4.0/gtk.css.rediwm-tmp", .data = "busy" });
+ try std.testing.expectError(error.PathAlreadyExists, apply(a, io, home, .gtk, p, .{ .qt5 = false, .qt6 = false }));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.access(io, "gtk-3.0/gtk.css", .{}));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.access(io, "gtk-3.0/rediwm-colors.css.rediwm-tmp", .{}));
+ try tmp.dir.deleteTree(io, "gtk-4.0");
+ try tmp.dir.createDirPath(io, "external4");
+ try tmp.dir.symLink(io, "external4", "gtk-4.0", .{});
+ try std.testing.expectError(error.ManagedSymlink, apply(a, io, home, .gtk, p, .{ .qt5 = false, .qt6 = false }));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.access(io, "external4/rediwm-colors.css", .{}));
+}
diff --git a/src/config/mod.zig b/src/config/mod.zig
index 4d94e98..0d9f4a4 100644
--- a/src/config/mod.zig
+++ b/src/config/mod.zig
@@ -1,5 +1,6 @@
//! Configuration data, parsing and persistence. Runtime application lives in config_runtime/.
pub const animations = @import("animations.zig");
+pub const app_theme = @import("app_theme.zig");
pub const default = @import("default.zig");
pub const keybinds = @import("keybinds.zig");
pub const keymap = @import("keymap.zig");
diff --git a/src/config_runtime/app_theme.zig b/src/config_runtime/app_theme.zig
new file mode 100644
index 0000000..2074248
--- /dev/null
+++ b/src/config_runtime/app_theme.zig
@@ -0,0 +1,61 @@
+//! Filesystem work runs only on an explicit Settings action. One eventfd
+//! wakes the compositor when the export finishes; there are no idle timers.
+const std = @import("std");
+const config = @import("config").app_theme;
+const c = std.posix.system;
+const a = std.heap.c_allocator;
+
+pub const Job = struct {
+ io: std.Io,
+ env: std.process.Environ,
+ toolkit: config.Toolkit,
+ palette: config.Palette,
+ fd: c_int,
+ thread: ?std.Thread = null,
+ result: anyerror!config.QtSupport = error.NotFinished,
+
+ pub fn create(io: std.Io, env: std.process.Environ, toolkit: config.Toolkit, palette: config.Palette) !*Job {
+ const self = try a.create(Job);
+ errdefer a.destroy(self);
+ const fd = c.eventfd(0, @intCast(std.os.linux.EFD.CLOEXEC | std.os.linux.EFD.NONBLOCK));
+ if (fd < 0) return error.EventFdFailed;
+ self.* = .{ .io = io, .env = env, .toolkit = toolkit, .palette = palette, .fd = fd };
+ return self;
+ }
+
+ pub fn start(self: *Job) !void {
+ self.thread = try std.Thread.spawn(.{}, run, .{self});
+ }
+
+ pub fn join(self: *Job) void {
+ if (self.thread) |thread| thread.join();
+ self.thread = null;
+ }
+
+ pub fn deinit(self: *Job) void {
+ self.join();
+ _ = c.close(self.fd);
+ a.destroy(self);
+ }
+
+ fn run(self: *Job) void {
+ self.result = self.apply();
+ const value: u64 = 1;
+ _ = c.write(self.fd, std.mem.asBytes(&value), @sizeOf(u64));
+ }
+
+ fn apply(self: *Job) !config.QtSupport {
+ const home = try config.configHome(a, self.env);
+ defer a.free(home);
+ var support = config.QtSupport{ .qt5 = false, .qt6 = false };
+ if (self.toolkit == .qt) {
+ const qt5 = try config.executable(a, self.io, self.env, "qt5ct");
+ defer if (qt5) |path| a.free(path);
+ const qt6 = try config.executable(a, self.io, self.env, "qt6ct");
+ defer if (qt6) |path| a.free(path);
+ support = .{ .qt5 = qt5 != null, .qt6 = qt6 != null };
+ }
+ try config.apply(a, self.io, home, self.toolkit, self.palette, support);
+ return support;
+ }
+};
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index 8ad24dc..4ff6b35 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -33,6 +33,8 @@ const start_button = @import("../../taskbar/start_button.zig");
const menu_size = @import("../../start_menu/size.zig");
const wlr = @import("wlroots");
const ipc_animations = @import("../../ipc/animations.zig");
+const app_theme = @import("config").app_theme;
+const AppColorsJob = @import("../../config_runtime/app_theme.zig").Job;
const segmented_width: f32 = 180;
@@ -99,7 +101,7 @@ pub const Section = struct {
cursor_themes: ?[]cursor_theme.Theme = null,
cursor_row_children: [2]Widget = undefined,
family_row_children: [2]Widget = undefined,
- row_storage: [22]Widget = undefined,
+ row_storage: [23]Widget = undefined,
focus_zoom_children: [3]Widget = undefined,
/// Rescanned on every build, so images added meanwhile show up.
wallpapers: []const wallpapers.Entry = &.{},
@@ -115,6 +117,12 @@ pub const Section = struct {
wallpaper_footer_children: [2]Widget = undefined,
theme_row_children: [2]Widget = undefined,
taskbar_theme_row_children: [2]Widget = undefined,
+ app_colors_children: [3]Widget = undefined,
+ app_colors_buttons: [2]Widget = undefined,
+ app_colors_job: ?*AppColorsJob = null,
+ app_colors_source: ?*wl.EventSource = null,
+ app_colors_message: []const u8 = "Uses the main theme. Apply again after changing it; restart apps to see the colors.",
+ app_colors_message_buf: [384]u8 = undefined,
dark_row_children: [2]Widget = undefined,
dark_label_children: [2]Widget = undefined,
splash_row_children: [2]Widget = undefined,
@@ -362,6 +370,15 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
buildWallpaper(out, arena);
const pal = panel.palette();
+ out.app_colors_buttons = .{
+ .{ .name = "apply_gtk_colors", .kind = .{ .button = .{ .label = "Apply GTK colors", .owner = out, .id = 0, .on_click = &onApplyAppColors, .state = if (out.app_colors_job != null) .disabled else .idle } }, .width = .{ .flex = 1 }, .height = .{ .fixed = 32 } },
+ .{ .name = "apply_qt_colors", .kind = .{ .button = .{ .label = "Apply Qt colors", .owner = out, .id = 1, .on_click = &onApplyAppColors, .state = if (out.app_colors_job != null) .disabled else .idle } }, .width = .{ .flex = 1 }, .height = .{ .fixed = 32 } },
+ };
+ out.app_colors_children = .{
+ labelWidget("App colors"),
+ .{ .kind = .container, .direction = .row, .gap = 8, .children = &out.app_colors_buttons },
+ appColorsNote(out, arena, pal.dim),
+ };
const dark_mode = out.cc.server.config.compositor.dark_mode;
out.dark_label_children = .{
.{ .kind = .{ .text = .{ .content = "Dark mode", .font_size = 13, .weight = 600, .color = pal.fg } } },
@@ -667,6 +684,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
out.row_storage = .{
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.theme_row_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.taskbar_theme_row_children },
+ .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.app_colors_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dark_row_children },
.{ .kind = .container, .direction = .column, .gap = 12, .children = &out.wallpaper_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.splash_row_children },
@@ -736,6 +754,92 @@ fn stopStrip(out: *Section) void {
pub fn deinit(out: *Section) void {
stopStrip(out);
+ finishAppColors(out, false);
+}
+
+fn appColorsNote(s: *Section, a: std.mem.Allocator, color: [4]f32) Widget {
+ const text = @import("ui").text;
+ const width: f32 = @floatFromInt(@max(120, s.cc.panel_box.width - @as(i32, if (s.cc.panel_box.width < 660) 70 else 238) - 100));
+ var lines: std.ArrayList(Widget) = .empty;
+ var start: usize = 0;
+ var words = std.mem.tokenizeScalar(u8, s.app_colors_message, ' ');
+ var end: usize = 0;
+ while (words.next()) |word| {
+ const next = @intFromPtr(word.ptr) - @intFromPtr(s.app_colors_message.ptr) + word.len;
+ const measured = text.measureWidthF(s.app_colors_message[start..next], .manrope, 12, 1) catch 0;
+ if (end > start and measured > width) {
+ lines.append(a, .{ .name = std.fmt.allocPrint(a, "app_colors_status_{d}", .{lines.items.len}) catch "app_colors_status_line", .kind = .{ .text = .{ .content = s.app_colors_message[start..end], .font_size = 12, .color = color } } }) catch break;
+ start = next - word.len;
+ }
+ end = next;
+ }
+ if (end > start) lines.append(a, .{ .name = std.fmt.allocPrint(a, "app_colors_status_{d}", .{lines.items.len}) catch "app_colors_status_line", .kind = .{ .text = .{ .content = s.app_colors_message[start..end], .font_size = 12, .color = color } } }) catch {};
+ return .{ .name = "app_colors_status", .kind = .container, .direction = .column, .gap = 2, .children = lines.toOwnedSlice(a) catch &.{} };
+}
+
+fn onApplyAppColors(owner: ?*anyopaque, id: usize) void {
+ const s = section(owner);
+ if (s.app_colors_job != null or s.cc.server.greeter_mode) return;
+ const job = AppColorsJob.create(s.cc.server.io, s.cc.server.environ, if (id == 0) .gtk else .qt, app_theme.Palette.fromTheme(theme.global)) catch |err| {
+ appColorsFailure(s, err);
+ return;
+ };
+ const source = s.cc.server.wl_server.getEventLoop().addFd(*Section, job.fd, .{ .readable = true }, appColorsReady, s) catch |err| {
+ job.deinit();
+ appColorsFailure(s, err);
+ return;
+ };
+ job.start() catch |err| {
+ source.remove();
+ job.deinit();
+ appColorsFailure(s, err);
+ return;
+ };
+ s.app_colors_job = job;
+ s.app_colors_source = source;
+ s.app_colors_message = "Applying app colors…";
+ s.cc.refresh();
+}
+
+fn appColorsFailure(s: *Section, err: anyerror) void {
+ s.app_colors_message = switch (err) {
+ error.QtToolsMissing => "Install qt5ct for Qt 5 apps or qt6ct for Qt 6 apps, then apply again.",
+ error.ManagedSymlink => "A toolkit file is managed by a symlink. Update its source configuration before applying colors.",
+ error.InvalidManagedCss => "The RediWM block in gtk.css is incomplete. Repair it before applying colors.",
+ else => std.fmt.bufPrint(&s.app_colors_message_buf, "Could not apply app colors: {s}. Check your configuration files and permissions.", .{@errorName(err)}) catch "Could not apply app colors. Check your configuration files and permissions.",
+ };
+ std.log.warn("app colors export failed: {}", .{err});
+ s.cc.refresh();
+}
+
+fn finishAppColors(s: *Section, refresh: bool) void {
+ if (s.app_colors_source) |source| source.remove();
+ s.app_colors_source = null;
+ const job = s.app_colors_job orelse return;
+ s.app_colors_job = null;
+ job.join();
+ defer job.deinit();
+ const support = job.result catch |err| {
+ if (refresh) appColorsFailure(s, err);
+ return;
+ };
+ if (job.toolkit == .qt) s.cc.server.qt_app_colors = true;
+ if (!refresh) return;
+ s.app_colors_message = switch (job.toolkit) {
+ .gtk => "GTK colors applied. Restart GTK apps. Apps with their own styles or sandbox settings may differ.",
+ .qt => if (support.qt5 and support.qt6)
+ "Qt 5 and Qt 6 colors applied. Restart apps; sign in again if their colors do not change."
+ else if (support.qt6)
+ "Qt 6 colors applied. Install qt5ct for Qt 5 apps. Restart apps; sign in again if their colors do not change."
+ else
+ "Qt 5 colors applied. Install qt6ct for Qt 6 apps. Restart apps; sign in again if their colors do not change.",
+ };
+ s.cc.refresh();
+}
+
+fn appColorsReady(_: c_int, _: wl.EventMask, s: *Section) c_int {
+ finishAppColors(s, true);
+ return 0;
}
/// Thumbnails arrive one by one; the panel repaints for each.
diff --git a/src/files/archive.zig b/src/files/archive.zig
index f047a59..56e2840 100644
--- a/src/files/archive.zig
+++ b/src/files/archive.zig
@@ -217,6 +217,33 @@ fn openDirectory(root: c_int, path: []const u8) !c_int {
return fd;
}
+const Links = std.StringHashMapUnmanaged([]const u8);
+
+/// Resolve archive links component by component, including links before '..'.
+/// Lexical normalization alone can miss escapes through another symlink.
+fn resolveLink(mem: Allocator, links: *const Links, path: []const u8, resolved: *std.ArrayList(u8), followed: *usize) anyerror!void {
+ if (path.len == 0 or path.len > 4095 or path[0] == '/' or std.mem.indexOfAny(u8, path, "\\\x00:") != null) return error.UnsafeArchivePath;
+ var parts = std.mem.splitScalar(u8, path, '/');
+ while (parts.next()) |part| {
+ if (part.len == 0 or std.mem.eql(u8, part, ".")) continue;
+ if (std.mem.eql(u8, part, "..")) {
+ if (resolved.items.len == 0) return error.UnsafeArchivePath;
+ resolved.shrinkRetainingCapacity(std.mem.lastIndexOfScalar(u8, resolved.items, '/') orelse 0);
+ continue;
+ }
+ const parent_len = resolved.items.len;
+ if (parent_len > 0) try resolved.append(mem, '/');
+ try resolved.appendSlice(mem, part);
+ if (resolved.items.len > 4095) return error.UnsafeArchivePath;
+ if (links.get(resolved.items)) |target| {
+ followed.* += 1;
+ if (followed.* > 40) return error.UnsafeArchivePath;
+ resolved.shrinkRetainingCapacity(parent_len);
+ try resolveLink(mem, links, target, resolved, followed);
+ }
+ }
+}
+
/// Destination must be a private, newly created staging directory. Publication
/// into the user's folder is handled by JobRunner's no-overwrite transfer path.
pub fn extract(mem: Allocator, path: []const u8, destination: []const u8, member: ?[]const u8, cancel: *const Cancel) !void {
@@ -227,6 +254,11 @@ pub fn extract(mem: Allocator, path: []const u8, destination: []const u8, member
const root = c.open(zdest, c.O_RDONLY | c.O_DIRECTORY | c.O_NOFOLLOW | c.O_CLOEXEC);
if (root < 0) return error.WriteFailed;
defer _ = c.close(root);
+ var arena = std.heap.ArenaAllocator.init(mem);
+ defer arena.deinit();
+ const alloc = arena.allocator();
+ var links: Links = .empty;
+ var link_bytes: usize = 0;
var found = false;
while (try reader.next(cancel)) |entry| {
const raw = a.archive_entry_pathname(entry) orelse return error.InvalidArchive;
@@ -238,6 +270,15 @@ pub fn extract(mem: Allocator, path: []const u8, destination: []const u8, member
}
if (member) |wanted| if (!std.mem.eql(u8, name, wanted)) continue;
const kind = a.archive_entry_filetype(entry);
+ if (kind == c.S_IFLNK and a.archive_entry_hardlink(entry) == null and member == null) {
+ const target = std.mem.span(a.archive_entry_symlink(entry) orelse return error.InvalidArchive);
+ link_bytes += name.len + target.len;
+ if (links.count() >= 250_000 or link_bytes > 32 * 1024 * 1024) return error.ArchiveTooLarge;
+ const slot = try links.getOrPut(alloc, try alloc.dupe(u8, name));
+ if (slot.found_existing) return error.InvalidArchive;
+ slot.value_ptr.* = try alloc.dupe(u8, target);
+ continue;
+ }
if ((kind != c.S_IFREG and kind != c.S_IFDIR) or a.archive_entry_hardlink(entry) != null) return error.UnsupportedArchiveEntry;
const parent = try openDirectory(root, if (kind == c.S_IFDIR) name else std.fs.path.dirname(name) orelse "");
defer _ = c.close(parent);
@@ -269,4 +310,26 @@ pub fn extract(mem: Allocator, path: []const u8, destination: []const u8, member
if (member != null) break;
}
if (member != null and !found) return error.MemberNotFound;
+ // Finish all file writes before installing links. Never traverse a link to
+ // create archive content, and validate the complete graph before publication.
+ var resolved: std.ArrayList(u8) = .empty;
+ defer resolved.deinit(mem);
+ var iterator = links.iterator();
+ while (iterator.next()) |link| {
+ try check(cancel);
+ resolved.clearRetainingCapacity();
+ var followed: usize = 0;
+ try resolveLink(mem, &links, link.key_ptr.*, &resolved, &followed);
+ }
+ iterator = links.iterator();
+ while (iterator.next()) |link| {
+ try check(cancel);
+ const parent = try openDirectory(root, std.fs.path.dirname(link.key_ptr.*) orelse "");
+ defer _ = c.close(parent);
+ const name = try mem.dupeZ(u8, std.fs.path.basename(link.key_ptr.*));
+ defer mem.free(name);
+ const target = try mem.dupeZ(u8, link.value_ptr.*);
+ defer mem.free(target);
+ if (c.symlinkat(target, parent, name) != 0) return error.WriteFailed;
+ }
}
diff --git a/src/files_tests.zig b/src/files_tests.zig
index f688ac1..4f57d8e 100644
--- a/src/files_tests.zig
+++ b/src/files_tests.zig
@@ -1145,6 +1145,12 @@ test "Git porcelain preserves paths, rename pairs, conflicts and directory bound
}
fn writeArchiveFixture(path: []const u8, names: []const [:0]const u8) !void {
+ try writeArchiveFixtureLinks(path, names, &.{});
+}
+
+const ArchiveLinkFixture = struct { name: [:0]const u8, target: [:0]const u8 };
+
+fn writeArchiveFixtureLinks(path: []const u8, names: []const [:0]const u8, links: []const ArchiveLinkFixture) !void {
const api = @cImport({
@cInclude("archive.h");
@cInclude("archive_entry.h");
@@ -1171,9 +1177,79 @@ fn writeArchiveFixture(path: []const u8, names: []const [:0]const u8) !void {
try std.testing.expectEqual(@as(c_int, 0), api.archive_write_header(writer, entry));
if (!directory) try std.testing.expectEqual(@as(isize, 7), api.archive_write_data(writer, "payload", 7));
}
+ for (links) |link| {
+ const entry = api.archive_entry_new() orelse return error.OutOfMemory;
+ defer api.archive_entry_free(entry);
+ api.archive_entry_set_pathname(entry, link.name);
+ api.archive_entry_set_filetype(entry, c.S_IFLNK);
+ api.archive_entry_set_perm(entry, 0o777);
+ api.archive_entry_set_symlink(entry, link.target);
+ try std.testing.expectEqual(@as(c_int, 0), api.archive_write_header(writer, entry));
+ }
try std.testing.expectEqual(@as(c_int, 0), api.archive_write_close(writer));
}
+test "archive relative symlinks survive publication and cannot escape staging" {
+ const archive = @import("files/archive.zig");
+ const mem = std.testing.allocator;
+ for ([_][]const u8{ ".zip", ".tar.gz" }) |extension| {
+ var buf: [256]u8 = undefined;
+ const root = try makeTestDir(&buf);
+ defer ops_mod.deleteRecursive(mem, root) catch {};
+ const source = try std.fmt.allocPrint(mem, "{s}/sample{s}", .{ root, extension });
+ defer mem.free(source);
+ try writeArchiveFixtureLinks(source, &.{"repo/dank-qml-common/DCommon/item.txt"}, &.{
+ .{ .name = "repo/quickshell/DCommon", .target = "../dank-qml-common/DCommon" },
+ .{ .name = "repo/alias", .target = "quickshell/DCommon" },
+ .{ .name = "repo/dangling", .target = "missing" },
+ });
+ var runner = try ops_mod.JobRunner.init(mem);
+ defer runner.deinit();
+ try runner.startArchive(source, root, null);
+ runner.thread.?.join();
+ runner.thread = null;
+ try std.testing.expectEqual(@as(usize, 1), runner.pollProgress().success_count);
+ const link = try std.fmt.allocPrintSentinel(mem, "{s}/repo/quickshell/DCommon", .{root}, 0);
+ defer mem.free(link);
+ var target: [128]u8 = undefined;
+ const n = c.readlink(link, &target, target.len);
+ try std.testing.expect(n > 0);
+ try std.testing.expectEqualStrings("../dank-qml-common/DCommon", target[0..@intCast(n)]);
+ const alias = try std.fmt.allocPrint(mem, "{s}/repo/alias/item.txt", .{root});
+ defer mem.free(alias);
+ var content: [32]u8 = undefined;
+ try std.testing.expectEqualStrings("payload", try readTestFile(alias, &content));
+
+ const unsafe: []const []const ArchiveLinkFixture = &.{
+ &.{.{ .name = "link", .target = "/tmp/outside" }},
+ &.{.{ .name = "repo/link", .target = "../../outside" }},
+ &.{.{ .name = "link", .target = "link" }},
+ &.{ .{ .name = "repo/up", .target = ".." }, .{ .name = "repo/link", .target = "up/../outside" } },
+ &.{ .{ .name = "a", .target = "b" }, .{ .name = "b", .target = "a" } },
+ };
+ var cancel: archive.Cancel = .init(false);
+ for (unsafe) |links| {
+ try writeArchiveFixtureLinks(source, &.{"safe.txt"}, links);
+ const stage = try archive.temporary(mem, root);
+ defer mem.free(stage);
+ try std.testing.expectError(error.UnsafeArchivePath, archive.extract(mem, source, stage, null, &cancel));
+ try runner.startArchive(source, root, null);
+ runner.thread.?.join();
+ runner.thread = null;
+ try std.testing.expectEqual(@as(usize, 1), runner.pollProgress().failed_count);
+ const safe = try std.fmt.allocPrintSentinel(mem, "{s}/safe.txt", .{root}, 0);
+ defer mem.free(safe);
+ try std.testing.expect(c.access(safe, c.F_OK) != 0);
+ }
+ // A link cannot turn an archived child path into a redirected write.
+ try writeArchiveFixtureLinks(source, &.{"repo/link/item.txt"}, &.{.{ .name = "repo/link", .target = "../other" }});
+ const stage = try archive.temporary(mem, root);
+ defer mem.free(stage);
+ try std.testing.expectError(error.WriteFailed, archive.extract(mem, source, stage, null, &cancel));
+ try std.testing.expectError(error.UnsupportedArchiveEntry, archive.extract(mem, source, stage, "repo/link", &cancel));
+ }
+}
+
test "archive index, staged extraction and member reads preserve destination boundaries" {
for ([_][]const u8{ ".zip", ".tar.gz" }) |extension| {
const archive = @import("files/archive.zig");
diff --git a/src/session/activation.zig b/src/session/activation.zig
index 5691370..31986e8 100644
--- a/src/session/activation.zig
+++ b/src/session/activation.zig
@@ -172,7 +172,10 @@ pub const Readiness = struct {
.XDG_CURRENT_DESKTOP = child_env.desktop_name,
.XDG_SESSION_TYPE = child_env.session_type,
.PATH = map.get("PATH") orelse "",
- }, .{});
+ .QT_QPA_PLATFORMTHEME = map.get("QT_QPA_PLATFORMTHEME"),
+ .QT_QPA_PLATFORMTHEME_QT6 = map.get("QT_QPA_PLATFORMTHEME_QT6"),
+ .QT_STYLE_OVERRIDE = map.get("QT_STYLE_OVERRIDE"),
+ }, .{ .emit_null_optional_fields = false });
defer allocator.free(message);
errdefer self.deinit();
diff --git a/src/session/publication.zig b/src/session/publication.zig
index 3589d84..f3afdeb 100644
--- a/src/session/publication.zig
+++ b/src/session/publication.zig
@@ -7,7 +7,7 @@ const linux = std.os.linux;
const sys = @import("login_sys.zig");
pub const owner_key = "REDIWM_ACTIVATION_OWNER";
-pub const allowlist = [_][]const u8{ "WAYLAND_DISPLAY", "DISPLAY", "REDIWM_SOCKET", "XDG_CURRENT_DESKTOP", "XDG_SESSION_TYPE", "PATH", owner_key };
+pub const allowlist = [_][]const u8{ "WAYLAND_DISPLAY", "DISPLAY", "REDIWM_SOCKET", "XDG_CURRENT_DESKTOP", "XDG_SESSION_TYPE", "PATH", "QT_QPA_PLATFORMTHEME", "QT_QPA_PLATFORMTHEME_QT6", "QT_STYLE_OVERRIDE", owner_key };
pub const Env = std.StringArrayHashMapUnmanaged([]const u8);
pub const Pair = struct { key: []const u8, value: []const u8 };
@@ -291,6 +291,23 @@ test "restore unsets or restores only allowlisted values" {
try testing.expectEqualStrings(":old", f.bus.activated.get("DISPLAY").?);
}
+test "Qt app colors activation lease restores the previous desktop theme" {
+ var f: Fixture = undefined;
+ try f.init();
+ defer f.deinit();
+ try f.bus.systemd(&.{.{ .key = "QT_QPA_PLATFORMTHEME", .value = "gtk3" }}, &.{});
+ try f.owner.publish(&.{
+ .{ .key = "QT_QPA_PLATFORMTHEME", .value = "qt5ct" },
+ .{ .key = "QT_QPA_PLATFORMTHEME_QT6", .value = "qt6ct" },
+ .{ .key = "QT_STYLE_OVERRIDE", .value = "Fusion" },
+ });
+ try testing.expectEqualStrings("qt5ct", f.bus.env.get("QT_QPA_PLATFORMTHEME").?);
+ try f.owner.restore();
+ try testing.expectEqualStrings("gtk3", f.bus.env.get("QT_QPA_PLATFORMTHEME").?);
+ try testing.expect(!f.bus.env.contains("QT_QPA_PLATFORMTHEME_QT6"));
+ try testing.expect(!f.bus.env.contains("QT_STYLE_OVERRIDE"));
+}
+
test "a value changed by someone else is not clobbered" {
var f: Fixture = undefined;
try f.init();
diff --git a/src/xwayland_output.zig b/src/xwayland_output.zig
index da2cab8..18884c1 100644
--- a/src/xwayland_output.zig
+++ b/src/xwayland_output.zig
@@ -1,8 +1,8 @@
// Specialized zxdg_output_manager_v1 global visible only to the Xwayland client.
-// Tells Xwayland the screen is N times larger than its logical geometry, so X11
-// apps render at panel resolution instead of 1x.
+// Describes the visible world in X11 pixels: rendering scale divided by camera
+// zoom, with the combined layout origin translated to zero. X11's root input
+// rectangle must cover everything visible even when the canvas is zoomed out.
const std = @import("std");
-const xscale = @import("xwayland_scale.zig");
const wayland = @import("wayland");
const wl = wayland.server.wl;
const zxdg = wayland.server.zxdg;
@@ -192,14 +192,25 @@ const XwaylandOutput = struct {
}
}
- fn sendState(self: *XwaylandOutput, r: *OutputResource) void {
+ fn geometry(self: *XwaylandOutput) wlr.Box {
var box: wlr.Box = undefined;
self.manager.server.output_layout.getBox(self.wlr_output, &box);
const n = self.manager.server.xwaylandScale();
- const lx = xscale.surfacePosition(box.x, n);
- const ly = xscale.surfacePosition(box.y, n);
- const lw = xscale.surfacePosition(box.x + box.width, n) - lx;
- const lh = xscale.surfacePosition(box.y + box.height, n) - ly;
+ const world = &self.manager.server.world;
+ const factor = n / world.camera.zoom();
+ const lx: i32 = @intFromFloat(@round((@as(f64, @floatFromInt(box.x)) - world.bounds.origin_x) * factor));
+ const ly: i32 = @intFromFloat(@round((@as(f64, @floatFromInt(box.y)) - world.bounds.origin_y) * factor));
+ const right: i32 = @intFromFloat(@round((@as(f64, @floatFromInt(box.x + box.width)) - world.bounds.origin_x) * factor));
+ const bottom: i32 = @intFromFloat(@round((@as(f64, @floatFromInt(box.y + box.height)) - world.bounds.origin_y) * factor));
+ return .{ .x = lx, .y = ly, .width = right - lx, .height = bottom - ly };
+ }
+
+ fn sendState(self: *XwaylandOutput, r: *OutputResource) void {
+ const box = self.geometry();
+ const lx = box.x;
+ const ly = box.y;
+ const lw = box.width;
+ const lh = box.height;
self.last_x = lx;
self.last_y = ly;
@@ -224,13 +235,11 @@ const XwaylandOutput = struct {
}
fn syncGeometry(self: *XwaylandOutput) void {
- var box: wlr.Box = undefined;
- self.manager.server.output_layout.getBox(self.wlr_output, &box);
- const n = self.manager.server.xwaylandScale();
- const lx = xscale.surfacePosition(box.x, n);
- const ly = xscale.surfacePosition(box.y, n);
- const lw = xscale.surfacePosition(box.x + box.width, n) - lx;
- const lh = xscale.surfacePosition(box.y + box.height, n) - ly;
+ const box = self.geometry();
+ const lx = box.x;
+ const ly = box.y;
+ const lw = box.width;
+ const lh = box.height;
if (lx == self.last_x and ly == self.last_y and lw == self.last_width and lh == self.last_height) {
return;
diff --git a/src/xwayland_surface.zig b/src/xwayland_surface.zig
index 84278ae..d32a123 100644
--- a/src/xwayland_surface.zig
+++ b/src/xwayland_surface.zig
@@ -146,10 +146,15 @@ pub fn serverDecorations(self: *const Adapter) bool {
return !(d.no_title and d.no_border);
}
+/// Positions arrive in world coordinates multiplied by the X11 rendering
+/// factor; only the protocol boundary subtracts the current root origin.
pub fn configure(self: *Adapter, x: i32, y: i32, width: i32, height: i32) void {
const hints: ?*const SizeHints = if (self.xsurface.size_hints) |ptr| @ptrCast(@alignCast(ptr)) else null;
const size = applySizeHints(width, height, hints);
- self.xsurface.configure(clampPos(x), clampPos(y), clampSize(size.width), clampSize(size.height));
+ const xwayland = self.window.server.xwayland;
+ const root_x = if (xwayland) |xw| xw.root_x else 0;
+ const root_y = if (xwayland) |xw| xw.root_y else 0;
+ self.xsurface.configure(clampPos(x - root_x), clampPos(y - root_y), clampSize(size.width), clampSize(size.height));
self.awaiting_commit = true;
}
@@ -306,8 +311,9 @@ fn handleRequestConfigure(
toplevel.clientSurfaceGeometry().height;
if (!toplevel.in_world) {
- if (event.mask & config_x != 0) x = xscale.worldFloor(event.x, n);
- if (event.mask & config_y != 0) y = xscale.worldFloor(event.y, n);
+ const xwayland = toplevel.server.xwayland;
+ if (event.mask & config_x != 0) x = xscale.worldFloor(@as(i32, event.x) + (if (xwayland) |xw| xw.root_x else @as(i32, 0)), n);
+ if (event.mask & config_y != 0) y = xscale.worldFloor(@as(i32, event.y) + (if (xwayland) |xw| xw.root_y else @as(i32, 0)), n);
}
if (toplevel.open_rules.width) |rw| width_x = xscale.surfaceLength(@as(i32, @intCast(rw)), n);
if (toplevel.open_rules.height) |rh| height_x = xscale.surfaceLength(@as(i32, @intCast(rh)), n);
diff --git a/src/xwayland_unmanaged.zig b/src/xwayland_unmanaged.zig
index 8016e82..d142d26 100644
--- a/src/xwayland_unmanaged.zig
+++ b/src/xwayland_unmanaged.zig
@@ -126,7 +126,17 @@ fn syncPosition(self: *Unmanaged) void {
self.tree.node.setPosition(px + xscale.worldFloor(dx, n), py + xscale.worldFloor(dy, n));
return;
}
- self.tree.node.setPosition(xscale.worldFloor(@as(i32, self.xsurface.x), n), xscale.worldFloor(@as(i32, self.xsurface.y), n));
+ const xwayland = self.server.xwayland;
+ const root_x = if (xwayland) |xw| xw.root_x else 0;
+ const root_y = if (xwayland) |xw| xw.root_y else 0;
+ self.tree.node.setPosition(xscale.worldFloor(@as(i32, self.xsurface.x) + root_x, n), xscale.worldFloor(@as(i32, self.xsurface.y) + root_y, n));
+}
+
+pub fn rebase(self: *Unmanaged, dx: i32, dy: i32) void {
+ const clamp = @import("xwayland_surface.zig").clampPos;
+ const xs = self.xsurface;
+ xs.configure(clamp(@as(i32, xs.x) + dx), clamp(@as(i32, xs.y) + dy), xs.width, xs.height);
+ self.syncPosition();
}
fn destroyRole(self: *Unmanaged) void {
diff --git a/tests/app_colors_gtk_client.c b/tests/app_colors_gtk_client.c
new file mode 100644
index 0000000..95681b6
--- /dev/null
+++ b/tests/app_colors_gtk_client.c
@@ -0,0 +1,54 @@
+/* Query actual toolkit styling after GTK loads the exported user CSS. */
+#include <gtk/gtk.h>
+#include <stdio.h>
+#ifdef USE_ADWAITA
+#include <adwaita.h>
+#endif
+
+int main(int argc, char **argv) {
+#if GTK_MAJOR_VERSION == 3
+ gtk_init(&argc, &argv);
+#else
+ (void)argc; (void)argv;
+ gtk_init();
+#endif
+#ifdef USE_ADWAITA
+ adw_init();
+ GtkWidget *window = adw_window_new();
+#else
+ GtkWidget *window = gtk_window_new(
+#if GTK_MAJOR_VERSION == 3
+ GTK_WINDOW_TOPLEVEL
+#endif
+ );
+#endif
+ GtkStyleContext *context = gtk_widget_get_style_context(window);
+ cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 4, 4);
+ cairo_t *cr = cairo_create(surface);
+ GdkRGBA fg;
+#if GTK_MAJOR_VERSION == 3
+ gtk_style_context_get_color(context, GTK_STATE_FLAG_NORMAL, &fg);
+ gtk_render_background(context, cr, 0, 0, 4, 4);
+#else
+ gtk_style_context_get_color(context, &fg);
+ GtkSnapshot *snapshot = gtk_snapshot_new();
+ gtk_snapshot_render_background(snapshot, context, 0, 0, 4, 4);
+ GskRenderNode *node = gtk_snapshot_free_to_node(snapshot);
+ if (node) {
+ gsk_render_node_draw(node, cr);
+ gsk_render_node_unref(node);
+ }
+#endif
+ cairo_destroy(cr);
+ cairo_surface_flush(surface);
+ unsigned pixel = *(unsigned *)(cairo_image_surface_get_data(surface) + cairo_image_surface_get_stride(surface) + 4);
+ printf("{\"bg\":\"#%06x\",\"fg\":\"#%02x%02x%02x\"}\n", pixel & 0xffffff,
+ (unsigned)(fg.red * 255 + .5), (unsigned)(fg.green * 255 + .5), (unsigned)(fg.blue * 255 + .5));
+ cairo_surface_destroy(surface);
+#if GTK_MAJOR_VERSION == 3
+ gtk_widget_destroy(window);
+#else
+ gtk_window_destroy(GTK_WINDOW(window));
+#endif
+ return 0;
+}
diff --git a/tests/app_colors_qt_client.cpp b/tests/app_colors_qt_client.cpp
new file mode 100644
index 0000000..87013d8
--- /dev/null
+++ b/tests/app_colors_qt_client.cpp
@@ -0,0 +1,22 @@
+// Read the platform plugin's real QPalette, including the Qt6 Accent role.
+#include <QApplication>
+#include <QPalette>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <cstdio>
+
+int main(int argc, char **argv) {
+ QApplication app(argc, argv);
+ QPalette p = app.palette();
+ QJsonObject out{
+ {"bg", p.color(QPalette::Window).name()},
+ {"fg", p.color(QPalette::WindowText).name()},
+ {"accent", p.color(QPalette::Highlight).name()},
+ {"on_accent", p.color(QPalette::HighlightedText).name()},
+ {"disabled", p.color(QPalette::Disabled, QPalette::WindowText).name()}
+ };
+#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)
+ out.insert("qt6_accent", p.color(QPalette::Accent).name());
+#endif
+ std::puts(QJsonDocument(out).toJson(QJsonDocument::Compact).constData());
+}
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index 31fb77b..68ff687 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -8,6 +8,10 @@ import tempfile
import time
import tomllib
import re
+import os
+import json
+import subprocess
+import sys
from ipc_client import IPCClient, spawn_compositor, stop_process
from ui_driver import UIDriver
@@ -521,6 +525,156 @@ def test_appearance_settings():
stop_process(process)
+def test_app_colors():
+ with tempfile.TemporaryDirectory(prefix="rediwm-app-colors-") as directory:
+ tmp = Path(directory)
+ config = tmp / "custom, config"
+ helpers = tmp / "bin"
+ helpers.mkdir()
+ for name in ("qt5ct", "qt6ct"):
+ helper = helpers / name
+ helper.write_text("#!/bin/sh\nexit 0\n")
+ helper.chmod(0o700)
+ gtk_original = "/* User CSS survives */\nlabel.user-rule { color: red; }\n"
+ for version in ("gtk-3.0", "gtk-4.0"):
+ (config / version).mkdir(parents=True)
+ (config / version / "gtk.css").write_text(gtk_original)
+ qt_original = "# User preferences\n[Appearance]\ncustom_palette=false\nstyle=Old\n[Fonts]\ngeneral=Example\n[Other]\ncustom_palette=false\n"
+ for version in ("qt5ct", "qt6ct"):
+ (config / version).mkdir()
+ (config / version / (version + ".conf")).write_text(qt_original)
+ theme = ('[compositor]\nxwayland = false\n[theme]\napp_bg = "#123456"\nwindow_fg = "#e1e2e3"\n'
+ 'app_toolbar = "#234567"\napp_sidebar = "#345678"\nshell_accent = "#abcdef"\n'
+ '[taskbar_theme]\nwindow_fg = "#010203"\nstart_menu_selected_marker = "#ff0000"\n')
+ env = {"HOME": str(tmp / "home"), "XDG_CONFIG_HOME": str(config),
+ "XDG_DATA_HOME": str(tmp / "custom-data"), "XDG_DATA_DIRS": str(tmp / "empty-data"),
+ "XDG_CACHE_HOME": str(tmp / "cache"), "DBUS_SESSION_BUS_ADDRESS": "",
+ "PATH": str(helpers), "QT_QPA_PLATFORMTHEME": "gtk3",
+ "QT_STYLE_OVERRIDE": "kvantum", "REDIWM_FILES_DEVICES": "0"}
+ process, log = spawn_compositor(tmp, config_content=theme, env_extra=env)
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ui = UIDriver(ipc)
+ ipc.action("open_appearance")
+ ui.wait_settled("control_center")
+
+ def message():
+ return " ".join((w.get("label") or "") for w in ui.widgets("control_center") if (w.get("name") or "").startswith("app_colors_status_"))
+
+ def apply(name, expected):
+ ui.click(ui.scroll_into_view(name))
+ wait_for(lambda: expected in message(), expected)
+
+ apply("apply_gtk_colors", "GTK colors applied")
+ apply("apply_gtk_colors", "GTK colors applied")
+ for version in ("gtk-3.0", "gtk-4.0"):
+ css = (config / version / "gtk.css").read_text()
+ assert css.count("BEGIN REDIWM APP COLORS") == 1
+ assert css.endswith(gtk_original), css
+ assert (config / version / "gtk.css.rediwm-backup").read_text() == gtk_original
+ assert "window_bg_color #123456" in (config / version / "rediwm-colors.css").read_text()
+
+ apply("apply_qt_colors", "Qt 5 and Qt 6 colors applied")
+ for version in ("qt5ct", "qt6ct"):
+ settings = (config / version / (version + ".conf")).read_text()
+ assert "style=Fusion" in settings and "[Fonts]\ngeneral=Example" in settings
+ assert "[Other]\ncustom_palette=false" in settings
+ assert (config / version / (version + ".conf.rediwm-backup")).read_text() == qt_original
+ palette = (config / version / "colors/rediwm.conf").read_text()
+ for line in palette.splitlines()[1:]:
+ assert len(line.split("=", 1)[1].split(",")) == 22
+ assert "qt=true" in (config / "rediwm/app-colors.conf").read_text()
+ if preview := os.environ.get("REDIWM_SETTINGS_PREVIEW"):
+ Path(preview).mkdir(parents=True, exist_ok=True)
+ ui.scroll_into_view("apply_gtk_colors")
+ ui.wait_settled("control_center")
+ capture = Path(preview) / "app-colors.png"
+ capture.unlink(missing_ok=True)
+ ipc.screenshot(str(capture))
+
+ # Check the environment delivered to a newly launched app.
+ received = tmp / "child-env.json"
+ probe = tmp / "env.py"
+ probe.write_text("""import os,json,sys
+from pathlib import Path
+keys = ('HOME', 'XDG_RUNTIME_DIR', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME',
+ 'XDG_DATA_DIRS', 'XDG_CACHE_HOME', 'WAYLAND_DISPLAY', 'DISPLAY',
+ 'DBUS_SESSION_BUS_ADDRESS', 'DBUS_SYSTEM_BUS_ADDRESS',
+ 'QT_QPA_PLATFORMTHEME', 'QT_QPA_PLATFORMTHEME_QT6', 'QT_STYLE_OVERRIDE',
+ 'PATH', 'LANG', 'LC_ALL', 'XDG_CURRENT_DESKTOP', 'XDG_SESSION_TYPE')
+Path(sys.argv[1]).write_text(json.dumps({k: os.environ[k] for k in keys if k in os.environ}))
+""")
+ ipc.action("spawn", {"argv": [sys.executable, str(probe), str(received)]})
+ wait_for(received.exists, "app environment")
+ child_env = json.loads(received.read_text())
+ assert child_env["QT_QPA_PLATFORMTHEME"] == "qt5ct", child_env
+ assert child_env["QT_STYLE_OVERRIDE"] == "Fusion", child_env
+
+ # These clients use real toolkit loaders, on the private display.
+ root = Path(__file__).resolve().parent
+ for package, source, compiler, extra in (
+ ("gtk+-3.0", "app_colors_gtk_client.c", "cc", []),
+ ("gtk4", "app_colors_gtk_client.c", "cc", []),
+ ("libadwaita-1", "app_colors_gtk_client.c", "cc", ["-DUSE_ADWAITA"]),
+ ("Qt5Widgets", "app_colors_qt_client.cpp", "c++", ["-fPIC"]),
+ ("Qt6Widgets", "app_colors_qt_client.cpp", "c++", ["-fPIC"])):
+ if subprocess.run(["pkg-config", "--exists", package]).returncode:
+ print("SKIP: app palette probe for", package)
+ continue
+ binary = tmp / package
+ flags = subprocess.check_output(["pkg-config", "--cflags", "--libs", package], text=True).split()
+ subprocess.run([compiler, str(root / source), "-o", str(binary), *extra, *flags], check=True, capture_output=True)
+ result = subprocess.run([str(binary)], env=child_env, text=True, capture_output=True, timeout=20, check=True)
+ assert "Theme parser error" not in result.stderr and "Theme parsing error" not in result.stderr, result.stderr
+ colors = json.loads(result.stdout)
+ assert colors["bg"] == "#123456" and colors["fg"] == "#e1e2e3", (package, colors, result.stderr)
+ if "accent" in colors:
+ assert colors["accent"] == "#abcdef" and colors["on_accent"] == "#000000", colors
+ assert colors["disabled"] != colors["fg"], colors
+ if "qt6_accent" in colors:
+ assert colors["qt6_accent"] == "#abcdef", colors
+
+ # A managed symlink must fail without touching either toolkit.
+ gtk4_css = config / "gtk-4.0/gtk.css"
+ gtk4_css.unlink()
+ external = tmp / "external.css"
+ external.write_text("/* external */\n")
+ gtk4_css.symlink_to(external)
+ before = (config / "gtk-3.0/rediwm-colors.css").read_bytes()
+ apply("apply_gtk_colors", "managed by a symlink")
+ assert external.read_text() == "/* external */\n"
+ assert before == (config / "gtk-3.0/rediwm-colors.css").read_bytes()
+ gtk4_css.unlink()
+ (config / "qt6ct/qt6ct.conf").unlink()
+ (config / "qt6ct/qt6ct.conf").mkdir()
+ apply("apply_qt_colors", "Could not apply app colors")
+ assert "InvalidFile" in message(), message()
+ for name in ("qt5ct", "qt6ct"):
+ (helpers / name).unlink()
+ apply("apply_qt_colors", "Install qt5ct")
+
+ stop_process(process)
+ assert process.returncode == 0, (tmp / "compositor.log").read_text()
+ finally:
+ stop_process(process)
+ log.close()
+ # The Qt opt-in survives compositor restart, including launches before
+ # Settings has ever been opened.
+ process, log = spawn_compositor(tmp, config_content=theme, env_extra=env)
+ try:
+ received.unlink()
+ with IPCClient(tmp) as ipc:
+ ipc.action("spawn", {"argv": [sys.executable, str(probe), str(received)]})
+ wait_for(received.exists, "persisted app environment")
+ assert json.loads(received.read_text())["QT_QPA_PLATFORMTHEME"] == "qt5ct"
+ finally:
+ stop_process(process)
+ log.close()
+ print("PASS: app colors buttons, GTK/Qt palettes, preservation, failures and launch environment")
+
+
if __name__ == "__main__":
- test_appearance_settings()
- print("PASS: appearance settings (chrome opacity, inactive opacity, animations controls, bundled themes)")
+ if "--app-colors-only" not in sys.argv:
+ test_appearance_settings()
+ print("PASS: appearance settings (chrome opacity, inactive opacity, animations controls, bundled themes)")
+ test_app_colors()
diff --git a/tests/files_controls.py b/tests/files_controls.py
index f6557b9..4682441 100644
--- a/tests/files_controls.py
+++ b/tests/files_controls.py
@@ -185,6 +185,10 @@ def run():
with zipfile.ZipFile(archive, "w") as z:
z.writestr("/", "")
z.writestr("nested/item.txt", "archive member")
+ link = zipfile.ZipInfo("nested/link.txt")
+ link.create_system = 3
+ link.external_attr = 0o120777 << 16
+ z.writestr(link, "../nested/item.txt")
key(38, ctrl=True)
text(str(archive_dir))
key(28)
@@ -209,7 +213,10 @@ def run():
key(28)
wait_for(lambda: (archive_dir / "nested/item.txt").exists(), "Extract in place failed")
assert (archive_dir / "nested/item.txt").read_text() == "archive member"
- print("PASS: ZIP root entry browsing, member opening and extraction")
+ wait_for(lambda: (archive_dir / "nested/link.txt").is_symlink(), "Archive link was not extracted")
+ assert os.readlink(archive_dir / "nested/link.txt") == "../nested/item.txt"
+ assert (archive_dir / "nested/link.txt").read_text() == "archive member"
+ print("PASS: ZIP root entry browsing, member opening and extraction with relative symlinks")
return
# Both common evdev side-button pairs navigate on press only.
diff --git a/tests/xdg_output.py b/tests/xdg_output.py
index f034ad2..ff035df 100644
--- a/tests/xdg_output.py
+++ b/tests/xdg_output.py
@@ -81,14 +81,21 @@ def run_case(binary, scale, count, placements="", xwayland=False):
owned_display = ipc.get_runtime()["xwayland_display"]
assert owned_display
# This display belongs to this test compositor. Never use host DISPLAY.
- result = subprocess.run(["xrandr", "-display", owned_display, "--query"],
- env=dict(env, DISPLAY=owned_display),
- capture_output=True, text=True, timeout=15)
- assert result.returncode == 0, result.stderr
- rectangles = [tuple(map(int, m)) for m in re.findall(
- r" connected[^\n]*? (\d+)x(\d+)\+(-?\d+)\+(-?\d+)", result.stdout)]
- wanted = sorted((o["logical_width"], o["logical_height"], o["x"], o["y"]) for o in expected)
- assert sorted(rectangles) == wanted, result.stdout
+ ox, oy = min(o["x"] for o in expected), min(o["y"] for o in expected)
+ wanted = sorted((o["logical_width"], o["logical_height"], o["x"] - ox, o["y"] - oy) for o in expected)
+
+ def reset_randr_geometry():
+ result = subprocess.run(["xrandr", "-display", owned_display, "--query"],
+ env=dict(env, DISPLAY=owned_display),
+ capture_output=True, text=True, timeout=15)
+ assert result.returncode == 0, result.stderr
+ rectangles = [tuple(map(int, m)) for m in re.findall(
+ r" connected[^\n]*? (\d+)x(\d+)\+(-?\d+)\+(-?\d+)", result.stdout)]
+ return sorted(rectangles) == wanted
+
+ # Reset animates the camera. X11's root covers its world
+ # viewport and returns to physical geometry when it settles.
+ wait_for(reset_randr_geometry, "Xwayland RandR did not settle after camera reset")
print("xdg-output: Xwayland RandR reports the real side-by-side monitor layout")
with (tmp / "live-client.log").open("w") as client_log:
diff --git a/tests/xwayland.py b/tests/xwayland.py
index 079bb1a..912e7d7 100644
--- a/tests/xwayland.py
+++ b/tests/xwayland.py
@@ -1324,7 +1324,7 @@ def test_gtk_combo_and_tooltip():
log.close()
-def test_gtk_menu_alignment_zoomed():
+def test_gtk_menu_alignment_zoomed(pan_x=20, pan_y=15, factor=0, zoom=70):
"""Same real-GTK-menu alignment check as test_gtk_menu_alignment, but
under camera zoom and pan. xwayland_unmanaged.zig's own comment claims
the popup is "positioned in world coordinates ... so camera pan/zoom
@@ -1341,7 +1341,7 @@ def test_gtk_menu_alignment_zoomed():
"""
with tempfile.TemporaryDirectory(prefix="rediwm-xwayland-gtk-zoom-") as directory:
tmp = Path(directory)
- compositor, log = start_compositor(tmp, "[compositor]\nxwayland = true\n")
+ compositor, log = start_compositor(tmp, f"[compositor]\nxwayland = true\nxwayland_scale = {factor}\ncanvas_columns = 5\ncanvas_rows = 5\n")
client = None
try:
sock, reader = ipc_connect(tmp)
@@ -1401,12 +1401,12 @@ def test_gtk_menu_alignment_zoomed():
request(sock, reader, {'version': 1, 'command': 'pointer_button', 'params': {"button": 273, "pressed": True}})
request(sock, reader, {'version': 1, 'command': 'pointer_button', 'params': {"button": 273, "pressed": False}})
- request(sock, reader, {"version": 1, "command": 'move_window_to', "params": {"id": wid, "x": 300, "y": 200}})
- wait_for(lambda: abs(client_box()["x"] - 300) < 4, "window did not move")
+ request(sock, reader, {"version": 1, "command": 'move_window_to', "params": {"id": wid, "x": pan_x + 280, "y": pan_y + 185}})
+ wait_for(lambda: abs(client_box()["x"] - (pan_x + 280)) < 4, "window did not move")
- request(sock, reader, {'version': 1, 'command': 'set_zoom', 'params': {"percent": 70}})
- request(sock, reader, {'version': 1, 'command': 'set_camera', 'params': {"x": 20, "y": 15}})
- wait_for(lambda: camera()["zoom_percent"] == 70 and camera()["x"] == 20, "zoom/pan did not apply")
+ request(sock, reader, {'version': 1, 'command': 'set_zoom', 'params': {"percent": zoom}})
+ request(sock, reader, {'version': 1, 'command': 'set_camera', 'params': {"x": pan_x, "y": pan_y}})
+ wait_for(lambda: camera()["zoom_percent"] == zoom and camera()["x"] == pan_x, "zoom/pan did not apply")
# GetCamera reflects the new state immediately, but a click
# fired in the same instant can still race the projection
# pipeline settling onto it (confirmed empirically: ~20%
@@ -1416,7 +1416,7 @@ def test_gtk_menu_alignment_zoomed():
time.sleep(0.15)
box = client_box()
- assert box["x"] == 301, f"MoveWindowTo/client_box drifted with the camera: {box}"
+ assert box["x"] == pan_x + 281, f"MoveWindowTo/client_box drifted with the camera: {box}"
wx, wy = box["x"] + 60, box["y"] + 60
sx, sy = world_to_screen(wx, wy)
right_click_screen(sx, sy)
@@ -1424,11 +1424,28 @@ def test_gtk_menu_alignment_zoomed():
hx, hy = world_to_screen(wx + 5, wy + 5)
wait_for(
lambda: hit_type(round(hx), round(hy)) == "xwayland_unmanaged",
- "context menu not aligned under 70% zoom + (20,15) pan",
+ f"context menu not aligned at {zoom}% zoom, pan=({pan_x},{pan_y})",
timeout=5,
)
- print("PASS: GTK context menu aligned under 70% zoom + (20,15) pan")
+ print(f"PASS: GTK receives clicks and aligns menus at {zoom}% zoom, pan=({pan_x},{pan_y}), factor={factor}")
+ # Rebase an already mapped override-redirect popup too. Its
+ # visible position and X11 input target must stay together.
+ request(sock, reader, {'version': 1, 'command': 'set_camera', 'params': {"x": pan_x - 20, "y": pan_y + 10}})
+ time.sleep(0.15)
+ hx, hy = world_to_screen(wx + 5, wy + 5)
+ assert hit_type(round(hx), round(hy)) == "xwayland_unmanaged", "mapped popup moved in world coordinates during pan"
+ sx, sy = world_to_screen(wx + 15, wy + 15)
+ request(sock, reader, {"version": 1, "command": "move_cursor", "params": {"x": round(sx), "y": round(sy)}})
+ for pressed in (True, False):
+ request(sock, reader, {"version": 1, "command": "pointer_button", "params": {"button": 272, "pressed": pressed}})
+ wait_for(lambda: "activated One" in client_log.read_text().splitlines(),
+ lambda: f"mapped menu lost clicks after panning: {client_log.read_text()}", timeout=3)
+ print("PASS: an open GTK menu remains clickable after panning")
+
+ sx, sy = world_to_screen(wx + 2, wy + 2)
+ right_click_screen(sx, sy)
+ wait_for(lambda: hit_type(round(hx), round(hy)) == "xwayland_unmanaged", "menu did not reopen")
request(sock, reader, {'version': 1, 'command': 'key_press', 'params': {"key": "Escape"}})
wait_for(
lambda: hit_type(round(hx), round(hy)) != "xwayland_unmanaged",
@@ -1542,16 +1559,12 @@ def test_gtk_menu_multi_output():
log.close()
-def test_negative_output_origin():
- """Compositor-side placement and hit-testing on a configured negative origin.
-
- xdg_output.py separately verifies native clients receive negative logical
- positions. This test does not verify X11 pointer delivery at negative origins.
- """
+def test_negative_output_origin(factor=1):
+ """Placement, hit-testing and actual X11 clicks at a negative origin."""
with tempfile.TemporaryDirectory(prefix="rediwm-xwayland-negorigin-") as directory:
tmp = Path(directory)
config = (
- "[compositor]\nxwayland = true\n"
+ f"[compositor]\nxwayland = true\nxwayland_scale = {factor}\n"
"\n[[outputs]]\nname = \"HEADLESS-1\"\nx = 0\ny = 0\n"
"\n[[outputs]]\nname = \"HEADLESS-2\"\nx = -1280\ny = 0\n"
)
@@ -1622,10 +1635,22 @@ def test_negative_output_origin():
"x": box["x"] + 60 - neg["x"], "y": box["y"] + 60 - neg["y"], "output": neg["name"],
}})["HitTest"]
assert hit["target_type"] == "window" and hit["window_id"] == wid, hit
- assert hit["local_x"] == 60 and hit["local_y"] == 60, hit
+ assert abs(hit["local_x"] - 60 * factor) < 1 and abs(hit["local_y"] - 60 * factor) < 1, hit
assert hit["layout_x"] < 0, hit
print("PASS: scene hit-testing at negative layout coordinates resolves to the right window")
+ time.sleep(0.2) # Let projection settle before delivering input.
+ request(sock, reader, {"version": 1, "command": "move_cursor", "params": {
+ "x": box["x"] + 60 - neg["x"], "y": box["y"] + 60 - neg["y"], "output": neg["name"],
+ }})
+ for pressed in (True, False):
+ request(sock, reader, {"version": 1, "command": "pointer_button", "params": {
+ "button": 273, "pressed": pressed,
+ }})
+ wait_for(lambda: "popup" in client_log.read_text().splitlines(),
+ lambda: f"X11 click at negative origin was lost: {client_log.read_text()}", timeout=3)
+ print(f"PASS: GTK receives a click at negative output origin (factor={factor})")
+
client.stdin.write("quit\n")
client.stdin.flush()
finally:
@@ -2336,8 +2361,12 @@ def run():
test_withdrawn_window_survives_close_animation()
test_gtk_menu_alignment()
test_gtk_menu_alignment_zoomed()
+ test_gtk_menu_alignment_zoomed(-1280, -720, 1.5)
+ test_gtk_menu_alignment_zoomed(-1706, 0, 1.5, zoom=100)
+ test_gtk_menu_alignment_zoomed(1920, 1080)
test_gtk_menu_multi_output()
test_negative_output_origin()
+ test_negative_output_origin(1.5)
test_gtk_menu_fractional_scale()
test_gtk_menu_fractional_scale("2")
test_gtk_transient_dialog()
diff --git a/tests/xwayland_gtk_client.py b/tests/xwayland_gtk_client.py
index e5828b7..149584a 100644
--- a/tests/xwayland_gtk_client.py
+++ b/tests/xwayland_gtk_client.py
@@ -32,6 +32,7 @@ def build_menu():
m = Gtk.Menu()
for label in ("One", "Two", "Three"):
item = Gtk.MenuItem(label=label)
+ item.connect("activate", lambda _item, name=label: emit(f"activated {name}"))
item.show()
m.append(item)
m.attach_to_widget(window, None)