summaryrefslogtreecommitdiff
path: root/src/safe_x11/mod.rs
blob: 4a1e0296ce6ab7c4225392d417bc8ca56884156b (plain)
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
// See LICENSE file for copyright and license details.

//! Safe wrapper around the `x11-rs` crate. This should be as much safe as possible.

#![allow(dead_code)]
use x11::xlib;
use x11::xlib::{
    Display,
    XDisplayWidth, XDisplayHeight,
    XDefaultScreen,
    XConnectionNumber,
    Cursor,
    XDefaultRootWindow,
    XQueryTree,

    XEvent,
    XNextEvent,
    XDefaultGC,

    // Windows
    Window,
    GC,

    Atom, XInternAtom,
};
use x11::xlib::XKeyEvent;

use std::ffi::CString;
use std::ffi::NulError;
use std::ptr;
use std::error;
use std::mem::uninitialized;
use std::slice;
use std::fmt;
use libc::c_int;

pub mod window;
pub mod display;

#[derive(Debug)]
pub struct XSafeError<'a> {
    _description: &'a str,
}

impl<'a> XSafeError<'a> {
    fn new(desc: &'static str) -> XSafeError<'a> {
        XSafeError { _description: desc }
    }
}

impl<'a> From<NulError> for XSafeError<'a> {
    fn from(_: NulError) -> XSafeError<'a> {
        XSafeError::new("Null ponter error!")
    }
}

impl<'a> error::Error for XSafeError<'a> {
    fn description(&self) -> &str {
        self._description
    }

    fn cause(&self) -> Option<&error::Error> {
        None
    }
}

impl<'a> fmt::Display for XSafeError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(f, "{}", self._description)
    }
}

pub fn close_display(display: *mut Display) {
    unsafe { xlib::XCloseDisplay(display); }
}

/// Get the file descriptor for the `XServer`
pub fn x11_fd(display: *mut Display) -> c_int {
    unsafe { XConnectionNumber(display) }
}

/// Get the next event from the xserver. This call will not block forever
/// (like `XNextEvent`), instead it will wait for a certain time (1 second
/// for now, but it can change) so we're not blocking the socket interface
/// on the main thread.
pub fn next_xevent(display: *mut Display) -> XEvent {
    unsafe {
        let mut last_event: XEvent = uninitialized();
        XNextEvent(display, &mut last_event);
        last_event
    }
}

pub fn screen_size(display: *mut Display) -> (u32, u32) {
    let screen = unsafe { XDefaultScreen(display) };
    let dw: u32 = unsafe { XDisplayWidth(display, screen) as u32 };
    let dh: u32 = unsafe { XDisplayHeight(display, screen) as u32 };
    (dw, dh)
}

pub fn root_window(display: *mut Display) -> Window {
    unsafe { xlib::XDefaultRootWindow(display) }
}

/// Grab pointer buttons. 
///
/// # Example
///
/// ```
/// grab_button(
///     // Display
///     display,
///     // Button to press
///     xlib::Button1 as i32,
///     // Modifiers (can be an or of modifiers).
///     xlib::Mod1Mask,
///     // owner events.
///     true,
///     // Which motions we'll handle
///     ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
///     // Keyboard and pointer sync moddes
///     GrabModeAsync, GrabModeAsync,
///     // Confine to and cursor. (Can be 0 :) )
///     0, 0
/// );
/// ```
#[allow(too_many_arguments)]
pub fn grab_button(display: *mut Display, button: u32, modifiers: u32,
                   owner_events: bool, event_mask: i64, pointer_mode: i32,
                   keyboard_mode: i32, confine_to: Window,
                   cursor: Cursor) {
    unsafe {
        let default_win = xlib::XDefaultRootWindow(display);
        xlib::XGrabButton(display, button, modifiers, default_win,
                          owner_events as i32, event_mask as u32, pointer_mode,
                          keyboard_mode, confine_to, cursor);
    }
}

/// Unregister a combination of keys that will send a `XEvent`
pub fn ungrab_button(display: *mut Display, button: u32, modifiers: u32) {
    unsafe {
        let default_win = xlib::XDefaultRootWindow(display);
        xlib::XUngrabButton(display, button, modifiers, default_win);
    }
}

/// Register a combination of keys that will send a `XEvent`
///
pub fn grab_key(display: *mut Display, key: u32, modifiers: u32, owner_events: bool,
                pointer_mode: i32, keyboard_mode: i32) {
    unsafe {
        let default_win = xlib::XDefaultRootWindow(display);
        let keycode: i32 = xlib::XKeysymToKeycode(display, key as u64) as i32;
        xlib::XGrabKey(display, keycode, modifiers, default_win,
                       owner_events as i32, pointer_mode, keyboard_mode);
    }
}
/// Unregister a combination of keys that will send a `XEvent`
pub fn ungrab_key(display: *mut Display, key: u32, modifiers: u32) {
    unsafe {
        let default_win = xlib::XDefaultRootWindow(display);
        let keycode: i32 = xlib::XKeysymToKeycode(display, key as u64) as i32;
        xlib::XUngrabKey(display, keycode, modifiers, default_win);
    }
}

// Window code.

/// Get a list from the active windows. This doesn't generate a hierarchical
/// struture, so it may change on the future.
pub fn window_list(display: *mut Display) -> &'static [Window] {
    let mut root: Window = 0;
    let mut parent: Window = 0;
    let mut children_count: u32 = 0;
    unsafe {
        let root_window = XDefaultRootWindow(display);
        let mut children: *mut Window = uninitialized();
        XQueryTree(display, root_window,
                   &mut root, &mut parent,
                   &mut children, &mut children_count);
        slice::from_raw_parts(children as *const Window, children_count as usize)
    }
}

fn screen_ratio(d: *mut Display) -> f32 {
    let screen: xlib::Screen = unsafe {
        let scrptr = xlib::XDefaultScreenOfDisplay(d);
        ptr::read(scrptr)
    };

    screen.height as f32 / screen.width as f32
}

/// Get certain color from the display.
///
/// # Example.
///
/// This function can be called with a &str
///
/// ```
/// get_color(display, "red");
/// ```
fn get_color<T: Into<Vec<u8>>>(display: *mut Display, color: T) -> u64{
    let screen_num = unsafe { xlib::XDefaultScreen(display) };
    let colormap = unsafe { xlib::XDefaultColormap(display, screen_num) };
    unsafe {
        let mut xcolor: xlib::XColor = uninitialized();
        let cstr = CString::new(color).unwrap();
        xlib::XAllocNamedColor(display, colormap, cstr.as_ptr(),
                               &mut xcolor, &mut xcolor);

        xcolor.pixel
    }
}

fn default_gc(display: *mut Display) -> GC {
    let screen_num = unsafe { xlib::XDefaultScreen(display) };
    unsafe { XDefaultGC(display, screen_num) }
}

/// Get the keysym for the given event.
pub fn lookup_keysym(ev: &mut XKeyEvent) -> xlib::KeySym {
    unsafe { xlib::XLookupKeysym(ev, 0) }
}

pub fn atom<T: Into<Vec<u8>>>(display: *mut Display, name: T) -> Atom {
    unsafe {
        let cstr = CString::new(name).unwrap();
        XInternAtom(display, cstr.as_ptr(), 0)
    }
}