cosmic/widget/
dnd_source.rs

1use std::any::Any;
2
3use iced_core::window;
4
5use crate::{
6    Element,
7    iced::{
8        Event, Length, Point, Rectangle, Vector,
9        clipboard::dnd::{DndAction, DndEvent, SourceEvent},
10        event, mouse, overlay,
11    },
12    iced_core::{
13        self, Clipboard, Shell, layout, renderer,
14        widget::{Tree, tree},
15    },
16    widget::{Id, Widget, container},
17};
18
19pub fn dnd_source<
20    'a,
21    Message: Clone + 'static,
22    D: iced::clipboard::mime::AsMimeTypes + Send + 'static,
23>(
24    child: impl Into<Element<'a, Message>>,
25) -> DndSource<'a, Message, D> {
26    DndSource::new(child)
27}
28
29pub struct DndSource<'a, Message, D> {
30    id: Id,
31    action: DndAction,
32    container: Element<'a, Message>,
33    window: Option<window::Id>,
34    drag_content: Option<Box<dyn Fn() -> D>>,
35    drag_icon: Option<Box<dyn Fn(Vector) -> (Element<'static, ()>, tree::State, Vector)>>,
36    on_start: Option<Message>,
37    on_cancelled: Option<Message>,
38    on_finish: Option<Message>,
39    drag_threshold: f32,
40}
41
42impl<
43    'a,
44    Message: Clone + 'static,
45    D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static,
46> DndSource<'a, Message, D>
47{
48    pub fn new(child: impl Into<Element<'a, Message>>) -> Self {
49        Self {
50            id: Id::unique(),
51            window: None,
52            action: DndAction::Copy | DndAction::Move,
53            container: container(child).into(),
54            drag_content: None,
55            drag_icon: None,
56            drag_threshold: 8.0,
57            on_start: None,
58            on_cancelled: None,
59            on_finish: None,
60        }
61    }
62
63    pub fn with_id(child: impl Into<Element<'a, Message>>, id: Id) -> Self {
64        Self {
65            id,
66            window: None,
67            action: DndAction::Copy | DndAction::Move,
68            container: container(child).into(),
69            drag_content: None,
70            drag_icon: None,
71            drag_threshold: 8.0,
72            on_start: None,
73            on_cancelled: None,
74            on_finish: None,
75        }
76    }
77
78    #[must_use]
79    pub fn action(mut self, action: DndAction) -> Self {
80        self.action = action;
81        self
82    }
83
84    #[must_use]
85    pub fn drag_content(mut self, f: impl Fn() -> D + 'static) -> Self {
86        self.drag_content = Some(Box::new(f));
87        self
88    }
89
90    #[must_use]
91    pub fn drag_icon(
92        mut self,
93        f: impl Fn(Vector) -> (Element<'static, ()>, tree::State, Vector) + 'static,
94    ) -> Self {
95        self.drag_icon = Some(Box::new(f));
96        self
97    }
98
99    #[must_use]
100    pub fn drag_threshold(mut self, threshold: f32) -> Self {
101        self.drag_threshold = threshold;
102        self
103    }
104
105    pub fn start_dnd(&self, clipboard: &mut dyn Clipboard, bounds: Rectangle, offset: Vector) {
106        let Some(content) = self.drag_content.as_ref().map(|f| f()) else {
107            return;
108        };
109
110        iced_core::clipboard::start_dnd(
111            clipboard,
112            false,
113            if let Some(window) = self.window.as_ref() {
114                Some(iced_core::clipboard::DndSource::Surface(*window))
115            } else {
116                Some(iced_core::clipboard::DndSource::Widget(self.id.clone()))
117            },
118            self.drag_icon.as_ref().map(|f| {
119                let (icon, state, offset) = f(offset);
120                iced_core::clipboard::IconSurface::new(
121                    container(icon)
122                        .width(Length::Fixed(bounds.width))
123                        .height(Length::Fixed(bounds.height))
124                        .into(),
125                    state,
126                    offset,
127                )
128            }),
129            Box::new(content),
130            self.action,
131        );
132    }
133
134    pub fn on_start(mut self, on_start: Option<Message>) -> Self {
135        self.on_start = on_start;
136        self
137    }
138
139    pub fn on_cancel(mut self, on_cancelled: Option<Message>) -> Self {
140        self.on_cancelled = on_cancelled;
141        self
142    }
143
144    pub fn on_finish(mut self, on_finish: Option<Message>) -> Self {
145        self.on_finish = on_finish;
146        self
147    }
148
149    pub fn window(mut self, window: window::Id) -> Self {
150        self.window = Some(window);
151        self
152    }
153}
154
155impl<Message: Clone + 'static, D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static>
156    Widget<Message, crate::Theme, crate::Renderer> for DndSource<'_, Message, D>
157{
158    fn children(&self) -> Vec<Tree> {
159        vec![Tree::new(&self.container)]
160    }
161
162    fn tag(&self) -> iced_core::widget::tree::Tag {
163        tree::Tag::of::<State>()
164    }
165
166    fn diff(&mut self, tree: &mut Tree) {
167        tree.children[0].diff(self.container.as_widget_mut());
168    }
169
170    fn state(&self) -> iced_core::widget::tree::State {
171        tree::State::new(State::new())
172    }
173
174    fn size(&self) -> iced_core::Size<Length> {
175        self.container.as_widget().size()
176    }
177
178    fn layout(
179        &self,
180        tree: &mut Tree,
181        renderer: &crate::Renderer,
182        limits: &layout::Limits,
183    ) -> layout::Node {
184        let state = tree.state.downcast_mut::<State>();
185        let node = self
186            .container
187            .as_widget()
188            .layout(&mut tree.children[0], renderer, limits);
189        state.cached_bounds = node.bounds();
190        node
191    }
192
193    fn operate(
194        &self,
195        tree: &mut Tree,
196        layout: layout::Layout<'_>,
197        renderer: &crate::Renderer,
198        operation: &mut dyn iced_core::widget::Operation<()>,
199    ) {
200        operation.custom((&mut tree.state) as &mut dyn Any, Some(&self.id));
201        operation.container(Some(&self.id), layout.bounds(), &mut |operation| {
202            self.container
203                .as_widget()
204                .operate(&mut tree.children[0], layout, renderer, operation)
205        });
206    }
207
208    fn on_event(
209        &mut self,
210        tree: &mut Tree,
211        event: Event,
212        layout: layout::Layout<'_>,
213        cursor: mouse::Cursor,
214        renderer: &crate::Renderer,
215        clipboard: &mut dyn Clipboard,
216        shell: &mut Shell<'_, Message>,
217        viewport: &Rectangle,
218    ) -> event::Status {
219        let ret = self.container.as_widget_mut().on_event(
220            &mut tree.children[0],
221            event.clone(),
222            layout,
223            cursor,
224            renderer,
225            clipboard,
226            shell,
227            viewport,
228        );
229
230        let state = tree.state.downcast_mut::<State>();
231
232        match event {
233            Event::Mouse(mouse_event) => match mouse_event {
234                mouse::Event::ButtonPressed(mouse::Button::Left) => {
235                    if let Some(position) = cursor.position() {
236                        if !state.hovered {
237                            return ret;
238                        }
239
240                        state.left_pressed_position = Some(position);
241                        return event::Status::Captured;
242                    }
243                }
244                mouse::Event::ButtonReleased(mouse::Button::Left)
245                    if state.left_pressed_position.is_some() =>
246                {
247                    state.left_pressed_position = None;
248                    return event::Status::Captured;
249                }
250                mouse::Event::CursorMoved { .. } => {
251                    if let Some(position) = cursor.position() {
252                        if state.hovered {
253                            // We ignore motion if we do not possess drag content by now.
254                            if self.drag_content.is_none() {
255                                state.left_pressed_position = None;
256                                return ret;
257                            }
258                            if let Some(left_pressed_position) = state.left_pressed_position {
259                                if position.distance(left_pressed_position) > self.drag_threshold {
260                                    if let Some(on_start) = self.on_start.as_ref() {
261                                        shell.publish(on_start.clone())
262                                    }
263                                    let offset = Vector::new(
264                                        left_pressed_position.x - layout.bounds().x,
265                                        left_pressed_position.y - layout.bounds().y,
266                                    );
267                                    self.start_dnd(clipboard, state.cached_bounds, offset);
268                                    state.is_dragging = true;
269                                    state.left_pressed_position = None;
270                                }
271                            }
272                            if !cursor.is_over(layout.bounds()) {
273                                state.hovered = false;
274
275                                return ret;
276                            }
277                        } else if cursor.is_over(layout.bounds()) {
278                            state.hovered = true;
279                        }
280                        return event::Status::Captured;
281                    }
282                }
283                _ => return ret,
284            },
285            Event::Dnd(DndEvent::Source(SourceEvent::Cancelled)) => {
286                if state.is_dragging {
287                    if let Some(m) = self.on_cancelled.as_ref() {
288                        shell.publish(m.clone());
289                    }
290                    state.is_dragging = false;
291                    return event::Status::Captured;
292                }
293                return ret;
294            }
295            Event::Dnd(DndEvent::Source(SourceEvent::Finished)) => {
296                if state.is_dragging {
297                    if let Some(m) = self.on_finish.as_ref() {
298                        shell.publish(m.clone());
299                    }
300                    state.is_dragging = false;
301                    return event::Status::Captured;
302                }
303                return ret;
304            }
305            _ => return ret,
306        }
307        ret
308    }
309
310    fn mouse_interaction(
311        &self,
312        tree: &Tree,
313        layout: layout::Layout<'_>,
314        cursor_position: mouse::Cursor,
315        viewport: &Rectangle,
316        renderer: &crate::Renderer,
317    ) -> mouse::Interaction {
318        let state = tree.state.downcast_ref::<State>();
319        if state.is_dragging {
320            return mouse::Interaction::Grabbing;
321        }
322        self.container.as_widget().mouse_interaction(
323            &tree.children[0],
324            layout,
325            cursor_position,
326            viewport,
327            renderer,
328        )
329    }
330
331    fn draw(
332        &self,
333        tree: &Tree,
334        renderer: &mut crate::Renderer,
335        theme: &crate::Theme,
336        renderer_style: &renderer::Style,
337        layout: layout::Layout<'_>,
338        cursor_position: mouse::Cursor,
339        viewport: &Rectangle,
340    ) {
341        self.container.as_widget().draw(
342            &tree.children[0],
343            renderer,
344            theme,
345            renderer_style,
346            layout,
347            cursor_position,
348            viewport,
349        );
350    }
351
352    fn overlay<'b>(
353        &'b mut self,
354        tree: &'b mut Tree,
355        layout: layout::Layout<'_>,
356        renderer: &crate::Renderer,
357        translation: Vector,
358    ) -> Option<overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
359        self.container
360            .as_widget_mut()
361            .overlay(&mut tree.children[0], layout, renderer, translation)
362    }
363
364    fn drag_destinations(
365        &self,
366        state: &Tree,
367        layout: layout::Layout<'_>,
368        renderer: &crate::Renderer,
369        dnd_rectangles: &mut iced_core::clipboard::DndDestinationRectangles,
370    ) {
371        self.container.as_widget().drag_destinations(
372            &state.children[0],
373            layout,
374            renderer,
375            dnd_rectangles,
376        );
377    }
378
379    fn id(&self) -> Option<Id> {
380        Some(self.id.clone())
381    }
382
383    fn set_id(&mut self, id: Id) {
384        self.id = id;
385    }
386
387    #[cfg(feature = "a11y")]
388    /// get the a11y nodes for the widget
389    fn a11y_nodes(
390        &self,
391        layout: iced_core::Layout<'_>,
392        state: &Tree,
393        p: mouse::Cursor,
394    ) -> iced_accessibility::A11yTree {
395        let c_state = &state.children[0];
396        self.container.as_widget().a11y_nodes(layout, c_state, p)
397    }
398}
399
400impl<
401    'a,
402    Message: Clone + 'static,
403    D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static,
404> From<DndSource<'a, Message, D>> for Element<'a, Message>
405{
406    fn from(e: DndSource<'a, Message, D>) -> Element<'a, Message> {
407        Element::new(e)
408    }
409}
410
411/// Local state of the [`MouseListener`].
412#[derive(Debug, Default)]
413struct State {
414    hovered: bool,
415    left_pressed_position: Option<Point>,
416    is_dragging: bool,
417    cached_bounds: Rectangle,
418}
419
420impl State {
421    fn new() -> Self {
422        Self::default()
423    }
424}