summaryrefslogtreecommitdiffstats
path: root/src/foldview.rs
blob: e4933ccc3f837606a40aa305b8f68b4fa83e2661 (plain)
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use termion::event::Key;
use failure::Fail;
use chrono::{DateTime, Local};

use crate::term;
use crate::widget::Widget;
use crate::listview::{ListView, Listable};
use crate::fail::{HResult, HError};
use crate::dirty::Dirtyable;

pub type LogView = ListView<Vec<LogEntry>>;


#[derive(Debug)]
pub struct LogEntry {
    description: String,
    content: Option<String>,
    lines: usize,
    folded: bool
}


impl Foldable for LogEntry {
    fn description(&self) -> &str {
        &self.description
    }
    fn content(&self) -> Option<&String> {
        self.content.as_ref()
    }
    fn lines(&self) -> usize {
        if self.is_folded() { 1 } else {
            self.lines
        }
    }
    fn toggle_fold(&mut self) {
        self.folded = !self.folded;
    }
    fn is_folded(&self) -> bool {
        self.folded
    }
}


impl From<&HError> for LogEntry {
    fn from(from: &HError) -> LogEntry {
        let time: DateTime<Local> = Local::now();

        let logcolor = match from {
            HError::Log(_) => term::normal_color(),
            _ => term::color_red()
        };

        let description = format!("{}{}{}: {}",
                                  term::color_green(),
                                  time.format("%F %R"),
                                  logcolor,
                                  from).lines().take(1).collect();
        let mut content = format!("{}{}{}: {}\n",
                                  term::color_green(),
                                  time.format("%F %R"),
                                  logcolor,
                                  from);


        if let Some(cause) = from.cause() {
            content += &format!("{}\n", cause);
        }

        if let Some(backtrace) = from.backtrace() {
            content += &format!("{}\n", backtrace);
        }

        let lines = content.lines().count();

        LogEntry {
            description: description,
            content: Some(content),
            lines: lines,
            folded: true
        }
    }
}



pub trait FoldableWidgetExt {
    fn on_refresh(&mut self) -> HResult<()> { Ok(()) }
    fn render_header(&self) -> HResult<String> { Ok("".to_string()) }
    fn render_footer(&self) -> HResult<String> { Ok("".to_string()) }
    fn on_key(&mut self, key: Key) -> HResult<()> {
        HError::undefined_key(key)?
    }
    fn render(&self) -> Vec<String> { vec![] }
}

impl FoldableWidgetExt for  ListView<Vec<LogEntry>> {
    fn on_refresh(&mut self) -> HResult<()> {
        if self.content.refresh_logs()? > 0 {
            self.core.set_dirty();
        }
        Ok(())
    }

    fn render_header(&self) -> HResult<String> {
        let (xsize, _) = self.core.coordinates.size_u();
        let current = self.current_fold().map(|n| n+1).unwrap_or(0);
        let num = self.content.len();
        let hint = format!("{} / {}", current, num);
        let hint_xpos = xsize - hint.len();
        let header = format!("Logged entries: {}{}{}",
                             num,
                             term::goto_xy_u(hint_xpos, 0),
                             hint);
        Ok(header)
    }

    fn render_footer(&self) -> HResult<String> {
        let current = self.current_fold()?;
        if let Some(logentry) = self.content.get(current) {
            let (xsize, ysize) = self.core.coordinates.size_u();
            let (_, ypos) = self.core.coordinates.position_u();
            let description = logentry.description();
            let lines = logentry.lines();
            let start_pos = self.fold_start_pos(current);
            let selection = self.get_selection();
            let current_line = (selection - start_pos) + 1;
            let line_hint = format!("{} / {}", current_line, lines);
            let hint_xpos = xsize - line_hint.len();
            let hint_ypos = ysize + ypos + 1;

            let sized_description = term::sized_string_u(&description,
                                                         xsize
                                                         - (line_hint.len()+2));

            let footer = format!("{}{}{}{}{}",
                                 sized_description,
                                 term::reset(),
                                 term::status_bg(),
                                 term::goto_xy_u(hint_xpos, hint_ypos),
                                 line_hint);

            Ok(footer)
        } else { Ok("No log entries".to_string()) }
    }
}

trait LogList {
    fn refresh_logs(&mut self) -> HResult<usize>;
}

impl LogList for Vec<LogEntry> {
    fn refresh_logs(&mut self) -> HResult<usize> {
        let logs = crate::fail::get_logs()?;

        let mut logentries = logs.into_iter().map(|log| {
            LogEntry::from(log)
        }).collect::<Vec<_>>();

        let n = logentries.len();

        self.append(&mut logentries);

        Ok(n)
    }
}


pub trait Foldable {
    fn description(&self) -> &str;
    fn content(&self) -> Option<&String>;
    fn lines(&self) -> usize;
    fn toggle_fold(&mut self);
    fn is_folded(&self) -> bool;

    fn text(&self) -> &str {
        if !self.is_folded() && self.content().is_some() {
            self.content().unwrap()
        } else {
            &self.description()
        }
    }

    fn render_description(&self) -> String {
        self.description().to_string()
    }

    fn render_content(&self) -> Vec<String> {
        if let Some(content) = self.content() {
            content
                .lines()
                .map(|line| line.to_string())
                .collect()
        } else { vec![self.render_description()] }
    }

    fn render(&self) -> Vec<String> {
        if self.is_folded() {
            vec![self.render_description()]
        } else {
            self.render_content()
        }
    }
}

impl<F: Foldable> ListView<Vec<F>>
where
    ListView<Vec<F>>: FoldableWidgetExt {

    pub fn toggle_fold(&mut self) -> HResult<()> {
        let fold = self.current_fold()?;
        let fold_pos = self.fold_start_pos(fold);

        self.content[fold].toggle_fold();

        if self.content[fold].is_folded() {
            self.set_selection(fold_pos);
        }

        self.core.set_dirty();
        Ok(())
    }

    pub fn fold_start_pos(&self, fold: usize) -> usize {
        self.content
            .iter()
            .take(fold)
            .fold(0, |pos, foldable| {
                pos + (foldable.lines())
            })
    }

    pub fn current_fold(&self) -> Option<usize> {
        let pos = self.get_selection();

        let fold_lines = self
            .content
            .iter()
            .map(|f| f.lines())
            .collect::<<