@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
@@ -5,8 +5,12 @@
5
5
  //!
6
6
  //! The registry is the missing bridge between fetched/decoded bytes and
7
7
  //! the canvas image pipeline, which was already id+fingerprint based end
8
- //! to end: `registerCanvasImage` copies pixels into a bounded
9
- //! runtime-owned pool, and the frame planner threads the registered set
8
+ //! to end: `registerCanvasImage` copies pixels into a bounded set of
9
+ //! runtime-owned slot buffers (each one lazy slot-budget allocation
10
+ //! from the runtime's init-frozen `owned_allocator` at the slot's first
11
+ //! use, freed only by `Runtime.deinit` — a runtime that never registers
12
+ //! an image allocates nothing), and the frame planner threads the
13
+ //! registered set
10
14
  //! into `CanvasFrameOptions.image_resources` for every view — the CPU
11
15
  //! reference renderer (presentation, screenshots, goldens) and the GPU
12
16
  //! packet planner (upload/retain/evict actions keyed by pixel
@@ -28,12 +32,13 @@ const canvas = @import("canvas");
28
32
  const canvas_frame_module = @import("canvas_frame.zig");
29
33
  const canvas_limits = @import("canvas_limits.zig");
30
34
  const effects_mod = @import("effects.zig");
35
+ const runtime_media_surface = @import("media_surface.zig");
31
36
 
32
37
  pub const max_registered_canvas_images = canvas_limits.max_registered_canvas_images;
33
38
  pub const max_registered_canvas_image_pixel_bytes = canvas_limits.max_registered_canvas_image_pixel_bytes;
34
39
 
35
40
  /// One registered image's metadata; pixels live in the runtime's slot
