Skip to main content

hjkl_buffer/
viewport.rs

1use crate::{Position, Wrap};
2
3/// Where the buffer is scrolled to and how big the visible area is.
4///
5/// `Viewport` is an **input** to [`crate::Buffer::ensure_cursor_visible`],
6/// not a derived value. The host writes `top_row`, `top_col`, `width`, and
7/// `height` per render frame; the buffer clamps the cursor inside the
8/// declared area.
9///
10/// `top_row` and `top_col` are the first visible row / column; `top_col` is
11/// a char index, matching [`Position`].
12///
13/// `wrap` and `text_width` together drive soft-wrap-aware scrolling and
14/// motion. `text_width` is the cell width of the text area (i.e. `width`
15/// minus any gutter the host renders) so the buffer can compute screen-line
16/// splits without duplicating gutter logic.
17///
18/// `scroll_off` is not a field on `Viewport` itself; the host computes it
19/// and adjusts `top_row` before handing the viewport to
20/// [`crate::Buffer::ensure_cursor_visible`].
21///
22/// [`Wrap::None`] / [`crate::Wrap::Char`] / [`crate::Wrap::Word`] change
23/// which screen-row arithmetic the buffer uses. Switching mid-session is
24/// supported but the host must call
25/// [`crate::Buffer::ensure_cursor_visible`] afterwards.
26#[derive(Debug, Clone, Copy, Default)]
27pub struct Viewport {
28    pub top_row: usize,
29    pub top_col: usize,
30    pub width: u16,
31    pub height: u16,
32    /// Soft-wrap mode the renderer + scroll math is using. Default
33    /// is [`Wrap::None`] (no wrap, horizontal scroll via `top_col`).
34    pub wrap: Wrap,
35    /// Cell width of the text area (after the host's gutter is
36    /// subtracted from the editor area). Used by wrap-aware scroll
37    /// and motion code; ignored when `wrap == Wrap::None`. Set to 0
38    /// before the first frame; wrap math falls back to no-op then.
39    pub text_width: u16,
40    /// Cells per `\t` expansion stop. The renderer uses this to align
41    /// tab characters; cursor_screen_pos uses it to map char column to
42    /// visual column. `0` is treated as the renderer's fallback (4) so
43    /// hosts that don't publish a value still render legibly.
44    pub tab_width: u16,
45}
46
47impl Viewport {
48    pub const fn new() -> Self {
49        Self {
50            top_row: 0,
51            top_col: 0,
52            width: 0,
53            height: 0,
54            wrap: Wrap::None,
55            text_width: 0,
56            tab_width: 0,
57        }
58    }
59
60    /// Effective tab width — falls back to 4 when `tab_width == 0` so
61    /// uninitialized viewports still expand tabs sensibly.
62    pub fn effective_tab_width(self) -> usize {
63        if self.tab_width == 0 {
64            4
65        } else {
66            self.tab_width as usize
67        }
68    }
69
70    /// Last document row that's currently on screen (inclusive).
71    /// Returns `top_row` when `height == 0` so callers don't have
72    /// to special-case the pre-first-draw state.
73    pub fn bottom_row(self) -> usize {
74        self.top_row
75            .saturating_add((self.height as usize).max(1).saturating_sub(1))
76    }
77
78    /// True when `pos` lies inside the current viewport rect.
79    pub fn contains(self, pos: Position) -> bool {
80        let in_rows = pos.row >= self.top_row && pos.row <= self.bottom_row();
81        let in_cols = pos.col >= self.top_col
82            && pos.col < self.top_col.saturating_add((self.width as usize).max(1));
83        in_rows && in_cols
84    }
85
86    /// Adjust `top_row` / `top_col` so `pos` is visible, scrolling by
87    /// the minimum amount needed. Used after motions and after
88    /// content edits that move the cursor.
89    pub fn ensure_visible(&mut self, pos: Position) {
90        if self.height == 0 || self.width == 0 {
91            return;
92        }
93        let rows = self.height as usize;
94        if pos.row < self.top_row {
95            self.top_row = pos.row;
96        } else if pos.row >= self.top_row + rows {
97            self.top_row = pos.row + 1 - rows;
98        }
99        let cols = self.width as usize;
100        if pos.col < self.top_col {
101            self.top_col = pos.col;
102        } else if pos.col >= self.top_col + cols {
103            self.top_col = pos.col + 1 - cols;
104        }
105    }
106}
107
108/// `true` when a viewport scroll from `prev_top` to `cur_top` lands
109/// past the over-provisioned band computed by [`over_provisioned_range`].
110///
111/// The over-provisioned range extends `±viewport_height` rows around
112/// the viewport, so a jump of MORE than `viewport_height` rows in either
113/// direction guarantees the new viewport sits on un-cached territory —
114/// hosts use this signal to decide whether to block briefly on a fresh
115/// parse (avoids the un-highlighted flash on `gg` / `G` / `<C-d>` / `:N`).
116///
117/// Host-agnostic: same shape as [`over_provisioned_range`], pure math.
118pub fn is_big_viewport_jump(prev_top: usize, cur_top: usize, viewport_height: usize) -> bool {
119    prev_top.abs_diff(cur_top) > viewport_height
120}
121
122/// Compute an **over-provisioned** row range for ahead-of-scroll work
123/// (syntax highlight, diagnostics gather, etc.): one viewport above +
124/// the current viewport + one viewport below, clamped to `[0, line_count)`.
125///
126/// Host-agnostic: takes only document line counts and viewport extents,
127/// no terminal cells or pixels. Future GUI hosts (floem, web, …) call
128/// the same function with their own viewport dimensions.
129///
130/// Returns `(top, height)` satisfying:
131/// - `top <= viewport_top`
132/// - `top + height >= viewport_top + viewport_height` (when room exists)
133/// - `top + height <= line_count` (clamped at the bottom edge)
134/// - `height <= viewport_height * 3`
135///
136/// Why 3×: gives the worker enough margin that a fast scroll within one
137/// viewport-height stays inside an already-parsed region. Halving (2×)
138/// is too tight in practice; quadrupling adds cost without payoff.
139pub fn over_provisioned_range(
140    viewport_top: usize,
141    viewport_height: usize,
142    line_count: usize,
143) -> (usize, usize) {
144    let top = viewport_top.saturating_sub(viewport_height);
145    let max_height = line_count.saturating_sub(top);
146    let height = viewport_height.saturating_mul(3).min(max_height);
147    (top, height)
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn vp(top_row: usize, height: u16) -> Viewport {
155        Viewport {
156            top_row,
157            top_col: 0,
158            width: 80,
159            height,
160            wrap: Wrap::None,
161            text_width: 80,
162            tab_width: 0,
163        }
164    }
165
166    #[test]
167    fn contains_inside_window() {
168        let v = vp(10, 5);
169        assert!(v.contains(Position::new(10, 0)));
170        assert!(v.contains(Position::new(14, 79)));
171    }
172
173    #[test]
174    fn contains_outside_window() {
175        let v = vp(10, 5);
176        assert!(!v.contains(Position::new(9, 0)));
177        assert!(!v.contains(Position::new(15, 0)));
178        assert!(!v.contains(Position::new(12, 80)));
179    }
180
181    #[test]
182    fn ensure_visible_scrolls_down() {
183        let mut v = vp(0, 5);
184        v.ensure_visible(Position::new(10, 0));
185        assert_eq!(v.top_row, 6);
186    }
187
188    #[test]
189    fn ensure_visible_scrolls_up() {
190        let mut v = vp(20, 5);
191        v.ensure_visible(Position::new(15, 0));
192        assert_eq!(v.top_row, 15);
193    }
194
195    #[test]
196    fn ensure_visible_no_scroll_when_inside() {
197        let mut v = vp(10, 5);
198        v.ensure_visible(Position::new(12, 4));
199        assert_eq!(v.top_row, 10);
200    }
201
202    #[test]
203    fn ensure_visible_zero_dim_is_noop() {
204        let mut v = Viewport::default();
205        v.ensure_visible(Position::new(100, 100));
206        assert_eq!(v.top_row, 0);
207        assert_eq!(v.top_col, 0);
208    }
209
210    // ── over_provisioned_range (host-agnostic ahead-of-scroll helper) ──────
211
212    #[test]
213    fn over_provisioned_range_middle_of_buffer() {
214        // 1000-line buffer, viewport at row 100, height 30.
215        // Expect: top = 100 - 30 = 70, height = 90 (3 viewports).
216        let (top, height) = over_provisioned_range(100, 30, 1000);
217        assert_eq!(top, 70);
218        assert_eq!(height, 90);
219    }
220
221    #[test]
222    fn over_provisioned_range_top_of_buffer() {
223        // Near the top: viewport at row 5, height 30 → top saturates at 0,
224        // height tries 90 but the buffer is only 1000 rows from 0 so it can
225        // fit the full 90.
226        let (top, height) = over_provisioned_range(5, 30, 1000);
227        assert_eq!(top, 0);
228        assert_eq!(height, 90);
229    }
230
231    #[test]
232    fn over_provisioned_range_bottom_of_buffer_clamps_height() {
233        // 50-line buffer, viewport at row 30, height 30 → top = 0, but
234        // height is capped at line_count - top = 50, not 90.
235        let (top, height) = over_provisioned_range(30, 30, 50);
236        assert_eq!(top, 0);
237        assert_eq!(height, 50);
238    }
239
240    #[test]
241    fn over_provisioned_range_zero_viewport_height() {
242        // Defensive: zero-height viewport returns zero-height oversize.
243        let (top, height) = over_provisioned_range(10, 0, 100);
244        assert_eq!(top, 10);
245        assert_eq!(height, 0);
246    }
247
248    #[test]
249    fn over_provisioned_range_zero_line_count() {
250        // Empty buffer — everything zero.
251        let (top, height) = over_provisioned_range(0, 30, 0);
252        assert_eq!(top, 0);
253        assert_eq!(height, 0);
254    }
255
256    #[test]
257    fn is_big_viewport_jump_within_one_height_is_not_big() {
258        // Scroll within ±1 viewport-height stays in the over-provisioned band.
259        assert!(!is_big_viewport_jump(100, 100, 30));
260        assert!(!is_big_viewport_jump(100, 130, 30));
261        assert!(!is_big_viewport_jump(100, 70, 30));
262    }
263
264    #[test]
265    fn is_big_viewport_jump_past_one_height_is_big() {
266        // gg from row 500 to row 0 — clearly past 30.
267        assert!(is_big_viewport_jump(500, 0, 30));
268        // G to last row from row 0.
269        assert!(is_big_viewport_jump(0, 9999, 30));
270        // Exactly one height + 1 row is the boundary (jump > viewport_height).
271        assert!(is_big_viewport_jump(0, 31, 30));
272        // Exactly viewport_height is NOT a big jump (the row at the band's edge).
273        assert!(!is_big_viewport_jump(0, 30, 30));
274    }
275
276    #[test]
277    fn over_provisioned_range_covers_viewport() {
278        // The over-provisioned range MUST cover the original viewport when
279        // there's enough buffer to do so — that's the load-bearing invariant
280        // (the renderer paints rows in the original viewport, the cache holds
281        // ones above + below).
282        let viewport_top = 100;
283        let viewport_height = 30;
284        let line_count = 1000;
285        let (top, height) = over_provisioned_range(viewport_top, viewport_height, line_count);
286        assert!(top <= viewport_top, "top must not exceed viewport_top");
287        assert!(
288            top + height >= viewport_top + viewport_height,
289            "oversize range must end at or past the viewport's bottom"
290        );
291        assert!(
292            top + height <= line_count,
293            "oversize range must stay inside the buffer"
294        );
295    }
296}