autoscroll.rs

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