1#![forbid(unsafe_code)]
2
3use 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::{RenderItem, Virtualized, VirtualizedList, VirtualizedListState};
47use crate::{StatefulWidget, clear_text_area, draw_text_span, draw_text_span_with_link};
48use std::cell::Cell;
49
50type Text = FtuiText<'static>;
51
52fn text_into_owned(text: FtuiText<'_>) -> FtuiText<'static> {
53 FtuiText::from_lines(
54 text.into_iter()
55 .map(|line| Line::from_spans(line.into_iter().map(Span::into_owned))),
56 )
57}
58
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub enum LogWrapMode {
62 #[default]
64 NoWrap,
65 CharWrap,
67 WordWrap,
69}
70
71impl From<LogWrapMode> for WrapMode {
72 fn from(mode: LogWrapMode) -> Self {
73 match mode {
74 LogWrapMode::NoWrap => WrapMode::None,
75 LogWrapMode::CharWrap => WrapMode::Char,
76 LogWrapMode::WordWrap => WrapMode::Word,
77 }
78 }
79}
80
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
83pub enum SearchMode {
84 #[default]
86 Literal,
87 Regex,
89}
90
91#[derive(Clone, Debug)]
93pub struct SearchConfig {
94 pub mode: SearchMode,
96 pub case_sensitive: bool,
98 pub context_lines: usize,
100}
101
102impl Default for SearchConfig {
103 fn default() -> Self {
104 Self {
105 mode: SearchMode::Literal,
106 case_sensitive: true,
107 context_lines: 0,
108 }
109 }
110}
111
112#[derive(Debug, Clone)]
114struct SearchState {
115 query: String,
117 query_lower: Option<String>,
119 config: SearchConfig,
121 matches: Vec<usize>,
123 current: usize,
125 highlight_ranges: Vec<Vec<(usize, usize)>>,
127 #[cfg(feature = "regex-search")]
129 compiled_regex: Option<regex::Regex>,
130 context_expanded: Option<Vec<usize>>,
133}
134
135#[derive(Debug, Clone, Default)]
140pub struct FilterStats {
141 pub incremental_checks: u64,
143 pub incremental_matches: u64,
145 pub full_rescans: u64,
147 pub full_rescan_lines: u64,
149 pub incremental_search_matches: u64,
151 pub incremental_search_checks: u64,
153}
154
155impl FilterStats {
156 pub fn reset(&mut self) {
158 *self = Self::default();
159 }
160}
161
162#[derive(Debug, Clone)]
175pub struct LogViewer {
176 virt: Virtualized<Text>,
178 max_lines: usize,
180 link_retention_lines: Option<usize>,
182 wrap_mode: LogWrapMode,
184 last_wrap_width: Cell<u16>,
186 style: Style,
188 highlight_style: Option<Style>,
190 search_highlight_style: Option<Style>,
192 filter: Option<String>,
194 filtered_indices: Option<Vec<usize>>,
196 filtered_scroll_offset: usize,
198 search: Option<SearchState>,
200 filter_stats: FilterStats,
202}
203
204#[derive(Debug, Clone)]
206pub struct LogViewerState {
207 pub last_viewport_height: u16,
209 pub last_visible_lines: usize,
211 pub selected_line: Option<usize>,
213 pub list_state: VirtualizedListState,
215}
216
217impl Default for LogViewerState {
218 fn default() -> Self {
219 Self {
220 last_viewport_height: 0,
221 last_visible_lines: 0,
222 selected_line: None,
223 list_state: VirtualizedListState::variable(1),
224 }
225 }
226}
227
228impl LogViewerState {
229 #[must_use]
231 pub fn offset_of_item(&self, idx: usize) -> u32 {
232 self.list_state.offset_of_item(idx)
233 }
234}
235
236impl LogViewer {
237 #[must_use]
243 pub fn new(max_lines: usize) -> Self {
244 Self {
245 virt: Virtualized::new(max_lines).with_follow(true),
246 max_lines,
247 link_retention_lines: None,
248 wrap_mode: LogWrapMode::NoWrap,
249 last_wrap_width: Cell::new(40),
250 style: Style::default(),
251 highlight_style: None,
252 search_highlight_style: None,
253 filter: None,
254 filtered_indices: None,
255 filtered_scroll_offset: 0,
256 search: None,
257 filter_stats: FilterStats::default(),
258 }
259 }
260
261 #[must_use]
263 pub fn wrap_mode(mut self, mode: LogWrapMode) -> Self {
264 self.set_wrap_mode(mode);
265 self
266 }
267
268 #[must_use]
270 pub const fn current_wrap_mode(&self) -> LogWrapMode {
271 self.wrap_mode
272 }
273
274 pub fn set_wrap_mode(&mut self, mode: LogWrapMode) {
276 self.wrap_mode = mode;
277 if matches!(mode, LogWrapMode::NoWrap) {
278 let virt = std::mem::replace(&mut self.virt, Virtualized::new(0));
279 self.virt = virt.with_fixed_height(1);
280 } else {
281 let virt = std::mem::replace(&mut self.virt, Virtualized::new(0));
282 self.virt = virt.with_variable_heights(1);
283 let w = self.last_wrap_width.get().max(1);
284 self.measure_heights(w);
285 }
286 }
287
288 pub fn measure_heights(&mut self, width: u16) {
290 let w = width.max(1);
291 self.last_wrap_width.set(w);
292 if matches!(self.wrap_mode, LogWrapMode::NoWrap) {
293 return;
294 }
295 if matches!(
296 self.virt.item_height(),
297 crate::virtualized::ItemHeight::Fixed(_)
298 ) {
299 let virt = std::mem::replace(&mut self.virt, Virtualized::new(0));
300 self.virt = virt.with_variable_heights(1);
301 }
302 for idx in 0..self.virt.len() {
303 if let Some(line) = self.virt.get(idx) {
304 let h = self.wrapped_rows(line, w);
305 self.virt.observe_height(idx, h);
306 }
307 }
308 }
309
310 #[must_use]
312 pub fn offset_of_item(&self, idx: usize) -> u32 {
313 self.virt.offset_of_item(idx)
314 }
315
316 #[must_use]
324 pub fn retain_links_for_last_lines(mut self, lines: usize) -> Self {
325 self.link_retention_lines = Some(lines);
326 for index in 0..self.virt.len().saturating_sub(lines) {
327 self.strip_line_links(index);
328 }
329 self
330 }
331
332 fn strip_line_links(&mut self, index: usize) {
333 let Some(text) = self.virt.get_mut(index) else {
334 return;
335 };
336 if !text
337 .lines()
338 .iter()
339 .flat_map(|line| line.spans())
340 .any(|span| span.link.is_some())
341 {
342 return;
343 }
344 *text = Text::from_lines(std::mem::take(text).into_iter().map(|line| {
345 Line::from_spans(line.into_iter().map(|mut span| {
346 span.link = None;
347 span
348 }))
349 }));
350 }
351
352 #[must_use]
354 pub fn style(mut self, style: Style) -> Self {
355 self.style = style;
356 self
357 }
358
359 #[must_use]
361 pub fn highlight_style(mut self, style: Style) -> Self {
362 self.highlight_style = Some(style);
363 self
364 }
365
366 #[must_use]
368 pub fn search_highlight_style(mut self, style: Style) -> Self {
369 self.search_highlight_style = Some(style);
370 self
371 }
372
373 #[inline]
375 #[must_use]
376 pub fn len(&self) -> usize {
377 self.virt.len()
378 }
379
380 #[inline]
382 #[must_use]
383 pub fn is_empty(&self) -> bool {
384 self.virt.is_empty()
385 }
386
387 pub fn push<'a>(&mut self, line: impl Into<FtuiText<'a>>) {
396 let follow_filtered = self.filtered_indices.as_ref().is_some_and(|indices| {
397 self.is_filtered_at_bottom(indices.len(), self.virt.visible_count())
398 });
399 let text: Text = text_into_owned(line.into());
400
401 for line in text.into_iter() {
403 let item = Text::from_line(line);
404 let plain = item.to_plain_text();
405
406 let filter_matched = if let Some(filter) = self.filter.as_ref() {
408 self.filter_stats.incremental_checks += 1;
409 let matched = plain.contains(filter.as_str());
410 if matched {
411 if let Some(indices) = self.filtered_indices.as_mut() {
412 let idx = self.virt.len();
413 indices.push(idx);
414 }
415 self.filter_stats.incremental_matches += 1;
416 }
417 matched
418 } else {
419 false
420 };
421
422 if let Some(ref mut search) = self.search {
426 let should_check = self.filter.is_none() || filter_matched;
427 if should_check {
428 self.filter_stats.incremental_search_checks += 1;
429 let ranges = find_match_ranges(
430 &plain,
431 &search.query,
432 search.query_lower.as_deref(),
433 &search.config,
434 #[cfg(feature = "regex-search")]
435 search.compiled_regex.as_ref(),
436 );
437 if !ranges.is_empty() {
438 let idx = self.virt.len();
439 search.matches.push(idx);
440 search.highlight_ranges.push(ranges);
441 self.filter_stats.incremental_search_matches += 1;
442 }
443 }
444 }
445
446 self.virt.push(item);
447 if !matches!(self.wrap_mode, LogWrapMode::NoWrap) {
448 let idx = self.virt.len().saturating_sub(1);
449 let w = self.last_wrap_width.get().max(1);
450 if let Some(added) = self.virt.get(idx) {
451 let h = self.wrapped_rows(added, w);
452 self.virt.observe_height(idx, h);
453 }
454 }
455
456 if let Some(lines) = self.link_retention_lines
458 && let Some(index) = self
459 .virt
460 .len()
461 .checked_sub(lines)
462 .and_then(|n| n.checked_sub(1))
463 {
464 self.strip_line_links(index);
465 }
466
467 if self.virt.len() > self.max_lines {
469 let removed = self.virt.trim_front(self.max_lines);
470
471 if let Some(ref mut indices) = self.filtered_indices {
473 let mut filtered_removed = 0usize;
474 indices.retain_mut(|idx| {
475 if *idx < removed {
476 filtered_removed += 1;
477 false
478 } else {
479 *idx -= removed;
480 true
481 }
482 });
483 if filtered_removed > 0 {
484 self.filtered_scroll_offset =
485 self.filtered_scroll_offset.saturating_sub(filtered_removed);
486 }
487 if indices.is_empty() {
488 self.filtered_scroll_offset = 0;
489 }
490 }
491
492 if let Some(ref mut search) = self.search {
494 let mut keep = Vec::with_capacity(search.matches.len());
495 let mut new_highlights = Vec::with_capacity(search.highlight_ranges.len());
496 let mut evicted_matches = 0;
497 for (i, idx) in search.matches.iter_mut().enumerate() {
498 if *idx < removed {
499 evicted_matches += 1;
500 } else {
501 *idx -= removed;
502 keep.push(*idx);
503 if i < search.highlight_ranges.len() {
504 new_highlights
505 .push(std::mem::take(&mut search.highlight_ranges[i]));
506 }
507 }
508 }
509 search.matches = keep;
510 search.highlight_ranges = new_highlights;
511 search.current = search.current.saturating_sub(evicted_matches);
512 if !search.matches.is_empty() {
514 search.current = search.current.min(search.matches.len() - 1);
515 } else {
516 search.current = 0;
517 }
518 if search.config.context_lines > 0 {
520 search.context_expanded = Some(expand_context(
521 &search.matches,
522 search.config.context_lines,
523 self.virt.len(),
524 ));
525 }
526 }
527 }
528
529 if follow_filtered
530 && let Some(indices) = self.filtered_indices.as_ref()
531 && !indices.is_empty()
532 {
533 self.filtered_scroll_offset = indices.len().saturating_sub(1);
534 }
535 }
536 }
537
538 pub fn push_many<'a>(&mut self, lines: impl IntoIterator<Item = impl Into<FtuiText<'a>>>) {
540 for line in lines {
541 self.push(line);
542 }
543 }
544
545 pub fn scroll_up(&mut self, lines: usize) {
547 if self.filtered_indices.is_some() {
548 if let Some(filtered_total) = self.filtered_indices.as_ref().map(Vec::len) {
550 let max = filtered_total.saturating_sub(1);
551 if self.filtered_scroll_offset > max {
552 self.filtered_scroll_offset = max;
553 }
554 }
555 self.filtered_scroll_offset = self.filtered_scroll_offset.saturating_sub(lines);
556 self.virt.set_follow(false);
557 } else {
558 let delta = i32::try_from(lines).unwrap_or(i32::MAX);
559 self.virt.scroll(-delta);
560 }
561 }
562
563 pub fn scroll_down(&mut self, lines: usize) {
565 if let Some(filtered_total) = self.filtered_indices.as_ref().map(Vec::len) {
566 if filtered_total == 0 {
567 self.filtered_scroll_offset = 0;
568 } else {
569 let visible_count = self.virt.visible_count();
571 let max_offset = filtered_total.saturating_sub(visible_count.max(1));
572 if self.filtered_scroll_offset > max_offset {
573 self.filtered_scroll_offset = max_offset;
574 }
575 self.filtered_scroll_offset = self.filtered_scroll_offset.saturating_add(lines);
576 if self.filtered_scroll_offset > max_offset {
577 self.filtered_scroll_offset = max_offset;
578 }
579 }
580 let vc = self.virt.visible_count();
582 if self.is_filtered_at_bottom(filtered_total, vc) {
583 self.virt.set_follow(true);
584 }
585 } else {
586 let delta = i32::try_from(lines).unwrap_or(i32::MAX);
587 self.virt.scroll(delta);
588 if self.virt.is_at_bottom() {
589 self.virt.set_follow(true);
590 }
591 }
592 }
593
594 pub fn scroll_to_top(&mut self) {
596 if self.filtered_indices.is_some() {
597 self.filtered_scroll_offset = 0;
598 self.virt.set_follow(false);
599 } else {
600 self.virt.scroll_to_top();
601 }
602 }
603
604 pub fn scroll_to_bottom(&mut self) {
606 if let Some(filtered_total) = self.filtered_indices.as_ref().map(Vec::len) {
607 if filtered_total == 0 {
608 self.filtered_scroll_offset = 0;
609 } else {
610 let visible_count = self.virt.visible_count();
611 if visible_count == 0 {
612 self.filtered_scroll_offset = usize::MAX;
614 } else {
615 self.filtered_scroll_offset = filtered_total.saturating_sub(visible_count);
616 }
617 }
618 self.virt.set_follow(true);
619 } else {
620 self.virt.scroll_to_end();
621 }
622 }
623
624 pub fn page_up(&mut self, _state: &LogViewerState) {
629 if self.filtered_indices.is_some() {
630 let lines = _state.last_viewport_height as usize;
631 if lines > 0 {
632 self.scroll_up(lines);
633 }
634 } else {
635 self.virt.page_up();
636 }
637 }
638
639 pub fn page_down(&mut self, _state: &LogViewerState) {
644 if self.filtered_indices.is_some() {
645 let lines = _state.last_viewport_height as usize;
646 if lines > 0 {
647 self.scroll_down(lines);
648 }
649 } else {
650 self.virt.page_down();
651 if self.virt.is_at_bottom() {
652 self.virt.set_follow(true);
653 }
654 }
655 }
656
657 #[must_use]
662 pub fn is_at_bottom(&self) -> bool {
663 if let Some(indices) = self.filtered_indices.as_ref() {
664 self.is_filtered_at_bottom(indices.len(), self.virt.visible_count())
665 } else {
666 self.virt.follow_mode() || self.virt.is_at_bottom()
667 }
668 }
669
670 #[must_use]
672 pub fn line_count(&self) -> usize {
673 self.virt.len()
674 }
675
676 #[must_use]
678 pub fn scroll_offset(&self) -> usize {
679 if let Some(indices) = self.filtered_indices.as_ref() {
680 self.filtered_scroll_offset
681 .min(indices.len().saturating_sub(1))
682 } else {
683 self.virt.scroll_offset()
684 }
685 }
686
687 #[must_use]
689 pub fn auto_scroll_enabled(&self) -> bool {
690 self.virt.follow_mode()
691 }
692
693 pub fn set_auto_scroll(&mut self, enabled: bool) {
695 self.virt.set_follow(enabled);
696 }
697
698 pub fn toggle_follow(&mut self) {
700 let current = self.virt.follow_mode();
701 self.virt.set_follow(!current);
702 }
703
704 pub fn clear(&mut self) {
706 self.virt.clear();
707 self.filtered_indices = self.filter.as_ref().map(|_| Vec::new());
708 self.filtered_scroll_offset = 0;
709 self.search = None;
710 self.filter_stats.reset();
711 }
712
713 #[must_use]
718 pub fn filter_stats(&self) -> &FilterStats {
719 &self.filter_stats
720 }
721
722 pub fn filter_stats_mut(&mut self) -> &mut FilterStats {
724 &mut self.filter_stats
725 }
726
727 pub fn set_filter(&mut self, pattern: Option<&str>) {
731 match pattern {
732 Some(pat) if !pat.is_empty() => {
733 self.filter_stats.full_rescans += 1;
735 self.filter_stats.full_rescan_lines += self.virt.len() as u64;
736 let mut indices = Vec::new();
737 for idx in 0..self.virt.len() {
738 if let Some(item) = self.virt.get(idx)
739 && item.to_plain_text().contains(pat)
740 {
741 indices.push(idx);
742 }
743 }
744 self.filter = Some(pat.to_string());
745 self.filtered_indices = Some(indices);
746 self.filtered_scroll_offset = if let Some(indices) = self.filtered_indices.as_ref()
747 {
748 if indices.is_empty() {
749 0
750 } else if self.virt.follow_mode() || self.virt.is_at_bottom() {
751 indices.len().saturating_sub(1)
752 } else {
753 let scroll_offset = self.virt.scroll_offset();
754 indices.partition_point(|&idx| idx < scroll_offset)
755 }
756 } else {
757 0
758 };
759 self.search = None;
760 }
761 _ => {
762 self.filter = None;
763 self.filtered_indices = None;
764 self.filtered_scroll_offset = 0;
765 self.search = None;
766 }
767 }
768 }
769
770 pub fn search(&mut self, query: &str) -> usize {
775 self.search_with_config(query, SearchConfig::default())
776 }
777
778 pub fn search_with_config(&mut self, query: &str, config: SearchConfig) -> usize {
782 if query.is_empty() {
783 self.search = None;
784 return 0;
785 }
786
787 #[cfg(feature = "regex-search")]
789 let compiled_regex = if config.mode == SearchMode::Regex {
790 match compile_regex(query, &config) {
791 Some(re) => Some(re),
792 None => {
793 self.search = None;
795 return 0;
796 }
797 }
798 } else {
799 None
800 };
801
802 let query_lower = if !config.case_sensitive {
804 Some(query.to_ascii_lowercase())
805 } else {
806 None
807 };
808
809 self.filter_stats.full_rescans += 1;
811 let mut matches = Vec::new();
812 let mut highlight_ranges = Vec::new();
813
814 let iter: Box<dyn Iterator<Item = usize>> =
815 if let Some(indices) = self.filtered_indices.as_ref() {
816 self.filter_stats.full_rescan_lines += indices.len() as u64;
817 Box::new(indices.iter().copied())
818 } else {
819 self.filter_stats.full_rescan_lines += self.virt.len() as u64;
820 Box::new(0..self.virt.len())
821 };
822
823 for idx in iter {
824 if let Some(item) = self.virt.get(idx) {
825 let plain = item.to_plain_text();
826 let ranges = find_match_ranges(
827 &plain,
828 query,
829 query_lower.as_deref(),
830 &config,
831 #[cfg(feature = "regex-search")]
832 compiled_regex.as_ref(),
833 );
834 if !ranges.is_empty() {
835 matches.push(idx);
836 highlight_ranges.push(ranges);
837 }
838 }
839 }
840
841 let count = matches.len();
842
843 let context_expanded = if config.context_lines > 0 {
844 Some(expand_context(
845 &matches,
846 config.context_lines,
847 self.virt.len(),
848 ))
849 } else {
850 None
851 };
852
853 self.search = Some(SearchState {
854 query: query.to_string(),
855 query_lower,
856 config,
857 matches,
858 current: 0,
859 highlight_ranges,
860 #[cfg(feature = "regex-search")]
861 compiled_regex,
862 context_expanded,
863 });
864
865 if let Some(ref search) = self.search
867 && let Some(&idx) = search.matches.first()
868 {
869 self.scroll_to_match(idx);
870 }
871
872 count
873 }
874
875 pub fn next_match(&mut self) {
877 if let Some(ref mut search) = self.search
878 && !search.matches.is_empty()
879 {
880 search.current = (search.current + 1) % search.matches.len();
881 let idx = search.matches[search.current];
882 self.scroll_to_match(idx);
883 }
884 }
885
886 pub fn prev_match(&mut self) {
888 if let Some(ref mut search) = self.search
889 && !search.matches.is_empty()
890 {
891 search.current = if search.current == 0 {
892 search.matches.len() - 1
893 } else {
894 search.current - 1
895 };
896 let idx = search.matches[search.current];
897 self.scroll_to_match(idx);
898 }
899 }
900
901 pub fn clear_search(&mut self) {
903 self.search = None;
904 }
905
906 #[must_use]
908 pub fn search_info(&self) -> Option<(usize, usize)> {
909 self.search.as_ref().and_then(|s| {
910 if s.matches.is_empty() {
911 None
912 } else {
913 Some((s.current + 1, s.matches.len()))
914 }
915 })
916 }
917
918 #[must_use]
922 pub fn highlight_ranges_for_line(&self, line_idx: usize) -> Option<&[(usize, usize)]> {
923 let search = self.search.as_ref()?;
924 let pos = search.matches.iter().position(|&m| m == line_idx)?;
925 search.highlight_ranges.get(pos).map(|v| v.as_slice())
926 }
927
928 #[must_use]
932 pub fn context_line_indices(&self) -> Option<&[usize]> {
933 self.search
934 .as_ref()
935 .and_then(|s| s.context_expanded.as_deref())
936 }
937
938 #[must_use]
944 pub fn search_match_rate_hint(&self) -> f64 {
945 let stats = &self.filter_stats;
946 if stats.incremental_search_checks == 0 {
947 return 0.0;
948 }
949 stats.incremental_search_matches as f64 / stats.incremental_search_checks as f64
950 }
951
952 fn wrapped_rows(&self, text: &Text, width: u16) -> u16 {
955 if matches!(self.wrap_mode, LogWrapMode::NoWrap) {
956 return 1;
957 }
958 let content = text.to_plain_text();
959 if display_width(&content) <= width as usize {
960 return 1;
961 }
962 let options = WrapOptions::new(width as usize).mode(self.wrap_mode.into());
963 u16::try_from(wrap_with_options(&content, &options).len())
964 .unwrap_or(u16::MAX)
965 .max(1)
966 }
967
968 #[allow(clippy::too_many_arguments)]
972 fn render_line(
973 &self,
974 text: &Text,
975 line_idx: usize,
976 x: u16,
977 y: u16,
978 width: u16,
979 max_y: u16,
980 frame: &mut Frame,
981 is_selected: bool,
982 skip_rows: u16,
983 ) -> u16 {
984 let effective_style = if is_selected {
985 self.highlight_style.unwrap_or(self.style)
986 } else {
987 self.style
988 };
989
990 let line = text.lines().first();
991 let content = text.to_plain_text();
992 let content_width = display_width(&content);
993 let hl_ranges = self.highlight_ranges_for_line(line_idx);
994
995 match self.wrap_mode {
997 LogWrapMode::NoWrap => {
998 if y < max_y {
999 if let Some(ranges) = hl_ranges.filter(|r| !r.is_empty()) {
1000 self.draw_highlighted_line(
1001 &content,
1002 ranges,
1003 x,
1004 y,
1005 x.saturating_add(width),
1006 frame,
1007 effective_style,
1008 );
1009 } else {
1010 self.draw_text_line(
1011 line,
1012 &content,
1013 x,
1014 y,
1015 x.saturating_add(width),
1016 frame,
1017 effective_style,
1018 );
1019 }
1020 }
1021 1
1022 }
1023 LogWrapMode::CharWrap | LogWrapMode::WordWrap => {
1024 if content_width <= width as usize {
1025 if y < max_y {
1026 if let Some(ranges) = hl_ranges.filter(|r| !r.is_empty()) {
1027 self.draw_highlighted_line(
1028 &content,
1029 ranges,
1030 x,
1031 y,
1032 x.saturating_add(width),
1033 frame,
1034 effective_style,
1035 );
1036 } else {
1037 self.draw_text_line(
1038 line,
1039 &content,
1040 x,
1041 y,
1042 x.saturating_add(width),
1043 frame,
1044 effective_style,
1045 );
1046 }
1047 }
1048 1
1049 } else {
1050 let options = WrapOptions::new(width as usize).mode(self.wrap_mode.into());
1051 let wrapped = wrap_with_options(&content, &options);
1052 let mut lines_rendered = 0u16;
1053
1054 for (i, part) in wrapped.into_iter().skip(skip_rows as usize).enumerate() {
1055 let line_y = y.saturating_add(i as u16);
1056 if line_y >= max_y {
1057 break;
1058 }
1059 draw_text_span(
1060 frame,
1061 x,
1062 line_y,
1063 &part,
1064 effective_style,
1065 x.saturating_add(width),
1066 );
1067 lines_rendered += 1;
1068 }
1069
1070 lines_rendered.max(1)
1071 }
1072 }
1073 }
1074 }
1075
1076 #[allow(clippy::too_many_arguments)]
1078 fn draw_highlighted_line(
1079 &self,
1080 content: &str,
1081 ranges: &[(usize, usize)],
1082 x: u16,
1083 y: u16,
1084 max_x: u16,
1085 frame: &mut Frame,
1086 base_style: Style,
1087 ) {
1088 let hl_style = self
1089 .search_highlight_style
1090 .unwrap_or_else(|| Style::new().bold().reverse());
1091 let mut cursor_x = x;
1092 let mut pos = 0;
1093
1094 for &(start, end) in ranges {
1095 let start = start.min(content.len());
1096 let end = end.min(content.len());
1097 if start > pos {
1098 cursor_x =
1100 draw_text_span(frame, cursor_x, y, &content[pos..start], base_style, max_x);
1101 }
1102 if start < end {
1103 cursor_x =
1105 draw_text_span(frame, cursor_x, y, &content[start..end], hl_style, max_x);
1106 }
1107 pos = end;
1108 }
1109 if pos < content.len() {
1111 draw_text_span(frame, cursor_x, y, &content[pos..], base_style, max_x);
1112 }
1113 }
1114
1115 #[allow(clippy::too_many_arguments)]
1116 fn draw_text_line(
1117 &self,
1118 line: Option<&ftui_text::Line>,
1119 fallback: &str,
1120 x: u16,
1121 y: u16,
1122 max_x: u16,
1123 frame: &mut Frame,
1124 base_style: Style,
1125 ) {
1126 if let Some(line) = line {
1127 let mut cursor_x = x;
1128 for span in line.spans() {
1129 if cursor_x >= max_x {
1130 break;
1131 }
1132 let span_style = span
1133 .style
1134 .map_or(base_style, |style| style.merge(&base_style));
1135 cursor_x = draw_text_span_with_link(
1136 frame,
1137 cursor_x,
1138 y,
1139 span.as_str(),
1140 span_style,
1141 max_x,
1142 span.link.as_deref(),
1143 );
1144 }
1145 } else {
1146 draw_text_span(frame, x, y, fallback, base_style, max_x);
1147 }
1148 }
1149
1150 fn scroll_to_match(&mut self, idx: usize) {
1151 if let Some(indices) = self.filtered_indices.as_ref() {
1152 let position = indices.partition_point(|&v| v < idx);
1153 self.filtered_scroll_offset = position.min(indices.len().saturating_sub(1));
1154 } else {
1155 self.virt.scroll_to(idx);
1156 }
1157 }
1158
1159 fn is_filtered_at_bottom(&self, total: usize, visible_count: usize) -> bool {
1160 if visible_count == 0 {
1161 return false;
1162 }
1163 if total == 0 {
1164 return true;
1165 }
1166 self.filtered_scroll_offset >= total.saturating_sub(visible_count)
1167 }
1168}
1169
1170struct LogLineRenderItem<'a> {
1171 viewer: &'a LogViewer,
1172 text: &'a Text,
1173 line_idx: usize,
1174 height: u16,
1175 is_selected: bool,
1176 initial_skip_rows: u16,
1177}
1178
1179impl RenderItem for LogLineRenderItem<'_> {
1180 fn render(&self, area: Rect, frame: &mut Frame, _selected: bool, skip_rows: u16) {
1181 let total_skip = self.initial_skip_rows.saturating_add(skip_rows);
1182 let _ = self.viewer.render_line(
1183 self.text,
1184 self.line_idx,
1185 area.x,
1186 area.y,
1187 area.width,
1188 area.bottom(),
1189 frame,
1190 self.is_selected,
1191 total_skip,
1192 );
1193 }
1194
1195 fn height(&self) -> u16 {
1196 self.height.max(1)
1197 }
1198}
1199
1200impl StatefulWidget for LogViewer {
1201 type State = LogViewerState;
1202
1203 fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
1204 if area.width == 0 || area.height == 0 {
1205 return;
1206 }
1207
1208 self.last_wrap_width.set(area.width.max(1));
1209 clear_text_area(frame, area, self.style);
1210
1211 let _ = self.virt.visible_range(area.height);
1213
1214 state.last_viewport_height = area.height;
1216
1217 let total_lines = self.virt.len();
1218 if total_lines == 0 {
1219 state.last_visible_lines = 0;
1220 state.list_state.resize_heights(0);
1221 return;
1222 }
1223
1224 let render_indices: Option<&[usize]> = self.filtered_indices.as_deref();
1226 let display_total = render_indices.map_or(total_lines, <[usize]>::len);
1227 state.list_state.resize_heights(display_total);
1228
1229 let visible_count = area.height as usize;
1231
1232 let (mut start_idx, mut end_idx, anchored_to_bottom) = if let Some(indices) = render_indices
1234 {
1235 let filtered_total = indices.len();
1237 if filtered_total == 0 {
1238 state.last_visible_lines = 0;
1239 return;
1240 }
1241 let max_offset = filtered_total.saturating_sub(visible_count);
1243 let offset = self.filtered_scroll_offset.min(max_offset);
1244 let start = offset;
1245 let end = (offset + visible_count).min(filtered_total);
1246 let is_bottom = offset >= max_offset;
1247 (start, end, is_bottom)
1248 } else {
1249 let range = self.virt.visible_range(area.height);
1251 (range.start, range.end, self.virt.follow_mode())
1252 };
1253
1254 let mut skip_first_rows = 0u16;
1261 if anchored_to_bottom && !matches!(self.wrap_mode, LogWrapMode::NoWrap) {
1262 let mut rows = 0u32;
1263 let mut start = display_total;
1264 while start > 0 && rows < u32::from(area.height) {
1265 start -= 1;
1266 let line_idx = render_indices.map_or(start, |indices| indices[start]);
1267 if let Some(text) = self.virt.get(line_idx) {
1268 let h = self.wrapped_rows(text, area.width);
1269 state.list_state.measure(start, h);
1270 rows += u32::from(h);
1271 }
1272 }
1273 start_idx = start;
1274 end_idx = display_total;
1275 skip_first_rows =
1276 u16::try_from(rows.saturating_sub(u32::from(area.height))).unwrap_or(u16::MAX);
1277 }
1278
1279 let mut y = area.y;
1280 let mut lines_rendered = 0;
1281 let mut last_rendered_index = None;
1282 let mut window_items = Vec::with_capacity(end_idx.saturating_sub(start_idx));
1283
1284 for display_idx in start_idx..end_idx {
1285 if y >= area.bottom() {
1286 break;
1287 }
1288
1289 let line_idx = if let Some(indices) = render_indices {
1291 indices[display_idx]
1292 } else {
1293 display_idx
1294 };
1295
1296 let Some(line) = self.virt.get(line_idx) else {
1297 continue;
1298 };
1299
1300 let is_selected = state.selected_line == Some(line_idx);
1301
1302 let skip_rows = if display_idx == start_idx {
1303 skip_first_rows
1304 } else {
1305 0
1306 };
1307 let raw_h = self.wrapped_rows(line, area.width);
1308 state.list_state.measure(display_idx, raw_h);
1309 let lines_used = raw_h
1310 .saturating_sub(skip_rows)
1311 .max(1)
1312 .min(area.bottom().saturating_sub(y));
1313
1314 window_items.push(LogLineRenderItem {
1315 viewer: self,
1316 text: line,
1317 line_idx,
1318 height: lines_used,
1319 is_selected,
1320 initial_skip_rows: skip_rows,
1321 });
1322
1323 y = y.saturating_add(lines_used);
1324 lines_rendered += 1;
1325 last_rendered_index = Some(display_idx);
1326 }
1327
1328 if !window_items.is_empty() {
1329 let mut window_state = VirtualizedListState::variable(1);
1330 VirtualizedList::new(&window_items)
1331 .variable_heights()
1332 .style(self.style)
1333 .show_scrollbar(false)
1334 .render(area, frame, &mut window_state);
1335 }
1336
1337 state.last_visible_lines = lines_rendered;
1338
1339 self.virt.set_visible_count(lines_rendered);
1341
1342 let at_bottom = if let Some(indices) = render_indices {
1344 if let Some(last) = last_rendered_index {
1345 last >= indices.len().saturating_sub(1)
1346 } else {
1347 false
1348 }
1349 } else if let Some(last) = last_rendered_index {
1350 last >= total_lines.saturating_sub(1)
1351 } else {
1352 false
1353 };
1354
1355 if !at_bottom && area.width >= 4 {
1357 let lines_below = if let Some(indices) = render_indices {
1358 indices.len().saturating_sub(end_idx)
1359 } else {
1360 total_lines.saturating_sub(end_idx)
1361 };
1362 let indicator = format!(" {} ", lines_below);
1363 let indicator_len = display_width(&indicator) as u16;
1364 if indicator_len < area.width {
1365 let indicator_x = area.right().saturating_sub(indicator_len);
1366 let indicator_y = area.bottom().saturating_sub(1);
1367 draw_text_span(
1368 frame,
1369 indicator_x,
1370 indicator_y,
1371 &indicator,
1372 Style::new().bold(),
1373 area.right(),
1374 );
1375 }
1376 }
1377
1378 if let Some((current, total)) = self.search_info()
1380 && area.width >= 10
1381 {
1382 let search_indicator = format!(" {}/{} ", current, total);
1383 let ind_len = display_width(&search_indicator) as u16;
1384 if ind_len < area.width {
1385 let ind_x = area.x;
1386 let ind_y = area.bottom().saturating_sub(1);
1387 draw_text_span(
1388 frame,
1389 ind_x,
1390 ind_y,
1391 &search_indicator,
1392 Style::new().bold(),
1393 ind_x.saturating_add(ind_len),
1394 );
1395 }
1396 }
1397 }
1398}
1399
1400fn search_ascii_case_insensitive_ranges(haystack: &str, needle_lower: &str) -> Vec<(usize, usize)> {
1402 let mut results = Vec::new();
1403 if needle_lower.is_empty() {
1404 return results;
1405 }
1406
1407 if !haystack.is_ascii() || !needle_lower.is_ascii() {
1408 return search_ascii_case_insensitive(haystack, needle_lower)
1409 .into_iter()
1410 .map(|r| (r.range.start, r.range.end))
1411 .collect();
1412 }
1413
1414 let haystack_bytes = haystack.as_bytes();
1415 let needle_bytes = needle_lower.as_bytes();
1416 let needle_len = needle_bytes.len();
1417
1418 if needle_len > haystack_bytes.len() {
1419 return results;
1420 }
1421
1422 const MAX_WORK: usize = 4096;
1423 if haystack_bytes.len().saturating_mul(needle_len) > MAX_WORK {
1424 return search_ascii_case_insensitive(haystack, needle_lower)
1425 .into_iter()
1426 .map(|r| (r.range.start, r.range.end))
1427 .collect();
1428 }
1429
1430 let mut i = 0;
1431 while i <= haystack_bytes.len() - needle_len {
1432 let mut match_found = true;
1433 for j in 0..needle_len {
1434 if haystack_bytes[i + j].to_ascii_lowercase() != needle_bytes[j] {
1435 match_found = false;
1436 break;
1437 }
1438 }
1439 if match_found {
1440 results.push((i, i + needle_len));
1441 i += needle_len;
1442 } else {
1443 i += 1;
1444 }
1445 }
1446 results
1447}
1448
1449fn find_match_ranges(
1451 plain: &str,
1452 query: &str,
1453 query_lower: Option<&str>,
1454 config: &SearchConfig,
1455 #[cfg(feature = "regex-search")] compiled_regex: Option<®ex::Regex>,
1456) -> Vec<(usize, usize)> {
1457 match config.mode {
1458 SearchMode::Literal => {
1459 if config.case_sensitive {
1460 search_exact(plain, query)
1461 .into_iter()
1462 .map(|r| (r.range.start, r.range.end))
1463 .collect()
1464 } else if let Some(lower) = query_lower {
1465 search_ascii_case_insensitive_ranges(plain, lower)
1466 } else {
1467 search_ascii_case_insensitive(plain, query)
1468 .into_iter()
1469 .map(|r| (r.range.start, r.range.end))
1470 .collect()
1471 }
1472 }
1473 SearchMode::Regex => {
1474 #[cfg(feature = "regex-search")]
1475 {
1476 if let Some(re) = compiled_regex {
1477 re.find_iter(plain).map(|m| (m.start(), m.end())).collect()
1478 } else {
1479 Vec::new()
1480 }
1481 }
1482 #[cfg(not(feature = "regex-search"))]
1483 {
1484 Vec::new()
1486 }
1487 }
1488 }
1489}
1490
1491#[cfg(feature = "regex-search")]
1493fn compile_regex(query: &str, config: &SearchConfig) -> Option<regex::Regex> {
1494 let pattern = if config.case_sensitive {
1495 query.to_string()
1496 } else {
1497 format!("(?i){}", query)
1498 };
1499 regex::Regex::new(&pattern).ok()
1500}
1501
1502fn expand_context(matches: &[usize], context_lines: usize, total_lines: usize) -> Vec<usize> {
1504 let mut expanded = Vec::new();
1505 for &idx in matches {
1506 let start = idx.saturating_sub(context_lines);
1507 let end = (idx + context_lines + 1).min(total_lines);
1508 for i in start..end {
1509 expanded.push(i);
1510 }
1511 }
1512 expanded.sort_unstable();
1513 expanded.dedup();
1514 expanded
1515}
1516
1517#[cfg(test)]
1518mod tests {
1519 use super::*;
1520 use ftui_render::cell::StyleFlags as RenderStyleFlags;
1521 use ftui_render::grapheme_pool::GraphemePool;
1522 use ftui_style::StyleFlags as TextStyleFlags;
1523
1524 fn line_text(frame: &Frame, y: u16, width: u16) -> String {
1525 let mut out = String::with_capacity(width as usize);
1526 for x in 0..width {
1527 let ch = frame
1528 .buffer
1529 .get(x, y)
1530 .and_then(|cell| cell.content.as_char())
1531 .unwrap_or(' ');
1532 out.push(ch);
1533 }
1534 out
1535 }
1536
1537 fn render_rows(
1540 log: &LogViewer,
1541 state: &mut LogViewerState,
1542 w: u16,
1543 h: u16,
1544 frames: usize,
1545 ) -> Vec<String> {
1546 let mut pool = GraphemePool::new();
1547 let mut frame = Frame::new(w, h, &mut pool);
1548 for _ in 0..frames {
1549 log.render(Rect::new(0, 0, w, h), &mut frame, state);
1550 }
1551 (0..h).map(|y| line_text(&frame, y, w)).collect()
1552 }
1553
1554 #[test]
1555 fn wrapped_follow_mode_shows_the_newest_entry() {
1556 let mut log = LogViewer::new(100).wrap_mode(LogWrapMode::CharWrap);
1559 for i in 0..5 {
1560 log.push(format!("entry-{i}-xxxxxxxx"));
1561 }
1562 let mut state = LogViewerState::default();
1563 for frames in [1, 3] {
1564 let rows = render_rows(&log, &mut state, 12, 4, frames);
1565 assert!(
1566 rows.iter().any(|r| r.contains("entry-4")),
1567 "{frames} frame(s): {rows:?}"
1568 );
1569 assert!(rows[0].contains("entry-3"), "{frames} frame(s): {rows:?}");
1570 }
1571 }
1572
1573 #[test]
1574 fn wrapped_entry_taller_than_the_viewport_shows_its_last_rows_when_following() {
1575 let mut log = LogViewer::new(10).wrap_mode(LogWrapMode::CharWrap);
1577 log.push("short");
1578 log.push("aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd");
1579 let mut state = LogViewerState::default();
1580 let rows = render_rows(&log, &mut state, 10, 3, 2);
1581 assert_eq!(rows, ["bbbbbbbbbb", "cccccccccc", "dddddddddd"]);
1582 }
1583
1584 #[test]
1585 fn wrapped_view_scrolled_to_the_top_stays_top_anchored() {
1586 let mut log = LogViewer::new(100).wrap_mode(LogWrapMode::CharWrap);
1587 for i in 0..5 {
1588 log.push(format!("entry-{i}-xxxxxxxx"));
1589 }
1590 log.scroll_to_top();
1591 let mut state = LogViewerState::default();
1592 let rows = render_rows(&log, &mut state, 12, 4, 2);
1593 assert!(rows[0].starts_with("entry-0"), "{rows:?}");
1594 }
1595
1596 #[test]
1597 fn wrapped_filtered_view_at_the_bottom_shows_the_newest_match() {
1598 let mut log = LogViewer::new(100).wrap_mode(LogWrapMode::CharWrap);
1599 for i in 0..6 {
1600 log.push(format!(
1601 "{}-{i}-xxxxxxxxxx",
1602 if i % 2 == 0 { "keep" } else { "drop" }
1603 ));
1604 }
1605 log.set_filter(Some("keep"));
1606 let mut state = LogViewerState::default();
1607 let rows = render_rows(&log, &mut state, 10, 4, 2);
1608 assert!(rows.iter().any(|r| r.contains("keep-4")), "{rows:?}");
1609 }
1610
1611 #[test]
1612 fn wrapped_short_log_is_drawn_from_the_top() {
1613 let mut log = LogViewer::new(10).wrap_mode(LogWrapMode::CharWrap);
1615 log.push("one");
1616 log.push("two");
1617 let mut state = LogViewerState::default();
1618 let rows = render_rows(&log, &mut state, 10, 5, 1);
1619 assert!(
1620 rows[0].starts_with("one") && rows[1].starts_with("two"),
1621 "{rows:?}"
1622 );
1623 }
1624
1625 #[test]
1626 fn test_push_appends_to_end() {
1627 let mut log = LogViewer::new(100);
1628 log.push("line 1");
1629 log.push("line 2");
1630 assert_eq!(log.line_count(), 2);
1631 }
1632
1633 #[test]
1634 fn test_circular_buffer_eviction() {
1635 let mut log = LogViewer::new(3);
1636 log.push("line 1");
1637 log.push("line 2");
1638 log.push("line 3");
1639 log.push("line 4"); assert_eq!(log.line_count(), 3);
1641 }
1642
1643 #[test]
1644 fn test_auto_scroll_stays_at_bottom() {
1645 let mut log = LogViewer::new(100);
1646 log.push("line 1");
1647 assert!(log.is_at_bottom());
1648 log.push("line 2");
1649 assert!(log.is_at_bottom());
1650 }
1651
1652 #[test]
1653 fn test_manual_scroll_disables_auto_scroll() {
1654 let mut log = LogViewer::new(100);
1655 log.virt.set_visible_count(10);
1656 for i in 0..50 {
1657 log.push(format!("line {}", i));
1658 }
1659 log.scroll_up(10);
1660 assert!(!log.auto_scroll_enabled());
1661 log.push("new line");
1662 assert!(!log.auto_scroll_enabled()); }
1664
1665 #[test]
1666 fn test_scroll_to_bottom_reengages_auto_scroll() {
1667 let mut log = LogViewer::new(100);
1668 log.virt.set_visible_count(10);
1669 for i in 0..50 {
1670 log.push(format!("line {}", i));
1671 }
1672 log.scroll_up(10);
1673 log.scroll_to_bottom();
1674 assert!(log.is_at_bottom());
1675 assert!(log.auto_scroll_enabled());
1676 }
1677
1678 #[test]
1679 fn test_scroll_down_reengages_at_bottom() {
1680 let mut log = LogViewer::new(100);
1681 log.virt.set_visible_count(10);
1682 for i in 0..50 {
1683 log.push(format!("line {}", i));
1684 }
1685 log.scroll_up(5);
1686 assert!(!log.auto_scroll_enabled());
1687
1688 log.scroll_down(5);
1689 if log.is_at_bottom() {
1690 assert!(log.auto_scroll_enabled());
1691 }
1692 }
1693
1694 #[test]
1695 fn test_scroll_to_top() {
1696 let mut log = LogViewer::new(100);
1697 for i in 0..50 {
1698 log.push(format!("line {}", i));
1699 }
1700 log.scroll_to_top();
1701 assert!(!log.auto_scroll_enabled());
1702 }
1703
1704 #[test]
1705 fn test_page_up_down() {
1706 let mut log = LogViewer::new(100);
1707 log.virt.set_visible_count(10);
1708 for i in 0..50 {
1709 log.push(format!("line {}", i));
1710 }
1711
1712 let state = LogViewerState {
1713 last_viewport_height: 10,
1714 ..Default::default()
1715 };
1716
1717 assert!(log.is_at_bottom());
1718
1719 log.page_up(&state);
1720 assert!(!log.is_at_bottom());
1721
1722 log.page_down(&state);
1723 }
1725
1726 #[test]
1727 fn test_clear() {
1728 let mut log = LogViewer::new(100);
1729 log.push("line 1");
1730 log.push("line 2");
1731 log.clear();
1732 assert_eq!(log.line_count(), 0);
1733 }
1734
1735 #[test]
1736 fn test_push_many() {
1737 let mut log = LogViewer::new(100);
1738 log.push_many(["line 1", "line 2", "line 3"]);
1739 assert_eq!(log.line_count(), 3);
1740 }
1741
1742 #[test]
1743 fn test_render_empty() {
1744 let mut pool = GraphemePool::new();
1745 let mut frame = Frame::new(80, 24, &mut pool);
1746 let log = LogViewer::new(100);
1747 let mut state = LogViewerState::default();
1748
1749 log.render(Rect::new(0, 0, 80, 24), &mut frame, &mut state);
1750
1751 assert_eq!(state.last_visible_lines, 0);
1752 }
1753
1754 #[test]
1755 fn test_render_empty_clears_stale_content() {
1756 let mut pool = GraphemePool::new();
1757 let mut frame = Frame::new(20, 3, &mut pool);
1758 let mut log = LogViewer::new(100);
1759 let mut state = LogViewerState::default();
1760 let area = Rect::new(0, 0, 20, 3);
1761
1762 log.push("first line");
1763 log.push("second line");
1764 log.render(area, &mut frame, &mut state);
1765
1766 log.clear();
1767 log.render(area, &mut frame, &mut state);
1768
1769 assert_eq!(state.last_visible_lines, 0);
1770 assert_eq!(line_text(&frame, 0, 20), " ".repeat(20));
1771 assert_eq!(line_text(&frame, 1, 20), " ".repeat(20));
1772 assert_eq!(line_text(&frame, 2, 20), " ".repeat(20));
1773 }
1774
1775 #[test]
1776 fn test_render_some_lines() {
1777 let mut pool = GraphemePool::new();
1778 let mut frame = Frame::new(80, 10, &mut pool);
1779 let mut log = LogViewer::new(100);
1780
1781 for i in 0..5 {
1782 log.push(format!("Line {}", i));
1783 }
1784
1785 let mut state = LogViewerState::default();
1786 log.render(Rect::new(0, 0, 80, 10), &mut frame, &mut state);
1787
1788 assert_eq!(state.last_viewport_height, 10);
1789 assert_eq!(state.last_visible_lines, 5);
1790 }
1791
1792 #[test]
1793 fn test_toggle_follow() {
1794 let mut log = LogViewer::new(100);
1795 assert!(log.auto_scroll_enabled());
1796 log.toggle_follow();
1797 assert!(!log.auto_scroll_enabled());
1798 log.toggle_follow();
1799 assert!(log.auto_scroll_enabled());
1800 }
1801
1802 #[test]
1803 fn test_filter_shows_matching_lines() {
1804 let mut log = LogViewer::new(100);
1805 log.push("INFO: starting");
1806 log.push("ERROR: something failed");
1807 log.push("INFO: processing");
1808 log.push("ERROR: another failure");
1809 log.push("INFO: done");
1810
1811 log.set_filter(Some("ERROR"));
1812 assert_eq!(log.filtered_indices.as_ref().unwrap().len(), 2);
1813
1814 log.set_filter(None);
1816 assert!(log.filtered_indices.is_none());
1817 }
1818
1819 #[test]
1820 fn test_render_filter_no_matches_clears_stale_content() {
1821 let mut pool = GraphemePool::new();
1822 let mut frame = Frame::new(20, 3, &mut pool);
1823 let mut log = LogViewer::new(100);
1824 let mut state = LogViewerState::default();
1825 let area = Rect::new(0, 0, 20, 3);
1826
1827 log.push("INFO: starting");
1828 log.push("ERROR: something failed");
1829 log.render(area, &mut frame, &mut state);
1830
1831 log.set_filter(Some("MISSING"));
1832 log.render(area, &mut frame, &mut state);
1833
1834 assert_eq!(state.last_visible_lines, 0);
1835 assert_eq!(line_text(&frame, 0, 20), " ".repeat(20));
1836 assert_eq!(line_text(&frame, 1, 20), " ".repeat(20));
1837 assert_eq!(line_text(&frame, 2, 20), " ".repeat(20));
1838 }
1839
1840 #[test]
1841 fn test_search_finds_matches() {
1842 let mut log = LogViewer::new(100);
1843 log.push("hello world");
1844 log.push("goodbye world");
1845 log.push("hello again");
1846
1847 let count = log.search("hello");
1848 assert_eq!(count, 2);
1849 assert_eq!(log.search_info(), Some((1, 2)));
1850 }
1851
1852 #[test]
1853 fn test_search_respects_filter() {
1854 let mut log = LogViewer::new(100);
1855 log.push("INFO: ok");
1856 log.push("ERROR: first");
1857 log.push("WARN: mid");
1858 log.push("ERROR: second");
1859
1860 log.set_filter(Some("ERROR"));
1861 assert_eq!(log.search("WARN"), 0);
1862 assert_eq!(log.search("ERROR"), 2);
1863 }
1864
1865 #[test]
1866 fn test_filter_clears_search() {
1867 let mut log = LogViewer::new(100);
1868 log.push("alpha");
1869 log.search("alpha");
1870 assert!(log.search_info().is_some());
1871
1872 log.set_filter(Some("alpha"));
1873 assert!(log.search_info().is_none());
1874 }
1875
1876 #[test]
1877 fn test_search_sets_filtered_scroll_offset() {
1878 let mut log = LogViewer::new(100);
1879 log.push("match one");
1880 log.push("line two");
1881 log.push("match three");
1882 log.push("match four");
1883
1884 log.set_filter(Some("match"));
1885 log.search("match");
1886
1887 assert_eq!(log.filtered_scroll_offset, 0);
1888 log.next_match();
1889 assert_eq!(log.filtered_scroll_offset, 1);
1890 }
1891
1892 #[test]
1893 fn test_search_next_prev() {
1894 let mut log = LogViewer::new(100);
1895 log.push("match A");
1896 log.push("nothing here");
1897 log.push("match B");
1898 log.push("match C");
1899
1900 log.search("match");
1901 assert_eq!(log.search_info(), Some((1, 3)));
1902
1903 log.next_match();
1904 assert_eq!(log.search_info(), Some((2, 3)));
1905
1906 log.next_match();
1907 assert_eq!(log.search_info(), Some((3, 3)));
1908
1909 log.next_match(); assert_eq!(log.search_info(), Some((1, 3)));
1911
1912 log.prev_match(); assert_eq!(log.search_info(), Some((3, 3)));
1914 }
1915
1916 #[test]
1917 fn test_clear_search() {
1918 let mut log = LogViewer::new(100);
1919 log.push("hello");
1920 log.search("hello");
1921 assert!(log.search_info().is_some());
1922
1923 log.clear_search();
1924 assert!(log.search_info().is_none());
1925 }
1926
1927 #[test]
1928 fn test_filter_with_push() {
1929 let mut log = LogViewer::new(100);
1930 log.set_filter(Some("ERROR"));
1931 log.push("INFO: ok");
1932 log.push("ERROR: bad");
1933 log.push("INFO: fine");
1934
1935 assert_eq!(log.filtered_indices.as_ref().unwrap().len(), 1);
1936 assert_eq!(log.filtered_indices.as_ref().unwrap()[0], 1);
1937 }
1938
1939 #[test]
1940 fn test_eviction_adjusts_filter_indices() {
1941 let mut log = LogViewer::new(3);
1942 log.set_filter(Some("x"));
1943 log.push("x1");
1944 log.push("y2");
1945 log.push("x3");
1946 assert_eq!(log.filtered_indices.as_ref().unwrap(), &[0, 2]);
1948
1949 log.push("y4"); assert_eq!(log.filtered_indices.as_ref().unwrap(), &[1]);
1952 }
1953
1954 #[test]
1955 fn test_filter_scroll_offset_tracks_unfiltered_position() {
1956 let mut log = LogViewer::new(100);
1957 for i in 0..20 {
1958 if i == 2 || i == 10 || i == 15 {
1959 log.push(format!("match {}", i));
1960 } else {
1961 log.push(format!("line {}", i));
1962 }
1963 }
1964
1965 log.virt.scroll_to(12);
1966 log.set_filter(Some("match"));
1967
1968 assert_eq!(log.filtered_scroll_offset, 2);
1970 }
1971
1972 #[test]
1973 fn test_filtered_scroll_down_moves_within_filtered_list() {
1974 let mut log = LogViewer::new(100);
1975 log.push("match one");
1976 log.push("line two");
1977 log.push("match three");
1978 log.push("line four");
1979 log.push("match five");
1980
1981 log.set_filter(Some("match"));
1982 log.scroll_to_top();
1983 log.scroll_down(1);
1984
1985 assert_eq!(log.filtered_scroll_offset, 1);
1986 }
1987
1988 #[test]
1993 fn test_incremental_filter_on_push_tracks_stats() {
1994 let mut log = LogViewer::new(100);
1995 log.set_filter(Some("ERROR"));
1996 assert_eq!(log.filter_stats().full_rescans, 1);
1998
1999 log.push("INFO: ok");
2000 log.push("ERROR: bad");
2001 log.push("INFO: fine");
2002 log.push("ERROR: worse");
2003
2004 assert_eq!(log.filter_stats().incremental_checks, 4);
2006 assert_eq!(log.filter_stats().incremental_matches, 2);
2008 assert_eq!(log.filter_stats().full_rescans, 1);
2010 }
2011
2012 #[test]
2013 fn test_incremental_search_on_push() {
2014 let mut log = LogViewer::new(100);
2015 log.push("hello world");
2016 log.push("goodbye world");
2017
2018 let count = log.search("hello");
2020 assert_eq!(count, 1);
2021 assert_eq!(log.filter_stats().full_rescans, 1);
2022
2023 log.push("hello again");
2025 log.push("nothing here");
2026
2027 assert_eq!(log.search_info(), Some((1, 2)));
2029 assert_eq!(log.filter_stats().incremental_search_matches, 1);
2030 }
2031
2032 #[test]
2033 fn test_incremental_search_respects_active_filter() {
2034 let mut log = LogViewer::new(100);
2035 log.push("ERROR: hello");
2036 log.push("INFO: hello");
2037
2038 log.set_filter(Some("ERROR"));
2039 let count = log.search("hello");
2040 assert_eq!(count, 1); log.push("ERROR: hello again");
2044 log.push("INFO: hello again"); assert_eq!(log.search_info(), Some((1, 2))); assert_eq!(log.filter_stats().incremental_search_matches, 1);
2048 }
2049
2050 #[test]
2051 fn test_incremental_search_without_filter() {
2052 let mut log = LogViewer::new(100);
2053 log.push("first");
2054 log.search("match");
2055 assert_eq!(log.search_info(), None); log.push("match found");
2059 assert_eq!(log.search_info(), Some((1, 1)));
2060 assert_eq!(log.filter_stats().incremental_search_matches, 1);
2061 }
2062
2063 #[test]
2064 fn test_filter_stats_reset_on_clear() {
2065 let mut log = LogViewer::new(100);
2066 log.set_filter(Some("x"));
2067 log.push("x1");
2068 log.push("y2");
2069
2070 assert!(log.filter_stats().incremental_checks > 0);
2071 log.clear();
2072 assert_eq!(log.filter_stats().incremental_checks, 0);
2073 assert_eq!(log.filter_stats().full_rescans, 0);
2074 }
2075
2076 #[test]
2077 fn test_filter_stats_full_rescan_on_filter_change() {
2078 let mut log = LogViewer::new(100);
2079 for i in 0..100 {
2080 log.push(format!("line {}", i));
2081 }
2082
2083 log.set_filter(Some("line 5"));
2084 assert_eq!(log.filter_stats().full_rescans, 1);
2085 assert_eq!(log.filter_stats().full_rescan_lines, 100);
2086
2087 log.set_filter(Some("line 9"));
2088 assert_eq!(log.filter_stats().full_rescans, 2);
2089 assert_eq!(log.filter_stats().full_rescan_lines, 200);
2090 }
2091
2092 #[test]
2093 fn test_filter_stats_manual_reset() {
2094 let mut log = LogViewer::new(100);
2095 log.set_filter(Some("x"));
2096 log.push("x1");
2097 assert!(log.filter_stats().incremental_checks > 0);
2098
2099 log.filter_stats_mut().reset();
2100 assert_eq!(log.filter_stats().incremental_checks, 0);
2101
2102 log.push("x2");
2104 assert_eq!(log.filter_stats().incremental_checks, 1);
2105 }
2106
2107 #[test]
2108 fn test_incremental_eviction_adjusts_search_matches() {
2109 let mut log = LogViewer::new(3);
2110 log.push("match A");
2111 log.push("no");
2112 log.push("match B");
2113 log.search("match");
2114 assert_eq!(log.search_info(), Some((1, 2)));
2115
2116 log.push("match C"); let search = log.search.as_ref().unwrap();
2121 assert_eq!(search.matches.len(), 2);
2122 for &idx in &search.matches {
2124 assert!(idx < log.line_count(), "Search index {} out of range", idx);
2125 }
2126 }
2127
2128 #[test]
2129 fn test_no_stats_when_no_filter_or_search() {
2130 let mut log = LogViewer::new(100);
2131 log.push("line 1");
2132 log.push("line 2");
2133
2134 assert_eq!(log.filter_stats().incremental_checks, 0);
2135 assert_eq!(log.filter_stats().full_rescans, 0);
2136 assert_eq!(log.filter_stats().incremental_search_matches, 0);
2137 }
2138
2139 #[test]
2140 fn test_search_full_rescan_counts_lines() {
2141 let mut log = LogViewer::new(100);
2142 for i in 0..50 {
2143 log.push(format!("line {}", i));
2144 }
2145
2146 log.search("line 1");
2147 assert_eq!(log.filter_stats().full_rescans, 1);
2148 assert_eq!(log.filter_stats().full_rescan_lines, 50);
2149 }
2150
2151 #[test]
2152 fn test_search_full_rescan_on_filtered_counts_filtered_lines() {
2153 let mut log = LogViewer::new(100);
2154 for i in 0..50 {
2155 if i % 2 == 0 {
2156 log.push(format!("even {}", i));
2157 } else {
2158 log.push(format!("odd {}", i));
2159 }
2160 }
2161
2162 log.set_filter(Some("even"));
2163 let initial_rescans = log.filter_stats().full_rescans;
2164 let initial_lines = log.filter_stats().full_rescan_lines;
2165
2166 log.search("even 4");
2167 assert_eq!(log.filter_stats().full_rescans, initial_rescans + 1);
2168 assert_eq!(log.filter_stats().full_rescan_lines, initial_lines + 25);
2170 }
2171
2172 #[test]
2177 fn test_search_literal_case_sensitive() {
2178 let mut log = LogViewer::new(100);
2179 log.push("Hello World");
2180 log.push("hello world");
2181 log.push("HELLO WORLD");
2182
2183 let config = SearchConfig {
2184 mode: SearchMode::Literal,
2185 case_sensitive: true,
2186 context_lines: 0,
2187 };
2188 let count = log.search_with_config("Hello", config);
2189 assert_eq!(count, 1);
2190 assert_eq!(log.search_info(), Some((1, 1)));
2191 }
2192
2193 #[test]
2194 fn test_search_literal_case_insensitive() {
2195 let mut log = LogViewer::new(100);
2196 log.push("Hello World");
2197 log.push("hello world");
2198 log.push("HELLO WORLD");
2199 log.push("no match here");
2200
2201 let config = SearchConfig {
2202 mode: SearchMode::Literal,
2203 case_sensitive: false,
2204 context_lines: 0,
2205 };
2206 let count = log.search_with_config("hello", config);
2207 assert_eq!(count, 3);
2208 }
2209
2210 #[test]
2211 fn test_search_ascii_case_insensitive_fast_path_ranges() {
2212 let mut log = LogViewer::new(100);
2213 log.push("Alpha beta ALPHA beta alpha");
2214
2215 let config = SearchConfig {
2216 mode: SearchMode::Literal,
2217 case_sensitive: false,
2218 context_lines: 0,
2219 };
2220 let count = log.search_with_config("alpha", config);
2221 assert_eq!(count, 1);
2222
2223 let ranges = log.highlight_ranges_for_line(0).expect("match ranges");
2224 assert_eq!(ranges, &[(0, 5), (11, 16), (22, 27)]);
2225 }
2226
2227 #[test]
2228 fn test_search_unicode_fallback_ranges() {
2229 let mut log = LogViewer::new(100);
2230 let line = "café résumé café";
2231 log.push(line);
2232
2233 let config = SearchConfig {
2234 mode: SearchMode::Literal,
2235 case_sensitive: false,
2236 context_lines: 0,
2237 };
2238 let count = log.search_with_config("café", config);
2239 assert_eq!(count, 1);
2240
2241 let expected: Vec<(usize, usize)> = search_exact(line, "café")
2242 .into_iter()
2243 .map(|r| (r.range.start, r.range.end))
2244 .collect();
2245 let ranges = log.highlight_ranges_for_line(0).expect("match ranges");
2246 assert_eq!(ranges, expected.as_slice());
2247 }
2248
2249 #[test]
2250 fn test_search_highlight_ranges_stable_after_push() {
2251 let mut log = LogViewer::new(100);
2252 log.push("Alpha beta ALPHA beta alpha");
2253
2254 let config = SearchConfig {
2255 mode: SearchMode::Literal,
2256 case_sensitive: false,
2257 context_lines: 0,
2258 };
2259 log.search_with_config("alpha", config);
2260 let before = log
2261 .highlight_ranges_for_line(0)
2262 .expect("match ranges")
2263 .to_vec();
2264
2265 log.push("no match here");
2266 let after = log
2267 .highlight_ranges_for_line(0)
2268 .expect("match ranges")
2269 .to_vec();
2270
2271 assert_eq!(before, after);
2272 }
2273
2274 #[cfg(feature = "regex-search")]
2275 #[test]
2276 fn test_search_regex_basic() {
2277 let mut log = LogViewer::new(100);
2278 log.push("error: code 42");
2279 log.push("error: code 99");
2280 log.push("info: all good");
2281 log.push("error: code 7");
2282
2283 let config = SearchConfig {
2284 mode: SearchMode::Regex,
2285 case_sensitive: true,
2286 context_lines: 0,
2287 };
2288 let count = log.search_with_config(r"error: code \d+", config);
2289 assert_eq!(count, 3);
2290 }
2291
2292 #[cfg(feature = "regex-search")]
2293 #[test]
2294 fn test_search_regex_invalid_pattern() {
2295 let mut log = LogViewer::new(100);
2296 log.push("something");
2297
2298 let config = SearchConfig {
2299 mode: SearchMode::Regex,
2300 case_sensitive: true,
2301 context_lines: 0,
2302 };
2303 let count = log.search_with_config(r"(unclosed", config);
2305 assert_eq!(count, 0);
2306 assert!(log.search_info().is_none());
2307 }
2308
2309 #[test]
2310 fn test_search_highlight_ranges() {
2311 let mut log = LogViewer::new(100);
2312 log.push("foo bar foo baz foo");
2313
2314 let count = log.search("foo");
2315 assert_eq!(count, 1);
2316
2317 let ranges = log.highlight_ranges_for_line(0);
2318 assert!(ranges.is_some());
2319 let ranges = ranges.unwrap();
2320 assert_eq!(ranges.len(), 3);
2321 assert_eq!(ranges[0], (0, 3));
2322 assert_eq!(ranges[1], (8, 11));
2323 assert_eq!(ranges[2], (16, 19));
2324 }
2325
2326 #[test]
2327 fn test_search_context_lines() {
2328 let mut log = LogViewer::new(100);
2329 for i in 0..10 {
2330 log.push(format!("line {}", i));
2331 }
2332
2333 let config = SearchConfig {
2334 mode: SearchMode::Literal,
2335 case_sensitive: true,
2336 context_lines: 1,
2337 };
2338 let count = log.search_with_config("line 5", config);
2340 assert_eq!(count, 1);
2341
2342 let ctx = log.context_line_indices();
2343 assert!(ctx.is_some());
2344 let ctx = ctx.unwrap();
2345 assert!(ctx.contains(&4));
2347 assert!(ctx.contains(&5));
2348 assert!(ctx.contains(&6));
2349 assert!(!ctx.contains(&3));
2350 assert!(!ctx.contains(&7));
2351 }
2352
2353 #[test]
2354 fn test_search_incremental_with_config() {
2355 let mut log = LogViewer::new(100);
2356 log.push("Hello World");
2357
2358 let config = SearchConfig {
2359 mode: SearchMode::Literal,
2360 case_sensitive: false,
2361 context_lines: 0,
2362 };
2363 let count = log.search_with_config("hello", config);
2364 assert_eq!(count, 1);
2365
2366 log.push("HELLO again");
2368 assert_eq!(log.search_info(), Some((1, 2)));
2369
2370 log.push("goodbye");
2372 assert_eq!(log.search_info(), Some((1, 2)));
2373 }
2374
2375 #[test]
2376 fn test_search_mode_switch() {
2377 let mut log = LogViewer::new(100);
2378 log.push("error 42");
2379 log.push("error 99");
2380 log.push("info ok");
2381
2382 let count = log.search("error");
2384 assert_eq!(count, 2);
2385
2386 let config = SearchConfig {
2388 mode: SearchMode::Literal,
2389 case_sensitive: false,
2390 context_lines: 0,
2391 };
2392 let count = log.search_with_config("ERROR", config);
2393 assert_eq!(count, 2);
2394
2395 let config = SearchConfig {
2397 mode: SearchMode::Literal,
2398 case_sensitive: true,
2399 context_lines: 0,
2400 };
2401 let count = log.search_with_config("ERROR", config);
2402 assert_eq!(count, 0);
2403 }
2404
2405 #[test]
2406 fn test_search_empty_query() {
2407 let mut log = LogViewer::new(100);
2408 log.push("something");
2409
2410 let count = log.search("");
2411 assert_eq!(count, 0);
2412 assert!(log.search_info().is_none());
2413
2414 let config = SearchConfig::default();
2415 let count = log.search_with_config("", config);
2416 assert_eq!(count, 0);
2417 assert!(log.search_info().is_none());
2418 }
2419
2420 #[test]
2421 fn test_highlight_ranges_within_bounds() {
2422 let mut log = LogViewer::new(100);
2423 let lines = [
2424 "short",
2425 "hello world hello",
2426 "café résumé café",
2427 "🌍 emoji 🌍",
2428 "",
2429 ];
2430 for line in &lines {
2431 log.push(*line);
2432 }
2433
2434 log.search("hello");
2435
2436 for match_idx in 0..log.line_count() {
2438 if let Some(ranges) = log.highlight_ranges_for_line(match_idx)
2439 && let Some(item) = log.virt.get(match_idx)
2440 {
2441 let plain = item.to_plain_text();
2442 for &(start, end) in ranges {
2443 assert!(
2444 start <= end,
2445 "Invalid range: start={} > end={} on line {}",
2446 start,
2447 end,
2448 match_idx
2449 );
2450 assert!(
2451 end <= plain.len(),
2452 "Out of bounds: end={} > len={} on line {}",
2453 end,
2454 plain.len(),
2455 match_idx
2456 );
2457 }
2458 }
2459 }
2460 }
2461
2462 #[test]
2463 fn test_search_match_rate_hint() {
2464 let mut log = LogViewer::new(100);
2465 log.set_filter(Some("x"));
2466 log.push("x match");
2467 log.search("match");
2468 log.push("x match again");
2469 log.push("x no");
2470
2471 let rate = log.search_match_rate_hint();
2473 assert!(rate > 0.0);
2474 assert!(rate <= 1.0);
2475 }
2476
2477 #[test]
2478 fn test_large_scrollback_eviction_and_scroll_bounds() {
2479 let mut log = LogViewer::new(1_000);
2480 log.virt.set_visible_count(25);
2481
2482 for i in 0..5_000 {
2483 log.push(format!("line {}", i));
2484 }
2485
2486 assert_eq!(log.line_count(), 1_000);
2487
2488 let first = log.virt.get(0).expect("first line");
2489 assert_eq!(first.lines()[0].to_plain_text(), "line 4000");
2490
2491 let last = log
2492 .virt
2493 .get(log.line_count().saturating_sub(1))
2494 .expect("last line");
2495 assert_eq!(last.lines()[0].to_plain_text(), "line 4999");
2496
2497 log.scroll_to_top();
2498 assert!(!log.auto_scroll_enabled());
2499
2500 log.scroll_down(10_000);
2501 assert!(log.is_at_bottom());
2502 assert!(log.auto_scroll_enabled());
2503
2504 let max_offset = log.line_count().saturating_sub(log.virt.visible_count());
2505 assert!(log.virt.scroll_offset() <= max_offset);
2506 }
2507
2508 #[test]
2509 fn test_large_scrollback_render_top_and_bottom_lines() {
2510 let mut log = LogViewer::new(1_000);
2511 log.virt.set_visible_count(3);
2512 for i in 0..5_000 {
2513 log.push(format!("line {}", i));
2514 }
2515
2516 let mut pool = GraphemePool::new();
2517 let mut state = LogViewerState::default();
2518
2519 log.scroll_to_top();
2520 let mut frame = Frame::new(20, 3, &mut pool);
2521 log.render(Rect::new(0, 0, 20, 3), &mut frame, &mut state);
2522 let top_line = line_text(&frame, 0, 20);
2523 assert!(
2524 top_line.trim_end().starts_with("line 4000"),
2525 "expected top line to start with line 4000, got: {top_line:?}"
2526 );
2527
2528 log.scroll_to_bottom();
2529 let mut frame = Frame::new(20, 3, &mut pool);
2530 log.render(Rect::new(0, 0, 20, 3), &mut frame, &mut state);
2531 let bottom_line = line_text(&frame, 2, 20);
2532 assert!(
2533 bottom_line.trim_end().starts_with("line 4999"),
2534 "expected bottom line to start with line 4999, got: {bottom_line:?}"
2535 );
2536 }
2537
2538 #[test]
2539 fn test_filtered_autoscroll_respects_manual_position() {
2540 let mut log = LogViewer::new(200);
2541 log.virt.set_visible_count(2);
2542
2543 log.push("match 1");
2544 log.push("skip");
2545 log.push("match 2");
2546 log.push("match 3");
2547 log.push("skip again");
2548 log.push("match 4");
2549 log.push("match 5");
2550
2551 log.set_filter(Some("match"));
2552 assert!(log.is_at_bottom());
2553
2554 log.scroll_up(2);
2555 let offset_before = log.filtered_scroll_offset;
2556 assert!(!log.is_at_bottom());
2557
2558 log.push("match 6");
2559 assert_eq!(log.filtered_scroll_offset, offset_before);
2560
2561 log.scroll_to_bottom();
2562 let offset_at_bottom = log.filtered_scroll_offset;
2563 log.push("match 7");
2564 assert!(log.filtered_scroll_offset >= offset_at_bottom);
2565 assert!(log.is_at_bottom());
2566 }
2567
2568 #[test]
2569 fn link_retention_builder_preserves_text_styles_and_search_state() {
2570 let mut log = LogViewer::new(10);
2571 for number in 0..4 {
2572 log.push(FtuiText::from_spans([
2573 Span::styled(format!("match {number}"), Style::new().bold())
2574 .link(format!("https://example.com/{number}")),
2575 Span::styled(" plain", Style::new().italic()),
2576 ]));
2577 }
2578 log.set_filter(Some("match"));
2579 assert_eq!(log.search("match"), 4);
2580 log.scroll_up(1);
2581 let original = log.clone();
2582 let log = log.retain_links_for_last_lines(2);
2583 assert_eq!(log.len(), 4);
2584 assert_eq!(log.filter, original.filter);
2585 assert_eq!(log.filtered_indices, original.filtered_indices);
2586 assert_eq!(log.filtered_scroll_offset, original.filtered_scroll_offset);
2587 assert_eq!(log.virt.scroll_offset(), original.virt.scroll_offset());
2588 assert_eq!(log.auto_scroll_enabled(), original.auto_scroll_enabled());
2589 assert_eq!(
2590 format!("{:?}", log.search),
2591 format!("{:?}", original.search)
2592 );
2593 assert_eq!(
2594 format!("{:?}", log.filter_stats),
2595 format!("{:?}", original.filter_stats)
2596 );
2597 for index in 0..4 {
2598 let before = original.virt.get(index).unwrap();
2599 let after = log.virt.get(index).unwrap();
2600 assert_eq!(after.to_plain_text(), format!("match {index} plain"));
2601 let before = before.lines()[0].spans();
2602 let after = after.lines()[0].spans();
2603 assert_eq!(after.len(), before.len());
2604 for (before, after) in before.iter().zip(after) {
2605 assert_eq!(after.content, before.content);
2606 assert_eq!(after.style, before.style);
2607 assert_eq!(
2608 after.link,
2609 if index < 2 { None } else { before.link.clone() }
2610 );
2611 }
2612 assert!(
2613 before[0].link.is_some(),
2614 "default retention keeps every link"
2615 );
2616 }
2617 }
2618
2619 #[test]
2620 fn link_retention_expires_each_multiline_push_and_survives_eviction() {
2621 let linked_line = |number| {
2622 Line::from_spans([
2623 Span::raw(format!("line {number}")).link(format!("https://example.com/{number}"))
2624 ])
2625 };
2626 let mut log = LogViewer::new(3).retain_links_for_last_lines(2);
2627 log.push(FtuiText::from_lines((0..5).map(linked_line)));
2628 assert_eq!(log.len(), 3);
2629 for index in 0..3 {
2630 let item = log.virt.get(index).unwrap();
2631 assert_eq!(item.to_plain_text(), format!("line {}", index + 2));
2632 assert_eq!(item.lines()[0].spans()[0].link.is_some(), index > 0);
2633 }
2634 let mut log = log.retain_links_for_last_lines(usize::MAX);
2635 assert!(
2636 log.virt.get(0).unwrap().lines()[0].spans()[0]
2637 .link
2638 .is_none()
2639 );
2640 log.push(FtuiText::from_line(linked_line(5)));
2641 for index in 0..3 {
2642 assert!(
2643 log.virt.get(index).unwrap().lines()[0].spans()[0]
2644 .link
2645 .is_some()
2646 );
2647 }
2648 let mut log = log.retain_links_for_last_lines(0);
2649 log.push(FtuiText::from_lines([linked_line(6), linked_line(7)]));
2650 for index in 0..3 {
2651 let item = log.virt.get(index).unwrap();
2652 assert_eq!(item.to_plain_text(), format!("line {}", index + 5));
2653 assert!(item.lines()[0].spans()[0].link.is_none());
2654 }
2655 log.clear();
2656 log.push(FtuiText::from_line(linked_line(8)));
2657 assert_eq!(log.len(), 1);
2658 assert!(
2659 log.virt.get(0).unwrap().lines()[0].spans()[0]
2660 .link
2661 .is_none()
2662 );
2663 let mut empty = LogViewer::new(0).retain_links_for_last_lines(0);
2664 empty.push(FtuiText::from_line(linked_line(9)));
2665 assert!(empty.is_empty());
2666 }
2667
2668 #[test]
2669 fn link_retention_keeps_all_ten_thousand_text_records_and_last_two_hundred_targets() {
2670 let mut log = LogViewer::new(10_000).retain_links_for_last_lines(200);
2671 for number in 0..10_001 {
2672 log.push(FtuiText::from_spans([
2673 Span::raw(format!("line {number}")).link(format!("https://example.com/{number}"))
2674 ]));
2675 if number >= 9_999 {
2676 assert_eq!(log.len(), 10_000);
2677 let first = number - 9_999;
2678 for index in 0..10_000 {
2679 let item = log.virt.get(index).unwrap();
2680 assert_eq!(item.to_plain_text(), format!("line {}", first + index));
2681 let link = item.lines()[0].spans()[0].link.as_deref();
2682 if index < 9_800 {
2683 assert_eq!(link, None);
2684 } else {
2685 let expected = format!("https://example.com/{}", first + index);
2686 assert_eq!(link, Some(expected.as_str()));
2687 }
2688 }
2689 }
2690 }
2691 }
2692
2693 #[test]
2694 fn first_hyperlink_from_default_registry_reaches_presenter() {
2695 use ftui_core::terminal_capabilities::TerminalCapabilities;
2696 use ftui_render::buffer::Buffer;
2697 use ftui_render::diff::BufferDiff;
2698 use ftui_render::link_registry::LinkRegistry;
2699 use ftui_render::presenter::Presenter;
2700 use ftui_text::Span;
2701
2702 let url = "https://example.com/first";
2703 let mut log = LogViewer::new(2);
2704 log.push(FtuiText::from_spans([
2705 Span::raw("first").link(url),
2706 Span::raw(" plain"),
2707 ]));
2708 log.push(FtuiText::from_spans([Span::raw("again").link(url)]));
2709 let mut pool = GraphemePool::new();
2710 let mut links = LinkRegistry::default();
2711 let mut frame = Frame::with_links(11, 2, &mut pool, &mut links);
2712 log.render(
2713 Rect::new(0, 0, 11, 2),
2714 &mut frame,
2715 &mut LogViewerState::default(),
2716 );
2717 assert_eq!(line_text(&frame, 0, 11), "first plain");
2718 assert_eq!(line_text(&frame, 1, 11), "again ");
2719 for y in 0..2 {
2720 for x in 0..11 {
2721 assert_eq!(
2722 frame.buffer.get(x, y).unwrap().attrs.link_id(),
2723 u32::from(x < 5),
2724 "link ownership at ({x}, {y})"
2725 );
2726 }
2727 }
2728 let buffer = frame.buffer;
2729 assert_eq!(links.len(), 1);
2730 assert_eq!(links.get(1), Some(url));
2731 let diff = BufferDiff::compute(&Buffer::new(11, 2), &buffer);
2732 for enabled in [true, false] {
2733 let mut caps = TerminalCapabilities::basic();
2734 caps.osc8_hyperlinks = enabled;
2735 let mut presenter = Presenter::new(Vec::new(), caps);
2736 presenter
2737 .present_with_pool(&buffer, &diff, Some(&pool), Some(&links))
2738 .unwrap();
2739 let output = String::from_utf8(presenter.into_inner().unwrap()).unwrap();
2740 if enabled {
2741 assert!(
2742 output.contains("\x1b]8;;https://example.com/first\x07first\x1b]8;;\x07 plain")
2743 );
2744 assert!(output.contains("\x1b]8;;https://example.com/first\x07again\x1b]8;;\x07"));
2745 assert_eq!(output.matches(url).count(), 2);
2746 } else {
2747 assert!(!output.contains("\x1b]8;"));
2748 assert!(output.contains("first plain"));
2749 assert!(output.contains("again"));
2750 }
2751 }
2752 }
2753
2754 #[test]
2755 fn test_markup_parsing_preserves_spans() {
2756 let mut log = LogViewer::new(100);
2757 let text = ftui_text::markup::parse_markup("[bold]Hello[/bold] [fg=red]world[/fg]!")
2758 .expect("markup parse failed");
2759 log.push(text);
2760
2761 let item = log.virt.get(0).expect("log line");
2762 let line = &item.lines()[0];
2763 assert_eq!(line.to_plain_text(), "Hello world!");
2764
2765 let spans = line.spans();
2766 assert!(spans.iter().any(|span| span.style.is_some()));
2767 assert!(spans.iter().any(|span| {
2768 span.style
2769 .and_then(|style| style.attrs)
2770 .is_some_and(|attrs| attrs.contains(TextStyleFlags::BOLD))
2771 }));
2772 }
2773
2774 #[test]
2775 fn test_markup_renders_bold_cells() {
2776 let mut log = LogViewer::new(10);
2777 let text = ftui_text::markup::parse_markup("[bold]Hello[/bold] world")
2778 .expect("markup parse failed");
2779 log.push(text);
2780
2781 let mut pool = GraphemePool::new();
2782 let mut frame = Frame::new(16, 1, &mut pool);
2783 let mut state = LogViewerState::default();
2784 log.render(Rect::new(0, 0, 16, 1), &mut frame, &mut state);
2785
2786 let rendered = line_text(&frame, 0, 16);
2787 assert!(rendered.trim_end().starts_with("Hello world"));
2788 for x in 0..5 {
2789 let cell = frame.buffer.get(x, 0).expect("cell");
2790 assert!(
2791 cell.attrs.has_flag(RenderStyleFlags::BOLD),
2792 "expected bold at x={x}, attrs={:?}",
2793 cell.attrs.flags()
2794 );
2795 }
2796 }
2797
2798 #[test]
2799 fn test_toggle_follow_disables_autoscroll_on_push() {
2800 let mut log = LogViewer::new(100);
2801 log.virt.set_visible_count(3);
2802 for i in 0..5 {
2803 log.push(format!("line {}", i));
2804 }
2805 assert!(log.is_at_bottom());
2806
2807 log.toggle_follow();
2808 assert!(!log.auto_scroll_enabled());
2809
2810 log.push("new line");
2811 assert!(!log.auto_scroll_enabled());
2812 assert!(!log.is_at_bottom());
2813 }
2814
2815 #[test]
2816 fn test_search_match_rate_hint_ratio() {
2817 let mut log = LogViewer::new(100);
2818 assert_eq!(log.search_match_rate_hint(), 0.0);
2819
2820 log.set_filter(Some("ERR"));
2821 log.search("ERR");
2822
2823 log.push("ERR one");
2824 log.push("INFO skip");
2825 log.push("ERR two");
2826 log.push("WARN skip");
2827
2828 assert_eq!(log.filter_stats().incremental_checks, 4);
2829 assert_eq!(log.filter_stats().incremental_search_checks, 2);
2830 assert_eq!(log.filter_stats().incremental_search_matches, 2);
2831 assert_eq!(log.search_match_rate_hint(), 1.0);
2832 }
2833
2834 #[test]
2835 fn test_render_char_wrap_splits_lines() {
2836 let mut log = LogViewer::new(10).wrap_mode(LogWrapMode::CharWrap);
2837 log.push("abcdefghij");
2838
2839 let mut pool = GraphemePool::new();
2840 let mut frame = Frame::new(5, 3, &mut pool);
2841 let mut state = LogViewerState::default();
2842 log.render(Rect::new(0, 0, 5, 3), &mut frame, &mut state);
2843
2844 assert_eq!(line_text(&frame, 0, 5), "abcde");
2845 assert_eq!(line_text(&frame, 1, 5), "fghij");
2846 }
2847
2848 #[test]
2849 fn test_render_scroll_indicator_when_not_at_bottom() {
2850 let mut log = LogViewer::new(100);
2851 for i in 0..5 {
2852 log.push(format!("line {}", i));
2853 }
2854
2855 log.scroll_to_top();
2856
2857 let mut pool = GraphemePool::new();
2858 let mut frame = Frame::new(10, 2, &mut pool);
2859 let mut state = LogViewerState::default();
2860 log.render(Rect::new(0, 0, 10, 2), &mut frame, &mut state);
2861
2862 let indicator = " 3 ";
2863 let bottom_line = line_text(&frame, 1, 10);
2864 assert_eq!(&bottom_line[7..10], indicator);
2865 }
2866
2867 #[test]
2868 fn test_render_search_indicator_when_active() {
2869 let mut log = LogViewer::new(100);
2870 for i in 0..5 {
2871 log.push(format!("line {}", i));
2872 }
2873 log.search("line");
2874
2875 let mut pool = GraphemePool::new();
2876 let mut frame = Frame::new(12, 2, &mut pool);
2877 let mut state = LogViewerState::default();
2878 log.render(Rect::new(0, 0, 12, 2), &mut frame, &mut state);
2879
2880 let indicator = " 1/5 ";
2881 let bottom_line = line_text(&frame, 1, 12);
2882 assert_eq!(&bottom_line[0..indicator.len()], indicator);
2883 }
2884
2885 #[test]
2886 fn test_search_ascii_case_insensitive_ranges_long_needle() {
2887 let ranges = search_ascii_case_insensitive_ranges("hi", "hello");
2888 assert!(ranges.is_empty());
2889 }
2890
2891 #[test]
2892 fn test_search_ascii_case_insensitive_ranges_large_work_fallback() {
2893 let mut haystack = "a".repeat(500);
2894 haystack.push_str("HELLO");
2895 haystack.push_str(&"b".repeat(500));
2896
2897 let ranges = search_ascii_case_insensitive_ranges(&haystack, "hello");
2898 assert_eq!(ranges, vec![(500, 505)]);
2899 }
2900
2901 #[test]
2902 fn wrapped_lines_have_variable_heights_in_fenwick_index() {
2903 let mut log = LogViewer::new(100).wrap_mode(LogWrapMode::CharWrap);
2904 log.push("a".repeat(10));
2905 log.push("b".repeat(100));
2906 log.push("c".repeat(250));
2907 log.measure_heights(40);
2908
2909 assert_eq!(log.offset_of_item(0), 0);
2910 assert_eq!(log.offset_of_item(1), 1);
2911 assert_eq!(log.offset_of_item(2), 4);
2912 assert_eq!(log.offset_of_item(3), 11);
2913
2914 let mut pool = GraphemePool::new();
2915 let mut frame = Frame::new(40, 20, &mut pool);
2916 let mut state = LogViewerState::default();
2917 log.render(Rect::new(0, 0, 40, 20), &mut frame, &mut state);
2918 assert_eq!(state.offset_of_item(0), 0);
2919 assert_eq!(state.offset_of_item(1), 1);
2920 assert_eq!(state.offset_of_item(2), 4);
2921 assert_eq!(state.offset_of_item(3), 11);
2922 }
2923}