ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
colorize.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define LOG_COLORIZE_KEY_BUFFER_SIZE 256
9#define LOG_COLORIZE_VALUE_BUFFER_SIZE 512
10#define LOG_COLORIZE_PATTERN_BUFFER_SIZE 256
11#define LOG_COLORIZE_PATH_BUFFER_SIZE 512
12#define LOG_COLORIZE_VAR_BUFFER_SIZE 256
13#define LOG_COLORIZE_URL_BUFFER_SIZE 2048
14
15/* Existing buffer budgets in bytes, including NUL for text storage. */
16#define LOG_COLORIZE_SLOT_COUNT 4
17
19#include <ascii-chat/log/log.h>
21#include <libplatform/system.h>
22#include <libplatform/terminal.h>
24#include <ctype.h>
25#include <string.h>
26#include <stdio.h>
27#include <stdbool.h>
28
36static bool is_known_unit(const char *str, size_t max_len) {
37 if (!str || max_len == 0) {
38 return false;
39 }
40
41 // Known units: byte sizes, time units, frequency, percentage, and count descriptors
42 const char *known_units[] = {
43 // Byte sizes
44 "B",
45 "KB",
46 "MB",
47 "GB",
48 "TB",
49 "PB",
50 "EB",
51 "KiB",
52 "MiB",
53 "GiB",
54 "TiB",
55 "PiB",
56 "EiB",
57 // Time
58 "ms",
59 "us",
60 "ns",
61 "ps",
62 "s",
63 "sec",
64 "second",
65 "seconds",
66 "m",
67 "min",
68 "minute",
69 "minutes",
70 "h",
71 "hr",
72 "hour",
73 "hours",
74 // Frequency
75 "Hz",
76 "kHz",
77 "MHz",
78 "GHz",
79 // Percentage
80 "%",
81 // Count descriptors (commonly used in logs)
82 "items",
83 "item",
84 "entries",
85 "entry",
86 "packets",
87 "packet",
88 "frames",
89 "frame",
90 "messages",
91 "message",
92 "connections",
93 "connection",
94 "clients",
95 "client",
96 "events",
97 "event",
98 "bytes",
99 "bits",
100 "retries",
101 "retry",
102 "attempts",
103 "attempt",
104 "chunks",
105 "chunk",
106 "blocks",
107 "block",
108 };
109
110 const size_t num_units = sizeof(known_units) / sizeof(known_units[0]);
111 for (size_t i = 0; i < num_units; i++) {
112 size_t unit_len = strlen(known_units[i]);
113 if (unit_len > max_len) {
114 continue;
115 }
116 // Case-insensitive comparison for units
117 if (platform_strncasecmp(str, known_units[i], unit_len) == 0 && (unit_len == max_len || !isalpha(str[unit_len]))) {
118 return true;
119 }
120 }
121
122 return false;
123}
124
136static bool is_numeric_pattern(const char *str, size_t pos, size_t *end_pos) {
137 if (!isdigit(str[pos]) && str[pos] != '.') {
138 return false;
139 }
140
141 // Don't match numbers in the middle of words - check if preceded by alphanumeric, hyphen, or underscore
142 if (pos > 0 && (isalnum(str[pos - 1]) || str[pos - 1] == '-' || str[pos - 1] == '_')) {
143 return false;
144 }
145
146 size_t i = pos;
147
148 // Handle hex numbers (0x...)
149 if (str[i] == '0' && (str[i + 1] == 'x' || str[i + 1] == 'X')) {
150 i += 2;
151 while (isxdigit(str[i])) {
152 i++;
153 }
154 *end_pos = i;
155 return true;
156 }
157
158 // Handle regular numbers and decimals
159 bool has_digit = false;
160 while (isdigit(str[i])) {
161 has_digit = true;
162 i++;
163 }
164
165 // Handle decimal point
166 if (str[i] == '.' && isdigit(str[i + 1])) {
167 i++;
168 while (isdigit(str[i])) {
169 i++;
170 }
171 has_digit = true;
172 }
173
174 if (!has_digit) {
175 return false;
176 }
177
178 // Check for dimension format (1920x1080)
179 if (str[i] == 'x' || str[i] == 'X') {
180 if (isdigit(str[i + 1])) {
181 i++;
182 while (isdigit(str[i])) {
183 i++;
184 }
185 }
186 }
187
188 // Check for fraction format (1/2, 3/4, etc.)
189 if (str[i] == '/' && isdigit(str[i + 1])) {
190 i++;
191 while (isdigit(str[i])) {
192 i++;
193 }
194 }
195
196 // Check for known units with optional spaces (e.g., "25 MB", "1024 GiB", "69.9%")
197 // Only include units if they're in the known units list to avoid colorizing random words
198 size_t j = i;
199 bool has_space = false;
200
201 // First try: units immediately following (no space) like "69.9%"
202 if ((isalpha(str[j]) || str[j] == '%') && (j == i || !isalnum(str[j - 1]))) {
203 size_t unit_start = j;
204 while ((isalpha(str[j]) || str[j] == '%') && (j - unit_start) < 32) {
205 j++;
206 }
207 size_t unit_len = j - unit_start;
208
209 // Check if this is a known unit
210 if (is_known_unit(str + unit_start, unit_len)) {
211 // It's a known unit immediately following, include it
212 i = j;
213 } else {
214 // Not a known unit, reset j
215 j = i;
216 }
217 }
218
219 // Second try: units with spaces (e.g., "25 MB")
220 if (i == j) {
221 while (str[j] == ' ' || str[j] == '\t') {
222 has_space = true;
223 j++;
224 }
225
226 if (has_space && (isalpha(str[j]) || str[j] == '%')) {
227 // Collect potential unit (up to 32 characters)
228 size_t unit_start = j;
229 while ((isalpha(str[j]) || str[j] == '%') && (j - unit_start) < 32) {
230 j++;
231 }
232 size_t unit_len = j - unit_start;
233
234 // Check if this is a known unit
235 if (is_known_unit(str + unit_start, unit_len)) {
236 // It's a known unit, include the space and unit
237 i = j;
238 }
239 // Otherwise, don't include - just the number (i stays as is)
240 }
241 }
242
243 *end_pos = i;
244 return true;
245}
246
260static bool is_file_path(const char *str, size_t pos, size_t *end_pos) {
261 size_t i = pos;
262 bool found = false;
263
264 // Check for Windows absolute path (C:\...)
265 // NOLINTNEXTLINE(bugprone-branch-clone)
266 // NOLINTNEXTLINE(bugprone-branch-clone) - Each path type requires distinct handling
267 if (pos > 0 && isalpha(str[pos]) && str[pos + 1] == ':' && str[pos + 2] == '\\') {
268 i = pos + 2; // Start after the colon
269 found = true;
270 }
271 // Check for Windows UNC path (\\server\share) or Unix absolute path (/)
272 else if ((str[pos] == '\\' && str[pos + 1] == '\\') || str[pos] == '/') {
273 i = (str[pos] == '\\' && str[pos + 1] == '\\') ? pos + 2 : pos;
274 found = true;
275 }
276 // Check for relative path (., .., or alphanumeric followed by /)
277 else if ((str[pos] == '.' && (str[pos + 1] == '/' || str[pos + 1] == '\\')) || (str[pos] == '.' && str[pos + 1] == '.' && (str[pos + 2] == '/' || str[pos + 2] == '\\'))) {
278 i = pos;
279 found = true;
280 } else if (isalnum(str[pos]) || str[pos] == '_' || str[pos] == '-') {
281 // Could be start of relative path like "src/main.c"
282 // Look ahead for slash to confirm it's a path
283 size_t lookahead = pos;
284 while ((isalnum(str[lookahead]) || str[lookahead] == '_' || str[lookahead] == '-' || str[lookahead] == '.' || str[lookahead] == '/' || str[lookahead] == '\\') && str[lookahead] != '\0') {
285 if (str[lookahead] == '/' || str[lookahead] == '\\') {
286 // Found a slash, this is a path
287 i = pos;
288 found = true;
289 break;
290 }
291 lookahead++;
292 }
293 }
294
295 if (!found) {
296 return false;
297 }
298
299 // Collect the path characters
300 while (str[i] != '\0' && str[i] != ' ' && str[i] != '\t' && str[i] != '\n' && str[i] != ':' && str[i] != ',' && str[i] != ')' && str[i] != ']' && str[i] != '}' && str[i] != '"' && str[i] != '\'') {
301 if ((str[i] == '/' || str[i] == '\\') || isalnum(str[i]) || strchr("._-~", str[i])) {
302 i++;
303 } else {
304 break;
305 }
306 }
307
308 // Must have at least one slash to be a valid path
309 bool has_slash = false;
310 for (size_t j = pos; j < i; j++) {
311 if (str[j] == '/' || str[j] == '\\') {
312 has_slash = true;
313 break;
314 }
315 }
316
317 if (!has_slash) {
318 return false;
319 }
320
321 *end_pos = i;
322 return true;
323}
324
335static bool is_url(const char *str, size_t pos, size_t *end_pos) {
336 // Check for common URL schemes: http, https, ftp, ws, wss
337 const char *schemes[] = {"https://", "http://", "ftp://", "wss://", "ws://"};
338
339 // Try each scheme
340 for (size_t s = 0; s < sizeof(schemes) / sizeof(schemes[0]); s++) {
341 size_t scheme_len = strlen(schemes[s]);
342 if (strncmp(str + pos, schemes[s], scheme_len) == 0) {
343 // Found the scheme, now collect the URL
344 size_t i = pos + scheme_len;
345
346 // URL continues until whitespace, common punctuation, or special chars
347 // Stop at: space, tab, newline, ), ], }, ", ', <, >
348 while (str[i] != '\0' && str[i] != ' ' && str[i] != '\t' && str[i] != '\n' && str[i] != ')' && str[i] != ']' && str[i] != '}' && str[i] != '"' && str[i] != '\'' && str[i] != '<' &&
349 str[i] != '>' && str[i] != ',') {
350 i++;
351 }
352
353 // Must have at least one character after the scheme
354 if (i > pos + scheme_len) {
355 *end_pos = i;
356 return true;
357 }
358 }
359 }
360
361 return false;
362}
363
374static bool is_env_var(const char *str, size_t pos, size_t *end_pos) {
375 if (str[pos] != '$') {
376 return false;
377 }
378
379 size_t i = pos + 1;
380
381 // Environment variables should be all caps or underscore
382 if (!isupper(str[i]) && str[i] != '_') {
383 return false;
384 }
385
386 while ((isupper(str[i]) || str[i] == '_' || isdigit(str[i])) && str[i] != '\0') {
387 i++;
388 }
389
390 // Must have at least 2 characters ($X is too short)
391 if (i - pos < 2) {
392 return false;
393 }
394
395 *end_pos = i;
396 return true;
397}
398
405static log_color_t get_value_color(const char *value) {
406 if (!value || *value == '\0') {
407 return LOG_COLOR_FATAL; // Default to magenta for empty/unknown
408 }
409
410 size_t end_pos = 0;
411
412 // Try to detect value type in order of specificity
413 if (is_numeric_pattern(value, 0, &end_pos)) {
414 return LOG_COLOR_GREY; // Grey for numbers (matching line numbers and tid)
415 }
416
417 if (is_url(value, 0, &end_pos)) {
418 return LOG_COLOR_INFO; // Blue for URLs
419 }
420
421 if (is_file_path(value, 0, &end_pos)) {
422 return LOG_COLOR_DEBUG; // Cyan/Blue for paths
423 }
424
425 if (is_env_var(value, 0, &end_pos)) {
426 return LOG_COLOR_GREY; // Grey for environment variables
427 }
428
429 // Check for quoted strings or common value patterns
430 if ((value[0] == '"' || value[0] == '\'' || value[0] == '`') || strchr(value, ' ') != NULL) { // Space indicates likely string value
431 return LOG_COLOR_FATAL; // Magenta for strings/unknown values
432 }
433
434 // Default: magenta for unrecognized values
435 return LOG_COLOR_FATAL;
436}
437
451static bool is_key_value_pair(const char *str, size_t pos, size_t *key_end, size_t *value_start, size_t *value_end) {
452 // Check if we're at the start of an identifier (key)
453 if (!isalpha(str[pos]) && str[pos] != '_') {
454 return false;
455 }
456
457 // Must not be preceded by alphanumeric or underscore (to avoid matching mid-word)
458 if (pos > 0 && (isalnum(str[pos - 1]) || str[pos - 1] == '_')) {
459 return false;
460 }
461
462 size_t i = pos;
463
464 // Collect the key (alphanumeric and underscores)
465 while ((isalnum(str[i]) || str[i] == '_') && str[i] != '\0') {
466 i++;
467 }
468
469 size_t key_len = i - pos;
470
471 // Check for equals sign
472 if (str[i] != '=') {
473 return false;
474 }
475
476 i++; // Skip the equals sign
477
478 // Skip optional whitespace after equals (though unusual)
479 while (str[i] == ' ' || str[i] == '\t') {
480 i++;
481 }
482
483 // Record where the value actually starts
484 size_t val_start = i;
485
486 // Value continues until we hit whitespace or special ending characters
487 // Stop at: space, tab, newline, comma, semicolon, ), ], }, or null terminator
488 while (str[i] != '\0' && str[i] != ' ' && str[i] != '\t' && str[i] != '\n' && str[i] != ',' && str[i] != ';' && str[i] != ')' && str[i] != ']' && str[i] != '}') {
489 i++;
490 }
491
492 size_t value_len = i - val_start;
493
494 // Must have a non-empty value
495 if (value_len == 0) {
496 return false;
497 }
498
499 *key_end = pos + key_len; // Position after the key
500 *value_start = val_start; // Position where value begins
501 *value_end = i; // Position after the value
502 return true;
503}
504
514static void append_colored_token(char *output, size_t capacity, size_t *position, log_color_t color, const char *text) {
515 const char *start = log_level_color_for_output(color, true);
516 const char *reset = log_level_color_for_output(LOG_COLOR_RESET, true);
517 size_t start_len = start ? strlen(start) : 0, text_len = strlen(text), reset_len = reset ? strlen(reset) : 0;
518 if (*position >= capacity || start_len + text_len + reset_len >= capacity - *position)
519 return;
520 if (start_len)
521 memcpy(output + *position, start, start_len);
522 *position += start_len;
523 memcpy(output + *position, text, text_len);
524 *position += text_len;
525 if (reset_len)
526 memcpy(output + *position, reset, reset_len);
527 *position += reset_len;
528}
529
530const char *colorize_log_message(const char *message) {
531 if (!message)
532 return message;
534}
535
536const char *colorize_log_message_with_color(const char *message, bool enabled) {
537 if (!message || !enabled) {
538 return message;
539 }
540
541 // Keep concurrent report formatting separate while allowing nested calls.
542 static _Thread_local char buffers[LOG_COLORIZE_SLOT_COUNT][LOG_MSG_BUFFER_SIZE];
543 static _Thread_local int buffer_index = 0;
544
545 char *output = buffers[buffer_index];
546 buffer_index = (buffer_index + 1) % 4;
547
548 size_t out_pos = 0;
549 const size_t max_size = sizeof(buffers[0]);
550
551 // Process the input string
552 for (size_t i = 0; message[i] != '\0' && out_pos < max_size - 100; i++) {
553 size_t end_pos = 0;
554
555 // Check if already colorized - only colorize if NOT already colored
556 bool can_colorize = !ansi_is_already_colorized(message, i);
557
558 // Try key=value pair first (highest priority pattern)
559 size_t key_end = 0, value_start = 0, value_end = 0;
560 if (can_colorize && is_key_value_pair(message, i, &key_end, &value_start, &value_end)) {
561 size_t key_len = key_end - i;
562 size_t value_len = value_end - value_start;
563
564 // Extract key
565 char key_buf[LOG_COLORIZE_KEY_BUFFER_SIZE];
566 safe_snprintf(key_buf, sizeof(key_buf), "%.*s", (int)key_len, message + i);
567
568 // Extract value
569 char value_buf[LOG_COLORIZE_VALUE_BUFFER_SIZE];
570 safe_snprintf(value_buf, sizeof(value_buf), "%.*s", (int)value_len, message + value_start);
571
572 // Check if we have enough space for key + equals + value
573 // including the bounded color prefixes and resets.
574 if (out_pos + key_len + 1 + value_len + 100 < max_size) {
575 append_colored_token(output, max_size, &out_pos, LOG_COLOR_FATAL, key_buf);
576
577 // Add uncolored equals sign
578 output[out_pos++] = '=';
579
580 // Determine value color and add colored value
581 log_color_t value_color = get_value_color(value_buf);
582 append_colored_token(output, max_size, &out_pos, value_color, value_buf);
583 }
584 i = value_end - 1;
585 continue;
586 }
587
588 // Try numeric pattern
589 if (can_colorize && is_numeric_pattern(message, i, &end_pos)) {
590 size_t pattern_len = end_pos - i;
591 char pattern_buf[LOG_COLORIZE_PATTERN_BUFFER_SIZE];
592 safe_snprintf(pattern_buf, sizeof(pattern_buf), "%.*s", (int)pattern_len, message + i);
593
594 append_colored_token(output, max_size, &out_pos, LOG_COLOR_GREY, pattern_buf);
595 i = end_pos - 1;
596 continue;
597 }
598
599 // Try file path
600 if (can_colorize && is_file_path(message, i, &end_pos)) {
601 size_t path_len = end_pos - i;
602 char path_buf[LOG_COLORIZE_PATH_BUFFER_SIZE];
603 safe_snprintf(path_buf, sizeof(path_buf), "%.*s", (int)path_len, message + i);
604
605 append_colored_token(output, max_size, &out_pos, LOG_COLOR_DEBUG, path_buf);
606 i = end_pos - 1;
607 continue;
608 }
609
610 // Try environment variable
611 if (can_colorize && is_env_var(message, i, &end_pos)) {
612 size_t var_len = end_pos - i;
613 char var_buf[LOG_COLORIZE_VAR_BUFFER_SIZE];
614 safe_snprintf(var_buf, sizeof(var_buf), "%.*s", (int)var_len, message + i);
615
616 append_colored_token(output, max_size, &out_pos, LOG_COLOR_GREY, var_buf);
617 i = end_pos - 1;
618 continue;
619 }
620
621 // Try URL
622 if (can_colorize && is_url(message, i, &end_pos)) {
623 size_t url_len = end_pos - i;
624 char url_buf[LOG_COLORIZE_URL_BUFFER_SIZE];
625 safe_snprintf(url_buf, sizeof(url_buf), "%.*s", (int)url_len, message + i);
626
627 append_colored_token(output, max_size, &out_pos, LOG_COLOR_INFO, url_buf);
628 i = end_pos - 1;
629 continue;
630 }
631
632 // Regular character - just copy
633 if (out_pos < max_size - 1) {
634 output[out_pos++] = message[i];
635 }
636 }
637
638 output[out_pos] = '\0';
639 return output;
640}
ANSI escape sequence utilities and fast color code generation.
const char * colorize_log_message(const char *message)
Colorize a log message for terminal output.
Definition colorize.c:530
#define LOG_COLORIZE_VALUE_BUFFER_SIZE
Definition colorize.c:9
#define LOG_COLORIZE_URL_BUFFER_SIZE
Definition colorize.c:13
#define LOG_COLORIZE_PATH_BUFFER_SIZE
Definition colorize.c:11
const char * colorize_log_message_with_color(const char *message, bool enabled)
Definition colorize.c:536
#define LOG_COLORIZE_PATTERN_BUFFER_SIZE
Definition colorize.c:10
#define LOG_COLORIZE_KEY_BUFFER_SIZE
Definition colorize.c:8
#define LOG_COLORIZE_VAR_BUFFER_SIZE
Definition colorize.c:12
#define LOG_COLORIZE_SLOT_COUNT
Definition colorize.c:16
Log message colorization for terminal output.
bool enabled
Is filtering active?
Definition grep.c:62
bool ansi_is_already_colorized(const char *message, size_t pos)
Check if a position in text is already colored.
Definition ansi.c:102
const char * log_level_color_for_output(log_color_t color, bool enabled)
#define LOG_MSG_BUFFER_SIZE
Maximum size of a single log message (including formatting).
Definition log/log.h:91
log_color_t
Color enum for logging - indexes into color arrays.
Definition log/log.h:146
@ 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_DEBUG
Definition log/log.h:148
@ LOG_COLOR_INFO
Definition log/log.h:149
#define options_terminal_settings()
Definition options.h:1287
📝 Logging API with multiple log levels and terminal output control
int platform_strncasecmp(const char *s1, const char *s2, size_t n)
bool terminal_should_color_output(int fd, const terminal_options_t *options)
🔤 String Manipulation and Shell Escaping Utilities