1use crate::{
  2    DisplayRow, Editor, EditorMode, LineWithInvisibles, RowExt, SelectionEffects,
  3    display_map::ToDisplayPoint,
  4    scroll::{ScrollOffset, WasScrolled},
  5};
  6use gpui::{Bounds, Context, Pixels, Window};
  7use language::Point;
  8use multi_buffer::Anchor;
  9use std::cmp;
 10
 11#[derive(Debug, PartialEq, Eq, Clone, Copy)]
 12pub enum Autoscroll {
 13    Next,
 14    Strategy(AutoscrollStrategy, Option<Anchor>),
 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, None)
 21    }
 22
 23    /// scrolls the minimal amount to fit the newest cursor
 24    pub fn newest() -> Self {
 25        Self::Strategy(AutoscrollStrategy::Newest, None)
 26    }
 27
 28    /// scrolls so the newest cursor is vertically centered
 29    pub fn center() -> Self {
 30        Self::Strategy(AutoscrollStrategy::Center, None)
 31    }
 32
 33    /// scrolls so the newest cursor is near the top
 34    /// (offset by vertical_scroll_margin)
 35    pub fn focused() -> Self {
 36        Self::Strategy(AutoscrollStrategy::Focused, None)
 37    }
 38
 39    /// Scrolls so that the newest cursor is roughly an n-th line from the top.
 40    pub fn top_relative(n: usize) -> Self {
 41        Self::Strategy(AutoscrollStrategy::TopRelative(n), None)
 42    }
 43
 44    /// Scrolls so that the newest cursor is at the top.
 45    pub fn top() -> Self {
 46        Self::Strategy(AutoscrollStrategy::Top, None)
 47    }
 48
 49    /// Scrolls so that the newest cursor is roughly an n-th line from the bottom.
 50    pub fn bottom_relative(n: usize) -> Self {
 51        Self::Strategy(AutoscrollStrategy::BottomRelative(n), None)
 52    }
 53
 54    /// Scrolls so that the newest cursor is at the bottom.
 55    pub fn bottom() -> Self {
 56        Self::Strategy(AutoscrollStrategy::Bottom, None)
 57    }
 58
 59    /// Applies a given auto-scroll strategy to a given anchor instead of a cursor.
 60    /// E.G: Autoscroll::center().for_anchor(...) results in the anchor being at the center of the screen.
 61    pub fn for_anchor(self, anchor: Anchor) -> Self {
 62        match self {
 63            Autoscroll::Next => self,
 64            Autoscroll::Strategy(autoscroll_strategy, _) => {
 65                Self::Strategy(autoscroll_strategy, Some(anchor))
 66            }
 67        }
 68    }
 69}
 70
 71impl Into<SelectionEffects> for Option<Autoscroll> {
 72    fn into(self) -> SelectionEffects {
 73        match self {
 74            Some(autoscroll) => SelectionEffects::scroll(autoscroll),
 75            None => SelectionEffects::no_scroll(),
 76        }
 77    }
 78}
 79
 80#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
 81pub enum AutoscrollStrategy {
 82    Fit,
 83    Newest,
 84    #[default]
 85    Center,
 86    Focused,
 87    Top,
 88    Bottom,
 89    TopRelative(usize),
 90    BottomRelative(usize),
 91}
 92
 93impl AutoscrollStrategy {
 94    fn next(&self) -> Self {
 95        match self {
 96            AutoscrollStrategy::Center => AutoscrollStrategy::Top,
 97            AutoscrollStrategy::Top => AutoscrollStrategy::Bottom,
 98            _ => AutoscrollStrategy::Center,
 99        }
100    }
101}
102
103pub(crate) struct NeedsHorizontalAutoscroll(pub(crate) bool);
104
105impl Editor {
106    pub(crate) fn autoscroll_vertically(
107        &mut self,
108        bounds: Bounds<Pixels>,
109        line_height: Pixels,
110        max_scroll_top: ScrollOffset,
111        autoscroll_request: Option<(Autoscroll, bool)>,
112        window: &mut Window,
113        cx: &mut Context<Editor>,
114    ) -> (NeedsHorizontalAutoscroll, WasScrolled) {
115        let viewport_height = bounds.size.height;
116        let visible_lines = ScrollOffset::from(viewport_height / line_height);
117        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
118        let mut scroll_position = self.scroll_manager.scroll_position(&display_map);
119        let original_y = scroll_position.y;
120        if let Some(last_bounds) = self.expect_bounds_change.take()
121            && scroll_position.y != 0.
122        {
123            scroll_position.y +=
124                ScrollOffset::from((bounds.top() - last_bounds.top()) / line_height);
125            if scroll_position.y < 0. {
126                scroll_position.y = 0.;
127            }
128        }
129        if scroll_position.y > max_scroll_top {
130            scroll_position.y = max_scroll_top;
131        }
132
133        let editor_was_scrolled = if original_y != scroll_position.y {
134            self.set_scroll_position(scroll_position, window, cx)
135        } else {
136            WasScrolled(false)
137        };
138
139        let Some((autoscroll, local)) = autoscroll_request else {
140            return (NeedsHorizontalAutoscroll(false), editor_was_scrolled);
141        };
142
143        let mut target_top;
144        let mut target_bottom;
145        if let Some(first_highlighted_row) =
146            self.highlighted_display_row_for_autoscroll(&display_map)
147        {
148            target_top = first_highlighted_row.as_f64();
149            target_bottom = target_top + 1.;
150        } else {
151            let selections = self.selections.all::<Point>(cx);
152
153            target_top = selections
154                .first()
155                .unwrap()
156                .head()
157                .to_display_point(&display_map)
158                .row()
159                .as_f64();
160            target_bottom = display_map
161                .point_to_display_point2(selections.last().unwrap().head(), text::Bias::Left)
162                .row()
163                .next_row()
164                .as_f64();
165
166            let selections_fit = target_bottom - target_top <= visible_lines;
167            if matches!(
168                autoscroll,
169                Autoscroll::Strategy(AutoscrollStrategy::Newest, _)
170            ) || (matches!(autoscroll, Autoscroll::Strategy(AutoscrollStrategy::Fit, _))
171                && !selections_fit)
172            {
173                let newest_selection_top = selections
174                    .iter()
175                    .max_by_key(|s| s.id)
176                    .unwrap()
177                    .head()
178                    .to_display_point(&display_map)
179                    .row()
180                    .as_f64();
181                target_top = newest_selection_top;
182                target_bottom = newest_selection_top + 1.;
183            }
184        }
185
186        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
187            0.
188        } else {
189            ((visible_lines - (target_bottom - target_top)) / 2.0).floor()
190        };
191
192        let strategy = match autoscroll {
193            Autoscroll::Strategy(strategy, _) => strategy,
194            Autoscroll::Next => {
195                let last_autoscroll = &self.scroll_manager.last_autoscroll;
196                if let Some(last_autoscroll) = last_autoscroll {
197                    if self.scroll_manager.anchor.offset == last_autoscroll.0
198                        && target_top == last_autoscroll.1
199                        && target_bottom == last_autoscroll.2
200                    {
201                        last_autoscroll.3.next()
202                    } else {
203                        AutoscrollStrategy::default()
204                    }
205                } else {
206                    AutoscrollStrategy::default()
207                }
208            }
209        };
210        if let Autoscroll::Strategy(_, Some(anchor)) = autoscroll {
211            target_top = anchor.to_display_point(&display_map).row().as_f64();
212            target_bottom = target_top + 1.;
213        }
214
215        let was_autoscrolled = match strategy {
216            AutoscrollStrategy::Fit | AutoscrollStrategy::Newest => {
217                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
218                let target_top = (target_top - margin).max(0.0);
219                let target_bottom = target_bottom + margin;
220                let start_row = scroll_position.y;
221                let end_row = start_row + visible_lines;
222
223                let needs_scroll_up = target_top < start_row;
224                let needs_scroll_down = target_bottom >= end_row;
225
226                if needs_scroll_up && !needs_scroll_down {
227                    scroll_position.y = target_top;
228                } else if !needs_scroll_up && needs_scroll_down {
229                    dbg!(scroll_position.y);
230                    scroll_position.y = dbg!(target_bottom) - dbg!(visible_lines);
231                    dbg!(scroll_position.y);
232                }
233
234                if needs_scroll_up ^ needs_scroll_down {
235                    self.set_scroll_position_internal(scroll_position, local, true, window, cx)
236                } else {
237                    WasScrolled(false)
238                }
239            }
240            AutoscrollStrategy::Center => {
241                scroll_position.y = (target_top - margin).max(0.0);
242                self.set_scroll_position_internal(scroll_position, local, true, window, cx)
243            }
244            AutoscrollStrategy::Focused => {
245                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
246                scroll_position.y = (target_top - margin).max(0.0);
247                self.set_scroll_position_internal(scroll_position, local, true, window, cx)
248            }
249            AutoscrollStrategy::Top => {
250                scroll_position.y = (target_top).max(0.0);
251                self.set_scroll_position_internal(scroll_position, local, true, window, cx)
252            }
253            AutoscrollStrategy::Bottom => {
254                scroll_position.y = (target_bottom - visible_lines).max(0.0);
255                self.set_scroll_position_internal(scroll_position, local, true, window, cx)
256            }
257            AutoscrollStrategy::TopRelative(lines) => {
258                scroll_position.y = target_top - lines as ScrollOffset;
259                self.set_scroll_position_internal(scroll_position, local, true, window, cx)
260            }
261            AutoscrollStrategy::BottomRelative(lines) => {
262                scroll_position.y = target_bottom + lines as ScrollOffset;
263                self.set_scroll_position_internal(scroll_position, local, true, window, cx)
264            }
265        };
266
267        self.scroll_manager.last_autoscroll = Some((
268            self.scroll_manager.anchor.offset,
269            target_top,
270            target_bottom,
271            strategy,
272        ));
273
274        let was_scrolled = WasScrolled(editor_was_scrolled.0 || was_autoscrolled.0);
275        (NeedsHorizontalAutoscroll(true), was_scrolled)
276    }
277
278    pub(crate) fn autoscroll_horizontally(
279        &mut self,
280        start_row: DisplayRow,
281        viewport_width: Pixels,
282        scroll_width: Pixels,
283        em_advance: Pixels,
284        layouts: &[LineWithInvisibles],
285        autoscroll_request: Option<(Autoscroll, bool)>,
286        window: &mut Window,
287        cx: &mut Context<Self>,
288    ) -> Option<gpui::Point<ScrollOffset>> {
289        let (_, local) = autoscroll_request?;
290        let em_advance = ScrollOffset::from(em_advance);
291        let viewport_width = ScrollOffset::from(viewport_width);
292        let scroll_width = ScrollOffset::from(scroll_width);
293
294        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
295        let selections = self.selections.all::<Point>(cx);
296        let mut scroll_position = self.scroll_manager.scroll_position(&display_map);
297
298        let mut target_left;
299        let mut target_right: f64;
300
301        if self
302            .highlighted_display_row_for_autoscroll(&display_map)
303            .is_none()
304        {
305            target_left = f64::INFINITY;
306            target_right = 0.;
307            for selection in selections {
308                let head = selection.head().to_display_point(&display_map);
309                if head.row() >= start_row
310                    && head.row() < DisplayRow(start_row.0 + layouts.len() as u32)
311                {
312                    let start_column = head.column();
313                    let end_column = cmp::min(display_map.line_len(head.row()), head.column());
314                    target_left = target_left.min(ScrollOffset::from(
315                        layouts[head.row().minus(start_row) as usize]
316                            .x_for_index(start_column as usize)
317                            + self.gutter_dimensions.margin,
318                    ));
319                    target_right = target_right.max(
320                        ScrollOffset::from(
321                            layouts[head.row().minus(start_row) as usize]
322                                .x_for_index(end_column as usize),
323                        ) + em_advance,
324                    );
325                }
326            }
327        } else {
328            target_left = 0.;
329            target_right = 0.;
330        }
331
332        target_right = target_right.min(scroll_width);
333
334        if target_right - target_left > viewport_width {
335            return None;
336        }
337
338        let scroll_left = self.scroll_manager.anchor.offset.x * em_advance;
339        let scroll_right = scroll_left + viewport_width;
340
341        let was_scrolled = if target_left < scroll_left {
342            scroll_position.x = target_left / em_advance;
343            self.set_scroll_position_internal(scroll_position, local, true, window, cx)
344        } else if target_right > scroll_right {
345            scroll_position.x = (target_right - viewport_width) / em_advance;
346            self.set_scroll_position_internal(scroll_position, local, true, window, cx)
347        } else {
348            WasScrolled(false)
349        };
350
351        if was_scrolled.0 {
352            Some(scroll_position)
353        } else {
354            None
355        }
356    }
357
358    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut Context<Self>) {
359        self.scroll_manager.autoscroll_request = Some((autoscroll, true));
360        cx.notify();
361    }
362
363    pub(crate) fn request_autoscroll_remotely(
364        &mut self,
365        autoscroll: Autoscroll,
366        cx: &mut Context<Self>,
367    ) {
368        self.scroll_manager.autoscroll_request = Some((autoscroll, false));
369        cx.notify();
370    }
371}