Skip to main content

hotkey_listener/
key.rs

1//! Platform-agnostic key representation.
2
3use anyhow::{anyhow, Result};
4
5/// Platform-agnostic key representation.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum Key {
8    F1,
9    F2,
10    F3,
11    F4,
12    F5,
13    F6,
14    F7,
15    F8,
16    F9,
17    F10,
18    F11,
19    F12,
20    ScrollLock,
21    Pause,
22    Insert,
23}
24
25impl Key {
26    /// Parse a key from a string like "F8" or "ScrollLock".
27    pub fn parse(s: &str) -> Result<Self> {
28        match s.to_uppercase().as_str() {
29            "F1" => Ok(Key::F1),
30            "F2" => Ok(Key::F2),
31            "F3" => Ok(Key::F3),
32            "F4" => Ok(Key::F4),
33            "F5" => Ok(Key::F5),
34            "F6" => Ok(Key::F6),
35            "F7" => Ok(Key::F7),
36            "F8" => Ok(Key::F8),
37            "F9" => Ok(Key::F9),
38            "F10" => Ok(Key::F10),
39            "F11" => Ok(Key::F11),
40            "F12" => Ok(Key::F12),
41            "SCROLLLOCK" | "SCROLL_LOCK" => Ok(Key::ScrollLock),
42            "PAUSE" => Ok(Key::Pause),
43            "INSERT" => Ok(Key::Insert),
44            _ => Err(anyhow!("Unknown key: {}", s)),
45        }
46    }
47}
48
49impl std::fmt::Display for Key {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        match self {
52            Key::F1 => write!(f, "F1"),
53            Key::F2 => write!(f, "F2"),
54            Key::F3 => write!(f, "F3"),
55            Key::F4 => write!(f, "F4"),
56            Key::F5 => write!(f, "F5"),
57            Key::F6 => write!(f, "F6"),
58            Key::F7 => write!(f, "F7"),
59            Key::F8 => write!(f, "F8"),
60            Key::F9 => write!(f, "F9"),
61            Key::F10 => write!(f, "F10"),
62            Key::F11 => write!(f, "F11"),
63            Key::F12 => write!(f, "F12"),
64            Key::ScrollLock => write!(f, "ScrollLock"),
65            Key::Pause => write!(f, "Pause"),
66            Key::Insert => write!(f, "Insert"),
67        }
68    }
69}