rust_droid/action/
keyevent.rs

1use crate::{Droid, Result, models::KeyCode};
2use std::time::Duration;
3
4/// 用于构建和执行 "keyevent" (按键事件) 操作。
5pub struct KeyeventBuilder<'a> {
6    droid: &'a mut Droid,
7    key_code: KeyCode,
8    times: u32,
9}
10
11impl<'a> KeyeventBuilder<'a> {
12    pub fn new(droid: &'a mut Droid, key_code: KeyCode) -> Self {
13        Self {
14            droid,
15            key_code,
16            times: 1,
17        }
18    }
19
20    /// 设置按键次数。
21    pub fn times(mut self, count: u32) -> Self {
22        self.times = count;
23        self
24    }
25
26    /// 执行按键操作。
27    pub fn execute(self) -> Result<()> {
28        log::info!(
29            "Executing keyevent {:?} for {} times",
30            self.key_code,
31            self.times
32        );
33
34        for i in 0..self.times {
35            self.droid.controller.input_keyevent(self.key_code as i32)?;
36
37            if self.times > 1 && i < self.times - 1 {
38                // 多次按键之间稍作停顿
39                std::thread::sleep(Duration::from_millis(50));
40            }
41        }
42        Ok(())
43    }
44}