@native-sdk/cli 0.6.3 → 0.7.1

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 +65 -91
  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 +25 -14
  6. package/packages/core/src/checker.ts +39 -0
  7. package/packages/core/src/emitter.ts +125 -1
  8. package/skill-data/native-ui/SKILL.md +23 -6
  9. package/src/platform/macos/appkit_host.m +25 -1
  10. package/src/platform/macos/cef_host.mm +24 -2
  11. package/src/platform/macos/root.zig +13 -0
  12. package/src/primitives/canvas/code.zig +1008 -0
  13. package/src/primitives/canvas/code_tests.zig +1912 -0
  14. package/src/primitives/canvas/events.zig +111 -1
  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 +168 -6
  18. package/src/primitives/canvas/root.zig +8 -2
  19. package/src/primitives/canvas/tests.zig +1 -0
  20. package/src/primitives/canvas/text.zig +6 -0
  21. package/src/primitives/canvas/text_measure_cache.zig +4 -4
  22. package/src/primitives/canvas/text_span_tests.zig +254 -0
  23. package/src/primitives/canvas/text_spans.zig +556 -32
  24. package/src/primitives/canvas/themes/geist.zig +29 -0
  25. package/src/primitives/canvas/tokens.zig +72 -2
  26. package/src/primitives/canvas/ui.zig +400 -22
  27. package/src/primitives/canvas/ui_markup.zig +78 -7
  28. package/src/primitives/canvas/ui_markup_compiled.zig +89 -0
  29. package/src/primitives/canvas/ui_markup_compiled_tests.zig +45 -0
  30. package/src/primitives/canvas/ui_markup_contract.zig +41 -0
  31. package/src/primitives/canvas/ui_markup_view.zig +89 -0
  32. package/src/primitives/canvas/ui_markup_view_tests.zig +154 -3
  33. package/src/primitives/canvas/ui_schema.zig +30 -6
  34. package/src/primitives/canvas/ui_schema_tests.zig +13 -10
  35. package/src/primitives/canvas/ui_tests.zig +26 -0
  36. package/src/primitives/canvas/widget_invalidation.zig +4 -0
  37. package/src/primitives/canvas/widget_layout.zig +57 -8
  38. package/src/primitives/canvas/widget_layout_tests.zig +35 -0
  39. package/src/primitives/canvas/widget_metrics.zig +35 -1
  40. package/src/primitives/canvas/widget_render.zig +1077 -11
  41. package/src/primitives/canvas/widget_render_controls.zig +4 -4
  42. package/src/primitives/canvas/widget_runtime.zig +2 -0
  43. package/src/primitives/canvas/widget_text_input.zig +165 -8
  44. package/src/primitives/canvas/widget_text_select.zig +2 -2
  45. package/src/primitives/canvas/widget_tree.zig +6 -5
  46. package/src/primitives/canvas/widgets.zig +38 -0
  47. package/src/root.zig +1 -0
  48. package/src/runtime/canvas_budget_edge_tests.zig +3 -2
  49. package/src/runtime/canvas_limits.zig +13 -6
  50. package/src/runtime/canvas_widget_clipboard_tests.zig +137 -4
  51. package/src/runtime/canvas_widget_context_menu.zig +17 -2
  52. package/src/runtime/canvas_widget_event_tests.zig +18 -14
  53. package/src/runtime/canvas_widget_events.zig +58 -21
  54. package/src/runtime/canvas_widget_runtime.zig +112 -6
  55. package/src/runtime/canvas_widget_scroll_driver_tests.zig +59 -0
  56. package/src/runtime/canvas_widget_split_tree_tests.zig +100 -0
  57. package/src/runtime/canvas_widget_state.zig +27 -0
  58. package/src/runtime/canvas_widget_text_tests.zig +383 -0
  59. package/src/runtime/core.zig +15 -5
  60. package/src/runtime/gpu_surface_events.zig +12 -12
  61. package/src/runtime/view.zig +61 -19
  62. package/src/runtime/view_widget_scroll.zig +48 -18
  63. package/src/runtime/view_widget_text.zig +248 -17
  64. package/src/runtime/window_view_runtime.zig +9 -0
@@ -4,6 +4,7 @@ const canvas = @import("root.zig");
4
4
  const drawing_model = @import("drawing.zig");
5
5
  const text_model = @import("text.zig");
6
6
  const text_spans_model = @import("text_spans.zig");
7
+ const code_model = @import("code.zig");
7
8
  const token_model = @import("tokens.zig");
8
9
  const widget_model = @import("widgets.zig");
9
10
  const event_model = @import("events.zig");
@@ -142,8 +143,17 @@ const widget_render_scratch = @import("lazy_tls.zig").LazyTls(WidgetRenderScratc
142
143
  /// the entry points record it here.
143
144
  threadlocal var scrim_viewport: ?geometry.RectF = null;
144
145
 
146
+ /// Visible bounds for the direct widget-tree walk, in the coordinate
147
+ /// space active at the current recursion depth. The layout walk derives
148
+ /// the same value from retained parent links; the direct walk carries it
149
+ /// alongside the builder transform/clip stack so code paragraphs use the
150
+ /// bounded emitter through both public rendering entry points.
151
+ threadlocal var tree_visible_bounds: ?geometry.RectF = null;
152
+
145
153
  pub fn emitWidgetTree(builder: *Builder, widget: Widget, tokens: DesignTokens) Error!void {
146
154
  scrim_viewport = widget.frame.normalized();
155
+ tree_visible_bounds = widget.frame.normalized();
156
+ defer tree_visible_bounds = null;
147
157
  try emitWidgetDepth(builder, widget, tokens, 0);
148
158
  }
149
159
 
@@ -170,6 +180,64 @@ pub fn widgetLayoutRootBounds(layout: anytype) ?geometry.RectF {
170
180
  return bounds;
171
181
  }
172
182
 
183
+ /// Accumulated transform active while `node_index` emits. Anchored surfaces
184
+ /// are hoisted into the late top-level pass, so their original ancestors do
185
+ /// not contribute transforms there.
186
+ fn widgetLayoutNodeEmissionTransform(layout: anytype, node_index: usize) ?Affine {
187
+ if (node_index >= layout.nodes.len) return null;
188
+ var indices: [widget_layout.max_widget_depth]usize = undefined;
189
+ var len: usize = 0;
190
+ var current: ?usize = node_index;
191
+ while (current) |index| {
192
+ if (index >= layout.nodes.len or len >= indices.len) return null;
193
+ indices[len] = index;
194
+ len += 1;
195
+ if (widget_tree.widgetIsAnchored(layout.nodes[index].widget)) break;
196
+ current = layout.nodes[index].parent_index;
197
+ }
198
+
199
+ var transform = Affine.identity();
200
+ while (len > 0) {
201
+ len -= 1;
202
+ transform = transform.multiply(widgetTransform(layout.nodes[indices[len]].widget));
203
+ }
204
+ return transform;
205
+ }
206
+
207
+ /// The rectangular part of one layout node that can reach the surface,
208
+ /// returned in the node's untransformed layout coordinate space. Window
209
+ /// and ancestor clip bounds are intersected in device space, then mapped
210
+ /// back through the exact transform stack active at node emission. Code
211
+ /// paragraphs use this so transformed sources neither disappear nor lose
212
+ /// later pages while still charging only visible runs to display budgets.
213
+ fn widgetLayoutNodeVisibleBounds(layout: anytype, node_index: usize, bounds: geometry.RectF) ?geometry.RectF {
214
+ if (node_index >= layout.nodes.len) return null;
215
+ var device_visible = (widgetLayoutRootBounds(layout) orelse return null).normalized();
216
+
217
+ var current = node_index;
218
+ while (true) {
219
+ // Hoisted anchored surfaces escape their original ancestor clips,
220
+ // but the window intersection still bounds display-list demand.
221
+ if (widget_tree.widgetIsAnchored(layout.nodes[current].widget)) break;
222
+ const parent_index = layout.nodes[current].parent_index orelse break;
223
+ if (parent_index >= layout.nodes.len) return null;
224
+ const parent = layout.nodes[parent_index];
225
+ if (widgetClipsContent(parent.widget)) {
226
+ const parent_transform = widgetLayoutNodeEmissionTransform(layout, parent_index) orelse return null;
227
+ const device_clip = parent_transform.transformRect(parent.frame.normalized());
228
+ device_visible = geometry.RectF.intersection(device_visible, device_clip);
229
+ if (device_visible.isEmpty()) return null;
230
+ }
231
+ current = parent_index;
232
+ }
233
+
234
+ const transform = widgetLayoutNodeEmissionTransform(layout, node_index) orelse return null;
235
+ const inverse = transform.inverse() orelse return null;
236
+ const local_visible = inverse.transformRect(device_visible);
237
+ const clipped = geometry.RectF.intersection(bounds.normalized(), local_visible.normalized());
238
+ return if (clipped.isEmpty()) null else clipped;
239
+ }
240
+
173
241
  /// The late z-pass for anchored floating surfaces: they are skipped by
174
242
  /// the in-tree walk above and emitted here LAST, at the top level, so no
175
243
  /// ancestor scroll/clip region crops them (window-clipped, not
@@ -199,9 +267,19 @@ fn emitWidgetDepth(builder: *Builder, widget: Widget, tokens: DesignTokens, dept
199
267
  const wrap_transform = !affinesEqual(transform, Affine.identity());
200
268
  const inverse_transform = if (wrap_transform) transform.inverse() orelse return error.InvalidTransform else Affine.identity();
201
269
  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);
270
+ if (wrap_transform) {
271
+ const parent_visible_bounds = tree_visible_bounds;
272
+ defer tree_visible_bounds = parent_visible_bounds;
273
+ tree_visible_bounds = if (parent_visible_bounds) |bounds|
274
+ inverse_transform.transformRect(bounds).normalized()
275
+ else
276
+ null;
277
+ try builder.transform(transform);
278
+ try emitWidgetDepthContent(builder, widget, tokens, depth);
279
+ try builder.transform(inverse_transform);
280
+ } else {
281
+ try emitWidgetDepthContent(builder, widget, tokens, depth);
282
+ }
205
283
  if (wrap_opacity) try builder.popOpacity();
206
284
  }
