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
|
use tui::buffer::Buffer;
use tui::layout::Rect;
use tui::text::Span;
use tui::widgets::Widget;
use crate::preview::preview_file::FilePreview;
pub struct TuiFilePreview<'a> {
preview: &'a FilePreview,
}
impl<'a> TuiFilePreview<'a> {
pub fn new(preview: &'a FilePreview) -> Self {
Self { preview }
}
#[cfg(not(feature = "syntax_highlight"))]
fn render_text_preview(&self, area: Rect, buf: &mut Buffer, s: &str) {
let vec: Vec<&str> = s.split('\n').collect();
for (line, y) in vec
.iter()
.skip(self.preview.index)
.zip(area.y + 1..area.y + area.height)
{
let span = Span::raw(line.to_string());
buf.set_span(area.x, y, &span, area.width);
}
}
#[cfg(feature = "syntax_highlight")]
fn render_text_preview(&self, area: Rect, buf: &mut Buffer, s: &str) {
use ansi_to_tui::ansi_to_text;
let vec = s.as_bytes().to_vec();
let res = ansi_to_text(vec);
match res {
Ok(text) => {
for (line, y) in text
.lines
.iter()
.skip(self.preview.index)
.zip(area.y..area.y + area.height)
{
buf.set_spans(area.x, y, line, area.width);
}
}
Err(e) => {
let span = Span::raw(format!("Failed to parse ansi colors: {}", e));
buf.set_span(area.x, area.y, &span, area.width);
let vec: Vec<&str> = s.split('\n').collect();
for (line, y) in vec
.iter()
.skip(self.preview.index)
.zip(area.y + 1..area.y + area.height)
{
let span = Span::raw(line.to_string());
buf.set_span(area.x, y, &span, area.width);
}
}
}
}
}
impl<'a> Widget for TuiFilePreview<'a> {
fn render(self, area: Rect, buf: &mut Buffer) {
self.render_text_preview(area, buf, self.preview.output.as_str());
}
}
|