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
/*!
rawinput library for rust development on windows

# Usage Example

```no_run
extern crate rawinput;
use rawinput::*;
use rawinput::RawEvent::*;
fn main() {
    let mut manager = RawInputManager::new().unwrap();
    manager.register_devices(DeviceType::All);
    'outer: loop{
        if let Some(event) = manager.get_event(){
            match event{
                KeyboardEvent(id,  KeyId::Return, State::Pressed) => println!("Keyboard Number {:?} Pressed Return", id),
                KeyboardEvent(id,  KeyId::Escape, State::Pressed) => break 'outer,
                _ => (),
            }
        }
    }
}
```

*/



extern crate libc;
extern crate winapi;
extern crate kernel32;
extern crate user32;

mod mouse;
pub mod event;
mod keyboard;


use mouse::*;
use keyboard::*;
pub use event::*;
use winapi::*;
use user32::*;
use kernel32::*;
use std::ptr;
use std::mem;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::collections::{HashMap,VecDeque};
use std::thread;
use std::thread::JoinHandle;
use std::sync::mpsc::{
    Sender,
    Receiver,
    channel
};

const HWND_MESSAGE: HWND = -3isize as HWND;


#[test]
fn it_works() {
}

#[repr(C)] #[derive(Debug)]
struct RAWINPUTHID {
    pub header: RAWINPUTHEADER,
    pub data: RAWHID,
}

#[repr(C)] #[derive(Clone, Copy, Debug)]
struct RAWINPUTMOUSE {
    pub header: RAWINPUTHEADER,
    pub data: RAWMOUSEMOD,
}


#[repr(C)] #[derive(Clone, Copy, Debug)]
struct RAWINPUTKEYBOARD {
    pub header: RAWINPUTHEADER,
    pub data: RAWKEYBOARD,
}


enum RAWINPUTTYPE {
    MOUSE(*mut RAWINPUTMOUSE),
    KEYBOARD(*mut RAWINPUTKEYBOARD),
    HID(*mut RAWINPUTHID),
}

unsafe fn derive_rawinput_type(input: *mut RAWINPUT) -> RAWINPUTTYPE {
    use RAWINPUTTYPE::*;
    let input_type = (*input).header.dwType;
    match input_type{
        RIM_TYPEMOUSE => MOUSE(input as *mut RAWINPUTMOUSE),
        RIM_TYPEKEYBOARD => KEYBOARD(input as *mut RAWINPUTKEYBOARD),
        RIM_TYPEHID => HID(input as *mut RAWINPUTHID),
        _ => panic!("Should be Unreachable!"),
    }
}

/// Mouse Raw Input Name
#[derive(Clone)]
pub struct Mouse {
    name: String,
}

/// Keyboard Raw Input Name
#[derive(Clone)]
pub struct Keyboard {
    name: String,
}

/// Hid Raw Input Name
#[derive(Clone)]
pub struct Hid {
    name: String,
}

/// Stores Names to All Raw Input Devices
#[derive(Clone)]
pub struct Devices{
    pub mice: Vec<Mouse>,
    pub keyboards: Vec<Keyboard>,
    pub hids: Vec<Hid>,
    device_map: HashMap<HANDLE, usize>,
}

impl Devices{
    pub fn new () -> Devices {
        Devices{ mice: Vec::new(),
                 keyboards: Vec::new(),
                 hids: Vec::new(),
                 device_map: HashMap::new(),
        }
    }
}

enum Command {
    Register(DeviceType),
    GetEvent,
    Finish
}

/// Types of Raw Input Device
#[derive(PartialEq, Eq)]
pub enum DeviceType {
    Mice,
    Keyboards,
    Hids,
    All,
}

/// Manages Raw Input Processing
pub struct RawInputManager {
    joiner: Option<JoinHandle<()>>,
    sender: Sender<Command>,
    receiver: Receiver<Option<RawEvent>>,
}

impl RawInputManager {

    pub fn new() -> Result<RawInputManager, &'static str> {
        let (tx, rx) = channel();
        let (tx2, rx2) = channel();

        let joiner = thread::spawn(move || {
            let hwnd = setup_message_window();
            let mut event_queue = VecDeque::new();
            let mut devices = Devices::new();

            let mut exit = false;
            while !exit {
                match  rx.recv().unwrap(){
                    Command::Register(thing) => {devices = register_devices(hwnd, thing).unwrap();
                                                 tx2.send(None).unwrap();},
                    Command::GetEvent => {tx2.send(get_event(&mut event_queue, &devices)).unwrap();},
                    Command::Finish => {exit = true;},
                };
            };
        });
        Ok(RawInputManager{
            joiner: Some(joiner),
            sender: tx,
            receiver: rx2,
        })
    }

    /// Allows Raw Input devices of type device_type to be received from the Input Manager
    pub fn register_devices(&mut self, device_type: DeviceType) {
        self.sender.send(Command::Register(device_type)).unwrap();
        self.receiver.recv().unwrap();
    }

    /// Get Event from the Input Manager
    pub fn get_event(&mut self) -> Option<RawEvent> {
        self.sender.send(Command::GetEvent).unwrap();
        self.receiver.recv().unwrap()
    }

}

