@native-sdk/cli 0.5.2 → 0.5.3

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 (82) hide show
  1. package/build.zig +41 -0
  2. package/package.json +9 -9
  3. package/packages/core/package-lock.json +2 -2
  4. package/packages/core/package.json +1 -1
  5. package/packages/core/sdk/events.ts +39 -2
  6. package/packages/core/src/checker.ts +1 -1
  7. package/packages/core/src/emitter.ts +39 -3
  8. package/packages/core/src/infer.ts +53 -7
  9. package/skill-data/automation/SKILL.md +7 -4
  10. package/skill-data/core/references/app-model-runtime.md +3 -0
  11. package/skill-data/native-ui/SKILL.md +1 -0
  12. package/src/app_runner/root.zig +25 -0
  13. package/src/automation/protocol.zig +20 -1
  14. package/src/embed/host.zig +27 -0
  15. package/src/embed/tests.zig +69 -0
  16. package/src/embed/ui_host.zig +4 -0
  17. package/src/platform/macos/appkit_host.h +11 -0
  18. package/src/platform/macos/appkit_host.m +130 -0
  19. package/src/platform/macos/root.zig +34 -0
  20. package/src/platform/null_platform_tests.zig +39 -0
  21. package/src/platform/root.zig +3 -0
  22. package/src/platform/types.zig +109 -4
  23. package/src/primitives/canvas/chart.zig +7 -7
  24. package/src/primitives/canvas/chart_tests.zig +66 -0
  25. package/src/primitives/canvas/commands.zig +48 -0
  26. package/src/primitives/canvas/events.zig +161 -0
  27. package/src/primitives/canvas/font_ttf.zig +155 -8
  28. package/src/primitives/canvas/font_ttf_tests.zig +686 -0
  29. package/src/primitives/canvas/reference.zig +67 -8
  30. package/src/primitives/canvas/render_fingerprints.zig +8 -0
  31. package/src/primitives/canvas/root.zig +25 -0
  32. package/src/primitives/canvas/ui.zig +35 -2
  33. package/src/primitives/canvas/ui_markup.zig +24 -0
  34. package/src/primitives/canvas/ui_markup_binary_tests.zig +25 -0
  35. package/src/primitives/canvas/ui_markup_compiled.zig +40 -3
  36. package/src/primitives/canvas/ui_markup_compiled_tests.zig +33 -0
  37. package/src/primitives/canvas/ui_markup_contract.zig +9 -0
  38. package/src/primitives/canvas/ui_markup_contract_tests.zig +24 -0
  39. package/src/primitives/canvas/ui_markup_tests.zig +26 -0
  40. package/src/primitives/canvas/ui_markup_view.zig +53 -4
  41. package/src/primitives/canvas/ui_markup_view_tests.zig +73 -2
  42. package/src/primitives/canvas/ui_schema.zig +16 -0
  43. package/src/primitives/canvas/ui_schema_tests.zig +10 -11
  44. package/src/primitives/canvas/ui_tests.zig +31 -0
  45. package/src/primitives/canvas/vector.zig +258 -141
  46. package/src/primitives/canvas/widget_access.zig +1 -1
  47. package/src/primitives/canvas/widget_builtin_tests.zig +129 -0
  48. package/src/primitives/canvas/widget_layout.zig +9 -4
  49. package/src/primitives/canvas/widget_render.zig +78 -40
  50. package/src/primitives/canvas/widget_render_controls.zig +15 -4
  51. package/src/primitives/canvas/widget_semantics.zig +6 -1
  52. package/src/primitives/canvas/widget_semantics_tests.zig +168 -0
  53. package/src/primitives/canvas/widget_text_input.zig +118 -10
  54. package/src/primitives/canvas/widgets.zig +16 -0
  55. package/src/root.zig +5 -0
  56. package/src/runtime/api.zig +13 -0
  57. package/src/runtime/automation_commands.zig +33 -0
  58. package/src/runtime/automation_widget_dispatch.zig +64 -0
  59. package/src/runtime/canvas_font_tests.zig +272 -3
  60. package/src/runtime/canvas_fonts.zig +60 -20
  61. package/src/runtime/canvas_frame_helpers.zig +15 -0
  62. package/src/runtime/canvas_image_tests.zig +26 -0
  63. package/src/runtime/canvas_images.zig +33 -7
  64. package/src/runtime/canvas_limits.zig +44 -8
  65. package/src/runtime/canvas_widget_clipboard_tests.zig +123 -0
  66. package/src/runtime/canvas_widget_context_menu_tests.zig +55 -0
  67. package/src/runtime/canvas_widget_events.zig +24 -4
  68. package/src/runtime/canvas_widget_runtime.zig +24 -7
  69. package/src/runtime/canvas_widget_state.zig +6 -1
  70. package/src/runtime/canvas_widget_text_tests.zig +277 -0
  71. package/src/runtime/core.zig +98 -6
  72. package/src/runtime/flow.zig +27 -0
  73. package/src/runtime/gpu_surface_events.zig +7 -0
  74. package/src/runtime/media_surface.zig +726 -0
  75. package/src/runtime/media_surface_tests.zig +1476 -0
  76. package/src/runtime/root.zig +9 -0
  77. package/src/runtime/session_journal.zig +30 -3
  78. package/src/runtime/session_tests.zig +126 -4
  79. package/src/runtime/tests.zig +1 -0
  80. package/src/runtime/ts_ui_app.zig +56 -0
  81. package/src/runtime/ui_app.zig +58 -0
  82. package/src/runtime/ui_app_tests.zig +334 -0
