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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// This source file is generated automatically from xtest.xml

use crate::base::{self, BaseError, BaseEvent, GeEvent, Raw, Reply, WiredIn, WiredOut, Xid};
use crate::ext;
use crate::ffi::base::*;
use crate::ffi::ext::*;
use crate::lat1_str::{Lat1Str, Lat1String, Lat1StrF};
use crate::xproto;
use crate::xproto::PropEl;

use bitflags::bitflags;
use libc::{self, iovec};
use std::convert::TryInto;
use std::hash::{Hash, Hasher};
use std::os::unix::io::RawFd;

/// The official identifier for the `Test` extension.
pub const XNAME: &str = "XTEST";
/// The major version of the `Test` extension.
pub const MAJOR_VERSION: u32 = 2;
/// The minor version of the `Test` extension.
pub const MINOR_VERSION: u32 = 2;
/// The version string of the `Test` extension.
pub const VERSION_STRING: &str = "2.2";

pub(crate) static mut FFI_EXT: xcb_extension_t = xcb_extension_t {
    name: "XTEST\0".as_ptr() as *const _,
    global_id: 0,
};

/// Prefetch server runtime info data of the `Test` extension.
pub fn prefetch_extension_data(conn: &base::Connection) {
    unsafe {
        xcb_prefetch_extension_data(conn.get_raw_conn(), &mut FFI_EXT as *mut _);
    }
}

/// Fetch server runtime info data of the `Test` extension.
///
/// Might be non-blocking if [prefetch_extension_data] was called before.
/// This function is of seldom use as the extensions are initialized by the
/// [Connection](crate::Connection) constructor.
pub fn get_extension_data(conn: &base::Connection) -> std::option::Option<ext::ExtensionData> {
    unsafe {
        let reply = xcb_get_extension_data(conn.get_raw_conn(), &mut FFI_EXT as *mut _);
        assert!(!reply.is_null(), "Could not fetch Test extension data");
        let reply = xproto::QueryExtensionReply::from_raw(reply);
        if !reply.present() {
            std::mem::forget(reply);
            return None;
        }
        let res = ext::ExtensionData{
            ext: ext::Extension::Test,
            major_opcode: reply.major_opcode(),
            first_event: reply.first_event(),
            first_error: reply.first_error(),
        };
        std::mem::forget(reply);
        Some(res)
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u32)]
pub enum Cursor {
    None = 0,
    Current = 1,
}

pub(crate) fn request_name(opcode: u16) -> std::option::Option<&'static str> {
    match opcode {
        0 => Some("xtest::GetVersion"),
        1 => Some("xtest::CompareCursor"),
        2 => Some("xtest::FakeInput"),
        3 => Some("xtest::GrabControl"),
        _ => None,
    }
}

/// Reply type for [GetVersion].
///
/// Can be obtained from a [GetVersionCookie] with [Connection::wait_for_reply](crate::Connection::wait_for_reply)
/// or from a [GetVersionCookieUnchecked] with [Connection::wait_for_reply_unchecked](crate::Connection::wait_for_reply_unchecked)
pub struct GetVersionReply {
    raw: *const u8,
}

impl GetVersionReply {

    fn wire_ptr(&self) -> *const u8 {
        self.raw
    }

    fn wire_len(&self) -> usize {
        (32 + self.length() * 4) as _
    }

    pub fn response_type(&self) -> u8 {
        unsafe {
            let offset = 0usize;
            let ptr = self.wire_ptr().add(offset) as *const u8;
            *ptr
        }
    }

    pub fn major_version(&self) -> u8 {
        unsafe {
            let offset = 1usize;
            let ptr = self.wire_ptr().add(offset) as *const u8;
            *ptr
        }
    }

    pub fn sequence(&self) -> u16 {
        unsafe {
            let offset = 2usize;
            let ptr = self.wire_ptr().add(offset) as *const u16;
            *ptr
        }
    }

    pub fn length(&self) -> u32 {
        unsafe {
            let offset = 4usize;
            let ptr = self.wire_ptr().add(offset) as *const u32;
            *ptr
        }
    }

    pub fn minor_version(&self) -> u16 {
        unsafe {
            let offset = 8usize;
            let ptr = self.wire_ptr().add(offset) as *const u16;
            *ptr
        }
    }
}

