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