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

core.ts

1,303 lines46.4 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 selectWord(col: number, row: number): GhosttySelectionRange | null {
740 return this.selectAt(
741 "GhosttyTerminalSelectWordOptions",
742 "ghostty_terminal_select_word",
743 col,
744 row,
745 );
746 }
747​
748 selectLine(col: number, row: number): GhosttySelectionRange | null {
749 return this.selectAt(
750 "GhosttyTerminalSelectLineOptions",
751 "ghostty_terminal_select_line",
752 col,
753 row,
754 );
755 }
756​
757 hyperlinkAt(col: number, row: number): string | null {
758 this.ensureActive();
759 const ref = this.gridRef(col, row);
760 const written = this.runtime.call("ghostty_wasm_alloc_usize");
761 const sizeResult = this.runtime.call("ghostty_grid_ref_hyperlink_uri", ref, 0, 0, written);
762 const outputSize = this.runtime.view(written, 4).getUint32(0, true);
763 let hyperlink: string | null = null;
764 if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
765 const output = this.runtime.alloc(outputSize);
766 const result = this.runtime.call(
767 "ghostty_grid_ref_hyperlink_uri",
768 ref,
769 output,
770 outputSize,
771 written,
772 );
773 const outputLength = this.runtime.view(written, 4).getUint32(0, true);
774 if (result === GHOSTTY_SUCCESS && outputLength > 0) {
775 hyperlink = decoder.decode(this.runtime.bytes(output, outputLength));
776 }
777 this.runtime.free(output, outputSize);
778 }
779 this.runtime.call("ghostty_wasm_free_usize", written);
780 this.runtime.free(ref, this.runtime.layout("GhosttyGridRef").size);
781 return hyperlink;
782 }
783​
784 clearSelection(): void {
785 this.ensureActive();
786 this.runtime.call("ghostty_terminal_set", this.terminal, 21, 0);
787 }
788​
789 snapshot(): GhosttySnapshot {
790 this.ensureActive();
791 this.assertSuccess(
792 "ghostty_render_state_update",
793 this.runtime.call("ghostty_render_state_update", this.renderState, this.terminal),
794 );
795 const cols = this.getU16(RENDER_DATA.cols);
796 const rowCount = this.getU16(RENDER_DATA.rows);
797 const dirty = this.getU32(RENDER_DATA.dirty);
798 const foreground = this.getColor(RENDER_DATA.foreground, { r: 229, g: 231, b: 235 });
799 const background = this.getColor(RENDER_DATA.background, { r: 0, g: 0, b: 0 });
800 const cursorHasValue = this.getBool(RENDER_DATA.cursorHasValue);
801 const cursor = cursorHasValue ? this.getColor(RENDER_DATA.cursor, foreground) : foreground;
802 const cursorInViewport = this.getBool(RENDER_DATA.cursorInViewport);
803 const cursorVisible = this.getBool(RENDER_DATA.cursorVisible) && cursorInViewport;
804 const cursorX = cursorInViewport ? this.getU16(RENDER_DATA.cursorX) : -1;
805 const cursorY = cursorInViewport ? this.getU16(RENDER_DATA.cursorY) : -1;
806​
807 if (this.rows.length !== rowCount || this.rows.some((row) => row.cells.length !== cols)) {
808 this.rows = Array.from({ length: rowCount }, () => ({
809 cells: Array.from({ length: cols }, () => this.emptyCell(foreground, background)),
810 text: "",
811 isWrapContinuation: false,
812 wrapsToNext: false,
813 }));
814 }
815​
816 const dirtyRows = new Set<number>();
817 if (dirty !== 0) {
818 this.assertSuccess(
819 "ghostty_render_state_get(row iterator)",
820 this.runtime.call(
821 "ghostty_render_state_get",
822 this.renderState,
823 RENDER_DATA.rowIterator,
824 this.rowIteratorSlot,
825 ),
826 );
827 const iterator = this.runtime.readPointer(this.rowIteratorSlot);
828 let rowIndex = 0;
829 while (
830 rowIndex < rowCount &&
831 this.runtime.call("ghostty_render_state_row_iterator_next", iterator) !== 0
832 ) {
833 const rowDirty = dirty === 2 || this.getRowBool(iterator, ROW_DATA.dirty);
834 if (rowDirty) {
835 this.rows[rowIndex] = this.readRow(iterator, cols, foreground, background);
836 dirtyRows.add(rowIndex);
837 this.runtime.bytes(this.scratch, 1)[0] = 0;
838 this.runtime.call("ghostty_render_state_row_set", iterator, 0, this.scratch);
839 }
840 rowIndex += 1;
841 }
842 this.runtime.view(this.scratch, 4).setUint32(0, 0, true);
843 this.runtime.call("ghostty_render_state_set", this.renderState, 0, this.scratch);
844 }
845​
846 return {
847 cols,
848 rows: rowCount,
849 foreground,
850 background,
851 cursor,
852 cursorX,
853 cursorY,
854 cursorVisible,
855 cursorBlinking: this.getBool(RENDER_DATA.cursorBlinking),
856 cursorStyle: this.getU32(RENDER_DATA.cursorStyle),
857 dirtyRows,
858 rowData: this.rows,
859 };
860 }
861​
862 selectionText(): string {
863 this.ensureActive();
864 const options = this.runtime.alloc(SELECTION_FORMAT_OPTIONS_SIZE);
865 const optionsView = this.runtime.view(options, SELECTION_FORMAT_OPTIONS_SIZE);
866 optionsView.setUint32(0, SELECTION_FORMAT_OPTIONS_SIZE, true);
867 optionsView.setUint32(4, 0, true);
868 optionsView.setUint8(8, 1);
869 optionsView.setUint8(9, 1);
870 optionsView.setUint32(12, 0, true);
871 const written = this.runtime.call("ghostty_wasm_alloc_usize");
872 const sizeResult = this.runtime.call(
873 "ghostty_terminal_selection_format_buf",
874 this.terminal,
875 options,
876 0,
877 0,
878 written,
879 );
880 const outputSize = this.runtime.view(written, 4).getUint32(0, true);
881 let text = "";
882 if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
883 const output = this.runtime.alloc(outputSize);
884 const result = this.runtime.call(
885 "ghostty_terminal_selection_format_buf",
886 this.terminal,
887 options,
888 output,
889 outputSize,
890 written,
891 );
892 const outputLength = this.runtime.view(written, 4).getUint32(0, true);
893 if (result === GHOSTTY_SUCCESS) {
894 text = decoder.decode(this.runtime.bytes(output, outputLength));
895 }
896 this.runtime.free(output, outputSize);
897 }
898 this.runtime.call("ghostty_wasm_free_usize", written);
899 this.runtime.free(options, SELECTION_FORMAT_OPTIONS_SIZE);
900 return text;
901 }
902​
903 viewportPointToScreen(col: number, row: number): { x: number; y: number } | null {
904 return this.convertPoint(col, row, 1, 2);
905 }
906​
907 screenPointToViewport(col: number, row: number): { x: number; y: number } | null {
908 return this.convertPoint(col, row, 2, 1);
909 }
910​
911 private convertPoint(
912 col: number,
913 row: number,
914 fromTag: 1 | 2,
915 toTag: 1 | 2,
916 ): { x: number; y: number } | null {
917 this.ensureActive();
918 const ref = this.gridRef(col, row, fromTag);
919 const point = this.pointFromGridRef(ref, toTag);
920 this.runtime.free(ref, this.runtime.layout("GhosttyGridRef").size);
921 return point;
922 }
923​
924 dispose(): void {
925 if (this.disposed) return;
926 this.disposed = true;
927 if (this.mouseEvent) this.runtime.call("ghostty_mouse_event_free", this.mouseEvent);
928 if (this.mouseEncoder) this.runtime.call("ghostty_mouse_encoder_free", this.mouseEncoder);
929 if (this.keyEvent) this.runtime.call("ghostty_key_event_free", this.keyEvent);
930 if (this.keyEncoder) this.runtime.call("ghostty_key_encoder_free", this.keyEncoder);
931 if (this.rowCellsSlot) {
932 const cells = this.runtime.readPointer(this.rowCellsSlot);
933 if (cells) this.runtime.call("ghostty_render_state_row_cells_free", cells);
934 }
935 if (this.rowIteratorSlot) {
936 const iterator = this.runtime.readPointer(this.rowIteratorSlot);
937 if (iterator) this.runtime.call("ghostty_render_state_row_iterator_free", iterator);
938 }
939 if (this.renderState) this.runtime.call("ghostty_render_state_free", this.renderState);
940 if (this.terminal) {
941 if (this.ptyWriterId) this.runtime.detachPtyWriter(this.terminal, this.ptyWriterId);
942 this.runtime.call("ghostty_terminal_free", this.terminal);
943 }
944 if (this.style) this.runtime.free(this.style, this.runtime.layout("GhosttyStyle").size);
945 if (this.cellQuery) this.runtime.free(this.cellQuery, CELL_QUERY.size);
946 if (this.scrollbar) {
947 this.runtime.free(this.scrollbar, this.runtime.layout("GhosttyTerminalScrollbar").size);
948 }
949 if (this.scratch) this.runtime.free(this.scratch, 16);
950 if (this.graphemes) this.runtime.free(this.graphemes, this.graphemeCapacity);
951 for (const slot of [
952 this.mouseEventSlot,
953 this.mouseEncoderSlot,
954 this.keyEventSlot,
955 this.keyEncoderSlot,
956 this.rowCellsSlot,
957 this.rowIteratorSlot,
958 this.renderStateSlot,
959 this.terminalSlot,
960 ]) {
961 this.runtime.freeOpaque(slot);
962 }
963 }
964​
965 private encodeOutput(
966 written: number,
967 encode: (output: number, outputSize: number) => number,
968 ): string {
969 const sizeResult = encode(0, 0);
970 const outputSize = this.runtime.view(written, 4).getUint32(0, true);
971 if (sizeResult === GHOSTTY_SUCCESS && outputSize === 0) return "";
972 if (sizeResult !== GHOSTTY_OUT_OF_SPACE || outputSize === 0) return "";
973​
974 const output = this.runtime.alloc(outputSize);
975 const result = encode(output, outputSize);
976 const outputLength = this.runtime.view(written, 4).getUint32(0, true);
977 const encoded =
978 result === GHOSTTY_SUCCESS ? decoder.decode(this.runtime.bytes(output, outputLength)) : "";
979 this.runtime.free(output, outputSize);
980 return encoded;
981 }
982​
983 private readRow(
984 iterator: number,
985 cols: number,
986 defaultForeground: GhosttyColor,
987 defaultBackground: GhosttyColor,
988 ): GhosttyRow {
989 this.assertSuccess(
990 "ghostty_render_state_row_get(raw)",
991 this.runtime.call("ghostty_render_state_row_get", iterator, ROW_DATA.raw, this.scratch),
992 );
993 const rawRow = this.runtime.view(this.scratch, 8).getBigUint64(0, true);
994 this.runtime.bytes(this.scratch + 8, 1)[0] = 0;
995 this.assertSuccess(
996 "ghostty_row_get(wrap continuation)",
997 this.runtime.call("ghostty_row_get", rawRow, 2, this.scratch + 8),
998 );
999 const isWrapContinuation = this.runtime.bytes(this.scratch + 8, 1)[0] !== 0;
1000 this.runtime.bytes(this.scratch + 8, 1)[0] = 0;
1001 this.assertSuccess(
1002 "ghostty_row_get(wrap)",
1003 this.runtime.call("ghostty_row_get", rawRow, 1, this.scratch + 8),
1004 );
1005 const wrapsToNext = this.runtime.bytes(this.scratch + 8, 1)[0] !== 0;
1006​
1007 this.assertSuccess(
1008 "ghostty_render_state_row_get(cells)",
1009 this.runtime.call(
1010 "ghostty_render_state_row_get",
1011 iterator,
1012 ROW_DATA.cells,
1013 this.rowCellsSlot,
1014 ),
1015 );
1016 const cellsIterator = this.runtime.readPointer(this.rowCellsSlot);
1017 const { size: styleSize, fields: styleFields } = this.runtime.layout("GhosttyStyle");
1018 const cells: GhosttyCell[] = [];
1019 while (
1020 cells.length < cols &&
1021 this.runtime.call("ghostty_render_state_row_cells_next", cellsIterator) !== 0
1022 ) {
1023 this.runtime.bytes(this.style, styleSize).fill(0);
1024 this.runtime.setField(this.style, "GhosttyStyle", "size", styleSize);
1025 const result = this.runtime.call(
1026 "ghostty_render_state_row_cells_get_multi",
1027 cellsIterator,
1028 5,
1029 this.cellQuery + CELL_QUERY.keys,
1030 this.cellQuery + CELL_QUERY.values,
1031 this.cellQuery + CELL_QUERY.written,
1032 );
1033 const queryView = this.runtime.memoryDataView();
1034 const written = queryView.getUint32(this.cellQuery + CELL_QUERY.written, true);
1035 if (written < 3) this.assertSuccess("ghostty_render_state_row_cells_get_multi", result);
1036 const graphemeLength = queryView.getUint32(this.cellQuery + CELL_QUERY.graphemesLength, true);
1037 const selected = queryView.getUint8(this.cellQuery + CELL_QUERY.selected) !== 0;
1038 let background =
1039 written >= 4 ? this.readColor(this.cellQuery + CELL_QUERY.background) : defaultBackground;
1040 let foreground =
1041 written === 5
1042 ? this.readColor(this.cellQuery + CELL_QUERY.foreground)
1043 : written === 3
1044 ? this.getCellColor(cellsIterator, CELL_DATA.foreground, defaultForeground)
1045 : defaultForeground;
1046 let text = "";
1047 if (graphemeLength > 0) {
1048 const bufferSize = graphemeLength * 4;
1049 if (bufferSize > this.graphemeCapacity) {
1050 const capacity = Math.max(bufferSize, this.graphemeCapacity * 2);
1051 const buffer = this.runtime.alloc(capacity);
1052 this.runtime.free(this.graphemes, this.graphemeCapacity);
1053 this.graphemes = buffer;
1054 this.graphemeCapacity = capacity;
1056 if (
1057 this.runtime.call(
1058 "ghostty_render_state_row_cells_get",
1059 cellsIterator,
1060 CELL_DATA.graphemes,
1061 this.graphemes,
1062 ) === GHOSTTY_SUCCESS
1063 ) {
1064 // Byte allocations need not be 4-byte aligned; use DataView instead of Uint32Array.
1065 const codepointView = this.runtime.view(this.graphemes, bufferSize);
1066 text = ghosttyCellText(codepointView, graphemeLength);
1069 let wide = 0;
1070 if (text.length === 0 && cells.at(-1)?.text.length) {
1071 this.assertSuccess(
1072 "ghostty_render_state_row_cells_get(raw)",
1073 this.runtime.call(
1074 "ghostty_render_state_row_cells_get",
1075 cellsIterator,
1076 CELL_DATA.raw,
1077 this.scratch,
1078 ),
1079 );
1080 const rawCell = this.runtime.view(this.scratch, 8).getBigUint64(0, true);
1081 this.runtime.view(this.scratch + 8, 4).setUint32(0, 0, true);
1082 this.assertSuccess(
1083 "ghostty_cell_get(wide)",
1084 this.runtime.call("ghostty_cell_get", rawCell, RAW_CELL_DATA.wide, this.scratch + 8),
1085 );
1086 wide = this.runtime.view(this.scratch + 8, 4).getUint32(0, true);
1088 // Read the style after allocation and ABI calls, which can grow WASM memory.
1089 const styleView = this.runtime.memoryDataView();
1090 if (styleView.getUint8(this.style + styleFields.inverse!.offset) !== 0) {
1091 [foreground, background] = [background, foreground];
1093 if (styleView.getUint8(this.style + styleFields.faint!.offset) !== 0) {
1094 foreground = blend(foreground, background);
1096 cells.push({
1097 text,
1098 wide,
1099 foreground,
1100 background,
1101 bold: styleView.getUint8(this.style + styleFields.bold!.offset) !== 0,
1102 italic: styleView.getUint8(this.style + styleFields.italic!.offset) !== 0,
1103 invisible: styleView.getUint8(this.style + styleFields.invisible!.offset) !== 0,
1104 strikethrough: styleView.getUint8(this.style + styleFields.strikethrough!.offset) !== 0,
1105 overline: styleView.getUint8(this.style + styleFields.overline!.offset) !== 0,
1106 underline: styleView.getInt32(this.style + styleFields.underline!.offset, true) !== 0,
1107 selected,
1108 });
1110 while (cells.length < cols) cells.push(this.emptyCell(defaultForeground, defaultBackground));
1111 return {
1112 cells,
1113 text: cells
1114 .map((cell) => cell.text || " ")
1115 .join("")
1116 .trimEnd(),
1117 isWrapContinuation,
1118 wrapsToNext,
1119 };
1121​
1122 private gridRef(col: number, row: number, tag: 1 | 2 = 1): number {
1123 const pointLayout = this.runtime.layout("GhosttyPoint");
1124 const point = this.runtime.alloc(pointLayout.size);
1125 this.runtime.setField(point, "GhosttyPoint", "tag", tag);
1126 const pointValue = pointLayout.fields.value!;
1127 const valueOffset = pointValue.offset;
1128 const view = this.runtime.view(point + valueOffset, pointValue.size);
1129 view.setUint16(0, Math.max(0, col), true);
1130 view.setUint32(4, Math.max(0, row), true);
1131 const gridRefSize = this.runtime.layout("GhosttyGridRef").size;
1132 const gridRef = this.runtime.alloc(gridRefSize);
1133 this.runtime.setField(gridRef, "GhosttyGridRef", "size", gridRefSize);
1134 const result = this.runtime.call("ghostty_terminal_grid_ref", this.terminal, point, gridRef);
1135 this.runtime.free(point, pointLayout.size);
1136 if (result !== GHOSTTY_SUCCESS) {
1137 this.runtime.free(gridRef, gridRefSize);
1138 this.assertSuccess("ghostty_terminal_grid_ref", result);
1140 return gridRef;
1142​
1143 private selectAt(
1144 optionsName: "GhosttyTerminalSelectWordOptions" | "GhosttyTerminalSelectLineOptions",
1145 operation: "ghostty_terminal_select_word" | "ghostty_terminal_select_line",
1146 col: number,
1147 row: number,
1148 ): GhosttySelectionRange | null {
1149 this.ensureActive();
1150 const optionsLayout = this.runtime.layout(optionsName);
1151 const selectionLayout = this.runtime.layout("GhosttySelection");
1152 const options = this.runtime.alloc(optionsLayout.size);
1153 let ref = 0;
1154 let selection = 0;
1155 let range: GhosttySelectionRange | null = null;
1156 try {
1157 this.runtime.setField(options, optionsName, "size", optionsLayout.size);
1158 ref = this.gridRef(col, row);
1159 const refField = optionsLayout.fields.ref!;
1160 this.runtime
1161 .bytes(options + refField.offset, refField.size)
1162 .set(this.runtime.bytes(ref, refField.size));
1163 selection = this.runtime.alloc(selectionLayout.size);
1164 this.runtime.setField(selection, "GhosttySelection", "size", selectionLayout.size);
1165 const result = this.runtime.call(operation, this.terminal, options, selection);
1166 if (result === GHOSTTY_SUCCESS) {
1167 const start = selection + selectionLayout.fields.start!.offset;
1168 const end = selection + selectionLayout.fields.end!.offset;
1169 const viewportStart = this.pointFromGridRef(start, 1);
1170 const viewportEnd = this.pointFromGridRef(end, 1);
1171 const screenStart = this.pointFromGridRef(start, 2);
1172 const screenEnd = this.pointFromGridRef(end, 2);
1173 if (viewportStart && viewportEnd && screenStart && screenEnd) {
1174 range = {
1175 viewport: { start: viewportStart, end: viewportEnd },
1176 screen: { start: screenStart, end: screenEnd },
1177 };
1179 this.runtime.call("ghostty_terminal_set", this.terminal, 21, selection);
1181 } finally {
1182 this.runtime.free(selection, selectionLayout.size);
1183 this.runtime.free(ref, this.runtime.layout("GhosttyGridRef").size);
1184 this.runtime.free(options, optionsLayout.size);
1186 return range;
1188​
1189 private pointFromGridRef(ref: number, tag: 1 | 2): { x: number; y: number } | null {
1190 const coordinateLayout = this.runtime.layout("GhosttyPointCoordinate");
1191 const coordinate = this.runtime.alloc(coordinateLayout.size);
1192 const result = this.runtime.call(
1193 "ghostty_terminal_point_from_grid_ref",
1194 this.terminal,
1195 ref,
1196 tag,
1197 coordinate,
1198 );
1199 const point =
1200 result === GHOSTTY_SUCCESS
1201 ? {
1202 x: this.runtime.readField(coordinate, "GhosttyPointCoordinate", "x"),
1203 y: this.runtime.readField(coordinate, "GhosttyPointCoordinate", "y"),
1205 : null;
1206 this.runtime.free(coordinate, coordinateLayout.size);
1207 return point;
1209​
1210 private getU16(data: number): number {
1211 this.runtime.bytes(this.scratch, 2).fill(0);
1212 this.assertSuccess(
1213 "ghostty_render_state_get",
1214 this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch),
1215 );
1216 return this.runtime.view(this.scratch, 2).getUint16(0, true);
1218​
1219 private getU32(data: number): number {
1220 this.runtime.bytes(this.scratch, 4).fill(0);
1221 this.assertSuccess(
1222 "ghostty_render_state_get",
1223 this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch),
1224 );
1225 return this.runtime.view(this.scratch, 4).getUint32(0, true);
1227​
1228 private getBool(data: number): boolean {
1229 this.runtime.bytes(this.scratch, 1)[0] = 0;
1230 this.assertSuccess(
1231 "ghostty_render_state_get",
1232 this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch),
1233 );
1234 return this.runtime.bytes(this.scratch, 1)[0] !== 0;
1236​
1237 private getColor(data: number, fallback: GhosttyColor): GhosttyColor {
1238 this.runtime.bytes(this.scratch, 3).fill(0);
1239 const result = this.runtime.call(
1240 "ghostty_render_state_get",
1241 this.renderState,
1242 data,
1243 this.scratch,
1244 );
1245 return result === GHOSTTY_SUCCESS ? this.readColor(this.scratch) : fallback;
1247​
1248 private getRowBool(iterator: number, data: number): boolean {
1249 this.runtime.bytes(this.scratch, 1)[0] = 0;
1250 return (
1251 this.runtime.call("ghostty_render_state_row_get", iterator, data, this.scratch) ===
1252 GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
1253 );
1255​
1256 private getCellColor(iterator: number, data: number, fallback: GhosttyColor): GhosttyColor {
1257 this.runtime.bytes(this.scratch, 3).fill(0);
1258 const result = this.runtime.call(
1259 "ghostty_render_state_row_cells_get",
1260 iterator,
1261 data,
1262 this.scratch,
1263 );
1264 return result === GHOSTTY_SUCCESS ? this.readColor(this.scratch) : fallback;
1266​
1267 private readColor(pointer: number): GhosttyColor {
1268 const view = this.runtime.memoryDataView();
1269 return {
1270 r: view.getUint8(pointer),
1271 g: view.getUint8(pointer + 1),
1272 b: view.getUint8(pointer + 2),
1273 };
1275​
1276 private emptyCell(foreground: GhosttyColor, background: GhosttyColor): GhosttyCell {
1277 return {
1278 text: "",
1279 wide: 0,
1280 foreground,
1281 background,
1282 bold: false,
1283 italic: false,
1284 invisible: false,
1285 strikethrough: false,
1286 overline: false,
1287 underline: false,
1288 selected: false,
1289 };
1291​
1292 private assertSuccess(operation: string, result: number): void {
1293 if (result !== GHOSTTY_SUCCESS) throw new Error(`${operation} failed with result ${result}`);
1295​
1296 private ensureActive(): void {
1297 if (this.disposed) throw new Error("libghostty-vt terminal has been disposed");
1300​
1301export function ghosttyColorsEqual(left: GhosttyColor, right: GhosttyColor): boolean {
1302 return sameColor(left, right);