@@ -133,6 +133,21 @@ pub const WidgetKind = enum {
133
133
  /// never double-draw. Not a hit target itself: the textarea fills the
134
134
  /// group's body, so a click "in the field" IS a click in the textarea.
135
135
  input_group,
136
+ /// The media surface leaf: composites a texture PRODUCED OUTSIDE the
137
+ /// widget tree (a video decoder, a camera pipeline, an external
138
+ /// renderer) into the layout like any widget — clipped, z-ordered,
139
+ /// transformed. `image_id` carries the SURFACE id the producer
140
+ /// targets (`Runtime.acquireMediaSurfaceProducer`), a model-owned
141
+ /// u64 in the ImageId value space; 0 is the unbound sentinel, and
142
+ /// usable ids are nonzero values below the reserved namespace bit
143
+ /// (`media_surface_image_id_bit`, refused at acquire).
144
+ /// Display-only like `image` and `chart`: not a hit target, presses
145
+ /// fall through to the nearest pressable ancestor. Texture CONTENTS
146
+ /// are presentation chrome — the deterministic reference renderer
147
+ /// draws the surface's id-derived placeholder instead (see
148
+ /// `ReferenceImage.presentation_only`), so goldens and session
149
+ /// fingerprints never depend on producer output.
150
+ media_surface,
136
151
  };
137
152
 
138
153
  /// STABLE code for a widget kind: assigned at birth, never reused or
@@ -210,6 +225,7 @@ pub fn widgetKindCode(kind: WidgetKind) u16 {
210
225
  .split_divider => 58,
211
226
  .tree => 59,
212
227
  .input_group => 60,
228
+ .media_surface => 61,
213
229
  };
214
230
  }
215
231
 
package/src/root.zig CHANGED
@@ -93,6 +93,9 @@ pub const setFreestandingMonotonicNanoseconds = runtime.setFreestandingMonotonic
93
93
  pub const RegisteredImage = runtime.RegisteredImage;
94
94
  pub const max_registered_canvas_images = runtime.max_registered_canvas_images;
95
95
  pub const max_registered_canvas_image_pixel_bytes = runtime.max_registered_canvas_image_pixel_bytes;
96
+ pub const MediaSurfaceProducer = runtime.MediaSurfaceProducer;
97
+ pub const max_media_surface_channels = runtime.max_media_surface_channels;
98
+ pub const max_media_surface_pixel_bytes = runtime.max_media_surface_pixel_bytes;
96
99
  pub const ShellConfig = app_manifest.ShellConfig;
97
100
  pub const ShellWindow = app_manifest.ShellWindow;
98
101
  pub const ShellView = app_manifest.ShellView;
@@ -147,6 +150,8 @@ pub const GpuSurfaceFrameEvent = platform.GpuSurfaceFrameEvent;
147
150
  pub const GpuSurfaceResizeEvent = platform.GpuSurfaceResizeEvent;
148
151
  pub const GpuSurfaceInputKind = platform.GpuSurfaceInputKind;
149
152
  pub const GpuSurfaceInputEvent = platform.GpuSurfaceInputEvent;
153
+ pub const PinchPhase = platform.PinchPhase;
154
+ pub const PinchEvent = platform.PinchEvent;
150
155
  pub const FileFilter = platform.FileFilter;
151
156
  pub const OpenDialogOptions = platform.OpenDialogOptions;
152
157
  pub const OpenDialogResult = platform.OpenDialogResult;
