ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
main.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define MAIN_LOG_OUT_BUFFER_SIZE 64
4#define MAIN_JSON_FILENAME_BUFFER_SIZE 256
5
6#include <ascii-chat/otel.h>
31
34
36#include <stdio.h>
37#include <unistd.h>
38#include <stdlib.h>
39#include <string.h>
40#include <stdbool.h>
41#include <signal.h>
42
43// Mode-specific entry points
44#include "server/main.h"
45#include "client/main.h"
46#include "mirror/main.h"
47#include "mcp-server/mcp.h"
48#include "api-server/main.h"
49#include <options/registry/core.h>
51#include "discovery/main.h"
53
54// Global exit API (exported in main.h)
55#include "main.h"
56
57// Application callbacks for library integration
59
60// Keyboard help UI
62
63// Utilities
65#include <ascii-chat/util/env.h>
68
69// Common headers for version info and initialization
70#include <libplatform/atomic.h>
71#include <ascii-chat/common.h>
72#include <libplatform/systemd.h>
74#include <ascii-chat/version.h>
75#include <options/options.h>
76#include <libplatform/system.h>
77#include <libplatform/thread.h>
79#include <options/common.h>
80#include <options/rcu.h>
81#include <options/actions.h>
82#include <options/colorscheme.h>
83#include <ascii-chat/log/log.h>
84#include <ascii-chat/log/json.h>
85#include <ascii-chat/log/grep.h>
86#include <libplatform/terminal.h>
87#include <libplatform/question.h>
88#include <libplatform/process.h>
91#include <options/colorscheme.h>
97#include <libplatform/thread.h>
98
99#ifndef NDEBUG
106#endif
107
108#ifndef _WIN32
109#include <signal.h>
110#endif
111
112/* ============================================================================
113 * Constants and Configuration
114 * ============================================================================ */
115
116#define APP_NAME "ascii-chat"
117#define VERSION ASCII_CHAT_VERSION_FULL
118
119static void app_question_error(const char *prompt) {
120 log_error("Cannot answer prompt without an interactive terminal: %s", prompt ? prompt : "(null)");
121}
122
123static void app_question_usage(const char *kind, const char *result) {
124 ascii_otel_ui_usage(kind ? kind : "confirmation", result ? result : "declined", 0);
125}
126
127/* ============================================================================
128 * Default Log File Path Determination
129 * ============================================================================ */
130
137static int platform_question_input_adapter(const char *prompt, char *buffer, size_t max_len, prompt_opts_t opts) {
138 return ui_input_prompt(prompt, buffer, max_len, opts) == ASCIICHAT_OK ? 0 : -1;
139}
140
141static const char *get_mode_log_filename(asciichat_mode_t mode) {
142 switch (mode) {
143 case MODE_SERVER:
144 return "server.log";
145 case MODE_CLIENT:
146 return "client.log";
147 case MODE_MIRROR:
148 return "mirror.log";
149 case MODE_MCP_SERVER:
150 return "mcp-server.log";
151 case MODE_API_SERVER:
152 return "api-server.log";
154 return "acds.log";
155 case MODE_DISCOVERY:
156 return "discovery.log";
157 case MODE_INVALID:
158 default:
159 return "ascii-chat.log";
160 }
161}
162
173static void generate_default_log_path(asciichat_mode_t mode, char *buf, size_t buf_size) {
174 if (!buf || buf_size == 0) {
175 return;
176 }
177
178 // Get mode-specific log filename
179 const char *log_filename = get_mode_log_filename(mode);
180
181#ifndef NDEBUG
182 // Debug mode: use current working directory
183 SAFE_STRNCPY(buf, log_filename, buf_size - 1);
184#else
185 // Non-debug mode: use system temp directory
186#ifdef _WIN32
187 const char *temp_dir = SAFE_GETENV("TEMP");
188 if (!temp_dir) {
189 temp_dir = SAFE_GETENV("TMP");
190 }
191 if (!temp_dir) {
192 temp_dir = SAFE_GETENV("USERPROFILE");
193 }
194 if (!temp_dir) {
195 temp_dir = ".";
196 }
197 safe_snprintf(buf, buf_size, "%s\\ascii-chat\\%s", temp_dir, log_filename);
198#else
199 safe_snprintf(buf, buf_size, "/tmp/ascii-chat/%s", log_filename);
200#endif
201 // Create directory if it doesn't exist (non-debug mode only)
202 char dir_path[PATH_MAX];
203 SAFE_STRNCPY(dir_path, buf, sizeof(dir_path) - 1);
204 char *last_slash = strrchr(dir_path, '/');
205#ifdef _WIN32
206 char *last_backslash = strrchr(dir_path, '\\');
207 if (last_backslash && (!last_slash || last_backslash > last_slash)) {
208 last_slash = last_backslash;
209 }
210#endif
211 if (last_slash) {
212 *last_slash = '\0';
213 platform_mkdir_recursive(dir_path, 0700);
214 }
215#endif
216}
217
218/* ============================================================================
219 * Global Application Exit State (Centralized Signal Handling)
220 * ============================================================================ */
221
224
225// Register with descriptive name for debug output
226#ifndef NDEBUG
227#define REGISTER_GLOBAL_ATOMICS() \
228 do { \
229 static bool _global_atomics_registered = false; \
230 if (!_global_atomics_registered) { \
231 NAMED_REGISTER_ATOMIC(&g_should_exit, "application_exit_flag", NULL); \
232 _global_atomics_registered = true; \
233 } \
234 } while (0)
235#else
236#define REGISTER_GLOBAL_ATOMICS() \
237 do { \
238 } while (0)
239#endif
240
242static void (*g_interrupt_callback)(void) = NULL;
243
244/* ============================================================================
245 * Global Exit API Implementation (from main.h)
246 * ============================================================================ */
247
248bool should_exit(void) {
250}
251
252void signal_exit(void) {
253 // Note: This function may be called from a signal handler context where
254 // other threads may hold mutex locks. We avoid log_console() here to prevent
255 // deadlock (render loop holds terminal lock, signal handler can't acquire it).
256 // The shutdown will be logged by normal thread context later.
257 // Ctrl-C can arrive through both the console-control handler and the
258 // terminal input path. Only the first request may run the shutdown
259 // callback; running it twice races teardown and can leave the process stuck.
261 return;
262 log_info("Shutdown signal received");
263 // Interrupt telemetry network I/O immediately. Full drain/free remains in
264 // the normal teardown path, but cancellation must not wait for atexit.
266 void (*cb)(void) = g_interrupt_callback;
267 if (cb) {
268 cb();
269 }
270}
271
272void set_interrupt_callback(void (*cb)(void)) {
273 g_interrupt_callback = cb;
274}
275
276/* ============================================================================
277 * Signal Handlers
278 * ============================================================================ */
279
280#ifndef _WIN32
285static void handle_sigterm(int sig) {
286 // Write to stderr about which signal was received for debugging
287 const char *sig_name = (sig == SIGTERM) ? "SIGTERM" : (sig == SIGINT) ? "SIGINT" : (sig == SIGHUP) ? "SIGHUP" : "UNKNOWN";
288 char log_out[MAIN_LOG_OUT_BUFFER_SIZE];
289 safe_snprintf(log_out, sizeof(log_out), "Signal '%s' received", sig_name);
290
291 // If Ctrl+C (SIGINT) and help screen is active, close it instead of exiting
292 if (sig == SIGINT && keyboard_help_is_active_global()) {
293 log_console(LOG_INFO, "Ctrl+C received - closing help screen");
295 return; // Help is now closed, don't exit
296 }
297
298 if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT) {
299 size_t used = strlen(log_out);
300 safe_snprintf(log_out + used, sizeof(log_out) - used, " - shutting down");
301 }
302 if (sig == SIGHUP)
303 platform_systemd_notify_reloading();
304 // log_console() is async-signal-safe - uses atomic ops and platform_write_all()
305 log_console(LOG_INFO, log_out);
306
307#ifndef NDEBUG
308 // Trigger debug sync state printing on shutdown (async-signal-safe)
309 // Defer these diagnostics to the normal teardown path. Console callbacks
310 // must remain non-blocking while the application is trying to exit.
311#endif
312
313 // Call signal_exit() to set flag AND interrupt blocking socket operations
314 signal_exit();
315}
316#endif
317
318#ifdef _WIN32
319static void windows_sigint_handler(int sig) {
320 (void)sig;
321 signal_exit();
322}
323#endif
324
330static bool console_ctrl_handler(console_ctrl_event_t event) {
331 if (event != CONSOLE_CTRL_C && event != CONSOLE_CTRL_BREAK && event != CONSOLE_CLOSE) {
332 return false;
333 }
334
335 // The console callback must initiate shutdown before touching UI state.
336 // UI locks/initialization can be unavailable at this point, while the
337 // telemetry cancellation path is deliberately lock-free and immediate.
338 signal_exit();
339
340 // Check if keyboard help screen is active (defined in session/display.c)
341 // Uses atomic load only - safe from signal context
343 // Help screen is active - close it instead of exiting
344 log_console(LOG_INFO, "Ctrl+C received - closing help screen");
346 return true; // Handled - don't exit
347 }
348
349 log_console(LOG_INFO, "Ctrl+C received - shutting down");
350
351#ifndef NDEBUG
352 // Trigger debug sync state printing on shutdown (async-signal-safe)
353 debug_sync_trigger_print();
356#endif
357
358 // Double Ctrl+C forces immediate exit
359 static atomic_t ctrl_c_count = {0};
360 static bool ctrl_c_count_registered = false;
361 if (!ctrl_c_count_registered) {
362 NAMED_REGISTER_ATOMIC(&ctrl_c_count, "ctrl_c_interrupt_count", NULL);
363 ctrl_c_count_registered = true;
364 }
365 if (atomic_fetch_add_int(&ctrl_c_count, 1) > 0) {
367 }
368
369 return true;
370}
371
372/* ============================================================================
373 * Debug Signal Handlers (all modes)
374 * ============================================================================ */
375
376#ifndef NDEBUG
377#ifndef _WIN32
382static void common_handle_sigusr1(int sig) {
383 (void)sig;
384 debug_sync_trigger_print();
387}
388
393static void common_handle_sigusr2(int sig) {
394 (void)sig;
396}
397#endif
398#endif
399
405 if (!platform_set_console_ctrl_handler(console_ctrl_handler)) {
406 log_warn("Failed to register Windows console control handler: %d", platform_get_last_error());
407 }
408
409#ifdef _WIN32
410 /* Keep a CRT fallback for consoles that deliver Ctrl-C as SIGINT rather
411 * than invoking the process console handler (notably private test consoles). */
412 signal(SIGINT, windows_sigint_handler);
413#ifdef SIGBREAK
414 signal(SIGBREAK, windows_sigint_handler);
415#endif
416 log_dev("Signal handlers registered");
417#endif
418
419#ifndef _WIN32
420 platform_signal_handler_t handlers[] = {
421 {SIGINT, handle_sigterm},
422 {SIGTERM, handle_sigterm},
423 {SIGPIPE, SIG_IGN},
424 };
425 platform_register_signal_handlers(handlers, 3);
426 log_dev("Signal handlers registered");
427#endif
428}
429
430/* ============================================================================
431 * Mode Registration Table
432 * ============================================================================ */
433
434typedef int (*mode_entry_point_t)(void);
435
436typedef struct {
437 const char *name;
438 const char *description;
441
442static const mode_descriptor_t g_mode_table[] = {
443 {
444 .name = "server",
445 .description = "Run as multi-client video chat server",
446 .entry_point = server_main,
447 },
448 {
449 .name = "client",
450 .description = "Run as video chat client (connect to server)",
451 .entry_point = client_main,
452 },
453 {
454 .name = "mirror",
455 .description = "View local webcam as ASCII art (no server)",
456 .entry_point = mirror_main,
457 },
458 {
459 .name = "discovery-service",
460 .description = "Secure P2P session signalling",
461 .entry_point = acds_main,
462 },
463 {.name = "mcp-server", .description = "MCP rendering tools", .entry_point = mcp_server_main},
464 {.name = "api-server", .description = "HTTP image-to-ASCII API", .entry_point = api_server_main},
465 {.name = NULL, .description = NULL, .entry_point = NULL},
466};
467
468/* ============================================================================
469 * Help and Usage Functions
470 * ============================================================================ */
471
472static void print_usage(asciichat_mode_t mode) {
473 // Use the new usage() function from common.c which handles mode-specific help properly
474 usage(stdout, mode);
475}
476
477// Discovery mode is implicit (no keyword) so it has a separate descriptor
478static const mode_descriptor_t g_discovery_mode = {
479 .name = "discovery",
480 .description = "P2P session with automatic host negotiation",
481 .entry_point = discovery_main,
482};
483
500static const mode_descriptor_t *g_mode_lookup[] = {
501 [MODE_SERVER] = &g_mode_table[0], // server_main
502 [MODE_CLIENT] = &g_mode_table[1], // client_main
503 [MODE_MIRROR] = &g_mode_table[2], // mirror_main
504 [MODE_DISCOVERY_SERVICE] = &g_mode_table[3], // acds_main
505 [MODE_DISCOVERY] = &g_discovery_mode, // discovery_main (implicit mode)
506 [MODE_MCP_SERVER] = &g_mode_table[4],
507 [MODE_API_SERVER] = &g_mode_table[5],
508 [MODE_INVALID] = NULL, // Invalid: no descriptor
509};
510
520static const mode_descriptor_t *find_mode(asciichat_mode_t mode) {
521 // Bounds check: ensure mode is within valid range (0 to MODE_INVALID)
522 if (mode < MODE_SERVER || mode > MODE_INVALID) {
523 return NULL;
524 }
525 return g_mode_lookup[mode];
526}
527
528/* ============================================================================
529 * Helper Functions for Post-Options Processing
530 * ============================================================================ */
531
532static void on_exit_show_cursor(void) {
535 else
537}
538
539/* ============================================================================
540 * Main Entry Point
541 * ============================================================================ */
542
543int main(int argc, char *argv[]) {
544 // Configure the console before --help or any early option error can emit
545 // Unicode text.
546 terminal_enable_ansi();
547 if (process_utf8_arguments(&argc, &argv) != ASCIICHAT_OK) {
548 fprintf(stderr, "Failed to convert command-line arguments to UTF-8\n");
549 return 1;
550 }
551 // Set global argc/argv for early argv inspection (e.g., in terminal.c)
552 g_argc = argc;
553 g_argv = argv;
554
555 // Validate basic argument structure
556 if (argc < 1 || argv == NULL || argv[0] == NULL) {
557 return 1;
558 }
559
560 // Initialize the named registry for debugging (allows --debug-state to show registered synchronization primitives)
561#ifndef NDEBUG
562 named_init();
563 // Initialize atomic operations debug tracking
565 // Register global atomics with descriptive names for debug sync state monitoring
567 // Static atomics are now auto-registered via ATOMIC_INIT_AUTO macro at definition time
568 // Register all packet types from the packet_type_t enum
570#endif
571
572 // Register the main thread IMMEDIATELY after named_init() to ensure it's available for all subsequent allocations
573#ifndef NDEBUG
574#ifdef _WIN32
575 NAMED_REGISTER_THREAD(GetCurrentThread(), "main", NULL);
576#else
577 NAMED_REGISTER_THREAD((platform_thread_t)thread_self(), "main", NULL);
578#endif
579 // Also save main thread ID for memory reporting (must be very early)
581#endif
582
583 // Preserve arguments before environment consumers or option parsing retain pointers.
584 asciichat_errno_scope_t title_init_scope = errno_scope_begin();
585 static const platform_application_config_t platform_config = {
586 .name = "ascii-chat",
587 .config_directory = "ascii-chat",
588 .data_directory = "ascii-chat",
589 };
590 // Register the application identity before options_init() so libplatform's
591 // automatic config search uses %APPDATA%\\ascii-chat, not its generic default.
592 (void)platform_set_application_config(&platform_config);
593
594 asciichat_error_t title_init_result = platform_process_title_init(argc, &argv);
595 if (title_init_result == ASCIICHAT_OK)
596 ASSERT_NO_ERRNO_SINCE(title_init_scope);
598 g_argv = argv;
599 (void)atexit(platform_process_title_destroy);
600
601 // Determine the first positional argument without mistaking an option value for a mode.
603 bool mcp_mode_early = false;
604 for (int i = 1; i < argc; ++i) {
605 if (argv[i][0] != '-') {
606 mcp_mode_early = strcmp(argv[i], "mcp-server") == 0;
607 break;
608 }
609 if (!strchr(argv[i], '=')) {
610 const char *name = argv[i] + (argv[i][1] == '-' ? 2 : 1);
611 const registry_entry_t *descriptor = argv[i][1] == '-' ? registry_find_entry_by_name(name) : (name[0] && !name[1] ? registry_find_entry_by_short(name[0]) : NULL);
612 if (descriptor && descriptor->type != OPTION_TYPE_BOOL && descriptor->type != OPTION_TYPE_ACTION && i + 1 < argc) {
613 bool next_is_mode = strcmp(argv[i + 1], "discovery") == 0 || strcmp(argv[i + 1], "acds") == 0;
614 for (const mode_descriptor_t *mode = g_mode_table; mode->name; ++mode)
615 if (strcmp(argv[i + 1], mode->name) == 0)
616 next_is_mode = true;
617 if (!descriptor->optional_arg || (argv[i + 1][0] != '-' && !next_is_mode))
618 ++i;
619 }
620 }
621 }
622 bool help_requested = false;
623 for (int i = 1; i < argc; ++i)
624 if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h"))
625 help_requested = true;
626 mcp_mode_early = mcp_mode_early && !help_requested;
627 // Reserve stdout even in HTTP mode: configuration can select the transport later.
628 if (mcp_mode_early && mcp_stdio_reserve() != ASCIICHAT_OK)
630 bool mcp_stdio = mcp_mode_early;
631
632 // Show cursor early in case a previous session crashed with it hidden.
633 if (!mcp_stdio && platform_isatty(STDOUT_FILENO))
634 (void)ui_controller_write(STDOUT_FILENO, "\033[?25h", 6);
635
636 // VERY FIRST: Scan for --color BEFORE ANY logging initialization
637 // This sets global flags that persist through cleanup, enabling --color to force colors
638 for (int i = 1; i < argc; i++) {
639 if (strcmp(argv[i], "--color") == 0 || strcmp(argv[i], "--color=true") == 0) {
640 g_color_flag_passed = true;
641 g_color_flag_value = true;
642 break;
643 } else if (strncmp(argv[i], "--color=", 8) == 0) {
644 g_color_flag_passed = true;
645 g_color_flag_value = strcmp(argv[i], "--color=false") != 0;
646 break;
647 }
648 }
649
650 // SECOND: Scan for --grep BEFORE ANY logging initialization
651 // This ensures ALL logs (including from shared_init) can be filtered
652 // Supports multiple --grep patterns (ORed together)
653 for (int i = 1; i < argc - 1; i++) {
654 if (strcmp(argv[i], "--grep") == 0) {
655 const char *pattern = argv[i + 1];
656 asciichat_error_t filter_result = grep_init(pattern);
657 if (filter_result != ASCIICHAT_OK) {
658 log_error("Invalid --grep pattern or invalid flags: \"%s\" - use /pattern/flags format (e.g., \"/query/ig\" or "
659 "\"/literal/F\")",
660 pattern);
661 return 1;
662 }
663 i++; // Skip the pattern argument
664 }
665 }
666
667 // Detect terminal capabilities early so colored help output works
668 // Logging will be initialized by asciichat_shared_init() before options_init()
670 terminal_capabilities_t caps;
673 platform_color_set_truecolor_supported(caps.color_level == TERM_COLOR_TRUECOLOR);
674
675 // Warn if Release build was built from dirty working tree
676#if ASCII_CHAT_GIT_IS_DIRTY
677 if (strcmp(ASCII_CHAT_BUILD_TYPE, "Release") == 0) {
678 // Dirty git warning will be logged after logging initialization
679 }
680#endif
681
682 // Load color scheme early (from config files and CLI) before logging initialization
683 // This allows logging to use the correct colors from the start
685
686 // Parse --color-scheme from argv early to set logging colors for help output
687 const char *colorscheme_name = "pastel"; // default
688 for (int i = 1; i < argc - 1; i++) {
689 if (strcmp(argv[i], "--color-scheme") == 0) {
690 colorscheme_name = argv[i + 1];
691 break;
692 }
693 }
694
695 // Load and apply colorscheme to logging BEFORE options_init() so help gets colors
696 color_scheme_t scheme;
697 if (colorscheme_load_builtin(colorscheme_name, &scheme) == ASCIICHAT_OK) {
698 log_set_color_scheme(&scheme);
699 } else {
700 // Fall back to default pastel if scheme not found
701 if (colorscheme_load_builtin("pastel", &scheme) == ASCIICHAT_OK) {
702 log_set_color_scheme(&scheme);
703 }
704 }
705
706 // Initialize logging colors so they're ready for help output
708
709 // Keep libplatform diagnostics on the same active ascii-chat palette.
710 platform_color_set_code(PLATFORM_COLOR_DEV, log_level_color(LOG_COLOR_DEV));
711 platform_color_set_code(PLATFORM_COLOR_DEBUG, log_level_color(LOG_COLOR_DEBUG));
712 platform_color_set_code(PLATFORM_COLOR_INFO, log_level_color(LOG_COLOR_INFO));
713 platform_color_set_code(PLATFORM_COLOR_WARN, log_level_color(LOG_COLOR_WARN));
714 platform_color_set_code(PLATFORM_COLOR_ERROR, log_level_color(LOG_COLOR_ERROR));
715 platform_color_set_code(PLATFORM_COLOR_FATAL, log_level_color(LOG_COLOR_FATAL));
716 platform_color_set_code(PLATFORM_COLOR_GREY, log_level_color(LOG_COLOR_GREY));
717 platform_color_set_code(PLATFORM_COLOR_RESET, log_level_color(LOG_COLOR_RESET));
718
719 // EARLY PARSE: Find the mode position (first positional argument)
720 // Binary-level options must appear BEFORE the mode
721 int mode_position = -1;
722 for (int i = 1; i < argc; i++) {
723 if (argv[i][0] != '-') {
724 // Found a positional argument - this is the mode or session string
725 mode_position = i;
726 break;
727 }
728
729 // Skip option and its argument if needed
730 // Check if this is an option that takes a required argument
731 const char *arg = argv[i];
732 const char *opt_name = arg;
733 if (arg[0] == '-') {
734 opt_name = arg + (arg[1] == '-' ? 2 : 1);
735 }
736
737 // Handle --option=value format
738 if (strchr(opt_name, '=')) {
739 continue; // Value is part of this arg, no need to skip next
740 }
741
742 const registry_entry_t *descriptor = arg[1] == '-' ? registry_find_entry_by_name(opt_name) : (opt_name[0] && !opt_name[1] ? registry_find_entry_by_short(opt_name[0]) : NULL);
743 if (descriptor && descriptor->type != OPTION_TYPE_BOOL && descriptor->type != OPTION_TYPE_ACTION && i + 1 < argc) {
744 bool next_is_mode = strcmp(argv[i + 1], "discovery") == 0 || strcmp(argv[i + 1], "acds") == 0;
745 for (const mode_descriptor_t *mode = g_mode_table; mode->name; ++mode)
746 if (strcmp(argv[i + 1], mode->name) == 0)
747 next_is_mode = true;
748 if (!descriptor->optional_arg || (argv[i + 1][0] != '-' && !next_is_mode))
749 ++i;
750 }
751 }
752
753 // EARLY PARSE: Determine mode from argv to know if this is client-like mode
754 // The first positional argument (after options) is the mode: client, server, mirror, discovery, acds
755 bool is_client_like_mode = false;
756 if (mode_position > 0) {
757 const char *first_arg = argv[mode_position];
758 if (strcmp(first_arg, "client") == 0 || strcmp(first_arg, "mirror") == 0 || strcmp(first_arg, "discovery") == 0) {
759 is_client_like_mode = true;
760 }
761 }
762
763 // EARLY PARSE: Extract log file from argv (--log-file or -L)
764 // Must appear BEFORE the mode
765 // Generate default log path based on build type and mode
766 char default_log_path[PATH_MAX];
767 asciichat_mode_t detected_mode = MODE_INVALID;
768 if (mode_position > 0) {
769 const char *mode_str = argv[mode_position];
770 // Convert mode string to enum
771 if (strcmp(mode_str, "server") == 0) {
772 detected_mode = MODE_SERVER;
773 } else if (strcmp(mode_str, "client") == 0) {
774 detected_mode = MODE_CLIENT;
775 } else if (strcmp(mode_str, "mirror") == 0) {
776 detected_mode = MODE_MIRROR;
777 } else if (strcmp(mode_str, "mcp-server") == 0) {
778 detected_mode = MODE_MCP_SERVER;
779 } else if (strcmp(mode_str, "api-server") == 0) {
780 detected_mode = MODE_API_SERVER;
781 } else if (strcmp(mode_str, "acds") == 0 || strcmp(mode_str, "discovery-service") == 0) {
782 detected_mode = MODE_DISCOVERY_SERVICE;
783 } else if (strcmp(mode_str, "discovery") == 0) {
784 detected_mode = MODE_DISCOVERY;
785 }
786 }
787 generate_default_log_path(detected_mode, default_log_path, sizeof(default_log_path));
788
789 const char *log_file = platform_systemd_is_managed() ? "/dev/null" : default_log_path;
790 int max_search = (mode_position > 0) ? mode_position : argc;
791 for (int i = 1; i < max_search - 1; i++) {
792 if ((strcmp(argv[i], "--log-file") == 0 || strcmp(argv[i], "-L") == 0)) {
793 log_file = argv[i + 1];
794 break;
795 }
796 }
797
798 // EARLY PARSE: Check for --json (JSON logging format)
799 // If JSON format is enabled, we'll use the JSON filename during early init
800 // --json MUST appear BEFORE the mode
801 bool early_json_format = false;
802 if (mode_position > 0) {
803 for (int i = 1; i < mode_position; i++) {
804 if (strcmp(argv[i], "--json") == 0) {
805 early_json_format = true;
806 break;
807 }
808 }
809 } else {
810 // If no mode found, search entire argv
811 for (int i = 1; i < argc; i++) {
812 if (strcmp(argv[i], "--json") == 0) {
813 early_json_format = true;
814 break;
815 }
816 }
817 }
818
819 // EARLY PARSE: Extract log template from argv (--log-template)
820 // Note: This is for format templates, different from --log-format which is the output format
821 // Binary-level options must appear BEFORE the mode
822 const char *early_log_template = NULL;
823 bool early_log_template_console_only = false;
824 for (int i = 1; i < max_search - 1; i++) {
825 if (strcmp(argv[i], "--log-template") == 0) {
826 early_log_template = argv[i + 1];
827 break;
828 }
829 }
830 for (int i = 1; i < max_search; i++) {
831 if (strcmp(argv[i], "--log-format-console") == 0 || strcmp(argv[i], "--log-format-console=true") == 0) {
832 early_log_template_console_only = true;
833 } else if (strcmp(argv[i], "--log-format-console=false") == 0) {
834 early_log_template_console_only = false;
835 }
836 }
837
838 // Documentation actions should not be preceded by startup diagnostics.
839 bool early_quiet_output = false;
840 for (int i = 1; i < argc; i++) {
841 if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-V") == 0) {
842 early_quiet_output = true;
843 break;
844 }
845 }
846
847 // Version output is self-contained and must not cross the shared platform
848 // initialization/DLL boundary. Keep this path deterministic for scripts
849 // and package managers, and avoid initializing subsystems that the action
850 // immediately terminates without using.
851 for (int i = 1; i < argc; i++) {
852 if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
853 printf("ascii-chat %s (%s, %s)\n", ASCII_CHAT_VERSION_FULL, ASCII_CHAT_BUILD_TYPE, ASCII_CHAT_BUILD_DATE);
854 fflush(stdout);
855 _Exit(0);
856 }
857 }
858
859 // Initialize shared subsystems BEFORE options_init()
860 // This ensures options parsing can use properly configured logging with colors
861 // If JSON format is requested, don't write text logs to file
862 // All logs will be JSON formatted later once options_init() runs
863 const char *early_log_file = early_json_format ? NULL : log_file;
864 asciichat_error_t init_result = asciichat_shared_init(early_log_file, is_client_like_mode, early_quiet_output);
865 if (init_result != ASCIICHAT_OK) {
866 return init_result;
867 }
868
869 // Install the console handler before option/media initialization. Startup
870 // can create worker threads and begin telemetry before mode dispatch; a
871 // Ctrl-C during that window must still enter the coordinated shutdown path.
873
874 // Route logs to stderr if stdout is piped (MUST happen early, before options_init logs)
875 // This keeps stdout clean for data output (e.g., --snapshot mode piped to file)
878 }
879
880 // Keep documentation output free of diagnostics while parsing the options.
881 if (early_quiet_output) {
883 }
884
885 // Register cleanup of shared subsystems to run on normal exit
886 // Library code doesn't call atexit() - the application is responsible
887 // Handlers run in reverse registration order: restore the cursor, destroy
888 // shared subsystems, then run the compatibility path cleanup.
889 (void)atexit(path_cleanup_thread_locals);
890 (void)atexit(asciichat_shared_destroy);
891 (void)atexit(on_exit_show_cursor);
892
893 // SECRET: Check for --backtrace (debug builds only) BEFORE options_init()
894 // Prints a backtrace and exits immediately - useful for debugging hangs
895#ifndef NDEBUG
896 for (int i = 1; i < argc; i++) {
897 if (strcmp(argv[i], "--backtrace") == 0) {
898 log_info("=== Backtrace at startup ===");
900 log_info("=== End Backtrace ===");
902 return 0;
903 }
904 }
905#endif
906
907 // NOW parse all options - can use logging with colors!
908 asciichat_error_t options_result = options_init(argc, argv);
909 if (options_result != ASCIICHAT_OK) {
911 if (HAS_ERRNO(&error_ctx)) {
912 NOTICE(WARNING, "INVALID OPTIONS", "%s", error_ctx.context_message);
913 } else {
914 NOTICE(WARNING, "OPTIONS INITIALIZATION FAILED", "Failed to initialize options %s", asciichat_error_format(NULL, options_result));
915 }
916
917 // Clean up options state before exiting
919
920 exit(options_result);
921 }
922
923 // Get parsed options
924 const options_t *opts = options_get();
925 if (!opts) {
926 log_error("Options not initialized");
927 return 1;
928 }
929
930 // Apply the parsed level after the early logger has initialized.
932 // Determine output format early to decide on filename and logging strategy
933 bool use_json_logging = GET_OPTION(json);
934
935 // Determine the log filename
936 // Check if user explicitly passed --log-file (not just the mode-specific default from options_init)
937 bool user_specified_log_file = false;
938 for (int i = 1; i < argc - 1; i++) {
939 if (strcmp(argv[i], "--log-file") == 0 || strcmp(argv[i], "-L") == 0) {
940 user_specified_log_file = true;
941 break;
942 }
943 }
944
945 const char *final_log_file = opts->log_file;
946 char json_filename_buf[MAIN_JSON_FILENAME_BUFFER_SIZE];
947
948 if (use_json_logging) {
949 // When JSON logging is enabled, determine JSON output filename
950 if (user_specified_log_file) {
951 // User explicitly specified a log file - use it exactly for JSON output
952 SAFE_STRNCPY(json_filename_buf, final_log_file, sizeof(json_filename_buf) - 1);
953 } else {
954 // Using default: replace .log with .json in the mode-specific default
955 // e.g., server.log -> server.json, mirror.log -> mirror.json, etc.
956 size_t len = strlen(final_log_file);
957 if (len > 4 && strcmp(&final_log_file[len - 4], ".log") == 0) {
958 // File ends with .log - replace with .json
959 SAFE_STRNCPY(json_filename_buf, final_log_file, sizeof(json_filename_buf) - 1);
960 // Replace .log with .json
961 asciichat_error_t strcpy_result = SAFE_STRCPY(&json_filename_buf[len - 4], sizeof(json_filename_buf) - (len - 4), ".json");
962 if (strcpy_result != ASCIICHAT_OK) {
963 log_error("Failed to write .json extension: %s", asciichat_error_format(NULL, strcpy_result));
964 }
965 } else {
966 // File doesn't end with .log - just append .json
967 snprintf(json_filename_buf, sizeof(json_filename_buf), "%s.json", final_log_file);
968 }
969 }
970 final_log_file = json_filename_buf;
971 // For JSON mode: Initialize logging without file (text will be disabled)
972 // We'll set up JSON output separately below
973 // Note: log_init() was already called in asciichat_shared_init()
974 } else {
975 // Text logging mode: use the file from options (which is mode-specific default or user-specified)
976 // Note: log_init() was already called in asciichat_shared_init()
977 }
978
979 // Apply custom log template if specified (use early parsed value if available, otherwise use options)
980 const char *final_format = early_log_template ? early_log_template : GET_OPTION(log_template);
981 bool final_format_console_only = early_log_template ? early_log_template_console_only : GET_OPTION(log_format_console_only);
982 if (final_format && final_format[0] != '\0') {
983 asciichat_error_t fmt_result = log_set_format(final_format, final_format_console_only);
984 if (fmt_result != ASCIICHAT_OK) {
985 log_error("Failed to apply custom log format");
986 }
987 }
988
989 // Configure JSON output if requested
990 if (use_json_logging) {
991 // Close the text sink before truncating the destination for JSON records.
992 // The two descriptors must not write different formats at independent offsets.
994 int json_fd = platform_open("main_log_file", final_log_file, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
995 if (json_fd >= 0) {
996 log_set_json_output(json_fd);
997 } else {
998 // Failed to open JSON file - report error and exit
999 SET_ERRNO(ERROR_CONFIG, "Failed to open JSON output file: %s", final_log_file);
1000 return ERROR_CONFIG;
1001 }
1002 }
1003
1004 // Initialize colors now that logging is fully initialized
1005 // This must happen after log_init() since log_init_colors() checks if g_log.initialized
1007 log_debug("SIMD luminance backend: %s", simd_backend()->name);
1008
1009 // Apply quiet mode - disables terminal output
1010 // Status screen mode only disables terminal output if terminal is interactive
1011 // In non-interactive mode (piped output), logs go to stdout/stderr normally
1012 if (GET_OPTION(quiet) || (opts->detected_mode == MODE_SERVER && GET_OPTION(status_screen) && terminal_is_interactive())) {
1014 }
1015
1016 // Initialize palette based on command line options
1017 const char *custom_chars = opts && opts->palette_custom_set ? opts->palette_custom : NULL;
1018 if (apply_palette_config(GET_OPTION(palette_type), custom_chars) != 0) {
1019 FATAL(ERROR_CONFIG, "Failed to apply palette configuration");
1020 }
1021
1022 // Set quiet mode for memory debugging
1023#if defined(DEBUG_MEMORY) && !defined(USE_MIMALLOC_DEBUG) && !defined(NDEBUG)
1024 debug_memory_set_quiet_mode(GET_OPTION(quiet));
1025#endif
1026
1027 // Truncate log if it's already too large
1029 fflush(stderr);
1030
1031 // Handle --help and --version (these are detected and flagged by options_init)
1032 // Terminal capabilities already initialized before options_init() at startup
1033 if (opts->help) {
1035 print_usage(opts->detected_mode);
1036 fflush(NULL);
1037 asciichat_coverage_flush();
1038 _Exit(0);
1039 }
1040
1041 if (opts->version) {
1044 // action_show_version() calls _Exit(), so we don't reach here
1045 }
1046
1047#ifndef NDEBUG
1048 // Handle --debug-state (debug builds only)
1049 // Sleep for specified time AFTER mode initialization so locks are created
1050 if (opts->debug_sync_state_time > 0.0) {
1051 log_info("Will print sync state after %f seconds", opts->debug_sync_state_time);
1052 }
1053#endif
1054
1055 // For server mode with status screen: disable terminal output only if interactive
1056 // In non-interactive mode (piped output), logs go to stdout/stderr normally
1057 // The status screen (when shown) will capture and display logs in its buffer instead
1060 }
1061
1062 log_dev("Logging initialized to %s", final_log_file);
1063
1064 // Note: We do NOT auto-disable colors when stdout appears to be piped, because:
1065 // 1. Tools like ripgrep can display ANSI colors when piped
1066 // 2. Sandboxed/containerized environments may report false positives for isatty()
1067 // 3. Users can explicitly disable colors with --color=false if needed
1068 // Color behavior is now fully controlled by --color and --color-mode options.
1069
1070#ifndef NDEBUG
1071 // Initialize lock debugging system after logging is fully set up
1072 log_debug("Initializing lock debug system...");
1073 int debug_sync_result = debug_stats_init();
1074 if (debug_sync_result != 0) {
1075 LOG_ERRNO_IF_SET("Debug sync system initialization failed");
1076 FATAL(ERROR_PLATFORM_INIT, "Debug sync system initialization failed");
1077 }
1078 log_debug("Debug sync system initialized successfully");
1079
1080#ifndef _WIN32
1081 // Unblock SIGUSR1 and SIGUSR2 at process level to ensure delivery
1082 sigset_t set;
1083 sigemptyset(&set);
1084 sigaddset(&set, SIGUSR1);
1085 sigaddset(&set, SIGUSR2);
1086 sigprocmask(SIG_UNBLOCK, &set, NULL);
1087
1088 // Register SIGUSR1 to trigger synchronization debugging output in all modes
1089 signal_handler_t old_usr1 = platform_signal(SIGUSR1, common_handle_sigusr1);
1090 if (old_usr1 == SIG_ERR) {
1091 log_warn("Failed to register SIGUSR1 handler");
1092 } else {
1093 log_debug("SIGUSR1 handler registered successfully");
1094 }
1095
1096 // Register SIGUSR2 to trigger memory report in all modes
1097 signal_handler_t old_usr2 = platform_signal(SIGUSR2, common_handle_sigusr2);
1098 if (old_usr2 == SIG_ERR) {
1099 log_warn("Failed to register SIGUSR2 handler");
1100 } else {
1101 log_debug("SIGUSR2 handler registered successfully");
1102 }
1103#endif
1104#endif
1105
1106 if (opts->fps > 0) {
1107 if (opts->fps < 1 || opts->fps > 144) {
1108 log_warn("FPS value %d out of range (1-144), using default", opts->fps);
1109 } else {
1110 log_debug("FPS set from command line: %d", opts->fps);
1111 }
1112 }
1113
1114 // Automatic update check in background thread (once per week maximum)
1115 if (opts->detected_mode != MODE_MCP_SERVER && !GET_OPTION(no_check_update)) {
1117 }
1118
1119 // Register application callbacks so lib code can check exit flags
1120 // This connects the render loop's should_exit check to signal_exit()
1121 static const app_callbacks_t app_callbacks = {
1122 .should_exit = should_exit,
1123 .signal_exit = signal_exit,
1124 .platform_get_monotonic_time_us = platform_get_monotonic_time_us,
1125 .platform_sleep_ms = platform_sleep_ms,
1126 };
1127 app_callbacks_register(&app_callbacks);
1128
1129 static const platform_question_callbacks_t question_callbacks = {
1130 .pop_response = env_pop_prompt_response,
1131 .input = platform_question_input_adapter,
1132 .notice_kind = ui_notice_prompt_kind,
1133 .kind_name = ui_prompt_kind_name,
1134 .error = app_question_error,
1135 .usage = app_question_usage,
1136 };
1137 platform_question_set_callbacks(&question_callbacks);
1138
1139 // Register shutdown callback so splash thread and other code can check for exit
1141
1142 // Diagnostic monitoring is Debug-only; error storage is available in every build.
1143#ifndef NDEBUG
1144 uint64_t sync_state_delay_ns = 0;
1145 uint64_t debug_backtrace_delay_ns = 0;
1146 if (opts->debug_sync_state_time > 0.0)
1147 sync_state_delay_ns = (uint64_t)(opts->debug_sync_state_time * 1000000000.0);
1148 if (opts->debug_backtrace_time > 0.0)
1149 debug_backtrace_delay_ns = (uint64_t)(opts->debug_backtrace_time * 1000000000.0);
1150 if (debug_sync_start_thread(sync_state_delay_ns, debug_backtrace_delay_ns) != 0) {
1151 FATAL(ERROR_THREAD, "Cannot start synchronization worker");
1152 }
1154 FATAL(ERROR_THREAD, "Cannot start errno worker");
1155 }
1157 FATAL(ERROR_THREAD, "Cannot start diagnostics worker");
1158 }
1159#endif
1160
1161 // Find and dispatch to mode entry point
1162 const mode_descriptor_t *mode = find_mode(opts->detected_mode);
1163 if (!mode) {
1164 log_error("Mode not found for detected_mode=%d", opts->detected_mode);
1165 return 1;
1166 }
1167
1168 // Call the mode-specific entry point
1169 // Mode entry points use options_get() to access parsed options
1170 if (title_init_result == ASCIICHAT_OK) {
1172 asciichat_error_t title_result = platform_process_title_set_args("ascii-chat: ", mode->name, argc, argv, opts->mode_arg_index);
1173 if (title_result != ASCIICHAT_OK) {
1174 log_debug("Could not set process title for %s mode", mode->name);
1175 } else {
1176 ASSERT_NO_ERRNO_SINCE(title_scope);
1177 }
1179 } else {
1180 log_debug("Process title initialization was unavailable %s", asciichat_error_format(NULL, title_init_result));
1181 }
1182 asciichat_errno_scope_t terminal_title_scope = errno_scope_begin();
1183 if (opts->detected_mode != MODE_MCP_SERVER || !strcmp(GET_OPTION(mcp_transport), "http"))
1184 (void)ui_controller_title_start(mode->name, platform_isatty(STDOUT_FILENO) ? STDOUT_FILENO : STDERR_FILENO);
1185 errno_scope_end(terminal_title_scope, ASCIICHAT_ERRNO_DISMISSED);
1186 if (strcmp(mode->name, "mirror") != 0) {
1187 asciichat_error_t stats_result = stats_runtime_start(mode->name, (unsigned)GET_OPTION(stats_interval));
1188 if (stats_result != ASCIICHAT_OK)
1189 return stats_result;
1190 }
1191 asciichat_error_t otel_result = ascii_otel_init(mode->name, argc, argv);
1192 if (otel_result != ASCIICHAT_OK) {
1194 const char *detail = HAS_ERRNO(&context) ? context.context_message : NULL;
1195 log_error("Telemetry configuration failed %s", asciichat_error_format(detail, otel_result));
1196 return otel_result;
1197 }
1198 int exit_code = mode->entry_point();
1199 asciichat_error_t requested_exit = errno_exit_code();
1200 if (requested_exit != ASCIICHAT_OK)
1201 exit_code = requested_exit;
1202 if (!shutdown_is_requested())
1204 if (!shutdown_is_requested())
1205 ascii_otel_exit(exit_code);
1206 log_debug("Shutdown: entering telemetry shutdown");
1208 log_debug("Shutdown: telemetry shutdown complete");
1209
1210 // Named registry cleanup is handled by asciichat_shared_destroy()
1211 // (called via atexit handler), which runs AFTER the memory report
1212
1213 if (exit_code == ERROR_USAGE) {
1214 exit(ERROR_USAGE);
1215 }
1216
1217 return exit_code;
1218}
Action option callbacks for ascii-chat.
int api_server_main(void)
Application-level callbacks for library code.
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_error_t errno_exit_code(void)
asciichat_errno_scope_t errno_scope_begin(void)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define HAS_ERRNO(context)
#define ASSERT_NO_ERRNO_SINCE(scope)
@ ASCIICHAT_ERRNO_DISMISSED
#define LOG_ERRNO_IF_SET(message)
#define ATOMIC_INIT_AUTO(...)
Initialize an atomic_t with automatic named registration.
Definition atomic.h:507
int atomic_fetch_add_int(atomic_t *a, int delta)
Atomically add to an int and return the previous value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void debug_atomic_init(void)
bool atomic_exchange_bool(atomic_t *a, bool new_value)
Atomically exchange a boolean and return the old value.
void backtrace_print_simple(int skip_frames)
Definition backtrace.c:60
@ OPTION_TYPE_ACTION
Action that executes and may exit (–list-webcams, etc.).
Definition builder.h:176
@ OPTION_TYPE_BOOL
Boolean flag (–flag, no value).
Definition builder.h:171
int client_main(void)
Client mode entry point for unified binary.
ascii-chat Client Mode Entry Point Header
asciichat_error_t options_colorscheme_init_early(int argc, const char *const argv[])
Initialize color scheme early (before logging).
asciichat_error_t colorscheme_load_builtin(const char *name, color_scheme_t *scheme)
Load a built-in color scheme.
const registry_entry_t * registry_find_entry_by_name(const char *long_name)
Get a registry entry by long name.
Definition core.c:126
const registry_entry_t * registry_find_entry_by_short(char short_name)
Get a registry entry by short name.
Definition core.c:144
void registry_init_size(void)
Initialize registry size and metadata.
Definition core.c:107
Named object registry for debugging — log identifiable resource names.
int acds_main(void)
This is the handoff point for acds config. Callers fill port, log_level, require_server_identity,...
int discovery_main(void)
Discovery mode entry point for unified binary.
ascii-chat Discovery Mode Entry Point Header
const simd_backend_t * simd_backend(void)
Definition dispatch.c:36
bool env_pop_prompt_response(char *response_out, size_t response_size)
Pop the first response from ASCII_CHAT_QUESTION_PROMPT_RESPONSE stack.
Definition env.c:96
Environment variable utilities with stack-based prompt responses.
void debug_errno_trigger_print(void)
Definition errno.c:47
asciichat_error_t debug_errno_start_thread(void)
Definition errno.c:90
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
int platform_mkdir_recursive(const char *path, int mode)
Definition filesystem.c:36
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
atomic_t g_should_exit
Global application exit flag (shared across all modes).
Definition globals.c:31
asciichat_error_t grep_init(const char *pattern)
Initialize log filtering with PCRE2 regex pattern.
Definition grep.c:411
bool g_color_flag_value
Value of –color flag (true if –color was in argv) Set by options_init() before RCU is initialized,...
Definition common.c:66
char ** g_argv
Global argv for early argument inspection (e.g., –color flag detection) Set by main() for access from...
Definition common.c:62
#define SAFE_STRNCPY(dst, src, size)
int g_argc
Global argc for early argument inspection (e.g., –color flag detection) Set by main() for access from...
Definition common.c:61
bool g_color_flag_passed
Was –color explicitly passed in command-line arguments? Set by options_init() before RCU is initializ...
Definition common.c:65
#define SAFE_GETENV(name)
asciichat_error_t asciichat_shared_init(const char *log_file, bool is_client, bool quiet_startup)
Initialize common subsystems shared by client and server.
Definition common.c:131
#define SAFE_STRCPY(dest, dest_size, src)
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
unsigned long long uint64_t
void asciichat_shared_destroy(void)
Clean up all shared library subsystems.
Definition common.c:219
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_REGISTER_THREAD(thread, name, parent_ptr)
Register a thread handle with name and automatic format specifier.
void named_registry_register_packet_types(void)
Register all packet types from packet_type_t enum.
asciichat_error_t named_init(void)
Initialize the named object registry.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_PLATFORM_INIT
Definition error_codes.h:59
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_FILE_OPERATION
@ ERROR_USAGE
Definition error_codes.h:52
@ ERROR_THREAD
void log_truncate_if_large(void)
Manually truncate large log files.
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
void log_init_colors(void)
Initialize logging color system with current terminal capabilities.
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
void log_set_force_stderr(bool enabled)
Force all terminal log output to stderr.
const char * log_level_color(log_color_t color)
Get color string for a given color enum.
void log_disable_file_output(void)
Disable file output and use stderr instead.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
void log_set_level(log_level_t level)
Set the minimum log level.
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
asciichat_error_t log_set_format(const char *format_str, bool console_only)
Set a custom log format string.
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:687
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
void log_set_color_scheme(const color_scheme_t *scheme)
Set the color scheme for logging output.
void log_redetect_terminal_capabilities(void)
Re-detect terminal capabilities after logging is initialized.
@ LOG_COLOR_RESET
Definition log/log.h:154
@ LOG_COLOR_GREY
Definition log/log.h:153
@ LOG_COLOR_FATAL
Definition log/log.h:152
@ LOG_COLOR_ERROR
Definition log/log.h:151
@ LOG_COLOR_DEV
Definition log/log.h:147
@ LOG_COLOR_DEBUG
Definition log/log.h:148
@ LOG_COLOR_INFO
Definition log/log.h:149
@ LOG_COLOR_WARN
Definition log/log.h:150
#define GET_OPTION(field)
Definition options.h:1333
asciichat_mode_t
Mode type for options parsing.
Definition options.h:916
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:495
asciichat_error_t options_init(int argc, char **argv)
Initialize options by parsing command-line arguments with unified mode detection.
Definition options.c:2291
void usage(FILE *desc, asciichat_mode_t mode)
Print usage information for a specific mode.
#define options_terminal_settings()
Definition options.h:1287
@ 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
int apply_palette_config(palette_type_t type, const char *custom_chars)
Apply palette configuration (set global palette).
Definition palette.c:243
bool keyboard_help_is_active_global(void)
Check if keyboard help is active (global accessor for signal handlers).
void update_banner_start_check(void)
Start the background update check thread.
void keyboard_help_toggle_global(void)
Toggle keyboard help (global accessor for signal handlers).
bool(* shutdown_check_fn)(void)
Shutdown check callback function type.
Definition shutdown.h:36
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:86
void shutdown_register_callback(shutdown_check_fn callback)
Register application's shutdown check function.
Definition common.c:78
void path_cleanup_thread_locals(void)
Cleanup thread-local path resources.
Definition path.c:32
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Statistics worker for error totals and memory reports. Signal handlers may only request a report.
📝 JSON structured logging output
Common utilities and helpers for option parsing across all modes.
🆘 Interactive keyboard help overlay for session keyboard shortcuts
void debug_stats_set_main_thread_id(void)
asciichat_error_t debug_stats_init(void)
void debug_stats_trigger_print(void)
void debug_stats_trigger_memory_report(void)
asciichat_error_t debug_stats_start_thread(void)
void log_set_json_output(int fd)
Set the JSON output file descriptor.
void action_show_version(void)
Show version information and exit.
📝 Logging API with multiple log levels and terminal output control
#define log_console(level, message)
Definition log/log.h:1046
void signal_exit(void)
Definition main.c:252
int main(int argc, char *argv[])
Definition main.c:543
#define REGISTER_GLOBAL_ATOMICS()
Definition main.c:227
void setup_signal_handlers(void)
Definition main.c:404
#define MAIN_JSON_FILENAME_BUFFER_SIZE
Definition main.c:4
int(* mode_entry_point_t)(void)
Definition main.c:434
#define MAIN_LOG_OUT_BUFFER_SIZE
Definition main.c:3
bool should_exit(void)
Definition main.c:248
void set_interrupt_callback(void(*cb)(void))
Definition main.c:272
Global application exit and signal handling API.
int mcp_server_main(void)
asciichat_error_t mcp_stdio_reserve(void)
Definition stdio.c:7
int mirror_main(void)
Run mirror mode main loop.
ascii-chat Mirror Mode Interface
signal_handler_t platform_signal(int sig, signal_handler_t handler)
Definition misc.c:123
void(* signal_handler_t)(int)
Definition misc.c:121
void platform_force_exit(int exit_code)
Definition misc.c:129
ui_prompt_kind_t ui_notice_prompt_kind(void)
Definition notice.c:494
#define NOTICE(severity, title,...)
Definition notice.h:56
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
void ascii_otel_shutdown(void)
Definition otel.c:445
void ascii_otel_ui_usage(const char *screen, const char *event, uint64_t duration_ns)
Definition otel.c:411
void ascii_otel_exit(int code)
Definition otel.c:715
void ascii_otel_request_shutdown(void)
Definition otel.c:156
asciichat_error_t ascii_otel_init(const char *mode, int argc, char **argv)
Definition otel.c:530
📂 Path Manipulation Utilities
PCRE2 compilation and match helpers.
const char * ui_prompt_kind_name(ui_prompt_kind_t kind)
Definition prompt.c:225
void options_state_destroy(void)
Shutdown RCU options system.
Definition rcu.c:465
void stats_runtime_stop(void)
Definition runtime.c:611
asciichat_error_t stats_runtime_start(const char *mode, unsigned interval_seconds)
Definition runtime.c:492
int server_main(void)
server context keeps the values that move through the subsystem: network_server, rate_limiter,...
Intro and status screen display for ascii-chat with animated rainbow effects.
void app_callbacks_register(app_callbacks_reg_t *callbacks)
void apply_color_mode_override_into(const terminal_capabilities_t *caps, const terminal_options_t *options, terminal_capabilities_t *out)
bool terminal_is_interactive(void)
void detect_terminal_capabilities_into(const terminal_options_t *options, terminal_capabilities_t *out)
bool terminal_should_force_stderr(void)
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76
Color scheme definition.
Definition colorscheme.h:76
mode_entry_point_t entry_point
Definition main.c:439
double debug_sync_state_time
Time parameter for –sync-state.
Definition options.h:1239
asciichat_mode_t detected_mode
Mode detected from command-line arguments.
Definition options.h:978
log_level_t log_level
Log level threshold.
Definition options.h:1160
char palette_custom[256]
Custom palette characters.
Definition options.h:1221
bool status_screen
Show status screen (default: true = show, use –no-status-screen to hide).
Definition options.h:1230
bool palette_custom_set
True if custom palette was set.
Definition options.h:1222
bool version
Show version information.
Definition options.h:985
bool help
Show help message.
Definition options.h:984
int fps
Target framerate (0 = auto, 1-144).
Definition options.h:1091
double debug_backtrace_time
Time parameter for –backtrace option.
Definition options.h:1241
int mode_arg_index
Explicit mode token in original argv, or -1 for implicit discovery/session strings.
Definition options.h:979
char log_file[256]
Log file path.
Definition options.h:1159
Registry entry - stores option definition with mode bitmask and metadata.
option_type_t type
bool optional_arg
⏱️ High-precision timing utilities using sokol_time.h and uthash
void ui_controller_restore_terminal_output(void)
asciichat_error_t ui_controller_title_start(const char *mode, int fd)
void ui_controller_restore_terminal(void)
asciichat_error_t ui_controller_write(int fd, const char *data, size_t len)
asciichat_error_t ui_input_prompt(const char *prompt, char *buffer, size_t max_len, prompt_opts_t opts)
Definition tui/input.c:744
#define LOG_INFO
Definition types.h:44
Update available prompt screen shown after splash.
🔄 Update checker for GitHub releases with DNS connectivity test and cache
🔤 UTF-8 Encoding and Decoding Utilities
int platform_isatty(int fd)
Definition util.c:70
int platform_get_last_error(void)
Definition util.c:101