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 File Reference

Color scheme management implementation and early initialization. More...

Go to the source code of this file.

Macros

#define OPTIONS_COLORSCHEME_TEMP_BUFFER_SIZE   128
#define OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE   8192
#define NUM_BUILTIN_SCHEMES   (sizeof(BUILTIN_SCHEMES) / sizeof(BUILTIN_SCHEMES[0]))

Functions

asciichat_error_t colorscheme_init (void)
 Initialize the color system.
void colorscheme_cleanup_compiled (compiled_color_scheme_t *compiled)
 Clean up allocated strings in a compiled color scheme.
void colorscheme_destroy (void)
 Shutdown the color system.
const color_scheme_t * colorscheme_get_active_scheme (void)
 Get currently active color scheme.
asciichat_error_t colorscheme_set_active_scheme (const char *name)
 Set the active color scheme.
asciichat_error_t colorscheme_load_builtin (const char *name, color_scheme_t *scheme)
 Load a built-in color scheme.
asciichat_error_t colorscheme_load_from_file (const char *path, color_scheme_t *scheme)
 Load a color scheme from a TOML file.
asciichat_error_t parse_hex_color (const char *hex, uint8_t *r, uint8_t *g, uint8_t *b)
 Parse a hex color string.
void rgb_to_truecolor_ansi (uint8_t r, uint8_t g, uint8_t b, char *buf, size_t size)
 Generate truecolor ANSI escape code.
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.
asciichat_error_t colorscheme_export_scheme (const char *scheme_name, const char *file_path)
 Export a color scheme to TOML format.
terminal_background_t detect_terminal_background (void)
 Detect the user's terminal theme (dark or light background).
asciichat_error_t options_colorscheme_init_early (int argc, const char *const argv[])
 Initialize color scheme early (before logging).
terminal_background_t colorscheme_current_background (void)
void colorscheme_current_palette (colorscheme_palette_t *palette, terminal_color_mode_t mode)
void colorscheme_apply (const color_scheme_t *scheme)
uint8_t colorscheme_highlight_background (void)

Variables

mutex_t g_colorscheme_mutex = {.impl = PTHREAD_MUTEX_INITIALIZER, .name = NULL}
 Shared mutex for color scheme compilation.

Detailed Description

Color scheme management implementation and early initialization.

Implements color scheme selection, loading, and compilation for ascii-chat. Supports built-in themes, TOML configuration files, and early initialization before logging starts.

Definition in file colorscheme.c.

Macro Definition Documentation

◆ NUM_BUILTIN_SCHEMES

#define NUM_BUILTIN_SCHEMES   (sizeof(BUILTIN_SCHEMES) / sizeof(BUILTIN_SCHEMES[0]))

Definition at line 257 of file colorscheme.c.

◆ OPTIONS_COLORSCHEME_TEMP_BUFFER_SIZE

#define OPTIONS_COLORSCHEME_TEMP_BUFFER_SIZE   128

Definition at line 12 of file colorscheme.c.

Referenced by colorscheme_compile_scheme().

◆ OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE

#define OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE   8192

Definition at line 13 of file colorscheme.c.

Referenced by colorscheme_export_scheme().

Function Documentation

◆ colorscheme_apply()

void colorscheme_apply ( const color_scheme_t * scheme)

Publish a complete scheme for all logging and UI consumers.

Definition at line 966 of file colorscheme.c.

966 {
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}
const color_scheme_t * colorscheme_get_active_scheme(void)
Get currently active color scheme.
mutex_t g_colorscheme_mutex
Shared mutex for color scheme compilation.
Definition colorscheme.c:50

References colorscheme_get_active_scheme(), and g_colorscheme_mutex.

Referenced by log_set_color_scheme().

◆ colorscheme_cleanup_compiled()

void colorscheme_cleanup_compiled ( compiled_color_scheme_t * compiled)

Clean up allocated strings in a compiled color scheme.

Parameters
compiledCompiled color scheme to clean (NULL-safe)

Frees all allocated color code strings and zeros the structure.

Definition at line 330 of file colorscheme.c.

330 {
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}
#define SAFE_FREE(ptr)
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]

References compiled_color_scheme_t::codes_16, compiled_color_scheme_t::codes_256, compiled_color_scheme_t::codes_truecolor, and SAFE_FREE.

Referenced by colorscheme_compile_scheme().

◆ colorscheme_compile_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.

