interface/user_interface.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "user_interface.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 <sstream> | ||
| 10 | |||
| 11 | std::weak_ptr<UserInterface> UserInterface::instance; | ||
| 12 | |||
| 13 | /** | ||
| 14 | * Creates a UserInterface instance with the light theme as the default color scheme. | ||
| 15 | * | ||
| 16 | * @return: Shared pointer to the newly created UserInterface, also stored in the static instance member. | ||
| 17 | * | ||
| 18 | * Delegates to create(bool) with dark_theme set to false, so use_dark_theme is initialized to the light theme. | ||
| 19 | * Any previously stored instance is replaced by the new one. | ||
| 20 | * | ||
| 21 | * Note: This overload does not call init_ncurses(). The caller must invoke init_ncurses() explicitly on the returned | ||
| 22 | * instance to set up the terminal, color pairs, and input handling. | ||
| 23 | */ | ||
| 24 | ✗ | std::shared_ptr<UserInterface> UserInterface::create() { | |
| 25 | ✗ | return create(false); | |
| 26 | } | ||
| 27 | |||
| 28 | /** | ||
| 29 | * Creates a UserInterface instance with a caller-specified color theme preference and registers it as the singleton | ||
| 30 | * instance. | ||
| 31 | * | ||
| 32 | * @param dark_theme: Boolean flag to select color scheme; true for dark theme, false for light theme. | ||
| 33 | * @return: Shared pointer to the newly created UserInterface, also stored in the static instance member. | ||
| 34 | * | ||
| 35 | * Allocates a new UserInterface through the constructor, passing dark_theme so that use_dark_theme is set during | ||
| 36 | * construction. Assigns the new object to instance, replacing any previously stored value. Returns the shared pointer | ||
| 37 | * to the caller. | ||
| 38 | * | ||
| 39 | * Note: This method does not call init_ncurses(). The caller must invoke init_ncurses() explicitly on the returned | ||
| 40 | * instance to set up the terminal, color pairs, and input handling. | ||
| 41 | */ | ||
| 42 | ✗ | std::shared_ptr<UserInterface> UserInterface::create(bool dark_theme) { | |
| 43 | ✗ | std::shared_ptr<UserInterface> ui(new UserInterface(dark_theme)); | |
| 44 | ✗ | instance = ui; | |
| 45 | ✗ | return ui; | |
| 46 | } | ||
| 47 | |||
| 48 | /** | ||
| 49 | * Constructs a UserInterface instance and initializes member variables. | ||
| 50 | * | ||
| 51 | * Initializes the TerminalBackend. | ||
| 52 | */ | ||
| 53 | ✗ | UserInterface::UserInterface() { | |
| 54 | ✗ | this->backend = std::make_unique<TerminalBackend>(); | |
| 55 | ✗ | } | |
| 56 | |||
| 57 | /** | ||
| 58 | * Constructs a UserInterface instance with a caller-specified color theme preference. | ||
| 59 | * | ||
| 60 | * @param dark_theme: Boolean flag to select color scheme; true for dark theme, false for light theme. | ||
| 61 | * | ||
| 62 | * Initializes the TerminalBackend. | ||
| 63 | */ | ||
| 64 | ✗ | UserInterface::UserInterface(bool dark_theme) { | |
| 65 | ✗ | this->backend = std::make_unique<TerminalBackend>(dark_theme); | |
| 66 | ✗ | } | |
| 67 | |||
| 68 | /** | ||
| 69 | * Destructs a UserInterface instance and releases ncurses resources. | ||
| 70 | */ | ||
| 71 | ✗ | UserInterface::~UserInterface() { | |
| 72 | ✗ | this->end_session(); | |
| 73 | ✗ | } | |
| 74 | |||
| 75 | /** | ||
| 76 | * Reports whether the backend's thread is currently running. | ||
| 77 | * | ||
| 78 | * The function returns the result of backend->is_running(). It does not | ||
| 79 | * acquire ui_mutex, and the value can change immediately after the call | ||
| 80 | * returns. | ||
| 81 | * | ||
| 82 | * @return true if the backend thread is running, false otherwise. | ||
| 83 | * | ||
| 84 | * @pre backend is not null. | ||
| 85 | * | ||
| 86 | * @note Use this for status checks only. Do not use it to decide whether to | ||
| 87 | * start or stop the backend without coordinating through another | ||
| 88 | * synchronization mechanism, because the state can change between the | ||
| 89 | * check and the action. | ||
| 90 | */ | ||
| 91 | ✗ | bool UserInterface::backend_running() { | |
| 92 | ✗ | return this->backend->is_running(); | |
| 93 | } | ||
| 94 | |||
| 95 | /** | ||
| 96 | * Runs the user interface by delegating to the backend. | ||
| 97 | * | ||
| 98 | * The function calls backend->run() and does nothing else. The behavior, | ||
| 99 | * including whether and when the call returns, is defined by | ||
| 100 | * TerminalBackend::run(). | ||
| 101 | * | ||
| 102 | * @pre backend is not null. | ||
| 103 | * | ||
| 104 | * @note Any blocking, error handling, or session termination happens inside | ||
| 105 | * TerminalBackend::run(). Refer to that method's documentation for those | ||
| 106 | * details. | ||
| 107 | */ | ||
| 108 | ✗ | void UserInterface::run(void) { | |
| 109 | ✗ | this->backend->run(); | |
| 110 | ✗ | } | |
| 111 | |||
| 112 | /** | ||
| 113 | * Shows a session-ended message, ends the backend session. | ||
| 114 | * | ||
| 115 | * The function calls print_message() with the end-of-session message, calls | ||
| 116 | * backend->end_session() to stop the render thread and restore the terminal, | ||
| 117 | * and then calls std::exit(code). The function does not return. | ||
| 118 | * | ||
| 119 | * @pre backend is not null. | ||
| 120 | */ | ||
| 121 | ✗ | void UserInterface::end_session(int code) { | |
| 122 | ✗ | this->print_message("🏁 The session has ended."); | |
| 123 | |||
| 124 | ✗ | if (this->backend->is_running()) { | |
| 125 | ✗ | this->backend->end_session(code); | |
| 126 | } else { | ||
| 127 | ✗ | throw ExitRequest{code}; | |
| 128 | } | ||
| 129 | ✗ | } | |
| 130 | |||
| 131 | /** | ||
| 132 | * Displays runtime configuration arguments as formatted diagnostic output. | ||
| 133 | * | ||
| 134 | * @param model Name of the primary language model in use. | ||
| 135 | * @param embedding_model Name of the embedding model in use. | ||
| 136 | * @param prompt Initial prompt or query string provided by the user. | ||
| 137 | * @param stream Boolean flag indicating whether streaming mode is enabled. | ||
| 138 | * @param rag Whether to run the program in the Retrieval Augmented Generation mode. | ||
| 139 | * @param interactive Boolean flag indicating whether interactive mode is enabled. | ||
| 140 | * @param dark_theme Boolean flag indicating whether dark theme is active. | ||
| 141 | * @param skip_embedding Whether to skip vectorizing documents and creating embeddings. | ||
| 142 | * | ||
| 143 | * Constructs a multi-line diagnostic string containing all provided configuration parameters. | ||
| 144 | * Each parameter is formatted with a 🛈 (information) icon prefix for visual consistency. | ||
| 145 | * Boolean parameters are converted to human-readable "true" or "false" strings using conditional | ||
| 146 | * operators, then concatenated into the buffer. | ||
| 147 | * | ||
| 148 | * Prints the formatted buffer via this->print_message(), displaying | ||
| 149 | * the configuration summary in the output area for user visibility. | ||
| 150 | * | ||
| 151 | * @return void | ||
| 152 | * | ||
| 153 | * Output is displayed via print() and committed to the output buffer. | ||
| 154 | * | ||
| 155 | * Acts as a diagnostic utility to confirm application startup parameters and aid in | ||
| 156 | * troubleshooting configuration issues. Typically called early during initialization to | ||
| 157 | * provide user confirmation of active settings. | ||
| 158 | * | ||
| 159 | * Enables transparency into runtime configuration and helps users verify that the correct | ||
| 160 | * models, modes, and theme are in effect. | ||
| 161 | */ | ||
| 162 | ✗ | void UserInterface::print_args(const std::string& model, const std::string& embedding_model, const std::string& prompt, | |
| 163 | bool stream, bool rag, bool interactive, bool dark_theme, bool skip_embedding) { | ||
| 164 | ✗ | std::string buffer; | |
| 165 | ✗ | buffer += "🛈 model = " + model + "\n"; | |
| 166 | ✗ | buffer += "🛈 embedding_model = " + embedding_model + "\n"; | |
| 167 | ✗ | buffer += "🛈 prompt = " + prompt + "\n"; | |
| 168 | ✗ | buffer += "🛈 stream = " + std::string(stream ? "true" : "false") + "\n"; | |
| 169 | ✗ | buffer += "🛈 rag = " + std::string(rag ? "true" : "false") + "\n"; | |
| 170 | ✗ | buffer += "🛈 interactive = " + std::string(interactive ? "true" : "false") + "\n"; | |
| 171 | ✗ | buffer += "🛈 dark_theme = " + std::string(dark_theme ? "true" : "false") + "\n"; | |
| 172 | ✗ | buffer += "🛈 skip_embedding = " + std::string(skip_embedding ? "true" : "false") + "\n"; | |
| 173 | |||
| 174 | ✗ | this->print_message(buffer); | |
| 175 | ✗ | } | |
| 176 | |||
| 177 | /** | ||
| 178 | * @brief Displays runtime configuration arguments to stdout in non-interactive mode. | ||
| 179 | * | ||
| 180 | * @param model Name of the primary language model in use. | ||
| 181 | * @param embedding_model Name of the embedding model in use. | ||
| 182 | * @param prompt Initial prompt or query string provided by the user. | ||
| 183 | * @param stream Boolean flag indicating whether streaming mode is enabled. | ||
| 184 | * @param rag Whether to run the program in the Retrieval Augmented Generation mode. | ||
| 185 | * @param interactive Boolean flag indicating whether interactive mode is enabled. | ||
| 186 | * @param dark_theme Boolean flag indicating whether dark theme is active. | ||
| 187 | * @param skip_embedding Whether to skip vectorizing documents and creating embeddings. | ||
| 188 | * | ||
| 189 | * @return void | ||
| 190 | * | ||
| 191 | * Outputs runtime configuration to standard output (stdout) using printf(), bypassing the | ||
| 192 | * ncurses UI buffer. This method is used when the application runs in non-interactive mode, | ||
| 193 | * where the terminal UI is not initialized and direct console output is required. | ||
| 194 | * | ||
| 195 | * Constructs and prints a multi-line diagnostic string containing all provided configuration | ||
| 196 | * parameters. Each parameter is formatted with a 🛈 (information) icon prefix for visual | ||
| 197 | * consistency with interactive mode output. Boolean parameters are converted to human-readable | ||
| 198 | * "true" or "false" strings using conditional operators. | ||
| 199 | * | ||
| 200 | * Includes leading and trailing newlines (printf("\n")) to visually separate the configuration | ||
| 201 | * summary from other console output, improving readability in log files and terminal sessions. | ||
| 202 | * | ||
| 203 | * Acts as the non-interactive counterpart to print_args(). Enables configuration transparency | ||
| 204 | * and aids in troubleshooting when the application runs in batch or command-line mode without | ||
| 205 | * the interactive terminal UI. | ||
| 206 | * | ||
| 207 | * @note This method uses direct printf() calls and should only be used before ncurses | ||
| 208 | * initialization or after cleanup, to avoid conflicts with the ncurses output buffer. | ||
| 209 | */ | ||
| 210 | ✗ | void UserInterface::print_args_noninteractive(const std::string& model, const std::string& embedding_model, | |
| 211 | const std::string& prompt, bool stream, bool rag, bool interactive, | ||
| 212 | bool dark_theme, bool skip_embedding) { | ||
| 213 | ✗ | printf("\n"); | |
| 214 | ✗ | printf("🛈 model = %s\n", model.c_str()); | |
| 215 | ✗ | printf("🛈 embedding_model = %s\n", embedding_model.c_str()); | |
| 216 | ✗ | printf("🛈 prompt = %s\n", prompt.c_str()); | |
| 217 | ✗ | printf("🛈 stream = %s\n", stream ? "true" : "false"); | |
| 218 | ✗ | printf("🛈 rag = %s\n", rag ? "true" : "false"); | |
| 219 | ✗ | printf("🛈 interactive = %s\n", interactive ? "true" : "false"); | |
| 220 | ✗ | printf("🛈 dark_theme = %s\n", dark_theme ? "true" : "false"); | |
| 221 | ✗ | printf("🛈 skip_embedding = %s\n", skip_embedding ? "true" : "false"); | |
| 222 | ✗ | printf("\n"); | |
| 223 | ✗ | } | |
| 224 | |||
| 225 | /** | ||
| 226 | * @brief Displays a numbered list of available models to the user via the UI buffer. | ||
| 227 | * | ||
| 228 | * @param models A constant reference to a vector of model name strings to be displayed. | ||
| 229 | * | ||
| 230 | * @return void | ||
| 231 | * | ||
| 232 | * Renders an interactive model selection menu by formatting each model name with its | ||
| 233 | * zero-indexed position. This method is used during interactive sessions to present | ||
| 234 | * available Ollama models to the user, enabling selection via numeric input. | ||
| 235 | * | ||
| 236 | * Constructs a formatted string buffer containing an information message ("🛈 Select a | ||
| 237 | * model from the list below:") followed by a numbered list. Each entry is formatted as | ||
| 238 | * "[index] model_name" on a separate line, where index is zero-based and automatically | ||
| 239 | * converted from the loop counter using std::to_string(). | ||
| 240 | * | ||
| 241 | * Outputs the constructed buffer to the ncurses UI using print_message() styling, | ||
| 242 | * ensuring the model list appears in the output area and is preserved in the UI's | ||
| 243 | * output_buffer for proper rendering and scrolling. | ||
| 244 | * | ||
| 245 | * @note This method assumes models is not empty; calling with an empty vector will display | ||
| 246 | * only the header message without any selectable options. Typically called after successfully | ||
| 247 | * retrieving the model list from the Ollama server via query_model_list(). | ||
| 248 | */ | ||
| 249 | ✗ | void UserInterface::print_model_list(const std::vector<std::string>& models) { | |
| 250 | ✗ | std::string buffer; | |
| 251 | ✗ | buffer += "\n🛈 Select a model from the list below:\n"; | |
| 252 | ✗ | for (size_t i = 0; i < models.size(); i += 1) { | |
| 253 | ✗ | buffer += "[" + std::to_string(i) + "] " + models[i] + "\n"; | |
| 254 | } | ||
| 255 | |||
| 256 | ✗ | this->print_message(buffer); | |
| 257 | ✗ | } | |
| 258 | |||
| 259 | /** | ||
| 260 | * @brief Outputs a numbered list of available models to stdout in non-interactive mode. | ||
| 261 | * | ||
| 262 | * @param models A constant reference to a vector of model name strings. | ||
| 263 | * | ||
| 264 | * @return void | ||
| 265 | * | ||
| 266 | * Formats and prints each model with its zero-indexed position as "[index] model_name" | ||
| 267 | * using printf() directly, bypassing the ncurses UI buffer. Called when the application | ||
| 268 | * runs in non-interactive mode and the terminal UI is not initialized. | ||
| 269 | * | ||
| 270 | * @note This method should only be used before ncurses initialization or after cleanup. | ||
| 271 | */ | ||
| 272 | ✗ | void UserInterface::print_model_list_noninteractive(const std::vector<std::string>& models) { | |
| 273 | ✗ | printf("\n🛈 Select a model from the list below:\n"); | |
| 274 | ✗ | for (size_t i = 0; i < models.size(); i += 1) { | |
| 275 | ✗ | printf("[%zu] %s\n", i, models[i].c_str()); | |
| 276 | } | ||
| 277 | ✗ | } | |
| 278 | |||
| 279 | /** | ||
| 280 | * @brief Prompts the user to select a model by numeric index via interactive keyboard input. | ||
| 281 | * | ||
| 282 | * @param models A constant reference to a vector of available model name strings. | ||
| 283 | * @param model A pointer to a string where the selected model name will be stored. | ||
| 284 | * | ||
| 285 | * @return void | ||
| 286 | * | ||
| 287 | * Validates that models is not empty; exits with error if no models are available. | ||
| 288 | * Clears the input buffer and enters a getch() loop to capture user input, supporting | ||
| 289 | * backspace (KEY_BACKSPACE or 127) and printable characters with length constraints. | ||
| 290 | * Input terminates on newline (Enter key). | ||
| 291 | * | ||
| 292 | * Interprets input as a zero-indexed model position via stoi(). If input is "q" or "Q", | ||
| 293 | * terminates the session. If the index is out of bounds, prints an error and recursively | ||
| 294 | * re-prompts. If valid, dereferences model and assigns the selected model name. | ||
| 295 | * | ||
| 296 | * @note Input buffer length is capped at COLS - 40 to prevent overflow. Invalid indices | ||
| 297 | * trigger recursive retry. Quit commands (q/Q) terminate the entire session. | ||
| 298 | */ | ||
| 299 | ✗ | void UserInterface::select_model(const std::vector<std::string>& models, std::string* model) { | |
| 300 | ✗ | int index{}; | |
| 301 | |||
| 302 | ✗ | if (models.size() == 0) { | |
| 303 | ✗ | this->print_error("There are no available models to select from.\n"); | |
| 304 | ✗ | this->end_session(EXIT_FAILURE); | |
| 305 | } | ||
| 306 | |||
| 307 | ✗ | this->request_redraw(); | |
| 308 | |||
| 309 | ✗ | this->backend->clear_input_buffer(); | |
| 310 | int ch; | ||
| 311 | |||
| 312 | ✗ | while ((ch = getch()) != '\n') { | |
| 313 | ✗ | if (ch == KEY_BACKSPACE || ch == 127) { | |
| 314 | ✗ | if (!this->backend->input_buffer_is_empty()) { | |
| 315 | ✗ | this->backend->pop_back_input_buffer(); | |
| 316 | ✗ | this->backend->shift_input_cursor_x(-1); | |
| 317 | ✗ | this->request_redraw(); | |
| 318 | } | ||
| 319 | ✗ | } else if (ch != ERR && isprint(ch)) { | |
| 320 | ✗ | if (this->backend->room_for_prompt_in_input_buffer()) { | |
| 321 | ✗ | this->backend->push_back_input_buffer(ch); | |
| 322 | ✗ | this->backend->shift_input_cursor_x(1); | |
| 323 | ✗ | this->request_redraw(); | |
| 324 | } | ||
| 325 | } | ||
| 326 | } | ||
| 327 | |||
| 328 | ✗ | if (this->backend->exit_keys_in_input_buffer()) { | |
| 329 | ✗ | this->end_session(EXIT_SUCCESS); | |
| 330 | } | ||
| 331 | |||
| 332 | ✗ | index = stoi(std::string(this->backend->get_input_buffer())); | |
| 333 | |||
| 334 | ✗ | if (index < 0 || index >= models.size()) { | |
| 335 | ✗ | std::string message = std::format("Model index {} does not exist.\n", index); | |
| 336 | ✗ | this->print_error(message); | |
| 337 | ✗ | this->select_model(models, model); | |
| 338 | ✗ | } else { | |
| 339 | ✗ | *model = models[index]; | |
| 340 | } | ||
| 341 | ✗ | } | |
| 342 | |||
| 343 | /** | ||
| 344 | * @brief Prompts for a model selection via stdin in non-interactive mode. | ||
| 345 | * | ||
| 346 | * @param models A constant reference to a vector of available model name strings. | ||
| 347 | * @param model A pointer to a string where the selected model name will be stored. | ||
| 348 | * | ||
| 349 | * @return void | ||
| 350 | * | ||
| 351 | * Validates that models is not empty; exits with error if none are available. | ||
| 352 | * Loops until a valid zero-indexed model position is successfully read from stdin via scanf(). | ||
| 353 | * Repeats the prompt if scanf() fails to read exactly one integer or if the index is out of bounds. | ||
| 354 | * Prints validation errors to stderr. On valid input, dereferences model and assigns the | ||
| 355 | * selected model name. | ||
| 356 | * | ||
| 357 | * @note Uses stderr for error messages and stdout for prompts. Loop continues until | ||
| 358 | * scanf() succeeds and index is within [0, models.size()). | ||
| 359 | */ | ||
| 360 | ✗ | void UserInterface::select_model_noninteractive(const std::vector<std::string>& models, std::string* model) { | |
| 361 | ✗ | int index{}; | |
| 362 | ✗ | int read_result{}; | |
| 363 | |||
| 364 | ✗ | if (models.size() == 0) { | |
| 365 | ✗ | UserInterface::print_error_noninteractive("There are no available models to select from.\n"); | |
| 366 | ✗ | if (auto ui = instance.lock()) { | |
| 367 | ✗ | ui->end_session(EXIT_FAILURE); | |
| 368 | ✗ | } | |
| 369 | } | ||
| 370 | |||
| 371 | ✗ | while (read_result != 1 || index < 0 || index >= models.size()) { | |
| 372 | ✗ | if (index < 0 || index >= models.size()) { | |
| 373 | ✗ | UserInterface::print_error_noninteractive(std::format("Model index {} does not exist.\n", index)); | |
| 374 | } | ||
| 375 | ✗ | UserInterface::print_message_noninteractive("Model index: "); | |
| 376 | ✗ | read_result = scanf("%d", &index); | |
| 377 | } | ||
| 378 | |||
| 379 | ✗ | *model = models[index]; | |
| 380 | ✗ | } | |
| 381 | |||
| 382 | /** | ||
| 383 | * Reads one line of user input into the prompt and reports whether it is an | ||
| 384 | * exit request. | ||
| 385 | * | ||
| 386 | * The function requests a redraw, clears the input buffer, and then reads keys | ||
| 387 | * with getch() until Enter ('\n') is pressed. Backspace removes the last | ||
| 388 | * character and moves the cursor left. A printable character is appended only | ||
| 389 | * if room_for_prompt_in_input_buffer() is true, and it moves the cursor right. | ||
| 390 | * Each change requests a redraw. When Enter is pressed, the buffer contents are | ||
| 391 | * copied into *prompt. The function returns true if the text is exactly "q" or | ||
| 392 | * "Q". | ||
| 393 | * | ||
| 394 | * @param prompt Output string that receives the entered text. Must not be null. | ||
| 395 | * | ||
| 396 | * @return true if the entered text is "q" or "Q", otherwise false. | ||
| 397 | * | ||
| 398 | * @pre prompt is not null. | ||
| 399 | * @post *prompt holds the text the user entered. The input buffer still holds | ||
| 400 | * the same text. | ||
| 401 | * | ||
| 402 | * @note getch() blocks until a key is pressed. Non-printable keys, such as | ||
| 403 | * arrow keys, are ignored. An ERR return is also ignored, but only | ||
| 404 | * because it fails the isprint() test. In non-blocking mode, this loop | ||
| 405 | * would busy-wait. | ||
| 406 | * @note The input buffer is modified without holding ui_mutex. The render thread | ||
| 407 | * can read it at the same time, so this is a data race unless the caller | ||
| 408 | * guarantees that the render thread is not reading the buffer. | ||
| 409 | */ | ||
| 410 | ✗ | bool UserInterface::next_prompt(std::string* prompt) { | |
| 411 | ✗ | bool done = false; | |
| 412 | |||
| 413 | ✗ | this->request_redraw(); | |
| 414 | |||
| 415 | ✗ | this->backend->clear_input_buffer(); | |
| 416 | |||
| 417 | ✗ | timeout(100); // getch() returns ERR after 100 ms if no key is pressed | |
| 418 | int ch; | ||
| 419 | |||
| 420 | ✗ | while ((ch = getch()) != '\n') { | |
| 421 | ✗ | if (ch == KEY_BACKSPACE || ch == 127) { | |
| 422 | ✗ | if (!this->backend->input_buffer_is_empty()) { | |
| 423 | ✗ | this->backend->pop_back_input_buffer(); | |
| 424 | ✗ | this->backend->shift_input_cursor_x(-1); | |
| 425 | ✗ | this->request_redraw(); | |
| 426 | } | ||
| 427 | ✗ | } else if (ch != ERR && isprint(ch)) { | |
| 428 | ✗ | if (this->backend->room_for_prompt_in_input_buffer()) { | |
| 429 | ✗ | this->backend->push_back_input_buffer(ch); | |
| 430 | ✗ | this->backend->shift_input_cursor_x(1); | |
| 431 | ✗ | this->request_redraw(); | |
| 432 | } | ||
| 433 | ✗ | } else if (ch == ERR && !this->backend->is_running()) { | |
| 434 | ✗ | return true; | |
| 435 | } | ||
| 436 | } | ||
| 437 | |||
| 438 | ✗ | *prompt = this->backend->get_input_buffer(); | |
| 439 | |||
| 440 | ✗ | if (*prompt == "q" || *prompt == "Q") { | |
| 441 | ✗ | done = true; | |
| 442 | } | ||
| 443 | |||
| 444 | ✗ | return done; | |
| 445 | } | ||
| 446 | |||
| 447 | /** | ||
| 448 | * @brief Captures the next user prompt via stdin in non-interactive mode and detects quit commands. | ||
| 449 | * | ||
| 450 | * @param prompt A pointer to a string where the captured prompt will be stored. | ||
| 451 | * | ||
| 452 | * @return bool True if the user entered "q" or "Q" (quit command); false otherwise. | ||
| 453 | * | ||
| 454 | * Prompts the user via stdout and reads a line from stdin using std::getline(). | ||
| 455 | * Terminates the program with exit code 1 if input reading fails. | ||
| 456 | * Detects quit commands ("q" or "Q") and returns true to signal session termination. | ||
| 457 | * | ||
| 458 | * @note Must be used outside an active ncurses session. Uses stdout/stderr for I/O. | ||
| 459 | * @see next_prompt() | ||
| 460 | */ | ||
| 461 | ✗ | bool UserInterface::next_prompt_noninteractive(std::string* prompt) { | |
| 462 | ✗ | bool done = false; | |
| 463 | ✗ | printf("⏳ Type your prompt (q/Q to quit): "); | |
| 464 | ✗ | if (!std::getline(std::cin, *prompt, '\n')) { | |
| 465 | ✗ | fprintf(stderr, "Error reading user input.\n"); | |
| 466 | ✗ | if (auto ui = instance.lock()) { | |
| 467 | ✗ | ui->end_session(EXIT_FAILURE); | |
| 468 | ✗ | } | |
| 469 | } | ||
| 470 | |||
| 471 | ✗ | if (*prompt == "q" || *prompt == "Q") { | |
| 472 | ✗ | done = true; | |
| 473 | } | ||
| 474 | |||
| 475 | ✗ | return done; | |
| 476 | } | ||
| 477 | |||
| 478 | /** | ||
| 479 | * @brief Queues an error message (bold red with ❌ prefix) and requests a redraw. | ||
| 480 | * | ||
| 481 | * @param text The error message content. | ||
| 482 | */ | ||
| 483 | ✗ | void UserInterface::print_error(const std::string& text) { | |
| 484 | ✗ | this->backend->print(text, TerminalBackend::MESSAGE_TYPE_ERROR); | |
| 485 | ✗ | } | |
| 486 | |||
| 487 | /** | ||
| 488 | * @brief Queues a success message (bold with ✅ prefix) and requests a redraw. | ||
| 489 | * | ||
| 490 | * @param text The success message content. | ||
| 491 | */ | ||
| 492 | ✗ | void UserInterface::print_success(const std::string& text) { | |
| 493 | ✗ | this->backend->print(text, TerminalBackend::MESSAGE_TYPE_SUCCESS); | |
| 494 | ✗ | } | |
| 495 | |||
| 496 | /** | ||
| 497 | * @brief Queues a normal message (plain text) and requests a redraw. | ||
| 498 | * | ||
| 499 | * @param text The message content. | ||
| 500 | * @param stream In the stream mode, every chunk of text after the first one is appended to the last buffer entry. | ||
| 501 | * Defaults to 'false'. | ||
| 502 | */ | ||
| 503 | ✗ | void UserInterface::print_message(const std::string& text, bool stream) { | |
| 504 | ✗ | this->backend->print(text, TerminalBackend::MESSAGE_TYPE_NORMAL, stream); | |
| 505 | ✗ | } | |
| 506 | |||
| 507 | /** | ||
| 508 | * @brief Outputs a message directly to stderr in non-interactive mode. | ||
| 509 | * | ||
| 510 | * @param text The message content to be displayed. | ||
| 511 | * | ||
| 512 | * Writes the text to stderr and immediately flushes the output buffer to ensure | ||
| 513 | * the message is visible without waiting for a newline. | ||
| 514 | * Adds an icon ❌ before the text. | ||
| 515 | * | ||
| 516 | * @note Must be used outside an active ncurses session. | ||
| 517 | * @see print_error() | ||
| 518 | */ | ||
| 519 | ✗ | void UserInterface::print_error_noninteractive(const std::string& text) { | |
| 520 | ✗ | fprintf(stderr, "❌ %s", text.c_str()); | |
| 521 | ✗ | fflush(stderr); | |
| 522 | ✗ | } | |
| 523 | |||
| 524 | /** | ||
| 525 | * @brief Outputs a message directly to stdout in non-interactive mode. | ||
| 526 | * | ||
| 527 | * @param text The message content to be displayed. | ||
| 528 | * | ||
| 529 | * Writes the text to stdout and immediately flushes the output buffer to ensure | ||
| 530 | * the message is visible without waiting for a newline. | ||
| 531 | * Adds an icon ✅ before the text. | ||
| 532 | * | ||
| 533 | * @note Must be used outside an active ncurses session. | ||
| 534 | * @see print_error() | ||
| 535 | */ | ||
| 536 | ✗ | void UserInterface::print_success_noninteractive(const std::string& text) { | |
| 537 | ✗ | fprintf(stdout, "✅ %s", text.c_str()); | |
| 538 | ✗ | fflush(stdout); | |
| 539 | ✗ | } | |
| 540 | |||
| 541 | /** | ||
| 542 | * @brief Outputs a message directly to stdout in non-interactive mode. | ||
| 543 | * | ||
| 544 | * @param text The message content to be displayed. | ||
| 545 | * | ||
| 546 | * Writes the text to stdout and immediately flushes the output buffer to ensure | ||
| 547 | * the message is visible without waiting for a newline. | ||
| 548 | * | ||
| 549 | * @note Must be used outside an active ncurses session. | ||
| 550 | * @see print_message() | ||
| 551 | */ | ||
| 552 | ✗ | void UserInterface::print_message_noninteractive(const std::string& text) { | |
| 553 | ✗ | fprintf(stdout, "%s", text.c_str()); | |
| 554 | ✗ | fflush(stdout); | |
| 555 | ✗ | } | |
| 556 | |||
| 557 | /** | ||
| 558 | * Requests a redraw and wakes a thread waiting on cv_redraw. | ||
| 559 | * | ||
| 560 | * The function sets should_redraw to true through set_should_redraw(true), then | ||
| 561 | * calls notify_cv_redraw() with its default argument. The method does not | ||
| 562 | * acquire ui_mutex. | ||
| 563 | * | ||
| 564 | * @pre backend is not null. | ||
| 565 | * @post should_redraw is true, and a waiter on cv_redraw has been notified. | ||
| 566 | * | ||
| 567 | * @note The flag is set before the notification, and there is no lock between | ||
| 568 | * them. A waiting thread can wake, see the flag, and proceed before the | ||
| 569 | * notification is sent. The waiter can then miss the signal and go back | ||
| 570 | * to sleep, or it can process the flag without needing the notification. | ||
| 571 | * @warning The waiter's predicate must be checked under ui_mutex. Otherwise a | ||
| 572 | * notification sent between the waiter's check and its wait can be | ||
| 573 | * lost. Whether one or all waiters are woken depends on the default | ||
| 574 | * argument of notify_cv_redraw(), which should be documented at that | ||
| 575 | * declaration. | ||
| 576 | */ | ||
| 577 | ✗ | void UserInterface::request_redraw(void) { | |
| 578 | ✗ | this->backend->set_should_redraw(true); | |
| 579 | ✗ | this->backend->notify_cv_redraw(); | |
| 580 | ✗ | } | |
| 581 | |||
| 582 | /** | ||
| 583 | * Starts the spinner from frame 0 and requests a redraw. | ||
| 584 | * | ||
| 585 | * The function sets spinner_active to true, resets the spinner frame to 0 | ||
| 586 | * through set_spinner_frame(0), and sets should_redraw to true. Each setter is | ||
| 587 | * atomic on its own, but the three updates are not performed as a group and | ||
| 588 | * ui_mutex is not held. cv_redraw is not notified. | ||
| 589 | * | ||
| 590 | * @pre backend is not null. | ||
| 591 | * @post get_spinner_active() returns true, the spinner frame is 0, and | ||
| 592 | * should_redraw is true. | ||
| 593 | * | ||
| 594 | * @note A render thread can read the spinner state between the updates and see | ||
| 595 | * a partial result, such as an active spinner that still shows the | ||
| 596 | * previous frame. | ||
| 597 | * @warning If the three updates must appear together, hold ui_mutex across all | ||
| 598 | * of them with a single scoped lock. Call notify_cv_redraw() afterward | ||
| 599 | * if a waiting thread needs to wake up. | ||
| 600 | */ | ||
| 601 | ✗ | void UserInterface::start_spinner() { | |
| 602 | ✗ | this->backend->set_spinner_active(true); | |
| 603 | ✗ | this->backend->set_spinner_frame(0); | |
| 604 | ✗ | this->backend->set_should_redraw(true); | |
| 605 | ✗ | } | |
| 606 | |||
| 607 | /** | ||
| 608 | * Stops the spinner, resets its frame to 0, and requests a redraw. | ||
| 609 | * | ||
| 610 | * The function sets spinner_active to false, resets the spinner frame to 0 | ||
| 611 | * through set_spinner_frame(0), and sets should_redraw to true. Each setter is | ||
| 612 | * atomic on its own, but the three updates are not performed as a group and | ||
| 613 | * ui_mutex is not held. cv_redraw is not notified. | ||
| 614 | * | ||
| 615 | * @pre backend is not null. | ||
| 616 | * @post get_spinner_active() returns false, the spinner frame is 0, and | ||
| 617 | * should_redraw is true. | ||
| 618 | * | ||
| 619 | * @note A render thread can read the spinner state between the updates and see | ||
| 620 | * a partial result, such as an inactive spinner with the previous frame | ||
| 621 | * still set. | ||
| 622 | * @warning If the three updates must appear together, hold ui_mutex across all | ||
| 623 | * of them with a single scoped lock. Call notify_cv_redraw() afterward | ||
| 624 | * if a waiting thread needs to wake up. | ||
| 625 | */ | ||
| 626 | ✗ | void UserInterface::stop_spinner() { | |
| 627 | ✗ | this->backend->set_spinner_active(false); | |
| 628 | ✗ | this->backend->set_spinner_frame(0); | |
| 629 | ✗ | this->backend->set_should_redraw(true); | |
| 630 | ✗ | } | |
| 631 | |||
| 632 | /** | ||
| 633 | * Advances the spinner to its next frame and requests a redraw, if the spinner | ||
| 634 | * is active. | ||
| 635 | * | ||
| 636 | * The function first checks get_spinner_active(). If the spinner is running, it | ||
| 637 | * advances the frame through set_spinner_frame() and then sets should_redraw. | ||
| 638 | * Nothing happens if the spinner is inactive. The check and the update are not | ||
| 639 | * performed under a lock, and the method does not notify cv_redraw. | ||
| 640 | * | ||
| 641 | * @pre backend is not null. | ||
| 642 | * @post If the spinner was active at the check, its frame has advanced by one | ||
| 643 | * step and should_redraw is true. | ||
| 644 | * | ||
| 645 | * @note The check and the update are not atomic together. If the spinner is | ||
| 646 | * deactivated between them, the frame can still advance once after | ||
| 647 | * deactivation. This is usually harmless for a visual effect. | ||
| 648 | * @warning Because cv_redraw is not notified, a waiting thread may not redraw | ||
| 649 | * until it is woken by another call. Use notify_cv_redraw() if an | ||
| 650 | * immediate redraw is needed. | ||
| 651 | */ | ||
| 652 | ✗ | void UserInterface::advance_spinner_frame() { | |
| 653 | ✗ | if (this->backend->get_spinner_active()) { | |
| 654 | ✗ | this->backend->set_spinner_frame(); | |
| 655 | ✗ | this->backend->set_should_redraw(true); | |
| 656 | } | ||
| 657 | ✗ | } | |
| 658 | |||
| 659 | /** | ||
| 660 | * Updates the displayed progress percentage and requests a redraw. | ||
| 661 | * | ||
| 662 | * The value is clamped to the range [0, 100] before being stored in the backend. | ||
| 663 | * The progress value and the redraw flag are set through two separate atomic | ||
| 664 | * operations, so the change is not applied as a single unit. This method does | ||
| 665 | * not acquire ui_mutex and does not notify cv_redraw. | ||
| 666 | * | ||
| 667 | * @param percent The requested progress percentage. Values below 0 are stored | ||
| 668 | * as 0, and values above 100 are stored as 100. | ||
| 669 | * | ||
| 670 | * @pre backend is not null. | ||
| 671 | * @post The backend's progress value is between 0 and 100, inclusive. | ||
| 672 | * @post should_redraw is set to true. | ||
| 673 | * | ||
| 674 | * @note A thread that reads the progress value between the two calls can see | ||
| 675 | * the new percentage before the redraw request is set. This is usually | ||
| 676 | * harmless but can cause a brief inconsistency. | ||
| 677 | * @warning Because cv_redraw is not notified, a thread waiting on it may not | ||
| 678 | * wake up to redraw. Callers that need an immediate redraw must notify | ||
| 679 | * it separately with notify_cv_redraw(). | ||
| 680 | */ | ||
| 681 | ✗ | void UserInterface::set_progress(int percent) { | |
| 682 | ✗ | this->backend->set_progress_percent(std::clamp(percent, 0, 100)); | |
| 683 | ✗ | this->backend->set_should_redraw(true); | |
| 684 | ✗ | } | |
| 685 |