FTXUI 7.1.0
C++ functional terminal UI.
Loading...
Searching...
No Matches
app.cpp
Go to the documentation of this file.
1// Copyright 2020 Arthur Sonzogni. All rights reserved.
2// Use of this source code is governed by the MIT license that can be found in
3// the LICENSE file.
4#include <algorithm> // for any_of, copy, max, min
5#include <array> // for array
6#include <atomic>
7#include <chrono> // for operator-, milliseconds, operator>=, duration, common_type<>::type, time_point
8#include <csignal> // for signal, SIGTSTP, SIGABRT, SIGWINCH, raise, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM, __sighandler_t, size_t
9#include <cstdint>
10#include <cstdio> // for fileno, stdin
12#include <ftxui/component/task.hpp> // for Task, Closure, AnimationTask
13#include <ftxui/screen/screen.hpp> // for Cell, Screen::Cursor, Screen, Screen::Cursor::Hidden
14#include <functional> // for function
15#include <initializer_list> // for initializer_list
16#include <iostream> // for cout, ostream, operator<<, basic_ostream, endl, flush
17#include <map>
18#include <memory>
19#include <stack> // for stack
20#include <string>
21#include <string_view>
22#include <thread> // for thread, sleep_for
23#include <tuple> // for _Swallow_assign, ignore
24#include <type_traits>
25#include <utility> // for move, swap
26#include <variant> // for visit, variant
27#include <vector> // for vector
28
29#include "ftxui/component/animation.hpp" // for TimePoint, Clock, Duration, Params, RequestAnimationFrame
30#include "ftxui/component/captured_mouse.hpp" // for CapturedMouse, CapturedMouseInterface
31#include "ftxui/component/component_base.hpp" // for ComponentBase
32#include "ftxui/component/event.hpp" // for Event
33#include "ftxui/component/loop.hpp" // for Loop
36#include "ftxui/component/terminal_input_parser.hpp" // for TerminalInputParser
37#include "ftxui/dom/elements.hpp" // for Dimension::Fit
38#include "ftxui/dom/node.hpp" // for Node, Render
39#include "ftxui/screen/cell.hpp" // for Cell
40#include "ftxui/screen/terminal.hpp" // for Dimensions, Size
41#include "ftxui/screen/util.hpp" // for util::clamp
42#include "ftxui/util/autoreset.hpp" // for AutoReset
43
44#if defined(_WIN32)
45#define DEFINE_CONSOLEV2_PROPERTIES
46#define WIN32_LEAN_AND_MEAN
47#ifndef NOMINMAX
48#define NOMINMAX
49#endif
50#include <io.h>
51#include <windows.h>
52#else
53#include <fcntl.h>
54#include <poll.h>
55#include <sys/poll.h>
56#include <sys/types.h>
57#include <termios.h> // for tcsetattr, termios, tcgetattr, TCSANOW, cc_t, ECHO, ICANON, VMIN, VTIME
58#include <unistd.h> // for STDIN_FILENO, STDOUT_FILENO, read
59#endif
60
61#if defined(__EMSCRIPTEN__)
62#include <emscripten.h>
63#endif
64
65namespace ftxui {
66
67enum class AppDimension {
69 Fixed,
72};
73
74namespace animation {
76 auto* screen = App::Active();
77 if (screen) {
78 screen->RequestAnimationFrame();
79 }
80}
81} // namespace animation
82
83#if defined(__EMSCRIPTEN__)
84extern "C" {
85EMSCRIPTEN_KEEPALIVE
86void ftxui_on_resize(int columns, int rows) {
88 columns,
89 rows,
90 });
91 std::raise(SIGWINCH);
92}
93}
94#endif
95
96struct App::Internal {
97 // The frame currently displayed by the terminal. Its cells are swapped with
98 // the App's ones, instead of being copied.
99 class PreviousFrame : public Screen {
100 public:
101 PreviousFrame() : Screen(0, 0) {}
102
103 void Swap(std::vector<Cell>& cells,
104 std::vector<std::string>& hyperlinks,
105 int dimx,
106 int dimy) {
107 std::swap(cells_, cells);
108 std::swap(hyperlinks_, hyperlinks);
109 dimx_ = dimx;
110 dimy_ = dimy;
111 }
112 };
113
114 App* public_;
115
116 App* suspended_screen_ = nullptr;
117 const AppDimension dimension_;
118 const bool use_alternative_screen_;
119
120 bool track_mouse_ = true;
121
122 std::string set_cursor_position_;
123 std::string reset_cursor_position_;
124
125 std::atomic<bool> quit_{false};
126 bool installed_ = false;
127 bool animation_requested_ = false;
128 animation::TimePoint previous_animation_time_;
129
130 int cursor_x_ = 1;
131 int cursor_y_ = 1;
132
133 std::uint64_t frame_count_ = 0;
134 bool mouse_captured = false;
135 bool previous_frame_resized_ = false;
136
137 bool frame_valid_ = false;
138
139 // The frame currently displayed by the terminal. Only the cells that changed
140 // since are printed. Empty when the terminal must be fully redrawn.
141 PreviousFrame previous_frame_;
142
143 // Elements to print above the app on the next frame.
144 std::vector<Element> print_above_;
145
146 bool force_handle_ctrl_c_ = true;
147 bool force_handle_ctrl_z_ = true;
148
149 // 0: the terminal's default shape, used when it doesn't report its own.
150 int cursor_reset_shape_ = 0;
151
152 // Piped input handling state (POSIX only)
153 bool handle_piped_input_ = true;
154 bool is_stdin_a_tty_ = false;
155 bool is_stdout_a_tty_ = false;
156 // File descriptor for /dev/tty, used for piped input handling.
157 int tty_fd_ = -1;
158
159 std::string terminal_name_ = "unknown";
160 int terminal_version_ = 0;
161
162 std::string terminal_emulator_name_ = "unknown";
163 std::string terminal_emulator_version_ = "unknown";
164
165 std::vector<int> terminal_capabilities_;
166
167 // Selection API:
168 CapturedMouse selection_pending_;
169 struct SelectionData {
170 int start_x = -1;
171 int start_y = -1;
172 int end_x = -2;
173 int end_y = -2;
174 bool empty = true;
175 bool operator==(const SelectionData& other) const {
176 if (empty && other.empty) {
177 return true;
178 }
179 if (empty || other.empty) {
180 return false;
181 }
182 return start_x == other.start_x && start_y == other.start_y &&
183 end_x == other.end_x && end_y == other.end_y;
184 }
185 bool operator!=(const SelectionData& other) const {
186 return !(*this == other);
187 }
188 };
189 SelectionData selection_data_;
190 SelectionData selection_data_previous_;
191 std::unique_ptr<Selection> selection_;
192 std::function<void()> selection_on_change_;
193
194 Component component_;
195
196 // Pre-existing in Internal:
197 TerminalInputParser terminal_input_parser;
198 task::TaskRunner task_runner;
199 std::chrono::time_point<std::chrono::steady_clock> last_char_time =
200 std::chrono::steady_clock::now();
201 std::string output_buffer;
202
203 class ThrottledRequest {
204 public:
205 ThrottledRequest(App::Internal* internal, std::function<void()> send)
206 : internal_(internal), send_(std::move(send)) {}
207
208 void Request(bool force = false) {
209 if (!internal_->is_stdin_a_tty_) {
210 return;
211 }
212
213 if (force) {
214 Send();
215 return;
216 }
217
218 // Allow only one pending request at a time. This is to avoid flooding the
219 // terminal with requests.
220 if (HasPending()) {
221 return;
222 }
223
224 const auto now = std::chrono::steady_clock::now();
225 if (now - last_request_time_ < std::chrono::milliseconds(500)) {
226 // Too soon since the last request. Skip it: the request must be sent
227 // synchronously from Draw(), right after the cursor is moved to the
228 // frame's origin, so that the terminal's reply reflects that
229 // position. Draw() calls Request() again on the next frame, so the
230 // request isn't lost, only delayed.
231 return;
232 }
233
234 Send();
235 }
236
237 void OnReply() { pending_request_ = false; }
238
239 bool HasPending() const {
240 if (!pending_request_) {
241 return false;
242 }
243 const auto now = std::chrono::steady_clock::now();
244 return now - last_sent_time_ < std::chrono::seconds(5);
245 }
246
247 private:
248 void Send() {
249 last_sent_time_ = std::chrono::steady_clock::now();
250 last_request_time_ = last_sent_time_;
251 pending_request_ = true;
252 send_();
253 }
254
255 App::Internal* internal_;
256 std::function<void()> send_;
257 bool pending_request_ = false;
258 std::chrono::steady_clock::time_point last_request_time_ =
259 std::chrono::steady_clock::now() - std::chrono::hours(1);
260 std::chrono::steady_clock::time_point last_sent_time_ =
261 std::chrono::steady_clock::now() - std::chrono::hours(1);
262 };
263
264 ThrottledRequest cursor_position_request;
265
266 MultiReceiverBuffer<Event> event_buffer;
267 std::unique_ptr<MultiReceiverBuffer<Event>::Receiver> main_loop_receiver;
268
269 Internal(App* app, AppDimension dimension, bool use_alternative_screen);
270
271 void ExitNow();
272 void Install();
273 void Uninstall();
274 void PreMain();
275 void PostMain();
276 bool HasQuitted();
277 void RunOnce(const Component& component);
278 void RunOnceBlocking(Component component);
279 void HandleTask(Component component, Task& task);
280 bool HandleSelection(bool handled, Event event);
281 void Draw(Component component);
282 std::string ResetCursorPosition();
283 void RequestCursorPosition(bool force = false);
284 void TerminalSend(std::string_view);
285 void TerminalFlush();
286 void InstallPipedInputHandling();
287 void InstallTerminalInfo();
288 void Signal(int signal);
289 size_t FetchTerminalEvents();
290 void PostAnimationTask();
291};
292
293namespace {
294
295App* g_active_screen = nullptr; // NOLINT
296
297std::stack<Closure> on_exit_functions; // NOLINT
298
299void OnExit() {
300 while (!on_exit_functions.empty()) {
301 on_exit_functions.top()();
302 on_exit_functions.pop();
303 }
304}
305
306// CSI: Control Sequence Introducer
307const std::string CSI = "\x1b["; // NOLINT
308 //
309// DCS: Device Control String
310const std::string DCS = "\x1bP"; // NOLINT
311
312// ST: String Terminator
313const std::string ST = "\x1b\\"; // NOLINT
314
315// DECRQSS: Request Status String
316// DECSCUSR: Set Cursor Style
317const std::string DECRQSS_DECSCUSR = DCS + "$q q" + ST; // NOLINT
318
319// Some terminals don't parse DCS sequences, and print their payload ("$q q")
320// instead. See https://github.com/ArthurSonzogni/FTXUI/issues/1217
321bool SupportsDECRQSS() {
322 // Apple's Terminal.app.
323 if (std::string_view(util::GetEnv("TERM_PROGRAM")) == "Apple_Terminal") {
324 return false;
325 }
326 // GNU Screen.
327 if (util::GetEnv("STY")[0] != '\0') {
328 return false;
329 }
330 return true;
331}
332
333// DEC: Digital Equipment Corporation
334enum class DECMode : std::uint16_t {
335 kLineWrap = 7,
336 kCursor = 25,
337
338 kMouseX10 = 9,
339 kMouseVt200 = 1000,
340 kMouseVt200Highlight = 1001,
341
342 kMouseBtnEventMouse = 1002,
343 kMouseAnyEvent = 1003,
344
345 kMouseUtf8 = 1005,
346 kMouseSgrExtMode = 1006,
347 kMouseUrxvtMode = 1015,
348 kMouseSgrPixelsMode = 1016,
349 kAlternateScreen = 1049,
350};
351
352// Device Status Report (DSR) {
353enum class DSRMode : std::uint8_t {
354 kCursor = 6,
355};
356
357std::string Serialize(const std::vector<DECMode>& parameters) {
358 bool first = true;
359 std::string out;
360 for (const DECMode parameter : parameters) {
361 if (!first) {
362 out += ";";
363 }
364 out += std::to_string(int(parameter));
365 first = false;
366 }
367 return out;
368}
369
370// DEC Private Mode Set (DECSET)
371std::string Set(const std::vector<DECMode>& parameters) {
372 return CSI + "?" + Serialize(parameters) + "h";
373}
374
375// DEC Private Mode Reset (DECRST)
376std::string Reset(const std::vector<DECMode>& parameters) {
377 return CSI + "?" + Serialize(parameters) + "l";
378}
379
380// Device Status Report (DSR)
381std::string DeviceStatusReport(DSRMode ps) {
382 return CSI + std::to_string(int(ps)) + "n";
383}
384
385class CapturedMouseImpl : public CapturedMouseInterface {
386 public:
387 explicit CapturedMouseImpl(std::function<void(void)> callback)
388 : callback_(std::move(callback)) {}
389 ~CapturedMouseImpl() override { callback_(); }
390 CapturedMouseImpl(const CapturedMouseImpl&) = delete;
391 CapturedMouseImpl(CapturedMouseImpl&&) = delete;
392 CapturedMouseImpl& operator=(const CapturedMouseImpl&) = delete;
393 CapturedMouseImpl& operator=(CapturedMouseImpl&&) = delete;
394
395 private:
396 std::function<void(void)> callback_;
397};
398
399#if !defined(_WIN32)
400std::atomic<int> g_signal_exit_count = 0; // NOLINT
401std::atomic<int> g_signal_stop_count = 0; // NOLINT
402std::atomic<int> g_signal_resize_count = 0; // NOLINT
403#else
404std::atomic<int> g_signal_exit_count = 0; // NOLINT
405#endif
406
407// Tracks whether the terminal is currently configured in raw mode.
408// Used to prevent double-restoration in emergency and normal exits.
409std::atomic<bool> g_terminal_is_raw{false};
410
411// Stores the last received deferred signal (e.g. SIGINT, SIGTERM) to be
412// re-raised during uninstallation/exit.
413std::atomic<int> g_last_signal{0}; // NOLINT
414
415#if defined(_WIN32)
416using SignalHandler = void (*)(int);
417// Stores the original signal handlers before FTXUI installed its own.
418std::map<int, SignalHandler> g_old_signal_handlers;
419
420// Stores the original console modes to restore them during exit.
421DWORD g_original_stdout_mode = 0;
422DWORD g_original_stdin_mode = 0;
423bool g_has_original_console_mode = false;
424#else
425// Stores the original sigaction structures before FTXUI installed its own.
426std::map<int, struct sigaction> g_old_sigactions;
427
428// Stores the original termios terminal settings to restore them during exit.
429struct termios g_original_termios;
430bool g_has_original_termios = false;
431int g_tty_fd = -1;
432#endif
433
434// Restores the original signal handler for the given signal and re-raises it.
435// Async-signal-safe function.
436void RestoreSignalHandlerAndRaise(int signal) {
437#if defined(_WIN32)
438 auto it = g_old_signal_handlers.find(signal);
439 auto old_handler = (it != g_old_signal_handlers.end()) ? it->second : SIG_DFL;
440 std::signal(signal, old_handler);
441#else
442 auto it = g_old_sigactions.find(signal);
443 if (it != g_old_sigactions.end()) {
444 sigaction(signal, &it->second, nullptr);
445 } else {
446 struct sigaction sa;
447 sa.sa_handler = SIG_DFL;
448 sigemptyset(&sa.sa_mask);
449 sa.sa_flags = 0;
450 sigaction(signal, &sa, nullptr);
451 }
452#endif
453 std::raise(signal);
454}
455
456// Emergency terminal state restoration.
457// Async-signal-safe function.
458void RestoreTerminalEmergency() {
459 if (!g_terminal_is_raw.exchange(false)) {
460 return;
461 }
462#if defined(_WIN32)
463 if (g_has_original_console_mode) {
464 auto stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
465 auto stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
466 SetConsoleMode(stdout_handle, g_original_stdout_mode);
467 SetConsoleMode(stdin_handle, g_original_stdin_mode);
468 }
469#else
470 if (g_has_original_termios && g_tty_fd >= 0) {
471 const char restore_seq[] =
472 "\x1b[?25h" // Show cursor.
473 "\x1b[?1049l" // Switch to normal screen buffer.
474 "\x1b[?1000l" // Disable normal mouse tracking.
475 "\x1b[?1002l" // Disable button event mouse tracking.
476 "\x1b[?1003l" // Disable all motion mouse tracking.
477 "\x1b[?1006l" // Disable SGR mouse tracking.
478 "\x1b[?1015l" // Disable Urxvt mouse tracking.
479 "\x1b[?7h"; // Enable line wrapping.
480 std::ignore = write(STDOUT_FILENO, restore_seq, sizeof(restore_seq) - 1);
481 tcsetattr(g_tty_fd, TCSANOW, &g_original_termios);
482 }
483#endif
484}
485
486// Async signal safe function
487void RecordSignal(int signal) {
488 switch (signal) {
489 // Abnormal termination (e.g. abort() or assertion failure).
490 case SIGABRT:
491 // Erroneous arithmetic operation (e.g. division by zero).
492 case SIGFPE:
493 // Illegal instruction.
494 case SIGILL:
495 // Invalid memory reference (segmentation fault).
496 case SIGSEGV:
497#if !defined(_WIN32)
498 // Bus error (e.g. bad memory access alignment).
499 case SIGBUS:
500 // Bad system call.
501 case SIGSYS:
502#endif
503 {
504 RestoreTerminalEmergency();
505 RestoreSignalHandlerAndRaise(signal);
506 break;
507 }
508
509 // Terminal interrupt (e.g. Ctrl-C).
510 case SIGINT:
511 // Termination request.
512 case SIGTERM:
513#if !defined(_WIN32)
514 // Terminal quit (e.g. Ctrl-\, produces core dump).
515 case SIGQUIT:
516 // Hangup detected on controlling terminal or death of controlling process.
517 case SIGHUP:
518#endif
519 g_last_signal.store(signal);
520 g_signal_exit_count++;
521 break;
522
523#if !defined(_WIN32)
524 // Terminal stop signal (e.g. Ctrl-Z).
525 case SIGTSTP: // NOLINT
526 g_signal_stop_count++;
527 break;
528
529 // Terminal window size change.
530 case SIGWINCH: // NOLINT
531 g_signal_resize_count++;
532 break;
533#endif
534
535 default:
536 break;
537 }
538}
539
540void ExecuteSignalHandlers() {
541 if (g_last_signal.load() != 0) {
542 App::Private::Signal(*g_active_screen, SIGABRT);
543 }
544
545 int signal_exit_count = g_signal_exit_count.exchange(0);
546 while (signal_exit_count--) {
547 App::Private::Signal(*g_active_screen, SIGABRT);
548 }
549
550#if !defined(_WIN32)
551 int signal_stop_count = g_signal_stop_count.exchange(0);
552 while (signal_stop_count--) {
553 App::Private::Signal(*g_active_screen, SIGTSTP);
554 }
555
556 int signal_resize_count = g_signal_resize_count.exchange(0);
557 while (signal_resize_count--) {
558 App::Private::Signal(*g_active_screen, SIGWINCH);
559 }
560#endif
561}
562
563void InstallSignalHandler(int sig) {
564#if defined(_WIN32)
565 auto old_signal_handler = std::signal(sig, RecordSignal);
566 g_old_signal_handlers[sig] = old_signal_handler;
567 on_exit_functions.emplace(
568 [=] { std::ignore = std::signal(sig, old_signal_handler); });
569#else
570 struct sigaction sa;
571 sa.sa_handler = RecordSignal;
572 sigemptyset(&sa.sa_mask);
573 sa.sa_flags = SA_RESTART;
574 struct sigaction old_sa;
575 sigaction(sig, &sa, &old_sa);
576 g_old_sigactions[sig] = old_sa;
577 on_exit_functions.emplace([=] { sigaction(sig, &old_sa, nullptr); });
578#endif
579}
580
581} // namespace
582
583App::Internal::Internal(App* app,
584 AppDimension dimension,
585 bool use_alternative_screen)
586 : public_(app),
587 dimension_(dimension),
588 use_alternative_screen_(use_alternative_screen),
589 terminal_input_parser([&](Event event) {
590 event_buffer.Push(std::move(event));
591 }),
592 cursor_position_request(this, [this] {
593 TerminalSend(DeviceStatusReport(DSRMode::kCursor));
594 }) {
595 main_loop_receiver = event_buffer.CreateReceiver();
596}
597
598void App::Internal::ExitNow() {
599 quit_ = true;
600}
601
602void App::Internal::Install() {
603 frame_valid_ = false;
604 previous_frame_ = PreviousFrame();
605
606 // Flush the buffer for stdout to ensure whatever the user has printed before
607 // is fully applied before we start modifying the terminal configuration. This
608 // is important, because we are using two different channels (stdout vs
609 // termios/WinAPI) to communicate with the terminal emulator below. See
610 // https://github.com/ArthurSonzogni/FTXUI/issues/846
611 TerminalFlush();
612
613 InstallPipedInputHandling();
614
615 // After uninstalling the new configuration, flush it to the terminal to
616 // ensure it is fully applied:
617 on_exit_functions.emplace([this] { TerminalFlush(); });
618
619 // Install signal handlers to restore the terminal state on exit. The default
620 // signal handlers are restored on exit.
621 for (const int signal : {SIGTERM, SIGSEGV, SIGINT, SIGILL, SIGABRT, SIGFPE}) {
622 InstallSignalHandler(signal);
623 }
624
625// Save the old terminal configuration and restore it on exit.
626#if defined(_WIN32)
627 // Enable VT processing on stdout and stdin
628 auto stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
629 auto stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
630
631 DWORD out_mode = 0;
632 DWORD in_mode = 0;
633 GetConsoleMode(stdout_handle, &out_mode);
634 GetConsoleMode(stdin_handle, &in_mode);
635 g_original_stdout_mode = out_mode;
636 g_original_stdin_mode = in_mode;
637 g_has_original_console_mode = true;
638 on_exit_functions.push([=] { SetConsoleMode(stdout_handle, out_mode); });
639 on_exit_functions.push([=] { SetConsoleMode(stdin_handle, in_mode); });
640
641 // https://docs.microsoft.com/en-us/windows/console/setconsolemode
642 const int enable_virtual_terminal_processing = 0x0004;
643 const int disable_newline_auto_return = 0x0008;
644 out_mode |= enable_virtual_terminal_processing;
645 out_mode |= disable_newline_auto_return;
646
647 // https://docs.microsoft.com/en-us/windows/console/setconsolemode
648 const int enable_line_input = 0x0002;
649 const int enable_echo_input = 0x0004;
650 const int enable_virtual_terminal_input = 0x0200;
651 const int enable_window_input = 0x0008;
652 in_mode &= ~enable_echo_input;
653 in_mode &= ~enable_line_input;
654 in_mode |= enable_virtual_terminal_input;
655 in_mode |= enable_window_input;
656
657 SetConsoleMode(stdin_handle, in_mode);
658 SetConsoleMode(stdout_handle, out_mode);
659#else // POSIX (Linux & Mac)
660 for (const int signal :
661 {SIGWINCH, SIGTSTP, SIGBUS, SIGSYS, SIGQUIT, SIGHUP}) {
662 InstallSignalHandler(signal);
663 }
664
665 struct termios terminal; // NOLINT
666 tcgetattr(tty_fd_, &terminal);
667 g_original_termios = terminal;
668 g_tty_fd = tty_fd_;
669 g_has_original_termios = true;
670 on_exit_functions.emplace([terminal = terminal, tty_fd_ = tty_fd_] {
671 tcsetattr(tty_fd_, TCSANOW, &terminal);
672 });
673
674 // Enabling raw terminal input mode
675 terminal.c_iflag &= ~IGNBRK; // Disable ignoring break condition
676 terminal.c_iflag &= ~BRKINT; // Disable break causing input and output to be
677 // flushed
678 terminal.c_iflag &= ~PARMRK; // Disable marking parity errors.
679 terminal.c_iflag &= ~ISTRIP; // Disable stripping 8th bit off characters.
680 terminal.c_iflag &= ~INLCR; // Disable mapping NL to CR.
681 terminal.c_iflag &= ~IGNCR; // Disable ignoring CR.
682 terminal.c_iflag &= ~ICRNL; // Disable mapping CR to NL.
683 terminal.c_iflag &= ~IXON; // Disable XON/XOFF flow control on output
684
685 terminal.c_lflag &= ~ECHO; // Disable echoing input characters.
686 terminal.c_lflag &= ~ECHONL; // Disable echoing new line characters.
687 terminal.c_lflag &= ~ICANON; // Disable Canonical mode.
688 terminal.c_lflag &= ~ISIG; // Disable sending signal when hitting:
689 // - => DSUSP
690 // - C-Z => SUSP
691 // - C-C => INTR
692 // - C-d => QUIT
693 terminal.c_lflag &= ~IEXTEN; // Disable extended input processing
694 terminal.c_cflag |= CS8; // 8 bits per byte
695
696 terminal.c_cc[VMIN] = 0; // Minimum number of characters for non-canonical
697 // read.
698 terminal.c_cc[VTIME] = 0; // Timeout in deciseconds for non-canonical read.
699
700 tcsetattr(tty_fd_, TCSANOW, &terminal);
701
702#endif
703
704 auto enable = [&](const std::vector<DECMode>& parameters) {
705 TerminalSend(Set(parameters));
706 on_exit_functions.emplace(
707 [this, parameters] { TerminalSend(Reset(parameters)); });
708 };
709
710 auto disable = [&](const std::vector<DECMode>& parameters) {
711 TerminalSend(Reset(parameters));
712 on_exit_functions.emplace(
713 [this, parameters] { TerminalSend(Set(parameters)); });
714 };
715
716 if (use_alternative_screen_) {
717 enable({
718 DECMode::kAlternateScreen,
719 });
720 }
721
722 disable({
723 DECMode::kLineWrap,
724 });
725
726 if (track_mouse_) {
727 enable({DECMode::kMouseVt200});
728 enable({DECMode::kMouseAnyEvent});
729 enable({DECMode::kMouseUrxvtMode});
730 enable({DECMode::kMouseSgrExtMode});
731 }
732
733 // After installing the new configuration, flush it to the terminal to
734 // ensure it is fully applied:
735 TerminalFlush();
736
737 InstallTerminalInfo();
738
739 quit_ = false;
740
741 PostAnimationTask();
742
743 installed_ = true;
744 g_terminal_is_raw = true;
745}
746
747void App::Internal::Uninstall() {
748 g_terminal_is_raw = false;
749 installed_ = false;
750
751 // During shutdown, wait for all of the replies.
752 if (is_stdin_a_tty_ && is_stdout_a_tty_) {
753 auto closing_receiver =
754 event_buffer.CreateReceiverAt(main_loop_receiver->index());
755 auto start = std::chrono::steady_clock::now();
756 while (cursor_position_request.HasPending()) {
757 FetchTerminalEvents();
758
759 while (closing_receiver->Has()) {
760 const auto event = closing_receiver->Pop();
761 if (event.is_cursor_position()) {
762 cursor_x_ = event.cursor_x();
763 cursor_y_ = event.cursor_y();
764 cursor_position_request.OnReply();
765 }
766 }
767
768 task_runner.RunUntilIdle();
769
770 if (std::chrono::steady_clock::now() - start >
771 std::chrono::milliseconds(400)) {
772 break;
773 }
774 std::this_thread::sleep_for(std::chrono::milliseconds(10));
775 }
776 }
777
778 OnExit();
779}
780
781void App::Internal::PreMain() {
782 // Suspend previously active screen:
783 if (g_active_screen) {
784 std::swap(suspended_screen_, g_active_screen);
785 // Reset cursor position to the top of the screen and clear the screen.
786 // Nothing to clear when nothing was drawn yet.
787 if (suspended_screen_->internal_->frame_count_ != 0) {
788 suspended_screen_->internal_->TerminalSend(
789 suspended_screen_->internal_->ResetCursorPosition());
790 suspended_screen_->ResetPosition(
791 suspended_screen_->internal_->output_buffer,
792 /*clear=*/true);
793 suspended_screen_->dimx_ = 0;
794 suspended_screen_->dimy_ = 0;
795 }
796
797 // Reset dimensions to force drawing the screen again next time:
798 suspended_screen_->internal_->Uninstall();
799 }
800
801 // The first frame is drawn at the cursor position, below what was printed
802 // before, including the last frame of a previous Loop. See #809.
803 frame_count_ = 0;
804
805 // This screen is now active:
806 g_active_screen = public_;
807 g_active_screen->internal_->Install();
808
809 previous_animation_time_ = animation::Clock::now();
810}
811
812void App::Internal::PostMain() {
813 // Put cursor position at the end of the drawing.
814 TerminalSend(ResetCursorPosition());
815
816 g_active_screen = nullptr;
817
818 // Restore suspended screen.
819 if (suspended_screen_) {
820 // Clear screen, and put the cursor at the beginning of the drawing.
821 if (frame_count_ != 0) {
822 public_->ResetPosition(output_buffer, /*clear=*/true);
823 public_->dimx_ = 0;
824 public_->dimy_ = 0;
825 }
826 Uninstall();
827 std::swap(g_active_screen, suspended_screen_);
828 g_active_screen->internal_->Install();
829 } else {
830 Uninstall();
831
832 std::cout << "\r";
833 // On final exit, keep the current drawing and reset cursor position one
834 // line after it.
835 if (!use_alternative_screen_) {
836 std::cout << "\n";
837 }
838 std::cout << std::flush;
839 }
840
841 int sig = g_last_signal.exchange(0);
842 if (sig != 0) {
843 RestoreSignalHandlerAndRaise(sig);
844 }
845}
846
847bool App::Internal::HasQuitted() {
848 return quit_;
849}
850
851void App::Internal::RunOnce(const Component& component) {
852 const AutoReset set_component(&component_, component);
853 ExecuteSignalHandlers();
854 FetchTerminalEvents();
855
856 while (!quit_ && main_loop_receiver->Has()) {
857 public_->Post(main_loop_receiver->Pop());
858 }
859
860 // Execute the pending tasks from the queue.
861 const size_t executed_task = task_runner.ExecutedTasks();
862 task_runner.RunUntilIdle();
863 // If no executed task, we can return early without redrawing the screen.
864 if (executed_task == task_runner.ExecutedTasks()) {
865 return;
866 }
867
868 ExecuteSignalHandlers();
869 Draw(component);
870
871 if (selection_data_previous_ != selection_data_) {
872 selection_data_previous_ = selection_data_;
873 if (selection_on_change_) {
874 selection_on_change_();
875 public_->Post(Event::Custom);
876 }
877 }
878}
879
880void App::Internal::RunOnceBlocking(Component component) {
881 // Set FPS to 60 at most.
882 const auto time_per_frame = std::chrono::microseconds(16666); // 1s / 60fps
883
884 auto time = std::chrono::steady_clock::now();
885 const size_t executed_task = task_runner.ExecutedTasks();
886
887 // Wait for at least one task to execute.
888 while (executed_task == task_runner.ExecutedTasks() && !HasQuitted()) {
889 RunOnce(component);
890
891 const auto now = std::chrono::steady_clock::now();
892 const auto delta = now - time;
893 time = now;
894
895 if (delta < time_per_frame) {
896 const auto sleep_duration = time_per_frame - delta;
897 std::this_thread::sleep_for(sleep_duration);
898 }
899 }
900}
901
902void App::Internal::HandleTask(Component component, Task& task) {
903 std::visit(
904 [&](auto&& arg) {
905 using T = std::decay_t<decltype(arg)>;
906 // clang-format off
907
908 // Handle Event.
909 if constexpr (std::is_same_v<T, Event>) {
910
911 if (arg.is_cursor_position()) {
912 cursor_x_ = arg.cursor_x();
913 cursor_y_ = arg.cursor_y();
914 cursor_position_request.OnReply();
915 return;
916 }
917
918 if (arg.is_cursor_shape()) {
919 cursor_reset_shape_ = arg.cursor_shape();
920 return;
921 }
922
923 if (arg.IsTerminalCapabilities()) {
924 terminal_capabilities_ = arg.TerminalCapabilities();
925 return;
926 }
927
928 if (arg.IsTerminalNameVersion()) {
929 terminal_name_ = arg.TerminalName();
930 terminal_version_ = arg.TerminalVersion();
931 return;
932 }
933
934 if (arg.IsTerminalEmulator()) {
935 terminal_emulator_name_ = arg.TerminalEmulatorName();
936 terminal_emulator_version_ = arg.TerminalEmulatorVersion();
937 return;
938 }
939
940 if (arg.is_mouse()) {
941 arg.mouse().x -= cursor_x_;
942 arg.mouse().y -= cursor_y_;
943 }
944
945 arg.screen_ = public_;
946
947 bool handled = component->OnEvent(arg);
948 handled = HandleSelection(handled, arg);
949
950 if (arg == Event::CtrlC && (!handled || force_handle_ctrl_c_)) {
951 RecordSignal(SIGINT);
952 }
953
954#if !defined(_WIN32)
955 if (arg == Event::CtrlZ && (!handled || force_handle_ctrl_z_)) {
956 RecordSignal(SIGTSTP);
957 }
958#endif
959
960 frame_valid_ = false;
961 return;
962 }
963
964 // Handle callback
965 if constexpr (std::is_same_v<T, Closure>) {
966 arg();
967 return;
968 }
969
970 // Handle Animation
971 if constexpr (std::is_same_v<T, AnimationTask>) {
972 if (!animation_requested_) {
973 return;
974 }
975
976 animation_requested_ = false;
977 const animation::TimePoint now = animation::Clock::now();
978 const animation::Duration delta = now - previous_animation_time_;
979 previous_animation_time_ = now;
980
981 animation::Params params(delta);
982 component->OnAnimation(params);
983 frame_valid_ = false;
984 return;
985 }
986 },
987 task);
988 // clang-format on
989}
990
991bool App::Internal::HandleSelection(bool handled, Event event) {
992 if (handled) {
993 selection_pending_ = nullptr;
994 selection_data_.empty = true;
995 selection_ = nullptr;
996 return true;
997 }
998
999 if (!event.is_mouse()) {
1000 return false;
1001 }
1002
1003 auto& mouse = event.mouse();
1004 if (mouse.button != Mouse::Left) {
1005 return false;
1006 }
1007
1008 if (mouse.motion == Mouse::Pressed) {
1009 selection_pending_ = public_->CaptureMouse();
1010 selection_data_.start_x = mouse.x;
1011 selection_data_.start_y = mouse.y;
1012 selection_data_.end_x = mouse.x;
1013 selection_data_.end_y = mouse.y;
1014 return false;
1015 }
1016
1017 if (!selection_pending_) {
1018 return false;
1019 }
1020
1021 if (mouse.motion == Mouse::Moved) {
1022 if ((mouse.x != selection_data_.end_x) ||
1023 (mouse.y != selection_data_.end_y)) {
1024 selection_data_.end_x = mouse.x;
1025 selection_data_.end_y = mouse.y;
1026 selection_data_.empty = false;
1027 }
1028
1029 return true;
1030 }
1031
1032 if (mouse.motion == Mouse::Released) {
1033 selection_pending_ = nullptr;
1034 selection_data_.end_x = mouse.x;
1035 selection_data_.end_y = mouse.y;
1036 selection_data_.empty = false;
1037 return true;
1038 }
1039
1040 return false;
1041}
1042
1043void App::Internal::Draw(Component component) {
1044 if (frame_valid_) {
1045 return;
1046 }
1047 auto document = component->Render();
1048 int dimx = 0;
1049 int dimy = 0;
1050 auto terminal = Terminal::Size();
1051 document->ComputeRequirement();
1052 switch (dimension_) {
1054 dimx = public_->dimx_;
1055 dimy = public_->dimy_;
1056 break;
1058 dimx = terminal.dimx;
1059 dimy = util::clamp(document->requirement().min_y, 0, terminal.dimy);
1060 break;
1062 dimx = terminal.dimx;
1063 dimy = terminal.dimy;
1064 break;
1066 dimx = util::clamp(document->requirement().min_x, 0, terminal.dimx);
1067 dimy = util::clamp(document->requirement().min_y, 0, terminal.dimy);
1068 break;
1069 }
1070
1071 // Hide cursor to prevent flickering during reset.
1072 TerminalSend("\033[?25l");
1073
1074 const bool resized =
1075 frame_count_ == 0 || (dimx != public_->dimx_) || (dimy != public_->dimy_);
1076 // Whether the frame can be updated in place, from the previous one.
1077 const bool update_in_place = !resized && print_above_.empty();
1078 TerminalSend(ResetCursorPosition());
1079
1080 if (frame_count_ != 0) {
1081 // Reset the cursor position to the lower left corner to start drawing the
1082 // new frame.
1083 // Clear the previous frame when printing above it, because the new frame
1084 // is drawn lower and would not overwrite it fully.
1085 public_->ResetPosition(output_buffer, resized || !print_above_.empty());
1086
1087 // If the terminal width decrease, the terminal emulator will start wrapping
1088 // lines and make the display dirty. We should clear it completely.
1089 if ((dimx < public_->dimx_) && !use_alternative_screen_) {
1090 TerminalSend("\033[J"); // clear terminal output
1091 TerminalSend("\033[H"); // move cursor to home position
1092 }
1093 }
1094
1095 // Print the pending elements above the frame. They are never drawn again,
1096 // and scroll into the terminal scrollback.
1097 for (auto& element : print_above_) {
1098 const int height =
1099 Dimension::Fit(element, /*extend_beyond_screen=*/true).dimy;
1100 Screen screen(terminal.dimx, height);
1101 Render(screen, element.get());
1102 screen.ToString(output_buffer);
1103 TerminalSend("\r\n");
1104 }
1105 print_above_.clear();
1106
1107 // Resize the screen if needed.
1108 if (resized) {
1109 public_->dimx_ = dimx;
1110 public_->dimy_ = dimy;
1111 public_->cells_ = std::vector<Cell>(static_cast<size_t>(dimx) *
1112 static_cast<size_t>(dimy));
1113 Cursor cursor = public_->cursor_;
1114 cursor.x = dimx - 1;
1115 cursor.y = dimy - 1;
1116 public_->SetCursor(cursor);
1117 }
1118
1119 // Periodically request the terminal emulator the frame position relative to
1120 // the screen. This is useful for converting mouse position reported in
1121 // screen's coordinates to frame's coordinates.
1122 if (!use_alternative_screen_ && is_stdout_a_tty_) {
1123 RequestCursorPosition(previous_frame_resized_);
1124 }
1125 previous_frame_resized_ = resized;
1126
1127 selection_ = selection_data_.empty
1128 ? std::make_unique<Selection>()
1129 : std::make_unique<Selection>(
1130 selection_data_.start_x, selection_data_.start_y, //
1131 selection_data_.end_x, selection_data_.end_y);
1132 Render(*public_, document.get(), *selection_);
1133
1134 // Set cursor position for user using tools to insert CJK characters.
1135 {
1136 const int dx = public_->dimx_ - 1 - public_->cursor_.x +
1137 int(public_->dimx_ != terminal.dimx);
1138 const int dy = public_->dimy_ - 1 - public_->cursor_.y;
1139
1140 set_cursor_position_.clear();
1141 reset_cursor_position_.clear();
1142
1143 if (dy != 0) {
1144 set_cursor_position_ += "\x1B[" + std::to_string(dy) + "A";
1145 reset_cursor_position_ += "\x1B[" + std::to_string(dy) + "B";
1146 }
1147
1148 if (dx != 0) {
1149 set_cursor_position_ += "\x1B[" + std::to_string(dx) + "D";
1150 reset_cursor_position_ += "\x1B[" + std::to_string(dx) + "C";
1151 }
1152
1153 if (public_->cursor_.shape != Screen::Cursor::Hidden) {
1154 set_cursor_position_ += "\033[?25h";
1155 set_cursor_position_ +=
1156 "\033[" + std::to_string(int(public_->cursor_.shape)) + " q";
1157 }
1158 }
1159
1160 if (update_in_place) {
1161 public_->ToString(output_buffer, previous_frame_);
1162 } else {
1163 public_->ToString(output_buffer);
1164 }
1165 TerminalSend(set_cursor_position_);
1166 TerminalFlush();
1167
1168 previous_frame_.Swap(public_->cells_, public_->hyperlinks_, public_->dimx_,
1169 public_->dimy_);
1170 public_->cells_.resize(static_cast<size_t>(public_->dimx_) *
1171 static_cast<size_t>(public_->dimy_));
1172 public_->Clear();
1173 frame_valid_ = true;
1174 frame_count_++;
1175}
1176
1177std::string App::Internal::ResetCursorPosition() {
1178 std::string result = std::move(reset_cursor_position_);
1179 reset_cursor_position_ = "";
1180 return result;
1181}
1182
1183void App::Internal::RequestCursorPosition(bool force) {
1184 cursor_position_request.Request(force);
1185}
1186
1187void App::Internal::TerminalSend(std::string_view s) {
1188 output_buffer += s;
1189}
1190
1191void App::Internal::TerminalFlush() {
1192 // Emscripten doesn't implement flush. We interpret zero as flush.
1193 output_buffer += '\0';
1194 std::cout << output_buffer << std::flush;
1195 output_buffer.clear();
1196}
1197
1198void App::Internal::InstallPipedInputHandling() {
1199 is_stdin_a_tty_ = false;
1200 is_stdout_a_tty_ = false;
1201#if defined(__EMSCRIPTEN__)
1202 is_stdin_a_tty_ = true;
1203 is_stdout_a_tty_ = true;
1204#elif defined(_WIN32)
1205 is_stdin_a_tty_ = _isatty(_fileno(stdin));
1206 is_stdout_a_tty_ = _isatty(_fileno(stdout));
1207#else
1208 tty_fd_ = STDIN_FILENO;
1209 is_stdout_a_tty_ = isatty(STDOUT_FILENO);
1210 // Handle piped input redirection if explicitly enabled by the application.
1211 // This allows applications to read data from stdin while still receiving
1212 // keyboard input from the terminal for interactive use.
1213 if (!handle_piped_input_) {
1214 is_stdin_a_tty_ = isatty(STDIN_FILENO);
1215 } else if (isatty(STDIN_FILENO)) {
1216 is_stdin_a_tty_ = true;
1217 } else {
1218 // Open /dev/tty for keyboard input.
1219 tty_fd_ = open("/dev/tty", O_RDONLY); // NOLINT
1220 if (tty_fd_ < 0) {
1221 // Failed to open /dev/tty (containers, headless systems, etc.)
1222 tty_fd_ = STDIN_FILENO; // Fallback to stdin.
1223 is_stdin_a_tty_ = isatty(STDIN_FILENO);
1224 } else {
1225 is_stdin_a_tty_ = true;
1226 // Close the /dev/tty file descriptor on exit.
1227 on_exit_functions.emplace([this] {
1228 close(tty_fd_);
1229 tty_fd_ = -1;
1230 });
1231 }
1232 }
1233#endif
1234}
1235
1236void App::Internal::InstallTerminalInfo() {
1237 // Request the terminal to report the current cursor shape. We will restore it
1238 // on exit.
1239 if (is_stdout_a_tty_) {
1240 if (SupportsDECRQSS()) {
1241 TerminalSend(DECRQSS_DECSCUSR);
1242 }
1243 TerminalSend("\033[>q"); // XTVERSION
1244 TerminalSend("\033[>c"); // DA2
1245 TerminalSend("\033[c"); // DA1
1246 TerminalFlush();
1247 }
1248
1249 // Wait for the cursor shape reply using the setup head.
1250 if (is_stdin_a_tty_ && is_stdout_a_tty_) {
1251 // A receiver scoped to the setup: keeping one alive after setup would pin
1252 // every subsequent event in the buffer, growing it for the whole app
1253 // lifetime.
1254 auto setup_receiver = event_buffer.CreateReceiver();
1255 auto start = std::chrono::steady_clock::now();
1256 bool terminal_capabilities_received = false;
1257 // Wait for the cursor shape reply using the setup head.
1258 while (true) {
1259 FetchTerminalEvents();
1260 while (setup_receiver->Has()) {
1261 const auto event = setup_receiver->Pop();
1262 if (event.is_cursor_shape()) {
1263 cursor_reset_shape_ = event.cursor_shape();
1264 }
1265
1266 if (event.IsTerminalCapabilities()) {
1267 terminal_capabilities_ = event.TerminalCapabilities();
1268 terminal_capabilities_received = true;
1269 }
1270
1271 if (event.IsTerminalNameVersion()) {
1272 terminal_name_ = event.TerminalName();
1273 terminal_version_ = event.TerminalVersion();
1274 }
1275
1276 if (event.IsTerminalEmulator()) {
1277 terminal_emulator_name_ = event.TerminalEmulatorName();
1278 terminal_emulator_version_ = event.TerminalEmulatorVersion();
1279 }
1280 }
1281
1282 // Response are expected to be received in order, so we can break when
1283 // the last one (XTVERSION) is received. We also set a timeout to prevent
1284 // waiting forever in case the terminal doesn't support these queries.
1285 if (terminal_capabilities_received) {
1286 break;
1287 }
1288
1289 if (std::chrono::steady_clock::now() - start >
1290 std::chrono::milliseconds(500)) {
1291 break;
1292 }
1293 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1294 }
1295 }
1296
1297 // Set quirks and color support based on terminal identification.
1298 Terminal::Quirks quirks = Terminal::GetQuirks();
1299
1300 auto color_support = Terminal::ComputeColorSupport(
1301 util::GetEnv("TERM"), util::GetEnv("COLORTERM"),
1302 util::GetEnv("TERM_PROGRAM"), terminal_name_, terminal_emulator_name_,
1303 terminal_capabilities_);
1304
1305 quirks.SetColorSupport(color_support);
1306
1307 const bool is_modern_emulator = (terminal_emulator_name_ != "unknown");
1308 const bool is_vt220_plus =
1309 (terminal_name_ != "vt100" && terminal_name_ != "unknown");
1310 bool reports_utf8 = false;
1311 for (const int x : terminal_capabilities_) {
1312 if (x == 52) {
1313 reports_utf8 = true;
1314 break;
1315 }
1316 }
1317
1318 // Heuristic: If the terminal emulator is modern, or it reports supporting
1319 // UTF-8 or color, we can assume it supports block characters and cursor
1320 // hiding, which are essential for a good experience. This is a heuristic, but
1321 // it allows us to work around some older terminal emulators that don't
1322 // support these features, while still providing a good experience on modern
1323 // terminal emulators that do support these features.
1324 bool modern = is_modern_emulator || is_vt220_plus || reports_utf8;
1325 if (modern) {
1326 quirks.SetBlockCharacters(true);
1327 quirks.SetCursorHiding(true);
1328 quirks.SetComponentAscii(false);
1329 }
1330
1331 Terminal::SetQuirks(quirks);
1332
1333 on_exit_functions.emplace([this] {
1334 TerminalSend("\033[?25h"); // Enable cursor.
1335 if (is_stdout_a_tty_) {
1336 TerminalSend("\033[" + std::to_string(cursor_reset_shape_) + " q");
1337 }
1338 });
1339}
1340
1341void App::Internal::Signal(int signal) {
1342 if (signal == SIGABRT) {
1343 public_->Exit();
1344 return;
1345 }
1346
1347// Windows do no support SIGTSTP / SIGWINCH
1348#if !defined(_WIN32)
1349 if (signal == SIGTSTP) {
1350 public_->Post([&] {
1351 TerminalSend(ResetCursorPosition());
1352 public_->ResetPosition(output_buffer, /*clear*/ true);
1353 Uninstall();
1354 public_->dimx_ = 0;
1355 public_->dimy_ = 0;
1356 (void)std::raise(SIGTSTP);
1357 Install();
1358 });
1359 return;
1360 }
1361
1362 if (signal == SIGWINCH) {
1363 public_->Post(Event::Special({0}));
1364 return;
1365 }
1366#endif
1367}
1368
1369size_t App::Internal::FetchTerminalEvents() {
1370#if defined(_WIN32)
1371 auto get_input_records = [&]() -> std::vector<INPUT_RECORD> {
1372 // Check if there is input in the console.
1373 auto console = GetStdHandle(STD_INPUT_HANDLE);
1374 DWORD number_of_events = 0;
1375 if (!GetNumberOfConsoleInputEvents(console, &number_of_events)) {
1376 return std::vector<INPUT_RECORD>();
1377 }
1378 if (number_of_events <= 0) {
1379 // No input, return.
1380 return std::vector<INPUT_RECORD>();
1381 }
1382 // Read the input events.
1383 std::vector<INPUT_RECORD> records(number_of_events);
1384 DWORD number_of_events_read = 0;
1385 if (!ReadConsoleInput(console, records.data(), (DWORD)records.size(),
1386 &number_of_events_read)) {
1387 return std::vector<INPUT_RECORD>();
1388 }
1389 records.resize(number_of_events_read);
1390 return records;
1391 };
1392
1393 auto records = get_input_records();
1394 if (records.size() == 0) {
1395 const auto timeout = std::chrono::steady_clock::now() - last_char_time;
1396 const size_t timeout_microseconds =
1397 std::chrono::duration_cast<std::chrono::microseconds>(timeout).count();
1398 terminal_input_parser.Timeout(timeout_microseconds);
1399 return 0;
1400 }
1401 last_char_time = std::chrono::steady_clock::now();
1402
1403 // Convert the input events to FTXUI events.
1404 // For each event, we call the terminal input parser to convert it to
1405 // Event.
1406 std::wstring wstring;
1407 for (const auto& r : records) {
1408 switch (r.EventType) {
1409 case KEY_EVENT: {
1410 auto key_event = r.Event.KeyEvent;
1411 // ignore UP key events
1412 if (key_event.bKeyDown == FALSE) {
1413 continue;
1414 }
1415 const wchar_t wc = key_event.uChar.UnicodeChar;
1416 wstring += wc;
1417 if (wc >= 0xd800 && wc <= 0xdbff) {
1418 // Wait for the Low Surrogate to arrive in the next record.
1419 continue;
1420 }
1421 for (auto it : to_string(wstring)) {
1422 terminal_input_parser.Add(it);
1423 }
1424 wstring.clear();
1425 } break;
1426 case WINDOW_BUFFER_SIZE_EVENT:
1427 public_->Post(Event::Special({0}));
1428 break;
1429 case MENU_EVENT:
1430 case FOCUS_EVENT:
1431 case MOUSE_EVENT:
1432 // TODO(mauve): Implement later.
1433 break;
1434 }
1435 }
1436 return records.size();
1437#elif defined(__EMSCRIPTEN__)
1438 // Read chars from the terminal.
1439 // We configured it to be non blocking.
1440 std::array<char, 4096> out{};
1441 const ssize_t l = read(STDIN_FILENO, out.data(), out.size());
1442 if (l <= 0) {
1443 const auto timeout = std::chrono::steady_clock::now() - last_char_time;
1444 const size_t timeout_microseconds =
1445 std::chrono::duration_cast<std::chrono::microseconds>(timeout).count();
1446 terminal_input_parser.Timeout(timeout_microseconds);
1447 return 0;
1448 }
1449 last_char_time = std::chrono::steady_clock::now();
1450
1451 // Convert the chars to events.
1452 for (ssize_t i = 0; i < l; ++i) {
1453 terminal_input_parser.Add(out.at(static_cast<size_t>(i)));
1454 }
1455 return (size_t)l;
1456#else // POSIX (Linux & Mac)
1457 struct pollfd pfd = {tty_fd_, POLLIN, 0};
1458 const int poll_result = poll(&pfd, 1, 0);
1459 if (poll_result <= 0) {
1460 const auto timeout = std::chrono::steady_clock::now() - last_char_time;
1461 const size_t timeout_ms =
1462 std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count();
1463 terminal_input_parser.Timeout(static_cast<int>(timeout_ms));
1464 return 0;
1465 }
1466 last_char_time = std::chrono::steady_clock::now();
1467
1468 // Drain the available input, so that bursts (e.g. fast mouse wheel
1469 // scrolling) do not accumulate across frames. The total is bounded to keep
1470 // the frame responsive under a continuous input flood. See #1348.
1471 constexpr size_t kMaxBytesPerFetch = 64 * 1024;
1472 std::array<char, 4096> out{};
1473 size_t total = 0;
1474 while (total < kMaxBytesPerFetch) {
1475 const ssize_t l = read(tty_fd_, out.data(), out.size());
1476 if (l <= 0) {
1477 break;
1478 }
1479
1480 // Convert the chars to events.
1481 for (ssize_t i = 0; i < l; ++i) {
1482 terminal_input_parser.Add(out.at(static_cast<size_t>(i)));
1483 }
1484 total += static_cast<size_t>(l);
1485
1486 pfd.revents = 0;
1487 if (poll(&pfd, 1, 0) <= 0) {
1488 break;
1489 }
1490 }
1491 return total;
1492#endif
1493}
1494
1495void App::Internal::PostAnimationTask() {
1496 public_->Post(AnimationTask());
1497
1498 // Repeat the animation task every 15ms. This correspond to a frame rate
1499 // of around 66fps.
1500 task_runner.PostDelayedTask([this] { PostAnimationTask(); },
1501 std::chrono::milliseconds(15));
1502}
1503
1504App::App(std::unique_ptr<Internal> internal, int dimx, int dimy)
1505 : Screen(dimx, dimy), internal_(std::move(internal)) {
1506 internal_->public_ = this;
1507}
1508
1509App::App(App&& other) noexcept : Screen(std::move(other)) {
1510 internal_ = std::move(other.internal_);
1511 if (internal_) {
1512 internal_->public_ = this;
1513 }
1514}
1515
1516App& App::operator=(App&& other) noexcept {
1517 Screen::operator=(std::move(other));
1518 internal_ = std::move(other.internal_);
1519 if (internal_) {
1520 internal_->public_ = this;
1521 }
1522 return *this;
1523}
1524
1525App::~App() = default;
1526
1527// static
1528App App::FixedSize(int dimx, int dimy) {
1529 auto internal =
1530 std::make_unique<Internal>(nullptr, AppDimension::Fixed, false);
1531 return App(std::move(internal), dimx, dimy);
1532}
1533
1534// static
1535App App::Fullscreen() {
1536 return FullscreenAlternateScreen();
1537}
1538
1539// static
1540App App::FullscreenPrimaryScreen() {
1541 auto terminal = Terminal::Size();
1542 auto internal =
1543 std::make_unique<Internal>(nullptr, AppDimension::Fullscreen, false);
1544 return App(std::move(internal), terminal.dimx, terminal.dimy);
1545}
1546
1547// static
1548App App::FullscreenAlternateScreen() {
1549 auto terminal = Terminal::Size();
1550 auto internal =
1551 std::make_unique<Internal>(nullptr, AppDimension::Fullscreen, true);
1552 return App(std::move(internal), terminal.dimx, terminal.dimy);
1553}
1554
1555// static
1556App App::FitComponent() {
1557 auto terminal = Terminal::Size();
1558 auto internal =
1559 std::make_unique<Internal>(nullptr, AppDimension::FitComponent, false);
1560 return App(std::move(internal), terminal.dimx, terminal.dimy);
1561}
1562
1563// static
1564App App::TerminalOutput() {
1565 auto terminal = Terminal::Size();
1566 auto internal =
1567 std::make_unique<Internal>(nullptr, AppDimension::TerminalOutput, false);
1568 return App(std::move(internal), terminal.dimx, terminal.dimy);
1569}
1570
1571void App::TrackMouse(bool enable) {
1572 internal_->track_mouse_ = enable;
1573}
1574
1575void App::HandlePipedInput(bool enable) {
1576 internal_->handle_piped_input_ = enable;
1577}
1578
1579// static
1580App* App::Active() {
1581 return g_active_screen;
1582}
1583
1584void App::Loop(Component component) {
1585 class Loop loop(this, std::move(component));
1586 loop.Run();
1587}
1588
1589void App::Exit() {
1590 Post([this] { internal_->ExitNow(); });
1591}
1592
1593Closure App::ExitLoopClosure() {
1594 return [this] { Exit(); };
1595}
1596
1597void App::PrintAbove(Element element) {
1598 Post([this, element = std::move(element)] {
1599 internal_->print_above_.push_back(element);
1600 internal_->frame_valid_ = false;
1601 });
1602}
1603
1604void App::Post(Task task) {
1605 internal_->task_runner.PostTask([this, task = std::move(task)]() mutable {
1606 if (internal_->component_) {
1607 internal_->HandleTask(internal_->component_, task);
1608 return;
1609 }
1610
1611 // If there is no component, we can still execute closures.
1612 if (std::holds_alternative<Closure>(task)) {
1613 std::get<Closure>(task)();
1614 }
1615 });
1616}
1617
1618void App::PostEvent(Event event) {
1619 // PostEvent is documented as thread safe: go through the mutex-protected
1620 // task queue. The event_buffer is only safe to use from the main thread.
1621 Post(Task(std::move(event)));
1622}
1623
1624// static
1625void App::PostEventOrExecute(Closure closure) {
1626 if (!closure) {
1627 return;
1628 }
1629 if (auto* app = App::Active()) {
1630 app->Post(std::move(closure));
1631 } else {
1632 closure();
1633 }
1634}
1635
1636void App::RequestAnimationFrame() {
1637 if (internal_->animation_requested_) {
1638 return;
1639 }
1640 internal_->animation_requested_ = true;
1641 auto now = animation::Clock::now();
1642 const auto time_histeresis = std::chrono::milliseconds(33);
1643 if (now - internal_->previous_animation_time_ >= time_histeresis) {
1644 internal_->previous_animation_time_ = now;
1645 }
1646}
1647
1648CapturedMouse App::CaptureMouse() {
1649 if (internal_->mouse_captured) {
1650 return nullptr;
1651 }
1652 internal_->mouse_captured = true;
1653 return std::make_unique<CapturedMouseImpl>(
1654 [this] { internal_->mouse_captured = false; });
1655}
1656
1657Closure App::WithRestoredIO(Closure fn) {
1658 return [this, fn] {
1659 internal_->Uninstall();
1660 fn();
1661 internal_->Install();
1662 };
1663}
1664
1665void App::ForceHandleCtrlC(bool force) {
1666 internal_->force_handle_ctrl_c_ = force;
1667}
1668
1669void App::ForceHandleCtrlZ(bool force) {
1670 internal_->force_handle_ctrl_z_ = force;
1671}
1672
1673std::string App::GetSelection() {
1674 if (!internal_->selection_) {
1675 return "";
1676 }
1677 return internal_->selection_->GetParts();
1678}
1679
1680void App::SelectionChange(std::function<void()> callback) {
1681 internal_->selection_on_change_ = std::move(callback);
1682}
1683
1684const std::string& App::TerminalName() const {
1685 return internal_->terminal_name_;
1686}
1687
1688int App::TerminalVersion() const {
1689 return internal_->terminal_version_;
1690}
1691
1692const std::string& App::TerminalEmulatorName() const {
1693 return internal_->terminal_emulator_name_;
1694}
1695
1696const std::string& App::TerminalEmulatorVersion() const {
1697 return internal_->terminal_emulator_version_;
1698}
1699
1700const std::vector<int>& App::TerminalCapabilities() const {
1701 return internal_->terminal_capabilities_;
1702}
1703
1704std::vector<std::string> App::TerminalCapabilityNames() const {
1705 return Event::TerminalCapabilities("", internal_->terminal_capabilities_)
1706 .TerminalCapabilityNames();
1707}
1708
1709// Loop calls these:
1710
1711void App::ExitNow() {
1712 internal_->ExitNow();
1713}
1714void App::Install() {
1715 internal_->Install();
1716}
1717void App::Uninstall() {
1718 internal_->Uninstall();
1719}
1720void App::PreMain() {
1721 internal_->PreMain();
1722}
1723void App::PostMain() {
1724 internal_->PostMain();
1725}
1726bool App::HasQuitted() {
1727 return internal_->HasQuitted();
1728}
1729void App::RunOnce(const Component& component) {
1730 internal_->RunOnce(component);
1731}
1732void App::RunOnceBlocking(Component component) {
1733 internal_->RunOnceBlocking(component);
1734}
1735void App::HandleTask(Component component, Task& task) {
1736 internal_->HandleTask(component, task);
1737}
1738bool App::HandleSelection(bool handled, Event event) {
1739 return internal_->HandleSelection(handled, event);
1740}
1741void App::Draw(Component component) {
1742 internal_->Draw(component);
1743}
1744std::string App::ResetCursorPosition() {
1745 return internal_->ResetCursorPosition();
1746}
1747void App::RequestCursorPosition(bool force) {
1748 internal_->RequestCursorPosition(force);
1749}
1750void App::TerminalSend(std::string_view s) {
1751 internal_->TerminalSend(s);
1752}
1753void App::TerminalFlush() {
1754 internal_->TerminalFlush();
1755}
1756void App::InstallPipedInputHandling() {
1757 internal_->InstallPipedInputHandling();
1758}
1759void App::InstallTerminalInfo() {
1760 internal_->InstallTerminalInfo();
1761}
1762void App::Signal(int signal) {
1763 internal_->Signal(signal);
1764}
1765size_t App::FetchTerminalEvents() {
1766 return internal_->FetchTerminalEvents();
1767}
1768void App::PostAnimationTask() {
1769 internal_->PostAnimationTask();
1770}
1771
1772Loop::Loop(App* screen, Component component)
1773 : screen_(screen), component_(std::move(component)) {
1774 screen_->PreMain();
1775}
1776
1777Loop::~Loop() {
1778 screen_->PostMain();
1779}
1780
1781bool Loop::HasQuitted() {
1782 return screen_->HasQuitted();
1783}
1784
1785void Loop::RunOnce() {
1786 screen_->RunOnce(component_);
1787}
1788
1789void Loop::RunOnceBlocking() {
1790 screen_->RunOnceBlocking(component_);
1791}
1792
1793void Loop::Run() {
1794 while (!HasQuitted()) {
1795 RunOnceBlocking();
1796 }
1797}
1798
1799} // namespace ftxui
Quirks GetQuirks()
Get the terminal quirks.
Definition terminal.cpp:365
Dimensions Size()
Get the terminal size.
Definition terminal.cpp:312
void SetQuirks(const Quirks &quirks)
Override terminal quirks.
Definition terminal.cpp:375
The FTXUI ftxui::animation:: namespace.
void SetFallbackSize(const Dimensions &fallbackSize)
Override terminal size in case auto-detection fails.
Definition terminal.cpp:342
Color ComputeColorSupport(std::string_view term, std::string_view colorterm, std::string_view term_program, std::string_view terminal_name, std::string_view terminal_emulator_name, const std::vector< int > &capabilities)
Compute the color support based on environment variables and terminal identification.
Definition terminal.cpp:197
std::chrono::duration< float > Duration
Definition animation.hpp:31
std::chrono::time_point< Clock > TimePoint
Definition animation.hpp:30
void RequestAnimationFrame()
Definition app.cpp:75
const char * GetEnv(const char *name)
Definition util.hpp:18
constexpr const T & clamp(const T &v, const T &lo, const T &hi)
Definition util.hpp:13
The FTXUI ftxui:: namespace.
Definition animation.hpp:11
std::unique_ptr< CapturedMouseInterface > CapturedMouse
std::shared_ptr< Node > Element
Definition app.hpp:25
std::string to_string(std::wstring_view s)
Convert a std::wstring into a UTF8 std::string.
Definition string.cpp:587
AppDimension
Definition app.cpp:67
std::variant< Event, Closure, AnimationTask > Task
Definition task.hpp:14
const Element & element
Definition node.hpp:95
void Render(Screen &screen, Node *node, Selection &selection)
Definition node.cpp:105
std::function< void()> Closure
Definition task.hpp:13
std::shared_ptr< ComponentBase > Component
Definition app.hpp:23