@@ -384,6 +384,19 @@ pub fn App(comptime Runtime: type) type {
384
384
 
385
385
  pub const Options = struct {
386
386
  platform: platform.Platform,
387
+ /// Allocator for the runtime's on-demand storage (registered
388
+ /// canvas font bytes, sized per file at registration, and adopted
389
+ /// media-surface texture buffers, one frame-budget buffer per
390
+ /// texture entry allocated at first adoption — a runtime with no
391
+ /// registered fonts and no media producers allocates nothing; the
392
+ /// fixed-capacity per-view storage stays embedded in the Runtime
393
+ /// struct). The default suits process-lifetime runtimes; embedders
394
+ /// that create and destroy runtimes in one process (tests, the docs
395
+ /// wasm preview host) pass their own and call `Runtime.deinit`. The
396
+ /// runtime captures this into its `owned_allocator` at init:
397
+ /// mutating `options.allocator` on a live runtime retargets
398
+ /// nothing — pick the owning allocator here, before init.
399
+ allocator: std.mem.Allocator = std.heap.page_allocator,
387
400
  trace_sink: ?trace.Sink = null,
388
401
  log_path: ?[]const u8 = null,
389
402
  extensions: ?extensions.ModuleRegistry = null,
@@ -58,6 +58,21 @@ pub const AutomationWidgetKey = struct {
58
58
  modifiers: AutomationKeyModifiers = .{},
59
59
  };
60
60
 
61
+ /// `widget-pinch <view-label> <scale> [<x> <y>]`: a trackpad pinch
62
+ /// gesture against a gpu-surface view. `scale` is the FINAL
63
+ /// multiplicative zoom for the gesture (1.5 zooms in 50%, 0.5 zooms out
64
+ /// to half) — the dispatch synthesizes begin, one change carrying
65
+ /// `scale - 1`, and end, so the product of `(1 + delta)` lands exactly
66
+ /// on `scale`. The optional
67
+ /// anchor point is view-local canvas points (where the zoom anchors,
68
+ /// like the pointer position under a real pinch); omitted, it defaults
69
+ /// to the view center.
70
+ pub const AutomationWidgetPinch = struct {
71
+ view_label: []const u8,
72
+ scale: f32,
73
+ point: ?geometry.PointF = null,
74
+ };
75
+
61
76
  /// Modifier chord for automation key dispatch, mirroring
62
77
  /// `platform.ShortcutModifiers` field-for-field (automation stays
63
78
  /// platform-agnostic; the dispatch layer copies these across).
@@ -261,6 +276,24 @@ pub fn parseAutomationWidgetKey(value: []const u8) !AutomationWidgetKey {
261
276
  return .{ .view_label = view.token, .key = chord.key, .text = text, .modifiers = chord.modifiers };
262
277
  }
263
278
 
279
+ pub fn parseAutomationWidgetPinch(value: []const u8) !AutomationWidgetPinch {
280
+ const view = takeAutomationToken(value) orelse return error.InvalidCommand;
281
+ const scale_part = takeAutomationToken(view.rest) orelse return error.InvalidCommand;
282
+ const scale = std.fmt.parseFloat(f32, scale_part.token) catch return error.InvalidCommand;
283
+ // A non-positive cumulative scale is not a gesture two fingers can
284
+ // perform (the product of 1 + delta stays positive); refuse loudly.
285
+ if (!std.math.isFinite(scale) or scale <= 0) return error.InvalidCommand;
286
+ const x_part = takeAutomationToken(scale_part.rest) orelse {
287
+ return .{ .view_label = view.token, .scale = scale };
288
+ };
289
+ const y_part = takeAutomationToken(x_part.rest) orelse return error.InvalidCommand;
290
+ if (takeAutomationToken(y_part.rest) != null) return error.InvalidCommand;
291
+ const x = std.fmt.parseFloat(f32, x_part.token) catch return error.InvalidCommand;
292
+ const y = std.fmt.parseFloat(f32, y_part.token) catch return error.InvalidCommand;
293
+ if (!std.math.isFinite(x) or !std.math.isFinite(y)) return error.InvalidCommand;
294
+ return .{ .view_label = view.token, .scale = scale, .point = geometry.PointF.init(x, y) };
295
+ }
296
+
264
297
  pub fn parseAutomationWidgetPointerDrag(value: []const u8) !AutomationWidgetPointerDrag {
265
298
  const view = takeAutomationToken(value) orelse return error.InvalidCommand;
266
299
  const id_part = takeAutomationToken(view.rest) orelse return error.InvalidCommand;
@@ -284,6 +284,70 @@ pub fn RuntimeAutomationWidgetDispatch(comptime Runtime: type) type {
284
284
  } });
285
285
  }
286
286
 
