interface/terminal_backend.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "terminal_backend.hpp" | ||
| 2 | #include "utils/exit_request.hpp" | ||
| 3 | #include <chrono> | ||
| 4 | #include <csignal> | ||
| 5 | #include <cstdlib> | ||
| 6 | #include <cstring> | ||
| 7 | #include <iostream> | ||
| 8 | #include <locale> | ||
| 9 | #include <ncurses.h> | ||
| 10 | #include <sstream> | ||
| 11 | #include <stdexcept> | ||
| 12 | #include <utility> | ||
| 13 | |||
| 14 | std::atomic<bool> TerminalBackend::interrupt_flag{false}; | ||
| 15 | std::atomic<bool> TerminalBackend::resize_flag{false}; | ||
| 16 | |||
| 17 | static_assert(std::atomic<bool>::is_always_lock_free, "std::atomic<bool> must be lock-free for use in signal handlers"); | ||
| 18 | |||
| 19 | /** | ||
| 20 | * Semantic color pair identifiers for terminal UI rendering. | ||
| 21 | * | ||
| 22 | * Defines named color pair constants for consistent theming across the application. | ||
| 23 | * Each constant maps to an ncurses color pair ID, enabling semantic color assignment | ||
| 24 | * for different UI contexts and message types. Values range from 1 to 9, matching | ||
| 25 | * ncurses color pair initialization indices. | ||
| 26 | * | ||
| 27 | * - DEFAULT_PAIR: Standard text color for neutral content | ||
| 28 | * - HIGHLIGHT_PAIR: Emphasis color for selected or important items | ||
| 29 | * - SUCCESS_PAIR: Color for successful operations or positive messages | ||
| 30 | * - WARNING_PAIR: Color for cautionary messages or non-critical issues | ||
| 31 | * - ERROR_PAIR: Color for error messages and critical failures | ||
| 32 | * - INFO_PAIR: Color for informational messages | ||
| 33 | * - MUTED_PAIR: Subdued color for de-emphasized content | ||
| 34 | * - ACCENT_PAIR: Decorative color for visual variety and UI separation | ||
| 35 | * - FOCUS_PAIR: Color for focused or active UI elements | ||
| 36 | */ | ||
| 37 | enum ColorPair { | ||
| 38 | DEFAULT_PAIR = 1, | ||
| 39 | HIGHLIGHT_PAIR = 2, | ||
| 40 | SUCCESS_PAIR = 3, | ||
| 41 | WARNING_PAIR = 4, | ||
| 42 | ERROR_PAIR = 5, | ||
| 43 | INFO_PAIR = 6, | ||
| 44 | MUTED_PAIR = 7, | ||
| 45 | ACCENT_PAIR = 8, | ||
| 46 | FOCUS_PAIR = 9 | ||
| 47 | }; | ||
| 48 | |||
| 49 | /** | ||
| 50 | * Initializes ncurses color pairs with a dark theme color scheme. | ||
| 51 | * | ||
| 52 | * Enables ncurses color support via start_color(), allows the terminal's default | ||
| 53 | * background color to be used via use_default_colors(), and defines all ColorPair | ||
| 54 | * color pair constants with semantic foreground/background combinations. | ||
| 55 | * | ||
| 56 | * Most pairs use -1 as background, preserving the terminal's default background | ||
| 57 | * color. HIGHLIGHT_PAIR uses black text on white background for strong contrast, | ||
| 58 | * and FOCUS_PAIR uses white text on blue background for focused element visibility. | ||
| 59 | * | ||
| 60 | * This method should be called early during TerminalBackend initialization, before | ||
| 61 | * any colored text is rendered to the terminal. | ||
| 62 | */ | ||
| 63 | ✗ | void TerminalBackend::init_dark_theme(void) { | |
| 64 | ✗ | start_color(); | |
| 65 | ✗ | use_default_colors(); | |
| 66 | |||
| 67 | // Purpose | Foreground | Background | ||
| 68 | ✗ | init_pair(DEFAULT_PAIR, COLOR_WHITE, -1); | |
| 69 | ✗ | init_pair(HIGHLIGHT_PAIR, COLOR_BLACK, COLOR_WHITE); | |
| 70 | ✗ | init_pair(SUCCESS_PAIR, COLOR_GREEN, -1); | |
| 71 | ✗ | init_pair(WARNING_PAIR, COLOR_YELLOW, -1); | |
| 72 | ✗ | init_pair(ERROR_PAIR, COLOR_RED, -1); | |
| 73 | ✗ | init_pair(INFO_PAIR, COLOR_CYAN, -1); | |
| 74 | ✗ | init_pair(ACCENT_PAIR, COLOR_MAGENTA, -1); | |
| 75 | ✗ | init_pair(FOCUS_PAIR, COLOR_WHITE, COLOR_BLUE); | |
| 76 | ✗ | } | |
| 77 | |||
| 78 | /** | ||
| 79 | * Initializes ncurses color pairs with a light theme color scheme. | ||
| 80 | * | ||
| 81 | * Enables ncurses color support via start_color(), allows the terminal's default | ||
| 82 | * background color to be used via use_default_colors(), and defines all ColorPair | ||
| 83 | * color pair constants with semantic foreground/background combinations optimized | ||
| 84 | * for light terminal backgrounds. | ||
| 85 | * | ||
| 86 | * Unlike the dark theme, most pairs use white backgrounds for contrast against | ||
| 87 | * darker text. DEFAULT_PAIR uses black text on white for standard content, and | ||
| 88 | * HIGHLIGHT_PAIR inverts to white text on black for strong emphasis. FOCUS_PAIR | ||
| 89 | * uses black text on cyan background for focused element visibility. | ||
| 90 | * | ||
| 91 | * This method should be called early during TerminalBackend initialization, before | ||
| 92 | * any colored text is rendered to the terminal. Select init_dark_theme() or | ||
| 93 | * init_light_theme() based on the user's terminal background preference. | ||
| 94 | */ | ||
| 95 | ✗ | void TerminalBackend::init_light_theme(void) { | |
| 96 | ✗ | start_color(); | |
| 97 | ✗ | use_default_colors(); | |
| 98 | |||
| 99 | // Purpose | Foreground | Background | ||
| 100 | ✗ | init_pair(DEFAULT_PAIR, COLOR_BLACK, COLOR_WHITE); | |
| 101 | ✗ | init_pair(HIGHLIGHT_PAIR, COLOR_WHITE, COLOR_BLACK); | |
| 102 | ✗ | init_pair(SUCCESS_PAIR, COLOR_GREEN, COLOR_WHITE); | |
| 103 | ✗ | init_pair(WARNING_PAIR, COLOR_YELLOW, COLOR_WHITE); | |
| 104 | ✗ | init_pair(ERROR_PAIR, COLOR_RED, COLOR_WHITE); | |
| 105 | ✗ | init_pair(INFO_PAIR, COLOR_BLUE, COLOR_WHITE); | |
| 106 | ✗ | init_pair(ACCENT_PAIR, COLOR_MAGENTA, COLOR_WHITE); | |
| 107 | ✗ | init_pair(FOCUS_PAIR, COLOR_BLACK, COLOR_CYAN); | |
| 108 | ✗ | } | |
| 109 | |||
| 110 | /** | ||
| 111 | * Initializes the ncurses terminal UI with locale support, terminal configuration, color theming, and signal handling. | ||
| 112 | * | ||
| 113 | * Sets the locale to UTF-8 for character encoding support and establishes TERMINFO fallback to the system | ||
| 114 | * terminfo database if not already set (handles Conan ncurses builds). Initializes ncurses with initscr(), | ||
| 115 | * terminating with error diagnostics on failure. Updates window layout via update_layout(). | ||
| 116 | * | ||
| 117 | * Configures terminal I/O: enables cbreak mode (immediate input) and disables echo. Attempts to enable | ||
| 118 | * function key and arrow key support via keypad(); non-fatal warning if unsupported. Sets input blocking | ||
| 119 | * mode (getch() waits for user input). Attempts to hide the cursor; non-fatal warning if unsupported. | ||
| 120 | * | ||
| 121 | * If the terminal supports colors, initializes color pairs by calling init_dark_theme() or init_light_theme() | ||
| 122 | * based on the use_dark_theme flag, and sets the terminal background to DEFAULT_PAIR. Registers SIGWINCH | ||
| 123 | * signal handler for terminal window resize detection and SIGINT handler for interrupt cleanup. | ||
| 124 | * | ||
| 125 | * Terminates the program on critical failures (initscr failure or terminal setup failure). | ||
| 126 | * Non-critical feature failures (keypad, cursor hiding) produce warnings but do not halt initialization. | ||
| 127 | */ | ||
| 128 | ✗ | void TerminalBackend::init_ncurses(void) { | |
| 129 | ✗ | std::string message{}; | |
| 130 | |||
| 131 | // Set up locale for UTF-8 support. | ||
| 132 | ✗ | setlocale(LC_ALL, ""); | |
| 133 | |||
| 134 | // Set TERMINFO to system database if Conan ncurses can't find it. | ||
| 135 | ✗ | if (!std::getenv("TERMINFO")) { | |
| 136 | ✗ | setenv("TERMINFO", "/usr/share/terminfo", 0); | |
| 137 | } | ||
| 138 | |||
| 139 | // Initialize ncurses. | ||
| 140 | ✗ | const WINDOW* w = initscr(); | |
| 141 | ✗ | if (!w) { | |
| 142 | ✗ | const char* term = getenv("TERM"); | |
| 143 | ✗ | fprintf(stderr, "Failed to initialize ncurses with TERM=%s\n", term ? term : "unset"); | |
| 144 | ✗ | throw ExitRequest{EXIT_FAILURE}; | |
| 145 | } | ||
| 146 | |||
| 147 | ✗ | this->update_layout(); | |
| 148 | |||
| 149 | // Setup terminal. | ||
| 150 | ✗ | if (cbreak() == ERR || noecho() == ERR) { | |
| 151 | ✗ | endwin(); | |
| 152 | ✗ | fprintf(stderr, "Terminal setup failed\n"); | |
| 153 | ✗ | throw ExitRequest{EXIT_FAILURE}; | |
| 154 | } | ||
| 155 | |||
| 156 | // Enable function keys and arrow keys. | ||
| 157 | ✗ | if (keypad(stdscr, TRUE) == ERR) { | |
| 158 | ✗ | fprintf(stderr, "Warning: keypad() not supported\n"); | |
| 159 | } | ||
| 160 | |||
| 161 | // Block on input (getch waits for input). | ||
| 162 | ✗ | nodelay(stdscr, FALSE); | |
| 163 | |||
| 164 | // Cursor hiding (may not be supported). | ||
| 165 | ✗ | if (curs_set(0) == ERR) { | |
| 166 | ✗ | fprintf(stderr, "Warning: cursor control not supported on this terminal\n"); | |
| 167 | } | ||
| 168 | |||
| 169 | ✗ | if (has_colors()) { | |
| 170 | ✗ | if (this->use_dark_theme == true) { | |
| 171 | ✗ | this->init_dark_theme(); | |
| 172 | } else { | ||
| 173 | ✗ | this->init_light_theme(); | |
| 174 | } | ||
| 175 | ✗ | bkgd(COLOR_PAIR(DEFAULT_PAIR)); | |
| 176 | } | ||
| 177 | |||
| 178 | ✗ | this->install_signal_handlers(); | |
| 179 | ✗ | } | |
| 180 | |||
| 181 | ✗ | void TerminalBackend::install_signal_handlers() { | |
| 182 | ✗ | struct sigaction sa {}; | |
| 183 | ✗ | sigemptyset(&sa.sa_mask); | |
| 184 | |||
| 185 | ✗ | sa.sa_handler = TerminalBackend::handle_resize; | |
| 186 | ✗ | sa.sa_flags = SA_RESTART; // don't interrupt getch() just for a resize | |
| 187 | ✗ | sigaction(SIGWINCH, &sa, nullptr); | |
| 188 | |||
| 189 | ✗ | sa.sa_handler = TerminalBackend::handle_interrupt; | |
| 190 | ✗ | sa.sa_flags = 0; // no SA_RESTART, so a blocking read returns EINTR | |
| 191 | ✗ | sigaction(SIGINT, &sa, nullptr); | |
| 192 | ✗ | } | |
| 193 | |||
| 194 | ✗ | void TerminalBackend::handle_resize(int sig) { | |
| 195 | ✗ | TerminalBackend::resize_flag.store(true, std::memory_order_relaxed); | |
| 196 | ✗ | } | |
| 197 | |||
| 198 | ✗ | void TerminalBackend::handle_interrupt(int sig) { | |
| 199 | ✗ | TerminalBackend::interrupt_flag.store(true, std::memory_order_relaxed); | |
| 200 | ✗ | } | |
| 201 | |||
| 202 | /** | ||
| 203 | * Constructs a TerminalBackend instance and initializes member variables. | ||
| 204 | * | ||
| 205 | * Initializes input_cursor_x to 0 (cursor at leftmost position). | ||
| 206 | * Initializes layout struct to default-constructed values (all fields zeroed/default). | ||
| 207 | * Sets use_dark_theme to true, establishing dark theme as the default color scheme preference. | ||
| 208 | * | ||
| 209 | * Note: This constructor performs only member initialization and singleton registration. | ||
| 210 | * Full ncurses initialization (terminal setup, color pair configuration, input handling) is deferred | ||
| 211 | * to init_ncurses(), which must be called explicitly after construction to establish the UI environment. | ||
| 212 | */ | ||
| 213 | ✗ | TerminalBackend::TerminalBackend() : input_cursor_x(0), layout({}), use_dark_theme(true) { | |
| 214 | ✗ | } | |
| 215 | |||
| 216 | /** | ||
| 217 | * Constructs a TerminalBackend instance with a caller-specified color theme preference. | ||
| 218 | * | ||
| 219 | * @param dark_theme: Boolean flag to select color scheme; true for dark theme, false for light theme. | ||
| 220 | * | ||
| 221 | * Initializes input_cursor_x to 0 (cursor at leftmost position). | ||
| 222 | * Initializes layout struct to default-constructed values (all fields zeroed/default). | ||
| 223 | * Sets use_dark_theme to the caller-provided dark_theme value, establishing the preferred | ||
| 224 | * color scheme that will be applied during init_ncurses(). | ||
| 225 | * | ||
| 226 | * Note: This constructor performs only member initialization and singleton registration. | ||
| 227 | * Full ncurses initialization (terminal setup, color pair configuration, input handling) is deferred | ||
| 228 | * to init_ncurses(), which must be called explicitly after construction to establish the UI environment. | ||
| 229 | */ | ||
| 230 | ✗ | TerminalBackend::TerminalBackend(bool dark_theme) : input_cursor_x(0), layout({}), use_dark_theme(dark_theme) { | |
| 231 | ✗ | } | |
| 232 | |||
| 233 | /** | ||
| 234 | * Destroys the TerminalBackend and ends its session if it is still active. | ||
| 235 | * | ||
| 236 | * Calls end_session() with its default exit code. That call stops the render | ||
| 237 | * thread and restores the terminal, but only if terminal_restored has not | ||
| 238 | * already been set. The destructor does not acquire ui_mutex directly. | ||
| 239 | * | ||
| 240 | * @post The render thread has been stopped. | ||
| 241 | * @post The terminal has been restored, and endwin() has run exactly | ||
| 242 | * once across all calls to end_session(). | ||
| 243 | * | ||
| 244 | * @note Destruction always blocks for about one second because end_session() | ||
| 245 | * calls napms(1000) unconditionally, even when the session was already | ||
| 246 | * ended earlier. | ||
| 247 | * @warning Destructors are implicitly noexcept. If end_session() or anything it | ||
| 248 | * calls throws, std::terminate() is called. Call end_session() | ||
| 249 | * explicitly before destruction if a session needs to be ended while | ||
| 250 | * exceptions are still being handled. | ||
| 251 | */ | ||
| 252 | ✗ | TerminalBackend::~TerminalBackend() { | |
| 253 | ✗ | this->end_session(); | |
| 254 | ✗ | } | |
| 255 | |||
| 256 | /** | ||
| 257 | * Ends the terminal session and restores the terminal state. | ||
| 258 | * | ||
| 259 | * The function sleeps for one second, stops the render thread, and then calls | ||
| 260 | * endwin() if the terminal has not been restored yet. The check and | ||
| 261 | * update of terminal_restored use exchange(), so cleanup runs at most once even | ||
| 262 | * if this function is called more than once. | ||
| 263 | * | ||
| 264 | * @post The render thread has been stopped. | ||
| 265 | * @post terminal_restored is true, and endwin() has run exactly once | ||
| 266 | * across all calls. | ||
| 267 | * | ||
| 268 | * @note The call blocks the calling thread for about one second through | ||
| 269 | * napms(1000) before doing anything else. Avoid calling it from a thread | ||
| 270 | * that must respond promptly. | ||
| 271 | */ | ||
| 272 | ✗ | void TerminalBackend::end_session(int code) { | |
| 273 | ✗ | napms(500); | |
| 274 | |||
| 275 | ✗ | this->stop_render_thread(); | |
| 276 | |||
| 277 | ✗ | if (!this->terminal_restored.exchange(true)) { | |
| 278 | ✗ | endwin(); | |
| 279 | } | ||
| 280 | |||
| 281 | ✗ | throw ExitRequest{code}; | |
| 282 | } | ||
| 283 | |||
| 284 | /** | ||
| 285 | * Initializes and starts the TerminalBackend subsystem. | ||
| 286 | * | ||
| 287 | * Performs full initialization pipeline: calls init_ncurses() to set up the ncurses | ||
| 288 | * library, terminal settings, and signal handlers; calls draw_ui() to render the initial | ||
| 289 | * full-terminal Unicode box border; and calls start_render_thread() to spawn the background rendering thread. | ||
| 290 | * | ||
| 291 | * The rendering thread continuously redraws the UI (output area, input area, spinner) | ||
| 292 | * in response to state changes and terminal resize events (resize_flag). | ||
| 293 | * | ||
| 294 | * No parameters; operates on the current TerminalBackend instance state. | ||
| 295 | * | ||
| 296 | * @return void | ||
| 297 | * | ||
| 298 | * Initialization status is communicated via successful completion (or | ||
| 299 | * program termination if init_ncurses() encounters a fatal error). | ||
| 300 | * | ||
| 301 | * Acts as the entry point for the UI system. Should be called once after TerminalBackend | ||
| 302 | * instantiation and before any event processing or input handling. | ||
| 303 | * | ||
| 304 | * Enables the interactive terminal UI with responsive rendering and asynchronous | ||
| 305 | * screen updates via the background thread, while the main thread handles user input | ||
| 306 | * and application logic. | ||
| 307 | */ | ||
| 308 | ✗ | void TerminalBackend::run(void) { | |
| 309 | ✗ | this->init_ncurses(); | |
| 310 | |||
| 311 | ✗ | this->draw_ui(); | |
| 312 | |||
| 313 | ✗ | this->start_render_thread(); | |
| 314 | ✗ | } | |
| 315 | |||
| 316 | /** | ||
| 317 | * Reports whether the backend's thread is currently running. | ||
| 318 | * | ||
| 319 | * The value is read atomically, so this function does not acquire ui_mutex. | ||
| 320 | * The result can become stale as soon as the function returns. | ||
| 321 | * | ||
| 322 | * @return true if the backend thread is running, false otherwise. | ||
| 323 | * | ||
| 324 | * @note Use this for status checks only. Do not use it to decide whether to | ||
| 325 | * start or stop the thread without coordinating through another | ||
| 326 | * synchronization mechanism, because the state can change between the | ||
| 327 | * check and the action. | ||
| 328 | */ | ||
| 329 | ✗ | bool TerminalBackend::is_running() { | |
| 330 | ✗ | return this->thread_running.load(); | |
| 331 | } | ||
| 332 | |||
| 333 | /** | ||
| 334 | * Wakes one or all threads waiting on cv_redraw. | ||
| 335 | * | ||
| 336 | * The function does not acquire ui_mutex and does not modify should_redraw or | ||
| 337 | * any other state. Notifying is the only effect. | ||
| 338 | * | ||
| 339 | * @param all true to wake all waiting threads with notify_all(), false to wake | ||
| 340 | * a single waiting thread with notify_one(). | ||
| 341 | * | ||
| 342 | * @note A waiter that checks a predicate such as should_redraw must update that | ||
| 343 | * predicate before calling this function, or a wakeup can be missed. | ||
| 344 | * @warning Calling this without first changing the state a waiter depends on | ||
| 345 | * can cause a lost wakeup. Waking one thread may also leave other | ||
| 346 | * waiters asleep if they need to act on the same change, so use | ||
| 347 | * all = true when more than one thread might need to respond. | ||
| 348 | */ | ||
| 349 | ✗ | void TerminalBackend::notify_cv_redraw(bool all) { | |
| 350 | ✗ | if (all == true) { | |
| 351 | ✗ | this->cv_redraw.notify_all(); | |
| 352 | } else { | ||
| 353 | ✗ | this->cv_redraw.notify_one(); | |
| 354 | } | ||
| 355 | ✗ | } | |
| 356 | |||
| 357 | /** | ||
| 358 | * Moves the input cursor one column to the left or right. | ||
| 359 | * | ||
| 360 | * Only steps of -1 or +1 are accepted. The function does not check whether the | ||
| 361 | * resulting position is within the bounds of input_buffer, and it does not | ||
| 362 | * acquire ui_mutex. | ||
| 363 | * | ||
| 364 | * @param shift The step to apply to input_cursor_x. Must be -1 or 1. | ||
| 365 | * | ||
| 366 | * @throws std::invalid_argument If shift is any value other than -1 or 1. | ||
| 367 | * | ||
| 368 | * @pre input_cursor_x is within the range [0, input_buffer.length()]. | ||
| 369 | * @post input_cursor_x has been moved by shift. | ||
| 370 | * | ||
| 371 | * @warning The position is not bounds-checked after the shift. Stepping left | ||
| 372 | * at position 0 or right past the end of input_buffer leaves | ||
| 373 | * input_cursor_x out of range, which callers must avoid. | ||
| 374 | * @note Access to input_cursor_x is not synchronized. If another thread reads or | ||
| 375 | * modifies the cursor, the caller must hold ui_mutex. | ||
| 376 | */ | ||
| 377 | ✗ | void TerminalBackend::shift_input_cursor_x(int shift) { | |
| 378 | ✗ | if (shift != -1 && shift != 1) { | |
| 379 | ✗ | throw std::invalid_argument("Cursor x can be shifted by -1 or +1."); | |
| 380 | } | ||
| 381 | ✗ | this->input_cursor_x += shift; | |
| 382 | ✗ | } | |
| 383 | |||
| 384 | /** | ||
| 385 | * Sets the flag that requests a screen redraw. | ||
| 386 | * | ||
| 387 | * The value is stored atomically, so this function does not acquire ui_mutex. | ||
| 388 | * The previous value is discarded. | ||
| 389 | * | ||
| 390 | * @param value true to request a redraw, false to clear the request. | ||
| 391 | * | ||
| 392 | * @note This function does not notify cv_redraw. Setting the flag to true does | ||
| 393 | * not wake a thread waiting on that condition variable, so a waiter may | ||
| 394 | * not see the request until it is woken by another call such as print(). | ||
| 395 | */ | ||
| 396 | ✗ | void TerminalBackend::set_should_redraw(bool value) { | |
| 397 | ✗ | std::lock_guard<std::mutex> lock(this->ui_mutex); | |
| 398 | ✗ | this->should_redraw.store(value); | |
| 399 | ✗ | } | |
| 400 | |||
| 401 | /** | ||
| 402 | * Sets whether the spinner is active. | ||
| 403 | * | ||
| 404 | * The value is stored atomically, so this function does not acquire ui_mutex. | ||
| 405 | * The previous value is discarded. | ||
| 406 | * | ||
| 407 | * @param value true to activate the spinner, false to deactivate it. | ||
| 408 | * | ||
| 409 | * @note This call does not set should_redraw or notify cv_redraw. Callers that | ||
| 410 | * need the spinner change displayed must trigger a redraw separately. | ||
| 411 | */ | ||
| 412 | ✗ | void TerminalBackend::set_spinner_active(bool value) { | |
| 413 | ✗ | std::lock_guard<std::mutex> lock(this->ui_mutex); | |
| 414 | ✗ | this->spinner_active.store(value); | |
| 415 | ✗ | } | |
| 416 | |||
| 417 | /** | ||
| 418 | * Sets the progress percentage shown by the terminal. | ||
| 419 | * | ||
| 420 | * The value is stored atomically, so this function does not acquire ui_mutex. | ||
| 421 | * The previous value is discarded. No range check is performed, so callers | ||
| 422 | * are responsible for passing a meaningful percentage. | ||
| 423 | * | ||
| 424 | * @param value The new progress percentage to store. | ||
| 425 | * | ||
| 426 | * @note Because no lock is taken, a redraw is not triggered by this call. | ||
| 427 | * Callers that need the change displayed must also update output state | ||
| 428 | * and signal cv_redraw through print(). | ||
| 429 | */ | ||
| 430 | ✗ | void TerminalBackend::set_spinner_frame(int value) { | |
| 431 | ✗ | std::lock_guard<std::mutex> lock(this->ui_mutex); | |
| 432 | ✗ | if (value >= 0 && value <= 4) { | |
| 433 | ✗ | this->spinner_frame.store(value); | |
| 434 | } else { | ||
| 435 | ✗ | this->spinner_frame.store((spinner_frame + 1) % 4); | |
| 436 | } | ||
| 437 | ✗ | } | |
| 438 | |||
| 439 | ✗ | void TerminalBackend::set_progress_percent(int value) { | |
| 440 | ✗ | this->progress_percent.store(value); | |
| 441 | ✗ | } | |
| 442 | |||
| 443 | /** | ||
| 444 | * Reports whether the spinner is currently active. | ||
| 445 | * | ||
| 446 | * The value is read atomically, so this function does not acquire ui_mutex. | ||
| 447 | * The result can change immediately after the call returns if another thread | ||
| 448 | * updates spinner_active. | ||
| 449 | * | ||
| 450 | * @return true if the spinner is active, false otherwise. | ||
| 451 | */ | ||
| 452 | ✗ | bool TerminalBackend::get_spinner_active() { | |
| 453 | ✗ | return this->spinner_active.load(); | |
| 454 | } | ||
| 455 | |||
| 456 | /** | ||
| 457 | * Draws the terminal UI frame with a Unicode box border. | ||
| 458 | * | ||
| 459 | * Clears the screen and retrieves the current terminal dimensions (max_y, max_x) via getmaxyx(). | ||
| 460 | * Draws a complete box frame using Unicode box-drawing characters: ╔ and ╗ (top corners), ╚ and ╝ | ||
| 461 | * (bottom corners), ═ (horizontal edges), and ║ (vertical edges). Positions characters using mvprintw() | ||
| 462 | * to create a full-terminal border with proper corner and edge placement. | ||
| 463 | * | ||
| 464 | * Refreshes the display with refresh() to flush buffered output and show the drawn frame on screen. | ||
| 465 | */ | ||
| 466 | ✗ | void TerminalBackend::draw_ui(void) { | |
| 467 | ✗ | clear(); | |
| 468 | |||
| 469 | int max_y; | ||
| 470 | int max_x; | ||
| 471 | ✗ | getmaxyx(stdscr, max_y, max_x); | |
| 472 | |||
| 473 | int i; | ||
| 474 | |||
| 475 | // Top border | ||
| 476 | ✗ | mvprintw(0, 0, "╔"); | |
| 477 | ✗ | for (i = 1; i < max_x - 1; i += 1) { | |
| 478 | ✗ | mvprintw(0, i, "═"); | |
| 479 | } | ||
| 480 | ✗ | mvprintw(0, max_x - 1, "╗"); | |
| 481 | |||
| 482 | // Side borders | ||
| 483 | ✗ | for (i = 1; i < max_y - 1; i += 1) { | |
| 484 | ✗ | mvprintw(i, 0, "║"); | |
| 485 | ✗ | mvprintw(i, max_x - 1, "║"); | |
| 486 | } | ||
| 487 | |||
| 488 | // Bottom border | ||
| 489 | ✗ | mvprintw(max_y - 1, 0, "╚"); | |
| 490 | ✗ | for (i = 1; i < max_x - 1; i += 1) { | |
| 491 | ✗ | mvprintw(max_y - 1, i, "═"); | |
| 492 | } | ||
| 493 | ✗ | mvprintw(max_y - 1, max_x - 1, "╝"); | |
| 494 | |||
| 495 | ✗ | refresh(); | |
| 496 | ✗ | } | |
| 497 | |||
| 498 | /** | ||
| 499 | * Draws an animated spinner with optional progress percentage at the UI layout position. | ||
| 500 | * | ||
| 501 | * Returns early if the spinner is not active. Loads the current animation frame | ||
| 502 | * index and progress percentage from atomic variables (spinner_frame, progress_percent) | ||
| 503 | * in a thread-safe manner. Selects the appropriate spinner character from a rotating set | ||
| 504 | * (|, /, -, \) based on the frame index. | ||
| 505 | * | ||
| 506 | * Enables DEFAULT_PAIR color styling and renders the spinner at the layout-defined position | ||
| 507 | * (layout.spinner_y, layout.spinner_x) using mvprintw(). If progress > 0, displays "X Loading..." | ||
| 508 | * with the progress percentage; otherwise displays "X Loading..." without percentage. Disables color | ||
| 509 | * styling after rendering. | ||
| 510 | * | ||
| 511 | * Thread-safe via atomic variable loads; does not modify shared state. | ||
| 512 | */ | ||
| 513 | ✗ | void TerminalBackend::draw_spinner() { | |
| 514 | ✗ | if (!this->spinner_active.load()) { | |
| 515 | ✗ | return; | |
| 516 | } | ||
| 517 | |||
| 518 | ✗ | const char spinner_chars[] = {'|', '/', '-', '\\'}; | |
| 519 | ✗ | int frame = this->spinner_frame.load(); | |
| 520 | ✗ | int progress = this->progress_percent.load(); | |
| 521 | |||
| 522 | ✗ | attron(COLOR_PAIR(DEFAULT_PAIR)); | |
| 523 | |||
| 524 | ✗ | if (progress > 0) { | |
| 525 | ✗ | mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Progress: %d%%", spinner_chars[frame], progress); | |
| 526 | } else { | ||
| 527 | ✗ | mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Loading...", spinner_chars[frame]); | |
| 528 | } | ||
| 529 | |||
| 530 | ✗ | attroff(COLOR_PAIR(DEFAULT_PAIR)); | |
| 531 | } | ||
| 532 | |||
| 533 | /** | ||
| 534 | * Recalculates UI layout positions and dimensions based on current terminal size. | ||
| 535 | * | ||
| 536 | * Retrieves the current terminal dimensions (max_y, max_x) via getmaxyx() and updates the layout | ||
| 537 | * structure to position UI elements relative to terminal boundaries. Sets status_y to the bottom row | ||
| 538 | * (max_y - 1), input area to max_y - 3 with left margin of 2 columns, and spinner to max_y - 2 | ||
| 539 | * (between input and status rows). Sets output area to start at row 1 (below top border) with height | ||
| 540 | * calculated as the vertical space between output_y and input_y minus one row for spacing. | ||
| 541 | * | ||
| 542 | * Intended to be called during initialization and in response to terminal resize events (SIGWINCH) | ||
| 543 | * to ensure all UI elements remain properly positioned and sized when the terminal is resized. | ||
| 544 | */ | ||
| 545 | ✗ | void TerminalBackend::update_layout() { | |
| 546 | int max_y, max_x; | ||
| 547 | ✗ | getmaxyx(stdscr, max_y, max_x); | |
| 548 | |||
| 549 | ✗ | layout.status_y = max_y - 1; | |
| 550 | ✗ | layout.input_y = max_y - 3; | |
| 551 | ✗ | layout.input_x = 2; | |
| 552 | ✗ | layout.spinner_y = max_y - 2; | |
| 553 | ✗ | layout.spinner_x = 2; | |
| 554 | ✗ | layout.output_y = 1; | |
| 555 | ✗ | layout.output_height = layout.input_y - layout.output_y - 1; | |
| 556 | ✗ | } | |
| 557 | |||
| 558 | /** | ||
| 559 | * Clears the input area rows by overwriting them with spaces. | ||
| 560 | * | ||
| 561 | * Retrieves the current terminal dimensions (max_y, max_x) via getmaxyx(). Erases two rows of the | ||
| 562 | * input area (layout.input_y and layout.input_y + 1) by drawing horizontal lines of spaces from | ||
| 563 | * column 1 to max_x - 2, leaving the left and right borders intact. | ||
| 564 | * | ||
| 565 | * Used to erase previous user input or prompts before rendering new content in the input area. | ||
| 566 | * Maintains visual consistency by preserving the terminal border structure. | ||
| 567 | */ | ||
| 568 | ✗ | void TerminalBackend::clear_input_area() { | |
| 569 | int max_y, max_x; | ||
| 570 | ✗ | getmaxyx(stdscr, max_y, max_x); | |
| 571 | |||
| 572 | ✗ | mvhline(layout.input_y, 1, ' ', max_x - 2); | |
| 573 | ✗ | mvhline(layout.input_y + 1, 1, ' ', max_x - 2); | |
| 574 | ✗ | } | |
| 575 | |||
| 576 | /** | ||
| 577 | * Renders the input prompt and user-typed content in the input area. | ||
| 578 | * | ||
| 579 | * Clears the input area via clear_input_area(). Returns early if the spinner is currently active, | ||
| 580 | * preventing prompt and input display while a background operation (query execution) is in progress. | ||
| 581 | * | ||
| 582 | * When the spinner is inactive, renders a static prompt "⏳ Type your prompt (q/Q to quit): " at | ||
| 583 | * the layout-defined input position (layout.input_y, layout.input_x). Renders the contents of the | ||
| 584 | * input_buffer (user-typed characters) immediately following the prompt text at a fixed column offset | ||
| 585 | * (+37 from input_x). | ||
| 586 | * | ||
| 587 | * Provides visual feedback and instructions to the user while maintaining a clean, non-overlapping | ||
| 588 | * layout during asynchronous spinner operation. | ||
| 589 | */ | ||
| 590 | ✗ | void TerminalBackend::draw_input_area() { | |
| 591 | ✗ | this->clear_input_area(); | |
| 592 | ✗ | if (this->spinner_active.load()) { | |
| 593 | ✗ | return; | |
| 594 | } | ||
| 595 | |||
| 596 | ✗ | mvprintw(layout.input_y, layout.input_x, "⏳ Type your prompt (q/Q to quit): "); | |
| 597 | |||
| 598 | // Draw the actual input buffer that user typed | ||
| 599 | ✗ | mvprintw(layout.input_y, layout.input_x + 37, "%s", input_buffer.c_str()); | |
| 600 | } | ||
| 601 | |||
| 602 | /** | ||
| 603 | * Renders the message output buffer in reverse chronological order (newest first), | ||
| 604 | * from the bottom of the output area upward. | ||
| 605 | * | ||
| 606 | * Clears the entire output area by filling each row with spaces, preserving the border columns. | ||
| 607 | * Iterates backwards through output_buffer, starting from the most recently added message. | ||
| 608 | * For each message, extracts the text content and message type (error/success/default). | ||
| 609 | * | ||
| 610 | * Splits multi-line message text by newline characters. Wraps each logical line at word | ||
| 611 | * boundaries using TextUtils::wrap_text() to fit within max_content_width (COLS - 4). | ||
| 612 | * Renders wrapped lines from bottom to top (reverse order) within the allocated output area, | ||
| 613 | * decrementing current_line after each rendered line. | ||
| 614 | * | ||
| 615 | * Applies semantic color and icon styling based on message type: | ||
| 616 | * - MESSAGE_TYPE_ERROR: bold red (ERROR_PAIR) with ❌ emoji prefix. | ||
| 617 | * - MESSAGE_TYPE_SUCCESS: bold default color with ✅ emoji prefix. | ||
| 618 | * - Default: plain text without icon. | ||
| 619 | * | ||
| 620 | * Breaks iteration early if current_line reaches or falls below layout.output_y (top boundary). | ||
| 621 | * Calls refresh() to update the terminal display. | ||
| 622 | * | ||
| 623 | * Provides a scrollable-like view of the most recent messages within the constrained output area, | ||
| 624 | * with automatic wrapping and visual differentiation for errors and successful operations. | ||
| 625 | */ | ||
| 626 | ✗ | void TerminalBackend::draw_output_area() { | |
| 627 | // Clear the output area | ||
| 628 | ✗ | for (int i = 0; i < layout.output_height; i += 1) { | |
| 629 | ✗ | mvhline(layout.output_y + i, 1, ' ', COLS - 2); | |
| 630 | } | ||
| 631 | |||
| 632 | ✗ | int current_line = layout.input_y - 2; // Start from bottom | |
| 633 | ✗ | int max_content_width = COLS - 4; | |
| 634 | |||
| 635 | // Iterate backwards through buffer (newest first) | ||
| 636 | ✗ | for (auto it = output_buffer.rbegin(); it != output_buffer.rend(); it += 1) { | |
| 637 | ✗ | if (current_line <= layout.output_y) { | |
| 638 | ✗ | break; | |
| 639 | } | ||
| 640 | |||
| 641 | ✗ | const auto& [text, type] = *it; | |
| 642 | ✗ | std::istringstream stream(text); | |
| 643 | ✗ | std::string line; | |
| 644 | ✗ | std::vector<std::string> display_lines; | |
| 645 | |||
| 646 | // Process each logical line from the message | ||
| 647 | ✗ | while (std::getline(stream, line)) { | |
| 648 | // Wrap long lines at word boundaries | ||
| 649 | ✗ | auto wrapped = TextUtils::wrap_text(line, max_content_width); | |
| 650 | ✗ | display_lines.insert(display_lines.end(), wrapped.begin(), wrapped.end()); | |
| 651 | ✗ | } | |
| 652 | |||
| 653 | // Render from bottom to top (reverse order) | ||
| 654 | ✗ | for (auto line_it = display_lines.rbegin(); line_it != display_lines.rend(); line_it += 1) { | |
| 655 | ✗ | if (current_line <= layout.output_y) break; | |
| 656 | |||
| 657 | ✗ | if (type == TerminalBackend::MESSAGE_TYPE_ERROR) { | |
| 658 | ✗ | wattron(stdscr, COLOR_PAIR(ERROR_PAIR) | A_BOLD); | |
| 659 | ✗ | mvprintw(current_line, 2, "❌ %s", line_it->c_str()); | |
| 660 | ✗ | wattroff(stdscr, COLOR_PAIR(ERROR_PAIR) | A_BOLD); | |
| 661 | ✗ | } else if (type == TerminalBackend::MESSAGE_TYPE_SUCCESS) { | |
| 662 | ✗ | wattron(stdscr, A_BOLD); | |
| 663 | ✗ | mvprintw(current_line, 2, "✅ %s", line_it->c_str()); | |
| 664 | ✗ | wattroff(stdscr, A_BOLD); | |
| 665 | } else { | ||
| 666 | ✗ | mvprintw(current_line, 2, "%s", line_it->c_str()); | |
| 667 | } | ||
| 668 | |||
| 669 | ✗ | current_line--; | |
| 670 | } | ||
| 671 | ✗ | } | |
| 672 | |||
| 673 | ✗ | refresh(); | |
| 674 | ✗ | } | |
| 675 | |||
| 676 | /** | ||
| 677 | * @brief Spawns the background rendering thread and sets the thread_running flag. | ||
| 678 | * | ||
| 679 | * Sets thread_running to true and creates a new std::thread that invokes render_loop(). | ||
| 680 | * The thread is joinable and must be cleaned up via stop_render_thread() or equivalent. | ||
| 681 | * | ||
| 682 | * @note Call this after init_ncurses() to begin continuous UI rendering. | ||
| 683 | * @see render_loop(), stop_render_thread() | ||
| 684 | */ | ||
| 685 | ✗ | void TerminalBackend::start_render_thread(void) { | |
| 686 | ✗ | this->thread_running.store(true); | |
| 687 | ✗ | this->render_thread = std::thread([this]() { | |
| 688 | try { | ||
| 689 | ✗ | this->render_loop(); | |
| 690 | ✗ | } catch (...) { | |
| 691 | ✗ | this->render_exception = std::current_exception(); | |
| 692 | ✗ | } | |
| 693 | ✗ | this->thread_running.store(false); | |
| 694 | ✗ | }); | |
| 695 | ✗ | } | |
| 696 | |||
| 697 | /** | ||
| 698 | * @brief Gracefully shuts down the background rendering thread. | ||
| 699 | * | ||
| 700 | * Sets thread_running to false and notifies the condition variable cv_redraw to | ||
| 701 | * wake the render loop. Joins the thread if it is joinable, ensuring complete cleanup. | ||
| 702 | * | ||
| 703 | * @note Call this during session shutdown or before destroying the TerminalBackend instance. | ||
| 704 | * @see start_render_thread(), render_loop() | ||
| 705 | */ | ||
| 706 | ✗ | void TerminalBackend::stop_render_thread(void) { | |
| 707 | { | ||
| 708 | ✗ | std::lock_guard<std::mutex> lock(this->ui_mutex); | |
| 709 | ✗ | this->thread_running.store(false); | |
| 710 | ✗ | } | |
| 711 | ✗ | this->cv_redraw.notify_all(); | |
| 712 | ✗ | if (this->render_thread.joinable() && this->render_thread.get_id() != std::this_thread::get_id()) { | |
| 713 | ✗ | this->render_thread.join(); | |
| 714 | } | ||
| 715 | ✗ | if (this->render_exception) { | |
| 716 | ✗ | std::exception_ptr error = std::exchange(this->render_exception, nullptr); | |
| 717 | ✗ | std::rethrow_exception(error); | |
| 718 | ✗ | } | |
| 719 | ✗ | } | |
| 720 | |||
| 721 | /** | ||
| 722 | * @brief Main rendering loop executed by the background render thread. | ||
| 723 | * | ||
| 724 | * Runs continuously while thread_running is true. Uses cv_redraw condition variable | ||
| 725 | * with a 1500ms timeout to wait efficiently for redraw requests. Handles terminal resize | ||
| 726 | * events (endwin(), refresh(), update_layout(), cursor recalculation). Conditionally | ||
| 727 | * redraws UI components (draw_ui, draw_output_area, draw_input_area, draw_spinner) | ||
| 728 | * when should_redraw is set. All ncurses operations are protected by ui_mutex. | ||
| 729 | * | ||
| 730 | * @note This method is the entry point for the render thread and should not be called directly. | ||
| 731 | * Call start_render_thread() to spawn it. Terminate via stop_render_thread(). | ||
| 732 | * @see start_render_thread(), stop_render_thread(), draw_ui(), draw_output_area(), draw_input_area(), draw_spinner() | ||
| 733 | */ | ||
| 734 | ✗ | void TerminalBackend::render_loop() { | |
| 735 | ✗ | const int INPUT_PROMPT_WIDTH = 37; | |
| 736 | try { | ||
| 737 | ✗ | while (this->thread_running.load(std::memory_order_acquire)) { | |
| 738 | ✗ | std::unique_lock<std::mutex> lock(ui_mutex); | |
| 739 | |||
| 740 | // Wake on redraw, resize, interrupt, or shutdown. The 1500 ms timeout is only a fallback. | ||
| 741 | ✗ | this->cv_redraw.wait_for(lock, std::chrono::milliseconds(1500), [this] { | |
| 742 | ✗ | return this->should_redraw.load(std::memory_order_acquire) | |
| 743 | ✗ | || TerminalBackend::resize_flag.load(std::memory_order_acquire) | |
| 744 | ✗ | || TerminalBackend::interrupt_flag.load(std::memory_order_acquire) | |
| 745 | ✗ | || !this->thread_running.load(std::memory_order_acquire); | |
| 746 | }); | ||
| 747 | |||
| 748 | ✗ | if (TerminalBackend::interrupt_flag.load(std::memory_order_acquire) | |
| 749 | ✗ | || !this->thread_running.load(std::memory_order_acquire)) { | |
| 750 | ✗ | endwin(); | |
| 751 | ✗ | break; // lock is released by the destructor; end_session runs on the main thread | |
| 752 | } | ||
| 753 | |||
| 754 | ✗ | if (TerminalBackend::resize_flag.exchange(false, std::memory_order_acq_rel)) { | |
| 755 | ✗ | endwin(); | |
| 756 | ✗ | refresh(); | |
| 757 | ✗ | this->update_layout(); | |
| 758 | ✗ | this->input_cursor_x = layout.input_x + INPUT_PROMPT_WIDTH + input_buffer.length(); | |
| 759 | ✗ | this->should_redraw.store(true, std::memory_order_release); | |
| 760 | } | ||
| 761 | |||
| 762 | ✗ | if (this->should_redraw.load(std::memory_order_acquire)) { | |
| 763 | ✗ | this->draw_ui(); | |
| 764 | ✗ | this->draw_output_area(); | |
| 765 | ✗ | this->draw_input_area(); | |
| 766 | ✗ | this->draw_spinner(); | |
| 767 | ✗ | refresh(); | |
| 768 | ✗ | this->should_redraw.store(false, std::memory_order_release); | |
| 769 | } | ||
| 770 | ✗ | } | |
| 771 | ✗ | } catch (...) { | |
| 772 | ✗ | std::lock_guard<std::mutex> g(exception_mutex); | |
| 773 | ✗ | this->render_exception = std::current_exception(); | |
| 774 | ✗ | this->thread_running.store(false, std::memory_order_release); | |
| 775 | ✗ | } | |
| 776 | ✗ | } | |
| 777 | |||
| 778 | /** | ||
| 779 | * Adds text to the output buffer and requests a redraw. | ||
| 780 | * | ||
| 781 | * When stream is true and the output buffer is not empty, text is appended to | ||
| 782 | * the text of the last entry, and type is ignored. Otherwise, a new entry | ||
| 783 | * holding text and type is added to the end of the buffer. The buffer is | ||
| 784 | * modified while ui_mutex is held. | ||
| 785 | * | ||
| 786 | * After the buffer is updated, the function sets should_redraw to true and | ||
| 787 | * wakes one thread waiting on cv_redraw. The lock is released before the | ||
| 788 | * notification is sent. | ||
| 789 | * | ||
| 790 | * @param text The text to add to the output buffer. | ||
| 791 | * @param type The category of the new entry. It is ignored when text is | ||
| 792 | * appended to an existing entry. | ||
| 793 | * @param stream If true, text continues the most recent entry instead of | ||
| 794 | * starting a new one. | ||
| 795 | */ | ||
| 796 | ✗ | void TerminalBackend::print(const std::string& text, int type, bool stream) { | |
| 797 | { | ||
| 798 | ✗ | std::lock_guard<std::mutex> lock(this->ui_mutex); | |
| 799 | ✗ | if (stream == true && !output_buffer.empty()) { | |
| 800 | ✗ | output_buffer.back().first += text; | |
| 801 | } else { | ||
| 802 | ✗ | output_buffer.push_back({text, type}); | |
| 803 | } | ||
| 804 | ✗ | } | |
| 805 | ✗ | this->should_redraw.store(true); | |
| 806 | ✗ | this->cv_redraw.notify_one(); | |
| 807 | ✗ | } | |
| 808 | |||
| 809 | /** | ||
| 810 | * Removes all characters from the input buffer. | ||
| 811 | * | ||
| 812 | * The buffer is empty after the call. Calling the function on an empty buffer | ||
| 813 | * has no effect. Any view previously returned by get_input_buffer is invalid | ||
| 814 | * after this call. The function does not acquire ui_mutex, so callers that | ||
| 815 | * share input_buffer across threads must synchronize access themselves. | ||
| 816 | */ | ||
| 817 | ✗ | void TerminalBackend::clear_input_buffer() { | |
| 818 | ✗ | this->input_buffer.clear(); | |
| 819 | ✗ | } | |
| 820 | |||
| 821 | /** | ||
| 822 | * Reports whether the input buffer holds an exit command. | ||
| 823 | * | ||
| 824 | * The buffer matches only when its entire contents are a single "q" or "Q". | ||
| 825 | * A buffer that contains either character along with other input does not | ||
| 826 | * match. The function does not acquire ui_mutex, so callers that share | ||
| 827 | * input_buffer across threads must synchronize access themselves. | ||
| 828 | * | ||
| 829 | * @return true if input_buffer is exactly "q" or "Q", false otherwise. | ||
| 830 | */ | ||
| 831 | ✗ | bool TerminalBackend::exit_keys_in_input_buffer() { | |
| 832 | ✗ | return this->input_buffer == "q" || this->input_buffer == "Q"; | |
| 833 | } | ||
| 834 | |||
| 835 | /** | ||
| 836 | * Reports whether the input buffer leaves room for a prompt. | ||
| 837 | * | ||
| 838 | * The buffer has room for a prompt when its length is less than the terminal | ||
| 839 | * width (COLS) minus 40 columns, which is reserved for the prompt. COLS is | ||
| 840 | * read at each call, so the result follows terminal resizes. | ||
| 841 | * | ||
| 842 | * The function does not acquire ui_mutex, so callers that share input_buffer | ||
| 843 | * across threads must synchronize access themselves. | ||
| 844 | * | ||
| 845 | * @return true if input_buffer has room for a prompt, false otherwise. | ||
| 846 | */ | ||
| 847 | ✗ | bool TerminalBackend::room_for_prompt_in_input_buffer() { | |
| 848 | ✗ | const int usable = COLS - 40; | |
| 849 | ✗ | return usable > 0 && this->input_buffer.length() < static_cast<std::size_t>(usable); | |
| 850 | } | ||
| 851 | |||
| 852 | /** | ||
| 853 | * Reports whether the input buffer contains no characters. | ||
| 854 | * | ||
| 855 | * The function does not acquire ui_mutex. Its result can be out of date by | ||
| 856 | * the time the caller acts on it if another thread modifies input_buffer in | ||
| 857 | * the meantime. | ||
| 858 | * | ||
| 859 | * @return true if input_buffer is empty, false otherwise. | ||
| 860 | */ | ||
| 861 | ✗ | bool TerminalBackend::input_buffer_is_empty() { | |
| 862 | ✗ | return this->input_buffer.empty(); | |
| 863 | } | ||
| 864 | |||
| 865 | /** | ||
| 866 | * Returns a non-owning view of the current input buffer contents. | ||
| 867 | * | ||
| 868 | * The view refers to the storage of input_buffer and does not copy it. It | ||
| 869 | * stays valid only until input_buffer is modified, for example by | ||
| 870 | * push_back_input_buffer or pop_back_input_buffer, which can reallocate or | ||
| 871 | * shrink the storage. It also remains valid only while this TerminalBackend | ||
| 872 | * exists. The function does not acquire ui_mutex, so callers that share | ||
| 873 | * input_buffer across threads must synchronize access themselves. | ||
| 874 | * | ||
| 875 | * @return A view of input_buffer. Copy the contents if they must outlive the | ||
| 876 | * next modification of the buffer. | ||
| 877 | */ | ||
| 878 | ✗ | std::string_view TerminalBackend::get_input_buffer() const { | |
| 879 | ✗ | return this->input_buffer; | |
| 880 | } | ||
| 881 | |||
| 882 | /** | ||
| 883 | * Removes the last character from the input buffer. | ||
| 884 | * | ||
| 885 | * The function does not check whether the buffer is empty. Calling it when | ||
| 886 | * input_buffer is empty is undefined behavior. Like push_back_input_buffer, | ||
| 887 | * it does not acquire ui_mutex, so callers that share input_buffer across | ||
| 888 | * threads must synchronize access themselves. | ||
| 889 | * | ||
| 890 | * @pre input_buffer is not empty. | ||
| 891 | */ | ||
| 892 | ✗ | void TerminalBackend::pop_back_input_buffer() { | |
| 893 | ✗ | std::lock_guard<std::mutex> lock(this->ui_mutex); | |
| 894 | ✗ | this->input_buffer.pop_back(); | |
| 895 | ✗ | } | |
| 896 | |||
| 897 | /** | ||
| 898 | * Appends a character code to the end of the input buffer. | ||
| 899 | * | ||
| 900 | * The value is stored as passed, without validation or conversion. The | ||
| 901 | * function does not acquire ui_mutex, so callers that share input_buffer | ||
| 902 | * across threads must synchronize access themselves. | ||
| 903 | * | ||
| 904 | * @param ch The character code to append to input_buffer. | ||
| 905 | */ | ||
| 906 | ✗ | void TerminalBackend::push_back_input_buffer(int ch) { | |
| 907 | ✗ | std::lock_guard<std::mutex> lock(this->ui_mutex); | |
| 908 | ✗ | this->input_buffer.push_back(ch); | |
| 909 | ✗ | } | |
| 910 |