ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
options/config/config.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define OPTIONS_CONFIG_QUESTION_BUFFER_SIZE 4096
9
10/* Existing buffer budgets in bytes, including NUL for text storage. */
11#define CONFIG_WRITTEN_FLAG_CAPACITY 64
12
13/* Existing buffer budgets in bytes, including NUL for text storage. */
14#define CONFIG_CATEGORY_CAPACITY 16
15
17
26#include <util/string.h>
28#include <ascii-chat/common.h>
29#include <libplatform/terminal.h>
30#include <libplatform/system.h>
31#include <libplatform/question.h>
32#include <sys/stat.h>
33#include <libplatform/filesystem.h>
35#include <ascii-chat/log/log.h>
38#include <ascii-chat/version.h>
39#include <defer.h>
40
41#include <ascii-chat-deps/tomlc17/src/tomlc17.h>
42#include <string.h>
43#include <stdlib.h>
44#include <stdio.h>
45#include <errno.h>
46#include <sys/stat.h>
47
56
63#define CONFIG_WARN(fmt, ...) \
64 do { \
65 log_warn("Config file: " fmt, ##__VA_ARGS__); \
66 } while (0)
67
74#define CONFIG_DEBUG(fmt, ...) \
75 do { \
76 /* Debug messages are only shown in debug builds after logging is initialized */ \
77 /* Use log_dev which safely checks initialization itself */ \
78 log_dev(fmt, ##__VA_ARGS__); \
79 } while (0)
80
82
83// Configuration state tracking removed - not needed with schema-driven approach
84// CLI arguments always override config values, so no need to track what was set
85
86/* Validation functions are now provided by options/validation.h */
87
94
104static const char *get_toml_string_validated(toml_datum_t datum) {
105 if (datum.type != TOML_STRING) {
106 SET_ERRNO(ERROR_INVALID_PARAM, "not a toml string");
107 return NULL;
108 }
109
110 const char *str = datum.u.s;
111 if (!str) {
112 SET_ERRNO(ERROR_INVALID_PARAM, "no toml string");
113 return NULL;
114 }
115
116 // Validate UTF-8 encoding using utility function
117 if (!utf8_is_valid(str)) {
118 log_warn("Config value contains invalid UTF-8 sequence");
119 return NULL;
120 }
121
122 return str;
123}
124
126
127// ============================================================================
128// Type Handler Registry - Consolidates 4 duplicated switch statements
129// ============================================================================
130// TECHNICAL DEBT FIX: The code previously had 4 separate switch(meta->type)
131// blocks for extract, parse, write, and format operations. This consolidated
132// registry eliminates ~300 lines of code duplication while maintaining all
133// type-specific logic and special case handling.
134
143typedef union {
144 char str_value[OPTIONS_BUFF_SIZE]; // STRING type
145 int int_value; // INT type
146 bool bool_value; // BOOL type
147 float float_value; // DOUBLE type (float variant)
148 double double_value; // DOUBLE type (double variant)
150
160
167typedef struct {
168 void (*extract)(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val,
169 bool *has_value);
170 asciichat_error_t (*parse_validate)(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg,
171 size_t error_size);
172 asciichat_error_t (*write_to_struct)(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg,
173 size_t error_size);
174 void (*format_output)(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf,
175 size_t bufsize);
177
178// Forward declarations
179static void extract_string(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value);
180static void extract_int(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value);
181static void extract_bool(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value);
182static void extract_double(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value);
183static asciichat_error_t parse_validate_string(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size);
184static asciichat_error_t parse_validate_int(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size);
185static asciichat_error_t parse_validate_bool(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size);
186static asciichat_error_t parse_validate_double(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size);
187static asciichat_error_t write_string(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size);
188static asciichat_error_t write_int(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size);
189static asciichat_error_t write_bool(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size);
190static asciichat_error_t write_double(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size);
191static void format_string(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize);
192static void format_int(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize);
193static void format_bool(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize);
194static void format_double(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize);
195static void format_callback(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize);
196
197// Handler registry - indexed by option_type_t
198static const option_type_handler_t g_type_handlers[] = {
199 [OPTION_TYPE_STRING] = {extract_string, parse_validate_string, write_string, format_string},
200 [OPTION_TYPE_INT] = {extract_int, parse_validate_int, write_int, format_int},
201 [OPTION_TYPE_BOOL] = {extract_bool, parse_validate_bool, write_bool, format_bool},
202 [OPTION_TYPE_DOUBLE] = {extract_double, parse_validate_double, write_double, format_double},
203 [OPTION_TYPE_CALLBACK] = {NULL, NULL, NULL, format_callback},
204 [OPTION_TYPE_ACTION] = {NULL, NULL, NULL, NULL},
205};
206
207// ============================================================================
208// Type Handler Implementations
209// ============================================================================
210
214static void extract_string(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value) {
215 (void)int_val;
216 (void)bool_val;
217 (void)double_val;
218
219 if (datum.type == TOML_STRING) {
220 const char *str = get_toml_string_validated(datum);
221 if (str && strlen(str) > 0) {
222 SAFE_STRNCPY(value_str, str, BUFFER_SIZE_MEDIUM);
223 *has_value = true;
224 }
225 } else if (datum.type == TOML_INT64) {
226 // Convert integer to string (e.g., port = 7777)
227 SAFE_SNPRINTF(value_str, BUFFER_SIZE_MEDIUM, "%lld", (long long)datum.u.int64);
228 *has_value = true;
229 }
230}
231
235static void extract_int(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value) {
236 (void)int_val;
237 (void)bool_val;
238 (void)double_val;
239
240 if (datum.type == TOML_INT64) {
241 SAFE_SNPRINTF(value_str, BUFFER_SIZE_MEDIUM, "%lld", (long long)datum.u.int64);
242 *has_value = true;
243 } else if (datum.type == TOML_STRING) {
244 const char *str = get_toml_string_validated(datum);
245 if (str) {
246 SAFE_STRNCPY(value_str, str, BUFFER_SIZE_MEDIUM);
247 *has_value = true;
248 }
249 }
250}
251
255static void extract_bool(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value) {
256 (void)int_val;
257 (void)double_val;
258
259 if (datum.type == TOML_BOOLEAN) {
260 *bool_val = datum.u.boolean;
261 // Also set value_str for parse_validate phase
263 *has_value = true;
264 }
265}
266
270static void extract_double(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value) {
271 (void)int_val;
272 (void)bool_val;
273
274 if (datum.type == TOML_FP64) {
275 *double_val = datum.u.fp64;
276 SAFE_SNPRINTF(value_str, BUFFER_SIZE_MEDIUM, "%.10g", *double_val);
277 *has_value = true;
278 } else if (datum.type == TOML_STRING) {
279 const char *str = get_toml_string_validated(datum);
280 if (str) {
281 SAFE_STRNCPY(value_str, str, BUFFER_SIZE_MEDIUM);
282 *has_value = true;
283 }
284 }
285}
286
290static asciichat_error_t parse_validate_string(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size) {
291 (void)meta;
292 (void)error_msg;
293 (void)error_size;
294
295 SAFE_STRNCPY(parsed->str_value, value_str, sizeof(parsed->str_value));
296 return ASCIICHAT_OK;
297}
298
302static asciichat_error_t parse_validate_int(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size) {
303 // Detect enum fields by checking field_offset
304 int enum_val = -1;
305 bool is_enum = false;
306
307 if (meta->field_offset == offsetof(options_t, color_mode)) {
308 enum_val = validate_opt_color_mode(value_str, error_msg, error_size);
309 is_enum = true;
310 } else if (meta->field_offset == offsetof(options_t, color_filter)) {
311 color_filter_t filter = color_filter_from_cli_name(value_str);
312 if (filter != COLOR_FILTER_NONE || strcmp(value_str, OPT_COLOR_FILTER_NONE) == 0) {
313 enum_val = (int)filter;
314 } else {
315 SAFE_SNPRINTF(error_msg, error_size, "Invalid color filter '%s'", value_str);
316 enum_val = -1;
317 }
318 is_enum = true;
319 } else if (meta->field_offset == offsetof(options_t, render_mode)) {
320 enum_val = validate_opt_render_mode(value_str, error_msg, error_size);
321 is_enum = true;
322 } else if (meta->field_offset == offsetof(options_t, palette_type)) {
323 enum_val = validate_opt_palette(value_str, error_msg, error_size);
324 is_enum = true;
325 }
326
327 if (is_enum) {
328 // Enum parsing
329 bool named_auto = meta->field_offset == offsetof(options_t, color_mode) && strcmp(value_str, OPT_VALUE_AUTO) == 0;
330 if (enum_val < 0 && !named_auto) {
331 // Backward compatibility: accept numeric enum values too.
332 char *endptr = NULL;
333 long raw_enum = strtol(value_str, &endptr, 10);
334 bool parsed_numeric = (value_str && *value_str != '\0' && endptr && *endptr == '\0');
335 bool numeric_valid = false;
336
337 if (parsed_numeric && raw_enum >= INT_MIN && raw_enum <= INT_MAX) {
338 int enum_int = (int)raw_enum;
339 if (meta->field_offset == offsetof(options_t, color_mode)) {
340 numeric_valid = (enum_int == COLOR_MODE_AUTO || enum_int == COLOR_MODE_NONE || enum_int == COLOR_MODE_16_COLOR || enum_int == COLOR_MODE_256_COLOR || enum_int == COLOR_MODE_TRUECOLOR);
341 } else if (meta->field_offset == offsetof(options_t, color_filter)) {
342 numeric_valid = (enum_int >= COLOR_FILTER_NONE && enum_int < COLOR_FILTER_COUNT);
343 } else if (meta->field_offset == offsetof(options_t, render_mode)) {
344 numeric_valid = (enum_int == RENDER_MODE_FOREGROUND || enum_int == RENDER_MODE_BACKGROUND || enum_int == RENDER_MODE_HALF_BLOCK);
345 } else if (meta->field_offset == offsetof(options_t, palette_type)) {
346 numeric_valid = (enum_int >= PALETTE_STANDARD && enum_int < PALETTE_COUNT);
347 }
348 if (numeric_valid) {
349 enum_val = enum_int;
350 }
351 }
352
353 if (!numeric_valid) {
354 if (strlen(error_msg) == 0) {
355 SAFE_SNPRINTF(error_msg, error_size, "Invalid enum value: %s", value_str);
356 }
357 return ERROR_CONFIG;
358 }
359 }
360 parsed->int_value = enum_val;
361 } else {
362 // Regular integer parsing
363 char *endptr = NULL;
364 long parsed_val = strtol(value_str, &endptr, 10);
365 if (*endptr != '\0') {
366 SAFE_SNPRINTF(error_msg, error_size, "Invalid integer: %s", value_str);
367 return ERROR_CONFIG;
368 }
369 if (parsed_val < INT_MIN || parsed_val > INT_MAX) {
370 SAFE_SNPRINTF(error_msg, error_size, "Integer out of range: %s", value_str);
371 return ERROR_CONFIG;
372 }
373
374 int int_val = (int)parsed_val;
375
376 // Check numeric range constraints if defined
377 // Constraints are present if max != 0 (max will always be non-zero for bounded integer ranges)
378 if (meta && meta->constraints.int_range.max != 0) {
379 // Allow 0 as special "use default" value for certain fields
380 bool is_auto_detect_field = (meta->field_offset == offsetof(options_t, width) || meta->field_offset == offsetof(options_t, height) || meta->field_offset == offsetof(options_t, fps) ||
381 meta->field_offset == offsetof(options_t, compression_level));
382
383 if (int_val == 0 && is_auto_detect_field) {
384 // 0 is allowed for these fields (means auto-detect or use default)
385 } else if (int_val < meta->constraints.int_range.min || int_val > meta->constraints.int_range.max) {
386 SAFE_SNPRINTF(error_msg, error_size, "Integer %d out of range [%d-%d]: %s", int_val, meta->constraints.int_range.min, meta->constraints.int_range.max, value_str);
387 return ERROR_CONFIG;
388 }
389 }
390
391 parsed->int_value = int_val;
392 }
393 return ASCIICHAT_OK;
394}
395
399static asciichat_error_t parse_validate_bool(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size) {
400 (void)meta;
401 (void)error_msg;
402 (void)error_size;
403
404 // Parse boolean from string representation (OPT_VALUE_TRUE or OPT_VALUE_FALSE)
405 parsed->bool_value = value_str && (strcmp(value_str, OPT_VALUE_TRUE) == 0 || strcmp(value_str, "1") == 0 || strcmp(value_str, "yes") == 0);
406 return ASCIICHAT_OK;
407}
408
412static asciichat_error_t parse_validate_double(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size) {
413 char *endptr = NULL;
414 double parsed_val = strtod(value_str, &endptr);
415 if (*endptr != '\0') {
416 SAFE_SNPRINTF(error_msg, error_size, "Invalid float: %s", value_str);
417 return ERROR_CONFIG;
418 }
419
420 // Check numeric range constraints if defined (for double types)
421 if (meta && meta->constraints.int_range.max != 0) {
422 // Use int_range for doubles too (the values are stored as doubles in the constraint)
423 double min = (double)meta->constraints.int_range.min;
424 double max = (double)meta->constraints.int_range.max;
425 if (parsed_val < min || parsed_val > max) {
426 SAFE_SNPRINTF(error_msg, error_size, "Float %.2f out of range [%.2f-%.2f]: %s", parsed_val, min, max, value_str);
427 return ERROR_CONFIG;
428 }
429 }
430
431 parsed->float_value = (float)parsed_val;
432 return ASCIICHAT_OK;
433}
434
438static asciichat_error_t write_string(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size) {
439 (void)error_msg;
440 (void)error_size;
441
442 char *field_ptr = ((char *)opts) + meta->field_offset;
443 const char *final_value = parsed->str_value;
444
445 // Special handling for path-based options (keys, log files)
446 bool is_path_option = (strstr(meta->toml_key, "key") != NULL || strstr(meta->toml_key, "log_file") != NULL || strstr(meta->toml_key, "keyfile") != NULL);
447 if (is_path_option) {
448 // Check if it's a path that needs normalization
449 if (path_looks_like_path(final_value)) {
450 char *normalized = NULL;
451 path_role_t role = PATH_ROLE_CONFIG_FILE; // Default
452 if (strstr(meta->toml_key, "key") != NULL) {
453 role = (strstr(meta->toml_key, "server_key") != NULL || strstr(meta->toml_key, "client_keys") != NULL) ? PATH_ROLE_KEY_PUBLIC : PATH_ROLE_KEY_PRIVATE;
454 } else if (strstr(meta->toml_key, "log_file") != NULL) {
455 role = PATH_ROLE_LOG_FILE;
456 }
457
458 asciichat_error_t path_result = path_validate_user_path(final_value, role, &normalized);
459 if (path_result != ASCIICHAT_OK) {
460 SAFE_FREE(normalized);
461 return path_result;
462 }
463 SAFE_STRNCPY(field_ptr, normalized, meta->field_size);
464 SAFE_FREE(normalized);
465 } else {
466 // Not a path, just an identifier (e.g., "gpg:keyid", "github:user")
467 SAFE_STRNCPY(field_ptr, final_value, meta->field_size);
468 }
469
470 } else {
471 SAFE_STRNCPY(field_ptr, final_value, meta->field_size);
472 }
473
474 return ASCIICHAT_OK;
475}
476
480static asciichat_error_t write_int(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size) {
481 (void)error_msg;
482 (void)error_size;
483
484 char *field_ptr = ((char *)opts) + meta->field_offset;
485
486 // Handle unsigned short int fields (webcam_index)
487 if (meta->field_size == sizeof(unsigned short int)) {
488 *(unsigned short int *)field_ptr = (unsigned short int)parsed->int_value;
489 } else {
490 *(int *)field_ptr = parsed->int_value;
491 }
492
493 return ASCIICHAT_OK;
494}
495
499static asciichat_error_t write_bool(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size) {
500 (void)error_msg;
501 (void)error_size;
502
503 char *field_ptr = ((char *)opts) + meta->field_offset;
504 bool bool_value = parsed->bool_value;
505 bool is_inverted_no_splash = false;
506 if (meta && meta->field_offset == offsetof(options_t, splash_screen) && meta->toml_key) {
507 const char *key = meta->toml_key;
508 size_t key_len = strlen(key);
509 static const char suffix[] = ".no_splash";
510 size_t suffix_len = sizeof(suffix) - 1;
511 is_inverted_no_splash = (key_len >= suffix_len && strcmp(key + (key_len - suffix_len), suffix) == 0);
512 }
513 if (is_inverted_no_splash) {
514 bool_value = !bool_value;
515 }
516
517 // Handle unsigned short int bool fields (common in options_t)
518 if (meta->field_size == sizeof(unsigned short int)) {
519 *(unsigned short int *)field_ptr = bool_value ? 1 : 0;
520 } else {
521 *(bool *)field_ptr = bool_value;
522 }
523
524 if (meta->field_offset == offsetof(options_t, flip_x))
525 opts->flip_x_explicit = true;
526
527 return ASCIICHAT_OK;
528}
529
533static asciichat_error_t write_double(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size) {
534 (void)error_msg;
535 (void)error_size;
536
537 char *field_ptr = ((char *)opts) + meta->field_offset;
538
539 // Check field_size to distinguish float from double
540 // Use memcpy for alignment-safe writes
541 if (meta->field_size == sizeof(float)) {
542 float float_val = (float)parsed->float_value;
543 memcpy(field_ptr, &float_val, sizeof(float));
544 } else {
545 double double_val = (double)parsed->float_value;
546 memcpy(field_ptr, &double_val, sizeof(double));
547 }
548
549 return ASCIICHAT_OK;
550}
551
555static void format_string(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize) {
556 (void)field_size;
557 (void)meta;
558
559 const char *str_value = (const char *)field_ptr;
560 if (str_value && strlen(str_value) > 0) {
561 char escaped_str[BUFFER_SIZE_MEDIUM * 2]; // Max 2x size for escaping '%'
562 size_t j = 0;
563 for (size_t i = 0; i < strlen(str_value) && j < sizeof(escaped_str) - 2; ++i) {
564 if (str_value[i] == '%') {
565 escaped_str[j++] = '%';
566 escaped_str[j++] = '%';
567 } else {
568 escaped_str[j++] = str_value[i];
569 }
570 }
571 escaped_str[j] = '\0';
572
573 SAFE_SNPRINTF(buf, bufsize, "\"%s\"", escaped_str);
574 } else {
575 SAFE_SNPRINTF(buf, bufsize, "\"\"");
576 }
577}
578
582static void format_int(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize) {
583 int int_value = 0;
584 if (field_size == sizeof(unsigned short int)) {
585 int_value = *(unsigned short int *)field_ptr;
586 } else {
587 int_value = *(int *)field_ptr;
588 }
589
590 // Emit symbolic names for enum-backed values in generated config.
591 if (meta && meta->field_offset == offsetof(options_t, color_mode)) {
592 const char *name = OPT_VALUE_AUTO;
593 if (int_value == COLOR_MODE_NONE) {
594 name = OPT_COLOR_MODE_NONE;
595 } else if (int_value == COLOR_MODE_16_COLOR) {
596 name = OPT_COLOR_MODE_16;
597 } else if (int_value == COLOR_MODE_256_COLOR) {
598 name = OPT_COLOR_MODE_256;
599 } else if (int_value == COLOR_MODE_TRUECOLOR) {
601 }
602 SAFE_SNPRINTF(buf, bufsize, "\"%s\"", name);
603 return;
604 }
605
606 if (meta && meta->field_offset == offsetof(options_t, color_filter)) {
607 const char *name = OPT_COLOR_FILTER_NONE;
608 if (int_value > COLOR_FILTER_NONE && int_value < COLOR_FILTER_COUNT) {
609 const color_filter_def_t *def = color_filter_get_metadata((color_filter_t)int_value);
610 if (def && def->cli_name) {
611 name = def->cli_name;
612 }
613 }
614 SAFE_SNPRINTF(buf, bufsize, "\"%s\"", name);
615 return;
616 }
617
618 if (meta && meta->field_offset == offsetof(options_t, renderer)) {
619 SAFE_SNPRINTF(buf, bufsize, "\"%s\"", int_value == ASCII_RENDERER_GLYPH ? "glyph" : "luminance");
620 return;
621 }
622
623 if (meta && meta->field_offset == offsetof(options_t, render_mode)) {
624 const char *name = OPT_RENDER_MODE_FOREGROUND;
625 if (int_value == RENDER_MODE_BACKGROUND) {
627 } else if (int_value == RENDER_MODE_HALF_BLOCK) {
629 }
630 SAFE_SNPRINTF(buf, bufsize, "\"%s\"", name);
631 return;
632 }
633
634 SAFE_SNPRINTF(buf, bufsize, "%d", int_value);
635}
636
640static void format_bool(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize) {
641 bool bool_value = false;
642 if (field_size == sizeof(unsigned short int)) {
643 bool_value = *(unsigned short int *)field_ptr != 0;
644 } else {
645 bool_value = *(bool *)field_ptr;
646 }
647 bool is_inverted_no_splash = false;
648 if (meta && meta->field_offset == offsetof(options_t, splash_screen) && meta->toml_key) {
649 const char *key = meta->toml_key;
650 size_t key_len = strlen(key);
651 static const char suffix[] = ".no_splash";
652 size_t suffix_len = sizeof(suffix) - 1;
653 is_inverted_no_splash = (key_len >= suffix_len && strcmp(key + (key_len - suffix_len), suffix) == 0);
654 }
655 if (is_inverted_no_splash) {
656 bool_value = !bool_value;
657 }
658 SAFE_SNPRINTF(buf, bufsize, "%s", bool_value ? OPT_VALUE_TRUE : OPT_VALUE_FALSE);
659}
660
664static void format_double(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize) {
665 (void)meta;
666
667 if (field_size == sizeof(float)) {
668 float float_value = 0.0f;
669 memcpy(&float_value, field_ptr, sizeof(float));
670 SAFE_SNPRINTF(buf, bufsize, "%.1f", (double)float_value);
671 } else {
672 double double_value = 0.0;
673 memcpy(&double_value, field_ptr, sizeof(double));
674 SAFE_SNPRINTF(buf, bufsize, "%.1f", double_value);
675 }
676}
677
684static void format_callback(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize) {
685 if (!field_ptr || !buf || !meta) {
686 return;
687 }
688
689 if (meta->field_offset == offsetof(options_t, zalgo)) {
690 int level = *(const int *)field_ptr;
691 SAFE_SNPRINTF(buf, bufsize, "%d", level > 0 ? level : 7);
692 return;
693 }
694 if (meta->field_offset == offsetof(options_t, audio_source)) {
695 static const char *const names[] = {"all", "call", "mic", "media"};
696 int value = *(const int *)field_ptr;
697 SAFE_SNPRINTF(buf, bufsize, "\"%s\"", value >= 0 && (size_t)value < ARRAY_SIZE(names) ? names[value] : "all");
698 return;
699 }
700 if (meta->field_offset == offsetof(options_t, audio_capture_source)) {
701 static const char *const names[] = {"auto", "mic", "media", "both", "remote"};
702 int value = *(const int *)field_ptr;
703 SAFE_SNPRINTF(buf, bufsize, "\"%s\"", value >= 0 && (size_t)value < ARRAY_SIZE(names) ? names[value] : "auto");
704 return;
705 }
706 if (meta->field_offset == offsetof(options_t, test_pattern)) {
707 const options_t *opts = (const options_t *)(field_ptr - offsetof(options_t, test_pattern));
708 if (opts->test_pattern)
709 SAFE_SNPRINTF(buf, bufsize, "%d", opts->test_pattern_index);
710 else
711 SAFE_SNPRINTF(buf, bufsize, "false");
712 return;
713 }
714 if (meta->field_offset == offsetof(options_t, log_file) || meta->field_offset == offsetof(options_t, palette_custom) || meta->field_offset == offsetof(options_t, yt_dlp_options)) {
715 format_string(field_ptr, field_size, meta, buf, bufsize);
716 return;
717 }
718
719 if (meta->field_offset == offsetof(options_t, media_seek_timestamp) || meta->field_offset == offsetof(options_t, microphone_sensitivity) ||
720 meta->field_offset == offsetof(options_t, speakers_volume)) {
721 format_double(field_ptr, field_size, meta, buf, bufsize);
722 return;
723 }
724
725 if (field_size == sizeof(bool)) {
726 format_bool(field_ptr, field_size, meta, buf, bufsize);
727 return;
728 }
729
730 format_int(field_ptr, field_size, meta, buf, bufsize);
731}
732
737
759static asciichat_error_t config_apply_schema(toml_datum_t toptab, asciichat_mode_t detected_mode, options_t *opts, bool strict) {
760 size_t metadata_count = 0;
761 const config_option_metadata_t *metadata = config_schema_get_all(&metadata_count);
762 asciichat_error_t first_error = ASCIICHAT_OK;
763
764 // Track which options were set to avoid duplicates (e.g., log_file vs logging.log_file)
765 size_t flags_count = metadata_count > 0 ? metadata_count : 1;
766 bool *option_set_flags = SAFE_CALLOC(flags_count, sizeof(bool), bool *);
767 if (!option_set_flags) {
768 asciichat_error_t err = SET_ERRNO(ERROR_MEMORY, "Failed to allocate config option flags");
769 return err;
770 }
771 defer(SAFE_FREE(option_set_flags));
772
773 for (size_t i = 0; i < metadata_count; i++) {
774 const config_option_metadata_t *meta = &metadata[i];
775
776 toml_datum_t datum = toml_seek(toptab, meta->toml_key);
777 if (datum.type == TOML_UNKNOWN) {
778 continue; // Absent options do not impose mode restrictions.
779 }
780
781 // Validate mode compatibility using mode_bitmask
782 // If mode_bitmask is 0 or BINARY, option applies to all modes
783 if (meta->mode_bitmask != 0 && !(meta->mode_bitmask & OPTION_MODE_BINARY)) {
784 // Option has specific mode restrictions - check if current mode matches
785 bool applies_to_mode = false;
786 if (detected_mode >= 0 && detected_mode < MODE_INVALID) {
787 option_mode_bitmask_t mode_bit = (option_mode_bitmask_t)(1 << detected_mode);
788 applies_to_mode = (meta->mode_bitmask & mode_bit) != 0;
789 }
790
791 if (!applies_to_mode) {
792 log_dev("Config: Option '%s' is not supported for this mode (skipping)", meta->toml_key);
793 continue;
794 }
795 }
796
797 // Skip if already set (avoid processing duplicates like log_file vs logging.log_file)
798 if (option_set_flags[i]) {
799 continue;
800 }
801
802 // Extract value based on type using handler
803 char value_str[BUFFER_SIZE_MEDIUM] = {0};
804 bool has_value = false;
805 int int_val = 0;
806 bool bool_val = false;
807 double double_val = 0.0;
808
809 // Use type handler for extraction (consolidated from 5 switch cases)
810 // For CALLBACK types, extract manually since they don't have extract handlers
811 if (meta->type == OPTION_TYPE_CALLBACK) {
812 if (datum.type == TOML_STRING) {
813 const char *str = get_toml_string_validated(datum);
814 if (str && strlen(str) > 0) {
815 SAFE_STRNCPY(value_str, str, BUFFER_SIZE_MEDIUM);
816 has_value = true;
817 }
818 } else if (datum.type == TOML_INT64) {
819 // Convert integer to string (e.g., port = 8080)
820 SAFE_SNPRINTF(value_str, BUFFER_SIZE_MEDIUM, "%lld", (long long)datum.u.int64);
821 has_value = true;
822 } else if (datum.type == TOML_BOOLEAN && meta->field_offset == offsetof(options_t, test_pattern)) {
823 SAFE_STRNCPY(value_str, datum.u.boolean ? "true" : "false", BUFFER_SIZE_MEDIUM);
824 has_value = true;
825 }
826 } else if (g_type_handlers[meta->type].extract) {
827 g_type_handlers[meta->type].extract(datum, value_str, &int_val, &bool_val, &double_val, &has_value);
828 }
829
830 if (!has_value) {
831 continue;
832 }
833
834 // Special handling for palette-chars (auto-sets palette_type to CUSTOM)
835 // The TOML key is "display.palette_chars" (from DISPLAY group, palette-chars option)
836 if (strcmp(meta->toml_key, "display.palette_chars") == 0) {
837 const char *chars_str = get_toml_string_validated(datum);
838 if (chars_str && strlen(chars_str) > 0) {
839 if (strlen(chars_str) < sizeof(opts->palette_custom)) {
840 SAFE_STRNCPY(opts->palette_custom, chars_str, sizeof(opts->palette_custom));
841 opts->palette_custom[sizeof(opts->palette_custom) - 1] = '\0';
842 opts->palette_custom_set = true;
843 opts->palette_explicit = true;
845 option_set_flags[i] = true;
846 } else {
847 CONFIG_WARN("Invalid palette.chars: too long (%zu chars, max %zu, skipping)", strlen(chars_str), sizeof(opts->palette_custom) - 1);
848 if (strict) {
849 SAFE_FREE(option_set_flags);
850 return SET_ERRNO(ERROR_CONFIG, "palette.chars too long");
851 }
852 }
853 }
854 continue;
855 }
856
857 // Special handling for no-encrypt (auto-disables encrypt_enabled)
858 // The TOML key is "security.no_encrypt" (from SECURITY group, no-encrypt option)
859 if (strcmp(meta->toml_key, "security.no_encrypt") == 0) {
860 bool no_encrypt_val = false;
861 if (strcmp(value_str, OPT_VALUE_TRUE) == 0 || strcmp(value_str, "1") == 0) {
862 no_encrypt_val = true;
863 } else if (strcmp(value_str, OPT_VALUE_FALSE) == 0 || strcmp(value_str, "0") == 0) {
864 no_encrypt_val = false;
865 } else {
866 CONFIG_WARN("Invalid no_encrypt value '%s' (expected true/false), skipping", value_str);
867 if (strict) {
868 SAFE_FREE(option_set_flags);
869 return SET_ERRNO(ERROR_CONFIG, "Invalid no_encrypt value");
870 }
871 continue;
872 }
873
874 opts->no_encrypt = no_encrypt_val;
875
876 option_set_flags[i] = true;
877 continue;
878 }
879
880 // Preserve boolean test_pattern config files; integers select an animation.
881 if (meta->field_offset == offsetof(options_t, test_pattern) && (strcmp(value_str, "true") == 0 || strcmp(value_str, "false") == 0)) {
882 opts->test_pattern = strcmp(value_str, "true") == 0;
883 option_set_flags[i] = true;
884 continue;
885 }
886
887 // Parse and validate value using handler
888 char error_msg[BUFFER_SIZE_SMALL] = {0};
889 option_parsed_value_t parsed = {0};
890 asciichat_error_t parse_result = ASCIICHAT_OK;
891
892 // MCP bind strings have a CLI parser that also validates address families.
893 // Keep their string schema, but apply that parser to TOML values as well.
894 bool mcp_bind = detected_mode == MODE_MCP_SERVER && meta->type == OPTION_TYPE_STRING && meta->parse_fn &&
895 (meta->field_offset == offsetof(options_t, address) || meta->field_offset == offsetof(options_t, address6));
896 if (meta->type == OPTION_TYPE_CALLBACK || mcp_bind) {
897 // Unified generated configs use "localhost"; the bind parser accepts
898 // numeric addresses, so preserve that loopback default for MCP.
899 if (mcp_bind && meta->field_offset == offsetof(options_t, address) && !strcmp(value_str, "localhost"))
900 SAFE_STRNCPY(value_str, "127.0.0.1", BUFFER_SIZE_MEDIUM);
901 if (meta->parse_fn) {
902 // Use custom parse function for callbacks (e.g., port parsing)
903 void *field_ptr = (char *)opts + meta->field_offset;
904 char *callback_error = NULL;
905 if (meta->parse_fn(value_str, field_ptr, &callback_error)) {
906 // Successfully parsed - callback has written to opts directly
907 if (callback_error) {
908 SAFE_FREE(callback_error);
909 }
910 // Mark as set to continue to validation
911 option_set_flags[i] = true;
912 // Don't continue - fall through to validation check below
913 } else {
914 // Parsing failed
915 CONFIG_WARN("Invalid %s value '%s': %s (skipping)", meta->toml_key, value_str, callback_error ? callback_error : "parsing failed");
916 if (callback_error) {
917 SAFE_FREE(callback_error);
918 }
919 if (strict) {
920 if (first_error == ASCIICHAT_OK) {
921 first_error = SET_ERRNO(ERROR_CONFIG, "Invalid %s value", meta->toml_key);
922 }
923 }
924 continue;
925 }
926 } else {
927 // No parse function for callback type
928 CONFIG_WARN("No parser for callback %s (parse_fn is NULL) (skipping)", meta->toml_key);
929 continue;
930 }
931 } else if (meta->type == OPTION_TYPE_ACTION) {
932 // Skip action types (not loaded from config)
933 continue;
934 } else if (g_type_handlers[meta->type].parse_validate) {
935 // Use standard type handler for parsing/validation
936 parse_result = g_type_handlers[meta->type].parse_validate(value_str, meta, &parsed, error_msg, sizeof(error_msg));
937 if (parse_result != ASCIICHAT_OK) {
938 CONFIG_WARN("Invalid %s value '%s': %s (skipping)", meta->toml_key, value_str, error_msg);
939 if (strict) {
940 if (first_error == ASCIICHAT_OK) {
941 first_error = SET_ERRNO(ERROR_CONFIG, "Invalid %s: %s", meta->toml_key, error_msg);
942 }
943 }
944 continue;
945 }
946
947 // Write value to options_t using handler
948 if (g_type_handlers[meta->type].write_to_struct) {
949 char error_msg_write[BUFFER_SIZE_SMALL] = {0};
950 asciichat_error_t write_result = g_type_handlers[meta->type].write_to_struct(&parsed, meta, opts, error_msg_write, sizeof(error_msg_write));
951 if (write_result != ASCIICHAT_OK) {
952 CONFIG_WARN("Failed to write %s: %s (skipping)", meta->toml_key, error_msg_write);
953 if (strict) {
954 if (first_error == ASCIICHAT_OK) {
955 first_error = write_result;
956 }
957 }
958 continue;
959 }
960 }
961
962 // Mark option as set
963 option_set_flags[i] = true;
964 } else {
965 // No handler for this type
966 CONFIG_WARN("No handler for %s (skipping)", meta->toml_key);
967 continue;
968 }
969
970 // Call builder's validate function if it exists (for cross-field validation)
971 if (meta->validate_fn) {
972 asciichat_errno_scope_t validation_scope = errno_checkpoint();
973 if (!meta->validate_fn(opts)) {
975 bool has_error = errno_peek_since(validation_scope, &error);
976 CONFIG_WARN("Validation failed for %s: %s (skipping)", meta->toml_key, has_error ? error.context_message : "validation failed");
977 if (strict && first_error == ASCIICHAT_OK) {
978 first_error = SET_ERRNO(ERROR_CONFIG, "Validation failed for %s: %s", meta->toml_key, has_error ? error.context_message : "validation failed");
979 } else {
981 }
982 continue;
983 }
984 }
985
986 // Mark this option as set
987 option_set_flags[i] = true;
988 }
989
990 // Handle special crypto.no_encrypt logic
991 toml_datum_t no_encrypt = toml_seek(toptab, "crypto.no_encrypt");
992 if (no_encrypt.type == TOML_BOOLEAN && no_encrypt.u.boolean) {
993 opts->no_encrypt = 1;
994 // Don't modify encrypt_enabled - they are independent flags
995 // The conflict validation will catch if both are set
996 }
997
998 // Handle password warning (check both crypto and security sections)
999 toml_datum_t password = toml_seek(toptab, "crypto.password");
1000 if (password.type == TOML_UNKNOWN) {
1001 password = toml_seek(toptab, "security.password");
1002 }
1003 if (password.type == TOML_STRING) {
1004 const char *password_str = get_toml_string_validated(password);
1005 if (password_str && strlen(password_str) > 0) {
1006 CONFIG_WARN("Password stored in config file is insecure! Use CLI --password instead.");
1007 }
1008 }
1009
1010 SAFE_FREE(option_set_flags);
1011 return first_error;
1012}
1013
1015
1046asciichat_error_t config_load_and_apply(asciichat_mode_t detected_mode, const char *config_path, bool strict, options_t *opts) {
1047 // detected_mode is used in config_apply_schema for bitmask validation
1048 char *config_path_expanded = NULL;
1049 defer(SAFE_FREE(config_path_expanded));
1050
1051 if (config_path) {
1052 // Use custom path provided
1053 config_path_expanded = expand_path(config_path);
1054 if (!config_path_expanded) {
1055 // If expansion fails, try using as-is (might already be absolute)
1056 config_path_expanded = platform_strdup(config_path);
1057 }
1058 } else {
1059 // Use default location with XDG support
1060 char *config_dir = get_config_dir();
1061 defer(SAFE_FREE(config_dir));
1062 if (config_dir) {
1063 size_t len = strlen(config_dir) + strlen("config.toml") + 1;
1064 config_path_expanded = SAFE_MALLOC(len, char *);
1065 if (config_path_expanded) {
1066 safe_snprintf(config_path_expanded, len, "%sconfig.toml", config_dir);
1067 }
1068 }
1069
1070 // Fallback to ~/.ascii-chat/config.toml
1071 if (!config_path_expanded) {
1072 config_path_expanded = expand_path("~/.ascii-chat/config.toml");
1073 }
1074 }
1075
1076 if (!config_path_expanded) {
1077 if (strict) {
1078 return SET_ERRNO(ERROR_CONFIG, "Failed to resolve config file path");
1079 }
1080 return ASCIICHAT_OK;
1081 }
1082
1083 char *validated_config_path = NULL;
1084 // An optional default config is allowed not to exist. Check this before the
1085 // whitelist validator, which quite correctly rejects paths whose parent
1086 // directory has not been created yet but should not turn that normal case
1087 // into a configuration error.
1088 if (!strict && platform_access(config_path_expanded, PLATFORM_ACCESS_EXISTS) != 0 && errno == ENOENT) {
1089 SAFE_FREE(config_path_expanded);
1090 return ASCIICHAT_OK;
1091 }
1092 // An explicit --config path is already user-authorized and may point to any
1093 // readable configuration file. Do not route Windows absolute paths through
1094 // the sandbox validator, which is intended for untrusted path-valued
1095 // options and can reject valid drive-qualified paths.
1096 if (config_path) {
1097 validated_config_path = platform_strdup(config_path_expanded);
1098 if (!validated_config_path) {
1099 SAFE_FREE(config_path_expanded);
1100 return SET_ERRNO(ERROR_MEMORY, "Failed to copy config file path");
1101 }
1102 } else {
1103 asciichat_error_t validate_result = path_validate_user_path(config_path_expanded, PATH_ROLE_CONFIG_FILE, &validated_config_path);
1104 if (validate_result != ASCIICHAT_OK) {
1105 SAFE_FREE(validated_config_path);
1106 SAFE_FREE(config_path_expanded);
1107 return validate_result;
1108 }
1109 }
1110 // Free the old path before reassigning (defer will free the new one)
1111 if (config_path_expanded != validated_config_path) {
1112 SAFE_FREE(config_path_expanded);
1113 }
1114 config_path_expanded = validated_config_path;
1115
1116 // Determine display path for error messages (before any early returns)
1117 const char *display_path = config_path ? config_path : config_path_expanded;
1118
1119 // Log that we're attempting to load config (before logging is initialized, use stderr)
1120 // Only print if terminal output is enabled (suppress with --quiet)
1121 if (config_path && log_get_terminal_output()) {
1122 log_dev("Loading configuration from: %s", display_path);
1123 }
1124
1125 // Check if config file exists
1126 struct stat st;
1127 if (stat(config_path_expanded, &st) != 0) {
1128 if (strict) {
1129 return SET_ERRNO(ERROR_CONFIG, "Config file does not exist: '%s'", display_path);
1130 }
1131 // File doesn't exist, that's OK - not required (non-strict mode)
1132 return ASCIICHAT_OK;
1133 }
1134
1135 // Verify it's a regular file
1136 if (!S_ISREG(st.st_mode)) {
1137 if (strict) {
1138 return SET_ERRNO(ERROR_CONFIG, "Config file exists but is not a regular file: '%s'", display_path);
1139 }
1140 CONFIG_WARN("Config file exists but is not a regular file: '%s' (skipping)", display_path);
1141 return ASCIICHAT_OK;
1142 }
1143
1144 // Parse TOML file
1145 toml_result_t result = toml_parse_file_ex(config_path_expanded);
1146 // Ensure TOML resources are freed at ALL function exit points (defer handles cleanup)
1147 defer(toml_free(result));
1148
1149 if (!result.ok) {
1150 // result.errmsg is an array, so check its first character
1151 const char *errmsg = (strlen(result.errmsg) > 0) ? result.errmsg : "Unknown parse error";
1152
1153 if (strict) {
1154 // For strict mode, return detailed error message directly
1155 // Note: SET_ERRNO stores the message in context, but asciichat_error_string() only returns generic codes
1156 // So we need to format the error message ourselves here
1157 char error_buffer[BUFFER_SIZE_MEDIUM];
1158 safe_snprintf(error_buffer, sizeof(error_buffer), "Failed to parse config file '%s': %s", display_path, errmsg);
1159 return SET_ERRNO(ERROR_CONFIG, "%s", error_buffer);
1160 }
1161 CONFIG_WARN("Failed to parse config file '%s': %s (skipping)", display_path, errmsg);
1162 return ASCIICHAT_OK; // Non-fatal error
1163 }
1164
1165 // Apply configuration using schema-driven parser with bitmask validation
1167 asciichat_error_t schema_result = config_apply_schema(result.toptab, detected_mode, opts, strict);
1168
1169 if (schema_result != ASCIICHAT_OK && strict) {
1170 return schema_result;
1171 }
1172 if (strict && schema_result == ASCIICHAT_OK)
1173 ASSERT_NO_ERRNO_SINCE(schema_scope);
1175 // In non-strict mode, continue even if some options failed validation
1176
1177 log_dev("Loaded configuration from %s", display_path);
1178
1179 // Log successful config load (use stderr since logging may not be initialized yet)
1180 // Only print if terminal output is enabled (suppress with --quiet)
1182 log_dev("Loaded configuration from: %s", display_path);
1183 }
1184
1185 // Update RCU system with modified options (for test compatibility)
1186 // In real usage, options_state_set is called later after CLI parsing
1188 asciichat_error_t rcu_result = options_state_set(opts);
1189 if (rcu_result != ASCIICHAT_OK) {
1190 // Non-fatal - RCU might not be initialized yet in some test scenarios
1191 // But log as warning so tests can see if this is the issue
1192 CONFIG_WARN("Failed to update RCU options state: %d (values may not be persisted)", rcu_result);
1193 } else {
1194 ASSERT_NO_ERRNO_SINCE(rcu_scope);
1195 }
1197
1198 return ASCIICHAT_OK;
1199}
1200
1204typedef struct {
1205 char *buffer; // Dynamically allocated buffer
1206 size_t size; // Current bytes used
1207 size_t capacity; // Total capacity
1208 bool overflow; // Set if buffer overflows
1210
1217static bool config_builder_append(config_builder_t *builder, const char *fmt, ...) {
1218 if (builder->overflow) {
1219 return false;
1220 }
1221
1222 if (builder->size >= builder->capacity) {
1223 builder->overflow = true;
1224 return false;
1225 }
1226
1227 va_list args;
1228 va_start(args, fmt);
1229 int written = safe_vsnprintf(builder->buffer + builder->size, builder->capacity - builder->size, fmt, args);
1230 va_end(args);
1231
1232 if (written < 0 || builder->size + written >= builder->capacity) {
1233 builder->overflow = true;
1234 return false;
1235 }
1236
1237 builder->size += written;
1238 return true;
1239}
1240
1241static bool config_key_should_be_commented(const char *toml_key) {
1242 if (!toml_key) {
1243 return false;
1244 }
1245
1246 return strcmp(toml_key, "display.zalgo") == 0 || strcmp(toml_key, "logging.log_file") == 0 || strcmp(toml_key, "security.password") == 0 || strcmp(toml_key, "security.key") == 0 ||
1247 strcmp(toml_key, "security.server_key") == 0 || strcmp(toml_key, "security.client_keys") == 0 || strcmp(toml_key, "media.file") == 0 || strcmp(toml_key, "media.url") == 0 ||
1248 strcmp(toml_key, "media.yt_dlp_options") == 0 || strcmp(toml_key, "network.turn_secret") == 0;
1249}
1250
1256static asciichat_mode_t extract_mode_from_bitmask(option_mode_bitmask_t mode_bitmask) {
1257 // Check each mode bit
1258 if (mode_bitmask == OPTION_MODE_SERVER)
1259 return MODE_SERVER;
1260 if (mode_bitmask == OPTION_MODE_CLIENT)
1261 return MODE_CLIENT;
1262 if (mode_bitmask == OPTION_MODE_MIRROR)
1263 return MODE_MIRROR;
1264 if (mode_bitmask == OPTION_MODE_DISCOVERY_SVC)
1266 if (mode_bitmask == OPTION_MODE_DISCOVERY)
1267 return MODE_DISCOVERY;
1268 if (mode_bitmask == OPTION_MODE_MCP_SERVER)
1269 return MODE_MCP_SERVER;
1270 if (mode_bitmask == OPTION_MODE_API_SERVER)
1271 return MODE_API_SERVER;
1272 // Bitmask has zero or multiple bits set
1273 return MODE_INVALID;
1274}
1275
1277 char *config_path_expanded = NULL;
1278
1279 defer(SAFE_FREE(config_path_expanded));
1280
1281 // Create fresh options with all OPT_*_DEFAULT values
1282 options_t defaults = options_t_new();
1283
1284 // Allocate buffer for building config content (256KB should be plenty)
1285 const size_t BUFFER_CAPACITY = 256 * 1024;
1286 config_builder_t builder = {0};
1287 builder.buffer = SAFE_MALLOC(BUFFER_CAPACITY, char *);
1288 if (!builder.buffer) {
1289 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate config buffer");
1290 }
1291 defer(SAFE_FREE(builder.buffer));
1292 builder.capacity = BUFFER_CAPACITY;
1293
1294 // Build version comment in buffer
1295 if (!config_builder_append(&builder, "# ascii-chat configuration file\n")) {
1296 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1297 }
1298 if (!config_builder_append(&builder, "# Generated by ascii-chat v%d.%d.%d-%s\n", ASCII_CHAT_VERSION_MAJOR, ASCII_CHAT_VERSION_MINOR, ASCII_CHAT_VERSION_PATCH, ASCII_CHAT_GIT_VERSION)) {
1299 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1300 }
1301 if (!config_builder_append(&builder, "#\n")) {
1302 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1303 }
1304 if (!config_builder_append(&builder, "# All options below are commented out because some configuration options\n")) {
1305 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1306 }
1307 if (!config_builder_append(&builder, "# conflict with each other (e.g., --file vs --url, --loop vs --url).\n")) {
1308 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1309 }
1310 if (!config_builder_append(&builder, "# Uncomment only the options you need and avoid conflicting combinations.\n")) {
1311 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1312 }
1313 if (!config_builder_append(&builder, "#\n")) {
1314 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1315 }
1316 if (!config_builder_append(&builder, "# If you upgrade ascii-chat and this version comment changes, you may need to\n")) {
1317 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1318 }
1319 if (!config_builder_append(&builder, "# delete and regenerate this file with: ascii-chat --config-create\n")) {
1320 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1321 }
1322 if (!config_builder_append(&builder, "#\n\n")) {
1323 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1324 }
1325
1326 // Get all options from schema
1327 size_t metadata_count = 0;
1328 const config_option_metadata_t *metadata = config_schema_get_all(&metadata_count);
1329 {
1330 options_config_t *unified_config = options_preset_unified(NULL, NULL);
1331 if (unified_config) {
1332 const options_config_t *schema_config = unified_config;
1333 (void)config_schema_build_from_configs(&schema_config, 1);
1334 options_config_destroy(unified_config);
1335 metadata = config_schema_get_all(&metadata_count);
1336 }
1337 }
1338
1339 // Build list of unique categories in order of first appearance
1340 const char *categories[CONFIG_CATEGORY_CAPACITY] = {0}; // Max expected categories
1341 size_t category_count = 0;
1342
1343 for (size_t i = 0; i < metadata_count && category_count < CONFIG_CATEGORY_CAPACITY; i++) {
1344 const char *category = metadata[i].category;
1345 if (!category) {
1346 continue;
1347 }
1348
1349 // Check if category already in list
1350 bool found = false;
1351 for (size_t j = 0; j < category_count; j++) {
1352 if (categories[j] && strcmp(categories[j], category) == 0) {
1353 found = true;
1354 break;
1355 }
1356 }
1357
1358 if (!found) {
1359 categories[category_count++] = category;
1360 }
1361 }
1362
1363 // Build each section dynamically from schema
1364 for (size_t cat_idx = 0; cat_idx < category_count; cat_idx++) {
1365 const char *category = categories[cat_idx];
1366 if (!category) {
1367 continue;
1368 }
1369
1370 // Get all options for this category
1371 size_t cat_option_count = 0;
1372 const config_option_metadata_t **cat_options = config_schema_get_by_category(category, &cat_option_count);
1373
1374 if (!cat_options || cat_option_count == 0) {
1375 continue;
1376 }
1377
1378 // Add section header
1379 if (!config_builder_append(&builder, "[%s]\n", category)) {
1380 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1381 }
1382
1383 // Track which options we've written (to avoid duplicates)
1384 bool written_flags[CONFIG_WRITTEN_FLAG_CAPACITY] = {0}; // Max options per category
1385
1386 // Add each option in this category
1387 for (size_t opt_idx = 0; opt_idx < cat_option_count && opt_idx < 64; opt_idx++) {
1388 const config_option_metadata_t *meta = cat_options[opt_idx];
1389 if (!meta || !meta->toml_key) {
1390 continue;
1391 }
1392
1393 // Skip if already written (duplicate)
1394 if (written_flags[opt_idx]) {
1395 continue;
1396 }
1397
1398 // Skip if this is a duplicate of another option (check by TOML key, not field_offset)
1399 // Note: Multiple options can map to the same field (e.g., server_log_file, client_log_file)
1400 bool is_duplicate = false;
1401 for (size_t j = 0; j < opt_idx; j++) {
1402 if (cat_options[j] && cat_options[j]->toml_key && meta->toml_key && strcmp(cat_options[j]->toml_key, meta->toml_key) == 0) {
1403 is_duplicate = true;
1404 break;
1405 }
1406 }
1407 if (is_duplicate) {
1408 continue;
1409 }
1410
1411 // Get field pointer from default options (or mode-specific default if available)
1412 const char *field_ptr = ((const char *)&defaults) + meta->field_offset;
1413
1414 // Buffer to hold mode-specific default value if needed
1415 char mode_default_buffer[OPTIONS_BUFF_SIZE] = {0};
1416 int mode_default_int = 0;
1417
1418 // If this option has a mode_default_getter, use it to get the correct default
1419 if (meta->mode_default_getter) {
1420 asciichat_mode_t mode = extract_mode_from_bitmask(meta->mode_bitmask);
1421 if (mode != MODE_INVALID) {
1422 const void *default_value = meta->mode_default_getter(mode);
1423 if (default_value) {
1424 // Copy the default value to our buffer based on type
1425 if (meta->type == OPTION_TYPE_STRING || meta->type == OPTION_TYPE_CALLBACK) {
1426 const char *str_value = (const char *)default_value;
1427 SAFE_STRNCPY(mode_default_buffer, str_value, sizeof(mode_default_buffer));
1428 field_ptr = mode_default_buffer;
1429 } else if (meta->type == OPTION_TYPE_INT) {
1430 mode_default_int = *(const int *)default_value;
1431 field_ptr = (const char *)&mode_default_int;
1432 }
1433 }
1434 }
1435 }
1436
1437 // Add description comment if available
1438 if (meta->description && strlen(meta->description) > 0) {
1439 if (!config_builder_append(&builder, "# %s\n", meta->description)) {
1440 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1441 }
1442 }
1443
1444 // Format and add the option value using handler (commented out to avoid conflicts)
1445 if (g_type_handlers[meta->type].format_output) {
1446 char formatted_value[BUFFER_SIZE_MEDIUM] = {0};
1447 g_type_handlers[meta->type].format_output(field_ptr, meta->field_size, meta, formatted_value, sizeof(formatted_value));
1448 const char *output_key = meta->toml_key;
1449 size_t category_len = strlen(category);
1450 if (strncmp(meta->toml_key, category, category_len) == 0 && meta->toml_key[category_len] == '.') {
1451 output_key = meta->toml_key + category_len + 1; // Strip "<category>."
1452 }
1453
1454 if (config_key_should_be_commented(meta->toml_key)) {
1455 if (!config_builder_append(&builder, "# %s = %s\n", output_key, formatted_value)) {
1456 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1457 }
1458 } else {
1459 if (!config_builder_append(&builder, "%s = %s\n", output_key, formatted_value)) {
1460 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1461 }
1462 }
1463 }
1464
1465 // Add blank line after each option
1466 if (!config_builder_append(&builder, "\n")) {
1467 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1468 }
1469
1470 written_flags[opt_idx] = true;
1471 }
1472
1473 // Add blank line between sections (but not after the last section)
1474 if (cat_idx < category_count - 1) {
1475 if (!config_builder_append(&builder, "\n")) {
1476 return SET_ERRNO(ERROR_CONFIG, "Config too large to fit in buffer");
1477 }
1478 }
1479 }
1480
1481 // Now write the buffer to either stdout or a file
1482 if (config_path && strlen(config_path) > 0) {
1483 // User provided a filepath - write to that file with overwrite prompt
1484
1485 // Expand and validate the path
1486 config_path_expanded = expand_path(config_path);
1487 if (!config_path_expanded) {
1488 config_path_expanded = platform_strdup(config_path);
1489 }
1490
1491 if (!config_path_expanded) {
1492 return SET_ERRNO(ERROR_CONFIG, "Failed to resolve config file path");
1493 }
1494
1495 char *validated_config_path = NULL;
1496 asciichat_error_t validate_result = path_validate_user_path(config_path_expanded, PATH_ROLE_CONFIG_FILE, &validated_config_path);
1497 if (validate_result != ASCIICHAT_OK) {
1498 SAFE_FREE(validated_config_path);
1499 SAFE_FREE(config_path_expanded);
1500 return validate_result;
1501 }
1502 // Free the old path before reassigning (defer will free the new one)
1503 if (config_path_expanded != validated_config_path) {
1504 SAFE_FREE(config_path_expanded);
1505 }
1506 config_path_expanded = validated_config_path;
1507
1508 // Check if file already exists
1509 struct stat st;
1510 if (stat(config_path_expanded, &st) == 0) {
1511 // File exists - ask user if they want to overwrite
1512 log_plain("Config file already exists: %s", config_path_expanded);
1513
1515 safe_snprintf(question, sizeof(question), "File already exists: %s\n\nOverwrite", config_path_expanded);
1516 bool overwrite = ui_notice_confirm_kind(UI_PROMPT_CONFIG_OVERWRITE, UI_NOTICE_WARNING, question, 30); // Default to No
1517 if (!overwrite) {
1518 log_plain("Config file creation cancelled.");
1519 return SET_ERRNO(ERROR_CONFIG, "User cancelled overwrite");
1520 }
1521
1522 log_plain("Overwriting existing config file...");
1523 }
1524
1525 // Create directory if needed
1526 char *dir_path = platform_strdup(config_path_expanded);
1527 if (!dir_path) {
1528 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for directory path");
1529 }
1530 defer(SAFE_FREE(dir_path));
1531
1532 // Find the last path separator
1533 char *last_sep = strrchr(dir_path, PATH_DELIM);
1534
1535 if (last_sep) {
1536 *last_sep = '\0';
1537 // Create directory recursively
1538 asciichat_error_t mkdir_result = platform_mkdir_recursive(dir_path, DIR_PERM_PRIVATE);
1539 if (mkdir_result != ASCIICHAT_OK) {
1540 return mkdir_result;
1541 }
1542 }
1543
1544 // Open file for writing
1545 FILE *output_file = platform_fopen("file_stream", config_path_expanded, "w");
1546 if (!output_file) {
1547 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open config file for writing: %s", config_path_expanded);
1548 }
1549 defer(SAFE_FCLOSE(output_file));
1550
1551 // Write buffer to file
1552 size_t written = fwrite(builder.buffer, 1, builder.size, output_file);
1553 if (written != builder.size) {
1554 asciichat_error_t error = SET_ERRNO_SYS(ERROR_CONFIG, "Failed to write config to file: %s", config_path_expanded);
1555 SAFE_FCLOSE(output_file);
1556 return error;
1557 }
1558 // Publish buffered bytes before returning, including builds without defer instrumentation.
1559 int close_result = fclose(output_file);
1560 output_file = NULL;
1561 if (close_result != 0) {
1562 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to close config file: %s", config_path_expanded);
1563 }
1564 } else {
1565 // No filepath provided - write buffer to stdout with automatic retry on transient errors
1566 (void)platform_write_all(STDOUT_FILENO, builder.buffer, builder.size);
1567 // Flush C stdio buffer and terminal to ensure piped output is written immediately
1568 (void)fflush(stdout);
1569 (void)terminal_flush(STDOUT_FILENO);
1570 }
1571
1572 return ASCIICHAT_OK;
1573}
1574
1576 // Use platform abstraction to find all config.toml files across standard locations
1577 config_file_list_t config_files = {0};
1578 asciichat_error_t search_result = platform_find_config_file("config.toml", &config_files);
1579 defer(config_file_list_destroy(&config_files));
1580
1581 // Keep the application config authoritative even when an older platform
1582 // runtime is present. The explicit config path and generated config both
1583 // use this directory, so discovery must not silently fall back to the
1584 // generic "application" directory.
1585 if (search_result == ASCIICHAT_OK && config_files.count == 0) {
1586 char *config_dir = get_config_dir();
1587 if (config_dir) {
1588 size_t dir_len = strlen(config_dir);
1589 bool has_separator = dir_len > 0 && (config_dir[dir_len - 1] == '/' || config_dir[dir_len - 1] == '\\');
1590 size_t path_len = dir_len + (has_separator ? 0 : 1) + strlen("config.toml") + 1;
1591 char *path = SAFE_MALLOC(path_len, char *);
1592 if (path) {
1593 safe_snprintf(path, path_len, "%s%sconfig.toml", config_dir, has_separator ? "" : "\\");
1594 if (config_files.capacity > config_files.count) {
1595 config_file_result_t *file = &config_files.files[config_files.count++];
1596 file->path = path;
1597 file->priority = 0;
1598 file->exists = true;
1599 file->is_system_config = false;
1600 path = NULL;
1601 }
1602 SAFE_FREE(path);
1603 }
1604 SAFE_FREE(config_dir);
1605 }
1606 }
1607
1608 if (search_result != ASCIICHAT_OK) {
1609 CONFIG_DEBUG("Failed to search for config files: %d", search_result);
1610 return search_result;
1611 }
1612
1613 // Cascade load: Load all found configs in reverse order (lowest priority first)
1614 // This allows higher-priority configs to override lower-priority values.
1615 // Example: System configs load first, then user configs override them.
1616
1618 for (size_t i = config_files.count; i > 0; i--) {
1619 const config_file_result_t *file = &config_files.files[i - 1];
1620
1621 // Determine strictness based on whether this is a system or user config
1622 // System configs are non-strict (values can be missing, errors are non-fatal)
1623 // User config is strict or non-strict based on parameter
1624 bool is_user_config = !file->is_system_config;
1625 bool file_strict = is_user_config ? strict : false;
1626
1627 CONFIG_DEBUG("Loading config from %s (system=%s, strict=%s)", file->path, file->is_system_config ? "yes" : "no", file_strict ? OPT_VALUE_TRUE : OPT_VALUE_FALSE);
1628
1630 asciichat_error_t load_result = config_load_and_apply(detected_mode, file->path, file_strict, opts);
1631
1632 if (load_result != ASCIICHAT_OK) {
1633 if (file_strict) {
1634 // Strict mode: errors are fatal
1635 CONFIG_DEBUG("Strict config loading failed for %s", file->path);
1636 result = load_result;
1637 } else {
1638 // Non-strict mode: errors are non-fatal, just log and continue
1639 CONFIG_DEBUG("Non-strict config loading warning for %s: %d (continuing)", file->path, load_result);
1641 ASSERT_NO_ERRNO_SINCE(load_scope);
1642 }
1643 } else {
1644 ASSERT_NO_ERRNO_SINCE(load_scope);
1646 }
1647 }
1648
1649 return result;
1650}
bool errno_peek_since(asciichat_errno_scope_t scope, asciichat_error_context_t *out)
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_checkpoint(void)
asciichat_errno_scope_t errno_scope_begin(void)
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
#define ASSERT_NO_ERRNO_SINCE(scope)
@ ASCIICHAT_ERRNO_HANDLED
@ ASCIICHAT_ERRNO_DISMISSED
@ OPTION_TYPE_INT
Integer value (–count 42).
Definition builder.h:182
@ OPTION_TYPE_DOUBLE
Floating point (–ratio 1.5).
Definition builder.h:184
@ OPTION_TYPE_STRING
String value (–name foo).
Definition builder.h:183
@ OPTION_TYPE_ACTION
Definition builder.h:186
@ OPTION_TYPE_CALLBACK
Custom parser function.
Definition builder.h:185
@ OPTION_TYPE_BOOL
Boolean flag (–flag, no value).
Definition builder.h:181
void options_config_destroy(options_config_t *config)
Free options config.
Option enum value definitions - single source of truth.
#define OPT_VALUE_FALSE
Definition enums.h:84
#define OPT_RENDER_MODE_FOREGROUND
Definition enums.h:133
#define OPT_RENDER_MODE_HALF_BLOCK
Definition enums.h:137
#define OPT_COLOR_MODE_256
Definition enums.h:106
#define OPT_VALUE_TRUE
Definition enums.h:83
#define OPT_COLOR_MODE_NONE
Definition enums.h:103
#define OPT_COLOR_FILTER_NONE
Definition enums.h:110
#define OPT_VALUE_AUTO
Definition enums.h:82
#define OPT_COLOR_MODE_TRUECOLOR
Definition enums.h:107
#define OPT_RENDER_MODE_BACKGROUND
Definition enums.h:135
#define OPT_COLOR_MODE_16
Definition enums.h:105
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
Error and exit codes - unified status values (0-255).
int color_mode
Definition fft.c:26
unsigned int height
Definition fft.c:24
terminal_render_mode_t render_mode
Definition fft.c:27
unsigned int width
Definition fft.c:24
int platform_mkdir_recursive(const char *path, int mode)
Definition filesystem.c:36
int platform_find_config_file(const char *filename, config_file_list_t *list_out)
Definition filesystem.c:42
int platform_access(const char *pathname, int mode)
Definition filesystem.c:95
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
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define SAFE_CALLOC(count, size, cast)
#define SAFE_FCLOSE(fp)
asciichat_error_t config_load_system_and_user(asciichat_mode_t detected_mode, bool strict, options_t *opts)
Load system config first, then user config (user config overrides system).
asciichat_error_t config_load_and_apply(asciichat_mode_t detected_mode, const char *config_path, bool strict, options_t *opts)
Main function to load configuration from file and apply to global options.
asciichat_error_t config_create_default(const char *config_path)
Create default configuration file with all default values.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
bool log_get_terminal_output(void)
Get current terminal output setting.
Definition log/log.c:836
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:663
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:635
#define COLOR_MODE_16_COLOR
16-color mode (full name)
Definition options.h:226
#define COLOR_MODE_256_COLOR
256-color mode (full name)
Definition options.h:228
#define COLOR_MODE_TRUECOLOR
24-bit truecolor mode
Definition options.h:229
int validate_opt_render_mode(const char *value_str, char *error_msg, size_t error_msg_size)
Validate render mode string.
Definition validation.c:180
asciichat_mode_t
Mode type for options parsing.
Definition options.h:916
#define COLOR_MODE_AUTO
Backward compatibility aliases for color mode enum values.
Definition options.h:223
int validate_opt_color_mode(const char *value_str, char *error_msg, size_t error_msg_size)
Validate color mode string.
Definition validation.c:147
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
int validate_opt_palette(const char *value_str, char *error_msg, size_t error_msg_size)
Validate palette type string.
Definition validation.c:207
#define OPTIONS_BUFF_SIZE
Buffer size for option string values.
Definition options.h:305
option_mode_bitmask_t
Option mode bitmask.
Definition options.h:933
#define COLOR_MODE_NONE
Monochrome mode.
Definition options.h:224
options_t options_t_new(void)
Initialize options by parsing command-line arguments.
Definition options.c:688
@ MODE_CLIENT
Client mode - network client options.
Definition options.h:918
@ MODE_MCP_SERVER
Model Context Protocol rendering server.
Definition options.h:922
@ MODE_DISCOVERY_SERVICE
Discovery server mode - session management and WebRTC signaling.
Definition options.h:920
@ MODE_API_SERVER
Image-to-ASCII HTTP API server.
Definition options.h:923
@ MODE_INVALID
Invalid mode.
Definition options.h:924
@ MODE_SERVER
Server mode - network server options.
Definition options.h:917
@ MODE_MIRROR
Mirror mode - local webcam viewing (no network).
Definition options.h:919
@ MODE_DISCOVERY
Discovery mode - participant that can dynamically become host.
Definition options.h:921
@ OPTION_MODE_BINARY
Binary-level options (parsed before mode detection).
Definition options.h:942
@ OPTION_MODE_CLIENT
Client mode (bit 1).
Definition options.h:936
@ OPTION_MODE_API_SERVER
Definition options.h:941
@ OPTION_MODE_DISCOVERY
Discovery mode (bit 4).
Definition options.h:939
@ OPTION_MODE_SERVER
Server mode (bit 0).
Definition options.h:935
@ OPTION_MODE_MIRROR
Mirror mode (bit 2).
Definition options.h:937
@ OPTION_MODE_MCP_SERVER
Definition options.h:940
@ OPTION_MODE_DISCOVERY_SVC
Discovery server mode (bit 3).
Definition options.h:938
@ PALETTE_COUNT
Number of palette types (not a valid palette).
Definition palette.h:112
@ PALETTE_CUSTOM
User-defined via –palette-chars.
Definition palette.h:110
@ PALETTE_STANDARD
Standard ASCII palette: " ...',;:clodxkO0KXNWM".
Definition palette.h:100
bool path_looks_like_path(const char *value)
Determine if a string is likely intended to reference the filesystem.
Definition path.c:518
bool utf8_is_valid(const char *str)
Check if a string is valid UTF-8.
Definition utf8.c:132
path_role_t
Classification for user-supplied filesystem paths.
Definition path.h:343
asciichat_error_t path_validate_user_path(const char *input, path_role_t role, char **normalized_out)
Validate and canonicalize a user-supplied filesystem path.
Definition path.c:739
char * expand_path(const char *path)
Expand path with tilde (~) support.
Definition path.c:270
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:293
@ PATH_ROLE_CONFIG_FILE
Definition path.h:344
@ PATH_ROLE_KEY_PUBLIC
Definition path.h:347
@ PATH_ROLE_LOG_FILE
Definition path.h:345
@ PATH_ROLE_KEY_PRIVATE
Definition path.h:346
color_filter_t color_filter_from_cli_name(const char *cli_name)
Convert color filter CLI name to enum value.
const color_filter_def_t * color_filter_get_metadata(color_filter_t filter)
Get color filter metadata by enum value.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 Logging API with multiple log levels and terminal output control
bool ui_notice_confirm_kind(ui_prompt_kind_t kind, ui_notice_severity_t severity, const char *text, unsigned timeout_seconds)
Definition notice.c:548
@ UI_NOTICE_WARNING
Definition notice.h:15
#define CONFIG_CATEGORY_CAPACITY
#define CONFIG_WRITTEN_FLAG_CAPACITY
#define CONFIG_DEBUG(fmt,...)
Print configuration debug message.
#define CONFIG_WARN(fmt,...)
Print configuration warning using the logging system.
#define OPTIONS_CONFIG_QUESTION_BUFFER_SIZE
TOML configuration file support for ascii-chat.
action_args_t args
Validation functions for options parsing.
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
ASCII Palette Management for Video-to-ASCII Conversion.
📂 Path Manipulation Utilities
options_config_t * options_preset_unified(const char *program_name, const char *description)
Build unified options config with ALL options (binary + all modes).
Definition presets.c:58
asciichat_error_t options_state_set(const options_t *opts)
Set options from a parsed options struct.
Definition rcu.c:459
const config_option_metadata_t ** config_schema_get_by_category(const char *category, size_t *count)
Get all option metadata for a category.
Definition schema.c:414
const config_option_metadata_t * config_schema_get_all(size_t *count)
Get all option metadata.
Definition schema.c:447
asciichat_error_t config_schema_build_from_configs(const options_config_t **configs, size_t num_configs)
Build schema dynamically from options builder configs.
Definition schema.c:250
Schema metadata for config file options.
char * platform_strdup(const char *s)
int terminal_flush(int fd)
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
For color filter def, this is the live record that ties name, cli_name, r, g together....
const char * cli_name
CLI argument name (e.g., "matrix-green").
Helper structure for building config content in a buffer.
Option metadata for config file parsing.
Definition schema.h:53
option_type_t type
Value type (from builder).
Definition schema.h:58
size_t field_size
Size of field in options_t.
Definition schema.h:62
bool(* parse_fn)(const char *arg, void *dest, char **error_msg)
Custom parser for callbacks (or NULL).
Definition schema.h:69
struct config_option_metadata_t::@047245164140222033316365214353336112047172131121::@271224077242344302200333333005050320172070077212 int_range
option_mode_bitmask_t mode_bitmask
Which modes this option applies to.
Definition schema.h:73
const void *(* mode_default_getter)(asciichat_mode_t mode)
Get mode-specific default value (NULL if not mode-aware).
Definition schema.h:91
size_t field_offset
offsetof(options_t, field) - where to store value
Definition schema.h:61
const char * description
Description for docs/help generation.
Definition schema.h:76
const char * category
Category name (e.g., "network", "client", "audio").
Definition schema.h:60
builder_validate_fn_t validate_fn
Definition schema.h:65
const char * toml_key
TOML key path (e.g., "network.port", "client.address").
Definition schema.h:55
union config_option_metadata_t::@047245164140222033316365214353336112047172131121 constraints
Function table for extracting, validating, storing, and formatting one TOML option type.
void(* format_output)(const char *field_ptr, size_t field_size, const config_option_metadata_t *meta, char *buf, size_t bufsize)
Format for TOML output.
void(* extract)(toml_datum_t datum, char *value_str, int *int_val, bool *bool_val, double *double_val, bool *has_value)
Extract value from TOML datum.
asciichat_error_t(* parse_validate)(const char *value_str, const config_option_metadata_t *meta, option_parsed_value_t *parsed, char *error_msg, size_t error_size)
Parse and validate value.
asciichat_error_t(* write_to_struct)(const option_parsed_value_t *parsed, const config_option_metadata_t *meta, options_t *opts, char *error_msg, size_t error_size)
Write to options struct.
Immutable parsing tables produced from an options builder.
Definition builder.h:456
bool flip_x_explicit
User selected an orientation for this process lifetime.
Definition options.h:1096
int test_pattern_index
Synthetic pattern selector (0 or 1).
Definition options.h:1064
bool palette_explicit
Palette explicitly selected.
Definition options.h:1223
bool no_encrypt
Disable encryption (opt-out).
Definition options.h:1175
char palette_custom[256]
Custom palette characters.
Definition options.h:1221
bool palette_custom_set
True if custom palette was set.
Definition options.h:1222
bool test_pattern
Use test pattern instead of webcam.
Definition options.h:1063
palette_type_t palette_type
Selected palette type.
Definition options.h:1220
test pattern is intentionally a small, concrete record. Fields such as image, rgba give callers the i...
Scratch storage for the scalar value produced while parsing one option.
🔤 UTF-8 Encoding and Decoding Utilities
@ ASCII_RENDERER_GLYPH