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
use std::any::Any;

use iced_core::window;

use crate::{
    iced::{
        clipboard::dnd::{DndAction, DndEvent, SourceEvent},
        event, mouse, overlay, Event, Length, Point, Rectangle, Vector,
    },
    iced_core::{
        self, layout, renderer,
        widget::{tree, Tree},
        Clipboard, Shell,
    },
    widget::{container, Id, Widget},
    Element,
};

pub fn dnd_source<
    'a,
    Message: Clone + 'static,
    D: iced::clipboard::mime::AsMimeTypes + Send + 'static,
>(
    child: impl Into<Element<'a, Message>>,
) -> DndSource<'a, Message, D> {
    DndSource::new(child)
}

pub struct DndSource<'a, Message, D> {
    id: Id,
    action: DndAction,
    container: Element<'a, Message>,
    window: Option<window::Id>,
    drag_content: Option<Box<dyn Fn() -> D>>,
    drag_icon: Option<Box<dyn Fn() -> (Element<'static, ()>, tree::State)>>,
    on_start: Option<Message>,
    on_cancelled: Option<Message>,
    on_finish: Option<Message>,
    drag_threshold: f32,
}

impl<
        'a,
        Message: Clone + 'static,
        D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static,
    > DndSource<'a, Message, D>
{
    pub fn new(child: impl Into<Element<'a, Message>>) -> Self {
        Self {
            id: Id::unique(),
            window: None,
            action: DndAction::Copy | DndAction::Move,
            container: container(child).into(),
            drag_content: None,
            drag_icon: None,
            drag_threshold: 8.0,
            on_start: None,
            on_cancelled: None,
            on_finish: None,
        }
    }

    pub fn with_id(child: impl Into<Element<'a, Message>>, id: Id) -> Self {
        Self {
            id,
            window: None,
            action: DndAction::Copy | DndAction::Move,
            container: container(child).into(),
            drag_content: None,
            drag_icon: None,
            drag_threshold: 8.0,
            on_start: None,
            on_cancelled: None,
            on_finish: None,
        }
    }

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

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

    #[must_use]
    pub fn drag_icon(
        mut self,
        f: impl Fn() -> (Element<'static, ()>, tree::State) + 'static,
    ) -> Self {
        self.drag_icon = Some(Box::new(f));
        self
    }

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

    pub fn start_dnd(&self, clipboard: &mut dyn Clipboard, bounds: Rectangle) {
        let Some(content) = self.drag_content.as_ref().map(|f| f()) else {
            return;
        };

        iced_core::clipboard::start_dnd(
            clipboard,
            false,
            if let Some(window) = self.window.as_ref() {
                Some(iced_core::clipboard::DndSource::Surface(window.clone()))
            } else {
                Some(iced_core::clipboard::DndSource::Widget(self.id.clone()))
            },
            self.drag_icon.as_ref().map(|f| {
                let (icon, state) = f();
                (
                    container(icon)
                        .width(Length::Fixed(bounds.width))
                        .height(Length::Fixed(bounds.height))
                        .into(),
                    state,
                )
            }),
            Box::new(content),
            self.action,
        );
    }

    pub fn on_start(mut self, on_start: Option<Message>) -> Self {
        self.on_start = on_start;
        self
    }

    pub fn on_cancel(mut self, on_cancelled: Option<Message>) -> Self {
        self.on_cancelled = on_cancelled;
        self
    }

    pub fn on_finish(mut self, on_finish: Option<Message>) -> Self {
        self.on_finish = on_finish;
        self
    }

    pub fn window(mut self, window: window::Id) -> Self {
        self.window = Some(window);
        self
    }
}

impl<
        'a,
        Message: Clone + 'static,
        D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static,
    > Widget<Message, crate::Theme, crate::Renderer> for DndSource<'a, Message, D>
{
    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 {
        let state = tree.state.downcast_mut::<State>();
        let node = self
            .container
            .as_widget()
            .layout(&mut tree.children[0], renderer, limits);
        state.cached_bounds = node.bounds();
        node
    }

    fn operate(
        &self,
        tree: &mut Tree,
        layout: layout::Layout<'_>,
        renderer: &crate::Renderer,
        operation: &mut dyn iced_core::widget::Operation<()>,
    ) {
        operation.custom((&mut tree.state) as &mut dyn Any, Some(&self.id));
        operation.container(Some(&self.id), layout.bounds(), &mut |operation| {
            self.container
                .as_widget()
                .operate(&mut tree.children[0], layout, renderer, operation)
        });
    }

    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 ret = self.container.as_widget_mut().on_event(
            &mut tree.children[0],
            event.clone(),
            layout,
            cursor,
            renderer,
            clipboard,
            shell,
            viewport,
        );

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

        match event {
            Event::Mouse(mouse_event) => match mouse_event {
                mouse::Event::ButtonPressed(mouse::Button::Left) => {
                    if let Some(position) = cursor.position() {
                        if !state.hovered {
                            return ret;
                        }

                        state.left_pressed_position = Some(position);
                        return event::Status::Captured;
                    }
                }
                mouse::Event::ButtonReleased(mouse::Button::Left)
                    if state.left_pressed_position.is_some() =>
                {
                    state.left_pressed_position = None;
                    return event::Status::Captured;
                }
                mouse::Event::CursorMoved { .. } => {
                    if let Some(position) = cursor.position() {
                        if state.hovered {
                            // We ignore motion if we do not possess drag content by now.
                            if self.drag_content.is_none() {
                                state.left_pressed_position = None;
                                return ret;
                            }
                            if let Some(left_pressed_position) = state.left_pressed_position {
                                if position.distance(left_pressed_position) > self.drag_threshold {
                                    if let Some(on_start) = self.on_start.as_ref() {
                                        shell.publish(on_start.clone())
                                    }
                                    self.start_dnd(clipboard, state.cached_bounds);
                                    state.is_dragging = true;
                                    state.left_pressed_position = None;
                                }
                            }
                            if !cursor.is_over(layout.bounds()) {
                                state.hovered = false;

                                return ret;
                            }
                        } else if cursor.is_over(layout.bounds()) {
                            state.hovered = true;
                        }
                        return event::Status::Captured;
                    }
                }
                _ => return ret,
            },
            Event::Dnd(DndEvent::Source(SourceEvent::Cancelled)) => {
                if state.is_dragging {
                    if let Some(m) = self.on_cancelled.as_ref() {
                        shell.publish(m.clone());
                    }
                    state.is_dragging = false;
                    return event::Status::Captured;
                }
                return ret;
            }
            Event::Dnd(DndEvent::Source(SourceEvent::Finished)) => {
                if state.is_dragging {
                    if let Some(m) = self.on_finish.as_ref() {
                        shell.publish(m.clone());
                    }
                    state.is_dragging = false;
                    return event::Status::Captured;
                }
                return ret;
            }
            _ => return ret,
        }
        ret
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: layout::Layout<'_>,
        cursor_position: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &crate::Renderer,
    ) -> mouse::Interaction {
        let state = tree.state.downcast_ref::<State>();
        if state.is_dragging {
            return mouse::Interaction::Grabbing;
        }
        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: &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,
        translation: Vector,
    ) -> Option<overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
        self.container
            .as_widget_mut()
            .overlay(&mut tree.children[0], layout, renderer, translation)
    }

    fn drag_destinations(
        &self,
        state: &Tree,
        layout: layout::Layout<'_>,
        renderer: &crate::Renderer,
        dnd_rectangles: &mut iced_core::clipboard::DndDestinationRectangles,
    ) {
        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;
    }

    #[cfg(feature = "a11y")]
    /// get the a11y nodes for the widget
    fn a11y_nodes(
        &self,
        layout: iced_core::Layout<'_>,
        state: &Tree,
        p: mouse::Cursor,
    ) -> iced_accessibility::A11yTree {
        let c_state = &state.children[0];
        self.container.as_widget().a11y_nodes(layout, c_state, p)
    }
}

impl<
        'a,
        Message: Clone + 'static,
        D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static,
    > From<DndSource<'a, Message, D>> for Element<'a, Message>
{
    fn from(e: DndSource<'a, Message, D>) -> Element<'a, Message> {
        Element::new(e)
    }
}

/// Local state of the [`MouseListener`].
#[derive(Debug, Default)]
struct State {
    hovered: bool,
    left_pressed_position: Option<Point>,
    is_dragging: bool,
    cached_bounds: Rectangle,
}

impl State {
    fn new() -> Self {
        Self::default()
    }
}