287
+ /// Drive a trackpad pinch through the real platform-event path:
288
+ /// `pinch_begin`, one `pinch_change` carrying `scale - 1` (so
289
+ /// the cumulative product of `1 + delta` lands exactly on the
290
+ /// commanded scale — the gesture's FINAL multiplicative zoom),
291
+ /// and `pinch_end`, all at the same anchor point. A scale so
292
+ /// small its f32 delta rounds to -1 (factor 0 on the wire) is
293
+ /// refused as `PinchScaleBelowWireMinimum` — see the guard
294
+ /// below for the named minimum.
295
+ /// Plain input synthesis, the `widget-key` discipline: every
296
+ /// event journals as itself and replays through the same
297
+ /// dispatch — no accessibility-action record, because pinch is
298
+ /// not a widget verb (it never routes into the widget tree; the
299
+ /// app hears it through the pinch channel).
300
+ pub fn dispatchAutomationWidgetPinch(self: *Runtime, app: runtime_api.App(Runtime), pinch: automation_commands.AutomationWidgetPinch) anyerror!void {
301
+ const view_index = try automationGpuSurfaceViewIndexByLabel(self, pinch.view_label);
302
+ const window_id = self.views[view_index].window_id;
303
+ const label = self.views[view_index].label;
304
+ const point = pinch.point orelse geometry.PointF.init(
305
+ self.views[view_index].gpu_size.width / 2,
306
+ self.views[view_index].gpu_size.height / 2,
307
+ );
308
+ // The wire delta is `scale - 1` in f32, and f32 rounding can
309
+ // betray the parser's `scale > 0` guard: any scale at or
310
+ // below 2^-25 rounds the difference to exactly -1
311
+ // (ties-to-even at the halfway point), which would put the
312
+ // factor `1 + delta = 0` on the wire — a zoom through zero
313
+ // scale, which no gesture can perform and no downstream
314
+ // product can recover from. The invariant is the WIRE's
315
+ // (every emitted factor stays > 0), so validate the computed
316
+ // delta, not the input; the minimum accepted scale is the
317
+ // smallest f32 above 2^-25 (~2.9802326e-8), whose delta
318
+ // rounds to -1 + 2^-24 — the smallest positive factor the
319
+ // wire can carry. Refused before anything dispatches, so no
320
+ // partial gesture reaches the journal.
321
+ const delta = pinch.scale - 1;
322
+ if (1 + delta <= 0) return error.PinchScaleBelowWireMinimum;
323
+ const timestamp_ns = automationInputTimestampNs();
324
+ try self.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
325
+ .window_id = window_id,
326
+ .label = label,
327
+ .kind = .pinch_begin,
328
+ .timestamp_ns = timestamp_ns,
329
+ .x = point.x,
330
+ .y = point.y,
331
+ } });
332
+ try self.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
333
+ .window_id = window_id,
334
+ .label = label,
335
+ .kind = .pinch_change,
336
+ .timestamp_ns = timestamp_ns,
337
+ .x = point.x,
338
+ .y = point.y,
339
+ .scale = delta,
340
+ } });
341
+ try self.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
342
+ .window_id = window_id,
343
+ .label = label,
344
+ .kind = .pinch_end,
345
+ .timestamp_ns = timestamp_ns,
346
+ .x = point.x,
347
+ .y = point.y,
348
+ } });
349
+ }
350
+
287
351
  pub fn dispatchAutomationWidgetPointerDrag(self: *Runtime, app: runtime_api.App(Runtime), drag: AutomationWidgetPointerDrag) anyerror!void {
288
352
  const view_index = try automationWidgetTargetViewIndex(self, drag.target);
289
353
  const layout = self.views[view_index].widgetLayoutTree();
@@ -1,8 +1,11 @@
1
1
  //! Runtime canvas font registry tests: registration validation and
2
2
  //! capacity bounds (loud, one-past-budget), hostile/truncated font
3
- //! files, the font-aware measure provider, pixel parity between the
4
- //! present path and the reference screenshot path for a registered
5
- //! face, and the UiApp `Options.fonts` startup seam.
3
+ //! files, the registration-time glyph-budget gate (over-declaring
4
+ //! `maxp` refused whole; the real Noto Sans JP accepted and outlining
5
+ //! dense kanji when the /tmp fixture is present), the font-aware
6
+ //! measure provider, pixel parity between the present path and the
7
+ //! reference screenshot path for a registered face, and the UiApp
8
+ //! `Options.fonts` startup seam.
6
9
  //!
7
10
  //! The registered fixture is the ALREADY-BUNDLED Geist Mono bytes
8
11
  //! (`canvas.font_ttf.geist_mono_bytes`) under a registered id: the
@@ -86,6 +89,75 @@ test "canvas font registry validates ids, bytes, and capacity" {
86
89
  try std.testing.expectEqual(registered_font_id, resources[0].id);
87
90
  }
88
91
 
92
+ test "a fresh runtime allocates zero font bytes until a registration happens" {
93
+ const harness = try startedGpuHarness(std.testing.allocator);
94
+ defer harness.destroy(std.testing.allocator);
95
+ var app_state: RegistryApp = .{};
96
+
97
+ // Count every runtime-allocator call: construction, startup, and
98
+ // frames perform NONE — font byte storage is on-demand at
99
+ // registration, so a fontless runtime carries zero font bytes. (The
100
+ // regression pinned here: a reservation-shaped slot pool at the
101
+ // 24 MiB CJK bound embedded 192 MiB in every Runtime, doubling the
102
+ // docs wasm preview host's per-tile memory before any font existed.)
103
+ // The ownership allocator is frozen at init, so the test re-freezes
104
+ // the field directly — equivalent to constructing with the counting
105
+ // allocator, and safe exactly because no owned bytes exist yet.
106
+ var counting = std.testing.FailingAllocator.init(std.testing.allocator, .{});
107
+ harness.runtime.owned_allocator = counting.allocator();
108
+ try harness.start(app_state.app());
109
+ try std.testing.expectEqual(@as(usize, 0), counting.allocations);
110
+
111
+ // Even an allocator that refuses everything leaves the runtime
112
+ // fully operational until a registration demands memory — and that
113
+ // failure is loud and recoverable, never a partial slot. (Still
114
+ // nothing owned, so re-freezing stays equivalent to init capture.)
115
+ var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });
116
+ harness.runtime.owned_allocator = failing.allocator();
117
+ try std.testing.expectError(error.OutOfMemory, harness.runtime.registerCanvasFont(registered_font_id, mono_bytes));
118
+ try std.testing.expectEqual(@as(usize, 0), harness.runtime.registeredCanvasFontCount());
119
+
120
+ // Registration is the first allocation: exactly one, exactly the
121
+ // file's size (freed by Runtime.deinit through harness.destroy —
122
+ // the leak-checked test allocator backs it).
123
+ harness.runtime.owned_allocator = counting.allocator();
124
+ try harness.runtime.registerCanvasFont(registered_font_id, mono_bytes);
125
+ try std.testing.expectEqual(@as(usize, 1), counting.allocations);
126
+ try std.testing.expectEqual(mono_bytes.len, counting.allocated_bytes);
127
+ }
128
+
129
+ test "deinit frees font bytes through the init-frozen allocator even after options.allocator is mutated" {
130
+ const harness = try startedGpuHarness(std.testing.allocator);
131
+ defer harness.destroy(std.testing.allocator);
132
+ var app_state: RegistryApp = .{};
133
+ try harness.start(app_state.app());
134
+
135
+ // Freeze a counting allocator as the runtime's owner (equivalent to
136
+ // constructing with it — nothing is owned yet) and register a face
137
+ // through it.
138
+ var counting = std.testing.FailingAllocator.init(std.testing.allocator, .{});
139
+ harness.runtime.owned_allocator = counting.allocator();
140
+ try harness.runtime.registerCanvasFont(registered_font_id, mono_bytes);
141
+ try std.testing.expectEqual(@as(usize, 1), counting.allocations);
142
+ try std.testing.expectEqual(@as(usize, 0), counting.deallocations);
143
+
144
+ // The hazard under test: `Runtime.options` is public and mutable, so
145
+ // an embedder can swap `options.allocator` AFTER fonts registered.
146
+ // Ownership must not retarget — the deinit free has to hit the
147
+ // allocator that made the bytes, not whatever the option points at
148
+ // by teardown time.
149
+ var mutated = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });
150
+ harness.runtime.options.allocator = mutated.allocator();
151
+ harness.runtime.deinit();
152
+
153
+ // Counts balance on the original identity; the mutated allocator
154
+ // saw zero activity in either direction.
155
+ try std.testing.expectEqual(counting.allocations, counting.deallocations);
156
+ try std.testing.expectEqual(counting.allocated_bytes, counting.freed_bytes);
157
+ try std.testing.expectEqual(@as(usize, 0), mutated.allocations);
158
+ try std.testing.expectEqual(@as(usize, 0), mutated.deallocations);
159
+ }
160
+
89
161
  test "hostile and truncated font files fail loud at registration and never corrupt the registry" {
90
162
  const harness = try startedGpuHarness(std.testing.allocator);
91
163
  defer harness.destroy(std.testing.allocator);
@@ -199,6 +271,167 @@ test "registered faces answer the batched advances seam identically to per-prefi
199
271
  }