Parameters
schemeSource scheme (must not be NULL)
modeTerminal color mode (16, 256, or truecolor)
backgroundTerminal background (light or dark)
compiledOutput compiled codes (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Compiles RGB colors to ANSI escape codes for the specified terminal mode and background. Applies background-appropriate color variant (light/dark).

Definition at line 573 of file colorscheme.c.

573 {
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}
#define SET_ERRNO(code,...)
#define OPTIONS_COLORSCHEME_TEMP_BUFFER_SIZE
Definition colorscheme.c:12
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.
@ TERM_BACKGROUND_LIGHT
Definition colorscheme.h:66
unsigned char colors[(512 *256 *2) *3]
Definition fft.c:23
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_STRNCPY(dst, src, size)
#define SAFE_MALLOC(size, cast)
unsigned char uint8_t
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
rgb_pixel_t log_colors_light[8]
Definition colorscheme.h:85
bool has_light_variant
Definition colorscheme.h:84
uint8_t b
Blue color component (0-255).
uint8_t g
Green color component (0-255).
uint8_t r
Red color component (0-255).

References ASCIICHAT_OK, rgb_pixel_t::b, compiled_color_scheme_t::codes_16, compiled_color_scheme_t::codes_256, compiled_color_scheme_t::codes_truecolor, colors, colorscheme_cleanup_compiled(), ERROR_INVALID_PARAM, ERROR_MEMORY, compiled_color_scheme_t::foreground_16, compiled_color_scheme_t::foreground_256, compiled_color_scheme_t::foreground_truecolor, rgb_pixel_t::g, color_scheme_t::has_light_variant, color_scheme_t::log_colors_dark, color_scheme_t::log_colors_light, OPTIONS_COLORSCHEME_TEMP_BUFFER_SIZE, rgb_pixel_t::r, rgb_to_16color(), rgb_to_256color(), rgb_to_truecolor_ansi(), SAFE_MALLOC, SAFE_STRNCPY, SET_ERRNO, and TERM_BACKGROUND_LIGHT.

◆ colorscheme_current_background()

terminal_background_t colorscheme_current_background ( void )

Definition at line 907 of file colorscheme.c.

907 {
908 return current_background();
909}

Referenced by colorscheme_highlight_background(), and render_file_create().

◆ colorscheme_current_palette()

void colorscheme_current_palette ( colorscheme_palette_t * palette,
terminal_color_mode_t mode )

Resolve the active scheme and current terminal theme/depth. Queries are asynchronous and coalesced across threads for 250ms. The returned palette uses the latest decoded reply and never waits for input. Terminal replies and ordinary keyboard input share the keyboard decoder.

Definition at line 911 of file colorscheme.c.

911 {
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}
#define COLORSCHEME_SGR_BUFFER_SIZE
Definition colorscheme.h:41
#define COLORSCHEME_LOG_COLOR_COUNT
Definition colorscheme.h:40
unsigned long long uint64_t
static bool size_t index
Definition queries.h:8
Color scheme definition.
Definition colorscheme.h:76
rgb_pixel_t log_colors_dark[8]
Definition colorscheme.h:81
char background_codes[8][32]
terminal_background_t background

References rgb_pixel_t::b, colorscheme_palette_t::background, colorscheme_palette_t::background_codes, colorscheme_palette_t::codes, colors, colorscheme_get_active_scheme(), COLORSCHEME_LOG_COLOR_COUNT, COLORSCHEME_SGR_BUFFER_SIZE, colorscheme_palette_t::foreground, rgb_pixel_t::g, color_scheme_t::has_light_variant, index, color_scheme_t::log_colors_dark, color_scheme_t::log_colors_light, rgb_pixel_t::r, rgb_to_16color(), rgb_to_256color(), rgb_to_truecolor_ansi(), and TERM_BACKGROUND_LIGHT.

Referenced by log_get_color_array(), log_level_color_for_output(), and ui_buttons_render().

◆ colorscheme_destroy()

void colorscheme_destroy ( void )

Shutdown the color system.

Frees all allocated resources. Call at program shutdown.

Definition at line 354 of file colorscheme.c.

354 {
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}

References g_colorscheme_mutex.

Referenced by asciichat_shared_destroy().

◆ colorscheme_export_scheme()

asciichat_error_t colorscheme_export_scheme ( const char * scheme_name,
const char * file_path )

Export a color scheme to TOML format.

Parameters
scheme_nameName of scheme to export
file_pathOutput file path (NULL = stdout)
Returns
ASCIICHAT_OK on success, error code on failure

Exports a color scheme to TOML format. If file_path is NULL, writes to stdout.

Definition at line 666 of file colorscheme.c.

666 {
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}
#define SET_ERRNO_SYS(code,...)
asciichat_error_t colorscheme_load_builtin(const char *name, color_scheme_t *scheme)
Load a built-in color scheme.
#define OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE
Definition colorscheme.c:13
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_FILE_OPERATION
char file_path[PLATFORM_MAX_PATH_LENGTH]
Definition mmap.c:42
char description[256]
Definition colorscheme.h:78
char name[64]
Definition colorscheme.h:77

References ASCIICHAT_OK, rgb_pixel_t::b, colorscheme_load_builtin(), color_scheme_t::description, ERROR_FILE_OPERATION, ERROR_INVALID_PARAM, file_path, rgb_pixel_t::g, color_scheme_t::has_light_variant, color_scheme_t::log_colors_dark, color_scheme_t::log_colors_light, color_scheme_t::name, OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE, platform_fopen(), rgb_pixel_t::r, SET_ERRNO, and SET_ERRNO_SYS.

◆ colorscheme_get_active_scheme()

const color_scheme_t * colorscheme_get_active_scheme ( void )

Get currently active color scheme.

Returns
Pointer to active color scheme (must not be freed)

Returns the currently active color scheme. Default is "pastel" if not set.

Definition at line 381 of file colorscheme.c.

381 {
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}
asciichat_error_t colorscheme_init(void)
Initialize the color system.

References colorscheme_init(), and g_colorscheme_mutex.

Referenced by colorscheme_apply(), colorscheme_current_palette(), and log_init_colors().

◆ colorscheme_highlight_background()

uint8_t colorscheme_highlight_background ( void )

Theme-adaptive neutral search highlight, with contrast against the last RGB reply.

Definition at line 976 of file colorscheme.c.

976 {
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}
terminal_background_t colorscheme_current_background(void)
@ TERM_BACKGROUND_DARK
Definition colorscheme.h:67

References colorscheme_current_background(), and TERM_BACKGROUND_DARK.

Referenced by ui_buttons_render().

◆ colorscheme_init()

asciichat_error_t colorscheme_init ( void )

Initialize the color system.

Returns
ASCIICHAT_OK on success, error code on failure

Must be called once at program startup before using any color functions.

Definition at line 288 of file colorscheme.c.

288 {
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}
#define NAMED_REGISTER_MUTEX(mutex, name, parent_ptr)
Register a mutex with automatic format specifier.
@ ERROR_CONFIG
Definition error_codes.h:56

References ASCIICHAT_OK, ERROR_CONFIG, g_colorscheme_mutex, NAMED_REGISTER_MUTEX, and SET_ERRNO.

Referenced by colorscheme_get_active_scheme(), colorscheme_set_active_scheme(), and options_colorscheme_init_early().

◆ colorscheme_load_builtin()

asciichat_error_t colorscheme_load_builtin ( const char * name,
color_scheme_t * scheme )

Load a built-in color scheme.

Parameters
nameScheme name
schemePointer to store loaded scheme
Returns
ASCIICHAT_OK on success, error code if not found

Loads a built-in color scheme by name. "default" is aliased to "pastel".

Definition at line 434 of file colorscheme.c.

434 {
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}

References ASCIICHAT_OK, ERROR_CONFIG, ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by colorscheme_export_scheme(), and main().

◆ colorscheme_load_from_file()

asciichat_error_t colorscheme_load_from_file ( const char * path,
color_scheme_t * scheme )

Load a color scheme from a TOML file.

Parameters
pathPath to TOML file
schemePointer to store loaded scheme
Returns
ASCIICHAT_OK on success, error code on failure

Loads a color scheme from a TOML configuration file. See docs/colors.toml for format specification.

Definition at line 448 of file colorscheme.c.

448 {
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}
asciichat_error_t parse_hex_color(const char *hex, uint8_t *r, uint8_t *g, uint8_t *b)
Parse a hex color string.
@ ERROR_FILE_NOT_FOUND
char source_file[4096]
Definition colorscheme.h:89

References ASCIICHAT_OK, rgb_pixel_t::b, color_scheme_t::description, ERROR_CONFIG, ERROR_FILE_NOT_FOUND, ERROR_INVALID_PARAM, rgb_pixel_t::g, color_scheme_t::has_light_variant, color_scheme_t::is_builtin, color_scheme_t::log_colors_dark, color_scheme_t::log_colors_light, color_scheme_t::name, parse_hex_color(), rgb_pixel_t::r, SAFE_STRNCPY, SET_ERRNO, and color_scheme_t::source_file.

Referenced by colorscheme_set_active_scheme().

◆ colorscheme_set_active_scheme()

asciichat_error_t colorscheme_set_active_scheme ( const char * name)

Set the active color scheme.

Parameters
nameScheme name (e.g., "pastel", "nord", "solarized-dark")
Returns
ASCIICHAT_OK on success, error code if scheme not found

Changes the active color scheme. Scheme must be either built-in or previously loaded from a TOML file.

Definition at line 398 of file colorscheme.c.

398 {
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}
asciichat_error_t colorscheme_load_from_file(const char *path, color_scheme_t *scheme)
Load a color scheme from a TOML file.
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575

References ASCIICHAT_OK, colorscheme_init(), colorscheme_load_from_file(), ERROR_CONFIG, ERROR_INVALID_PARAM, g_colorscheme_mutex, log_dev, and SET_ERRNO.

Referenced by options_colorscheme_init_early().

◆ detect_terminal_background()

terminal_background_t detect_terminal_background ( void )

Detect the user's terminal theme (dark or light background).

Detect terminal background (light or dark).

Determines the terminal's color background theme to adapt color schemes accordingly. The detection uses a priority-based approach:

  1. Environment variable override (TERM_BACKGROUND="light" or "dark")
  2. Automatic detection via terminal_has_dark_background():
    • OSC 11 escape query with luminance calculation (modern terminals)
    • Environment variables and terminal type hints (fallback)
Returns
The detected theme: TERM_BACKGROUND_LIGHT or TERM_BACKGROUND_DARK

Definition at line 744 of file colorscheme.c.

744 {
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}
#define SAFE_GETENV(name)
int platform_strcasecmp(const char *s1, const char *s2)
bool terminal_has_dark_background(void)

References platform_strcasecmp(), SAFE_GETENV, TERM_BACKGROUND_DARK, TERM_BACKGROUND_LIGHT, and terminal_has_dark_background().

◆ options_colorscheme_init_early()

asciichat_error_t options_colorscheme_init_early ( int argc,
const char *const argv[] )

Initialize color scheme early (before logging).

Initialize color scheme early, before logging.

Parameters
argcArgument count
argvArgument array
Returns
ASCIICHAT_OK on success, error code on failure (non-fatal)

This function is called from main() BEFORE log_init() to apply color scheme to logging before any log messages are printed.

Priority order:

  1. –color-scheme CLI argument (highest priority)
  2. ~/.config/ascii-chat/colors.toml config file
  3. Built-in "pastel" default scheme (lowest priority)

Definition at line 839 of file colorscheme.c.

839 {
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}
asciichat_error_t colorscheme_set_active_scheme(const char *name)
Set the active color scheme.

References ASCIICHAT_OK, colorscheme_init(), colorscheme_set_active_scheme(), and color_scheme_t::name.

Referenced by main().

◆ parse_hex_color()

asciichat_error_t parse_hex_color ( const char * hex,
uint8_t * r,
uint8_t * g,
uint8_t * b )

Parse a hex color string.

Parameters
hexHex color string (e.g., "#FF0000" or "FF0000")
rPointer to store red channel
gPointer to store green channel
bPointer to store blue channel
Returns
ASCIICHAT_OK on success, error code on failure

Parses hex color strings in #RRGGBB or RRGGBB format.

Definition at line 525 of file colorscheme.c.

525 {
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}
#define SAFE_SSCANF(str, format,...)

References ASCIICHAT_OK, ERROR_CONFIG, ERROR_INVALID_PARAM, SAFE_SSCANF, and SET_ERRNO.

Referenced by colorscheme_load_from_file().

◆ rgb_to_truecolor_ansi()

void rgb_to_truecolor_ansi ( uint8_t r,
uint8_t g,
uint8_t b,
char * buf,
size_t size )

Generate truecolor ANSI escape code.

Parameters
rRed channel (0-255)
gGreen channel (0-255)
bBlue channel (0-255)
bufOutput buffer for escape code
sizeBuffer size (minimum 20 bytes)

Generates ANSI truecolor escape code: \x1b[38;2;R;G;Bm

Definition at line 563 of file colorscheme.c.

563 {
564 if (!buf || size < 20)
565 return;
566 safe_snprintf(buf, size, "\x1b[38;2;%d;%d;%dm", r, g, b);
567}

Referenced by colorscheme_compile_scheme(), and colorscheme_current_palette().

Variable Documentation

◆ g_colorscheme_mutex

mutex_t g_colorscheme_mutex = {.impl = PTHREAD_MUTEX_INITIALIZER, .name = NULL}

Shared mutex for color scheme compilation.

Used by lib/options/colorscheme.c and lib/log/logging.c to synchronize color scheme compilation. Defined in colorscheme.c and declared here for use by logging.c.

Definition at line 50 of file colorscheme.c.

50{.impl = PTHREAD_MUTEX_INITIALIZER, .name = NULL}; /* POSIX pthread_mutex_t */

Referenced by colorscheme_apply(), colorscheme_destroy(), colorscheme_get_active_scheme(), colorscheme_init(), and colorscheme_set_active_scheme().