Skip to main content

sui_widgets/
drag_drop.rs

1use std::{path::PathBuf, sync::Arc};
2
3use sui_core::{
4    DragDropScope, DragEvent, DragEventKind, DragPayload, DragPreview, DragSessionId, DropEffect,
5    Event, Point, PointerButton, PointerEventKind, Rect, Size, Vector, WindowEvent,
6};
7use sui_layout::Constraints;
8use sui_runtime::{
9    ArrangeCtx, EventCtx, LayerOptions, MeasureCtx, OverlayDismissPolicy, OverlayFocusBehavior,
10    OverlayKind, OverlayOptions, PaintBoundaryMode, PaintCtx, SemanticsCtx, SingleChild,
11    StackSurfaceOptions, Widget, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
12};
13use sui_scene::{Border, LayerCompositionMode};
14
15use crate::DefaultTheme;
16
17const DEFAULT_DRAG_THRESHOLD: f32 = 4.0;
18
19type PayloadFactory = Box<dyn FnMut() -> DragPayload>;
20type DragStartCallback = Box<dyn FnMut(&mut EventCtx, &DragPreview)>;
21type DragEndCallback = Box<dyn FnMut(&mut EventCtx, &DragEvent)>;
22type DropAcceptCallback = Box<dyn FnMut(&DragEvent) -> DropEffect>;
23type DropCallback = Box<dyn FnMut(&mut EventCtx, &DragEvent)>;
24type HoverCallback = Box<dyn FnMut(bool)>;
25
26pub struct DragDropHost {
27    scope: DragDropScope,
28    child: SingleChild,
29    overlay: SingleChild,
30    external_hovered: Vec<PathBuf>,
31    on_external_hover: Option<Box<dyn FnMut(&mut EventCtx, &[PathBuf])>>,
32    on_external_drop: Option<Box<dyn FnMut(&mut EventCtx, PathBuf)>>,
33    on_external_cancel: Option<Box<dyn FnMut(&mut EventCtx)>>,
34}
35
36impl DragDropHost {
37    pub fn new<W>(scope: DragDropScope, child: W) -> Self
38    where
39        W: Widget + 'static,
40    {
41        Self {
42            overlay: SingleChild::new(DragPreviewOverlay::new(scope.clone())),
43            scope,
44            child: SingleChild::new(child),
45            external_hovered: Vec::new(),
46            on_external_hover: None,
47            on_external_drop: None,
48            on_external_cancel: None,
49        }
50    }
51
52    pub fn scope(&self) -> &DragDropScope {
53        &self.scope
54    }
55
56    pub fn child(&self) -> &WidgetPod {
57        self.child.child()
58    }
59
60    pub fn child_mut(&mut self) -> &mut WidgetPod {
61        self.child.child_mut()
62    }
63
64    pub fn external_hovered_files(&self) -> &[PathBuf] {
65        &self.external_hovered
66    }
67
68    pub fn on_external_file_hover<F>(mut self, callback: F) -> Self
69    where
70        F: FnMut(&mut EventCtx, &[PathBuf]) + 'static,
71    {
72        self.on_external_hover = Some(Box::new(callback));
73        self
74    }
75
76    pub fn on_external_file_drop<F>(mut self, callback: F) -> Self
77    where
78        F: FnMut(&mut EventCtx, PathBuf) + 'static,
79    {
80        self.on_external_drop = Some(Box::new(callback));
81        self
82    }
83
84    pub fn on_external_file_hover_cancelled<F>(mut self, callback: F) -> Self
85    where
86        F: FnMut(&mut EventCtx) + 'static,
87    {
88        self.on_external_cancel = Some(Box::new(callback));
89        self
90    }
91}
92
93impl Widget for DragDropHost {
94    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
95        match event {
96            Event::Window(WindowEvent::ExternalFileHovered(path)) => {
97                if !self.external_hovered.contains(path) {
98                    self.external_hovered.push(path.clone());
99                }
100                if let Some(callback) = &mut self.on_external_hover {
101                    callback(ctx, &self.external_hovered);
102                }
103                ctx.request_paint();
104                ctx.request_semantics();
105                ctx.set_handled();
106            }
107            Event::Window(WindowEvent::ExternalFileHoverCancelled) => {
108                self.external_hovered.clear();
109                if let Some(callback) = &mut self.on_external_cancel {
110                    callback(ctx);
111                }
112                ctx.request_paint();
113                ctx.request_semantics();
114                ctx.set_handled();
115            }
116            Event::Window(WindowEvent::ExternalFileDropped(path)) => {
117                self.external_hovered.retain(|hovered| hovered != path);
118                if let Some(callback) = &mut self.on_external_drop {
119                    callback(ctx, path.clone());
120                }
121                ctx.request_paint();
122                ctx.request_semantics();
123                ctx.set_handled();
124            }
125            _ => {}
126        }
127    }
128
129    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
130        let size = self.child.measure(ctx, constraints);
131        self.overlay.measure(ctx, Constraints::tight(size));
132        size
133    }
134
135    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
136        self.child.arrange(ctx, bounds);
137        self.overlay.arrange(ctx, bounds);
138    }
139
140    fn paint(&self, ctx: &mut PaintCtx) {
141        self.child.paint(ctx);
142        self.overlay.paint(ctx);
143    }
144
145    fn semantics(&self, ctx: &mut SemanticsCtx) {
146        self.child.semantics(ctx);
147    }
148
149    fn overlay_options(&self) -> Option<OverlayOptions> {
150        self.scope.active_drag().is_some().then_some(
151            OverlayOptions::new(OverlayKind::DragPreview)
152                .dismiss(OverlayDismissPolicy::NONE)
153                .focus(OverlayFocusBehavior::NONE),
154        )
155    }
156
157    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
158        self.child.visit_children(visitor);
159        self.overlay.visit_children(visitor);
160    }
161
162    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
163        self.child.visit_children_mut(visitor);
164        self.overlay.visit_children_mut(visitor);
165    }
166}
167
168struct DragPreviewOverlay {
169    scope: DragDropScope,
170}
171
172impl DragPreviewOverlay {
173    fn new(scope: DragDropScope) -> Self {
174        Self { scope }
175    }
176}
177
178impl Widget for DragPreviewOverlay {
179    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
180        constraints.clamp(Size::new(
181            constraints.max.width.max(0.0),
182            constraints.max.height.max(0.0),
183        ))
184    }
185
186    fn paint(&self, ctx: &mut PaintCtx) {
187        let Some(active) = self.scope.active_drag() else {
188            return;
189        };
190
191        let label = drag_preview_label(&active);
192        let width = ((label.chars().count() as f32 * 7.0) + 24.0).clamp(48.0, 260.0);
193        let height = 30.0;
194        let offset = Vector::new(12.0, 12.0);
195        let bounds = ctx.bounds();
196        let x = (active.position.x + offset.x).min((bounds.max_x() - width).max(bounds.x()));
197        let y = (active.position.y + offset.y).min((bounds.max_y() - height).max(bounds.y()));
198        let rect = Rect::new(x.max(bounds.x()), y.max(bounds.y()), width, height);
199        let theme = DefaultTheme::default();
200        let mut text_style = theme.body_text_style();
201        text_style.font_size = text_style.font_size.min(13.0);
202        text_style.line_height = text_style.line_height.min(18.0);
203        text_style.color = theme.palette.text;
204
205        ctx.fill_rrect_bordered(
206            rect,
207            [7.0; 4],
208            theme.palette.surface_raised.with_alpha(0.96),
209            Border {
210                width: 1.0,
211                color: theme.palette.border.with_alpha(0.72),
212            },
213        );
214
215        let text_rect = Rect::new(rect.x() + 12.0, rect.y() + 5.0, rect.width() - 24.0, 20.0);
216        ctx.push_clip_rect(text_rect);
217        ctx.draw_text(text_rect, label, text_style);
218        ctx.pop_clip();
219    }
220
221    fn layer_options(&self) -> LayerOptions {
222        LayerOptions {
223            paint_boundary: PaintBoundaryMode::Explicit,
224            composition_mode: LayerCompositionMode::Overlay,
225        }
226    }
227
228    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
229        Some(StackSurfaceOptions {
230            transient: true,
231            hit_test: false,
232            ..StackSurfaceOptions::default()
233        })
234    }
235}
236
237pub struct Draggable {
238    scope: DragDropScope,
239    child: SingleChild,
240    payload: PayloadFactory,
241    allowed_effect: DropEffect,
242    preview_label: Option<String>,
243    threshold: f32,
244    press: Option<DragPress>,
245    active_session: Option<DragSessionId>,
246    on_drag_start: Option<DragStartCallback>,
247    on_drag_end: Option<DragEndCallback>,
248}
249
250#[derive(Debug, Clone, Copy)]
251struct DragPress {
252    pointer_id: u64,
253    start_position: Point,
254}
255
256impl Draggable {
257    pub fn new<W>(child: W) -> Self
258    where
259        W: Widget + 'static,
260    {
261        Self {
262            scope: DragDropScope::new(),
263            child: SingleChild::new(child),
264            payload: Box::new(|| DragPayload::text("")),
265            allowed_effect: DropEffect::Move,
266            preview_label: None,
267            threshold: DEFAULT_DRAG_THRESHOLD,
268            press: None,
269            active_session: None,
270            on_drag_start: None,
271            on_drag_end: None,
272        }
273    }
274
275    pub fn scope(mut self, scope: DragDropScope) -> Self {
276        self.scope = scope;
277        self
278    }
279
280    pub fn payload<F>(mut self, payload: F) -> Self
281    where
282        F: FnMut() -> DragPayload + 'static,
283    {
284        self.payload = Box::new(payload);
285        self
286    }
287
288    pub fn effect(mut self, effect: DropEffect) -> Self {
289        self.allowed_effect = effect;
290        self
291    }
292
293    pub fn preview_label(mut self, label: impl Into<String>) -> Self {
294        self.preview_label = Some(label.into());
295        self
296    }
297
298    pub fn threshold(mut self, threshold: f32) -> Self {
299        self.threshold = threshold.max(0.0);
300        self
301    }
302
303    pub fn on_drag_start<F>(mut self, callback: F) -> Self
304    where
305        F: FnMut(&mut EventCtx, &DragPreview) + 'static,
306    {
307        self.on_drag_start = Some(Box::new(callback));
308        self
309    }
310
311    pub fn on_drag_end<F>(mut self, callback: F) -> Self
312    where
313        F: FnMut(&mut EventCtx, &DragEvent) + 'static,
314    {
315        self.on_drag_end = Some(Box::new(callback));
316        self
317    }
318
319    pub fn scope_ref(&self) -> &DragDropScope {
320        &self.scope
321    }
322
323    pub fn child(&self) -> &WidgetPod {
324        self.child.child()
325    }
326
327    pub fn child_mut(&mut self) -> &mut WidgetPod {
328        self.child.child_mut()
329    }
330
331    fn start_drag(&mut self, ctx: &mut EventCtx, press: DragPress, position: Point) {
332        let payload = (self.payload)();
333        let preview_label = self.preview_label.clone();
334        let session_id = ctx.begin_drag(
335            self.scope.id(),
336            press.pointer_id,
337            press.start_position,
338            payload.clone(),
339            self.allowed_effect,
340            preview_label.clone(),
341        );
342        let preview = DragPreview {
343            session_id,
344            scope_id: self.scope.id(),
345            pointer_id: press.pointer_id,
346            source: ctx.widget_id(),
347            position,
348            start_position: press.start_position,
349            payload,
350            allowed_effect: self.allowed_effect,
351            preview_label: preview_label.map(Arc::from),
352        };
353        self.scope.set_active_drag(preview.clone());
354        self.active_session = Some(session_id);
355        if let Some(callback) = &mut self.on_drag_start {
356            callback(ctx, &preview);
357        }
358        ctx.request_paint();
359    }
360}
361
362impl Widget for Draggable {
363    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
364        match event {
365            Event::Pointer(pointer)
366                if pointer.kind == PointerEventKind::Down
367                    && pointer.button == Some(PointerButton::Primary)
368                    && ctx.bounds().contains(pointer.position)
369                    && ctx.phase() != sui_runtime::EventPhase::Capture =>
370            {
371                self.press = Some(DragPress {
372                    pointer_id: pointer.pointer_id,
373                    start_position: pointer.position,
374                });
375                self.active_session = None;
376                ctx.request_pointer_capture(pointer.pointer_id);
377                ctx.set_handled();
378            }
379            Event::Pointer(pointer)
380                if pointer.kind == PointerEventKind::Move
381                    && self
382                        .press
383                        .is_some_and(|press| press.pointer_id == pointer.pointer_id) =>
384            {
385                if let Some(session_id) = self.active_session {
386                    self.scope
387                        .update_drag_position(session_id, pointer.position);
388                    ctx.request_paint();
389                    ctx.set_handled();
390                    return;
391                }
392
393                let press = self.press.unwrap();
394                let delta = pointer.position - press.start_position;
395                let distance_sq = (delta.x * delta.x) + (delta.y * delta.y);
396                if distance_sq >= self.threshold * self.threshold {
397                    self.start_drag(ctx, press, pointer.position);
398                    ctx.set_handled();
399                }
400            }
401            Event::Pointer(pointer)
402                if matches!(
403                    pointer.kind,
404                    PointerEventKind::Up | PointerEventKind::Cancel
405                ) && self
406                    .press
407                    .is_some_and(|press| press.pointer_id == pointer.pointer_id) =>
408            {
409                if self.active_session.is_none() {
410                    self.press = None;
411                }
412                ctx.release_pointer_capture(pointer.pointer_id);
413                ctx.set_handled();
414            }
415            Event::Drag(drag)
416                if drag.kind == DragEventKind::End
417                    && self.active_session == Some(drag.session_id) =>
418            {
419                self.scope.finish_drag(drag.session_id);
420                self.press = None;
421                self.active_session = None;
422                if let Some(callback) = &mut self.on_drag_end {
423                    callback(ctx, drag);
424                }
425                ctx.request_paint();
426                ctx.set_handled();
427            }
428            _ => {}
429        }
430    }
431
432    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
433        self.child.measure(ctx, constraints)
434    }
435
436    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
437        self.child.arrange(ctx, bounds);
438    }
439
440    fn paint(&self, ctx: &mut PaintCtx) {
441        self.child.paint(ctx);
442    }
443
444    fn semantics(&self, ctx: &mut SemanticsCtx) {
445        self.child.semantics(ctx);
446    }
447
448    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
449        self.child.visit_children(visitor);
450    }
451
452    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
453        self.child.visit_children_mut(visitor);
454    }
455}
456
457pub struct DropTarget {
458    scope: DragDropScope,
459    child: SingleChild,
460    accept: DropAcceptCallback,
461    hovered: bool,
462    on_drop: Option<DropCallback>,
463    on_hover_change: Option<HoverCallback>,
464}
465
466impl DropTarget {
467    pub fn new<W>(child: W) -> Self
468    where
469        W: Widget + 'static,
470    {
471        Self {
472            scope: DragDropScope::new(),
473            child: SingleChild::new(child),
474            accept: Box::new(|_| DropEffect::Copy),
475            hovered: false,
476            on_drop: None,
477            on_hover_change: None,
478        }
479    }
480
481    pub fn scope(mut self, scope: DragDropScope) -> Self {
482        self.scope = scope;
483        self
484    }
485
486    pub fn accept<F>(mut self, accept: F) -> Self
487    where
488        F: FnMut(&DragEvent) -> DropEffect + 'static,
489    {
490        self.accept = Box::new(accept);
491        self
492    }
493
494    pub fn on_drop<F>(mut self, callback: F) -> Self
495    where
496        F: FnMut(&mut EventCtx, &DragEvent) + 'static,
497    {
498        self.on_drop = Some(Box::new(callback));
499        self
500    }
501
502    pub fn on_hover_change<F>(mut self, callback: F) -> Self
503    where
504        F: FnMut(bool) + 'static,
505    {
506        self.on_hover_change = Some(Box::new(callback));
507        self
508    }
509
510    pub fn is_hovered(&self) -> bool {
511        self.hovered
512    }
513
514    pub fn scope_ref(&self) -> &DragDropScope {
515        &self.scope
516    }
517
518    pub fn child(&self) -> &WidgetPod {
519        self.child.child()
520    }
521
522    pub fn child_mut(&mut self) -> &mut WidgetPod {
523        self.child.child_mut()
524    }
525
526    fn set_hovered(&mut self, ctx: &mut EventCtx, hovered: bool) {
527        if self.hovered == hovered {
528            return;
529        }
530        self.hovered = hovered;
531        if let Some(callback) = &mut self.on_hover_change {
532            callback(hovered);
533        }
534        ctx.request_paint();
535        ctx.request_semantics();
536    }
537}
538
539impl Widget for DropTarget {
540    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
541        let Event::Drag(drag) = event else {
542            return;
543        };
544        if drag.scope_id != self.scope.id() {
545            return;
546        }
547
548        match drag.kind {
549            DragEventKind::Enter | DragEventKind::Over => {
550                let effect = (self.accept)(drag);
551                if effect.is_some() {
552                    ctx.accept_drop(effect);
553                    self.set_hovered(ctx, true);
554                } else {
555                    self.set_hovered(ctx, false);
556                }
557            }
558            DragEventKind::Leave => {
559                self.set_hovered(ctx, false);
560            }
561            DragEventKind::Drop if drag.target == Some(ctx.widget_id()) => {
562                if let Some(callback) = &mut self.on_drop {
563                    callback(ctx, drag);
564                }
565                self.set_hovered(ctx, false);
566                ctx.set_handled();
567            }
568            _ => {}
569        }
570    }
571
572    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
573        self.child.measure(ctx, constraints)
574    }
575
576    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
577        self.child.arrange(ctx, bounds);
578    }
579
580    fn paint(&self, ctx: &mut PaintCtx) {
581        self.child.paint(ctx);
582    }
583
584    fn semantics(&self, ctx: &mut SemanticsCtx) {
585        self.child.semantics(ctx);
586    }
587
588    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
589        self.child.visit_children(visitor);
590    }
591
592    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
593        self.child.visit_children_mut(visitor);
594    }
595}
596
597fn drag_preview_label(active: &DragPreview) -> String {
598    if let Some(label) = &active.preview_label {
599        return label.to_string();
600    }
601
602    match &active.payload {
603        DragPayload::Text(text) if !text.is_empty() => text.clone(),
604        DragPayload::Image { .. } => "Image".to_string(),
605        DragPayload::Custom { kind, .. } => kind.to_string(),
606        DragPayload::Text(_) => "Dragging".to_string(),
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use std::{cell::RefCell, rc::Rc};
613
614    use super::*;
615    use crate::{SizedBox, Stack};
616    use sui_core::{
617        DragOutcome, Modifiers, PointerButtons, PointerEvent, PointerKind, Result, WindowId,
618    };
619    use sui_runtime::{Application, Runtime, WindowBuilder};
620
621    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
622        let mut buttons = PointerButtons::NONE;
623        if pressed {
624            buttons.insert(PointerButton::Primary);
625        }
626
627        Event::Pointer(PointerEvent {
628            pointer_id: 1,
629            kind,
630            position,
631            delta: Vector::ZERO,
632            scroll_delta: None,
633            button: Some(PointerButton::Primary),
634            buttons,
635            modifiers: Modifiers::NONE,
636            pointer_kind: PointerKind::Mouse,
637            is_primary: true,
638        })
639    }
640
641    fn build_runtime<W>(root: W) -> (Runtime, WindowId)
642    where
643        W: Widget + 'static,
644    {
645        let runtime = Application::new()
646            .window(WindowBuilder::new().title("Drag Drop").root(root))
647            .build()
648            .unwrap();
649        let window_id = runtime.window_ids()[0];
650        (runtime, window_id)
651    }
652
653    #[test]
654    fn draggable_starts_after_threshold_and_drops_typed_payload() -> Result<()> {
655        let scope = DragDropScope::new();
656        let starts = Rc::new(RefCell::new(0));
657        let ends = Rc::new(RefCell::new(Vec::new()));
658        let drops = Rc::new(RefCell::new(Vec::new()));
659        let hover_changes = Rc::new(RefCell::new(Vec::new()));
660
661        let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
662            .scope(scope.clone())
663            .payload(|| DragPayload::custom("asset", 42_u32))
664            .effect(DropEffect::Move)
665            .preview_label("Asset")
666            .on_drag_start({
667                let starts = Rc::clone(&starts);
668                move |_, _| *starts.borrow_mut() += 1
669            })
670            .on_drag_end({
671                let ends = Rc::clone(&ends);
672                move |_, drag| ends.borrow_mut().push(drag.outcome)
673            });
674
675        let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
676            .scope(scope.clone())
677            .accept(|drag| {
678                if drag.payload.custom_data::<u32>() == Some(&42) {
679                    DropEffect::Move
680                } else {
681                    DropEffect::None
682                }
683            })
684            .on_drop({
685                let drops = Rc::clone(&drops);
686                move |_, drag| {
687                    drops
688                        .borrow_mut()
689                        .push(*drag.payload.custom_data::<u32>().unwrap());
690                }
691            })
692            .on_hover_change({
693                let hover_changes = Rc::clone(&hover_changes);
694                move |hovered| hover_changes.borrow_mut().push(hovered)
695            });
696
697        let root = DragDropHost::new(
698            scope.clone(),
699            Stack::horizontal().with_child(source).with_child(target),
700        );
701        let (mut runtime, window_id) = build_runtime(root);
702        let _ = runtime.render(window_id)?;
703
704        runtime.handle_event(
705            window_id,
706            primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
707        )?;
708        runtime.handle_event(
709            window_id,
710            primary_pointer(PointerEventKind::Move, Point::new(12.0, 20.0), true),
711        )?;
712
713        assert_eq!(*starts.borrow(), 0);
714        assert!(scope.active_drag().is_none());
715
716        runtime.handle_event(
717            window_id,
718            primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
719        )?;
720        assert_eq!(*starts.borrow(), 1);
721        assert!(scope.active_drag().is_some());
722
723        runtime.handle_event(
724            window_id,
725            primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
726        )?;
727
728        assert_eq!(&*drops.borrow(), &[42]);
729        assert!(matches!(
730            ends.borrow().as_slice(),
731            [Some(DragOutcome::Dropped {
732                effect: DropEffect::Move,
733                ..
734            })]
735        ));
736        assert_eq!(&*hover_changes.borrow(), &[true, false]);
737        assert!(scope.active_drag().is_none());
738        Ok(())
739    }
740
741    #[test]
742    fn nearest_accepting_drop_target_receives_drop() -> Result<()> {
743        let scope = DragDropScope::new();
744        let inner_drops = Rc::new(RefCell::new(0));
745        let outer_drops = Rc::new(RefCell::new(0));
746
747        let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
748            .scope(scope.clone())
749            .payload(|| DragPayload::text("item"));
750
751        let inner = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
752            .scope(scope.clone())
753            .accept(|_| DropEffect::Copy)
754            .on_drop({
755                let inner_drops = Rc::clone(&inner_drops);
756                move |_, _| *inner_drops.borrow_mut() += 1
757            });
758        let outer = DropTarget::new(inner)
759            .scope(scope.clone())
760            .accept(|_| DropEffect::Copy)
761            .on_drop({
762                let outer_drops = Rc::clone(&outer_drops);
763                move |_, _| *outer_drops.borrow_mut() += 1
764            });
765
766        let root = DragDropHost::new(
767            scope,
768            Stack::horizontal().with_child(source).with_child(outer),
769        );
770        let (mut runtime, window_id) = build_runtime(root);
771        let _ = runtime.render(window_id)?;
772
773        runtime.handle_event(
774            window_id,
775            primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
776        )?;
777        runtime.handle_event(
778            window_id,
779            primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
780        )?;
781        runtime.handle_event(
782            window_id,
783            primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
784        )?;
785
786        assert_eq!(*inner_drops.borrow(), 1);
787        assert_eq!(*outer_drops.borrow(), 0);
788        Ok(())
789    }
790
791    #[test]
792    fn cross_scope_target_ignores_drag_session() -> Result<()> {
793        let source_scope = DragDropScope::new();
794        let target_scope = DragDropScope::new();
795        let ends = Rc::new(RefCell::new(Vec::new()));
796        let drops = Rc::new(RefCell::new(0));
797
798        let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
799            .scope(source_scope.clone())
800            .payload(|| DragPayload::text("item"))
801            .on_drag_end({
802                let ends = Rc::clone(&ends);
803                move |_, drag| ends.borrow_mut().push(drag.outcome)
804            });
805        let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
806            .scope(target_scope)
807            .accept(|_| DropEffect::Copy)
808            .on_drop({
809                let drops = Rc::clone(&drops);
810                move |_, _| *drops.borrow_mut() += 1
811            });
812
813        let root = DragDropHost::new(
814            source_scope,
815            Stack::horizontal().with_child(source).with_child(target),
816        );
817        let (mut runtime, window_id) = build_runtime(root);
818        let _ = runtime.render(window_id)?;
819
820        runtime.handle_event(
821            window_id,
822            primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
823        )?;
824        runtime.handle_event(
825            window_id,
826            primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
827        )?;
828        runtime.handle_event(
829            window_id,
830            primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
831        )?;
832
833        assert_eq!(*drops.borrow(), 0);
834        assert_eq!(&*ends.borrow(), &[Some(DragOutcome::Cancelled)]);
835        Ok(())
836    }
837
838    #[test]
839    fn drag_drop_host_preview_layer_is_not_hit_tested() -> Result<()> {
840        let scope = DragDropScope::new();
841        let starts = Rc::new(RefCell::new(0));
842        let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
843            .scope(scope.clone())
844            .payload(|| DragPayload::text("item"))
845            .on_drag_start({
846                let starts = Rc::clone(&starts);
847                move |_, _| *starts.borrow_mut() += 1
848            });
849        let root = DragDropHost::new(scope, source);
850        let (mut runtime, window_id) = build_runtime(root);
851
852        let output = runtime.render(window_id)?;
853        let mut preview_layer = None;
854        output.frame.scene.visit_layers(&mut |layer| {
855            if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
856                preview_layer = Some((layer.widget_id(), layer.descriptor.hit_test));
857            }
858        });
859
860        assert!(matches!(preview_layer, Some((_, false))));
861
862        runtime.handle_event(
863            window_id,
864            primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
865        )?;
866        runtime.handle_event(
867            window_id,
868            primary_pointer(PointerEventKind::Move, Point::new(24.0, 20.0), true),
869        )?;
870
871        assert_eq!(*starts.borrow(), 1);
872        Ok(())
873    }
874
875    #[test]
876    fn drag_drop_host_routes_platform_file_hover_drop_and_cancel() -> Result<()> {
877        let hovered = Rc::new(RefCell::new(Vec::<Vec<PathBuf>>::new()));
878        let dropped = Rc::new(RefCell::new(Vec::<PathBuf>::new()));
879        let cancelled = Rc::new(RefCell::new(0));
880        let root = DragDropHost::new(
881            DragDropScope::new(),
882            SizedBox::new().width(160.0).height(80.0),
883        )
884        .on_external_file_hover({
885            let hovered = Rc::clone(&hovered);
886            move |_, paths| hovered.borrow_mut().push(paths.to_vec())
887        })
888        .on_external_file_drop({
889            let dropped = Rc::clone(&dropped);
890            move |_, path| dropped.borrow_mut().push(path)
891        })
892        .on_external_file_hover_cancelled({
893            let cancelled = Rc::clone(&cancelled);
894            move |_| *cancelled.borrow_mut() += 1
895        });
896        let (mut runtime, window_id) = build_runtime(root);
897        let _ = runtime.render(window_id)?;
898        let first = PathBuf::from("/tmp/first.txt");
899        let second = PathBuf::from("/tmp/second.png");
900
901        runtime.handle_event(
902            window_id,
903            Event::Window(WindowEvent::ExternalFileHovered(first.clone())),
904        )?;
905        runtime.handle_event(
906            window_id,
907            Event::Window(WindowEvent::ExternalFileHovered(second.clone())),
908        )?;
909        runtime.handle_event(
910            window_id,
911            Event::Window(WindowEvent::ExternalFileDropped(first.clone())),
912        )?;
913        runtime.handle_event(
914            window_id,
915            Event::Window(WindowEvent::ExternalFileHoverCancelled),
916        )?;
917
918        assert_eq!(
919            hovered.borrow().as_slice(),
920            &[vec![first.clone()], vec![first.clone(), second]]
921        );
922        assert_eq!(dropped.borrow().as_slice(), &[first]);
923        assert_eq!(*cancelled.borrow(), 1);
924        Ok(())
925    }
926
927    #[test]
928    fn drag_payload_custom_equality_uses_stable_kind() {
929        let left = DragPayload::custom("asset", 1_u32);
930        let right = DragPayload::custom("asset", 2_u32);
931        let other = DragPayload::custom("other", 1_u32);
932
933        assert_eq!(left, right);
934        assert_ne!(left, other);
935        assert_eq!(left.custom_data::<u32>(), Some(&1));
936        assert_eq!(right.custom_data::<u32>(), Some(&2));
937    }
938}