@native-sdk/cli 0.5.2 → 0.5.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 (123) hide show
  1. package/build/app.zig +41 -1
  2. package/build.zig +264 -3
  3. package/native-sdk.d.ts +17 -1
  4. package/package.json +9 -9
  5. package/packages/core/package-lock.json +2 -2
  6. package/packages/core/package.json +1 -1
  7. package/packages/core/rt/rt.zig +138 -3
  8. package/packages/core/sdk/core.ts +225 -3
  9. package/packages/core/sdk/events.ts +39 -2
  10. package/packages/core/src/checker.ts +1 -1
  11. package/packages/core/src/emitter.ts +2625 -262
  12. package/packages/core/src/infer.ts +53 -7
  13. package/skill-data/automation/SKILL.md +7 -4
  14. package/skill-data/core/references/app-model-runtime.md +3 -0
  15. package/skill-data/native-ui/SKILL.md +4 -2
  16. package/skill-data/ts-core/SKILL.md +9 -1
  17. package/src/app_runner/root.zig +106 -1
  18. package/src/app_runner/ts_core_main.zig +4 -0
  19. package/src/automation/protocol.zig +20 -1
  20. package/src/embed/host.zig +27 -0
  21. package/src/embed/tests.zig +187 -0
  22. package/src/embed/ui_host.zig +4 -0
  23. package/src/platform/linux/gtk_host.c +112 -3
  24. package/src/platform/linux/root.zig +71 -0
  25. package/src/platform/macos/appkit_host.h +59 -2
  26. package/src/platform/macos/appkit_host.m +663 -34
  27. package/src/platform/macos/cef_host.mm +262 -10
  28. package/src/platform/macos/root.zig +126 -4
  29. package/src/platform/null_platform.zig +298 -5
  30. package/src/platform/null_platform_tests.zig +39 -0
  31. package/src/platform/root.zig +36 -0
  32. package/src/platform/types.zig +247 -8
  33. package/src/platform/windows/root.zig +134 -0
  34. package/src/platform/windows/webview2_host.cpp +152 -40
  35. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  36. package/src/primitives/app_manifest/root.zig +1 -0
  37. package/src/primitives/app_manifest/types.zig +32 -0
  38. package/src/primitives/canvas/chart.zig +7 -7
  39. package/src/primitives/canvas/chart_tests.zig +66 -0
  40. package/src/primitives/canvas/commands.zig +48 -0
  41. package/src/primitives/canvas/events.zig +161 -0
  42. package/src/primitives/canvas/font_ttf.zig +155 -8
  43. package/src/primitives/canvas/font_ttf_tests.zig +686 -0
  44. package/src/primitives/canvas/reference.zig +67 -8
  45. package/src/primitives/canvas/render_fingerprints.zig +8 -0
  46. package/src/primitives/canvas/root.zig +25 -0
  47. package/src/primitives/canvas/tests.zig +1 -0
  48. package/src/primitives/canvas/ui.zig +46 -9
  49. package/src/primitives/canvas/ui_markup.zig +82 -34
  50. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  51. package/src/primitives/canvas/ui_markup_binary_tests.zig +25 -0
  52. package/src/primitives/canvas/ui_markup_compiled.zig +63 -11
  53. package/src/primitives/canvas/ui_markup_compiled_tests.zig +88 -0
  54. package/src/primitives/canvas/ui_markup_contract.zig +10 -1
  55. package/src/primitives/canvas/ui_markup_contract_tests.zig +50 -0
  56. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  57. package/src/primitives/canvas/ui_markup_tests.zig +55 -9
  58. package/src/primitives/canvas/ui_markup_view.zig +81 -14
  59. package/src/primitives/canvas/ui_markup_view_tests.zig +219 -7
  60. package/src/primitives/canvas/ui_schema.zig +29 -0
  61. package/src/primitives/canvas/ui_schema_tests.zig +11 -11
  62. package/src/primitives/canvas/ui_tests.zig +31 -0
  63. package/src/primitives/canvas/vector.zig +258 -141
  64. package/src/primitives/canvas/widget_access.zig +1 -1
  65. package/src/primitives/canvas/widget_builtin_tests.zig +129 -0
  66. package/src/primitives/canvas/widget_layout.zig +9 -4
  67. package/src/primitives/canvas/widget_render.zig +78 -40
  68. package/src/primitives/canvas/widget_render_controls.zig +15 -4
  69. package/src/primitives/canvas/widget_semantics.zig +6 -1
  70. package/src/primitives/canvas/widget_semantics_tests.zig +168 -0
  71. package/src/primitives/canvas/widget_text_input.zig +118 -10
  72. package/src/primitives/canvas/widgets.zig +16 -0
  73. package/src/root.zig +12 -0
  74. package/src/runtime/api.zig +15 -0
  75. package/src/runtime/automation_commands.zig +33 -0
  76. package/src/runtime/automation_widget_dispatch.zig +64 -0
  77. package/src/runtime/bridge_payload.zig +7 -0
  78. package/src/runtime/bridge_responses.zig +5 -0
  79. package/src/runtime/builtin_bridge.zig +9 -4
  80. package/src/runtime/canvas_font_tests.zig +711 -5
  81. package/src/runtime/canvas_fonts.zig +120 -25
  82. package/src/runtime/canvas_frame_helpers.zig +15 -0
  83. package/src/runtime/canvas_image_tests.zig +221 -0
  84. package/src/runtime/canvas_images.zig +78 -19
  85. package/src/runtime/canvas_limits.zig +44 -8
  86. package/src/runtime/canvas_widget_clipboard_tests.zig +123 -0
  87. package/src/runtime/canvas_widget_context_menu_tests.zig +55 -0
  88. package/src/runtime/canvas_widget_events.zig +24 -4
  89. package/src/runtime/canvas_widget_runtime.zig +24 -7
  90. package/src/runtime/canvas_widget_state.zig +6 -1
  91. package/src/runtime/canvas_widget_text_tests.zig +277 -0
  92. package/src/runtime/core.zig +148 -9
  93. package/src/runtime/effects.zig +1664 -43
  94. package/src/runtime/effects_fetch_tests.zig +89 -1
  95. package/src/runtime/effects_file_tests.zig +41 -1
  96. package/src/runtime/effects_image_tests.zig +1304 -0
  97. package/src/runtime/effects_tests.zig +153 -0
  98. package/src/runtime/flow.zig +44 -0
  99. package/src/runtime/gpu_surface_events.zig +7 -0
  100. package/src/runtime/media_surface.zig +726 -0
  101. package/src/runtime/media_surface_tests.zig +1476 -0
  102. package/src/runtime/root.zig +20 -0
  103. package/src/runtime/session_blobs.zig +689 -0
  104. package/src/runtime/session_journal.zig +111 -20
  105. package/src/runtime/session_record.zig +27 -2
  106. package/src/runtime/session_replay.zig +168 -16
  107. package/src/runtime/session_tests.zig +2118 -4
  108. package/src/runtime/shell_layout.zig +7 -0
  109. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  110. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  111. package/src/runtime/tests.zig +3 -0
  112. package/src/runtime/ts_core_host.zig +439 -4
  113. package/src/runtime/ts_core_host_tests.zig +41 -0
  114. package/src/runtime/ts_ui_app.zig +63 -0
  115. package/src/runtime/ui_app.zig +169 -6
  116. package/src/runtime/ui_app_tests.zig +334 -0
  117. package/src/runtime/ui_app_window_tests.zig +468 -0
  118. package/src/runtime/window_command_bridge_tests.zig +117 -0
  119. package/src/runtime/window_storage.zig +32 -0
  120. package/src/runtime/window_views.zig +61 -1
  121. package/src/tooling/manifest.zig +75 -0
  122. package/src/tooling/raw_manifest.zig +2 -0
  123. package/src/tooling/templates.zig +219 -1
