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
use crate::child::{register_child_hook, Children};
use crate::config::{self, Keybind};
use crate::errors::{self, Error, LeftError};
use crate::ipc::Pipe;
use crate::xkeysym_lookup;
use crate::xwrap::{self, XWrap};
#[cfg(feature = "watcher")]
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use x11_dl::xlib;
use xdg::BaseDirectories;

pub struct Worker {
    pub keybinds: Vec<Keybind>,
    #[cfg(feature = "watcher")]
    pub config_file: PathBuf,
    pub base_directory: BaseDirectories,
    pub xwrap: XWrap,
    pub children: Children,
    pub reap_requested: Arc<AtomicBool>,
    pub reload_requested: bool,
    pub kill_requested: bool,
    chord_keybinds: Option<Vec<Keybind>>,
    chord_elapsed: bool,
}

impl Drop for Worker {
    fn drop(&mut self) {
        self.xwrap.shutdown();
    }
}

impl Worker {
    #[cfg(feature = "watcher")]
    pub fn new(
        keybinds: Vec<Keybind>,
        config_file: PathBuf,
        base_directory: BaseDirectories,
    ) -> Self {
        Self {
            keybinds,
            config_file,
            base_directory,
            xwrap: XWrap::new(),
            children: Default::default(),
            reap_requested: Default::default(),
            reload_requested: false,
            kill_requested: false,
            chord_keybinds: None,
            chord_elapsed: false,
        }
    }

    #[cfg(feature = "watcher")]
    pub async fn event_loop(&mut self) {
        use crate::config::watcher::Watcher;

        self.xwrap.grab_keys(&self.keybinds);
        let mut watcher = errors::exit_on_error!(Watcher::new(&self.config_file));
        let pipe_name = Pipe::pipe_name();
        let pipe_file = errors::exit_on_error!(self.base_directory.place_runtime_file(pipe_name));
        let mut pipe = errors::exit_on_error!(Pipe::new(pipe_file).await);
        loop {
            if self.kill_requested || self.reload_requested {
                break;
            }

            if self.chord_elapsed {
                self.xwrap.grab_keys(&self.keybinds);
                self.chord_keybinds = None;
                self.chord_elapsed = false;
            }

            let task_notify = xwrap::wait_readable(self.xwrap.task_notify.clone());
            tokio::pin!(task_notify);

            tokio::select! {
                _ = timeout(500) => {
                    if self.reap_requested.swap(false, Ordering::SeqCst) {
                        self.children.reap();
                    }
                }
                _ = &mut task_notify => {
                    let event_in_queue = self.xwrap.queue_len();
                    for _ in 0..event_in_queue {
                        let xlib_event = self.xwrap.get_next_event();
                        self.handle_event(&xlib_event);
                    }
                    continue;
                }
                _ = watcher.wait_readable(), if cfg!(watcher) => {
                    if watcher.has_events() {
                        errors::exit_on_error!(watcher.refresh_watch(&self.config_file));
                        self.reload_requested = true;
                    }
                    continue;
                }
                Some(command) = pipe.read_command() => {
                    match command {
                        config::Command::Reload => self.reload_requested = true,
                        config::Command::Kill => self.kill_requested = true,
                        _ => (),
                    }
                    continue;
                }
            }
        }
    }

    #[cfg(not(feature = "watcher"))]
    pub fn new(keybinds: Vec<Keybind>, base_directory: BaseDirectories) -> Self {
        Self {
            keybinds,
            base_directory,
            xwrap: XWrap::new(),
            children: Default::default(),
            reap_requested: Default::default(),
            reload_requested: false,
            kill_requested: false,
            chord_keybinds: None,
            chord_elapsed: false,
        }
    }

