Skip to main content

ftui_widgets/
log_viewer.rs

1#![forbid(unsafe_code)]
2
3//! A scrolling log viewer widget optimized for streaming append-only content.
4//!
5//! `LogViewer` is THE essential widget for agent harness UIs. It displays streaming
6//! logs with scrollback while maintaining UI chrome and handles:
7//!
8//! - High-frequency log line additions without flicker
9//! - Auto-scroll behavior for "follow" mode
10//! - Manual scrolling to inspect history
11//! - Memory bounds via circular buffer eviction
12//! - Substring filtering for log lines
13//! - Text search with next/prev match navigation
14//!
15//! # Architecture
16//!
17//! LogViewer delegates storage and scroll state to [`Virtualized<Text>`], gaining
18//! momentum scrolling, overscan, and page navigation for free. LogViewer adds
19//! capacity management (eviction), wrapping, filtering, and search on top.
20//!
21//! # Example
22//! ```ignore
23//! use ftui_widgets::log_viewer::{LogViewer, LogViewerState, LogWrapMode};
24//! use ftui_text::Text;
25//!
26//! // Create a viewer with 10,000 line capacity
27//! let mut viewer = LogViewer::new(10_000);
28//!
29//! // Push log lines (styled or plain)
30//! viewer.push("Starting process...");
31//! viewer.push(Text::styled("ERROR: failed", Style::new().fg(Color::Red)));
32//!
33//! // Render with state
34//! let mut state = LogViewerState::default();
35//! viewer.render(area, frame, &mut state);
36//! ```
37
38use ftui_core::geometry::Rect;
39use ftui_render::frame::Frame;
40use ftui_style::Style;
41use ftui_text::search::{search_ascii_case_insensitive, search_exact};
42use ftui_text::{
43    Line, Span, Text as FtuiText, WrapMode, WrapOptions, display_width, wrap_with_options,
44};
45
46use crate::virtualized::Virtualized;
47use crate::{StatefulWidget, clear_text_area, draw_text_span, draw_text_span_with_link};
48
49type Text = FtuiText<'static>;
50
51fn text_into_owned(text: FtuiText<'_>) -> FtuiText<'static> {
52    FtuiText::from_lines(
53        text.into_iter()
54            .map(|line| Line::from_spans(line.into_iter().map(Span::into_owned))),
55    )
56}
57
58/// Line wrapping mode for log lines.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum LogWrapMode {
61    /// No wrapping, truncate long lines.
62    #[default]
63    NoWrap,
64    /// Wrap at any character boundary.
65    CharWrap,
66    /// Wrap at word boundaries (Unicode-aware).
67    WordWrap,
68}
69
70impl From<LogWrapMode> for WrapMode {
71    fn from(mode: LogWrapMode) -> Self {
72        match mode {
73            LogWrapMode::NoWrap => WrapMode::None,
74            LogWrapMode::CharWrap => WrapMode::Char,
75            LogWrapMode::WordWrap => WrapMode::Word,
76        }
77    }
78}
79
80/// Search mode for log search.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82pub enum SearchMode {
83    /// Plain substring matching.
84    #[default]
85    Literal,
86    /// Regular expression matching (requires `regex-search` feature).
87    Regex,
88}
89
90/// Search configuration.
91#[derive(Clone, Debug)]
92pub struct SearchConfig {
93    /// Search mode (literal or regex).
94    pub mode: SearchMode,
95    /// Whether the search is case-sensitive.
96    pub case_sensitive: bool,
97    /// Number of context lines around matches (0 = only matching lines).
98    pub context_lines: usize,
99}
100
101impl Default for SearchConfig {
102    fn default() -> Self {
103        Self {
104            mode: SearchMode::Literal,
105            case_sensitive: true,
106            context_lines: 0,
107        }
108    }
109}
110
111/// Search state for text search within the log.
112#[derive(Debug, Clone)]
113struct SearchState {
114    /// The search query string (retained for re-search after eviction).
115    query: String,
116    /// Lowercase query for case-insensitive search optimization.
117    query_lower: Option<String>,
118    /// Current search configuration.
119    config: SearchConfig,
120    /// Indices of matching lines.
121    matches: Vec<usize>,
122    /// Current match index within the matches vector.
123    current: usize,
124    /// Per-match-line byte ranges for highlighting. Indexed by position in `matches`.
125    highlight_ranges: Vec<Vec<(usize, usize)>>,
126    /// Compiled regex pattern (behind feature gate).
127    #[cfg(feature = "regex-search")]
128    compiled_regex: Option<regex::Regex>,
129    /// Indices including context lines around matches (sorted, deduped).
130    /// `None` when `config.context_lines == 0`.
131    context_expanded: Option<Vec<usize>>,
132}
133
134/// Statistics tracking incremental vs full-rescan filter/search operations.
135///
136/// Useful for monitoring the efficiency of the streaming update path.
137/// Reset with [`FilterStats::reset`].
138#[derive(Debug, Clone, Default)]
139pub struct FilterStats {
140    /// Lines checked incrementally (O(1) per push).
141    pub incremental_checks: u64,
142    /// Lines that matched during incremental checks.
143    pub incremental_matches: u64,
144    /// Full rescans triggered (e.g., by `set_filter` or `search`).
145    pub full_rescans: u64,
146    /// Total lines scanned during full rescans.
147    pub full_rescan_lines: u64,
148    /// Search matches added incrementally on push.
149    pub incremental_search_matches: u64,
150    /// Lines checked incrementally for search matches.
151    pub incremental_search_checks: u64,
152}
153
154impl FilterStats {
155    /// Reset all counters to zero.
156    pub fn reset(&mut self) {
157        *self = Self::default();
158    }
159}
160
161/// A scrolling log viewer optimized for streaming append-only content.
162///
163/// Internally uses [`Virtualized<Text>`] for storage and scroll management,
164/// adding capacity enforcement, wrapping, filtering, and search on top.
165///
166/// # Design Rationale
167/// - Virtualized handles scroll offset, follow mode, momentum, page navigation
168/// - LogViewer adds max_lines eviction (Virtualized has no built-in capacity limit)
169/// - Separate scroll semantics: Virtualized uses "offset from top"; LogViewer
170///   exposes "follow mode" (newest at bottom) as the default behavior
171/// - wrap_mode configurable per-instance for different use cases
172/// - Stateful widget pattern for scroll state preservation across renders
173#[derive(Debug, Clone)]
174pub struct LogViewer {
175    /// Virtualized storage with scroll state management.
176    virt: Virtualized<Text>,
177    /// Maximum lines to retain (memory bound).
178    max_lines: usize,
179    /// Optional trailing line count whose span links are retained.
180    link_retention_lines: Option<usize>,
181    /// Line wrapping mode.
182    wrap_mode: LogWrapMode,
183    /// Default style for lines.
184    style: Style,
185    /// Highlight style for selected/focused line.
186    highlight_style: Option<Style>,
187    /// Highlight style for search matches within a line.
188    search_highlight_style: Option<Style>,
189    /// Active filter pattern (plain substring match).
190    filter: Option<String>,
191    /// Indices of lines matching the filter (None = show all).
192    filtered_indices: Option<Vec<usize>>,
193    /// Scroll offset within the filtered set (top index of filtered list).
194    filtered_scroll_offset: usize,
195    /// Active search state.
196    search: Option<SearchState>,
197    /// Incremental filter/search statistics.
198    filter_stats: FilterStats,
199}
200
201/// Separate state for StatefulWidget pattern.
202#[derive(Debug, Clone, Default)]
203pub struct LogViewerState {
204    /// Viewport height from last render (for page up/down).
205    pub last_viewport_height: u16,
206    /// Total visible line count from last render.
207    pub last_visible_lines: usize,
208    /// Selected line index (for copy/selection features).
209    pub selected_line: Option<usize>,
210}
211
212impl LogViewer {
213    /// Create a new LogViewer with specified max line capacity.
214    ///
215    /// # Arguments
216    /// * `max_lines` - Maximum lines to retain. When exceeded, oldest lines
217    ///   are evicted. Recommend 10,000-100,000 for typical agent use cases.
218    #[must_use]
219    pub fn new(max_lines: usize) -> Self {
220        Self {
221            virt: Virtualized::new(max_lines).with_follow(true),
222            max_lines,
223            link_retention_lines: None,
224            wrap_mode: LogWrapMode::NoWrap,
225            style: Style::default(),
226            highlight_style: None,
227            search_highlight_style: None,
228            filter: None,
229            filtered_indices: None,
230            filtered_scroll_offset: 0,
231            search: None,
232            filter_stats: FilterStats::default(),
233        }
234    }
235
236    /// Set the wrap mode.
237    #[must_use]
238    pub fn wrap_mode(mut self, mode: LogWrapMode) -> Self {
239        self.wrap_mode = mode;
240        self
241    }
242
243    /// Keep hyperlink metadata only on the newest `lines` retained records.
244    ///
245    /// Older records keep their text and styling, but their spans lose link
246    /// targets. This applies immediately to existing records and after each
247    /// appended line, including lines within a multi-line push. Zero strips all
248    /// links. By default, links remain for the full text retention period.
249    /// Increasing this limit cannot restore targets already removed.
250    #[must_use]
251    pub fn retain_links_for_last_lines(mut self, lines: usize) -> Self {
252        self.link_retention_lines = Some(lines);
253        for index in 0..self.virt.len().saturating_sub(lines) {
254            self.strip_line_links(index);
255        }
256        self
257    }
258
259    fn strip_line_links(&mut self, index: usize) {
260        let Some(text) = self.virt.get_mut(index) else {
261            return;
262        };
263        if !text
264            .lines()
265            .iter()
266            .flat_map(|line| line.spans())
267            .any(|span| span.link.is_some())
268        {
269            return;
270        }
271        *text = Text::from_lines(std::mem::take(text).into_iter().map(|line| {
272            Line::from_spans(line.into_iter().map(|mut span| {
273                span.link = None;
274                span
275            }))
276        }));
277    }
278
279    /// Set the default style for lines.
280    #[must_use]
281    pub fn style(mut self, style: Style) -> Self {
282        self.style = style;
283        self
284    }
285
286    /// Set the highlight style for selected lines.
287    #[must_use]
288    pub fn highlight_style(mut self, style: Style) -> Self {
289        self.highlight_style = Some(style);
290        self
291    }
292
293    /// Set the highlight style for search matches within lines.
294    #[must_use]
295    pub fn search_highlight_style(mut self, style: Style) -> Self {
296        self.search_highlight_style = Some(style);
297        self
298    }
299
300    /// Returns the total number of log lines.
301    #[inline]
302    #[must_use]
303    pub fn len(&self) -> usize {
304        self.virt.len()
305    }
306
307    /// Returns true if there are no log lines.
308    #[inline]
309    #[must_use]
310    pub fn is_empty(&self) -> bool {
311        self.virt.is_empty()
312    }
313
314    /// Append a single log line.
315    ///
316    /// # Performance
317    /// - O(1) amortized for append
318    /// - O(1) for eviction when at capacity
319    ///
320    /// # Auto-scroll Behavior
321    /// If follow mode is enabled, view stays at bottom after push.
322    pub fn push<'a>(&mut self, line: impl Into<FtuiText<'a>>) {
323        let follow_filtered = self.filtered_indices.as_ref().is_some_and(|indices| {
324            self.is_filtered_at_bottom(indices.len(), self.virt.visible_count())
325        });
326        let text: Text = text_into_owned(line.into());
327
328        // Split multi-line text into individual items for smooth scrolling
329        for line in text.into_iter() {
330            let item = Text::from_line(line);
331            let plain = item.to_plain_text();
332
333            // Incremental filter check: test new line against active filter.
334            let filter_matched = if let Some(filter) = self.filter.as_ref() {
335                self.filter_stats.incremental_checks += 1;
336                let matched = plain.contains(filter.as_str());
337                if matched {
338                    if let Some(indices) = self.filtered_indices.as_mut() {
339                        let idx = self.virt.len();
340                        indices.push(idx);
341                    }
342                    self.filter_stats.incremental_matches += 1;
343                }
344                matched
345            } else {
346                false
347            };
348
349            // Incremental search check: test new line against active search query.
350            // Only add to search matches if (a) there is no filter or (b) the
351            // line passed the filter, because search results respect the filter.
352            if let Some(ref mut search) = self.search {
353                let should_check = self.filter.is_none() || filter_matched;
354                if should_check {
355                    self.filter_stats.incremental_search_checks += 1;
356                    let ranges = find_match_ranges(
357                        &plain,
358                        &search.query,
359                        search.query_lower.as_deref(),
360                        &search.config,
361                        #[cfg(feature = "regex-search")]
362                        search.compiled_regex.as_ref(),
363                    );
364                    if !ranges.is_empty() {
365                        let idx = self.virt.len();
366                        search.matches.push(idx);
367                        search.highlight_ranges.push(ranges);
368                        self.filter_stats.incremental_search_matches += 1;
369                    }
370                }
371            }
372
373            self.virt.push(item);
374
375            // Only one record crosses the metadata boundary per appended line.
376            if let Some(lines) = self.link_retention_lines
377                && let Some(index) = self
378                    .virt
379                    .len()
380                    .checked_sub(lines)
381                    .and_then(|n| n.checked_sub(1))
382            {
383                self.strip_line_links(index);
384            }
385
386            // Enforce capacity
387            if self.virt.len() > self.max_lines {
388                let removed = self.virt.trim_front(self.max_lines);
389
390                // Adjust filtered indices
391                if let Some(ref mut indices) = self.filtered_indices {
392                    let mut filtered_removed = 0usize;
393                    indices.retain_mut(|idx| {
394                        if *idx < removed {
395                            filtered_removed += 1;
396                            false
397                        } else {
398                            *idx -= removed;
399                            true
400                        }
401                    });
402                    if filtered_removed > 0 {
403                        self.filtered_scroll_offset =
404                            self.filtered_scroll_offset.saturating_sub(filtered_removed);
405                    }
406                    if indices.is_empty() {
407                        self.filtered_scroll_offset = 0;
408                    }
409                }
410
411                // Adjust search match indices and corresponding highlight_ranges
412                if let Some(ref mut search) = self.search {
413                    let mut keep = Vec::with_capacity(search.matches.len());
414                    let mut new_highlights = Vec::with_capacity(search.highlight_ranges.len());
415                    let mut evicted_matches = 0;
416                    for (i, idx) in search.matches.iter_mut().enumerate() {
417                        if *idx < removed {
418                            evicted_matches += 1;
419                        } else {
420                            *idx -= removed;
421                            keep.push(*idx);
422                            if i < search.highlight_ranges.len() {
423                                new_highlights
424                                    .push(std::mem::take(&mut search.highlight_ranges[i]));
425                            }
426                        }
427                    }
428                    search.matches = keep;
429                    search.highlight_ranges = new_highlights;
430                    search.current = search.current.saturating_sub(evicted_matches);
431                    // Clamp current to valid range
432                    if !search.matches.is_empty() {
433                        search.current = search.current.min(search.matches.len() - 1);
434                    } else {
435                        search.current = 0;
436                    }
437                    // Recompute context expansion if needed
438                    if search.config.context_lines > 0 {
439                        search.context_expanded = Some(expand_context(
440                            &search.matches,
441                            search.config.context_lines,
442                            self.virt.len(),
443                        ));
444                    }
445                }
446            }
447
448            if follow_filtered
449                && let Some(indices) = self.filtered_indices.as_ref()
450                && !indices.is_empty()
451            {
452                self.filtered_scroll_offset = indices.len().saturating_sub(1);
453            }
454        }
455    }
456
457    /// Append multiple lines efficiently.
458    pub fn push_many<'a>(&mut self, lines: impl IntoIterator<Item = impl Into<FtuiText<'a>>>) {
459        for line in lines {
460            self.push(line);
461        }
462    }
463
464    /// Scroll up by N lines. Disables follow mode.
465    pub fn scroll_up(&mut self, lines: usize) {
466        if self.filtered_indices.is_some() {
467            // Clamp usize::MAX sentinel (set by scroll_to_bottom when viewport unknown)
468            if let Some(filtered_total) = self.filtered_indices.as_ref().map(Vec::len) {
469                let max = filtered_total.saturating_sub(1);
470                if self.filtered_scroll_offset > max {
471                    self.filtered_scroll_offset = max;
472                }
473            }
474            self.filtered_scroll_offset = self.filtered_scroll_offset.saturating_sub(lines);
475            self.virt.set_follow(false);
476        } else {
477            let delta = i32::try_from(lines).unwrap_or(i32::MAX);
478            self.virt.scroll(-delta);
479        }
480    }
481
482    /// Scroll down by N lines. Re-enables follow mode if at bottom.
483    pub fn scroll_down(&mut self, lines: usize) {
484        if let Some(filtered_total) = self.filtered_indices.as_ref().map(Vec::len) {
485            if filtered_total == 0 {
486                self.filtered_scroll_offset = 0;
487            } else {
488                // Clamp usize::MAX sentinel before arithmetic
489                let visible_count = self.virt.visible_count();
490                let max_offset = filtered_total.saturating_sub(visible_count.max(1));
491                if self.filtered_scroll_offset > max_offset {
492                    self.filtered_scroll_offset = max_offset;
493                }
494                self.filtered_scroll_offset = self.filtered_scroll_offset.saturating_add(lines);
495                if self.filtered_scroll_offset > max_offset {
496                    self.filtered_scroll_offset = max_offset;
497                }
498            }
499            // Re-enable follow if we scrolled to the bottom of the filtered set.
500            let vc = self.virt.visible_count();
501            if self.is_filtered_at_bottom(filtered_total, vc) {
502                self.virt.set_follow(true);
503            }
504        } else {
505            let delta = i32::try_from(lines).unwrap_or(i32::MAX);
506            self.virt.scroll(delta);
507            if self.virt.is_at_bottom() {
508                self.virt.set_follow(true);
509            }
510        }
511    }
512
513    /// Jump to top of log history. Disables follow mode.
514    pub fn scroll_to_top(&mut self) {
515        if self.filtered_indices.is_some() {
516            self.filtered_scroll_offset = 0;
517            self.virt.set_follow(false);
518        } else {
519            self.virt.scroll_to_top();
520        }
521    }
522
523    /// Jump to bottom and re-enable follow mode.
524    pub fn scroll_to_bottom(&mut self) {
525        if let Some(filtered_total) = self.filtered_indices.as_ref().map(Vec::len) {
526            if filtered_total == 0 {
527                self.filtered_scroll_offset = 0;
528            } else {
529                let visible_count = self.virt.visible_count();
530                if visible_count == 0 {
531                    // Viewport unknown; keep sentinel and clamp during render.
532                    self.filtered_scroll_offset = usize::MAX;
533                } else {
534                    self.filtered_scroll_offset = filtered_total.saturating_sub(visible_count);
535                }
536            }
537            self.virt.set_follow(true);
538        } else {
539            self.virt.scroll_to_end();
540        }
541    }
542
543    /// Page up (scroll by viewport height).
544    ///
545    /// Uses the visible count tracked by the Virtualized container.
546    /// The `state` parameter is accepted for API compatibility.
547    pub fn page_up(&mut self, _state: &LogViewerState) {
548        if self.filtered_indices.is_some() {
549            let lines = _state.last_viewport_height as usize;
550            if lines > 0 {
551                self.scroll_up(lines);
552            }
553        } else {
554            self.virt.page_up();
555        }
556    }
557
558    /// Page down (scroll by viewport height).
559    ///
560    /// Uses the visible count tracked by the Virtualized container.
561    /// The `state` parameter is accepted for API compatibility.
562    pub fn page_down(&mut self, _state: &LogViewerState) {
563        if self.filtered_indices.is_some() {
564            let lines = _state.last_viewport_height as usize;
565            if lines > 0 {
566                self.scroll_down(lines);
567            }
568        } else {
569            self.virt.page_down();
570            if self.virt.is_at_bottom() {
571                self.virt.set_follow(true);
572            }
573        }
574    }
575
576    /// Check if currently scrolled to the bottom.
577    ///
578    /// Returns `true` when follow mode is active (even before first render
579    /// when the viewport size is unknown).
580    #[must_use]
581    pub fn is_at_bottom(&self) -> bool {
582        if let Some(indices) = self.filtered_indices.as_ref() {
583            self.is_filtered_at_bottom(indices.len(), self.virt.visible_count())
584        } else {
585            self.virt.follow_mode() || self.virt.is_at_bottom()
586        }
587    }
588
589    /// Total line count in buffer.
590    #[must_use]
591    pub fn line_count(&self) -> usize {
592        self.virt.len()
593    }
594
595    /// Check if follow mode (auto-scroll) is enabled.
596    #[must_use]
597    pub fn auto_scroll_enabled(&self) -> bool {
598        self.virt.follow_mode()
599    }
600
601    /// Set follow mode (auto-scroll) state.
602    pub fn set_auto_scroll(&mut self, enabled: bool) {
603        self.virt.set_follow(enabled);
604    }
605
606    /// Toggle follow mode on/off.
607    pub fn toggle_follow(&mut self) {
608        let current = self.virt.follow_mode();
609        self.virt.set_follow(!current);
610    }
611
612    /// Clear all lines.
613    pub fn clear(&mut self) {
614        self.virt.clear();
615        self.filtered_indices = self.filter.as_ref().map(|_| Vec::new());
616        self.filtered_scroll_offset = 0;
617        self.search = None;
618        self.filter_stats.reset();
619    }
620
621    /// Get a reference to the incremental filter/search statistics.
622    ///
623    /// Use this to monitor how often the streaming incremental path is used
624    /// versus full rescans.
625    #[must_use]
626    pub fn filter_stats(&self) -> &FilterStats {
627        &self.filter_stats
628    }
629
630    /// Get a mutable reference to the filter statistics (for resetting).
631    pub fn filter_stats_mut(&mut self) -> &mut FilterStats {
632        &mut self.filter_stats
633    }
634
635    /// Set a filter pattern (plain substring match).
636    ///
637    /// Only lines containing the pattern will be shown. Pass `None` to clear.
638    pub fn set_filter(&mut self, pattern: Option<&str>) {
639        match pattern {
640            Some(pat) if !pat.is_empty() => {
641                // Full rescan: rebuild filtered indices from all lines.
642                self.filter_stats.full_rescans += 1;
643                self.filter_stats.full_rescan_lines += self.virt.len() as u64;
644                let mut indices = Vec::new();
645                for idx in 0..self.virt.len() {
646                    if let Some(item) = self.virt.get(idx)
647                        && item.to_plain_text().contains(pat)
648                    {
649                        indices.push(idx);
650                    }
651                }
652                self.filter = Some(pat.to_string());
653                self.filtered_indices = Some(indices);
654                self.filtered_scroll_offset = if let Some(indices) = self.filtered_indices.as_ref()
655                {
656                    if indices.is_empty() {
657                        0
658                    } else if self.virt.follow_mode() || self.virt.is_at_bottom() {
659                        indices.len().saturating_sub(1)
660                    } else {
661                        let scroll_offset = self.virt.scroll_offset();
662                        indices.partition_point(|&idx| idx < scroll_offset)
663                    }
664                } else {
665                    0
666                };
667                self.search = None;
668            }
669            _ => {
670                self.filter = None;
671                self.filtered_indices = None;
672                self.filtered_scroll_offset = 0;
673                self.search = None;
674            }
675        }
676    }
677
678    /// Search for text and return match count.
679    ///
680    /// Convenience wrapper using default config (literal, case-sensitive, no context).
681    /// Sets up search state for navigation with `next_match` / `prev_match`.
682    pub fn search(&mut self, query: &str) -> usize {
683        self.search_with_config(query, SearchConfig::default())
684    }
685
686    /// Search with full configuration (mode, case sensitivity, context lines).
687    ///
688    /// Returns match count. Sets up state for `next_match` / `prev_match`.
689    pub fn search_with_config(&mut self, query: &str, config: SearchConfig) -> usize {
690        if query.is_empty() {
691            self.search = None;
692            return 0;
693        }
694
695        // Compile regex if needed
696        #[cfg(feature = "regex-search")]
697        let compiled_regex = if config.mode == SearchMode::Regex {
698            match compile_regex(query, &config) {
699                Some(re) => Some(re),
700                None => {
701                    // Invalid regex — clear search and return 0
702                    self.search = None;
703                    return 0;
704                }
705            }
706        } else {
707            None
708        };
709
710        // Pre-compute lowercase query for optimization
711        let query_lower = if !config.case_sensitive {
712            Some(query.to_ascii_lowercase())
713        } else {
714            None
715        };
716
717        // Full rescan for search matches.
718        self.filter_stats.full_rescans += 1;
719        let mut matches = Vec::new();
720        let mut highlight_ranges = Vec::new();
721
722        let iter: Box<dyn Iterator<Item = usize>> =
723            if let Some(indices) = self.filtered_indices.as_ref() {
724                self.filter_stats.full_rescan_lines += indices.len() as u64;
725                Box::new(indices.iter().copied())
726            } else {
727                self.filter_stats.full_rescan_lines += self.virt.len() as u64;
728                Box::new(0..self.virt.len())
729            };
730
731        for idx in iter {
732            if let Some(item) = self.virt.get(idx) {
733                let plain = item.to_plain_text();
734                let ranges = find_match_ranges(
735                    &plain,
736                    query,
737                    query_lower.as_deref(),
738                    &config,
739                    #[cfg(feature = "regex-search")]
740                    compiled_regex.as_ref(),
741                );
742                if !ranges.is_empty() {
743                    matches.push(idx);
744                    highlight_ranges.push(ranges);
745                }
746            }
747        }
748
749        let count = matches.len();
750
751        let context_expanded = if config.context_lines > 0 {
752            Some(expand_context(
753                &matches,
754                config.context_lines,
755                self.virt.len(),
756            ))
757        } else {
758            None
759        };
760
761        self.search = Some(SearchState {
762            query: query.to_string(),
763            query_lower,
764            config,
765            matches,
766            current: 0,
767            highlight_ranges,
768            #[cfg(feature = "regex-search")]
769            compiled_regex,
770            context_expanded,
771        });
772
773        // Jump to first match
774        if let Some(ref search) = self.search
775            && let Some(&idx) = search.matches.first()
776        {
777            self.scroll_to_match(idx);
778        }
779
780        count
781    }
782
783    /// Jump to next search match.
784    pub fn next_match(&mut self) {
785        if let Some(ref mut search) = self.search
786            && !search.matches.is_empty()
787        {
788            search.current = (search.current + 1) % search.matches.len();
789            let idx = search.matches[search.current];
790            self.scroll_to_match(idx);
791        }
792    }
793
794    /// Jump to previous search match.
795    pub fn prev_match(&mut self) {
796        if let Some(ref mut search) = self.search
797            && !search.matches.is_empty()
798        {
799            search.current = if search.current == 0 {
800                search.matches.len() - 1
801            } else {
802                search.current - 1
803            };
804            let idx = search.matches[search.current];
805            self.scroll_to_match(idx);
806        }
807    }
808
809    /// Clear active search.
810    pub fn clear_search(&mut self) {
811        self.search = None;
812    }
813
814    /// Get current search match info: (current_match_1indexed, total_matches).
815    #[must_use]
816    pub fn search_info(&self) -> Option<(usize, usize)> {
817        self.search.as_ref().and_then(|s| {
818            if s.matches.is_empty() {
819                None
820            } else {
821                Some((s.current + 1, s.matches.len()))
822            }
823        })
824    }
825
826    /// Get the highlight byte ranges for a given line index, if any.
827    ///
828    /// Returns `Some(&[(start, end)])` when the line is a search match.
829    #[must_use]
830    pub fn highlight_ranges_for_line(&self, line_idx: usize) -> Option<&[(usize, usize)]> {
831        let search = self.search.as_ref()?;
832        let pos = search.matches.iter().position(|&m| m == line_idx)?;
833        search.highlight_ranges.get(pos).map(|v| v.as_slice())
834    }
835
836    /// Get the context-expanded line indices, if context lines are configured.
837    ///
838    /// Returns `None` when no search is active or `context_lines == 0`.
839    #[must_use]
840    pub fn context_line_indices(&self) -> Option<&[usize]> {
841        self.search
842            .as_ref()
843            .and_then(|s| s.context_expanded.as_deref())
844    }
845
846    /// Returns the fraction of recent pushes that matched the active search.
847    ///
848    /// Useful for callers integrating with an `EProcessThrottle` to decide
849    /// when to trigger a full UI refresh vs. deferring.
850    /// Returns 0.0 when no search is active or no incremental checks occurred.
851    #[must_use]
852    pub fn search_match_rate_hint(&self) -> f64 {
853        let stats = &self.filter_stats;
854        if stats.incremental_search_checks == 0 {
855            return 0.0;
856        }
857        stats.incremental_search_matches as f64 / stats.incremental_search_checks as f64
858    }
859
860    /// Rows `text` occupies at `width` under the current wrap mode; the same
861    /// decision [`Self::render_line`] makes.
862    fn wrapped_rows(&self, text: &Text, width: u16) -> u16 {
863        if matches!(self.wrap_mode, LogWrapMode::NoWrap) {
864            return 1;
865        }
866        let content = text.to_plain_text();
867        if display_width(&content) <= width as usize {
868            return 1;
869        }
870        let options = WrapOptions::new(width as usize).mode(self.wrap_mode.into());
871        u16::try_from(wrap_with_options(&content, &options).len())
872            .unwrap_or(u16::MAX)
873            .max(1)
874    }
875
876    /// Render a single line with optional wrapping and search highlighting.
877    /// `skip_rows` drops that many leading wrapped rows (the entry is clipped
878    /// at the top of the viewport); it has no effect on a one-row entry.
879    #[allow(clippy::too_many_arguments)]
880    fn render_line(
881        &self,
882        text: &Text,
883        line_idx: usize,
884        x: u16,
885        y: u16,
886        width: u16,
887        max_y: u16,
888        frame: &mut Frame,
889        is_selected: bool,
890        skip_rows: u16,
891    ) -> u16 {
892        let effective_style = if is_selected {
893            self.highlight_style.unwrap_or(self.style)
894        } else {
895            self.style
896        };
897
898        let line = text.lines().first();
899        let content = text.to_plain_text();
900        let content_width = display_width(&content);
901        let hl_ranges = self.highlight_ranges_for_line(line_idx);
902
903        // Handle wrapping
904        match self.wrap_mode {
905            LogWrapMode::NoWrap => {
906                if y < max_y {
907                    if let Some(ranges) = hl_ranges.filter(|r| !r.is_empty()) {
908                        self.draw_highlighted_line(
909                            &content,
910                            ranges,
911                            x,
912                            y,
913                            x.saturating_add(width),
914                            frame,
915                            effective_style,
916                        );
917                    } else {
918                        self.draw_text_line(
919                            line,
920                            &content,
921                            x,
922                            y,
923                            x.saturating_add(width),
924                            frame,
925                            effective_style,
926                        );
927                    }
928                }
929                1
930            }
931            LogWrapMode::CharWrap | LogWrapMode::WordWrap => {
932                if content_width <= width as usize {
933                    if y < max_y {
934                        if let Some(ranges) = hl_ranges.filter(|r| !r.is_empty()) {
935                            self.draw_highlighted_line(
936                                &content,
937                                ranges,
938                                x,
939                                y,
940                                x.saturating_add(width),
941                                frame,
942                                effective_style,
943                            );
944                        } else {
945                            self.draw_text_line(
946                                line,
947                                &content,
948                                x,
949                                y,
950                                x.saturating_add(width),
951                                frame,
952                                effective_style,
953                            );
954                        }
955                    }
956                    1
957                } else {
958                    let options = WrapOptions::new(width as usize).mode(self.wrap_mode.into());
959                    let wrapped = wrap_with_options(&content, &options);
960                    let mut lines_rendered = 0u16;
961
962                    for (i, part) in wrapped.into_iter().skip(skip_rows as usize).enumerate() {
963                        let line_y = y.saturating_add(i as u16);
964                        if line_y >= max_y {
965                            break;
966                        }
967                        draw_text_span(
968                            frame,
969                            x,
970                            line_y,
971                            &part,
972                            effective_style,
973                            x.saturating_add(width),
974                        );
975                        lines_rendered += 1;
976                    }
977
978                    lines_rendered.max(1)
979                }
980            }
981        }
982    }
983
984    /// Draw a line with search match highlights.
985    #[allow(clippy::too_many_arguments)]
986    fn draw_highlighted_line(
987        &self,
988        content: &str,
989        ranges: &[(usize, usize)],
990        x: u16,
991        y: u16,
992        max_x: u16,
993        frame: &mut Frame,
994        base_style: Style,
995    ) {
996        let hl_style = self
997            .search_highlight_style
998            .unwrap_or_else(|| Style::new().bold().reverse());
999        let mut cursor_x = x;
1000        let mut pos = 0;
1001
1002        for &(start, end) in ranges {
1003            let start = start.min(content.len());
1004            let end = end.min(content.len());
1005            if start > pos {
1006                // Draw non-highlighted segment
1007                cursor_x =
1008                    draw_text_span(frame, cursor_x, y, &content[pos..start], base_style, max_x);
1009            }
1010            if start < end {
1011                // Draw highlighted segment
1012                cursor_x =
1013                    draw_text_span(frame, cursor_x, y, &content[start..end], hl_style, max_x);
1014            }
1015            pos = end;
1016        }
1017        // Draw trailing non-highlighted text
1018        if pos < content.len() {
1019            draw_text_span(frame, cursor_x, y, &content[pos..], base_style, max_x);
1020        }
1021    }
1022
1023    #[allow(clippy::too_many_arguments)]
1024    fn draw_text_line(
1025        &self,
1026        line: Option<&ftui_text::Line>,
1027        fallback: &str,
1028        x: u16,
1029        y: u16,
1030        max_x: u16,
1031        frame: &mut Frame,
1032        base_style: Style,
1033    ) {
1034        if let Some(line) = line {
1035            let mut cursor_x = x;
1036            for span in line.spans() {
1037                if cursor_x >= max_x {
1038                    break;
1039                }
1040                let span_style = span
1041                    .style
1042                    .map_or(base_style, |style| style.merge(&base_style));
1043                cursor_x = draw_text_span_with_link(
1044                    frame,
1045                    cursor_x,
1046                    y,
1047                    span.as_str(),
1048                    span_style,
1049                    max_x,
1050                    span.link.as_deref(),
1051                );
1052            }
1053        } else {
1054            draw_text_span(frame, x, y, fallback, base_style, max_x);
1055        }
1056    }
1057
1058    fn scroll_to_match(&mut self, idx: usize) {
1059        if let Some(indices) = self.filtered_indices.as_ref() {
1060            let position = indices.partition_point(|&v| v < idx);
1061            self.filtered_scroll_offset = position.min(indices.len().saturating_sub(1));
1062        } else {
1063            self.virt.scroll_to(idx);
1064        }
1065    }
1066
1067    fn is_filtered_at_bottom(&self, total: usize, visible_count: usize) -> bool {
1068        if visible_count == 0 {
1069            return false;
1070        }
1071        if total == 0 {
1072            return true;
1073        }
1074        self.filtered_scroll_offset >= total.saturating_sub(visible_count)
1075    }
1076}
1077
1078impl StatefulWidget for LogViewer {
1079    type State = LogViewerState;
1080
1081    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
1082        if area.width == 0 || area.height == 0 {
1083            return;
1084        }
1085
1086        clear_text_area(frame, area, self.style);
1087
1088        // Keep Virtualized's visible_count in sync even in filtered mode.
1089        let _ = self.virt.visible_range(area.height);
1090
1091        // Update state with current viewport info
1092        state.last_viewport_height = area.height;
1093
1094        let total_lines = self.virt.len();
1095        if total_lines == 0 {
1096            state.last_visible_lines = 0;
1097            return;
1098        }
1099
1100        // Use filtered indices if a filter is active
1101        let render_indices: Option<&[usize]> = self.filtered_indices.as_deref();
1102
1103        // Calculate visible range using Virtualized's scroll state
1104        let visible_count = area.height as usize;
1105
1106        // Determine which lines to show
1107        let (mut start_idx, mut end_idx, anchored_to_bottom) = if let Some(indices) = render_indices
1108        {
1109            // Filtered mode: show lines matching the filter
1110            let filtered_total = indices.len();
1111            if filtered_total == 0 {
1112                state.last_visible_lines = 0;
1113                return;
1114            }
1115            // Clamp scroll to filtered set
1116            let max_offset = filtered_total.saturating_sub(visible_count);
1117            let offset = self.filtered_scroll_offset.min(max_offset);
1118            let start = offset;
1119            let end = (offset + visible_count).min(filtered_total);
1120            let is_bottom = offset >= max_offset;
1121            (start, end, is_bottom)
1122        } else {
1123            // Unfiltered mode: use Virtualized's range directly
1124            let range = self.virt.visible_range(area.height);
1125            (range.start, range.end, self.virt.follow_mode())
1126        };
1127
1128        // The ranges above count one row per entry. With wrapping an entry can
1129        // take several rows, so a range picked that way from the bottom runs
1130        // out of rows before its newest entries - a followed log hid exactly
1131        // the lines being tailed (bd-mbsre). Following, measure from the
1132        // newest entry back until the viewport is full instead, clipping the
1133        // top of the oldest one if it overflows.
1134        let mut skip_first_rows = 0u16;
1135        if anchored_to_bottom && !matches!(self.wrap_mode, LogWrapMode::NoWrap) {
1136            let display_total = render_indices.map_or(total_lines, <[usize]>::len);
1137            let mut rows = 0u32;
1138            let mut start = display_total;
1139            while start > 0 && rows < u32::from(area.height) {
1140                start -= 1;
1141                let line_idx = render_indices.map_or(start, |indices| indices[start]);
1142                if let Some(text) = self.virt.get(line_idx) {
1143                    rows += u32::from(self.wrapped_rows(text, area.width));
1144                }
1145            }
1146            start_idx = start;
1147            end_idx = display_total;
1148            skip_first_rows =
1149                u16::try_from(rows.saturating_sub(u32::from(area.height))).unwrap_or(u16::MAX);
1150        }
1151
1152        let mut y = area.y;
1153        let mut lines_rendered = 0;
1154        let mut last_rendered_index = None;
1155
1156        for display_idx in start_idx..end_idx {
1157            if y >= area.bottom() {
1158                break;
1159            }
1160
1161            // Resolve to actual line index
1162            let line_idx = if let Some(indices) = render_indices {
1163                indices[display_idx]
1164            } else {
1165                display_idx
1166            };
1167
1168            let Some(line) = self.virt.get(line_idx) else {
1169                continue;
1170            };
1171
1172            let is_selected = state.selected_line == Some(line_idx);
1173
1174            let skip_rows = if display_idx == start_idx {
1175                skip_first_rows
1176            } else {
1177                0
1178            };
1179            let lines_used = self.render_line(
1180                line,
1181                line_idx,
1182                area.x,
1183                y,
1184                area.width,
1185                area.bottom(),
1186                frame,
1187                is_selected,
1188                skip_rows,
1189            );
1190
1191            y = y.saturating_add(lines_used);
1192            lines_rendered += 1;
1193            last_rendered_index = Some(display_idx);
1194        }
1195
1196        state.last_visible_lines = lines_rendered;
1197
1198        // Correct visible count in Virtualized based on actual wrapped rendering
1199        self.virt.set_visible_count(lines_rendered);
1200
1201        // Determine if we are truly at the bottom (rendered the last item)
1202        let at_bottom = if let Some(indices) = render_indices {
1203            if let Some(last) = last_rendered_index {
1204                last >= indices.len().saturating_sub(1)
1205            } else {
1206                false
1207            }
1208        } else if let Some(last) = last_rendered_index {
1209            last >= total_lines.saturating_sub(1)
1210        } else {
1211            false
1212        };
1213
1214        // Render scroll indicator if not at bottom
1215        if !at_bottom && area.width >= 4 {
1216            let lines_below = if let Some(indices) = render_indices {
1217                indices.len().saturating_sub(end_idx)
1218            } else {
1219                total_lines.saturating_sub(end_idx)
1220            };
1221            let indicator = format!(" {} ", lines_below);
1222            let indicator_len = display_width(&indicator) as u16;
1223            if indicator_len < area.width {
1224                let indicator_x = area.right().saturating_sub(indicator_len);
1225                let indicator_y = area.bottom().saturating_sub(1);
1226                draw_text_span(
1227                    frame,
1228                    indicator_x,
1229                    indicator_y,
1230                    &indicator,
1231                    Style::new().bold(),
1232                    area.right(),
1233                );
1234            }
1235        }
1236
1237        // Render search indicator if active
1238        if let Some((current, total)) = self.search_info()
1239            && area.width >= 10
1240        {
1241            let search_indicator = format!(" {}/{} ", current, total);
1242            let ind_len = display_width(&search_indicator) as u16;
1243            if ind_len < area.width {
1244                let ind_x = area.x;
1245                let ind_y = area.bottom().saturating_sub(1);
1246                draw_text_span(
1247                    frame,
1248                    ind_x,
1249                    ind_y,
1250                    &search_indicator,
1251                    Style::new().bold(),
1252                    ind_x.saturating_add(ind_len),
1253                );
1254            }
1255        }
1256    }
1257}
1258
1259/// Find match ranges using allocation-free case-insensitive search.
1260fn search_ascii_case_insensitive_ranges(haystack: &str, needle_lower: &str) -> Vec<(usize, usize)> {
1261    let mut results = Vec::new();
1262    if needle_lower.is_empty() {
1263        return results;
1264    }
1265
1266    if !haystack.is_ascii() || !needle_lower.is_ascii() {
1267        return search_ascii_case_insensitive(haystack, needle_lower)
1268            .into_iter()
1269            .map(|r| (r.range.start, r.range.end))
1270            .collect();
1271    }
1272
1273    let haystack_bytes = haystack.as_bytes();
1274    let needle_bytes = needle_lower.as_bytes();
1275    let needle_len = needle_bytes.len();
1276
1277    if needle_len > haystack_bytes.len() {
1278        return results;
1279    }
1280
1281    const MAX_WORK: usize = 4096;
1282    if haystack_bytes.len().saturating_mul(needle_len) > MAX_WORK {
1283        return search_ascii_case_insensitive(haystack, needle_lower)
1284            .into_iter()
1285            .map(|r| (r.range.start, r.range.end))
1286            .collect();
1287    }
1288
1289    let mut i = 0;
1290    while i <= haystack_bytes.len() - needle_len {
1291        let mut match_found = true;
1292        for j in 0..needle_len {
1293            if haystack_bytes[i + j].to_ascii_lowercase() != needle_bytes[j] {
1294                match_found = false;
1295                break;
1296            }
1297        }
1298        if match_found {
1299            results.push((i, i + needle_len));
1300            i += needle_len;
1301        } else {
1302            i += 1;
1303        }
1304    }
1305    results
1306}
1307
1308/// Find match byte ranges within a single line using the given config.
1309fn find_match_ranges(
1310    plain: &str,
1311    query: &str,
1312    query_lower: Option<&str>,
1313    config: &SearchConfig,
1314    #[cfg(feature = "regex-search")] compiled_regex: Option<&regex::Regex>,
1315) -> Vec<(usize, usize)> {
1316    match config.mode {
1317        SearchMode::Literal => {
1318            if config.case_sensitive {
1319                search_exact(plain, query)
1320                    .into_iter()
1321                    .map(|r| (r.range.start, r.range.end))
1322                    .collect()
1323            } else if let Some(lower) = query_lower {
1324                search_ascii_case_insensitive_ranges(plain, lower)
1325            } else {
1326                search_ascii_case_insensitive(plain, query)
1327                    .into_iter()
1328                    .map(|r| (r.range.start, r.range.end))
1329                    .collect()
1330            }
1331        }
1332        SearchMode::Regex => {
1333            #[cfg(feature = "regex-search")]
1334            {
1335                if let Some(re) = compiled_regex {
1336                    re.find_iter(plain).map(|m| (m.start(), m.end())).collect()
1337                } else {
1338                    Vec::new()
1339                }
1340            }
1341            #[cfg(not(feature = "regex-search"))]
1342            {
1343                // Without the feature, regex mode is a no-op.
1344                Vec::new()
1345            }
1346        }
1347    }
1348}
1349
1350/// Compile a regex from the query, respecting case sensitivity.
1351#[cfg(feature = "regex-search")]
1352fn compile_regex(query: &str, config: &SearchConfig) -> Option<regex::Regex> {
1353    let pattern = if config.case_sensitive {
1354        query.to_string()
1355    } else {
1356        format!("(?i){}", query)
1357    };
1358    regex::Regex::new(&pattern).ok()
1359}
1360
1361/// Expand match indices by ±N context lines, dedup and sort.
1362fn expand_context(matches: &[usize], context_lines: usize, total_lines: usize) -> Vec<usize> {
1363    let mut expanded = Vec::new();
1364    for &idx in matches {
1365        let start = idx.saturating_sub(context_lines);
1366        let end = (idx + context_lines + 1).min(total_lines);
1367        for i in start..end {
1368            expanded.push(i);
1369        }
1370    }
1371    expanded.sort_unstable();
1372    expanded.dedup();
1373    expanded
1374}
1375
1376#[cfg(test)]
1377mod tests {
1378    use super::*;
1379    use ftui_render::cell::StyleFlags as RenderStyleFlags;
1380    use ftui_render::grapheme_pool::GraphemePool;
1381    use ftui_style::StyleFlags as TextStyleFlags;
1382
1383    fn line_text(frame: &Frame, y: u16, width: u16) -> String {
1384        let mut out = String::with_capacity(width as usize);
1385        for x in 0..width {
1386            let ch = frame
1387                .buffer
1388                .get(x, y)
1389                .and_then(|cell| cell.content.as_char())
1390                .unwrap_or(' ');
1391            out.push(ch);
1392        }
1393        out
1394    }
1395
1396    // --- Wrapped entries and follow mode (bd-mbsre) ---
1397
1398    fn render_rows(
1399        log: &LogViewer,
1400        state: &mut LogViewerState,
1401        w: u16,
1402        h: u16,
1403        frames: usize,
1404    ) -> Vec<String> {
1405        let mut pool = GraphemePool::new();
1406        let mut frame = Frame::new(w, h, &mut pool);
1407        for _ in 0..frames {
1408            log.render(Rect::new(0, 0, w, h), &mut frame, state);
1409        }
1410        (0..h).map(|y| line_text(&frame, y, w)).collect()
1411    }
1412
1413    #[test]
1414    fn wrapped_follow_mode_shows_the_newest_entry() {
1415        // Each entry is 18 cells, two rows at width 12, so a 4-row viewport
1416        // holds two entries. Following, those must be the newest two.
1417        let mut log = LogViewer::new(100).wrap_mode(LogWrapMode::CharWrap);
1418        for i in 0..5 {
1419            log.push(format!("entry-{i}-xxxxxxxx"));
1420        }
1421        let mut state = LogViewerState::default();
1422        for frames in [1, 3] {
1423            let rows = render_rows(&log, &mut state, 12, 4, frames);
1424            assert!(
1425                rows.iter().any(|r| r.contains("entry-4")),
1426                "{frames} frame(s): {rows:?}"
1427            );
1428            assert!(rows[0].contains("entry-3"), "{frames} frame(s): {rows:?}");
1429        }
1430    }
1431
1432    #[test]
1433    fn wrapped_entry_taller_than_the_viewport_shows_its_last_rows_when_following() {
1434        // 40 cells at width 10 is four rows; a 3-row viewport shows rows 2-4.
1435        let mut log = LogViewer::new(10).wrap_mode(LogWrapMode::CharWrap);
1436        log.push("short");
1437        log.push("aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd");
1438        let mut state = LogViewerState::default();
1439        let rows = render_rows(&log, &mut state, 10, 3, 2);
1440        assert_eq!(rows, ["bbbbbbbbbb", "cccccccccc", "dddddddddd"]);
1441    }
1442
1443    #[test]
1444    fn wrapped_view_scrolled_to_the_top_stays_top_anchored() {
1445        let mut log = LogViewer::new(100).wrap_mode(LogWrapMode::CharWrap);
1446        for i in 0..5 {
1447            log.push(format!("entry-{i}-xxxxxxxx"));
1448        }
1449        log.scroll_to_top();
1450        let mut state = LogViewerState::default();
1451        let rows = render_rows(&log, &mut state, 12, 4, 2);
1452        assert!(rows[0].starts_with("entry-0"), "{rows:?}");
1453    }
1454
1455    #[test]
1456    fn wrapped_filtered_view_at_the_bottom_shows_the_newest_match() {
1457        let mut log = LogViewer::new(100).wrap_mode(LogWrapMode::CharWrap);
1458        for i in 0..6 {
1459            log.push(format!(
1460                "{}-{i}-xxxxxxxxxx",
1461                if i % 2 == 0 { "keep" } else { "drop" }
1462            ));
1463        }
1464        log.set_filter(Some("keep"));
1465        let mut state = LogViewerState::default();
1466        let rows = render_rows(&log, &mut state, 10, 4, 2);
1467        assert!(rows.iter().any(|r| r.contains("keep-4")), "{rows:?}");
1468    }
1469
1470    #[test]
1471    fn wrapped_short_log_is_drawn_from_the_top() {
1472        // Room to spare: entries start at row 0, nothing is clipped.
1473        let mut log = LogViewer::new(10).wrap_mode(LogWrapMode::CharWrap);
1474        log.push("one");
1475        log.push("two");
1476        let mut state = LogViewerState::default();
1477        let rows = render_rows(&log, &mut state, 10, 5, 1);
1478        assert!(
1479            rows[0].starts_with("one") && rows[1].starts_with("two"),
1480            "{rows:?}"
1481        );
1482    }
1483
1484    #[test]
1485    fn test_push_appends_to_end() {
1486        let mut log = LogViewer::new(100);
1487        log.push("line 1");
1488        log.push("line 2");
1489        assert_eq!(log.line_count(), 2);
1490    }
1491
1492    #[test]
1493    fn test_circular_buffer_eviction() {
1494        let mut log = LogViewer::new(3);
1495        log.push("line 1");
1496        log.push("line 2");
1497        log.push("line 3");
1498        log.push("line 4"); // Should evict "line 1"
1499        assert_eq!(log.line_count(), 3);
1500    }
1501
1502    #[test]
1503    fn test_auto_scroll_stays_at_bottom() {
1504        let mut log = LogViewer::new(100);
1505        log.push("line 1");
1506        assert!(log.is_at_bottom());
1507        log.push("line 2");
1508        assert!(log.is_at_bottom());
1509    }
1510
1511    #[test]
1512    fn test_manual_scroll_disables_auto_scroll() {
1513        let mut log = LogViewer::new(100);
1514        log.virt.set_visible_count(10);
1515        for i in 0..50 {
1516            log.push(format!("line {}", i));
1517        }
1518        log.scroll_up(10);
1519        assert!(!log.auto_scroll_enabled());
1520        log.push("new line");
1521        assert!(!log.auto_scroll_enabled()); // Still scrolled up
1522    }
1523
1524    #[test]
1525    fn test_scroll_to_bottom_reengages_auto_scroll() {
1526        let mut log = LogViewer::new(100);
1527        log.virt.set_visible_count(10);
1528        for i in 0..50 {
1529            log.push(format!("line {}", i));
1530        }
1531        log.scroll_up(10);
1532        log.scroll_to_bottom();
1533        assert!(log.is_at_bottom());
1534        assert!(log.auto_scroll_enabled());
1535    }
1536
1537    #[test]
1538    fn test_scroll_down_reengages_at_bottom() {
1539        let mut log = LogViewer::new(100);
1540        log.virt.set_visible_count(10);
1541        for i in 0..50 {
1542            log.push(format!("line {}", i));
1543        }
1544        log.scroll_up(5);
1545        assert!(!log.auto_scroll_enabled());
1546
1547        log.scroll_down(5);
1548        if log.is_at_bottom() {
1549            assert!(log.auto_scroll_enabled());
1550        }
1551    }
1552
1553    #[test]
1554    fn test_scroll_to_top() {
1555        let mut log = LogViewer::new(100);
1556        for i in 0..50 {
1557            log.push(format!("line {}", i));
1558        }
1559        log.scroll_to_top();
1560        assert!(!log.auto_scroll_enabled());
1561    }
1562
1563    #[test]
1564    fn test_page_up_down() {
1565        let mut log = LogViewer::new(100);
1566        log.virt.set_visible_count(10);
1567        for i in 0..50 {
1568            log.push(format!("line {}", i));
1569        }
1570
1571        let state = LogViewerState {
1572            last_viewport_height: 10,
1573            ..Default::default()
1574        };
1575
1576        assert!(log.is_at_bottom());
1577
1578        log.page_up(&state);
1579        assert!(!log.is_at_bottom());
1580
1581        log.page_down(&state);
1582        // After paging down from near-bottom, should be closer to bottom
1583    }
1584
1585    #[test]
1586    fn test_clear() {
1587        let mut log = LogViewer::new(100);
1588        log.push("line 1");
1589        log.push("line 2");
1590        log.clear();
1591        assert_eq!(log.line_count(), 0);
1592    }
1593
1594    #[test]
1595    fn test_push_many() {
1596        let mut log = LogViewer::new(100);
1597        log.push_many(["line 1", "line 2", "line 3"]);
1598        assert_eq!(log.line_count(), 3);
1599    }
1600
1601    #[test]
1602    fn test_render_empty() {
1603        let mut pool = GraphemePool::new();
1604        let mut frame = Frame::new(80, 24, &mut pool);
1605        let log = LogViewer::new(100);
1606        let mut state = LogViewerState::default();
1607
1608        log.render(Rect::new(0, 0, 80, 24), &mut frame, &mut state);
1609
1610        assert_eq!(state.last_visible_lines, 0);
1611    }
1612
1613    #[test]
1614    fn test_render_empty_clears_stale_content() {
1615        let mut pool = GraphemePool::new();
1616        let mut frame = Frame::new(20, 3, &mut pool);
1617        let mut log = LogViewer::new(100);
1618        let mut state = LogViewerState::default();
1619        let area = Rect::new(0, 0, 20, 3);
1620
1621        log.push("first line");
1622        log.push("second line");
1623        log.render(area, &mut frame, &mut state);
1624
1625        log.clear();
1626        log.render(area, &mut frame, &mut state);
1627
1628        assert_eq!(state.last_visible_lines, 0);
1629        assert_eq!(line_text(&frame, 0, 20), " ".repeat(20));
1630        assert_eq!(line_text(&frame, 1, 20), " ".repeat(20));
1631        assert_eq!(line_text(&frame, 2, 20), " ".repeat(20));
1632    }
1633
1634    #[test]
1635    fn test_render_some_lines() {
1636        let mut pool = GraphemePool::new();
1637        let mut frame = Frame::new(80, 10, &mut pool);
1638        let mut log = LogViewer::new(100);
1639
1640        for i in 0..5 {
1641            log.push(format!("Line {}", i));
1642        }
1643
1644        let mut state = LogViewerState::default();
1645        log.render(Rect::new(0, 0, 80, 10), &mut frame, &mut state);
1646
1647        assert_eq!(state.last_viewport_height, 10);
1648        assert_eq!(state.last_visible_lines, 5);
1649    }
1650
1651    #[test]
1652    fn test_toggle_follow() {
1653        let mut log = LogViewer::new(100);
1654        assert!(log.auto_scroll_enabled());
1655        log.toggle_follow();
1656        assert!(!log.auto_scroll_enabled());
1657        log.toggle_follow();
1658        assert!(log.auto_scroll_enabled());
1659    }
1660
1661    #[test]
1662    fn test_filter_shows_matching_lines() {
1663        let mut log = LogViewer::new(100);
1664        log.push("INFO: starting");
1665        log.push("ERROR: something failed");
1666        log.push("INFO: processing");
1667        log.push("ERROR: another failure");
1668        log.push("INFO: done");
1669
1670        log.set_filter(Some("ERROR"));
1671        assert_eq!(log.filtered_indices.as_ref().unwrap().len(), 2);
1672
1673        // Clear filter
1674        log.set_filter(None);
1675        assert!(log.filtered_indices.is_none());
1676    }
1677
1678    #[test]
1679    fn test_render_filter_no_matches_clears_stale_content() {
1680        let mut pool = GraphemePool::new();
1681        let mut frame = Frame::new(20, 3, &mut pool);
1682        let mut log = LogViewer::new(100);
1683        let mut state = LogViewerState::default();
1684        let area = Rect::new(0, 0, 20, 3);
1685
1686        log.push("INFO: starting");
1687        log.push("ERROR: something failed");
1688        log.render(area, &mut frame, &mut state);
1689
1690        log.set_filter(Some("MISSING"));
1691        log.render(area, &mut frame, &mut state);
1692
1693        assert_eq!(state.last_visible_lines, 0);
1694        assert_eq!(line_text(&frame, 0, 20), " ".repeat(20));
1695        assert_eq!(line_text(&frame, 1, 20), " ".repeat(20));
1696        assert_eq!(line_text(&frame, 2, 20), " ".repeat(20));
1697    }
1698
1699    #[test]
1700    fn test_search_finds_matches() {
1701        let mut log = LogViewer::new(100);
1702        log.push("hello world");
1703        log.push("goodbye world");
1704        log.push("hello again");
1705
1706        let count = log.search("hello");
1707        assert_eq!(count, 2);
1708        assert_eq!(log.search_info(), Some((1, 2)));
1709    }
1710
1711    #[test]
1712    fn test_search_respects_filter() {
1713        let mut log = LogViewer::new(100);
1714        log.push("INFO: ok");
1715        log.push("ERROR: first");
1716        log.push("WARN: mid");
1717        log.push("ERROR: second");
1718
1719        log.set_filter(Some("ERROR"));
1720        assert_eq!(log.search("WARN"), 0);
1721        assert_eq!(log.search("ERROR"), 2);
1722    }
1723
1724    #[test]
1725    fn test_filter_clears_search() {
1726        let mut log = LogViewer::new(100);
1727        log.push("alpha");
1728        log.search("alpha");
1729        assert!(log.search_info().is_some());
1730
1731        log.set_filter(Some("alpha"));
1732        assert!(log.search_info().is_none());
1733    }
1734
1735    #[test]
1736    fn test_search_sets_filtered_scroll_offset() {
1737        let mut log = LogViewer::new(100);
1738        log.push("match one");
1739        log.push("line two");
1740        log.push("match three");
1741        log.push("match four");
1742
1743        log.set_filter(Some("match"));
1744        log.search("match");
1745
1746        assert_eq!(log.filtered_scroll_offset, 0);
1747        log.next_match();
1748        assert_eq!(log.filtered_scroll_offset, 1);
1749    }
1750
1751    #[test]
1752    fn test_search_next_prev() {
1753        let mut log = LogViewer::new(100);
1754        log.push("match A");
1755        log.push("nothing here");
1756        log.push("match B");
1757        log.push("match C");
1758
1759        log.search("match");
1760        assert_eq!(log.search_info(), Some((1, 3)));
1761
1762        log.next_match();
1763        assert_eq!(log.search_info(), Some((2, 3)));
1764
1765        log.next_match();
1766        assert_eq!(log.search_info(), Some((3, 3)));
1767
1768        log.next_match(); // wraps around
1769        assert_eq!(log.search_info(), Some((1, 3)));
1770
1771        log.prev_match(); // wraps back
1772        assert_eq!(log.search_info(), Some((3, 3)));
1773    }
1774
1775    #[test]
1776    fn test_clear_search() {
1777        let mut log = LogViewer::new(100);
1778        log.push("hello");
1779        log.search("hello");
1780        assert!(log.search_info().is_some());
1781
1782        log.clear_search();
1783        assert!(log.search_info().is_none());
1784    }
1785
1786    #[test]
1787    fn test_filter_with_push() {
1788        let mut log = LogViewer::new(100);
1789        log.set_filter(Some("ERROR"));
1790        log.push("INFO: ok");
1791        log.push("ERROR: bad");
1792        log.push("INFO: fine");
1793
1794        assert_eq!(log.filtered_indices.as_ref().unwrap().len(), 1);
1795        assert_eq!(log.filtered_indices.as_ref().unwrap()[0], 1);
1796    }
1797
1798    #[test]
1799    fn test_eviction_adjusts_filter_indices() {
1800        let mut log = LogViewer::new(3);
1801        log.set_filter(Some("x"));
1802        log.push("x1");
1803        log.push("y2");
1804        log.push("x3");
1805        // At capacity: indices [0, 2]
1806        assert_eq!(log.filtered_indices.as_ref().unwrap(), &[0, 2]);
1807
1808        log.push("y4"); // evicts "x1", indices should adjust
1809        // After eviction of 1 item: "x3" was at 2, now at 1
1810        assert_eq!(log.filtered_indices.as_ref().unwrap(), &[1]);
1811    }
1812
1813    #[test]
1814    fn test_filter_scroll_offset_tracks_unfiltered_position() {
1815        let mut log = LogViewer::new(100);
1816        for i in 0..20 {
1817            if i == 2 || i == 10 || i == 15 {
1818                log.push(format!("match {}", i));
1819            } else {
1820                log.push(format!("line {}", i));
1821            }
1822        }
1823
1824        log.virt.scroll_to(12);
1825        log.set_filter(Some("match"));
1826
1827        // Matches before index 12 are at 2 and 10 -> offset should be 2.
1828        assert_eq!(log.filtered_scroll_offset, 2);
1829    }
1830
1831    #[test]
1832    fn test_filtered_scroll_down_moves_within_filtered_list() {
1833        let mut log = LogViewer::new(100);
1834        log.push("match one");
1835        log.push("line two");
1836        log.push("match three");
1837        log.push("line four");
1838        log.push("match five");
1839
1840        log.set_filter(Some("match"));
1841        log.scroll_to_top();
1842        log.scroll_down(1);
1843
1844        assert_eq!(log.filtered_scroll_offset, 1);
1845    }
1846
1847    // -----------------------------------------------------------------------
1848    // Incremental filter/search tests (bd-1b5h.11)
1849    // -----------------------------------------------------------------------
1850
1851    #[test]
1852    fn test_incremental_filter_on_push_tracks_stats() {
1853        let mut log = LogViewer::new(100);
1854        log.set_filter(Some("ERROR"));
1855        // set_filter triggers one full rescan (on empty log).
1856        assert_eq!(log.filter_stats().full_rescans, 1);
1857
1858        log.push("INFO: ok");
1859        log.push("ERROR: bad");
1860        log.push("INFO: fine");
1861        log.push("ERROR: worse");
1862
1863        // 4 lines pushed with filter active → 4 incremental checks.
1864        assert_eq!(log.filter_stats().incremental_checks, 4);
1865        // 2 matched.
1866        assert_eq!(log.filter_stats().incremental_matches, 2);
1867        // No additional full rescans.
1868        assert_eq!(log.filter_stats().full_rescans, 1);
1869    }
1870
1871    #[test]
1872    fn test_incremental_search_on_push() {
1873        let mut log = LogViewer::new(100);
1874        log.push("hello world");
1875        log.push("goodbye world");
1876
1877        // Full search scan.
1878        let count = log.search("hello");
1879        assert_eq!(count, 1);
1880        assert_eq!(log.filter_stats().full_rescans, 1);
1881
1882        // Push new lines while search is active → incremental search update.
1883        log.push("hello again");
1884        log.push("nothing here");
1885
1886        // Search matches should include the new "hello again" line.
1887        assert_eq!(log.search_info(), Some((1, 2)));
1888        assert_eq!(log.filter_stats().incremental_search_matches, 1);
1889    }
1890
1891    #[test]
1892    fn test_incremental_search_respects_active_filter() {
1893        let mut log = LogViewer::new(100);
1894        log.push("ERROR: hello");
1895        log.push("INFO: hello");
1896
1897        log.set_filter(Some("ERROR"));
1898        let count = log.search("hello");
1899        assert_eq!(count, 1); // Only ERROR line passes filter.
1900
1901        // Push new lines: only those passing filter should be search-matched.
1902        log.push("ERROR: hello again");
1903        log.push("INFO: hello again"); // Doesn't pass filter.
1904
1905        assert_eq!(log.search_info(), Some((1, 2))); // Original + new ERROR.
1906        assert_eq!(log.filter_stats().incremental_search_matches, 1);
1907    }
1908
1909    #[test]
1910    fn test_incremental_search_without_filter() {
1911        let mut log = LogViewer::new(100);
1912        log.push("first");
1913        log.search("match");
1914        assert_eq!(log.search_info(), None); // No matches.
1915
1916        // Push matching line without any filter active.
1917        log.push("match found");
1918        assert_eq!(log.search_info(), Some((1, 1)));
1919        assert_eq!(log.filter_stats().incremental_search_matches, 1);
1920    }
1921
1922    #[test]
1923    fn test_filter_stats_reset_on_clear() {
1924        let mut log = LogViewer::new(100);
1925        log.set_filter(Some("x"));
1926        log.push("x1");
1927        log.push("y2");
1928
1929        assert!(log.filter_stats().incremental_checks > 0);
1930        log.clear();
1931        assert_eq!(log.filter_stats().incremental_checks, 0);
1932        assert_eq!(log.filter_stats().full_rescans, 0);
1933    }
1934
1935    #[test]
1936    fn test_filter_stats_full_rescan_on_filter_change() {
1937        let mut log = LogViewer::new(100);
1938        for i in 0..100 {
1939            log.push(format!("line {}", i));
1940        }
1941
1942        log.set_filter(Some("line 5"));
1943        assert_eq!(log.filter_stats().full_rescans, 1);
1944        assert_eq!(log.filter_stats().full_rescan_lines, 100);
1945
1946        log.set_filter(Some("line 9"));
1947        assert_eq!(log.filter_stats().full_rescans, 2);
1948        assert_eq!(log.filter_stats().full_rescan_lines, 200);
1949    }
1950
1951    #[test]
1952    fn test_filter_stats_manual_reset() {
1953        let mut log = LogViewer::new(100);
1954        log.set_filter(Some("x"));
1955        log.push("x1");
1956        assert!(log.filter_stats().incremental_checks > 0);
1957
1958        log.filter_stats_mut().reset();
1959        assert_eq!(log.filter_stats().incremental_checks, 0);
1960
1961        // Subsequent pushes still tracked after reset.
1962        log.push("x2");
1963        assert_eq!(log.filter_stats().incremental_checks, 1);
1964    }
1965
1966    #[test]
1967    fn test_incremental_eviction_adjusts_search_matches() {
1968        let mut log = LogViewer::new(3);
1969        log.push("match A");
1970        log.push("no");
1971        log.push("match B");
1972        log.search("match");
1973        assert_eq!(log.search_info(), Some((1, 2)));
1974
1975        // Push beyond capacity: evicts "match A".
1976        log.push("match C"); // Incremental search match.
1977
1978        // "match A" evicted. "match B" index adjusted. "match C" added.
1979        let search = log.search.as_ref().unwrap();
1980        assert_eq!(search.matches.len(), 2);
1981        // All search match indices should be valid (< log.line_count()).
1982        for &idx in &search.matches {
1983            assert!(idx < log.line_count(), "Search index {} out of range", idx);
1984        }
1985    }
1986
1987    #[test]
1988    fn test_no_stats_when_no_filter_or_search() {
1989        let mut log = LogViewer::new(100);
1990        log.push("line 1");
1991        log.push("line 2");
1992
1993        assert_eq!(log.filter_stats().incremental_checks, 0);
1994        assert_eq!(log.filter_stats().full_rescans, 0);
1995        assert_eq!(log.filter_stats().incremental_search_matches, 0);
1996    }
1997
1998    #[test]
1999    fn test_search_full_rescan_counts_lines() {
2000        let mut log = LogViewer::new(100);
2001        for i in 0..50 {
2002            log.push(format!("line {}", i));
2003        }
2004
2005        log.search("line 1");
2006        assert_eq!(log.filter_stats().full_rescans, 1);
2007        assert_eq!(log.filter_stats().full_rescan_lines, 50);
2008    }
2009
2010    #[test]
2011    fn test_search_full_rescan_on_filtered_counts_filtered_lines() {
2012        let mut log = LogViewer::new(100);
2013        for i in 0..50 {
2014            if i % 2 == 0 {
2015                log.push(format!("even {}", i));
2016            } else {
2017                log.push(format!("odd {}", i));
2018            }
2019        }
2020
2021        log.set_filter(Some("even"));
2022        let initial_rescans = log.filter_stats().full_rescans;
2023        let initial_lines = log.filter_stats().full_rescan_lines;
2024
2025        log.search("even 4");
2026        assert_eq!(log.filter_stats().full_rescans, initial_rescans + 1);
2027        // Search scanned only filtered lines (25 even lines).
2028        assert_eq!(log.filter_stats().full_rescan_lines, initial_lines + 25);
2029    }
2030
2031    // -----------------------------------------------------------------------
2032    // Enhanced search tests (bd-1b5h.2)
2033    // -----------------------------------------------------------------------
2034
2035    #[test]
2036    fn test_search_literal_case_sensitive() {
2037        let mut log = LogViewer::new(100);
2038        log.push("Hello World");
2039        log.push("hello world");
2040        log.push("HELLO WORLD");
2041
2042        let config = SearchConfig {
2043            mode: SearchMode::Literal,
2044            case_sensitive: true,
2045            context_lines: 0,
2046        };
2047        let count = log.search_with_config("Hello", config);
2048        assert_eq!(count, 1);
2049        assert_eq!(log.search_info(), Some((1, 1)));
2050    }
2051
2052    #[test]
2053    fn test_search_literal_case_insensitive() {
2054        let mut log = LogViewer::new(100);
2055        log.push("Hello World");
2056        log.push("hello world");
2057        log.push("HELLO WORLD");
2058        log.push("no match here");
2059
2060        let config = SearchConfig {
2061            mode: SearchMode::Literal,
2062            case_sensitive: false,
2063            context_lines: 0,
2064        };
2065        let count = log.search_with_config("hello", config);
2066        assert_eq!(count, 3);
2067    }
2068
2069    #[test]
2070    fn test_search_ascii_case_insensitive_fast_path_ranges() {
2071        let mut log = LogViewer::new(100);
2072        log.push("Alpha beta ALPHA beta alpha");
2073
2074        let config = SearchConfig {
2075            mode: SearchMode::Literal,
2076            case_sensitive: false,
2077            context_lines: 0,
2078        };
2079        let count = log.search_with_config("alpha", config);
2080        assert_eq!(count, 1);
2081
2082        let ranges = log.highlight_ranges_for_line(0).expect("match ranges");
2083        assert_eq!(ranges, &[(0, 5), (11, 16), (22, 27)]);
2084    }
2085
2086    #[test]
2087    fn test_search_unicode_fallback_ranges() {
2088        let mut log = LogViewer::new(100);
2089        let line = "café résumé café";
2090        log.push(line);
2091
2092        let config = SearchConfig {
2093            mode: SearchMode::Literal,
2094            case_sensitive: false,
2095            context_lines: 0,
2096        };
2097        let count = log.search_with_config("café", config);
2098        assert_eq!(count, 1);
2099
2100        let expected: Vec<(usize, usize)> = search_exact(line, "café")
2101            .into_iter()
2102            .map(|r| (r.range.start, r.range.end))
2103            .collect();
2104        let ranges = log.highlight_ranges_for_line(0).expect("match ranges");
2105        assert_eq!(ranges, expected.as_slice());
2106    }
2107
2108    #[test]
2109    fn test_search_highlight_ranges_stable_after_push() {
2110        let mut log = LogViewer::new(100);
2111        log.push("Alpha beta ALPHA beta alpha");
2112
2113        let config = SearchConfig {
2114            mode: SearchMode::Literal,
2115            case_sensitive: false,
2116            context_lines: 0,
2117        };
2118        log.search_with_config("alpha", config);
2119        let before = log
2120            .highlight_ranges_for_line(0)
2121            .expect("match ranges")
2122            .to_vec();
2123
2124        log.push("no match here");
2125        let after = log
2126            .highlight_ranges_for_line(0)
2127            .expect("match ranges")
2128            .to_vec();
2129
2130        assert_eq!(before, after);
2131    }
2132
2133    #[cfg(feature = "regex-search")]
2134    #[test]
2135    fn test_search_regex_basic() {
2136        let mut log = LogViewer::new(100);
2137        log.push("error: code 42");
2138        log.push("error: code 99");
2139        log.push("info: all good");
2140        log.push("error: code 7");
2141
2142        let config = SearchConfig {
2143            mode: SearchMode::Regex,
2144            case_sensitive: true,
2145            context_lines: 0,
2146        };
2147        let count = log.search_with_config(r"error: code \d+", config);
2148        assert_eq!(count, 3);
2149    }
2150
2151    #[cfg(feature = "regex-search")]
2152    #[test]
2153    fn test_search_regex_invalid_pattern() {
2154        let mut log = LogViewer::new(100);
2155        log.push("something");
2156
2157        let config = SearchConfig {
2158            mode: SearchMode::Regex,
2159            case_sensitive: true,
2160            context_lines: 0,
2161        };
2162        // Invalid regex (unmatched paren)
2163        let count = log.search_with_config(r"(unclosed", config);
2164        assert_eq!(count, 0);
2165        assert!(log.search_info().is_none());
2166    }
2167
2168    #[test]
2169    fn test_search_highlight_ranges() {
2170        let mut log = LogViewer::new(100);
2171        log.push("foo bar foo baz foo");
2172
2173        let count = log.search("foo");
2174        assert_eq!(count, 1);
2175
2176        let ranges = log.highlight_ranges_for_line(0);
2177        assert!(ranges.is_some());
2178        let ranges = ranges.unwrap();
2179        assert_eq!(ranges.len(), 3);
2180        assert_eq!(ranges[0], (0, 3));
2181        assert_eq!(ranges[1], (8, 11));
2182        assert_eq!(ranges[2], (16, 19));
2183    }
2184
2185    #[test]
2186    fn test_search_context_lines() {
2187        let mut log = LogViewer::new(100);
2188        for i in 0..10 {
2189            log.push(format!("line {}", i));
2190        }
2191
2192        let config = SearchConfig {
2193            mode: SearchMode::Literal,
2194            case_sensitive: true,
2195            context_lines: 1,
2196        };
2197        // "line 5" is at index 5
2198        let count = log.search_with_config("line 5", config);
2199        assert_eq!(count, 1);
2200
2201        let ctx = log.context_line_indices();
2202        assert!(ctx.is_some());
2203        let ctx = ctx.unwrap();
2204        // Should include lines 4, 5, 6
2205        assert!(ctx.contains(&4));
2206        assert!(ctx.contains(&5));
2207        assert!(ctx.contains(&6));
2208        assert!(!ctx.contains(&3));
2209        assert!(!ctx.contains(&7));
2210    }
2211
2212    #[test]
2213    fn test_search_incremental_with_config() {
2214        let mut log = LogViewer::new(100);
2215        log.push("Hello World");
2216
2217        let config = SearchConfig {
2218            mode: SearchMode::Literal,
2219            case_sensitive: false,
2220            context_lines: 0,
2221        };
2222        let count = log.search_with_config("hello", config);
2223        assert_eq!(count, 1);
2224
2225        // Push new line that matches case-insensitively
2226        log.push("HELLO again");
2227        assert_eq!(log.search_info(), Some((1, 2)));
2228
2229        // Push line that doesn't match
2230        log.push("goodbye");
2231        assert_eq!(log.search_info(), Some((1, 2)));
2232    }
2233
2234    #[test]
2235    fn test_search_mode_switch() {
2236        let mut log = LogViewer::new(100);
2237        log.push("error 42");
2238        log.push("error 99");
2239        log.push("info ok");
2240
2241        // First search: literal
2242        let count = log.search("error");
2243        assert_eq!(count, 2);
2244
2245        // Switch to case-insensitive
2246        let config = SearchConfig {
2247            mode: SearchMode::Literal,
2248            case_sensitive: false,
2249            context_lines: 0,
2250        };
2251        let count = log.search_with_config("ERROR", config);
2252        assert_eq!(count, 2);
2253
2254        // Switch back to case-sensitive — "ERROR" shouldn't match "error"
2255        let config = SearchConfig {
2256            mode: SearchMode::Literal,
2257            case_sensitive: true,
2258            context_lines: 0,
2259        };
2260        let count = log.search_with_config("ERROR", config);
2261        assert_eq!(count, 0);
2262    }
2263
2264    #[test]
2265    fn test_search_empty_query() {
2266        let mut log = LogViewer::new(100);
2267        log.push("something");
2268
2269        let count = log.search("");
2270        assert_eq!(count, 0);
2271        assert!(log.search_info().is_none());
2272
2273        let config = SearchConfig::default();
2274        let count = log.search_with_config("", config);
2275        assert_eq!(count, 0);
2276        assert!(log.search_info().is_none());
2277    }
2278
2279    #[test]
2280    fn test_highlight_ranges_within_bounds() {
2281        let mut log = LogViewer::new(100);
2282        let lines = [
2283            "short",
2284            "hello world hello",
2285            "café résumé café",
2286            "🌍 emoji 🌍",
2287            "",
2288        ];
2289        for line in &lines {
2290            log.push(*line);
2291        }
2292
2293        log.search("hello");
2294
2295        // Check all highlight ranges are valid byte ranges
2296        for match_idx in 0..log.line_count() {
2297            if let Some(ranges) = log.highlight_ranges_for_line(match_idx)
2298                && let Some(item) = log.virt.get(match_idx)
2299            {
2300                let plain = item.to_plain_text();
2301                for &(start, end) in ranges {
2302                    assert!(
2303                        start <= end,
2304                        "Invalid range: start={} > end={} on line {}",
2305                        start,
2306                        end,
2307                        match_idx
2308                    );
2309                    assert!(
2310                        end <= plain.len(),
2311                        "Out of bounds: end={} > len={} on line {}",
2312                        end,
2313                        plain.len(),
2314                        match_idx
2315                    );
2316                }
2317            }
2318        }
2319    }
2320
2321    #[test]
2322    fn test_search_match_rate_hint() {
2323        let mut log = LogViewer::new(100);
2324        log.set_filter(Some("x"));
2325        log.push("x match");
2326        log.search("match");
2327        log.push("x match again");
2328        log.push("x no");
2329
2330        // 3 incremental checks, 1 search match
2331        let rate = log.search_match_rate_hint();
2332        assert!(rate > 0.0);
2333        assert!(rate <= 1.0);
2334    }
2335
2336    #[test]
2337    fn test_large_scrollback_eviction_and_scroll_bounds() {
2338        let mut log = LogViewer::new(1_000);
2339        log.virt.set_visible_count(25);
2340
2341        for i in 0..5_000 {
2342            log.push(format!("line {}", i));
2343        }
2344
2345        assert_eq!(log.line_count(), 1_000);
2346
2347        let first = log.virt.get(0).expect("first line");
2348        assert_eq!(first.lines()[0].to_plain_text(), "line 4000");
2349
2350        let last = log
2351            .virt
2352            .get(log.line_count().saturating_sub(1))
2353            .expect("last line");
2354        assert_eq!(last.lines()[0].to_plain_text(), "line 4999");
2355
2356        log.scroll_to_top();
2357        assert!(!log.auto_scroll_enabled());
2358
2359        log.scroll_down(10_000);
2360        assert!(log.is_at_bottom());
2361        assert!(log.auto_scroll_enabled());
2362
2363        let max_offset = log.line_count().saturating_sub(log.virt.visible_count());
2364        assert!(log.virt.scroll_offset() <= max_offset);
2365    }
2366
2367    #[test]
2368    fn test_large_scrollback_render_top_and_bottom_lines() {
2369        let mut log = LogViewer::new(1_000);
2370        log.virt.set_visible_count(3);
2371        for i in 0..5_000 {
2372            log.push(format!("line {}", i));
2373        }
2374
2375        let mut pool = GraphemePool::new();
2376        let mut state = LogViewerState::default();
2377
2378        log.scroll_to_top();
2379        let mut frame = Frame::new(20, 3, &mut pool);
2380        log.render(Rect::new(0, 0, 20, 3), &mut frame, &mut state);
2381        let top_line = line_text(&frame, 0, 20);
2382        assert!(
2383            top_line.trim_end().starts_with("line 4000"),
2384            "expected top line to start with line 4000, got: {top_line:?}"
2385        );
2386
2387        log.scroll_to_bottom();
2388        let mut frame = Frame::new(20, 3, &mut pool);
2389        log.render(Rect::new(0, 0, 20, 3), &mut frame, &mut state);
2390        let bottom_line = line_text(&frame, 2, 20);
2391        assert!(
2392            bottom_line.trim_end().starts_with("line 4999"),
2393            "expected bottom line to start with line 4999, got: {bottom_line:?}"
2394        );
2395    }
2396
2397    #[test]
2398    fn test_filtered_autoscroll_respects_manual_position() {
2399        let mut log = LogViewer::new(200);
2400        log.virt.set_visible_count(2);
2401
2402        log.push("match 1");
2403        log.push("skip");
2404        log.push("match 2");
2405        log.push("match 3");
2406        log.push("skip again");
2407        log.push("match 4");
2408        log.push("match 5");
2409
2410        log.set_filter(Some("match"));
2411        assert!(log.is_at_bottom());
2412
2413        log.scroll_up(2);
2414        let offset_before = log.filtered_scroll_offset;
2415        assert!(!log.is_at_bottom());
2416
2417        log.push("match 6");
2418        assert_eq!(log.filtered_scroll_offset, offset_before);
2419
2420        log.scroll_to_bottom();
2421        let offset_at_bottom = log.filtered_scroll_offset;
2422        log.push("match 7");
2423        assert!(log.filtered_scroll_offset >= offset_at_bottom);
2424        assert!(log.is_at_bottom());
2425    }
2426
2427    #[test]
2428    fn link_retention_builder_preserves_text_styles_and_search_state() {
2429        let mut log = LogViewer::new(10);
2430        for number in 0..4 {
2431            log.push(FtuiText::from_spans([
2432                Span::styled(format!("match {number}"), Style::new().bold())
2433                    .link(format!("https://example.com/{number}")),
2434                Span::styled(" plain", Style::new().italic()),
2435            ]));
2436        }
2437        log.set_filter(Some("match"));
2438        assert_eq!(log.search("match"), 4);
2439        log.scroll_up(1);
2440        let original = log.clone();
2441        let log = log.retain_links_for_last_lines(2);
2442        assert_eq!(log.len(), 4);
2443        assert_eq!(log.filter, original.filter);
2444        assert_eq!(log.filtered_indices, original.filtered_indices);
2445        assert_eq!(log.filtered_scroll_offset, original.filtered_scroll_offset);
2446        assert_eq!(log.virt.scroll_offset(), original.virt.scroll_offset());
2447        assert_eq!(log.auto_scroll_enabled(), original.auto_scroll_enabled());
2448        assert_eq!(
2449            format!("{:?}", log.search),
2450            format!("{:?}", original.search)
2451        );
2452        assert_eq!(
2453            format!("{:?}", log.filter_stats),
2454            format!("{:?}", original.filter_stats)
2455        );
2456        for index in 0..4 {
2457            let before = original.virt.get(index).unwrap();
2458            let after = log.virt.get(index).unwrap();
2459            assert_eq!(after.to_plain_text(), format!("match {index} plain"));
2460            let before = before.lines()[0].spans();
2461            let after = after.lines()[0].spans();
2462            assert_eq!(after.len(), before.len());
2463            for (before, after) in before.iter().zip(after) {
2464                assert_eq!(after.content, before.content);
2465                assert_eq!(after.style, before.style);
2466                assert_eq!(
2467                    after.link,
2468                    if index < 2 { None } else { before.link.clone() }
2469                );
2470            }
2471            assert!(
2472                before[0].link.is_some(),
2473                "default retention keeps every link"
2474            );
2475        }
2476    }
2477
2478    #[test]
2479    fn link_retention_expires_each_multiline_push_and_survives_eviction() {
2480        let linked_line = |number| {
2481            Line::from_spans([
2482                Span::raw(format!("line {number}")).link(format!("https://example.com/{number}"))
2483            ])
2484        };
2485        let mut log = LogViewer::new(3).retain_links_for_last_lines(2);
2486        log.push(FtuiText::from_lines((0..5).map(linked_line)));
2487        assert_eq!(log.len(), 3);
2488        for index in 0..3 {
2489            let item = log.virt.get(index).unwrap();
2490            assert_eq!(item.to_plain_text(), format!("line {}", index + 2));
2491            assert_eq!(item.lines()[0].spans()[0].link.is_some(), index > 0);
2492        }
2493        let mut log = log.retain_links_for_last_lines(usize::MAX);
2494        assert!(
2495            log.virt.get(0).unwrap().lines()[0].spans()[0]
2496                .link
2497                .is_none()
2498        );
2499        log.push(FtuiText::from_line(linked_line(5)));
2500        for index in 0..3 {
2501            assert!(
2502                log.virt.get(index).unwrap().lines()[0].spans()[0]
2503                    .link
2504                    .is_some()
2505            );
2506        }
2507        let mut log = log.retain_links_for_last_lines(0);
2508        log.push(FtuiText::from_lines([linked_line(6), linked_line(7)]));
2509        for index in 0..3 {
2510            let item = log.virt.get(index).unwrap();
2511            assert_eq!(item.to_plain_text(), format!("line {}", index + 5));
2512            assert!(item.lines()[0].spans()[0].link.is_none());
2513        }
2514        log.clear();
2515        log.push(FtuiText::from_line(linked_line(8)));
2516        assert_eq!(log.len(), 1);
2517        assert!(
2518            log.virt.get(0).unwrap().lines()[0].spans()[0]
2519                .link
2520                .is_none()
2521        );
2522        let mut empty = LogViewer::new(0).retain_links_for_last_lines(0);
2523        empty.push(FtuiText::from_line(linked_line(9)));
2524        assert!(empty.is_empty());
2525    }
2526
2527    #[test]
2528    fn link_retention_keeps_all_ten_thousand_text_records_and_last_two_hundred_targets() {
2529        let mut log = LogViewer::new(10_000).retain_links_for_last_lines(200);
2530        for number in 0..10_001 {
2531            log.push(FtuiText::from_spans([
2532                Span::raw(format!("line {number}")).link(format!("https://example.com/{number}"))
2533            ]));
2534            if number >= 9_999 {
2535                assert_eq!(log.len(), 10_000);
2536                let first = number - 9_999;
2537                for index in 0..10_000 {
2538                    let item = log.virt.get(index).unwrap();
2539                    assert_eq!(item.to_plain_text(), format!("line {}", first + index));
2540                    let link = item.lines()[0].spans()[0].link.as_deref();
2541                    if index < 9_800 {
2542                        assert_eq!(link, None);
2543                    } else {
2544                        let expected = format!("https://example.com/{}", first + index);
2545                        assert_eq!(link, Some(expected.as_str()));
2546                    }
2547                }
2548            }
2549        }
2550    }
2551
2552    #[test]
2553    fn first_hyperlink_from_default_registry_reaches_presenter() {
2554        use ftui_core::terminal_capabilities::TerminalCapabilities;
2555        use ftui_render::buffer::Buffer;
2556        use ftui_render::diff::BufferDiff;
2557        use ftui_render::link_registry::LinkRegistry;
2558        use ftui_render::presenter::Presenter;
2559        use ftui_text::Span;
2560
2561        let url = "https://example.com/first";
2562        let mut log = LogViewer::new(2);
2563        log.push(FtuiText::from_spans([
2564            Span::raw("first").link(url),
2565            Span::raw(" plain"),
2566        ]));
2567        log.push(FtuiText::from_spans([Span::raw("again").link(url)]));
2568        let mut pool = GraphemePool::new();
2569        let mut links = LinkRegistry::default();
2570        let mut frame = Frame::with_links(11, 2, &mut pool, &mut links);
2571        log.render(
2572            Rect::new(0, 0, 11, 2),
2573            &mut frame,
2574            &mut LogViewerState::default(),
2575        );
2576        assert_eq!(line_text(&frame, 0, 11), "first plain");
2577        assert_eq!(line_text(&frame, 1, 11), "again      ");
2578        for y in 0..2 {
2579            for x in 0..11 {
2580                assert_eq!(
2581                    frame.buffer.get(x, y).unwrap().attrs.link_id(),
2582                    u32::from(x < 5),
2583                    "link ownership at ({x}, {y})"
2584                );
2585            }
2586        }
2587        let buffer = frame.buffer;
2588        assert_eq!(links.len(), 1);
2589        assert_eq!(links.get(1), Some(url));
2590        let diff = BufferDiff::compute(&Buffer::new(11, 2), &buffer);
2591        for enabled in [true, false] {
2592            let mut caps = TerminalCapabilities::basic();
2593            caps.osc8_hyperlinks = enabled;
2594            let mut presenter = Presenter::new(Vec::new(), caps);
2595            presenter
2596                .present_with_pool(&buffer, &diff, Some(&pool), Some(&links))
2597                .unwrap();
2598            let output = String::from_utf8(presenter.into_inner().unwrap()).unwrap();
2599            if enabled {
2600                assert!(
2601                    output.contains("\x1b]8;;https://example.com/first\x07first\x1b]8;;\x07 plain")
2602                );
2603                assert!(output.contains("\x1b]8;;https://example.com/first\x07again\x1b]8;;\x07"));
2604                assert_eq!(output.matches(url).count(), 2);
2605            } else {
2606                assert!(!output.contains("\x1b]8;"));
2607                assert!(output.contains("first plain"));
2608                assert!(output.contains("again"));
2609            }
2610        }
2611    }
2612
2613    #[test]
2614    fn test_markup_parsing_preserves_spans() {
2615        let mut log = LogViewer::new(100);
2616        let text = ftui_text::markup::parse_markup("[bold]Hello[/bold] [fg=red]world[/fg]!")
2617            .expect("markup parse failed");
2618        log.push(text);
2619
2620        let item = log.virt.get(0).expect("log line");
2621        let line = &item.lines()[0];
2622        assert_eq!(line.to_plain_text(), "Hello world!");
2623
2624        let spans = line.spans();
2625        assert!(spans.iter().any(|span| span.style.is_some()));
2626        assert!(spans.iter().any(|span| {
2627            span.style
2628                .and_then(|style| style.attrs)
2629                .is_some_and(|attrs| attrs.contains(TextStyleFlags::BOLD))
2630        }));
2631    }
2632
2633    #[test]
2634    fn test_markup_renders_bold_cells() {
2635        let mut log = LogViewer::new(10);
2636        let text = ftui_text::markup::parse_markup("[bold]Hello[/bold] world")
2637            .expect("markup parse failed");
2638        log.push(text);
2639
2640        let mut pool = GraphemePool::new();
2641        let mut frame = Frame::new(16, 1, &mut pool);
2642        let mut state = LogViewerState::default();
2643        log.render(Rect::new(0, 0, 16, 1), &mut frame, &mut state);
2644
2645        let rendered = line_text(&frame, 0, 16);
2646        assert!(rendered.trim_end().starts_with("Hello world"));
2647        for x in 0..5 {
2648            let cell = frame.buffer.get(x, 0).expect("cell");
2649            assert!(
2650                cell.attrs.has_flag(RenderStyleFlags::BOLD),
2651                "expected bold at x={x}, attrs={:?}",
2652                cell.attrs.flags()
2653            );
2654        }
2655    }
2656
2657    #[test]
2658    fn test_toggle_follow_disables_autoscroll_on_push() {
2659        let mut log = LogViewer::new(100);
2660        log.virt.set_visible_count(3);
2661        for i in 0..5 {
2662            log.push(format!("line {}", i));
2663        }
2664        assert!(log.is_at_bottom());
2665
2666        log.toggle_follow();
2667        assert!(!log.auto_scroll_enabled());
2668
2669        log.push("new line");
2670        assert!(!log.auto_scroll_enabled());
2671        assert!(!log.is_at_bottom());
2672    }
2673
2674    #[test]
2675    fn test_search_match_rate_hint_ratio() {
2676        let mut log = LogViewer::new(100);
2677        assert_eq!(log.search_match_rate_hint(), 0.0);
2678
2679        log.set_filter(Some("ERR"));
2680        log.search("ERR");
2681
2682        log.push("ERR one");
2683        log.push("INFO skip");
2684        log.push("ERR two");
2685        log.push("WARN skip");
2686
2687        assert_eq!(log.filter_stats().incremental_checks, 4);
2688        assert_eq!(log.filter_stats().incremental_search_checks, 2);
2689        assert_eq!(log.filter_stats().incremental_search_matches, 2);
2690        assert_eq!(log.search_match_rate_hint(), 1.0);
2691    }
2692
2693    #[test]
2694    fn test_render_char_wrap_splits_lines() {
2695        let mut log = LogViewer::new(10).wrap_mode(LogWrapMode::CharWrap);
2696        log.push("abcdefghij");
2697
2698        let mut pool = GraphemePool::new();
2699        let mut frame = Frame::new(5, 3, &mut pool);
2700        let mut state = LogViewerState::default();
2701        log.render(Rect::new(0, 0, 5, 3), &mut frame, &mut state);
2702
2703        assert_eq!(line_text(&frame, 0, 5), "abcde");
2704        assert_eq!(line_text(&frame, 1, 5), "fghij");
2705    }
2706
2707    #[test]
2708    fn test_render_scroll_indicator_when_not_at_bottom() {
2709        let mut log = LogViewer::new(100);
2710        for i in 0..5 {
2711            log.push(format!("line {}", i));
2712        }
2713
2714        log.scroll_to_top();
2715
2716        let mut pool = GraphemePool::new();
2717        let mut frame = Frame::new(10, 2, &mut pool);
2718        let mut state = LogViewerState::default();
2719        log.render(Rect::new(0, 0, 10, 2), &mut frame, &mut state);
2720
2721        let indicator = " 3 ";
2722        let bottom_line = line_text(&frame, 1, 10);
2723        assert_eq!(&bottom_line[7..10], indicator);
2724    }
2725
2726    #[test]
2727    fn test_render_search_indicator_when_active() {
2728        let mut log = LogViewer::new(100);
2729        for i in 0..5 {
2730            log.push(format!("line {}", i));
2731        }
2732        log.search("line");
2733
2734        let mut pool = GraphemePool::new();
2735        let mut frame = Frame::new(12, 2, &mut pool);
2736        let mut state = LogViewerState::default();
2737        log.render(Rect::new(0, 0, 12, 2), &mut frame, &mut state);
2738
2739        let indicator = " 1/5 ";
2740        let bottom_line = line_text(&frame, 1, 12);
2741        assert_eq!(&bottom_line[0..indicator.len()], indicator);
2742    }
2743
2744    #[test]
2745    fn test_search_ascii_case_insensitive_ranges_long_needle() {
2746        let ranges = search_ascii_case_insensitive_ranges("hi", "hello");
2747        assert!(ranges.is_empty());
2748    }
2749
2750    #[test]
2751    fn test_search_ascii_case_insensitive_ranges_large_work_fallback() {
2752        let mut haystack = "a".repeat(500);
2753        haystack.push_str("HELLO");
2754        haystack.push_str(&"b".repeat(500));
2755
2756        let ranges = search_ascii_case_insensitive_ranges(&haystack, "hello");
2757        assert_eq!(ranges, vec![(500, 505)]);
2758    }
2759}