1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
use std::{
    borrow::Cow,
    sync::atomic::{AtomicU64, Ordering},
};

use crate::{
    iced::{
        clipboard::{
            dnd::{self, DndAction, DndDestinationRectangle, DndEvent, OfferEvent},
            mime::AllowedMimeTypes,
        },
        event,
        id::Internal,
        mouse, overlay, Event, Length, Rectangle,
    },
    iced_core::{
        self, layout,
        widget::{tree, Tree},
        Clipboard, Shell,
    },
    widget::{Id, Widget},
    Element,
};

pub fn dnd_destination<'a, Message: 'static>(
    child: impl Into<Element<'a, Message>>,
    mimes: Vec<Cow<'static, str>>,
) -> DndDestination<'a, Message> {
    DndDestination::new(child, mimes)
}

pub fn dnd_destination_for_data<T: AllowedMimeTypes, Message: 'static>(
    child: impl Into<Element<'static, Message>>,
    on_finish: impl Fn(Option<T>, DndAction) -> Message + 'static,
) -> DndDestination<'static, Message> {
    DndDestination::for_data(child, on_finish)
}

static DRAG_ID_COUNTER: AtomicU64 = AtomicU64::new(0);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DragId(pub u128);

impl DragId {
    pub fn new() -> Self {
        DragId(u128::from(u64::MAX) + u128::from(DRAG_ID_COUNTER.fetch_add(1, Ordering::Relaxed)))
    }
}

#[allow(clippy::new_without_default)]
impl Default for DragId {
    fn default() -> Self {
        DragId::new()
    }
}

pub struct DndDestination<'a, Message> {
    id: Id,
    drag_id: Option<u64>,
    preferred_action: DndAction,
    action: DndAction,
    container: Element<'a, Message>,
    mime_types: Vec<Cow<'static, str>>,
    forward_drag_as_cursor: bool,
    on_hold: Option<Box<dyn Fn(f64, f64) -> Message>>,
    on_drop: Option<Box<dyn Fn(f64, f64) -> Message>>,
    on_enter: Option<Box<dyn Fn(f64, f64, Vec<String>) -> Message>>,
    on_leave: Option<Box<dyn Fn() -> Message>>,
    on_motion: Option<Box<dyn Fn(f64, f64) -> Message>>,
    on_action_selected: Option<Box<dyn Fn(DndAction) -> Message>>,
    on_data_received: Option<Box<dyn Fn(String, Vec<u8>) -> Message>>,
    on_finish: Option<Box<dyn Fn(String, Vec<u8>, DndAction, f64, f64) -> Message>>,
}

