Skip to content

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

Follow RediWM application colors in GTK and Qt apps

oxydizer160a8bbb59d7
diff --git a/TESTING.md b/TESTING.md
index 3bf0250..0ed09c8 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -32,6 +32,14 @@ wayland-protocols and GLES2; D-Bus suites also need PyGObject,
App checks include [calculator](tests/calculator.py), [editor](tests/editor.py)
and [editor visuals](tests/editor_visuals.py).
+Application colors: `python3 tests/app_colors.py` checks snapshot exports and
+opt-in following with a private bus, scratch HOME/XDG directories, and real
+GTK3/GTK4/Qt5/Qt6 palette probes when installed. It keeps clients open across
+theme changes, closes Settings, checks portal publication and compositor restart,
+and verifies that disabling following stops exports. Repeat with
+`REDIWM_TEST_SCALE=1.5`. Browser chrome still needs a visual check with isolated
+profiles in GTK/System/Linux theme mode; never use the host browser profile.
+
SSH keys: `zig build test-keys` and
`dbus-run-session -- python3 tests/keys_settings.py` (repeat with
`REDIWM_TEST_SCALE=1.5`). Fixtures generate OpenSSH and legacy RSA keys in a
diff --git a/build.zig b/build.zig
index 9ae67d0..ed3b93f 100644
--- a/build.zig
+++ b/build.zig
@@ -9,6 +9,7 @@ const Context = @import("build/context.zig").Context;
const protocols = @import("build/protocols.zig");
const apps = @import("build/apps.zig");
const player_build = @import("build/player.zig");
+const qt_style = @import("build/qt_style.zig");
const data = @import("build/data.zig");
const session_build = @import("build/session.zig");
const tests = @import("build/tests.zig");
@@ -249,6 +250,7 @@ pub fn build(b: *std.Build) void {
};
const app = apps.add(ctx);
player_build.add(ctx);
+ qt_style.add(ctx);
const files = app.files;
const images = app.images;
const monitor = app.monitor;
diff --git a/build/qt_style.zig b/build/qt_style.zig
new file mode 100644
index 0000000..b5a2ecf
--- /dev/null
+++ b/build/qt_style.zig
@@ -0,0 +1,47 @@
+//! The RediWM Qt style (src/qt_style/): Fusion with neutral title bars. One
+//! plugin per Qt major, built with the system C++ compiler and moc so it
+//! matches the distro's Qt ABI, wherever that Qt's development files exist.
+//! Installed as lib/rediwm/qt<N>/styles/; the compositor finds it beside its
+//! own executable (src/config_runtime/app_theme.zig `findQtStyles`).
+const std = @import("std");
+const Context = @import("context.zig").Context;
+
+const Qt = struct { major: u8, widgets: []const u8, moc: []const u8 };
+const versions = [_]Qt{
+ .{ .major = 5, .widgets = "Qt5Widgets", .moc = "\"$(pkg-config --variable=host_bins Qt5Core)/moc\"" },
+ .{ .major = 6, .widgets = "Qt6Widgets", .moc = "\"$(pkg-config --variable=libexecdir Qt6Core)/moc\"" },
+};
+
+pub fn add(ctx: Context) void {
+ const b = ctx.b;
+ const wanted = b.option(bool, "qt-style", "Build the RediWM Qt style for each Qt with development files (default: when found)");
+ if (wanted == false) return;
+ // The system compiler and Qt are the host's; cross builds skip the style.
+ if (!ctx.target.query.isNative()) return;
+ var built = false;
+ for (versions) |qt| {
+ if (!present(b, qt)) continue;
+ built = true;
+ const script = b.fmt(
+ \\set -e
+ \\tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
+ \\{s} $(pkg-config --cflags-only-I {s}) -o "$tmp/rediwm_style.moc" "$1"
+ \\exec c++ -std=c++17 -shared -fPIC -Wall -Wextra -Werror -fstack-protector-strong {s} -I"$tmp" \
+ \\ $(pkg-config --cflags {s}) "$1" -o "$2" -Wl,--as-needed $(pkg-config --libs {s})
+ , .{ qt.moc, qt.widgets, if (ctx.optimize == .debug) "-O0 -g" else "-O2 -g -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3", qt.widgets, qt.widgets });
+ const run = b.addSystemCommand(&.{ "sh", "-c", script, b.fmt("build-qt{d}-style", .{qt.major}) });
+ run.addFileArg(b.path("src/qt_style/rediwm_style.cpp"));
+ run.addFileInput(b.path("src/qt_style/rediwm_style.json"));
+ const plugin = run.addOutputFileArg("librediwm-style.so");
+ const install = b.addInstallFileWithDir(plugin, .lib, b.fmt("rediwm/qt{d}/styles/librediwm-style.so", .{qt.major}));
+ b.getInstallStep().dependOn(&install.step);
+ }
+ if (wanted == true and !built) std.debug.panic("-Dqt-style needs Qt5Widgets or Qt6Widgets development files and moc", .{});
+}
+
+fn present(b: *std.Build, qt: Qt) bool {
+ var code: u8 = 0;
+ const probe = b.fmt("pkg-config --exists {s} && test -x {s}", .{ qt.widgets, qt.moc });
+ _ = b.runAllowFail(&.{ "sh", "-c", probe }, &code, .ignore) catch return false;
+ return true;
+}
diff --git a/data/rediwm-portals.conf b/data/rediwm-portals.conf
index 826e0bf..2b1c502 100644
--- a/data/rediwm-portals.conf
+++ b/data/rediwm-portals.conf
@@ -2,6 +2,7 @@
default=gtk
org.freedesktop.impl.portal.ScreenCast=wlr
# The compositor answers color-scheme ([compositor] dark_mode); gtk keeps
-# every other setting. xdg-desktop-portal uses the first backend with a key.
+# every other setting except gtk-theme when application colors follow RediWM.
+# xdg-desktop-portal uses the first backend with a key.
org.freedesktop.impl.portal.Settings=rediwm;gtk
org.freedesktop.impl.portal.FileChooser=rediwm;gtk
diff --git a/docs/wiki/Theme.md b/docs/wiki/Theme.md
index 03e21f8..85a035b 100644
--- a/docs/wiki/Theme.md
+++ b/docs/wiki/Theme.md
@@ -39,10 +39,51 @@ follows it), and default to false.
## GTK and Qt app colors
+**Follow RediWM application colors** (Settings → Appearance) keeps compatible
+applications in sync with the main theme. It is off by default and is saved as
+`[compositor] follow_app_colors = true`. Following continues with Settings closed
+and applies the current palette at login. Turning it off stops future exports
+and leaves the last applied colors in place. The taskbar override is not used.
+
+In **Brave and Chrome**, select **Use GTK** (or **Use Qt**) in the browser's Appearance settings;
+in **Firefox**, enable **System theme — auto**; in **Falkon**, select its native
+**Linux** theme. RediWM uses the standard toolkit settings, so it does not create
+or edit browser profiles or require any of these browsers to be installed.
+Browsers keep their own layout, and some colors may be derived from the palette.
+An application with a custom theme can override the system colors.
+
+GTK following installs two reusable themes, `RediWM-a` and `RediWM-b`, under
+`$XDG_DATA_HOME/themes` (else `~/.local/share/themes`). Changes select the next
+theme only after its files are ready. RediWM updates `gtk-theme-name` in GTK3/4
+`settings.ini`, publishes `org.gnome.desktop.interface` / `gtk-theme` through
+the Settings portal, and uses **gsettings** to notify native Wayland clients.
+The previous GSettings value is kept in
+`$XDG_CONFIG_HOME/rediwm/gtk-theme.gsettings-backup`. The themes' base stylesheet
+is Adwaita light or dark to match the palette, whatever `dark_mode` says.
+GTK3's user `gtk.css` outranks every theme, and other palette generators
+(matugen/DMS, KDE's `colors.css`) define colors there. Following replaces
+RediWM's old snapshot import with a marked block of aliases at the end of that
+file (`@define-color window_bg_color @rediwm_window_bg_color;` …); they win
+over earlier definitions and resolve against whichever `RediWM-*` theme is
+loaded, so running apps still change live. Other user CSS is kept. GTK4's
+`gtk.css` gets no aliases (libadwaita loads no named theme). Restart apps once
+when migrating from a snapshot.
+Without a working GSettings helper/session bus, RediWM exports a snapshot and
+Settings reports that GTK apps need restarting after changes. X11 clients
+without a settings manager and sandboxed apps without access to the generated
+theme may also need additional setup; libadwaita or custom app styles may differ.
+
+Qt following updates whichever of **qt5ct** and **qt6ct** are installed and
+notifies their palette watchers. Missing Qt tools do not prevent GTK following.
+New RediWM launches use the palette plugin; already-running Qt apps may need
+one restart, and apps launched outside RediWM may need a new login. No polling
+or background exporter remains active while the palette is unchanged.
+
**Apply GTK colors** and **Apply Qt colors** (Settings → Appearance, below the
theme selectors) export the main theme's app backgrounds, toolbar, sidebar, text
and shell accent; the taskbar override is not used. Exports are snapshots: apply
-again after changing a theme, then restart the apps.
+again after changing a theme, then restart the apps. These manual buttons are
+shown only while automatic following is off.
**GTK:** written to `gtk-3.0/rediwm-colors.css` and `gtk-4.0/rediwm-colors.css`
under `$XDG_CONFIG_HOME` (else `~/.config`), with a marked import added at the
@@ -52,8 +93,16 @@ common widget overrides, GTK4 also the CSS variables recent libadwaita uses. No
theme package is patched and the dark-mode preference is never flipped.
**Qt:** needs **qt5ct** (Qt 5) or **qt6ct** (Qt 6). The toolkit configs select
-native `colors/rediwm.conf` palettes and the palette-aware Fusion style; other
-preferences are kept. RediWM launches get the platform theme at once; sign in
+native `colors/rediwm.conf` palettes and the **RediWM** style; other
+preferences are kept. The RediWM style is Fusion except that title bars use the
+window colour: Fusion fills an active title bar with the accent, and Chromium's
+Qt mode (Brave, Chrome) samples that title bar as its whole frame. It is built
+per Qt major when that Qt's development files and `moc` are present
+(`-Dqt-style`, default: when found), installed as
+`lib/rediwm/qt<N>/styles/librediwm-style.so`, and found through
+`QT_PLUGIN_PATH`; a Qt major without it gets Fusion. Launches get an empty
+`QT_STYLE_OVERRIDE`, so an inherited override (e.g. kvantum) no longer applies.
+RediWM launches get the platform theme at once; sign in
again for apps activated by D-Bus or launched elsewhere. The opt-in is recorded
in `rediwm/app-colors.conf`. KDE apps such as Dolphin read `kdeglobals`, so the
export also rewrites its `[Colors:*]` groups (Window, View, Button, Selection,
@@ -67,7 +116,10 @@ as `<filename>.rediwm-backup`, and later applications keep that first backup. A
symlinked `gtk.css` or Qt config (e.g. from another theming tool) is replaced by
a regular file with its current contents plus the RediWM block; the target is not
modified. A symlinked config *folder* is refused and reported in Settings. To
-undo GTK, remove the marked import blocks from both `gtk.css` files (or restore
+undo following, turn it off, restore the backed-up GTK `settings.ini` files
+(or remove their `gtk-theme-name` entry if there was no previous file), and
+restore the saved GSettings theme value. The generated themes can then be removed.
+To undo GTK snapshots or following's aliases, remove the marked blocks from both `gtk.css` files (or restore
the backups). To undo Qt, restore the qt5ct/qt6ct and `kdeglobals` backups (or
delete configs the export created if none exists), remove
`rediwm/app-colors.conf`, and sign in again.
diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD
index d7df1a3..4884a67 100644
--- a/packaging/arch/PKGBUILD
+++ b/packaging/arch/PKGBUILD
@@ -39,6 +39,9 @@ makedepends=(
'zig>=0.17.0'
'pkgconf'
'boost'
+ # The RediWM Qt style plugins; Qt apps bring their own Qt at run time.
+ 'qt5-base'
+ 'qt6-base'
)
optdepends=(
'xorg-xwayland: run X11 applications'
@@ -65,7 +68,7 @@ pkgver() {
build() {
cd "$_pkgname"
zig build -Doptimize=ReleaseSafe -j"$(nproc)" \
- -Dinstall-prefix=/usr \
+ -Dinstall-prefix=/usr -Dqt-style=true \
--prefix "$srcdir/rediwm-build-prefix"
}
diff --git a/po/rediwm.pot b/po/rediwm.pot
index 1ba104f..4e341ac 100644
--- a/po/rediwm.pot
+++ b/po/rediwm.pot
@@ -640,6 +640,10 @@ msgstr ""
msgid "Automatic tiling"
msgstr ""
+#: src/control_center/sections/appearance_colors.zig
+msgid "Automatic updates are off. Applications keep the last applied colors."
+msgstr ""
+
#: src/control_center/sections/bluetooth.zig
msgid "Available Devices"
msgstr ""
@@ -1854,6 +1858,10 @@ msgstr ""
msgid "Could not save Places"
msgstr ""
+#: src/control_center/sections/appearance_colors.zig
+msgid "Could not save application color preference: {reason}."
+msgstr ""
+
#: src/control_center/sections/desktop.zig
msgid "Could not save desktop mode."
msgstr ""
@@ -3104,10 +3112,26 @@ msgstr ""
msgid "Folders only"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "Follow RediWM application colors"
+msgstr ""
+
#: src/control_center/sections/power.zig
msgid "Follow lid action"
msgstr ""
+#: src/control_center/sections/appearance_colors.zig
+msgid "Following GTK colors. Install qt5ct or qt6ct to include Qt apps. Choose GTK in Brave or Chrome, or System theme in Firefox; restart apps once if needed."
+msgstr ""
+
+#: src/control_center/sections/appearance_colors.zig
+msgid "Following application colors. GTK live updates are unavailable; restart GTK apps after theme changes. Choose GTK in Brave or Chrome, System theme in Firefox, or Linux in Falkon."
+msgstr ""
+
+#: src/control_center/sections/appearance_colors.zig
+msgid "Following the main theme. Choose GTK in Brave or Chrome, System theme in Firefox, or Linux in Falkon. Restart apps once if needed; apps with their own styles may differ."
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "Font"
msgstr ""
@@ -7979,6 +8003,10 @@ msgstr ""
msgid "brightness plugged battery"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "browser brave chrome firefox falkon gtk qt colours theme sync"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "buttons close maximize minimize"
msgstr ""
diff --git a/src/Server.zig b/src/Server.zig
index 05ae333..ab878d0 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -267,6 +267,7 @@ rfkill_before: ?@import("platform").rfkill.State = null,
bluetooth: ?*@import("bluetooth.zig").Manager = null,
services: ?*services_mod.Manager = null,
qt_app_colors: bool = false,
+app_colors: @import("config_runtime/app_colors.zig").State = .{},
pending_launches: std.ArrayList(*@import("start_menu/launch.zig").Pending) = .empty,
layout_autosave: ?*layout_autosave_mod.Autosave = null,
session: ?*wlr.Session = null,
@@ -398,6 +399,8 @@ pub fn applyChildEnvWithToken(server: *Server, map: *child_env.Map, token: ?[]co
try child_env.apply(map, .{
.qt_app_colors = !server.greeter_mode and server.qt_app_colors,
+ .follow_app_colors = !server.greeter_mode and server.config.compositor.follow_app_colors,
+ .qt_plugin_path = server.app_colors.qt_styles.path,
.region = server.config.region,
.input_method = server.config.input_method.env,
.app_scopes = server.app_scopes != null,
diff --git a/src/child_env.zig b/src/child_env.zig
index 6c42024..a02ec8a 100644
--- a/src/child_env.zig
+++ b/src/child_env.zig
@@ -14,6 +14,9 @@ pub const InputMethod = @import("config").types.InputMethod;
pub const Spec = struct {
qt_app_colors: bool = false,
+ follow_app_colors: bool = false,
+ /// Directories holding the RediWM Qt style, prepended to QT_PLUGIN_PATH.
+ qt_plugin_path: ?[]const u8 = null,
region: @import("config").loader.RegionConfig = .{},
input_method: InputMethod = .none,
/// Resolved by the compositor before private supervisor fields are
@@ -34,12 +37,27 @@ pub const Spec = struct {
cursor_path: ?[]const u8 = null,
};
+fn prependPluginPath(map: *Map, ours: []const u8) !void {
+ const inherited = map.get("QT_PLUGIN_PATH") orelse "";
+ if (std.mem.startsWith(u8, inherited, ours) and (inherited.len == ours.len or inherited[ours.len] == ':')) return;
+ if (inherited.len == 0) return map.put("QT_PLUGIN_PATH", ours);
+ const joined = try std.fmt.allocPrint(map.allocator, "{s}:{s}", .{ ours, inherited });
+ defer map.allocator.free(joined);
+ try map.put("QT_PLUGIN_PATH", joined);
+}
+
pub fn apply(map: *Map, spec: Spec) !void {
try applyRegion(map, spec.region);
+ // A fixed GTK_THEME prevents GtkSettings changes from selecting the next
+ // palette. Following is explicit opt-in; preserve it otherwise.
+ if (spec.follow_app_colors) _ = map.swapRemove("GTK_THEME");
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");
+ // Empty cancels an inherited override (kvantum) without one of our
+ // own, so qt5ct/qt6ct pick the RediWM style or Fusion per Qt major.
+ try map.put("QT_STYLE_OVERRIDE", "");
+ if (spec.qt_plugin_path) |ours| try prependPluginPath(map, ours);
}
// Private supervisor authority must never escape to descendant launches.
inline for (.{ "REDIWM_SESSION_FD", "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY", "REDIWM_LOGIN_STARTED_NS" }) |key| _ = map.swapRemove(key);
@@ -235,16 +253,24 @@ test "private session authority and stale activation tokens never reach children
try std.testing.expectEqualStrings("1", map.get("REDIWM_APP_SCOPES").?);
}
-test "Qt app colors override inherited theming only after explicit opt in" {
+test "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 map.put("GTK_THEME", "Adwaita");
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("Adwaita", map.get("GTK_THEME").?);
+ try map.put("QT_PLUGIN_PATH", "/opt/plugins");
+ try apply(&map, .{ .qt_app_colors = true, .follow_app_colors = true, .qt_plugin_path = "/usr/lib/rediwm/qt6:/usr/lib/rediwm/qt5" });
+ try std.testing.expect(map.get("GTK_THEME") == null);
+ try std.testing.expectEqualStrings("/usr/lib/rediwm/qt6:/usr/lib/rediwm/qt5:/opt/plugins", map.get("QT_PLUGIN_PATH").?);
+ // Reapplying (a restarted compositor inherits its own value) adds nothing.
+ try apply(&map, .{ .qt_app_colors = true, .qt_plugin_path = "/usr/lib/rediwm/qt6:/usr/lib/rediwm/qt5" });
+ try std.testing.expectEqualStrings("/usr/lib/rediwm/qt6:/usr/lib/rediwm/qt5:/opt/plugins", map.get("QT_PLUGIN_PATH").?);
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").?);
+ try std.testing.expectEqualStrings("", map.get("QT_STYLE_OVERRIDE").?);
}
diff --git a/src/config/app_theme.zig b/src/config/app_theme.zig
index f4520ae..db88fdb 100644
--- a/src/config/app_theme.zig
+++ b/src/config/app_theme.zig
@@ -8,8 +8,12 @@ const Allocator = std.mem.Allocator;
const Io = std.Io;
pub const Toolkit = enum { gtk, qt };
-pub const QtSupport = struct { qt5: bool, qt6: bool };
+/// `style5`/`style6`: the RediWM Qt style plugin is installed for that major.
+pub const QtSupport = struct { qt5: bool, qt6: bool, style5: bool = false, style6: bool = false };
pub const qt_platform = "qt5ct"; // qt6ct also advertises this plugin key.
+/// Fusion with neutral title bars (src/qt_style/); Fusion where it is missing.
+pub const qt_style = "RediWM";
+pub const follow = @import("app_theme_follow.zig");
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);
@@ -91,6 +95,11 @@ fn blend(fg: Color, bg: Color, alpha: f32) Color {
return result;
}
+/// Whether the palette needs a dark base stylesheet beneath it.
+pub fn isDark(p: Palette) bool {
+ return contrast(p.bg)[0] == 255;
+}
+
fn contrast(c: Color) Color {
var luminance: f32 = 0;
for (c, [_]f32{ 0.2126, 0.7152, 0.0722 }) |byte, weight| {
@@ -282,6 +291,19 @@ pub fn patchIni(a: Allocator, content: []const u8, section: []const u8, key: []c
const css_begin = "/* BEGIN REDIWM APP COLORS */";
const css_end = "/* END REDIWM APP COLORS */";
pub fn patchCss(a: Allocator, content: []const u8) ![]u8 {
+ return replaceManagedCss(a, content, "@import url(\"rediwm-colors.css\");\n");
+}
+
+/// Later rules and named colors win over other palette generators, so the
+/// block goes last.
+pub fn replaceManagedCss(a: Allocator, content: []const u8, body: []const u8) ![]u8 {
+ const original = try removeManagedCss(a, content);
+ defer a.free(original);
+ return std.fmt.allocPrint(a, "{s}" ++ css_begin ++ "\n{s}" ++ css_end ++ "\n", .{ original, body });
+}
+
+/// Named themes must not compete with a stale, higher-priority snapshot.
+pub fn removeManagedCss(a: Allocator, content: []const u8) ![]u8 {
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(a);
var rest = content;
@@ -294,15 +316,10 @@ pub fn patchCss(a: Allocator, content: []const u8) ![]u8 {
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');
- // The import goes last: GTK keeps the final @define-color and the later of
- // two equal rules, and generators such as matugen/DMS import their own
- // palette into gtk.css. Applying must win over those.
- const result = try std.fmt.allocPrint(a, "{s}" ++ css_begin ++ "\n@import url(\"rediwm-colors.css\");\n" ++ css_end ++ "\n", .{out.items});
- out.deinit(a);
- return result;
+ return out.toOwnedSlice(a);
}
-fn readOptional(a: Allocator, io: Io, path: []const u8) !?[]u8 {
+pub fn readOptional(a: Allocator, io: Io, path: []const u8) !?[]u8 {
// Follows a file symlink: the link target's content is what gets merged.
const stat = Io.Dir.cwd().statFile(io, path, .{}) catch |err| switch (err) {
error.FileNotFound => return null,
@@ -313,12 +330,12 @@ fn readOptional(a: Allocator, io: Io, path: []const u8) !?[]u8 {
}
const Change = struct { path: []const u8, data: []const u8, original: ?[]const u8, link: ?[]const u8, temp: []const u8, permissions: Io.File.Permissions };
-const Transaction = struct {
+pub 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 {
+ pub 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;
@@ -345,7 +362,7 @@ const Transaction = struct {
try self.changes.append(self.a, .{ .path = path, .data = data, .original = original, .link = link, .temp = try std.fmt.allocPrint(self.a, "{s}.rediwm-tmp", .{path}), .permissions = permissions });
}
- fn commit(self: *Transaction) !void {
+ pub 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
@@ -397,6 +414,12 @@ const Transaction = struct {
};
pub fn apply(a: Allocator, io: Io, home: []const u8, toolkit: Toolkit, p: Palette, support: QtSupport) !void {
+ return applyRevision(a, io, home, toolkit, p, support, null);
+}
+
+/// A palette revision in the watched config directory wakes qt5ct/qt6ct even
+/// when only the palette in its colors/ subdirectory changed.
+pub fn applyRevision(a: Allocator, io: Io, home: []const u8, toolkit: Toolkit, p: Palette, support: QtSupport, revision: ?[]const u8) !void {
var arena: std.heap.ArenaAllocator = .init(a);
defer arena.deinit();
const alloc = arena.allocator();
@@ -411,14 +434,15 @@ pub fn apply(a: Allocator, io: Io, home: []const u8, toolkit: Toolkit, p: Palett
.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| {
+ for ([_][]const u8{ "qt5ct", "qt6ct" }, [_]bool{ support.qt5, support.qt6 }, [_]bool{ support.style5, support.style6 }) |version, installed, styled| {
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");
+ content = try patchIni(alloc, content, "Appearance", "style", if (styled) qt_style else "Fusion");
+ if (revision) |value| content = try patchIni(alloc, content, "RediWM", "palette_revision", value);
try tx.add(scheme, colors, false);
try tx.add(config, content, true);
}
diff --git a/src/config/app_theme_follow.zig b/src/config/app_theme_follow.zig
new file mode 100644
index 0000000..6248985
--- /dev/null
+++ b/src/config/app_theme_follow.zig
@@ -0,0 +1,131 @@
+//! Reloadable GTK themes. Two bounded slots give GtkSettings a new name when
+//! colors change; GTK caches user gtk.css for the lifetime of an application.
+const std = @import("std");
+const app = @import("app_theme.zig");
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+
+pub const names = [_][]const u8{ "RediWM-a", "RediWM-b" };
+
+pub fn name(slot: u1) []const u8 {
+ return names[slot];
+}
+
+pub fn dataHome(a: Allocator, env: std.process.Environ) ![]u8 {
+ if (env.getPosix("XDG_DATA_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, ".local/share" });
+}
+
+pub fn current(a: Allocator, io: Io, home: []const u8) !?u1 {
+ const path = try std.fs.path.join(a, &.{ home, "gtk-3.0/settings.ini" });
+ defer a.free(path);
+ const bytes = try app.readOptional(a, io, path) orelse return null;
+ defer a.free(bytes);
+ const selected = app.iniValue(bytes, "Settings", "gtk-theme-name") orelse return null;
+ for (names, 0..) |value, slot| if (std.mem.eql(u8, selected, value)) return @intCast(slot);
+ return null;
+}
+
+pub fn css(a: Allocator, p: app.Palette, gtk4: bool) ![]u8 {
+ const colors = try app.gtkColors(a, p, gtk4);
+ defer a.free(colors);
+ const private = if (gtk4) try a.dupe(u8, "") else try privateColors(a, colors);
+ defer a.free(private);
+ // The base follows the palette, not dark_mode: a dark palette over light
+ // Adwaita leaves every widget the overrides miss light.
+ const dark = app.isDark(p);
+ const base = if (gtk4)
+ (if (dark) "Default/Default-dark.css" else "Default/Default-light.css")
+ else
+ (if (dark) "Adwaita/gtk-contained-dark.css" else "Adwaita/gtk-contained.css");
+ return std.fmt.allocPrint(a, "@import url(\"resource:///org/gtk/libgtk/theme/{s}\");\n{s}{s}\n" ++
+ // Chromium samples the window as its toolbar and a headerbar as
+ // its frame. Keep the address field separate from that toolbar.
+ "window.background.chromium {{ background-color: @headerbar_bg_color; color: @window_fg_color; }}\n" ++
+ "window.background.chromium label {{ color: @window_fg_color; }}\n" ++
+ "window.background.chromium entry {{ background-color: @view_bg_color; color: @view_fg_color; }}\n", .{ base, colors, private });
+}
+
+const define = "@define-color ";
+
+/// Each named color again as `rediwm_<name>`, which only the slots define.
+fn privateColors(a: Allocator, colors: []const u8) ![]u8 {
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ var lines = std.mem.splitScalar(u8, colors, '\n');
+ while (lines.next()) |line| {
+ if (!std.mem.startsWith(u8, line, define)) continue;
+ try out.appendSlice(a, define ++ "rediwm_");
+ try out.appendSlice(a, line[define.len..]);
+ try out.append(a, '\n');
+ }
+ return out.toOwnedSlice(a);
+}
+
+/// GTK3 user CSS outranks every theme, and generators (matugen/DMS, KDE's
+/// colors.css) define the standard names there. Aliases appended last win
+/// over those, and GTK resolves them at style time against the loaded slot,
+/// so running apps still follow a slot switch although user CSS is cached.
+/// GTK4 gets none: libadwaita loads no slot, leaving the aliases unresolved.
+pub fn userAliases(a: Allocator, p: app.Palette) ![]u8 {
+ const colors = try app.gtkColors(a, p, false);
+ defer a.free(colors);
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ var lines = std.mem.splitScalar(u8, colors, '\n');
+ while (lines.next()) |line| {
+ if (!std.mem.startsWith(u8, line, define)) continue;
+ const color = line[define.len..][0 .. std.mem.indexOfScalar(u8, line[define.len..], ' ') orelse continue];
+ try out.appendSlice(a, define);
+ try out.appendSlice(a, color);
+ try out.appendSlice(a, " @rediwm_");
+ try out.appendSlice(a, color);
+ try out.appendSlice(a, ";\n");
+ }
+ return out.toOwnedSlice(a);
+}
+
+/// Writes all files before any settings-change notification may be sent. User
+/// CSS and settings are retained; RediWM's snapshot import is removed, and
+/// GTK3's gtk.css gains `userAliases` in its place.
+pub fn apply(a: Allocator, io: Io, home: []const u8, data: []const u8, p: app.Palette) !u1 {
+ var arena: std.heap.ArenaAllocator = .init(a);
+ defer arena.deinit();
+ const mem = arena.allocator();
+ const styles = [_][]const u8{ try css(mem, p, false), try css(mem, p, true) };
+ const aliases = try userAliases(mem, p);
+ const previous = try current(mem, io, home);
+ var slot: u1 = if (previous) |old| old ^ 1 else 0;
+ if (previous) |old| {
+ var same = true;
+ for ([_][]const u8{ "gtk-3.0", "gtk-4.0" }, styles) |version, style| {
+ const path = try std.fs.path.join(mem, &.{ data, "themes", name(old), version, "gtk.css" });
+ const saved = try app.readOptional(mem, io, path) orelse "";
+ same = same and std.mem.eql(u8, saved, style);
+ }
+ if (same) slot = old;
+ }
+ var tx = app.Transaction{ .a = mem, .io = io };
+ for ([_][]const u8{ "gtk-3.0", "gtk-4.0" }, styles) |version, style| {
+ const path = try std.fs.path.join(mem, &.{ data, "themes", name(slot), version, "gtk.css" });
+ try tx.add(path, style, false);
+ // Supply either requested variant from the same resolved palette.
+ const dark_path = try std.fs.path.join(mem, &.{ data, "themes", name(slot), version, "gtk-dark.css" });
+ try tx.add(dark_path, style, false);
+ const settings_path = try std.fs.path.join(mem, &.{ home, version, "settings.ini" });
+ const settings = try app.readOptional(mem, io, settings_path) orelse "";
+ try tx.add(settings_path, try app.patchIni(mem, settings, "Settings", "gtk-theme-name", name(slot)), true);
+ const user_path = try std.fs.path.join(mem, &.{ home, version, "gtk.css" });
+ if (try app.readOptional(mem, io, user_path)) |user| {
+ const patched = if (std.mem.eql(u8, version, "gtk-3.0"))
+ try app.replaceManagedCss(mem, user, aliases)
+ else
+ try app.removeManagedCss(mem, user);
+ try tx.add(user_path, patched, true);
+ }
+ }
+ try tx.commit();
+ return slot;
+}
diff --git a/src/config/default.zig b/src/config/default.zig
index 3b323d9..2a888de 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -190,6 +190,7 @@ pub const source =
\\xwayland_native_scaling = false # sharp X11 apps on fractional scales (requires restart)
\\xwayland_scale = 0 # global render factor: 0 = automatic, 1.0-4.0 = explicit (requires restart)
\\dark_mode = false # apps and web pages prefer dark (live; via the Settings portal)
+ \\follow_app_colors = false # keep GTK/Qt application colors in sync with the main theme
\\placeholder_delay_ms = 0 # show splash only if app hasn't appeared after N ms (0 disables)
\\# wallpaper = "" # empty = RediWM's; a file in ~/.local/share/rediwm/wallpapers, or a path
\\lid_close = "display_off" # closing the laptop lid: display_off (built-in screen off while another display is on), lock, suspend, ignore
diff --git a/src/config/loader.zig b/src/config/loader.zig
index 4006004..f46d42e 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -265,6 +265,8 @@ pub const CompositorConfig = struct {
/// Colour scheme apps are told to prefer through the Settings portal
/// (`session/settings_portal.zig`): dark when true, light when false.
dark_mode: bool = false,
+ /// Export the main palette to installed GTK/Qt integrations on theme changes.
+ follow_app_colors: bool = false,
/// Delay before showing a placeholder frame for an unmapped launch (ms).
/// 0 disables the placeholder frame.
placeholder_delay_ms: u32 = 0,
diff --git a/src/config/loader_fields.zig b/src/config/loader_fields.zig
index 6565a23..12bfc88 100644
--- a/src/config/loader_fields.zig
+++ b/src/config/loader_fields.zig
@@ -165,6 +165,7 @@ pub const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(Composi
.xwayland_native_scaling = .boolean,
.xwayland_scale = .{ .float = .{ .min = 0, .max = 4 } },
.dark_mode = .boolean,
+ .follow_app_colors = .boolean,
.placeholder_delay_ms = .{ .uint = .{ .min = 0, .max = 10_000 } },
.wallpaper = .string,
.sound_theme = .string,
diff --git a/src/config_runtime/app_colors.zig b/src/config_runtime/app_colors.zig
new file mode 100644
index 0000000..f541a7b
--- /dev/null
+++ b/src/config_runtime/app_colors.zig
@@ -0,0 +1,105 @@
+//! One compositor-owned exporter for manual snapshots and automatic following.
+//! A burst of edits retains only the latest palette; closing Settings never
+//! cancels synchronization. An unchanged palette performs no filesystem work.
+const std = @import("std");
+const Server = @import("../Server.zig");
+const wl = @import("wayland").server.wl;
+const app = @import("config").app_theme;
+const worker = @import("app_theme.zig");
+const theme = @import("ui").theme;
+
+pub const State = struct {
+ job: ?*worker.Job = null,
+ source: ?*wl.EventSource = null,
+ pending: bool = false,
+ action: ?worker.Action = null,
+ result: ?worker.Result = null,
+ failure: ?anyerror = null,
+ palette: ?app.Palette = null,
+ gtk_slot: ?u1 = null,
+ qt_styles: worker.QtStyles = .{},
+
+ pub fn deinit(self: *State) void {
+ if (self.source) |source| source.remove();
+ if (self.job) |job| job.deinit();
+ self.qt_styles.deinit();
+ self.* = .{};
+ }
+};
+
+pub fn gtkTheme(server: *Server) ?[]const u8 {
+ if (server.greeter_mode or !server.config.compositor.follow_app_colors) return null;
+ return if (server.app_colors.gtk_slot) |slot| app.follow.name(slot) else null;
+}
+
+pub fn sync(server: *Server) void {
+ const state = &server.app_colors;
+ if (server.greeter_mode or !server.config.compositor.follow_app_colors) {
+ state.pending = false;
+ state.palette = null;
+ return;
+ }
+ if (state.job != null) {
+ state.pending = true;
+ return;
+ }
+ const palette = app.Palette.fromTheme(theme.global);
+ if (state.palette) |last| {
+ if (state.failure == null and std.meta.eql(last, palette)) return;
+ }
+ start(server, .follow) catch |err| fail(server, err);
+}
+
+pub fn start(server: *Server, action: worker.Action) !void {
+ if (server.greeter_mode) return error.GreeterMode;
+ const state = &server.app_colors;
+ if (state.job != null) return error.AppColorsBusy;
+ const job = try worker.Job.create(server.io, server.environ, action, app.Palette.fromTheme(theme.global), .{ state.qt_styles.qt5, state.qt_styles.qt6 });
+ errdefer job.deinit();
+ const source = try server.wl_server.getEventLoop().addFd(*Server, job.fd, .{ .readable = true }, ready, server);
+ errdefer source.remove();
+ try job.start();
+ state.job = job;
+ state.source = source;
+ state.action = action;
+ state.failure = null;
+ state.result = null;
+ refresh(server);
+}
+
+pub fn fail(server: *Server, err: anyerror) void {
+ server.app_colors.failure = err;
+ std.log.warn("app colors export failed: {}", .{err});
+ refresh(server);
+}
+
+fn refresh(server: *Server) void {
+ if (server.input.open_control_center) |cc| {
+ if (cc.showingPage(.appearance)) cc.refresh();
+ }
+}
+
+fn ready(_: c_int, _: wl.EventMask, server: *Server) c_int {
+ const state = &server.app_colors;
+ const job = state.job orelse return 0;
+ state.source.?.remove();
+ state.source = null;
+ state.job = null;
+ job.join();
+ defer job.deinit();
+ if (job.result) |result| {
+ state.result = result;
+ if (result.qt_error == null and (result.support.qt5 or result.support.qt6)) server.qt_app_colors = true;
+ if (result.gtk_slot) |slot| {
+ const changed = state.gtk_slot == null or state.gtk_slot.? != slot;
+ state.gtk_slot = slot;
+ state.palette = job.palette;
+ if (changed) @import("../session/settings_portal.zig").emitGtkTheme(server);
+ } else state.palette = null;
+ } else |err| fail(server, err);
+ const pending = state.pending;
+ state.pending = false;
+ if (pending) sync(server);
+ refresh(server);
+ return 0;
+}
diff --git a/src/config_runtime/app_theme.zig b/src/config_runtime/app_theme.zig
index 996d90c..5b54816 100644
--- a/src/config_runtime/app_theme.zig
+++ b/src/config_runtime/app_theme.zig
@@ -1,25 +1,70 @@
-//! Filesystem work runs only on an explicit Settings action. One eventfd
-//! wakes the compositor when the export finishes; there are no idle timers.
+//! A bounded background export. The compositor-owned manager serializes jobs;
+//! no toolkit work runs on the event loop and there are no idle timers.
const std = @import("std");
const platform = @import("platform");
const config = @import("config").app_theme;
const c = std.posix.system;
const a = std.heap.c_allocator;
+pub const Action = enum { gtk, qt, follow };
+pub const Result = struct {
+ support: config.QtSupport = .{ .qt5 = false, .qt6 = false },
+ gtk_slot: ?u1 = null,
+ gtk_notified: bool = false,
+ qt_error: ?anyerror = null,
+};
+
+/// RediWM Qt style plugins installed beside this executable
+/// (`<bin>/../lib/rediwm/qt<N>/styles`, see build/qt_style.zig).
+pub const QtStyles = struct {
+ /// `QT_PLUGIN_PATH` entries for the installed majors, or null for none.
+ path: ?[]u8 = null,
+ qt5: bool = false,
+ qt6: bool = false,
+
+ pub fn deinit(self: *QtStyles) void {
+ if (self.path) |path| a.free(path);
+ self.* = .{};
+ }
+};
+
+pub fn findQtStyles(io: std.Io) QtStyles {
+ const bin = std.process.executableDirPathAlloc(io, a) catch return .{};
+ defer a.free(bin);
+ var result: QtStyles = .{};
+ var path: std.ArrayList(u8) = .empty;
+ defer path.deinit(a);
+ for ([_]u8{ 6, 5 }) |major| {
+ const dir = std.fmt.allocPrint(a, "{s}/../lib/rediwm/qt{d}", .{ bin, major }) catch return .{};
+ defer a.free(dir);
+ const plugin = std.fmt.allocPrint(a, "{s}/styles/librediwm-style.so", .{dir}) catch return .{};
+ defer a.free(plugin);
+ std.Io.Dir.cwd().access(io, plugin, .{}) catch continue;
+ const resolved = std.fs.path.resolve(a, &.{dir}) catch return .{};
+ defer a.free(resolved);
+ if (path.items.len > 0) path.append(a, ':') catch return .{};
+ path.appendSlice(a, resolved) catch return .{};
+ if (major == 5) result.qt5 = true else result.qt6 = true;
+ }
+ if (path.items.len > 0) result.path = path.toOwnedSlice(a) catch return .{};
+ return result;
+}
+
pub const Job = struct {
io: std.Io,
env: std.process.Environ,
- toolkit: config.Toolkit,
+ action: Action,
palette: config.Palette,
+ styles: [2]bool,
fd: c_int,
thread: ?std.Thread = null,
- result: anyerror!config.QtSupport = error.NotFinished,
+ result: anyerror!Result = error.NotFinished,
- pub fn create(io: std.Io, env: std.process.Environ, toolkit: config.Toolkit, palette: config.Palette) !*Job {
+ pub fn create(io: std.Io, env: std.process.Environ, action: Action, palette: config.Palette, styles: [2]bool) !*Job {
const self = try a.create(Job);
errdefer a.destroy(self);
const fd = platform.wake.create() orelse return error.EventFdFailed;
- self.* = .{ .io = io, .env = env, .toolkit = toolkit, .palette = palette, .fd = fd };
+ self.* = .{ .io = io, .env = env, .action = action, .palette = palette, .styles = styles, .fd = fd };
return self;
}
@@ -44,18 +89,38 @@ pub const Job = struct {
_ = c.write(self.fd, std.mem.asBytes(&value), @sizeOf(u64));
}
- fn apply(self: *Job) !config.QtSupport {
+ fn apply(self: *Job) !Result {
const home = try config.configHome(a, self.env);
defer a.free(home);
var support = config.QtSupport{ .qt5 = false, .qt6 = false };
- if (self.toolkit == .qt) {
+ if (self.action != .gtk) {
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 };
+ support = .{ .qt5 = qt5 != null, .qt6 = qt6 != null, .style5 = self.styles[0], .style6 = self.styles[1] };
+ }
+ if (self.action != .follow) {
+ try config.apply(a, self.io, home, if (self.action == .gtk) .gtk else .qt, self.palette, support);
+ return .{ .support = support };
+ }
+ const data = try config.follow.dataHome(a, self.env);
+ defer a.free(data);
+ const slot = try config.follow.apply(a, self.io, home, data, self.palette);
+ var result = Result{ .support = support, .gtk_slot = slot };
+ if (support.qt5 or support.qt6) {
+ var buf: [16]u8 = undefined;
+ const revision = std.fmt.bufPrint(&buf, "{x:0>16}", .{std.hash.Wyhash.hash(0, std.mem.asBytes(&self.palette))}) catch unreachable;
+ config.applyRevision(a, self.io, home, .qt, self.palette, support, revision) catch |err| {
+ result.qt_error = err;
+ };
+ }
+ result.gtk_notified = @import("app_theme_notify.zig").gtk(self.io, self.env, home, config.follow.name(slot)) catch false;
+ if (!result.gtk_notified) {
+ // Without a working settings transport, the user stylesheet is
+ // the reliable startup fallback even when GSettings overrides ini.
+ try config.apply(a, self.io, home, .gtk, self.palette, support);
}
- try config.apply(a, self.io, home, self.toolkit, self.palette, support);
- return support;
+ return result;
}
};
diff --git a/src/config_runtime/app_theme_notify.zig b/src/config_runtime/app_theme_notify.zig
new file mode 100644
index 0000000..9a3d47e
--- /dev/null
+++ b/src/config_runtime/app_theme_notify.zig
@@ -0,0 +1,45 @@
+//! GTK's Wayland backend reads GSettings outside sandboxes. Portal clients
+//! receive a Settings signal separately, after the worker completes.
+const std = @import("std");
+const app = @import("config").app_theme;
+const a = std.heap.c_allocator;
+
+pub fn gtk(io: std.Io, env: std.process.Environ, home: []const u8, name: []const u8) !bool {
+ // A private/headless environment without a bus must not activate the host
+ // user's dconf service. settings.ini still provides the startup fallback.
+ const bus: []const u8 = env.getPosix("DBUS_SESSION_BUS_ADDRESS") orelse "";
+ if (bus.len == 0) return false;
+ const helper = try app.executable(a, io, env, "gsettings") orelse return false;
+ defer a.free(helper);
+ var map = try env.createMap(a);
+ defer map.deinit();
+ const backup = try std.fs.path.join(a, &.{ home, "rediwm/gtk-theme.gsettings-backup" });
+ defer a.free(backup);
+ const old = try app.readOptional(a, io, backup);
+ defer if (old) |bytes| a.free(bytes);
+ if (old == null) {
+ const result = try run(io, &map, &.{ helper, "get", "org.gnome.desktop.interface", "gtk-theme" });
+ defer a.free(result.stdout);
+ defer a.free(result.stderr);
+ if (result.term != .exited or result.term.exited != 0) return false;
+ var arena: std.heap.ArenaAllocator = .init(a);
+ defer arena.deinit();
+ var tx = app.Transaction{ .a = arena.allocator(), .io = io };
+ try tx.add(backup, result.stdout, false);
+ try tx.commit();
+ }
+ const result = try run(io, &map, &.{ helper, "set", "org.gnome.desktop.interface", "gtk-theme", name });
+ defer a.free(result.stdout);
+ defer a.free(result.stderr);
+ return result.term == .exited and result.term.exited == 0;
+}
+
+fn run(io: std.Io, env: *const std.process.Environ.Map, argv: []const []const u8) !std.process.RunResult {
+ return std.process.run(a, io, .{
+ .argv = argv,
+ .environ_map = env,
+ .stdout_limit = .limited(4096),
+ .stderr_limit = .limited(4096),
+ .timeout = .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } },
+ });
+}
diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zig
index 26f9bf8..9f43bc2 100644
--- a/src/config_runtime/apply.zig
+++ b/src/config_runtime/apply.zig
@@ -199,6 +199,10 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
const theme_changed = pack_changed or !themeEql(old.theme, new.theme) or old.compositor.border_radius != new.compositor.border_radius;
const taskbar_theme_changed = !theme_mod.taskbarOverrideEql(old.taskbar_theme, new.taskbar_theme);
+ if (theme_changed or old.compositor.follow_app_colors != new.compositor.follow_app_colors or old.compositor.dark_mode != new.compositor.dark_mode) {
+ @import("app_colors.zig").sync(server);
+ if (server.input.open_control_center) |cc| cc.refresh();
+ }
if (theme_changed) {
server.saveLoginTheme();
if (server.notifications) |manager| manager.themeChanged();
diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zig
index 36cad80..50e8657 100644
--- a/src/control_center/search_index.zig
+++ b/src/control_center/search_index.zig
@@ -158,6 +158,7 @@ const source_entries = [_]SourceEntry{
.{ .page = .appearance, .title = i18n.msg("Taskbar theme"), .target = "taskbar_theme", .keywords = i18n.msg("panel colors colours") },
.{ .page = .appearance, .title = i18n.msg("Dark mode"), .target = "dark_mode", .keywords = i18n.msg("light appearance theme") },
.{ .page = .appearance, .title = i18n.msg("Apply GTK colors"), .target = "apply_gtk_colors", .keywords = i18n.msg("application colours theme") },
+ .{ .page = .appearance, .title = i18n.msg("Follow RediWM application colors"), .target = "follow_app_colors", .keywords = i18n.msg("browser brave chrome firefox falkon gtk qt colours theme sync") },
.{ .page = .appearance, .title = i18n.msg("Apply Qt colors"), .target = "apply_qt_colors", .keywords = i18n.msg("application colours theme") },
.{ .page = .appearance, .title = i18n.msg("Launch splash"), .target = "launch_splash", .keywords = i18n.msg("startup welcome animation") },
.{ .page = .appearance, .title = i18n.msg("Flames while moving windows"), .target = "effect_window_move", .keywords = i18n.msg("effects fire trail ribbon drag animation") },
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index 95faadc..14c2e6f 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -31,7 +31,6 @@ const start_button = @import("../../taskbar/start_button.zig");
const menu_size = @import("../../start_menu/size.zig");
const wlr = @import("wlroots");
const app_theme = @import("config").app_theme;
-const AppColorsJob = @import("../../config_runtime/app_theme.zig").Job;
const appearance_wallpaper = @import("appearance_wallpaper.zig");
const appearance_colors = @import("appearance_colors.zig");
const appearance_themes = @import("appearance_themes.zig");
@@ -51,9 +50,6 @@ pub const stopStrip = appearance_wallpaper.stopStrip;
pub const deinit = appearance_wallpaper.deinit;
pub const appColorsNote = appearance_colors.appColorsNote;
pub const onApplyAppColors = appearance_colors.onApplyAppColors;
-pub const appColorsFailure = appearance_colors.appColorsFailure;
-pub const finishAppColors = appearance_colors.finishAppColors;
-pub const appColorsReady = appearance_colors.appColorsReady;
pub const stripWake = appearance_wallpaper.stripWake;
pub const restartStrip = appearance_wallpaper.restartStrip;
pub const buildWallpaper = appearance_wallpaper.buildWallpaper;
@@ -254,10 +250,10 @@ pub const Section = struct {
icon_theme_names: []const []const u8 = &.{},
taskbar_theme_row_children: [2]Widget = undefined,
- app_colors_children: [3]Widget = undefined,
+ app_colors_children: [4]Widget = undefined,
+ app_colors_len: usize = 4,
+ follow_colors_children: [2]Widget = undefined,
app_colors_buttons: [2]Widget = undefined,
- app_colors_job: ?*AppColorsJob = null,
- app_colors_source: ?*wl.EventSource = null,
app_colors_message: []const u8 = "",
app_colors_message_buf: [384]u8 = undefined,
dark_row_children: [2]Widget = undefined,
@@ -508,7 +504,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.icon_theme_row },
.{ .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 = .column, .gap = 8, .children = out.app_colors_children[0..out.app_colors_len] },
.{ .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 },
@@ -549,7 +545,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
at += 1;
}
for (group.rows) |row| {
- out.group_storage[at] = out.row_storage[@intFromEnum(row)];
+ out.group_storage[at] = out.row_storage[@backingInt(row)];
at += 1;
}
// An untitled group is one row that brings its own title.
@@ -637,8 +633,8 @@ comptime {
// Every row is shown exactly once.
var seen = @as([row_count]bool, @splat(false));
for (groups) |group| for (group.rows) |row| {
- if (seen[@intFromEnum(row)]) @compileError("row in two groups: " ++ @tagName(row));
- seen[@intFromEnum(row)] = true;
+ if (seen[@backingInt(row)]) @compileError("row in two groups: " ++ @tagName(row));
+ seen[@backingInt(row)] = true;
};
- for (seen, 0..) |shown, i| if (!shown) @compileError("row in no group: " ++ @tagName(@as(Row, @enumFromInt(i))));
+ for (seen, 0..) |shown, i| if (!shown) @compileError("row in no group: " ++ @tagName(@as(Row, @fromBackingInt(@intCast(i)))));
}
diff --git a/src/control_center/sections/appearance_chrome.zig b/src/control_center/sections/appearance_chrome.zig
index d5e2691..02d0c48 100644
--- a/src/control_center/sections/appearance_chrome.zig
+++ b/src/control_center/sections/appearance_chrome.zig
@@ -84,7 +84,7 @@ pub fn onFontSizeChanged(owner: ?*anyopaque, _: usize, index: usize) void {
}
pub fn onRadiusChanged(owner: ?*anyopaque, _: usize, index: usize) void {
- theme.applyRadiusPreset(&theme.global, @enumFromInt(index));
+ theme.applyRadiusPreset(&theme.global, @fromBackingInt(@intCast(index)));
applyThemeChange(section(owner));
}
@@ -199,11 +199,11 @@ pub fn onTaskbarPositionChanged(owner: ?*anyopaque, _: usize, index: usize) void
if (index > 1) return;
const s = section(owner);
const server = s.cc.server;
- const position: @TypeOf(server.config.compositor.taskbar_position) = @enumFromInt(index);
+ const position: @TypeOf(server.config.compositor.taskbar_position) = @fromBackingInt(@intCast(index));
if (position == server.config.compositor.taskbar_position) return;
setting_save.saveCompositor(main.gpa, server.io, server.config.path, "taskbar_position", position) catch |err| {
std.log.warn("could not save taskbar position: {}", .{err});
- s.taskbar_position_children[1].kind.segmented.selected = @intFromEnum(server.config.compositor.taskbar_position);
+ s.taskbar_position_children[1].kind.segmented.selected = @backingInt(server.config.compositor.taskbar_position);
s.taskbar_position_children[1].markDirty();
return;
};
@@ -215,11 +215,11 @@ pub fn onTaskbarAlignmentChanged(owner: ?*anyopaque, _: usize, index: usize) voi
if (index > 2) return;
const s = section(owner);
const server = s.cc.server;
- const alignment: @TypeOf(server.config.compositor.taskbar_alignment) = @enumFromInt(index);
+ const alignment: @TypeOf(server.config.compositor.taskbar_alignment) = @fromBackingInt(@intCast(index));
if (alignment == server.config.compositor.taskbar_alignment) return;
setting_save.saveCompositor(main.gpa, server.io, server.config.path, "taskbar_alignment", alignment) catch |err| {
std.log.warn("could not save taskbar alignment: {}", .{err});
- s.taskbar_alignment_children[1].kind.segmented.selected = @intFromEnum(server.config.compositor.taskbar_alignment);
+ s.taskbar_alignment_children[1].kind.segmented.selected = @backingInt(server.config.compositor.taskbar_alignment);
s.taskbar_alignment_children[1].markDirty();
return;
};
@@ -231,7 +231,7 @@ pub fn onFocusZoomChanged(owner: ?*anyopaque, _: usize, index: usize) void {
if (index >= focus_zoom_labels.len) return;
const s = section(owner);
const server = section(owner).cc.server;
- const mode: @import("../../camera.zig").FocusZoom = @enumFromInt(index);
+ const mode: @import("../../camera.zig").FocusZoom = @fromBackingInt(@intCast(index));
setting_save.saveCompositor(main.gpa, server.io, server.config.path, "focus_zoom", mode) catch |err| {
std.log.warn("could not save focus_zoom: {}", .{err});
return;
@@ -246,11 +246,11 @@ pub fn onSwitcherStyleChanged(owner: ?*anyopaque, _: usize, index: usize) void {
if (index > 1) return;
const s = section(owner);
const server = s.cc.server;
- const style: @TypeOf(server.config.compositor.switcher_style) = @enumFromInt(index);
+ const style: @TypeOf(server.config.compositor.switcher_style) = @fromBackingInt(@intCast(index));
if (style == server.config.compositor.switcher_style) return;
setting_save.saveCompositor(main.gpa, server.io, server.config.path, "switcher_style", style) catch |err| {
std.log.warn("could not save switcher style: {}", .{err});
- s.switcher_style_children[1].kind.segmented.selected = @intFromEnum(server.config.compositor.switcher_style);
+ s.switcher_style_children[1].kind.segmented.selected = @backingInt(server.config.compositor.switcher_style);
s.switcher_style_children[1].markDirty();
return;
};
@@ -343,6 +343,7 @@ pub fn onDarkModeChanged(owner: ?*anyopaque, _: usize, on: bool) void {
if (server.config.compositor.dark_mode == on) return;
server.config.compositor.dark_mode = on;
settings_portal.emitColorScheme(server);
+ @import("../../config_runtime/app_colors.zig").sync(server);
setting_save.saveCompositor(main.gpa, server.io, server.config.path, "dark_mode", on) catch |err| {
std.log.warn("could not save dark_mode: {}", .{err});
};
diff --git a/src/control_center/sections/appearance_colors.zig b/src/control_center/sections/appearance_colors.zig
index 70334ff..b9e3578 100644
--- a/src/control_center/sections/appearance_colors.zig
+++ b/src/control_center/sections/appearance_colors.zig
@@ -5,14 +5,14 @@ const std = @import("std");
const layout = @import("ui").layout;
const theme = @import("ui").theme;
const Widget = layout.Widget;
-const wl = @import("wayland").server.wl;
-const app_theme = @import("config").app_theme;
-const AppColorsJob = @import("../../config_runtime/app_theme.zig").Job;
+const manager = @import("../../config_runtime/app_colors.zig");
+const setting_save = @import("config").setting_save;
+const main = @import("../../main.zig");
const section = @import("appearance_dock.zig").section;
const Section = @import("appearance.zig").Section;
pub fn appColorsNote(s: *Section, a: std.mem.Allocator, color: [4]f32) Widget {
- const message = if (s.app_colors_message.len > 0) s.app_colors_message else i18n.tr("Uses the main theme. Apply again after changing it; restart apps to see the colors.");
+ const message = status(s);
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;
@@ -34,65 +34,60 @@ pub fn appColorsNote(s: *Section, a: std.mem.Allocator, color: [4]f32) Widget {
pub 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);
+ const server = s.cc.server;
+ if (server.app_colors.job != null or server.config.compositor.follow_app_colors) return;
+ s.app_colors_message = "";
+ manager.start(server, if (id == 0) .gtk else .qt) catch |err| manager.fail(server, err);
+}
+
+pub fn onFollowChanged(owner: ?*anyopaque, _: usize, on: bool) void {
+ const s = section(owner);
+ const server = s.cc.server;
+ if (server.greeter_mode) return;
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "follow_app_colors", on) catch |err| {
+ s.app_colors_message = i18n.fmt(&s.app_colors_message_buf, i18n.tr("Could not save application color preference: {reason}."), .{ .reason = @errorName(err) }) catch "";
+ s.cc.refresh();
return;
};
- s.app_colors_job = job;
- s.app_colors_source = source;
- s.app_colors_message = i18n.tr("Applying app colors…");
+ server.config.compositor.follow_app_colors = on;
+ s.app_colors_message = "";
+ manager.sync(server);
s.cc.refresh();
}
-pub fn appColorsFailure(s: *Section, err: anyerror) void {
- s.app_colors_message = switch (err) {
+fn status(s: *Section) []const u8 {
+ if (s.app_colors_message.len > 0) return s.app_colors_message;
+ const state = &s.cc.server.app_colors;
+ if (state.job != null) return i18n.tr("Applying app colors…");
+ if (state.failure) |err| return failure(s, err);
+ if (s.cc.server.config.compositor.follow_app_colors) {
+ if (state.result) |result| {
+ if (result.qt_error) |err| return failure(s, err);
+ if (!result.gtk_notified) return i18n.tr("Following application colors. GTK live updates are unavailable; restart GTK apps after theme changes. Choose GTK in Brave or Chrome, System theme in Firefox, or Linux in Falkon.");
+ if (!result.support.qt5 and !result.support.qt6) return i18n.tr("Following GTK colors. Install qt5ct or qt6ct to include Qt apps. Choose GTK in Brave or Chrome, or System theme in Firefox; restart apps once if needed.");
+ }
+ return i18n.tr("Following the main theme. Choose GTK in Brave or Chrome, System theme in Firefox, or Linux in Falkon. Restart apps once if needed; apps with their own styles may differ.");
+ }
+ if (state.result) |result| {
+ switch (state.action orelse return "") {
+ .gtk => return i18n.tr("GTK colors applied. Restart GTK apps. Apps with their own styles or sandbox settings may differ."),
+ .qt => return if (result.support.qt5 and result.support.qt6)
+ i18n.tr("Qt 5 and Qt 6 colors applied. Restart apps; sign in again if their colors do not change.")
+ else if (result.support.qt6)
+ i18n.tr("Qt 6 colors applied. Install qt5ct for Qt 5 apps. Restart apps; sign in again if their colors do not change.")
+ else
+ i18n.tr("Qt 5 colors applied. Install qt6ct for Qt 6 apps. Restart apps; sign in again if their colors do not change."),
+ .follow => return i18n.tr("Automatic updates are off. Applications keep the last applied colors."),
+ }
+ }
+ return i18n.tr("Uses the main theme. Apply again after changing it; restart apps to see the colors.");
+}
+
+fn failure(s: *Section, err: anyerror) []const u8 {
+ return switch (err) {
error.QtToolsMissing => i18n.tr("Install qt5ct for Qt 5 apps or qt6ct for Qt 6 apps, then apply again."),
error.ManagedSymlink => i18n.tr("A toolkit config folder is a symlink. Apply the colors in its real location, or make it a regular folder."),
error.InvalidManagedCss => i18n.tr("The RediWM block in gtk.css is incomplete. Repair it before applying colors."),
else => i18n.fmt(&s.app_colors_message_buf, i18n.tr("Could not apply app colors: {reason}. Check your configuration files and permissions."), .{ .reason = @errorName(err) }) catch i18n.tr("Could not apply app colors. Check your configuration files and permissions."),
};
- std.log.warn("app colors export failed: {}", .{err});
- s.cc.refresh();
-}
-
-pub 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 => i18n.tr("GTK colors applied. Restart GTK apps. Apps with their own styles or sandbox settings may differ."),
- .qt => if (support.qt5 and support.qt6)
- i18n.tr("Qt 5 and Qt 6 colors applied. Restart apps; sign in again if their colors do not change.")
- else if (support.qt6)
- i18n.tr("Qt 6 colors applied. Install qt5ct for Qt 5 apps. Restart apps; sign in again if their colors do not change.")
- else
- i18n.tr("Qt 5 colors applied. Install qt6ct for Qt 6 apps. Restart apps; sign in again if their colors do not change."),
- };
- s.cc.refresh();
-}
-
-pub fn appColorsReady(_: c_int, _: wl.EventMask, s: *Section) c_int {
- finishAppColors(s, true);
- return 0;
}
diff --git a/src/control_center/sections/appearance_rows.zig b/src/control_center/sections/appearance_rows.zig
index 808e057..3824f4b 100644
--- a/src/control_center/sections/appearance_rows.zig
+++ b/src/control_center/sections/appearance_rows.zig
@@ -124,15 +124,26 @@ pub fn buildThemeRows(out: *Section, arena: std.mem.Allocator) ?usize {
/// The app colour buttons and the dark mode toggle.
pub fn buildColorRows(out: *Section, arena: std.mem.Allocator, pal: theme.Theme) void {
- out.app_colors_buttons = .{
- .{ .name = "apply_gtk_colors", .kind = .{ .button = .{ .label = i18n.tr("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 = i18n.tr("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(i18n.tr("App colors")),
- .{ .kind = .container, .direction = .row, .gap = 8, .children = &out.app_colors_buttons },
- appColorsNote(out, arena, pal.dim),
+ const following = out.cc.server.config.compositor.follow_app_colors;
+ const busy = out.cc.server.app_colors.job != null;
+ out.follow_colors_children = .{
+ labelWidget(i18n.tr("Follow RediWM application colors")),
+ .{ .name = "follow_app_colors", .kind = .{ .toggle = .{ .on = following, .owner = out, .on_change = &appearance_colors.onFollowChanged } } },
};
+ out.app_colors_buttons = .{
+ .{ .name = "apply_gtk_colors", .kind = .{ .button = .{ .label = i18n.tr("Apply GTK colors"), .owner = out, .id = 0, .on_click = &onApplyAppColors, .state = if (busy) .disabled else .idle } }, .width = .{ .flex = 1 }, .height = .{ .fixed = 32 } },
+ .{ .name = "apply_qt_colors", .kind = .{ .button = .{ .label = i18n.tr("Apply Qt colors"), .owner = out, .id = 1, .on_click = &onApplyAppColors, .state = if (busy) .disabled else .idle } }, .width = .{ .flex = 1 }, .height = .{ .fixed = 32 } },
+ };
+ const label = labelWidget(i18n.tr("App colors"));
+ const follow_row: Widget = .{ .kind = .container, .direction = .row, .@"align" = .center, .children = &out.follow_colors_children };
+ const note = appColorsNote(out, arena, pal.dim);
+ // Following keeps both toolkits current; a manual GTK snapshot would pin
+ // newly started apps to its colors, so the buttons exist only when off.
+ out.app_colors_children = if (following)
+ .{ label, follow_row, note, undefined }
+ else
+ .{ label, follow_row, .{ .kind = .container, .direction = .row, .gap = 8, .children = &out.app_colors_buttons }, note };
+ out.app_colors_len = if (following) 3 else 4;
const dark_mode = out.cc.server.config.compositor.dark_mode;
out.dark_label_children = .{
.{ .kind = .{ .text = .{ .content = i18n.tr("Dark mode"), .font_size = theme.global.app_text_size, .weight = 600, .color = pal.fg } } },
@@ -210,15 +221,15 @@ pub fn buildBehaviorRows(out: *Section, pal: theme.Theme) void {
const focus_zoom = out.cc.server.config.compositor.focus_zoom;
out.focus_zoom_children = .{
labelWidget(i18n.tr("Window switching zoom")),
- .{ .name = "focus_zoom", .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&focus_zoom_labels), .selected = @intFromEnum(focus_zoom), .owner = out, .on_change = &onFocusZoomChanged } }, .width = .{ .percent = 1 } },
- .{ .kind = .{ .text = .{ .content = focus_zoom_descriptions[@intFromEnum(focus_zoom)].get(), .font_size = theme.global.settings_description_size, .color = pal.dim } } },
+ .{ .name = "focus_zoom", .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&focus_zoom_labels), .selected = @backingInt(focus_zoom), .owner = out, .on_change = &onFocusZoomChanged } }, .width = .{ .percent = 1 } },
+ .{ .kind = .{ .text = .{ .content = focus_zoom_descriptions[@backingInt(focus_zoom)].get(), .font_size = theme.global.settings_description_size, .color = pal.dim } } },
};
out.switcher_style_children = .{
labelWidget(i18n.tr("Window switcher")),
.{
.name = "switcher_style",
- .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&.{ i18n.msg("Linear"), i18n.msg("Circular") }), .selected = @intFromEnum(out.cc.server.config.compositor.switcher_style), .owner = out, .on_change = &appearance_chrome.onSwitcherStyleChanged } },
+ .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&.{ i18n.msg("Linear"), i18n.msg("Circular") }), .selected = @backingInt(out.cc.server.config.compositor.switcher_style), .owner = out, .on_change = &appearance_chrome.onSwitcherStyleChanged } },
.width = .{ .fixed = segmented_width },
},
};
@@ -329,7 +340,7 @@ pub fn buildFontRows(out: *Section, arena: std.mem.Allocator, t: theme.Theme, pa
labelWidget(i18n.tr("Radius")),
.{
.name = "radius",
- .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&radius_labels), .selected = if (theme.radiusPreset(t)) |preset| @intFromEnum(preset) else radius_labels.len, .owner = out, .on_change = &onRadiusChanged } },
+ .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&radius_labels), .selected = if (theme.radiusPreset(t)) |preset| @backingInt(preset) else radius_labels.len, .owner = out, .on_change = &onRadiusChanged } },
.width = .{ .fixed = segmented_width },
},
};
diff --git a/src/control_center/sections/appearance_themes.zig b/src/control_center/sections/appearance_themes.zig
index f0bd877..62e9825 100644
--- a/src/control_center/sections/appearance_themes.zig
+++ b/src/control_center/sections/appearance_themes.zig
@@ -97,6 +97,7 @@ pub fn onResetStartLogo(owner: ?*anyopaque, _: usize) void {
}
pub fn refreshTheme(server: *@import("../../Server.zig"), taskbar_geometry: bool) void {
+ @import("../../config_runtime/app_colors.zig").sync(server);
server.saveLoginTheme();
if (server.desktop) |desktop| desktop.app.themeChanged();
@import("ui").text.setPreferredFamilies(theme.global.font, theme.global.mono_font);
diff --git a/src/control_center/sections/appearance_wallpaper.zig b/src/control_center/sections/appearance_wallpaper.zig
index e024c7a..c04fbac 100644
--- a/src/control_center/sections/appearance_wallpaper.zig
+++ b/src/control_center/sections/appearance_wallpaper.zig
@@ -14,7 +14,6 @@ const wallpapers = @import("../../wallpapers.zig");
const wallpaper_strip = @import("../../wallpaper_strip.zig");
const folder_picker = @import("../folder_picker.zig");
const wl = @import("wayland").server.wl;
-const finishAppColors = @import("appearance_colors.zig").finishAppColors;
const section = @import("appearance_dock.zig").section;
const segmented_width = @import("appearance.zig").segmented_width;
const Section = @import("appearance.zig").Section;
@@ -61,7 +60,6 @@ pub fn stopStrip(out: *Section) void {
pub fn deinit(out: *Section) void {
stopStrip(out);
- finishAppColors(out, false);
if (out.theme_pending_path) |p| main.gpa.free(p);
out.theme_pending_path = null;
}
diff --git a/src/qt_style/rediwm_style.cpp b/src/qt_style/rediwm_style.cpp
new file mode 100644
index 0000000..b2feebe
--- /dev/null
+++ b/src/qt_style/rediwm_style.cpp
@@ -0,0 +1,46 @@
+// RediWM's Qt style: Fusion, except that title bars use the window colour.
+// Fusion fills an active title bar with the palette's Highlight (the theme
+// accent). Chromium's Qt mode samples that title bar as its whole frame, so
+// a following palette turned Brave's tab strip accent yellow.
+// Built per Qt major against the system Qt (build/qt_style.zig).
+#include <QPalette>
+#include <QProxyStyle>
+#include <QStyleFactory>
+#include <QStyleOptionTitleBar>
+#include <QStylePlugin>
+
+namespace {
+
+class Style : public QProxyStyle {
+public:
+ Style() : QProxyStyle(QStyleFactory::create(QStringLiteral("Fusion"))) {}
+
+ void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter,
+ const QWidget *widget) const override {
+ const auto *bar = control == CC_TitleBar ? qstyleoption_cast<const QStyleOptionTitleBar *>(option) : nullptr;
+ if (!bar) {
+ QProxyStyle::drawComplexControl(control, option, painter, widget);
+ return;
+ }
+ // Fusion draws an inactive bar from Window/WindowText; give the
+ // active one the same colours so focus never paints the accent.
+ QStyleOptionTitleBar neutral(*bar);
+ neutral.palette.setColor(QPalette::Highlight, bar->palette.color(QPalette::Active, QPalette::Window));
+ neutral.palette.setColor(QPalette::HighlightedText, bar->palette.color(QPalette::Active, QPalette::WindowText));
+ QProxyStyle::drawComplexControl(control, &neutral, painter, widget);
+ }
+};
+
+} // namespace
+
+class RediwmStylePlugin : public QStylePlugin {
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID QStyleFactoryInterface_iid FILE "rediwm_style.json")
+
+public:
+ QStyle *create(const QString &key) override {
+ return key.compare(QLatin1String("RediWM"), Qt::CaseInsensitive) == 0 ? new Style : nullptr;
+ }
+};
+
+#include "rediwm_style.moc"
diff --git a/src/qt_style/rediwm_style.json b/src/qt_style/rediwm_style.json
new file mode 100644
index 0000000..c8f63f3
--- /dev/null
+++ b/src/qt_style/rediwm_style.json
@@ -0,0 +1 @@
+{ "Keys": [ "RediWM" ] }
diff --git a/src/server/setup.zig b/src/server/setup.zig
index 14fc4db..6a25139 100644
--- a/src/server/setup.zig
+++ b/src/server/setup.zig
@@ -152,6 +152,7 @@ pub fn init(server: *Server, scale: ?f32, icon_theme_cfg: icon_theme.Config, io:
};
try initSession(server, world_tree);
+ @import("../config_runtime/app_colors.zig").sync(server);
}
fn initSession(server: *Server, world_tree: *sn.Tree) CompositorError!void {
@@ -177,6 +178,7 @@ fn initSession(server: *Server, world_tree: *sn.Tree) CompositorError!void {
break :blk false;
};
} else |_| {}
+ server.app_colors.qt_styles = @import("../config_runtime/app_theme.zig").findQtStyles(io);
}
if (!greeter) @import("../config_runtime/region.zig").applyTimezone(@import("../main.zig").gpa, loaded.region.timezone, environ.getPosix("TZ")) catch |err| {
diff --git a/src/server/teardown.zig b/src/server/teardown.zig
index 02ab6a8..1a28c52 100644
--- a/src/server/teardown.zig
+++ b/src/server/teardown.zig
@@ -22,6 +22,7 @@ pub fn deinit(server: *Server) void {
server.startup_tasks.deinit();
server.reveal.deinit();
server.session_startup.deinit();
+ server.app_colors.deinit();
if (!already_terminating) {
if (server.layout_autosave) |as| as.saveNow();
}
diff --git a/src/session/activation.zig b/src/session/activation.zig
index 5bb1d7c..8fed4db 100644
--- a/src/session/activation.zig
+++ b/src/session/activation.zig
@@ -139,6 +139,7 @@ pub const Readiness = struct {
.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"),
+ .QT_PLUGIN_PATH = map.get("QT_PLUGIN_PATH"),
}, .{ .emit_null_optional_fields = false });
defer allocator.free(message);
diff --git a/src/session/publication.zig b/src/session/publication.zig
index 3a0de53..aea56b3 100644
--- a/src/session/publication.zig
+++ b/src/session/publication.zig
@@ -7,7 +7,7 @@ const c = std.c;
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", "QT_QPA_PLATFORMTHEME", "QT_QPA_PLATFORMTHEME_QT6", "QT_STYLE_OVERRIDE", 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", "QT_PLUGIN_PATH", owner_key };
pub const Env = std.StringArrayHashMapUnmanaged([]const u8);
pub const Pair = struct { key: []const u8, value: []const u8 };
@@ -299,13 +299,16 @@ test "Qt app colors activation lease restores the previous desktop theme" {
try f.owner.publish(&.{
.{ .key = "QT_QPA_PLATFORMTHEME", .value = "qt5ct" },
.{ .key = "QT_QPA_PLATFORMTHEME_QT6", .value = "qt6ct" },
- .{ .key = "QT_STYLE_OVERRIDE", .value = "Fusion" },
+ .{ .key = "QT_STYLE_OVERRIDE", .value = "" },
+ .{ .key = "QT_PLUGIN_PATH", .value = "/usr/local/lib/rediwm/qt6" },
});
+ try testing.expectEqualStrings("/usr/local/lib/rediwm/qt6", f.bus.env.get("QT_PLUGIN_PATH").?);
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"));
+ try testing.expect(!f.bus.env.contains("QT_PLUGIN_PATH"));
}
test "a value changed by someone else is not clobbered" {
diff --git a/src/session/settings_portal.zig b/src/session/settings_portal.zig
index 58dc421..590c0fe 100644
--- a/src/session/settings_portal.zig
+++ b/src/session/settings_portal.zig
@@ -12,12 +12,15 @@
//! Rides the notifications manager's session-bus connection, so it is up in
//! exactly the sessions that connection is (a real login, or
//! REDIWM_FORCE_DBUS=1).
+//! Opt-in application colors additionally publish `gtk-theme` after the
+//! reloadable palette files have been committed.
const std = @import("std");
const dbus = @import("dbus");
const wire = dbus.wire;
const Server = @import("../Server.zig");
const anim = @import("ui").anim;
+const app_colors = @import("../config_runtime/app_colors.zig");
const log = std.log.scoped(.settings_portal);
@@ -30,6 +33,7 @@ pub const appearance_namespace = "org.freedesktop.appearance";
pub const color_scheme_key = "color-scheme";
pub const gnome_interface_namespace = "org.gnome.desktop.interface";
pub const enable_animations_key = "enable-animations";
+pub const gtk_theme_key = "gtk-theme";
const portal_frontend_name = "org.freedesktop.portal.Desktop";
const portal_frontend_iface = "org.freedesktop.portal.Settings";
const not_found_error = "org.freedesktop.portal.Error.NotFound";
@@ -124,6 +128,21 @@ pub fn emitEnableAnimations(server: *Server, served: ?bool) void {
};
}
+pub fn emitGtkTheme(server: *Server) void {
+ const name = app_colors.gtkTheme(server) orelse return;
+ const mgr = server.notifications orelse return;
+ const conn = mgr.conn orelse return;
+ var body: wire.Writer = .{ .allocator = mgr.allocator };
+ defer body.deinit();
+ body.string(gnome_interface_namespace) catch return;
+ body.string(gtk_theme_key) catch return;
+ body.variant("s") catch return;
+ body.string(name) catch return;
+ conn.signal(object_path, interface, "SettingChanged", "ssv", &body) catch |err| {
+ if (err != error.NotRegistered) log.warn("GTK SettingChanged failed: {}", .{err});
+ };
+}
+
/// Namespace patterns as xdg-desktop-portal documents them: an empty list or
/// an empty string matches everything, and a trailing `*` matches a prefix.
pub fn namespaceMatches(pattern: []const u8, namespace: []const u8) bool {
@@ -133,7 +152,7 @@ pub fn namespaceMatches(pattern: []const u8, namespace: []const u8) bool {
}
/// `a{sa{sv}}` for ReadAll. `patterns` is the request's `as` array reader.
-fn writeReadAll(body: *wire.Writer, patterns: wire.Reader, scheme: ColorScheme, enable_animations: ?bool) !void {
+fn writeReadAll(body: *wire.Writer, patterns: wire.Reader, scheme: ColorScheme, enable_animations: ?bool, gtk_theme: ?[]const u8) !void {
var reader = patterns;
var match_appearance = reader.offset == reader.bytes.len;
var match_gnome = match_appearance;
@@ -150,20 +169,26 @@ fn writeReadAll(body: *wire.Writer, patterns: wire.Reader, scheme: ColorScheme,
try body.alignTo(8);
try body.string(color_scheme_key);
try body.variant("u");
- try body.uint32(@intFromEnum(scheme));
+ try body.uint32(@backingInt(scheme));
try body.endArray(values);
}
- if (enable_animations) |enabled| {
- if (match_gnome) {
- try body.alignTo(8);
- try body.string(gnome_interface_namespace);
- const values = try body.beginArray(8);
+ if (match_gnome and (enable_animations != null or gtk_theme != null)) {
+ try body.alignTo(8);
+ try body.string(gnome_interface_namespace);
+ const values = try body.beginArray(8);
+ if (enable_animations) |enabled| {
try body.alignTo(8);
try body.string(enable_animations_key);
try body.variant("b");
try body.boolean(enabled);
- try body.endArray(values);
}
+ if (gtk_theme) |name| {
+ try body.alignTo(8);
+ try body.string(gtk_theme_key);
+ try body.variant("s");
+ try body.string(name);
+ }
+ try body.endArray(values);
}
try body.endArray(namespaces);
}
@@ -172,7 +197,7 @@ fn writeSettingChanged(body: *wire.Writer, scheme: ColorScheme) !void {
try body.string(appearance_namespace);
try body.string(color_scheme_key);
try body.variant("u");
- try body.uint32(@intFromEnum(scheme));
+ try body.uint32(@backingInt(scheme));
}
fn writeEnableAnimationsChanged(body: *wire.Writer, enabled: bool) !void {
@@ -194,6 +219,7 @@ fn handleReadAll(owner: ?*anyopaque, conn: *dbus.Connection, request: wire.Messa
patterns,
colorScheme(server.config.compositor.dark_mode),
anim.servedEnableAnimations(server.config.animations),
+ app_colors.gtkTheme(server),
);
try conn.reply(request, "a{sa{sv}}", &body);
}
@@ -208,7 +234,7 @@ fn handleRead(owner: ?*anyopaque, conn: *dbus.Connection, request: wire.Message)
defer body.deinit();
if (std.mem.eql(u8, namespace, appearance_namespace) and std.mem.eql(u8, key, color_scheme_key)) {
try body.variant("u");
- try body.uint32(@intFromEnum(colorScheme(server.config.compositor.dark_mode)));
+ try body.uint32(@backingInt(colorScheme(server.config.compositor.dark_mode)));
try conn.reply(request, "v", &body);
return;
}
@@ -220,6 +246,14 @@ fn handleRead(owner: ?*anyopaque, conn: *dbus.Connection, request: wire.Message)
return;
}
}
+ if (std.mem.eql(u8, namespace, gnome_interface_namespace) and std.mem.eql(u8, key, gtk_theme_key)) {
+ if (app_colors.gtkTheme(server)) |name| {
+ try body.variant("s");
+ try body.string(name);
+ try conn.reply(request, "v", &body);
+ return;
+ }
+ }
try conn.replyError(request, not_found_error, "Requested setting not found");
}
@@ -282,8 +316,8 @@ test "settings portal namespace patterns" {
test "settings portal color scheme follows dark_mode, off is explicit light" {
try std.testing.expectEqual(ColorScheme.prefer_dark, colorScheme(true));
try std.testing.expectEqual(ColorScheme.prefer_light, colorScheme(false));
- try std.testing.expectEqual(@as(u32, 1), @intFromEnum(colorScheme(true)));
- try std.testing.expectEqual(@as(u32, 2), @intFromEnum(colorScheme(false)));
+ try std.testing.expectEqual(@as(u32, 1), @backingInt(colorScheme(true)));
+ try std.testing.expectEqual(@as(u32, 2), @backingInt(colorScheme(false)));
}
fn expectReadAll(patterns: []const []const u8, expect_appearance: bool) !void {
@@ -298,7 +332,7 @@ fn expectReadAll(patterns: []const []const u8, expect_appearance: bool) !void {
var body: wire.Writer = .{ .allocator = allocator };
defer body.deinit();
- try writeReadAll(&body, pattern_reader, .prefer_dark, null);
+ try writeReadAll(&body, pattern_reader, .prefer_dark, null, null);
// encode validates the body against the signature.
var msg = try wire.encode(allocator, .method_return, 0, 2, .{ .reply_serial = 1, .destination = ":1.1", .signature = "a{sa{sv}}" }, &body);
defer msg.deinit();
@@ -325,7 +359,7 @@ test "settings portal ReadAll filters namespaces and encodes a{sa{sv}}" {
try expectReadAll(&.{"org.gnome.*"}, false);
}
-test "settings portal ReadAll includes enable-animations when we own it" {
+test "settings portal ReadAll includes animation and GTK keys in one namespace" {
const allocator = std.testing.allocator;
var request: wire.Writer = .{ .allocator = allocator };
defer request.deinit();
@@ -337,7 +371,7 @@ test "settings portal ReadAll includes enable-animations when we own it" {
var body: wire.Writer = .{ .allocator = allocator };
defer body.deinit();
- try writeReadAll(&body, pattern_reader, .prefer_light, false);
+ try writeReadAll(&body, pattern_reader, .prefer_light, false, "RediWM-b");
var msg = try wire.encode(allocator, .method_return, 0, 2, .{ .reply_serial = 1, .destination = ":1.1", .signature = "a{sa{sv}}" }, &body);
defer msg.deinit();
var reader = (try wire.decode(msg.bytes.items)).body;
@@ -349,6 +383,10 @@ test "settings portal ReadAll includes enable-animations when we own it" {
try std.testing.expectEqualStrings(enable_animations_key, try values.string());
try std.testing.expectEqualStrings("b", try values.variant());
try std.testing.expectEqual(false, try values.boolean());
+ try values.alignTo(8);
+ try std.testing.expectEqualStrings(gtk_theme_key, try values.string());
+ try std.testing.expectEqualStrings("s", try values.variant());
+ try std.testing.expectEqualStrings("RediWM-b", try values.string());
try values.done();
try namespaces.done();
try reader.done();
diff --git a/tests/app_colors.py b/tests/app_colors.py
new file mode 100644
index 0000000..96c4d6b
--- /dev/null
+++ b/tests/app_colors.py
@@ -0,0 +1,413 @@
+#!/usr/bin/env python3
+"""Application palettes: manual exports and opt-in live GTK/Qt synchronization."""
+from pathlib import Path
+import tempfile
+import time
+import tomllib
+import os
+import json
+import subprocess
+import sys
+import shutil
+
+from ipc_client import IPCClient, spawn_compositor, stop_process
+from ui_driver import UIDriver
+from desktop_zoom import wait_for
+
+# The RediWM Qt style beside the compositor under test (build/qt_style.zig).
+QT_STYLE_DIR = Path(__file__).resolve().parent.parent / "zig-out/lib/rediwm"
+
+
+def qt_style_built(major):
+ return (QT_STYLE_DIR / f"qt{major}/styles/librediwm-style.so").exists()
+
+
+def check_qt_frame(package, colors):
+ """Chromium's Qt frame is the style's active title bar: never the accent."""
+ if not qt_style_built(package[2]):
+ return
+ assert colors["style"] != "QFusionStyle", (package, colors)
+ near = lambda a, b: all(abs(int(a[i:i + 2], 16) - int(b[i:i + 2], 16)) <= 12 for i in (1, 3, 5))
+ assert near(colors["frame"], colors["bg"]) and not near(colors["frame"], colors["accent"]), (package, colors)
+
+
+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.startswith(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()
+ style = "RediWM" if qt_style_built(version[2]) else "Fusion"
+ assert f"style={style}" 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', 'QT_PLUGIN_PATH',
+ '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
+ # Empty: qt5ct/qt6ct choose the style per Qt major.
+ assert child_env["QT_STYLE_OVERRIDE"] == "", child_env
+ for major in (5, 6):
+ if qt_style_built(major):
+ assert str((QT_STYLE_DIR / f"qt{major}").resolve()) in child_env["QT_PLUGIN_PATH"].split(":"), 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
+ if "frame" in colors:
+ check_qt_frame(package, colors)
+
+ # A symlinked gtk.css becomes a regular file with its content merged.
+ 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)
+ apply("apply_gtk_colors", "GTK colors applied")
+ wait_for(lambda: not gtk4_css.is_symlink(), "gtk.css replaced")
+ assert "/* external */" in gtk4_css.read_text() and "rediwm-colors.css" in gtk4_css.read_text()
+ assert external.read_text() == "/* external */\n"
+ 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")
+
+
+
+def test_follow_private(tmp):
+ """Real settings bus and toolkit clients, all using a scratch HOME/XDG tree."""
+ config = Path(os.environ['XDG_CONFIG_HOME'])
+ data = Path(os.environ['XDG_DATA_HOME'])
+ colors = ('#123456', '#234567', '#345678')
+ def content(bg, on=True, taskbar='#ff0000'):
+ return (f'[compositor]\nxwayland = false\nfollow_app_colors = {str(on).lower()}\n'
+ f'[theme]\napp_bg = "{bg}"\nwindow_fg = "#e1e2e3"\n'
+ 'app_toolbar = "#456789"\nshell_accent = "#abcdef"\n'
+ f'[taskbar_theme]\napp_bg = "{taskbar}"\n')
+
+ # Starting with the default off never creates toolkit configuration.
+ process, log = spawn_compositor(tmp, config_content=content(colors[0], False),
+ scale=os.environ.get('REDIWM_TEST_SCALE', '1'),
+ env_extra={'REDIWM_FORCE_DBUS': '1'})
+ clients = []
+ streams = []
+ try:
+ with IPCClient(tmp, timeout=20) as ipc:
+ assert not (config / 'gtk-3.0').exists()
+ # Generators (matugen/DMS, KDE colors.css) define the standard
+ # names in user CSS, which outranks any theme: following must win.
+ competing = '/* BEGIN DMS OVERRIDE */\n@define-color window_bg_color #242730;\n/* END DMS OVERRIDE */\n'
+ (config / 'gtk-3.0').mkdir(parents=True)
+ (config / 'gtk-3.0/gtk.css').write_text(competing)
+ ipc.action('open_appearance')
+ ui = UIDriver(ipc)
+ ui.wait_settled('control_center')
+ toggle = ui.scroll_into_view('follow_app_colors')
+ def manual_buttons():
+ return {w.get('name') for w in ui.widgets()} & {'apply_gtk_colors', 'apply_qt_colors'}
+ assert manual_buttons() == {'apply_gtk_colors', 'apply_qt_colors'}
+ ui.click(toggle)
+ def selected():
+ p = config / 'gtk-3.0/settings.ini'
+ if not p.exists():
+ return None
+ return next((line.split('=', 1)[1] for line in p.read_text().splitlines()
+ if line.startswith('gtk-theme-name=')), None)
+ wait_for(lambda: selected() in ('RediWM-a', 'RediWM-b'), 'follow enabled')
+ path = tmp / 'rediwm-config.toml'
+ assert tomllib.loads(path.read_text())['compositor']['follow_app_colors']
+ # Following replaces the manual snapshot buttons.
+ wait_for(lambda: not manual_buttons(), 'manual buttons hidden while following')
+ def portal_theme():
+ r = subprocess.run(['busctl', '--user', '--timeout=3', 'call',
+ 'org.freedesktop.impl.portal.desktop.rediwm', '/org/freedesktop/portal/desktop',
+ 'org.freedesktop.impl.portal.Settings', 'Read', 'ss',
+ 'org.gnome.desktop.interface', 'gtk-theme'], capture_output=True, text=True)
+ return r.stdout.strip()
+ wait_for(lambda: portal_theme() == f'v s "{selected()}"', 'GTK theme published')
+ assert (config / 'rediwm/gtk-theme.gsettings-backup').exists()
+ user_css = (config / 'gtk-3.0/gtk.css').read_text()
+ assert user_css.startswith(competing), user_css
+ assert '@define-color window_bg_color @rediwm_window_bg_color;' in user_css, user_css
+ # Setup remains generic: no absent browser profile is created.
+ for name in ('BraveSoftware', 'google-chrome', 'falkon', 'mozilla'):
+ assert not (config / name).exists()
+
+ probe = tmp / 'env.py'
+ received = tmp / 'env.json'
+ probe.write_text('import os,json,sys\nfrom pathlib import Path\nPath(sys.argv[1]).write_text(json.dumps(dict(os.environ)))\n')
+ ipc.action('spawn', {'argv': [sys.executable, str(probe), str(received)]})
+ wait_for(received.exists, 'follow launch environment')
+ child_env = json.loads(received.read_text())
+ assert 'GTK_THEME' not in child_env
+ if preview := os.environ.get('REDIWM_SETTINGS_PREVIEW'):
+ Path(preview).mkdir(parents=True, exist_ok=True)
+ ui.scroll_into_view('follow_app_colors')
+ shot = Path(preview) / 'follow-app-colors.png'
+ shot.unlink(missing_ok=True)
+ ipc.screenshot(str(shot))
+ # Close Settings: palette following must outlive its widgets.
+ ipc.action('close_window')
+
+ root = Path(__file__).resolve().parent
+ import threading
+ for package, source, compiler, extra in (
+ ('gtk+-3.0', 'app_colors_gtk_client.c', 'cc', []),
+ ('gtk4', 'app_colors_gtk_client.c', 'cc', []),
+ ('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 live palette:', package)
+ continue
+ if package.startswith('Qt') and not shutil.which('qt' + package[2] + 'ct'):
+ print('SKIP live palette plugin:', 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)
+ errors = (tmp / (package + '.log')).open('w')
+ streams.append(errors)
+ proc = subprocess.Popen([str(binary), '--watch'], env=child_env,
+ stdout=subprocess.PIPE, stderr=errors, text=True)
+ samples = []
+ def collect(proc=proc, samples=samples):
+ for line in proc.stdout:
+ samples.append(json.loads(line))
+ threading.Thread(target=collect, daemon=True).start()
+ clients.append((package, proc, samples))
+ wait_for(lambda: samples and samples[-1]['bg'] == colors[0], f'{package} initial palette', timeout=15)
+ if 'frame' in samples[-1]:
+ check_qt_frame(package, samples[-1])
+
+ # Same palette and taskbar-only changes leave the named theme and
+ # watched toolkit files untouched.
+ first = selected()
+ gtk_file = data / 'themes' / first / 'gtk-3.0/gtk.css'
+ stamp = gtk_file.stat().st_mtime_ns
+ path.write_text(content(colors[0], taskbar='#00ff00'))
+ ipc.reload_config()
+ assert selected() == first and gtk_file.stat().st_mtime_ns == stamp
+ for bg in colors[1:]:
+ old = selected()
+ path.write_text(content(bg))
+ ipc.reload_config()
+ wait_for(lambda: selected() != old, 'new named GTK palette')
+ wait_for(lambda: portal_theme() == f'v s "{selected()}"', 'new theme published')
+ for package, proc, samples in clients:
+ wait_for(lambda: samples and samples[-1]['bg'] == bg,
+ f'{package} live palette {bg}', timeout=15)
+ assert samples[-1]['fg'] == '#e1e2e3', (package, samples)
+ # Rapid edits may overlap one worker; the final request must win.
+ for bg in ('#224466', '#335577', '#446688', colors[-1]):
+ path.write_text(content(bg))
+ ipc.reload_config()
+ wait_for(lambda: f'window_bg_color {colors[-1]}' in
+ (data / 'themes' / selected() / 'gtk-3.0/gtk.css').read_text(),
+ 'latest palette wins')
+ for package, proc, samples in clients:
+ wait_for(lambda: samples and samples[-1]['bg'] == colors[-1],
+ f'{package} final palette', timeout=15)
+ assert len(list((data / 'themes').glob('RediWM-*'))) == 2
+
+ # Disabling following keeps the current colors and stops future
+ # exports, both immediately and after a compositor restart.
+ last = selected()
+ last_file = data / 'themes' / last / 'gtk-3.0/gtk.css'
+ last_bytes = last_file.read_bytes()
+ path.write_text(content('#778899', False))
+ ipc.reload_config()
+ assert selected() == last and last_file.read_bytes() == last_bytes
+ assert not portal_theme()
+ for _, proc, _ in clients:
+ stop_process(proc)
+ clients.clear()
+ stop_process(process)
+ log.close()
+ process, log = spawn_compositor(tmp, config_content=content('#778899', False))
+ with IPCClient(tmp):
+ assert selected() == last and last_file.read_bytes() == last_bytes
+ stop_process(process)
+ log.close()
+ # Startup following also works without ever opening Settings.
+ process, log = spawn_compositor(tmp, config_content=content('#778899'))
+ with IPCClient(tmp):
+ wait_for(lambda: selected() != last, 'startup palette export')
+ print('PASS: opt-in persistence, live GTK3/GTK4/Qt palettes, portal, closed Settings, bounded themes, off and restart')
+ finally:
+ for _, proc, _ in clients:
+ stop_process(proc)
+ for stream in streams:
+ stream.close()
+ stop_process(process)
+ log.close()
+
+
+def test_follow_colors():
+ with tempfile.TemporaryDirectory(prefix='rediwm-follow-colors-') as directory:
+ tmp = Path(directory)
+ env = dict(os.environ, HOME=str(tmp / 'home'), XDG_CONFIG_HOME=str(tmp / 'config'),
+ XDG_DATA_HOME=str(tmp / 'data'), XDG_CACHE_HOME=str(tmp / 'cache'),
+ XDG_STATE_HOME=str(tmp / 'state'), XDG_RUNTIME_DIR=str(tmp),
+ GSETTINGS_BACKEND='keyfile', GTK_THEME='Adwaita',
+ REDIWM_FILES_DEVICES='0', REDIWM_FORCE_DBUS='1',
+ GIO_USE_VFS='local', NO_AT_BRIDGE='1', GTK_A11Y='none')
+ env.pop('DBUS_SESSION_BUS_ADDRESS', None)
+ env.pop('DISPLAY', None)
+ env.pop('WAYLAND_DISPLAY', None)
+ env.pop('REDIWM_THEME', None)
+ # The bus and its activation environment must also use the scratch
+ # home; only then can GSettings or portal services be safely exercised.
+ subprocess.run(['dbus-run-session', '--', sys.executable, __file__, '--follow-private', str(tmp)],
+ env=env, check=True, timeout=180)
+
+
+def test_follow_without_helpers():
+ with tempfile.TemporaryDirectory(prefix='rediwm-follow-minimal-') as directory:
+ tmp = Path(directory)
+ config = tmp / 'config'
+ process, log = spawn_compositor(tmp,
+ config_content='[compositor]\nxwayland=false\nfollow_app_colors=true\n[theme]\napp_bg="#314159"\n',
+ env_extra={'HOME': str(tmp / 'home'), 'XDG_CONFIG_HOME': str(config),
+ 'XDG_DATA_HOME': str(tmp / 'data'), 'XDG_CACHE_HOME': str(tmp / 'cache'),
+ 'PATH': str(tmp / 'missing-tools'), 'DBUS_SESSION_BUS_ADDRESS': ''})
+ try:
+ with IPCClient(tmp) as ipc:
+ exported = config / 'gtk-3.0/rediwm-colors.css'
+ wait_for(exported.exists, 'GTK fallback without optional tools')
+ assert 'window_bg_color #314159' in exported.read_text()
+ assert not (config / 'qt5ct').exists() and not (config / 'qt6ct').exists()
+ ipc.action('open_appearance')
+ ui = UIDriver(ipc)
+ ui.wait_settled('control_center')
+ note = ' '.join(w.get('label') or '' for w in ui.widgets()
+ if (w.get('name') or '').startswith('app_colors_status_'))
+ assert 'GTK live updates are unavailable' in note, note
+ print('PASS: GTK snapshots and clear status when optional tools are absent')
+ finally:
+ stop_process(process)
+ log.close()
+
+
+if __name__ == '__main__':
+ if '--follow-private' in sys.argv:
+ test_follow_private(Path(sys.argv[-1]))
+ elif '--follow-only' in sys.argv:
+ test_follow_colors()
+ else:
+ test_app_colors()
+ test_follow_colors()
+ test_follow_without_helpers()
diff --git a/tests/app_colors_gtk_client.c b/tests/app_colors_gtk_client.c
index 95681b6..5569547 100644
--- a/tests/app_colors_gtk_client.c
+++ b/tests/app_colors_gtk_client.c
@@ -1,28 +1,13 @@
/* Query actual toolkit styling after GTK loads the exported user CSS. */
#include <gtk/gtk.h>
#include <stdio.h>
+#include <string.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);
+static gboolean sample(gpointer window) {
+ GtkStyleContext *context = gtk_widget_get_style_context(GTK_WIDGET(window));
cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 4, 4);
cairo_t *cr = cairo_create(surface);
GdkRGBA fg;
@@ -44,7 +29,41 @@ int main(int argc, char **argv) {
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));
+ fflush(stdout);
cairo_surface_destroy(surface);
+ return G_SOURCE_REMOVE;
+}
+
+static void changed(GObject *object, GParamSpec *param, gpointer window) {
+ (void)object; (void)param;
+ g_idle_add(sample, window);
+}
+
+int main(int argc, char **argv) {
+ gboolean watch = argc > 1 && strcmp(argv[1], "--watch") == 0;
+#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
+ sample(window);
+ if (watch) {
+ g_signal_connect(gtk_settings_get_default(), "notify::gtk-theme-name", G_CALLBACK(changed), window);
+ GMainLoop *loop = g_main_loop_new(NULL, FALSE);
+ g_main_loop_run(loop);
+ g_main_loop_unref(loop);
+ }
#if GTK_MAJOR_VERSION == 3
gtk_widget_destroy(window);
#else
diff --git a/tests/app_colors_qt_client.cpp b/tests/app_colors_qt_client.cpp
index 87013d8..7cf8f20 100644
--- a/tests/app_colors_qt_client.cpp
+++ b/tests/app_colors_qt_client.cpp
@@ -1,22 +1,57 @@
-// Read the platform plugin's real QPalette, including the Qt6 Accent role.
+// Read the platform plugin's real QPalette, including the Qt6 Accent role, and
+// the frame colour Chromium's Qt mode derives from an active title bar.
#include <QApplication>
+#include <QImage>
+#include <QPainter>
#include <QPalette>
+#include <QStyle>
+#include <QStyleOptionTitleBar>
#include <QJsonDocument>
#include <QJsonObject>
#include <cstdio>
-int main(int argc, char **argv) {
- QApplication app(argc, argv);
- QPalette p = app.palette();
+// As Chromium's QtShim::GetFrameColor: the style's active title bar, averaged.
+static QString frame() {
+ QImage image(32, 32, QImage::Format_ARGB32_Premultiplied);
+ image.fill(qApp->palette().color(QPalette::Window));
+ QPainter painter(&image);
+ QStyleOptionTitleBar option;
+ option.rect = QRect(-5, -5, 42, 42);
+ option.titleBarState = QStyle::State_Active;
+ qApp->style()->drawComplexControl(QStyle::CC_TitleBar, &option, &painter, nullptr);
+ painter.end();
+ long sum[3] = {0, 0, 0};
+ for (int y = 0; y < image.height(); y++)
+ for (int x = 0; x < image.width(); x++) {
+ const QColor c = image.pixelColor(x, y);
+ sum[0] += c.red(), sum[1] += c.green(), sum[2] += c.blue();
+ }
+ const long n = image.width() * image.height();
+ return QColor(int(sum[0] / n), int(sum[1] / n), int(sum[2] / n)).name();
+}
+
+static void sample(const QPalette &p) {
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()}
+ {"disabled", p.color(QPalette::Disabled, QPalette::WindowText).name()},
+ {"style", QString::fromLatin1(qApp->style()->metaObject()->className())},
+ {"frame", frame()}
};
#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());
+ std::fflush(stdout);
+}
+
+int main(int argc, char **argv) {
+ QApplication app(argc, argv);
+ sample(app.palette());
+ if (app.arguments().contains("--watch")) {
+ QObject::connect(&app, &QGuiApplication::paletteChanged, &app, sample);
+ return app.exec();
+ }
}
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index e403192..6182260 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -656,152 +656,7 @@ def test_gold_settings_palette():
print("PASS: Gold Settings content, controls and sidebar colors, live and reloaded")
-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 symlinked gtk.css becomes a regular file with its content merged.
- 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)
- apply("apply_gtk_colors", "GTK colors applied")
- wait_for(lambda: not gtk4_css.is_symlink(), "gtk.css replaced")
- assert "/* external */" in gtk4_css.read_text() and "rediwm-colors.css" in gtk4_css.read_text()
- assert external.read_text() == "/* external */\n"
- 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")
+from app_colors import test_app_colors
if __name__ == "__main__":