summaryrefslogtreecommitdiff
path: root/helix-view/src/view.rs
blob: 3450da9b3faee8dd4c2440832c04763b06cfa6ce (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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use std::borrow::Cow;

use crate::{
    graphics::Rect,
    gutter::{self, Gutter},
    Document, DocumentId, ViewId,
};
use helix_core::{
    graphemes::{grapheme_width, RopeGraphemes},
    line_ending::line_end_char_index,
    visual_coords_at_pos, Position, RopeSlice, Selection,
};

use std::fmt;

type Jump = (DocumentId, Selection);

#[derive(Debug, Clone)]
pub struct JumpList {
    jumps: Vec<Jump>,
    current: usize,
}

impl JumpList {
    pub fn new(initial: Jump) -> Self {
        Self {
            jumps: vec![initial],
            current: 0,
        }
    }

    pub fn push(&mut self, jump: Jump) {
        self.jumps.truncate(self.current);
        // don't push duplicates
        if self.jumps.last() != Some(&jump) {
            self.jumps.push(jump);
            self.current = self.jumps.len();
        }
    }

    pub fn forward(&mut self, count: usize) -> Option<&Jump> {
        if self.current + count < self.jumps.len() {
            self.current += count;
            self.jumps.get(self.current)
        } else {
            None
        }
    }

    // Taking view and doc to prevent unnecessary cloning when jump is not required.
    pub fn backward(&mut self, view_id: ViewId, doc: &mut Document, count: usize) -> Option<&Jump> {
        if let Some(current) = self.current.checked_sub(count) {
            if self.current == self.jumps.len() {
                let jump = (doc.id(), doc.selection(view_id).clone());
                self.push(jump);
            }
            self.current = current;
            self.jumps.get(self.current)
        } else {
            None
        }
    }

    pub fn remove(&mut self, doc_id: &DocumentId) {
        self.jumps.retain(|(other_id, _)| other_id != doc_id);
    }
}

pub struct View {
    pub id: ViewId,
    pub offset: Position,
    pub area: Rect,
    pub doc: DocumentId,
    pub jumps: JumpList,
    // documents accessed from this view from the oldest one to last viewed one
    pub docs_access_history: Vec<DocumentId>,
    /// the last modified files before the current one
    /// ordered from most frequent to least frequent
    // uses two docs because we want to be able to swap between the
    // two last modified docs which we need to manually keep track of
    pub last_modified_docs: [Option<DocumentId>; 2],
    /// used to store previous selections of tree-sitter objecs
    pub object_selections: Vec<Selection>,
    pub gutters: Vec<(Gutter, usize)>,
}

impl fmt::Debug for View {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("View")
            .field("id", &self.id)
            .field("area", &self.area)
            .field("doc", &self.doc)
            .finish()
    }
}

impl View {
    pub fn new(doc: DocumentId, gutter_types: Vec<crate::editor::GutterType>) -> Self {
        let mut gutters: Vec<(Gutter, usize)> = vec![];
        use crate::editor::GutterType;
        for gutter_type in &gutter_types {
            match gutter_type {
                GutterType::Diagnostics => gutters.push((gutter::diagnostics_or_breakpoints, 1)),
                GutterType::LineNumbers => gutters.push((gutter::line_numbers, 5)),
            }
        }
        Self {
            id: ViewId::default(),
            doc,
            offset: Position::new(0, 0),
            area: Rect::default(), // will get calculated upon inserting into tree
            jumps: JumpList::new((doc, Selection::point(0))), // TODO: use actual sel
            docs_access_history: Vec::new(),
            last_modified_docs: [None, None],
            object_selections: Vec::new(),
            gutters,
        }
    }

    pub fn add_to_history(&mut self, id: DocumentId) {
        if let Some(pos) = self.docs_access_history.iter().position(|&doc| doc == id) {
            self.docs_access_history.remove(pos);
        }
        self.docs_access_history.push(id);
    }

    pub fn inner_area(&self) -> Rect {
        // TODO: cache this
        let offset = self
            .gutters
            .iter()
            .map(|(_, width)| *width as u16)
            .sum::<u16>()
            + 1; // +1 for some space between gutters and line
        self.area.clip_left(offset).clip_bottom(1) // -1 for statusline
    }

