autoscroll.rs

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