impl<'a, Message: 'static> DndDestination<'a, Message> {
    pub fn new(child: impl Into<Element<'a, Message>>, mimes: Vec<Cow<'static, str>>) -> Self {
        Self {
            id: Id::unique(),
            drag_id: None,
            mime_types: mimes,
            preferred_action: DndAction::Move,
            action: DndAction::Copy | DndAction::Move,
            container: child.into(),
            forward_drag_as_cursor: false,
            on_hold: None,
            on_drop: None,
            on_enter: None,
            on_leave: None,
            on_motion: None,
            on_action_selected: None,
            on_data_received: None,
            on_finish: None,
        }
    }

    pub fn for_data<T: AllowedMimeTypes>(
        child: impl Into<Element<'a, Message>>,
        on_finish: impl Fn(Option<T>, DndAction) -> Message + 'static,
    ) -> Self {
        Self {
            id: Id::unique(),
            drag_id: None,
            mime_types: T::allowed().iter().cloned().map(Cow::Owned).collect(),
            preferred_action: DndAction::Move,
            action: DndAction::Copy | DndAction::Move,
            container: child.into(),
            forward_drag_as_cursor: false,
            on_hold: None,
            on_drop: None,
            on_enter: None,
            on_leave: None,
            on_motion: None,
            on_action_selected: None,
            on_data_received: None,
            on_finish: Some(Box::new(move |mime, data, action, _, _| {
                on_finish(T::try_from((data, mime)).ok(), action)
            })),
        }
    }

    #[must_use]
    pub fn data_received_for<T: AllowedMimeTypes>(
        mut self,
        f: impl Fn(Option<T>) -> Message + 'static,
    ) -> Self {
        self.on_data_received = Some(Box::new(
            move |mime, data| f(T::try_from((data, mime)).ok()),
        ));
        self
    }

    pub fn with_id(
        child: impl Into<Element<'a, Message>>,
        id: Id,
        mimes: Vec<Cow<'static, str>>,
    ) -> Self {
        Self {
            id,
            drag_id: None,
            mime_types: mimes,
            preferred_action: DndAction::Move,
            action: DndAction::Copy | DndAction::Move,
            container: child.into(),
            forward_drag_as_cursor: false,
            on_hold: None,
            on_drop: None,
            on_enter: None,
            on_leave: None,
            on_motion: None,
            on_action_selected: None,
            on_data_received: None,
            on_finish: None,
        }
    }

    #[must_use]
    pub fn drag_id(mut self, id: u64) -> Self {
        self.drag_id = Some(id);
        self
    }

    #[must_use]
    pub fn action(mut self, action: DndAction) -> Self {
        self.action = action;
        self
    }

    #[must_use]
    pub fn preferred_action(mut self, action: DndAction) -> Self {
        self.preferred_action = action;
        self
    }

    #[must_use]
    pub fn forward_drag_as_cursor(mut self, forward: bool) -> Self {
        self.forward_drag_as_cursor = forward;
        self
    }

    #[must_use]
    pub fn on_hold(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self {
        self.on_hold = Some(Box::new(f));
        self
    }

    #[must_use]
    pub fn on_drop(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self {
        self.on_drop = Some(Box::new(f));
        self
    }

    #[must_use]
    pub fn on_enter(mut self, f: impl Fn(f64, f64, Vec<String>) -> Message + 'static) -> Self {
        self.on_enter = Some(Box::new(f));
        self
    }

    #[must_use]
    pub fn on_leave(mut self, m: impl Fn() -> Message + 'static) -> Self {
        self.on_leave = Some(Box::new(m));
        self
    }

    #[must_use]
    pub fn on_finish(
        mut self,
        f: impl Fn(String, Vec<u8>, DndAction, f64, f64) -> Message + 'static,
    ) -> Self {
        self.on_finish = Some(Box::new(f));
        self
    }

    #[must_use]
    pub fn on_motion(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self {
        self.on_motion = Some(Box::new(f));
        self
    }

    #[must_use]
    pub fn on_action_selected(mut self, f: impl Fn(DndAction) -> Message + 'static) -> Self {
        self.on_action_selected = Some(Box::new(f));
        self
    }

    #[must_use]
    pub fn on_data_received(mut self, f: impl Fn(String, Vec<u8>) -> Message + 'static) -> Self {
        self.on_data_received = Some(Box::new(f));
        self
    }

    /// Returns the drag id of the destination.
    ///
    /// # Panics
    /// Panics if the destination has been assigned a Set id, which is invalid.
    #[must_use]
    pub fn get_drag_id(&self) -> u128 {
        u128::from(self.drag_id.unwrap_or_else(|| match &self.id.0 {
            Internal::Unique(id) | Internal::Custom(id, _) => *id,
            Internal::Set(_) => panic!("Invalid Id assigned to dnd destination."),
        }))
    }
}

impl<'a, Message: 'static> Widget<Message, crate::Theme, crate::Renderer>
    for DndDestination<'a, Message>
{
    fn children(&self) -> Vec<Tree> {
        vec![Tree::new(&self.container)]
    }

    fn tag(&self) -> iced_core::widget::tree::Tag {
        tree::Tag::of::<State<()>>()
    }

    fn diff(&mut self, tree: &mut Tree) {
        tree.children[0].diff(self.container.as_widget_mut());
    }

    fn state(&self) -> iced_core::widget::tree::State {
        tree::State::new(State::<()>::new())
    }

    fn size(&self) -> iced_core::Size<Length> {
        self.container.as_widget().size()
    }

    fn layout(
        &self,
        tree: &mut Tree,
        renderer: &crate::Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        self.container
            .as_widget()
            .layout(&mut tree.children[0], renderer, limits)
    }

    fn operate(
        &self,
        tree: &mut Tree,
        layout: layout::Layout<'_>,
        renderer: &crate::Renderer,
        operation: &mut dyn iced_core::widget::Operation<
            iced_core::widget::OperationOutputWrapper<Message>,
        >,
    ) {
        self.container
            .as_widget()
            .operate(&mut tree.children[0], layout, renderer, operation);
    }

    #[allow(clippy::too_many_lines)]
    fn on_event(
        &mut self,
        tree: &mut Tree,
        event: Event,
        layout: layout::Layout<'_>,
        cursor: mouse::Cursor,
        renderer: &crate::Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) -> event::Status {
        let s = self.container.as_widget_mut().on_event(
            &mut tree.children[0],
            event.clone(),
            layout,
            cursor,
            renderer,
            clipboard,
            shell,
            viewport,
        );
        if matches!(s, event::Status::Captured) {
            return event::Status::Captured;
        }

        let state = tree.state.downcast_mut::<State<()>>();

        let my_id = self.get_drag_id();

        match event {
            Event::Dnd(DndEvent::Offer(
                id,
                OfferEvent::Enter {
                    x, y, mime_types, ..
                },
            )) if id == Some(my_id) => {
                if let Some(msg) = state.on_enter(
                    x,
                    y,
                    mime_types,
                    self.on_enter.as_ref().map(std::convert::AsRef::as_ref),
                    (),
                ) {
                    shell.publish(msg);
                }
                if self.forward_drag_as_cursor {
                    #[allow(clippy::cast_possible_truncation)]
                    let drag_cursor = mouse::Cursor::Available((x as f32, y as f32).into());
                    let event = Event::Mouse(mouse::Event::CursorMoved {
                        position: drag_cursor.position().unwrap(),
                    });
                    self.container.as_widget_mut().on_event(
                        &mut tree.children[0],
                        event,
                        layout,
                        drag_cursor,
                        renderer,
                        clipboard,
                        shell,
                        viewport,
                    );
                }
                return event::Status::Captured;
            }
            Event::Dnd(DndEvent::Offer(id, OfferEvent::Leave)) if id == Some(my_id) => {
                state.on_leave(self.on_leave.as_ref().map(std::convert::AsRef::as_ref));

                if self.forward_drag_as_cursor {
                    let drag_cursor = mouse::Cursor::Unavailable;
                    let event = Event::Mouse(mouse::Event::CursorLeft);
                    self.container.as_widget_mut().on_event(
                        &mut tree.children[0],
                        event,
                        layout,
                        drag_cursor,
                        renderer,
                        clipboard,
                        shell,
                        viewport,
                    );
                }
                return event::Status::Captured;
            }
            Event::Dnd(DndEvent::Offer(id, OfferEvent::Motion { x, y })) if id == Some(my_id) => {
                if let Some(msg) = state.on_motion(
                    x,
                    y,
                    self.on_motion.as_ref().map(std::convert::AsRef::as_ref),
                    self.on_enter.as_ref().map(std::convert::AsRef::as_ref),
                    (),
                ) {
                    shell.publish(msg);
                }

                if self.forward_drag_as_cursor {
                    #[allow(clippy::cast_possible_truncation)]
                    let drag_cursor = mouse::Cursor::Available((x as f32, y as f32).into());
                    let event = Event::Mouse(mouse::Event::CursorMoved {
                        position: drag_cursor.position().unwrap(),
                    });
                    self.container.as_widget_mut().on_event(
                        &mut tree.children[0],
                        event,
                        layout,
                        drag_cursor,
                        renderer,
                        clipboard,
                        shell,
                        viewport,
                    );
                }
                return event::Status::Captured;
            }
            Event::Dnd(DndEvent::Offer(id, OfferEvent::LeaveDestination)) if id == Some(my_id) => {
                if let Some(msg) =
                    state.on_leave(self.on_leave.as_ref().map(std::convert::AsRef::as_ref))
                {
                    shell.publish(msg);
                }
                return event::Status::Captured;
            }
            Event::Dnd(DndEvent::Offer(id, OfferEvent::Drop)) if id == Some(my_id) => {
                if let Some(msg) =
                    state.on_drop(self.on_drop.as_ref().map(std::convert::AsRef::as_ref))
                {
                    shell.publish(msg);
                }
                return event::Status::Captured;
            }
            Event::Dnd(DndEvent::Offer(id, OfferEvent::SelectedAction(action)))
                if id == Some(my_id) =>
            {
                if let Some(msg) = state.on_action_selected(
                    action,
                    self.on_action_selected
                        .as_ref()
                        .map(std::convert::AsRef::as_ref),
                ) {
                    shell.publish(msg);
                }
                return event::Status::Captured;
            }
            Event::Dnd(DndEvent::Offer(id, OfferEvent::Data { data, mime_type }))
                if id == Some(my_id) =>
            {
                if let (Some(msg), ret) = state.on_data_received(
                    mime_type,
                    data,
                    self.on_data_received
                        .as_ref()
                        .map(std::convert::AsRef::as_ref),
                    self.on_finish.as_ref().map(std::convert::AsRef::as_ref),
                ) {
                    shell.publish(msg);
                    return ret;
                }
                return event::Status::Captured;
            }
            _ => {}
        }
        event::Status::Ignored
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: layout::Layout<'_>,
        cursor_position: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &crate::Renderer,
    ) -> mouse::Interaction {
        self.container.as_widget().mouse_interaction(
            &tree.children[0],
            layout,
            cursor_position,
            viewport,
            renderer,
        )
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut crate::Renderer,
        theme: &crate::Theme,
        renderer_style: &iced_core::renderer::Style,
        layout: layout::Layout<'_>,
        cursor_position: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        self.container.as_widget().draw(
            &tree.children[0],
            renderer,
            theme,
            renderer_style,
            layout,
            cursor_position,
            viewport,
        );
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: layout::Layout<'_>,
        renderer: &crate::Renderer,
    ) -> Option<overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
        self.container
            .as_widget_mut()
            .overlay(&mut tree.children[0], layout, renderer)
    }

    fn drag_destinations(
        &self,
        state: &Tree,
        layout: layout::Layout<'_>,
        renderer: &crate::Renderer,
        dnd_rectangles: &mut iced_core::clipboard::DndDestinationRectangles,
    ) {
        let bounds = layout.bounds();
        let my_id = self.get_drag_id();
        let my_dest = DndDestinationRectangle {
            id: my_id,
            rectangle: dnd::Rectangle {
                x: f64::from(bounds.x),
                y: f64::from(bounds.y),
                width: f64::from(bounds.width),
                height: f64::from(bounds.height),
            },
            mime_types: self.mime_types.clone(),
            actions: self.action,
            preferred: self.preferred_action,
        };
        dnd_rectangles.push(my_dest);

        self.container.as_widget().drag_destinations(
            &state.children[0],
            layout,
            renderer,
            dnd_rectangles,
        );
    }

    fn id(&self) -> Option<Id> {
        Some(self.id.clone())
    }

    fn set_id(&mut self, id: Id) {
        self.id = id;
    }
}

#[derive(Default)]
pub struct State<T> {
    pub drag_offer: Option<DragOffer<T>>,
}

pub struct DragOffer<T> {
    pub x: f64,
    pub y: f64,
    pub dropped: bool,
    pub selected_action: DndAction,
    pub data: T,
}

impl<T> State<T> {
    #[must_use]
    pub fn new() -> Self {
        Self { drag_offer: None }
    }

    pub fn on_enter<Message>(
        &mut self,
        x: f64,
        y: f64,
        mime_types: Vec<String>,
        on_enter: Option<impl Fn(f64, f64, Vec<String>) -> Message>,
        data: T,
    ) -> Option<Message> {
        self.drag_offer = Some(DragOffer {
            x,
            y,
            dropped: false,
            selected_action: DndAction::empty(),
            data,
        });
        on_enter.map(|f| f(x, y, mime_types))
    }

    pub fn on_leave<Message>(&mut self, on_leave: Option<&dyn Fn() -> Message>) -> Option<Message> {
        if self.drag_offer.as_ref().is_some_and(|d| !d.dropped) {
            self.drag_offer = None;
            on_leave.map(|f| f())
        } else {
            None
        }
    }

    pub fn on_motion<Message>(
        &mut self,
        x: f64,
        y: f64,
        on_motion: Option<impl Fn(f64, f64) -> Message>,
        on_enter: Option<impl Fn(f64, f64, Vec<String>) -> Message>,
        data: T,
    ) -> Option<Message> {
        if let Some(s) = self.drag_offer.as_mut() {
            s.x = x;
            s.y = y;
        } else {
            self.drag_offer = Some(DragOffer {
                x,
                y,
                dropped: false,
                selected_action: DndAction::empty(),
                data,
            });
            if let Some(f) = on_enter {
                return Some(f(x, y, vec![]));
            }
        }
        on_motion.map(|f| f(x, y))
    }

    pub fn on_drop<Message>(
        &mut self,
        on_drop: Option<impl Fn(f64, f64) -> Message>,
    ) -> Option<Message> {
        if let Some(offer) = self.drag_offer.as_mut() {
            offer.dropped = true;
            if let Some(f) = on_drop {
                return Some(f(offer.x, offer.y));
            }
        }
        None
    }

    pub fn on_action_selected<Message>(
        &mut self,
        action: DndAction,
        on_action_selected: Option<impl Fn(DndAction) -> Message>,
    ) -> Option<Message> {
        if let Some(s) = self.drag_offer.as_mut() {
            s.selected_action = action;
        }
        if let Some(f) = on_action_selected {
            f(action).into()
        } else {
            None
        }
    }

    pub fn on_data_received<Message>(
        &mut self,
        mime: String,
        data: Vec<u8>,
        on_data_received: Option<impl Fn(String, Vec<u8>) -> Message>,
        on_finish: Option<impl Fn(String, Vec<u8>, DndAction, f64, f64) -> Message>,
    ) -> (Option<Message>, event::Status) {
        let Some(dnd) = self.drag_offer.as_ref() else {
            self.drag_offer = None;
            return (None, event::Status::Ignored);
        };

        if dnd.dropped {
            let ret = (
                on_finish.map(|f| f(mime, data, dnd.selected_action, dnd.x, dnd.y)),
                event::Status::Captured,
            );
            self.drag_offer = None;
            ret
        } else if let Some(f) = on_data_received {
            (Some(f(mime, data)), event::Status::Captured)
        } else {
            (None, event::Status::Ignored)
        }
    }
}

impl<'a, Message: 'static> From<DndDestination<'a, Message>> for Element<'a, Message> {
    fn from(wrapper: DndDestination<'a, Message>) -> Self {
        Element::new(wrapper)
    }
}