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
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::{AxisUse, Device, Display, EventType, ModifierType, Seat, Surface, TimeCoord};
use glib::translate::*;
use glib::{StaticType, Type};
use std::fmt;
use std::mem;

glib::wrapper! {
    /// [`Event`][crate::Event]s are immutable data structures, created by GDK to
    /// represent windowing system events.
    ///
    /// In GTK applications the events are handled automatically by toplevel
    /// widgets and passed on to the event controllers of appropriate widgets,
    /// so using [`Event`][crate::Event] and its related API is rarely needed.
    ///
    /// This is an Abstract Base Class, you cannot instantiate it.
    #[doc(alias = "GdkEvent")]
    pub struct Event(Shared<ffi::GdkEvent>);

    match fn {
        ref => |ptr| ffi::gdk_event_ref(ptr),
        unref => |ptr| ffi::gdk_event_unref(ptr),
    }
}

pub const NONE_EVENT: Option<&Event> = None;

impl StaticType for Event {
    #[doc(alias = "gdk_event_get_type")]
    fn static_type() -> Type {
        unsafe { from_glib(ffi::gdk_event_get_type()) }
    }
}

impl Event {
    pub fn downcast<T: EventKind>(self) -> Result<T, Event> {
        unsafe {
            if T::event_types().contains(&self.event_type()) {
                Ok(from_glib_full(self.to_glib_full()))
            } else {
                Err(self)
            }
        }
    }

    pub fn downcast_ref<T: EventKind>(&self) -> Option<&T> {
        unsafe {
            if T::event_types().contains(&self.event_type()) {
                Some(&*(self as *const Event as *const T))
            } else {
                None
            }
        }
    }

    #[doc(alias = "gdk_events_get_angle")]
    #[doc(alias = "get_angle")]
    pub fn angle<P: AsRef<Event>>(&self, event: P) -> Option<f64> {
        skip_assert_initialized!();
        unsafe {
            let mut angle = mem::MaybeUninit::uninit();
            let ret = from_glib(ffi::gdk_events_get_angle(
                self.to_glib_none().0,
                event.as_ref().to_glib_none().0,
                angle.as_mut_ptr(),
            ));
            if ret {
                let angle = angle.assume_init();
                Some(angle)
            } else {
                None
            }
        }
    }

    #[doc(alias = "gdk_events_get_center")]
    #[doc(alias = "get_center")]
    pub fn center<P: AsRef<Event>>(&self, event: P) -> Option<(f64, f64)> {
        skip_assert_initialized!();
        unsafe {
            let mut x = mem::MaybeUninit::uninit();
            let mut y = mem::MaybeUninit::uninit();
            let ret = from_glib(ffi::gdk_events_get_center(
                self.to_glib_none().0,
                event.as_ref().to_glib_none().0,
                x.as_mut_ptr(),
                y.as_mut_ptr(),
            ));
            if ret {
                let x = x.assume_init();
                let y = y.assume_init();
                Some((x, y))
            } else {
                None
            }
        }
    }

    #[doc(alias = "gdk_events_get_distance")]
    #[doc(alias = "get_distance")]
    pub fn distance<P: AsRef<Event>>(&self, event: P) -> Option<f64> {
        skip_assert_initialized!();
        unsafe {
            let mut distance = mem::MaybeUninit::uninit();
            let ret = from_glib(ffi::gdk_events_get_distance(
                self.to_glib_none().0,
                event.as_ref().to_glib_none().0,
                distance.as_mut_ptr(),
            ));
            if ret {
                let distance = distance.assume_init();
                Some(distance)
            } else {
                None
            }
        }
    }

    /// Extract the axis value for a particular axis use from
    /// an event structure.
    /// ## `axis_use`
    /// the axis use to look for
    ///
    /// # Returns
    ///
    /// [`true`] if the specified axis was found, otherwise [`false`]
    ///
    /// ## `value`
    /// location to store the value found
    #[doc(alias = "gdk_event_get_axis")]
    #[doc(alias = "get_axis")]
    pub fn axis(&self, axis_use: AxisUse) -> Option<f64> {
        unsafe {
            let mut value = mem::MaybeUninit::uninit();
            let ret = from_glib(ffi::gdk_event_get_axis(
                self.to_glib_none().0,
                axis_use.into_glib(),
                value.as_mut_ptr(),
            ));
            if ret {
                let value = value.assume_init();
                Some(value)
            } else {
                None
            }
        }
    }

