1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use std::{
    fs,
    path::PathBuf
};
use cursive_core::{
    View,
    Printer,
    Vec2,
    utils::{
        markup::StyledString,
        lines::spans::{LinesIterator, Row}
    },
    views::ScrollView,
    view::{ScrollStrategy, Scrollable},
    theme::{
        BaseColor,
        Color,
        Style,
        ColorStyle
    }
};
use rust_utils::logging::Log;
use lazy_static::lazy_static;
use regex::Regex;
use unicode_width::UnicodeWidthStr;
use crate::SpannedStrExt;

lazy_static! {
    static ref INFO_RE: Regex = Regex::new(r"\[.*INFO\]").unwrap();
    static ref DBG_RE: Regex = Regex::new(r"\[.*DEBUG\]").unwrap();
    static ref WARN_RE: Regex = Regex::new(r"\[.*WARN\]").unwrap();
    static ref ERROR_RE: Regex = Regex::new(r"\[.*ERROR\]").unwrap();
    static ref FATAL_RE: Regex = Regex::new(r"\[.*FATAL\]").unwrap();
}

/// A special view that follows a specified log file
/// similar to how `tail -f <log file name>` tracks a log file
///
/// Auto-refresh in cursive must be set by calling `Cursive::set_fps()`
/// or `Cursive::set_autorefresh()` before using this view or it won't work
#[derive(Clone)]
pub struct LogView {
    path: PathBuf,
    content: LogContent
}

impl LogView {
    /// Create a new `LogView` with the specified log file path
    pub fn new<P: Into<PathBuf>>(path: P) -> LogView {
        let path = path.into();
        let raw_log = fs::read_to_string(&path).unwrap_or_default();
        let content = LogContent::new(raw_log);

        LogView {
            path,
            content
        }
    }

    /// Wrap the `LogView` in a `ScrollView` that jumps to the bottom when the log updates
    pub fn scroll_to_bottom(self) -> ScrollView<Self> {
        self.scrollable().scroll_strategy(ScrollStrategy::StickToBottom)
    }
}

impl View for LogView {
    fn draw(&self, printer: &Printer) {
        for y in 0..printer.size.y {
            printer.print_hline((0, y), printer.size.x, " ");
        }
        self.content.draw(printer);
    }

    fn required_size(&mut self, bound: Vec2) -> Vec2 {
        self.content.fit_to_width(bound.x);
        (bound.x, self.content.num_lines()).into()
    }

    fn layout(&mut self, size: Vec2) {
        let raw_log = fs::read_to_string(&self.path).unwrap_or_default();
        self.content.set_content(raw_log);
        self.content.fit_to_width(size.x);
    }
}

impl From<&Log> for LogView {
    /// Create a `LogView` from a `rust-utils` `Log` object
    ///
    /// This will follow the main log if it is enabled or the latest dated
    /// log file otherwise
    fn from(log: &Log) -> Self {
        let path = if let Some(main_log_path) = log.main_log_path() {
            main_log_path
        }
        else {
            log.log_path()
        };

        Self::new(path)
    }
}

#[derive(Clone)]
struct LogContent {
    content: StyledString,
    rows: Vec<Row>
}

impl LogContent {
    fn new(content: String) -> Self {
        let content = colorize_log(&content);
        LogContent {
            content,
            rows: Vec::new()
        }
    }

    // sets the content
    // since this might be expensive, the content
    // is only set when the new content is different from the current content
    fn set_content(&mut self, new_content: String) {
        if new_content.as_str() != self.content.source() {
            self.content = colorize_log(&new_content);
        }
    }

    // resize the log content to fit in the specified width
    fn fit_to_width(&mut self, width: usize) {
        if width == 0 { return; }
        self.rows = LinesIterator::new(self.content.as_spanned_str(), width).collect();
    }

    fn num_lines(&self) -> usize {
        self.rows.len()
    }

    fn draw(&self, printer: &Printer) {
        for (y, row) in self.rows.iter().enumerate() {
            let mut x = 0;
            for span in row.resolve(self.content.as_spanned_str()) {
                printer.with_style(*span.attr, |printer| {
                    printer.print((x, y), span.content);
                    x += span.content.width();
                });
            }
        }
    }
}

fn colorize_log(log: &str) -> StyledString {
    let mut styled_log = StyledString::new();

    let mut line_color = Style::from(Color::Light(BaseColor::White));
    for log_line in log.lines() {
        if INFO_RE.is_match(log_line) {
            line_color = Style::from(Color::Dark(BaseColor::Green));
        }
        else if DBG_RE.is_match(log_line) {
            line_color = Style::from(Color::Dark(BaseColor::Cyan));
        }
        else if WARN_RE.is_match(log_line) {
            line_color = Style::from(Color::Light(BaseColor::Yellow));
        }
        else if ERROR_RE.is_match(log_line) {
            line_color = Style::from(Color::Light(BaseColor::Red));
        }
        else if FATAL_RE.is_match(log_line) {
            line_color = Style::from(ColorStyle::new(Color::Light(BaseColor::Red), Color::Dark(BaseColor::Black)));
        }

        styled_log.append_styled(log_line, line_color);
        styled_log.append('\n');
    }

    styled_log
}