autoscroll.rs

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