@@ -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,41 @@ 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 = &.{},
78
+ /// The host-side unregistration owner — the platform's
79
+ /// `unregister_gpu_surface_font_fn` and its context, captured from
80
+ /// the services in effect when THIS registration was pushed to the
81
+ /// host. Captured precisely because `Runtime.options` is public and
82
+ /// mutable while registration and teardown can be a whole runtime
83
+ /// lifetime apart: the registration must be returned to the host
84
+ /// that received it, so `Runtime.deinit` unregisters through this
85
+ /// captured pair and mutating `options.platform` on a live runtime
86
+ /// retargets nothing (the `owned_allocator` identity-freeze
87
+ /// doctrine, applied to the host seam — a deinit that read the live
88
+ /// options would unregister against whatever platform the option
89
+ /// points at by teardown time, stranding the original host's
90
+ /// descriptor and caches). Null when the platform at registration
91
+ /// time had no unregister seam: it retained nothing to return.
92
+ host_unregister_fn: ?*const fn (context: ?*anyopaque, id: u64, token: u64) anyerror!void = null,
93
+ host_unregister_context: ?*anyopaque = null,
94
+ /// The host's ownership token for THIS registration, returned by
95
+ /// `registerGpuSurfaceFont` and passed back through the owner above
96
+ /// at deinit. Host font state is per-process while ids are only
97
+ /// permanent per-runtime, so a later runtime may re-register this
98
+ /// entry's id (last wins, the documented lifecycle); the host
99
+ /// removes an id's state only while its current registration still
100
+ /// carries the presented token, which keeps an older runtime's
101
+ /// deinit from tearing down a newer runtime's live face. 0 when the
102
+ /// platform returned no token (a stateless accept, or no register
103
+ /// seam at all): nothing was installed for this registration, and
104
+ /// an unregister carrying 0 removes nothing.
105
+ host_registration_token: u64 = 0,
60
106
  };