    /// Returns the device of an event.
    ///
    /// # Returns
    ///
    /// a [`Device`][crate::Device]
    #[doc(alias = "gdk_event_get_device")]
    #[doc(alias = "get_device")]
    pub fn device(&self) -> Option<Device> {
        unsafe { from_glib_none(ffi::gdk_event_get_device(self.to_glib_none().0)) }
    }

    /// Retrieves the display associated to the `self`.
    ///
    /// # Returns
    ///
    /// a [`Display`][crate::Display]
    #[doc(alias = "gdk_event_get_display")]
    #[doc(alias = "get_display")]
    pub fn display(&self) -> Option<Display> {
        unsafe { from_glib_none(ffi::gdk_event_get_display(self.to_glib_none().0)) }
    }

    /// Retrieves the type of the event.
    ///
    /// # Returns
    ///
    /// a [`Event`][crate::Event]Type
    #[doc(alias = "gdk_event_get_event_type")]
    #[doc(alias = "get_event_type")]
    pub fn event_type(&self) -> EventType {
        unsafe { from_glib(ffi::gdk_event_get_event_type(self.to_glib_none().0)) }
    }

    /// Retrieves the history of the device that `self` is for, as a list of
    /// time and coordinates.
    ///
    /// The history includes positions that are not delivered as separate events
    /// to the application because they occurred in the same frame as `self`.
    ///
    /// Note that only motion and scroll events record history, and motion
    /// events do it only if one of the mouse buttons is down.
    ///
    /// # Returns
    ///
    /// an
    ///  array of time and coordinates
    #[doc(alias = "gdk_event_get_history")]
    #[doc(alias = "get_history")]
    pub fn history(&self) -> Vec<TimeCoord> {
        unsafe {
            let mut out_n_coords = mem::MaybeUninit::uninit();
            let ret = FromGlibContainer::from_glib_container_num(
                ffi::gdk_event_get_history(self.to_glib_none().0, out_n_coords.as_mut_ptr()),
                out_n_coords.assume_init() as usize,
            );
            ret
        }
    }

    /// Returns the modifier state field of an event.
    ///
    /// # Returns
    ///
    /// the modifier state of `self`
    #[doc(alias = "gdk_event_get_modifier_state")]
    #[doc(alias = "get_modifier_state")]
    pub fn modifier_state(&self) -> ModifierType {
        unsafe { from_glib(ffi::gdk_event_get_modifier_state(self.to_glib_none().0)) }
    }

    /// Returns whether this event is an 'emulated' pointer event.
    ///
    /// Emulated pointer events typically originate from a touch events.
    ///
    /// # Returns
    ///
    /// [`true`] if this event is emulated
    #[doc(alias = "gdk_event_get_pointer_emulated")]
    #[doc(alias = "get_pointer_emulated")]
    pub fn is_pointer_emulated(&self) -> bool {
        unsafe { from_glib(ffi::gdk_event_get_pointer_emulated(self.to_glib_none().0)) }
    }

    /// Extract the event surface relative x/y coordinates from an event.
    ///
    /// # Returns
    ///
    ///
    /// ## `x`
    /// location to put event surface x coordinate
    ///
    /// ## `y`
    /// location to put event surface y coordinate
    #[doc(alias = "gdk_event_get_position")]
    #[doc(alias = "get_position")]
    pub fn position(&self) -> Option<(f64, f64)> {
        unsafe {
            let mut x = mem::MaybeUninit::uninit();
            let mut y = mem::MaybeUninit::uninit();
            let ret = from_glib(ffi::gdk_event_get_position(
                self.to_glib_none().0,
                x.as_mut_ptr(),
                y.as_mut_ptr(),
            ));
            if ret {
                let x = x.assume_init();
                let y = y.assume_init();
                Some((x, y))
            } else {
                None
            }
        }
    }

