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
#[cfg(windows)]
mod windows;
#[cfg(windows)]
static SIM: windows::WindowsSimulate = windows::WindowsSimulate;

mod buf;
pub use buf::EventBuffer;

/// An action for a key.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[repr(u8)]
pub enum Action {
    /// Presses the key.
    Press,
    /// Releases the key.
    Release,
}

/// The direction of a `Scroll` event.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[repr(u8)]
pub enum ScrollDirection {
    Horizontal,
    Vertical,
}

/// A key that can be pressed.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Key {
    // Mouse buttons
    MouseLeft,
    MouseRight,
    MouseMiddle,
    MouseX(u8),

    // Keyboard keys
    /// Also named BACK
    Backspace,
    Tab,
    Clear,
    /// Also named RETURN
    Enter,
    Shift,
    LeftShift,
    RightShift,
    Control,
    LeftControl,
    RightControl,
    Menu,
    LeftMenu,
    RightMenu,
    Home,
    LeftWindows,
    RightWindows,
    Pause,
    /// Also named CAPITAL
    CapsLock,
    Escape,
    Space,
    /// Also named PRIOR
    PageUp,
    /// Also named NEXT
    PageDown,
    End,
    Select,
    Print,
    Execute,
    /// Also named SNAPSHOT
    PrintScreen,
    Insert,
    Delete,
    Help,
    Apps,
    Sleep,
    BrowserBack,
    BrowserForward,
    BrowserRefresh,
    BrowserStop,
    BrowserSearch,
    BrowserFavorites,
    BrowserHome,
    VolumeMute,
    VolumeDown,
    VolumeUp,
    MediaNextTrack,
    MediaPreviousTrack,
    MediaStop,
    MediaPlayPause,
    LaunchMail,
    SelectMedia,
    LaunchApp1,
    LaunchApp2,

    Attn,
    Crsel,
    Exsel,
    Ereof,
    Play,
    Zoom,
    NoName,

    Left,
    Up,
    Right,
    Down,

    Kana,
    Hangul,
    Junja,
    Final,
    Kanji,
    Convert,
    Nonconvert,
    Accept,
    ModeChange,
    /// The IME PROCESS key
    ProcessKey,
    ImeOn,
    ImeOff,

    /// On US keyboards, the ';:' key.
    Oem1,
    /// On US keyboards, the '+' key.
    OemPlus,
    /// On US keyboards, the ',' key.
    OemComma,
    /// On US keyboards, the '-' key.
    OemMinus,
    /// On US keyboards, the '.' key.
    OemPeriod,
    /// On US keyboards, the '/' key.
    Oem2,
    /// On US keyboards, the '~' key.
    Oem3,
    /// On US keyboards, the '[{' key.
    Oem4,
    /// On US keyboards, the '\|' key.
    Oem5,
    /// On US keyboards, the ']}'
    Oem6,
    /// On US keyboards, the ''"' key.
    Oem7,
    /// Miscellaneous characters; can vary by keyboard.
    Oem8,
    /// Either the angle backet key or the backslash on the RT 102-key keyboard.
    Oem102,
    OemClear,

    _0,
    _1,
    _2,
    _3,
    _4,
    _5,
    _6,
    _7,
    _8,
    _9,

    Numpad0,
    Numpad1,
    Numpad2,
    Numpad3,
    Numpad4,
    Numpad5,
    Numpad6,
    Numpad7,
    Numpad8,
    Numpad9,
    Multiply,
    Add,
    Subtract,
    Decimal,
    Divide,
    Separator,
    NumLock,
    ScrollLock,

    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H,
    I,
    J,
    K,
    L,
    M,
    N,
    O,
    P,
    Q,
    R,
    S,
    T,
    U,
    V,
    W,
    X,
    Y,
    Z,

    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
    F13,
    F14,
    F15,
    F16,
    F17,
    F18,
    F19,
    F20,
    F21,
    F22,
    F23,
    F24,
}

impl Key {
    /// Checks if this `Key` is a mouse button.
    #[inline(always)]
    pub fn is_mouse_button(&self) -> bool {
        matches!(self, Key::MouseLeft | Key::MouseMiddle | Key::MouseRight | Key::MouseX(_))
    }
}

/// A trait for structures which can be turned into an event, given an action.
pub trait Keylike: Copy {
    /// Turns the keylike into an event.
    fn into_event(self, action: Action) -> Event;

    /// Creates an event that causes the keylike to be pressed.
    #[inline(always)]
    fn press(self) -> Event {
        self.into_event(Action::Press)
    }

    /// Creates an event that causes the keylike to be released.
    #[inline(always)]
    fn release(self) -> Event {
        self.into_event(Action::Release)
    }

