1use std::collections::BTreeSet;
59use std::ops::Range;
60
61use crate::app_link::AppHandle;
62use egui::{
63 Align, Color32, FontId, Layout, Rect, Response, RichText, Role, TextStyle, Ui, UiBuilder, pos2,
64 vec2,
65};
66use egui_pop_core::a11y;
67use egui_pop_core::strings::{tr, tr_args, tr_with};
68use egui_pop_core::theme::{LogPalette, Tokens};
69use egui_pop_core::widgets::ToggleChip;
70
71use crate::list::Signal;
72use crate::select::Mode;
73use crate::strings as s;
74use crate::table::{Column, DataTable, TableRows, TableState};
75use crate::timeline::{TimeScale, TimelineState};
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
80pub enum Level {
81 Trace,
82 Debug,
83 Info,
84 Warn,
85 Error,
86 Critical,
87}
88
89impl Level {
90 pub const ALL: [Level; 6] = [
92 Level::Trace,
93 Level::Debug,
94 Level::Info,
95 Level::Warn,
96 Level::Error,
97 Level::Critical,
98 ];
99
100 pub fn name(self) -> &'static str {
102 match self {
103 Level::Trace => "TRACE",
104 Level::Debug => "DEBUG",
105 Level::Info => "INFO",
106 Level::Warn => "WARN",
107 Level::Error => "ERROR",
108 Level::Critical => "CRITICAL",
109 }
110 }
111
112 pub fn parse(name: &str) -> Option<Level> {
114 Some(match name.trim().to_ascii_lowercase().as_str() {
115 "trace" => Level::Trace,
116 "debug" => Level::Debug,
117 "info" => Level::Info,
118 "warn" | "warning" => Level::Warn,
119 "error" | "err" => Level::Error,
120 "critical" | "crit" | "fatal" => Level::Critical,
121 _ => return None,
122 })
123 }
124
125 pub fn color(self, palette: &LogPalette) -> Color32 {
127 palette.levels()[self as usize]
128 }
129}
130
131#[derive(Clone, Debug, PartialEq)]
134pub struct LogEntry {
135 pub time: f64,
138 pub entity: String,
140 pub level: Level,
141 pub body: String,
143}
144
145impl LogEntry {
146 pub fn new(
147 time: f64,
148 entity: impl Into<String>,
149 level: Level,
150 body: impl Into<String>,
151 ) -> Self {
152 Self {
153 time,
154 entity: entity.into(),
155 level,
156 body: body.into(),
157 }
158 }
159}
160
161pub trait LogSource {
165 fn len(&self) -> usize;
166
167 fn is_empty(&self) -> bool {
168 self.len() == 0
169 }
170
171 fn time(&self, index: usize) -> f64;
172 fn entity(&self, index: usize) -> &str;
173 fn level(&self, index: usize) -> Level;
174 fn body(&self, index: usize) -> &str;
175}
176
177impl LogSource for [LogEntry] {
178 fn len(&self) -> usize {
179 <[LogEntry]>::len(self)
180 }
181
182 fn time(&self, index: usize) -> f64 {
183 self[index].time
184 }
185
186 fn entity(&self, index: usize) -> &str {
187 &self[index].entity
188 }
189
190 fn level(&self, index: usize) -> Level {
191 self[index].level
192 }
193
194 fn body(&self, index: usize) -> &str {
195 &self[index].body
196 }
197}
198
199impl LogSource for Vec<LogEntry> {
200 fn len(&self) -> usize {
201 self.as_slice().len()
202 }
203
204 fn time(&self, index: usize) -> f64 {
205 self[index].time
206 }
207
208 fn entity(&self, index: usize) -> &str {
209 &self[index].entity
210 }
211
212 fn level(&self, index: usize) -> Level {
213 self[index].level
214 }
215
216 fn body(&self, index: usize) -> &str {
217 &self[index].body
218 }
219}
220
221#[derive(Clone, Debug, PartialEq)]
223struct FilterKey {
224 levels: [bool; 6],
225 text: String,
227}
228
229#[derive(Debug)]
232pub struct TextLogState {
233 table: TableState<usize>,
234 levels: [bool; 6],
235 text: String,
236 follow: bool,
237 expanded: BTreeSet<usize>,
238 rows: Vec<usize>,
240 scanned: usize,
242 counts: [usize; 6],
244 key: Option<FilterKey>,
245 cursor_entry: Option<usize>,
247 cursor_rows: Vec<usize>,
249 moved_here: bool,
252 reveal_end: bool,
254 at_end: bool,
256}
257
258impl Default for TextLogState {
259 fn default() -> Self {
260 Self {
261 table: TableState::new(),
262 levels: [true; 6],
263 text: String::new(),
264 follow: true,
265 expanded: BTreeSet::new(),
266 rows: Vec::new(),
267 scanned: 0,
268 counts: [0; 6],
269 key: None,
270 cursor_entry: None,
271 cursor_rows: Vec::new(),
272 moved_here: false,
273 reveal_end: false,
274 at_end: true,
275 }
276 }
277}
278
279impl TextLogState {
280 pub fn new() -> Self {
281 Self::default()
282 }
283
284 pub fn level_shown(&self, level: Level) -> bool {
286 self.levels[level as usize]
287 }
288
289 pub fn set_level_shown(&mut self, level: Level, on: bool) {
291 self.levels[level as usize] = on;
292 }
293
294 pub fn filter(&self) -> &str {
296 &self.text
297 }
298
299 pub fn set_filter(&mut self, text: impl Into<String>) {
302 self.text = text.into();
303 }
304
305 pub fn follow(&self) -> bool {
307 self.follow
308 }
309
310 pub fn set_follow(&mut self, on: bool) {
312 if on && !self.follow {
313 self.reveal_end = true;
314 }
315 self.follow = on;
316 }
317
318 pub fn is_expanded(&self, index: usize) -> bool {
320 self.expanded.contains(&index)
321 }
322
323 pub fn set_expanded(&mut self, index: usize, on: bool) {
325 if on {
326 self.expanded.insert(index);
327 } else {
328 self.expanded.remove(&index);
329 }
330 }
331
332 pub fn shown(&self) -> &[usize] {
334 &self.rows
335 }
336
337 pub fn count(&self, level: Level) -> usize {
339 self.counts[level as usize]
340 }
341
342 pub fn refilter(&mut self) {
346 self.key = None;
347 }
348
349 pub fn table(&self) -> &TableState<usize> {
352 &self.table
353 }
354
355 fn update(&mut self, source: &dyn LogSource, keep: Option<&dyn Fn(usize) -> bool>) {
358 let key = FilterKey {
359 levels: self.levels,
360 text: self.text.to_lowercase(),
361 };
362 let len = source.len();
363 if self.key.as_ref() != Some(&key) || len < self.scanned {
364 self.rows.clear();
365 self.scanned = 0;
366 self.counts = [0; 6];
367 self.expanded.retain(|&i| i < len);
368 }
369 for i in self.scanned..len {
370 if keep.is_some_and(|keep| !keep(i)) {
371 continue;
372 }
373 if !key.text.is_empty()
374 && !contains_folded(source.body(i), &key.text)
375 && !contains_folded(source.entity(i), &key.text)
376 {
377 continue;
378 }
379 let level = source.level(i) as usize;
380 self.counts[level] += 1;
381 if key.levels[level] {
382 self.rows.push(i);
383 }
384 }
385 self.scanned = len;
386 self.key = Some(key);
387 }
388
389 fn cursor_range(&self, source: &dyn LogSource, cursor: Option<f64>) -> Range<usize> {
392 let Some(t) = cursor.filter(|t| t.is_finite()) else {
393 return 0..0;
394 };
395 let end = self.rows.partition_point(|&i| source.time(i) <= t);
396 if end == 0 {
397 return 0..0;
398 }
399 let at = source.time(self.rows[end - 1]);
400 let start = self.rows[..end].partition_point(|&i| source.time(i) < at);
401 start..end
402 }
403}
404
405fn contains_folded(text: &str, needle: &str) -> bool {
407 if needle.is_empty() {
408 true
409 } else if text.is_ascii() && needle.is_ascii() {
410 text.as_bytes()
411 .windows(needle.len())
412 .any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
413 } else {
414 text.to_lowercase().contains(needle)
415 }
416}
417
418pub fn format_time(scale: Option<&TimeScale>, time: f64) -> String {
421 match scale {
422 Some(scale) => scale.format(time),
423 None if time.fract() == 0.0 && time.abs() < 1e15 => format!("{}", time as i64),
424 None => format!("{time:.3}"),
425 }
426}
427
428#[derive(Debug)]
430#[non_exhaustive]
431pub struct TextLogOutput {
432 pub response: Response,
434 pub cursor_moved: Option<f64>,
437 pub picked: Option<usize>,
439 pub hovered: Option<usize>,
441 pub following: bool,
443 pub shown: usize,
445 pub total: usize,
446}
447
448type KeepFn<'a> = dyn Fn(usize) -> bool + 'a;
451
452pub struct TextLog<'a> {
454 id: String,
455 source: &'a dyn LogSource,
456 label: Option<String>,
457 time_cursor: Option<f64>,
458 timeline: Option<&'a mut TimelineState>,
459 scale: Option<TimeScale>,
460 keep: Option<&'a KeepFn<'a>>,
461 highlight_entity: Option<&'a str>,
462 height: Option<f32>,
463 toolbar: bool,
464 reveal_cursor: bool,
465 app: Option<&'a AppHandle>,
466}
467
468impl std::fmt::Debug for TextLog<'_> {
469 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
470 f.debug_struct("TextLog")
471 .field("id", &self.id)
472 .field("entries", &self.source.len())
473 .field("time_cursor", &self.time_cursor)
474 .finish_non_exhaustive()
475 }
476}
477
478impl<'a> TextLog<'a> {
479 pub fn new(id: impl Into<String>, source: &'a dyn LogSource) -> Self {
482 Self {
483 id: id.into(),
484 source,
485 label: None,
486 time_cursor: None,
487 timeline: None,
488 scale: None,
489 keep: None,
490 highlight_entity: None,
491 height: None,
492 toolbar: true,
493 reveal_cursor: true,
494 app: None,
495 }
496 }
497
498 pub fn label(mut self, label: impl Into<String>) -> Self {
500 self.label = Some(label.into());
501 self
502 }
503
504 pub fn time_cursor(mut self, time: Option<f64>) -> Self {
508 self.time_cursor = time;
509 self
510 }
511
512 pub fn timeline(mut self, state: &'a mut TimelineState) -> Self {
515 self.timeline = Some(state);
516 self
517 }
518
519 pub fn time_scale(mut self, scale: TimeScale) -> Self {
523 self.scale = Some(scale);
524 self
525 }
526
527 pub fn keep(mut self, keep: &'a KeepFn<'a>) -> Self {
531 self.keep = Some(keep);
532 self
533 }
534
535 pub fn highlight_entity(mut self, path: Option<&'a str>) -> Self {
538 self.highlight_entity = path;
539 self
540 }
541
542 pub fn height(mut self, height: f32) -> Self {
544 self.height = Some(height);
545 self
546 }
547
548 pub fn toolbar(mut self, on: bool) -> Self {
551 self.toolbar = on;
552 self
553 }
554
555 pub fn reveal_cursor(mut self, on: bool) -> Self {
558 self.reveal_cursor = on;
559 self
560 }
561
562 #[cfg(feature = "api")]
564 pub fn app(mut self, app: &'a AppHandle) -> Self {
565 self.app = Some(app);
566 self
567 }
568
569 pub fn show(self, ui: &mut Ui, state: &mut TextLogState) -> TextLogOutput {
570 let TextLog {
571 id,
572 source,
573 label,
574 time_cursor,
575 mut timeline,
576 scale,
577 keep,
578 highlight_entity,
579 height,
580 toolbar,
581 reveal_cursor,
582 app,
583 } = self;
584 let ctx = ui.ctx().clone();
585 let label = label.unwrap_or_else(|| tr(&ctx, &s::TEXT_LOG));
586 let top = ui.cursor().top();
587 if toolbar {
588 toolbar_ui(ui, state, &id);
589 }
590 state.update(source, keep);
591
592 let cursor = timeline.as_ref().map(|t| t.playhead).or(time_cursor);
594 let scale = timeline.as_ref().map(|t| t.scale).or(scale);
595 let range = state.cursor_range(source, cursor);
596 let at_cursor: Vec<usize> = state.rows[range.clone()].to_vec();
597 let moved_here = std::mem::take(&mut state.moved_here);
598 if at_cursor != state.cursor_rows {
599 if reveal_cursor && !moved_here && !range.is_empty() {
600 state.table.reveal(range.end - 1);
601 }
602 state.cursor_rows = at_cursor.clone();
603 }
604 let entry = state
605 .cursor_entry
606 .filter(|e| at_cursor.contains(e))
607 .or(at_cursor.last().copied());
608 state.cursor_entry = entry;
609 if state.table.selection().keys() != at_cursor.as_slice()
610 || state.table.selection().cursor() != entry.as_ref()
611 {
612 state.table.set_selection(at_cursor, entry);
613 }
614 if std::mem::take(&mut state.reveal_end) && !state.rows.is_empty() {
615 state.table.reveal(state.rows.len() - 1);
616 }
617
618 let t = Tokens::of(&ctx);
620 let body_font = TextStyle::Body.resolve(ui.style());
621 let line_h = ui.fonts_mut(|f| f.row_height(&body_font));
622 let row_h = crate::rows::height(ui);
623 let mut extra: Vec<(usize, f32)> = Vec::new();
624 let mut total_extra = 0.0;
625 for &e in &state.expanded {
626 let Ok(pos) = state.rows.binary_search(&e) else {
627 continue;
628 };
629 let lines = source.body(e).lines().count().max(1);
630 if lines > 1 {
631 total_extra += (lines - 1) as f32 * line_h;
632 extra.push((pos, total_extra));
633 }
634 }
635
636 let columns = [
637 Column::new("time", tr(&ctx, &s::TEXT_LOG_TIME))
638 .width(96.0)
639 .sortable(false),
640 Column::new("entity", tr(&ctx, &s::TEXT_LOG_ENTITY))
641 .width(140.0)
642 .sortable(false),
643 Column::new("level", tr(&ctx, &s::TEXT_LOG_LEVEL))
644 .width(84.0)
645 .sortable(false),
646 Column::new("body", tr(&ctx, &s::TEXT_LOG_BODY))
647 .width(480.0)
648 .sortable(false),
649 ];
650 let mut rows = Rows {
651 source,
652 shown: &state.rows,
653 expanded: &state.expanded,
654 extra: &extra,
655 scale: scale.as_ref(),
656 palette: &t.palette.log,
657 muted: t.text.muted,
658 tint: t.accent.subtle,
659 highlight_entity,
660 mono: TextStyle::Monospace.resolve(ui.style()),
661 body_font,
662 row_h,
663 toggle: None,
664 hovered: None,
665 };
666 let mut table = DataTable::new(id, &columns)
667 .label(label)
668 .mode(Mode::Single)
669 .stick_to_bottom(state.follow);
670 #[cfg(feature = "api")]
671 if let Some(app) = app {
672 table = table.app(app);
673 }
674 #[cfg(not(feature = "api"))]
675 let _ = app;
676 if let Some(h) = height {
677 let used = ui.cursor().top() - top;
678 table = table.height((h - used).max(row_h * 2.0));
679 }
680 let out = table.show(ui, &mut state.table, &mut rows);
681 let toggle = rows.toggle.take();
682 let hovered = rows.hovered.take();
683 drop(rows);
684 if let Some(e) = toggle {
685 let on = !state.is_expanded(e);
686 state.set_expanded(e, on);
687 ctx.request_repaint();
688 }
689
690 let mut cursor_moved = None;
692 let mut picked = None;
693 for signal in &out.signals {
694 if let Signal::Select {
695 cursor: Some(e), ..
696 } = signal
697 && *e < source.len()
698 {
699 let time = source.time(*e);
700 picked = Some(*e);
701 state.cursor_entry = Some(*e);
702 state.moved_here = true;
703 cursor_moved = Some(match timeline.as_deref_mut() {
704 Some(tl) => {
705 tl.set_playhead(time);
706 tl.playhead
707 }
708 None => time,
709 });
710 ctx.request_repaint();
711 }
712 }
713 let len = state.rows.len();
714 state.at_end = len == 0 || out.visible_rows.end >= len;
715 TextLogOutput {
716 response: out.response,
717 cursor_moved,
718 picked,
719 hovered,
720 following: state.follow && state.at_end,
721 shown: len,
722 total: source.len(),
723 }
724 }
725}
726
727fn toolbar_ui(ui: &mut Ui, state: &mut TextLogState, id: &str) {
729 let ctx = ui.ctx().clone();
730 ui.horizontal_wrapped(|ui| {
731 for level in Level::ALL {
732 let mut on = state.level_shown(level);
733 let count = state.count(level);
734 let name = tr_args(&ctx, &s::TEXT_LOG_SHOW_LEVEL, &[("level", level.name())]);
735 let text = format!("{} {count}", level.name());
736 if ui.add(ToggleChip::new(&mut on, text).name(name)).changed() {
737 state.set_level_shown(level, on);
738 }
739 }
740 let hint = tr(&ctx, &s::TEXT_LOG_FILTER);
741 let mut text = state.filter().to_string();
742 let edit = ui.add(
743 egui::TextEdit::singleline(&mut text)
744 .id(egui::Id::unique(("egui_pop_views::text_log::filter", id)))
745 .hint_text(&hint)
746 .desired_width(160.0),
747 );
748 a11y::name(&edit, Role::SearchInput, &hint);
749 if edit.changed() {
750 state.set_filter(text);
751 }
752 let mut follow = state.follow();
753 let name = tr(&ctx, &s::TEXT_LOG_FOLLOW);
754 if ui.add(ToggleChip::new(&mut follow, name)).changed() {
755 state.set_follow(follow);
756 }
757 ui.weak(tr_with(
758 &ctx,
759 &s::TEXT_LOG_COUNT,
760 &[
761 ("count", (state.rows.len()).into()),
762 ("total", state.scanned.into()),
763 ],
764 ));
765 });
766}
767
768struct Rows<'a> {
770 source: &'a dyn LogSource,
771 shown: &'a [usize],
772 expanded: &'a BTreeSet<usize>,
773 extra: &'a [(usize, f32)],
776 scale: Option<&'a TimeScale>,
777 palette: &'a LogPalette,
778 muted: Color32,
779 tint: Color32,
780 highlight_entity: Option<&'a str>,
781 mono: FontId,
782 body_font: FontId,
783 row_h: f32,
784 toggle: Option<usize>,
786 hovered: Option<usize>,
787}
788
789impl Rows<'_> {
790 fn band(ui: &Ui, row_h: f32) -> Rect {
792 let max = ui.max_rect();
793 Rect::from_min_max(
794 pos2(ui.cursor().min.x, max.top()),
795 pos2(max.right(), max.top() + row_h.min(max.height())),
796 )
797 }
798}
799
800impl TableRows<usize> for Rows<'_> {
801 fn len(&self) -> usize {
802 self.shown.len()
803 }
804
805 fn key(&self, row: usize) -> usize {
806 self.shown[row]
807 }
808
809 fn label(&self, row: usize) -> String {
810 let e = self.shown[row];
811 let body = self.source.body(e);
812 format!(
813 "{} {} {} {}",
814 format_time(self.scale, self.source.time(e)),
815 self.source.level(e).name(),
816 self.source.entity(e),
817 body.lines().next().unwrap_or(body)
818 )
819 }
820
821 fn cell(&mut self, ui: &mut Ui, row: usize, column: usize, selected: bool) {
822 let e = self.shown[row];
823 if ui.rect_contains_pointer(ui.max_rect()) {
824 self.hovered = Some(e);
825 }
826 let band = Self::band(ui, self.row_h);
827 let muted = if selected {
828 ui.visuals().text_color()
829 } else {
830 self.muted
831 };
832 let mut child = ui.new_child(
833 UiBuilder::new()
834 .max_rect(band)
835 .layout(Layout::left_to_right(Align::Center)),
836 );
837 let ui = &mut child;
838 ui.style_mut().interaction.selectable_labels = false;
842 match column {
843 0 => {
844 let text = format_time(self.scale, self.source.time(e));
845 ui.label(RichText::new(text).font(self.mono.clone()).color(muted));
846 }
847 1 => {
848 let path = self.source.entity(e);
849 if self.highlight_entity == Some(path) {
850 ui.painter().rect_filled(ui.max_rect(), 0.0, self.tint);
851 }
852 ui.label(RichText::new(path).color(muted));
853 }
854 2 => {
855 let level = self.source.level(e);
856 let color = level.color(self.palette);
857 let galley = ui.painter().layout_no_wrap(
858 level.name().to_string(),
859 FontId::new(self.mono.size * 0.9, self.mono.family.clone()),
860 color,
861 );
862 let size = galley.size() + vec2(8.0, 2.0);
863 let (rect, _) = ui.allocate_exact_size(size, egui::Sense::hover());
864 ui.painter()
865 .rect_filled(rect, 3.0, color.gamma_multiply(0.16));
866 ui.painter()
867 .galley(rect.min + vec2(4.0, 1.0), galley, color);
868 }
869 _ => {
870 let body = self.source.body(e);
871 let mut lines = body.lines();
872 let first = lines.next().unwrap_or("");
873 let more = lines.count();
874 if more > 0 {
875 let open = self.expanded.contains(&e);
876 let name = if open {
877 tr(ui.ctx(), &s::TEXT_LOG_COLLAPSE)
878 } else {
879 tr_with(
880 ui.ctx(),
881 &s::TEXT_LOG_EXPAND,
882 &[("count", (more + 1).into())],
883 )
884 };
885 let r = disclosure(ui, open, self.body_font.size);
886 a11y::name(&r, Role::Button, &name);
887 if r.clicked() {
888 self.toggle = Some(e);
889 }
890 ui.label(RichText::new(first).font(self.body_font.clone()));
891 if open {
892 let rest: Vec<&str> = body.lines().skip(1).collect();
893 let color = ui.visuals().text_color();
894 let galley = ui.painter().layout_no_wrap(
895 rest.join("\n"),
896 self.body_font.clone(),
897 color,
898 );
899 let at = pos2(r.rect.right() + ui.spacing().item_spacing.x, band.bottom());
900 ui.painter().galley(at, galley, color);
902 } else {
903 ui.label(
904 RichText::new(tr_with(
905 ui.ctx(),
906 &s::TEXT_LOG_MORE,
907 &[("count", more.into())],
908 ))
909 .color(muted),
910 );
911 }
912 } else {
913 ui.label(RichText::new(first).font(self.body_font.clone()));
914 }
915 }
916 }
917 }
918
919 fn row_top(&self, row: usize, row_h: f32) -> f32 {
920 let before = self.extra.partition_point(|(pos, _)| *pos < row);
921 let extra = if before == 0 {
922 0.0
923 } else {
924 self.extra[before - 1].1
925 };
926 row as f32 * row_h + extra
927 }
928}
929
930fn disclosure(ui: &mut Ui, open: bool, size: f32) -> Response {
933 let (rect, r) = ui.allocate_exact_size(vec2(size, size), egui::Sense::click());
934 let color = if r.hovered() {
935 ui.visuals().strong_text_color()
936 } else {
937 ui.visuals().text_color()
938 };
939 let c = rect.center();
940 let h = size * 0.3;
941 let points = if open {
942 vec![
943 pos2(c.x - h, c.y - h * 0.6),
944 pos2(c.x + h, c.y - h * 0.6),
945 pos2(c.x, c.y + h * 0.7),
946 ]
947 } else {
948 vec![
949 pos2(c.x - h * 0.6, c.y - h),
950 pos2(c.x + h * 0.7, c.y),
951 pos2(c.x - h * 0.6, c.y + h),
952 ]
953 };
954 ui.painter().add(egui::Shape::convex_polygon(
955 points,
956 color,
957 egui::Stroke::NONE,
958 ));
959 r
960}