forked from coder/ghostty-web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathghostty-wasm-api.patch
More file actions
1267 lines (1260 loc) · 42.8 KB
/
ghostty-wasm-api.patch
File metadata and controls
1267 lines (1260 loc) · 42.8 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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/.gitignore b/.gitignore
index e451b171a..89c623d8b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,3 +23,4 @@ glad.zip
/ghostty.qcow2
vgcore.*
+node_modules/
diff --git a/include/ghostty/vt.h b/include/ghostty/vt.h
index 4f8fef88e..ca9fb1d4d 100644
--- a/include/ghostty/vt.h
+++ b/include/ghostty/vt.h
@@ -28,6 +28,7 @@
* @section groups_sec API Reference
*
* The API is organized into the following groups:
+ * - @ref terminal "Terminal Emulator" - Complete terminal emulator with VT parsing
* - @ref key "Key Encoding" - Encode key events into terminal sequences
* - @ref osc "OSC Parser" - Parse OSC (Operating System Command) sequences
* - @ref sgr "SGR Parser" - Parse SGR (Select Graphic Rendition) sequences
@@ -74,6 +75,7 @@ extern "C" {
#include <ghostty/vt/result.h>
#include <ghostty/vt/allocator.h>
+#include <ghostty/vt/terminal.h>
#include <ghostty/vt/osc.h>
#include <ghostty/vt/sgr.h>
#include <ghostty/vt/key.h>
diff --git a/include/ghostty/vt/terminal.h b/include/ghostty/vt/terminal.h
new file mode 100644
index 000000000..078a0b872
--- /dev/null
+++ b/include/ghostty/vt/terminal.h
@@ -0,0 +1,499 @@
+/**
+ * @file terminal.h
+ *
+ * Complete terminal emulator API for WASM integration.
+ */
+
+#ifndef GHOSTTY_VT_TERMINAL_H
+#define GHOSTTY_VT_TERMINAL_H
+
+/** @defgroup terminal Terminal Emulator
+ *
+ * Complete terminal emulator with VT100/ANSI parsing and screen buffer management.
+ *
+ * This API exports Ghostty's production-tested terminal emulator for use in
+ * WASM environments. It handles all VT sequence parsing, screen buffer management,
+ * scrollback, cursor positioning, and text styling.
+ *
+ * ## Basic Usage
+ *
+ * 1. Create a terminal with ghostty_terminal_new()
+ * 2. Write data with ghostty_terminal_write() (parses VT sequences)
+ * 3. Read screen content with ghostty_terminal_get_line()
+ * 4. Query cursor position with ghostty_terminal_get_cursor_x/y()
+ * 5. Free with ghostty_terminal_free() when done
+ *
+ * ## Example
+ *
+ * @code{.c}
+ * #include <ghostty/vt.h>
+ * #include <string.h>
+ *
+ * int main() {
+ * // Create 80x24 terminal
+ * GhosttyTerminal term = ghostty_terminal_new(80, 24);
+ * if (!term) return 1;
+ *
+ * // Write some text with color
+ * const char* data = "Hello \x1b[31mRed\x1b[0m World!";
+ * ghostty_terminal_write(term, (const uint8_t*)data, strlen(data));
+ *
+ * // Read first line
+ * GhosttyCell cells[80];
+ * int count = ghostty_terminal_get_line(term, 0, cells, 80);
+ *
+ * // Check cursor position
+ * int x = ghostty_terminal_get_cursor_x(term);
+ * int y = ghostty_terminal_get_cursor_y(term);
+ *
+ * // Cleanup
+ * ghostty_terminal_free(term);
+ * return 0;
+ * }
+ * @endcode
+ *
+ * @{
+ */
+
+#include <ghostty/vt/allocator.h>
+#include <ghostty/vt/result.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Opaque terminal handle.
+ *
+ * Represents a terminal emulator instance. Create with ghostty_terminal_new()
+ * and free with ghostty_terminal_free().
+ */
+typedef void* GhosttyTerminal;
+
+/**
+ * Terminal configuration options.
+ *
+ * Used when creating a new terminal to specify behavior and limits.
+ * All colors use 0xRRGGBB format. A value of 0 means "use default".
+ */
+typedef struct {
+ /**
+ * Maximum scrollback lines (0 = unlimited, default = 10000).
+ *
+ * Limits memory usage by restricting how many lines of history are kept.
+ * For WASM environments, a reasonable limit is recommended.
+ */
+ uint32_t scrollback_limit;
+
+ /**
+ * Initial foreground color (RGB, 0xRRGGBB format, 0 = use default).
+ */
+ uint32_t fg_color;
+
+ /**
+ * Initial background color (RGB, 0xRRGGBB format, 0 = use default).
+ */
+ uint32_t bg_color;
+
+ /**
+ * Cursor color (RGB, 0xRRGGBB format, 0 = use default).
+ */
+ uint32_t cursor_color;
+
+ /**
+ * ANSI color palette (16 colors, 0xRRGGBB format, 0 = use default).
+ * Index 0-7: Normal colors (black, red, green, yellow, blue, magenta, cyan, white)
+ * Index 8-15: Bright colors (same order)
+ */
+ uint32_t palette[16];
+} GhosttyTerminalConfig;
+
+/**
+ * Cell structure - represents a single character position.
+ *
+ * This is designed to be simple and C-compatible. Colors are always
+ * exported as RGB (terminal color palette is resolved internally).
+ *
+ * Size: 16 bytes (efficient for bulk transfers across WASM boundary)
+ */
+typedef struct {
+ /** Unicode codepoint (0 = empty cell) */
+ uint32_t codepoint;
+
+ /** Foreground color - Red component (0-255) */
+ uint8_t fg_r;
+ /** Foreground color - Green component (0-255) */
+ uint8_t fg_g;
+ /** Foreground color - Blue component (0-255) */
+ uint8_t fg_b;
+
+ /** Background color - Red component (0-255) */
+ uint8_t bg_r;
+ /** Background color - Green component (0-255) */
+ uint8_t bg_g;
+ /** Background color - Blue component (0-255) */
+ uint8_t bg_b;
+
+ /** Style flags (see GHOSTTY_CELL_* constants) */
+ uint8_t flags;
+
+ /** Character width: 0=combining, 1=normal, 2=wide (CJK) */
+ uint8_t width;
+
+ /** Hyperlink ID (0 = no link, >0 = lookup in hyperlink set) */
+ uint16_t hyperlink_id;
+
+ /** Padding for alignment (keeps struct at 16 bytes) */
+ uint32_t _padding;
+} GhosttyCell;
+
+/** Cell flag: Bold text */
+#define GHOSTTY_CELL_BOLD (1 << 0)
+/** Cell flag: Italic text */
+#define GHOSTTY_CELL_ITALIC (1 << 1)
+/** Cell flag: Underlined text */
+#define GHOSTTY_CELL_UNDERLINE (1 << 2)
+/** Cell flag: Strikethrough text */
+#define GHOSTTY_CELL_STRIKETHROUGH (1 << 3)
+/** Cell flag: Inverse video (swap fg/bg) */
+#define GHOSTTY_CELL_INVERSE (1 << 4)
+/** Cell flag: Invisible text */
+#define GHOSTTY_CELL_INVISIBLE (1 << 5)
+/** Cell flag: Blinking text */
+#define GHOSTTY_CELL_BLINK (1 << 6)
+/** Cell flag: Faint/dim text */
+#define GHOSTTY_CELL_FAINT (1 << 7)
+
+/* ============================================================================
+ * Lifecycle Management
+ * ========================================================================= */
+
+/**
+ * Create a new terminal instance with default configuration.
+ *
+ * Creates an 80x24 terminal with default settings (10,000 line scrollback,
+ * standard color palette, autowrap enabled).
+ *
+ * @param cols Number of columns (typically 80, minimum 1)
+ * @param rows Number of rows (typically 24, minimum 1)
+ * @return Terminal handle, or NULL on allocation failure
+ *
+ * @see ghostty_terminal_new_with_config() for custom configuration
+ * @see ghostty_terminal_free()
+ */
+GhosttyTerminal ghostty_terminal_new(int cols, int rows);
+
+/**
+ * Create a new terminal instance with custom configuration.
+ *
+ * @param cols Number of columns (typically 80, minimum 1)
+ * @param rows Number of rows (typically 24, minimum 1)
+ * @param config Configuration options (NULL = use defaults)
+ * @return Terminal handle, or NULL on allocation failure
+ *
+ * @see ghostty_terminal_new()
+ * @see ghostty_terminal_free()
+ */
+GhosttyTerminal ghostty_terminal_new_with_config(
+ int cols,
+ int rows,
+ const GhosttyTerminalConfig* config
+);
+
+/**
+ * Free a terminal instance.
+ *
+ * Releases all memory associated with the terminal. The handle becomes
+ * invalid after this call.
+ *
+ * @param term Terminal to free (NULL is safe)
+ */
+void ghostty_terminal_free(GhosttyTerminal term);
+
+/**
+ * Resize the terminal.
+ *
+ * Changes the terminal dimensions. Content is preserved where possible,
+ * with appropriate reflowing or truncation.
+ *
+ * @param term Terminal instance
+ * @param cols New column count (minimum 1)
+ * @param rows New row count (minimum 1)
+ */
+void ghostty_terminal_resize(GhosttyTerminal term, int cols, int rows);
+
+/* ============================================================================
+ * Input/Output
+ * ========================================================================= */
+
+/**
+ * Write data to terminal (parses VT sequences and updates screen).
+ *
+ * This is the main entry point - all terminal output goes through here.
+ * The data is parsed as VT100/ANSI escape sequences and the screen
+ * buffer is updated accordingly.
+ *
+ * Supports:
+ * - Text output (UTF-8)
+ * - CSI sequences (colors, cursor movement, etc.)
+ * - OSC sequences (title, colors, etc.)
+ * - All standard VT100/xterm sequences
+ *
+ * @param term Terminal instance
+ * @param data UTF-8 encoded data (may contain VT sequences)
+ * @param len Length of data in bytes
+ *
+ * @note This function marks affected rows as dirty for rendering optimization
+ */
+void ghostty_terminal_write(GhosttyTerminal term, const uint8_t* data, size_t len);
+
+/* ============================================================================
+ * Screen Queries
+ * ========================================================================= */
+
+/**
+ * Get terminal width in columns.
+ *
+ * @param term Terminal instance
+ * @return Number of columns, or 0 if term is NULL
+ */
+int ghostty_terminal_get_cols(GhosttyTerminal term);
+
+/**
+ * Get terminal height in rows.
+ *
+ * @param term Terminal instance
+ * @return Number of rows, or 0 if term is NULL
+ */
+int ghostty_terminal_get_rows(GhosttyTerminal term);
+
+/**
+ * Get cursor X position (column).
+ *
+ * @param term Terminal instance
+ * @return Column position (0-indexed), or 0 if term is NULL
+ */
+int ghostty_terminal_get_cursor_x(GhosttyTerminal term);
+
+/**
+ * Get cursor Y position (row).
+ *
+ * @param term Terminal instance
+ * @return Row position (0-indexed), or 0 if term is NULL
+ */
+int ghostty_terminal_get_cursor_y(GhosttyTerminal term);
+
+/**
+ * Get cursor visibility state.
+ *
+ * @param term Terminal instance
+ * @return true if cursor is visible, false otherwise
+ */
+bool ghostty_terminal_get_cursor_visible(GhosttyTerminal term);
+
+/**
+ * Check if terminal is in alternate screen buffer mode.
+ */
+bool ghostty_terminal_is_alternate_screen(GhosttyTerminal term);
+
+/**
+ * Check if a row is wrapped from the previous row.
+ */
+bool ghostty_terminal_is_row_wrapped(GhosttyTerminal term, int row);
+
+/**
+ * Get scrollback length (number of lines in history).
+ *
+ * @param term Terminal instance
+ * @return Number of scrollback lines, or 0 if none/NULL
+ */
+int ghostty_terminal_get_scrollback_length(GhosttyTerminal term);
+
+/* ============================================================================
+ * Cell Data Access
+ * ========================================================================= */
+
+/**
+ * Get a line of cells from the visible screen.
+ *
+ * Retrieves an entire row of cells at once for efficient rendering.
+ * Colors are returned as RGB values (palette indices are resolved).
+ *
+ * @param term Terminal instance
+ * @param y Line number (0-indexed, 0 = top visible line)
+ * @param out_buffer Output buffer (must have space for at least 'cols' cells)
+ * @param buffer_size Size of output buffer in cells (should be >= cols)
+ * @return Number of cells written (equals cols on success), or -1 on error
+ *
+ * @note Always writes exactly 'cols' cells, padding with empty cells if needed
+ */
+int ghostty_terminal_get_line(
+ GhosttyTerminal term,
+ int y,
+ GhosttyCell* out_buffer,
+ size_t buffer_size
+);
+
+/**
+ * Get a line from scrollback history.
+ *
+ * @param term Terminal instance
+ * @param y Line number (0 = oldest scrollback line)
+ * @param out_buffer Output buffer
+ * @param buffer_size Size of output buffer in cells
+ * @return Number of cells written, or -1 on error/not implemented
+ *
+ * @note Currently not implemented - returns -1
+ */
+int ghostty_terminal_get_scrollback_line(
+ GhosttyTerminal term,
+ int y,
+ GhosttyCell* out_buffer,
+ size_t buffer_size
+);
+
+/* ============================================================================
+ * Dirty Tracking (for efficient rendering)
+ * ========================================================================= */
+
+/**
+ * Check if any part of the screen is dirty.
+ *
+ * Dirty tracking helps optimize rendering by identifying what changed.
+ * After writing to the terminal, check which rows are dirty and only
+ * re-render those.
+ *
+ * @param term Terminal instance
+ * @return true if any row needs redrawing, false otherwise
+ *
+ * @see ghostty_terminal_is_row_dirty()
+ * @see ghostty_terminal_clear_dirty()
+ */
+bool ghostty_terminal_is_dirty(GhosttyTerminal term);
+
+/**
+ * Check if a specific row is dirty.
+ *
+ * @param term Terminal instance
+ * @param y Row number (0-indexed)
+ * @return true if row needs redrawing, false otherwise
+ */
+bool ghostty_terminal_is_row_dirty(GhosttyTerminal term, int y);
+
+/**
+ * Clear all dirty flags (call after rendering).
+ *
+ * After reading dirty rows and re-rendering them, call this to mark
+ * the screen as clean.
+ *
+ * @param term Terminal instance
+ */
+void ghostty_terminal_clear_dirty(GhosttyTerminal term);
+
+/* ============================================================================
+ * Hyperlink Support
+ * ========================================================================= */
+
+/**
+ * Get hyperlink URI by ID.
+ *
+ * Retrieves the URI string for a hyperlink ID obtained from a GhosttyCell.
+ * The URI is written to the provided buffer.
+ *
+ * @param term Terminal instance
+ * @param hyperlink_id Hyperlink ID from GhosttyCell (must be > 0)
+ * @param out_buffer Buffer to write URI string (UTF-8)
+ * @param buffer_size Size of output buffer in bytes
+ * @return Number of bytes written (not including null terminator), or 0 if:
+ * - hyperlink_id is 0 or invalid
+ * - URI doesn't exist
+ * - buffer is too small (URI is truncated)
+ *
+ * @note The returned string is NOT null-terminated. Use the return value
+ * to determine the actual length.
+ */
+int ghostty_terminal_get_hyperlink_uri(
+ GhosttyTerminal term,
+ uint16_t hyperlink_id,
+ uint8_t* out_buffer,
+ size_t buffer_size
+);
+
+
+/* ============================================================================
+ * Terminal Modes
+ * ========================================================================= */
+
+/**
+ * Query terminal mode state.
+ *
+ * This function queries whether a specific terminal mode is enabled or disabled.
+ * Modes can be either ANSI modes or DEC private modes (indicated by is_ansi parameter).
+ *
+ * Common DEC modes (is_ansi = false):
+ * - 25 = Cursor visible (DECTCEM)
+ * - 1000 = Mouse tracking (normal)
+ * - 1002 = Mouse tracking (button events)
+ * - 1003 = Mouse tracking (any events)
+ * - 1004 = Focus event reporting
+ * - 1047 = Alternate screen buffer
+ * - 1049 = Alternate screen buffer with cursor save
+ * - 2004 = Bracketed paste mode
+ *
+ * Common ANSI modes (is_ansi = true):
+ * - 4 = Insert/replace mode (IRM)
+ *
+ * @param term Terminal instance
+ * @param mode_number Mode number to query
+ * @param is_ansi true for ANSI modes, false for DEC private modes
+ * @return true if mode is enabled, false if disabled or mode is invalid
+ */
+bool ghostty_terminal_get_mode(GhosttyTerminal term, int mode_number, bool is_ansi);
+
+/**
+ * Check if bracketed paste mode is enabled (DEC mode 2004).
+ *
+ * Bracketed paste wraps pasted text with escape sequences to distinguish
+ * it from typed text: ESC[200~ ... ESC[201~
+ *
+ * @param term Terminal instance
+ * @return true if bracketed paste is enabled
+ */
+bool ghostty_terminal_has_bracketed_paste(GhosttyTerminal term);
+
+/**
+ * Check if focus event reporting is enabled (DEC mode 1004).
+ *
+ * When enabled, the terminal reports focus in/out events:
+ * - Focus in: ESC[I
+ * - Focus out: ESC[O
+ *
+ * @param term Terminal instance
+ * @return true if focus events are enabled
+ */
+bool ghostty_terminal_has_focus_events(GhosttyTerminal term);
+
+/**
+ * Check if any mouse tracking mode is enabled.
+ *
+ * Returns true if any of these DEC modes are enabled:
+ * - 1000: Normal mouse tracking
+ * - 1002: Button event tracking
+ * - 1003: Any event tracking
+ *
+ * @param term Terminal instance
+ * @return true if mouse tracking is enabled
+ */
+bool ghostty_terminal_has_mouse_tracking(GhosttyTerminal term);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/** @} */
+
+#endif /* GHOSTTY_VT_TERMINAL_H */
diff --git a/src/lib_vt.zig b/src/lib_vt.zig
index e95eee5f4..687ccc6a3 100644
--- a/src/lib_vt.zig
+++ b/src/lib_vt.zig
@@ -137,6 +137,29 @@ comptime {
@export(&c.sgr_unknown_partial, .{ .name = "ghostty_sgr_unknown_partial" });
@export(&c.sgr_attribute_tag, .{ .name = "ghostty_sgr_attribute_tag" });
@export(&c.sgr_attribute_value, .{ .name = "ghostty_sgr_attribute_value" });
+ @export(&c.terminal_new, .{ .name = "ghostty_terminal_new" });
+ @export(&c.terminal_new_with_config, .{ .name = "ghostty_terminal_new_with_config" });
+ @export(&c.terminal_free, .{ .name = "ghostty_terminal_free" });
+ @export(&c.terminal_resize, .{ .name = "ghostty_terminal_resize" });
+ @export(&c.terminal_write, .{ .name = "ghostty_terminal_write" });
+ @export(&c.terminal_get_cols, .{ .name = "ghostty_terminal_get_cols" });
+ @export(&c.terminal_get_rows, .{ .name = "ghostty_terminal_get_rows" });
+ @export(&c.terminal_get_cursor_x, .{ .name = "ghostty_terminal_get_cursor_x" });
+ @export(&c.terminal_get_cursor_y, .{ .name = "ghostty_terminal_get_cursor_y" });
+ @export(&c.terminal_get_cursor_visible, .{ .name = "ghostty_terminal_get_cursor_visible" });
+ @export(&c.terminal_is_alternate_screen, .{ .name = "ghostty_terminal_is_alternate_screen" });
+ @export(&c.terminal_is_row_wrapped, .{ .name = "ghostty_terminal_is_row_wrapped" });
+ @export(&c.terminal_get_scrollback_length, .{ .name = "ghostty_terminal_get_scrollback_length" });
+ @export(&c.terminal_get_line, .{ .name = "ghostty_terminal_get_line" });
+ @export(&c.terminal_get_scrollback_line, .{ .name = "ghostty_terminal_get_scrollback_line" });
+ @export(&c.terminal_is_dirty, .{ .name = "ghostty_terminal_is_dirty" });
+ @export(&c.terminal_is_row_dirty, .{ .name = "ghostty_terminal_is_row_dirty" });
+ @export(&c.terminal_clear_dirty, .{ .name = "ghostty_terminal_clear_dirty" });
+ @export(&c.terminal_get_hyperlink_uri, .{ .name = "ghostty_terminal_get_hyperlink_uri" });
+ @export(&c.terminal_get_mode, .{ .name = "ghostty_terminal_get_mode" });
+ @export(&c.terminal_has_bracketed_paste, .{ .name = "ghostty_terminal_has_bracketed_paste" });
+ @export(&c.terminal_has_focus_events, .{ .name = "ghostty_terminal_has_focus_events" });
+ @export(&c.terminal_has_mouse_tracking, .{ .name = "ghostty_terminal_has_mouse_tracking" });
// On Wasm we need to export our allocator convenience functions.
if (builtin.target.cpu.arch.isWasm()) {
diff --git a/src/terminal/c/main.zig b/src/terminal/c/main.zig
index bc92597f5..d988967f7 100644
--- a/src/terminal/c/main.zig
+++ b/src/terminal/c/main.zig
@@ -4,6 +4,7 @@ pub const key_event = @import("key_event.zig");
pub const key_encode = @import("key_encode.zig");
pub const paste = @import("paste.zig");
pub const sgr = @import("sgr.zig");
+pub const terminal = @import("terminal.zig");
// The full C API, unexported.
pub const osc_new = osc.new;
@@ -52,6 +53,30 @@ pub const key_encoder_encode = key_encode.encode;
pub const paste_is_safe = paste.is_safe;
+pub const terminal_new = terminal.new;
+pub const terminal_new_with_config = terminal.newWithConfig;
+pub const terminal_free = terminal.free;
+pub const terminal_resize = terminal.resize;
+pub const terminal_write = terminal.write;
+pub const terminal_get_cols = terminal.getCols;
+pub const terminal_get_rows = terminal.getRows;
+pub const terminal_get_cursor_x = terminal.getCursorX;
+pub const terminal_get_cursor_y = terminal.getCursorY;
+pub const terminal_get_cursor_visible = terminal.getCursorVisible;
+pub const terminal_is_alternate_screen = terminal.isAlternateScreen;
+pub const terminal_is_row_wrapped = terminal.isRowWrapped;
+pub const terminal_get_scrollback_length = terminal.getScrollbackLength;
+pub const terminal_get_line = terminal.getLine;
+pub const terminal_get_scrollback_line = terminal.getScrollbackLine;
+pub const terminal_is_dirty = terminal.isDirty;
+pub const terminal_is_row_dirty = terminal.isRowDirty;
+pub const terminal_clear_dirty = terminal.clearDirty;
+pub const terminal_get_hyperlink_uri = terminal.getHyperlinkUri;
+pub const terminal_get_mode = terminal.getMode;
+pub const terminal_has_bracketed_paste = terminal.hasBracketedPaste;
+pub const terminal_has_focus_events = terminal.hasFocusEvents;
+pub const terminal_has_mouse_tracking = terminal.hasMouseTracking;
+
test {
_ = color;
_ = osc;
@@ -59,6 +84,7 @@ test {
_ = key_encode;
_ = paste;
_ = sgr;
+ _ = terminal;
// We want to make sure we run the tests for the C allocator interface.
_ = @import("../../lib/allocator.zig");
diff --git a/src/terminal/c/terminal.zig b/src/terminal/c/terminal.zig
new file mode 100644
index 000000000..e79702488
--- /dev/null
+++ b/src/terminal/c/terminal.zig
@@ -0,0 +1,642 @@
+//! C API wrapper for Terminal
+//!
+//! This provides a C-compatible interface to Ghostty's Terminal for WASM export.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const assert = std.debug.assert;
+const builtin = @import("builtin");
+
+const Terminal = @import("../Terminal.zig");
+const ReadonlyStream = @import("../stream_readonly.zig").Stream;
+const size = @import("../size.zig");
+const pagepkg = @import("../page.zig");
+const Cell = pagepkg.Cell;
+const PageList = @import("../PageList.zig");
+const color = @import("../color.zig");
+const point = @import("../point.zig");
+const style = @import("../style.zig");
+const modespkg = @import("../modes.zig");
+
+const log = std.log.scoped(.terminal_c);
+
+/// Wrapper struct that owns both the Terminal and its allocator.
+/// This is what we return as an opaque pointer to C.
+const TerminalWrapper = struct {
+ /// The allocator that owns all terminal memory
+ alloc: Allocator,
+
+ /// The terminal instance
+ terminal: Terminal,
+
+ /// Persistent VT stream for parsing (preserves state across writes)
+ /// This is critical for handling escape sequences split across WebSocket messages.
+ stream: ReadonlyStream,
+
+ /// Dirty tracking - which rows have changed since last clear
+ dirty_rows: []bool,
+
+ /// Configuration used for terminal
+ config: Config,
+
+ const Config = struct {
+ scrollback_limit: u32,
+ fg_color: u32,
+ bg_color: u32,
+ cursor_color: u32,
+ palette: [16]u32,
+ };
+};
+
+/// C-compatible cell structure (14 bytes actual, padded to 16 by compiler)
+pub const GhosttyCell = extern struct {
+ codepoint: u32, // 0-3
+ fg_r: u8, // 4
+ fg_g: u8, // 5
+ fg_b: u8, // 6
+ bg_r: u8, // 7
+ bg_g: u8, // 8
+ bg_b: u8, // 9
+ flags: u8, // 10
+ width: u8, // 11
+ hyperlink_id: u16, // 12-13 (0 = no link, >0 = hyperlink ID in set)
+ // Compiler adds 2 bytes padding here to align to 4 bytes
+ // Total size: 16 bytes with padding
+};
+
+/// C-compatible terminal configuration
+pub const GhosttyTerminalConfig = extern struct {
+ scrollback_limit: u32,
+ fg_color: u32,
+ bg_color: u32,
+ cursor_color: u32,
+ palette: [16]u32,
+};
+
+// ============================================================================
+// Lifecycle Management
+// ============================================================================
+
+pub fn new(cols: c_int, rows: c_int) callconv(.c) ?*anyopaque {
+ return newWithConfig(cols, rows, null);
+}
+
+pub fn newWithConfig(
+ cols: c_int,
+ rows: c_int,
+ config_: ?*const GhosttyTerminalConfig,
+) callconv(.c) ?*anyopaque {
+ // Use WASM allocator for WASM builds, GPA otherwise
+ const alloc = if (builtin.target.cpu.arch.isWasm())
+ std.heap.wasm_allocator
+ else
+ std.heap.c_allocator;
+
+ // Parse configuration
+ const config: TerminalWrapper.Config = if (config_) |cfg| .{
+ .scrollback_limit = cfg.scrollback_limit,
+ .fg_color = cfg.fg_color,
+ .bg_color = cfg.bg_color,
+ .cursor_color = cfg.cursor_color,
+ .palette = cfg.palette,
+ } else .{
+ .scrollback_limit = 10_000,
+ .fg_color = 0,
+ .bg_color = 0,
+ .cursor_color = 0,
+ .palette = [_]u32{0} ** 16,
+ };
+
+ // Allocate wrapper
+ const wrapper = alloc.create(TerminalWrapper) catch |err| {
+ log.err("Failed to allocate TerminalWrapper: {}", .{err});
+ return null;
+ };
+
+ // Setup terminal colors
+ var colors = Terminal.Colors.default;
+ if (config.fg_color != 0) {
+ const rgb = color.RGB{
+ .r = @truncate((config.fg_color >> 16) & 0xFF),
+ .g = @truncate((config.fg_color >> 8) & 0xFF),
+ .b = @truncate(config.fg_color & 0xFF),
+ };
+ colors.foreground = color.DynamicRGB.init(rgb);
+ }
+ if (config.bg_color != 0) {
+ const rgb = color.RGB{
+ .r = @truncate((config.bg_color >> 16) & 0xFF),
+ .g = @truncate((config.bg_color >> 8) & 0xFF),
+ .b = @truncate(config.bg_color & 0xFF),
+ };
+ colors.background = color.DynamicRGB.init(rgb);
+ }
+ if (config.cursor_color != 0) {
+ const rgb = color.RGB{
+ .r = @truncate((config.cursor_color >> 16) & 0xFF),
+ .g = @truncate((config.cursor_color >> 8) & 0xFF),
+ .b = @truncate(config.cursor_color & 0xFF),
+ };
+ colors.cursor = color.DynamicRGB.init(rgb);
+ }
+ // Apply palette colors (0 = use default, non-zero = override)
+ for (config.palette, 0..) |palette_color, i| {
+ if (palette_color != 0) {
+ const rgb = color.RGB{
+ .r = @truncate((palette_color >> 16) & 0xFF),
+ .g = @truncate((palette_color >> 8) & 0xFF),
+ .b = @truncate(palette_color & 0xFF),
+ };
+ colors.palette.set(@intCast(i), rgb);
+ }
+ }
+
+ // Create terminal
+ const terminal = Terminal.init(
+ alloc,
+ .{
+ .cols = @intCast(cols),
+ .rows = @intCast(rows),
+ .max_scrollback = if (config.scrollback_limit == 0)
+ std.math.maxInt(usize)
+ else
+ config.scrollback_limit,
+ .colors = colors,
+ },
+ ) catch |err| {
+ log.err("Failed to initialize Terminal: {}", .{err});
+ alloc.destroy(wrapper);
+ return null;
+ };
+
+ // Allocate dirty tracking
+ const rows_usize: usize = @intCast(rows);
+ const dirty_rows = alloc.alloc(bool, rows_usize) catch |err| {
+ log.err("Failed to allocate dirty tracking: {}", .{err});
+ // Note: terminal.deinit() requires the allocator be passed
+ var term_mut = terminal;
+ term_mut.deinit(alloc);
+ alloc.destroy(wrapper);
+ return null;
+ };
+ @memset(dirty_rows, true); // Initially all dirty
+
+ wrapper.* = .{
+ .alloc = alloc,
+ .terminal = terminal,
+ .stream = undefined, // Will be initialized below
+ .dirty_rows = dirty_rows,
+ .config = config,
+ };
+
+ // Initialize the persistent VT stream (must be done after terminal is set)
+ wrapper.stream = wrapper.terminal.vtStream();
+
+ // Enable linefeed mode so \n performs carriage return (moves cursor to column 0)
+ // Without this, \n only moves down without returning to column 0, causing staggered text
+ wrapper.terminal.modes.set(.linefeed, true);
+
+ return @ptrCast(wrapper);
+}
+
+pub fn free(ptr: ?*anyopaque) callconv(.c) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return));
+ const alloc = wrapper.alloc;
+
+ wrapper.stream.deinit();
+ alloc.free(wrapper.dirty_rows);
+ wrapper.terminal.deinit(alloc);
+ alloc.destroy(wrapper);
+}
+
+pub fn resize(ptr: ?*anyopaque, cols: c_int, rows: c_int) callconv(.c) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return));
+
+ // Resize terminal
+ wrapper.terminal.resize(
+ wrapper.alloc,
+ @intCast(cols),
+ @intCast(rows),
+ ) catch |err| {
+ log.err("Resize failed: {}", .{err});
+ return;
+ };
+
+ // Reallocate dirty tracking
+ const rows_usize: usize = @intCast(rows);
+ const new_dirty = wrapper.alloc.realloc(wrapper.dirty_rows, rows_usize) catch |err| {
+ log.err("Failed to reallocate dirty tracking: {}", .{err});
+ return;
+ };
+ wrapper.dirty_rows = new_dirty;
+ @memset(new_dirty, true); // All dirty after resize
+}
+
+// ============================================================================
+// Input/Output
+// ============================================================================
+
+pub fn write(ptr: ?*anyopaque, data: [*]const u8, len: usize) callconv(.c) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return));
+
+ // Use persistent stream to preserve parser state across writes
+ // This is critical for handling escape sequences split across WebSocket messages
+ const slice = data[0..len];
+ wrapper.stream.nextSlice(slice) catch |err| {
+ log.err("Write failed: {}", .{err});
+ return;
+ };
+
+ // Mark all visible rows as dirty (conservative approach)
+ @memset(wrapper.dirty_rows, true);
+}
+
+// ============================================================================
+// Screen Queries
+// ============================================================================
+
+pub fn getCols(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ return @intCast(wrapper.terminal.cols);
+}
+
+pub fn getRows(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ return @intCast(wrapper.terminal.rows);
+}
+
+pub fn getCursorX(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ return @intCast(wrapper.terminal.screen.cursor.x);
+}
+
+pub fn getCursorY(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ return @intCast(wrapper.terminal.screen.cursor.y);
+}
+
+pub fn getCursorVisible(ptr: ?*anyopaque) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ // Check if cursor is visible based on modes
+ return wrapper.terminal.modes.get(.cursor_visible);
+}
+
+pub fn isAlternateScreen(ptr: ?*anyopaque) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ return wrapper.terminal.active_screen == .alternate;
+}
+
+pub fn isRowWrapped(ptr: ?*anyopaque, row: c_int) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ if (row < 0 or row >= wrapper.terminal.rows) return false;
+ if (row == 0) return false;
+ const pt = point.Point{ .viewport = .{ .x = 0, .y = @intCast(row) }};
+ const list_cell = wrapper.terminal.screen.pages.getCell(pt) orelse return false;
+ return list_cell.row.wrap;
+}
+
+pub fn getScrollbackLength(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ // Calculate scrollback length as difference between history top and active top
+ const active_pin = wrapper.terminal.screen.pages.getTopLeft(.active);
+ const screen_pin = wrapper.terminal.screen.pages.getTopLeft(.screen);
+
+ // Count rows between screen top and active top
+ var count: c_int = 0;
+ var pin = screen_pin;
+ while (pin.node != active_pin.node or pin.y != active_pin.y) {
+ count += 1;
+ pin = pin.down(1) orelse break;
+ if (count > 100000) break; // Safety limit
+ }
+ return count;
+}
+
+// ============================================================================
+// Cell Data Access
+// ============================================================================
+
+/// Convert Ghostty's internal Cell to C-compatible GhosttyCell
+/// list_cell_opt can be null if we're using a default empty cell
+fn convertCell(wrapper: *const TerminalWrapper, cell: Cell, list_cell_opt: @TypeOf(wrapper.terminal.screen.pages.getCell(.{.viewport = .{}}))) GhosttyCell {
+ const terminal = &wrapper.terminal;
+ const palette = &terminal.colors.palette.current;
+
+ // Get codepoint
+ const cp = cell.content.codepoint;
+
+ // Get the style - either from the page or use default
+ const cell_style: style.Style = if (cell.style_id == style.default_id)
+ .{}
+ else if (list_cell_opt) |list_cell|
+ list_cell.node.data.styles.get(list_cell.node.data.memory, cell.style_id).*
+ else
+ .{};
+
+ // Resolve foreground color
+ const fg_rgb: color.RGB = fg: {
+ switch (cell_style.fg_color) {
+ .none => {
+ // Use default foreground
+ if (terminal.colors.foreground.get()) |rgb| {
+ break :fg rgb;
+ } else {
+ // Default to white
+ break :fg .{ .r = 0xEA, .g = 0xEA, .b = 0xEA };
+ }
+ },
+ .palette => |idx| break :fg palette[idx],
+ .rgb => |rgb| break :fg rgb,
+ }
+ };
+
+ // Resolve background color
+ const bg_rgb: color.RGB = bg: {
+ // Check for cell-level color override
+ if (cell_style.bg(&cell, palette)) |rgb| {
+ break :bg rgb;
+ }
+
+ // Use default background
+ if (terminal.colors.background.get()) |rgb| {
+ break :bg rgb;
+ } else {
+ // Default to black
+ break :bg .{ .r = 0x1D, .g = 0x1F, .b = 0x21 };
+ }
+ };
+
+ // Build flags bitfield
+ var flags: u8 = 0;
+ if (cell_style.flags.bold) flags |= 1 << 0;
+ if (cell_style.flags.italic) flags |= 1 << 1;
+ if (cell_style.flags.underline != .none) flags |= 1 << 2;
+ if (cell_style.flags.strikethrough) flags |= 1 << 3;
+ if (cell_style.flags.inverse) flags |= 1 << 4;