RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
ui: move theme file I/O and tests out of theme.zig
Claudec973dd3db740
diff --git a/src/ui/theme.zig b/src/ui/theme.zigindex e9c47fc..16d6a35 100644--- a/src/ui/theme.zig+++ b/src/ui/theme.zig@@ -570,7 +570,7 @@ pub var global: Theme = .{};// Keep the darkness slider anchored to the original charcoal, independently// of the default theme tint.-const chrome_base: [4]f32 = .{ 38.0 / 255.0, 45.0 / 255.0, 55.0 / 255.0, 1 };+pub const chrome_base: [4]f32 = .{ 38.0 / 255.0, 45.0 / 255.0, 55.0 / 255.0, 1 };/// Brightness of an sRGB-encoded colour: enough to say which of two/// charcoals looks darker, which is all the chrome darkness compares.@@ -596,599 +596,27 @@ pub fn withChromeDarkness(bg: [4]f32, darkness: f32) [4]f32 {return .{ @min(1, hue[0] * scale), @min(1, hue[1] * scale), @min(1, hue[2] * scale), bg[3] };}-/// `REDIWM_THEME`, matching this project's existing env-var config-/// conventions (`REDIWM_SCALE`, `REDIWM_ICON_THEME` in icon_theme.zig).-/// Unset means "use the built-in defaults above", not an error.-pub fn resolvePath(environ: std.process.Environ) ?[]const u8 {- return environ.getPosix("REDIWM_THEME");-}--/// Best-effort: logs and falls back to defaults on any failure (missing-/// file, malformed TOML) rather than failing compositor startup over a-/// theme file.-pub fn loadGlobal(allocator: Allocator, io: Io, path: []const u8) void {- global = load(allocator, io, path) catch |err| blk: {- log.warn("loadGlobal: failed to load '{s}': {}, using defaults", .{ path, err });- break :blk .{};- };-}--pub fn load(allocator: Allocator, io: Io, path: []const u8) !Theme {- const bytes = try Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(1 << 20));- defer allocator.free(bytes);- return parse(allocator, bytes);-}--// Derive supported keys from Theme so a field cannot be exposed through IPC-// but silently omitted by TOML parsing or Appearance's save.-fn keysOf(comptime T: type) []const []const u8 {- const keys = comptime blk: {- var count: usize = 0;- for (std.meta.fields(Theme)) |field| if (field.type == T) {- count += 1;- };- var names: [count][]const u8 = undefined;- var i: usize = 0;- for (std.meta.fields(Theme)) |field| {- if (field.type == T) {- names[i] = field.name;- i += 1;- }- }- break :blk names;- };- return &keys;-}-const color_keys = keysOf([4]f32);-const number_keys = keysOf(f32);-const boolean_keys = keysOf(bool);-const optional_color_keys = keysOf(?[4]f32);-const string_keys = keysOf([]const u8);--/// Parses theme file bytes. String fields (`font`, `mono_font`) are duped-/// with `allocator` and, like `icon_theme.resolveConfig`'s paths, meant to-/// live for the process lifetime — pass a persistent allocator, not an-/// arena that gets torn down.-pub fn parse(allocator: Allocator, bytes: []const u8) !Theme {- var t: Theme = .{};- try overlay(allocator, &t, bytes);- return t;-}--/// Applies `[theme]` keys from `bytes` onto an existing theme, leaving-/// unspecified fields untouched. Used to merge `REDIWM_THEME` over the-/// compositor config's `[theme]` section.-pub fn overlay(allocator: Allocator, t: *Theme, bytes: []const u8) !void {- var in_theme_section = false;- var lines = std.mem.splitScalar(u8, bytes, '\n');- while (lines.next()) |raw_line| {- const line = stripComment(std.mem.trim(u8, raw_line, " \t\r"));- if (line.len == 0) continue;- if (line[0] == '[') {- const close = std.mem.indexOfScalar(u8, line, ']') orelse continue;- in_theme_section = std.mem.eql(u8, line[1..close], "theme");- continue;- }- if (!in_theme_section) continue;- const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;- const key = std.mem.trim(u8, line[0..eq], " \t");- const value = std.mem.trim(u8, line[eq + 1 ..], " \t");- try applyKey(allocator, t, key, value);- }-}--/// Drops a `#` comment that is not inside a quoted string.-pub fn stripComment(line: []const u8) []const u8 {- var in_string = false;- var i: usize = 0;- while (i < line.len) : (i += 1) {- const ch = line[i];- if (ch == '"' and (i == 0 or line[i - 1] != '\\')) in_string = !in_string;- if (ch == '#' and !in_string) return std.mem.trimEnd(u8, line[0..i], " \t");- }- return line;-}--pub fn applyKey(allocator: Allocator, t: *Theme, name_in: []const u8, value: []const u8) !void {- @setEvalBranchQuota(10000);- // The marker once lit hovers; saved looks may still use that name.- const key = if (std.mem.eql(u8, name_in, "app_sidebar_hover_marker")) "app_sidebar_selected_marker" else name_in;- inline for (boolean_keys) |name| {- if (std.mem.eql(u8, key, name)) {- @field(t, name) = if (std.mem.eql(u8, value, "true")) true else if (std.mem.eql(u8, value, "false")) false else return error.InvalidBoolean;- return;- }- }- inline for (string_keys) |name| {- if (std.mem.eql(u8, key, name)) {- const text = try unquote(value);- if (comptime std.mem.eql(u8, name, "start_button_icon")) {- if (text.len > 0 and !std.fs.path.isAbsolute(text)) return error.InvalidIconPath;- }- @field(t, name) = try allocator.dupe(u8, text);- return;- }- }- if (std.mem.eql(u8, key, "taskbar_height")) {- const number = try std.fmt.parseFloat(f32, value);- if (!std.math.isFinite(number) or number < 0 or number > 4096) return error.InvalidSize;- t.taskbar_size = number;- return;- }- inline for (number_keys) |name| {- if (std.mem.eql(u8, key, name)) {- const number = try std.fmt.parseFloat(f32, value);- if (!std.math.isFinite(number) or number < 0 or number > 4096) return error.InvalidSize;- if (comptime std.mem.eql(u8, name, "scrollbar_width")) {- if (number < 4 or number > 24) return error.InvalidSize;- }- if (comptime std.mem.eql(u8, name, "chip_width")) {- if (number < 64 or number > 400) return error.InvalidSize;- }- if (comptime std.mem.eql(u8, name, "chrome_height")) {- if (number < 28 or number > 84) return error.InvalidSize;- }- if (comptime std.mem.eql(u8, name, "chrome_control_gap")) {- if (number > 24) return error.InvalidSize;- }- if (comptime std.mem.eql(u8, name, "taskbar_length")) {- if (number < 20 or number > 100) return error.InvalidSize;- }- if (comptime std.mem.eql(u8, name, "taskbar_outline_width")) {- if (number > 8) return error.InvalidSize;- }- if (comptime std.mem.endsWith(u8, name, "_alpha") or std.mem.endsWith(u8, name, "_opacity") or std.mem.eql(u8, name, "dialog_glyph_lift")) {- if (number > 1) return error.InvalidSize;- }- if (comptime std.mem.eql(u8, name, "image_checker_size")) {- if (number < 1 or number > 128) return error.InvalidSize;- }- if (comptime std.mem.eql(u8, name, "scrollbar_rest_width") or std.mem.eql(u8, name, "scrollbar_active_width")) {- if (number < 0.25 or number > 1.125) return error.InvalidSize;- }- @field(t, name) = number;- return;- }- }- inline for (optional_color_keys) |name| {- if (std.mem.eql(u8, key, name)) {- const text = try unquote(value);- @field(t, name) = if (std.mem.eql(u8, text, "inherit")) null else try parseColor(text);- return;- }- }- inline for (color_keys) |name| {- if (std.mem.eql(u8, key, name)) {- @field(t, name) = try parseColor(try unquote(value));- return;- }- }- // Unknown key: ignore, so a newer theme file with extra tokens still- // loads under an older build.-}--/// Serializes `t` back into this file's tiny TOML dialect, replacing the-/// whole `[theme]` section, and writes it to `path`. Round-trips every value-/// but reformats colors as `rgba(...)` regardless of how the file originally-/// spelled them — this reader has no comments or alternate spellings worth-/// preserving, just the values themselves. Values equal to the defaults are-/// left out, so changing a default reaches everyone who never changed that-/// key. Best-effort: logs-/// and returns without touching the file on any failure, matching-/// `loadGlobal`'s "never crash over a theme file" stance; does not update-/// `global` itself — call `loadGlobal` afterward to do that via the same-/// path malformed-file errors already take.-pub fn save(allocator: Allocator, io: Io, path: []const u8, t: Theme) void {- var buf: std.ArrayList(u8) = .empty;- defer buf.deinit(allocator);- writeInto(allocator, &buf, t) catch |err| {- log.warn("save: failed to format '{s}': {}", .{ path, err });- return;- };- Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = buf.items }) catch |err| {- log.warn("save: failed to write '{s}': {}", .{ path, err });- };-}--fn appendLine(allocator: Allocator, buf: *std.ArrayList(u8), comptime fmt: []const u8, args: anytype) !void {- var line: [160]u8 = undefined;- try buf.appendSlice(allocator, try std.fmt.bufPrint(&line, fmt, args));-}--/// A colour as written: 8-bit channels and alpha to three decimals.-fn quantize(c: [4]f32) [4]u32 {- var q: [4]u32 = undefined;- for (0..3) |i| q[i] = @intFromFloat(@round(std.math.clamp(c[i], 0, 1) * 255));- q[3] = @intFromFloat(@round(std.math.clamp(c[3], 0, 1) * 1000));- return q;-}--fn appendColor(allocator: Allocator, buf: *std.ArrayList(u8), key: []const u8, c: [4]f32) !void {- const q = quantize(c);- try appendLine(allocator, buf, "{s} = \"rgba({d},{d},{d},{d:.3})\"\n", .{ key, q[0], q[1], q[2], std.math.clamp(c[3], 0, 1) });-}--pub fn knownKey(key: []const u8) bool {- inline for (std.meta.fields(Theme)) |field| if (std.mem.eql(u8, key, field.name)) return true;- return std.mem.eql(u8, key, "taskbar_height");-}--pub fn writeInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme) !void {- return writeOverrides(allocator, buf, t, .{}, "");-}--pub fn writeOverrides(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme, defaults: Theme, base: []const u8) !void {- return writeDiff(allocator, buf, t, defaults, base, base.len == 0);-}--pub fn saveOverlay(allocator: Allocator, io: Io, path: []const u8, t: Theme, below: Theme) !void {- var buf: std.ArrayList(u8) = .empty;- defer buf.deinit(allocator);- try writeDiff(allocator, &buf, t, below, "", false);- try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = buf.items });-}--fn writeDiff(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme, defaults: Theme, base: []const u8, force_radius: bool) !void {- try buf.appendSlice(allocator, "[theme]\n");- if (base.len > 0) try appendLine(allocator, buf, "base = \"{s}\"\n", .{base});- inline for (boolean_keys) |name| {- if (@field(t, name) != @field(defaults, name)) try appendLine(allocator, buf, "{s} = {}\n", .{ name, @field(t, name) });- }- inline for (string_keys) |name| {- if (!std.mem.eql(u8, @field(t, name), @field(defaults, name))) {- try buf.appendSlice(allocator, name ++ " = \"");- try buf.appendSlice(allocator, @field(t, name));- try buf.appendSlice(allocator, "\"\n");- }- }- inline for (number_keys) |name| {- // Keep the frame radius explicit even at Default, so a legacy- // compositor.border_radius cannot reappear after saving the theme.- if (comptime std.mem.eql(u8, name, "radius_lg")) {- if (force_radius) try appendLine(allocator, buf, "{s} = {d}\n", .{ name, @field(t, name) });- }- if ((!force_radius or !std.mem.eql(u8, name, "radius_lg")) and @field(t, name) != @field(defaults, name)) try appendLine(allocator, buf, "{s} = {d}\n", .{ name, @field(t, name) });- }- inline for (color_keys) |name| {- if (!std.meta.eql(quantize(@field(t, name)), quantize(@field(defaults, name)))) try appendColor(allocator, buf, name, @field(t, name));- }- // Written only when set: an emitted value would pin these to the accent of- // whichever palette happened to be current, turning "follow the accent"- // into a fixed colour on the first save.- inline for (optional_color_keys) |name| {- const actual = @field(t, name);- const original = @field(defaults, name);- const equal = if (actual) |value| (if (original) |other| std.meta.eql(quantize(value), quantize(other)) else false) else original == null;- if (!equal) {- if (@field(t, name)) |color| try appendColor(allocator, buf, name, color) else try appendLine(allocator, buf, "{s} = \"inherit\"\n", .{name});- }- }-}--/// The `[taskbar_theme]` section for `t`'s taskbar tokens. Values equal to the-/// defaults are left out, as `writeInto` does: the section's presence, not its-/// keys, says a taskbar theme is chosen, and it reads back over the defaults.-pub fn writeTaskbarInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme) !void {- const defaults: Theme = .{};- try buf.appendSlice(allocator, "[taskbar_theme]\n");- inline for (std.meta.fields(TaskbarToken)) |field| {- const value = @field(t, field.name);- if (comptime @TypeOf(value) == bool) {- if (value != @field(defaults, field.name)) try appendLine(allocator, buf, "{s} = {}\n", .{ field.name, value });- } else if (comptime @TypeOf(value) == ?[4]f32) {- if (value) |color| try appendColor(allocator, buf, field.name, color);- } else if (!std.meta.eql(quantize(value), quantize(@field(defaults, field.name)))) {- try appendColor(allocator, buf, field.name, value);- }- }-}--pub fn unquote(v: []const u8) ![]const u8 {- if (v.len >= 2 and v[0] == '"' and v[v.len - 1] == '"') return v[1 .. v.len - 1];- return error.ExpectedQuotedString;-}--/// Accepts "#rrggbb", "#rrggbbaa", or "rgba(r,g,b,a)" (r/g/b 0-255, a 0-1)-/// and returns straight-alpha RGBA, matching every other `[4]f32` color in-/// this codebase (chrome.Color, Taskbar.Color).-pub fn parseColor(s: []const u8) ![4]f32 {- if (s.len > 0 and s[0] == '#') return parseHex(s);- if (std.mem.startsWith(u8, s, "rgba(")) return parseRgba(s);- return error.InvalidColor;-}--fn parseHex(s: []const u8) ![4]f32 {- if (s.len != 7 and s.len != 9) return error.InvalidColor;- const r = try std.fmt.parseInt(u8, s[1..3], 16);- const g = try std.fmt.parseInt(u8, s[3..5], 16);- const b = try std.fmt.parseInt(u8, s[5..7], 16);- const a: u8 = if (s.len == 9) try std.fmt.parseInt(u8, s[7..9], 16) else 255;- return .{- @as(f32, @floatFromInt(r)) / 255.0,- @as(f32, @floatFromInt(g)) / 255.0,- @as(f32, @floatFromInt(b)) / 255.0,- @as(f32, @floatFromInt(a)) / 255.0,- };-}--fn parseRgba(s: []const u8) ![4]f32 {- if (!std.mem.endsWith(u8, s, ")")) return error.InvalidColor;- const inner = s["rgba(".len .. s.len - 1];- var comps: [4]f32 = .{ 0, 0, 0, 1 };- var it = std.mem.splitScalar(u8, inner, ',');- var i: usize = 0;- while (it.next()) |part| : (i += 1) {- if (i >= 4) return error.InvalidColor;- const v = try std.fmt.parseFloat(f32, std.mem.trim(u8, part, " \t"));- if (!std.math.isFinite(v) or v < 0 or v > (if (i < 3) @as(f32, 255) else 1)) return error.InvalidColor;- comps[i] = if (i < 3) v / 255.0 else v;- }- if (i < 3) return error.InvalidColor;- return comps;-}--test "parseColor hex with and without alpha" {- try std.testing.expectEqual([4]f32{ 1, 1, 1, 1 }, try parseColor("#ffffff"));- const with_alpha = try parseColor("#ffffff80");- try std.testing.expectApproxEqAbs(@as(f32, 128.0 / 255.0), with_alpha[3], 1e-6);-}--test "parseColor rgba" {- for ([_][]const u8{ "rgba(nan,0,0,1)", "rgba(0,0,0,inf)", "rgba(256,0,0,1)", "rgba(0,0,0,2)", "rgba(-1,0,0,1)" }) |bad| {- try std.testing.expectError(error.InvalidColor, parseColor(bad));- }- const c = try parseColor("rgba(255,255,255,0.045)");- try std.testing.expectEqual(@as(f32, 1), c[0]);- try std.testing.expectApproxEqAbs(@as(f32, 0.045), c[3], 1e-6);-}--test "parse reads the spec's example theme file" {- const sample =- \\[theme]- \\font = "Manrope"- \\mono_font = "JetBrains Mono"- \\font_size = 13.0- \\radius = 5.0- \\bg = "#090b18"- \\accent = "#5eead4"- \\surface = "rgba(255,255,255,0.045)"- \\border_focus = "rgba(94,234,212,0.40)"- ;- const t = try parse(std.testing.allocator, sample);- defer std.testing.allocator.free(t.font);- defer std.testing.allocator.free(t.mono_font);-- try std.testing.expectEqualStrings("Manrope", t.font);- try std.testing.expectEqualStrings("JetBrains Mono", t.mono_font);- try std.testing.expectEqual(@as(f32, 13.0), t.font_size);- try std.testing.expectEqual(@as(f32, 5.0), t.radius);- try std.testing.expectApproxEqAbs(@as(f32, 0.045), t.surface[3], 1e-6);- try std.testing.expectApproxEqAbs(@as(f32, 0.40), t.border_focus[3], 1e-6);-}--test "writeInto then parse round-trips every field" {- var t: Theme = .{};- t.clock_bold = true;- t.clock_italic = true;- // Exercise every registered field with a non-default value, so omission- // from either parser or serializer cannot pass as a default round-trip.- // Keys defaulting to 0 (automatic sizes) would stay at the default under *= 0.9.- inline for (number_keys) |name| @field(t, name) = if (@field(t, name) == 0) 500 else @field(t, name) * 0.9;- inline for (color_keys) |name| @field(t, name) = .{ 16.0 / 255.0, 32.0 / 255.0, 48.0 / 255.0, 0.321 };- inline for (optional_color_keys) |name| @field(t, name) = .{ 16.0 / 255.0, 32.0 / 255.0, 48.0 / 255.0, 0.321 };- t.accent = .{ 167.0 / 255.0, 139.0 / 255.0, 250.0 / 255.0, 1 };- t.radius = 8;- t.font_size = 14;- t.radius_md = 9;- t.radius_lg = 12;- t.glass = .{ 0.2, 0.4, 0.6, 0.56 };- t.taskbar_bg = .{ 0.1, 0.2, 0.3, 0.62 };- t.start_button_icon = "/tmp/custom logo.svg";- t.shadow_size = 32;- t.shadow = .{ 0, 0, 0, 0.45 };-- var buf: std.ArrayList(u8) = .empty;- defer buf.deinit(std.testing.allocator);- try writeInto(std.testing.allocator, &buf, t);-- const parsed = try parse(std.testing.allocator, buf.items);- // writeInto omits unchanged fonts; parse keeps their borrowed defaults.- defer std.testing.allocator.free(parsed.start_button_icon);- try std.testing.expectEqualStrings(t.start_button_icon, parsed.start_button_icon);- try std.testing.expect(parsed.clock_bold and parsed.clock_italic);-- var taskbar_buf: std.ArrayList(u8) = .empty;- defer taskbar_buf.deinit(std.testing.allocator);- try writeTaskbarInto(std.testing.allocator, &taskbar_buf, t);- var taskbar_theme: Theme = .{};- var lines = std.mem.tokenizeScalar(u8, taskbar_buf.items, '\n');- while (lines.next()) |line| {- const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;- try std.testing.expect(try applyTaskbarKey(std.testing.allocator, &taskbar_theme, std.mem.trim(u8, line[0..eq], " "), std.mem.trim(u8, line[eq + 1 ..], " ")));- }- try std.testing.expect(taskbarTokensEql(t, taskbar_theme));-- inline for (number_keys) |name| try std.testing.expectEqual(@field(t, name), @field(parsed, name));- inline for (color_keys) |name| {- for (@field(t, name), @field(parsed, name)) |expected, actual| {- try std.testing.expectApproxEqAbs(expected, actual, 1.0 / 255.0);- }- }- inline for (optional_color_keys) |name| try std.testing.expectEqual(@field(t, name), @field(parsed, name));- try std.testing.expectEqual(@as(f32, 8), parsed.radius);- try std.testing.expectEqual(@as(f32, 14), parsed.font_size);- try std.testing.expectApproxEqAbs(t.accent[0], parsed.accent[0], 1.0 / 255.0);- try std.testing.expectApproxEqAbs(t.accent[1], parsed.accent[1], 1.0 / 255.0);- try std.testing.expectApproxEqAbs(t.accent[2], parsed.accent[2], 1.0 / 255.0);- try std.testing.expectApproxEqAbs(t.border_focus[3], parsed.border_focus[3], 1e-3);-}--test "writeInto omits defaults except the explicit frame radius" {- var t: Theme = .{};- t.radius = 9;- t.window_bg[3] = 0.5;- var buf: std.ArrayList(u8) = .empty;- defer buf.deinit(std.testing.allocator);- try writeInto(std.testing.allocator, &buf, t);- try std.testing.expectEqualStrings("[theme]\nradius = 9\nradius_lg = 10\nwindow_bg = \"rgba(8,9,11,0.500)\"\n", buf.items);-}--test "theme sizes reject non-finite and unsafe geometry" {- for ([_][]const u8{ "nan", "inf", "-1", "1000000" }) |value| {- var t: Theme = .{};- try std.testing.expectError(error.InvalidSize, applyKey(std.testing.allocator, &t, "radius_lg", value));- }-}--test "floating taskbar tokens check their ranges and sit outside the radius presets" {- var t: Theme = .{};- try applyKey(std.testing.allocator, &t, "taskbar_edge_gap", "12");- try applyKey(std.testing.allocator, &t, "taskbar_length", "60");- try applyKey(std.testing.allocator, &t, "taskbar_radius", "22");- try applyKey(std.testing.allocator, &t, "taskbar_outline_width", "2");- try applyKey(std.testing.allocator, &t, "taskbar_outline", "\"#ff0000\"");- try std.testing.expectEqual(@as(f32, 60), t.taskbar_length);- try std.testing.expectEqual(@as(f32, 2), t.taskbar_outline_width);- try std.testing.expect(t.taskbar_outline != null);- for ([_][2][]const u8{ .{ "taskbar_length", "19" }, .{ "taskbar_length", "101" }, .{ "taskbar_outline_width", "9" }, .{ "taskbar_edge_gap", "-1" } }) |bad| {- try std.testing.expectError(error.InvalidSize, applyKey(std.testing.allocator, &t, bad[0], bad[1]));- }- // A preset rescales window radii; the taskbar's own corner is neither- // reset by it nor stops the preset from being recognised.- applyRadiusPreset(&t, .round);- try std.testing.expectEqual(@as(f32, 22), t.taskbar_radius);- try std.testing.expectEqual(RadiusPreset.round, radiusPreset(t).?);- // The default look is the flush, full-width, square bar.- const flush: Theme = .{};- try std.testing.expectEqual(@as(f32, 0), flush.taskbar_edge_gap);- try std.testing.expectEqual(@as(f32, 100), flush.taskbar_length);- try std.testing.expectEqual(@as(f32, 0), flush.taskbar_radius);-}--test "caret colour follows the accent in effect until the file sets one" {- var t: Theme = .{};- // Panels remap `accent` for their own palette; an unset caret has to- // follow that, which is what it did before the token existed.- t.accent = .{ 1, 0, 0, 1 };- try std.testing.expectEqual([4]f32{ 1, 0, 0, 1 }, t.caretColor());-- try applyKey(std.testing.allocator, &t, "caret", "\"rgba(0,255,0,1)\"");- try std.testing.expectEqual([4]f32{ 0, 1, 0, 1 }, t.caretColor());-- // Round-trips only once set, so saving a theme cannot freeze "follow the- // accent" into a literal colour.- var buf: std.ArrayList(u8) = .empty;- defer buf.deinit(std.testing.allocator);- try writeInto(std.testing.allocator, &buf, .{});- try std.testing.expect(std.mem.indexOf(u8, buf.items, "\ncaret = ") == null);-- buf.clearRetainingCapacity();- try writeInto(std.testing.allocator, &buf, t);- const parsed = try parse(std.testing.allocator, buf.items);- // writeInto omits unchanged fonts; parse keeps their borrowed defaults.- try std.testing.expectEqual([4]f32{ 0, 1, 0, 1 }, parsed.caret.?);-}--test "bundled RediWM Dark preset round-trips to Theme{}'s defaults field-for-field" {- try std.testing.expectApproxEqAbs(@as(f32, 0.80), (Theme{}).window_bg[3], 1e-5);- try std.testing.expectApproxEqAbs(@as(f32, 0.80), chromeDarkness((Theme{}).window_bg), 1e-5);- const bytes = @embedFile("theme-rediwm-dark");- const t = try parse(std.testing.allocator, bytes);- defer std.testing.allocator.free(t.font);- defer std.testing.allocator.free(t.mono_font);-- const defaults: Theme = .{};- try std.testing.expectEqualStrings(defaults.font, t.font);- try std.testing.expectEqualStrings(defaults.mono_font, t.mono_font);- inline for (number_keys) |name| try std.testing.expectEqual(@field(defaults, name), @field(t, name));- inline for (color_keys) |name| {- for (@field(defaults, name), @field(t, name)) |expected, actual| {- try std.testing.expectApproxEqAbs(expected, actual, 1.0 / 255.0);- }- }-}--test "scrollbar width validates and survives theme serialization" {- const a = std.testing.allocator;- for ([_][]const u8{ "0", "3", "25", "nan", "inf" }) |value| {- var t: Theme = .{};- try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "scrollbar_width", value));- }- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const t = try parse(arena.allocator(), "[theme]\nscrollbar_width = 19\n");- var buf: std.ArrayList(u8) = .empty;- defer buf.deinit(a);- try writeInto(a, &buf, t);- const restored = try parse(arena.allocator(), buf.items);- try std.testing.expectEqual(@as(f32, 19), restored.scrollbar_width);-}--test "chrome darkness scales the tint's brightness and keeps its hue and alpha" {- const stock = chrome_base;- try std.testing.expectEqual(@as(f32, 0), chromeDarkness(stock));- // Zero darkness is the stock colour exactly, at whatever opacity it had.- const untouched = withChromeDarkness(.{ stock[0], stock[1], stock[2], 0.37 }, 0);- try std.testing.expectEqual(stock[0], untouched[0]);- try std.testing.expectEqual(stock[1], untouched[1]);- try std.testing.expectEqual(stock[2], untouched[2]);- try std.testing.expectEqual(@as(f32, 0.37), untouched[3]);-- // Half darkness reads back as half, with the stock hue.- const half = withChromeDarkness(stock, 0.5);- try std.testing.expectApproxEqAbs(@as(f32, 0.5), chromeDarkness(half), 1e-5);- try std.testing.expectApproxEqAbs(stock[0] / stock[2], half[0] / half[2], 1e-5);- try std.testing.expectApproxEqAbs(stock[1] / stock[2], half[1] / half[2], 1e-5);- try std.testing.expect(half[0] < stock[0] and half[1] < stock[1] and half[2] < stock[2]);-- // Full darkness is black; going back up recovers the stock hue.- const black = withChromeDarkness(stock, 1);- try std.testing.expectEqual(@as(f32, 0), black[0] + black[1] + black[2]);- const back = withChromeDarkness(black, 0.25);- try std.testing.expectApproxEqAbs(@as(f32, 0.25), chromeDarkness(back), 1e-5);- try std.testing.expectApproxEqAbs(stock[0] / stock[2], back[0] / back[2], 1e-5);-}--test "chrome darkness follows a custom tint and survives 8-bit storage" {- // A user's own darker charcoal reads as darkened, not as 0.- const custom: [4]f32 = .{ 16.0 / 255.0, 18.0 / 255.0, 21.0 / 255.0, 0.98 };- const d = chromeDarkness(custom);- try std.testing.expect(d > 0.5 and d < 0.7);- // Moving the slider keeps the tint's hue rather than resetting to stock.- const moved = withChromeDarkness(custom, 0.5);- try std.testing.expectApproxEqAbs(custom[0] / custom[2], moved[0] / moved[2], 1e-5);- try std.testing.expectEqual(@as(f32, 0.98), moved[3]);- // A lighter-than-stock colour reads 0 and is never pushed past white.- try std.testing.expectEqual(@as(f32, 0), chromeDarkness(.{ 1, 1, 1, 1 }));- const white = withChromeDarkness(.{ 1, 1, 1, 1 }, 0);- try std.testing.expect(white[0] <= 1 and white[1] <= 1 and white[2] <= 1);- // Reloading from the theme file quantises to 8 bits; the readout stays put.- const stored: [4]f32 = .{ @round(moved[0] * 255) / 255.0, @round(moved[1] * 255) / 255.0, @round(moved[2] * 255) / 255.0, moved[3] };- try std.testing.expectApproxEqAbs(chromeDarkness(moved), chromeDarkness(stored), 0.01);-}--test "chrome geometry validates and survives theme serialization" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- for ([_][]const u8{ "0", "27", "85", "nan", "inf" }) |value| {- var t: Theme = .{};- try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "chrome_height", value));- }- for ([_][]const u8{ "-1", "25", "nan", "inf" }) |value| {- var t: Theme = .{};- try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "chrome_control_gap", value));- }- for ([_][]const u8{ "1", "\"true\"", "True" }) |value| {- var t: Theme = .{};- try std.testing.expectError(error.InvalidBoolean, applyKey(a, &t, "chrome_round_buttons", value));- }- try std.testing.expect(!(try parse(a, "[theme]\nchrome_round_buttons = false\n")).chrome_round_buttons);- const t = try parse(a, "[theme]\nchrome_height = 28\nchrome_control_gap = 0\nchrome_round_buttons = true\n");- var buf: std.ArrayList(u8) = .empty;- try writeInto(a, &buf, t);- const restored = try parse(a, buf.items);- try std.testing.expectEqual(@as(f32, 28), restored.chrome_height);- try std.testing.expectEqual(@as(f32, 0), restored.chrome_control_gap);- try std.testing.expect(restored.chrome_round_buttons);+const theme_file = @import("theme_file.zig");+pub const resolvePath = theme_file.resolvePath;+pub const loadGlobal = theme_file.loadGlobal;+pub const load = theme_file.load;+pub const color_keys = theme_file.color_keys;+pub const number_keys = theme_file.number_keys;+pub const optional_color_keys = theme_file.optional_color_keys;+pub const parse = theme_file.parse;+pub const overlay = theme_file.overlay;+pub const stripComment = theme_file.stripComment;+pub const applyKey = theme_file.applyKey;+pub const save = theme_file.save;+const quantize = theme_file.quantize;+pub const knownKey = theme_file.knownKey;+pub const writeInto = theme_file.writeInto;+pub const writeOverrides = theme_file.writeOverrides;+pub const saveOverlay = theme_file.saveOverlay;+pub const writeTaskbarInto = theme_file.writeTaskbarInto;+pub const unquote = theme_file.unquote;+pub const parseColor = theme_file.parseColor;++test {+ _ = @import("theme_tests.zig");}diff --git a/src/ui/theme_file.zig b/src/ui/theme_file.zignew file mode 100644index 0000000..bf5f004--- /dev/null+++ b/src/ui/theme_file.zig@@ -0,0 +1,345 @@+//! Theme files: locating, loading, parsing and overlaying them, applying keys, colour syntax and writing them back.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Io = std.Io;+const log = std.log.scoped(.theme);+const theme = @import("theme.zig");+const Theme = theme.Theme;+const TaskbarToken = theme.TaskbarToken;++/// `REDIWM_THEME`, matching this project's existing env-var config+/// conventions (`REDIWM_SCALE`, `REDIWM_ICON_THEME` in icon_theme.zig).+/// Unset means "use the built-in defaults above", not an error.+pub fn resolvePath(environ: std.process.Environ) ?[]const u8 {+ return environ.getPosix("REDIWM_THEME");+}++/// Best-effort: logs and falls back to defaults on any failure (missing+/// file, malformed TOML) rather than failing compositor startup over a+/// theme file.+pub fn loadGlobal(allocator: Allocator, io: Io, path: []const u8) void {+ theme.global = load(allocator, io, path) catch |err| blk: {+ log.warn("loadGlobal: failed to load '{s}': {}, using defaults", .{ path, err });+ break :blk .{};+ };+}++pub fn load(allocator: Allocator, io: Io, path: []const u8) !Theme {+ const bytes = try Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(1 << 20));+ defer allocator.free(bytes);+ return parse(allocator, bytes);+}++// Derive supported keys from Theme so a field cannot be exposed through IPC+// but silently omitted by TOML parsing or Appearance's save.+pub fn keysOf(comptime T: type) []const []const u8 {+ const keys = comptime blk: {+ var count: usize = 0;+ for (std.meta.fields(Theme)) |field| if (field.type == T) {+ count += 1;+ };+ var names: [count][]const u8 = undefined;+ var i: usize = 0;+ for (std.meta.fields(Theme)) |field| {+ if (field.type == T) {+ names[i] = field.name;+ i += 1;+ }+ }+ break :blk names;+ };+ return &keys;+}++pub const color_keys = keysOf([4]f32);++pub const number_keys = keysOf(f32);++pub const boolean_keys = keysOf(bool);++pub const optional_color_keys = keysOf(?[4]f32);++pub const string_keys = keysOf([]const u8);++/// Parses theme file bytes. String fields (`font`, `mono_font`) are duped+/// with `allocator` and, like `icon_theme.resolveConfig`'s paths, meant to+/// live for the process lifetime — pass a persistent allocator, not an+/// arena that gets torn down.+pub fn parse(allocator: Allocator, bytes: []const u8) !Theme {+ var t: Theme = .{};+ try overlay(allocator, &t, bytes);+ return t;+}++/// Applies `[theme]` keys from `bytes` onto an existing theme, leaving+/// unspecified fields untouched. Used to merge `REDIWM_THEME` over the+/// compositor config's `[theme]` section.+pub fn overlay(allocator: Allocator, t: *Theme, bytes: []const u8) !void {+ var in_theme_section = false;+ var lines = std.mem.splitScalar(u8, bytes, '\n');+ while (lines.next()) |raw_line| {+ const line = stripComment(std.mem.trim(u8, raw_line, " \t\r"));+ if (line.len == 0) continue;+ if (line[0] == '[') {+ const close = std.mem.indexOfScalar(u8, line, ']') orelse continue;+ in_theme_section = std.mem.eql(u8, line[1..close], "theme");+ continue;+ }+ if (!in_theme_section) continue;+ const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;+ const key = std.mem.trim(u8, line[0..eq], " \t");+ const value = std.mem.trim(u8, line[eq + 1 ..], " \t");+ try applyKey(allocator, t, key, value);+ }+}++/// Drops a `#` comment that is not inside a quoted string.+pub fn stripComment(line: []const u8) []const u8 {+ var in_string = false;+ var i: usize = 0;+ while (i < line.len) : (i += 1) {+ const ch = line[i];+ if (ch == '"' and (i == 0 or line[i - 1] != '\\')) in_string = !in_string;+ if (ch == '#' and !in_string) return std.mem.trimEnd(u8, line[0..i], " \t");+ }+ return line;+}++pub fn applyKey(allocator: Allocator, t: *Theme, name_in: []const u8, value: []const u8) !void {+ @setEvalBranchQuota(10000);+ // The marker once lit hovers; saved looks may still use that name.+ const key = if (std.mem.eql(u8, name_in, "app_sidebar_hover_marker")) "app_sidebar_selected_marker" else name_in;+ inline for (boolean_keys) |name| {+ if (std.mem.eql(u8, key, name)) {+ @field(t, name) = if (std.mem.eql(u8, value, "true")) true else if (std.mem.eql(u8, value, "false")) false else return error.InvalidBoolean;+ return;+ }+ }+ inline for (string_keys) |name| {+ if (std.mem.eql(u8, key, name)) {+ const text = try unquote(value);+ if (comptime std.mem.eql(u8, name, "start_button_icon")) {+ if (text.len > 0 and !std.fs.path.isAbsolute(text)) return error.InvalidIconPath;+ }+ @field(t, name) = try allocator.dupe(u8, text);+ return;+ }+ }+ if (std.mem.eql(u8, key, "taskbar_height")) {+ const number = try std.fmt.parseFloat(f32, value);+ if (!std.math.isFinite(number) or number < 0 or number > 4096) return error.InvalidSize;+ t.taskbar_size = number;+ return;+ }+ inline for (number_keys) |name| {+ if (std.mem.eql(u8, key, name)) {+ const number = try std.fmt.parseFloat(f32, value);+ if (!std.math.isFinite(number) or number < 0 or number > 4096) return error.InvalidSize;+ if (comptime std.mem.eql(u8, name, "scrollbar_width")) {+ if (number < 4 or number > 24) return error.InvalidSize;+ }+ if (comptime std.mem.eql(u8, name, "chip_width")) {+ if (number < 64 or number > 400) return error.InvalidSize;+ }+ if (comptime std.mem.eql(u8, name, "chrome_height")) {+ if (number < 28 or number > 84) return error.InvalidSize;+ }+ if (comptime std.mem.eql(u8, name, "chrome_control_gap")) {+ if (number > 24) return error.InvalidSize;+ }+ if (comptime std.mem.eql(u8, name, "taskbar_length")) {+ if (number < 20 or number > 100) return error.InvalidSize;+ }+ if (comptime std.mem.eql(u8, name, "taskbar_outline_width")) {+ if (number > 8) return error.InvalidSize;+ }+ if (comptime std.mem.endsWith(u8, name, "_alpha") or std.mem.endsWith(u8, name, "_opacity") or std.mem.eql(u8, name, "dialog_glyph_lift")) {+ if (number > 1) return error.InvalidSize;+ }+ if (comptime std.mem.eql(u8, name, "image_checker_size")) {+ if (number < 1 or number > 128) return error.InvalidSize;+ }+ if (comptime std.mem.eql(u8, name, "scrollbar_rest_width") or std.mem.eql(u8, name, "scrollbar_active_width")) {+ if (number < 0.25 or number > 1.125) return error.InvalidSize;+ }+ @field(t, name) = number;+ return;+ }+ }+ inline for (optional_color_keys) |name| {+ if (std.mem.eql(u8, key, name)) {+ const text = try unquote(value);+ @field(t, name) = if (std.mem.eql(u8, text, "inherit")) null else try parseColor(text);+ return;+ }+ }+ inline for (color_keys) |name| {+ if (std.mem.eql(u8, key, name)) {+ @field(t, name) = try parseColor(try unquote(value));+ return;+ }+ }+ // Unknown key: ignore, so a newer theme file with extra tokens still+ // loads under an older build.+}++/// Serializes `t` back into this file's tiny TOML dialect, replacing the+/// whole `[theme]` section, and writes it to `path`. Round-trips every value+/// but reformats colors as `rgba(...)` regardless of how the file originally+/// spelled them — this reader has no comments or alternate spellings worth+/// preserving, just the values themselves. Values equal to the defaults are+/// left out, so changing a default reaches everyone who never changed that+/// key. Best-effort: logs+/// and returns without touching the file on any failure, matching+/// `loadGlobal`'s "never crash over a theme file" stance; does not update+/// `global` itself — call `loadGlobal` afterward to do that via the same+/// path malformed-file errors already take.+pub fn save(allocator: Allocator, io: Io, path: []const u8, t: Theme) void {+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(allocator);+ writeInto(allocator, &buf, t) catch |err| {+ log.warn("save: failed to format '{s}': {}", .{ path, err });+ return;+ };+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = buf.items }) catch |err| {+ log.warn("save: failed to write '{s}': {}", .{ path, err });+ };+}++pub fn appendLine(allocator: Allocator, buf: *std.ArrayList(u8), comptime fmt: []const u8, args: anytype) !void {+ var line: [160]u8 = undefined;+ try buf.appendSlice(allocator, try std.fmt.bufPrint(&line, fmt, args));+}++/// A colour as written: 8-bit channels and alpha to three decimals.+pub fn quantize(c: [4]f32) [4]u32 {+ var q: [4]u32 = undefined;+ for (0..3) |i| q[i] = @intFromFloat(@round(std.math.clamp(c[i], 0, 1) * 255));+ q[3] = @intFromFloat(@round(std.math.clamp(c[3], 0, 1) * 1000));+ return q;+}++pub fn appendColor(allocator: Allocator, buf: *std.ArrayList(u8), key: []const u8, c: [4]f32) !void {+ const q = quantize(c);+ try appendLine(allocator, buf, "{s} = \"rgba({d},{d},{d},{d:.3})\"\n", .{ key, q[0], q[1], q[2], std.math.clamp(c[3], 0, 1) });+}++pub fn knownKey(key: []const u8) bool {+ inline for (std.meta.fields(Theme)) |field| if (std.mem.eql(u8, key, field.name)) return true;+ return std.mem.eql(u8, key, "taskbar_height");+}++pub fn writeInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme) !void {+ return writeOverrides(allocator, buf, t, .{}, "");+}++pub fn writeOverrides(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme, defaults: Theme, base: []const u8) !void {+ return writeDiff(allocator, buf, t, defaults, base, base.len == 0);+}++pub fn saveOverlay(allocator: Allocator, io: Io, path: []const u8, t: Theme, below: Theme) !void {+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(allocator);+ try writeDiff(allocator, &buf, t, below, "", false);+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = buf.items });+}++pub fn writeDiff(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme, defaults: Theme, base: []const u8, force_radius: bool) !void {+ try buf.appendSlice(allocator, "[theme]\n");+ if (base.len > 0) try appendLine(allocator, buf, "base = \"{s}\"\n", .{base});+ inline for (boolean_keys) |name| {+ if (@field(t, name) != @field(defaults, name)) try appendLine(allocator, buf, "{s} = {}\n", .{ name, @field(t, name) });+ }+ inline for (string_keys) |name| {+ if (!std.mem.eql(u8, @field(t, name), @field(defaults, name))) {+ try buf.appendSlice(allocator, name ++ " = \"");+ try buf.appendSlice(allocator, @field(t, name));+ try buf.appendSlice(allocator, "\"\n");+ }+ }+ inline for (number_keys) |name| {+ // Keep the frame radius explicit even at Default, so a legacy+ // compositor.border_radius cannot reappear after saving the theme.+ if (comptime std.mem.eql(u8, name, "radius_lg")) {+ if (force_radius) try appendLine(allocator, buf, "{s} = {d}\n", .{ name, @field(t, name) });+ }+ if ((!force_radius or !std.mem.eql(u8, name, "radius_lg")) and @field(t, name) != @field(defaults, name)) try appendLine(allocator, buf, "{s} = {d}\n", .{ name, @field(t, name) });+ }+ inline for (color_keys) |name| {+ if (!std.meta.eql(quantize(@field(t, name)), quantize(@field(defaults, name)))) try appendColor(allocator, buf, name, @field(t, name));+ }+ // Written only when set: an emitted value would pin these to the accent of+ // whichever palette happened to be current, turning "follow the accent"+ // into a fixed colour on the first save.+ inline for (optional_color_keys) |name| {+ const actual = @field(t, name);+ const original = @field(defaults, name);+ const equal = if (actual) |value| (if (original) |other| std.meta.eql(quantize(value), quantize(other)) else false) else original == null;+ if (!equal) {+ if (@field(t, name)) |color| try appendColor(allocator, buf, name, color) else try appendLine(allocator, buf, "{s} = \"inherit\"\n", .{name});+ }+ }+}++/// The `[taskbar_theme]` section for `t`'s taskbar tokens. Values equal to the+/// defaults are left out, as `writeInto` does: the section's presence, not its+/// keys, says a taskbar theme is chosen, and it reads back over the defaults.+pub fn writeTaskbarInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme) !void {+ const defaults: Theme = .{};+ try buf.appendSlice(allocator, "[taskbar_theme]\n");+ inline for (std.meta.fields(TaskbarToken)) |field| {+ const value = @field(t, field.name);+ if (comptime @TypeOf(value) == bool) {+ if (value != @field(defaults, field.name)) try appendLine(allocator, buf, "{s} = {}\n", .{ field.name, value });+ } else if (comptime @TypeOf(value) == ?[4]f32) {+ if (value) |color| try appendColor(allocator, buf, field.name, color);+ } else if (!std.meta.eql(quantize(value), quantize(@field(defaults, field.name)))) {+ try appendColor(allocator, buf, field.name, value);+ }+ }+}++pub fn unquote(v: []const u8) ![]const u8 {+ if (v.len >= 2 and v[0] == '"' and v[v.len - 1] == '"') return v[1 .. v.len - 1];+ return error.ExpectedQuotedString;+}++/// Accepts "#rrggbb", "#rrggbbaa", or "rgba(r,g,b,a)" (r/g/b 0-255, a 0-1)+/// and returns straight-alpha RGBA, matching every other `[4]f32` color in+/// this codebase (chrome.Color, Taskbar.Color).+pub fn parseColor(s: []const u8) ![4]f32 {+ if (s.len > 0 and s[0] == '#') return parseHex(s);+ if (std.mem.startsWith(u8, s, "rgba(")) return parseRgba(s);+ return error.InvalidColor;+}++pub fn parseHex(s: []const u8) ![4]f32 {+ if (s.len != 7 and s.len != 9) return error.InvalidColor;+ const r = try std.fmt.parseInt(u8, s[1..3], 16);+ const g = try std.fmt.parseInt(u8, s[3..5], 16);+ const b = try std.fmt.parseInt(u8, s[5..7], 16);+ const a: u8 = if (s.len == 9) try std.fmt.parseInt(u8, s[7..9], 16) else 255;+ return .{+ @as(f32, @floatFromInt(r)) / 255.0,+ @as(f32, @floatFromInt(g)) / 255.0,+ @as(f32, @floatFromInt(b)) / 255.0,+ @as(f32, @floatFromInt(a)) / 255.0,+ };+}++pub fn parseRgba(s: []const u8) ![4]f32 {+ if (!std.mem.endsWith(u8, s, ")")) return error.InvalidColor;+ const inner = s["rgba(".len .. s.len - 1];+ var comps: [4]f32 = .{ 0, 0, 0, 1 };+ var it = std.mem.splitScalar(u8, inner, ',');+ var i: usize = 0;+ while (it.next()) |part| : (i += 1) {+ if (i >= 4) return error.InvalidColor;+ const v = try std.fmt.parseFloat(f32, std.mem.trim(u8, part, " \t"));+ if (!std.math.isFinite(v) or v < 0 or v > (if (i < 3) @as(f32, 255) else 1)) return error.InvalidColor;+ comps[i] = if (i < 3) v / 255.0 else v;+ }+ if (i < 3) return error.InvalidColor;+ return comps;+}diff --git a/src/ui/theme_tests.zig b/src/ui/theme_tests.zignew file mode 100644index 0000000..03eca60--- /dev/null+++ b/src/ui/theme_tests.zig@@ -0,0 +1,285 @@+const std = @import("std");+const theme = @import("theme.zig");+const Theme = theme.Theme;+const taskbarTokensEql = theme.taskbarTokensEql;+const applyTaskbarKey = theme.applyTaskbarKey;+const RadiusPreset = theme.RadiusPreset;+const applyRadiusPreset = theme.applyRadiusPreset;+const radiusPreset = theme.radiusPreset;+const chrome_base = theme.chrome_base;+const chromeDarkness = theme.chromeDarkness;+const withChromeDarkness = theme.withChromeDarkness;+const color_keys = theme.color_keys;+const number_keys = theme.number_keys;+const optional_color_keys = theme.optional_color_keys;+const parse = theme.parse;+const applyKey = theme.applyKey;+const writeInto = theme.writeInto;+const writeTaskbarInto = theme.writeTaskbarInto;+const parseColor = theme.parseColor;++test "parseColor hex with and without alpha" {+ try std.testing.expectEqual([4]f32{ 1, 1, 1, 1 }, try parseColor("#ffffff"));+ const with_alpha = try parseColor("#ffffff80");+ try std.testing.expectApproxEqAbs(@as(f32, 128.0 / 255.0), with_alpha[3], 1e-6);+}++test "parseColor rgba" {+ for ([_][]const u8{ "rgba(nan,0,0,1)", "rgba(0,0,0,inf)", "rgba(256,0,0,1)", "rgba(0,0,0,2)", "rgba(-1,0,0,1)" }) |bad| {+ try std.testing.expectError(error.InvalidColor, parseColor(bad));+ }+ const c = try parseColor("rgba(255,255,255,0.045)");+ try std.testing.expectEqual(@as(f32, 1), c[0]);+ try std.testing.expectApproxEqAbs(@as(f32, 0.045), c[3], 1e-6);+}++test "parse reads the spec's example theme file" {+ const sample =+ \\[theme]+ \\font = "Manrope"+ \\mono_font = "JetBrains Mono"+ \\font_size = 13.0+ \\radius = 5.0+ \\bg = "#090b18"+ \\accent = "#5eead4"+ \\surface = "rgba(255,255,255,0.045)"+ \\border_focus = "rgba(94,234,212,0.40)"+ ;+ const t = try parse(std.testing.allocator, sample);+ defer std.testing.allocator.free(t.font);+ defer std.testing.allocator.free(t.mono_font);++ try std.testing.expectEqualStrings("Manrope", t.font);+ try std.testing.expectEqualStrings("JetBrains Mono", t.mono_font);+ try std.testing.expectEqual(@as(f32, 13.0), t.font_size);+ try std.testing.expectEqual(@as(f32, 5.0), t.radius);+ try std.testing.expectApproxEqAbs(@as(f32, 0.045), t.surface[3], 1e-6);+ try std.testing.expectApproxEqAbs(@as(f32, 0.40), t.border_focus[3], 1e-6);+}++test "writeInto then parse round-trips every field" {+ var t: Theme = .{};+ t.clock_bold = true;+ t.clock_italic = true;+ // Exercise every registered field with a non-default value, so omission+ // from either parser or serializer cannot pass as a default round-trip.+ // Keys defaulting to 0 (automatic sizes) would stay at the default under *= 0.9.+ inline for (number_keys) |name| @field(t, name) = if (@field(t, name) == 0) 500 else @field(t, name) * 0.9;+ inline for (color_keys) |name| @field(t, name) = .{ 16.0 / 255.0, 32.0 / 255.0, 48.0 / 255.0, 0.321 };+ inline for (optional_color_keys) |name| @field(t, name) = .{ 16.0 / 255.0, 32.0 / 255.0, 48.0 / 255.0, 0.321 };+ t.accent = .{ 167.0 / 255.0, 139.0 / 255.0, 250.0 / 255.0, 1 };+ t.radius = 8;+ t.font_size = 14;+ t.radius_md = 9;+ t.radius_lg = 12;+ t.glass = .{ 0.2, 0.4, 0.6, 0.56 };+ t.taskbar_bg = .{ 0.1, 0.2, 0.3, 0.62 };+ t.start_button_icon = "/tmp/custom logo.svg";+ t.shadow_size = 32;+ t.shadow = .{ 0, 0, 0, 0.45 };++ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(std.testing.allocator);+ try writeInto(std.testing.allocator, &buf, t);++ const parsed = try parse(std.testing.allocator, buf.items);+ // writeInto omits unchanged fonts; parse keeps their borrowed defaults.+ defer std.testing.allocator.free(parsed.start_button_icon);+ try std.testing.expectEqualStrings(t.start_button_icon, parsed.start_button_icon);+ try std.testing.expect(parsed.clock_bold and parsed.clock_italic);++ var taskbar_buf: std.ArrayList(u8) = .empty;+ defer taskbar_buf.deinit(std.testing.allocator);+ try writeTaskbarInto(std.testing.allocator, &taskbar_buf, t);+ var taskbar_theme: Theme = .{};+ var lines = std.mem.tokenizeScalar(u8, taskbar_buf.items, '\n');+ while (lines.next()) |line| {+ const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;+ try std.testing.expect(try applyTaskbarKey(std.testing.allocator, &taskbar_theme, std.mem.trim(u8, line[0..eq], " "), std.mem.trim(u8, line[eq + 1 ..], " ")));+ }+ try std.testing.expect(taskbarTokensEql(t, taskbar_theme));++ inline for (number_keys) |name| try std.testing.expectEqual(@field(t, name), @field(parsed, name));+ inline for (color_keys) |name| {+ for (@field(t, name), @field(parsed, name)) |expected, actual| {+ try std.testing.expectApproxEqAbs(expected, actual, 1.0 / 255.0);+ }+ }+ inline for (optional_color_keys) |name| try std.testing.expectEqual(@field(t, name), @field(parsed, name));+ try std.testing.expectEqual(@as(f32, 8), parsed.radius);+ try std.testing.expectEqual(@as(f32, 14), parsed.font_size);+ try std.testing.expectApproxEqAbs(t.accent[0], parsed.accent[0], 1.0 / 255.0);+ try std.testing.expectApproxEqAbs(t.accent[1], parsed.accent[1], 1.0 / 255.0);+ try std.testing.expectApproxEqAbs(t.accent[2], parsed.accent[2], 1.0 / 255.0);+ try std.testing.expectApproxEqAbs(t.border_focus[3], parsed.border_focus[3], 1e-3);+}++test "writeInto omits defaults except the explicit frame radius" {+ var t: Theme = .{};+ t.radius = 9;+ t.window_bg[3] = 0.5;+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(std.testing.allocator);+ try writeInto(std.testing.allocator, &buf, t);+ try std.testing.expectEqualStrings("[theme]\nradius = 9\nradius_lg = 10\nwindow_bg = \"rgba(8,9,11,0.500)\"\n", buf.items);+}++test "theme sizes reject non-finite and unsafe geometry" {+ for ([_][]const u8{ "nan", "inf", "-1", "1000000" }) |value| {+ var t: Theme = .{};+ try std.testing.expectError(error.InvalidSize, applyKey(std.testing.allocator, &t, "radius_lg", value));+ }+}++test "floating taskbar tokens check their ranges and sit outside the radius presets" {+ var t: Theme = .{};+ try applyKey(std.testing.allocator, &t, "taskbar_edge_gap", "12");+ try applyKey(std.testing.allocator, &t, "taskbar_length", "60");+ try applyKey(std.testing.allocator, &t, "taskbar_radius", "22");+ try applyKey(std.testing.allocator, &t, "taskbar_outline_width", "2");+ try applyKey(std.testing.allocator, &t, "taskbar_outline", "\"#ff0000\"");+ try std.testing.expectEqual(@as(f32, 60), t.taskbar_length);+ try std.testing.expectEqual(@as(f32, 2), t.taskbar_outline_width);+ try std.testing.expect(t.taskbar_outline != null);+ for ([_][2][]const u8{ .{ "taskbar_length", "19" }, .{ "taskbar_length", "101" }, .{ "taskbar_outline_width", "9" }, .{ "taskbar_edge_gap", "-1" } }) |bad| {+ try std.testing.expectError(error.InvalidSize, applyKey(std.testing.allocator, &t, bad[0], bad[1]));+ }+ // A preset rescales window radii; the taskbar's own corner is neither+ // reset by it nor stops the preset from being recognised.+ applyRadiusPreset(&t, .round);+ try std.testing.expectEqual(@as(f32, 22), t.taskbar_radius);+ try std.testing.expectEqual(RadiusPreset.round, radiusPreset(t).?);+ // The default look is the flush, full-width, square bar.+ const flush: Theme = .{};+ try std.testing.expectEqual(@as(f32, 0), flush.taskbar_edge_gap);+ try std.testing.expectEqual(@as(f32, 100), flush.taskbar_length);+ try std.testing.expectEqual(@as(f32, 0), flush.taskbar_radius);+}++test "caret colour follows the accent in effect until the file sets one" {+ var t: Theme = .{};+ // Panels remap `accent` for their own palette; an unset caret has to+ // follow that, which is what it did before the token existed.+ t.accent = .{ 1, 0, 0, 1 };+ try std.testing.expectEqual([4]f32{ 1, 0, 0, 1 }, t.caretColor());++ try applyKey(std.testing.allocator, &t, "caret", "\"rgba(0,255,0,1)\"");+ try std.testing.expectEqual([4]f32{ 0, 1, 0, 1 }, t.caretColor());++ // Round-trips only once set, so saving a theme cannot freeze "follow the+ // accent" into a literal colour.+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(std.testing.allocator);+ try writeInto(std.testing.allocator, &buf, .{});+ try std.testing.expect(std.mem.indexOf(u8, buf.items, "\ncaret = ") == null);++ buf.clearRetainingCapacity();+ try writeInto(std.testing.allocator, &buf, t);+ const parsed = try parse(std.testing.allocator, buf.items);+ // writeInto omits unchanged fonts; parse keeps their borrowed defaults.+ try std.testing.expectEqual([4]f32{ 0, 1, 0, 1 }, parsed.caret.?);+}++test "bundled RediWM Dark preset round-trips to Theme{}'s defaults field-for-field" {+ try std.testing.expectApproxEqAbs(@as(f32, 0.80), (Theme{}).window_bg[3], 1e-5);+ try std.testing.expectApproxEqAbs(@as(f32, 0.80), chromeDarkness((Theme{}).window_bg), 1e-5);+ const bytes = @embedFile("theme-rediwm-dark");+ const t = try parse(std.testing.allocator, bytes);+ defer std.testing.allocator.free(t.font);+ defer std.testing.allocator.free(t.mono_font);++ const defaults: Theme = .{};+ try std.testing.expectEqualStrings(defaults.font, t.font);+ try std.testing.expectEqualStrings(defaults.mono_font, t.mono_font);+ inline for (number_keys) |name| try std.testing.expectEqual(@field(defaults, name), @field(t, name));+ inline for (color_keys) |name| {+ for (@field(defaults, name), @field(t, name)) |expected, actual| {+ try std.testing.expectApproxEqAbs(expected, actual, 1.0 / 255.0);+ }+ }+}++test "scrollbar width validates and survives theme serialization" {+ const a = std.testing.allocator;+ for ([_][]const u8{ "0", "3", "25", "nan", "inf" }) |value| {+ var t: Theme = .{};+ try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "scrollbar_width", value));+ }+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const t = try parse(arena.allocator(), "[theme]\nscrollbar_width = 19\n");+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(a);+ try writeInto(a, &buf, t);+ const restored = try parse(arena.allocator(), buf.items);+ try std.testing.expectEqual(@as(f32, 19), restored.scrollbar_width);+}++test "chrome darkness scales the tint's brightness and keeps its hue and alpha" {+ const stock = chrome_base;+ try std.testing.expectEqual(@as(f32, 0), chromeDarkness(stock));+ // Zero darkness is the stock colour exactly, at whatever opacity it had.+ const untouched = withChromeDarkness(.{ stock[0], stock[1], stock[2], 0.37 }, 0);+ try std.testing.expectEqual(stock[0], untouched[0]);+ try std.testing.expectEqual(stock[1], untouched[1]);+ try std.testing.expectEqual(stock[2], untouched[2]);+ try std.testing.expectEqual(@as(f32, 0.37), untouched[3]);++ // Half darkness reads back as half, with the stock hue.+ const half = withChromeDarkness(stock, 0.5);+ try std.testing.expectApproxEqAbs(@as(f32, 0.5), chromeDarkness(half), 1e-5);+ try std.testing.expectApproxEqAbs(stock[0] / stock[2], half[0] / half[2], 1e-5);+ try std.testing.expectApproxEqAbs(stock[1] / stock[2], half[1] / half[2], 1e-5);+ try std.testing.expect(half[0] < stock[0] and half[1] < stock[1] and half[2] < stock[2]);++ // Full darkness is black; going back up recovers the stock hue.+ const black = withChromeDarkness(stock, 1);+ try std.testing.expectEqual(@as(f32, 0), black[0] + black[1] + black[2]);+ const back = withChromeDarkness(black, 0.25);+ try std.testing.expectApproxEqAbs(@as(f32, 0.25), chromeDarkness(back), 1e-5);+ try std.testing.expectApproxEqAbs(stock[0] / stock[2], back[0] / back[2], 1e-5);+}++test "chrome darkness follows a custom tint and survives 8-bit storage" {+ // A user's own darker charcoal reads as darkened, not as 0.+ const custom: [4]f32 = .{ 16.0 / 255.0, 18.0 / 255.0, 21.0 / 255.0, 0.98 };+ const d = chromeDarkness(custom);+ try std.testing.expect(d > 0.5 and d < 0.7);+ // Moving the slider keeps the tint's hue rather than resetting to stock.+ const moved = withChromeDarkness(custom, 0.5);+ try std.testing.expectApproxEqAbs(custom[0] / custom[2], moved[0] / moved[2], 1e-5);+ try std.testing.expectEqual(@as(f32, 0.98), moved[3]);+ // A lighter-than-stock colour reads 0 and is never pushed past white.+ try std.testing.expectEqual(@as(f32, 0), chromeDarkness(.{ 1, 1, 1, 1 }));+ const white = withChromeDarkness(.{ 1, 1, 1, 1 }, 0);+ try std.testing.expect(white[0] <= 1 and white[1] <= 1 and white[2] <= 1);+ // Reloading from the theme file quantises to 8 bits; the readout stays put.+ const stored: [4]f32 = .{ @round(moved[0] * 255) / 255.0, @round(moved[1] * 255) / 255.0, @round(moved[2] * 255) / 255.0, moved[3] };+ try std.testing.expectApproxEqAbs(chromeDarkness(moved), chromeDarkness(stored), 0.01);+}++test "chrome geometry validates and survives theme serialization" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ for ([_][]const u8{ "0", "27", "85", "nan", "inf" }) |value| {+ var t: Theme = .{};+ try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "chrome_height", value));+ }+ for ([_][]const u8{ "-1", "25", "nan", "inf" }) |value| {+ var t: Theme = .{};+ try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "chrome_control_gap", value));+ }+ for ([_][]const u8{ "1", "\"true\"", "True" }) |value| {+ var t: Theme = .{};+ try std.testing.expectError(error.InvalidBoolean, applyKey(a, &t, "chrome_round_buttons", value));+ }+ try std.testing.expect(!(try parse(a, "[theme]\nchrome_round_buttons = false\n")).chrome_round_buttons);+ const t = try parse(a, "[theme]\nchrome_height = 28\nchrome_control_gap = 0\nchrome_round_buttons = true\n");+ var buf: std.ArrayList(u8) = .empty;+ try writeInto(a, &buf, t);+ const restored = try parse(a, buf.items);+ try std.testing.expectEqual(@as(f32, 28), restored.chrome_height);+ try std.testing.expectEqual(@as(f32, 0), restored.chrome_control_gap);+ try std.testing.expect(restored.chrome_round_buttons);+}