ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
tui/input.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define TUI_INPUT_MESSAGE_BUFFER_SIZE 512
4#define TUI_INPUT_BURST_BUFFER_SIZE 8192
5#define TUI_INPUT_BUFFER_BUFFER_SIZE 8192
6#define TUI_INPUT_TIMED_PROMPT_BUFFER_SIZE 8192
7#define TUI_INPUT_PASTED_BUFFER_SIZE 8192
8
9/* Existing buffer budgets in bytes, including NUL for text storage. */
10#define TUI_SYNC_KEY_CAPACITY 256
11
13#include <ascii-chat/common.h>
20#include <ascii-chat/otel.h>
29#include <ascii-chat/tui/sync.h>
33#include <ascii-chat/ui/input.h>
34#include <ascii-chat/util/env.h>
37#include <libplatform/atomic.h>
38#include <libplatform/clipboard.h>
39#include <libplatform/compiler.h>
40#include <libplatform/lifecycle.h>
41#include <libplatform/question.h>
42#include <libplatform/system.h>
43#include <libplatform/terminal.h>
44#include <options/options.h>
45#include <sodium.h>
46#include <string.h>
47
48uint64_t ui_input_deadline(unsigned seconds) {
49 return time_get_ns() + (uint64_t)seconds * NS_PER_SEC_INT;
50}
51
52bool ui_input_expired(uint64_t deadline) { return time_get_ns() >= deadline; }
53
54void ui_input_timeout_report(unsigned seconds, const char *consequence) {
56 int length = snprintf(message, sizeof(message),
57 "\nPrompt timed out after %u seconds; %s.\n", seconds,
58 consequence);
59 // This diagnostic must remain visible even while a background screen owns the
60 // terminal.
61 if (length > 0)
62 platform_write_all(STDERR_FILENO, message,
63 (size_t)length < sizeof(message) ? (size_t)length
64 : sizeof(message) - 1);
65 SET_ERRNO(ERROR_PROMPT_TIMEOUT, "Prompt timed out after %u seconds: %s",
66 seconds, consequence);
67}
68
69static lifecycle_t g_input_lifecycle = LIFECYCLE_INIT;
70static mutex_t g_input_mutex;
71static mutex_t g_input_prompt_mutex;
72static _Atomic bool g_discarding_covered_input;
73static keyboard_key_t g_sync_keys[TUI_SYNC_KEY_CAPACITY];
74static unsigned g_sync_key_head, g_sync_key_count;
75static bool g_switch_pending;
76static _Atomic bool g_input_buffered;
77
78static bool input_switch_key(keyboard_key_t key) {
83}
84
86 keyboard_key_t (*read_key)(void),
87 bool (*classify_paste)(const char *)) {
88 if (s->ready)
89 return KEY_NONE;
90 for (unsigned i = 0; i < 1024; ++i) {
91 bool buffered = s->count != 0;
92 keyboard_key_t key = buffered ? s->keys[s->head++] : read_key();
93 if (buffered)
94 --s->count;
95 if (key == KEY_NONE)
96 return KEY_NONE;
97 if (key == KEY_PASTE_BEGIN) {
98 s->pasting = true;
99 s->invalid = false;
100 s->length = 0;
101 continue;
102 }
103 if (key == KEY_PASTE_END) {
104 if (!s->pasting)
105 continue;
106 s->pasting = false;
107 s->paste[s->length] = '\0';
108 s->ready = true;
109 return KEY_PASTE;
110 }
111 char text[8];
112 size_t bytes = keyboard_text_encode(key, text);
113 if (s->pasting) {
114 // Paste payloads remain raw UTF-8 bytes until whole-paste validation.
115 if (key >= 128 && key <= 255) {
116 text[0] = (char)key;
117 bytes = 1;
118 }
119 if (!bytes || (key < 32 && key != '\r' && key != '\n' && key != '\t') ||
120 key == 127 || bytes >= sizeof(s->paste) - s->length)
121 s->invalid = true;
122 else {
123 memcpy(s->paste + s->length, text, bytes);
124 s->length += bytes;
125 }
126 continue;
127 }
128 if (buffered || !bytes || key < 32 || key == 127)
129 return key;
130 s->head = 0;
131 s->keys[0] = key;
132 size_t count = 1;
133 keyboard_key_t next;
134 while (count < 8192 && (next = read_key()) != KEY_NONE) {
135 s->keys[count++] = next;
136 if (next == KEY_PASTE_BEGIN || next == KEY_PASTE_END)
137 break;
138 }
139 bool boundary = s->keys[count - 1] == KEY_PASTE_BEGIN ||
140 s->keys[count - 1] == KEY_PASTE_END;
141 size_t consumed = boundary ? count - 1 : count;
142 size_t text_count = consumed;
143 while (text_count &&
144 (s->keys[text_count - 1] == '\r' || s->keys[text_count - 1] == '\n'))
145 --text_count;
146 char burst[TUI_INPUT_BURST_BUFFER_SIZE];
147 size_t length = 0;
148 bool valid = true;
149 for (size_t n = 0; n < text_count; ++n) {
150 bytes = keyboard_text_encode(s->keys[n], text);
151 if (!bytes || s->keys[n] < 32 || s->keys[n] == 127 ||
152 bytes >= sizeof(burst) - length) {
153 valid = false;
154 break;
155 }
156 memcpy(burst + length, text, bytes);
157 length += bytes;
158 }
159 burst[length] = '\0';
160 if (text_count > 1 && classify_paste && classify_paste(burst)) {
161 // Keep the delimiter queued so the following payload remains framed.
162 s->head = consumed;
163 s->count = count - consumed;
164 s->invalid = !valid;
165 s->length = valid ? length : 0;
166 memcpy(s->paste, burst, s->length);
167 s->paste[s->length] = '\0';
168 s->ready = true;
169 return KEY_PASTE;
170 }
171 s->head = 1;
172 s->count = count - 1;
173 return key;
174 }
175 return KEY_NONE;
176}
177
178static tui_input_events_t g_events;
179
192static input_editor_t g_media_editor;
193
194// Publish only whether routing work remains; the actual queues stay serialized.
195static void input_unlock(void) {
196 atomic_store(&g_input_buffered, g_sync_key_count || g_events.count ||
197 g_events.ready || g_events.pasting ||
198 g_media_editor.active);
199 mutex_unlock(&g_input_mutex);
200}
201
202static bool input_ready(void) {
203 return atomic_load(&g_input_buffered) || keyboard_input_available();
204}
205
206static bool input_media_paste(const char *text) {
207 return text[0] == '.' || text[0] == '/' || text[0] == '\\' ||
208 text[0] == '~' || text[0] == '\'' || text[0] == '"' ||
209 (strlen(text) > 2 && text[1] == ':') || strstr(text, "://") != NULL;
210}
211
212static keyboard_key_t input_read_event(void) {
214 input_media_paste);
215}
216
217// Bound each poll so a continuous input stream cannot monopolize the input
218// mutex.
219static bool input_discard_pending_events(void) {
220 const unsigned discard_budget = 256;
221 g_sync_key_count = 0;
222 for (unsigned n = 0; n < discard_budget; ++n) {
223 // Release completed paste events before reading again; retain unfinished
224 // paste framing so its remaining bytes cannot become application shortcuts.
225 g_events.ready = false;
226 if (input_read_event() == KEY_NONE)
227 return !g_events.pasting;
228 }
229 g_events.ready = false;
230 return false;
231}
232
233static bool input_discard_covered(bool covered) {
234 if (!covered && !atomic_load(&g_discarding_covered_input))
235 return false;
236 bool drained = input_discard_pending_events();
237 // Recovery ends only when both the size cover and its queued input are gone.
238 atomic_store(&g_discarding_covered_input, covered || !drained);
239 return true;
240}
241
242/* Background debug polling can retain an event before a modal screen appears.
243 */
244static keyboard_key_t input_next_key(void) {
245 if (g_sync_key_count) {
246 keyboard_key_t key = g_sync_keys[g_sync_key_head];
247 g_sync_key_head = (g_sync_key_head + 1) % 256;
248 --g_sync_key_count;
249 return key;
250 }
251 return input_read_event();
252}
253
254static bool input_initialize(void) {
255 if (lifecycle_init_once(&g_input_lifecycle)) {
256 if (mutex_init(&g_input_mutex, "ui_input") != 0) {
257 lifecycle_init_abort(&g_input_lifecycle);
258 return false;
259 }
260 if (mutex_init(&g_input_prompt_mutex, "ui_prompt_input") != 0) {
261 mutex_destroy(&g_input_mutex);
262 lifecycle_init_abort(&g_input_lifecycle);
263 return false;
264 }
265 NAMED_REGISTER_ATOMIC(&g_input_lifecycle.state, "ui_input_lifecycle", NULL);
266 g_discarding_covered_input = false;
267 g_switch_pending = false;
268 lifecycle_init_commit(&g_input_lifecycle);
269 }
270 uint64_t deadline = time_get_ns() + NS_PER_SEC_INT;
271 while (atomic_load(&g_input_lifecycle.state) == LIFECYCLE_INITIALIZING) {
272 if (time_get_ns() >= deadline) {
274 "Timed out waiting for terminal input initialization");
275 return false;
276 }
277 platform_sleep_ms(1);
278 }
279 return lifecycle_is_initialized(&g_input_lifecycle);
280}
281
282asciichat_error_t ui_input_take_paste(char *buffer, size_t capacity) {
283 if (!buffer || !capacity || !input_initialize())
284 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid paste buffer");
285 mutex_lock(&g_input_mutex);
287 if (g_events.invalid || g_events.length >= capacity ||
288 !utf8_is_valid(g_events.paste))
290 "Paste media paths or URLs without terminal controls "
291 "(maximum 8191 bytes)");
292 else
293 memcpy(buffer, g_events.paste, g_events.length + 1);
294 g_events.length = 0;
295 sodium_memzero(g_events.paste, sizeof(g_events.paste));
296 g_events.ready = false;
297 input_unlock();
298 return result;
299}
300
302#ifndef NDEBUG
303 if (atomic_load(&g_input_lifecycle.state) == LIFECYCLE_INITIALIZING ||
304 !input_initialize() || !input_ready() ||
305 mutex_trylock(&g_input_mutex) != 0)
306 return;
307 if (g_switch_pending) {
308 input_unlock();
309 return;
310 }
313 keyboard_key_t key = input_read_event();
314 if (key != KEY_PASTE && !log_search_is_entering())
315 key = ui_sync_handle_key(key);
316 if (key && g_sync_key_count < TUI_SYNC_KEY_CAPACITY) {
317 g_sync_keys[(g_sync_key_head + g_sync_key_count++) % 256] = key;
318 g_switch_pending = input_switch_key(key);
319 }
320 }
321 input_unlock();
322#endif
323}
324
325static keyboard_key_t input_common_key(keyboard_key_t key, int current) {
326 if (key == KEY_NONE || key == KEY_PASTE || log_search_is_entering())
327 return key;
329 if (action == TUI_SHORTCUT_STATS) {
330 ascii_otel_ui_usage("stats", "shortcut", 0);
332 return KEY_NONE;
333 }
334 if (action == TUI_SHORTCUT_HELP && current != UI_SCREEN_LOGS) {
336 return KEY_NONE;
337 }
338 bool server = GET_OPTION(detected_mode) == MODE_SERVER ||
339 GET_OPTION(detected_mode) == MODE_DISCOVERY_SERVICE ||
340 GET_OPTION(detected_mode) == MODE_MCP_SERVER;
341 if (action == TUI_SHORTCUT_LOGS && !server) {
342 ascii_otel_ui_usage("logs", "shortcut", 0);
344 return KEY_NONE;
345 }
347 ascii_otel_ui_usage("errno", "shortcut", 0);
349 return KEY_NONE;
350 }
351 if (key == KEY_ESCAPE && current == UI_SCREEN_HELP) {
353 return KEY_NONE;
354 }
355 if (server && current == UI_SCREEN_LOGS) {
356 if (ui_session_logs_key(key))
357 return KEY_NONE;
358 if (key == KEY_ESCAPE || key == 'q') {
360 return KEY_NONE;
361 }
362 }
363 if (server && (key == 'Q' || key == KEY_SHIFT_ESCAPE)) {
365 return KEY_NONE;
366 }
367 if (server && (key == 'q' || key == 3)) {
369 return KEY_NONE;
370 }
371 return key;
372}
373
375 if (!input_initialize())
376 return KEY_NONE;
377 if (!input_ready()) {
378 // Once recovery has an empty input queue, the next key is a fresh action.
379 if (atomic_load(&g_discarding_covered_input) &&
380 !ui_controller_state().covered)
381 atomic_store(&g_discarding_covered_input, false);
382 return KEY_NONE;
383 }
384 mutex_lock(&g_input_mutex);
386 // The previous event has now been dispatched by the session. Background
387 // polling must not overtake a pending switch with the next shortcut.
388 g_switch_pending = false;
389 if (input_discard_covered(state.covered)) {
390 input_unlock();
391 return KEY_NONE;
392 }
393 if (state.screen == UI_SCREEN_HELP &&
396 keyboard_key_t key =
397 keyboard_help_check_signal_cancel() ? KEY_ESCAPE : input_next_key();
398 if (key == KEY_ESCAPE || key == KEY_QUESTION)
400 if (key == KEY_PASTE)
401 g_events.ready = false;
402 input_unlock();
403 return KEY_NONE;
404 }
406 keyboard_key_t key = input_next_key();
407 if (key != KEY_NONE)
409 if (key == KEY_PASTE)
410 g_events.ready = false;
411 input_unlock();
412 return KEY_NONE;
413 }
414 if (state.screen == UI_SCREEN_ERROR) {
415 keyboard_key_t key = input_next_key();
416 if (key == KEY_QUESTION)
418 else if (key != KEY_NONE && key != KEY_PASTE && key != 3) {
420 /* The first q dismisses the modal error. Only a later q, after the
421 * final error is gone, is allowed to reach the session exit handler. */
422 if (key == 'q' && !ui_error_popup_visible()) {
423 input_unlock();
424 return key;
425 }
426 }
427 if (key == KEY_PASTE)
428 g_events.ready = false;
429 input_unlock();
430 return key == 3 ? key : KEY_NONE;
431 }
432 if (state.screen == UI_SCREEN_NOTICE) {
433 g_events.ready = false;
434 g_sync_key_count = 0;
435 keyboard_key_t notice_key = input_read_event();
436 if (notice_key == KEY_PASTE)
437 g_events.ready = false;
438 bool first_use = ui_controller_first_use_key(notice_key);
439 if (!first_use &&
440 (notice_key == KEY_ESCAPE || notice_key == '\r' || notice_key == '\n' ||
441 notice_key == 'q' || notice_key == 3))
443 input_unlock();
444 return notice_key == 'q' || notice_key == 3 ? notice_key : KEY_NONE;
445 }
447 keyboard_key_t update_key = input_read_event();
448 if (update_key == '=' || update_key == KEY_0 ||
449 update_key == KEY_QUESTION || update_key == ']') {
450 if (update_key != KEY_QUESTION)
452 if (update_key == KEY_QUESTION) {
454 } else {
455 update_key = input_common_key(update_key, UI_SCREEN_UPDATE);
456 (void)ui_sync_handle_key(update_key);
457 }
458 } else if (update_key != KEY_NONE)
459 (void)update_banner_handle_key(update_key);
460 input_unlock();
461 return KEY_NONE;
462 }
463 if (screen == UI_SCREEN_MEDIA && g_media_editor.active &&
464 state.screen == UI_SCREEN_PROMPT) {
465 keyboard_key_t key = input_next_key();
466 bool switch_screen = input_switch_key(key) && key != '=' &&
467 (g_media_editor.length == 0 || key == 15);
468#ifndef NDEBUG
469 switch_screen |= key == KEY_0 && g_media_editor.length == 0;
470#endif
471 if (switch_screen) {
472 // Keep the old prompt on screen until its replacement is published.
473 if (key != KEY_QUESTION)
474 g_media_editor.active = false;
475 if (key == KEY_0)
476 key = ui_sync_handle_key(key);
477 key = input_common_key(key, state.screen);
478 g_switch_pending = input_switch_key(key);
479 input_unlock();
480 return key;
481 }
482 if (key == KEY_ESCAPE || key == 3 ||
483 ui_input_expired(g_media_editor.deadline)) {
484 if (key == KEY_PASTE)
485 g_events.ready = false;
487 "media_input_prompt",
488 ui_input_expired(g_media_editor.deadline) ? "timed_out" : "cancelled",
489 0);
490 g_media_editor.active = false;
492 } else if (key == '\r' || key == '\n') {
493 g_media_editor.active = false;
494 g_media_editor.submitted = true;
495 ascii_otel_ui_usage("media_input_prompt", "submitted", 0);
496 input_unlock();
497 return KEY_MEDIA_SUBMIT;
498 } else if (key != KEY_NONE) {
499 if (key == KEY_PASTE)
500 ascii_otel_ui_usage("media_input_prompt", "paste", 0);
501 if (key == KEY_PASTE) {
502 if (!g_events.invalid && utf8_is_valid(g_events.paste)) {
503 media_playlist_t items = {0}, added = {0};
504 bool valid = !g_media_editor.length ||
505 media_playlist_parse(g_media_editor.buffer, &items) ==
507 valid = valid &&
508 media_playlist_parse(g_events.paste, &added) == ASCIICHAT_OK;
509 if (valid) {
510 for (size_t i = 0; i < added.count && valid; ++i)
511 valid = media_playlist_append(&items, added.paths[i],
512 added.urls[i]) == ASCIICHAT_OK;
513 char formatted[sizeof(g_media_editor.buffer)];
514 valid = valid &&
515 media_playlist_format(&items, formatted,
516 sizeof(formatted)) == ASCIICHAT_OK;
517 if (valid) {
518 memcpy(g_media_editor.buffer, formatted, strlen(formatted) + 1);
519 g_media_editor.length = g_media_editor.cursor = strlen(formatted);
520 }
521 }
522 if (valid)
523 ascii_otel_ui_usage("media_input_prompt", "queue_changed", 0);
524 CLEAR_ERRNO();
525 }
526 g_events.ready = false;
527 g_media_editor.pasted = true;
528 } else if (!(key == ' ' && g_media_editor.pasted &&
529 g_media_editor.cursor == g_media_editor.length)) {
530 g_media_editor.pasted = false;
531 ui_input_edit_key(g_media_editor.buffer, sizeof(g_media_editor.buffer),
532 &g_media_editor.length, &g_media_editor.cursor, key);
533 }
534 if (ui_prompt_present_kind("Open media: files or URLs\nDrop more files "
535 "to queue; Enter plays; Esc cancels",
536 g_media_editor.buffer, g_media_editor.cursor,
537 false,
538 UI_PROMPT_MEDIA_INPUT) != ASCIICHAT_OK) {
539 g_media_editor.active = false;
541 CLEAR_ERRNO();
542 }
543 }
544 input_unlock();
545 return KEY_NONE;
546 }
547 bool primary = screen == UI_SCREEN_MEDIA || screen == UI_SCREEN_SPLASH ||
549 bool server = GET_OPTION(detected_mode) == MODE_SERVER ||
550 GET_OPTION(detected_mode) == MODE_DISCOVERY_SERVICE ||
551 GET_OPTION(detected_mode) == MODE_MCP_SERVER;
552 bool server_owner = screen == UI_SCREEN_STATS && server &&
554 bool active =
555 state.screen < 0 || state.screen == (int)screen ||
556 ((primary || server_owner) && state.screen <= UI_SCREEN_SYNC &&
557 state.screen != UI_SCREEN_STATS && state.screen != UI_SCREEN_RECONNECT);
558 keyboard_key_t key = KEY_NONE;
559 if (active) {
560 if (g_sync_key_count) {
561 key = g_sync_keys[g_sync_key_head];
562 g_sync_key_head = (g_sync_key_head + 1) % 256;
563 --g_sync_key_count;
564 }
565 if (key == KEY_NONE)
566 key =
568 ? KEY_QUESTION
569 : input_read_event();
570 if (key == KEY_F12) {
571 // Synchronous prompts own their input, including function keys.
572 // Opening the update checker here would suspend credential entry.
575 key = KEY_NONE;
576 }
577 if (screen != UI_SCREEN_PROMPT) {
578 key = input_common_key(key, state.screen);
579 if (key != KEY_PASTE && !log_search_is_entering() &&
580 !(screen == UI_SCREEN_MDNS && state.screen == UI_SCREEN_MDNS))
581 key = ui_sync_handle_key(key);
582 }
583 }
584 if (key == KEY_PASTE && log_search_is_entering()) {
585 if (!g_events.invalid)
586 (void)log_search_insert_text(g_events.paste);
587 g_events.ready = false;
588 key = KEY_NONE;
589 }
590 if (key == KEY_PASTE && screen != UI_SCREEN_MEDIA &&
592 g_events.ready = false;
593 key = KEY_NONE;
594 }
595 if (screen != UI_SCREEN_PROMPT && key != KEY_NONE &&
597 key = KEY_NONE;
598 g_switch_pending |= input_switch_key(key);
599 input_unlock();
600 return key;
601}
602
603keyboard_key_t ui_input_wait_key(ui_screen_t screen, unsigned timeout_ms) {
604 uint64_t deadline = time_get_ns() + (uint64_t)timeout_ms * NS_PER_MS_INT;
605 do {
606 keyboard_key_t key = ui_input_read_key(screen);
607 if (key != KEY_NONE || shutdown_is_requested())
608 return key;
609 platform_sleep_ns(NS_PER_MS_INT);
610 } while (time_get_ns() < deadline);
611 return KEY_NONE;
612}
613
615 if (!lifecycle_destroy_once(&g_input_lifecycle))
616 return;
617 mutex_destroy(&g_input_prompt_mutex);
618 mutex_destroy(&g_input_mutex);
619 lifecycle_destroy_commit(&g_input_lifecycle);
620}
621
627static asciichat_error_t input_prompt(const char *prompt, char *buffer,
628 size_t max_len, prompt_opts_t opts,
629 bool password_dialog, bool incorrect) {
630 if (!prompt || !buffer || max_len < 2)
631 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid prompt buffer");
632 if (keyboard_init() != ASCIICHAT_OK)
633 return SET_ERRNO(ERROR_PLATFORM_INIT, "Cannot initialize prompt input");
634 const char *usage_name = ui_prompt_kind_name(
635 password_dialog || (opts.kind == UI_PROMPT_INPUT && !opts.echo)
636 ? UI_PROMPT_PASSWORD
637 : opts.kind);
638 if (password_dialog && incorrect)
639 ascii_otel_ui_usage(usage_name, "rejected", 0);
640 char *visible = SAFE_CALLOC(max_len, 1, char *);
641 if (!visible)
642 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate prompt display");
643 if (!input_initialize()) {
644 SAFE_FREE(visible);
645 return SET_ERRNO(ERROR_THREAD, "Cannot initialize prompt input lock");
646 }
647 mutex_lock(&g_input_prompt_mutex);
648 const char *end = memchr(buffer, '\0', max_len);
649 if (!end) {
650 mutex_unlock(&g_input_prompt_mutex);
651 SAFE_FREE(visible);
652 return SET_ERRNO(ERROR_INVALID_PARAM, "Prompt text is too long");
653 }
654 int previous_interactive = ui_controller_interactive_screen();
655 size_t len = (size_t)(end - buffer), cursor = len;
656 unsigned seconds =
657 opts.timeout_seconds ? opts.timeout_seconds : (opts.echo ? 30 : 60);
658 uint64_t deadline = ui_input_deadline(seconds);
659 char timed_prompt[TUI_INPUT_TIMED_PROMPT_BUFFER_SIZE];
660 snprintf(timed_prompt, sizeof(timed_prompt),
661 "%s\n(Timeout: %us; cancels without an answer)", prompt, seconds);
663 bool newline_limit = false, cancelled = false;
664 // Request modifier-aware Enter while this dialog owns terminal input.
665 if (password_dialog) {
666 const char *enable = "\033[>1u\033[>4;2m";
667 platform_write_all(STDERR_FILENO, enable, strlen(enable));
668 }
669 ui_buttons_t buttons = {0};
670 ui_button_t actions[] = {{"[ Confirm ]", 0, false, 0},
671 {"[ Cancel ]", 0, false, 0}};
672 while (!shutdown_is_requested()) {
673 if (ui_input_expired(deadline)) {
674 result = ERROR_PROMPT_TIMEOUT;
675 break;
676 }
677 size_t display_cursor = cursor;
678 if (opts.echo) {
679 memcpy(visible, buffer, len + 1);
680 } else {
681 size_t chars = 0;
682 for (size_t i = 0; i < len; ++i) {
683 if (((unsigned char)buffer[i] & 0xc0) != 0x80)
684 visible[chars++] =
685 password_dialog && buffer[i] == '\n' ? '\n' : opts.mask_char;
686 }
687 visible[opts.mask_char ? chars : 0] = '\0';
688 display_cursor = 0;
689 for (size_t i = 0; i < cursor; ++i)
690 if (((unsigned char)buffer[i] & 0xc0) != 0x80)
691 ++display_cursor;
692 if (!opts.mask_char)
693 display_cursor = 0;
694 }
695 // Presentation owns only the mask; the caller retains the credential.
696 result = password_dialog
698 prompt, visible, display_cursor, buttons.selected,
699 incorrect, len >= MIN_PASSWORD_LENGTH, newline_limit)
701 timed_prompt, visible, display_cursor, !opts.echo,
702 opts.kind == UI_PROMPT_INPUT && !opts.echo
703 ? UI_PROMPT_PASSWORD
704 : opts.kind);
705 if (result != ASCIICHAT_OK)
706 break;
707 keyboard_key_t key = ui_input_wait_key(UI_SCREEN_PROMPT, 100);
708 if (ui_input_expired(deadline)) {
709 result = ERROR_PROMPT_TIMEOUT;
710 break;
711 }
712 if (key == KEY_NONE)
713 continue;
714 newline_limit = false;
715 if (password_dialog && key == KEY_SHIFT_ENTER) {
716 size_t newlines = 0;
717 for (size_t i = 0; i < len; ++i)
718 newlines += buffer[i] == '\n';
719 if (newlines >= 3)
720 newline_limit = true;
721 else
722 (void)ui_input_insert(buffer, max_len, &len, &cursor, "\n");
723 continue;
724 }
725 actions[0].disabled = password_dialog && len < MIN_PASSWORD_LENGTH;
726 if (password_dialog && (key == '\t' || key == '\r' || key == '\n')) {
727 int activated = ui_buttons_key(&buttons, actions, 2, key);
728 if (activated == 0)
729 break;
730 if (activated == 1) {
731 cancelled = true;
732 result = SET_ERRNO(ERROR_CRYPTO_AUTH, "Password entry cancelled");
733 break;
734 }
735 continue;
736 }
737 // Validate the whole paste before editing so rejection cannot leave a
738 // partial password.
739 if (key == KEY_PASTE || key == 22) {
740 char pasted[TUI_INPUT_PASTED_BUFFER_SIZE] = {0};
741 asciichat_error_t pasted_result =
742 key == 22 ? (asciichat_error_t)platform_clipboard_read(pasted,
743 sizeof(pasted))
744 : ui_input_take_paste(pasted, sizeof(pasted));
745 if (pasted_result == ASCIICHAT_OK) {
746 if (key == 22) {
747 size_t write = 0;
748 for (size_t read = 0; pasted[read]; ++read) {
749 if (pasted[read] == '\r' && pasted[read + 1] == '\n')
750 continue;
751 pasted[write++] = pasted[read] == '\r' ? '\n' : pasted[read];
752 }
753 pasted[write] = '\0';
754 }
755 size_t newlines = 0;
756 for (size_t i = 0; i < len; ++i)
757 newlines += buffer[i] == '\n';
758 for (size_t i = 0; pasted[i]; ++i)
759 newlines += pasted[i] == '\n';
760 if (password_dialog && newlines > 3)
761 newline_limit = true;
762 else if (!strpbrk(pasted, password_dialog ? "\r\t" : "\r\n\t") &&
763 strlen(pasted) + len < max_len)
764 (void)ui_input_insert(buffer, max_len, &len, &cursor, pasted);
765 else
766 CLEAR_ERRNO();
767 } else {
768 CLEAR_ERRNO();
769 }
770 // Clipboard and terminal paste buffers can contain unmasked credentials.
771 sodium_memzero(pasted, sizeof(pasted));
772 continue;
773 }
774 if (key == '\r' || key == '\n') {
775 if (!password_dialog || len >= MIN_PASSWORD_LENGTH)
776 break;
777 continue;
778 }
779 if (key == KEY_ESCAPE || key == 3) {
780 cancelled = true;
781 result = SET_ERRNO(ERROR_GENERAL, "Prompt cancelled");
782 break;
783 }
784 ui_input_edit_key(buffer, max_len, &len, &cursor, key);
785 }
787 result = SET_ERRNO(ERROR_GENERAL, "Prompt interrupted");
788 ascii_otel_ui_usage(usage_name,
789 result == ASCIICHAT_OK ? "submitted"
790 : result == ERROR_PROMPT_TIMEOUT ? "timed_out"
791 : shutdown_is_requested() ? "interrupted"
792 : cancelled ? "cancelled"
793 : "failed",
794 0);
795 ui_prompt_dismiss(previous_interactive);
796 if (password_dialog) {
797 const char *disable = "\033[<u\033[>4;0m";
798 platform_write_all(STDERR_FILENO, disable, strlen(disable));
799 }
800 mutex_unlock(&g_input_prompt_mutex);
801 SAFE_FREE(visible);
802 if (result == ERROR_PROMPT_TIMEOUT)
803 ui_input_timeout_report(seconds, opts.echo ? "answer declined"
804 : "password entry cancelled");
805 if (result != ASCIICHAT_OK)
806 sodium_memzero(buffer, max_len);
807 return result;
808}
809
810asciichat_error_t ui_input_prompt_prefilled(const char *prompt, char *buffer,
811 size_t max_len,
812 prompt_opts_t opts) {
813 return input_prompt(prompt, buffer, max_len, opts, false, false);
814}
815
816asciichat_error_t ui_input_password(const char *target, char *buffer,
817 size_t capacity, bool incorrect) {
818 if (!target || !buffer || capacity < 2)
819 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid password dialog");
820 sodium_memzero(buffer, capacity);
821 if (env_pop_prompt_response(buffer, capacity))
822 return ASCIICHAT_OK;
824 return SET_ERRNO(
826 "Server password requires an interactive terminal or --password");
827 asciichat_error_t result = input_prompt(
828 target, buffer, capacity, PROMPT_OPTS_PASSWORD, true, incorrect);
829 if (result != ASCIICHAT_OK) {
832 return SET_ERRNO(ERROR_CRYPTO_AUTH, "Password entry cancelled");
833 }
834 return result;
835}
836
837asciichat_error_t ui_input_prompt(const char *prompt, char *buffer,
838 size_t max_len, prompt_opts_t opts) {
839 if (buffer && max_len)
840 buffer[0] = '\0';
841 return ui_input_prompt_prefilled(prompt, buffer, max_len, opts);
842}
843
845 if (!text || !utf8_is_valid(text) ||
846 strlen(text) >= sizeof(g_media_editor.buffer) || !input_initialize())
847 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid media prompt text");
848 mutex_lock(&g_input_mutex);
849 memset(&g_media_editor, 0, sizeof(g_media_editor));
850 memcpy(g_media_editor.buffer, text, strlen(text) + 1);
851 g_media_editor.length = g_media_editor.cursor = strlen(text);
852 g_media_editor.deadline = ui_input_deadline(120);
853 asciichat_error_t result =
854 ui_prompt_present_kind("Open media: files or URLs\nDrop more files to "
855 "queue; Enter plays; Esc cancels",
856 g_media_editor.buffer, g_media_editor.cursor,
857 false, UI_PROMPT_MEDIA_INPUT);
858 g_media_editor.active = result == ASCIICHAT_OK;
859 input_unlock();
860 return result;
861}
862
863asciichat_error_t ui_input_media_take(char *output, size_t capacity) {
864 if (!output || !input_initialize())
865 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid media prompt destination");
866 mutex_lock(&g_input_mutex);
868 if (!g_media_editor.submitted || g_media_editor.length >= capacity)
869 result = SET_ERRNO(ERROR_INVALID_STATE, "No submitted media prompt");
870 else {
871 memcpy(output, g_media_editor.buffer, g_media_editor.length + 1);
873 media_playlist_t playlist = {0};
874 if (media_playlist_parse(output, &playlist) == ASCIICHAT_OK) {
875 bool file = false, url = false;
876 for (size_t i = 0; i < playlist.count; ++i) {
877 file |= !playlist.urls[i];
878 url |= playlist.urls[i];
879 }
880 if (file)
881 ascii_otel_ui_usage("media_input_prompt", "source_file", 0);
882 if (url)
883 ascii_otel_ui_usage("media_input_prompt", "source_url", 0);
884 ascii_otel_ui_usage("media_input_prompt", "queue_submitted", 0);
885 } else {
886 ascii_otel_ui_usage("media_input_prompt", "rejected", 0);
887 }
889 }
890 g_media_editor.submitted = false;
891 input_unlock();
892 return result;
893}
Application-level callbacks for library code.
#define APP_CALLBACK_VOID(callback_name)
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_scope_begin(void)
#define SET_ERRNO(code,...)
#define CLEAR_ERRNO()
@ ASCIICHAT_ERRNO_DISMISSED
Common buffer size definitions.
int ui_buttons_key(ui_buttons_t *s, const ui_button_t *b, size_t n, keyboard_key_t key)
Definition buttons.c:8
Named object registry for debugging — log identifiable resource names.
bool env_pop_prompt_response(char *response_out, size_t response_size)
Pop the first response from ASCII_CHAT_QUESTION_PROMPT_RESPONSE stack.
Definition env.c:98
Environment variable utilities with stack-based prompt responses.
void ui_errno_stacks_toggle(void)
bool ui_error_popup_visible(void)
Definition error_popup.c:74
void ui_error_popup_key(keyboard_key_t key)
Definition error_popup.c:88
bool valid
Definition fft.c:29
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_PLATFORM_INIT
Definition error_codes.h:59
@ ERROR_PROMPT_TIMEOUT
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_GENERAL
Definition error_codes.h:51
@ ERROR_CRYPTO_AUTH
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
#define GET_OPTION(field)
Definition options.h:1339
@ MODE_MCP_SERVER
Model Context Protocol rendering server.
Definition options.h:922
@ MODE_DISCOVERY_SERVICE
Discovery server mode - session management and WebRTC signaling.
Definition options.h:920
@ MODE_SERVER
Server mode - network server options.
Definition options.h:917
void keyboard_help_toggle_terminal(int fd)
int keyboard_help_parent_screen(void)
bool update_banner_handle_key(int key)
bool keyboard_help_check_signal_cancel(void)
Check if help screen closure was requested by signal handler.
void update_banner_toggle_overlay(void)
bool update_banner_is_overlay_open(void)
void shutdown_request(void)
Definition common.c:85
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:87
bool utf8_is_valid(const char *str)
Check if a string is valid UTF-8.
Definition utf8.c:132
⚙️ Common definitions, error codes, macros, and types shared throughout the application
keyboard_key_t keyboard_read_nonblocking(void)
Definition keyboard.c:11
bool keyboard_input_available(void)
Definition keyboard.c:7
🆘 Interactive keyboard help overlay for session keyboard shortcuts
bool ui_session_logs_key(keyboard_key_t key)
void signal_exit(void)
Definition main.c:262
bool platform_is_interactive(void)
deferred_action_t action
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
void ascii_otel_ui_usage(const char *screen, const char *event, uint64_t duration_ns)
Definition otel.c:506
asciichat_error_t media_playlist_format(const media_playlist_t *list, char *text, size_t capacity)
Definition playlist.c:103
asciichat_error_t media_playlist_append(media_playlist_t *list, const char *path, bool url)
Definition playlist.c:7
asciichat_error_t media_playlist_parse(const char *text, media_playlist_t *list)
Definition playlist.c:40
asciichat_error_t ui_password_prompt_present(const char *target, const char *masked, size_t cursor, size_t selected_button, bool incorrect, bool can_confirm, bool newline_limit)
Definition prompt.c:388
void ui_prompt_remove(void)
Definition prompt.c:355
asciichat_error_t ui_prompt_present_kind(const char *prompt, const char *visible, size_t cursor, bool secret, ui_prompt_kind_t kind)
Definition prompt.c:309
const char * ui_prompt_kind_name(ui_prompt_kind_t kind)
Definition prompt.c:272
void ui_prompt_dismiss(int previous)
Definition prompt.c:349
void stats_runtime_toggle(void)
Definition runtime.c:99
bool log_search_is_entering(void)
Check if currently in input mode (typing pattern).
Definition search.c:423
asciichat_error_t log_search_insert_text(const char *text)
Definition search.c:501
Interactive search filtering for terminal screens.
tui_shortcut_t tui_shortcut_action(keyboard_key_t key)
Definition shortcuts.c:61
tui_shortcut_t
Definition shortcuts.h:8
@ TUI_SHORTCUT_LOGS
Definition shortcuts.h:11
@ TUI_SHORTCUT_MEDIA
Definition shortcuts.h:16
@ TUI_SHORTCUT_HELP
Definition shortcuts.h:10
@ TUI_SHORTCUT_STATS
Definition shortcuts.h:12
@ TUI_SHORTCUT_ERRORS
Definition shortcuts.h:14
Shutdown check system for clean library/application separation.
#define MIN_PASSWORD_LENGTH
Minimum password length (8 characters).
Definition sizes.h:24
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
uint64_t deadline
Definition tui/input.c:183
char buffer[8192]
Definition tui/input.c:181
bool urls[64]
Definition playlist.h:15
char paths[64][256]
Definition playlist.h:14
keyboard_key_t keys[8192]
Definition tui/input.h:53
char paste[8192]
Definition tui/input.h:51
bool disabled
Definition buttons.h:12
When code needs to work with ui button, it keeps label, shortcut, disabled, color here instead of sca...
Definition buttons.h:24
size_t selected
Definition buttons.h:25
void platform_force_exit(int)
keyboard_key_t ui_sync_handle_key(keyboard_key_t key)
Definition sync.c:388
bool terminal_screen_logs_help_open(void)
bool terminal_screen_logs_handle_key(int key)
Reusable "fixed header + scrolling logs" terminal screen abstraction.
⏱️ High-precision timing utilities using sokol_time.h and uthash
void ui_controller_remove(ui_screen_t screen)
bool ui_controller_first_use_key(int key)
void ui_controller_toggle_logs(void)
int ui_controller_current_screen(void)
void ui_controller_hide_logs(void)
int ui_controller_interactive_screen(void)
bool ui_controller_is_blocked(void)
ui_presentation_state_t ui_controller_state(void)
bool ui_controller_screen_live(ui_screen_t screen)
int ui_controller_active_fd(void)
ui_screen_t
@ UI_SCREEN_PROMPT
@ UI_SCREEN_NOTICE
@ UI_SCREEN_LOGS
@ UI_SCREEN_MEDIA
@ UI_SCREEN_RECONNECT
@ UI_SCREEN_STATS
@ UI_SCREEN_UPDATE
@ UI_SCREEN_SYNC
@ UI_SCREEN_SPLASH
@ UI_SCREEN_STATUS
@ UI_SCREEN_MDNS
@ UI_SCREEN_HELP
@ UI_SCREEN_ERROR
void ui_input_poll_sync(void)
Definition tui/input.c:301
keyboard_key_t tui_input_events_read(tui_input_events_t *s, keyboard_key_t(*read_key)(void), bool(*classify_paste)(const char *))
Definition tui/input.c:85
#define TUI_INPUT_MESSAGE_BUFFER_SIZE
Definition tui/input.c:3
#define TUI_SYNC_KEY_CAPACITY
Definition tui/input.c:10
keyboard_key_t ui_input_wait_key(ui_screen_t screen, unsigned timeout_ms)
Definition tui/input.c:603
keyboard_key_t ui_input_read_key(ui_screen_t screen)
Definition tui/input.c:374
asciichat_error_t ui_input_prompt_prefilled(const char *prompt, char *buffer, size_t max_len, prompt_opts_t opts)
Definition tui/input.c:810
asciichat_error_t ui_input_media_take(char *output, size_t capacity)
Definition tui/input.c:863
void ui_input_shutdown(void)
Definition tui/input.c:614
#define TUI_INPUT_BUFFER_BUFFER_SIZE
Definition tui/input.c:5
#define TUI_INPUT_TIMED_PROMPT_BUFFER_SIZE
Definition tui/input.c:6
asciichat_error_t ui_input_take_paste(char *buffer, size_t capacity)
Definition tui/input.c:282
asciichat_error_t ui_input_media_begin(const char *text)
Definition tui/input.c:844
asciichat_error_t ui_input_prompt(const char *prompt, char *buffer, size_t max_len, prompt_opts_t opts)
Definition tui/input.c:837
#define TUI_INPUT_BURST_BUFFER_SIZE
Definition tui/input.c:4
void ui_input_timeout_report(unsigned seconds, const char *consequence)
Definition tui/input.c:54
uint64_t ui_input_deadline(unsigned seconds)
Definition tui/input.c:48
asciichat_error_t ui_input_password(const char *target, char *buffer, size_t capacity, bool incorrect)
Definition tui/input.c:816
bool ui_input_expired(uint64_t deadline)
Definition tui/input.c:52
#define TUI_INPUT_PASTED_BUFFER_SIZE
Definition tui/input.c:7
asciichat_error_t ui_input_insert(char *buffer, size_t capacity, size_t *length, size_t *cursor, const char *text)
Definition ui/input.c:145
void ui_input_edit_key(char *buffer, size_t capacity, size_t *length, size_t *position, keyboard_key_t key)
Definition ui/input.c:95
Update available prompt screen shown after splash.
🔤 UTF-8 Encoding and Decoding Utilities