ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
colorscheme.h File Reference

Go to the source code of this file.

Data Structures

struct  color_scheme_t
 Color scheme definition. More...
struct  compiled_color_scheme_t
 Compiled ANSI escape codes for a color scheme. More...
struct  colorscheme_palette_t

Macros

#define OPTIONS_COLORSCHEME_NAME_BUFFER_SIZE   64
#define OPTIONS_COLORSCHEME_DESCRIPTION_BUFFER_SIZE   256
#define OPTIONS_COLORSCHEME_FOREGROUND_16_BUFFER_SIZE   16
#define OPTIONS_COLORSCHEME_FOREGROUND_256_BUFFER_SIZE   24
#define OPTIONS_COLORSCHEME_FOREGROUND_TRUECOLOR_BUFFER_SIZE   32
#define COLORSCHEME_LOG_COLOR_COUNT   8
#define COLORSCHEME_SGR_BUFFER_SIZE   32

Typedefs

typedef struct color_scheme_t color_scheme_t
 Color scheme definition.

Enumerations

enum  terminal_background_t { TERM_BACKGROUND_UNKNOWN , TERM_BACKGROUND_LIGHT , TERM_BACKGROUND_DARK }
 Color scheme definition. More...

Functions

void colorscheme_current_palette (colorscheme_palette_t *palette, terminal_color_mode_t mode)
terminal_background_t colorscheme_current_background (void)
uint8_t colorscheme_highlight_background (void)
void colorscheme_apply (const color_scheme_t *scheme)
asciichat_error_t colorscheme_init (void)
 Initialize the color system.
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 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 colorscheme_cleanup_compiled (compiled_color_scheme_t *compiled)
 Clean up allocated strings in a compiled color scheme.
asciichat_error_t colorscheme_export_scheme (const char *scheme_name, const char *file_path)
 Export a color scheme to TOML format.
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.
terminal_background_t detect_terminal_background (void)
 Detect terminal background (light or dark).
asciichat_error_t options_colorscheme_init_early (int argc, const char *const argv[])
 Initialize color scheme early, before logging.

Variables

mutex_t g_colorscheme_mutex
 Shared mutex for color scheme compilation.

Macro Definition Documentation

◆ COLORSCHEME_LOG_COLOR_COUNT

#define COLORSCHEME_LOG_COLOR_COUNT   8

Definition at line 41 of file colorscheme.h.

Referenced by colorscheme_current_palette().

◆ COLORSCHEME_SGR_BUFFER_SIZE

#define COLORSCHEME_SGR_BUFFER_SIZE   32

Definition at line 42 of file colorscheme.h.

Referenced by colorscheme_current_palette().

◆ OPTIONS_COLORSCHEME_DESCRIPTION_BUFFER_SIZE

#define OPTIONS_COLORSCHEME_DESCRIPTION_BUFFER_SIZE   256

Definition at line 35 of file colorscheme.h.

◆ OPTIONS_COLORSCHEME_FOREGROUND_16_BUFFER_SIZE

#define OPTIONS_COLORSCHEME_FOREGROUND_16_BUFFER_SIZE   16

Definition at line 36 of file colorscheme.h.

◆ OPTIONS_COLORSCHEME_FOREGROUND_256_BUFFER_SIZE

#define OPTIONS_COLORSCHEME_FOREGROUND_256_BUFFER_SIZE   24

Definition at line 37 of file colorscheme.h.

◆ OPTIONS_COLORSCHEME_FOREGROUND_TRUECOLOR_BUFFER_SIZE

#define OPTIONS_COLORSCHEME_FOREGROUND_TRUECOLOR_BUFFER_SIZE   32

Definition at line 38 of file colorscheme.h.

◆ OPTIONS_COLORSCHEME_NAME_BUFFER_SIZE

#define OPTIONS_COLORSCHEME_NAME_BUFFER_SIZE   64

Definition at line 34 of file colorscheme.h.

Typedef Documentation

◆ color_scheme_t

