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
use wayland_client::{
    protocol::{wl_data_device, wl_data_device_manager, wl_data_offer, wl_seat, wl_surface},
    DispatchData, Main,
};

use std::sync::{Arc, Mutex};

use super::{DataOffer, DataSource, DndAction};

#[derive(Debug)]
struct Inner {
    selection: Option<DataOffer>,
    current_dnd: Option<DataOffer>,
    known_offers: Vec<DataOffer>,
}

impl Inner {
    fn new_offer(&mut self, offer: Main<wl_data_offer::WlDataOffer>) {
        self.known_offers.push(DataOffer::new(offer));
    }

    fn set_selection(&mut self, offer: Option<wl_data_offer::WlDataOffer>) {
        if let Some(offer) = offer {
            if let Some(id) = self.known_offers.iter().position(|o| o.offer == offer) {
                self.selection = Some(self.known_offers.swap_remove(id));
            } else {
                panic!("Compositor set an unknown data_offer for selection.");
            }
        } else {
            // drop the current offer if any
            self.selection = None;
        }
    }

    fn set_dnd(&mut self, offer: Option<wl_data_offer::WlDataOffer>) {
        if let Some(offer) = offer {
            if let Some(id) = self.known_offers.iter().position(|o| o.offer == offer) {
                self.current_dnd = Some(self.known_offers.swap_remove(id));
            } else {
                panic!("Compositor set an unknown data_offer for selection.");
            }
        } else {
            // drop the current offer if any
            self.current_dnd = None;
        }
    }
}

/// Handle to support data exchange on a given seat
///
/// This type provides you with functionality to send and receive
/// data through drag'n'drop or copy/paste actions. It is associated
/// with a seat upon creation.
#[derive(Debug)]
pub struct DataDevice {
    device: wl_data_device::WlDataDevice,
    inner: Arc<Mutex<Inner>>,
}

/// Possible events generated during a drag'n'drop session
#[derive(Debug)]
pub enum DndEvent<'a> {
    /// A new drag'n'drop entered your surfaces
    Enter {
        /// The associated data offer
        ///
        /// Is None if it is an internal drag'n'drop you started with
        /// no source. See `DataDevice::start_drag` for details.
        offer: Option<&'a DataOffer>,
        /// A serial associated with the entry of this dnd
        serial: u32,
        /// The entered surface
        surface: wl_surface::WlSurface,
        /// horizontal location on the surface
        x: f64,
        /// vertical location on the surface
        y: f64,
    },
    /// The drag'n'drop offer moved on the surface
    Motion {
        /// The associated data offer
        ///
        /// Is None if it is an internal drag'n'drop you started with
        /// no source. See `DataDevice::start_drag` for details.
        offer: Option<&'a DataOffer>,
        /// The time of this motion
        time: u32,
        /// new horizontal location
        x: f64,
        /// new vertical location
        y: f64,
    },
    /// The drag'n'drop offer left your surface
    Leave,
    /// The drag'n'drop was dropped on your surface
    Drop {
        /// The associated data offer
        ///
        /// Is None if it is an internal drag'n'drop you started with
        /// no source. See `DataDevice::start_drag` for details.
        offer: Option<&'a DataOffer>,
    },
}

fn data_device_implem<F>(
    event: wl_data_device::Event,
    inner: &mut Inner,
    implem: &mut F,
    ddata: DispatchData,
) where
    for<'a> F: FnMut(DndEvent<'a>, DispatchData),
{
    use self::wl_data_device::Event;

    match event {
        Event::DataOffer { id } => inner.new_offer(id),
        Event::Enter { serial, surface, x, y, id } => {
            inner.set_dnd(id);
            implem(
                DndEvent::Enter { serial, surface, x, y, offer: inner.current_dnd.as_ref() },
                ddata,
            );
        }
        Event::Motion { time, x, y } => {
            implem(DndEvent::Motion { x, y, time, offer: inner.current_dnd.as_ref() }, ddata);
        }
        Event::Leave => implem(DndEvent::Leave, ddata),
        Event::Drop => {
            implem(DndEvent::Drop { offer: inner.current_dnd.as_ref() }, ddata);
        }
        Event::Selection { id } => inner.set_selection(id),
        _ => unreachable!(),
    }
}

impl DataDevice {
    /// Create the DataDevice helper for this seat.
    ///
    /// You need to provide an implementation that will handle drag'n'drop
    /// events.
    pub fn init_for_seat<F>(
        manager: &wl_data_device_manager::WlDataDeviceManager,
        seat: &wl_seat::WlSeat,
        mut callback: F,
    ) -> DataDevice
    where
        for<'a> F: FnMut(DndEvent<'a>, DispatchData) + 'static,
    {
        let inner = Arc::new(Mutex::new(Inner {
            selection: None,
            current_dnd: None,
            known_offers: Vec::new(),
        }));

        let inner2 = inner.clone();
        let device = manager.get_data_device(seat);
        device.quick_assign(move |_, evt, ddata| {
            let mut inner = inner2.lock().unwrap();
            data_device_implem(evt, &mut *inner, &mut callback, ddata);
        });

        DataDevice { device: device.detach(), inner }
    }

    /// Start a drag'n'drop offer
    ///
    /// You need to specify the origin surface, as well a serial associated
    /// to an implicit grab on this surface (for example received by a pointer click).
    ///
    /// An optional `DataSource` can be provided. If it is `None`, this drag'n'drop will
    /// be considered as internal to your application, and other applications will not be
    /// notified of it. You are then responsible for acting accordingly on drop.
    ///
    /// You also need to specify which possible drag'n'drop actions are associated to this
    /// drag (copy, move, or ask), the final action will be chosen by the target and/or
    /// compositor.
    ///
    /// You can finally provide a surface that will be used as an icon associated with
    /// this drag'n'drop for user visibility.
    pub fn start_drag(
        &self,
        origin: &wl_surface::WlSurface,
        source: Option<DataSource>,
        actions: DndAction,
        icon: Option<&wl_surface::WlSurface>,
        serial: u32,
    ) {
        if let Some(source) = source {
            source.source.set_actions(actions);
            self.device.start_drag(Some(&source.source), origin, icon, serial);
        } else {
            self.device.start_drag(None, origin, icon, serial);
        }
    }

    /// Provide a data source as the new content for the selection
    ///
    /// Correspond to traditional copy/paste behavior. Setting the
    /// source to `None` will clear the selection.
    pub fn set_selection(&self, source: &Option<DataSource>, serial: u32) {
        self.device.set_selection(source.as_ref().map(|s| &s.source), serial);
    }

    /// Access the `DataOffer` currently associated with the selection buffer
    pub fn with_selection<F, T>(&self, f: F) -> T
    where
        F: FnOnce(Option<&DataOffer>) -> T,
    {
        let inner = self.inner.lock().unwrap();
        f(inner.selection.as_ref())
    }
}

impl Drop for DataDevice {
    fn drop(&mut self) {
        self.device.release();
    }
}