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
pub extern crate interception_sys;

#[macro_use]
extern crate bitflags;

pub use interception_sys as raw;
pub mod scancode;

pub use scancode::ScanCode;

use std::convert::{TryFrom, TryInto};
use std::default::Default;
use std::time::Duration;
use std::vec::Vec;

pub type Device = i32;
pub type Precedence = i32;

pub enum Filter {
    MouseFilter(MouseFilter),
    KeyFilter(KeyFilter),
}

pub type Predicate = extern "C" fn(device: Device) -> bool;

bitflags! {
    pub struct MouseState: u16 {
        const LEFT_BUTTON_DOWN = 1;
        const LEFT_BUTTON_UP = 2;

        const RIGHT_BUTTON_DOWN = 4;
        const RIGHT_BUTTON_UP = 8;

        const MIDDLE_BUTTON_DOWN = 16;
        const MIDDLE_BUTTON_UP = 32;

        const BUTTON_4_DOWN = 64;
        const BUTTON_4_UP = 128;

        const BUTTON_5_DOWN = 256;
        const BUTTON_5_UP = 512;

        const WHEEL = 1024;
        const HWHEEL = 2048;

        // MouseFilter only
        const MOVE = 4096;
    }
}

pub type MouseFilter = MouseState;

bitflags! {
    pub struct MouseFlags: u16 {
        const MOVE_RELATIVE = 0;
        const MOVE_ABSOLUTE = 1;

        const VIRTUAL_DESKTOP = 2;
        const ATTRIBUTES_CHANGED = 4;

        const MOVE_NO_COALESCE = 8;

        const TERMSRV_SRC_SHADOW = 256;
    }
}

bitflags! {
    pub struct KeyState: u16 {
        const DOWN = 0;
        const UP = 1;

        const E0 = 2;
        const E1 = 3;

        const TERMSRV_SET_LED = 8;
        const TERMSRV_SHADOW = 16;
        const TERMSRV_VKPACKET = 32;
    }
}

bitflags! {
    pub struct KeyFilter: u16 {
        const DOWN = 1;
        const UP = 2;

        const E0 = 4;
        const E1 = 8;

        const TERMSRV_SET_LED = 16;
        const TERMSRV_SHADOW = 32;
        const TERMSRV_VKPACKET = 64;
    }
}

#[derive(Debug, Copy, Clone)]
pub enum Stroke {
    Mouse {
        state: MouseState,
        flags: MouseFlags,
        rolling: i16,
        x: i32,
        y: i32,
        information: u32,
    },

    Keyboard {
        code: ScanCode,
        state: KeyState,
        information: u32,
    },
}

impl TryFrom<raw::InterceptionMouseStroke> for Stroke {
    type Error = &'static str;

    fn try_from(raw_stroke: raw::InterceptionMouseStroke) -> Result<Self, Self::Error> {
        let state = match MouseState::from_bits(raw_stroke.state) {
            Some(state) => state,
            None => return Err("Extra bits in raw mouse state"),
        };

        let flags = match MouseFlags::from_bits(raw_stroke.flags) {
            Some(flags) => flags,
            None => return Err("Extra bits in raw mouse flags"),
        };

        Ok(Stroke::Mouse {
            state: state,
            flags: flags,
            rolling: raw_stroke.rolling,
            x: raw_stroke.x,
            y: raw_stroke.y,
            information: raw_stroke.information,
        })
    }
}

impl TryFrom<raw::InterceptionKeyStroke> for Stroke {
    type Error = &'static str;

    fn try_from(raw_stroke: raw::InterceptionKeyStroke) -> Result<Self, Self::Error> {
        let state = match KeyState::from_bits(raw_stroke.state) {
            Some(state) => state,
            None => return Err("Extra bits in raw keyboard state"),
        };

        let code = match ScanCode::try_from(raw_stroke.code) {
            Ok(code) => code,
            Err(_) => ScanCode::Esc,
        };

        Ok(Stroke::Keyboard {
            code: code,
            state: state,
            information: raw_stroke.information,
        })
    }
}

impl TryFrom<Stroke> for raw::InterceptionMouseStroke {
    type Error = &'static str;

    fn try_from(stroke: Stroke) -> Result<Self, Self::Error> {
        if let Stroke::Mouse {
            state,
            flags,
            rolling,
            x,
            y,
            information,
        } = stroke
        {
            Ok(raw::InterceptionMouseStroke {
                state: state.bits(),
                flags: flags.bits(),
                rolling: rolling,
                x: x,
                y: y,
                information: information,
            })
        } else {
            Err("Stroke must be a mouse stroke")
        }
    }
}

impl TryFrom<Stroke> for raw::InterceptionKeyStroke {
    type Error = &'static str;

    fn try_from(stroke: Stroke) -> Result<Self, Self::Error> {
        if let Stroke::Keyboard {
            code,
            state,
            information,
        } = stroke
        {
            Ok(raw::InterceptionKeyStroke {
                code: code as u16,
                state: state.bits(),
                information: information,
            })
        } else {
            Err("Stroke must be a keyboard stroke")
        }
    }
}

pub struct Interception {
    ctx: raw::InterceptionContext,
}