typedef struct color_scheme_t color_scheme_t

Color scheme definition.

Defines a color scheme with RGB colors for logging levels. Supports both dark and light mode variants.

Enumeration Type Documentation

◆ terminal_background_t

Color scheme definition.

Compiled ANSI escape codes for a color scheme

Terminal theme detection result

Represents the detected or selected terminal theme (color background preference). Used to choose appropriate color schemes and contrast levels.

Enumerator
TERM_BACKGROUND_UNKNOWN 

Theme not detected or auto-detect disabled

TERM_BACKGROUND_LIGHT 

Light theme: light/white background, use dark text colors

TERM_BACKGROUND_DARK 

Dark theme: dark/black background, use light text colors

Definition at line 66 of file colorscheme.h.

66 {
68 0,
70 1,
72 2
terminal_background_t
Color scheme definition.
Definition colorscheme.h:66
@ TERM_BACKGROUND_DARK
Definition colorscheme.h:71
@ TERM_BACKGROUND_UNKNOWN
Definition colorscheme.h:67
@ TERM_BACKGROUND_LIGHT
Definition colorscheme.h:69

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 1066 of file colorscheme.c.

1066 {
1067 if (!scheme)
1068 return;
1070 mutex_lock(&g_colorscheme_mutex);
1071 memmove(&g_active_scheme, scheme, sizeof(g_active_scheme));
1072 atomic_fetch_add(&g_scheme_revision, 1);
1073 mutex_unlock(&g_colorscheme_mutex);
1074}
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:56

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 354 of file colorscheme.c.

354 {
355 if (!compiled) {
356 return;
357 }
358
359 /* Free allocated color code strings */
360 for (int i = 0; i < 8; i++) {
361 char *str_16 = (char *)compiled->codes_16[i];
362 char *str_256 = (char *)compiled->codes_256[i];
363 char *str_truecolor = (char *)compiled->codes_truecolor[i];
364 /* Only free non-NULL pointers - protects against uninitialized data */
365 if (str_16 != NULL) {
366 SAFE_FREE(str_16);
367 }
368 if (str_256 != NULL) {
369 SAFE_FREE(str_256);
370 }
371 if (str_truecolor != NULL) {
372 SAFE_FREE(str_truecolor);
373 }
374 }
375 memset(compiled, 0, sizeof(compiled_color_scheme_t));
376}
#define SAFE_FREE(ptr)
Compiled ANSI escape codes for a color scheme.
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 620 of file colorscheme.c.

622 {
623 if (!scheme || !compiled) {
624 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL scheme or compiled pointer");
625 }
626
627 /* Note: mode parameter reserved for future use */
628 (void)mode;
629
630 /* Free any previously compiled strings before recompiling */
631 /* This prevents memory leaks when the color scheme is recompiled */
632 /* Only cleanup if we've actually compiled before (codes_16[0] != NULL means
633 * already compiled) */
634 if (compiled->codes_16[0] != NULL) {
636 } else {
637 }
638
639 /* Select color array based on background */
640 const rgb_pixel_t *colors =
641 (background == TERM_BACKGROUND_LIGHT && scheme->has_light_variant)
642 ? scheme->log_colors_light
643 : scheme->log_colors_dark;
644 // Slot 7 stores the scheme's neutral RGB value, although log entries compile
645 // that slot as an ANSI reset. Notices need its actual foreground color.
646 rgb_pixel_t foreground = colors[7];
647 uint8_t foreground_index =
648 rgb_to_16color(foreground.r, foreground.g, foreground.b);
649 safe_snprintf(
650 compiled->foreground_16, sizeof(compiled->foreground_16), "\033[%dm",
651 foreground_index < 8 ? 30 + foreground_index : 90 + foreground_index - 8);
652 safe_snprintf(compiled->foreground_256, sizeof(compiled->foreground_256),
653 "\033[38;5;%dm",
654 rgb_to_256color(foreground.r, foreground.g, foreground.b));
655 rgb_to_truecolor_ansi(foreground.r, foreground.g, foreground.b,
656 compiled->foreground_truecolor,
657 sizeof(compiled->foreground_truecolor));
658 /* Helper: allocate and format a color code string */
660
661 /* Compile for 16-color mode */
662 for (int i = 0; i < 8; i++) {
663 if (i == 7) {
664 /* RESET */
665 SAFE_STRNCPY(temp_buf, "\x1b[0m", sizeof(temp_buf));
666 } else {
667 uint8_t color_idx = rgb_to_16color(colors[i].r, colors[i].g, colors[i].b);
668 /* ANSI color codes: 30-37 for normal, 90-97 for bright */
669 if (color_idx < 8) {
670 safe_snprintf(temp_buf, sizeof(temp_buf), "\x1b[%dm", 30 + color_idx);
671 } else {
672 safe_snprintf(temp_buf, sizeof(temp_buf), "\x1b[%dm",
673 90 + (color_idx - 8));
674 }
675 }
676 /* Allocate string with SAFE_MALLOC and copy */
677 size_t len = strlen(temp_buf) + 1;
678 char *allocated = SAFE_MALLOC(len, char *);
679 if (!allocated) {
680 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate color code string");
681 }
682 memcpy(allocated, temp_buf, len);
683 compiled->codes_16[i] = allocated;
684 }
685 /* Compile for 256-color mode */
686 for (int i = 0; i < 8; i++) {
687 if (i == 7) {
688 SAFE_STRNCPY(temp_buf, "\x1b[0m", sizeof(temp_buf));
689 } else {
690 uint8_t color_idx =
691 rgb_to_256color(colors[i].r, colors[i].g, colors[i].b);
692 safe_snprintf(temp_buf, sizeof(temp_buf), "\x1b[38;5;%dm", color_idx);
693 }
694 /* Allocate string with SAFE_MALLOC and copy */
695 size_t len = strlen(temp_buf) + 1;
696 char *allocated = SAFE_MALLOC(len, char *);
697 if (!allocated) {
698 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate color code string");
699 }
700 memcpy(allocated, temp_buf, len);
701 compiled->codes_256[i] = allocated;
702 }
703
704 /* Compile for truecolor mode */
705 for (int i = 0; i < 8; i++) {
706 if (i == 7) {
707 SAFE_STRNCPY(temp_buf, "\x1b[0m", sizeof(temp_buf));
708 } else {
709 rgb_to_truecolor_ansi(colors[i].r, colors[i].g, colors[i].b, temp_buf,
710 sizeof(temp_buf));
711 }
712 /* Allocate string with SAFE_MALLOC and copy */
713 size_t len = strlen(temp_buf) + 1;
714 char *allocated = SAFE_MALLOC(len, char *);
715 if (!allocated) {
716 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate color code string");
717 }
718 memcpy(allocated, temp_buf, len);
719 compiled->codes_truecolor[i] = allocated;
720 }
721
722 return ASCIICHAT_OK;
723}
#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.
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:93
bool has_light_variant
Definition colorscheme.h:92
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 995 of file colorscheme.c.

995 {
996 return current_background();
997}

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 999 of file colorscheme.c.

1000 {
1001 if (!palette)
1002 return;
1003 if (g_resolving_palette)
1004 return;
1005 memset(palette, 0, sizeof(*palette));
1006 g_resolving_palette = true;
1007 palette->background = current_background();
1008 static _Thread_local colorscheme_palette_t cached;
1009 static _Thread_local terminal_color_mode_t cached_mode;
1010 static _Thread_local uint64_t cached_revision;
1011 uint64_t revision = atomic_load(&g_scheme_revision);
1012 if (cached_revision == revision && cached_mode == mode &&
1013 cached.background == palette->background) {
1014 *palette = cached;
1015 g_resolving_palette = false;
1016 return;
1017 }
1020 memcpy(colors,
1021 palette->background == TERM_BACKGROUND_LIGHT &&
1022 active->has_light_variant
1023 ? active->log_colors_light
1024 : active->log_colors_dark,
1025 sizeof(colors));
1026 for (int i = 0; i < 9; ++i) {
1027 char *code = i == 8 ? palette->foreground : palette->codes[i];
1028 rgb_pixel_t rgb = colors[i == 8 ? 7 : i];
1029 if (mode == TERM_COLOR_NONE)
1030 continue;
1031 if (i < 8) {
1032 char *background = palette->background_codes[i];
1033 if (i == 7)
1034 safe_snprintf(background, COLORSCHEME_SGR_BUFFER_SIZE, "\033[49m");
1035 else if (mode >= TERM_COLOR_TRUECOLOR)
1036 safe_snprintf(background, COLORSCHEME_SGR_BUFFER_SIZE,
1037 "\033[48;2;%u;%u;%um", rgb.r, rgb.g, rgb.b);
1038 else if (mode >= TERM_COLOR_256)
1039 safe_snprintf(background, COLORSCHEME_SGR_BUFFER_SIZE, "\033[48;5;%dm",
1040 rgb_to_256color(rgb.r, rgb.g, rgb.b));
1041 else {
1042 unsigned index = rgb_to_16color(rgb.r, rgb.g, rgb.b);
1043 safe_snprintf(background, COLORSCHEME_SGR_BUFFER_SIZE, "\033[%um",
1044 index < 8 ? 40 + index : 100 + index - 8);
1045 }
1046 }
1047 if (i == 7)
1048 safe_snprintf(code, COLORSCHEME_SGR_BUFFER_SIZE, "\033[0m");
1049 else if (mode >= TERM_COLOR_TRUECOLOR)
1050 rgb_to_truecolor_ansi(rgb.r, rgb.g, rgb.b, code, 32);
1051 else if (mode >= TERM_COLOR_256)
1052 safe_snprintf(code, COLORSCHEME_SGR_BUFFER_SIZE, "\033[38;5;%dm",
1053 rgb_to_256color(rgb.r, rgb.g, rgb.b));
1054 else {
1055 unsigned index = rgb_to_16color(rgb.r, rgb.g, rgb.b);
1056 safe_snprintf(code, COLORSCHEME_SGR_BUFFER_SIZE, "\033[%um",
1057 index < 8 ? 30 + index : 90 + index - 8);
1058 }
1059 }
1060 cached = *palette;
1061 cached_mode = mode;
1062 cached_revision = revision;
1063 g_resolving_palette = false;
1064}
#define COLORSCHEME_SGR_BUFFER_SIZE
Definition colorscheme.h:42
#define COLORSCHEME_LOG_COLOR_COUNT
Definition colorscheme.h:41
unsigned long long uint64_t
static bool size_t index
Definition queries.h:10
Color scheme definition.
Definition colorscheme.h:81
rgb_pixel_t log_colors_dark[8]
Definition colorscheme.h:88
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 378 of file colorscheme.c.

378 {
379 if (!lifecycle_is_initialized(&g_colorscheme_lifecycle)) {
380 return;
381 }
382
383 mutex_lock(&g_colorscheme_mutex);
384 memset(&g_active_scheme, 0, sizeof(color_scheme_t));
385 atomic_fetch_add(&g_scheme_revision, 1);
386
387 /* Mark as uninitialized */
388 lifecycle_shutdown(&g_colorscheme_lifecycle);
389
390 mutex_unlock(&g_colorscheme_mutex);
391
392 /* NOTE: Do NOT call mutex_destroy() on native POSIX because the mutex is
393 * statically initialized with PTHREAD_MUTEX_INITIALIZER. Destroying a
394 * statically-initialized mutex is undefined behavior. On Windows and
395 * Emscripten, we must destroy the mutex because it was explicitly initialized
396 * in colorscheme_init(). */
397#if defined(_WIN32) || defined(__EMSCRIPTEN__)
398 mutex_destroy(&g_colorscheme_mutex);
399#endif
400}

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 730 of file colorscheme.c.

731 {
732 if (!scheme_name) {
733 return SET_ERRNO(ERROR_INVALID_PARAM, "Scheme name is NULL");
734 }
735
736 color_scheme_t scheme = {0};
737 asciichat_error_t result = colorscheme_load_builtin(scheme_name, &scheme);
738 if (result != ASCIICHAT_OK) {
739 return result;
740 }
741
742 /* Generate TOML content */
743 char toml_content[OPTIONS_COLORSCHEME_TOML_CONTENT_BUFFER_SIZE] = {0};
744 size_t offset = 0;
745
746 /* Scheme header section */
747 offset += safe_snprintf(toml_content + offset, sizeof(toml_content) - offset,
748 "[scheme]\n"
749 "name = \"%s\"\n"
750 "description = \"%s\"\n\n",
751 scheme.name, scheme.description);
752
753 /* Dark mode colors */
754 const char *color_names[] = {"dev", "debug", "info", "warn",
755 "error", "fatal", "grey", "reset"};
756 offset += safe_snprintf(toml_content + offset, sizeof(toml_content) - offset,
757 "[colors.dark]\n");
758
759 for (int i = 0; i < 8; i++) {
760 offset += safe_snprintf(
761 toml_content + offset, sizeof(toml_content) - offset,
762 "%s = \"#%02X%02X%02X\"\n", color_names[i], scheme.log_colors_dark[i].r,
763 scheme.log_colors_dark[i].g, scheme.log_colors_dark[i].b);
764 }
765
766 /* Light mode colors if available */
767 if (scheme.has_light_variant) {
768 offset +=
769 safe_snprintf(toml_content + offset, sizeof(toml_content) - offset,
770 "\n[colors.light]\n");
771 for (int i = 0; i < 8; i++) {
772 offset += safe_snprintf(
773 toml_content + offset, sizeof(toml_content) - offset,
774 "%s = \"#%02X%02X%02X\"\n", color_names[i],
775 scheme.log_colors_light[i].r, scheme.log_colors_light[i].g,
776 scheme.log_colors_light[i].b);
777 }
778 }
779
780 /* Write to file or stdout */
781 if (file_path) {
782 FILE *fp = platform_fopen("file_stream", file_path, "w");
783 if (!fp) {
784 return SET_ERRNO_SYS(ERROR_FILE_OPERATION, "Cannot open %s for writing",
785 file_path);
786 }
787 defer(fclose(fp));
788 if (fputs(toml_content, fp) < 0) {
789 return SET_ERRNO_SYS(ERROR_FILE_OPERATION, "Failed to write to %s",
790 file_path);
791 }
792 } else {
793 /* Write to stdout */
794 if (fputs(toml_content, stdout) < 0) {
795 return SET_ERRNO_SYS(ERROR_FILE_OPERATION, "Failed to write to stdout");
796 }
797 /* Flush to ensure piped output is written immediately */
798 (void)fflush(stdout);
799 }
800
801 return ASCIICHAT_OK;
802}
#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:44
char description[256]
Definition colorscheme.h:85
char name[64]
Definition colorscheme.h:82

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 407 of file colorscheme.c.

407 {
408 if (!lifecycle_is_initialized(&g_colorscheme_lifecycle)) {
409 /* Lazy initialization of color system */
411 }
412
413 static _Thread_local color_scheme_t snapshot;
414 static _Thread_local uint64_t revision;
415 if (revision != atomic_load(&g_scheme_revision)) {
416 mutex_lock(&g_colorscheme_mutex);
417 memcpy(&snapshot, &g_active_scheme, sizeof(snapshot));
418 revision = atomic_load(&g_scheme_revision);
419 mutex_unlock(&g_colorscheme_mutex);
420 }
421 return &snapshot;
422}
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 1076 of file colorscheme.c.

1076 {
1078 uint8_t grey = dark ? 70 : 200;
1079#if !defined(__EMSCRIPTEN__)
1080 uint8_t r, g, b;
1081 if (keyboard_is_initialized() && keyboard_stream_background(&r, &g, &b) &&
1082 abs((int)((r + g + b) / 3) - grey) < 40)
1083 grey = dark ? 0 : 255;
1084#endif
1085 return grey;
1086}
terminal_background_t colorscheme_current_background(void)

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 308 of file colorscheme.c.

308 {
309 if (lifecycle_is_initialized(&g_colorscheme_lifecycle)) {
310 return ASCIICHAT_OK;
311 }
312
313 /* NOTE: Mutex is already statically initialized on POSIX with
314 * PTHREAD_MUTEX_INITIALIZER. On Windows and Emscripten/WASM, we initialize it
315 * here. Do NOT call mutex_init() on native POSIX because
316 * double-initialization of pthread_mutex_t causes undefined behavior and
317 * deadlocks. Emscripten with pthreads requires explicit initialization
318 * because PTHREAD_MUTEX_INITIALIZER doesn't work correctly in threaded WASM
319 * builds. */
320#if defined(_WIN32) || defined(__EMSCRIPTEN__)
321 static bool mutex_initialized = false;
322 if (!mutex_initialized) {
323#ifdef __EMSCRIPTEN__
324#else
325#endif
326 mutex_init(&g_colorscheme_mutex, "colorscheme");
327 mutex_initialized = true;
328 } else {
329 }
330#else
331#endif
332
333 /* Load default scheme */
334 const color_scheme_t *pastel = find_builtin_scheme("pastel");
335 if (!pastel) {
336 return SET_ERRNO(ERROR_CONFIG, "Failed to load default pastel scheme");
337 }
338
339 memcpy(&g_active_scheme, pastel, sizeof(color_scheme_t));
340 atomic_fetch_add(&g_scheme_revision, 1);
341
342 /* Mark as initialized */
343 lifecycle_init(&g_colorscheme_lifecycle, "colorscheme");
344#if !defined(_WIN32) && !defined(__EMSCRIPTEN__)
345 // Register the statically initialized mutex without initializing its pthread
346 // storage again.
348 NAMED_REGISTER_MUTEX(&g_colorscheme_mutex, "colorscheme", NULL);
349#endif
350
351 return ASCIICHAT_OK;
352}
#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 463 of file colorscheme.c.

464 {
465 if (!name || !scheme) {
466 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL name or scheme pointer");
467 }
468
469 const color_scheme_t *builtin = find_builtin_scheme(name);
470 if (!builtin) {
471 return SET_ERRNO(ERROR_CONFIG, "Unknown built-in color scheme: %s", name);
472 }
473
474 memcpy(scheme, builtin, sizeof(color_scheme_t));
475 return ASCIICHAT_OK;
476}

References ASCIICHAT_OK, ERROR_CONFIG, ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by colorscheme_export_scheme().

◆ 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 478 of file colorscheme.c.

479 {
480 if (!path || !scheme) {
481 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL path or scheme pointer");
482 }
483
484 /* Check if file exists and is readable */
485 struct stat sb;
486 if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode)) {
488 "Color scheme file not found or not readable: %s", path);
489 }
490
491 /* Parse TOML file */
492 toml_result_t result = toml_parse_file_ex(path);
493 if (!result.ok) {
494 toml_free(result);
495 return SET_ERRNO(ERROR_CONFIG, "Failed to parse color scheme file '%s': %s",
496 path, result.errmsg);
497 }
498
499 /* Extract scheme information */
500 memset(scheme, 0, sizeof(color_scheme_t));
501
502 /* Get scheme section */
503 toml_datum_t scheme_section = toml_get(result.toptab, "scheme");
504 if (scheme_section.type == TOML_TABLE) {
505 /* Get scheme name */
506 toml_datum_t name_datum = toml_get(scheme_section, "name");
507 if (name_datum.type == TOML_STRING) {
508 SAFE_STRNCPY(scheme->name, name_datum.u.s, sizeof(scheme->name));
509 }
510
511 /* Get scheme description */
512 toml_datum_t desc_datum = toml_get(scheme_section, "description");
513 if (desc_datum.type == TOML_STRING) {
514 SAFE_STRNCPY(scheme->description, desc_datum.u.s,
515 sizeof(scheme->description));
516 }
517 }
518
519 /* Get colors section */
520 toml_datum_t colors_section = toml_get(result.toptab, "colors");
521 if (colors_section.type == TOML_TABLE) {
522 /* Parse dark mode colors */
523 toml_datum_t dark_section = toml_get(colors_section, "dark");
524 if (dark_section.type == TOML_TABLE) {
525 const char *color_names[] = {"dev", "debug", "info", "warn",
526 "error", "fatal", "grey", "reset"};
527 for (int i = 0; i < 8; i++) {
528 toml_datum_t color_value = toml_get(dark_section, color_names[i]);
529 if (color_value.type == TOML_STRING) {
530 parse_hex_color(color_value.u.s, &scheme->log_colors_dark[i].r,
531 &scheme->log_colors_dark[i].g,
532 &scheme->log_colors_dark[i].b);
533 }
534 }
535 }
536
537 /* Parse light mode colors (optional) */
538 toml_datum_t light_section = toml_get(colors_section, "light");
539 if (light_section.type == TOML_TABLE) {
540 scheme->has_light_variant = true;
541 const char *color_names[] = {"dev", "debug", "info", "warn",
542 "error", "fatal", "grey", "reset"};
543 for (int i = 0; i < 8; i++) {
544 toml_datum_t color_value = toml_get(light_section, color_names[i]);
545 if (color_value.type == TOML_STRING) {
546 parse_hex_color(color_value.u.s, &scheme->log_colors_light[i].r,
547 &scheme->log_colors_light[i].g,
548 &scheme->log_colors_light[i].b);
549 }
550 }
551 }
552 }
553
554 scheme->is_builtin = false;
555 SAFE_STRNCPY(scheme->source_file, path, sizeof(scheme->source_file));
556
557 toml_free(result);
558 return ASCIICHAT_OK;
559}
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[PLATFORM_MAX_PATH_LENGTH]
Definition colorscheme.h:97

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 424 of file colorscheme.c.

