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
extern crate x11;

use self::x11::xlib::*;
use self::x11::xtest::*;
use std::mem::{uninitialized, transmute};
use ::*;
use std::thread::spawn;

pub mod inputs;

lazy_static! {
    static ref LBUTTON_STATE: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
    static ref MBUTTON_STATE: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
    static ref RBUTTON_STATE: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
    static ref KEYBD_BINDS: Arc<Mutex<HashMap<u64, Arc<Fn() + Send + Sync + 'static>>>> = Arc::new(Mutex::new(HashMap::<u64, Arc<Fn() + Send + Sync + 'static>>::new()));
    static ref MOUSE_BINDS: Arc<Mutex<HashMap<MouseButton, Arc<Fn() + Send + Sync + 'static>>>> = Arc::new(Mutex::new(HashMap::<MouseButton, Arc<Fn() + Send + Sync + 'static>>::new()));
}

impl KeybdKey {
    pub fn bind<F>(self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        let input = get_key_code(self as u64) as u64;
        KEYBD_BINDS.lock().unwrap().insert(input, Arc::new(callback));
        with_display2(|display| {
            let window = unsafe {XDefaultRootWindow(display)};
            unsafe{XGrabKey(
                display,
                input as i32,
                ShiftMask,
                window,
                0,
                GrabModeAsync,
                GrabModeAsync,
            )};
            unsafe{XGrabKey(
                display,
                input as i32,
                0,
                window,
                0,
                GrabModeAsync,
                GrabModeAsync,
            )};
        });
        if KEYBD_BINDS.lock().unwrap().len() != 1 {
            return;
        };
        spawn(move || while KEYBD_BINDS.lock().unwrap().len() != 0 {
            unsafe{handle_event()};
        });
    }

    pub fn unbind(self) {
        let input = get_key_code(self as u64) as u64;
        KEYBD_BINDS.lock().unwrap().remove(&input);
    }

    pub fn is_pressed(self) -> bool {
        let code = get_key_code(self as _);
        let mut array: [i8; 32] = [0; 32];
        with_display(|display| unsafe {
            XQueryKeymap(display, transmute(&mut array));
        });
        array[(code >> 3) as usize] & (1 << (code & 7)) != 0
    }

    pub fn press(self) {
        send_keybd_input(get_key_code(self as _), 1);
    }

    pub fn release(self) {
        send_keybd_input(get_key_code(self as _), 0);
    }
}

impl MouseButton {
    pub fn bind<F>(self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        MOUSE_BINDS.lock().unwrap().insert(self, Arc::new(callback));
        with_display2(|display| {
            let window = unsafe{XDefaultRootWindow(display)};
            grab_button(self as _, display, window);
        });
        if KEYBD_BINDS.lock().unwrap().len() != 1 {
            return;
        };
        if MOUSE_BINDS.lock().unwrap().len() != 1 {
            return;
        };
        spawn(move || while KEYBD_BINDS.lock().unwrap().len() != 0 {
            unsafe{handle_event()};
        });
    }

    pub fn unbind(self) {
        let input = get_key_code(self as u64) as u64;
        KEYBD_BINDS.lock().unwrap().remove(&input);
    }

    pub fn is_pressed(self) -> bool {
        match self {
            MouseButton::LeftButton => *LBUTTON_STATE.lock().unwrap(),
            MouseButton::RightButton => *RBUTTON_STATE.lock().unwrap(),
            MouseButton::MiddleButton => *MBUTTON_STATE.lock().unwrap(),
            _ => false
        }
    }

    pub fn press(self) {
        send_mouse_input(self as _, 1);
    }

    pub fn release(self) {
        send_mouse_input(self as _, 0);
    }
}

fn get_key_code(code: u64) -> u8 {
    let mut key_code = 0;
    with_display(|display| key_code = unsafe { XKeysymToKeycode(display, code) });
    key_code
}

fn with_display<F>(cb: F)
where
    F: FnOnce(*mut Display),
{
    let display = *STATE.lock().unwrap() as *mut Display;
    unsafe {
        XLockDisplay(display);
    };
    cb(display);
    unsafe {
        XUnlockDisplay(display);
        XFlush(display) 
    };
}

