15#include <initializer_list>
45#define DEFINE_CONSOLEV2_PROPERTIES
46#define WIN32_LEAN_AND_MEAN
61#if defined(__EMSCRIPTEN__)
62#include <emscripten.h>
76 auto* screen = App::Active();
78 screen->RequestAnimationFrame();
83#if defined(__EMSCRIPTEN__)
86void ftxui_on_resize(
int columns,
int rows) {
99 class PreviousFrame :
public Screen {
101 PreviousFrame() : Screen(0, 0) {}
103 void Swap(std::vector<Cell>& cells,
104 std::vector<std::string>& hyperlinks,
107 std::swap(cells_, cells);
108 std::swap(hyperlinks_, hyperlinks);
116 App* suspended_screen_ =
nullptr;
118 const bool use_alternative_screen_;
120 bool track_mouse_ =
true;
122 std::string set_cursor_position_;
123 std::string reset_cursor_position_;
125 std::atomic<bool> quit_{
false};
126 bool installed_ =
false;
127 bool animation_requested_ =
false;
133 std::uint64_t frame_count_ = 0;
134 bool mouse_captured =
false;
135 bool previous_frame_resized_ =
false;
137 bool frame_valid_ =
false;
141 PreviousFrame previous_frame_;
144 std::vector<Element> print_above_;
146 bool force_handle_ctrl_c_ =
true;
147 bool force_handle_ctrl_z_ =
true;
150 int cursor_reset_shape_ = 0;
153 bool handle_piped_input_ =
true;
154 bool is_stdin_a_tty_ =
false;
155 bool is_stdout_a_tty_ =
false;
159 std::string terminal_name_ =
"unknown";
160 int terminal_version_ = 0;
162 std::string terminal_emulator_name_ =
"unknown";
163 std::string terminal_emulator_version_ =
"unknown";
165 std::vector<int> terminal_capabilities_;
169 struct SelectionData {
175 bool operator==(
const SelectionData& other)
const {
176 if (empty && other.empty) {
179 if (empty || other.empty) {
182 return start_x == other.start_x && start_y == other.start_y &&
183 end_x == other.end_x && end_y == other.end_y;
185 bool operator!=(
const SelectionData& other)
const {
186 return !(*
this == other);
189 SelectionData selection_data_;
190 SelectionData selection_data_previous_;
191 std::unique_ptr<Selection> selection_;
192 std::function<void()> selection_on_change_;
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;
203 class ThrottledRequest {
205 ThrottledRequest(App::Internal* internal, std::function<
void()> send)
206 : internal_(internal), send_(std::move(send)) {}
208 void Request(
bool force =
false) {
209 if (!internal_->is_stdin_a_tty_) {
224 const auto now = std::chrono::steady_clock::now();
225 if (now - last_request_time_ < std::chrono::milliseconds(500)) {
237 void OnReply() { pending_request_ =
false; }
239 bool HasPending()
const {
240 if (!pending_request_) {
243 const auto now = std::chrono::steady_clock::now();
244 return now - last_sent_time_ < std::chrono::seconds(5);
249 last_sent_time_ = std::chrono::steady_clock::now();
250 last_request_time_ = last_sent_time_;
251 pending_request_ =
true;
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);
264 ThrottledRequest cursor_position_request;
266 MultiReceiverBuffer<Event> event_buffer;
267 std::unique_ptr<MultiReceiverBuffer<Event>::Receiver> main_loop_receiver;
269 Internal(App* app,
AppDimension dimension,
bool use_alternative_screen);
277 void RunOnce(
const Component& component);
278 void RunOnceBlocking(
Component component);
280 bool HandleSelection(
bool handled, Event event);
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();
295App* g_active_screen =
nullptr;
297std::stack<Closure> on_exit_functions;
300 while (!on_exit_functions.empty()) {
301 on_exit_functions.top()();
302 on_exit_functions.pop();
307const std::string CSI =
"\x1b[";
310const std::string DCS =
"\x1bP";
313const std::string ST =
"\x1b\\";
317const std::string DECRQSS_DECSCUSR = DCS +
"$q q" + ST;
321bool SupportsDECRQSS() {
323 if (std::string_view(
util::GetEnv(
"TERM_PROGRAM")) ==
"Apple_Terminal") {
334enum class DECMode : std::uint16_t {
340 kMouseVt200Highlight = 1001,
342 kMouseBtnEventMouse = 1002,
343 kMouseAnyEvent = 1003,
346 kMouseSgrExtMode = 1006,
347 kMouseUrxvtMode = 1015,
348 kMouseSgrPixelsMode = 1016,
349 kAlternateScreen = 1049,
353enum class DSRMode : std::uint8_t {
357std::string Serialize(
const std::vector<DECMode>& parameters) {
360 for (
const DECMode parameter : parameters) {
364 out += std::to_string(
int(parameter));
371std::string Set(
const std::vector<DECMode>& parameters) {
372 return CSI +
"?" + Serialize(parameters) +
"h";
376std::string Reset(
const std::vector<DECMode>& parameters) {
377 return CSI +
"?" + Serialize(parameters) +
"l";
381std::string DeviceStatusReport(DSRMode ps) {
382 return CSI + std::to_string(
int(ps)) +
"n";
385class CapturedMouseImpl :
public CapturedMouseInterface {
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;
396 std::function<void(
void)> callback_;
400std::atomic<int> g_signal_exit_count = 0;
401std::atomic<int> g_signal_stop_count = 0;
402std::atomic<int> g_signal_resize_count = 0;
404std::atomic<int> g_signal_exit_count = 0;
409std::atomic<bool> g_terminal_is_raw{
false};
413std::atomic<int> g_last_signal{0};
416using SignalHandler = void (*)(int);
418std::map<int, SignalHandler> g_old_signal_handlers;
421DWORD g_original_stdout_mode = 0;
422DWORD g_original_stdin_mode = 0;
423bool g_has_original_console_mode =
false;
426std::map<int, struct sigaction> g_old_sigactions;
429struct termios g_original_termios;
430bool g_has_original_termios =
false;
436void RestoreSignalHandlerAndRaise(
int signal) {
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);
442 auto it = g_old_sigactions.find(signal);
443 if (it != g_old_sigactions.end()) {
444 sigaction(signal, &it->second,
nullptr);
447 sa.sa_handler = SIG_DFL;
448 sigemptyset(&sa.sa_mask);
450 sigaction(signal, &sa,
nullptr);
458void RestoreTerminalEmergency() {
459 if (!g_terminal_is_raw.exchange(
false)) {
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);
470 if (g_has_original_termios && g_tty_fd >= 0) {
471 const char restore_seq[] =
480 std::ignore = write(STDOUT_FILENO, restore_seq,
sizeof(restore_seq) - 1);
481 tcsetattr(g_tty_fd, TCSANOW, &g_original_termios);
487void RecordSignal(
int signal) {
504 RestoreTerminalEmergency();
505 RestoreSignalHandlerAndRaise(signal);
519 g_last_signal.store(signal);
520 g_signal_exit_count++;
526 g_signal_stop_count++;
531 g_signal_resize_count++;
540void ExecuteSignalHandlers() {
541 if (g_last_signal.load() != 0) {
542 App::Private::Signal(*g_active_screen, SIGABRT);
545 int signal_exit_count = g_signal_exit_count.exchange(0);
546 while (signal_exit_count--) {
547 App::Private::Signal(*g_active_screen, SIGABRT);
551 int signal_stop_count = g_signal_stop_count.exchange(0);
552 while (signal_stop_count--) {
553 App::Private::Signal(*g_active_screen, SIGTSTP);
556 int signal_resize_count = g_signal_resize_count.exchange(0);
557 while (signal_resize_count--) {
558 App::Private::Signal(*g_active_screen, SIGWINCH);
563void InstallSignalHandler(
int sig) {
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); });
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); });
583App::Internal::Internal(App* app,
585 bool use_alternative_screen)
587 dimension_(dimension),
588 use_alternative_screen_(use_alternative_screen),
589 terminal_input_parser([&](Event event) {
590 event_buffer.Push(std::move(event));
592 cursor_position_request(
this, [
this] {
593 TerminalSend(DeviceStatusReport(DSRMode::kCursor));
595 main_loop_receiver = event_buffer.CreateReceiver();
598void App::Internal::ExitNow() {
602void App::Internal::Install() {
603 frame_valid_ =
false;
604 previous_frame_ = PreviousFrame();
613 InstallPipedInputHandling();
617 on_exit_functions.emplace([
this] { TerminalFlush(); });
621 for (
const int signal : {SIGTERM, SIGSEGV, SIGINT, SIGILL, SIGABRT, SIGFPE}) {
622 InstallSignalHandler(signal);
628 auto stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
629 auto stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
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); });
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;
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;
657 SetConsoleMode(stdin_handle, in_mode);
658 SetConsoleMode(stdout_handle, out_mode);
660 for (
const int signal :
661 {SIGWINCH, SIGTSTP, SIGBUS, SIGSYS, SIGQUIT, SIGHUP}) {
662 InstallSignalHandler(signal);
665 struct termios terminal;
666 tcgetattr(tty_fd_, &terminal);
667 g_original_termios = terminal;
669 g_has_original_termios =
true;
670 on_exit_functions.emplace([terminal = terminal, tty_fd_ = tty_fd_] {
671 tcsetattr(tty_fd_, TCSANOW, &terminal);
675 terminal.c_iflag &= ~IGNBRK;
676 terminal.c_iflag &= ~BRKINT;
678 terminal.c_iflag &= ~PARMRK;
679 terminal.c_iflag &= ~ISTRIP;
680 terminal.c_iflag &= ~INLCR;
681 terminal.c_iflag &= ~IGNCR;
682 terminal.c_iflag &= ~ICRNL;
683 terminal.c_iflag &= ~IXON;
685 terminal.c_lflag &= ~ECHO;
686 terminal.c_lflag &= ~ECHONL;
687 terminal.c_lflag &= ~ICANON;
688 terminal.c_lflag &= ~ISIG;
693 terminal.c_lflag &= ~IEXTEN;
694 terminal.c_cflag |= CS8;
696 terminal.c_cc[VMIN] = 0;
698 terminal.c_cc[VTIME] = 0;
700 tcsetattr(tty_fd_, TCSANOW, &terminal);
704 auto enable = [&](
const std::vector<DECMode>& parameters) {
705 TerminalSend(Set(parameters));
706 on_exit_functions.emplace(
707 [
this, parameters] { TerminalSend(Reset(parameters)); });
710 auto disable = [&](
const std::vector<DECMode>& parameters) {
711 TerminalSend(Reset(parameters));
712 on_exit_functions.emplace(
713 [
this, parameters] { TerminalSend(Set(parameters)); });
716 if (use_alternative_screen_) {
718 DECMode::kAlternateScreen,
727 enable({DECMode::kMouseVt200});
728 enable({DECMode::kMouseAnyEvent});
729 enable({DECMode::kMouseUrxvtMode});
730 enable({DECMode::kMouseSgrExtMode});
737 InstallTerminalInfo();
744 g_terminal_is_raw =
true;
747void App::Internal::Uninstall() {
748 g_terminal_is_raw =
false;
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();
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();
768 task_runner.RunUntilIdle();
770 if (std::chrono::steady_clock::now() - start >
771 std::chrono::milliseconds(400)) {
774 std::this_thread::sleep_for(std::chrono::milliseconds(10));
781void App::Internal::PreMain() {
783 if (g_active_screen) {
784 std::swap(suspended_screen_, g_active_screen);
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,
793 suspended_screen_->dimx_ = 0;
794 suspended_screen_->dimy_ = 0;
798 suspended_screen_->internal_->Uninstall();
806 g_active_screen = public_;
807 g_active_screen->internal_->Install();
809 previous_animation_time_ = animation::Clock::now();
812void App::Internal::PostMain() {
814 TerminalSend(ResetCursorPosition());
816 g_active_screen =
nullptr;
819 if (suspended_screen_) {
821 if (frame_count_ != 0) {
822 public_->ResetPosition(output_buffer,
true);
827 std::swap(g_active_screen, suspended_screen_);
828 g_active_screen->internal_->Install();
835 if (!use_alternative_screen_) {
838 std::cout << std::flush;
841 int sig = g_last_signal.exchange(0);
843 RestoreSignalHandlerAndRaise(sig);
847bool App::Internal::HasQuitted() {
851void App::Internal::RunOnce(
const Component& component) {
852 const AutoReset set_component(&component_, component);
853 ExecuteSignalHandlers();
854 FetchTerminalEvents();
856 while (!quit_ && main_loop_receiver->Has()) {
857 public_->Post(main_loop_receiver->Pop());
861 const size_t executed_task = task_runner.ExecutedTasks();
862 task_runner.RunUntilIdle();
864 if (executed_task == task_runner.ExecutedTasks()) {
868 ExecuteSignalHandlers();
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);
880void App::Internal::RunOnceBlocking(
Component component) {
882 const auto time_per_frame = std::chrono::microseconds(16666);
884 auto time = std::chrono::steady_clock::now();
885 const size_t executed_task = task_runner.ExecutedTasks();
888 while (executed_task == task_runner.ExecutedTasks() && !HasQuitted()) {
891 const auto now = std::chrono::steady_clock::now();
892 const auto delta = now - time;
895 if (delta < time_per_frame) {
896 const auto sleep_duration = time_per_frame - delta;
897 std::this_thread::sleep_for(sleep_duration);
902void App::Internal::HandleTask(
Component component,
Task& task) {
905 using T = std::decay_t<
decltype(arg)>;
909 if constexpr (std::is_same_v<T, Event>) {
911 if (arg.is_cursor_position()) {
912 cursor_x_ = arg.cursor_x();
913 cursor_y_ = arg.cursor_y();
914 cursor_position_request.OnReply();
918 if (arg.is_cursor_shape()) {
919 cursor_reset_shape_ = arg.cursor_shape();
923 if (arg.IsTerminalCapabilities()) {
924 terminal_capabilities_ = arg.TerminalCapabilities();
928 if (arg.IsTerminalNameVersion()) {
929 terminal_name_ = arg.TerminalName();
930 terminal_version_ = arg.TerminalVersion();
934 if (arg.IsTerminalEmulator()) {
935 terminal_emulator_name_ = arg.TerminalEmulatorName();
936 terminal_emulator_version_ = arg.TerminalEmulatorVersion();
940 if (arg.is_mouse()) {
941 arg.mouse().x -= cursor_x_;
942 arg.mouse().y -= cursor_y_;
945 arg.screen_ = public_;
947 bool handled = component->OnEvent(arg);
948 handled = HandleSelection(handled, arg);
950 if (arg == Event::CtrlC && (!handled || force_handle_ctrl_c_)) {
951 RecordSignal(SIGINT);
955 if (arg == Event::CtrlZ && (!handled || force_handle_ctrl_z_)) {
956 RecordSignal(SIGTSTP);
960 frame_valid_ =
false;
965 if constexpr (std::is_same_v<T, Closure>) {
971 if constexpr (std::is_same_v<T, AnimationTask>) {
972 if (!animation_requested_) {
976 animation_requested_ =
false;
979 previous_animation_time_ = now;
981 animation::Params params(delta);
982 component->OnAnimation(params);
983 frame_valid_ =
false;
991bool App::Internal::HandleSelection(
bool handled, Event event) {
993 selection_pending_ =
nullptr;
994 selection_data_.empty =
true;
995 selection_ =
nullptr;
999 if (!event.is_mouse()) {
1003 auto& mouse =
event.mouse();
1004 if (mouse.button != Mouse::Left) {
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;
1017 if (!selection_pending_) {
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;
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;
1043void App::Internal::Draw(
Component component) {
1047 auto document = component->Render();
1051 document->ComputeRequirement();
1052 switch (dimension_) {
1054 dimx = public_->dimx_;
1055 dimy = public_->dimy_;
1058 dimx = terminal.dimx;
1059 dimy =
util::clamp(document->requirement().min_y, 0, terminal.dimy);
1062 dimx = terminal.dimx;
1063 dimy = terminal.dimy;
1066 dimx =
util::clamp(document->requirement().min_x, 0, terminal.dimx);
1067 dimy =
util::clamp(document->requirement().min_y, 0, terminal.dimy);
1072 TerminalSend(
"\033[?25l");
1074 const bool resized =
1075 frame_count_ == 0 || (dimx != public_->dimx_) || (dimy != public_->dimy_);
1077 const bool update_in_place = !resized && print_above_.empty();
1078 TerminalSend(ResetCursorPosition());
1080 if (frame_count_ != 0) {
1085 public_->ResetPosition(output_buffer, resized || !print_above_.empty());
1089 if ((dimx < public_->dimx_) && !use_alternative_screen_) {
1090 TerminalSend(
"\033[J");
1091 TerminalSend(
"\033[H");
1097 for (
auto&
element : print_above_) {
1099 Dimension::Fit(
element,
true).dimy;
1100 Screen screen(terminal.dimx, height);
1102 screen.ToString(output_buffer);
1103 TerminalSend(
"\r\n");
1105 print_above_.clear();
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);
1122 if (!use_alternative_screen_ && is_stdout_a_tty_) {
1123 RequestCursorPosition(previous_frame_resized_);
1125 previous_frame_resized_ = resized;
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_);
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;
1140 set_cursor_position_.clear();
1141 reset_cursor_position_.clear();
1144 set_cursor_position_ +=
"\x1B[" + std::to_string(dy) +
"A";
1145 reset_cursor_position_ +=
"\x1B[" + std::to_string(dy) +
"B";
1149 set_cursor_position_ +=
"\x1B[" + std::to_string(dx) +
"D";
1150 reset_cursor_position_ +=
"\x1B[" + std::to_string(dx) +
"C";
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";
1160 if (update_in_place) {
1161 public_->ToString(output_buffer, previous_frame_);
1163 public_->ToString(output_buffer);
1165 TerminalSend(set_cursor_position_);
1168 previous_frame_.Swap(public_->cells_, public_->hyperlinks_, public_->dimx_,
1170 public_->cells_.resize(
static_cast<size_t>(public_->dimx_) *
1171 static_cast<size_t>(public_->dimy_));
1173 frame_valid_ =
true;
1177std::string App::Internal::ResetCursorPosition() {
1178 std::string result = std::move(reset_cursor_position_);
1179 reset_cursor_position_ =
"";
1183void App::Internal::RequestCursorPosition(
bool force) {
1184 cursor_position_request.Request(force);
1187void App::Internal::TerminalSend(std::string_view s) {
1191void App::Internal::TerminalFlush() {
1193 output_buffer +=
'\0';
1194 std::cout << output_buffer << std::flush;
1195 output_buffer.clear();
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));
1208 tty_fd_ = STDIN_FILENO;
1209 is_stdout_a_tty_ = isatty(STDOUT_FILENO);
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;
1219 tty_fd_ = open(
"/dev/tty", O_RDONLY);
1222 tty_fd_ = STDIN_FILENO;
1223 is_stdin_a_tty_ = isatty(STDIN_FILENO);
1225 is_stdin_a_tty_ =
true;
1227 on_exit_functions.emplace([
this] {
1236void App::Internal::InstallTerminalInfo() {
1239 if (is_stdout_a_tty_) {
1240 if (SupportsDECRQSS()) {
1241 TerminalSend(DECRQSS_DECSCUSR);
1243 TerminalSend(
"\033[>q");
1244 TerminalSend(
"\033[>c");
1245 TerminalSend(
"\033[c");
1250 if (is_stdin_a_tty_ && is_stdout_a_tty_) {
1254 auto setup_receiver = event_buffer.CreateReceiver();
1255 auto start = std::chrono::steady_clock::now();
1256 bool terminal_capabilities_received =
false;
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();
1266 if (event.IsTerminalCapabilities()) {
1267 terminal_capabilities_ =
event.TerminalCapabilities();
1268 terminal_capabilities_received =
true;
1271 if (event.IsTerminalNameVersion()) {
1272 terminal_name_ =
event.TerminalName();
1273 terminal_version_ =
event.TerminalVersion();
1276 if (event.IsTerminalEmulator()) {
1277 terminal_emulator_name_ =
event.TerminalEmulatorName();
1278 terminal_emulator_version_ =
event.TerminalEmulatorVersion();
1285 if (terminal_capabilities_received) {
1289 if (std::chrono::steady_clock::now() - start >
1290 std::chrono::milliseconds(500)) {
1293 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1302 util::GetEnv(
"TERM_PROGRAM"), terminal_name_, terminal_emulator_name_,
1303 terminal_capabilities_);
1305 quirks.SetColorSupport(color_support);
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_) {
1313 reports_utf8 =
true;
1324 bool modern = is_modern_emulator || is_vt220_plus || reports_utf8;
1326 quirks.SetBlockCharacters(
true);
1327 quirks.SetCursorHiding(
true);
1328 quirks.SetComponentAscii(
false);
1333 on_exit_functions.emplace([
this] {
1334 TerminalSend(
"\033[?25h");
1335 if (is_stdout_a_tty_) {
1336 TerminalSend(
"\033[" + std::to_string(cursor_reset_shape_) +
" q");
1341void App::Internal::Signal(
int signal) {
1342 if (signal == SIGABRT) {
1349 if (signal == SIGTSTP) {
1351 TerminalSend(ResetCursorPosition());
1352 public_->ResetPosition(output_buffer,
true);
1356 (void)std::raise(SIGTSTP);
1362 if (signal == SIGWINCH) {
1363 public_->Post(Event::Special({0}));
1369size_t App::Internal::FetchTerminalEvents() {
1371 auto get_input_records = [&]() -> std::vector<INPUT_RECORD> {
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>();
1378 if (number_of_events <= 0) {
1380 return std::vector<INPUT_RECORD>();
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>();
1389 records.resize(number_of_events_read);
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);
1401 last_char_time = std::chrono::steady_clock::now();
1406 std::wstring wstring;
1407 for (
const auto& r : records) {
1408 switch (r.EventType) {
1410 auto key_event = r.Event.KeyEvent;
1412 if (key_event.bKeyDown == FALSE) {
1415 const wchar_t wc = key_event.uChar.UnicodeChar;
1417 if (wc >= 0xd800 && wc <= 0xdbff) {
1422 terminal_input_parser.Add(it);
1426 case WINDOW_BUFFER_SIZE_EVENT:
1427 public_->Post(Event::Special({0}));
1436 return records.size();
1437#elif defined(__EMSCRIPTEN__)
1440 std::array<char, 4096> out{};
1441 const ssize_t l = read(STDIN_FILENO, out.data(), out.size());
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);
1449 last_char_time = std::chrono::steady_clock::now();
1452 for (ssize_t i = 0; i < l; ++i) {
1453 terminal_input_parser.Add(out.at(
static_cast<size_t>(i)));
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));
1466 last_char_time = std::chrono::steady_clock::now();
1471 constexpr size_t kMaxBytesPerFetch = 64 * 1024;
1472 std::array<char, 4096> out{};
1474 while (total < kMaxBytesPerFetch) {
1475 const ssize_t l = read(tty_fd_, out.data(), out.size());
1481 for (ssize_t i = 0; i < l; ++i) {
1482 terminal_input_parser.Add(out.at(
static_cast<size_t>(i)));
1484 total +=
static_cast<size_t>(l);
1487 if (poll(&pfd, 1, 0) <= 0) {
1495void App::Internal::PostAnimationTask() {
1496 public_->Post(AnimationTask());
1500 task_runner.PostDelayedTask([
this] { PostAnimationTask(); },
1501 std::chrono::milliseconds(15));
1504App::App(std::unique_ptr<Internal> internal,
int dimx,
int dimy)
1505 : Screen(dimx, dimy), internal_(std::move(internal)) {
1506 internal_->public_ =
this;
1509App::App(App&& other) noexcept : Screen(std::move(other)) {
1510 internal_ = std::move(other.internal_);
1512 internal_->public_ =
this;
1516App& App::operator=(App&& other)
noexcept {
1517 Screen::operator=(std::move(other));
1518 internal_ = std::move(other.internal_);
1520 internal_->public_ =
this;
1525App::~App() =
default;
1528App App::FixedSize(
int dimx,
int dimy) {
1531 return App(std::move(internal), dimx, dimy);
1535App App::Fullscreen() {
1536 return FullscreenAlternateScreen();
1540App App::FullscreenPrimaryScreen() {
1544 return App(std::move(internal), terminal.dimx, terminal.dimy);
1548App App::FullscreenAlternateScreen() {
1552 return App(std::move(internal), terminal.dimx, terminal.dimy);
1556App App::FitComponent() {
1560 return App(std::move(internal), terminal.dimx, terminal.dimy);
1564App App::TerminalOutput() {
1568 return App(std::move(internal), terminal.dimx, terminal.dimy);
1571void App::TrackMouse(
bool enable) {
1572 internal_->track_mouse_ = enable;
1575void App::HandlePipedInput(
bool enable) {
1576 internal_->handle_piped_input_ = enable;
1581 return g_active_screen;
1585 class Loop loop(this, std::move(component));
1590 Post([
this] { internal_->ExitNow(); });
1593Closure App::ExitLoopClosure() {
1594 return [
this] { Exit(); };
1599 internal_->print_above_.push_back(
element);
1600 internal_->frame_valid_ =
false;
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);
1612 if (std::holds_alternative<Closure>(task)) {
1613 std::get<Closure>(task)();
1618void App::PostEvent(Event event) {
1621 Post(
Task(std::move(event)));
1625void App::PostEventOrExecute(
Closure closure) {
1629 if (
auto* app = App::Active()) {
1630 app->Post(std::move(closure));
1636void App::RequestAnimationFrame() {
1637 if (internal_->animation_requested_) {
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;
1649 if (internal_->mouse_captured) {
1652 internal_->mouse_captured =
true;
1653 return std::make_unique<CapturedMouseImpl>(
1654 [
this] { internal_->mouse_captured =
false; });
1659 internal_->Uninstall();
1661 internal_->Install();
1665void App::ForceHandleCtrlC(
bool force) {
1666 internal_->force_handle_ctrl_c_ = force;
1669void App::ForceHandleCtrlZ(
bool force) {
1670 internal_->force_handle_ctrl_z_ = force;
1673std::string App::GetSelection() {
1674 if (!internal_->selection_) {
1677 return internal_->selection_->GetParts();
1680void App::SelectionChange(std::function<
void()> callback) {
1681 internal_->selection_on_change_ = std::move(callback);
1684const std::string& App::TerminalName()
const {
1685 return internal_->terminal_name_;
1688int App::TerminalVersion()
const {
1689 return internal_->terminal_version_;
1692const std::string& App::TerminalEmulatorName()
const {
1693 return internal_->terminal_emulator_name_;
1696const std::string& App::TerminalEmulatorVersion()
const {
1697 return internal_->terminal_emulator_version_;
1700const std::vector<int>& App::TerminalCapabilities()
const {
1701 return internal_->terminal_capabilities_;
1704std::vector<std::string> App::TerminalCapabilityNames()
const {
1705 return Event::TerminalCapabilities(
"", internal_->terminal_capabilities_)
1706 .TerminalCapabilityNames();
1711void App::ExitNow() {
1712 internal_->ExitNow();
1714void App::Install() {
1715 internal_->Install();
1717void App::Uninstall() {
1718 internal_->Uninstall();
1720void App::PreMain() {
1721 internal_->PreMain();
1723void App::PostMain() {
1724 internal_->PostMain();
1726bool App::HasQuitted() {
1727 return internal_->HasQuitted();
1729void App::RunOnce(
const Component& component) {
1730 internal_->RunOnce(component);
1732void App::RunOnceBlocking(
Component component) {
1733 internal_->RunOnceBlocking(component);
1736 internal_->HandleTask(component, task);
1738bool App::HandleSelection(
bool handled, Event event) {
1739 return internal_->HandleSelection(handled, event);
1742 internal_->Draw(component);
1744std::string App::ResetCursorPosition() {
1745 return internal_->ResetCursorPosition();
1747void App::RequestCursorPosition(
bool force) {
1748 internal_->RequestCursorPosition(force);
1750void App::TerminalSend(std::string_view s) {
1751 internal_->TerminalSend(s);
1753void App::TerminalFlush() {
1754 internal_->TerminalFlush();
1756void App::InstallPipedInputHandling() {
1757 internal_->InstallPipedInputHandling();
1759void App::InstallTerminalInfo() {
1760 internal_->InstallTerminalInfo();
1762void App::Signal(
int signal) {
1763 internal_->Signal(signal);
1765size_t App::FetchTerminalEvents() {
1766 return internal_->FetchTerminalEvents();
1768void App::PostAnimationTask() {
1769 internal_->PostAnimationTask();
1772Loop::Loop(App* screen,
Component component)
1773 : screen_(screen), component_(std::move(component)) {
1778 screen_->PostMain();
1781bool Loop::HasQuitted() {
1782 return screen_->HasQuitted();
1785void Loop::RunOnce() {
1786 screen_->RunOnce(component_);
1789void Loop::RunOnceBlocking() {
1790 screen_->RunOnceBlocking(component_);
1794 while (!HasQuitted()) {
Quirks GetQuirks()
Get the terminal quirks.
Dimensions Size()
Get the terminal size.
void SetQuirks(const Quirks &quirks)
Override terminal quirks.
The FTXUI ftxui::animation:: namespace.
void SetFallbackSize(const Dimensions &fallbackSize)
Override terminal size in case auto-detection fails.
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.
std::chrono::duration< float > Duration
std::chrono::time_point< Clock > TimePoint
void RequestAnimationFrame()
const char * GetEnv(const char *name)
constexpr const T & clamp(const T &v, const T &lo, const T &hi)
The FTXUI ftxui:: namespace.
std::unique_ptr< CapturedMouseInterface > CapturedMouse
std::shared_ptr< Node > Element
std::string to_string(std::wstring_view s)
Convert a std::wstring into a UTF8 std::string.
std::variant< Event, Closure, AnimationTask > Task
void Render(Screen &screen, Node *node, Selection &selection)
std::function< void()> Closure
std::shared_ptr< ComponentBase > Component