-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathterminal.cpp
More file actions
3222 lines (2900 loc) · 74.2 KB
/
terminal.cpp
File metadata and controls
3222 lines (2900 loc) · 74.2 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
/*
util/terminal.cpp
This utility adds a terminal emulator, activate it using the keybind cmd t
The emulator is based suckless st.c and support most xterm ansi sequences
*/
#include "terminal.h"
// Files.h dependency removed - not needed for standalone terminal
// Settings dependency removed - using hardcoded values instead
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <signal.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <limits.h> // For PATH_MAX (on Linux)
#include <pwd.h> // For getpwuid
#include <stdlib.h> // For getenv, setenv, unsetenv, realpath
#include <string.h> // For strrchr, strcpy, strncpy, strerror
#include <sys/types.h> // For getpwuid, uid_t
#ifndef PATH_MAX // Define a fallback if PATH_MAX is not found (e.g., on some
// systems)
#define PATH_MAX 1024
#endif
ImVec4 Terminal::defaultColorMap[16] = {
// Standard colors
ImVec4(0.0f, 0.0f, 0.0f, 1.0f), // Black
ImVec4(0.8f, 0.2f, 0.2f, 1.0f), // Rich Red
ImVec4(0.2f, 0.8f, 0.2f, 1.0f), // Vibrant Green
ImVec4(0.9f, 0.9f, 0.3f, 1.0f), // Sunny Yellow
ImVec4(0.2f, 0.5f, 1.0f, 1.0f), // Sky Blue (brighter blue)
ImVec4(0.8f, 0.3f, 0.8f, 1.0f), // Electric Purple
ImVec4(0.3f, 0.8f, 0.8f, 1.0f), // Aqua Cyan
ImVec4(0.9f, 0.9f, 0.9f, 1.0f), // Off-White
// Bright colors (pastel-like but still vibrant)
ImVec4(0.5f, 0.5f, 0.5f, 1.0f), // Medium Gray
ImVec4(1.0f, 0.4f, 0.4f, 1.0f), // Coral Red
ImVec4(0.4f, 1.0f, 0.4f, 1.0f), // Lime Green
ImVec4(1.0f, 1.0f, 0.6f, 1.0f), // Lemon Yellow
ImVec4(0.4f, 0.6f, 1.0f, 1.0f), // Bright Sky Blue
ImVec4(1.0f, 0.5f, 1.0f, 1.0f), // Pink Purple
ImVec4(0.5f, 1.0f, 1.0f, 1.0f), // Ice Blue
ImVec4(1.0f, 1.0f, 1.0f, 1.0f) // Pure White
};
Terminal gTerminal;
Terminal::Terminal()
{
// Initialize with safe default size
state.row = 24;
state.col = 80;
state.bot = state.row - 1;
sel.mode = SEL_IDLE;
sel.type = SEL_REGULAR;
sel.snap = 0;
sel.ob.x = -1;
sel.ob.y = -1;
sel.oe.x = -1;
sel.oe.y = -1;
sel.nb.x = -1;
sel.nb.y = -1;
sel.ne.x = -1;
sel.ne.y = -1;
sel.alt = 0;
// Initialize screen buffer
state.lines.resize(state.row, std::vector<Glyph>(state.col));
state.altLines.resize(state.row, std::vector<Glyph>(state.col));
state.dirty.resize(state.row, true);
// Initialize tab stops (every 8 columns)
state.tabs.resize(state.col, false);
for (int i = 8; i < state.col; i += 8)
{
state.tabs[i] = true;
}
}
void Terminal::UpdateTerminalColors()
{
// Hardcoded terminal colors - no settings dependency
// ANSI color map (0-15): 0-7 are normal colors, 8-15 are bright colors
defaultColorMap[0] = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black (background)
defaultColorMap[1] = ImVec4(0.8f, 0.2f, 0.2f, 1.0f); // Red
defaultColorMap[2] = ImVec4(0.2f, 0.8f, 0.2f, 1.0f); // Green
defaultColorMap[3] = ImVec4(0.8f, 0.8f, 0.2f, 1.0f); // Yellow
defaultColorMap[4] = ImVec4(0.2f, 0.2f, 0.8f, 1.0f); // Blue
defaultColorMap[5] = ImVec4(0.8f, 0.2f, 0.8f, 1.0f); // Magenta
defaultColorMap[6] = ImVec4(0.2f, 0.8f, 0.8f, 1.0f); // Cyan
defaultColorMap[7] = ImVec4(0.8f, 0.8f, 0.8f, 1.0f); // White
// Bright colors (8-15)
defaultColorMap[8] = ImVec4(0.4f, 0.4f, 0.4f, 1.0f); // Bright Black
defaultColorMap[9] = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); // Bright Red
defaultColorMap[10] = ImVec4(0.4f, 1.0f, 0.4f, 1.0f); // Bright Green
defaultColorMap[11] = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); // Bright Yellow
defaultColorMap[12] = ImVec4(0.4f, 0.4f, 1.0f, 1.0f); // Bright Blue
defaultColorMap[13] = ImVec4(1.0f, 0.4f, 1.0f, 1.0f); // Bright Magenta
defaultColorMap[14] = ImVec4(0.4f, 1.0f, 1.0f, 1.0f); // Bright Cyan
defaultColorMap[15] = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // Bright White
}
Terminal::~Terminal()
{
shouldTerminate = true;
if (readThread.joinable())
{
readThread.join();
}
if (ptyFd >= 0)
{
close(ptyFd);
}
if (childPid > 0)
{
kill(childPid, SIGTERM);
}
}
void Terminal::startShell()
{
// Open PTY master
ptyFd = posix_openpt(O_RDWR | O_NOCTTY);
if (ptyFd < 0)
{
perror("posix_openpt failed");
return;
}
if (grantpt(ptyFd) < 0)
{
perror("grantpt failed");
close(ptyFd);
ptyFd = -1;
return;
}
if (unlockpt(ptyFd) < 0)
{
perror("unlockpt failed");
close(ptyFd);
ptyFd = -1;
return;
}
char *slaveName = ptsname(ptyFd);
if (!slaveName)
{
perror("ptsname failed");
close(ptyFd);
ptyFd = -1;
return;
}
childPid = fork();
if (childPid < 0)
{ // Fork failed
perror("fork failed");
close(ptyFd);
ptyFd = -1;
return;
}
if (childPid == 0)
{ // Child process
close(ptyFd); // Close master PTY in child
if (setsid() < 0)
{ // Create new session, detach from parent's controlling TTY
perror("setsid failed");
exit(EXIT_FAILURE);
}
// Open slave PTY
int slaveFd = open(slaveName, O_RDWR);
if (slaveFd < 0)
{
perror("open slave PTY failed");
exit(EXIT_FAILURE);
}
// Make the slave PTY the controlling terminal for this new session
if (ioctl(slaveFd, TIOCSCTTY, 0) < 0)
{
// This can fail if the process is not a session leader and already
// has a controlling TTY. setsid() should make us a session leader.
perror("ioctl TIOCSCTTY failed (can be non-fatal depending on "
"context)");
}
dup2(slaveFd, STDIN_FILENO);
dup2(slaveFd, STDOUT_FILENO);
dup2(slaveFd, STDERR_FILENO);
if (slaveFd > STDERR_FILENO)
{
close(slaveFd);
}
// Configure terminal modes for the slave PTY
struct termios tios;
if (tcgetattr(STDIN_FILENO, &tios) < 0)
{
perror("tcgetattr failed on slave pty");
exit(EXIT_FAILURE);
}
// Set reasonable default modes (from st/typical terminal settings)
tios.c_iflag = ICRNL | IXON | IXANY | IMAXBEL | BRKINT;
#ifdef IUTF8 // Common on Linux, good to enable if available
tios.c_iflag |= IUTF8;
#endif
tios.c_oflag =
OPOST | ONLCR; // OPOST: enable output processing, ONLCR: map NL to CR-NL
tios.c_cflag &= ~(CSIZE | PARENB); // Clear size and parity bits
tios.c_cflag |= CS8; // 8 bits per character
tios.c_cflag |= CREAD; // Enable receiver
tios.c_cflag |= HUPCL; // Hang up on last close (sends SIGHUP to
// foreground process group)
// Standard local modes for interactive shells
tios.c_lflag = ICANON | ISIG | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
if (tcsetattr(STDIN_FILENO, TCSANOW, &tios) < 0)
{
perror("tcsetattr failed on slave pty");
exit(EXIT_FAILURE);
}
// Set window size
struct winsize ws = {};
ws.ws_row = state.row; // Use initial rows/cols from Terminal state object
ws.ws_col = state.col;
if (ioctl(STDIN_FILENO, TIOCSWINSZ, &ws) < 0)
{
perror("ioctl TIOCSWINSZ failed on slave pty (non-fatal, shell "
"might misbehave)");
}
// Prepare environment for the shell
setenv("TERM", "xterm-256color", 1);
// Unsetting these is often good as the login shell will set them
// appropriately
unsetenv("COLUMNS");
unsetenv("LINES");
// Optionally, clear other inherited variables that might cause issues,
// e.g., unsetenv("TERMCAP"); unsetenv("WINDOWID"); // Common in some
// terminal emulators
#ifdef __APPLE__
// Revised logic for macOS: Launch as a login shell
const char *user_shell_from_passwd = nullptr;
struct passwd *pw = getpwuid(getuid());
if (pw && pw->pw_shell && pw->pw_shell[0] != '\0')
{
user_shell_from_passwd = pw->pw_shell;
}
const char *shell_to_launch_path_str = user_shell_from_passwd;
// Fallback 1: getenv("SHELL")
if (!shell_to_launch_path_str || shell_to_launch_path_str[0] == '\0')
{
shell_to_launch_path_str = getenv("SHELL");
}
// Fallback 2: Default to /bin/zsh (modern macOS default)
// If on an older Mac where /bin/bash is default, this might still be better.
if (!shell_to_launch_path_str || shell_to_launch_path_str[0] == '\0')
{
shell_to_launch_path_str = "/bin/zsh";
}
char shell_exec_path_buf[PATH_MAX]; // Full path to the executable
strncpy(shell_exec_path_buf,
shell_to_launch_path_str,
sizeof(shell_exec_path_buf));
shell_exec_path_buf[sizeof(shell_exec_path_buf) - 1] =
'\0'; // Ensure null termination
// Prepare argv[0] for the child shell: "-basename"
char shell_argv0_login[PATH_MAX + 1]; // +1 for the leading hyphen
shell_argv0_login[0] = '-'; // Signal to the shell to act as a login shell
const char *shell_basename_ptr = strrchr(shell_exec_path_buf, '/');
if (shell_basename_ptr)
{
// Found a '/', so use the part after it
strncpy(shell_argv0_login + 1,
shell_basename_ptr + 1,
sizeof(shell_argv0_login) - 2);
} else
{
// No '/', so use the whole path string (it's already a basename or
// relative)
strncpy(shell_argv0_login + 1,
shell_exec_path_buf,
sizeof(shell_argv0_login) - 2);
}
shell_argv0_login[sizeof(shell_argv0_login) - 1] =
'\0'; // Ensure null termination
// Arguments for a login shell.
char *const args[] = {shell_argv0_login, NULL};
// --- Debugging Output ---
fprintf(stderr, "[TERMINAL DEBUG] macOS Shell Launch Information:\n");
fprintf(stderr,
" User's pw_shell (from getpwuid): '%s'\n",
(pw && pw->pw_shell) ? pw->pw_shell : "(not found or empty)");
const char *env_shell_in_child = getenv("SHELL");
fprintf(stderr,
" getenv(\"SHELL\") in child process: '%s'\n",
env_shell_in_child ? env_shell_in_child : "(not set or empty)");
fprintf(stderr,
" Path to be executed (shell_exec_path_buf): '%s'\n",
shell_exec_path_buf);
fprintf(stderr,
" argv[0] for child shell (shell_argv0_login): '%s'\n",
args[0] ? args[0] : "(NULL)");
// --- End Debugging Output ---
execv(shell_exec_path_buf, args);
// If execv returns, an error occurred.
fprintf(stderr,
"FATAL: Failed to execv shell '%s' (intended argv[0]='%s'): %s\n",
shell_exec_path_buf,
args[0] ? args[0] : "(null)",
strerror(errno));
exit(EXIT_FAILURE); // Or exit(127) for command not found / exec failure
// Removed unreachable:
// std::this_thread::sleep_for(std::chrono::milliseconds(100));
#else
// Logic for Linux and other Unix-like systems (also launch as login shell)
char shell_path_buf[PATH_MAX];
const char *shell_env_val = getenv("SHELL"); // SHELL env var is primary on Linux
if (shell_env_val && shell_env_val[0] != '\0')
{
strncpy(shell_path_buf, shell_env_val, sizeof(shell_path_buf));
shell_path_buf[sizeof(shell_path_buf) - 1] = '\0';
} else
{
struct passwd *pw_linux = getpwuid(getuid()); // Fallback to passwd entry
if (pw_linux && pw_linux->pw_shell && pw_linux->pw_shell[0] != '\0')
{
strncpy(shell_path_buf, pw_linux->pw_shell, sizeof(shell_path_buf));
shell_path_buf[sizeof(shell_path_buf) - 1] = '\0';
} else
{
strncpy(shell_path_buf,
"/bin/bash",
sizeof(shell_path_buf)); // Absolute fallback for Linux
shell_path_buf[sizeof(shell_path_buf) - 1] = '\0';
}
}
char shell_argv0_login_linux[PATH_MAX + 1];
shell_argv0_login_linux[0] = '-';
const char *shell_basename_linux = strrchr(shell_path_buf, '/');
if (shell_basename_linux)
{
strncpy(shell_argv0_login_linux + 1,
shell_basename_linux + 1,
sizeof(shell_argv0_login_linux) - 2);
} else
{
strncpy(shell_argv0_login_linux + 1,
shell_path_buf,
sizeof(shell_argv0_login_linux) - 2);
}
shell_argv0_login_linux[sizeof(shell_argv0_login_linux) - 1] = '\0';
char *const new_argv_linux[] = {shell_argv0_login_linux, NULL};
// --- Debugging Output for Linux ---
fprintf(stderr, "[TERMINAL DEBUG] Linux/Other Shell Launch Information:\n");
struct passwd *pw_linux_debug = getpwuid(getuid());
fprintf(stderr,
" User's pw_shell (from getpwuid): '%s'\n",
(pw_linux_debug && pw_linux_debug->pw_shell) ? pw_linux_debug->pw_shell
: "(not found or empty)");
const char *env_shell_child_linux = getenv("SHELL");
fprintf(stderr,
" getenv(\"SHELL\") in child process: '%s'\n",
env_shell_child_linux ? env_shell_child_linux : "(not set or empty)");
fprintf(stderr, " Path to be executed (shell_path_buf): '%s'\n", shell_path_buf);
fprintf(stderr,
" argv[0] for child shell (new_argv_linux[0]): '%s'\n",
new_argv_linux[0] ? new_argv_linux[0] : "(NULL)");
// --- End Debugging Output for Linux ---
execv(shell_path_buf, new_argv_linux);
fprintf(stderr,
"FATAL: Failed to execv shell '%s' (intended argv[0]='%s'): %s\n",
shell_path_buf,
new_argv_linux[0] ? new_argv_linux[0] : "(null)",
strerror(errno));
exit(127); // Standard exit code for command not found / exec failure
#endif
}
// Parent process
// Make sure ptyFd is non-blocking for the read thread if select/poll isn't
// used This can be optional if read() behaves well or if your readOutput
// uses select/poll. int flags = fcntl(ptyFd, F_GETFL, 0); if (flags != -1)
// fcntl(ptyFd, F_SETFL, flags | O_NONBLOCK);
#ifdef __APPLE__
// Send initial commands (cd ~ and clear) to the shell on Apple systems.
// A short delay helps ensure the shell has initialized before receiving
// commands. This is a heuristic; 100ms is a common value.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::string command_str =
std::string("cd ~\nclear\n");
// 2. Now get the pointer. It's valid as long as command_str exists.
const char *initial_commands = command_str.c_str();
ssize_t bytes_written = write(ptyFd, initial_commands, strlen(initial_commands));
if (bytes_written == -1)
{
perror("write to pty (initial_commands for Apple) failed in parent");
// This is a non-critical enhancement, so we log the error and continue.
} else if (static_cast<size_t>(bytes_written) < strlen(initial_commands))
{
// Handle partial write, though unlikely for small command strings with TTYs.
fprintf(stderr, "Partial write to pty (initial_commands for Apple) in parent.\n");
}
#endif
readThread = std::thread(&Terminal::readOutput, this);
}
void Terminal::render()
{
if (!isVisible)
return;
if (ptyFd < 0)
{
startShell();
}
ImGuiIO &io = ImGui::GetIO();
checkFontSizeChange();
bool windowCreated = setupWindow();
// Only render terminal content if window is open and not collapsed
if (windowCreated && (!isEmbedded || !embeddedWindowCollapsed))
{
handleTerminalResize();
renderBuffer();
handleScrollback(io, state.row);
handleMouseInput(io);
handleKeyboardInput(io);
}
// Only call End() if Begin() was actually called and succeeded
if (windowCreated && isEmbedded)
{
ImGui::End();
}
}
void Terminal::renderBuffer()
{
std::lock_guard<std::mutex> lock(bufferMutex);
ImDrawList *drawList;
ImVec2 pos;
float charWidth, lineHeight;
setupRenderContext(drawList, pos, charWidth, lineHeight);
if (state.mode & MODE_ALTSCREEN)
{
renderAltScreen(drawList, pos, charWidth, lineHeight);
} else
{
renderMainScreen(drawList, pos, charWidth, lineHeight);
}
}
void Terminal::checkFontSizeChange()
{
float currentFontSize = ImGui::GetFont()->FontSize;
if (currentFontSize != lastFontSize)
{
lastFontSize = currentFontSize;
ImVec2 contentSize = ImGui::GetContentRegionAvail();
resize(state.col, state.row);
}
}
bool Terminal::setupWindow()
{
if (isEmbedded)
{
ImGui::SetNextWindowPos(embeddedWindowPos, ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(embeddedWindowSize, ImGuiCond_FirstUseEver);
bool windowOpen = true;
bool windowCreated =
ImGui::Begin("Terminal", &windowOpen, ImGuiWindowFlags_NoCollapse);
if (windowCreated)
{
embeddedWindowPos = ImGui::GetWindowPos();
embeddedWindowSize = ImGui::GetWindowSize();
embeddedWindowCollapsed = ImGui::IsWindowCollapsed();
if (!windowOpen)
{
isVisible = false;
}
} else
{
embeddedWindowCollapsed = true;
}
return windowCreated;
} else
{
// For standalone terminal, assume we're already inside an ImGui window
// and just return true to indicate we can render
return true;
}
}
void Terminal::handleTerminalResize()
{
ImVec2 contentSize = ImGui::GetContentRegionAvail();
float charWidth = ImGui::GetFont()->GetCharAdvance('M');
float lineHeight = ImGui::GetTextLineHeight();
int new_cols = std::max(1, static_cast<int>(contentSize.x / charWidth));
int new_rows = std::max(1, static_cast<int>(contentSize.y / lineHeight));
if (new_cols != state.col || new_rows != state.row)
{
std::cout << "resizing terminal" << std::endl;
resize(new_cols, new_rows);
}
}
void Terminal::handleScrollback(const ImGuiIO &io, int new_rows)
{
if (ImGui::IsWindowFocused() && ImGui::IsWindowHovered() &&
!(state.mode & MODE_ALTSCREEN))
{
if (io.MouseWheel != 0.0f)
{
int maxScroll =
std::max(0, (int)(scrollbackBuffer.size() + state.row) - new_rows);
// Reverse the scroll direction by changing subtraction to addition
scrollOffset += static_cast<int>(io.MouseWheel * 3);
scrollOffset = std::clamp(scrollOffset, 0, maxScroll);
}
}
}
void Terminal::handleMouseInput(const ImGuiIO &io)
{
if (!ImGui::IsWindowFocused() || !ImGui::IsWindowHovered())
return;
ImVec2 mousePos = ImGui::GetMousePos();
ImVec2 contentPos = ImGui::GetCursorScreenPos();
float charWidth = ImGui::GetFont()->GetCharAdvance('M');
float lineHeight = ImGui::GetTextLineHeight();
int cellX = static_cast<int>((mousePos.x - contentPos.x) / charWidth);
int cellY =
static_cast<int>((mousePos.y - contentPos.y + (lineHeight * 0.2)) / lineHeight);
cellX = std::clamp(cellX, 0, state.col - 1);
// Account for scrollback offset when not in alt screen
if (!(state.mode & MODE_ALTSCREEN))
{
ImVec2 contentSize = ImGui::GetContentRegionAvail();
int visibleRows = std::max(1, static_cast<int>(contentSize.y / lineHeight));
int totalLines = scrollbackBuffer.size() + state.row;
int maxScroll = std::max(0, totalLines - visibleRows);
scrollOffset = std::clamp(scrollOffset, 0, maxScroll);
int startLine = std::max(0, totalLines - visibleRows - scrollOffset);
// Convert visible Y coordinate to actual buffer coordinate
int actualY = startLine + cellY;
// Convert to selection coordinate system (relative to scrollback buffer)
cellY = actualY - scrollbackBuffer.size();
} else
{
// In alt screen, clamp to current screen
cellY = std::clamp(cellY, 0, state.row - 1);
}
static ImVec2 clickStartPos{0, 0};
if (ImGui::IsMouseClicked(ImGuiMouseButton_Left))
{
clickStartPos = mousePos;
selectionStart(cellX, cellY);
} else if (ImGui::IsMouseDragging(ImGuiMouseButton_Left))
{
ImVec2 dragDelta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Left);
float dragDistance = sqrt(dragDelta.x * dragDelta.x + dragDelta.y * dragDelta.y);
if (dragDistance > DRAG_THRESHOLD)
{
selectionExtend(cellX, cellY);
}
} else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left))
{
ImVec2 dragDelta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Left);
float dragDistance = sqrt(dragDelta.x * dragDelta.x + dragDelta.y * dragDelta.y);
if (dragDistance <= DRAG_THRESHOLD)
{
selectionClear();
}
}
if (ImGui::IsMouseClicked(ImGuiMouseButton_Right))
{
pasteFromClipboard();
}
// Handle clipboard shortcuts
if (io.KeyCtrl)
{
if (ImGui::IsKeyPressed(ImGuiKey_Y, false) ||
ImGui::IsKeyPressed(ImGuiKey_C, false))
{
copySelection();
}
if (ImGui::IsKeyPressed(ImGuiKey_V, false))
{
pasteFromClipboard();
}
}
}
void Terminal::handleKeyboardInput(const ImGuiIO &io)
{
if (!ImGui::IsWindowFocused())
return;
handleSpecialKeys(io);
handleControlCombos(io);
handleRegularTextInput(io);
}
void Terminal::handleSpecialKeys(const ImGuiIO &io)
{
if (ImGui::IsKeyPressed(ImGuiKey_Enter))
{
processInput("\r");
} else if (ImGui::IsKeyPressed(ImGuiKey_Backspace))
{
processInput("\x7f");
} else if (ImGui::IsKeyPressed(ImGuiKey_UpArrow))
{
processInput(state.mode & MODE_APPCURSOR ? "\033OA" : "\033[A");
} else if (ImGui::IsKeyPressed(ImGuiKey_DownArrow))
{
processInput(state.mode & MODE_APPCURSOR ? "\033OB" : "\033[B");
} else if (ImGui::IsKeyPressed(ImGuiKey_RightArrow))
{
processInput(state.mode & MODE_APPCURSOR ? "\033OC" : "\033[C");
} else if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow))
{
if (io.KeyCtrl)
{
processInput("\033[1;5D");
} else if (io.KeyShift)
{
processInput("\033[1;2D");
} else if (state.mode & MODE_APPCURSOR)
{
processInput("\033OD");
} else
{
processInput("\033[D");
}
} else if (ImGui::IsKeyPressed(ImGuiKey_Home))
{
processInput("\033[H");
} else if (ImGui::IsKeyPressed(ImGuiKey_End))
{
processInput("\033[F");
} else if (ImGui::IsKeyPressed(ImGuiKey_Delete))
{
processInput("\033[3~");
} else if (ImGui::IsKeyPressed(ImGuiKey_PageUp))
{
processInput("\033[5~");
} else if (ImGui::IsKeyPressed(ImGuiKey_PageDown))
{
processInput("\033[6~");
} else if (ImGui::IsKeyPressed(ImGuiKey_Tab))
{
processInput("\t");
} else if (ImGui::IsKeyPressed(ImGuiKey_Escape))
{
processInput("\033");
}
}
void Terminal::handleControlCombos(const ImGuiIO &io)
{
if (!io.KeyCtrl && !io.KeySuper)
return;
static const std::pair<ImGuiKey, char> controlKeys[] = {
{ImGuiKey_A, '\x01'}, {ImGuiKey_B, '\x02'}, {ImGuiKey_C, '\x03'},
{ImGuiKey_D, '\x04'}, {ImGuiKey_E, '\x05'}, {ImGuiKey_F, '\x06'},
{ImGuiKey_G, '\x07'}, {ImGuiKey_H, '\x08'}, {ImGuiKey_I, '\x09'},
{ImGuiKey_J, '\x0A'}, {ImGuiKey_K, '\x0B'}, {ImGuiKey_L, '\x0C'},
{ImGuiKey_M, '\x0D'}, {ImGuiKey_N, '\x0E'}, {ImGuiKey_O, '\x0F'},
{ImGuiKey_P, '\x10'}, {ImGuiKey_Q, '\x11'}, {ImGuiKey_R, '\x12'},
{ImGuiKey_S, '\x13'}, {ImGuiKey_T, '\x14'}, {ImGuiKey_U, '\x15'},
{ImGuiKey_W, '\x17'}, {ImGuiKey_X, '\x18'}, {ImGuiKey_Y, '\x19'},
{ImGuiKey_Z, '\x1A'}};
for (const auto &[key, ctrl_char] : controlKeys)
{
if (ImGui::IsKeyPressed(key))
{
processInput(std::string(1, ctrl_char));
}
}
}
void Terminal::handleRegularTextInput(const ImGuiIO &io)
{
if (io.KeySuper || io.KeyCtrl || io.KeyAlt)
return;
for (int i = 0; i < io.InputQueueCharacters.Size; i++)
{
char c = (char)io.InputQueueCharacters[i];
if (c != 0)
{
processInput(std::string(1, c));
}
}
}
void Terminal::setupRenderContext(ImDrawList *&drawList,
ImVec2 &pos,
float &charWidth,
float &lineHeight)
{
drawList = ImGui::GetWindowDrawList();
pos = ImGui::GetCursorScreenPos();
charWidth = ImGui::GetFont()->GetCharAdvance('M');
lineHeight = ImGui::GetTextLineHeight();
}
void Terminal::renderAltScreen(ImDrawList *drawList,
const ImVec2 &pos,
float charWidth,
float lineHeight)
{
// Handle selection highlight
if (sel.mode != SEL_IDLE && sel.ob.x != -1)
{
renderSelectionHighlight(drawList, pos, charWidth, lineHeight, 0, state.row);
}
// Draw alt screen characters
for (int y = 0; y < state.row; y++)
{
if (!state.dirty[y])
continue;
for (int x = 0; x < state.col; x++)
{
const Glyph &glyph = state.lines[y][x];
if (glyph.mode & ATTR_WDUMMY)
continue;
ImVec2 charPos(pos.x + x * charWidth, pos.y + y * lineHeight);
renderGlyph(drawList, glyph, charPos, charWidth, lineHeight);
if (glyph.mode & ATTR_WIDE)
x++;
}
}
// Draw cursor
if (ImGui::IsWindowFocused())
{
ImVec2 cursorPos(pos.x + state.c.x * charWidth, pos.y + state.c.y * lineHeight);
float alpha = (sin(ImGui::GetTime() * 3.14159f) * 0.3f) + 0.5f;
renderCursor(drawList,
cursorPos,
state.lines[state.c.y][state.c.x],
charWidth,
lineHeight,
alpha);
}
}
void Terminal::renderMainScreen(ImDrawList *drawList,
const ImVec2 &pos,
float charWidth,
float lineHeight)
{
ImVec2 contentSize = ImGui::GetContentRegionAvail();
int visibleRows = std::max(1, static_cast<int>(contentSize.y / lineHeight));
int totalLines = scrollbackBuffer.size() + state.row;
// Handle scrollback clamping
int maxScroll = std::max(0, totalLines - visibleRows);
scrollOffset = std::clamp(scrollOffset, 0, maxScroll);
int startLine = std::max(0, totalLines - visibleRows - scrollOffset);
// Handle selection highlighting
if (sel.mode != SEL_IDLE && sel.ob.x != -1)
{
renderSelectionHighlight(drawList,
pos,
charWidth,
lineHeight,
startLine,
startLine + visibleRows,
scrollbackBuffer.size());
}
// Draw content
for (int visY = 0; visY < visibleRows; visY++)
{
int currentLine = startLine + visY;
const std::vector<Glyph> *line = nullptr;
if (currentLine < scrollbackBuffer.size())
{
line = &scrollbackBuffer[currentLine];
} else
{
int screenY = currentLine - scrollbackBuffer.size();
if (screenY >= 0 && screenY < state.lines.size())
{
line = &state.lines[screenY];
}
}
if (!line)
continue;
for (int x = 0; x < state.col && x < line->size(); x++)
{
const Glyph &glyph = (*line)[x];
if (glyph.mode & ATTR_WDUMMY)
continue;
ImVec2 charPos(pos.x + x * charWidth, pos.y + visY * lineHeight);
renderGlyph(drawList, glyph, charPos, charWidth, lineHeight);
if (glyph.mode & ATTR_WIDE)
x++;
}
}
// Draw cursor when not scrolled
if (ImGui::IsWindowFocused() && scrollOffset == 0)
{
ImVec2 cursorPos(pos.x + state.c.x * charWidth,
pos.y + (visibleRows - (totalLines - scrollbackBuffer.size()) +
state.c.y) *
lineHeight);
float alpha = (sin(ImGui::GetTime() * 3.14159f) * 0.3f) + 0.5f;
renderCursor(drawList,
cursorPos,
state.lines[state.c.y][state.c.x],
charWidth,
lineHeight,
alpha);
}
}
void Terminal::renderGlyph(ImDrawList *drawList,
const Glyph &glyph,
const ImVec2 &charPos,
float charWidth,
float lineHeight)
{
ImVec4 fg = glyph.fg;
ImVec4 bg = glyph.bg;
handleGlyphColors(glyph, fg, bg);
// Draw background
if (bg.x != 0 || bg.y != 0 || bg.z != 0 || (glyph.mode & ATTR_REVERSE))
{
drawList->AddRectFilled(charPos,
ImVec2(charPos.x + charWidth, charPos.y + lineHeight),
ImGui::ColorConvertFloat4ToU32(bg));
}
// Draw character
if (glyph.u != ' ' && glyph.u != 0)
{
char text[UTF_SIZ] = {0};
utf8Encode(glyph.u, text);
drawList->AddText(charPos, ImGui::ColorConvertFloat4ToU32(fg), text);
}
// Draw underline
if (glyph.mode & ATTR_UNDERLINE)
{
drawList->AddLine(ImVec2(charPos.x, charPos.y + lineHeight - 1),
ImVec2(charPos.x + charWidth, charPos.y + lineHeight - 1),
ImGui::ColorConvertFloat4ToU32(fg));
}
}
void Terminal::handleGlyphColors(const Glyph &glyph, ImVec4 &fg, ImVec4 &bg)
{
// Handle true color
if (glyph.colorMode == COLOR_TRUE)
{
uint32_t tc = glyph.trueColorFg;
fg = ImVec4(((tc >> 16) & 0xFF) / 255.0f,
((tc >> 8) & 0xFF) / 255.0f,
(tc & 0xFF) / 255.0f,
1.0f);
}
// Handle reverse video
if (glyph.mode & ATTR_REVERSE)
{
std::swap(fg, bg);
}
// Handle bold
if (glyph.mode & ATTR_BOLD && glyph.colorMode == COLOR_BASIC)
{
fg.x = std::min(1.0f, fg.x * 1.5f);
fg.y = std::min(1.0f, fg.y * 1.5f);
fg.z = std::min(1.0f, fg.z * 1.5f);
}
}
void Terminal::renderCursor(ImDrawList *drawList,
const ImVec2 &cursorPos,
const Glyph &cursorCell,
float charWidth,
float lineHeight,
float alpha)
{
if (state.mode & MODE_INSERT)
{
drawList->AddRectFilled(cursorPos,
ImVec2(cursorPos.x + 2, cursorPos.y + lineHeight),
ImGui::ColorConvertFloat4ToU32(
ImVec4(0.7f, 0.7f, 0.7f, alpha)));
} else
{
if (cursorCell.u != 0)
{
char text[UTF_SIZ] = {0};
utf8Encode(cursorCell.u, text);
ImVec4 bg = cursorCell.fg;
ImVec4 fg = cursorCell.bg;
drawList->AddRectFilled(
cursorPos,
ImVec2(cursorPos.x + charWidth, cursorPos.y + lineHeight),
ImGui::ColorConvertFloat4ToU32(ImVec4(bg.x, bg.y, bg.z, alpha)));
drawList->AddText(cursorPos, ImGui::ColorConvertFloat4ToU32(fg), text);
} else
{
drawList->AddRectFilled(
cursorPos,
ImVec2(cursorPos.x + charWidth, cursorPos.y + lineHeight),
ImGui::ColorConvertFloat4ToU32(ImVec4(0.7f, 0.7f, 0.7f, alpha)));
}
}
}
void Terminal::renderSelectionHighlight(ImDrawList *drawList,
const ImVec2 &pos,
float charWidth,
float lineHeight,
int startY,
int endY,
int screenOffset)
{
for (int y = startY; y < endY; y++)
{
int screenY = y - screenOffset;