@native-sdk/cli 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/build/app.zig +121 -66
  2. package/build.zig +123 -6
  3. package/package.json +9 -9
  4. package/skill-data/core/SKILL.md +3 -0
  5. package/skill-data/native-ui/SKILL.md +16 -0
  6. package/skill-data/zig/SKILL.md +198 -0
  7. package/skills/native-sdk/SKILL.md +1 -1
  8. package/src/app_runner/root.zig +51 -9
  9. package/src/platform/linux/gtk_host.c +226 -21
  10. package/src/platform/windows/webview2_host.cpp +16 -10
  11. package/src/primitives/app_manifest/root.zig +8 -0
  12. package/src/primitives/app_manifest/types.zig +14 -0
  13. package/src/primitives/app_manifest/validation.zig +18 -0
  14. package/src/primitives/app_manifest/web_layer.zig +366 -0
  15. package/src/primitives/canvas/chart_tests.zig +2 -2
  16. package/src/primitives/canvas/markdown_tests.zig +1 -1
  17. package/src/primitives/canvas/reference.zig +135 -6
  18. package/src/primitives/canvas/reference_tests.zig +171 -6
  19. package/src/primitives/canvas/root.zig +3 -0
  20. package/src/primitives/canvas/test_support.zig +3 -0
  21. package/src/primitives/canvas/widget_builtin_tests.zig +249 -4
  22. package/src/primitives/canvas/widget_render_controls.zig +18 -1
  23. package/src/primitives/canvas/widget_runtime.zig +3 -0
  24. package/src/primitives/canvas/widget_text_input.zig +104 -1
  25. package/src/runtime/api.zig +7 -0
  26. package/src/runtime/bridge_responses.zig +2 -0
  27. package/src/runtime/builtin_bridge.zig +6 -0
  28. package/src/runtime/canvas_widget_runtime.zig +23 -3
  29. package/src/runtime/canvas_widget_text_tests.zig +101 -0
  30. package/src/runtime/flow.zig +8 -0
  31. package/src/runtime/platform_bridge_tests.zig +1 -0
  32. package/src/runtime/session_tests.zig +35 -8
  33. package/src/runtime/view.zig +1 -1
  34. package/src/runtime/view_widget_scroll.zig +12 -1
  35. package/src/runtime/view_widget_text.zig +6 -2
  36. package/src/runtime/web_layer_gate_tests.zig +242 -0
  37. package/src/runtime/window_storage.zig +5 -0
  38. package/src/runtime/window_view_runtime.zig +1 -0
  39. package/src/tooling/buildgraph.zig +119 -3
  40. package/src/tooling/junction.zig +247 -0
  41. package/src/tooling/manifest.zig +267 -1
  42. package/src/tooling/package.zig +598 -6
  43. package/src/tooling/raw_manifest.zig +1 -0
  44. package/src/tooling/root.zig +1 -0
  45. package/src/tooling/templates.zig +288 -61
  46. package/src/tooling/verbs.zig +5 -0
