autoscroll.rs

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