Open History to see the last commit
1import {
2 type GhosttyKeyboardLayoutMap,
3 ghosttyConsumedMods,
4 ghosttyKeyForCode,
5 ghosttyUnshiftedCodepoint,
6 loadGhosttyKeyboardLayoutMap,
7} from "./keyCodes";
8import { GhosttyRuntime, loadGhosttyRuntime } from "./runtime";
9
10const GHOSTTY_SUCCESS = 0;
11const GHOSTTY_OUT_OF_SPACE = -3;
12const MAX_SCROLLBACK_ROWS = 10_000;
13// wasm32 C ABI layout for GhosttyTerminalSelectionFormatOptions at the
14// libghostty-vt revision pinned alongside this module.
15const SELECTION_FORMAT_OPTIONS_SIZE = 16;
16
17const RENDER_DATA = {
18 cols: 1,
19 rows: 2,
20 dirty: 3,
21 rowIterator: 4,
22 background: 5,
23 foreground: 6,
24 cursor: 7,
25 cursorHasValue: 8,
26 cursorStyle: 10,
27 cursorVisible: 11,
28 cursorBlinking: 12,
29 cursorInViewport: 14,
30 cursorX: 15,
31 cursorY: 16,
32} as const;
33
34const ROW_DATA = {
35 dirty: 1,
36 raw: 2,
37 cells: 3,
38} as const;
39
40const CELL_DATA = {
41 raw: 1,
42 style: 2,
43 graphemesLength: 3,
44 graphemes: 4,
45 background: 5,
46 foreground: 6,
47 selected: 7,
48} as const;
49
50const RAW_CELL_DATA = {
51 wide: 3,
52} as const;
53
54export const GHOSTTY_CELL_WIDE = {
55 narrow: 0,
56 wide: 1,
57 spacerTail: 2,
58 spacerHead: 3,
59} as const;
60
61export interface GhosttyColor {
62 readonly r: number;
63 readonly g: number;
64 readonly b: number;
65}
66
67export interface GhosttyTheme {
68 readonly foreground: GhosttyColor;
69 readonly background: GhosttyColor;
70 readonly cursor: GhosttyColor;
71 /** CSS color the renderer overlays on selected cells; not sent to Ghostty. */
72 readonly selectionBackground?: string;
73}
74
75export interface GhosttyCell {
76 readonly text: string;
77 readonly wide: number;
78 readonly foreground: GhosttyColor;
79 readonly background: GhosttyColor;
80 readonly bold: boolean;
81 readonly italic: boolean;
82 readonly invisible: boolean;
83 readonly strikethrough: boolean;
84 readonly overline: boolean;
85 readonly underline: boolean;
86 readonly selected: boolean;
87}
88
89export interface GhosttyRow {
90 readonly cells: readonly GhosttyCell[];
91 readonly text: string;
92 readonly isWrapContinuation: boolean;
93 /** Whether this row soft-wraps onto the next row. */
94 readonly wrapsToNext: boolean;
95}
96
97export interface GhosttySnapshot {
98 readonly cols: number;
99 readonly rows: number;
100 readonly foreground: GhosttyColor;
101 readonly background: GhosttyColor;
102 readonly cursor: GhosttyColor;
103 readonly cursorX: number;
104 readonly cursorY: number;
105 readonly cursorVisible: boolean;
106 readonly cursorBlinking: boolean;
107 readonly cursorStyle: number;
108 readonly dirtyRows: ReadonlySet<number>;
109 readonly rowData: readonly GhosttyRow[];
110}
111
112export interface GhosttySelectionRange {
113 readonly viewport: {
114 readonly start: { readonly x: number; readonly y: number };
115 readonly end: { readonly x: number; readonly y: number };
116 };
117 readonly screen: {
118 readonly start: { readonly x: number; readonly y: number };
119 readonly end: { readonly x: number; readonly y: number };
120 };
121}
122
123export interface GhosttyScrollbar {
124 readonly total: number;
125 readonly offset: number;
126 readonly len: number;
127}
128
129/** Grid position tagged with its Ghostty coordinate space: 1 viewport, 2 screen. */
130export interface GhosttyPointInput {
131 readonly x: number;
132 readonly y: number;
133 readonly tag?: 1 | 2;
134}
135
136export interface GhosttyMouseInput {
137 readonly action: "press" | "release" | "motion";
138 readonly button: number | null;
139 readonly mods: number;
140 readonly x: number;
141 readonly y: number;
142 readonly screenWidth: number;
143 readonly screenHeight: number;
144 readonly cellWidth: number;
145 readonly cellHeight: number;
146 readonly paddingLeft: number;
147 readonly paddingRight: number;
148 readonly paddingTop: number;
149 readonly paddingBottom: number;
150 readonly anyButtonPressed: boolean;
151}
152
153const decoder = new TextDecoder();
154const encoder = new TextEncoder();
155
156function blend(foreground: GhosttyColor, background: GhosttyColor): GhosttyColor {
157 const channel = (front: number, back: number) => Math.floor((front * 155 + back * 100) / 255);
158 return {
159 r: channel(foreground.r, background.r),
160 g: channel(foreground.g, background.g),
161 b: channel(foreground.b, background.b),
162 };
163}
164
165function sameColor(left: GhosttyColor, right: GhosttyColor): boolean {
166 return left.r === right.r && left.g === right.g && left.b === right.b;
167}
168
169/**
170 * A terminal program can print one base character followed by a huge run of
171 * combining marks, packing hundreds of thousands of codepoints into a single
172 * cell that still fits the scrollback buffer. Engines cap spread-call
173 * arguments far below that, so convert in bounded chunks instead of spreading
174 * every codepoint into String.fromCodePoint at once.
175 */
176export function ghosttyCellText(codepointView: DataView, graphemeLength: number): string {
177 if (graphemeLength === 1) return String.fromCodePoint(codepointView.getUint32(0, true));
178 const CHUNK_SIZE = 4_096;
179 let text = "";
180 for (let start = 0; start < graphemeLength; start += CHUNK_SIZE) {
181 const count = Math.min(CHUNK_SIZE, graphemeLength - start);
182 const codes = new Array<number>(count);
183 for (let index = 0; index < count; index += 1) {
184 codes[index] = codepointView.getUint32((start + index) * 4, true);
185 }
186 text += String.fromCodePoint(...codes);
187 }
188 return text;
189}
190
191export class GhosttyTerminalCore {
192 private readonly runtime: GhosttyRuntime;
193 private terminalSlot = 0;
194 private terminal = 0;
195 private renderStateSlot = 0;
196 private renderState = 0;
197 private rowIteratorSlot = 0;
198 private rowCellsSlot = 0;
199 private keyEncoderSlot = 0;
200 private keyEncoder = 0;
201 private keyEventSlot = 0;
202 private keyEvent = 0;
203 private mouseEncoderSlot = 0;
204 private mouseEncoder = 0;
205 private mouseEventSlot = 0;
206 private mouseEvent = 0;
207 private ptyWriterId = 0;
208 private ptyWriter: ((data: string) => void) | null = null;
209 private scratch = 0;
210 private graphemes = 0;
211 private graphemeCapacity = 0;
212 private style = 0;
213 private scrollbar = 0;
214 private rows: GhosttyRow[] = [];
215 private disposed = false;
216 private keyboardLayoutMap: GhosttyKeyboardLayoutMap | undefined;
217
218 private constructor(runtime: GhosttyRuntime) {
219 this.runtime = runtime;
220 void loadGhosttyKeyboardLayoutMap().then((layoutMap) => {
221 if (!this.disposed) this.keyboardLayoutMap = layoutMap;
222 });
223 }
224
225 static async create(
226 cols: number,
227 rows: number,
228 cellWidth: number,
229 cellHeight: number,
230 theme: GhosttyTheme,
231 onPtyData: (data: string) => void,
232 ): Promise<GhosttyTerminalCore> {
233 const core = new GhosttyTerminalCore(await loadGhosttyRuntime());
234 try {
235 core.initialize(cols, rows, cellWidth, cellHeight, theme, onPtyData);
236 return core;
237 } catch (error) {
238 core.dispose();
239 throw error;
240 }
241 }
242
243 private initialize(
244 cols: number,
245 rows: number,
246 cellWidth: number,
247 cellHeight: number,
248 theme: GhosttyTheme,
249 onPtyData: (data: string) => void,
250 ): void {
251 const optionsSize = this.runtime.layout("GhosttyTerminalOptions").size;
252 const options = this.runtime.alloc(optionsSize);
253 this.runtime.setField(options, "GhosttyTerminalOptions", "cols", cols);
254 this.runtime.setField(options, "GhosttyTerminalOptions", "rows", rows);
255 this.runtime.setField(options, "GhosttyTerminalOptions", "max_scrollback", MAX_SCROLLBACK_ROWS);
256 this.terminalSlot = this.runtime.allocOpaque();
257 const terminalResult = this.runtime.call("ghostty_terminal_new", 0, this.terminalSlot, options);
258 this.runtime.free(options, optionsSize);
259 this.assertSuccess("ghostty_terminal_new", terminalResult);
260 this.terminal = this.runtime.readPointer(this.terminalSlot);
261 this.applyDefaultCursorBlink();
262 this.ptyWriter = onPtyData;
263 this.ptyWriterId = this.runtime.attachPtyWriter(this.terminal, onPtyData);
264
265 this.renderStateSlot = this.runtime.allocOpaque();
266 this.assertSuccess(
267 "ghostty_render_state_new",
268 this.runtime.call("ghostty_render_state_new", 0, this.renderStateSlot),
269 );
270 this.renderState = this.runtime.readPointer(this.renderStateSlot);
271
272 this.rowIteratorSlot = this.runtime.allocOpaque();
273 this.assertSuccess(
274 "ghostty_render_state_row_iterator_new",
275 this.runtime.call("ghostty_render_state_row_iterator_new", 0, this.rowIteratorSlot),
276 );
277 this.rowCellsSlot = this.runtime.allocOpaque();
278 this.assertSuccess(
279 "ghostty_render_state_row_cells_new",
280 this.runtime.call("ghostty_render_state_row_cells_new", 0, this.rowCellsSlot),
281 );
282
283 this.keyEncoderSlot = this.runtime.allocOpaque();
284 this.assertSuccess(
285 "ghostty_key_encoder_new",
286 this.runtime.call("ghostty_key_encoder_new", 0, this.keyEncoderSlot),
287 );
288 this.keyEncoder = this.runtime.readPointer(this.keyEncoderSlot);
289 this.keyEventSlot = this.runtime.allocOpaque();
290 this.assertSuccess(
291 "ghostty_key_event_new",
292 this.runtime.call("ghostty_key_event_new", 0, this.keyEventSlot),
293 );
294 this.keyEvent = this.runtime.readPointer(this.keyEventSlot);
295
296 this.mouseEncoderSlot = this.runtime.allocOpaque();
297 this.assertSuccess(
298 "ghostty_mouse_encoder_new",
299 this.runtime.call("ghostty_mouse_encoder_new", 0, this.mouseEncoderSlot),
300 );
301 this.mouseEncoder = this.runtime.readPointer(this.mouseEncoderSlot);
302 this.mouseEventSlot = this.runtime.allocOpaque();
303 this.assertSuccess(
304 "ghostty_mouse_event_new",
305 this.runtime.call("ghostty_mouse_event_new", 0, this.mouseEventSlot),
306 );
307 this.mouseEvent = this.runtime.readPointer(this.mouseEventSlot);
308
309 this.scratch = this.runtime.alloc(16);
310 const styleSize = this.runtime.layout("GhosttyStyle").size;
311 this.style = this.runtime.alloc(styleSize);
312 this.runtime.setField(this.style, "GhosttyStyle", "size", styleSize);
313 this.scrollbar = this.runtime.alloc(this.runtime.layout("GhosttyTerminalScrollbar").size);
314 this.setTheme(theme);
315 this.resize(cols, rows, cellWidth, cellHeight);
316 }
317
318 write(data: string | Uint8Array): void {
319 this.ensureActive();
320 const bytes = typeof data === "string" ? encoder.encode(data) : data;
321 if (bytes.length === 0) return;
322 const pointer = this.runtime.alloc(bytes.length);
323 this.runtime.bytes(pointer, bytes.length).set(bytes);
324 this.runtime.call("ghostty_terminal_vt_write", this.terminal, pointer, bytes.length);
325 this.runtime.free(pointer, bytes.length);
326 }
327
328 resetAndWrite(data: string): void {
329 this.ensureActive();
330 this.runtime.call("ghostty_terminal_reset", this.terminal);
331 // RIS returns the cursor to Ghostty's built-in steady default, so the
332 // embedder default has to be applied again before the replay runs.
333 this.applyDefaultCursorBlink();
334 this.rows = [];
335 if (data.length === 0) return;
336 const writer = this.ptyWriter;
337 if (this.ptyWriterId !== 0) {
338 this.runtime.detachPtyWriter(this.terminal, this.ptyWriterId);
339 this.ptyWriterId = 0;
340 }
341 try {
342 this.write(data);
343 } finally {
344 if (writer !== null && !this.disposed) {
345 this.ptyWriterId = this.runtime.attachPtyWriter(this.terminal, writer);
346 }
347 }
348 }
349
350 resize(cols: number, rows: number, cellWidth: number, cellHeight: number): void {
351 this.ensureActive();
352 this.assertSuccess(
353 "ghostty_terminal_resize",
354 this.runtime.call(
355 "ghostty_terminal_resize",
356 this.terminal,
357 Math.max(1, Math.min(65_535, cols)),
358 Math.max(1, Math.min(65_535, rows)),
359 Math.max(1, Math.round(cellWidth)),
360 Math.max(1, Math.round(cellHeight)),
361 ),
362 );
363 }
364
365 /**
366 * Ghostty's built-in default cursor is steady, while the xterm.js renderer
367 * this replaced ran with `cursorBlink: true`. Option 23 is the embedder's
368 * default blink, which is the state a session starts in and returns to on
369 * DECSCUSR reset (CSI 0 q), so programs that ask for a specific cursor
370 * through DECSCUSR or DEC mode 12 still win.
371 */
372 private applyDefaultCursorBlink(): void {
373 const blink = this.runtime.alloc(1);
374 this.runtime.bytes(blink, 1)[0] = 1;
375 this.runtime.call("ghostty_terminal_set", this.terminal, 23, blink);
376 this.runtime.free(blink, 1);
377 }
378
379 setTheme(theme: GhosttyTheme): void {
380 this.ensureActive();
381 const color = this.runtime.alloc(3);
382 for (const [option, value] of [
383 [11, theme.foreground],
384 [12, theme.background],
385 [13, theme.cursor],
386 ] as const) {
387 this.runtime.bytes(color, 3).set([value.r, value.g, value.b]);
388 this.runtime.call("ghostty_terminal_set", this.terminal, option, color);
389 }
390 this.runtime.free(color, 3);
391 }
392
393 scroll(deltaRows: number): void {
394 this.ensureActive();
395 const layout = this.runtime.layout("GhosttyTerminalScrollViewport");
396 const scroll = this.runtime.alloc(layout.size);
397 this.runtime.setField(scroll, "GhosttyTerminalScrollViewport", "tag", 2);
398 const value = layout.fields.value!;
399 this.runtime.view(scroll + value.offset, value.size).setInt32(0, deltaRows, true);
400 this.runtime.call("ghostty_terminal_scroll_viewport", this.terminal, scroll);
401 this.runtime.free(scroll, layout.size);
402 }
403
404 scrollToBottom(): void {
405 this.ensureActive();
406 const layout = this.runtime.layout("GhosttyTerminalScrollViewport");
407 const scroll = this.runtime.alloc(layout.size);
408 this.runtime.setField(scroll, "GhosttyTerminalScrollViewport", "tag", 1);
409 this.runtime.call("ghostty_terminal_scroll_viewport", this.terminal, scroll);
410 this.runtime.free(scroll, layout.size);
411 }
412
413 isViewportActive(): boolean {
414 this.ensureActive();
415 this.runtime.bytes(this.scratch, 1)[0] = 0;
416 return (
417 this.runtime.call("ghostty_terminal_get", this.terminal, 32, this.scratch) ===
418 GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
419 );
420 }
421
422 scrollbarState(): GhosttyScrollbar | null {
423 this.ensureActive();
424 const layout = this.runtime.layout("GhosttyTerminalScrollbar");
425 this.runtime.bytes(this.scrollbar, layout.size).fill(0);
426 if (
427 this.runtime.call("ghostty_terminal_get", this.terminal, 9, this.scrollbar) !==
428 GHOSTTY_SUCCESS
429 ) {
430 return null;
431 }
432 return {
433 total: this.runtime.readField(this.scrollbar, "GhosttyTerminalScrollbar", "total"),
434 offset: this.runtime.readField(this.scrollbar, "GhosttyTerminalScrollbar", "offset"),
435 len: this.runtime.readField(this.scrollbar, "GhosttyTerminalScrollbar", "len"),
436 };
437 }
438
439 isMouseTracking(): boolean {
440 this.ensureActive();
441 this.runtime.bytes(this.scratch, 1)[0] = 0;
442 return (
443 this.runtime.call("ghostty_terminal_get", this.terminal, 11, this.scratch) ===
444 GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
445 );
446 }
447
448 isMouseAnyEventTracking(): boolean {
449 this.ensureActive();
450 this.runtime.bytes(this.scratch, 1)[0] = 0;
451 return (
452 this.runtime.call("ghostty_terminal_mode_get", this.terminal, 1003, this.scratch) ===
453 GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
454 );
455 }
456
457 isAlternateScreen(): boolean {
458 this.ensureActive();
459 this.runtime.bytes(this.scratch, 4).fill(0);
460 return (
461 this.runtime.call("ghostty_terminal_get", this.terminal, 6, this.scratch) ===
462 GHOSTTY_SUCCESS && this.runtime.view(this.scratch, 4).getUint32(0, true) === 1
463 );
464 }
465
466 isApplicationCursorKeys(): boolean {
467 this.ensureActive();
468 this.runtime.bytes(this.scratch, 1)[0] = 0;
469 return (
470 this.runtime.call("ghostty_terminal_mode_get", this.terminal, 1, this.scratch) ===
471 GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
472 );
473 }
474
475 encodeKey(event: KeyboardEvent, action: "press" | "release" = "press"): string {
476 this.ensureActive();
477 this.runtime.call("ghostty_key_encoder_setopt_from_terminal", this.keyEncoder, this.terminal);
478 this.runtime.call(
479 "ghostty_key_event_set_action",
480 this.keyEvent,
481 action === "release" ? 0 : event.repeat ? 2 : 1,
482 );
483 this.runtime.call("ghostty_key_event_set_key", this.keyEvent, ghosttyKeyForCode(event.code));
484 const mods =
485 (event.shiftKey ? 1 : 0) |
486 (event.ctrlKey ? 1 << 1 : 0) |
487 (event.altKey ? 1 << 2 : 0) |
488 (event.metaKey ? 1 << 3 : 0) |
489 (event.getModifierState("CapsLock") ? 1 << 4 : 0) |
490 (event.getModifierState("NumLock") ? 1 << 5 : 0);
491 this.runtime.call("ghostty_key_event_set_mods", this.keyEvent, mods);
492 this.runtime.call(
493 "ghostty_key_event_set_consumed_mods",
494 this.keyEvent,
495 ghosttyConsumedMods(event),
496 );
497 this.runtime.call("ghostty_key_event_set_composing", this.keyEvent, event.isComposing ? 1 : 0);
498 this.runtime.call(
499 "ghostty_key_event_set_unshifted_codepoint",
500 this.keyEvent,
501 ghosttyUnshiftedCodepoint(event, this.keyboardLayoutMap),
502 );
503
504 const text = event.key.length === 1 ? event.key : "";
505 const textBytes = encoder.encode(text);
506 const textPointer = textBytes.length === 0 ? 0 : this.runtime.alloc(textBytes.length);
507 if (textPointer !== 0) this.runtime.bytes(textPointer, textBytes.length).set(textBytes);
508 this.runtime.call("ghostty_key_event_set_utf8", this.keyEvent, textPointer, textBytes.length);
509
510 const written = this.runtime.call("ghostty_wasm_alloc_usize");
511 const encoded = this.encodeOutput(written, (output, outputSize) =>
512 this.runtime.call(
513 "ghostty_key_encoder_encode",
514 this.keyEncoder,
515 this.keyEvent,
516 output,
517 outputSize,
518 written,
519 ),
520 );
521 this.runtime.call("ghostty_wasm_free_usize", written);
522 if (textPointer !== 0) this.runtime.free(textPointer, textBytes.length);
523 return encoded;
524 }
525
526 encodePaste(data: string): string {
527 this.ensureActive();
528 const input = encoder.encode(data);
529 if (input.length === 0) return "";
530 const inputPointer = this.runtime.alloc(input.length);
531 this.runtime.bytes(inputPointer, input.length).set(input);
532 this.runtime.bytes(this.scratch, 1)[0] = 0;
533 const bracketed =
534 this.runtime.call("ghostty_terminal_mode_get", this.terminal, 2004, this.scratch) ===
535 GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0;
536 const written = this.runtime.call("ghostty_wasm_alloc_usize");
537 let encoded = "";
538 const sizeResult = this.runtime.call(
539 "ghostty_paste_encode",
540 inputPointer,
541 input.length,
542 bracketed ? 1 : 0,
543 0,
544 0,
545 written,
546 );
547 const outputSize = this.runtime.view(written, 4).getUint32(0, true);
548 if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
549 const output = this.runtime.alloc(outputSize);
550 const result = this.runtime.call(
551 "ghostty_paste_encode",
552 inputPointer,
553 input.length,
554 bracketed ? 1 : 0,
555 output,
556 outputSize,
557 written,
558 );
559 const outputLength = this.runtime.view(written, 4).getUint32(0, true);
560 encoded =
561 result === GHOSTTY_SUCCESS ? decoder.decode(this.runtime.bytes(output, outputLength)) : "";
562 this.runtime.free(output, outputSize);
563 }
564 this.runtime.call("ghostty_wasm_free_usize", written);
565 this.runtime.free(inputPointer, input.length);
566 return encoded;
567 }
568
569 encodeMouse(input: GhosttyMouseInput): string {
570 this.ensureActive();
571 this.runtime.call(
572 "ghostty_mouse_encoder_setopt_from_terminal",
573 this.mouseEncoder,
574 this.terminal,
575 );
576
577 const sizeLayout = this.runtime.layout("GhosttyMouseEncoderSize");
578 const size = this.runtime.alloc(sizeLayout.size);
579 for (const [field, value] of [
580 ["size", sizeLayout.size],
581 ["screen_width", input.screenWidth],
582 ["screen_height", input.screenHeight],
583 ["cell_width", input.cellWidth],
584 ["cell_height", input.cellHeight],
585 ["padding_top", input.paddingTop],
586 ["padding_bottom", input.paddingBottom],
587 ["padding_right", input.paddingRight],
588 ["padding_left", input.paddingLeft],
589 ] as const) {
590 this.runtime.setField(size, "GhosttyMouseEncoderSize", field, Math.max(0, Math.round(value)));
591 }
592 this.runtime.call("ghostty_mouse_encoder_setopt", this.mouseEncoder, 2, size);
593 this.runtime.free(size, sizeLayout.size);
594
595 this.runtime.bytes(this.scratch, 1)[0] = input.anyButtonPressed ? 1 : 0;
596 this.runtime.call("ghostty_mouse_encoder_setopt", this.mouseEncoder, 3, this.scratch);
597 this.runtime.bytes(this.scratch, 1)[0] = 1;
598 this.runtime.call("ghostty_mouse_encoder_setopt", this.mouseEncoder, 4, this.scratch);
599
600 this.runtime.call(
601 "ghostty_mouse_event_set_action",
602 this.mouseEvent,
603 input.action === "press" ? 0 : input.action === "release" ? 1 : 2,
604 );
605 if (input.button === null) {
606 this.runtime.call("ghostty_mouse_event_clear_button", this.mouseEvent);
607 } else {
608 this.runtime.call("ghostty_mouse_event_set_button", this.mouseEvent, input.button);
609 }
610 this.runtime.call("ghostty_mouse_event_set_mods", this.mouseEvent, input.mods);
611 const positionLayout = this.runtime.layout("GhosttyMousePosition");
612 const position = this.runtime.alloc(positionLayout.size);
613 const positionView = this.runtime.view(position, positionLayout.size);
614 positionView.setFloat32(positionLayout.fields.x!.offset, input.x, true);
615 positionView.setFloat32(positionLayout.fields.y!.offset, input.y, true);
616 this.runtime.call("ghostty_mouse_event_set_position", this.mouseEvent, position);
617 this.runtime.free(position, positionLayout.size);
618
619 const written = this.runtime.call("ghostty_wasm_alloc_usize");
620 const encoded = this.encodeOutput(written, (output, outputSize) =>
621 this.runtime.call(
622 "ghostty_mouse_encoder_encode",
623 this.mouseEncoder,
624 this.mouseEvent,
625 output,
626 outputSize,
627 written,
628 ),
629 );
630 this.runtime.call("ghostty_wasm_free_usize", written);
631 return encoded;
632 }
633
634 setSelection(anchor: GhosttyPointInput, end: GhosttyPointInput): void {
635 this.ensureActive();
636 const selectionLayout = this.runtime.layout("GhosttySelection");
637 const gridRefSize = this.runtime.layout("GhosttyGridRef").size;
638 const selection = this.runtime.alloc(selectionLayout.size);
639 let start = 0;
640 let endRef = 0;
641 try {
642 this.runtime.setField(selection, "GhosttySelection", "size", selectionLayout.size);
643 start = this.gridRef(anchor.x, anchor.y, anchor.tag ?? 1);
644 endRef = this.gridRef(end.x, end.y, end.tag ?? 1);
645 const startField = selectionLayout.fields.start!;
646 const endField = selectionLayout.fields.end!;
647 this.runtime
648 .bytes(selection + startField.offset, startField.size)
649 .set(this.runtime.bytes(start, startField.size));
650 this.runtime
651 .bytes(selection + endField.offset, endField.size)
652 .set(this.runtime.bytes(endRef, endField.size));
653 this.runtime.call("ghostty_terminal_set", this.terminal, 21, selection);
654 } finally {
655 this.runtime.free(start, gridRefSize);
656 this.runtime.free(endRef, gridRefSize);
657 this.runtime.free(selection, selectionLayout.size);
658 }
659 }
660
661 selectAll(): void {
662 this.ensureActive();
663 const layout = this.runtime.layout("GhosttySelection");
664 const selection = this.runtime.alloc(layout.size);
665 this.runtime.setField(selection, "GhosttySelection", "size", layout.size);
666 if (
667 this.runtime.call("ghostty_terminal_select_all", this.terminal, selection) === GHOSTTY_SUCCESS
668 ) {
669 this.runtime.call("ghostty_terminal_set", this.terminal, 21, selection);
670 }
671 this.runtime.free(selection, layout.size);
672 }
673
674 selectWord(col: number, row: number): GhosttySelectionRange | null {
675 return this.selectAt(
676 "GhosttyTerminalSelectWordOptions",
677 "ghostty_terminal_select_word",
678 col,
679 row,
680 );
681 }
682
683 selectLine(col: number, row: number): GhosttySelectionRange | null {
684 return this.selectAt(
685 "GhosttyTerminalSelectLineOptions",
686 "ghostty_terminal_select_line",
687 col,
688 row,
689 );
690 }
691
692 hyperlinkAt(col: number, row: number): string | null {
693 this.ensureActive();
694 const ref = this.gridRef(col, row);
695 const written = this.runtime.call("ghostty_wasm_alloc_usize");
696 const sizeResult = this.runtime.call("ghostty_grid_ref_hyperlink_uri", ref, 0, 0, written);
697 const outputSize = this.runtime.view(written, 4).getUint32(0, true);
698 let hyperlink: string | null = null;
699 if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
700 const output = this.runtime.alloc(outputSize);
701 const result = this.runtime.call(
702 "ghostty_grid_ref_hyperlink_uri",
703 ref,
704 output,
705 outputSize,
706 written,
707 );
708 const outputLength = this.runtime.view(written, 4).getUint32(0, true);
709 if (result === GHOSTTY_SUCCESS && outputLength > 0) {
710 hyperlink = decoder.decode(this.runtime.bytes(output, outputLength));
711 }
712 this.runtime.free(output, outputSize);
713 }
714 this.runtime.call("ghostty_wasm_free_usize", written);
715 this.runtime.free(ref, this.runtime.layout("GhosttyGridRef").size);
716 return hyperlink;
717 }
718
719 clearSelection(): void {
720 this.ensureActive();
721 this.runtime.call("ghostty_terminal_set", this.terminal, 21, 0);
722 }
723
724 snapshot(): GhosttySnapshot {
725 this.ensureActive();
726 this.assertSuccess(
727 "ghostty_render_state_update",
728 this.runtime.call("ghostty_render_state_update", this.renderState, this.terminal),
729 );
730 const cols = this.getU16(RENDER_DATA.cols);
731 const rowCount = this.getU16(RENDER_DATA.rows);
732 const dirty = this.getU32(RENDER_DATA.dirty);
733 const foreground = this.getColor(RENDER_DATA.foreground, { r: 229, g: 231, b: 235 });
734 const background = this.getColor(RENDER_DATA.background, { r: 0, g: 0, b: 0 });
735 const cursorHasValue = this.getBool(RENDER_DATA.cursorHasValue);
736 const cursor = cursorHasValue ? this.getColor(RENDER_DATA.cursor, foreground) : foreground;
737 const cursorInViewport = this.getBool(RENDER_DATA.cursorInViewport);
738 const cursorVisible = this.getBool(RENDER_DATA.cursorVisible) && cursorInViewport;
739 const cursorX = cursorInViewport ? this.getU16(RENDER_DATA.cursorX) : -1;
740 const cursorY = cursorInViewport ? this.getU16(RENDER_DATA.cursorY) : -1;
741
742 if (this.rows.length !== rowCount || this.rows.some((row) => row.cells.length !== cols)) {
743 this.rows = Array.from({ length: rowCount }, () => ({
744 cells: Array.from({ length: cols }, () => this.emptyCell(foreground, background)),
745 text: "",
746 isWrapContinuation: false,
747 wrapsToNext: false,
748 }));
749 }
750
751 const dirtyRows = new Set<number>();
752 if (dirty !== 0) {
753 this.assertSuccess(
754 "ghostty_render_state_get(row iterator)",
755 this.runtime.call(
756 "ghostty_render_state_get",
757 this.renderState,
758 RENDER_DATA.rowIterator,
759 this.rowIteratorSlot,
760 ),
761 );
762 const iterator = this.runtime.readPointer(this.rowIteratorSlot);
763 let rowIndex = 0;
764 while (
765 rowIndex < rowCount &&
766 this.runtime.call("ghostty_render_state_row_iterator_next", iterator) !== 0
767 ) {
768 const rowDirty = dirty === 2 || this.getRowBool(iterator, ROW_DATA.dirty);
769 if (rowDirty) {
770 this.rows[rowIndex] = this.readRow(iterator, cols, foreground, background);
771 dirtyRows.add(rowIndex);
772 this.runtime.bytes(this.scratch, 1)[0] = 0;
773 this.runtime.call("ghostty_render_state_row_set", iterator, 0, this.scratch);
774 }
775 rowIndex += 1;
776 }
777 this.runtime.view(this.scratch, 4).setUint32(0, 0, true);
778 this.runtime.call("ghostty_render_state_set", this.renderState, 0, this.scratch);
779 }
780
781 return {
782 cols,
783 rows: rowCount,
784 foreground,
785 background,
786 cursor,
787 cursorX,
788 cursorY,
789 cursorVisible,
790 cursorBlinking: this.getBool(RENDER_DATA.cursorBlinking),
791 cursorStyle: this.getU32(RENDER_DATA.cursorStyle),
792 dirtyRows,
793 rowData: this.rows,
794 };
795 }
796
797 selectionText(): string {
798 this.ensureActive();
799 const options = this.runtime.alloc(SELECTION_FORMAT_OPTIONS_SIZE);
800 const optionsView = this.runtime.view(options, SELECTION_FORMAT_OPTIONS_SIZE);
801 optionsView.setUint32(0, SELECTION_FORMAT_OPTIONS_SIZE, true);
802 optionsView.setUint32(4, 0, true);
803 optionsView.setUint8(8, 1);
804 optionsView.setUint8(9, 1);
805 optionsView.setUint32(12, 0, true);
806 const written = this.runtime.call("ghostty_wasm_alloc_usize");
807 const sizeResult = this.runtime.call(
808 "ghostty_terminal_selection_format_buf",
809 this.terminal,
810 options,
811 0,
812 0,
813 written,
814 );
815 const outputSize = this.runtime.view(written, 4).getUint32(0, true);
816 let text = "";
817 if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
818 const output = this.runtime.alloc(outputSize);
819 const result = this.runtime.call(
820 "ghostty_terminal_selection_format_buf",
821 this.terminal,
822 options,
823 output,
824 outputSize,
825 written,
826 );
827 const outputLength = this.runtime.view(written, 4).getUint32(0, true);
828 if (result === GHOSTTY_SUCCESS) {
829 text = decoder.decode(this.runtime.bytes(output, outputLength));
830 }
831 this.runtime.free(output, outputSize);
832 }
833 this.runtime.call("ghostty_wasm_free_usize", written);
834 this.runtime.free(options, SELECTION_FORMAT_OPTIONS_SIZE);
835 return text;
836 }
837
838 viewportPointToScreen(col: number, row: number): { x: number; y: number } | null {
839 return this.convertPoint(col, row, 1, 2);
840 }
841
842 screenPointToViewport(col: number, row: number): { x: number; y: number } | null {
843 return this.convertPoint(col, row, 2, 1);
844 }
845
846 private convertPoint(
847 col: number,
848 row: number,
849 fromTag: 1 | 2,
850 toTag: 1 | 2,
851 ): { x: number; y: number } | null {
852 this.ensureActive();
853 const ref = this.gridRef(col, row, fromTag);
854 const point = this.pointFromGridRef(ref, toTag);
855 this.runtime.free(ref, this.runtime.layout("GhosttyGridRef").size);
856 return point;
857 }
858
859 dispose(): void {
860 if (this.disposed) return;
861 this.disposed = true;
862 if (this.mouseEvent) this.runtime.call("ghostty_mouse_event_free", this.mouseEvent);
863 if (this.mouseEncoder) this.runtime.call("ghostty_mouse_encoder_free", this.mouseEncoder);
864 if (this.keyEvent) this.runtime.call("ghostty_key_event_free", this.keyEvent);
865 if (this.keyEncoder) this.runtime.call("ghostty_key_encoder_free", this.keyEncoder);
866 if (this.rowCellsSlot) {
867 const cells = this.runtime.readPointer(this.rowCellsSlot);
868 if (cells) this.runtime.call("ghostty_render_state_row_cells_free", cells);
869 }
870 if (this.rowIteratorSlot) {
871 const iterator = this.runtime.readPointer(this.rowIteratorSlot);
872 if (iterator) this.runtime.call("ghostty_render_state_row_iterator_free", iterator);
873 }
874 if (this.renderState) this.runtime.call("ghostty_render_state_free", this.renderState);
875 if (this.terminal) {
876 if (this.ptyWriterId) this.runtime.detachPtyWriter(this.terminal, this.ptyWriterId);
877 this.runtime.call("ghostty_terminal_free", this.terminal);
878 }
879 if (this.style) this.runtime.free(this.style, this.runtime.layout("GhosttyStyle").size);
880 if (this.scrollbar) {
881 this.runtime.free(this.scrollbar, this.runtime.layout("GhosttyTerminalScrollbar").size);
882 }
883 if (this.scratch) this.runtime.free(this.scratch, 16);
884 if (this.graphemes) this.runtime.free(this.graphemes, this.graphemeCapacity);
885 for (const slot of [
886 this.mouseEventSlot,
887 this.mouseEncoderSlot,
888 this.keyEventSlot,
889 this.keyEncoderSlot,
890 this.rowCellsSlot,
891 this.rowIteratorSlot,
892 this.renderStateSlot,
893 this.terminalSlot,
894 ]) {
895 this.runtime.freeOpaque(slot);
896 }
897 }
898
899 private encodeOutput(
900 written: number,
901 encode: (output: number, outputSize: number) => number,
902 ): string {
903 const sizeResult = encode(0, 0);
904 const outputSize = this.runtime.view(written, 4).getUint32(0, true);
905 if (sizeResult === GHOSTTY_SUCCESS && outputSize === 0) return "";
906 if (sizeResult !== GHOSTTY_OUT_OF_SPACE || outputSize === 0) return "";
907
908 const output = this.runtime.alloc(outputSize);
909 const result = encode(output, outputSize);
910 const outputLength = this.runtime.view(written, 4).getUint32(0, true);
911 const encoded =
912 result === GHOSTTY_SUCCESS ? decoder.decode(this.runtime.bytes(output, outputLength)) : "";
913 this.runtime.free(output, outputSize);
914 return encoded;
915 }
916
917 private readRow(
918 iterator: number,
919 cols: number,
920 defaultForeground: GhosttyColor,
921 defaultBackground: GhosttyColor,
922 ): GhosttyRow {
923 this.assertSuccess(
924 "ghostty_render_state_row_get(raw)",
925 this.runtime.call("ghostty_render_state_row_get", iterator, ROW_DATA.raw, this.scratch),
926 );
927 const rawRow = this.runtime.view(this.scratch, 8).getBigUint64(0, true);
928 this.runtime.bytes(this.scratch + 8, 1)[0] = 0;
929 this.assertSuccess(
930 "ghostty_row_get(wrap continuation)",
931 this.runtime.call("ghostty_row_get", rawRow, 2, this.scratch + 8),
932 );
933 const isWrapContinuation = this.runtime.bytes(this.scratch + 8, 1)[0] !== 0;
934 this.runtime.bytes(this.scratch + 8, 1)[0] = 0;
935 this.assertSuccess(
936 "ghostty_row_get(wrap)",
937 this.runtime.call("ghostty_row_get", rawRow, 1, this.scratch + 8),
938 );
939 const wrapsToNext = this.runtime.bytes(this.scratch + 8, 1)[0] !== 0;
940
941 this.assertSuccess(
942 "ghostty_render_state_row_get(cells)",
943 this.runtime.call(
944 "ghostty_render_state_row_get",
945 iterator,
946 ROW_DATA.cells,
947 this.rowCellsSlot,
948 ),
949 );
950 const cellsIterator = this.runtime.readPointer(this.rowCellsSlot);
951 const { size: styleSize, fields: styleFields } = this.runtime.layout("GhosttyStyle");
952 const cells: GhosttyCell[] = [];
953 while (
954 cells.length < cols &&
955 this.runtime.call("ghostty_render_state_row_cells_next", cellsIterator) !== 0
956 ) {
957 let foreground = this.getCellColor(cellsIterator, CELL_DATA.foreground, defaultForeground);
958 let background = this.getCellColor(cellsIterator, CELL_DATA.background, defaultBackground);
959 this.runtime.bytes(this.style, styleSize).fill(0);
960 this.runtime.setField(this.style, "GhosttyStyle", "size", styleSize);
961 this.runtime.call(
962 "ghostty_render_state_row_cells_get",
963 cellsIterator,
964 CELL_DATA.style,
965 this.style,
966 );
967 const graphemeLength = this.getCellU32(cellsIterator, CELL_DATA.graphemesLength);
968 let text = "";
969 if (graphemeLength > 0) {
970 const bufferSize = graphemeLength * 4;
971 if (bufferSize > this.graphemeCapacity) {
972 const capacity = Math.max(bufferSize, this.graphemeCapacity * 2);
973 const buffer = this.runtime.alloc(capacity);
974 this.runtime.free(this.graphemes, this.graphemeCapacity);
975 this.graphemes = buffer;
976 this.graphemeCapacity = capacity;
977 }
978 if (
979 this.runtime.call(
980 "ghostty_render_state_row_cells_get",
981 cellsIterator,
982 CELL_DATA.graphemes,
983 this.graphemes,
984 ) === GHOSTTY_SUCCESS
985 ) {
986 // Read through a DataView: the byte-array allocator guarantees no
987 // 4-byte alignment, which a Uint32Array view would require.
988 const codepointView = this.runtime.view(this.graphemes, bufferSize);
989 text = ghosttyCellText(codepointView, graphemeLength);
990 }
991 }
992 let wide = 0;
993 if (text.length === 0 && cells.at(-1)?.text.length) {
994 this.assertSuccess(
995 "ghostty_render_state_row_cells_get(raw)",
996 this.runtime.call(
997 "ghostty_render_state_row_cells_get",
998 cellsIterator,
999 CELL_DATA.raw,
1000 this.scratch,
1001 ),
1002 );
1003 const rawCell = this.runtime.view(this.scratch, 8).getBigUint64(0, true);
1004 this.runtime.view(this.scratch + 8, 4).setUint32(0, 0, true);
1005 this.assertSuccess(
1006 "ghostty_cell_get(wide)",
1007 this.runtime.call("ghostty_cell_get", rawCell, RAW_CELL_DATA.wide, this.scratch + 8),
1008 );
1009 wide = this.runtime.view(this.scratch + 8, 4).getUint32(0, true);
1010 }
1011 const selected = this.getCellBool(cellsIterator, CELL_DATA.selected);
1012 // Read the style after allocation and ABI calls, which can grow WASM memory.
1013 const styleView = this.runtime.view(this.style, styleSize);
1014 if (styleView.getUint8(styleFields.inverse!.offset) !== 0) {
1015 [foreground, background] = [background, foreground];
1016 }
1017 if (styleView.getUint8(styleFields.faint!.offset) !== 0) {
1018 foreground = blend(foreground, background);
1019 }
1020 cells.push({
1021 text,
1022 wide,
1023 foreground,
1024 background,
1025 bold: styleView.getUint8(styleFields.bold!.offset) !== 0,
1026 italic: styleView.getUint8(styleFields.italic!.offset) !== 0,
1027 invisible: styleView.getUint8(styleFields.invisible!.offset) !== 0,
1028 strikethrough: styleView.getUint8(styleFields.strikethrough!.offset) !== 0,
1029 overline: styleView.getUint8(styleFields.overline!.offset) !== 0,
1030 underline: styleView.getInt32(styleFields.underline!.offset, true) !== 0,
1031 selected,
1032 });
1033 }
1034 while (cells.length < cols) cells.push(this.emptyCell(defaultForeground, defaultBackground));
1035 return {
1036 cells,
1037 text: cells
1038 .map((cell) => cell.text || " ")
1039 .join("")
1040 .trimEnd(),
1041 isWrapContinuation,
1042 wrapsToNext,
1043 };
1044 }
1045
1046 private gridRef(col: number, row: number, tag: 1 | 2 = 1): number {
1047 const pointLayout = this.runtime.layout("GhosttyPoint");
1048 const point = this.runtime.alloc(pointLayout.size);
1049 this.runtime.setField(point, "GhosttyPoint", "tag", tag);
1050 const pointValue = pointLayout.fields.value!;
1051 const valueOffset = pointValue.offset;
1052 const view = this.runtime.view(point + valueOffset, pointValue.size);
1053 view.setUint16(0, Math.max(0, col), true);
1054 view.setUint32(4, Math.max(0, row), true);
1055 const gridRefSize = this.runtime.layout("GhosttyGridRef").size;
1056 const gridRef = this.runtime.alloc(gridRefSize);
1057 this.runtime.setField(gridRef, "GhosttyGridRef", "size", gridRefSize);
1058 const result = this.runtime.call("ghostty_terminal_grid_ref", this.terminal, point, gridRef);
1059 this.runtime.free(point, pointLayout.size);
1060 if (result !== GHOSTTY_SUCCESS) {
1061 this.runtime.free(gridRef, gridRefSize);
1062 this.assertSuccess("ghostty_terminal_grid_ref", result);
1063 }
1064 return gridRef;
1065 }
1066
1067 private selectAt(
1068 optionsName: "GhosttyTerminalSelectWordOptions" | "GhosttyTerminalSelectLineOptions",
1069 operation: "ghostty_terminal_select_word" | "ghostty_terminal_select_line",
1070 col: number,
1071 row: number,
1072 ): GhosttySelectionRange | null {
1073 this.ensureActive();
1074 const optionsLayout = this.runtime.layout(optionsName);
1075 const selectionLayout = this.runtime.layout("GhosttySelection");
1076 const options = this.runtime.alloc(optionsLayout.size);
1077 let ref = 0;
1078 let selection = 0;
1079 let range: GhosttySelectionRange | null = null;
1080 try {
1081 this.runtime.setField(options, optionsName, "size", optionsLayout.size);
1082 ref = this.gridRef(col, row);
1083 const refField = optionsLayout.fields.ref!;
1084 this.runtime
1085 .bytes(options + refField.offset, refField.size)
1086 .set(this.runtime.bytes(ref, refField.size));
1087 selection = this.runtime.alloc(selectionLayout.size);
1088 this.runtime.setField(selection, "GhosttySelection", "size", selectionLayout.size);
1089 const result = this.runtime.call(operation, this.terminal, options, selection);
1090 if (result === GHOSTTY_SUCCESS) {
1091 const start = selection + selectionLayout.fields.start!.offset;
1092 const end = selection + selectionLayout.fields.end!.offset;
1093 const viewportStart = this.pointFromGridRef(start, 1);
1094 const viewportEnd = this.pointFromGridRef(end, 1);
1095 const screenStart = this.pointFromGridRef(start, 2);
1096 const screenEnd = this.pointFromGridRef(end, 2);
1097 if (viewportStart && viewportEnd && screenStart && screenEnd) {
1098 range = {
1099 viewport: { start: viewportStart, end: viewportEnd },
1100 screen: { start: screenStart, end: screenEnd },
1101 };
1102 }
1103 this.runtime.call("ghostty_terminal_set", this.terminal, 21, selection);
1104 }
1105 } finally {
1106 this.runtime.free(selection, selectionLayout.size);
1107 this.runtime.free(ref, this.runtime.layout("GhosttyGridRef").size);
1108 this.runtime.free(options, optionsLayout.size);
1109 }
1110 return range;
1111 }
1112
1113 private pointFromGridRef(ref: number, tag: 1 | 2): { x: number; y: number } | null {
1114 const coordinateLayout = this.runtime.layout("GhosttyPointCoordinate");
1115 const coordinate = this.runtime.alloc(coordinateLayout.size);
1116 const result = this.runtime.call(
1117 "ghostty_terminal_point_from_grid_ref",
1118 this.terminal,
1119 ref,
1120 tag,
1121 coordinate,
1122 );
1123 const point =
1124 result === GHOSTTY_SUCCESS
1125 ? {
1126 x: this.runtime.readField(coordinate, "GhosttyPointCoordinate", "x"),
1127 y: this.runtime.readField(coordinate, "GhosttyPointCoordinate", "y"),
1128 }
1129 : null;
1130 this.runtime.free(coordinate, coordinateLayout.size);
1131 return point;
1132 }
1133
1134 private getU16(data: number): number {
1135 this.runtime.bytes(this.scratch, 2).fill(0);
1136 this.assertSuccess(
1137 "ghostty_render_state_get",
1138 this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch),
1139 );
1140 return this.runtime.view(this.scratch, 2).getUint16(0, true);
1141 }
1142
1143 private getU32(data: number): number {
1144 this.runtime.bytes(this.scratch, 4).fill(0);
1145 this.assertSuccess(
1146 "ghostty_render_state_get",
1147 this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch),
1148 );
1149 return this.runtime.view(this.scratch, 4).getUint32(0, true);
1150 }
1151
1152 private getBool(data: number): boolean {
1153 this.runtime.bytes(this.scratch, 1)[0] = 0;
1154 this.assertSuccess(
1155 "ghostty_render_state_get",
1156 this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch),
1157 );
1158 return this.runtime.bytes(this.scratch, 1)[0] !== 0;
1159 }
1160
1161 private getColor(data: number, fallback: GhosttyColor): GhosttyColor {
1162 this.runtime.bytes(this.scratch, 3).fill(0);
1163 const result = this.runtime.call(
1164 "ghostty_render_state_get",
1165 this.renderState,
1166 data,
1167 this.scratch,
1168 );
1169 return result === GHOSTTY_SUCCESS ? this.readColor(this.scratch) : fallback;
1170 }
1171
1172 private getRowBool(iterator: number, data: number): boolean {
1173 this.runtime.bytes(this.scratch, 1)[0] = 0;
1174 return (
1175 this.runtime.call("ghostty_render_state_row_get", iterator, data, this.scratch) ===
1176 GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
1177 );
1178 }
1179
1180 private getCellU32(iterator: number, data: number): number {
1181 this.runtime.bytes(this.scratch, 4).fill(0);
1182 const result = this.runtime.call(
1183 "ghostty_render_state_row_cells_get",
1184 iterator,
1185 data,
1186 this.scratch,
1187 );
1188 return result === GHOSTTY_SUCCESS ? this.runtime.view(this.scratch, 4).getUint32(0, true) : 0;
1189 }
1190
1191 private getCellBool(iterator: number, data: number): boolean {
1192 this.runtime.bytes(this.scratch, 1)[0] = 0;
1193 return (
1194 this.runtime.call("ghostty_render_state_row_cells_get", iterator, data, this.scratch) ===
1195 GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
1196 );
1197 }
1198
1199 private getCellColor(iterator: number, data: number, fallback: GhosttyColor): GhosttyColor {
1200 this.runtime.bytes(this.scratch, 3).fill(0);
1201 const result = this.runtime.call(
1202 "ghostty_render_state_row_cells_get",
1203 iterator,
1204 data,
1205 this.scratch,
1206 );
1207 return result === GHOSTTY_SUCCESS ? this.readColor(this.scratch) : fallback;
1208 }
1209
1210 private readColor(pointer: number): GhosttyColor {
1211 const bytes = this.runtime.bytes(pointer, 3);
1212 return { r: bytes[0] ?? 0, g: bytes[1] ?? 0, b: bytes[2] ?? 0 };
1213 }
1214
1215 private emptyCell(foreground: GhosttyColor, background: GhosttyColor): GhosttyCell {
1216 return {
1217 text: "",
1218 wide: 0,
1219 foreground,
1220 background,
1221 bold: false,
1222 italic: false,
1223 invisible: false,
1224 strikethrough: false,
1225 overline: false,
1226 underline: false,
1227 selected: false,
1228 };
1229 }
1230
1231 private assertSuccess(operation: string, result: number): void {
1232 if (result !== GHOSTTY_SUCCESS) throw new Error(`${operation} failed with result ${result}`);
1233 }
1234
1235 private ensureActive(): void {
1236 if (this.disposed) throw new Error("libghostty-vt terminal has been disposed");
1237 }
1238}
1239
1240export function ghosttyColorsEqual(left: GhosttyColor, right: GhosttyColor): boolean {
1241 return sameColor(left, right);
1242}