1mod actions;
2pub(crate) mod autoscroll;
3pub(crate) mod scroll_amount;
4
5use crate::editor_settings::{ScrollBeyondLastLine, ScrollbarAxes};
6use crate::{
7 display_map::{DisplaySnapshot, ToDisplayPoint},
8 hover_popover::hide_hover,
9 persistence::DB,
10 Anchor, DisplayPoint, DisplayRow, Editor, EditorEvent, EditorMode, EditorSettings,
11 InlayHintRefreshReason, MultiBufferSnapshot, RowExt, ToPoint,
12};
13pub use autoscroll::{Autoscroll, AutoscrollStrategy};
14use core::fmt::Debug;
15use gpui::{point, px, Along, App, Axis, Context, Global, Pixels, Task, Window};
16use language::{Bias, Point};
17pub use scroll_amount::ScrollAmount;
18use settings::Settings;
19use std::{
20 cmp::Ordering,
21 time::{Duration, Instant},
22};
23use util::ResultExt;
24use workspace::{ItemId, WorkspaceId};
25
26pub const SCROLL_EVENT_SEPARATION: Duration = Duration::from_millis(28);
27const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
28
29#[derive(Default)]
30pub struct ScrollbarAutoHide(pub bool);
31
32impl Global for ScrollbarAutoHide {}
33
34#[derive(Clone, Copy, Debug, PartialEq)]
35pub struct ScrollAnchor {
36 pub offset: gpui::Point<f32>,
37 pub anchor: Anchor,
38}
39
40impl ScrollAnchor {
41 fn new() -> Self {
42 Self {
43 offset: gpui::Point::default(),
44 anchor: Anchor::min(),
45 }
46 }
47
48 pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> gpui::Point<f32> {
49 let mut scroll_position = self.offset;
50 if self.anchor == Anchor::min() {
51 scroll_position.y = 0.;
52 } else {
53 let scroll_top = self.anchor.to_display_point(snapshot).row().as_f32();
54 scroll_position.y += scroll_top;
55 }
56 scroll_position
57 }
58
59 pub fn top_row(&self, buffer: &MultiBufferSnapshot) -> u32 {
60 self.anchor.to_point(buffer).row
61 }
62}
63
64#[derive(Debug, Clone)]
65pub struct AxisPair<T: Clone> {
66 pub vertical: T,
67 pub horizontal: T,
68}
69
70pub fn axis_pair<T: Clone>(horizontal: T, vertical: T) -> AxisPair<T> {
71 AxisPair {
72 vertical,
73 horizontal,
74 }
75}
76
77impl<T: Clone> AxisPair<T> {
78 pub fn as_xy(&self) -> (&T, &T) {
79 (&self.horizontal, &self.vertical)
80 }
81}
82
83impl<T: Clone> Along for AxisPair<T> {
84 type Unit = T;
85
86 fn along(&self, axis: gpui::Axis) -> Self::Unit {
87 match axis {
88 gpui::Axis::Horizontal => self.horizontal.clone(),
89 gpui::Axis::Vertical => self.vertical.clone(),
90 }
91 }
92
93 fn apply_along(&self, axis: gpui::Axis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
94 match axis {
95 gpui::Axis::Horizontal => Self {
96 horizontal: f(self.horizontal.clone()),
97 vertical: self.vertical.clone(),
98 },
99 gpui::Axis::Vertical => Self {
100 horizontal: self.horizontal.clone(),
101 vertical: f(self.vertical.clone()),
102 },
103 }
104 }
105}
106
107impl From<ScrollbarAxes> for AxisPair<bool> {
108 fn from(value: ScrollbarAxes) -> Self {
109 axis_pair(value.horizontal, value.vertical)
110 }
111}
112
113#[derive(Clone, Copy, Debug)]
114pub struct OngoingScroll {
115 last_event: Instant,
116 axis: Option<Axis>,
117}
118
119impl OngoingScroll {
120 fn new() -> Self {
121 Self {
122 last_event: Instant::now() - SCROLL_EVENT_SEPARATION,
123 axis: None,
124 }
125 }
126
127 pub fn filter(&self, delta: &mut gpui::Point<Pixels>) -> Option<Axis> {
128 const UNLOCK_PERCENT: f32 = 1.9;
129 const UNLOCK_LOWER_BOUND: Pixels = px(6.);
130 let mut axis = self.axis;
131
132 let x = delta.x.abs();
133 let y = delta.y.abs();
134 let duration = Instant::now().duration_since(self.last_event);
135 if duration > SCROLL_EVENT_SEPARATION {
136 //New ongoing scroll will start, determine axis
137 axis = if x <= y {
138 Some(Axis::Vertical)
139 } else {
140 Some(Axis::Horizontal)
141 };
142 } else if x.max(y) >= UNLOCK_LOWER_BOUND {
143 //Check if the current ongoing will need to unlock
144 match axis {
145 Some(Axis::Vertical) => {
146 if x > y && x >= y * UNLOCK_PERCENT {
147 axis = None;
148 }
149 }
150
151 Some(Axis::Horizontal) => {
152 if y > x && y >= x * UNLOCK_PERCENT {
153 axis = None;
154 }
155 }
156
157 None => {}
158 }
159 }
160
161 match axis {
162 Some(Axis::Vertical) => {
163 *delta = point(px(0.), delta.y);
164 }
165 Some(Axis::Horizontal) => {
166 *delta = point(delta.x, px(0.));
167 }
168 None => {}
169 }
170
171 axis
172 }
173}
174
175pub struct ScrollManager {
176 pub(crate) vertical_scroll_margin: f32,
177 anchor: ScrollAnchor,
178 ongoing: OngoingScroll,
179 autoscroll_request: Option<(Autoscroll, bool)>,
180 last_autoscroll: Option<(gpui::Point<f32>, f32, f32, AutoscrollStrategy)>,
181 show_scrollbars: bool,
182 hide_scrollbar_task: Option<Task<()>>,
183 dragging_scrollbar: AxisPair<bool>,
184 visible_line_count: Option<f32>,
185 forbid_vertical_scroll: bool,
186}
187
188impl ScrollManager {
189 pub fn new(cx: &mut App) -> Self {
190 ScrollManager {
191 vertical_scroll_margin: EditorSettings::get_global(cx).vertical_scroll_margin,
192 anchor: ScrollAnchor::new(),
193 ongoing: OngoingScroll::new(),
194 autoscroll_request: None,
195 show_scrollbars: true,
196 hide_scrollbar_task: None,
197 dragging_scrollbar: axis_pair(false, false),
198 last_autoscroll: None,
199 visible_line_count: None,
200 forbid_vertical_scroll: false,
201 }
202 }
203
204 pub fn clone_state(&mut self, other: &Self) {
205 self.anchor = other.anchor;
206 self.ongoing = other.ongoing;
207 }
208
209 pub fn anchor(&self) -> ScrollAnchor {
210 self.anchor
211 }
212
213 pub fn ongoing_scroll(&self) -> OngoingScroll {
214 self.ongoing
215 }
216
217 pub fn update_ongoing_scroll(&mut self, axis: Option<Axis>) {
218 self.ongoing.last_event = Instant::now();
219 self.ongoing.axis = axis;
220 }
221
222 pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> gpui::Point<f32> {
223 self.anchor.scroll_position(snapshot)
224 }
225
226 #[allow(clippy::too_many_arguments)]
227 fn set_scroll_position(
228 &mut self,
229 scroll_position: gpui::Point<f32>,
230 map: &DisplaySnapshot,
231 local: bool,
232 autoscroll: bool,
233 workspace_id: Option<WorkspaceId>,
234 window: &mut Window,
235 cx: &mut Context<Editor>,
236 ) {
237 if self.forbid_vertical_scroll {
238 return;
239 }
240 let (new_anchor, top_row) = if scroll_position.y <= 0. {
241 (
242 ScrollAnchor {
243 anchor: Anchor::min(),
244 offset: scroll_position.max(&gpui::Point::default()),
245 },
246 0,
247 )
248 } else {
249 let scroll_top = scroll_position.y;
250 let scroll_top = match EditorSettings::get_global(cx).scroll_beyond_last_line {
251 ScrollBeyondLastLine::OnePage => scroll_top,
252 ScrollBeyondLastLine::Off => {
253 if let Some(height_in_lines) = self.visible_line_count {
254 let max_row = map.max_point().row().0 as f32;
255 scroll_top.min(max_row - height_in_lines + 1.).max(0.)
256 } else {
257 scroll_top
258 }
259 }
260 ScrollBeyondLastLine::VerticalScrollMargin => {
261 if let Some(height_in_lines) = self.visible_line_count {
262 let max_row = map.max_point().row().0 as f32;
263 scroll_top
264 .min(max_row - height_in_lines + 1. + self.vertical_scroll_margin)
265 .max(0.)
266 } else {
267 scroll_top
268 }
269 }
270 };
271
272 let scroll_top_buffer_point =
273 DisplayPoint::new(DisplayRow(scroll_top as u32), 0).to_point(map);
274 let top_anchor = map
275 .buffer_snapshot
276 .anchor_at(scroll_top_buffer_point, Bias::Right);
277
278 (
279 ScrollAnchor {
280 anchor: top_anchor,
281 offset: point(
282 scroll_position.x.max(0.),
283 scroll_top - top_anchor.to_display_point(map).row().as_f32(),
284 ),
285 },
286 scroll_top_buffer_point.row,
287 )
288 };
289
290 self.set_anchor(
291 new_anchor,
292 top_row,
293 local,
294 autoscroll,
295 workspace_id,
296 window,
297 cx,
298 );
299 }
300
301 #[allow(clippy::too_many_arguments)]
302 fn set_anchor(
303 &mut self,
304 anchor: ScrollAnchor,
305 top_row: u32,
306 local: bool,
307 autoscroll: bool,
308 workspace_id: Option<WorkspaceId>,
309 window: &mut Window,
310 cx: &mut Context<Editor>,
311 ) {
312 if self.forbid_vertical_scroll {
313 return;
314 }
315 self.anchor = anchor;
316 cx.emit(EditorEvent::ScrollPositionChanged { local, autoscroll });
317 self.show_scrollbar(window, cx);
318 self.autoscroll_request.take();
319 if let Some(workspace_id) = workspace_id {
320 let item_id = cx.entity().entity_id().as_u64() as ItemId;
321
322 cx.foreground_executor()
323 .spawn(async move {
324 DB.save_scroll_position(
325 item_id,
326 workspace_id,
327 top_row,
328 anchor.offset.x,
329 anchor.offset.y,
330 )
331 .await
332 .log_err()
333 })
334 .detach()
335 }
336 cx.notify();
337 }
338
339 pub fn show_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
340 if !self.show_scrollbars {
341 self.show_scrollbars = true;
342 cx.notify();
343 }
344
345 if cx.default_global::<ScrollbarAutoHide>().0 {
346 self.hide_scrollbar_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
347 cx.background_executor()
348 .timer(SCROLLBAR_SHOW_INTERVAL)
349 .await;
350 editor
351 .update(&mut cx, |editor, cx| {
352 editor.scroll_manager.show_scrollbars = false;
353 cx.notify();
354 })
355 .log_err();
356 }));
357 } else {
358 self.hide_scrollbar_task = None;
359 }
360 }
361
362 pub fn scrollbars_visible(&self) -> bool {
363 self.show_scrollbars
364 }
365
366 pub fn autoscroll_request(&self) -> Option<Autoscroll> {
367 self.autoscroll_request.map(|(autoscroll, _)| autoscroll)
368 }
369
370 pub fn is_dragging_scrollbar(&self, axis: Axis) -> bool {
371 self.dragging_scrollbar.along(axis)
372 }
373
374 pub fn set_is_dragging_scrollbar(
375 &mut self,
376 axis: Axis,
377 dragging: bool,
378 cx: &mut Context<Editor>,
379 ) {
380 self.dragging_scrollbar = self.dragging_scrollbar.apply_along(axis, |_| dragging);
381 cx.notify();
382 }
383
384 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
385 if max < self.anchor.offset.x {
386 self.anchor.offset.x = max;
387 true
388 } else {
389 false
390 }
391 }
392
393 pub fn set_forbid_vertical_scroll(&mut self, forbid: bool) {
394 self.forbid_vertical_scroll = forbid;
395 }
396
397 pub fn forbid_vertical_scroll(&self) -> bool {
398 self.forbid_vertical_scroll
399 }
400}
401
402impl Editor {
403 pub fn vertical_scroll_margin(&self) -> usize {
404 self.scroll_manager.vertical_scroll_margin as usize
405 }
406
407 pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut Context<Self>) {
408 self.scroll_manager.vertical_scroll_margin = margin_rows as f32;
409 cx.notify();
410 }
411
412 pub fn visible_line_count(&self) -> Option<f32> {
413 self.scroll_manager.visible_line_count
414 }
415
416 pub fn visible_row_count(&self) -> Option<u32> {
417 self.visible_line_count()
418 .map(|line_count| line_count as u32 - 1)
419 }
420
421 pub(crate) fn set_visible_line_count(
422 &mut self,
423 lines: f32,
424 window: &mut Window,
425 cx: &mut Context<Self>,
426 ) {
427 let opened_first_time = self.scroll_manager.visible_line_count.is_none();
428 self.scroll_manager.visible_line_count = Some(lines);
429 if opened_first_time {
430 cx.spawn_in(window, |editor, mut cx| async move {
431 editor
432 .update(&mut cx, |editor, cx| {
433 editor.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx)
434 })
435 .ok()
436 })
437 .detach()
438 }
439 }
440
441 pub fn apply_scroll_delta(
442 &mut self,
443 scroll_delta: gpui::Point<f32>,
444 window: &mut Window,
445 cx: &mut Context<Self>,
446 ) {
447 if self.scroll_manager.forbid_vertical_scroll {
448 return;
449 }
450 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
451 let position = self.scroll_manager.anchor.scroll_position(&display_map) + scroll_delta;
452 self.set_scroll_position_taking_display_map(position, true, false, display_map, window, cx);
453 }
454
455 pub fn set_scroll_position(
456 &mut self,
457 scroll_position: gpui::Point<f32>,
458 window: &mut Window,
459 cx: &mut Context<Self>,
460 ) {
461 if self.scroll_manager.forbid_vertical_scroll {
462 return;
463 }
464 self.set_scroll_position_internal(scroll_position, true, false, window, cx);
465 }
466
467 pub(crate) fn set_scroll_position_internal(
468 &mut self,
469 scroll_position: gpui::Point<f32>,
470 local: bool,
471 autoscroll: bool,
472 window: &mut Window,
473 cx: &mut Context<Self>,
474 ) {
475 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
476 self.set_scroll_position_taking_display_map(
477 scroll_position,
478 local,
479 autoscroll,
480 map,
481 window,
482 cx,
483 );
484 }
485
486 fn set_scroll_position_taking_display_map(
487 &mut self,
488 scroll_position: gpui::Point<f32>,
489 local: bool,
490 autoscroll: bool,
491 display_map: DisplaySnapshot,
492 window: &mut Window,
493 cx: &mut Context<Self>,
494 ) {
495 hide_hover(self, cx);
496 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
497
498 self.edit_prediction_preview
499 .set_previous_scroll_position(None);
500
501 self.scroll_manager.set_scroll_position(
502 scroll_position,
503 &display_map,
504 local,
505 autoscroll,
506 workspace_id,
507 window,
508 cx,
509 );
510
511 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
512 }
513
514 pub fn scroll_position(&self, cx: &mut Context<Self>) -> gpui::Point<f32> {
515 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
516 self.scroll_manager.anchor.scroll_position(&display_map)
517 }
518
519 pub fn set_scroll_anchor(
520 &mut self,
521 scroll_anchor: ScrollAnchor,
522 window: &mut Window,
523 cx: &mut Context<Self>,
524 ) {
525 hide_hover(self, cx);
526 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
527 let top_row = scroll_anchor
528 .anchor
529 .to_point(&self.buffer().read(cx).snapshot(cx))
530 .row;
531 self.scroll_manager.set_anchor(
532 scroll_anchor,
533 top_row,
534 true,
535 false,
536 workspace_id,
537 window,
538 cx,
539 );
540 }
541
542 pub(crate) fn set_scroll_anchor_remote(
543 &mut self,
544 scroll_anchor: ScrollAnchor,
545 window: &mut Window,
546 cx: &mut Context<Self>,
547 ) {
548 hide_hover(self, cx);
549 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
550 let snapshot = &self.buffer().read(cx).snapshot(cx);
551 if !scroll_anchor.anchor.is_valid(snapshot) {
552 log::warn!("Invalid scroll anchor: {:?}", scroll_anchor);
553 return;
554 }
555 let top_row = scroll_anchor.anchor.to_point(snapshot).row;
556 self.scroll_manager.set_anchor(
557 scroll_anchor,
558 top_row,
559 false,
560 false,
561 workspace_id,
562 window,
563 cx,
564 );
565 }
566
567 pub fn scroll_screen(
568 &mut self,
569 amount: &ScrollAmount,
570 window: &mut Window,
571 cx: &mut Context<Self>,
572 ) {
573 if matches!(self.mode, EditorMode::SingleLine { .. }) {
574 cx.propagate();
575 return;
576 }
577
578 if self.take_rename(true, window, cx).is_some() {
579 return;
580 }
581
582 let cur_position = self.scroll_position(cx);
583 let Some(visible_line_count) = self.visible_line_count() else {
584 return;
585 };
586 let new_pos = cur_position + point(0., amount.lines(visible_line_count));
587 self.set_scroll_position(new_pos, window, cx);
588 }
589
590 /// Returns an ordering. The newest selection is:
591 /// Ordering::Equal => on screen
592 /// Ordering::Less => above the screen
593 /// Ordering::Greater => below the screen
594 pub fn newest_selection_on_screen(&self, cx: &mut App) -> Ordering {
595 let snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
596 let newest_head = self
597 .selections
598 .newest_anchor()
599 .head()
600 .to_display_point(&snapshot);
601 let screen_top = self
602 .scroll_manager
603 .anchor
604 .anchor
605 .to_display_point(&snapshot);
606
607 if screen_top > newest_head {
608 return Ordering::Less;
609 }
610
611 if let Some(visible_lines) = self.visible_line_count() {
612 if newest_head.row() <= DisplayRow(screen_top.row().0 + visible_lines as u32) {
613 return Ordering::Equal;
614 }
615 }
616
617 Ordering::Greater
618 }
619
620 pub fn read_scroll_position_from_db(
621 &mut self,
622 item_id: u64,
623 workspace_id: WorkspaceId,
624 window: &mut Window,
625 cx: &mut Context<Editor>,
626 ) {
627 let scroll_position = DB.get_scroll_position(item_id, workspace_id);
628 if let Ok(Some((top_row, x, y))) = scroll_position {
629 let top_anchor = self
630 .buffer()
631 .read(cx)
632 .snapshot(cx)
633 .anchor_at(Point::new(top_row, 0), Bias::Left);
634 let scroll_anchor = ScrollAnchor {
635 offset: gpui::Point::new(x, y),
636 anchor: top_anchor,
637 };
638 self.set_scroll_anchor(scroll_anchor, window, cx);
639 }
640 }
641}