200
272
  }
201
273
 
274
+ /// Byte offset of the `maxp` table in a TrueType file (test fixture
275
+ /// helper for building over-declaring faces out of the bundled bytes).
276
+ fn maxpTableOffset(bytes: []const u8) usize {
277
+ const table_count = std.mem.readInt(u16, bytes[4..6], .big);
278
+ var index: usize = 0;
279
+ while (index < table_count) : (index += 1) {
280
+ const record = 12 + index * 16;
281
+ if (std.mem.eql(u8, bytes[record .. record + 4], "maxp")) {
282
+ return std.mem.readInt(u32, bytes[record + 8 ..][0..4], .big);
283
+ }
284
+ }
285
+ unreachable; // the bundled faces always carry maxp
286
+ }
287
+
288
+ /// The bundled mono bytes with `maxp.maxPoints` patched one past the
289
+ /// glyph-point budget: a face that DECLARES denser glyphs than the
290
+ /// outline pipeline's budgets and must be refused whole at
291
+ /// registration, never degraded per glyph at render time.
292
+ fn overBudgetFontBytes(allocator: std.mem.Allocator) ![]u8 {
293
+ const patched = try allocator.dupe(u8, mono_bytes);
294
+ const maxp = maxpTableOffset(patched);
295
+ std.mem.writeInt(u16, patched[maxp + 6 ..][0..2], @intCast(canvas.font_ttf.max_glyph_points + 1), .big);
296
+ return patched;
297
+ }
298
+
299
+ /// The bundled mono bytes with `maxp.maxCompositePoints` (offset 10)
300
+ /// patched one past the flattened-composite budget: modest simple
301
+ /// maxima, composite flattening the path builder could not hold — the
302
+ /// exact face shape a simple-only gate would admit and then silently
303
+ /// block at render time.
304
+ fn overCompositeBudgetFontBytes(allocator: std.mem.Allocator) ![]u8 {
305
+ const patched = try allocator.dupe(u8, mono_bytes);
306
+ const maxp = maxpTableOffset(patched);
307
+ std.mem.writeInt(u16, patched[maxp + 10 ..][0..2], @intCast(canvas.font_ttf.max_composite_points + 1), .big);
308
+ return patched;
309
+ }
310
+
311
+ test "a face declaring glyphs denser than the budgets is refused at registration" {
312
+ const harness = try startedGpuHarness(std.testing.allocator);
313
+ defer harness.destroy(std.testing.allocator);
314
+ var app_state: RegistryApp = .{};
315
+ try harness.start(app_state.app());
316
+
317
+ const patched = try overBudgetFontBytes(std.testing.allocator);
318
+ defer std.testing.allocator.free(patched);
319
+
320
+ try std.testing.expectError(error.FontExceedsGlyphBudgets, harness.runtime.registerCanvasFont(registered_font_id, patched));
321
+ try std.testing.expectEqual(@as(usize, 0), harness.runtime.registeredCanvasFontCount());
322
+
323
+ // The teaching machinery names the refusal: parse-reason carries the
324
+ // budget sentence, and the declared maxima expose the face's own
325
+ // numbers for callers that format (UiApp's fonts teaching).
326
+ try std.testing.expect(std.mem.indexOf(u8, canvas.font_ttf.parseFailureReason(patched).?, "budgets") != null);
327
+ const maxima = canvas.font_ttf.declaredGlyphMaxima(patched).?;
328
+ try std.testing.expectEqual(@as(u16, @intCast(canvas.font_ttf.max_glyph_points + 1)), maxima.points);
329
+ try std.testing.expect(!maxima.withinBudgets());
330
+
331
+ // No partial slot: the honest twin registers under the same id.
332
+ try harness.runtime.registerCanvasFont(registered_font_id, mono_bytes);
333
+ try std.testing.expectEqual(@as(usize, 1), harness.runtime.registeredCanvasFontCount());
334
+ }
335
+
336
+ test "a face declaring flattened composites denser than the budgets is refused at registration" {
337
+ const harness = try startedGpuHarness(std.testing.allocator);
338
+ defer harness.destroy(std.testing.allocator);
339
+ var app_state: RegistryApp = .{};
340
+ try harness.start(app_state.app());
341
+
342
+ // Simple maxima untouched (well within budget) — only the
343
+ // flattened-composite declaration is over. A gate reading simple
344
+ // maxima alone admits this face; its composites then overflow the
345
+ // reference path builder at render time and degrade to blocks, the
346
+ // exact silent failure registration-time validation forbids.
347
+ const patched = try overCompositeBudgetFontBytes(std.testing.allocator);
348
+ defer std.testing.allocator.free(patched);
349
+
350
+ try std.testing.expectError(error.FontExceedsGlyphBudgets, harness.runtime.registerCanvasFont(registered_font_id, patched));
351
+ try std.testing.expectEqual(@as(usize, 0), harness.runtime.registeredCanvasFontCount());
352
+
353
+ // The teaching names the composite budgets and the declared maxima
354
+ // expose the face's own composite numbers.
355
+ const reason = canvas.font_ttf.parseFailureReason(patched).?;
356
+ try std.testing.expect(std.mem.indexOf(u8, reason, "flattened composite") != null);
357
+ const maxima = canvas.font_ttf.declaredGlyphMaxima(patched).?;
358
+ try std.testing.expectEqual(@as(u16, @intCast(canvas.font_ttf.max_composite_points + 1)), maxima.composite_points);
359
+ try std.testing.expect(!maxima.withinBudgets());
360
+
361
+ // The unpatched twin registers: the gate reads the declaration, not
362
+ // the patch's collateral.
363
+ try harness.runtime.registerCanvasFont(registered_font_id, mono_bytes);
364
+ try std.testing.expectEqual(@as(usize, 1), harness.runtime.registeredCanvasFontCount());
365
+ }
366
+
367
+ test "the real Noto Sans JP face registers and outlines dense kanji (guarded by /tmp/NotoSansJP.ttf)" {
368
+ // Ground-truth end-to-end proof with the face the budgets were
369
+ // sized from: the Google Fonts TrueType build of Noto Sans JP
370
+ // (OFL). Font binaries stay out of the repo, so the fixture is a
371
+ // local download; environments without it skip.
372
+ const bytes = std.Io.Dir.cwd().readFileAlloc(
373
+ std.testing.io,
374
+ "/tmp/NotoSansJP.ttf",
375
+ std.testing.allocator,
376
+ .limited(canvas_limits.max_registered_canvas_font_bytes),
377
+ ) catch return error.SkipZigTest;
378
+ defer std.testing.allocator.free(bytes);
379
+
380
+ const harness = try startedGpuHarness(std.testing.allocator);
381
+ defer harness.destroy(std.testing.allocator);
382
+ var app_state: RegistryApp = .{};
383
+ try harness.start(app_state.app());
384
+
385
+ // Registration passes the byte bound, the maxp gate, and the host
386
+ // seam — the whole registration-time validation doctrine.
387
+ try harness.runtime.registerCanvasFont(registered_font_id, bytes);
388
+ const face = harness.runtime.registeredCanvasFontFace(registered_font_id).?;
389
+
390
+ // Everyday-dense kanji resolve to real outlines, not notdef blocks:
391
+ // 鬱 U+9B31 measures 237 points / 26 contours in this face — far
392
+ // past the old Latin-sized 128-point/24-contour budgets that made
393
+ // it render as a block.
394
+ const dense_kanji = [_]u21{ 0x9B31, 0x9A5A, 0x7C60, 0x9451 }; // 鬱 驚 籠 鑑
395
+ for (dense_kanji) |codepoint| {
396
+ const glyph = face.glyphIndex(codepoint);
397
+ try std.testing.expect(glyph != 0);
398
+ var builder = canvas.vector.PathBuilder(2048){};
399
+ try face.glyphOutline(glyph, canvas.Affine.identity(), &builder);
400
+ try std.testing.expect(builder.slice().len > 0);
401
+ }
402
+
403
+ // The dense outline rasterizes within the vector budgets at body
404
+ // and headline sizes.
405
+ const InkCounter = struct {
406
+ covered: usize = 0,
407
+ pub fn pixel(self: *@This(), x: i32, y: i32, coverage: f32) void {
408
+ _ = x;
409
+ _ = y;
410
+ if (coverage > 0) self.covered += 1;
411
+ }
412
+ };
413
+ for ([_]f32{ 16, 96 }) |size| {
414
+ const glyph = face.glyphIndex(0x9B31);
415
+ const scale = size / face.units_per_em;
416
+ var builder = canvas.vector.PathBuilder(2048){};
417
+ try face.glyphOutline(glyph, .{ .a = scale, .b = 0, .c = 0, .d = -scale, .tx = 4, .ty = size }, &builder);
418
+ var counter = InkCounter{};
419
+ try canvas.vector.fillPath(
420
+ builder.slice(),
421
+ canvas.Affine.identity(),
422
+ .nonzero,
423
+ canvas.vector.default_tolerance,
424
+ .{ .x0 = 0, .y0 = 0, .x1 = 128, .y1 = 128 },
425
+ &counter,
426
+ );
427
+ try std.testing.expect(counter.covered > 0);
428
+ }
429
+
430
+ // Layout measures the registered face's own advances for the kanji.
431
+ const provider = harness.runtime.textMeasureProvider().?;
432
+ try std.testing.expect(provider.measureWidth(registered_font_id, 16.0, "鬱") > 0);
433
+ }
434
+
202
435
  fn installFontFixtureWidgets(harness: anytype) !void {
203
436
  _ = try harness.runtime.createView(.{
204
437
  .window_id = 1,
@@ -408,3 +641,39 @@ test "ui app declared font failures are teaching errors, not crashes or silent f
408
641
  try std.testing.expect(app_state.installed);
409
642
  try std.testing.expectEqual(first_errors, harness.runtime.dispatchErrorTotal());
410
643
  }
644
+
645
+ test "ui app fonts option surfaces the glyph-budget refusal as a teaching error" {
646
+ const harness = try TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(240, 200) });
647
+ defer harness.destroy(std.testing.allocator);
648
+ harness.null_platform.gpu_surfaces = true;
649
+
650
+ const patched = try overBudgetFontBytes(std.testing.allocator);
651
+ defer std.testing.allocator.free(patched);
652
+
653
+ const fonts = [_]FontApp.FontRegistration{.{
654
+ .id = registered_font_id,
655
+ .name = "TooDense.ttf",
656
+ .ttf = patched,
657
+ }};
658
+ const app_state = try std.testing.allocator.create(FontApp);
659
+ defer std.testing.allocator.destroy(app_state);
660
+ app_state.* = FontApp.init(std.testing.allocator, .{}, fontAppOptions(&fonts));
661
+ defer app_state.deinit();
662
+ const app = app_state.app();
663
+ try harness.start(app);
664
+ harness.runtime.dispatch_error_policy = .degrade;
665
+
666
+ // The installing frame surfaces the refusal through the dispatch
667
+ // error channel (the warn log names the face's declared maxima
668
+ // against the budgets); nothing registers, the app stays alive.
669
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
670
+ .label = font_app_canvas_label,
671
+ .size = geometry.SizeF.init(240, 200),
672
+ .scale_factor = 1,
673
+ .frame_index = 1,
674
+ .timestamp_ns = 1_000_000,
675
+ .nonblank = true,
676
+ } });
677
+ try std.testing.expectEqual(@as(usize, 0), harness.runtime.registeredCanvasFontCount());
678
+ try std.testing.expect(harness.runtime.dispatchErrorTotal() > 0);
679
+ }
@@ -7,12 +7,18 @@
7
7
  //!
