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
use crate::base::{BaseEvent, Raw, ResolveWireEvent, ResolveWireGeEvent};
use crate::ext::{Extension, ExtensionData};
use crate::ffi::*;
use crate::x;

#[cfg(feature = "damage")]
use crate::damage;

#[cfg(feature = "dri2")]
use crate::dri2;

#[cfg(feature = "glx")]
use crate::glx;

#[cfg(feature = "present")]
use crate::present;

#[cfg(feature = "randr")]
use crate::randr;

#[cfg(feature = "screensaver")]
use crate::screensaver;

#[cfg(feature = "shape")]
use crate::shape;

#[cfg(feature = "shm")]
use crate::shm;

#[cfg(feature = "sync")]
use crate::sync;

#[cfg(feature = "xfixes")]
use crate::xfixes;

#[cfg(feature = "xinput")]
use crate::xinput;

#[cfg(feature = "xkb")]
use crate::xkb;

#[cfg(feature = "xprint")]
use crate::xprint;

#[cfg(feature = "xv")]
use crate::xv;

/// Unified Event type from the X server.
#[derive(Debug)]
pub enum Event {
    /// The event is issued from the X core protocol.
    X(x::Event),

    #[cfg(feature = "damage")]
    /// The event is issued from the `DAMAGE` extension.
    Damage(damage::Event),

    #[cfg(feature = "dri2")]
    /// The event is issued from the `DRI2` extension.
    Dri2(dri2::Event),

    #[cfg(feature = "glx")]
    /// The event is issued from the `GLX` extension.
    Glx(glx::Event),

    #[cfg(feature = "present")]
    /// The event is issued from the `Present` extension.
    Present(present::Event),

    #[cfg(feature = "randr")]
    /// The event is issued from the `RANDR` extension.
    RandR(randr::Event),

    #[cfg(feature = "screensaver")]
    /// The event is issued from the `MIT-SCREEN-SAVER` extension.
    ScreenSaver(screensaver::Event),

    #[cfg(feature = "shape")]
    /// The event is issued from the `SHAPE` extension.
    Shape(shape::Event),

    #[cfg(feature = "shm")]
    /// The event is issued from the `MIT-SHM` extension.
    Shm(shm::Event),

    #[cfg(feature = "sync")]
    /// The event is issued from the `SYNC` extension.
    Sync(sync::Event),

    #[cfg(feature = "xfixes")]
    /// The event is issued from the `XFIXES` extension.
    XFixes(xfixes::Event),

    #[cfg(feature = "xinput")]
    /// The event is issued from the `XInputExtension` extension.
    Input(xinput::Event),

    #[cfg(feature = "xkb")]
    /// The event is issued from the `XKEYBOARD` extension.
    Xkb(xkb::Event),

    #[cfg(feature = "xprint")]
    /// The event is issued from the `XpExtension` extension.
    XPrint(xprint::Event),

    #[cfg(feature = "xv")]
    /// The event is issued from the `XVideo` extension.
    Xv(xv::Event),

    /// The event was not recognized, it was likely issued from a disabled extension.
    Unknown(UnknownEvent),
}

impl Event {
    pub fn as_raw(&self) -> *mut xcb_generic_event_t {
        match self {
            Self::X(e) => e.as_raw(),
            #[cfg(feature = "damage")]
            Self::Damage(e) => e.as_raw(),
            #[cfg(feature = "dri2")]
            Self::Dri2(e) => e.as_raw(),
            #[cfg(feature = "glx")]
            Self::Glx(e) => e.as_raw(),
            #[cfg(feature = "present")]
            Self::Present(e) => e.as_raw(),
            #[cfg(feature = "randr")]
            Self::RandR(e) => e.as_raw(),
            #[cfg(feature = "screensaver")]
            Self::ScreenSaver(e) => e.as_raw(),
            #[cfg(feature = "shape")]
            Self::Shape(e) => e.as_raw(),
            #[cfg(feature = "shm")]
            Self::Shm(e) => e.as_raw(),
            #[cfg(feature = "sync")]
            Self::Sync(e) => e.as_raw(),
            #[cfg(feature = "xfixes")]
            Self::XFixes(e) => e.as_raw(),
            #[cfg(feature = "xinput")]
            Self::Input(e) => e.as_raw(),
            #[cfg(feature = "xkb")]
            Self::Xkb(e) => e.as_raw(),
            #[cfg(feature = "xprint")]
            Self::XPrint(e) => e.as_raw(),
            #[cfg(feature = "xv")]
            Self::Xv(e) => e.as_raw(),
            Self::Unknown(e) => e.as_raw(),
        }
    }
}

