@native-sdk/cli 0.5.3 → 0.6.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 (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +3187 -264
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -0,0 +1,978 @@
1
+ //! The terminal grid: the `.terminal` widget's cell model and painter.
2
+ //!
3
+ //! The canvas owns the PIXELS of a terminal, never the emulator: a
4
+ //! `TerminalGrid` is a resolved snapshot of one emulator viewport —
5
+ //! per-cell code points, cluster bytes, and final colors — produced
6
+ //! outside this module (the runtime's terminal session adapter feeds a
7
+ //! live emulator; tests and the docs previews build snapshots by hand).
8
+ //! Keeping the snapshot emulator-free is what lets the widget render on
9
+ //! every canvas target: cell state arrives as plain data, and this
10
+ //! painter turns it into REAL text runs, geometric box drawing
11
+ //! (`terminal_box.zig`), the selection wash, the cursor, and the
12
+ //! scrollback indicator — damage kept row-shaped by stable command ids.
13
+ //!
14
+ //! Colors arrive RESOLVED. The producer owns the palette policy (the
15
+ //! theme-derived ANSI-16 story, exact 256-color and truecolor); the
16
+ //! painter draws the colors it is handed, so two producers with
17
+ //! different palette policies still paint through one code path.
18
+ //!
19
+ //! Budgets: painting degrades ROW-ATOMICALLY under three ceilings — the
20
+ //! display-list command budget, the text-byte store, and the
21
+ //! glyph-atlas proxy — so a pathological screen paints fewer complete
22
+ //! rows instead of failing the whole frame. Each ceiling's preflight
23
+ //! mirrors the paint loop's emissions exactly; counting bytes the loop
24
+ //! would suppress would silently blank every row after a paintable one.
25
+
26
+ const std = @import("std");
27
+ const canvas = @import("root.zig");
28
+ const geometry = @import("geometry");
29
+ const box = @import("terminal_box.zig");
30
+
31
+ /// Grid ceilings, derived from the per-view canvas budgets: the glyph
32
+ /// budget bounds how many cells can hold ink at once, and the command
33
+ /// budget bounds per-row style runs. A viewport is clamped to these
34
+ /// before it reaches an emulator, so a huge window degrades to a
35
+ /// bounded grid instead of a budget error.
36
+ pub const max_cols: usize = 320;
37
+ pub const max_rows: usize = 96;
38
+ pub const max_cells: usize = 7168;
39
+
40
+ /// Painter budgets when the grid rides the WIDGET tree, where it shares
41
+ /// the per-view stores with every other widget. The command reserve is
42
+ /// the tail held back from the display-list capacity for the widgets
43
+ /// emitted after the grid (a status bar, window chrome); the text
44
+ /// reserve holds back the same store their labels draw from; the glyph
45
+ /// budget mirrors the runtime's per-view glyph-atlas capacity minus a
46
+ /// chrome allowance (a lockstep test on the runtime side keeps the
47
+ /// mirror honest). A grid that would cross any of them degrades to
48
+ /// fewer complete rows instead of failing the frame.
49
+ pub const widget_command_reserve: usize = 256;
50
+ pub const widget_text_reserve: usize = 8192;
51
+ // Sized to hold ONE maximal filled-line chart series after the grid: a
52
+ // 256-point series strokes its polyline (256 elements) AND fills its
53
+ // area (the points plus closure vertices down to the baseline), so the
54
+ // reserve derives from the series ceiling with slack for the closure —
55
+ // a flat 512 fell three elements short of exactly that documented
56
+ // maximum.
57
+ pub const widget_path_reserve: usize = 2 * chart_ceiling + 16;
58
+ const chart_ceiling: usize = canvas.max_chart_points_per_series;
59
+ pub const widget_glyph_budget: usize = 8192 - 512;
60
+
61
+ /// One text run's staging capacity — shared by the paint loop's scratch
62
+ /// and the preflight's per-cell cap so measure and emission agree.
63
+ /// Sized to the WHOLE display-list text store, so the paint tier is
64
+ /// never the binding constraint on a grapheme cluster: any cluster the
65
+ /// producer hands over paints complete, and only a cluster the store
66
+ /// itself cannot hold skips — row-atomically, the preflight rule.
67
+ const text_scratch_bytes: usize = canvas.max_display_list_text_bytes;
68
+
69
+ /// Cell occupancy: a `.wide` cell paints a two-column cluster and the
70
+ /// following `.spacer` column carries no ink of its own (its background
71
+ /// is pre-resolved by the producer to extend the primary's, so a styled
72
+ /// wide character never paints over half its width).
73
+ pub const TerminalWide = enum(u2) { narrow, wide, spacer };
74
+
75
+ /// One resolved viewport cell. `cp == 0` paints no ink (an empty cell,
76
+ /// or one whose style suppressed it — the producer resolves invisible
77
+ /// styling to 0 so measure and paint cannot disagree). Box-drawing code
78
+ /// points render as GEOMETRY at exact cell bounds, never font glyphs,
79
+ /// so their `cluster` stays empty.
80
+ pub const TerminalCell = struct {
81
+ /// Primary code point; 0 paints nothing.
82
+ cp: u21 = 0,
83
+ /// UTF-8 bytes of the full cluster (primary code point plus every
84
+ /// combining mark), producer-owned for the snapshot's lifetime.
85
+ /// Empty exactly when `cp` is 0 or names a box-drawing cell.
86
+ cluster: []const u8 = "",
87
+ fg: canvas.Color = canvas.Color.rgba(1, 1, 1, 1),
88
+ /// Resolved cell background; null paints the grid background only.
89
+ bg: ?canvas.Color = null,
90
+ underline: bool = false,
91
+ wide: TerminalWide = .narrow,
92
+ };
93
+
94
+ pub const TerminalRow = struct {
95
+ cells: []const TerminalCell = &.{},
96
+ /// Inclusive selected column range, viewport-resolved by the
97
+ /// producer (the painter draws the wash; the selection MODEL stays
98
+ /// with the emulator).
99
+ selection: ?[2]u16 = null,
100
+ };
101
+
102
+ pub const TerminalCursorShape = enum { block, bar, underline };
103
+
104
+ pub const TerminalCursor = struct {
105
+ x: u16 = 0,
106
+ y: u16 = 0,
107
+ shape: TerminalCursorShape = .block,
108
+ };
109
+
110
+ pub const TerminalCellPos = struct { x: u16 = 0, y: u16 = 0 };
111
+
112
+ /// Scrollback indicator state: `offset` rows of content sit above the
113
+ /// viewport's first row, `len` rows are visible, `total` rows exist.
114
+ pub const TerminalScrollbar = struct {
115
+ offset: u32 = 0,
116
+ len: u32 = 0,
117
+ total: u32 = 0,
118
+ };
119
+
120
+ /// One resolved emulator viewport, ready to paint. Produced outside the
121
+ /// canvas (the runtime session adapter, a test, a docs scene); every
122
+ /// slice is producer-owned and must outlive the build that references
123
+ /// it.
124
+ pub const TerminalGrid = struct {
125
+ rows: []const TerminalRow = &.{},
126
+ /// Resolved surface colors: the producer's palette policy applied
127
+ /// (theme defaults, an application's OSC overrides, DECSCNM).
128
+ background: canvas.Color,
129
+ foreground: canvas.Color,
130
+ cursor_color: canvas.Color,
131
+ selection_color: canvas.Color,
132
+ cursor: ?TerminalCursor = null,
133
+ /// The session is live: the cursor paints filled; an ended session
134
+ /// paints it hollow-dim, the honest at-rest state.
135
+ running: bool = true,
136
+ /// Keyboard-selection caret: while selection mode is armed the head
137
+ /// cell paints a focus outline (the selection wash itself rides the
138
+ /// rows' `selection` ranges).
139
+ select_head: ?TerminalCellPos = null,
140
+ scrollbar: TerminalScrollbar = .{},
141
+ /// The viewport as PLAIN TEXT — the grid's accessibility surface (a
142
+ /// terminal's semantic content is its text) and, through the widget
143
+ /// text channel, the a11y-tree fingerprint's coverage of the
144
+ /// viewport's CHARACTERS. It is text only: colors, styles, the
145
+ /// cursor position, the selection, and the running state are NOT
146
+ /// encoded here, so two viewports with identical characters but
147
+ /// different colors or cursor cells hash alike. The producer that
148
+ /// owns replay-grade determinism must fold those channels into its
149
+ /// own checkpoint; this field is the text-coverage layer, not a
150
+ /// whole-cell-state hash. Empty means "unknown", never "same as
151
+ /// before".
152
+ screen_text: []const u8 = "",
153
+ /// The emulator-serialized pointer selection, ready for the
154
+ /// platform clipboard. Empty means no copyable selection. This is
155
+ /// deliberately separate from `screen_text`: terminal selections
156
+ /// follow cell pins (including soft wraps and wide cells), so byte
157
+ /// offsets into the accessibility string are not an honest
158
+ /// selection model.
159
+ selection_text: []const u8 = "",
160
+ /// Whether the emulator currently owns a selection, including a
161
+ /// whitespace-only range whose trimmed `selection_text` is empty.
162
+ /// Pointer release uses this to distinguish select-drag from click.
163
+ selection_active: bool = false,
164
+ };
165
+
166
+ /// The app-visible terminal view state: the payload `on-terminal`
167
+ /// delivers and the shape the `scrollback` attribute echoes back into
168
+ /// (the ScrollState source-wins precedent). Deliberately ONLY what the
169
+ /// app legitimately owns — the scrollback position it may set and the
170
+ /// layout-derived grid it may display; emulator internals (cell state,
171
+ /// modes, selection pins) stay framework-owned and never surface here.
172
+ pub const TerminalState = struct {
173
+ /// Rows the viewport sits above the live screen; 0 is pinned to the
174
+ /// bottom (the live view). Echo it into `scrollback` and the
175
+ /// runtime-owned position survives rebuilds; move it model-side to
176
+ /// scroll programmatically.
177
+ scrollback: u32 = 0,
178
+ /// Total rows of history above the live screen (the scrollback
179
+ /// ceiling `scrollback` clamps against).
180
+ history: u32 = 0,
181
+ /// The live grid the layout derived, in cells — what the pty was
182
+ /// last resized to.
183
+ cols: u16 = 0,
184
+ rows: u16 = 0,
185
+ };
186
+
187
+ /// Mono cell metrics at the terminal type size, derived from the active
188
+ /// tokens: one seam shared by the painter and the runtime's grid sizing
189
+ /// so the cells painted and the cols/rows pushed to the pty can never
190
+ /// disagree.
191
+ pub const TerminalCellMetrics = struct {
192
+ width: f32,
193
+ height: f32,
194
+ font_size: f32,
195
+ };
196
+
197
+ /// Glyphs in the advance probe. A row paints as MERGED text runs the
198
+ /// text layout advances itself, so the cell width has to be the layout's
199
+ /// own advance: one glyph's measured width is its box, which on a real
200
+ /// mono face sits inside the advance, and the difference compounds
201
+ /// across a run until the row's tail clips at the widget edge. Measuring
202
+ /// a run and dividing takes the advance the layout will actually use
203
+ /// (every mono cell the same), so column N lands where the painter's
204
+ /// backgrounds, cursor, and selection put it.
205
+ const advance_probe_len = 16;
206
+ const advance_probe = "M" ** advance_probe_len;
207
+
208
+ pub fn cellMetrics(tokens: canvas.DesignTokens) TerminalCellMetrics {
209
+ const font_size = tokens.typography.label_size;
210
+ const height = @round(font_size * 1.4);
211
+ var width: f32 = @round(font_size * 0.6);
212
+ const measured = canvas.measureTextWidthForFont(
213
+ tokens.text_measure,
214
+ tokens.typography.mono_font_id,
215
+ advance_probe,
216
+ font_size,
217
+ );
218
+ if (measured > 0) width = measured / advance_probe_len;
219
+ // Deliberately NOT quantized to the device pixel grid: the cell
220
+ // width has to be the advance the text renderer actually walks a
221
+ // merged run by, and that advance is the face's, not a rounded one.
222
+ // Rounding it — even to a whole device pixel — makes every glyph in
223
+ // a run land a fraction past its cell, and by column 50 the drift is
224
+ // visible against the cell backgrounds, cursor, and selection.
225
+ return .{ .width = width, .height = height, .font_size = font_size };
226
+ }
227
+
228
+ /// Clamp a proposed grid to the canvas budgets: the glyph budget bounds
229
+ /// total cells, so a very wide viewport trades rows for columns to stay
230
+ /// under the cell ceiling instead of overflowing the frame.
231
+ pub fn clampGrid(proposed_cols: usize, proposed_rows: usize) TerminalCellPos {
232
+ var c = std.math.clamp(proposed_cols, 2, max_cols);
233
+ var r = std.math.clamp(proposed_rows, 2, max_rows);
234
+ if (c * r > max_cells) r = @max(2, max_cells / c);
235
+ if (c * r > max_cells) c = @max(2, max_cells / r);
236
+ return .{ .x = @intCast(c), .y = @intCast(r) };
237
+ }
238
+
239
+ // ------------------------------------------------------------- painting
240
+
241
+ /// Everything one paint needs beyond the grid.
242
+ pub const TerminalPaintOptions = struct {
243
+ /// Grid origin and extent in canvas points (the text region).
244
+ frame: geometry.RectF,
245
+ tokens: canvas.DesignTokens,
246
+ /// Whether this terminal owns keyboard focus. A live focused cursor
247
+ /// paints solid; an unfocused cursor paints as a hollow outline, the
248
+ /// conventional terminal-window focus cue. Defaults on for direct
249
+ /// painter callers; the `.terminal` widget always supplies its live
250
+ /// logical focus state.
251
+ focused: bool = true,
252
+ /// The rect the grid background fills — the widget's whole frame,
253
+ /// so the inset text region sits on a full-bleed surface. Null
254
+ /// fills `frame` (tests that paint the grid alone).
255
+ background_frame: ?geometry.RectF = null,
256
+ /// Namespace for the emitted command ids: stable per widget, so the
257
+ /// retained renderer matches rows across rebuilds and damage stays
258
+ /// row-shaped. Pass the widget id (or any per-grid-stable value).
259
+ id_base: u64 = 0,
260
+ /// Hard ceiling on display-list commands this paint may emit. A
261
+ /// pathological screen (every cell a different style, so no run
262
+ /// merges) can generate more commands than the budget; painting
263
+ /// stops row-wise at the ceiling rather than overflowing the frame.
264
+ /// 0 means unbounded (tests that size their own builder).
265
+ command_budget: usize = 0,
266
+ /// Display-list TEXT bytes to hold back from the grid for the other
267
+ /// widgets in the same view (they draw their own glyphs into the
268
+ /// SAME per-view text store): the grid degrades to fewer painted
269
+ /// rows instead of pushing the combined display list over the
270
+ /// runtime limit and failing the whole frame. 0 means the grid may
271
+ /// use the whole store.
272
+ text_reserve: usize = 0,
273
+ /// Path elements to hold back from the grid for the widgets after
274
+ /// it (a chart's polylines, the checkbox mark, the spinner arc all
275
+ /// draw from the same per-view element store): the grid's
276
+ /// rounded-corner rows degrade instead of starving them into
277
+ /// ChartPathElementListFull. 0 means the grid may use the whole
278
+ /// store.
279
+ path_reserve: usize = 0,
280
+ /// Ceiling on glyph-ATLAS ENTRIES the grid may claim in one paint
281
+ /// (the runtime's per-view atlas capacity minus a reserve): every
282
+ /// new distinct code point is charged at the atlas's subpixel
283
+ /// variant multiplier (`atlas_variants_per_glyph`), since one
284
+ /// scalar occupies up to four x-bucket entries across a row's
285
+ /// columns. Painting stops row-atomically BEFORE the row whose new
286
+ /// code points would cross it. 0 means unbounded.
287
+ glyph_budget: usize = 0,
288
+ };
289
+
290
+ /// The painter's command-id base for a caller's `id_base` (typically a
291
+ /// widget id): the widget part-id convention scaled up. `widgetPartId`
292
+ /// reserves the low 4 bits for a widget's part slots (`id *% 16 + slot`,
293
+ /// slots < 16); the grid needs a larger slot space (rows x runs x
294
+ /// decorations), so it reserves the low 24 bits (`id *% 2^24 + offset`,
295
+ /// every painter offset < 2^24). The guarantee is EXACTLY the part-id
296
+ /// convention's: the wrapping multiply discards the id's top bits, so
297
+ /// two ids agreeing modulo 2^40 share a namespace (as two ids agreeing
298
+ /// modulo 2^60 share a `widgetPartId` namespace) — the framework's
299
+ /// accepted residual, unreachable for the structural-hash ids real
300
+ /// widgets carry and identical in kind to what every other widget's
301
+ /// commands already live with. Within one grid, and between grids whose
302
+ /// ids differ modulo 2^40, commands can never collide.
303
+ /// An id of 0 is the framework's ANONYMOUS convention (`widgetPartId`
304
+ /// returns 0 for it): the painter then emits EVERY command with id 0 —
305
+ /// no retained identity, no cross-widget collisions.
306
+ /// A caller that emits its OWN commands around the grid (a widget's
307
+ /// focus ring) must derive its ids from THIS base at an offset the
308
+ /// painter leaves free (see `reserved_id_offset`).
309
+ pub fn paintIdBase(id: u64) u64 {
310
+ return id *% (1 << 24);
311
+ }
312
+
313
+ /// An id offset the painter never emits (its own commands stay within
314
+ /// `id_base + [0, 0x61_ffff]`): callers layering commands over the grid
315
+ /// claim ids at `paintIdBase(id) + reserved_id_offset + n` (n < 2^16,
316
+ /// keeping the whole namespace under the 2^24 stride).
317
+ pub const reserved_id_offset: u64 = 0x62_0000;
318
+
319
+ /// The paint's command-id derivation: keyed grids take `base + offset`
320
+ /// (offsets < 2^24, disjoint per widget by the `paintIdBase` stride);
321
+ /// an anonymous grid (caller id 0) emits every command with id 0, the
322
+ /// `widgetPartId` convention for identity-less widgets.
323
+ const CommandIds = struct {
324
+ base: u64,
325
+ keyed: bool,
326
+
327
+ fn at(self: CommandIds, offset: u64) u64 {
328
+ return if (self.keyed) self.base +% offset else 0;
329
+ }
330
+ };
331
+
332
+ /// Atlas entries one DISTINCT code point can occupy: the runtime atlas
333
+ /// keys on (font, glyph, size, subpixel_x, subpixel_y), and the
334
+ /// subpixel quantization has FOUR x buckets — a fractional cell width
335
+ /// walks the same scalar through all of them across a row's columns
336
+ /// (the grid's rows share one y bucket: row advance is the rounded
337
+ /// integral cell height). The glyph preflight charges every new code
338
+ /// point at this multiplier so a grid within its budget can never
339
+ /// undercount its own atlas usage 4x and fail the frame with
340
+ /// GlyphAtlasListFull.
341
+ const atlas_variants_per_glyph: usize = 4;
342
+
343
+ /// Distinct-code-point probe set backing `glyph_budget`: open-addressed,
344
+ /// power-of-two slots, zero meaning empty (a stored value is `cp + 1` so
345
+ /// U+0000 never aliases an empty slot). Sized at twice the runtime's
346
+ /// per-view atlas capacity so any honest budget stays under half load
347
+ /// and lookups stay O(1); budgets are clamped to half the slots so the
348
+ /// probe loop can never run against a full table.
349
+ const glyph_probe_slots: usize = 16384;
350
+
351
+ fn glyphProbeInsert(slots: *[glyph_probe_slots]u32, cp: u21) bool {
352
+ const stored: u32 = @as(u32, cp) + 1;
353
+ var index: usize = (stored *% 0x9E37_79B1) >> (32 - 14);
354
+ while (true) {
355
+ const entry = slots[index];
356
+ if (entry == stored) return false;
357
+ if (entry == 0) {
358
+ slots[index] = stored;
359
+ return true;
360
+ }
361
+ index = (index + 1) & (glyph_probe_slots - 1);
362
+ }
363
+ }
364
+
365
+ /// Count the row's code points NOT yet in `seen`, inserting them —
366
+ /// mirroring the paint loop's emissions exactly (spacer cells and box
367
+ /// cells contribute nothing; a cluster's combining marks count like its
368
+ /// primary). Entries inserted by a row the budget then rejects stay in
369
+ /// the set harmlessly: painting stops at that row, so the set is never
370
+ /// consulted again.
371
+ fn rowNewGlyphs(row: TerminalRow, seen: *[glyph_probe_slots]u32) usize {
372
+ var new_count: usize = 0;
373
+ for (row.cells) |cell| {
374
+ if (cell.wide == .spacer or cell.cp == 0) continue;
375
+ if (box.isBoxDrawing(cell.cp)) continue;
376
+ var iterator = std.unicode.Utf8Iterator{ .bytes = cell.cluster, .i = 0 };
377
+ while (iterator.nextCodepoint()) |cp| {
378
+ if (glyphProbeInsert(seen, cp)) new_count += 1;
379
+ }
380
+ }
381
+ return new_count;
382
+ }
383
+
384
+ /// The bytes painting will actually EMIT for one cell — the preflight
385
+ /// (`rowTextBytes`) sums these against the text store, so this mirrors
386
+ /// the paint loop's suppressions exactly: spacer, empty, and box cells
387
+ /// paint no text.
388
+ fn cellTextBytes(cell: TerminalCell) usize {
389
+ if (cell.wide == .spacer or cell.cp == 0) return 0;
390
+ if (box.isBoxDrawing(cell.cp)) return 0;
391
+ return cell.cluster.len;
392
+ }
393
+
394
+ fn rowTextBytes(row: TerminalRow) usize {
395
+ var total: usize = 0;
396
+ for (row.cells) |cell| total += cellTextBytes(cell);
397
+ return total;
398
+ }
399
+
400
+ /// Rounded-corner code points that draw through `strokePath` and so
401
+ /// consume the builder's path-element store (three elements each). Every
402
+ /// other box glyph paints as `fillRect`s and consumes none.
403
+ fn cellPathElements(cell: TerminalCell) usize {
404
+ if (cell.wide == .spacer or cell.cp == 0) return 0;
405
+ return switch (cell.cp) {
406
+ 0x256D, 0x256E, 0x256F, 0x2570 => 3,
407
+ else => 0,
408
+ };
409
+ }
410
+
411
+ fn rowPathElements(row: TerminalRow) usize {
412
+ var total: usize = 0;
413
+ for (row.cells) |cell| total += cellPathElements(cell);
414
+ return total;
415
+ }
416
+
417
+ /// Text bytes ALREADY in the display list — every `draw_text`, whether
418
+ /// its bytes are builder-owned (a chart's labels, this grid's own runs)
419
+ /// or referenced from view-owned memory (an earlier text widget). The
420
+ /// runtime's per-view text budget (`CanvasResourceCounts`, 32 KiB)
421
+ /// counts them all, so the grid must degrade against this total, not
422
+ /// against its builder-owned counter alone.
423
+ fn displayListTextBytes(list: canvas.DisplayList) usize {
424
+ var total: usize = 0;
425
+ for (list.commands) |command| {
426
+ if (command == .draw_text) total += command.draw_text.text.len;
427
+ }
428
+ return total;
429
+ }
430
+
431
+ /// Path elements already in the display list — every `fill_path`/
432
+ /// `stroke_path`, including static (comptime) paths that bypass the
433
+ /// builder's element store (an icon's geometry). The runtime's per-view
434
+ /// path-element budget (2048) counts them all.
435
+ fn displayListPathElements(list: canvas.DisplayList) usize {
436
+ var total: usize = 0;
437
+ for (list.commands) |command| {
438
+ total += switch (command) {
439
+ .fill_path => |c| c.elements.len,
440
+ .stroke_path => |c| c.elements.len,
441
+ else => 0,
442
+ };
443
+ }
444
+ return total;
445
+ }
446
+
447
+ /// An UPPER BOUND on the display-list commands one row emits, assuming
448
+ /// no runs merge (the pathological worst case): a background run per
449
+ /// cell that carries one, plus the cell's ink — eight commands for a
450
+ /// pure-double box joint, two (text run + underline) for a styled
451
+ /// character, none for an empty cell — plus one selection wash. Real
452
+ /// rows merge runs and cost far less; this bound is what the per-row
453
+ /// preflight checks so a row is only started when it can finish whole,
454
+ /// and it is content-accurate (a cheap ASCII row costs ~2/column, not a
455
+ /// flat worst-case-per-column reserve that would starve wide grids).
456
+ fn rowCommandCost(row: TerminalRow) usize {
457
+ var total: usize = 1; // the selection wash
458
+ var i: usize = 0;
459
+ while (i < row.cells.len) : (i += 1) {
460
+ const cell = row.cells[i];
461
+ if (cell.wide == .spacer) continue;
462
+ if (cell.bg != null) total += 1;
463
+ if (cell.cp == 0) continue;
464
+ if (box.isBoxDrawing(cell.cp)) {
465
+ if (box.mergesHorizontally(cell.cp)) {
466
+ // A horizontally-merged run (a long `─` border) paints
467
+ // ONE geometry command plus a possible underline, no
468
+ // matter how wide — mirror the paint loop's merge (same
469
+ // code point, foreground, and underline) so the estimate
470
+ // does not charge nine per column for what collapses to
471
+ // two commands. Backgrounds still count per cell (their
472
+ // own run pass is separate).
473
+ var span: usize = 1;
474
+ while (i + span < row.cells.len) : (span += 1) {
475
+ const next = row.cells[i + span];
476
+ if (next.cp != cell.cp or !colorEql(next.fg, cell.fg) or next.underline != cell.underline) break;
477
+ if (next.bg != null) total += 1;
478
+ }
479
+ // A merged run's worst-case ink: a double piece (═)
480
+ // paints TWO parallel bars, plus a possible underline.
481
+ total += 3;
482
+ i += span - 1;
483
+ } else {
484
+ // The glyph's own worst case (kept lockstep with the
485
+ // paint switch by `box.maxCommands`) plus a possible
486
+ // underline — a row of one-bar pieces costs what it
487
+ // paints, never a flat joint-worst-case that starves
488
+ // wide grids.
489
+ total += box.maxCommands(cell.cp) + 1;
490
+ }
491
+ } else {
492
+ total += 2; // the text run plus its underline
493
+ }
494
+ }
495
+ return total;
496
+ }
497
+
498
+ fn colorEql(a: canvas.Color, b: canvas.Color) bool {
499
+ return a.r == b.r and a.g == b.g and a.b == b.b and a.a == b.a;
500
+ }
501
+
502
+ /// Paint the grid into the display list: per-row background runs, the
503
+ /// selection wash, per-run text, decorations, the cursor, the keyboard
504
+ /// caret, and the scrollback indicator. Row commands carry stable ids
505
+ /// derived from `options.id_base` so the retained renderer's diff keeps
506
+ /// damage row-shaped.
507
+ pub fn paint(grid: TerminalGrid, builder: *canvas.Builder, options: TerminalPaintOptions) !void {
508
+ const tokens = options.tokens;
509
+ const metrics = cellMetrics(tokens);
510
+ // The command-id namespace (see `paintIdBase`): the widget part-id
511
+ // convention with a 24-bit slot space. An anonymous caller (id 0)
512
+ // keeps the framework's unkeyed convention — every command id 0.
513
+ const ids = CommandIds{ .base = paintIdBase(options.id_base), .keyed = options.id_base != 0 };
514
+
515
+ // Fixed prologue/epilogue overhead (background fill, clip push,
516
+ // scrollbar thumb, clip pop): if the builder — with whatever earlier
517
+ // widgets already emitted — cannot seat that overhead under the
518
+ // budget, the paint degrades to nothing BEFORE emitting the prologue,
519
+ // so a full builder never overruns its ceiling and never leaves an
520
+ // unbalanced clip. The `builder.len` term is what makes the check an
521
+ // ABSOLUTE ceiling, not a per-paint one. 0 stays the unbounded
522
+ // (test) mode.
523
+ const fixed_overhead: usize = 8;
524
+ if (options.command_budget > 0 and builder.len + fixed_overhead > options.command_budget) return;
525
+
526
+ // The terminal surface: full-bleed background under the grid.
527
+ try builder.fillRect(.{
528
+ .id = ids.at(0x61_0000),
529
+ .rect = options.background_frame orelse options.frame,
530
+ .fill = .{ .color = grid.background },
531
+ });
532
+
533
+ // Everything the grid paints is CLIPPED to its frame: for one frame
534
+ // after a shrink the producer may still hold the pre-resize grid,
535
+ // and unclipped rows or wide cells would paint past the region. The
536
+ // clip makes the stale frame degrade to a cropped grid.
537
+ try builder.pushClip(.{ .id = ids.at(0x61_0001), .rect = options.frame });
538
+
539
+ const origin_x = options.frame.x;
540
+ const origin_y = options.frame.y;
541
+ const cell_w = metrics.width;
542
+ const cell_h = metrics.height;
543
+
544
+ // The id stride between box cells: a pure-double joint (╬ ╪ ╫ and the
545
+ // double tees) emits up to eight commands, so a shorter stride would
546
+ // collide adjacent double cells' ids.
547
+ const commands_per_cell: usize = 8;
548
+ // The command budget is checked PER ROW against that row's actual
549
+ // upper-bound cost (`rowCommandCost`), not a flat worst-case-per-
550
+ // column reserve: a cheap ASCII row costs ~2/column, so a wide grid
551
+ // paints its rows instead of reserving them all away. The epilogue
552
+ // (cursor, caret, scrollbar thumb, clip pop) rides this fixed slack.
553
+ const epilogue_reserve: usize = 8;
554
+ // The per-view TEXT budget is a separate ceiling from the command
555
+ // count, and the runtime enforces it over EVERY `draw_text` in the
556
+ // finished display list (`CanvasResourceCounts`, 32 KiB) — referenced
557
+ // sibling text included, not just this builder's own `allocTextBytes`
558
+ // bytes. So the grid degrades against the running total of ALL text
559
+ // already in the list plus what it adds, minus the reserve held back
560
+ // for widgets emitted AFTER it. Each row is measured up front and
561
+ // skipped WHOLE if it would cross the ceiling — never torn midway.
562
+ const text_ceiling: usize = if (canvas.max_display_list_text_bytes > options.text_reserve)
563
+ canvas.max_display_list_text_bytes - options.text_reserve
564
+ else
565
+ 0;
566
+ var text_total: usize = displayListTextBytes(builder.displayList());
567
+ // The per-view PATH-ELEMENT budget (2048), likewise enforced over the
568
+ // whole display list including static sibling paths (an icon's
569
+ // geometry) that never touch this builder's element store — so the
570
+ // rounded-corner preflight degrades against the running list total,
571
+ // not the builder-owned counter alone.
572
+ var path_total: usize = displayListPathElements(builder.displayList());
573
+ const path_ceiling: usize = builder.path_elements.len -| options.path_reserve;
574
+
575
+ // The glyph-atlas proxy budget (see `TerminalPaintOptions`): clamped
576
+ // under half the probe table so insertion can never scan a full
577
+ // ring; the set costs one 64 KiB clear per bounded paint.
578
+ const glyph_budget = @min(options.glyph_budget, glyph_probe_slots / 2);
579
+ var glyph_seen: [glyph_probe_slots]u32 = undefined;
580
+ if (glyph_budget > 0) @memset(&glyph_seen, 0);
581
+ var glyphs_counted: usize = 0;
582
+
583
+ // Light box-drawing line weight, scaled with the cell (roughly the
584
+ // stroke a terminal font would carry at this size).
585
+ const box_thickness: f32 = @max(1, @round(metrics.font_size / 8));
586
+
587
+ // A run's staging buffer, sized to the whole text store (see
588
+ // `text_scratch_bytes`): any cluster the store can hold stages
589
+ // whole. The run-break flushes when the buffer nears full, so long
590
+ // runs simply split across draw commands rather than overflow.
591
+ var text_scratch: [text_scratch_bytes]u8 = undefined;
592
+ // Rows painted so far (the loop paints 0..N contiguously from the
593
+ // top and stops at the first row a budget rejects): the cursor and
594
+ // caret below are suppressed on any row this never reached, so a row
595
+ // dropped for budget never leaves its lone cursor floating over the
596
+ // blank background.
597
+ var painted_rows: usize = 0;
598
+ for (grid.rows, 0..) |row, row_index| {
599
+ // Command-count stop, ATOMIC per row: this row's actual
600
+ // upper-bound cost plus the epilogue must fit the budget, so a
601
+ // cheap wide row paints while a genuinely too-dense row (and
602
+ // everything after it) is skipped whole — never started and torn.
603
+ if (options.command_budget > 0 and
604
+ builder.len + rowCommandCost(row) + epilogue_reserve > options.command_budget) break;
605
+ // Text stop, ATOMIC per row, against the view-global running
606
+ // total (all draw_text already in the list plus this row's
607
+ // bytes) — stop BEFORE a row that would cross the per-view text
608
+ // ceiling, never emit its first runs and then have the frame
609
+ // rejected at commit. A row that ADDS no text can never cross
610
+ // anything, so it paints even when earlier widgets already sit
611
+ // past the grid's reserved share — the ceiling bounds what the
612
+ // grid adds, not what its siblings spent.
613
+ const row_text = rowTextBytes(row);
614
+ if (row_text > 0 and text_total + row_text > text_ceiling) break;
615
+ // Path-element stop, ATOMIC per row, against the view-global
616
+ // running total (static sibling paths included): a row of rounded
617
+ // corners is skipped BEFORE it would cross the per-view
618
+ // path-element budget; a row adding none paints regardless.
619
+ const row_paths = rowPathElements(row);
620
+ if (row_paths > 0 and path_total + row_paths > path_ceiling) break;
621
+ // Glyph-budget stop, same row-atomic shape: stop BEFORE the row
622
+ // whose new DISTINCT code points would cross the atlas proxy —
623
+ // the frame degrades to fewer rows instead of failing whole on
624
+ // `GlyphAtlasListFull`.
625
+ if (glyph_budget > 0) {
626
+ glyphs_counted += rowNewGlyphs(row, &glyph_seen) * atlas_variants_per_glyph;
627
+ if (glyphs_counted > glyph_budget) break;
628
+ }
629
+ // Row-atomic rollback snapshot: the preflights above make a tear
630
+ // unreachable, but if a builder store is ever exhausted mid-row
631
+ // anyway, these restore points drop the partial row's commands
632
+ // whole (see the `row_torn` handling below) so nothing half a row
633
+ // ever reaches the glass.
634
+ const row_start_len = builder.len;
635
+ const row_start_paths = builder.path_element_len;
636
+ const row_start_text = builder.text_byte_len;
637
+ const row_y = origin_y + @as(f32, @floatFromInt(row_index)) * cell_h;
638
+ // Rows STARTING at or past the frame's bottom paint nothing
639
+ // visible; a row straddling the edge still paints and the clip
640
+ // crops it, so content reaches the very edge without spilling.
641
+ if (row_y >= options.frame.y + options.frame.height) break;
642
+ const row_id = @as(u64, @intCast(row_index)) << 16;
643
+
644
+ // Background runs: contiguous cells sharing a non-default bg
645
+ // (the producer already extended a wide primary's background
646
+ // onto its spacer column).
647
+ var run_start: usize = 0;
648
+ var run_color: ?canvas.Color = null;
649
+ var x: usize = 0;
650
+ while (x <= row.cells.len) : (x += 1) {
651
+ const bg: ?canvas.Color = if (x < row.cells.len) row.cells[x].bg else null;
652
+ if (run_color) |color| {
653
+ const same = if (bg) |next| colorEql(color, next) else false;
654
+ if (!same) {
655
+ try builder.fillRect(.{
656
+ .id = ids.at(row_id + 1 + run_start),
657
+ .rect = geometry.RectF.init(
658
+ origin_x + @as(f32, @floatFromInt(run_start)) * cell_w,
659
+ row_y,
660
+ @as(f32, @floatFromInt(x - run_start)) * cell_w,
661
+ cell_h,
662
+ ),
663
+ .fill = .{ .color = color },
664
+ });
665
+ run_color = bg;
666
+ run_start = x;
667
+ }
668
+ } else if (bg != null) {
669
+ run_color = bg;
670
+ run_start = x;
671
+ }
672
+ }
673
+
674
+ // Selection wash (under the ink, over the backgrounds).
675
+ if (row.selection) |range| {
676
+ const wash = canvas.Color.rgba(
677
+ grid.selection_color.r,
678
+ grid.selection_color.g,
679
+ grid.selection_color.b,
680
+ 0.30,
681
+ );
682
+ try builder.fillRect(.{
683
+ .id = ids.at(row_id + 0x4000),
684
+ .rect = geometry.RectF.init(
685
+ origin_x + @as(f32, @floatFromInt(range[0])) * cell_w,
686
+ row_y,
687
+ @as(f32, @floatFromInt(@as(usize, range[1]) - range[0] + 1)) * cell_w,
688
+ cell_h,
689
+ ),
690
+ .fill = .{ .color = wash },
691
+ });
692
+ }
693
+
694
+ // Text runs: contiguous cells sharing a foreground, flushed on
695
+ // color or decoration change (bold/italic render with the one
696
+ // mono face — weight axes require registered companion faces,
697
+ // a limitation the docs state outright).
698
+ // A builder-store exhaustion mid-row (the display list, its text
699
+ // bytes, or its path elements filling despite the reserves) TEARS
700
+ // the row: the reserves make it unreachable in the widget path,
701
+ // but if it ever happens the row is left incomplete, so it must
702
+ // NOT count as painted and no further row may start — otherwise
703
+ // the cursor could paint over content the tear dropped.
704
+ var row_torn = false;
705
+ var run_len: usize = 0;
706
+ var run_x: usize = 0;
707
+ var run_fg: canvas.Color = grid.foreground;
708
+ var run_underline = false;
709
+ var text_len: usize = 0;
710
+ // Multi-codepoint clusters (combining marks) paint as their OWN
711
+ // single-cell run at their exact cell origin: inside a merged
712
+ // run their advance would come from the text layout, and a
713
+ // layout that advances a combining mark by a full glyph would
714
+ // shift every later cell in the run off the grid — while the
715
+ // backgrounds, cursor, and selection stayed cell-aligned.
716
+ // Isolating the cluster pins its neighbors to their own cell
717
+ // origins whatever the mark advances to; plain single-scalar
718
+ // runs keep the merged fast path.
719
+ var break_after_cluster = false;
720
+ x = 0;
721
+ while (x <= row.cells.len) : (x += 1) {
722
+ var cp: u21 = 0;
723
+ var fg = grid.foreground;
724
+ var underline = false;
725
+ var skip = false;
726
+ var box_cp: u21 = 0;
727
+ var cell_bytes: usize = 0;
728
+ var multi_cluster = false;
729
+ if (x < row.cells.len) {
730
+ const cell = row.cells[x];
731
+ if (cell.wide == .spacer) skip = true;
732
+ cp = cell.cp;
733
+ fg = cell.fg;
734
+ underline = cell.underline;
735
+ // Box-drawing, block, and shade cells render as GEOMETRY
736
+ // at exact cell bounds, never font glyphs: glyphs fill
737
+ // the em box, not the padded cell, so borders drawn from
738
+ // them show seams between rows and columns. The cell
739
+ // still breaks the text run (cp zeroes) and paints below.
740
+ if (cp != 0 and !skip and box.isBoxDrawing(cp)) {
741
+ box_cp = cp;
742
+ cp = 0;
743
+ }
744
+ // The current cell's full byte need: the run breaks
745
+ // BEFORE a cell that would not fit the remaining
746
+ // scratch, so the cell restarts in a fresh buffer and a
747
+ // large grapheme landing near the buffer's end keeps
748
+ // all its marks instead of being cut.
749
+ if (cp != 0 and !skip) {
750
+ cell_bytes = cell.cluster.len;
751
+ const primary_len = std.unicode.utf8CodepointSequenceLength(cp) catch 1;
752
+ multi_cluster = cell.cluster.len > primary_len;
753
+ }
754
+ }
755
+ const breaks = x == row.cells.len or skip or cp == 0 or
756
+ !colorEql(fg, run_fg) or underline != run_underline or
757
+ multi_cluster or break_after_cluster or
758
+ text_len + cell_bytes > text_scratch.len;
759
+ if (breaks and run_len > 0 and text_len > 0) {
760
+ // The row-wise text ceiling reserves enough that this
761
+ // append fits; the catch is a defensive floor that stops
762
+ // the run cleanly if it ever did not (never a torn cell).
763
+ const run_text = builder.allocTextBytes(text_scratch[0..text_len]) catch {
764
+ row_torn = true;
765
+ break;
766
+ };
767
+ try builder.drawText(.{
768
+ .id = ids.at(row_id + 0x8000 + run_x),
769
+ .font_id = tokens.typography.mono_font_id,
770
+ .size = metrics.font_size,
771
+ // `origin` is the BASELINE, not the glyph top: the
772
+ // canvas boxes a run as one em of ascent above the
773
+ // origin and a quarter below, so centering that
774
+ // 1.25em box in the cell puts the baseline at
775
+ // row top + (cell - 1.25*size)/2 + size. Anchoring
776
+ // the top here instead paints every row one line
777
+ // high — and the clip swallows row zero whole.
778
+ .origin = geometry.PointF.init(
779
+ origin_x + @as(f32, @floatFromInt(run_x)) * cell_w,
780
+ row_y + (cell_h - metrics.font_size * 1.25) * 0.5 + metrics.font_size,
781
+ ),
782
+ .color = run_fg,
783
+ .text = run_text,
784
+ // The run carries the measurement seam for one
785
+ // reason: a command's raster extent comes from its
786
+ // own declared bounds, and without a provider those
787
+ // bounds are the estimator's 0.6 em mono pitch. A
788
+ // host face with a wider pitch (macOS resolves the
789
+ // mono id to the system monospaced face at 0.618 em
790
+ // when Geist Mono is absent) then inks past the
791
+ // declared extent, and a full-width row loses its
792
+ // last cell — measured: column 50 of 50 sheared to a
793
+ // two-pixel sliver. Measuring the run the way the
794
+ // host inks it makes the bounds cover the ink for
795
+ // whatever face resolves. Line breaking stays off
796
+ // (`wrap = .none`, no `max_width`), so the run still
797
+ // paints as one line at this exact baseline.
798
+ .text_layout = .{
799
+ .wrap = .none,
800
+ .line_height = cell_h,
801
+ .measure = tokens.text_measure,
802
+ },
803
+ });
804
+ if (run_underline) {
805
+ try builder.fillRect(.{
806
+ .id = ids.at(row_id + 0xc000 + run_x),
807
+ .rect = geometry.RectF.init(
808
+ origin_x + @as(f32, @floatFromInt(run_x)) * cell_w,
809
+ row_y + cell_h - 2,
810
+ @as(f32, @floatFromInt(run_len)) * cell_w,
811
+ 1,
812
+ ),
813
+ .fill = .{ .color = run_fg },
814
+ });
815
+ }
816
+ text_len = 0;
817
+ run_len = 0;
818
+ }
819
+ if (x >= row.cells.len or skip) continue;
820
+ if (box_cp != 0) {
821
+ // Merge a run of the same seamless piece (a border's
822
+ // long `─`) into ONE command: fewer commands and one
823
+ // unbroken bar instead of per-cell segments. Cells merge
824
+ // only when they match on EVERY channel the span paints —
825
+ // code point, foreground, AND underline — so a run where
826
+ // underline toggles mid-way breaks into separate spans
827
+ // and each keeps its own decoration.
828
+ var span: usize = 1;
829
+ if (box.mergesHorizontally(box_cp)) {
830
+ while (x + span < row.cells.len) : (span += 1) {
831
+ const next = row.cells[x + span];
832
+ if (next.cp != box_cp or !colorEql(next.fg, fg) or next.underline != underline) break;
833
+ }
834
+ }
835
+ const rect = geometry.RectF.init(
836
+ origin_x + @as(f32, @floatFromInt(x)) * cell_w,
837
+ row_y,
838
+ @as(f32, @floatFromInt(span)) * cell_w,
839
+ cell_h,
840
+ );
841
+ // Eight-command stride per column: a pure-double joint
842
+ // emits up to eight commands (two bars per side), so a
843
+ // four-wide stride would collide the ids of adjacent
844
+ // double cells and fail the retained diff with
845
+ // DuplicateObjectId.
846
+ box.paint(builder, ids.at(row_id + 0x6000 + @as(u64, @intCast(x)) * commands_per_cell), rect, box_cp, fg, box_thickness) catch {
847
+ row_torn = true;
848
+ break;
849
+ };
850
+ // A box/block cell can still carry SGR underline: the
851
+ // geometry replaces the glyph, not its decoration, so an
852
+ // underlined `─` or `█` keeps its underline like any other
853
+ // styled cell (0xd000 id range, clear of the box geometry
854
+ // and text ranges).
855
+ if (underline) {
856
+ builder.fillRect(.{
857
+ .id = ids.at(row_id + 0xd000 + @as(u64, @intCast(x))),
858
+ .rect = geometry.RectF.init(rect.x, row_y + cell_h - 2, rect.width, 1),
859
+ .fill = .{ .color = fg },
860
+ }) catch {
861
+ row_torn = true;
862
+ break;
863
+ };
864
+ }
865
+ x += span - 1;
866
+ continue;
867
+ }
868
+ if (cp == 0) continue;
869
+ if (run_len == 0) {
870
+ run_x = x;
871
+ run_fg = fg;
872
+ run_underline = underline;
873
+ }
874
+ const cell = row.cells[x];
875
+ // Stage the whole cluster; the break above guaranteed it
876
+ // fits, and the min is a defensive floor that can only cut
877
+ // where the preflight already stopped the row.
878
+ const take = @min(cell.cluster.len, text_scratch.len - text_len);
879
+ @memcpy(text_scratch[text_len..][0..take], cell.cluster[0..take]);
880
+ text_len += take;
881
+ run_len += if (cell.wide == .wide) 2 else 1;
882
+ break_after_cluster = multi_cluster;
883
+ }
884
+ // A torn row is not painted content: roll the builder back to the
885
+ // row's start so no partial row reaches the glass, then stop (the
886
+ // suppressed cursor/caret rely on `painted_rows` not advancing).
887
+ if (row_torn) {
888
+ builder.len = row_start_len;
889
+ builder.path_element_len = row_start_paths;
890
+ builder.text_byte_len = row_start_text;
891
+ break;
892
+ }
893
+ // Advance the view-global running totals by exactly what this row
894
+ // added (the builder-owned deltas): the terminal's own text/path
895
+ // emissions all flow through `allocTextBytes`/`allocPathElements`,
896
+ // so the counter deltas are its contribution to the per-view
897
+ // budgets the next row's preflight checks.
898
+ text_total += builder.text_byte_len - row_start_text;
899
+ path_total += builder.path_element_len - row_start_paths;
900
+ painted_rows = row_index + 1;
901
+ }
902
+
903
+ // The cursor, over the ink: solid only while this live terminal owns
904
+ // keyboard focus. Blur leaves the conventional hollow terminal
905
+ // cursor; an ended session keeps that outline at the dimmer stopped
906
+ // alpha. Suppressed if its row was never painted (dropped for budget).
907
+ if (grid.cursor) |cursor| if (cursor.y < painted_rows) {
908
+ const cursor_x = origin_x + @as(f32, @floatFromInt(cursor.x)) * cell_w;
909
+ const cursor_y = origin_y + @as(f32, @floatFromInt(cursor.y)) * cell_h;
910
+ const cursor_color = canvas.Color.rgba(
911
+ grid.cursor_color.r,
912
+ grid.cursor_color.g,
913
+ grid.cursor_color.b,
914
+ if (grid.running) 0.45 else 0.22,
915
+ );
916
+ const rect = switch (cursor.shape) {
917
+ .bar => geometry.RectF.init(cursor_x, cursor_y, 2, cell_h),
918
+ .underline => geometry.RectF.init(cursor_x, cursor_y + cell_h - 2, cell_w, 2),
919
+ .block => geometry.RectF.init(cursor_x, cursor_y, cell_w, cell_h),
920
+ };
921
+ if (options.focused and grid.running) {
922
+ try builder.fillRect(.{
923
+ .id = ids.at(0x61_0002),
924
+ .rect = rect,
925
+ .fill = .{ .color = cursor_color },
926
+ });
927
+ } else {
928
+ try builder.strokeRect(.{
929
+ .id = ids.at(0x61_0002),
930
+ .rect = rect,
931
+ .stroke = .{ .fill = .{ .color = cursor_color }, .width = 1 },
932
+ });
933
+ }
934
+ };
935
+
936
+ // Selection head outline while selecting (the keyboard caret).
937
+ // Suppressed on a row that was never painted, like the cursor.
938
+ if (grid.select_head) |head| if (head.y < painted_rows) {
939
+ const head_x = origin_x + @as(f32, @floatFromInt(head.x)) * cell_w;
940
+ const head_y = origin_y + @as(f32, @floatFromInt(head.y)) * cell_h;
941
+ try builder.strokeRect(.{
942
+ .id = ids.at(0x61_0003),
943
+ .rect = geometry.RectF.init(head_x, head_y, cell_w, cell_h),
944
+ .stroke = .{ .fill = .{ .color = tokens.colors.focus_ring }, .width = 1 },
945
+ });
946
+ };
947
+
948
+ // Scrollback indicator: a right-edge thumb while the viewport is in
949
+ // history, sized by the visible fraction.
950
+ const bar = grid.scrollbar;
951
+ if (bar.total > bar.len) {
952
+ const total: f32 = @floatFromInt(bar.total);
953
+ const offset: f32 = @floatFromInt(bar.offset);
954
+ const visible: f32 = @floatFromInt(bar.len);
955
+ const at_bottom = bar.offset + bar.len >= bar.total;
956
+ if (!at_bottom) {
957
+ const track_h = options.frame.height;
958
+ const thumb_h = @max(24, track_h * (visible / total));
959
+ const thumb_y = options.frame.y + (track_h - thumb_h) * (offset / @max(1, total - visible));
960
+ try builder.fillRect(.{
961
+ .id = ids.at(0x61_0004),
962
+ .rect = geometry.RectF.init(
963
+ options.frame.x + options.frame.width - 5,
964
+ thumb_y,
965
+ 3,
966
+ thumb_h,
967
+ ),
968
+ .fill = .{ .color = canvas.Color.rgba(
969
+ tokens.colors.text_muted.r,
970
+ tokens.colors.text_muted.g,
971
+ tokens.colors.text_muted.b,
972
+ 0.6,
973
+ ) },
974
+ });
975
+ }
976
+ }
977
+ try builder.popClip();
978
+ }