ascii-chat 0.11.33
Video chat in your terminal
Loading...
Searching...
No Matches
terminal.h File Reference

πŸ–₯️ Cross-platform terminal interface for ascii-chat More...

Go to the source code of this file.

Data Structures

struct  terminal_size_t
 Terminal size structure. More...
 
struct  terminal_capabilities_t
 Complete terminal capabilities structure. More...
 
struct  tty_info_t
 TTY detection and management structure. More...
 

Macros

#define TERMINAL_COLOR_THEME_LIGHT_FG_R   65
 Platform-specific getopt include.
 
#define TERMINAL_COLOR_THEME_LIGHT_FG_G   61
 
#define TERMINAL_COLOR_THEME_LIGHT_FG_B   61
 
#define TERMINAL_COLOR_THEME_DARK_FG_R   204
 Default text color for dark theme (RGB)
 
#define TERMINAL_COLOR_THEME_DARK_FG_G   204
 
#define TERMINAL_COLOR_THEME_DARK_FG_B   204
 
#define TERMINAL_COLOR_THEME_LIGHT_BG_R   255
 Default background color for light theme (RGB)
 
#define TERMINAL_COLOR_THEME_LIGHT_BG_G   255
 
#define TERMINAL_COLOR_THEME_LIGHT_BG_B   255
 
#define TERMINAL_COLOR_THEME_DARK_BG_R   0
 Default background color for dark theme (RGB)
 
#define TERMINAL_COLOR_THEME_DARK_BG_G   0
 
#define TERMINAL_COLOR_THEME_DARK_BG_B   0
 

Typedefs

typedef bool(* console_ctrl_handler_t) (console_ctrl_event_t event)
 Console control handler callback type.
 

Enumerations

enum  terminal_color_mode_t {
  TERM_COLOR_AUTO = -1 , TERM_COLOR_NONE = 0 , TERM_COLOR_16 = 1 , TERM_COLOR_256 = 2 ,
  TERM_COLOR_TRUECOLOR = 3
}
 Terminal color support levels. More...
 
enum  color_filter_t {
  COLOR_FILTER_NONE = 0 , COLOR_FILTER_BLACK = 1 , COLOR_FILTER_WHITE = 2 , COLOR_FILTER_GREEN = 3 ,
  COLOR_FILTER_MAGENTA = 4 , COLOR_FILTER_FUCHSIA = 5 , COLOR_FILTER_ORANGE = 6 , COLOR_FILTER_TEAL = 7 ,
  COLOR_FILTER_CYAN = 8 , COLOR_FILTER_PINK = 9 , COLOR_FILTER_RED = 10 , COLOR_FILTER_YELLOW = 11 ,
  COLOR_FILTER_RAINBOW = 12 , COLOR_FILTER_COUNT
}
 Monochromatic color filter enumeration. More...
 
enum  terminal_capability_flags_t {
  TERM_CAP_COLOR_16 = 0x0001 , TERM_CAP_COLOR_256 = 0x0002 , TERM_CAP_COLOR_TRUE = 0x0004 , TERM_CAP_UTF8 = 0x0008 ,
  TERM_CAP_BACKGROUND = 0x0010 , TERM_CAP_MATRIX_RAIN = 0x0020
}
 Terminal capability flags (bitmask) More...
 
enum  render_mode_t { RENDER_MODE_FOREGROUND = 0 , RENDER_MODE_BACKGROUND = 1 , RENDER_MODE_HALF_BLOCK = 2 }
 Render mode preferences. More...
 
enum  console_ctrl_event_t {
  CONSOLE_CTRL_C = 0 , CONSOLE_CTRL_BREAK = 1 , CONSOLE_CLOSE = 2 , CONSOLE_LOGOFF = 3 ,
  CONSOLE_SHUTDOWN = 4
}
 Console control event types (cross-platform Ctrl+C handling) More...
 

Functions

asciichat_error_t terminal_get_size (terminal_size_t *size)
 Get terminal size.
 
asciichat_error_t terminal_set_raw_mode (bool enable)
 Set terminal to raw mode.
 
asciichat_error_t terminal_set_echo (bool enable)
 Set terminal echo mode.
 
bool terminal_supports_color (void)
 Check if terminal supports color.
 
bool terminal_supports_unicode (void)
 Check if terminal supports unicode.
 
bool terminal_supports_utf8 (void)
 Check if terminal supports UTF-8.
 
asciichat_error_t terminal_clear_screen (void)
 Clear the terminal screen.
 
asciichat_error_t terminal_move_cursor (int row, int col)
 Move cursor to specified position.
 
asciichat_error_t terminal_move_cursor_relative (int offset)
 Move cursor relative to current position.
 
void terminal_enable_ansi (void)
 Enable ANSI escape sequences.
 
asciichat_error_t terminal_set_buffering (bool line_buffered)
 Set terminal buffering mode.
 
asciichat_error_t terminal_flush (int fd)
 Flush terminal output.
 
asciichat_error_t terminal_get_cursor_position (int *row, int *col)
 Get current cursor position.
 
asciichat_error_t terminal_save_cursor (void)
 Save cursor position.
 
asciichat_error_t terminal_restore_cursor (void)
 Restore saved cursor position.
 
asciichat_error_t terminal_set_title (const char *title)
 Set terminal window title.
 
asciichat_error_t terminal_ring_bell (void)
 Ring terminal bell.
 
asciichat_error_t terminal_cursor_hide (void)
 Hide terminal cursor.
 
asciichat_error_t terminal_cursor_show (void)
 Show terminal cursor.
 
asciichat_error_t terminal_set_scroll_region (int top, int bottom)
 Set scroll region.
 
asciichat_error_t terminal_reset (int fd)
 Reset terminal to default state.
 
asciichat_error_t terminal_cursor_home (int fd)
 Move cursor to home position (top-left)
 
asciichat_error_t terminal_clear_scrollback (int fd)
 Clear terminal scrollback buffer.
 
terminal_capabilities_t detect_terminal_capabilities (void)
 Detect terminal capabilities.
 
tty_info_t get_current_tty (void)
 Get current TTY information.
 
bool is_valid_tty_path (const char *path)
 Check if a TTY path is valid.
 
asciichat_error_t get_terminal_size (unsigned short int *width, unsigned short int *height)
 Get terminal size with multiple fallback methods.
 
const char * terminal_color_level_name (terminal_color_mode_t level)
 Get name of color level.
 
const char * terminal_capabilities_summary (const terminal_capabilities_t *caps)
 Get summary string of terminal capabilities.
 
void test_terminal_output_modes (void)
 Test terminal output modes.
 
terminal_capabilities_t apply_color_mode_override (terminal_capabilities_t caps)
 Apply command-line overrides to detected capabilities.
 
bool terminal_should_color_output (int fd)
 Determine if color output should be used.
 
terminal_color_mode_t terminal_get_effective_color_mode (void)
 Get current color mode considering all overrides.
 
bool terminal_has_dark_background (void)
 Detect if terminal theme is dark.
 
bool terminal_query_background_color (uint8_t *bg_r, uint8_t *bg_g, uint8_t *bg_b)
 Query terminal background color using OSC 11 escape sequence.
 
bool terminal_should_use_control_sequences (int fd)
 Check if terminal control sequences should be used for the given fd.
 
bool terminal_is_stdin_tty (void)
 Check if stdin is connected to a TTY.
 