61
107
 
62
108
  /// Placeholder measure fn for the runtime's font-aware provider field
@@ -82,14 +128,18 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
82
128
  /// `error.InvalidFontId` (id 0 is the "inherit run font"
83
129
  /// sentinel), `error.ReservedFontId` (below
84
130
  /// `canvas.min_registered_font_id` — reserved for built-in
85
- /// faces), `error.FontTooLarge` (over the per-slot bound
131
+ /// faces), `error.FontTooLarge` (over the per-font bound
86
132
  /// `canvas_limits.max_registered_canvas_font_bytes`),
87
133
  /// `error.FontIdInUse` (ids are permanent; see the module doc),
88
134
  /// `error.FontRegistryFull` (all
89
- /// `canvas_limits.max_registered_canvas_fonts` slots hold other
90
- /// ids), `error.FontParseFailed` (not a parseable TrueType face —
135
+ /// `canvas_limits.max_registered_canvas_fonts` registrations
136
+ /// hold other ids), `error.FontParseFailed` (not a parseable TrueType face —
91
137
  /// `canvas.font_ttf.parseFailureReason(ttf)` names what is wrong),
92
- /// `error.FontHostRegistrationUnsupported` (the platform measures
138
+ /// `error.FontExceedsGlyphBudgets` (the face's `maxp` declares
139
+ /// glyphs denser than `canvas.font_ttf`'s outline budgets, so its
140
+ /// densest glyphs could not render as outlines —
141
+ /// `canvas.font_ttf.declaredGlyphMaxima(ttf)` names the declared
142
+ /// maxima), `error.FontHostRegistrationUnsupported` (the platform measures
93
143
  /// and draws text host-side but has no font registration seam, so
94
144
  /// the face could not be honored pixel-honestly).
