@native-sdk/cli 0.6.2 → 0.7.0

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 (64) hide show
  1. package/build.zig +8 -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/text.ts +62 -21
  6. package/skill-data/native-ui/SKILL.md +17 -2
  7. package/src/platform/macos/appkit_host.h +2 -0
  8. package/src/platform/macos/appkit_host.m +36 -10
  9. package/src/platform/macos/root.zig +7 -1
  10. package/src/platform/types.zig +2 -0
  11. package/src/primitives/canvas/code.zig +590 -0
  12. package/src/primitives/canvas/code_tests.zig +1062 -0
  13. package/src/primitives/canvas/equality.zig +3 -1
  14. package/src/primitives/canvas/events.zig +4 -0
  15. package/src/primitives/canvas/layout_audit.zig +3 -1
  16. package/src/primitives/canvas/markdown.zig +13 -11
  17. package/src/primitives/canvas/markdown_tests.zig +167 -4
  18. package/src/primitives/canvas/root.zig +15 -2
  19. package/src/primitives/canvas/tests.zig +1 -0
  20. package/src/primitives/canvas/text.zig +10 -0
  21. package/src/primitives/canvas/text_interaction.zig +164 -22
  22. package/src/primitives/canvas/text_layout.zig +107 -21
  23. package/src/primitives/canvas/text_measure_cache.zig +4 -4
  24. package/src/primitives/canvas/text_span_tests.zig +254 -0
  25. package/src/primitives/canvas/text_spans.zig +556 -32
  26. package/src/primitives/canvas/text_tests.zig +86 -0
  27. package/src/primitives/canvas/themes/geist.zig +29 -0
  28. package/src/primitives/canvas/tokens.zig +72 -2
  29. package/src/primitives/canvas/ui.zig +325 -21
  30. package/src/primitives/canvas/ui_markup.zig +59 -2
  31. package/src/primitives/canvas/ui_markup_compiled.zig +76 -0
  32. package/src/primitives/canvas/ui_markup_compiled_tests.zig +33 -0
  33. package/src/primitives/canvas/ui_markup_contract.zig +34 -0
  34. package/src/primitives/canvas/ui_markup_reflect.zig +20 -3
  35. package/src/primitives/canvas/ui_markup_view.zig +73 -0
  36. package/src/primitives/canvas/ui_markup_view_tests.zig +101 -0
  37. package/src/primitives/canvas/ui_schema.zig +17 -6
  38. package/src/primitives/canvas/ui_schema_tests.zig +7 -6
  39. package/src/primitives/canvas/ui_tests.zig +6 -0
  40. package/src/primitives/canvas/widget_invalidation.zig +3 -0
  41. package/src/primitives/canvas/widget_layout.zig +57 -8
  42. package/src/primitives/canvas/widget_layout_tests.zig +35 -0
  43. package/src/primitives/canvas/widget_metrics.zig +30 -1
  44. package/src/primitives/canvas/widget_render.zig +454 -9
  45. package/src/primitives/canvas/widget_runtime.zig +1 -0
  46. package/src/primitives/canvas/widget_text_input.zig +23 -11
  47. package/src/primitives/canvas/widget_text_select.zig +2 -2
  48. package/src/primitives/canvas/widgets.zig +13 -0
  49. package/src/root.zig +1 -0
  50. package/src/runtime/api.zig +9 -0
  51. package/src/runtime/canvas_frame_helpers.zig +1 -0
  52. package/src/runtime/canvas_limits.zig +7 -0
  53. package/src/runtime/canvas_widget_accessibility_tests.zig +27 -1
  54. package/src/runtime/canvas_widget_clipboard_tests.zig +146 -0
  55. package/src/runtime/canvas_widget_context_menu.zig +12 -2
  56. package/src/runtime/canvas_widget_display.zig +15 -1
  57. package/src/runtime/canvas_widget_events.zig +50 -20
  58. package/src/runtime/canvas_widget_runtime.zig +74 -12
  59. package/src/runtime/canvas_widget_state.zig +1 -0
  60. package/src/runtime/canvas_widget_text_tests.zig +1935 -70
  61. package/src/runtime/gpu_surface_events.zig +38 -0
  62. package/src/runtime/view.zig +37 -3
  63. package/src/runtime/view_widget_text.zig +1242 -14
  64. package/src/runtime/view_widget_tree.zig +2 -0