424 {
425 if (!name) {
426 return SET_ERRNO(ERROR_INVALID_PARAM, "Scheme name is NULL");
427 }
428
429 /* Ensure color system is initialized */
430 if (!lifecycle_is_initialized(&g_colorscheme_lifecycle)) {
432 }
433
434 color_scheme_t scheme = {0};
436
437 /* Try loading as built-in scheme first */
438 const color_scheme_t *builtin = find_builtin_scheme(name);
439 if (builtin) {
440 memcpy(&scheme, builtin, sizeof(color_scheme_t));
441 } else if (strchr(name, '/') || strchr(name, '.')) {
442 /* Try loading as file path if it contains / or . */
443 result = colorscheme_load_from_file(name, &scheme);
444 if (result != ASCIICHAT_OK) {
445 return result;
446 }
447 } else {
448 return SET_ERRNO(
450 "Unknown color scheme: %s (not a built-in scheme or valid file path)",
451 name);
452 }
453
454 mutex_lock(&g_colorscheme_mutex);
455 memcpy(&g_active_scheme, &scheme, sizeof(color_scheme_t));
456 atomic_fetch_add(&g_scheme_revision, 1);
457 mutex_unlock(&g_colorscheme_mutex);
458
459 log_dev("Switched to color scheme: %s", name);
460 return ASCIICHAT_OK;
461}
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:551

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 terminal background (light or dark).

