1use std::any::Any;
11use std::fmt::{self, Debug};
12use std::rc::Rc;
13use std::time::Duration;
14
15use waft_animation::{
16 AnimationBehavior, AnimationController, AnimationLocalStatusListenersMixin, AnimationRef,
17 AnimationStatus, AnimationStatusListener, AnyAnimation, CurvedAnimation, Curves,
18};
19use waft_embedder::{
20 Canvas, Color, FillRule, Matrix4, Offset, Paint, PaintStyle, PathBuilder, PointerDeviceKind,
21 RRect, Radius, Rect, Size, Stroke, TargetPlatform, TextDirection, clamp_double,
22};
23use waft_foundation::{
24 App, ChangeNotifier, ChangeNotifierData, Handle, Listenable, Listener, Timer,
25};
26use waft_foundation::{OptionRetained, PRECISION_ERROR_TOLERANCE};
27use waft_gestures::DragDirection;
28use waft_gestures::{
29 BaseTapData, BaseTapGestureRecognizer, BaseTapLeaf, BaseTapLeafData, DeviceGestureSettings,
30 Drag, DragData, DragDownDetails, DragEndDetails, DragGestureRecognizer, DragLeaf, DragLeafData,
31 DragStartBehavior, DragStartDetails, DragUpdateDetails, GestureBinding, GestureDisposition,
32 GestureRecognizer, GestureRecognizerData, GestureTapDownCallback,
33 HorizontalDragGestureRecognizerBase, K_PRESS_TIMEOUT, K_PRIMARY_BUTTON, OneSequenceData,
34 OneSequenceLeafData, PointerCancelEvent, PointerDownEvent, PointerEvent, PointerHoverEvent,
35 PointerPanZoomStartEvent, PointerScrollEvent, PointerUpEvent, PrimaryPointerData,
36 PrimaryPointerGestureRecognizer, PrimaryPointerLeaf, PrimaryPointerLeafData, RecognizerLeaf,
37 RecognizerLeafData, TapDownDetails, UNSET_TOUCH_SLOP, Velocity, VelocityEstimate,
38 VerticalDragGestureRecognizerBase,
39};
40use waft_painting::{
41 Axis, AxisDirection, EdgeInsets, EdgeInsetsGeometry, OutlinedBorderRef,
42 axis_direction_is_reversed, axis_direction_to_axis, draw_rrect,
43};
44use waft_rendering::{AnyRenderBox, CustomPainter};
45
46use crate::framework::{
47 BuildContext, BuildOwner, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget,
48 WidgetRef, downcast_widget,
49};
50use crate::view::View;
51use crate::widgets::basic::{
52 CustomPaint, Listener as PointerListener, MouseRegion, RepaintBoundary,
53};
54use crate::widgets::gesture_detector::{
55 GestureRecognizerFactories, GestureRecognizerFactory, GestureRecognizerFactoryWithHandlers,
56 RawGestureDetector,
57};
58use crate::widgets::media_query::MediaQuery;
59use crate::widgets::notification_listener::NotificationListener;
60use crate::widgets::primary_scroll_controller::PrimaryScrollController;
61use crate::widgets::scroll_activity::ScrollHoldController;
62use crate::widgets::scroll_configuration::ScrollConfiguration;
63use crate::widgets::scroll_controller::ScrollControllerRef;
64use crate::widgets::scroll_metrics::ScrollMetrics;
65use crate::widgets::scroll_notification::{
66 OverscrollNotification, ScrollEndNotification, ScrollNotification, ScrollNotificationPredicate,
67 ScrollUpdateNotification, default_scroll_notification_predicate,
68};
69use crate::widgets::scroll_position::ScrollMetricsNotification;
70use crate::widgets::scrollable::Scrollable;
71use crate::widgets::scrollable_helpers::{ScrollAction, ScrollIncrementType, ScrollIntent};
72use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
73use waft_foundation::Ref;
74use waft_scheduler::{
75 FrameCallback, SchedulerBinding, Ticker, TickerCallback, TickerProviderObject,
76};
77
78const K_MIN_THUMB_EXTENT: f64 = 18.0;
79const K_MIN_INTERACTIVE_SIZE: f64 = 48.0;
80const K_SCROLLBAR_THICKNESS: f64 = 6.0;
81const K_SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(300);
82const K_SCROLLBAR_TIME_TO_FADE: Duration = Duration::from_millis(600);
83
84const K_DEFAULT_THUMB_COLOR: Color = Color::from_argb(0x66, 0xBC, 0xBC, 0xBC);
86const K_DEFAULT_TRACK_COLOR: Color = Color::from_argb(0x08, 0x00, 0x00, 0x00);
88const K_DEFAULT_TRACK_BORDER_COLOR: Color = Color::from_argb(0x1a, 0x00, 0x00, 0x00);
90const K_TRANSPARENT: Color = Color::from_argb(0, 0, 0, 0);
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
95pub enum ScrollbarOrientation {
96 Left,
98
99 Right,
101
102 Top,
104
105 Bottom,
107}
108
109impl ScrollbarOrientation {
110 fn is_vertical(self) -> bool {
111 matches!(
112 self,
113 ScrollbarOrientation::Left | ScrollbarOrientation::Right
114 )
115 }
116}
117
118pub struct ScrollbarPainter {
143 change_notifier: ChangeNotifierData,
144 color: Color,
145 track_color: Color,
146 track_border_color: Color,
147 track_radius: Option<Radius>,
148 text_direction: Option<TextDirection>,
149 thickness: f64,
150 fadeout_opacity_animation: AnimationRef<f64>,
151 main_axis_margin: f64,
152 cross_axis_margin: f64,
153 radius: Option<Radius>,
154 shape: Option<OutlinedBorderRef>,
155 padding: EdgeInsetsGeometry,
156 min_length: f64,
157 min_overscroll_length: f64,
158 scrollbar_orientation: Option<ScrollbarOrientation>,
159 ignore_pointer: bool,
160
161 track_rect: Option<Rect>,
163 resolved_padding: Option<EdgeInsets>,
164 thumb_rect: Option<Rect>,
165 thumb_offset: f64,
167 thumb_extent: f64,
169
170 last_metrics: Option<Rc<dyn ScrollMetrics>>,
172 last_axis_direction: Option<AxisDirection>,
173}
174
175impl ScrollbarPainter {
176 pub fn new(
180 app: &mut App,
181 color: Color,
182 fadeout_opacity_animation: AnimationRef<f64>,
183 ) -> Ref<ScrollbarPainter> {
184 let this = app.create(ScrollbarPainter {
185 change_notifier: ChangeNotifierData::new(),
186 color,
187 track_color: K_TRANSPARENT,
188 track_border_color: K_TRANSPARENT,
189 track_radius: None,
190 text_direction: None,
191 thickness: K_SCROLLBAR_THICKNESS,
192 fadeout_opacity_animation: fadeout_opacity_animation.clone(),
193 main_axis_margin: 0.0,
194 cross_axis_margin: 0.0,
195 radius: None,
196 shape: None,
197 padding: EdgeInsetsGeometry::ZERO,
198 min_length: K_MIN_THUMB_EXTENT,
199 min_overscroll_length: K_MIN_THUMB_EXTENT,
200 scrollbar_orientation: None,
201 ignore_pointer: false,
202 track_rect: None,
203 resolved_padding: Some(EdgeInsets::ZERO),
204 thumb_rect: None,
205 thumb_offset: 0.0,
206 thumb_extent: 0.0,
207 last_metrics: None,
208 last_axis_direction: None,
209 });
210 fadeout_opacity_animation.add_listener(
211 app,
212 Listener::handle_method(this.handle(), Handle::<ScrollbarPainter>::notify_listeners),
213 );
214 this
215 }
216
217 pub fn color(self: Handle<Self>, app: &App) -> Color {
219 app.get(self).color
220 }
221
222 pub fn set_color(self: Handle<Self>, app: &mut App, value: Color) {
224 if self.color(app) == value {
225 return;
226 }
227 app.get_mut(self).color = value;
228 self.notify_listeners(app);
229 }
230
231 pub fn track_color(self: Handle<Self>, app: &App) -> Color {
233 app.get(self).track_color
234 }
235
236 pub fn set_track_color(self: Handle<Self>, app: &mut App, value: Color) {
238 if self.track_color(app) == value {
239 return;
240 }
241 app.get_mut(self).track_color = value;
242 self.notify_listeners(app);
243 }
244
245 pub fn track_border_color(self: Handle<Self>, app: &App) -> Color {
247 app.get(self).track_border_color
248 }
249
250 pub fn set_track_border_color(self: Handle<Self>, app: &mut App, value: Color) {
252 if self.track_border_color(app) == value {
253 return;
254 }
255 app.get_mut(self).track_border_color = value;
256 self.notify_listeners(app);
257 }
258
259 pub fn track_radius(self: Handle<Self>, app: &App) -> Option<Radius> {
263 app.get(self).track_radius
264 }
265
266 pub fn set_track_radius(self: Handle<Self>, app: &mut App, value: Option<Radius>) {
268 if self.track_radius(app) == value {
269 return;
270 }
271 app.get_mut(self).track_radius = value;
272 self.notify_listeners(app);
273 }
274
275 pub fn text_direction(self: Handle<Self>, app: &App) -> Option<TextDirection> {
279 app.get(self).text_direction
280 }
281
282 pub fn set_text_direction(self: Handle<Self>, app: &mut App, value: Option<TextDirection>) {
284 debug_assert!(value.is_some());
285 if self.text_direction(app) == value {
286 return;
287 }
288 let painter = app.get_mut(self);
289 painter.text_direction = value;
290 painter.resolved_padding = Some(painter.padding.resolve(value));
291 self.notify_listeners(app);
292 }
293
294 pub fn thickness(self: Handle<Self>, app: &App) -> f64 {
296 app.get(self).thickness
297 }
298
299 pub fn set_thickness(self: Handle<Self>, app: &mut App, value: f64) {
301 if self.thickness(app) == value {
302 return;
303 }
304 app.get_mut(self).thickness = value;
305 self.notify_listeners(app);
306 }
307
308 pub fn fadeout_opacity_animation(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
312 app.get(self).fadeout_opacity_animation.handle()
313 }
314
315 pub fn main_axis_margin(self: Handle<Self>, app: &App) -> f64 {
320 app.get(self).main_axis_margin
321 }
322
323 pub fn set_main_axis_margin(self: Handle<Self>, app: &mut App, value: f64) {
325 if self.main_axis_margin(app) == value {
326 return;
327 }
328 app.get_mut(self).main_axis_margin = value;
329 self.notify_listeners(app);
330 }
331
332 pub fn cross_axis_margin(self: Handle<Self>, app: &App) -> f64 {
337 app.get(self).cross_axis_margin
338 }
339
340 pub fn set_cross_axis_margin(self: Handle<Self>, app: &mut App, value: f64) {
342 if self.cross_axis_margin(app) == value {
343 return;
344 }
345 app.get_mut(self).cross_axis_margin = value;
346 self.notify_listeners(app);
347 }
348
349 pub fn radius(self: Handle<Self>, app: &App) -> Option<Radius> {
353 app.get(self).radius
354 }
355
356 pub fn set_radius(self: Handle<Self>, app: &mut App, value: Option<Radius>) {
358 debug_assert!(app.get(self).shape.is_none() || value.is_none());
359 if self.radius(app) == value {
360 return;
361 }
362 app.get_mut(self).radius = value;
363 self.notify_listeners(app);
364 }
365
366 pub fn shape(self: Handle<Self>, app: &App) -> Option<OutlinedBorderRef> {
375 app.get(self).shape.clone()
376 }
377
378 pub fn set_shape(self: Handle<Self>, app: &mut App, value: Option<OutlinedBorderRef>) {
380 debug_assert!(app.get(self).radius.is_none() || value.is_none());
381 if app.get(self).shape == value {
382 return;
383 }
384 app.get_mut(self).shape = value;
385 self.notify_listeners(app);
386 }
387
388 pub fn padding(self: Handle<Self>, app: &App) -> EdgeInsetsGeometry {
394 app.get(self).padding
395 }
396
397 pub fn set_padding(self: Handle<Self>, app: &mut App, value: EdgeInsetsGeometry) {
399 if self.padding(app) == value {
400 return;
401 }
402 let painter = app.get_mut(self);
403 painter.padding = value;
404 let text_direction = painter.text_direction;
405 painter.resolved_padding = Some(painter.padding.resolve(text_direction));
406 self.notify_listeners(app);
407 }
408
409 pub fn min_length(self: Handle<Self>, app: &App) -> f64 {
416 app.get(self).min_length
417 }
418
419 pub fn set_min_length(self: Handle<Self>, app: &mut App, value: f64) {
421 if self.min_length(app) == value {
422 return;
423 }
424 app.get_mut(self).min_length = value;
425 self.notify_listeners(app);
426 }
427
428 pub fn min_overscroll_length(self: Handle<Self>, app: &App) -> f64 {
434 app.get(self).min_overscroll_length
435 }
436
437 pub fn set_min_overscroll_length(self: Handle<Self>, app: &mut App, value: f64) {
439 if self.min_overscroll_length(app) == value {
440 return;
441 }
442 app.get_mut(self).min_overscroll_length = value;
443 self.notify_listeners(app);
444 }
445
446 pub fn scrollbar_orientation(self: Handle<Self>, app: &App) -> Option<ScrollbarOrientation> {
456 app.get(self).scrollbar_orientation
457 }
458
459 pub fn set_scrollbar_orientation(
461 self: Handle<Self>,
462 app: &mut App,
463 value: Option<ScrollbarOrientation>,
464 ) {
465 if self.scrollbar_orientation(app) == value {
466 return;
467 }
468 app.get_mut(self).scrollbar_orientation = value;
469 self.notify_listeners(app);
470 }
471
472 pub fn ignore_pointer(self: Handle<Self>, app: &App) -> bool {
474 app.get(self).ignore_pointer
475 }
476
477 pub fn set_ignore_pointer(self: Handle<Self>, app: &mut App, value: bool) {
479 if self.ignore_pointer(app) == value {
480 return;
481 }
482 app.get_mut(self).ignore_pointer = value;
483 self.notify_listeners(app);
484 }
485
486 fn track_extent(self: Handle<Self>, app: &App) -> f64 {
490 self.metrics(app).viewport_dimension() - self.total_track_main_axis_offsets(app)
491 }
492
493 fn traversable_track_extent(self: Handle<Self>, app: &App) -> f64 {
495 self.track_extent(app) - (2.0 * self.main_axis_margin(app))
496 }
497
498 fn total_track_main_axis_offsets(self: Handle<Self>, app: &App) -> f64 {
500 let padding = self.resolved_padding(app);
501 if self.is_vertical(app) {
502 padding.vertical()
503 } else {
504 padding.horizontal()
505 }
506 }
507
508 fn leading_track_main_axis_offset(self: Handle<Self>, app: &App) -> f64 {
509 let padding = self.resolved_padding(app);
510 match self.resolved_orientation(app) {
511 ScrollbarOrientation::Left | ScrollbarOrientation::Right => padding.top,
512 ScrollbarOrientation::Top | ScrollbarOrientation::Bottom => padding.left,
513 }
514 }
515
516 fn leading_thumb_main_axis_offset(self: Handle<Self>, app: &App) -> f64 {
518 self.leading_track_main_axis_offset(app) + self.main_axis_margin(app)
519 }
520
521 fn resolved_padding(self: Handle<Self>, app: &App) -> EdgeInsets {
522 app.get(self)
523 .resolved_padding
524 .expect("the padding resolves when it or the text direction is set")
525 }
526
527 fn metrics(self: Handle<Self>, app: &App) -> Rc<dyn ScrollMetrics> {
528 app.get(self)
529 .last_metrics
530 .clone()
531 .expect("update() supplies the metrics before the painter reads them")
532 }
533
534 fn set_thumb_extent(self: Handle<Self>, app: &mut App) {
535 let metrics = self.metrics(app);
538 let total_track_main_axis_offsets = self.total_track_main_axis_offsets(app);
539 let fraction_visible = clamp_double(
540 (metrics.extent_inside() - total_track_main_axis_offsets)
541 / (self.total_content_extent(app) - total_track_main_axis_offsets),
542 0.0,
543 1.0,
544 );
545
546 let traversable_track_extent = self.traversable_track_extent(app);
547 let thumb_extent = traversable_track_extent
548 .min(self.min_overscroll_length(app))
549 .max(traversable_track_extent * fraction_visible);
550
551 let fraction_overscrolled = 1.0 - metrics.extent_inside() / metrics.viewport_dimension();
552 let safe_min_length = self.min_length(app).min(traversable_track_extent);
553 let new_min_length = if self.before_extent(app) > 0.0 && self.after_extent(app) > 0.0 {
554 safe_min_length
556 } else {
557 safe_min_length * (1.0 - clamp_double(fraction_overscrolled, 0.0, 0.2) / 0.2)
563 };
564
565 app.get_mut(self).thumb_extent =
568 clamp_double(thumb_extent, new_min_length, traversable_track_extent);
569 }
570
571 fn last_metrics_are_scrollable(self: Handle<Self>, app: &App) -> bool {
574 let metrics = self.metrics(app);
575 metrics.min_scroll_extent() != metrics.max_scroll_extent()
576 }
577
578 fn is_vertical(self: Handle<Self>, app: &App) -> bool {
579 matches!(
580 app.get(self).last_axis_direction,
581 Some(AxisDirection::Down) | Some(AxisDirection::Up)
582 )
583 }
584
585 fn is_reversed(self: Handle<Self>, app: &App) -> bool {
586 matches!(
587 app.get(self).last_axis_direction,
588 Some(AxisDirection::Up) | Some(AxisDirection::Left)
589 )
590 }
591
592 fn before_extent(self: Handle<Self>, app: &App) -> f64 {
594 let metrics = self.metrics(app);
595 if self.is_reversed(app) {
596 metrics.extent_after()
597 } else {
598 metrics.extent_before()
599 }
600 }
601
602 fn after_extent(self: Handle<Self>, app: &App) -> f64 {
604 let metrics = self.metrics(app);
605 if self.is_reversed(app) {
606 metrics.extent_before()
607 } else {
608 metrics.extent_after()
609 }
610 }
611
612 fn total_content_extent(self: Handle<Self>, app: &App) -> f64 {
614 let metrics = self.metrics(app);
615 metrics.max_scroll_extent() - metrics.min_scroll_extent() + metrics.viewport_dimension()
616 }
617
618 fn resolved_orientation(self: Handle<Self>, app: &App) -> ScrollbarOrientation {
619 match self.scrollbar_orientation(app) {
620 Some(orientation) => orientation,
621 None => {
622 if self.is_vertical(app) {
623 if self.text_direction(app) == Some(TextDirection::Ltr) {
624 ScrollbarOrientation::Right
625 } else {
626 ScrollbarOrientation::Left
627 }
628 } else {
629 ScrollbarOrientation::Bottom
630 }
631 }
632 }
633 }
634
635 fn debug_assert_is_valid_orientation(
636 self: Handle<Self>,
637 app: &App,
638 orientation: ScrollbarOrientation,
639 ) {
640 debug_assert!(
641 self.is_vertical(app) == orientation.is_vertical(),
642 "The given ScrollbarOrientation: {orientation:?} is incompatible with the current \
643 AxisDirection: {:?}.",
644 app.get(self).last_axis_direction
645 );
646 }
647
648 pub fn update(
655 self: Handle<Self>,
656 app: &mut App,
657 metrics: Rc<dyn ScrollMetrics>,
658 axis_direction: AxisDirection,
659 ) {
660 if let Some(last) = app.get(self).last_metrics.clone()
661 && last.extent_before() == metrics.extent_before()
662 && last.extent_inside() == metrics.extent_inside()
663 && last.extent_after() == metrics.extent_after()
664 && app.get(self).last_axis_direction == Some(axis_direction)
665 {
666 return;
667 }
668
669 let old_metrics = app.get(self).last_metrics.clone();
670 let painter = app.get_mut(self);
671 painter.last_metrics = Some(metrics.clone());
672 painter.last_axis_direction = Some(axis_direction);
673
674 if !need_paint(old_metrics.as_deref()) && !need_paint(Some(&*metrics)) {
675 return;
676 }
677 self.notify_listeners(app);
678 }
679
680 pub fn update_thickness(
682 self: Handle<Self>,
683 app: &mut App,
684 next_thickness: f64,
685 next_radius: Radius,
686 ) {
687 self.set_thickness(app, next_thickness);
688 self.set_radius(app, Some(next_radius));
689 }
690
691 fn paint_thumb(self: Handle<Self>, app: &App) -> Paint {
694 let color = self.color(app);
695 let opacity = self.fadeout_opacity_animation(app).value(app);
696 Paint {
697 color: color
698 .with_values(Some(color.a * opacity), None, None, None, None)
699 .into(),
700 ..Paint::default()
701 }
702 }
703
704 fn paint_track(self: Handle<Self>, app: &App, is_border: bool) -> Paint {
705 let opacity = self.fadeout_opacity_animation(app).value(app);
706 if is_border {
707 let color = self.track_border_color(app);
708 return Paint {
709 color: color
710 .with_values(Some(color.a * opacity), None, None, None, None)
711 .into(),
712 style: PaintStyle::Stroke(Stroke::new(1.0)),
713 ..Paint::default()
714 };
715 }
716 let color = self.track_color(app);
717 Paint {
718 color: color
719 .with_values(Some(color.a * opacity), None, None, None, None)
720 .into(),
721 ..Paint::default()
722 }
723 }
724
725 fn paint_scrollbar(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, size: Size) {
726 debug_assert!(
727 self.text_direction(app).is_some(),
728 "A TextDirection must be provided before a Scrollbar can be painted."
729 );
730 let orientation = self.resolved_orientation(app);
731 self.debug_assert_is_valid_orientation(app, orientation);
732
733 let thickness = self.thickness(app);
734 let cross_axis_margin = self.cross_axis_margin(app);
735 let padding = self.resolved_padding(app);
736 let track_extent = self.track_extent(app);
737 let thumb_extent = app.get(self).thumb_extent;
738 let thumb_offset = app.get(self).thumb_offset;
739 let leading_track_main_axis_offset = self.leading_track_main_axis_offset(app);
740
741 let (x, y, thumb_size, track_size, track_offset, border_start, border_end) =
742 match orientation {
743 ScrollbarOrientation::Left => {
744 let thumb_size = Size::new(thickness, thumb_extent);
745 let track_size = Size::new(thickness + 2.0 * cross_axis_margin, track_extent);
746 let x = cross_axis_margin + padding.left;
747 let y = thumb_offset;
748 let track_offset =
749 Offset::new(x - cross_axis_margin, leading_track_main_axis_offset);
750 let border_start = track_offset + Offset::new(track_size.width(), 0.0);
751 let border_end = Offset::new(
752 track_offset.dx() + track_size.width(),
753 track_offset.dy() + track_extent,
754 );
755 (
756 x,
757 y,
758 thumb_size,
759 track_size,
760 track_offset,
761 border_start,
762 border_end,
763 )
764 }
765 ScrollbarOrientation::Right => {
766 let thumb_size = Size::new(thickness, thumb_extent);
767 let track_size = Size::new(thickness + 2.0 * cross_axis_margin, track_extent);
768 let x = size.width() - thickness - cross_axis_margin - padding.right;
769 let y = thumb_offset;
770 let track_offset =
771 Offset::new(x - cross_axis_margin, leading_track_main_axis_offset);
772 let border_start = track_offset;
773 let border_end =
774 Offset::new(track_offset.dx(), track_offset.dy() + track_extent);
775 (
776 x,
777 y,
778 thumb_size,
779 track_size,
780 track_offset,
781 border_start,
782 border_end,
783 )
784 }
785 ScrollbarOrientation::Top => {
786 let thumb_size = Size::new(thumb_extent, thickness);
787 let track_size = Size::new(track_extent, thickness + 2.0 * cross_axis_margin);
788 let x = thumb_offset;
789 let y = cross_axis_margin + padding.top;
790 let track_offset =
791 Offset::new(leading_track_main_axis_offset, y - cross_axis_margin);
792 let border_start = track_offset + Offset::new(0.0, track_size.height());
793 let border_end = Offset::new(
794 track_offset.dx() + track_extent,
795 track_offset.dy() + track_size.height(),
796 );
797 (
798 x,
799 y,
800 thumb_size,
801 track_size,
802 track_offset,
803 border_start,
804 border_end,
805 )
806 }
807 ScrollbarOrientation::Bottom => {
808 let thumb_size = Size::new(thumb_extent, thickness);
809 let track_size = Size::new(track_extent, thickness + 2.0 * cross_axis_margin);
810 let x = thumb_offset;
811 let y = size.height() - thickness - cross_axis_margin - padding.bottom;
812 let track_offset =
813 Offset::new(leading_track_main_axis_offset, y - cross_axis_margin);
814 let border_start = track_offset;
815 let border_end =
816 Offset::new(track_offset.dx() + track_extent, track_offset.dy());
817 (
818 x,
819 y,
820 thumb_size,
821 track_size,
822 track_offset,
823 border_start,
824 border_end,
825 )
826 }
827 };
828
829 let track_rect = track_offset & track_size;
832 let thumb_rect = Offset::new(x, y) & thumb_size;
833 let painter = app.get_mut(self);
834 painter.track_rect = Some(track_rect);
835 painter.thumb_rect = Some(thumb_rect);
836
837 if self.fadeout_opacity_animation(app).value(app) == 0.0 {
839 return;
840 }
841 match self.track_radius(app) {
843 None => canvas.draw_rect(track_rect, &self.paint_track(app, false)),
844 Some(track_radius) => draw_rrect(
845 canvas,
846 RRect::from_rect_and_radius(track_rect, track_radius),
847 &self.paint_track(app, false),
848 ),
849 }
850 let mut border = PathBuilder::new();
852 border.move_to(border_start);
853 border.line_to(border_end);
854 canvas.draw_path(
855 &border.build(),
856 FillRule::NonZero,
857 &self.paint_track(app, true),
858 );
859
860 if let Some(radius) = self.radius(app) {
861 draw_rrect(
863 canvas,
864 RRect::from_rect_and_radius(thumb_rect, radius),
865 &self.paint_thumb(app),
866 );
867 return;
868 }
869 let Some(shape) = self.shape(app) else {
870 canvas.draw_rect(thumb_rect, &self.paint_thumb(app));
872 return;
873 };
874 let text_direction = self.text_direction(app);
876 if shape.prefer_paint_interior() {
877 shape.paint_interior(canvas, thumb_rect, &self.paint_thumb(app), text_direction);
878 } else {
879 let outer_path = shape.get_outer_path(thumb_rect, text_direction);
880 canvas.draw_path(
881 outer_path.as_valo(),
882 outer_path.fill_type,
883 &self.paint_thumb(app),
884 );
885 }
886 shape.paint(canvas, thumb_rect, text_direction);
887 }
888
889 pub fn paint(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, size: Size) {
891 if app.get(self).last_axis_direction.is_none()
892 || !need_paint(app.get(self).last_metrics.as_deref())
893 {
894 return;
895 }
896
897 if self.traversable_track_extent(app) <= 0.0 {
899 return;
900 }
901 if self.metrics(app).max_scroll_extent().is_infinite() {
903 return;
904 }
905
906 self.set_thumb_extent(app);
907 let thumb_extent = app.get(self).thumb_extent;
908 let metrics = self.metrics(app);
909 let thumb_position_offset = self.get_scroll_to_track(app, &*metrics, thumb_extent);
910 app.get_mut(self).thumb_offset =
911 thumb_position_offset + self.leading_thumb_main_axis_offset(app);
912
913 self.paint_scrollbar(app, canvas, size);
914 }
915
916 pub fn get_track_to_scroll(self: Handle<Self>, app: &App, thumb_offset_local: f64) -> f64 {
923 let metrics = self.metrics(app);
924 let scrollable_extent = metrics.max_scroll_extent() - metrics.min_scroll_extent();
925 let thumb_movable_extent = self.traversable_track_extent(app) - app.get(self).thumb_extent;
926
927 scrollable_extent * thumb_offset_local / thumb_movable_extent
928 }
929
930 pub fn get_thumb_scroll_offset(self: Handle<Self>, app: &App) -> f64 {
932 let metrics = self.metrics(app);
933 debug_assert!(
934 metrics.max_scroll_extent().is_finite() && metrics.min_scroll_extent().is_finite()
935 );
936 let scrollable_extent = metrics.max_scroll_extent() - metrics.min_scroll_extent();
937 let max_fraction = metrics.max_scroll_extent() / scrollable_extent;
938 let min_fraction = metrics.min_scroll_extent() / scrollable_extent;
939
940 let fraction_past = if scrollable_extent > 0.0 {
941 clamp_double(
942 metrics.pixels() / scrollable_extent,
943 min_fraction,
944 max_fraction,
945 )
946 } else {
947 0.0
948 };
949
950 fraction_past * (self.traversable_track_extent(app) - app.get(self).thumb_extent)
951 }
952
953 fn get_scroll_to_track(
956 self: Handle<Self>,
957 app: &App,
958 metrics: &dyn ScrollMetrics,
959 thumb_extent: f64,
960 ) -> f64 {
961 let scrollable_extent = metrics.max_scroll_extent() - metrics.min_scroll_extent();
962
963 let fraction_past = if scrollable_extent > 0.0 {
964 clamp_double(
965 (metrics.pixels() - metrics.min_scroll_extent()) / scrollable_extent,
966 0.0,
967 1.0,
968 )
969 } else {
970 0.0
971 };
972
973 let fraction_past = if self.is_reversed(app) {
974 1.0 - fraction_past
975 } else {
976 fraction_past
977 };
978 fraction_past * (self.traversable_track_extent(app) - thumb_extent)
979 }
980
981 pub fn should_repaint(self: Handle<Self>, app: &App, old_delegate: Handle<Self>) -> bool {
984 let (new, old) = (app.get(self), app.get(old_delegate));
985 let same_shape = new.shape == old.shape;
986 new.color != old.color
987 || new.track_color != old.track_color
988 || new.track_border_color != old.track_border_color
989 || new.text_direction != old.text_direction
990 || new.thickness != old.thickness
991 || new.fadeout_opacity_animation != old.fadeout_opacity_animation
992 || new.main_axis_margin != old.main_axis_margin
993 || new.cross_axis_margin != old.cross_axis_margin
994 || new.radius != old.radius
995 || new.track_radius != old.track_radius
996 || !same_shape
997 || new.padding != old.padding
998 || new.min_length != old.min_length
999 || new.min_overscroll_length != old.min_overscroll_length
1000 || new.scrollbar_orientation != old.scrollbar_orientation
1001 || new.ignore_pointer != old.ignore_pointer
1002 }
1003
1004 pub fn hit_test(self: Handle<Self>, app: &App, position: Option<Offset>) -> Option<bool> {
1009 app.get(self).thumb_rect?;
1011 let track_rect = app.get(self).track_rect.expect("a thumb implies a track");
1012
1013 if self.ignore_pointer(app)
1016 || self.fadeout_opacity_animation(app).value(app) == 0.0
1017 || !self.last_metrics_are_scrollable(app)
1018 {
1019 return Some(false);
1020 }
1021
1022 Some(track_rect.contains(position.expect("a hit test has a position")))
1023 }
1024
1025 pub fn hit_test_interactive(
1033 self: Handle<Self>,
1034 app: &App,
1035 position: Offset,
1036 kind: PointerDeviceKind,
1037 for_hover: bool,
1038 ) -> bool {
1039 let Some(interactive_rect) = app.get(self).track_rect else {
1041 return false;
1042 };
1043 if self.ignore_pointer(app) {
1044 return false;
1045 }
1046 if !self.last_metrics_are_scrollable(app) {
1047 return false;
1048 }
1049
1050 let thumb_rect = app.get(self).thumb_rect.expect("a track implies a thumb");
1051 let padded_rect = interactive_rect.expand_to_include(Rect::from_circle(
1052 thumb_rect.center(),
1053 K_MIN_INTERACTIVE_SIZE / 2.0,
1054 ));
1055
1056 if self.fadeout_opacity_animation(app).value(app) == 0.0 {
1059 if for_hover && kind == PointerDeviceKind::Mouse {
1060 return padded_rect.contains(position);
1061 }
1062 return false;
1063 }
1064
1065 match kind {
1066 PointerDeviceKind::Touch | PointerDeviceKind::Trackpad => {
1067 padded_rect.contains(position)
1068 }
1069 PointerDeviceKind::Mouse
1070 | PointerDeviceKind::Stylus
1071 | PointerDeviceKind::InvertedStylus
1072 | PointerDeviceKind::Unknown => interactive_rect.contains(position),
1073 }
1074 }
1075
1076 pub fn hit_test_only_thumb_interactive(
1079 self: Handle<Self>,
1080 app: &App,
1081 position: Offset,
1082 kind: PointerDeviceKind,
1083 ) -> bool {
1084 let Some(thumb_rect) = app.get(self).thumb_rect else {
1085 return false;
1086 };
1087 if self.ignore_pointer(app) {
1088 return false;
1089 }
1090 if self.fadeout_opacity_animation(app).value(app) == 0.0 {
1092 return false;
1093 }
1094 if !self.last_metrics_are_scrollable(app) {
1095 return false;
1096 }
1097
1098 match kind {
1099 PointerDeviceKind::Touch | PointerDeviceKind::Trackpad => {
1100 let touch_thumb_rect = thumb_rect.expand_to_include(Rect::from_circle(
1101 thumb_rect.center(),
1102 K_MIN_INTERACTIVE_SIZE / 2.0,
1103 ));
1104 touch_thumb_rect.contains(position)
1105 }
1106 PointerDeviceKind::Mouse
1107 | PointerDeviceKind::Stylus
1108 | PointerDeviceKind::InvertedStylus
1109 | PointerDeviceKind::Unknown => thumb_rect.contains(position),
1110 }
1111 }
1112
1113 pub fn dispose(self: Handle<Self>, app: &mut App) {
1115 let animation = self.fadeout_opacity_animation(app);
1116 animation.remove_listener(
1117 app,
1118 &Listener::handle_method(self, Handle::<ScrollbarPainter>::notify_listeners),
1119 );
1120 ChangeNotifierData::dispose(app, self);
1121 }
1122}
1123
1124impl ChangeNotifier for ScrollbarPainter {
1125 fn change_notifier_data(&self) -> &ChangeNotifierData {
1126 &self.change_notifier
1127 }
1128
1129 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1130 &mut self.change_notifier
1131 }
1132}
1133
1134impl Debug for ScrollbarPainter {
1135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1136 f.write_str("ScrollbarPainter")
1137 }
1138}
1139
1140fn need_paint(metrics: Option<&dyn ScrollMetrics>) -> bool {
1141 metrics.is_some_and(|metrics| {
1142 metrics.max_scroll_extent() - metrics.min_scroll_extent() > PRECISION_ERROR_TOLERANCE
1143 })
1144}
1145
1146#[derive(Clone)]
1150pub struct ScrollbarPainterRef {
1151 painter: Ref<ScrollbarPainter>,
1152 repaint: Rc<dyn Listenable>,
1153}
1154
1155impl ScrollbarPainterRef {
1156 pub fn new(painter: Ref<ScrollbarPainter>) -> ScrollbarPainterRef {
1158 ScrollbarPainterRef {
1159 repaint: Rc::new(painter.clone()),
1160 painter,
1161 }
1162 }
1163
1164 pub fn painter(&self) -> Handle<ScrollbarPainter> {
1166 self.painter.handle()
1167 }
1168}
1169
1170impl CustomPainter for ScrollbarPainterRef {
1171 fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
1172 Some(&self.repaint)
1173 }
1174
1175 fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
1176 self.painter.paint(app, canvas, size);
1177 }
1178
1179 fn should_repaint(&self, app: &App, old_delegate: &dyn CustomPainter) -> bool {
1180 let old_delegate = old_delegate
1181 .as_any()
1182 .downcast_ref::<ScrollbarPainterRef>()
1183 .expect("Dart's covariant parameter");
1184 self.painter.should_repaint(app, old_delegate.painter())
1185 }
1186
1187 fn hit_test(&self, app: &App, position: Offset) -> Option<bool> {
1188 self.painter.hit_test(app, Some(position))
1189 }
1190
1191 fn as_any(&self) -> &dyn Any {
1192 self
1193 }
1194}
1195
1196impl Debug for ScrollbarPainterRef {
1197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1198 f.write_str("ScrollbarPainter")
1199 }
1200}
1201
1202pub struct RawScrollbarData {
1204 pub key: Option<KeyRef>,
1205
1206 pub child: WidgetRef,
1211
1212 pub controller: Option<ScrollControllerRef>,
1218
1219 pub thumb_visibility: Option<bool>,
1229
1230 pub shape: Option<OutlinedBorderRef>,
1234
1235 pub radius: Option<Radius>,
1240
1241 pub thickness: Option<f64>,
1245
1246 pub thumb_color: Option<Color>,
1250
1251 pub min_thumb_length: f64,
1257
1258 pub min_overscroll_length: Option<f64>,
1264
1265 pub track_visibility: Option<bool>,
1273
1274 pub track_radius: Option<Radius>,
1276
1277 pub track_color: Option<Color>,
1281
1282 pub track_border_color: Option<Color>,
1286
1287 pub fade_duration: Duration,
1291
1292 pub time_to_fade: Duration,
1296
1297 pub press_duration: Duration,
1302
1303 pub notification_predicate: ScrollNotificationPredicate,
1310
1311 pub interactive: Option<bool>,
1319
1320 pub scrollbar_orientation: Option<ScrollbarOrientation>,
1322
1323 pub main_axis_margin: f64,
1328
1329 pub cross_axis_margin: f64,
1334
1335 pub padding: Option<EdgeInsetsGeometry>,
1339}
1340
1341impl RawScrollbarData {
1342 pub fn new(child: WidgetRef) -> RawScrollbarData {
1344 RawScrollbarData {
1345 key: None,
1346 child,
1347 controller: None,
1348 thumb_visibility: None,
1349 shape: None,
1350 radius: None,
1351 thickness: None,
1352 thumb_color: None,
1353 min_thumb_length: K_MIN_THUMB_EXTENT,
1354 min_overscroll_length: None,
1355 track_visibility: None,
1356 track_radius: None,
1357 track_color: None,
1358 track_border_color: None,
1359 fade_duration: K_SCROLLBAR_FADE_DURATION,
1360 time_to_fade: K_SCROLLBAR_TIME_TO_FADE,
1361 press_duration: Duration::ZERO,
1362 notification_predicate: Rc::new(default_scroll_notification_predicate),
1363 interactive: None,
1364 scrollbar_orientation: None,
1365 main_axis_margin: 0.0,
1366 cross_axis_margin: 0.0,
1367 padding: None,
1368 }
1369 }
1370}
1371
1372impl Debug for RawScrollbarData {
1373 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1374 f.debug_struct("RawScrollbar")
1375 .field("child", &self.child)
1376 .finish_non_exhaustive()
1377 }
1378}
1379
1380#[macro_export]
1383macro_rules! raw_scrollbar_accessors {
1384 () => {
1385 fn raw_scrollbar_data(&self) -> &$crate::RawScrollbarData {
1386 &self.raw_scrollbar
1387 }
1388
1389 fn raw_scrollbar_data_mut(&mut self) -> &mut $crate::RawScrollbarData {
1390 &mut self.raw_scrollbar
1391 }
1392 };
1393}
1394
1395#[macro_export]
1397macro_rules! raw_scrollbar_setters {
1398 ($name:ident) => {
1399 pub fn key(mut self, key: $crate::KeyRef) -> $name {
1401 self.raw_scrollbar.key = Some(key);
1402 self
1403 }
1404
1405 pub fn controller(mut self, controller: $crate::ScrollControllerRef) -> $name {
1407 self.raw_scrollbar.controller = Some(controller);
1408 self
1409 }
1410
1411 pub fn thumb_visibility(mut self, thumb_visibility: bool) -> $name {
1413 debug_assert!(
1414 thumb_visibility || !self.raw_scrollbar.track_visibility.unwrap_or(false),
1415 "A scrollbar track cannot be drawn without a scrollbar thumb."
1416 );
1417 self.raw_scrollbar.thumb_visibility = Some(thumb_visibility);
1418 self
1419 }
1420
1421 pub fn track_visibility(mut self, track_visibility: bool) -> $name {
1423 debug_assert!(
1424 !(self.raw_scrollbar.thumb_visibility == Some(false) && track_visibility),
1425 "A scrollbar track cannot be drawn without a scrollbar thumb."
1426 );
1427 self.raw_scrollbar.track_visibility = Some(track_visibility);
1428 self
1429 }
1430
1431 pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> $name {
1433 debug_assert!(self.raw_scrollbar.radius.is_none());
1434 self.raw_scrollbar.shape = Some(shape.into());
1435 self
1436 }
1437
1438 pub fn radius(mut self, radius: waft_embedder::Radius) -> $name {
1440 debug_assert!(self.raw_scrollbar.shape.is_none());
1441 self.raw_scrollbar.radius = Some(radius);
1442 self
1443 }
1444
1445 pub fn thickness(mut self, thickness: f64) -> $name {
1447 self.raw_scrollbar.thickness = Some(thickness);
1448 self
1449 }
1450
1451 pub fn thumb_color(mut self, thumb_color: waft_embedder::Color) -> $name {
1453 self.raw_scrollbar.thumb_color = Some(thumb_color);
1454 self
1455 }
1456
1457 pub fn min_thumb_length(mut self, min_thumb_length: f64) -> $name {
1459 debug_assert!(min_thumb_length >= 0.0);
1460 debug_assert!(
1461 self.raw_scrollbar
1462 .min_overscroll_length
1463 .is_none_or(|length| length <= min_thumb_length)
1464 );
1465 self.raw_scrollbar.min_thumb_length = min_thumb_length;
1466 self
1467 }
1468
1469 pub fn min_overscroll_length(mut self, min_overscroll_length: f64) -> $name {
1471 debug_assert!(min_overscroll_length >= 0.0);
1472 debug_assert!(min_overscroll_length <= self.raw_scrollbar.min_thumb_length);
1473 self.raw_scrollbar.min_overscroll_length = Some(min_overscroll_length);
1474 self
1475 }
1476
1477 pub fn track_radius(mut self, track_radius: waft_embedder::Radius) -> $name {
1479 self.raw_scrollbar.track_radius = Some(track_radius);
1480 self
1481 }
1482
1483 pub fn track_color(mut self, track_color: waft_embedder::Color) -> $name {
1485 self.raw_scrollbar.track_color = Some(track_color);
1486 self
1487 }
1488
1489 pub fn track_border_color(mut self, track_border_color: waft_embedder::Color) -> $name {
1491 self.raw_scrollbar.track_border_color = Some(track_border_color);
1492 self
1493 }
1494
1495 pub fn fade_duration(mut self, fade_duration: std::time::Duration) -> $name {
1497 self.raw_scrollbar.fade_duration = fade_duration;
1498 self
1499 }
1500
1501 pub fn time_to_fade(mut self, time_to_fade: std::time::Duration) -> $name {
1503 self.raw_scrollbar.time_to_fade = time_to_fade;
1504 self
1505 }
1506
1507 pub fn press_duration(mut self, press_duration: std::time::Duration) -> $name {
1509 self.raw_scrollbar.press_duration = press_duration;
1510 self
1511 }
1512
1513 pub fn notification_predicate(
1515 mut self,
1516 notification_predicate: $crate::ScrollNotificationPredicate,
1517 ) -> $name {
1518 self.raw_scrollbar.notification_predicate = notification_predicate;
1519 self
1520 }
1521
1522 pub fn interactive(mut self, interactive: bool) -> $name {
1524 self.raw_scrollbar.interactive = Some(interactive);
1525 self
1526 }
1527
1528 pub fn scrollbar_orientation(
1530 mut self,
1531 scrollbar_orientation: $crate::ScrollbarOrientation,
1532 ) -> $name {
1533 self.raw_scrollbar.scrollbar_orientation = Some(scrollbar_orientation);
1534 self
1535 }
1536
1537 pub fn main_axis_margin(mut self, main_axis_margin: f64) -> $name {
1539 self.raw_scrollbar.main_axis_margin = main_axis_margin;
1540 self
1541 }
1542
1543 pub fn cross_axis_margin(mut self, cross_axis_margin: f64) -> $name {
1545 self.raw_scrollbar.cross_axis_margin = cross_axis_margin;
1546 self
1547 }
1548
1549 pub fn padding(mut self, padding: impl Into<waft_painting::EdgeInsetsGeometry>) -> $name {
1551 self.raw_scrollbar.padding = Some(padding.into());
1552 self
1553 }
1554 };
1555}
1556
1557pub trait RawScrollbarLeaf: StatefulWidget {
1560 fn raw_scrollbar_data(&self) -> &RawScrollbarData;
1563
1564 fn raw_scrollbar_data_mut(&mut self) -> &mut RawScrollbarData;
1566}
1567
1568pub struct RawScrollbar {
1607 raw_scrollbar: RawScrollbarData,
1608}
1609
1610impl RawScrollbar {
1611 #[cfg_attr(debug_assertions, track_caller)]
1616 pub fn new<K>(child: impl IntoWidget<K>) -> RawScrollbar {
1617 RawScrollbar {
1618 raw_scrollbar: RawScrollbarData::new(child.into_widget()),
1619 }
1620 }
1621
1622 crate::raw_scrollbar_setters!(RawScrollbar);
1623}
1624
1625impl RawScrollbarLeaf for RawScrollbar {
1626 crate::raw_scrollbar_accessors!();
1627}
1628
1629impl Debug for RawScrollbar {
1630 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1631 Debug::fmt(&self.raw_scrollbar, f)
1632 }
1633}
1634
1635impl StatefulWidget for RawScrollbar {
1636 type State = RawScrollbarState;
1637
1638 fn key(&self) -> Option<&KeyRef> {
1639 self.raw_scrollbar.key.as_ref()
1640 }
1641
1642 fn create_state(&self) -> RawScrollbarState {
1643 RawScrollbarState {
1644 state: StateData::new(),
1645 ticker_provider: TickerProviderStateMixinData::new(),
1646 raw_scrollbar_state: RawScrollbarStateData::new(),
1647 }
1648 }
1649}
1650
1651pub struct RawScrollbarStateData {
1653 start_drag_scrollbar_axis_offset: Option<Offset>,
1654 last_drag_update_offset: Option<Offset>,
1655 start_drag_thumb_offset: Option<f64>,
1656 cached_controller: Option<ScrollControllerRef>,
1657 fadeout_timer: Option<Timer>,
1658 fadeout_animation_controller: Option<Ref<AnimationController>>,
1659 fadeout_opacity_animation: Option<Ref<CurvedAnimation>>,
1660 scrollbar_painter: Option<Ref<ScrollbarPainter>>,
1661 scrollbar_painter_key: GlobalKey,
1662 hover_is_active: bool,
1663 thumb_drag: Option<Rc<dyn Drag>>,
1664 max_scroll_extent_permits_scrolling: bool,
1665 thumb_hold: Option<Rc<dyn ScrollHoldController>>,
1666 axis: Option<Axis>,
1667 gesture_detector_key: GlobalKey,
1668}
1669
1670impl RawScrollbarStateData {
1671 pub fn new() -> RawScrollbarStateData {
1673 RawScrollbarStateData {
1674 start_drag_scrollbar_axis_offset: None,
1675 last_drag_update_offset: None,
1676 start_drag_thumb_offset: None,
1677 cached_controller: None,
1678 fadeout_timer: None,
1679 fadeout_animation_controller: None,
1680 fadeout_opacity_animation: None,
1681 scrollbar_painter: None,
1682 scrollbar_painter_key: GlobalKey::new(),
1683 hover_is_active: false,
1684 thumb_drag: None,
1685 max_scroll_extent_permits_scrolling: false,
1686 thumb_hold: None,
1687 axis: None,
1688 gesture_detector_key: GlobalKey::new(),
1689 }
1690 }
1691}
1692
1693impl Default for RawScrollbarStateData {
1694 fn default() -> RawScrollbarStateData {
1695 RawScrollbarStateData::new()
1696 }
1697}
1698
1699#[macro_export]
1702macro_rules! raw_scrollbar_state_accessors {
1703 () => {
1704 fn raw_scrollbar_state_data(
1705 self: ::waft_foundation::Handle<Self>,
1706 app: &::waft_foundation::App,
1707 ) -> &$crate::RawScrollbarStateData {
1708 &app.get(self).raw_scrollbar_state
1709 }
1710
1711 fn raw_scrollbar_state_data_mut(
1712 self: ::waft_foundation::Handle<Self>,
1713 app: &mut ::waft_foundation::App,
1714 ) -> &mut $crate::RawScrollbarStateData {
1715 &mut app.get_mut(self).raw_scrollbar_state
1716 }
1717
1718 fn raw_scrollbar_state_bag(&mut self) -> &mut $crate::RawScrollbarStateData {
1719 &mut self.raw_scrollbar_state
1720 }
1721 };
1722}
1723
1724pub trait RawScrollbarStateLeaf: State + TickerProviderStateMixin + TickerProviderObject
1732where
1733 Self::Widget: RawScrollbarLeaf,
1734{
1735 fn raw_scrollbar_state_data(self: Handle<Self>, app: &App) -> &RawScrollbarStateData;
1738
1739 fn raw_scrollbar_state_data_mut(
1741 self: Handle<Self>,
1742 app: &mut App,
1743 ) -> &mut RawScrollbarStateData;
1744
1745 fn raw_scrollbar_state_bag(&mut self) -> &mut RawScrollbarStateData;
1748
1749 fn show_scrollbar(self: Handle<Self>, app: &mut App) -> bool {
1756 self.widget(app)
1757 .raw_scrollbar_data()
1758 .thumb_visibility
1759 .unwrap_or(false)
1760 }
1761
1762 fn enable_gestures(self: Handle<Self>, app: &mut App) -> bool {
1770 self.widget(app)
1771 .raw_scrollbar_data()
1772 .interactive
1773 .unwrap_or(true)
1774 }
1775
1776 fn update_scrollbar_painter(self: Handle<Self>, app: &mut App) {
1783 RawScrollbarState::update_scrollbar_painter(self, app);
1784 }
1785
1786 fn get_scrollbar_direction(self: Handle<Self>, app: &App) -> Option<Axis> {
1789 self.raw_scrollbar_state_data(app).axis
1790 }
1791
1792 fn handle_thumb_press(self: Handle<Self>, app: &mut App) {
1796 RawScrollbarState::handle_thumb_press(self, app);
1797 }
1798
1799 fn handle_thumb_press_start(self: Handle<Self>, app: &mut App, local_position: Offset) {
1803 RawScrollbarState::handle_thumb_press_start(self, app, local_position);
1804 }
1805
1806 fn handle_thumb_press_update(self: Handle<Self>, app: &mut App, local_position: Offset) {
1810 RawScrollbarState::handle_thumb_press_update(self, app, local_position);
1811 }
1812
1813 fn handle_thumb_press_end(
1815 self: Handle<Self>,
1816 app: &mut App,
1817 local_position: Offset,
1818 velocity: Velocity,
1819 ) {
1820 RawScrollbarState::handle_thumb_press_end(self, app, local_position, velocity);
1821 }
1822
1823 fn handle_track_tap_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
1826 RawScrollbarState::handle_track_tap_down(self, app, details);
1827 }
1828
1829 fn handle_hover(self: Handle<Self>, app: &mut App, event: &PointerHoverEvent) {
1838 RawScrollbarState::handle_hover(self, app, event);
1839 }
1840
1841 fn handle_hover_exit(self: Handle<Self>, app: &mut App) {
1845 RawScrollbarState::handle_hover_exit(self, app);
1846 }
1847}
1848
1849pub struct RawScrollbarState {
1851 state: StateData<RawScrollbar>,
1852 ticker_provider: TickerProviderStateMixinData,
1853 raw_scrollbar_state: RawScrollbarStateData,
1854}
1855
1856impl RawScrollbarState {
1857 pub fn scrollbar_painter<S: RawScrollbarStateLeaf>(
1862 this: Handle<S>,
1863 app: &App,
1864 ) -> Handle<ScrollbarPainter>
1865 where
1866 S::Widget: RawScrollbarLeaf,
1867 {
1868 this.raw_scrollbar_state_data(app)
1869 .scrollbar_painter
1870 .handle()
1871 .expect("initState creates the painter")
1872 }
1873
1874 pub fn fadeout_animation_controller<S: RawScrollbarStateLeaf>(
1876 this: Handle<S>,
1877 app: &App,
1878 ) -> Handle<AnimationController>
1879 where
1880 S::Widget: RawScrollbarLeaf,
1881 {
1882 this.raw_scrollbar_state_data(app)
1883 .fadeout_animation_controller
1884 .handle()
1885 .expect("initState creates the controller")
1886 }
1887
1888 fn effective_scroll_controller<S: RawScrollbarStateLeaf>(
1889 this: Handle<S>,
1890 app: &mut App,
1891 ) -> Option<ScrollControllerRef>
1892 where
1893 S::Widget: RawScrollbarLeaf,
1894 {
1895 if let Some(controller) = this.widget(app).raw_scrollbar_data().controller.clone() {
1896 return Some(controller);
1897 }
1898 let context = this.context(app);
1899 PrimaryScrollController::maybe_of(app, context)
1900 }
1901
1902 fn show_track<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App) -> bool
1903 where
1904 S::Widget: RawScrollbarLeaf,
1905 {
1906 this.show_scrollbar(app)
1907 && this
1908 .widget(app)
1909 .raw_scrollbar_data()
1910 .track_visibility
1911 .unwrap_or(false)
1912 }
1913
1914 pub fn init_state<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
1916 where
1917 S::Widget: RawScrollbarLeaf,
1918 {
1919 let fade_duration = this.widget(app).raw_scrollbar_data().fade_duration;
1920 let controller = AnimationController::new(
1921 app,
1922 None,
1923 Some(fade_duration),
1924 None,
1925 0.0,
1926 1.0,
1927 AnimationBehavior::Normal,
1928 this,
1929 );
1930 AnimationLocalStatusListenersMixin::add_status_listener(
1931 controller.handle(),
1932 app,
1933 AnimationStatusListener::handle_method(this, validate_interactions::<S>),
1934 );
1935 let opacity =
1936 CurvedAnimation::new(app, controller.erase(), Curves::fast_out_slow_in(), None);
1937 this.raw_scrollbar_state_data_mut(app)
1938 .fadeout_animation_controller = Some(controller);
1939 this.raw_scrollbar_state_data_mut(app)
1940 .fadeout_opacity_animation = Some(opacity.clone());
1941
1942 let widget = this.widget(app).raw_scrollbar_data();
1943 let color = widget.thumb_color.unwrap_or(K_DEFAULT_THUMB_COLOR);
1944 let thickness = widget.thickness.unwrap_or(K_SCROLLBAR_THICKNESS);
1945 let radius = widget.radius;
1946 let track_radius = widget.track_radius;
1947 let scrollbar_orientation = widget.scrollbar_orientation;
1948 let main_axis_margin = widget.main_axis_margin;
1949 let shape = widget.shape.clone();
1950 let cross_axis_margin = widget.cross_axis_margin;
1951 let min_length = widget.min_thumb_length;
1952 let min_overscroll_length = widget.min_overscroll_length.unwrap_or(min_length);
1953
1954 let painter = ScrollbarPainter::new(app, color, opacity.into_erased());
1955 painter.set_thickness(app, thickness);
1956 painter.set_radius(app, radius);
1957 painter.set_track_radius(app, track_radius);
1958 painter.set_scrollbar_orientation(app, scrollbar_orientation);
1959 painter.set_main_axis_margin(app, main_axis_margin);
1960 painter.set_shape(app, shape);
1961 painter.set_cross_axis_margin(app, cross_axis_margin);
1962 painter.set_min_length(app, min_length);
1963 painter.set_min_overscroll_length(app, min_overscroll_length);
1964 this.raw_scrollbar_state_data_mut(app).scrollbar_painter = Some(painter);
1965 }
1966
1967 pub fn did_change_dependencies<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
1970 where
1971 S::Widget: RawScrollbarLeaf,
1972 {
1973 RawScrollbarState::debug_schedule_check_has_valid_scroll_position(this, app);
1974 }
1975
1976 fn debug_schedule_check_has_valid_scroll_position<S: RawScrollbarStateLeaf>(
1977 this: Handle<S>,
1978 app: &mut App,
1979 ) where
1980 S::Widget: RawScrollbarLeaf,
1981 {
1982 if !cfg!(debug_assertions) || !this.show_scrollbar(app) {
1983 return;
1984 }
1985 SchedulerBinding::add_post_frame_callback(
1986 app,
1987 FrameCallback::new(move |app: &mut App, _duration| {
1988 RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
1989 }),
1990 View::maybe_id_of(app, this.context(app)),
1991 );
1992 }
1993
1994 fn debug_check_has_valid_scroll_position<S: RawScrollbarStateLeaf>(
1995 this: Handle<S>,
1996 app: &mut App,
1997 ) where
1998 S::Widget: RawScrollbarLeaf,
1999 {
2000 if !cfg!(debug_assertions) || !this.mounted(app) {
2001 return;
2002 }
2003 let scroll_controller = RawScrollbarState::effective_scroll_controller(this, app);
2004 let try_primary = this.widget(app).raw_scrollbar_data().controller.is_none();
2005 let controller_for_error = if try_primary {
2006 "PrimaryScrollController"
2007 } else {
2008 "provided ScrollController"
2009 };
2010
2011 let when = if this
2012 .widget(app)
2013 .raw_scrollbar_data()
2014 .thumb_visibility
2015 .unwrap_or(false)
2016 {
2017 "Scrollbar.thumbVisibility is true"
2018 } else if this.enable_gestures(app) {
2019 "the scrollbar is interactive"
2020 } else {
2021 "using the Scrollbar"
2022 };
2023
2024 assert!(
2025 scroll_controller.is_some(),
2026 "A ScrollController is required when {when}. {}",
2027 if try_primary {
2028 "The Scrollbar was not provided a ScrollController, and attempted to use the \
2029 PrimaryScrollController, but none was found."
2030 } else {
2031 ""
2032 }
2033 );
2034 let scroll_controller = scroll_controller.expect("asserted above");
2035 assert!(
2036 scroll_controller.has_clients(app),
2037 "The Scrollbar's ScrollController has no ScrollPosition attached.\n\
2038 A Scrollbar cannot be painted without a ScrollPosition. \n\
2039 The Scrollbar attempted to use the {controller_for_error}. This ScrollController \
2040 should be associated with the ScrollView that the Scrollbar is being applied to.\n\
2041 {}",
2042 if try_primary {
2043 "If a ScrollController has not been provided, the PrimaryScrollController is \
2044 used by default on mobile platforms for ScrollViews with an Axis.vertical \
2045 scroll direction.\n\
2046 To use the PrimaryScrollController explicitly, set ScrollView.primary to true \
2047 on the Scrollable widget."
2048 } else {
2049 "When providing your own ScrollController, ensure both the Scrollbar and the \
2050 Scrollable widget use the same one."
2051 }
2052 );
2053 assert!(
2054 scroll_controller.positions(app).len() == 1,
2055 "The {controller_for_error} is attached to more than one ScrollPosition.\n\
2056 The Scrollbar requires a single ScrollPosition in order to be painted.\n\
2057 When {when}, the associated ScrollController must only have one ScrollPosition \
2058 attached.\n\
2059 {}",
2060 if try_primary {
2061 "If a ScrollController has not been provided, the PrimaryScrollController is \
2062 used by default on mobile platforms for ScrollViews with an Axis.vertical \
2063 scroll direction.\n\
2064 More than one ScrollView may have tried to use the PrimaryScrollController of \
2065 the current context. ScrollView.primary can override this behavior."
2066 } else {
2067 "The provided ScrollController cannot be shared by multiple ScrollView widgets."
2068 }
2069 );
2070 }
2071
2072 pub fn update_scrollbar_painter<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2075 where
2076 S::Widget: RawScrollbarLeaf,
2077 {
2078 let context = this.context(app);
2079 let text_direction = crate::widgets::basic::Directionality::of(app, context);
2080 let show_track = RawScrollbarState::show_track(this, app);
2081 let enable_gestures = this.enable_gestures(app);
2082 let painter = RawScrollbarState::scrollbar_painter(this, app);
2083
2084 let widget = this.widget(app).raw_scrollbar_data();
2085 let color = widget.thumb_color.unwrap_or(K_DEFAULT_THUMB_COLOR);
2086 let track_radius = widget.track_radius;
2087 let track_color = if show_track {
2088 widget.track_color.unwrap_or(K_DEFAULT_TRACK_COLOR)
2089 } else {
2090 K_TRANSPARENT
2091 };
2092 let track_border_color = if show_track {
2093 widget
2094 .track_border_color
2095 .unwrap_or(K_DEFAULT_TRACK_BORDER_COLOR)
2096 } else {
2097 K_TRANSPARENT
2098 };
2099 let thickness = widget.thickness.unwrap_or(K_SCROLLBAR_THICKNESS);
2100 let radius = widget.radius;
2101 let padding = widget.padding;
2102 let scrollbar_orientation = widget.scrollbar_orientation;
2103 let main_axis_margin = widget.main_axis_margin;
2104 let shape = widget.shape.clone();
2105 let cross_axis_margin = widget.cross_axis_margin;
2106 let min_length = widget.min_thumb_length;
2107 let min_overscroll_length = widget.min_overscroll_length.unwrap_or(min_length);
2108
2109 let padding = padding
2110 .unwrap_or_else(|| EdgeInsetsGeometry::from(MediaQuery::padding_of(app, context)))
2111 .resolve(Some(text_direction));
2112
2113 painter.set_color(app, color);
2114 painter.set_track_radius(app, track_radius);
2115 painter.set_track_color(app, track_color);
2116 painter.set_track_border_color(app, track_border_color);
2117 painter.set_text_direction(app, Some(text_direction));
2118 painter.set_thickness(app, thickness);
2119 painter.set_radius(app, radius);
2120 painter.set_padding(app, EdgeInsetsGeometry::from(padding));
2121 painter.set_scrollbar_orientation(app, scrollbar_orientation);
2122 painter.set_main_axis_margin(app, main_axis_margin);
2123 painter.set_shape(app, shape);
2124 painter.set_cross_axis_margin(app, cross_axis_margin);
2125 painter.set_min_length(app, min_length);
2126 painter.set_min_overscroll_length(app, min_overscroll_length);
2127 painter.set_ignore_pointer(app, !enable_gestures);
2128 }
2129
2130 pub fn did_update_widget<S: RawScrollbarStateLeaf>(
2132 this: Handle<S>,
2133 app: &mut App,
2134 old_widget: &S::Widget,
2135 ) where
2136 S::Widget: RawScrollbarLeaf,
2137 {
2138 let thumb_visibility = this.widget(app).raw_scrollbar_data().thumb_visibility;
2139 if thumb_visibility == old_widget.raw_scrollbar_data().thumb_visibility {
2140 return;
2141 }
2142 let controller = RawScrollbarState::fadeout_animation_controller(this, app);
2143 if thumb_visibility.unwrap_or(false) {
2144 RawScrollbarState::debug_schedule_check_has_valid_scroll_position(this, app);
2145 RawScrollbarState::cancel_fadeout_timer(this, app);
2146 controller.animate_to(app, 1.0, None, Curves::linear());
2147 } else {
2148 controller.reverse(app, None);
2149 }
2150 }
2151
2152 fn cancel_fadeout_timer<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2153 where
2154 S::Widget: RawScrollbarLeaf,
2155 {
2156 if let Some(timer) = this.raw_scrollbar_state_data(app).fadeout_timer {
2157 timer.cancel(app);
2158 this.raw_scrollbar_state_data_mut(app).fadeout_timer = None;
2159 }
2160 }
2161
2162 fn maybe_start_fadeout_timer<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2163 where
2164 S::Widget: RawScrollbarLeaf,
2165 {
2166 if this.show_scrollbar(app) {
2167 return;
2168 }
2169 RawScrollbarState::cancel_fadeout_timer(this, app);
2170 let time_to_fade = this.widget(app).raw_scrollbar_data().time_to_fade;
2171 let timer = Timer::new(
2172 app,
2173 time_to_fade,
2174 Listener::new(move |app: &mut App| {
2175 RawScrollbarState::fadeout_timer_fired(this, app);
2176 }),
2177 );
2178 this.raw_scrollbar_state_data_mut(app).fadeout_timer = Some(timer);
2179 }
2180
2181 fn fadeout_timer_fired<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2182 where
2183 S::Widget: RawScrollbarLeaf,
2184 {
2185 RawScrollbarState::fadeout_animation_controller(this, app).reverse(app, None);
2186 this.raw_scrollbar_state_data_mut(app).fadeout_timer = None;
2187 }
2188
2189 fn dispose_thumb_drag<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2190 where
2191 S::Widget: RawScrollbarLeaf,
2192 {
2193 this.raw_scrollbar_state_data_mut(app).thumb_drag = None;
2194 }
2195
2196 fn dispose_thumb_hold<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2197 where
2198 S::Widget: RawScrollbarLeaf,
2199 {
2200 this.raw_scrollbar_state_data_mut(app).thumb_hold = None;
2201 }
2202
2203 fn get_primary_delta<S: RawScrollbarStateLeaf>(
2208 this: Handle<S>,
2209 app: &mut App,
2210 local_position: Offset,
2211 ) -> Option<f64>
2212 where
2213 S::Widget: RawScrollbarLeaf,
2214 {
2215 let data = this.raw_scrollbar_state_data(app);
2216 let cached_controller = data
2217 .cached_controller
2218 .handle()
2219 .expect("a press caches the controller");
2220 let start_drag_scrollbar_axis_offset = data
2221 .start_drag_scrollbar_axis_offset
2222 .expect("a drag records its start");
2223 let last_drag_update_offset = data
2224 .last_drag_update_offset
2225 .expect("a drag records its last update");
2226 let start_drag_thumb_offset = data
2227 .start_drag_thumb_offset
2228 .expect("a drag records the thumb offset");
2229
2230 let position = cached_controller.position(app);
2231 let (primary_delta_from_drag_start, primary_delta_from_last_drag_update) =
2232 match position.axis_direction(app) {
2233 AxisDirection::Up => (
2234 start_drag_scrollbar_axis_offset.dy() - local_position.dy(),
2235 last_drag_update_offset.dy() - local_position.dy(),
2236 ),
2237 AxisDirection::Right => (
2238 local_position.dx() - start_drag_scrollbar_axis_offset.dx(),
2239 local_position.dx() - last_drag_update_offset.dx(),
2240 ),
2241 AxisDirection::Down => (
2242 local_position.dy() - start_drag_scrollbar_axis_offset.dy(),
2243 local_position.dy() - last_drag_update_offset.dy(),
2244 ),
2245 AxisDirection::Left => (
2246 start_drag_scrollbar_axis_offset.dx() - local_position.dx(),
2247 last_drag_update_offset.dx() - local_position.dx(),
2248 ),
2249 };
2250
2251 let painter = RawScrollbarState::scrollbar_painter(this, app);
2254 let mut scroll_offset_global = painter
2255 .get_track_to_scroll(app, start_drag_thumb_offset + primary_delta_from_drag_start);
2256
2257 let pixels = position.pixels(app);
2258 if (primary_delta_from_drag_start > 0.0 && scroll_offset_global < pixels)
2259 || (primary_delta_from_drag_start < 0.0 && scroll_offset_global > pixels)
2260 {
2261 scroll_offset_global =
2264 pixels + painter.get_track_to_scroll(app, primary_delta_from_last_drag_update);
2265 }
2266 if scroll_offset_global == pixels {
2267 return None;
2268 }
2269
2270 let metrics = position.copy_with(app);
2272 let physics_adjustment = position
2273 .physics(app)
2274 .apply_boundary_conditions(&*metrics, scroll_offset_global);
2275 let mut new_position = scroll_offset_global - physics_adjustment;
2276
2277 let context = this.context(app);
2280 match ScrollConfiguration::of(app, context).get_platform(app, context) {
2281 TargetPlatform::Fuchsia
2282 | TargetPlatform::Linux
2283 | TargetPlatform::MacOS
2284 | TargetPlatform::Windows => {
2285 new_position = clamp_double(
2286 new_position,
2287 position.min_scroll_extent(app),
2288 position.max_scroll_extent(app),
2289 );
2290 }
2291 TargetPlatform::IOS | TargetPlatform::Android => {}
2294 }
2295 let is_reversed = axis_direction_is_reversed(position.axis_direction(app));
2296 Some(if is_reversed {
2297 new_position - pixels
2298 } else {
2299 pixels - new_position
2300 })
2301 }
2302
2303 pub fn handle_thumb_press<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2306 where
2307 S::Widget: RawScrollbarLeaf,
2308 {
2309 RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
2310 let controller = RawScrollbarState::effective_scroll_controller(this, app);
2311 this.raw_scrollbar_state_data_mut(app).cached_controller = controller.clone();
2312 if this.get_scrollbar_direction(app).is_none() {
2313 return;
2314 }
2315 RawScrollbarState::cancel_fadeout_timer(this, app);
2316 let position = controller.expect("a valid scroll position").position(app);
2317 let hold = position.hold(
2318 app,
2319 Listener::new(move |app: &mut App| {
2320 RawScrollbarState::dispose_thumb_hold(this, app);
2321 }),
2322 );
2323 this.raw_scrollbar_state_data_mut(app).thumb_hold = Some(hold);
2324 }
2325
2326 pub fn handle_thumb_press_start<S: RawScrollbarStateLeaf>(
2329 this: Handle<S>,
2330 app: &mut App,
2331 local_position: Offset,
2332 ) where
2333 S::Widget: RawScrollbarLeaf,
2334 {
2335 RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
2336 if this.get_scrollbar_direction(app).is_none() {
2337 return;
2338 }
2339 RawScrollbarState::cancel_fadeout_timer(this, app);
2340 RawScrollbarState::fadeout_animation_controller(this, app).forward(app, None);
2341
2342 debug_assert!(this.raw_scrollbar_state_data(app).thumb_drag.is_none());
2343 let position = this
2344 .raw_scrollbar_state_data(app)
2345 .cached_controller
2346 .handle()
2347 .expect("a press caches the controller")
2348 .position(app);
2349 let render_box = RawScrollbarState::painter_render_box(this, app);
2350 let details = DragStartDetails::new(
2351 render_box.local_to_global(app, local_position, None),
2352 Some(local_position),
2353 None,
2354 None,
2355 );
2356 let drag = position.drag(
2357 app,
2358 details,
2359 Listener::new(move |app: &mut App| {
2360 RawScrollbarState::dispose_thumb_drag(this, app);
2361 }),
2362 );
2363 this.raw_scrollbar_state_data_mut(app).thumb_drag = Some(drag);
2364 debug_assert!(this.raw_scrollbar_state_data(app).thumb_hold.is_none());
2365
2366 let thumb_offset =
2367 RawScrollbarState::scrollbar_painter(this, app).get_thumb_scroll_offset(app);
2368 let data = this.raw_scrollbar_state_data_mut(app);
2369 data.start_drag_scrollbar_axis_offset = Some(local_position);
2370 data.last_drag_update_offset = Some(local_position);
2371 data.start_drag_thumb_offset = Some(thumb_offset);
2372 }
2373
2374 pub fn handle_thumb_press_update<S: RawScrollbarStateLeaf>(
2377 this: Handle<S>,
2378 app: &mut App,
2379 local_position: Offset,
2380 ) where
2381 S::Widget: RawScrollbarLeaf,
2382 {
2383 RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
2384 if this.raw_scrollbar_state_data(app).last_drag_update_offset == Some(local_position) {
2385 return;
2386 }
2387 let position = this
2388 .raw_scrollbar_state_data(app)
2389 .cached_controller
2390 .handle()
2391 .expect("a press caches the controller")
2392 .position(app);
2393 let metrics = position.copy_with(app);
2394 if !position.physics(app).should_accept_user_offset(&*metrics) {
2395 return;
2396 }
2397 let Some(direction) = this.get_scrollbar_direction(app) else {
2398 return;
2399 };
2400 debug_assert!(
2402 this.raw_scrollbar_state_data(app).thumb_hold.is_none()
2403 || this.raw_scrollbar_state_data(app).thumb_drag.is_none()
2404 );
2405 let Some(thumb_drag) = this.raw_scrollbar_state_data(app).thumb_drag.clone() else {
2406 return;
2407 };
2408
2409 let Some(primary_delta) = RawScrollbarState::get_primary_delta(this, app, local_position)
2410 else {
2411 return;
2412 };
2413
2414 let delta = match direction {
2415 Axis::Horizontal => Offset::new(primary_delta, 0.0),
2416 Axis::Vertical => Offset::new(0.0, primary_delta),
2417 };
2418 let render_box = RawScrollbarState::painter_render_box(this, app);
2419 let scroll_details = DragUpdateDetails::new(
2420 render_box.local_to_global(app, local_position, None),
2421 Some(local_position),
2422 None,
2423 delta,
2424 Some(primary_delta),
2425 None,
2426 );
2427 thumb_drag.update(app, scroll_details);
2429
2430 this.raw_scrollbar_state_data_mut(app)
2431 .last_drag_update_offset = Some(local_position);
2432 }
2433
2434 pub fn handle_thumb_press_end<S: RawScrollbarStateLeaf>(
2437 this: Handle<S>,
2438 app: &mut App,
2439 local_position: Offset,
2440 velocity: Velocity,
2441 ) where
2442 S::Widget: RawScrollbarLeaf,
2443 {
2444 RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
2445 let Some(direction) = this.get_scrollbar_direction(app) else {
2446 return;
2447 };
2448 RawScrollbarState::maybe_start_fadeout_timer(this, app);
2449 let data = this.raw_scrollbar_state_data_mut(app);
2450 data.cached_controller = None;
2451 data.last_drag_update_offset = None;
2452
2453 debug_assert!(
2455 this.raw_scrollbar_state_data(app).thumb_hold.is_none()
2456 || this.raw_scrollbar_state_data(app).thumb_drag.is_none()
2457 );
2458 let Some(thumb_drag) = this.raw_scrollbar_state_data(app).thumb_drag.clone() else {
2459 return;
2460 };
2461
2462 let context = this.context(app);
2466 let platform = ScrollConfiguration::of(app, context).get_platform(app, context);
2467 let adjusted_velocity = match platform {
2468 TargetPlatform::IOS | TargetPlatform::Android => -velocity,
2469 _ => Velocity::ZERO,
2470 };
2471 let render_box = RawScrollbarState::painter_render_box(this, app);
2472 let details = DragEndDetails::new(
2473 render_box.local_to_global(app, local_position, None),
2474 Some(local_position),
2475 adjusted_velocity,
2476 Some(match direction {
2477 Axis::Horizontal => adjusted_velocity.pixels_per_second.dx(),
2478 Axis::Vertical => adjusted_velocity.pixels_per_second.dy(),
2479 }),
2480 );
2481
2482 thumb_drag.end(app, details);
2483 debug_assert!(this.raw_scrollbar_state_data(app).thumb_drag.is_none());
2484
2485 let data = this.raw_scrollbar_state_data_mut(app);
2486 data.start_drag_scrollbar_axis_offset = None;
2487 data.last_drag_update_offset = None;
2488 data.start_drag_thumb_offset = None;
2489 data.cached_controller = None;
2490 }
2491
2492 pub fn handle_track_tap_down<S: RawScrollbarStateLeaf>(
2495 this: Handle<S>,
2496 app: &mut App,
2497 details: TapDownDetails,
2498 ) where
2499 S::Widget: RawScrollbarLeaf,
2500 {
2501 RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
2503 let controller = RawScrollbarState::effective_scroll_controller(this, app);
2504 this.raw_scrollbar_state_data_mut(app).cached_controller = controller.clone();
2505
2506 let position = controller.expect("a valid scroll position").position(app);
2507 let metrics = position.copy_with(app);
2508 if !position.physics(app).should_accept_user_offset(&*metrics) {
2509 return;
2510 }
2511
2512 let thumb_offset = app
2514 .get(RawScrollbarState::scrollbar_painter(this, app))
2515 .thumb_offset;
2516 let local_position = details.local_position;
2517 let scroll_direction = match axis_direction_to_axis(position.axis_direction(app)) {
2518 Axis::Vertical => {
2519 if local_position.dy() > thumb_offset {
2520 AxisDirection::Down
2521 } else {
2522 AxisDirection::Up
2523 }
2524 }
2525 Axis::Horizontal => {
2526 if local_position.dx() > thumb_offset {
2527 AxisDirection::Right
2528 } else {
2529 AxisDirection::Left
2530 }
2531 }
2532 };
2533
2534 let notification_context = position
2535 .context(app)
2536 .notification_context(app)
2537 .expect("a laid-out scrollable has a notification context");
2538 let state = Scrollable::maybe_of(app, notification_context, None);
2539 let intent = ScrollIntent {
2540 direction: scroll_direction,
2541 r#type: ScrollIncrementType::Page,
2542 };
2543 debug_assert!(state.is_some());
2544 let scroll_increment =
2545 ScrollAction::get_directional_increment(app, state.expect("a scrollable"), &intent);
2546
2547 position.move_to(
2548 app,
2549 position.pixels(app) + scroll_increment,
2550 Some(Duration::from_millis(100)),
2551 Some(Curves::ease_in_out()),
2552 None,
2553 );
2554 }
2555
2556 fn should_update_painter<S: RawScrollbarStateLeaf>(
2558 this: Handle<S>,
2559 app: &mut App,
2560 notification_axis: Axis,
2561 ) -> bool
2562 where
2563 S::Widget: RawScrollbarLeaf,
2564 {
2565 let Some(scroll_controller) = RawScrollbarState::effective_scroll_controller(this, app)
2568 else {
2569 return true;
2571 };
2572 if scroll_controller.positions(app).len() > 1 {
2574 return false;
2575 }
2576
2577 !scroll_controller.has_clients(app)
2580 || scroll_controller.position(app).axis(app) == notification_axis
2581 }
2582
2583 fn handle_scroll_metrics_notification<S: RawScrollbarStateLeaf>(
2584 this: Handle<S>,
2585 app: &mut App,
2586 notification: &ScrollMetricsNotification,
2587 ) -> bool
2588 where
2589 S::Widget: RawScrollbarLeaf,
2590 {
2591 let predicate = this
2592 .widget(app)
2593 .raw_scrollbar_data()
2594 .notification_predicate
2595 .clone();
2596 if !predicate(¬ification.as_scroll_update()) {
2597 return false;
2598 }
2599
2600 let controller = RawScrollbarState::fadeout_animation_controller(this, app);
2601 if this.show_scrollbar(app) && !controller.status(app).is_forward_or_completed() {
2602 controller.forward(app, None);
2603 }
2604
2605 let metrics = notification.metrics.clone();
2606 if RawScrollbarState::should_update_painter(this, app, metrics.axis()) {
2607 let axis_direction = metrics.axis_direction();
2608 RawScrollbarState::scrollbar_painter(this, app).update(
2609 app,
2610 metrics.clone(),
2611 axis_direction,
2612 );
2613 }
2614 if Some(metrics.axis()) != this.raw_scrollbar_state_data(app).axis {
2615 let axis = metrics.axis();
2616 this.set_state(app, |state| {
2617 state.raw_scrollbar_state_bag().axis = Some(axis);
2618 });
2619 }
2620 let permits = metrics.max_scroll_extent() > 0.0;
2621 if this
2622 .raw_scrollbar_state_data(app)
2623 .max_scroll_extent_permits_scrolling
2624 != permits
2625 {
2626 this.set_state(app, |state| {
2627 let data = state.raw_scrollbar_state_bag();
2628 data.max_scroll_extent_permits_scrolling =
2629 !data.max_scroll_extent_permits_scrolling;
2630 });
2631 }
2632
2633 false
2634 }
2635
2636 fn handle_scroll_notification<S: RawScrollbarStateLeaf>(
2637 this: Handle<S>,
2638 app: &mut App,
2639 notification: &dyn ScrollNotification,
2640 ) -> bool
2641 where
2642 S::Widget: RawScrollbarLeaf,
2643 {
2644 let predicate = this
2645 .widget(app)
2646 .raw_scrollbar_data()
2647 .notification_predicate
2648 .clone();
2649 if !predicate(notification) {
2650 return false;
2651 }
2652
2653 let metrics = notification.metrics().clone();
2654 let controller = RawScrollbarState::fadeout_animation_controller(this, app);
2655 if metrics.max_scroll_extent() <= metrics.min_scroll_extent() {
2656 if controller.status(app).is_forward_or_completed() {
2658 controller.reverse(app, None);
2659 }
2660
2661 if RawScrollbarState::should_update_painter(this, app, metrics.axis()) {
2662 let axis_direction = metrics.axis_direction();
2663 RawScrollbarState::scrollbar_painter(this, app).update(
2664 app,
2665 metrics,
2666 axis_direction,
2667 );
2668 }
2669 return false;
2670 }
2671
2672 let any = notification.as_any();
2673 if any.is::<ScrollUpdateNotification>() || any.is::<OverscrollNotification>() {
2674 if !controller.status(app).is_forward_or_completed() {
2676 controller.forward(app, None);
2677 }
2678
2679 RawScrollbarState::cancel_fadeout_timer(this, app);
2680
2681 if RawScrollbarState::should_update_painter(this, app, metrics.axis()) {
2682 let axis_direction = metrics.axis_direction();
2683 RawScrollbarState::scrollbar_painter(this, app).update(
2684 app,
2685 metrics,
2686 axis_direction,
2687 );
2688 }
2689 } else if any.is::<ScrollEndNotification>()
2690 && this.raw_scrollbar_state_data(app).thumb_drag.is_none()
2691 {
2692 RawScrollbarState::maybe_start_fadeout_timer(this, app);
2693 }
2694 false
2695 }
2696
2697 fn global_to_scrollbar<S: RawScrollbarStateLeaf>(
2702 this: Handle<S>,
2703 app: &mut App,
2704 offset: Offset,
2705 ) -> Offset
2706 where
2707 S::Widget: RawScrollbarLeaf,
2708 {
2709 RawScrollbarState::painter_render_box(this, app).global_to_local(app, offset, None)
2710 }
2711
2712 fn painter_render_box<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App) -> AnyRenderBox
2713 where
2714 S::Widget: RawScrollbarLeaf,
2715 {
2716 let key = this
2717 .raw_scrollbar_state_data(app)
2718 .scrollbar_painter_key
2719 .clone();
2720 let context = key
2721 .current_context(app)
2722 .expect("the CustomPaint is in the tree");
2723 context
2724 .find_render_object(app)
2725 .expect("the CustomPaint has a render object")
2726 .as_box()
2727 .expect("the key is on the scrollbar's CustomPaint")
2728 }
2729
2730 fn handle_thumb_drag_cancel<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2731 where
2732 S::Widget: RawScrollbarLeaf,
2733 {
2734 let key = this
2735 .raw_scrollbar_state_data(app)
2736 .gesture_detector_key
2737 .clone();
2738 if key.current_context(app).is_none() {
2739 return;
2742 }
2743 debug_assert!(
2746 this.raw_scrollbar_state_data(app).thumb_hold.is_none()
2747 || this.raw_scrollbar_state_data(app).thumb_drag.is_none()
2748 );
2749 if let Some(hold) = this.raw_scrollbar_state_data(app).thumb_hold.clone() {
2750 hold.cancel(app);
2751 }
2752 if let Some(drag) = this.raw_scrollbar_state_data(app).thumb_drag.clone() {
2753 drag.cancel(app);
2754 }
2755 debug_assert!(this.raw_scrollbar_state_data(app).thumb_hold.is_none());
2756 debug_assert!(this.raw_scrollbar_state_data(app).thumb_drag.is_none());
2757 }
2758
2759 fn can_handle_scroll_gestures<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App) -> bool
2760 where
2761 S::Widget: RawScrollbarLeaf,
2762 {
2763 if !this.enable_gestures(app) {
2764 return false;
2765 }
2766 let Some(controller) = RawScrollbarState::effective_scroll_controller(this, app) else {
2767 return false;
2768 };
2769 if controller.positions(app).len() != 1 {
2770 return false;
2771 }
2772 let position = controller.position(app);
2773 position.has_content_dimensions(app)
2774 && position.max_scroll_extent(app) - position.min_scroll_extent(app)
2775 > PRECISION_ERROR_TOLERANCE
2776 }
2777
2778 fn gestures<S: RawScrollbarStateLeaf>(
2779 this: Handle<S>,
2780 app: &mut App,
2781 ) -> GestureRecognizerFactories
2782 where
2783 S::Widget: RawScrollbarLeaf,
2784 {
2785 let mut gestures: GestureRecognizerFactories = Vec::new();
2786 if !RawScrollbarState::can_handle_scroll_gestures(this, app) {
2787 return gestures;
2788 }
2789
2790 let painter_key = this
2791 .raw_scrollbar_state_data(app)
2792 .scrollbar_painter_key
2793 .clone();
2794 let owner = this
2795 .context(app)
2796 .owner(app)
2797 .expect("a mounted element has a build owner");
2798 let controller =
2799 RawScrollbarState::effective_scroll_controller(this, app).expect("checked above");
2800 match controller.position(app).axis(app) {
2801 Axis::Horizontal => {
2802 let key = painter_key.clone();
2803 gestures.push((
2804 std::any::TypeId::of::<HorizontalThumbDragGestureRecognizer>(),
2805 GestureRecognizerFactoryWithHandlers::new(
2806 move |app: &mut App| {
2807 HorizontalThumbDragGestureRecognizer::new(app, owner, key.clone())
2808 },
2809 move |app: &mut App, instance| {
2810 init_thumb_drag_gesture_recognizer(this, app, instance);
2811 },
2812 )
2813 .into_factory(),
2814 ));
2815 }
2816 Axis::Vertical => {
2817 let key = painter_key.clone();
2818 gestures.push((
2819 std::any::TypeId::of::<VerticalThumbDragGestureRecognizer>(),
2820 GestureRecognizerFactoryWithHandlers::new(
2821 move |app: &mut App| {
2822 VerticalThumbDragGestureRecognizer::new(app, owner, key.clone())
2823 },
2824 move |app: &mut App, instance| {
2825 init_thumb_drag_gesture_recognizer(this, app, instance);
2826 },
2827 )
2828 .into_factory(),
2829 ));
2830 }
2831 }
2832
2833 let key = painter_key;
2834 gestures.push((
2835 std::any::TypeId::of::<TrackTapGestureRecognizer>(),
2836 GestureRecognizerFactoryWithHandlers::new(
2837 move |app: &mut App| TrackTapGestureRecognizer::new(app, owner, key.clone()),
2838 move |app: &mut App, instance: Handle<TrackTapGestureRecognizer>| {
2839 instance.set_on_tap_down(
2840 app,
2841 Some(Rc::new(move |app: &mut App, details| {
2842 this.handle_track_tap_down(app, details);
2843 })),
2844 );
2845 },
2846 )
2847 .into_factory(),
2848 ));
2849
2850 gestures
2851 }
2852
2853 pub fn is_pointer_over_track<S: RawScrollbarStateLeaf>(
2857 this: Handle<S>,
2858 app: &mut App,
2859 position: Offset,
2860 kind: PointerDeviceKind,
2861 ) -> bool
2862 where
2863 S::Widget: RawScrollbarLeaf,
2864 {
2865 if !RawScrollbarState::has_painter_context(this, app) {
2866 return false;
2867 }
2868 let local_offset = RawScrollbarState::global_to_scrollbar(this, app, position);
2869 let painter = RawScrollbarState::scrollbar_painter(this, app);
2870 painter.hit_test_interactive(app, local_offset, kind, false)
2871 && !painter.hit_test_only_thumb_interactive(app, local_offset, kind)
2872 }
2873
2874 pub fn is_pointer_over_thumb<S: RawScrollbarStateLeaf>(
2876 this: Handle<S>,
2877 app: &mut App,
2878 position: Offset,
2879 kind: PointerDeviceKind,
2880 ) -> bool
2881 where
2882 S::Widget: RawScrollbarLeaf,
2883 {
2884 if !RawScrollbarState::has_painter_context(this, app) {
2885 return false;
2886 }
2887 let local_offset = RawScrollbarState::global_to_scrollbar(this, app, position);
2888 RawScrollbarState::scrollbar_painter(this, app).hit_test_only_thumb_interactive(
2889 app,
2890 local_offset,
2891 kind,
2892 )
2893 }
2894
2895 pub fn is_pointer_over_scrollbar<S: RawScrollbarStateLeaf>(
2902 this: Handle<S>,
2903 app: &mut App,
2904 position: Offset,
2905 kind: PointerDeviceKind,
2906 ) -> bool
2907 where
2908 S::Widget: RawScrollbarLeaf,
2909 {
2910 if !RawScrollbarState::has_painter_context(this, app) {
2911 return false;
2912 }
2913 let local_offset = RawScrollbarState::global_to_scrollbar(this, app, position);
2914 RawScrollbarState::scrollbar_painter(this, app).hit_test_interactive(
2915 app,
2916 local_offset,
2917 kind,
2918 true,
2919 )
2920 }
2921
2922 fn has_painter_context<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App) -> bool
2923 where
2924 S::Widget: RawScrollbarLeaf,
2925 {
2926 let key = this
2927 .raw_scrollbar_state_data(app)
2928 .scrollbar_painter_key
2929 .clone();
2930 key.current_context(app).is_some()
2931 }
2932
2933 pub fn handle_hover<S: RawScrollbarStateLeaf>(
2935 this: Handle<S>,
2936 app: &mut App,
2937 event: &PointerHoverEvent,
2938 ) where
2939 S::Widget: RawScrollbarLeaf,
2940 {
2941 if RawScrollbarState::is_pointer_over_scrollbar(this, app, event.position, event.kind) {
2943 this.raw_scrollbar_state_data_mut(app).hover_is_active = true;
2944 RawScrollbarState::fadeout_animation_controller(this, app).forward(app, None);
2946 RawScrollbarState::cancel_fadeout_timer(this, app);
2947 } else if this.raw_scrollbar_state_data(app).hover_is_active {
2948 this.raw_scrollbar_state_data_mut(app).hover_is_active = false;
2950 RawScrollbarState::maybe_start_fadeout_timer(this, app);
2951 }
2952 }
2953
2954 pub fn handle_hover_exit<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
2957 where
2958 S::Widget: RawScrollbarLeaf,
2959 {
2960 this.raw_scrollbar_state_data_mut(app).hover_is_active = false;
2961 RawScrollbarState::maybe_start_fadeout_timer(this, app);
2962 }
2963
2964 fn pointer_signal_event_delta<S: RawScrollbarStateLeaf>(
2967 this: Handle<S>,
2968 app: &mut App,
2969 event: &PointerScrollEvent,
2970 ) -> f64
2971 where
2972 S::Widget: RawScrollbarLeaf,
2973 {
2974 let position = this
2975 .raw_scrollbar_state_data(app)
2976 .cached_controller
2977 .handle()
2978 .expect("a pointer signal caches the controller")
2979 .position(app);
2980 let mut delta = if position.axis(app) == Axis::Horizontal {
2981 event.scroll_delta.dx()
2982 } else {
2983 event.scroll_delta.dy()
2984 };
2985
2986 if axis_direction_is_reversed(position.axis_direction(app)) {
2987 delta *= -1.0;
2988 }
2989 delta
2990 }
2991
2992 fn target_scroll_offset_for_pointer_scroll<S: RawScrollbarStateLeaf>(
2995 this: Handle<S>,
2996 app: &mut App,
2997 delta: f64,
2998 ) -> f64
2999 where
3000 S::Widget: RawScrollbarLeaf,
3001 {
3002 let position = this
3003 .raw_scrollbar_state_data(app)
3004 .cached_controller
3005 .handle()
3006 .expect("a pointer signal caches the controller")
3007 .position(app);
3008 (position.pixels(app) + delta)
3009 .max(position.min_scroll_extent(app))
3010 .min(position.max_scroll_extent(app))
3011 }
3012
3013 fn handle_pointer_scroll<S: RawScrollbarStateLeaf>(
3014 this: Handle<S>,
3015 app: &mut App,
3016 event: &PointerEvent,
3017 ) where
3018 S::Widget: RawScrollbarLeaf,
3019 {
3020 let PointerEvent::Scroll(event) = event else {
3021 debug_assert!(false, "the pointer signal resolver replays a scroll event");
3022 return;
3023 };
3024 let controller = RawScrollbarState::effective_scroll_controller(this, app);
3025 this.raw_scrollbar_state_data_mut(app).cached_controller = controller.clone();
3026 let delta = RawScrollbarState::pointer_signal_event_delta(this, app, event);
3027 let target_scroll_offset =
3028 RawScrollbarState::target_scroll_offset_for_pointer_scroll(this, app, delta);
3029 let position = controller.expect("a cached controller").position(app);
3030 if delta != 0.0 && target_scroll_offset != position.pixels(app) {
3031 position.pointer_scroll(app, delta);
3032 }
3033 }
3034
3035 fn received_pointer_signal<S: RawScrollbarStateLeaf>(
3036 this: Handle<S>,
3037 app: &mut App,
3038 event: &PointerEvent,
3039 ) where
3040 S::Widget: RawScrollbarLeaf,
3041 {
3042 let controller = RawScrollbarState::effective_scroll_controller(this, app);
3043 this.raw_scrollbar_state_data_mut(app).cached_controller = controller.clone();
3044 let painter = RawScrollbarState::scrollbar_painter(this, app);
3046 let hit = painter
3047 .hit_test(app, Some(event.local_position()))
3048 .unwrap_or(false);
3049 let Some(controller) = controller else {
3050 return;
3051 };
3052 if !hit
3053 || !controller.has_clients(app)
3054 || this.raw_scrollbar_state_data(app).thumb_drag.is_some()
3055 {
3056 return;
3057 }
3058 let position = controller.position(app);
3059 match event {
3060 PointerEvent::Scroll(scroll) => {
3061 let metrics = position.copy_with(app);
3062 if !position.physics(app).should_accept_user_offset(&*metrics) {
3063 return;
3064 }
3065 let delta = RawScrollbarState::pointer_signal_event_delta(this, app, scroll);
3066 let target_scroll_offset =
3067 RawScrollbarState::target_scroll_offset_for_pointer_scroll(this, app, delta);
3068 if delta != 0.0 && target_scroll_offset != position.pixels(app) {
3069 let resolver = GestureBinding::instance(app).pointer_signal_resolver(app);
3070 resolver.register(
3071 app,
3072 event,
3073 Rc::new(move |app: &mut App, event: &PointerEvent| {
3074 RawScrollbarState::handle_pointer_scroll(this, app, event);
3075 }),
3076 );
3077 }
3078 }
3079 PointerEvent::ScrollInertiaCancel(_) => {
3080 position.jump_to(app, position.pixels(app));
3081 }
3084 _ => {}
3085 }
3086 }
3087
3088 pub fn dispose<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
3090 where
3091 S::Widget: RawScrollbarLeaf,
3092 {
3093 let fadeout_animation_controller =
3094 RawScrollbarState::fadeout_animation_controller(this, app);
3095 fadeout_animation_controller.dispose(app);
3096 RawScrollbarState::cancel_fadeout_timer(this, app);
3097 let scrollbar_painter = RawScrollbarState::scrollbar_painter(this, app);
3098 scrollbar_painter.dispose(app);
3099 if let Some(opacity) = this
3100 .raw_scrollbar_state_data(app)
3101 .fadeout_opacity_animation
3102 .handle()
3103 {
3104 opacity.dispose(app);
3105 }
3106 }
3107
3108 pub fn build<S: RawScrollbarStateLeaf>(
3110 this: Handle<S>,
3111 app: &mut App,
3112 _context: BuildContext,
3113 ) -> WidgetRef
3114 where
3115 S::Widget: RawScrollbarLeaf,
3116 {
3117 this.update_scrollbar_painter(app);
3118
3119 let data = this.raw_scrollbar_state_data(app);
3120 let painter_key = data.scrollbar_painter_key.clone();
3121 let gesture_detector_key = data.gesture_detector_key.clone();
3122 let painter = data
3123 .scrollbar_painter
3124 .clone()
3125 .expect("initState creates the painter");
3126 let child = this.widget(app).raw_scrollbar_data().child.clone();
3127 let gestures = RawScrollbarState::gestures(this, app);
3128
3129 let custom_paint = CustomPaint::new()
3130 .key(painter_key.into())
3131 .foreground_painter(ScrollbarPainterRef::new(painter))
3132 .child(RepaintBoundary::new().child(child));
3133
3134 let mouse_region = MouseRegion::new()
3135 .on_exit(Rc::new(move |app: &mut App, event| match event.kind {
3136 PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad => {
3137 if this.enable_gestures(app) {
3138 this.handle_hover_exit(app);
3139 }
3140 }
3141 PointerDeviceKind::Stylus
3142 | PointerDeviceKind::InvertedStylus
3143 | PointerDeviceKind::Unknown
3144 | PointerDeviceKind::Touch => {}
3145 }))
3146 .on_hover(Rc::new(move |app: &mut App, event| match event.kind {
3147 PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad => {
3148 if this.enable_gestures(app) {
3149 this.handle_hover(app, &event);
3150 }
3151 }
3152 PointerDeviceKind::Stylus
3153 | PointerDeviceKind::InvertedStylus
3154 | PointerDeviceKind::Unknown
3155 | PointerDeviceKind::Touch => {}
3156 }))
3157 .child(custom_paint);
3158
3159 let gesture_detector = RawGestureDetector::new()
3160 .key(gesture_detector_key.into())
3161 .gestures(gestures)
3162 .child(mouse_region);
3163
3164 let listener = PointerListener::new()
3165 .on_pointer_signal(Rc::new(move |app: &mut App, event| {
3166 RawScrollbarState::received_pointer_signal(this, app, &event);
3167 }))
3168 .child(gesture_detector);
3169
3170 NotificationListener::<ScrollMetricsNotification>::new(
3171 NotificationListener::<dyn ScrollNotification>::new(
3172 RepaintBoundary::new().child(listener),
3173 )
3174 .on_notification(
3175 move |app: &mut App, notification: &dyn ScrollNotification| {
3176 RawScrollbarState::handle_scroll_notification(this, app, notification)
3177 },
3178 )
3179 .into_widget(),
3180 )
3181 .on_notification(
3182 move |app: &mut App, notification: &ScrollMetricsNotification| {
3183 RawScrollbarState::handle_scroll_metrics_notification(this, app, notification)
3184 },
3185 )
3186 .into_widget()
3187 }
3188}
3189
3190fn validate_interactions<S: RawScrollbarStateLeaf>(
3191 this: Handle<S>,
3192 app: &mut App,
3193 status: AnimationStatus,
3194) where
3195 S::Widget: RawScrollbarLeaf,
3196{
3197 if status.is_dismissed() {
3198 return;
3201 }
3202 if RawScrollbarState::effective_scroll_controller(this, app).is_none()
3203 || !this.enable_gestures(app)
3204 {
3205 return;
3206 }
3207 let controller = RawScrollbarState::fadeout_animation_controller(this, app);
3211 if controller.status(app) == AnimationStatus::Forward
3212 && this
3213 .widget(app)
3214 .raw_scrollbar_data()
3215 .thumb_visibility
3216 .unwrap_or(false)
3217 {
3218 return;
3221 }
3222 RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
3223}
3224
3225fn init_thumb_drag_gesture_recognizer<S, R>(this: Handle<S>, app: &mut App, instance: Handle<R>)
3226where
3227 S: RawScrollbarStateLeaf,
3228 S::Widget: RawScrollbarLeaf,
3229 R: DragGestureRecognizer + ThumbDragGestureRecognizer,
3230{
3231 instance.set_on_down(
3232 app,
3233 Some(Rc::new(move |app: &mut App, _details: DragDownDetails| {
3234 this.handle_thumb_press(app);
3235 })),
3236 );
3237 instance.set_on_start(
3238 app,
3239 Some(Rc::new(move |app: &mut App, details: DragStartDetails| {
3240 let local = RawScrollbarState::global_to_scrollbar(this, app, details.global_position);
3241 this.handle_thumb_press_start(app, local);
3242 })),
3243 );
3244 instance.set_on_update(
3245 app,
3246 Some(Rc::new(move |app: &mut App, details: DragUpdateDetails| {
3247 let local = RawScrollbarState::global_to_scrollbar(this, app, details.global_position);
3248 this.handle_thumb_press_update(app, local);
3249 })),
3250 );
3251 instance.set_on_end(
3252 app,
3253 Some(Rc::new(move |app: &mut App, details: DragEndDetails| {
3254 let local = RawScrollbarState::global_to_scrollbar(this, app, details.global_position);
3255 this.handle_thumb_press_end(app, local, details.velocity);
3256 })),
3257 );
3258 instance.set_on_cancel(
3259 app,
3260 Some(Listener::new(move |app: &mut App| {
3261 RawScrollbarState::handle_thumb_drag_cancel(this, app);
3262 })),
3263 );
3264 instance.set_thumb_gesture_settings(app, DeviceGestureSettings::new(Some(0.0)));
3265 instance.set_drag_start_behavior(app, DragStartBehavior::Down);
3266}
3267
3268impl State for RawScrollbarState {
3269 type Widget = RawScrollbar;
3270 crate::state_accessors!();
3271
3272 fn init_state(self: Handle<Self>, app: &mut App) {
3273 RawScrollbarState::init_state(self, app);
3274 }
3275
3276 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3277 RawScrollbarState::did_change_dependencies(self, app);
3278 }
3279
3280 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RawScrollbar) {
3281 RawScrollbarState::did_update_widget(self, app, old_widget);
3282 }
3283
3284 fn dispose(self: Handle<Self>, app: &mut App) {
3285 RawScrollbarState::dispose(self, app);
3286 TickerProviderStateMixin::dispose(self, app);
3287 }
3288
3289 fn activate(self: Handle<Self>, app: &mut App) {
3290 TickerProviderStateMixin::activate(self, app);
3291 }
3292
3293 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3294 RawScrollbarState::build(self, app, context)
3295 }
3296}
3297
3298impl RawScrollbarStateLeaf for RawScrollbarState {
3299 crate::raw_scrollbar_state_accessors!();
3300}
3301
3302impl TickerProviderObject for RawScrollbarState {
3303 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
3304 TickerProviderStateMixin::create_ticker(self, app, on_tick)
3305 }
3306}
3307
3308impl TickerProviderStateMixin for RawScrollbarState {
3309 fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
3310 &app.get(self).ticker_provider
3311 }
3312
3313 fn ticker_provider_data_mut(
3314 self: Handle<Self>,
3315 app: &mut App,
3316 ) -> &mut TickerProviderStateMixinData {
3317 &mut app.get_mut(self).ticker_provider
3318 }
3319}
3320
3321impl Debug for RawScrollbarState {
3322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3323 f.write_str("RawScrollbarState")
3324 }
3325}
3326
3327fn get_local_offset(
3330 app: &App,
3331 owner: Handle<BuildOwner>,
3332 scrollbar_painter_key: &GlobalKey,
3333 position: Offset,
3334) -> Option<Offset> {
3335 let element = owner.global_key_element(app, scrollbar_painter_key)?;
3336 let render_box = element
3337 .find_render_object(app)?
3338 .as_box()
3339 .expect("the key is on the scrollbar's CustomPaint");
3340 Some(render_box.global_to_local(app, position, None))
3341}
3342
3343fn painter_of(
3344 app: &App,
3345 owner: Handle<BuildOwner>,
3346 custom_paint_key: &GlobalKey,
3347) -> Option<Handle<ScrollbarPainter>> {
3348 let element = owner.global_key_element(app, custom_paint_key)?;
3349 let custom_paint = downcast_widget::<CustomPaint>(&**element.widget(app))?;
3350 custom_paint
3351 .foreground_painter
3352 .as_ref()?
3353 .as_any()
3354 .downcast_ref::<ScrollbarPainterRef>()
3355 .map(ScrollbarPainterRef::painter)
3356}
3357
3358fn is_thumb_event(
3359 app: &App,
3360 owner: Handle<BuildOwner>,
3361 custom_paint_key: &GlobalKey,
3362 event: &PointerDownEvent,
3363) -> bool {
3364 let Some(painter) = painter_of(app, owner, custom_paint_key) else {
3365 return false;
3366 };
3367 let Some(local_offset) = get_local_offset(app, owner, custom_paint_key, event.position) else {
3368 return false;
3369 };
3370 painter.hit_test_only_thumb_interactive(app, local_offset, event.kind)
3371}
3372
3373fn is_track_event(
3374 app: &App,
3375 owner: Handle<BuildOwner>,
3376 custom_paint_key: &GlobalKey,
3377 event: &PointerDownEvent,
3378) -> bool {
3379 let Some(painter) = painter_of(app, owner, custom_paint_key) else {
3380 return false;
3381 };
3382 let Some(local_offset) = get_local_offset(app, owner, custom_paint_key, event.position) else {
3383 return false;
3384 };
3385 let kind = event.kind;
3386 painter.hit_test_interactive(app, local_offset, kind, false)
3387 && !painter.hit_test_only_thumb_interactive(app, local_offset, kind)
3388}
3389
3390pub trait ThumbDragGestureRecognizer: Sized + 'static {
3393 fn set_thumb_gesture_settings(
3396 self: Handle<Self>,
3397 app: &mut App,
3398 settings: DeviceGestureSettings,
3399 );
3400}
3401
3402macro_rules! thumb_drag_gesture_recognizer_leaf {
3406 ($name:ident, $description:literal) => {
3407 impl $name {
3408 pub fn new(
3411 app: &mut App,
3412 owner: Handle<BuildOwner>,
3413 custom_paint_key: GlobalKey,
3414 ) -> Ref<$name> {
3415 app.create($name {
3416 recognizer: GestureRecognizerData::new(),
3417 one_sequence: OneSequenceData::new(),
3418 drag: DragData::new(),
3419 owner,
3420 custom_paint_key,
3421 })
3422 }
3423 }
3424
3425 impl ThumbDragGestureRecognizer for $name {
3426 fn set_thumb_gesture_settings(
3427 self: Handle<Self>,
3428 app: &mut App,
3429 settings: DeviceGestureSettings,
3430 ) {
3431 app.get_mut(self)
3432 .recognizer
3433 .set_gesture_settings(Some(settings));
3434 }
3435 }
3436
3437 impl RecognizerLeafData for $name {
3438 fn recognizer(&self) -> &GestureRecognizerData {
3439 &self.recognizer
3440 }
3441
3442 fn recognizer_mut(&mut self) -> &mut GestureRecognizerData {
3443 &mut self.recognizer
3444 }
3445 }
3446
3447 impl OneSequenceLeafData for $name {
3448 fn one_sequence(&self) -> &OneSequenceData {
3449 &self.one_sequence
3450 }
3451
3452 fn one_sequence_mut(&mut self) -> &mut OneSequenceData {
3453 &mut self.one_sequence
3454 }
3455 }
3456
3457 impl DragLeafData for $name {
3458 fn drag(&self) -> &DragData {
3459 &self.drag
3460 }
3461
3462 fn drag_mut(&mut self) -> &mut DragData {
3463 &mut self.drag
3464 }
3465 }
3466
3467 impl RecognizerLeaf for $name {
3468 fn handle_non_allowed_pointer(
3469 self: Handle<Self>,
3470 app: &mut App,
3471 _event: &PointerDownEvent,
3472 ) {
3473 waft_gestures::OneSequenceGestureRecognizer::handle_non_allowed_pointer(self, app);
3474 }
3475
3476 fn is_pointer_allowed(self: Handle<Self>, app: &App, event: &PointerDownEvent) -> bool {
3477 let recognizer = app.get(self);
3478 is_thumb_event(app, recognizer.owner, &recognizer.custom_paint_key, event)
3479 && DragGestureRecognizer::is_pointer_allowed(self, app, event)
3480 }
3481
3482 fn is_pointer_pan_zoom_allowed(
3483 self: Handle<Self>,
3484 _app: &App,
3485 _event: &PointerPanZoomStartEvent,
3486 ) -> bool {
3487 false
3488 }
3489
3490 fn add_allowed_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
3491 DragGestureRecognizer::add_allowed_pointer(self, app, event);
3492 }
3493
3494 fn add_allowed_pointer_pan_zoom(
3495 self: Handle<Self>,
3496 app: &mut App,
3497 event: PointerPanZoomStartEvent,
3498 ) {
3499 DragGestureRecognizer::add_allowed_pointer_pan_zoom(self, app, event);
3500 }
3501
3502 fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
3503 DragGestureRecognizer::handle_event(self, app, event);
3504 }
3505
3506 fn accept_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
3507 DragGestureRecognizer::accept_gesture(self, app, pointer);
3508 }
3509
3510 fn reject_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
3511 DragGestureRecognizer::reject_gesture(self, app, pointer);
3512 }
3513
3514 fn did_stop_tracking_last_pointer(self: Handle<Self>, app: &mut App, pointer: i64) {
3515 DragGestureRecognizer::did_stop_tracking_last_pointer(self, app, pointer);
3516 }
3517
3518 fn dispose(self: Handle<Self>, app: &mut App) {
3519 DragGestureRecognizer::dispose(self, app);
3520 }
3521
3522 fn debug_description(self: Handle<Self>) -> &'static str {
3523 $description
3524 }
3525 }
3526 };
3527}
3528
3529pub struct VerticalThumbDragGestureRecognizer {
3532 recognizer: GestureRecognizerData,
3533 one_sequence: OneSequenceData,
3534 drag: DragData,
3535 owner: Handle<BuildOwner>,
3536 custom_paint_key: GlobalKey,
3537}
3538
3539thumb_drag_gesture_recognizer_leaf!(VerticalThumbDragGestureRecognizer, "vertical thumb drag");
3540
3541impl DragLeaf for VerticalThumbDragGestureRecognizer {
3542 fn is_fling_gesture(
3543 self: Handle<Self>,
3544 app: &App,
3545 estimate: &VelocityEstimate,
3546 kind: PointerDeviceKind,
3547 ) -> bool {
3548 VerticalDragGestureRecognizerBase::is_fling_gesture(self, app, estimate, kind)
3549 }
3550
3551 fn consider_fling(
3552 self: Handle<Self>,
3553 app: &App,
3554 estimate: &VelocityEstimate,
3555 kind: PointerDeviceKind,
3556 ) -> Option<DragEndDetails> {
3557 VerticalDragGestureRecognizerBase::consider_fling(self, app, estimate, kind)
3558 }
3559
3560 fn has_sufficient_global_distance_to_accept(
3561 self: Handle<Self>,
3562 app: &App,
3563 pointer_device_kind: PointerDeviceKind,
3564 device_touch_slop: Option<f64>,
3565 ) -> bool {
3566 VerticalDragGestureRecognizerBase::has_sufficient_global_distance_to_accept(
3567 self,
3568 app,
3569 pointer_device_kind,
3570 device_touch_slop,
3571 )
3572 }
3573
3574 fn get_delta_for_details(self: Handle<Self>, app: &App, delta: Offset) -> Offset {
3575 VerticalDragGestureRecognizerBase::get_delta_for_details(self, app, delta)
3576 }
3577
3578 fn get_primary_value_from_offset(self: Handle<Self>, app: &App, value: Offset) -> Option<f64> {
3579 VerticalDragGestureRecognizerBase::get_primary_value_from_offset(self, app, value)
3580 }
3581
3582 fn get_primary_drag_axis(self: Handle<Self>, app: &App) -> Option<DragDirection> {
3583 VerticalDragGestureRecognizerBase::get_primary_drag_axis(self, app)
3584 }
3585}
3586
3587pub struct HorizontalThumbDragGestureRecognizer {
3590 recognizer: GestureRecognizerData,
3591 one_sequence: OneSequenceData,
3592 drag: DragData,
3593 owner: Handle<BuildOwner>,
3594 custom_paint_key: GlobalKey,
3595}
3596
3597thumb_drag_gesture_recognizer_leaf!(
3598 HorizontalThumbDragGestureRecognizer,
3599 "horizontal thumb drag"
3600);
3601
3602impl DragLeaf for HorizontalThumbDragGestureRecognizer {
3603 fn is_fling_gesture(
3604 self: Handle<Self>,
3605 app: &App,
3606 estimate: &VelocityEstimate,
3607 kind: PointerDeviceKind,
3608 ) -> bool {
3609 HorizontalDragGestureRecognizerBase::is_fling_gesture(self, app, estimate, kind)
3610 }
3611
3612 fn consider_fling(
3613 self: Handle<Self>,
3614 app: &App,
3615 estimate: &VelocityEstimate,
3616 kind: PointerDeviceKind,
3617 ) -> Option<DragEndDetails> {
3618 HorizontalDragGestureRecognizerBase::consider_fling(self, app, estimate, kind)
3619 }
3620
3621 fn has_sufficient_global_distance_to_accept(
3622 self: Handle<Self>,
3623 app: &App,
3624 pointer_device_kind: PointerDeviceKind,
3625 device_touch_slop: Option<f64>,
3626 ) -> bool {
3627 HorizontalDragGestureRecognizerBase::has_sufficient_global_distance_to_accept(
3628 self,
3629 app,
3630 pointer_device_kind,
3631 device_touch_slop,
3632 )
3633 }
3634
3635 fn get_delta_for_details(self: Handle<Self>, app: &App, delta: Offset) -> Offset {
3636 HorizontalDragGestureRecognizerBase::get_delta_for_details(self, app, delta)
3637 }
3638
3639 fn get_primary_value_from_offset(self: Handle<Self>, app: &App, value: Offset) -> Option<f64> {
3640 HorizontalDragGestureRecognizerBase::get_primary_value_from_offset(self, app, value)
3641 }
3642
3643 fn get_primary_drag_axis(self: Handle<Self>, app: &App) -> Option<DragDirection> {
3644 HorizontalDragGestureRecognizerBase::get_primary_drag_axis(self, app)
3645 }
3646}
3647
3648pub struct TrackTapGestureRecognizer {
3651 recognizer: GestureRecognizerData,
3652 one_sequence: OneSequenceData,
3653 primary: PrimaryPointerData,
3654 base_tap: BaseTapData,
3655 owner: Handle<BuildOwner>,
3656 custom_paint_key: GlobalKey,
3657 on_tap_down: Option<GestureTapDownCallback>,
3658}
3659
3660impl TrackTapGestureRecognizer {
3661 pub fn new(
3664 app: &mut App,
3665 owner: Handle<BuildOwner>,
3666 custom_paint_key: GlobalKey,
3667 ) -> Ref<TrackTapGestureRecognizer> {
3668 app.create(TrackTapGestureRecognizer {
3669 recognizer: GestureRecognizerData::new(),
3670 one_sequence: OneSequenceData::new(),
3671 primary: PrimaryPointerData::new(
3672 Some(K_PRESS_TIMEOUT),
3673 Some(UNSET_TOUCH_SLOP),
3674 Some(UNSET_TOUCH_SLOP),
3675 ),
3676 base_tap: BaseTapData::new(),
3677 owner,
3678 custom_paint_key,
3679 on_tap_down: None,
3680 })
3681 }
3682
3683 pub fn on_tap_down(self: Handle<Self>, app: &App) -> Option<GestureTapDownCallback> {
3686 app.get(self).on_tap_down.clone()
3687 }
3688
3689 pub fn set_on_tap_down(
3691 self: Handle<Self>,
3692 app: &mut App,
3693 callback: Option<GestureTapDownCallback>,
3694 ) {
3695 app.get_mut(self).on_tap_down = callback;
3696 }
3697}
3698
3699impl RecognizerLeafData for TrackTapGestureRecognizer {
3700 fn recognizer(&self) -> &GestureRecognizerData {
3701 &self.recognizer
3702 }
3703
3704 fn recognizer_mut(&mut self) -> &mut GestureRecognizerData {
3705 &mut self.recognizer
3706 }
3707}
3708
3709impl OneSequenceLeafData for TrackTapGestureRecognizer {
3710 fn one_sequence(&self) -> &OneSequenceData {
3711 &self.one_sequence
3712 }
3713
3714 fn one_sequence_mut(&mut self) -> &mut OneSequenceData {
3715 &mut self.one_sequence
3716 }
3717}
3718
3719impl PrimaryPointerLeafData for TrackTapGestureRecognizer {
3720 fn primary(&self) -> &PrimaryPointerData {
3721 &self.primary
3722 }
3723
3724 fn primary_mut(&mut self) -> &mut PrimaryPointerData {
3725 &mut self.primary
3726 }
3727}
3728
3729impl BaseTapLeafData for TrackTapGestureRecognizer {
3730 fn base_tap(&self) -> &BaseTapData {
3731 &self.base_tap
3732 }
3733
3734 fn base_tap_mut(&mut self) -> &mut BaseTapData {
3735 &mut self.base_tap
3736 }
3737}
3738
3739impl RecognizerLeaf for TrackTapGestureRecognizer {
3740 fn add_allowed_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
3741 BaseTapGestureRecognizer::add_allowed_pointer(self, app, event);
3742 }
3743
3744 fn handle_non_allowed_pointer(self: Handle<Self>, app: &mut App, event: &PointerDownEvent) {
3745 PrimaryPointerGestureRecognizer::handle_non_allowed_pointer(self, app, event);
3746 }
3747
3748 fn start_tracking_pointer(
3749 self: Handle<Self>,
3750 app: &mut App,
3751 pointer: i64,
3752 transform: Option<Matrix4>,
3753 ) {
3754 BaseTapGestureRecognizer::start_tracking_pointer(self, app, pointer, transform);
3755 }
3756
3757 fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
3758 PrimaryPointerGestureRecognizer::handle_event(self, app, event);
3759 }
3760
3761 fn did_stop_tracking_last_pointer(self: Handle<Self>, app: &mut App, pointer: i64) {
3762 PrimaryPointerGestureRecognizer::did_stop_tracking_last_pointer(self, app, pointer);
3763 }
3764
3765 fn dispose(self: Handle<Self>, app: &mut App) {
3766 PrimaryPointerGestureRecognizer::dispose(self, app);
3767 }
3768
3769 fn resolve(self: Handle<Self>, app: &mut App, disposition: GestureDisposition) {
3770 BaseTapGestureRecognizer::resolve(self, app, disposition);
3771 }
3772
3773 fn accept_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
3774 BaseTapGestureRecognizer::accept_gesture(self, app, pointer);
3775 }
3776
3777 fn reject_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
3778 BaseTapGestureRecognizer::reject_gesture(self, app, pointer);
3779 }
3780
3781 fn is_pointer_allowed(self: Handle<Self>, app: &App, event: &PointerDownEvent) -> bool {
3782 let recognizer = app.get(self);
3783 is_track_event(app, recognizer.owner, &recognizer.custom_paint_key, event)
3784 && recognizer.on_tap_down.is_some()
3785 && event.buttons == K_PRIMARY_BUTTON
3786 && GestureRecognizer::is_pointer_allowed(self, app, event)
3787 }
3788
3789 fn debug_description(self: Handle<Self>) -> &'static str {
3790 "track tap"
3791 }
3792}
3793
3794impl PrimaryPointerLeaf for TrackTapGestureRecognizer {
3795 fn handle_primary_pointer(self: Handle<Self>, app: &mut App, event: PointerEvent) {
3796 BaseTapGestureRecognizer::handle_primary_pointer(self, app, event);
3797 }
3798
3799 fn did_exceed_deadline(self: Handle<Self>, app: &mut App) {
3800 BaseTapGestureRecognizer::did_exceed_deadline(self, app);
3801 }
3802}
3803
3804impl BaseTapLeaf for TrackTapGestureRecognizer {
3805 fn handle_tap_down(self: Handle<Self>, app: &mut App, down: &PointerDownEvent) {
3806 if down.buttons != K_PRIMARY_BUTTON {
3807 return;
3808 }
3809 let details = TapDownDetails::new(
3810 down.position,
3811 Some(down.local_position()),
3812 Some(GestureRecognizer::kind_for_pointer(self, app, down.pointer)),
3813 );
3814 if let Some(callback) = app.get(self).on_tap_down.clone() {
3815 GestureRecognizer::invoke_callback(self, app, "onTapDown", |app| {
3816 callback(app, details)
3817 });
3818 }
3819 }
3820
3821 fn handle_tap_up(
3822 self: Handle<Self>,
3823 _app: &mut App,
3824 _down: &PointerDownEvent,
3825 _up: &PointerUpEvent,
3826 ) {
3827 }
3828
3829 fn handle_tap_cancel(
3830 self: Handle<Self>,
3831 _app: &mut App,
3832 _down: &PointerDownEvent,
3833 _cancel: Option<&PointerCancelEvent>,
3834 _reason: &str,
3835 ) {
3836 }
3837}
3838
3839#[cfg(test)]
3840mod tests {
3841 use waft_embedder::TextDirection;
3842 use waft_foundation::OptionRetained;
3843 use waft_gestures::HitTestResult;
3844 use waft_painting::EdgeInsets;
3845 use waft_rendering::{BoxHitTestEntry, RenderCustomPaint, RendererBinding};
3846
3847 use super::*;
3848 use crate::testing::{WidgetTester, test_widgets};
3849 use crate::widgets::basic::{Directionality, SizedBox};
3850 use crate::widgets::media_query::MediaQueryData;
3851 use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
3852 use crate::widgets::scroll_view::ListView;
3853
3854 const ITEM_EXTENT: f64 = 50.0;
3855 const ITEM_COUNT: usize = 40;
3856 const VIEW_WIDTH: f64 = WidgetTester::SIZE.width();
3857 const VIEW_HEIGHT: f64 = WidgetTester::SIZE.height();
3858
3859 fn mount(tester: &mut WidgetTester) -> (GlobalKey, Handle<ScrollController>) {
3862 let key = GlobalKey::new();
3863 let controller = tester.update(ScrollController::default);
3864 let list = ListView::new()
3865 .controller(controller.erase())
3866 .children((0..ITEM_COUNT).map(|_| SizedBox::new().height(ITEM_EXTENT).into_widget()));
3867 let scrollbar = RawScrollbar::new(list)
3868 .key(key.clone().into())
3869 .controller(controller.erase());
3870 let tree: WidgetRef = MediaQuery::new(
3871 MediaQueryData::new()
3872 .size(WidgetTester::SIZE)
3873 .padding(EdgeInsets::ZERO),
3874 scrollbar,
3875 )
3876 .into_widget();
3877 tester.pump_widget(Directionality::new(TextDirection::Ltr, tree));
3878 tester.pump_by(Duration::from_millis(16));
3881 (key, controller.handle())
3882 }
3883
3884 fn painter(app: &mut App, key: &GlobalKey) -> Handle<ScrollbarPainter> {
3885 let state = key
3886 .current_state::<RawScrollbarState>(app)
3887 .expect("the scrollbar is mounted");
3888 RawScrollbarState::scrollbar_painter(state, app)
3889 }
3890
3891 fn scroll_a_little(tester: &mut WidgetTester, controller: Handle<ScrollController>) {
3893 tester.update(|app| controller.jump_to(app, 10.0));
3894 for _ in 1..4 {
3895 tester.pump_by(Duration::from_millis(100));
3896 }
3897 }
3898
3899 #[test]
3900 fn a_raw_scrollbar_paints_a_thumb_whose_extent_follows_the_metrics_and_fades_after_the_timer() {
3901 test_widgets(|tester| {
3902 let (key, controller) = mount(tester);
3903 scroll_a_little(tester, controller);
3904
3905 let painter = tester.update(|app| painter(app, &key));
3906 {
3907 let app = tester.cell.borrow();
3908 let thumb = app.get(painter).thumb_rect.expect("the thumb is painted");
3909 let content = ITEM_EXTENT * ITEM_COUNT as f64;
3910 assert!(
3911 (thumb.height() - VIEW_HEIGHT * (VIEW_HEIGHT / content)).abs() < 0.5,
3912 "the thumb extent is the visible fraction of the track: {thumb:?}"
3913 );
3914 assert!(
3915 painter.fadeout_opacity_animation(&app).value(&app) > 0.0,
3916 "a scroll fades the thumb in"
3917 );
3918 }
3919
3920 tester.pump_by(K_SCROLLBAR_TIME_TO_FADE + Duration::from_millis(1));
3923 for _ in 0..8 {
3924 tester.pump_by(Duration::from_millis(60));
3925 }
3926 let app = tester.cell.borrow();
3927 assert_eq!(
3928 painter.fadeout_opacity_animation(&app).value(&app),
3929 0.0,
3930 "the thumb has faded out"
3931 );
3932 });
3933 }
3934
3935 #[test]
3939 fn a_disposed_raw_scrollbar_frees_its_fade_and_painter() {
3940 test_widgets(|tester| {
3941 let (key, _controller) = mount(tester);
3942 let (fade, controller, painter) = {
3943 let app = tester.cell.borrow();
3944 let state = key
3945 .current_state::<RawScrollbarState>(&app)
3946 .expect("the scrollbar is mounted");
3947 let data = RawScrollbarState::raw_scrollbar_state_data(state, &app);
3948 (
3949 data.fadeout_opacity_animation
3950 .handle()
3951 .expect("made in init_state"),
3952 data.fadeout_animation_controller
3953 .handle()
3954 .expect("made in init_state"),
3955 data.scrollbar_painter.handle().expect("made in init_state"),
3956 )
3957 };
3958
3959 tester.pump_widget(SizedBox::new());
3960 let app = tester.cell.borrow();
3961 assert!(!app.contains(fade));
3962 assert!(!app.contains(controller));
3963 assert!(!app.contains(painter));
3964 });
3965 }
3966
3967 #[test]
3968 fn a_hit_on_the_painted_scrollbar_stops_at_the_custom_paint() {
3969 test_widgets(|tester| {
3970 let (key, controller) = mount(tester);
3971 scroll_a_little(tester, controller);
3972 let mut app = tester.cell.borrow_mut();
3973 let painter = painter(&mut app, &key);
3974 let thumb = app.get(painter).thumb_rect.expect("the thumb is painted");
3975
3976 let boxes_at = |app: &mut App, position: Offset| -> Vec<AnyRenderBox> {
3978 let mut result = HitTestResult::new();
3979 let views = RendererBinding::instance(app).render_views(app);
3980 let [view] = views.as_slice() else {
3981 panic!("the View widget registered one render view: {views:?}");
3982 };
3983 view.hit_test(app, &mut result, position);
3984 result
3985 .path()
3986 .iter()
3987 .filter_map(|entry| {
3988 let target: &dyn Any = entry.target();
3989 target
3990 .downcast_ref::<BoxHitTestEntry>()
3991 .map(BoxHitTestEntry::target)
3992 })
3993 .collect()
3994 };
3995 let is_custom_paint = |app: &App, hit: &AnyRenderBox| {
3996 hit.as_object().downcast::<RenderCustomPaint>(app).is_some()
3997 };
3998
3999 let on_thumb = boxes_at(&mut app, thumb.center());
4000 assert!(
4001 is_custom_paint(&app, &on_thumb[0]),
4002 "the painter absorbs the hit, so nothing below its CustomPaint is hit: {on_thumb:?}"
4003 );
4004 let beside_thumb = boxes_at(&mut app, Offset::new(20.0, thumb.center().dy()));
4005 assert!(
4006 !is_custom_paint(&app, &beside_thumb[0]) && beside_thumb.len() > on_thumb.len(),
4007 "a hit off the track goes on to the scrollable underneath: {beside_thumb:?}"
4008 );
4009 });
4010 }
4011
4012 #[test]
4013 fn dragging_the_raw_scrollbar_thumb_moves_the_scroll_position() {
4014 test_widgets(|tester| {
4015 let (key, controller) = mount(tester);
4016 let mut app = tester.cell.borrow_mut();
4017 let state = key
4018 .current_state::<RawScrollbarState>(&app)
4019 .expect("the scrollbar is mounted");
4020 assert_eq!(
4021 state.get_scrollbar_direction(&app),
4022 Some(Axis::Vertical),
4023 "the metrics notification tells the scrollbar its axis"
4024 );
4025
4026 state.handle_thumb_press(&mut app);
4027 state.handle_thumb_press_start(&mut app, Offset::new(VIEW_WIDTH - 3.0, 5.0));
4028 state.handle_thumb_press_update(&mut app, Offset::new(VIEW_WIDTH - 3.0, 25.0));
4029
4030 let content = ITEM_EXTENT * ITEM_COUNT as f64;
4031 let scrollable = content - VIEW_HEIGHT;
4032 let thumb_extent = VIEW_HEIGHT * (VIEW_HEIGHT / content);
4033 let expected = 20.0 * scrollable / (VIEW_HEIGHT - thumb_extent);
4034 assert!(
4035 (controller.offset(&app) - expected).abs() < 0.5,
4036 "a 20 pixel thumb drag scrolls the track fraction: {}",
4037 controller.offset(&app)
4038 );
4039
4040 state.handle_thumb_press_end(
4041 &mut app,
4042 Offset::new(VIEW_WIDTH - 3.0, 25.0),
4043 Velocity::ZERO,
4044 );
4045 assert!(
4046 app.get(state).raw_scrollbar_state.thumb_drag.is_none(),
4047 "the drag is released"
4048 );
4049 });
4050 }
4051
4052 #[test]
4053 fn a_raw_scrollbar_hides_its_thumb_when_the_child_cannot_scroll() {
4054 test_widgets(|tester| {
4055 let key = GlobalKey::new();
4056 let controller = tester.update(ScrollController::default);
4057 let list = ListView::new()
4058 .controller(controller.erase())
4059 .children([SizedBox::new().height(ITEM_EXTENT).into_widget()]);
4060 let scrollbar = RawScrollbar::new(list)
4061 .key(key.clone().into())
4062 .controller(controller.erase());
4063 let tree: WidgetRef =
4064 MediaQuery::new(MediaQueryData::new().size(WidgetTester::SIZE), scrollbar)
4065 .into_widget();
4066 tester.pump_widget(Directionality::new(TextDirection::Ltr, tree));
4067
4068 let painter = tester.update(|app| painter(app, &key));
4069 let app = tester.cell.borrow();
4070 assert_eq!(
4071 painter.fadeout_opacity_animation(&app).value(&app),
4072 0.0,
4073 "a scroll view with nothing to scroll never fades the thumb in"
4074 );
4075 });
4076 }
4077}