8
8
  //! Validation is loud and registration-time only: the bytes must parse as
9
9
  //! a TrueType face (`canvas.font_ttf.Face.parse`) under the registry
10
- //! bounds, or registration fails with a recoverable error — a registered
11
- //! id therefore ALWAYS resolves at render time, and the only per-glyph
10
+ //! bounds — including the glyph-outline budget gate on the face's
11
+ //! declared `maxp` maxima (`error.FontExceedsGlyphBudgets` when a face
12
+ //! declares denser glyphs than `canvas.font_ttf`'s budgets; the budgets
13
+ //! are sized from real CJK faces, so this refuses only outliers) — or
14
+ //! registration fails with a recoverable error. A registered id
15
+ //! therefore ALWAYS resolves at render time, and the only per-glyph
12
16
  //! fallback is the same notdef block built-in faces use for codepoints a
13
17
  //! face does not cover. `canvas.font_ttf.parseFailureReason` turns a
14
- //! rejected file into a teaching sentence for callers that know the
15
- //! file's name (UiApp's `fonts` option does this).
18
+ //! rejected file into a teaching sentence, and
19
+ //! `canvas.font_ttf.declaredGlyphMaxima` names a budget-refused face's
20
+ //! declared numbers, for callers that know the file's name (UiApp's
21
+ //! `fonts` option uses both).
16
22
  //!
