Skip to main content

egui_pop_views/
text_log.rs

1//! A text log view on the data table: a line per entry, its time, entity,
2//! level and body, filtered by level and by text, following the tail, and
3//! tied to a time cursor.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! Its design follows the text log view of the Rerun viewer
9//! (<https://rerun.io>, `re_view_text_log`, MIT OR Apache-2.0): the same
10//! four columns, the level in its colour (`palette.log.*`), the rows at
11//! the time cursor highlighted and brought into view when the cursor
12//! moves, a click on a row moving the time cursor to it. No Rerun code is
13//! used; the table is egui-pop's [`DataTable`] (on Rerun's `egui_table`).
14//!
15//! - **Columns**: the time, written in a timeline's scale
16//!   ([`TextLog::time_scale`], or a bound timeline's), else as a plain
17//!   number; the entity path; the level as a coloured chip; the body, its
18//!   first line, a multi-line body expanding to all its lines.
19//! - **Filters**: a toggle chip per level, each with its count, and a text
20//!   filter matching the body or the entity path, case aside.
21//! - **The tail**: with Follow on (the default), the last line stays in
22//!   view as lines come in; scrolled up, the view stays where it was, and
23//!   scrolled back to the end it follows again.
24//! - **The time cursor**: the rows at the latest time not after the
25//!   cursor ([`TextLog::time_cursor`], or a bound timeline's playhead,
26//!   [`TextLog::timeline`]) are the table's selection, drawn by the kit's
27//!   `table-row`; a click or the arrow keys move the cursor to a row's
28//!   time ([`TextLogOutput::cursor_moved`]; a bound timeline's playhead is
29//!   already there).
30//! - **Large logs**: only the rows in view are built, and the filter keeps
31//!   its result between passes, scanning only the entries added since
32//!   (a log grows at its end; [`TextLogState::refilter`] after anything
33//!   else changed).
34//!
35//! The application owns the entries ([`LogSource`], in time order) and
36//! keeps a [`TextLogState`].
37//!
38//! ```
39//! use egui_pop_views::text_log::{Level, LogEntry, TextLog, TextLogState};
40//!
41//! fn ui(ui: &mut egui::Ui, state: &mut TextLogState, log: &Vec<LogEntry>, now: &mut f64) {
42//!     let out = TextLog::new("app.log", log)
43//!         .label("Application log")
44//!         .time_cursor(Some(*now))
45//!         .show(ui, state);
46//!     if let Some(t) = out.cursor_moved {
47//!         *now = t;
48//!     }
49//! }
50//!
51//! let log = vec![
52//!     LogEntry::new(0.0, "/robot", Level::Info, "started"),
53//!     LogEntry::new(1.5, "/robot/arm", Level::Warn, "joint 2 near its limit"),
54//! ];
55//! # let _ = log;
56//! ```
57
58use 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/// How severe a log line is, from trace to critical: the six levels of
78/// the `palette.log.*` tokens, in their order.
79#[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    /// Every level, from trace to critical.
91    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    /// How the log writes it: `TRACE` to `CRITICAL`.
101    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    /// The level a name gives (`warn`, `WARNING`, `err`...), case aside.
113    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    /// Its colour among the theme's (`palette.log.<level>`).
126    pub fn color(self, palette: &LogPalette) -> Color32 {
127        palette.levels()[self as usize]
128    }
129}
130
131/// A log line, as an application may keep them ([`LogSource`] is
132/// implemented for a slice of them).
133#[derive(Clone, Debug, PartialEq)]
134pub struct LogEntry {
135    /// When it was logged, on the time cursor's axis (seconds on a
136    /// timeline).
137    pub time: f64,
138    /// The entity it was logged on, a path (`/robot/arm`).
139    pub entity: String,
140    pub level: Level,
141    /// Its text, perhaps on several lines.
142    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
161/// The entries a text log shows, in time order (an entry is never before
162/// the one ahead of it); the application owns them. Entries are named by
163/// their index, which stays theirs as the log grows at its end.
164pub 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/// What the filter was computed for.
222#[derive(Clone, Debug, PartialEq)]
223struct FilterKey {
224    levels: [bool; 6],
225    /// The text filter, lower case.
226    text: String,
227}
228
229/// A text log's state between passes: its filters, Follow, the bodies
230/// expanded, the table's own state and the filter's result.
231#[derive(Debug)]
232pub struct TextLogState {
233    table: TableState<usize>,
234    levels: [bool; 6],
235    text: String,
236    follow: bool,
237    expanded: BTreeSet<usize>,
238    /// The entries shown, by index, in order.
239    rows: Vec<usize>,
240    /// How many entries the filter has seen.
241    scanned: usize,
242    /// Per level, the entries matching the text filter.
243    counts: [usize; 6],
244    key: Option<FilterKey>,
245    /// The entry the cursor's rows put the table's cursor on.
246    cursor_entry: Option<usize>,
247    /// The rows at the time cursor at the last pass (entries).
248    cursor_rows: Vec<usize>,
249    /// This log moved the time cursor at the last pass: its rows are not
250    /// brought into view (the user is looking at them).
251    moved_here: bool,
252    /// The end to be brought into view (Follow turned on).
253    reveal_end: bool,
254    /// The last row was in view at the last pass.
255    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    /// Whether lines of `level` are shown (all are by default).
285    pub fn level_shown(&self, level: Level) -> bool {
286        self.levels[level as usize]
287    }
288
289    /// Shows or hides the lines of `level`.
290    pub fn set_level_shown(&mut self, level: Level, on: bool) {
291        self.levels[level as usize] = on;
292    }
293
294    /// The text filter (empty: none).
295    pub fn filter(&self) -> &str {
296        &self.text
297    }
298
299    /// Shows only the lines whose body or entity path holds `text`, case
300    /// aside.
301    pub fn set_filter(&mut self, text: impl Into<String>) {
302        self.text = text.into();
303    }
304
305    /// Whether Follow is on: the last line kept in view as lines come in.
306    pub fn follow(&self) -> bool {
307        self.follow
308    }
309
310    /// Turns Follow on (bringing the last line into view) or off.
311    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    /// Whether entry `index`'s body shows all its lines.
319    pub fn is_expanded(&self, index: usize) -> bool {
320        self.expanded.contains(&index)
321    }
322
323    /// Shows all the lines of entry `index`'s body, or its first one.
324    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    /// The entries shown at the last pass, by index, in order.
333    pub fn shown(&self) -> &[usize] {
334        &self.rows
335    }
336
337    /// How many entries of `level` match the text filter (shown or not).
338    pub fn count(&self, level: Level) -> usize {
339        self.counts[level as usize]
340    }
341
342    /// Filters again from the first entry at the next pass: after the
343    /// entries changed otherwise than by growing at their end, or the
344    /// application's own filter ([`TextLog::keep`]) changed.
345    pub fn refilter(&mut self) {
346        self.key = None;
347    }
348
349    /// The table's own state (its selection is the rows at the time
350    /// cursor).
351    pub fn table(&self) -> &TableState<usize> {
352        &self.table
353    }
354
355    /// Brings the filter up to date with `source`: from scratch when the
356    /// filter changed or the source shrank, else the new entries only.
357    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    /// The rows (positions in `rows`) at the time cursor: those at the
390    /// latest time not after it.
391    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
405/// `text` holds `needle` (lower case), case aside.
406fn 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
418/// How a time is written: in `scale`, else as a plain number (whole
419/// numbers without decimals: frame numbers).
420pub 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/// What [`TextLog::show`] returns.
429#[derive(Debug)]
430#[non_exhaustive]
431pub struct TextLogOutput {
432    /// The table, as one focusable widget.
433    pub response: Response,
434    /// A row was clicked or reached with the keys this pass: the time it
435    /// moves the cursor to. A bound timeline's playhead is already there.
436    pub cursor_moved: Option<f64>,
437    /// The entry of that row.
438    pub picked: Option<usize>,
439    /// The entry under the pointer.
440    pub hovered: Option<usize>,
441    /// Follow is on and the last line is in view.
442    pub following: bool,
443    /// How many lines are shown, of how many entries.
444    pub shown: usize,
445    pub total: usize,
446}
447
448/// Decides which entries the application shows, beside the log's own
449/// filters: `keep(index)`.
450type KeepFn<'a> = dyn Fn(usize) -> bool + 'a;
451
452/// The text log widget.
453pub 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    /// A text log named `id` (its table's id in steps and signals),
480    /// showing `source`.
481    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    /// Its accessible name (default: "Text log").
499    pub fn label(mut self, label: impl Into<String>) -> Self {
500        self.label = Some(label.into());
501        self
502    }
503
504    /// The time cursor, on the entries' time axis; the application passes
505    /// it every pass. The rows at the latest time not after it are
506    /// highlighted.
507    pub fn time_cursor(mut self, time: Option<f64>) -> Self {
508        self.time_cursor = time;
509        self
510    }
511
512    /// Follows a timeline: its playhead is the time cursor, its scale
513    /// writes the times, and a row picked moves the playhead.
514    pub fn timeline(mut self, state: &'a mut TimelineState) -> Self {
515        self.timeline = Some(state);
516        self
517    }
518
519    /// Writes the times in a timeline's scale (`1:02.500`, a timecode,
520    /// bars and beats); a bound timeline gives its own. Without one, a
521    /// time is a plain number.
522    pub fn time_scale(mut self, scale: TimeScale) -> Self {
523        self.scale = Some(scale);
524        self
525    }
526
527    /// The application's own filter, beside the log's: only the entries
528    /// for which `keep(index)` holds are shown. Call
529    /// [`TextLogState::refilter`] when its answers change.
530    pub fn keep(mut self, keep: &'a KeepFn<'a>) -> Self {
531        self.keep = Some(keep);
532        self
533    }
534
535    /// Tints the entity cell of the rows logged on `path` (an entity
536    /// selected or hovered elsewhere).
537    pub fn highlight_entity(mut self, path: Option<&'a str>) -> Self {
538        self.highlight_entity = path;
539        self
540    }
541
542    /// Its height, the filters included (default: what is available).
543    pub fn height(mut self, height: f32) -> Self {
544        self.height = Some(height);
545        self
546    }
547
548    /// Shows the level chips, the text filter and Follow above the table
549    /// (default: on).
550    pub fn toolbar(mut self, on: bool) -> Self {
551        self.toolbar = on;
552        self
553    }
554
555    /// Brings the rows at the time cursor into view when the cursor moves
556    /// elsewhere than from this log (default: on).
557    pub fn reveal_cursor(mut self, on: bool) -> Self {
558        self.reveal_cursor = on;
559        self
560    }
561
562    /// Runs its table's moments as steps of this application.
563    #[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        // The time cursor's rows are the table's selection.
593        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        // Rows expanded to all their lines, by position.
619        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        // A row picked moves the time cursor to its time.
691        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
727/// The level chips, the text filter and Follow, on one line.
728fn 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
768/// The rows the table draws: the entries the filters let through.
769struct Rows<'a> {
770    source: &'a dyn LogSource,
771    shown: &'a [usize],
772    expanded: &'a BTreeSet<usize>,
773    /// Rows taller than one line, by position, with the extra height of
774    /// them all up to and including each.
775    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    /// The entry whose body's disclosure was clicked.
785    toggle: Option<usize>,
786    hovered: Option<usize>,
787}
788
789impl Rows<'_> {
790    /// The band of a cell holding its first line.
791    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        // A selectable label senses clicks and sits above the row: a
839        // click on a time, an entity or a body would select its text
840        // instead of picking the row.
841        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                        // Under the first line, in the row's own height.
901                        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
930/// A body's disclosure: a small triangle, pointing down when open,
931/// right when folded, in the text's colour (strong under the pointer).
932fn 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}