@@ -142,8 +142,17 @@ const widget_render_scratch = @import("lazy_tls.zig").LazyTls(WidgetRenderScratc
142
142
  /// the entry points record it here.
143
143
  threadlocal var scrim_viewport: ?geometry.RectF = null;
144
144
 
145
+ /// Visible bounds for the direct widget-tree walk, in the coordinate
146
+ /// space active at the current recursion depth. The layout walk derives
147
+ /// the same value from retained parent links; the direct walk carries it
148
+ /// alongside the builder transform/clip stack so code paragraphs use the
149
+ /// bounded emitter through both public rendering entry points.
150
+ threadlocal var tree_visible_bounds: ?geometry.RectF = null;
151
+
145
152
  pub fn emitWidgetTree(builder: *Builder, widget: Widget, tokens: DesignTokens) Error!void {
146
153
  scrim_viewport = widget.frame.normalized();
154
+ tree_visible_bounds = widget.frame.normalized();
155
+ defer tree_visible_bounds = null;
147
156
  try emitWidgetDepth(builder, widget, tokens, 0);
148
157
  }
149
158
 
@@ -170,6 +179,64 @@ pub fn widgetLayoutRootBounds(layout: anytype) ?geometry.RectF {
170
179
  return bounds;
171
180
  }
172
181
 
182
+ /// Accumulated transform active while `node_index` emits. Anchored surfaces
183
+ /// are hoisted into the late top-level pass, so their original ancestors do
184
+ /// not contribute transforms there.
185
+ fn widgetLayoutNodeEmissionTransform(layout: anytype, node_index: usize) ?Affine {
186
+ if (node_index >= layout.nodes.len) return null;
187
+ var indices: [widget_layout.max_widget_depth]usize = undefined;
188
+ var len: usize = 0;
189
+ var current: ?usize = node_index;
190
+ while (current) |index| {
191
+ if (index >= layout.nodes.len or len >= indices.len) return null;
192
+ indices[len] = index;
193
+ len += 1;
194
+ if (widget_tree.widgetIsAnchored(layout.nodes[index].widget)) break;
195
+ current = layout.nodes[index].parent_index;
196
+ }
197
+
198
+ var transform = Affine.identity();
199
+ while (len > 0) {
200
+ len -= 1;
201
+ transform = transform.multiply(widgetTransform(layout.nodes[indices[len]].widget));
202
+ }
203
+ return transform;
204
+ }
205
+
206
+ /// The rectangular part of one layout node that can reach the surface,
207
+ /// returned in the node's untransformed layout coordinate space. Window
208
+ /// and ancestor clip bounds are intersected in device space, then mapped
209
+ /// back through the exact transform stack active at node emission. Code
210
+ /// paragraphs use this so transformed sources neither disappear nor lose
211
+ /// later pages while still charging only visible runs to display budgets.
212
+ fn widgetLayoutNodeVisibleBounds(layout: anytype, node_index: usize, bounds: geometry.RectF) ?geometry.RectF {
213
+ if (node_index >= layout.nodes.len) return null;
214
+ var device_visible = (widgetLayoutRootBounds(layout) orelse return null).normalized();
215
+
216
+ var current = node_index;
217
+ while (true) {
218
+ // Hoisted anchored surfaces escape their original ancestor clips,
219
+ // but the window intersection still bounds display-list demand.
220
+ if (widget_tree.widgetIsAnchored(layout.nodes[current].widget)) break;
221
+ const parent_index = layout.nodes[current].parent_index orelse break;
222
+ if (parent_index >= layout.nodes.len) return null;
223
+ const parent = layout.nodes[parent_index];
224
+ if (widgetClipsContent(parent.widget)) {
225
+ const parent_transform = widgetLayoutNodeEmissionTransform(layout, parent_index) orelse return null;
226
+ const device_clip = parent_transform.transformRect(parent.frame.normalized());
227
+ device_visible = geometry.RectF.intersection(device_visible, device_clip);
228
+ if (device_visible.isEmpty()) return null;
229
+ }
230
+ current = parent_index;
231
+ }
232
+
233
+ const transform = widgetLayoutNodeEmissionTransform(layout, node_index) orelse return null;
234
+ const inverse = transform.inverse() orelse return null;
235
+ const local_visible = inverse.transformRect(device_visible);
236
+ const clipped = geometry.RectF.intersection(bounds.normalized(), local_visible.normalized());
237
+ return if (clipped.isEmpty()) null else clipped;
238
+ }
239
+
173
240
  /// The late z-pass for anchored floating surfaces: they are skipped by
174
241
  /// the in-tree walk above and emitted here LAST, at the top level, so no
175
242
  /// ancestor scroll/clip region crops them (window-clipped, not
@@ -199,9 +266,19 @@ fn emitWidgetDepth(builder: *Builder, widget: Widget, tokens: DesignTokens, dept
199
266
  const wrap_transform = !affinesEqual(transform, Affine.identity());
200
267
  const inverse_transform = if (wrap_transform) transform.inverse() orelse return error.InvalidTransform else Affine.identity();
201
268
  if (wrap_opacity) try builder.pushOpacity(opacity);
202
- if (wrap_transform) try builder.transform(transform);
203
- try emitWidgetDepthContent(builder, widget, tokens, depth);
204
- if (wrap_transform) try builder.transform(inverse_transform);
269
+ if (wrap_transform) {
270
+ const parent_visible_bounds = tree_visible_bounds;
271
+ defer tree_visible_bounds = parent_visible_bounds;
272
+ tree_visible_bounds = if (parent_visible_bounds) |bounds|
273
+ inverse_transform.transformRect(bounds).normalized()
274
+ else
275
+ null;
276
+ try builder.transform(transform);
277
+ try emitWidgetDepthContent(builder, widget, tokens, depth);
278
+ try builder.transform(inverse_transform);
279
+ } else {
280
+ try emitWidgetDepthContent(builder, widget, tokens, depth);
281
+ }
205
282
  if (wrap_opacity) try builder.popOpacity();
206
283
  }
207
284
 
@@ -235,7 +312,21 @@ fn emitWidgetDepthContent(builder: *Builder, widget: Widget, tokens: DesignToken
235
312
  .resizable, .panel => try emitPanelWidget(builder, paint_widget, tokens, depth),
236
313
  .popover => try emitPopoverWidget(builder, paint_widget, tokens, depth),
237
314
  .menu_surface, .dropdown_menu => try emitMenuSurfaceWidget(builder, paint_widget, tokens, depth),
238
- .text => try emitTextWidget(builder, paint_widget, tokens),
315
+ .text => {
316
+ if (isSyntaxCodeParagraph(paint_widget)) {
317
+ if (tree_visible_bounds) |visible_bounds| {
318
+ const clipped = geometry.RectF.intersection(
319
+ paint_widget.frame.normalized(),
320
+ visible_bounds.normalized(),
321
+ );
322
+ if (!clipped.isEmpty()) {
323
+ try emitVisibleCodeTextSpansWidget(builder, paint_widget, tokens, clipped);
324
+ }
325
+ }
326
+ } else {
327
+ try emitTextWidget(builder, paint_widget, tokens);
328
+ }
329
+ },
239
330
  .icon => try emitIconWidget(builder, paint_widget, tokens),
240
331
  .image => try emitImageWidget(builder, paint_widget),
241
332
  .media_surface => try emitMediaSurfaceWidget(builder, paint_widget),
@@ -395,6 +486,11 @@ fn buttonGroupSegmentAt(ordinal: usize, visible_total: usize) widget_model.Widge
395
486
  /// docs scene and a live app would render different bars.
396
487
  fn emitButtonGroupWidget(builder: *Builder, widget: Widget, tokens: DesignTokens, depth: usize) Error!void {
397
488
  if (!buttonGroupStampsSegments(widget, tokens)) return emitWidgetClippedChildren(builder, widget, tokens, depth);
489
+ const parent_visible_bounds = tree_visible_bounds;
490
+ defer tree_visible_bounds = parent_visible_bounds;
491
+ if (widget.layout.clip_content) {
492
+ tree_visible_bounds = visibleBoundsInsideClip(parent_visible_bounds, widgetContentClip(widget, tokens).rect);
493
+ }
398
494
  if (widget.layout.clip_content) try builder.pushClip(widgetContentClip(widget, tokens));
399
495
  var emitted: usize = 0;
400
496
  var previous: ?WidgetPaintOrder = null;
@@ -579,7 +675,15 @@ fn emitWidgetLayoutNodeContent(
579
675
  .resizable, .panel => try widget_render_surfaces.emitPanelWidgetChrome(builder, paint_widget, tokens),
580
676
  .popover => try widget_render_surfaces.emitPopoverWidgetChrome(builder, paint_widget, tokens),
581
677
  .menu_surface, .dropdown_menu => try widget_render_surfaces.emitMenuSurfaceWidgetChrome(builder, paint_widget, tokens),
582
- .text => try emitTextWidget(builder, paint_widget, tokens),
678
+ .text => {
679
+ if (isSyntaxCodeParagraph(paint_widget)) {
680
+ if (widgetLayoutNodeVisibleBounds(layout, node_index, paint_widget.frame)) |visible_bounds| {
681
+ try emitVisibleCodeTextSpansWidget(builder, paint_widget, tokens, visible_bounds);
682
+ }
683
+ } else {
684
+ try emitTextWidget(builder, paint_widget, tokens);
685
+ }
686
+ },
583
687
  .icon => try emitIconWidget(builder, paint_widget, tokens),
584
688
  .image => try emitImageWidget(builder, paint_widget),
585
689
  .media_surface => try emitMediaSurfaceWidget(builder, paint_widget),
@@ -896,6 +1000,9 @@ fn emitMenuSurfaceWidget(builder: *Builder, widget: Widget, tokens: DesignTokens
896
1000
  }
897
1001
 
898
1002
  fn emitScrollViewWidget(builder: *Builder, widget: Widget, tokens: DesignTokens, depth: usize) Error!void {
1003
+ const parent_visible_bounds = tree_visible_bounds;
1004
+ defer tree_visible_bounds = parent_visible_bounds;
1005
+ tree_visible_bounds = visibleBoundsInsideClip(parent_visible_bounds, widget.frame);
899
1006
  try builder.pushClip(.{ .id = widgetPartId(widget.id, 1), .rect = widget.frame });
900
1007
  try emitWidgetChildren(builder, widget.children, tokens, depth);
901
1008
  try builder.popClip();
@@ -913,9 +1020,22 @@ fn emitScrollViewWidget(builder: *Builder, widget: Widget, tokens: DesignTokens,
913
1020
  }
914
1021
 
915
1022
  fn emitWidgetClippedChildren(builder: *Builder, widget: Widget, tokens: DesignTokens, depth: usize) Error!void {
916
- if (widget.layout.clip_content) try builder.pushClip(widgetContentClip(widget, tokens));
1023
+ if (!widget.layout.clip_content) return emitWidgetChildren(builder, widget.children, tokens, depth);
1024
+ const parent_visible_bounds = tree_visible_bounds;
1025
+ defer tree_visible_bounds = parent_visible_bounds;
1026
+ const clip = widgetContentClip(widget, tokens);
1027
+ tree_visible_bounds = visibleBoundsInsideClip(parent_visible_bounds, clip.rect);
1028
+ try builder.pushClip(clip);
917
1029
  try emitWidgetChildren(builder, widget.children, tokens, depth);
918
- if (widget.layout.clip_content) try builder.popClip();
1030
+ try builder.popClip();
1031
+ }
1032
+
1033
+ fn visibleBoundsInsideClip(bounds: ?geometry.RectF, clip: geometry.RectF) ?geometry.RectF {
1034
+ const clipped = geometry.RectF.intersection(
1035
+ (bounds orelse return null).normalized(),
1036
+ clip.normalized(),
1037
+ );
1038
+ return if (clipped.isEmpty()) null else clipped;
919
1039
  }
920
1040
 
921
1041
  fn widgetScrollSemantics(layout: anytype, node_index: usize) widget_semantics.WidgetScrollSemantics {
@@ -992,11 +1112,22 @@ const textWrapMaxWidth = widget_metrics.textWrapMaxWidth;
992
1112
  /// of a `.text` widget (plain or span paragraph). Command ids are hashed
993
1113
  /// per line ordinal like span runs, so retained diffing stays stable.
994
1114
  fn emitStaticTextSelection(builder: *Builder, widget: Widget, tokens: DesignTokens) Error!void {
1115
+ return emitStaticTextSelectionBounded(builder, widget, tokens, builder.commands.len);
1116
+ }
1117
+
1118
+ fn emitStaticTextSelectionBounded(
1119
+ builder: *Builder,
1120
+ widget: Widget,
1121
+ tokens: DesignTokens,
1122
+ command_ceiling: usize,
1123
+ ) Error!void {
1124
+ if (builder.len >= command_ceiling) return;
995
1125
  const range = widget_access.widgetTextSelectionRange(widget) orelse return;
996
1126
  if (range.isCollapsed(widget.text.len)) return;
997
1127
  var rect_buffer: [widget_text_select.max_static_text_selection_rects]text_model.TextSelectionRect = undefined;
998
1128
  const rects = widget_text_select.staticTextSelectionRects(widget, tokens, range, &rect_buffer);
999
1129
  for (rects, 0..) |selection, ordinal| {
1130
+ if (builder.len >= command_ceiling) break;
1000
1131
  try builder.fillRoundedRect(.{
1001
1132
  .id = textSelectionCommandId(widget.id, ordinal),
1002
1133
  .rect = pixelSnapGeometryRect(tokens, selection.rect),
@@ -1011,14 +1142,20 @@ fn emitStaticTextSelection(builder: *Builder, widget: Widget, tokens: DesignToke
1011
1142
  /// decorations get stable hashed command ids derived from the widget id
1012
1143
  /// and their ordinal, so retained diffing works across frames.
1013
1144
  fn emitTextSpansWidget(builder: *Builder, widget: Widget, tokens: DesignTokens) Error!void {
1014
- const content = widget.frame.inset(widget.layout.padding);
1145
+ const content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
1146
+ const layout_options = widget_metrics.widgetTextSpanLayoutOptions(
1147
+ widget,
1148
+ tokens,
1149
+ textWrapMaxWidth(tokens, content.width),
1150
+ );
1015
1151
  var runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
1016
1152
  const layout = text_spans_model.layoutTextSpans(
1017
1153
  widget.spans,
1018
- widget_metrics.widgetTextSpanLayoutOptions(widget, tokens, textWrapMaxWidth(tokens, content.width)),
1154
+ layout_options,
1019
1155
  &runs,
1020
1156
  );
1021
1157
 
1158
+ try emitCodeLineNumberGutter(builder, widget, tokens, content, widget.frame, layout_options, null);
1022
1159
  // Span background highlights (intra-line diff emphasis): one
1023
1160
  // full-line-height rect per run, the same geometry selection rects
1024
1161
  // use, painted before selection and glyphs. Edge-snapped rects of
@@ -1109,6 +1246,314 @@ fn emitTextSpansWidget(builder: *Builder, widget: Widget, tokens: DesignTokens)
1109
1246
  }
1110
1247
  }
1111
1248
 
1249
+ fn isSyntaxColor(color: text_spans_model.TextSpanColor) bool {
1250
+ return switch (color) {
1251
+ .syntax_plain,
1252
+ .syntax_comment,
1253
+ .syntax_keyword,
1254
+ .syntax_literal,
1255
+ .syntax_function,
1256
+ .syntax_property,
1257
+ .syntax_constant,
1258
+ => true,
1259
+ else => false,
1260
+ };
1261
+ }
1262
+
1263
+ /// `Ui.code` lowers to ordinary text widgets whose spans are all monospace
1264
+ /// syntax-token runs. Keep that marker structural instead of adding another
1265
+ /// public widget kind solely for an emission optimization.
1266
+ fn isSyntaxCodeParagraph(widget: Widget) bool {
1267
+ if (widget.kind != .text or widget.spans.len == 0) return false;
1268
+ for (widget.spans) |span| {
1269
+ if (!span.monospace or
1270
+ !isSyntaxColor(span.color orelse return false) or
1271
+ span.background != null or
1272
+ span.underline or
1273
+ span.strikethrough or
1274
+ span.link.len != 0)
1275
+ {
1276
+ return false;
1277
+ }
1278
+ }
1279
+ return true;
1280
+ }
1281
+
1282
+ // A code surface shares the frame's fixed display-list stores with every
1283
+ // widget emitted around it. Hold back the same practical tail as the
1284
+ // terminal painter: enough commands and referenced text for trailing
1285
+ // siblings, transform/clip epilogues, and window chrome. Small direct
1286
+ // builders retain seven eighths of their capacity so focused unit tests
1287
+ // remain representative while still leaving their enclosing epilogue room.
1288
+ const code_widget_command_reserve: usize = 256;
1289
+ const code_widget_text_reserve: usize = 8192;
1290
+
1291
+ const CodeEmissionBudget = struct {
1292
+ command_ceiling: usize,
1293
+ text_ceiling: usize,
1294
+ text_total: usize,
1295
+
1296
+ fn init(builder: *const Builder) CodeEmissionBudget {
1297
+ const command_reserve = @min(
1298
+ code_widget_command_reserve,
1299
+ @max(@as(usize, 1), builder.commands.len / 8),
1300
+ );
1301
+ return .{
1302
+ .command_ceiling = builder.commands.len -| command_reserve,
1303
+ .text_ceiling = canvas.max_display_list_text_bytes -| code_widget_text_reserve,
1304
+ .text_total = displayListTextBytes(builder.displayList()),
1305
+ };
1306
+ }
1307
+
1308
+ fn hasCommand(self: CodeEmissionBudget, builder: *const Builder) bool {
1309
+ return builder.len < self.command_ceiling;
1310
+ }
1311
+
1312
+ fn remainingText(self: CodeEmissionBudget) usize {
1313
+ return self.text_ceiling -| self.text_total;
1314
+ }
1315
+
1316
+ fn chargeText(self: *CodeEmissionBudget, len: usize) void {
1317
+ self.text_total += len;
1318
+ }
1319
+ };
1320
+
1321
+ fn displayListTextBytes(list: canvas.DisplayList) usize {
1322
+ var total: usize = 0;
1323
+ for (list.commands) |command| {
1324
+ if (command == .draw_text) total += command.draw_text.text.len;
1325
+ }
1326
+ return total;
1327
+ }
1328
+
1329
+ /// Keep a text-budget truncation on a UTF-8 scalar boundary. Code source
1330
+ /// accepts arbitrary bytes, so invalid leading/continuation bytes simply
1331
+ /// degrade to the maximal prefix the display store can retain.
1332
+ fn codeTextPrefix(text: []const u8, max_len: usize) []const u8 {
1333
+ var end = @min(text.len, max_len);
1334
+ while (end > 0 and end < text.len and text[end] & 0xc0 == 0x80) end -= 1;
1335
+ return text[0..end];
1336
+ }
1337
+
1338
+ /// Viewport-aware code emission: the full source remains in retained
1339
+ /// paragraph widgets for layout, selection, copy, and scroll extents, while
1340
+ /// the display list contains only line runs that intersect the current
1341
+ /// window/scroll clip. Long no-wrap runs are sliced horizontally as well.
1342
+ fn emitVisibleCodeTextSpansWidget(
1343
+ builder: *Builder,
1344
+ widget: Widget,
1345
+ tokens: DesignTokens,
1346
+ visible_bounds: geometry.RectF,
1347
+ ) Error!void {
1348
+ const content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
1349
+ const layout_options = widget_metrics.widgetTextSpanLayoutOptions(
1350
+ widget,
1351
+ tokens,
1352
+ textWrapMaxWidth(tokens, content.width),
1353
+ );
1354
+ const line_height = text_spans_model.textSpanLineHeight(widget.spans, layout_options);
1355
+ const visible_line: usize = if (line_height > 0 and
1356
+ std.math.isFinite(line_height) and
1357
+ std.math.isFinite(visible_bounds.y - content.y) and
1358
+ visible_bounds.y > content.y)
1359
+ @intFromFloat(@floor((visible_bounds.y - content.y) / line_height))
1360
+ else
1361
+ 0;
1362
+ const last_visible_line: usize = if (line_height > 0 and
1363
+ std.math.isFinite(line_height) and
1364
+ std.math.isFinite(visible_bounds.maxY() - content.y) and
1365
+ visible_bounds.maxY() > content.y)
1366
+ @intFromFloat(@floor((visible_bounds.maxY() - content.y) / line_height))
1367
+ else
1368
+ visible_line;
1369
+ var runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
1370
+ var budget = CodeEmissionBudget.init(builder);
1371
+ if (!budget.hasCommand(builder)) return;
1372
+
1373
+ try emitCodeLineNumberGutter(builder, widget, tokens, content, visible_bounds, layout_options, &budget);
1374
+ try emitStaticTextSelectionBounded(builder, widget, tokens, budget.command_ceiling);
1375
+ if (!budget.hasCommand(builder) or budget.remainingText() == 0) return;
1376
+ var page_first_line = visible_line -| 1;
1377
+ while (true) {
1378
+ const layout = text_spans_model.layoutTextSpansFromLine(
1379
+ widget.spans,
1380
+ layout_options,
1381
+ page_first_line,
1382
+ &runs,
1383
+ );
1384
+ for (layout.runs) |run| {
1385
+ if (run.text.len == 0) continue;
1386
+ const local_bounds = text_spans_model.textSpanRunBounds(layout, run);
1387
+ const run_bounds = geometry.RectF.init(
1388
+ content.x + local_bounds.x,
1389
+ content.y + local_bounds.y,
1390
+ local_bounds.width,
1391
+ local_bounds.height,
1392
+ );
1393
+ if (!run_bounds.intersects(visible_bounds)) continue;
1394
+
1395
+ const span = widget.spans[run.span_index];
1396
+ const absolute_x = content.x + run.x;
1397
+ const visible = text_spans_model.textSpanRunVisibleSlice(
1398
+ span,
1399
+ run,
1400
+ layout_options,
1401
+ visible_bounds.x - absolute_x,
1402
+ visible_bounds.maxX() - absolute_x,
1403
+ ) orelse continue;
1404
+ if (!budget.hasCommand(builder)) return;
1405
+ const admitted_text = codeTextPrefix(visible.text, budget.remainingText());
1406
+ if (admitted_text.len == 0) return;
1407
+ const color = text_spans_model.textSpanColorValue(tokens.colors, span.color.?);
1408
+ const origin = pixelSnapTextPoint(tokens, geometry.PointF.init(absolute_x + visible.x, content.y + run.baseline));
1409
+ try builder.drawText(.{
1410
+ .id = codeTextSpanRunCommandId(widget, run),
1411
+ .font_id = run.font_id,
1412
+ .size = run.size,
1413
+ .origin = origin,
1414
+ .color = color,
1415
+ .text = admitted_text,
1416
+ .text_layout = .{
1417
+ .max_width = 0,
1418
+ .line_height = layout.line_height,
1419
+ .wrap = .none,
1420
+ .alignment = .start,
1421
+ .measure = tokens.text_measure,
1422
+ },
1423
+ });
1424
+ budget.chargeText(admitted_text.len);
1425
+ }
1426
+
1427
+ const next_first_line = page_first_line +| text_spans_model.max_text_span_lines_per_paragraph;
1428
+ if (next_first_line <= page_first_line or
1429
+ next_first_line > last_visible_line or
1430
+ next_first_line >= layout.line_count)
1431
+ {
1432
+ break;
1433
+ }
1434
+ page_first_line = next_first_line;
1435
+ }
1436
+ }
1437
+
1438
+ /// Muted logical-line markers for one coherent code paragraph. Each
1439
+ /// logical line is measured independently with the same monospace layout
1440
+ /// options; summing those wrapped extents places the next marker on the
1441
+ /// exact first visual line occupied by its source.
1442
+ fn emitCodeLineNumberGutter(
1443
+ builder: *Builder,
1444
+ widget: Widget,
1445
+ tokens: DesignTokens,
1446
+ content: geometry.RectF,
1447
+ visible_bounds: geometry.RectF,
1448
+ layout_options: text_spans_model.TextSpanLayoutOptions,
1449
+ budget: ?*CodeEmissionBudget,
1450
+ ) Error!void {
1451
+ if (widget.code_line_number_digits == 0) return;
1452
+ const line_height = text_spans_model.textSpanLineHeight(widget.spans, layout_options);
1453
+ if (line_height <= 0 or !std.math.isFinite(line_height)) return;
1454
+
1455
+ const padded = widget.frame.inset(widget.layout.padding);
1456
+ const marker_width = @max(0, content.x - 12 - padded.x);
1457
+ const digits = @min(@as(usize, widget.code_line_number_digits), 20);
1458
+ var line_runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
1459
+ var logical_line: usize = 1;
1460
+ var visual_line: usize = 0;
1461
+ var line_start: usize = 0;
1462
+ while (line_start <= widget.text.len) : (logical_line += 1) {
1463
+ // A terminal newline closes the preceding painted line; the span
1464
+ // breaker intentionally does not reserve another empty visual line.
1465
+ if (line_start == widget.text.len and widget.text.len > 0) break;
1466
+ const newline = std.mem.indexOfScalarPos(u8, widget.text, line_start, '\n');
1467
+ const line_end = newline orelse widget.text.len;
1468
+ const baseline = content.y + layout_options.size +
1469
+ @as(f32, @floatFromInt(visual_line)) * line_height;
1470
+ const marker_bounds = geometry.RectF.init(
1471
+ padded.x,
1472
+ baseline - layout_options.size,
1473
+ marker_width,
1474
+ line_height,
1475
+ );
1476
+ if (marker_bounds.intersects(visible_bounds)) {
1477
+ const marker_text = codeLineNumberText(logical_line, digits);
1478
+ if (budget) |admission| {
1479
+ if (!admission.hasCommand(builder)) return;
1480
+ if (marker_text.len > admission.remainingText()) return;
1481
+ }
1482
+ try builder.drawText(.{
1483
+ .id = codeLineNumberCommandId(widget.id, logical_line),
1484
+ .font_id = tokens.typography.mono_font_id,
1485
+ .size = layout_options.size,
1486
+ .origin = pixelSnapTextPoint(tokens, geometry.PointF.init(padded.x, baseline)),
1487
+ .color = tokens.colors.text_muted,
1488
+ .text = marker_text,
1489
+ .text_layout = .{
1490
+ .max_width = marker_width,
1491
+ .line_height = line_height,
1492
+ .wrap = .none,
1493
+ .alignment = .end,
1494
+ .measure = tokens.text_measure,
1495
+ },
1496
+ });
1497
+ if (budget) |admission| admission.chargeText(marker_text.len);
1498
+ }
1499
+
1500
+ const line = widget.text[line_start..line_end];
1501
+ if (line.len == 0) {
1502
+ visual_line += 1;
1503
+ } else {
1504
+ const line_spans = [_]text_spans_model.TextSpan{.{
1505
+ .text = line,
1506
+ .monospace = true,
1507
+ .color = .syntax_plain,
1508
+ }};
1509
+ const line_layout = text_spans_model.layoutTextSpans(
1510
+ &line_spans,
1511
+ layout_options,
1512
+ &line_runs,
1513
+ );
1514
+ visual_line += @max(1, line_layout.line_count);
1515
+ }
1516
+ if (newline == null) break;
1517
+ line_start = line_end + 1;
1518
+ }
1519
+ }
1520
+
1521
+ const code_line_number_texts = blk: {
1522
+ var values: [128][3]u8 = @splat(@splat(' '));
1523
+ for (&values, 1..) |*text, line_number| {
1524
+ var value = line_number;
1525
+ var cursor: usize = text.len;
1526
+ while (cursor > 0 and value > 0) {
1527
+ cursor -= 1;
1528
+ text[cursor] = '0' + @as(u8, @intCast(value % 10));
1529
+ value /= 10;
1530
+ }
1531
+ }
1532
+ break :blk values;
1533
+ };
1534
+
1535
+ fn codeLineNumberText(logical_line: usize, digits: usize) []const u8 {
1536
+ if (logical_line == 0 or logical_line > code_line_number_texts.len) return "";
1537
+ const text = &code_line_number_texts[logical_line - 1];
1538
+ const len = @min(digits, text.len);
1539
+ return text[text.len - len ..];
1540
+ }
1541
+
1542
+ fn codeTextSpanRunCommandId(widget: Widget, run: text_spans_model.TextSpanRun) ObjectId {
1543
+ const range = text_spans_model.textSpanRunParagraphRange(widget.text, run) orelse
1544
+ text_model.TextRange.init(0, run.text.len);
1545
+ var hasher = std.hash.Wyhash.init(0x5eed_59a2_0000_0011);
1546
+ hasher.update(std.mem.asBytes(&widget.id));
1547
+ hasher.update(std.mem.asBytes(&run.line_index));
1548
+ hasher.update(std.mem.asBytes(&range.start));
1549
+ const value = hasher.final();
1550
+ return if (value == 0) 1 else value;
1551
+ }
1552
+
1553
+ fn codeLineNumberCommandId(widget_id: ObjectId, logical_line: usize) ObjectId {
1554
+ return textSpanCommandId(0x5eed_59a2_0000_0012, widget_id, logical_line);
1555
+ }
1556
+
1112
1557
  pub fn textSpanRunCommandId(widget_id: ObjectId, ordinal: usize) ObjectId {
1113
1558
  return textSpanCommandId(0x5eed_59a2_0000_0001, widget_id, ordinal);
1114
1559
  }
@@ -43,6 +43,7 @@ pub const max_widget_text_range_rects: usize = 4;
43
43
  pub const widgetControlHeight = widget_metrics.widgetControlHeight;
44
44
  pub const WidgetTextGeometry = widget_text_input.WidgetTextGeometry;
45
45
  pub const textSelectionForWidgetPoint = widget_text_input.textSelectionForWidgetPoint;
46
+ pub const textCaretPositionForWidgetPoint = widget_text_input.textCaretPositionForWidgetPoint;
46
47
  pub const textOffsetForWidgetPoint = widget_text_input.textOffsetForWidgetPoint;
47
48
  pub const textInputViewportForWidget = widget_text_input.textInputViewportForWidget;
48
49
  pub const textInputClearButtonRect = widget_text_input.textInputClearButtonRect;
@@ -17,7 +17,7 @@ const TextRange = text_model.TextRange;
17
17
  const TextSelection = text_model.TextSelection;
18
18
  const DesignTokens = token_model.DesignTokens;
19
19
  const Widget = widget_model.Widget;
20
- const snapTextSelection = text_model.snapTextSelection;
20
+ const snapTextCaretSelection = text_model.snapTextCaretSelection;
21
21
  const snapTextOffset = text_model.snapTextOffset;
22
22
  const snapTextRange = text_model.snapTextRange;
23
23
  const measureTextWidthForFont = text_model.measureTextWidthForFont;
@@ -25,8 +25,8 @@ const nextTextLineEnd = text_model.nextTextLineEnd;
25
25
  const isTextBreakByte = text_model.isTextBreakByte;
26
26
  const textLineRange = text_model.textLineRange;
27
27
  const textLineCaretX = text_model.textLineCaretX;
28
- const layoutTextCaretRect = text_model.layoutTextCaretRect;
29
- const layoutTextOffsetForPoint = text_model.layoutTextOffsetForPoint;
28
+ const layoutTextCaretRectWithAffinity = text_model.layoutTextCaretRectWithAffinity;
29
+ const layoutTextCaretPositionForPoint = text_model.layoutTextCaretPositionForPoint;
30
30
  const TextLineIterator = text_model.TextLineIterator;
31
31
 
32
32
  pub fn widgetPlaceholder(widget: Widget) []const u8 {
@@ -128,15 +128,20 @@ pub fn persistWidgetTextInputPresentedText(builder: *Builder, raw: []const u8, p
128
128
  }
129
129
 
130
130
  pub fn textSelectionForWidgetPoint(widget: Widget, point: geometry.PointF, anchor: ?usize, tokens: DesignTokens) ?TextSelection {
131
- const offset = textOffsetForWidgetPoint(widget, point, tokens) orelse return null;
131
+ const position = textCaretPositionForWidgetPoint(widget, point, tokens) orelse return null;
132
132
  const selection = if (anchor) |anchor_offset|
133
- TextSelection{ .anchor = anchor_offset, .focus = offset }
133
+ TextSelection{ .anchor = anchor_offset, .focus = position.offset, .affinity = position.affinity }
134
134
  else
135
- TextSelection.collapsed(offset);
136
- return snapTextSelection(widget.text, selection);
135
+ TextSelection.collapsedAt(position);
136
+ return snapTextCaretSelection(widget.text, selection);
137
137
  }
138
138
 
139
139
  pub fn textOffsetForWidgetPoint(widget: Widget, point: geometry.PointF, tokens: DesignTokens) ?usize {
140
+ const position = textCaretPositionForWidgetPoint(widget, point, tokens) orelse return null;
141
+ return position.offset;
142
+ }
143
+
144
+ pub fn textCaretPositionForWidgetPoint(widget: Widget, point: geometry.PointF, tokens: DesignTokens) ?text_model.TextCaretPosition {
140
145
  if (!widget_access.widgetTextInputKind(widget.kind)) return null;
141
146
  if (widget.state.disabled) return null;
142
147
  const text_size = widgetTextInputSize(widget, tokens);
@@ -144,7 +149,8 @@ pub fn textOffsetForWidgetPoint(widget: Widget, point: geometry.PointF, tokens:
144
149
  const layout_options = widgetTextInputLayoutOptions(widget, tokens, text_size, text_inset);
145
150
  const origin = widgetTextInputOrigin(widget, tokens, text_size, text_inset, layout_options);
146
151
  const draw_text = widgetTextInputDrawText(widget, tokens, text_size, origin, tokens.colors.text, layout_options);
147
- return layoutTextOffsetForPoint(draw_text, layout_options, point);
152
+ const position = layoutTextCaretPositionForPoint(draw_text, layout_options, point) orelse return null;
153
+ return text_model.snapTextCaretPosition(widget.text, position);
148
154
  }
149
155
 
150
156
  pub fn widgetTextInputSize(widget: Widget, tokens: DesignTokens) f32 {
@@ -371,8 +377,13 @@ fn widgetTextInputLineCount(widget: Widget, font_id: FontId, text_size: f32, opt
371
377
  count += 1;
372
378
  if (end >= text.len) break;
373
379
  start = end;
374
- if (start < text.len and text[start] == '\n') start += 1;
375
- while (options.wrap == .word and start < text.len and isTextBreakByte(text[start])) start += 1;
380
+ if (start < text.len and text[start] == '\n') {
381
+ // Leading whitespace after a hard break belongs to the next
382
+ // editable line; only a soft wrap elides separators.
383
+ start += 1;
384
+ } else {
385
+ while (options.wrap == .word and start < text.len and isTextBreakByte(text[start])) start += 1;
386
+ }
376
387
  }
377
388
  return @max(1, count);
378
389
  }
@@ -478,7 +489,8 @@ pub fn textGeometryForWidget(widget: Widget, tokens: DesignTokens) WidgetTextGeo
478
489
 
479
490
  if (widget_access.widgetTextSelectionRange(widget)) |range| {
480
491
  if (range.isCollapsed(widget.text.len)) {
481
- value.caret_bounds = layoutTextCaretRect(draw_text, layout_options, range.start);
492
+ const affinity = if (widget.text_selection) |selection| selection.affinity else .upstream;
493
+ value.caret_bounds = layoutTextCaretRectWithAffinity(draw_text, layout_options, range.start, affinity);
482
494
  } else {
483
495
  const bounds = textRangeBounds(draw_text, layout_options, range);
484
496
  value.selection_bounds = bounds.bounds;
@@ -57,7 +57,7 @@ pub fn staticTextSelectionForWidgetPoint(
57
57
  pub fn staticTextOffsetForWidgetPoint(widget: Widget, point: geometry.PointF, tokens: DesignTokens) ?usize {
58
58
  if (!widgetStaticTextSelectable(widget)) return null;
59
59
  if (widget.spans.len > 0) {
60
- const content = widget.frame.inset(widget.layout.padding);
60
+ const content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
61
61
  const options = widget_metrics.widgetTextSpanLayoutOptions(widget, tokens, content.width);
62
62
  return text_spans_model.textSpanOffsetForPoint(
63
63
  widget.text,
@@ -82,7 +82,7 @@ pub fn staticTextSelectionRects(
82
82
  ) []const TextSelectionRect {
83
83
  if (widget.kind != .text or widget.text.len == 0) return output[0..0];
84
84
  if (widget.spans.len > 0) {
85
- const content = widget.frame.inset(widget.layout.padding);
85
+ const content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
86
86
  const options = widget_metrics.widgetTextSpanLayoutOptions(widget, tokens, content.width);
87
87
  const rects = text_spans_model.textSpanSelectionRects(widget.text, widget.spans, options, range, output);
88
88
  for (output[0..rects.len]) |*rect| {