@native-sdk/cli 0.6.3 → 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 (40) hide show
  1. package/package.json +9 -9
  2. package/packages/core/package-lock.json +2 -2
  3. package/packages/core/package.json +1 -1
  4. package/skill-data/native-ui/SKILL.md +17 -2
  5. package/src/primitives/canvas/code.zig +590 -0
  6. package/src/primitives/canvas/code_tests.zig +1062 -0
  7. package/src/primitives/canvas/layout_audit.zig +3 -1
  8. package/src/primitives/canvas/markdown.zig +13 -11
  9. package/src/primitives/canvas/markdown_tests.zig +167 -4
  10. package/src/primitives/canvas/root.zig +4 -2
  11. package/src/primitives/canvas/tests.zig +1 -0
  12. package/src/primitives/canvas/text_measure_cache.zig +4 -4
  13. package/src/primitives/canvas/text_span_tests.zig +254 -0
  14. package/src/primitives/canvas/text_spans.zig +556 -32
  15. package/src/primitives/canvas/themes/geist.zig +29 -0
  16. package/src/primitives/canvas/tokens.zig +72 -2
  17. package/src/primitives/canvas/ui.zig +304 -5
  18. package/src/primitives/canvas/ui_markup.zig +59 -2
  19. package/src/primitives/canvas/ui_markup_compiled.zig +76 -0
  20. package/src/primitives/canvas/ui_markup_compiled_tests.zig +33 -0
  21. package/src/primitives/canvas/ui_markup_contract.zig +34 -0
  22. package/src/primitives/canvas/ui_markup_view.zig +73 -0
  23. package/src/primitives/canvas/ui_markup_view_tests.zig +85 -0
  24. package/src/primitives/canvas/ui_schema.zig +17 -6
  25. package/src/primitives/canvas/ui_schema_tests.zig +7 -6
  26. package/src/primitives/canvas/widget_invalidation.zig +3 -0
  27. package/src/primitives/canvas/widget_layout.zig +57 -8
  28. package/src/primitives/canvas/widget_layout_tests.zig +35 -0
  29. package/src/primitives/canvas/widget_metrics.zig +30 -1
  30. package/src/primitives/canvas/widget_render.zig +454 -9
  31. package/src/primitives/canvas/widget_text_select.zig +2 -2
  32. package/src/primitives/canvas/widgets.zig +13 -0
  33. package/src/root.zig +1 -0
  34. package/src/runtime/canvas_widget_clipboard_tests.zig +130 -0
  35. package/src/runtime/canvas_widget_context_menu.zig +12 -2
  36. package/src/runtime/canvas_widget_events.zig +7 -1
  37. package/src/runtime/canvas_widget_runtime.zig +7 -2
  38. package/src/runtime/canvas_widget_text_tests.zig +57 -0
  39. package/src/runtime/view.zig +7 -3
  40. package/src/runtime/view_widget_text.zig +194 -4
@@ -1,6 +1,8 @@
1
1
  const std = @import("std");
2
+ const geometry = @import("geometry");
2
3
  const token_model = @import("tokens.zig");
3
4
  const widget_model = @import("widgets.zig");
5
+ const text_model = @import("text.zig");
4
6
  const text_spans_model = @import("text_spans.zig");
5
7
 
6
8
  const Density = token_model.Density;
@@ -103,13 +105,40 @@ pub fn widgetTextSpanLayoutOptions(widget: Widget, tokens: DesignTokens, max_wid
103
105
  return .{
104
106
  .size = widgetBodyTextSize(widget, tokens),
105
107
  .max_width = max_width,
106
- .wrap = .word,
108
+ .wrap = if (widget.text_no_wrap) .none else .word,
107
109
  .alignment = widget.text_alignment,
108
110
  .typography = tokens.typography,
109
111
  .measure = tokens.text_measure,
110
112
  };
111
113
  }
112
114
 
115
+ /// Width reserved before a numbered code paragraph: the largest muted
116
+ /// monospace marker plus the component's fixed marker-to-source gap.
117
+ /// Marker bytes never live in `Widget.text`; paint selects them from a
118
+ /// compile-time table.
119
+ pub fn widgetCodeLineNumberGutterWidth(widget: Widget, tokens: DesignTokens) f32 {
120
+ if (widget.code_line_number_digits == 0) return 0;
121
+ const zeros: [20]u8 = @splat('0');
122
+ const digits = @min(@as(usize, widget.code_line_number_digits), zeros.len);
123
+ return text_model.measureTextWidthForFont(
124
+ tokens.text_measure,
125
+ tokens.typography.mono_font_id,
126
+ zeros[0..digits],
127
+ widgetBodyTextSize(widget, tokens),
128
+ ) + 12;
129
+ }
130
+
131
+ /// Span paragraph content after authored padding and the engine-owned code
132
+ /// gutter. Layout, painting, hit mapping, and selection all use this exact
133
+ /// frame so numbered source stays one coherent text model.
134
+ pub fn widgetTextSpanContentFrame(widget: Widget, tokens: DesignTokens) geometry.RectF {
135
+ var content = widget.frame.inset(widget.layout.padding);
136
+ const gutter = @min(content.width, widgetCodeLineNumberGutterWidth(widget, tokens));
137
+ content.x += gutter;
138
+ content.width -= gutter;
139
+ return content;
140
+ }
141
+
113
142
  /// The ONE control height register — buttons, inputs, and select
114
143
  /// triggers all sit on the whole-pixel token ladder
115
144
  /// (`metrics.control_height_sm`/`control_height`/`control_height_lg`,
@@ -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
  }
@@ -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| {
@@ -863,6 +863,19 @@ pub const Widget = struct {
863
863
  /// tooling and write-back can round-trip it. Span paragraphs
864
864
  /// (`spans`) wrap by design and ignore it.
865
865
  text_no_wrap: bool = false,
866
+ /// Renderer-owned logical-line gutter for a syntax-code paragraph.
867
+ /// Zero keeps an ordinary paragraph; a positive value is the decimal
868
+ /// digit width of the largest marker. The gutter is decoration, not
869
+ /// retained text, so selection/copy remains the exact source bytes.
870
+ /// Stamped only by `Ui.code`; there is no generic builder/markup
871
+ /// channel for turning arbitrary paragraphs into numbered code.
872
+ code_line_number_digits: u8 = 0,
873
+ /// Nonzero on bounded paragraph chunks that together present one
874
+ /// selectable source-code document. The group id is the structural id
875
+ /// of their internal parent; offsets order each chunk's exact source
876
+ /// bytes without duplicating the full source in retained storage.
877
+ static_text_group_id: ObjectId = 0,
878
+ static_text_group_offset: usize = 0,
866
879
  /// What a single-line text run does with content that does not fit
867
880
  /// its frame (`ElementOptions.overflow` / markup `overflow=` on
868
881
  /// text leaves): `.ellipsis` (default) elides the tail behind a
package/src/root.zig CHANGED
@@ -6,6 +6,7 @@ pub const trace = @import("trace");
6
6
  pub const diagnostics = @import("diagnostics");
7
7
  pub const platform_info = @import("platform_info");
8
8
  pub const canvas = @import("canvas");
9
+ pub const code = canvas.code;
9
10
  pub const markdown = canvas.markdown;
10
11
 
11
12
  pub const runtime = @import("runtime/root.zig");