36
- /// pool at the same index.
41
+ /// buffer at the same index.
37
42
  pub const CanvasImageEntry = struct {
38
43
  id: canvas.ImageId = 0,
39
44
  width: usize = 0,
@@ -75,9 +80,19 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
75
80
  /// dimensions or a pixel slice that is not exactly
76
81
  /// `width * height * 4`), `error.ImageTooLarge` (over the
77
82
  /// per-image slot bound), `error.ImageRegistryFull` (all
78
- /// `max_registered_canvas_images` slots hold other ids).
83
+ /// `max_registered_canvas_images` slots hold other ids),
84
+ /// `error.OutOfMemory` (the slot's pixel buffer — one lazy
85
+ /// slot-budget heap allocation at the slot's first use — could
86
+ /// not be allocated; the registry is unchanged and the same
87
+ /// registration can be retried once memory recovers).
79
88
  pub fn registerCanvasImage(self: *Runtime, id: canvas.ImageId, width: usize, height: usize, rgba8: []const u8) anyerror!void {
80
89
  if (id == 0) return error.InvalidImageId;
90
+ // The high bit is the media-surface texture namespace
91
+ // (`canvas.media_surface_image_id_bit`): producer-pushed
92
+ // textures and registered images share one flat id space,
93
+ // so a registration inside the reserved namespace is
94
+ // refused loudly rather than shadowed silently.
95
+ if ((id & canvas.media_surface_image_id_bit) != 0) return error.InvalidImageId;
81
96
  if (width == 0 or height == 0) return error.InvalidImageDimensions;
82
97
  const row_len = std.math.mul(usize, width, 4) catch return error.InvalidImageDimensions;
83
98
  const byte_len = std.math.mul(usize, row_len, height) catch return error.InvalidImageDimensions;
@@ -86,10 +101,26 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
86
101
 
87
102
  const index = findCanvasImageIndex(self, id) orelse blk: {
88
103
  if (self.canvas_image_count >= max_registered_canvas_images) return error.ImageRegistryFull;
89
- const index = self.canvas_image_count;
90
- self.canvas_image_count += 1;
91
- break :blk index;
104
+ break :blk self.canvas_image_count;
92
105
  };
106
+ if (self.canvas_image_pixels[index].len == 0) {
107
+ // The slot's pixel buffer, allocated LAZILY at the
108
+ // slot's first registration (one slot-budget block from
109
+ // the runtime's FROZEN `owned_allocator` — never the
110
+ // live `options.allocator`, which is public and mutable,
111
+ // so a swap between this allocation and `Runtime.deinit`'s
112
+ // free must not split the alloc/free pair across
113
+ // allocators). Re-registrations and unregister/register
114
+ // churn reuse slot buffers, so a runtime allocates at
115
+ // most once per high-water slot; a runtime that never
116
+ // registers an image allocates nothing — an embedded
117
+ // pool at the budget was 16 MiB in every Runtime, the
118
+ // media-texture-pool regression's twin. This is the only
119
+ // failable step past validation and it runs BEFORE any
120
+ // registry mutation, so an OOM refusal leaves the
121
+ // registry exactly as it was and the caller can retry.
122
+ self.canvas_image_pixels[index] = try self.owned_allocator.alloc(u8, max_registered_canvas_image_pixel_bytes);
123
+ }
93
124
  @memcpy(self.canvas_image_pixels[index][0..byte_len], rgba8);
94
125
  self.canvas_image_entries[index] = .{
95
126
  .id = id,
@@ -97,6 +128,7 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
97
128
  .height = height,
98
129
  .byte_len = byte_len,
99
130
  };
131
+ if (index == self.canvas_image_count) self.canvas_image_count += 1;
100
132
  // No pixel push here: GPU packet hosts receive the bytes
101
133
  // through the binary upload side-channel when a packet's
102
134
  // upload cache action first references the new content
@@ -116,8 +148,17 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
116
148
  /// `error.UnsupportedService` (platform has no codec),
117
149
  /// `error.ImageDecodeFailed` (undecodable bytes),
118
150
  /// `error.ImageTooLarge` (decoded pixels over the slot bound).
151
+ /// `error.InvalidImageId` covers the same ids
152
+ /// `registerCanvasImage` refuses (0 and the reserved
153
+ /// media-surface namespace) and fires before any decode work.
119
154
  pub fn registerCanvasImageBytes(self: *Runtime, id: canvas.ImageId, bytes: []const u8) anyerror!RegisteredCanvasImage {
120
155
  if (id == 0) return error.InvalidImageId;
156
+ // Same reserved-namespace refusal as `registerCanvasImage`
157
+ // (see the comment there), checked before the decode so an
158
+ // unusable id never reaches the platform codec — the caller
159
+ // gets `error.InvalidImageId`, not a codec error, and pays
160
+ // no decode cost for it.
161
+ if ((id & canvas.media_surface_image_id_bit) != 0) return error.InvalidImageId;
121
162
  const decoded = try self.options.platform.services.decodeImage(bytes, &canvas_image_decode_scratch.get().bytes);
122
163
  if (decoded.rgba8.len > max_registered_canvas_image_pixel_bytes) return error.ImageTooLarge;
123
164
  try registerCanvasImage(self, id, decoded.width, decoded.height, decoded.rgba8);
@@ -133,13 +174,21 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
133
174
  const last = self.canvas_image_count - 1;
134
175
  if (index != last) {
135
176
  self.canvas_image_entries[index] = self.canvas_image_entries[last];
136
- @memcpy(
137
- self.canvas_image_pixels[index][0..self.canvas_image_entries[index].byte_len],
138
- self.canvas_image_pixels[last][0..self.canvas_image_entries[index].byte_len],
139
- );
177
+ // Slot buffers are whole-budget heap blocks, so
178
+ // compaction swaps the POINTERS — the last entry's
179
+ // pixels move to `index` without copying a byte, and
180
+ // the freed id's buffer parks on the vacated last slot.
181
+ std.mem.swap([]u8, &self.canvas_image_pixels[index], &self.canvas_image_pixels[last]);
140
182
  }
141
183
  self.canvas_image_entries[last] = .{};
142
184
  self.canvas_image_count = last;
185
+ // The vacated slot KEEPS its buffer for reuse: like the
186
+ // media-surface texture pool, `Runtime.deinit` is the only
187
+ // free — one ownership story for every buffer, no
188
+ // conditional lifetime to reason about. Unregister/register
189
+ // churn (avatar refresh loops) never touches the allocator
190
+ // again, and the footprint stays bounded by the high-water
191
+ // slot count, never lifetime registrations.
143
192
  // Best-effort drop of the platform-side texture: platforms
144
193
  // without the upload seam report UnsupportedService, and a
145
194
  // failed removal only costs the host a stale (unreferenced)
@@ -152,8 +201,12 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
152
201
 
153
202
  /// The registered set as the `ReferenceImage` slice both
154
203
  /// renderers consume, rebuilt into runtime scratch (pixels are
155
- /// borrowed from the slot pool, valid until the next
156
- /// register/unregister).
204
+ /// borrowed from the slot buffers, valid until the next
205
+ /// register/unregister), with the adopted media-surface
206
+ /// textures appended as `presentation_only` entries — GPU and
207
+ /// packet hosts upload and composite those, the deterministic
208
+ /// reference renderer skips them by policy (the media surface's
209
+ /// id-derived placeholder is what it draws instead).
157
210
  pub fn registeredCanvasImages(self: *Runtime) []const canvas.ReferenceImage {
158
211
  for (self.canvas_image_entries[0..self.canvas_image_count], 0..) |entry, index| {
159
212
  self.canvas_image_resources_scratch[index] = .{
@@ -163,7 +216,11 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
163
216
  .pixels = self.canvas_image_pixels[index][0..entry.byte_len],
164
217
  };
165
218
  }
166
- return self.canvas_image_resources_scratch[0..self.canvas_image_count];
219
+ const media = runtime_media_surface.RuntimeMediaSurfaces(Runtime).adoptedMediaSurfaceTextures(
220
+ self,
221
+ self.canvas_image_resources_scratch[self.canvas_image_count..],
222
+ );
223
+ return self.canvas_image_resources_scratch[0 .. self.canvas_image_count + media.len];
167
224
  }
168
225
 
169
226
  /// Dimensions of a registered image, or null when `id` is not
@@ -213,11 +270,13 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
213
270
  return null;
214
271
  }
215
272
 
216
- /// Registered pixels changed: force every gpu_surface view to
217
- /// re-render its next frame (an image swap with an unchanged
218
- /// display list would otherwise take the skip path) and request
219
- /// frames so the repaint is not gated on other input.
220
- fn noteCanvasImagesChanged(self: *Runtime) void {
273
+ /// Registered pixels (or adopted media-surface textures, which
274
+ /// ride the same resource set) changed: force every gpu_surface
275
+ /// view to re-render its next frame (an image swap with an
276
+ /// unchanged display list would otherwise take the skip path)
277
+ /// and request frames so the repaint is not gated on other
278
+ /// input. Pub for media_surface.zig's adoption path.
279
+ pub fn noteCanvasImagesChanged(self: *Runtime) void {
221
280
  const frame_methods = canvas_frame_module.RuntimeCanvasFrames(Runtime);
222
281
  for (self.views[0..self.view_count], 0..) |*view, index| {
223
282
  if (!view.open or view.kind != .gpu_surface) continue;
@@ -105,6 +105,31 @@ pub const max_canvas_text_layout_lines_per_view: usize = 8192;
105
105
  pub const max_registered_canvas_images: usize = 16;
106
106
  pub const max_registered_canvas_image_pixel_bytes: usize = 1024 * 1024;
107
107
 
108
+ // Media-surface texture channels (media_surface.zig): producer-pushed
109
+ // dynamic textures composited by media_surface widgets. Sized at video
110
+ // scale, not avatar scale — one 1080p RGBA8 frame is ~7.9 MiB, so the
111
+ // per-channel bound fits it exactly (8 MiB) and refuses 4K until the
112
+ // format axis grows real zero-copy paths; 4 concurrent channels covers
113
+ // a player plus a camera preview plus headroom, and a fifth acquire
114
+ // fails loudly (`error.MediaSurfaceChannelsExhausted`). Both bounds are
115
+ // VALIDATION bounds plus per-USE allocation sizes, never Runtime-struct
116
+ // reservations: an ADOPTED texture's buffer is one lazy frame-budget
117
+ // allocation from the runtime's `owned_allocator` (frozen from
118
+ // `Options.allocator` at init) at the entry's first adoption (freed by
119
+ // `Runtime.deinit`), so a runtime with no
120
+ // media producers carries zero media-texture bytes — an embedded pool
121
+ // at this bound put 4 x 8 MiB = 32 MiB in EVERY Runtime, measured on
122
+ // the docs wasm preview host (one Runtime per component tile, wasm
123
+ // linear memory never overcommits) as 137.5 -> 169.5 MB per instance
124
+ // before any producer existed, the registered-font-pool regression's
125
+ // twin. The producer-side STAGING buffers are allocated at first claim
126
+ // into process-lived module state and kept for the process's life —
127
+ // the mailbox a producer thread may touch after its runtime died,
128
+ // which is why they can never be freed (the effects executor's
129
+ // process-lifetime doctrine).
130
+ pub const max_media_surface_channels: usize = 4;
131
+ pub const max_media_surface_pixel_bytes: usize = 8 * 1024 * 1024;
132
+
108
133
  // Runtime-registered font faces: TrueType bytes apps register under a
109
134
  // caller-chosen FontId (>= canvas.min_registered_font_id) so their own
110
135
  // typefaces resolve everywhere a font id rides — token overrides, text
@@ -116,15 +141,26 @@ pub const max_registered_canvas_image_pixel_bytes: usize = 1024 * 1024;
116
141
  // so re-registering an id with different bytes would serve stale glyphs —
117
142
  // re-use of a registered id fails loudly instead (`error.FontIdInUse`).
118
143
  // The slot count covers a real brand set (a text family in 2-3 weights
119
- // plus a display and a mono face); the per-font bound fits full
120
- // static-instance UI faces (the bundled faces are 71/116 KB; a large
121
- // Latin+Cyrillic+Greek UI face is a few hundred KB) while refusing
122
- // multi-megabyte CJK/variable fonts the glyph pipeline is not sized for.
123
- // Memory is fixed-capacity address space in the Runtime: 8 x 2 MiB =
124
- // 16 MiB, pages touched only as fonts register; oversized files and a
125
- // ninth font fail loudly (`error.FontTooLarge` / `error.FontRegistryFull`).
144
+ // plus a display and a mono face); the per-font bound fits full CJK
145
+ // faces — the glyph pipeline is sized for them (canvas.font_ttf budgets)
146
+ // and the canonical Google Fonts TrueType builds measure 9.6 MB (Noto
147
+ // Sans JP), 10.4 (KR), 11.9 (TC), 13.6 (Noto Serif JP), and 17.8 (Noto
148
+ // Sans SC), so 24 MiB covers the largest measured with ~1.4x headroom.
149
+ // Latin UI faces stay a few hundred KB (the bundled faces are 71/116 KB).
150
+ // Both bounds are VALIDATION bounds, not storage reservations: the
151
+ // registry heap-allocates each font's exact file size from the
152
+ // allocator the runtime froze at init (`Options.allocator`, captured
153
+ // into `Runtime.owned_allocator`) at registration (canvas_fonts.zig), so
154
+ // a runtime with no registered fonts carries zero font bytes. An
155
+ // embedded slot pool at this bound would put 8 x 24 MiB = 192 MiB in
156
+ // EVERY Runtime — measured on the docs wasm preview host (one Runtime
157
+ // per component tile, wasm linear memory never overcommits) as 137.5 ->
158
+ // 313.5 MB per instance before any font registered. Oversized files and
159
+ // a ninth font fail loudly (`error.FontTooLarge` /
160
+ // `error.FontRegistryFull`). The gpu-surface registration side-channel
161
+ // bound (`platform.max_gpu_surface_font_bytes`) pins the same value.
126
162
  pub const max_registered_canvas_fonts: usize = 8;
127
- pub const max_registered_canvas_font_bytes: usize = 2 * 1024 * 1024;
163
+ pub const max_registered_canvas_font_bytes: usize = 24 * 1024 * 1024;
128
164
 
129
165
  // The retained widget-tree budgets (raised 256 -> 1024; see the header
130
166
  // comment). `automation.snapshot.max_widgets_per_view`
@@ -168,6 +168,129 @@ test "keyboard-only selection (shift+arrows) feeds copy" {
168
168
  try std.testing.expectEqualStrings("ry", try harness.runtime.readClipboard(&clipboard_buffer));
169
169
  }
170
170
 
171
+ test "a multi-line paste into a single-line field strips line breaks; a textarea keeps them" {
172
+ var app_state: ClipboardTestApp = .{};
173
+ const app = app_state.app();
174
+ const harness = try createClipboardHarness(app);
175
+ defer harness.destroy(std.testing.allocator);
176
+
177
+ const children = [_]canvas.Widget{
178
+ .{
179
+ .id = 2,
180
+ .kind = .text_field,
181
+ .frame = geometry.RectF.init(12, 16, 200, 36),
182
+ .text = "",
183
+ },
184
+ .{
185
+ .id = 3,
186
+ .kind = .textarea,
187
+ .frame = geometry.RectF.init(12, 64, 280, 100),
188
+ .text = "",
189
+ },
190
+ };
191
+ var nodes: [3]canvas.WidgetLayoutNode = undefined;
192
+ const layout = try canvas.layoutWidgetTree(.{ .kind = .stack, .children = &children }, geometry.RectF.init(0, 0, 320, 200), &nodes);
193
+ _ = try harness.runtime.setCanvasWidgetLayout(1, "canvas", layout);
194
+
195
+ // Interior LF, CRLF, and a trailing CR: the single-line field strips
196
+ // every break (the HTML value-sanitization rule — lines join with
197
+ // nothing between them), and the app-facing keyboard event carries
198
+ // the SAME stripped insert so a model mirror stays byte-identical.
199
+ try harness.runtime.writeClipboard("alpha\nbeta\r\ngamma\r");
200
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_down, 100, 30));
201
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("v", cmd));
202
+ var retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
203
+ try std.testing.expectEqualStrings("alphabetagamma", retained.nodes[1].widget.text);
204
+ try std.testing.expectEqualDeep(canvas.TextSelection.collapsed(14), retained.nodes[1].widget.text_selection.?);
205
+ try std.testing.expectEqualStrings("alphabetagamma", app_state.last_edit_insert[0..app_state.last_edit_insert_len]);
206
+ try std.testing.expect(!app_state.saw_truncated);
207
+
208
+ // The SAME clipboard pasted into the textarea keeps its breaks: only
209
+ // single-line kinds sanitize.
210
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_down, 100, 100));
211
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("v", cmd));
212
+ retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
213
+ try std.testing.expectEqualStrings("alpha\nbeta\r\ngamma\r", retained.nodes[2].widget.text);
214
+ try std.testing.expectEqualStrings("alpha\nbeta\r\ngamma\r", app_state.last_edit_insert[0..app_state.last_edit_insert_len]);
215
+ }
216
+
217
+ test "a paste of only line breaks into a single-line field inserts nothing and keeps the selection" {
218
+ var app_state: ClipboardTestApp = .{};
219
+ const app = app_state.app();
220
+ const harness = try createClipboardHarness(app);
221
+ defer harness.destroy(std.testing.allocator);
222
+
223
+ const text_field = canvas.Widget{
224
+ .id = 2,
225
+ .kind = .text_field,
226
+ .frame = geometry.RectF.init(12, 16, 200, 36),
227
+ .text = "Keep",
228
+ };
229
+ var nodes: [2]canvas.WidgetLayoutNode = undefined;
230
+ const layout = try canvas.layoutWidgetTree(.{ .kind = .stack, .children = &.{text_field} }, geometry.RectF.init(0, 0, 320, 200), &nodes);
231
+ _ = try harness.runtime.setCanvasWidgetLayout(1, "canvas", layout);
232
+
233
+ // Select all, then paste bare newlines: the sanitized insert is
234
+ // EMPTY, so the edit suppresses — nothing inserts, the live
235
+ // selection survives, and the app hears no insert at all (an empty
236
+ // insert is cut's delete-selection edit, which this must never be).
237
+ try harness.runtime.writeClipboard("\r\n\n");
238
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_down, 100, 30));
239
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("a", cmd));
240
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("v", cmd));
241
+ const retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
242
+ try std.testing.expectEqualStrings("Keep", retained.nodes[1].widget.text);
243
+ try std.testing.expectEqualDeep(canvas.TextSelection{ .anchor = 0, .focus = 4 }, retained.nodes[1].widget.text_selection.?);
244
+ try std.testing.expect(!app_state.saw_empty_insert);
245
+ try std.testing.expectEqual(@as(usize, 0), app_state.last_edit_insert_len);
246
+ }
247
+
248
+ test "a near-capacity multi-line paste sanitizes before it clamps" {
249
+ var app_state: ClipboardTestApp = .{};
250
+ const app = app_state.app();
251
+ const harness = try createClipboardHarness(app);
252
+ defer harness.destroy(std.testing.allocator);
253
+
254
+ // Fill the view's shared widget-text storage to EXACTLY three free
255
+ // bytes, the boundary where the sanitize/clamp ordering shows:
256
+ // pasting "a\nbc" must land "abc" (sanitized 3 bytes, fits whole).
257
+ // Clamping the raw clipboard first would spend the third byte on
258
+ // the '\n' the seam strips anyway — "a\nb" then "ab" — silently
259
+ // discarding the valid 'c' and flagging a truncation that never
260
+ // happened to the bytes that count.
261
+ const fill_len = canvas_limits.max_canvas_widget_text_bytes_per_view - 3;
262
+ const fill = try std.testing.allocator.alloc(u8, fill_len);
263
+ defer std.testing.allocator.free(fill);
264
+ @memset(fill, 'x');
265
+ const text_field = canvas.Widget{
266
+ .id = 2,
267
+ .kind = .text_field,
268
+ .frame = geometry.RectF.init(12, 16, 200, 36),
269
+ .text = fill,
270
+ };
271
+ var nodes: [2]canvas.WidgetLayoutNode = undefined;
272
+ const layout = try canvas.layoutWidgetTree(.{ .kind = .stack, .children = &.{text_field} }, geometry.RectF.init(0, 0, 320, 200), &nodes);
273
+ _ = try harness.runtime.setCanvasWidgetLayout(1, "canvas", layout);
274
+ // Pin the boundary premise: exactly 3 bytes of capacity remain.
275
+ try std.testing.expectEqual(fill_len, harness.runtime.views[0].widget_text_len);
276
+
277
+ try harness.runtime.writeClipboard("a\nbc");
278
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_down, 100, 30));
279
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("end", .{}));
280
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("v", cmd));
281
+
282
+ // The retained editor holds the whole sanitized suffix ...
283
+ const retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
284
+ const text = retained.nodes[1].widget.text;
285
+ try std.testing.expectEqual(fill_len + 3, text.len);
286
+ try std.testing.expectEqualStrings("abc", text[text.len - 3 ..]);
287
+ try std.testing.expectEqualDeep(canvas.TextSelection.collapsed(text.len), retained.nodes[1].widget.text_selection.?);
288
+ // ... the app's stamped edit is byte-identical to what the editor
289
+ // applied, and nothing was (falsely) reported truncated.
290
+ try std.testing.expectEqualStrings("abc", app_state.last_edit_insert[0..app_state.last_edit_insert_len]);
291
+ try std.testing.expect(!app_state.saw_truncated);
292
+ }
293
+
171
294
  test "paste clamps to view text capacity and flags truncation loudly" {
172
295
  var app_state: ClipboardTestApp = .{};
173
296
  const app = app_state.app();
@@ -25,6 +25,9 @@ const MenuTestApp = struct {
25
25
  last_menu_item_index: usize = 0,
26
26
  request_count: u32 = 0,
27
27
  last_request_target: canvas.ObjectId = 0,
28
+ last_edit_insert: [64]u8 = undefined,
29
+ last_edit_insert_len: usize = 0,
30
+ saw_truncated: bool = false,
28
31
 
29
32
  fn app(self: *@This()) App {
30
33
  return .{ .context = self, .name = "context-menus", .source = platform.WebViewSource.html("<h1>Hello</h1>"), .event_fn = event };
@@ -45,6 +48,17 @@ const MenuTestApp = struct {
45
48
  self.request_count += 1;
46
49
  self.last_request_target = request_event.target_id;
47
50
  },
51
+ .canvas_widget_keyboard => |keyboard_event| {
52
+ if (keyboard_event.keyboard.edit_truncated) self.saw_truncated = true;
53
+ if (keyboard_event.keyboard.edit) |edit| switch (edit) {
54
+ .insert_text => |text| {
55
+ const len = @min(text.len, self.last_edit_insert.len);
56
+ @memcpy(self.last_edit_insert[0..len], text[0..len]);
57
+ self.last_edit_insert_len = len;
58
+ },
59
+ else => {},
60
+ };
61
+ },
48
62
  else => {},
49
63
  }
50
64
  }
@@ -210,6 +224,47 @@ test "right click on editable text presents the default edit menu wired to clipb
210
224
  try std.testing.expectEqualDeep(canvas.TextSelection{ .anchor = 0, .focus = 5 }, retained.nodes[1].widget.text_selection.?);
211
225
  }