    #[cfg(not(feature = "watcher"))]
    pub async fn event_loop(&mut self) {
        self.xwrap.grab_keys(&self.keybinds);
        let pipe_name = Pipe::pipe_name();
        let pipe_file = errors::exit_on_error!(self.base_directory.place_runtime_file(pipe_name));
        let mut pipe = errors::exit_on_error!(Pipe::new(pipe_file).await);
        loop {
            if self.kill_requested || self.reload_requested {
                break;
            }

            if self.chord_elapsed {
                self.xwrap.grab_keys(&self.keybinds);
                self.chord_keybinds = None;
                self.chord_elapsed = false;
            }

            let task_notify = xwrap::wait_readable(self.xwrap.task_notify.clone());
            tokio::pin!(task_notify);

            tokio::select! {
                _ = timeout(500) => {
                    if self.reap_requested.swap(false, Ordering::SeqCst) {
                        self.children.reap();
                    }
                }
                _ = &mut task_notify => {
                    let event_in_queue = self.xwrap.queue_len();
                    for _ in 0..event_in_queue {
                        let xlib_event = self.xwrap.get_next_event();
                        self.handle_event(&xlib_event);
                    }
                    continue;
                }
                Some(command) = pipe.read_command() => {
                    match command {
                        config::Command::Reload => self.reload_requested = true,
                        config::Command::Kill => self.kill_requested = true,
                        _ => (),
                    }
                    continue;
                }
            }
        }
    }

    fn handle_event(&mut self, xlib_event: &xlib::XEvent) {
        let error = match xlib_event.get_type() {
            xlib::KeyPress => self.key_press(&xlib::XKeyEvent::from(xlib_event)),
            xlib::MappingNotify => self.mapping_notify(&mut xlib::XMappingEvent::from(xlib_event)),
            _ => return,
        };
        let _ = errors::log_on_error!(error);
    }

    fn key_press(&mut self, event: &xlib::XKeyEvent) -> Error {
        let key = self.xwrap.keycode_to_keysym(event.keycode);
        let mask = xkeysym_lookup::clean_mask(event.state);
        if let Some(keybind) = self.get_keybind((mask, key)) {
            match keybind.command {
                config::Command::Chord(children) => {
                    self.chord_keybinds = Some(children);
                    if let Some(keybinds) = &self.chord_keybinds {
                        self.xwrap.grab_keys(keybinds);
                    }
                }
                config::Command::Execute(value) => {
                    self.chord_elapsed = self.chord_keybinds.is_some();
                    return self.exec(&value);
                }
                config::Command::ExitChord => {
                    if self.chord_keybinds.is_some() {
                        self.chord_elapsed = true;
                    }
                }
                config::Command::Reload => self.reload_requested = true,
                config::Command::Kill => self.kill_requested = true,
            }
        } else {
            return Err(LeftError::CommandNotFound);
        }
        Ok(())
    }

    fn get_keybind(&self, mask_key_pair: (u32, u32)) -> Option<Keybind> {
        let keybinds = if let Some(keybinds) = &self.chord_keybinds {
            keybinds
        } else {
            &self.keybinds
        };
        keybinds
            .iter()
            .find(|keybind| {
                if let Some(key) = xkeysym_lookup::into_keysym(&keybind.key) {
                    let mask = xkeysym_lookup::into_modmask(&keybind.modifier);
                    return mask_key_pair == (mask, key);
                }
                false
            })
            .cloned()
    }

    fn mapping_notify(&self, event: &mut xlib::XMappingEvent) -> Error {
        if event.request == xlib::MappingModifier || event.request == xlib::MappingKeyboard {
            return self.xwrap.refresh_keyboard(event);
        }
        Ok(())
    }

    /// Sends command for execution
    /// Assumes STDIN/STDOUT unwanted.
    pub fn exec(&mut self, command: &str) -> Error {
        let child = Command::new("sh")
            .arg("-c")
            .arg(&command)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .spawn()?;
        self.children.insert(child);
        println!("Children {:?}", self.children);
        Ok(())
    }

    pub fn register_child_hook(&self) {
        register_child_hook(self.reap_requested.clone());
    }
}

async fn timeout(mills: u64) {
    use tokio::time::{sleep, Duration};
    sleep(Duration::from_millis(mills)).await;
}