@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,1569 @@
1
+ //! The framework-owned terminal sessions behind `<terminal pty={key}>`.
2
+ //!
3
+ //! The element contract (see `canvas.terminal_grid`): the app owns a pty
4
+ //! effect key (`fx.ptySpawn` named it) and binds it to a `<terminal>`;
5
+ //! the RUNTIME owns the emulator behind that key. This module is that
6
+ //! ownership — a per-app store of libghostty-vt sessions keyed by pty
7
+ //! key, publishing each session's viewport as a resolved
8
+ //! `canvas.TerminalGrid` snapshot for the widget painter, and carrying
9
+ //! the input model the example tier hand-wires:
10
+ //!
11
+ //! - Output feeds arrive through the effects engine's pty tap (the same
12
+ //! delivery instant the app's Msg is built, live and replay alike), so
13
+ //! the emulator state derives entirely from journaled inputs and a
14
+ //! recorded session replays byte-identical.
15
+ //! - Emulator query answers (DSR, DA1, XTVERSION) and focused keyboard
16
+ //! input travel back through the JOURNALED pty write path via the
17
+ //! gateway the app loop installs — admission verdicts are executor
18
+ //! truth, so replay takes the identical retain/drop path.
19
+ //! - The app loop derives cols/rows from the element's laid-out frame
20
+ //! (`canvas.terminalCellMetrics` + `canvas.clampTerminalGrid`, the
21
+ //! painter's own sizing seam) and reconciles them here; the session
22
+ //! resizes the emulator and pushes `ptyResize` so the child sees
23
+ //! SIGWINCH.
24
+ //! - Scrollback follows the scroll `value` source-wins rule: the bound
25
+ //! `scrollback` applies when the DECLARED value changes between
26
+ //! builds; the runtime-owned position stands otherwise, and every
27
+ //! applied view-state change reports back through `on-terminal` as a
28
+ //! `canvas.TerminalState`.
29
+ //!
30
+ //! The emulator dependency is comptime-gated through the `terminal_vt`
31
+ //! seam (see `terminal_vt_stub.zig`): with the stub wired the store
32
+ //! compiles to inert no-ops and `<terminal>` renders the honest empty
33
+ //! surface — scaffolded and consumer builds never traverse ghostty's
34
+ //! dependency graph.
35
+
36
+ const std = @import("std");
37
+ const builtin = @import("builtin");
38
+ const canvas = @import("canvas");
39
+ const effects = @import("effects.zig");
40
+ const term_vt = @import("terminal_vt");
41
+
42
+ pub const enabled = term_vt.enabled;
43
+
44
+ /// One session per pty slot: the effects engine's own table bound.
45
+ pub const max_sessions: usize = effects.max_effect_ptys;
46
+
47
+ /// The journaled pty verbs the store drives, type-erased so this module
48
+ /// never names the Msg-generic engine: the app loop wraps its engine.
49
+ /// `write` is `Effects.ptyWrite` (all-or-nothing, verdict-journaling);
50
+ /// `resize` is `Effects.ptyResize`.
51
+ pub const PtyGateway = struct {
52
+ context: *anyopaque,
53
+ write: *const fn (context: *anyopaque, key: u64, bytes: []const u8) bool,
54
+ resize: *const fn (context: *anyopaque, key: u64, cols: u16, rows: u16) void,
55
+ };
56
+
57
+ /// One pointer event already translated into the terminal's padded
58
+ /// content box. Coordinates remain unclamped so a captured drag beyond
59
+ /// an edge extends to that edge; the session maps them onto its live
60
+ /// emulator grid using the same cell metrics the snapshot painter uses.
61
+ pub const PointerSelectionEvent = struct {
62
+ phase: canvas.WidgetPointerPhase,
63
+ x: f32,
64
+ y: f32,
65
+ width: f32,
66
+ height: f32,
67
+ click_count: u8 = 1,
68
+ };
69
+
70
+ pub const PointerSelectionResult = struct {
71
+ changed: bool = false,
72
+ selection_active: bool = false,
73
+ };
74
+
75
+ pub const TerminalSessions = if (enabled) EnabledStore else DisabledStore;
76
+
77
+ /// The stub-build store: every entry point compiles against the same
78
+ /// signatures and answers "no session" — `<terminal>` stays the honest
79
+ /// empty surface and the app loop's call sites stay unconditional.
80
+ const DisabledStore = struct {
81
+ pub fn init(backing: std.mem.Allocator) DisabledStore {
82
+ _ = backing;
83
+ return .{};
84
+ }
85
+ pub fn deinit(self: *DisabledStore) void {
86
+ _ = self;
87
+ }
88
+ pub fn setGateway(self: *DisabledStore, gateway: PtyGateway) void {
89
+ _ = self;
90
+ _ = gateway;
91
+ }
92
+ pub fn beginBuild(self: *DisabledStore, tokens: canvas.DesignTokens) void {
93
+ _ = self;
94
+ _ = tokens;
95
+ }
96
+ pub fn lookup(self: *DisabledStore) ?canvas.TerminalGridLookup {
97
+ _ = self;
98
+ return null;
99
+ }
100
+ pub fn notePtyEvent(self: *DisabledStore, event: *const effects.EffectPtyEvent) void {
101
+ _ = self;
102
+ _ = event;
103
+ }
104
+ pub fn hasSession(self: *const DisabledStore, pty: u64) bool {
105
+ _ = self;
106
+ _ = pty;
107
+ return false;
108
+ }
109
+ pub fn keyEvent(self: *DisabledStore, pty: u64, keyboard: canvas.WidgetKeyboardEvent) bool {
110
+ _ = self;
111
+ _ = pty;
112
+ _ = keyboard;
113
+ return false;
114
+ }
115
+ pub fn textInput(self: *DisabledStore, pty: u64, text: []const u8) bool {
116
+ _ = self;
117
+ _ = pty;
118
+ _ = text;
119
+ return false;
120
+ }
121
+ pub fn pasteInput(self: *DisabledStore, pty: u64, text: []const u8) bool {
122
+ _ = self;
123
+ _ = pty;
124
+ _ = text;
125
+ return false;
126
+ }
127
+ pub fn wheel(self: *DisabledStore, pty: u64, delta_y: f32) bool {
128
+ _ = self;
129
+ _ = pty;
130
+ _ = delta_y;
131
+ return false;
132
+ }
133
+ pub fn pointerSelection(self: *DisabledStore, pty: u64, event: PointerSelectionEvent) PointerSelectionResult {
134
+ _ = self;
135
+ _ = pty;
136
+ _ = event;
137
+ return .{};
138
+ }
139
+ pub fn reconcile(self: *DisabledStore, pty: u64, bound_scrollback: u32, cols: u16, rows: u16) ?canvas.TerminalState {
140
+ _ = self;
141
+ _ = pty;
142
+ _ = bound_scrollback;
143
+ _ = cols;
144
+ _ = rows;
145
+ return null;
146
+ }
147
+ pub fn currentState(self: *DisabledStore, pty: u64) ?canvas.TerminalState {
148
+ _ = self;
149
+ _ = pty;
150
+ return null;
151
+ }
152
+ pub fn refreshDirty(self: *DisabledStore) bool {
153
+ _ = self;
154
+ return false;
155
+ }
156
+ pub fn flushPending(self: *DisabledStore) bool {
157
+ _ = self;
158
+ return false;
159
+ }
160
+ };
161
+
162
+ const vt = if (enabled) term_vt.vt else struct {};
163
+
164
+ const EnabledStore = struct {
165
+ allocator: std.mem.Allocator,
166
+ /// The `std.Io` libghostty-vt's Terminal wants at init. Heap-owned
167
+ /// for a stable address; built on first session create so apps with
168
+ /// no `<terminal>` pay nothing.
169
+ threaded: ?*std.Io.Threaded = null,
170
+ entries: [max_sessions]Entry = @splat(.{}),
171
+ gateway: ?PtyGateway = null,
172
+ /// The tokens the CURRENT build resolves snapshots with, stamped by
173
+ /// `beginBuild` (the palette's theme mapping needs them). Valid for
174
+ /// the duration of one build — exactly the window `resolve` runs in.
175
+ tokens: canvas.DesignTokens = .{},
176
+
177
+ const Entry = struct {
178
+ key: u64 = 0,
179
+ session: ?*Session = null,
180
+ };
181
+
182
+ pub fn init(backing: std.mem.Allocator) EnabledStore {
183
+ return .{ .allocator = backing };
184
+ }
185
+
186
+ pub fn deinit(self: *EnabledStore) void {
187
+ for (&self.entries) |*entry| {
188
+ if (entry.session) |session| session.destroy();
189
+ entry.* = .{};
190
+ }
191
+ if (self.threaded) |threaded| {
192
+ threaded.deinit();
193
+ self.allocator.destroy(threaded);
194
+ self.threaded = null;
195
+ }
196
+ }
197
+
198
+ pub fn setGateway(self: *EnabledStore, gateway: PtyGateway) void {
199
+ self.gateway = gateway;
200
+ }
201
+
202
+ pub fn beginBuild(self: *EnabledStore, tokens: canvas.DesignTokens) void {
203
+ self.tokens = tokens;
204
+ }
205
+
206
+ /// The builder seam (`Ui.terminal_lookup`): finalize resolves each
207
+ /// bound pty key through this to the session's published snapshot,
208
+ /// creating the session on first sight — binding the key IS the
209
+ /// request for a framework-owned emulator behind it.
210
+ pub fn lookup(self: *EnabledStore) ?canvas.TerminalGridLookup {
211
+ return .{ .context = @ptrCast(self), .resolve = resolveOpaque };
212
+ }
213
+
214
+ fn resolveOpaque(context: *anyopaque, pty: u64) ?*const canvas.TerminalGrid {
215
+ const self: *EnabledStore = @ptrCast(@alignCast(context));
216
+ const session = self.ensureSession(pty) orelse return null;
217
+ if (session.snapshot_dirty) {
218
+ session.rebuildSnapshot(self.tokens) catch return &session.grid;
219
+ }
220
+ return &session.grid;
221
+ }
222
+
223
+ fn io(self: *EnabledStore) ?std.Io {
224
+ if (self.threaded == null) {
225
+ const threaded = self.allocator.create(std.Io.Threaded) catch return null;
226
+ threaded.* = std.Io.Threaded.init(self.allocator, .{});
227
+ self.threaded = threaded;
228
+ }
229
+ return self.threaded.?.io();
230
+ }
231
+
232
+ fn find(self: *EnabledStore, pty: u64) ?*Session {
233
+ if (pty == 0) return null;
234
+ for (&self.entries) |*entry| {
235
+ if (entry.key == pty) return entry.session;
236
+ }
237
+ return null;
238
+ }
239
+
240
+ fn ensureSession(self: *EnabledStore, pty: u64) ?*Session {
241
+ if (pty == 0) return null;
242
+ if (self.find(pty)) |session| return session;
243
+ for (&self.entries) |*entry| {
244
+ if (entry.session != null) continue;
245
+ const session_io = self.io() orelse return null;
246
+ const session = Session.create(self.allocator, session_io, 80, 24) catch return null;
247
+ entry.* = .{ .key = pty, .session = session };
248
+ return session;
249
+ }
250
+ return null;
251
+ }
252
+
253
+ pub fn hasSession(self: *const EnabledStore, pty: u64) bool {
254
+ if (pty == 0) return false;
255
+ for (&self.entries) |*entry| {
256
+ if (entry.key == pty and entry.session != null) return true;
257
+ }
258
+ return false;
259
+ }
260
+
261
+ /// The effects engine's pty tap: every delivered pty event — live
262
+ /// drain and replay feed alike — passes through here at the same
263
+ /// instant the app's Msg is built, so the emulator's inputs are
264
+ /// exactly the journaled stream.
265
+ pub fn notePtyEvent(self: *EnabledStore, event: *const effects.EffectPtyEvent) void {
266
+ const session = self.find(event.key) orelse return;
267
+ switch (event.kind) {
268
+ .output => {
269
+ // Output for a session that already ENDED is the first
270
+ // batch of a NEW spawn reusing the key (the key freed at
271
+ // exit delivery): hard-reset the emulator first so the
272
+ // new shell starts from a clean terminal — no leftover
273
+ // modes, scrollback, palette overrides, or a partial
274
+ // escape sequence mid-parse from its predecessor.
275
+ if (session.ended) session.resetForRespawn();
276
+ session.feedOutput(self.gateway, event.key, event.bytes);
277
+ session.snapshot_dirty = true;
278
+ },
279
+ .exit => {
280
+ session.ended = true;
281
+ session.grid.running = false;
282
+ // The child is gone: queued bytes can never land — drop
283
+ // them counted, and clear retained emulator replies (the
284
+ // same outbound loss), or the frame flush would retry
285
+ // them against the dead key until a respawn.
286
+ session.outbound_dropped += session.outbound_len;
287
+ session.outbound_dropped += session.response_len;
288
+ session.outbound_head = 0;
289
+ session.outbound_len = 0;
290
+ session.clearResponses();
291
+ session.snapshot_dirty = true;
292
+ },
293
+ // Write-admission verdicts are journal-only replay machinery;
294
+ // the engine never delivers one as an event.
295
+ .write => {},
296
+ }
297
+ }
298
+
299
+ /// Focused-terminal key input: specials and chords encode through
300
+ /// the emulator (application cursor-key mode, the kitty protocol,
301
+ /// and modifier encodings all honored); plain printable presses
302
+ /// arrive through the committed-text channel and are consumed here
303
+ /// silently — the editable-text convention, so an app-level key
304
+ /// fallback can never fire while the user is typing. Releases feed
305
+ /// the encoder too (kitty event reporting; silent in legacy modes).
306
+ /// Returns whether the terminal consumed the key.
307
+ pub fn keyEvent(self: *EnabledStore, pty: u64, keyboard: canvas.WidgetKeyboardEvent) bool {
308
+ const session = self.find(pty) orelse return false;
309
+ if (!session.acceptsInput()) return false;
310
+ const action: KeyAction = if (keyboard.phase == .key_up) .release else .press;
311
+ if (keyboard.phase != .key_up and keyboard.phase != .key_down) return false;
312
+ session.clearSelectionForInput();
313
+ session.encodeKeyEvent(self.gateway, pty, keyboard, action);
314
+ return true;
315
+ }
316
+
317
+ /// Focused-terminal committed text (IME results included): the
318
+ /// typing channel. Returns whether the session took it.
319
+ pub fn textInput(self: *EnabledStore, pty: u64, text: []const u8) bool {
320
+ const session = self.find(pty) orelse return false;
321
+ if (!session.acceptsInput()) return false;
322
+ if (text.len == 0) return true;
323
+ session.clearSelectionForInput();
324
+ // Typing snaps the viewport to the live screen (every terminal's
325
+ // rule); the cells only change when the echo comes back, so the
326
+ // snapshot re-resolves only when the viewport actually moved.
327
+ const before = session.scrollbarState().offset;
328
+ session.scrollToBottom();
329
+ if (session.scrollbarState().offset != before) session.snapshot_dirty = true;
330
+ session.sendCommittedText(self.gateway, pty, text);
331
+ return true;
332
+ }
333
+
334
+ /// Clipboard paste is terminal input with distinct protocol
335
+ /// semantics, never just a multi-byte typing commit. Encode against
336
+ /// the emulator's live bracketed-paste mode, normalize unbracketed
337
+ /// newlines like xterm, and strip control bytes that could inject
338
+ /// terminal commands. Returns whether a live session consumed the
339
+ /// paste; an ended or unknown session declines without writing.
340
+ pub fn pasteInput(self: *EnabledStore, pty: u64, text: []const u8) bool {
341
+ const session = self.find(pty) orelse return false;
342
+ if (!session.acceptsInput()) return false;
343
+ if (text.len == 0) return true;
344
+ session.clearSelectionForInput();
345
+ const before = session.scrollbarState().offset;
346
+ session.scrollToBottom();
347
+ if (session.scrollbarState().offset != before) session.snapshot_dirty = true;
348
+
349
+ const options: vt.input.PasteOptions = .fromTerminal(&session.term);
350
+ var mutable: ?[]u8 = null;
351
+ const encoded = vt.input.encodePaste(text, options) catch |err| switch (err) {
352
+ error.MutableRequired => encoded: {
353
+ const copy = session.gpa.dupe(u8, text) catch {
354
+ session.outbound_dropped += text.len;
355
+ return true;
356
+ };
357
+ mutable = copy;
358
+ break :encoded vt.input.encodePaste(copy, options);
359
+ },
360
+ };
361
+ defer if (mutable) |copy| session.gpa.free(copy);
362
+ session.enqueueTransientSlices(self.gateway, pty, &encoded);
363
+ return true;
364
+ }
365
+
366
+ /// Wheel scrollback over a bound terminal: natural direction, like
367
+ /// every terminal — swiping the content down reveals history.
368
+ /// Deltas accumulate into whole rows against the session's current
369
+ /// cell height. Returns whether the viewport moved.
370
+ pub fn wheel(self: *EnabledStore, pty: u64, delta_y: f32) bool {
371
+ const session = self.find(pty) orelse return false;
372
+ session.wheel_accum += delta_y;
373
+ const cell_h = @max(1, session.cell_height);
374
+ const rows = @trunc(session.wheel_accum / cell_h);
375
+ if (rows == 0) return false;
376
+ session.wheel_accum -= rows * cell_h;
377
+ const before = session.scrollbarState().offset;
378
+ session.scrollLines(-@as(isize, @intFromFloat(rows)));
379
+ if (session.scrollbarState().offset == before) return false;
380
+ session.snapshot_dirty = true;
381
+ // The runtime moved the position: remember it as the value the
382
+ // app will echo back, so the echo never reads as a model-driven
383
+ // scroll (the source-wins compare in `reconcile`).
384
+ session.last_bound_scrollback = session.currentState().scrollback;
385
+ return true;
386
+ }
387
+
388
+ /// Primary-pointer terminal selection. The emulator owns the
389
+ /// tracked pins and selection serialization; the canvas runtime
390
+ /// supplies only the gesture and the content-box geometry.
391
+ pub fn pointerSelection(self: *EnabledStore, pty: u64, event: PointerSelectionEvent) PointerSelectionResult {
392
+ const session = self.find(pty) orelse return .{};
393
+ const result = session.pointerSelection(event);
394
+ if (result.changed) session.snapshot_dirty = true;
395
+ return result;
396
+ }
397
+
398
+ /// The per-build view-state reconcile the app loop runs against the
399
+ /// element's laid-out extent: applies a CHANGED declared scrollback
400
+ /// (source wins), resizes the emulator and pushes `ptyResize` when
401
+ /// the layout-derived grid moved, and returns the post-change
402
+ /// `canvas.TerminalState` when it differs from the last one
403
+ /// reported — the `on-terminal` dispatch trigger.
404
+ pub fn reconcile(self: *EnabledStore, pty: u64, bound_scrollback: u32, cols: u16, rows: u16) ?canvas.TerminalState {
405
+ const session = self.ensureSession(pty) orelse return null;
406
+ var changed = false;
407
+ if (bound_scrollback != session.last_bound_scrollback) {
408
+ // The DECLARED value moved between builds: the model scrolled
409
+ // programmatically (an unchanged echo compares equal and the
410
+ // runtime-owned position stands).
411
+ session.last_bound_scrollback = bound_scrollback;
412
+ if (session.applyScrollback(bound_scrollback)) changed = true;
413
+ }
414
+ if (cols != session.cols() or rows != session.rows()) {
415
+ if (session.resize(cols, rows)) {
416
+ changed = true;
417
+ if (self.gateway) |gateway| {
418
+ gateway.resize(gateway.context, pty, cols, rows);
419
+ }
420
+ // A resize is the child reading and redrawing: push any
421
+ // pending outbound the freed FIFO will now take.
422
+ session.flushOutbound(self.gateway, pty);
423
+ }
424
+ }
425
+ if (changed) {
426
+ session.snapshot_dirty = true;
427
+ // The snapshot must speak for the applied change before the
428
+ // caller re-emits the display list.
429
+ session.rebuildSnapshot(self.tokens) catch {};
430
+ }
431
+ const state = session.currentState();
432
+ if (session.last_reported == null or !stateEql(session.last_reported.?, state)) {
433
+ session.last_reported = state;
434
+ return state;
435
+ }
436
+ return null;
437
+ }
438
+
439
+ pub fn currentState(self: *EnabledStore, pty: u64) ?canvas.TerminalState {
440
+ const session = self.find(pty) orelse return null;
441
+ const state = session.currentState();
442
+ session.last_reported = state;
443
+ return state;
444
+ }
445
+
446
+ /// Rebuild any dirty published snapshots in place (with the last
447
+ /// build's tokens) so a display-list re-emission paints the current
448
+ /// emulator state. Returns whether anything was dirty — the
449
+ /// caller's re-emit trigger.
450
+ pub fn refreshDirty(self: *EnabledStore) bool {
451
+ var any = false;
452
+ for (&self.entries) |*entry| {
453
+ const session = entry.session orelse continue;
454
+ if (!session.snapshot_dirty) continue;
455
+ any = true;
456
+ session.rebuildSnapshot(self.tokens) catch {};
457
+ }
458
+ return any;
459
+ }
460
+
461
+ /// The frame-tick flush: a child that read without echoing freed
462
+ /// FIFO room no output event announces, so pending outbound (typed
463
+ /// keys a full ring retained, emulator replies) drains here. A
464
+ /// no-op when nothing is pending — no journal traffic. Returns
465
+ /// whether any bytes moved.
466
+ pub fn flushPending(self: *EnabledStore) bool {
467
+ var moved = false;
468
+ for (&self.entries) |*entry| {
469
+ const session = entry.session orelse continue;
470
+ if (session.ended) continue;
471
+ if (session.outbound_len == 0 and session.response_len == 0) continue;
472
+ const before = session.outbound_len + session.response_len;
473
+ session.moveResponsesToOutbound(self.gateway, entry.key);
474
+ session.flushOutbound(self.gateway, entry.key);
475
+ if (session.outbound_len + session.response_len != before) moved = true;
476
+ }
477
+ return moved;
478
+ }
479
+
480
+ fn stateEql(a: canvas.TerminalState, b: canvas.TerminalState) bool {
481
+ return a.scrollback == b.scrollback and a.history == b.history and
482
+ a.cols == b.cols and a.rows == b.rows;
483
+ }
484
+ };
485
+
486
+ const KeyAction = if (enabled) vt.input.KeyAction else enum { press, release };
487
+
488
+ /// The pending-outbound ring size, matched to the example tier: 4x the
489
+ /// pty's 64 KiB stdin FIFO, so only a paste or reply burst far larger
490
+ /// than this, into a child that never reads, reaches the counted drop
491
+ /// path.
492
+ const outbound_buffer_bytes: usize = 256 * 1024;
493
+
494
+ /// One live emulator session (enabled builds only). Heap-owned by the
495
+ /// store; everything inside derives from journaled inputs — fed pty
496
+ /// bytes, layout-derived resizes, and input events — so a replayed
497
+ /// session rebuilds byte-identical.
498
+ const Session = if (enabled) struct {
499
+ gpa: std.mem.Allocator,
500
+ term: vt.Terminal,
501
+ stream: vt.TerminalStream,
502
+ render: vt.RenderState,
503
+
504
+ /// Emulator answers to queries (DSR, DA1, XTVERSION, ...) produced
505
+ /// while feeding output, drained after every feed slice and written
506
+ /// back to the pty through the outbound ring. Grown to fit up to
507
+ /// the ring's own ceiling; a reply past it drops WHOLE and counted
508
+ /// (never cut, which would desync the child's parser).
509
+ response_buffer: []u8 = &.{},
510
+ response_len: usize = 0,
511
+ responses_dropped: u32 = 0,
512
+
513
+ /// Pending outbound bytes toward the child's stdin — typed keys,
514
+ /// IME commits, AND emulator query replies, one stream-ordered ring
515
+ /// drained as the pty's stdin FIFO accepts them (the example tier's
516
+ /// lossless-write design, verbatim).
517
+ outbound_buffer: []u8,
518
+ outbound_head: usize = 0,
519
+ outbound_len: usize = 0,
520
+ outbound_dropped: u64 = 0,
521
+
522
+ /// The published snapshot the widget painter borrows (stable
523
+ /// address: the painter's borrowed-pointer lifetime contract).
524
+ grid: canvas.TerminalGrid,
525
+ rows_buf: [canvas.max_terminal_rows]canvas.TerminalRow = @splat(.{}),
526
+ cells_buf: []canvas.TerminalCell = &.{},
527
+ cluster_buf: []u8 = &.{},
528
+ screen_text: []const u8 = &.{},
529
+ selection_text: ?[:0]const u8 = null,
530
+ snapshot_dirty: bool = true,
531
+
532
+ /// Ghostty's gesture owns a tracked press pin across output and
533
+ /// viewport movement, so a drag continues selecting the same text
534
+ /// even when the page list shifts underneath it.
535
+ selection_gesture: vt.SelectionGesture = .init,
536
+
537
+ /// Session lifecycle: exactly one exit ends every spawn; output on
538
+ /// an ended session is a new spawn reusing the key.
539
+ ended: bool = false,
540
+
541
+ /// View state for the source-wins scrollback echo and the
542
+ /// `on-terminal` change compare.
543
+ last_bound_scrollback: u32 = 0,
544
+ last_reported: ?canvas.TerminalState = null,
545
+ wheel_accum: f32 = 0,
546
+ /// Cell metrics at the last snapshot's tokens, shared by wheel
547
+ /// delta-to-rows and pointer-to-cell selection.
548
+ cell_width: f32 = 8,
549
+ cell_height: f32 = 18,
550
+ /// Physical macOS natural-editing keys whose press bypassed kitty
551
+ /// reporting as legacy shell bytes. Their matching release must be
552
+ /// swallowed by key identity even if Command/Option came up first.
553
+ macos_natural_keys_held: u8 = 0,
554
+
555
+ /// Query-answer buffer's initial size and growth ceiling — the
556
+ /// example tier's bounds verbatim (the ceiling matches the ring:
557
+ /// replies past it could never enqueue whole anyway).
558
+ const response_capacity: usize = 16 * 1024;
559
+ const response_capacity_max: usize = outbound_buffer_bytes;
560
+
561
+ /// Output feeds in sub-slices no larger than this, draining answers
562
+ /// after each, so a burst of pipelined query replies cannot outrun
563
+ /// the response buffer within one feed (a reply can be several
564
+ /// times its triggering query; see the example tier's derivation).
565
+ const feed_slice_bytes: usize = response_capacity / 16;
566
+
567
+ fn create(gpa: std.mem.Allocator, session_io: std.Io, initial_cols: u16, initial_rows: u16) !*Session {
568
+ const session = try gpa.create(Session);
569
+ errdefer gpa.destroy(session);
570
+ session.* = .{
571
+ .gpa = gpa,
572
+ .term = try vt.Terminal.init(session_io, gpa, .{
573
+ .cols = @intCast(@min(initial_cols, canvas.max_terminal_cols)),
574
+ .rows = @intCast(@min(initial_rows, canvas.max_terminal_rows)),
575
+ .max_scrollback = 1_000_000,
576
+ }),
577
+ .stream = undefined,
578
+ .render = .empty,
579
+ .outbound_buffer = &.{},
580
+ .grid = .{
581
+ .background = canvas.Color.rgba(0, 0, 0, 1),
582
+ .foreground = canvas.Color.rgba(1, 1, 1, 1),
583
+ .cursor_color = canvas.Color.rgba(1, 1, 1, 1),
584
+ .selection_color = canvas.Color.rgba(1, 1, 1, 1),
585
+ },
586
+ };
587
+ errdefer session.term.deinit(gpa);
588
+ session.response_buffer = try gpa.alloc(u8, response_capacity);
589
+ errdefer gpa.free(session.response_buffer);
590
+ session.outbound_buffer = try gpa.alloc(u8, outbound_buffer_bytes);
591
+ errdefer gpa.free(session.outbound_buffer);
592
+ session.stream = .initAlloc(gpa, .init(&session.term));
593
+ session.installStreamEffects();
594
+ return session;
595
+ }
596
+
597
+ /// Wire the stream handler's effect callbacks — only `write_pty`
598
+ /// (query answers routed back toward the pty); everything else
599
+ /// stays null (the emulator's read-only defaults).
600
+ fn installStreamEffects(session: *Session) void {
601
+ session.stream.handler.effects = .{
602
+ .bell = null,
603
+ .clipboard_write = null,
604
+ .color_scheme = null,
605
+ .device_attributes = null,
606
+ .enquiry = null,
607
+ .size = null,
608
+ .title_changed = null,
609
+ .pwd_changed = null,
610
+ .write_pty = writePtyResponse,
611
+ .xtversion = null,
612
+ };
613
+ }
614
+
615
+ fn destroy(session: *Session) void {
616
+ const gpa = session.gpa;
617
+ session.selection_gesture.deinit(&session.term);
618
+ session.render.deinit(gpa);
619
+ session.stream.deinit();
620
+ session.term.deinit(gpa);
621
+ gpa.free(session.response_buffer);
622
+ gpa.free(session.outbound_buffer);
623
+ if (session.cells_buf.len > 0) gpa.free(session.cells_buf);
624
+ if (session.cluster_buf.len > 0) gpa.free(session.cluster_buf);
625
+ if (session.screen_text.len > 0) gpa.free(session.screen_text);
626
+ if (session.selection_text) |text| gpa.free(text);
627
+ gpa.destroy(session);
628
+ }
629
+
630
+ fn acceptsInput(session: *const Session) bool {
631
+ return !session.ended;
632
+ }
633
+
634
+ /// Hard-reset for a spawn reusing the key: clears the screen,
635
+ /// scrollback, modes, palette overrides, and — by rebuilding the
636
+ /// stream — any partial escape sequence left mid-parse.
637
+ fn resetForRespawn(session: *Session) void {
638
+ // Drop the tracked gesture pin before the RIS recycles the
639
+ // screen/page list it belongs to.
640
+ session.selection_gesture.reset(&session.term);
641
+ session.term.fullReset();
642
+ // A RIS leaves the OSC color state alone: overrides from the
643
+ // ended shell must not tint the new one.
644
+ session.term.colors.foreground.override = null;
645
+ session.term.colors.background.override = null;
646
+ session.term.colors.cursor.override = null;
647
+ session.term.colors.palette.resetAll();
648
+ session.stream.deinit();
649
+ session.stream = .initAlloc(session.gpa, .init(&session.term));
650
+ session.installStreamEffects();
651
+ session.response_len = 0;
652
+ session.responses_dropped = 0;
653
+ session.outbound_head = 0;
654
+ session.outbound_len = 0;
655
+ session.outbound_dropped = 0;
656
+ session.wheel_accum = 0;
657
+ session.macos_natural_keys_held = 0;
658
+ session.ended = false;
659
+ session.grid.running = true;
660
+ session.snapshot_dirty = true;
661
+ }
662
+
663
+ // ------------------------------------------------------ output feed
664
+
665
+ /// Feed one pty output batch and return the emulator's query answers
666
+ /// toward the child, in bounded sub-slices so pipelined replies can
667
+ /// never outrun the response buffer within one feed. The VT stream
668
+ /// keeps parser state across slices, so splitting mid-escape-sequence
669
+ /// is invisible.
670
+ fn feedOutput(session: *Session, gateway: ?PtyGateway, key: u64, bytes: []const u8) void {
671
+ var offset: usize = 0;
672
+ while (offset < bytes.len) {
673
+ const end = @min(offset + feed_slice_bytes, bytes.len);
674
+ session.stream.nextSlice(bytes[offset..end]);
675
+ session.moveResponsesToOutbound(gateway, key);
676
+ offset = end;
677
+ }
678
+ if (bytes.len == 0) session.moveResponsesToOutbound(gateway, key);
679
+ // The child produced output, so it is reading: push pending
680
+ // outbound the freed FIFO will now take.
681
+ session.flushOutbound(gateway, key);
682
+ }
683
+
684
+ fn writePtyResponse(handler: *vt.TerminalStream.Handler, bytes: [:0]const u8) void {
685
+ const session: *Session = @alignCast(@fieldParentPtr("term", handler.terminal));
686
+ const needed = session.response_len + bytes.len;
687
+ if (needed > session.response_buffer.len) {
688
+ if (needed > response_capacity_max) {
689
+ session.responses_dropped +|= 1;
690
+ return;
691
+ }
692
+ var new_cap = @max(session.response_buffer.len * 2, response_capacity);
693
+ while (new_cap < needed) new_cap *= 2;
694
+ if (new_cap > response_capacity_max) new_cap = response_capacity_max;
695
+ if (session.gpa.realloc(session.response_buffer, new_cap)) |grown| {
696
+ session.response_buffer = grown;
697
+ } else |_| {
698
+ session.responses_dropped +|= 1;
699
+ return;
700
+ }
701
+ }
702
+ @memcpy(session.response_buffer[session.response_len..needed], bytes);
703
+ session.response_len += bytes.len;
704
+ }
705
+
706
+ fn clearResponses(session: *Session) void {
707
+ session.response_len = 0;
708
+ }
709
+
710
+ /// Move the emulator's query answers into the pending outbound ring
711
+ /// in stream order, then flush. Replies are DURABLE (the response
712
+ /// buffer holds them): a ring too full right now leaves them in
713
+ /// place for the next output, resize, or frame — never a discarded
714
+ /// answer the child may be blocked on, never a torn escape sequence.
715
+ fn moveResponsesToOutbound(session: *Session, gateway: ?PtyGateway, key: u64) void {
716
+ if (session.response_len > 0) {
717
+ if (!session.enqueueOutbound(gateway, key, session.response_buffer[0..session.response_len])) return;
718
+ }
719
+ session.clearResponses();
720
+ }
721
+
722
+ /// Append outbound bytes in stream order, then flush what the pty's
723
+ /// stdin FIFO will take. Admission is ALL-OR-NOTHING (a control
724
+ /// sequence cut mid-way would feed the child malformed input): true
725
+ /// means the payload is DISPOSED (queued whole, or impossible and
726
+ /// counted); false means it does not fit RIGHT NOW and the caller
727
+ /// retains it.
728
+ fn enqueueOutbound(session: *Session, gateway: ?PtyGateway, key: u64, bytes: []const u8) bool {
729
+ const cap = session.outbound_buffer.len;
730
+ if (bytes.len > cap) {
731
+ session.outbound_dropped += bytes.len;
732
+ return true;
733
+ }
734
+ if (bytes.len > cap - session.outbound_len) {
735
+ session.flushOutbound(gateway, key);
736
+ if (bytes.len > cap - session.outbound_len) return false;
737
+ }
738
+ for (bytes, 0..) |byte, i| {
739
+ session.outbound_buffer[(session.outbound_head + session.outbound_len + i) % cap] = byte;
740
+ }
741
+ session.outbound_len += bytes.len;
742
+ session.flushOutbound(gateway, key);
743
+ return true;
744
+ }
745
+
746
+ /// Enqueue a TRANSIENT payload (typed text, an encoded key): the
747
+ /// event's bytes do not outlive the dispatch, so a right-now refusal
748
+ /// counts as dropped instead of silent loss. Stdin order comes
749
+ /// first: a query reply retained behind a full ring is OLDER than
750
+ /// this keystroke and must reach the child before it.
751
+ fn enqueueTransient(session: *Session, gateway: ?PtyGateway, key: u64, bytes: []const u8) void {
752
+ session.moveResponsesToOutbound(gateway, key);
753
+ if (session.response_len > 0) {
754
+ session.outbound_dropped += bytes.len;
755
+ return;
756
+ }
757
+ if (!session.enqueueOutbound(gateway, key, bytes)) {
758
+ session.outbound_dropped += bytes.len;
759
+ }
760
+ }
761
+
762
+ /// Paste encoding is a vector (optional bracket, payload, optional
763
+ /// bracket) but admission is atomic: never enqueue an opening
764
+ /// bracket without its payload and closing bracket when a
765
+ /// back-pressured child has nearly filled the ring.
766
+ fn enqueueTransientSlices(session: *Session, gateway: ?PtyGateway, key: u64, slices: []const []const u8) void {
767
+ session.moveResponsesToOutbound(gateway, key);
768
+ var total: usize = 0;
769
+ for (slices) |bytes| total += bytes.len;
770
+ if (session.response_len > 0) {
771
+ session.outbound_dropped += total;
772
+ return;
773
+ }
774
+
775
+ const cap = session.outbound_buffer.len;
776
+ if (total > cap) {
777
+ session.outbound_dropped += total;
778
+ return;
779
+ }
780
+ if (total > cap - session.outbound_len) session.flushOutbound(gateway, key);
781
+ if (total > cap - session.outbound_len) {
782
+ session.outbound_dropped += total;
783
+ return;
784
+ }
785
+
786
+ var offset = session.outbound_len;
787
+ for (slices) |bytes| {
788
+ for (bytes) |byte| {
789
+ session.outbound_buffer[(session.outbound_head + offset) % cap] = byte;
790
+ offset += 1;
791
+ }
792
+ }
793
+ session.outbound_len += total;
794
+ session.flushOutbound(gateway, key);
795
+ }
796
+
797
+ /// Push as much pending outbound as the pty's stdin FIFO will
798
+ /// accept, in per-write-bound chunks through the JOURNALED write
799
+ /// path. A refused chunk stays in the ring for the next output,
800
+ /// resize, or frame — a non-reading child pauses the stream instead
801
+ /// of losing its tail.
802
+ fn flushOutbound(session: *Session, gateway: ?PtyGateway, key: u64) void {
803
+ const gw = gateway orelse return;
804
+ const cap = session.outbound_buffer.len;
805
+ while (session.outbound_len > 0) {
806
+ const run_to_end = cap - session.outbound_head;
807
+ const n = @min(
808
+ effects.max_effect_pty_write_bytes,
809
+ @min(session.outbound_len, run_to_end),
810
+ );
811
+ if (!gw.write(gw.context, key, session.outbound_buffer[session.outbound_head .. session.outbound_head + n])) break;
812
+ session.outbound_head = (session.outbound_head + n) % cap;
813
+ session.outbound_len -= n;
814
+ }
815
+ }
816
+
817
+ // -------------------------------------------------------- geometry
818
+
819
+ fn cols(session: *const Session) u16 {
820
+ return @intCast(session.term.cols);
821
+ }
822
+
823
+ fn rows(session: *const Session) u16 {
824
+ return @intCast(session.term.rows);
825
+ }
826
+
827
+ /// Resize the emulator grid (reflow included). Returns whether the
828
+ /// grid now matches the request; an allocation failure returns
829
+ /// false so the caller leaves the pty untouched and retries on the
830
+ /// next build — the emulator and the pty never disagree.
831
+ fn resize(session: *Session, new_cols: u16, new_rows: u16) bool {
832
+ const c: vt.size.CellCountInt = @intCast(std.math.clamp(@as(usize, new_cols), 2, canvas.max_terminal_cols));
833
+ const r: vt.size.CellCountInt = @intCast(std.math.clamp(@as(usize, new_rows), 2, canvas.max_terminal_rows));
834
+ if (c == session.term.cols and r == session.term.rows) return true;
835
+ session.term.resize(session.gpa, .{ .cols = c, .rows = r }) catch return false;
836
+ return true;
837
+ }
838
+
839
+ // ------------------------------------------------------- scrollback
840
+
841
+ fn scrollLines(session: *Session, delta: isize) void {
842
+ session.term.screens.active.pages.scroll(.{ .delta_row = delta });
843
+ }
844
+
845
+ fn scrollToBottom(session: *Session) void {
846
+ session.term.screens.active.pages.scroll(.{ .active = {} });
847
+ }
848
+
849
+ fn scrollbarState(session: *Session) vt.PageList.Scrollbar {
850
+ return session.term.screens.active.pages.scrollbar();
851
+ }
852
+
853
+ // ------------------------------------------------ pointer selection
854
+
855
+ /// Default terminal word boundaries, matching Ghostty's standard
856
+ /// selection gesture. Kept local because the pinned vt module
857
+ /// exports SelectionGesture but not its codepoint-policy module.
858
+ const word_boundaries = [_]u21{
859
+ 0, ' ', '\t', '\'', '"',
860
+ '│',
861
+ '`', '|', ':', ';', ',',
862
+ '(', ')', '[', ']', '{',
863
+ '}', '<', '>', '$',
864
+ };
865
+
866
+ fn pointerSelection(session: *Session, event: PointerSelectionEvent) PointerSelectionResult {
867
+ if (!std.math.isFinite(event.x) or !std.math.isFinite(event.y) or
868
+ !std.math.isFinite(event.width) or !std.math.isFinite(event.height) or
869
+ session.cell_width <= 0 or session.cell_height <= 0)
870
+ {
871
+ return .{};
872
+ }
873
+
874
+ const screen = session.term.screens.active;
875
+ switch (event.phase) {
876
+ .down => {
877
+ const pin = session.pointerPin(event) orelse return .{};
878
+ session.selection_gesture.reset(&session.term);
879
+ const behavior: vt.SelectionGesture.Behavior = if (event.click_count >= 3)
880
+ .line
881
+ else if (event.click_count == 2)
882
+ .word
883
+ else
884
+ .cell;
885
+ // The runtime already derives and journals click_count.
886
+ // Force all gesture slots to that behavior and omit a
887
+ // timestamp, avoiding a second, divergent click clock
888
+ // inside the emulator.
889
+ const behaviors = [3]vt.SelectionGesture.Behavior{ behavior, behavior, behavior };
890
+ const selected = session.selection_gesture.press(&session.term, .{
891
+ .time = null,
892
+ .pin = pin,
893
+ .xpos = event.x,
894
+ .ypos = event.y,
895
+ .max_distance = @max(1, session.cell_width),
896
+ .repeat_interval = 0,
897
+ .word_boundary_codepoints = &word_boundaries,
898
+ .behaviors = &behaviors,
899
+ }) catch {
900
+ screen.clearSelection();
901
+ return .{ .changed = true };
902
+ };
903
+ if (selected) |selection| {
904
+ screen.select(selection) catch screen.clearSelection();
905
+ } else {
906
+ // A plain press collapses the previous selection;
907
+ // crossing the drag threshold establishes the new
908
+ // range on the following move/up.
909
+ screen.clearSelection();
910
+ }
911
+ return .{
912
+ .changed = true,
913
+ .selection_active = screen.selection != null,
914
+ };
915
+ },
916
+ .move => {
917
+ const changed = session.applyPointerDrag(event);
918
+ return .{
919
+ .changed = changed,
920
+ .selection_active = screen.selection != null,
921
+ };
922
+ },
923
+ .up => {
924
+ const pin = session.pointerPin(event);
925
+ const changed = session.applyPointerDrag(event);
926
+ session.selection_gesture.release(&session.term, .{ .pin = pin });
927
+ return .{
928
+ .changed = changed,
929
+ .selection_active = screen.selection != null,
930
+ };
931
+ },
932
+ .cancel => {
933
+ session.selection_gesture.reset(&session.term);
934
+ return .{ .selection_active = screen.selection != null };
935
+ },
936
+ .hover, .wheel => return .{ .selection_active = screen.selection != null },
937
+ }
938
+ }
939
+
940
+ fn applyPointerDrag(session: *Session, event: PointerSelectionEvent) bool {
941
+ const pin = session.pointerPin(event) orelse return false;
942
+ const selection = session.selection_gesture.drag(&session.term, .{
943
+ .pin = pin,
944
+ .xpos = event.x,
945
+ .ypos = event.y,
946
+ .rectangle = false,
947
+ .word_boundary_codepoints = &word_boundaries,
948
+ .geometry = .{
949
+ .columns = session.cols(),
950
+ .cell_width = @intFromFloat(@max(1, @round(session.cell_width))),
951
+ .padding_left = 0,
952
+ .screen_height = @intFromFloat(@max(1, @round(event.height))),
953
+ },
954
+ }) orelse return false;
955
+ session.term.screens.active.select(selection) catch return false;
956
+ return true;
957
+ }
958
+
959
+ fn pointerPin(session: *Session, event: PointerSelectionEvent) ?vt.Pin {
960
+ const cols_count = session.cols();
961
+ const rows_count = session.rows();
962
+ if (cols_count == 0 or rows_count == 0) return null;
963
+ const max_x = @as(f32, @floatFromInt(cols_count - 1));
964
+ const max_y = @as(f32, @floatFromInt(rows_count - 1));
965
+ const cell_x = std.math.clamp(@floor(event.x / session.cell_width), 0, max_x);
966
+ const cell_y = std.math.clamp(@floor(event.y / session.cell_height), 0, max_y);
967
+ return session.term.screens.active.pages.pin(.{ .viewport = .{
968
+ .x = @intFromFloat(cell_x),
969
+ .y = @intFromFloat(cell_y),
970
+ } });
971
+ }
972
+
973
+ /// Any input sent to the child dismisses the pointer selection,
974
+ /// matching terminal convention. Cmd/Ctrl+C is intercepted before
975
+ /// `keyEvent` while a selection exists, so copy never reaches this
976
+ /// clearing path.
977
+ fn clearSelectionForInput(session: *Session) void {
978
+ session.selection_gesture.reset(&session.term);
979
+ if (session.term.screens.active.selection == null) return;
980
+ session.term.screens.active.clearSelection();
981
+ session.snapshot_dirty = true;
982
+ }
983
+
984
+ /// Scroll to an offset-from-bottom (the `TerminalState.scrollback`
985
+ /// shape). Returns whether the viewport moved.
986
+ fn applyScrollback(session: *Session, target: u32) bool {
987
+ const bar = session.scrollbarState();
988
+ const history: u32 = @intCast(bar.total -| bar.len);
989
+ const clamped = @min(target, history);
990
+ const current: u32 = @intCast((bar.total -| bar.len) -| bar.offset);
991
+ if (clamped == current) return false;
992
+ const delta: isize = @as(isize, @intCast(clamped)) - @as(isize, @intCast(current));
993
+ session.scrollLines(-delta);
994
+ return true;
995
+ }
996
+
997
+ fn currentState(session: *Session) canvas.TerminalState {
998
+ const bar = session.scrollbarState();
999
+ const history: u32 = @intCast(bar.total -| bar.len);
1000
+ return .{
1001
+ .scrollback = @intCast(history -| @as(u32, @intCast(bar.offset))),
1002
+ .history = history,
1003
+ .cols = session.cols(),
1004
+ .rows = session.rows(),
1005
+ };
1006
+ }
1007
+
1008
+ // --------------------------------------------------------- keyboard
1009
+
1010
+ /// Encode one key transition and push the bytes toward the child.
1011
+ /// macOS natural-text arrow gestures use the platform's conventional
1012
+ /// shell bindings; everything else follows the emulator's encoder
1013
+ /// (C0 chords, CSI-u exceptions, application cursor-key modes, kitty
1014
+ /// event reporting for releases).
1015
+ fn encodeKeyEvent(session: *Session, gateway: ?PtyGateway, pty_key: u64, event: canvas.WidgetKeyboardEvent, action: vt.input.KeyAction) void {
1016
+ const natural_key_mask = macosNaturalTextKeyMask(event.key);
1017
+ if (action == .release and natural_key_mask != 0 and
1018
+ (session.macos_natural_keys_held & natural_key_mask) != 0)
1019
+ {
1020
+ session.macos_natural_keys_held &= ~natural_key_mask;
1021
+ return;
1022
+ }
1023
+ // A fresh press supersedes any stale held bit (focus loss or a
1024
+ // host-generated press with no matching release). A natural
1025
+ // press below immediately re-arms it, including auto-repeat.
1026
+ if (action == .press and natural_key_mask != 0) {
1027
+ session.macos_natural_keys_held &= ~natural_key_mask;
1028
+ }
1029
+ if (macosNaturalTextSequence(event)) |sequence| {
1030
+ // Natural-text bindings consume the whole gesture. In
1031
+ // particular, a child using kitty event reporting must not
1032
+ // receive a release for a modified arrow whose press arrived
1033
+ // as legacy editing bytes.
1034
+ if (action == .release) return;
1035
+ session.macos_natural_keys_held |= natural_key_mask;
1036
+ const before = session.scrollbarState().offset;
1037
+ session.scrollToBottom();
1038
+ if (session.scrollbarState().offset != before) session.snapshot_dirty = true;
1039
+ session.enqueueTransient(gateway, pty_key, sequence);
1040
+ return;
1041
+ }
1042
+ const mods = event.modifiers;
1043
+ const key = mapKey(event) orelse blk: {
1044
+ // A release of a plain printable never maps (its PRESS came
1045
+ // through the text channel): synthesize the codepoint-keyed
1046
+ // event so kitty event reporting hears the release too.
1047
+ if (action != .release) return;
1048
+ break :blk mapPrintable(event.key) orelse return;
1049
+ };
1050
+ var buffer: [128]u8 = undefined;
1051
+ var writer: std.Io.Writer = .fixed(&buffer);
1052
+ const encode_options: vt.input.KeyEncodeOptions = .fromTerminal(&session.term);
1053
+ // The runtime folds the platform's PRIMARY modifier into
1054
+ // `super`. On macOS primary IS the GUI key, so the fold is
1055
+ // harmless — but on hosts whose primary is Ctrl, a bare Ctrl
1056
+ // chord arrives as ctrl+super and the encoder would skip its C0
1057
+ // byte (Ctrl+C must deliver ETX). Undo the alias: super counts
1058
+ // only when Ctrl is not the key raising it.
1059
+ const encoder_super = mods.super and !mods.control;
1060
+ _ = vt.input.encodeKey(&writer, .{
1061
+ .key = key.key,
1062
+ .action = action,
1063
+ .mods = .{
1064
+ .shift = mods.shift,
1065
+ .ctrl = mods.control,
1066
+ .alt = mods.alt,
1067
+ .super = encoder_super,
1068
+ },
1069
+ .utf8 = key.utf8,
1070
+ .unshifted_codepoint = key.unshifted,
1071
+ }, encode_options) catch return;
1072
+ if (writer.end == 0) return;
1073
+ const before = session.scrollbarState().offset;
1074
+ session.scrollToBottom();
1075
+ if (session.scrollbarState().offset != before) session.snapshot_dirty = true;
1076
+ session.enqueueTransient(gateway, pty_key, buffer[0..writer.end]);
1077
+ }
1078
+
1079
+ fn macosNaturalTextKeyMask(key: []const u8) u8 {
1080
+ if (comptime builtin.os.tag != .macos) return 0;
1081
+ if (std.ascii.eqlIgnoreCase(key, "arrowleft")) return 1 << 0;
1082
+ if (std.ascii.eqlIgnoreCase(key, "arrowright")) return 1 << 1;
1083
+ if (std.ascii.eqlIgnoreCase(key, "backspace")) return 1 << 2;
1084
+ return 0;
1085
+ }
1086
+
1087
+ /// Match macOS terminals' "natural text editing" bindings. These are
1088
+ /// exact bare-modifier gestures: shifted or combined chords continue
1089
+ /// through the key encoder so terminal applications can distinguish
1090
+ /// them. The raw bindings intentionally bypass negotiated kitty
1091
+ /// reporting, just as Ghostty's own default keybinds do.
1092
+ fn macosNaturalTextSequence(event: canvas.WidgetKeyboardEvent) ?[]const u8 {
1093
+ if (comptime builtin.os.tag != .macos) return null;
1094
+ const mods = event.modifiers;
1095
+ if (mods.shift or mods.control) return null;
1096
+ if (mods.alt and !mods.super) {
1097
+ if (std.ascii.eqlIgnoreCase(event.key, "arrowleft")) return "\x1bb";
1098
+ if (std.ascii.eqlIgnoreCase(event.key, "arrowright")) return "\x1bf";
1099
+ }
1100
+ if (mods.super and !mods.alt) {
1101
+ if (std.ascii.eqlIgnoreCase(event.key, "arrowleft")) return "\x01";
1102
+ if (std.ascii.eqlIgnoreCase(event.key, "arrowright")) return "\x05";
1103
+ // The physical macOS Delete key is normalized as Backspace.
1104
+ if (std.ascii.eqlIgnoreCase(event.key, "backspace")) return "\x15";
1105
+ }
1106
+ return null;
1107
+ }
1108
+
1109
+ /// Committed text reaches the child through the emulator's key
1110
+ /// encoder when it is a single scalar (byte-identical under legacy
1111
+ /// modes, the negotiated CSI-u form when a TUI enabled the kitty
1112
+ /// protocol's report-all mode); multi-scalar commits (IME words,
1113
+ /// paste) stay raw text, the protocol's rule for composed input.
1114
+ fn sendCommittedText(session: *Session, gateway: ?PtyGateway, pty_key: u64, text: []const u8) void {
1115
+ single: {
1116
+ const len = std.unicode.utf8ByteSequenceLength(text[0]) catch break :single;
1117
+ if (text.len != len) break :single;
1118
+ const cp = std.unicode.utf8Decode(text[0..len]) catch break :single;
1119
+ var buffer: [128]u8 = undefined;
1120
+ var writer: std.Io.Writer = .fixed(&buffer);
1121
+ _ = vt.input.encodeKey(&writer, .{
1122
+ .key = .unidentified,
1123
+ .action = .press,
1124
+ .utf8 = text,
1125
+ .unshifted_codepoint = cp,
1126
+ }, .fromTerminal(&session.term)) catch break :single;
1127
+ if (writer.end == 0) break :single;
1128
+ session.enqueueTransient(gateway, pty_key, buffer[0..writer.end]);
1129
+ return;
1130
+ }
1131
+ session.enqueueTransient(gateway, pty_key, text);
1132
+ }
1133
+
1134
+ const MappedKey = struct {
1135
+ key: vt.input.Key,
1136
+ utf8: []const u8 = "",
1137
+ unshifted: u21 = 0,
1138
+ };
1139
+
1140
+ /// A plain printable's codepoint-keyed event, for RELEASE encoding
1141
+ /// only: its press travels the committed-text channel, but kitty
1142
+ /// event reporting still owes the child the release. No text rides
1143
+ /// a release.
1144
+ fn mapPrintable(key: []const u8) ?MappedKey {
1145
+ if (key.len == 0) return null;
1146
+ const len = std.unicode.utf8ByteSequenceLength(key[0]) catch return null;
1147
+ if (key.len != len) return null;
1148
+ const cp = std.unicode.utf8Decode(key[0..len]) catch return null;
1149
+ return .{ .key = .unidentified, .unshifted = cp };
1150
+ }
1151
+
1152
+ /// Host key names -> emulator key codes: specials always;
1153
+ /// letters/digits/punctuation only under a chord modifier, where the
1154
+ /// text channel stays silent and the encoder must speak.
1155
+ fn mapKey(event: canvas.WidgetKeyboardEvent) ?MappedKey {
1156
+ const key = event.key;
1157
+ const specials = [_]struct { name: []const u8, key: vt.input.Key }{
1158
+ .{ .name = "enter", .key = .enter },
1159
+ .{ .name = "tab", .key = .tab },
1160
+ .{ .name = "escape", .key = .escape },
1161
+ .{ .name = "backspace", .key = .backspace },
1162
+ .{ .name = "delete", .key = .delete },
1163
+ .{ .name = "arrowup", .key = .arrow_up },
1164
+ .{ .name = "arrowdown", .key = .arrow_down },
1165
+ .{ .name = "arrowleft", .key = .arrow_left },
1166
+ .{ .name = "arrowright", .key = .arrow_right },
1167
+ .{ .name = "home", .key = .home },
1168
+ .{ .name = "end", .key = .end },
1169
+ .{ .name = "pageup", .key = .page_up },
1170
+ .{ .name = "pagedown", .key = .page_down },
1171
+ .{ .name = "insert", .key = .insert },
1172
+ .{ .name = "f1", .key = .f1 },
1173
+ .{ .name = "f2", .key = .f2 },
1174
+ .{ .name = "f3", .key = .f3 },
1175
+ .{ .name = "f4", .key = .f4 },
1176
+ .{ .name = "f5", .key = .f5 },
1177
+ .{ .name = "f6", .key = .f6 },
1178
+ .{ .name = "f7", .key = .f7 },
1179
+ .{ .name = "f8", .key = .f8 },
1180
+ .{ .name = "f9", .key = .f9 },
1181
+ .{ .name = "f10", .key = .f10 },
1182
+ .{ .name = "f11", .key = .f11 },
1183
+ .{ .name = "f12", .key = .f12 },
1184
+ };
1185
+ for (specials) |entry| {
1186
+ if (std.ascii.eqlIgnoreCase(key, entry.name)) return .{ .key = entry.key };
1187
+ }
1188
+ // Chorded character keys (ctrl+c, alt+f, ...): the text channel
1189
+ // is silent for these, so the encoder builds the control
1190
+ // sequence. Alt is a chord EXCEPT on macOS (Option composes
1191
+ // text); Ctrl+Alt together on Windows is AltGr and composes.
1192
+ const altgr = event.modifiers.control and event.modifiers.alt and builtin.os.tag == .windows;
1193
+ const alt_is_chord = event.modifiers.alt and builtin.os.tag != .macos;
1194
+ const chorded = (event.modifiers.control or event.modifiers.super or alt_is_chord) and !altgr;
1195
+ if (!chorded) return null;
1196
+ if (key.len == 1) {
1197
+ const ch = key[0];
1198
+ const utf8 = key[0..1];
1199
+ if (ch >= 'a' and ch <= 'z') {
1200
+ const base = @intFromEnum(vt.input.Key.key_a);
1201
+ return .{
1202
+ .key = @enumFromInt(base + @as(c_int, ch - 'a')),
1203
+ .utf8 = utf8,
1204
+ .unshifted = ch,
1205
+ };
1206
+ }
1207
+ if (ch >= '0' and ch <= '9') {
1208
+ const base = @intFromEnum(vt.input.Key.digit_0);
1209
+ return .{
1210
+ .key = @enumFromInt(base + @as(c_int, ch - '0')),
1211
+ .utf8 = utf8,
1212
+ .unshifted = ch,
1213
+ };
1214
+ }
1215
+ // Chorded punctuation carries real control meaning (Ctrl+[
1216
+ // is the ESC chord, Ctrl+\ is SIGQUIT) with no text-channel
1217
+ // fallback — an unmapped key here is silently lost input.
1218
+ const punctuation = [_]struct { ch: u8, key: vt.input.Key }{
1219
+ .{ .ch = '[', .key = .bracket_left },
1220
+ .{ .ch = ']', .key = .bracket_right },
1221
+ .{ .ch = '\\', .key = .backslash },
1222
+ .{ .ch = ';', .key = .semicolon },
1223
+ .{ .ch = '\'', .key = .quote },
1224
+ .{ .ch = ',', .key = .comma },
1225
+ .{ .ch = '.', .key = .period },
1226
+ .{ .ch = '/', .key = .slash },
1227
+ .{ .ch = '-', .key = .minus },
1228
+ .{ .ch = '=', .key = .equal },
1229
+ .{ .ch = '`', .key = .backquote },
1230
+ };
1231
+ for (punctuation) |entry| {
1232
+ if (ch == entry.ch) return .{ .key = entry.key, .utf8 = utf8, .unshifted = entry.ch };
1233
+ }
1234
+ }
1235
+ if (std.ascii.eqlIgnoreCase(key, "space")) return .{ .key = .space, .utf8 = " ", .unshifted = ' ' };
1236
+ return null;
1237
+ }
1238
+
1239
+ // --------------------------------------------------------- snapshot
1240
+
1241
+ /// Rebuild the published `canvas.TerminalGrid` from the emulator's
1242
+ /// render state, colors RESOLVED per the painter's contract: the
1243
+ /// theme-derived ANSI-16 story (untouched palette entries derive
1244
+ /// from the active tokens; an OSC-restyled slot wins verbatim),
1245
+ /// exact 256-color and truecolor pass-through, inverse/faint/
1246
+ /// invisible folded in, and a spacer cell's background pre-resolved
1247
+ /// to extend its wide primary's.
1248
+ fn rebuildSnapshot(session: *Session, tokens: canvas.DesignTokens) !void {
1249
+ const gpa = session.gpa;
1250
+ // Push the theme colors into the emulator's DEFAULTS (never the
1251
+ // OSC overrides) so ghostty itself composes the final
1252
+ // foreground/background/cursor: an application's OSC 10/11/12
1253
+ // override wins, and DECSCNM swaps whichever pair is in effect.
1254
+ session.term.colors.foreground.default = themeRgb(tokens.colors.text);
1255
+ session.term.colors.background.default = themeRgb(tokens.colors.background);
1256
+ session.term.colors.cursor.default = themeRgb(tokens.colors.accent);
1257
+ const metrics = canvas.terminalCellMetrics(tokens);
1258
+ session.cell_width = metrics.width;
1259
+ session.cell_height = metrics.height;
1260
+
1261
+ try session.render.update(gpa, &session.term);
1262
+ const rs = &session.render;
1263
+ const palette = Palette.init(tokens, &rs.colors, &session.term.colors.palette);
1264
+
1265
+ const row_count = @min(rs.row_data.len, canvas.max_terminal_rows);
1266
+ var col_count: usize = 0;
1267
+ var cluster_bytes: usize = 0;
1268
+ var index: usize = 0;
1269
+ while (index < row_count) : (index += 1) {
1270
+ const row = rs.row_data.get(index);
1271
+ col_count = @max(col_count, row.cells.len);
1272
+ var x: usize = 0;
1273
+ while (x < row.cells.len) : (x += 1) {
1274
+ cluster_bytes += cellClusterBytes(row.cells.get(x));
1275
+ }
1276
+ }
1277
+ // Widen before multiplying: `@min` against a comptime bound
1278
+ // REFINES its result type to the bound's range (u7-by-u9 here),
1279
+ // and the product does not fit the refined peer type.
1280
+ const cell_count = @as(usize, row_count) * @as(usize, @min(col_count, canvas.max_terminal_cols));
1281
+ if (session.cells_buf.len < cell_count) {
1282
+ if (session.cells_buf.len > 0) gpa.free(session.cells_buf);
1283
+ session.cells_buf = &.{};
1284
+ session.cells_buf = try gpa.alloc(canvas.TerminalCell, cell_count);
1285
+ }
1286
+ if (session.cluster_buf.len < cluster_bytes) {
1287
+ if (session.cluster_buf.len > 0) gpa.free(session.cluster_buf);
1288
+ session.cluster_buf = &.{};
1289
+ session.cluster_buf = try gpa.alloc(u8, cluster_bytes);
1290
+ }
1291
+
1292
+ var cell_index: usize = 0;
1293
+ var cluster_len: usize = 0;
1294
+ var y: usize = 0;
1295
+ while (y < row_count) : (y += 1) {
1296
+ const row = rs.row_data.get(y);
1297
+ const cols_here = @min(row.cells.len, canvas.max_terminal_cols);
1298
+ const row_start = cell_index;
1299
+ var prev_bg: ?canvas.Color = null;
1300
+ var x: usize = 0;
1301
+ while (x < cols_here) : (x += 1) {
1302
+ const cell = row.cells.get(x);
1303
+ var out: canvas.TerminalCell = .{ .fg = palette.foreground };
1304
+ out.wide = switch (cell.raw.wide) {
1305
+ .wide => .wide,
1306
+ .spacer_tail, .spacer_head => .spacer,
1307
+ else => .narrow,
1308
+ };
1309
+ // A wide glyph's style lives on its PRIMARY cell only:
1310
+ // the spacer tail extends the primary's background, or a
1311
+ // styled wide character would paint over half its width.
1312
+ out.bg = if (cell.raw.wide == .spacer_tail)
1313
+ prev_bg
1314
+ else
1315
+ cellBackground(cell, &palette);
1316
+ prev_bg = out.bg;
1317
+ var cp: u21 = switch (cell.raw.content_tag) {
1318
+ .codepoint, .codepoint_grapheme => cell.raw.content.codepoint.data,
1319
+ else => 0,
1320
+ };
1321
+ if (out.wide == .spacer) cp = 0;
1322
+ if (cp != 0 and cell.raw.style_id != 0) {
1323
+ const style = cell.style;
1324
+ out.fg = palette.resolveFg(style);
1325
+ out.underline = style.flags.underline != .none;
1326
+ if (style.flags.invisible) cp = 0;
1327
+ }
1328
+ out.cp = cp;
1329
+ // Box-drawing cells render as geometry from `cp` alone;
1330
+ // their cluster stays empty (the painter's contract).
1331
+ if (cp != 0 and !canvas.terminal_box.isBoxDrawing(cp)) {
1332
+ const start = cluster_len;
1333
+ cluster_len += std.unicode.utf8Encode(cp, session.cluster_buf[cluster_len..]) catch 0;
1334
+ if (cell.raw.content_tag == .codepoint_grapheme) {
1335
+ for (cell.grapheme) |extra| {
1336
+ cluster_len += std.unicode.utf8Encode(extra, session.cluster_buf[cluster_len..]) catch 0;
1337
+ }
1338
+ }
1339
+ out.cluster = session.cluster_buf[start..cluster_len];
1340
+ }
1341
+ session.cells_buf[cell_index] = out;
1342
+ cell_index += 1;
1343
+ }
1344
+ session.rows_buf[y] = .{
1345
+ .cells = session.cells_buf[row_start..cell_index],
1346
+ .selection = if (row.selection) |selection| .{
1347
+ @intCast(selection[0]),
1348
+ @intCast(selection[1]),
1349
+ } else null,
1350
+ };
1351
+ }
1352
+
1353
+ // The viewport as plain text: the widget's semantic content and
1354
+ // the fingerprint's text-coverage layer. Unknown beats stale on
1355
+ // failure — empty never reads as "same as before".
1356
+ const text = session.term.plainString(gpa) catch blk: {
1357
+ break :blk @as(?[]const u8, null);
1358
+ };
1359
+ if (session.screen_text.len > 0) gpa.free(session.screen_text);
1360
+ session.screen_text = text orelse &.{};
1361
+
1362
+ // Clipboard text comes from the emulator's selection formatter,
1363
+ // not byte offsets into `screen_text`: this preserves soft-wrap,
1364
+ // wide-cell, word, and line semantics exactly.
1365
+ if (session.selection_text) |selection| gpa.free(selection);
1366
+ session.selection_text = if (session.term.screens.active.selection) |selection|
1367
+ session.term.screens.active.selectionString(gpa, .{
1368
+ .sel = selection,
1369
+ .trim = true,
1370
+ }) catch null
1371
+ else
1372
+ null;
1373
+
1374
+ const bar = session.scrollbarState();
1375
+ session.grid = .{
1376
+ .rows = session.rows_buf[0..row_count],
1377
+ .background = rgbToColor(rs.colors.background),
1378
+ .foreground = rgbToColor(rs.colors.foreground),
1379
+ .cursor_color = if (rs.colors.cursor) |cur| rgbToColor(cur) else tokens.colors.accent,
1380
+ .selection_color = tokens.colors.accent,
1381
+ .cursor = if (rs.cursor.visible) cursor: {
1382
+ const viewport = rs.cursor.viewport orelse break :cursor null;
1383
+ break :cursor .{
1384
+ .x = @intCast(viewport.x),
1385
+ .y = @intCast(viewport.y),
1386
+ .shape = switch (rs.cursor.visual_style) {
1387
+ .bar => .bar,
1388
+ .underline => .underline,
1389
+ else => .block,
1390
+ },
1391
+ };
1392
+ } else null,
1393
+ .running = !session.ended,
1394
+ .select_head = null,
1395
+ .scrollbar = .{
1396
+ .offset = @intCast(bar.offset),
1397
+ .len = @intCast(bar.len),
1398
+ .total = @intCast(bar.total),
1399
+ },
1400
+ .screen_text = session.screen_text,
1401
+ .selection_text = if (session.selection_text) |selection| selection else "",
1402
+ .selection_active = session.term.screens.active.selection != null,
1403
+ };
1404
+ session.snapshot_dirty = false;
1405
+ }
1406
+
1407
+ /// UTF-8 byte need of one cell's cluster, mirroring the snapshot
1408
+ /// loop's emissions exactly (spacers, invisible cells, and
1409
+ /// box-drawing cells contribute nothing).
1410
+ fn cellClusterBytes(cell: anytype) usize {
1411
+ if (cell.raw.wide == .spacer_tail or cell.raw.wide == .spacer_head) return 0;
1412
+ const cp: u21 = switch (cell.raw.content_tag) {
1413
+ .codepoint, .codepoint_grapheme => cell.raw.content.codepoint.data,
1414
+ else => 0,
1415
+ };
1416
+ if (cp == 0) return 0;
1417
+ if (cell.raw.style_id != 0 and cell.style.flags.invisible) return 0;
1418
+ if (canvas.terminal_box.isBoxDrawing(cp)) return 0;
1419
+ var n: usize = std.unicode.utf8CodepointSequenceLength(cp) catch 1;
1420
+ if (cell.raw.content_tag == .codepoint_grapheme) {
1421
+ for (cell.grapheme) |extra| {
1422
+ n += std.unicode.utf8CodepointSequenceLength(extra) catch 1;
1423
+ }
1424
+ }
1425
+ return n;
1426
+ }
1427
+
1428
+ /// A theme token color (f32 rgba 0..1) as the emulator's 8-bit RGB.
1429
+ fn themeRgb(color: canvas.Color) vt.color.RGB {
1430
+ return .{
1431
+ .r = @intFromFloat(std.math.clamp(color.r, 0, 1) * 255 + 0.5),
1432
+ .g = @intFromFloat(std.math.clamp(color.g, 0, 1) * 255 + 0.5),
1433
+ .b = @intFromFloat(std.math.clamp(color.b, 0, 1) * 255 + 0.5),
1434
+ };
1435
+ }
1436
+
1437
+ fn cellBackground(cell: anytype, palette: *const Palette) ?canvas.Color {
1438
+ switch (cell.raw.content_tag) {
1439
+ .bg_color_palette => return palette.indexed(cell.raw.content.color_palette.data),
1440
+ .bg_color_rgb => {
1441
+ const rgb = cell.raw.content.color_rgb;
1442
+ return canvas.Color.rgb8(rgb.r, rgb.g, rgb.b);
1443
+ },
1444
+ else => {},
1445
+ }
1446
+ if (cell.raw.style_id == 0) return null;
1447
+ const style = cell.style;
1448
+ if (style.flags.inverse) {
1449
+ return palette.resolveFgRaw(style);
1450
+ }
1451
+ return switch (style.bg_color) {
1452
+ .none => null,
1453
+ .palette => |index| palette.indexed(index),
1454
+ .rgb => |rgb| canvas.Color.rgb8(rgb.r, rgb.g, rgb.b),
1455
+ };
1456
+ }
1457
+ } else struct {
1458
+ fn unused() void {}
1459
+ };
1460
+
1461
+ // ------------------------------------------------------------- palette
1462
+
1463
+ fn rgbToColor(rgb: anytype) canvas.Color {
1464
+ return canvas.Color.rgb8(rgb.r, rgb.g, rgb.b);
1465
+ }
1466
+
1467
+ /// The theme mapping, stated plainly: where the emulator's palette entry
1468
+ /// still holds its DEFAULT value, the ANSI-16 slot derives from the
1469
+ /// active theme tokens so a themed app and its terminal read as one
1470
+ /// surface. The moment a program restyles an entry (OSC 4), the
1471
+ /// programmed color wins verbatim — and the cube (16..231), the
1472
+ /// grayscale ramp (232..255), and truecolor always pass through exactly.
1473
+ /// (The example tier's palette, promoted with the session store.)
1474
+ const Palette = if (enabled) struct {
1475
+ background: canvas.Color,
1476
+ foreground: canvas.Color,
1477
+ ansi: [16]canvas.Color,
1478
+ /// The emulator's live palette WITH its override mask, so an
1479
+ /// explicit OSC 4 set is honored even when it equals the default
1480
+ /// RGB — the mask, not RGB equality, decides "untouched".
1481
+ dynamic: *const vt.color.DynamicPalette,
1482
+
1483
+ fn init(tokens: canvas.DesignTokens, terminal_colors: *const vt.RenderState.Colors, dynamic: *const vt.color.DynamicPalette) Palette {
1484
+ const colors = tokens.colors;
1485
+ const dark = colors.background.r + colors.background.g + colors.background.b < 1.5;
1486
+ const dim: f32 = if (dark) 0.85 else 1.0;
1487
+ const bright: f32 = if (dark) 1.0 else 0.8;
1488
+ return .{
1489
+ .background = rgbToColor(terminal_colors.background),
1490
+ .foreground = rgbToColor(terminal_colors.foreground),
1491
+ .dynamic = dynamic,
1492
+ .ansi = .{
1493
+ // 0-7: black, red, green, yellow, blue, magenta, cyan, white.
1494
+ blend(colors.text, colors.background, if (dark) 0.35 else 0.95),
1495
+ scale(colors.destructive, dim),
1496
+ scale(colors.success, dim),
1497
+ scale(colors.warning, dim),
1498
+ scale(canvas.Color.rgb8(37, 99, 235), dim),
1499
+ scale(canvas.Color.rgb8(147, 51, 234), dim),
1500
+ scale(canvas.Color.rgb8(8, 145, 178), dim),
1501
+ blend(colors.text, colors.background, if (dark) 0.75 else 0.35),
1502
+ // 8-15: the bright ramp.
1503
+ blend(colors.text, colors.background, if (dark) 0.5 else 0.75),
1504
+ scale(colors.destructive, bright),
1505
+ scale(colors.success, bright),
1506
+ scale(colors.warning, bright),
1507
+ scale(canvas.Color.rgb8(59, 130, 246), bright),
1508
+ scale(canvas.Color.rgb8(168, 85, 247), bright),
1509
+ scale(canvas.Color.rgb8(34, 211, 238), bright),
1510
+ colors.text,
1511
+ },
1512
+ };
1513
+ }
1514
+
1515
+ fn indexed(palette: *const Palette, index: u8) canvas.Color {
1516
+ if (index < 16 and !palette.dynamic.mask.isSet(index)) {
1517
+ return palette.ansi[index];
1518
+ }
1519
+ const live = palette.dynamic.current[index];
1520
+ return canvas.Color.rgb8(live.r, live.g, live.b);
1521
+ }
1522
+
1523
+ fn resolveFg(palette: *const Palette, style: vt.Style) canvas.Color {
1524
+ if (style.flags.inverse) {
1525
+ // Inverse paints the text in the cell's BACKGROUND color
1526
+ // (the theme background when the cell chose none) — the
1527
+ // opposite of `cellBackground`, which paints the swapped
1528
+ // foreground behind it.
1529
+ return palette.resolveBgRaw(style);
1530
+ }
1531
+ var color = palette.resolveFgRaw(style);
1532
+ if (style.flags.faint) color = blend(color, palette.background, 0.5);
1533
+ return color;
1534
+ }
1535
+
1536
+ fn resolveFgRaw(palette: *const Palette, style: vt.Style) canvas.Color {
1537
+ return switch (style.fg_color) {
1538
+ .none => palette.foreground,
1539
+ .palette => |index| palette.indexed(index),
1540
+ .rgb => |rgb| canvas.Color.rgb8(rgb.r, rgb.g, rgb.b),
1541
+ };
1542
+ }
1543
+
1544
+ fn resolveBgRaw(palette: *const Palette, style: vt.Style) canvas.Color {
1545
+ return switch (style.bg_color) {
1546
+ .none => palette.background,
1547
+ .palette => |index| palette.indexed(index),
1548
+ .rgb => |rgb| canvas.Color.rgb8(rgb.r, rgb.g, rgb.b),
1549
+ };
1550
+ }
1551
+
1552
+ fn blend(a: canvas.Color, b: canvas.Color, t: f32) canvas.Color {
1553
+ return canvas.Color.rgba(
1554
+ a.r + (b.r - a.r) * t,
1555
+ a.g + (b.g - a.g) * t,
1556
+ a.b + (b.b - a.b) * t,
1557
+ 1,
1558
+ );
1559
+ }
1560
+
1561
+ fn scale(color: canvas.Color, factor: f32) canvas.Color {
1562
+ return canvas.Color.rgba(
1563
+ @min(1, color.r * factor),
1564
+ @min(1, color.g * factor),
1565
+ @min(1, color.b * factor),
1566
+ 1,
1567
+ );
1568
+ }
1569
+ } else struct {};