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