autoscroll.rs

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