    /// Returns the seat that originated the event.
    ///
    /// # Returns
    ///
    /// a [`Seat`][crate::Seat].
    #[doc(alias = "gdk_event_get_seat")]
    #[doc(alias = "get_seat")]
    pub fn seat(&self) -> Option<Seat> {
        unsafe { from_glib_none(ffi::gdk_event_get_seat(self.to_glib_none().0)) }
    }

    /// Extracts the surface associated with an event.
    ///
    /// # Returns
    ///
    /// The [`Surface`][crate::Surface] associated with the event
    #[doc(alias = "gdk_event_get_surface")]
    #[doc(alias = "get_surface")]
    pub fn surface(&self) -> Option<Surface> {
        unsafe { from_glib_none(ffi::gdk_event_get_surface(self.to_glib_none().0)) }
    }

    /// Returns the timestamp of `self`.
    ///
    /// Not all events have timestamps. In that case, this function
    /// returns `GDK_CURRENT_TIME`.
    ///
    /// # Returns
    ///
    /// timestamp field from `self`
    #[doc(alias = "gdk_event_get_time")]
    #[doc(alias = "get_time")]
    pub fn time(&self) -> u32 {
        unsafe { ffi::gdk_event_get_time(self.to_glib_none().0) }
    }

    /// Returns whether a [`Event`][crate::Event] should trigger a context menu,
    /// according to platform conventions.
    ///
    /// The right mouse button typically triggers context menus.
    ///
    /// This function should always be used instead of simply checking for
    /// event->button == `GDK_BUTTON_SECONDARY`.
    ///
    /// # Returns
    ///
    /// [`true`] if the event should trigger a context menu.
    #[doc(alias = "gdk_event_triggers_context_menu")]
    pub fn triggers_context_menu(&self) -> bool {
        unsafe { from_glib(ffi::gdk_event_triggers_context_menu(self.to_glib_none().0)) }
    }
}

impl fmt::Display for Event {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Event")
            .field("event_type", &self.event_type())
            .field("history", &self.history())
            .field("modifier_state", &self.modifier_state())
            .field("pointer_emulated", &self.is_pointer_emulated())
            .field("position", &self.position())
            .field("time", &self.time())
            .field("triggers_context_menu", &self.triggers_context_menu())
            .finish()
    }
}

impl fmt::Debug for Event {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_fmt(format_args!("{}", self))
    }
}

#[doc(hidden)]
impl AsRef<Event> for Event {
    fn as_ref(&self) -> &Self {
        self
    }
}

pub unsafe trait EventKind:
    StaticType + FromGlibPtrFull<*mut ffi::GdkEvent> + 'static
{
    fn event_types() -> &'static [EventType];
}

macro_rules! define_event {
    ($rust_type:ident, $ffi_type:path, $ffi_type_path:path, $event_event_types:expr) => {
        impl glib::StaticType for $rust_type {
            fn static_type() -> glib::Type {
                unsafe { from_glib($ffi_type_path()) }
            }
        }

        unsafe impl crate::event::EventKind for $rust_type {
            fn event_types() -> &'static [crate::EventType] {
                $event_event_types
            }
        }

        impl std::ops::Deref for $rust_type {
            type Target = crate::Event;

            fn deref(&self) -> &Self::Target {
                unsafe { &*(self as *const $rust_type as *const crate::Event) }
            }
        }

        impl AsRef<crate::Event> for $rust_type {
            fn as_ref(&self) -> &crate::Event {
                self.upcast_ref()
            }
        }

        #[doc(hidden)]
        impl glib::translate::FromGlibPtrFull<*mut ffi::GdkEvent> for $rust_type {
            unsafe fn from_glib_full(ptr: *mut ffi::GdkEvent) -> Self {
                glib::translate::FromGlibPtrFull::from_glib_full(ptr as *mut $ffi_type)
            }
        }

        impl $rust_type {
            pub fn upcast(self) -> crate::Event {
                unsafe { std::mem::transmute(self) }
            }

            pub fn upcast_ref(&self) -> &crate::Event {
                &*self
            }
        }

        impl std::fmt::Debug for $rust_type {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_fmt(format_args!("{}", self))
            }
        }
    };
}