summaryrefslogtreecommitdiffstats
path: root/src/ui/syntax_text.rs
blob: 9cd8ae9b3ed8b9dac44e03263f5ede4b6b1c2a5f (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
use asyncgit::asyncjob::AsyncJob;
use lazy_static::lazy_static;
use scopetime::scope_time;
use std::{
    ffi::OsStr,
    ops::Range,
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};
use syntect::{
    highlighting::{
        FontStyle, HighlightState, Highlighter,
        RangedHighlightIterator, Style, ThemeSet,
    },
    parsing::{ParseState, ScopeStack, SyntaxSet},
};
use tui::text::{Span, Spans};

//TODO: no clone, make user consume result
#[derive(Clone)]
struct SyntaxLine {
    items: Vec<(Style, usize, Range<usize>)>,
}

//TODO: no clone, make user consume result
#[derive(Clone)]
pub struct SyntaxText {
    text: String,
    lines: Vec<SyntaxLine>,
    path: PathBuf,
}

lazy_static! {
    static ref SYNTAX_SET: SyntaxSet =
        SyntaxSet::load_defaults_nonewlines();
    static ref THEME_SET: ThemeSet = ThemeSet::load_defaults();
}

impl SyntaxText {
    pub fn new(text: String, file_path: &Path) -> Self {
        scope_time!("syntax_highlighting");
        log::debug!("syntax: {:?}", file_path);

        let mut state = {
            let syntax = file_path
                .extension()
                .and_then(OsStr::to_str)
                .map_or_else(
                    || {
                        SYNTAX_SET.find_syntax_by_path(
                            file_path.to_str().unwrap_or_default(),
                        )
                    },
                    |ext| SYNTAX_SET.find_syntax_by_extension(ext),
                );

            ParseState::new(syntax.unwrap_or_else(|| {
                SYNTAX_SET.find_syntax_plain_text()
            }))
        };

        let highlighter = Highlighter::new(
            &THEME_SET.themes["base16-eighties.dark"],
        );

        let mut syntax_lines: Vec<SyntaxLine> = Vec::new();

        let mut highlight_state =
            HighlightState::new(&highlighter, ScopeStack::new());

        for (number, line) in text.lines().enumerate() {
            let ops = state.parse_line(line, &SYNTAX_SET);
            let iter = RangedHighlightIterator::new(
                &mut highlight_state,
                &ops[..],
                line,
                &highlighter,
            );

            syntax_lines.push(SyntaxLine {
                items: iter
                    .map(|(style, _, range)| (style, number, range))
                    .collect(),
            });
        }

        Self {
            text,
            lines: syntax_lines,
            path: file_path.into(),
        }
    }

    ///
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl<'a> From<&'a SyntaxText> for tui::text::Text<'a> {
    fn from(v: &'a SyntaxText) -> Self {
        let mut result_lines: Vec<Spans> =
            Vec::with_capacity(v.lines.len());

        for (syntax_line, line_content) in
            v.lines.iter().zip(v.text.lines())
        {
            let mut line_span =
                Spans(Vec::with_capacity(syntax_line.items.len()));

            for (style, _, range) in &syntax_line.items {
                let item_content = &line_content[range.clone()];
                let item_style = syntact_style_to_tui(style);

                line_span
                    .0
                    .push(Span::styled(item_content, item_style));
            }

            result_lines.push(line_span);
        }

        result_lines.into()
    }
}

fn syntact_style_to_tui(style: &Style) -> tui::style::Style {
    let mut res =
        tui::style::Style::default().fg(tui::style::Color::Rgb(
            style.foreground.r,
            style.foreground.g,
            style.foreground.b,
        ));

    if style.font_style.contains(FontStyle::BOLD) {
        res = res.add_modifier(tui::style::Modifier::BOLD);
    }
    if style.font_style.contains(FontStyle::ITALIC) {
        res = res.add_modifier(tui::style::Modifier::ITALIC);
    }
    if style.font_style.contains(FontStyle::UNDERLINE) {
        res = res.add_modifier(tui::style::Modifier::UNDERLINED);
    }

    res
}

enum JobState {
    Request((String, String)),
    Response(SyntaxText),
}

#[derive(Clone, Default)]
pub struct AsyncSyntaxJob {
    state: Arc<Mutex<Option<JobState>>>,
}

impl AsyncSyntaxJob {
    pub fn new(content: String, path: String) -> Self {
        Self {
            state: Arc::new(Mutex::new(Some(JobState::Request((
                content, path,
            ))))),
        }
    }

    pub fn result(&self) -> Option<SyntaxText> {
        if let Ok(mut state) = self.state.lock() {
            if let Some(state) = state.take() {
                return match state {
                    JobState::Request(_) => None,
                    JobState::Response(text) => Some(text),
                };
            }
        }

        None
    }
}

impl AsyncJob for AsyncSyntaxJob {
    fn run(&mut self) {
        if let Ok(mut state) = self.state.lock() {
            *state = state.take().map(|state| match state {
                JobState::Request((content, path)) => {
                    let syntax =
                        SyntaxText::new(content, Path::new(&path));
                    JobState::Response(syntax)
                }
                JobState::Response(res) => JobState::Response(res),
            });
        }
    }
}