impl base::Reply for GetVersionReply {
    unsafe fn from_raw(raw: *const u8) -> Self {
        Self { raw }
    }

    unsafe fn into_raw(self) -> *const u8 {
        let raw = self.raw;
        std::mem::forget(self);
        raw
    }
}

impl std::fmt::Debug for GetVersionReply {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GetVersionReply")
            .field("response_type", &self.response_type())
            .field("major_version", &self.major_version())
            .field("sequence", &self.sequence())
            .field("length", &self.length())
            .field("minor_version", &self.minor_version())
            .finish()
    }
}

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

unsafe impl std::marker::Send for GetVersionReply {}
unsafe impl std::marker::Sync for GetVersionReply {}

/// Cookie type for [GetVersion].
///
/// This cookie can be used to get a [GetVersionReply]
/// with [Connection::wait_for_reply](crate::Connection::wait_for_reply)
#[derive(Debug)]
pub struct GetVersionCookie {
    seq: u64,
}

#[derive(Debug)]
/// Unchecked cookie type for [GetVersion].
///
/// This cookie can be used to get a [GetVersionReply]
/// with [Connection::wait_for_reply_unchecked](crate::Connection::wait_for_reply_unchecked)
pub struct GetVersionCookieUnchecked {
    seq: u64,
}

impl base::Cookie for GetVersionCookie {
    unsafe fn from_sequence(seq: u64) -> Self {
        GetVersionCookie { seq }
    }

    fn sequence(&self) -> u64 {
        self.seq
    }
}

unsafe impl base::CookieChecked for GetVersionCookie {
}

unsafe impl base::CookieWithReplyChecked for GetVersionCookie {
    type Reply = GetVersionReply;
}

impl base::Cookie for GetVersionCookieUnchecked {
    unsafe fn from_sequence(seq: u64) -> Self {
        GetVersionCookieUnchecked { seq }
    }

    fn sequence(&self) -> u64 {
        self.seq
    }
}

unsafe impl base::CookieWithReplyUnchecked for GetVersionCookieUnchecked {
    type Reply = GetVersionReply;
}

/// The `GetVersion` request.
///
/// This request replies [GetVersionReply].
///
/// Associated cookie types are [GetVersionCookie] and [GetVersionCookieUnchecked].
#[derive(Clone, Debug)]
pub struct GetVersion {
    pub major_version: u8,
    pub minor_version: u16,
}

unsafe impl base::RawRequest for GetVersion {
    fn raw_request(&self, c: &base::Connection, checked: bool) -> u64 { unsafe {
        let mut protocol_request = xcb_protocol_request_t {
            count: 2,
            ext: (&mut FFI_EXT) as *mut _,
            opcode: 0,
            isvoid: 0,
        };

        let mut sections: [iovec; 4] = [iovec {
            iov_base: std::ptr::null_mut(),
            iov_len: 0,
        }; 4];

        let buf0: &mut [u8] = &mut [0; 8];
        self.major_version.serialize(&mut buf0[4 .. ]);
        self.minor_version.serialize(&mut buf0[6 .. ]);
        sections[2].iov_base = buf0.as_mut_ptr() as *mut _;
        sections[2].iov_len = 8;
        sections[3].iov_len = base::align_pad(sections[2].iov_len, 4);

        let flags = if checked { base::RequestFlags::CHECKED } else { base::RequestFlags::NONE };

        xcb_send_request64(
            c.get_raw_conn(),
            flags.bits() as _,
            sections.as_mut_ptr().add(2),
            &mut protocol_request as *mut _,
        )
    }
}}

impl base::Request for GetVersion {
    type Cookie = GetVersionCookie;
    const IS_VOID: bool = false;
}

impl base::RequestWithReply for GetVersion {
    type Reply = GetVersionReply;
    type Cookie = GetVersionCookie;
    type CookieUnchecked = GetVersionCookieUnchecked;
}

/// Reply type for [CompareCursor].
///
/// Can be obtained from a [CompareCursorCookie] with [Connection::wait_for_reply](crate::Connection::wait_for_reply)
/// or from a [CompareCursorCookieUnchecked] with [Connection::wait_for_reply_unchecked](crate::Connection::wait_for_reply_unchecked)
pub struct CompareCursorReply {
    raw: *const u8,
}

