RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
app colors
oxydizer77fb922f615b
diff --git a/TESTING.md b/TESTING.mdindex 5c2a5f4..0b7974b 100644--- a/TESTING.md+++ b/TESTING.md@@ -37,9 +37,15 @@ Application colors: `python3 tests/app_colors.py` checks snapshot exports andopt-in following with a private bus, scratch HOME/XDG directories, and realGTK3/GTK4/Qt5/Qt6 palette probes when installed. It keeps clients open acrosstheme changes, closes Settings, checks portal publication and compositor restart,-and verifies that disabling following stops exports. Repeat with+and verifies that disabling following stops exports. Qt probes that preload a+stand-in `libqt<N>_shim.so` check the Chromium colours, also after Dark mode is+switched in Settings. 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.+profiles in GTK/Qt/System/Linux theme mode; never use the host browser profile.+For Brave, check the tab strip against the active tab, a context menu's+shortcuts and disabled items, and the print preview (Ctrl+P) with a dropdown+open, with Dark mode both off and on, under a real xdg-desktop-portal with the+rediwm and gtk backends. Brave's Qt mode reads Qt colours only at startup.SSH keys: `zig build test-keys` and`dbus-run-session -- python3 tests/keys_settings.py` (repeat with@@ -156,6 +162,7 @@ readback. Keep real power actions out of automated tests.Canvas overview: `python3 tests/overview.py` checks the rendered 2×2 and2+3 grids, live minimized previews, restoration, pointer and keyboard selection,+hover and wheel magnification of a preview,consumed input, client teardown, config reload and reduced motion in a private headless session. Repeat with`REDIWM_TEST_SCALE=1.5 REDIWM_TEST_OUTPUTS=2`. Also run `focus_zoom.py`,`desktop_zoom.py`, `keyboard_shortcuts.py`, `shortcuts_inhibit.py`,diff --git a/docs/plans/hdr.md b/docs/plans/hdr.mdnew file mode 100644index 0000000..60333f8--- /dev/null+++ b/docs/plans/hdr.md@@ -0,0 +1,218 @@+# Plan: HDR output++Status: draft, 2026-11-16. Nothing is built. Started from the outside audit+in discussion #27 (github.com/oxydizer/rediwm/discussions/27). Its author+could not read `src/`, so this version checks its assumptions against our+code and the wlroots 0.20.2 source, and folds in the changes. The decisions+below are proposals.++Scope: HDR10 output (PQ, BT.2020) on DRM outputs, an SDR white level, and+color-management-v1 content (HDR video, games) on top of it. Out of scope:+ICC profiles, HLG output, HDR on nested or headless sessions (the host or+backend decides those), wide gamut without HDR.++## Decision: opt-in HDR in the GLES2 pass, no Vulkan++HDR is a per-output setting, **off by default**, implemented in our own GLES2+output pass. The audit's recommended path stays (its Path B). Its Path A, a+port to wlroots' Vulkan renderer, is dropped, and so is the variant of making+Vulkan an opt-in renderer just for HDR:++* **Our pass is our own code.** `rediwm_scene_pass_begin`+ (`src/scene_pass.h:21`) is our own GLES2 implementation of the wlroots render+ pass interface: about 260 raw GL calls in `scene_pass*.c`, and our own GLSL+ programs for rounded and polygon shapes, sectors, shadows, dimming, glass+ backdrops and ribbons. Even a plain `wlr_render_pass_add_texture` runs our+ code, not wlroots'.+* **Vulkan would not do the colour work for us.** wlroots' HDR math (transfer+ function decode, primaries, the FP16 blend image, the output encode) lives+ inside its private Vulkan render pass. The public Vulkan API+ (`include/wlr/render/vulkan.h`) only hands out the instance, physical device,+ device and queue family, plus a texture's image attributes. An opt-in Vulkan+ mode would be a second implementation of our pass in Vulkan, and we would+ still write the colour math ourselves.+* **Two renderers forever.** Every effect (glow, dimming, flames, polygon+ shapes, glass) would be written twice, or HDR mode would lack it. The+ integration suites run GLES2 on llvmpipe; Vulkan would need lavapipe and a+ second set of reference screenshots.+* **Not live, not per output.** The renderer is chosen once at startup+ (`src/wlr/renderer.zig:39`), and one renderer serves every output, so+ turning HDR on would need a compositor restart and would move SDR monitors+ to Vulkan too. On GLES2, HDR switches per output while running: an image+ description, a render format and a shader variant.++Revisit only if wlroots drops its GLES2 renderer.++## What the code says++Verified 2026-11-16 on master (df0b032) and wlroots 0.20.2:++* **The DRM side does not depend on the renderer** (the audit's highest risk,+ its Phase 0 go/no-go). `wlr_output_state_set_image_description` is checked+ only against `supported_primaries` and `supported_transfer_functions`+ (wlroots `types/output/output.c:703`). These come from the EDID and the+ connector's `Colorspace` and `HDR_OUTPUT_METADATA` properties+ (`backend/drm/util.c:97-106`). The atomic commit sets both properties from+ the description (`backend/drm/atomic.c:384-392`), and `max bpc` follows a+ 10-bit render format (`max_bpc_for_format`). No wlroots patch is needed.+* **Stale HDR state is reset.** Every atomic commit writes `Colorspace` and+ `HDR_OUTPUT_METADATA` from the connector's cached state, which starts at+ zero. A compositor that crashed in HDR, or a greeter that follows a session+ in HDR, comes up in SDR on its first commit.+* **GLES2 can hold the formats.** wlroots' GLES2 format table has+ `XBGR2101010`/`ABGR2101010` and `XBGR16161616F`/`ABGR16161616F`, gated by+ `EXT_texture_type_2_10_10_10_REV` and the half-float extensions+ (`render/gles2/pixel_format.c`). Rendering into a 10-bit dmabuf and an FP16+ texture also needs `EXT_color_buffer_half_float`; Phase 0 checks it on our+ drivers.+* **The protocols are advertised but SDR-only.** `src/extra_protocols.c:252-259`+ builds the colour manager's lists from the renderer, and GLES2 reports no+ input colour transforms, so the transfer function and primaries lists are+ empty and `parametric` is off. `rediwm_surface_edge_is_srgb` and+ `node_surface.c` already read per-surface descriptions; nothing draws+ differently with them.+* **The output format is never set.** `wlr_output_configure_primary_swapchain`+ (`src/scene_output.c:313`) picks the default 8-bit format; the+ `setRenderFormat` binding exists (`src/wlr/output.zig:208`) but is unused.+* **Glass blurs encoded values.** `scene_pass_backdrop.c` never linearizes.+* **The hardware cursor would be wrong.** wlroots colour-converts a cursor+ for an HDR output by passing `color_transform` to the cursor's render pass+ (`types/output/cursor.c:259`), but the GLES2 renderer ignores that option+ (`features.output_color_transform = false`, never read in `render/gles2/`).+ An sRGB cursor would go out as PQ.+* **Output capture would be wrong.** Output screencopy and ext-image-copy+ copy the committed buffer through the renderer with no conversion. Window+ capture (`src/capture/window_source.zig`) renders through our pass and can+ render SDR directly.+* **Direct scanout ignores colour.** `try_scanout` (`src/scene_output.c:102`)+ would put an sRGB client buffer straight onto a PQ output. wlroots' scene+ had `color_management_is_scanout_allowed` for this.+* **Night light uses the KMS gamma table** (`src/output/frame.zig`, the+ `color_transform` in the output state). On a PQ signal that table is wrong.++## Off means off++With every output at `hdr = off`, nothing changes for anyone:++* No HDR GL program is compiled. HDR programs are built on demand like the+ polygon ones, since each linked program costs about 140 KiB of RSS.+* No FP16 buffers, 8-bit render format, no image description in any commit.+* Frames with only sRGB surfaces are byte-identical to today's (scene-pass+ tests plus a before/after screenshot diff), and idle CPU and RAM stay at the+ baseline.++The one possible exception is D3 (what the colour manager advertises).++## Pipeline when on++Per HDR output:++1. **Blend in linear light into an FP16 buffer.** It is retained, so it is+ only redrawn where there is damage. Primaries are BT.2020 (D1), and 1.0 is+ the SDR white level (D2).+2. **Inputs convert on sampling.** sRGB textures (shell buffers, Cairo text,+ wallpaper, X11 clients, sRGB Wayland clients) get unpremultiplied, decoded,+ converted from BT.709 to BT.2020, scaled by the white level and+ premultiplied again. Theme colours (`col.Straight`) and analytic draws+ (rects, shadows, the veil, dim) get the same treatment in their uniforms.+ Surfaces with a parametric description (Phase 4) decode their own transfer+ function and primaries.+3. **Glass blurs in linear light**, in FP16 backdrop images.+4. **Encode** the damaged region from the FP16 buffer into the+ `XRGB2101010` swapchain buffer: gamut clip, PQ encode, and night light as+ a linear-light RGB multiply. The age damage of the swapchain buffer is+ re-encoded from the retained FP16 buffer, so nothing is drawn twice.+5. **Commit** the image description (PQ, BT.2020, mastering luminance from+ the EDID) with the frame through `Output.commitFrameState`, as a commit+ reason in `commitIsRedundant`.++Memory when on: about 8 bytes per pixel extra for the FP16 buffer (about+63 MiB at 3840x2160), FP16 glass backdrops, and the HDR programs. The 10-bit+swapchain is the same size as the 8-bit one. This is the main reason HDR is+opt-in.++Side channels:++* **Cursor:** HDR outputs use the software cursor+ (`wlr_output_lock_software_cursors`) until wlroots' GLES2 renderer honours+ pass colour transforms or we render cursor buffers ourselves. The software+ cursor is drawn by our pass (`scene_output_effects.c`), so it gets step 2.+* **Direct scanout:** on an HDR output, allowed only for a surface whose+ description matches the output's.+* **Capture:** an owned output capture source that renders the output through+ the pass in SDR mode into the client's 8-bit buffer. This follows how+ `WindowCaptureSource` replaced wlroots' helper. Capture clients only ever+ see SDR formats. IPC screenshots also get SDR, with a raw option for pixel+ probe tests.+* **Xwayland:** X11 clients are sRGB and composited at the white level.+* **Lock screen:** SDR content at the white level, on the same output state+ (no mode flip on lock).+* **Greeter:** never sets HDR, whatever the output config says.+* **Brightness:** laptop panels with HDR keep backlight control; the white+ level is separate from brightness.++## Decisions++* **D1, working primaries:** BT.2020 (recommended; it is the signal's gamut,+ and the encode is then just a clip and PQ) or BT.709 with negative values+ (scRGB-style; cheaper for an all-sRGB desktop, but the encode needs a+ matrix).+* **D2, SDR white level:** per output (recommended, since the setting already+ lives on the output), default 203 nits (BT.2408 reference white), capped+ below the EDID's peak.+* **D3, colour manager when HDR is off.** Its lists are global and sent when a+ client binds, not per output. Recommended: once Phase 4 lands, advertise+ parametric support always, send each surface its output's description as+ preferred (sRGB on SDR outputs, so well-behaved clients send SDR there), and+ tone map with a cheap clip and knee, built on demand, if HDR content lands+ on an SDR output anyway. The alternative, advertising only when some output+ has HDR at startup, keeps today's protocol behaviour exactly but means+ protocol support needs a restart after turning HDR on.+* **D4, `auto`:** ship `off`/`on` first. Add `auto` (on when the EDID says+ PQ) only after tone mapping and brightness have been seen on several+ monitors.+* **D5, blend look:** linear blending makes translucency and antialiased+ edges (window_bg 0.80, shadows, text) look slightly different from the SDR+ path, which blends encoded values. Accept it (recommended; other HDR+ compositors do the same), or blend SDR content in an encoded space and+ convert after (exact match, but HDR content then blends wrongly).++## Phases++Each phase ends testable on real hardware, and the work can stop after any of+them with a working compositor. Week counts are rough guesses for one person.++| Phase | Work | Exit check | Est. |+|---|---|---|---|+| 0. Hardware recon | `drm_info` (`Colorspace`, `HDR_OUTPUT_METADATA`, plane formats) and `edid-decode` (static metadata, luminance) on the test monitor; GL extensions for 10-bit and FP16 rendering on Intel/AMD/NVIDIA; read wlroots' `supported_*` bits for the output. The code-side questions are answered above. | Written list of what the test monitor and drivers support | 2-3 days |+| 1. Plumbing | `hdr = off/on` and `sdr_white` in `[[outputs]]` (`config/output_config.zig`, `output_save.zig`), `rediwm-msg output-config`, the Settings display page (`control_center/sections/display.zig`, greyed out when the output cannot do HDR), `Output.applyAndPersist`. No rendering change. | Config round-trips; Settings shows availability; frames unchanged | 1 wk |+| 2. Linear pass | FP16 blend buffer, input conversion for every draw kind, theme colours, linear glass, software cursor; HDR programs on demand. Encode back to sRGB for now. | With HDR forced on, an SDR monitor looks like SDR within D5's tolerance (screenshot diff); off is byte-identical | 2-3 wks |+| 3. Encode and scan out | PQ encode, `XRGB2101010` render format with a test-commit fallback, image description commit and commit reason, night light in the encode, software cursor lock, scanout gate. | PQ test pattern and a known HDR still correct on a real monitor; toggling HDR drops no frames | 2 wks |+| 4. Client content | Parametric descriptions backed by the pass (sRGB, gamma 2.2, linear, PQ, BT.2020) replacing the renderer lists in `extra_protocols.c`; per-surface decode; preferred description per output; color-representation-v1 YCbCr coefficients and range; D3's tone map. dmabuf and explicit sync paths unchanged. | mpv, a Proton HDR game (Wayland driver) and browser HDR video right under HDR and cleanly SDR elsewhere | 2-3 wks |+| 5. Side channels | Owned output capture source in SDR, IPC screenshot SDR/raw, lock and greeter rules, mixed HDR/SDR outputs and the camera across them. | grim, wf-recorder, OBS and portal sharing look right with HDR on; every row of the README protocol table is correct under HDR or documented SDR-only | 1-2 wks |+| 6. Hardening | Hardware checklist in `TESTING.md` (nested and headless cannot exercise HDR), pixel probes through the raw IPC read, idle CPU and RAM re-measured with HDR off and on. | HDR off at the baseline; HDR on cost written down | 1 wk |++## Risks++* **Drivers.** HDR needs atomic KMS and both connector properties; NVIDIA and+ older kernels differ. FP16 render targets are an extension in GLES2.+* **Tone mapping and brightness.** Other compositors kept iterating after+ first shipping. The audit cites GNOME 48's notes that HDR often disables+ hardware brightness on laptops (not checked here).+* **Owning colour science.** Transfer functions, gamut maps and PQ encode are+ ours to get right; wlroots' Vulkan shaders (`render/vulkan/shaders/`) are a+ reference, not code we can call.+* **Cost when on.** FP16 doubles blend and backdrop memory and bandwidth.+ Measure after Phase 2, not at the end.+* **Test coverage.** Everything past Phase 2 needs a real HDR monitor, which+ makes regressions easy to miss. Phase 6's raw probes are the guard.++## Sources++* Discussion #27, the original audit.+* wlroots 0.20.2: `types/output/output.c`, `types/output/cursor.c`,+ `backend/drm/atomic.c`, `backend/drm/util.c`, `render/gles2/`,+ `include/wlr/render/pass.h`, `include/wlr/render/vulkan.h`.+* Jay compositor HDR docs (the OpenGL renderer has no colour management):+ docs.rs/crate/jay-compositor/1.15.0/source/book/src/hdr.md.+* ITU-R BT.2408 (203 nit reference white).diff --git a/docs/wiki/Theme.md b/docs/wiki/Theme.mdindex 85a035b..39fe4ff 100644--- a/docs/wiki/Theme.md+++ b/docs/wiki/Theme.md@@ -52,6 +52,23 @@ 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.+**Dark mode** stays independent of following: apps keep the palette, and web+pages follow Dark mode. Chromium browsers (Brave, Chrome) in GTK or Qt mode take+only some colors from the toolkit and draw the rest (print preview, dropdown+lists, settings pages, menu shortcuts) from their own light or dark scheme, so+toolkit colors of the other darkness gave white-on-white text. They therefore+get colors matching Dark mode: the palette itself when its darkness agrees,+otherwise a muted version of it with the same tint and accent (light grey, L*+80 window and 88 toolbar, with dark text; or dark grey with light text).+Chromium's own pages stay its near-white or dark scheme. Its tab strip (its+frame) is kept 14 L* darker than its toolbar, which is also the active tab+(Chrome's own themes keep about 10), going no darker than black; beside a+near-black toolbar it is lighter instead. In GTK mode a switch shows at once:+each theme's `gtk.css` holds the light colors and `gtk-dark.css` the dark ones,+and Chromium asks GTK for the dark variant under a dark preference. In Qt mode+Brave reads Qt colors only when it starts, so restart it after changing Dark+mode or the theme.+GTK following installs two reusable themes, `RediWM-a` and `RediWM-b`, under`$XDG_DATA_HOME/themes` (else `~/.local/share/themes`). Changes select the nexttheme only after its files are ready. RediWM updates `gtk-theme-name` in GTK3/4@@ -94,9 +111,13 @@ theme package is patched and the dark-mode preference is never flipped.**Qt:** needs **qt5ct** (Qt 5) or **qt6ct** (Qt 6). The toolkit configs selectnative `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+preferences are kept. The RediWM style is Fusion except for title bars, which+Chromium's Qt mode (Brave, Chrome) samples as its whole frame while its toolbar+and active tab take the Button colour. Fusion fills an active title bar with the+accent; the RediWM style uses the window colour moved that 14 L* away from+Button, in both active and inactive bars. Inside a Chromium browser (which loads+`libqt5_shim.so` or `libqt6_shim.so`) the style replaces the palette with the+`[Chromium]` group RediWM writes into the scheme while following. It is builtper 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 throughdiff --git a/docs/wiki/Using-RediWM.md b/docs/wiki/Using-RediWM.mdindex 0003a91..b839a5a 100644--- a/docs/wiki/Using-RediWM.md+++ b/docs/wiki/Using-RediWM.md@@ -48,6 +48,10 @@ centred above three. Previews preserve aspect ratios and fill the screen withonly narrow gaps between them. Offscreen and minimized windows are included; hidden tabsare excluded.+Hovering a preview enlarges it by about 10% and lifts it above its neighbours;+scrolling up over it zooms it further around the pointer, and scrolling down+returns it to the hover size.+Click a preview, or select one with the arrow keys and press Enter, to visit it.Selecting a minimized window restores it. Escape, Super+A again, or clickingempty space returns to the previous view and leaves minimized windows minimized.diff --git a/src/config/app_theme.zig b/src/config/app_theme.zigindex db88fdb..9be518e 100644--- a/src/config/app_theme.zig+++ b/src/config/app_theme.zig@@ -14,6 +14,9 @@ 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");+test {+ _ = follow;+}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);@@ -100,16 +103,96 @@ pub fn isDark(p: Palette) bool {return contrast(p.bg)[0] == 255;}-fn contrast(c: Color) Color {- var luminance: f32 = 0;+fn luminance(c: Color) f32 {+ var y: f32 = 0;for (c, [_]f32{ 0.2126, 0.7152, 0.0722 }) |byte, weight| {const v = @as(f32, @floatFromInt(byte)) / 255;- luminance += weight * (if (v <= 0.04045) v / 12.92 else std.math.pow(f32, (v + 0.055) / 1.055, 2.4));+ y += weight * (if (v <= 0.04045) v / 12.92 else std.math.pow(f32, (v + 0.055) / 1.055, 2.4));+ }+ return y;+}++fn contrast(c: Color) Color {+ return if (luminance(c) > 0.179) .{ 0, 0, 0 } else .{ 255, 255, 255 };+}++/// CIE L*: 0 is black, 100 white.+fn lightness(c: Color) f32 {+ const y = luminance(c);+ return if (y > 216.0 / 24389.0) 116 * std.math.cbrt(y) - 16 else y * 24389.0 / 27.0;+}++/// L* between a browser's tab strip and its toolbar, which is also the active+/// tab. Chrome's own themes keep 10, but in RediWM's darker palettes that left+/// the active tab hard to find, and Chromium's Qt mode lifts a dark frame.+pub const frame_distance: f32 = 14;++/// Chromium's frame (its tab strip) beside `toolbar`: `bg`, darkened until the+/// toolbar stands `frame_distance` above it (at most to black), or lightened+/// when the toolbar is too dark for even half of that. src/qt_style/ derives+/// the Qt frame the same way.+pub fn frame(bg: Color, toolbar: Color) Color {+ const goal = lightness(toolbar);+ if (lightness(bg) <= goal - frame_distance) return bg;+ const darken = goal >= frame_distance / 2;+ const target: Color = if (darken) .{ 0, 0, 0 } else .{ 255, 255, 255 };+ var low: f32 = 0;+ var high: f32 = 1;+ for (0..16) |_| {+ const mid = (low + high) / 2;+ const l = lightness(blend(target, bg, mid));+ if (if (darken) l <= goal - frame_distance else l >= goal + frame_distance) high = mid else low = mid;+ }+ return blend(target, bg, high);+}++/// `c` moved toward white or black until its L* reaches `goal`.+fn toLightness(c: Color, goal: f32) Color {+ const lighten = lightness(c) < goal;+ const target: Color = if (lighten) .{ 255, 255, 255 } else .{ 0, 0, 0 };+ var low: f32 = 0;+ var high: f32 = 1;+ for (0..16) |_| {+ const mid = (low + high) / 2;+ const l = lightness(blend(target, c, mid));+ if (if (lighten) l >= goal else l <= goal) high = mid else low = mid;}- return if (luminance > 0.179) .{ 0, 0, 0 } else .{ 255, 255, 255 };+ return blend(target, c, high);+}++/// The colours Chromium browsers get for a light or dark preference. Chromium+/// takes only some colours from the toolkit and draws the rest (print preview,+/// dropdown lists, settings pages, menu shortcuts) from its own scheme for the+/// preference, so toolkit colours of the other darkness gave white text on+/// white. The variant keeps the palette's tint and accent at muted levels,+/// neither white nor black; a palette that already matches is kept as it is.+pub fn browserPalette(p: Palette, dark: bool) Palette {+ if (isDark(p) == dark) return p;+ const Levels = struct { bg: f32, toolbar: f32, hover: f32, border: f32, fg: f32 };+ const l: Levels = if (dark)+ .{ .bg = 16, .toolbar = 24, .hover = 30, .border = 38, .fg = 90 }+ else+ .{ .bg = 80, .toolbar = 88, .hover = 82, .border = 64, .fg = 14 };+ const bg = toLightness(p.bg, l.bg);+ const fg = toLightness(p.bg, l.fg);+ const toolbar = toLightness(p.bg, l.toolbar);+ return .{+ .bg = bg,+ .fg = fg,+ .toolbar = toolbar,+ .sidebar = bg,+ .sidebar_fg = fg,+ .item = toolbar,+ .hover = toLightness(p.bg, l.hover),+ .border = toLightness(p.bg, l.border),+ .accent = p.accent,+ .on_accent = p.on_accent,+ .danger = p.danger,+ .dim = blend(fg, bg, 0.5),+ };}-fn hex(c: Color) [7]u8 {+pub fn hex(c: Color) [7]u8 {const digits = "0123456789abcdef";var result: [7]u8 = undefined;result[0] = '#';@@ -181,9 +264,24 @@ pub fn gtkColors(a: Allocator, p: Palette, gtk4: bool) ![]u8 {}pub fn qtColors(a: Allocator, p: Palette) ![]u8 {+ return qtSection(a, "ColorScheme", p);+}++/// The scheme qt5ct/qt6ct read, plus a `[Chromium]` group that only RediWM's+/// Qt style reads: inside Chromium browsers it replaces the palette, because+/// their colours have to match the light/dark preference (`browserPalette`).+pub fn qtColorsWithBrowser(a: Allocator, p: Palette, browser: Palette) ![]u8 {+ const scheme = try qtSection(a, "ColorScheme", p);+ defer a.free(scheme);+ const chromium = try qtSection(a, "Chromium", browser);+ defer a.free(chromium);+ return std.mem.concat(a, u8, &.{ scheme, "\n", chromium });+}++fn qtSection(a: Allocator, section: []const u8, p: Palette) ![]u8 {var out: std.ArrayList(u8) = .empty;errdefer out.deinit(a);- try out.appendSlice(a, "[ColorScheme]\n");+ try appendFmt(&out, a, "[{s}]\n", .{section});// QPalette::ColorRole order, including NoRole, PlaceholderText and Qt6's// Accent. Extra roles are ignored by Qt5 and older Qt6.// QPalette has no separate foreground for AlternateBase. A contrasting@@ -414,12 +512,13 @@ pub 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);+ return applyRevision(a, io, home, toolkit, p, support, null, 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 {+/// when only the palette in its colors/ subdirectory changed. `browser` adds+/// the Chromium colours (`qtColorsWithBrowser`) while following.+pub fn applyRevision(a: Allocator, io: Io, home: []const u8, toolkit: Toolkit, p: Palette, support: QtSupport, revision: ?[]const u8, browser: ?Palette) !void {var arena: std.heap.ArenaAllocator = .init(a);defer arena.deinit();const alloc = arena.allocator();@@ -433,7 +532,7 @@ pub fn applyRevision(a: Allocator, io: Io, home: []const u8, toolkit: Toolkit, p},.qt => {if (!support.qt5 and !support.qt6) return error.QtToolsMissing;- const colors = try qtColors(alloc, p);+ const colors = if (browser) |b| try qtColorsWithBrowser(alloc, p, b) else try qtColors(alloc, p);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" });@@ -490,6 +589,44 @@ test "app palettes composite straight alpha and choose readable accent text" {try std.testing.expectEqual((theme.Theme{}).window_fg, t.window_fg);}+test "browser frames stand frame_distance below the toolbar" {+ // A frame already far enough below is kept.+ try std.testing.expectEqual(Color{ 0x10, 0x11, 0x12 }, frame(.{ 0x10, 0x11, 0x12 }, .{ 0x35, 0x36, 0x3a }));+ try std.testing.expectEqual(Color{ 0xc0, 0xc0, 0xc0 }, frame(.{ 0xc0, 0xc0, 0xc0 }, .{ 255, 255, 255 }));+ // RediWM's default window colour sits too close to the toolbar.+ const dark = frame(.{ 0x18, 0x1c, 0x22 }, .{ 0x22, 0x28, 0x2e });+ try std.testing.expect(lightness(.{ 0x22, 0x28, 0x2e }) - lightness(dark) >= frame_distance);+ try std.testing.expect(lightness(.{ 0x22, 0x28, 0x2e }) - lightness(dark) < frame_distance + 1);+ const light = frame(.{ 0xf5, 0xf5, 0xf5 }, .{ 0xf0, 0xf0, 0xf0 });+ try std.testing.expect(lightness(.{ 0xf0, 0xf0, 0xf0 }) - lightness(light) >= frame_distance);+ // Too dark a toolbar for the whole distance: black.+ try std.testing.expectEqual(Color{ 0, 0, 0 }, frame(.{ 0x18, 0x1c, 0x22 }, .{ 0x1d, 0x22, 0x29 }));+ // Beside a black toolbar the frame turns lighter instead.+ try std.testing.expect(lightness(frame(.{ 0, 0, 0 }, .{ 0, 0, 0 })) >= frame_distance);+}++test "browser colours match the preference with muted levels, keeping the accent" {+ const dark = Palette.fromTheme(.{});+ try std.testing.expect(isDark(dark));+ try std.testing.expectEqual(dark, browserPalette(dark, true));+ const light = browserPalette(dark, false);+ try std.testing.expect(!isDark(light));+ try std.testing.expectEqual(dark.accent, light.accent);+ // Grey rather than white, with dark text.+ try std.testing.expect(@abs(lightness(light.bg) - 80) < 1 and @abs(lightness(light.toolbar) - 88) < 1);+ try std.testing.expect(lightness(light.fg) < 15);+ // The tab strip still stands below the active tab.+ try std.testing.expect(lightness(light.toolbar) - lightness(frame(light.bg, light.toolbar)) >= frame_distance);+ // And the other way round for a light theme under a dark preference.+ const back = browserPalette(light, true);+ try std.testing.expect(isDark(back) and lightness(back.fg) > 85);+ try std.testing.expectEqual(light, browserPalette(light, false));+ const qt = try qtColorsWithBrowser(std.testing.allocator, dark, light);+ defer std.testing.allocator.free(qt);+ try std.testing.expectEqualStrings(&hex(light.fg), iniValue(qt, "Chromium", "active_colors").?[0..7]);+ try std.testing.expectEqualStrings(&hex(dark.fg), iniValue(qt, "ColorScheme", "active_colors").?[0..7]);+}+test "app colors edits are idempotent and scoped to their INI section" {const a = std.testing.allocator;const original = "# keep\n[Other]\ncustom_palette=false\n[Appearance]\nstyle=Old\ncustom_palette=false\n[Fonts]\ngeneral=Example\n";diff --git a/src/config/app_theme_follow.zig b/src/config/app_theme_follow.zigindex 6248985..fc84e9f 100644--- a/src/config/app_theme_follow.zig+++ b/src/config/app_theme_follow.zig@@ -28,24 +28,102 @@ pub fn current(a: Allocator, io: Io, home: []const u8) !?u1 {return null;}-pub fn css(a: Allocator, p: app.Palette, gtk4: bool) ![]u8 {+/// One slot stylesheet. GTK loads gtk-dark.css instead of gtk.css when an+/// application prefers a dark theme, which Chromium browsers set from the+/// light/dark preference: `dark` picks the Chromium colours for that file+/// (`app.browserPalette`). Everything else follows the palette in both.+pub fn css(a: Allocator, p: app.Palette, gtk4: bool, dark: 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);+ const chromium = try chromiumCss(a, app.browserPalette(p, dark));+ defer a.free(chromium);// 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")+ (if (app.isDark(p)) "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 });+ (if (app.isDark(p)) "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{s}", .{ base, colors, private, chromium });+}++/// Chromium's GTK mode renders these nodes (ui/gtk/gtk_color_mixers.cc), each+/// under a `window.background` root, with a `chromium` class on every node.+/// Colours are literal: the browser palette may differ from the named colours+/// and from the Adwaita base, which would otherwise show through.+fn chromiumCss(a: Allocator, b: app.Palette) ![]u8 {+ const w = "window.background.chromium";+ const toolbar = app.hex(b.toolbar);+ const fg = app.hex(b.fg);+ const dim = app.hex(b.dim);+ const border = app.hex(b.border);+ const accent = app.hex(b.accent);+ const on_accent = app.hex(b.on_accent);+ const view = app.hex(b.bg);+ return std.fmt.allocPrint(a,+ // The window is the toolbar and the active tab; a headerbar the frame,+ // the tab strip. The address field stays apart from that toolbar.+ w ++ ", " ++ w ++ " window.background {{ background-color: {[toolbar]s}; color: {[fg]s}; }}\n" +++ w ++ " headerbar, " ++ w ++ " headerbar:backdrop {{ background-color: {[frame]s}; background-image: none; color: {[fg]s}; border-color: {[border]s}; }}\n" +++ w ++ " headerbar label.title, " ++ w ++ " headerbar:backdrop label.title {{ color: {[fg]s}; }}\n" +++ // Direct labels only: a menu item's label inherits its disabled colour.+ w ++ " > label, " ++ w ++ " spinner, " ++ w ++ " button.image-button, " ++ w ++ " button.flat.scale image {{ color: {[fg]s}; }}\n" +++ w ++ " label:disabled, " ++ w ++ " spinner:disabled {{ color: {[dim]s}; }}\n" +++ w ++ " label.link:link {{ color: {[accent]s}; }}\n" +++ w ++ " entry, " ++ w ++ " textview.view, " ++ w ++ " textview.view text, " ++ w ++ " treeview.view {{ background-color: {[view]s}; color: {[fg]s}; border-color: {[border]s}; }}\n" +++ w ++ " entry:focus {{ border-color: {[accent]s}; }}\n" +++ w ++ " textview.view:disabled text {{ color: {[dim]s}; }}\n" +++ w ++ " textview.view text selection, " ++ w ++ " treeview.view:selected, " ++ w ++ " treeview.view:selected label {{ background-color: {[accent]s}; color: {[on_accent]s}; }}\n" +++ w ++ " button, " ++ w ++ " button:backdrop {{ background-color: {[item]s}; background-image: none; box-shadow: none; color: {[fg]s}; border-color: {[border]s}; }}\n" +++ w ++ " button label {{ color: {[fg]s}; }}\n" +++ w ++ " button:disabled label {{ color: {[dim]s}; }}\n" +++ w ++ " button.toggle:checked {{ background-color: {[accent]s}; color: {[on_accent]s}; }}\n" +++ w ++ " menu {{ background-color: {[toolbar]s}; color: {[fg]s}; border-color: {[border]s}; }}\n" +++ w ++ " menu menuitem, " ++ w ++ " menu menuitem label, " ++ w ++ " menu menuitem radio, " ++ w ++ " menu menuitem cellview {{ color: {[fg]s}; }}\n" +++ w ++ " menu menuitem:hover {{ background-color: {[accent]s}; color: {[on_accent]s}; }}\n" +++ w ++ " menu menuitem:hover label, " ++ w ++ " menu menuitem:hover cellview {{ color: {[on_accent]s}; }}\n" +++ w ++ " menu menuitem:disabled label {{ color: {[dim]s}; }}\n" +++ // Shortcuts: a little quieter than the item, still readable.+ w ++ " menu menuitem accelerator {{ color: alpha(currentColor, 0.8); }}\n" +++ w ++ " separator {{ background-color: {[border]s}; color: {[border]s}; }}\n" +++ w ++ " frame border, " ++ w ++ " box.frame {{ border-color: {[border]s}; }}\n" +++ w ++ " scrollbar trough, " ++ w ++ " statusbar {{ background-color: {[view]s}; }}\n" +++ w ++ " scrollbar slider {{ background-color: {[dim]s}; }}\n" +++ w ++ " scale trough {{ background-color: {[border]s}; }}\n" +++ w ++ " scale highlight {{ background-color: {[accent]s}; }}\n" +++ w ++ " notebook tab:checked {{ background-color: {[toolbar]s}; }}\n", .{+ .toolbar = &toolbar,+ .frame = &app.hex(app.frame(b.bg, b.toolbar)),+ .fg = &fg,+ .dim = &dim,+ .border = &border,+ .accent = &accent,+ .on_accent = &on_accent,+ .view = &view,+ .item = &app.hex(b.item),+ });+}++test "Chromium's GTK colours follow the requested darkness, the frame stands apart, and menu labels keep their state" {+ const a = std.testing.allocator;+ const p = app.Palette.fromTheme(.{});+ for ([_]bool{ false, true }) |gtk4| for ([_]bool{ false, true }) |dark| {+ const style = try css(a, p, gtk4, dark);+ defer a.free(style);+ const b = app.browserPalette(p, dark);+ const frame = app.hex(app.frame(b.bg, b.toolbar));+ try std.testing.expect(!std.mem.eql(u8, &frame, &app.hex(b.toolbar)));+ var buf: [96]u8 = undefined;+ const rule = try std.fmt.bufPrint(&buf, "headerbar:backdrop {{ background-color: {s};", .{&frame});+ try std.testing.expect(std.mem.indexOf(u8, style, rule) != null);+ const window = try std.fmt.bufPrint(&buf, "window.background.chromium window.background {{ background-color: {s}; color: {s}; }}", .{ &app.hex(b.toolbar), &app.hex(b.fg) });+ try std.testing.expect(std.mem.indexOf(u8, style, window) != null);+ try std.testing.expect(std.mem.indexOf(u8, style, "window.background.chromium label {") == null);+ try std.testing.expect(std.mem.indexOf(u8, style, "window.background.chromium > label") != null);+ // The rest of the slot follows the palette in both files.+ try std.testing.expect(std.mem.indexOf(u8, style, "gtk-contained-dark.css") != null or std.mem.indexOf(u8, style, "Default-dark.css") != null);+ };}const define = "@define-color ";@@ -94,26 +172,31 @@ pub fn apply(a: Allocator, io: Io, home: []const u8, data: []const u8, p: app.Pavar 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) };+ // Per GTK version: gtk.css, then gtk-dark.css.+ const styles = [_][2][]const u8{+ .{ try css(mem, p, false, false), try css(mem, p, false, true) },+ .{ try css(mem, p, true, false), try css(mem, p, true, 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);+ for ([_][]const u8{ "gtk-3.0", "gtk-4.0" }, styles) |version, pair| {+ for ([_][]const u8{ "gtk.css", "gtk-dark.css" }, pair) |file, style| {+ const path = try std.fs.path.join(mem, &.{ data, "themes", name(old), version, file });+ 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);+ for ([_][]const u8{ "gtk-3.0", "gtk-4.0" }, styles) |version, pair| {+ for ([_][]const u8{ "gtk.css", "gtk-dark.css" }, pair) |file, style| {+ const path = try std.fs.path.join(mem, &.{ data, "themes", name(slot), version, file });+ try tx.add(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);diff --git a/src/config_runtime/app_colors.zig b/src/config_runtime/app_colors.zigindex f541a7b..d3244d1 100644--- a/src/config_runtime/app_colors.zig+++ b/src/config_runtime/app_colors.zig@@ -16,6 +16,8 @@ pub const State = struct {result: ?worker.Result = null,failure: ?anyerror = null,palette: ?app.Palette = null,+ /// The preference the last follow export chose Chromium's Qt colours for.+ exported_dark: ?bool = null,gtk_slot: ?u1 = null,qt_styles: worker.QtStyles = .{},@@ -32,11 +34,14 @@ pub fn gtkTheme(server: *Server) ?[]const u8 {return if (server.app_colors.gtk_slot) |slot| app.follow.name(slot) else null;}+/// `dark_mode` also picks the Chromium colours exported while following+/// (`app.browserPalette`), so a change to it exports again.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;+ state.exported_dark = null;return;}if (state.job != null) {@@ -45,7 +50,8 @@ pub fn sync(server: *Server) void {}const palette = app.Palette.fromTheme(theme.global);if (state.palette) |last| {- if (state.failure == null and std.meta.eql(last, palette)) return;+ const same_dark = state.exported_dark == null or state.exported_dark.? == server.config.compositor.dark_mode;+ if (state.failure == null and same_dark and std.meta.eql(last, palette)) return;}start(server, .follow) catch |err| fail(server, err);}@@ -54,7 +60,7 @@ 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 });+ const job = try worker.Job.create(server.io, server.environ, action, app.Palette.fromTheme(theme.global), server.config.compositor.dark_mode, .{ 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();@@ -94,8 +100,12 @@ fn ready(_: c_int, _: wl.EventMask, server: *Server) c_int {const changed = state.gtk_slot == null or state.gtk_slot.? != slot;state.gtk_slot = slot;state.palette = job.palette;+ state.exported_dark = if (result.qt_error == null and (result.support.qt5 or result.support.qt6)) job.dark else null;if (changed) @import("../session/settings_portal.zig").emitGtkTheme(server);- } else state.palette = null;+ } else {+ state.palette = null;+ state.exported_dark = null;+ }} else |err| fail(server, err);const pending = state.pending;state.pending = false;diff --git a/src/config_runtime/app_theme.zig b/src/config_runtime/app_theme.zigindex 5b54816..19c1d35 100644--- a/src/config_runtime/app_theme.zig+++ b/src/config_runtime/app_theme.zig@@ -55,16 +55,18 @@ pub const Job = struct {env: std.process.Environ,action: Action,palette: config.Palette,+ /// The light/dark preference, which picks the Chromium colours.+ dark: bool,styles: [2]bool,fd: c_int,thread: ?std.Thread = null,result: anyerror!Result = error.NotFinished,- pub fn create(io: std.Io, env: std.process.Environ, action: Action, palette: config.Palette, styles: [2]bool) !*Job {+ pub fn create(io: std.Io, env: std.process.Environ, action: Action, palette: config.Palette, dark: bool, 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, .action = action, .palette = palette, .styles = styles, .fd = fd };+ self.* = .{ .io = io, .env = env, .action = action, .palette = palette, .dark = dark, .styles = styles, .fd = fd };return self;}@@ -110,8 +112,12 @@ pub const Job = struct {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| {+ const browser = config.browserPalette(self.palette, self.dark);+ var hasher = std.hash.Wyhash.init(0);+ hasher.update(std.mem.asBytes(&self.palette));+ hasher.update(std.mem.asBytes(&browser));+ const revision = std.fmt.bufPrint(&buf, "{x:0>16}", .{hasher.final()}) catch unreachable;+ config.applyRevision(a, self.io, home, .qt, self.palette, support, revision, browser) catch |err| {result.qt_error = err;};}diff --git a/src/input/axis.zig b/src/input/axis.zigindex 13a4d25..1c91608 100644--- a/src/input/axis.zig+++ b/src/input/axis.zig@@ -49,13 +49,21 @@ pub fn processAxis(}if (input.server.polkit_dialog != null or input.server.screenshot_selector.output != null) return;if (input.server.world.mini_map.dragging) return;- if (input.server.switcher.active() or input.server.world.overview.active()) return;+ if (input.server.switcher.active()) return;// Flip here, before zoom/UI/client branches, so `invert_scroll` behaves// like `natural_scroll` would if libinput's device toggle applied to// this device: a single, uniform reversal rather than one per consumer.const invert = input.server.config.input.invert_scroll;const delta: f64 = if (invert) -raw_delta else raw_delta;const delta_discrete: i32 = if (invert) -raw_delta_discrete else raw_delta_discrete;+ if (input.server.world.overview.active()) {+ // Wheel zooms the preview under the pointer (wheel up enlarges).+ if (orientation == .vertical_scroll) {+ const steps = input.zoom_scroll.feed(delta_discrete, delta, @intCast(@intFromEnum(source)));+ if (steps != 0) input.server.world.overview.zoom(&input.server.world, steps, input.cursor.x, input.cursor.y);+ }+ return;+ }if (input.window_menu.node != null) {if (orientation == .vertical_scroll) input.window_menu.scroll(ui_scroll.axisDeltaPx(delta, delta_discrete));return;diff --git a/src/qt_style/rediwm_style.cpp b/src/qt_style/rediwm_style.cppindex b2feebe..b08a499 100644--- a/src/qt_style/rediwm_style.cpp+++ b/src/qt_style/rediwm_style.cpp@@ -1,19 +1,119 @@-// 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.+// RediWM's Qt style: Fusion, except for title bars. Chromium's Qt mode+// samples a title bar as its whole frame, the tab strip, while its toolbar and+// active tab take the Button colour. Fusion fills an active title bar with the+// palette's Highlight (the theme accent), which turned a following Brave's tab+// strip accent yellow, and the Window colour alone sits too close to Button to+// show which tab is active. Title bars are therefore the Window colour moved+// kFrameDistance away from Button, the same rule as frame() in+// src/config/app_theme.zig, which colours Chromium's GTK frame.+// Chromium also draws much of its UI from its own light or dark scheme, so in+// a Chromium browser the palette is replaced by the colours RediWM exports for+// the light/dark preference (the `[Chromium]` group of the qt5ct/qt6ct scheme,+// `browserPalette` in app_theme.zig); other applications keep the scheme.// Built per Qt major against the system Qt (build/qt_style.zig).+#include <QDir>#include <QPalette>#include <QProxyStyle>+#include <QSettings>#include <QStyleFactory>#include <QStyleOptionTitleBar>#include <QStylePlugin>+#include <cmath>+#include <cstring>+#include <link.h>namespace {+// L* between the frame and the toolbar (frame_distance in app_theme.zig).+constexpr double kFrameDistance = 14;++// CIE L*: 0 is black, 100 white.+double lightness(const QColor &c) {+ const auto linear = [](double v) { return v <= 0.04045 ? v / 12.92 : std::pow((v + 0.055) / 1.055, 2.4); };+ const double y = 0.2126 * linear(c.redF()) + 0.7152 * linear(c.greenF()) + 0.0722 * linear(c.blueF());+ return y > 216.0 / 24389.0 ? 116 * std::cbrt(y) - 16 : y * 24389.0 / 27.0;+}++QColor mix(const QColor &target, const QColor &c, double amount) {+ const auto channel = [&](int t, int v) { return int(std::lround(t * amount + v * (1 - amount))); };+ return QColor(channel(target.red(), c.red()), channel(target.green(), c.green()), channel(target.blue(), c.blue()));+}++// Window, darkened until Button stands kFrameDistance above it (at most to+// black), or lightened when Button is too dark for even half of that.+QColor frameColor(const QPalette &palette) {+ const QColor window = palette.color(QPalette::Active, QPalette::Window);+ const double goal = lightness(palette.color(QPalette::Active, QPalette::Button));+ if (lightness(window) <= goal - kFrameDistance)+ return window;+ const bool darken = goal >= kFrameDistance / 2;+ const QColor target = darken ? QColor(0, 0, 0) : QColor(255, 255, 255);+ double low = 0, high = 1;+ for (int i = 0; i < 16; i++) {+ const double mid = (low + high) / 2;+ const double l = lightness(mix(target, window, mid));+ if (darken ? l <= goal - kFrameDistance : l >= goal + kFrameDistance)+ high = mid;+ else+ low = mid;+ }+ return mix(target, window, high);+}++// Chromium's Qt mode runs through libqt5_shim.so or libqt6_shim.so, which+// Chrome, Brave and the other Chromium browsers load before Qt itself.+bool inChromium() {+ return dl_iterate_phdr(+ [](dl_phdr_info *info, size_t, void *) {+ const char *name = info->dlpi_name ? std::strrchr(info->dlpi_name, '/') : nullptr;+ return name && (std::strcmp(name, "/libqt5_shim.so") == 0 || std::strcmp(name, "/libqt6_shim.so") == 0) ? 1 : 0;+ },+ nullptr) != 0;+}++// The scheme qt5ct or qt6ct loads, which RediWM writes while following.+QString schemePath() {+ QString config = qEnvironmentVariable("XDG_CONFIG_HOME");+ if (!QDir::isAbsolutePath(config))+ config = QDir::homePath() + QStringLiteral("/.config");+ const QString tool = QStringLiteral("qt%1ct").arg(QT_VERSION_MAJOR);+ return QSettings(config + QLatin1Char('/') + tool + QLatin1Char('/') + tool + QStringLiteral(".conf"), QSettings::IniFormat)+ .value(QStringLiteral("Appearance/color_scheme_path"))+ .toString();+}++// Roles in QPalette::ColorRole order, as qt5ct/qt6ct schemes list them.+void applyBrowserColors(QPalette &palette) {+ const QString path = schemePath();+ if (path.isEmpty())+ return;+ QSettings scheme(path, QSettings::IniFormat);+ const struct {+ const char *key;+ QPalette::ColorGroup group;+ } groups[] = {{"Chromium/active_colors", QPalette::Active},+ {"Chromium/inactive_colors", QPalette::Inactive},+ {"Chromium/disabled_colors", QPalette::Disabled}};+ for (const auto &g : groups) {+ const QStringList colors = scheme.value(QLatin1String(g.key)).toStringList();+ for (int role = 0; role < colors.size() && role < QPalette::NColorRoles; role++) {+ const QColor color(colors[role].trimmed());+ if (role != QPalette::NoRole && color.isValid())+ palette.setColor(g.group, QPalette::ColorRole(role), color);+ }+ }+}+class Style : public QProxyStyle {public:- Style() : QProxyStyle(QStyleFactory::create(QStringLiteral("Fusion"))) {}+ Style() : QProxyStyle(QStyleFactory::create(QStringLiteral("Fusion"))), chromium_(inChromium()) {}++ using QProxyStyle::polish;+ void polish(QPalette &palette) override {+ QProxyStyle::polish(palette);+ if (chromium_)+ applyBrowserColors(palette);+ }void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter,const QWidget *widget) const override {@@ -22,13 +122,18 @@ public: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.+ // Fusion fills an active bar with Highlight and an inactive one with+ // Window: both get the frame colour, so focus never paints the accent.QStyleOptionTitleBar neutral(*bar);- neutral.palette.setColor(QPalette::Highlight, bar->palette.color(QPalette::Active, QPalette::Window));+ const QColor frame = frameColor(bar->palette);+ neutral.palette.setColor(QPalette::Highlight, frame);+ neutral.palette.setColor(QPalette::Window, frame);neutral.palette.setColor(QPalette::HighlightedText, bar->palette.color(QPalette::Active, QPalette::WindowText));QProxyStyle::drawComplexControl(control, &neutral, painter, widget);}++private:+ const bool chromium_;};} // namespacediff --git a/src/system_monitor/app_table.zig b/src/system_monitor/app_table.zigindex 31f1b74..de6170c 100644--- a/src/system_monitor/app_table.zig+++ b/src/system_monitor/app_table.zig@@ -108,7 +108,7 @@ fn paintRows(self: *App, cr: *c.cairo_t) void {label(cr, stateName(row.state), state_box);}if (count == 0) label(cr, if (snap.failed) tr("Process data unavailable") else tr("No matching processes"), .{ .x = list.x + pad, .y = list.y + 12, .w = content_w - 2 * pad, .h = row_h });- if (self.barGeometry()) |g| cairo.drawScrollbar(cr, scrollbar.look(g, self.bar, theme.global.scrollbar_width, theme.global));+ if (self.barGeometry()) |g| cairo.drawScrollbar(cr, scrollbar.look(g, self.bar, theme.global.scrollbar_width, theme.shellPalette()));}fn cell(self: *const App, column: usize, y: f32) Rect {diff --git a/src/world/overview.zig b/src/world/overview.zigindex 9b365cc..b6f9f3e 100644--- a/src/world/overview.zig+++ b/src/world/overview.zig@@ -10,12 +10,15 @@ const anim = @import("ui").anim;const sn = @import("../node.zig");const Self = @This();const cards_mod = @import("overview_cards.zig");+const hover_mod = @import("overview_hover.zig");const gpa = @import("../main.zig").gpa;saved: ?camera.Camera = null,destination: camera.Camera = .{},returning: bool = false,selected: ?u64 = null,+/// Preview under the pointer, magnified by `overview_hover.zig`.+hovered: ?u64 = null,activate: ?u64 = null,boosted: ?u64 = null,output: ?*Output = null,@@ -24,9 +27,11 @@ edges: [4]*sn.Buffer = undefined,pointer_x: f64 = 0,pointer_y: f64 = 0,cards: std.ArrayList(cards_mod.Card) = .empty,+lifts: std.ArrayList(hover_mod.Lift) = .empty,spread: anim.Anim = .{},pub const apply = cards_mod.apply;+pub const zoom = hover_mod.zoom;pub fn amount(self: *const Self, now: i64) f64 {return if (self.active()) std.math.clamp(self.spread.value(now), 0, 1) else 0;@@ -186,6 +191,7 @@ pub fn cancel(self: *Self, world: *World) void {fn finish(self: *Self, world: *World, accepted: bool) void {const chosen = if (accepted) self.activate else null;const boosted = self.boosted;+ hover_mod.restack(self, world);self.clear();world.snapCamera();if (find(world, chosen)) |top| {@@ -205,6 +211,7 @@ fn finish(self: *Self, world: *World, accepted: bool) void {fn clear(self: *Self) void {if (self.tree) |tree| tree.node.destroy();self.cards.deinit(gpa);+ self.lifts.deinit(gpa);self.* = .{};}@@ -228,18 +235,24 @@ pub fn update(self: *Self, world: *World, now: i64) bool {cards_mod.prepare(self, world) catch self.dismiss(world);if (self.cards.items.len == 0) self.dismiss(world);if (find(world, self.selected) == null) self.selected = if (self.cards.items.len > 0) self.cards.items[0].id else null;+ if (self.hovered) |id| if (cards_mod.find(self, id) == null) {+ self.hovered = null;+ };}+ if (!self.active()) return false;+ const magnifying = hover_mod.moving(self, now);for (self.cards.items) |card| if (find(world, card.id)) |top| top.applyVisualTransform(now);cards_mod.paint(self, now);- return moving or (self.active() and !self.spread.settled(now));+ return moving or magnifying or !self.spread.settled(now);}pub fn motion(self: *Self, world: *World, x: f64, y: f64) void {if (self.returning or (x == self.pointer_x and y == self.pointer_y)) return;self.pointer_x = x;self.pointer_y = y;- if (cards_mod.picked(self, world, x, y)) |id| {- if (self.selected == id) return;+ const id = cards_mod.picked(self, world, x, y);+ hover_mod.hover(self, world, id);+ if (id != null and self.selected != id) {self.selected = id;world.server.scheduleFrames();}diff --git a/src/world/overview_cards.zig b/src/world/overview_cards.zigindex 954b406..a01f42e 100644--- a/src/world/overview_cards.zig+++ b/src/world/overview_cards.zig@@ -12,6 +12,10 @@ pub const Card = struct {id: u64,target: layout.Rect = .{},presented: layout.Rect = .{},+ /// Hover/wheel magnification of `target` and its top-left offset (layout px).+ magnify: ui.anim.Anim = .{ .from = 1, .to = 1 },+ shift_x: ui.anim.Anim = .{},+ shift_y: ui.anim.Anim = .{},};pub fn find(self: *Self, id: u64) ?*Card {@@ -59,9 +63,10 @@ pub fn apply(self: *Self, top: *Top, x: i32, y: i32, scale: f64, now: i64) boolconst amount = self.amount(now);const normal = world.toLayout(@floatFromInt(x), @floatFromInt(y));const z = world.camera.zoom();- const displayed_scale = scale * z + (card.target.width / @as(f64, @floatFromInt(top.chrome_width)) - scale * z) * amount;- const left = normal.x + (card.target.x - normal.x) * amount;- const upper = normal.y + (card.target.y - normal.y) * amount;+ const goal = @import("overview_hover.zig").rect(card, now);+ const displayed_scale = scale * z + (goal.width / @as(f64, @floatFromInt(top.chrome_width)) - scale * z) * amount;+ const left = normal.x + (goal.x - normal.x) * amount;+ const upper = normal.y + (goal.y - normal.y) * amount;const p = world.toWorld(left, upper);const wx: i32 = @intFromFloat(@round(p.x));const wy: i32 = @intFromFloat(@round(p.y));diff --git a/src/world/overview_hover.zig b/src/world/overview_hover.zignew file mode 100644index 0000000..3f23577--- /dev/null+++ b/src/world/overview_hover.zig@@ -0,0 +1,163 @@+//! Overview hover and wheel magnification. The preview under the pointer grows+//! by `hover_factor` and the wheel zooms it further about the pointer. Each is a+//! presentation offset relative to the card's grid rectangle. A magnified preview+//! is drawn above its neighbours; `restack` puts the scene order back on exit.+const std = @import("std");+const World = @import("../World.zig");+const Top = @import("../Toplevel.zig");+const Self = @import("overview.zig");+const cards_mod = @import("overview_cards.zig");+const layout = @import("overview_layout.zig");+const scene_data = @import("../scene_data.zig");+const anim = @import("ui").anim;+const gpa = @import("../main.zig").gpa;++pub const hover_factor: f64 = 1.1;+/// Per wheel notch.+const wheel_step: f64 = 1.25;+/// Beyond the window's own size, wheel zoom stops at this multiple of the grid size.+const min_zoom_limit: f64 = 2;+const max_zoom_limit: f64 = 8;++/// A preview raised above the frame that was directly over it.+pub const Lift = struct { id: u64, above: ?u64 };++/// Grid rectangle plus magnification, in layout coordinates.+pub fn rect(card: *const cards_mod.Card, now: i64) layout.Rect {+ const f: f64 = card.magnify.value(now);+ return .{+ .x = card.target.x + card.shift_x.value(now),+ .y = card.target.y + card.shift_y.value(now),+ .width = card.target.width * f,+ .height = card.target.height * f,+ };+}++pub fn moving(self: *const Self, now: i64) bool {+ for (self.cards.items) |card| {+ if (!card.magnify.settled(now) or !card.shift_x.settled(now) or !card.shift_y.settled(now)) return true;+ }+ return false;+}++/// Follow the pointer: `id` is the preview under it, or null over empty space.+pub fn hover(self: *Self, world: *World, id: ?u64) void {+ if (self.hovered == id) return;+ world.server.input.zoom_scroll.reset();+ if (self.hovered) |old| if (cards_mod.find(self, old)) |card| settle(card, 1, 0, 0);+ self.hovered = id;+ if (id) |new| if (cards_mod.find(self, new)) |card| {+ if (Self.find(world, new)) |top| lift(self, top);+ const goal = fit(self, scaled(card.target, hover_factor));+ settle(card, hover_factor, goal.x - card.target.x, goal.y - card.target.y);+ };+ world.server.scheduleFrames();+}++/// Wheel zoom of the hovered preview, keeping the point under (x, y) fixed.+/// Negative steps (wheel up) zoom in.+pub fn zoom(self: *Self, world: *World, steps: i32, x: f64, y: f64) void {+ if (self.returning) return;+ const id = self.hovered orelse return;+ const card = cards_mod.find(self, id) orelse return;+ const top = Self.find(world, id) orelse return;+ const native = @as(f64, @floatFromInt(top.chrome_width)) / card.target.width;+ const limit = std.math.clamp(native, min_zoom_limit, max_zoom_limit);+ const current: f64 = card.magnify.to;+ const next = std.math.clamp(current * std.math.pow(f64, wheel_step, @floatFromInt(-steps)), hover_factor, @max(hover_factor, limit));+ if (@abs(next - current) < 1e-6) {+ world.server.input.zoom_scroll.reset();+ return;+ }+ const goal = if (next <= hover_factor + 1e-6) fit(self, scaled(card.target, hover_factor)) else blk: {+ const k = next / current;+ const from: layout.Rect = .{+ .x = card.target.x + card.shift_x.to,+ .y = card.target.y + card.shift_y.to,+ .width = card.target.width * current,+ .height = card.target.height * current,+ };+ break :blk fit(self, .{+ .x = x + (from.x - x) * k,+ .y = y + (from.y - y) * k,+ .width = from.width * k,+ .height = from.height * k,+ });+ };+ settle(card, next, goal.x - card.target.x, goal.y - card.target.y);+ world.server.scheduleFrames();+}++/// Undo the scene raises, newest first, before the overview lets go of its windows.+pub fn restack(self: *Self, world: *World) void {+ var i = self.lifts.items.len;+ while (i > 0) {+ i -= 1;+ const entry = self.lifts.items[i];+ const top = byId(world, entry.id) orelse continue;+ const above = byId(world, entry.above orelse continue) orelse continue;+ if (top.frame_tree.node.parent != above.frame_tree.node.parent) continue;+ top.frame_tree.node.placeBelow(&above.frame_tree.node);+ }+ self.lifts.clearRetainingCapacity();+}++fn lift(self: *Self, top: *Top) void {+ const node = &top.frame_tree.node;+ const parent = node.parent orelse return;+ var above: ?u64 = null;+ var found = false;+ var it = parent.children.iterator(.forward);+ while (it.next()) |sibling| {+ if (sibling == node) {+ found = true;+ continue;+ }+ if (!found) continue;+ const data = scene_data.SceneData.fromNode(sibling) orelse continue;+ if (data.role != .toplevel) continue;+ above = data.role.toplevel.id;+ break;+ }+ // Already above every other window: nothing to raise or restore.+ const id = above orelse return;+ self.lifts.append(gpa, .{ .id = top.id, .above = id }) catch return;+ node.raiseToTop();+}++fn byId(world: *World, id: u64) ?*Top {+ var it = world.toplevels.iterator(.forward);+ while (it.next()) |top| if (top.id == id) return top;+ return null;+}++fn settle(card: *cards_mod.Card, factor: f64, dx: f64, dy: f64) void {+ const now = anim.nowMs();+ const curve = anim.curveFor(.window_zoom);+ card.magnify.retargetTo(now, @floatCast(factor), curve);+ card.shift_x.retargetTo(now, @floatCast(dx), curve);+ card.shift_y.retargetTo(now, @floatCast(dy), curve);+}++fn scaled(r: layout.Rect, factor: f64) layout.Rect {+ const w = r.width * factor;+ const h = r.height * factor;+ return .{ .x = r.x + (r.width - w) / 2, .y = r.y + (r.height - h) / 2, .width = w, .height = h };+}++/// Keep a preview that fits inside the output; one larger than the output+/// covers it on that axis instead of leaving a gap at an edge.+fn fit(self: *const Self, r: layout.Rect) layout.Rect {+ const area = self.output.?.usableBox();+ var out = r;+ out.x = axis(r.x, r.width, @floatFromInt(area.x), @floatFromInt(area.width));+ out.y = axis(r.y, r.height, @floatFromInt(area.y), @floatFromInt(area.height));+ return out;+}++fn axis(start: f64, size: f64, lo: f64, span: f64) f64 {+ return if (size <= span)+ std.math.clamp(start, lo, lo + span - size)+ else+ std.math.clamp(start, lo + span - size, lo);+}diff --git a/tests/app_colors.py b/tests/app_colors.pyindex 96c4d6b..95b2cc7 100644--- a/tests/app_colors.py+++ b/tests/app_colors.py@@ -11,6 +11,7 @@ import sysimport shutilfrom ipc_client import IPCClient, spawn_compositor, stop_process+from settings_portal import SettingChangedWatcherfrom ui_driver import UIDriverfrom desktop_zoom import wait_for@@ -22,13 +23,77 @@ def qt_style_built(major):return (QT_STYLE_DIR / f"qt{major}/styles/librediwm-style.so").exists()+def lightness(color):+ """CIE L* of a #rrggbb colour."""+ linear = [(v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4)+ for v in (int(color[i:i + 2], 16) / 255 for i in (1, 3, 5))]+ y = 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]+ return 116 * y ** (1 / 3) - 16 if y > 216 / 24389 else y * 24389 / 27+++def near(a, b, tolerance=2):+ return all(abs(int(a[i:i + 2], 16) - int(b[i:i + 2], 16)) <= tolerance for i in (1, 3, 5))+++def chromium_bg(bg, dark):+ """Window colour of browserPalette (src/config/app_theme.zig): the palette's+ own when its darkness matches, else its tint at L* 80 (light) or 16."""+ if (lightness(bg) < 50) == dark: # isDark's contrast split is near L* 50+ return bg+ goal = 16 if dark else 80+ target = 0 if lightness(bg) > goal else 255+ rgb = [int(bg[i:i + 2], 16) for i in (1, 3, 5)]+ low, high = 0.0, 1.0+ for _ in range(16):+ mid = (low + high) / 2+ mixed = '#' + ''.join(f'{round(target * mid + v * (1 - mid)):02x}' for v in rgb)+ if (lightness(mixed) >= goal) if target == 255 else (lightness(mixed) <= goal):+ high = mid+ else:+ low = mid+ return '#' + ''.join(f'{round(target * high + v * (1 - high)):02x}' for v in rgb)+++def check_chromium_files(config, slot, bg, dark):+ """gtk.css carries Chromium's colours for a light preference and+ gtk-dark.css for a dark one; the qt5ct/qt6ct scheme carries the ones for+ dark_mode in its [Chromium] group."""+ rule = 'window.background.chromium, window.background.chromium window.background { background-color: '+ for version in ('gtk-3.0', 'gtk-4.0'):+ for name, variant in (('gtk.css', False), ('gtk-dark.css', True)):+ css = (slot / version / name).read_text()+ assert f'@define-color window_bg_color {bg};' in css, (version, name)+ toolbar = css.split(rule, 1)[1][:7]+ if (lightness(bg) < 50) != variant:+ # The palette's own darkness differs: a muted variant of it.+ assert (lightness(toolbar) < 50) == variant, (version, name, toolbar)+ for tool in ('qt5ct', 'qt6ct'):+ scheme = config / tool / 'colors/rediwm.conf'+ if not scheme.exists():+ continue+ groups = {}+ current = None+ for line in scheme.read_text().splitlines():+ if line.startswith('['):+ current = line.strip('[]')+ elif line.startswith('active_colors='):+ groups[current] = line.split('=', 1)[1].split(', ')+ assert groups['ColorScheme'][10] == bg, groups+ assert near(groups['Chromium'][10], chromium_bg(bg, dark)), (groups, chromium_bg(bg, dark))++def check_qt_frame(package, colors):- """Chromium's Qt frame is the style's active title bar: never the accent."""+ """Chromium's Qt frame (its tab strip) is the style's active title bar:+ never the accent, and 14 L* away from Button, its toolbar and active tab+ (or black when Button is too dark for that). Fusion's bar is a gradient,+ so its average lands up to a couple of L* short."""if not qt_style_built(package[2]):returnassert 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)+ assert not near(colors["frame"], colors["accent"]), (package, colors)+ assert (abs(lightness(colors["button"]) - lightness(colors["frame"])) >= 12+ or colors["frame"] == "#000000"), (package, colors)def test_app_colors():@@ -191,7 +256,8 @@ 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')+ # The second palette is light: Chromium keeps it under a light preference.+ colors = ('#123456', '#e8ecf0', '#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'@@ -204,9 +270,20 @@ def test_follow_private(tmp):env_extra={'REDIWM_FORCE_DBUS': '1'})clients = []streams = []+ watcher = Nonetry:with IPCClient(tmp, timeout=20) as ipc:assert not (config / 'gtk-3.0').exists()+ def portal_read(namespace, key):+ 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', namespace, key],+ capture_output=True, text=True)+ return r.stdout.strip()+ def scheme():+ return portal_read('org.freedesktop.appearance', 'color-scheme')+ wait_for(lambda: scheme() == 'v u 2', 'dark_mode (off) answers light')+ watcher = SettingChangedWatcher('org.freedesktop.impl.portal.Settings')# 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'@@ -232,12 +309,14 @@ def test_follow_private(tmp):# 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()+ return portal_read('org.gnome.desktop.interface', 'gtk-theme')wait_for(lambda: portal_theme() == f'v s "{selected()}"', 'GTK theme published')+ # dark_mode stays the preference and stays changeable; Chromium+ # browsers get colours of its darkness instead (see chromium_bg).+ assert scheme() == 'v u 2', scheme()+ dark_toggle = next(w for w in ui.widgets() if w.get('name') == 'dark_mode')+ assert dark_toggle['on'] is False and not dark_toggle.get('is_disabled'), dark_toggle+ check_chromium_files(config, data / 'themes' / selected(), colors[0], dark=False)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@@ -279,19 +358,28 @@ def test_follow_private(tmp):binary = tmp / packageflags = 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])+ variants = [(package, child_env)]+ if package.startswith('Qt') and qt_style_built(package[2]):+ # RediWM's style recognises Chromium by its Qt shim library.+ shim = tmp / f'libqt{package[2]}_shim.so'+ subprocess.run(['cc', '-shared', '-fPIC', '-x', 'c', '-', '-o', str(shim)],+ input='void rediwm_test_shim(void) {}', text=True, check=True)+ variants.append((package + ' chromium', dict(child_env, LD_PRELOAD=str(shim))))+ for name, env in variants:+ errors = (tmp / (name.replace(' ', '-') + '.log')).open('w')+ streams.append(errors)+ proc = subprocess.Popen([str(binary), '--watch'], env=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((name, proc, samples))+ expected = chromium_bg(colors[0], dark=False) if name.endswith('chromium') else colors[0]+ wait_for(lambda: samples and near(samples[-1]['bg'], expected), f'{name} initial palette', timeout=15)+ if 'frame' in samples[-1]:+ check_qt_frame(name, samples[-1])# Same palette and taskbar-only changes leave the named theme and# watched toolkit files untouched.@@ -308,6 +396,11 @@ def test_follow_private(tmp):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:+ if package.endswith('chromium'):+ expected = chromium_bg(bg, dark=False)+ wait_for(lambda: samples and near(samples[-1]['bg'], expected),+ f'{package} live Chromium palette {bg}', timeout=15)+ continuewait_for(lambda: samples and samples[-1]['bg'] == bg,f'{package} live palette {bg}', timeout=15)assert samples[-1]['fg'] == '#e1e2e3', (package, samples)@@ -319,10 +412,38 @@ def test_follow_private(tmp):(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],+ expected = chromium_bg(colors[-1], dark=False) if package.endswith('chromium') else colors[-1]+ wait_for(lambda: samples and near(samples[-1]['bg'], expected),f'{package} final palette', timeout=15)assert len(list((data / 'themes').glob('RediWM-*'))) == 2+ # Dark mode on: the preference is announced, the GTK slot is+ # unchanged (Chromium picks gtk-dark.css itself) and Chromium's Qt+ # colours become the dark palette's own.+ ipc.action('open_appearance')+ ui.wait_settled('control_center')+ slot_bytes = (data / 'themes' / selected() / 'gtk-3.0/gtk-dark.css').read_bytes()+ ui.click(ui.scroll_into_view('dark_mode'))+ wait_for(lambda: scheme() == 'v u 1', 'Dark mode on announced')+ assert watcher.values[-1] == 1, watcher.values+ assert tomllib.loads(path.read_text())['compositor']['dark_mode']+ def exported():+ try:+ check_chromium_files(config, data / 'themes' / selected(), colors[-1], dark=True)+ return True+ except AssertionError:+ return False+ wait_for(exported, 'Chromium colours for Dark mode exported')+ assert (data / 'themes' / selected() / 'gtk-3.0/gtk-dark.css').read_bytes() == slot_bytes+ for package, proc, samples in clients:+ if package.endswith('chromium'):+ wait_for(lambda: samples and samples[-1]['bg'] == colors[-1],+ f'{package} Chromium palette under Dark mode', timeout=15)+ check_qt_frame(package, samples[-1])+ ui.click(ui.scroll_into_view('dark_mode'))+ wait_for(lambda: scheme() == 'v u 2', 'Dark mode off announced')+ ipc.action('close_window')+# Disabling following keeps the current colors and stops future# exports, both immediately and after a compositor restart.last = selected()@@ -332,6 +453,8 @@ def test_follow_private(tmp):ipc.reload_config()assert selected() == last and last_file.read_bytes() == last_bytesassert not portal_theme()+ assert scheme() == 'v u 2', scheme()+ wait_for(lambda: watcher.values == [1, 2], 'SettingChanged per preference change')for _, proc, _ in clients:stop_process(proc)clients.clear()@@ -346,8 +469,10 @@ def test_follow_private(tmp):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')+ print('PASS: opt-in persistence, live GTK3/GTK4/Qt palettes, Chromium colours per light/dark preference, portal, closed Settings, bounded themes, off and restart')finally:+ if watcher is not None:+ watcher.close()for _, proc, _ in clients:stop_process(proc)for stream in streams:diff --git a/tests/app_colors_qt_client.cpp b/tests/app_colors_qt_client.cppindex 7cf8f20..a42b8b1 100644--- a/tests/app_colors_qt_client.cpp+++ b/tests/app_colors_qt_client.cpp@@ -33,6 +33,7 @@ static QString frame() {static void sample(const QPalette &p) {QJsonObject out{{"bg", p.color(QPalette::Window).name()},+ {"button", p.color(QPalette::Button).name()},{"fg", p.color(QPalette::WindowText).name()},{"accent", p.color(QPalette::Highlight).name()},{"on_accent", p.color(QPalette::HighlightedText).name()},diff --git a/tests/overview.py b/tests/overview.pyindex 500b360..b0c0c93 100644--- a/tests/overview.py+++ b/tests/overview.py@@ -43,6 +43,20 @@ def blue_windows(image):return boxes+def outline(image):+ """Bounding box of the magenta selection outline."""+ pixels = image.load()+ xs, ys = [], []+ for y in range(image.height):+ for x in range(image.width):+ r, g, b = pixels[x, y]+ if r > 240 and g < 15 and b > 240:+ xs.append(x)+ ys.append(y)+ assert xs, "no selection outline"+ return min(xs), min(ys), max(xs), max(ys)++def run():with tempfile.TemporaryDirectory(prefix="rediwm-spread-") as directory:tmp = Path(directory)@@ -207,6 +221,32 @@ def run():assert geometry() == positionsassert camera()["zoom_percent"] == original["zoom_percent"]+ # Hover enlarges a preview by ~10%; the wheel zooms it further+ # about the pointer and back down to the hover size.+ toggle()+ tick()+ x0, y0, x1, y1 = outline(picture("plain"))+ ipc.move_cursor((x0 + x1) // 2, (y0 + y1) // 2, output=output["name"])+ tick()+ h0, _, h1, _ = outline(picture("hover"))+ assert 1.06 < (h1 - h0) / (x1 - x0) < 1.12, ((x0, x1), (h0, h1))+ ipc.scroll(0, -40)+ tick()+ z0, _, z1, _ = outline(picture("zoomed"))+ assert (z1 - z0) > (h1 - h0) * 1.15, ((h0, h1), (z0, z1))+ assert z0 <= (x0 + x1) // 2 <= z1+ ipc.scroll(0, 400)+ tick()+ b0, _, b1, _ = outline(picture("unzoomed"))+ assert abs((b1 - b0) - (h1 - h0)) <= 2, ((h0, h1), (b0, b1))+ ipc.move_cursor(2, 2, output=output["name"])+ tick()+ p0, _, p1, _ = outline(picture("left"))+ assert abs((p1 - p0) - (x1 - x0)) <= 2, ((x0, x1), (p0, p1))+ ipc.key_down_up(1)+ tick()+ assert camera() == original and geometry() == positions+# Clicking the last card restores only that minimized window.toggle()tick()