Skip to main content

cosmic/widget/
dnd_destination.rs

1use std::borrow::Cow;
2use std::sync::atomic::{AtomicU64, Ordering};
3
4use iced::Vector;
5
6use crate::Element;
7use crate::widget::{Id, Widget};
8
9use iced::clipboard::dnd::{self, DndAction, DndDestinationRectangle, DndEvent, OfferEvent};
10use iced::clipboard::mime::AllowedMimeTypes;
11use iced::id::Internal;
12use iced::{Event, Length, Rectangle, event, mouse, overlay};
13use iced_core::widget::{Tree, tree};
14use iced_core::{self, Clipboard, Shell, layout};
15
16pub fn dnd_destination<'a, Message: 'static>(
17    child: impl Into<Element<'a, Message>>,
18    mimes: Vec<Cow<'static, str>>,
19) -> DndDestination<'a, Message> {
20    DndDestination::new(child, mimes)
21}
22
23pub fn dnd_destination_for_data<'a, T: AllowedMimeTypes, Message: 'static>(
24    child: impl Into<Element<'a, Message>>,
25    on_finish: impl Fn(Option<T>, DndAction) -> Message + 'static,
26) -> DndDestination<'a, Message> {
27    DndDestination::for_data(child, on_finish)
28}
29
30static DRAG_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
31const DND_DEST_LOG_TARGET: &str = "libcosmic::widget::dnd_destination";
32#[cfg(xdg_portal)]
33pub const FILE_TRANSFER_MIME: &str = "application/vnd.portal.filetransfer";
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub struct DragId(pub u128);
37
38impl DragId {
39    pub fn new() -> Self {
40        DragId(u128::from(u64::MAX) + u128::from(DRAG_ID_COUNTER.fetch_add(1, Ordering::Relaxed)))
41    }
42}
43
44#[allow(clippy::new_without_default)]
45impl Default for DragId {
46    fn default() -> Self {
47        DragId::new()
48    }
49}
50
51pub struct DndDestination<'a, Message> {
52    id: Id,
53    drag_id: Option<u64>,
54    preferred_action: DndAction,
55    action: DndAction,
56    container: Element<'a, Message>,
57    mime_types: Vec<Cow<'static, str>>,
58    forward_drag_as_cursor: bool,
59    on_hold: Option<Box<dyn Fn(f64, f64) -> Message>>,
60    on_drop: Option<Box<dyn Fn(f64, f64) -> Message>>,
61    on_enter: Option<Box<dyn Fn(f64, f64, Vec<String>) -> Message>>,
62    on_leave: Option<Box<dyn Fn() -> Message>>,
63    on_motion: Option<Box<dyn Fn(f64, f64) -> Message>>,
64    on_action_selected: Option<Box<dyn Fn(DndAction) -> Message>>,
65    on_data_received: Option<Box<dyn Fn(String, Vec<u8>) -> Message>>,
66    on_finish: Option<Box<dyn Fn(String, Vec<u8>, DndAction, f64, f64) -> Message>>,
67    #[cfg(xdg_portal)]
68    on_file_transfer: Option<Box<dyn Fn(String) -> Message>>,
69}
70
71impl<'a, Message: 'static> DndDestination<'a, Message> {
72    fn mime_matches(&self, offered: &[String]) -> bool {
73        self.mime_types.is_empty()
74            || offered
75                .iter()
76                .any(|mime| self.mime_types.iter().any(|allowed| allowed == mime))
77    }
78    pub fn new(child: impl Into<Element<'a, Message>>, mimes: Vec<Cow<'static, str>>) -> Self {
79        Self {
80            id: Id::unique(),
81            drag_id: None,
82            mime_types: mimes,
83            preferred_action: DndAction::Move,
84            action: DndAction::Copy | DndAction::Move,
85            container: child.into(),
86            forward_drag_as_cursor: false,
87            on_hold: None,
88            on_drop: None,
89            on_enter: None,
90            on_leave: None,
91            on_motion: None,
92            on_action_selected: None,
93            on_data_received: None,
94            on_finish: None,
95            #[cfg(xdg_portal)]
96            on_file_transfer: None,
97        }
98    }
99
100    pub fn for_data<T: AllowedMimeTypes>(
101        child: impl Into<Element<'a, Message>>,
102        on_finish: impl Fn(Option<T>, DndAction) -> Message + 'static,
103    ) -> Self {
104        Self {
105            id: Id::unique(),
106            drag_id: None,
107            mime_types: T::allowed().iter().cloned().map(Cow::Owned).collect(),
108            preferred_action: DndAction::Move,
109            action: DndAction::Copy | DndAction::Move,
110            container: child.into(),
111            forward_drag_as_cursor: false,
112            on_hold: None,
113            on_drop: None,
114            on_enter: None,
115            on_leave: None,
116            on_motion: None,
117            on_action_selected: None,
118            on_data_received: None,
119            on_finish: Some(Box::new(move |mime, data, action, _, _| {
120                on_finish(T::try_from((data, mime)).ok(), action)
121            })),
122            #[cfg(xdg_portal)]
123            on_file_transfer: None,
124        }
125    }
126
127    #[must_use]
128    pub fn data_received_for<T: AllowedMimeTypes>(
129        mut self,
130        f: impl Fn(Option<T>) -> Message + 'static,
131    ) -> Self {
132        self.on_data_received = Some(Box::new(
133            move |mime, data| f(T::try_from((data, mime)).ok()),
134        ));
135        self
136    }
137
138    pub fn with_id(
139        child: impl Into<Element<'a, Message>>,
140        id: Id,
141        mimes: Vec<Cow<'static, str>>,
142    ) -> Self {
143        Self {
144            id,
145            drag_id: None,
146            mime_types: mimes,
147            preferred_action: DndAction::Move,
148            action: DndAction::Copy | DndAction::Move,
149            container: child.into(),
150            forward_drag_as_cursor: false,
151            on_hold: None,
152            on_drop: None,
153            on_enter: None,
154            on_leave: None,
155            on_motion: None,
156            on_action_selected: None,
157            on_data_received: None,
158            on_finish: None,
159            #[cfg(xdg_portal)]
160            on_file_transfer: None,
161        }
162    }
163
164    #[must_use]
165    pub fn drag_id(mut self, id: u64) -> Self {
166        self.drag_id = Some(id);
167        self
168    }
169
170    #[must_use]
171    pub fn action(mut self, action: DndAction) -> Self {
172        self.action = action;
173        self
174    }
175
176    #[must_use]
177    pub fn preferred_action(mut self, action: DndAction) -> Self {
178        self.preferred_action = action;
179        self
180    }
181
182    #[must_use]
183    pub fn forward_drag_as_cursor(mut self, forward: bool) -> Self {
184        self.forward_drag_as_cursor = forward;
185        self
186    }
187
188    #[must_use]
189    pub fn on_hold(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self {
190        self.on_hold = Some(Box::new(f));
191        self
192    }
193
194    #[must_use]
195    pub fn on_drop(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self {
196        self.on_drop = Some(Box::new(f));
197        self
198    }
199
200    #[must_use]
201    pub fn on_enter(mut self, f: impl Fn(f64, f64, Vec<String>) -> Message + 'static) -> Self {
202        self.on_enter = Some(Box::new(f));
203        self
204    }
205
206    #[must_use]
207    pub fn on_leave(mut self, m: impl Fn() -> Message + 'static) -> Self {
208        self.on_leave = Some(Box::new(m));
209        self
210    }
211
212    #[must_use]
213    pub fn on_finish(
214        mut self,
215        f: impl Fn(String, Vec<u8>, DndAction, f64, f64) -> Message + 'static,
216    ) -> Self {
217        self.on_finish = Some(Box::new(f));
218        self
219    }
220
221    #[must_use]
222    pub fn on_motion(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self {
223        self.on_motion = Some(Box::new(f));
224        self
225    }
226
227    #[must_use]
228    pub fn on_action_selected(mut self, f: impl Fn(DndAction) -> Message + 'static) -> Self {
229        self.on_action_selected = Some(Box::new(f));
230        self
231    }
232
233    #[must_use]
234    pub fn on_data_received(mut self, f: impl Fn(String, Vec<u8>) -> Message + 'static) -> Self {
235        self.on_data_received = Some(Box::new(f));
236        self
237    }
238
239    /// Add a message that will be emitted instead of [`on_data_received`](Self::on_data_received) if the dropped files
240    /// are offered through the xdg share portal. You can then use [`crate::command::file_transfer_receive`]
241    /// with the key to receive the files.
242    #[cfg(xdg_portal)]
243    #[must_use]
244    pub fn on_file_transfer(mut self, f: impl Fn(String) -> Message + 'static) -> Self {
245        match self.mime_types.iter().position(|v| v == "text/uri-list") {
246            Some(i) => self.mime_types.insert(i, Cow::Borrowed(FILE_TRANSFER_MIME)),
247            None => self.mime_types.push(Cow::Borrowed(FILE_TRANSFER_MIME)),
248        }
249        self.on_file_transfer = Some(Box::new(f));
250        self
251    }
252
253    /// Returns the drag id of the destination.
254    ///
255    /// # Panics
256    /// Panics if the destination has been assigned a Set id, which is invalid.
257    #[must_use]
258    pub fn get_drag_id(&self) -> u128 {
259        u128::from(self.drag_id.unwrap_or_else(|| match &self.id.0 {
260            Internal::Unique(id) | Internal::Custom(id, _) => *id,
261            Internal::Set(_) => panic!("Invalid Id assigned to dnd destination."),
262        }))
263    }
264
265    pub fn id(mut self, id: Id) -> Self {
266        self.id = id;
267        self
268    }
269}
270
271impl<Message: 'static> Widget<Message, crate::Theme, crate::Renderer>
272    for DndDestination<'_, Message>
273{
274    fn children(&self) -> Vec<Tree> {
275        vec![Tree::new(&self.container)]
276    }
277
278    fn tag(&self) -> iced_core::widget::tree::Tag {
279        tree::Tag::of::<State<()>>()
280    }
281
282    fn diff(&mut self, tree: &mut Tree) {
283        tree.diff_children(std::slice::from_mut(&mut self.container));
284    }
285
286    fn state(&self) -> iced_core::widget::tree::State {
287        tree::State::new(State::<()>::new())
288    }
289
290    fn size(&self) -> iced_core::Size<Length> {
291        self.container.as_widget().size()
292    }
293
294    fn layout(
295        &mut self,
296        tree: &mut Tree,
297        renderer: &crate::Renderer,
298        limits: &layout::Limits,
299    ) -> layout::Node {
300        self.container
301            .as_widget_mut()
302            .layout(&mut tree.children[0], renderer, limits)
303    }
304
305    fn operate(
306        &mut self,
307        tree: &mut Tree,
308        layout: layout::Layout<'_>,
309        renderer: &crate::Renderer,
310        operation: &mut dyn iced_core::widget::Operation<()>,
311    ) {
312        self.container
313            .as_widget_mut()
314            .operate(&mut tree.children[0], layout, renderer, operation);
315    }
316
317    #[allow(clippy::too_many_lines)]
318    fn update(
319        &mut self,
320        tree: &mut Tree,
321        event: &Event,
322        layout: layout::Layout<'_>,
323        cursor: mouse::Cursor,
324        renderer: &crate::Renderer,
325        clipboard: &mut dyn Clipboard,
326        shell: &mut Shell<'_, Message>,
327        viewport: &Rectangle,
328    ) {
329        self.container.as_widget_mut().update(
330            &mut tree.children[0],
331            event,
332            layout,
333            cursor,
334            renderer,
335            clipboard,
336            shell,
337            viewport,
338        );
339        if shell.is_event_captured() {
340            return;
341        }
342
343        let state = tree.state.downcast_mut::<State<()>>();
344
345        let my_id = self.get_drag_id();
346
347        log::trace!(
348            target: DND_DEST_LOG_TARGET,
349            "dnd_destination id={:?}: event {:?}",
350            self.drag_id.unwrap_or_default(),
351            event
352        );
353        match event {
354            Event::Dnd(DndEvent::Offer(
355                id,
356                OfferEvent::Enter {
357                    x, y, mime_types, ..
358                },
359            )) if *id == Some(my_id) => {
360                if !self.mime_matches(mime_types) {
361                    log::trace!(
362                        target: DND_DEST_LOG_TARGET,
363                        "offer enter id={my_id:?} ignored (mimes={mime_types:?} not in {:?})",
364                        self.mime_types
365                    );
366                    return;
367                }
368                log::trace!(
369                    target: DND_DEST_LOG_TARGET,
370                    "offer enter id={my_id:?} coords=({x},{y}) mimes={mime_types:?}"
371                );
372                if let Some(msg) = state.on_enter(
373                    *x,
374                    *y,
375                    mime_types.clone(),
376                    self.on_enter.as_ref().map(std::convert::AsRef::as_ref),
377                    (),
378                ) {
379                    shell.publish(msg);
380                }
381                if self.forward_drag_as_cursor {
382                    #[allow(clippy::cast_possible_truncation)]
383                    let drag_cursor = mouse::Cursor::Available((*x as f32, *y as f32).into());
384                    let event = Event::Mouse(mouse::Event::CursorMoved {
385                        position: drag_cursor.position().unwrap(),
386                    });
387                    self.container.as_widget_mut().update(
388                        &mut tree.children[0],
389                        &event,
390                        layout,
391                        drag_cursor,
392                        renderer,
393                        clipboard,
394                        shell,
395                        viewport,
396                    );
397                }
398                shell.capture_event();
399            }
400            Event::Dnd(DndEvent::Offer(_, OfferEvent::Leave)) => {
401                log::trace!(
402                    target: DND_DEST_LOG_TARGET,
403                    "offer leave id={:?}",
404                    my_id
405                );
406                if let Some(msg) =
407                    state.on_leave(self.on_leave.as_ref().map(std::convert::AsRef::as_ref))
408                {
409                    shell.publish(msg);
410                }
411
412                if self.forward_drag_as_cursor {
413                    let drag_cursor = mouse::Cursor::Unavailable;
414                    let event = Event::Mouse(mouse::Event::CursorLeft);
415                    self.container.as_widget_mut().update(
416                        &mut tree.children[0],
417                        &event,
418                        layout,
419                        drag_cursor,
420                        renderer,
421                        clipboard,
422                        shell,
423                        viewport,
424                    );
425                }
426            }
427            Event::Dnd(DndEvent::Offer(id, OfferEvent::Motion { x, y })) if *id == Some(my_id) => {
428                log::trace!(
429                    target: DND_DEST_LOG_TARGET,
430                    "offer motion id={my_id:?} coords=({x},{y})"
431                );
432                if let Some(msg) = state.on_motion(
433                    *x,
434                    *y,
435                    self.on_motion.as_ref().map(std::convert::AsRef::as_ref),
436                    self.on_enter.as_ref().map(std::convert::AsRef::as_ref),
437                    (),
438                ) {
439                    shell.publish(msg);
440                }
441
442                if self.forward_drag_as_cursor {
443                    #[allow(clippy::cast_possible_truncation)]
444                    let drag_cursor = mouse::Cursor::Available((*x as f32, *y as f32).into());
445                    let event = Event::Mouse(mouse::Event::CursorMoved {
446                        position: drag_cursor.position().unwrap(),
447                    });
448                    self.container.as_widget_mut().update(
449                        &mut tree.children[0],
450                        &event,
451                        layout,
452                        drag_cursor,
453                        renderer,
454                        clipboard,
455                        shell,
456                        viewport,
457                    );
458                }
459                shell.capture_event();
460            }
461            Event::Dnd(DndEvent::Offer(_, OfferEvent::LeaveDestination)) => {
462                log::trace!(
463                    target: DND_DEST_LOG_TARGET,
464                    "offer leave-destination id={:?}",
465                    my_id
466                );
467                if let Some(msg) =
468                    state.on_leave(self.on_leave.as_ref().map(std::convert::AsRef::as_ref))
469                {
470                    shell.publish(msg);
471                }
472            }
473            Event::Dnd(DndEvent::Offer(id, OfferEvent::Drop)) if *id == Some(my_id) => {
474                log::trace!(
475                    target: DND_DEST_LOG_TARGET,
476                    "offer drop id={my_id:?}"
477                );
478                if let Some(msg) =
479                    state.on_drop(self.on_drop.as_ref().map(std::convert::AsRef::as_ref))
480                {
481                    shell.publish(msg);
482                }
483                shell.capture_event();
484            }
485            Event::Dnd(DndEvent::Offer(id, OfferEvent::SelectedAction(action)))
486                if *id == Some(my_id) =>
487            {
488                log::trace!(
489                    target: DND_DEST_LOG_TARGET,
490                    "offer selected-action id={my_id:?} action={action:?}"
491                );
492                if let Some(msg) = state.on_action_selected(
493                    *action,
494                    self.on_action_selected
495                        .as_ref()
496                        .map(std::convert::AsRef::as_ref),
497                ) {
498                    shell.publish(msg);
499                }
500                shell.capture_event();
501            }
502            Event::Dnd(DndEvent::Offer(id, OfferEvent::Data { data, mime_type }))
503                if *id == Some(my_id) =>
504            {
505                log::trace!(
506                    target: DND_DEST_LOG_TARGET,
507                    "offer data id={my_id:?} mime={mime_type:?} bytes={}",
508                    data.len()
509                );
510
511                #[cfg(xdg_portal)]
512                if mime_type == FILE_TRANSFER_MIME
513                    && let Some(f) = self.on_file_transfer.as_ref()
514                    && let Ok(s) = String::from_utf8(data[..data.len() - 1].to_vec())
515                {
516                    shell.publish(f(s));
517                    shell.capture_event();
518                    return;
519                }
520
521                if let (Some(msg), ret) = state.on_data_received(
522                    mime_type.clone(),
523                    data.clone(),
524                    self.on_data_received
525                        .as_ref()
526                        .map(std::convert::AsRef::as_ref),
527                    self.on_finish.as_ref().map(std::convert::AsRef::as_ref),
528                ) {
529                    shell.publish(msg);
530                    if ret == event::Status::Captured {
531                        log::trace!(
532                            target: DND_DEST_LOG_TARGET,
533                            "offer data id={my_id:?} captured"
534                        );
535                        shell.capture_event();
536                    }
537                    return;
538                }
539                shell.capture_event();
540            }
541            _ => {}
542        }
543    }
544
545    fn mouse_interaction(
546        &self,
547        tree: &Tree,
548        layout: layout::Layout<'_>,
549        cursor_position: mouse::Cursor,
550        viewport: &Rectangle,
551        renderer: &crate::Renderer,
552    ) -> mouse::Interaction {
553        self.container.as_widget().mouse_interaction(
554            &tree.children[0],
555            layout,
556            cursor_position,
557            viewport,
558            renderer,
559        )
560    }
561
562    fn draw(
563        &self,
564        tree: &Tree,
565        renderer: &mut crate::Renderer,
566        theme: &crate::Theme,
567        renderer_style: &iced_core::renderer::Style,
568        layout: layout::Layout<'_>,
569        cursor_position: mouse::Cursor,
570        viewport: &Rectangle,
571    ) {
572        self.container.as_widget().draw(
573            &tree.children[0],
574            renderer,
575            theme,
576            renderer_style,
577            layout,
578            cursor_position,
579            viewport,
580        );
581    }
582
583    fn overlay<'b>(
584        &'b mut self,
585        tree: &'b mut Tree,
586        layout: layout::Layout<'b>,
587        renderer: &crate::Renderer,
588        viewport: &Rectangle,
589        translation: Vector,
590    ) -> Option<overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
591        self.container.as_widget_mut().overlay(
592            &mut tree.children[0],
593            layout,
594            renderer,
595            viewport,
596            translation,
597        )
598    }
599
600    fn drag_destinations(
601        &self,
602        state: &Tree,
603        layout: layout::Layout<'_>,
604        renderer: &crate::Renderer,
605        dnd_rectangles: &mut iced_core::clipboard::DndDestinationRectangles,
606    ) {
607        let bounds = layout.bounds();
608        let my_id = self.get_drag_id();
609        log::trace!(
610            target: DND_DEST_LOG_TARGET,
611            "register destination id={:?} bounds=({:.2},{:.2},{:.2},{:.2}) mimes={:?}",
612            my_id,
613            bounds.x,
614            bounds.y,
615            bounds.width,
616            bounds.height,
617            self.mime_types
618        );
619        let my_dest = DndDestinationRectangle {
620            id: my_id,
621            rectangle: dnd::Rectangle {
622                x: f64::from(bounds.x),
623                y: f64::from(bounds.y),
624                width: f64::from(bounds.width),
625                height: f64::from(bounds.height),
626            },
627            mime_types: self.mime_types.clone(),
628            actions: self.action,
629            preferred: self.preferred_action,
630        };
631        dnd_rectangles.push(my_dest);
632
633        self.container.as_widget().drag_destinations(
634            &state.children[0],
635            layout,
636            renderer,
637            dnd_rectangles,
638        );
639    }
640
641    fn id(&self) -> Option<Id> {
642        Some(self.id.clone())
643    }
644
645    fn set_id(&mut self, id: Id) {
646        self.id = id;
647    }
648
649    #[cfg(feature = "a11y")]
650    /// get the a11y nodes for the widget
651    fn a11y_nodes(
652        &self,
653        layout: iced_core::Layout<'_>,
654        state: &Tree,
655        p: mouse::Cursor,
656    ) -> iced_accessibility::A11yTree {
657        let c_state = &state.children[0];
658        self.container.as_widget().a11y_nodes(layout, c_state, p)
659    }
660}
661
662#[derive(Default)]
663pub struct State<T> {
664    pub drag_offer: Option<DragOffer<T>>,
665}
666
667pub struct DragOffer<T> {
668    pub x: f64,
669    pub y: f64,
670    pub dropped: bool,
671    pub selected_action: DndAction,
672    pub data: T,
673}
674
675impl<T> State<T> {
676    #[must_use]
677    pub fn new() -> Self {
678        Self { drag_offer: None }
679    }
680
681    pub fn on_enter<Message>(
682        &mut self,
683        x: f64,
684        y: f64,
685        mime_types: Vec<String>,
686        on_enter: Option<impl Fn(f64, f64, Vec<String>) -> Message>,
687        data: T,
688    ) -> Option<Message> {
689        self.drag_offer = Some(DragOffer {
690            x,
691            y,
692            dropped: false,
693            selected_action: DndAction::empty(),
694            data,
695        });
696        on_enter.map(|f| f(x, y, mime_types))
697    }
698
699    pub fn on_leave<Message>(&mut self, on_leave: Option<&dyn Fn() -> Message>) -> Option<Message> {
700        if self.drag_offer.as_ref().is_some_and(|d| !d.dropped) {
701            self.drag_offer = None;
702            on_leave.map(|f| f())
703        } else {
704            None
705        }
706    }
707
708    pub fn on_motion<Message>(
709        &mut self,
710        x: f64,
711        y: f64,
712        on_motion: Option<impl Fn(f64, f64) -> Message>,
713        on_enter: Option<impl Fn(f64, f64, Vec<String>) -> Message>,
714        data: T,
715    ) -> Option<Message> {
716        if let Some(s) = self.drag_offer.as_mut() {
717            s.x = x;
718            s.y = y;
719        } else {
720            self.drag_offer = Some(DragOffer {
721                x,
722                y,
723                dropped: false,
724                selected_action: DndAction::empty(),
725                data,
726            });
727            if let Some(f) = on_enter {
728                return Some(f(x, y, vec![]));
729            }
730        }
731        on_motion.map(|f| f(x, y))
732    }
733
734    pub fn on_drop<Message>(
735        &mut self,
736        on_drop: Option<impl Fn(f64, f64) -> Message>,
737    ) -> Option<Message> {
738        if let Some(offer) = self.drag_offer.as_mut() {
739            offer.dropped = true;
740            if let Some(f) = on_drop {
741                return Some(f(offer.x, offer.y));
742            }
743        }
744        None
745    }
746
747    pub fn on_action_selected<Message>(
748        &mut self,
749        action: DndAction,
750        on_action_selected: Option<impl Fn(DndAction) -> Message>,
751    ) -> Option<Message> {
752        if let Some(s) = self.drag_offer.as_mut() {
753            s.selected_action = action;
754        }
755        if let Some(f) = on_action_selected {
756            f(action).into()
757        } else {
758            None
759        }
760    }
761
762    pub fn on_data_received<Message>(
763        &mut self,
764        mime: String,
765        data: Vec<u8>,
766        on_data_received: Option<impl Fn(String, Vec<u8>) -> Message>,
767        on_finish: Option<impl Fn(String, Vec<u8>, DndAction, f64, f64) -> Message>,
768    ) -> (Option<Message>, event::Status) {
769        let Some(dnd) = self.drag_offer.as_ref() else {
770            self.drag_offer = None;
771            return (None, event::Status::Ignored);
772        };
773
774        if dnd.dropped {
775            let ret = (
776                on_finish.map(|f| f(mime, data, dnd.selected_action, dnd.x, dnd.y)),
777                event::Status::Captured,
778            );
779            self.drag_offer = None;
780            ret
781        } else if let Some(f) = on_data_received {
782            (Some(f(mime, data)), event::Status::Captured)
783        } else {
784            (None, event::Status::Ignored)
785        }
786    }
787}
788
789impl<'a, Message: 'static> From<DndDestination<'a, Message>> for Element<'a, Message> {
790    fn from(wrapper: DndDestination<'a, Message>) -> Self {
791        Element::new(wrapper)
792    }
793}
794
795#[cfg(test)]
796mod tests {
797    use super::*;
798
799    #[derive(Clone, Copy, Debug, PartialEq)]
800    enum TestMsg {
801        Data,
802        Finished,
803    }
804
805    #[test]
806    fn data_before_drop_invokes_data_handler_only() {
807        let mut state: State<()> = State::new();
808        assert!(state.drag_offer.is_none());
809        state.on_enter::<TestMsg>(
810            4.0,
811            2.0,
812            vec!["text/plain".into()],
813            Option::<fn(_, _, _) -> TestMsg>::None,
814            (),
815        );
816        let (message, status) = state.on_data_received(
817            "text/plain".into(),
818            vec![1],
819            Some(|mime, data| {
820                assert_eq!(mime, "text/plain");
821                assert_eq!(data, vec![1]);
822                TestMsg::Data
823            }),
824            Option::<fn(_, _, _, _, _) -> TestMsg>::None,
825        );
826        assert!(matches!(message, Some(TestMsg::Data)));
827        assert_eq!(status, event::Status::Captured);
828        assert!(state.drag_offer.is_some());
829    }
830
831    #[test]
832    fn finish_only_emits_after_drop() {
833        let mut state: State<()> = State::new();
834        state.on_enter::<TestMsg>(
835            5.0,
836            -1.0,
837            vec![],
838            Option::<fn(_, _, _) -> TestMsg>::None,
839            (),
840        );
841        state.on_action_selected::<TestMsg>(DndAction::Move, Option::<fn(_) -> TestMsg>::None);
842        state.on_drop::<TestMsg>(Option::<fn(_, _) -> TestMsg>::None);
843
844        let (message, status) = state.on_data_received(
845            "application/x-test".into(),
846            vec![7],
847            Option::<fn(_, _) -> TestMsg>::None,
848            Some(|mime, data, action, x, y| {
849                assert_eq!(mime, "application/x-test");
850                assert_eq!(data, vec![7]);
851                assert_eq!(action, DndAction::Move);
852                assert_eq!(x, 5.0);
853                assert_eq!(y, -1.0);
854                TestMsg::Finished
855            }),
856        );
857        assert!(matches!(message, Some(TestMsg::Finished)));
858        assert_eq!(status, event::Status::Captured);
859        assert!(state.drag_offer.is_none());
860    }
861}