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
/*
 * Copyright (C) 2013 James Miller <james@aatch.net>
 * Copyright (c) 2016
 *         Remi Thebault <remi.thebault@gmail.com>
 *         Thomas Bracht Laumann Jespersen <laumann.thomas@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any
 * person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the
 * Software without restriction, including without
 * limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software
 * is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice
 * shall be included in all copies or substantial portions
 * of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
 * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
 * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
 * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */


use xproto::*;
use ffi::base::*;
use ffi::xproto::*;
#[cfg(feature="xlib_xcb")]
use ffi::xlib_xcb::*;

#[cfg(feature="xlib_xcb")]
use x11::xlib;

use libc::{self, c_int, c_char, c_void};
use std::option::Option;

use std::mem;
use std::ptr::{null, null_mut};
use std::marker::PhantomData;
// std::num::Zero is unstable in rustc 1.5 => remove the Zero defined
// hereunder as soon as Zero gets stabilized (or replaced by something else)
//use std::num::Zero;
use std::cmp::Ordering;
use std::ops::{BitAnd, BitOr};



pub const NONE: u32 = 0;
pub const COPY_FROM_PARENT: u32 = 0;
pub const CURRENT_TIME: u32 = 0;
pub const NO_SYMBOL: u32 = 0;


pub type Extension = xcb_extension_t;


/// `StructPtr` is a wrapper for pointer to struct owned by XCB
/// that must not be freed
/// it is instead bound to the lifetime of its parent that it borrows immutably
pub struct StructPtr<'a, T: 'a> {
    pub ptr: *mut T,
    phantom: PhantomData<&'a T>
}



/// `Event` wraps a pointer to `xcb_*_event_t`
/// this pointer will be freed when the `Event` goes out of scope
pub struct Event<T> {
   pub ptr: *mut T
}

impl<T> Event<T> {
    pub fn response_type(&self) -> u8 {
        unsafe {
            let gev : *mut xcb_generic_event_t = mem::transmute(self.ptr);
            (*gev).response_type
        }
    }
}

impl<T> Drop for Event<T> {
    fn drop(&mut self) {
        unsafe {
            libc::free(self.ptr as *mut c_void);
        }
    }
}

/// Casts the generic event to the right event. Assumes that the given
/// event is really the correct type.
pub fn cast_event<'r, T>(event : &'r GenericEvent) -> &'r T {
    // This isn't very safe... but other options incur yet more overhead
    // that I really don't want to.
    unsafe { mem::transmute(event) }
}




/// `Error` wraps a pointer to `xcb_*_error_t`
/// this pointer will be freed when the `Error` goes out of scope
#[derive(Debug)]
pub struct Error<T> {
    pub ptr: *mut T
}

impl<T> Error<T> {
    pub fn response_type(&self) -> u8 {
        unsafe {
            let ger : *mut xcb_generic_error_t = mem::transmute(self.ptr);
            (*ger).response_type
        }
    }
    pub fn error_code(&self) -> u8 {
        unsafe {
            let ger : *mut xcb_generic_error_t = mem::transmute(self.ptr);
            (*ger).error_code
        }
    }
}

impl<T> Drop for Error<T> {
    fn drop(&mut self) {
        unsafe {
            libc::free(self.ptr as *mut c_void);
        }
    }
}

/// Casts the generic error to the right error. Assumes that the given
/// errir is really the correct type.
pub fn cast_error<'r, T>(error : &'r GenericError) -> &'r T {
    // This isn't very safe... but other options incur yet more overhead
    // that I really don't want to.
    unsafe { mem::transmute(error) }
}




/// wraps a cookie as returned by a request function
/// instantiation of `Cookie` that are not `VoidCookie`
/// should provide a `get_reply` method to return a `Reply`
pub struct Cookie<T: Copy> {
    pub cookie: T,
    pub conn: *mut xcb_connection_t,
    pub checked: bool
}

pub type VoidCookie = Cookie<xcb_void_cookie_t>;

impl VoidCookie {
    pub fn request_check(&self) -> Result<(), GenericError> {
        unsafe {
            let c : xcb_void_cookie_t = mem::transmute(self.cookie);
            let err = xcb_request_check(self.conn, c);

            if err.is_null() {
                Ok(())
            } else {
                Err(GenericError{ ptr: err })
            }
        }
    }
}



/// Wraps a pointer to a `xcb_*_reply_t`
/// the pointer is freed when the `Reply` goes out of scope
pub struct Reply<T> {
    pub ptr: *mut T
}

impl<T> Drop for Reply<T> {
    fn drop(&mut self) {
        unsafe {
            libc::free(self.ptr as *mut c_void);
        }
    }
}


