summaryrefslogtreecommitdiff
path: root/src/watch/terminal_event.rs
blob: 7f7ebe06f3e26e9663af44b063db9795b1253d1b (plain)
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
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use std::sync::mpsc::Sender;

use super::WatchEvent;

pub enum InputEvent {
    Next,
    Hint,
    List,
    Quit,
    Unrecognized(String),
}

pub fn terminal_event_handler(tx: Sender<WatchEvent>) {
    let mut input = String::with_capacity(8);

    let last_input_event = loop {
        let terminal_event = match event::read() {
            Ok(v) => v,
            Err(e) => {
                // If `send` returns an error, then the receiver is dropped and
                // a shutdown has been already initialized.
                let _ = tx.send(WatchEvent::TerminalEventErr(e));
                return;
            }
        };

        match terminal_event {
            Event::Key(key) => {
                if key.modifiers != KeyModifiers::NONE {
                    continue;
                }

                match key.kind {
                    KeyEventKind::Release => continue,
                    KeyEventKind::Press | KeyEventKind::Repeat => (),
                }

                match key.code {
                    KeyCode::Enter => {
                        let input_event = match input.trim() {
                            "n" | "next" => InputEvent::Next,
                            "h" | "hint" => InputEvent::Hint,
                            "l" | "list" => break InputEvent::List,
                            "q" | "quit" => break InputEvent::Quit,
                            _ => InputEvent::Unrecognized(input.clone()),
                        };

                        if tx.send(WatchEvent::Input(input_event)).is_err() {
                            return;
                        }

                        input.clear();
                    }
                    KeyCode::Char(c) => {
                        input.push(c);
                    }
                    _ => (),
                }
            }
            Event::Resize(_, _) => {
                if tx.send(WatchEvent::TerminalResize).is_err() {
                    return;
                }
            }
            Event::FocusGained | Event::FocusLost | Event::Mouse(_) | Event::Paste(_) => continue,
        }
    };

    let _ = tx.send(WatchEvent::Input(last_input_event));
}