aboutsummaryrefslogtreecommitdiff
path: root/alacritty/src/url.rs
blob: e538331dc2b7ae4041fab40b686ea31151f41438 (plain) (blame)
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use std::cmp::min;
use std::mem;

use glutin::event::{ElementState, ModifiersState};
use urlocator::{UrlLocation, UrlLocator};

use font::Metrics;

use alacritty_terminal::index::Point;
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::color::Rgb;
use alacritty_terminal::term::{RenderableCell, RenderableCellContent, SizeInfo};

use crate::config::Config;
use crate::event::Mouse;
use crate::renderer::rects::{RenderLine, RenderRect};

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Url {
    lines: Vec<RenderLine>,
    end_offset: u16,
    num_cols: usize,
}

impl Url {
    pub fn rects(&self, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> {
        let end = self.end();
        self.lines
            .iter()
            .filter(|line| line.start <= end)
            .map(|line| {
                let mut rect_line = *line;
                rect_line.end = min(line.end, end);
                rect_line.rects(Flags::UNDERLINE, metrics, size)
            })
            .flatten()
            .collect()
    }

    pub fn start(&self) -> Point {
        self.lines[0].start
    }

    pub fn end(&self) -> Point {
        self.lines[self.lines.len() - 1].end.sub(self.num_cols, self.end_offset as usize)
    }
}

pub struct Urls {
    locator: UrlLocator,
    urls: Vec<Url>,
    scheme_buffer: Vec<RenderableCell>,
    last_point: Option<Point>,
    state: UrlLocation,
}

impl Default for Urls {
    fn default() -> Self {
        Self {
            locator: UrlLocator::new(),
            scheme_buffer: Vec::new(),
            urls: Vec::new(),
            state: UrlLocation::Reset,
            last_point: None,
        }
    }
}

impl Urls {
    pub fn new() -> Self {
        Self::default()
    }

    // Update tracked URLs
    pub fn update(&mut self, num_cols: usize, cell: RenderableCell) {
        // Convert cell to character
        let c = match cell.inner {
            RenderableCellContent::Chars(chars) => chars[0],
            RenderableCellContent::Cursor(_) => return,
        };

        let point: Point = cell.into();
        let end = point;

        // Reset URL when empty cells have been skipped
        if point != Point::default() && Some(point.sub(num_cols, 1)) != self.last_point {
            self.reset();
        }

        self.last_point = Some(end);

        // Extend current state if a wide char spacer is encountered
        if cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
            if let UrlLocation::Url(_, mut end_offset) = self.state {
                if end_offset != 0 {
                    end_offset += 1;
                }

                self.extend_url(point, end, cell.fg, end_offset);
            }

            return;
        }

        // Advance parser
        let last_state = mem::replace(&mut self.state, self.locator.advance(c));
        match (self.state, last_state) {
            (UrlLocation::Url(_length, end_offset), UrlLocation::Scheme) => {
                // Create empty URL
                self.urls.push(Url { lines: Vec::new(), end_offset, num_cols });

                // Push schemes into URL
                for scheme_cell in self.scheme_buffer.split_off(0) {
                    let point = scheme_cell.into();
                    self.extend_url(point, point, scheme_cell.fg, end_offset);
                }

                // Push the new cell into URL
                self.extend_url(point, end, cell.fg, end_offset);
            },
            (UrlLocation::Url(_length, end_offset), UrlLocation::Url(..)) => {
                self.extend_url(point, end, cell.fg, end_offset);
            },
            (UrlLocation::Scheme, _) => self.scheme_buffer.push(cell),
            (UrlLocation::Reset, _) => self.reset(),
            _ => (),
        }

        // Reset at un-wrapped linebreak
        if cell.column.0 + 1 == num_cols && !cell.flags.contains(Flags::WRAPLINE) {
            self.reset();
        }
    }

    // Extend the last URL
    fn extend_url(&mut self, start: Point, end: Point, color: Rgb, end_offset: u16) {
        let url = self.urls.last_mut().unwrap();

        // If color changed, we need to insert a new line
        if url.lines.last().map(|last| last.color) == Some(color) {
            url.lines.last_mut().unwrap().end = end;
        } else {
            url.lines.push(RenderLine { color, start, end });
        }

        // Update excluded cells at the end of the URL
        url.end_offset = end_offset;
    }

    pub fn highlighted(
        &self,
        config: &Config,
        mouse: &Mouse,
        mods: ModifiersState,
        mouse_mode: bool,
        selection: bool,
    ) -> Option<Url> {
        // Require additional shift in mouse mode
        let mut required_mods = config.ui_config.mouse.url.mods();
        if mouse_mode {
            required_mods |= ModifiersState::SHIFT;
        }

        // Make sure all prerequisites for highlighting are met
        if selection
            || !mouse.inside_grid
            || config.ui_config.mouse.url.launcher.is_none()
            || required_mods != mods
            || mouse.left_button_state == ElementState::Pressed
        {
            return None;
        }

        for url in &self.urls {
            if (url.start()..=url.end()).contains(&Point::new(mouse.line, mouse.column)) {
                return Some(url.clone());
            }
        }

        None
    }

    fn reset(&mut self) {
        self.locator = UrlLocator::new();
        self.state = UrlLocation::Reset;
        self.scheme_buffer.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use alacritty_terminal::index::{Column, Line};
    use alacritty_terminal::term::cell::MAX_ZEROWIDTH_CHARS;

    fn text_to_cells(text: &str) -> Vec<RenderableCell> {
        text.chars()
            .enumerate()
            .map(|(i, c)| RenderableCell {
                inner: RenderableCellContent::Chars([c; MAX_ZEROWIDTH_CHARS + 1]),
                line: Line(0),
                column: Column(i),
                fg: Default::default(),
                bg: Default::default(),
                bg_alpha: 0.,
                flags: Flags::empty(),
            })
            .collect()
    }

    #[test]
    fn multi_color_url() {
        let mut input = text_to_cells("test https://example.org ing");
        let num_cols = input.len();

        input[10].fg = Rgb { r: 0xff, g: 0x00, b: 0xff };

        let mut urls = Urls::new();

        for cell in input {
            urls.update(num_cols, cell);
        }

        let url = urls.urls.first().unwrap();
        assert_eq!(url.start().col, Column(5));
        assert_eq!(url.end().col, Column(23));
    }

    #[test]
    fn multiple_urls() {
        let input = text_to_cells("test git:a git:b git:c ing");
        let num_cols = input.len();

        let mut urls = Urls::new();

        for cell in input {
            urls.update(num_cols, cell);
        }

        assert_eq!(urls.urls.len(), 3);

        assert_eq!(urls.urls[0].start().col, Column(5));
        assert_eq!(urls.urls[0].end().col, Column(9));

        assert_eq!(urls.urls[1].start().col, Column(11));
        assert_eq!(urls.urls[1].end().col, Column(15));

        assert_eq!(urls.urls[2].start().col, Column(17));
        assert_eq!(urls.urls[2].end().col, Column(21));
    }
}