-
Notifications
You must be signed in to change notification settings - Fork 285
/
event-poll-read.rs
61 lines (47 loc) · 1.51 KB
/
event-poll-read.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
//! Demonstrates how to match on modifiers like: Control, alt, shift.
//!
//! cargo run --example event-poll-read
use std::{io, time::Duration};
use crossterm::{
cursor::position,
event::{poll, read, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
execute,
terminal::{disable_raw_mode, enable_raw_mode},
};
const HELP: &str = r#"Blocking poll() & non-blocking read()
- Keyboard, mouse and terminal resize events enabled
- Prints "." every second if there's no event
- Hit "c" to print current cursor position
- Use Esc to quit
"#;
fn print_events() -> io::Result<()> {
loop {
// Wait up to 1s for another event
if poll(Duration::from_millis(1_000))? {
// It's guaranteed that read() won't block if `poll` returns `Ok(true)`
let event = read()?;
println!("Event::{:?}\r", event);
if event == Event::Key(KeyCode::Char('c').into()) {
println!("Cursor position: {:?}\r", position());
}
if event == Event::Key(KeyCode::Esc.into()) {
break;
}
} else {
// Timeout expired, no event for 1s
println!(".\r");
}
}
Ok(())
}
fn main() -> io::Result<()> {
println!("{}", HELP);
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnableMouseCapture)?;
if let Err(e) = print_events() {
println!("Error: {:?}\r", e);
}
execute!(stdout, DisableMouseCapture)?;
disable_raw_mode()
}