1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
use std::{cmp, f32};

use gpui::{px, Pixels, ViewContext};
use language::Point;

use crate::{display_map::ToDisplayPoint, Editor, EditorMode, LineWithInvisibles};

#[derive(PartialEq, Eq)]
pub enum Autoscroll {
    Next,
    Strategy(AutoscrollStrategy),
}

impl Autoscroll {
    pub fn fit() -> Self {
        Self::Strategy(AutoscrollStrategy::Fit)
    }

    pub fn newest() -> Self {
        Self::Strategy(AutoscrollStrategy::Newest)
    }

    pub fn center() -> Self {
        Self::Strategy(AutoscrollStrategy::Center)
    }
}

#[derive(PartialEq, Eq, Default)]
pub enum AutoscrollStrategy {
    Fit,
    Newest,
    #[default]
    Center,
    Top,
    Bottom,
}

impl AutoscrollStrategy {
    fn next(&self) -> Self {
        match self {
            AutoscrollStrategy::Center => AutoscrollStrategy::Top,
            AutoscrollStrategy::Top => AutoscrollStrategy::Bottom,
            _ => AutoscrollStrategy::Center,
        }
    }
}

impl Editor {
    pub fn autoscroll_vertically(
        &mut self,
        viewport_height: Pixels,
        line_height: Pixels,
        cx: &mut ViewContext<Editor>,
    ) -> bool {
        let visible_lines = f32::from(viewport_height / line_height);
        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
        let mut scroll_position = self.scroll_manager.scroll_position(&display_map);
        let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
            (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
        } else {
            display_map.max_point().row() as f32
        };
        if scroll_position.y > max_scroll_top {
            scroll_position.y = (max_scroll_top);
            self.set_scroll_position(scroll_position, cx);
        }

        let Some((autoscroll, local)) = self.scroll_manager.autoscroll_request.take() else {
            return false;
        };

        let mut target_top;
        let mut target_bottom;
        if let Some(highlighted_rows) = &self.highlighted_rows {
            target_top = highlighted_rows.start as f32;
            target_bottom = target_top + 1.;
        } else {
            let selections = self.selections.all::<Point>(cx);
            target_top = selections
                .first()
                .unwrap()
                .head()
                .to_display_point(&display_map)
                .row() as f32;
            target_bottom = selections
                .last()
                .unwrap()
                .head()
                .to_display_point(&display_map)
                .row() as f32
                + 1.0;

            // If the selections can't all fit on screen, scroll to the newest.
            if autoscroll == Autoscroll::newest()
                || autoscroll == Autoscroll::fit() && target_bottom - target_top > visible_lines
            {
                let newest_selection_top = selections
                    .iter()
                    .max_by_key(|s| s.id)
                    .unwrap()
                    .head()
                    .to_display_point(&display_map)
                    .row() as f32;
                target_top = newest_selection_top;
                target_bottom = newest_selection_top + 1.;
            }
        }

        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
            0.
        } else {
            ((visible_lines - (target_bottom - target_top)) / 2.0).floor()
        };

        let strategy = match autoscroll {
            Autoscroll::Strategy(strategy) => strategy,
            Autoscroll::Next => {
                let last_autoscroll = &self.scroll_manager.last_autoscroll;
                if let Some(last_autoscroll) = last_autoscroll {
                    if self.scroll_manager.anchor.offset == last_autoscroll.0
                        && target_top == last_autoscroll.1
                        && target_bottom == last_autoscroll.2
                    {
                        last_autoscroll.3.next()
                    } else {
                        AutoscrollStrategy::default()
                    }
                } else {
                    AutoscrollStrategy::default()
                }
            }
        };

        match strategy {
            AutoscrollStrategy::Fit | AutoscrollStrategy::Newest => {
                let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
                let target_top = (target_top - margin).max(0.0);
                let target_bottom = target_bottom + margin;
                let start_row = scroll_position.y;
                let end_row = start_row + visible_lines;

                let needs_scroll_up = target_top < start_row;
                let needs_scroll_down = target_bottom >= end_row;

                if needs_scroll_up && !needs_scroll_down {
                    scroll_position.y = (target_top);
                    self.set_scroll_position_internal(scroll_position, local, true, cx);
                }
                if !needs_scroll_up && needs_scroll_down {
                    scroll_position.y = (target_bottom - visible_lines);
                    self.set_scroll_position_internal(scroll_position, local, true, cx);
                }
            }
            AutoscrollStrategy::Center => {
                scroll_position.y = ((target_top - margin).max(0.0));
                self.set_scroll_position_internal(scroll_position, local, true, cx);
            }
            AutoscrollStrategy::Top => {
                scroll_position.y = ((target_top).max(0.0));
                self.set_scroll_position_internal(scroll_position, local, true, cx);
            }
            AutoscrollStrategy::Bottom => {
                scroll_position.y = ((target_bottom - visible_lines).max(0.0));
                self.set_scroll_position_internal(scroll_position, local, true, cx);
            }
        }

        self.scroll_manager.last_autoscroll = Some((
            self.scroll_manager.anchor.offset,
            target_top,
            target_bottom,
            strategy,
        ));

        true
    }

    pub fn autoscroll_horizontally(
        &mut self,
        start_row: u32,
        viewport_width: Pixels,
        scroll_width: Pixels,
        max_glyph_width: Pixels,
        layouts: &[LineWithInvisibles],
        cx: &mut ViewContext<Self>,
    ) -> bool {
        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
        let selections = self.selections.all::<Point>(cx);

        let mut target_left;
        let mut target_right;

        if self.highlighted_rows.is_some() {
            target_left = px(0.);
            target_right = px(0.);
        } else {
            target_left = px(f32::INFINITY);
            target_right = px(0.);
            for selection in selections {
                let head = selection.head().to_display_point(&display_map);
                if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
                    let start_column = head.column().saturating_sub(3);
                    let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
                    target_left = target_left.min(
                        layouts[(head.row() - start_row) as usize]
                            .line
                            .x_for_index(start_column as usize),
                    );
                    target_right = target_right.max(
                        layouts[(head.row() - start_row) as usize]
                            .line
                            .x_for_index(end_column as usize)
                            + max_glyph_width,
                    );
                }
            }
        }

        target_right = target_right.min(scroll_width);

        if target_right - target_left > viewport_width {
            return false;
        }

        let scroll_left = self.scroll_manager.anchor.offset.x * max_glyph_width;
        let scroll_right = scroll_left + viewport_width;

        if target_left < scroll_left {
            self.scroll_manager.anchor.offset.x = (target_left / max_glyph_width).into();
            true
        } else if target_right > scroll_right {
            self.scroll_manager.anchor.offset.x =
                ((target_right - viewport_width) / max_glyph_width).into();
            true
        } else {
            false
        }
    }

    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
        self.scroll_manager.autoscroll_request = Some((autoscroll, true));
        cx.notify();
    }

    pub(crate) fn request_autoscroll_remotely(
        &mut self,
        autoscroll: Autoscroll,
        cx: &mut ViewContext<Self>,
    ) {
        self.scroll_manager.autoscroll_request = Some((autoscroll, false));
        cx.notify();
    }
}