autoscroll.rs

  1use crate::{
  2    DisplayRow, Editor, EditorMode, LineWithInvisibles, RowExt, SelectionEffects,
  3    display_map::ToDisplayPoint,
  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
102impl Editor {
103    pub fn autoscroll_request(&self) -> Option<Autoscroll> {
104        self.scroll_manager.autoscroll_request()
105    }
106
107    pub fn autoscroll_vertically(
108        &mut self,
109        bounds: Bounds<Pixels>,
110        line_height: Pixels,
111        max_scroll_top: f32,
112        window: &mut Window,
113        cx: &mut Context<Editor>,
114    ) -> bool {
115        let viewport_height = bounds.size.height;
116        let visible_lines = 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            if scroll_position.y != 0. {
122                scroll_position.y += (bounds.top() - last_bounds.top()) / line_height;
123                if scroll_position.y < 0. {
124                    scroll_position.y = 0.;
125                }
126            }
127        }
128        if scroll_position.y > max_scroll_top {
129            scroll_position.y = max_scroll_top;
130        }
131
132        if original_y != scroll_position.y {
133            self.set_scroll_position(scroll_position, window, cx);
134        }
135
136        let Some((autoscroll, local)) = self.scroll_manager.autoscroll_request.take() else {
137            return false;
138        };
139
140        let mut target_top;
141        let mut target_bottom;
142        if let Some(first_highlighted_row) =
143            self.highlighted_display_row_for_autoscroll(&display_map)
144        {
145            target_top = first_highlighted_row.as_f32();
146            target_bottom = target_top + 1.;
147        } else {
148            let selections = self.selections.all::<Point>(cx);
149
150            target_top = selections
151                .first()
152                .unwrap()
153                .head()
154                .to_display_point(&display_map)
155                .row()
156                .as_f32();
157            target_bottom = selections
158                .last()
159                .unwrap()
160                .head()
161                .to_display_point(&display_map)
162                .row()
163                .next_row()
164                .as_f32();
165
166            let selections_fit = target_bottom - target_top <= visible_lines;
167            if matches!(
168                autoscroll,
169                Autoscroll::Strategy(AutoscrollStrategy::Newest, _)
170            ) || (matches!(autoscroll, Autoscroll::Strategy(AutoscrollStrategy::Fit, _))
171                && !selections_fit)
172            {
173                let newest_selection_top = selections
174                    .iter()
175                    .max_by_key(|s| s.id)
176                    .unwrap()
177                    .head()
178                    .to_display_point(&display_map)
179                    .row()
180                    .as_f32();
181                target_top = newest_selection_top;
182                target_bottom = newest_selection_top + 1.;
183            }
184        }
185
186        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
187            0.
188        } else {
189            ((visible_lines - (target_bottom - target_top)) / 2.0).floor()
190        };
191
192        let strategy = match autoscroll {
193            Autoscroll::Strategy(strategy, _) => strategy,
194            Autoscroll::Next => {
195                let last_autoscroll = &self.scroll_manager.last_autoscroll;
196                if let Some(last_autoscroll) = last_autoscroll {
197                    if self.scroll_manager.anchor.offset == last_autoscroll.0
198                        && target_top == last_autoscroll.1
199                        && target_bottom == last_autoscroll.2
200                    {
201                        last_autoscroll.3.next()
202                    } else {
203                        AutoscrollStrategy::default()
204                    }
205                } else {
206                    AutoscrollStrategy::default()
207                }
208            }
209        };
210        if let Autoscroll::Strategy(_, Some(anchor)) = autoscroll {
211            target_top = anchor.to_display_point(&display_map).row().as_f32();
212            target_bottom = target_top + 1.;
213        }
214
215        match strategy {
216            AutoscrollStrategy::Fit | AutoscrollStrategy::Newest => {
217                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
218                let target_top = (target_top - margin).max(0.0);
219                let target_bottom = target_bottom + margin;
220                let start_row = scroll_position.y;
221                let end_row = start_row + visible_lines;
222
223                let needs_scroll_up = target_top < start_row;
224                let needs_scroll_down = target_bottom >= end_row;
225
226                if needs_scroll_up && !needs_scroll_down {
227                    scroll_position.y = target_top;
228                    self.set_scroll_position_internal(scroll_position, local, true, window, cx);
229                }
230                if !needs_scroll_up && needs_scroll_down {
231                    scroll_position.y = target_bottom - visible_lines;
232                    self.set_scroll_position_internal(scroll_position, local, true, window, cx);
233                }
234            }
235            AutoscrollStrategy::Center => {
236                scroll_position.y = (target_top - margin).max(0.0);
237                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
238            }
239            AutoscrollStrategy::Focused => {
240                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
241                scroll_position.y = (target_top - margin).max(0.0);
242                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
243            }
244            AutoscrollStrategy::Top => {
245                scroll_position.y = (target_top).max(0.0);
246                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
247            }
248            AutoscrollStrategy::Bottom => {
249                scroll_position.y = (target_bottom - visible_lines).max(0.0);
250                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
251            }
252            AutoscrollStrategy::TopRelative(lines) => {
253                scroll_position.y = target_top - lines as f32;
254                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
255            }
256            AutoscrollStrategy::BottomRelative(lines) => {
257                scroll_position.y = target_bottom + lines as f32;
258                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
259            }
260        }
261
262        self.scroll_manager.last_autoscroll = Some((
263            self.scroll_manager.anchor.offset,
264            target_top,
265            target_bottom,
266            strategy,
267        ));
268
269        true
270    }
271
272    pub(crate) fn autoscroll_horizontally(
273        &mut self,
274        start_row: DisplayRow,
275        viewport_width: Pixels,
276        scroll_width: Pixels,
277        em_advance: Pixels,
278        layouts: &[LineWithInvisibles],
279        window: &mut Window,
280        cx: &mut Context<Self>,
281    ) -> bool {
282        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
283        let selections = self.selections.all::<Point>(cx);
284        let mut scroll_position = self.scroll_manager.scroll_position(&display_map);
285
286        let mut target_left;
287        let mut target_right;
288
289        if self
290            .highlighted_display_row_for_autoscroll(&display_map)
291            .is_none()
292        {
293            target_left = px(f32::INFINITY);
294            target_right = px(0.);
295            for selection in selections {
296                let head = selection.head().to_display_point(&display_map);
297                if head.row() >= start_row
298                    && head.row() < DisplayRow(start_row.0 + layouts.len() as u32)
299                {
300                    let start_column = head.column();
301                    let end_column = cmp::min(display_map.line_len(head.row()), head.column());
302                    target_left = target_left.min(
303                        layouts[head.row().minus(start_row) as usize]
304                            .x_for_index(start_column as usize)
305                            + self.gutter_dimensions.margin,
306                    );
307                    target_right = target_right.max(
308                        layouts[head.row().minus(start_row) as usize]
309                            .x_for_index(end_column as usize)
310                            + em_advance,
311                    );
312                }
313            }
314        } else {
315            target_left = px(0.);
316            target_right = px(0.);
317        }
318
319        target_right = target_right.min(scroll_width);
320
321        if target_right - target_left > viewport_width {
322            return false;
323        }
324
325        let scroll_left = self.scroll_manager.anchor.offset.x * em_advance;
326        let scroll_right = scroll_left + viewport_width;
327
328        if target_left < scroll_left {
329            scroll_position.x = target_left / em_advance;
330            self.set_scroll_position_internal(scroll_position, true, true, window, cx);
331            true
332        } else if target_right > scroll_right {
333            scroll_position.x = (target_right - viewport_width) / em_advance;
334            self.set_scroll_position_internal(scroll_position, true, true, window, cx);
335            true
336        } else {
337            false
338        }
339    }
340
341    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut Context<Self>) {
342        self.scroll_manager.autoscroll_request = Some((autoscroll, true));
343        cx.notify();
344    }
345
346    pub(crate) fn request_autoscroll_remotely(
347        &mut self,
348        autoscroll: Autoscroll,
349        cx: &mut Context<Self>,
350    ) {
351        self.scroll_manager.autoscroll_request = Some((autoscroll, false));
352        cx.notify();
353    }
354}