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

use crate::{Event, EventType};
use glib::translate::*;
use glib::StaticType;
use std::fmt;
use std::mem;

impl Event {
    pub fn is<T: EventKind>(&self) -> bool {
        T::event_types().contains(&self.event_type())
    }

    pub fn type_(&self) -> glib::Type {
        unsafe {
            let ptr = self.to_glib_none().0;
            from_glib((*(*(ptr as *mut glib::gobject_ffi::GTypeInstance)).g_class).g_type)
        }
    }

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

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

    /// Returns the relative angle from @event1 to @event2.
    ///
    /// The relative angle is the angle between the X axis and the line
    /// through both events' positions. The rotation direction for positive
    /// angles is from the positive X axis towards the positive Y axis.
    ///
    /// This assumes that both events have X/Y information.
    /// If not, this function returns [`false`].
    /// ## `event1`
    /// first [`Event`][crate::Event]
    /// ## `event2`
    /// second [`Event`][crate::Event]
    ///
    /// # Returns
    ///
    /// [`true`] if the angle could be calculated.
    ///
    /// ## `angle`
    /// return location for the relative angle between both events
    #[doc(alias = "gdk_events_get_angle")]
    #[doc(alias = "get_angle")]
    pub fn angle(&self, event: impl AsRef<Event>) -> 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
            }
        }
    }

    /// Returns the point halfway between the events' positions.
    ///
    /// This assumes that both events have X/Y information.
    /// If not, this function returns [`false`].
    /// ## `event1`
    /// first [`Event`][crate::Event]
    /// ## `event2`
    /// second [`Event`][crate::Event]
    ///
    /// # Returns
    ///
    /// [`true`] if the center could be calculated.
    ///
    /// ## `x`
    /// return location for the X coordinate of the center
    ///
    /// ## `y`
    /// return location for the Y coordinate of the center
    #[doc(alias = "gdk_events_get_center")]
    #[doc(alias = "get_center")]
    pub fn center(&self, event: impl AsRef<Event>) -> 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
            }
        }
    }

    /// Returns the distance between the event locations.
    ///
    /// This assumes that both events have X/Y information.
    /// If not, this function returns [`false`].
    /// ## `event1`
    /// first [`Event`][crate::Event]
    /// ## `event2`
    /// second [`Event`][crate::Event]
    ///
    /// # Returns
    ///
    /// [`true`] if the distance could be calculated.
    ///
    /// ## `distance`
    /// return location for the distance
    #[doc(alias = "gdk_events_get_distance")]
    #[doc(alias = "get_distance")]
    pub fn distance(&self, event: impl AsRef<Event>) -> 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
            }
        }
    }
}

impl fmt::Debug 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()
    }
}

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

// rustdoc-stripper-ignore-next
/// A common trait implemented by the various [`Event`](crate::Event) types.
///
/// # Safety
///
/// The user is not supposed to implement this trait.
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,$event_event_types:expr) => {
        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
            }
        }
    };
}