summaryrefslogtreecommitdiffstats
path: root/src/util/event.rs
blob: 5a767027cd8e6c1c458f9c563ec0b1b7acc15378 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std::io;
use std::sync::mpsc;
use std::thread;

use termion::event::Key;
use termion::input::TermRead;

#[derive(Debug)]
pub enum Event {
    Input(Key),
    IOWorkerProgress(u64),
    IOWorkerResult,
}

#[derive(Debug, Clone, Copy)]
pub struct Config {}

impl Default for Config {
    fn default() -> Config {
        Config {}
    }
}

/// A small event handler that wrap termion input and tick events. Each event
/// type is handled in its own thread and returned to a common `Receiver`
pub struct Events {
    prefix: &'static str,
    pub event_tx: mpsc::Sender<Event>,
    event_rx: mpsc::Receiver<Event>,
    pub sync_tx: mpsc::SyncSender<()>,
    // fileio_handle: thread::JoinHandle<()>,
}

impl Events {
    pub fn new() -> Self {
        Events::with_config("")
    }
    pub fn with_debug(s: &'static str) -> Self {
        let event = Events::with_config(s);
        event
    }

    pub fn with_config(prefix: &'static str) -> Self {
        let (sync_tx, sync_rx) = mpsc::sync_channel(1);
        let (event_tx, event_rx) = mpsc::channel();

        {
            let event_tx = event_tx.clone();
            thread::spawn(move || {
                let stdin = io::stdin();
                let mut keys = stdin.keys();
                while let Ok(_) = sync_rx.recv() {
                    if let Some(evt) = keys.next() {
                        match evt {
                            Ok(key) => {
                                if let Err(e) = event_tx.send(Event::Input(key)) {
                                    eprintln!("[{}] Input thread send err: {:#?}", prefix, e);
                                    return;
                                }
                            }
                            _ => {}
                        }
                    }
                }
            })
        };

        Events {
            event_tx,
            event_rx,
            sync_tx,
            prefix,
        }
    }

    pub fn next(&self) -> Result<Event, mpsc::RecvError> {
        self.sync_tx.try_send(());
        let event = self.event_rx.recv()?;
        Ok(event)
    }
    /*
        pub fn flush(&self) {
            self.sync_rx.try_recv();
        }
    */
}