1pub mod actions;
2pub mod autoscroll;
3pub mod scroll_amount;
4
5use std::{
6 cmp::Ordering,
7 time::{Duration, Instant},
8};
9
10use gpui::{
11 geometry::vector::{vec2f, Vector2F},
12 AppContext, Axis, Task, ViewContext,
13};
14use language::{Bias, Point};
15use util::ResultExt;
16use workspace::WorkspaceId;
17
18use crate::{
19 display_map::{DisplaySnapshot, ToDisplayPoint},
20 hover_popover::{hide_hover, HideHover},
21 persistence::DB,
22 Anchor, DisplayPoint, Editor, EditorMode, Event, MultiBufferSnapshot, ToPoint,
23};
24
25use self::{
26 autoscroll::{Autoscroll, AutoscrollStrategy},
27 scroll_amount::ScrollAmount,
28};
29
30pub const SCROLL_EVENT_SEPARATION: Duration = Duration::from_millis(28);
31const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
32
33#[derive(Default)]
34pub struct ScrollbarAutoHide(pub bool);
35
36#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct ScrollAnchor {
38 pub offset: Vector2F,
39 pub top_anchor: Anchor,
40}
41
42impl ScrollAnchor {
43 fn new() -> Self {
44 Self {
45 offset: Vector2F::zero(),
46 top_anchor: Anchor::min(),
47 }
48 }
49
50 pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> Vector2F {
51 let mut scroll_position = self.offset;
52 if self.top_anchor != Anchor::min() {
53 let scroll_top = self.top_anchor.to_display_point(snapshot).row() as f32;
54 scroll_position.set_y(scroll_top + scroll_position.y());
55 } else {
56 scroll_position.set_y(0.);
57 }
58 scroll_position
59 }
60
61 pub fn top_row(&self, buffer: &MultiBufferSnapshot) -> u32 {
62 self.top_anchor.to_point(buffer).row
63 }
64}
65
66#[derive(Clone, Copy, Debug)]
67pub struct OngoingScroll {
68 last_event: Instant,
69 axis: Option<Axis>,
70}
71
72impl OngoingScroll {
73 fn new() -> Self {
74 Self {
75 last_event: Instant::now() - SCROLL_EVENT_SEPARATION,
76 axis: None,
77 }
78 }
79
80 pub fn filter(&self, delta: &mut Vector2F) -> Option<Axis> {
81 const UNLOCK_PERCENT: f32 = 1.9;
82 const UNLOCK_LOWER_BOUND: f32 = 6.;
83 let mut axis = self.axis;
84
85 let x = delta.x().abs();
86 let y = delta.y().abs();
87 let duration = Instant::now().duration_since(self.last_event);
88 if duration > SCROLL_EVENT_SEPARATION {
89 //New ongoing scroll will start, determine axis
90 axis = if x <= y {
91 Some(Axis::Vertical)
92 } else {
93 Some(Axis::Horizontal)
94 };
95 } else if x.max(y) >= UNLOCK_LOWER_BOUND {
96 //Check if the current ongoing will need to unlock
97 match axis {
98 Some(Axis::Vertical) => {
99 if x > y && x >= y * UNLOCK_PERCENT {
100 axis = None;
101 }
102 }
103
104 Some(Axis::Horizontal) => {
105 if y > x && y >= x * UNLOCK_PERCENT {
106 axis = None;
107 }
108 }
109
110 None => {}
111 }
112 }
113
114 match axis {
115 Some(Axis::Vertical) => *delta = vec2f(0., delta.y()),
116 Some(Axis::Horizontal) => *delta = vec2f(delta.x(), 0.),
117 None => {}
118 }
119
120 axis
121 }
122}
123
124pub struct ScrollManager {
125 vertical_scroll_margin: f32,
126 anchor: ScrollAnchor,
127 ongoing: OngoingScroll,
128 autoscroll_request: Option<(Autoscroll, bool)>,
129 last_autoscroll: Option<(Vector2F, f32, f32, AutoscrollStrategy)>,
130 show_scrollbars: bool,
131 hide_scrollbar_task: Option<Task<()>>,
132 visible_line_count: Option<f32>,
133}
134
135impl ScrollManager {
136 pub fn new() -> Self {
137 ScrollManager {
138 vertical_scroll_margin: 3.0,
139 anchor: ScrollAnchor::new(),
140 ongoing: OngoingScroll::new(),
141 autoscroll_request: None,
142 show_scrollbars: true,
143 hide_scrollbar_task: None,
144 last_autoscroll: None,
145 visible_line_count: None,
146 }
147 }
148
149 pub fn clone_state(&mut self, other: &Self) {
150 self.anchor = other.anchor;
151 self.ongoing = other.ongoing;
152 }
153
154 pub fn anchor(&self) -> ScrollAnchor {
155 self.anchor
156 }
157
158 pub fn ongoing_scroll(&self) -> OngoingScroll {
159 self.ongoing
160 }
161
162 pub fn update_ongoing_scroll(&mut self, axis: Option<Axis>) {
163 self.ongoing.last_event = Instant::now();
164 self.ongoing.axis = axis;
165 }
166
167 pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> Vector2F {
168 self.anchor.scroll_position(snapshot)
169 }
170
171 fn set_scroll_position(
172 &mut self,
173 scroll_position: Vector2F,
174 map: &DisplaySnapshot,
175 local: bool,
176 workspace_id: Option<i64>,
177 cx: &mut ViewContext<Editor>,
178 ) {
179 let (new_anchor, top_row) = if scroll_position.y() <= 0. {
180 (
181 ScrollAnchor {
182 top_anchor: Anchor::min(),
183 offset: scroll_position.max(vec2f(0., 0.)),
184 },
185 0,
186 )
187 } else {
188 let scroll_top_buffer_point =
189 DisplayPoint::new(scroll_position.y() as u32, 0).to_point(&map);
190 let top_anchor = map
191 .buffer_snapshot
192 .anchor_at(scroll_top_buffer_point, Bias::Right);
193
194 (
195 ScrollAnchor {
196 top_anchor,
197 offset: vec2f(
198 scroll_position.x(),
199 scroll_position.y() - top_anchor.to_display_point(&map).row() as f32,
200 ),
201 },
202 scroll_top_buffer_point.row,
203 )
204 };
205
206 self.set_anchor(new_anchor, top_row, local, workspace_id, cx);
207 }
208
209 fn set_anchor(
210 &mut self,
211 anchor: ScrollAnchor,
212 top_row: u32,
213 local: bool,
214 workspace_id: Option<i64>,
215 cx: &mut ViewContext<Editor>,
216 ) {
217 self.anchor = anchor;
218 cx.emit(Event::ScrollPositionChanged { local });
219 self.show_scrollbar(cx);
220 self.autoscroll_request.take();
221 if let Some(workspace_id) = workspace_id {
222 let item_id = cx.view_id();
223
224 cx.background()
225 .spawn(async move {
226 DB.save_scroll_position(
227 item_id,
228 workspace_id,
229 top_row,
230 anchor.offset.x(),
231 anchor.offset.y(),
232 )
233 .await
234 .log_err()
235 })
236 .detach()
237 }
238 cx.notify();
239 }
240
241 pub fn show_scrollbar(&mut self, cx: &mut ViewContext<Editor>) {
242 if !self.show_scrollbars {
243 self.show_scrollbars = true;
244 cx.notify();
245 }
246
247 if cx.default_global::<ScrollbarAutoHide>().0 {
248 self.hide_scrollbar_task = Some(cx.spawn(|editor, mut cx| async move {
249 cx.background().timer(SCROLLBAR_SHOW_INTERVAL).await;
250 editor
251 .update(&mut cx, |editor, cx| {
252 editor.scroll_manager.show_scrollbars = false;
253 cx.notify();
254 })
255 .log_err();
256 }));
257 } else {
258 self.hide_scrollbar_task = None;
259 }
260 }
261
262 pub fn scrollbars_visible(&self) -> bool {
263 self.show_scrollbars
264 }
265
266 pub fn has_autoscroll_request(&self) -> bool {
267 self.autoscroll_request.is_some()
268 }
269
270 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
271 if max < self.anchor.offset.x() {
272 self.anchor.offset.set_x(max);
273 true
274 } else {
275 false
276 }
277 }
278}
279
280impl Editor {
281 pub fn vertical_scroll_margin(&mut self) -> usize {
282 self.scroll_manager.vertical_scroll_margin as usize
283 }
284
285 pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut ViewContext<Self>) {
286 self.scroll_manager.vertical_scroll_margin = margin_rows as f32;
287 cx.notify();
288 }
289
290 pub fn visible_line_count(&self) -> Option<f32> {
291 self.scroll_manager.visible_line_count
292 }
293
294 pub(crate) fn set_visible_line_count(&mut self, lines: f32) {
295 self.scroll_manager.visible_line_count = Some(lines)
296 }
297
298 pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
299 self.set_scroll_position_internal(scroll_position, true, cx);
300 }
301
302 pub(crate) fn set_scroll_position_internal(
303 &mut self,
304 scroll_position: Vector2F,
305 local: bool,
306 cx: &mut ViewContext<Self>,
307 ) {
308 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
309
310 hide_hover(self, &HideHover, cx);
311 self.scroll_manager.set_scroll_position(
312 scroll_position,
313 &map,
314 local,
315 self.workspace_id,
316 cx,
317 );
318 }
319
320 pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
322 self.scroll_manager.anchor.scroll_position(&display_map)
323 }
324
325 pub fn set_scroll_anchor(&mut self, scroll_anchor: ScrollAnchor, cx: &mut ViewContext<Self>) {
326 hide_hover(self, &HideHover, cx);
327 let top_row = scroll_anchor
328 .top_anchor
329 .to_point(&self.buffer().read(cx).snapshot(cx))
330 .row;
331 self.scroll_manager
332 .set_anchor(scroll_anchor, top_row, true, self.workspace_id, cx);
333 }
334
335 pub(crate) fn set_scroll_anchor_remote(
336 &mut self,
337 scroll_anchor: ScrollAnchor,
338 cx: &mut ViewContext<Self>,
339 ) {
340 hide_hover(self, &HideHover, cx);
341 let top_row = scroll_anchor
342 .top_anchor
343 .to_point(&self.buffer().read(cx).snapshot(cx))
344 .row;
345 self.scroll_manager
346 .set_anchor(scroll_anchor, top_row, false, self.workspace_id, cx);
347 }
348
349 pub fn scroll_screen(&mut self, amount: &ScrollAmount, cx: &mut ViewContext<Self>) {
350 if matches!(self.mode, EditorMode::SingleLine) {
351 cx.propagate_action();
352 return;
353 }
354
355 if self.take_rename(true, cx).is_some() {
356 return;
357 }
358
359 if amount.move_context_menu_selection(self, cx) {
360 return;
361 }
362
363 let cur_position = self.scroll_position(cx);
364 let new_pos = cur_position + vec2f(0., amount.lines(self) - 1.);
365 self.set_scroll_position(new_pos, cx);
366 }
367
368 /// Returns an ordering. The newest selection is:
369 /// Ordering::Equal => on screen
370 /// Ordering::Less => above the screen
371 /// Ordering::Greater => below the screen
372 pub fn newest_selection_on_screen(&self, cx: &mut AppContext) -> Ordering {
373 let snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
374 let newest_head = self
375 .selections
376 .newest_anchor()
377 .head()
378 .to_display_point(&snapshot);
379 let screen_top = self
380 .scroll_manager
381 .anchor
382 .top_anchor
383 .to_display_point(&snapshot);
384
385 if screen_top > newest_head {
386 return Ordering::Less;
387 }
388
389 if let Some(visible_lines) = self.visible_line_count() {
390 if newest_head.row() < screen_top.row() + visible_lines as u32 {
391 return Ordering::Equal;
392 }
393 }
394
395 Ordering::Greater
396 }
397
398 pub fn read_scroll_position_from_db(
399 &mut self,
400 item_id: usize,
401 workspace_id: WorkspaceId,
402 cx: &mut ViewContext<Editor>,
403 ) {
404 let scroll_position = DB.get_scroll_position(item_id, workspace_id);
405 if let Ok(Some((top_row, x, y))) = scroll_position {
406 let top_anchor = self
407 .buffer()
408 .read(cx)
409 .snapshot(cx)
410 .anchor_at(Point::new(top_row as u32, 0), Bias::Left);
411 let scroll_anchor = ScrollAnchor {
412 offset: Vector2F::new(x, y),
413 top_anchor,
414 };
415 self.set_scroll_anchor(scroll_anchor, cx);
416 }
417 }
418}