1use std::rc::Rc;
4use std::time::Duration;
5
6use waft_animation::{AnimationBehavior, AnimationController, Curve};
7use waft_embedder::PointerDeviceKind;
8use waft_foundation::{
9 App, Completer, CompleterFuture, Handle, HandleId, ListenableObject, Listener, OptionRetained,
10 PRECISION_ERROR_TOLERANCE, Retained,
11};
12use waft_gestures::{DragEndDetails, DragObject, DragStartDetails, DragUpdateDetails};
13use waft_painting::{AxisDirection, axis_direction_is_reversed};
14use waft_physics::Simulation;
15use waft_scheduler::TickerProvider;
16
17use crate::framework::{BuildContext, Notification};
18use crate::widgets::scroll_metrics::ScrollMetrics;
19use crate::widgets::scroll_notification::{
20 OverscrollNotification, ScrollEndNotification, ScrollStartNotification,
21 ScrollUpdateNotification,
22};
23use waft_foundation::Ref;
24
25pub trait ScrollActivityDelegate: Sized + 'static {
35 fn axis_direction(self: Handle<Self>, app: &App) -> AxisDirection;
37
38 fn set_pixels(self: Handle<Self>, app: &mut App, pixels: f64) -> f64;
43
44 fn apply_user_offset(self: Handle<Self>, app: &mut App, delta: f64);
51
52 fn go_idle(self: Handle<Self>, app: &mut App);
54
55 fn go_ballistic(self: Handle<Self>, app: &mut App, velocity: f64);
58
59 fn as_scroll_activity_delegate(self: Handle<Self>) -> AnyScrollActivityDelegate {
62 AnyScrollActivityDelegate {
63 id: self.id(),
64 vtable: const { &ScrollActivityDelegateVTable::of::<Self>() },
65 }
66 }
67}
68
69struct ScrollActivityDelegateVTable {
71 axis_direction: fn(&App, HandleId) -> AxisDirection,
72 set_pixels: fn(&mut App, HandleId, f64) -> f64,
73 apply_user_offset: fn(&mut App, HandleId, f64),
74 go_idle: fn(&mut App, HandleId),
75 go_ballistic: fn(&mut App, HandleId, f64),
76}
77
78fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
80 Handle::from_id(id)
81}
82
83impl ScrollActivityDelegateVTable {
84 const fn of<D: ScrollActivityDelegate>() -> ScrollActivityDelegateVTable {
86 ScrollActivityDelegateVTable {
87 axis_direction: |app, id| D::axis_direction(resolve(id), app),
88 set_pixels: |app, id, pixels| D::set_pixels(resolve(id), app, pixels),
89 apply_user_offset: |app, id, delta| D::apply_user_offset(resolve(id), app, delta),
90 go_idle: |app, id| D::go_idle(resolve(id), app),
91 go_ballistic: |app, id, velocity| D::go_ballistic(resolve(id), app, velocity),
92 }
93 }
94}
95
96#[derive(Clone, Copy)]
100pub struct AnyScrollActivityDelegate {
101 id: HandleId,
102 vtable: &'static ScrollActivityDelegateVTable,
103}
104
105impl AnyScrollActivityDelegate {
106 pub fn axis_direction(self, app: &App) -> AxisDirection {
108 (self.vtable.axis_direction)(app, self.id)
109 }
110
111 pub fn set_pixels(self, app: &mut App, pixels: f64) -> f64 {
113 (self.vtable.set_pixels)(app, self.id, pixels)
114 }
115
116 pub fn apply_user_offset(self, app: &mut App, delta: f64) {
118 (self.vtable.apply_user_offset)(app, self.id, delta);
119 }
120
121 pub fn go_idle(self, app: &mut App) {
123 (self.vtable.go_idle)(app, self.id);
124 }
125
126 pub fn go_ballistic(self, app: &mut App, velocity: f64) {
128 (self.vtable.go_ballistic)(app, self.id, velocity);
129 }
130}
131
132impl PartialEq for AnyScrollActivityDelegate {
133 fn eq(&self, other: &AnyScrollActivityDelegate) -> bool {
134 self.id == other.id
135 }
136}
137
138impl Eq for AnyScrollActivityDelegate {}
139
140pub struct ScrollActivityData {
142 delegate: AnyScrollActivityDelegate,
143 is_disposed: bool,
144}
145
146impl ScrollActivityData {
147 pub fn new(delegate: AnyScrollActivityDelegate) -> ScrollActivityData {
149 ScrollActivityData {
150 delegate,
151 is_disposed: false,
152 }
153 }
154}
155
156#[macro_export]
159macro_rules! scroll_activity_accessors {
160 () => {
161 fn scroll_activity_data(
162 self: ::waft_foundation::Handle<Self>,
163 app: &::waft_foundation::App,
164 ) -> &$crate::ScrollActivityData {
165 &app.get(self).scroll_activity
166 }
167
168 fn scroll_activity_data_mut(
169 self: ::waft_foundation::Handle<Self>,
170 app: &mut ::waft_foundation::App,
171 ) -> &mut $crate::ScrollActivityData {
172 &mut app.get_mut(self).scroll_activity
173 }
174 };
175}
176
177pub trait ScrollActivity: Sized + 'static {
187 fn scroll_activity_data(self: Handle<Self>, app: &App) -> &ScrollActivityData;
190
191 fn scroll_activity_data_mut(self: Handle<Self>, app: &mut App) -> &mut ScrollActivityData;
193
194 fn delegate(self: Handle<Self>, app: &App) -> AnyScrollActivityDelegate {
196 self.scroll_activity_data(app).delegate
197 }
198
199 fn is_disposed(self: Handle<Self>, app: &App) -> bool {
201 self.scroll_activity_data(app).is_disposed
202 }
203
204 fn update_delegate(self: Handle<Self>, app: &mut App, value: AnyScrollActivityDelegate) {
209 debug_assert!(self.delegate(app) != value);
210 self.scroll_activity_data_mut(app).delegate = value;
211 }
212
213 fn reset_activity(self: Handle<Self>, app: &mut App) {
222 let _ = (self, app);
223 }
224
225 fn dispatch_scroll_start_notification(
227 self: Handle<Self>,
228 app: &mut App,
229 metrics: Rc<dyn ScrollMetrics>,
230 context: Option<BuildContext>,
231 ) {
232 ScrollActivityBase::dispatch_scroll_start_notification(app, metrics, context);
233 }
234
235 fn dispatch_scroll_update_notification(
237 self: Handle<Self>,
238 app: &mut App,
239 metrics: Rc<dyn ScrollMetrics>,
240 context: BuildContext,
241 scroll_delta: f64,
242 ) {
243 ScrollActivityBase::dispatch_scroll_update_notification(
244 app,
245 metrics,
246 context,
247 scroll_delta,
248 );
249 }
250
251 fn dispatch_overscroll_notification(
253 self: Handle<Self>,
254 app: &mut App,
255 metrics: Rc<dyn ScrollMetrics>,
256 context: BuildContext,
257 overscroll: f64,
258 ) {
259 ScrollActivityBase::dispatch_overscroll_notification(app, metrics, context, overscroll);
260 }
261
262 fn dispatch_scroll_end_notification(
264 self: Handle<Self>,
265 app: &mut App,
266 metrics: Rc<dyn ScrollMetrics>,
267 context: BuildContext,
268 ) {
269 ScrollActivityBase::dispatch_scroll_end_notification(app, metrics, context);
270 }
271
272 fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
274 let _ = (self, app);
275 }
276
277 fn should_ignore_pointer(self: Handle<Self>, app: &App) -> bool;
285
286 fn is_scrolling(self: Handle<Self>, app: &App) -> bool;
298
299 fn velocity(self: Handle<Self>, app: &mut App) -> f64;
303
304 fn dispose(self: Handle<Self>, app: &mut App) {
306 ScrollActivityBase::dispose(self, app);
307 }
308
309 fn describe(self: Handle<Self>, app: &App) -> String {
311 let _ = app;
312 describe_identity::<Self>(self.id())
313 }
314
315 fn as_hold_controller(self: Handle<Self>) -> Option<Rc<dyn ScrollHoldController>> {
318 let _ = self;
319 None
320 }
321
322 fn as_activity(self: Handle<Self>) -> AnyScrollActivity {
325 AnyScrollActivity {
326 id: self.id(),
327 vtable: const { &ScrollActivityVTable::of::<Self>() },
328 }
329 }
330}
331
332fn describe_identity<T: ?Sized>(id: HandleId) -> String {
334 let name = std::any::type_name::<T>();
335 let short = name.rsplit("::").next().unwrap_or(name);
336 format!("{short}#{id:?}")
337}
338
339pub struct ScrollActivityBase;
341
342impl ScrollActivityBase {
343 pub fn dispatch_scroll_start_notification(
345 app: &mut App,
346 metrics: Rc<dyn ScrollMetrics>,
347 context: Option<BuildContext>,
348 ) {
349 ScrollStartNotification::new(metrics, context).dispatch(app, context);
350 }
351
352 pub fn dispatch_scroll_update_notification(
354 app: &mut App,
355 metrics: Rc<dyn ScrollMetrics>,
356 context: BuildContext,
357 scroll_delta: f64,
358 ) {
359 ScrollUpdateNotification::new(metrics, context)
360 .scroll_delta(scroll_delta)
361 .dispatch(app, Some(context));
362 }
363
364 pub fn dispatch_overscroll_notification(
366 app: &mut App,
367 metrics: Rc<dyn ScrollMetrics>,
368 context: BuildContext,
369 overscroll: f64,
370 ) {
371 OverscrollNotification::new(metrics, context, overscroll).dispatch(app, Some(context));
372 }
373
374 pub fn dispatch_scroll_end_notification(
376 app: &mut App,
377 metrics: Rc<dyn ScrollMetrics>,
378 context: BuildContext,
379 ) {
380 ScrollEndNotification::new(metrics, context).dispatch(app, Some(context));
381 }
382
383 pub fn dispose<A: ScrollActivity>(this: Handle<A>, app: &mut App) {
385 this.scroll_activity_data_mut(app).is_disposed = true;
386 }
387}
388
389type DispatchDeltaFn = fn(&mut App, HandleId, Rc<dyn ScrollMetrics>, BuildContext, f64);
391
392struct ScrollActivityVTable {
395 delegate: fn(&App, HandleId) -> AnyScrollActivityDelegate,
396 is_disposed: fn(&App, HandleId) -> bool,
397 update_delegate: fn(&mut App, HandleId, AnyScrollActivityDelegate),
398 reset_activity: fn(&mut App, HandleId),
399 dispatch_scroll_start_notification:
400 fn(&mut App, HandleId, Rc<dyn ScrollMetrics>, Option<BuildContext>),
401 dispatch_scroll_update_notification: DispatchDeltaFn,
402 dispatch_overscroll_notification: DispatchDeltaFn,
403 dispatch_scroll_end_notification: fn(&mut App, HandleId, Rc<dyn ScrollMetrics>, BuildContext),
404 apply_new_dimensions: fn(&mut App, HandleId),
405 should_ignore_pointer: fn(&App, HandleId) -> bool,
406 is_scrolling: fn(&App, HandleId) -> bool,
407 velocity: fn(&mut App, HandleId) -> f64,
408 dispose: fn(&mut App, HandleId),
409 describe: fn(&App, HandleId) -> String,
410 as_hold_controller: fn(HandleId) -> Option<Rc<dyn ScrollHoldController>>,
411}
412
413impl ScrollActivityVTable {
414 const fn of<A: ScrollActivity>() -> ScrollActivityVTable {
416 ScrollActivityVTable {
417 delegate: |app, id| A::delegate(resolve(id), app),
418 is_disposed: |app, id| A::is_disposed(resolve(id), app),
419 update_delegate: |app, id, value| A::update_delegate(resolve(id), app, value),
420 reset_activity: |app, id| A::reset_activity(resolve(id), app),
421 dispatch_scroll_start_notification: |app, id, metrics, context| {
422 A::dispatch_scroll_start_notification(resolve(id), app, metrics, context);
423 },
424 dispatch_scroll_update_notification: |app, id, metrics, context, delta| {
425 A::dispatch_scroll_update_notification(resolve(id), app, metrics, context, delta);
426 },
427 dispatch_overscroll_notification: |app, id, metrics, context, overscroll| {
428 A::dispatch_overscroll_notification(resolve(id), app, metrics, context, overscroll);
429 },
430 dispatch_scroll_end_notification: |app, id, metrics, context| {
431 A::dispatch_scroll_end_notification(resolve(id), app, metrics, context);
432 },
433 apply_new_dimensions: |app, id| A::apply_new_dimensions(resolve(id), app),
434 should_ignore_pointer: |app, id| A::should_ignore_pointer(resolve(id), app),
435 is_scrolling: |app, id| A::is_scrolling(resolve(id), app),
436 velocity: |app, id| A::velocity(resolve(id), app),
437 dispose: |app, id| A::dispose(resolve(id), app),
438 describe: |app, id| A::describe(resolve(id), app),
439 as_hold_controller: |id| A::as_hold_controller(resolve(id)),
440 }
441 }
442}
443
444#[derive(Clone, Copy)]
449pub struct AnyScrollActivity {
450 id: HandleId,
451 vtable: &'static ScrollActivityVTable,
452}
453
454pub type ScrollActivityRef = Retained<AnyScrollActivity>;
456
457waft_foundation::erased_handle!(AnyScrollActivity: ScrollActivity => ScrollActivity::as_activity);
458
459impl AnyScrollActivity {
460 pub fn delegate(self, app: &App) -> AnyScrollActivityDelegate {
462 (self.vtable.delegate)(app, self.id)
463 }
464
465 pub fn is_disposed(self, app: &App) -> bool {
467 (self.vtable.is_disposed)(app, self.id)
468 }
469
470 pub fn update_delegate(self, app: &mut App, value: AnyScrollActivityDelegate) {
472 (self.vtable.update_delegate)(app, self.id, value);
473 }
474
475 pub fn reset_activity(self, app: &mut App) {
477 (self.vtable.reset_activity)(app, self.id);
478 }
479
480 pub fn dispatch_scroll_start_notification(
482 self,
483 app: &mut App,
484 metrics: Rc<dyn ScrollMetrics>,
485 context: Option<BuildContext>,
486 ) {
487 (self.vtable.dispatch_scroll_start_notification)(app, self.id, metrics, context);
488 }
489
490 pub fn dispatch_scroll_update_notification(
492 self,
493 app: &mut App,
494 metrics: Rc<dyn ScrollMetrics>,
495 context: BuildContext,
496 scroll_delta: f64,
497 ) {
498 (self.vtable.dispatch_scroll_update_notification)(
499 app,
500 self.id,
501 metrics,
502 context,
503 scroll_delta,
504 );
505 }
506
507 pub fn dispatch_overscroll_notification(
509 self,
510 app: &mut App,
511 metrics: Rc<dyn ScrollMetrics>,
512 context: BuildContext,
513 overscroll: f64,
514 ) {
515 (self.vtable.dispatch_overscroll_notification)(app, self.id, metrics, context, overscroll);
516 }
517
518 pub fn dispatch_scroll_end_notification(
520 self,
521 app: &mut App,
522 metrics: Rc<dyn ScrollMetrics>,
523 context: BuildContext,
524 ) {
525 (self.vtable.dispatch_scroll_end_notification)(app, self.id, metrics, context);
526 }
527
528 pub fn apply_new_dimensions(self, app: &mut App) {
530 (self.vtable.apply_new_dimensions)(app, self.id);
531 }
532
533 pub fn should_ignore_pointer(self, app: &App) -> bool {
535 (self.vtable.should_ignore_pointer)(app, self.id)
536 }
537
538 pub fn is_scrolling(self, app: &App) -> bool {
540 (self.vtable.is_scrolling)(app, self.id)
541 }
542
543 pub fn velocity(self, app: &mut App) -> f64 {
545 (self.vtable.velocity)(app, self.id)
546 }
547
548 pub fn dispose(self, app: &mut App) {
550 (self.vtable.dispose)(app, self.id);
551 }
552
553 pub fn describe(self, app: &App) -> String {
555 (self.vtable.describe)(app, self.id)
556 }
557
558 pub fn as_hold_controller(self) -> Option<Rc<dyn ScrollHoldController>> {
560 (self.vtable.as_hold_controller)(self.id)
561 }
562}
563
564pub struct IdleScrollActivity {
571 scroll_activity: ScrollActivityData,
572}
573
574impl IdleScrollActivity {
575 pub fn new(app: &mut App, delegate: AnyScrollActivityDelegate) -> Ref<IdleScrollActivity> {
577 app.create(IdleScrollActivity {
578 scroll_activity: ScrollActivityData::new(delegate),
579 })
580 }
581}
582
583impl ScrollActivity for IdleScrollActivity {
584 crate::scroll_activity_accessors!();
585
586 fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
587 self.delegate(app).go_ballistic(app, 0.0);
588 }
589
590 fn should_ignore_pointer(self: Handle<Self>, _app: &App) -> bool {
591 false
592 }
593
594 fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
595 false
596 }
597
598 fn velocity(self: Handle<Self>, _app: &mut App) -> f64 {
599 0.0
600 }
601}
602
603pub trait ScrollHoldController {
613 fn cancel(&self, app: &mut App);
616}
617
618pub trait ScrollHoldControllerObject: Sized + 'static {
621 fn cancel(self: Handle<Self>, app: &mut App);
623}
624
625impl<T: ScrollHoldControllerObject> ScrollHoldController for Handle<T> {
626 fn cancel(&self, app: &mut App) {
627 T::cancel(*self, app);
628 }
629}
630
631impl<T: ScrollHoldControllerObject> ScrollHoldController for Ref<T> {
633 fn cancel(&self, app: &mut App) {
634 T::cancel(self.handle(), app);
635 }
636}
637
638pub struct HoldScrollActivity {
649 scroll_activity: ScrollActivityData,
650 pub on_hold_canceled: Option<Listener>,
652}
653
654impl HoldScrollActivity {
655 pub fn new(
657 app: &mut App,
658 delegate: AnyScrollActivityDelegate,
659 on_hold_canceled: Option<Listener>,
660 ) -> Ref<HoldScrollActivity> {
661 app.create(HoldScrollActivity {
662 scroll_activity: ScrollActivityData::new(delegate),
663 on_hold_canceled,
664 })
665 }
666}
667
668impl ScrollActivity for HoldScrollActivity {
669 crate::scroll_activity_accessors!();
670
671 fn should_ignore_pointer(self: Handle<Self>, _app: &App) -> bool {
672 false
673 }
674
675 fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
676 false
677 }
678
679 fn velocity(self: Handle<Self>, _app: &mut App) -> f64 {
680 0.0
681 }
682
683 fn dispose(self: Handle<Self>, app: &mut App) {
684 if let Some(on_hold_canceled) = app.get(self).on_hold_canceled.clone() {
685 on_hold_canceled.call(app);
686 }
687 ScrollActivityBase::dispose(self, app);
688 }
689
690 fn as_hold_controller(self: Handle<Self>) -> Option<Rc<dyn ScrollHoldController>> {
691 Some(Rc::new(self))
692 }
693}
694
695impl ScrollHoldControllerObject for HoldScrollActivity {
696 fn cancel(self: Handle<Self>, app: &mut App) {
697 self.delegate(app).go_ballistic(app, 0.0);
698 }
699}
700
701#[derive(Clone)]
703pub enum LastDragDetails {
704 Start(DragStartDetails),
706 Update(DragUpdateDetails),
708 End(DragEndDetails),
710}
711
712pub struct ScrollDragController {
719 delegate: AnyScrollActivityDelegate,
720
721 pub on_drag_canceled: Option<Listener>,
723
724 pub carried_velocity: Option<f64>,
727
728 pub motion_start_distance_threshold: Option<f64>,
731
732 last_non_stationary_timestamp: Option<Duration>,
733 retain_momentum: bool,
734 offset_since_last_stop: Option<f64>,
737 kind: Option<PointerDeviceKind>,
738 last_details: Option<LastDragDetails>,
739}
740
741impl ScrollDragController {
742 pub const MOMENTUM_RETAIN_STATIONARY_DURATION_THRESHOLD: Duration = Duration::from_millis(20);
746
747 pub const MOMENTUM_RETAIN_VELOCITY_THRESHOLD_FACTOR: f64 = 0.5;
755
756 pub const MOTION_STOPPED_DURATION_THRESHOLD: Duration = Duration::from_millis(50);
761
762 const BIG_THRESHOLD_BREAK_DISTANCE: f64 = 24.0;
766
767 pub fn new(
770 app: &mut App,
771 delegate: AnyScrollActivityDelegate,
772 details: DragStartDetails,
773 on_drag_canceled: Option<Listener>,
774 carried_velocity: Option<f64>,
775 motion_start_distance_threshold: Option<f64>,
776 ) -> Ref<ScrollDragController> {
777 debug_assert!(
778 motion_start_distance_threshold.is_none_or(|threshold| threshold > 0.0),
779 "motionStartDistanceThreshold must be a positive number or null"
780 );
781 app.create(ScrollDragController {
782 delegate,
783 on_drag_canceled,
784 carried_velocity,
785 motion_start_distance_threshold,
786 last_non_stationary_timestamp: details.source_time_stamp,
787 retain_momentum: carried_velocity.is_some_and(|velocity| velocity != 0.0),
788 offset_since_last_stop: motion_start_distance_threshold.map(|_| 0.0),
789 kind: details.kind,
790 last_details: Some(LastDragDetails::Start(details)),
791 })
792 }
793
794 pub fn delegate(self: Handle<Self>, app: &App) -> AnyScrollActivityDelegate {
796 app.get(self).delegate
797 }
798
799 pub fn kind(self: Handle<Self>, app: &App) -> Option<PointerDeviceKind> {
801 app.get(self).kind
802 }
803
804 pub fn last_details(self: Handle<Self>, app: &App) -> Option<&LastDragDetails> {
807 app.get(self).last_details.as_ref()
808 }
809
810 pub fn update_delegate(self: Handle<Self>, app: &mut App, value: AnyScrollActivityDelegate) {
815 debug_assert!(app.get(self).delegate != value);
816 app.get_mut(self).delegate = value;
817 }
818
819 pub fn dispose(self: Handle<Self>, app: &mut App) {
821 app.get_mut(self).last_details = None;
822 if let Some(on_drag_canceled) = app.get(self).on_drag_canceled.clone() {
823 on_drag_canceled.call(app);
824 }
825 }
826
827 pub fn describe(self: Handle<Self>) -> String {
829 describe_identity::<ScrollDragController>(self.id())
830 }
831
832 fn reversed(self: Handle<Self>, app: &App) -> bool {
833 axis_direction_is_reversed(self.delegate(app).axis_direction(app))
834 }
835
836 fn maybe_lose_momentum(
839 self: Handle<Self>,
840 app: &mut App,
841 offset: f64,
842 timestamp: Option<Duration>,
843 ) {
844 let controller = app.get(self);
845 if controller.retain_momentum
846 && offset == 0.0
847 && timestamp.is_none_or(|timestamp| {
848 timestamp.saturating_sub(
850 controller
851 .last_non_stationary_timestamp
852 .expect("a retained momentum carries a timestamp"),
853 ) > Self::MOMENTUM_RETAIN_STATIONARY_DURATION_THRESHOLD
854 })
855 {
856 app.get_mut(self).retain_momentum = false;
858 }
859 }
860
861 fn adjust_for_scroll_start_threshold(
868 self: Handle<Self>,
869 app: &mut App,
870 offset: f64,
871 timestamp: Option<Duration>,
872 ) -> f64 {
873 let Some(timestamp) = timestamp else {
874 return offset;
877 };
878 let controller = app.get(self);
879 let threshold = controller.motion_start_distance_threshold;
880 if offset == 0.0 {
881 if threshold.is_some()
882 && controller.offset_since_last_stop.is_none()
883 && timestamp.saturating_sub(
884 controller
885 .last_non_stationary_timestamp
886 .expect("a stationary update follows a timestamped one"),
887 ) > Self::MOTION_STOPPED_DURATION_THRESHOLD
888 {
889 app.get_mut(self).offset_since_last_stop = Some(0.0);
891 }
892 0.0
894 } else {
895 let Some(offset_since_last_stop) = controller.offset_since_last_stop else {
896 return offset;
899 };
900 let offset_since_last_stop = offset_since_last_stop + offset;
901 app.get_mut(self).offset_since_last_stop = Some(offset_since_last_stop);
902 let threshold = threshold.expect("an offset since the last stop implies a threshold");
903 if offset_since_last_stop.abs() > threshold {
904 app.get_mut(self).offset_since_last_stop = None;
906 if offset.abs() > Self::BIG_THRESHOLD_BREAK_DISTANCE {
907 offset
910 } else {
911 (threshold / 3.0).min(offset.abs()) * offset.signum()
915 }
916 } else {
917 0.0
918 }
919 }
920 }
921}
922
923impl DragObject for ScrollDragController {
924 fn update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
925 debug_assert!(details.primary_delta.is_some());
926 let mut offset = details.primary_delta.expect("a primary delta");
927 let source_time_stamp = details.source_time_stamp;
928 app.get_mut(self).last_details = Some(LastDragDetails::Update(details));
929 if offset != 0.0 {
930 app.get_mut(self).last_non_stationary_timestamp = source_time_stamp;
931 }
932 self.maybe_lose_momentum(app, offset, source_time_stamp);
936 offset = self.adjust_for_scroll_start_threshold(app, offset, source_time_stamp);
937 if offset == 0.0 {
938 return;
939 }
940 if self.reversed(app) {
941 offset = -offset;
942 }
943 self.delegate(app).apply_user_offset(app, offset);
944 }
945
946 fn end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
947 debug_assert!(details.primary_velocity.is_some());
948 let mut velocity = -details.primary_velocity.expect("a primary velocity");
952 if self.reversed(app) {
953 velocity = -velocity;
954 }
955 app.get_mut(self).last_details = Some(LastDragDetails::End(details));
956
957 let controller = app.get(self);
958 if controller.retain_momentum {
959 let carried_velocity = controller
960 .carried_velocity
961 .expect("a retained momentum carries a velocity");
962 let is_flinging_in_same_direction = velocity.signum() == carried_velocity.signum();
964 let is_velocity_not_substantially_less_than_carried_momentum = velocity.abs()
967 > carried_velocity.abs() * Self::MOMENTUM_RETAIN_VELOCITY_THRESHOLD_FACTOR;
968 if is_flinging_in_same_direction
969 && is_velocity_not_substantially_less_than_carried_momentum
970 {
971 velocity += carried_velocity;
972 }
973 }
974 self.delegate(app).go_ballistic(app, velocity);
975 }
976
977 fn cancel(self: Handle<Self>, app: &mut App) {
978 self.delegate(app).go_ballistic(app, 0.0);
979 }
980}
981
982pub struct DragScrollActivity {
990 scroll_activity: ScrollActivityData,
991 controller: Option<Ref<ScrollDragController>>,
992}
993
994impl DragScrollActivity {
995 pub fn new(
998 app: &mut App,
999 delegate: AnyScrollActivityDelegate,
1000 controller: Ref<ScrollDragController>,
1001 ) -> Ref<DragScrollActivity> {
1002 app.create(DragScrollActivity {
1003 scroll_activity: ScrollActivityData::new(delegate),
1004 controller: Some(controller),
1005 })
1006 }
1007
1008 fn controller(self: Handle<Self>, app: &App) -> Handle<ScrollDragController> {
1009 app.get(self)
1010 .controller
1011 .handle()
1012 .expect("the drag activity outlives its controller")
1013 }
1014}
1015
1016impl ScrollActivity for DragScrollActivity {
1017 crate::scroll_activity_accessors!();
1018
1019 fn dispatch_scroll_start_notification(
1020 self: Handle<Self>,
1021 app: &mut App,
1022 metrics: Rc<dyn ScrollMetrics>,
1023 context: Option<BuildContext>,
1024 ) {
1025 let last_details = self.controller(app).last_details(app).cloned();
1026 let Some(LastDragDetails::Start(drag_details)) = last_details else {
1027 unreachable!("a drag activity starts with its start details");
1028 };
1029 ScrollStartNotification::new(metrics, context)
1030 .drag_details(drag_details)
1031 .dispatch(app, context);
1032 }
1033
1034 fn dispatch_scroll_update_notification(
1035 self: Handle<Self>,
1036 app: &mut App,
1037 metrics: Rc<dyn ScrollMetrics>,
1038 context: BuildContext,
1039 scroll_delta: f64,
1040 ) {
1041 let last_details = self.controller(app).last_details(app).cloned();
1042 let Some(LastDragDetails::Update(drag_details)) = last_details else {
1043 unreachable!("a drag update carries its update details");
1044 };
1045 ScrollUpdateNotification::new(metrics, context)
1046 .scroll_delta(scroll_delta)
1047 .drag_details(drag_details)
1048 .dispatch(app, Some(context));
1049 }
1050
1051 fn dispatch_overscroll_notification(
1052 self: Handle<Self>,
1053 app: &mut App,
1054 metrics: Rc<dyn ScrollMetrics>,
1055 context: BuildContext,
1056 overscroll: f64,
1057 ) {
1058 let last_details = self.controller(app).last_details(app).cloned();
1059 let Some(LastDragDetails::Update(drag_details)) = last_details else {
1060 unreachable!("an overscroll follows an update");
1061 };
1062 OverscrollNotification::new(metrics, context, overscroll)
1063 .drag_details(drag_details)
1064 .dispatch(app, Some(context));
1065 }
1066
1067 fn dispatch_scroll_end_notification(
1068 self: Handle<Self>,
1069 app: &mut App,
1070 metrics: Rc<dyn ScrollMetrics>,
1071 context: BuildContext,
1072 ) {
1073 let last_details = self.controller(app).last_details(app).cloned();
1075 let mut notification = ScrollEndNotification::new(metrics, context);
1076 if let Some(LastDragDetails::End(drag_details)) = last_details {
1077 notification = notification.drag_details(drag_details);
1078 }
1079 notification.dispatch(app, Some(context));
1080 }
1081
1082 fn should_ignore_pointer(self: Handle<Self>, app: &App) -> bool {
1083 app.get(self)
1084 .controller
1085 .as_ref()
1086 .and_then(|controller| controller.kind(app))
1087 != Some(PointerDeviceKind::Trackpad)
1088 }
1089
1090 fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
1091 true
1092 }
1093
1094 fn velocity(self: Handle<Self>, _app: &mut App) -> f64 {
1097 0.0
1098 }
1099
1100 fn dispose(self: Handle<Self>, app: &mut App) {
1101 app.get_mut(self).controller = None;
1102 ScrollActivityBase::dispose(self, app);
1103 }
1104
1105 fn describe(self: Handle<Self>, app: &App) -> String {
1106 let controller = app.get(self).controller.handle();
1107 let described =
1108 controller.map_or_else(|| "null".to_string(), ScrollDragController::describe);
1109 format!(
1110 "{}({described})",
1111 describe_identity::<DragScrollActivity>(self.id())
1112 )
1113 }
1114}
1115
1116pub struct BallisticScrollActivity {
1141 scroll_activity: ScrollActivityData,
1142 controller: Ref<AnimationController>,
1143 should_ignore_pointer: bool,
1144}
1145
1146impl BallisticScrollActivity {
1147 pub fn new(
1153 app: &mut App,
1154 delegate: AnyScrollActivityDelegate,
1155 simulation: Box<dyn Simulation>,
1156 vsync: impl TickerProvider,
1157 should_ignore_pointer: bool,
1158 ) -> Ref<BallisticScrollActivity> {
1159 let controller = AnimationController::unbounded(
1160 app,
1161 0.0,
1162 None,
1163 None,
1164 AnimationBehavior::Preserve,
1165 vsync,
1166 );
1167 let this = app.create(BallisticScrollActivity {
1168 scroll_activity: ScrollActivityData::new(delegate),
1169 controller: controller.clone(),
1170 should_ignore_pointer,
1171 });
1172 controller.add_listener(app, Listener::handle_method(this.handle(), Self::tick));
1173 let done = controller.animate_with(app, simulation);
1174 done.when_complete(app, Listener::handle_method(this.handle(), Self::end));
1176 this
1177 }
1178
1179 fn tick(self: Handle<Self>, app: &mut App) {
1180 let value = app.get(self).controller.value(app);
1181 if !self.apply_move_to(app, value) {
1182 self.delegate(app).go_idle(app);
1183 }
1184 }
1185
1186 pub fn apply_move_to(self: Handle<Self>, app: &mut App, value: f64) -> bool {
1194 self.delegate(app).set_pixels(app, value).abs() < PRECISION_ERROR_TOLERANCE
1195 }
1196
1197 fn end(self: Handle<Self>, app: &mut App) {
1198 if !self.is_disposed(app) {
1201 self.delegate(app).go_ballistic(app, 0.0);
1202 }
1203 }
1204}
1205
1206impl ScrollActivity for BallisticScrollActivity {
1207 crate::scroll_activity_accessors!();
1208
1209 fn reset_activity(self: Handle<Self>, app: &mut App) {
1210 let velocity = self.velocity(app);
1211 self.delegate(app).go_ballistic(app, velocity);
1212 }
1213
1214 fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
1215 let velocity = self.velocity(app);
1216 self.delegate(app).go_ballistic(app, velocity);
1217 }
1218
1219 fn dispatch_overscroll_notification(
1220 self: Handle<Self>,
1221 app: &mut App,
1222 metrics: Rc<dyn ScrollMetrics>,
1223 context: BuildContext,
1224 overscroll: f64,
1225 ) {
1226 let velocity = self.velocity(app);
1227 OverscrollNotification::new(metrics, context, overscroll)
1228 .velocity(velocity)
1229 .dispatch(app, Some(context));
1230 }
1231
1232 fn should_ignore_pointer(self: Handle<Self>, app: &App) -> bool {
1233 app.get(self).should_ignore_pointer
1234 }
1235
1236 fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
1237 true
1238 }
1239
1240 fn velocity(self: Handle<Self>, app: &mut App) -> f64 {
1241 app.get(self).controller.velocity(app)
1242 }
1243
1244 fn dispose(self: Handle<Self>, app: &mut App) {
1245 app.get(self).controller.dispose(app);
1246 ScrollActivityBase::dispose(self, app);
1247 }
1248
1249 fn describe(self: Handle<Self>, app: &App) -> String {
1250 format!(
1251 "{}({:?})",
1252 describe_identity::<BallisticScrollActivity>(self.id()),
1253 app.get(self).controller.id()
1254 )
1255 }
1256}
1257
1258pub struct DrivenScrollActivity {
1274 scroll_activity: ScrollActivityData,
1275 completer: Completer<()>,
1276 controller: Ref<AnimationController>,
1277}
1278
1279impl DrivenScrollActivity {
1280 pub fn new(
1283 app: &mut App,
1284 delegate: AnyScrollActivityDelegate,
1285 from: f64,
1286 to: f64,
1287 duration: Duration,
1288 curve: Rc<dyn Curve>,
1289 vsync: impl TickerProvider,
1290 ) -> Ref<DrivenScrollActivity> {
1291 debug_assert!(duration > Duration::ZERO);
1292 let completer = Completer::new();
1293 let controller = AnimationController::unbounded(
1294 app,
1295 from,
1296 None,
1297 None,
1298 AnimationBehavior::Preserve,
1299 vsync,
1300 );
1301 let this = app.create(DrivenScrollActivity {
1302 scroll_activity: ScrollActivityData::new(delegate),
1303 completer,
1304 controller: controller.clone(),
1305 });
1306 controller.add_listener(app, Listener::handle_method(this.handle(), Self::tick));
1307 let done = controller.animate_to(app, to, Some(duration), curve);
1308 done.when_complete(app, Listener::handle_method(this.handle(), Self::end));
1310 this
1311 }
1312
1313 pub fn simulation(
1316 app: &mut App,
1317 delegate: AnyScrollActivityDelegate,
1318 simulation: Box<dyn Simulation>,
1319 vsync: impl TickerProvider,
1320 ) -> Ref<DrivenScrollActivity> {
1321 let completer = Completer::new();
1322 let controller = AnimationController::unbounded(
1323 app,
1324 0.0,
1325 None,
1326 None,
1327 AnimationBehavior::Preserve,
1328 vsync,
1329 );
1330 let this = app.create(DrivenScrollActivity {
1331 scroll_activity: ScrollActivityData::new(delegate),
1332 completer,
1333 controller: controller.clone(),
1334 });
1335 controller.add_listener(app, Listener::handle_method(this.handle(), Self::tick));
1336 let done = controller.animate_with(app, simulation);
1337 done.when_complete(app, Listener::handle_method(this.handle(), Self::end));
1339 this
1340 }
1341
1342 pub fn done(self: Handle<Self>, app: &App) -> CompleterFuture<()> {
1348 app.get(self).completer.future()
1349 }
1350
1351 fn tick(self: Handle<Self>, app: &mut App) {
1352 let value = app.get(self).controller.value(app);
1353 if !self.apply_move_to(app, value) {
1354 self.delegate(app).go_idle(app);
1355 }
1356 }
1357
1358 pub fn apply_move_to(self: Handle<Self>, app: &mut App, value: f64) -> bool {
1366 self.delegate(app).set_pixels(app, value).abs() < PRECISION_ERROR_TOLERANCE
1367 }
1368
1369 fn end(self: Handle<Self>, app: &mut App) {
1370 if !self.is_disposed(app) {
1373 let velocity = self.velocity(app);
1374 self.delegate(app).go_ballistic(app, velocity);
1375 }
1376 }
1377}
1378
1379impl ScrollActivity for DrivenScrollActivity {
1380 crate::scroll_activity_accessors!();
1381
1382 fn dispatch_overscroll_notification(
1383 self: Handle<Self>,
1384 app: &mut App,
1385 metrics: Rc<dyn ScrollMetrics>,
1386 context: BuildContext,
1387 overscroll: f64,
1388 ) {
1389 let velocity = self.velocity(app);
1390 OverscrollNotification::new(metrics, context, overscroll)
1391 .velocity(velocity)
1392 .dispatch(app, Some(context));
1393 }
1394
1395 fn should_ignore_pointer(self: Handle<Self>, _app: &App) -> bool {
1396 true
1397 }
1398
1399 fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
1400 true
1401 }
1402
1403 fn velocity(self: Handle<Self>, app: &mut App) -> f64 {
1404 app.get(self).controller.velocity(app)
1405 }
1406
1407 fn dispose(self: Handle<Self>, app: &mut App) {
1408 let completer = app.get(self).completer.clone();
1409 completer.complete(app, ());
1410 app.get(self).controller.dispose(app);
1411 ScrollActivityBase::dispose(self, app);
1412 }
1413
1414 fn describe(self: Handle<Self>, app: &App) -> String {
1415 format!(
1416 "{}({:?})",
1417 describe_identity::<DrivenScrollActivity>(self.id()),
1418 app.get(self).controller.id()
1419 )
1420 }
1421}