95
145
  pub fn registerCanvasFont(self: *Runtime, id: canvas.FontId, ttf: []const u8) anyerror!void {
@@ -100,9 +150,27 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
100
150
  if (self.canvas_font_count >= max_registered_canvas_fonts) return error.FontRegistryFull;
101
151
 
102
152
  const index = self.canvas_font_count;
103
- const pooled = self.canvas_font_bytes[index][0..ttf.len];
153
+ // Exact-size heap copy, owned by the runtime until deinit
154
+ // (registration is permanent — no unregister — so this is
155
+ // the only allocation and the only free the registry ever
156
+ // makes). On-demand allocation instead of a slot pool keeps
157
+ // a fontless Runtime at zero font bytes.
158
+ // Alloc and every free (the refusal paths below, the deinit
159
+ // free) go through the runtime's init-frozen ownership
160
+ // allocator: `options.allocator` is publicly mutable and a
161
+ // swap between registration and teardown must never split
162
+ // the alloc/free identity.
163
+ const pooled = try self.owned_allocator.alloc(u8, ttf.len);
164
+ errdefer self.owned_allocator.free(pooled);
104
165
  @memcpy(pooled, ttf);
105
- const face = canvas.font_ttf.Face.parse(pooled) catch return error.FontParseFailed;
166
+ const face = canvas.font_ttf.Face.parse(pooled) catch |err| switch (err) {
167
+ // The registration-time glyph-budget gate: refusing the
168
+ // face here (loudly, with its declared numbers available
169
+ // via `declaredGlyphMaxima`) is what keeps render-time
170
+ // glyph resolution total for registered ids.
171
+ error.FontGlyphTooComplex => return error.FontExceedsGlyphBudgets,
172
+ else => return error.FontParseFailed,
173
+ };
106
174
 
107
175
  // Host sync BEFORE committing the slot: platforms with
108
176
  // host-side text (measure_text_fn) must learn the face or the
@@ -111,16 +179,38 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
111
179
  // exact silent fallback this seam forbids. Platforms without
112
180
  // host-side text may lack the seam (`UnsupportedService`):
113
181
  // the engine measures with the parsed face and inks it
114
- // through the reference renderer, so nothing is lost.
115
- self.options.platform.services.registerGpuSurfaceFont(.{ .id = id, .ttf = pooled }) catch |err| switch (err) {
116
- error.UnsupportedService => {
117
- if (self.options.platform.services.measure_text_fn != null) return error.FontHostRegistrationUnsupported;
182
+ // through the reference renderer, so nothing is lost. ONE
183
+ // services read serves both the sync and the captured return
184
+ // path below, so the host that hears the registration is the
185
+ // host the entry's unregister owner names.
186
+ const services = self.options.platform.services;
187
+ // The returned token is the host's ownership handle for THIS
188
+ // registration (0 when the host retained nothing); it rides
189
+ // the entry beside the captured owner so deinit can tell the
190
+ // host which registration to remove — see
191
+ // `CanvasFontEntry.host_registration_token`.
192
+ const host_token: u64 = services.registerGpuSurfaceFont(.{ .id = id, .ttf = pooled }) catch |err| switch (err) {
193
+ error.UnsupportedService => blk: {
194
+ if (services.measure_text_fn != null) return error.FontHostRegistrationUnsupported;
195
+ break :blk 0;
118
196
  },
119
197
  else => return err,
120
198
  };
121
199
 
122
200
  self.canvas_font_faces[index] = face;
123
- self.canvas_font_entries[index] = .{ .id = id, .byte_len = ttf.len };
201
+ // The entry carries its own host unregistration owner,
202
+ // captured now (see `CanvasFontEntry.host_unregister_fn`):
203
+ // `options.platform` is publicly mutable, and the teardown
204
+ // return must land on the host that received this
205
+ // registration, never on whatever platform the option holds
206
+ // by `Runtime.deinit` time.
207
+ self.canvas_font_entries[index] = .{
208
+ .id = id,
209
+ .bytes = pooled,
210
+ .host_unregister_fn = services.unregister_gpu_surface_font_fn,
211
+ .host_unregister_context = services.context,
212
+ .host_registration_token = host_token,
213
+ };
124
214
  self.canvas_font_count = index + 1;
125
215
  // Bind the font-aware measure provider on first registration.
126
216
  // The runtime address is stable from here on (registration
@@ -138,9 +228,9 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
138
228
  }
139
229
 
140
230
  /// 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).
231
+ /// consume, rebuilt into runtime scratch (faces borrow each
232
+ /// entry's heap-owned bytes; with no unregister they stay valid
233
+ /// for the runtime's lifetime).
144
234
  pub fn registeredCanvasFonts(self: *Runtime) []const canvas.ReferenceFont {
145
235
  for (self.canvas_font_entries[0..self.canvas_font_count], 0..) |entry, index| {
146
236
  self.canvas_font_resources_scratch[index] = .{
@@ -210,7 +300,12 @@ pub fn RuntimeCanvasFonts(comptime Runtime: type) type {
210
300
  /// A face joined the registry: force every gpu_surface view to
211
301
  /// re-render its next frame (text referencing the id may already
212
302
  /// be retained) and request frames so the repaint is not gated on
213
- /// other input — the image-registry choreography.
303
+ /// other input — the image-registry choreography. Re-rendering
304
+ /// alone re-inks RETAINED geometry; installed UiApps complete the
305
+ /// late-registration story by comparing the registered count on
306
+ /// each presented frame and rebuilding every surface so layout
307
+ /// re-measures with the new face (ui_app.zig,
308
+ /// `rebuildForRegisteredFonts`).
214
309
  fn noteCanvasFontsChanged(self: *Runtime) void {
215
310
  // A new face changes what the measurement seam answers for
216
311
  // its id (host providers just learned the face; the engine
@@ -140,6 +140,12 @@ pub fn canvasWidgetPointerEventFromGpuInput(input_event: GpuSurfaceInputEvent) ?
140
140
  .ime_set_composition,
141
141
  .ime_commit_composition,
142
142
  .ime_cancel_composition,
143
+ // Pinch is not a widget pointer gesture: it reaches the app as
144
+ // the raw `gpu_surface_input` event (timeline/canvas zoom is an
145
+ // app-level concern, not a widget press/scroll).
146
+ .pinch_begin,
147
+ .pinch_change,
148
+ .pinch_end,
143
149
  => return null,
144
150
  };
145
151
  return .{
@@ -163,6 +169,9 @@ pub fn canvasWidgetInputBatchesDisplayListRefresh(kind: platform.GpuSurfaceInput
163
169
  .ime_set_composition,
164
170
  .ime_commit_composition,
165
171
  .ime_cancel_composition,
172
+ .pinch_begin,
173
+ .pinch_change,
174
+ .pinch_end,
166
175
  => true,
167
176
  };
168
177
  }
@@ -181,6 +190,9 @@ pub fn canvasWidgetKeyboardEventFromGpuInput(input_event: GpuSurfaceInputEvent,
181
190
  .ime_set_composition,
182
191
  .ime_commit_composition,
183
192
  .ime_cancel_composition,
193
+ .pinch_begin,
194
+ .pinch_change,
195
+ .pinch_end,
184
196
  => return null,
185
197
  };
186
198
  return .{
@@ -221,6 +233,9 @@ fn canvasWidgetTextEditEventFromGpuInput(input_event: GpuSurfaceInputEvent) ?can
221
233
  .pointer_move,
222
234
  .pointer_drag,
223
235
  .scroll,
236
+ .pinch_begin,
237
+ .pinch_change,
238
+ .pinch_end,
224
239
  => null,
225
240
  };
226
241
  }
@@ -207,6 +207,227 @@ test "registerCanvasImageBytes decodes through the platform seam" {
207
207
  try std.testing.expectError(error.InvalidImageId, harness.runtime.registerCanvasImageBytes(0, encoded));
208
208
  }
209
209
 
210
+ test "registerCanvasImageBytes refuses reserved media-surface ids before decoding" {
211
+ const harness = try startedGpuHarness(std.testing.allocator);
212
+ defer harness.destroy(std.testing.allocator);
213
+ var app_state: RegistryApp = .{};
214
+ try harness.start(app_state.app());
215
+ harness.null_platform.image_decode = true;
216
+
217
+ const fixture = [_]u8{ 255, 0, 0, 255 };
218
+ var encoded_buffer: [1024]u8 = undefined;
219
+ var writer = std.Io.Writer.fixed(&encoded_buffer);
220
+ try canvas.png.writeRgba8(&writer, 1, 1, &fixture);
221
+ const encoded = writer.buffered();
222
+
223
+ // An id inside the reserved media-surface texture namespace is
224
+ // refused as an invalid id — not surfaced as a codec error — and
225
+ // the refusal happens before the platform decoder ever runs.
226
+ const reserved_id: canvas.ImageId = canvas.media_surface_image_id_bit | 9;
227
+ try std.testing.expectError(error.InvalidImageId, harness.runtime.registerCanvasImageBytes(reserved_id, encoded));
228
+ try std.testing.expectEqual(@as(usize, 0), harness.null_platform.image_decode_count);
229
+ try std.testing.expectEqual(@as(usize, 0), harness.runtime.registeredCanvasImageCount());
230
+
231
+ // The same bytes under an ordinary id decode and register fine.
232
+ _ = try harness.runtime.registerCanvasImageBytes(9, encoded);
233
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.image_decode_count);
234
+ }
235
+
236
+ // ------------------------------------------------------ lazy slot buffers
237
+
238
+ /// A started GPU harness whose runtime froze `runtime_allocator` at
239
+ /// init. The runtime's `owned_allocator` captures `Options.allocator`
240
+ /// in `initAt` and mutating `options.allocator` on a live runtime
241
+ /// deliberately retargets nothing, so a test allocator must be injected
242
+ /// through the real capture site: re-initialize the runtime in place
243
+ /// with the harness's own platform and trace wiring (nothing is
244
+ /// heap-owned yet, so the re-init leaks nothing).
245
+ fn startedGpuHarnessWithRuntimeAllocator(gpa: std.mem.Allocator, runtime_allocator: std.mem.Allocator) !*TestHarness() {
246
+ const harness = try startedGpuHarness(gpa);
247
+ errdefer harness.destroy(gpa);
248
+ core.Runtime.initAt(&harness.runtime, .{
249
+ .platform = harness.null_platform.platform(),
250
+ .trace_sink = harness.trace_sink.sink(),
251
+ .allocator = runtime_allocator,
252
+ .environ = std.testing.environ,
253
+ });
254
+ // Match TestHarness().init: tests fail loud on handler/update errors.
255
+ harness.runtime.dispatch_error_policy = .propagate;
256
+ return harness;
257
+ }
258
+
259
+ /// The registered pixels for `id`, looked up through the same
260
+ /// `ReferenceImage` set the renderers consume — compaction correctness
261
+ /// is judged where the pixels are actually read.
262
+ fn registeredPixelsById(runtime: *core.Runtime, id: canvas.ImageId) ?[]const u8 {
263
+ for (runtime.registeredCanvasImages()) |resource| {
264
+ if (resource.id == id) return resource.pixels;
265
+ }
266
+ return null;
267
+ }
268
+
269
+ test "a fresh runtime allocates zero registered-image bytes until the first registration" {
270
+ // Count every runtime-allocator call: construction, startup, and
271
+ // view creation perform NONE — slot buffer storage is on-demand at
272
+ // a slot's first registration. (The regression pinned here: an
273
+ // embedded pool put 16 x 1 MiB = 16 MiB in every Runtime before
274
+ // any image existed; the media-texture-pool regression's twin.)
275
+ var counting = std.testing.FailingAllocator.init(std.testing.allocator, .{});
276
+ const harness = try startedGpuHarnessWithRuntimeAllocator(std.testing.allocator, counting.allocator());
277
+ defer harness.destroy(std.testing.allocator);
278
+ var app_state: RegistryApp = .{};
279
+ try harness.start(app_state.app());
280
+ _ = try harness.runtime.createView(.{
281
+ .window_id = 1,
282
+ .label = "canvas",
283
+ .kind = .gpu_surface,
284
+ .frame = geometry.RectF.init(0, 0, 240, 140),
285
+ });
286
+ try std.testing.expectEqual(@as(usize, 0), counting.allocations);
287
+
288
+ // The first registration is the first allocation: exactly one,
289
+ // exactly the slot budget (freed by Runtime.deinit through
290
+ // harness.destroy — the leak-checked test allocator backs it).
291
+ const red = [_]u8{ 255, 0, 0, 255 };
292
+ try harness.runtime.registerCanvasImage(1, 1, 1, &red);
293
+ try std.testing.expectEqual(@as(usize, 1), counting.allocations);
294
+ try std.testing.expectEqual(canvas_limits.max_registered_canvas_image_pixel_bytes, counting.allocated_bytes);
295
+
296
+ // Replacing an id's pixels reuses the slot buffer: the count stays
297
+ // one — the allocation is per used slot, not per registration.
298
+ const blue = [_]u8{ 0, 0, 255, 255 };
299
+ try harness.runtime.registerCanvasImage(1, 1, 1, &blue);
300
+ try std.testing.expectEqual(@as(usize, 1), counting.allocations);
301
+
302
+ // A second id claims a second slot: one more allocation.
303
+ try harness.runtime.registerCanvasImage(2, 1, 1, &red);
304
+ try std.testing.expectEqual(@as(usize, 2), counting.allocations);
305
+
306
+ // Unregister keeps vacated buffers for reuse (deinit is the only
307
+ // free), so churn never touches the allocator again: the footprint
308
+ // is bounded by the high-water slot count.
309
+ try std.testing.expect(harness.runtime.unregisterCanvasImage(1));
310
+ try std.testing.expect(harness.runtime.unregisterCanvasImage(2));
311
+ try harness.runtime.registerCanvasImage(3, 1, 1, &blue);
312
+ try harness.runtime.registerCanvasImage(4, 1, 1, &red);
313
+ try std.testing.expectEqual(@as(usize, 2), counting.allocations);
314
+ }
315
+
316
+ test "image slot buffer ownership freezes at init: a mutated options.allocator sees zero activity" {
317
+ // The hazard pinned here: `Runtime.options` is public and mutable,
318
+ // so if the lazy slot allocation and deinit's free both read
319
+ // `options.allocator` LIVE, swapping it between registration and
320
+ // deinit frees through the wrong allocator — silent UB. Ownership
321
+ // must freeze into `owned_allocator` at init instead.
322
+ var frozen = std.testing.FailingAllocator.init(std.testing.allocator, .{});
323
+ const harness = try startedGpuHarnessWithRuntimeAllocator(std.testing.allocator, frozen.allocator());
324
+ defer harness.destroy(std.testing.allocator);
325
+ var app_state: RegistryApp = .{};
326
+ try harness.start(app_state.app());
327
+ const red = [_]u8{ 255, 0, 0, 255 };
328
+ try harness.runtime.registerCanvasImage(7, 1, 1, &red);
329
+ try std.testing.expectEqual(@as(usize, 1), frozen.allocations);
330
+
331
+ // Sabotage: swap options.allocator AFTER the registration
332
+ // allocated. fail_index = 0 poisons the swapped-in allocator (any
333
+ // allocation through it refuses), and its counters pin that deinit
334
+ // routes NOTHING here — neither an alloc nor, critically, the free.
335
+ var poisoned = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });
336
+ harness.runtime.options.allocator = poisoned.allocator();
337
+
338
+ harness.runtime.deinit();
339
+ try std.testing.expectEqual(@as(usize, 1), frozen.deallocations);
340
+ try std.testing.expectEqual(canvas_limits.max_registered_canvas_image_pixel_bytes, frozen.freed_bytes);
341
+ try std.testing.expectEqual(@as(usize, 0), poisoned.allocations);
342
+ try std.testing.expectEqual(@as(usize, 0), poisoned.deallocations);
343
+ try std.testing.expectEqual(@as(usize, 0), poisoned.freed_bytes);
344
+ // harness.destroy's second deinit finds the buffers already
345
+ // returned (deinit resets them to empty) — no double free through
346
+ // either allocator.
347
+ }
348
+
349
+ test "unregister compacts by pointer swap: surviving pixels stay intact and vacated buffers are reused" {
350
+ var counting = std.testing.FailingAllocator.init(std.testing.allocator, .{});
351
+ const harness = try startedGpuHarnessWithRuntimeAllocator(std.testing.allocator, counting.allocator());
352
+ defer harness.destroy(std.testing.allocator);
353
+ var app_state: RegistryApp = .{};
354
+ try harness.start(app_state.app());
355
+
356
+ const colors = [_][4]u8{
357
+ .{ 255, 0, 0, 255 },
358
+ .{ 0, 255, 0, 255 },
359
+ .{ 0, 0, 255, 255 },
360
+ .{ 255, 255, 0, 255 },
361
+ };
362
+ for (colors, 1..) |color, id| {
363
+ try harness.runtime.registerCanvasImage(id, 1, 1, &color);
364
+ }
365
+ try std.testing.expectEqual(@as(usize, 4), counting.allocations);
366
+
367
+ // Removing a middle id compacts the last entry into its slot; every
368
+ // survivor's pixels must read back exactly through the renderer set.
369
+ try std.testing.expect(harness.runtime.unregisterCanvasImage(2));
370
+ try std.testing.expectEqual(@as(usize, 3), harness.runtime.registeredCanvasImageCount());
371
+ try std.testing.expect(registeredPixelsById(&harness.runtime, 2) == null);
372
+ try std.testing.expectEqualSlices(u8, &colors[0], registeredPixelsById(&harness.runtime, 1).?);
373
+ try std.testing.expectEqualSlices(u8, &colors[2], registeredPixelsById(&harness.runtime, 3).?);
374
+ try std.testing.expectEqualSlices(u8, &colors[3], registeredPixelsById(&harness.runtime, 4).?);
375
+
376
+ // A second compaction swaps again: the moved entry from the first
377
+ // pass moves once more and its pixels still hold.
378
+ try std.testing.expect(harness.runtime.unregisterCanvasImage(1));
379
+ try std.testing.expectEqual(@as(usize, 2), harness.runtime.registeredCanvasImageCount());
380
+ try std.testing.expectEqualSlices(u8, &colors[2], registeredPixelsById(&harness.runtime, 3).?);
381
+ try std.testing.expectEqualSlices(u8, &colors[3], registeredPixelsById(&harness.runtime, 4).?);
382
+
383
+ // Re-registering into the vacated slots reuses their parked buffers:
384
+ // the allocation count never moves past the high-water mark, and the
385
+ // fresh pixels land next to the untouched survivors.
386
+ const teal = [_]u8{ 0, 128, 128, 255 };
387
+ const gray = [_]u8{ 90, 90, 90, 255 };
388
+ try harness.runtime.registerCanvasImage(5, 1, 1, &teal);
389
+ try harness.runtime.registerCanvasImage(6, 1, 1, &gray);
390
+ try std.testing.expectEqual(@as(usize, 4), counting.allocations);
391
+ try std.testing.expectEqual(@as(usize, 4), harness.runtime.registeredCanvasImageCount());
392
+ try std.testing.expectEqualSlices(u8, &teal, registeredPixelsById(&harness.runtime, 5).?);
393
+ try std.testing.expectEqualSlices(u8, &gray, registeredPixelsById(&harness.runtime, 6).?);
394
+ try std.testing.expectEqualSlices(u8, &colors[2], registeredPixelsById(&harness.runtime, 3).?);
395
+ try std.testing.expectEqualSlices(u8, &colors[3], registeredPixelsById(&harness.runtime, 4).?);
396
+ }
397
+
398
+ test "a failed slot-buffer allocation refuses cleanly and a retry succeeds after memory heals" {
399
+ var counting = std.testing.FailingAllocator.init(std.testing.allocator, .{});
400
+ const harness = try startedGpuHarnessWithRuntimeAllocator(std.testing.allocator, counting.allocator());
401
+ defer harness.destroy(std.testing.allocator);
402
+ var app_state: RegistryApp = .{};
403
+ try harness.start(app_state.app());
404
+
405
+ const red = [_]u8{ 255, 0, 0, 255 };
406
+ const blue = [_]u8{ 0, 0, 255, 255 };
407
+ try harness.runtime.registerCanvasImage(1, 1, 1, &red);
408
+
409
+ // The next slot's lazy allocation fails: the registration refuses
410
+ // with the honest allocator error and the registry is EXACTLY as it
411
+ // was — the earlier id intact, the failed id absent, no committed
412
+ // slot without pixels.
413
+ counting.fail_index = counting.alloc_index;
414
+ try std.testing.expectError(error.OutOfMemory, harness.runtime.registerCanvasImage(2, 1, 1, &blue));
415
+ try std.testing.expectEqual(@as(usize, 1), harness.runtime.registeredCanvasImageCount());
416
+ try std.testing.expect(harness.runtime.registeredCanvasImage(2) == null);
417
+ try std.testing.expectEqualSlices(u8, &red, registeredPixelsById(&harness.runtime, 1).?);
418
+
419
+ // Replacing an ALREADY-registered id needs no allocation, so it
420
+ // still succeeds while memory is exhausted.
421
+ try harness.runtime.registerCanvasImage(1, 1, 1, &blue);
422
+ try std.testing.expectEqualSlices(u8, &blue, registeredPixelsById(&harness.runtime, 1).?);
423
+
424
+ // Memory recovers: the same registration retries and lands.
425
+ counting.fail_index = std.math.maxInt(usize);
426
+ try harness.runtime.registerCanvasImage(2, 1, 1, &blue);
427
+ try std.testing.expectEqual(@as(usize, 2), harness.runtime.registeredCanvasImageCount());
428
+ try std.testing.expectEqualSlices(u8, &blue, registeredPixelsById(&harness.runtime, 2).?);
429
+ }
430
+
210
431
  // ---------------------------------------------------------------- avatar app
211
432
 
212
433
  const avatar_canvas_label = "avatar-canvas";