-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathterminal.cpp
More file actions
1452 lines (1251 loc) · 46.2 KB
/
Copy pathterminal.cpp
File metadata and controls
1452 lines (1251 loc) · 46.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
#include "terminal.h"
#include "application.h"
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <vector>
#ifdef _WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0A00
#endif
#include <consoleapi2.h>
#include <consoleapi3.h>
#include <processthreadsapi.h>
#include <windows.h>
#else
#include <fcntl.h>
#include <stdio.h>
#endif
namespace {
constexpr OurCell kDefaultCell{U' ', 0, 0, 0, 255, 255, 255};
#ifdef _WIN32
inline void closeHandleIfValid(HANDLE& h) {
if (h && h != INVALID_HANDLE_VALUE) {
::CloseHandle(h);
h = INVALID_HANDLE_VALUE;
}
}
inline std::wstring defaultShell() {
return widen(App::settings->getValue("terminal_cmd", std::string("cmd.exe")));
}
#else
inline int fdCloseIfValid(int& fd) {
if (fd >= 0) {
const int ret = ::close(fd);
fd = -1;
return ret;
}
return 0;
}
inline std::string defaultShell() {
std::string sh = App::settings->getValue("terminal_cmd", std::string("/bin/bash"));
if (sh.empty()) {
const char* env = std::getenv("SHELL");
sh = env ? env : "/bin/bash";
}
return sh;
}
static std::string wstringToUtf8(const std::wstring& wstr) {
MST::MonoString u = MST::toMonoString(
reinterpret_cast<const UChar32*>(wstr.data()),
static_cast<int32_t>(wstr.size()));
std::string out;
u.toUTF8String(out);
return out;
}
#endif
static inline int xtermMod(bool shift, bool alt, bool ctrl) {
return 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0);
}
static inline int clampDimension(int value) {
#ifdef _WIN32
// COORD uses signed 16-bit SHORT values.
constexpr int maxDimension = static_cast<int>(std::numeric_limits<SHORT>::max());
#else
constexpr int maxDimension = static_cast<int>(std::numeric_limits<uint16_t>::max());
#endif
return std::max(1, std::min(value, maxDimension));
}
} // namespace
// ============================================================================
// Construction / destruction
// ============================================================================
Terminal::Terminal(int cols, int rows, SCROLLDOWN sd)
: m_cols(clampDimension(cols)),
m_rows(clampDimension(rows)),
scrollDown(std::move(sd)) {
#ifdef _WIN32
ZeroMemory(&m_pi, sizeof(m_pi));
#endif
}
Terminal::~Terminal() {
stop();
}
// ============================================================================
// Lifecycle
// ============================================================================
#ifdef WIN32
std::string wstring_to_utf8_windows(const std::wstring& wstr) {
if (wstr.empty()) return std::string();
// Calculate required buffer size first
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
// Perform the actual conversion
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
#endif
bool Terminal::start(const std::wstring& shell) {
if (m_running.load(std::memory_order_acquire)) return true;
if (!initConPty()) {
teardownConPty();
return false;
}
#ifdef _WIN32
shellStr = shell.empty() ? wstring_to_utf8_windows(defaultShell()) : wstring_to_utf8_windows(shell);
if (!launchShell(shell.empty() ? defaultShell() : shell)) {
teardownConPty();
return false;
}
#else
shellStr = shell.empty() ? defaultShell() : wstringToUtf8(shell);
if (!launchShell(shellStr)) {
teardownConPty();
return false;
}
#endif
if (!initGhostty()) {
teardownConPty();
return false;
}
m_running.store(true, std::memory_order_release);
m_reader = std::thread(&Terminal::readerLoop, this);
return true;
}
void Terminal::stop() {
m_running.exchange(false, std::memory_order_acq_rel);
#ifdef _WIN32
if (m_hFromPty != INVALID_HANDLE_VALUE) ::CancelIoEx(m_hFromPty, nullptr);
if (m_hToPty != INVALID_HANDLE_VALUE) ::CancelIoEx(m_hToPty, nullptr);
if (m_reader.joinable()) m_reader.join();
closeHandleIfValid(m_hToPty);
closeHandleIfValid(m_hFromPty);
if (m_pi.hProcess) {
if (::WaitForSingleObject(m_pi.hProcess, 200) == WAIT_TIMEOUT) {
::TerminateProcess(m_pi.hProcess, 0);
}
closeHandleIfValid(m_pi.hProcess);
}
if (m_hPC) {
m_closePseudoConsole(m_hPC);
m_hPC = nullptr;
}
unloadConPtyApi();
#else
if (m_childPid > 0) {
::kill(m_childPid, SIGTERM);
int status = 0;
if (::waitpid(m_childPid, &status, WNOHANG) == 0) {
::kill(m_childPid, SIGKILL);
::waitpid(m_childPid, nullptr, 0);
}
m_childPid = -1;
}
fdCloseIfValid(m_masterFd);
if (m_reader.joinable()) m_reader.join();
#endif
teardownGhostty();
}
bool Terminal::resize(int cols, int rows) {
return resize(cols, rows,
m_cellWidthPx.load(std::memory_order_acquire),
m_cellHeightPx.load(std::memory_order_acquire));
}
bool Terminal::resize(int cols, int rows, int cellWidthPx, int cellHeightPx) {
cols = clampDimension(cols);
rows = clampDimension(rows);
cellWidthPx = std::max(cellWidthPx, 1);
cellHeightPx = std::max(cellHeightPx, 1);
RERENDER.store(true, std::memory_order_release);
std::lock_guard<std::mutex> resizeLock(m_resizeMutex);
auto resizeModel = [&](int targetCols,
int targetRows,
int targetCellWidth,
int targetCellHeight) -> bool {
std::lock_guard<std::mutex> stateLock(m_stateMutex);
if (!m_terminal) {
m_cols.store(targetCols, std::memory_order_release);
m_rows.store(targetRows, std::memory_order_release);
m_cellWidthPx.store(targetCellWidth, std::memory_order_release);
m_cellHeightPx.store(targetCellHeight, std::memory_order_release);
m_viewCells.assign(
static_cast<size_t>(targetCols) * static_cast<size_t>(targetRows),
kDefaultCell);
return true;
}
refreshTerminalMetadataLocked();
// If the user is looking at history, preserve the actual top-left
// cell rather than an absolute row number. Reflow changes row numbers,
// but a tracked grid ref follows the cell through that reflow.
const bool wasAtBottom =
m_scrollbar.offset + m_scrollbar.len >= m_scrollbar.total;
GhosttyTrackedGridRef viewportAnchor = nullptr;
if (!wasAtBottom) {
GhosttyPoint topLeft{};
topLeft.tag = GHOSTTY_POINT_TAG_VIEWPORT;
topLeft.value.coordinate.x = 0;
topLeft.value.coordinate.y = 0;
if (ghostty_terminal_grid_ref_track(
m_terminal, topLeft, &viewportAnchor) != GHOSTTY_SUCCESS) {
viewportAnchor = nullptr;
}
}
const GhosttyResult resizeResult = ghostty_terminal_resize(
m_terminal,
static_cast<uint16_t>(targetCols),
static_cast<uint16_t>(targetRows),
static_cast<uint32_t>(targetCellWidth),
static_cast<uint32_t>(targetCellHeight));
if (resizeResult != GHOSTTY_SUCCESS) {
if (viewportAnchor) ghostty_tracked_grid_ref_free(viewportAnchor);
return false;
}
m_cols.store(targetCols, std::memory_order_release);
m_rows.store(targetRows, std::memory_order_release);
m_cellWidthPx.store(targetCellWidth, std::memory_order_release);
m_cellHeightPx.store(targetCellHeight, std::memory_order_release);
if (viewportAnchor) {
GhosttyPointCoordinate resolved{};
if (ghostty_tracked_grid_ref_point(
viewportAnchor,
GHOSTTY_POINT_TAG_SCREEN,
&resolved) == GHOSTTY_SUCCESS) {
GhosttyTerminalScrollViewport scroll{};
scroll.tag = GHOSTTY_SCROLL_VIEWPORT_ROW;
scroll.value.row = static_cast<size_t>(resolved.y);
ghostty_terminal_scroll_viewport(m_terminal, scroll);
}
ghostty_tracked_grid_ref_free(viewportAnchor);
}
updateMouseGeometryLocked();
refreshTerminalMetadataLocked();
m_renderSnapshotDirty = true;
return true;
};
const int oldCols = m_cols.load(std::memory_order_acquire);
const int oldRows = m_rows.load(std::memory_order_acquire);
const int oldCellWidth = m_cellWidthPx.load(std::memory_order_acquire);
const int oldCellHeight = m_cellHeightPx.load(std::memory_order_acquire);
#ifdef _WIN32
// A pixel-size-only update does not require a ConPTY resize. In particular,
// the post-start resize that changes 1x1 cell metrics must not trigger an
// unnecessary ConPTY repaint at the same row/column geometry.
const bool ptyGeometryChanged = oldCols != cols || oldRows != rows;
if (!m_hPC || !ptyGeometryChanged) {
return resizeModel(cols, rows, cellWidthPx, cellHeightPx);
}
// Keep reading the output pipe during ResizePseudoConsole, but temporarily
// queue the bytes instead of parsing them. This avoids both interleaving the
// ConPTY repaint with libghostty's reflow and blocking a large repaint while
// holding m_stateMutex.
{
std::lock_guard<std::mutex> gateLock(m_outputGateMutex);
m_resizeInProgress = true;
}
auto finishPtyResize = [&]() {
bool parsedPendingOutput = false;
std::unique_lock<std::mutex> gateLock(m_outputGateMutex);
std::vector<uint8_t> pending;
pending.swap(m_pendingPtyOutput);
if (!pending.empty()) {
std::lock_guard<std::mutex> stateLock(m_stateMutex);
if (m_terminal) {
ghostty_terminal_vt_write(
m_terminal, pending.data(), pending.size());
refreshTerminalMetadataLocked();
m_renderSnapshotDirty = true;
parsedPendingOutput = true;
}
}
// The gate remains locked until queued bytes have been parsed. A reader
// that already completed ReadFile cannot overtake them.
m_resizeInProgress = false;
gateLock.unlock();
if (parsedPendingOutput) {
App::time_till_regular = std::max(App::time_till_regular, 2);
RERENDER.store(true, std::memory_order_release);
}
};
COORD size{};
size.X = static_cast<SHORT>(cols);
size.Y = static_cast<SHORT>(rows);
const HRESULT ptyResizeResult = m_resizePseudoConsole(m_hPC, size);
if (FAILED(ptyResizeResult)) {
std::cerr << "ResizePseudoConsole failed: hr=0x"
<< std::hex << ptyResizeResult << std::dec << "\n";
finishPtyResize();
return false;
}
if (!resizeModel(cols, rows, cellWidthPx, cellHeightPx)) {
// ConPTY accepted the new size but libghostty did not. Restore ConPTY so
// the child and renderer do not remain permanently out of sync.
COORD oldSize{};
oldSize.X = static_cast<SHORT>(oldCols);
oldSize.Y = static_cast<SHORT>(oldRows);
const HRESULT rollbackResult = m_resizePseudoConsole(m_hPC, oldSize);
if (FAILED(rollbackResult)) {
std::cerr << "ResizePseudoConsole rollback failed: hr=0x"
<< std::hex << rollbackResult << std::dec << "\n";
}
finishPtyResize();
return false;
}
finishPtyResize();
return true;
#else
if (!resizeModel(cols, rows, cellWidthPx, cellHeightPx)) return false;
if (m_masterFd >= 0) {
struct winsize ws{};
ws.ws_row = static_cast<unsigned short>(rows);
ws.ws_col = static_cast<unsigned short>(cols);
ws.ws_xpixel = static_cast<unsigned short>(std::min(cols * cellWidthPx, 65535));
ws.ws_ypixel = static_cast<unsigned short>(std::min(rows * cellHeightPx, 65535));
if (::ioctl(m_masterFd, TIOCSWINSZ, &ws) < 0) {
resizeModel(oldCols, oldRows, oldCellWidth, oldCellHeight);
return false;
}
}
return true;
#endif
}
// ============================================================================
// ConPTY / PTY
// ============================================================================
#ifdef _WIN32
void Terminal::loadConPtyApi() {
// Start with the inbox API. A current side-by-side conpty.dll plus its
// matching OpenConsole.exe can be placed beside this executable to avoid
// depending on the older ConPTY implementation bundled with the OS.
unloadConPtyApi();
wchar_t executablePath[32768]{};
const DWORD pathLength = ::GetModuleFileNameW(
nullptr, executablePath,
static_cast<DWORD>(sizeof(executablePath) / sizeof(executablePath[0])));
if (pathLength == 0 || pathLength >= sizeof(executablePath) / sizeof(executablePath[0])) {
return;
}
std::wstring dllPath(executablePath, pathLength);
const size_t slash = dllPath.find_last_of(L"\\/");
if (slash == std::wstring::npos) return;
dllPath.resize(slash + 1);
dllPath += L"conpty.dll";
HMODULE module = ::LoadLibraryExW(
dllPath.c_str(), nullptr,
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
if (!module) return;
FARPROC createProc = ::GetProcAddress(module, "CreatePseudoConsole");
if (!createProc) createProc = ::GetProcAddress(module, "ConptyCreatePseudoConsole");
FARPROC resizeProc = ::GetProcAddress(module, "ResizePseudoConsole");
if (!resizeProc) resizeProc = ::GetProcAddress(module, "ConptyResizePseudoConsole");
FARPROC closeProc = ::GetProcAddress(module, "ClosePseudoConsole");
if (!closeProc) closeProc = ::GetProcAddress(module, "ConptyClosePseudoConsole");
auto createFn = reinterpret_cast<CreatePseudoConsoleFn>(createProc);
auto resizeFn = reinterpret_cast<ResizePseudoConsoleFn>(resizeProc);
auto closeFn = reinterpret_cast<ClosePseudoConsoleFn>(closeProc);
if (!createFn || !resizeFn || !closeFn) {
::FreeLibrary(module);
return;
}
m_conPtyModule = module;
m_createPseudoConsole = createFn;
m_resizePseudoConsole = resizeFn;
m_closePseudoConsole = closeFn;
m_usingSideBySideConPty = true;
std::cerr << "Loaded side-by-side conpty.dll; use its matching OpenConsole.exe.\n";
}
void Terminal::unloadConPtyApi() {
{
std::lock_guard<std::mutex> gateLock(m_outputGateMutex);
m_resizeInProgress = false;
m_pendingPtyOutput.clear();
}
if (m_conPtyModule) {
::FreeLibrary(m_conPtyModule);
m_conPtyModule = nullptr;
}
m_createPseudoConsole = &::CreatePseudoConsole;
m_resizePseudoConsole = &::ResizePseudoConsole;
m_closePseudoConsole = &::ClosePseudoConsole;
m_usingSideBySideConPty = false;
}
bool Terminal::initConPty() {
loadConPtyApi();
if (!m_usingSideBySideConPty) {
static std::once_flag inboxWarningOnce;
std::call_once(inboxWarningOnce, [] {
std::cerr
<< "Using the Windows inbox ConPTY. Older Windows builds can repaint "
"and truncate host-managed scrollback during resize; bundle a current "
"conpty.dll and matching OpenConsole.exe beside the application.\n";
});
}
HANDLE hPtyInRead = INVALID_HANDLE_VALUE;
if (!::CreatePipe(&hPtyInRead, &m_hToPty, nullptr, 0)) {
std::cerr << "CreatePipe (to PTY) failed: " << GetLastError() << "\n";
return false;
}
HANDLE hPtyOutWrite = INVALID_HANDLE_VALUE;
if (!::CreatePipe(&m_hFromPty, &hPtyOutWrite, nullptr, 0)) {
std::cerr << "CreatePipe (from PTY) failed: " << GetLastError() << "\n";
closeHandleIfValid(hPtyInRead);
closeHandleIfValid(m_hToPty);
return false;
}
COORD size{};
size.X = static_cast<SHORT>(m_cols.load());
size.Y = static_cast<SHORT>(m_rows.load());
// Only pass documented flags. The old internal value 0x2 is not a feature
// probe: CreatePseudoConsole may succeed while silently ignoring that bit.
HRESULT hr = m_createPseudoConsole(
size, hPtyInRead, hPtyOutWrite, 0, &m_hPC);
// A broken or mismatched side-by-side installation should not prevent the
// terminal from starting. Retry with the inbox implementation.
if (FAILED(hr) && m_usingSideBySideConPty) {
if (m_hPC) {
m_closePseudoConsole(m_hPC);
m_hPC = nullptr;
}
std::cerr << "Side-by-side ConPTY failed; retrying with the Windows inbox API.\n";
unloadConPtyApi();
hr = m_createPseudoConsole(size, hPtyInRead, hPtyOutWrite, 0, &m_hPC);
}
closeHandleIfValid(hPtyInRead);
closeHandleIfValid(hPtyOutWrite);
if (FAILED(hr)) {
std::cerr << "CreatePseudoConsole failed: hr=0x" << std::hex << hr << std::dec << "\n";
closeHandleIfValid(m_hToPty);
closeHandleIfValid(m_hFromPty);
unloadConPtyApi();
return false;
}
return true;
}
bool Terminal::launchShell(const std::wstring& shell) {
SIZE_T attrListSize = 0;
::InitializeProcThreadAttributeList(nullptr, 1, 0, &attrListSize);
std::vector<char> attrStorage(attrListSize);
auto attrList = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attrStorage.data());
if (!::InitializeProcThreadAttributeList(attrList, 1, 0, &attrListSize)) {
std::cerr << "InitializeProcThreadAttributeList failed: " << GetLastError() << "\n";
return false;
}
if (!::UpdateProcThreadAttribute(
attrList, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
m_hPC, sizeof(m_hPC), nullptr, nullptr)) {
std::cerr << "UpdateProcThreadAttribute failed: " << GetLastError() << "\n";
::DeleteProcThreadAttributeList(attrList);
return false;
}
STARTUPINFOEXW siex{};
siex.StartupInfo.cb = sizeof(siex);
siex.lpAttributeList = attrList;
std::wstring cmdline = shell;
const DWORD flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT;
const BOOL ok = ::CreateProcessW(
nullptr, cmdline.data(), nullptr, nullptr, FALSE, flags,
nullptr, nullptr, &siex.StartupInfo, &m_pi);
::DeleteProcThreadAttributeList(attrList);
if (!ok) return false;
closeHandleIfValid(m_pi.hThread);
return true;
}
void Terminal::teardownConPty() {
closeHandleIfValid(m_hToPty);
closeHandleIfValid(m_hFromPty);
if (m_pi.hProcess) {
::TerminateProcess(m_pi.hProcess, 0);
closeHandleIfValid(m_pi.hProcess);
}
if (m_hPC) {
m_closePseudoConsole(m_hPC);
m_hPC = nullptr;
}
unloadConPtyApi();
}
void Terminal::readerLoop() {
constexpr DWORD kBufferSize = 16384;
std::vector<uint8_t> buffer(kBufferSize);
while (m_running.load(std::memory_order_acquire)) {
const HANDLE h = m_hFromPty;
if (h == INVALID_HANDLE_VALUE) break;
DWORD got = 0;
const BOOL ok = ::ReadFile(h, buffer.data(), kBufferSize, &got, nullptr);
if (!ok) {
const DWORD err = ::GetLastError();
if (err == ERROR_OPERATION_ABORTED || err == ERROR_BROKEN_PIPE) break;
break;
}
if (got == 0) break;
bool queuedForResize = false;
{
// ResizePseudoConsole may emit a full-screen repaint. Continue draining
// the pipe while a resize is active, but let resize() parse these bytes
// only after libghostty has adopted the matching geometry.
std::unique_lock<std::mutex> gateLock(m_outputGateMutex);
if (m_resizeInProgress) {
m_pendingPtyOutput.insert(
m_pendingPtyOutput.end(), buffer.begin(), buffer.begin() + got);
queuedForResize = true;
} else {
std::lock_guard<std::mutex> stateLock(m_stateMutex);
if (!m_terminal) continue;
ghostty_terminal_vt_write(
m_terminal, buffer.data(), static_cast<size_t>(got));
refreshTerminalMetadataLocked();
m_renderSnapshotDirty = true;
}
}
if (!queuedForResize) {
App::time_till_regular = std::max(App::time_till_regular, 2);
RERENDER.store(true, std::memory_order_release);
}
}
}
#else // Linux
bool Terminal::initConPty() {
m_masterFd = ::posix_openpt(O_RDWR | O_NOCTTY);
if (m_masterFd < 0) {
std::cerr << "posix_openpt failed: " << strerror(errno) << "\n";
return false;
}
if (::grantpt(m_masterFd) < 0) {
std::cerr << "grantpt failed: " << strerror(errno) << "\n";
fdCloseIfValid(m_masterFd);
return false;
}
if (::unlockpt(m_masterFd) < 0) {
std::cerr << "unlockpt failed: " << strerror(errno) << "\n";
fdCloseIfValid(m_masterFd);
return false;
}
struct winsize ws{};
ws.ws_row = static_cast<unsigned short>(m_rows.load());
ws.ws_col = static_cast<unsigned short>(m_cols.load());
::ioctl(m_masterFd, TIOCSWINSZ, &ws);
return true;
}
bool Terminal::launchShell(const std::string& shell) {
m_childPid = ::fork();
if (m_childPid < 0) {
std::cerr << "fork failed: " << strerror(errno) << "\n";
return false;
}
if (m_childPid == 0) {
if (::setsid() < 0) ::_exit(1);
const char* ptsName = ::ptsname(m_masterFd);
if (!ptsName) ::_exit(1);
const int slave = ::open(ptsName, O_RDWR);
if (slave < 0) ::_exit(1);
::ioctl(slave, TIOCSCTTY, 0);
::close(m_masterFd);
::dup2(slave, STDIN_FILENO);
::dup2(slave, STDOUT_FILENO);
::dup2(slave, STDERR_FILENO);
if (slave > STDERR_FILENO) ::close(slave);
::setenv("TERM", "xterm-256color", 1);
::setenv("COLORTERM", "truecolor", 1);
const char* sh = shell.c_str();
const char* shBase = std::strrchr(sh, '/');
shBase = shBase ? shBase + 1 : sh;
::execlp(sh, shBase, nullptr);
::_exit(1);
}
return true;
}
void Terminal::teardownConPty() {
fdCloseIfValid(m_masterFd);
if (m_childPid > 0) {
::kill(m_childPid, SIGTERM);
::waitpid(m_childPid, nullptr, WNOHANG);
m_childPid = -1;
}
}
void Terminal::readerLoop() {
constexpr size_t kBufferSize = 16384;
std::vector<uint8_t> buffer(kBufferSize);
while (m_running.load(std::memory_order_acquire)) {
const int fd = m_masterFd;
if (fd < 0) break;
const ssize_t got = ::read(fd, buffer.data(), buffer.size());
if (got <= 0) {
if (got < 0 && errno == EINTR) continue;
break;
}
{
std::lock_guard<std::mutex> lock(m_stateMutex);
if (!m_terminal) continue;
ghostty_terminal_vt_write(m_terminal, buffer.data(), static_cast<size_t>(got));
refreshTerminalMetadataLocked();
m_renderSnapshotDirty = true;
}
App::time_till_regular = std::max(App::time_till_regular, 2);
RERENDER.store(true, std::memory_order_release);
}
}
#endif
// ============================================================================
// libghostty state and rendering
// ============================================================================
bool Terminal::initGhostty() {
std::lock_guard<std::mutex> lock(m_stateMutex);
GhosttyTerminalOptions options{};
options.cols = static_cast<uint16_t>(m_cols.load());
options.rows = static_cast<uint16_t>(m_rows.load());
options.max_scrollback = m_scrollbackMax;
if (ghostty_terminal_new(nullptr, &m_terminal, options) != GHOSTTY_SUCCESS) return false;
if (ghostty_render_state_new(nullptr, &m_renderState) != GHOSTTY_SUCCESS) {
teardownGhostty();
return false;
}
if (ghostty_render_state_row_iterator_new(nullptr, &m_rowIterator) != GHOSTTY_SUCCESS) {
teardownGhostty();
return false;
}
if (ghostty_render_state_row_cells_new(nullptr, &m_rowCells) != GHOSTTY_SUCCESS) {
teardownGhostty();
return false;
}
if (ghostty_mouse_encoder_new(nullptr, &m_mouseEncoder) != GHOSTTY_SUCCESS) {
teardownGhostty();
return false;
}
if (ghostty_mouse_event_new(nullptr, &m_mouseEvent) != GHOSTTY_SUCCESS) {
teardownGhostty();
return false;
}
if (ghostty_terminal_set(m_terminal, GHOSTTY_TERMINAL_OPT_USERDATA, this) != GHOSTTY_SUCCESS ||
ghostty_terminal_set(m_terminal, GHOSTTY_TERMINAL_OPT_WRITE_PTY,
reinterpret_cast<const void*>(&Terminal::sWritePty)) != GHOSTTY_SUCCESS) {
teardownGhostty();
return false;
}
ghostty_terminal_resize(
m_terminal,
static_cast<uint16_t>(m_cols.load()),
static_cast<uint16_t>(m_rows.load()),
static_cast<uint32_t>(m_cellWidthPx.load()),
static_cast<uint32_t>(m_cellHeightPx.load()));
updateMouseGeometryLocked();
m_terminalReady.store(true, std::memory_order_release);
return refreshRenderStateLocked();
}
void Terminal::teardownGhostty() {
m_terminalReady.store(false, std::memory_order_release);
// This function is also used by initGhostty while the mutex is already held.
if (m_mouseEvent) {
ghostty_mouse_event_free(m_mouseEvent);
m_mouseEvent = nullptr;
}
if (m_mouseEncoder) {
ghostty_mouse_encoder_free(m_mouseEncoder);
m_mouseEncoder = nullptr;
}
if (m_rowCells) {
ghostty_render_state_row_cells_free(m_rowCells);
m_rowCells = nullptr;
}
if (m_rowIterator) {
ghostty_render_state_row_iterator_free(m_rowIterator);
m_rowIterator = nullptr;
}
if (m_renderState) {
ghostty_render_state_free(m_renderState);
m_renderState = nullptr;
}
if (m_terminal) {
ghostty_terminal_free(m_terminal);
m_terminal = nullptr;
}
m_viewCells.clear();
m_renderSnapshotDirty = true;
}
GhosttyColorRgb Terminal::resolveColor(const GhosttyStyleColor& color,
const GhosttyRenderStateColors& colors,
GhosttyColorRgb fallback) {
switch (color.tag) {
case GHOSTTY_STYLE_COLOR_RGB:
return color.value.rgb;
case GHOSTTY_STYLE_COLOR_PALETTE:
return colors.palette[color.value.palette];
default:
return fallback;
}
}
void Terminal::refreshTerminalMetadataLocked() {
GhosttyTerminalScreen screen = GHOSTTY_TERMINAL_SCREEN_PRIMARY;
bool mouse = false;
GhosttyTerminalScrollbar scrollbar{};
ghostty_terminal_get(m_terminal, GHOSTTY_TERMINAL_DATA_ACTIVE_SCREEN, &screen);
ghostty_terminal_get(m_terminal, GHOSTTY_TERMINAL_DATA_MOUSE_TRACKING, &mouse);
ghostty_terminal_get(m_terminal, GHOSTTY_TERMINAL_DATA_SCROLLBAR, &scrollbar);
m_altScreen.store(screen == GHOSTTY_TERMINAL_SCREEN_ALTERNATE, std::memory_order_release);
m_mouseReporting.store(mouse, std::memory_order_release);
m_scrollbar = scrollbar;
if (m_mouseEncoder) ghostty_mouse_encoder_setopt_from_terminal(m_mouseEncoder, m_terminal);
}
bool Terminal::refreshRenderStateLocked() {
if (!m_terminal || !m_renderState || !m_rowIterator || !m_rowCells) return false;
if (ghostty_render_state_update(m_renderState, m_terminal) != GHOSTTY_SUCCESS) return false;
GhosttyRenderStateColors colors{};
colors.size = sizeof(colors);
if (ghostty_render_state_colors_get(m_renderState, &colors) == GHOSTTY_SUCCESS) {
m_colors = colors;
}
refreshTerminalMetadataLocked();
const int cols = m_cols.load(std::memory_order_acquire);
const int rows = m_rows.load(std::memory_order_acquire);
m_viewCells.assign(static_cast<size_t>(cols) * static_cast<size_t>(rows), kDefaultCell);
if (ghostty_render_state_get(
m_renderState, GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR, &m_rowIterator) != GHOSTTY_SUCCESS) {
return false;
}
int rowIndex = 0;
while (rowIndex < rows && ghostty_render_state_row_iterator_next(m_rowIterator)) {
if (ghostty_render_state_row_get(
m_rowIterator, GHOSTTY_RENDER_STATE_ROW_DATA_CELLS, &m_rowCells) != GHOSTTY_SUCCESS) {
++rowIndex;
continue;
}
int colIndex = 0;
while (colIndex < cols && ghostty_render_state_row_cells_next(m_rowCells)) {
uint32_t graphemeLen = 0;
ghostty_render_state_row_cells_get(
m_rowCells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_LEN, &graphemeLen);
uint32_t codepoint = U' ';
if (graphemeLen > 0) {
uint32_t inlineGraphemes[16]{};
if (graphemeLen <= 16) {
ghostty_render_state_row_cells_get(
m_rowCells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF, inlineGraphemes);
codepoint = inlineGraphemes[0];
} else {
std::vector<uint32_t> graphemes(graphemeLen);
ghostty_render_state_row_cells_get(
m_rowCells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF, graphemes.data());
codepoint = graphemes[0];
}
}
GhosttyStyle style{};
style.size = sizeof(style);
ghostty_render_state_row_cells_get(
m_rowCells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_STYLE, &style);
GhosttyColorRgb fg = m_colors.foreground;
GhosttyColorRgb bg = m_colors.background;
ghostty_render_state_row_cells_get(
m_rowCells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_FG_COLOR, &fg);
ghostty_render_state_row_cells_get(
m_rowCells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR, &bg);
if (style.inverse) std::swap(fg, bg);
if (style.invisible) fg = bg;
OurCell cell{};
cell.c = static_cast<UChar32>(codepoint);
cell.bg_red = bg.r;
cell.bg_green = bg.g;
cell.bg_blue = bg.b;
cell.fg_red = fg.r;
cell.fg_green = fg.g;
cell.fg_blue = fg.b;
m_viewCells[static_cast<size_t>(rowIndex) * cols + colIndex] = cell;
++colIndex;
}
const bool cleanRow = false;
ghostty_render_state_row_set(
m_rowIterator, GHOSTTY_RENDER_STATE_ROW_OPTION_DIRTY, &cleanRow);
++rowIndex;
}
bool cursorVisible = false;
bool cursorBlinking = false;
bool cursorInViewport = false;
ghostty_render_state_get(
m_renderState, GHOSTTY_RENDER_STATE_DATA_CURSOR_VISIBLE, &cursorVisible);
ghostty_render_state_get(
m_renderState, GHOSTTY_RENDER_STATE_DATA_CURSOR_BLINKING, &cursorBlinking);
ghostty_render_state_get(
m_renderState, GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_HAS_VALUE, &cursorInViewport);
CursorInfo cursor{};
cursor.visible = cursorVisible && cursorInViewport;
cursor.blink = cursorBlinking;
if (cursor.visible) {
uint16_t x = 0;
uint16_t y = 0;
GhosttyRenderStateCursorVisualStyle visual = GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK;
ghostty_render_state_get(
m_renderState, GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_X, &x);
ghostty_render_state_get(
m_renderState, GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_Y, &y);
ghostty_render_state_get(
m_renderState, GHOSTTY_RENDER_STATE_DATA_CURSOR_VISUAL_STYLE, &visual);
cursor.col = x;
cursor.row = y;
switch (visual) {
case GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_UNDERLINE: cursor.shape = 2; break;
case GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BAR: cursor.shape = 3; break;
default: cursor.shape = 1; break;
}
}
m_cursorInfo = cursor;
GhosttyRenderStateDirty clean = GHOSTTY_RENDER_STATE_DIRTY_FALSE;
ghostty_render_state_set(m_renderState, GHOSTTY_RENDER_STATE_OPTION_DIRTY, &clean);
m_renderSnapshotDirty = false;
return true;
}
void Terminal::updateMouseGeometryLocked() {
if (!m_mouseEncoder) return;
GhosttyMouseEncoderSize size{};
size.size = sizeof(size);
size.cell_width = static_cast<uint32_t>(std::max(m_cellWidthPx.load(), 1));
size.cell_height = static_cast<uint32_t>(std::max(m_cellHeightPx.load(), 1));
size.screen_width = static_cast<uint32_t>(m_cols.load()) * size.cell_width;
size.screen_height = static_cast<uint32_t>(m_rows.load()) * size.cell_height;
size.padding_top = 0;
size.padding_bottom = 0;
size.padding_left = 0;
size.padding_right = 0;
ghostty_mouse_encoder_setopt(m_mouseEncoder, GHOSTTY_MOUSE_ENCODER_OPT_SIZE, &size);
}
void Terminal::sWritePty(GhosttyTerminal, void* userdata, const uint8_t* data, size_t len) {
auto* self = static_cast<Terminal*>(userdata);
if (self && data && len > 0) self->writeInput(data, len);
}
// ============================================================================
// Cell/document access
// ============================================================================
OurCell Terminal::getCell(int row, int col) {
std::lock_guard<std::mutex> lock(m_stateMutex);
if (m_renderSnapshotDirty) refreshRenderStateLocked();
const int rows = m_rows.load();
const int cols = m_cols.load();
if (row < 0 || col < 0 || row >= rows || col >= cols) return kDefaultCell;
const size_t index = static_cast<size_t>(row) * cols + col;
return index < m_viewCells.size() ? m_viewCells[index] : kDefaultCell;
}
CursorInfo Terminal::getCursorInfo() {
std::lock_guard<std::mutex> lock(m_stateMutex);
if (m_renderSnapshotDirty) refreshRenderStateLocked();
CursorInfo result = m_cursorInfo;
if (!m_terminalReady.load(std::memory_order_acquire)) result.visible = false;
return result;
}
bool Terminal::getViewSnapshot(std::vector<OurCell>& cells,
CursorInfo& cursor,
int& cols,
int& rows) {
std::lock_guard<std::mutex> lock(m_stateMutex);
if (m_renderSnapshotDirty && !refreshRenderStateLocked()) return false;
cols = m_cols.load(std::memory_order_acquire);
rows = m_rows.load(std::memory_order_acquire);
cells = m_viewCells;
cursor = m_cursorInfo;
if (!m_terminalReady.load(std::memory_order_acquire)) cursor.visible = false;
return cells.size() == static_cast<size_t>(cols) * static_cast<size_t>(rows);
}
std::string Terminal::getLastTextLines(int maxLogicalLines) {
if (maxLogicalLines <= 0) return {};
std::lock_guard<std::mutex> lock(m_stateMutex);