207
285
 
@@ -235,7 +313,21 @@ fn emitWidgetDepthContent(builder: *Builder, widget: Widget, tokens: DesignToken
235
313
  .resizable, .panel => try emitPanelWidget(builder, paint_widget, tokens, depth),
236
314
  .popover => try emitPopoverWidget(builder, paint_widget, tokens, depth),
237
315
  .menu_surface, .dropdown_menu => try emitMenuSurfaceWidget(builder, paint_widget, tokens, depth),
238
- .text => try emitTextWidget(builder, paint_widget, tokens),
316
+ .text => {
317
+ if (isSyntaxCodeParagraph(paint_widget)) {
318
+ if (tree_visible_bounds) |visible_bounds| {
319
+ const clipped = geometry.RectF.intersection(
320
+ paint_widget.frame.normalized(),
321
+ visible_bounds.normalized(),
322
+ );
323
+ if (!clipped.isEmpty()) {
324
+ try emitVisibleCodeTextSpansWidget(builder, paint_widget, tokens, clipped, .{});
325
+ }
326
+ }
327
+ } else {
328
+ try emitTextWidget(builder, paint_widget, tokens);
329
+ }
330
+ },
239
331
  .icon => try emitIconWidget(builder, paint_widget, tokens),
240
332
  .image => try emitImageWidget(builder, paint_widget),
241
333
  .media_surface => try emitMediaSurfaceWidget(builder, paint_widget),
@@ -245,7 +337,11 @@ fn emitWidgetDepthContent(builder: *Builder, widget: Widget, tokens: DesignToken
245
337
  .button, .toggle_button, .toggle => try widget_render_controls.emitButtonWidget(builder, paint_widget, tokens),
246
338
  .icon_button => try widget_render_controls.emitIconButtonWidget(builder, paint_widget, tokens),
247
339
  .select => try widget_render_controls.emitSelectWidget(builder, paint_widget, tokens),
248
- .input, .text_field, .textarea => try widget_render_controls.emitTextFieldWidget(builder, paint_widget, tokens),
340
+ .input, .text_field => try widget_render_controls.emitTextFieldWidget(builder, paint_widget, tokens),
341
+ .textarea => if (paint_widget.code_editor)
342
+ try emitCodeEditorWidget(builder, paint_widget, tokens)
343
+ else
344
+ try widget_render_controls.emitTextFieldWidget(builder, paint_widget, tokens),
249
345
  .search_field, .combobox => try widget_render_controls.emitSearchFieldWidget(builder, paint_widget, tokens),
250
346
  .tooltip => try widget_render_controls.emitTooltipWidget(builder, paint_widget, tokens),
251
347
  .menu_item => try widget_render_controls.emitMenuItemWidget(builder, paint_widget, tokens),
@@ -395,6 +491,11 @@ fn buttonGroupSegmentAt(ordinal: usize, visible_total: usize) widget_model.Widge
395
491
  /// docs scene and a live app would render different bars.
396
492
  fn emitButtonGroupWidget(builder: *Builder, widget: Widget, tokens: DesignTokens, depth: usize) Error!void {
397
493
  if (!buttonGroupStampsSegments(widget, tokens)) return emitWidgetClippedChildren(builder, widget, tokens, depth);
494
+ const parent_visible_bounds = tree_visible_bounds;
495
+ defer tree_visible_bounds = parent_visible_bounds;
496
+ if (widget.layout.clip_content) {
497
+ tree_visible_bounds = visibleBoundsInsideClip(parent_visible_bounds, widgetContentClip(widget, tokens).rect);
498
+ }
398
499
  if (widget.layout.clip_content) try builder.pushClip(widgetContentClip(widget, tokens));
399
500
  var emitted: usize = 0;
400
501
  var previous: ?WidgetPaintOrder = null;
@@ -579,7 +680,15 @@ fn emitWidgetLayoutNodeContent(
579
680
  .resizable, .panel => try widget_render_surfaces.emitPanelWidgetChrome(builder, paint_widget, tokens),
580
681
  .popover => try widget_render_surfaces.emitPopoverWidgetChrome(builder, paint_widget, tokens),
581
682
  .menu_surface, .dropdown_menu => try widget_render_surfaces.emitMenuSurfaceWidgetChrome(builder, paint_widget, tokens),
582
- .text => try emitTextWidget(builder, paint_widget, tokens),
683
+ .text => {
684
+ if (isSyntaxCodeParagraph(paint_widget)) {
685
+ if (widgetLayoutNodeVisibleBounds(layout, node_index, paint_widget.frame)) |visible_bounds| {
686
+ try emitVisibleCodeTextSpansWidget(builder, paint_widget, tokens, visible_bounds, .{});
687
+ }
688
+ } else {
689
+ try emitTextWidget(builder, paint_widget, tokens);
690
+ }
691
+ },
583
692
  .icon => try emitIconWidget(builder, paint_widget, tokens),
584
693
  .image => try emitImageWidget(builder, paint_widget),
585
694
  .media_surface => try emitMediaSurfaceWidget(builder, paint_widget),
@@ -589,7 +698,11 @@ fn emitWidgetLayoutNodeContent(
589
698
  .button, .toggle_button, .toggle => try widget_render_controls.emitButtonWidget(builder, paint_widget, tokens),
590
699
  .icon_button => try widget_render_controls.emitIconButtonWidget(builder, paint_widget, tokens),
591
700
  .select => try widget_render_controls.emitSelectWidget(builder, paint_widget, tokens),
592
- .input, .text_field, .textarea => try widget_render_controls.emitTextFieldWidget(builder, paint_widget, tokens),
701
+ .input, .text_field => try widget_render_controls.emitTextFieldWidget(builder, paint_widget, tokens),
702
+ .textarea => if (paint_widget.code_editor)
703
+ try emitCodeEditorWidget(builder, paint_widget, tokens)
704
+ else
705
+ try widget_render_controls.emitTextFieldWidget(builder, paint_widget, tokens),
593
706
  .search_field, .combobox => try widget_render_controls.emitSearchFieldWidget(builder, paint_widget, tokens),
594
707
  .tooltip => try widget_render_controls.emitTooltipWidget(builder, paint_widget, tokens),
595
708
  .menu_item => try widget_render_controls.emitMenuItemWidget(builder, paint_widget, tokens),
@@ -896,6 +1009,9 @@ fn emitMenuSurfaceWidget(builder: *Builder, widget: Widget, tokens: DesignTokens
896
1009
  }
897
1010
 
898
1011
  fn emitScrollViewWidget(builder: *Builder, widget: Widget, tokens: DesignTokens, depth: usize) Error!void {
1012
+ const parent_visible_bounds = tree_visible_bounds;
1013
+ defer tree_visible_bounds = parent_visible_bounds;
1014
+ tree_visible_bounds = visibleBoundsInsideClip(parent_visible_bounds, widget.frame);
899
1015
  try builder.pushClip(.{ .id = widgetPartId(widget.id, 1), .rect = widget.frame });
900
1016
  try emitWidgetChildren(builder, widget.children, tokens, depth);
901
1017
  try builder.popClip();
@@ -913,9 +1029,22 @@ fn emitScrollViewWidget(builder: *Builder, widget: Widget, tokens: DesignTokens,
913
1029
  }
914
1030
 
915
1031
  fn emitWidgetClippedChildren(builder: *Builder, widget: Widget, tokens: DesignTokens, depth: usize) Error!void {
916
- if (widget.layout.clip_content) try builder.pushClip(widgetContentClip(widget, tokens));
1032
+ if (!widget.layout.clip_content) return emitWidgetChildren(builder, widget.children, tokens, depth);
1033
+ const parent_visible_bounds = tree_visible_bounds;
1034
+ defer tree_visible_bounds = parent_visible_bounds;
1035
+ const clip = widgetContentClip(widget, tokens);
1036
+ tree_visible_bounds = visibleBoundsInsideClip(parent_visible_bounds, clip.rect);
1037
+ try builder.pushClip(clip);
917
1038
  try emitWidgetChildren(builder, widget.children, tokens, depth);
918
- if (widget.layout.clip_content) try builder.popClip();
1039
+ try builder.popClip();
1040
+ }
1041
+
1042
+ fn visibleBoundsInsideClip(bounds: ?geometry.RectF, clip: geometry.RectF) ?geometry.RectF {
1043
+ const clipped = geometry.RectF.intersection(
1044
+ (bounds orelse return null).normalized(),
1045
+ clip.normalized(),
1046
+ );
1047
+ return if (clipped.isEmpty()) null else clipped;
919
1048
  }
920
1049
 
921
1050
  fn widgetScrollSemantics(layout: anytype, node_index: usize) widget_semantics.WidgetScrollSemantics {
@@ -983,6 +1112,151 @@ fn emitTextWidget(builder: *Builder, widget: Widget, tokens: DesignTokens) Error
983
1112
  if (clip_overflow) try builder.popClip();
984
1113
  }
985
1114
 
1115
+ /// Editable code is a textarea behaviorally and a bare code surface
1116
+ /// visually. Selection/caret geometry comes from the shared text-input
1117
+ /// seam while glyphs come from the same syntax-span emitter as read-only
1118
+ /// code; there is intentionally no textarea chrome or component inset.
1119
+ fn emitCodeEditorWidget(builder: *Builder, widget: Widget, tokens: DesignTokens) Error!void {
1120
+ const text_size = widgetTextInputSize(widget, tokens);
1121
+ const text_inset = widgetTextInputInset(widget, tokens);
1122
+ const layout_options = widgetTextInputLayoutOptions(widget, tokens, text_size, text_inset);
1123
+ const origin = widgetTextInputOrigin(widget, tokens, text_size, text_inset, layout_options);
1124
+ const draw_text = widget_text_input.widgetTextInputDrawText(
1125
+ widget,
1126
+ tokens,
1127
+ text_size,
1128
+ origin,
1129
+ widgetForegroundColor(widget, tokens, tokens.colors.text),
1130
+ layout_options,
1131
+ );
1132
+ const selection_range = widget_access.widgetTextSelectionRange(widget);
1133
+ const composition_range = widget_access.widgetTextCompositionRange(widget);
1134
+ const active_row = codeEditorActiveRowRect(widget, draw_text, layout_options, selection_range);
1135
+
1136
+ try builder.pushClip(.{ .id = widgetPartId(widget.id, 16), .rect = widget.frame });
1137
+ if (active_row) |row| {
1138
+ try builder.fillRect(.{
1139
+ .id = codeEditorActiveRowCommandId(widget.id, 0),
1140
+ .rect = pixelSnapGeometryRect(tokens, row),
1141
+ .fill = colorFill(tokens.colors.surface_subtle),
1142
+ });
1143
+ }
1144
+ if (selection_range) |range| {
1145
+ if (!range.isCollapsed(widget.text.len)) {
1146
+ try widget_render_controls.emitWidgetTextSelectionRects(
1147
+ builder,
1148
+ widget,
1149
+ draw_text,
1150
+ layout_options,
1151
+ range,
1152
+ 3,
1153
+ 13,
1154
+ 4,
1155
+ tokens,
1156
+ );
1157
+ }
1158
+ }
1159
+ try emitVisibleCodeTextSpansWidget(builder, widget, tokens, widget.frame, .{});
1160
+ if (selection_range) |range| {
1161
+ if (!range.isCollapsed(widget.text.len)) {
1162
+ try emitCodeEditorSelectedGlyphs(
1163
+ builder,
1164
+ widget,
1165
+ draw_text,
1166
+ layout_options,
1167
+ range,
1168
+ tokens,
1169
+ );
1170
+ }
1171
+ }
1172
+ if (composition_range) |range| {
1173
+ if (!range.isCollapsed(widget.text.len)) {
1174
+ try widget_render_controls.emitWidgetTextCompositionLines(
1175
+ builder,
1176
+ widget,
1177
+ draw_text,
1178
+ layout_options,
1179
+ range,
1180
+ 5,
1181
+ 10,
1182
+ 4,
1183
+ tokens,
1184
+ );
1185
+ }
1186
+ }
1187
+ if (widget.state.focused) {
1188
+ if (selection_range) |range| {
1189
+ if (range.isCollapsed(widget.text.len)) {
1190
+ try widget_render_controls.emitWidgetTextCaret(
1191
+ builder,
1192
+ widget,
1193
+ draw_text,
1194
+ layout_options,
1195
+ range.start,
1196
+ 6,
1197
+ tokens,
1198
+ );
1199
+ }
1200
+ }
1201
+ }
1202
+ // Wrapped code emits its gutter beside the wrapped span rows. The
1203
+ // viewport-owned gutter below is the no-wrap path: emitting both would
1204
+ // duplicate the retained line-number command IDs and place a second set
1205
+ // of markers at logical-line rather than visual-row positions.
1206
+ if (widget.text_no_wrap) {
1207
+ try emitVisibleEditableCodeLineNumberGutter(builder, widget, tokens, widget.frame, active_row);
1208
+ }
1209
+ try builder.popClip();
1210
+ }
1211
+
1212
+ /// Repaint selected code from the same viewport-bounded syntax runs as the
1213
+ /// base pass. Ordinary text inputs can safely repeat their one small text
1214
+ /// command under each selection clip; an editor may retain hundreds of KiB,
1215
+ /// so repeating its full `DrawText` would overflow the 32 KiB display-list
1216
+ /// text store even when only a few visible glyphs are selected.
1217
+ fn emitCodeEditorSelectedGlyphs(
1218
+ builder: *Builder,
1219
+ widget: Widget,
1220
+ text: text_model.DrawText,
1221
+ options: TextLayoutOptions,
1222
+ range: text_model.TextRange,
1223
+ tokens: DesignTokens,
1224
+ ) Error!void {
1225
+ var rect_buffer: [4]text_model.TextSelectionRect = undefined;
1226
+ const rects = text_model.layoutTextSelectionRects(text, options, range, &rect_buffer);
1227
+ for (rects, 0..) |selection, ordinal| {
1228
+ const visible = geometry.RectF.intersection(selection.rect, widget.frame);
1229
+ if (visible.isEmpty()) continue;
1230
+ try builder.pushClip(.{
1231
+ .id = textSpanCommandId(0x5eed_59a2_0000_0017, widget.id, ordinal),
1232
+ .rect = pixelSnapGeometryRect(tokens, selection.rect),
1233
+ });
1234
+ try emitVisibleCodeTextSpansWidget(builder, widget, tokens, visible, .{
1235
+ .color = textSelectionTextColor(widget, tokens),
1236
+ .selection_ordinal = ordinal,
1237
+ });
1238
+ try builder.popClip();
1239
+ }
1240
+ }
1241
+
1242
+ /// The visual row containing the rendered caret. It derives from the
1243
+ /// same scroll/wrap-aware text command as the caret itself, then spans
1244
+ /// the editor viewport instead of the caret's one-point width.
1245
+ fn codeEditorActiveRowRect(
1246
+ widget: Widget,
1247
+ draw_text: text_model.DrawText,
1248
+ layout_options: TextLayoutOptions,
1249
+ selection_range: ?text_model.TextRange,
1250
+ ) ?geometry.RectF {
1251
+ if (!widget.state.focused) return null;
1252
+ const range = selection_range orelse return null;
1253
+ if (!range.isCollapsed(widget.text.len)) return null;
1254
+ const caret = text_model.layoutTextCaretRect(draw_text, layout_options, range.start) orelse return null;
1255
+ const row = geometry.RectF.init(widget.frame.x, caret.y, widget.frame.width, caret.height);
1256
+ const clipped = geometry.RectF.intersection(row, widget.frame);
1257
+ return if (clipped.isEmpty()) null else clipped;
1258
+ }
1259
+
986
1260
  /// Wrap budget for text painted inside a pixel-snapped frame — the
987
1261
  /// shared quantum hand-back (`widget_metrics.textWrapMaxWidth`), aliased
988
1262
  /// for the emit sites here.
@@ -992,11 +1266,22 @@ const textWrapMaxWidth = widget_metrics.textWrapMaxWidth;
992
1266
  /// of a `.text` widget (plain or span paragraph). Command ids are hashed
993
1267
  /// per line ordinal like span runs, so retained diffing stays stable.
994
1268
  fn emitStaticTextSelection(builder: *Builder, widget: Widget, tokens: DesignTokens) Error!void {
1269
+ return emitStaticTextSelectionBounded(builder, widget, tokens, builder.commands.len);
1270
+ }
1271
+
1272
+ fn emitStaticTextSelectionBounded(
1273
+ builder: *Builder,
1274
+ widget: Widget,
1275
+ tokens: DesignTokens,
1276
+ command_ceiling: usize,
1277
+ ) Error!void {
1278
+ if (builder.len >= command_ceiling) return;
995
1279
  const range = widget_access.widgetTextSelectionRange(widget) orelse return;
996
1280
  if (range.isCollapsed(widget.text.len)) return;
997
1281
  var rect_buffer: [widget_text_select.max_static_text_selection_rects]text_model.TextSelectionRect = undefined;
998
1282
  const rects = widget_text_select.staticTextSelectionRects(widget, tokens, range, &rect_buffer);
999
1283
  for (rects, 0..) |selection, ordinal| {
1284
+ if (builder.len >= command_ceiling) break;
1000
1285
  try builder.fillRoundedRect(.{
1001
1286
  .id = textSelectionCommandId(widget.id, ordinal),
1002
1287
  .rect = pixelSnapGeometryRect(tokens, selection.rect),
@@ -1011,14 +1296,20 @@ fn emitStaticTextSelection(builder: *Builder, widget: Widget, tokens: DesignToke
1011
1296
  /// decorations get stable hashed command ids derived from the widget id
1012
1297
  /// and their ordinal, so retained diffing works across frames.
1013
1298
  fn emitTextSpansWidget(builder: *Builder, widget: Widget, tokens: DesignTokens) Error!void {
1014
- const content = widget.frame.inset(widget.layout.padding);
1299
+ const content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
1300
+ const layout_options = widget_metrics.widgetTextSpanLayoutOptions(
1301
+ widget,
1302
+ tokens,
1303
+ textWrapMaxWidth(tokens, content.width),
1304
+ );
1015
1305
  var runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
1016
1306
  const layout = text_spans_model.layoutTextSpans(
1017
1307
  widget.spans,
1018
- widget_metrics.widgetTextSpanLayoutOptions(widget, tokens, textWrapMaxWidth(tokens, content.width)),
1308
+ layout_options,
1019
1309
  &runs,
1020
1310
  );
1021
1311
 
1312
+ try emitCodeLineNumberGutter(builder, widget, widget.spans, tokens, content, widget.frame, layout_options, null);
1022
1313
  // Span background highlights (intra-line diff emphasis): one
1023
1314
  // full-line-height rect per run, the same geometry selection rects
1024
1315
  // use, painted before selection and glyphs. Edge-snapped rects of
@@ -1109,6 +1400,781 @@ fn emitTextSpansWidget(builder: *Builder, widget: Widget, tokens: DesignTokens)
1109
1400
  }
1110
1401
  }
1111
1402
 
1403
+ fn isSyntaxColor(color: text_spans_model.TextSpanColor) bool {
1404
+ return switch (color) {
1405
+ .syntax_plain,
1406
+ .syntax_comment,
1407
+ .syntax_keyword,
1408
+ .syntax_literal,
1409
+ .syntax_function,
1410
+ .syntax_property,
1411
+ .syntax_constant,
1412
+ => true,
1413
+ else => false,
1414
+ };
1415
+ }
1416
+
1417
+ /// `Ui.code` lowers to ordinary text widgets whose spans are all monospace
1418
+ /// syntax-token runs. Keep that marker structural instead of adding another
1419
+ /// public widget kind solely for an emission optimization.
1420
+ fn isSyntaxCodeParagraph(widget: Widget) bool {
1421
+ if (widget.kind != .text or widget.spans.len == 0) return false;
1422
+ for (widget.spans) |span| {
1423
+ if (!span.monospace or
1424
+ !isSyntaxColor(span.color orelse return false) or
1425
+ span.background != null or
1426
+ span.underline or
1427
+ span.strikethrough or
1428
+ span.link.len != 0)
1429
+ {
1430
+ return false;
1431
+ }
1432
+ }
1433
+ return true;
1434
+ }
1435
+
1436
+ // A code surface shares the frame's fixed display-list stores with every
1437
+ // widget emitted around it. Hold back the same practical tail as the
1438
+ // terminal painter: enough commands and referenced text for trailing
1439
+ // siblings, transform/clip epilogues, and window chrome. Small direct
1440
+ // builders retain seven eighths of their capacity so focused unit tests
1441
+ // remain representative while still leaving their enclosing epilogue room.
1442
+ const code_widget_command_reserve: usize = 256;
1443
+ const code_widget_text_reserve: usize = 8192;
1444
+
1445
+ const CodeEmissionBudget = struct {
1446
+ command_ceiling: usize,
1447
+ text_ceiling: usize,
1448
+ text_total: usize,
1449
+
1450
+ fn init(builder: *const Builder) CodeEmissionBudget {
1451
+ const command_reserve = @min(
1452
+ code_widget_command_reserve,
1453
+ @max(@as(usize, 1), builder.commands.len / 8),
1454
+ );
1455
+ return .{
1456
+ .command_ceiling = builder.commands.len -| command_reserve,
1457
+ .text_ceiling = canvas.max_display_list_text_bytes -| code_widget_text_reserve,
1458
+ .text_total = displayListTextBytes(builder.displayList()),
1459
+ };
1460
+ }
1461
+
1462
+ fn hasCommand(self: CodeEmissionBudget, builder: *const Builder) bool {
1463
+ return builder.len < self.command_ceiling;
1464
+ }
1465
+
1466
+ fn remainingText(self: CodeEmissionBudget) usize {
1467
+ return self.text_ceiling -| self.text_total;
1468
+ }
1469
+
1470
+ fn chargeText(self: *CodeEmissionBudget, len: usize) void {
1471
+ self.text_total += len;
1472
+ }
1473
+ };
1474
+
1475
+ fn displayListTextBytes(list: canvas.DisplayList) usize {
1476
+ var total: usize = 0;
1477
+ for (list.commands) |command| {
1478
+ if (command == .draw_text) total += command.draw_text.text.len;
1479
+ }
1480
+ return total;
1481
+ }
1482
+
1483
+ /// Keep a text-budget truncation on a UTF-8 scalar boundary. Code source
1484
+ /// accepts arbitrary bytes, so invalid leading/continuation bytes simply
1485
+ /// degrade to the maximal prefix the display store can retain.
1486
+ fn codeTextPrefix(text: []const u8, max_len: usize) []const u8 {
1487
+ var end = @min(text.len, max_len);
1488
+ while (end > 0 and end < text.len and text[end] & 0xc0 == 0x80) end -= 1;
1489
+ return text[0..end];
1490
+ }
1491
+
1492
+ /// Viewport-aware code emission: the full source remains in retained
1493
+ /// paragraph widgets for layout, selection, copy, and scroll extents, while
1494
+ /// the display list contains only line runs that intersect the current
1495
+ /// window/scroll clip. Long no-wrap runs are sliced horizontally as well.
1496
+ const CodeTextPaint = struct {
1497
+ color: ?Color = null,
1498
+ selection_ordinal: ?usize = null,
1499
+ };
1500
+
1501
+ fn emitVisibleCodeTextSpansWidget(
1502
+ builder: *Builder,
1503
+ widget: Widget,
1504
+ tokens: DesignTokens,
1505
+ visible_bounds: geometry.RectF,
1506
+ paint: CodeTextPaint,
1507
+ ) Error!void {
1508
+ if (widget.code_editor and widget.text_no_wrap) {
1509
+ return emitVisibleEditableCodeLines(builder, widget, tokens, visible_bounds, paint);
1510
+ }
1511
+ if (widget.code_editor) {
1512
+ return emitVisibleWrappedEditableCodeLines(builder, widget, tokens, visible_bounds, paint);
1513
+ }
1514
+ const spans = widget.spans;
1515
+ const content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
1516
+ const layout_options = widget_metrics.widgetTextSpanLayoutOptions(
1517
+ widget,
1518
+ tokens,
1519
+ textWrapMaxWidth(tokens, content.width),
1520
+ );
1521
+ const line_height = text_spans_model.textSpanLineHeight(spans, layout_options);
1522
+ const visible_line: usize = if (line_height > 0 and
1523
+ std.math.isFinite(line_height) and
1524
+ std.math.isFinite(visible_bounds.y - content.y) and
1525
+ visible_bounds.y > content.y)
1526
+ @intFromFloat(@floor((visible_bounds.y - content.y) / line_height))
1527
+ else
1528
+ 0;
1529
+ const last_visible_line: usize = if (line_height > 0 and
1530
+ std.math.isFinite(line_height) and
1531
+ std.math.isFinite(visible_bounds.maxY() - content.y) and
1532
+ visible_bounds.maxY() > content.y)
1533
+ @intFromFloat(@floor((visible_bounds.maxY() - content.y) / line_height))
1534
+ else
1535
+ visible_line;
1536
+ var runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
1537
+ var budget = CodeEmissionBudget.init(builder);
1538
+ if (!budget.hasCommand(builder)) return;
1539
+
1540
+ if (paint.selection_ordinal == null) {
1541
+ try emitCodeLineNumberGutter(builder, widget, spans, tokens, content, visible_bounds, layout_options, &budget);
1542
+ try emitStaticTextSelectionBounded(builder, widget, tokens, budget.command_ceiling);
1543
+ }
1544
+ if (!budget.hasCommand(builder) or budget.remainingText() == 0) return;
1545
+ var page_first_line = visible_line -| 1;
1546
+ while (true) {
1547
+ const layout = text_spans_model.layoutTextSpansFromLine(
1548
+ spans,
1549
+ layout_options,
1550
+ page_first_line,
1551
+ &runs,
1552
+ );
1553
+ for (layout.runs) |run| {
1554
+ if (run.text.len == 0) continue;
1555
+ const local_bounds = text_spans_model.textSpanRunBounds(layout, run);
1556
+ const run_bounds = geometry.RectF.init(
1557
+ content.x + local_bounds.x,
1558
+ content.y + local_bounds.y,
1559
+ local_bounds.width,
1560
+ local_bounds.height,
1561
+ );
1562
+ if (!run_bounds.intersects(visible_bounds)) continue;
1563
+
1564
+ const span = spans[run.span_index];
1565
+ const absolute_x = content.x + run.x;
1566
+ const visible = text_spans_model.textSpanRunVisibleSlice(
1567
+ span,
1568
+ run,
1569
+ layout_options,
1570
+ visible_bounds.x - absolute_x,
1571
+ visible_bounds.maxX() - absolute_x,
1572
+ ) orelse continue;
1573
+ if (!budget.hasCommand(builder)) return;
1574
+ const admitted_text = codeTextPrefix(visible.text, budget.remainingText());
1575
+ if (admitted_text.len == 0) return;
1576
+ const color = paint.color orelse text_spans_model.textSpanColorValue(tokens.colors, span.color.?);
1577
+ const origin = pixelSnapTextPoint(tokens, geometry.PointF.init(absolute_x + visible.x, content.y + run.baseline));
1578
+ try builder.drawText(.{
1579
+ .id = codeTextPaintCommandId(codeTextSpanRunCommandId(widget, spans, run), paint),
1580
+ .font_id = run.font_id,
1581
+ .size = run.size,
1582
+ .origin = origin,
1583
+ .color = color,
1584
+ .text = admitted_text,
1585
+ .text_layout = .{
1586
+ .max_width = 0,
1587
+ .line_height = layout.line_height,
1588
+ .wrap = .none,
1589
+ .alignment = .start,
1590
+ .measure = tokens.text_measure,
1591
+ },
1592
+ });
1593
+ budget.chargeText(admitted_text.len);
1594
+ }
1595
+
1596
+ const next_first_line = page_first_line +| text_spans_model.max_text_span_lines_per_paragraph;
1597
+ if (next_first_line <= page_first_line or
1598
+ next_first_line > last_visible_line or
1599
+ next_first_line >= layout.line_count)
1600
+ {
1601
+ break;
1602
+ }
1603
+ page_first_line = next_first_line;
1604
+ }
1605
+ }
1606
+
1607
+ /// Wrapped editors cannot retain one syntax span for every token in a large
1608
+ /// document. Tokenize one logical line at a time while advancing lexer state
1609
+ /// through the prefix, then paint only lines intersecting the viewport. Each
1610
+ /// line gets the full bounded span budget without dropping later syntax.
1611
+ fn emitVisibleWrappedEditableCodeLines(
1612
+ builder: *Builder,
1613
+ widget: Widget,
1614
+ tokens: DesignTokens,
1615
+ visible_bounds: geometry.RectF,
1616
+ paint: CodeTextPaint,
1617
+ ) Error!void {
1618
+ var content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
1619
+ content.x -= widget.value_x;
1620
+ content.y -= widget.value;
1621
+ const layout_options = widget_metrics.widgetTextSpanLayoutOptions(
1622
+ widget,
1623
+ tokens,
1624
+ // Interactive glyphs must wrap on the exact same width as caret,
1625
+ // selection, composition, and hit-test geometry. The pixel-snap
1626
+ // hand-back is safe only for non-interactive paragraph painting.
1627
+ content.width,
1628
+ );
1629
+ const line_height = text_spans_model.textSpanLineHeight(widget.spans, layout_options);
1630
+ if (line_height <= 0 or !std.math.isFinite(line_height)) return;
1631
+
1632
+ var budget = CodeEmissionBudget.init(builder);
1633
+ if (!budget.hasCommand(builder)) return;
1634
+ if (paint.selection_ordinal == null) {
1635
+ var gutter_content = content;
1636
+ gutter_content.x += widget.value_x;
1637
+ try emitCodeLineNumberGutter(
1638
+ builder,
1639
+ widget,
1640
+ widget.spans,
1641
+ tokens,
1642
+ gutter_content,
1643
+ visible_bounds,
1644
+ layout_options,
1645
+ &budget,
1646
+ );
1647
+ }
1648
+ if (!budget.hasCommand(builder) or budget.remainingText() == 0) return;
1649
+
1650
+ var state: code_model.HighlightState = .{};
1651
+ var span_storage: [text_spans_model.max_text_spans_per_paragraph]text_spans_model.TextSpan = undefined;
1652
+ var line_runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
1653
+ var line_start: usize = 0;
1654
+ var logical_line: usize = 0;
1655
+ var visual_line: usize = 0;
1656
+
1657
+ while (line_start <= widget.text.len) : (logical_line += 1) {
1658
+ const newline = std.mem.indexOfScalarPos(u8, widget.text, line_start, '\n');
1659
+ const line_end = if (newline) |index| index + 1 else widget.text.len;
1660
+ const line_source = widget.text[line_start..line_end];
1661
+ const highlighted = if (line_source.len == 0) blk: {
1662
+ span_storage[0] = .{
1663
+ .text = line_source,
1664
+ .monospace = true,
1665
+ .color = .syntax_plain,
1666
+ };
1667
+ break :blk span_storage[0..1];
1668
+ } else code_model.highlightWithState(
1669
+ line_source,
1670
+ widget.code_language,
1671
+ &span_storage,
1672
+ &state,
1673
+ );
1674
+ const line_layout = text_spans_model.layoutTextSpans(
1675
+ highlighted,
1676
+ layout_options,
1677
+ &line_runs,
1678
+ );
1679
+ const visual_count = @max(1, line_layout.line_count);
1680
+ const line_top = content.y + @as(f32, @floatFromInt(visual_line)) * line_height;
1681
+ const line_bottom = line_top + @as(f32, @floatFromInt(visual_count)) * line_height;
1682
+ if (line_top > visible_bounds.maxY()) return;
1683
+
1684
+ if (line_bottom >= visible_bounds.y) {
1685
+ const first_visible_line: usize = if (visible_bounds.y > line_top and
1686
+ std.math.isFinite(visible_bounds.y - line_top))
1687
+ @intFromFloat(@floor((visible_bounds.y - line_top) / line_height))
1688
+ else
1689
+ 0;
1690
+ const last_visible_line: usize = if (visible_bounds.maxY() > line_top and
1691
+ std.math.isFinite(visible_bounds.maxY() - line_top))
1692
+ @intFromFloat(@floor((visible_bounds.maxY() - line_top) / line_height))
1693
+ else
1694
+ first_visible_line;
1695
+ var page_first_line = first_visible_line -| 1;
1696
+ while (true) {
1697
+ const page_layout = if (page_first_line == 0)
1698
+ line_layout
1699
+ else
1700
+ text_spans_model.layoutTextSpansFromLine(
1701
+ highlighted,
1702
+ layout_options,
1703
+ page_first_line,
1704
+ &line_runs,
1705
+ );
1706
+ for (page_layout.runs) |run| {
1707
+ if (run.text.len == 0) continue;
1708
+ const local_bounds = text_spans_model.textSpanRunBounds(page_layout, run);
1709
+ const run_bounds = geometry.RectF.init(
1710
+ content.x + local_bounds.x,
1711
+ line_top + local_bounds.y,
1712
+ local_bounds.width,
1713
+ local_bounds.height,
1714
+ );
1715
+ if (!run_bounds.intersects(visible_bounds)) continue;
1716
+ const span = highlighted[run.span_index];
1717
+ const absolute_x = content.x + run.x;
1718
+ const visible = text_spans_model.textSpanRunVisibleSlice(
1719
+ span,
1720
+ run,
1721
+ layout_options,
1722
+ visible_bounds.x - absolute_x,
1723
+ visible_bounds.maxX() - absolute_x,
1724
+ ) orelse continue;
1725
+ if (!budget.hasCommand(builder)) return;
1726
+ const admitted_text = codeTextPrefix(visible.text, budget.remainingText());
1727
+ if (admitted_text.len == 0) return;
1728
+ const color_ref = span.color orelse .syntax_plain;
1729
+ try builder.drawText(.{
1730
+ .id = codeTextPaintCommandId(editableCodeRunCommandId(widget, logical_line, run), paint),
1731
+ .font_id = run.font_id,
1732
+ .size = run.size,
1733
+ .origin = pixelSnapTextPoint(tokens, geometry.PointF.init(
1734
+ absolute_x + visible.x,
1735
+ line_top + run.baseline,
1736
+ )),
1737
+ .color = paint.color orelse text_spans_model.textSpanColorValue(tokens.colors, color_ref),
1738
+ .text = admitted_text,
1739
+ .text_layout = .{
1740
+ .max_width = 0,
1741
+ .line_height = line_height,
1742
+ .wrap = .none,
1743
+ .alignment = .start,
1744
+ .measure = tokens.text_measure,
1745
+ },
1746
+ });
1747
+ budget.chargeText(admitted_text.len);
1748
+ }
1749
+
1750
+ const next_first_line = page_first_line +| text_spans_model.max_text_span_lines_per_paragraph;
1751
+ if (next_first_line <= page_first_line or
1752
+ next_first_line > last_visible_line or
1753
+ next_first_line >= line_layout.line_count)
1754
+ {
1755
+ break;
1756
+ }
1757
+ page_first_line = next_first_line;
1758
+ }
1759
+ }
1760
+
1761
+ visual_line += visual_count;
1762
+ if (newline == null) break;
1763
+ line_start = line_end;
1764
+ }
1765
+ }
1766
+
1767
+ /// Large no-wrap editors retain one plain source span, then tokenize just
1768
+ /// the logical lines intersecting the viewport. Lexer state is advanced
1769
+ /// across the offscreen prefix so multiline comments, strings, and JSX
1770
+ /// constructs remain correct without retaining an unbounded run list.
1771
+ fn emitVisibleEditableCodeLines(
1772
+ builder: *Builder,
1773
+ widget: Widget,
1774
+ tokens: DesignTokens,
1775
+ visible_bounds: geometry.RectF,
1776
+ paint: CodeTextPaint,
1777
+ ) Error!void {
1778
+ var content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
1779
+ content.x -= widget.value_x;
1780
+ content.y -= widget.value;
1781
+ const layout_options = widget_metrics.widgetTextSpanLayoutOptions(
1782
+ widget,
1783
+ tokens,
1784
+ 0,
1785
+ );
1786
+ const line_height = text_spans_model.textSpanLineHeight(widget.spans, layout_options);
1787
+ if (line_height <= 0 or !std.math.isFinite(line_height)) return;
1788
+
1789
+ const first_visible: usize = if (visible_bounds.y > content.y and
1790
+ std.math.isFinite(visible_bounds.y - content.y))
1791
+ @intFromFloat(@floor((visible_bounds.y - content.y) / line_height))
1792
+ else
1793
+ 0;
1794
+ const last_visible: usize = if (visible_bounds.maxY() > content.y and
1795
+ std.math.isFinite(visible_bounds.maxY() - content.y))
1796
+ @intFromFloat(@floor((visible_bounds.maxY() - content.y) / line_height))
1797
+ else
1798
+ first_visible;
1799
+ const first_line = first_visible -| 1;
1800
+ const last_line = last_visible +| 1;
1801
+
1802
+ var line_start: usize = 0;
1803
+ var logical_line: usize = 0;
1804
+ while (logical_line < first_line and line_start < widget.text.len) : (logical_line += 1) {
1805
+ const newline = std.mem.indexOfScalarPos(u8, widget.text, line_start, '\n') orelse {
1806
+ line_start = widget.text.len;
1807
+ break;
1808
+ };
1809
+ line_start = newline + 1;
1810
+ }
1811
+
1812
+ var state: code_model.HighlightState = .{};
1813
+ var span_storage: [text_spans_model.max_text_spans_per_paragraph]text_spans_model.TextSpan = undefined;
1814
+ if (line_start > 0) {
1815
+ _ = code_model.highlightWithState(
1816
+ widget.text[0..line_start],
1817
+ widget.code_language,
1818
+ &span_storage,
1819
+ &state,
1820
+ );
1821
+ }
1822
+
1823
+ var budget = CodeEmissionBudget.init(builder);
1824
+ if (!budget.hasCommand(builder)) return;
1825
+ var line_runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
1826
+
1827
+ while (line_start <= widget.text.len and logical_line <= last_line) : (logical_line += 1) {
1828
+ const newline = std.mem.indexOfScalarPos(u8, widget.text, line_start, '\n');
1829
+ const line_end = if (newline) |index| index + 1 else widget.text.len;
1830
+ const line_source = widget.text[line_start..line_end];
1831
+ const highlighted = if (line_source.len == 0) blk: {
1832
+ span_storage[0] = .{
1833
+ .text = line_source,
1834
+ .monospace = true,
1835
+ .color = .syntax_plain,
1836
+ };
1837
+ break :blk span_storage[0..1];
1838
+ } else code_model.highlightWithState(
1839
+ line_source,
1840
+ widget.code_language,
1841
+ &span_storage,
1842
+ &state,
1843
+ );
1844
+ const line_layout = text_spans_model.layoutTextSpans(
1845
+ highlighted,
1846
+ layout_options,
1847
+ &line_runs,
1848
+ );
1849
+ const line_top = content.y + @as(f32, @floatFromInt(logical_line)) * line_height;
1850
+
1851
+ for (line_layout.runs) |run| {
1852
+ if (run.text.len == 0) continue;
1853
+ const local_bounds = text_spans_model.textSpanRunBounds(line_layout, run);
1854
+ const run_bounds = geometry.RectF.init(
1855
+ content.x + local_bounds.x,
1856
+ line_top + local_bounds.y,
1857
+ local_bounds.width,
1858
+ local_bounds.height,
1859
+ );
1860
+ if (!run_bounds.intersects(visible_bounds)) continue;
1861
+ const span = highlighted[run.span_index];
1862
+ const absolute_x = content.x + run.x;
1863
+ const visible = text_spans_model.textSpanRunVisibleSlice(
1864
+ span,
1865
+ run,
1866
+ layout_options,
1867
+ visible_bounds.x - absolute_x,
1868
+ visible_bounds.maxX() - absolute_x,
1869
+ ) orelse continue;
1870
+ if (!budget.hasCommand(builder)) return;
1871
+ const admitted_text = codeTextPrefix(visible.text, budget.remainingText());
1872
+ if (admitted_text.len == 0) return;
1873
+ const color_ref = span.color orelse .syntax_plain;
1874
+ try builder.drawText(.{
1875
+ .id = codeTextPaintCommandId(editableCodeRunCommandId(widget, logical_line, run), paint),
1876
+ .font_id = run.font_id,
1877
+ .size = run.size,
1878
+ .origin = pixelSnapTextPoint(tokens, geometry.PointF.init(
1879
+ absolute_x + visible.x,
1880
+ line_top + run.baseline,
1881
+ )),
1882
+ .color = paint.color orelse text_spans_model.textSpanColorValue(tokens.colors, color_ref),
1883
+ .text = admitted_text,
1884
+ .text_layout = .{
1885
+ .max_width = 0,
1886
+ .line_height = line_height,
1887
+ .wrap = .none,
1888
+ .alignment = .start,
1889
+ .measure = tokens.text_measure,
1890
+ },
1891
+ });
1892
+ budget.chargeText(admitted_text.len);
1893
+ }
1894
+
1895
+ if (newline == null) break;
1896
+ line_start = line_end;
1897
+ }
1898
+ }
1899
+
1900
+ /// The editable no-wrap code path scrolls source glyphs beneath a pinned
1901
+ /// line-number gutter. Paint that gutter last so source, selection, IME
1902
+ /// decoration, and the caret all disappear cleanly behind its opaque
1903
+ /// surface instead of clashing with the anchored markers.
1904
+ fn emitVisibleEditableCodeLineNumberGutter(
1905
+ builder: *Builder,
1906
+ widget: Widget,
1907
+ tokens: DesignTokens,
1908
+ visible_bounds: geometry.RectF,
1909
+ active_row: ?geometry.RectF,
1910
+ ) Error!void {
1911
+ if (widget.code_line_number_digits == 0) return;
1912
+
1913
+ var content = widget_metrics.widgetTextSpanContentFrame(widget, tokens);
1914
+ content.y -= widget.value;
1915
+ const layout_options = widget_metrics.widgetTextSpanLayoutOptions(widget, tokens, 0);
1916
+ const line_height = text_spans_model.textSpanLineHeight(widget.spans, layout_options);
1917
+ if (line_height <= 0 or !std.math.isFinite(line_height)) return;
1918
+
1919
+ const padded = widget.frame.inset(widget.layout.padding);
1920
+ const marker_width = @max(0, content.x - 12 - padded.x);
1921
+ const gutter_bounds = geometry.RectF.intersection(
1922
+ geometry.RectF.init(
1923
+ widget.frame.x,
1924
+ widget.frame.y,
1925
+ @max(0, content.x - widget.frame.x),
1926
+ widget.frame.height,
1927
+ ),
1928
+ visible_bounds,
1929
+ );
1930
+ if (!gutter_bounds.isEmpty()) {
1931
+ try builder.fillRect(.{
1932
+ .id = codeLineNumberGutterCommandId(widget.id),
1933
+ .rect = pixelSnapGeometryRect(tokens, gutter_bounds),
1934
+ .fill = colorFill(widgetBackgroundColor(widget, tokens.colors.background)),
1935
+ });
1936
+ }
1937
+ if (active_row) |row| {
1938
+ const active_gutter = geometry.RectF.intersection(gutter_bounds, row);
1939
+ if (!active_gutter.isEmpty()) {
1940
+ try builder.fillRect(.{
1941
+ .id = codeEditorActiveRowCommandId(widget.id, 1),
1942
+ .rect = pixelSnapGeometryRect(tokens, active_gutter),
1943
+ .fill = colorFill(tokens.colors.surface_subtle),
1944
+ });
1945
+ }
1946
+ }
1947
+
1948
+ const first_visible: usize = if (visible_bounds.y > content.y and
1949
+ std.math.isFinite(visible_bounds.y - content.y))
1950
+ @intFromFloat(@floor((visible_bounds.y - content.y) / line_height))
1951
+ else
1952
+ 0;
1953
+ const last_visible: usize = if (visible_bounds.maxY() > content.y and
1954
+ std.math.isFinite(visible_bounds.maxY() - content.y))
1955
+ @intFromFloat(@floor((visible_bounds.maxY() - content.y) / line_height))
1956
+ else
1957
+ first_visible;
1958
+ const first_line = first_visible -| 1;
1959
+ const last_line = last_visible +| 1;
1960
+
1961
+ var line_start: usize = 0;
1962
+ var logical_line: usize = 0;
1963
+ while (logical_line < first_line and line_start < widget.text.len) : (logical_line += 1) {
1964
+ const newline = std.mem.indexOfScalarPos(u8, widget.text, line_start, '\n') orelse {
1965
+ line_start = widget.text.len;
1966
+ break;
1967
+ };
1968
+ line_start = newline + 1;
1969
+ }
1970
+
1971
+ while (line_start <= widget.text.len and logical_line <= last_line) : (logical_line += 1) {
1972
+ const line_top = content.y + @as(f32, @floatFromInt(logical_line)) * line_height;
1973
+ const marker_bounds = geometry.RectF.init(padded.x, line_top, marker_width, line_height);
1974
+ if (marker_bounds.intersects(visible_bounds)) {
1975
+ var marker_buffer: [20]u8 = undefined;
1976
+ const marker_formatted = std.fmt.bufPrint(
1977
+ &marker_buffer,
1978
+ "{d}",
1979
+ .{logical_line + 1},
1980
+ ) catch "";
1981
+ const marker_text = builder.allocTextBytes(marker_formatted) catch "";
1982
+ if (marker_text.len > 0) {
1983
+ try builder.drawText(.{
1984
+ .id = codeLineNumberCommandId(widget.id, logical_line + 1),
1985
+ .font_id = tokens.typography.mono_font_id,
1986
+ .size = layout_options.size,
1987
+ .origin = pixelSnapTextPoint(tokens, geometry.PointF.init(
1988
+ padded.x,
1989
+ line_top + layout_options.size,
1990
+ )),
1991
+ .color = tokens.colors.text_muted,
1992
+ .text = marker_text,
1993
+ .text_layout = .{
1994
+ .max_width = marker_width,
1995
+ .line_height = line_height,
1996
+ .wrap = .none,
1997
+ .alignment = .end,
1998
+ .measure = tokens.text_measure,
1999
+ },
2000
+ });
2001
+ }
2002
+ }
2003
+
2004
+ const newline = std.mem.indexOfScalarPos(u8, widget.text, line_start, '\n') orelse break;
2005
+ line_start = newline + 1;
2006
+ }
2007
+ }
2008
+
2009
+ /// Muted logical-line markers for one coherent code paragraph. Each
2010
+ /// logical line is measured independently with the same monospace layout
2011
+ /// options; summing those wrapped extents places the next marker on the
2012
+ /// exact first visual line occupied by its source.
2013
+ fn emitCodeLineNumberGutter(
2014
+ builder: *Builder,
2015
+ widget: Widget,
2016
+ spans: []const text_spans_model.TextSpan,
2017
+ tokens: DesignTokens,
2018
+ content: geometry.RectF,
2019
+ visible_bounds: geometry.RectF,
2020
+ layout_options: text_spans_model.TextSpanLayoutOptions,
2021
+ budget: ?*CodeEmissionBudget,
2022
+ ) Error!void {
2023
+ if (widget.code_line_number_digits == 0) return;
2024
+ const line_height = text_spans_model.textSpanLineHeight(spans, layout_options);
2025
+ if (line_height <= 0 or !std.math.isFinite(line_height)) return;
2026
+
2027
+ const padded = widget.frame.inset(widget.layout.padding);
2028
+ const marker_width = @max(0, content.x - 12 - padded.x);
2029
+ var line_runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
2030
+ var logical_line: usize = 1;
2031
+ var visual_line: usize = 0;
2032
+ var line_start: usize = 0;
2033
+ while (line_start <= widget.text.len) : (logical_line += 1) {
2034
+ // A terminal newline closes the preceding painted line; the span
2035
+ // breaker intentionally does not reserve another empty visual line.
2036
+ if (line_start == widget.text.len and widget.text.len > 0 and !widget.code_editor) break;
2037
+ const newline = std.mem.indexOfScalarPos(u8, widget.text, line_start, '\n');
2038
+ const line_end = newline orelse widget.text.len;
2039
+ const baseline = content.y + layout_options.size +
2040
+ @as(f32, @floatFromInt(visual_line)) * line_height;
2041
+ const marker_bounds = geometry.RectF.init(
2042
+ padded.x,
2043
+ baseline - layout_options.size,
2044
+ marker_width,
2045
+ line_height,
2046
+ );
2047
+ if (marker_bounds.intersects(visible_bounds)) {
2048
+ var marker_buffer: [20]u8 = undefined;
2049
+ const marker_formatted = std.fmt.bufPrint(
2050
+ &marker_buffer,
2051
+ "{d}",
2052
+ .{logical_line},
2053
+ ) catch "";
2054
+ const marker_text = builder.allocTextBytes(marker_formatted) catch "";
2055
+ if (budget) |admission| {
2056
+ if (!admission.hasCommand(builder)) return;
2057
+ if (marker_text.len > admission.remainingText()) return;
2058
+ }
2059
+ try builder.drawText(.{
2060
+ .id = codeLineNumberCommandId(widget.id, logical_line),
2061
+ .font_id = tokens.typography.mono_font_id,
2062
+ .size = layout_options.size,
2063
+ .origin = pixelSnapTextPoint(tokens, geometry.PointF.init(padded.x, baseline)),
2064
+ .color = tokens.colors.text_muted,
2065
+ .text = marker_text,
2066
+ .text_layout = .{
2067
+ .max_width = marker_width,
2068
+ .line_height = line_height,
2069
+ .wrap = .none,
2070
+ .alignment = .end,
2071
+ .measure = tokens.text_measure,
2072
+ },
2073
+ });
2074
+ if (budget) |admission| admission.chargeText(marker_text.len);
2075
+ }
2076
+
2077
+ const line = widget.text[line_start..line_end];
2078
+ if (line.len == 0) {
2079
+ visual_line += 1;
2080
+ } else {
2081
+ const line_spans = [_]text_spans_model.TextSpan{.{
2082
+ .text = line,
2083
+ .monospace = true,
2084
+ .color = .syntax_plain,
2085
+ }};
2086
+ const line_layout = text_spans_model.layoutTextSpans(
2087
+ &line_spans,
2088
+ layout_options,
2089
+ &line_runs,
2090
+ );
2091
+ visual_line += @max(1, line_layout.line_count);
2092
+ }
2093
+ if (newline == null) break;
2094
+ line_start = line_end + 1;
2095
+ }
2096
+ }
2097
+
2098
+ fn codeTextSpanRunCommandId(widget: Widget, spans: []const text_spans_model.TextSpan, run: text_spans_model.TextSpanRun) ObjectId {
2099
+ if (text_spans_model.textSpanRunParagraphRange(widget.text, run)) |range| {
2100
+ var hasher = std.hash.Wyhash.init(0x5eed_59a2_0000_0011);
2101
+ hasher.update(std.mem.asBytes(&widget.id));
2102
+ hasher.update(std.mem.asBytes(&run.line_index));
2103
+ hasher.update(std.mem.asBytes(&range.start));
2104
+ const value = hasher.final();
2105
+ return if (value == 0) 1 else value;
2106
+ }
2107
+
2108
+ // An editable widget's runtime-owned text allocation can briefly be
2109
+ // distinct from the source allocation its freshly highlighted spans
2110
+ // reference. Paragraph-relative pointer arithmetic is unavailable in
2111
+ // that state, but every layout run still belongs to one span. Key the
2112
+ // fallback by that span and the run's offset within it; collapsing all
2113
+ // detached runs to byte zero gives every token on a line the same id
2114
+ // and makes the retained display-list diff reject the frame.
2115
+ var hasher = std.hash.Wyhash.init(0x5eed_59a2_0000_0013);
2116
+ hasher.update(std.mem.asBytes(&widget.id));
2117
+ hasher.update(std.mem.asBytes(&run.line_index));
2118
+ hasher.update(std.mem.asBytes(&run.span_index));
2119
+ if (run.span_index < spans.len) {
2120
+ const span = spans[run.span_index];
2121
+ const span_start = @intFromPtr(span.text.ptr);
2122
+ const run_start = @intFromPtr(run.text.ptr);
2123
+ if (run_start >= span_start and run_start - span_start + run.text.len <= span.text.len) {
2124
+ const span_offset = run_start - span_start;
2125
+ hasher.update(std.mem.asBytes(&span_offset));
2126
+ const value = hasher.final();
2127
+ return if (value == 0) 1 else value;
2128
+ }
2129
+ }
2130
+ hasher.update(std.mem.asBytes(&run.x));
2131
+ hasher.update(std.mem.asBytes(&run.text.len));
2132
+ hasher.update(run.text);
2133
+ const value = hasher.final();
2134
+ return if (value == 0) 1 else value;
2135
+ }
2136
+
2137
+ fn editableCodeRunCommandId(
2138
+ widget: Widget,
2139
+ logical_line: usize,
2140
+ run: text_spans_model.TextSpanRun,
2141
+ ) ObjectId {
2142
+ var hasher = std.hash.Wyhash.init(0x5eed_59a2_0000_0014);
2143
+ hasher.update(std.mem.asBytes(&widget.id));
2144
+ hasher.update(std.mem.asBytes(&logical_line));
2145
+ const text_start = @intFromPtr(widget.text.ptr);
2146
+ const run_start = @intFromPtr(run.text.ptr);
2147
+ if (run_start >= text_start and run_start - text_start <= widget.text.len) {
2148
+ const offset = run_start - text_start;
2149
+ hasher.update(std.mem.asBytes(&offset));
2150
+ } else {
2151
+ hasher.update(run.text);
2152
+ }
2153
+ const value = hasher.final();
2154
+ return if (value == 0) 1 else value;
2155
+ }
2156
+
2157
+ fn codeTextPaintCommandId(base_id: ObjectId, paint: CodeTextPaint) ObjectId {
2158
+ const ordinal = paint.selection_ordinal orelse return base_id;
2159
+ var hasher = std.hash.Wyhash.init(0x5eed_59a2_0000_0018);
2160
+ hasher.update(std.mem.asBytes(&base_id));
2161
+ hasher.update(std.mem.asBytes(&ordinal));
2162
+ const value = hasher.final();
2163
+ return if (value == 0) 1 else value;
2164
+ }
2165
+
2166
+ fn codeLineNumberCommandId(widget_id: ObjectId, logical_line: usize) ObjectId {
2167
+ return textSpanCommandId(0x5eed_59a2_0000_0012, widget_id, logical_line);
2168
+ }
2169
+
2170
+ fn codeLineNumberGutterCommandId(widget_id: ObjectId) ObjectId {
2171
+ return textSpanCommandId(0x5eed_59a2_0000_0015, widget_id, 0);
2172
+ }
2173
+
2174
+ fn codeEditorActiveRowCommandId(widget_id: ObjectId, ordinal: usize) ObjectId {
2175
+ return textSpanCommandId(0x5eed_59a2_0000_0016, widget_id, ordinal);
2176
+ }
2177
+
1112
2178
  pub fn textSpanRunCommandId(widget_id: ObjectId, ordinal: usize) ObjectId {
1113
2179
  return textSpanCommandId(0x5eed_59a2_0000_0001, widget_id, ordinal);
1114
2180
  }