ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
colorscheme.c
Go to the documentation of this file.
1
10
11/* Storage capacities in elements; text buffers include the terminating NUL. */
12#define OPTIONS_COLORSCHEME_TEMP_BUFFER_SIZE 128
13#define OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE 8192
14
15#include <defer.h>
18#include <ascii-chat/common.h>
20#include <libplatform/terminal.h>
21#include <util/string.h>
23#include <sys/stat.h>
24#include <libplatform/filesystem.h>
25#include <libplatform/lifecycle.h>
26#include <ascii-chat-deps/tomlc17/src/tomlc17.h>
27#include <string.h>
28#include <stdlib.h>
29#include <stdio.h>
30#include <limits.h>
31#include <stdatomic.h>
32#include <libplatform/keyboard.h>
34
35/* ============================================================================
36 * Global State
37 * ============================================================================ */
38
39static color_scheme_t g_active_scheme = {0};
40static _Atomic uint64_t g_scheme_revision = 1;
41static lifecycle_t g_colorscheme_lifecycle = LIFECYCLE_INIT;
42
43/* Mutex for color scheme compilation - used by both colorscheme.c and logging.c */
44/* Must be statically initialized with PTHREAD_MUTEX_INITIALIZER to avoid deadlock
45 * EXCEPTION: Emscripten/WASM with pthreads doesn't support static mutex initialization properly,
46 * so we initialize it explicitly in colorscheme_init() like Windows. */
47#if defined(_WIN32) || defined(__EMSCRIPTEN__)
48mutex_t g_colorscheme_mutex = {.impl = {0}, .name = NULL}; /* Windows CRITICAL_SECTION or Emscripten pthread_mutex_t - initialized in colorscheme_init() */
49#else
50mutex_t g_colorscheme_mutex = {.impl = PTHREAD_MUTEX_INITIALIZER, .name = NULL}; /* POSIX pthread_mutex_t */
51#endif
52
53/* ============================================================================
54 * Built-In Color Schemes
55 * ============================================================================ */
56
61static const color_scheme_t PASTEL_SCHEME = {.name = "pastel",
62 .description = "Soft pastel colors (ascii-chat default)",
63 .log_colors_dark =
64 {
65 {240, 150, 100}, /* DEV: Orange */
66 {101, 172, 225}, /* DEBUG: Cyan */
67 {144, 224, 112}, /* INFO: Green */
68 {240, 204, 145}, /* WARN: Yellow */
69 {232, 93, 111}, /* ERROR: Red */
70 {200, 160, 216}, /* FATAL: Magenta */
71 {128, 128, 128}, /* GREY */
72 {255, 255, 255} /* RESET */
73 },
74 .has_light_variant = true,
75 .log_colors_light =
76 {
77 {156, 97, 65}, /* DEV: Darker orange (matches dark) */
78 {65, 111, 146}, /* DEBUG: Darker cyan (matches dark) */
79 {93, 145, 72}, /* INFO: Darker green (matches dark) */
80 {156, 132, 94}, /* WARN: Darker yellow (matches dark) */
81 {150, 60, 72}, /* ERROR: Darker red (matches dark) */
82 {130, 104, 140}, /* FATAL: Darker magenta (matches dark) */
83 {80, 80, 80}, /* GREY: Darker gray */
84 {0, 0, 0} /* RESET */
85 },
86 .is_builtin = true};
87
92static const color_scheme_t NORD_SCHEME = {.name = "nord",
93 .description = "Arctic, muted Nord theme colors",
94 .log_colors_dark =
95 {
96 {191, 144, 97}, /* DEV: Nord orange */
97 {143, 188, 187}, /* DEBUG: Nord frost */
98 {163, 190, 140}, /* INFO: Nord green */
99 {235, 203, 139}, /* WARN: Nord sun */
100 {191, 97, 106}, /* ERROR: Nord red */
101 {180, 142, 173}, /* FATAL: Nord purple */
102 {216, 222, 233}, /* GREY: Nord snow */
103 {255, 255, 255} /* RESET */
104 },
105 .has_light_variant = true,
106 .log_colors_light =
107 {
108 {76, 86, 106}, /* DEV: Nord bg dark */
109 {67, 76, 94}, /* DEBUG: Nord bg darker */
110 {89, 131, 52}, /* INFO: Darker green */
111 {191, 144, 0}, /* WARN: Darker yellow */
112 {129, 30, 44}, /* ERROR: Darker red */
113 {110, 76, 101}, /* FATAL: Darker purple */
114 {76, 86, 106}, /* GREY */
115 {0, 0, 0} /* RESET */
116 },
117 .is_builtin = true};
118
123static const color_scheme_t SOLARIZED_SCHEME = {.name = "solarized",
124 .description = "Solarized theme - precision colors",
125 .log_colors_dark =
126 {
127 {203, 75, 22}, /* DEV: Orange */
128 {42, 161, 152}, /* DEBUG: Cyan */
129 {133, 153, 0}, /* INFO: Green */
130 {181, 137, 0}, /* WARN: Yellow */
131 {220, 50, 47}, /* ERROR: Red */
132 {108, 113, 196}, /* FATAL: Violet */
133 {101, 123, 142}, /* GREY: Base0 */
134 {255, 255, 255} /* RESET */
135 },
136 .has_light_variant = true,
137 .log_colors_light =
138 {
139 {161, 105, 70}, /* DEV: Brown/Orange */
140 {20, 110, 101}, /* DEBUG: Darker cyan */
141 {89, 100, 0}, /* INFO: Darker green */
142 {101, 76, 0}, /* WARN: Darker yellow */
143 {153, 0, 0}, /* ERROR: Darker red */
144 {68, 68, 153}, /* FATAL: Darker violet */
145 {42, 61, 76}, /* GREY */
146 {0, 0, 0} /* RESET */
147 },
148 .is_builtin = true};
149
154static const color_scheme_t DRACULA_SCHEME = {.name = "dracula",
155 .description = "Dracula dark theme - vampiric colors",
156 .log_colors_dark =
157 {
158 {255, 121, 84}, /* DEV: Orange */
159 {139, 233, 253}, /* DEBUG: Cyan */
160 {80, 250, 123}, /* INFO: Green */
161 {241, 250, 140}, /* WARN: Yellow */
162 {255, 121, 198}, /* ERROR: Pink */
163 {189, 147, 249}, /* FATAL: Purple */
164 {98, 114, 164}, /* GREY: Comment */
165 {255, 255, 255} /* RESET */
166 },
167 .has_light_variant = false,
168 .is_builtin = true};
169
174static const color_scheme_t GRUVBOX_SCHEME = {.name = "gruvbox",
175 .description = "Gruvbox theme - retro warm colors",
176 .log_colors_dark =
177 {
178 {254, 128, 25}, /* DEV: bright_orange */
179 {142, 192, 124}, /* DEBUG: bright_green */
180 {142, 192, 124}, /* INFO: bright_green */
181 {250, 189, 47}, /* WARN: bright_yellow */
182 {251, 73, 52}, /* ERROR: bright_red */
183 {211, 134, 155}, /* FATAL: bright_purple */
184 {168, 153, 132}, /* GREY: gray */
185 {255, 255, 255} /* RESET */
186 },
187 .has_light_variant = true,
188 .log_colors_light =
189 {
190 {175, 58, 3}, /* DEV: faded_orange */
191 {121, 116, 14}, /* DEBUG: faded_green */
192 {121, 116, 14}, /* INFO: faded_green */
193 {181, 118, 20}, /* WARN: faded_yellow */
194 {157, 0, 6}, /* ERROR: faded_red */
195 {108, 52, 107}, /* FATAL: faded_purple */
196 {105, 104, 98}, /* GREY */
197 {0, 0, 0} /* RESET */
198 },
199 .is_builtin = true};
200
205static const color_scheme_t MONOKAI_SCHEME = {.name = "monokai",
206 .description = "Monokai theme - vibrant coding colors",
207 .log_colors_dark =
208 {
209 {253, 151, 31}, /* DEV: Orange */
210 {166, 226, 46}, /* DEBUG: Green */
211 {174, 213, 129}, /* INFO: Light green */
212 {241, 250, 140}, /* WARN: Yellow */
213 {249, 38, 114}, /* ERROR: Magenta */
214 {174, 129, 255}, /* FATAL: Purple */
215 {117, 113, 94}, /* GREY: Comment */
216 {255, 255, 255} /* RESET */
217 },
218 .has_light_variant = false,
219 .is_builtin = true};
220
225static const color_scheme_t BASE16_DEFAULT_SCHEME = {.name = "base16-default",
226 .description = "Base16 Default theme (Chris Kempson)",
227 .log_colors_dark =
228 {
229 {220, 150, 86}, /* DEV: base09 (orange) */
230 {134, 193, 185}, /* DEBUG: base0C (cyan) */
231 {161, 181, 108}, /* INFO: base0B (green) */
232 {247, 202, 136}, /* WARN: base0A (yellow) */
233 {171, 70, 66}, /* ERROR: base08 (red) */
234 {186, 139, 175}, /* FATAL: base0E (magenta) */
235 {88, 88, 88}, /* GREY: base03 */
236 {248, 248, 248} /* RESET: base07 */
237 },
238 .has_light_variant = true,
239 .log_colors_light =
240 {
241 {161, 105, 70}, /* DEV: base0F (brown) */
242 {124, 175, 194}, /* DEBUG: base0D (blue) */
243 {161, 181, 108}, /* INFO: base0B (green) */
244 {247, 202, 136}, /* WARN: base0A (yellow) */
245 {171, 70, 66}, /* ERROR: base08 (red) */
246 {186, 139, 175}, /* FATAL: base0E (magenta) */
247 {184, 184, 184}, /* GREY: base04 */
248 {24, 24, 24} /* RESET: base00 */
249 },
250 .is_builtin = true};
251
255static const color_scheme_t *BUILTIN_SCHEMES[] = {&PASTEL_SCHEME, &NORD_SCHEME, &SOLARIZED_SCHEME, &DRACULA_SCHEME, &GRUVBOX_SCHEME, &MONOKAI_SCHEME, &BASE16_DEFAULT_SCHEME};
256
257#define NUM_BUILTIN_SCHEMES (sizeof(BUILTIN_SCHEMES) / sizeof(BUILTIN_SCHEMES[0]))
258
259/* ============================================================================
260 * Internal Functions
261 * ============================================================================ */
262
266static const color_scheme_t *find_builtin_scheme(const char *name) {
267 if (!name)
268 return NULL;
269
270 /* Handle "default" alias */
271 if (strcmp(name, "default") == 0) {
272 name = "pastel";
273 }
274
275 for (size_t i = 0; i < NUM_BUILTIN_SCHEMES; i++) {
276 if (strcmp(BUILTIN_SCHEMES[i]->name, name) == 0) {
277 return BUILTIN_SCHEMES[i];
278 }
279 }
280
281 return NULL;
282}
283
284/* ============================================================================
285 * Public API: Initialization
286 * ============================================================================ */
287
289 if (lifecycle_is_initialized(&g_colorscheme_lifecycle)) {
290 return ASCIICHAT_OK;
291 }
292
293 /* NOTE: Mutex is already statically initialized on POSIX with PTHREAD_MUTEX_INITIALIZER.
294 * On Windows and Emscripten/WASM, we initialize it here. Do NOT call mutex_init() on native POSIX
295 * because double-initialization of pthread_mutex_t causes undefined behavior and deadlocks.
296 * Emscripten with pthreads requires explicit initialization because PTHREAD_MUTEX_INITIALIZER
297 * doesn't work correctly in threaded WASM builds. */
298#if defined(_WIN32) || defined(__EMSCRIPTEN__)
299 static bool mutex_initialized = false;
300 if (!mutex_initialized) {
301#ifdef __EMSCRIPTEN__
302#else
303#endif
304 mutex_init(&g_colorscheme_mutex, "colorscheme");
305 mutex_initialized = true;
306 } else {
307 }
308#else
309#endif
310
311 /* Load default scheme */
312 const color_scheme_t *pastel = find_builtin_scheme("pastel");
313 if (!pastel) {
314 return SET_ERRNO(ERROR_CONFIG, "Failed to load default pastel scheme");
315 }
316
317 memcpy(&g_active_scheme, pastel, sizeof(color_scheme_t));
318 atomic_fetch_add(&g_scheme_revision, 1);
319
320 /* Mark as initialized */
321 lifecycle_init(&g_colorscheme_lifecycle, "colorscheme");
322#if !defined(_WIN32) && !defined(__EMSCRIPTEN__)
323 // Register the statically initialized mutex without initializing its pthread storage again.
325#endif
326
327 return ASCIICHAT_OK;
328}
329
331 if (!compiled) {
332 return;
333 }
334
335 /* Free allocated color code strings */
336 for (int i = 0; i < 8; i++) {
337 char *str_16 = (char *)compiled->codes_16[i];
338 char *str_256 = (char *)compiled->codes_256[i];
339 char *str_truecolor = (char *)compiled->codes_truecolor[i];
340 /* Only free non-NULL pointers - protects against uninitialized data */
341 if (str_16 != NULL) {
342 SAFE_FREE(str_16);
343 }
344 if (str_256 != NULL) {
345 SAFE_FREE(str_256);
346 }
347 if (str_truecolor != NULL) {
348 SAFE_FREE(str_truecolor);
349 }
350 }
351 memset(compiled, 0, sizeof(compiled_color_scheme_t));
352}
353
355 if (!lifecycle_is_initialized(&g_colorscheme_lifecycle)) {
356 return;
357 }
358
359 mutex_lock(&g_colorscheme_mutex);
360 memset(&g_active_scheme, 0, sizeof(color_scheme_t));
361 atomic_fetch_add(&g_scheme_revision, 1);
362
363 /* Mark as uninitialized */
364 lifecycle_shutdown(&g_colorscheme_lifecycle);
365
366 mutex_unlock(&g_colorscheme_mutex);
367
368 /* NOTE: Do NOT call mutex_destroy() on native POSIX because the mutex is statically
369 * initialized with PTHREAD_MUTEX_INITIALIZER. Destroying a statically-initialized
370 * mutex is undefined behavior. On Windows and Emscripten, we must destroy the mutex
371 * because it was explicitly initialized in colorscheme_init(). */
372#if defined(_WIN32) || defined(__EMSCRIPTEN__)
373 mutex_destroy(&g_colorscheme_mutex);
374#endif
375}
376
377/* ============================================================================
378 * Public API: Scheme Management
379 * ============================================================================ */
380
382 if (!lifecycle_is_initialized(&g_colorscheme_lifecycle)) {
383 /* Lazy initialization of color system */
385 }
386
387 static _Thread_local color_scheme_t snapshot;
388 static _Thread_local uint64_t revision;
389 if (revision != atomic_load(&g_scheme_revision)) {
390 mutex_lock(&g_colorscheme_mutex);
391 memcpy(&snapshot, &g_active_scheme, sizeof(snapshot));
392 revision = atomic_load(&g_scheme_revision);
393 mutex_unlock(&g_colorscheme_mutex);
394 }
395 return &snapshot;
396}
397
399 if (!name) {
400 return SET_ERRNO(ERROR_INVALID_PARAM, "Scheme name is NULL");
401 }
402
403 /* Ensure color system is initialized */
404 if (!lifecycle_is_initialized(&g_colorscheme_lifecycle)) {
406 }
407
408 color_scheme_t scheme = {0};
410
411 /* Try loading as built-in scheme first */
412 const color_scheme_t *builtin = find_builtin_scheme(name);
413 if (builtin) {
414 memcpy(&scheme, builtin, sizeof(color_scheme_t));
415 } else if (strchr(name, '/') || strchr(name, '.')) {
416 /* Try loading as file path if it contains / or . */
417 result = colorscheme_load_from_file(name, &scheme);
418 if (result != ASCIICHAT_OK) {
419 return result;
420 }
421 } else {
422 return SET_ERRNO(ERROR_CONFIG, "Unknown color scheme: %s (not a built-in scheme or valid file path)", name);
423 }
424
425 mutex_lock(&g_colorscheme_mutex);
426 memcpy(&g_active_scheme, &scheme, sizeof(color_scheme_t));
427 atomic_fetch_add(&g_scheme_revision, 1);
428 mutex_unlock(&g_colorscheme_mutex);
429
430 log_dev("Switched to color scheme: %s", name);
431 return ASCIICHAT_OK;
432}
433
435 if (!name || !scheme) {
436 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL name or scheme pointer");
437 }
438
439 const color_scheme_t *builtin = find_builtin_scheme(name);
440 if (!builtin) {
441 return SET_ERRNO(ERROR_CONFIG, "Unknown built-in color scheme: %s", name);
442 }
443
444 memcpy(scheme, builtin, sizeof(color_scheme_t));
445 return ASCIICHAT_OK;
446}
447
449 if (!path || !scheme) {
450 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL path or scheme pointer");
451 }
452
453 /* Check if file exists and is readable */
454 struct stat sb;
455 if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode)) {
456 return SET_ERRNO(ERROR_FILE_NOT_FOUND, "Color scheme file not found or not readable: %s", path);
457 }
458
459 /* Parse TOML file */
460 toml_result_t result = toml_parse_file_ex(path);
461 if (!result.ok) {
462 toml_free(result);
463 return SET_ERRNO(ERROR_CONFIG, "Failed to parse color scheme file '%s': %s", path, result.errmsg);
464 }
465
466 /* Extract scheme information */
467 memset(scheme, 0, sizeof(color_scheme_t));
468
469 /* Get scheme section */
470 toml_datum_t scheme_section = toml_get(result.toptab, "scheme");
471 if (scheme_section.type == TOML_TABLE) {
472 /* Get scheme name */
473 toml_datum_t name_datum = toml_get(scheme_section, "name");
474 if (name_datum.type == TOML_STRING) {
475 SAFE_STRNCPY(scheme->name, name_datum.u.s, sizeof(scheme->name));
476 }
477
478 /* Get scheme description */
479 toml_datum_t desc_datum = toml_get(scheme_section, "description");
480 if (desc_datum.type == TOML_STRING) {
481 SAFE_STRNCPY(scheme->description, desc_datum.u.s, sizeof(scheme->description));
482 }
483 }
484
485 /* Get colors section */
486 toml_datum_t colors_section = toml_get(result.toptab, "colors");
487 if (colors_section.type == TOML_TABLE) {
488 /* Parse dark mode colors */
489 toml_datum_t dark_section = toml_get(colors_section, "dark");
490 if (dark_section.type == TOML_TABLE) {
491 const char *color_names[] = {"dev", "debug", "info", "warn", "error", "fatal", "grey", "reset"};
492 for (int i = 0; i < 8; i++) {
493 toml_datum_t color_value = toml_get(dark_section, color_names[i]);
494 if (color_value.type == TOML_STRING) {
495 parse_hex_color(color_value.u.s, &scheme->log_colors_dark[i].r, &scheme->log_colors_dark[i].g, &scheme->log_colors_dark[i].b);
496 }
497 }
498 }
499
500 /* Parse light mode colors (optional) */
501 toml_datum_t light_section = toml_get(colors_section, "light");
502 if (light_section.type == TOML_TABLE) {
503 scheme->has_light_variant = true;
504 const char *color_names[] = {"dev", "debug", "info", "warn", "error", "fatal", "grey", "reset"};
505 for (int i = 0; i < 8; i++) {
506 toml_datum_t color_value = toml_get(light_section, color_names[i]);
507 if (color_value.type == TOML_STRING) {
508 parse_hex_color(color_value.u.s, &scheme->log_colors_light[i].r, &scheme->log_colors_light[i].g, &scheme->log_colors_light[i].b);
509 }
510 }
511 }
512 }
513
514 scheme->is_builtin = false;
515 SAFE_STRNCPY(scheme->source_file, path, sizeof(scheme->source_file));
516
517 toml_free(result);
518 return ASCIICHAT_OK;
519}
520
521/* ============================================================================
522 * Public API: Color Conversion
523 * ============================================================================ */
524
526 if (!hex || !r || !g || !b) {
527 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
528 }
529
530 /* Skip '#' prefix if present */
531 if (hex[0] == '#') {
532 hex++;
533 }
534
535 /* Validate hex string length */
536 if (strlen(hex) != 6) {
537 return SET_ERRNO(ERROR_CONFIG, "Invalid hex color (must be #RRGGBB): %s", hex);
538 }
539
540 for (size_t i = 0; i < 6; ++i) {
541 if (!((hex[i] >= '0' && hex[i] <= '9') || (hex[i] >= 'a' && hex[i] <= 'f') || (hex[i] >= 'A' && hex[i] <= 'F'))) {
542 return SET_ERRNO(ERROR_CONFIG, "Invalid hex color format: %s", hex);
543 }
544 }
545
546 /* Parse hex digits */
547 unsigned int rgb = 0;
548 if (SAFE_SSCANF(hex, "%6x", &rgb) != 1) {
549 return SET_ERRNO(ERROR_CONFIG, "Invalid hex color format: %s", hex);
550 }
551
552 *r = (rgb >> 16) & 0xFF;
553 *g = (rgb >> 8) & 0xFF;
554 *b = rgb & 0xFF;
555
556 return ASCIICHAT_OK;
557}
558
559/* Note: rgb_to_16color() and rgb_to_256color() are already defined in lib/video/ansi_fast.c
560 * We use those definitions instead of duplicating them here.
561 * External declarations from ansi_fast.h are used above. */
562
563void rgb_to_truecolor_ansi(uint8_t r, uint8_t g, uint8_t b, char *buf, size_t size) {
564 if (!buf || size < 20)
565 return;
566 safe_snprintf(buf, size, "\x1b[38;2;%d;%d;%dm", r, g, b);
567}
568
569/* ============================================================================
570 * Public API: Scheme Compilation
571 * ============================================================================ */
572
573asciichat_error_t colorscheme_compile_scheme(const color_scheme_t *scheme, terminal_color_mode_t mode, terminal_background_t background, compiled_color_scheme_t *compiled) {
574 if (!scheme || !compiled) {
575 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL scheme or compiled pointer");
576 }
577
578 /* Note: mode parameter reserved for future use */
579 (void)mode;
580
581 /* Free any previously compiled strings before recompiling */
582 /* This prevents memory leaks when the color scheme is recompiled */
583 /* Only cleanup if we've actually compiled before (codes_16[0] != NULL means already compiled) */
584 if (compiled->codes_16[0] != NULL) {
586 } else {
587 }
588
589 /* Select color array based on background */
590 const rgb_pixel_t *colors = (background == TERM_BACKGROUND_LIGHT && scheme->has_light_variant) ? scheme->log_colors_light : scheme->log_colors_dark;
591 // Slot 7 stores the scheme's neutral RGB value, although log entries compile
592 // that slot as an ANSI reset. Notices need its actual foreground color.
593 rgb_pixel_t foreground = colors[7];
594 uint8_t foreground_index = rgb_to_16color(foreground.r, foreground.g, foreground.b);
595 safe_snprintf(compiled->foreground_16, sizeof(compiled->foreground_16), "\033[%dm", foreground_index < 8 ? 30 + foreground_index : 90 + foreground_index - 8);
596 safe_snprintf(compiled->foreground_256, sizeof(compiled->foreground_256), "\033[38;5;%dm", rgb_to_256color(foreground.r, foreground.g, foreground.b));
597 rgb_to_truecolor_ansi(foreground.r, foreground.g, foreground.b, compiled->foreground_truecolor, sizeof(compiled->foreground_truecolor));
598 /* Helper: allocate and format a color code string */
600
601 /* Compile for 16-color mode */
602 for (int i = 0; i < 8; i++) {
603 if (i == 7) {
604 /* RESET */
605 SAFE_STRNCPY(temp_buf, "\x1b[0m", sizeof(temp_buf));
606 } else {
607 uint8_t color_idx = rgb_to_16color(colors[i].r, colors[i].g, colors[i].b);
608 /* ANSI color codes: 30-37 for normal, 90-97 for bright */
609 if (color_idx < 8) {
610 safe_snprintf(temp_buf, sizeof(temp_buf), "\x1b[%dm", 30 + color_idx);
611 } else {
612 safe_snprintf(temp_buf, sizeof(temp_buf), "\x1b[%dm", 90 + (color_idx - 8));
613 }
614 }
615 /* Allocate string with SAFE_MALLOC and copy */
616 size_t len = strlen(temp_buf) + 1;
617 char *allocated = SAFE_MALLOC(len, char *);
618 if (!allocated) {
619 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate color code string");
620 }
621 memcpy(allocated, temp_buf, len);
622 compiled->codes_16[i] = allocated;
623 }
624 /* Compile for 256-color mode */
625 for (int i = 0; i < 8; i++) {
626 if (i == 7) {
627 SAFE_STRNCPY(temp_buf, "\x1b[0m", sizeof(temp_buf));
628 } else {
629 uint8_t color_idx = rgb_to_256color(colors[i].r, colors[i].g, colors[i].b);
630 safe_snprintf(temp_buf, sizeof(temp_buf), "\x1b[38;5;%dm", color_idx);
631 }
632 /* Allocate string with SAFE_MALLOC and copy */
633 size_t len = strlen(temp_buf) + 1;
634 char *allocated = SAFE_MALLOC(len, char *);
635 if (!allocated) {
636 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate color code string");
637 }
638 memcpy(allocated, temp_buf, len);
639 compiled->codes_256[i] = allocated;
640 }
641
642 /* Compile for truecolor mode */
643 for (int i = 0; i < 8; i++) {
644 if (i == 7) {
645 SAFE_STRNCPY(temp_buf, "\x1b[0m", sizeof(temp_buf));
646 } else {
647 rgb_to_truecolor_ansi(colors[i].r, colors[i].g, colors[i].b, temp_buf, sizeof(temp_buf));
648 }
649 /* Allocate string with SAFE_MALLOC and copy */
650 size_t len = strlen(temp_buf) + 1;
651 char *allocated = SAFE_MALLOC(len, char *);
652 if (!allocated) {
653 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate color code string");
654 }
655 memcpy(allocated, temp_buf, len);
656 compiled->codes_truecolor[i] = allocated;
657 }
658
659 return ASCIICHAT_OK;
660}
661
662/* ============================================================================
663 * Public API: Export
664 * ============================================================================ */
665
666asciichat_error_t colorscheme_export_scheme(const char *scheme_name, const char *file_path) {
667 if (!scheme_name) {
668 return SET_ERRNO(ERROR_INVALID_PARAM, "Scheme name is NULL");
669 }
670
671 color_scheme_t scheme = {0};
672 asciichat_error_t result = colorscheme_load_builtin(scheme_name, &scheme);
673 if (result != ASCIICHAT_OK) {
674 return result;
675 }
676
677 /* Generate TOML content */
678 char toml_content[OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE] = {0};
679 size_t offset = 0;
680
681 /* Scheme header section */
682 offset += safe_snprintf(toml_content + offset, sizeof(toml_content) - offset,
683 "[scheme]\n"
684 "name = \"%s\"\n"
685 "description = \"%s\"\n\n",
686 scheme.name, scheme.description);
687
688 /* Dark mode colors */
689 const char *color_names[] = {"dev", "debug", "info", "warn", "error", "fatal", "grey", "reset"};
690 offset += safe_snprintf(toml_content + offset, sizeof(toml_content) - offset, "[colors.dark]\n");
691
692 for (int i = 0; i < 8; i++) {
693 offset += safe_snprintf(toml_content + offset, sizeof(toml_content) - offset, "%s = \"#%02X%02X%02X\"\n", color_names[i], scheme.log_colors_dark[i].r, scheme.log_colors_dark[i].g,
694 scheme.log_colors_dark[i].b);
695 }
696
697 /* Light mode colors if available */
698 if (scheme.has_light_variant) {
699 offset += safe_snprintf(toml_content + offset, sizeof(toml_content) - offset, "\n[colors.light]\n");
700 for (int i = 0; i < 8; i++) {
701 offset += safe_snprintf(toml_content + offset, sizeof(toml_content) - offset, "%s = \"#%02X%02X%02X\"\n", color_names[i], scheme.log_colors_light[i].r, scheme.log_colors_light[i].g,
702 scheme.log_colors_light[i].b);
703 }
704 }
705
706 /* Write to file or stdout */
707 if (file_path) {
708 FILE *fp = platform_fopen("file_stream", file_path, "w");
709 if (!fp) {
710 return SET_ERRNO_SYS(ERROR_FILE_OPERATION, "Cannot open %s for writing", file_path);
711 }
712 defer(fclose(fp));
713 if (fputs(toml_content, fp) < 0) {
714 return SET_ERRNO_SYS(ERROR_FILE_OPERATION, "Failed to write to %s", file_path);
715 }
716 } else {
717 /* Write to stdout */
718 if (fputs(toml_content, stdout) < 0) {
719 return SET_ERRNO_SYS(ERROR_FILE_OPERATION, "Failed to write to stdout");
720 }
721 /* Flush to ensure piped output is written immediately */
722 (void)fflush(stdout);
723 }
724
725 return ASCIICHAT_OK;
726}
727
728/* ============================================================================
729 * Terminal Theme Detection
730 * ============================================================================ */
731
745 /* Method 1: Check environment variable override (highest priority) */
746 const char *term_bg = SAFE_GETENV("TERM_BACKGROUND");
747 if (term_bg) {
748 if (platform_strcasecmp(term_bg, "light") == 0) {
750 }
751 if (platform_strcasecmp(term_bg, "dark") == 0) {
753 }
754 }
755
756 /* Method 2: Use terminal_has_dark_background() for automatic theme detection
757 * This checks OSC 11 background color, environment variables, and terminal type */
758 bool is_dark = terminal_has_dark_background();
760}
761
762/* ============================================================================
763 * Early Color Scheme Loading (called from main() before log_init)
764 * ============================================================================ */
765
775static const char *find_cli_color_scheme(int argc, const char *const argv[]) {
776 for (int i = 1; i < argc - 1; i++) {
777 if (strcmp(argv[i], "--color-scheme") == 0) {
778 return argv[i + 1];
779 }
780 }
781 return NULL;
782}
783
799static asciichat_error_t load_config_color_scheme(color_scheme_t *scheme) {
800 if (!scheme) {
801 return SET_ERRNO(ERROR_INVALID_PARAM, "scheme pointer is NULL");
802 }
803
804 /* Use platform abstraction to find colors.toml across standard locations */
805 config_file_list_t config_files = {0};
806 asciichat_error_t search_result = platform_find_config_file("colors.toml", &config_files);
807
808 if (search_result != ASCIICHAT_OK) {
809 /* Platform search failed - non-fatal, will use built-in defaults */
810 return ERROR_NOT_FOUND;
811 }
812
813 /* Use first match (highest priority) - override semantics */
815 if (config_files.count > 0) {
816 load_result = colorscheme_load_from_file(config_files.files[0].path, scheme);
817 }
818
819 /* Clean up search results */
820 config_file_list_destroy(&config_files);
821
822 return load_result;
823}
824
839asciichat_error_t options_colorscheme_init_early(int argc, const char *const argv[]) {
840 /* Initialize the color system with defaults */
842 if (result != ASCIICHAT_OK) {
843 /* Non-fatal: use built-in defaults */
844 return ASCIICHAT_OK;
845 }
846
847 /* Step 1: Try to load from config file (~/.config/ascii-chat/colors.toml) */
848 color_scheme_t config_scheme = {0};
849 asciichat_error_t config_result = load_config_color_scheme(&config_scheme);
850 if (config_result == ASCIICHAT_OK) {
851 /* Config file loaded successfully, apply it */
852 colorscheme_set_active_scheme(config_scheme.name);
853 }
854
855 /* Step 2: CLI --color-scheme overrides config file */
856 const char *cli_scheme = find_cli_color_scheme(argc, argv);
857 if (cli_scheme) {
858 asciichat_error_t cli_result = colorscheme_set_active_scheme(cli_scheme);
859 if (cli_result != ASCIICHAT_OK) {
860 /* Invalid scheme name from CLI, continue with current scheme */
861 return cli_result;
862 }
863 }
864
865 return ASCIICHAT_OK;
866}
867
868/* A single query services all logging and UI threads. Never hold the scheme
869 * mutex during terminal I/O: the input path can itself produce log messages. */
870static atomic_flag g_background_query = ATOMIC_FLAG_INIT;
871static atomic_uint_fast64_t g_background_checked_us;
872static atomic_int g_live_background = TERM_BACKGROUND_DARK;
873static _Thread_local bool g_resolving_palette;
874
875static terminal_background_t current_background(void) {
876 const char *override = SAFE_GETENV("TERM_BACKGROUND");
877 if (override && platform_strcasecmp(override, "light") == 0)
879 if (override && platform_strcasecmp(override, "dark") == 0)
881#if !defined(__EMSCRIPTEN__)
882 bool keyboard = keyboard_is_initialized();
883 uint8_t r, g, b;
884 if (keyboard && keyboard_stream_background(&r, &g, &b))
885 atomic_store(&g_live_background, (0.2126 * r + 0.7152 * g + 0.0722 * b) < 127.5 ? TERM_BACKGROUND_DARK : TERM_BACKGROUND_LIGHT);
886#endif
887 if (!platform_isatty(STDERR_FILENO))
888 return (terminal_background_t)atomic_load(&g_live_background);
889 uint64_t now = platform_get_monotonic_time_us();
890 uint64_t checked = atomic_load(&g_background_checked_us);
891 if ((!checked || now - checked >= 250000) && !atomic_flag_test_and_set(&g_background_query)) {
892#if !defined(__EMSCRIPTEN__)
893 if (keyboard && ui_controller_current_screen() != UI_SCREEN_MEDIA) {
894 // Rendering and logging must never wait for an unsupported terminal.
895 // Its normal input pump decodes the reply and publishes the new RGB.
897 }
898#else
899 atomic_store(&g_live_background, detect_terminal_background());
900#endif
901 atomic_store(&g_background_checked_us, platform_get_monotonic_time_us());
902 atomic_flag_clear(&g_background_query);
903 }
904 return (terminal_background_t)atomic_load(&g_live_background);
905}
906
908 return current_background();
909}
910
911void colorscheme_current_palette(colorscheme_palette_t *palette, terminal_color_mode_t mode) {
912 if (!palette)
913 return;
914 if (g_resolving_palette)
915 return;
916 memset(palette, 0, sizeof(*palette));
917 g_resolving_palette = true;
918 palette->background = current_background();
919 static _Thread_local colorscheme_palette_t cached;
920 static _Thread_local terminal_color_mode_t cached_mode;
921 static _Thread_local uint64_t cached_revision;
922 uint64_t revision = atomic_load(&g_scheme_revision);
923 if (cached_revision == revision && cached_mode == mode && cached.background == palette->background) {
924 *palette = cached;
925 g_resolving_palette = false;
926 return;
927 }
930 memcpy(colors, palette->background == TERM_BACKGROUND_LIGHT && active->has_light_variant ? active->log_colors_light : active->log_colors_dark, sizeof(colors));
931 for (int i = 0; i < 9; ++i) {
932 char *code = i == 8 ? palette->foreground : palette->codes[i];
933 rgb_pixel_t rgb = colors[i == 8 ? 7 : i];
934 if (mode == TERM_COLOR_NONE)
935 continue;
936 if (i < 8) {
937 char *background = palette->background_codes[i];
938 if (i == 7)
939 safe_snprintf(background, COLORSCHEME_SGR_BUFFER_SIZE, "\033[49m");
940 else if (mode >= TERM_COLOR_TRUECOLOR)
941 safe_snprintf(background, COLORSCHEME_SGR_BUFFER_SIZE, "\033[48;2;%u;%u;%um", rgb.r, rgb.g, rgb.b);
942 else if (mode >= TERM_COLOR_256)
943 safe_snprintf(background, COLORSCHEME_SGR_BUFFER_SIZE, "\033[48;5;%dm", rgb_to_256color(rgb.r, rgb.g, rgb.b));
944 else {
945 unsigned index = rgb_to_16color(rgb.r, rgb.g, rgb.b);
946 safe_snprintf(background, COLORSCHEME_SGR_BUFFER_SIZE, "\033[%um", index < 8 ? 40 + index : 100 + index - 8);
947 }
948 }
949 if (i == 7)
950 safe_snprintf(code, COLORSCHEME_SGR_BUFFER_SIZE, "\033[0m");
951 else if (mode >= TERM_COLOR_TRUECOLOR)
952 rgb_to_truecolor_ansi(rgb.r, rgb.g, rgb.b, code, 32);
953 else if (mode >= TERM_COLOR_256)
954 safe_snprintf(code, COLORSCHEME_SGR_BUFFER_SIZE, "\033[38;5;%dm", rgb_to_256color(rgb.r, rgb.g, rgb.b));
955 else {
956 unsigned index = rgb_to_16color(rgb.r, rgb.g, rgb.b);
957 safe_snprintf(code, COLORSCHEME_SGR_BUFFER_SIZE, "\033[%um", index < 8 ? 30 + index : 90 + index - 8);
958 }
959 }
960 cached = *palette;
961 cached_mode = mode;
962 cached_revision = revision;
963 g_resolving_palette = false;
964}
965
967 if (!scheme)
968 return;
970 mutex_lock(&g_colorscheme_mutex);
971 memmove(&g_active_scheme, scheme, sizeof(g_active_scheme));
972 atomic_fetch_add(&g_scheme_revision, 1);
973 mutex_unlock(&g_colorscheme_mutex);
974}
975
978 uint8_t grey = dark ? 70 : 200;
979#if !defined(__EMSCRIPTEN__)
980 uint8_t r, g, b;
981 if (keyboard_is_initialized() && keyboard_stream_background(&r, &g, &b) && abs((int)((r + g + b) / 3) - grey) < 40)
982 grey = dark ? 0 : 255;
983#endif
984 return grey;
985}
ANSI escape sequence utilities and fast color code generation.
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
terminal_background_t colorscheme_current_background(void)
void colorscheme_apply(const color_scheme_t *scheme)
asciichat_error_t options_colorscheme_init_early(int argc, const char *const argv[])
Initialize color scheme early (before logging).
asciichat_error_t colorscheme_export_scheme(const char *scheme_name, const char *file_path)
Export a color scheme to TOML format.
asciichat_error_t colorscheme_init(void)
Initialize the color system.
asciichat_error_t parse_hex_color(const char *hex, uint8_t *r, uint8_t *g, uint8_t *b)
Parse a hex color string.
asciichat_error_t colorscheme_load_builtin(const char *name, color_scheme_t *scheme)
Load a built-in color scheme.
const color_scheme_t * colorscheme_get_active_scheme(void)
Get currently active color scheme.
void colorscheme_current_palette(colorscheme_palette_t *palette, terminal_color_mode_t mode)
#define OPTIONS_COLORSCHEME_TEMP_BUFFER_SIZE
Definition colorscheme.c:12
#define OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE
Definition colorscheme.c:13
terminal_background_t detect_terminal_background(void)
Detect the user's terminal theme (dark or light background).
asciichat_error_t colorscheme_load_from_file(const char *path, color_scheme_t *scheme)
Load a color scheme from a TOML file.
uint8_t colorscheme_highlight_background(void)
void colorscheme_destroy(void)
Shutdown the color system.
asciichat_error_t colorscheme_set_active_scheme(const char *name)
Set the active color scheme.
asciichat_error_t colorscheme_compile_scheme(const color_scheme_t *scheme, terminal_color_mode_t mode, terminal_background_t background, compiled_color_scheme_t *compiled)
Compile a color scheme to ANSI codes.
void rgb_to_truecolor_ansi(uint8_t r, uint8_t g, uint8_t b, char *buf, size_t size)
Generate truecolor ANSI escape code.
void colorscheme_cleanup_compiled(compiled_color_scheme_t *compiled)
Clean up allocated strings in a compiled color scheme.
#define NUM_BUILTIN_SCHEMES
mutex_t g_colorscheme_mutex
Shared mutex for color scheme compilation.
Definition colorscheme.c:50
terminal_background_t
Color scheme definition.
Definition colorscheme.h:64
@ TERM_BACKGROUND_DARK
Definition colorscheme.h:67
@ TERM_BACKGROUND_LIGHT
Definition colorscheme.h:66
#define COLORSCHEME_SGR_BUFFER_SIZE
Definition colorscheme.h:41
#define COLORSCHEME_LOG_COLOR_COUNT
Definition colorscheme.h:40
Named object registry for debugging — log identifiable resource names.
unsigned char colors[(512 *256 *2) *3]
Definition fft.c:23
int platform_find_config_file(const char *filename, config_file_list_t *list_out)
Definition filesystem.c:42
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
void config_file_list_destroy(config_file_list_t *list)
Definition filesystem.c:52
uint8_t rgb_to_16color(uint8_t r, uint8_t g, uint8_t b)
Definition ansi.c:353
uint8_t rgb_to_256color(uint8_t r, uint8_t g, uint8_t b)
Definition ansi.c:250
#define SAFE_SSCANF(str, format,...)
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER_MUTEX(mutex, name, parent_ptr)
Register a mutex with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_FILE_NOT_FOUND
@ ERROR_NOT_FOUND
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_FILE_OPERATION
@ ERROR_INVALID_PARAM
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
⚙️ Common definitions, error codes, macros, and types shared throughout the application
char file_path[PLATFORM_MAX_PATH_LENGTH]
Definition mmap.c:42
static bool size_t index
Definition queries.h:8
int platform_strcasecmp(const char *s1, const char *s2)
bool keyboard_request_background(void)
bool terminal_has_dark_background(void)
🔤 String Manipulation and Shell Escaping Utilities
Color scheme definition.
Definition colorscheme.h:76
rgb_pixel_t log_colors_light[8]
Definition colorscheme.h:85
char source_file[4096]
Definition colorscheme.h:89
char description[256]
Definition colorscheme.h:78
rgb_pixel_t log_colors_dark[8]
Definition colorscheme.h:81
char name[64]
Definition colorscheme.h:77
bool has_light_variant
Definition colorscheme.h:84
char background_codes[8][32]
terminal_background_t background
Compiled ANSI escape codes for a color scheme.
Definition colorscheme.h:99
const char * codes_16[8]
const char * codes_256[8]
const char * codes_truecolor[8]
uint8_t b
Blue color component (0-255).
uint8_t g
Green color component (0-255).
uint8_t r
Red color component (0-255).
int ui_controller_current_screen(void)
@ UI_SCREEN_MEDIA
int platform_isatty(int fd)
Definition util.c:70