17
23
  //! Both renderers resolve registered ids exactly like built-ins:
18
24
  //! - The frame planner threads the registered set into
@@ -39,8 +45,19 @@
39
45
  //! retained caches. Re-using a registered id fails with
40
46
  //! `error.FontIdInUse`; there is deliberately no unregister.
41
47
  //!
42
- //! Capacities follow `canvas_limits`: `max_registered_canvas_fonts` slots
43
- //! of `max_registered_canvas_font_bytes` each, overflow is
48
+ //! Byte storage is on-demand: registration copies the file into an
49
+ //! exact-size heap allocation from the runtime's init-frozen
50
+ //! `owned_allocator` (captured from `Options.allocator`), so
51
+ //! a runtime with no registered fonts carries zero font bytes (embedding
52
+ //! hosts create a Runtime per surface — a reservation-shaped pool at the
53
+ //! 24 MiB CJK bound would embed 192 MiB in every one). Permanence makes
54
+ //! ownership trivial: the bytes live until `Runtime.deinit`, and the
55
+ //! parsed `Face` views, the gpu-surface host copy, and the measure
56
+ //! provider all borrow them for exactly that lifetime.
57
+ //!
58
+ //! Capacities follow `canvas_limits` as VALIDATION bounds, not storage
59
+ //! reservations: at most `max_registered_canvas_fonts` registrations of
60
+ //! at most `max_registered_canvas_font_bytes` each, overflow is
44
61
  //! `error.FontRegistryFull` / `error.FontTooLarge` — never silent.
45
62
 
46
63
  const std = @import("std");
@@ -51,12 +68,13 @@ const canvas_limits = @import("canvas_limits.zig");
51
68
  pub const max_registered_canvas_fonts = canvas_limits.max_registered_canvas_fonts;
52
69
  pub const max_registered_canvas_font_bytes = canvas_limits.max_registered_canvas_font_bytes;
53
70
 
