forked from coder/ghostty-web
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathghostty-wasm-api.patch
More file actions
1011 lines (1006 loc) · 39.6 KB
/
Copy pathghostty-wasm-api.patch
File metadata and controls
1011 lines (1006 loc) · 39.6 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/src/build/GhosttyZig.zig b/src/build/GhosttyZig.zig
index 44c300e15..e447079d4 100644
--- a/src/build/GhosttyZig.zig
+++ b/src/build/GhosttyZig.zig
@@ -137,6 +137,11 @@ fn initVt(
// We need uucode for grapheme break support
deps.addUucode(b, vt, cfg.target, cfg.optimize);
+ if (b.lazyDependency("z2d", .{
+ .target = cfg.target,
+ .optimize = cfg.optimize,
+ })) |dep| vt.addImport("z2d", dep.module("z2d"));
+
// If SIMD is enabled, add all our SIMD dependencies.
if (cfg.simd) {
try SharedDeps.addSimd(b, vt, simd_libs);
diff --git a/src/font/main.zig b/src/font/main.zig
index 0c218bbda..b8b974ed3 100644
--- a/src/font/main.zig
+++ b/src/font/main.zig
@@ -32,7 +32,7 @@ pub const Library = library.Library;
// If we're targeting wasm then we export some wasm APIs.
comptime {
- if (builtin.target.cpu.arch.isWasm()) {
+ if (builtin.target.cpu.arch.isWasm() and !@hasDecl(@import("root"), "ghostty_lib_vt_sprite_only")) {
_ = Atlas.Wasm;
_ = DeferredFace.Wasm;
_ = face.web_canvas.Wasm;
diff --git a/src/font/sprite/Face.zig b/src/font/sprite/Face.zig
index f5df2d421..846583040 100644
--- a/src/font/sprite/Face.zig
+++ b/src/font/sprite/Face.zig
@@ -15,7 +15,6 @@ const Face = @This();
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
-const wuffs = @import("wuffs");
const z2d = @import("z2d");
const font = @import("../main.zig");
const Sprite = font.sprite.Sprite;
@@ -242,6 +241,7 @@ fn testDiffAtlas(
) !bool {
// Get the file contents, we compare the PNG data first in
// order to ensure that no one smuggles arbitrary binary
+ const wuffs = @import("wuffs");
// data in to the reference PNGs.
const test_file = try std.fs.openFileAbsolute(path, .{ .mode = .read_only });
defer test_file.close();
diff --git a/src/lib_vt.zig b/src/lib_vt.zig
index 6d4406e88..49d94d3be 100644
--- a/src/lib_vt.zig
+++ b/src/lib_vt.zig
@@ -8,6 +8,7 @@
//! types, etc.) may change without warning. We're working on stabilizing
//! this in the future.
const lib = @This();
+pub const ghostty_lib_vt_sprite_only = {};
const std = @import("std");
const builtin = @import("builtin");
@@ -212,7 +213,7 @@ comptime {
@export(&c.terminal_selection_format_buf, .{ .name = "ghostty_terminal_selection_format_buf" });
@export(&c.terminal_selection_format_alloc, .{ .name = "ghostty_terminal_selection_format_alloc" });
@export(&c.render_state_new, .{ .name = "ghostty_render_state_new" });
- @export(&c.render_state_update, .{ .name = "ghostty_render_state_update" });
+ @export(&c.render_state_update, .{ .name = "ghostty_core_render_state_update" });
@export(&c.render_state_get, .{ .name = "ghostty_render_state_get" });
@export(&c.render_state_get_multi, .{ .name = "ghostty_render_state_get_multi" });
@export(&c.render_state_set, .{ .name = "ghostty_render_state_set" });
@@ -230,10 +231,41 @@ comptime {
@export(&c.render_state_row_cells_get_multi, .{ .name = "ghostty_render_state_row_cells_get_multi" });
@export(&c.render_state_row_cells_free, .{ .name = "ghostty_render_state_row_cells_free" });
@export(&c.render_state_free, .{ .name = "ghostty_render_state_free" });
- @export(&c.terminal_new, .{ .name = "ghostty_terminal_new" });
- @export(&c.terminal_free, .{ .name = "ghostty_terminal_free" });
+ @export(&c.web.new, .{ .name = "ghostty_terminal_new" });
+ @export(&c.web.newWithConfig, .{ .name = "ghostty_terminal_new_with_config" });
+ @export(&c.web.free, .{ .name = "ghostty_terminal_free" });
+ @export(&c.web.resize, .{ .name = "ghostty_terminal_resize" });
+ @export(&c.web.write, .{ .name = "ghostty_terminal_write" });
+ @export(&c.web.setColorScheme, .{ .name = "ghostty_terminal_set_color_scheme" });
+ @export(&c.web.setConfig, .{ .name = "ghostty_terminal_set_config" });
+ @export(&c.web.renderStateUpdate, .{ .name = "ghostty_render_state_update" });
+ @export(&c.web.renderStateGetCols, .{ .name = "ghostty_render_state_get_cols" });
+ @export(&c.web.renderStateGetRows, .{ .name = "ghostty_render_state_get_rows" });
+ @export(&c.web.renderStateGetCursorX, .{ .name = "ghostty_render_state_get_cursor_x" });
+ @export(&c.web.renderStateGetCursorY, .{ .name = "ghostty_render_state_get_cursor_y" });
+ @export(&c.web.renderStateGetCursorVisible, .{ .name = "ghostty_render_state_get_cursor_visible" });
+ @export(&c.web.renderStateGetBgColor, .{ .name = "ghostty_render_state_get_bg_color" });
+ @export(&c.web.renderStateGetFgColor, .{ .name = "ghostty_render_state_get_fg_color" });
+ @export(&c.web.renderStateIsRowDirty, .{ .name = "ghostty_render_state_is_row_dirty" });
+ @export(&c.web.renderStateMarkClean, .{ .name = "ghostty_render_state_mark_clean" });
+ @export(&c.web.renderStateGetViewport, .{ .name = "ghostty_render_state_get_viewport" });
+ @export(&c.web.renderStateGetGrapheme, .{ .name = "ghostty_render_state_get_grapheme" });
+ @export(&c.web.isAlternateScreen, .{ .name = "ghostty_terminal_is_alternate_screen" });
+ @export(&c.web.hasMouseTracking, .{ .name = "ghostty_terminal_has_mouse_tracking" });
+ @export(&c.web.getMode, .{ .name = "ghostty_terminal_get_mode" });
+ @export(&c.web.getScrollbackLength, .{ .name = "ghostty_terminal_get_scrollback_length" });
+ @export(&c.web.getScrollbackLine, .{ .name = "ghostty_terminal_get_scrollback_line" });
+ @export(&c.web.getScrollbackGrapheme, .{ .name = "ghostty_terminal_get_scrollback_grapheme" });
+ @export(&c.web.isRowWrapped, .{ .name = "ghostty_terminal_is_row_wrapped" });
+ @export(&c.web.getHyperlinkUri, .{ .name = "ghostty_terminal_get_hyperlink_uri" });
+ @export(&c.web.getScrollbackHyperlinkUri, .{ .name = "ghostty_terminal_get_scrollback_hyperlink_uri" });
+ @export(&c.web.hasResponse, .{ .name = "ghostty_terminal_has_response" });
+ @export(&c.web.readResponse, .{ .name = "ghostty_terminal_read_response" });
+
+ @export(&c.terminal_new, .{ .name = "ghostty_core_terminal_new" });
+ @export(&c.terminal_free, .{ .name = "ghostty_core_terminal_free" });
@export(&c.terminal_reset, .{ .name = "ghostty_terminal_reset" });
- @export(&c.terminal_resize, .{ .name = "ghostty_terminal_resize" });
+ @export(&c.terminal_resize, .{ .name = "ghostty_core_terminal_resize" });
@export(&c.terminal_set, .{ .name = "ghostty_terminal_set" });
@export(&c.terminal_vt_write, .{ .name = "ghostty_terminal_vt_write" });
@export(&c.terminal_scroll_viewport, .{ .name = "ghostty_terminal_scroll_viewport" });
@@ -289,6 +321,8 @@ comptime {
@export(&c.tracked_grid_ref_point, .{ .name = "ghostty_tracked_grid_ref_point" });
@export(&c.tracked_grid_ref_set, .{ .name = "ghostty_tracked_grid_ref_set" });
@export(&c.tracked_grid_ref_snapshot, .{ .name = "ghostty_tracked_grid_ref_snapshot" });
+ @export(&c.sprite_web.hasCodepoint, .{ .name = "ghostty_sprite_has_codepoint" });
+ @export(&c.sprite_web.rasterize, .{ .name = "ghostty_sprite_rasterize" });
@export(&c.build_info, .{ .name = "ghostty_build_info" });
@export(&c.type_json, .{ .name = "ghostty_type_json" });
@export(&c.alloc_alloc, .{ .name = "ghostty_alloc" });
diff --git a/src/terminal/c/main.zig b/src/terminal/c/main.zig
index 648bdbe51..7e7d1b2f7 100644
--- a/src/terminal/c/main.zig
+++ b/src/terminal/c/main.zig
@@ -43,12 +43,14 @@ pub const size_report = @import("size_report.zig");
pub const style = @import("style.zig");
pub const sys = @import("sys.zig");
pub const terminal = @import("terminal.zig");
+pub const web = @import("web.zig");
// The full C API, unexported.
pub const build_info = buildpkg.get;
pub const osc_new = osc.new;
pub const osc_free = osc.free;
+pub const sprite_web = @import("sprite_web.zig");
pub const osc_reset = osc.reset;
pub const osc_next = osc.next;
pub const osc_end = osc.end;
diff --git a/src/terminal/c/sprite_web.zig b/src/terminal/c/sprite_web.zig
new file mode 100644
index 000000000..87efc96ca
--- /dev/null
+++ b/src/terminal/c/sprite_web.zig
@@ -0,0 +1,80 @@
+const std = @import("std");
+const builtin = @import("builtin");
+const font = @import("../../font/main.zig");
+const SpriteFace = font.sprite.Face;
+
+pub const Bitmap = extern struct {
+ width: u32,
+ height: u32,
+ offset_x: i32,
+ offset_y: i32,
+ len: u32,
+};
+
+pub fn hasCodepoint(cp: u32) callconv(.c) bool {
+ const face: SpriteFace = .{ .metrics = undefined };
+ return face.hasCodepoint(cp, null);
+}
+
+pub fn rasterize(
+ cp: u32,
+ cell_width: u32,
+ cell_height: u32,
+ box_thickness: u32,
+ out: [*]u8,
+ out_len: usize,
+ result: *Bitmap,
+) callconv(.c) bool {
+ if (cell_width == 0 or cell_height == 0 or box_thickness == 0) return false;
+
+ const metrics: font.Metrics = .{
+ .cell_width = cell_width,
+ .cell_height = cell_height,
+ .cell_baseline = cell_height / 4,
+ .underline_position = cell_height -| box_thickness,
+ .underline_thickness = box_thickness,
+ .strikethrough_position = cell_height / 2,
+ .strikethrough_thickness = box_thickness,
+ .overline_position = 0,
+ .overline_thickness = box_thickness,
+ .box_thickness = box_thickness,
+ .cursor_thickness = box_thickness,
+ .cursor_height = cell_height,
+ .icon_height = @floatFromInt(cell_height),
+ .icon_height_single = @floatFromInt(cell_height),
+ .face_width = @floatFromInt(cell_width),
+ .face_height = @floatFromInt(cell_height),
+ .face_y = 0,
+ };
+ const face: SpriteFace = .{ .metrics = metrics };
+ if (!face.hasCodepoint(cp, null)) return false;
+
+ const alloc = if (builtin.target.cpu.arch.isWasm()) std.heap.wasm_allocator else std.heap.c_allocator;
+ const padded_width = cell_width + 2 * (cell_width / 4);
+ const padded_height = cell_height + 2 * (cell_height / 4);
+ var atlas = font.Atlas.init(alloc, @max(padded_width, padded_height) + 2, .grayscale) catch return false;
+ defer atlas.deinit(alloc);
+
+ const glyph = face.renderGlyph(alloc, &atlas, cp, .{ .grid_metrics = metrics }) catch return false;
+ const len: usize = @as(usize, cell_width) * cell_height;
+ if (out_len < len) return false;
+ @memset(out[0..len], 0);
+ for (0..glyph.height) |y| {
+ for (0..glyph.width) |x| {
+ const dst_x = glyph.offset_x + @as(i32, @intCast(x));
+ const dst_y = @as(i32, @intCast(cell_height)) - glyph.offset_y + @as(i32, @intCast(y));
+ if (dst_x < 0 or dst_y < 0 or dst_x >= cell_width or dst_y >= cell_height) continue;
+ const src = @as(usize, glyph.atlas_y + @as(u32, @intCast(y))) * atlas.size + glyph.atlas_x + x;
+ const dst = @as(usize, @intCast(dst_y)) * cell_width + @as(usize, @intCast(dst_x));
+ out[dst] = atlas.data[src];
+ }
+ }
+ result.* = .{
+ .width = cell_width,
+ .height = cell_height,
+ .offset_x = 0,
+ .offset_y = @intCast(cell_height),
+ .len = @intCast(len),
+ };
+ return true;
+}
diff --git a/src/terminal/c/web.zig b/src/terminal/c/web.zig
new file mode 100644
index 000000000..874853d57
--- /dev/null
+++ b/src/terminal/c/web.zig
@@ -0,0 +1,776 @@
+//! ghostty-web compatibility API for libghostty-vt.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const builtin = @import("builtin");
+const lib = @import("../lib.zig");
+const terminal_c = @import("terminal.zig");
+const Terminal = terminal_c.ZigTerminal;
+const render = @import("../render.zig");
+const RenderState = render.RenderState;
+const color = @import("../color.zig");
+const device_status = @import("../device_status.zig");
+const modespkg = @import("../modes.zig");
+const pagepkg = @import("../page.zig");
+const Page = pagepkg.Page;
+const Style = @import("../style.zig").Style;
+
+const TerminalWrapper = struct {
+ alloc: Allocator,
+ terminal: terminal_c.Terminal,
+ render_state: RenderState = .empty,
+ response_buffer: std.ArrayList(u8) = .empty,
+ color_scheme: ?device_status.ColorScheme = null,
+ last_screen_is_alternate: bool = false,
+};
+
+fn zigTerminal(wrapper: anytype) *Terminal {
+ return terminal_c.zigTerminal(wrapper.terminal).?;
+}
+
+fn responseCallback(_: terminal_c.Terminal, userdata: ?*anyopaque, data: [*]const u8, len: usize) callconv(lib.calling_conv) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(userdata orelse return));
+ wrapper.response_buffer.appendSlice(wrapper.alloc, data[0..len]) catch {};
+}
+
+fn colorSchemeCallback(_: terminal_c.Terminal, userdata: ?*anyopaque, scheme: *device_status.ColorScheme) callconv(lib.calling_conv) bool {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(userdata orelse return false));
+ scheme.* = wrapper.color_scheme orelse return false;
+ return true;
+}
+
+/// C-compatible cell structure (16 bytes)
+pub const GhosttyCell = extern struct {
+ codepoint: u32,
+ fg_r: u8,
+ fg_g: u8,
+ fg_b: u8,
+ bg_r: u8,
+ bg_g: u8,
+ bg_b: u8,
+ flags: u8,
+ width: u8,
+ hyperlink_id: u16,
+ grapheme_len: u8 = 0, // Number of extra codepoints beyond first
+ _pad: u8 = 0,
+};
+
+/// Dirty state
+pub const GhosttyDirty = enum(u8) {
+ none = 0,
+ partial = 1,
+ full = 2,
+};
+
+/// 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
+// ============================================================================
+
+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 {
+ if (cols <= 0 or rows <= 0) return null;
+ const alloc = if (builtin.target.cpu.arch.isWasm()) std.heap.wasm_allocator else std.heap.c_allocator;
+ const wrapper = alloc.create(TerminalWrapper) catch return null;
+ wrapper.* = .{ .alloc = alloc, .terminal = null };
+
+ const scrollback_lines: usize = if (config) |cfg|
+ if (cfg.scrollback_limit == 0) std.math.maxInt(usize) else cfg.scrollback_limit
+ else
+ 10_000;
+ const max_scrollback: usize = if (scrollback_lines == std.math.maxInt(usize))
+ std.math.maxInt(usize)
+ else blk: {
+ const capacity = pagepkg.std_capacity.adjust(.{ .cols = @intCast(cols) }) catch
+ break :blk scrollback_lines * 1024;
+ const page_size = Page.layout(capacity).total_size;
+ break :blk scrollback_lines * (page_size / capacity.rows);
+ };
+ if (terminal_c.new(null, &wrapper.terminal, .{
+ .cols = @intCast(cols),
+ .rows = @intCast(rows),
+ .max_scrollback = max_scrollback,
+ }) != .success) {
+ alloc.destroy(wrapper);
+ return null;
+ }
+
+ const t = zigTerminal(wrapper);
+ if (config) |cfg| applyConfig(wrapper, cfg);
+ t.modes.set(.linefeed, false);
+ t.modes.set(.grapheme_cluster, true);
+
+ _ = terminal_c.set(wrapper.terminal, .userdata, wrapper);
+ _ = terminal_c.set(wrapper.terminal, .write_pty, @ptrCast(&responseCallback));
+ _ = terminal_c.set(wrapper.terminal, .color_scheme, @ptrCast(&colorSchemeCallback));
+ return @ptrCast(wrapper);
+}
+
+pub fn setColorScheme(ptr: ?*anyopaque, scheme_raw: c_int) callconv(.c) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return));
+ const scheme = std.meta.intToEnum(device_status.ColorScheme, scheme_raw) catch return;
+ if (wrapper.color_scheme == scheme) return;
+ wrapper.color_scheme = scheme;
+ if (!zigTerminal(wrapper).modes.get(.report_color_scheme)) return;
+ const response = switch (scheme) {
+ .dark => "\x1B[?997;1n",
+ .light => "\x1B[?997;2n",
+ };
+ wrapper.response_buffer.appendSlice(wrapper.alloc, response) catch {};
+}
+
+pub fn setConfig(ptr: ?*anyopaque, config: ?*const GhosttyTerminalConfig) callconv(.c) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return));
+ applyConfig(wrapper, config orelse return);
+}
+
+fn applyConfig(wrapper: *TerminalWrapper, config: *const GhosttyTerminalConfig) void {
+ const t = zigTerminal(wrapper);
+ t.colors.foreground.default = colorFromInt(config.fg_color);
+ t.colors.background.default = colorFromInt(config.bg_color);
+ t.colors.cursor.default = colorFromInt(config.cursor_color);
+ var palette = t.colors.palette.original;
+ for (config.palette, 0..) |value, i| {
+ palette[i] = colorFromInt(value);
+ }
+ t.colors.palette.changeDefault(palette);
+}
+
+fn colorFromInt(value: u32) color.RGB {
+ return .{
+ .r = @truncate((value >> 16) & 0xff),
+ .g = @truncate((value >> 8) & 0xff),
+ .b = @truncate(value & 0xff),
+ };
+}
+
+pub fn free(ptr: ?*anyopaque) callconv(.c) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return));
+ const alloc = wrapper.alloc;
+ wrapper.response_buffer.deinit(alloc);
+ wrapper.render_state.deinit(alloc);
+ terminal_c.free(wrapper.terminal);
+ 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));
+ if (cols <= 0 or rows <= 0) return;
+ _ = terminal_c.resize(wrapper.terminal, @intCast(cols), @intCast(rows), 0, 0);
+}
+
+pub fn write(ptr: ?*anyopaque, data: [*]const u8, len: usize) callconv(.c) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return));
+ terminal_c.vt_write(wrapper.terminal, data, len);
+}
+
+// ============================================================================
+// RenderState API - High-performance rendering
+// ============================================================================
+
+/// Update render state from terminal. Call once per frame.
+/// Returns dirty state: 0=none, 1=partial, 2=full
+pub fn renderStateUpdate(ptr: ?*anyopaque) callconv(.c) GhosttyDirty {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return .full));
+
+ // Detect screen buffer switch (normal <-> alternate)
+ const current_is_alternate = zigTerminal(wrapper).screens.active_key == .alternate;
+ const screen_switched = current_is_alternate != wrapper.last_screen_is_alternate;
+ wrapper.last_screen_is_alternate = current_is_alternate;
+
+ // When screen switches, we must fully reset the render state to avoid
+ // stale cached cell data from the previous screen buffer.
+ if (screen_switched) {
+ wrapper.render_state.deinit(wrapper.alloc);
+ wrapper.render_state = RenderState.empty;
+ }
+
+ wrapper.render_state.update(wrapper.alloc, zigTerminal(wrapper)) catch return .full;
+
+ // If screen switched, always return full dirty to force complete redraw
+ if (screen_switched) {
+ return .full;
+ }
+
+ return switch (wrapper.render_state.dirty) {
+ .false => .none,
+ .partial => .partial,
+ .full => .full,
+ };
+}
+
+/// Get dimensions from render state
+pub fn renderStateGetCols(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ return @intCast(wrapper.render_state.cols);
+}
+
+pub fn renderStateGetRows(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ return @intCast(wrapper.render_state.rows);
+}
+
+/// Get cursor X position
+pub fn renderStateGetCursorX(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ return @intCast(wrapper.render_state.cursor.active.x);
+}
+
+/// Get cursor Y position
+pub fn renderStateGetCursorY(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ return @intCast(wrapper.render_state.cursor.active.y);
+}
+
+/// Check if cursor is visible
+pub fn renderStateGetCursorVisible(ptr: ?*anyopaque) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ return wrapper.render_state.cursor.visible;
+}
+
+/// Get default background color as 0xRRGGBB
+pub fn renderStateGetBgColor(ptr: ?*anyopaque) callconv(.c) u32 {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ const bg = wrapper.render_state.colors.background;
+ return (@as(u32, bg.r) << 16) | (@as(u32, bg.g) << 8) | bg.b;
+}
+
+/// Get default foreground color as 0xRRGGBB
+pub fn renderStateGetFgColor(ptr: ?*anyopaque) callconv(.c) u32 {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0xCCCCCC));
+ const fg = wrapper.render_state.colors.foreground;
+ return (@as(u32, fg.r) << 16) | (@as(u32, fg.g) << 8) | fg.b;
+}
+
+/// Check if row is dirty
+pub fn renderStateIsRowDirty(ptr: ?*anyopaque, y: c_int) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return true));
+ if (wrapper.render_state.dirty == .full) return true;
+ if (wrapper.render_state.dirty == .false) return false;
+ const y_usize: usize = @intCast(y);
+ if (y_usize >= wrapper.render_state.row_data.len) return false;
+ return wrapper.render_state.row_data.items(.dirty)[y_usize];
+}
+
+/// Mark render state as clean after rendering
+pub fn renderStateMarkClean(ptr: ?*anyopaque) callconv(.c) void {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return));
+ wrapper.render_state.dirty = .false;
+ @memset(wrapper.render_state.row_data.items(.dirty), false);
+}
+
+/// Get ALL viewport cells in one call - reads directly from terminal screen buffer.
+/// Uses the cached row pins from RenderState (built during update()) to read
+/// cell data. This matches the native renderer which uses the same cached pins
+/// rather than re-iterating the page list.
+/// Returns total cells written (rows * cols), or -1 on error.
+pub fn renderStateGetViewport(
+ ptr: ?*anyopaque,
+ out: [*]GhosttyCell,
+ buf_size: usize,
+) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return -1));
+ const rs = &wrapper.render_state;
+ const rows = rs.rows;
+ const cols = rs.cols;
+ const total: usize = @as(usize, rows) * cols;
+
+ if (buf_size < total) return -1;
+
+ const default_cell: GhosttyCell = .{
+ .codepoint = 0,
+ .fg_r = rs.colors.foreground.r,
+ .fg_g = rs.colors.foreground.g,
+ .fg_b = rs.colors.foreground.b,
+ .bg_r = rs.colors.background.r,
+ .bg_g = rs.colors.background.g,
+ .bg_b = rs.colors.background.b,
+ .flags = 0,
+ .width = 1,
+ .hyperlink_id = 0,
+ };
+
+ // Use the cached row pins from RenderState, built during update().
+ // The native renderer also reads from these cached pins rather than
+ // re-iterating the page list, which avoids any inconsistency from
+ // independent top-left resolution across page boundaries.
+ const row_pins = rs.row_data.items(.pin);
+
+ var idx: usize = 0;
+ for (0..rows) |y| {
+ if (y >= row_pins.len) {
+ // Row not in cache — fill with defaults
+ for (0..cols) |_| {
+ out[idx] = default_cell;
+ idx += 1;
+ }
+ continue;
+ }
+
+ const row_pin = row_pins[y];
+ const row_cells = row_pin.cells(.all);
+ const page = &row_pin.node.data;
+
+ for (0..cols) |x| {
+ if (x >= row_cells.len) {
+ out[idx] = default_cell;
+ idx += 1;
+ continue;
+ }
+
+ const cell = &row_cells[x];
+
+ // Get style from page styles (cell has style_id)
+ const sty: Style = if (cell.style_id > 0)
+ page.styles.get(page.memory, cell.style_id).*
+ else
+ .{};
+
+ // Resolve colors
+ const fg: color.RGB = switch (sty.fg_color) {
+ .none => rs.colors.foreground,
+ .palette => |i| rs.colors.palette[i],
+ .rgb => |rgb| rgb,
+ };
+ const bg: color.RGB = if (sty.bg(cell, &rs.colors.palette)) |rgb| rgb else rs.colors.background;
+
+ // Build flags
+ var flags: u8 = 0;
+ if (sty.flags.bold) flags |= 1 << 0;
+ if (sty.flags.italic) flags |= 1 << 1;
+ if (sty.flags.underline != .none) flags |= 1 << 2;
+ if (sty.flags.strikethrough) flags |= 1 << 3;
+ if (sty.flags.inverse) flags |= 1 << 4;
+ if (sty.flags.invisible) flags |= 1 << 5;
+ if (sty.flags.blink) flags |= 1 << 6;
+ if (sty.flags.faint) flags |= 1 << 7;
+
+ // Get grapheme length if cell has grapheme data
+ const grapheme_len: u8 = if (cell.hasGrapheme())
+ if (page.lookupGrapheme(cell)) |cps| @min(@as(u8, @intCast(cps.len)), 255) else 0
+ else
+ 0;
+
+ out[idx] = .{
+ .codepoint = cell.codepoint(),
+ .fg_r = fg.r,
+ .fg_g = fg.g,
+ .fg_b = fg.b,
+ .bg_r = bg.r,
+ .bg_g = bg.g,
+ .bg_b = bg.b,
+ .flags = flags,
+ .width = switch (cell.wide) {
+ .narrow => 1,
+ .wide => 2,
+ .spacer_tail, .spacer_head => 0,
+ },
+ .hyperlink_id = if (cell.hyperlink) 1 else 0,
+ .grapheme_len = grapheme_len,
+ };
+ idx += 1;
+ }
+ }
+
+ return @intCast(total);
+}
+
+/// Get grapheme codepoints for a cell at (row, col).
+/// Returns all codepoints (including the first one) as u32 values.
+/// Returns the number of codepoints written, or -1 on error.
+pub fn renderStateGetGrapheme(
+ ptr: ?*anyopaque,
+ row: c_int,
+ col: c_int,
+ out: [*]u32,
+ buf_size: usize,
+) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return -1));
+ const rs = &wrapper.render_state;
+ const t = zigTerminal(wrapper);
+ const cols: usize = @intCast(rs.cols);
+
+ if (row < 0 or col < 0) return -1;
+ if (@as(usize, @intCast(row)) >= rs.rows) return -1;
+ if (@as(usize, @intCast(col)) >= cols) return -1;
+ if (buf_size < 1) return -1;
+
+ // Get the pin for this row from the terminal's active screen
+ const pages = &t.screens.active.pages;
+ const pin = pages.pin(.{ .active = .{ .y = @intCast(row) } }) orelse return -1;
+
+ const cells = pin.cells(.all);
+ const page = pin.node.data;
+ const x: usize = @intCast(col);
+
+ if (x >= cells.len) return -1;
+
+ const cell = &cells[x];
+
+ // First codepoint is always from the cell
+ out[0] = cell.codepoint();
+ var count: usize = 1;
+
+ // Add extra codepoints from grapheme map if present
+ if (cell.hasGrapheme()) {
+ if (page.lookupGrapheme(cell)) |cps| {
+ for (cps) |cp| {
+ if (count >= buf_size) break;
+ out[count] = cp;
+ count += 1;
+ }
+ }
+ }
+
+ return @intCast(count);
+}
+
+// ============================================================================
+// Terminal Modes (minimal set for compatibility)
+// ============================================================================
+
+pub fn isAlternateScreen(ptr: ?*anyopaque) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ return zigTerminal(wrapper).screens.active_key == .alternate;
+}
+
+pub fn hasMouseTracking(ptr: ?*anyopaque) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ return zigTerminal(wrapper).modes.get(.mouse_event_normal) or
+ zigTerminal(wrapper).modes.get(.mouse_event_button) or
+ zigTerminal(wrapper).modes.get(.mouse_event_any);
+}
+
+/// Query arbitrary terminal mode by number
+/// Returns true if mode is set, false otherwise
+pub fn getMode(ptr: ?*anyopaque, mode_num: c_int, is_ansi: bool) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ const mode = modespkg.modeFromInt(@intCast(mode_num), is_ansi) orelse return false;
+ return zigTerminal(wrapper).modes.get(mode);
+}
+
+// ============================================================================
+// Scrollback API
+// ============================================================================
+
+/// Get the number of scrollback lines (history, not including active screen)
+pub fn getScrollbackLength(ptr: ?*anyopaque) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return 0));
+ const pages = zigTerminal(wrapper).screens.active.pages;
+ // total_rows includes both scrollback and active area
+ // We subtract rows (active area) to get just scrollback
+ if (pages.total_rows <= pages.rows) return 0;
+ return @intCast(pages.total_rows - pages.rows);
+}
+
+/// Get a line from the scrollback buffer
+/// offset 0 = oldest line in scrollback, offset (length-1) = most recent scrollback line
+/// Returns number of cells written, or -1 on error
+pub fn getScrollbackLine(
+ ptr: ?*anyopaque,
+ offset: c_int,
+ out: [*]GhosttyCell,
+ buf_size: usize,
+) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return -1));
+ const rs = &wrapper.render_state;
+ const cols = rs.cols;
+
+ if (buf_size < cols) return -1;
+ if (offset < 0) return -1;
+
+ const scrollback_len = getScrollbackLength(ptr);
+ if (offset >= scrollback_len) return -1;
+
+ // Get the pin for this scrollback row
+ // history point: y=0 is oldest, y=scrollback_len-1 is newest
+ const pages = zigTerminal(wrapper).screens.active.pages;
+ const pin = pages.pin(.{ .history = .{ .y = @intCast(offset) } }) orelse return -1;
+
+ // Get cells for this row
+ const cells = pin.cells(.all);
+ const page = pin.node.data;
+
+ // Fill output buffer
+ for (0..cols) |x| {
+ if (x >= cells.len) {
+ // Fill with default
+ out[x] = .{
+ .codepoint = 0,
+ .fg_r = rs.colors.foreground.r,
+ .fg_g = rs.colors.foreground.g,
+ .fg_b = rs.colors.foreground.b,
+ .bg_r = rs.colors.background.r,
+ .bg_g = rs.colors.background.g,
+ .bg_b = rs.colors.background.b,
+ .flags = 0,
+ .width = 1,
+ .hyperlink_id = 0,
+ };
+ continue;
+ }
+
+ const cell = &cells[x];
+
+ // Get style from page styles (cell has style_id)
+ const sty: Style = if (cell.style_id > 0)
+ page.styles.get(page.memory, cell.style_id).*
+ else
+ .{};
+
+ // Resolve colors
+ const fg: color.RGB = switch (sty.fg_color) {
+ .none => rs.colors.foreground,
+ .palette => |i| rs.colors.palette[i],
+ .rgb => |rgb| rgb,
+ };
+ const bg: color.RGB = if (sty.bg(cell, &rs.colors.palette)) |rgb| rgb else rs.colors.background;
+
+ // Build flags
+ var flags: u8 = 0;
+ if (sty.flags.bold) flags |= 1 << 0;
+ if (sty.flags.italic) flags |= 1 << 1;
+ if (sty.flags.underline != .none) flags |= 1 << 2;
+ if (sty.flags.strikethrough) flags |= 1 << 3;
+ if (sty.flags.inverse) flags |= 1 << 4;
+ if (sty.flags.invisible) flags |= 1 << 5;
+ if (sty.flags.blink) flags |= 1 << 6;
+ if (sty.flags.faint) flags |= 1 << 7;
+
+ // Get grapheme length if cell has grapheme data
+ const grapheme_len: u8 = if (cell.hasGrapheme())
+ if (page.lookupGrapheme(cell)) |cps| @min(@as(u8, @intCast(cps.len)), 255) else 0
+ else
+ 0;
+
+ out[x] = .{
+ .codepoint = cell.codepoint(),
+ .fg_r = fg.r,
+ .fg_g = fg.g,
+ .fg_b = fg.b,
+ .bg_r = bg.r,
+ .bg_g = bg.g,
+ .bg_b = bg.b,
+ .flags = flags,
+ .width = switch (cell.wide) {
+ .narrow => 1,
+ .wide => 2,
+ .spacer_tail, .spacer_head => 0,
+ },
+ .hyperlink_id = if (cell.hyperlink) 1 else 0,
+ .grapheme_len = grapheme_len,
+ };
+ }
+ return @intCast(cols);
+}
+
+/// Get grapheme codepoints for a cell in the scrollback buffer.
+/// Returns all codepoints (including the first one) as u32 values.
+/// Returns the number of codepoints written, or -1 on error.
+pub fn getScrollbackGrapheme(
+ ptr: ?*anyopaque,
+ offset: c_int,
+ col: c_int,
+ out: [*]u32,
+ buf_size: usize,
+) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return -1));
+ const rs = &wrapper.render_state;
+ const cols: usize = @intCast(rs.cols);
+
+ if (offset < 0 or col < 0) return -1;
+ if (@as(usize, @intCast(col)) >= cols) return -1;
+ if (buf_size < 1) return -1;
+
+ const scrollback_len = getScrollbackLength(ptr);
+ if (offset >= scrollback_len) return -1;
+
+ // Get the pin for this scrollback row
+ const pages = zigTerminal(wrapper).screens.active.pages;
+ const pin = pages.pin(.{ .history = .{ .y = @intCast(offset) } }) orelse return -1;
+
+ const cells = pin.cells(.all);
+ const page = pin.node.data;
+ const x: usize = @intCast(col);
+
+ if (x >= cells.len) return -1;
+
+ const cell = &cells[x];
+
+ // First codepoint is always from the cell
+ out[0] = cell.codepoint();
+ var count: usize = 1;
+
+ // Add extra codepoints from grapheme map if present
+ if (cell.hasGrapheme()) {
+ if (page.lookupGrapheme(cell)) |cps| {
+ for (cps) |cp| {
+ if (count >= buf_size) break;
+ out[count] = cp;
+ count += 1;
+ }
+ }
+ }
+
+ return @intCast(count);
+}
+
+/// Check if a row is a continuation from the previous row (soft-wrapped)
+/// This matches xterm.js semantics where isWrapped indicates the row continues
+/// from the previous row, not that it wraps to the next row.
+pub fn isRowWrapped(ptr: ?*anyopaque, y: c_int) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ const pages = zigTerminal(wrapper).screens.active.pages;
+
+ // Get pin for this row in active area
+ const pin = pages.pin(.{ .active = .{ .y = @intCast(y) } }) orelse return false;
+ const rac = pin.rowAndCell();
+
+ // wrap_continuation means this row continues from the previous row
+ return rac.row.wrap_continuation;
+}
+
+// ============================================================================
+// Hyperlink API
+// ============================================================================
+
+/// Get the hyperlink URI for a cell in the active viewport.
+/// Returns number of bytes written, 0 if no hyperlink, -1 on error.
+pub fn getHyperlinkUri(
+ ptr: ?*anyopaque,
+ row: c_int,
+ col: c_int,
+ out: [*]u8,
+ buf_size: usize,
+) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return -1));
+ const t = zigTerminal(wrapper);
+
+ if (row < 0 or col < 0) return -1;
+
+ // Get the pin for this row from the terminal's active screen
+ const pages = &t.screens.active.pages;
+ const pin = pages.pin(.{ .active = .{ .y = @intCast(row) } }) orelse return -1;
+
+ const cells = pin.cells(.all);
+ const page = pin.node.data;
+ const x: usize = @intCast(col);
+
+ if (x >= cells.len) return -1;
+
+ const cell = &cells[x];
+
+ // Check if cell has a hyperlink
+ if (!cell.hyperlink) return 0;
+
+ // Look up the hyperlink ID from the page
+ const hyperlink_id = page.lookupHyperlink(cell) orelse return 0;
+
+ // Get the hyperlink entry from the set
+ const hyperlink_entry = page.hyperlink_set.get(page.memory, hyperlink_id);
+
+ // Get the URI bytes from the page memory
+ const uri = hyperlink_entry.uri.slice(page.memory);
+
+ if (uri.len == 0) return 0;
+ if (buf_size < uri.len) return -1;
+
+ @memcpy(out[0..uri.len], uri);
+ return @intCast(uri.len);
+}
+
+/// 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 number of bytes written, 0 if no hyperlink, -1 on error.
+pub fn getScrollbackHyperlinkUri(
+ ptr: ?*anyopaque,
+ offset: c_int,
+ col: c_int,
+ out: [*]u8,
+ buf_size: usize,
+) callconv(.c) c_int {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return -1));
+
+ if (offset < 0 or col < 0) return -1;
+
+ const scrollback_len = getScrollbackLength(ptr);
+ if (offset >= scrollback_len) return -1;
+
+ // Get the pin for this scrollback row
+ const pages = zigTerminal(wrapper).screens.active.pages;
+ const pin = pages.pin(.{ .history = .{ .y = @intCast(offset) } }) orelse return -1;
+
+ const cells = pin.cells(.all);
+ const page = pin.node.data;
+ const x: usize = @intCast(col);
+
+ if (x >= cells.len) return -1;
+
+ const cell = &cells[x];
+
+ // Check if cell has a hyperlink
+ if (!cell.hyperlink) return 0;
+
+ // Look up the hyperlink ID from the page
+ const hyperlink_id = page.lookupHyperlink(cell) orelse return 0;
+
+ // Get the hyperlink entry from the set
+ const hyperlink_entry = page.hyperlink_set.get(page.memory, hyperlink_id);
+
+ // Get the URI bytes from the page memory
+ const uri = hyperlink_entry.uri.slice(page.memory);
+
+ if (uri.len == 0) return 0;
+ if (buf_size < uri.len) return -1;
+
+ @memcpy(out[0..uri.len], uri);
+ return @intCast(uri.len);
+}
+
+// ============================================================================
+// Response API - for DSR and other terminal queries
+// ============================================================================
+
+/// Check if there are pending responses from the terminal
+pub fn hasResponse(ptr: ?*anyopaque) callconv(.c) bool {
+ const wrapper: *const TerminalWrapper = @ptrCast(@alignCast(ptr orelse return false));
+ return wrapper.response_buffer.items.len > 0;
+}
+
+/// Read pending responses from the terminal.
+/// Returns number of bytes written to buffer, or 0 if no responses pending.
+/// Returns -1 on error (null pointer or buffer too small).
+pub fn readResponse(ptr: ?*anyopaque, out: [*]u8, buf_size: usize) callconv(.c) c_int {
+ const wrapper: *TerminalWrapper = @ptrCast(@alignCast(ptr orelse return -1));
+ const len = @min(wrapper.response_buffer.items.len, buf_size);
+ if (len == 0) return 0;
+
+ @memcpy(out[0..len], wrapper.response_buffer.items[0..len]);
+
+ // Remove consumed bytes from buffer
+ if (len == wrapper.response_buffer.items.len) {
+ wrapper.response_buffer.clearRetainingCapacity();
+ } else {