ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
sync.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define TUI_SYNC_NAME_BUFFER_SIZE 256
4#define TUI_SYNC_TYPE_BUFFER_SIZE 24
5#define TUI_SYNC_FILE_BUFFER_SIZE 160
6#define TUI_SYNC_OUTPUT_BUFFER_SIZE 2048
7#define TUI_SYNC_LINE_BUFFER_SIZE 2048
8#define TUI_SYNC_LABEL_BUFFER_SIZE 288
9#define TUI_SYNC_DEADLOCK_BUFFER_SIZE 128
10#define TUI_SYNC_LINE_SHORT_BUFFER_SIZE 1024
11#define TUI_SYNC_NAME_EXTENDED_BUFFER_SIZE 288
12#define TUI_SYNC_STATE_BUFFER_SIZE 128
13#define TUI_SYNC_PADDED_STATE_BUFFER_SIZE 256
14#define TUI_SYNC_PLAIN_ACTIONS_BUFFER_SIZE 32
15#define TUI_SYNC_ACTIONS_BUFFER_SIZE 256
16#define TUI_SYNC_PADDED_ACTIONS_BUFFER_SIZE 32
17#define TUI_SYNC_CHANGES_BUFFER_SIZE 64
18#define TUI_SYNC_PADDED_WAIT_BUFFER_SIZE 48
19#define TUI_SYNC_COLORED_WAIT_BUFFER_SIZE 512
20#define TUI_SYNC_LOCKS_BUFFER_SIZE 96
21#define TUI_SYNC_UNLOCKS_BUFFER_SIZE 96
22#define TUI_SYNC_NUMBERS_BUFFER_SIZE 512
23#define TUI_SYNC_FULL_NAME_BUFFER_SIZE 288
24#define TUI_SYNC_COLORED_NAME_BUFFER_SIZE 640
25#define TUI_SYNC_OUTPUT_SHORT_BUFFER_SIZE 512
26
27/* Existing buffer budgets in bytes, including NUL for text storage. */
28#define SYNC_WAIT_SNAPSHOT_CAPACITY 256
29#define SYNC_ROW_CAPACITY 128
30#define SYNC_OUTPUT_BUFFER_SIZE (64 * 1024)
31
32#include <ascii-chat/common.h>
38#include <ascii-chat/tui/sync.h>
42#include <ascii-chat/ui/table.h>
43#include <ascii-chat/ui/text.h>
48#include <inttypes.h>
49#include <libplatform/compiler.h>
50#include <libplatform/cond.h>
51#include <libplatform/rwlock.h>
52#include <libplatform/system.h>
53#include <libplatform/terminal.h>
54#include <libplatform/thread.h>
55#include <limits.h>
56#include <options/options.h>
57#include <stdatomic.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61
62#ifndef NDEBUG
63
77
97
98static sync_sample_t g_sync_samples[3] = {{.busy = ATOMIC_FLAG_INIT},
99 {.busy = ATOMIC_FLAG_INIT},
100 {.busy = ATOMIC_FLAG_INIT}};
101static _Atomic int g_sync_published = -1;
102static _Atomic int g_sync_selected;
103static _Atomic int g_sync_page_size = 1;
104static _Atomic int g_sync_total;
105static _Atomic bool g_sync_stop;
106static atomic_flag g_sync_starting = ATOMIC_FLAG_INIT;
107static bool g_sync_started;
108static platform_thread_t g_sync_thread;
109static int g_sync_fd = -1;
110static _Thread_local bool g_sync_use_color, g_sync_use_utf8;
111
112static void sync_copy_row(uintptr_t key, uint64_t generation, const char *name,
113 const char *type, const char *file, int line,
114 void *data) {
115 sync_sample_t *sample = data;
116 if (!type || (strcmp(type, "mutex") && strcmp(type, "rwlock") &&
117 strcmp(type, "cond") && strcmp(type, "atomic") &&
118 strcmp(type, "atomic_ptr")))
119 return;
120 // Initializers and their owning resources can both register the same
121 // primitive. Show its latest name once, rather than counting aliases.
122 sync_row_t *r = NULL;
123 for (size_t i = 0; i < sample->count; ++i) {
124 if (sample->rows[i].key != key)
125 continue;
126 if (sample->rows[i].generation >= generation)
127 return;
128 r = &sample->rows[i];
129 break;
130 }
131 if (!r)
132 r = &sample->rows[sample->count++];
133 memset(r, 0, sizeof(*r));
134 r->key = key;
135 r->generation = generation;
136 r->line = line;
137 snprintf(r->name, sizeof(r->name), "%s", name ? name : "?");
138 snprintf(r->type, sizeof(r->type), "%s", type);
139 const char *source = file ? file : "?";
140 for (const char *p = source; *p; ++p) {
141 if (p != source && p[-1] != '/' && p[-1] != '\\')
142 continue;
143 if (((!strncmp(p, "lib", 3) || !strncmp(p, "src", 3)) &&
144 (p[3] == '/' || p[3] == '\\')) ||
145 (!strncmp(p, "include", 7) && (p[7] == '/' || p[7] == '\\'))) {
146 source = p;
147 break;
148 }
149 }
150 snprintf(r->file, sizeof(r->file), "%s", source);
151 for (char *p = r->file; *p; ++p)
152 if (*p == '\\')
153 *p = '/';
154 if (!strcmp(type, "mutex")) {
155 const mutex_t *m = (const mutex_t *)key;
156 r->owner = m->currently_held_by_key;
157 r->locks = m->lock_count + m->trylock_success_count;
158 r->unlocks = m->unlock_count;
159 r->last_ns = m->last_lock_time_ns;
160 } else if (!strcmp(type, "rwlock")) {
161 const rwlock_t *m = (const rwlock_t *)key;
162 r->owner = m->write_held_by_key;
163 r->value = atomic_load(&m->read_lock_count);
164 r->locks = m->rdlock_count + m->wrlock_count;
165 r->unlocks = m->unlock_count;
166 r->last_ns = m->last_wrlock_time_ns;
167 } else if (!strcmp(type, "cond")) {
168 const cond_t *m = (const cond_t *)key;
169 r->value = atomic_load(&m->waiting_count);
170 r->locks = m->wait_count;
171 r->unlocks = m->signal_count + m->broadcast_count;
172 r->last_ns = m->last_wait_time_ns;
173 r->owner = m->last_waiting_key;
174 r->wait_known = cond_total_wait_ns(m, time_get_ns(), &r->wait_ns);
175 } else if (!strcmp(type, "atomic")) {
176 const atomic_t *m = (const atomic_t *)key;
177 r->value = atomic_load(&m->impl);
178 r->changes = m->change_count;
179 r->actions = atomic_load(&m->load_count) + atomic_load(&m->store_count) +
180 atomic_load(&m->cas_count) + atomic_load(&m->fetch_count);
181 r->last_ns = m->last_store_time_ns;
182 } else {
183 const atomic_ptr_t *m = (const atomic_ptr_t *)key;
184 r->value = (uintptr_t)atomic_load(&m->impl);
185 r->changes = m->change_count;
186 r->actions = atomic_load(&m->load_count) + atomic_load(&m->store_count) +
187 atomic_load(&m->cas_count) + atomic_load(&m->exchange_count);
188 r->last_ns = m->last_store_time_ns;
189 }
190 if (strncmp(type, "atomic", 6))
191 r->actions = r->locks + r->unlocks;
192}
193
194static const char *sync_short_name(const sync_row_t *row) {
195 const char *name = strrchr(row->name, '#');
196 return name ? name + 1 : row->name;
197}
198
199static void sync_row_label(const sync_row_t *row, char *label,
200 size_t capacity) {
201 const char *name = sync_short_name(row);
202 if (name != row->name)
203 snprintf(label, capacity, "%s.%" PRIu64, name, row->generation);
204 else
205 snprintf(label, capacity, "%s", name);
206}
207
208static int sync_compare_rows(const void *a, const void *b) {
209 const sync_row_t *x = a, *y = b;
210 if (x->cycle != y->cycle)
211 return x->cycle ? -1 : 1;
212 double x_activity = x->lock_rate + x->unlock_rate + x->change_rate;
213 double y_activity = y->lock_rate + y->unlock_rate + y->change_rate;
214 if (x_activity != y_activity)
215 return x_activity > y_activity ? -1 : 1;
216 if (x->total_score != y->total_score)
217 return x->total_score > y->total_score ? -1 : 1;
218 int result = strcmp(x->type, y->type);
219 if (!result)
220 result = strcmp(sync_short_name(x), sync_short_name(y));
221 return result ? result
222 : x->generation < y->generation ? -1
223 : x->generation > y->generation;
224}
225
226static double sync_rate(uint64_t current, uint64_t previous, double seconds) {
227 return current >= previous && seconds > 0
228 ? (double)(current - previous) / seconds
229 : 0;
230}
231
232static void *sync_collect_main(void *unused) {
233 (void)unused;
234 uint64_t next_sample = 0;
235 while (!atomic_load(&g_sync_stop)) {
237 // Poll the debug shortcut while hidden, but collect registry and waiter
238 // snapshots only for the visible overlay. The pairwise rate comparisons
239 // otherwise compete with live capture and input throughout the session.
240 if (!ui_sync_is_visible() &&
243 next_sample = 0;
244 platform_sleep_ns(10 * NS_PER_MS_INT);
245 continue;
246 }
247 uint64_t now = time_get_ns();
248 if (now >= next_sample) {
249 next_sample = now + 250 * NS_PER_MS_INT;
250 int previous = atomic_load(&g_sync_published);
251 for (int slot = 0; slot < 3; ++slot) {
252 sync_sample_t *sample = &g_sync_samples[slot];
253 if (slot == previous || atomic_flag_test_and_set(&sample->busy))
254 continue;
255 size_t required = 0;
256 bool complete = false;
257 sample->count = 0;
259 sample->capacity, &required, &complete, sync_copy_row, sample);
260 if (result == ASCIICHAT_OK && !complete &&
261 required > sample->capacity &&
262 required <= SIZE_MAX / sizeof(sync_row_t)) {
263 // Diagnostic storage must not enter memory tracking or the registry.
264 sync_row_t *rows = malloc(required * sizeof(*rows));
265 if (!rows)
266 FATAL(ERROR_MEMORY, "Memory allocation failed: %zu bytes",
267 required * sizeof(*rows));
268 if (rows) {
269 UNTRACKED_FREE(sample->rows);
270 sample->rows = rows;
271 sample->capacity = required;
272 }
273 }
274 if (complete) {
275 sample->sampled_ns = now;
277 size_t wait_count = 0;
278 sample->limited = false;
280 waits, 256, &wait_count, &sample->limited);
281 for (size_t i = 0; i < sample->count; ++i) {
282 sync_row_t *r = &sample->rows[i];
283 for (size_t j = 0; j < wait_count; ++j) {
284 if (waits[j].mutex_key == r->key) {
285 ++r->waiters;
286 r->waiter = waits[j].thread_key;
287 r->cycle |= waits[j].cycle;
288 }
289 }
290 if (previous >= 0) {
291 const sync_sample_t *old = &g_sync_samples[previous];
292 double seconds = (double)(now - old->sampled_ns) / NS_PER_SEC_INT;
293 for (size_t j = 0; j < old->count; ++j) {
294 const sync_row_t *p = &old->rows[j];
295 if (p->generation == r->generation) {
296 r->lock_rate = sync_rate(r->locks, p->locks, seconds);
297 r->unlock_rate = sync_rate(r->unlocks, p->unlocks, seconds);
298 r->change_rate = sync_rate(r->changes, p->changes, seconds);
299 break;
300 }
301 }
302 }
303 }
304 uint64_t max_actions = 0, max_wait = 0;
305 for (size_t i = 0; i < sample->count; ++i) {
306 const sync_row_t *r = &sample->rows[i];
307 if (r->actions > max_actions)
308 max_actions = r->actions;
309 if (r->wait_known && r->wait_ns > max_wait)
310 max_wait = r->wait_ns;
311 }
312 // Normalize counts and durations before combining them with equal
313 // weight.
314 for (size_t i = 0; i < sample->count; ++i) {
315 sync_row_t *r = &sample->rows[i];
316 r->total_score =
317 (max_actions ? (double)r->actions / (double)max_actions : 0) +
318 (max_wait && r->wait_known
319 ? (double)r->wait_ns / (double)max_wait
320 : 0);
321 }
322 qsort(sample->rows, sample->count, sizeof(*sample->rows),
323 sync_compare_rows);
324 atomic_store(&g_sync_published, slot);
325 }
326 atomic_flag_clear(&sample->busy);
327 break;
328 }
329 }
330 platform_sleep_ns(10 * NS_PER_MS_INT);
331 }
332 return NULL;
333}
334
336 while (atomic_flag_test_and_set(&g_sync_starting))
337 platform_sleep_ms(1);
339 if (!g_sync_started && platform_isatty(fd) && platform_isatty(STDIN_FILENO)) {
340 g_sync_fd = platform_dup(fd);
341 if (g_sync_fd < 0) {
343 "Cannot retain sync display terminal");
344 } else if ((result = keyboard_init()) != ASCIICHAT_OK) {
345 platform_close(g_sync_fd);
346 g_sync_fd = -1;
347 } else {
348 atomic_store(&g_sync_stop, false);
349 result = platform_thread_create(&g_sync_thread, "sync_collector",
350 sync_collect_main, NULL);
351 if (result == ASCIICHAT_OK) {
352 g_sync_started = true;
353 } else {
355 platform_close(g_sync_fd);
356 g_sync_fd = -1;
357 result = SET_ERRNO(ERROR_THREAD, "Cannot start sync collector");
358 }
359 }
360 }
361 atomic_flag_clear(&g_sync_starting);
362 return result;
363}
364
365void ui_sync_stop(void) {
366 if (!g_sync_started)
367 return;
368 atomic_store(&g_sync_stop, true);
369 thread_join(&g_sync_thread, NULL);
371 platform_close(g_sync_fd);
372 g_sync_fd = -1;
373 for (int i = 0; i < 3; ++i) {
374 UNTRACKED_FREE(g_sync_samples[i].rows);
375 g_sync_samples[i].capacity = g_sync_samples[i].count = 0;
376 }
377 atomic_store(&g_sync_published, -1);
378 if (ui_sync_is_visible())
380 g_sync_started = false;
381}
382
386int ui_sync_output_fd(void) { return g_sync_fd; }
387
388keyboard_key_t ui_sync_handle_key(keyboard_key_t key) {
389 if (key == KEY_0) {
392 return KEY_NONE;
393 }
394 if (!ui_sync_is_visible())
395 return key;
396 // Leave sync selected until the replacement has a complete snapshot.
397 if (key == '=' || key == KEY_BACKTICK || key == KEY_QUESTION || key == ']' ||
398 key == 'o' || key == 'O' || key == 15)
399 return key;
400 if (key == KEY_ESCAPE) {
402 return KEY_NONE;
403 }
404 ui_viewport_t viewport = {.selected = (size_t)atomic_load(&g_sync_selected),
405 .page_size =
406 (size_t)atomic_load(&g_sync_page_size)};
407 ui_viewport_key(&viewport, (size_t)atomic_load(&g_sync_total),
408 viewport.page_size, key);
409 atomic_store(&g_sync_selected, (int)viewport.selected);
410 return key == 'q' || key == 3 ? key : KEY_NONE;
411}
412
413static const char *sync_color(log_color_t color) {
414 return g_sync_use_color ? ui_text_color_prefix(color) : "";
415}
416
417static const char *sync_rate_color(double rate) {
418 return sync_color(rate >= 60 ? LOG_COLOR_ERROR
419 : rate >= 10 ? LOG_COLOR_WARN
420 : rate > 0 ? LOG_COLOR_INFO
422}
423
424// Only the presentation worker writes this storage. Diagnostic rendering must
425// remain usable even when the allocator or another subsystem mutex is stuck.
426static char g_sync_output[SYNC_OUTPUT_BUFFER_SIZE];
427static size_t g_sync_output_used;
428
429static void sync_flush(void) {
430 if (g_sync_output_used) {
431 ui_controller_write(g_sync_fd, g_sync_output, g_sync_output_used);
432 g_sync_output_used = 0;
433 }
434}
435
436static void sync_write(const char *text, size_t length) {
437 if (length > sizeof(g_sync_output) - g_sync_output_used)
438 sync_flush();
439 if (length > sizeof(g_sync_output)) {
440 ui_controller_write(g_sync_fd, text, length);
441 return;
442 }
443 memcpy(g_sync_output + g_sync_output_used, text, length);
444 g_sync_output_used += length;
445}
446
447static void sync_write_line(const char *text, int columns, bool newline,
448 int *measured_width) {
449 char output[TUI_SYNC_OUTPUT_BUFFER_SIZE];
450 size_t used = 0;
451 int visible = 0;
452 const char *prefix = "\033[0m";
453 memcpy(output, prefix, strlen(prefix));
454 used = strlen(prefix);
455 for (size_t i = 0; text[i] && used + 16 < sizeof(output);) {
456 if (text[i] == '\033' && text[i + 1] == '[') {
457 output[used++] = text[i++];
458 output[used++] = text[i++];
459 while (text[i] && !(text[i] >= '@' && text[i] <= '~'))
460 output[used++] = text[i++];
461 if (text[i])
462 output[used++] = text[i++];
463 } else {
464 if (!measured_width && visible >= columns - 1)
465 break;
466 int bytes = utf8_next_char_bytes(text + i, strlen(text + i));
467 if (bytes <= 0)
468 break;
469 int width = utf8_display_width_n(text + i, bytes);
470 if (!measured_width && visible + width > columns - 1)
471 break;
472 memcpy(output + used, text + i, bytes);
473 used += bytes;
474 i += bytes;
475 visible += width;
476 }
477 }
478 if (measured_width) {
479 if (visible > *measured_width)
480 *measured_width = visible;
481 return;
482 }
483 const char *suffix = newline ? "\033[0m\033[K\r\n" : "\033[0m\033[K";
484 memcpy(output + used, suffix, strlen(suffix));
485 used += strlen(suffix);
486 sync_write(output, used);
487}
488
489// Header/detail numbers share the log palette, including hexadecimal addresses.
490static void sync_color_numbers(const char *text, char *output,
491 size_t capacity) {
492 ui_text_values(output, capacity, text);
493}
494
495static void sync_write_numbers(const char *text, int columns, int *measure) {
496 char output[TUI_SYNC_OUTPUT_BUFFER_SIZE];
497 sync_color_numbers(text, output, sizeof(output));
498 sync_write_line(output, columns, true, measure);
499}
500
501static void sync_separator(int columns, int *measure) {
502 if (measure)
503 return;
504 char line[TUI_SYNC_LINE_BUFFER_SIZE];
505 const char *rule = g_sync_use_utf8 ? "━" : "-";
506 size_t width = strlen(rule), used = 0;
507 used += snprintf(line, sizeof(line), "%s", sync_color(LOG_COLOR_DEBUG));
508 for (int col = 0; col < columns - 1 && used + width + 1 < sizeof(line);
509 ++col) {
510 memcpy(line + used, rule, width);
511 used += width;
512 }
513 line[used] = '\0';
514 sync_write_line(line, columns, true, NULL);
515}
516
517void ui_sync_render(terminal_size_t size) {
519 : STDOUT_FILENO);
520 terminal_capabilities_t caps =
522 terminal_color_mode_t mode = GET_OPTION(color_mode);
523 g_sync_use_color =
524 mode != TERM_COLOR_NONE && GET_OPTION(color) != COLOR_SETTING_FALSE &&
525 !GET_OPTION(strip_ansi) &&
526 (mode != TERM_COLOR_AUTO || caps.color_level != TERM_COLOR_NONE);
527 g_sync_use_utf8 = terminal_should_use_utf8(GET_OPTION(force_utf8));
528 // Copy only the visible page before terminal writes; the collector never
529 // waits for output, and the renderer never waits for collection.
531 size_t count = 0, total = 0, cycles = 0;
532 size_t mutexes = 0, conditions = 0, rwlocks = 0, atomics = 0;
533 uint64_t sampled = 0;
534 bool waits_complete = false, limited = false;
535 enum { header_rows = 4, detail_rows = 3, footer_rows = 1 };
536 const int fixed_rows = header_rows + detail_rows + footer_rows;
537 int name_width = (int)strlen("Name");
538 ui_layout_t layout;
539 if (ui_layout_measure(size, header_rows, detail_rows, footer_rows, &layout) !=
541 return;
542 int per_page = layout.body_rows > 0 ? layout.body_rows : 1;
543 if (per_page > 128)
544 per_page = 128;
545 atomic_store(&g_sync_page_size, per_page);
546 int selected = atomic_load(&g_sync_selected);
547 int page = 0, pages = 1;
548 int slot = atomic_load(&g_sync_published);
549 if (slot >= 0) {
550 // Keep the last complete screen if collection is reusing this mailbox.
551 if (atomic_flag_test_and_set(&g_sync_samples[slot].busy)) {
552 return;
553 }
554 sync_sample_t *s = &g_sync_samples[slot];
555 total = s->count;
556 atomic_store(&g_sync_total, total > INT_MAX ? INT_MAX : (int)total);
557 if ((size_t)selected >= total) {
558 int previous = selected;
559 selected = total ? (int)total - 1 : 0;
560 // Do not overwrite a key received while the renderer copies a sample.
561 atomic_compare_exchange_strong(&g_sync_selected, &previous, selected);
562 }
563 pages = total ? (int)((total + per_page - 1) / per_page) : 1;
564 page = selected / per_page;
565 size_t first = (size_t)page * per_page;
566 count = total > first ? total - first : 0;
567 if (count > (size_t)per_page)
568 count = per_page;
569 if (count)
570 memcpy(rows, s->rows + first, count * sizeof(*rows));
571 for (size_t i = 0; i < total; ++i) {
572 cycles += s->rows[i].cycle;
573 const char *type = s->rows[i].type;
574 mutexes += !strcmp(type, "mutex");
575 conditions += !strcmp(type, "cond");
576 rwlocks += !strcmp(type, "rwlock");
577 atomics += !strncmp(type, "atomic", 6);
578 char label[TUI_SYNC_LABEL_BUFFER_SIZE];
579 sync_row_label(&s->rows[i], label, sizeof(label));
580 int width = (int)strlen(label);
581 if (width > name_width)
582 name_width = width;
583 }
584 sampled = s->sampled_ns;
585 waits_complete = s->waits_complete;
586 limited = s->limited;
587 atomic_flag_clear(&s->busy);
588 }
589 if (name_width > 30)
590 name_width = 30;
591 uint64_t now = time_get_ns();
592 selected %= per_page;
593 if ((size_t)selected >= count)
594 selected = count ? (int)count - 1 : 0;
595 char deadlock[TUI_SYNC_DEADLOCK_BUFFER_SIZE];
596 snprintf(deadlock, sizeof(deadlock), "%s%s%s", sync_color(LOG_COLOR_ERROR),
597 g_sync_use_utf8 ? "DEADLOCK ❌" : "DEADLOCK!",
598 sync_color(LOG_COLOR_RESET));
599 int measured_width = 0;
600 for (int pass = 0; pass < 2; ++pass) {
601 int *measure = pass == 0 ? &measured_width : NULL;
603 if (!measure)
604 sync_write("\033[?2026h\033[H", 11);
605 snprintf(
606 line, sizeof(line),
607 "Sync primitives | %zu objects | page %d/%d | item %zu/%zu | age %.1fs",
608 total, page + 1, pages,
609 count ? (size_t)page * per_page + selected + 1 : 0, total,
610 sampled ? (double)(now - sampled) / NS_PER_SEC_INT : 0.0);
611 sync_write_numbers(line, size.cols, measure);
612 snprintf(line, sizeof(line),
613 "%s%s | M=%zu RW=%zu C=%zu A=%zu | %zu mutexes in wait cycles%s",
614 cycles ? sync_color(LOG_COLOR_ERROR) : "",
615 !sampled ? "Waiting for registry"
616 : now - sampled > NS_PER_SEC_INT ? "STALE: collection unavailable"
617 : "Live registered",
618 mutexes, rwlocks, conditions, atomics, cycles,
619 !waits_complete ? " | wait tracker busy"
620 : limited ? " | wait tracker capacity reached"
621 : "");
622 sync_write_numbers(line, size.cols, measure);
623 snprintf(line, sizeof(line), "%s %-8s %-*s %-12s %13s %6s %6s %7s %12s%s",
624 sync_color(LOG_COLOR_GREY), "Type", name_width, "Name",
625 "State/value", "Total Actions", "L/s", "U/s", "Change/s",
626 "Total Wait", sync_color(LOG_COLOR_RESET));
627 sync_write_line(line, size.cols, true, measure);
628 sync_separator(size.cols, measure);
629 for (size_t i = 0; i < count; ++i) {
630 sync_row_t *r = &rows[i];
631 // Parent names may be media paths; keep the primitive visible in the
632 // table. The detail row identifies the source location and address.
634 sync_row_label(r, name, sizeof(name));
635 if (strlen(name) > (size_t)name_width) {
636 const char *suffix = strrchr(name, '.');
637 size_t suffix_bytes =
638 suffix && strspn(suffix + 1, "0123456789") == strlen(suffix + 1)
639 ? strlen(suffix)
640 : 0;
641 if (suffix_bytes >= (size_t)name_width - 1)
642 suffix_bytes = 0;
643 size_t used = 0;
644 int columns = 0;
645 while (name[used]) {
646 int bytes = utf8_next_char_bytes(name + used, strlen(name + used));
647 if (bytes <= 0)
648 break;
649 int width = utf8_display_width_n(name + used, bytes);
650 if (columns + width > name_width - 1 - (int)suffix_bytes)
651 break;
652 used += bytes;
653 columns += width;
654 }
655 name[used++] = '~';
656 if (suffix_bytes) {
657 memmove(name + used, suffix, suffix_bytes);
658 used += suffix_bytes;
659 }
660 name[used] = '\0';
661 }
662 char state[TUI_SYNC_STATE_BUFFER_SIZE];
663 if (r->cycle)
664 snprintf(state, sizeof(state), "DEADLOCK");
665 else if (!strcmp(r->type, "mutex"))
666 snprintf(state, sizeof(state), "%s t=%" PRIxPTR " w=%u",
667 r->cycle ? "CYCLE"
668 : r->owner ? "HELD"
669 : "FREE",
670 r->owner, r->waiters);
671 else if (!strcmp(r->type, "rwlock"))
672 snprintf(state, sizeof(state), "W=%" PRIxPTR " R=%" PRIu64, r->owner,
673 r->value);
674 else if (!strcmp(r->type, "cond"))
675 snprintf(state, sizeof(state), "waiting=%" PRIu64, r->value);
676 else
677 snprintf(state, sizeof(state), "0x%" PRIx64 " (%" PRIu64 ")", r->value,
678 r->value);
679 // Prefer the complete hex value over a clipped redundant decimal copy.
680 if (!strncmp(r->type, "atomic", 6) && strlen(state) > 12)
681 snprintf(state, sizeof(state), "0x%" PRIx64, r->value);
682 char padded_state[TUI_SYNC_PADDED_STATE_BUFFER_SIZE];
683 if (r->cycle) {
684 int width =
685 utf8_display_width(g_sync_use_utf8 ? "DEADLOCK ❌" : "DEADLOCK!");
686 snprintf(padded_state, sizeof(padded_state), "%s%*s", deadlock,
687 12 - width, "");
688 } else {
689 snprintf(padded_state, sizeof(padded_state), "%-12.12s", state);
690 }
691 char plain_actions[TUI_SYNC_PLAIN_ACTIONS_BUFFER_SIZE],
693 format_number_compact(r->actions, plain_actions, sizeof(plain_actions));
694 char padded_actions[TUI_SYNC_PADDED_ACTIONS_BUFFER_SIZE];
695 snprintf(padded_actions, sizeof(padded_actions), "%13s", plain_actions);
696 sync_color_numbers(padded_actions, actions, sizeof(actions));
697 char changes[TUI_SYNC_CHANGES_BUFFER_SIZE];
698 if (!strncmp(r->type, "atomic", 6))
699 snprintf(changes, sizeof(changes), "%s%7.1f",
700 sync_rate_color(r->change_rate), r->change_rate);
701 else
702 snprintf(changes, sizeof(changes), "%s%7s", sync_color(LOG_COLOR_RESET),
703 "-");
704 char wait[TIME_DURATION_BUFFER_SIZE] = "-";
705 if (!strcmp(r->type, "cond")) {
706 if (r->wait_known)
707 time_pretty(r->wait_ns, -1, wait, sizeof(wait));
708 else
709 snprintf(wait, sizeof(wait), "busy");
710 }
711 char padded_wait[TUI_SYNC_PADDED_WAIT_BUFFER_SIZE],
713 snprintf(padded_wait, sizeof(padded_wait), "%12s", wait);
714 sync_color_numbers(padded_wait, colored_wait, sizeof(colored_wait));
715 char locks[TUI_SYNC_LOCKS_BUFFER_SIZE],
717 snprintf(locks, sizeof(locks), "%s%6.1f%s", sync_rate_color(r->lock_rate),
718 r->lock_rate, sync_color(LOG_COLOR_RESET));
719 snprintf(unlocks, sizeof(unlocks), "%s%6.1f%s",
720 sync_rate_color(r->unlock_rate), r->unlock_rate,
721 sync_color(LOG_COLOR_RESET));
722 const ui_table_column_t columns[] = {
723 {"Type", 8, UI_ALIGN_LEFT, false},
724 {"Name", name_width, UI_ALIGN_LEFT, false},
725 {"State/value", 13, UI_ALIGN_LEFT, false},
726 {"Total Actions", 13, UI_ALIGN_RIGHT, false},
727 {"L/s", 6, UI_ALIGN_RIGHT, false},
728 {"U/s", 6, UI_ALIGN_RIGHT, false},
729 {"Change/s", 7, UI_ALIGN_RIGHT, false},
730 {"Total Wait", 12, UI_ALIGN_RIGHT, false}};
731 const char *cells[] = {r->type, name, padded_state, actions,
732 locks, unlocks, changes, colored_wait};
733 ui_table_row(line, sizeof(line), columns, cells, 8, name_width + 83, true,
734 (int)i == selected);
735 sync_write_line(line, size.cols, true, measure);
736 }
737 if (!measure) {
738 // Clear only unused table rows, leaving the live footer in place.
739 for (int row = header_rows + (int)count + 1; row < size.rows - 3; ++row) {
740 snprintf(line, sizeof(line), "\033[%d;1H\033[K", row);
741 sync_write(line, strlen(line));
742 }
743 snprintf(line, sizeof(line), "\033[%d;1H",
744 size.rows > 3 ? size.rows - 3 : 1);
745 sync_write(line, strlen(line));
746 }
747 sync_separator(size.cols, measure);
748 if (count) {
749 sync_row_t *r = &rows[selected];
750 snprintf(line, sizeof(line), "%d @0x%" PRIxPTR, r->line, r->key);
751 char numbers[TUI_SYNC_NUMBERS_BUFFER_SIZE];
752 sync_color_numbers(line, numbers, sizeof(numbers));
753 char full_name[TUI_SYNC_FULL_NAME_BUFFER_SIZE],
755 sync_row_label(r, full_name, sizeof(full_name));
756 sync_color_numbers(full_name, colored_name, sizeof(colored_name));
757 snprintf(line, sizeof(line), "%.*s%.*s%.*s:%.*s | %.*s",
758 (int)(sizeof(line) / 5), sync_color(LOG_COLOR_DEV),
759 (int)(sizeof(line) / 5), r->file, (int)(sizeof(line) / 5),
760 sync_color(LOG_COLOR_RESET), (int)(sizeof(line) / 5), numbers,
761 (int)(sizeof(line) / 5), colored_name);
762 sync_write_line(line, size.cols, true, measure);
763 snprintf(line, sizeof(line),
764 "owner=0x%" PRIxPTR " waiter=0x%" PRIxPTR " | value=%" PRIu64
765 " | last operation %.2fs ago%s%s",
766 r->owner, r->waiter, r->value,
767 r->last_ns ? (double)(now - r->last_ns) / NS_PER_SEC_INT : 0.0,
768 r->cycle ? " " : "", r->cycle ? deadlock : "");
769 sync_write_numbers(line, size.cols, measure);
770 } else if (!measure) {
771 snprintf(line, sizeof(line), "\033[%d;1H\033[K\033[%d;1H\033[K",
772 size.rows - 2, size.rows - 1);
773 sync_write(line, strlen(line));
774 }
775 snprintf(line, sizeof(line), "\033[%d;1H", size.rows);
776 if (!measure)
777 sync_write(line, strlen(line));
778 snprintf(line, sizeof(line),
779 "%s0%s/%sEsc%s close | %s?%s help | %sLeft%s/%sRight%s page | "
780 "%sUp%s/%sDown%s select | "
781 "%sHome%s/%sEnd%s first/last",
782 sync_color(LOG_COLOR_FATAL), sync_color(LOG_COLOR_RESET),
783 sync_color(LOG_COLOR_WARN), sync_color(LOG_COLOR_RESET),
784 sync_color(LOG_COLOR_WARN), sync_color(LOG_COLOR_RESET),
785 sync_color(LOG_COLOR_WARN), sync_color(LOG_COLOR_RESET),
786 sync_color(LOG_COLOR_WARN), sync_color(LOG_COLOR_RESET),
787 sync_color(LOG_COLOR_WARN), sync_color(LOG_COLOR_RESET),
788 sync_color(LOG_COLOR_WARN), sync_color(LOG_COLOR_RESET),
789 sync_color(LOG_COLOR_WARN), sync_color(LOG_COLOR_RESET),
790 sync_color(LOG_COLOR_WARN), sync_color(LOG_COLOR_RESET));
791 sync_write_line(line, size.cols, false, measure);
792 if (measure) {
793 terminal_size_t minimum = {.cols = measured_width + 1,
794 .rows = fixed_rows + 1};
795 if (ui_too_small(size, minimum)) {
797 size_t length =
798 ui_too_small_format(output, sizeof(output), size, minimum);
799 ui_controller_write(g_sync_fd, output, length);
800 return;
801 }
802 }
803 }
804 sync_write("\033[?2026l", 8);
805 sync_flush();
806}
807
808#else
810 (void)fd;
811 return ASCIICHAT_OK;
812}
813void ui_sync_stop(void) {}
814bool ui_sync_is_visible(void) { return false; }
815keyboard_key_t ui_sync_handle_key(keyboard_key_t key) { return key; }
816void ui_sync_render(terminal_size_t size) { (void)size; }
817int ui_sync_output_fd(void) { return -1; }
818#endif
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
log_color_t
Definition color.h:6
@ LOG_COLOR_RESET
Definition color.h:14
@ LOG_COLOR_GREY
Definition color.h:13
@ LOG_COLOR_FATAL
Definition color.h:12
@ LOG_COLOR_ERROR
Definition color.h:11
@ LOG_COLOR_DEV
Definition color.h:7
@ LOG_COLOR_DEBUG
Definition color.h:8
@ LOG_COLOR_INFO
Definition color.h:9
@ LOG_COLOR_WARN
Definition color.h:10
Named object registry for debugging — log identifiable resource names.
int color_mode
Definition fft.c:26
char cells[(512 *256 *2)]
Definition fft.c:22
audio_visualization_source_t source
Definition fft.c:25
unsigned int width
Definition fft.c:24
int platform_close(int fd)
Definition filesystem.c:91
Buffered terminal frame rendering.
#define UNTRACKED_FREE(ptr)
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
unsigned long long uint64_t
asciichat_error_t named_registry_try_snapshot(size_t capacity, size_t *required, bool *completed, named_snapshot_fn copy, void *data)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_FILE_OPERATION
@ ERROR_THREAD
#define NS_PER_SEC_INT
Definition time.h:173
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:406
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
#define NS_PER_MS_INT
Definition time.h:172
#define GET_OPTION(field)
Definition options.h:1339
#define options_terminal_settings()
Definition options.h:1287
@ COLOR_SETTING_FALSE
Force colors OFF: disable all colors and logging colors.
Definition options.h:250
int utf8_display_width_n(const char *str, size_t max_bytes)
Calculate terminal display width of a UTF-8 string up to byte limit.
Definition utf8.c:106
int colored_string_set_output_fd(int fd)
int utf8_display_width(const char *str)
Calculate terminal display width of a UTF-8 string.
Definition utf8.c:102
int utf8_next_char_bytes(const char *str, size_t max_bytes)
Get byte length of next UTF-8 character.
Definition utf8.c:183
⚙️ Common definitions, error codes, macros, and types shared throughout the application
void keyboard_destroy(void)
Definition keyboard.c:15
int keyboard_help_previous_interactive(void)
🆘 Interactive keyboard help overlay for session keyboard shortcuts
bool mutex_stack_try_snapshot(mutex_wait_snapshot_t *waits, size_t capacity, size_t *count, bool *limited)
Definition mutex.c:529
Per-thread mutex lock stack for deadlock detection.
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
terminal_capabilities_t detect_terminal_capabilities(const terminal_options_t *options)
bool terminal_should_use_utf8(terminal_utf8_setting_t user_setting)
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:114
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
For mutex wait snapshot, this is the live record that ties mutex_key, thread_key, since_ns,...
Definition mutex.h:122
uintptr_t thread_key
Definition mutex.h:124
char type[24]
Definition sync.c:69
uint64_t actions
Definition sync.c:66
double unlock_rate
Definition sync.c:68
unsigned waiters
Definition sync.c:72
char name[256]
Definition sync.c:69
double total_score
Definition sync.c:68
bool cycle
Definition sync.c:73
uint64_t changes
Definition sync.c:66
uintptr_t key
Definition sync.c:65
int line
Definition sync.c:71
char file[160]
Definition sync.c:70
uint64_t generation
Definition sync.c:66
uint64_t wait_ns
Definition sync.c:67
uint64_t value
Definition sync.c:66
uintptr_t owner
Definition sync.c:65
uint64_t locks
Definition sync.c:66
double change_rate
Definition sync.c:68
uint64_t unlocks
Definition sync.c:66
uint64_t last_ns
Definition sync.c:66
uintptr_t waiter
Definition sync.c:65
double lock_rate
Definition sync.c:68
bool wait_known
Definition sync.c:73
sync row keeps the values that move through the subsystem: key, owner, waiter, generation....
Definition sync.c:84
size_t capacity
Definition sync.c:87
bool waits_complete
Definition sync.c:89
size_t count
Definition sync.c:87
sync_row_t * rows
Definition sync.c:86
bool limited
Definition sync.c:89
atomic_flag busy
Definition sync.c:85
uint64_t sampled_ns
Definition sync.c:88
int body_rows
Definition ui/layout.h:9
For ui viewport, this is the live record that ties selected, first_visible, page_size together....
Definition viewport.h:20
size_t selected
Definition viewport.h:21
size_t page_size
Definition viewport.h:21
#define TUI_SYNC_STATE_BUFFER_SIZE
Definition sync.c:12
#define TUI_SYNC_OUTPUT_BUFFER_SIZE
Definition sync.c:6
#define TUI_SYNC_FULL_NAME_BUFFER_SIZE
Definition sync.c:23
keyboard_key_t ui_sync_handle_key(keyboard_key_t key)
Definition sync.c:388
#define TUI_SYNC_NAME_BUFFER_SIZE
Definition sync.c:3
void ui_sync_stop(void)
Definition sync.c:365
#define SYNC_OUTPUT_BUFFER_SIZE
Definition sync.c:30
#define TUI_SYNC_DEADLOCK_BUFFER_SIZE
Definition sync.c:9
#define TUI_SYNC_FILE_BUFFER_SIZE
Definition sync.c:5
#define TUI_SYNC_ACTIONS_BUFFER_SIZE
Definition sync.c:15
#define TUI_SYNC_CHANGES_BUFFER_SIZE
Definition sync.c:17
asciichat_error_t ui_sync_start(int fd)
Definition sync.c:335
#define TUI_SYNC_PLAIN_ACTIONS_BUFFER_SIZE
Definition sync.c:14
#define TUI_SYNC_PADDED_ACTIONS_BUFFER_SIZE
Definition sync.c:16
#define SYNC_WAIT_SNAPSHOT_CAPACITY
Definition sync.c:28
#define TUI_SYNC_NAME_EXTENDED_BUFFER_SIZE
Definition sync.c:11
void ui_sync_render(terminal_size_t size)
Definition sync.c:517
#define SYNC_ROW_CAPACITY
Definition sync.c:29
#define TUI_SYNC_LOCKS_BUFFER_SIZE
Definition sync.c:20
bool ui_sync_is_visible(void)
Definition sync.c:383
#define TUI_SYNC_LABEL_BUFFER_SIZE
Definition sync.c:8
#define TUI_SYNC_COLORED_WAIT_BUFFER_SIZE
Definition sync.c:19
#define TUI_SYNC_COLORED_NAME_BUFFER_SIZE
Definition sync.c:24
#define TUI_SYNC_TYPE_BUFFER_SIZE
Definition sync.c:4
#define TUI_SYNC_PADDED_WAIT_BUFFER_SIZE
Definition sync.c:18
#define TUI_SYNC_LINE_BUFFER_SIZE
Definition sync.c:7
#define TUI_SYNC_NUMBERS_BUFFER_SIZE
Definition sync.c:22
#define TUI_SYNC_UNLOCKS_BUFFER_SIZE
Definition sync.c:21
#define TUI_SYNC_OUTPUT_SHORT_BUFFER_SIZE
Definition sync.c:25
int ui_sync_output_fd(void)
Definition sync.c:386
#define TUI_SYNC_PADDED_STATE_BUFFER_SIZE
Definition sync.c:13
#define TUI_SYNC_LINE_SHORT_BUFFER_SIZE
Definition sync.c:10
size_t ui_table_row(char *out, size_t cap, const ui_table_column_t *cols, const char *const *cells, size_t count, int width, bool selectable, bool selected)
When code needs to work with ui table, it keeps columns, column_count, row_count, viewport here inste...
Definition table.c:18
const char * ui_text_color_prefix(log_color_t color)
Definition text.c:18
void ui_text_values(char *out, size_t cap, const char *text)
Definition text.c:154
@ UI_ALIGN_RIGHT
Definition text.h:14
@ UI_ALIGN_LEFT
Definition text.h:14
⏱️ High-precision timing utilities using sokol_time.h and uthash
size_t ui_too_small_format(char *output, size_t capacity, terminal_size_t actual, terminal_size_t minimum)
Definition too_small.c:15
bool ui_too_small(terminal_size_t actual, terminal_size_t minimum)
Definition too_small.c:10
void ui_controller_select_interactive(int screen)
int ui_controller_current_screen(void)
int ui_controller_interactive_screen(void)
asciichat_error_t ui_controller_write(int fd, const char *data, size_t len)
@ UI_SCREEN_SYNC
@ UI_SCREEN_HELP
void ui_input_poll_sync(void)
Definition tui/input.c:301
asciichat_error_t ui_layout_measure(terminal_size_t size, int header, int detail, int footer, ui_layout_t *out)
Definition ui/layout.c:3
🔤 UTF-8 Encoding and Decoding Utilities
void format_number_compact(uint64_t value, char *out, size_t out_capacity)
Definition util/format.c:53
📊 String Formatting Utilities
int platform_isatty(int fd)
Definition util.c:70
bool ui_viewport_key(ui_viewport_t *v, size_t count, size_t rows, keyboard_key_t key)
Definition viewport.c:40