impl Drop for RawInputManager {
    fn drop(&mut self) {
        self.sender.send(Command::Finish).unwrap();
        self.joiner.take().unwrap().join().unwrap();
    }
}

fn register_devices(hwnd: HWND, reg_type: DeviceType) -> Result<Devices, &'static str> {
    let mut rid_vec: Vec<RAWINPUTDEVICE> = Vec::new();

    if (reg_type == DeviceType::Mice) || (reg_type == DeviceType::All) {
        let rid = RAWINPUTDEVICE{
	    usUsagePage: 1,
	    usUsage: 2,	// Mice
	    dwFlags: RIDEV_INPUTSINK,
	    hwndTarget: hwnd,
        };
        rid_vec.push(rid);
    }


    if (reg_type == DeviceType::Hids) || (reg_type == DeviceType::All) {
        let rid = RAWINPUTDEVICE{
	    usUsagePage: 1,
	    usUsage: 5,	// Gamepads
	    dwFlags: RIDEV_INPUTSINK,
	    hwndTarget: hwnd,
        };
        rid_vec.push(rid);
    }


    if (reg_type == DeviceType::Keyboards) || (reg_type == DeviceType::All) {
        let rid = RAWINPUTDEVICE{
	    usUsagePage: 1,
	    usUsage: 6,	// Keyboards
	    dwFlags: RIDEV_INPUTSINK,
	    hwndTarget: hwnd,
        };
        rid_vec.push(rid);
    }

    unsafe{
        if RegisterRawInputDevices(rid_vec.as_mut_ptr(), rid_vec.len() as UINT, mem::size_of::<RAWINPUTDEVICE>() as UINT) ==0 {
	    return Err("Registration of Controller Failed");
        }
    }
    Ok(produce_raw_device_list())
}


fn read_input_buffer(event_queue: &mut VecDeque<RawEvent>, devices: &Devices){
    unsafe{
        let mut array_alloc: [u8;1024] = mem::uninitialized();
        let mut buffer_size: UINT = 0;

        let mut numberofelements: i32 = GetRawInputBuffer(ptr::null_mut(),
                                                          &mut buffer_size,
                                                          mem::size_of::<RAWINPUTHEADER>() as UINT) as INT;
        if numberofelements as INT == -1{
            panic!("GetRawInputBuffer Gave Error on First Call!");
        }
        buffer_size = 1024;
        numberofelements = GetRawInputBuffer(array_alloc.as_mut_ptr() as PRAWINPUT,
                                             &mut buffer_size,
                                             mem::size_of::<RAWINPUTHEADER>() as UINT) as INT;

        if numberofelements as INT == -1{
            panic!("GetRawInputBuffer Gave Error on Second Call!");
        }

        let mut array_ptr = array_alloc.as_mut_ptr();

        for _ in 0..numberofelements as u32{
            let header = (*(array_ptr as *mut RAWINPUT)).header;
            let raw_input_ptr = derive_rawinput_type(array_ptr as *mut RAWINPUT);
            array_ptr = array_ptr.offset(header.dwSize as isize);
            let pos = match devices.device_map.get(&header.hDevice){
                Some(item) => *item,
                None => continue,
            };
            match raw_input_ptr{
                RAWINPUTTYPE::MOUSE(pointer) => {
                    let value = *pointer;
                    event_queue.extend(process_mouse_data(&value.data, pos));
                }
                RAWINPUTTYPE::KEYBOARD(pointer) => {
                    let value = *pointer;
                    event_queue.extend(process_keyboard_data(&value.data, pos));
                }
                _ => (),
            }
        }
    }
}

fn get_event(event_queue: &mut VecDeque<RawEvent>, devices: &Devices) -> Option<RawEvent>{
    if event_queue.is_empty(){
        read_input_buffer( event_queue, &devices);
    }
    let event = event_queue.pop_front();
    event
}

