//! Colour themes: the Theme type, the curated and generated ring, chrome //! colours, theme files, and switching themes at runtime. const pardes = @import("root.zig"); const tagline = @import("tagline.zig"); const panes = @import("panes.zig"); const std = @import("std"); const Color = @import("surface.zig").Color; const FontRole = @import("surface.zig").FontRole; const config = @import("config.zig"); const platform = pardes.platform; const BOX_H = pardes.BOX_H; const Pardes = pardes.Pardes; /// The 256-colour palette a terminal starts from (its emulator's default): /// sixteen named colours, a 6x6x6 cube at xterm's levels (0, then 95 to /// 255 by 40) and a ramp of 24 greys from 8 by 10. pub const xterm: [256][3]u8 = blk: { var p: [256][3]u8 = undefined; p[0..16].* = .{ .{ 0x1D, 0x1F, 0x21 }, // black .{ 0xCC, 0x66, 0x66 }, // red .{ 0xB5, 0xBD, 0x68 }, // green .{ 0xF0, 0xC6, 0x74 }, // yellow .{ 0x81, 0xA2, 0xBE }, // blue .{ 0xB2, 0x94, 0xBB }, // magenta .{ 0x8A, 0xBE, 0xB7 }, // cyan .{ 0xC5, 0xC8, 0xC6 }, // white .{ 0x66, 0x66, 0x66 }, // bright black .{ 0xD5, 0x4E, 0x53 }, // bright red .{ 0xB9, 0xCA, 0x4A }, // bright green .{ 0xE7, 0xC5, 0x47 }, // bright yellow .{ 0x7A, 0xA6, 0xDA }, // bright blue .{ 0xC3, 0x97, 0xD8 }, // bright magenta .{ 0x70, 0xC0, 0xB1 }, // bright cyan .{ 0xEA, 0xEA, 0xEA }, // bright white }; for (0..216) |i| { for (0..3, [3]usize{ i / 36, i / 6 % 6, i % 6 }) |c, v| p[16 + i][c] = if (v == 0) 0 else 55 + 40 * v; } for (0..24) |i| p[232 + i] = @splat(8 + 10 * i); break :blk p; }; /// sRGB channel to linear light. pub const to_linear: [256]f32 = blk: { @setEvalBranchQuota(100_000); var table: [256]f32 = undefined; for (&table, 0..) |*out, i| { const c = @as(f64, @floatFromInt(i)) / 255; out.* = @floatCast(if (c <= 0.04045) c / 12.92 else std.math.pow(f64, (c + 0.055) / 1.055, 2.4)); } break :blk table; }; /// WCAG relative luminance, and the contrast of two colours. pub fn relativeLuminance(rgb: [3]u8) f32 { return 0.2126 * to_linear[rgb[0]] + 0.7152 * to_linear[rgb[1]] + 0.0722 * to_linear[rgb[2]]; } pub fn contrast(a: [3]u8, b: [3]u8) f32 { const x = relativeLuminance(a); const y = relativeLuminance(b); return (@max(x, y) + 0.05) / (@min(x, y) + 0.05); } pub fn lerp(a: [3]u8, b: [3]u8, t: f32) [3]u8 { var out: [3]u8 = undefined; for (&out, a, b) |*o, x, y| o.* = @intFromFloat(std.math.clamp(@round(@as(f32, @floatFromInt(x)) + (@as(f32, @floatFromInt(y)) - @as(f32, @floatFromInt(x))) * t), 0, 255)); return out; } /// The rules between panes and columns: acme's contrast, black on white. /// A theme's own border, or its scroll track, as long as it stands off the /// page by 1.5:1; one that does not (on a near-black page, a dark rule all /// but vanishes) is lifted toward the text until it does, to 1.6:1. pub const separator_floor: f32 = 1.5; /// The page a theme with none (`dark`: the host's own) is judged against: /// the GUI's default ground, and a dark terminal's. pub const null_page: [3]u8 = .{ 18, 18, 18 }; fn separatorOf(th: *const Theme) [3]u8 { const base = th.border orelse th.scroll_track; const page = th.bg orelse null_page; if (contrast(base, page) >= separator_floor) return base; const ink = th.fg orelse th.tag_fg; var t: f32 = 0.05; while (t <= 1) : (t += 0.05) { const lifted = lerp(base, ink, t); if (contrast(lifted, page) >= 1.6) return lifted; } return ink; } /// The focused tag's tint, the main focus indicator: a theme's own, pushed /// further the way it already leans from the plain tag where the two are /// closer than the floor (1.5:1 on a dark page, where a tint is all that /// tells the focused tag at a glance; 1.25:1 on a light one), but never so /// far its text drops below its own contrast or 4.5. A theme with no tint /// (acme: the grip's button says it) keeps none. pub const focus_tint_floor: f32 = 1.25; pub const focus_tint_floor_dark: f32 = 1.5; pub fn focusTintFloor(th: *const Theme) f32 { return if (relativeLuminance(th.bg orelse null_page) < 0.18) focus_tint_floor_dark else focus_tint_floor; } fn focusTint(th: *const Theme) [3]u8 { const tint = th.tag_active_bg orelse return th.tag_bg; const floor = focusTintFloor(th); if (contrast(tint, th.tag_bg) >= floor) return tint; const ink = th.tag_active_fg orelse th.tag_fg; const text_floor = @min(contrast(ink, tint), 4.5); var best = tint; var k: f32 = 1.1; while (k <= 12) : (k += 0.1) { const pushed = lerp(th.tag_bg, tint, k); if (contrast(ink, pushed) < text_floor) break; best = pushed; if (contrast(pushed, th.tag_bg) >= floor) break; } return best; } /// sRGB bytes to OKLab and back (Björn Ottosson's), and a mix in it. fn toOklab(rgb: [3]u8) [3]f32 { var l: [3]f32 = undefined; for (&l, rgb) |*out, v| { const x = @as(f32, @floatFromInt(v)) / 255; out.* = if (x <= 0.04045) x / 12.92 else std.math.pow(f32, (x + 0.055) / 1.055, 2.4); } const lm = std.math.cbrt(0.4122214708 * l[0] + 0.5363325363 * l[1] + 0.0514459929 * l[2]); const mm = std.math.cbrt(0.2119034982 * l[0] + 0.6806995451 * l[1] + 0.1073969566 * l[2]); const sm = std.math.cbrt(0.0883024619 * l[0] + 0.2817188376 * l[1] + 0.6299787005 * l[2]); return .{ 0.2104542553 * lm + 0.7936177850 * mm - 0.0040720468 * sm, 1.9779984951 * lm - 2.4285922050 * mm + 0.4505937099 * sm, 0.0259040371 * lm + 0.7827717662 * mm - 0.8086757660 * sm, }; } fn oklabLinear(lab: [3]f32) [3]f32 { const lm = lab[0] + 0.3963377774 * lab[1] + 0.2158037573 * lab[2]; const mm = lab[0] - 0.1055613458 * lab[1] - 0.0638541728 * lab[2]; const sm = lab[0] - 0.0894841775 * lab[1] - 1.2914855480 * lab[2]; const l = lm * lm * lm; const m = mm * mm * mm; const s = sm * sm * sm; return .{ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s, }; } fn fromOklab(lab: [3]f32) [3]u8 { const linear = oklabLinear(lab); var out: [3]u8 = undefined; for (&out, linear) |*o, v| { const x = std.math.clamp(v, 0, 1); const srgb = if (x <= 0.0031308) x * 12.92 else 1.055 * std.math.pow(f32, x, 1.0 / 2.4) - 0.055; o.* = @intFromFloat(@round(std.math.clamp(srgb, 0, 1) * 255)); } return out; } pub fn mixOklab(a: [3]u8, b: [3]u8, t: f32) [3]u8 { if (std.mem.eql(u8, &a, &b)) return a; const x = toOklab(a); const y = toOklab(b); return fromOklab(.{ x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t, x[2] + (y[2] - x[2]) * t }); } fn oklabDistance(a: [3]f32, b: [3]f32) f32 { return @sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2])); } /// How far a name's tint stands off its tag's ink in OKLab: a hue you see /// at a glance, not a shade you look for. pub const name_tint_distance: f32 = 0.07; /// How much hue a colour needs to lend a name its tint. const name_tint_chroma: f32 = 0.06; /// A name's tint for a theme that sets none (the faithful ports, the /// imports, a theme file): a hue of the theme's own -- its keyword colour, /// else the first of its ANSI accents, syntax, grip, selection or /// diagnostic colours that has one -- at the lightness nearest the tag's /// ink where that hue holds, the name reads on its ground (nameTintFloor) /// and it stands off the ink. Null when no colour of the theme will do. fn derivedNameTint(th: *const Theme, ink: [3]u8, ground: [3]u8) ?[3]u8 { const pal = th.palette orelse @as([16][3]u8, @splat(th.kw)); const sources = [_][3]u8{ th.kw, pal[4], pal[5], pal[6], pal[3], pal[2], pal[1], th.num, th.str, th.box } ++ [_][3]u8{ th.column_box orelse th.num, th.box_dirty orelse th.num, th.sel_bg, th.search_bg orelse th.num } ++ [_][3]u8{ th.diagnostic_info orelse th.num, th.diagnostic_hint orelse th.num, th.diagnostic_warning orelse th.num } ++ // A theme with no hue of its own at all (flatwhite): acme's DMedblue's. [_][3]u8{.{ 0x00, 0x00, 0x99 }}; // Near the ink's lightness first, from any of the theme's hues; only // then further off it. for ([2]f32{ 0.15, 1 }) |reach| for (sources) |source| { if (nameTintFrom(toOklab(source), ink, ground, reach)) |tint| return tint; }; return null; } fn nameTintFrom(source: [3]f32, ink: [3]u8, ground: [3]u8, reach: f32) ?[3]u8 { const chroma = @sqrt(source[1] * source[1] + source[2] * source[2]); if (chroma < name_tint_chroma) return null; const ink_lab = toOklab(ink); const floor = nameTintFloor(ink, ground); var step: f32 = 0; while (step <= reach) : (step += 0.01) { for ([2]f32{ 1, -1 }) |sign| { const lightness = ink_lab[0] + sign * step; if (lightness < 0 or lightness > 1) continue; // As much of the hue as that lightness holds, up to a tint's. var want = @min(chroma, 0.12); while (want >= 0.04) : (want -= 0.01) { const lab: [3]f32 = .{ lightness, source[1] / chroma * want, source[2] / chroma * want }; const in_gamut = for (oklabLinear(lab)) |v| { if (v < -0.001 or v > 1.001) break false; } else true; if (!in_gamut) continue; const tint = fromOklab(lab); if (contrast(tint, ground) < floor) continue; if (oklabDistance(toOklab(tint), ink_lab) < name_tint_distance) continue; return tint; } } } return null; } /// What a name's tint must read at on its ground: 4.5:1, or within half a /// point of the ink's own where the ink has less to spare (seoulbones_dark's /// near-white on grey leaves no hue at the ink's 4.53:1). pub fn nameTintFloor(ink: [3]u8, ground: [3]u8) f32 { return @min(4.5, contrast(ink, ground) - 0.5); } pub fn mix(a: [3]u8, b: [3]u8) [3]u8 { var out: [3]u8 = undefined; for (&out, a, b) |*c, x, y| c.* = @intCast((@as(u16, x) + y) / 2); return out; } pub const Theme = struct { name: []const u8, bg: ?[3]u8, fg: ?[3]u8, sel_bg: [3]u8, sel_fg: [3]u8, tag_bg: [3]u8, tag_fg: [3]u8, box: [3]u8, // move box, focused pane box_dim: [3]u8, // move box, everything else kw: [3]u8, str: [3]u8, num: [3]u8, comment: [3]u8, lineno: [3]u8, scroll_track: [3]u8, scroll_thumb: [3]u8, palette: ?[16][3]u8, // Pardes UI roles. Optional so existing ThemeFile documents and imported // editor palettes keep working; ChromeTheme resolves their legacy defaults. tag_active_bg: ?[3]u8 = null, tag_active_fg: ?[3]u8 = null, /// The workspace row (the tagline): an editor's status bar in its own /// colours, where it has them; else the tag's. tagline_bg: ?[3]u8 = null, tagline_fg: ?[3]u8 = null, /// Filename/output-name accent, also used by the Term command. tag_name_fg: ?[3]u8 = null, /// Active tint; absence preserves the shared name tint or active tag ink. tag_active_name_fg: ?[3]u8 = null, /// Column grips stay distinct from pane grips in both focus states. column_box: ?[3]u8 = null, column_box_dim: ?[3]u8 = null, border: ?[3]u8 = null, /// What an empty column shows under its tag; the border fill without it. empty_col: ?[3]u8 = null, search_bg: ?[3]u8 = null, search_fg: ?[3]u8 = null, diagnostic_error: ?[3]u8 = null, diagnostic_warning: ?[3]u8 = null, diagnostic_info: ?[3]u8 = null, diagnostic_hint: ?[3]u8 = null, // The current line number is a quiet foreground cue, not a tag-colored // background block. Older themes fall back to their normal gutter ink. lineno_active: ?[3]u8 = null, /// A tag's selection, where it differs from the body's (acme's #9eeeee). tag_sel_bg: ?[3]u8 = null, /// The tag of a reading pane, one a jump steps (Trail.zig): unset, or /// too near the tag to see, the tag toward paper yellow (readingOf). tag_reading_bg: ?[3]u8 = null, /// Each pointer button's sweep, select, exec and look (Mouse.Button /// order), and the ink over it. Unset, tints of `sel_bg` in `sel_fg`. sweep_bg: ?[3][3]u8 = null, sweep_fg: ?[3][3]u8 = null, /// A pixel shell's rules, in pixels (2 unset); the rule between a tag /// and its body is always one. rule_px: ?u8 = null, /// A grip is acme's button: `box` filled when focused, else a ring of /// `box_border` (unset: `box_dim`) round the tag's ground; `box_dirty` /// (unset: `diagnostic_warning`, then `num`) fills it, in either ring, /// while its file is unsaved. box_border: ?[3]u8 = null, box_dirty: ?[3]u8 = null, /// The rule between a pane's tag and its body, one pixel, quieter than /// the rules between panes (acme's #8888cc under its 2px black ones). /// Unset, halfway between the tag's ground and the page. tag_rule: ?[3]u8 = null, /// A pixel shell's scroll column, the grip's button over the scrollbar, /// in pixels at a 17px tagline, the thumb one narrower (acme's 12px /// Scrollwid, the default). rail_px: ?u8 = null, }; /// The ink a syntax class is drawn in; a byte of none keeps its text's own. pub fn synInk(th: *const Theme, sy: @import("syntax.zig").Syn) ?[3]u8 { return switch (sy) { .none => null, .keyword => th.kw, .string => th.str, .number => th.num, .comment => th.comment, }; } /// The grounds a style byte's high bits name (syntax.ground_add and the /// rest) in a theme: a row added or removed on a ground a little way from /// the page toward the theme's green or red (its own ANSI ones where it has /// a palette), a stronger one, a faint one, and the row's marker in that /// hue, pushed toward the ink until it reads on the row's ground. Syntax /// colours are drawn over a ground unchanged. pub const Grounds = struct { add: Ground, del: Ground, pub const Ground = struct { row: [3]u8, emph: [3]u8, line: [3]u8, ink: [3]u8 }; pub fn of(th: *const Theme) Grounds { const page = th.bg orelse th.tag_bg; const ink = th.fg orelse th.tag_fg; const green: [3]u8 = if (th.palette) |pal| pal[2] else .{ 0x2e, 0xa0, 0x43 }; const red: [3]u8 = if (th.palette) |pal| pal[1] else .{ 0xcf, 0x22, 0x2e }; return .{ .add = ground(page, ink, green), .del = ground(page, ink, red) }; } fn ground(page: [3]u8, ink: [3]u8, hue: [3]u8) Ground { const row = mixOklab(page, hue, 0.18); var marker = hue; var step: usize = 0; while (step < 4 and contrast(marker, row) < 3) : (step += 1) marker = mixOklab(marker, ink, 0.4); return .{ .row = row, .emph = mixOklab(page, hue, 0.28), .line = mixOklab(page, hue, 0.07), .ink = marker }; } /// The ground of a byte's hue, if it has one. pub fn forStyle(g: *const Grounds, style: u8) ?Ground { const syntax = @import("syntax.zig"); if (style & syntax.ground_add != 0) return g.add; if (style & syntax.ground_del != 0) return g.del; return null; } }; /// One family, its twelve backgrounds a theme each (`curated`). const seoul256 = @import("themes/seoul256.zig"); const curated = struct { pub const orchard = @import("themes/orchard.zig"); pub const dusk = @import("themes/dusk.zig"); pub const ink = @import("themes/ink.zig"); pub const paper = @import("themes/paper.zig"); pub const daybreak = @import("themes/daybreak.zig"); pub const atelier = @import("themes/atelier.zig"); pub const forge = @import("themes/forge.zig"); pub const lagoon = @import("themes/lagoon.zig"); pub const solarium = @import("themes/solarium.zig"); pub const spectrum = @import("themes/spectrum.zig"); pub const harvest = @import("themes/harvest.zig"); pub const clay = @import("themes/clay.zig"); pub const forge_black = @import("themes/forge_black.zig"); pub const forge_soft = @import("themes/forge_soft.zig"); pub const orchard_black = @import("themes/orchard_black.zig"); pub const acme = @import("themes/acme.zig"); pub const lapis = @import("themes/lapis.zig"); // Faithful ports of well-known themes, a family at a time (core/themes/ // .zig says where each value came from): `theme_groups`. pub const dark_plus = @import("themes/dark_plus.zig"); pub const solarized_dark = @import("themes/solarized_dark.zig"); pub const solarized_light = @import("themes/solarized_light.zig"); pub const dracula = @import("themes/dracula.zig"); pub const dracula_soft = @import("themes/dracula_soft.zig"); pub const alucard = @import("themes/alucard.zig"); pub const monokai = @import("themes/monokai.zig"); pub const monokai_pro = @import("themes/monokai_pro.zig"); pub const monokai_pro_classic = @import("themes/monokai_pro_classic.zig"); pub const monokai_pro_machine = @import("themes/monokai_pro_machine.zig"); pub const monokai_pro_octagon = @import("themes/monokai_pro_octagon.zig"); pub const monokai_pro_ristretto = @import("themes/monokai_pro_ristretto.zig"); pub const monokai_pro_spectrum = @import("themes/monokai_pro_spectrum.zig"); pub const monokai_pro_light = @import("themes/monokai_pro_light.zig"); pub const monokai_pro_light_sun = @import("themes/monokai_pro_light_sun.zig"); pub const tokyonight_night = @import("themes/tokyonight_night.zig"); pub const tokyonight_storm = @import("themes/tokyonight_storm.zig"); pub const tokyonight_moon = @import("themes/tokyonight_moon.zig"); pub const tokyonight_day = @import("themes/tokyonight_day.zig"); pub const rose_pine = @import("themes/rose_pine.zig"); pub const rose_pine_moon = @import("themes/rose_pine_moon.zig"); pub const rose_pine_dawn = @import("themes/rose_pine_dawn.zig"); pub const catppuccin_latte = @import("themes/catppuccin_latte.zig"); pub const catppuccin_frappe = @import("themes/catppuccin_frappe.zig"); pub const catppuccin_macchiato = @import("themes/catppuccin_macchiato.zig"); pub const catppuccin_mocha = @import("themes/catppuccin_mocha.zig"); pub const seoul256_dark_233 = seoul256.dark(233); pub const seoul256_dark_234 = seoul256.dark(234); pub const seoul256_dark_235 = seoul256.dark(235); pub const seoul256_dark_236 = seoul256.dark(236); pub const seoul256_dark_237 = seoul256.dark(237); pub const seoul256_dark_238 = seoul256.dark(238); pub const seoul256_dark_239 = seoul256.dark(239); pub const seoul256_light_252 = seoul256.light(252); pub const seoul256_light_253 = seoul256.light(253); pub const seoul256_light_254 = seoul256.light(254); pub const seoul256_light_255 = seoul256.light(255); pub const seoul256_light_256 = seoul256.light(256); pub const zenbones_light = @import("themes/zenbones_light.zig"); pub const zenbones_dark = @import("themes/zenbones_dark.zig"); pub const neobones_light = @import("themes/neobones_light.zig"); pub const neobones_dark = @import("themes/neobones_dark.zig"); pub const vimbones = @import("themes/vimbones.zig"); pub const forestbones_light = @import("themes/forestbones_light.zig"); pub const forestbones_dark = @import("themes/forestbones_dark.zig"); pub const nordbones = @import("themes/nordbones.zig"); pub const rosebones_light = @import("themes/rosebones_light.zig"); pub const rosebones_dark = @import("themes/rosebones_dark.zig"); pub const tokyobones_light = @import("themes/tokyobones_light.zig"); pub const tokyobones_dark = @import("themes/tokyobones_dark.zig"); pub const seoulbones_light = @import("themes/seoulbones_light.zig"); pub const seoulbones_dark = @import("themes/seoulbones_dark.zig"); pub const duckbones = @import("themes/duckbones.zig"); pub const zenburned = @import("themes/zenburned.zig"); pub const zenwritten_light = @import("themes/zenwritten_light.zig"); pub const zenwritten_dark = @import("themes/zenwritten_dark.zig"); pub const kanagawabones = @import("themes/kanagawabones.zig"); pub const nord = @import("themes/nord.zig"); pub const ayu_dark = @import("themes/ayu_dark.zig"); pub const ayu_mirage = @import("themes/ayu_mirage.zig"); pub const ayu_light = @import("themes/ayu_light.zig"); pub const doom_one = @import("themes/doom_one.zig"); pub const doom_one_light = @import("themes/doom_one_light.zig"); // The legacy pair last. pub const helix = @import("themes/helix.zig"); pub const dark = @import("themes/dark.zig"); }; fn fold(comptime C: type) [@typeInfo(C).@"struct".decl_names.len]Theme { comptime { @setEvalBranchQuota(400000); var out: [@typeInfo(C).@"struct".decl_names.len]Theme = undefined; const theme_info = @typeInfo(Theme).@"struct"; for (@typeInfo(C).@"struct".decl_names, 0..) |d, i| { var t: Theme = undefined; const source = @field(C, d).theme; for (theme_info.field_names, theme_info.field_types, theme_info.field_attrs) |name, T, attrs| { @field(t, name) = if (@hasField(@TypeOf(source), name)) @field(source, name) else if (attrs.defaultValue(T)) |value| value else @compileError("theme " ++ d ++ " is missing " ++ name); } out[i] = t; } return out; } } pub const themes = fold(curated) ++ fold(@import("generated_themes")); /// The first `native_count` of `themes` are pardes's own; the rest imported. pub const native_count = @typeInfo(curated).@"struct".decl_names.len; /// The picker's sections (`Themes`), in ring order, each running from /// the theme it names to the next section's; `NextColor` and `Theme` still /// see one flat ring. The current pardes themes, then the faithful ports a /// family at a time, then the legacy pair (`helix`, captured from an old /// helix setup and the boot default before orchard; `dark`, the host /// terminal's own ground), then everything imported. pub const ThemeGroup = struct { title: []const u8, first: []const u8 }; const theme_groups = [_]ThemeGroup{ .{ .title = "Pardes themes", .first = "orchard" }, .{ .title = "Visual Studio Code", .first = "dark_plus" }, .{ .title = "Solarized", .first = "solarized_dark" }, .{ .title = "Dracula", .first = "dracula" }, .{ .title = "Monokai", .first = "monokai" }, .{ .title = "Monokai Pro", .first = "monokai_pro" }, .{ .title = "Tokyo Night", .first = "tokyonight_night" }, .{ .title = "Rosé Pine", .first = "rose_pine" }, .{ .title = "Catppuccin", .first = "catppuccin_latte" }, .{ .title = "Seoul256", .first = "seoul256_dark_233" }, .{ .title = "Zenbones", .first = "zenbones_light" }, .{ .title = "Nord", .first = "nord" }, .{ .title = "Ayu", .first = "ayu_dark" }, .{ .title = "Doom One", .first = "doom_one" }, .{ .title = "Legacy themes", .first = "helix" }, }; fn indexOfTheme(comptime name: []const u8) usize { return comptime blk: { @setEvalBranchQuota(100000); for (themes[0..native_count], 0..) |t, i| if (std.mem.eql(u8, t.name, name)) break :blk i; @compileError("theme_groups names " ++ name ++ ", which is not one of ours"); }; } /// The heading of the picker section that starts at ring index `index`. pub fn groupAt(index: usize) ?[]const u8 { inline for (theme_groups) |g| if (index == comptime indexOfTheme(g.first)) return g.title; if (index == native_count) return "Imported themes (helix, zed)"; return null; } /// Original and classic-inspired Pardes palettes precede retained imports. pub const native_theme_count = 15; comptime { if (themes.len > std.math.maxInt(u16) + 1) @compileError("runtime config theme index no longer fits u16"); } comptime { @setEvalBranchQuota(20000); const ours = fold(curated).len; for (themes[0..ours]) |c| for (themes[ours..]) |g| if (std.mem.eql(u8, c.name, g.name)) @compileError("theme name \"" ++ c.name ++ "\" is both ours and generated; rename the vendored source"); } pub const ChromeTheme = struct { tag_bg: [3]u8, tag_fg: [3]u8, tagline_bg: [3]u8, tagline_fg: [3]u8, tag_active_bg: [3]u8, tag_active_fg: [3]u8, tag_name_fg: [3]u8, tag_active_name_fg: [3]u8, border: [3]u8, empty_col: [3]u8, search_bg: [3]u8, search_fg: [3]u8, tag_reading_bg: [3]u8, diagnostic_error: [3]u8, diagnostic_warning: [3]u8, diagnostic_info: [3]u8, diagnostic_hint: [3]u8, box: [3]u8, box_dim: [3]u8, column_box: [3]u8, column_box_dim: [3]u8, lineno: [3]u8, scroll_track: [3]u8, scroll_thumb: [3]u8, roles: Roles, pub fn fromTheme(th: *const Theme) ChromeTheme { // The initial chrome is resolved at compile time: contrast takes pow. @setEvalBranchQuota(1_000_000); const active_bg = focusTint(th); const active_fg = th.tag_active_fg orelse th.tag_fg; // A name is always tinted: a theme that names no tint gets one of // its own hues, on each ground. One that names only the plain tint // keeps it when focused too. const name_fg = th.tag_name_fg orelse (derivedNameTint(th, th.tag_fg, th.tag_bg) orelse th.tag_fg); const active_name_fg = th.tag_active_name_fg orelse (th.tag_name_fg orelse (derivedNameTint(th, active_fg, active_bg) orelse active_fg)); const reading = readingOf(th); return .{ .tag_bg = th.tag_bg, .tag_fg = th.tag_fg, .tagline_bg = th.tagline_bg orelse th.tag_bg, .tagline_fg = th.tagline_fg orelse th.tag_fg, .tag_active_bg = active_bg, .tag_active_fg = active_fg, .tag_name_fg = name_fg, .tag_active_name_fg = active_name_fg, .border = separatorOf(th), .empty_col = th.empty_col orelse separatorOf(th), .search_bg = th.search_bg orelse th.sel_bg, .search_fg = th.search_fg orelse th.sel_fg, .tag_reading_bg = reading, // A theme's error ink, else its palette's red (UX E3). .diagnostic_error = th.diagnostic_error orelse if (th.palette) |pal| pal[1] else (th.fg orelse th.tag_fg), .diagnostic_warning = th.diagnostic_warning orelse (th.fg orelse th.tag_fg), .diagnostic_info = th.diagnostic_info orelse (th.fg orelse th.tag_fg), .diagnostic_hint = th.diagnostic_hint orelse (th.fg orelse th.tag_fg), .box = th.box, .box_dim = th.box_dim, .column_box = th.column_box orelse th.num, .column_box_dim = th.column_box_dim orelse mix(th.column_box orelse th.num, th.tag_bg), .lineno = th.lineno, .scroll_track = th.scroll_track, .scroll_thumb = th.scroll_thumb, .roles = .of(th, th.tag_bg, active_bg, reading), }; } }; /// A tag's ground in the walk UI (UX DESIGN.md D4): the plain tag's, the /// focused one's tint, a reading pane's tint, focused or not (its ink is /// the focused tag's while it has the keyboard). pub const TagGround = enum { plain, focused, reading, reading_focused }; /// The inks drawn on one ground: labels and rows (`text`, 4.5:1 at least), /// hints, meta and forward steps (`dim`, 3.5:1, never under 3), and the /// spines and the rules between steps (`rule`, 2:1). pub const Inks = struct { ground: [3]u8, text: [3]u8, dim: [3]u8, rule: [3]u8 }; /// The walk UI's colour roles (UX DESIGN.md D4), worked out from a theme /// once, with its chrome (never a frame), each held to its floor on every /// ground it is drawn on: a tag's four (`tag`) and a band's cursor row on /// each of them (`selected`, its ground that tag's selection). pub const Roles = struct { tag: [4]Inks, selected: [4]Inks, /// The notice row's (the tagline's ground): its dim words. notice: Inks, /// Key cells, a level's or a row's key letters, `▶`, `•`, a target's /// keys: 4.5:1 on every tag ground and on the selection. key: [3]u8, /// The letters a query matched: an ink, never a ground, 4.5:1 on every /// tag ground and on the selection. match: [3]u8, /// The body's places and a preview's landing line, and the current /// one (its matched span): grounds off the page, its ink on them 4.5:1. hit: [3]u8, hit_current: [3]u8, /// A message's ink by its kind (Messages.ink): 4.5:1 on the tags and /// the page. err: [3]u8, warn: [3]u8, question: [3]u8, hint: [3]u8, pub const text_floor: f32 = 4.5; pub const dim_floor: f32 = 3; pub const rule_floor: f32 = 1.8; pub const rule_ceiling: f32 = 2.5; pub const ink_floor: f32 = 4.5; pub const hit_floor: f32 = 1.5; pub const hit_current_floor: f32 = 1.9; pub const reading_distance: f32 = 0.04; pub fn on(r: *const Roles, ground: TagGround) *const Inks { return &r.tag[@backingInt(ground)]; } pub fn selectedOn(r: *const Roles, ground: TagGround) *const Inks { return &r.selected[@backingInt(ground)]; } /// The selection's floor off a tag's ground: 1.4:1 on a dark tag, 1.25 /// on a light one. pub fn selectionFloor(ground: [3]u8) f32 { return if (relativeLuminance(ground) < 0.18) 1.4 else 1.25; } fn of(th: *const Theme, plain: [3]u8, focused: [3]u8, reading: [3]u8) Roles { const grounds = [4][3]u8{ plain, focused, reading, reading }; const plain_ink = th.tag_fg; const focused_ink = th.tag_active_fg orelse th.tag_fg; const texts = [4][3]u8{ plain_ink, focused_ink, plain_ink, focused_ink }; var r: Roles = undefined; for (&r.tag, &r.selected, grounds, texts) |*inks, *selected, ground, ink| { inks.* = inksOn(ground, ink); selected.* = inksOn(selectionOf(th.tag_sel_bg orelse th.sel_bg, ground, inks.text), inks.text); } r.notice = inksOn(th.tagline_bg orelse th.tag_bg, th.tagline_fg orelse th.tag_fg); const tag_grounds = [_][3]u8{ plain, focused, reading, r.selected[0].ground, r.selected[1].ground, r.selected[2].ground, r.selected[3].ground }; r.key = pushAway(th.box, &tag_grounds, ink_floor); r.match = pushAway(matchHue(th), &tag_grounds, ink_floor); const page = th.bg orelse null_page; const body_ink = th.fg orelse th.tag_fg; const dark = relativeLuminance(page) < 0.18; // The theme's search ground where it stands off the page and the // body reads on it; else the page a little way toward its hue (the // warm accent's without one). The current one as far past the hit // as 32 % is past 18 % (38 past 22 on a light page). const hue = th.search_bg orelse th.num; const own = th.search_bg != null and contrast(hue, page) >= hit_floor and contrast(body_ink, hue) >= ink_floor; const at: f32 = if (own) 1 else if (dark) 0.18 else 0.22; r.hit = if (own) hue else hitOf(page, hue, body_ink, at, hit_floor); const past: f32 = if (dark) 0.32 / 0.18 else 0.38 / 0.22; r.hit_current = hitOf(page, hue, body_ink, at * past, hit_current_floor); // Never fainter than the hit, where the ink holds both short. if (contrast(r.hit_current, page) < contrast(r.hit, page)) r.hit_current = r.hit; const message_grounds = [_][3]u8{ plain, focused, reading, page }; const ink = th.fg orelse th.tag_fg; r.err = pushAway(th.diagnostic_error orelse if (th.palette) |pal| pal[1] else ink, &message_grounds, ink_floor); r.warn = pushAway(th.diagnostic_warning orelse ink, &message_grounds, ink_floor); r.question = pushAway(th.diagnostic_info orelse ink, &message_grounds, ink_floor); r.hint = pushAway(th.diagnostic_hint orelse ink, &message_grounds, ink_floor); return r; } }; /// A tag's text, dim and rule inks on `ground`, from its ink (pushed to the /// text floor where it has less). fn inksOn(ground: [3]u8, ink: [3]u8) Inks { const text = pushAway(ink, &.{ground}, Roles.text_floor); return .{ .ground = ground, .text = text, .dim = toward(text, ground, 3.5), .rule = toward(text, ground, 2) }; } /// `ink` mixed toward `ground` (OKLab) by hundredths as far as it still /// reads at `floor` on it: found by halves (its contrast falls as it nears /// the ground), seven mixes where a walk took up to a hundred (the first /// frame's bodyChrome derives them too). fn toward(ink: [3]u8, ground: [3]u8, floor: f32) [3]u8 { const a = toOklab(ink); const b = toOklab(ground); var best = ink; var lo: u32 = 0; var hi: u32 = 101; while (hi - lo > 1) { const mid = (lo + hi) / 2; const t = @as(f32, @floatFromInt(mid)) / 100; const c = fromOklab(.{ a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t }); if (contrast(c, ground) >= floor) { lo = mid; best = c; } else hi = mid; } return best; } /// `ink` pushed by fiftieths toward white or black, whichever reads better /// on all its grounds, until it reads at `floor` on every one; where no ink /// does (solarized's mid-grey tag), that end, the most any ink reaches. pub fn pushAway(ink: [3]u8, grounds: []const [3]u8, floor: f32) [3]u8 { const white: [3]u8 = @splat(255); const black: [3]u8 = @splat(0); if (leastContrast(ink, grounds) >= floor) return ink; const end = if (leastContrast(white, grounds) >= leastContrast(black, grounds)) white else black; const a = toOklab(ink); const b = toOklab(end); var step: f32 = 0; while (step <= 50) : (step += 1) { const t = step / 50; const c = fromOklab(.{ a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t }); if (leastContrast(c, grounds) >= floor) return c; } return end; } fn leastContrast(ink: [3]u8, grounds: []const [3]u8) f32 { var least: f32 = 21; for (grounds) |g| least = @min(least, contrast(ink, g)); return least; } /// The match's hue: the search's ink where it is a hue of its own (a port's /// is often the page's or the tag's, set for the search's ground), else the /// theme's warm accent. fn matchHue(th: *const Theme) [3]u8 { const own = th.search_fg orelse return th.num; const lab = toOklab(own); return if (@sqrt(lab[1] * lab[1] + lab[2] * lab[2]) >= name_tint_chroma) own else th.num; } /// The selection a band's cursor row is drawn on over `ground`: the /// theme's where it stands off it, else moved by hundredths toward the /// text, then away from it, to the first that does with the text still at /// 4.5:1 on it; where none does (a tag whose text has no contrast to /// spare), the one furthest off it. fn selectionOf(own: [3]u8, ground: [3]u8, text: [3]u8) [3]u8 { var best = own; var best_off: f32 = 0; const away: [3]u8 = if (relativeLuminance(text) > relativeLuminance(own)) @splat(0) else @splat(255); if (contrast(own, ground) >= Roles.selectionFloor(ground) and contrast(text, own) >= Roles.text_floor) return own; const o = toOklab(own); for ([2][3]u8{ text, away }) |end| { const e = toOklab(end); var step: f32 = 0; while (step <= 100) : (step += 1) { const t = step / 100; const c = fromOklab(.{ o[0] + (e[0] - o[0]) * t, o[1] + (e[1] - o[1]) * t, o[2] + (e[2] - o[2]) * t }); if (contrast(text, c) < Roles.text_floor) break; const off = contrast(c, ground) / Roles.selectionFloor(ground); if (off >= 1) return c; if (off > best_off) { best = c; best_off = off; } } } return best; } /// A ground off `page` toward `hue` at `t` (past 1, beyond the hue, as far /// as the gamut goes), held where the body's `ink` reads on it at 4.5:1 /// (or its own on the page, where that is less); on toward the hue, the /// least way that stands off the page at `floor`, where the ink still /// reads on it; else moved on toward the ink until it stands off the page /// at `floor`, as far as the ink allows. fn hitOf(page: [3]u8, hue: [3]u8, ink: [3]u8, t: f32, floor: f32) [3]u8 { const a = toOklab(page); const b = toOklab(hue); const ink_floor = @min(Roles.ink_floor, contrast(ink, page)); var k = t; var c = fromOklab(.{ a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k }); while (contrast(ink, c) < ink_floor and k > 0) { k -= t / 50; c = fromOklab(.{ a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k }); } // Found by halves, seven mixes: the nearer the hue, the further off // the page (UX E7 7b: a landing line 1.5:1, its span 1.9:1). if (contrast(c, page) < floor and k < 1 and contrast(hue, page) >= floor) { var lo = k; var hi: f32 = 1; var far = hue; for (0..7) |_| { const mid = (lo + hi) / 2; const m = fromOklab(.{ a[0] + (b[0] - a[0]) * mid, a[1] + (b[1] - a[1]) * mid, a[2] + (b[2] - a[2]) * mid }); if (contrast(m, page) < floor) lo = mid else { hi = mid; far = m; } } if (contrast(ink, far) >= ink_floor) c = far; } const start = c; var step: f32 = 1; while (contrast(c, page) < floor and step <= 50) : (step += 1) { const next = mixOklab(start, ink, step / 100); if (contrast(ink, next) < ink_floor) break; c = next; } return c; } /// A reading pane's tag (UX DESIGN.md D4): the theme's own where it stands /// off the tag, else the tag shifted toward paper yellow by 0.04 in OKLab /// and lighter by half that on a dark tag (darker on a light), so it reads /// as a page; then less light, or darker, where its text would lose /// contrast, and further where the bytes cannot show so small a step (a /// near-black tag). fn readingOf(th: *const Theme) [3]u8 { if (th.tag_reading_bg) |own| if (oklabDistance(toOklab(own), toOklab(th.tag_bg)) >= Roles.reading_distance) return own; const tag = toOklab(th.tag_bg); const paper = toOklab(.{ 0xdc, 0xc8, 0x78 }); const da = paper[1] - tag[1]; const db = paper[2] - tag[2]; const n = @max(@sqrt(da * da + db * db), 1e-6); const sign: f32 = if (relativeLuminance(th.tag_bg) < 0.18) 1 else -1; // Away from the text's lightness, where the first lean costs it. const away: f32 = if (relativeLuminance(th.tag_fg) > relativeLuminance(th.tag_bg)) -1 else 1; const inks = [2][3]u8{ th.tag_fg, th.tag_active_fg orelse th.tag_fg }; var best = th.tag_bg; var best_text: f32 = -21; var reach = Roles.reading_distance; while (reach <= 0.2) : (reach *= 1.25) { for ([_]f32{ sign * 0.5, 0, away * 0.5, away, away * 1.5 }) |lean| { const c = fromOklab(.{ tag[0] + lean * reach, tag[1] + da / n * reach, tag[2] + db / n * reach }); if (oklabDistance(toOklab(c), tag) < Roles.reading_distance) continue; // Each ink by its own floor: 7:1, or what it has on the tag. var text: f32 = 21; for (inks) |ink| text = @min(text, contrast(ink, c) - (@min(7, contrast(ink, th.tag_bg)) - 0.01)); if (text >= 0) return c; if (text > best_text) { best = c; best_text = text; } } } return best; } pub const initial_chrome = ChromeTheme.fromTheme(&themes[0]); fn nextThemeFileGeneration(p: *Pardes) u32 { p.theme_file_generation +%= 1; if (p.theme_file_generation == 0) p.theme_file_generation = 1; return p.theme_file_generation; } pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { const input = std.mem.trim(u8, argument, " \t\r\n"); if (input.len == 0 or !std.mem.endsWith(u8, input, ".zon")) { p.reportError(.at(id), "theme file", error.InvalidThemePath); return; } const absolute = std.Io.Dir.path.isAbsolute(input); const config_dir = if (absolute) null else p.configDir(); if (!absolute and config_dir == null) { p.reportError(.at(id), "theme file", error.NoConfigDirectory); return; } var joined: [4095]u8 = undefined; const resolved = if (absolute) input else path: { const dir = config_dir.?; const separator = if (dir.len > 0 and dir[dir.len - 1] != std.Io.Dir.path.sep) std.Io.Dir.path.sep_str else ""; break :path std.fmt.bufPrint(&joined, "{s}{s}{s}", .{ dir, separator, input }) catch { p.reportError(.at(id), "theme file", error.PathTooLong); return; }; }; if (!p.theme_file_path.set(resolved)) { p.reportError(.at(id), "theme file", error.PathTooLong); return; } p.theme_file_pane = .at(id); const generation = nextThemeFileGeneration(p); p.emit(.{ .theme_file = .{ .generation = generation, .on = true } }); } /// The .zon a ThemeFile loaded, while it is the theme in effect: what /// /ctl and DumpConfig say in place of `Theme `, since the name /// inside the file is no theme `Theme` knows. pub fn loadedThemeFile(p: *const Pardes) ?[]const u8 { const path = p.theme_file_loaded.get(); return if (p.custom_theme != null and path.len > 0) path else null; } pub const ThemeFileRequest = struct { path: []const u8, pane: pardes.Pane.Id, }; /// Borrow the current request while a native host performs its synchronous /// read. A later command invalidates an already-queued generation. pub fn themeFileRequest(p: *const Pardes, generation: u32) ?ThemeFileRequest { if (generation == 0 or generation != p.theme_file_generation) return null; const path = p.theme_file_path.get(); if (path.len == 0) return null; return .{ .path = path, .pane = p.theme_file_pane }; } pub fn failThemeFile(p: *Pardes, generation: u32, err: anyerror) void { const request = themeFileRequest(p, generation) orelse return; themeFileError(p, request, err); } /// A theme file's failure, said with its path: `theme file x.zon: file /// not found`, not which file left to guess. fn themeFileError(p: *Pardes, request: ThemeFileRequest, err: anyerror) void { var words: [128]u8 = undefined; themeFileFailure(p, request, pardes.Messages.errorWords(err, &words)); } fn themeFileFailure(p: *Pardes, request: ThemeFileRequest, why: []const u8) void { var said: pardes.Kind.Buf(520) = .{}; var cut: [200]u8 = undefined; const path = @import("ninep/tree.zig").fitErr(request.path, &cut); p.reportFailure(request.pane.index(), said.print("theme file {s}: {s}", .{ path, why })); revertThemeFile(p); } /// A ThemeFile that did not load changes nothing: the request goes back to /// the file last loaded (watched again), or to none, so /ctl and DumpConfig /// still read what replays. A bad save of the loaded file itself keeps it. fn revertThemeFile(p: *Pardes) void { const loaded = p.theme_file_loaded.get(); if (std.mem.eql(u8, loaded, p.theme_file_path.get())) return; if (loaded.len == 0) p.theme_file_path.clear() else _ = p.theme_file_path.set(loaded); const generation = nextThemeFileGeneration(p); p.emit(.{ .theme_file = .{ .generation = generation, .on = loaded.len > 0 } }); } /// The deepest a theme file's brackets nest: its schema is three levels /// deep, and std's ZON parser recurses a level a bracket with no bound of /// its own (a file 5 000 deep overflowed a 16 MiB stack in a Debug build: /// the session's end, at every start that loaded it). const max_theme_nesting = 64; /// How deep `source`'s brackets nest, as std's tokenizer reads it (strings /// and comments are tokens of their own). fn nesting(source: [:0]const u8) usize { var tokens: std.zig.Tokenizer = .init(source); var depth: usize = 0; var most: usize = 0; while (true) switch (tokens.next().tag) { .eof => return most, .l_brace, .l_bracket, .l_paren => { depth += 1; most = @max(most, depth); }, .r_brace, .r_bracket, .r_paren => depth -|= 1, else => {}, }; } pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8) bool { // ZON's generated field dispatch grows with the complete theme schema. @setEvalBranchQuota(10000); const request = themeFileRequest(p, generation) orelse return false; if (bytes.len > 1024 * 1024) { themeFileError(p, request, error.ThemeFileTooLarge); return false; } const source = p.gpa.dupeSentinel(u8, bytes, 0) catch |err| { themeFileError(p, request, err); return false; }; defer p.gpa.free(source); if (nesting(source) > max_theme_nesting) { themeFileFailure(p, request, std.fmt.comptimePrint("nested past {d} levels", .{max_theme_nesting})); return false; } // The parse's results live in `arena`; the theme kept owns only its name. var arena: std.heap.ArenaAllocator = .init(p.gpa); defer arena.deinit(); var diagnostics: std.zon.parse.Diagnostics = undefined; var parsed = std.zon.parse.fromSlice(Theme, .{ .gpa = p.gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics }) catch |err| { if (err != error.ParseZon) themeFileError(p, request, err) else { // Which line, and what the parser wanted there. var why: [200]u8 = undefined; themeFileFailure(p, request, pardes.Messages.zonWhy(&diagnostics, &why)); } return false; }; if (parsed.name.len == 0 or parsed.name.len > 255) { themeFileError(p, request, error.InvalidThemeName); return false; } parsed.name = p.gpa.dupe(u8, parsed.name) catch |err| { themeFileError(p, request, err); return false; }; p.chrome = ChromeTheme.fromTheme(&parsed); const old = p.custom_theme; p.custom_theme = parsed; if (old) |theme_value| p.gpa.free(theme_value.name); _ = p.theme_file_loaded.set(request.path); _ = p.scratch.reset(.{ .retain_with_limit = pardes.memory.limits.scratch_kept }); p.sync(); return true; } pub fn finishThemeInitialization(p: *Pardes) void { // The session's own theme's: never one the window previews // (`previewTheme`). p.chrome = ChromeTheme.fromTheme(if (p.custom_theme) |*custom| custom else &themes[p.settings.theme]); } /// Themes near `name`, a line of them, for a Theme given a name there is /// none of (all of them, Themes, are too many for a refused write): every /// one sharing its first letter when they fit in `buf`, else the 8 nearest. pub fn themesNear(buf: []u8, name: []const u8) []const u8 { var w = std.Io.Writer.fixed(buf); for (themes) |t| { if (name.len > 0 and std.ascii.toLower(t.name[0]) != std.ascii.toLower(name[0])) continue; if (!putName(&w, buf.len, t.name)) break; } else if (w.buffered().len > 0) return w.buffered(); // The nearest, most alike first: ponytail, a plain score (shared // prefix, the name inside, its letters in order), no edit distance. var best: [8]usize = undefined; var scores: [8]usize = undefined; var n: usize = 0; for (themes, 0..) |t, i| { const s = likeness(t.name, name); var at = n; while (at > 0 and scores[at - 1] < s) at -= 1; if (at == best.len) continue; const last = @min(n, best.len - 1); var k = last; while (k > at) : (k -= 1) { best[k] = best[k - 1]; scores[k] = scores[k - 1]; } best[at] = i; scores[at] = s; n = @min(n + 1, best.len); } w = std.Io.Writer.fixed(buf); for (best[0..n]) |i| if (!putName(&w, buf.len, themes[i].name)) break; return w.buffered(); } /// One more name on the line, whole, or none: false when it would not fit. fn putName(w: *std.Io.Writer, cap: usize, name: []const u8) bool { const sep: []const u8 = if (w.buffered().len > 0) " " else ""; if (w.buffered().len + sep.len + name.len > cap) return false; w.print("{s}{s}", .{ sep, name }) catch return false; return true; } fn likeness(theme_name: []const u8, name: []const u8) usize { var prefix: usize = 0; while (prefix < @min(theme_name.len, name.len) and std.ascii.toLower(theme_name[prefix]) == std.ascii.toLower(name[prefix])) prefix += 1; // Its letters found in order, one not there passed over. var in_order: usize = 0; var pos: usize = 0; for (name) |c| { const at = for (theme_name[pos..], pos..) |t, i| { if (std.ascii.toLower(t) == std.ascii.toLower(c)) break i; } else continue; in_order += 1; pos = at + 1; } const inside: usize = if (name.len > 0 and std.ascii.findIgnoreCase(theme_name, name) != null) name.len * 4 else 0; return prefix * 3 + in_order + inside; } /// The theme named `name`, whatever its case. pub fn themeIndex(name: []const u8) ?usize { for (themes, 0..) |t, i| if (std.ascii.eqlIgnoreCase(t.name, name)) return i; return null; } /// The window wearing theme `index` (SPEC §5.1, a theme's preview), or /// its own again (null): nothing loaded, the session's theme and a theme /// file as they were; its chrome worked out once a theme, never a frame. /// The themes picker's (Pick.zig), and `:theme `'s argument rows'. pub fn previewTheme(p: *Pardes, index: ?usize) void { const i = index orelse { p.theme_preview = null; return; }; if (i >= themes.len) return; if (p.theme_preview) |had| if (had == i) return; p.theme_preview = @intCast(i); p.preview_chrome = ChromeTheme.fromTheme(&themes[i]); } pub fn setThemeIndex(p: *Pardes, index: usize) void { if (index >= themes.len or (p.custom_theme == null and p.theme_file_path.get().len == 0 and index == @as(usize, p.settings.theme))) return; p.chrome = ChromeTheme.fromTheme(&themes[index]); if (p.custom_theme) |theme_value| { p.custom_theme = null; p.gpa.free(theme_value.name); } p.theme_file_loaded.clear(); if (p.theme_file_path.get().len > 0) { p.theme_file_path.clear(); const generation = nextThemeFileGeneration(p); p.emit(.{ .theme_file = .{ .generation = generation, .on = false } }); } p.settings.theme = @intCast(index); } test "every native theme's separators stand off its page, and its focus tint off its tag" { for (themes[0..native_count]) |*theme| { const chrome = ChromeTheme.fromTheme(theme); const page = theme.bg orelse null_page; try std.testing.expect(contrast(chrome.border, page) >= separator_floor); // A dark page's focused tag is told by its band too, not the grip // alone; acme's (light, and acme's own) is told by its button. if (relativeLuminance(page) < 0.18) try std.testing.expect(theme.tag_active_bg != null); if (theme.tag_active_bg) |own| { try std.testing.expect(contrast(chrome.tag_active_bg, theme.tag_bg) >= focusTintFloor(theme)); // And its text still reads. const ink = theme.tag_active_fg orelse theme.tag_fg; try std.testing.expect(contrast(ink, chrome.tag_active_bg) >= @min(contrast(ink, own), 4.5) - 0.01); } } } test "every faithful port meets pardes's chrome floors in its own colours, with nothing left to derive" { const first = comptime indexOfTheme("lapis") + 1; const last = comptime indexOfTheme("helix"); for (themes[first..last]) |*th| { const chrome = ChromeTheme.fromTheme(th); const page = th.bg.?; // Written out already adjusted: the run-time lift and push leave // the file's own values, so what the file says is what is drawn. try std.testing.expectEqual(th.border.?, chrome.border); try std.testing.expectEqual(th.tag_active_bg.?, chrome.tag_active_bg); try std.testing.expect(contrast(th.border.?, page) >= separator_floor); try std.testing.expect(contrast(th.tag_active_bg.?, th.tag_bg) >= focusTintFloor(th)); try std.testing.expect(contrast(th.tag_fg, th.tag_bg) >= 4.5); try std.testing.expect(contrast(th.tag_active_fg.?, th.tag_active_bg.?) >= 4.5); try std.testing.expect(contrast(th.box_dim, th.tag_bg) >= 1.5); try std.testing.expect(th.palette != null); // A status bar of its own reads as tag text does; without one the // tagline is the tag's. try std.testing.expect(contrast(chrome.tagline_fg, chrome.tagline_bg) >= 4.5); if (th.tagline_bg == null) try std.testing.expectEqual(th.tag_bg, chrome.tagline_bg); } } test "a derived separator or tint keeps the theme's own when it already stands off" { const forge = &themes[ for (themes[0..native_count], 0..) |t, i| { if (std.mem.eql(u8, t.name, "forge")) break i; } else unreachable ]; const chrome = ChromeTheme.fromTheme(forge); try std.testing.expectEqual(forge.border.?, chrome.border); // forge's own tint is 1.23:1 off its tag: pushed on the way it leans. try std.testing.expect(!std.meta.eql(forge.tag_active_bg.?, chrome.tag_active_bg)); for (chrome.tag_active_bg, forge.tag_active_bg.?, forge.tag_bg) |pushed, own, plain| try std.testing.expect(pushed >= own and own >= plain); } test "an OKLab fade holds its ends exactly and keeps a mid-way bright" { for ([_][3]u8{ .{ 0, 0, 0 }, .{ 255, 255, 255 }, .{ 0x0c, 0x0c, 0x0e }, .{ 0xe8, 0xc4, 0x6a }, .{ 0x1c, 0x51, 0x72 } }) |rgb| { try std.testing.expectEqual(rgb, fromOklab(toOklab(rgb))); try std.testing.expectEqual(rgb, mixOklab(rgb, .{ 10, 200, 30 }, 0)); } // Red to green through sRGB bytes dips dark at the middle; through // OKLab it keeps its lightness. const red: [3]u8 = .{ 255, 0, 0 }; const green: [3]u8 = .{ 0, 200, 0 }; const srgb_mid = mix(red, green); const lab_mid = mixOklab(red, green, 0.5); try std.testing.expect(relativeLuminance(lab_mid) > relativeLuminance(srgb_mid) * 1.3); } test "the picker's sections run in ring order and cover it" { var last: usize = 0; inline for (theme_groups, 0..) |g, n| { const at = comptime indexOfTheme(g.first); if (n == 0) try std.testing.expectEqual(@as(usize, 0), at) else try std.testing.expect(at > last); last = at; } try std.testing.expectEqualStrings("Pardes themes", groupAt(0).?); // acme is a current theme, not a legacy one. try std.testing.expect(indexOfTheme("acme") < indexOfTheme("helix")); try std.testing.expect(groupAt(native_count) != null); } test "seoul256's twelve backgrounds ring in their order, after Catppuccin and before Zenbones" { const names = [_][]const u8{ "seoul256_dark_233", "seoul256_dark_234", "seoul256_dark_235", "seoul256_dark_236", "seoul256_dark_237", "seoul256_dark_238", "seoul256_dark_239", "seoul256_light_252", "seoul256_light_253", "seoul256_light_254", "seoul256_light_255", "seoul256_light_256", }; const first = indexOfTheme("seoul256_dark_233"); for (names, themes[first..][0..names.len]) |name, t| try std.testing.expectEqualStrings(name, t.name); try std.testing.expectEqualStrings("catppuccin_mocha", themes[first - 1].name); try std.testing.expectEqualStrings("zenbones_light", themes[first + names.len].name); } test "a theme hint drops whole names to fit, never cutting one" { var buf: [23]u8 = undefined; const said = themesNear(&buf, "9dracula"); var words = std.mem.tokenizeScalar(u8, said, ' '); while (words.next()) |word| { var whole = false; for (themes) |t| whole = whole or std.mem.eql(u8, t.name, word); try std.testing.expect(whole); } } test "a theme file that cannot be read is named in the failure" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); requestThemeFile(p, 0, "/nowhere/mine.zon"); failThemeFile(p, p.theme_file_generation, error.FileNotFound); const pane = p.panes[0].?; try std.testing.expect(std.mem.indexOf(u8, p.messages.saidBy(pane), "theme file /nowhere/mine.zon: ") != null); } test "a theme file nested 10, 1 000 and 100 000 deep is refused in words, never a stack overflow" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .config_dir = "/tmp/pardes-config" }); defer p.deinit(); for ([_]usize{ 10, 1000, 100_000 }) |depth| { requestThemeFile(p, 0, "themes/deep.zon"); var source: std.ArrayList(u8) = .empty; defer source.deinit(gpa); try source.appendSlice(gpa, ".{ .name = \"deep\", .bg = "); for (0..depth) |_| try source.appendSlice(gpa, ".{"); try source.appendSlice(gpa, "1"); for (0..depth) |_| try source.append(gpa, '}'); try source.appendSlice(gpa, " }\n"); p.messages.live_len = 0; // Up to 2026-11-23 std's parser took it: 5 000 deep overflowed the // stack (a Debug build's 16 MiB). try std.testing.expect(!loadThemeFile(p, p.theme_file_generation, source.items)); const said = p.messages.saidBy(p.panes[0].?); std.testing.expect(std.mem.indexOf(u8, said, "theme file /tmp/pardes-config/themes/deep.zon: ") != null) catch |err| { std.debug.print("{d} deep: said {s}\n", .{ depth, said }); return err; }; } } test "ThemeFile parses ZON atomically and Theme returns to the compiled ring" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .config_dir = "/tmp/pardes-config", }); defer p.deinit(); while (p.nextEffect()) |_| {} requestThemeFile(p, 0, "themes/mine.zon"); const request_effect = while (p.nextEffect()) |effect| switch (effect) { .theme_file => |request| break request, else => {}, } else return error.MissingThemeFileEffect; try std.testing.expect(request_effect.on); const request = themeFileRequest(p, request_effect.generation) orelse return error.MissingThemeFileRequest; try std.testing.expectEqualStrings("/tmp/pardes-config/themes/mine.zon", request.path); var custom = themes[0]; custom.name = "mine"; custom.bg = .{ 1, 2, 3 }; custom.tag_bg = .{ 4, 5, 6 }; var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator); defer encoded.deinit(); try std.zon.stringify.serialize(custom, .{ .whitespace = true }, &encoded.writer); try std.testing.expect(loadThemeFile(p, request_effect.generation, encoded.written())); try std.testing.expectEqualStrings("mine", p.theme().name); try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), p.theme().bg); try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*); // A half-written save is rejected without disturbing the last good value. try std.testing.expect(!loadThemeFile(p, request_effect.generation, ".{ .name = ")); // Said with its line, in words: never a bare `parse zon`. const said = p.messages.saidBy(p.panes[0].?); try std.testing.expect(std.mem.indexOf(u8, said, ": line 1: ") != null and std.mem.indexOf(u8, said, "parse zon") == null); try std.testing.expectEqualStrings("mine", p.theme().name); try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), p.theme().bg); setThemeIndex(p, 0); try std.testing.expectEqualStrings(themes[0].name, p.theme().name); try std.testing.expect(themeFileRequest(p, request_effect.generation) == null); const stop = while (p.nextEffect()) |effect| switch (effect) { .theme_file => |theme_file| break theme_file, else => {}, } else return error.MissingThemeFileStop; try std.testing.expect(!stop.on); } test "native themes keep text and UI roles readable on their own surfaces" { const names = [_][]const u8{ "orchard", "dusk", "ink", "paper", "daybreak", "atelier", "forge", "lagoon", "solarium", "spectrum", "harvest", "clay", "forge_black", "forge_soft", "orchard_black" }; try std.testing.expectEqual(names.len, native_theme_count); for (themes[0..names.len], names) |th, name| { try std.testing.expectEqualStrings(name, th.name); const chrome = ChromeTheme.fromTheme(&th); const minimum: f32 = if (std.mem.eql(u8, name, "ink") or std.mem.eql(u8, name, "daybreak")) 7 else 4.5; const text_colors = [_][3]u8{ th.fg.?, th.kw, th.str, th.num, th.comment, chrome.diagnostic_error, chrome.diagnostic_warning, chrome.diagnostic_info, chrome.diagnostic_hint, }; for (text_colors) |fg| try std.testing.expect(contrast(fg, th.bg.?) >= minimum); // Gutters are orientation aids, not source text: stay visible without // competing with comments or pulling attention away from the body. try std.testing.expect(contrast(th.lineno, th.bg.?) >= 2.5); try std.testing.expect(contrast(th.lineno, th.bg.?) <= 4); try std.testing.expect(contrast(th.lineno_active.?, th.bg.?) >= contrast(th.lineno, th.bg.?)); try std.testing.expect(contrast(th.lineno_active.?, th.bg.?) <= 4.5); try std.testing.expect(contrast(th.comment, th.bg.?) >= 5); try std.testing.expect(contrast(th.comment, th.bg.?) >= contrast(th.lineno, th.bg.?) + 2); try std.testing.expect(contrast(th.tag_fg, th.tag_bg) >= minimum); try std.testing.expect(contrast(chrome.tag_active_fg, chrome.tag_active_bg) >= minimum); try std.testing.expect(th.tag_name_fg != null); try std.testing.expect(contrast(chrome.tag_name_fg, th.tag_bg) >= minimum); try std.testing.expect(contrast(chrome.tag_active_name_fg, chrome.tag_active_bg) >= minimum); // Focus stays on the same tonal surface, rather than inverting a // whole command strip. Text remains readable in both states. try std.testing.expect(contrast(chrome.tag_active_bg, th.tag_bg) <= 1.6); try std.testing.expect(contrast(chrome.tag_active_fg, th.tag_fg) <= 1.6); try std.testing.expect(contrast(th.sel_fg, th.sel_bg) >= minimum); try std.testing.expect(contrast(chrome.search_fg, chrome.search_bg) >= minimum); // ANSI black can intentionally match the page (for backgrounds). All // other ANSI foregrounds, including bright black, remain legible. for (th.palette.?[1..]) |fg| try std.testing.expect(contrast(fg, th.bg.?) >= minimum); } } test "native filename tints change hue without changing perceived lightness" { for (themes[0..native_theme_count]) |th| { try std.testing.expect(th.tag_name_fg != null and th.tag_active_name_fg != null); const chrome = ChromeTheme.fromTheme(&th); const pairs = [2][2][3]u8{ .{ chrome.tag_fg, chrome.tag_name_fg }, .{ chrome.tag_active_fg, chrome.tag_active_name_fg }, }; for (pairs) |pair| { const base = toOklab(pair[0]); const name = toOklab(pair[1]); // Half a lightness point allows 8-bit quantization without a // basename becoming visibly brighter or darker than its tag. try std.testing.expectApproxEqAbs(base[0], name[0], 0.005); const base_chroma = @sqrt(base[1] * base[1] + base[2] * base[2]); const name_chroma = @sqrt(name[1] * name[1] + name[2] * name[2]); try std.testing.expect(base_chroma > 0.005 and name_chroma > 0.02); // A normalized dot product <= cos(60 degrees) means a clear // hue difference, independent of saturation or lightness. const hue_cosine = (base[1] * name[1] + base[2] * name[2]) / (base_chroma * name_chroma); try std.testing.expect(hue_cosine <= 0.5); } } } test "native dark palettes choose near-black or deliberately soft contrast" { for (themes[0..native_theme_count]) |th| { if (contrast(th.bg.?, .{ 0, 0, 0 }) > 10) continue; // light paper const soft = std.mem.eql(u8, th.name, "dusk") or std.mem.eql(u8, th.name, "lagoon") or std.mem.eql(u8, th.name, "solarium") or std.mem.eql(u8, th.name, "forge_soft"); if (soft) { try std.testing.expect(contrast(th.fg.?, th.bg.?) >= 4.5); try std.testing.expect(contrast(th.fg.?, th.bg.?) <= 7); } else { for (th.bg.?) |channel| try std.testing.expect(channel <= 0x14); try std.testing.expect(contrast(th.fg.?, th.bg.?) >= 14); } } const forge = curated.forge.theme; try std.testing.expectEqual(forge.bg[0], forge.bg[1]); // Forge chrome is cool-neutral, never the old green-over-blue mint cast. for ([_][3]u8{ forge.tag_bg, forge.tag_active_bg, forge.box, forge.border }) |rgb| try std.testing.expect(rgb[2] >= rgb[1]); try std.testing.expectEqual([3]u8{ 0, 0, 0 }, @as([3]u8, curated.forge_black.theme.bg)); try std.testing.expectEqual([3]u8{ 0, 0, 0 }, @as([3]u8, curated.orchard_black.theme.bg)); } test "line numbers stay quiet without a current-line tag background" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = try p.setTestFile("first\nsecond\n"); pane.body.cur_pinned = true; pane.body.cur_row = 0; var custom = themes[0]; custom.name = try gpa.dupe(u8, "quiet-gutter"); custom.lineno = .{ 70, 70, 70 }; custom.lineno_active = .{ 95, 95, 95 }; p.custom_theme = custom; p.sync(); const x = p.view().rects[0].x + config.GUTTER; const y = p.view().rects[0].y + BOX_H; const surface = try p.render(p.scratch.allocator()); try std.testing.expectEqual(Color{ .rgb = .{ 95, 95, 95 } }, surface.at(x, y).style.fg); try std.testing.expectEqual(Color{ .rgb = .{ 70, 70, 70 } }, surface.at(x, y + 1).style.fg); try std.testing.expectEqual(Color{ .rgb = custom.bg.? }, surface.at(x, y).style.bg); try std.testing.expect(surface.at(x, y).style.bold); try std.testing.expect(!surface.at(x, y + 1).style.bold); // Old ThemeFile palettes need no new field, and do not regain the block. p.custom_theme.?.lineno_active = null; const fallback = try p.render(p.scratch.allocator()); try std.testing.expectEqual(Color{ .rgb = .{ 70, 70, 70 } }, fallback.at(x, y).style.fg); try std.testing.expectEqual(Color{ .rgb = custom.bg.? }, fallback.at(x, y).style.bg); try std.testing.expect(fallback.at(x, y).style.bold); // Moving the caret clears the previous cue; editing the tag parks it. pane.body.cur_row = 1; const moved = try p.render(p.scratch.allocator()); try std.testing.expect(!moved.at(x, y).style.bold); try std.testing.expect(moved.at(x, y + 1).style.bold); tagline.enterTag(p, pane); const tag_edit = try p.render(p.scratch.allocator()); try std.testing.expect(!tag_edit.at(x, y + 1).style.bold); } test "legacy ThemeFile documents inherit Pardes UI roles without new fields" { @setEvalBranchQuota(10000); var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator); defer encoded.deinit(); try std.zon.stringify.serialize(curated.helix.theme, .{ .whitespace = false }, &encoded.writer); // helix without the focused tag's pair it has since gained: a document // written before those fields existed. var legacy: std.ArrayList(u8) = .empty; defer legacy.deinit(std.testing.allocator); var rest: []const u8 = encoded.written(); while (true) { const at = @min(std.mem.indexOf(u8, rest, ".tag_active_bg") orelse rest.len, std.mem.indexOf(u8, rest, ".tag_active_fg") orelse rest.len); try legacy.appendSlice(std.testing.allocator, rest[0..at]); if (at == rest.len) break; rest = rest[at + std.mem.indexOfScalar(u8, rest[at..], '}').? + 1 ..]; rest = std.mem.trimStart(u8, rest, " ,"); } const source = try std.testing.allocator.dupeSentinel(u8, legacy.items, 0); defer std.testing.allocator.free(source); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); var diagnostics: std.zon.parse.Diagnostics = undefined; const parsed = try std.zon.parse.fromSlice(Theme, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics }); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_bg); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_name_fg); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_name_fg); try std.testing.expectEqual(@as(?[3]u8, null), parsed.column_box); try std.testing.expectEqual(@as(?[3]u8, null), parsed.column_box_dim); try std.testing.expectEqual(@as(?[3]u8, null), parsed.search_bg); const chrome = ChromeTheme.fromTheme(&parsed); try std.testing.expectEqual(parsed.tag_bg, chrome.tag_active_bg); // Its names take a tint of its own hues, never the plain ink. try std.testing.expect(!std.meta.eql(parsed.tag_fg, chrome.tag_name_fg)); try std.testing.expect(!std.meta.eql(chrome.tag_active_fg, chrome.tag_active_name_fg)); try std.testing.expectEqual(parsed.num, chrome.column_box); try std.testing.expectEqual(mix(parsed.num, parsed.tag_bg), chrome.column_box_dim); try std.testing.expectEqual(parsed.sel_bg, chrome.search_bg); try std.testing.expectEqual(parsed.fg.?, chrome.diagnostic_error); } test "column grip colors remain distinct from pane grips across native themes" { for (themes[0..native_theme_count]) |th| { try std.testing.expect(th.column_box != null and th.column_box_dim != null); const chrome = ChromeTheme.fromTheme(&th); for ([_][2][3]u8{ .{ chrome.box, chrome.column_box }, .{ chrome.box_dim, chrome.column_box_dim }, }) |pair| { var distance: u32 = 0; for (pair[0], pair[1]) |a, b| { const delta = @as(i32, a) - b; distance += @intCast(delta * delta); } try std.testing.expect(distance >= 30 * 30); } } var custom = themes[0]; custom.column_box = .{ 90, 130, 170 }; custom.column_box_dim = null; var chrome = ChromeTheme.fromTheme(&custom); try std.testing.expectEqual(custom.column_box.?, chrome.column_box); try std.testing.expectEqual(mix(custom.column_box.?, custom.tag_bg), chrome.column_box_dim); custom.column_box_dim = .{ 40, 60, 80 }; chrome = ChromeTheme.fromTheme(&custom); try std.testing.expectEqual(custom.column_box_dim.?, chrome.column_box_dim); } test "custom filename tints preserve optional active fallback precedence" { var theme = themes[0]; theme.tag_name_fg = null; theme.tag_active_name_fg = null; var chrome = ChromeTheme.fromTheme(&theme); // Neither named: each derived, on its own ground. try std.testing.expectEqual(derivedNameTint(&theme, theme.tag_fg, theme.tag_bg).?, chrome.tag_name_fg); try std.testing.expectEqual(derivedNameTint(&theme, theme.tag_active_fg.?, chrome.tag_active_bg).?, chrome.tag_active_name_fg); theme.tag_name_fg = .{ 120, 130, 140 }; chrome = ChromeTheme.fromTheme(&theme); try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_name_fg); try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_active_name_fg); theme.tag_active_name_fg = .{ 150, 160, 170 }; chrome = ChromeTheme.fromTheme(&theme); try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_name_fg); try std.testing.expectEqual(theme.tag_active_name_fg.?, chrome.tag_active_name_fg); theme.tag_name_fg = null; chrome = ChromeTheme.fromTheme(&theme); try std.testing.expectEqual(derivedNameTint(&theme, theme.tag_fg, theme.tag_bg).?, chrome.tag_name_fg); try std.testing.expectEqual(theme.tag_active_name_fg.?, chrome.tag_active_name_fg); } test "every theme tints its names off the tag's ink, and they read on both grounds" { for (&themes) |*th| { const chrome = ChromeTheme.fromTheme(th); const pairs = [2][3][3]u8{ .{ chrome.tag_fg, chrome.tag_name_fg, chrome.tag_bg }, .{ chrome.tag_active_fg, chrome.tag_active_name_fg, chrome.tag_active_bg }, }; for (pairs) |pair| { const ink, const name, const ground = pair; const apart = oklabDistance(toOklab(ink), toOklab(name)); const floor = nameTintFloor(ink, ground); if (apart < name_tint_distance or contrast(name, ground) < floor - 0.01) std.debug.print("{s}: name {x} on {x} is {d:.3} off the ink {x}, {d:.2}:1\n", .{ th.name, name, ground, apart, ink, contrast(name, ground) }); try std.testing.expect(apart >= name_tint_distance); try std.testing.expect(contrast(name, ground) >= floor - 0.01); } } } test "every theme's walk UI roles meet their floors on every ground they are drawn on, dark and light" { // Where a theme's own colours leave no room for a floor, the most it // allows: an ink's on a mid-grey tag (solarized's) is the better of // white and black there; a ground's is where the ink it carries would // drop under its floor. const white: [3]u8 = @splat(255); const black: [3]u8 = @splat(0); const Reach = struct { fn of(grounds: []const [3]u8) f32 { return @max(leastContrast(white, grounds), leastContrast(black, grounds)); } }; const a = std.testing.allocator; const Check = struct { what: []const u8, got: f32, floor: f32 }; var checks: std.ArrayList(Check) = .empty; defer checks.deinit(a); var failed: usize = 0; for (&themes) |*th| { checks.clearRetainingCapacity(); const chrome = ChromeTheme.fromTheme(th); const r = &chrome.roles; const page = th.bg orelse null_page; const body_ink = th.fg orelse th.tag_fg; const tags = [_][3]u8{ r.tag[0].ground, r.tag[1].ground, r.tag[2].ground, r.selected[0].ground, r.selected[1].ground, r.selected[2].ground, r.selected[3].ground }; const messages = [_][3]u8{ r.tag[0].ground, r.tag[1].ground, r.tag[2].ground, page }; for (r.tag ++ r.selected ++ [1]Inks{r.notice}) |inks| { const text = contrast(inks.text, inks.ground); try checks.append(a, .{ .what = "text", .got = text, .floor = @min(Roles.text_floor, Reach.of(&.{inks.ground})) }); try checks.append(a, .{ .what = "dim", .got = contrast(inks.dim, inks.ground), .floor = @min(Roles.dim_floor, text) }); try checks.append(a, .{ .what = "dim under text", .got = text - contrast(inks.dim, inks.ground), .floor = 0 }); } try checks.append(a, .{ .what = "key", .got = leastContrast(r.key, &tags), .floor = @min(Roles.ink_floor, Reach.of(&tags)) }); try checks.append(a, .{ .what = "match", .got = leastContrast(r.match, &tags), .floor = @min(Roles.ink_floor, Reach.of(&tags)) }); for (r.tag) |inks| { try checks.append(a, .{ .what = "rule", .got = contrast(inks.rule, inks.ground), .floor = Roles.rule_floor }); try checks.append(a, .{ .what = "rule ceiling", .got = Roles.rule_ceiling - contrast(inks.rule, inks.ground), .floor = 0 }); } for ([_][3]u8{ r.err, r.warn, r.question, r.hint }) |ink| try checks.append(a, .{ .what = "message", .got = leastContrast(ink, &messages), .floor = @min(Roles.ink_floor, Reach.of(&messages)) }); // A selection off its tag by 1.4:1 (1.25 light) with the text at // 4.5:1 on it, where the text has that much over the tag. for (r.tag, r.selected) |inks, selected| { const floor = Roles.selectionFloor(inks.ground); const room = contrast(inks.text, inks.ground) >= floor * Roles.text_floor * 1.03; try checks.append(a, .{ .what = "selection", .got = contrast(selected.ground, inks.ground), .floor = if (room) floor else 0 }); } try checks.append(a, .{ .what = "reading", .got = oklabDistance(toOklab(chrome.tag_reading_bg), toOklab(th.tag_bg)), .floor = Roles.reading_distance }); for ([_][3]u8{ th.tag_fg, th.tag_active_fg orelse th.tag_fg }) |ink| try checks.append(a, .{ .what = "text on reading", .got = contrast(ink, chrome.tag_reading_bg), .floor = @min(7, contrast(ink, th.tag_bg)) - 0.02 }); const ink_floor = @min(Roles.ink_floor, contrast(body_ink, page)); // A preview's landing line 1.5:1 off the page, its matched span (the // current hit) a step stronger, 1.9:1 (UX E7 7b: 1.29 read as faint). for ([_][3]u8{ r.hit, r.hit_current }, [_]f32{ 1.5, 1.9 }) |ground, floor| { const on = contrast(body_ink, ground); try checks.append(a, .{ .what = "hit", .got = contrast(ground, page), .floor = if (on < ink_floor + 0.3) 0 else floor }); try checks.append(a, .{ .what = "ink on hit", .got = on, .floor = ink_floor - 0.01 }); } try checks.append(a, .{ .what = "current over hit", .got = contrast(r.hit_current, page) - contrast(r.hit, page), .floor = 0 }); for (checks.items) |c| if (c.got < c.floor - 0.005) { failed += 1; std.debug.print("{s}: {s} {d:.2} under {d:.2}\n", .{ th.name, c.what, c.got, c.floor }); }; } try std.testing.expectEqual(0, failed); } test "neonotte84's and acme's roles are the ones UX derived (DESIGN.md D4, tools/roles.py)" { const Want = struct { name: []const u8, text: ?[3]u8, dim: [3]u8, rule: [3]u8, key: [3]u8, match: [3]u8, reading: [3]u8, hit: [3]u8, hit_current: [3]u8 }; // The hit grounds past UX's 18 % / 32 % mix, to 1.5:1 and 1.9:1 off the // page (UX E7 7b). const wants = [_]Want{ .{ .name = "neonotte84", .text = .{ 0xb5, 0xbf, 0xe3 }, .dim = .{ 0x70, 0x76, 0x8f }, .rule = .{ 0x4c, 0x50, 0x63 }, .key = .{ 0xf8, 0xde, 0xd9 }, .match = .{ 0xf1, 0xa2, 0x71 }, .reading = .{ 0x29, 0x27, 0x1e }, .hit = .{ 0x47, 0x32, 0x2e }, .hit_current = .{ 0x5f, 0x3f, 0x33 } }, // acme's key and match a little darker than UX's #5c5c8d and // #974d00 (which hold on its tag and its #9eeeee): a reading pane's // band's selection is pushed off the reading ground (#9eeeee is // 1.12:1 off #f3f0cc), and they read on that one too. .{ .name = "acme", .text = null, .dim = .{ 0x7a, 0x86, 0x86 }, .rule = .{ 0xa8, 0xb7, 0xb7 }, .key = .{ 0x55, 0x55, 0x83 }, .match = .{ 0x8f, 0x48, 0x00 }, .reading = .{ 0xf3, 0xf0, 0xcc }, .hit = .{ 0xe6, 0xcd, 0xae }, .hit_current = .{ 0xd9, 0xb4, 0x90 } }, }; for (wants) |want| { const chrome = ChromeTheme.fromTheme(&themes[themeIndex(want.name).?]); const plain = chrome.roles.on(.plain); const got = [_][3]u8{ plain.text, plain.dim, plain.rule, chrome.roles.key, chrome.roles.match, chrome.tag_reading_bg, chrome.roles.hit, chrome.roles.hit_current }; const expected = [_][3]u8{ want.text orelse plain.text, want.dim, want.rule, want.key, want.match, want.reading, want.hit, want.hit_current }; for (got, expected, 0..) |g, e, i| for (g, e) |x, y| if (@abs(@as(i16, x) - y) > 2) { std.debug.print("{s} role {d}: {x} for {x}\n", .{ want.name, i, g, e }); return error.TestUnexpectedResult; }; } } test "the err role falls back from diagnostic.error's ink to error's, then to the theme's red (UX E3): neonotte84's (its diagnostic.error an underline only) is its red, acme's its palette's" { const neonotte = &themes[themeIndex("neonotte84").?]; // neonotte.toml: "error" = { fg = "red" }, its palette's red #ff7ea2. try std.testing.expectEqual([3]u8{ 0xff, 0x7e, 0xa2 }, neonotte.diagnostic_error.?); for ([_][]const u8{ "neonotte84", "acme" }) |name| { const chrome = ChromeTheme.fromTheme(&themes[themeIndex(name).?]); const err = chrome.roles.err; // Red: its red channel well over the others, on the page and the tags. try std.testing.expect(err[0] > err[1] + 40 and err[0] > err[2] + 40); } try std.testing.expectEqual([3]u8{ 0xaa, 0x22, 0x22 }, ChromeTheme.fromTheme(&themes[themeIndex("acme").?]).diagnostic_error); }