ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
schema.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_SCHEMA_CLI_FLAG_BUFFER_SIZE 256
9#define OPTIONS_CONFIG_SCHEMA_CATEGORY_BUFFER_SIZE 64
10
11/* Existing buffer budgets in bytes, including NUL for text storage. */
12#define SCHEMA_OPTION_CAPACITY 256
13#define SCHEMA_CATEGORY_OPTION_CAPACITY 64
14
15/* Existing buffer budgets in bytes, including NUL for text storage. */
16#define SCHEMA_INITIAL_STRING_CAPACITY 64
17
25#include <libplatform/terminal.h>
26#include <libplatform/system.h>
27#include <ascii-chat/common.h>
28
29#include <string.h>
30#include <limits.h>
31#include <ctype.h>
32
33// ============================================================================
34// Option Metadata Registry
35// ============================================================================
36// Schema is now built dynamically from options builder configs.
37// See config_schema_build_from_configs() below.
38
39// ============================================================================
40// Dynamic Schema Storage
41// ============================================================================
42
43static config_option_metadata_t *g_dynamic_schema = NULL;
44static size_t g_dynamic_schema_count = 0;
45static bool g_schema_built = false;
46static char **g_dynamic_strings = NULL; // Storage for allocated strings (toml_key, cli_flag, category)
47static size_t g_dynamic_strings_count = 0;
48static size_t g_dynamic_strings_capacity = 0;
49
50// ============================================================================
51// Helper Functions for Dynamic Schema Building
52// ============================================================================
53
57static void str_tolower(char *str) {
58 if (!str) {
59 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid string");
60 return;
61 }
62 for (; *str; str++) {
63 *str = (char)tolower((unsigned char)*str);
64 }
65}
66
70static void dashes_to_underscores(char *str) {
71 if (!str) {
72 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid string");
73 return;
74 }
75 for (; *str; str++) {
76 if (*str == '-') {
77 *str = '_';
78 }
79 }
80}
81
86static char *generate_toml_key(const char *group, const char *field_name, char *buffer, size_t buffer_size) {
87 if (!group || !field_name || !buffer || buffer_size == 0) {
88 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
89 return NULL;
90 }
91
92 // Copy group and convert to lowercase
93 size_t group_len = strlen(group);
94 if (group_len >= buffer_size) {
95 SET_ERRNO(ERROR_CONFIG, "Group name is too long for buffer");
96 return NULL;
97 }
98 memcpy(buffer, group, group_len + 1);
99 str_tolower(buffer);
100
101 // Append dot
102 if (group_len + 1 >= buffer_size) {
103 SET_ERRNO(ERROR_CONFIG, "Group name is too long for buffer");
104 return NULL;
105 }
106 buffer[group_len] = '.';
107
108 // Copy field name, convert dashes to underscores, and lowercase
109 size_t field_len = strlen(field_name);
110 if (group_len + 1 + field_len >= buffer_size) {
111 SET_ERRNO(ERROR_INVALID_STATE, "Field name is too long for buffer");
112 return NULL;
113 }
114 memcpy(buffer + group_len + 1, field_name, field_len + 1);
115 dashes_to_underscores(buffer + group_len + 1);
116 str_tolower(buffer + group_len + 1);
117
118 return buffer;
119}
120
125static char *generate_cli_flag(const char *long_name, char *buffer, size_t buffer_size) {
126 if (!long_name || !buffer || buffer_size < 3) { // Need at least "--" + 1 char
127 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
128 return NULL;
129 }
130
131 buffer[0] = '-';
132 buffer[1] = '-';
133 size_t name_len = strlen(long_name);
134 if (name_len + 2 >= buffer_size) {
135 SET_ERRNO(ERROR_CONFIG, "Long name is too long for buffer");
136 return NULL;
137 }
138 memcpy(buffer + 2, long_name, name_len + 1);
139 return buffer;
140}
141
145static size_t get_field_size(option_type_t type, size_t offset) {
146 // We can't determine field size from offset alone, so we'll use sizeof() on a dummy struct
147 // For now, use reasonable defaults based on type
148 switch (type) {
149 case OPTION_TYPE_BOOL:
150 return sizeof(bool);
151 case OPTION_TYPE_INT:
152 // Check if this is an unsigned short int field
153 if (offset == offsetof(options_t, webcam_index)) {
154 return sizeof(unsigned short int);
155 }
156 // Check if this is an enum field by offset
157 if (offset == offsetof(options_t, color_mode)) {
158 return sizeof(terminal_color_mode_t);
159 } else if (offset == offsetof(options_t, render_mode)) {
160 return sizeof(terminal_render_mode_t);
161 } else if (offset == offsetof(options_t, palette_type)) {
162 return sizeof(palette_type_t);
163 }
164 return sizeof(int);
166 // Check if this is a float field instead of double
167 if (offset == offsetof(options_t, microphone_sensitivity) || offset == offsetof(options_t, speakers_volume)) {
168 return sizeof(float);
169 }
170 // Check field_size at runtime to distinguish float from double
171 // For now, return double size (will be checked when writing)
172 return sizeof(double);
174 // String fields are typically OPTIONS_BUFF_SIZE
175 return OPTIONS_BUFF_SIZE;
177 // CALLBACK options store into regular options_t fields; infer by offset.
178 if (offset == offsetof(options_t, log_file) || offset == offsetof(options_t, port) || offset == offsetof(options_t, palette_custom) || offset == offsetof(options_t, yt_dlp_options)) {
179 return OPTIONS_BUFF_SIZE;
180 }
181 if (offset == offsetof(options_t, media_seek_timestamp)) {
182 return sizeof(double);
183 }
184 if (offset == offsetof(options_t, microphone_sensitivity) || offset == offsetof(options_t, speakers_volume)) {
185 return sizeof(float);
186 }
187 if (offset == offsetof(options_t, verbose_level)) {
188 return sizeof(unsigned short int);
189 }
190 return sizeof(int);
191 default:
192 return sizeof(int); // Safe default
193 }
194}
195
196// Validation wrapper functions removed - we use builder's validate functions directly
197
198// ============================================================================
199// Dynamic Schema Building
200// ============================================================================
201
205static bool should_add_descriptor(const option_descriptor_t *desc, const option_descriptor_t **existing, size_t count) {
206 if (!desc || desc->type == OPTION_TYPE_ACTION) {
207 return false; // Skip actions (not an error, just filtering)
208 }
209
210 // Check if we already have this exact offset
211 for (size_t i = 0; i < count; i++) {
212 if (existing[i] && existing[i]->offset == desc->offset) {
213 return false; // Already have this offset
214 }
215 }
216 return true;
217}
218
222static char *store_dynamic_string(const char *str) {
223 if (!str) {
224 return NULL;
225 }
226
227 // Grow string storage if needed
228 if (g_dynamic_strings_count >= g_dynamic_strings_capacity) {
229 size_t new_capacity = g_dynamic_strings_capacity == 0 ? SCHEMA_INITIAL_STRING_CAPACITY : g_dynamic_strings_capacity * 2;
230 char **new_strings = SAFE_REALLOC(g_dynamic_strings, new_capacity * sizeof(char *), char **);
231 if (!new_strings) {
232 SET_ERRNO(ERROR_MEMORY, "Failed to allocate new strings");
233 return NULL;
234 }
235 g_dynamic_strings = new_strings;
236 g_dynamic_strings_capacity = new_capacity;
237 }
238
239 // Allocate and copy the string
240 char *stored = platform_strdup(str);
241 if (!stored) {
242 SET_ERRNO(ERROR_MEMORY, "Failed to allocate new string");
243 return NULL;
244 }
245
246 g_dynamic_strings[g_dynamic_strings_count++] = stored;
247 return stored;
248}
249
251 // Free existing dynamic schema if any
252 if (g_dynamic_schema) {
253 SAFE_FREE(g_dynamic_schema);
254 g_dynamic_schema = NULL;
255 g_dynamic_schema_count = 0;
256 }
257
258 // Free existing string storage
259 if (g_dynamic_strings) {
260 for (size_t i = 0; i < g_dynamic_strings_count; i++) {
261 SAFE_FREE(g_dynamic_strings[i]);
262 }
263 SAFE_FREE(g_dynamic_strings);
264 g_dynamic_strings = NULL;
265 g_dynamic_strings_count = 0;
266 g_dynamic_strings_capacity = 0;
267 }
268
269 // Count total unique descriptors (by offset) across all configs
270 // Use a simple approach: collect all descriptors, then deduplicate by offset
271 const option_descriptor_t *all_descriptors[SCHEMA_OPTION_CAPACITY] = {0}; // Max expected options
272 size_t descriptor_count = 0;
273
274 // Collect descriptors from all configs
275 for (size_t cfg_idx = 0; cfg_idx < num_configs; cfg_idx++) {
276 const options_config_t *config = configs[cfg_idx];
277 if (!config) {
278 log_debug("Config %zu is NULL, skipping", cfg_idx);
279 continue;
280 }
281
282 if (!config->descriptors || config->num_descriptors == 0) {
283 log_debug("Config %zu has no descriptors", cfg_idx);
284 continue;
285 }
286
287 for (size_t i = 0; i < config->num_descriptors && descriptor_count < SCHEMA_OPTION_CAPACITY; i++) {
288 const option_descriptor_t *desc = &config->descriptors[i];
289 if (!desc) {
290 log_warn("Descriptor at index %zu in config %zu is NULL", i, cfg_idx);
291 continue;
292 }
293 if (should_add_descriptor(desc, all_descriptors, descriptor_count)) {
294 all_descriptors[descriptor_count++] = desc;
295 }
296 }
297 }
298
299 // Allocate schema array
300 g_dynamic_schema = SAFE_MALLOC(descriptor_count * sizeof(config_option_metadata_t), config_option_metadata_t *);
301 if (!g_dynamic_schema) {
302 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate dynamic schema");
303 }
304
305 // Build schema entries
306 g_dynamic_schema_count = 0;
307 char toml_key_buffer[BUFFER_SIZE_SMALL];
308 char cli_flag_buffer[OPTIONS_CONFIG_SCHEMA_CLI_FLAG_BUFFER_SIZE];
309 char category_buffer[OPTIONS_CONFIG_SCHEMA_CATEGORY_BUFFER_SIZE];
310
311 for (size_t i = 0; i < descriptor_count; i++) {
312 const option_descriptor_t *desc = all_descriptors[i];
313 if (!desc || !desc->long_name || !desc->group) {
314 continue;
315 }
316
317 config_option_metadata_t *meta = &g_dynamic_schema[g_dynamic_schema_count++];
318 // Zero-initialize the metadata struct to ensure all fields are initialized
319 memset(meta, 0, sizeof(*meta));
320
321 // Use builder's type directly
322 meta->type = desc->type;
323
324 // Generate category: lowercase the group name from builder
325 SAFE_STRNCPY(category_buffer, desc->group, sizeof(category_buffer) - 1);
326 category_buffer[sizeof(category_buffer) - 1] = '\0';
327 str_tolower(category_buffer);
328
329 // Generate TOML key: "category.field_name" (category is lowercase group, field_name is long_name with
330 // dashes->underscores)
331 const char *field_name = desc->long_name;
332 if (strcmp(category_buffer, "otel") == 0 && strncmp(field_name, "otel-", 5) == 0)
333 field_name += 5;
334 if (!generate_toml_key(category_buffer, field_name, toml_key_buffer, sizeof(toml_key_buffer))) {
335 g_dynamic_schema_count--; // Skip this entry
336 continue;
337 }
338
339 // Store generated strings (allocate and store)
340 meta->toml_key = store_dynamic_string(toml_key_buffer);
341 meta->category = store_dynamic_string(category_buffer);
342 if (!meta->toml_key || !meta->category) {
343 // Failed to allocate strings, skip this entry
344 g_dynamic_schema_count--;
345 continue;
346 }
347
348 // Generate CLI flag: "--long-name"
349 if (generate_cli_flag(desc->long_name, cli_flag_buffer, sizeof(cli_flag_buffer))) {
350 meta->cli_flag = store_dynamic_string(cli_flag_buffer);
351 if (!meta->cli_flag) {
352 // Failed to allocate, but continue (cli_flag can be NULL)
353 }
354 } else {
355 meta->cli_flag = NULL;
356 }
357
358 // Set other fields
359 meta->context = OPTION_CONTEXT_BOTH; // Most options can appear in both CLI and config
360 meta->field_offset = desc->offset;
361 meta->field_size = get_field_size(meta->type, desc->offset);
362 // Use builder's validate function directly - it receives the full options struct
363 meta->validate_fn = desc->validate;
364 // Use builder's parse function for CALLBACK types
365 meta->parse_fn = desc->parse_fn;
366 meta->description = desc->help_text;
367
368 // Set mode_bitmask from option descriptor
369 // The descriptor should have mode_bitmask set from the registry
370 meta->mode_bitmask = desc->mode_bitmask;
371
372 // Copy mode_default_getter function pointer
374
375 // Copy constraints from descriptor's metadata
376 // For integer types, copy numeric_range to int_range (always copy, even if min is 0)
377 memset(&meta->constraints, 0, sizeof(meta->constraints));
378 // Always copy numeric_range if descriptor has it (check max or min)
379 if (desc && desc->metadata.numeric_range.max > 0) {
382 }
383 }
384
385 g_schema_built = true;
386 return ASCIICHAT_OK;
387}
388
389// ============================================================================
390// Lookup Functions
391// ============================================================================
392
394 if (!toml_key) {
395 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
396 return NULL;
397 }
398
399 // Schema must be built before use
400 if (!g_schema_built || !g_dynamic_schema) {
401 SET_ERRNO(ERROR_INVALID_STATE, "Schema not built");
402 return NULL;
403 }
404
405 for (size_t i = 0; i < g_dynamic_schema_count; i++) {
406 if (g_dynamic_schema[i].toml_key && strcmp(g_dynamic_schema[i].toml_key, toml_key) == 0) {
407 return &g_dynamic_schema[i];
408 }
409 }
410
411 return NULL;
412}
413
414const config_option_metadata_t **config_schema_get_by_category(const char *category, size_t *count) {
415 static const config_option_metadata_t *results[SCHEMA_CATEGORY_OPTION_CAPACITY]; // Max options per category
416 size_t result_count = 0;
417
418 if (!category) {
419 if (count) {
420 *count = 0;
421 }
422 return NULL;
423 }
424
425 // Schema must be built before use
426 if (!g_schema_built || !g_dynamic_schema) {
427 if (count) {
428 *count = 0;
429 }
430 SET_ERRNO(ERROR_INVALID_STATE, "Schema not built");
431 return NULL;
432 }
433
434 for (size_t i = 0; i < g_dynamic_schema_count && result_count < SCHEMA_CATEGORY_OPTION_CAPACITY; i++) {
435 if (g_dynamic_schema[i].category && strcmp(g_dynamic_schema[i].category, category) == 0) {
436 results[result_count++] = &g_dynamic_schema[i];
437 }
438 }
439
440 if (count) {
441 *count = result_count;
442 }
443
444 return (result_count > 0) ? results : NULL;
445}
446
448 // Schema must be built before use
449 if (!g_schema_built || !g_dynamic_schema) {
450 if (count) {
451 *count = 0;
452 }
453 SET_ERRNO(ERROR_INVALID_STATE, "Schema not built");
454 return NULL;
455 }
456
457 if (count) {
458 *count = g_dynamic_schema_count;
459 }
460 return g_dynamic_schema;
461}
462
463// ============================================================================
464// Schema Cleanup
465// ============================================================================
466
468 if (!g_schema_built) {
469 return; // Nothing to clean up
470 }
471
472 // Free all dynamically allocated strings (toml_key, cli_flag, category)
473 if (g_dynamic_strings) {
474 for (size_t i = 0; i < g_dynamic_strings_count; i++) {
475 SAFE_FREE(g_dynamic_strings[i]);
476 }
477 SAFE_FREE(g_dynamic_strings);
478 g_dynamic_strings = NULL;
479 g_dynamic_strings_count = 0;
480 g_dynamic_strings_capacity = 0;
481 }
482
483 // Free the schema array itself
484 if (g_dynamic_schema) {
485 SAFE_FREE(g_dynamic_schema);
486 g_dynamic_schema = NULL;
487 g_dynamic_schema_count = 0;
488 }
489
490 g_schema_built = false;
491}
#define SET_ERRNO(code,...)
Options builder API for flexible command-line option configuration.
option_type_t
Custom help section descriptor.
Definition builder.h:180
@ 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
int color_mode
Definition fft.c:26
terminal_render_mode_t render_mode
Definition fft.c:27
int buffer_size
Size of circular buffer.
Definition grep.c:69
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define SAFE_REALLOC(ptr, size, cast)
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ 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
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:663
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
#define OPTIONS_BUFF_SIZE
Buffer size for option string values.
Definition options.h:305
palette_type_t
Built-in palette type enumeration.
Definition palette.h:96
⚙️ Common definitions, error codes, macros, and types shared throughout the application
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
Preset option configurations for ascii-chat modes.
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
#define SCHEMA_CATEGORY_OPTION_CAPACITY
Definition schema.c:13
void config_schema_destroy(void)
Clean up dynamically allocated schema resources.
Definition schema.c:467
#define OPTIONS_CONFIG_SCHEMA_CLI_FLAG_BUFFER_SIZE
Definition schema.c:8
#define OPTIONS_CONFIG_SCHEMA_CATEGORY_BUFFER_SIZE
Definition schema.c:9
const config_option_metadata_t * config_schema_get_all(size_t *count)
Get all option metadata.
Definition schema.c:447
#define SCHEMA_OPTION_CAPACITY
Definition schema.c:12
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
const config_option_metadata_t * config_schema_get_by_toml_key(const char *toml_key)
Get option metadata by TOML key.
Definition schema.c:393
#define SCHEMA_INITIAL_STRING_CAPACITY
Definition schema.c:16
Schema metadata for config file options.
@ OPTION_CONTEXT_BOTH
Can appear in both CLI and config.
Definition schema.h:32
char * platform_strdup(const char *s)
🔤 String Manipulation and Shell Escaping Utilities
Option metadata for config file parsing.
Definition schema.h:53
option_context_t context
Where this option can appear.
Definition schema.h:59
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
const char * cli_flag
CLI flag name (e.g., "--port") or NULL if no CLI flag.
Definition schema.h:57
union config_option_metadata_t::@047245164140222033316365214353336112047172131121 constraints
The complete registry entry for one command-line/configuration option.
Definition builder.h:271
option_mode_bitmask_t mode_bitmask
Which modes this option applies to.
Definition builder.h:313
const char * help_text
Description for –help.
Definition builder.h:281
size_t offset
offsetof(struct, field) - where to store value
Definition builder.h:278
const char * group
Group name for help sections (e.g., "NETWORK OPTIONS").
Definition builder.h:282
bool(* parse_fn)(const char *arg, void *dest, char **error_msg)
Definition builder.h:300
bool(* validate)(const void *options_struct)
Definition builder.h:297
const char * long_name
Long option name (e.g., "port").
Definition builder.h:273
const void *(* mode_default_getter)(asciichat_mode_t mode)
Get mode-specific default value (NULL if not mode-aware).
Definition builder.h:320
option_metadata_t metadata
Definition builder.h:316
option_type_t type
Value type.
Definition builder.h:277
int max
Maximum value (or 0 if no limit).
Definition builder.h:227
int min
Minimum value (or 0 if no limit).
Definition builder.h:226
struct option_metadata_t::@061372117173071240020206164036331043262170062306 numeric_range
Immutable parsing tables produced from an options builder.
Definition builder.h:456
option_descriptor_t * descriptors
Array of option descriptors.
Definition builder.h:457
size_t num_descriptors
Number of descriptors.
Definition builder.h:458