Skip to content

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

Blackout theme

oxydizer16d85542768b
diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.md
index b300131..b3fa779 100644
--- a/docs/agent-notes/rendering.md
+++ b/docs/agent-notes/rendering.md
@@ -51,8 +51,10 @@ chrome, capture, or retained panel painting. General rules remain in
no ring or shadow.
Optional `window_corner_*` accents are four small immutable rasters owned by
the frame tree (`toplevel/corner_accents.zig`), following that same shape just
- inside its ring. They decline input, inherit opacity, and memoize geometry,
- shape, scale and theme; maximized/fullscreen/undecorated windows hide them.
+ inside its ring. They decline input, inherit opacity, and memoize scale and
+ theme; maximized/fullscreen/undecorated windows hide them. Each corner is
+ keyed by the part of the outline it shows (`window_shape.localKey`), so a
+ resize or a size animation moves the four nodes and paints none of them.
`window_corner_resize_extra` adds length during a live resize grab. The normal
chrome frame tick eases that extension in/out, including split resizes; it
stops scheduling when settled. Begin/end wake the tick even without a client
@@ -67,9 +69,20 @@ chrome, capture, or retained panel painting. General rules remain in
Plate inset, bevel, height-relative slant, control gap and text padding are
theme tokens too; narrow frames clamp opposing cuts to prevent crossed edges.
With a polygon outline (`ChromeState.outline`) the plate is also cut by the
- outline moved in by the inset (`chrome_plate.distance`, keyed in the memo),
- so chamfers keep an even margin; a step meant to hug the plate's slant has
- to be placed in px in `window_shape` to match the plate's width and slant.
+ outline moved in by the inset (`chrome_plate.distance`), so chamfers keep an
+ even margin; a step meant to hug the plate's slant has to be placed in px in
+ `window_shape` to match the plate's width and slant. The memo keys only the
+ outline's edges near the plate, and not the frame's height: a window resized
+ in height alone keeps its titlebar raster.
+ Rasters that follow a distance field (the plate, the accents) ask for a
+ distance only where an edge can be: a distance changes by at most one per
+ pixel, so `window_shape.saturatedRun` pixels after one are as covered as it
+ is. A per-pixel polygon distance over a whole box costs milliseconds.
+ The plate's coverage is the same for every titlebar of one theme, scale and
+ outline, so `chrome_plate.mask` keeps the last one: a resize or a title
+ change reads it and works out no distance.
+ `Toplevel.shapePolygon` keeps the parsed outline and the last frame's
+ polygon: every client commit asks for it several times.
`chrome_control_right_pad` and `chrome_control_offset_y` move the shared
control rectangles, including painting and input. `controlInsets` measures
the polygon at the shifted control rows while leaving the icon centred.
diff --git a/docs/plans/keys-certificates.md b/docs/plans/keys-certificates.md
new file mode 100644
index 0000000..0a590b8
--- /dev/null
+++ b/docs/plans/keys-certificates.md
@@ -0,0 +1,262 @@
+# Keys & Certificates plan
+
+Status: draft, 2026-11-10. Nothing built. Decisions D1–D8 are open; each has a
+recommendation. Start with Phase 0.
+
+Add a **Keys & Certificates** page to Settings: one place that shows every SSH
+key, certificate and private key the user owns, wherever it lies, says what
+each one *is* and whether it is healthy, and offers the handful of actions
+people otherwise look up every time (copy the public key, add a passphrase,
+load into the agent, convert a `.pfx`, find out what that `.pem` in Downloads
+is).
+
+## What a survey of one real home directory showed
+
+Taken 2026-11-10 on the development machine (names only, no contents read):
+
+* `~/.ssh` holds four private keys. One has no `.pub` and no extension, so
+ **extensions cannot be the classifier**; content is.
+* 26 more candidates (`.pem`, `.crt`, `.key`, `.pfx`, `.pub`) lie outside it.
+ Most belong to tools (a container dev proxy's TLS pairs, the .NET dev-cert
+ store, application state). A few are true strays in Downloads, Documents and
+ project folders. **A manager that offers to tidy tool-owned files breaks
+ those tools**, so ownership is part of the model.
+* The session exports no `SSH_AUTH_SOCK`. `gpg-agent-ssh.socket` listens but
+ nothing points at it, so no agent is in use.
+* The system trust store has 168 anchors, one of them added locally. A local
+ anchor can sign for any site; it deserves to be visible.
+* `~/.pki/nssdb` exists (the store Chromium-family browsers read).
+* Present: `ssh-keygen`, `ssh-add`, `openssl`, `certutil`, `trust` (p11-kit),
+ `update-ca-trust`. Nothing in the tree links a crypto library today.
+
+Spike results (throwaway key in a scratch directory, OpenSSH 10.6, OpenSSL 3.6):
+
+* `ssh-keygen` generates and re-encrypts with passphrases read through
+ `SSH_ASKPASS` + `SSH_ASKPASS_REQUIRE=force`, no tty, no `-N`/`-P`. The
+ prompts are distinguishable ("Enter old passphrase", "Enter new passphrase",
+ "Enter same passphrase again").
+* An encrypted OpenSSH private key carries its public key in clear: type,
+ fingerprint, cipher and KDF are readable **without the passphrase**.
+* `openssl pkcs12` takes passwords with `-passin fd:N` / `-passout fd:N`.
+
+So no secret ever needs to be in an argv or the environment.
+
+## Placement (D1)
+
+Recommended: its own page, not a part of Users. Users administers *system
+accounts* through the root helper and polkit; these are the *current user's*
+files and need no privilege. `users.zig` is also 732 lines, close to the split
+threshold. Users gets one row linking to the page.
+
+The page has four views behind a segmented control:
+
+```
+ Keys & Certificates [ Scan this computer ]
+ ( SSH keys ) ( Certificates ) ( Found files ) ( Trust )
+
+ SSH keys Agent: running · 1 loaded
+ ┌───────────────────────────────────────────────────────────────┐
+ │ ● work laptop ED25519 SHA256:Unenw… 🔒 [Copy public] │
+ │ ~/.ssh/id_ed25519 · used for github.com, 2 more ◉ loaded │
+ │ ● staging RSA 2048 SHA256:9fQk… ⚠ no passphrase │
+ │ ~/.ssh/staging · no .pub file ○ load │
+ └───────────────────────────────────────────────────────────────┘
+ [ New key… ] [ Import… ] Known hosts (41) › Authorized (2) ›
+```
+
+Selecting a row opens details in the same column (as Users and Network do):
+every location of that key, fingerprints, comment, label and notes, where it
+is referenced, and its actions.
+
+## Model
+
+Items are identified by **public-key fingerprint**, not by path:
+
+* The same key copied to three places is one item with three locations.
+* A certificate and a private key pair up when their public keys match; an SSH
+ private key pairs with its `.pub`, with `authorized_keys` lines, with
+ `IdentityFile` entries in `~/.ssh/config`, and with agent identities.
+* Labels, notes and tags are stored against the fingerprint
+ (`$XDG_DATA_HOME/rediwm/keys/index.json`), so they survive moves and apply
+ to files RediWM does not own.
+
+Kinds, decided from content (PEM armor label, then structure; DER by ASN.1
+shape): OpenSSH private/public key, PuTTY key, PKCS#1 / SEC1 / PKCS#8 private
+key (plain or encrypted), X.509 certificate (leaf, CA, self-signed), chain or
+bundle, CSR, CRL, PKCS#12, and "unrecognised". The common "cloud `.pem`" is
+shown as what it is: an RSA private key usable for SSH.
+
+Ownership of a location:
+
+| Class | Example | Offered |
+| --- | --- | --- |
+| Standard | `~/.ssh`, the vault | Everything |
+| Stray | Downloads, Documents, Desktop, home root | Everything, plus *Move to vault* |
+| Project | inside a git work tree | View, copy, health; move only on request. Shows whether git tracks or ignores it |
+| Tool-managed | a reviewed catalog: dev proxies, mkcert, .NET, kube, cloud CLIs, VM tools | Read-only, grouped "Managed by …" |
+| System | trust store, `/etc/ssl` | Read-only (D5) |
+
+Health badges, each with a one-line explanation and, where safe, a fix:
+private key without passphrase; permissions `ssh` will refuse; weak or retired
+algorithm (DSA, RSA under 2048, SHA-1 signatures); certificate expired or
+expiring within 30 days; `.pub` missing or not matching; private key tracked
+by git; private key in a stray location; certificate whose key is nowhere to
+be found; locally added trust anchor.
+
+## Actions
+
+SSH: generate (Ed25519 by default, comment, optional passphrase); copy public
+key; add, change or remove passphrase; edit comment and label; recreate a
+missing `.pub`; fix permissions; load into or remove from the agent, with a
+lifetime; "use for host…" (adds a `Host` block with `IdentityFile` and
+`IdentitiesOnly`); delete. `authorized_keys` and `known_hosts` get list views
+with remove. "Add to GitHub/GitLab" copies the public key and opens the
+provider's page.
+
+Certificates: details (subject, issuer, names, validity, usage, fingerprints,
+chain); verify against system trust; check that a key matches; copy PEM or
+fingerprint; convert PEM ↔ DER; split a PKCS#12 into certificate and key, or
+build one; export the public certificate; delete.
+
+Found files: label, reveal in Files, move to vault, ignore this file or folder.
+
+Never offered: showing or copying private key material.
+
+## Architecture
+
+The page is drawn by the compositor, so the rules are strict:
+
+* **The compositor never reads key files.** A new unprivileged
+ `rediwm-keys` helper scans, parses and runs operations; the page receives
+ metadata only (kind, algorithm, fingerprint, flags, paths). Parsing a file
+ from Downloads is parsing hostile input, and it must not happen in the
+ process that owns the session.
+* **Read side:** `rediwm-keys scan` runs under a `platform/seccomp.zig`
+ policy (read-only filesystem calls, no network, no exec), like the PDF and
+ theme helpers. Metadata parsing is native Zig: PEM armor, a tolerant DER
+ walker, the OpenSSH wire format, SHA-256. No library dependency, small
+ enough to fuzz.
+* **Write side:** each operation is a separate `rediwm-keys` invocation that
+ validates its target again and runs the reference tool with a fixed argv:
+ `ssh-keygen`, `ssh-add`, `openssl`, `certutil`. We do not write private-key
+ cryptography ourselves. A missing tool disables its actions with a reason.
+* **Secrets** are typed into `secret_input.Input` over mlocked storage and
+ travel over a pipe to the helper, which answers the tool's askpass prompts
+ (or passes an fd to `openssl`). Wiped on submit, cancel, hide and page
+ change, as Printers does. Never in argv, environment, logs or the arena.
+* **Lifetime follows Printers:** the client exists only while the page is
+ selected; bounded pipe reads, absolute deadlines, snapshots copied into the
+ section arena, action generations so an old refresh cannot clear a newer
+ action's busy state. Opening Settings elsewhere starts nothing.
+* **No idle work.** Opening the page reads the standard locations and the
+ cached result of the last scan. The whole-home scan is explicit and
+ cancellable, with incremental results. No inotify watches.
+* The greeter gets none of this. No new IPC request returns key material.
+
+Proposed files:
+
+| File | Responsibility |
+| --- | --- |
+| `src/keys/` (named module, no compositor imports) | `model`, `pem`, `der`, `x509`, `openssh`, `classify`, `scan`, `catalog` (tool-managed locations), `health`, `index` (labels), `agent` (agent protocol: list, remove), `ops` (operation plans and fixed argv), `protocol` |
+| `src/keys/helper_main.zig` | `rediwm-keys` entry: `scan`, `op`, `askpass` modes |
+| `src/keys/client.zig` | Page-side child process, snapshots, generations |
+| `src/control_center/sections/keys.zig` | Section state, view switch, build |
+| `sections/keys_ssh.zig`, `keys_certs.zig`, `keys_files.zig`, `keys_trust.zig`, `keys_details.zig`, `keys_forms.zig` | One file per view, split from the start |
+| `panel.zig`, `tree.zig`, `keys.zig`, `search_index.zig` | Page enum, navigation, Escape handling, search entries |
+| `build/` | Helper artifact, `test-keys` step |
+
+OS differences (trust store layout, `certctl` on FreeBSD) sit behind one
+adapter in `src/keys/`; process and file primitives come from `src/platform/`.
+
+## Agent (D2)
+
+Recommended: when the session starts with no `SSH_AUTH_SOCK`, `rediwm-session`
+starts OpenSSH `ssh-agent` on a socket under `$XDG_RUNTIME_DIR` and exports it
+through `child_env` and the activation environment. An agent that already
+exists (set by the user, gpg-agent with SSH support, a keyring daemon) is
+respected and shown by name; the agent protocol is the same, so list, load and
+unload work with any of them. We do not write our own agent: that would put
+decrypted keys in our process.
+
+With an agent in place:
+
+* Loaded state per key, load with a lifetime (until logout, 1 h, 8 h).
+* Optional "forget keys when the screen locks" and "on suspend", fired after
+ `Lock.announce`, never delaying the lock.
+* A native passphrase prompt: `SSH_ASKPASS` points at `rediwm-keys askpass`,
+ which asks the compositor to show a secret dialog. This is a dialog any
+ local program can raise, so it shows the requesting program, the tool's
+ prompt verbatim, and is refused for sandboxed callers without a
+ `[[sandbox_allow]]` grant. It needs its own review before it ships.
+
+## Vault (D3, D4)
+
+Files stay ordinary files that every other tool can read; there is no
+container format. SSH keys belong in `~/.ssh`. Everything else moves to
+`$XDG_DATA_HOME/rediwm/keys/` (directory 0700, files 0600), named from the
+label. A move is copy, verify by fingerprint, then remove the original, and
+records where the file came from. No symlink is left behind by default: a
+link to a private key in Downloads defeats the purpose. Project files can opt
+in to a symlink.
+
+Delete moves to the home Trash with a confirmation that names the fingerprint
+and every place the key is referenced. Losing the only copy of an SSH key
+locks people out of servers; a recoverable delete is the kinder default.
+
+## Phases
+
+0. **Facts and corpus.** No UI. Measure a whole-home scan (time, candidates,
+ false positives in vendored trees). Decide the candidate rule: extension
+ list, `~/.ssh`, and an optional content sniff of small files. Check
+ `std.crypto.Certificate` against the system bundle and odd certificates;
+ write the tolerant walker if it rejects what users have. Confirm the
+ askpass behaviour on the oldest OpenSSH we support and for `ssh-add`.
+ Survey trust-store tooling per distribution and FreeBSD. Draft the seccomp
+ policy. Build a generated fixture corpus (never real keys) and a fuzz
+ target for the parsers.
+1. **SSH keys.** Page, helper, `~/.ssh` inventory with badges, details, copy
+ public key, generate, passphrase, comment and label, recreate `.pub`, fix
+ permissions, delete. Search entries, translations.
+2. **Agent and hosts.** Session agent, loaded state and lifetimes, forget on
+ lock, askpass dialog, "used for" from `~/.ssh/config`, `authorized_keys`,
+ `known_hosts`.
+3. **Certificates and found files.** Explicit scan, classification, pairing
+ and de-duplication, ownership classes, health, certificate details and
+ chain, labels and notes, reveal in Files, ignore list.
+4. **Vault and conversion.** Move to vault, import, PEM/DER/PKCS#12
+ conversion, export.
+5. **Trust and reach.** System anchors read-only with local ones called out,
+ the user NSS store (list, add, remove), expiry notifications on a
+ deadline-only timer, opening a key or certificate from Files in this page.
+
+Later, each its own plan: GPG keys (D7), FIDO2 and resident keys, PKCS#11 and
+smart cards, an encrypted backup of the vault, CSR and self-signed generation,
+installing a key on a server, ACME renewal, Java keystores, WireGuard keys.
+
+## Tests
+
+Nothing may touch the host's `~/.ssh`, agent, NSS store or trust store. Every
+test runs with a scratch `HOME` and `XDG_*`, its own agent on a short socket
+path, and keys generated in the test.
+
+* `zig build test-keys`: parsers against the corpus, classification, pairing,
+ health rules, ownership catalog, operation plans (argv is asserted, never
+ containing a secret), index round trip, fuzz smoke.
+* `tests/keys_settings.py`: inventory, badges, generate, passphrase change
+ (verified with `ssh-keygen -y`), copy public key, delete to Trash, agent
+ load and unload, scan with tool-managed and project fixtures, move to vault.
+* `strings` on a ReleaseSafe `rediwm`: no test hooks, no new environment
+ reads beyond `SSH_AUTH_SOCK`.
+
+## Decisions
+
+| | Question | Recommendation |
+| --- | --- | --- |
+| D1 | Own page or part of Users? | Own page "Keys & Certificates"; a link row in Users |
+| D2 | Agent | Start OpenSSH `ssh-agent` when the session has none; respect an existing one |
+| D3 | Vault location; symlinks on move | `$XDG_DATA_HOME/rediwm/keys`, SSH keys in `~/.ssh`; no symlink by default |
+| D4 | Delete | Home Trash, with a confirmation naming fingerprint and references |
+| D5 | Adding or removing *system* trust anchors (needs root) | Read-only in this plan. A root path means widening the accounts helper or a fixed-argv polkit action; decide separately |
+| D6 | Scan scope | Home only, explicit, cached; extra folders added by the user; content sniff as an opt-in "deep scan" |
+| D7 | GPG keys | Out of this plan |
+| D8 | Parsing | Native metadata parsing plus reference CLI tools for operations; do not link OpenSSL |
diff --git a/src/chrome.zig b/src/chrome.zig
index 3149cdb..61f3c72 100644
--- a/src/chrome.zig
+++ b/src/chrome.zig
@@ -111,8 +111,9 @@ pub const ChromeState = struct {
pub const TitlebarMemo = struct {
font_generation: u32 = 0,
tabs_hash: u64 = 0,
+ // The band's width. The frame's height is not an input: a window resized
+ // only in height keeps its titlebar.
width: i32,
- height: i32,
density: f32 = 1,
active: bool = false,
workspace_focus: bool = false,
@@ -152,12 +153,11 @@ pub const TitlebarMemo = struct {
inset_left: i32 = 0,
inset_right: i32 = 0,
- pub fn capture(width: i32, height: i32, title_ptr: ?[*:0]const u8, state: ChromeState) TitlebarMemo {
+ pub fn capture(width: i32, title_ptr: ?[*:0]const u8, state: ChromeState) TitlebarMemo {
const t = theme.global;
return .{
.font_generation = text.font_generation,
.width = width,
- .height = height,
.density = state.density,
.active = state.active,
.workspace_focus = state.workspace_focus,
@@ -192,7 +192,7 @@ pub const TitlebarMemo = struct {
.title_plate_width = t.window_title_plate_width,
.title_plate_fg = t.window_title_plate_fg,
.title_plate_geometry = plate.geometry(t),
- .title_plate_outline = plate.outlineKey(state),
+ .title_plate_outline = plate.outlineKey(width, state),
.inset_left = state.inset_left,
.inset_right = state.inset_right,
};
@@ -220,7 +220,6 @@ pub const TitlebarMemo = struct {
pub fn eql(a: TitlebarMemo, b: TitlebarMemo) bool {
if (a.font_generation != b.font_generation) return false;
if (a.width != b.width) return false;
- if (a.height != b.height) return false;
if (a.density != b.density) return false;
if (a.active != b.active) return false;
if (a.workspace_focus != b.workspace_focus) return false;
@@ -462,6 +461,7 @@ pub const ChromeBuffer = struct {
const icon_top: f32 = @floatFromInt(@divTrunc(m.titlebarHeight() - m.iconSize(), 2));
const base = Color.chrome();
const title_plate = plate.polygon(frame.logical_width, frame.state);
+ const plate_mask = if (title_plate) |polygon| try plate.mask(polygon, frame.logical_width, frame.state, @intCast(frame.height)) else null;
// Away from the controls and the icon every pixel in a row has the same
// fill. Pack that colour once instead of repeating four rounded float
// conversions across the bar.
@@ -513,6 +513,10 @@ pub const ChromeBuffer = struct {
count += 1;
}
}
+ // The plate is one colour inside and absent outside: but for the
+ // pixels on its edge, a row of it is two packed colours.
+ const plate_color = Color.fromRgba(theme.global.window_title_plate);
+ const plate_flat: [2]u32 = if (title_plate != null) .{ plate_color.scaled(0).over(row_color).argb(), plate_color.scaled(1).over(row_color).argb() } else @splat(flat_color);
var x = x0;
for (runs[0..count]) |run| {
@memset(row[x..run.start], flat_color);
@@ -520,16 +524,20 @@ pub const ChromeBuffer = struct {
const px = (@as(f32, @floatFromInt(shaded)) + 0.5) / scale;
const in_controls = control_row and px >= control_left and px <= control_right;
const in_icon = icon_row and px >= icon_left and px < icon_right;
- if (!in_controls and !in_icon and title_plate == null) {
- row[shaded] = flat_color;
- continue;
+ const plate_cover = if (plate_mask) |mask| mask.at(shaded, device_y) else 0;
+ if (!in_controls and !in_icon) {
+ if (title_plate == null) {
+ row[shaded] = flat_color;
+ continue;
+ }
+ if (plate_cover == 0 or plate_cover == 1) {
+ row[shaded] = plate_flat[@intFromFloat(plate_cover)];
+ continue;
+ }
}
var color = row_color;
- if (title_plate) |polygon| {
- const distance: f32 = @floatCast(plate.distance(polygon, frame.state, px, py));
- color = Color.fromRgba(theme.global.window_title_plate).scaled(sdf.coverage(distance * scale)).over(color);
- }
+ if (title_plate != null) color = plate_color.scaled(plate_cover).over(color);
if (in_controls) color = controls.paint(color, px, py);
if (if (frame.state.tabs.tabs.len == 0) frame.state.icon else null) |icon| {
diff --git a/src/chrome_plate.zig b/src/chrome_plate.zig
index af6ebcc..63931db 100644
--- a/src/chrome_plate.zig
+++ b/src/chrome_plate.zig
@@ -1,6 +1,7 @@
//! Optional angled label behind a single window title. Tabs keep their own look.
const std = @import("std");
const chrome = @import("chrome.zig");
+const gpa = @import("main.zig").gpa;
const theme = @import("ui").theme;
const shape = @import("ui").window_shape;
@@ -53,16 +54,78 @@ pub fn right(p: shape.Resolved) f32 {
/// window outline moved in by the inset, so a chamfer or step in the outline is
/// followed at the same even margin as the plate's straight edges.
pub fn distance(p: shape.Resolved, state: chrome.ChromeState, px: f32, py: f32) f64 {
- const own = shape.sdPolygon(p, px, py);
+ return cut(shape.sdPolygon(p, px, py), state, px, py);
+}
+
+fn cut(own: f64, state: chrome.ChromeState, px: f32, py: f32) f64 {
const outline = state.outline orelse return own;
return @max(own, shape.sdPolygon(outline, px, py) + theme.global.window_title_plate_inset * state.density);
}
+/// The plate's coverage of each device pixel at the titlebar's left end. Every
+/// titlebar with this plate, scale and outline shows the same one whatever its
+/// width or title, and working it out was most of a raster: the last one is
+/// kept, so a resize or a title change reads it instead.
+pub const Mask = struct {
+ key: u64 = 0,
+ width: usize = 0,
+ height: usize = 0,
+ coverage: []f32 = &.{},
+
+ pub fn at(m: *const Mask, x: usize, y: usize) f32 {
+ return if (x < m.width and y < m.height) m.coverage[y * m.width + x] else 0;
+ }
+};
+
+var kept: Mask = .{};
+
+pub fn mask(p: shape.Resolved, frame_width: i32, state: chrome.ChromeState, height: usize) !*const Mask {
+ const scale = state.scale;
+ const columns: usize = @intFromFloat(@ceil(right(p) * scale));
+ var hasher = std.hash.Wyhash.init(outlineKey(frame_width, state));
+ hasher.update(std.mem.sliceAsBytes(p.points[0..p.count]));
+ hasher.update(std.mem.asBytes(&[2]f32{ scale, theme.global.window_title_plate_inset * state.density }));
+ hasher.update(std.mem.asBytes(&[2]usize{ columns, height }));
+ const key = hasher.final() | 1;
+ if (kept.key == key) return &kept;
+ kept.key = 0;
+ kept.coverage = try gpa.realloc(kept.coverage, columns * height);
+ kept.width = columns;
+ kept.height = height;
+ for (0..height) |y| {
+ const py = (@as(f32, @floatFromInt(y)) + 0.5) / scale;
+ const row = kept.coverage[y * columns ..][0..columns];
+ var x: usize = 0;
+ while (x < columns) {
+ const px = (@as(f32, @floatFromInt(x)) + 0.5) / scale;
+ // Outside the plate's own outline the window's cannot matter. A
+ // distance changes by at most one per pixel, so the pixels after
+ // this one are as covered as it is for as far as an edge is away.
+ const own = shape.sdPolygon(p, px, py);
+ const d = @as(f32, @floatCast(if (own * scale >= 0.5 + 1e-3) own else cut(own, state, px, py))) * scale;
+ const run = @min(columns - x, 1 + shape.saturatedRun(d));
+ @memset(row[x..][0..run], @import("ui").sdf.coverage(d));
+ x += run;
+ }
+ }
+ kept.key = key;
+ return &kept;
+}
+
+/// Frees the kept mask at shutdown.
+pub fn deinit() void {
+ gpa.free(kept.coverage);
+ kept = .{};
+}
+
/// What the plate takes from the outline, for the titlebar memo: 0 without one.
-pub fn outlineKey(state: chrome.ChromeState) u64 {
+/// Only the edges that pass within the inset of the plate cut it, so a frame
+/// resized away from the plate keeps its key (and its titlebar raster).
+pub fn outlineKey(frame_width: i32, state: chrome.ChromeState) u64 {
const outline = state.outline orelse return 0;
- if (state.tabs.tabs.len > 0 or theme.global.window_title_plate[3] <= 0) return 0;
- return std.hash.Wyhash.hash(outline.count, std.mem.sliceAsBytes(outline.points[0..outline.count])) | 1;
+ const p = polygon(frame_width, state) orelse return 0;
+ const reach = theme.global.window_title_plate_inset * state.density + 1;
+ return shape.localKey(outline, 0, 0, right(p), theme.global.chrome_height * state.density, reach) | 1;
}
pub fn color() @import("chrome_paint.zig").Color {
diff --git a/src/chrome_tests.zig b/src/chrome_tests.zig
index 2823fbd..cbd0a0c 100644
--- a/src/chrome_tests.zig
+++ b/src/chrome_tests.zig
@@ -29,7 +29,6 @@ test "titlebar glass holds only while the titlebar is at least 98% opaque" {
pub fn sampleTitlebarMemo() TitlebarMemo {
return .{
.width = 200,
- .height = 100,
.title_ptr = null,
.scale = 1,
.hover = 0,
@@ -109,37 +108,37 @@ test "TitlebarMemo.capture reads title_size from theme.global" {
const saved = theme.global;
defer theme.global = saved;
theme.global.title_size = 19.25;
- const memo = TitlebarMemo.capture(10, 10, null, .{ .scale = 1 });
+ const memo = TitlebarMemo.capture(10, null, .{ .scale = 1 });
try std.testing.expectEqual(@as(f32, 19.25), memo.title_size);
}
test "chrome geometry changes invalidate retained titlebar pixels" {
const saved = theme.global;
defer theme.global = saved;
- const before = TitlebarMemo.capture(400, 320, null, .{});
+ const before = TitlebarMemo.capture(400, null, .{});
theme.global.chrome_control_gap += 1;
- const spaced = TitlebarMemo.capture(400, 320, null, .{});
+ const spaced = TitlebarMemo.capture(400, null, .{});
try std.testing.expect(!before.eql(spaced));
try std.testing.expect(!before.reusableFor(spaced));
theme.global.chrome_control_gap = saved.chrome_control_gap;
theme.global.chrome_height += 1;
- const taller = TitlebarMemo.capture(400, 320, null, .{});
+ const taller = TitlebarMemo.capture(400, null, .{});
try std.testing.expect(!before.reusableFor(taller));
theme.global.chrome_height = saved.chrome_height;
theme.global.chrome_round_buttons = !saved.chrome_round_buttons;
- const round = TitlebarMemo.capture(400, 320, null, .{});
+ const round = TitlebarMemo.capture(400, null, .{});
try std.testing.expect(!before.eql(round));
try std.testing.expect(!before.reusableFor(round));
theme.global = saved;
theme.global.chrome_control_right_pad = 2;
- try std.testing.expect(!before.reusableFor(TitlebarMemo.capture(400, 320, null, .{})));
+ try std.testing.expect(!before.reusableFor(TitlebarMemo.capture(400, null, .{})));
theme.global = saved;
theme.global.chrome_control_offset_y = 5;
- try std.testing.expect(!before.reusableFor(TitlebarMemo.capture(400, 320, null, .{})));
+ try std.testing.expect(!before.reusableFor(TitlebarMemo.capture(400, null, .{})));
inline for (.{ "window_title_plate_inset", "window_title_plate_bevel", "window_title_plate_slant", "window_title_plate_control_gap", "window_title_plate_text_padding" }) |field| {
theme.global = saved;
@field(theme.global, field) += 0.1;
- try std.testing.expect(!before.reusableFor(TitlebarMemo.capture(400, 320, null, .{})));
+ try std.testing.expect(!before.reusableFor(TitlebarMemo.capture(400, null, .{})));
}
}
diff --git a/src/main.zig b/src/main.zig
index 9f49df1..8c13b15 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -112,6 +112,7 @@ fn start(init: std.process.Init) !bool {
defer @import("ui").shell_icons.deinitPack();
defer @import("desktop/watcher.zig").deinitIcons();
defer @import("icon_cache.zig").deinit();
+ defer @import("chrome_plate.zig").deinit();
defer server.deinit();
var buf: [11]u8 = undefined;
diff --git a/src/toplevel/chrome_sync.zig b/src/toplevel/chrome_sync.zig
index 96d3c75..74c1fc5 100644
--- a/src/toplevel/chrome_sync.zig
+++ b/src/toplevel/chrome_sync.zig
@@ -175,7 +175,7 @@ pub fn syncChrome(toplevel: *Toplevel, rebuild_shadow: bool, now_ms: i64) !void
state.inset_right = insets.right;
state.outline = toplevel.shapePolygon(width, height);
- const title_memo = chrome.TitlebarMemo.capture(width, height, toplevel.titlePtr(), state);
+ const title_memo = chrome.TitlebarMemo.capture(width, toplevel.titlePtr(), state);
const skip_titlebar = if (toplevel.last_titlebar) |prev| prev.eql(title_memo) or toplevel.stretchesTitlebar(prev, title_memo, now_ms) else false;
if (!skip_titlebar) {
const titlebar = if (toplevel.cached_titlebar != null and toplevel.last_titlebar != null and toplevel.last_titlebar.?.reusableFor(title_memo))
@@ -250,7 +250,6 @@ pub fn stretchesTitlebar(toplevel: *const Toplevel, raster: chrome.TitlebarMemo,
if (toplevel.size_w.settled(now_ms) and toplevel.size_h.settled(now_ms)) return false;
var resized = raster;
resized.width = next.width;
- resized.height = next.height;
if (!resized.eql(next)) return false;
const ratio = @as(f32, @floatFromInt(next.width)) / @as(f32, @floatFromInt(@max(raster.width, 1)));
return @abs(ratio - 1) <= titlebar_stretch;
diff --git a/src/toplevel/configure.zig b/src/toplevel/configure.zig
index 1184d54..bb6f5c4 100644
--- a/src/toplevel/configure.zig
+++ b/src/toplevel/configure.zig
@@ -116,11 +116,48 @@ pub fn cornerRadius(toplevel: *const Toplevel) f32 {
/// ignored (the theme loader refuses one that does not parse).
pub fn shapePolygon(toplevel: *const Toplevel, width: i32, height: i32) ?window_shape.Resolved {
if (!chrome.polygons or toplevel.isMaximized() or toplevel.isFullscreen() or width <= 0 or height <= 0) return null;
- const outline = (window_shape.parse(theme.global.window_shape) catch return null) orelse return null;
- const resolved = window_shape.resolve(outline, @floatFromInt(width), @floatFromInt(height), toplevel.chromeDensity());
- return if (window_shape.usable(resolved)) resolved else null;
+ const density = toplevel.chromeDensity();
+ const text = theme.global.window_shape;
+ // Every client commit asks several times (insets, clip, plate, shadow), nearly
+ // always for the frame it asked for last: parse the theme's text once, and
+ // keep the last frame's answer.
+ const cache = &shape_cache;
+ if (text.len > cache.text.len) {
+ const outline = (window_shape.parse(text) catch return null) orelse return null;
+ const resolved = window_shape.resolve(outline, @floatFromInt(width), @floatFromInt(height), density);
+ return if (window_shape.usable(resolved)) resolved else null;
+ }
+ if (!cache.parsed or !std.mem.eql(u8, cache.text[0..cache.len], text)) {
+ cache.outline = window_shape.parse(text) catch null;
+ @memcpy(cache.text[0..text.len], text);
+ cache.len = text.len;
+ cache.parsed = true;
+ cache.width = 0;
+ }
+ const outline = cache.outline orelse return null;
+ if (cache.width != width or cache.height != height or cache.density != density) {
+ const resolved = window_shape.resolve(outline, @floatFromInt(width), @floatFromInt(height), density);
+ cache.resolved = if (window_shape.usable(resolved)) resolved else null;
+ cache.width = width;
+ cache.height = height;
+ cache.density = density;
+ }
+ return cache.resolved;
}
+/// The theme's outline as last parsed, and its polygon for the last frame asked
+/// about (`width` 0: none yet). Main thread only, like every caller.
+var shape_cache: struct {
+ text: [256]u8 = undefined,
+ len: usize = 0,
+ parsed: bool = false,
+ outline: ?window_shape.Outline = null,
+ width: i32 = 0,
+ height: i32 = 0,
+ density: f32 = 0,
+ resolved: ?window_shape.Resolved = null,
+} = .{};
+
/// What the window's polygon depends on beyond its size, for memos: the outline's
/// text and the density its px coordinates scale with. 0 without a polygon.
pub fn shapeKey(toplevel: *const Toplevel) u64 {
diff --git a/src/toplevel/corner_accents.zig b/src/toplevel/corner_accents.zig
index 16a1a41..5d747e2 100644
--- a/src/toplevel/corner_accents.zig
+++ b/src/toplevel/corner_accents.zig
@@ -7,23 +7,27 @@ const chrome = @import("../chrome.zig");
const PanelBuffer = @import("../panel_buffer.zig").PanelBuffer;
const ui = @import("ui");
+/// What every corner's raster is painted from, besides its own part of the outline.
const Memo = struct {
- width: i32,
- height: i32,
scale: f32,
density: f32,
- radius: f32,
- shape: u64,
color: [4]f32,
- extent: f32,
+ // Device-independent side of each corner's square, in logical px.
+ extent: i32,
stroke: f32,
inset: f32,
end_padding: f32,
};
+/// What the last sync saw: an unchanged client commit stops at comparing it.
+const Seen = struct { memo: Memo, width: i32, height: i32, radius: f32, shape: u64, opacity: f32 };
+
pub const State = struct {
nodes: [4]?*sn.Buffer = @splat(null),
- memo: ?Memo = null,
+ memo: ?Seen = null,
+ // What each corner's raster shows of the outline (`cornerKey`): a resize
+ // moves the corners without painting them again.
+ keys: [4]u64 = @splat(0),
extension: ui.anim.Anim = .{},
};
@@ -89,31 +93,37 @@ pub fn syncCornerAccents(t: *Toplevel) !void {
const now_ms = Toplevel.nowMs();
retarget(t, now_ms);
const density = t.chromeDensity();
- const memo: Memo = .{
- .width = t.chrome_width,
- .height = t.chrome_height,
- .scale = t.render_scale,
- .density = density,
+ const width = t.chrome_width;
+ const height = t.chrome_height;
+ // The small raster's bounds are whole logical pixels, so subpixel animation
+ // changes cannot reraster a held bar.
+ const wanted = @ceil((palette.window_corner_extent + state.extension.value(now_ms)) * density);
+ const extent: i32 = @intFromFloat(@ceil(@min(wanted, @as(f32, @floatFromInt(@min(width, height))) / 2)));
+ const seen: Seen = .{
+ .memo = .{
+ .scale = t.render_scale,
+ .density = density,
+ .color = palette.window_corner_accent,
+ .extent = extent,
+ .stroke = palette.window_corner_width,
+ .inset = palette.window_corner_inset,
+ .end_padding = palette.window_corner_end_padding,
+ },
+ .width = width,
+ .height = height,
.radius = t.cornerRadius(),
.shape = t.shapeKey(),
- .color = palette.window_corner_accent,
- // The small raster's bounds are whole logical pixels. Memoize those
- // same lengths so subpixel animation changes cannot reraster a held bar.
- .extent = @ceil((palette.window_corner_extent + state.extension.value(now_ms)) * density) / density,
- .stroke = palette.window_corner_width,
- .inset = palette.window_corner_inset,
- .end_padding = palette.window_corner_end_padding,
+ .opacity = t.shape_opacity,
};
- if (state.memo) |previous| if (std.meta.eql(previous, memo)) return;
- const extent: i32 = @intFromFloat(@ceil(@min(memo.extent * memo.density, @as(f32, @floatFromInt(@min(memo.width, memo.height))) / 2)));
+ if (state.memo) |previous| if (std.meta.eql(previous, seen)) return;
if (extent <= 0) return;
- const polygon = t.shapePolygon(memo.width, memo.height);
+ const memo = seen.memo;
+ const repaint = if (state.memo) |previous| !std.meta.eql(previous.memo, memo) else true;
+ const polygon = t.shapePolygon(width, height);
for (&state.nodes, 0..) |*slot, i| {
- const x = if (i % 2 == 0) 0 else memo.width - extent;
- const y = if (i < 2) 0 else memo.height - extent;
- const buffer = try PanelBuffer.createUnpooled(extent, extent, memo.scale);
- defer buffer.base.drop();
- paint(buffer, memo, polygon, x, y, extent);
+ const x = if (i % 2 == 0) 0 else width - extent;
+ const y = if (i < 2) 0 else height - extent;
+ const key = cornerKey(memo, polygon, seen.radius, x, y, width, height);
if (slot.* == null) {
const node = try t.frame_tree.createSceneBuffer(null);
node.point_accepts_input = struct {
@@ -123,35 +133,75 @@ pub fn syncCornerAccents(t: *Toplevel) !void {
}.accepts;
node.setFilterMode(.bilinear);
slot.* = node;
+ state.keys[i] = ~key;
}
const node = slot.*.?;
+ if (repaint or state.keys[i] != key) {
+ const buffer = try PanelBuffer.createUnpooled(extent, extent, memo.scale);
+ defer buffer.base.drop();
+ paint(buffer, memo, polygon, seen.radius, x, y, width, height);
+ node.setBuffer(&buffer.base);
+ node.setDestSize(extent, extent);
+ state.keys[i] = key;
+ }
node.node.setPosition(x, y);
- node.setDestSize(extent, extent);
- node.setBuffer(&buffer.base);
- node.setOpacity(t.shape_opacity);
+ node.setOpacity(seen.opacity);
node.node.setEnabled(true);
}
- state.memo = memo;
+ state.memo = seen;
+}
+
+/// How far from the outline the stroke's ink can lie, in logical px.
+fn reach(memo: Memo) f32 {
+ return @as(f32, @floatFromInt(chrome.frame_border)) + (memo.inset + memo.stroke) * memo.density + 1;
+}
+
+/// What the corner whose square starts at (`x`, `y`) shows of the outline. A
+/// rounded frame's corner depends on its radius alone (capped by a small frame).
+fn cornerKey(memo: Memo, polygon: ?ui.window_shape.Resolved, radius: f32, x: i32, y: i32, width: i32, height: i32) u64 {
+ if (polygon) |p| return ui.window_shape.localKey(p, @floatFromInt(x), @floatFromInt(y), @floatFromInt(memo.extent), @floatFromInt(memo.extent), reach(memo)) | 1;
+ const capped: u32 = @bitCast(@min(radius, @as(f32, @floatFromInt(@min(width, height))) / 2));
+ return @as(u64, capped) << 1;
}
-fn paint(buffer: *PanelBuffer, memo: Memo, polygon: ?ui.window_shape.Resolved, x: i32, y: i32, extent: i32) void {
- const color = memo.color;
+fn paint(buffer: *PanelBuffer, memo: Memo, polygon: ?ui.window_shape.Resolved, radius: f32, x: i32, y: i32, width: i32, height: i32) void {
+ const color: ui.text.Color = .{ .r = memo.color[0], .g = memo.color[1], .b = memo.color[2], .a = memo.color[3] };
+ const extent: f32 = @floatFromInt(memo.extent);
const inset = @as(f32, @floatFromInt(chrome.frame_border)) + memo.inset * memo.density;
+ const stroke = memo.stroke * memo.density;
+ // The stroke is the band `inset` to `inset + stroke` inside the outline.
+ // Its ink ends half a device pixel beyond either side.
+ const centre = -(inset + stroke / 2);
+ const half = stroke / 2 + 0.5 / memo.scale;
+ const stride: usize = @intCast(buffer.width);
+ // A raster outlives a resize, so it must not depend on where the frame's far
+ // edges were when it was painted: the polygon is measured in f64, and a
+ // rounded corner in a box of its own, by how far in from the frame's edges
+ // a pixel is.
+ const capped = @min(radius, @as(f32, @floatFromInt(@min(width, height))) / 2);
+ const box = 2 * @max(extent, capped) + 2;
for (0..@intCast(buffer.height)) |dy| {
const py = (@as(f32, @floatFromInt(dy)) + 0.5) / memo.scale;
- for (0..@intCast(buffer.width)) |dx| {
+ const wy = @as(f64, py) + @as(f64, @floatFromInt(y));
+ const along_y = if (y == 0) py else extent - py;
+ var dx: usize = 0;
+ while (dx < stride) : (dx += 1) {
const px = (@as(f32, @floatFromInt(dx)) + 0.5) / memo.scale;
- const wx = px + @as(f32, @floatFromInt(x));
- const wy = py + @as(f32, @floatFromInt(y));
- const distance: f32 = if (polygon) |p| @floatCast(ui.window_shape.sdPolygon(p, wx, wy)) else ui.sdf.sdRoundedBox(wx, wy, 0, 0, @floatFromInt(memo.width), @floatFromInt(memo.height), memo.radius);
+ const along_x = if (x == 0) px else extent - px;
+ const distance: f32 = if (polygon) |p| @floatCast(ui.window_shape.sdPolygon(p, @as(f64, px) + @as(f64, @floatFromInt(x)), wy)) else ui.sdf.sdRoundedBox(along_x, along_y, 0, 0, box, box, capped);
+ // Most of the square is clear of the band, and a distance changes by
+ // at most one per pixel: skip to where the band can next be.
+ const clear = (@abs(distance - centre) - half) * memo.scale - 1e-3;
+ if (clear >= 0) {
+ dx += @intFromFloat(clear);
+ continue;
+ }
// Leave the output pass's one-pixel ring untouched. This stroke is
// just inside it; all pixels still inherit frame opacity and clipping.
const coverage = ui.sdf.coverage((distance + inset) * memo.scale) *
- ui.sdf.coverage((-distance - inset - memo.stroke * memo.density) * memo.scale);
- const along_x = if (x == 0) px else @as(f32, @floatFromInt(extent)) - px;
- const along_y = if (y == 0) py else @as(f32, @floatFromInt(extent)) - py;
- const end = ui.sdf.coverage((@max(along_x, along_y) - @as(f32, @floatFromInt(extent)) + memo.end_padding * memo.density) * memo.scale);
- ui.text.blendPixel(&buffer.pixels[dy * @as(usize, @intCast(buffer.width)) + dx], .{ .r = color[0], .g = color[1], .b = color[2], .a = color[3] }, coverage * end);
+ ui.sdf.coverage((-distance - inset - stroke) * memo.scale);
+ const end = ui.sdf.coverage((@max(along_x, along_y) - extent + memo.end_padding * memo.density) * memo.scale);
+ if (coverage * end > 0) ui.text.blendPixel(&buffer.pixels[dy * stride + dx], color, coverage * end);
}
}
}
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
index 984c629..dbaffc4 100644
--- a/src/ui/AGENTS.md
+++ b/src/ui/AGENTS.md
@@ -10,6 +10,8 @@ text and colours, secrets) are in the root `AGENTS.md` ("Shared UI").
rect can cut its corners with `RectStyle.bevel` (`fillRect` hands it to
`highlight.fillBeveled`; no relief or `replace`). The power menu uses it
through `power_menu_bevel`, rounding its glass to stay inside the cut.
+ Like `fillRectPlain`, a beveled fill shades only the pixels near an edge:
+ each row's interior is one run (stored, blended, or skipped for an outline).
* **The scrollbar** (`widgets/scrollbar.zig`, Files' look): a thumb (track-less
unless painted track tokens or `scrollbar_track_relief` enable one; flat at `scrollbar_glow = 0`)
@@ -34,6 +36,8 @@ text and colours, secrets) are in the root `AGENTS.md` ("Shared UI").
controls Cairo's layer bounds: include the whole channel even without relief.
Stripe period, width and slope also come from the theme through `Look`;
period/width zero hides the stripes, and slope zero draws transverse bands.
+ App clients paint the channel on every scroll frame: keep its loop free of
+ soft-float calls (`@mod`, `@floor`, `@round` on a baseline x86_64 target).
* **Text fields with child accessories** reserve text/caret room with
`field.trailing = .accessory`. Place a shared button in the field's children
(Settings search uses a ghost clear button), so normal pointer and keyboard
diff --git a/src/ui/widgets/highlight.zig b/src/ui/widgets/highlight.zig
index b462d57..12b6803 100644
--- a/src/ui/widgets/highlight.zig
+++ b/src/ui/widgets/highlight.zig
@@ -4,6 +4,7 @@ const c = @import("c_gfx");
const theme = @import("../theme.zig");
const paint_mod = @import("../paint.zig");
const layout = @import("../layout.zig");
+const Color = @import("../text.zig").Color;
pub fn path(cr: *c.cairo_t, x: f64, y: f64, w: f64, h: f64, radius: f64) void {
const bevel = @min(theme.global.app_highlight_bevel, @min(w, h) / 2);
@@ -51,20 +52,44 @@ pub fn fillBeveled(r: *paint_mod.Renderer, box: paint_mod.ClipRect, style: layou
const half_w = box.w / 2;
const half_h = box.h / 2;
r.clean = false;
+ const fill: Color = .{ .r = style.color[0], .g = style.color[1], .b = style.color[2], .a = style.color[3] };
+ const border: Color = .{ .r = style.border_color[0], .g = style.border_color[1], .b = style.border_color[2], .a = style.border_color[3] };
+ // Pixels this far inside every edge are the fill alone, at full coverage:
+ // one run per row, with no distance to work out. An opaque fill stores one
+ // packed colour there and a clear one (an outline) leaves the run untouched.
+ const inner = style.border_width + 0.5 / s + 1e-3;
+ var solid: u32 = 0;
+ paint_mod.blendPixel(&solid, fill, 1);
var py = y0;
while (py < y1) : (py += 1) {
const y = @abs((@as(f32, @floatFromInt(py)) + 0.5) / s - box.y - half_h);
+ const row: usize = @intCast(py * r.width);
+ // Half the width of the run about the box's centre; negative on a row
+ // with none (within the border of the top or bottom edge).
+ const reach = if (y <= half_h - inner) @min(half_w - inner, half_w + half_h - bevel - inner * std.math.sqrt2 - y) else -1;
+ const centre = (box.x + half_w) * s;
+ const run_x0 = if (reach >= 0) std.math.clamp(@as(i32, @intFromFloat(@ceil(centre - reach * s - 0.5))), x0, x1) else x1;
+ const run_x1 = if (reach >= 0) std.math.clamp(@as(i32, @intFromFloat(@floor(centre + reach * s - 0.5))) + 1, run_x0, x1) else x1;
var px = x0;
while (px < x1) : (px += 1) {
+ if (px == run_x0 and run_x1 > run_x0) {
+ const run = r.pixels[row + @as(usize, @intCast(run_x0)) .. row + @as(usize, @intCast(run_x1))];
+ if (fill.a >= 1) {
+ @memset(run, solid);
+ } else if (fill.a > 0) {
+ for (run) |*pixel| paint_mod.blendPixel(pixel, fill, 1);
+ }
+ px = run_x1 - 1;
+ continue;
+ }
const x = @abs((@as(f32, @floatFromInt(px)) + 0.5) / s - box.x - half_w);
const distance = @max(@max(x - half_w, y - half_h), (x + y - half_w - half_h + bevel) / std.math.sqrt2);
const outer = paint_mod.sdf.coverage(distance * s);
- const inner = paint_mod.sdf.coverage((distance + style.border_width) * s);
- const index: usize = @intCast(py * r.width + px);
- const fill = style.color;
- paint_mod.blendPixel(&r.pixels[index], .{ .r = fill[0], .g = fill[1], .b = fill[2], .a = fill[3] }, outer);
- const border = style.border_color;
- paint_mod.blendPixel(&r.pixels[index], .{ .r = border[0], .g = border[1], .b = border[2], .a = border[3] }, @max(0, outer - inner));
+ if (outer <= 0) continue;
+ const inside = paint_mod.sdf.coverage((distance + style.border_width) * s);
+ const index = row + @as(usize, @intCast(px));
+ if (fill.a > 0) paint_mod.blendPixel(&r.pixels[index], fill, outer);
+ if (outer > inside and border.a > 0) paint_mod.blendPixel(&r.pixels[index], border, outer - inside);
}
}
}
diff --git a/src/ui/widgets/highlight_tests.zig b/src/ui/widgets/highlight_tests.zig
index f1fc960..8507f12 100644
--- a/src/ui/widgets/highlight_tests.zig
+++ b/src/ui/widgets/highlight_tests.zig
@@ -35,3 +35,45 @@ test "beveled highlights cut straight corners in Cairo and shell rasters" {
}
}
}
+
+/// Every pixel from its distance, as `fillBeveled` shades the ones near an edge.
+fn referenceBeveled(pixels: []u32, width: usize, height: usize, scale: f32, box: paint.ClipRect, style: @import("../layout.zig").RectStyle, wanted: f32) void {
+ const bevel = @min(wanted, @min(box.w, box.h) / 2);
+ for (0..height) |py| {
+ const y = @abs((@as(f32, @floatFromInt(py)) + 0.5) / scale - box.y - box.h / 2);
+ for (0..width) |px| {
+ const x = @abs((@as(f32, @floatFromInt(px)) + 0.5) / scale - box.x - box.w / 2);
+ const distance = @max(@max(x - box.w / 2, y - box.h / 2), (x + y - box.w / 2 - box.h / 2 + bevel) / std.math.sqrt2);
+ const outer = paint.sdf.coverage(distance * scale);
+ const inner = paint.sdf.coverage((distance + style.border_width) * scale);
+ const fill = style.color;
+ paint.blendPixel(&pixels[py * width + px], .{ .r = fill[0], .g = fill[1], .b = fill[2], .a = fill[3] }, outer);
+ const border = style.border_color;
+ paint.blendPixel(&pixels[py * width + px], .{ .r = border[0], .g = border[1], .b = border[2], .a = border[3] }, @max(0, outer - inner));
+ }
+ }
+}
+
+test "a beveled fill's interior runs match the per-pixel raster" {
+ const styles = [_]@import("../layout.zig").RectStyle{
+ .{ .color = .{ 0.1, 0.2, 0.3, 1 }, .border_width = 1, .border_color = .{ 1, 0.9, 0, 1 } },
+ .{ .color = .{ 0.1, 0.2, 0.3, 0.6 }, .border_width = 2.5, .border_color = .{ 1, 0.9, 0, 0.7 } },
+ .{ .color = .{ 0, 0, 0, 0 }, .border_width = 3, .border_color = .{ 1, 0.2, 0, 1 } },
+ .{ .color = .{ 0.4, 0.4, 0.4, 1 } },
+ };
+ const boxes = [_]paint.ClipRect{ .{ .x = 3, .y = 2, .w = 70, .h = 40 }, .{ .x = 0.5, .y = 1.25, .w = 21, .h = 9 }, .{ .x = -4, .y = 30, .w = 60, .h = 30 } };
+ for ([_]f32{ 1, 1.25, 1.5, 2 }) |scale| {
+ for (styles) |style| {
+ for (boxes) |box| {
+ for ([_]f32{ 3, 7, 16, 40 }) |bevel| {
+ var got: [120 * 100]u32 = @splat(0x80402010);
+ var want: [120 * 100]u32 = @splat(0x80402010);
+ var renderer = paint.Renderer.init(&got, 120, 100, scale);
+ highlight.fillBeveled(&renderer, box, style, bevel);
+ referenceBeveled(&want, 120, 100, scale, box, style, bevel);
+ try std.testing.expectEqualSlices(u32, &want, &got);
+ }
+ }
+ }
+ }
+}
diff --git a/src/ui/widgets/scrollbar_track.zig b/src/ui/widgets/scrollbar_track.zig
index 50d7317..fcdbf01 100644
--- a/src/ui/widgets/scrollbar_track.zig
+++ b/src/ui/widgets/scrollbar_track.zig
@@ -2,6 +2,7 @@
const scrollbar = @import("scrollbar.zig");
const paint_mod = @import("../paint.zig");
const sdf = @import("../sdf.zig");
+const Color = @import("../text.zig").Color;
pub fn paint(r: *paint_mod.Renderer, l: scrollbar.Look) void {
const box = l.track;
@@ -25,20 +26,73 @@ pub fn paint(r: *paint_mod.Renderer, l: scrollbar.Look) void {
const y0: i32 = @intFromFloat(@floor(@max(0, top * s)));
const x1: i32 = @intFromFloat(@ceil(@min(@as(f32, @floatFromInt(r.width)), right * s)));
const y1: i32 = @intFromFloat(@ceil(@min(@as(f32, @floatFromInt(r.height)), bottom * s)));
- const color = l.track_stripe;
+ const color: Color = .{ .r = l.track_stripe[0], .g = l.track_stripe[1], .b = l.track_stripe[2], .a = l.track_stripe[3] };
+ var solid: u32 = 0;
+ paint_mod.blendPixel(&solid, color, 1);
+ // Away from the rounded ends the channel's edge is a straight side: a pixel
+ // this far inside both sides is wholly covered, with no distance to work out.
+ const radius = @min(l.track_radius, @min(box.w, box.h) / 2);
+ const clear = 0.5 / s + 1e-3;
r.clean = false;
var py = y0;
while (py < y1) : (py += 1) {
const y = (@as(f32, @floatFromInt(py)) + 0.5) / s - box.y;
+ const side_y = @abs(y - box.h / 2) - box.h / 2;
var px = x0;
while (px < x1) : (px += 1) {
const x = (@as(f32, @floatFromInt(px)) + 0.5) / s - box.x;
- const edge = sdf.coverage(sdf.sdRoundedBox(x, y, 0, 0, box.w, box.h, l.track_radius) * s);
const along = if (l.axis == .vertical) y else x;
const across = if (l.axis == .vertical) x else y;
- const phase = @mod(across * l.stripe_slope + along, period);
- const stripe = sdf.coverage((@abs(phase - period / 2) - half_width) * s / normal);
- if (edge * stripe > 0) paint_mod.blendPixel(&r.pixels[@intCast(py * r.width + px)], .{ .r = color[0], .g = color[1], .b = color[2], .a = color[3] }, edge * stripe);
+ const stripe = sdf.coverage((@abs(phase(across * l.stripe_slope + along, period) - period / 2) - half_width) * s / normal);
+ if (stripe <= 0) continue;
+ const side_x = @abs(x - box.w / 2) - box.w / 2;
+ const inside = side_x <= -clear and side_y <= -clear and !(side_x > -radius and side_y > -radius);
+ const cover = if (inside) stripe else stripe * sdf.coverage(sdf.sdRoundedBox(x, y, 0, 0, box.w, box.h, l.track_radius) * s);
+ if (cover <= 0) continue;
+ const pixel = &r.pixels[@intCast(py * r.width + px)];
+ if (cover >= 1 and color.a >= 1) pixel.* = solid else paint_mod.blendPixel(pixel, color, cover);
+ }
+ }
+}
+
+/// `@mod(v, period)`, without the soft-float remainder a baseline x86_64 build
+/// calls for it: the quotient's whole part, then the exact remainder in f64.
+fn phase(v: f32, period: f32) f32 {
+ if (!(v >= 0) or v / period > 1e9) return @mod(v, period);
+ const whole: f64 = @floatFromInt(@as(i64, @intFromFloat(v / period)));
+ var rem = @as(f64, v) - whole * @as(f64, period);
+ if (rem < 0) rem += period else if (rem >= period) rem -= period;
+ return @floatCast(rem);
+}
+
+test "the hatching matches a raster that works out every pixel" {
+ const std = @import("std");
+ for ([_]f32{ 0.37, 4.2, 9.999, 10, 10.001, 123.456, 9999.5 }) |v| {
+ for ([_]f32{ 10, 3.3, 0.7 }) |period| try std.testing.expectEqual(@mod(v, period), phase(v, period));
+ }
+ for ([_]f32{ 1, 1.25, 1.5, 2 }) |scale| {
+ for ([_]scrollbar.Axis{ .vertical, .horizontal }) |axis| {
+ for ([_][4]f32{ .{ 0.2, 0.3, 0.4, 1 }, .{ 0.2, 0.3, 0.4, 0.5 } }) |stripe| {
+ const track: scrollbar.Rect = if (axis == .vertical) .{ .x = 3.25, .y = 2, .w = 8, .h = 60 } else .{ .x = 2, .y = 3.25, .w = 60, .h = 8 };
+ const look: scrollbar.Look = .{ .track = track, .track_radius = 3.5, .track_color = @splat(0), .track_fill = .{ 0.1, 0.1, 0.1, 1 }, .track_stripe = stripe, .stripe_period = 10, .stripe_width = 5, .stripe_slope = 1, .rect = track, .radius = 3, .color = @splat(1), .axis = axis, .highlight = @splat(0), .shine = 0, .glow = 0 };
+ var got: [140 * 140]u32 = @splat(0);
+ var want: [140 * 140]u32 = @splat(0);
+ var renderer = paint_mod.Renderer.init(&got, 140, 140, scale);
+ paint(&renderer, look);
+ var reference = paint_mod.Renderer.init(&want, 140, 140, scale);
+ reference.fillRect(track.x, track.y, track.w, track.h, .{ .color = look.track_fill, .radius = look.track_radius });
+ for (0..140) |py| for (0..140) |px| {
+ const x = (@as(f32, @floatFromInt(px)) + 0.5) / scale - track.x;
+ const y = (@as(f32, @floatFromInt(py)) + 0.5) / scale - track.y;
+ if (x < -1 or y < -1 or x > track.w + 1 or y > track.h + 1) continue;
+ const edge = sdf.coverage(sdf.sdRoundedBox(x, y, 0, 0, track.w, track.h, look.track_radius) * scale);
+ const along = if (axis == .vertical) y else x;
+ const across = if (axis == .vertical) x else y;
+ const hatch = sdf.coverage((@abs(@mod(across + along, 10) - 5) - 2.5) * scale / @sqrt(2.0));
+ if (edge * hatch > 0) paint_mod.blendPixel(&want[py * 140 + px], .{ .r = stripe[0], .g = stripe[1], .b = stripe[2], .a = stripe[3] }, edge * hatch);
+ };
+ try std.testing.expectEqualSlices(u32, &want, &got);
+ }
}
}
}
diff --git a/src/ui/window_shape.zig b/src/ui/window_shape.zig
index 9a79f21..a18f993 100644
--- a/src/ui/window_shape.zig
+++ b/src/ui/window_shape.zig
@@ -101,7 +101,8 @@ pub fn sdPolygon(r: Resolved, px: f64, py: f64) f64 {
var s: f64 = 1;
for (0..r.count) |i| {
const a = r.points[i];
- const b = r.points[(i + 1) % r.count];
+ // Not `% r.count`: a division per edge was a third of a raster's time.
+ const b = r.points[if (i + 1 == r.count) 0 else i + 1];
const ex = b[0] - a[0];
const ey = b[1] - a[1];
const wx = px - a[0];
@@ -119,6 +120,59 @@ pub fn sdPolygon(r: Resolved, px: f64, py: f64) f64 {
return s * @sqrt(d);
}
+/// How many device pixels after this one, along a row or column, keep a
+/// saturated coverage (wholly inside or wholly outside), given this pixel's
+/// signed distance in device pixels. A distance changes by at most one per
+/// pixel, so a raster asks for the next distance only where an edge can be.
+pub fn saturatedRun(device_distance: f32) usize {
+ const clear = @abs(device_distance) - 0.5 - 1e-3;
+ return if (clear >= 1) @intFromFloat(clear) else 0;
+}
+
+/// What the outline looks like inside the box (`x`, `y`, `w`, `h`) grown by
+/// `margin`: the edges that reach it, clipped to it and measured from its
+/// origin, and whether its centre is inside. A raster of the outline within
+/// `margin` of the box, drawn from the box's origin, is the same while this is:
+/// a corner keeps its key when the frame is resized, as far-edge anchors move
+/// with the corner.
+pub fn localKey(r: Resolved, x: f64, y: f64, w: f64, h: f64, margin: f64) u64 {
+ var hasher = std.hash.Wyhash.init(r.count);
+ const lo = [2]f64{ x - margin, y - margin };
+ const hi = [2]f64{ x + w + margin, y + h + margin };
+ for (0..r.count) |i| {
+ const a = r.points[i];
+ const b = r.points[(i + 1) % r.count];
+ var t0: f64 = 0;
+ var t1: f64 = 1;
+ var reaches = true;
+ for (0..2) |axis| {
+ const d = b[axis] - a[axis];
+ if (d == 0) {
+ if (a[axis] < lo[axis] or a[axis] > hi[axis]) reaches = false;
+ continue;
+ }
+ const ta = (lo[axis] - a[axis]) / d;
+ const tb = (hi[axis] - a[axis]) / d;
+ t0 = @max(t0, @min(ta, tb));
+ t1 = @min(t1, @max(ta, tb));
+ }
+ if (!reaches or t0 > t1) continue;
+ // Whole 1/1024ths of a pixel: the same edge at another frame size must
+ // not differ by the rounding of its far-edge anchor.
+ const ends = [4]i64{
+ quantize(a[0] + (b[0] - a[0]) * t0 - x), quantize(a[1] + (b[1] - a[1]) * t0 - y),
+ quantize(a[0] + (b[0] - a[0]) * t1 - x), quantize(a[1] + (b[1] - a[1]) * t1 - y),
+ };
+ hasher.update(std.mem.asBytes(&ends));
+ }
+ hasher.update(&.{@intFromBool(sdPolygon(r, x + w / 2, y + h / 2) < 0)});
+ return hasher.final();
+}
+
+fn quantize(v: f64) i64 {
+ return @intFromFloat(@round(std.math.clamp(v, -1e9, 1e9) * 1024));
+}
+
pub const Insets = struct { left: i32 = 0, right: i32 = 0 };
/// How far in from the left and right edges of a frame `width` wide the outline
@@ -231,3 +285,29 @@ test "row insets follow the slants and skip a notch" {
const box = resolve((try parse("0 0, -0 0, -0 -0, 0 -0")).?, 1000, 44, 1);
try std.testing.expectEqual(Insets{}, rowInsets(box, 1000, 4, 40));
}
+
+test "a corner's local key survives a resize and follows its own edges" {
+ const outline = (try parse("0 14, 14 0, 282.5 0, 289.5 7, -14 7, -0 21, -0 -12, -12 -0, 12 -0, 0 -12")).?;
+ const small = resolve(outline, 700, 500, 1);
+ const large = resolve(outline, 913, 641, 1);
+ // Each corner's 52 px square, measured from its own origin.
+ try std.testing.expectEqual(localKey(small, 0, 0, 52, 52, 5), localKey(large, 0, 0, 52, 52, 5));
+ try std.testing.expectEqual(localKey(small, 700 - 52, 0, 52, 52, 5), localKey(large, 913 - 52, 0, 52, 52, 5));
+ try std.testing.expectEqual(localKey(small, 0, 500 - 52, 52, 52, 5), localKey(large, 0, 641 - 52, 52, 52, 5));
+ try std.testing.expectEqual(localKey(small, 700 - 52, 500 - 52, 52, 52, 5), localKey(large, 913 - 52, 641 - 52, 52, 52, 5));
+ // The corners differ from one another, and a narrow frame brings the step
+ // of the top edge into the top right corner's square.
+ try std.testing.expect(localKey(small, 0, 0, 52, 52, 5) != localKey(small, 700 - 52, 0, 52, 52, 5));
+ const narrow = resolve(outline, 320, 500, 1);
+ try std.testing.expect(localKey(narrow, 320 - 52, 0, 52, 52, 5) != localKey(small, 700 - 52, 0, 52, 52, 5));
+ // Another density moves the cuts.
+ const dense = resolve(outline, 700, 500, 1.25);
+ try std.testing.expect(localKey(dense, 0, 0, 52, 52, 5) != localKey(small, 0, 0, 52, 52, 5));
+}
+
+test "a saturated run never reaches an edge" {
+ try std.testing.expectEqual(@as(usize, 0), saturatedRun(0.2));
+ try std.testing.expectEqual(@as(usize, 0), saturatedRun(-1.4));
+ try std.testing.expectEqual(@as(usize, 1), saturatedRun(-1.6));
+ try std.testing.expectEqual(@as(usize, 11), saturatedRun(12.4));
+}