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

core.ts

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