Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

core.ts

1,324 lines47.5 KB

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