54
- /// One registered font's metadata; the bytes live in the runtime's slot
55
- /// pool and the parsed face view in the parallel face array at the same
56
- /// index.
71
+ /// One registered font: its id and the exact-size heap copy of its
72
+ /// TrueType bytes (owned by the runtime's init-frozen `owned_allocator`,
73
+ /// freed at `Runtime.deinit`); the parsed face view lives in the parallel
74
+ /// face array at the same index and points into these bytes.
57
75
  pub const CanvasFontEntry = struct {
58
76
  id: canvas.FontId = 0,
59
- byte_len: usize = 0,
77
+ bytes: []const u8 = &.{},
60
78
  };
61
79
 
62
80
  /// Placeholder measure fn for the runtime's font-aware provider field
@@ -82,14 +100,18 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
82
100
  /// `error.InvalidFontId` (id 0 is the "inherit run font"
83
101
  /// sentinel), `error.ReservedFontId` (below
84
102
  /// `canvas.min_registered_font_id` — reserved for built-in
85
- /// faces), `error.FontTooLarge` (over the per-slot bound
103
+ /// faces), `error.FontTooLarge` (over the per-font bound
86
104
  /// `canvas_limits.max_registered_canvas_font_bytes`),
87
105
  /// `error.FontIdInUse` (ids are permanent; see the module doc),
88
106
  /// `error.FontRegistryFull` (all
89
- /// `canvas_limits.max_registered_canvas_fonts` slots hold other
90
- /// ids), `error.FontParseFailed` (not a parseable TrueType face —
107
+ /// `canvas_limits.max_registered_canvas_fonts` registrations
108
+ /// hold other ids), `error.FontParseFailed` (not a parseable TrueType face —
91
109
  /// `canvas.font_ttf.parseFailureReason(ttf)` names what is wrong),
92
- /// `error.FontHostRegistrationUnsupported` (the platform measures
110
+ /// `error.FontExceedsGlyphBudgets` (the face's `maxp` declares
111
+ /// glyphs denser than `canvas.font_ttf`'s outline budgets, so its
112
+ /// densest glyphs could not render as outlines —
113
+ /// `canvas.font_ttf.declaredGlyphMaxima(ttf)` names the declared
114
+ /// maxima), `error.FontHostRegistrationUnsupported` (the platform measures
93
115
  /// and draws text host-side but has no font registration seam, so
94
116
  /// the face could not be honored pixel-honestly).
95
117
  pub fn registerCanvasFont(self: *Runtime, id: canvas.FontId, ttf: []const u8) anyerror!void {
@@ -100,9 +122,27 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
100
122
  if (self.canvas_font_count >= max_registered_canvas_fonts) return error.FontRegistryFull;
101
123
 
102
124
  const index = self.canvas_font_count;
103
- const pooled = self.canvas_font_bytes[index][0..ttf.len];
125
+ // Exact-size heap copy, owned by the runtime until deinit
126
+ // (registration is permanent — no unregister — so this is
127
+ // the only allocation and the only free the registry ever
128
+ // makes). On-demand allocation instead of a slot pool keeps
129
+ // a fontless Runtime at zero font bytes.
130
+ // Alloc and every free (the refusal paths below, the deinit
131
+ // free) go through the runtime's init-frozen ownership
132
+ // allocator: `options.allocator` is publicly mutable and a
133
+ // swap between registration and teardown must never split
134
+ // the alloc/free identity.
135
+ const pooled = try self.owned_allocator.alloc(u8, ttf.len);
136
+ errdefer self.owned_allocator.free(pooled);
104
137
  @memcpy(pooled, ttf);
105
- const face = canvas.font_ttf.Face.parse(pooled) catch return error.FontParseFailed;
138
+ const face = canvas.font_ttf.Face.parse(pooled) catch |err| switch (err) {
139
+ // The registration-time glyph-budget gate: refusing the
140
+ // face here (loudly, with its declared numbers available
141
+ // via `declaredGlyphMaxima`) is what keeps render-time
142
+ // glyph resolution total for registered ids.
143
+ error.FontGlyphTooComplex => return error.FontExceedsGlyphBudgets,
144
+ else => return error.FontParseFailed,
145
+ };
106
146
 
107
147
  // Host sync BEFORE committing the slot: platforms with
108
148
  // host-side text (measure_text_fn) must learn the face or the
@@ -120,7 +160,7 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
120
160
  };
121
161
 
122
162
  self.canvas_font_faces[index] = face;
123
- self.canvas_font_entries[index] = .{ .id = id, .byte_len = ttf.len };
163
+ self.canvas_font_entries[index] = .{ .id = id, .bytes = pooled };
124
164
  self.canvas_font_count = index + 1;
125
165
  // Bind the font-aware measure provider on first registration.
126
166
  // The runtime address is stable from here on (registration
@@ -138,9 +178,9 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
138
178
  }
139
179
 
140
180
  /// The registered set as the `ReferenceFont` slice both renderers
141
- /// consume, rebuilt into runtime scratch (faces are borrowed from
142
- /// the slot pool; with no unregister they stay valid for the
143
- /// runtime's lifetime).
181
+ /// consume, rebuilt into runtime scratch (faces borrow each
182
+ /// entry's heap-owned bytes; with no unregister they stay valid
183
+ /// for the runtime's lifetime).
144
184
  pub fn registeredCanvasFonts(self: *Runtime) []const canvas.ReferenceFont {
145
185
  for (self.canvas_font_entries[0..self.canvas_font_count], 0..) |entry, index| {
146
186
  self.canvas_font_resources_scratch[index] = .{