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

core.ts

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