bool terminal_is_stdout_tty (void)
 Check if stdout is connected to a TTY.
 
bool terminal_is_stderr_tty (void)
 Check if stderr is connected to a TTY.
 
bool terminal_is_interactive (void)
 Check if the session is fully interactive.
 
bool terminal_is_piped_output (void)
 Check if stdout is piped or redirected.
 
bool terminal_should_force_stderr (void)
 Determine if logs should be forced to stderr.
 
int terminal_choose_log_fd (log_level_t level)
 Choose output file descriptor for logging based on level and interactivity.
 
bool terminal_can_prompt_user (void)
 Determine if interactive user prompts are appropriate.
 
bool platform_set_console_ctrl_handler (console_ctrl_handler_t handler)
 Register a console control handler (for Ctrl+C, etc.)
 
int platform_isatty (int fd)
 Check if a file descriptor is a terminal.
 
const char * platform_ttyname (int fd)
 Get the name of the terminal associated with a file descriptor.
 
void terminal_get_default_foreground_color (int theme, uint8_t *out_r, uint8_t *out_g, uint8_t *out_b)
 Get theme-aware default foreground color for pixel renderers.
 
void terminal_get_default_background_color (int theme, uint8_t *out_r, uint8_t *out_g, uint8_t *out_b)
 Get theme-aware default background color for pixel renderers.
 
unsigned short int terminal_get_effective_width (void)
 Get effective terminal width with fallback priority.
 
unsigned short int terminal_get_effective_height (void)
 Get effective terminal height with fallback priority.
 
void terminal_stop_resize_detection (void)
 No-op stub on POSIX platforms (no resize detection thread)
 

Detailed Description

πŸ–₯️ Cross-platform terminal interface for ascii-chat

Definition in file terminal.h.

Typedef Documentation

◆ console_ctrl_handler_t

typedef bool(* console_ctrl_handler_t) (console_ctrl_event_t event)

Console control handler callback type.

Parameters
eventThe control event that occurred
Returns
true if the event was handled, false to pass to next handler
Note
On Windows, this is called from a separate thread, not from signal context
On Unix, this is called from signal context (limited safe operations)

Definition at line 1229 of file terminal.h.

Enumeration Type Documentation

◆ color_filter_t

Monochromatic color filter enumeration.

Defines color filters for applying single-color tints to grayscale video. Filters are applied server-side; clients see each user in their chosen color.

Enumerator
COLOR_FILTER_NONE 

No filtering (default)

COLOR_FILTER_BLACK 

Dark content on white background.

COLOR_FILTER_WHITE 

White content on black background.

COLOR_FILTER_GREEN 

