-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathmain.c
More file actions
1604 lines (1419 loc) · 65.9 KB
/
main.c
File metadata and controls
1604 lines (1419 loc) · 65.9 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <pwd.h>
#if defined(__APPLE__)
#include <util.h>
#else
#include <pty.h>
#endif
#include "raylib.h"
#include <ghostty/vt.h>
// Embed the font file directly into the binary at compile time.
// The header is generated by CMake from fonts/JetBrainsMono-Regular.ttf
// so we don't need to locate it at runtime.
#include "font_jetbrains_mono.h"
// ---------------------------------------------------------------------------
// PTY helpers
// ---------------------------------------------------------------------------
// Spawn the user's default shell in a new pseudo-terminal.
//
// Creates a pty pair via forkpty(), sets the initial window size, execs the
// shell in the child, and puts the master fd into non-blocking mode so we
// can poll it each frame without stalling the render loop.
//
// The shell is chosen by checking, in order:
// 1. $SHELL environment variable
// 2. The pw_shell field from the passwd database
// 3. /bin/sh as a last resort
//
// Returns the master fd on success (>= 0) and stores the child pid in
// *child_out. Returns -1 on failure.
static int pty_spawn(pid_t *child_out, uint16_t cols, uint16_t rows,
int cell_width, int cell_height)
{
int pty_fd;
struct winsize ws = {
.ws_row = rows,
.ws_col = cols,
.ws_xpixel = (unsigned short)(cols * cell_width),
.ws_ypixel = (unsigned short)(rows * cell_height),
};
// forkpty() combines openpty + fork + login_tty into one call.
// In the child it sets up the slave side as stdin/stdout/stderr.
pid_t child = forkpty(&pty_fd, NULL, NULL, &ws);
if (child < 0) {
perror("forkpty");
return -1;
}
if (child == 0) {
// Determine the user's preferred shell. We try $SHELL first (the
// standard convention), then fall back to the passwd entry, and
// finally to /bin/sh if nothing else is available.
const char *shell = getenv("SHELL");
if (!shell || shell[0] == '\0') {
struct passwd *pw = getpwuid(getuid());
if (pw && pw->pw_shell && pw->pw_shell[0] != '\0')
shell = pw->pw_shell;
else
shell = "/bin/sh";
}
// Extract just the program name for argv[0] (e.g. "/bin/zsh" → "zsh").
const char *shell_name = strrchr(shell, '/');
shell_name = shell_name ? shell_name + 1 : shell;
// Child process — replace ourselves with the shell.
// TERM tells programs what escape sequences we understand.
setenv("TERM", "xterm-256color", 1);
execl(shell, shell_name, NULL);
_exit(127); // execl only returns on error
}
// Parent — make the master fd non-blocking so read() returns EAGAIN
// instead of blocking when there's no data, letting us poll each frame.
int flags = fcntl(pty_fd, F_GETFL);
if (flags < 0 || fcntl(pty_fd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("fcntl O_NONBLOCK");
close(pty_fd);
return -1;
}
*child_out = child;
return pty_fd;
}
// Best-effort write to the pty master fd. Because the fd is
// non-blocking, write() may return short or fail with EAGAIN. We
// retry on EINTR, advance past partial writes, and silently drop
// data if the kernel buffer is full (EAGAIN) — this matches what
// most terminal emulators do under back-pressure.
static void pty_write(int pty_fd, const char *buf, size_t len)
{
while (len > 0) {
ssize_t n = write(pty_fd, buf, len);
if (n > 0) {
buf += n;
len -= (size_t)n;
} else if (n < 0) {
if (errno == EINTR)
continue;
// EAGAIN or real error — drop the remainder.
break;
}
}
}
// Result of draining the pty master fd.
typedef enum {
PTY_READ_OK, // data was drained (or EAGAIN, i.e. nothing available right now)
PTY_READ_EOF, // the child closed its end of the pty
PTY_READ_ERROR, // a real read error occurred
} PtyReadResult;
// Drain all available output from the pty master and feed it into the
// ghostty terminal. The terminal's VT parser will process any escape
// sequences and update its internal screen/cursor/style state.
//
// Because the fd is non-blocking, read() returns -1 with EAGAIN once
// the kernel buffer is empty, at which point we stop.
static PtyReadResult pty_read(int pty_fd, GhosttyTerminal terminal)
{
uint8_t buf[4096];
for (;;) {
ssize_t n = read(pty_fd, buf, sizeof(buf));
if (n > 0) {
ghostty_terminal_vt_write(terminal, buf, (size_t)n);
} else if (n == 0) {
// EOF — the child closed its side of the pty.
return PTY_READ_EOF;
} else {
// n == -1: distinguish "no data right now" from real errors.
if (errno == EAGAIN)
return PTY_READ_OK;
if (errno == EINTR)
continue; // retry the read
// On Linux, the slave closing often produces EIO rather
// than a clean EOF (read returning 0). Treat it the same.
if (errno == EIO)
return PTY_READ_EOF;
perror("pty read");
return PTY_READ_ERROR;
}
}
}
// ---------------------------------------------------------------------------
// Input handling
// ---------------------------------------------------------------------------
// Map a raylib key constant to a GhosttyKey code.
// Returns GHOSTTY_KEY_UNIDENTIFIED for keys we don't handle.
static GhosttyKey raylib_key_to_ghostty(int rl_key)
{
// Letters — raylib KEY_A..KEY_Z are contiguous, and so are
// GHOSTTY_KEY_A..GHOSTTY_KEY_Z.
if (rl_key >= KEY_A && rl_key <= KEY_Z)
return GHOSTTY_KEY_A + (rl_key - KEY_A);
// Digits — raylib KEY_ZERO..KEY_NINE are contiguous.
if (rl_key >= KEY_ZERO && rl_key <= KEY_NINE)
return GHOSTTY_KEY_DIGIT_0 + (rl_key - KEY_ZERO);
// Function keys — raylib KEY_F1..KEY_F12 are contiguous.
if (rl_key >= KEY_F1 && rl_key <= KEY_F12)
return GHOSTTY_KEY_F1 + (rl_key - KEY_F1);
switch (rl_key) {
case KEY_SPACE: return GHOSTTY_KEY_SPACE;
case KEY_ENTER: return GHOSTTY_KEY_ENTER;
case KEY_TAB: return GHOSTTY_KEY_TAB;
case KEY_BACKSPACE: return GHOSTTY_KEY_BACKSPACE;
case KEY_DELETE: return GHOSTTY_KEY_DELETE;
case KEY_ESCAPE: return GHOSTTY_KEY_ESCAPE;
case KEY_UP: return GHOSTTY_KEY_ARROW_UP;
case KEY_DOWN: return GHOSTTY_KEY_ARROW_DOWN;
case KEY_LEFT: return GHOSTTY_KEY_ARROW_LEFT;
case KEY_RIGHT: return GHOSTTY_KEY_ARROW_RIGHT;
case KEY_HOME: return GHOSTTY_KEY_HOME;
case KEY_END: return GHOSTTY_KEY_END;
case KEY_PAGE_UP: return GHOSTTY_KEY_PAGE_UP;
case KEY_PAGE_DOWN: return GHOSTTY_KEY_PAGE_DOWN;
case KEY_INSERT: return GHOSTTY_KEY_INSERT;
case KEY_MINUS: return GHOSTTY_KEY_MINUS;
case KEY_EQUAL: return GHOSTTY_KEY_EQUAL;
case KEY_LEFT_BRACKET: return GHOSTTY_KEY_BRACKET_LEFT;
case KEY_RIGHT_BRACKET: return GHOSTTY_KEY_BRACKET_RIGHT;
case KEY_BACKSLASH: return GHOSTTY_KEY_BACKSLASH;
case KEY_SEMICOLON: return GHOSTTY_KEY_SEMICOLON;
case KEY_APOSTROPHE: return GHOSTTY_KEY_QUOTE;
case KEY_COMMA: return GHOSTTY_KEY_COMMA;
case KEY_PERIOD: return GHOSTTY_KEY_PERIOD;
case KEY_SLASH: return GHOSTTY_KEY_SLASH;
case KEY_GRAVE: return GHOSTTY_KEY_BACKQUOTE;
default: return GHOSTTY_KEY_UNIDENTIFIED;
}
}
// Build a GhosttyMods bitmask from the current raylib modifier key state.
static GhosttyMods get_ghostty_mods(void)
{
GhosttyMods mods = 0;
if (IsKeyDown(KEY_LEFT_SHIFT) || IsKeyDown(KEY_RIGHT_SHIFT))
mods |= GHOSTTY_MODS_SHIFT;
if (IsKeyDown(KEY_LEFT_CONTROL) || IsKeyDown(KEY_RIGHT_CONTROL))
mods |= GHOSTTY_MODS_CTRL;
if (IsKeyDown(KEY_LEFT_ALT) || IsKeyDown(KEY_RIGHT_ALT))
mods |= GHOSTTY_MODS_ALT;
if (IsKeyDown(KEY_LEFT_SUPER) || IsKeyDown(KEY_RIGHT_SUPER))
mods |= GHOSTTY_MODS_SUPER;
return mods;
}
// Return the unshifted Unicode codepoint for a raylib key, i.e. the
// character the key produces with no modifiers on a US layout. The
// Kitty keyboard protocol requires this to identify keys. Returns 0
// for keys that don't have a natural codepoint (arrows, F-keys, etc.).
static uint32_t raylib_key_unshifted_codepoint(int rl_key)
{
if (rl_key >= KEY_A && rl_key <= KEY_Z)
return 'a' + (uint32_t)(rl_key - KEY_A);
if (rl_key >= KEY_ZERO && rl_key <= KEY_NINE)
return '0' + (uint32_t)(rl_key - KEY_ZERO);
switch (rl_key) {
case KEY_SPACE: return ' ';
case KEY_MINUS: return '-';
case KEY_EQUAL: return '=';
case KEY_LEFT_BRACKET: return '[';
case KEY_RIGHT_BRACKET: return ']';
case KEY_BACKSLASH: return '\\';
case KEY_SEMICOLON: return ';';
case KEY_APOSTROPHE: return '\'';
case KEY_COMMA: return ',';
case KEY_PERIOD: return '.';
case KEY_SLASH: return '/';
case KEY_GRAVE: return '`';
default: return 0;
}
}
// Encode a single Unicode codepoint into a UTF-8 byte buffer.
// Returns the number of bytes written (1–4).
// Invalid codepoints (> U+10FFFF) are replaced with U+FFFD.
static int utf8_encode(uint32_t cp, char out[4])
{
// Unicode defines the maximum valid codepoint as U+10FFFF.
// Codepoints above this value are invalid and should be replaced
// with the Unicode replacement character U+FFFD.
const uint32_t MAX_UNICODE = 0x10FFFF;
const uint32_t REPLACEMENT_CHAR = 0xFFFD;
if (cp > MAX_UNICODE) {
cp = REPLACEMENT_CHAR;
}
if (cp < 0x80) {
out[0] = (char)cp;
return 1;
} else if (cp < 0x800) {
out[0] = (char)(0xC0 | (cp >> 6));
out[1] = (char)(0x80 | (cp & 0x3F));
return 2;
} else if (cp < 0x10000) {
out[0] = (char)(0xE0 | (cp >> 12));
out[1] = (char)(0x80 | ((cp >> 6) & 0x3F));
out[2] = (char)(0x80 | (cp & 0x3F));
return 3;
} else {
out[0] = (char)(0xF0 | (cp >> 18));
out[1] = (char)(0x80 | ((cp >> 12) & 0x3F));
out[2] = (char)(0x80 | ((cp >> 6) & 0x3F));
out[3] = (char)(0x80 | (cp & 0x3F));
return 4;
}
}
// Map a raylib mouse button to a GhosttyMouseButton.
static GhosttyMouseButton raylib_mouse_to_ghostty(int rl_button)
{
switch (rl_button) {
case MOUSE_BUTTON_LEFT: return GHOSTTY_MOUSE_BUTTON_LEFT;
case MOUSE_BUTTON_RIGHT: return GHOSTTY_MOUSE_BUTTON_RIGHT;
case MOUSE_BUTTON_MIDDLE: return GHOSTTY_MOUSE_BUTTON_MIDDLE;
case MOUSE_BUTTON_SIDE: return GHOSTTY_MOUSE_BUTTON_FOUR;
case MOUSE_BUTTON_EXTRA: return GHOSTTY_MOUSE_BUTTON_FIVE;
case MOUSE_BUTTON_FORWARD: return GHOSTTY_MOUSE_BUTTON_SIX;
case MOUSE_BUTTON_BACK: return GHOSTTY_MOUSE_BUTTON_SEVEN;
default: return GHOSTTY_MOUSE_BUTTON_UNKNOWN;
}
}
// Encode a mouse event and write the resulting escape sequence to the pty.
// If the encoder produces no output (e.g. tracking is disabled), this is
// a no-op.
static void mouse_encode_and_write(int pty_fd, GhosttyMouseEncoder encoder,
GhosttyMouseEvent event)
{
char buf[128];
size_t written = 0;
GhosttyResult res = ghostty_mouse_encoder_encode(
encoder, event, buf, sizeof(buf), &written);
if (res == GHOSTTY_SUCCESS && written > 0)
pty_write(pty_fd, buf, written);
}
// Poll raylib for mouse events and use the libghostty mouse encoder
// to produce the correct VT escape sequences, which are then written
// to the pty. The encoder handles tracking mode (X10, normal, button,
// any-event) and output format (X10, UTF8, SGR, URxvt, SGR-Pixels)
// based on what the terminal application has requested.
static void handle_mouse(int pty_fd, GhosttyMouseEncoder encoder,
GhosttyMouseEvent event, GhosttyTerminal terminal,
int cell_width, int cell_height, int pad)
{
// Sync encoder tracking mode and format from terminal state so
// mode changes (e.g. applications enabling SGR mouse reporting)
// are honoured automatically.
ghostty_mouse_encoder_setopt_from_terminal(encoder, terminal);
// Provide the encoder with the current terminal geometry so it
// can convert pixel positions to cell coordinates.
int scr_w = GetScreenWidth();
int scr_h = GetScreenHeight();
GhosttyMouseEncoderSize enc_size = {
.size = sizeof(GhosttyMouseEncoderSize),
.screen_width = (uint32_t)scr_w,
.screen_height = (uint32_t)scr_h,
.cell_width = (uint32_t)cell_width,
.cell_height = (uint32_t)cell_height,
.padding_top = (uint32_t)pad,
.padding_bottom = (uint32_t)pad,
.padding_left = (uint32_t)pad,
.padding_right = (uint32_t)pad,
};
ghostty_mouse_encoder_setopt(encoder,
GHOSTTY_MOUSE_ENCODER_OPT_SIZE, &enc_size);
// Track whether any button is currently held — the encoder uses
// this to distinguish drags from plain motion.
bool any_pressed = IsMouseButtonDown(MOUSE_BUTTON_LEFT)
|| IsMouseButtonDown(MOUSE_BUTTON_RIGHT)
|| IsMouseButtonDown(MOUSE_BUTTON_MIDDLE);
ghostty_mouse_encoder_setopt(encoder,
GHOSTTY_MOUSE_ENCODER_OPT_ANY_BUTTON_PRESSED, &any_pressed);
// Enable motion deduplication so the encoder suppresses redundant
// motion events within the same cell.
bool track_cell = true;
ghostty_mouse_encoder_setopt(encoder,
GHOSTTY_MOUSE_ENCODER_OPT_TRACK_LAST_CELL, &track_cell);
GhosttyMods mods = get_ghostty_mods();
Vector2 pos = GetMousePosition();
ghostty_mouse_event_set_mods(event, mods);
ghostty_mouse_event_set_position(event,
(GhosttyMousePosition){ .x = pos.x, .y = pos.y });
// Check each mouse button for press/release events.
static const int buttons[] = {
MOUSE_BUTTON_LEFT, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_MIDDLE,
MOUSE_BUTTON_SIDE, MOUSE_BUTTON_EXTRA, MOUSE_BUTTON_FORWARD,
MOUSE_BUTTON_BACK,
};
for (size_t i = 0; i < sizeof(buttons) / sizeof(buttons[0]); i++) {
int rl_btn = buttons[i];
GhosttyMouseButton gbtn = raylib_mouse_to_ghostty(rl_btn);
if (gbtn == GHOSTTY_MOUSE_BUTTON_UNKNOWN)
continue;
if (IsMouseButtonPressed(rl_btn)) {
ghostty_mouse_event_set_action(event, GHOSTTY_MOUSE_ACTION_PRESS);
ghostty_mouse_event_set_button(event, gbtn);
mouse_encode_and_write(pty_fd, encoder, event);
} else if (IsMouseButtonReleased(rl_btn)) {
ghostty_mouse_event_set_action(event, GHOSTTY_MOUSE_ACTION_RELEASE);
ghostty_mouse_event_set_button(event, gbtn);
mouse_encode_and_write(pty_fd, encoder, event);
}
}
// Mouse motion — send a motion event with whatever button is held
// (or no button for pure motion in any-event tracking mode).
Vector2 delta = GetMouseDelta();
if (delta.x != 0.0f || delta.y != 0.0f) {
ghostty_mouse_event_set_action(event, GHOSTTY_MOUSE_ACTION_MOTION);
if (IsMouseButtonDown(MOUSE_BUTTON_LEFT))
ghostty_mouse_event_set_button(event, GHOSTTY_MOUSE_BUTTON_LEFT);
else if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
ghostty_mouse_event_set_button(event, GHOSTTY_MOUSE_BUTTON_RIGHT);
else if (IsMouseButtonDown(MOUSE_BUTTON_MIDDLE))
ghostty_mouse_event_set_button(event, GHOSTTY_MOUSE_BUTTON_MIDDLE);
else
ghostty_mouse_event_clear_button(event);
mouse_encode_and_write(pty_fd, encoder, event);
}
// Scroll wheel handling. When a mouse tracking mode is active the
// wheel events are forwarded to the application as button 4/5
// press+release pairs. Otherwise we scroll the viewport through
// the scrollback buffer so the user can review history.
float wheel = GetMouseWheelMove();
if (wheel != 0.0f) {
// Check whether any mouse tracking mode is enabled. If so,
// the application wants to handle scroll events itself.
bool mouse_tracking = false;
ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_MOUSE_TRACKING, &mouse_tracking);
if (mouse_tracking) {
// Forward to the application via the mouse encoder.
GhosttyMouseButton scroll_btn = (wheel > 0.0f)
? GHOSTTY_MOUSE_BUTTON_FOUR
: GHOSTTY_MOUSE_BUTTON_FIVE;
ghostty_mouse_event_set_button(event, scroll_btn);
ghostty_mouse_event_set_action(event, GHOSTTY_MOUSE_ACTION_PRESS);
mouse_encode_and_write(pty_fd, encoder, event);
ghostty_mouse_event_set_action(event, GHOSTTY_MOUSE_ACTION_RELEASE);
mouse_encode_and_write(pty_fd, encoder, event);
} else {
// Scroll the viewport through scrollback. Scroll 3 rows
// per wheel tick for a comfortable pace. Delta is negative
// to scroll up (into history), positive to scroll down.
int delta = (wheel > 0.0f) ? -3 : 3;
GhosttyTerminalScrollViewport sv = {
.tag = GHOSTTY_SCROLL_VIEWPORT_DELTA,
.value = { .delta = delta },
};
ghostty_terminal_scroll_viewport(terminal, sv);
}
}
}
// Poll raylib for keyboard events and use the libghostty key encoder
// to produce the correct VT escape sequences, which are then written
// to the pty. The encoder respects terminal modes (cursor key
// application mode, Kitty keyboard protocol, etc.) so we don't need
// to maintain our own escape-sequence tables.
static void handle_input(int pty_fd, GhosttyKeyEncoder encoder,
GhosttyKeyEvent event, GhosttyTerminal terminal)
{
// Sync encoder options from the terminal so mode changes (e.g.
// application cursor keys, Kitty keyboard protocol) are honoured.
ghostty_key_encoder_setopt_from_terminal(encoder, terminal);
// Drain printable characters from raylib's input queue. We collect
// them into a single UTF-8 buffer so the encoder can attach text
// to the key event.
char char_utf8[64];
int char_utf8_len = 0;
int ch;
while ((ch = GetCharPressed()) != 0) {
char u8[4];
int n = utf8_encode(ch, u8);
if (char_utf8_len + n < (int)sizeof(char_utf8)) {
memcpy(&char_utf8[char_utf8_len], u8, n);
char_utf8_len += n;
}
}
// All raylib keys we want to check for press/repeat events.
// Letters and digits are handled via ranges; everything else is
// enumerated explicitly.
static const int special_keys[] = {
KEY_SPACE, KEY_ENTER, KEY_TAB, KEY_BACKSPACE, KEY_DELETE,
KEY_ESCAPE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT,
KEY_HOME, KEY_END, KEY_PAGE_UP, KEY_PAGE_DOWN, KEY_INSERT,
KEY_MINUS, KEY_EQUAL, KEY_LEFT_BRACKET, KEY_RIGHT_BRACKET,
KEY_BACKSLASH, KEY_SEMICOLON, KEY_APOSTROPHE, KEY_COMMA,
KEY_PERIOD, KEY_SLASH, KEY_GRAVE,
KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6,
KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12,
};
// Build the set of raylib keys to scan: letters + digits + specials.
int keys_to_check[26 + 10 + sizeof(special_keys) / sizeof(special_keys[0])];
int num_keys = 0;
for (int k = KEY_A; k <= KEY_Z; k++)
keys_to_check[num_keys++] = k;
for (int k = KEY_ZERO; k <= KEY_NINE; k++)
keys_to_check[num_keys++] = k;
for (size_t i = 0; i < sizeof(special_keys) / sizeof(special_keys[0]); i++)
keys_to_check[num_keys++] = special_keys[i];
GhosttyMods mods = get_ghostty_mods();
for (int i = 0; i < num_keys; i++) {
int rl_key = keys_to_check[i];
bool pressed = IsKeyPressed(rl_key);
bool repeated = IsKeyPressedRepeat(rl_key);
bool released = IsKeyReleased(rl_key);
if (!pressed && !repeated && !released)
continue;
GhosttyKey gkey = raylib_key_to_ghostty(rl_key);
if (gkey == GHOSTTY_KEY_UNIDENTIFIED)
continue;
GhosttyKeyAction action = released ? GHOSTTY_KEY_ACTION_RELEASE
: pressed ? GHOSTTY_KEY_ACTION_PRESS
: GHOSTTY_KEY_ACTION_REPEAT;
ghostty_key_event_set_key(event, gkey);
ghostty_key_event_set_action(event, action);
ghostty_key_event_set_mods(event, mods);
// The unshifted codepoint is the character the key produces
// with no modifiers. The Kitty protocol needs it to identify
// keys independent of the current shift state.
uint32_t ucp = raylib_key_unshifted_codepoint(rl_key);
ghostty_key_event_set_unshifted_codepoint(event, ucp);
// Consumed mods are modifiers the platform's text input
// already accounted for when producing the UTF-8 text.
// For printable keys, shift is consumed (it turns 'a' → 'A').
// For non-printable keys nothing is consumed.
GhosttyMods consumed = 0;
if (ucp != 0 && (mods & GHOSTTY_MODS_SHIFT))
consumed |= GHOSTTY_MODS_SHIFT;
ghostty_key_event_set_consumed_mods(event, consumed);
// Attach any UTF-8 text that raylib produced for this frame.
// For unmodified printable keys this is the character itself;
// for special keys or ctrl combos there's typically no text.
// Release events never carry text.
if (char_utf8_len > 0 && !released) {
ghostty_key_event_set_utf8(event, char_utf8, (size_t)char_utf8_len);
// Only attach the text to the first key event this frame
// to avoid duplicating it.
char_utf8_len = 0;
} else {
ghostty_key_event_set_utf8(event, NULL, 0);
}
char buf[128];
size_t written = 0;
GhosttyResult res = ghostty_key_encoder_encode(
encoder, event, buf, sizeof(buf), &written);
if (res == GHOSTTY_SUCCESS && written > 0) {
pty_write(pty_fd, buf, written);
// Text was consumed by the encoder — clear it so the
// fallback below doesn't double-send.
char_utf8_len = 0;
}
}
// Fallback: on some platforms (e.g. VMs) the character event arrives
// a frame after the key-press event. If we collected UTF-8 text but
// no key event consumed it, write it directly to the PTY so input
// isn't silently dropped.
if (char_utf8_len > 0)
pty_write(pty_fd, char_utf8, char_utf8_len);
}
// Handle scrollbar drag-to-scroll. When the user clicks in the
// scrollbar region we begin tracking; while held we map the mouse Y
// position directly to an absolute scroll offset so the thumb follows
// the cursor exactly.
//
// Returns true while a drag is in progress so the caller can skip
// normal mouse handling if desired.
static bool handle_scrollbar(GhosttyTerminal terminal,
GhosttyRenderState render_state,
bool *dragging)
{
// Query scrollbar geometry from the terminal.
GhosttyTerminalScrollbar scrollbar = {0};
if (ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_SCROLLBAR,
&scrollbar) != GHOSTTY_SUCCESS)
return false;
// Nothing to drag when the viewport covers all content.
if (scrollbar.total <= scrollbar.len) {
*dragging = false;
return false;
}
int scr_w = GetScreenWidth();
int scr_h = GetScreenHeight();
const int bar_width = 6;
const int bar_margin = 2;
int bar_left = scr_w - bar_width - bar_margin;
// Use a wider hit region for easier grabbing.
int hit_left = bar_left - 8;
Vector2 mpos = GetMousePosition();
// Start a drag when the user clicks inside the hit region.
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)
&& mpos.x >= hit_left && mpos.x <= scr_w) {
*dragging = true;
}
if (*dragging && IsMouseButtonDown(MOUSE_BUTTON_LEFT)) {
// Map mouse Y directly to an absolute scroll offset.
// Y=0 → top of scrollback (offset 0), Y=scr_h → bottom
// (offset = total - len).
uint64_t scrollable = scrollbar.total - scrollbar.len;
double frac = (double)mpos.y / (double)scr_h;
if (frac < 0.0) frac = 0.0;
if (frac > 1.0) frac = 1.0;
int64_t target = (int64_t)(frac * (double)scrollable);
intptr_t delta = (intptr_t)(target - (int64_t)scrollbar.offset);
if (delta != 0) {
GhosttyTerminalScrollViewport sv = {
.tag = GHOSTTY_SCROLL_VIEWPORT_DELTA,
.value = { .delta = delta },
};
ghostty_terminal_scroll_viewport(terminal, sv);
ghostty_render_state_update(render_state, terminal);
}
}
if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT))
*dragging = false;
return *dragging;
}
// Deferred texture cleanup — textures uploaded during a frame can't be
// freed until after EndDrawing() flushes the draw commands to the GPU.
#define MAX_DEFERRED_TEXTURES 256
static Texture2D deferred_textures[MAX_DEFERRED_TEXTURES];
static int deferred_texture_count = 0;
static void defer_unload_texture(Texture2D tex)
{
if (deferred_texture_count < MAX_DEFERRED_TEXTURES)
deferred_textures[deferred_texture_count++] = tex;
else
UnloadTexture(tex); // overflow fallback — may glitch but won't leak
}
static void flush_deferred_textures(void)
{
for (int i = 0; i < deferred_texture_count; i++)
UnloadTexture(deferred_textures[i]);
deferred_texture_count = 0;
}
// Draw all Kitty graphics placements for a given z-layer.
//
// The layer filter is applied by the iterator itself via
// ghostty_kitty_graphics_placement_iterator_set(), so we only see
// placements matching the requested layer.
//
// WARNING: This is deliberately simple but very inefficient. Every
// visible image is re-uploaded to the GPU every frame and destroyed
// right after. A real implementation should cache Texture2D objects
// keyed by image ID and only re-upload when the image is re-transmitted
// or evicted from the terminal's storage.
static void render_kitty_images(GhosttyTerminal terminal,
GhosttyKittyGraphics graphics,
GhosttyKittyGraphicsPlacementIterator placement_iter,
int cell_width, int cell_height, int pad,
GhosttyKittyPlacementLayer layer)
{
// Configure the layer filter on the iterator so
// placement_next() only yields matching placements.
ghostty_kitty_graphics_placement_iterator_set(placement_iter,
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER, &layer);
// Re-populate the iterator for this layer scan.
if (ghostty_kitty_graphics_get(graphics,
GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR,
&placement_iter) != GHOSTTY_SUCCESS)
return;
while (ghostty_kitty_graphics_placement_next(placement_iter)) {
// Look up the image for this placement.
uint32_t image_id = 0;
ghostty_kitty_graphics_placement_get(placement_iter,
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID, &image_id);
GhosttyKittyGraphicsImage image_handle =
ghostty_kitty_graphics_image(graphics, image_id);
if (!image_handle)
continue;
// Get viewport-relative position. Returns NO_VALUE when the
// placement is entirely off-screen or is a virtual (unicode
// placeholder) placement, so both cases are handled in one call.
int32_t vp_col = 0, vp_row = 0;
if (ghostty_kitty_graphics_placement_viewport_pos(
placement_iter, image_handle, terminal,
&vp_col, &vp_row) != GHOSTTY_SUCCESS)
continue;
// Read image dimensions and pixel data. We only handle RGBA
// (the PNG decoder we registered converts everything to RGBA).
uint32_t img_w = 0, img_h = 0;
ghostty_kitty_graphics_image_get(image_handle,
GHOSTTY_KITTY_IMAGE_DATA_WIDTH, &img_w);
ghostty_kitty_graphics_image_get(image_handle,
GHOSTTY_KITTY_IMAGE_DATA_HEIGHT, &img_h);
if (img_w == 0 || img_h == 0)
continue;
GhosttyKittyImageFormat fmt = GHOSTTY_KITTY_IMAGE_FORMAT_RGBA;
ghostty_kitty_graphics_image_get(image_handle,
GHOSTTY_KITTY_IMAGE_DATA_FORMAT, &fmt);
if (fmt != GHOSTTY_KITTY_IMAGE_FORMAT_RGBA)
continue;
const uint8_t *data_ptr = NULL;
size_t data_len = 0;
ghostty_kitty_graphics_image_get(image_handle,
GHOSTTY_KITTY_IMAGE_DATA_DATA_PTR, &data_ptr);
ghostty_kitty_graphics_image_get(image_handle,
GHOSTTY_KITTY_IMAGE_DATA_DATA_LEN, &data_len);
if (!data_ptr || data_len < (size_t)img_w * img_h * 4)
continue;
// Compute grid cell count for rendered size.
uint32_t grid_cols = 0, grid_rows = 0;
if (ghostty_kitty_graphics_placement_grid_size(
placement_iter, image_handle, terminal,
&grid_cols, &grid_rows) != GHOSTTY_SUCCESS)
continue;
if (grid_cols == 0 || grid_rows == 0)
continue;
uint32_t dest_w = grid_cols * (uint32_t)cell_width;
uint32_t dest_h = grid_rows * (uint32_t)cell_height;
// Get the resolved source rectangle (handles "0 = full image"
// semantics and clamps to image bounds).
uint32_t src_x = 0, src_y = 0, src_w = 0, src_h = 0;
if (ghostty_kitty_graphics_placement_source_rect(
placement_iter, image_handle,
&src_x, &src_y, &src_w, &src_h) != GHOSTTY_SUCCESS)
continue;
// Read the sub-cell pixel offsets.
uint32_t x_offset = 0, y_offset = 0;
ghostty_kitty_graphics_placement_get(placement_iter,
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_X_OFFSET, &x_offset);
ghostty_kitty_graphics_placement_get(placement_iter,
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Y_OFFSET, &y_offset);
// Upload the RGBA data to a temporary texture, draw, and free.
Image img = {
.data = (void *)(uintptr_t)data_ptr,
.width = (int)img_w,
.height = (int)img_h,
.mipmaps = 1,
.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8,
};
Texture2D tex = LoadTextureFromImage(img);
SetTextureFilter(tex, TEXTURE_FILTER_BILINEAR);
int dest_x = pad + (int)vp_col * cell_width + (int)x_offset;
int dest_y = pad + (int)vp_row * cell_height + (int)y_offset;
Rectangle src_rect = {
(float)src_x, (float)src_y,
(float)src_w, (float)src_h
};
Rectangle dst_rect = {
(float)dest_x, (float)dest_y,
(float)dest_w, (float)dest_h
};
DrawTexturePro(tex, src_rect, dst_rect,
(Vector2){0, 0}, 0.0f, WHITE);
defer_unload_texture(tex);
}
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
// Render the current terminal screen using the RenderState API.
//
// For each row/cell we read the grapheme codepoints and the cell's style,
// resolve foreground/background colors via the palette, and draw each
// character individually with DrawTextEx. This supports per-cell colors
// from SGR sequences (bold, 256-color, 24-bit RGB, etc.).
//
// cell_width and cell_height are the measured dimensions of a single
// monospace glyph at the current font size, in screen (logical) pixels.
// font_size is the logical font size (before DPI scaling).
// pad is the pixel margin between the window edges and the terminal grid.
//
// If scrollbar is non-NULL, a scrollbar indicator is drawn on the right
// edge of the window.
static void render_terminal(GhosttyRenderState render_state,
GhosttyRenderStateRowIterator row_iter,
GhosttyRenderStateRowCells cells,
Font font,
int cell_width, int cell_height,
int font_size,
int pad,
const GhosttyTerminalScrollbar *scrollbar,
GhosttyTerminal terminal,
GhosttyKittyGraphicsPlacementIterator placement_iter)
{
// Grab colors (palette, default fg/bg) from the render state so we
// can resolve palette-indexed cell colors.
GhosttyRenderStateColors colors = GHOSTTY_INIT_SIZED(GhosttyRenderStateColors);
if (ghostty_render_state_colors_get(render_state, &colors) != GHOSTTY_SUCCESS)
return;
// Obtain the Kitty graphics storage from the terminal. This is a
// borrowed pointer valid until the next mutating terminal call.
GhosttyKittyGraphics kitty_gfx = NULL;
bool has_kitty = (ghostty_terminal_get(terminal,
GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS, &kitty_gfx) == GHOSTTY_SUCCESS
&& kitty_gfx != NULL);
// Populate the row iterator from the current render state snapshot.
if (ghostty_render_state_get(render_state,
GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR, &row_iter) != GHOSTTY_SUCCESS)
return;
// --- Layer 1: images below cell backgrounds (z < INT32_MIN/2) ---
if (has_kitty && placement_iter) {
render_kitty_images(terminal, kitty_gfx, placement_iter,
cell_width, cell_height, pad,
GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_BG);
}
// Small padding from the window edges.
int y = pad;
while (ghostty_render_state_row_iterator_next(row_iter)) {
// Get the cells for this row (reuses the same cells handle).
if (ghostty_render_state_row_get(row_iter,
GHOSTTY_RENDER_STATE_ROW_DATA_CELLS, &cells) != GHOSTTY_SUCCESS)
continue;
int x = pad;
while (ghostty_render_state_row_cells_next(cells)) {
// How many codepoints make up the grapheme? 0 = empty cell.
uint32_t grapheme_len = 0;
ghostty_render_state_row_cells_get(cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_LEN, &grapheme_len);
if (grapheme_len == 0) {
// The cell has no text, but it might have a background
// color (e.g. from an erase with a color set). The
// BG_COLOR data query resolves content-tag bg colors
// and palette indices for us, returning INVALID_VALUE
// when the cell has no background.
GhosttyColorRgb bg = {0};
if (ghostty_render_state_row_cells_get(cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR, &bg) == GHOSTTY_SUCCESS) {
DrawRectangle(x, y, cell_width, cell_height,
(Color){ bg.r, bg.g, bg.b, 255 });
}
x += cell_width;
continue;
}
// Read the grapheme codepoints.
uint32_t codepoints[16];
uint32_t len = grapheme_len < 16 ? grapheme_len : 16;
ghostty_render_state_row_cells_get(cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF, codepoints);
// Build a UTF-8 string from the grapheme codepoints.
char text[64];
int pos = 0;
for (uint32_t i = 0; i < len && pos < 60; i++) {
char u8[4];
int n = utf8_encode(codepoints[i], u8);
memcpy(&text[pos], u8, n);
pos += n;
}
text[pos] = '\0';
// Resolve foreground and background colors using the new
// per-cell color queries. These flatten style colors,
// content-tag colors, and palette lookups into a single RGB
// value, returning INVALID_VALUE when the cell has no
// explicit color (in which case we use the terminal default).
GhosttyColorRgb fg = colors.foreground;
ghostty_render_state_row_cells_get(cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_FG_COLOR, &fg);
GhosttyColorRgb bg_rgb = colors.background;
bool has_bg = ghostty_render_state_row_cells_get(cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR, &bg_rgb) == GHOSTTY_SUCCESS;
// Read the style for flags (inverse, bold, italic) — color
// resolution is handled above via the new API.
GhosttyStyle style = GHOSTTY_INIT_SIZED(GhosttyStyle);
ghostty_render_state_row_cells_get(cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_STYLE, &style);
// Inverse (reverse video): swap foreground and background colors.
if (style.inverse) {
GhosttyColorRgb tmp = fg;
fg = bg_rgb;
bg_rgb = tmp;
has_bg = true;
}
Color ray_fg = { fg.r, fg.g, fg.b, 255 };
// Draw a background rectangle if the cell has a non-default bg
// or if inverse mode forced a swap.
if (has_bg) {
DrawRectangle(x, y, cell_width, cell_height, (Color){ bg_rgb.r, bg_rgb.g, bg_rgb.b, 255 });
}
// Italic: apply a simple shear by shifting the top of the glyph
// to the right. The offset is proportional to font size so it
// looks reasonable at any scale.
int italic_offset = style.italic ? (font_size / 6) : 0;
DrawTextEx(font, text, (Vector2){x + italic_offset, y}, font_size, 0, ray_fg);
// Bold: draw the text a second time shifted 1 pixel to the
// right to thicken the strokes ("fake bold").
if (style.bold) {
DrawTextEx(font, text, (Vector2){x + italic_offset + 1, y}, font_size, 0, ray_fg);
}
x += cell_width;
}
// Clear per-row dirty flag after rendering it.
bool clean = false;
ghostty_render_state_row_set(row_iter,
GHOSTTY_RENDER_STATE_ROW_OPTION_DIRTY, &clean);
y += cell_height;
}
// --- Layer 2: images below text (INT32_MIN/2 <= z < 0) ---
// Drawn after cell backgrounds but before the cursor and any
// above-text images. In our single-pass renderer the cell text
// has already been drawn, but this still achieves the correct
// visual for the common case where images sit behind text.
if (has_kitty && placement_iter) {
render_kitty_images(terminal, kitty_gfx, placement_iter,
cell_width, cell_height, pad,
GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_TEXT);
}
// Draw the cursor.
bool cursor_visible = false;
ghostty_render_state_get(render_state,
GHOSTTY_RENDER_STATE_DATA_CURSOR_VISIBLE, &cursor_visible);
bool cursor_in_viewport = false;
ghostty_render_state_get(render_state,
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_HAS_VALUE, &cursor_in_viewport);
if (cursor_visible && cursor_in_viewport) {
uint16_t cx = 0, cy = 0;
ghostty_render_state_get(render_state,
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_X, &cx);
ghostty_render_state_get(render_state,
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_Y, &cy);
// Draw the cursor using the foreground color (or explicit cursor
// color if the terminal set one).
GhosttyColorRgb cur_rgb = colors.foreground;
if (colors.cursor_has_value)
cur_rgb = colors.cursor;
int cur_x = pad + cx * cell_width;
int cur_y = pad + cy * cell_height;
DrawRectangle(cur_x, cur_y, cell_width, cell_height, (Color){ cur_rgb.r, cur_rgb.g, cur_rgb.b, 128 });
}
// --- Layer 3: images above text (z >= 0) ---
if (has_kitty && placement_iter) {
render_kitty_images(terminal, kitty_gfx, placement_iter,
cell_width, cell_height, pad,
GHOSTTY_KITTY_PLACEMENT_LAYER_ABOVE_TEXT);
}
// Draw the scrollbar when there is scrollback content to scroll through.
if (scrollbar && scrollbar->total > scrollbar->len) {
int scr_w = GetScreenWidth();
int scr_h = GetScreenHeight();
// Scrollbar track spans the full window height; the thumb
// is proportional to the visible fraction of the total content.
const int bar_width = 6;
const int bar_margin = 2;
int bar_x = scr_w - bar_width - bar_margin;
double visible_frac = (double)scrollbar->len / (double)scrollbar->total;
int thumb_height = (int)(scr_h * visible_frac);
if (thumb_height < 10) thumb_height = 10;