212
226
 
227
+ test "a near-capacity multi-line context-menu paste sanitizes before it clamps" {
228
+ var app_state: MenuTestApp = .{};
229
+ const app = app_state.app();
230
+ const harness = try createMenuHarness(app);
231
+ defer harness.destroy(std.testing.allocator);
232
+
233
+ // Same boundary as the cmd+V shortcut test: exactly three free bytes
234
+ // in the view's shared widget-text storage, clipboard "a\nbc". The
235
+ // context menu's Paste flows through the same sanitize-then-clamp
236
+ // helper, so the sanitized "abc" lands whole instead of the raw
237
+ // clamp's "a\nb" -> "ab".
238
+ const fill_len = canvas_limits.max_canvas_widget_text_bytes_per_view - 3;
239
+ const fill = try std.testing.allocator.alloc(u8, fill_len);
240
+ defer std.testing.allocator.free(fill);
241
+ @memset(fill, 'x');
242
+ const text_field = canvas.Widget{
243
+ .id = 2,
244
+ .kind = .text_field,
245
+ .frame = geometry.RectF.init(12, 16, 200, 36),
246
+ .text = fill,
247
+ };
248
+ var nodes: [2]canvas.WidgetLayoutNode = undefined;
249
+ const layout = try canvas.layoutWidgetTree(.{ .kind = .stack, .children = &.{text_field} }, geometry.RectF.init(0, 0, 320, 200), &nodes);
250
+ _ = try harness.runtime.setCanvasWidgetLayout(1, "canvas", layout);
251
+ try std.testing.expectEqual(fill_len, harness.runtime.views[0].widget_text_len);
252
+
253
+ try harness.runtime.writeClipboard("a\nbc");
254
+ try harness.runtime.dispatchPlatformEvent(app, rightClick(100, 30));
255
+ // Paste is the default edit menu's third item.
256
+ try harness.runtime.dispatchPlatformEvent(app, menuAction(2, 3));
257
+
258
+ // Retained editor and the app's stamped edit hear the same whole
259
+ // sanitized suffix, with no false truncation flag.
260
+ const retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
261
+ const text = retained.nodes[1].widget.text;
262
+ try std.testing.expectEqual(fill_len + 3, text.len);
263
+ try std.testing.expectEqualStrings("abc", text[text.len - 3 ..]);
264
+ try std.testing.expectEqualStrings("abc", app_state.last_edit_insert[0..app_state.last_edit_insert_len]);
265
+ try std.testing.expect(!app_state.saw_truncated);
266
+ }
267
+
213
268
  test "right click on selected static text presents a copy-only menu" {
214
269
  var app_state: MenuTestApp = .{};
215
270
  const app = app_state.app();
@@ -1796,9 +1796,12 @@ pub fn RuntimeCanvasWidgetEvents(comptime Runtime: type) type {
1796
1796
  /// - cut: copy, then stamp a delete-selection edit onto the routed
1797
1797
  /// keyboard event so runtime widget and app model apply the same
1798
1798
  /// removal.
1799
- /// - paste: reads the clipboard into `paste_buffer`, clamps it to
1800
- /// the view's text capacity (setting `edit_truncated` loudly),
1801
- /// and stamps the insertion onto the routed keyboard event.
1799
+ /// - paste: reads the clipboard into `paste_buffer`, sanitizes it
1800
+ /// for the target kind and THEN clamps to the view's text
1801
+ /// capacity (setting `edit_truncated` loudly) — order matters:
1802
+ /// clamping first would spend capacity on line-break bytes the
1803
+ /// seam strips anyway — and stamps the insertion onto the
1804
+ /// routed keyboard event.
1802
1805
  ///
1803
1806
  /// Platforms without a clipboard capability report
1804
1807
  /// `UnsupportedService`; the shortcut degrades to a no-op instead
@@ -1877,7 +1880,24 @@ pub fn RuntimeCanvasWidgetEvents(comptime Runtime: type) type {
1877
1880
  const index = runtimeFindViewIndex(self, keyboard_event.window_id, keyboard_event.view_label) orelse return;
1878
1881
  if (self.views[index].kind != .gpu_surface) return;
1879
1882
  const target = keyboard_event.target orelse return;
1880
- const edit = self.views[index].canvasWidgetKeyboardTextEdit(target, keyboard_event.keyboard) orelse return;
1883
+ const derived = self.views[index].canvasWidgetKeyboardTextEdit(target, keyboard_event.keyboard) orelse return;
1884
+ // Single-line sanitization happens HERE — after derivation,
1885
+ // BEFORE the stamp — so the retained editor and the app's
1886
+ // `on_input` mirror hear byte-identical sanitized inserts
1887
+ // (clipboard paste from both entry points, typed and
1888
+ // automation text_input, IME composition — every insertion
1889
+ // source flows through this one seam). Pre-stamped pastes
1890
+ // arrive already sanitized (`clampCanvasWidgetPasteText`
1891
+ // strips BEFORE clamping so capacity never counts stripped
1892
+ // bytes); re-sanitizing them is a no-op. A suppressed edit (an
1893
+ // insert that was ONLY line breaks) also clears any raw
1894
+ // pre-stamped paste so the app can never hear bytes the
1895
+ // editor refused; the app-side fallback derivation applies
1896
+ // the same sanitize rule, so both derivations still agree.
1897
+ const edit = canvas.sanitizedSingleLineTextInputEvent(target.kind, derived) orelse {
1898
+ keyboard_event.keyboard.edit = null;
1899
+ return;
1900
+ };
1881
1901
  keyboard_event.keyboard.edit = edit;
1882
1902
 
1883
1903
  const dirty = try self.views[index].applyCanvasWidgetTextEdit(target.id, edit) orelse return;
@@ -393,16 +393,33 @@ pub fn canvasWidgetEditableTextKind(kind: canvas.WidgetKind) bool {
393
393
  return kind == .input or kind == .text_field or kind == .search_field or kind == .combobox or kind == .textarea;
394
394
  }
395
395
 
396
- /// Clipboard paste text clamped to what the view's shared widget text
397
- /// storage can absorb (the bytes the edit replaces are freed first).
398
- /// Clamping lands on a UTF-8 boundary; `truncated` is the loud flag the
399
- /// runtime forwards to apps on the keyboard event.
396
+ /// Clipboard paste text sanitized for the target kind and then clamped
397
+ /// to what the view's shared widget text storage can absorb (the bytes
398
+ /// the edit replaces are freed first). Clamping lands on a UTF-8
399
+ /// boundary; `truncated` is the loud flag the runtime forwards to apps
400
+ /// on the keyboard event.
400
401
  pub const CanvasWidgetPasteClamp = struct {
401
402
  text: []const u8 = "",
402
403
  truncated: bool = false,
403
404
  };
404
405
 
405
406
  pub fn clampCanvasWidgetPasteText(widget: canvas.Widget, view_text_len: usize, text: []const u8) CanvasWidgetPasteClamp {
407
+ // Sanitize BEFORE clamping — the shared step for BOTH paste entry
408
+ // points (the cmd+V shortcut and the context-menu Paste). A
409
+ // single-line target strips \r/\n at the edit-derivation seam
410
+ // anyway, so capacity must be measured against the bytes that
411
+ // actually land: clamping the raw clipboard first discarded valid
412
+ // suffix text near the limit ("a\nbc" into 3 free bytes clamped to
413
+ // "a\nb" and then sanitized to "ab", when the sanitized "abc" fits
414
+ // whole). The stamped edit is the post-clamp bytes, so the retained
415
+ // editor and the app's `on_input` mirror still hear identically —
416
+ // the seam's re-sanitize is a no-op on already-stripped text. A
417
+ // paste that sanitizes to nothing clamps to nothing; that is the
418
+ // sanitize rule speaking, NOT capacity, so `truncated` stays false.
419
+ const sanitized = if (canvas.sanitizedSingleLineTextInputEvent(widget.kind, .{ .insert_text = text })) |event|
420
+ event.insert_text
421
+ else
422
+ return .{};
406
423
  const capacity = @import("canvas_limits.zig").max_canvas_widget_text_bytes_per_view;
407
424
  const replaced_len = blk: {
408
425
  if (widget.text_composition) |composition| break :blk composition.byteLen(widget.text.len);
@@ -411,9 +428,9 @@ pub fn clampCanvasWidgetPasteText(widget: canvas.Widget, view_text_len: usize, t
411
428
  };
412
429
  const used = view_text_len -| replaced_len;
413
430
  const available = capacity -| used;
414
- if (text.len <= available) return .{ .text = text };
415
- const clamped = canvas.snapTextOffset(text, available);
416
- return .{ .text = text[0..clamped], .truncated = true };
431
+ if (sanitized.len <= available) return .{ .text = sanitized };
432
+ const clamped = canvas.snapTextOffset(sanitized, available);
433
+ return .{ .text = sanitized[0..clamped], .truncated = true };
417
434
  }
418
435
 
419
436
  pub fn canvasWidgetSingleLineTextKind(kind: canvas.WidgetKind) bool {
@@ -819,7 +819,12 @@ pub fn RuntimeCanvasWidgetState(comptime Runtime: type) type {
819
819
  if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
820
820
  if (!self.views[index].canEditCanvasWidgetText(id)) return error.InvalidCommand;
821
821
 
822
- const dirty = try self.views[index].applyCanvasWidgetTextEdit(id, edit) orelse return self.views[index].info();
822
+ // Direct runtime edits sanitize like every other insertion
823
+ // source (the keyboard choke point's rule): a single-line
824
+ // field's editor never accepts a line break, whoever writes.
825
+ const node = self.views[index].widgetLayoutTree().findById(id) orelse return error.InvalidCommand;
826
+ const sanitized = canvas.sanitizedSingleLineTextInputEvent(node.widget.kind, edit) orelse return self.views[index].info();
827
+ const dirty = try self.views[index].applyCanvasWidgetTextEdit(id, sanitized) orelse return self.views[index].info();
823
828
  try CanvasWidgetEventMethods(Runtime).invalidateForCanvasWidgetDirty(self, index, dirty);
824
829
  _ = try CanvasWidgetDisplayMethods(Runtime).refreshCanvasWidgetDisplayListIfOwned(self, index);
825
830
  return self.views[index].info();