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::Match;
7use super::vocabulary::Mark;
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    /// A fully-qualified address — a re-export alias.
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 single(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::single(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    /// Cut the line to `budget` columns, `…` where it is cut.
150    pub fn fit(self, budget: usize) -> Self {
151        let total: usize = self.pieces.iter().map(|p| p.text.chars().count()).sum();
152        if total <= budget {
153            return self;
154        }
155        let last = self.pieces.len().saturating_sub(1);
156        let mut remaining = budget.saturating_sub(1);
157        let mut out = Self::new();
158        for (i, piece) in self.pieces.into_iter().enumerate() {
159            let take = piece.text.chars().count().min(remaining);
160            let mut text: String = piece.text.chars().take(take).collect();
161            remaining = remaining.saturating_sub(take);
162            if i == last {
163                text.push('…');
164            }
165            out = out.and(piece.role, text);
166        }
167        out
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use std::collections::BTreeMap;
174    use vvv_core::RelPath;
175
176    use vvv_core::{LanguageId, Position, Role as MatchRole, Span};
177
178    use super::*;
179    use crate::protocol::MatchId;
180
181    fn at(line: &str, start: u32, end: u32) -> Match {
182        Match {
183            content: None,
184            id: MatchId::from("test".to_owned()),
185            path: RelPath::from("a.rs"),
186            language: LanguageId::from("rust"),
187            span: Span::new(0, 0),
188            start: Position::new(0, start),
189            end: Position::new(0, end),
190            kind: "identifier".to_owned(),
191            text: String::new(),
192            line: line.to_owned(),
193            captures: BTreeMap::new(),
194            symbol: None,
195            role: MatchRole::Use,
196            address: None,
197        }
198    }
199
200    #[test]
201    fn hit_uses_char_columns_and_trims_leading_indent() {
202        let line = Line::hit(&at("    let é = foo(1);", 12, 15), Role::Plain);
203        let text: String = line.pieces().iter().map(|p| p.text.as_str()).collect();
204        assert_eq!(text, "let é = foo(1);");
205        assert_eq!(line.pieces()[1].role, Role::Hit);
206        assert_eq!(line.pieces()[1].text, "foo");
207    }
208
209    #[test]
210    fn counts_puts_a_marks_glyph_beside_its_count() {
211        let line = Line::counts(&[(Mark::Safe, 3), (Mark::Unverified, 1), (Mark::Other, 0)]);
212        let text: String = line.pieces().iter().map(|p| p.text.as_str()).collect();
213        assert_eq!(text, "✓ 3  ? 1  ✗ 0");
214        assert_eq!(line.pieces()[0].role, Role::Mark(Mark::Safe));
215        assert_eq!(line.pieces()[1].role, Role::Plain);
216    }
217}