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
use crate::builder::KeyflowBuilder;
use crate::error::*;
use crate::eventhandler::EventHandler;
use crate::hotkey::{Hotkey, HotkeyRegistry};
use crate::platform::{Backend, BackendListener, Listener, Simulation};
use crate::types::*;
use crossbeam_channel::{Sender, unbounded};
use std::sync::{Arc, OnceLock, RwLock};
static KEYFLOW: OnceLock<Keyflow> = OnceLock::new();
/// Main interface for Keyflow input simulation
///
/// All methods panic if Keyflow is not initialized. Initialize with
/// [`Keyflow::initialize()`] or [`Keyflow::builder()`].
pub struct Keyflow {
event_tx: Sender<InternalMessage>,
hotkey_listener: Option<Box<dyn Listener>>,
}
impl Keyflow {
/// Initialize with default settings
///
/// Equivalent to [`builder().initialize()`](KeyflowBuilder::initialize). Does not enable hotkeys.
///
/// # Errors
///
/// Returns error if already initialized or device creation fails.
///
/// # Example
///
/// ```no_run
/// use keyflow::prelude::*;
///
/// Keyflow::initialize()?;
/// Keyflow::press_key(Key::A);
///
/// # Ok(())
/// ```
pub fn initialize() -> Result<()> {
Self::builder().initialize()
}
/// Initialize with custom configuration.
pub(crate) fn initialize_with_config(config: KeyflowBuilder) -> Result<()> {
if KEYFLOW.get().is_some() {
return Err(KeyflowError::AlreadyInitialized);
}
// creates the target_os backend, screen size is required in linux to map absolute movement correctly
// in windows it get retrieved with `GetSystemMetrics`
#[cfg(target_os = "linux")]
let backend = {
if config.screen.is_none() {
return Err(KeyflowError::PlatformError(
"Screen size not set. It is required if run on linux".into(),
));
}
Box::new(Backend::new(config.screen.unwrap())?) as Box<dyn Simulation>
};
#[cfg(target_os = "windows")]
let backend = { Box::new(Backend::new()?) as Box<dyn Simulation> };
// start event handler
let (event_tx, event_rx) = unbounded();
let hotkey_registry = Arc::new(RwLock::new(HotkeyRegistry::new()));
let mut handler = EventHandler::new(backend, hotkey_registry.clone(), event_rx);
std::thread::Builder::new()
.name("keyflow-event-handler".to_string())
.spawn(move || {
if let Err(e) = handler.run() {
eprintln!("EventHandler error: {}", e);
}
})
.map_err(|e| KeyflowError::PlatformError(e.to_string()))?;
// start hotkey listener if enabled
let hotkey_listener = if config.enable_hotkeys {
let listener =
Box::new(BackendListener::new(hotkey_registry.clone())) as Box<dyn Listener>;
listener.start()?;
Some(listener)
} else {
None
};
KEYFLOW
.set(Self {
event_tx,
hotkey_listener,
})
.map_err(|_| KeyflowError::AlreadyInitialized)?;
Ok(())
}
/// Press a key down
///
/// The key remains pressed until [`release_key`](Self::release_key) is called.
pub fn press_key(key: Key) {
Self::send_event(InputEvent::KeyEvent {
key,
action: Action::Press,
})
.expect("Failed to send key press event");
}
/// Release a key.
pub fn release_key(key: Key) {
Self::send_event(InputEvent::KeyEvent {
key,
action: Action::Release,
})
.expect("Failed to send key release event");
}
/// Click a key (press + release).
pub fn click_key(key: Key) {
Self::send_event(InputEvent::KeyEvent {
key,
action: Action::Click,
})
.expect("Failed to send key click event");
}
/// Press a mouse button.
pub fn press_button(button: Button) {
Self::send_event(InputEvent::ButtonEvent {
button,
action: Action::Press,
})
.expect("Failed to send button press event");
}
/// Release a mouse button.
pub fn release_button(button: Button) {
Self::send_event(InputEvent::ButtonEvent {
button,
action: Action::Release,
})
.expect("Failed to send button release event");
}
/// Click a mouse button (press + release).
pub fn click_button(button: Button) {
Self::send_event(InputEvent::ButtonEvent {
button,
action: Action::Click,
})
.expect("Failed to send button click event");
}
/// Move mouse relative to current position
///
/// # Example
///
/// ```no_run
/// # use keyflow::prelude::*;
/// # Keyflow::initialize().unwrap();
/// // Move 100 pixels right, 50 pixels down
/// Keyflow::move_relative(100, 50);
/// ```
pub fn move_by(dx: i32, dy: i32) {
Self::send_event(InputEvent::MouseMove(Movement::Relative { dx, dy }))
.expect("Failed to send relative move event");
}
/// Move mouse to absolute screen position
///
/// # Example
///
/// ```no_run
/// # use keyflow::prelude::*;
/// # Keyflow::initialize().unwrap();
/// // Move to center of 1920x1080 screen
/// Keyflow::move_to(960, 540);
/// ```
pub fn move_to(x: i32, y: i32) {
Self::send_event(InputEvent::MouseMove(Movement::Absolute { x, y }))
.expect("Failed to send absolute move event");
}
/// Scroll vertically
///
/// Positive values scroll up, negative values scroll down.
pub fn scroll_vertical(delta: i32) {
Self::send_event(InputEvent::MouseScroll(Scroll::Vertical(delta)))
.expect("Failed to send scroll event");
}
/// Scroll horizontally
///
/// Positive values scroll right, negative values scroll left.
pub fn scroll_horizontal(delta: i32) {
Self::send_event(InputEvent::MouseScroll(Scroll::Horizontal(delta)))
.expect("Failed to send scroll event");
}
// TODO: maybe provide macro to create batch
/// Send a batch of events efficiently
///
/// Events are processed as a single unit.
///
/// See `examples/batch.rs` for usage patterns.
///
/// # Example
///
/// ```no_run
/// use keyflow::prelude::*;
/// use std::time::Duration;
///
/// # Keyflow::initialize().unwrap();
/// let events = vec![
/// InputEvent::KeyEvent { key: Key::A, action: Action::Press },
/// InputEvent::Delay(Duration::from_millis(100)),
/// InputEvent::KeyEvent { key: Key::A, action: Action::Release },
/// ];
///
/// Keyflow::batch(events);
/// ```
pub fn batch(events: Vec<InputEvent>) {
Self::send_batch_events(events).expect("Failed to send batch events");
}
/// Register a global hotkey
///
/// Requires initialization with [`builder().with_hotkeys()`](KeyflowBuilder::with_hotkeys).
///
/// # Errors
///
/// - Returns error if hotkeys not enabled during initialization
/// - Returns error if `id` already exists
///
/// # Example
///
/// See `examples/hotkeys.rs` for complete example.
///
/// ```no_run
/// use keyflow::prelude::*;
///
/// Keyflow::builder().with_hotkeys().initialize()?;
///
/// Keyflow::register_hotkey(
/// "save",
/// Hotkey::new(Key::S).with_ctrl(),
/// || println!("Ctrl+S pressed!")
/// )?;
///
/// # Ok(())
/// ```
pub fn register_hotkey<F>(id: impl Into<String>, hotkey: Hotkey, callback: F) -> Result<()>
where
F: Fn() + Send + Sync + 'static,
{
let state = Self::get_state()?;
if state.hotkey_listener.is_none() {
return Err(KeyflowError::HotkeysNotEnabled);
}
state
.event_tx
.send(InternalMessage::RegisterHotkey {
id: id.into(),
combo: hotkey,
callback: Box::new(callback),
})
.map_err(|_| KeyflowError::ChannelDisconnected)?;
Ok(())
}
/// Unregister a hotkey by ID
///
/// # Errors
///
/// Returns error if hotkey with given ID does not exist.
pub fn unregister_hotkey(id: impl Into<String>) -> Result<()> {
let state = Self::get_state()?;
if state.hotkey_listener.is_none() {
return Err(KeyflowError::HotkeysNotEnabled);
}
state
.event_tx
.send(InternalMessage::UnregisterHotkey { id: id.into() })
.map_err(|_| KeyflowError::ChannelDisconnected)?;
Ok(())
}
/// Send a single event to the event handler.
fn send_event(event: InputEvent) -> Result<()> {
let state = Self::get_state()?;
state
.event_tx
.send(InternalMessage::SimulateEvent(event))
.map_err(|_| KeyflowError::ChannelDisconnected)
}
/// Send an event batch to the event handler.
fn send_batch_events(events: Vec<InputEvent>) -> Result<()> {
let state = Self::get_state()?;
state
.event_tx
.send(InternalMessage::BatchEvents(events))
.map_err(|_| KeyflowError::ChannelDisconnected)
}
fn get_state() -> Result<&'static Keyflow> {
KEYFLOW.get().ok_or(KeyflowError::NotInitialized)
}
}
impl Drop for Keyflow {
fn drop(&mut self) {
if let Some(listener) = &self.hotkey_listener {
listener.stop()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "linux")]
#[test]
fn test_screen_required() {
let result = Keyflow::initialize();
assert!(result.is_err());
}
#[test]
fn test_hotkeys_enabled() {
Keyflow::builder()
.with_hotkeys()
.with_screen(Screen::default())
.initialize()
.unwrap();
Keyflow::register_hotkey("test", Hotkey::new(Key::P).with_alt(), || {}).unwrap()
}
#[test]
fn test_hotkeys_disabled() {
Keyflow::builder()
.with_screen(Screen::default())
.initialize()
.unwrap();
let result = Keyflow::register_hotkey("test", Hotkey::new(Key::P).with_alt(), || {});
assert!(result.is_err());
}
}