Skip to main content

sui_widgets/
drag_drop.rs

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