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
mod error;

#[cfg(target_os = "macos")]
mod macos;

#[cfg(target_os = "windows")]
mod windows;

use crossbeam_channel::{Receiver, Sender};
use once_cell::sync::Lazy;
use std::{
    fmt,
    sync::atomic::{AtomicBool, Ordering},
};

pub use error::*;

static INITIALIZED: AtomicBool = AtomicBool::new(false);

static CHANNEL: Lazy<(Sender<Event>, Receiver<Event>)> =
    Lazy::new(|| crossbeam_channel::unbounded());

static CLOSE_CHANNEL: Lazy<(Sender<()>, Receiver<()>)> =
    Lazy::new(|| crossbeam_channel::bounded(0));

/// Initializes the keylogging thread and returns a [`Receiver<Event>`] to listen for keystrokes
/// and mouse events.
pub fn init() -> Receiver<Event> {
    let receiver = CHANNEL.1.clone();

    if INITIALIZED.load(Ordering::Relaxed) {
        return receiver;
    }

    #[cfg(target_os = "macos")]
    {
        macos::init();
    }

    #[cfg(target_os = "windows")]
    {
        windows::init();
    }

    INITIALIZED.store(true, Ordering::SeqCst);

    receiver
}

pub fn deinit() {
    if !INITIALIZED.load(Ordering::Relaxed) {
        return;
    }

    let sender = &CLOSE_CHANNEL.0;

    unsafe {
        sender.send(()).unwrap_unchecked();
    }

    INITIALIZED.store(false, Ordering::SeqCst);

    // Clean the global channel.
    while CHANNEL.1.try_recv().is_ok() {}
}

#[derive(Debug, Copy, Clone)]
pub enum Event {
    Mouse(Mouse),
    Keystroke(Keystroke),
}

impl From<Mouse> for Event {
    fn from(mouse: Mouse) -> Self {
        Self::Mouse(mouse)
    }
}

impl From<Keystroke> for Event {
    fn from(keystroke: Keystroke) -> Self {
        Self::Keystroke(keystroke)
    }
}

#[derive(Debug, Copy, Clone)]
pub enum Keystroke {
    Escape,
    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
    Return,
    Tab,
    Space,
    Delete,
    Backspace,
    VolumeUp,
    VolumeDown,
    Mute,
    ForwardDelete,
    #[cfg(any(target_os = "windows", target_os = "linux"))]
    Alt,
    #[cfg(target_os = "windows")]
    LeftWindows,
    #[cfg(target_os = "windows")]
    RightWindows,
    #[cfg(target_os = "macos")]
    Command,
    #[cfg(target_os = "macos")]
    RightCommand,
    #[cfg(target_os = "macos")]
    _Option,
    #[cfg(target_os = "macos")]
    RightOption,
    Control,
    RightControl,
    Shift,
    RightShift,
    CapsLock,
    Function,
    Home,
    PageUp,
    PageDown,
    End,
    LeftArrow,
    UpArrow,
    RightArrow,
    DownArrow,
    Help,
    Insert,
    Printscreen,
    ScrollLock,
    Pause,
    Menu,
    Char(char),
}

impl fmt::Display for Keystroke {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Keystroke::Char(c) => write!(f, "{}", c),
            _ => write!(f, "{:?}", self),
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum MouseButton {
    Left,
    Right,
    Other,
}

#[derive(Debug, Copy, Clone)]
pub struct Mouse {
    button: MouseButton,
    position: (i64, i64),
}

impl Mouse {
    pub fn new(button: MouseButton, position: (i64, i64)) -> Self {
        Self { button, position }
    }

    pub fn button(&self) -> MouseButton {
        self.button
    }

    pub fn position(&self) -> (i64, i64) {
        self.position
    }
}