mki/
sequence.rs

1use crate::Keyboard;
2use std::str::FromStr;
3use std::thread;
4use std::time::Duration;
5
6#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)]
7/// A sequence of events to execute.
8pub struct Sequence {
9    sequence: Vec<Vec<Keyboard>>,
10}
11
12impl Sequence {
13    /// A Sequence of events to execute parsed from some text.
14    /// Can only be created if all the keys are supported. upon encountering a key that cannot be
15    /// represented will return None.
16    pub fn text(text: &str) -> Option<Self> {
17        let mut sequence = Vec::new();
18        for char in text.chars() {
19            let uppercase = char.to_ascii_uppercase();
20            use Keyboard::*;
21            let key = Keyboard::from_str(&uppercase.to_string()).ok()?;
22            if char.is_uppercase() || char == ':' || char == '\"' {
23                sequence.push(vec![LeftShift, key])
24            } else {
25                sequence.push(vec![key])
26            }
27        }
28        Some(Sequence { sequence })
29    }
30
31    /// send this Sequence on new thread.
32    pub fn send(&self) {
33        let cloned = self.clone();
34        thread::spawn(move || {
35            for keys in &cloned.sequence {
36                for key in keys {
37                    key.press();
38                }
39                thread::sleep(Duration::from_millis(15));
40                for key in keys {
41                    key.release();
42                }
43                thread::sleep(Duration::from_millis(15));
44            }
45        });
46    }
47}