    /// Creates an iterator that yield a `Press` event and a `Release` for this keylike.
    #[inline]
    fn press_release(self) -> std::iter::Chain<std::iter::Once<Event>, std::iter::Once<Event>> {
        std::iter::once(self.press()).chain(std::iter::once(self.release()))
    }
}

impl Keylike for Key {
    #[inline(always)]
    fn into_event(self, action: Action) -> Event {
        Event::Key { key: self, action }
    }
}

impl Keylike for char {
    #[inline(always)]
    fn into_event(self, action: Action) -> Event {
        Event::Char {
            character: self,
            action,
        }
    }
}

/// An event that can be sent to a `Simulate`.
#[derive(Clone, Debug)]
pub enum Event {
    Key {
        key: Key,
        action: Action,
    },

    Char {
        character: char,
        action: Action,
    },

    MoveMouseAbsolute {
        x: f32,
        y: f32,
        /// Maps the given coordinates to the whole virtual desktop (if multiple monitors
        /// are used). When this flag is off, the coordinates (1, 1) map to the lower-right
        /// corner of the main monitor.
        map_to_virtual_desktop: bool,
    },

    MoveMouseRelative {
        dx: i32,
        dy: i32,
    },

    Scroll {
        /// One mouse clock is a `delta` of `1`.
        /// A positive value means the wheel must be rotated forward (or to the right if
        /// the direction is horizontal).
        delta: f32,
        direction: ScrollDirection,
    },
}

#[derive(Clone, Debug)]
pub enum Error {
    /// A key was not supported by the platform.
    UnsupportedKey(Key),

    /// A character was not supported by the platform.
    UnsupportedChar(char),

    /// An event was not supported by the platform,
    UnsupportedEvent(Event),

    /// An error occured whilst simulating events.
    OsError {
        /// The code of the error.
        code: u32,
        /// A message describing the error.
        message: String,
    },
}

/// The result type of the crate.
pub type Result<T> = std::result::Result<T, Error>;

/// A trait to handle the input simulation.
pub trait Simulate {
    /// Simulates the specified events.
    fn send_events(&self, events: impl IntoIterator<Item = Event>) -> Result<()>;
}

/// Sends the given events to the default simulator.
#[inline(always)]
pub fn send_events(events: impl IntoIterator<Item = Event>) -> Result<()> {
    SIM.send_events(events)
}

/// Sends a single event.
#[inline(always)]
pub fn send_event(event: Event) -> Result<()> {
    send_events(Some(event))
}

/// Sends `Press` and `Release` events for the given keylikes.
#[inline]
pub fn send_multiple<K: Keylike>(keys: impl IntoIterator<Item = K>) -> Result<()> {
    let iter = keys.into_iter().flat_map(Keylike::press_release);
    send_events(iter)
}

/// Sends an event for the given keylike.
#[inline(always)]
pub fn send(key: impl Keylike) -> Result<()> {
    send_events(key.press_release())
}

/// Sends a `Press` event for the given keylike.
#[inline(always)]
pub fn press(key: impl Keylike) -> Result<()> {
    send_events(Some(key.press()))
}

/// Sends a `Release` event for the given keylike.
#[inline(always)]
pub fn release(key: Key) -> Result<()> {
    send_events(Some(key.release()))
}

/// Types the given string.
#[inline(always)]
pub fn type_str(s: &str) -> Result<()> {
    send_multiple(s.chars())
}

/// Moves the mouse `dx` pixels to the right
/// and `dy` pixels down.
#[inline(always)]
pub fn move_mouse_relative(dx: i32, dy: i32) -> Result<()> {
    send_events(Some(Event::MoveMouseRelative { dx, dy }))
}

/// Moves the mouse, coordinates are normalized to the desktop: (0, 0) map to the top-left
/// of the main monitor and (1, 1) maps to the bottom-right of the main monitor.
#[inline(always)]
pub fn move_mouse_absolute(x: f32, y: f32) -> Result<()> {
    send_events(Some(Event::MoveMouseAbsolute {
        x,
        y,
        map_to_virtual_desktop: false,
    }))
}

/// Sends a scroll event to rotate the mouse wheel in the given direction.
#[inline(always)]
pub fn send_scroll_event(delta: f32, direction: ScrollDirection) -> Result<()> {
    send_events(Some(Event::Scroll { delta, direction }))
}

/// Uses the mouse wheel vertically.
#[inline(always)]
pub fn scroll(delta: f32) -> Result<()> {
    send_scroll_event(delta, ScrollDirection::Vertical)
}

/// Uses the mouse wheel horizontally.
#[inline(always)]
pub fn scroll_horizontal(delta: f32) -> Result<()> {
    send_scroll_event(delta, ScrollDirection::Horizontal)
}