pub type GenericEvent = Event<xcb_generic_event_t>;
pub type GenericError = Error<xcb_generic_error_t>;
pub type GenericReply = Reply<xcb_generic_reply_t>;




pub type AuthInfo = xcb_auth_info_t;
//TODO: Implement wrapper functions for constructing auth_info



#[cfg(feature="xlib_xcb")]
pub enum EventQueueOwner {
    Xcb,
    Xlib
}


/// wraps an `xcb_connection_t` object
/// will call `xcb_disconnect` when the `Connection` goes out of scope
/// (unless the `Connection` is made with `from_raw_conn`)
pub struct Connection {
    c:   *mut xcb_connection_t,
    #[cfg(feature="xlib_xcb")]
    dpy: *mut xlib::Display,
}

impl Connection {
    pub fn flush(&self) -> bool {
        unsafe {
            xcb_flush(self.c) > 0
        }
    }

    pub fn get_maximum_request_length(&self) -> u32 {
        unsafe {
            xcb_get_maximum_request_length(self.c)
        }
    }

    pub fn wait_for_event(&self) -> Option<GenericEvent> {
        unsafe {
            let event = xcb_wait_for_event(self.c);
            if event.is_null() {
                None
            } else {
                Some(GenericEvent { ptr: event })
            }
        }
    }

    pub fn poll_for_event(&self) -> Option<GenericEvent> {
        unsafe {
            let event = xcb_poll_for_event(self.c);
            if event.is_null() {
                None
            } else {
                Some(GenericEvent { ptr: event })
            }
        }
    }

    pub fn poll_for_queued_event(&self) -> Option<GenericEvent> {
        unsafe {
            let event = xcb_poll_for_queued_event(self.c);
            if event.is_null() {
                None
            } else {
                Some(GenericEvent { ptr: event })
            }
        }
    }

    pub fn get_setup(&self) -> Setup {
        unsafe {

            let setup = xcb_get_setup(self.c);
            if setup.is_null() {
                panic!("NULL setup on connection")
            }
            mem::transmute(setup)
        }
    }

    pub fn has_error(&self) -> bool {
        unsafe {
            xcb_connection_has_error(self.c) > 0
        }
    }

    pub fn generate_id(&self) -> Window {
        unsafe {
            xcb_generate_id(self.c)
        }
    }

    pub fn get_raw_conn(&self) -> *mut xcb_connection_t {
        self.c
    }

    #[cfg(feature="xlib_xcb")]
    pub fn get_raw_dpy(&self) -> *mut xlib::Display {
        self.dpy
    }

    pub fn send_event<T>(&self,
                  propogate: bool,
                  destination: Window,
                  event_mask : u32,
                  event : Event<T>) {
        unsafe {
        xcb_send_event(self.c,
            propogate as u8, destination as xcb_window_t,
            event_mask, event.ptr as *mut c_char);
        }
    }


    pub fn prefetch_extension_data(&self, ext: &mut Extension) {
        unsafe {
            xcb_prefetch_extension_data(self.c, ext);
        }
    }


    pub fn get_extension_data(&self, ext: &mut Extension)
            -> Option<QueryExtensionData> {
        unsafe {
            let ptr = xcb_get_extension_data(self.c, ext);
            if !ptr.is_null() { Some(QueryExtensionData { ptr: ptr }) }
            else { None }
        }
    }

    #[cfg(feature="xlib_xcb")]
    pub fn set_event_queue_owner(&self, owner: EventQueueOwner) {
        if self.dpy.is_null() {
            panic!("set_event_queue_owner needs the xlib::Display");
        }
        unsafe {
            let owner = match owner {
                EventQueueOwner::Xcb => XCBOwnsEventQueue,
                EventQueueOwner::Xlib => XlibOwnsEventQueue
            };
            XSetEventQueueOwner(self.dpy, owner);
        }
    }



    #[cfg(not(feature="xlib_xcb"))]
    pub fn connect() -> (Connection, i32) {
        let mut screen_num : c_int = 0;
        unsafe {
            let conn = xcb_connect(null_mut(), &mut screen_num);
            if conn.is_null() {
                panic!("Couldn't connect")
            } else {
                xcb_prefetch_maximum_request_length(conn);
                (
                    Connection {
                        c:conn,
                    },
                    screen_num as i32
                )
            }
        }
    }

    #[cfg(feature="xlib_xcb")]
    pub fn connect_with_xlib_display() -> (Connection, i32) {
        unsafe {
            let dpy = xlib::XOpenDisplay(null());
            let conn = XGetXCBConnection(dpy);
            if conn.is_null() || dpy.is_null() {
                panic!("Couldn't connect")
            } else {
                xcb_prefetch_maximum_request_length(conn);
                (
                    Connection {
                        c:   conn,
                        dpy: dpy,
                    },
                    xlib::XDefaultScreen(dpy) as i32
                )
            }
        }
    }

