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
use std::sync::{Arc, Mutex};
use std::time::Instant;
use device_query::{DeviceEvents, DeviceQuery, DeviceState, Keycode};
// region keyboard event recorder
/// single record of keyboard event
#[derive(Copy, Clone)]
pub struct KeyboardEv {
/// key code
pub code: Keycode,
/// press or release
pub press: bool,
/// timestamp from the start
pub timestamp: u64,
}
/// the result of `KeyboardRecorder.do_record`
pub struct KeyboardAction {
pub evs: Vec<KeyboardEv>,
pub till: u64,
}
pub struct KeyboardRecorder {
/// stop signal
recording: Arc<Mutex<bool>>,
/// Here, we've wrapped your vector in a Arc<Mutex<T>> so we can
/// write to it inside our closure.
ev_queue: Arc<Mutex<Vec<KeyboardEv>>>,
}
impl KeyboardRecorder {
pub fn new() -> KeyboardRecorder {
KeyboardRecorder {
recording: Arc::new(Mutex::new(false)),
ev_queue: Arc::new(Mutex::new(vec![])),
}
}
pub fn get_record(&self) -> Vec<KeyboardEv> {
(*self.ev_queue.lock().unwrap()).clone()
}
/// Doing record work in main thread.
/// Anyway, the listener(s) is working in separator thread(s).
/// But the guard(s) of listener(s) can only live in the scope of this function.
/// So this call need to be 'block' until you press the key representing 'stop_code'.
pub fn do_record(&mut self, stop_code: Keycode) -> KeyboardAction {
// start recording: clear records and set the signal
*self.ev_queue.lock().unwrap() = vec![];
*self.recording.lock().unwrap() = true;
// instance
let device_state = DeviceState::new();
// record start time as zero
let timeline = Instant::now();
// We make a clone of the Arc<Mutex<T>> here so we can move it
// into our closure without moving self into the closure.
let ev_queue_down = Arc::clone(&self.ev_queue);
let ev_queue_up = Arc::clone(&self.ev_queue);
let recording = Arc::clone(&self.recording);
// Note the `move` here on the closure.
let _guard_down = device_state.on_key_down(move |key| {
// if the stop key is pressed, stop record.
if key == &stop_code {
let mut recording = recording.lock().unwrap();
*recording = false;
return;
}
// We lock the mutex here and write to it.
let mut ev_queue_down = ev_queue_down.lock().unwrap();
ev_queue_down.push(KeyboardEv {
code: key.clone(),
press: true,
timestamp: timeline.elapsed().as_millis() as u64,
})
});
// Note the `move` here on the closure.
let _guard_up = device_state.on_key_up(move |key| {
// We lock the mutex here and write to it.
let mut ev_queue_up = ev_queue_up.lock().unwrap();
ev_queue_up.push(KeyboardEv {
code: key.clone(),
press: false,
timestamp: timeline.elapsed().as_millis() as u64,
})
});
// a block loop till the stop key is pressed.
loop {
if !*self.recording.lock().unwrap() {
// jump out of the loop, the guard(s) will `drop` then.
return KeyboardAction {
evs: (*self.ev_queue.lock().unwrap()).clone(),
till: timeline.elapsed().as_millis() as u64,
};
}
}
}
// Do record work in separator thread(s).
// The async version of `do_record`, but it is unsafe somehow, logically.
// I use a signal to make sure the main thread lives longer then the record thread.
// But that does not means the life of `do_record_async` is longer then record thread (in face, this call will return immediately)
// For example, maybe there is a `while signal {}` loop after this call, and the signal will be changed to `false` inside the record thread.
// Therefore i can say the main thread is always lives longer then the record thread.
// pub fn do_record_async(&mut self, stop_code: Keycode) {
//
// }
}
// endregion
// region mouse event recorder
/// single record of mouse event
#[derive(Copy, Clone, Debug)]
pub enum MouseEventName {
LeftDown,
LeftUp,
RightDown,
RightUp,
MidDown,
MidUp,
}
#[derive(Copy, Clone)]
pub struct MouseEv {
/// mouse event name
pub ev_name: MouseEventName,
/// position
pub position: (i32, i32),
/// timestamp from the start
pub timestamp: u64,
}
/// the result of `MouseRecorder.do_record`
pub struct MouseAction {
pub evs: Vec<MouseEv>,
pub till: u64,
}
pub struct MouseRecorder {
/// stop signal
recording: Arc<Mutex<bool>>,
/// Here, we've wrapped your vector in a Arc<Mutex<>> so we can
/// write to it inside our closure.
ev_queue: Arc<Mutex<Vec<MouseEv>>>,
}
impl MouseRecorder {
pub fn new() -> MouseRecorder {
MouseRecorder {
recording: Arc::new(Mutex::new(false)),
ev_queue: Arc::new(Mutex::new(vec![])),
}
}
pub fn get_record(&self) -> Vec<MouseEv> {
(*self.ev_queue.lock().unwrap()).clone()
}
/// Doing record work in main thread.
/// Anyway, the listener(s) is working in separator thread(s).
/// But the guard(s) of listener(s) can only live in the scope of this function.
/// So this call need to be 'block' until you press the key representing 'stop_code'.
pub fn do_record(&mut self, stop_code: Keycode) -> MouseAction {
// start recording: clear records and set the signal
*self.ev_queue.lock().unwrap() = vec![];
*self.recording.lock().unwrap() = true;
// instance
let device_state = DeviceState::new();
// record start time as zero
let timeline = Instant::now();
// region an extra listener to watch the stop signal
let recording = Arc::clone(&self.recording);
let _guard_stop = device_state.on_key_down(move |key| {
if key == &stop_code {
let mut recording = recording.lock().unwrap();
*recording = false;
}
});
// endregion
// region mouse down
let ev_queue_down = Arc::clone(&self.ev_queue);
let device_state_down = DeviceState::new();
let _guard_down = device_state.on_mouse_down(move |btn| {
match *btn {
1 => {
let mut ev_queue_down = ev_queue_down.lock().unwrap();
ev_queue_down.push(MouseEv {
ev_name: MouseEventName::LeftDown,
position: device_state_down.get_mouse().coords,
timestamp: timeline.elapsed().as_millis() as u64,
});
}
2 => {
let mut ev_queue_down = ev_queue_down.lock().unwrap();
ev_queue_down.push(MouseEv {
ev_name: MouseEventName::RightDown,
position: device_state_down.get_mouse().coords,
timestamp: timeline.elapsed().as_millis() as u64,
});
}
3 => {
let mut ev_queue_down = ev_queue_down.lock().unwrap();
ev_queue_down.push(MouseEv {
ev_name: MouseEventName::MidDown,
position: device_state_down.get_mouse().coords,
timestamp: timeline.elapsed().as_millis() as u64,
});
}
_ => () // ignore other button event
}
});
// endregion
// region mouse up
let ev_queue_up = Arc::clone(&self.ev_queue);
let device_state_up = DeviceState::new();
let _guard_up = device_state.on_mouse_up(move |btn| {
match *btn {
1 => {
let mut ev_queue_up = ev_queue_up.lock().unwrap();
ev_queue_up.push(MouseEv {
ev_name: MouseEventName::LeftUp,
position: device_state_up.get_mouse().coords,
timestamp: timeline.elapsed().as_millis() as u64,
});
}
2 => {
let mut ev_queue_up = ev_queue_up.lock().unwrap();
ev_queue_up.push(MouseEv {
ev_name: MouseEventName::RightUp,
position: device_state_up.get_mouse().coords,
timestamp: timeline.elapsed().as_millis() as u64,
});
}
3 => {
let mut ev_queue_up = ev_queue_up.lock().unwrap();
ev_queue_up.push(MouseEv {
ev_name: MouseEventName::MidUp,
position: device_state_up.get_mouse().coords,
timestamp: timeline.elapsed().as_millis() as u64,
});
}
_ => () // ignore other button event
}
});
// endregion
// a block loop till the stop key is pressed.
loop {
if !*self.recording.lock().unwrap() {
// jump out of the loop, the guard(s) will `drop` then.
return MouseAction {
evs: (*self.ev_queue.lock().unwrap()).clone(),
till: timeline.elapsed().as_millis() as u64,
};
}
}
}
}
// endregion
// region unit test
#[cfg(test)]
mod test {
use super::*;
/// 键盘行为录制测试 - 无断言, 需要自行判断输出是否正确
#[test]
fn keyboard_recorder_test() {
let mut recorder = KeyboardRecorder::new();
println!("record start. (press any key to record, press ESC to stop.)");
let action = recorder.do_record(Keycode::Escape);
println!("record stop. duration: {}ms", action.till);
for ev in action.evs {
println!("[{}ms]: {} {}", ev.timestamp, (if ev.press { "Press" } else { "Release" }), ev.code);
}
}
/// 鼠标行为录制测试 - 无断言, 需要自行判断输出是否正确
#[test]
fn mouse_recorder_test() {
let mut recorder = MouseRecorder::new();
println!("record start. (press ESC to stop.)");
let action = recorder.do_record(Keycode::Escape);
println!("record stop. last: {}ms", action.till);
for ev in action.evs {
println!("[{}ms]: {:?} at {:?}", ev.timestamp, ev.ev_name, ev.position);
}
}
}
// endregion