autoscroll.rs

  1use std::{any::TypeId, cmp, f32};
  2
  3use collections::HashSet;
  4use gpui::{px, Bounds, Pixels, ViewContext};
  5use language::Point;
  6
  7use crate::{
  8    display_map::ToDisplayPoint, DiffRowHighlight, DisplayRow, Editor, EditorMode,
  9    LineWithInvisibles, RowExt,
 10};
 11
 12#[derive(PartialEq, Eq, Clone, Copy)]
 13pub enum Autoscroll {
 14    Next,
 15    Strategy(AutoscrollStrategy),
 16}
 17
 18impl Autoscroll {
 19    /// scrolls the minimal amount to (try) and fit all cursors onscreen
 20    pub fn fit() -> Self {
 21        Self::Strategy(AutoscrollStrategy::Fit)
 22    }
 23
 24    /// scrolls the minimal amount to fit the newest cursor
 25    pub fn newest() -> Self {
 26        Self::Strategy(AutoscrollStrategy::Newest)
 27    }
 28
 29    /// scrolls so the newest cursor is vertically centered
 30    pub fn center() -> Self {
 31        Self::Strategy(AutoscrollStrategy::Center)
 32    }
 33
 34    /// scrolls so the neweset cursor is near the top
 35    /// (offset by vertical_scroll_margin)
 36    pub fn focused() -> Self {
 37        Self::Strategy(AutoscrollStrategy::Focused)
 38    }
 39    /// Scrolls so that the newest cursor is roughly an n-th line from the top.
 40    pub fn top_relative(n: usize) -> Self {
 41        Self::Strategy(AutoscrollStrategy::TopRelative(n))
 42    }
 43}
 44
 45#[derive(PartialEq, Eq, Default, Clone, Copy)]
 46pub enum AutoscrollStrategy {
 47    Fit,
 48    Newest,
 49    #[default]
 50    Center,
 51    Focused,
 52    Top,
 53    Bottom,
 54    TopRelative(usize),
 55}
 56
 57impl AutoscrollStrategy {
 58    fn next(&self) -> Self {
 59        match self {
 60            AutoscrollStrategy::Center => AutoscrollStrategy::Top,
 61            AutoscrollStrategy::Top => AutoscrollStrategy::Bottom,
 62            _ => AutoscrollStrategy::Center,
 63        }
 64    }
 65}
 66
 67impl Editor {
 68    pub fn autoscroll_requested(&self) -> bool {
 69        self.scroll_manager.autoscroll_requested()
 70    }
 71
 72    pub fn autoscroll_vertically(
 73        &mut self,
 74        bounds: Bounds<Pixels>,
 75        line_height: Pixels,
 76        cx: &mut ViewContext<Editor>,
 77    ) -> bool {
 78        let viewport_height = bounds.size.height;
 79        let visible_lines = viewport_height / line_height;
 80        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 81        let mut scroll_position = self.scroll_manager.scroll_position(&display_map);
 82        let original_y = scroll_position.y;
 83        if let Some(last_bounds) = self.expect_bounds_change.take() {
 84            if scroll_position.y != 0. {
 85                scroll_position.y += (bounds.top() - last_bounds.top()) / line_height;
 86                if scroll_position.y < 0. {
 87                    scroll_position.y = 0.;
 88                }
 89            }
 90        }
 91        let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 92            (display_map.max_point().row().as_f32() - visible_lines + 1.).max(0.)
 93        } else {
 94            display_map.max_point().row().as_f32()
 95        };
 96        if scroll_position.y > max_scroll_top {
 97            scroll_position.y = max_scroll_top;
 98        }
 99
100        if original_y != scroll_position.y {
101            self.set_scroll_position(scroll_position, cx);
102        }
103
104        let Some((autoscroll, local)) = self.scroll_manager.autoscroll_request.take() else {
105            return false;
106        };
107
108        let mut target_top;
109        let mut target_bottom;
110        if let Some(first_highlighted_row) = &self
111            .highlighted_display_rows(
112                HashSet::from_iter(Some(TypeId::of::<DiffRowHighlight>())),
113                cx,
114            )
115            .first_entry()
116        {
117            target_top = first_highlighted_row.key().as_f32();
118            target_bottom = target_top + 1.;
119        } else {
120            let selections = self.selections.all::<Point>(cx);
121            target_top = selections
122                .first()
123                .unwrap()
124                .head()
125                .to_display_point(&display_map)
126                .row()
127                .as_f32();
128            target_bottom = selections
129                .last()
130                .unwrap()
131                .head()
132                .to_display_point(&display_map)
133                .row()
134                .next_row()
135                .as_f32();
136
137            // If the selections can't all fit on screen, scroll to the newest.
138            if autoscroll == Autoscroll::newest()
139                || autoscroll == Autoscroll::fit() && target_bottom - target_top > visible_lines
140            {
141                let newest_selection_top = selections
142                    .iter()
143                    .max_by_key(|s| s.id)
144                    .unwrap()
145                    .head()
146                    .to_display_point(&display_map)
147                    .row()
148                    .as_f32();
149                target_top = newest_selection_top;
150                target_bottom = newest_selection_top + 1.;
151            }
152        }
153
154        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
155            0.
156        } else {
157            ((visible_lines - (target_bottom - target_top)) / 2.0).floor()
158        };
159
160        let strategy = match autoscroll {
161            Autoscroll::Strategy(strategy) => strategy,
162            Autoscroll::Next => {
163                let last_autoscroll = &self.scroll_manager.last_autoscroll;
164                if let Some(last_autoscroll) = last_autoscroll {
165                    if self.scroll_manager.anchor.offset == last_autoscroll.0
166                        && target_top == last_autoscroll.1
167                        && target_bottom == last_autoscroll.2
168                    {
169                        last_autoscroll.3.next()
170                    } else {
171                        AutoscrollStrategy::default()
172                    }
173                } else {
174                    AutoscrollStrategy::default()
175                }
176            }
177        };
178
179        match strategy {
180            AutoscrollStrategy::Fit | AutoscrollStrategy::Newest => {
181                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
182                let target_top = (target_top - margin).max(0.0);
183                let target_bottom = target_bottom + margin;
184                let start_row = scroll_position.y;
185                let end_row = start_row + visible_lines;
186
187                let needs_scroll_up = target_top < start_row;
188                let needs_scroll_down = target_bottom >= end_row;
189
190                if needs_scroll_up && !needs_scroll_down {
191                    scroll_position.y = target_top;
192                    self.set_scroll_position_internal(scroll_position, local, true, cx);
193                }
194                if !needs_scroll_up && needs_scroll_down {
195                    scroll_position.y = target_bottom - visible_lines;
196                    self.set_scroll_position_internal(scroll_position, local, true, cx);
197                }
198            }
199            AutoscrollStrategy::Center => {
200                scroll_position.y = (target_top - margin).max(0.0);
201                self.set_scroll_position_internal(scroll_position, local, true, cx);
202            }
203            AutoscrollStrategy::Focused => {
204                scroll_position.y =
205                    (target_top - self.scroll_manager.vertical_scroll_margin).max(0.0);
206                self.set_scroll_position_internal(scroll_position, local, true, cx);
207            }
208            AutoscrollStrategy::Top => {
209                scroll_position.y = (target_top).max(0.0);
210                self.set_scroll_position_internal(scroll_position, local, true, cx);
211            }
212            AutoscrollStrategy::Bottom => {
213                scroll_position.y = (target_bottom - visible_lines).max(0.0);
214                self.set_scroll_position_internal(scroll_position, local, true, cx);
215            }
216            AutoscrollStrategy::TopRelative(lines) => {
217                scroll_position.y = target_top - lines as f32;
218                self.set_scroll_position_internal(scroll_position, local, true, cx);
219            }
220        }
221
222        self.scroll_manager.last_autoscroll = Some((
223            self.scroll_manager.anchor.offset,
224            target_top,
225            target_bottom,
226            strategy,
227        ));
228
229        true
230    }
231
232    pub(crate) fn autoscroll_horizontally(
233        &mut self,
234        start_row: DisplayRow,
235        viewport_width: Pixels,
236        scroll_width: Pixels,
237        max_glyph_width: Pixels,
238        layouts: &[LineWithInvisibles],
239        cx: &mut ViewContext<Self>,
240    ) -> bool {
241        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
242        let selections = self.selections.all::<Point>(cx);
243
244        let mut target_left;
245        let mut target_right;
246
247        if self.highlighted_rows.is_empty() {
248            target_left = px(f32::INFINITY);
249            target_right = px(0.);
250            for selection in selections {
251                let head = selection.head().to_display_point(&display_map);
252                if head.row() >= start_row
253                    && head.row() < DisplayRow(start_row.0 + layouts.len() as u32)
254                {
255                    let start_column = head.column().saturating_sub(3);
256                    let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
257                    target_left = target_left.min(
258                        layouts[head.row().minus(start_row) as usize]
259                            .line
260                            .x_for_index(start_column as usize),
261                    );
262                    target_right = target_right.max(
263                        layouts[head.row().minus(start_row) as usize]
264                            .line
265                            .x_for_index(end_column as usize)
266                            + max_glyph_width,
267                    );
268                }
269            }
270        } else {
271            target_left = px(0.);
272            target_right = px(0.);
273        }
274
275        target_right = target_right.min(scroll_width);
276
277        if target_right - target_left > viewport_width {
278            return false;
279        }
280
281        let scroll_left = self.scroll_manager.anchor.offset.x * max_glyph_width;
282        let scroll_right = scroll_left + viewport_width;
283
284        if target_left < scroll_left {
285            self.scroll_manager.anchor.offset.x = target_left / max_glyph_width;
286            true
287        } else if target_right > scroll_right {
288            self.scroll_manager.anchor.offset.x = (target_right - viewport_width) / max_glyph_width;
289            true
290        } else {
291            false
292        }
293    }
294
295    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
296        self.scroll_manager.autoscroll_request = Some((autoscroll, true));
297        cx.notify();
298    }
299
300    pub(crate) fn request_autoscroll_remotely(
301        &mut self,
302        autoscroll: Autoscroll,
303        cx: &mut ViewContext<Self>,
304    ) {
305        self.scroll_manager.autoscroll_request = Some((autoscroll, false));
306        cx.notify();
307    }
308}