-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
util.rs
174 lines (158 loc) · 5.6 KB
/
util.rs
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
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, Clear, ClearType},
cursor,
};
use tui::{backend::CrosstermBackend, Terminal};
use std::io::{self, Write};
use std::sync::{Arc, Mutex};
use std::{sync::mpsc, thread, time::Duration};
#[derive(Debug, Clone, Copy)]
pub enum Key {
Backspace,
Left,
Right,
Up,
Down,
Home,
End,
PageUp,
PageDown,
BackTab,
Delete,
Insert,
F(u8),
Char(char),
Alt(char),
Ctrl(char),
Null,
Esc,
}
#[derive(Debug, Clone, Copy)]
pub struct EventConfig {
pub tick_rate: Duration,
}
#[derive(Debug, Clone, Copy)]
pub enum Event<I> {
Input(I),
Tick,
}
pub fn setup_terminal() -> Terminal<CrosstermBackend<io::Stdout>> {
enable_raw_mode().unwrap();
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen).unwrap();
execute!(stdout, Clear(ClearType::All)).unwrap();
let backend = CrosstermBackend::new(stdout);
Terminal::new(backend).unwrap()
}
pub fn destruct_terminal() {
disable_raw_mode().unwrap();
execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture).unwrap();
execute!(io::stdout(), cursor::Show).unwrap();
}
pub struct Events {
pub rx: mpsc::Receiver<Event<Key>>,
pub tx: mpsc::Sender<Event<Key>>,
pub pause_stdin: Arc<Mutex<bool>>,
pub pause_ticker: Arc<Mutex<bool>>,
}
impl Events {
#[cfg(feature = "crossterm")]
pub fn with_config(config: EventConfig) -> Events {
use crossterm::event::{KeyCode::*, KeyModifiers};
let (tx, rx) = mpsc::channel();
let pause_stdin = Arc::new(Mutex::new(false));
let pause_ticker = Arc::new(Mutex::new(false));
let _input_handle = {
let tx = tx.clone();
let pause_stdin = pause_stdin.clone();
thread::spawn(move || {
loop {
if *pause_stdin.lock().unwrap() {
thread::sleep(Duration::from_millis(250));
continue;
}
// poll for tick rate duration, if no event, sent tick event.
if let event::Event::Key(key) = event::read().unwrap() {
let key = match key.code {
Backspace => Key::Backspace,
Enter => Key::Char('\n'),
Left => Key::Left,
Right => Key::Right,
Up => Key::Up,
Down => Key::Down,
Home => Key::Home,
End => Key::End,
PageUp => Key::PageUp,
PageDown => Key::PageDown,
Tab => Key::Char('\t'),
BackTab => Key::BackTab,
Delete => Key::Delete,
Insert => Key::Insert,
F(k) => Key::F(k),
Null => Key::Null,
Esc => Key::Esc,
Char(c) => match key.modifiers {
KeyModifiers::NONE | KeyModifiers::SHIFT => Key::Char(c),
KeyModifiers::CONTROL => Key::Ctrl(c),
KeyModifiers::ALT => Key::Alt(c),
_ => Key::Null,
},
};
tx.send(Event::Input(key)).unwrap();
}
}
})
};
let _tick_handle = {
let tx = tx.clone();
let pause_ticker = pause_ticker.clone();
thread::spawn(move || loop {
// print!("\r\n");
// dbg!(*pause_ticker.lock().unwrap());
while *pause_ticker.lock().unwrap() {
thread::sleep(Duration::from_millis(250));
}
if tx.send(Event::Tick).is_err() {
break;
}
thread::sleep(config.tick_rate);
})
};
Events { rx, tx, pause_stdin, pause_ticker }
}
/// Attempts to read an event.
/// This function will block the current thread.
pub fn next(&self) -> Result<Event<Key>, mpsc::RecvError> {
self.rx.recv()
}
pub fn pause_ticker(&self) {
*self.pause_ticker.lock().unwrap() = true;
// print!("\r\n");
// dbg!(*self.pause_ticker.lock().unwrap());
}
pub fn resume_ticker(&self) {
*self.pause_ticker.lock().unwrap() = false;
}
pub fn pause_event_loop(&self) {
*self.pause_stdin.lock().unwrap() = true;
}
pub fn resume_event_loop(&self) {
*self.pause_stdin.lock().unwrap() = false;
}
pub fn pause_key_capture(&self, terminal: &mut Terminal<CrosstermBackend<io::Stdout>>) {
self.pause_event_loop();
std::thread::sleep(std::time::Duration::from_millis(50));
disable_raw_mode().unwrap();
execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture).unwrap();
terminal.show_cursor().unwrap();
}
pub fn resume_key_capture(&self, terminal: &mut Terminal<CrosstermBackend<io::Stdout>>) {
enable_raw_mode().unwrap();
execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture).unwrap();
std::thread::sleep(std::time::Duration::from_millis(50));
self.resume_event_loop();
terminal.resize(terminal.size().unwrap()).unwrap();
}
}