fn with_display2<F>(cb: F)
where
    F: FnOnce(*mut Display),
{
    let display = *STATE2.lock().unwrap() as *mut Display;
    unsafe {
        XLockDisplay(display);
    };
    cb(display);
    unsafe {
        XUnlockDisplay(display);
    };
    unsafe { XFlush(display) };
}

fn grab_button(button: u32, display: *mut Display, window: u64) {
    unsafe {
        XGrabButton(
            display,
            button,
            AnyModifier,
            window,
            1,
            (ButtonPressMask | ButtonReleaseMask) as u32,
            GrabModeAsync,
            GrabModeAsync,
            0,
            0,
        );
    }
}

lazy_static! {
    static ref STATE: Arc<Mutex<u64>> = {unsafe{
        XInitThreads();
        Arc::new(Mutex::new(XOpenDisplay(std::ptr::null()) as u64))
    }};
    static ref STATE2: Arc<Mutex<u64>> = {unsafe{
        XInitThreads();
        Arc::new(Mutex::new(XOpenDisplay(std::ptr::null()) as u64))
    }};
}

pub unsafe fn handle_event() {
    let mut ev = uninitialized();
    with_display2(|display| {
        XNextEvent(display, &mut ev);
    });
    let mut keybd_key: Option<u64> = None;
    let mut mouse_button: Option<MouseButton> = None;
    match ev.get_type() {
        KeyPress => keybd_key = Some(
            (ev.as_ref() as &XKeyEvent).keycode as u64
        ),
        ButtonPress => {
            match (ev.as_ref() as &XKeyEvent).keycode {
                1 => {
                    *LBUTTON_STATE.lock().unwrap() = true;
                    mouse_button = Some(MouseButton::LeftButton)
                },
                2 => {
                    *MBUTTON_STATE.lock().unwrap() = true;
                    mouse_button = Some(MouseButton::MiddleButton)
                },
                3 => {
                    *RBUTTON_STATE.lock().unwrap() = true;
                    mouse_button = Some(MouseButton::RightButton)
                },
                _ => {},
            }
        }
        ButtonRelease => {
            match (ev.as_ref() as &XKeyEvent).keycode {
                1 => *LBUTTON_STATE.lock().unwrap() = false,
                2 => *MBUTTON_STATE.lock().unwrap() = false,
                3 => *RBUTTON_STATE.lock().unwrap() = false,
                _ => {},
            }
        }
        _ => {},
    };
    if let Some(event) = keybd_key {
        if let Some(cb) = KEYBD_BINDS.lock().unwrap().get_mut(&event) {
            let cb = cb.clone();
            spawn(move || cb());
        };
    }
    if let Some(event) = mouse_button {
        if let Some(cb) = MOUSE_BINDS.lock().unwrap().get_mut(&event) {
            let cb = cb.clone();
            spawn(move || cb());
        };
    }
}

pub fn mouse_move_to(x: i32, y: i32) {
    with_display(|display| unsafe {
        XWarpPointer(display, 0, 0, 0, 0, 0, 0, x, y);
    });
}

pub fn mouse_move(x: i32, y: i32) {
    with_display(|display| unsafe {
        XWarpPointer(display, 0, 0, 0, 0, 0, 0, x, y);
    });
}

fn send_mouse_input(button: u32, is_press: i32) {
    with_display(|display| unsafe {
        XTestFakeButtonEvent(display, button, is_press, 0);
    });
}

fn send_keybd_input(code: u8, is_press: i32) {
    with_display(|display| unsafe {
        XTestFakeKeyEvent(display, code as u32, is_press, 0);
    });
}

pub fn keybd_press(code: u64) {
    send_keybd_input(get_key_code(code), 1);
}

pub fn keybd_release(code: u64) {
    send_keybd_input(get_key_code(code), 0);
}

pub fn num_lock_is_toggled() -> bool {
    let mut state: XKeyboardState = unsafe { uninitialized() };
    with_display(|display| unsafe {
        XGetKeyboardControl(display, &mut state);
    });
    (state.led_mask & 2 != 0)
}


pub fn caps_lock_is_toggled() -> bool {
    let mut state: XKeyboardState = unsafe { uninitialized() };
    with_display(|display| unsafe {
        XGetKeyboardControl(display, &mut state);
    });
    (state.led_mask & 1 != 0)
}