@@ -0,0 +1,366 @@
1
+ //! The web-layer inference contract: the ONE definition of when an app
2
+ //! ships the embedded web layer. An app is WEB when it declares web use
3
+ //! (a `.frontend` block, the `"webview"` capability, a `.shell` webview
4
+ //! view) or the RESOLVED web engine is Chromium; otherwise it is
5
+ //! native-only and the platform host compiles without the embedded
6
+ //! layer. `.webview_layer = "include"|"exclude"` overrides the
7
+ //! inference — and an exclude that contradicts a web declaration is a
8
+ //! refused conflict, never a silently broken app.
9
+ //!
10
+ //! Every boundary consumes this file and feeds it the inputs that
11
+ //! boundary owns:
12
+ //!
13
+ //! - The standard build graph (build/app.zig) sees `-Dweb-engine` and
14
+ //! `-Dweb-layer`: its resolved engine is the flag orelse app.zon, its
15
+ //! effective layer setting is the flag orelse app.zon, and a conflict
16
+ //! is a configure-time error.
17
+ //! - The CLI (src/tooling/manifest.zig `webLayer`/`webLayerResolved`,
18
+ //! consumed by src/tooling/package.zig) sees `--web-engine` and the
19
+ //! package verb's `--web-layer`: each flag beats its app.zon field the
20
+ //! same way the `-D` options do in the build graph, and a conflict
21
+ //! refuses the package. Both standard graph shapes (build/app.zig and
22
+ //! the generated template's build.zig) forward their RESOLVED layer
23
+ //! decision to `native package` as `--web-layer include|exclude`, so a
24
+ //! graph-driven package never re-infers what the graph already decided
25
+ //! and the packaged artifact structurally agrees with the exe.
26
+ //! - The app runner (src/app_runner/root.zig) evaluates the contract at
27
+ //! comptime over the app.zon import. It NEVER sees the `-Dweb-engine`
28
+ //! flag, so its engine input is the manifest's own engine: the
29
+ //! runner's guard fires on every manifest-visible web declaration,
30
+ //! while an engine resolved to Chromium by flag alone stays a
31
+ //! configure-time error in the build graph, which does see the flag.
32
+
33
+ const std = @import("std");
34
+ const types = @import("types.zig");
35
+
36
+ pub const WebEngine = types.WebEngine;
37
+ pub const WebViewLayer = types.WebViewLayer;
38
+
39
+ /// A web declaration: one reason an app needs the embedded web layer.
40
+ /// Scanning stops at the first hit, in this order, so teaching messages
41
+ /// stay deterministic.
42
+ pub const Declaration = enum {
43
+ frontend,
44
+ capability,
45
+ shell_webview,
46
+ chromium_engine,
47
+ /// Not a manifest field: a lenient parse (the build graph reading
48
+ /// app.zon it may not fully understand) could not read the manifest
49
+ /// at all. Absence of proof is not proof of a native-only app, so an
50
+ /// unreadable manifest counts as a web declaration — over-inclusion
51
+ /// costs binary size, a wrong exclusion breaks declared webviews.
52
+ unreadable_manifest,
53
+
54
+ /// The teaching-message half of a declaration, shared so every
55
+ /// boundary names the same cause the same way.
56
+ pub fn text(self: Declaration) []const u8 {
57
+ return switch (self) {
58
+ .frontend => "a .frontend block",
59
+ .capability => "the \"webview\" capability",
60
+ .shell_webview => "a .shell webview view",
61
+ .chromium_engine => "the Chromium web engine",
62
+ .unreadable_manifest => "an app.zon the build graph could not parse",
63
+ };
64
+ }
65
+
66
+ fn reason(self: Declaration) Reason {
67
+ return switch (self) {
68
+ .frontend => .frontend,
69
+ .capability => .capability,
70
+ .shell_webview => .shell_webview,
71
+ .chromium_engine => .chromium_engine,
72
+ .unreadable_manifest => .unreadable_manifest,
73
+ };
74
+ }
75
+ };
76
+
77
+ /// Why the web layer is (or is not) in the build, for verdict lines.
78
+ pub const Reason = enum {
79
+ inferred_native_only,
80
+ declared_exclude,
81
+ capability,
82
+ frontend,
83
+ shell_webview,
84
+ chromium_engine,
85
+ declared_include,
86
+ unreadable_manifest,
87
+ };
88
+
89
+ pub const Decision = struct {
90
+ enabled: bool,
91
+ reason: Reason,
92
+ };
93
+
94
+ pub const Error = error{WebViewLayerConflict};
95
+
96
+ /// The decision half of the contract: `include` forces the layer on,
97
+ /// `auto` infers it from the declarations, and `exclude` promises a
98
+ /// native-only app — so an exclude alongside any web declaration is a
99
+ /// contradiction this returns as an error for the boundary to report,
100
+ /// never resolved silently in either direction.
101
+ pub fn decide(setting: WebViewLayer, declaration: ?Declaration) Error!Decision {
102
+ return switch (setting) {
103
+ .include => .{ .enabled = true, .reason = .declared_include },
104
+ .exclude => if (declaration != null) error.WebViewLayerConflict else .{ .enabled = false, .reason = .declared_exclude },
105
+ .auto => if (declaration) |value| .{ .enabled = true, .reason = value.reason() } else .{ .enabled = false, .reason = .inferred_native_only },
106
+ };
107
+ }
108
+
109
+ /// The full inference over manifest-shaped data plus the resolved
110
+ /// engine and the effective layer setting (override orelse manifest).
111
+ pub fn infer(manifest: anytype, resolved_engine: WebEngine, setting: WebViewLayer) Error!Decision {
112
+ return decide(setting, webDeclaration(manifest, resolved_engine));
113
+ }
114
+
115
+ /// The first web declaration for a build: the manifest scan, then the
116
+ /// RESOLVED engine. Boundaries that resolve an engine flag pass the
117
+ /// resolved value; boundaries without one (validation, the runner) pass
118
+ /// the manifest's own engine.
119
+ pub fn webDeclaration(manifest: anytype, resolved_engine: WebEngine) ?Declaration {
120
+ return foldEngine(manifestDeclaration(manifest), resolved_engine);
121
+ }
122
+
123
+ /// Fold the resolved engine into an already-computed manifest scan, for
124
+ /// boundaries (the build graph) that scan at parse time and resolve the
125
+ /// engine later.
126
+ pub fn foldEngine(declaration: ?Declaration, resolved_engine: WebEngine) ?Declaration {
127
+ if (declaration) |value| return value;
128
+ return if (resolved_engine == .chromium) .chromium_engine else null;
129
+ }
130
+
131
+ /// The manifest half of the scan, duck-typed so every boundary feeds
132
+ /// the shape it has: the runner's comptime app.zon import (fields may
133
+ /// be absent, lists are tuples), a lenient build-graph parse and the
134
+ /// CLI's parsed metadata (string kinds, slice lists), and the typed
135
+ /// `Manifest` (Capability unions, ViewKind enums). The engine is NOT
136
+ /// part of this scan — pass the resolved engine to `webDeclaration`.
137
+ pub fn manifestDeclaration(manifest: anytype) ?Declaration {
138
+ if (declaresFrontend(manifest)) return .frontend;
139
+ if (declaresWebviewCapability(manifest)) return .capability;
140
+ if (declaresShellWebviewView(manifest)) return .shell_webview;
141
+ return null;
142
+ }
143
+
144
+ pub fn parseWebEngine(value: []const u8) ?WebEngine {
145
+ if (std.mem.eql(u8, value, "system")) return .system;
146
+ if (std.mem.eql(u8, value, "chromium")) return .chromium;
147
+ return null;
148
+ }
149
+
150
+ pub fn parseWebViewLayer(value: []const u8) ?WebViewLayer {
151
+ if (std.mem.eql(u8, value, "auto")) return .auto;
152
+ if (std.mem.eql(u8, value, "include")) return .include;
153
+ if (std.mem.eql(u8, value, "exclude")) return .exclude;
154
+ return null;
155
+ }
156
+
157
+ fn declaresFrontend(manifest: anytype) bool {
158
+ if (comptime !@hasField(@TypeOf(manifest), "frontend")) return false;
159
+ const frontend = manifest.frontend;
160
+ const T = @TypeOf(frontend);
161
+ if (comptime T == @TypeOf(null)) return false;
162
+ if (comptime @typeInfo(T) == .optional) return frontend != null;
163
+ // A ZON `.frontend = .{ ... }` block: present means declared.
164
+ return true;
165
+ }
166
+
167
+ fn declaresWebviewCapability(manifest: anytype) bool {
168
+ if (comptime !@hasField(@TypeOf(manifest), "capabilities")) return false;
169
+ return anyElement(manifest.capabilities, isWebviewName);
170
+ }
171
+
172
+ fn declaresShellWebviewView(manifest: anytype) bool {
173
+ if (comptime !@hasField(@TypeOf(manifest), "shell")) return false;
174
+ const shell = manifest.shell;
175
+ if (comptime !@hasField(@TypeOf(shell), "windows")) return false;
176
+ return anyElement(shell.windows, windowHasWebviewView);
177
+ }
178
+
179
+ fn windowHasWebviewView(window: anytype) bool {
180
+ if (comptime !@hasField(@TypeOf(window), "views")) return false;
181
+ return anyElement(window.views, viewIsWebview);
182
+ }
183
+
184
+ fn viewIsWebview(view: anytype) bool {
185
+ if (comptime !@hasField(@TypeOf(view), "kind")) return false;
186
+ return isWebviewName(view.kind);
187
+ }
188
+
189
+ /// Whether a capability or view kind names the webview: an enum tag
190
+ /// (`ViewKind`), a tagged-union tag (`Capability`), or string data (the
191
+ /// ZON import and parsed-metadata shapes).
192
+ fn isWebviewName(value: anytype) bool {
193
+ return switch (@typeInfo(@TypeOf(value))) {
194
+ .@"enum" => value == .webview,
195
+ .@"union" => std.meta.activeTag(value) == .webview,
196
+ else => std.mem.eql(u8, value, "webview"),
197
+ };
198
+ }
199
+
200
+ /// Whether any element of `list` matches. Slices and arrays iterate at
201
+ /// runtime; ZON tuples iterate inline so the whole scan stays usable in
202
+ /// the runner's comptime evaluation.
203
+ fn anyElement(list: anytype, comptime match: anytype) bool {
204
+ switch (@typeInfo(@TypeOf(list))) {
205
+ .pointer, .array => {
206
+ for (list) |element| {
207
+ if (match(element)) return true;
208
+ }
209
+ return false;
210
+ },
211
+ .@"struct" => |info| {
212
+ if (comptime info.fields.len == 0) return false;
213
+ inline for (list) |element| {
214
+ if (match(element)) return true;
215
+ }
216
+ return false;
217
+ },
218
+ else => return false,
219
+ }
220
+ }
221
+
222
+ // ---------------------------------------------------------------------------
223
+ // Contract matrix: every boundary shape, every inference row.
224
+ // ---------------------------------------------------------------------------
225
+
226
+ /// The typed-Manifest shape (what validation.zig scans).
227
+ const typed = struct {
228
+ const webview_capability = [_]types.Capability{.webview};
229
+ const canvas_capabilities = [_]types.Capability{ .native_views, .gpu_surfaces };
230
+ const webview_views = [_]types.ShellView{.{ .label = "content", .kind = .webview }};
231
+ const toolbar_views = [_]types.ShellView{.{ .label = "bar", .kind = .toolbar }};
232
+ const webview_windows = [_]types.ShellWindow{.{ .label = "main", .views = &webview_views }};
233
+ const toolbar_windows = [_]types.ShellWindow{.{ .label = "main", .views = &toolbar_views }};
234
+ };
235
+
236
+ /// The parsed-metadata shape (what the CLI's manifest tooling scans):
237
+ /// string kinds, slice lists, an optional frontend block.
238
+ const MetadataShape = struct {
239
+ const View = struct { kind: []const u8 };
240
+ const Window = struct { views: []const View = &.{} };
241
+ capabilities: []const []const u8 = &.{},
242
+ frontend: ?struct {} = null,
243
+ shell: struct { windows: []const Window = &.{} } = .{},
244
+ };
245
+
246
+ test "web-layer contract matrix agrees across boundary shapes" {
247
+ // Each row runs the scan over three shapes of the same manifest —
248
+ // the runner's comptime ZON import (tuples, absent fields), the
249
+ // typed Manifest, and the CLI's parsed metadata — and every shape
250
+ // must produce the same declaration. The build graph's lenient
251
+ // parse is the metadata shape with narrower fields, and its adapter
252
+ // (build/app.zig resolveWebLayer) is `foldEngine` + `decide`, both
253
+ // exercised below.
254
+
255
+ // Canvas-only: nothing declared, native-only under auto.
256
+ try std.testing.expectEqual(null, manifestDeclaration(.{ .capabilities = .{ "native_views", "gpu_surfaces" } }));
257
+ try std.testing.expectEqual(null, manifestDeclaration(types.Manifest{
258
+ .identity = .{ .id = "dev.example.canvas", .name = "canvas" },
259
+ .version = .{ .major = 1, .minor = 0, .patch = 0 },
260
+ .capabilities = &typed.canvas_capabilities,
261
+ }));
262
+ try std.testing.expectEqual(null, manifestDeclaration(MetadataShape{ .capabilities = &.{ "native_views", "gpu_surfaces" } }));
263
+ {
264
+ const decision = try infer(.{}, .system, .auto);
265
+ try std.testing.expect(!decision.enabled);
266
+ try std.testing.expectEqual(Reason.inferred_native_only, decision.reason);
267
+ }
268
+
269
+ // The "webview" capability.
270
+ try std.testing.expectEqual(Declaration.capability, manifestDeclaration(.{ .capabilities = .{"webview"} }));
271
+ try std.testing.expectEqual(Declaration.capability, manifestDeclaration(types.Manifest{
272
+ .identity = .{ .id = "dev.example.a", .name = "a" },
273
+ .version = .{ .major = 1, .minor = 0, .patch = 0 },
274
+ .capabilities = &typed.webview_capability,
275
+ }));
276
+ try std.testing.expectEqual(Declaration.capability, manifestDeclaration(MetadataShape{ .capabilities = &.{"webview"} }));
277
+
278
+ // A .frontend block.
279
+ try std.testing.expectEqual(Declaration.frontend, manifestDeclaration(.{ .frontend = .{ .dist = "frontend/dist" } }));
280
+ try std.testing.expectEqual(Declaration.frontend, manifestDeclaration(types.Manifest{
281
+ .identity = .{ .id = "dev.example.b", .name = "b" },
282
+ .version = .{ .major = 1, .minor = 0, .patch = 0 },
283
+ .frontend = .{},
284
+ }));
285
+ try std.testing.expectEqual(Declaration.frontend, manifestDeclaration(MetadataShape{ .frontend = .{} }));
286
+
287
+ // A .shell webview view (and a webview-free shell stays native).
288
+ try std.testing.expectEqual(Declaration.shell_webview, manifestDeclaration(.{ .shell = .{ .windows = .{.{ .views = .{.{ .kind = "webview" }} }} } }));
289
+ try std.testing.expectEqual(Declaration.shell_webview, manifestDeclaration(types.Manifest{
290
+ .identity = .{ .id = "dev.example.c", .name = "c" },
291
+ .version = .{ .major = 1, .minor = 0, .patch = 0 },
292
+ .shell = .{ .windows = &typed.webview_windows },
293
+ }));
294
+ try std.testing.expectEqual(Declaration.shell_webview, manifestDeclaration(MetadataShape{ .shell = .{ .windows = &.{.{ .views = &.{.{ .kind = "webview" }} }} } }));
295
+ try std.testing.expectEqual(null, manifestDeclaration(types.Manifest{
296
+ .identity = .{ .id = "dev.example.d", .name = "d" },
297
+ .version = .{ .major = 1, .minor = 0, .patch = 0 },
298
+ .shell = .{ .windows = &typed.toolbar_windows },
299
+ }));
300
+
301
+ // The Chromium engine is web intent wherever it was resolved: from
302
+ // app.zon (every boundary sees it) or from a flag (`-Dweb-engine` /
303
+ // `--web-engine`, seen by the build graph and the CLI; the runner
304
+ // never sees flags and covers only the manifest engine — the split
305
+ // this file's module doc pins down).
306
+ try std.testing.expectEqual(Declaration.chromium_engine, webDeclaration(.{}, .chromium));
307
+ try std.testing.expectEqual(Declaration.chromium_engine, foldEngine(null, .chromium));
308
+ {
309
+ const decision = try infer(.{}, .chromium, .auto);
310
+ try std.testing.expect(decision.enabled);
311
+ try std.testing.expectEqual(Reason.chromium_engine, decision.reason);
312
+ }
313
+
314
+ // A vestigial explicit `.web_engine = "system"` is NOT web intent.
315
+ try std.testing.expectEqual(null, webDeclaration(.{ .web_engine = "system" }, .system));
316
+ try std.testing.expectEqual(WebEngine.system, parseWebEngine("system"));
317
+
318
+ // Explicit overrides win in both directions.
319
+ {
320
+ const included = try infer(.{}, .system, .include);
321
+ try std.testing.expect(included.enabled);
322
+ try std.testing.expectEqual(Reason.declared_include, included.reason);
323
+ const excluded = try infer(.{}, .system, .exclude);
324
+ try std.testing.expect(!excluded.enabled);
325
+ try std.testing.expectEqual(Reason.declared_exclude, excluded.reason);
326
+ }
327
+
328
+ // Exclude + any web declaration is a refused conflict — including
329
+ // an engine resolved to Chromium with a web-free manifest.
330
+ try std.testing.expectError(error.WebViewLayerConflict, infer(.{ .capabilities = .{"webview"} }, .system, .exclude));
331
+ try std.testing.expectError(error.WebViewLayerConflict, infer(.{}, .chromium, .exclude));
332
+ try std.testing.expectError(error.WebViewLayerConflict, decide(.exclude, .unreadable_manifest));
333
+
334
+ // The package boundary's forwarded resolution: the build graphs hand
335
+ // `native package` their computed decision as `--web-layer
336
+ // include|exclude`, and replaying that setting through `decide` must
337
+ // reproduce the same enabled-ness for every row the graph can reach
338
+ // — forwarding the resolution is lossless, so the exe and the
339
+ // package it lands in can never disagree about the web layer.
340
+ const forward_settings = [_]WebViewLayer{ .auto, .include, .exclude };
341
+ const forward_declarations = [_]?Declaration{ null, .capability, .chromium_engine };
342
+ for (forward_settings) |setting| {
343
+ for (forward_declarations) |declaration| {
344
+ // A refused conflict never configures, so the graph has
345
+ // nothing to forward for that row.
346
+ const original = decide(setting, declaration) catch continue;
347
+ const replayed = try decide(if (original.enabled) .include else .exclude, declaration);
348
+ try std.testing.expectEqual(original.enabled, replayed.enabled);
349
+ }
350
+ }
351
+
352
+ // The runner's comptime evaluation: the same scan over a ZON-import
353
+ // shape, forced through comptime.
354
+ comptime {
355
+ if (manifestDeclaration(.{ .capabilities = .{ "native_views", "gpu_surfaces" } }) != null) @compileError("canvas manifest must scan native-only");
356
+ if (manifestDeclaration(.{ .capabilities = .{"webview"} }) != Declaration.capability) @compileError("webview capability must scan as a declaration");
357
+ if (webDeclaration(.{ .web_engine = "chromium" }, parseWebEngine("chromium").?) != Declaration.chromium_engine) @compileError("manifest chromium engine must scan as a declaration");
358
+ }
359
+ }
360
+
361
+ test "web-layer declarations carry the shared teaching text" {
362
+ try std.testing.expectEqualStrings("a .frontend block", Declaration.frontend.text());
363
+ try std.testing.expectEqualStrings("the \"webview\" capability", Declaration.capability.text());
364
+ try std.testing.expectEqualStrings("a .shell webview view", Declaration.shell_webview.text());
365
+ try std.testing.expectEqualStrings("the Chromium web engine", Declaration.chromium_engine.text());
366
+ }
@@ -722,8 +722,8 @@ test "chart golden: line + bar + band render byte-identically in light and dark"
722
722
  // category labels (q1, q3) under the bars. Both themes clear with their