Returns
Detected terminal background

Uses multiple methods to detect terminal background:

  1. TERM_BACKGROUND environment variable
  2. COLORFGBG environment variable
  3. OSC 11 terminal query (if supported)
  4. Defaults to DARK

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 821 of file colorscheme.c.

821 {
822 /* Method 1: Check environment variable override (highest priority) */
823 const char *term_bg = SAFE_GETENV("TERM_BACKGROUND");
824 if (term_bg) {
825 if (platform_strcasecmp(term_bg, "light") == 0) {
827 }
828 if (platform_strcasecmp(term_bg, "dark") == 0) {
830 }
831 }
832
833 /* Method 2: Use terminal_has_dark_background() for automatic theme detection
834 * This checks OSC 11 background color, environment variables, and terminal
835 * type */
836 bool is_dark = terminal_has_dark_background();
838}
#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.

Parameters
argcCommand-line argument count
argvCommand-line arguments
Returns
ASCIICHAT_OK on success, error code on failure (non-fatal)

Called from main() BEFORE log_init() to apply color scheme to logging. Scans for –color-scheme and loads ~/.config/ascii-chat/colors.toml.

Priority: –color-scheme CLI > colors.toml > built-in default

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 922 of file colorscheme.c.

923 {
924 /* Initialize the color system with defaults */
926 if (result != ASCIICHAT_OK) {
927 /* Non-fatal: use built-in defaults */
928 return ASCIICHAT_OK;
929 }
930
931 /* Step 1: Try to load from config file (~/.config/ascii-chat/colors.toml) */
932 color_scheme_t config_scheme = {0};
933 asciichat_error_t config_result = load_config_color_scheme(&config_scheme);
934 if (config_result == ASCIICHAT_OK) {
935 /* Config file loaded successfully, apply it */
936 colorscheme_set_active_scheme(config_scheme.name);
937 }
938
939 /* Step 2: CLI --color-scheme overrides config file */
940 const char *cli_scheme = find_cli_color_scheme(argc, argv);
941 if (cli_scheme) {
942 asciichat_error_t cli_result = colorscheme_set_active_scheme(cli_scheme);
943 if (cli_result != ASCIICHAT_OK) {
944 /* Invalid scheme name from CLI, continue with current scheme */
945 return cli_result;
946 }
947 }
948
949 return ASCIICHAT_OK;
950}
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.