impl CompareCursorReply {

    fn wire_ptr(&self) -> *const u8 {
        self.raw
    }

    fn wire_len(&self) -> usize {
        (32 + self.length() * 4) as _
    }

    pub fn response_type(&self) -> u8 {
        unsafe {
            let offset = 0usize;
            let ptr = self.wire_ptr().add(offset) as *const u8;
            *ptr
        }
    }

    pub fn same(&self) -> bool {
        let val = unsafe { *(self.wire_ptr().add(1usize)) };
        val != 0
    }

    pub fn sequence(&self) -> u16 {
        unsafe {
            let offset = 2usize;
            let ptr = self.wire_ptr().add(offset) as *const u16;
            *ptr
        }
    }

    pub fn length(&self) -> u32 {
        unsafe {
            let offset = 4usize;
            let ptr = self.wire_ptr().add(offset) as *const u32;
            *ptr
        }
    }
}

impl base::Reply for CompareCursorReply {
    unsafe fn from_raw(raw: *const u8) -> Self {
        Self { raw }
    }

    unsafe fn into_raw(self) -> *const u8 {
        let raw = self.raw;
        std::mem::forget(self);
        raw
    }
}

impl std::fmt::Debug for CompareCursorReply {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompareCursorReply")
            .field("response_type", &self.response_type())
            .field("same", &self.same())
            .field("sequence", &self.sequence())
            .field("length", &self.length())
            .finish()
    }
}

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

unsafe impl std::marker::Send for CompareCursorReply {}
unsafe impl std::marker::Sync for CompareCursorReply {}

/// Cookie type for [CompareCursor].
///
/// This cookie can be used to get a [CompareCursorReply]
/// with [Connection::wait_for_reply](crate::Connection::wait_for_reply)
#[derive(Debug)]
pub struct CompareCursorCookie {
    seq: u64,
}

#[derive(Debug)]
/// Unchecked cookie type for [CompareCursor].
///
/// This cookie can be used to get a [CompareCursorReply]
/// with [Connection::wait_for_reply_unchecked](crate::Connection::wait_for_reply_unchecked)
pub struct CompareCursorCookieUnchecked {
    seq: u64,
}

impl base::Cookie for CompareCursorCookie {
    unsafe fn from_sequence(seq: u64) -> Self {
        CompareCursorCookie { seq }
    }

    fn sequence(&self) -> u64 {
        self.seq
    }
}

unsafe impl base::CookieChecked for CompareCursorCookie {
}

unsafe impl base::CookieWithReplyChecked for CompareCursorCookie {
    type Reply = CompareCursorReply;
}

impl base::Cookie for CompareCursorCookieUnchecked {
    unsafe fn from_sequence(seq: u64) -> Self {
        CompareCursorCookieUnchecked { seq }
    }

    fn sequence(&self) -> u64 {
        self.seq
    }
}

unsafe impl base::CookieWithReplyUnchecked for CompareCursorCookieUnchecked {
    type Reply = CompareCursorReply;
}

/// The `CompareCursor` request.
///
/// This request replies [CompareCursorReply].
///
/// Associated cookie types are [CompareCursorCookie] and [CompareCursorCookieUnchecked].
#[derive(Clone, Debug)]
pub struct CompareCursor {
    pub window: xproto::Window,
    pub cursor: xproto::Cursor,
}

unsafe impl base::RawRequest for CompareCursor {
    fn raw_request(&self, c: &base::Connection, checked: bool) -> u64 { unsafe {
        let mut protocol_request = xcb_protocol_request_t {
            count: 2,
            ext: (&mut FFI_EXT) as *mut _,
            opcode: 1,
            isvoid: 0,
        };

        let mut sections: [iovec; 4] = [iovec {
            iov_base: std::ptr::null_mut(),
            iov_len: 0,
        }; 4];

        let buf0: &mut [u8] = &mut [0; 12];
        self.window.serialize(&mut buf0[4 .. ]);
        self.cursor.serialize(&mut buf0[8 .. ]);
        sections[2].iov_base = buf0.as_mut_ptr() as *mut _;
        sections[2].iov_len = 12;
        sections[3].iov_len = base::align_pad(sections[2].iov_len, 4);

        let flags = if checked { base::RequestFlags::CHECKED } else { base::RequestFlags::NONE };

        xcb_send_request64(
            c.get_raw_conn(),
            flags.bits() as _,
            sections.as_mut_ptr().add(2),
            &mut protocol_request as *mut _,
        )
    }
}}

