ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
search.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define LOG_SEARCH_OUTPUT_BUFFER_SIZE 512
4
5#include <ascii-chat/otel.h>
13
14#include "ascii-chat/common.h"
15#include "ascii-chat/log/grep.h"
16#include "ascii-chat/log/log.h"
24#include <ascii-chat/ui/input.h>
26#include <libplatform/keyboard.h>
27#include <libplatform/lifecycle.h>
28#include <libplatform/mutex.h>
29#include <libplatform/terminal.h>
30#include <options/options.h>
31
32#include <libplatform/atomic.h>
33#include <pcre2.h>
34#include <stdio.h>
35#include <string.h>
36
37/* ============================================================================
38 * Constants
39 * ========================================================================== */
40
41#define MAX_LOG_SEARCH_PATTERNS 32
42#define LOG_SEARCH_INPUT_BUFFER_SIZE 256
43#define LOG_SEARCH_DEBOUNCE_NS 200000000ULL
44
45/* ============================================================================
46 * State Structure
47 * ========================================================================== */
48
86
87static log_search_state_t g_search_state = {
89 .len = 0,
90 .cursor = 0,
91 .previous_pattern_count = 0,
92 .active_pattern_count = 0,
93 .case_insensitive = false,
94 .fixed_string = false,
95 .global_highlight = false,
96 .invert_match = false,
97 .context_before = 0,
98 .context_after = 0,
99 .lifecycle = LIFECYCLE_INIT,
100 .needs_rerender = {0},
101 .signal_cancelled = {0},
102 .mode_atomic = {0},
103 .cli_pattern_auto_populated = false,
104};
105
106static lifecycle_t g_log_search_lifecycle = LIFECYCLE_INIT;
107
108/* ============================================================================
109 * Pattern Validation
110 * ========================================================================== */
111
117static bool validate_pcre2_pattern(const char *input) {
118 if (!input || strlen(input) == 0) {
119 return true; // Empty is valid (no filtering)
120 }
121
122 // Use the shared parser from filter.c
124
125 if (!parsed.valid) {
126 return false; // Invalid format
127 }
128
129 // If fixed string, always valid
130 if (parsed.is_fixed_string) {
131 return true;
132 }
133
134 // Try to compile pattern with full pcre2_options (includes UTF, UCP,
135 // CASELESS, etc.)
136 pcre2_code *code =
138 if (!code)
139 return false;
140 pcre2_code_free(code);
141 return true;
142}
143
144/* ============================================================================
145 * Lifecycle Functions
146 * ========================================================================== */
147
149 // Use lifecycle API for unified initialization
150 if (!lifecycle_init_once(&g_log_search_lifecycle)) {
151 // Already initialized.
152 return ASCIICHAT_OK;
153 }
154
155 memset(&g_search_state, 0, sizeof(g_search_state));
156 if (mutex_init(&g_search_state.mutex, "log_search") != 0) {
157 lifecycle_init_abort(&g_log_search_lifecycle);
158 return SET_ERRNO(ERROR_THREAD, "Cannot initialize log search");
159 }
160 mutex_lock(&g_search_state.mutex);
161
162 // Check if there are CLI --grep patterns to use
163 const char *cli_pattern = grep_get_last_pattern();
164
165 // Start in INACTIVE mode if no CLI pattern is provided.
166 // Only use patterns from CLI --grep arguments, not default patterns.
167 // This ensures logs are visible by default and only filtered if explicitly
168 // requested.
169 if (!cli_pattern || cli_pattern[0] == '\0') {
170 // No CLI pattern - start inactive
171 g_search_state.mode = LOG_SEARCH_MODE_INACTIVE;
172 atomic_store_int(&g_search_state.mode_atomic, LOG_SEARCH_MODE_INACTIVE);
173 lifecycle_init_commit(&g_log_search_lifecycle);
174 mutex_unlock(&g_search_state.mutex);
175 return ASCIICHAT_OK;
176 }
177
178 // Load CLI pattern into input buffer
179 SAFE_STRNCPY(g_search_state.input_buffer, cli_pattern,
181 g_search_state.len = strlen(cli_pattern);
182 g_search_state.cursor = g_search_state.len;
183 g_search_state.mode = LOG_SEARCH_MODE_ACTIVE;
184 atomic_store_int(&g_search_state.mode_atomic, LOG_SEARCH_MODE_ACTIVE);
185
186 // Compile the initial pattern
187 grep_parse_result_t parsed = grep_parse_pattern(cli_pattern);
188 if (parsed.valid) {
189 pcre2_code *compiled =
191 if (compiled) {
192 g_search_state.active_patterns[0] = compiled;
193 g_search_state.active_pattern_count = 1;
194 }
195 g_search_state.case_insensitive = parsed.case_insensitive;
196 g_search_state.fixed_string = parsed.is_fixed_string;
197 g_search_state.global_highlight = parsed.global_flag;
198 g_search_state.invert_match = parsed.invert;
199 g_search_state.context_before = parsed.context_before;
200 g_search_state.context_after = parsed.context_after;
201 }
202
203 atomic_store_bool(&g_search_state.needs_rerender, true);
204 lifecycle_init_commit(&g_log_search_lifecycle);
205
206 mutex_unlock(&g_search_state.mutex);
207 return ASCIICHAT_OK;
208}
209
211 if (!lifecycle_shutdown(&g_log_search_lifecycle)) {
212 return; // Already shut down or never initialized
213 }
214
215 mutex_lock(&g_search_state.mutex);
216
217 // Free active patterns
218 for (int i = 0; i < g_search_state.active_pattern_count; i++) {
219 if (g_search_state.active_patterns[i]) {
220 pcre2_code_free(g_search_state.active_patterns[i]);
221 g_search_state.active_patterns[i] = NULL;
222 }
223 }
224
225 mutex_unlock(&g_search_state.mutex);
226 mutex_destroy(&g_search_state.mutex);
227}
228
229/* ============================================================================
230 * Mode Management
231 * ========================================================================== */
232
234 ascii_otel_ui_usage("logs", "search_started", 0);
235 // Ensure cursor is visible for user typing
236 (void)terminal_cursor_show();
237
238 mutex_lock(&g_search_state.mutex);
239
240 // Save current patterns (CLI --grep patterns)
242 if (result != ASCIICHAT_OK) {
243 log_warn("Failed to save filter patterns");
244 }
245
246 // Clear input buffer
247 memset(g_search_state.input_buffer, 0, sizeof(g_search_state.input_buffer));
248 g_search_state.len = 0;
249 g_search_state.cursor = 0;
250 flow_control_debounce_cancel(&g_search_state.debounce);
251
252 // Pre-populate with CLI --grep pattern if available (only once at startup)
253 if (!g_search_state.cli_pattern_auto_populated) {
254 const char *cli_pattern = grep_get_last_pattern();
255 if (cli_pattern && cli_pattern[0] != '\0') {
256 // Skip leading slash if present (prompt already shows "/")
257 const char *pattern_to_use = cli_pattern;
258 if (cli_pattern[0] == '/') {
259 pattern_to_use = cli_pattern + 1;
260 }
261
262 size_t pattern_len = strlen(pattern_to_use);
263 if (pattern_len < sizeof(g_search_state.input_buffer) - 1) {
264 memcpy(g_search_state.input_buffer, pattern_to_use, pattern_len + 1);
265 g_search_state.len = pattern_len;
266 g_search_state.cursor = pattern_len;
267 g_search_state.cli_pattern_auto_populated = true;
268
269 // Compile and apply the pattern immediately so it starts filtering
270 grep_parse_result_t parsed =
271 grep_parse_pattern(g_search_state.input_buffer);
272 if (parsed.valid) {
273 // Store parsed flags
274 g_search_state.case_insensitive = parsed.case_insensitive;
275 g_search_state.fixed_string = parsed.is_fixed_string;
276 g_search_state.global_highlight = parsed.global_flag;
277 g_search_state.invert_match = parsed.invert;
278 g_search_state.context_before = parsed.context_before;
279 g_search_state.context_after = parsed.context_after;
280
281 // Compile pattern if not fixed string
282 if (strlen(parsed.pattern) > 0 && !parsed.is_fixed_string) {
283 pcre2_code *compiled =
285 if (compiled) {
286 pcre2_code *code = compiled;
287 if (code) {
288 if (g_search_state.active_pattern_count > 0)
289 pcre2_code_free(g_search_state.active_patterns[0]);
290 g_search_state.active_patterns[0] = compiled;
291 g_search_state.active_pattern_count = 1;
292 } else {
293 g_search_state.fixed_string = true;
294 }
295 } else {
296 g_search_state.fixed_string = true;
297 }
298 }
299 }
300 }
301 }
302 }
303
304 // Enter input mode
305 g_search_state.mode = LOG_SEARCH_MODE_ENTERING;
306 atomic_store_int(&g_search_state.mode_atomic, LOG_SEARCH_MODE_ENTERING);
307 atomic_store_bool(&g_search_state.needs_rerender, true);
308
309 mutex_unlock(&g_search_state.mutex);
310}
311
312void log_search_exit_mode(bool accept) {
313 mutex_lock(&g_search_state.mutex);
314
315 if (g_search_state.mode == LOG_SEARCH_MODE_INACTIVE ||
316 (accept && g_search_state.mode != LOG_SEARCH_MODE_ENTERING)) {
317 mutex_unlock(&g_search_state.mutex);
318 return;
319 }
320
321 if (!accept) {
322 flow_control_debounce_cancel(&g_search_state.debounce);
323 ascii_otel_ui_usage("logs", "search_cancelled", 0);
324 // Cancel - restore previous patterns and reset CLI pattern flag so user can
325 // re-populate
327 if (result != ASCIICHAT_OK) {
328 log_warn("Failed to restore filter patterns");
329 }
330
331 // Clear interactive grep patterns
332 for (int i = 0; i < g_search_state.active_pattern_count; i++) {
333 pcre2_code_free(g_search_state.active_patterns[i]);
334 g_search_state.active_patterns[i] = NULL;
335 }
336 g_search_state.active_pattern_count = 0;
337
338 // Reset the CLI pattern auto-populated flag so user can re-enter grep mode
339 // with the pattern again
340 g_search_state.cli_pattern_auto_populated = false;
341
342 g_search_state.mode = LOG_SEARCH_MODE_INACTIVE;
343 atomic_store_int(&g_search_state.mode_atomic, LOG_SEARCH_MODE_INACTIVE);
344 atomic_store_bool(&g_search_state.needs_rerender, true);
345 mutex_unlock(&g_search_state.mutex);
346 return;
347 }
348
349 // Accept - parse and compile pattern
350 flow_control_debounce_cancel(&g_search_state.debounce);
351 grep_parse_result_t parsed = grep_parse_pattern(g_search_state.input_buffer);
352
353 if (!parsed.valid) {
354 ascii_otel_ui_usage("logs", "search_rejected", 0);
355 log_error("Invalid pattern format");
356 mutex_unlock(&g_search_state.mutex);
357 return; // Stay in input mode
358 }
359
360 // Clear old regex patterns
361 for (int i = 0; i < g_search_state.active_pattern_count; i++) {
362 pcre2_code_free(g_search_state.active_patterns[i]);
363 g_search_state.active_patterns[i] = NULL;
364 }
365 g_search_state.active_pattern_count = 0;
366
367 // Store parsed flags first
368 g_search_state.case_insensitive = parsed.case_insensitive;
369 g_search_state.fixed_string = parsed.is_fixed_string;
370 g_search_state.global_highlight = parsed.global_flag;
371 g_search_state.invert_match = parsed.invert;
372 g_search_state.context_before = parsed.context_before;
373 g_search_state.context_after = parsed.context_after;
374
375 // Compile and store new pattern (if not fixed string)
376 if (strlen(parsed.pattern) > 0 && !parsed.is_fixed_string) {
377 pcre2_code *compiled =
379 if (compiled) {
380 // Verify the pattern actually compiles
381 pcre2_code *code = compiled;
382 if (code) {
383 g_search_state.active_patterns[0] = compiled;
384 g_search_state.active_pattern_count = 1;
385 } else {
386 // Compilation failed - fall back to fixed string matching
387 g_search_state.fixed_string =
388 true; // Override to use fixed string instead
389 }
390 } else {
391 // Malloc failed - fall back to fixed string
392 g_search_state.fixed_string = true;
393 }
394 }
395 // For fixed strings, pattern stays in input_buffer and fixed_string=true
396
397 ascii_otel_ui_usage("logs", "filter_applied", 0);
398 g_search_state.mode = LOG_SEARCH_MODE_ACTIVE;
399 atomic_store_int(&g_search_state.mode_atomic, LOG_SEARCH_MODE_ACTIVE);
400 atomic_store_bool(&g_search_state.needs_rerender, true);
401
402 mutex_unlock(&g_search_state.mutex);
403}
404
405/* ============================================================================
406 * Signal-Safe Interface
407 * ========================================================================== */
408
410 return atomic_load_int(&g_search_state.mode_atomic) ==
412}
413
415 atomic_store_bool(&g_search_state.signal_cancelled, true);
416}
417
419 bool expected = true;
420 return atomic_cas_bool(&g_search_state.signal_cancelled, &expected, false);
421}
422
424 // Use atomic read (async-signal-safe) to avoid mutex issues when called from
425 // signal handlers
426 return atomic_load_int(&g_search_state.mode_atomic) ==
428}
429
431 // Use atomic read (async-signal-safe) to avoid mutex issues when called from
432 // signal handlers
433 return atomic_load_int(&g_search_state.mode_atomic) !=
435}
436
437/* ============================================================================
438 * Keyboard Handling
439 * ========================================================================== */
440
442 mutex_lock(&g_search_state.mutex);
443
444 // If in input mode, handle all keys
445 if (g_search_state.mode == LOG_SEARCH_MODE_ENTERING) {
446 mutex_unlock(&g_search_state.mutex);
447 return true;
448 }
449
450 // If not in input mode, only handle '/' to enter mode
451 bool should_handle = (key == '/');
452 mutex_unlock(&g_search_state.mutex);
453 return should_handle;
454}
455
456static void log_search_update_filter_locked(void) {
457 for (int i = 0; i < g_search_state.active_pattern_count; i++) {
458 pcre2_code_free(g_search_state.active_patterns[i]);
459 g_search_state.active_patterns[i] = NULL;
460 }
461 g_search_state.active_pattern_count = 0;
462 if (g_search_state.len == 0) {
463 g_search_state.active_pattern_count = 0;
464 g_search_state.fixed_string = false;
465 return;
466 }
467 grep_parse_result_t parsed = grep_parse_pattern(g_search_state.input_buffer);
468 if (!parsed.valid)
469 return;
470 g_search_state.active_pattern_count = 0;
471 g_search_state.case_insensitive = parsed.case_insensitive;
472 g_search_state.fixed_string = parsed.is_fixed_string;
473 if (!parsed.is_fixed_string) {
474 pcre2_code *compiled =
476 if (compiled) {
477 g_search_state.active_patterns[0] = compiled;
478 g_search_state.active_pattern_count = 1;
479 } else {
480 g_search_state.fixed_string = true;
481 }
482 }
483 g_search_state.global_highlight = parsed.global_flag;
484 g_search_state.invert_match = parsed.invert;
485 g_search_state.context_before = parsed.context_before;
486 g_search_state.context_after = parsed.context_after;
487}
488
490 mutex_lock(&g_search_state.mutex);
491 bool ready =
492 g_search_state.mode == LOG_SEARCH_MODE_ENTERING &&
493 flow_control_debounce_take_ready(&g_search_state.debounce, time_get_ns());
494 if (ready)
495 log_search_update_filter_locked();
496 mutex_unlock(&g_search_state.mutex);
497 if (ready)
498 atomic_store_bool(&g_search_state.needs_rerender, true);
499}
500
502 if (!text || strlen(text) >= LOG_SEARCH_INPUT_BUFFER_SIZE)
504 "Search paste exceeds input capacity");
506 return SET_ERRNO(ERROR_INVALID_STATE, "Search input is not active");
507 char normalized[LOG_SEARCH_INPUT_BUFFER_SIZE];
508 size_t i;
509 for (i = 0; text[i]; ++i) {
510 unsigned char byte = (unsigned char)text[i];
511 normalized[i] = byte < 32 || byte == 127 ? ' ' : (char)byte;
512 }
513 normalized[i] = '\0';
514 mutex_lock(&g_search_state.mutex);
516 if (g_search_state.mode != LOG_SEARCH_MODE_ENTERING)
517 result = SET_ERRNO(ERROR_INVALID_STATE, "Search input is not active");
518 else {
519 result = ui_input_insert(
520 g_search_state.input_buffer, sizeof(g_search_state.input_buffer),
521 &g_search_state.len, &g_search_state.cursor, normalized);
522 if (result == ASCIICHAT_OK)
523 flow_control_debounce_trigger(&g_search_state.debounce, time_get_ns(),
525 }
526 mutex_unlock(&g_search_state.mutex);
527 if (result == ASCIICHAT_OK)
528 atomic_store_bool(&g_search_state.needs_rerender, true);
529 return result;
530}
531
533 mutex_lock(&g_search_state.mutex);
534
535 // If not in input mode, check if user pressed '/'
536 if (g_search_state.mode != LOG_SEARCH_MODE_ENTERING) {
537 mutex_unlock(&g_search_state.mutex);
538
539 // Check for '/' key (key already passed as parameter, don't read again!)
540 if (key == '/') {
542 }
543 return ASCIICHAT_OK;
544 }
545
546 // In input mode - use keyboard_read_line_interactive()
547 // Keep the mutex held during editing to prevent races
548 // with the rendering thread. The validator callback and buffer modifications
549 // must be synchronized with readers in log_search_gather_and_filter_logs().
550 keyboard_line_edit_opts_t opts = {
551 .buffer = g_search_state.input_buffer,
552 .max_len = sizeof(g_search_state.input_buffer),
553 .len = &g_search_state.len,
554 .cursor = &g_search_state.cursor,
555 .echo = false, // We handle rendering ourselves
556 .mask_char = 0, // No masking
557 .prefix = NULL, // Don't render prefix - log_search_render_input_line()
558 // handles it
559 .validator = validate_pcre2_pattern, // Live validation
560 .key = key // Pass the pre-read key
561 };
562
563 keyboard_line_edit_result_t result = keyboard_read_line_interactive(&opts);
564
565 switch (result) {
566 case LINE_EDIT_ACCEPTED:
567 // Unlock before exit_mode since it acquires the mutex
568 mutex_unlock(&g_search_state.mutex);
569 log_search_exit_mode(true); // Parse and accept pattern
570 break;
571 case LINE_EDIT_CANCELLED:
572 // Unlock before exit_mode since it acquires the mutex
573 mutex_unlock(&g_search_state.mutex);
574 log_search_exit_mode(false); // Restore previous
575 break;
576 case LINE_EDIT_CONTINUE:
577 flow_control_debounce_trigger(&g_search_state.debounce, time_get_ns(),
579 mutex_unlock(&g_search_state.mutex);
580 atomic_store_bool(&g_search_state.needs_rerender, true);
581 break;
582 case LINE_EDIT_NO_INPUT:
583 // No input available
584 mutex_unlock(&g_search_state.mutex);
585 break;
586 }
587
588 return ASCIICHAT_OK;
589}
590
591/* ============================================================================
592 * Log Filtering
593 * ========================================================================== */
594
597 size_t *out_count) {
600 out_entries, out_count);
601}
602
604 session_log_entry_t **out_entries,
605 size_t *out_count) {
606 if (!out_entries || !out_count) {
608 "out_entries and out_count must not be NULL");
609 }
610
611 // Get logs from in-memory buffer
612 session_log_entry_t *buffer_entries =
615 if (!buffer_entries) {
616 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate log buffer");
617 }
618
619 size_t buffer_count = session_log_buffer_get_recent(log_buf, buffer_entries,
621
622 // Check if filtering is active (either regex patterns or fixed string)
623 mutex_lock(&g_search_state.mutex);
624 bool has_regex_patterns = (g_search_state.active_pattern_count > 0);
625 bool has_fixed_string =
626 (g_search_state.fixed_string && g_search_state.len > 0);
627 bool filtering_active = has_regex_patterns || has_fixed_string;
628
629 if (!filtering_active) {
630 // No filtering active - return all entries
631 mutex_unlock(&g_search_state.mutex);
632 *out_entries = buffer_entries;
633 *out_count = buffer_count;
634 return ASCIICHAT_OK;
635 }
636
637 // Filter entries with PCRE2
638 session_log_entry_t *filtered =
641 if (!filtered) {
642 mutex_unlock(&g_search_state.mutex);
643 SAFE_FREE(buffer_entries);
644 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate filtered buffer");
645 }
646
647 size_t filtered_count = 0;
648
649 // Create match data for PCRE2 matching
650 pcre2_match_data *match_data = NULL;
651 for (int p = 0; p < g_search_state.active_pattern_count; p++) {
652 if (g_search_state.active_patterns[p]) {
653 pcre2_code *code = g_search_state.active_patterns[p];
654 if (code) {
655 match_data = pcre2_match_data_create_from_pattern(code, NULL);
656 break;
657 }
658 }
659 }
660
661 if (!match_data && g_search_state.active_pattern_count > 0) {
662 // Couldn't create match data - fall back to returning all entries
663 mutex_unlock(&g_search_state.mutex);
664 SAFE_FREE(filtered);
665 *out_entries = buffer_entries;
666 *out_count = buffer_count;
667 return ASCIICHAT_OK;
668 }
669
670 // Parse pattern once before loop (for fixed string mode)
671 grep_parse_result_t parsed = {0};
672 if (has_fixed_string) {
673 parsed = grep_parse_pattern(g_search_state.input_buffer);
674 }
675
676 for (size_t i = 0; i < buffer_count; i++) {
677 const char *original_message = buffer_entries[i].message;
678 bool matches = false;
679
680 // Strip ANSI codes to match against plain text (consistent with
681 // highlighting)
682 char plain_message[SESSION_LOG_LINE_MAX] = {0};
683 // Use inline stripping to avoid function call overhead
684 {
685 size_t pos = 0;
686 const char *src = original_message;
687 char *dst = plain_message;
688 size_t dst_size = sizeof(plain_message);
689
690 while (*src && pos < dst_size - 1) {
691 if (*src == '\x1b' && src[1] != '\0' && src[1] == '[') {
692 // CSI sequence - skip until final byte
693 src += 2;
694 while (*src && pos < dst_size - 1 &&
695 !(*src >= 0x40 && *src <= 0x7E)) {
696 src++;
697 }
698 if (*src)
699 src++; // Skip final byte
700 } else {
701 dst[pos++] = *src++;
702 }
703 }
704 dst[pos] = '\0';
705 }
706
707 size_t message_len = strlen(plain_message);
708
709 // Fixed string matching
710 if (has_fixed_string) {
711 const char *search_pattern = parsed.pattern;
712
713 if (g_search_state.case_insensitive) {
714 // Unicode-aware case-insensitive fixed string search
715 matches = (utf8_strcasestr(plain_message, search_pattern) != NULL);
716 } else {
717 // Case-sensitive fixed string search
718 matches = (strstr(plain_message, search_pattern) != NULL);
719 }
720 }
721 // Regex pattern matching
722 else if (has_regex_patterns) {
723 // Check against all active patterns (OR logic)
724 for (int p = 0; p < g_search_state.active_pattern_count; p++) {
725 pcre2_code *compiled = g_search_state.active_patterns[p];
726 if (!compiled) {
727 continue;
728 }
729
730 pcre2_code *code = compiled;
731 if (!code) {
732 continue;
733 }
734
735 // Match against plain message (without ANSI codes)
736 int rc = pcre2_match(code, (PCRE2_SPTR)plain_message, message_len, 0, 0,
737 match_data, NULL);
738 if (rc >= 0) {
739 matches = true;
740 break;
741 }
742 }
743 }
744
745 // Apply invert logic
746 if (g_search_state.invert_match) {
747 matches = !matches;
748 }
749
750 if (matches) {
751 filtered[filtered_count++] = buffer_entries[i];
752 }
753 }
754
755 // Free match data
756 if (match_data) {
757 pcre2_match_data_free(match_data);
758 }
759
760 mutex_unlock(&g_search_state.mutex);
761
762 SAFE_FREE(buffer_entries);
763 *out_entries = filtered;
764 *out_count = filtered_count;
765 return ASCIICHAT_OK;
766}
767
768/* ============================================================================
769 * Display Rendering
770 * ========================================================================== */
771
773 (void)width; // Reserved for future use (line truncation)
774
775 mutex_lock(&g_search_state.mutex);
776
777 if (g_search_state.mode != LOG_SEARCH_MODE_ENTERING) {
778 mutex_unlock(&g_search_state.mutex);
779 return;
780 }
781
782 // Render the pattern and position terminal cursor at current edit position
783 char output_buf[LOG_SEARCH_OUTPUT_BUFFER_SIZE];
784
785 // Build output: "/" + pattern
786 int pattern_len =
787 snprintf(output_buf, sizeof(output_buf), "/%.*s", (int)g_search_state.len,
788 g_search_state.input_buffer);
789
790 if (pattern_len > 0 && pattern_len < (int)sizeof(output_buf)) {
791 // Write the pattern to terminal
792 ui_controller_write(STDOUT_FILENO, output_buf, (size_t)pattern_len);
793
794 // After writing, cursor is at: column = 1 (for "/") + len + 1
795 // We want it at: column = 1 (for "/") + cursor_position + 1
796 // So we need to move back by: len - cursor_position columns
797 int cursor_offset = (int)g_search_state.len - (int)g_search_state.cursor;
798 if (cursor_offset > 0) {
799 // Move left by the difference
800 ui_controller_printf(STDOUT_FILENO, "\033[%dD", cursor_offset);
801 }
802 }
803
804 mutex_unlock(&g_search_state.mutex);
805}
806
807/* ============================================================================
808 * Display Highlighting
809 * ========================================================================== */
810
811bool log_search_get_match_info(const char *message, size_t *out_match_start,
812 size_t *out_match_len) {
813 if (!message || !out_match_start || !out_match_len) {
814 return false;
815 }
816
817 *out_match_start = 0;
818 *out_match_len = 0;
819
820 // Use atomic read to avoid mutex contention with keyboard handler
821 int mode = atomic_load_int(&g_search_state.mode_atomic);
822 if (mode == LOG_SEARCH_MODE_INACTIVE) {
823 return false;
824 }
825
826 // Make a safe copy of state under mutex, then release before doing expensive
827 // work
828 mutex_lock(&g_search_state.mutex);
829
830 bool has_fixed_string = g_search_state.fixed_string && g_search_state.len > 0;
831 bool case_insensitive = g_search_state.case_insensitive;
832 char pattern_copy[LOG_SEARCH_INPUT_BUFFER_SIZE];
833 size_t pattern_len = g_search_state.len;
834 int pattern_count = g_search_state.active_pattern_count;
835 pcre2_code *patterns_copy[MAX_LOG_SEARCH_PATTERNS] = {0};
836
837 if (has_fixed_string) {
838 // Parse the input buffer to extract just the pattern part (without flags)
839 grep_parse_result_t parsed =
840 grep_parse_pattern(g_search_state.input_buffer);
841 const char *src =
842 parsed.valid ? parsed.pattern : g_search_state.input_buffer;
843 SAFE_STRNCPY(pattern_copy, src, sizeof(pattern_copy) - 1);
844 pattern_copy[sizeof(pattern_copy) - 1] = '\0';
845 pattern_len = strlen(
846 pattern_copy); // Update pattern_len for the actual parsed pattern
847 }
848
849 for (int i = 0; i < pattern_count && i < MAX_LOG_SEARCH_PATTERNS; i++) {
850 if (g_search_state.active_patterns[i])
851 patterns_copy[i] = pcre2_code_copy(g_search_state.active_patterns[i]);
852 }
853
854 mutex_unlock(&g_search_state.mutex);
855
856 // Now do matching without holding mutex
857 size_t message_len = strlen(message);
858 bool matches = false;
859
860 // Fixed string matching
861 if (has_fixed_string) {
862 const char *found = NULL;
863
864 if (case_insensitive) {
865 found = utf8_strcasestr(message, pattern_copy);
866 } else {
867 found = strstr(message, pattern_copy);
868 }
869
870 if (found) {
871 matches = true;
872
873 // Convert byte position to character position (UTF-8 aware)
874 size_t byte_pos = (size_t)(found - message);
875 size_t char_pos = 0;
876 for (size_t i = 0; i < byte_pos && message[i] != '\0';) {
877 uint32_t codepoint;
878 int utf8_len = utf8_decode((const uint8_t *)(message + i), &codepoint);
879 if (utf8_len <= 0)
880 utf8_len = 1;
881 i += utf8_len;
882 char_pos++;
883 }
884
885 // Count characters in the match (pattern_len is in bytes for the pattern)
886 size_t match_char_len = 0;
887 for (size_t i = 0; i < pattern_len && found[i] != '\0';) {
888 uint32_t codepoint;
889 int utf8_len = utf8_decode((const uint8_t *)(found + i), &codepoint);
890 if (utf8_len <= 0)
891 utf8_len = 1;
892 i += utf8_len;
893 match_char_len++;
894 }
895
896 *out_match_start = char_pos;
897 *out_match_len = match_char_len;
898 }
899 }
900 // Regex pattern matching
901 else if (pattern_count > 0) {
902 pcre2_match_data *match_data = NULL;
903 for (int p = 0; p < pattern_count; p++) {
904 if (patterns_copy[p]) {
905 pcre2_code *code = patterns_copy[p];
906 if (code) {
907 match_data = pcre2_match_data_create_from_pattern(code, NULL);
908 break;
909 }
910 }
911 }
912
913 if (match_data) {
914 for (int p = 0; p < pattern_count; p++) {
915 pcre2_code *compiled = patterns_copy[p];
916 if (!compiled) {
917 continue;
918 }
919
920 pcre2_code *code = compiled;
921 if (!code) {
922 continue;
923 }
924
925 int rc = pcre2_match(code, (PCRE2_SPTR)message, message_len, 0, 0,
926 match_data, NULL);
927 if (rc >= 0) {
928 matches = true;
929 PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
930
931 // Convert byte positions to character positions (UTF-8 aware)
932 size_t byte_start = (size_t)ovector[0];
933 size_t byte_end = (size_t)ovector[1];
934
935 // Count characters up to byte_start
936 size_t char_start = 0;
937 for (size_t i = 0; i < byte_start && message[i] != '\0';) {
938 uint32_t codepoint;
939 int utf8_len =
940 utf8_decode((const uint8_t *)(message + i), &codepoint);
941 if (utf8_len <= 0)
942 utf8_len = 1;
943 i += utf8_len;
944 char_start++;
945 }
946
947 // Count characters up to byte_end
948 size_t char_end = char_start;
949 for (size_t i = byte_start; i < byte_end && message[i] != '\0';) {
950 uint32_t codepoint;
951 int utf8_len =
952 utf8_decode((const uint8_t *)(message + i), &codepoint);
953 if (utf8_len <= 0)
954 utf8_len = 1;
955 i += utf8_len;
956 char_end++;
957 }
958
959 *out_match_start = char_start;
960 *out_match_len = char_end - char_start;
961 break;
962 }
963 }
964 pcre2_match_data_free(match_data);
965 }
966 }
967
968 for (int i = 0; i < pattern_count && i < MAX_LOG_SEARCH_PATTERNS; i++) {
969 if (patterns_copy[i])
970 pcre2_code_free(patterns_copy[i]);
971 }
972 return matches;
973}
974
975/* ============================================================================
976 * Re-render Notification
977 * ========================================================================== */
978
980 bool needs = atomic_load_bool(&g_search_state.needs_rerender);
981 if (needs) {
982 atomic_store_bool(&g_search_state.needs_rerender, false);
983 }
984 return needs;
985}
986
987/* ============================================================================
988 * Query Functions
989 * ========================================================================== */
990
992 // Use atomic read to avoid mutex contention with keyboard handler
993 int mode = atomic_load_int(&g_search_state.mode_atomic);
994 if (mode == LOG_SEARCH_MODE_INACTIVE) {
995 return false;
996 }
997
998 // Safe read under mutex (quick operation)
999 mutex_lock(&g_search_state.mutex);
1000 bool result = g_search_state.global_highlight;
1001 mutex_unlock(&g_search_state.mutex);
1002
1003 return result;
1004}
1005
1007 // Use atomic read to check if active
1008 int mode = atomic_load_int(&g_search_state.mode_atomic);
1009 if (mode == LOG_SEARCH_MODE_INACTIVE) {
1010 return NULL;
1011 }
1012
1013 // Safe read under mutex
1014 mutex_lock(&g_search_state.mutex);
1015
1016 // Return the compiled pattern if we have one (not fixed string)
1017 void *result = NULL;
1018 if (g_search_state.active_pattern_count > 0 && !g_search_state.fixed_string) {
1019 result = (void *)pcre2_code_copy(g_search_state.active_patterns[0]);
1020 }
1021
1022 mutex_unlock(&g_search_state.mutex);
1023
1024 return result;
1025}
1026
1027/* ============================================================================
1028 * Internal Access for Atomic Rendering
1029 * ========================================================================== */
1030
1031void *log_search_get_mutex(void) { return (void *)&g_search_state.mutex; }
1032
1033int log_search_get_input_len(void) { return (int)g_search_state.len; }
1034
1035int log_search_get_cursor_position(void) { return (int)g_search_state.cursor; }
1036
1038 return g_search_state.input_buffer;
1039}
1040
1042 return g_search_state.case_insensitive;
1043}
ANSI escape sequence utilities and fast color code generation.
#define SET_ERRNO(code,...)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void atomic_store_int(atomic_t *a, int value)
Atomically store an int value.
int atomic_load_int(atomic_t *a)
Atomically load an int value.
bool atomic_cas_bool(atomic_t *a, bool *expected, bool new_value)
Atomically compare-and-swap a boolean.
unsigned int width
Definition fft.c:24
void flow_control_debounce_cancel(flow_control_debounce_t *debounce)
void flow_control_debounce_trigger(flow_control_debounce_t *debounce, uint64_t now_ns, uint64_t delay_ns)
Definition flow_control.c:3
bool flow_control_debounce_take_ready(flow_control_debounce_t *debounce, uint64_t now_ns)
asciichat_error_t grep_restore_patterns(void)
Restore previously saved filter patterns.
Definition grep.c:1173
asciichat_error_t grep_save_patterns(void)
Save current filter patterns for later restoration.
Definition grep.c:1157
int pattern_count
Number of active patterns.
Definition grep.c:61
const char * grep_get_last_pattern(void)
Get the last (most recent) filter pattern string.
Definition grep.c:1198
grep_parse_result_t grep_parse_pattern(const char *input)
Parse pattern in /pattern/flags or pattern/flags format.
Definition grep.c:269
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
struct session_log_buffer session_log_buffer_t
Thread-safe fixed-size history ring for session-screen log lines.
session_log_buffer_t * log_get_session_log_buffer(void)
Get the currently registered session log buffer.
Definition log/log.c:2287
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
int utf8_decode(const uint8_t *s, uint32_t *codepoint)
Decode a UTF-8 sequence to a Unicode codepoint.
Definition utf8.c:28
const char * utf8_strcasestr(const char *haystack, const char *needle)
Case-insensitive substring search with full Unicode support.
Definition utf8.c:212
⚙️ Common definitions, error codes, macros, and types shared throughout the application
session_log_buffer_t * log_get_history_buffer(void)
Definition log/log.c:625
📝 Logging API with multiple log levels and terminal output control
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
void ascii_otel_ui_usage(const char *screen, const char *event, uint64_t duration_ns)
Definition otel.c:506
pcre2_code * asciichat_pcre2_compile(const char *pattern, uint32_t flags)
Definition pcre2.c:16
PCRE2 compilation and match helpers.
asciichat_error_t log_search_init(void)
Initialize interactive grep subsystem.
Definition search.c:148
void * log_search_get_mutex(void)
Get the mutex protecting grep state.
Definition search.c:1031
bool log_search_needs_rerender(void)
Check if screen needs immediate re-render.
Definition search.c:979
bool log_search_check_signal_cancel(void)
Check and clear the signal-cancel flag.
Definition search.c:418
void log_search_signal_cancel(void)
Cancel grep mode from a signal handler (async-signal-safe).
Definition search.c:414
bool log_search_is_entering(void)
Check if currently in input mode (typing pattern).
Definition search.c:423
void log_search_process_pending(void)
Definition search.c:489
#define MAX_LOG_SEARCH_PATTERNS
Maximum number of patterns to support.
Definition search.c:41
bool log_search_get_global_highlight(void)
Check if global highlighting (/g flag) is enabled in current pattern.
Definition search.c:991
int log_search_get_input_len(void)
Get current input buffer length (must hold mutex).
Definition search.c:1033
void log_search_enter_mode(void)
Enter search mode (user pressed '/').
Definition search.c:233
asciichat_error_t log_search_insert_text(const char *text)
Definition search.c:501
asciichat_error_t log_search_filter_buffer(session_log_buffer_t *log_buf, session_log_entry_t **out_entries, size_t *out_count)
Definition search.c:603
const char * log_search_get_input_buffer(void)
Get current input buffer content (must hold mutex).
Definition search.c:1037
bool log_search_is_active(void)
Check if filtering is active.
Definition search.c:430
bool log_search_get_case_insensitive(void)
Check if case-insensitive flag is set (must hold mutex).
Definition search.c:1041
void log_search_exit_mode(bool accept)
Exit search mode.
Definition search.c:312
void * log_search_copy_pattern(void)
Get the compiled regex pattern for interactive grep (internal use).
Definition search.c:1006
bool log_search_get_match_info(const char *message, size_t *out_match_start, size_t *out_match_len)
Get match info for highlighting a log message.
Definition search.c:811
bool log_search_should_handle(int key)
Check if a key should be handled by grep module.
Definition search.c:441
#define LOG_SEARCH_OUTPUT_BUFFER_SIZE
Definition search.c:3
#define LOG_SEARCH_DEBOUNCE_NS
Definition search.c:43
void log_search_destroy(void)
Clean up interactive grep subsystem.
Definition search.c:210
int log_search_get_cursor_position(void)
Get current cursor position in input buffer (must hold mutex).
Definition search.c:1035
asciichat_error_t log_search_handle_key(keyboard_key_t key)
Process keyboard input for grep.
Definition search.c:532
void log_search_render_input_line(int width)
Render grep input line at bottom of screen.
Definition search.c:772
bool log_search_is_entering_atomic(void)
Check if grep is in entering mode (async-signal-safe).
Definition search.c:409
asciichat_error_t log_search_gather_and_filter_logs(session_log_entry_t **out_entries, size_t *out_count)
Gather and filter logs for display.
Definition search.c:596
#define LOG_SEARCH_INPUT_BUFFER_SIZE
Input buffer size.
Definition search.c:42
Interactive search filtering for terminal screens.
log_search_mode_t
Search mode states.
Definition search.h:36
@ LOG_SEARCH_MODE_ACTIVE
Pattern accepted and filtering.
Definition search.h:39
@ LOG_SEARCH_MODE_ENTERING
'/' pressed, typing pattern
Definition search.h:38
@ LOG_SEARCH_MODE_INACTIVE
Not in search mode.
Definition search.h:37
size_t session_log_buffer_get_recent(session_log_buffer_t *buf, session_log_entry_t *out_entries, size_t max_count)
Get recent log entries from buffer.
Thread-safe circular log buffer for session screens (status, splash).
#define SESSION_LOG_BUFFER_SIZE
#define SESSION_LOG_LINE_MAX
int terminal_cursor_show(void)
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
Parsed pattern result from /pattern/flags syntax.
Definition grep.h:26
int context_before
Lines before match (B<n> flag).
Definition grep.h:33
bool global_flag
Highlight all matches (g flag).
Definition grep.h:32
bool is_fixed_string
True if fixed string (not regex).
Definition grep.h:29
bool invert
Invert match (I flag).
Definition grep.h:31
char pattern[4096]
Parsed pattern string.
Definition grep.h:27
bool case_insensitive
Case-insensitive (i flag).
Definition grep.h:30
bool valid
True if parsing succeeded.
Definition grep.h:35
int context_after
Lines after match (A<n> flag).
Definition grep.h:34
uint32_t pcre2_options
PCRE2 compile options.
Definition grep.h:28
char previous_patterns[32][256]
Definition search.c:56
atomic_t mode_atomic
Shadow of mode for signal-safe reads.
Definition search.c:75
bool cli_pattern_auto_populated
Definition search.c:76
int previous_pattern_count
Definition search.c:57
int active_pattern_count
Definition search.c:61
flow_control_debounce_t debounce
Definition search.c:78
log_search_mode_t mode
Definition search.c:50
atomic_t needs_rerender
Definition search.c:73
atomic_t signal_cancelled
Set by signal handler, checked by render loop.
Definition search.c:74
pcre2_code * active_patterns[32]
Definition search.c:60
bool global_highlight
Definition search.c:66
bool case_insensitive
Definition search.c:64
mutex_t mutex
Definition search.c:71
char input_buffer[256]
Definition search.c:51
lifecycle_t lifecycle
Definition search.c:72
One formatted session log line and its monotonic history sequence.
char message[1024]
ANSI colors).
⏱️ High-precision timing utilities using sokol_time.h and uthash
asciichat_error_t ui_controller_write(int fd, const char *data, size_t len)
asciichat_error_t ui_controller_printf(int fd, const char *format,...)
asciichat_error_t ui_input_insert(char *buffer, size_t capacity, size_t *length, size_t *cursor, const char *text)
Definition ui/input.c:145
🔤 UTF-8 Encoding and Decoding Utilities
keyboard_line_edit_result_t keyboard_read_line_interactive(keyboard_line_edit_opts_t *opts)
Definition util.c:29