Green (#00FF41)

COLOR_FILTER_MAGENTA 

Magenta (#FF00FF)

COLOR_FILTER_FUCHSIA 

Fuchsia (#FF00AA)

COLOR_FILTER_ORANGE 

Orange (#FF8800)

COLOR_FILTER_TEAL 

Teal (#00DDDD)

COLOR_FILTER_CYAN 

Cyan (#00FFFF)

COLOR_FILTER_PINK 

Pink (#FFB6C1)

COLOR_FILTER_RED 

Red (#FF3333)

COLOR_FILTER_YELLOW 

Yellow (#FFEB99)

COLOR_FILTER_RAINBOW 

Rainbow (cycles through spectrum over 3.5s)

COLOR_FILTER_COUNT 

Total count of filters (not a valid filter)

Definition at line 599 of file terminal.h.

599 {
621 COLOR_FILTER_RED = 10,
color_filter_t
Monochromatic color filter enumeration.
Definition terminal.h:599
@ COLOR_FILTER_WHITE
White content on black background.
Definition terminal.h:605
@ COLOR_FILTER_FUCHSIA
Fuchsia (#FF00AA)
Definition terminal.h:611
@ COLOR_FILTER_NONE
No filtering (default)
Definition terminal.h:601
@ COLOR_FILTER_TEAL
Teal (#00DDDD)
Definition terminal.h:615
@ COLOR_FILTER_CYAN
Cyan (#00FFFF)
Definition terminal.h:617
@ COLOR_FILTER_GREEN
Green (#00FF41)
Definition terminal.h:607
@ COLOR_FILTER_COUNT
Total count of filters (not a valid filter)
Definition terminal.h:627
@ COLOR_FILTER_MAGENTA
Magenta (#FF00FF)
Definition terminal.h:609
@ COLOR_FILTER_RAINBOW
Rainbow (cycles through spectrum over 3.5s)
Definition terminal.h:625
@ COLOR_FILTER_RED
Red (#FF3333)
Definition terminal.h:621
@ COLOR_FILTER_YELLOW
Yellow (#FFEB99)
Definition terminal.h:623
@ COLOR_FILTER_PINK
Pink (#FFB6C1)
Definition terminal.h:619
@ COLOR_FILTER_BLACK
Dark content on white background.
Definition terminal.h:603
@ COLOR_FILTER_ORANGE
Orange (#FF8800)
Definition terminal.h:613

◆ console_ctrl_event_t

Console control event types (cross-platform Ctrl+C handling)

Enumerator
CONSOLE_CTRL_C 

Ctrl+C pressed (SIGINT equivalent)

CONSOLE_CTRL_BREAK 

Ctrl+Break pressed (Windows only, maps to SIGINT on Unix)

CONSOLE_CLOSE 

Console window closed

CONSOLE_LOGOFF 

User logoff event (Windows only)

CONSOLE_SHUTDOWN 

System shutdown event (Windows only)

Definition at line 1211 of file terminal.h.

1211 {
1212 CONSOLE_CTRL_C = 0,
1213 CONSOLE_CTRL_BREAK = 1,
1214 CONSOLE_CLOSE = 2,
1215 CONSOLE_LOGOFF = 3,
1216 CONSOLE_SHUTDOWN = 4
console_ctrl_event_t
Console control event types (cross-platform Ctrl+C handling)
Definition terminal.h:1211
@ CONSOLE_CTRL_BREAK
Definition terminal.h:1213
@ CONSOLE_SHUTDOWN
Definition terminal.h:1216
@ CONSOLE_LOGOFF
Definition terminal.h:1215
@ CONSOLE_CTRL_C
Definition terminal.h:1212
@ CONSOLE_CLOSE
Definition terminal.h:1214

◆ render_mode_t

Render mode preferences.

Enumeration of rendering modes for ASCII art output. Different modes provide different visual effects and require different terminal capabilities.

Enumerator
RENDER_MODE_FOREGROUND 

Foreground colors only (text color)

RENDER_MODE_BACKGROUND 

Background colors (block colors)

RENDER_MODE_HALF_BLOCK 

Unicode half-block characters (mixed foreground/background)

Definition at line 662 of file terminal.h.

662 {
render_mode_t
Render mode preferences.
Definition terminal.h:662
@ RENDER_MODE_FOREGROUND
Foreground colors only (text color)
Definition terminal.h:664
@ RENDER_MODE_BACKGROUND
Background colors (block colors)
Definition terminal.h:666
@ RENDER_MODE_HALF_BLOCK
Unicode half-block characters (mixed foreground/background)
Definition terminal.h:668

◆ terminal_capability_flags_t

Terminal capability flags (bitmask)

Bitmask enumeration for terminal capabilities. Multiple flags can be combined to indicate support for various features. Used in terminal capability detection and rendering optimization.

Enumerator
TERM_CAP_COLOR_16 

16-color support (TERM_CAP_COLOR_16)

TERM_CAP_COLOR_256 

256-color support (TERM_CAP_COLOR_256)

TERM_CAP_COLOR_TRUE 

Truecolor support (TERM_CAP_COLOR_TRUE)

TERM_CAP_UTF8 

UTF-8 encoding support (TERM_CAP_UTF8)

TERM_CAP_BACKGROUND 

Background color support (TERM_CAP_BACKGROUND)

TERM_CAP_MATRIX_RAIN 

Client requests Matrix digital-rain post-processing.

Definition at line 639 of file terminal.h.

639 {
641 TERM_CAP_COLOR_16 = 0x0001,
643 TERM_CAP_COLOR_256 = 0x0002,
645 TERM_CAP_COLOR_TRUE = 0x0004,
647 TERM_CAP_UTF8 = 0x0008,
649 TERM_CAP_BACKGROUND = 0x0010,
651 TERM_CAP_MATRIX_RAIN = 0x0020
terminal_capability_flags_t
Terminal capability flags (bitmask)
Definition terminal.h:639
@ TERM_CAP_COLOR_256
256-color support (TERM_CAP_COLOR_256)
Definition terminal.h:643
@ TERM_CAP_COLOR_16
16-color support (TERM_CAP_COLOR_16)
Definition terminal.h:641
@ TERM_CAP_UTF8
UTF-8 encoding support (TERM_CAP_UTF8)
Definition terminal.h:647
@ TERM_CAP_MATRIX_RAIN
Client requests Matrix digital-rain post-processing.
Definition terminal.h:651
@ TERM_CAP_BACKGROUND
Background color support (TERM_CAP_BACKGROUND)
Definition terminal.h:649
@ TERM_CAP_COLOR_TRUE
Truecolor support (TERM_CAP_COLOR_TRUE)
Definition terminal.h:645

◆ terminal_color_mode_t

Terminal color support levels.

Enumeration of terminal color capability levels from no color support to full 24-bit truecolor support. Used for capability detection and rendering mode selection.

Color palette sizes:

  • NONE: 2 colors (black and white)
  • 16: 16 ANSI colors (black, red, green, yellow, blue, magenta, cyan, white + bright variants)
  • 256: 256-color palette (16 base + 216 RGB cube + 24 grayscale)
  • TRUECOLOR: 16,777,216 colors (24-bit RGB, 256 levels per channel)

Detection method:

  • Auto-detect from $TERM and $COLORTERM environment variables
  • Falls back to terminal type database lookups
  • Can be overridden with command-line flags (–color, –256, –truecolor)

Common terminal capabilities:

  • xterm, xterm-256color, xterm-truecolor
  • Linux console (VT100, color, 256color)
  • iTerm2 (auto-detects truecolor)
  • Windows Console (Windows 10+ supports ANSI)
  • tmux (supports truecolor with proper configuration)
Enumerator
TERM_COLOR_AUTO 

Auto-detect color support from terminal capabilities.

TERM_COLOR_NONE 

No color support (monochrome terminal)

TERM_COLOR_16 

16-color support (standard ANSI colors)

TERM_COLOR_256 

256-color support (extended ANSI palette)

TERM_COLOR_TRUECOLOR 

24-bit truecolor support (RGB colors)

Definition at line 578 of file terminal.h.

578 {
580 TERM_COLOR_AUTO = -1,
582 TERM_COLOR_NONE = 0,
584 TERM_COLOR_16 = 1,
586 TERM_COLOR_256 = 2,
terminal_color_mode_t
Terminal color support levels.
Definition terminal.h:578
@ TERM_COLOR_NONE
No color support (monochrome terminal)
Definition terminal.h:582
@ TERM_COLOR_16
16-color support (standard ANSI colors)
Definition terminal.h:584
@ TERM_COLOR_256
256-color support (extended ANSI palette)
Definition terminal.h:586
@ TERM_COLOR_AUTO
Auto-detect color support from terminal capabilities.
Definition terminal.h:580
@ TERM_COLOR_TRUECOLOR
24-bit truecolor support (RGB colors)
Definition terminal.h:588

Function Documentation

◆ apply_color_mode_override()

terminal_capabilities_t apply_color_mode_override ( terminal_capabilities_t  caps)

Apply command-line overrides to detected capabilities.

Parameters
capsTerminal capabilities structure to modify
Returns
Modified terminal capabilities structure

Applies any command-line option overrides to the detected terminal capabilities. Overrides may include:

  • Force color mode (–color, –no-color, –256, –truecolor)
  • Force UTF-8 mode (–utf8)
  • Render mode selection (–bg, –fg, –half-block)
  • Palette selection (–palette)
Note
Returns a modified copy of the input structure.
Overrides take precedence over detected capabilities.

Definition at line 29 of file misc.c.

29 {
30 return caps;
31}

Referenced by main(), session_display_create(), and threaded_send_terminal_size_with_auto_detect().

◆ detect_terminal_capabilities()

terminal_capabilities_t detect_terminal_capabilities ( void  )

Detect terminal capabilities.

Returns
Terminal capabilities structure with all detected features

Comprehensively detects terminal capabilities including:

  • Color support level (none, 16, 256, truecolor)
  • UTF-8 encoding support
  • Terminal type and environment variables
  • Render mode preferences
  • Detection reliability

Detection uses multiple methods:

  • Environment variable analysis ($TERM, $COLORTERM, $LC_ALL, $LANG)
  • Terminal type database lookups
  • Runtime capability queries (where available)
Note
Returns a structure with all detected capabilities.
Detection reliability is indicated by detection_reliable field.
Use apply_color_mode_override() to apply command-line overrides.

Definition at line 169 of file platform/wasm/terminal.c.

169 {
170 terminal_capabilities_t caps = {0};
172 caps.capabilities = 0;
173 caps.color_count = 16777216;
174 caps.utf8_support = true;
175 caps.detection_reliable = true;
176 caps.render_mode = RENDER_MODE_FOREGROUND; // Default to foreground mode
177 platform_strlcpy(caps.term_type, "xterm-256color", sizeof(caps.term_type));
178 platform_strlcpy(caps.colorterm, "truecolor", sizeof(caps.colorterm));
179 caps.wants_background = true;
180 caps.palette_type = 0; // Default palette
181 // Browser rendering uses requestAnimationFrame and supports the same
182 // 60 FPS default as the native terminal paths.
185 return caps;
186}
#define DEFAULT_MAX_FPS
Default maximum frame rate (frames per second)
Definition limits.h:29
size_t platform_strlcpy(char *dst, const char *src, size_t size)
Safe string copy with size tracking (strlcpy)
Complete terminal capabilities structure.
Definition terminal.h:709
int palette_type
Palette type enum value (palette_type_t)
Definition terminal.h:729
terminal_color_mode_t color_level
Detected color support level (terminal_color_mode_t)
Definition terminal.h:711
uint8_t desired_fps
Client's desired frame rate (1-144 FPS)
Definition terminal.h:733
render_mode_t render_mode
Preferred rendering mode (render_mode_t)
Definition terminal.h:721
bool utf8_support
True if terminal supports UTF-8 encoding.
Definition terminal.h:717
uint32_t capabilities
Capability flags bitmask (terminal_capability_flags_t)
Definition terminal.h:713
uint32_t color_count
Maximum number of colors (2, 16, 256, or 16777216)
Definition terminal.h:715
color_filter_t color_filter
Monochromatic color filter enum value (color_filter_t)
Definition terminal.h:735
char term_type[64]
$TERM environment variable value (for debugging)
Definition terminal.h:723
char colorterm[64]
$COLORTERM environment variable value (for debugging)
Definition terminal.h:725
bool detection_reliable
True if detection is confident (reliable detection)
Definition terminal.h:719
bool wants_background
True if background colors are preferred.
Definition terminal.h:727

References terminal_capabilities_t::capabilities, terminal_capabilities_t::color_count, terminal_capabilities_t::color_filter, COLOR_FILTER_NONE, terminal_capabilities_t::color_level, terminal_capabilities_t::colorterm, DEFAULT_MAX_FPS, terminal_capabilities_t::desired_fps, terminal_capabilities_t::detection_reliable, terminal_capabilities_t::palette_type, platform_strlcpy(), terminal_capabilities_t::render_mode, RENDER_MODE_FOREGROUND, TERM_COLOR_TRUECOLOR, terminal_capabilities_t::term_type, terminal_capabilities_t::utf8_support, and terminal_capabilities_t::wants_background.

Referenced by action_show_capabilities_immediate(), log_redetect_terminal_capabilities(), main(), session_display_create(), and threaded_send_terminal_size_with_auto_detect().

◆ get_current_tty()

tty_info_t get_current_tty ( void  )

Get current TTY information.

Returns
TTY information structure with file descriptor and path

Retrieves information about the current TTY (terminal). Returns file descriptor for TTY access, device path, and ownership information. Useful for advanced terminal operations that require direct TTY access.

Note
File descriptor may need to be closed if owns_fd is true.
TTY path is platform-specific (Unix: /dev/tty, Windows: CON, etc.).

Definition at line 24 of file misc.c.

24 {
25 tty_info_t tty = {0};
26 return tty;
27}
TTY detection and management structure.
Definition terminal.h:753

Referenced by session_display_create().

◆ get_terminal_size()

asciichat_error_t get_terminal_size ( unsigned short int *  width,
unsigned short int *  height 
)

Get terminal size with multiple fallback methods.

Parameters
widthPointer to store width in columns (must not be NULL)
heightPointer to store height in rows (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Detects terminal size using multiple fallback methods for reliability:

  1. Terminal size query (ioctl TIOCGWINSZ on Unix, Console API on Windows)
  2. Environment variable fallback ($COLUMNS, $LINES)
  3. Default size fallback (80x24) if all methods fail
Note
On failure, output parameters are not modified.
Terminal size may change if terminal is resized.
This function is more reliable than terminal_get_size() due to fallbacks.

Definition at line 103 of file platform/wasm/terminal.c.

103 {
104 if (!width || !height) {
105 return ERROR_INVALID_PARAM;
106 }
107 int cols, rows;
108 if (platform_get_terminal_size(&cols, &rows) != 0) {
109 return ERROR_PLATFORM_INIT;
110 }
111 *width = (unsigned short int)cols;
112 *height = (unsigned short int)rows;
113 return ASCIICHAT_OK;
114}
@ ERROR_PLATFORM_INIT
Definition error_codes.h:60
@ ASCIICHAT_OK
Definition error_codes.h:51
@ ERROR_INVALID_PARAM
int platform_get_terminal_size(int *cols, int *rows)

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_PLATFORM_INIT, and platform_get_terminal_size().

Referenced by session_render_loop(), update_dimensions_for_full_height(), and update_dimensions_to_terminal_size().

◆ is_valid_tty_path()

bool is_valid_tty_path ( const char *  path)

Check if a TTY path is valid.

Parameters
pathPath to check (must not be NULL)
Returns
true if path is valid TTY device, false otherwise

Validates that a path points to a valid TTY (terminal) device. Checks device file existence and type on Unix systems.

Note
Returns false for non-TTY devices or invalid paths.
Useful for validating TTY paths before use.

◆ platform_isatty()

int platform_isatty ( int  fd)

Check if a file descriptor is a terminal.

Parameters
fdFile descriptor to check
Returns
Non-zero if fd is a terminal, 0 otherwise

Definition at line 63 of file util.c.

63 {
64 (void)fd;
65 return 1; // Always true for the browser terminal
66}

Referenced by session_display_create(), splash_intro_start(), terminal_is_stderr_tty(), terminal_is_stdin_tty(), terminal_is_stdout_tty(), terminal_should_color_output(), terminal_should_use_control_sequences(), and ui_status_display().

◆ platform_set_console_ctrl_handler()

bool platform_set_console_ctrl_handler ( console_ctrl_handler_t  handler)

Register a console control handler (for Ctrl+C, etc.)

Parameters
handlerHandler function to register, or NULL to unregister
Returns
true on success, false on failure

This provides cross-platform handling for console control events like Ctrl+C.

  • On Windows: Uses SetConsoleCtrlHandler() for proper signal handling
  • On Unix: Uses sigaction() for SIGINT/SIGTERM handling

Unlike platform_signal() which uses CRT signal() on Windows (known issues), this function uses the native Windows API for reliable Ctrl+C handling.

Note
Only one handler is supported at a time. Registering a new handler replaces the previous one.

Referenced by setup_signal_handlers().

◆ platform_ttyname()

const char * platform_ttyname ( int  fd)

Get the name of the terminal associated with a file descriptor.

Parameters
fdFile descriptor
Returns
Pointer to terminal name string (or NULL), may be static, do not free

Returns the name of the terminal device associated with the file descriptor.

Note
The returned string may be a static buffer. Do not modify or free it.

◆ terminal_can_prompt_user()

bool terminal_can_prompt_user ( void  )

Determine if interactive user prompts are appropriate.

Returns
true if prompts can be shown, false if non-interactive/automated

Determines whether interactive user prompts (yes/no, passwords, confirmations) should be displayed. Returns false in non-interactive or automated contexts.

Use this to decide whether:

  • Password prompts should be shown (or auto-cancel)
  • Yes/No confirmations should wait for input (or use defaults)
  • Known hosts prompts should be interactive (or auto-deny)

Logic:

  1. If not fully interactive (stdin or stdout not TTY) β†’ false
  2. If in snapshot mode (–snapshot) β†’ false
  3. If ASCII_CHAT_QUESTION_PROMPT_RESPONSE set β†’ false (automated responses)
  4. Otherwise β†’ true (interactive prompts OK)

Examples:

  • ascii-chat client in terminal β†’ true (can prompt)
  • ascii-chat client --snapshot β†’ false (non-interactive mode)
  • echo data | ascii-chat client β†’ false (stdin piped)
  • ‘ASCII_CHAT_QUESTION_PROMPT_RESPONSE='y’ ascii-chat clientβ†’ false (automated) -ascii-chat client > output.txt` β†’ false (stdout redirected)
Note
Combines checks for: TTY status, snapshot mode, automation env vars
Used by password prompts, known_hosts verification, user confirmations
When false, password prompts should auto-cancel with error
When false, yes/no prompts should use default value or deny

Definition at line 215 of file platform/terminal.c.

215 {
216 // Must be fully interactive (stdin and stdout are TTYs)
218 return false;
219 }
220
221 // Must not be in snapshot mode (non-interactive capture)
222 if (GET_OPTION(snapshot_mode)) {
223 return false;
224 }
225
226 // Must not have automated prompt responses configured
227 const char *auto_response = SAFE_GETENV("ASCII_CHAT_QUESTION_PROMPT_RESPONSE");
228 if (auto_response && *auto_response != '\0') {
229 // NOLINTNEXTLINE(readability-simplify-boolean-expr) - Intentional check for configured automated responses
230 return false;
231 }
232
233 // All checks passed, interactive prompts are appropriate
234 return true;
235}
#define SAFE_GETENV(name)
Definition common.h:434
#define GET_OPTION(field)
Safely get a specific option field (lock-free read)
bool terminal_is_interactive(void)
Check if the session is fully interactive.

References GET_OPTION, SAFE_GETENV, and terminal_is_interactive().

Referenced by prompt_unknown_host().

◆ terminal_capabilities_summary()

const char * terminal_capabilities_summary ( const terminal_capabilities_t *  caps)

Get summary string of terminal capabilities.

Parameters
capsTerminal capabilities structure (must not be NULL)
Returns
Summary string describing capabilities (may be static, do not free)

Generates a human-readable summary string describing the terminal's capabilities including color level, UTF-8 support, and render mode. Useful for logging and debugging terminal configuration.

Note
Returns static string (do not free).
Summary format: "16-color, UTF-8, foreground mode" (example).

◆ terminal_choose_log_fd()

int terminal_choose_log_fd ( log_level_t  level)

Choose output file descriptor for logging based on level and interactivity.

Parameters
levelLog level (determines default routing: WARN+ to stderr, others to stdout)
Returns
STDERR_FILENO or STDOUT_FILENO based on log level and terminal state

Routes logs appropriately:

  • When terminal is NOT interactive (piped): ALL logs to stderr
  • When force_stderr enabled: ALL logs to stderr
  • Otherwise: WARN/ERROR/FATAL to stderr, others to stdout

This consolidates log routing logic used throughout the codebase.

Note
Use: int fd = terminal_choose_log_fd(LOG_INFO);
Common usage: platform_write_all(terminal_choose_log_fd(level), data, len);

Definition at line 237 of file platform/terminal.c.

237 {
238 // When force_stderr is enabled (client mode), send ALL logs to stderr
239 // When terminal is NOT interactive (piped/redirected), send ALL logs to stderr
240 // to keep stdout clean for piped data (JSON, frames, etc.)
242 return STDERR_FILENO;
243 }
244
245 // In interactive mode, route based on level:
246 // WARN and above (ERROR, FATAL) go to stderr
247 // Others (DEV, DEBUG, INFO) go to stdout
248 if (level >= LOG_WARN) {
249 return STDERR_FILENO;
250 }
251
252 return STDOUT_FILENO;
253}
bool log_get_force_stderr(void)
Get current force_stderr setting.
Definition log/log.c:725
#define LOG_WARN
Definition types.h:41

References log_get_force_stderr(), LOG_WARN, and terminal_is_interactive().

Referenced by log_console_impl(), log_msg(), and log_plain_msg().

◆ terminal_color_level_name()

const char * terminal_color_level_name ( terminal_color_mode_t  level)

Get name of color level.

Parameters
levelColor level enum value (terminal_color_mode_t)
Returns
Human-readable color level name (e.g., "16-color", "truecolor")

Converts a terminal color level enum value to a human-readable string name. Useful for logging and debugging terminal capability detection.

Note
Returns static string (do not free).
Returns "unknown" for invalid level values.

Referenced by action_show_capabilities_immediate(), and handle_client_capabilities_packet().

◆ terminal_get_default_background_color()

void terminal_get_default_background_color ( int  theme,
uint8_t *  out_r,
uint8_t *  out_g,
uint8_t *  out_b 
)

Get theme-aware default background color for pixel renderers.

Parameters
themeTerminal theme (0=dark, 1=light, 2=auto)
out_rPointer to store red component (0-255)
out_gPointer to store green component (0-255)
out_bPointer to store blue component (0-255)

Used by both Linux and macOS renderers for consistent color selection. Returns appropriate background color based on terminal theme.

Get theme-aware default background color for pixel renderers.

Parameters
themeTerminal theme (dark or light)
out_rPointer to store red component (0-255)
out_gPointer to store green component (0-255)
out_bPointer to store blue component (0-255)

Returns appropriate default background color based on terminal theme. Light theme uses white background, dark theme uses black background.

Definition at line 291 of file platform/terminal.c.

291 {
292 if (theme == 1) { // TERM_RENDERER_THEME_LIGHT
296 } else { // TERM_RENDERER_THEME_DARK or TERM_RENDERER_THEME_AUTO
300 }
301}
#define TERMINAL_COLOR_THEME_LIGHT_BG_R
Default background color for light theme (RGB)
Definition terminal.h:135
#define TERMINAL_COLOR_THEME_DARK_BG_G
Definition terminal.h:145
#define TERMINAL_COLOR_THEME_LIGHT_BG_B
Definition terminal.h:137
#define TERMINAL_COLOR_THEME_DARK_BG_B
Definition terminal.h:146
#define TERMINAL_COLOR_THEME_DARK_BG_R
Default background color for dark theme (RGB)
Definition terminal.h:144
#define TERMINAL_COLOR_THEME_LIGHT_BG_G
Definition terminal.h:136

References TERMINAL_COLOR_THEME_DARK_BG_B, TERMINAL_COLOR_THEME_DARK_BG_G, TERMINAL_COLOR_THEME_DARK_BG_R, TERMINAL_COLOR_THEME_LIGHT_BG_B, TERMINAL_COLOR_THEME_LIGHT_BG_G, and TERMINAL_COLOR_THEME_LIGHT_BG_R.

Referenced by term_renderer_feed().

◆ terminal_get_default_foreground_color()

void terminal_get_default_foreground_color ( int  theme,
uint8_t *  out_r,
uint8_t *  out_g,
uint8_t *  out_b 
)

Get theme-aware default foreground color for pixel renderers.

Parameters
themeTerminal theme (0=dark, 1=light, 2=auto)
out_rPointer to store red component (0-255)
out_gPointer to store green component (0-255)
out_bPointer to store blue component (0-255)

Used by both Linux and macOS renderers for consistent color selection. Returns appropriate text color based on terminal theme.

Get theme-aware default foreground color for pixel renderers.

Parameters
themeTerminal theme (dark or light)
out_rPointer to store red component (0-255)
out_gPointer to store green component (0-255)
out_bPointer to store blue component (0-255)

Returns appropriate default text color based on terminal theme. Both Linux and macOS renderers use this for consistent color selection.

Definition at line 269 of file platform/terminal.c.

269 {
270 if (theme == 1) { // TERM_RENDERER_THEME_LIGHT
274 } else { // TERM_RENDERER_THEME_DARK or TERM_RENDERER_THEME_AUTO
278 }
279}
#define TERMINAL_COLOR_THEME_DARK_FG_B
Definition terminal.h:128
#define TERMINAL_COLOR_THEME_LIGHT_FG_G
Definition terminal.h:117
#define TERMINAL_COLOR_THEME_DARK_FG_R
Default text color for dark theme (RGB)
Definition terminal.h:126
#define TERMINAL_COLOR_THEME_DARK_FG_G
Definition terminal.h:127
#define TERMINAL_COLOR_THEME_LIGHT_FG_B
Definition terminal.h:118
#define TERMINAL_COLOR_THEME_LIGHT_FG_R
Platform-specific getopt include.
Definition terminal.h:116

References TERMINAL_COLOR_THEME_DARK_FG_B, TERMINAL_COLOR_THEME_DARK_FG_G, TERMINAL_COLOR_THEME_DARK_FG_R, TERMINAL_COLOR_THEME_LIGHT_FG_B, TERMINAL_COLOR_THEME_LIGHT_FG_G, and TERMINAL_COLOR_THEME_LIGHT_FG_R.

Referenced by term_renderer_feed().

◆ terminal_get_effective_color_mode()

terminal_color_mode_t terminal_get_effective_color_mode ( void  )

Get current color mode considering all overrides.

Determines effective color mode by checking:

  1. –color flag (force enable)
  2. –color-mode option (none/16/256/truecolor)
  3. Terminal capability detection
Returns
Effective terminal_color_mode_t to use

Definition at line 107 of file platform/terminal.c.

107 {
108 // If colors are disabled entirely by terminal_should_color_output(), return NONE
109 if (!terminal_should_color_output(STDOUT_FILENO)) {
110 return TERM_COLOR_NONE;
111 }
112
113 // If --color-mode is set to specific value, use it
114 terminal_color_mode_t color_mode = GET_OPTION(color_mode);
115 if (color_mode != TERM_COLOR_AUTO) {
116 return color_mode;
117 }
118
119 // Otherwise auto-detect from terminal capabilities
120 // For now, return the detected color mode from terminal capabilities
121 // This will be used by apply_color_mode_override() if needed
122 return TERM_COLOR_AUTO; // Let the calling code handle auto-detection
123}
bool terminal_should_color_output(int fd)
Determine if color output should be used.

References GET_OPTION, TERM_COLOR_AUTO, TERM_COLOR_NONE, and terminal_should_color_output().

◆ terminal_get_effective_height()

unsigned short int terminal_get_effective_height ( void  )

Get effective terminal height with fallback priority.

Returns
Terminal height in characters with priority: option β†’ detected β†’ default

Returns the effective terminal height to use, checking in priority order:

  1. Option value: If --height was set to a non-zero value, return it
  2. Detected size: Try to detect actual terminal height via terminal_get_size()
  3. Default: Return OPT_HEIGHT_DEFAULT (70) as final fallback

This function simplifies the common pattern of "use option if set, else detect, else use default" that appears throughout the codebase for terminal dimension handling.

Note
Safe to call from any thread (uses lock-free option access)
Detection may fail on non-TTY output (piped/redirected), falls back gracefully
Height option defaults to 0, so non-zero means it was explicitly set

Usage Example:

// Old pattern (scattered throughout code):
unsigned short int height = GET_OPTION(height);
if (height == 0) {
height = size.rows;
} else {
}
}
// New pattern (unified):
unsigned short int height = terminal_get_effective_height();
#define OPT_HEIGHT_DEFAULT
Default terminal height in characters.
asciichat_error_t terminal_get_size(terminal_size_t *size)
Get terminal size.
unsigned short int terminal_get_effective_height(void)
Get effective terminal height with fallback priority.
Terminal size structure.
Definition terminal.h:163
int rows
Number of rows (height) in terminal.
Definition terminal.h:164

Returns height in priority order:

  1. Option height if set to non-zero value
  2. Detected terminal height
  3. OPT_HEIGHT_DEFAULT fallback

Definition at line 179 of file platform/terminal.c.

179 {
180 int height = GET_OPTION(height);
181
182 // If height option is explicitly set to non-zero, use it
183 if (height > 0) {
184 return (unsigned short int)height;
185 }
186
187 // Try to detect actual terminal height
188 terminal_size_t size;
189 if (terminal_get_size(&size) == ASCIICHAT_OK && size.rows > 0) {
190 return (unsigned short int)size.rows;
191 }
192
193 // Fallback to default
194 return OPT_HEIGHT_DEFAULT;
195}

References ASCIICHAT_OK, GET_OPTION, OPT_HEIGHT_DEFAULT, terminal_size_t::rows, and terminal_get_size().

Referenced by keyboard_help_render(), mirror_convert_frame(), protocol_start_connection(), server_connection_establish(), session_display_convert_to_ascii(), session_display_create(), session_render_loop(), session_settings_init(), splash_intro_start(), and update_banner_show_prompt().

◆ terminal_get_effective_width()

unsigned short int terminal_get_effective_width ( void  )

Get effective terminal width with fallback priority.

Returns
Terminal width in characters with priority: option β†’ detected β†’ default

Returns the effective terminal width to use, checking in priority order:

  1. Option value: If --width was set to a non-zero value, return it
  2. Detected size: Try to detect actual terminal width via terminal_get_size()
  3. Default: Return OPT_WIDTH_DEFAULT (110) as final fallback

This function simplifies the common pattern of "use option if set, else detect, else use default" that appears throughout the codebase for terminal dimension handling.

Note
Safe to call from any thread (uses lock-free option access)
Detection may fail on non-TTY output (piped/redirected), falls back gracefully
Width option defaults to 0, so non-zero means it was explicitly set

Usage Example:

// Old pattern (scattered throughout code):
unsigned short int width = GET_OPTION(width);
if (width == 0) {
width = size.cols;
} else {
}
}
// New pattern (unified):
unsigned short int width = terminal_get_effective_width();
#define OPT_WIDTH_DEFAULT
Default terminal width in characters.
unsigned short int terminal_get_effective_width(void)
Get effective terminal width with fallback priority.
int cols
Number of columns (width) in terminal.
Definition terminal.h:165

Returns width in priority order:

  1. Option width if set to non-zero value
  2. Detected terminal width
  3. OPT_WIDTH_DEFAULT fallback

Definition at line 153 of file platform/terminal.c.

153 {
154 int width = GET_OPTION(width);
155
156 // If width option is explicitly set to non-zero, use it
157 if (width > 0) {
158 return (unsigned short int)width;
159 }
160
161 // Try to detect actual terminal width
162 terminal_size_t size;
163 if (terminal_get_size(&size) == ASCIICHAT_OK && size.cols > 0) {
164 return (unsigned short int)size.cols;
165 }
166
167 // Fallback to default
168 return OPT_WIDTH_DEFAULT;
169}

References ASCIICHAT_OK, terminal_size_t::cols, GET_OPTION, OPT_WIDTH_DEFAULT, and terminal_get_size().

Referenced by keyboard_help_render(), mirror_convert_frame(), protocol_start_connection(), server_connection_establish(), session_display_convert_to_ascii(), session_display_create(), session_display_render_fps_overlay(), session_render_loop(), session_settings_init(), splash_intro_start(), and update_banner_show_prompt().

◆ terminal_has_dark_background()

bool terminal_has_dark_background ( void  )

Detect if terminal theme is dark.

Returns
true if terminal has a dark theme, false if light theme or unknown

Attempts to detect terminal's color theme (dark or light background) using:

  1. OSC 11 escape sequence query with luminance calculation (modern terminals)
  2. Common environment variables (COLORFGBG, TERM_PROGRAM)
  3. Terminal-specific hints (iTerm2, VS Code, Konsole, etc.)
  4. Defaults to dark theme (most common for developer terminals)

Used by the theme system to select appropriate colors throughout the UI:

  • Color schemes adapt based on detected theme
  • Highlight colors choose better contrast for the detected theme
  • Text colors are selected to work with the background theme
Note
This is a best-effort heuristic and may not be 100% accurate
Result is cached for performance (theme doesn't change during session)
User can override via TERM_BACKGROUND environment variable

Definition at line 158 of file platform/wasm/terminal.c.

158 {
159 return true; // Default to dark background for terminals
160}

Referenced by detect_terminal_background(), and render_file_create().

◆ terminal_is_interactive()

bool terminal_is_interactive ( void  )

Check if the session is fully interactive.

Returns
true if BOTH stdin AND stdout are TTYs, false otherwise

Determines whether the session is fully interactive (user at terminal). Returns true only when BOTH stdin and stdout are connected to TTYs.

Use this to decide whether:

  • User prompts and interactive input should be shown
  • Splash screens and animations should be displayed
  • Frame padding should be enabled
  • Password prompts are appropriate

Examples:

  • ascii-chat mirror in terminal β†’ true (interactive)
  • ascii-chat mirror | less β†’ false (stdout piped)
  • cat file | ascii-chat client β†’ false (stdin piped)
  • ascii-chat client < input.txt > output.txt β†’ false (both piped)
Note
Equivalent to: terminal_is_stdin_tty() && terminal_is_stdout_tty()
Used for enabling interactive features (prompts, padding, splash)
Snapshot mode is checked separately via GET_OPTION(snapshot_mode)

Definition at line 141 of file platform/terminal.c.

141 {
143}
bool terminal_is_stdin_tty(void)
Check if stdin is connected to a TTY.
bool terminal_is_stdout_tty(void)
Check if stdout is connected to a TTY.

References terminal_is_stdin_tty(), and terminal_is_stdout_tty().

Referenced by main(), options_init(), session_display_write_ascii(), session_render_loop(), session_server_like_run(), terminal_can_prompt_user(), terminal_choose_log_fd(), threaded_send_terminal_size_with_auto_detect(), ui_status_display(), and ui_status_display_interactive().

◆ terminal_is_piped_output()

bool terminal_is_piped_output ( void  )

Check if stdout is piped or redirected.

Returns
true if stdout is piped/redirected, false if connected to TTY

Determines whether standard output is being piped or redirected to a file. This is the logical inverse of terminal_is_stdout_tty().

Use this to decide whether:

  • Logs should be forced to stderr (to avoid corrupting piped output)
  • Frame padding should be disabled
  • Clean, parseable output should be preferred

Examples:

  • ascii-chat mirror > output.txt β†’ true (redirected)
  • ascii-chat client | grep pattern β†’ true (piped)
  • ascii-chat mirror in terminal β†’ false (TTY)
Note
Equivalent to: !terminal_is_stdout_tty()
Common pattern: force stderr when piped to prevent data corruption

Definition at line 197 of file platform/terminal.c.

197 {
198 return !terminal_is_stdout_tty();
199}

References terminal_is_stdout_tty().

Referenced by asciichat_shared_init(), log_init(), and terminal_should_force_stderr().

◆ terminal_is_stderr_tty()

bool terminal_is_stderr_tty ( void  )

Check if stderr is connected to a TTY.

Returns
true if stderr is a TTY, false otherwise

Determines whether standard error is connected to a terminal device. Returns false when stderr is piped or redirected to a file.

Use this to decide whether diagnostic messages should include colors.

Note
Wrapper around platform_isatty(STDERR_FILENO) for clarity
stderr is often a TTY even when stdout is piped

Definition at line 137 of file platform/terminal.c.

137 {
138 return platform_isatty(STDERR_FILENO) != 0;
139}
int platform_isatty(int fd)
Check if a file descriptor is a terminal.
Definition util.c:63

References platform_isatty().

◆ terminal_is_stdin_tty()

bool terminal_is_stdin_tty ( void  )

Check if stdin is connected to a TTY.

Returns
true if stdin is a TTY (can read interactive input), false otherwise

Determines whether standard input is connected to a terminal device. Returns false when stdin is piped or redirected from a file.

Use this to decide whether interactive input (prompts, keyboard events) is possible.

Note
Wrapper around platform_isatty(STDIN_FILENO) for clarity
Returns false in non-interactive environments (CI, scripts, pipes)

Definition at line 129 of file platform/terminal.c.

129 {
130 return platform_isatty(STDIN_FILENO) != 0;
131}

References platform_isatty().

Referenced by display_init(), session_client_like_run(), session_display_create(), session_render_loop(), terminal_is_interactive(), and threaded_send_terminal_size_with_auto_detect().

◆ terminal_is_stdout_tty()

bool terminal_is_stdout_tty ( void  )

Check if stdout is connected to a TTY.

Returns
true if stdout is a TTY (not piped/redirected), false otherwise

Determines whether standard output is connected to a terminal device. Returns false when stdout is piped or redirected to a file.

Use this to decide whether:

  • Terminal control sequences (colors, cursor movement) should be used
  • Output padding/formatting should be applied
  • Progress bars or animations should be shown
Note
Wrapper around platform_isatty(STDOUT_FILENO) for clarity
Returns false in piped contexts (e.g., ascii-chat client | less)

Definition at line 133 of file platform/terminal.c.

133 {
134 return platform_isatty(STDOUT_FILENO) != 0;
135}

References platform_isatty().

Referenced by session_client_like_run(), session_display_create(), session_render_loop(), terminal_is_interactive(), terminal_is_piped_output(), and threaded_send_terminal_size_with_auto_detect().

◆ terminal_query_background_color()

bool terminal_query_background_color ( uint8_t *  bg_r,
uint8_t *  bg_g,
uint8_t *  bg_b 
)

Query terminal background color using OSC 11 escape sequence.

Parameters
bg_rPointer to store red component (0-255)
bg_gPointer to store green component (0-255)
bg_bPointer to store blue component (0-255)
Returns
true if successful, false if query failed or timed out

Sends OSC 11 query to terminal and parses RGB response. Works with modern terminals (iTerm2, kitty, Konsole, etc.) Returns false if terminal doesn't support OSC 11 or times out.

Note
Requires raw terminal mode to read response
Has 100ms timeout to prevent hanging
Only works if stdout is a TTY

Definition at line 189 of file platform/wasm/terminal.c.

189 {
190 // Return dark background (black)
191 if (bg_r)
192 *bg_r = 0;
193 if (bg_g)
194 *bg_g = 0;
195 if (bg_b)
196 *bg_b = 0;
197 return true;
198}

◆ terminal_should_color_output()

bool terminal_should_color_output ( int  fd)

Determine if color output should be used.

Priority order:

  1. If –color flag is set β†’ ALWAYS use colors (force override)
  2. If CLAUDECODE env var is set β†’ NEVER use colors (LLM automation)
  3. If output is not a TTY (piping) β†’ NO colors
  4. If –color-mode=none β†’ NO colors (user choice)
  5. Otherwise β†’ Use colors
Parameters
fdFile descriptor to check (STDOUT_FILENO or STDERR_FILENO)
Returns
true if colors should be used, false otherwise

Definition at line 31 of file platform/terminal.c.

31 {
32 // Check color_mode setting - if explicitly set to NONE, disable colors
33 int color_mode = GET_OPTION(color_mode);
34 if (color_mode == COLOR_MODE_NONE) {
35 return false; // Color mode explicitly disabled
36 }
37
38 // Get current color setting (auto/true/false)
39 int color_setting = GET_OPTION(color);
40
41 // Priority 1: --color=true - Force colors ON (overrides everything)
42 if (color_setting == COLOR_SETTING_TRUE) {
43 return true; // ALWAYS colorize
44 }
45
46 // Priority 2: --color=false - Force colors OFF (overrides everything)
47 if (color_setting == COLOR_SETTING_FALSE) {
48 return false; // NEVER colorize
49 }
50
51 // Priority 3: --color=auto (default) - Smart detection
52 // Special case: Show colors for --help and --version even if not a TTY
53 // Check for help/version in global argv (set by main.c early)
54 if (g_argc > 1 && g_argv) {
55 for (int i = 1; i < g_argc; i++) {
56 if (strcmp(g_argv[i], "--help") == 0 || strcmp(g_argv[i], "-h") == 0 || strcmp(g_argv[i], "--version") == 0 ||
57 strcmp(g_argv[i], "-v") == 0 || strcmp(g_argv[i], "--show-capabilities") == 0) {
58 // For help/version/show-capabilities, use colors only if output is a TTY
59 // (respect piping convention: no colors unless --color=true)
60 int is_tty = platform_isatty(fd);
61 if (!is_tty) {
62 // Piping detected - fall through to check environment overrides
63 break;
64 }
65
66 // It's a TTY - show colors for help. Check environment overrides.
67 if (SAFE_GETENV("ASCII_CHAT_COLOR")) {
68 return true; // ASCII_CHAT_COLOR env var forces colors
69 }
70
71 // CLAUDECODE environment variable (LLM automation) - disable colors
72 if (SAFE_GETENV("CLAUDECODE")) {
73 return false; // NO colors in Claude Code environment
74 }
75
76 // For help output to TTY, show colors by default
77 return true;
78 }
79 }
80 }
81
82 // Check environment variable overrides
83 if (SAFE_GETENV("ASCII_CHAT_COLOR")) {
84 return true; // ASCII_CHAT_COLOR env var forces colors
85 }
86
87 // CLAUDECODE environment variable (LLM automation) - disable colors
88 if (SAFE_GETENV("CLAUDECODE")) {
89 return false; // NO colors in Claude Code environment
90 }
91
92 // Check if output is a TTY (pipe detection)
93 // Default: Use colors only if we have TTY and no environment overrides
94 return platform_isatty(fd);
95}
char ** g_argv
Global argv for early argument inspection (e.g., –color flag detection) Set by main() for access from...
Definition common.c:54
int g_argc
Global argc for early argument inspection (e.g., –color flag detection) Set by main() for access from...
Definition common.c:53
#define COLOR_MODE_NONE
Monochrome mode.
@ COLOR_SETTING_TRUE
Force colors ON: always colorize regardless of TTY/piping/CLAUDECODE.
@ COLOR_SETTING_FALSE
Force colors OFF: disable all colors and logging colors.

References COLOR_MODE_NONE, COLOR_SETTING_FALSE, COLOR_SETTING_TRUE, g_argc, g_argv, GET_OPTION, platform_isatty(), and SAFE_GETENV.

Referenced by action_show_capabilities_immediate(), action_show_version(), colored_string(), colorize_log_message(), log_plain_msg(), and terminal_get_effective_color_mode().

◆ terminal_should_force_stderr()

bool terminal_should_force_stderr ( void  )

Determine if logs should be forced to stderr.

Returns
true if logs should go to stderr only, false if stdout is acceptable

Determines whether logging output should be forced to stderr instead of stdout. Returns true when stdout is piped/redirected (to avoid corrupting output data).

Use this to decide whether to call log_set_force_stderr(true).

Logic:

  1. If stdout is piped/redirected β†’ force stderr (true)
  2. If in TESTING environment β†’ allow stdout (false)
  3. Otherwise β†’ allow stdout (false)

Examples:

  • ascii-chat mirror > frames.txt β†’ true (don't corrupt frame data)
  • ascii-chat mirror in terminal β†’ false (stdout is fine)
  • TESTING=1 ascii-chat mirror β†’ false (tests may capture stdout)
Note
This prevents logs from corrupting piped ASCII frame data
TESTING environment variable bypasses this for test environments
Typical usage: if (terminal_should_force_stderr()) log_set_force_stderr(true);

Definition at line 201 of file platform/terminal.c.

201 {
202 // If stdout is piped/redirected, force logs to stderr to avoid corruption
204 // Unless in TESTING environment where test framework may capture stdout
205 const char *testing = SAFE_GETENV("TESTING");
206 if (testing && strcmp(testing, "1") == 0) {
207 // NOLINTNEXTLINE(readability-simplify-boolean-expr) - Intentional logic for test environment override
208 return false;
209 }
210 return true; // Force stderr when piped
211 }
212 return false; // stdout is TTY, no need to force stderr
213}
bool terminal_is_piped_output(void)
Check if stdout is piped or redirected.

References SAFE_GETENV, and terminal_is_piped_output().

Referenced by main(), session_client_like_run(), and session_display_create().

◆ terminal_should_use_control_sequences()

bool terminal_should_use_control_sequences ( int  fd)

Check if terminal control sequences should be used for the given fd.

Parameters
fdFile descriptor to check (must be valid or -1)
Returns
true if terminal control sequences should be used, false otherwise

Determines whether terminal control sequences (cursor home, clear screen, etc.) should be sent to the given file descriptor. Checks:

  1. File descriptor is valid (>= 0)
  2. Not in snapshot mode
  3. Not in TESTING environment
  4. File descriptor is connected to a TTY (not piped/redirected)

This is useful for deciding whether to send ANSI escape sequences to output. When piped or redirected, escape sequences should not be sent.

Note
Returns false if fd is invalid (-1) to be safe.
Returns false in snapshot mode to provide clean output.
Checks TESTING environment variable for test/CI environments.
Primary use case: determining if output is going to a TTY.
Parameters
fdFile descriptor to check
Returns
true if terminal control sequences should be used, false otherwise

This function determines whether to send terminal POSITIONING and CONTROL sequences (cursor home, clear screen, hide cursor, etc.) which should only be sent to TTY and never to pipes/redirected output.

Note: This does NOT control ANSI COLOR CODES, which are controlled by –color-mode option and may be sent to pipes if explicitly requested.

Definition at line 315 of file platform/terminal.c.

315 {
316 if (fd < 0) {
317 return false;
318 }
319 if (GET_OPTION(snapshot_mode)) {
320 return false;
321 }
322 const char *testing_env = SAFE_GETENV("TESTING");
323 if (testing_env != NULL) {
324 return false;
325 }
326 return platform_isatty(fd) != 0;
327}

References GET_OPTION, platform_isatty(), and SAFE_GETENV.

Referenced by ascii_write(), ascii_write_destroy(), and ascii_write_init().

◆ terminal_stop_resize_detection()

void terminal_stop_resize_detection ( void  )

No-op stub on POSIX platforms (no resize detection thread)

Definition at line 91 of file misc.c.

91{}

Referenced by asciichat_shared_destroy().

◆ test_terminal_output_modes()

void test_terminal_output_modes ( void  )

Test terminal output modes.

Tests various terminal output modes to verify capabilities. Outputs test patterns for different color modes (16-color, 256-color, truecolor) and rendering modes to verify terminal behavior.

Note
This function outputs test patterns to stdout.
Useful for verifying terminal capability detection accuracy.