impl Interception {
    pub fn new() -> Option<Self> {
        let ctx = unsafe { raw::interception_create_context() };

        if ctx == std::ptr::null_mut() {
            return None;
        }

        Some(Interception { ctx: ctx })
    }

    pub fn get_precedence(&self, device: Device) -> Precedence {
        unsafe { raw::interception_get_precedence(self.ctx, device) }
    }

    pub fn set_precedence(&self, device: Device, precedence: Precedence) {
        unsafe { raw::interception_set_precedence(self.ctx, device, precedence) }
    }

    pub fn get_filter(&self, device: Device) -> Filter {
        if is_invalid(device) {
            return Filter::KeyFilter(KeyFilter::empty());
        }

        let raw_filter = unsafe { raw::interception_get_filter(self.ctx, device) };
        if is_mouse(device) {
            let filter = match MouseFilter::from_bits(raw_filter) {
                Some(filter) => filter,
                None => MouseFilter::empty(),
            };

            Filter::MouseFilter(filter)
        } else {
            let filter = match KeyFilter::from_bits(raw_filter) {
                Some(filter) => filter,
                None => KeyFilter::empty(),
            };

            Filter::KeyFilter(filter)
        }
    }

    pub fn set_filter(&self, predicate: Predicate, filter: Filter) {
        let filter = match filter {
            Filter::MouseFilter(filter) => filter.bits(),
            Filter::KeyFilter(filter) => filter.bits(),
        };

        unsafe {
            let predicate = std::mem::transmute(Some(predicate));
            raw::interception_set_filter(self.ctx, predicate, filter)
        }
    }

    pub fn wait(&self) -> Device {
        unsafe { raw::interception_wait(self.ctx) }
    }

    pub fn wait_with_timeout(&self, duration: Duration) -> Device {
        let millis = match u32::try_from(duration.as_millis()) {
            Ok(m) => m,
            Err(_) => u32::MAX,
        };

        unsafe { raw::interception_wait_with_timeout(self.ctx, millis) }
    }

    pub fn send(&self, device: Device, strokes: &[Stroke]) -> i32 {
        if is_mouse(device) {
            self.send_internal::<raw::InterceptionMouseStroke>(device, strokes)
        } else if is_keyboard(device) {
            self.send_internal::<raw::InterceptionKeyStroke>(device, strokes)
        } else {
            0
        }
    }

    fn send_internal<T: TryFrom<Stroke>>(&self, device: Device, strokes: &[Stroke]) -> i32 {
        let mut raw_strokes = Vec::new();

        for stroke in strokes {
            if let Ok(raw_stroke) = T::try_from(*stroke) {
                raw_strokes.push(raw_stroke)
            }
        }

        let ptr = raw_strokes.as_ptr();
        let len = match u32::try_from(raw_strokes.len()) {
            Ok(l) => l,
            Err(_) => u32::MAX,
        };

        unsafe { raw::interception_send(self.ctx, device, std::mem::transmute(ptr), len) }
    }

    pub fn receive(&self, device: Device, strokes: &mut [Stroke]) -> i32 {
        if is_mouse(device) {
            self.receive_internal::<raw::InterceptionMouseStroke>(device, strokes)
        } else if is_keyboard(device) {
            self.receive_internal::<raw::InterceptionKeyStroke>(device, strokes)
        } else {
            0
        }
    }

    fn receive_internal<T: TryInto<Stroke> + Default + Copy>(
        &self,
        device: Device,
        strokes: &mut [Stroke],
    ) -> i32 {
        let mut raw_strokes: Vec<T> = Vec::with_capacity(strokes.len());
        raw_strokes.resize_with(strokes.len(), Default::default);

        let ptr = raw_strokes.as_ptr();
        let len = match u32::try_from(raw_strokes.len()) {
            Ok(l) => l,
            Err(_) => u32::MAX,
        };

        let num_read =
            unsafe { raw::interception_receive(self.ctx, device, std::mem::transmute(ptr), len) };

        let mut num_valid: i32 = 0;
        for i in 0..num_read {
            if let Ok(stroke) = raw_strokes[i as usize].try_into() {
                strokes[num_valid as usize] = stroke;
                num_valid += 1;
            }
        }

        num_valid
    }

    pub fn get_hardware_id(&self, device: Device, buffer: &mut [u8]) -> u32 {
        let ptr = buffer.as_mut_ptr();
        let len = match u32::try_from(buffer.len()) {
            Ok(l) => l,
            Err(_) => u32::MAX,
        };

        unsafe {
            raw::interception_get_hardware_id(self.ctx, device, std::mem::transmute(ptr), len)
        }
    }
}

impl Drop for Interception {
    fn drop(&mut self) {
        unsafe { raw::interception_destroy_context(self.ctx) }
    }
}

pub extern "C" fn is_invalid(device: Device) -> bool {
    unsafe { raw::interception_is_invalid(device) != 0 }
}

pub extern "C" fn is_keyboard(device: Device) -> bool {
    unsafe { raw::interception_is_keyboard(device) != 0 }
}

pub extern "C" fn is_mouse(device: Device) -> bool {
    unsafe { raw::interception_is_mouse(device) != 0 }
}