    //
    pub fn offset_coords_to_in_view(
        &self,
        doc: &Document,
        scrolloff: usize,
    ) -> Option<(usize, usize)> {
        let cursor = doc
            .selection(self.id)
            .primary()
            .cursor(doc.text().slice(..));

        let Position { col, row: line } =
            visual_coords_at_pos(doc.text().slice(..), cursor, doc.tab_width());

        let inner_area = self.inner_area();
        let last_line = (self.offset.row + inner_area.height as usize).saturating_sub(1);

        // - 1 so we have at least one gap in the middle.
        // a height of 6 with padding of 3 on each side will keep shifting the view back and forth
        // as we type
        let scrolloff = scrolloff.min(inner_area.height.saturating_sub(1) as usize / 2);

        let last_col = self.offset.col + inner_area.width.saturating_sub(1) as usize;

        let row = if line > last_line.saturating_sub(scrolloff) {
            // scroll down
            self.offset.row + line - (last_line.saturating_sub(scrolloff))
        } else if line < self.offset.row + scrolloff {
            // scroll up
            line.saturating_sub(scrolloff)
        } else {
            self.offset.row
        };

        let col = if col > last_col.saturating_sub(scrolloff) {
            // scroll right
            self.offset.col + col - (last_col.saturating_sub(scrolloff))
        } else if col < self.offset.col + scrolloff {
            // scroll left
            col.saturating_sub(scrolloff)
        } else {
            self.offset.col
        };
        if row == self.offset.row && col == self.offset.col {
            None
        } else {
            Some((row, col))
        }
    }

    pub fn ensure_cursor_in_view(&mut self, doc: &Document, scrolloff: usize) {
        if let Some((row, col)) = self.offset_coords_to_in_view(doc, scrolloff) {
            self.offset.row = row;
            self.offset.col = col;
        }
    }

    pub fn is_cursor_in_view(&mut self, doc: &Document, scrolloff: usize) -> bool {
        self.offset_coords_to_in_view(doc, scrolloff).is_none()
    }

    /// Calculates the last visible line on screen
    #[inline]
    pub fn last_line(&self, doc: &Document) -> usize {
        let height = self.inner_area().height;
        std::cmp::min(
            // Saturating subs to make it inclusive zero indexing.
            (self.offset.row + height as usize).saturating_sub(1),
            doc.text().len_lines().saturating_sub(1),
        )
    }

    /// Translates a document position to an absolute position in the terminal.
    /// Returns a (line, col) position if the position is visible on screen.
    // TODO: Could return width as well for the character width at cursor.
    pub fn screen_coords_at_pos(
        &self,
        doc: &Document,
        text: RopeSlice,
        pos: usize,
    ) -> Option<Position> {
        let line = text.char_to_line(pos);

        if line < self.offset.row || line > self.last_line(doc) {
            // Line is not visible on screen
            return None;
        }

        let tab_width = doc.tab_width();
        // TODO: visual_coords_at_pos also does char_to_line which we ignore, can we reuse the call?
        let Position { col, .. } = visual_coords_at_pos(text, pos, tab_width);

        // It is possible for underflow to occur if the buffer length is larger than the terminal width.
        let row = line.saturating_sub(self.offset.row);
        let col = col.saturating_sub(self.offset.col);

        Some(Position::new(row, col))
    }

    pub fn text_pos_at_screen_coords(
        &self,
        text: &RopeSlice,
        row: u16,
        column: u16,
        tab_width: usize,
    ) -> Option<usize> {
        let inner = self.inner_area();
        // 1 for status
        if row < inner.top() || row >= inner.bottom() {
            return None;
        }

        if column < inner.left() || column > inner.right() {
            return None;
        }

        let line_number = (row - inner.y) as usize + self.offset.row;

        if line_number > text.len_lines() - 1 {
            return Some(text.len_chars());
        }

        let mut pos = text.line_to_char(line_number);

        let current_line = text.line(line_number);

        let target = (column - inner.x) as usize + self.offset.col;
        let mut col = 0;

        // TODO: extract this part as pos_at_visual_coords
        for grapheme in RopeGraphemes::new(current_line) {
            if col >= target {
                break;
            }

            let width = if grapheme == "\t" {
                tab_width - (col % tab_width)
            } else {
                let grapheme = Cow::from(grapheme);
                grapheme_width(&grapheme)
            };

            // If pos is in the middle of a wider grapheme (tab for example)
            // return the starting offset.
            if col + width > target {
                break;
            }

            col += width;
            // TODO: use byte pos that converts back to char pos?
            pos += grapheme.chars().count();
        }

        Some(pos.min(line_end_char_index(&text.slice(..), line_number)))
    }

    /// Translates a screen position to position in the text document.
    /// Returns a usize typed position in bounds of the text if found in this view, None if out of view.
    pub fn pos_at_screen_coords(&self, doc: &Document, row: u16, column: u16) -> Option<usize> {
        self.text_pos_at_screen_coords(&doc.text().slice(..), row, column, doc.tab_width())
    }

    /// Translates screen coordinates into coordinates on the gutter of the view.
    /// Returns a tuple of usize typed line and column numbers starting with 0.
    /// Returns None if coordinates are not on the gutter.
    pub fn gutter_coords_at_screen_coords(&self, row: u16, column: u16) -> Option<Position> {
        // 1 for status
        if row < self.area.top() || row >= self.area.bottom() {
            return None;
        }

        if column < self.area.left() || column > self.area.right() {
            return None;
        }

        Some(Position::new(
            (row - self.area.top()) as usize,
            (column - self.area.left()) as usize,
        ))
    }