723
723
  // background token. Update deliberately when chart rendering changes,
724
724
  // reviewing the dumped pixels first.
725
- const golden_light_signature: u64 = 11237334215963301158;
726
- const golden_dark_signature: u64 = 4053146140543071333;
725
+ const golden_light_signature: u64 = 4743613392161459263;
726
+ const golden_dark_signature: u64 = 13208780493823093371;
727
727
 
728
728
  fn goldenDumpRequested() bool {
729
729
  if (comptime !@import("builtin").link_libc) return false;
@@ -405,7 +405,7 @@ test "the README-shaped fixture renders through the mapper and the reference ren
405
405
  // separators, fenced-code panels, and near-black underlined links.
406
406
  // Update deliberately when markdown rendering changes, reviewing the
407
407
  // rendered pixels first (see reference_tests.zig conventions).
408
- const markdown_document_reference_signature: u64 = 6015448079037287912;
408
+ const markdown_document_reference_signature: u64 = 4124710367581899536;
409
409
 
410
410
 
411
411
  test "bare URLs autolink at word boundaries with trailing punctuation trimmed" {
@@ -225,9 +225,11 @@ pub const ReferenceRenderSurface = struct {
225
225
  }
226
226
 
227
227
  pub fn renderPass(self: ReferenceRenderSurface, pass: CanvasRenderPass, clear_color: Color) Error!void {
228
- // One-time sRGB decode table fill (see the table's doc comment);
229
- // outside the per-pixel loops so the hot path pays no checks.
228
+ // One-time sRGB decode/encode table fills (see the tables' doc
229
+ // comments); outside the per-pixel loops so the hot path pays no
230
+ // checks.
230
231
  ensureSrgbToLinearByteTable();
232
+ ensureLinearToSrgbTable();
231
233
  // Fresh per-pass panel-fill budget (see the memo's doc comment).
232
234
  if (self.render_memo) |memo| memo.image_scale_fills_this_pass = 0;
233
235
  const scale = referencePassScale(pass.scale);
@@ -309,7 +311,7 @@ pub const ReferenceRenderSurface = struct {
309
311
  continue;
310
312
  }
311
313
  const coverage = referenceRoundedRectCoverage(point, rect, radius);
312
- if (coverage > 0) self.blendPixel(@intCast(x), @intCast(y), referenceScaleColorAlpha(referenceSampleFill(value.fill, command.transform, point), coverage), command.opacity);
314
+ if (coverage > 0) self.blendPixelCoverage(@intCast(x), @intCast(y), referenceSampleFill(value.fill, command.transform, point), coverage, command.opacity, .linear_light);
313
315
  }
314
316
  }
315
317
  self.memoStore(probe, pixel_rect);
@@ -353,7 +355,7 @@ pub const ReferenceRenderSurface = struct {
353
355
  }
354
356
  const coverage = std.math.clamp(referenceRoundedRectCoverage(point, outer, outer_radius) - referenceRoundedRectCoverage(point, inner, inner_radius), 0, 1);
355
357
  if (coverage > 0) {
356
- self.blendPixel(@intCast(x), @intCast(y), referenceScaleColorAlpha(referenceSampleFill(value.stroke.fill, command.transform, point), coverage), command.opacity);
358
+ self.blendPixelCoverage(@intCast(x), @intCast(y), referenceSampleFill(value.stroke.fill, command.transform, point), coverage, command.opacity, .linear_light);
357
359
  }
358
360
  }