◆ 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 566 of file colorscheme.c.

567 {
568 if (!hex || !r || !g || !b) {
569 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
570 }
571
572 /* Skip '#' prefix if present */
573 if (hex[0] == '#') {
574 hex++;
575 }
576
577 /* Validate hex string length */
578 if (strlen(hex) != 6) {
579 return SET_ERRNO(ERROR_CONFIG, "Invalid hex color (must be #RRGGBB): %s",
580 hex);
581 }
582
583 for (size_t i = 0; i < 6; ++i) {
584 if (!((hex[i] >= '0' && hex[i] <= '9') ||
585 (hex[i] >= 'a' && hex[i] <= 'f') ||
586 (hex[i] >= 'A' && hex[i] <= 'F'))) {
587 return SET_ERRNO(ERROR_CONFIG, "Invalid hex color format: %s", hex);
588 }
589 }
590
591 /* Parse hex digits */
592 unsigned int rgb = 0;
593 if (SAFE_SSCANF(hex, "%6x", &rgb) != 1) {
594 return SET_ERRNO(ERROR_CONFIG, "Invalid hex color format: %s", hex);
595 }
596
597 *r = (rgb >> 16) & 0xFF;
598 *g = (rgb >> 8) & 0xFF;
599 *b = rgb & 0xFF;
600
601 return ASCIICHAT_OK;
602}
#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 608 of file colorscheme.c.

609 {
610 if (!buf || size < 20)
611 return;
612 safe_snprintf(buf, size, "\x1b[38;2;%d;%d;%dm", r, g, b);
613}

Referenced by colorscheme_compile_scheme(), and colorscheme_current_palette().

Variable Documentation

◆ g_colorscheme_mutex

mutex_t g_colorscheme_mutex
extern

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 56 of file colorscheme.c.

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

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