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            if self.edit_prediction_preview.is_active() {
150                if let Some(completion) = self.active_inline_completion.as_ref() {
151                    match completion.completion {
152                        crate::InlineCompletion::Edit { .. } => {}
153                        crate::InlineCompletion::Move { target, .. } => {
154                            let target_row = target.to_display_point(&display_map).row().as_f32();
155
156                            if target_row < target_top {
157                                target_top = target_row;
158                            } else if target_row >= target_bottom {
159                                target_bottom = target_row + 1.;
160                            }
161
162                            let selections_fit = target_bottom - target_top <= visible_lines;
163                            if !selections_fit {
164                                target_top = target_row;
165                                target_bottom = target_row + 1.;
166                            }
167                        }
168                    }
169                }
170            }
171        }
172
173        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
174            0.
175        } else {
176            ((visible_lines - (target_bottom - target_top)) / 2.0).floor()
177        };
178
179        let strategy = match autoscroll {
180            Autoscroll::Strategy(strategy) => strategy,
181            Autoscroll::Next => {
182                let last_autoscroll = &self.scroll_manager.last_autoscroll;
183                if let Some(last_autoscroll) = last_autoscroll {
184                    if self.scroll_manager.anchor.offset == last_autoscroll.0
185                        && target_top == last_autoscroll.1
186                        && target_bottom == last_autoscroll.2
187                    {
188                        last_autoscroll.3.next()
189                    } else {
190                        AutoscrollStrategy::default()
191                    }
192                } else {
193                    AutoscrollStrategy::default()
194                }
195            }
196        };
197
198        match strategy {
199            AutoscrollStrategy::Fit | AutoscrollStrategy::Newest => {
200                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
201                let target_top = (target_top - margin).max(0.0);
202                let target_bottom = target_bottom + margin;
203                let start_row = scroll_position.y;
204                let end_row = start_row + visible_lines;
205
206                let needs_scroll_up = target_top < start_row;
207                let needs_scroll_down = target_bottom >= end_row;
208
209                if needs_scroll_up && !needs_scroll_down {
210                    scroll_position.y = target_top;
211                    self.set_scroll_position_internal(scroll_position, local, true, window, cx);
212                }
213                if !needs_scroll_up && needs_scroll_down {
214                    scroll_position.y = target_bottom - visible_lines;
215                    self.set_scroll_position_internal(scroll_position, local, true, window, cx);
216                }
217            }
218            AutoscrollStrategy::Center => {
219                scroll_position.y = (target_top - margin).max(0.0);
220                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
221            }
222            AutoscrollStrategy::Focused => {
223                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
224                scroll_position.y = (target_top - margin).max(0.0);
225                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
226            }
227            AutoscrollStrategy::Top => {
228                scroll_position.y = (target_top).max(0.0);
229                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
230            }
231            AutoscrollStrategy::Bottom => {
232                scroll_position.y = (target_bottom - visible_lines).max(0.0);
233                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
234            }
235            AutoscrollStrategy::TopRelative(lines) => {
236                scroll_position.y = target_top - lines as f32;
237                self.set_scroll_position_internal(scroll_position, local, true, window, cx);
238            }
239        }
240
241        self.scroll_manager.last_autoscroll = Some((
242            self.scroll_manager.anchor.offset,
243            target_top,
244            target_bottom,
245            strategy,
246        ));
247
248        true
249    }
250
251    pub(crate) fn autoscroll_horizontally(
252        &mut self,
253        start_row: DisplayRow,
254        viewport_width: Pixels,
255        scroll_width: Pixels,
256        max_glyph_width: Pixels,
257        layouts: &[LineWithInvisibles],
258        cx: &mut Context<Self>,
259    ) -> bool {
260        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
261        let selections = self.selections.all::<Point>(cx);
262
263        let mut target_left;
264        let mut target_right;
265
266        if self
267            .highlighted_display_row_for_autoscroll(&display_map)
268            .is_none()
269        {
270            target_left = px(f32::INFINITY);
271            target_right = px(0.);
272            for selection in selections {
273                let head = selection.head().to_display_point(&display_map);
274                if head.row() >= start_row
275                    && head.row() < DisplayRow(start_row.0 + layouts.len() as u32)
276                {
277                    let start_column = head.column().saturating_sub(3);
278                    let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
279                    target_left = target_left.min(
280                        layouts[head.row().minus(start_row) as usize]
281                            .x_for_index(start_column as usize),
282                    );
283                    target_right = target_right.max(
284                        layouts[head.row().minus(start_row) as usize]
285                            .x_for_index(end_column as usize)
286                            + max_glyph_width,
287                    );
288                }
289            }
290        } else {
291            target_left = px(0.);
292            target_right = px(0.);
293        }
294
295        target_right = target_right.min(scroll_width);
296
297        if target_right - target_left > viewport_width {
298            return false;
299        }
300
301        let scroll_left = self.scroll_manager.anchor.offset.x * max_glyph_width;
302        let scroll_right = scroll_left + viewport_width;
303
304        if target_left < scroll_left {
305            self.scroll_manager.anchor.offset.x = target_left / max_glyph_width;
306            true
307        } else if target_right > scroll_right {
308            self.scroll_manager.anchor.offset.x = (target_right - viewport_width) / max_glyph_width;
309            true
310        } else {
311            false
312        }
313    }
314
315    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut Context<Self>) {
316        self.scroll_manager.autoscroll_request = Some((autoscroll, true));
317        cx.notify();
318    }
319
320    pub(crate) fn request_autoscroll_remotely(
321        &mut self,
322        autoscroll: Autoscroll,
323        cx: &mut Context<Self>,
324    ) {
325        self.scroll_manager.autoscroll_request = Some((autoscroll, false));
326        cx.notify();
327    }
328}