autoscroll.rs

  1use crate::{
  2    display_map::ToDisplayPoint, DisplayRow, Editor, EditorMode, LineWithInvisibles, RowExt,
  3};
  4use gpui::{px, Bounds, Context, Pixels, Window};
  5use language::Point;
  6use std::{cmp, f32};
  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 newest cursor is near the top
 31    /// (offset by vertical_scroll_margin)
 32    pub fn focused() -> Self {
 33        Self::Strategy(AutoscrollStrategy::Focused)
 34    }
 35
 36    /// Scrolls so that the newest cursor is roughly an n-th line from the top.
 37    pub fn top_relative(n: usize) -> Self {
 38        Self::Strategy(AutoscrollStrategy::TopRelative(n))
 39    }
 40
 41    /// Scrolls so that the newest cursor is at the bottom.
 42    pub fn bottom() -> Self {
 43        Self::Strategy(AutoscrollStrategy::Bottom)
 44    }
 45}
 46
 47#[derive(PartialEq, Eq, Default, Clone, Copy)]
 48pub enum AutoscrollStrategy {
 49    Fit,
 50    Newest,
 51    #[default]
 52    Center,
 53    Focused,
 54    Top,
 55    Bottom,
 56    TopRelative(usize),
 57}
 58
 59impl AutoscrollStrategy {
 60    fn next(&self) -> Self {
 61        match self {
 62            AutoscrollStrategy::Center => AutoscrollStrategy::Top,
 63            AutoscrollStrategy::Top => AutoscrollStrategy::Bottom,
 64            _ => AutoscrollStrategy::Center,
 65        }
 66    }
 67}
 68
 69impl Editor {
 70    pub fn autoscroll_request(&self) -> Option<Autoscroll> {
 71        self.scroll_manager.autoscroll_request()
 72    }
 73
 74    pub fn autoscroll_vertically(
 75        &mut self,
 76        bounds: Bounds<Pixels>,
 77        line_height: Pixels,
 78        max_scroll_top: f32,
 79        window: &mut Window,
 80        cx: &mut Context<Editor>,
 81    ) -> bool {
 82        let viewport_height = bounds.size.height;
 83        let visible_lines = viewport_height / line_height;
 84        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 85        let mut scroll_position = self.scroll_manager.scroll_position(&display_map);
 86        let original_y = scroll_position.y;
 87        if let Some(last_bounds) = self.expect_bounds_change.take() {
 88            if scroll_position.y != 0. {
 89                scroll_position.y += (bounds.top() - last_bounds.top()) / line_height;
 90                if scroll_position.y < 0. {
 91                    scroll_position.y = 0.;
 92                }
 93            }
 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, window, 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) =
110            self.highlighted_display_row_for_autoscroll(&display_map)
111        {
112            target_top = first_highlighted_row.as_f32();
113            target_bottom = target_top + 1.;
114        } else {
115            let selections = self.selections.all::<Point>(cx);
116
117            target_top = selections
118                .first()
119                .unwrap()
120                .head()
121                .to_display_point(&display_map)
122                .row()
123                .as_f32();
124            target_bottom = selections
125                .last()
126                .unwrap()
127                .head()
128                .to_display_point(&display_map)
129                .row()
130                .next_row()
131                .as_f32();
132
133            let selections_fit = target_bottom - target_top <= visible_lines;
134            if autoscroll == Autoscroll::newest()
135                || (autoscroll == Autoscroll::fit() && !selections_fit)
136            {
137                let newest_selection_top = selections
138                    .iter()
139                    .max_by_key(|s| s.id)
140                    .unwrap()
141                    .head()
142                    .to_display_point(&display_map)
143                    .row()
144                    .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, window, 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, window, 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, window, cx);
198            }
199            AutoscrollStrategy::Focused => {
200                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
201                scroll_position.y = (target_top - margin).max(0.0);
202                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
203            }
204            AutoscrollStrategy::Top => {
205                scroll_position.y = (target_top).max(0.0);
206                self.set_scroll_position_internal(scroll_position, local, true, window, 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, window, 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, window, 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: DisplayRow,
231        viewport_width: Pixels,
232        scroll_width: Pixels,
233        max_glyph_width: Pixels,
234        layouts: &[LineWithInvisibles],
235        cx: &mut Context<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
244            .highlighted_display_row_for_autoscroll(&display_map)
245            .is_none()
246        {
247            target_left = px(f32::INFINITY);
248            target_right = px(0.);
249            for selection in selections {
250                let head = selection.head().to_display_point(&display_map);
251                if head.row() >= start_row
252                    && head.row() < DisplayRow(start_row.0 + layouts.len() as u32)
253                {
254                    let start_column = head.column().saturating_sub(3);
255                    let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
256                    target_left = target_left.min(
257                        layouts[head.row().minus(start_row) as usize]
258                            .x_for_index(start_column as usize),
259                    );
260                    target_right = target_right.max(
261                        layouts[head.row().minus(start_row) as usize]
262                            .x_for_index(end_column as usize)
263                            + max_glyph_width,
264                    );
265                }
266            }
267        } else {
268            target_left = px(0.);
269            target_right = px(0.);
270        }
271
272        target_right = target_right.min(scroll_width);
273
274        if target_right - target_left > viewport_width {
275            return false;
276        }
277
278        let scroll_left = self.scroll_manager.anchor.offset.x * max_glyph_width;
279        let scroll_right = scroll_left + viewport_width;
280
281        if target_left < scroll_left {
282            self.scroll_manager.anchor.offset.x = target_left / max_glyph_width;
283            true
284        } else if target_right > scroll_right {
285            self.scroll_manager.anchor.offset.x = (target_right - viewport_width) / max_glyph_width;
286            true
287        } else {
288            false
289        }
290    }
291
292    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut Context<Self>) {
293        self.scroll_manager.autoscroll_request = Some((autoscroll, true));
294        cx.notify();
295    }
296
297    pub(crate) fn request_autoscroll_remotely(
298        &mut self,
299        autoscroll: Autoscroll,
300        cx: &mut Context<Self>,
301    ) {
302        self.scroll_manager.autoscroll_request = Some((autoscroll, false));
303        cx.notify();
304    }
305}