1use std::{cell::RefCell, path::PathBuf, rc::Rc, 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)>;
25type ThemeReader = Rc<dyn Fn() -> DefaultTheme>;
26
27struct DragPreviewThemeSource {
28 theme: DefaultTheme,
29 reader: Option<ThemeReader>,
30}
31
32impl Default for DragPreviewThemeSource {
33 fn default() -> Self {
34 Self {
35 theme: DefaultTheme::default(),
36 reader: None,
37 }
38 }
39}
40
41impl DragPreviewThemeSource {
42 fn resolve(&self) -> DefaultTheme {
43 self.reader
44 .as_ref()
45 .map(|reader| reader())
46 .unwrap_or(self.theme)
47 }
48}
49
50pub struct DragDropHost {
51 scope: DragDropScope,
52 child: SingleChild,
53 overlay: SingleChild,
54 preview_theme: Rc<RefCell<DragPreviewThemeSource>>,
55 external_hovered: Vec<PathBuf>,
56 on_external_hover: Option<Box<dyn FnMut(&mut EventCtx, &[PathBuf])>>,
57 on_external_drop: Option<Box<dyn FnMut(&mut EventCtx, PathBuf)>>,
58 on_external_cancel: Option<Box<dyn FnMut(&mut EventCtx)>>,
59}
60
61impl DragDropHost {
62 pub fn new<W>(scope: DragDropScope, child: W) -> Self
63 where
64 W: Widget + 'static,
65 {
66 let preview_theme = Rc::new(RefCell::new(DragPreviewThemeSource::default()));
67 Self {
68 overlay: SingleChild::new(DragPreviewOverlay::new(
69 scope.clone(),
70 Rc::clone(&preview_theme),
71 )),
72 scope,
73 child: SingleChild::new(child),
74 preview_theme,
75 external_hovered: Vec::new(),
76 on_external_hover: None,
77 on_external_drop: None,
78 on_external_cancel: None,
79 }
80 }
81
82 pub fn scope(&self) -> &DragDropScope {
83 &self.scope
84 }
85
86 pub fn child(&self) -> &WidgetPod {
87 self.child.child()
88 }
89
90 pub fn child_mut(&mut self) -> &mut WidgetPod {
91 self.child.child_mut()
92 }
93
94 pub fn external_hovered_files(&self) -> &[PathBuf] {
95 &self.external_hovered
96 }
97
98 pub fn theme(self, theme: DefaultTheme) -> Self {
100 {
101 let mut source = self.preview_theme.borrow_mut();
102 source.theme = theme;
103 source.reader = None;
104 }
105 self
106 }
107
108 pub fn theme_when<F>(self, reader: F) -> Self
110 where
111 F: Fn() -> DefaultTheme + 'static,
112 {
113 self.preview_theme.borrow_mut().reader = Some(Rc::new(reader));
114 self
115 }
116
117 pub fn on_external_file_hover<F>(mut self, callback: F) -> Self
118 where
119 F: FnMut(&mut EventCtx, &[PathBuf]) + 'static,
120 {
121 self.on_external_hover = Some(Box::new(callback));
122 self
123 }
124
125 pub fn on_external_file_drop<F>(mut self, callback: F) -> Self
126 where
127 F: FnMut(&mut EventCtx, PathBuf) + 'static,
128 {
129 self.on_external_drop = Some(Box::new(callback));
130 self
131 }
132
133 pub fn on_external_file_hover_cancelled<F>(mut self, callback: F) -> Self
134 where
135 F: FnMut(&mut EventCtx) + 'static,
136 {
137 self.on_external_cancel = Some(Box::new(callback));
138 self
139 }
140}
141
142impl Widget for DragDropHost {
143 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
144 match event {
145 Event::Window(WindowEvent::ExternalFileHovered(path)) => {
146 if !self.external_hovered.contains(path) {
147 self.external_hovered.push(path.clone());
148 }
149 if let Some(callback) = &mut self.on_external_hover {
150 callback(ctx, &self.external_hovered);
151 }
152 ctx.request_paint();
153 ctx.request_semantics();
154 ctx.set_handled();
155 }
156 Event::Window(WindowEvent::ExternalFileHoverCancelled) => {
157 self.external_hovered.clear();
158 if let Some(callback) = &mut self.on_external_cancel {
159 callback(ctx);
160 }
161 ctx.request_paint();
162 ctx.request_semantics();
163 ctx.set_handled();
164 }
165 Event::Window(WindowEvent::ExternalFileDropped(path)) => {
166 self.external_hovered.retain(|hovered| hovered != path);
167 if let Some(callback) = &mut self.on_external_drop {
168 callback(ctx, path.clone());
169 }
170 ctx.request_paint();
171 ctx.request_semantics();
172 ctx.set_handled();
173 }
174 _ => {}
175 }
176 }
177
178 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
179 let size = self.child.measure(ctx, constraints);
180 self.overlay.measure(ctx, Constraints::tight(size));
181 size
182 }
183
184 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
185 self.child.arrange(ctx, bounds);
186 self.overlay.arrange(ctx, bounds);
187 }
188
189 fn paint(&self, ctx: &mut PaintCtx) {
190 self.child.paint(ctx);
191 self.overlay.paint(ctx);
192 }
193
194 fn semantics(&self, ctx: &mut SemanticsCtx) {
195 self.child.semantics(ctx);
196 }
197
198 fn overlay_options(&self) -> Option<OverlayOptions> {
199 self.scope.active_drag().is_some().then_some(
200 OverlayOptions::new(OverlayKind::DragPreview)
201 .dismiss(OverlayDismissPolicy::NONE)
202 .focus(OverlayFocusBehavior::NONE),
203 )
204 }
205
206 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
207 self.child.visit_children(visitor);
208 self.overlay.visit_children(visitor);
209 }
210
211 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
212 self.child.visit_children_mut(visitor);
213 self.overlay.visit_children_mut(visitor);
214 }
215}
216
217struct DragPreviewOverlay {
218 scope: DragDropScope,
219 theme: Rc<RefCell<DragPreviewThemeSource>>,
220}
221
222impl DragPreviewOverlay {
223 fn new(scope: DragDropScope, theme: Rc<RefCell<DragPreviewThemeSource>>) -> Self {
224 Self { scope, theme }
225 }
226
227 fn resolved_theme(&self) -> DefaultTheme {
228 self.theme.borrow().resolve()
229 }
230}
231
232impl Widget for DragPreviewOverlay {
233 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
234 constraints.clamp(Size::new(
235 constraints.max.width.max(0.0),
236 constraints.max.height.max(0.0),
237 ))
238 }
239
240 fn paint(&self, ctx: &mut PaintCtx) {
241 let Some(active) = self.scope.active_drag() else {
242 return;
243 };
244
245 let label = drag_preview_label(&active);
246 let theme = self.resolved_theme();
247 let text_style = drag_preview_text_style(theme);
248 let estimated_character_width = text_style.font_size * 0.54;
249 let width =
250 ((label.chars().count() as f32 * estimated_character_width) + 24.0).clamp(48.0, 260.0);
251 let height = text_style.line_height + 12.0;
252 let offset = Vector::new(12.0, 12.0);
253 let bounds = ctx.bounds();
254 let x = (active.position.x + offset.x).min((bounds.max_x() - width).max(bounds.x()));
255 let y = (active.position.y + offset.y).min((bounds.max_y() - height).max(bounds.y()));
256 let rect = Rect::new(x.max(bounds.x()), y.max(bounds.y()), width, height);
257
258 ctx.fill_rrect_bordered(
259 rect,
260 [7.0; 4],
261 theme.palette.surface_raised.with_alpha(0.96),
262 Border {
263 width: 1.0,
264 color: theme.palette.border.with_alpha(0.72),
265 },
266 );
267
268 let text_rect = Rect::new(
269 rect.x() + 12.0,
270 rect.y() + 6.0,
271 rect.width() - 24.0,
272 text_style.line_height,
273 );
274 ctx.push_clip_rect(text_rect);
275 ctx.draw_text(text_rect, label, text_style);
276 ctx.pop_clip();
277 }
278
279 fn layer_options(&self) -> LayerOptions {
280 LayerOptions {
281 paint_boundary: PaintBoundaryMode::Explicit,
282 composition_mode: LayerCompositionMode::Overlay,
283 }
284 }
285
286 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
287 Some(StackSurfaceOptions {
288 transient: true,
289 hit_test: false,
290 ..StackSurfaceOptions::default()
291 })
292 }
293}
294
295fn drag_preview_text_style(theme: DefaultTheme) -> sui_text::TextStyle {
296 let mut style = theme.text_style(theme.palette.text);
297 style.font_size = theme.text.sm.size.max(1.0);
298 style.line_height = theme.text.sm.line_height.max(1.0);
299 style
300}
301
302pub struct Draggable {
303 scope: DragDropScope,
304 child: SingleChild,
305 payload: PayloadFactory,
306 allowed_effect: DropEffect,
307 preview_label: Option<String>,
308 threshold: f32,
309 press: Option<DragPress>,
310 active_session: Option<DragSessionId>,
311 on_drag_start: Option<DragStartCallback>,
312 on_drag_end: Option<DragEndCallback>,
313}
314
315#[derive(Debug, Clone, Copy)]
316struct DragPress {
317 pointer_id: u64,
318 start_position: Point,
319}
320
321impl Draggable {
322 pub fn new<W>(child: W) -> Self
323 where
324 W: Widget + 'static,
325 {
326 Self {
327 scope: DragDropScope::new(),
328 child: SingleChild::new(child),
329 payload: Box::new(|| DragPayload::text("")),
330 allowed_effect: DropEffect::Move,
331 preview_label: None,
332 threshold: DEFAULT_DRAG_THRESHOLD,
333 press: None,
334 active_session: None,
335 on_drag_start: None,
336 on_drag_end: None,
337 }
338 }
339
340 pub fn scope(mut self, scope: DragDropScope) -> Self {
341 self.scope = scope;
342 self
343 }
344
345 pub fn payload<F>(mut self, payload: F) -> Self
346 where
347 F: FnMut() -> DragPayload + 'static,
348 {
349 self.payload = Box::new(payload);
350 self
351 }
352
353 pub fn effect(mut self, effect: DropEffect) -> Self {
354 self.allowed_effect = effect;
355 self
356 }
357
358 pub fn preview_label(mut self, label: impl Into<String>) -> Self {
359 self.preview_label = Some(label.into());
360 self
361 }
362
363 pub fn threshold(mut self, threshold: f32) -> Self {
364 self.threshold = threshold.max(0.0);
365 self
366 }
367
368 pub fn on_drag_start<F>(mut self, callback: F) -> Self
369 where
370 F: FnMut(&mut EventCtx, &DragPreview) + 'static,
371 {
372 self.on_drag_start = Some(Box::new(callback));
373 self
374 }
375
376 pub fn on_drag_end<F>(mut self, callback: F) -> Self
377 where
378 F: FnMut(&mut EventCtx, &DragEvent) + 'static,
379 {
380 self.on_drag_end = Some(Box::new(callback));
381 self
382 }
383
384 pub fn scope_ref(&self) -> &DragDropScope {
385 &self.scope
386 }
387
388 pub fn child(&self) -> &WidgetPod {
389 self.child.child()
390 }
391
392 pub fn child_mut(&mut self) -> &mut WidgetPod {
393 self.child.child_mut()
394 }
395
396 fn start_drag(&mut self, ctx: &mut EventCtx, press: DragPress, position: Point) {
397 let payload = (self.payload)();
398 let preview_label = self.preview_label.clone();
399 let session_id = ctx.begin_drag(
400 self.scope.id(),
401 press.pointer_id,
402 press.start_position,
403 payload.clone(),
404 self.allowed_effect,
405 preview_label.clone(),
406 );
407 let preview = DragPreview {
408 session_id,
409 scope_id: self.scope.id(),
410 pointer_id: press.pointer_id,
411 source: ctx.widget_id(),
412 position,
413 start_position: press.start_position,
414 payload,
415 allowed_effect: self.allowed_effect,
416 preview_label: preview_label.map(Arc::from),
417 };
418 self.scope.set_active_drag(preview.clone());
419 self.active_session = Some(session_id);
420 if let Some(callback) = &mut self.on_drag_start {
421 callback(ctx, &preview);
422 }
423 ctx.request_paint();
424 }
425}
426
427impl Widget for Draggable {
428 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
429 match event {
430 Event::Pointer(pointer)
431 if pointer.kind == PointerEventKind::Down
432 && pointer.button == Some(PointerButton::Primary)
433 && ctx.bounds().contains(pointer.position)
434 && ctx.phase() != sui_runtime::EventPhase::Capture =>
435 {
436 self.press = Some(DragPress {
437 pointer_id: pointer.pointer_id,
438 start_position: pointer.position,
439 });
440 self.active_session = None;
441 ctx.request_pointer_capture(pointer.pointer_id);
442 ctx.set_handled();
443 }
444 Event::Pointer(pointer)
445 if pointer.kind == PointerEventKind::Move
446 && self
447 .press
448 .is_some_and(|press| press.pointer_id == pointer.pointer_id) =>
449 {
450 if let Some(session_id) = self.active_session {
451 self.scope
452 .update_drag_position(session_id, pointer.position);
453 ctx.request_paint();
454 ctx.set_handled();
455 return;
456 }
457
458 let press = self.press.unwrap();
459 let delta = pointer.position - press.start_position;
460 let distance_sq = (delta.x * delta.x) + (delta.y * delta.y);
461 if distance_sq >= self.threshold * self.threshold {
462 self.start_drag(ctx, press, pointer.position);
463 ctx.set_handled();
464 }
465 }
466 Event::Pointer(pointer)
467 if matches!(
468 pointer.kind,
469 PointerEventKind::Up | PointerEventKind::Cancel
470 ) && self
471 .press
472 .is_some_and(|press| press.pointer_id == pointer.pointer_id) =>
473 {
474 if self.active_session.is_none() {
475 self.press = None;
476 }
477 ctx.release_pointer_capture(pointer.pointer_id);
478 ctx.set_handled();
479 }
480 Event::Drag(drag)
481 if drag.kind == DragEventKind::End
482 && self.active_session == Some(drag.session_id) =>
483 {
484 self.scope.finish_drag(drag.session_id);
485 self.press = None;
486 self.active_session = None;
487 if let Some(callback) = &mut self.on_drag_end {
488 callback(ctx, drag);
489 }
490 ctx.request_paint();
491 ctx.set_handled();
492 }
493 _ => {}
494 }
495 }
496
497 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
498 self.child.measure(ctx, constraints)
499 }
500
501 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
502 self.child.arrange(ctx, bounds);
503 }
504
505 fn paint(&self, ctx: &mut PaintCtx) {
506 self.child.paint(ctx);
507 }
508
509 fn semantics(&self, ctx: &mut SemanticsCtx) {
510 self.child.semantics(ctx);
511 }
512
513 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
514 self.child.visit_children(visitor);
515 }
516
517 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
518 self.child.visit_children_mut(visitor);
519 }
520}
521
522pub struct DropTarget {
523 scope: DragDropScope,
524 child: SingleChild,
525 accept: DropAcceptCallback,
526 hovered: bool,
527 on_drop: Option<DropCallback>,
528 on_hover_change: Option<HoverCallback>,
529}
530
531impl DropTarget {
532 pub fn new<W>(child: W) -> Self
537 where
538 W: Widget + 'static,
539 {
540 Self {
541 scope: DragDropScope::new(),
542 child: SingleChild::new(child),
543 accept: Box::new(|_| DropEffect::Copy),
544 hovered: false,
545 on_drop: None,
546 on_hover_change: None,
547 }
548 }
549
550 pub fn scope(mut self, scope: DragDropScope) -> Self {
551 self.scope = scope;
552 self
553 }
554
555 pub fn accept<F>(mut self, accept: F) -> Self
556 where
557 F: FnMut(&DragEvent) -> DropEffect + 'static,
558 {
559 self.accept = Box::new(accept);
560 self
561 }
562
563 pub fn on_drop<F>(mut self, callback: F) -> Self
564 where
565 F: FnMut(&mut EventCtx, &DragEvent) + 'static,
566 {
567 self.on_drop = Some(Box::new(callback));
568 self
569 }
570
571 pub fn on_hover_change<F>(mut self, callback: F) -> Self
572 where
573 F: FnMut(bool) + 'static,
574 {
575 self.on_hover_change = Some(Box::new(callback));
576 self
577 }
578
579 pub fn is_hovered(&self) -> bool {
580 self.hovered
581 }
582
583 pub fn scope_ref(&self) -> &DragDropScope {
584 &self.scope
585 }
586
587 pub fn child(&self) -> &WidgetPod {
588 self.child.child()
589 }
590
591 pub fn child_mut(&mut self) -> &mut WidgetPod {
592 self.child.child_mut()
593 }
594
595 fn set_hovered(&mut self, ctx: &mut EventCtx, hovered: bool) {
596 if self.hovered == hovered {
597 return;
598 }
599 self.hovered = hovered;
600 if let Some(callback) = &mut self.on_hover_change {
601 callback(hovered);
602 }
603 ctx.request_paint();
604 ctx.request_semantics();
605 }
606}
607
608impl Widget for DropTarget {
609 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
610 let Event::Drag(drag) = event else {
611 return;
612 };
613 if drag.scope_id != self.scope.id() {
614 return;
615 }
616
617 match drag.kind {
618 DragEventKind::Enter | DragEventKind::Over => {
619 let effect = (self.accept)(drag);
620 if effect.is_some() {
621 ctx.accept_drop(effect);
622 self.set_hovered(ctx, true);
623 } else {
624 self.set_hovered(ctx, false);
625 }
626 }
627 DragEventKind::Leave => {
628 self.set_hovered(ctx, false);
629 }
630 DragEventKind::Drop if drag.target == Some(ctx.widget_id()) => {
631 if let Some(callback) = &mut self.on_drop {
632 callback(ctx, drag);
633 }
634 self.set_hovered(ctx, false);
635 ctx.set_handled();
636 }
637 _ => {}
638 }
639 }
640
641 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
642 self.child.measure(ctx, constraints)
643 }
644
645 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
646 self.child.arrange(ctx, bounds);
647 }
648
649 fn paint(&self, ctx: &mut PaintCtx) {
650 self.child.paint(ctx);
651 }
652
653 fn semantics(&self, ctx: &mut SemanticsCtx) {
654 self.child.semantics(ctx);
655 }
656
657 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
658 self.child.visit_children(visitor);
659 }
660
661 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
662 self.child.visit_children_mut(visitor);
663 }
664}
665
666fn drag_preview_label(active: &DragPreview) -> String {
667 if let Some(label) = &active.preview_label {
668 return label.to_string();
669 }
670
671 match &active.payload {
672 DragPayload::Text(text) if !text.is_empty() => text.clone(),
673 DragPayload::Image { .. } => "Image".to_string(),
674 DragPayload::Custom { kind, .. } => kind.to_string(),
675 DragPayload::Text(_) => "Dragging".to_string(),
676 }
677}
678
679#[cfg(test)]
680mod tests {
681 use std::{cell::RefCell, rc::Rc};
682
683 use super::*;
684 use crate::{Label, SizedBox, Stack, Surface, ThemeTextToken};
685 use sui_core::{
686 DragOutcome, Modifiers, PointerButtons, PointerEvent, PointerKind, Result, WindowId,
687 };
688 use sui_runtime::{Application, Runtime, WindowBuilder};
689 use sui_scene::{Brush, SceneCommand};
690
691 fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
692 let mut buttons = PointerButtons::NONE;
693 if pressed {
694 buttons.insert(PointerButton::Primary);
695 }
696
697 Event::Pointer(PointerEvent {
698 pointer_id: 1,
699 kind,
700 position,
701 delta: Vector::ZERO,
702 scroll_delta: None,
703 button: Some(PointerButton::Primary),
704 buttons,
705 modifiers: Modifiers::NONE,
706 pointer_kind: PointerKind::Mouse,
707 is_primary: true,
708 })
709 }
710
711 fn build_runtime<W>(root: W) -> (Runtime, WindowId)
712 where
713 W: Widget + 'static,
714 {
715 let runtime = Application::new()
716 .window(WindowBuilder::new().title("Drag Drop").root(root))
717 .build()
718 .unwrap();
719 let window_id = runtime.window_ids()[0];
720 (runtime, window_id)
721 }
722
723 fn has_fill_color(output: &sui_runtime::RenderOutput, color: sui_core::Color) -> bool {
724 let mut found = false;
725 output
726 .frame
727 .scene
728 .visit_commands(&mut |command| match command {
729 SceneCommand::FillRect {
730 brush: Brush::Solid(fill),
731 ..
732 }
733 | SceneCommand::FillPath {
734 brush: Brush::Solid(fill),
735 ..
736 }
737 | SceneCommand::FillRoundedRect {
738 brush: Brush::Solid(fill),
739 ..
740 } if *fill == color => found = true,
741 _ => {}
742 });
743 found
744 }
745
746 fn has_stroke_color(output: &sui_runtime::RenderOutput, color: sui_core::Color) -> bool {
747 let mut found = false;
748 output
749 .frame
750 .scene
751 .visit_commands(&mut |command| match command {
752 SceneCommand::StrokeRect {
753 brush: Brush::Solid(stroke),
754 ..
755 }
756 | SceneCommand::StrokePath {
757 brush: Brush::Solid(stroke),
758 ..
759 } if *stroke == color => found = true,
760 _ => {}
761 });
762 found
763 }
764
765 fn feedback_fill_precedes_text(
766 output: &sui_runtime::RenderOutput,
767 color: sui_core::Color,
768 ) -> bool {
769 let mut command_index = 0;
770 let mut fill_index = None;
771 let mut text_index = None;
772 output.frame.scene.visit_commands(&mut |command| {
773 match command {
774 SceneCommand::FillRect {
775 brush: Brush::Solid(fill),
776 ..
777 }
778 | SceneCommand::FillPath {
779 brush: Brush::Solid(fill),
780 ..
781 }
782 | SceneCommand::FillRoundedRect {
783 brush: Brush::Solid(fill),
784 ..
785 } if *fill == color => {
786 fill_index.get_or_insert(command_index);
787 }
788 SceneCommand::DrawText(_)
789 | SceneCommand::DrawShapedText(_)
790 | SceneCommand::DrawShapedTextWindow(_) => {
791 text_index.get_or_insert(command_index);
792 }
793 _ => {}
794 };
795 command_index += 1;
796 });
797 matches!((fill_index, text_index), (Some(fill), Some(text)) if fill < text)
798 }
799
800 #[test]
801 fn drag_preview_theme_tracks_static_and_dynamic_small_tokens() {
802 let mut static_theme = DefaultTheme::default();
803 static_theme.text.sm = ThemeTextToken {
804 size: 17.0,
805 line_height: 24.0,
806 };
807 let host = DragDropHost::new(
808 DragDropScope::new(),
809 SizedBox::new().width(80.0).height(40.0),
810 )
811 .theme(static_theme);
812 let resolved = host.preview_theme.borrow().resolve();
813 let style = drag_preview_text_style(resolved);
814 assert_eq!(style.font_size, static_theme.text.sm.size);
815 assert_eq!(style.line_height, static_theme.text.sm.line_height);
816 assert_eq!(style.color, static_theme.palette.text);
817
818 let current = Rc::new(RefCell::new(DefaultTheme::default()));
819 let dynamic_host = DragDropHost::new(
820 DragDropScope::new(),
821 SizedBox::new().width(80.0).height(40.0),
822 )
823 .theme_when({
824 let current = Rc::clone(¤t);
825 move || *current.borrow()
826 });
827 current.borrow_mut().text.sm = ThemeTextToken {
828 size: 19.0,
829 line_height: 27.0,
830 };
831
832 let resolved = dynamic_host.preview_theme.borrow().resolve();
833 let style = drag_preview_text_style(resolved);
834 assert_eq!(style.font_size, 19.0);
835 assert_eq!(style.line_height, 27.0);
836 }
837
838 #[test]
839 fn draggable_starts_after_threshold_and_drops_typed_payload() -> Result<()> {
840 let scope = DragDropScope::new();
841 let starts = Rc::new(RefCell::new(0));
842 let ends = Rc::new(RefCell::new(Vec::new()));
843 let drops = Rc::new(RefCell::new(Vec::new()));
844 let hover_changes = Rc::new(RefCell::new(Vec::new()));
845
846 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
847 .scope(scope.clone())
848 .payload(|| DragPayload::custom("asset", 42_u32))
849 .effect(DropEffect::Move)
850 .preview_label("Asset")
851 .on_drag_start({
852 let starts = Rc::clone(&starts);
853 move |_, _| *starts.borrow_mut() += 1
854 })
855 .on_drag_end({
856 let ends = Rc::clone(&ends);
857 move |_, drag| ends.borrow_mut().push(drag.outcome)
858 });
859
860 let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
861 .scope(scope.clone())
862 .accept(|drag| {
863 if drag.payload.custom_data::<u32>() == Some(&42) {
864 DropEffect::Move
865 } else {
866 DropEffect::None
867 }
868 })
869 .on_drop({
870 let drops = Rc::clone(&drops);
871 move |_, drag| {
872 drops
873 .borrow_mut()
874 .push(*drag.payload.custom_data::<u32>().unwrap());
875 }
876 })
877 .on_hover_change({
878 let hover_changes = Rc::clone(&hover_changes);
879 move |hovered| hover_changes.borrow_mut().push(hovered)
880 });
881
882 let root = DragDropHost::new(
883 scope.clone(),
884 Stack::horizontal().with_child(source).with_child(target),
885 );
886 let (mut runtime, window_id) = build_runtime(root);
887 let _ = runtime.render(window_id)?;
888
889 runtime.handle_event(
890 window_id,
891 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
892 )?;
893 runtime.handle_event(
894 window_id,
895 primary_pointer(PointerEventKind::Move, Point::new(12.0, 20.0), true),
896 )?;
897
898 assert_eq!(*starts.borrow(), 0);
899 assert!(scope.active_drag().is_none());
900
901 runtime.handle_event(
902 window_id,
903 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
904 )?;
905 assert_eq!(*starts.borrow(), 1);
906 assert!(scope.active_drag().is_some());
907
908 runtime.handle_event(
909 window_id,
910 primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
911 )?;
912
913 assert_eq!(&*drops.borrow(), &[42]);
914 assert!(matches!(
915 ends.borrow().as_slice(),
916 [Some(DragOutcome::Dropped {
917 effect: DropEffect::Move,
918 ..
919 })]
920 ));
921 assert_eq!(&*hover_changes.borrow(), &[true, false]);
922 assert!(scope.active_drag().is_none());
923 Ok(())
924 }
925
926 #[test]
927 fn accepting_drop_target_has_no_default_hover_feedback() -> Result<()> {
928 let scope = DragDropScope::new();
929 let theme = DefaultTheme::default();
930 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
931 .scope(scope.clone())
932 .payload(|| DragPayload::text("item"))
933 .effect(DropEffect::Copy)
934 .preview_label("Item");
935 let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
936 .scope(scope.clone())
937 .accept(|_| DropEffect::Copy);
938 let root = DragDropHost::new(
939 scope,
940 Stack::horizontal().with_child(source).with_child(target),
941 );
942 let (mut runtime, window_id) = build_runtime(root);
943
944 let idle = runtime.render(window_id)?;
945 assert!(!has_fill_color(&idle, theme.palette.accent_soft));
946
947 runtime.handle_event(
948 window_id,
949 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
950 )?;
951 runtime.handle_event(
952 window_id,
953 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
954 )?;
955
956 let hovering = runtime.render(window_id)?;
957 assert!(!has_fill_color(&hovering, theme.palette.accent_soft));
958 Ok(())
959 }
960
961 #[test]
962 fn drop_target_hover_callback_can_drive_child_feedback_behind_content() -> Result<()> {
963 let scope = DragDropScope::new();
964 let theme = DefaultTheme::default();
965 let hovered = Rc::new(RefCell::new(false));
966 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
967 .scope(scope.clone())
968 .payload(|| DragPayload::text("item"))
969 .effect(DropEffect::Copy)
970 .preview_label("Item");
971 let surface_hovered = Rc::clone(&hovered);
972 let target = DropTarget::new(
973 Surface::panel(
974 SizedBox::new()
975 .width(80.0)
976 .height(40.0)
977 .with_child(Label::new("Drop here")),
978 )
979 .theme_when(move || {
980 let mut resolved = theme;
981 if *surface_hovered.borrow() {
982 resolved.surfaces.panel = resolved.palette.accent_soft;
983 resolved.surfaces.border = resolved.palette.accent_border_focus;
984 }
985 resolved
986 }),
987 )
988 .scope(scope.clone())
989 .accept(|_| DropEffect::Copy)
990 .on_hover_change(move |value| *hovered.borrow_mut() = value);
991 let root = DragDropHost::new(
992 scope,
993 Stack::horizontal().with_child(source).with_child(target),
994 );
995 let (mut runtime, window_id) = build_runtime(root);
996 let idle = runtime.render(window_id)?;
997 assert!(!has_fill_color(&idle, theme.palette.accent_soft));
998
999 runtime.handle_event(
1000 window_id,
1001 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1002 )?;
1003 runtime.handle_event(
1004 window_id,
1005 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1006 )?;
1007
1008 let hovering = runtime.render(window_id)?;
1009 assert!(has_fill_color(&hovering, theme.palette.accent_soft));
1010 assert!(has_stroke_color(
1011 &hovering,
1012 theme.palette.accent_border_focus
1013 ));
1014 assert!(feedback_fill_precedes_text(
1015 &hovering,
1016 theme.palette.accent_soft
1017 ));
1018 Ok(())
1019 }
1020
1021 #[test]
1022 fn nearest_accepting_drop_target_receives_drop() -> Result<()> {
1023 let scope = DragDropScope::new();
1024 let inner_drops = Rc::new(RefCell::new(0));
1025 let outer_drops = Rc::new(RefCell::new(0));
1026
1027 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1028 .scope(scope.clone())
1029 .payload(|| DragPayload::text("item"));
1030
1031 let inner = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
1032 .scope(scope.clone())
1033 .accept(|_| DropEffect::Copy)
1034 .on_drop({
1035 let inner_drops = Rc::clone(&inner_drops);
1036 move |_, _| *inner_drops.borrow_mut() += 1
1037 });
1038 let outer = DropTarget::new(inner)
1039 .scope(scope.clone())
1040 .accept(|_| DropEffect::Copy)
1041 .on_drop({
1042 let outer_drops = Rc::clone(&outer_drops);
1043 move |_, _| *outer_drops.borrow_mut() += 1
1044 });
1045
1046 let root = DragDropHost::new(
1047 scope,
1048 Stack::horizontal().with_child(source).with_child(outer),
1049 );
1050 let (mut runtime, window_id) = build_runtime(root);
1051 let _ = runtime.render(window_id)?;
1052
1053 runtime.handle_event(
1054 window_id,
1055 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1056 )?;
1057 runtime.handle_event(
1058 window_id,
1059 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1060 )?;
1061 runtime.handle_event(
1062 window_id,
1063 primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
1064 )?;
1065
1066 assert_eq!(*inner_drops.borrow(), 1);
1067 assert_eq!(*outer_drops.borrow(), 0);
1068 Ok(())
1069 }
1070
1071 #[test]
1072 fn cross_scope_target_ignores_drag_session() -> Result<()> {
1073 let source_scope = DragDropScope::new();
1074 let target_scope = DragDropScope::new();
1075 let ends = Rc::new(RefCell::new(Vec::new()));
1076 let drops = Rc::new(RefCell::new(0));
1077
1078 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1079 .scope(source_scope.clone())
1080 .payload(|| DragPayload::text("item"))
1081 .on_drag_end({
1082 let ends = Rc::clone(&ends);
1083 move |_, drag| ends.borrow_mut().push(drag.outcome)
1084 });
1085 let target = DropTarget::new(SizedBox::new().width(80.0).height(40.0))
1086 .scope(target_scope)
1087 .accept(|_| DropEffect::Copy)
1088 .on_drop({
1089 let drops = Rc::clone(&drops);
1090 move |_, _| *drops.borrow_mut() += 1
1091 });
1092
1093 let root = DragDropHost::new(
1094 source_scope,
1095 Stack::horizontal().with_child(source).with_child(target),
1096 );
1097 let (mut runtime, window_id) = build_runtime(root);
1098 let _ = runtime.render(window_id)?;
1099
1100 runtime.handle_event(
1101 window_id,
1102 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1103 )?;
1104 runtime.handle_event(
1105 window_id,
1106 primary_pointer(PointerEventKind::Move, Point::new(100.0, 20.0), true),
1107 )?;
1108 runtime.handle_event(
1109 window_id,
1110 primary_pointer(PointerEventKind::Up, Point::new(100.0, 20.0), false),
1111 )?;
1112
1113 assert_eq!(*drops.borrow(), 0);
1114 assert_eq!(&*ends.borrow(), &[Some(DragOutcome::Cancelled)]);
1115 Ok(())
1116 }
1117
1118 #[test]
1119 fn drag_drop_host_preview_layer_is_not_hit_tested() -> Result<()> {
1120 let scope = DragDropScope::new();
1121 let starts = Rc::new(RefCell::new(0));
1122 let source = Draggable::new(SizedBox::new().width(80.0).height(40.0))
1123 .scope(scope.clone())
1124 .payload(|| DragPayload::text("item"))
1125 .on_drag_start({
1126 let starts = Rc::clone(&starts);
1127 move |_, _| *starts.borrow_mut() += 1
1128 });
1129 let root = DragDropHost::new(scope, source);
1130 let (mut runtime, window_id) = build_runtime(root);
1131
1132 let output = runtime.render(window_id)?;
1133 let mut preview_layer = None;
1134 output.frame.scene.visit_layers(&mut |layer| {
1135 if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
1136 preview_layer = Some((layer.widget_id(), layer.descriptor.hit_test));
1137 }
1138 });
1139
1140 assert!(matches!(preview_layer, Some((_, false))));
1141
1142 runtime.handle_event(
1143 window_id,
1144 primary_pointer(PointerEventKind::Down, Point::new(10.0, 20.0), true),
1145 )?;
1146 runtime.handle_event(
1147 window_id,
1148 primary_pointer(PointerEventKind::Move, Point::new(24.0, 20.0), true),
1149 )?;
1150
1151 assert_eq!(*starts.borrow(), 1);
1152 Ok(())
1153 }
1154
1155 #[test]
1156 fn drag_drop_host_routes_platform_file_hover_drop_and_cancel() -> Result<()> {
1157 let hovered = Rc::new(RefCell::new(Vec::<Vec<PathBuf>>::new()));
1158 let dropped = Rc::new(RefCell::new(Vec::<PathBuf>::new()));
1159 let cancelled = Rc::new(RefCell::new(0));
1160 let root = DragDropHost::new(
1161 DragDropScope::new(),
1162 SizedBox::new().width(160.0).height(80.0),
1163 )
1164 .on_external_file_hover({
1165 let hovered = Rc::clone(&hovered);
1166 move |_, paths| hovered.borrow_mut().push(paths.to_vec())
1167 })
1168 .on_external_file_drop({
1169 let dropped = Rc::clone(&dropped);
1170 move |_, path| dropped.borrow_mut().push(path)
1171 })
1172 .on_external_file_hover_cancelled({
1173 let cancelled = Rc::clone(&cancelled);
1174 move |_| *cancelled.borrow_mut() += 1
1175 });
1176 let (mut runtime, window_id) = build_runtime(root);
1177 let _ = runtime.render(window_id)?;
1178 let first = PathBuf::from("/tmp/first.txt");
1179 let second = PathBuf::from("/tmp/second.png");
1180
1181 runtime.handle_event(
1182 window_id,
1183 Event::Window(WindowEvent::ExternalFileHovered(first.clone())),
1184 )?;
1185 runtime.handle_event(
1186 window_id,
1187 Event::Window(WindowEvent::ExternalFileHovered(second.clone())),
1188 )?;
1189 runtime.handle_event(
1190 window_id,
1191 Event::Window(WindowEvent::ExternalFileDropped(first.clone())),
1192 )?;
1193 runtime.handle_event(
1194 window_id,
1195 Event::Window(WindowEvent::ExternalFileHoverCancelled),
1196 )?;
1197
1198 assert_eq!(
1199 hovered.borrow().as_slice(),
1200 &[vec![first.clone()], vec![first.clone(), second]]
1201 );
1202 assert_eq!(dropped.borrow().as_slice(), &[first]);
1203 assert_eq!(*cancelled.borrow(), 1);
1204 Ok(())
1205 }
1206
1207 #[test]
1208 fn drag_payload_custom_equality_uses_stable_kind() {
1209 let left = DragPayload::custom("asset", 1_u32);
1210 let right = DragPayload::custom("asset", 2_u32);
1211 let other = DragPayload::custom("other", 1_u32);
1212
1213 assert_eq!(left, right);
1214 assert_ne!(left, other);
1215 assert_eq!(left.custom_data::<u32>(), Some(&1));
1216 assert_eq!(right.custom_data::<u32>(), Some(&2));
1217 }
1218}