359
361
  }
@@ -389,6 +391,7 @@ pub const ReferenceRenderSurface = struct {
389
391
  .fill = value.fill,
390
392
  .transform = command.transform,
391
393
  .opacity = command.opacity,
394
+ .coverage_blend = .linear_light,
392
395
  };
393
396
  vector.fillPath(
394
397
  value.elements,
@@ -416,6 +419,7 @@ pub const ReferenceRenderSurface = struct {
416
419
  .fill = value.stroke.fill,
417
420
  .transform = command.transform,
418
421
  .opacity = command.opacity,
422
+ .coverage_blend = .linear_light,
419
423
  };
420
424
  vector.strokePath(
421
425
  value.elements,
@@ -823,11 +827,16 @@ pub const ReferenceRenderSurface = struct {
823
827
  if (builder.slice().len == 0) return true; // Space: nothing to ink.
824
828
 
825
829
  const pixel_rect = referencePixelRect(draw_bounds, self.width, self.height) orelse return true;
830
+ // Glyph coverage blends in sRGB, not linear light (see
831
+ // `CoverageBlend`): apparent text weight is set by how edge
832
+ // pixels darken, and re-blending them in linear light thins
833
+ // dark-on-light runs and blooms light-on-dark runs at UI sizes.
826
834
  var sink = ReferenceCoverageSink{
827
835
  .surface = self,
828
836
  .fill = .{ .color = value.color },
829
837
  .transform = command.transform,
830
838
  .opacity = command.opacity,
839
+ .coverage_blend = .srgb,
831
840
  };
832
841
  // The outline is already in device space; TrueType interiorness
833
842
  // is the nonzero rule.
@@ -869,18 +878,66 @@ pub const ReferenceRenderSurface = struct {
869
878
  self.pixels[index + 3] = out[3];
870
879
  }
871
880
 
881
+ /// Blend one pixel whose fractional alpha is ANTI-ALIASED EDGE
882
+ /// COVERAGE (kept separate from the color's own alpha so the blend
883
+ /// can tell an AA fringe from a translucent wash — see
884
+ /// `CoverageBlend`).
885
+ fn blendPixelCoverage(self: ReferenceRenderSurface, x: usize, y: usize, color: Color, coverage: f32, opacity: f32, blend: CoverageBlend) void {
886
+ const index = (y * self.width + x) * 4;
887
+ const dst = [4]u8{
888
+ self.pixels[index + 0],
889
+ self.pixels[index + 1],
890
+ self.pixels[index + 2],
891
+ self.pixels[index + 3],
892
+ };
893
+ const out = blendRgba8Coverage(dst, color, coverage, opacity, blend);
894
+ self.pixels[index + 0] = out[0];
895
+ self.pixels[index + 1] = out[1];
896
+ self.pixels[index + 2] = out[2];
897
+ self.pixels[index + 3] = out[3];
898
+ }
899
+
872
900
  fn findImage(self: ReferenceRenderSurface, id: ImageId) ?ReferenceImage {
873
901
  return findReferenceImage(self.images, id);
874
902
  }
875
903
  };
876
904
 
905
+ /// Which space a shape's fractional edge coverage blends in.
906
+ ///
907
+ /// GEOMETRY — rounded rects, filled/stroked paths, icons, chart marks —
908
+ /// blends its anti-aliased edge pixels in LINEAR LIGHT. Compositing the
909
+ /// sRGB-encoded bytes directly weights half coverage far below half the
910
+ /// light (a 50% black-on-white fringe lands near 21% luminance instead
911
+ /// of 50%), so every edge grows a dark rim on light backgrounds (a light
912
+ /// halo on dark ones) that reads as jagged even though the coverage
913
+ /// values are correct. Decoding to linear light, blending, and
914
+ /// re-encoding removes the rim.
915
+ ///
916
+ /// GLYPHS stay in sRGB. Text coverage funnels through the exact same
917
+ /// vector core, but apparent text WEIGHT is a product of how edge pixels
918
+ /// darken: the same coverage blended in linear light renders visibly
919
+ /// thinner dark-on-light runs and bloomier light-on-dark runs at UI
920
+ /// sizes, and the toolkit's type ramp was tuned against sRGB-blended
921
+ /// stems. sRGB glyph compositing also matches the packet-backed macOS
922
+ /// text pipeline, so mixed CPU/host frames keep one text weight.
923
+ ///
924
+ /// Only opaque-source fractional-coverage pixels differ between the two
925
+ /// modes: fully covered pixels short-circuit identically in either
926
+ /// space, and translucent sources (washes, scrims, faded layers) keep
927
+ /// sRGB blending so overlay brightness — tuned in sRGB terms — is
928
+ /// untouched and an AA edge never diverges from the interior it borders.
929
+ const CoverageBlend = enum { linear_light, srgb };
930
+
877
931
  /// Per-pixel coverage sink for the vector core: samples the fill at the
878
- /// pixel center and blends with the coverage folded into alpha.
932
+ /// pixel center and blends with the coverage, in the blend space the
933
+ /// emitter declared (geometry linear-light, glyphs sRGB — see
934
+ /// `CoverageBlend`).
879
935
  const ReferenceCoverageSink = struct {
880
936
  surface: ReferenceRenderSurface,
881
937
  fill: Fill,
882
938
  transform: Affine,
883
939
  opacity: f32,
940
+ coverage_blend: CoverageBlend,
884
941
 
885
942
  pub fn pixel(self: *ReferenceCoverageSink, x: i32, y: i32, coverage: f32) void {
886
943
  if (x < 0 or y < 0) return;
@@ -889,7 +946,7 @@ const ReferenceCoverageSink = struct {
889
946
  if (px >= self.surface.width or py >= self.surface.height) return;
890
947
  const point = referencePixelCenter(px, py);
891
948
  const color = referenceSampleFill(self.fill, self.transform, point);
892
- self.surface.blendPixel(px, py, referenceScaleColorAlpha(color, coverage), self.opacity);
949
+ self.surface.blendPixelCoverage(px, py, color, coverage, self.opacity, self.coverage_blend);
893
950
  }
894
951
  };
895
952
 
@@ -1339,6 +1396,31 @@ fn ensureSrgbToLinearByteTable() void {
1339
1396
  srgb_to_linear_byte_table_ready = true;
1340
1397
  }
1341
1398
 
1399
+ /// Precomputed `referenceLinearToSrgb` over evenly spaced linear inputs:
1400
+ /// the linear-light coverage blend re-encodes three channels per fringe
1401
+ /// pixel, and each direct encode costs a `pow`. 4096 entries keep the
1402
+ /// nearest-entry result within one 8-bit step of direct evaluation: the
1403
+ /// curve is steepest near black (slope 12.92), where one table cell
1404
+ /// still spans under one output byte step, so the looked-up value sits
1405
+ /// within half a step of exact and the final byte rounding moves by at
1406
+ /// most one level. Same benign-race lazy fill as the decode table above.
1407
+ const linear_to_srgb_table_len = 4096;
1408
+ var linear_to_srgb_table: [linear_to_srgb_table_len]f32 = undefined;
1409
+ var linear_to_srgb_table_ready: bool = false;
1410
+
1411
+ fn ensureLinearToSrgbTable() void {
1412
+ if (linear_to_srgb_table_ready) return;
1413
+ for (&linear_to_srgb_table, 0..) |*value, index| {
1414
+ value.* = referenceLinearToSrgb(@as(f32, @floatFromInt(index)) / (linear_to_srgb_table_len - 1));
1415
+ }
1416
+ linear_to_srgb_table_ready = true;
1417
+ }
1418
+
1419
+ fn referenceLinearToSrgbLut(value: f32) f32 {
1420
+ const index: usize = @intFromFloat(@round(std.math.clamp(value, 0, 1) * (linear_to_srgb_table_len - 1)));
1421
+ return linear_to_srgb_table[index];
1422
+ }
1423
+
1342
1424
  fn referencePremultiplySrgba8(pixel: [4]u8) ReferencePremultipliedLinearColor {
1343
1425
  const alpha = @as(f32, @floatFromInt(pixel[3])) / 255.0;
1344
1426
  return .{
@@ -1528,6 +1610,53 @@ fn blendRgba8(dst: [4]u8, src: Color, opacity: f32) [4]u8 {
1528
1610
  };
1529
1611
  }
1530
1612
 
1613
+ /// Source-over with the source's fractional alpha split into COLOR alpha
1614
+ /// and EDGE COVERAGE, so the blend space can key off what the alpha
1615
+ /// means (see `CoverageBlend`).
1616
+ ///
1617
+ /// Linear-light blending is reserved for the one case the split targets:
1618
+ /// an effectively opaque source's anti-aliased fringe. Everything else —
1619
+ /// sRGB-mode callers (glyphs), fully covered pixels, and translucent
1620
+ /// sources — folds coverage into alpha and takes the historical sRGB
1621
+ /// blend, byte for byte. That routing is also the cost story: interiors
1622
+ /// (`coverage >= 1`) and washes never pay a decode/encode round-trip, so
1623
+ /// the linear math runs only on the thin edge band, where the two table
1624
+ /// lookups per channel replace `pow` evaluations.
1625
+ fn blendRgba8Coverage(dst: [4]u8, src: Color, coverage: f32, opacity: f32, blend: CoverageBlend) [4]u8 {
1626
+ const cov = std.math.clamp(coverage, 0, 1);
1627
+ const src_a = std.math.clamp(src.a, 0, 1) * std.math.clamp(opacity, 0, 1);
1628
+ if (blend == .srgb or cov <= 0 or cov >= 1 or src_a < 1) {
1629
+ return blendRgba8(dst, referenceScaleColorAlpha(src, cov), opacity);
1630
+ }
1631
+
1632
+ // Belt over the renderPass-level fills for direct callers (unit
1633
+ // tests, future paths): two predictable branches per fringe pixel.
1634
+ ensureSrgbToLinearByteTable();
1635
+ ensureLinearToSrgbTable();
1636
+
1637
+ // Alpha stays in coverage space — it counts covered area, not light
1638
+ // — so the alpha math is IDENTICAL to the sRGB path; only the color
1639
+ // channels decode to linear light. `out_a >= cov > 0` here, so the
1640
+ // straight-alpha un-premultiply divide is safe. The source decodes
1641
+ // through the same byte quantization its coverage-1 pixels store,
1642
+ // so a fringe converges exactly onto the interior bytes it borders.
1643
+ const dst_a = @as(f32, @floatFromInt(dst[3])) / 255.0;
1644
+ const out_a = cov + dst_a * (1 - cov);
1645
+ const src_r = srgb_to_linear_byte_table[colorChannelToByte(src.r)];
1646
+ const src_g = srgb_to_linear_byte_table[colorChannelToByte(src.g)];
1647
+ const src_b = srgb_to_linear_byte_table[colorChannelToByte(src.b)];
1648
+ const dst_r = srgb_to_linear_byte_table[dst[0]];
1649
+ const dst_g = srgb_to_linear_byte_table[dst[1]];
1650
+ const dst_b = srgb_to_linear_byte_table[dst[2]];
1651
+ const dst_weight = dst_a * (1 - cov);
1652
+ return .{
1653
+ colorChannelToByte(referenceLinearToSrgbLut((src_r * cov + dst_r * dst_weight) / out_a)),
1654
+ colorChannelToByte(referenceLinearToSrgbLut((src_g * cov + dst_g * dst_weight) / out_a)),
1655
+ colorChannelToByte(referenceLinearToSrgbLut((src_b * cov + dst_b * dst_weight) / out_a)),
1656
+ colorChannelToByte(out_a),
1657
+ };
1658
+ }
1659
+
1531
1660
  fn colorChannelToByte(value: f32) u8 {
1532
1661
  return @intFromFloat(@round(std.math.clamp(value, 0, 1) * 255.0));
1533
1662
  }