autoscroll.rs

  1use std::{cmp, f32};
  2
  3use gpui::{px, Bounds, 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_requested(&self) -> bool {
 65        self.scroll_manager.autoscroll_requested()
 66    }
 67
 68    pub fn autoscroll_vertically(
 69        &mut self,
 70        bounds: Bounds<Pixels>,
 71        line_height: Pixels,
 72        cx: &mut ViewContext<Editor>,
 73    ) -> bool {
 74        let viewport_height = bounds.size.height;
 75        let visible_lines = viewport_height / line_height;
 76        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 77        let mut scroll_position = self.scroll_manager.scroll_position(&display_map);
 78        let original_y = scroll_position.y;
 79        if let Some(last_bounds) = self.expect_bounds_change.take() {
 80            if scroll_position.y != 0. {
 81                scroll_position.y += (bounds.top() - last_bounds.top()) / line_height;
 82                if scroll_position.y < 0. {
 83                    scroll_position.y = 0.;
 84                }
 85            }
 86        }
 87        let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 88            (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
 89        } else {
 90            display_map.max_point().row() as f32
 91        };
 92        if scroll_position.y > max_scroll_top {
 93            scroll_position.y = max_scroll_top;
 94        }
 95
 96        if original_y != scroll_position.y {
 97            self.set_scroll_position(scroll_position, cx);
 98        }
 99
100        let Some((autoscroll, local)) = self.scroll_manager.autoscroll_request.take() else {
101            return false;
102        };
103
104        let mut target_top;
105        let mut target_bottom;
106        if let Some(first_highlighted_row) = &self.highlighted_display_rows(cx).first_entry() {
107            target_top = *first_highlighted_row.key() as f32;
108            target_bottom = target_top + 1.;
109        } else {
110            let selections = self.selections.all::<Point>(cx);
111            target_top = selections
112                .first()
113                .unwrap()
114                .head()
115                .to_display_point(&display_map)
116                .row() as f32;
117            target_bottom = selections
118                .last()
119                .unwrap()
120                .head()
121                .to_display_point(&display_map)
122                .row() as f32
123                + 1.0;
124
125            // If the selections can't all fit on screen, scroll to the newest.
126            if autoscroll == Autoscroll::newest()
127                || autoscroll == Autoscroll::fit() && target_bottom - target_top > visible_lines
128            {
129                let newest_selection_top = selections
130                    .iter()
131                    .max_by_key(|s| s.id)
132                    .unwrap()
133                    .head()
134                    .to_display_point(&display_map)
135                    .row() as f32;
136                target_top = newest_selection_top;
137                target_bottom = newest_selection_top + 1.;
138            }
139        }
140
141        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
142            0.
143        } else {
144            ((visible_lines - (target_bottom - target_top)) / 2.0).floor()
145        };
146
147        let strategy = match autoscroll {
148            Autoscroll::Strategy(strategy) => strategy,
149            Autoscroll::Next => {
150                let last_autoscroll = &self.scroll_manager.last_autoscroll;
151                if let Some(last_autoscroll) = last_autoscroll {
152                    if self.scroll_manager.anchor.offset == last_autoscroll.0
153                        && target_top == last_autoscroll.1
154                        && target_bottom == last_autoscroll.2
155                    {
156                        last_autoscroll.3.next()
157                    } else {
158                        AutoscrollStrategy::default()
159                    }
160                } else {
161                    AutoscrollStrategy::default()
162                }
163            }
164        };
165
166        match strategy {
167            AutoscrollStrategy::Fit | AutoscrollStrategy::Newest => {
168                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
169                let target_top = (target_top - margin).max(0.0);
170                let target_bottom = target_bottom + margin;
171                let start_row = scroll_position.y;
172                let end_row = start_row + visible_lines;
173
174                let needs_scroll_up = target_top < start_row;
175                let needs_scroll_down = target_bottom >= end_row;
176
177                if needs_scroll_up && !needs_scroll_down {
178                    scroll_position.y = target_top;
179                    self.set_scroll_position_internal(scroll_position, local, true, cx);
180                }
181                if !needs_scroll_up && needs_scroll_down {
182                    scroll_position.y = target_bottom - visible_lines;
183                    self.set_scroll_position_internal(scroll_position, local, true, cx);
184                }
185            }
186            AutoscrollStrategy::Center => {
187                scroll_position.y = (target_top - margin).max(0.0);
188                self.set_scroll_position_internal(scroll_position, local, true, cx);
189            }
190            AutoscrollStrategy::Focused => {
191                scroll_position.y =
192                    (target_top - self.scroll_manager.vertical_scroll_margin).max(0.0);
193                self.set_scroll_position_internal(scroll_position, local, true, cx);
194            }
195            AutoscrollStrategy::Top => {
196                scroll_position.y = (target_top).max(0.0);
197                self.set_scroll_position_internal(scroll_position, local, true, cx);
198            }
199            AutoscrollStrategy::Bottom => {
200                scroll_position.y = (target_bottom - visible_lines).max(0.0);
201                self.set_scroll_position_internal(scroll_position, local, true, cx);
202            }
203            AutoscrollStrategy::TopRelative(lines) => {
204                scroll_position.y = target_top - lines as f32;
205                self.set_scroll_position_internal(scroll_position, local, true, cx);
206            }
207        }
208
209        self.scroll_manager.last_autoscroll = Some((
210            self.scroll_manager.anchor.offset,
211            target_top,
212            target_bottom,
213            strategy,
214        ));
215
216        true
217    }
218
219    pub(crate) fn autoscroll_horizontally(
220        &mut self,
221        start_row: u32,
222        viewport_width: Pixels,
223        scroll_width: Pixels,
224        max_glyph_width: Pixels,
225        layouts: &[LineWithInvisibles],
226        cx: &mut ViewContext<Self>,
227    ) -> bool {
228        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
229        let selections = self.selections.all::<Point>(cx);
230
231        let mut target_left;
232        let mut target_right;
233
234        if self.highlighted_rows.is_empty() {
235            target_left = px(f32::INFINITY);
236            target_right = px(0.);
237            for selection in selections {
238                let head = selection.head().to_display_point(&display_map);
239                if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
240                    let start_column = head.column().saturating_sub(3);
241                    let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
242                    target_left = target_left.min(
243                        layouts[(head.row() - start_row) as usize]
244                            .line
245                            .x_for_index(start_column as usize),
246                    );
247                    target_right = target_right.max(
248                        layouts[(head.row() - start_row) as usize]
249                            .line
250                            .x_for_index(end_column as usize)
251                            + max_glyph_width,
252                    );
253                }
254            }
255        } else {
256            target_left = px(0.);
257            target_right = px(0.);
258        }
259
260        target_right = target_right.min(scroll_width);
261
262        if target_right - target_left > viewport_width {
263            return false;
264        }
265
266        let scroll_left = self.scroll_manager.anchor.offset.x * max_glyph_width;
267        let scroll_right = scroll_left + viewport_width;
268
269        if target_left < scroll_left {
270            self.scroll_manager.anchor.offset.x = target_left / max_glyph_width;
271            true
272        } else if target_right > scroll_right {
273            self.scroll_manager.anchor.offset.x = (target_right - viewport_width) / max_glyph_width;
274            true
275        } else {
276            false
277        }
278    }
279
280    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
281        self.scroll_manager.autoscroll_request = Some((autoscroll, true));
282        cx.notify();
283    }
284
285    pub(crate) fn request_autoscroll_remotely(
286        &mut self,
287        autoscroll: Autoscroll,
288        cx: &mut ViewContext<Self>,
289    ) {
290        self.scroll_manager.autoscroll_request = Some((autoscroll, false));
291        cx.notify();
292    }
293}