fn setup_message_window() -> HWND{
    let hwnd: HWND;
    unsafe{
        let hinstance = GetModuleHandleW(ptr::null());
        if hinstance == ptr::null_mut(){
            panic!("Instance Generation Failed");
        }
        let classname =  OsStr::new("RawInput Hidden Window").encode_wide().chain(Some(0).into_iter())
            .collect::<Vec<_>>();

        let wcex = WNDCLASSEXW{
            cbSize: (mem::size_of::<WNDCLASSEXW>()) as UINT,
            cbClsExtra: 0,
            cbWndExtra: 0,
            hbrBackground: ptr::null_mut(),
            hCursor:  ptr::null_mut(),
            hIcon:  ptr::null_mut(),
            hIconSm:  ptr::null_mut(),
            hInstance: hinstance,
            lpfnWndProc: Some(DefWindowProcW),
            lpszClassName: classname.as_ptr(),
            lpszMenuName: ptr::null_mut(),
            style: 0,
        };
        let a = RegisterClassExW(&wcex);
        if a == 0{
	    panic!("Registering WindowClass Failed!");
        }

        hwnd = CreateWindowExW(0,
                               classname.as_ptr(),
                               classname.as_ptr(),
                               0,
                               CW_USEDEFAULT,
                               CW_USEDEFAULT,
                               CW_USEDEFAULT,
                               CW_USEDEFAULT,
                               HWND_MESSAGE,
                               ptr::null_mut(),
                               hinstance,
                               ptr::null_mut());
        if hwnd.is_null(){
            panic!("Window Creation Failed!");
        }
    }
    hwnd
}

/// Produces a Device struct containing ID's to all available raw input Devices
pub fn produce_raw_device_list() -> Devices {
    let mut device_list = Devices::new();
    unsafe{
        let mut buffer: [u8; 10000] = mem::uninitialized();
        let mut num_devices: UINT = 0;
        let device_list_size =  mem::size_of::<RAWINPUTDEVICELIST>();
        let mut result = GetRawInputDeviceList(ptr::null_mut(),
                                               &mut num_devices,
                                               device_list_size as UINT);
        if result == -1i32 as UINT{
            panic!("Failed to Get Raw Device List!");
        }
        result = GetRawInputDeviceList(buffer.as_mut_ptr() as *mut RAWINPUTDEVICELIST,
                                       &mut num_devices,
                                       mem::size_of::<RAWINPUTDEVICELIST>() as UINT);
        if result == -1i32 as UINT{
            panic!("Failed to Get Raw Device List Again!");
        }

        for pos in 0..result as usize{
            let device_ptr = (&mut buffer[pos * device_list_size..
                                          (pos+1) * device_list_size]).as_mut_ptr() as *const RAWINPUTDEVICELIST;
            let device = *device_ptr;
            let device_handle = device.hDevice;
            let device_type = device.dwType;
            let mut name_buffer: [u16; 1024] = mem::uninitialized();
            let mut name_buffer_size: UINT = 1024;
            let result_2 = GetRawInputDeviceInfoW(device_handle,
                                                  RIDI_DEVICENAME,
                                                  name_buffer.as_mut_ptr() as LPVOID,
                                                  &mut name_buffer_size);
            if result_2 == -1i32 as UINT{
                panic!("GetRawInputDeviceInfo Failed: Required Size: {:?}", name_buffer_size);
            }
            let name_slice = &name_buffer[0..result_2 as usize];
            let full_name = match OsString::from_wide(name_slice).into_string(){
                Ok(something) => something,
                Err(_) => panic!("String Conversion Failed"),
            };

            let name = String::from(full_name);

            match device_type {
                RIM_TYPEMOUSE => {
                    if let Some(pos) = device_list.mice.iter().cloned().enumerate().find(|m| m.1.name == name) {
                        device_list.device_map.insert(device_handle, pos.0);
                    }
                    else{
                        device_list.device_map.insert(device_handle, device_list.mice.len());
                        device_list.mice.push(Mouse{name: name});
                    }
                },
                RIM_TYPEKEYBOARD => {
                    if let Some(pos) = device_list.keyboards.iter().cloned().enumerate().find(|m| m.1.name == name) {
                        device_list.device_map.insert(device_handle, pos.0);
                    }
                    else{
                        device_list.device_map.insert(device_handle, device_list.keyboards.len());
                        device_list.keyboards.push(Keyboard{name: name});
                    }
                },
                RIM_TYPEHID => {
                    if let Some(pos) = device_list.hids.iter().cloned().enumerate().find(|m| m.1.name == name) {
                        device_list.device_map.insert(device_handle, pos.0);
                    }
                    else{
                        device_list.device_map.insert(device_handle, device_list.hids.len());
                        device_list.hids.push(Hid{name: name});
                    }
                },
                _ => (),
            }
        }
    }
    device_list
}

/// Prints a list of all available raw input devices
pub fn print_raw_device_list () {
    let device_list = produce_raw_device_list();
    println!("Mice:");
    for mouse in device_list.mice{
        println!("{}", mouse.name);
    }
    println!("Keyboards:");
    for keyboard in device_list.keyboards{
        println!("{}", keyboard.name);
    }
    println!("Hids:");
    for hid in device_list.hids{
        println!("{}", hid.name);
    }
}