    // pub fn traverse<F>(&self, text: RopeSlice, start: usize, end: usize, fun: F)
    // where
    //     F: Fn(usize, usize),
    // {
    //     let start = self.screen_coords_at_pos(text, start);
    //     let end = self.screen_coords_at_pos(text, end);

    //     match (start, end) {
    //         // fully on screen
    //         (Some(start), Some(end)) => {
    //             // we want to calculate ends of lines for each char..
    //         }
    //         // from start to end of screen
    //         (Some(start), None) => {}
    //         // from start of screen to end
    //         (None, Some(end)) => {}
    //         // not on screen
    //         (None, None) => return,
    //     }
    // }
}

#[cfg(test)]
mod tests {
    use super::*;
    use helix_core::Rope;
    const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter
    const OFFSET_WITHOUT_LINE_NUMBERS: u16 = 2; // 1 diagnostic + 1 gutter
                                                // const OFFSET: u16 = GUTTERS.iter().map(|(_, width)| *width as u16).sum();
    use crate::editor::GutterType;

    #[test]
    fn test_text_pos_at_screen_coords() {
        let mut view = View::new(
            DocumentId::default(),
            vec![GutterType::Diagnostics, GutterType::LineNumbers],
        );
        view.area = Rect::new(40, 40, 40, 40);
        let rope = Rope::from_str("abc\n\tdef");
        let text = rope.slice(..);

        assert_eq!(view.text_pos_at_screen_coords(&text, 40, 2, 4), None);

        assert_eq!(view.text_pos_at_screen_coords(&text, 40, 41, 4), None);

        assert_eq!(view.text_pos_at_screen_coords(&text, 0, 2, 4), None);

        assert_eq!(view.text_pos_at_screen_coords(&text, 0, 49, 4), None);

        assert_eq!(view.text_pos_at_screen_coords(&text, 0, 41, 4), None);

        assert_eq!(view.text_pos_at_screen_coords(&text, 40, 81, 4), None);

        assert_eq!(view.text_pos_at_screen_coords(&text, 78, 41, 4), None);

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 3, 4),
            Some(3)
        );

        assert_eq!(view.text_pos_at_screen_coords(&text, 40, 80, 4), Some(3));

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 41, 40 + OFFSET + 1, 4),
            Some(4)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 41, 40 + OFFSET + 4, 4),
            Some(5)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 41, 40 + OFFSET + 7, 4),
            Some(8)
        );

        assert_eq!(view.text_pos_at_screen_coords(&text, 41, 80, 4), Some(8));
    }

    #[test]
    fn test_text_pos_at_screen_coords_without_line_numbers_gutter() {
        let mut view = View::new(DocumentId::default(), vec![GutterType::Diagnostics]);
        view.area = Rect::new(40, 40, 40, 40);
        let rope = Rope::from_str("abc\n\tdef");
        let text = rope.slice(..);
        assert_eq!(
            view.text_pos_at_screen_coords(&text, 41, 40 + OFFSET_WITHOUT_LINE_NUMBERS + 1, 4),
            Some(4)
        );
    }

    #[test]
    fn test_text_pos_at_screen_coords_without_any_gutters() {
        let mut view = View::new(DocumentId::default(), vec![]);
        view.area = Rect::new(40, 40, 40, 40);
        let rope = Rope::from_str("abc\n\tdef");
        let text = rope.slice(..);
        assert_eq!(
            view.text_pos_at_screen_coords(&text, 41, 40 + 1, 4),
            Some(4)
        );
    }

    #[test]
    fn test_text_pos_at_screen_coords_cjk() {
        let mut view = View::new(
            DocumentId::default(),
            vec![GutterType::Diagnostics, GutterType::LineNumbers],
        );
        view.area = Rect::new(40, 40, 40, 40);
        let rope = Rope::from_str("Hi! こんにちは皆さん");
        let text = rope.slice(..);

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET, 4),
            Some(0)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 4, 4),
            Some(4)
        );
        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 5, 4),
            Some(4)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 6, 4),
            Some(5)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 7, 4),
            Some(5)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 8, 4),
            Some(6)
        );
    }

    #[test]
    fn test_text_pos_at_screen_coords_graphemes() {
        let mut view = View::new(
            DocumentId::default(),
            vec![GutterType::Diagnostics, GutterType::LineNumbers],
        );
        view.area = Rect::new(40, 40, 40, 40);
        let rope = Rope::from_str("Hèl̀l̀ò world!");
        let text = rope.slice(..);

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET, 4),
            Some(0)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 1, 4),
            Some(1)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 2, 4),
            Some(3)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 3, 4),
            Some(5)
        );

        assert_eq!(
            view.text_pos_at_screen_coords(&text, 40, 40 + OFFSET + 4, 4),
            Some(7)
        );
    }
}