-
-
Notifications
You must be signed in to change notification settings - Fork 597
Expand file tree
/
Copy pathapp.cpp
More file actions
1714 lines (1470 loc) · 48.3 KB
/
Copy pathapp.cpp
File metadata and controls
1714 lines (1470 loc) · 48.3 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
// Copyright 2020 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <algorithm> // for any_of, copy, max, min
#include <array> // for array
#include <atomic>
#include <chrono> // for operator-, milliseconds, operator>=, duration, common_type<>::type, time_point
#include <csignal> // for signal, SIGTSTP, SIGABRT, SIGWINCH, raise, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM, __sighandler_t, size_t
#include <cstdint>
#include <cstdio> // for fileno, stdin
#include <ftxui/component/app.hpp>
#include <ftxui/component/task.hpp> // for Task, Closure, AnimationTask
#include <ftxui/screen/screen.hpp> // for Cell, Screen::Cursor, Screen, Screen::Cursor::Hidden
#include <functional> // for function
#include <initializer_list> // for initializer_list
#include <iostream> // for cout, ostream, operator<<, basic_ostream, endl, flush
#include <map>
#include <memory>
#include <stack> // for stack
#include <string>
#include <string_view>
#include <thread> // for thread, sleep_for
#include <tuple> // for _Swallow_assign, ignore
#include <type_traits>
#include <utility> // for move, swap
#include <variant> // for visit, variant
#include <vector> // for vector
#include "ftxui/component/animation.hpp" // for TimePoint, Clock, Duration, Params, RequestAnimationFrame
#include "ftxui/component/captured_mouse.hpp" // for CapturedMouse, CapturedMouseInterface
#include "ftxui/component/component_base.hpp" // for ComponentBase
#include "ftxui/component/event.hpp" // for Event
#include "ftxui/component/loop.hpp" // for Loop
#include "ftxui/component/multi_receiver_buffer.hpp"
#include "ftxui/component/task_runner.hpp"
#include "ftxui/component/terminal_input_parser.hpp" // for TerminalInputParser
#include "ftxui/dom/node.hpp" // for Node, Render
#include "ftxui/screen/cell.hpp" // for Cell
#include "ftxui/screen/terminal.hpp" // for Dimensions, Size
#include "ftxui/screen/util.hpp" // for util::clamp
#include "ftxui/util/autoreset.hpp" // for AutoReset
#if defined(_WIN32)
#define DEFINE_CONSOLEV2_PROPERTIES
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h>
#include <windows.h>
#else
#include <fcntl.h>
#include <poll.h>
#include <sys/poll.h>
#include <sys/types.h>
#include <termios.h> // for tcsetattr, termios, tcgetattr, TCSANOW, cc_t, ECHO, ICANON, VMIN, VTIME
#include <unistd.h> // for STDIN_FILENO, STDOUT_FILENO, read
#endif
#if defined(__EMSCRIPTEN__)
#include <emscripten.h>
#endif
namespace ftxui {
enum class AppDimension {
FitComponent,
Fixed,
Fullscreen,
TerminalOutput,
};
namespace animation {
void RequestAnimationFrame() {
auto* screen = App::Active();
if (screen) {
screen->RequestAnimationFrame();
}
}
} // namespace animation
#if defined(__EMSCRIPTEN__)
extern "C" {
EMSCRIPTEN_KEEPALIVE
void ftxui_on_resize(int columns, int rows) {
Terminal::SetFallbackSize({
columns,
rows,
});
std::raise(SIGWINCH);
}
}
#endif
struct App::Internal {
App* public_;
App* suspended_screen_ = nullptr;
const AppDimension dimension_;
const bool use_alternative_screen_;
bool track_mouse_ = true;
std::string set_cursor_position_;
std::string reset_cursor_position_;
std::atomic<bool> quit_{false};
bool installed_ = false;
bool animation_requested_ = false;
animation::TimePoint previous_animation_time_;
int cursor_x_ = 1;
int cursor_y_ = 1;
std::uint64_t frame_count_ = 0;
bool mouse_captured = false;
bool previous_frame_resized_ = false;
bool frame_valid_ = false;
bool force_handle_ctrl_c_ = true;
bool force_handle_ctrl_z_ = true;
int cursor_reset_shape_ = 1;
// Piped input handling state (POSIX only)
bool handle_piped_input_ = true;
bool is_stdin_a_tty_ = false;
bool is_stdout_a_tty_ = false;
// File descriptor for /dev/tty, used for piped input handling.
int tty_fd_ = -1;
std::string terminal_name_ = "unknown";
int terminal_version_ = 0;
std::string terminal_emulator_name_ = "unknown";
std::string terminal_emulator_version_ = "unknown";
std::vector<int> terminal_capabilities_;
// Selection API:
CapturedMouse selection_pending_;
struct SelectionData {
int start_x = -1;
int start_y = -1;
int end_x = -2;
int end_y = -2;
bool empty = true;
bool operator==(const SelectionData& other) const {
if (empty && other.empty) {
return true;
}
if (empty || other.empty) {
return false;
}
return start_x == other.start_x && start_y == other.start_y &&
end_x == other.end_x && end_y == other.end_y;
}
bool operator!=(const SelectionData& other) const {
return !(*this == other);
}
};
SelectionData selection_data_;
SelectionData selection_data_previous_;
std::unique_ptr<Selection> selection_;
std::function<void()> selection_on_change_;
Component component_;
// Pre-existing in Internal:
TerminalInputParser terminal_input_parser;
task::TaskRunner task_runner;
std::chrono::time_point<std::chrono::steady_clock> last_char_time =
std::chrono::steady_clock::now();
std::string output_buffer;
class ThrottledRequest {
public:
ThrottledRequest(App::Internal* internal, std::function<void()> send)
: internal_(internal), send_(std::move(send)) {}
void Request(bool force = false) {
if (!internal_->is_stdin_a_tty_) {
return;
}
if (force) {
Send();
return;
}
// Allow only one pending request at a time. This is to avoid flooding the
// terminal with requests.
if (HasPending()) {
return;
}
const auto now = std::chrono::steady_clock::now();
const auto delta = now - last_request_time_;
const auto delay = std::chrono::milliseconds(500) - delta;
if (delay <= std::chrono::milliseconds(0)) {
Send();
return;
}
request_queued_ = true;
internal_->task_runner.PostDelayedTask(
[this] {
request_queued_ = false;
Request();
},
delay);
}
void OnReply() { pending_request_ = false; }
bool HasPending() const {
if (pending_request_) {
const auto now = std::chrono::steady_clock::now();
if (now - last_sent_time_ < std::chrono::seconds(5)) {
return true;
}
}
return request_queued_;
}
private:
void Send() {
last_sent_time_ = std::chrono::steady_clock::now();
pending_request_ = true;
send_();
}
App::Internal* internal_;
std::function<void()> send_;
bool pending_request_ = false;
std::chrono::steady_clock::time_point last_request_time_ =
std::chrono::steady_clock::now() - std::chrono::hours(1);
std::chrono::steady_clock::time_point last_sent_time_ =
std::chrono::steady_clock::now() - std::chrono::hours(1);
bool request_queued_ = false;
};
ThrottledRequest cursor_position_request;
MultiReceiverBuffer<Event> event_buffer;
std::unique_ptr<MultiReceiverBuffer<Event>::Receiver> setup_receiver;
std::unique_ptr<MultiReceiverBuffer<Event>::Receiver> main_loop_receiver;
Internal(App* app, AppDimension dimension, bool use_alternative_screen);
void ExitNow();
void Install();
void Uninstall();
void PreMain();
void PostMain();
bool HasQuitted();
void RunOnce(const Component& component);
void RunOnceBlocking(Component component);
void HandleTask(Component component, Task& task);
bool HandleSelection(bool handled, Event event);
void Draw(Component component);
std::string ResetCursorPosition();
void RequestCursorPosition(bool force = false);
void TerminalSend(std::string_view);
void TerminalFlush();
void InstallPipedInputHandling();
void InstallTerminalInfo();
void Signal(int signal);
size_t FetchTerminalEvents();
void PostAnimationTask();
};
namespace {
App* g_active_screen = nullptr; // NOLINT
std::stack<Closure> on_exit_functions; // NOLINT
void OnExit() {
while (!on_exit_functions.empty()) {
on_exit_functions.top()();
on_exit_functions.pop();
}
}
// CSI: Control Sequence Introducer
const std::string CSI = "\x1b["; // NOLINT
//
// DCS: Device Control String
const std::string DCS = "\x1bP"; // NOLINT
// ST: String Terminator
const std::string ST = "\x1b\\"; // NOLINT
// DECRQSS: Request Status String
// DECSCUSR: Set Cursor Style
const std::string DECRQSS_DECSCUSR = DCS + "$q q" + ST; // NOLINT
// DEC: Digital Equipment Corporation
enum class DECMode : std::uint16_t {
kLineWrap = 7,
kCursor = 25,
kMouseX10 = 9,
kMouseVt200 = 1000,
kMouseVt200Highlight = 1001,
kMouseBtnEventMouse = 1002,
kMouseAnyEvent = 1003,
kMouseUtf8 = 1005,
kMouseSgrExtMode = 1006,
kMouseUrxvtMode = 1015,
kMouseSgrPixelsMode = 1016,
kAlternateScreen = 1049,
};
// Device Status Report (DSR) {
enum class DSRMode : std::uint8_t {
kCursor = 6,
};
std::string Serialize(const std::vector<DECMode>& parameters) {
bool first = true;
std::string out;
for (const DECMode parameter : parameters) {
if (!first) {
out += ";";
}
out += std::to_string(int(parameter));
first = false;
}
return out;
}
// DEC Private Mode Set (DECSET)
std::string Set(const std::vector<DECMode>& parameters) {
return CSI + "?" + Serialize(parameters) + "h";
}
// DEC Private Mode Reset (DECRST)
std::string Reset(const std::vector<DECMode>& parameters) {
return CSI + "?" + Serialize(parameters) + "l";
}
// Device Status Report (DSR)
std::string DeviceStatusReport(DSRMode ps) {
return CSI + std::to_string(int(ps)) + "n";
}
class CapturedMouseImpl : public CapturedMouseInterface {
public:
explicit CapturedMouseImpl(std::function<void(void)> callback)
: callback_(std::move(callback)) {}
~CapturedMouseImpl() override { callback_(); }
CapturedMouseImpl(const CapturedMouseImpl&) = delete;
CapturedMouseImpl(CapturedMouseImpl&&) = delete;
CapturedMouseImpl& operator=(const CapturedMouseImpl&) = delete;
CapturedMouseImpl& operator=(CapturedMouseImpl&&) = delete;
private:
std::function<void(void)> callback_;
};
#if !defined(_WIN32)
std::atomic<int> g_signal_exit_count = 0; // NOLINT
std::atomic<int> g_signal_stop_count = 0; // NOLINT
std::atomic<int> g_signal_resize_count = 0; // NOLINT
#else
std::atomic<int> g_signal_exit_count = 0; // NOLINT
#endif
// Tracks whether the terminal is currently configured in raw mode.
// Used to prevent double-restoration in emergency and normal exits.
std::atomic<bool> g_terminal_is_raw{false};
// Stores the last received deferred signal (e.g. SIGINT, SIGTERM) to be
// re-raised during uninstallation/exit.
std::atomic<int> g_last_signal{0}; // NOLINT
#if defined(_WIN32)
using SignalHandler = void (*)(int);
// Stores the original signal handlers before FTXUI installed its own.
std::map<int, SignalHandler> g_old_signal_handlers;
// Stores the original console modes to restore them during exit.
DWORD g_original_stdout_mode = 0;
DWORD g_original_stdin_mode = 0;
bool g_has_original_console_mode = false;
#else
// Stores the original sigaction structures before FTXUI installed its own.
std::map<int, struct sigaction> g_old_sigactions;
// Stores the original termios terminal settings to restore them during exit.
struct termios g_original_termios;
bool g_has_original_termios = false;
int g_tty_fd = -1;
#endif
// Restores the original signal handler for the given signal and re-raises it.
// Async-signal-safe function.
void RestoreSignalHandlerAndRaise(int signal) {
#if defined(_WIN32)
auto it = g_old_signal_handlers.find(signal);
auto old_handler = (it != g_old_signal_handlers.end()) ? it->second : SIG_DFL;
std::signal(signal, old_handler);
#else
auto it = g_old_sigactions.find(signal);
if (it != g_old_sigactions.end()) {
sigaction(signal, &it->second, nullptr);
} else {
struct sigaction sa;
sa.sa_handler = SIG_DFL;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(signal, &sa, nullptr);
}
#endif
std::raise(signal);
}
// Emergency terminal state restoration.
// Async-signal-safe function.
void RestoreTerminalEmergency() {
if (!g_terminal_is_raw.exchange(false)) {
return;
}
#if defined(_WIN32)
if (g_has_original_console_mode) {
auto stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
auto stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleMode(stdout_handle, g_original_stdout_mode);
SetConsoleMode(stdin_handle, g_original_stdin_mode);
}
#else
if (g_has_original_termios && g_tty_fd >= 0) {
const char restore_seq[] =
"\x1b[?25h" // Show cursor.
"\x1b[?1049l" // Switch to normal screen buffer.
"\x1b[?1000l" // Disable normal mouse tracking.
"\x1b[?1002l" // Disable button event mouse tracking.
"\x1b[?1003l" // Disable all motion mouse tracking.
"\x1b[?1006l" // Disable SGR mouse tracking.
"\x1b[?1015l" // Disable Urxvt mouse tracking.
"\x1b[?7h"; // Enable line wrapping.
std::ignore = write(STDOUT_FILENO, restore_seq, sizeof(restore_seq) - 1);
tcsetattr(g_tty_fd, TCSANOW, &g_original_termios);
}
#endif
}
// Async signal safe function
void RecordSignal(int signal) {
switch (signal) {
// Abnormal termination (e.g. abort() or assertion failure).
case SIGABRT:
// Erroneous arithmetic operation (e.g. division by zero).
case SIGFPE:
// Illegal instruction.
case SIGILL:
// Invalid memory reference (segmentation fault).
case SIGSEGV:
#if !defined(_WIN32)
// Bus error (e.g. bad memory access alignment).
case SIGBUS:
// Bad system call.
case SIGSYS:
#endif
{
RestoreTerminalEmergency();
RestoreSignalHandlerAndRaise(signal);
break;
}
// Terminal interrupt (e.g. Ctrl-C).
case SIGINT:
// Termination request.
case SIGTERM:
#if !defined(_WIN32)
// Terminal quit (e.g. Ctrl-\, produces core dump).
case SIGQUIT:
// Hangup detected on controlling terminal or death of controlling process.
case SIGHUP:
#endif
g_last_signal.store(signal);
g_signal_exit_count++;
break;
#if !defined(_WIN32)
// Terminal stop signal (e.g. Ctrl-Z).
case SIGTSTP: // NOLINT
g_signal_stop_count++;
break;
// Terminal window size change.
case SIGWINCH: // NOLINT
g_signal_resize_count++;
break;
#endif
default:
break;
}
}
void ExecuteSignalHandlers() {
if (g_last_signal.load() != 0) {
App::Private::Signal(*g_active_screen, SIGABRT);
}
int signal_exit_count = g_signal_exit_count.exchange(0);
while (signal_exit_count--) {
App::Private::Signal(*g_active_screen, SIGABRT);
}
#if !defined(_WIN32)
int signal_stop_count = g_signal_stop_count.exchange(0);
while (signal_stop_count--) {
App::Private::Signal(*g_active_screen, SIGTSTP);
}
int signal_resize_count = g_signal_resize_count.exchange(0);
while (signal_resize_count--) {
App::Private::Signal(*g_active_screen, SIGWINCH);
}
#endif
}
void InstallSignalHandler(int sig) {
#if defined(_WIN32)
auto old_signal_handler = std::signal(sig, RecordSignal);
g_old_signal_handlers[sig] = old_signal_handler;
on_exit_functions.emplace(
[=] { std::ignore = std::signal(sig, old_signal_handler); });
#else
struct sigaction sa;
sa.sa_handler = RecordSignal;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
struct sigaction old_sa;
sigaction(sig, &sa, &old_sa);
g_old_sigactions[sig] = old_sa;
on_exit_functions.emplace([=] { sigaction(sig, &old_sa, nullptr); });
#endif
}
} // namespace
App::Internal::Internal(App* app,
AppDimension dimension,
bool use_alternative_screen)
: public_(app),
dimension_(dimension),
use_alternative_screen_(use_alternative_screen),
terminal_input_parser([&](Event event) {
event_buffer.Push(std::move(event));
public_->RequestAnimationFrame();
}),
cursor_position_request(this, [this] {
TerminalSend(DeviceStatusReport(DSRMode::kCursor));
}) {
setup_receiver = event_buffer.CreateReceiver();
main_loop_receiver = event_buffer.CreateReceiver();
}
void App::Internal::ExitNow() {
quit_ = true;
}
void App::Internal::Install() {
frame_valid_ = false;
// Flush the buffer for stdout to ensure whatever the user has printed before
// is fully applied before we start modifying the terminal configuration. This
// is important, because we are using two different channels (stdout vs
// termios/WinAPI) to communicate with the terminal emulator below. See
// https://github.com/ArthurSonzogni/FTXUI/issues/846
TerminalFlush();
InstallPipedInputHandling();
// After uninstalling the new configuration, flush it to the terminal to
// ensure it is fully applied:
on_exit_functions.emplace([this] { TerminalFlush(); });
// Install signal handlers to restore the terminal state on exit. The default
// signal handlers are restored on exit.
for (const int signal : {SIGTERM, SIGSEGV, SIGINT, SIGILL, SIGABRT, SIGFPE}) {
InstallSignalHandler(signal);
}
// Save the old terminal configuration and restore it on exit.
#if defined(_WIN32)
// Enable VT processing on stdout and stdin
auto stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
auto stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD out_mode = 0;
DWORD in_mode = 0;
GetConsoleMode(stdout_handle, &out_mode);
GetConsoleMode(stdin_handle, &in_mode);
g_original_stdout_mode = out_mode;
g_original_stdin_mode = in_mode;
g_has_original_console_mode = true;
on_exit_functions.push([=] { SetConsoleMode(stdout_handle, out_mode); });
on_exit_functions.push([=] { SetConsoleMode(stdin_handle, in_mode); });
// https://docs.microsoft.com/en-us/windows/console/setconsolemode
const int enable_virtual_terminal_processing = 0x0004;
const int disable_newline_auto_return = 0x0008;
out_mode |= enable_virtual_terminal_processing;
out_mode |= disable_newline_auto_return;
// https://docs.microsoft.com/en-us/windows/console/setconsolemode
const int enable_line_input = 0x0002;
const int enable_echo_input = 0x0004;
const int enable_virtual_terminal_input = 0x0200;
const int enable_window_input = 0x0008;
in_mode &= ~enable_echo_input;
in_mode &= ~enable_line_input;
in_mode |= enable_virtual_terminal_input;
in_mode |= enable_window_input;
SetConsoleMode(stdin_handle, in_mode);
SetConsoleMode(stdout_handle, out_mode);
#else // POSIX (Linux & Mac)
for (const int signal :
{SIGWINCH, SIGTSTP, SIGBUS, SIGSYS, SIGQUIT, SIGHUP}) {
InstallSignalHandler(signal);
}
struct termios terminal; // NOLINT
tcgetattr(tty_fd_, &terminal);
g_original_termios = terminal;
g_tty_fd = tty_fd_;
g_has_original_termios = true;
on_exit_functions.emplace([terminal = terminal, tty_fd_ = tty_fd_] {
tcsetattr(tty_fd_, TCSANOW, &terminal);
});
// Enabling raw terminal input mode
terminal.c_iflag &= ~IGNBRK; // Disable ignoring break condition
terminal.c_iflag &= ~BRKINT; // Disable break causing input and output to be
// flushed
terminal.c_iflag &= ~PARMRK; // Disable marking parity errors.
terminal.c_iflag &= ~ISTRIP; // Disable stripping 8th bit off characters.
terminal.c_iflag &= ~INLCR; // Disable mapping NL to CR.
terminal.c_iflag &= ~IGNCR; // Disable ignoring CR.
terminal.c_iflag &= ~ICRNL; // Disable mapping CR to NL.
terminal.c_iflag &= ~IXON; // Disable XON/XOFF flow control on output
terminal.c_lflag &= ~ECHO; // Disable echoing input characters.
terminal.c_lflag &= ~ECHONL; // Disable echoing new line characters.
terminal.c_lflag &= ~ICANON; // Disable Canonical mode.
terminal.c_lflag &= ~ISIG; // Disable sending signal when hitting:
// - => DSUSP
// - C-Z => SUSP
// - C-C => INTR
// - C-d => QUIT
terminal.c_lflag &= ~IEXTEN; // Disable extended input processing
terminal.c_cflag |= CS8; // 8 bits per byte
terminal.c_cc[VMIN] = 0; // Minimum number of characters for non-canonical
// read.
terminal.c_cc[VTIME] = 0; // Timeout in deciseconds for non-canonical read.
tcsetattr(tty_fd_, TCSANOW, &terminal);
#endif
auto enable = [&](const std::vector<DECMode>& parameters) {
TerminalSend(Set(parameters));
on_exit_functions.emplace(
[this, parameters] { TerminalSend(Reset(parameters)); });
};
auto disable = [&](const std::vector<DECMode>& parameters) {
TerminalSend(Reset(parameters));
on_exit_functions.emplace(
[this, parameters] { TerminalSend(Set(parameters)); });
};
if (use_alternative_screen_) {
enable({
DECMode::kAlternateScreen,
});
}
disable({
DECMode::kLineWrap,
});
if (track_mouse_) {
enable({DECMode::kMouseVt200});
enable({DECMode::kMouseAnyEvent});
enable({DECMode::kMouseUrxvtMode});
enable({DECMode::kMouseSgrExtMode});
}
// After installing the new configuration, flush it to the terminal to
// ensure it is fully applied:
TerminalFlush();
InstallTerminalInfo();
quit_ = false;
PostAnimationTask();
installed_ = true;
g_terminal_is_raw = true;
}
void App::Internal::Uninstall() {
g_terminal_is_raw = false;
installed_ = false;
// During shutdown, wait for all of the replies.
if (is_stdin_a_tty_ && is_stdout_a_tty_) {
auto closing_receiver =
event_buffer.CreateReceiverAt(main_loop_receiver->index());
auto start = std::chrono::steady_clock::now();
while (cursor_position_request.HasPending()) {
FetchTerminalEvents();
while (closing_receiver->Has()) {
const auto event = closing_receiver->Pop();
if (event.is_cursor_position()) {
cursor_x_ = event.cursor_x();
cursor_y_ = event.cursor_y();
cursor_position_request.OnReply();
}
}
task_runner.RunUntilIdle();
if (std::chrono::steady_clock::now() - start >
std::chrono::milliseconds(400)) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
OnExit();
}
void App::Internal::PreMain() {
// Suspend previously active screen:
if (g_active_screen) {
std::swap(suspended_screen_, g_active_screen);
// Reset cursor position to the top of the screen and clear the screen.
suspended_screen_->internal_->TerminalSend(
suspended_screen_->internal_->ResetCursorPosition());
suspended_screen_->ResetPosition(
suspended_screen_->internal_->output_buffer,
/*clear=*/true);
suspended_screen_->dimx_ = 0;
suspended_screen_->dimy_ = 0;
// Reset dimensions to force drawing the screen again next time:
suspended_screen_->internal_->Uninstall();
}
// This screen is now active:
g_active_screen = public_;
g_active_screen->internal_->Install();
previous_animation_time_ = animation::Clock::now();
}
void App::Internal::PostMain() {
// Put cursor position at the end of the drawing.
TerminalSend(ResetCursorPosition());
g_active_screen = nullptr;
// Restore suspended screen.
if (suspended_screen_) {
// Clear screen, and put the cursor at the beginning of the drawing.
public_->ResetPosition(output_buffer, /*clear=*/true);
public_->dimx_ = 0;
public_->dimy_ = 0;
Uninstall();
std::swap(g_active_screen, suspended_screen_);
g_active_screen->internal_->Install();
} else {
Uninstall();
std::cout << "\r";
// On final exit, keep the current drawing and reset cursor position one
// line after it.
if (!use_alternative_screen_) {
std::cout << "\n";
}
std::cout << std::flush;
}
int sig = g_last_signal.exchange(0);
if (sig != 0) {
RestoreSignalHandlerAndRaise(sig);
}
}
bool App::Internal::HasQuitted() {
return quit_;
}
void App::Internal::RunOnce(const Component& component) {
const AutoReset set_component(&component_, component);
ExecuteSignalHandlers();
FetchTerminalEvents();
while (!quit_ && main_loop_receiver->Has()) {
public_->Post(main_loop_receiver->Pop());
}
// Execute the pending tasks from the queue.
const size_t executed_task = task_runner.ExecutedTasks();
task_runner.RunUntilIdle();
// If no executed task, we can return early without redrawing the screen.
if (executed_task == task_runner.ExecutedTasks()) {
return;
}
ExecuteSignalHandlers();
Draw(component);
if (selection_data_previous_ != selection_data_) {
selection_data_previous_ = selection_data_;
if (selection_on_change_) {
selection_on_change_();
public_->Post(Event::Custom);
}
}
}
void App::Internal::RunOnceBlocking(Component component) {
// Set FPS to 60 at most.
const auto time_per_frame = std::chrono::microseconds(16666); // 1s / 60fps
auto time = std::chrono::steady_clock::now();
const size_t executed_task = task_runner.ExecutedTasks();
// Wait for at least one task to execute.
while (executed_task == task_runner.ExecutedTasks() && !HasQuitted()) {
RunOnce(component);
const auto now = std::chrono::steady_clock::now();
const auto delta = now - time;
time = now;
if (delta < time_per_frame) {
const auto sleep_duration = time_per_frame - delta;
std::this_thread::sleep_for(sleep_duration);
}
}
}
void App::Internal::HandleTask(Component component, Task& task) {
std::visit(
[&](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
// clang-format off
// Handle Event.
if constexpr (std::is_same_v<T, Event>) {
if (arg.is_cursor_position()) {
cursor_x_ = arg.cursor_x();
cursor_y_ = arg.cursor_y();
cursor_position_request.OnReply();
return;
}
if (arg.is_cursor_shape()) {
cursor_reset_shape_ = arg.cursor_shape();
return;
}
if (arg.IsTerminalCapabilities()) {
terminal_capabilities_ = arg.TerminalCapabilities();
return;
}
if (arg.IsTerminalNameVersion()) {
terminal_name_ = arg.TerminalName();
terminal_version_ = arg.TerminalVersion();
return;
}
if (arg.IsTerminalEmulator()) {
terminal_emulator_name_ = arg.TerminalEmulatorName();
terminal_emulator_version_ = arg.TerminalEmulatorVersion();
return;
}
if (arg.is_mouse()) {
arg.mouse().x -= cursor_x_;
arg.mouse().y -= cursor_y_;
}
arg.screen_ = public_;
bool handled = component->OnEvent(arg);
handled = HandleSelection(handled, arg);
if (arg == Event::CtrlC && (!handled || force_handle_ctrl_c_)) {
RecordSignal(SIGINT);
}
#if !defined(_WIN32)
if (arg == Event::CtrlZ && (!handled || force_handle_ctrl_z_)) {
RecordSignal(SIGTSTP);
}
#endif
frame_valid_ = false;
return;
}
// Handle callback
if constexpr (std::is_same_v<T, Closure>) {
arg();
return;
}
// Handle Animation
if constexpr (std::is_same_v<T, AnimationTask>) {
if (!animation_requested_) {
return;
}
animation_requested_ = false;
const animation::TimePoint now = animation::Clock::now();
const animation::Duration delta = now - previous_animation_time_;
previous_animation_time_ = now;
animation::Params params(delta);
component->OnAnimation(params);
frame_valid_ = false;
return;
}
},
task);
// clang-format on
}
bool App::Internal::HandleSelection(bool handled, Event event) {
if (handled) {
selection_pending_ = nullptr;
selection_data_.empty = true;
selection_ = nullptr;
return true;
}
if (!event.is_mouse()) {
return false;
}
auto& mouse = event.mouse();
if (mouse.button != Mouse::Left) {
return false;
}
if (mouse.motion == Mouse::Pressed) {
selection_pending_ = public_->CaptureMouse();
selection_data_.start_x = mouse.x;
selection_data_.start_y = mouse.y;
selection_data_.end_x = mouse.x;
selection_data_.end_y = mouse.y;
return false;
}
if (!selection_pending_) {
return false;
}
if (mouse.motion == Mouse::Moved) {
if ((mouse.x != selection_data_.end_x) ||
(mouse.y != selection_data_.end_y)) {
selection_data_.end_x = mouse.x;
selection_data_.end_y = mouse.y;
selection_data_.empty = false;
}
return true;
}
if (mouse.motion == Mouse::Released) {
selection_pending_ = nullptr;
selection_data_.end_x = mouse.x;
selection_data_.end_y = mouse.y;
selection_data_.empty = false;
return true;
}
return false;