1use std::{
2 cell::{Cell, RefCell},
3 path::PathBuf,
4 rc::Rc,
5 sync::Arc,
6};
7
8use sui_core::{
9 DragDropScope, DragEvent, DragEventKind, DragPayload, DragPreview, DragSessionId, DropEffect,
10 DropEffects, Event, InvalidationKind, InvalidationRequest, InvalidationTarget, Point,
11 PointerButton, PointerEventKind, Rect, Size, Vector, WindowEvent,
12};
13use sui_layout::Constraints;
14use sui_runtime::{
15 ArrangeCtx, EventCtx, LayerOptions, MeasureCtx, OverlayDismissPolicy, OverlayFocusBehavior,
16 OverlayKind, OverlayOptions, PaintBoundaryMode, PaintCtx, SemanticsCtx, SingleChild,
17 StackSurfaceOptions, Widget, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
18};
19use sui_scene::{Border, LayerCompositionMode};
20
21use crate::DefaultTheme;
22
23const DEFAULT_DRAG_THRESHOLD: f32 = 4.0;
24
25type PayloadFactory = Box<dyn FnMut() -> DragPayload>;
26type DragStartCallback = Box<dyn FnMut(&mut EventCtx, &DragPreview)>;
27type DragEndCallback = Box<dyn FnMut(&mut EventCtx, &DragEvent)>;
28type DropAcceptCallback = Box<dyn FnMut(&DragEvent) -> DropEffect>;
29type DropCallback = Box<dyn FnMut(&mut EventCtx, &DragEvent)>;
30type HoverCallback = Box<dyn FnMut(bool)>;
31type HoverCallbackWithCtx = Box<dyn FnMut(&mut EventCtx, bool)>;
32type HoverStateCallback = Box<dyn FnMut(DropHover)>;
33type HoverStateCallbackWithCtx = Box<dyn FnMut(&mut EventCtx, DropHover)>;
34type ThemeReader = Rc<dyn Fn() -> DefaultTheme>;
35type PreviewBuilder = Box<dyn FnMut(&DragPreview) -> Option<Box<dyn Widget>>>;
36
37const DRAG_PREVIEW_OFFSET: Vector = Vector::new(12.0, 12.0);
39
40#[derive(Default)]
41struct DragPreviewThemeSource {
42 theme: DefaultTheme,
43 reader: Option<ThemeReader>,
44}
45
46impl DragPreviewThemeSource {
47 fn resolve(&self) -> DefaultTheme {
48 self.reader
49 .as_ref()
50 .map(|reader| reader())
51 .unwrap_or(self.theme)
52 }
53}
54
55pub struct DragDropHost {
56 scope: DragDropScope,
57 child: SingleChild,
58 overlay: SingleChild,
59 preview_theme: Rc<RefCell<DragPreviewThemeSource>>,
60 preview_builder: Option<PreviewBuilder>,
61 preview_session: Option<DragSessionId>,
63 preview: Option<SingleChild>,
64 widget_preview_session: Rc<Cell<Option<DragSessionId>>>,
66 external_hovered: Vec<PathBuf>,
67 on_external_hover: Option<Box<dyn FnMut(&mut EventCtx, &[PathBuf])>>,
68 on_external_drop: Option<Box<dyn FnMut(&mut EventCtx, PathBuf)>>,
69 on_external_cancel: Option<Box<dyn FnMut(&mut EventCtx)>>,
70}
71
72impl DragDropHost {
73 pub fn new<W>(scope: DragDropScope, child: W) -> Self
74 where
75 W: Widget + 'static,
76 {
77 let preview_theme = Rc::new(RefCell::new(DragPreviewThemeSource::default()));
78 let widget_preview_session = Rc::new(Cell::new(None));
79 Self {
80 overlay: SingleChild::new(DragPreviewOverlay::new(
81 scope.clone(),
82 Rc::clone(&preview_theme),
83 Rc::clone(&widget_preview_session),
84 )),
85 scope,
86 child: SingleChild::new(child),
87 preview_theme,
88 preview_builder: None,
89 preview_session: None,
90 preview: None,
91 widget_preview_session,
92 external_hovered: Vec::new(),
93 on_external_hover: None,
94 on_external_drop: None,
95 on_external_cancel: None,
96 }
97 }
98
99 pub fn scope(&self) -> &DragDropScope {
100 &self.scope
101 }
102
103 pub fn child_pod(&self) -> &WidgetPod {
104 self.child.child()
105 }
106
107 pub fn child_mut(&mut self) -> &mut WidgetPod {
108 self.child.child_mut()
109 }
110
111 pub fn external_hovered_files(&self) -> &[PathBuf] {
112 &self.external_hovered
113 }
114
115 pub fn theme(self, theme: DefaultTheme) -> Self {
117 {
118 let mut source = self.preview_theme.borrow_mut();
119 source.theme = theme;
120 source.reader = None;
121 }
122 self
123 }
124
125 pub fn theme_when<F>(self, reader: F) -> Self
127 where
128 F: Fn() -> DefaultTheme + 'static,
129 {
130 self.preview_theme.borrow_mut().reader = Some(Rc::new(reader));
131 self
132 }
133
134 pub fn preview<F>(mut self, builder: F) -> Self
140 where
141 F: FnMut(&DragPreview) -> Option<Box<dyn Widget>> + 'static,
142 {
143 self.preview_builder = Some(Box::new(builder));
144 self
145 }
146
147 fn preview_is_current(&self) -> bool {
149 self.preview.is_some()
150 && self
151 .scope
152 .active_drag()
153 .is_some_and(|active| Some(active.session_id) == self.preview_session)
154 }
155
156 fn follow_drag(&mut self, ctx: &mut EventCtx, drag: &DragEvent) {
157 if drag.scope_id != self.scope.id()
158 || !matches!(drag.kind, DragEventKind::Enter | DragEventKind::Over)
159 {
160 return;
161 }
162 self.scope
165 .update_drag_position(drag.session_id, drag.position);
166 ctx.request_paint();
167 if self.preview_session == Some(drag.session_id) {
168 if let Some(preview) = &self.preview {
170 ctx.request(InvalidationRequest::new(
171 InvalidationTarget::Widget(preview.child().id()),
172 InvalidationKind::Arrange,
173 ));
174 }
175 return;
176 }
177 self.preview_session = Some(drag.session_id);
178 let widget = match (&mut self.preview_builder, self.scope.active_drag()) {
179 (Some(builder), Some(active)) if active.session_id == drag.session_id => {
180 builder(&active)
181 }
182 _ => None,
183 };
184 self.widget_preview_session
185 .set(widget.as_ref().map(|_| drag.session_id));
186 self.preview = widget.map(|widget| {
187 SingleChild::new(DragPreviewSurface {
188 scope: self.scope.clone(),
189 session_id: drag.session_id,
190 child: SingleChild::from_pod(WidgetPod::new_boxed(widget)),
191 })
192 });
193 ctx.request_measure();
194 ctx.request_arrange();
195 }
196
197 pub fn on_external_file_hover<F>(mut self, callback: F) -> Self
198 where
199 F: FnMut(&mut EventCtx, &[PathBuf]) + 'static,
200 {
201 self.on_external_hover = Some(Box::new(callback));
202 self
203 }
204
205 pub fn on_external_file_drop<F>(mut self, callback: F) -> Self
206 where
207 F: FnMut(&mut EventCtx, PathBuf) + 'static,
208 {
209 self.on_external_drop = Some(Box::new(callback));
210 self
211 }
212
213 pub fn on_external_file_hover_cancelled<F>(mut self, callback: F) -> Self
214 where
215 F: FnMut(&mut EventCtx) + 'static,
216 {
217 self.on_external_cancel = Some(Box::new(callback));
218 self
219 }
220}
221
222impl Widget for DragDropHost {
223 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
224 match event {
225 Event::Drag(drag) if ctx.phase() != sui_runtime::EventPhase::Capture => {
226 self.follow_drag(ctx, drag);
227 }
228 Event::Window(WindowEvent::ExternalFileHovered(path)) => {
229 if !self.external_hovered.contains(path) {
230 self.external_hovered.push(path.clone());
231 }
232 if let Some(callback) = &mut self.on_external_hover {
233 callback(ctx, &self.external_hovered);
234 }
235 ctx.request_paint();
236 ctx.request_semantics();
237 ctx.set_handled();
238 }
239 Event::Window(WindowEvent::ExternalFileHoverCancelled) => {
240 self.external_hovered.clear();
241 if let Some(callback) = &mut self.on_external_cancel {
242 callback(ctx);
243 }
244 ctx.request_paint();
245 ctx.request_semantics();
246 ctx.set_handled();
247 }
248 Event::Window(WindowEvent::ExternalFileDropped(path)) => {
249 self.external_hovered.retain(|hovered| hovered != path);
250 if let Some(callback) = &mut self.on_external_drop {
251 callback(ctx, path.clone());
252 }
253 ctx.request_paint();
254 ctx.request_semantics();
255 ctx.set_handled();
256 }
257 _ => {}
258 }
259 }
260
261 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
262 if !self.preview_is_current() {
263 self.preview = None;
264 }
265 let size = self.child.measure(ctx, constraints);
266 self.overlay.measure(ctx, Constraints::tight(size));
267 if let Some(preview) = &mut self.preview {
268 preview.measure(ctx, Constraints::tight(size));
269 }
270 size
271 }
272
273 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
274 self.child.arrange(ctx, bounds);
275 self.overlay.arrange(ctx, bounds);
276 if let Some(preview) = &mut self.preview {
277 preview.arrange(ctx, bounds);
278 }
279 }
280
281 fn paint(&self, ctx: &mut PaintCtx) {
282 self.child.paint(ctx);
283 self.overlay.paint(ctx);
284 if self.preview_is_current()
285 && let Some(preview) = &self.preview
286 {
287 preview.paint(ctx);
288 }
289 }
290
291 fn semantics(&self, ctx: &mut SemanticsCtx) {
292 self.child.semantics(ctx);
293 }
294
295 fn overlay_options(&self) -> Option<OverlayOptions> {
296 self.scope.active_drag().is_some().then_some(
297 OverlayOptions::new(OverlayKind::DragPreview)
298 .dismiss(OverlayDismissPolicy::NONE)
299 .focus(OverlayFocusBehavior::NONE),
300 )
301 }
302
303 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
304 self.child.visit_children(visitor);
305 self.overlay.visit_children(visitor);
306 if self.preview_is_current()
307 && let Some(preview) = &self.preview
308 {
309 preview.visit_children(visitor);
310 }
311 }
312
313 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
314 self.child.visit_children_mut(visitor);
315 self.overlay.visit_children_mut(visitor);
316 if self.preview_is_current()
317 && let Some(preview) = &mut self.preview
318 {
319 preview.visit_children_mut(visitor);
320 }
321 }
322}
323
324fn drag_preview_origin(pointer: Point, size: Size, bounds: Rect) -> Point {
327 let x = (pointer.x + DRAG_PREVIEW_OFFSET.x).min((bounds.max_x() - size.width).max(bounds.x()));
328 let y = (pointer.y + DRAG_PREVIEW_OFFSET.y).min((bounds.max_y() - size.height).max(bounds.y()));
329 Point::new(x.max(bounds.x()), y.max(bounds.y()))
330}
331
332struct DragPreviewSurface {
336 scope: DragDropScope,
337 session_id: DragSessionId,
338 child: SingleChild,
339}
340
341impl Widget for DragPreviewSurface {
342 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
343 self.child.measure(ctx, constraints.loosen());
344 constraints.clamp(Size::new(
345 constraints.max.width.max(0.0),
346 constraints.max.height.max(0.0),
347 ))
348 }
349
350 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
351 let size = self.child.child().measured_size();
352 let pointer = self
353 .scope
354 .active_drag()
355 .filter(|active| active.session_id == self.session_id)
356 .map_or(bounds.origin, |active| active.position);
357 self.child.arrange(
358 ctx,
359 Rect::from_origin_size(drag_preview_origin(pointer, size, bounds), size),
360 );
361 }
362
363 fn paint(&self, ctx: &mut PaintCtx) {
364 if self
365 .scope
366 .active_drag()
367 .is_some_and(|active| active.session_id == self.session_id)
368 {
369 self.child.paint(ctx);
370 }
371 }
372
373 fn layer_options(&self) -> LayerOptions {
374 LayerOptions {
375 paint_boundary: PaintBoundaryMode::Explicit,
376 composition_mode: LayerCompositionMode::Overlay,
377 }
378 }
379
380 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
381 Some(StackSurfaceOptions {
382 transient: true,
383 hit_test: false,
384 ..StackSurfaceOptions::default()
385 })
386 }
387
388 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
389 self.child.visit_children(visitor);
390 }
391
392 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
393 self.child.visit_children_mut(visitor);
394 }
395}
396
397struct DragPreviewOverlay {
398 scope: DragDropScope,
399 theme: Rc<RefCell<DragPreviewThemeSource>>,
400 widget_preview_session: Rc<Cell<Option<DragSessionId>>>,
401}
402
403impl DragPreviewOverlay {
404 fn new(
405 scope: DragDropScope,
406 theme: Rc<RefCell<DragPreviewThemeSource>>,
407 widget_preview_session: Rc<Cell<Option<DragSessionId>>>,
408 ) -> Self {
409 Self {
410 scope,
411 theme,
412 widget_preview_session,
413 }
414 }
415
416 fn resolved_theme(&self) -> DefaultTheme {
417 self.theme.borrow().resolve()
418 }
419}
420
421impl Widget for DragPreviewOverlay {
422 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
423 constraints.clamp(Size::new(
424 constraints.max.width.max(0.0),
425 constraints.max.height.max(0.0),
426 ))
427 }
428
429 fn paint(&self, ctx: &mut PaintCtx) {
430 let Some(active) = self.scope.active_drag() else {
431 return;
432 };
433 if self.widget_preview_session.get() == Some(active.session_id) {
434 return;
435 }
436
437 let label = drag_preview_label(&active);
438 let theme = self.resolved_theme();
439 let text_style = drag_preview_text_style(theme);
440 let estimated_character_width = text_style.font_size * 0.54;
441 let width =
442 ((label.chars().count() as f32 * estimated_character_width) + 24.0).clamp(48.0, 260.0);
443 let height = text_style.line_height + 12.0;
444 let rect = Rect::from_origin_size(
445 drag_preview_origin(active.position, Size::new(width, height), ctx.bounds()),
446 Size::new(width, height),
447 );
448
449 ctx.fill_rrect_bordered(
450 rect,
451 [7.0; 4],
452 theme.palette.surface_raised.with_alpha(0.96),
453 Border {
454 width: 1.0,
455 color: theme.palette.border.with_alpha(0.72),
456 },
457 );
458
459 let text_rect = Rect::new(
460 rect.x() + 12.0,
461 rect.y() + 6.0,
462 rect.width() - 24.0,
463 text_style.line_height,
464 );
465 ctx.push_clip_rect(text_rect);
466 ctx.draw_text(text_rect, label, text_style);
467 ctx.pop_clip();
468 }
469
470 fn layer_options(&self) -> LayerOptions {
471 LayerOptions {
472 paint_boundary: PaintBoundaryMode::Explicit,
473 composition_mode: LayerCompositionMode::Overlay,
474 }
475 }
476
477 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
478 Some(StackSurfaceOptions {
479 transient: true,
480 hit_test: false,
481 ..StackSurfaceOptions::default()
482 })
483 }
484}
485
486fn drag_preview_text_style(theme: DefaultTheme) -> sui_text::TextStyle {
487 let mut style = theme.text_style(theme.palette.text);
488 style.font_size = theme.text.sm.size.max(1.0);
489 style.line_height = theme.text.sm.line_height.max(1.0);
490 style
491}
492
493pub struct Draggable {
494 scope: DragDropScope,
495 child: SingleChild,
496 payload: PayloadFactory,
497 allowed_effects: DropEffects,
498 preview_label: Option<String>,
499 threshold: f32,
500 press: Option<DragPress>,
501 active_session: Option<DragSessionId>,
502 on_drag_start: Option<DragStartCallback>,
503 on_drag_end: Option<DragEndCallback>,
504}
505
506#[derive(Debug, Clone, Copy)]
507struct DragPress {
508 pointer_id: u64,
509 start_position: Point,
510}
511
512impl Draggable {
513 pub fn new<W>(child: W) -> Self
514 where
515 W: Widget + 'static,
516 {
517 Self {
518 scope: DragDropScope::new(),
519 child: SingleChild::new(child),
520 payload: Box::new(|| DragPayload::text("")),
521 allowed_effects: DropEffects::MOVE,
522 preview_label: None,
523 threshold: DEFAULT_DRAG_THRESHOLD,
524 press: None,
525 active_session: None,
526 on_drag_start: None,
527 on_drag_end: None,
528 }
529 }
530
531 pub fn scope(mut self, scope: DragDropScope) -> Self {
532 self.scope = scope;
533 self
534 }
535
536 pub fn payload<F>(mut self, payload: F) -> Self
537 where
538 F: FnMut() -> DragPayload + 'static,
539 {
540 self.payload = Box::new(payload);
541 self
542 }
543
544 pub fn effect(mut self, effect: DropEffect) -> Self {
546 self.allowed_effects = effect.into();
547 self
548 }
549
550 pub fn effects(mut self, effects: DropEffects) -> Self {
554 self.allowed_effects = effects;
555 self
556 }
557
558 pub fn preview_label(mut self, label: impl Into<String>) -> Self {
559 self.preview_label = Some(label.into());
560 self
561 }
562
563 pub fn threshold(mut self, threshold: f32) -> Self {
564 self.threshold = threshold.max(0.0);
565 self
566 }
567
568 pub fn on_drag_start<F>(mut self, callback: F) -> Self
569 where
570 F: FnMut(&mut EventCtx, &DragPreview) + 'static,
571 {
572 self.on_drag_start = Some(Box::new(callback));
573 self
574 }
575
576 pub fn on_drag_end<F>(mut self, callback: F) -> Self
577 where
578 F: FnMut(&mut EventCtx, &DragEvent) + 'static,
579 {
580 self.on_drag_end = Some(Box::new(callback));
581 self
582 }
583
584 pub fn scope_ref(&self) -> &DragDropScope {
585 &self.scope
586 }
587
588 pub fn child_pod(&self) -> &WidgetPod {
589 self.child.child()
590 }
591
592 pub fn child_mut(&mut self) -> &mut WidgetPod {
593 self.child.child_mut()
594 }
595
596 fn start_drag(&mut self, ctx: &mut EventCtx, press: DragPress, position: Point) {
597 let payload = (self.payload)();
598 let preview_label = self.preview_label.clone();
599 let session_id = ctx.begin_drag(
600 self.scope.id(),
601 press.pointer_id,
602 press.start_position,
603 payload.clone(),
604 self.allowed_effects,
605 preview_label.clone(),
606 );
607 let preview = DragPreview {
608 session_id,
609 scope_id: self.scope.id(),
610 pointer_id: press.pointer_id,
611 source: ctx.widget_id(),
612 position,
613 start_position: press.start_position,
614 payload,
615 allowed_effect: self.allowed_effects.default_effect(),
616 allowed_effects: self.allowed_effects,
617 preview_label: preview_label.map(Arc::from),
618 };
619 self.scope.set_active_drag(preview.clone());
620 self.active_session = Some(session_id);
621 if let Some(callback) = &mut self.on_drag_start {
622 callback(ctx, &preview);
623 }
624 ctx.request_paint();
625 }
626}
627
628impl Widget for Draggable {
629 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
630 match event {
631 Event::Pointer(pointer)
632 if pointer.kind == PointerEventKind::Down
633 && pointer.button == Some(PointerButton::Primary)
634 && ctx.bounds().contains(pointer.position)
635 && ctx.phase() != sui_runtime::EventPhase::Capture =>
636 {
637 self.press = Some(DragPress {
638 pointer_id: pointer.pointer_id,
639 start_position: pointer.position,
640 });
641 self.active_session = None;
642 ctx.request_pointer_capture(pointer.pointer_id);
643 ctx.set_handled();
644 }
645 Event::Pointer(pointer)
646 if pointer.kind == PointerEventKind::Move
647 && self
648 .press
649 .is_some_and(|press| press.pointer_id == pointer.pointer_id) =>
650 {
651 if let Some(session_id) = self.active_session {
652 self.scope
653 .update_drag_position(session_id, pointer.position);
654 ctx.request_paint();
655 ctx.set_handled();
656 return;
657 }
658
659 let press = self.press.unwrap();
660 let delta = pointer.position - press.start_position;
661 let distance_sq = (delta.x * delta.x) + (delta.y * delta.y);
662 if distance_sq >= self.threshold * self.threshold {
663 self.start_drag(ctx, press, pointer.position);
664 ctx.set_handled();
665 }
666 }
667 Event::Pointer(pointer)
668 if matches!(
669 pointer.kind,
670 PointerEventKind::Up | PointerEventKind::Cancel
671 ) && self
672 .press
673 .is_some_and(|press| press.pointer_id == pointer.pointer_id) =>
674 {
675 if self.active_session.is_none() {
676 self.press = None;
677 }
678 ctx.release_pointer_capture(pointer.pointer_id);
679 ctx.set_handled();
680 }
681 Event::Drag(drag)
682 if drag.kind == DragEventKind::End
683 && self.active_session == Some(drag.session_id) =>
684 {
685 self.scope.finish_drag(drag.session_id);
686 self.press = None;
687 self.active_session = None;
688 if let Some(callback) = &mut self.on_drag_end {
689 callback(ctx, drag);
690 }
691 ctx.request_paint();
692 ctx.set_handled();
693 }
694 _ => {}
695 }
696 }
697
698 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
699 self.child.measure(ctx, constraints)
700 }
701
702 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
703 self.child.arrange(ctx, bounds);
704 }
705
706 fn paint(&self, ctx: &mut PaintCtx) {
707 self.child.paint(ctx);
708 }
709
710 fn semantics(&self, ctx: &mut SemanticsCtx) {
711 self.child.semantics(ctx);
712 }
713
714 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
715 self.child.visit_children(visitor);
716 }
717
718 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
719 self.child.visit_children_mut(visitor);
720 }
721}
722
723#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
725pub enum DropHover {
726 #[default]
727 Idle,
728 Accepting(DropEffect),
730 Refusing,
732}
733
734impl DropHover {
735 pub const fn is_accepting(self) -> bool {
736 matches!(self, Self::Accepting(_))
737 }
738}
739
740pub struct DropTarget {
741 scope: DragDropScope,
742 child: SingleChild,
743 accept: DropAcceptCallback,
744 hover: DropHover,
745 on_drop: Option<DropCallback>,
746 on_hover_change: Option<HoverCallback>,
747 on_hover_change_with_ctx: Option<HoverCallbackWithCtx>,
748 on_hover_state: Option<HoverStateCallback>,
749 on_hover_state_with_ctx: Option<HoverStateCallbackWithCtx>,
750}
751
752impl DropTarget {
753 pub fn new<W>(child: W) -> Self
758 where
759 W: Widget + 'static,
760 {
761 Self {
762 scope: DragDropScope::new(),
763 child: SingleChild::new(child),
764 accept: Box::new(|_| DropEffect::Copy),
765 hover: DropHover::Idle,
766 on_drop: None,
767 on_hover_change: None,
768 on_hover_change_with_ctx: None,
769 on_hover_state: None,
770 on_hover_state_with_ctx: None,
771 }
772 }
773
774 pub fn scope(mut self, scope: DragDropScope) -> Self {
775 self.scope = scope;
776 self
777 }
778
779 pub fn accept<F>(mut self, accept: F) -> Self
780 where
781 F: FnMut(&DragEvent) -> DropEffect + 'static,
782 {
783 self.accept = Box::new(accept);
784 self
785 }
786
787 pub fn on_drop<F>(mut self, callback: F) -> Self
788 where
789 F: FnMut(&mut EventCtx, &DragEvent) + 'static,
790 {
791 self.on_drop = Some(Box::new(callback));
792 self
793 }
794
795 pub fn on_hover_change<F>(mut self, callback: F) -> Self
796 where
797 F: FnMut(bool) + 'static,
798 {
799 self.on_hover_change = Some(Box::new(callback));
800 self
801 }
802
803 pub fn on_hover_change_with_ctx<F>(mut self, callback: F) -> Self
805 where
806 F: FnMut(&mut EventCtx, bool) + 'static,
807 {
808 self.on_hover_change_with_ctx = Some(Box::new(callback));
809 self
810 }
811
812 pub fn on_hover_state<F>(mut self, callback: F) -> Self
816 where
817 F: FnMut(DropHover) + 'static,
818 {
819 self.on_hover_state = Some(Box::new(callback));
820 self
821 }
822
823 pub fn on_hover_state_with_ctx<F>(mut self, callback: F) -> Self
825 where
826 F: FnMut(&mut EventCtx, DropHover) + 'static,
827 {
828 self.on_hover_state_with_ctx = Some(Box::new(callback));
829 self
830 }
831
832 pub fn is_hovered(&self) -> bool {
833 self.hover.is_accepting()
834 }
835
836 pub fn hover_state(&self) -> DropHover {
837 self.hover
838 }
839
840 pub fn scope_ref(&self) -> &DragDropScope {
841 &self.scope
842 }
843
844 pub fn child_pod(&self) -> &WidgetPod {
845 self.child.child()
846 }
847
848 pub fn child_mut(&mut self) -> &mut WidgetPod {
849 self.child.child_mut()
850 }
851
852 fn set_hover(&mut self, ctx: &mut EventCtx, hover: DropHover) {
853 if self.hover == hover {
854 return;
855 }
856 let was_hovered = self.hover.is_accepting();
857 self.hover = hover;
858 if let Some(callback) = &mut self.on_hover_state {
859 callback(hover);
860 }
861 if let Some(callback) = &mut self.on_hover_state_with_ctx {
862 callback(ctx, hover);
863 }
864 let accepting_changed = was_hovered != hover.is_accepting();
865 if accepting_changed && let Some(callback) = &mut self.on_hover_change {
866 callback(hover.is_accepting());
867 }
868 if accepting_changed && let Some(callback) = &mut self.on_hover_change_with_ctx {
869 callback(ctx, hover.is_accepting());
870 }
871 ctx.request_paint();
872 ctx.request_semantics();
873 }
874}
875
876impl Widget for DropTarget {
877 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
878 let Event::Drag(drag) = event else {
879 return;
880 };
881 if drag.scope_id != self.scope.id() {
882 return;
883 }
884
885 match drag.kind {
886 DragEventKind::Enter | DragEventKind::Over => {
887 let effect = (self.accept)(drag);
888 if effect.is_some() {
889 ctx.accept_drop(effect);
890 self.set_hover(ctx, DropHover::Accepting(effect));
891 } else {
892 self.set_hover(ctx, DropHover::Refusing);
893 }
894 }
895 DragEventKind::Leave => {
896 self.set_hover(ctx, DropHover::Idle);
897 }
898 DragEventKind::Drop if drag.target == Some(ctx.widget_id()) => {
899 if let Some(callback) = &mut self.on_drop {
900 callback(ctx, drag);
901 }
902 self.set_hover(ctx, DropHover::Idle);
903 ctx.set_handled();
904 }
905 _ => {}
906 }
907 }
908
909 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
910 self.child.measure(ctx, constraints)
911 }
912
913 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
914 self.child.arrange(ctx, bounds);
915 }
916
917 fn paint(&self, ctx: &mut PaintCtx) {
918 self.child.paint(ctx);
919 }
920
921 fn semantics(&self, ctx: &mut SemanticsCtx) {
922 self.child.semantics(ctx);
923 }
924
925 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
926 self.child.visit_children(visitor);
927 }
928
929 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
930 self.child.visit_children_mut(visitor);
931 }
932}
933
934fn drag_preview_label(active: &DragPreview) -> String {
935 if let Some(label) = &active.preview_label {
936 return label.to_string();
937 }
938
939 match &active.payload {
940 DragPayload::Text(text) if !text.is_empty() => text.clone(),
941 DragPayload::Image { .. } => "Image".to_string(),
942 DragPayload::Custom { kind, .. } => kind.to_string(),
943 DragPayload::Text(_) => "Dragging".to_string(),
944 }
945}
946
947#[cfg(test)]
948mod tests {
949 use std::{cell::RefCell, rc::Rc};
950
951 use super::*;
952 use crate::{Label, ScrollState, ScrollView, SizedBox, Stack, Surface, ThemeTextToken};
953 use sui_core::{
954 Color, DragOutcome, KeyState, KeyboardEvent, Modifiers, Path, PointerButtons, PointerEvent,
955 PointerKind, Result, WindowId,
956 };
957 use sui_runtime::{Application, FramePacing, Runtime, WindowBuilder};
958 use sui_scene::{Brush, SceneCommand};
959
960 fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
961 let mut buttons = PointerButtons::NONE;
962 if pressed {
963 buttons.insert(PointerButton::Primary);
964 }
965
966 Event::Pointer(PointerEvent {
967 pointer_id: 1,
968 kind,
969 position,
970 delta: Vector::ZERO,
971 scroll_delta: None,
972 button: Some(PointerButton::Primary),
973 buttons,
974 modifiers: Modifiers::NONE,
975 pointer_kind: PointerKind::Mouse,
976 is_primary: true,
977 })
978 }
979
980 fn build_runtime<W>(root: W) -> (Runtime, WindowId)
981 where
982 W: Widget + 'static,
983 {
984 let runtime = Application::new()
985 .window(WindowBuilder::new().title("Drag Drop").root(root))
986 .build()
987 .unwrap();
988 let window_id = runtime.window_ids()[0];
989 (runtime, window_id)
990 }
991
992 fn has_fill_color(output: &sui_runtime::RenderOutput, color: sui_core::Color) -> bool {
993 let mut found = false;
994 output
995 .frame
996 .scene
997 .visit_commands(&mut |command| match command {
998 SceneCommand::FillRect {
999 brush: Brush::Solid(fill),
1000 ..
1001 }
1002 | SceneCommand::FillPath {
1003 brush: Brush::Solid(fill),
1004 ..
1005 }
1006 | SceneCommand::FillRoundedRect {
1007 brush: Brush::Solid(fill),
1008 ..
1009 } if *fill == color => found = true,
1010 _ => {}
1011 });
1012 found
1013 }
1014
1015 fn has_stroke_color(output: &sui_runtime::RenderOutput, color: sui_core::Color) -> bool {
1016 let mut found = false;
1017 output
1018 .frame
1019 .scene
1020 .visit_commands(&mut |command| match command {
1021 SceneCommand::StrokeRect {
1022 brush: Brush::Solid(stroke),
1023 ..
1024 }
1025 | SceneCommand::StrokePath {
1026 brush: Brush::Solid(stroke),
1027 ..
1028 } if *stroke == color => found = true,
1029 _ => {}
1030 });
1031 found
1032 }
1033
1034 fn feedback_fill_precedes_text(
1035 output: &sui_runtime::RenderOutput,
1036 color: sui_core::Color,
1037 ) -> bool {
1038 let mut command_index = 0;
1039 let mut fill_index = None;
1040 let mut text_index = None;
1041 output.frame.scene.visit_commands(&mut |command| {
1042 match command {
1043 SceneCommand::FillRect {
1044 brush: Brush::Solid(fill),
1045 ..
1046 }
1047 | SceneCommand::FillPath {
1048 brush: Brush::Solid(fill),
1049 ..
1050 }
1051 | SceneCommand::FillRoundedRect {
1052 brush: Brush::Solid(fill),
1053 ..
1054 } if *fill == color => {
1055 fill_index.get_or_insert(command_index);
1056 }
1057 SceneCommand::DrawText(_)
1058 | SceneCommand::DrawShapedText(_)
1059 | SceneCommand::DrawShapedTextWindow(_) => {
1060 text_index.get_or_insert(command_index);
1061 }
1062 _ => {}
1063 };
1064 command_index += 1;
1065 });
1066 matches!((fill_index, text_index), (Some(fill), Some(text)) if fill < text)
1067 }
1068
1069 #[test]
1070 fn drag_preview_theme_tracks_static_and_dynamic_small_tokens() {
1071 let mut static_theme = DefaultTheme::default();
1072 static_theme.text.sm = ThemeTextToken {
1073 size: 17.0,
1074 line_height: 24.0,
1075 };
1076 let host = DragDropHost::new(
1077 DragDropScope::new(),
1078 SizedBox::new().width(80.0).height(40.0),
1079 )
1080 .theme(static_theme);
1081 let resolved = host.preview_theme.borrow().resolve();
1082 let style = drag_preview_text_style(resolved);
1083 assert_eq!(style.font_size, static_theme.text.sm.size);
1084 assert_eq!(style.line_height, static_theme.text.sm.line_height);
1085 assert_eq!(style.color, static_theme.palette.text);
1086
1087 let current = Rc::new(RefCell::new(DefaultTheme::default()));
1088 let dynamic_host = DragDropHost::new(
1089 DragDropScope::new(),
1090 SizedBox::new().width(80.0).height(40.0),
1091 )
1092 .theme_when({
1093 let current = Rc::clone(¤t);
1094 move || *current.borrow()
1095 });
1096 current.borrow_mut().text.sm = ThemeTextToken {
1097 size: 19.0,
1098 line_height: 27.0,
1099 };
1100
1101 let resolved = dynamic_host.preview_theme.borrow().resolve();
1102 let style = drag_preview_text_style(resolved);
1103 assert_eq!(style.font_size, 19.0);
1104 assert_eq!(style.line_height, 27.0);
1105 }
1106
1107 #[test]
1108 fn draggable_starts_after_threshold_and_drops_typed_payload() -> Result<()> {
1109 let scope = DragDropScope::new();
1110 let starts = Rc::new(RefCell::new(0));
1111 let ends = Rc::new(RefCell::new(Vec::new()));
1112 let drops = Rc::new(RefCell::new(Vec::new()));
1113 let hover_changes = Rc::new(RefCell::new(Vec::new()));
1114
1115 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1116 .scope(scope.clone())
1117 .payload(|| DragPayload::custom("asset", 42_u32))
1118 .effect(DropEffect::Move)
1119 .preview_label("Asset")
1120 .on_drag_start({
1121 let starts = Rc::clone(&starts);
1122 move |_, _| *starts.borrow_mut() += 1
1123 })
1124 .on_drag_end({
1125 let ends = Rc::clone(&ends);
1126 move |_, drag| ends.borrow_mut().push(drag.outcome)
1127 });
1128
1129 let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
1130 .scope(scope.clone())
1131 .accept(|drag| {
1132 if drag.payload.custom_data::<u32>() == Some(&42) {
1133 DropEffect::Move
1134 } else {
1135 DropEffect::None
1136 }
1137 })
1138 .on_drop({
1139 let drops = Rc::clone(&drops);
1140 move |_, drag| {
1141 drops
1142 .borrow_mut()
1143 .push(*drag.payload.custom_data::<u32>().unwrap());
1144 }
1145 })
1146 .on_hover_change({
1147 let hover_changes = Rc::clone(&hover_changes);
1148 move |hovered| hover_changes.borrow_mut().push(hovered)
1149 });
1150
1151 let root = DragDropHost::new(
1152 scope.clone(),
1153 Stack::horizontal().with_child(source).with_child(target),
1154 );
1155 let (mut runtime, window_id) = build_runtime(root);
1156 let _ = runtime.render(window_id)?;
1157
1158 runtime.handle_event(
1159 window_id,
1160 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1161 )?;
1162 runtime.handle_event(
1163 window_id,
1164 primary_pointer(PointerEventKind::Move, Point::new(12.0, 20.0), true),
1165 )?;
1166
1167 assert_eq!(*starts.borrow(), 0);
1168 assert!(scope.active_drag().is_none());
1169
1170 runtime.handle_event(
1171 window_id,
1172 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1173 )?;
1174 assert_eq!(*starts.borrow(), 1);
1175 assert!(scope.active_drag().is_some());
1176
1177 runtime.handle_event(
1178 window_id,
1179 primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
1180 )?;
1181
1182 assert_eq!(&*drops.borrow(), &[42]);
1183 assert!(matches!(
1184 ends.borrow().as_slice(),
1185 [Some(DragOutcome::Dropped {
1186 effect: DropEffect::Move,
1187 ..
1188 })]
1189 ));
1190 assert_eq!(&*hover_changes.borrow(), &[true, false]);
1191 assert!(scope.active_drag().is_none());
1192 Ok(())
1193 }
1194
1195 #[test]
1196 fn accepting_drop_target_has_no_default_hover_feedback() -> Result<()> {
1197 let scope = DragDropScope::new();
1198 let theme = DefaultTheme::default();
1199 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1200 .scope(scope.clone())
1201 .payload(|| DragPayload::text("item"))
1202 .effect(DropEffect::Copy)
1203 .preview_label("Item");
1204 let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
1205 .scope(scope.clone())
1206 .accept(|_| DropEffect::Copy);
1207 let root = DragDropHost::new(
1208 scope,
1209 Stack::horizontal().with_child(source).with_child(target),
1210 );
1211 let (mut runtime, window_id) = build_runtime(root);
1212
1213 let idle = runtime.render(window_id)?;
1214 assert!(!has_fill_color(&idle, theme.palette.accent_soft));
1215
1216 runtime.handle_event(
1217 window_id,
1218 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1219 )?;
1220 runtime.handle_event(
1221 window_id,
1222 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1223 )?;
1224
1225 let hovering = runtime.render(window_id)?;
1226 assert!(!has_fill_color(&hovering, theme.palette.accent_soft));
1227 Ok(())
1228 }
1229
1230 #[test]
1231 fn drop_target_hover_callback_can_drive_child_feedback_behind_content() -> Result<()> {
1232 let scope = DragDropScope::new();
1233 let theme = DefaultTheme::default();
1234 let hovered = Rc::new(RefCell::new(false));
1235 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1236 .scope(scope.clone())
1237 .payload(|| DragPayload::text("item"))
1238 .effect(DropEffect::Copy)
1239 .preview_label("Item");
1240 let surface_hovered = Rc::clone(&hovered);
1241 let target = DropTarget::new(
1242 Surface::panel(
1243 SizedBox::new()
1244 .width(80.0)
1245 .height(40.0)
1246 .child(Label::new("Drop here")),
1247 )
1248 .theme_when(move || {
1249 let mut resolved = theme;
1250 if *surface_hovered.borrow() {
1251 resolved.surfaces.panel = resolved.palette.accent_soft;
1252 resolved.surfaces.border = resolved.palette.accent_border_focus;
1253 }
1254 resolved
1255 }),
1256 )
1257 .scope(scope.clone())
1258 .accept(|_| DropEffect::Copy)
1259 .on_hover_change(move |value| *hovered.borrow_mut() = value);
1260 let root = DragDropHost::new(
1261 scope,
1262 Stack::horizontal().with_child(source).with_child(target),
1263 );
1264 let (mut runtime, window_id) = build_runtime(root);
1265 let idle = runtime.render(window_id)?;
1266 assert!(!has_fill_color(&idle, theme.palette.accent_soft));
1267
1268 runtime.handle_event(
1269 window_id,
1270 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1271 )?;
1272 runtime.handle_event(
1273 window_id,
1274 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1275 )?;
1276
1277 let hovering = runtime.render(window_id)?;
1278 assert!(has_fill_color(&hovering, theme.palette.accent_soft));
1279 assert!(has_stroke_color(
1280 &hovering,
1281 theme.palette.accent_border_focus
1282 ));
1283 assert!(feedback_fill_precedes_text(
1284 &hovering,
1285 theme.palette.accent_soft
1286 ));
1287 Ok(())
1288 }
1289
1290 #[test]
1291 fn nearest_accepting_drop_target_receives_drop() -> Result<()> {
1292 let scope = DragDropScope::new();
1293 let inner_drops = Rc::new(RefCell::new(0));
1294 let outer_drops = Rc::new(RefCell::new(0));
1295
1296 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1297 .scope(scope.clone())
1298 .payload(|| DragPayload::text("item"));
1299
1300 let inner = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
1301 .scope(scope.clone())
1302 .accept(|_| DropEffect::Copy)
1303 .on_drop({
1304 let inner_drops = Rc::clone(&inner_drops);
1305 move |_, _| *inner_drops.borrow_mut() += 1
1306 });
1307 let outer = DropTarget::new(inner)
1308 .scope(scope.clone())
1309 .accept(|_| DropEffect::Copy)
1310 .on_drop({
1311 let outer_drops = Rc::clone(&outer_drops);
1312 move |_, _| *outer_drops.borrow_mut() += 1
1313 });
1314
1315 let root = DragDropHost::new(
1316 scope,
1317 Stack::horizontal().with_child(source).with_child(outer),
1318 );
1319 let (mut runtime, window_id) = build_runtime(root);
1320 let _ = runtime.render(window_id)?;
1321
1322 runtime.handle_event(
1323 window_id,
1324 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1325 )?;
1326 runtime.handle_event(
1327 window_id,
1328 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1329 )?;
1330 runtime.handle_event(
1331 window_id,
1332 primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
1333 )?;
1334
1335 assert_eq!(*inner_drops.borrow(), 1);
1336 assert_eq!(*outer_drops.borrow(), 0);
1337 Ok(())
1338 }
1339
1340 #[test]
1341 fn cross_scope_target_ignores_drag_session() -> Result<()> {
1342 let source_scope = DragDropScope::new();
1343 let target_scope = DragDropScope::new();
1344 let ends = Rc::new(RefCell::new(Vec::new()));
1345 let drops = Rc::new(RefCell::new(0));
1346
1347 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1348 .scope(source_scope.clone())
1349 .payload(|| DragPayload::text("item"))
1350 .on_drag_end({
1351 let ends = Rc::clone(&ends);
1352 move |_, drag| ends.borrow_mut().push(drag.outcome)
1353 });
1354 let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
1355 .scope(target_scope)
1356 .accept(|_| DropEffect::Copy)
1357 .on_drop({
1358 let drops = Rc::clone(&drops);
1359 move |_, _| *drops.borrow_mut() += 1
1360 });
1361
1362 let root = DragDropHost::new(
1363 source_scope,
1364 Stack::horizontal().with_child(source).with_child(target),
1365 );
1366 let (mut runtime, window_id) = build_runtime(root);
1367 let _ = runtime.render(window_id)?;
1368
1369 runtime.handle_event(
1370 window_id,
1371 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1372 )?;
1373 runtime.handle_event(
1374 window_id,
1375 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1376 )?;
1377 runtime.handle_event(
1378 window_id,
1379 primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
1380 )?;
1381
1382 assert_eq!(*drops.borrow(), 0);
1383 assert_eq!(&*ends.borrow(), &[Some(DragOutcome::Cancelled)]);
1384 Ok(())
1385 }
1386
1387 #[test]
1388 fn drag_drop_host_preview_layer_is_not_hit_tested() -> Result<()> {
1389 let scope = DragDropScope::new();
1390 let starts = Rc::new(RefCell::new(0));
1391 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1392 .scope(scope.clone())
1393 .payload(|| DragPayload::text("item"))
1394 .on_drag_start({
1395 let starts = Rc::clone(&starts);
1396 move |_, _| *starts.borrow_mut() += 1
1397 });
1398 let root = DragDropHost::new(scope, source);
1399 let (mut runtime, window_id) = build_runtime(root);
1400
1401 let output = runtime.render(window_id)?;
1402 let mut preview_layer = None;
1403 output.frame.scene.visit_layers(&mut |layer| {
1404 if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
1405 preview_layer = Some((layer.widget_id(), layer.descriptor.hit_test));
1406 }
1407 });
1408
1409 assert!(matches!(preview_layer, Some((_, false))));
1410
1411 runtime.handle_event(
1412 window_id,
1413 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1414 )?;
1415 runtime.handle_event(
1416 window_id,
1417 primary_pointer(PointerEventKind::Move, Point::new(24.0, 20.0), true),
1418 )?;
1419
1420 assert_eq!(*starts.borrow(), 1);
1421 Ok(())
1422 }
1423
1424 #[test]
1425 fn drag_drop_host_routes_platform_file_hover_drop_and_cancel() -> Result<()> {
1426 let hovered = Rc::new(RefCell::new(Vec::<Vec<PathBuf>>::new()));
1427 let dropped = Rc::new(RefCell::new(Vec::<PathBuf>::new()));
1428 let cancelled = Rc::new(RefCell::new(0));
1429 let root = DragDropHost::new(
1430 DragDropScope::new(),
1431 SizedBox::new().width(160.0).height(80.0),
1432 )
1433 .on_external_file_hover({
1434 let hovered = Rc::clone(&hovered);
1435 move |_, paths| hovered.borrow_mut().push(paths.to_vec())
1436 })
1437 .on_external_file_drop({
1438 let dropped = Rc::clone(&dropped);
1439 move |_, path| dropped.borrow_mut().push(path)
1440 })
1441 .on_external_file_hover_cancelled({
1442 let cancelled = Rc::clone(&cancelled);
1443 move |_| *cancelled.borrow_mut() += 1
1444 });
1445 let (mut runtime, window_id) = build_runtime(root);
1446 let _ = runtime.render(window_id)?;
1447 let first = PathBuf::from("/tmp/first.txt");
1448 let second = PathBuf::from("/tmp/second.png");
1449
1450 runtime.handle_event(
1451 window_id,
1452 Event::Window(WindowEvent::ExternalFileHovered(first.clone())),
1453 )?;
1454 runtime.handle_event(
1455 window_id,
1456 Event::Window(WindowEvent::ExternalFileHovered(second.clone())),
1457 )?;
1458 runtime.handle_event(
1459 window_id,
1460 Event::Window(WindowEvent::ExternalFileDropped(first.clone())),
1461 )?;
1462 runtime.handle_event(
1463 window_id,
1464 Event::Window(WindowEvent::ExternalFileHoverCancelled),
1465 )?;
1466
1467 assert_eq!(
1468 hovered.borrow().as_slice(),
1469 &[vec![first.clone()], vec![first.clone(), second]]
1470 );
1471 assert_eq!(dropped.borrow().as_slice(), &[first]);
1472 assert_eq!(*cancelled.borrow(), 1);
1473 Ok(())
1474 }
1475
1476 fn with_modifiers(event: Event, modifiers: Modifiers) -> Event {
1477 match event {
1478 Event::Pointer(mut pointer) => {
1479 pointer.modifiers = modifiers;
1480 Event::Pointer(pointer)
1481 }
1482 other => other,
1483 }
1484 }
1485
1486 fn copy_key() -> (&'static str, Modifiers) {
1489 let mut modifiers = Modifiers::NONE;
1490 if cfg!(target_os = "macos") {
1491 modifiers.alt = true;
1492 ("Alt", modifiers)
1493 } else {
1494 modifiers.control = true;
1495 ("Control", modifiers)
1496 }
1497 }
1498
1499 fn key(name: &str, state: KeyState, modifiers: Modifiers) -> Event {
1500 let mut event = KeyboardEvent::new(name, state);
1501 event.modifiers = modifiers;
1502 Event::Keyboard(event)
1503 }
1504
1505 struct SourceAndTarget {
1508 runtime: Runtime,
1509 window_id: WindowId,
1510 scope: DragDropScope,
1511 accepted: Rc<RefCell<Vec<DropEffect>>>,
1512 hover_changes: Rc<RefCell<Vec<bool>>>,
1513 drops: Rc<RefCell<Vec<DropEffect>>>,
1514 ends: Rc<RefCell<Vec<Option<DragOutcome>>>>,
1515 }
1516
1517 fn source_and_target(effects: DropEffects) -> Result<SourceAndTarget> {
1518 let scope = DragDropScope::new();
1519 let accepted = Rc::new(RefCell::new(Vec::new()));
1520 let hover_changes = Rc::new(RefCell::new(Vec::new()));
1521 let drops = Rc::new(RefCell::new(Vec::new()));
1522 let ends = Rc::new(RefCell::new(Vec::new()));
1523 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1524 .scope(scope.clone())
1525 .payload(|| DragPayload::text("card"))
1526 .effects(effects)
1527 .on_drag_end({
1528 let ends = Rc::clone(&ends);
1529 move |_, drag| ends.borrow_mut().push(drag.outcome)
1530 });
1531 let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
1532 .scope(scope.clone())
1533 .accept({
1534 let accepted = Rc::clone(&accepted);
1535 move |drag| {
1536 let effect = drag.preferred_effect();
1537 accepted.borrow_mut().push(effect);
1538 effect
1539 }
1540 })
1541 .on_hover_change({
1542 let hover_changes = Rc::clone(&hover_changes);
1543 move |hovered| hover_changes.borrow_mut().push(hovered)
1544 })
1545 .on_drop({
1546 let drops = Rc::clone(&drops);
1547 move |_, drag| drops.borrow_mut().push(drag.accepted_effect)
1548 });
1549 let root = DragDropHost::new(
1550 scope.clone(),
1551 Stack::horizontal().with_child(source).with_child(target),
1552 );
1553 let (mut runtime, window_id) = build_runtime(root);
1554 let _ = runtime.render(window_id)?;
1555 Ok(SourceAndTarget {
1556 runtime,
1557 window_id,
1558 scope,
1559 accepted,
1560 hover_changes,
1561 drops,
1562 ends,
1563 })
1564 }
1565
1566 fn drag_onto_target(harness: &mut SourceAndTarget) -> Result<()> {
1568 let window_id = harness.window_id;
1569 harness.runtime.handle_event(
1570 window_id,
1571 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1572 )?;
1573 harness.runtime.handle_event(
1574 window_id,
1575 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1576 )?;
1577 Ok(())
1578 }
1579
1580 #[test]
1581 fn held_modifiers_choose_among_the_allowed_effects() -> Result<()> {
1582 let mut harness = source_and_target(DropEffects::MOVE | DropEffects::COPY)?;
1583 let window_id = harness.window_id;
1584 let (copy_key, copy_modifiers) = copy_key();
1585 drag_onto_target(&mut harness)?;
1586 assert_eq!(harness.accepted.borrow().last(), Some(&DropEffect::Move));
1587
1588 harness
1591 .runtime
1592 .handle_event(window_id, key(copy_key, KeyState::Pressed, copy_modifiers))?;
1593 assert_eq!(harness.accepted.borrow().last(), Some(&DropEffect::Copy));
1594 harness.runtime.handle_event(
1595 window_id,
1596 key(copy_key, KeyState::Released, Modifiers::NONE),
1597 )?;
1598 assert_eq!(harness.accepted.borrow().last(), Some(&DropEffect::Move));
1599
1600 harness.runtime.handle_event(
1601 window_id,
1602 with_modifiers(
1603 primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
1604 copy_modifiers,
1605 ),
1606 )?;
1607 assert_eq!(&*harness.drops.borrow(), &[DropEffect::Copy]);
1608 assert!(matches!(
1609 harness.ends.borrow().as_slice(),
1610 [Some(DragOutcome::Dropped {
1611 effect: DropEffect::Copy,
1612 ..
1613 })]
1614 ));
1615 Ok(())
1616 }
1617
1618 #[test]
1619 fn modifiers_cannot_ask_for_an_effect_the_source_does_not_allow() -> Result<()> {
1620 let mut harness = source_and_target(DropEffect::Move.into())?;
1621 let (copy_key, copy_modifiers) = copy_key();
1622 drag_onto_target(&mut harness)?;
1623 harness.runtime.handle_event(
1624 harness.window_id,
1625 key(copy_key, KeyState::Pressed, copy_modifiers),
1626 )?;
1627 assert!(
1628 harness
1629 .accepted
1630 .borrow()
1631 .iter()
1632 .all(|effect| *effect == DropEffect::Move)
1633 );
1634 Ok(())
1635 }
1636
1637 #[test]
1638 fn escape_cancels_the_drag() -> Result<()> {
1639 let mut harness = source_and_target(DropEffects::MOVE)?;
1640 let window_id = harness.window_id;
1641 drag_onto_target(&mut harness)?;
1642 assert_eq!(&*harness.hover_changes.borrow(), &[true]);
1643
1644 harness
1645 .runtime
1646 .handle_event(window_id, key("Escape", KeyState::Pressed, Modifiers::NONE))?;
1647 assert_eq!(&*harness.ends.borrow(), &[Some(DragOutcome::Cancelled)]);
1648 assert_eq!(&*harness.hover_changes.borrow(), &[true, false]);
1649 assert!(harness.scope.active_drag().is_none());
1650
1651 harness.runtime.handle_event(
1653 window_id,
1654 primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
1655 )?;
1656 assert!(harness.drops.borrow().is_empty());
1657 assert_eq!(harness.ends.borrow().len(), 1);
1658 Ok(())
1659 }
1660
1661 #[test]
1662 fn losing_window_focus_cancels_the_drag() -> Result<()> {
1663 let mut harness = source_and_target(DropEffects::MOVE)?;
1664 drag_onto_target(&mut harness)?;
1665 harness.runtime.handle_event(
1666 harness.window_id,
1667 Event::Window(WindowEvent::Focused(false)),
1668 )?;
1669 assert_eq!(&*harness.ends.borrow(), &[Some(DragOutcome::Cancelled)]);
1670 assert_eq!(&*harness.hover_changes.borrow(), &[true, false]);
1671 assert!(harness.scope.active_drag().is_none());
1672 Ok(())
1673 }
1674
1675 #[test]
1676 fn drop_targets_report_drags_they_refuse() -> Result<()> {
1677 let scope = DragDropScope::new();
1678 let states = Rc::new(RefCell::new(Vec::new()));
1679 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1680 .scope(scope.clone())
1681 .payload(|| DragPayload::text("card"));
1682 let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
1683 .scope(scope.clone())
1684 .accept(|drag| {
1685 if drag.payload.as_text().is_some() {
1686 DropEffect::None
1687 } else {
1688 DropEffect::Copy
1689 }
1690 })
1691 .on_hover_state({
1692 let states = Rc::clone(&states);
1693 move |state| states.borrow_mut().push(state)
1694 });
1695 let root = DragDropHost::new(
1696 scope,
1697 Stack::horizontal().with_child(source).with_child(target),
1698 );
1699 let (mut runtime, window_id) = build_runtime(root);
1700 let _ = runtime.render(window_id)?;
1701
1702 for (kind, x, pressed) in [
1703 (PointerEventKind::Down, 10.0, true),
1704 (PointerEventKind::Move, 100.0, true),
1705 (PointerEventKind::Move, 20.0, true),
1706 (PointerEventKind::Move, 110.0, true),
1707 (PointerEventKind::Up, 110.0, false),
1708 ] {
1709 runtime.handle_event(
1710 window_id,
1711 primary_pointer(kind, Point::new(x, 20.0), pressed),
1712 )?;
1713 }
1714 assert_eq!(
1715 &*states.borrow(),
1716 &[
1717 DropHover::Refusing,
1718 DropHover::Idle,
1719 DropHover::Refusing,
1720 DropHover::Idle,
1721 ]
1722 );
1723 Ok(())
1724 }
1725
1726 #[test]
1727 fn modifier_conventions_follow_the_platform() {
1728 let mut copy = Modifiers::NONE;
1729 let mut moving = Modifiers::NONE;
1730 if cfg!(target_os = "macos") {
1731 copy.alt = true;
1732 moving.meta = true;
1733 } else {
1734 copy.control = true;
1735 moving.shift = true;
1736 }
1737 let mut both = copy;
1738 both.alt |= moving.alt;
1739 both.meta |= moving.meta;
1740 both.control |= moving.control;
1741 both.shift |= moving.shift;
1742 assert_eq!(DropEffect::for_modifiers(Modifiers::NONE), None);
1743 assert_eq!(DropEffect::for_modifiers(copy), Some(DropEffect::Copy));
1744 assert_eq!(DropEffect::for_modifiers(moving), Some(DropEffect::Move));
1745 assert_eq!(DropEffect::for_modifiers(both), Some(DropEffect::Link));
1746
1747 let effects = DropEffects::COPY | DropEffects::LINK;
1748 assert!(effects.contains(DropEffect::Link));
1749 assert!(!effects.contains(DropEffect::Move));
1750 assert!(!effects.contains(DropEffect::None));
1751 assert_eq!(effects.default_effect(), DropEffect::Copy);
1752 assert_eq!(DropEffects::ALL.default_effect(), DropEffect::Move);
1753 assert_eq!(DropEffects::NONE.default_effect(), DropEffect::None);
1754 }
1755
1756 struct Swatch {
1758 color: Color,
1759 size: Size,
1760 }
1761
1762 impl Widget for Swatch {
1763 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1764 constraints.clamp(self.size)
1765 }
1766
1767 fn paint(&self, ctx: &mut PaintCtx) {
1768 ctx.fill(Path::rounded_rect(ctx.bounds(), 0.0), self.color);
1769 }
1770 }
1771
1772 #[test]
1773 fn host_draws_a_built_preview_widget_instead_of_the_label() -> Result<()> {
1774 let scope = DragDropScope::new();
1775 let swatch = Color::srgba(0.05, 0.78, 0.35, 1.0);
1776 let built = Rc::new(RefCell::new(Vec::new()));
1777 let theme = DefaultTheme::default();
1778 let label_fill = theme.palette.surface_raised.with_alpha(0.96);
1779 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1780 .scope(scope.clone())
1781 .payload(|| DragPayload::custom("asset", 7_u32))
1782 .preview_label("Asset");
1783 let root = DragDropHost::new(scope.clone(), Stack::horizontal().with_child(source))
1784 .theme(theme)
1785 .preview({
1786 let built = Rc::clone(&built);
1787 move |preview| {
1788 let asset = *preview.payload.custom_data::<u32>()?;
1789 built.borrow_mut().push(asset);
1790 Some(Box::new(Swatch {
1791 color: swatch,
1792 size: Size::new(30.0, 20.0),
1793 }) as Box<dyn Widget>)
1794 }
1795 });
1796 let (mut runtime, window_id) = build_runtime(root);
1797 let idle = runtime.render(window_id)?;
1798 assert!(!has_fill_color(&idle, swatch));
1799
1800 runtime.handle_event(
1801 window_id,
1802 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1803 )?;
1804 for x in [40.0, 60.0, 90.0] {
1805 runtime.handle_event(
1806 window_id,
1807 primary_pointer(PointerEventKind::Move, Point::new(x, 20.0), true),
1808 )?;
1809 }
1810 let dragging = runtime.render(window_id)?;
1811 assert_eq!(&*built.borrow(), &[7], "built once for the drag");
1812 assert!(has_fill_color(&dragging, swatch));
1813 assert!(!has_fill_color(&dragging, label_fill), "no label box");
1814
1815 runtime.handle_event(
1816 window_id,
1817 primary_pointer(PointerEventKind::Up, Point::new(90.0, 20.0), false),
1818 )?;
1819 let after = runtime.render(window_id)?;
1820 assert!(!has_fill_color(&after, swatch));
1821 Ok(())
1822 }
1823
1824 #[test]
1825 fn previews_stay_under_the_pointer_inside_the_host() {
1826 let bounds = Rect::new(0.0, 0.0, 200.0, 100.0);
1827 let size = Size::new(60.0, 30.0);
1828 assert_eq!(
1829 drag_preview_origin(Point::new(20.0, 10.0), size, bounds),
1830 Point::new(32.0, 22.0)
1831 );
1832 assert_eq!(
1834 drag_preview_origin(Point::new(190.0, 95.0), size, bounds),
1835 Point::new(140.0, 70.0)
1836 );
1837 }
1838
1839 #[test]
1840 fn scroll_view_scrolls_while_a_drag_holds_near_its_edge() -> Result<()> {
1841 let scope = DragDropScope::new();
1842 let state = ScrollState::new();
1843 let hover_changes = Rc::new(RefCell::new(Vec::new()));
1844 let content = Stack::vertical()
1845 .with_child(
1846 Draggable::new(SizedBox::new().width(200.0).height(40.0))
1847 .scope(scope.clone())
1848 .payload(|| DragPayload::text("card")),
1849 )
1850 .with_child(SizedBox::new().width(200.0).height(400.0))
1851 .with_child(
1852 DropTarget::new(SizedBox::new().width(200.0).height(40.0))
1853 .scope(scope.clone())
1854 .on_hover_change({
1855 let hover_changes = Rc::clone(&hover_changes);
1856 move |hovered| hover_changes.borrow_mut().push(hovered)
1857 }),
1858 );
1859 let scroll = SizedBox::new()
1860 .width(220.0)
1861 .height(200.0)
1862 .child(ScrollView::new(content).state(state.clone()));
1863 let root = DragDropHost::new(scope, Stack::vertical().with_child(scroll));
1864 let (mut runtime, window_id) = build_runtime(root);
1865 runtime.set_frame_pacing(window_id, FramePacing::Display)?;
1866 let _ = runtime.render(window_id)?;
1867
1868 runtime.handle_event(
1869 window_id,
1870 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1871 )?;
1872 runtime.handle_event(
1874 window_id,
1875 primary_pointer(PointerEventKind::Move, Point::new(10.0, 190.0), true),
1876 )?;
1877 let mut time = 0.0;
1878 for _ in 0..120 {
1879 time += 1.0 / 60.0;
1880 let events = runtime.begin_animation_frame(window_id, time)?;
1881 if events.is_empty() {
1882 break;
1883 }
1884 for event in events {
1885 runtime.handle_event(window_id, event)?;
1886 }
1887 let _ = runtime.render(window_id)?;
1888 }
1889
1890 assert_eq!(state.current_offset().y, 280.0);
1893 assert_eq!(&*hover_changes.borrow(), &[true]);
1894 assert!(
1895 !runtime.has_pending_animation_frames(window_id)?,
1896 "scrolling stops at the end"
1897 );
1898 Ok(())
1899 }
1900
1901 #[test]
1902 fn drag_payload_custom_equality_uses_stable_kind() {
1903 let left = DragPayload::custom("asset", 1_u32);
1904 let right = DragPayload::custom("asset", 2_u32);
1905 let other = DragPayload::custom("other", 1_u32);
1906
1907 assert_eq!(left, right);
1908 assert_ne!(left, other);
1909 assert_eq!(left.custom_data::<u32>(), Some(&1));
1910 assert_eq!(right.custom_data::<u32>(), Some(&2));
1911 }
1912}