1use std::any::Any;
4use std::fmt;
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_embedder::{Offset, ViewId};
9use waft_foundation::{App, Handle, HandleId, Listener, OptionRetained};
10use waft_gestures::*;
11use waft_painting::Axis;
12use waft_rendering::{BoxHitTestEntry, HitTestBehavior, RenderMetaData};
13use waft_services::HapticFeedback;
14
15use crate::*;
16use waft_foundation::Ref;
17
18pub type DragTargetWillAccept<T> = Rc<dyn Fn(&mut App, Option<Rc<T>>) -> bool>;
20
21pub type DragTargetWillAcceptWithDetails<T> = Rc<dyn Fn(&mut App, DragTargetDetails<T>) -> bool>;
23
24pub type DragTargetAccept<T> = Rc<dyn Fn(&mut App, Rc<T>)>;
26
27pub type DragTargetAcceptWithDetails<T> = Rc<dyn Fn(&mut App, DragTargetDetails<T>)>;
29
30pub type DragTargetBuilder<T> =
32 Rc<dyn Fn(&mut App, BuildContext, Vec<Option<Rc<T>>>, Vec<Option<Rc<dyn Any>>>) -> WidgetRef>;
33
34pub type DragUpdateCallback = Rc<dyn Fn(&mut App, DragUpdateDetails)>;
36
37pub type DraggableCanceledCallback = Rc<dyn Fn(&mut App, Velocity, Offset)>;
39
40pub type DragEndCallback = Rc<dyn Fn(&mut App, DraggableDetails)>;
42
43pub type DragTargetLeave<T> = Rc<dyn Fn(&mut App, Option<Rc<T>>)>;
45
46pub type DragTargetMove<T> = Rc<dyn Fn(&mut App, DragTargetDetails<T>)>;
48
49pub type DragAnchorStrategy<T> =
51 Rc<dyn Fn(&mut App, &Draggable<T>, BuildContext, Offset) -> Offset>;
52
53pub fn child_drag_anchor_strategy<T: 'static>(
55 app: &mut App,
56 _draggable: &Draggable<T>,
57 context: BuildContext,
58 position: Offset,
59) -> Offset {
60 context
61 .find_render_object(app)
62 .unwrap()
63 .as_box()
64 .unwrap()
65 .global_to_local(app, position, None)
66}
67
68pub fn pointer_drag_anchor_strategy<T: 'static>(
70 _app: &mut App,
71 _draggable: &Draggable<T>,
72 _context: BuildContext,
73 _position: Offset,
74) -> Offset {
75 Offset::ZERO
76}
77
78pub struct Draggable<T: 'static> {
82 pub key: Option<KeyRef>,
84
85 pub data: Option<Rc<T>>,
87
88 pub axis: Option<Axis>,
100
101 pub child: WidgetRef,
115
116 pub child_when_dragging: Option<WidgetRef>,
127
128 pub feedback: WidgetRef,
133
134 pub feedback_offset: Offset,
138
139 pub drag_anchor_strategy: DragAnchorStrategy<T>,
156
157 pub ignoring_feedback_semantics: bool,
167
168 pub ignoring_feedback_pointer: bool,
175
176 pub affinity: Option<Axis>,
194
195 pub max_simultaneous_drags: Option<usize>,
204
205 pub on_drag_started: Option<Listener>,
207
208 pub on_drag_update: Option<DragUpdateCallback>,
213
214 pub on_draggable_canceled: Option<DraggableCanceledCallback>,
223
224 pub on_drag_completed: Option<Listener>,
233
234 pub on_drag_end: Option<DragEndCallback>,
243
244 pub root_overlay: bool,
252
253 pub hit_test_behavior: HitTestBehavior,
257
258 pub allowed_buttons_filter: Option<AllowedButtonsFilter>,
260}
261
262impl<T: 'static> Clone for Draggable<T> {
263 fn clone(&self) -> Self {
264 Self {
265 key: self.key.clone(),
266 data: self.data.clone(),
267 axis: self.axis,
268 child: self.child.clone(),
269 child_when_dragging: self.child_when_dragging.clone(),
270 feedback: self.feedback.clone(),
271 feedback_offset: self.feedback_offset,
272 drag_anchor_strategy: self.drag_anchor_strategy.clone(),
273 ignoring_feedback_semantics: self.ignoring_feedback_semantics,
274 ignoring_feedback_pointer: self.ignoring_feedback_pointer,
275 affinity: self.affinity,
276 max_simultaneous_drags: self.max_simultaneous_drags,
277 on_drag_started: self.on_drag_started.clone(),
278 on_drag_update: self.on_drag_update.clone(),
279 on_draggable_canceled: self.on_draggable_canceled.clone(),
280 on_drag_completed: self.on_drag_completed.clone(),
281 on_drag_end: self.on_drag_end.clone(),
282 root_overlay: self.root_overlay,
283 hit_test_behavior: self.hit_test_behavior,
284 allowed_buttons_filter: self.allowed_buttons_filter.clone(),
285 }
286 }
287}
288
289impl<T: 'static> fmt::Debug for Draggable<T> {
290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291 f.debug_struct("Draggable").finish_non_exhaustive()
292 }
293}
294
295impl<T: 'static> Draggable<T> {
296 #[cfg_attr(debug_assertions, track_caller)]
298 pub fn new<C, F>(child: impl IntoWidget<C>, feedback: impl IntoWidget<F>) -> Self {
299 Self {
300 key: None,
301 data: None,
302 axis: None,
303 child: child.into_widget(),
304 child_when_dragging: None,
305 feedback: feedback.into_widget(),
306 feedback_offset: Offset::ZERO,
307 drag_anchor_strategy: Rc::new(child_drag_anchor_strategy::<T>),
308 ignoring_feedback_semantics: true,
309 ignoring_feedback_pointer: true,
310 affinity: None,
311 max_simultaneous_drags: None,
312 on_drag_started: None,
313 on_drag_update: None,
314 on_draggable_canceled: None,
315 on_drag_completed: None,
316 on_drag_end: None,
317 root_overlay: false,
318 hit_test_behavior: HitTestBehavior::DeferToChild,
319 allowed_buttons_filter: None,
320 }
321 }
322
323 pub fn key(mut self, value: KeyRef) -> Self {
325 self.key = Some(value);
326 self
327 }
328
329 pub fn data(mut self, value: T) -> Self {
331 self.data = Some(Rc::new(value));
332 self
333 }
334
335 pub fn axis(mut self, value: Axis) -> Self {
337 self.axis = Some(value);
338 self
339 }
340
341 #[cfg_attr(debug_assertions, track_caller)]
343 pub fn child_when_dragging<K>(mut self, value: impl IntoWidget<K>) -> Self {
344 self.child_when_dragging = Some(value.into_widget());
345 self
346 }
347
348 pub fn feedback_offset(mut self, value: Offset) -> Self {
350 self.feedback_offset = value;
351 self
352 }
353
354 pub fn drag_anchor_strategy(mut self, value: DragAnchorStrategy<T>) -> Self {
356 self.drag_anchor_strategy = value;
357 self
358 }
359
360 pub fn ignoring_feedback_semantics(mut self, value: bool) -> Self {
362 self.ignoring_feedback_semantics = value;
363 self
364 }
365
366 pub fn ignoring_feedback_pointer(mut self, value: bool) -> Self {
368 self.ignoring_feedback_pointer = value;
369 self
370 }
371
372 pub fn affinity(mut self, value: Axis) -> Self {
374 self.affinity = Some(value);
375 self
376 }
377
378 pub fn max_simultaneous_drags(mut self, value: usize) -> Self {
380 self.max_simultaneous_drags = Some(value);
381 self
382 }
383
384 pub fn on_drag_started(mut self, value: Listener) -> Self {
386 self.on_drag_started = Some(value);
387 self
388 }
389
390 pub fn on_drag_update(mut self, value: DragUpdateCallback) -> Self {
392 self.on_drag_update = Some(value);
393 self
394 }
395
396 pub fn on_draggable_canceled(mut self, value: DraggableCanceledCallback) -> Self {
398 self.on_draggable_canceled = Some(value);
399 self
400 }
401
402 pub fn on_drag_completed(mut self, value: Listener) -> Self {
404 self.on_drag_completed = Some(value);
405 self
406 }
407
408 pub fn on_drag_end(mut self, value: DragEndCallback) -> Self {
410 self.on_drag_end = Some(value);
411 self
412 }
413
414 pub fn root_overlay(mut self, value: bool) -> Self {
416 self.root_overlay = value;
417 self
418 }
419
420 pub fn hit_test_behavior(mut self, value: HitTestBehavior) -> Self {
422 self.hit_test_behavior = value;
423 self
424 }
425
426 pub fn allowed_buttons_filter(mut self, value: AllowedButtonsFilter) -> Self {
428 self.allowed_buttons_filter = Some(value);
429 self
430 }
431}
432
433pub trait DraggableWidget: StatefulWidget<State = DraggableState<Self>> + Clone {
435 type Data: 'static;
436
437 fn draggable(&self) -> &Draggable<Self::Data>;
438
439 fn create_recognizer(
440 &self,
441 app: &mut App,
442 on_start: GestureMultiDragStartCallback,
443 ) -> MultiDragRecognizerRef {
444 let draggable = self.draggable();
445 let recognizer: MultiDragRecognizerRef = match draggable.affinity {
446 Some(Axis::Horizontal) => HorizontalMultiDragGestureRecognizer::new(app).into_erased(),
447 Some(Axis::Vertical) => VerticalMultiDragGestureRecognizer::new(app).into_erased(),
448 None => ImmediateMultiDragGestureRecognizer::new(app).into_erased(),
449 };
450 if let Some(filter) = draggable.allowed_buttons_filter.clone() {
451 recognizer.set_allowed_buttons_filter(app, filter);
452 }
453 recognizer.set_on_start(app, Some(on_start));
454 recognizer
455 }
456}
457
458impl<T: 'static> DraggableWidget for Draggable<T> {
459 type Data = T;
460
461 fn draggable(&self) -> &Self {
462 self
463 }
464}
465
466impl<T: 'static> StatefulWidget for Draggable<T> {
467 type State = DraggableState<Self>;
468
469 fn key(&self) -> Option<&KeyRef> {
470 self.key.as_ref()
471 }
472
473 fn create_state(&self) -> Self::State {
474 DraggableState::new()
475 }
476}
477
478pub struct LongPressDraggable<T: 'static> {
480 pub draggable: Draggable<T>,
482
483 pub haptic_feedback_on_start: bool,
485
486 pub delay: Duration,
490}
491
492impl<T: 'static> Clone for LongPressDraggable<T> {
493 fn clone(&self) -> Self {
494 Self {
495 draggable: self.draggable.clone(),
496 haptic_feedback_on_start: self.haptic_feedback_on_start,
497 delay: self.delay,
498 }
499 }
500}
501
502impl<T: 'static> fmt::Debug for LongPressDraggable<T> {
503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 f.debug_struct("LongPressDraggable").finish_non_exhaustive()
505 }
506}
507
508impl<T: 'static> LongPressDraggable<T> {
509 #[cfg_attr(debug_assertions, track_caller)]
511 pub fn new<C, F>(child: impl IntoWidget<C>, feedback: impl IntoWidget<F>) -> Self {
512 Self {
513 draggable: Draggable::new(child, feedback),
514 haptic_feedback_on_start: true,
515 delay: K_LONG_PRESS_TIMEOUT,
516 }
517 }
518
519 pub fn delay(mut self, value: Duration) -> Self {
521 self.delay = value;
522 self
523 }
524
525 pub fn haptic_feedback_on_start(mut self, value: bool) -> Self {
527 self.haptic_feedback_on_start = value;
528 self
529 }
530
531 pub fn key(mut self, value: KeyRef) -> Self {
533 self.draggable.key = Some(value);
534 self
535 }
536
537 pub fn data(mut self, value: T) -> Self {
539 self.draggable.data = Some(Rc::new(value));
540 self
541 }
542
543 pub fn axis(mut self, value: Axis) -> Self {
545 self.draggable.axis = Some(value);
546 self
547 }
548
549 #[cfg_attr(debug_assertions, track_caller)]
551 pub fn child_when_dragging<K>(mut self, value: impl IntoWidget<K>) -> Self {
552 self.draggable.child_when_dragging = Some(value.into_widget());
553 self
554 }
555
556 pub fn feedback_offset(mut self, value: Offset) -> Self {
558 self.draggable.feedback_offset = value;
559 self
560 }
561
562 pub fn drag_anchor_strategy(mut self, value: DragAnchorStrategy<T>) -> Self {
564 self.draggable.drag_anchor_strategy = value;
565 self
566 }
567
568 pub fn ignoring_feedback_semantics(mut self, value: bool) -> Self {
570 self.draggable.ignoring_feedback_semantics = value;
571 self
572 }
573
574 pub fn ignoring_feedback_pointer(mut self, value: bool) -> Self {
576 self.draggable.ignoring_feedback_pointer = value;
577 self
578 }
579
580 pub fn max_simultaneous_drags(mut self, value: usize) -> Self {
582 self.draggable.max_simultaneous_drags = Some(value);
583 self
584 }
585
586 pub fn on_drag_started(mut self, value: Listener) -> Self {
588 self.draggable.on_drag_started = Some(value);
589 self
590 }
591
592 pub fn on_drag_update(mut self, value: DragUpdateCallback) -> Self {
594 self.draggable.on_drag_update = Some(value);
595 self
596 }
597
598 pub fn on_draggable_canceled(mut self, value: DraggableCanceledCallback) -> Self {
600 self.draggable.on_draggable_canceled = Some(value);
601 self
602 }
603
604 pub fn on_drag_completed(mut self, value: Listener) -> Self {
606 self.draggable.on_drag_completed = Some(value);
607 self
608 }
609
610 pub fn on_drag_end(mut self, value: DragEndCallback) -> Self {
612 self.draggable.on_drag_end = Some(value);
613 self
614 }
615
616 pub fn root_overlay(mut self, value: bool) -> Self {
618 self.draggable.root_overlay = value;
619 self
620 }
621
622 pub fn hit_test_behavior(mut self, value: HitTestBehavior) -> Self {
624 self.draggable.hit_test_behavior = value;
625 self
626 }
627
628 pub fn allowed_buttons_filter(mut self, value: AllowedButtonsFilter) -> Self {
630 self.draggable.allowed_buttons_filter = Some(value);
631 self
632 }
633}
634
635impl<T: 'static> DraggableWidget for LongPressDraggable<T> {
636 type Data = T;
637
638 fn draggable(&self) -> &Draggable<T> {
639 &self.draggable
640 }
641
642 fn create_recognizer(
643 &self,
644 app: &mut App,
645 on_start: GestureMultiDragStartCallback,
646 ) -> MultiDragRecognizerRef {
647 let recognizer = DelayedMultiDragGestureRecognizer::new(app);
648 recognizer.set_delay(app, self.delay);
649 let recognizer: MultiDragRecognizerRef = recognizer.into_erased();
650 if let Some(filter) = self.draggable.allowed_buttons_filter.clone() {
651 recognizer.set_allowed_buttons_filter(app, filter);
652 }
653 let haptic = self.haptic_feedback_on_start;
654 recognizer.set_on_start(
655 app,
656 Some(Rc::new(move |app, position| {
657 let result = on_start(app, position);
658 if result.is_some() && haptic {
659 HapticFeedback::selection_click(app);
660 }
661 result
662 })),
663 );
664 recognizer
665 }
666}
667
668impl<T: 'static> StatefulWidget for LongPressDraggable<T> {
669 type State = DraggableState<Self>;
670
671 fn key(&self) -> Option<&KeyRef> {
672 self.draggable.key.as_ref()
673 }
674
675 fn create_state(&self) -> Self::State {
676 DraggableState::new()
677 }
678}
679
680pub struct DraggableState<W: DraggableWidget> {
682 state: StateData<W>,
684
685 recognizer: Option<MultiDragRecognizerRef>,
687
688 active_count: usize,
690}
691
692impl<W: DraggableWidget> Default for DraggableState<W> {
693 fn default() -> Self {
695 Self::new()
696 }
697}
698
699impl<W: DraggableWidget> DraggableState<W> {
700 pub fn new() -> Self {
702 Self {
703 state: StateData::new(),
704 recognizer: None,
705 active_count: 0,
706 }
707 }
708
709 fn dispose_recognizer_if_inactive(self: Handle<Self>, app: &mut App) {
710 if app.get(self).active_count > 0 {
711 return;
712 }
713 if let Some(recognizer) = app.get_mut(self).recognizer.take() {
714 recognizer.dispose(app);
715 }
716 }
717
718 fn route_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
719 if self
720 .widget(app)
721 .draggable()
722 .max_simultaneous_drags
723 .is_some_and(|max| app.get(self).active_count >= max)
724 {
725 return;
726 }
727 app.get(self)
728 .recognizer
729 .handle()
730 .unwrap()
731 .add_pointer(app, &event);
732 }
733
734 fn start_drag(self: Handle<Self>, app: &mut App, position: Offset) -> Option<Rc<dyn Drag>> {
735 let widget = self.widget(app).draggable().clone();
736 if widget
737 .max_simultaneous_drags
738 .is_some_and(|max| app.get(self).active_count >= max)
739 {
740 return None;
741 }
742 let context = self.context(app);
743 let start = (widget.drag_anchor_strategy)(app, &widget, context, position);
744 self.set_state(app, |state| state.active_count += 1);
745 let retained = self.keep(app);
746 let overlay = Overlay::of(app, context, widget.root_overlay);
747 let view_id = View::of(app, context).id();
748 let avatar = DragAvatar::new(
749 app,
750 overlay,
751 widget.data.clone().map(|data| data as Rc<dyn Any>),
752 widget.axis,
753 position,
754 start,
755 widget.feedback.clone(),
756 widget.feedback_offset,
757 widget.ignoring_feedback_semantics,
758 widget.ignoring_feedback_pointer,
759 view_id,
760 Rc::new(move |app, details| {
761 if self.mounted(app)
762 && let Some(callback) = self.widget(app).draggable().on_drag_update.clone()
763 {
764 callback(app, details);
765 }
766 }),
767 Rc::new(move |app, velocity, offset, was_accepted| {
768 let _keep_alive = &retained;
769 if self.mounted(app) {
770 self.set_state(app, |state| state.active_count -= 1);
771 } else {
772 app.get_mut(self).active_count -= 1;
773 self.dispose_recognizer_if_inactive(app);
774 }
775 let widget = self.widget(app).draggable().clone();
776 if self.mounted(app)
777 && let Some(callback) = widget.on_drag_end
778 {
779 callback(
780 app,
781 DraggableDetails {
782 was_accepted,
783 velocity,
784 offset,
785 },
786 );
787 }
788 if was_accepted
789 && let Some(callback) = self.widget(app).draggable().on_drag_completed.clone()
790 {
791 callback.call(app);
792 }
793 if !was_accepted
794 && let Some(callback) =
795 self.widget(app).draggable().on_draggable_canceled.clone()
796 {
797 callback(app, velocity, offset);
798 }
799 }),
800 );
801 if let Some(callback) = widget.on_drag_started {
802 callback.call(app);
803 }
804 Some(Rc::new(avatar))
805 }
806}
807
808impl<W: DraggableWidget> State for DraggableState<W> {
809 type Widget = W;
810 crate::state_accessors!();
811 fn init_state(self: Handle<Self>, app: &mut App) {
812 let widget = self.widget(app).clone();
813 let recognizer = widget.create_recognizer(
814 app,
815 Rc::new(move |app, position| self.start_drag(app, position)),
816 );
817 app.get_mut(self).recognizer = Some(recognizer);
818 }
819
820 fn dispose(self: Handle<Self>, app: &mut App) {
821 self.dispose_recognizer_if_inactive(app);
822 }
823
824 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
825 let context = self.context(app);
826 let settings = MediaQuery::maybe_gesture_settings_of(app, context);
827 app.get(self)
828 .recognizer
829 .handle()
830 .unwrap()
831 .set_gesture_settings(app, settings);
832 }
833
834 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
835 let widget = self.widget(app).draggable();
836 let can_drag = widget
837 .max_simultaneous_drags
838 .is_none_or(|max| app.get(self).active_count < max);
839 let show_child = app.get(self).active_count == 0 || widget.child_when_dragging.is_none();
840 let mut listener = crate::Listener::new()
841 .behavior(widget.hit_test_behavior)
842 .child(if show_child {
843 widget.child.clone()
844 } else {
845 widget.child_when_dragging.clone().unwrap()
846 });
847 if can_drag {
848 listener =
849 listener.on_pointer_down(Rc::new(move |app, event| self.route_pointer(app, event)));
850 }
851 listener.into_widget()
852 }
853}
854
855#[derive(Clone, Copy, Debug)]
857pub struct DraggableDetails {
858 pub was_accepted: bool,
860
861 pub velocity: Velocity,
864
865 pub offset: Offset,
868}
869
870pub struct DragTargetDetails<T> {
872 pub data: Rc<T>,
874
875 pub offset: Offset,
878}
879
880impl<T> Clone for DragTargetDetails<T> {
881 fn clone(&self) -> Self {
882 Self {
883 data: self.data.clone(),
884 offset: self.offset,
885 }
886 }
887}
888
889pub struct DragTarget<T: 'static> {
891 pub key: Option<KeyRef>,
893
894 pub builder: DragTargetBuilder<T>,
896
897 pub on_will_accept: Option<DragTargetWillAccept<T>>,
899
900 pub on_will_accept_with_details: Option<DragTargetWillAcceptWithDetails<T>>,
902
903 pub on_accept: Option<DragTargetAccept<T>>,
905
906 pub on_accept_with_details: Option<DragTargetAcceptWithDetails<T>>,
908
909 pub on_leave: Option<DragTargetLeave<T>>,
911
912 pub on_move: Option<DragTargetMove<T>>,
914
915 pub hit_test_behavior: HitTestBehavior,
917}
918
919impl<T: 'static> fmt::Debug for DragTarget<T> {
920 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921 f.debug_struct("DragTarget").finish_non_exhaustive()
922 }
923}
924
925impl<T: 'static> DragTarget<T> {
926 pub fn new(
928 builder: impl Fn(
929 &mut App,
930 BuildContext,
931 Vec<Option<Rc<T>>>,
932 Vec<Option<Rc<dyn Any>>>,
933 ) -> WidgetRef
934 + 'static,
935 ) -> Self {
936 Self {
937 key: None,
938 builder: Rc::new(builder),
939 on_will_accept: None,
940 on_will_accept_with_details: None,
941 on_accept: None,
942 on_accept_with_details: None,
943 on_leave: None,
944 on_move: None,
945 hit_test_behavior: HitTestBehavior::Translucent,
946 }
947 }
948
949 pub fn key(mut self, value: KeyRef) -> Self {
951 self.key = Some(value);
952 self
953 }
954
955 pub fn on_will_accept(mut self, value: DragTargetWillAccept<T>) -> Self {
957 self.on_will_accept = Some(value);
958 self
959 }
960
961 pub fn on_will_accept_with_details(
963 mut self,
964 value: DragTargetWillAcceptWithDetails<T>,
965 ) -> Self {
966 self.on_will_accept_with_details = Some(value);
967 self
968 }
969
970 pub fn on_accept(mut self, value: DragTargetAccept<T>) -> Self {
972 self.on_accept = Some(value);
973 self
974 }
975
976 pub fn on_accept_with_details(mut self, value: DragTargetAcceptWithDetails<T>) -> Self {
978 self.on_accept_with_details = Some(value);
979 self
980 }
981
982 pub fn on_leave(mut self, value: DragTargetLeave<T>) -> Self {
984 self.on_leave = Some(value);
985 self
986 }
987
988 pub fn on_move(mut self, value: DragTargetMove<T>) -> Self {
990 self.on_move = Some(value);
991 self
992 }
993
994 pub fn hit_test_behavior(mut self, value: HitTestBehavior) -> Self {
996 self.hit_test_behavior = value;
997 self
998 }
999}
1000
1001impl<T: 'static> StatefulWidget for DragTarget<T> {
1002 type State = DragTargetState<T>;
1003
1004 fn key(&self) -> Option<&KeyRef> {
1005 self.key.as_ref()
1006 }
1007
1008 fn create_state(&self) -> Self::State {
1009 debug_assert!(
1010 self.on_will_accept.is_none() || self.on_will_accept_with_details.is_none(),
1011 "Don't pass both acceptance callbacks"
1012 );
1013 DragTargetState {
1014 state: StateData::new(),
1015 candidate_avatars: Vec::new(),
1016 rejected_avatars: Vec::new(),
1017 }
1018 }
1019}
1020
1021pub struct DragTargetState<T: 'static> {
1023 state: StateData<DragTarget<T>>,
1025
1026 candidate_avatars: Vec<Ref<DragAvatar>>,
1028
1029 rejected_avatars: Vec<Ref<DragAvatar>>,
1031}
1032
1033trait DragTargetHandler {
1035 fn id(&self) -> HandleId;
1036
1037 fn is_expected_data_type(&self, data: &Option<Rc<dyn Any>>) -> bool;
1038
1039 fn did_enter(&self, app: &mut App, avatar: Handle<DragAvatar>) -> bool;
1040
1041 fn did_leave(&self, app: &mut App, avatar: Handle<DragAvatar>);
1042
1043 fn did_drop(&self, app: &mut App, avatar: Handle<DragAvatar>);
1044
1045 fn did_move(&self, app: &mut App, avatar: Handle<DragAvatar>);
1046}
1047
1048struct DragTargetMetadata {
1050 handler: Rc<dyn DragTargetHandler>,
1052}
1053
1054impl<T: 'static> DragTargetHandler for Ref<DragTargetState<T>> {
1055 fn id(&self) -> HandleId {
1056 self.into()
1057 }
1058
1059 fn is_expected_data_type(&self, data: &Option<Rc<dyn Any>>) -> bool {
1060 data.as_ref().is_none_or(|data| data.is::<T>())
1061 }
1062
1063 fn did_enter(&self, app: &mut App, avatar: Handle<DragAvatar>) -> bool {
1064 debug_assert!(
1065 !app.get(self)
1066 .candidate_avatars
1067 .iter()
1068 .any(|kept| kept == avatar)
1069 );
1070 debug_assert!(
1071 !app.get(self)
1072 .rejected_avatars
1073 .iter()
1074 .any(|kept| kept == avatar)
1075 );
1076 let data = app
1077 .get(avatar)
1078 .data
1079 .clone()
1080 .map(|data| data.downcast::<T>().unwrap());
1081 let widget = self.widget(app);
1082 let accepted = match (
1083 widget.on_will_accept.clone(),
1084 widget.on_will_accept_with_details.clone(),
1085 ) {
1086 (None, None) => true,
1087 (Some(callback), _) => callback(app, data.clone()),
1088 (_, Some(callback)) => data.is_some_and(|data| {
1089 callback(
1090 app,
1091 DragTargetDetails {
1092 data,
1093 offset: app.get(avatar).last_offset.unwrap(),
1094 },
1095 )
1096 }),
1097 };
1098 let kept = avatar.keep(app);
1099 self.set_state(app, |state| {
1100 if accepted {
1101 state.candidate_avatars.push(kept)
1102 } else {
1103 state.rejected_avatars.push(kept)
1104 }
1105 });
1106 accepted
1107 }
1108
1109 fn did_leave(&self, app: &mut App, avatar: Handle<DragAvatar>) {
1110 if !self.mounted(app) {
1111 return;
1112 }
1113 self.set_state(app, |state| {
1114 state
1115 .candidate_avatars
1116 .retain(|candidate| candidate != avatar);
1117 state
1118 .rejected_avatars
1119 .retain(|candidate| candidate != avatar);
1120 });
1121 if let Some(callback) = self.widget(app).on_leave.clone() {
1122 let data = app
1123 .get(avatar)
1124 .data
1125 .clone()
1126 .map(|data| data.downcast::<T>().unwrap());
1127 callback(app, data);
1128 }
1129 }
1130
1131 fn did_drop(&self, app: &mut App, avatar: Handle<DragAvatar>) {
1132 debug_assert!(
1133 app.get(self)
1134 .candidate_avatars
1135 .iter()
1136 .any(|kept| kept == avatar)
1137 );
1138 if !self.mounted(app) {
1139 return;
1140 }
1141 self.set_state(app, |state| {
1142 state
1143 .candidate_avatars
1144 .retain(|candidate| candidate != avatar)
1145 });
1146 if let Some(data) = app.get(avatar).data.clone() {
1147 let data = data.downcast::<T>().unwrap();
1148 if let Some(callback) = self.widget(app).on_accept.clone() {
1149 callback(app, data.clone());
1150 }
1151 if let Some(callback) = self.widget(app).on_accept_with_details.clone() {
1152 callback(
1153 app,
1154 DragTargetDetails {
1155 data,
1156 offset: app.get(avatar).last_offset.unwrap(),
1157 },
1158 );
1159 }
1160 }
1161 }
1162
1163 fn did_move(&self, app: &mut App, avatar: Handle<DragAvatar>) {
1164 if !self.mounted(app) {
1165 return;
1166 }
1167 if let Some(data) = app.get(avatar).data.clone()
1168 && let Some(callback) = self.widget(app).on_move.clone()
1169 {
1170 callback(
1171 app,
1172 DragTargetDetails {
1173 data: data.downcast::<T>().unwrap(),
1174 offset: app.get(avatar).last_offset.unwrap(),
1175 },
1176 );
1177 }
1178 }
1179}
1180
1181impl<T: 'static> State for DragTargetState<T> {
1182 type Widget = DragTarget<T>;
1183 crate::state_accessors!();
1184
1185 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1186 let state = app.get(self);
1187 let candidates = state
1188 .candidate_avatars
1189 .iter()
1190 .map(|avatar| {
1191 app.get(avatar)
1192 .data
1193 .clone()
1194 .map(|data| data.downcast::<T>().unwrap())
1195 })
1196 .collect();
1197 let rejected = state
1198 .rejected_avatars
1199 .iter()
1200 .map(|avatar| app.get(avatar).data.clone())
1201 .collect();
1202 let builder = self.widget(app).builder.clone();
1203 let child = builder(app, context, candidates, rejected);
1204 MetaData::new()
1205 .meta_data(Rc::new(DragTargetMetadata {
1206 handler: Rc::new(self.keep(app)),
1207 }))
1208 .behavior(self.widget(app).hit_test_behavior)
1209 .child(child)
1210 .into_widget()
1211 }
1212}
1213
1214#[derive(Clone, Copy, PartialEq, Eq)]
1216enum DragEndKind {
1217 Dropped,
1218 Canceled,
1219}
1220
1221type OnDragEnd = Rc<dyn Fn(&mut App, Velocity, Offset, bool)>;
1223
1224struct DragAvatar {
1226 data: Option<Rc<dyn Any>>,
1228
1229 axis: Option<Axis>,
1231
1232 drag_start_point: Offset,
1234
1235 feedback: WidgetRef,
1237
1238 feedback_offset: Offset,
1240
1241 on_drag_update: DragUpdateCallback,
1243
1244 on_drag_end: OnDragEnd,
1246
1247 overlay_state: Handle<OverlayState>,
1249
1250 ignoring_feedback_semantics: bool,
1252
1253 ignoring_feedback_pointer: bool,
1255
1256 view_id: ViewId,
1258
1259 active_target: Option<Rc<DragTargetMetadata>>,
1261
1262 entered_targets: Vec<Rc<DragTargetMetadata>>,
1264
1265 position: Offset,
1267
1268 last_offset: Option<Offset>,
1270
1271 overlay_offset: Offset,
1273
1274 entry: Option<Ref<OverlayEntry>>,
1276}
1277
1278impl DragAvatar {
1279 #[allow(clippy::too_many_arguments)]
1281 fn new(
1282 app: &mut App,
1283 overlay_state: Handle<OverlayState>,
1284 data: Option<Rc<dyn Any>>,
1285 axis: Option<Axis>,
1286 initial_position: Offset,
1287 drag_start_point: Offset,
1288 feedback: WidgetRef,
1289 feedback_offset: Offset,
1290 ignoring_feedback_semantics: bool,
1291 ignoring_feedback_pointer: bool,
1292 view_id: ViewId,
1293 on_drag_update: DragUpdateCallback,
1294 on_drag_end: OnDragEnd,
1295 ) -> Ref<Self> {
1296 let avatar = app.create(Self {
1297 data,
1298 axis,
1299 drag_start_point,
1300 feedback,
1301 feedback_offset,
1302 on_drag_update,
1303 on_drag_end,
1304 overlay_state,
1305 ignoring_feedback_semantics,
1306 ignoring_feedback_pointer,
1307 view_id,
1308 active_target: None,
1309 entered_targets: Vec::new(),
1310 position: initial_position,
1311 last_offset: None,
1312 overlay_offset: Offset::ZERO,
1313 entry: None,
1314 });
1315 let kept = avatar.clone();
1319 let entry = OverlayEntry::new(
1320 app,
1321 Rc::new(move |app, context| kept.build(app, context)),
1322 false,
1323 false,
1324 false,
1325 );
1326 app.get_mut(&avatar).entry = Some(entry.clone());
1327 overlay_state.insert(app, entry, None, None);
1328 avatar.update_drag(app, initial_position);
1329 avatar
1330 }
1331
1332 fn update_drag(self: Handle<Self>, app: &mut App, global_position: Offset) {
1334 let state = app.get(self);
1335 let (overlay, anchor, feedback_offset, view_id) = (
1336 state.overlay_state,
1337 state.drag_start_point,
1338 state.feedback_offset,
1339 state.view_id,
1340 );
1341 app.get_mut(self).last_offset = Some(global_position - anchor);
1342 if overlay.mounted(app) {
1343 let render_box = overlay
1344 .context(app)
1345 .find_render_object(app)
1346 .unwrap()
1347 .as_box()
1348 .unwrap();
1349 app.get_mut(self).overlay_offset =
1350 render_box.global_to_local(app, global_position, None) - anchor;
1351 app.get(self).entry.handle().unwrap().mark_needs_build(app);
1352 }
1353 let mut result = HitTestResult::new();
1354 GestureBinding::instance(app).hit_test_in_view(
1355 app,
1356 &mut result,
1357 global_position + feedback_offset,
1358 view_id,
1359 );
1360 let mut targets = Vec::new();
1361 for entry in result.path() {
1362 let Some(hit) = (entry.target() as &dyn Any).downcast_ref::<BoxHitTestEntry>() else {
1363 continue;
1364 };
1365 let Some(render) = hit.target().as_object().downcast::<RenderMetaData>(app) else {
1366 continue;
1367 };
1368 let Some(metadata) = render
1369 .meta_data(app)
1370 .and_then(|value| value.downcast::<DragTargetMetadata>().ok())
1371 else {
1372 continue;
1373 };
1374 if metadata.handler.is_expected_data_type(&app.get(self).data) {
1375 targets.push(metadata);
1376 }
1377 }
1378 let state = app.get(self);
1379 let lists_match = !state.entered_targets.is_empty()
1380 && targets.len() >= state.entered_targets.len()
1381 && targets
1382 .iter()
1383 .zip(&state.entered_targets)
1384 .all(|(a, b)| a.handler.id() == b.handler.id());
1385 if lists_match
1386 && (state.active_target.is_some() || targets.len() == state.entered_targets.len())
1387 {
1388 for target in state.entered_targets.clone() {
1389 target.handler.did_move(app, self);
1390 }
1391 return;
1392 }
1393 self.leave_all_entered(app);
1394 let mut active = None;
1395 for target in targets {
1396 app.get_mut(self).entered_targets.push(target.clone());
1397 if target.handler.did_enter(app, self) {
1398 active = Some(target);
1399 break;
1400 }
1401 }
1402 for target in app.get(self).entered_targets.clone() {
1403 target.handler.did_move(app, self);
1404 }
1405 app.get_mut(self).active_target = active;
1406 }
1407
1408 fn leave_all_entered(self: Handle<Self>, app: &mut App) {
1410 for target in app.get(self).entered_targets.clone() {
1411 target.handler.did_leave(app, self);
1412 }
1413 app.get_mut(self).entered_targets.clear();
1414 }
1415
1416 fn finish_drag(self: Handle<Self>, app: &mut App, kind: DragEndKind, velocity: Velocity) {
1418 let target = app.get(self).active_target.clone();
1419 let mut accepted = false;
1420 if kind == DragEndKind::Dropped
1421 && let Some(target) = target
1422 {
1423 target.handler.did_drop(app, self);
1424 accepted = true;
1425 app.get_mut(self)
1426 .entered_targets
1427 .retain(|entry| entry.handler.id() != target.handler.id());
1428 }
1429 self.leave_all_entered(app);
1430 app.get_mut(self).active_target = None;
1431 let entry = app.get_mut(self).entry.take().unwrap();
1432 entry.remove(app);
1433 entry.dispose(app);
1434 let callback = app.get(self).on_drag_end.clone();
1435 callback(app, velocity, app.get(self).last_offset.unwrap(), accepted);
1436 }
1437
1438 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1440 let state = app.get(self);
1441 Positioned::new(
1442 ExcludeSemantics::new()
1443 .excluding(state.ignoring_feedback_semantics)
1444 .child(
1445 IgnorePointer::new()
1446 .ignoring(state.ignoring_feedback_pointer)
1447 .child(state.feedback.clone()),
1448 ),
1449 )
1450 .left(state.overlay_offset.dx())
1451 .top(state.overlay_offset.dy())
1452 .into_widget()
1453 }
1454
1455 fn restrict_axis(self: Handle<Self>, app: &App, offset: Offset) -> Offset {
1457 match app.get(self).axis {
1458 Some(Axis::Horizontal) => Offset::new(offset.dx(), 0.0),
1459 Some(Axis::Vertical) => Offset::new(0.0, offset.dy()),
1460 None => offset,
1461 }
1462 }
1463}
1464
1465impl DragObject for DragAvatar {
1466 fn update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
1467 let old_position = app.get(self).position;
1468 let position = old_position + self.restrict_axis(app, details.delta);
1469 app.get_mut(self).position = position;
1470 self.update_drag(app, position);
1471 if position != old_position {
1472 let callback = app.get(self).on_drag_update.clone();
1473 callback(app, details);
1474 }
1475 }
1476
1477 fn end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
1478 let velocity = Velocity::new(self.restrict_axis(app, details.velocity.pixels_per_second));
1479 self.finish_drag(app, DragEndKind::Dropped, velocity);
1480 }
1481
1482 fn cancel(self: Handle<Self>, app: &mut App) {
1483 self.finish_drag(app, DragEndKind::Canceled, Velocity::ZERO);
1484 }
1485}