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

use wayland_client::protocol::wl_data_device::RequestsTrait as DeviceRequests;
use wayland_client::protocol::wl_data_device_manager::RequestsTrait as MgrRequests;
use wayland_client::protocol::wl_data_source::RequestsTrait as SourceRequests;

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

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

struct Inner {
    selection: Option<DataOffer>,
    current_dnd: Option<DataOffer>,
    known_offers: Vec<DataOffer>,
}

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

    fn set_selection(&mut self, offer: Option<Proxy<wl_data_offer::WlDataOffer>>) {
        if let Some(offer) = offer {
            if let Some(id) = self
                .known_offers
                .iter()
                .position(|o| o.offer.equals(&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<Proxy<wl_data_offer::WlDataOffer>>) {
        if let Some(offer) = offer {
            if let Some(id) = self
                .known_offers
                .iter()
                .position(|o| o.offer.equals(&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.
pub struct DataDevice {
    device: Proxy<wl_data_device::WlDataDevice>,
    inner: Arc<Mutex<Inner>>,
}

/// Possible events generated during a drag'n'drop session
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: Proxy<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<Impl>(event: wl_data_device::Event, inner: &mut Inner, implem: &mut Impl)
where
    for<'a> Impl: FnMut(DndEvent<'a>),
{
    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(),
            });
        }
        Event::Motion { time, x, y } => {
            implem(DndEvent::Motion {
                x,
                y,
                time,
                offer: inner.current_dnd.as_ref(),
            });
        }
        Event::Leave => implem(DndEvent::Leave),
        Event::Drop => {
            implem(DndEvent::Drop {
                offer: inner.current_dnd.as_ref(),
            });
        }
        Event::Selection { id } => inner.set_selection(id),
    }
}

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<Impl>(
        manager: &Proxy<wl_data_device_manager::WlDataDeviceManager>,
        seat: &Proxy<wl_seat::WlSeat>,
        mut implem: Impl,
    ) -> DataDevice
    where
        for<'a> Impl: FnMut(DndEvent<'a>) + Send + '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, move |device| {
                device.implement(
                    move |evt, _| {
                        let mut inner = inner2.lock().unwrap();
                        data_device_implem(evt, &mut *inner, &mut implem);
                    },
                    (),
                )
            })
            .expect("Invalid data device or seat.");

        DataDevice { device, inner }
    }

    /// Create the DataDevice helper for this seat.
    ///
    /// Same as `init_for_seat()`, but allows the implementation to
    /// not be send.
    ///
    /// **unsafety**: unsafe for the same reasons as `NewProxy::implement_nonsend`.
    pub unsafe fn init_for_seat_nonsend<Impl>(
        manager: &Proxy<wl_data_device_manager::WlDataDeviceManager>,
        seat: &Proxy<wl_seat::WlSeat>,
        mut implem: Impl,
        token: &QueueToken,
    ) -> DataDevice
    where
        for<'a> Impl: FnMut(DndEvent<'a>) + Send + '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, move |device| {
                device.implement_nonsend(
                    move |evt, _| {
                        let mut inner = inner2.lock().unwrap();
                        data_device_implem(evt, &mut *inner, &mut implem);
                    },
                    (),
                    token,
                )
            })
            .expect("Invalid data device or seat.");

        DataDevice { device, 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: &Proxy<wl_surface::WlSurface>,
        source: Option<DataSource>,
        actions: DndAction,
        icon: Option<&Proxy<wl_surface::WlSurface>>,
        serial: u32,
    ) {
        if let Some(source) = source {
            source.source.set_actions(actions.to_raw());
            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();
    }
}