impl base::Request for CompareCursor {
    type Cookie = CompareCursorCookie;
    const IS_VOID: bool = false;
}

impl base::RequestWithReply for CompareCursor {
    type Reply = CompareCursorReply;
    type Cookie = CompareCursorCookie;
    type CookieUnchecked = CompareCursorCookieUnchecked;
}

/// The `FakeInput` request.
///
/// This request has no reply.
///
/// Associated cookie types are [VoidCookie](crate::VoidCookie) and [VoidCookieChecked](crate::VoidCookieChecked).
#[derive(Clone, Debug)]
pub struct FakeInput {
    pub r#type: u8,
    pub detail: u8,
    pub time: u32,
    pub root: xproto::Window,
    pub root_x: i16,
    pub root_y: i16,
    pub deviceid: u8,
}

unsafe impl base::RawRequest for FakeInput {
    fn raw_request(&self, c: &base::Connection, checked: bool) -> u64 { unsafe {
        let mut protocol_request = xcb_protocol_request_t {
            count: 2,
            ext: (&mut FFI_EXT) as *mut _,
            opcode: 2,
            isvoid: 1,
        };

        let mut sections: [iovec; 4] = [iovec {
            iov_base: std::ptr::null_mut(),
            iov_len: 0,
        }; 4];

        let buf0: &mut [u8] = &mut [0; 36];
        self.r#type.serialize(&mut buf0[4 .. ]);
        self.detail.serialize(&mut buf0[5 .. ]);
        self.time.serialize(&mut buf0[8 .. ]);
        self.root.serialize(&mut buf0[12 .. ]);
        self.root_x.serialize(&mut buf0[24 .. ]);
        self.root_y.serialize(&mut buf0[26 .. ]);
        self.deviceid.serialize(&mut buf0[35 .. ]);
        sections[2].iov_base = buf0.as_mut_ptr() as *mut _;
        sections[2].iov_len = 36;
        sections[3].iov_len = base::align_pad(sections[2].iov_len, 4);

        let flags = if checked { base::RequestFlags::CHECKED } else { base::RequestFlags::NONE };

        xcb_send_request64(
            c.get_raw_conn(),
            flags.bits() as _,
            sections.as_mut_ptr().add(2),
            &mut protocol_request as *mut _,
        )
    }
}}

impl base::Request for FakeInput {
    type Cookie = base::VoidCookie;
    const IS_VOID: bool = true;
}

impl base::RequestWithoutReply for FakeInput {
}

/// The `GrabControl` request.
///
/// This request has no reply.
///
/// Associated cookie types are [VoidCookie](crate::VoidCookie) and [VoidCookieChecked](crate::VoidCookieChecked).
#[derive(Clone, Debug)]
pub struct GrabControl {
    pub impervious: bool,
}

unsafe impl base::RawRequest for GrabControl {
    fn raw_request(&self, c: &base::Connection, checked: bool) -> u64 { unsafe {
        let mut protocol_request = xcb_protocol_request_t {
            count: 2,
            ext: (&mut FFI_EXT) as *mut _,
            opcode: 3,
            isvoid: 1,
        };

        let mut sections: [iovec; 4] = [iovec {
            iov_base: std::ptr::null_mut(),
            iov_len: 0,
        }; 4];

        let buf0: &mut [u8] = &mut [0; 8];
        (if self.impervious { 1u8 } else { 0u8 }).serialize(&mut buf0[4 .. ]);
        sections[2].iov_base = buf0.as_mut_ptr() as *mut _;
        sections[2].iov_len = 8;
        sections[3].iov_len = base::align_pad(sections[2].iov_len, 4);

        let flags = if checked { base::RequestFlags::CHECKED } else { base::RequestFlags::NONE };

        xcb_send_request64(
            c.get_raw_conn(),
            flags.bits() as _,
            sections.as_mut_ptr().add(2),
            &mut protocol_request as *mut _,
        )
    }
}}

impl base::Request for GrabControl {
    type Cookie = base::VoidCookie;
    const IS_VOID: bool = true;
}

impl base::RequestWithoutReply for GrabControl {
}