/// an event was not recognized as part of the core protocol or any enabled extension
pub struct UnknownEvent {
    raw: *mut xcb_generic_event_t,
}

impl Raw<xcb_generic_event_t> for UnknownEvent {
    unsafe fn from_raw(raw: *mut xcb_generic_event_t) -> Self {
        UnknownEvent { raw }
    }

    fn as_raw(&self) -> *mut xcb_generic_event_t {
        self.raw
    }
}

impl BaseEvent for UnknownEvent {
    const EXTENSION: Option<Extension> = None;
    const NUMBER: u32 = u32::MAX;
}

impl UnknownEvent {
    pub fn response_type(&self) -> u8 {
        unsafe { (*self.raw).response_type }
    }
    pub fn sequence(&self) -> u16 {
        unsafe { (*self.raw).sequence }
    }
    pub fn full_sequence(&self) -> u32 {
        unsafe { (*self.raw).full_sequence }
    }
}

unsafe impl Send for UnknownEvent {}
unsafe impl Sync for UnknownEvent {}

impl std::fmt::Debug for UnknownEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("UnknownEvent").finish()
    }
}

impl Drop for UnknownEvent {
    fn drop(&mut self) {
        unsafe { libc::free(self.raw as *mut _) }
    }
}

/// Resolve an event from the X server
///
/// If the event originates from an extension, the `extension_data` parameter must contain the
/// data for the extension of origin.
/// If the resolution fails, an `Event::Unknown` is returned.
///
/// # Panics
/// The function will panic if the matches with an `XCB_GE_GENERIC` event, but can't
/// be resolved as such.
///
/// # Safety
/// The caller must ensure that `event` is a valid pointer to an `xcb_generic_event_t`.
pub unsafe fn resolve_event(
    event: *mut xcb_generic_event_t,
    extension_data: &[ExtensionData],
) -> Event {
    let response_type = (*event).response_type & 0x7F;

    if response_type == XCB_GE_GENERIC {
        let event = event as *mut xcb_ge_generic_event_t;
        let extension = (*event).extension;
        for ext in extension_data {
            if ext.major_opcode == extension {
                match ext.ext {
                    #[cfg(feature = "present")]
                    Extension::Present => {
                        return Event::Present(present::Event::resolve_wire_ge_event(event));
                    }
                    #[cfg(feature = "xinput")]
                    Extension::Input => {
                        return Event::Input(xinput::Event::resolve_wire_ge_event(event));
                    }
                    _ => panic!("could not resolve Generic Event extension"),
                }
            }
        }
        return Event::Unknown(UnknownEvent::from_raw(event as *mut _));
    }

    for data in extension_data {
        if response_type >= data.first_event && data.first_event != 0 {
            match data.ext {
                #[cfg(feature = "damage")]
                Extension::Damage => {
                    return Event::Damage(
                        damage::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "dri2")]
                Extension::Dri2 => {
                    return Event::Dri2(
                        dri2::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "glx")]
                Extension::Glx => {
                    return Event::Glx(
                        glx::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "present")]
                Extension::Present => {
                    return Event::Present(
                        present::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "randr")]
                Extension::RandR => {
                    return Event::RandR(
                        randr::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "screensaver")]
                Extension::ScreenSaver => {
                    return Event::ScreenSaver(
                        screensaver::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "shape")]
                Extension::Shape => {
                    return Event::Shape(
                        shape::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "shm")]
                Extension::Shm => {
                    return Event::Shm(
                        shm::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "sync")]
                Extension::Sync => {
                    return Event::Sync(
                        sync::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "xfixes")]
                Extension::XFixes => {
                    return Event::XFixes(
                        xfixes::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "xinput")]
                Extension::Input => {
                    return Event::Input(
                        xinput::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "xkb")]
                Extension::Xkb => {
                    return Event::Xkb(
                        xkb::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "xprint")]
                Extension::XPrint => {
                    return Event::XPrint(
                        xprint::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                #[cfg(feature = "xv")]
                Extension::Xv => {
                    return Event::Xv(
                        xv::Event::resolve_wire_event(data.first_event, event).unwrap(),
                    );
                }

                _ => {}
            }
        }
    }

    x::Event::resolve_wire_event(0, event)
        .map(Event::X)
        .unwrap_or_else(|| {
            // SAFETY the event type is checked above and the function panicked if it was
            // not a basic event (XCB_GE_GENERIC)
            let unknown = UnknownEvent::from_raw(event);
            Event::Unknown(unknown)
        })
}

#[test]
fn test_event_send_sync() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    assert_send::<Event>();
    assert_sync::<Event>();
}