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