-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathghostty.ts
More file actions
886 lines (759 loc) · 28.4 KB
/
ghostty.ts
File metadata and controls
886 lines (759 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
/**
* TypeScript wrapper for libghostty-vt WASM API
*
* High-performance terminal emulation using Ghostty's battle-tested VT100 parser.
* The key optimization is the RenderState API which provides a pre-computed
* snapshot of all render data in a single update call.
*/
import {
CellFlags,
type Cursor,
DirtyState,
GHOSTTY_CONFIG_SIZE,
type GhosttyCell,
type GhosttyTerminalConfig,
type GhosttyWasmExports,
KeyEncoderOption,
type KeyEvent,
type KittyKeyFlags,
type RGB,
type RenderStateColors,
type RenderStateCursor,
type TerminalHandle,
} from './types';
// Re-export types for convenience
export {
CellFlags,
type Cursor,
DirtyState,
type GhosttyCell,
type GhosttyTerminalConfig,
KeyEncoderOption,
type RenderStateColors,
type RenderStateCursor,
type RGB,
};
/**
* Main Ghostty WASM wrapper class
*/
export class Ghostty {
private exports: GhosttyWasmExports;
private memory: WebAssembly.Memory;
constructor(wasmInstance: WebAssembly.Instance) {
this.exports = wasmInstance.exports as GhosttyWasmExports;
this.memory = this.exports.memory;
}
createKeyEncoder(): KeyEncoder {
return new KeyEncoder(this.exports);
}
createTerminal(
cols: number = 80,
rows: number = 24,
config?: GhosttyTerminalConfig,
): GhosttyTerminal {
return new GhosttyTerminal(this.exports, this.memory, cols, rows, config);
}
static async load(wasmPath?: string): Promise<Ghostty> {
// If explicit path provided, use it
if (wasmPath) {
return Ghostty.loadFromPath(wasmPath);
}
// Resolve path relative to this module
const moduleUrl = new URL('../ghostty-vt.wasm', import.meta.url);
// Build paths to try, prioritizing file system paths for Node/Bun
const defaultPaths: string[] = [];
// For Node/Bun: try absolute file path first (strip file:// protocol)
if (moduleUrl.protocol === 'file:') {
let filePath = moduleUrl.pathname;
// Remove leading slash on Windows paths (e.g., /C:/ -> C:/)
if (filePath.match(/^\/[A-Za-z]:\//)) {
filePath = filePath.slice(1);
}
defaultPaths.push(filePath);
}
// Also try other common paths
defaultPaths.push(moduleUrl.href, './ghostty-vt.wasm', '/ghostty-vt.wasm');
let lastError: Error | null = null;
for (const path of defaultPaths) {
try {
return await Ghostty.loadFromPath(path);
} catch (e) {
lastError = e instanceof Error ? e : new Error(String(e));
}
}
throw lastError || new Error('Failed to load Ghostty WASM');
}
private static async loadFromPath(path: string): Promise<Ghostty> {
let wasmBytes: ArrayBuffer | undefined;
// Try Bun.file first (for Bun environments)
if (typeof Bun !== 'undefined' && typeof Bun.file === 'function') {
try {
const file = Bun.file(path);
if (await file.exists()) {
wasmBytes = await file.arrayBuffer();
}
} catch {
// Bun.file failed, try next method
}
}
// Try Node.js fs module if Bun.file didn't work
if (!wasmBytes) {
try {
const fs = await import('fs/promises');
const buffer = await fs.readFile(path);
wasmBytes = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
} catch {
// fs failed, try fetch
}
}
// Fall back to fetch (for browser environments)
if (!wasmBytes) {
const response = await fetch(path);
if (!response.ok) {
throw new Error(`Failed to fetch WASM: ${response.status} ${response.statusText}`);
}
wasmBytes = await response.arrayBuffer();
if (wasmBytes.byteLength === 0) {
throw new Error(`WASM file is empty (0 bytes). Check path: ${path}`);
}
}
if (!wasmBytes) {
throw new Error(`Could not load WASM from path: ${path}`);
}
const wasmModule = await WebAssembly.compile(wasmBytes);
const wasmInstance = await WebAssembly.instantiate(wasmModule, {
env: {
log: (ptr: number, len: number) => {
const bytes = new Uint8Array(
(wasmInstance.exports as GhosttyWasmExports).memory.buffer,
ptr,
len,
);
console.log('[ghostty-vt]', new TextDecoder().decode(bytes));
},
},
});
return new Ghostty(wasmInstance);
}
}
/**
* Key Encoder - converts keyboard events into terminal escape sequences
*/
export class KeyEncoder {
private exports: GhosttyWasmExports;
private encoder: number = 0;
constructor(exports: GhosttyWasmExports) {
this.exports = exports;
const encoderPtrPtr = this.exports.ghostty_wasm_alloc_opaque();
const result = this.exports.ghostty_key_encoder_new(0, encoderPtrPtr);
if (result !== 0) throw new Error(`Failed to create key encoder: ${result}`);
const view = new DataView(this.exports.memory.buffer);
this.encoder = view.getUint32(encoderPtrPtr, true);
this.exports.ghostty_wasm_free_opaque(encoderPtrPtr);
}
setOption(option: KeyEncoderOption, value: boolean | number): void {
const valuePtr = this.exports.ghostty_wasm_alloc_u8();
const view = new DataView(this.exports.memory.buffer);
view.setUint8(valuePtr, typeof value === 'boolean' ? (value ? 1 : 0) : value);
this.exports.ghostty_key_encoder_setopt(this.encoder, option, valuePtr);
this.exports.ghostty_wasm_free_u8(valuePtr);
}
setKittyFlags(flags: KittyKeyFlags): void {
this.setOption(KeyEncoderOption.KITTY_KEYBOARD_FLAGS, flags);
}
encode(event: KeyEvent): Uint8Array {
const eventPtrPtr = this.exports.ghostty_wasm_alloc_opaque();
const createResult = this.exports.ghostty_key_event_new(0, eventPtrPtr);
if (createResult !== 0) throw new Error(`Failed to create key event: ${createResult}`);
const view = new DataView(this.exports.memory.buffer);
const eventPtr = view.getUint32(eventPtrPtr, true);
this.exports.ghostty_wasm_free_opaque(eventPtrPtr);
this.exports.ghostty_key_event_set_action(eventPtr, event.action);
this.exports.ghostty_key_event_set_key(eventPtr, event.key);
this.exports.ghostty_key_event_set_mods(eventPtr, event.mods);
if (event.utf8) {
const encoder = new TextEncoder();
const utf8Bytes = encoder.encode(event.utf8);
const utf8Ptr = this.exports.ghostty_wasm_alloc_u8_array(utf8Bytes.length);
new Uint8Array(this.exports.memory.buffer).set(utf8Bytes, utf8Ptr);
this.exports.ghostty_key_event_set_utf8(eventPtr, utf8Ptr, utf8Bytes.length);
this.exports.ghostty_wasm_free_u8_array(utf8Ptr, utf8Bytes.length);
}
const bufferSize = 32;
const bufPtr = this.exports.ghostty_wasm_alloc_u8_array(bufferSize);
const writtenPtr = this.exports.ghostty_wasm_alloc_usize();
const encodeResult = this.exports.ghostty_key_encoder_encode(
this.encoder,
eventPtr,
bufPtr,
bufferSize,
writtenPtr,
);
if (encodeResult !== 0) {
this.exports.ghostty_wasm_free_u8_array(bufPtr, bufferSize);
this.exports.ghostty_wasm_free_usize(writtenPtr);
this.exports.ghostty_key_event_free(eventPtr);
throw new Error(`Failed to encode key: ${encodeResult}`);
}
const bytesWritten = view.getUint32(writtenPtr, true);
const encoded = new Uint8Array(this.exports.memory.buffer, bufPtr, bytesWritten).slice();
this.exports.ghostty_wasm_free_u8_array(bufPtr, bufferSize);
this.exports.ghostty_wasm_free_usize(writtenPtr);
this.exports.ghostty_key_event_free(eventPtr);
return encoded;
}
dispose(): void {
if (this.encoder) {
this.exports.ghostty_key_encoder_free(this.encoder);
this.encoder = 0;
}
}
}
/**
* GhosttyTerminal - High-performance terminal emulator
*
* Uses Ghostty's native RenderState for optimal performance:
* - ONE call to update all state (renderStateUpdate)
* - ONE call to get all cells (getViewport)
* - No per-row WASM boundary crossings!
*/
export class GhosttyTerminal {
private exports: GhosttyWasmExports;
private memory: WebAssembly.Memory;
private handle: TerminalHandle;
private _cols: number;
private _rows: number;
/** Size of GhosttyCell in WASM (16 bytes) */
private static readonly CELL_SIZE = 16;
/** Reusable buffer for viewport operations */
private viewportBufferPtr: number = 0;
private viewportBufferSize: number = 0;
/** Cell pool for zero-allocation rendering */
private cellPool: GhosttyCell[] = [];
constructor(
exports: GhosttyWasmExports,
memory: WebAssembly.Memory,
cols: number = 80,
rows: number = 24,
config?: GhosttyTerminalConfig,
) {
this.exports = exports;
this.memory = memory;
this._cols = cols;
this._rows = rows;
if (config) {
// Allocate config struct in WASM memory
const configPtr = this.exports.ghostty_wasm_alloc_u8_array(GHOSTTY_CONFIG_SIZE);
if (configPtr === 0) {
throw new Error('Failed to allocate config (out of memory)');
}
try {
// Write config to WASM memory
const view = new DataView(this.memory.buffer);
let offset = configPtr;
// scrollback_limit (u32)
view.setUint32(offset, config.scrollbackLimit ?? 10000, true);
offset += 4;
// fg_color (u32)
view.setUint32(offset, config.fgColor ?? 0, true);
offset += 4;
// bg_color (u32)
view.setUint32(offset, config.bgColor ?? 0, true);
offset += 4;
// cursor_color (u32)
view.setUint32(offset, config.cursorColor ?? 0, true);
offset += 4;
// palette[16] (u32 * 16)
for (let i = 0; i < 16; i++) {
view.setUint32(offset, config.palette?.[i] ?? 0, true);
offset += 4;
}
this.handle = this.exports.ghostty_terminal_new_with_config(cols, rows, configPtr);
} finally {
// Free the config memory
this.exports.ghostty_wasm_free_u8_array(configPtr, GHOSTTY_CONFIG_SIZE);
}
} else {
this.handle = this.exports.ghostty_terminal_new(cols, rows);
}
if (!this.handle) throw new Error('Failed to create terminal');
this.initCellPool();
}
get cols(): number {
return this._cols;
}
get rows(): number {
return this._rows;
}
// ==========================================================================
// Lifecycle
// ==========================================================================
write(data: string | Uint8Array): void {
const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
const ptr = this.exports.ghostty_wasm_alloc_u8_array(bytes.length);
new Uint8Array(this.memory.buffer).set(bytes, ptr);
this.exports.ghostty_terminal_write(this.handle, ptr, bytes.length);
this.exports.ghostty_wasm_free_u8_array(ptr, bytes.length);
}
resize(cols: number, rows: number): void {
if (cols === this._cols && rows === this._rows) return;
this._cols = cols;
this._rows = rows;
this.exports.ghostty_terminal_resize(this.handle, cols, rows);
this.invalidateBuffers();
this.initCellPool();
}
free(): void {
if (this.viewportBufferPtr) {
this.exports.ghostty_wasm_free_u8_array(this.viewportBufferPtr, this.viewportBufferSize);
this.viewportBufferPtr = 0;
}
this.exports.ghostty_terminal_free(this.handle);
}
// ==========================================================================
// RenderState API - The key performance optimization
// ==========================================================================
/**
* Update render state from terminal.
*
* This syncs the RenderState with the current Terminal state.
* The dirty state (full/partial/none) is stored in the WASM RenderState
* and can be queried via isRowDirty(). When dirty==full, isRowDirty()
* returns true for ALL rows.
*
* The WASM layer automatically detects screen switches (normal <-> alternate)
* and returns FULL dirty state when switching screens (e.g., vim exit).
*
* Safe to call multiple times - dirty state persists until markClean().
*/
update(): DirtyState {
return this.exports.ghostty_render_state_update(this.handle) as DirtyState;
}
/**
* Get cursor state from render state.
* Ensures render state is fresh by calling update().
*/
getCursor(): RenderStateCursor {
// Call update() to ensure render state is fresh.
// This is safe to call multiple times - dirty state persists until markClean().
this.update();
return {
x: this.exports.ghostty_render_state_get_cursor_x(this.handle),
y: this.exports.ghostty_render_state_get_cursor_y(this.handle),
viewportX: this.exports.ghostty_render_state_get_cursor_x(this.handle),
viewportY: this.exports.ghostty_render_state_get_cursor_y(this.handle),
visible: this.exports.ghostty_render_state_get_cursor_visible(this.handle),
blinking: this.exports.ghostty_render_state_get_cursor_blinking(this.handle),
style:
(['block', 'bar', 'underline'] as const)[
this.exports.ghostty_render_state_get_cursor_style(this.handle)
] ?? 'block',
};
}
/**
* Get default colors from render state
*/
getColors(): RenderStateColors {
const bg = this.exports.ghostty_render_state_get_bg_color(this.handle);
const fg = this.exports.ghostty_render_state_get_fg_color(this.handle);
return {
background: {
r: (bg >> 16) & 0xff,
g: (bg >> 8) & 0xff,
b: bg & 0xff,
},
foreground: {
r: (fg >> 16) & 0xff,
g: (fg >> 8) & 0xff,
b: fg & 0xff,
},
cursor: null, // TODO: Add cursor color support
};
}
/**
* Check if a specific row is dirty
*/
isRowDirty(y: number): boolean {
return this.exports.ghostty_render_state_is_row_dirty(this.handle, y);
}
/**
* Mark render state as clean (call after rendering)
*/
markClean(): void {
this.exports.ghostty_render_state_mark_clean(this.handle);
}
/**
* Get ALL viewport cells in ONE WASM call - the key performance optimization!
* Returns a reusable cell array (zero allocation after warmup).
*/
getViewport(): GhosttyCell[] {
const totalCells = this._cols * this._rows;
const neededSize = totalCells * GhosttyTerminal.CELL_SIZE;
// Ensure buffer is allocated
if (!this.viewportBufferPtr || this.viewportBufferSize < neededSize) {
if (this.viewportBufferPtr) {
this.exports.ghostty_wasm_free_u8_array(this.viewportBufferPtr, this.viewportBufferSize);
}
this.viewportBufferPtr = this.exports.ghostty_wasm_alloc_u8_array(neededSize);
this.viewportBufferSize = neededSize;
}
// Get all cells in one call
const count = this.exports.ghostty_render_state_get_viewport(
this.handle,
this.viewportBufferPtr,
totalCells,
);
if (count < 0) return this.cellPool;
// Parse cells into pool (reuses existing objects)
this.parseCellsIntoPool(this.viewportBufferPtr, totalCells);
return this.cellPool;
}
// ==========================================================================
// Compatibility methods (delegate to render state)
// ==========================================================================
/**
* Get line - for compatibility, extracts from viewport.
* Ensures render state is fresh by calling update().
* Returns a COPY of the cells to avoid pool reference issues.
*/
getLine(y: number): GhosttyCell[] | null {
if (y < 0 || y >= this._rows) return null;
// Call update() to ensure render state is fresh.
// This is safe to call multiple times - dirty state persists until markClean().
this.update();
const viewport = this.getViewport();
const start = y * this._cols;
// Return deep copies to avoid cell pool reference issues
return viewport.slice(start, start + this._cols).map((cell) => ({ ...cell }));
}
/** For compatibility with old API */
isDirty(): boolean {
return this.update() !== DirtyState.NONE;
}
/**
* Check if a full redraw is needed (screen change, resize, etc.)
* Note: This calls update() to ensure fresh state. Safe to call multiple times.
*/
needsFullRedraw(): boolean {
return this.update() === DirtyState.FULL;
}
/** Mark render state as clean after rendering */
clearDirty(): void {
this.markClean();
}
// ==========================================================================
// Terminal modes
// ==========================================================================
isAlternateScreen(): boolean {
return !!this.exports.ghostty_terminal_is_alternate_screen(this.handle);
}
hasBracketedPaste(): boolean {
// Mode 2004 = bracketed paste (DEC mode)
return this.getMode(2004, false);
}
hasFocusEvents(): boolean {
// Mode 1004 = focus events (DEC mode)
return this.getMode(1004, false);
}
hasMouseTracking(): boolean {
return this.exports.ghostty_terminal_has_mouse_tracking(this.handle) !== 0;
}
// ==========================================================================
// Extended API (scrollback, modes, etc.)
// ==========================================================================
/** Get dimensions - for compatibility */
getDimensions(): { cols: number; rows: number } {
return { cols: this._cols, rows: this._rows };
}
/** Get number of scrollback lines (history, not including active screen) */
getScrollbackLength(): number {
return this.exports.ghostty_terminal_get_scrollback_length(this.handle);
}
/**
* Get a line from the scrollback buffer.
* Ensures render state is fresh by calling update().
* @param offset 0 = oldest line, (length-1) = most recent scrollback line
*/
getScrollbackLine(offset: number): GhosttyCell[] | null {
const neededSize = this._cols * GhosttyTerminal.CELL_SIZE;
// Ensure buffer is allocated
if (!this.viewportBufferPtr || this.viewportBufferSize < neededSize) {
if (this.viewportBufferPtr) {
this.exports.ghostty_wasm_free_u8_array(this.viewportBufferPtr, this.viewportBufferSize);
}
this.viewportBufferPtr = this.exports.ghostty_wasm_alloc_u8_array(neededSize);
this.viewportBufferSize = neededSize;
}
// Call update() to ensure render state is fresh (needed for colors).
// This is safe to call multiple times - dirty state persists until markClean().
this.update();
const count = this.exports.ghostty_terminal_get_scrollback_line(
this.handle,
offset,
this.viewportBufferPtr,
this._cols,
);
if (count < 0) return null;
// Parse cells
const cells: GhosttyCell[] = [];
const buffer = this.memory.buffer;
const u8 = new Uint8Array(buffer, this.viewportBufferPtr, count * GhosttyTerminal.CELL_SIZE);
const view = new DataView(buffer, this.viewportBufferPtr, count * GhosttyTerminal.CELL_SIZE);
for (let i = 0; i < count; i++) {
const cellOffset = i * GhosttyTerminal.CELL_SIZE;
cells.push({
codepoint: view.getUint32(cellOffset, true),
fg_r: u8[cellOffset + 4],
fg_g: u8[cellOffset + 5],
fg_b: u8[cellOffset + 6],
bg_r: u8[cellOffset + 7],
bg_g: u8[cellOffset + 8],
bg_b: u8[cellOffset + 9],
flags: u8[cellOffset + 10],
width: u8[cellOffset + 11],
hyperlink_id: view.getUint16(cellOffset + 12, true),
grapheme_len: u8[cellOffset + 14],
});
}
return cells;
}
/** Check if a row in the active screen is wrapped (soft-wrapped to next line) */
isRowWrapped(row: number): boolean {
return this.exports.ghostty_terminal_is_row_wrapped(this.handle, row) !== 0;
}
/**
* Get the hyperlink URI for a cell at the given position.
* @param row Row index (0-based, in active viewport)
* @param col Column index (0-based)
* @returns The URI string, or null if no hyperlink at that position
*/
getHyperlinkUri(row: number, col: number): string | null {
// Check if WASM has this function (requires rebuilt WASM with hyperlink support)
if (!this.exports.ghostty_terminal_get_hyperlink_uri) {
return null;
}
// Try with initial buffer, retry with larger if needed (for very long URLs)
const bufferSizes = [2048, 8192, 32768];
for (const bufSize of bufferSizes) {
const bufPtr = this.exports.ghostty_wasm_alloc_u8_array(bufSize);
try {
const bytesWritten = this.exports.ghostty_terminal_get_hyperlink_uri(
this.handle,
row,
col,
bufPtr,
bufSize,
);
// 0 means no hyperlink at this position
if (bytesWritten === 0) return null;
// -1 means buffer too small, try next size
if (bytesWritten === -1) continue;
// Negative values other than -1 are errors
if (bytesWritten < 0) return null;
const bytes = new Uint8Array(this.memory.buffer, bufPtr, bytesWritten);
return new TextDecoder().decode(bytes.slice());
} finally {
this.exports.ghostty_wasm_free_u8_array(bufPtr, bufSize);
}
}
// URI too long even for largest buffer
return null;
}
/**
* Get the hyperlink URI for a cell in the scrollback buffer.
* @param offset Scrollback line offset (0 = oldest, scrollback_len-1 = newest)
* @param col Column index (0-based)
* @returns The URI string, or null if no hyperlink at that position
*/
getScrollbackHyperlinkUri(offset: number, col: number): string | null {
// Check if WASM has this function
if (!this.exports.ghostty_terminal_get_scrollback_hyperlink_uri) {
return null;
}
// Try with initial buffer, retry with larger if needed (for very long URLs)
const bufferSizes = [2048, 8192, 32768];
for (const bufSize of bufferSizes) {
const bufPtr = this.exports.ghostty_wasm_alloc_u8_array(bufSize);
try {
const bytesWritten = this.exports.ghostty_terminal_get_scrollback_hyperlink_uri(
this.handle,
offset,
col,
bufPtr,
bufSize,
);
// 0 means no hyperlink at this position
if (bytesWritten === 0) return null;
// -1 means buffer too small, try next size
if (bytesWritten === -1) continue;
// Negative values other than -1 are errors
if (bytesWritten < 0) return null;
const bytes = new Uint8Array(this.memory.buffer, bufPtr, bytesWritten);
return new TextDecoder().decode(bytes.slice());
} finally {
this.exports.ghostty_wasm_free_u8_array(bufPtr, bufSize);
}
}
// URI too long even for largest buffer
return null;
}
/**
* Check if there are pending responses from the terminal.
* Responses are generated by escape sequences like DSR (Device Status Report).
*/
hasResponse(): boolean {
return this.exports.ghostty_terminal_has_response(this.handle);
}
/**
* Read pending responses from the terminal.
* Returns the response string, or null if no responses pending.
*
* Responses are generated by escape sequences that require replies:
* - DSR 6 (cursor position): Returns \x1b[row;colR
* - DSR 5 (operating status): Returns \x1b[0n
*/
readResponse(): string | null {
if (!this.hasResponse()) return null;
const bufSize = 256; // Most responses are small
const bufPtr = this.exports.ghostty_wasm_alloc_u8_array(bufSize);
try {
const bytesRead = this.exports.ghostty_terminal_read_response(this.handle, bufPtr, bufSize);
if (bytesRead <= 0) return null;
const bytes = new Uint8Array(this.memory.buffer, bufPtr, bytesRead);
return new TextDecoder().decode(bytes.slice());
} finally {
this.exports.ghostty_wasm_free_u8_array(bufPtr, bufSize);
}
}
/**
* Query arbitrary terminal mode by number
* @param mode Mode number (e.g., 25 for cursor visibility, 2004 for bracketed paste)
* @param isAnsi True for ANSI modes, false for DEC modes (default: false)
*/
getMode(mode: number, isAnsi: boolean = false): boolean {
return this.exports.ghostty_terminal_get_mode(this.handle, mode, isAnsi) !== 0;
}
// ==========================================================================
// Private helpers
// ==========================================================================
private initCellPool(): void {
const total = this._cols * this._rows;
if (this.cellPool.length < total) {
for (let i = this.cellPool.length; i < total; i++) {
this.cellPool.push({
codepoint: 0,
fg_r: 204,
fg_g: 204,
fg_b: 204,
bg_r: 0,
bg_g: 0,
bg_b: 0,
flags: 0,
width: 1,
hyperlink_id: 0,
grapheme_len: 0,
});
}
}
}
private parseCellsIntoPool(ptr: number, count: number): void {
const buffer = this.memory.buffer;
const u8 = new Uint8Array(buffer, ptr, count * GhosttyTerminal.CELL_SIZE);
const view = new DataView(buffer, ptr, count * GhosttyTerminal.CELL_SIZE);
for (let i = 0; i < count; i++) {
const offset = i * GhosttyTerminal.CELL_SIZE;
const cell = this.cellPool[i];
cell.codepoint = view.getUint32(offset, true);
cell.fg_r = u8[offset + 4];
cell.fg_g = u8[offset + 5];
cell.fg_b = u8[offset + 6];
cell.bg_r = u8[offset + 7];
cell.bg_g = u8[offset + 8];
cell.bg_b = u8[offset + 9];
cell.flags = u8[offset + 10];
cell.width = u8[offset + 11];
cell.hyperlink_id = view.getUint16(offset + 12, true);
cell.grapheme_len = u8[offset + 14]; // grapheme_len is at byte 14
}
}
/** Small buffer for grapheme lookups (reused to avoid allocation) */
private graphemeBuffer: Uint32Array | null = null;
private graphemeBufferPtr: number = 0;
/**
* Get all codepoints for a grapheme cluster at the given position.
* For most cells this returns a single codepoint, but for complex scripts
* (Hindi, emoji with ZWJ, etc.) it returns multiple codepoints.
* @returns Array of codepoints, or null on error
*/
getGrapheme(row: number, col: number): number[] | null {
// Allocate buffer on first use (16 codepoints should be enough for any grapheme)
if (!this.graphemeBuffer) {
this.graphemeBufferPtr = this.exports.ghostty_wasm_alloc_u8_array(16 * 4);
this.graphemeBuffer = new Uint32Array(this.memory.buffer, this.graphemeBufferPtr, 16);
}
const count = this.exports.ghostty_render_state_get_grapheme(
this.handle,
row,
col,
this.graphemeBufferPtr,
16,
);
if (count < 0) return null;
// Re-create view in case memory grew
const view = new Uint32Array(this.memory.buffer, this.graphemeBufferPtr, count);
return Array.from(view);
}
/**
* Get a string representation of the grapheme at the given position.
* This properly handles complex scripts like Hindi, emoji with ZWJ, etc.
*/
getGraphemeString(row: number, col: number): string {
const codepoints = this.getGrapheme(row, col);
if (!codepoints || codepoints.length === 0) return ' ';
return String.fromCodePoint(...codepoints);
}
/**
* Get all codepoints for a grapheme cluster in the scrollback buffer.
* @param offset Scrollback line offset (0 = oldest)
* @param col Column index
* @returns Array of codepoints, or null on error
*/
getScrollbackGrapheme(offset: number, col: number): number[] | null {
// Reuse the same buffer as getGrapheme
if (!this.graphemeBuffer) {
this.graphemeBufferPtr = this.exports.ghostty_wasm_alloc_u8_array(16 * 4);
this.graphemeBuffer = new Uint32Array(this.memory.buffer, this.graphemeBufferPtr, 16);
}
const count = this.exports.ghostty_terminal_get_scrollback_grapheme(
this.handle,
offset,
col,
this.graphemeBufferPtr,
16,
);
if (count < 0) return null;
// Re-create view in case memory grew
const view = new Uint32Array(this.memory.buffer, this.graphemeBufferPtr, count);
return Array.from(view);
}
/**
* Get a string representation of a grapheme in the scrollback buffer.
*/
getScrollbackGraphemeString(offset: number, col: number): string {
const codepoints = this.getScrollbackGrapheme(offset, col);
if (!codepoints || codepoints.length === 0) return ' ';
return String.fromCodePoint(...codepoints);
}
private invalidateBuffers(): void {
if (this.viewportBufferPtr) {
this.exports.ghostty_wasm_free_u8_array(this.viewportBufferPtr, this.viewportBufferSize);
this.viewportBufferPtr = 0;
this.viewportBufferSize = 0;
}
if (this.graphemeBufferPtr) {
this.exports.ghostty_wasm_free_u8_array(this.graphemeBufferPtr, 16 * 4);
this.graphemeBufferPtr = 0;
}
this.graphemeBuffer = null;
}
}