tui_logger/widget/
standard.rs

1use crate::widget::logformatter::LogFormatter;
2use crate::widget::standard_formatter::LogStandardFormatter;
3use parking_lot::Mutex;
4use std::sync::Arc;
5
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::Style,
10    text::Line,
11    widgets::{Block, Widget},
12};
13
14use crate::widget::inner::LinePointer;
15use crate::{CircularBuffer, ExtLogRecord, TuiLoggerLevelOutput, TuiWidgetState, TUI_LOGGER};
16
17use super::inner::TuiWidgetInnerState;
18
19pub struct TuiLoggerWidget<'b> {
20    block: Option<Block<'b>>,
21    logformatter: Option<Box<dyn LogFormatter>>,
22    /// Base style of the widget
23    style: Style,
24    /// Level based style
25    style_error: Option<Style>,
26    style_warn: Option<Style>,
27    style_debug: Option<Style>,
28    style_trace: Option<Style>,
29    style_info: Option<Style>,
30    format_separator: char,
31    format_timestamp: Option<String>,
32    format_output_level: Option<TuiLoggerLevelOutput>,
33    format_output_target: bool,
34    format_output_file: bool,
35    format_output_line: bool,
36    state: Arc<Mutex<TuiWidgetInnerState>>,
37}
38impl<'b> Default for TuiLoggerWidget<'b> {
39    fn default() -> TuiLoggerWidget<'b> {
40        TuiLoggerWidget {
41            block: None,
42            logformatter: None,
43            style: Default::default(),
44            style_error: None,
45            style_warn: None,
46            style_debug: None,
47            style_trace: None,
48            style_info: None,
49            format_separator: ':',
50            format_timestamp: Some("%H:%M:%S".to_string()),
51            format_output_level: Some(TuiLoggerLevelOutput::Long),
52            format_output_target: true,
53            format_output_file: true,
54            format_output_line: true,
55            state: Arc::new(Mutex::new(TuiWidgetInnerState::new())),
56        }
57    }
58}
59impl<'b> TuiLoggerWidget<'b> {
60    pub fn block(mut self, block: Block<'b>) -> Self {
61        self.block = Some(block);
62        self
63    }
64    pub fn opt_formatter(mut self, formatter: Option<Box<dyn LogFormatter>>) -> Self {
65        self.logformatter = formatter;
66        self
67    }
68    pub fn formatter(mut self, formatter: Box<dyn LogFormatter>) -> Self {
69        self.logformatter = Some(formatter);
70        self
71    }
72    pub fn opt_style(mut self, style: Option<Style>) -> Self {
73        if let Some(s) = style {
74            self.style = s;
75        }
76        self
77    }
78    pub fn opt_style_error(mut self, style: Option<Style>) -> Self {
79        if style.is_some() {
80            self.style_error = style;
81        }
82        self
83    }
84    pub fn opt_style_warn(mut self, style: Option<Style>) -> Self {
85        if style.is_some() {
86            self.style_warn = style;
87        }
88        self
89    }
90    pub fn opt_style_info(mut self, style: Option<Style>) -> Self {
91        if style.is_some() {
92            self.style_info = style;
93        }
94        self
95    }
96    pub fn opt_style_trace(mut self, style: Option<Style>) -> Self {
97        if style.is_some() {
98            self.style_trace = style;
99        }
100        self
101    }
102    pub fn opt_style_debug(mut self, style: Option<Style>) -> Self {
103        if style.is_some() {
104            self.style_debug = style;
105        }
106        self
107    }
108    pub fn style(mut self, style: Style) -> Self {
109        self.style = style;
110        self
111    }
112    pub fn style_error(mut self, style: Style) -> Self {
113        self.style_error = Some(style);
114        self
115    }
116    pub fn style_warn(mut self, style: Style) -> Self {
117        self.style_warn = Some(style);
118        self
119    }
120    pub fn style_info(mut self, style: Style) -> Self {
121        self.style_info = Some(style);
122        self
123    }
124    pub fn style_trace(mut self, style: Style) -> Self {
125        self.style_trace = Some(style);
126        self
127    }
128    pub fn style_debug(mut self, style: Style) -> Self {
129        self.style_debug = Some(style);
130        self
131    }
132    pub fn opt_output_separator(mut self, opt_sep: Option<char>) -> Self {
133        if let Some(ch) = opt_sep {
134            self.format_separator = ch;
135        }
136        self
137    }
138    /// Separator character between field.
139    /// Default is ':'
140    pub fn output_separator(mut self, sep: char) -> Self {
141        self.format_separator = sep;
142        self
143    }
144    pub fn opt_output_timestamp(mut self, opt_fmt: Option<Option<String>>) -> Self {
145        if let Some(fmt) = opt_fmt {
146            self.format_timestamp = fmt;
147        }
148        self
149    }
150    /// The format string can be defined as described in
151    /// <https://docs.rs/chrono/0.4.19/chrono/format/strftime/index.html>
152    ///
153    /// If called with None, timestamp is not included in output.
154    ///
155    /// Default is %H:%M:%S
156    pub fn output_timestamp(mut self, fmt: Option<String>) -> Self {
157        self.format_timestamp = fmt;
158        self
159    }
160    pub fn opt_output_level(mut self, opt_fmt: Option<Option<TuiLoggerLevelOutput>>) -> Self {
161        if let Some(fmt) = opt_fmt {
162            self.format_output_level = fmt;
163        }
164        self
165    }
166    /// Possible values are
167    /// - TuiLoggerLevelOutput::Long        => DEBUG/TRACE/...
168    /// - TuiLoggerLevelOutput::Abbreviated => D/T/...
169    ///
170    /// If called with None, level is not included in output.
171    ///
172    /// Default is Long
173    pub fn output_level(mut self, level: Option<TuiLoggerLevelOutput>) -> Self {
174        self.format_output_level = level;
175        self
176    }
177    pub fn opt_output_target(mut self, opt_enabled: Option<bool>) -> Self {
178        if let Some(enabled) = opt_enabled {
179            self.format_output_target = enabled;
180        }
181        self
182    }
183    /// Enables output of target field of event
184    ///
185    /// Default is true
186    pub fn output_target(mut self, enabled: bool) -> Self {
187        self.format_output_target = enabled;
188        self
189    }
190    pub fn opt_output_file(mut self, opt_enabled: Option<bool>) -> Self {
191        if let Some(enabled) = opt_enabled {
192            self.format_output_file = enabled;
193        }
194        self
195    }
196    /// Enables output of file field of event
197    ///
198    /// Default is true
199    pub fn output_file(mut self, enabled: bool) -> Self {
200        self.format_output_file = enabled;
201        self
202    }
203    pub fn opt_output_line(mut self, opt_enabled: Option<bool>) -> Self {
204        if let Some(enabled) = opt_enabled {
205            self.format_output_line = enabled;
206        }
207        self
208    }
209    /// Enables output of line field of event
210    ///
211    /// Default is true
212    pub fn output_line(mut self, enabled: bool) -> Self {
213        self.format_output_line = enabled;
214        self
215    }
216    pub fn inner_state(mut self, state: Arc<Mutex<TuiWidgetInnerState>>) -> Self {
217        self.state = state;
218        self
219    }
220    pub fn state(mut self, state: &TuiWidgetState) -> Self {
221        self.state = state.clone_state();
222        self
223    }
224    fn next_event<'a>(
225        &self,
226        events: &'a CircularBuffer<ExtLogRecord>,
227        mut index: usize,
228        ignore_current: bool,
229        increment: bool,
230        state: &TuiWidgetInnerState,
231    ) -> Option<(Option<usize>, usize, &'a ExtLogRecord)> {
232        // The result is an optional next_index, the event index and the event
233        if ignore_current {
234            index = if increment {
235                index + 1
236            } else {
237                if index == 0 {
238                    return None;
239                }
240                index - 1
241            };
242        }
243        while let Some(evt) = events.element_at_index(index) {
244            let mut skip = false;
245            if let Some(level) = state
246                .config
247                .get(evt.target())
248                .or(state.config.get_default_display_level())
249            {
250                if level < evt.level {
251                    skip = true;
252                }
253            }
254            if !skip && state.focus_selected {
255                if let Some(target) = state.opt_selected_target.as_ref() {
256                    if target != evt.target() {
257                        skip = true;
258                    }
259                }
260            }
261            if skip {
262                index = if increment {
263                    index + 1
264                } else {
265                    if index == 0 {
266                        break;
267                    }
268                    index - 1
269                };
270            } else if increment {
271                return Some((Some(index + 1), index, evt));
272            } else {
273                if index == 0 {
274                    return Some((None, index, evt));
275                }
276                return Some((Some(index - 1), index, evt));
277            }
278        }
279        None
280    }
281}
282impl<'b> Widget for TuiLoggerWidget<'b> {
283    fn render(mut self, area: Rect, buf: &mut Buffer) {
284        let render_debug = false;
285
286        let formatter = match self.logformatter.take() {
287            Some(fmt) => fmt,
288            None => {
289                let fmt = LogStandardFormatter {
290                    style: self.style,
291                    style_error: self.style_error,
292                    style_warn: self.style_warn,
293                    style_debug: self.style_debug,
294                    style_trace: self.style_trace,
295                    style_info: self.style_info,
296                    format_separator: self.format_separator,
297                    format_timestamp: self.format_timestamp.clone(),
298                    format_output_level: self.format_output_level,
299                    format_output_target: self.format_output_target,
300                    format_output_file: self.format_output_file,
301                    format_output_line: self.format_output_line,
302                };
303                Box::new(fmt)
304            }
305        };
306
307        buf.set_style(area, self.style);
308        let list_area = match self.block.take() {
309            Some(b) => {
310                let inner_area = b.inner(area);
311                b.render(area, buf);
312                inner_area
313            }
314            None => area,
315        };
316        if list_area.width < formatter.min_width() || list_area.height < 1 {
317            return;
318        }
319
320        let mut state = self.state.lock();
321        let la_height = list_area.height as usize;
322        let la_left = list_area.left();
323        let la_top = list_area.top();
324        let la_width = list_area.width as usize;
325        let mut rev_lines: Vec<(LinePointer, Line)> = vec![];
326        let mut can_scroll_up = true;
327        let mut can_scroll_down = state.opt_line_pointer_center.is_some();
328        {
329            enum Pos {
330                Top,
331                Bottom,
332                Center(usize),
333            }
334            let tui_lock = TUI_LOGGER.inner.lock();
335            // If scrolling, the opt_line_pointer_center is set.
336            // Otherwise we are following the bottom of the events
337            let opt_pos_event_index = if let Some(lp) = state.opt_line_pointer_center {
338                tui_lock.events.first_index().map(|first_index| {
339                    if first_index <= lp.event_index {
340                        (Pos::Center(lp.subline), lp.event_index)
341                    } else {
342                        (Pos::Top, first_index)
343                    }
344                })
345            } else {
346                tui_lock
347                    .events
348                    .last_index()
349                    .map(|last_index| (Pos::Bottom, last_index))
350            };
351            if let Some((pos, event_index)) = opt_pos_event_index {
352                // There are events to be shown
353                let mut lines: Vec<(usize, Vec<Line>, usize)> = Vec::new();
354                let mut from_line: isize = 0;
355                let mut to_line = 0;
356                match pos {
357                    Pos::Center(subline) => {
358                        if render_debug {
359                            println!("CENTER {}", event_index);
360                        }
361                        if let Some((_, evt_index, evt)) =
362                            self.next_event(&tui_lock.events, event_index, false, true, &state)
363                        {
364                            let evt_lines = formatter.format(la_width, evt);
365                            from_line = (la_height / 2) as isize - subline as isize;
366                            to_line = la_height / 2 + (evt_lines.len() - 1) - subline;
367                            let n = evt_lines.len();
368                            lines.push((evt_index, evt_lines, n));
369                            if render_debug {
370                                println!("Center is {}", evt_index);
371                            }
372                        }
373                    }
374                    Pos::Top => {
375                        can_scroll_up = false;
376                        if render_debug {
377                            println!("TOP");
378                        }
379                        if let Some((_, evt_index, evt)) =
380                            self.next_event(&tui_lock.events, event_index, false, true, &state)
381                        {
382                            let evt_lines = formatter.format(la_width, evt);
383                            from_line = 0;
384                            to_line = evt_lines.len() - 1;
385                            let n = evt_lines.len();
386                            lines.push((evt_index, evt_lines, n));
387                            if render_debug {
388                                println!("Top is {}", evt_index);
389                            }
390                        }
391                    }
392                    Pos::Bottom => {
393                        if render_debug {
394                            println!("TOP");
395                        }
396                        if let Some((_, evt_index, evt)) =
397                            self.next_event(&tui_lock.events, event_index, false, false, &state)
398                        {
399                            let evt_lines = formatter.format(la_width, evt);
400                            to_line = la_height - 1;
401                            from_line = to_line as isize - (evt_lines.len() - 1) as isize;
402                            let n = evt_lines.len();
403                            lines.push((evt_index, evt_lines, n));
404                            if render_debug {
405                                println!("Bottom is {}", evt_index);
406                            }
407                        }
408                    }
409                }
410                if !lines.is_empty() {
411                    let mut cont = true;
412                    let mut at_top = false;
413                    let mut at_bottom = false;
414                    while cont {
415                        if render_debug {
416                            println!("from_line {}, to_line {}", from_line, to_line);
417                        }
418                        cont = false;
419                        if from_line > 0 {
420                            if let Some((_, evt_index, evt)) = self.next_event(
421                                &tui_lock.events,
422                                lines.first().as_ref().unwrap().0,
423                                true,
424                                false,
425                                &state,
426                            ) {
427                                let evt_lines = formatter.format(la_width, evt);
428                                from_line -= evt_lines.len() as isize;
429                                let n = evt_lines.len();
430                                lines.insert(0, (evt_index, evt_lines, n));
431                                cont = true;
432                            } else {
433                                // no more events, so adjust start
434                                at_top = true;
435                                if render_debug {
436                                    println!("no more events adjust start");
437                                }
438                                to_line -= from_line as usize;
439                                from_line = 0;
440                                if render_debug {
441                                    println!("=> from_line {}, to_line {}", from_line, to_line);
442                                }
443                            }
444                        }
445                        if to_line < la_height - 1 {
446                            if let Some((_, evt_index, evt)) = self.next_event(
447                                &tui_lock.events,
448                                lines.last().as_ref().unwrap().0,
449                                true,
450                                true,
451                                &state,
452                            ) {
453                                let evt_lines = formatter.format(la_width, evt);
454                                to_line += evt_lines.len();
455                                let n = evt_lines.len();
456                                lines.push((evt_index, evt_lines, n));
457                                cont = true;
458                            } else {
459                                at_bottom = true;
460                                can_scroll_down = false;
461                                if render_debug {
462                                    println!("no more events at end");
463                                }
464                                // no more events
465                                if to_line != la_height - 1 {
466                                    cont = true;
467                                } else if !cont {
468                                    break;
469                                }
470                                // no more events, so adjust end
471                                from_line += (la_height - 1 - to_line) as isize;
472                                to_line = la_height - 1;
473                                if render_debug {
474                                    println!("=> from_line {}, to_line {}", from_line, to_line);
475                                }
476                            }
477                        }
478                        if at_top && at_bottom {
479                            break;
480                        }
481                    }
482                    if at_top {
483                        can_scroll_up = false;
484                    }
485                    if at_bottom {
486                        can_scroll_down = false;
487                    }
488                    if render_debug {
489                        println!("finished: from_line {}, to_line {}", from_line, to_line);
490                    }
491                    let mut curr: isize = to_line as isize;
492                    while let Some((evt_index, evt_lines, mut n)) = lines.pop() {
493                        for line in evt_lines.into_iter().rev() {
494                            n -= 1;
495                            if curr < 0 {
496                                break;
497                            }
498                            if curr < la_height as isize {
499                                let line_ptr = LinePointer {
500                                    event_index: evt_index,
501                                    subline: n,
502                                };
503                                rev_lines.push((line_ptr, line));
504                            }
505                            curr -= 1;
506                        }
507                    }
508                }
509            } else {
510                can_scroll_down = false;
511                can_scroll_up = false;
512            }
513        }
514
515        state.opt_line_pointer_next_page = if can_scroll_down {
516            rev_lines.first().map(|l| l.0)
517        } else {
518            None
519        };
520        state.opt_line_pointer_prev_page = if can_scroll_up {
521            rev_lines.last().map(|l| l.0)
522        } else {
523            None
524        };
525
526        if render_debug {
527            println!("Line pointers in buffer:");
528            for l in rev_lines.iter().rev() {
529                println!("event_index {}, subline {}", l.0.event_index, l.0.subline);
530            }
531            if state.opt_line_pointer_center.is_some() {
532                println!(
533                    "Linepointer center: {:?}",
534                    state.opt_line_pointer_center.unwrap()
535                );
536            }
537            if state.opt_line_pointer_next_page.is_some() {
538                println!(
539                    "Linepointer next: {:?}",
540                    state.opt_line_pointer_next_page.unwrap()
541                );
542            }
543            if state.opt_line_pointer_prev_page.is_some() {
544                println!(
545                    "Linepointer prev: {:?}",
546                    state.opt_line_pointer_prev_page.unwrap()
547                );
548            }
549        }
550
551        // This apparently ensures, that the log starts at top
552        let offset: u16 = if state.opt_line_pointer_center.is_none() {
553            0
554        } else {
555            let lines_cnt = rev_lines.len();
556            std::cmp::max(0, la_height - lines_cnt) as u16
557        };
558
559        for (i, line) in rev_lines.into_iter().rev().take(la_height).enumerate() {
560            line.1.render(
561                Rect {
562                    x: la_left,
563                    y: la_top + i as u16 + offset,
564                    width: list_area.width,
565                    height: 1,
566                },
567                buf,
568            )
569        }
570    }
571}