    #[cfg(feature="xlib_xcb")]
    pub fn new_from_xlib_display(dpy: *mut xlib::Display) -> Connection {
        unsafe {
            if dpy.is_null() {
                panic!("attempt connect with null display");
            }
            Connection {
                c: XGetXCBConnection(dpy),
                dpy: dpy
            }
        }
    }




    #[cfg(not(feature="xlib_xcb"))]
    pub fn connect_to_display(display:&str) -> Option<(Connection, i32)> {
        let mut screen_num : c_int = 0;
        unsafe {
            let conn = {
                let s = display.as_ptr();
                xcb_connect(s as *mut c_char, &mut screen_num)
            };
            if conn.is_null() {
                None
            } else {
                xcb_prefetch_maximum_request_length(conn);
                Some((
                    Connection {
                        c:conn,
                    },
                    screen_num as i32
                ))
            }
        }
    }

    #[cfg(not(feature="xlib_xcb"))]
    pub fn connect_with_auth(display:&str, auth_info: &AuthInfo) -> Option<(Connection, i32)> {
        let mut screen_num : c_int = 0;
        unsafe {
            let conn = {
                let s = display.as_ptr();
                xcb_connect_to_display_with_auth_info(
                        s as *mut c_char,
                        mem::transmute(auth_info),
                        &mut screen_num)
            };
            if conn.is_null() {
                None
            } else {
                xcb_prefetch_maximum_request_length(conn);
                Some((
                    Connection {
                        c:conn,
                    },
                    screen_num as i32
                ))
            }
        }
    }

    #[cfg(not(feature="xlib_xcb"))]
    pub unsafe fn from_raw_conn(conn: *mut xcb_connection_t) -> Connection {
        if conn.is_null() {
            panic!("Cannot construct from null pointer");
        }

        Connection {
            c:  conn,
        }
    }

}

impl Drop for Connection {
    #[cfg(not(feature="xlib_xcb"))]
    fn drop(&mut self) {
        unsafe {
            xcb_disconnect(self.c);
        }
    }

    #[cfg(feature="xlib_xcb")]
    fn drop(&mut self) {
        unsafe {
            if self.dpy.is_null() {
                xcb_disconnect(self.c);
            }
            else {
                xlib::XCloseDisplay(self.dpy);
            }
        }
    }
}


// Mimics xproto::QueryExtensionReply, but without the Drop trait.
// Used for Connection::get_extension_data whose returned value
// must not be freed.
// Named QueryExtensionData to avoid name collision
pub struct QueryExtensionData {
    ptr: *const xcb_query_extension_reply_t
}

impl QueryExtensionData {
    pub fn present(&self) -> u8 {
        unsafe {
            (*self.ptr).present
        }
    }
    pub fn major_opcode(&self) -> u8 {
        unsafe {
            (*self.ptr).major_opcode
        }
    }
    pub fn first_event(&self) -> u8 {
        unsafe {
            (*self.ptr).first_event
        }
    }
    pub fn first_error(&self) -> u8 {
        unsafe {
            (*self.ptr).first_error
        }
    }
}


pub trait Zero {
    fn zero() -> Self;
}

impl Zero for u8    { fn zero() -> u8    {0} }
impl Zero for u16   { fn zero() -> u16   {0} }
impl Zero for u32   { fn zero() -> u32   {0} }
impl Zero for u64   { fn zero() -> u64   {0} }
impl Zero for usize { fn zero() -> usize {0} }
impl Zero for i8    { fn zero() -> i8    {0} }
impl Zero for i16   { fn zero() -> i16   {0} }
impl Zero for i32   { fn zero() -> i32   {0} }
impl Zero for i64   { fn zero() -> i64   {0} }
impl Zero for isize { fn zero() -> isize {0} }
impl Zero for f32   { fn zero() -> f32   {0f32} }
impl Zero for f64   { fn zero() -> f64   {0f64} }

pub fn pack_bitfield<T, L>(bf : &mut Vec<(T,L)>) -> (T, Vec<L>)
    where T: Ord + Zero + Copy + BitAnd<Output=T> + BitOr<Output=T>,
          L: Copy {
	bf.sort_by(|a,b| {
        let &(a, _) = a;
        let &(b, _) = b;
        if a < b {
            Ordering::Less
        }
        else if a > b {
            Ordering::Greater
        }
        else {
            Ordering::Equal
        }
    });

    let mut mask = T::zero();
    let mut list: Vec<L> = Vec::new();

    for el in bf.iter() {
        let &(f, v) = el;
        if mask & f > T::zero() {
            continue;
        } else {
            mask = mask|f;
            list.push(v);
        }
    }

    (mask, list)
}