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/controller.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define TUI_CONTROLLER_LAST_TITLE_BUFFER_SIZE 512
4#define TUI_CONTROLLER_TITLE_BUFFER_SIZE 512
5#define TUI_CONTROLLER_BUFFER_BUFFER_SIZE 16384
6
7/* Existing buffer budgets in bytes, including NUL for text storage. */
8#define TUI_MEDIA_SNAPSHOT_CAPACITY 8
9#define TUI_LAYER_CAPACITY 3
10
11#include <ascii-chat/common.h>
14#include <ascii-chat/otel.h>
24#include <ascii-chat/tui/sync.h>
31#include <ascii-chat/ui/text.h>
37#include <libplatform/atomic.h>
38#include <libplatform/compiler.h>
39#include <libplatform/cond.h>
40#include <libplatform/keyboard.h>
41#include <libplatform/lifecycle.h>
42#include <libplatform/system.h>
43#include <libplatform/terminal.h>
44#include <libplatform/thread.h>
45#include <options/options.h>
46#include <options/runtime.h>
47#include <stdarg.h>
48#include <stdatomic.h>
49#include <stddef.h>
50#include <stdio.h>
51#include <string.h>
52
53typedef struct {
54 _Atomic unsigned references;
55 int fd;
59
61
81
88
89typedef struct {
90 int fd;
91 bool media;
92 terminal_size_t dimensions;
93 size_t len;
94 const char *text;
102static void render_text(terminal_size_t size, const void *data);
103
113
114static screen_t g_screens[UI_SCREEN_COUNT];
115static ui_session_t *g_session;
116static _Thread_local frame_buffer_t *g_capture;
117static _Thread_local const animation_sample_t *g_animation;
118static lifecycle_t g_lifecycle = LIFECYCLE_INIT;
119static mutex_t g_mutex;
120static mutex_t g_title_packet_mutex;
121static cond_t g_render_done;
122static cond_t g_render_requested;
123static int g_rendering_screen = -1;
124static uint32_t g_rendering_layers;
125static uint64_t g_render_started;
126static uint64_t g_render_completed;
127static platform_thread_t g_thread;
128static atomic_t g_presentation_stop_requested = {0};
129static _Atomic bool g_sync_finishing;
130static _Atomic bool g_sync_rendering;
131static _Thread_local bool g_owner;
132static _Thread_local int g_render_fd = -1;
133static _Thread_local screen_snapshot_t *g_render_snapshot;
134static _Thread_local terminal_size_t g_render_size;
135// Input readers need geometry and minimums, never a borrowed screen snapshot.
136static _Atomic uint64_t g_size = UINT64_C(80) | (UINT64_C(24) << 32);
137// Lower bits identify published slots; upper bits identify covered slots.
138static _Atomic uint64_t g_input_state;
139_Static_assert(UI_SCREEN_COUNT <= 32,
140 "Input publication reserves 32 bits per screen mask");
141
142static uint64_t pack_size(terminal_size_t size) {
143 return (uint32_t)size.cols | ((uint64_t)(uint32_t)size.rows << 32);
144}
145
146static terminal_size_t unpack_size(uint64_t packed) {
147 return (terminal_size_t){.cols = (int)(uint32_t)packed,
148 .rows = (int)(uint32_t)(packed >> 32)};
149}
150
151static void publish_input_state_locked(void) {
152 terminal_size_t size = unpack_size(atomic_load(&g_size));
153 uint64_t state = 0;
154 for (int i = 0; i < UI_SCREEN_COUNT; ++i) {
155 if (!g_screens[i].render)
156 continue;
157 terminal_size_t minimum = g_screens[i].minimum;
158 if (i == UI_SCREEN_PROMPT)
159 minimum.rows = ui_prompt_required_rows(g_screens[i].snapshot, size.cols);
160 state |= UINT64_C(1) << i;
161 if (size.cols <= 0 || size.rows <= 0 || ui_too_small(size, minimum))
162 state |= UINT64_C(1) << (i + 32);
163 }
164 if (atomic_load(&g_input_state) != state)
165 atomic_store(&g_input_state, state);
166}
167
168static int g_active = -1;
169static _Atomic int g_interactive_screen = -1;
170static _Atomic int g_background_screen = -1;
171static _Atomic uint32_t g_screen_mask;
172static atomic_t g_volume_until = {0};
173/* The UI controller owns the terminal while any full-screen presentation is
174 * live. */
175static bool g_terminal_screen_active;
176static int g_terminal_screen_fd = -1;
177static _Thread_local bool g_render_volume;
178static _Thread_local bool g_volume_caps_valid;
179static _Thread_local terminal_capabilities_t g_volume_caps;
180static _Thread_local terminal_color_mode_t g_volume_color_mode;
181static _Thread_local color_setting_t g_volume_color_setting;
182static _Thread_local utf8_setting_t g_volume_utf8_setting;
183static _Thread_local terminal_render_mode_t g_volume_render_mode;
184
185static terminal_capabilities_t volume_capabilities(void) {
186 terminal_color_mode_t mode = GET_OPTION(color_mode);
187 color_setting_t color = GET_OPTION(color);
188 utf8_setting_t utf8 = GET_OPTION(force_utf8);
189 terminal_render_mode_t render = GET_OPTION(render_mode);
190 if (!g_volume_caps_valid || mode != g_volume_color_mode ||
191 color != g_volume_color_setting || utf8 != g_volume_utf8_setting ||
192 render != g_volume_render_mode) {
193 g_volume_caps = apply_color_mode_override(
196 g_volume_color_mode = mode;
197 g_volume_color_setting = color;
198 g_volume_utf8_setting = utf8;
199 g_volume_render_mode = render;
200 g_volume_caps_valid = true;
201 }
202 return g_volume_caps;
203}
204
205static void terminal_screen_enter(int fd) {
206 if (!platform_isatty(fd) || GET_OPTION(snapshot_mode))
207 return;
208 const char sequence[] = "\033[?1049h\033[?25l\033[H\033[2J";
209 size_t written = platform_write_all(fd, sequence, sizeof(sequence) - 1);
210 if (written > 0) {
211 g_terminal_screen_active = true;
212 g_terminal_screen_fd = fd;
213 }
214 if (written != sizeof(sequence) - 1)
215 log_error("Cannot completely enter alternate terminal screen");
216}
217
218static void terminal_screen_leave(void) {
219 if (!g_terminal_screen_active || g_terminal_screen_fd < 0)
220 return;
221 const char sequence[] = "\033[0m\033[?25h\033[?1049l";
222 size_t written =
223 platform_write_all(g_terminal_screen_fd, sequence, sizeof(sequence) - 1);
224 if (written == sizeof(sequence) - 1) {
225 g_terminal_screen_active = false;
226 g_terminal_screen_fd = -1;
227 } else {
228 log_error("Cannot completely restore the normal terminal screen");
229 }
230}
231
233 if (!GET_OPTION(snapshot_mode))
234 atomic_store_u64(&g_volume_until, time_get_ns() + 1500 * NS_PER_MS_INT);
235}
236
237static void append_volume(frame_buffer_t *buffer, terminal_size_t size) {
238 if (size.cols < 8 || size.rows < 6)
239 return;
240 double volume = GET_OPTION(speakers_volume);
241 if (volume < 0.0)
242 volume = 0.0;
243 if (volume > 1.0)
244 volume = 1.0;
245 int height = size.rows - 4;
246 if (height > 10)
247 height = 10;
248 int filled = (int)(volume * height + 0.5);
249 int top = (size.rows - height - 1) / 2 + 1;
250 int col = size.cols - 5;
251 terminal_capabilities_t caps = volume_capabilities();
252 bool color = caps.color_level != TERM_COLOR_NONE &&
254 bool utf8 = terminal_should_use_utf8(GET_OPTION(force_utf8));
255 frame_buffer_append(buffer,
256 "\033"
257 "7"
258 "\033[0m",
259 6);
260 for (int row = 0; row < height; ++row) {
261 int level = height - row;
262 bool lit = level <= filled;
263 log_color_t shade = level * 3 <= height ? LOG_COLOR_ERROR
264 : level * 3 <= height * 2 ? LOG_COLOR_WARN
266 frame_buffer_printf(buffer, "\033[%d;%dH", top + row, col);
267 if (color)
268 frame_buffer_printf(buffer, "%s",
269 ui_text_color_prefix(lit ? shade : LOG_COLOR_GREY));
270 const char *cells = utf8 ? (lit ? "██" : "░░") : (lit ? "##" : "..");
271 frame_buffer_printf(buffer, " %s \033[0m", cells);
272 }
273 frame_buffer_printf(buffer, "\033[%d;%dH", top + height, col);
274 if (volume <= 0.01)
275 frame_buffer_append(buffer, "MUTE", 4);
276 else
277 frame_buffer_printf(buffer, "%3d%%", (int)(volume * 100.0 + 0.5));
278 frame_buffer_append(buffer,
279 "\033[0m"
280 "\033"
281 "8",
282 6);
283}
284
286 int background = atomic_load(&g_background_screen);
287 int interactive = atomic_load(&g_interactive_screen);
288 if (interactive == UI_SCREEN_HELP &&
289 (atomic_load(&g_screen_mask) & (1u << UI_SCREEN_HELP)) &&
290 (background != UI_SCREEN_UPDATE ||
293 return UI_SCREEN_HELP;
294 if ((background >= 0 || interactive >= 0) && ui_error_popup_visible())
295 return UI_SCREEN_ERROR;
296 if (interactive < 0 && background < UI_SCREEN_MDNS &&
297 (atomic_load(&g_screen_mask) & (1u << UI_SCREEN_MDNS)))
298 return UI_SCREEN_MDNS;
299 return background > interactive ? background : interactive;
300}
301
302static atomic_int g_default_fd = STDOUT_FILENO;
303
305 int fd = atomic_load(&g_default_fd);
306 if (!lifecycle_is_initialized(&g_lifecycle))
307 return fd;
308 mutex_lock(&g_mutex);
309 if (g_active >= 0 && g_active < UI_SCREEN_COUNT && g_screens[g_active].render)
310 fd = g_screens[g_active].fd;
311 mutex_unlock(&g_mutex);
312 return fd;
313}
314
315static bool interactive_screen(int screen) {
316 return screen == UI_SCREEN_HELP || screen == UI_SCREEN_LOGS ||
320}
321
323 return atomic_load(&g_interactive_screen);
324}
325
327 atomic_store(&g_interactive_screen, screen);
328}
329
330static int selected_screen_excluding_locked(int excluded) {
331 uint32_t visible = 0;
332 int interactive = ui_controller_interactive_screen();
333 if (interactive == UI_SCREEN_HELP)
335 for (int i = 0; i < UI_SCREEN_COUNT; ++i)
336 if (i != excluded && g_screens[i].render &&
337 (!interactive_screen(i) || i == interactive ||
338 (interactive < 0 && i == UI_SCREEN_MDNS)))
339 visible |= 1u << i;
340 if (excluded != UI_SCREEN_HELP &&
342 g_screens[UI_SCREEN_HELP].render) {
343 // F12 covers existing help; help opened from the update checker covers it
344 // in turn.
345 if (excluded != UI_SCREEN_UPDATE && g_screens[UI_SCREEN_UPDATE].render &&
348 return UI_SCREEN_UPDATE;
349 return UI_SCREEN_HELP;
350 }
351 int selected = ui_session_select_screen(visible);
352 // Sync presents from its independent mailbox. Never fall through to media
353 // if it was selected after the presentation loop checked that mailbox.
354 return interactive == UI_SCREEN_SYNC && selected < UI_SCREEN_SYNC ? -1
355 : selected;
356}
357
358static int selected_screen_locked(void) {
359 return selected_screen_excluding_locked(-1);
360}
361
362static void publish_screen_locked(void) {
363 publish_input_state_locked();
364 uint32_t background = 0, live = 0;
365 for (int i = 0; i < UI_SCREEN_COUNT; ++i) {
366 if (g_screens[i].render) {
367 live |= 1u << i;
368 if (!interactive_screen(i))
369 background |= 1u << i;
370 }
371 }
372 atomic_store(&g_screen_mask, live);
373 int selected = ui_session_select_screen(background);
374 if (atomic_load(&g_background_screen) != selected)
375 atomic_store(&g_background_screen, selected);
376 cond_signal(&g_render_requested);
377}
378static bool g_redraw;
379static bool g_finished;
380static uint64_t g_media_frame_id;
381static _Atomic uint64_t g_media_epoch;
382static atomic_t g_sync_initialized = {0};
383static _Thread_local uint64_t g_acquisition_started_ns;
384static _Thread_local bool g_probe_frame;
385static _Thread_local uint64_t g_probe_requested_ns;
386static _Thread_local fps_counter_t *g_fps;
387static atomic_t g_effective_fps = {.impl = 60};
388
390 g_acquisition_started_ns = started_ns;
391}
392
393void ui_controller_set_effective_fps(unsigned int fps) {
394 atomic_store_int(&g_effective_fps, (int)(fps > 0 ? fps : 60));
395 if (g_fps)
397}
398static atomic_t g_blocked = {0};
399static atomic_t g_live = {0};
400static _Thread_local bool g_help_sync_open;
401static _Thread_local bool g_stats_media, g_stats_failed,
402 g_media_overlay_written;
403static _Thread_local uint64_t g_stats_write_ns, g_stats_writes,
404 g_stats_max_chunk_ns, g_stats_chunks;
405static void stats_media_begin(bool media) {
406 g_stats_media = media;
407 g_stats_failed = false;
408 g_stats_write_ns = g_stats_writes = g_stats_max_chunk_ns = g_stats_chunks = 0;
409 g_media_overlay_written = false;
410 g_probe_frame = false;
411 g_probe_requested_ns = 0;
412}
413static void stats_media_end(void) {
414 if (g_stats_media && g_stats_writes) {
416 g_stats_write_ns);
418 g_stats_failed ? STATS_COUNTER_FRAMES_DROPPED
420 1);
421 }
422 g_stats_media = false;
423}
424
425static bool trace_terminal_calls(void) {
426 static _Thread_local int trace_writes;
427 if (!trace_writes) {
428 const char *value = SAFE_GETENV("ASCII_CHAT_TRACE_TERMINAL_WRITES");
429 trace_writes = value && strcmp(value, "1") == 0 ? 1 : -1;
430 }
431 return trace_writes > 0;
432}
433
434static bool read_terminal_size(int fd, terminal_size_t *size) {
435 bool trace = trace_terminal_calls();
436 static _Thread_local uint64_t sequence;
437 uint64_t id = trace ? ++sequence : 0;
438 if (trace)
439 log_file_msg("TERMINAL_CALL_BEGIN: thread=%llu sequence=%llu "
440 "call=terminal_get_size_fd fd=%d at_ns=%llu",
441 (unsigned long long)thread_current_id(),
442 (unsigned long long)id, fd, (unsigned long long)time_get_ns());
443 uint64_t started_ns = trace ? time_get_ns() : 0;
444 int result = terminal_get_size_fd(fd, size);
445 uint64_t returned_ns = trace ? time_get_ns() : 0;
446 if (trace)
447 log_file_msg("TERMINAL_CALL_END: thread=%llu sequence=%llu "
448 "call=terminal_get_size_fd fd=%d result=%d cols=%d rows=%d "
449 "elapsed_ms=%.3f at_ns=%llu",
450 (unsigned long long)thread_current_id(),
451 (unsigned long long)id, fd, result,
452 result == 0 ? size->cols : 0, result == 0 ? size->rows : 0,
453 (double)(returned_ns - started_ns) / NS_PER_MS_INT,
454 (unsigned long long)returned_ns);
455 return result == ASCIICHAT_OK;
456}
457
458static size_t write_output_chunk(int fd, const void *data, size_t length) {
459 uint64_t started_ns = g_stats_media ? time_get_ns() : 0;
460 static _Thread_local uint64_t trace_sequence;
461 bool trace = g_stats_media && trace_terminal_calls();
462 uint64_t sequence = trace ? ++trace_sequence : 0;
463 if (trace)
464 log_file_msg("MEDIA_WRITE_BEGIN: thread=%llu sequence=%llu chunk=%llu "
465 "fd=%d requested=%zu at_ns=%llu",
466 (unsigned long long)thread_current_id(),
467 (unsigned long long)sequence,
468 (unsigned long long)g_stats_chunks, fd, length,
469 (unsigned long long)time_get_ns());
470#ifndef NDEBUG
471 static _Thread_local bool test_delay_checked, test_delay;
472 if (!test_delay_checked) {
473 const char *value = SAFE_GETENV("ASCII_CHAT_TEST_SLOW_MEDIA_OUTPUT");
474 test_delay = value && strcmp(value, "1") == 0;
475 test_delay_checked = true;
476 }
477 if (g_stats_media && test_delay && length > 1024)
478 platform_sleep_ms(25);
479#endif
480 // A presentation write must not split an image protocol packet emitted by
481 // another thread. Non-owner logging must remain nonblocking here.
482 if (trace)
483 log_file_msg("TERMINAL_CALL_BEGIN: thread=%llu sequence=%llu "
484 "call=ui_controller_packet_begin fd=%d at_ns=%llu",
485 (unsigned long long)thread_current_id(),
486 (unsigned long long)sequence, fd,
487 (unsigned long long)time_get_ns());
488 uint64_t lock_started_ns = trace ? time_get_ns() : 0;
489 if (g_owner)
491 uint64_t acquired_ns = trace ? time_get_ns() : 0;
492 if (trace) {
494 "TERMINAL_CALL_END: thread=%llu sequence=%llu "
495 "call=ui_controller_packet_begin fd=%d elapsed_ms=%.3f at_ns=%llu",
496 (unsigned long long)thread_current_id(), (unsigned long long)sequence,
497 fd, (double)(acquired_ns - lock_started_ns) / NS_PER_MS_INT,
498 (unsigned long long)acquired_ns);
499 log_file_msg("TERMINAL_CALL_BEGIN: thread=%llu sequence=%llu "
500 "call=platform_write_all fd=%d requested=%zu at_ns=%llu",
501 (unsigned long long)thread_current_id(),
502 (unsigned long long)sequence, fd, length,
503 (unsigned long long)time_get_ns());
504 }
505 uint64_t write_started_ns = trace ? time_get_ns() : 0;
506 size_t written = platform_write_all(fd, data, length);
507 uint64_t returned_ns = trace ? time_get_ns() : 0;
508 if (trace) {
510 "TERMINAL_CALL_END: thread=%llu sequence=%llu call=platform_write_all "
511 "fd=%d requested=%zu written=%zu elapsed_ms=%.3f at_ns=%llu",
512 (unsigned long long)thread_current_id(), (unsigned long long)sequence,
513 fd, length, written,
514 (double)(returned_ns - write_started_ns) / NS_PER_MS_INT,
515 (unsigned long long)returned_ns);
516 log_file_msg("TERMINAL_CALL_BEGIN: thread=%llu sequence=%llu "
517 "call=ui_controller_packet_end fd=%d at_ns=%llu",
518 (unsigned long long)thread_current_id(),
519 (unsigned long long)sequence, fd,
520 (unsigned long long)time_get_ns());
521 }
522 uint64_t unlock_started_ns = trace ? time_get_ns() : 0;
523 if (g_owner)
525 if (trace)
527 "TERMINAL_CALL_END: thread=%llu sequence=%llu "
528 "call=ui_controller_packet_end fd=%d elapsed_ms=%.3f at_ns=%llu",
529 (unsigned long long)thread_current_id(), (unsigned long long)sequence,
530 fd, (double)(time_get_ns() - unlock_started_ns) / NS_PER_MS_INT,
531 (unsigned long long)time_get_ns());
532 if (g_stats_media) {
533 uint64_t elapsed_ns = time_get_ns() - started_ns;
534 if (elapsed_ns > g_stats_max_chunk_ns)
535 g_stats_max_chunk_ns = elapsed_ns;
536 ++g_stats_chunks;
537 if (elapsed_ns >= 50 * NS_PER_MS_INT || written != length)
538 log_debug("MEDIA_WRITE_CHUNK: frame=%llu fd=%d requested=%zu written=%zu "
539 "elapsed_ms=%.2f",
540 g_render_snapshot
541 ? (unsigned long long)g_render_snapshot->frame_id
542 : 0ULL,
543 fd, length, written, (double)elapsed_ns / NS_PER_MS_INT);
544 }
545 return written;
546}
547
548// Media frames contain complete newline-separated rows; clipped frames end
549// each row with EL. Splitting after a row keeps CSI and UTF-8 sequences intact.
550static size_t media_chunk_boundary(const char *data, size_t length) {
551 if (!data || length == 0)
552 return 0;
553 const char *end = data + length;
554 const char *last = NULL;
555 for (const char *p = data; p < end;) {
556 const char *newline = memchr(p, '\n', (size_t)(end - p));
557 if (!newline)
558 break;
559 last = newline + 1;
560 p = last;
561 }
562 for (const char *p = data; p < end;) {
563 const char *k = memchr(p, 'K', (size_t)(end - p));
564 if (!k)
565 break;
566 if (k - data >= 2 && k[-2] == '\033' && k[-1] == '[' &&
567 (!last || k + 1 > last))
568 last = k + 1;
569 p = k + 1;
570 }
571 return last ? (size_t)(last - data) : 0;
572}
573
574size_t ui_controller_trim_utf8_chunk(const char *data, size_t length) {
575 while (data && length && ((unsigned char)data[length - 1] & 0xc0) == 0x80)
576 --length;
577 return length;
578}
579
580asciichat_error_t ui_controller_write(int fd, const char *data, size_t len) {
581 if (!data || !len)
582 return ASCIICHAT_OK;
583 if (g_capture) {
584 frame_buffer_append(g_capture, data, len);
585 return ASCIICHAT_OK;
586 }
587 // Logging may call this while holding subsystem locks; never wait for a
588 // renderer callback here. Live screens already capture logs in their model.
589 if (!g_owner && ui_controller_is_presenting())
590 return ASCIICHAT_OK;
591 if (g_owner && g_render_fd >= 0)
592 fd = g_render_fd;
593 bool measure_media_write = g_stats_media;
594 bool media_snapshot_stale =
595 g_render_snapshot && g_rendering_screen == UI_SCREEN_MEDIA &&
596 g_render_snapshot->media_epoch != atomic_load(&g_media_epoch);
597 if (media_snapshot_stale)
598 return ASCIICHAT_OK;
599 if (measure_media_write)
601 uint64_t stats_start = g_stats_media ? time_get_ns() : 0;
602 bool help_media_overlay = ui_controller_current_screen() == UI_SCREEN_HELP &&
604 // Terminals supporting synchronized output present the art and its overlays
605 // together, even when a large UTF-8 frame requires several writes.
606 bool synchronized = g_render_snapshot != NULL || help_media_overlay;
607 g_help_sync_open = help_media_overlay;
608 // A frame can legitimately occupy the terminal's last column and row.
609 // Disable DECAWM while presenting it so writing the bottom-right cell does
610 // not trigger an implicit wrap/scroll before the synchronized update ends.
611 static const char begin_media_frame[] = "\033[?2026h\033[?7l";
612 static const char begin_media_write[] = "\033[?7l";
613 bool protect_media_wrap =
614 ui_controller_current_screen() == UI_SCREEN_MEDIA || help_media_overlay;
615 const char *begin_sequence =
616 synchronized ? begin_media_frame : begin_media_write;
617 size_t begin_length = synchronized ? sizeof(begin_media_frame) - 1
618 : sizeof(begin_media_write) - 1;
619 bool started =
620 !protect_media_wrap ||
621 write_output_chunk(fd, begin_sequence, begin_length) == begin_length;
622 uint64_t sync_started_ns = g_stats_media && synchronized ? time_get_ns() : 0;
623 size_t written = 0;
624 bool superseded = false;
625 while (started && written < len) {
626 if (shutdown_is_requested()) {
627 superseded = true;
628 break;
629 }
630 if (g_render_snapshot && g_rendering_screen == UI_SCREEN_MEDIA &&
631 g_render_snapshot->media_epoch != atomic_load(&g_media_epoch)) {
632 superseded = true;
633 break;
634 }
635 // A pending editor or overlay supersedes the remainder of a media frame.
636 // Bound each console write so a large frame cannot delay that transition.
637 if (g_stats_media && ui_controller_current_screen() != UI_SCREEN_MEDIA &&
639 superseded = true;
640 break;
641 }
642 size_t count = len - written;
643 bool row_boundary = false;
644 if (g_stats_media && count > 16384) {
645 count = 16384;
646 size_t boundary = media_chunk_boundary(data + written, count);
647 if (boundary) {
648 count = boundary;
649 row_boundary = true;
650 }
651 count = ui_controller_trim_utf8_chunk(data + written, count);
652 }
653 size_t sent = write_output_chunk(fd, data + written, count);
654 written += sent;
655 if (sent != count)
656 break;
657 if (synchronized && g_stats_media && written < len && row_boundary &&
658 time_get_ns() - sync_started_ns >= 40 * NS_PER_MS_INT) {
659 // Give the terminal a complete set of rows before its synchronized
660 // output watchdog can expose a partly written row.
661 if (write_output_chunk(fd, "\033[?2026l\033[?2026h", 16) != 16) {
662 started = false;
663 break;
664 }
665 sync_started_ns = time_get_ns();
666 }
667 }
668 // When help covers media, keep the FPS overlay inside the same synchronized
669 // update as the menu and backdrop. Writing it afterward causes a visible
670 // one-frame gap while the terminal presents the help screen.
671 bool include_media_overlay = g_stats_media || help_media_overlay;
672 if (started && include_media_overlay && GET_OPTION(fps_counter)) {
673 char overlay[128];
674 size_t overlay_length = fps_counter_format(g_fps, overlay, sizeof(overlay),
675 g_render_size.cols, true);
676 if (overlay_length) {
677 if (write_output_chunk(fd, overlay, overlay_length) == overlay_length)
678 g_media_overlay_written = true;
679 else
680 started = false;
681 }
682 }
683 // End the update even when input superseded the frame halfway through.
684 static const char end_with_query[] =
685 "\033[1G\033[?7h\033[?2026l\033]11;?\033\\";
686 bool probe = synchronized && g_probe_frame && written == len && started;
687 if (probe)
688 g_probe_requested_ns = time_get_ns();
689 static const char end_frame[] = "\033[1G\033[?7h\033[?2026l";
690 static const char end_media[] = "\033[1G\033[?7h";
691 const char *end_sequence = probe ? end_with_query
692 : synchronized ? end_frame
693 : end_media;
694 size_t end_length = probe ? sizeof(end_with_query) - 1
695 : synchronized ? sizeof(end_frame) - 1
696 : sizeof(end_media) - 1;
697 bool ended = !protect_media_wrap ||
698 write_output_chunk(fd, end_sequence, end_length) == end_length;
699 if (superseded && ended) {
700 // A prompt can take ownership while a large media frame is being sent.
701 // The frame is deliberately allowed to stop at a row boundary, but its
702 // already-presented rows must not remain underneath the prompt.
703 static const char clear_aborted_media[] = "\033[r\033[0m\033[2J\033[H";
704 ended = write_output_chunk(fd, clear_aborted_media,
705 sizeof(clear_aborted_media) - 1) ==
706 sizeof(clear_aborted_media) - 1;
707 }
708 if (!ended)
709 g_probe_requested_ns = 0;
710 // Switching screens intentionally cancels the remainder of an old media
711 // frame.
712 bool complete = (written == len || superseded) && started && ended;
713 if (g_stats_media) {
714 g_stats_write_ns += time_get_ns() - stats_start;
715 g_stats_writes++;
716 g_stats_failed |= !complete;
717 }
718 if (measure_media_write)
719 fps_counter_write_end(g_fps, complete);
720 return complete ? ASCIICHAT_OK
722 "Incomplete terminal frame write (%zu/%zu bytes)",
723 written, len);
724}
725
726static void release_terminal(screen_terminal_t *terminal) {
727 if (terminal && atomic_fetch_sub(&terminal->references, 1) == 1) {
728 platform_close(terminal->fd);
729 SAFE_FREE(terminal);
730 }
731}
732
733static void release_snapshot(screen_snapshot_t *snapshot) {
734 if (snapshot && atomic_fetch_sub(&snapshot->references, 1) == 1) {
735 release_terminal(snapshot->terminal);
736 snapshot->terminal = NULL;
737 if (snapshot->slot)
738 atomic_store_explicit(&snapshot->slot->busy, false, memory_order_release);
739 else
741 }
742}
743
744static screen_snapshot_t *allocate_snapshot(ui_screen_t screen, size_t bytes) {
745 media_snapshot_slot_t *slot = NULL;
746 if (screen == UI_SCREEN_MEDIA) {
747 for (size_t i = 0; i < 3; ++i) {
748 bool expected = false;
749 if (atomic_compare_exchange_strong_explicit(
750 &g_media_snapshots[i].busy, &expected, true, memory_order_acquire,
751 memory_order_relaxed)) {
752 slot = &g_media_snapshots[i];
753 break;
754 }
755 }
756 }
757 screen_snapshot_t *copy;
758 if (slot) {
759 if (slot->capacity < bytes) {
760 size_t capacity = slot->capacity ? slot->capacity : 4096;
761 while (capacity < bytes && capacity <= SIZE_MAX / 2)
762 capacity *= 2;
763 if (capacity < bytes)
764 capacity = bytes;
765 slot->snapshot =
766 SAFE_REALLOC(slot->snapshot, capacity, screen_snapshot_t *);
767 slot->capacity = capacity;
768 }
769 copy = slot->snapshot;
770 } else {
771 copy = SAFE_MALLOC(bytes, screen_snapshot_t *);
772 }
773 if (!copy) {
774 if (slot)
775 atomic_store(&slot->busy, false);
776 return NULL;
777 }
778 atomic_init(&copy->references, 1);
779 copy->slot = slot;
780 copy->terminal = NULL;
781 return copy;
782}
783
784static void destroy_media_snapshots(void) {
785 for (size_t i = 0; i < 3; ++i) {
786 bool expected = false;
787 if (atomic_compare_exchange_strong(&g_media_snapshots[i].busy, &expected,
788 true)) {
789 SAFE_FREE(g_media_snapshots[i].snapshot);
790 g_media_snapshots[i].capacity = 0;
791 atomic_store(&g_media_snapshots[i].busy, false);
792 }
793 }
794}
795
796static void release_screen(screen_t *screen, bool flush_notices) {
797 screen_t *current = screen;
798 while (current) {
799 screen_t *next = current->next;
800 if (current->render) {
801 if (flush_notices)
802 ui_notice_flush_snapshot(current->fd, current->snapshot);
803 }
804 release_snapshot(current->owned);
805 if (current != screen)
806 SAFE_FREE(current);
807 current = next;
808 }
809 memset(screen, 0, sizeof(*screen));
810}
811
812void ui_controller_finish(int fd, const char *data, size_t len) {
813 atomic_store(&g_sync_finishing, true);
814 if (!g_owner)
815 while (atomic_load(&g_sync_rendering))
816 platform_sleep_ms(1);
818 screen_t retired[UI_SCREEN_COUNT] = {0};
819 bool locked = lifecycle_is_initialized(&g_lifecycle);
820 if (locked) {
821 mutex_lock(&g_mutex);
822 g_finished = true;
823 memcpy(retired, g_screens, sizeof(retired));
824 memset(g_screens, 0, sizeof(g_screens));
825 atomic_store(&g_background_screen, -1);
826 atomic_store(&g_screen_mask, 0);
828 cond_signal(&g_render_requested);
829 uint64_t pending = g_render_started;
830 while (!g_render_snapshot && g_render_completed < pending)
831 cond_wait(&g_render_done, &g_mutex);
832 mutex_unlock(&g_mutex);
833 }
834 for (int i = 0; i < UI_SCREEN_COUNT; ++i)
835 release_screen(&retired[i], i == UI_SCREEN_NOTICE);
836 terminal_screen_leave();
837 platform_write_all(fd, data, len);
838 atomic_store_bool(&g_live, false);
839}
840
841bool ui_controller_is_blocked(void) { return atomic_load_bool(&g_blocked); }
842
846
847bool ui_controller_is_owner(void) { return g_owner; }
848
849terminal_size_t ui_controller_size(void) {
850 if (g_owner)
851 return g_render_size;
852 terminal_size_t size = {.cols = 80, .rows = 24};
853 if (lifecycle_is_initialized(&g_lifecycle)) {
854 size = unpack_size(atomic_load(&g_size));
855 }
856 // A title-only controller has no screen to poll geometry yet.
857 if (!lifecycle_is_initialized(&g_lifecycle) ||
858 atomic_load(&g_screen_mask) == 0) {
859 terminal_size_t detected = {0};
861 int fd = atomic_load(&g_default_fd);
862 if (platform_isatty(fd) && read_terminal_size(fd, &detected) &&
863 detected.cols > 0 && detected.rows > 0)
864 size = detected;
866 }
867 return size;
868}
869
871 return g_animation;
872}
873
896
897static void draw_native_view(frame_buffer_t *output, terminal_size_t size,
898 const animation_sample_t *animation,
899 void *context) {
900 native_view_t *view = context;
901 g_capture = output;
902 g_animation = animation;
903 g_render_volume = view->volume;
904 bool previous = errno_notifications_suppress(true);
905 /* Media frames already cover the terminal. Clearing before composing the
906 * help overlay forces an expensive full-screen erase on every frame. */
907 bool help_over_media = view->active == UI_SCREEN_HELP &&
909 if (view->errors || (view->layer_count > 1 && !help_over_media))
911 if (view->sync_backdrop)
912 ui_sync_render(size);
913 size_t first_layer = 0;
914 if (help_over_media && view->layer_count >= 2 &&
915 view->layers[0].render == render_text && view->layers[0].snapshot) {
916 const text_snapshot_t *media = view->layers[0].snapshot;
917 frame_buffer_append(output, media->text, media->len);
918 first_layer = 1;
919 }
920 for (size_t i = first_layer; i < view->layer_count; ++i) {
921 screen_t *layer = &view->layers[i];
922 bool help = i + 1 == view->layer_count && view->active == UI_SCREEN_HELP;
923 if (help && view->errors)
924 ui_error_popup_render(output, size);
925 if (ui_too_small(size, layer->minimum)) {
926 ui_too_small_render(output, size, layer->minimum);
927 continue;
928 }
929 screen_snapshot_t *previous_snapshot = g_render_snapshot;
930 g_render_snapshot = layer->owned;
931 if (help && layer->render == render_text && layer->snapshot) {
932 const text_snapshot_t *help_text = layer->snapshot;
933 frame_buffer_append(output, help_text->text, help_text->len);
934 } else {
935 layer->render(size, layer->snapshot);
936 }
937 g_render_snapshot = previous_snapshot;
938 }
939 uint64_t media_frame_id = 0;
940 if (!view->errors) {
941 for (size_t i = 0; i < view->layer_count; ++i) {
942 if (view->layers[i].render == render_text && view->layers[i].owned) {
943 media_frame_id = view->layers[i].owned->frame_id;
944 break;
945 }
946 }
947 }
948 // Measure the media layer wherever it is rendered, including beneath an
949 // interactive TUI overlay. The active screen is not sufficient here:
950 // keyboard help, stats, and other screens can still compose and print the
951 // current ASCII frame.
952 view->fresh = fps_counter_frame_begin_id(g_fps, media_frame_id);
953 if (view->errors && view->active != UI_SCREEN_HELP)
954 ui_error_popup_render(output, size);
955 if (view->errors && terminal_screen_logs_help_open() &&
956 (view->active == UI_SCREEN_LOGS || view->active == UI_SCREEN_STATUS ||
957 view->active == UI_SCREEN_SPLASH))
960 g_render_volume = false;
961 g_animation = NULL;
962 g_capture = NULL;
963 view->drew = true;
964}
965
966static atomic_t g_title_active = {0};
967static bool g_title_saved;
968static bool g_title_written;
969static bool g_title_startup_finished;
970static int g_title_fd = -1;
971static uint64_t g_title_started;
972static atomic_t g_title_render = {0};
973static atomic_t g_title_ready = {0};
974static char g_last_title[TUI_CONTROLLER_LAST_TITLE_BUFFER_SIZE];
975static const char *g_title_mode;
976static atomic_t g_title_activity = {0};
977
979 atomic_store_bool(&g_title_ready, true);
980}
982 atomic_store_int(&g_title_render, phase);
983 if (phase != UI_TITLE_IDLE)
985}
986
988 atomic_store_int(&g_title_activity, activity);
989}
990
994void ui_controller_title_discovery(bool has_session, bool joining) {
996 : has_session ? UI_TITLE_WAITING_PEERS
998}
999
1000static const char *title_screen_label(int screen, const void *snapshot) {
1001 switch (screen) {
1002 case UI_SCREEN_LOGS:
1003 return "log viewer";
1004 case UI_SCREEN_ERRNO:
1005 return "errors";
1006 case UI_SCREEN_STATS:
1007 return "statistics";
1008 case UI_SCREEN_SYNC:
1009 return "sync primitives";
1010 case UI_SCREEN_MDNS:
1011 return "LAN server discovery";
1012 case UI_SCREEN_UPDATE:
1013 return "updates";
1014 case UI_SCREEN_PROMPT:
1015 return snapshot ? ui_prompt_title(snapshot) : "input";
1016 case UI_SCREEN_NOTICE:
1017 return snapshot ? ui_notice_title(snapshot) : "notice";
1018 default:
1019 return NULL;
1020 }
1021}
1022
1023static void title_update(int screen, const void *snapshot, bool covered) {
1024 if (!atomic_load_bool(&g_title_active))
1025 return;
1026 // Preserve the shell's title once for application exit, never for view
1027 // navigation.
1028 if (!g_title_saved) {
1030 mutex_lock(&g_title_packet_mutex);
1031 (void)terminal_title_save(g_title_fd);
1032 mutex_unlock(&g_title_packet_mutex);
1034 g_title_saved = true;
1035 }
1036 char title[TUI_CONTROLLER_TITLE_BUFFER_SIZE] = {0};
1037 asciichat_error_context_t latest = {0};
1038 size_t errors = errno_title_snapshot(&latest);
1039 if (errors) {
1040 char count[32] = "";
1041 if (errors > 1)
1042 snprintf(count, sizeof(count), "(%zu) ", errors);
1043 snprintf(title, sizeof(title), "‼️ ascii-chat %s %sERROR code=%d - %s",
1044 terminal_should_use_utf8(GET_OPTION(force_utf8)) ? "•" : "*",
1045 count, (int)latest.code, asciichat_error_string(latest.code));
1046 } else if (terminal_should_use_utf8(GET_OPTION(force_utf8))) {
1047 int phase = atomic_load_int(&g_title_render);
1048 int activity = atomic_load_int(&g_title_activity);
1049 if (phase != UI_TITLE_IDLE || activity != UI_TITLE_ACTIVITY_IDLE ||
1051 (atomic_load_bool(&g_title_ready) &&
1052 time_get_ns() - g_title_started >= 3 * NS_PER_SEC_INT))
1053 g_title_startup_finished = true;
1054 bool startup = !g_title_startup_finished;
1055 const char *status =
1056 phase == UI_TITLE_RENDERING ? "rendering file..."
1057 : phase == UI_TITLE_FINALIZING ? "finalizing file..."
1058 : phase == UI_TITLE_FAILED ? "rendering failed"
1059 : activity == UI_TITLE_CONNECTING ? "connecting..."
1060 : activity == UI_TITLE_RECONNECTING ? "reconnecting..."
1061 : activity == UI_TITLE_HANDSHAKE ? "secure handshake..."
1062 : activity == UI_TITLE_NEGOTIATING ? "negotiating..."
1063 : activity == UI_TITLE_RECEIVING ? "waiting for first frame..."
1064 : activity == UI_TITLE_CREATING_SESSION ? "creating session..."
1065 : activity == UI_TITLE_JOINING_SESSION ? "joining session..."
1066 : activity == UI_TITLE_WAITING_PEERS ? "waiting for peers..."
1067 : NULL;
1068 bool spinning =
1069 phase == UI_TITLE_RENDERING || phase == UI_TITLE_FINALIZING ||
1070 (phase == UI_TITLE_IDLE && activity != UI_TITLE_ACTIVITY_IDLE);
1071 // Spinner glyphs use one column; reserve the emoji's second column with
1072 // padding.
1073 const char *icon =
1074 spinning ? ui_spinner_glyph(time_get_ns() - g_title_started, false)
1075 : "🔠";
1076 snprintf(title, sizeof(title), "%s%s ascii-chat • %s%s%s", icon,
1077 spinning ? " " : "",
1078 startup ? "video chat in your terminal" : g_title_mode,
1079 status ? " • " : "", status ? status : "");
1080 int parent =
1082 const char *label;
1083 if (screen == UI_SCREEN_HELP) {
1084 mutex_lock(&g_mutex);
1085 label = title_screen_label(parent, parent >= 0 && parent < UI_SCREEN_COUNT
1086 ? g_screens[parent].snapshot
1087 : NULL);
1088 mutex_unlock(&g_mutex);
1089 } else {
1090 label = title_screen_label(parent, snapshot);
1091 }
1092 if (parent == UI_SCREEN_RENDER_PROGRESS && phase == UI_TITLE_IDLE)
1093 label = "load file/url";
1094 size_t used = strlen(title);
1095 if (label)
1096 snprintf(title + used, sizeof(title) - used, " • %s", label);
1097 used = strlen(title);
1098 if (screen == UI_SCREEN_HELP ||
1100 snprintf(title + used, sizeof(title) - used, " • help");
1101 used = strlen(title);
1102 if (covered)
1103 snprintf(title + used, sizeof(title) - used, " • terminal too small");
1104 }
1105 if (!g_title_written || strcmp(title, g_last_title) != 0) {
1107 mutex_lock(&g_title_packet_mutex);
1108 (void)terminal_set_title_fd(g_title_fd, title);
1109 mutex_unlock(&g_title_packet_mutex);
1110 // Retry cosmetic failures only when the desired text changes.
1111 snprintf(g_last_title, sizeof(g_last_title), "%s", title);
1112 g_title_written = true;
1114 }
1115}
1116
1117static const char *usage_screen_name(int screen) {
1118 static const char *names[UI_SCREEN_COUNT] = {
1119 [UI_SCREEN_STATUS] = "status",
1120 [UI_SCREEN_MEDIA] = "media",
1121 [UI_SCREEN_SPLASH] = "splash",
1122 [UI_SCREEN_RECONNECT] = "reconnect",
1123 [UI_SCREEN_RENDER_PROGRESS] = "render_progress",
1124 [UI_SCREEN_LOGS] = "logs",
1125 [UI_SCREEN_ERRNO] = "errno",
1126 [UI_SCREEN_HELP] = "help",
1127 [UI_SCREEN_STATS] = "stats",
1128 [UI_SCREEN_SYNC] = "sync",
1129 [UI_SCREEN_MDNS] = "mdns",
1130 [UI_SCREEN_UPDATE] = "update",
1131 [UI_SCREEN_NOTICE] = "notice",
1132 [UI_SCREEN_PROMPT] = "prompt",
1133 [UI_SCREEN_ERROR] = "error"};
1134 if (screen == UI_SCREEN_PROMPT) {
1135 mutex_lock(&g_mutex);
1136 const char *name =
1137 ui_prompt_usage_name(g_screens[UI_SCREEN_PROMPT].snapshot);
1138 mutex_unlock(&g_mutex);
1139 return name;
1140 }
1141 if (screen == UI_SCREEN_HELP)
1145 return "logs_help";
1146 return screen >= 0 && screen < UI_SCREEN_COUNT ? names[screen] : NULL;
1147}
1148
1149// Only the presentation thread owns this state. Repaints do not create visits.
1150static void usage_transition(const char *next, const char **previous,
1151 uint64_t *since) {
1152 if (next == *previous || (next && *previous && strcmp(next, *previous) == 0))
1153 return;
1154 uint64_t now = time_get_ns();
1155 if (*previous)
1156 ascii_otel_ui_usage(*previous, "leave", now - *since);
1157 if (next)
1158 ascii_otel_ui_usage(next, "enter", 0);
1159 *previous = next;
1160 *since = now;
1161}
1162
1163static void *presentation_main(void *unused) {
1164 (void)unused;
1165 g_owner = true;
1166 g_fps = fps_counter_create();
1167 unsigned int applied_effective_fps =
1168 (unsigned int)atomic_load_int(&g_effective_fps);
1169 fps_counter_set_effective_fps(g_fps, applied_effective_fps);
1170 bool was_sync = false;
1171 uint64_t last_volume_until = 0;
1172 bool volume_was_visible = false;
1173 uint64_t help_revision = 0;
1174 uint64_t reply_requested_ns = 0, reply_frame_ns = 0, reply_frame_id = 0,
1175 reply_written_ns = 0;
1176 int reply_support = 0;
1177 bool awaiting_reply = false;
1178 uint64_t error_revision = 0;
1179 const char *usage_screen = NULL;
1180 uint64_t usage_since = 0;
1181 const char *stats_page = NULL, *covered_screen = NULL;
1182 uint64_t stats_since = 0, covered_since = 0;
1183 while (!atomic_load_bool(&g_presentation_stop_requested)) {
1184 unsigned int effective_fps =
1185 (unsigned int)atomic_load_int(&g_effective_fps);
1186 if (effective_fps != applied_effective_fps) {
1187 fps_counter_set_effective_fps(g_fps, effective_fps);
1188 applied_effective_fps = effective_fps;
1189 }
1190 int usage_current = ui_controller_current_screen();
1191 usage_transition(usage_screen_name(usage_current), &usage_screen,
1192 &usage_since);
1194 const char *next_page = NULL;
1195 if (usage_current == UI_SCREEN_STATS && !usage_state.covered) {
1196 mutex_lock(&g_mutex);
1197 const stats_view_t *view = g_screens[UI_SCREEN_STATS].snapshot;
1198 if (view)
1199 next_page = view->page ? "stats_details" : "stats_overview";
1200 mutex_unlock(&g_mutex);
1201 }
1202 usage_transition(next_page, &stats_page, &stats_since);
1203 const char *next_covered =
1204 usage_state.covered ? usage_screen_name(usage_state.screen) : NULL;
1205 if (next_covered != covered_screen &&
1206 (!next_covered || !covered_screen ||
1207 strcmp(next_covered, covered_screen))) {
1208 uint64_t now = time_get_ns();
1209 if (covered_screen) {
1210 ascii_otel_ui_usage(covered_screen, "size_warning_ended",
1211 now - covered_since);
1212 if (!next_covered && usage_screen &&
1213 !strcmp(covered_screen, usage_screen))
1214 ascii_otel_ui_usage(covered_screen, "size_warning_resolved", 0);
1215 }
1216 if (next_covered)
1217 ascii_otel_ui_usage(next_covered, "size_warning_started", 0);
1218 covered_screen = next_covered;
1219 covered_since = now;
1220 }
1221 uint64_t iteration_started_ns = time_get_ns();
1223 title_update(-1, NULL, false);
1224 uint64_t refresh_deadline = iteration_started_ns + 16 * NS_PER_MS_INT;
1225 uint64_t replied_ns = keyboard_stream_terminal_reply_ns();
1226 if (reply_requested_ns && replied_ns >= reply_requested_ns) {
1227 reply_support = 1;
1228 if (awaiting_reply) {
1229 fps_counter_frame_end(g_fps, replied_ns);
1232 "TERMINAL_ACK: id=%llu response_ms=%.2f "
1233 "capture_to_terminal_ms=%.2f",
1234 (unsigned long long)reply_frame_id,
1235 (double)(replied_ns - reply_requested_ns) / NS_PER_MS_INT,
1236 reply_frame_ns
1237 ? (double)(replied_ns - reply_frame_ns) / NS_PER_MS_INT
1238 : 0);
1239 }
1240 awaiting_reply = false;
1241 }
1242 if (awaiting_reply &&
1243 iteration_started_ns - reply_requested_ns > 500 * NS_PER_MS_INT) {
1244 // Classic consoles need no remote acknowledgement and may not answer OSC.
1245 reply_support = -1;
1246 awaiting_reply = false;
1247 fps_counter_frame_end(g_fps, reply_written_ns);
1248 }
1249 // A terminal capability query is advisory. Some ConPTY frontends,
1250 // including Alacritty, do not answer the OSC query; never hold the media
1251 // presentation loop behind that optional reply. The timeout below still
1252 // records the frontend as non-responsive for diagnostics.
1253 // This path must remain independent of producers, including one stuck
1254 // holding the controller mutex. It reads only the collector's mailbox.
1259 atomic_store(&g_sync_rendering, true);
1260 if (atomic_load(&g_sync_finishing)) {
1261 atomic_store(&g_sync_rendering, false);
1262 platform_sleep_ms(1);
1263 continue;
1264 }
1265 if (!was_sync) {
1266 const ui_session_view_t hidden = {.screen = -1};
1267 ui_session_render(g_session, &hidden, time_get_ns());
1268 }
1269 int fd = ui_sync_output_fd();
1270 terminal_size_t size = {0};
1271 g_render_fd = fd;
1272 if (read_terminal_size(fd, &size) && size.cols > 0 && size.rows > 0) {
1273 g_render_size = size;
1274 title_update(UI_SCREEN_SYNC, NULL, false);
1275 atomic_store_bool(&g_blocked, false);
1276 if (ui_error_popup_visible()) {
1277 frame_buffer_t *composed = frame_buffer_create(size.rows, size.cols);
1278 if (composed) {
1279 bool previous = errno_notifications_suppress(true);
1280 g_capture = composed;
1281 ui_sync_render(size);
1282 ui_error_popup_render(composed, size);
1283 g_capture = NULL;
1285 frame_buffer_get_length(composed));
1287 frame_buffer_destroy(composed);
1288 }
1289 } else {
1290 ui_sync_render(size);
1291 }
1292 atomic_store(&g_size, pack_size(size));
1293 }
1294 g_render_fd = -1;
1295 atomic_store(&g_sync_rendering, false);
1296 was_sync = true;
1297 platform_sleep_ns(50 * NS_PER_MS_INT);
1298 continue;
1299 }
1300 if (was_sync) {
1301 g_active = -1;
1302 ui_session_redraw(g_session);
1303 was_sync = false;
1304 }
1305 mutex_lock(&g_mutex);
1306 int active = selected_screen_locked();
1307 bool changed = active != g_active;
1308 g_active = active;
1309 bool redraw = g_redraw;
1310 g_redraw = false;
1311 terminal_size_t previous_size = unpack_size(atomic_load(&g_size));
1312 if ((active == UI_SCREEN_MEDIA || active == UI_SCREEN_HELP ||
1313 active == UI_SCREEN_STATS) &&
1314 time_get_ns() >= atomic_load_u64(&g_volume_until))
1315 refresh_deadline = iteration_started_ns + 100 * NS_PER_MS_INT;
1316 screen_t frame = {0};
1317 screen_t layers[TUI_LAYER_CAPACITY] = {0};
1318 size_t layer_count = 0;
1319 if (active >= 0 && !g_finished &&
1321 frame = g_screens[active];
1322 atomic_fetch_add(&frame.owned->references, 1);
1323 g_screens[active].dirty = false;
1324 g_rendering_screen = active;
1325 ++g_render_started;
1326 }
1327 mutex_unlock(&g_mutex);
1328 if (active < 0) {
1329 if (changed) {
1330 const char restore[] = "\033[0m\033[2J\033[H\033[?25h";
1331 ui_controller_write(atomic_load(&g_default_fd), restore,
1332 sizeof(restore) - 1);
1333 }
1334 const ui_session_view_t hidden = {.screen = -1};
1335 ui_session_render(g_session, &hidden, time_get_ns());
1336 atomic_store_bool(&g_blocked, false);
1337 }
1338 if (frame.render) {
1339 g_render_snapshot = frame.owned;
1340 screen_t *screen = &frame;
1341 terminal_resize_watcher_t watcher = {.size = previous_size};
1342 bool resized = false;
1343 // Observe physical changes once for all modes; consumers use the
1344 // published dimensions.
1345 bool trace_resize = trace_terminal_calls();
1346 if (trace_resize)
1347 log_file_msg("TERMINAL_CALL_BEGIN: thread=%llu "
1348 "call=terminal_resize_poll fd=%d at_ns=%llu",
1349 (unsigned long long)thread_current_id(), screen->fd,
1350 (unsigned long long)time_get_ns());
1351 uint64_t resize_started_ns = trace_resize ? time_get_ns() : 0;
1352 int resize_result = terminal_resize_poll(&watcher, screen->fd, &resized);
1353 uint64_t resize_returned_ns = trace_resize ? time_get_ns() : 0;
1354 if (trace_resize)
1355 log_file_msg("TERMINAL_CALL_END: thread=%llu call=terminal_resize_poll "
1356 "fd=%d result=%d changed=%d elapsed_ms=%.3f at_ns=%llu",
1357 (unsigned long long)thread_current_id(), screen->fd,
1358 resize_result, resized,
1359 (double)(resize_returned_ns - resize_started_ns) /
1361 (unsigned long long)resize_returned_ns);
1362 if (resize_result != ASCIICHAT_OK) {
1363 atomic_store_bool(&g_blocked, true);
1364 const ui_session_view_t hidden = {.screen = -1};
1365 ui_session_render(g_session, &hidden, time_get_ns());
1366 goto frame_complete;
1367 }
1368 uint64_t geometry_done_ns = time_get_ns();
1369 terminal_size_t size = watcher.size;
1370 if (size.cols != previous_size.cols || size.rows != previous_size.rows) {
1371 mutex_lock(&g_mutex);
1372 atomic_store(&g_size, pack_size(size));
1373 publish_input_state_locked();
1374 mutex_unlock(&g_mutex);
1375 }
1376 g_render_size = size;
1377 if (active == UI_SCREEN_PROMPT)
1378 screen->minimum.rows =
1380 title_update(active, screen->snapshot,
1381 ui_too_small(size, screen->minimum));
1382 uint64_t now = time_get_ns();
1383 uint64_t volume_until = atomic_load_u64(&g_volume_until);
1384 bool volume_visible = active == UI_SCREEN_MEDIA &&
1385 !GET_OPTION(snapshot_mode) &&
1386 !GET_OPTION(strip_ansi) && now < volume_until;
1387 bool volume_changed =
1388 volume_visible != volume_was_visible ||
1389 (volume_visible && volume_until != last_volume_until);
1390 if (volume_was_visible && !volume_visible)
1391 redraw = true;
1392 volume_was_visible = volume_visible;
1393 last_volume_until = volume_until;
1394 int fps_screen =
1395 active == UI_SCREEN_HELP ? keyboard_help_parent_screen() : active;
1396 bool show_fps = fps_screen == UI_SCREEN_MEDIA && GET_OPTION(fps_counter);
1397 redraw |= fps_counter_set_visible(g_fps, show_fps);
1398 bool was_covered = ui_session_is_covered(g_session);
1399 // Opening keyboard help does not stop the media layer underneath it.
1400 // Preserve its measured FPS instead of resetting the overlay to zero
1401 // merely because the active presentation screen changed to HELP.
1402 if ((changed && fps_screen != UI_SCREEN_MEDIA) || was_covered)
1403 fps_counter_reset(g_fps);
1404 g_render_fd = screen->fd;
1406 bool errors = ui_error_popup_visible();
1407 uint64_t current_error_revision = ui_error_popup_revision();
1408 bool errors_changed = current_error_revision != error_revision;
1409 error_revision = current_error_revision;
1410 bool overlay =
1411 errors || active == UI_SCREEN_HELP || active == UI_SCREEN_UPDATE;
1412 bool sync_backdrop = false;
1413 mutex_lock(&g_mutex);
1414 if (active == UI_SCREEN_HELP || active == UI_SCREEN_UPDATE) {
1415 int parent = selected_screen_excluding_locked(active);
1416 // Help can cover the update dialog, which itself covers the retained
1417 // TUI.
1418 if (parent == UI_SCREEN_UPDATE && active == UI_SCREEN_HELP) {
1419 int underlying = keyboard_help_previous_interactive();
1420 if (underlying >= 0 && underlying != UI_SCREEN_HELP &&
1421 g_screens[underlying].render)
1422 layers[layer_count++] = g_screens[underlying];
1423 else {
1424 for (int i = UI_SCREEN_SPLASH; i >= UI_SCREEN_STATUS; --i)
1425 if (g_screens[i].render) {
1426 layers[layer_count++] = g_screens[i];
1427 break;
1428 }
1429 }
1430 }
1431 if (parent >= 0 && parent != active && g_screens[parent].render)
1432 layers[layer_count++] = g_screens[parent];
1433 sync_backdrop =
1435 layer_count == 0;
1436 }
1437 // The active frame already has its own lifetime reference.
1438 for (size_t i = 0; i < layer_count; ++i) {
1439 atomic_fetch_add(&layers[i].owned->references, 1);
1440 }
1441 g_rendering_layers = 1u << active;
1442 for (int i = 0; i < UI_SCREEN_COUNT; ++i)
1443 for (size_t j = 0; j < layer_count; ++j)
1444 if (g_screens[i].owned == layers[j].owned)
1445 g_rendering_layers |= 1u << i;
1446 mutex_unlock(&g_mutex);
1447 layers[layer_count++] = frame;
1448 if ((resized || changed) && (active == UI_SCREEN_MEDIA || overlay)) {
1449 // Keep the last usable media dimensions while a small-terminal view is
1450 // shown.
1451 if (GET_OPTION(auto_width) && size.cols >= UI_MEDIA_MIN_COLS &&
1452 size.cols <= 1024)
1453 options_set_int("width", size.cols);
1454 if (GET_OPTION(auto_height) && size.rows >= UI_MEDIA_MIN_ROWS &&
1455 size.rows <= 1024)
1456 options_set_int("height", size.rows);
1457 }
1458 ui_session_resize(g_session, size.cols, size.rows);
1459 if (redraw)
1460 ui_session_redraw(g_session);
1461 if (active == UI_SCREEN_MEDIA) {
1462 // Console geometry queries can block while capture continues. Take the
1463 // latest mailbox snapshot after those queries instead of drawing the
1464 // image retained before them.
1465 screen_snapshot_t *retired = NULL;
1466 mutex_lock(&g_mutex);
1467 if (g_screens[active].owned && g_screens[active].owned != frame.owned) {
1468 retired = frame.owned;
1469 frame = g_screens[active];
1470 atomic_fetch_add(&frame.owned->references, 1);
1471 g_screens[active].dirty = false;
1472 g_render_snapshot = frame.owned;
1473 }
1474 mutex_unlock(&g_mutex);
1475 release_snapshot(retired);
1476 }
1477 layers[layer_count - 1] = frame;
1478 native_view_t context = {.screen = screen,
1479 .layers = layers,
1480 .layer_count = layer_count,
1481 .active = active,
1482 .volume = volume_visible,
1483 .errors = errors,
1484 .sync_backdrop = sync_backdrop};
1485 bool help_changed = false;
1486 if (active == UI_SCREEN_HELP) {
1487 uint64_t revision = options_revision();
1488 help_changed = revision != help_revision;
1489 help_revision = revision;
1490 }
1491 ui_session_view_t view = {
1492 .screen = active,
1493 .minimum = errors && active != UI_SCREEN_HELP
1494 ? (terminal_size_t){1, 1}
1495 : screen->minimum,
1496 .dirty = redraw || screen->dirty || errors_changed ||
1497 volume_changed || help_changed,
1498 .refresh_ns =
1499 active == UI_SCREEN_PROMPT ? 50 * NS_PER_MS_INT
1500 : active == UI_SCREEN_LOGS ? 100 * NS_PER_MS_INT
1501 : active == UI_SCREEN_UPDATE
1503 : active == UI_SCREEN_RENDER_PROGRESS ? 125 * NS_PER_MS_INT
1504 : active == UI_SCREEN_NOTICE || active == UI_SCREEN_ERROR
1505 ? 0
1506 : (active != UI_SCREEN_MEDIA && active != UI_SCREEN_STATS &&
1507 active != UI_SCREEN_HELP
1508 ? 16 * NS_PER_MS_INT
1509 : 0),
1510 .draw = draw_native_view,
1511 .context = &context};
1512 uint64_t compose_started_ns = time_get_ns();
1513 const char *output = ui_session_render(g_session, &view, now);
1514 uint64_t animation_deadline = ui_session_next_frame_ns(g_session);
1515 if (active == UI_SCREEN_HELP && animation_deadline < refresh_deadline)
1516 refresh_deadline = animation_deadline;
1517 uint64_t composed_ns = time_get_ns();
1518 bool covered = ui_session_is_covered(g_session);
1519 atomic_store_bool(&g_blocked, covered);
1520 g_media_overlay_written = false;
1521 if (covered && !was_covered)
1522 fps_counter_reset(g_fps);
1523 if (output) {
1524 if (active == UI_SCREEN_MEDIA &&
1525 screen->owned->media_epoch != atomic_load(&g_media_epoch))
1526 goto frame_complete;
1527 // Only a fresh media presentation participates in media write
1528 // cancellation and FPS accounting. Help and other modal screens can
1529 // be rendered over a media backdrop, but their own output must not be
1530 // treated as a supersedable media frame.
1531 bool fresh_media = context.fresh && context.drew;
1532 stats_media_begin(fresh_media);
1533 // Probe terminal acknowledgement support during startup only. Once a
1534 // frontend has answered (or timed out), media presentation must not
1535 // make every frame wait on an optional terminal protocol round trip.
1536 // The mailbox already retains the newest frame when a frontend is
1537 // temporarily busy, so steady-state video should follow capture FPS.
1538 g_probe_frame = fresh_media && reply_support == 0;
1540 screen->fd, output, ui_session_frame_length(g_session));
1541 uint64_t write_done_ns = time_get_ns();
1542 if (written == ASCIICHAT_OK && active == UI_SCREEN_NOTICE &&
1543 context.drew && !covered && !errors)
1545 if (fresh_media) {
1547 // platform_write_all has already submitted the complete frame. Do
1548 // not synchronously drain the Windows console after every frame:
1549 // ConPTY/Alacritty can make that wait for terminal-side rendering
1550 // and serialize the producer behind the terminal compositor.
1552 fps_counter_write_end(g_fps, drained == ASCIICHAT_OK);
1553 if (written != ASCIICHAT_OK || drained != ASCIICHAT_OK)
1554 CLEAR_ERRNO();
1555 else {
1556 uint64_t completed_ns = time_get_ns();
1559 "FRAME_PRESENT: id=%llu submit_to_stdout_ms=%.2f "
1560 "acquired_ns=%llu submitted_ns=%llu "
1561 "completed_ns=%llu capture_to_stdout_ms=%.2f mailbox_ms=%.2f "
1562 "geometry_ms=%.2f "
1563 "compose_ms=%.2f write_ms=%.2f drain_ms=%.2f max_chunk_ms=%.2f "
1564 "chunks=%llu bytes=%zu cols=%d rows=%d",
1565 (unsigned long long)screen->owned->frame_id,
1566 (double)(completed_ns - screen->owned->submitted_ns) /
1568 (unsigned long long)screen->owned->acquisition_started_ns,
1569 (unsigned long long)screen->owned->submitted_ns,
1570 (unsigned long long)completed_ns,
1572 ? (double)(completed_ns -
1575 : 0,
1576 (double)(compose_started_ns - screen->owned->submitted_ns) /
1578 (double)(geometry_done_ns - iteration_started_ns) /
1580 (double)(composed_ns - compose_started_ns) / NS_PER_MS_INT,
1581 (double)(write_done_ns - composed_ns) / NS_PER_MS_INT,
1582 (double)(completed_ns - write_done_ns) / NS_PER_MS_INT,
1583 (double)g_stats_max_chunk_ns / NS_PER_MS_INT,
1584 (unsigned long long)g_stats_chunks,
1585 ui_session_frame_length(g_session), size.cols, size.rows);
1586 }
1587 }
1588 stats_media_end();
1589 if (g_probe_frame) {
1590 awaiting_reply = written == ASCIICHAT_OK && g_probe_requested_ns != 0;
1591 if (awaiting_reply) {
1592 reply_requested_ns = g_probe_requested_ns;
1593 reply_frame_ns = screen->owned->acquisition_started_ns;
1594 reply_frame_id = screen->owned->frame_id;
1595 reply_written_ns = time_get_ns();
1596 }
1597 }
1598 if (fresh_media && !awaiting_reply)
1599 fps_counter_frame_end(g_fps, time_get_ns());
1600 }
1601 if (!covered && show_fps && !g_media_overlay_written)
1602 // The frame may have repainted the overlay's row without owning the
1603 // synchronized media write. Always repaint the complete label here;
1604 // suppressing unchanged values leaves a stale/blank FPS label that
1605 // visibly flickers as the UI redraws.
1606 fps_counter_render(g_fps, screen->fd, size.cols, true);
1607 if (g_help_sync_open) {
1608 (void)write_output_chunk(screen->fd, "\033[1G\033[?7h\033[?2026l", 17);
1609 g_help_sync_open = false;
1610 }
1611 }
1612 frame_complete:
1613 g_render_fd = -1;
1614 g_render_snapshot = NULL;
1615 for (size_t i = 0; i + 1 < layer_count; ++i)
1616 release_snapshot(layers[i].owned);
1617 if (frame.render) {
1618 release_snapshot(frame.owned);
1619 mutex_lock(&g_mutex);
1620 g_rendering_screen = -1;
1621 g_rendering_layers = 0;
1622 g_render_completed = g_render_started;
1623 bool live = false;
1624 for (int i = 0; i < UI_SCREEN_COUNT; ++i)
1625 live |= g_screens[i].render != NULL;
1626 atomic_store_bool(&g_live, live);
1627 if (!live) {
1629 ui_error_popup_preserve(atomic_load(&g_default_fd),
1630 unpack_size(atomic_load(&g_size)));
1632 }
1633 cond_broadcast(&g_render_done);
1634 mutex_unlock(&g_mutex);
1635 }
1636 // New snapshots wake presentation immediately. The deadline only refreshes
1637 // animations, terminal geometry and idle FPS counters; rendering time is
1638 // part of the interval rather than an additional delay after each frame.
1639 mutex_lock(&g_mutex);
1640 int pending_screen = selected_screen_locked();
1641 bool pending =
1642 g_redraw || pending_screen != g_active ||
1643 (pending_screen >= 0 && g_screens[pending_screen].dirty) ||
1644 (ui_error_popup_visible() && g_screens[UI_SCREEN_MEDIA].dirty);
1645 uint64_t now = time_get_ns();
1646 if (!pending && !atomic_load_bool(&g_presentation_stop_requested) &&
1647 now < refresh_deadline)
1648 cond_timedwait(&g_render_requested, &g_mutex, refresh_deadline - now);
1649 mutex_unlock(&g_mutex);
1650 }
1651 usage_transition(NULL, &stats_page, &stats_since);
1652 if (covered_screen)
1653 ascii_otel_ui_usage(covered_screen, "size_warning_ended",
1654 time_get_ns() - covered_since);
1655 usage_transition(NULL, &usage_screen, &usage_since);
1656 if (g_title_saved) {
1658 (void)terminal_title_restore(g_title_fd);
1659 (void)platform_close(g_title_fd);
1660 g_title_fd = -1;
1661 g_title_saved = false;
1662 atomic_store_bool(&g_title_active, false);
1664 }
1665 fps_counter_destroy(g_fps);
1666 g_fps = NULL;
1667 g_owner = false;
1668 return NULL;
1669}
1670
1671static asciichat_error_t controller_start(void) {
1673 if (lifecycle_init_once(&g_lifecycle)) {
1674 atomic_store_bool(&g_presentation_stop_requested, false);
1675 atomic_store_bool(&g_sync_initialized, false);
1676 atomic_store(&g_sync_finishing, false);
1677 atomic_store(&g_sync_rendering, false);
1678 atomic_store_bool(&g_blocked, false);
1679 g_active = -1;
1680 g_redraw = false;
1681 g_finished = false;
1682 g_rendering_screen = -1;
1683 g_render_started = g_render_completed = 0;
1684 if (mutex_init(&g_mutex, "ui_controller") != 0) {
1685 lifecycle_init_abort(&g_lifecycle);
1686 return SET_ERRNO(ERROR_THREAD, "Cannot initialize UI mutex");
1687 }
1688 if (mutex_init(&g_title_packet_mutex, "terminal_title_packets") != 0) {
1689 mutex_destroy(&g_mutex);
1690 lifecycle_init_abort(&g_lifecycle);
1691 return SET_ERRNO(ERROR_THREAD,
1692 "Cannot initialize terminal title packet mutex");
1693 }
1694 if (cond_init(&g_render_done, "ui_render_done") != 0) {
1695 mutex_destroy(&g_title_packet_mutex);
1696 mutex_destroy(&g_mutex);
1697 lifecycle_init_abort(&g_lifecycle);
1698 return SET_ERRNO(ERROR_THREAD,
1699 "Cannot initialize UI render completion condition");
1700 }
1701 if (cond_init(&g_render_requested, "ui_render_requested") != 0) {
1702 cond_destroy(&g_render_done);
1703 mutex_destroy(&g_title_packet_mutex);
1704 mutex_destroy(&g_mutex);
1705 lifecycle_init_abort(&g_lifecycle);
1706 return SET_ERRNO(ERROR_THREAD,
1707 "Cannot initialize UI presentation condition");
1708 }
1709 g_session = ui_session_create();
1710 if (!g_session) {
1711 cond_destroy(&g_render_requested);
1712 cond_destroy(&g_render_done);
1713 mutex_destroy(&g_title_packet_mutex);
1714 mutex_destroy(&g_mutex);
1715 lifecycle_init_abort(&g_lifecycle);
1716 return SET_ERRNO(ERROR_MEMORY, "Cannot create session UI runtime");
1717 }
1718 NAMED_REGISTER_ATOMIC(&g_title_active, "terminal_title_active", NULL);
1719 NAMED_REGISTER_ATOMIC(&g_title_render, "terminal_title_render", NULL);
1720 NAMED_REGISTER_ATOMIC(&g_title_ready, "terminal_title_ready", NULL);
1721 NAMED_REGISTER_ATOMIC(&g_title_activity, "terminal_title_activity", NULL);
1722 NAMED_REGISTER_ATOMIC(&g_live, "ui_controller_live", NULL);
1723 NAMED_REGISTER_ATOMIC(&g_presentation_stop_requested,
1724 "ui_presentation_stop_requested", NULL);
1725 NAMED_REGISTER_ATOMIC(&g_blocked, "ui_controller_blocked", NULL);
1726 NAMED_REGISTER_ATOMIC(&g_lifecycle.state, "ui_controller_lifecycle", NULL);
1727 if (platform_thread_create(&g_thread, "ui_controller", presentation_main,
1728 NULL) != ASCIICHAT_OK) {
1729 ui_session_destroy(g_session);
1730 g_session = NULL;
1731 NAMED_UNREGISTER(&g_title_active);
1732 NAMED_UNREGISTER(&g_title_render);
1733 NAMED_UNREGISTER(&g_title_ready);
1734 NAMED_UNREGISTER(&g_title_activity);
1735 NAMED_UNREGISTER(&g_live);
1736 NAMED_UNREGISTER(&g_presentation_stop_requested);
1737 NAMED_UNREGISTER(&g_blocked);
1738 NAMED_UNREGISTER(&g_lifecycle.state);
1739 cond_destroy(&g_render_requested);
1740 cond_destroy(&g_render_done);
1741 mutex_destroy(&g_title_packet_mutex);
1742 mutex_destroy(&g_mutex);
1743 lifecycle_init_abort(&g_lifecycle);
1744 return SET_ERRNO(ERROR_THREAD, "Cannot start UI controller");
1745 }
1746 terminal_screen_enter(atomic_load(&g_default_fd));
1747 lifecycle_init_commit(&g_lifecycle);
1748 }
1749 if (!lifecycle_is_initialized(&g_lifecycle))
1751 "UI controller initialization is not complete");
1752 return ASCIICHAT_OK;
1753}
1754
1756 if (lifecycle_is_initialized(&g_lifecycle))
1757 mutex_lock(&g_title_packet_mutex);
1758}
1759
1761 if (lifecycle_is_initialized(&g_lifecycle))
1762 mutex_unlock(&g_title_packet_mutex);
1763}
1764
1766 if (fd < 0)
1767 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid UI terminal descriptor");
1768 atomic_store(&g_default_fd, fd);
1769 asciichat_error_t result = controller_start();
1770 return result == ASCIICHAT_OK ? ui_sync_start(fd) : result;
1771}
1772
1774 if (!mode || !platform_isatty(fd) ||
1775 (GET_OPTION(snapshot_mode) && !GET_OPTION(render_file)[0] &&
1776 !GET_OPTION(render_kitty)))
1777 return ASCIICHAT_OK;
1778 if (atomic_load_bool(&g_title_active))
1780 "Terminal title is already initialized");
1781 atomic_store(&g_default_fd, fd);
1782 asciichat_error_t result = controller_start();
1783 if (result != ASCIICHAT_OK)
1784 return result;
1785 g_title_fd = platform_dup(fd);
1786 if (g_title_fd < 0)
1787 return SET_ERRNO_SYS(ERROR_TERMINAL, "Cannot retain title terminal");
1788 g_title_mode = mode;
1789 g_title_started = time_get_ns();
1790 g_last_title[0] = '\0';
1791 g_title_written = false;
1792 g_title_startup_finished = false;
1793 atomic_store_int(&g_title_render, UI_TITLE_IDLE);
1794 atomic_store_int(&g_title_activity, UI_TITLE_ACTIVITY_IDLE);
1795 atomic_store_bool(&g_title_ready, false);
1796 // Publish only after the retained descriptor and immutable configuration are
1797 // ready.
1798 atomic_store_bool(&g_title_active, true);
1799 return ASCIICHAT_OK;
1800}
1801
1803 return screen >= 0 && screen < UI_SCREEN_COUNT &&
1804 (atomic_load(&g_screen_mask) & (1u << screen));
1805}
1806
1807static asciichat_error_t
1808submit_screen(ui_screen_t screen, int fd, terminal_size_t minimum,
1809 ui_render_fn render, const void *snapshot, size_t bytes,
1810 screen_terminal_t *retained_terminal, bool fresh_frame) {
1811 uint64_t entered_ns = time_get_ns();
1812 if (screen < 0 || screen >= UI_SCREEN_COUNT || !render || !snapshot ||
1813 !bytes || minimum.cols <= 0 || minimum.rows <= 0)
1814 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid UI screen snapshot");
1815 if (interactive_screen(screen) && screen != UI_SCREEN_ERRNO &&
1817 (screen != UI_SCREEN_STATS ||
1820 // A live slot retains its terminal even while LOG_IO redirects process stdio.
1821 bool live = lifecycle_is_initialized(&g_lifecycle) &&
1822 (atomic_load(&g_screen_mask) & (1u << screen));
1823 // New modal slots inherit the live terminal instead of process stdio, which
1824 // an audio/decoder worker can temporarily redirect through LOG_IO.
1825 if (!live && !retained_terminal && lifecycle_is_initialized(&g_lifecycle) &&
1828 screen_terminal_t *inherited = NULL;
1829 mutex_lock(&g_mutex);
1830 int active = selected_screen_locked();
1831 if (active >= 0) {
1832 inherited = g_screens[active].owned->terminal;
1833 atomic_fetch_add(&inherited->references, 1);
1834 }
1835 mutex_unlock(&g_mutex);
1836 if (inherited) {
1837 asciichat_error_t result =
1838 submit_screen(screen, inherited->fd, minimum, render, snapshot, bytes,
1839 inherited, fresh_frame);
1840 release_terminal(inherited);
1841 return result;
1842 }
1843 }
1844 // Batch output and finite snapshots retain their synchronous output
1845 // semantics.
1846 if ((!live && !retained_terminal && !platform_isatty(fd)) ||
1847 (GET_OPTION(snapshot_mode) && screen != UI_SCREEN_RENDER_PROGRESS)) {
1848 bool previous_owner = g_owner;
1849 int previous_fd = g_render_fd;
1850 terminal_size_t detected = {0};
1851 // Redirected output has no terminal geometry. Avoid raising a terminal
1852 // error for every frame when rendering to a file, pipe, or null device.
1853 if (!platform_isatty(fd) || !read_terminal_size(fd, &detected) ||
1854 detected.cols <= 0 || detected.rows <= 0)
1855 detected = (terminal_size_t){.cols = GET_OPTION(width),
1856 .rows = GET_OPTION(height)};
1857 g_render_size = detected;
1858 g_owner = true;
1859 g_render_fd = fd;
1861 stats_media_begin(screen == UI_SCREEN_MEDIA);
1862 render(g_render_size, snapshot);
1863 stats_media_end();
1864 g_owner = previous_owner;
1865 g_render_fd = previous_fd;
1866 return ASCIICHAT_OK;
1867 }
1868 if (!lifecycle_is_initialized(&g_lifecycle))
1869 atomic_store(&g_default_fd, fd);
1870 asciichat_error_t err = controller_start();
1871 if (err != ASCIICHAT_OK)
1872 return err;
1873 size_t payload =
1874 render == render_text ? ((const text_snapshot_t *)snapshot)->len : 0;
1875 if (bytes > SIZE_MAX - sizeof(screen_snapshot_t) ||
1876 payload > SIZE_MAX - sizeof(screen_snapshot_t) - bytes)
1877 return SET_ERRNO(ERROR_MEMORY, "UI snapshot is too large");
1878 screen_snapshot_t *copy =
1879 allocate_snapshot(screen, sizeof(*copy) + bytes + payload);
1880 if (!copy)
1881 return SET_ERRNO(ERROR_MEMORY, "Cannot copy UI snapshot");
1882 memcpy(copy->data, snapshot, bytes);
1883 if (payload) {
1884 text_snapshot_t *text = (text_snapshot_t *)copy->data;
1885 text->text = copy->data + bytes;
1886 memcpy((char *)text->text, ((const text_snapshot_t *)snapshot)->text,
1887 payload);
1888 }
1889 uint64_t prepared_ns = time_get_ns();
1890 mutex_lock(&g_mutex);
1891 uint64_t locked_ns = time_get_ns();
1892 if (g_finished) {
1893 mutex_unlock(&g_mutex);
1894 release_snapshot(copy);
1895 return ASCIICHAT_OK;
1896 }
1897 copy->frame_id =
1898 screen == UI_SCREEN_MEDIA && fresh_frame ? ++g_media_frame_id : 0;
1899 copy->media_epoch =
1900 screen == UI_SCREEN_MEDIA ? atomic_load(&g_media_epoch) : 0;
1901 copy->submitted_ns = time_get_ns();
1903 screen == UI_SCREEN_MEDIA ? g_acquisition_started_ns : 0;
1904 screen_t *slot = &g_screens[screen];
1905 bool queue_notice = screen == UI_SCREEN_NOTICE && slot->render;
1906 if (slot->render && !queue_notice) {
1907 // The terminal belongs to the live slot, not to each incoming image.
1908 // Duplicating/closing a Windows console handle per frame introduces console
1909 // RPCs on producers and can serialize them behind ongoing presentation.
1910 copy->terminal = slot->owned->terminal;
1911 atomic_fetch_add(&copy->terminal->references, 1);
1912 } else if (retained_terminal) {
1913 copy->terminal = retained_terminal;
1914 atomic_fetch_add(&copy->terminal->references, 1);
1915 } else {
1916 int retained_fd = platform_dup(fd);
1917 if (retained_fd < 0) {
1918 mutex_unlock(&g_mutex);
1919 release_snapshot(copy);
1921 "Cannot retain UI output descriptor");
1922 }
1923 copy->terminal = SAFE_MALLOC(sizeof(*copy->terminal), screen_terminal_t *);
1924 if (!copy->terminal) {
1925 platform_close(retained_fd);
1926 mutex_unlock(&g_mutex);
1927 release_snapshot(copy);
1928 return SET_ERRNO(ERROR_MEMORY, "Cannot retain UI terminal ownership");
1929 }
1930 atomic_init(&copy->terminal->references, 1);
1931 copy->terminal->fd = retained_fd;
1932 }
1933 int output_fd = copy->terminal->fd;
1934 if (!atomic_load_bool(&g_sync_initialized)) {
1935 err = ui_sync_start(output_fd);
1936 if (err != ASCIICHAT_OK) {
1937 mutex_unlock(&g_mutex);
1938 release_snapshot(copy);
1939 return err;
1940 }
1941 atomic_store_bool(&g_sync_initialized, true);
1942 }
1943 if (queue_notice) {
1944 size_t pending = 1;
1945 screen_t *tail = slot;
1946 while (tail->next) {
1947 tail = tail->next;
1948 ++pending;
1949 }
1950 if (pending >= 64) {
1951 release_snapshot(copy);
1952 mutex_unlock(&g_mutex);
1953 return SET_ERRNO(ERROR_BUFFER_FULL, "UI notice queue is full");
1954 }
1955 screen_t *queued = SAFE_CALLOC(1, sizeof(*queued), screen_t *);
1956 if (!queued) {
1957 release_snapshot(copy);
1958 mutex_unlock(&g_mutex);
1959 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate queued UI notice");
1960 }
1961 *queued = (screen_t){.owned = copy,
1962 .snapshot = copy->data,
1963 .render = render,
1964 .minimum = minimum,
1965 .fd = output_fd,
1966 .dirty = true};
1967 tail->next = queued;
1968 mutex_unlock(&g_mutex);
1969 return ASCIICHAT_OK;
1970 }
1971 screen_snapshot_t *retired = slot->owned;
1972 atomic_store_bool(&g_live, true);
1974 *slot = (screen_t){.owned = copy,
1975 .snapshot = copy->data,
1976 .render = render,
1977 .minimum = minimum,
1978 .fd = output_fd,
1979 .dirty = true};
1980 if (interactive_screen(screen) && screen != UI_SCREEN_STATS &&
1981 (screen != UI_SCREEN_MDNS || !live) &&
1982 !(screen == UI_SCREEN_PROMPT && live &&
1986 publish_screen_locked();
1987 mutex_unlock(&g_mutex);
1988 uint64_t published_ns = time_get_ns();
1989 release_snapshot(retired);
1990 uint64_t retired_ns = time_get_ns();
1991 uint64_t finished_ns = time_get_ns();
1992 if (screen == UI_SCREEN_MEDIA &&
1993 finished_ns - entered_ns > 50 * NS_PER_MS_INT)
1995 "UI_SUBMIT_STAGE: build_ms=%.2f lock_ms=%.2f "
1996 "publish_ms=%.2f retire_ms=%.2f",
1997 (double)(prepared_ns - entered_ns) / NS_PER_MS_INT,
1998 (double)(locked_ns - prepared_ns) / NS_PER_MS_INT,
1999 (double)(published_ns - locked_ns) / NS_PER_MS_INT,
2000 (double)(retired_ns - published_ns) / NS_PER_MS_INT);
2001 return ASCIICHAT_OK;
2002}
2003
2005 terminal_size_t minimum,
2006 ui_render_fn render,
2007 const void *snapshot, size_t bytes) {
2008 return submit_screen(screen, fd, minimum, render, snapshot, bytes, NULL,
2009 true);
2010}
2011
2012static void remove_screen(ui_screen_t screen, int previous,
2013 screen_snapshot_t *expected_owned) {
2014 if (screen < 0 || screen >= UI_SCREEN_COUNT ||
2015 !lifecycle_is_initialized(&g_lifecycle))
2016 return;
2017 mutex_lock(&g_mutex);
2018 if (expected_owned && g_screens[screen].owned != expected_owned) {
2019 mutex_unlock(&g_mutex);
2020 return;
2021 }
2022 // An old callback must not remove a replacement submitted while it rendered.
2023 if (g_render_snapshot && g_rendering_screen == (int)screen &&
2024 g_screens[screen].owned != g_render_snapshot) {
2025 mutex_unlock(&g_mutex);
2026 return;
2027 }
2028 screen_snapshot_t *retired = g_screens[screen].owned;
2029 // Restore focus before retiring the modal so underlying workers never see an
2030 // intermediate empty selection. A departed parent must not regain input.
2031 if (previous < 0 || previous >= UI_SCREEN_COUNT || previous == (int)screen ||
2032 !interactive_screen(previous) ||
2033 (previous != UI_SCREEN_SYNC && !g_screens[previous].render))
2034 previous = -1;
2035 int expected = screen;
2036 atomic_compare_exchange_strong(&g_interactive_screen, &expected, previous);
2037 uint64_t pending =
2038 (g_rendering_layers & (1u << screen)) ? g_render_started : 0;
2039 screen_t *next = g_screens[screen].next;
2040 if (next) {
2041 g_screens[screen] = *next;
2042 SAFE_FREE(next);
2043 g_redraw = true;
2044 } else {
2045 memset(&g_screens[screen], 0, sizeof(screen_t));
2046 }
2047 publish_screen_locked();
2048 bool live = g_rendering_screen >= 0;
2049 for (int i = 0; i < UI_SCREEN_COUNT; ++i)
2050 live |= g_screens[i].render != NULL;
2051 atomic_store_bool(&g_live, live);
2052 // Borrowed pointers inside snapshots may be freed as soon as remove returns.
2053 // A callback removing itself retains its owned bytes until the frame ends.
2054 while (!g_render_snapshot && g_render_completed < pending)
2055 cond_wait(&g_render_done, &g_mutex);
2056 live = g_rendering_screen >= 0;
2057 for (int i = 0; i < UI_SCREEN_COUNT; ++i)
2058 live |= g_screens[i].render != NULL;
2059 if (!live) {
2060 if (!g_render_snapshot && shutdown_is_requested())
2061 ui_error_popup_preserve(atomic_load(&g_default_fd),
2062 unpack_size(atomic_load(&g_size)));
2064 }
2065 mutex_unlock(&g_mutex);
2066 release_snapshot(retired);
2067}
2068
2070 remove_screen(screen, -1, NULL);
2071}
2072
2074 remove_screen(screen, previous, NULL);
2075}
2076
2078 if (!lifecycle_is_initialized(&g_lifecycle))
2079 return false;
2080 mutex_lock(&g_mutex);
2081 screen_snapshot_t *owned = g_screens[UI_SCREEN_NOTICE].owned;
2082 if (owned)
2083 atomic_fetch_add(&owned->references, 1);
2084 mutex_unlock(&g_mutex);
2085 if (!owned)
2086 return false;
2087 ui_notice_key_result_t result = ui_notice_first_use_key(owned->data, key);
2088 if (result == UI_NOTICE_KEY_HELP)
2090 if (result == UI_NOTICE_KEY_COMPLETE)
2091 ui_notice_first_use_complete(owned->data);
2092 if (result == UI_NOTICE_KEY_COMPLETE || result == UI_NOTICE_KEY_DISMISS)
2093 remove_screen(UI_SCREEN_NOTICE, -1, owned);
2094 else if (result == UI_NOTICE_KEY_HANDLED &&
2095 (key == '\r' || key == '\n' || key == KEY_LEFT || key == KEY_RIGHT))
2097 release_snapshot(owned);
2098 return result != UI_NOTICE_KEY_ORDINARY;
2099}
2100
2102 ui_presentation_state_t state = {.screen = -1};
2103 if (!lifecycle_is_initialized(&g_lifecycle))
2104 return state;
2106 if (state.screen == UI_SCREEN_ERROR) {
2107 state.covered =
2109 return state;
2110 }
2111 if (state.screen >= 0 && state.screen < UI_SCREEN_COUNT) {
2112 uint64_t published = atomic_load(&g_input_state);
2113 // Sync has an independent mailbox instead of a controller slot. Treat an
2114 // unpublished slot as absent so the session can dispatch queued switches.
2115 if (!(published & (UINT64_C(1) << state.screen)))
2116 state.screen = -1;
2117 else
2118 state.covered = (published & (UINT64_C(1) << (state.screen + 32))) != 0;
2119 }
2120 return state;
2121}
2122
2123// Bound REP expansion to one terminal row before allocating its expanded text.
2124static char *expand_media_row(const char *row, size_t length, int columns) {
2125 size_t repeats = 0;
2126 for (const char *p = row, *end = row + length; p < end;) {
2127 if (*p != '\033') {
2128 ++p;
2129 continue;
2130 }
2131 const char *next = ansi_skip_escape(p, end);
2132 if (next <= p)
2133 return NULL;
2134 if (next - p >= 3 && p[1] == '[' && next[-1] == 'b') {
2135 size_t count = 0;
2136 for (const char *digit = p + 2; digit < next - 1; ++digit) {
2137 if (*digit < '0' || *digit > '9' || count > (size_t)columns / 10)
2138 return NULL;
2139 count = count * 10 + (size_t)(*digit - '0');
2140 if (count > (size_t)columns)
2141 return NULL;
2142 }
2143 if (!count || count > (size_t)columns - repeats)
2144 return NULL;
2145 repeats += count;
2146 }
2147 p = next;
2148 }
2149 return ansi_expand_rle(row, length);
2150}
2151
2152static void render_text(terminal_size_t size, const void *data) {
2153 const text_snapshot_t *text = data;
2154 bool help_overlay = ui_controller_current_screen() == UI_SCREEN_HELP;
2155 if (text->media && !help_overlay && !GET_OPTION(snapshot_mode) &&
2156 GET_OPTION(fps_counter) && size.cols >= 7 &&
2157 text->dimensions.cols <= size.cols &&
2158 text->dimensions.rows <= size.rows) {
2159 const char *newline = memchr(text->text, '\n', text->len);
2160 size_t first_bytes = newline ? (size_t)(newline - text->text) : text->len;
2161 // Expand REP before clipping, so a repeated glyph cannot cross the counter.
2162 char *first = expand_media_row(text->text, first_bytes, size.cols);
2163 if (first) {
2164 size_t prefix =
2165 utf8_prefix_bytes_for_width(first, strlen(first), size.cols - 7);
2166 ui_controller_write(text->fd, first, prefix);
2167 SAFE_FREE(first);
2168 } else {
2169 ui_controller_printf(text->fd, "\033[1;1H\033[%dX", size.cols - 7);
2170 }
2171 if (newline) {
2172 ui_controller_write(text->fd, "\033[0m\033[2;1H", 10);
2173 ui_controller_write(text->fd, newline + 1, text->len - first_bytes - 1);
2174 }
2175 if (g_render_volume)
2176 append_volume(g_capture, size);
2177 return;
2178 }
2179 if (!text->media || GET_OPTION(snapshot_mode) ||
2180 (text->dimensions.cols <= size.cols &&
2181 text->dimensions.rows <= size.rows) ||
2182 !platform_isatty(g_render_fd >= 0 ? g_render_fd : text->fd)) {
2183 if (text->media && g_render_volume) {
2184 frame_buffer_t *buffer = frame_buffer_create(size.rows, size.cols);
2185 if (buffer) {
2186 frame_buffer_append(buffer, text->text, text->len);
2187 append_volume(buffer, size);
2189 frame_buffer_get_length(buffer));
2190 frame_buffer_destroy(buffer);
2191 } else {
2192 ui_controller_write(text->fd, text->text, text->len);
2193 }
2194 } else {
2195 ui_controller_write(text->fd, text->text, text->len);
2196 }
2197 return;
2198 }
2199 // If only the height exceeds the terminal, every visible row already fits.
2200 // Preserve its SGR and REP sequences instead of expanding and clipping it.
2201 bool counter = !help_overlay && GET_OPTION(fps_counter) && size.cols >= 7;
2202 if (text->dimensions.cols > 0 && text->dimensions.cols < size.cols &&
2203 (!counter || text->dimensions.cols <= size.cols - 7)) {
2204 const char *cursor = text->text;
2205 const char *end = cursor + text->len;
2206 for (int row = 1; row <= size.rows && cursor < end; ++row) {
2207 const char *newline = memchr(cursor, '\n', (size_t)(end - cursor));
2208 size_t length = (size_t)((newline ? newline : end) - cursor);
2209 ui_controller_printf(text->fd, "\033[%d;1H", row);
2210 ui_controller_write(text->fd, cursor, length);
2211 // Keep the old row visible until its replacement has been written.
2212 // The FPS counter owns the right edge of the first row.
2213 if (row != 1 || !counter)
2214 ui_controller_write(text->fd, "\033[K", 3);
2215 cursor += length + (newline ? 1 : 0);
2216 }
2217 if (g_render_volume)
2218 append_volume(g_capture, size);
2219 return;
2220 }
2221 // A paused frame can outlive its original dimensions. Clip its rows instead
2222 // of letting old-sized content wrap and scroll after a terminal resize.
2223 frame_buffer_t *buffer = frame_buffer_create(size.rows, size.cols);
2224 char *line = SAFE_MALLOC(text->len + 1, char *);
2225 char *clipped = SAFE_MALLOC(text->len + UI_CLIPPED_TEXT_OVERHEAD, char *);
2226 if (buffer && line && clipped) {
2227 const char *cursor = text->text;
2228 const char *end = cursor + text->len;
2229 for (int row = 1; row <= size.rows && cursor < end; ++row) {
2230 const char *newline = memchr(cursor, '\n', (size_t)(end - cursor));
2231 size_t length = (size_t)((newline ? newline : end) - cursor);
2232 memcpy(line, cursor, length);
2233 line[length] = '\0';
2234 bool reserved_counter =
2235 row == 1 && GET_OPTION(fps_counter) && size.cols >= 7;
2236 char *expanded = expand_media_row(line, length, text->dimensions.cols);
2237 truncate_with_ellipsis(expanded ? expanded : "", clipped,
2239 size.cols - (reserved_counter ? 7 : 1));
2240 SAFE_FREE(expanded);
2241 frame_buffer_printf(buffer, "\033[%d;1H", row);
2242 frame_buffer_append(buffer, clipped, strlen(clipped));
2243 if (!reserved_counter)
2244 frame_buffer_append(buffer, "\033[K", 3);
2245 cursor += length + (newline ? 1 : 0);
2246 }
2247 if (g_render_volume)
2248 append_volume(buffer, size);
2250 frame_buffer_get_length(buffer));
2251 }
2252 if (buffer)
2253 frame_buffer_destroy(buffer);
2254 SAFE_FREE(line);
2255 SAFE_FREE(clipped);
2256}
2257
2259 if (!lifecycle_is_initialized(&g_lifecycle))
2260 return;
2261 mutex_lock(&g_mutex);
2262 g_redraw = true;
2263 cond_signal(&g_render_requested);
2264 mutex_unlock(&g_mutex);
2265}
2266
2268 atomic_fetch_add(&g_media_epoch, 1);
2269 mutex_lock(&g_mutex);
2270 cond_signal(&g_render_requested);
2271 mutex_unlock(&g_mutex);
2272}
2273
2274static asciichat_error_t present_text(ui_screen_t screen, int fd,
2275 terminal_size_t minimum, const char *data,
2276 size_t len, bool fresh) {
2277 uint64_t entered_ns = time_get_ns();
2278 if (!data || !len || len > UI_CONTROLLER_MAX_FRAME_BYTES)
2279 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid UI frame");
2280 text_snapshot_t text = {
2281 .fd = fd,
2282 .media = screen == UI_SCREEN_MEDIA,
2283 .dimensions = {.cols = GET_OPTION(width), .rows = GET_OPTION(height)},
2284 .len = len,
2285 .text = data};
2286 uint64_t prepared_ns = time_get_ns();
2287 asciichat_error_t err = submit_screen(screen, fd, minimum, render_text, &text,
2288 sizeof(text), NULL, fresh);
2289 uint64_t submitted_ns = time_get_ns();
2290 uint64_t finished_ns = time_get_ns();
2291 if (screen == UI_SCREEN_MEDIA &&
2292 finished_ns - entered_ns > 50 * NS_PER_MS_INT)
2295 "UI_TEXT_STAGE: prepare_ms=%.2f submit_ms=%.2f free_ms=%.2f",
2296 (double)(prepared_ns - entered_ns) / NS_PER_MS_INT,
2297 (double)(submitted_ns - prepared_ns) / NS_PER_MS_INT,
2298 (double)(finished_ns - submitted_ns) / NS_PER_MS_INT);
2299 return err;
2300}
2301
2303 if (!lifecycle_destroy_once(&g_lifecycle))
2304 return;
2305 mutex_lock(&g_mutex);
2306 atomic_store_bool(&g_presentation_stop_requested, true);
2307 cond_signal(&g_render_requested);
2308 mutex_unlock(&g_mutex);
2309 thread_join(&g_thread, NULL);
2310 // Shutdown may precede the next presentation tick. Keep pending errors
2311 // readable after exit without delaying transport teardown or waiting for
2312 // terminal input.
2313 ui_error_popup_preserve(atomic_load(&g_default_fd),
2314 unpack_size(atomic_load(&g_size)));
2315 ui_session_destroy(g_session);
2316 g_session = NULL;
2319 atomic_store_u64(&g_volume_until, 0);
2320 ui_sync_stop();
2321 for (int i = 0; i < UI_SCREEN_COUNT; ++i) {
2322 release_screen(&g_screens[i], i == UI_SCREEN_NOTICE);
2323 }
2324 destroy_media_snapshots();
2325 cond_destroy(&g_render_requested);
2326 cond_destroy(&g_render_done);
2327 mutex_destroy(&g_title_packet_mutex);
2328 mutex_destroy(&g_mutex);
2329 atomic_store_bool(&g_live, false);
2330 atomic_store(&g_background_screen, -1);
2331 atomic_store(&g_screen_mask, 0);
2333 terminal_screen_leave();
2334 // Named entries are reclaimed by the shared debug-registry teardown. Do
2335 // not acquire its writer lock from the cursor-restoration atexit path.
2336 lifecycle_destroy_commit(&g_lifecycle);
2337}
2338
2339asciichat_error_t ui_controller_printf(int fd, const char *format, ...) {
2341 va_list args;
2342 va_start(args, format);
2343 int len = vsnprintf(buffer, sizeof(buffer), format, args);
2344 va_end(args);
2345 if (len < 0)
2346 return SET_ERRNO(ERROR_INVALID_PARAM, "Cannot format terminal output");
2347 size_t bytes =
2348 (size_t)len < sizeof(buffer) ? (size_t)len : sizeof(buffer) - 1;
2349 return ui_controller_write(fd, buffer, bytes);
2350}
2351
2356
2358 if (!platform_isatty(STDOUT_FILENO))
2359 return;
2360 // This path runs immediately before a bounded process exit. Avoid the
2361 // controller locks that may be held by the render thread.
2362 terminal_screen_leave();
2363 static const char sequence[] = "\033[0m\033[?25h";
2364 (void)platform_write_all(STDOUT_FILENO, sequence, sizeof(sequence) - 1);
2365}
2366
2367static void render_logs(terminal_size_t size, const void *snapshot) {
2368 (void)snapshot;
2369 ui_session_logs_render(g_capture, size, g_session);
2370}
2371
2376
2381 return;
2382 }
2383 if (!platform_isatty(STDOUT_FILENO) || GET_OPTION(snapshot_mode))
2384 return;
2385 const bool snapshot = true;
2387 UI_SCREEN_LOGS, STDOUT_FILENO, (terminal_size_t){.cols = 40, .rows = 6},
2388 render_logs, &snapshot, sizeof(snapshot));
2389 if (result != ASCIICHAT_OK)
2390 log_warn("Cannot show application logs: %d", result);
2391}
2392
2394 terminal_size_t minimum,
2395 const char *data, size_t len) {
2396 return present_text(screen, fd, minimum, data, len, true);
2397}
2399 terminal_size_t minimum,
2400 const char *data, size_t len) {
2401 return present_text(screen, fd, minimum, data, len, false);
2402}
ANSI escape sequence utilities and fast color code generation.
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
void errno_notifications_pause(void)
bool errno_notifications_suppress(bool suppress)
asciichat_errno_scope_t errno_scope_begin(void)
void errno_notifications_enable(bool enabled)
size_t errno_title_snapshot(asciichat_error_context_t *latest)
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
#define CLEAR_ERRNO()
@ ASCIICHAT_ERRNO_DISMISSED
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
void atomic_store_int(atomic_t *a, int value)
Atomically store an int value.
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
int atomic_load_int(atomic_t *a)
Atomically load an int value.
log_color_t
Definition color.h:6
@ LOG_COLOR_GREY
Definition color.h:13
@ LOG_COLOR_ERROR
Definition color.h:11
@ LOG_COLOR_INFO
Definition color.h:9
@ LOG_COLOR_WARN
Definition color.h:10
Named object registry for debugging — log identifiable resource names.
void ui_errno_stacks_hide(void)
bool ui_error_popup_visible(void)
Definition error_popup.c:74
void ui_error_popup_preserve(int fd, terminal_size_t size)
uint64_t ui_error_popup_revision(void)
Definition error_popup.c:76
void ui_error_popup_reset(void)
void ui_error_popup_render(frame_buffer_t *out, terminal_size_t size)
terminal_size_t ui_error_popup_minimum(void)
Definition error_popup.c:84
int color_mode
Definition fft.c:26
char cells[(512 *256 *2)]
Definition fft.c:22
unsigned int height
Definition fft.c:24
terminal_render_mode_t render_mode
Definition fft.c:27
unsigned int width
Definition fft.c:24
int platform_close(int fd)
Definition filesystem.c:91
bool fps_counter_frame_begin_id(fps_counter_t *counter, uint64_t frame_id)
⏱️ FPS counter for measuring output write throughput
void frame_buffer_append(frame_buffer_t *buf, const char *str, size_t len)
Append raw bytes to the buffer.
void frame_buffer_set_screen_output_fd(int fd)
Set output file descriptor for terminal screen (splash/status) rendering.
void frame_buffer_destroy(frame_buffer_t *buf)
Destroy a frame buffer.
size_t frame_buffer_get_length(const frame_buffer_t *buf)
Get the current content length of the frame buffer.
const char * frame_buffer_get_content(const frame_buffer_t *buf)
Get a pointer to the buffer content.
frame_buffer_t * frame_buffer_create(int rows, int cols)
Create a new frame buffer.
void frame_buffer_printf(frame_buffer_t *buf, const char *fmt,...)
Printf-style append to the buffer.
void frame_buffer_clear_screen(frame_buffer_t *buf)
Append clear screen and home escape codes (\033[2J\033[H).
struct frame_buffer frame_buffer_t
Opaque frame buffer handle.
const char * ansi_skip_escape(const char *ptr, const char *end)
Find the end of an ANSI CSI escape sequence.
Definition ansi.c:78
#define SAFE_REALLOC(ptr, size, cast)
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
#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.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_BUFFER_FULL
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_FILE_OPERATION
@ ERROR_INVALID_PARAM
@ ERROR_TERMINAL
Definition error_codes.h:68
@ ERROR_THREAD
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
void log_file_msg(const char *fmt,...)
Log to file only, no stderr output.
Definition log/log.c:1952
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
#define US_PER_SEC_INT
Definition time.h:177
utf8_setting_t
UTF-8 support setting (–utf8 flag values).
Definition options.h:263
#define GET_OPTION(field)
Definition options.h:1339
asciichat_error_t options_set_int(const char *name, int value)
Check if an option was explicitly set via command-line.
Definition rcu.c:964
color_setting_t
For options state, this is the live record that ties detected_mode, mode_arg_index,...
Definition options.h:244
#define options_terminal_settings()
Definition options.h:1287
@ COLOR_SETTING_FALSE
Force colors OFF: disable all colors and logging colors.
Definition options.h:250
void keyboard_help_toggle_terminal(int fd)
void fps_counter_reset(fps_counter_t *counter)
Definition fps_counter.c:88
void fps_counter_frame_end(fps_counter_t *counter, uint64_t now)
void fps_counter_write_begin(fps_counter_t *counter)
int keyboard_help_parent_screen(void)
void fps_counter_set_effective_fps(fps_counter_t *counter, unsigned int fps)
size_t fps_counter_format(fps_counter_t *counter, char *buffer, size_t capacity, int columns, bool redrawn)
bool fps_counter_set_visible(fps_counter_t *counter, bool visible)
void fps_counter_destroy(fps_counter_t *counter)
Destroy FPS counter and free resources.
Definition fps_counter.c:73
bool update_banner_is_checking(void)
void fps_counter_render(fps_counter_t *counter, int fd, int columns, bool redrawn)
void fps_counter_write_end(fps_counter_t *counter, bool complete)
struct fps_counter_s fps_counter_t
Opaque FPS counter handle.
Definition fps_counter.h:45
const char * keyboard_help_screen_name(int parent)
fps_counter_t * fps_counter_create(void)
Create a new FPS counter.
Definition fps_counter.c:53
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:87
void truncate_with_ellipsis(const char *input, char *output, size_t output_size, int max_width)
Truncate a string to a maximum display width, with ellipsis.
char * ansi_expand_rle(const char *input, size_t input_len)
Expand RLE escape sequences in a string.
Definition rle.c:14
⚙️ Common definitions, error codes, macros, and types shared throughout the application
struct ui_session ui_session_t
int keyboard_help_previous_interactive(void)
🆘 Interactive keyboard help overlay for session keyboard shortcuts
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
void ui_session_redraw(ui_session_t *s)
void ui_session_resize(ui_session_t *s, int cols, int rows)
int ui_session_select_screen(uint32_t visible_screens)
const char * ui_session_render(ui_session_t *s, const ui_session_view_t *view, uint64_t now_ns)
size_t ui_session_frame_length(const ui_session_t *s)
void ui_session_destroy(ui_session_t *s)
uint64_t ui_session_next_frame_ns(const ui_session_t *s)
bool ui_session_is_covered(const ui_session_t *s)
ui_session_t * ui_session_create(void)
void ui_session_logs_render(frame_buffer_t *output, terminal_size_t size, ui_session_t *s)
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
void ui_notice_flush_snapshot(int fd, const void *data)
Definition notice.c:576
ui_notice_key_result_t ui_notice_first_use_key(const void *data, int key)
Definition notice.c:498
void ui_notice_frame_presented(const void *data)
Definition notice.c:492
const char * ui_notice_title(const void *data)
Definition notice.c:203
void ui_notice_first_use_complete(const void *data)
Definition notice.c:523
ui_notice_key_result_t
Definition notice.h:40
@ UI_NOTICE_KEY_HELP
Definition notice.h:43
@ UI_NOTICE_KEY_ORDINARY
Definition notice.h:41
@ UI_NOTICE_KEY_DISMISS
Definition notice.h:44
@ UI_NOTICE_KEY_COMPLETE
Definition notice.h:45
@ UI_NOTICE_KEY_HANDLED
Definition notice.h:42
bool auto_height
bool auto_width
action_args_t args
⚙️ 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
void ui_output_set_writer(ui_output_write_fn writer)
Definition output.c:13
const char * ui_spinner_glyph(uint64_t elapsed_ns, bool use_colors)
Definition progress.c:36
const char * ui_prompt_title(const void *data)
Definition prompt.c:212
const char * ui_prompt_usage_name(const void *data)
Definition prompt.c:265
int ui_prompt_required_rows(const void *data, int cols)
Definition prompt.c:357
uint64_t options_revision(void)
Definition rcu.c:945
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
void terminal_screen_logs_render_help(frame_buffer_t *output, terminal_size_t size)
Shutdown check system for clean library/application separation.
terminal_capabilities_t apply_color_mode_override(terminal_capabilities_t caps, const terminal_options_t *)
terminal_capabilities_t detect_terminal_capabilities(const terminal_options_t *options)
int terminal_get_size_fd(int fd, terminal_size_t *size)
bool terminal_should_use_utf8(terminal_utf8_setting_t user_setting)
🔤 String Manipulation and Shell Escaping Utilities
For animation config, this is the live record that ties type, fps, speed, hidden_policy together....
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
screen_snapshot_t * snapshot
screen_t * layers
screen_t * screen
When code needs to work with media snapshot slot, it keeps busy, snapshot, capacity here instead of s...
screen_terminal_t * terminal
uint64_t acquisition_started_ns
media_snapshot_slot_t * slot
_Atomic unsigned references
_Atomic unsigned references
ui_render_fn render
screen_snapshot_t * owned
struct screen * next
void * snapshot
terminal_size_t minimum
unsigned page
const char * text
terminal_size_t dimensions
void ui_sync_stop(void)
Definition sync.c:365
asciichat_error_t ui_sync_start(int fd)
Definition sync.c:335
void ui_sync_render(terminal_size_t size)
Definition sync.c:517
bool ui_sync_is_visible(void)
Definition sync.c:383
int ui_sync_output_fd(void)
Definition sync.c:386
bool terminal_screen_logs_help_open(void)
void terminal_screen_logs_reset(void)
Reusable "fixed header + scrolling logs" terminal screen abstraction.
const char * ui_text_color_prefix(log_color_t color)
Definition text.c:18
#define UI_CLIPPED_TEXT_OVERHEAD
Definition text.h:5
⏱️ High-precision timing utilities using sokol_time.h and uthash
void ui_too_small_render(frame_buffer_t *buffer, terminal_size_t actual, terminal_size_t minimum)
Definition too_small.c:44
bool ui_too_small(terminal_size_t actual, terminal_size_t minimum)
Definition too_small.c:10
#define UI_MEDIA_MIN_COLS
Definition too_small.h:9
#define UI_MEDIA_MIN_ROWS
Definition too_small.h:10
void ui_controller_packet_begin(void)
asciichat_error_t ui_controller_start_terminal(int fd)
void ui_controller_remove(ui_screen_t screen)
bool ui_controller_first_use_key(int key)
#define TUI_CONTROLLER_BUFFER_BUFFER_SIZE
void ui_controller_dismiss(ui_screen_t screen, int previous)
void ui_controller_title_render(ui_title_render_t phase)
void ui_controller_invalidate_media(void)
struct screen screen_t
void ui_controller_select_interactive(int screen)
asciichat_error_t ui_controller_submit(ui_screen_t screen, int fd, terminal_size_t minimum, ui_render_fn render, const void *snapshot, size_t bytes)
#define TUI_CONTROLLER_TITLE_BUFFER_SIZE
ui_title_activity_t ui_controller_get_title_activity(void)
void ui_controller_set_effective_fps(unsigned int fps)
bool ui_controller_is_presenting(void)
void ui_controller_restore_terminal_output(void)
void ui_controller_redraw(void)
#define TUI_CONTROLLER_LAST_TITLE_BUFFER_SIZE
asciichat_error_t ui_controller_title_start(const char *mode, int fd)
void ui_controller_frame_acquired_at(uint64_t started_ns)
bool ui_controller_is_owner(void)
void ui_controller_restore_terminal(void)
const animation_sample_t * ui_controller_animation_sample(void)
void ui_controller_toggle_logs(void)
void ui_controller_title_activity(ui_title_activity_t activity)
int ui_controller_current_screen(void)
void ui_controller_packet_end(void)
void ui_controller_finish(int fd, const char *data, size_t len)
terminal_size_t ui_controller_size(void)
#define TUI_LAYER_CAPACITY
void ui_controller_title_ready(void)
void ui_controller_hide_logs(void)
void ui_controller_show_volume(void)
struct media_snapshot_slot media_snapshot_slot_t
void ui_controller_shutdown(void)
int ui_controller_interactive_screen(void)
size_t ui_controller_trim_utf8_chunk(const char *data, size_t length)
bool ui_controller_is_blocked(void)
asciichat_error_t ui_controller_write(int fd, const char *data, size_t len)
asciichat_error_t ui_controller_present_retained(ui_screen_t screen, int fd, terminal_size_t minimum, const char *data, size_t len)
#define TUI_MEDIA_SNAPSHOT_CAPACITY
ui_presentation_state_t ui_controller_state(void)
bool ui_controller_screen_live(ui_screen_t screen)
void ui_controller_title_discovery(bool has_session, bool joining)
asciichat_error_t ui_controller_present(ui_screen_t screen, int fd, terminal_size_t minimum, const char *data, size_t len)
int ui_controller_active_fd(void)
asciichat_error_t ui_controller_printf(int fd, const char *format,...)
ui_title_activity_t
@ UI_TITLE_CONNECTING
@ UI_TITLE_NEGOTIATING
@ UI_TITLE_WAITING_PEERS
@ UI_TITLE_CREATING_SESSION
@ UI_TITLE_ACTIVITY_IDLE
@ UI_TITLE_HANDSHAKE
@ UI_TITLE_RECEIVING
@ UI_TITLE_RECONNECTING
@ UI_TITLE_JOINING_SESSION
#define UI_CONTROLLER_MAX_FRAME_BYTES
ui_screen_t
@ UI_SCREEN_PROMPT
@ UI_SCREEN_COUNT
@ UI_SCREEN_NOTICE
@ UI_SCREEN_LOGS
@ UI_SCREEN_ERRNO
@ 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
@ UI_SCREEN_RENDER_PROGRESS
ui_title_render_t
@ UI_TITLE_FINALIZING
@ UI_TITLE_RENDERING
@ UI_TITLE_FAILED
@ UI_TITLE_IDLE
void(* ui_render_fn)(terminal_size_t size, const void *snapshot)
Update available prompt screen shown after splash.
size_t utf8_prefix_bytes_for_width(const char *str, size_t max_bytes, int max_width)
Return the byte length of a prefix fitting a terminal column limit.
Definition utf8.c:96
🔤 UTF-8 Encoding and Decoding Utilities
int platform_isatty(int fd)
Definition util.c:70