summaryrefslogtreecommitdiffstats
path: root/src/ui/widgets/tui_file_preview.rs
blob: c1e6632ea238b8fd1f362786022616dd95fb1364 (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
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, vec: Vec<u8>) {
        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, vec: Vec<u8>) {
        use ansi_to_tui::ansi_to_text;

        let res = ansi_to_text(vec.clone());
        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);

                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) {
        let vec = self.preview.output.as_str().as_bytes().to_vec();
        self.render_text_preview(area, buf, vec);
    }
}