Skip to main content

vvv_engine/protocol/
display.rs

1//! A styled line as data: the words and their roles, no colours. An
2//! interface maps a [`Role`] to its own style and renders the line, so the
3//! composition of a row — what is written, in what order, which part is the
4//! hit — lives once, in the protocol.
5
6use super::vocabulary::Mark;
7use super::{FileChange, Match};
8
9/// The semantic role of a run of text. A backend names the colour; the data
10/// never carries one.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Role {
13    /// No style of its own.
14    Plain,
15    /// A word around the answer: a label, a count.
16    Dim,
17    /// A heading or a section label.
18    Title,
19    /// An emphasised word: a count, a history id, a module header.
20    Strong,
21    /// A file path.
22    Path,
23    /// A line number.
24    LineNumber,
25    /// A row's number.
26    Ordinal,
27    /// A declaration's modifier.
28    Symbol,
29    /// `●` and a declaration's `kind name`.
30    Declaration,
31    /// An import, or the text around one.
32    Import,
33    /// `◆ address`.
34    Address,
35    /// `✗` and an error.
36    Error,
37    /// `!` and a warning.
38    Warning,
39    /// `hint:` and what to try instead.
40    Hint,
41    /// The hit within a line.
42    Hit,
43    /// A line a change adds.
44    Added,
45    /// A line a change removes.
46    Removed,
47    /// A diff hunk header.
48    Hunk,
49    /// A mark's glyph (`●`, `✓`, `→`): the renderer colours it by the mark.
50    Mark(Mark),
51}
52
53/// A run of text with one role.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Piece {
56    pub text: String,
57    pub role: Role,
58}
59
60impl Piece {
61    pub fn new(role: Role, text: impl Into<String>) -> Self {
62        Self {
63            text: text.into(),
64            role,
65        }
66    }
67}
68
69/// One line of output: its pieces, in order.
70#[derive(Debug, Clone, Default, PartialEq, Eq)]
71pub struct Line {
72    pieces: Vec<Piece>,
73}
74
75impl Line {
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    pub fn of(role: Role, text: impl Into<String>) -> Self {
81        Self {
82            pieces: vec![Piece::new(role, text)],
83        }
84    }
85
86    /// A match's source line split around the hit, leading indentation
87    /// dropped: the text before, the hit, the text after. The text around the
88    /// hit takes `rest`.
89    pub fn hit(m: &Match, rest: Role) -> Self {
90        let chars: Vec<char> = m.line.chars().collect();
91        let start = (m.start.column as usize).min(chars.len());
92        let stop = if m.end.line == m.start.line {
93            (m.end.column as usize).clamp(start, chars.len())
94        } else {
95            chars.len()
96        };
97        let indent = chars[..start]
98            .iter()
99            .take_while(|c| c.is_whitespace())
100            .count();
101        let before: String = chars[indent..start].iter().collect();
102        let token: String = chars[start..stop].iter().collect();
103        let after: String = chars[stop..].iter().collect();
104        Self::new()
105            .and(rest, before)
106            .and(Role::Hit, token)
107            .and(rest, after)
108    }
109
110    /// A mark's glyph as a line.
111    pub fn mark(mark: Mark) -> Self {
112        Self::of(Role::Mark(mark), mark.glyph().to_string())
113    }
114
115    /// `✓ 3  ? 1  ✗ 0`: each mark's glyph and count, pairs two spaces apart.
116    pub fn counts(counts: &[(Mark, usize)]) -> Self {
117        let mut line = Self::new();
118        for (i, (mark, count)) in counts.iter().enumerate() {
119            if i > 0 {
120                line = line.and(Role::Plain, "  ");
121            }
122            line = line
123                .and(Role::Mark(*mark), format!("{} ", mark.glyph()))
124                .and(Role::Plain, count.to_string());
125        }
126        line
127    }
128
129    /// Add a piece; the line, for chaining.
130    pub fn and(mut self, role: Role, text: impl Into<String>) -> Self {
131        self.pieces.push(Piece::new(role, text));
132        self
133    }
134
135    /// Append another line's pieces; the line, for chaining.
136    pub fn and_line(mut self, other: Line) -> Self {
137        self.pieces.extend(other.pieces);
138        self
139    }
140
141    pub fn pieces(&self) -> &[Piece] {
142        &self.pieces
143    }
144
145    pub fn is_empty(&self) -> bool {
146        self.pieces.iter().all(|p| p.text.is_empty())
147    }
148}
149
150/// A file's unified diff lines: the `---`/`+++` headers dropped, each line's
151/// role by its first byte (`@` hunk, `+` added, `-` removed, else plain).
152pub fn diff(file: &FileChange) -> Vec<Line> {
153    file.diff
154        .as_str()
155        .lines()
156        .filter(|l| !l.starts_with("--- ") && !l.starts_with("+++ "))
157        .map(|l| {
158            let role = match l.as_bytes().first() {
159                Some(b'@') => Role::Hunk,
160                Some(b'+') => Role::Added,
161                Some(b'-') => Role::Removed,
162                _ => Role::Plain,
163            };
164            Line::of(role, l)
165        })
166        .collect()
167}
168
169#[cfg(test)]
170mod tests {
171    use std::collections::BTreeMap;
172    use vvv_core::RelPath;
173
174    use vvv_core::{LanguageId, Position, Role as MatchRole, Span};
175
176    use super::*;
177    use crate::protocol::MatchId;
178
179    fn at(line: &str, start: u32, end: u32) -> Match {
180        Match {
181            id: MatchId::from("test".to_owned()),
182            path: RelPath::from("a.rs"),
183            language: LanguageId::from("rust"),
184            span: Span::new(0, 0),
185            start: Position::new(0, start),
186            end: Position::new(0, end),
187            kind: "identifier".to_owned(),
188            text: String::new(),
189            line: line.to_owned(),
190            captures: BTreeMap::new(),
191            symbol: None,
192            role: MatchRole::Use,
193            address: None,
194        }
195    }
196
197    #[test]
198    fn hit_uses_char_columns_and_trims_leading_indent() {
199        let line = Line::hit(&at("    let é = foo(1);", 12, 15), Role::Plain);
200        let text: String = line.pieces().iter().map(|p| p.text.as_str()).collect();
201        assert_eq!(text, "let é = foo(1);");
202        assert_eq!(line.pieces()[1].role, Role::Hit);
203        assert_eq!(line.pieces()[1].text, "foo");
204    }
205
206    #[test]
207    fn counts_puts_a_marks_glyph_beside_its_count() {
208        let line = Line::counts(&[(Mark::Safe, 3), (Mark::Unverified, 1), (Mark::Other, 0)]);
209        let text: String = line.pieces().iter().map(|p| p.text.as_str()).collect();
210        assert_eq!(text, "✓ 3  ? 1  ✗ 0");
211        assert_eq!(line.pieces()[0].role, Role::Mark(Mark::Safe));
212        assert_eq!(line.pieces()[1].role, Role::Plain);
213    }
214}