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            target_top = selections
117                .first()
118                .unwrap()
119                .head()
120                .to_display_point(&display_map)
121                .row()
122                .as_f32();
123            target_bottom = selections
124                .last()
125                .unwrap()
126                .head()
127                .to_display_point(&display_map)
128                .row()
129                .next_row()
130                .as_f32();
131
132            let selections_fit = target_bottom - target_top <= visible_lines;
133            if autoscroll == Autoscroll::newest()
134                || (autoscroll == Autoscroll::fit() && !selections_fit)
135            {
136                let newest_selection_top = selections
137                    .iter()
138                    .max_by_key(|s| s.id)
139                    .unwrap()
140                    .head()
141                    .to_display_point(&display_map)
142                    .row()
143                    .as_f32();
144                target_top = newest_selection_top;
145                target_bottom = newest_selection_top + 1.;
146            }
147        }
148
149        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
150            0.
151        } else {
152            ((visible_lines - (target_bottom - target_top)) / 2.0).floor()
153        };
154
155        let strategy = match autoscroll {
156            Autoscroll::Strategy(strategy) => strategy,
157            Autoscroll::Next => {
158                let last_autoscroll = &self.scroll_manager.last_autoscroll;
159                if let Some(last_autoscroll) = last_autoscroll {
160                    if self.scroll_manager.anchor.offset == last_autoscroll.0
161                        && target_top == last_autoscroll.1
162                        && target_bottom == last_autoscroll.2
163                    {
164                        last_autoscroll.3.next()
165                    } else {
166                        AutoscrollStrategy::default()
167                    }
168                } else {
169                    AutoscrollStrategy::default()
170                }
171            }
172        };
173
174        match strategy {
175            AutoscrollStrategy::Fit | AutoscrollStrategy::Newest => {
176                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
177                let target_top = (target_top - margin).max(0.0);
178                let target_bottom = target_bottom + margin;
179                let start_row = scroll_position.y;
180                let end_row = start_row + visible_lines;
181
182                let needs_scroll_up = target_top < start_row;
183                let needs_scroll_down = target_bottom >= end_row;
184
185                if needs_scroll_up && !needs_scroll_down {
186                    scroll_position.y = target_top;
187                    self.set_scroll_position_internal(scroll_position, local, true, window, cx);
188                }
189                if !needs_scroll_up && needs_scroll_down {
190                    scroll_position.y = target_bottom - visible_lines;
191                    self.set_scroll_position_internal(scroll_position, local, true, window, cx);
192                }
193            }
194            AutoscrollStrategy::Center => {
195                scroll_position.y = (target_top - margin).max(0.0);
196                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
197            }
198            AutoscrollStrategy::Focused => {
199                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
200                scroll_position.y = (target_top - margin).max(0.0);
201                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
202            }
203            AutoscrollStrategy::Top => {
204                scroll_position.y = (target_top).max(0.0);
205                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
206            }
207            AutoscrollStrategy::Bottom => {
208                scroll_position.y = (target_bottom - visible_lines).max(0.0);
209                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
210            }
211            AutoscrollStrategy::TopRelative(lines) => {
212                scroll_position.y = target_top - lines as f32;
213                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
214            }
215        }
216
217        self.scroll_manager.last_autoscroll = Some((
218            self.scroll_manager.anchor.offset,
219            target_top,
220            target_bottom,
221            strategy,
222        ));
223
224        true
225    }
226
227    pub(crate) fn autoscroll_horizontally(
228        &mut self,
229        start_row: DisplayRow,
230        viewport_width: Pixels,
231        scroll_width: Pixels,
232        max_glyph_width: Pixels,
233        layouts: &[LineWithInvisibles],
234        cx: &mut Context<Self>,
235    ) -> bool {
236        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
237        let selections = self.selections.all::<Point>(cx);
238
239        let mut target_left;
240        let mut target_right;
241
242        if self
243            .highlighted_display_row_for_autoscroll(&display_map)
244            .is_none()
245        {
246            target_left = px(f32::INFINITY);
247            target_right = px(0.);
248            for selection in selections {
249                let head = selection.head().to_display_point(&display_map);
250                if head.row() >= start_row
251                    && head.row() < DisplayRow(start_row.0 + layouts.len() as u32)
252                {
253                    let start_column = head.column().saturating_sub(3);
254                    let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
255                    target_left = target_left.min(
256                        layouts[head.row().minus(start_row) as usize]
257                            .x_for_index(start_column as usize),
258                    );
259                    target_right = target_right.max(
260                        layouts[head.row().minus(start_row) as usize]
261                            .x_for_index(end_column as usize)
262                            + max_glyph_width,
263                    );
264                }
265            }
266        } else {
267            target_left = px(0.);
268            target_right = px(0.);
269        }
270
271        target_right = target_right.min(scroll_width);
272
273        if target_right - target_left > viewport_width {
274            return false;
275        }
276
277        let scroll_left = self.scroll_manager.anchor.offset.x * max_glyph_width;
278        let scroll_right = scroll_left + viewport_width;
279
280        if target_left < scroll_left {
281            self.scroll_manager.anchor.offset.x = target_left / max_glyph_width;
282            true
283        } else if target_right > scroll_right {
284            self.scroll_manager.anchor.offset.x = (target_right - viewport_width) / max_glyph_width;
285            true
286        } else {
287            false
288        }
289    }
290
291    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut Context<Self>) {
292        self.scroll_manager.autoscroll_request = Some((autoscroll, true));
293        cx.notify();
294    }
295
296    pub(crate) fn request_autoscroll_remotely(
297        &mut self,
298        autoscroll: Autoscroll,
299        cx: &mut Context<Self>,
300    ) {
301        self.scroll_manager.autoscroll_request = Some((autoscroll, false));
302        cx.notify();
303    }
304}