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