-
Notifications
You must be signed in to change notification settings - Fork 284
/
event-read.rs
112 lines (91 loc) · 2.83 KB
/
event-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
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
//! Demonstrates how to block read events.
//!
//! cargo run --example event-read
use std::io;
use crossterm::event::{
poll, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::{
cursor::position,
event::{
read, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
EnableFocusChange, EnableMouseCapture, Event, KeyCode,
},
execute, queue,
terminal::{disable_raw_mode, enable_raw_mode},
};
use std::time::Duration;
const HELP: &str = r#"Blocking read()
- Keyboard, mouse, focus and terminal resize events enabled
- Hit "c" to print current cursor position
- Use Esc to quit
"#;
fn print_events() -> io::Result<()> {
loop {
// Blocking read
let event = read()?;
println!("Event: {:?}\r", event);
if event == Event::Key(KeyCode::Char('c').into()) {
println!("Cursor position: {:?}\r", position());
}
if let Event::Resize(x, y) = event {
let (original_size, new_size) = flush_resize_events((x, y));
println!("Resize from: {:?}, to: {:?}\r", original_size, new_size);
}
if event == Event::Key(KeyCode::Esc.into()) {
break;
}
}
Ok(())
}
// Resize events can occur in batches.
// With a simple loop they can be flushed.
// This function will keep the first and last resize event.
fn flush_resize_events(first_resize: (u16, u16)) -> ((u16, u16), (u16, u16)) {
let mut last_resize = first_resize;
while let Ok(true) = poll(Duration::from_millis(50)) {
if let Ok(Event::Resize(x, y)) = read() {
last_resize = (x, y);
}
}
(first_resize, last_resize)
}
fn main() -> io::Result<()> {
println!("{}", HELP);
enable_raw_mode()?;
let mut stdout = io::stdout();
let supports_keyboard_enhancement = matches!(
crossterm::terminal::supports_keyboard_enhancement(),
Ok(true)
);
if supports_keyboard_enhancement {
queue!(
stdout,
PushKeyboardEnhancementFlags(
KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
| KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES
| KeyboardEnhancementFlags::REPORT_ALTERNATE_KEYS
| KeyboardEnhancementFlags::REPORT_EVENT_TYPES
)
)?;
}
execute!(
stdout,
EnableBracketedPaste,
EnableFocusChange,
EnableMouseCapture,
)?;
if let Err(e) = print_events() {
println!("Error: {:?}\r", e);
}
if supports_keyboard_enhancement {
queue!(stdout, PopKeyboardEnhancementFlags)?;
}
execute!(
stdout,
DisableBracketedPaste,
DisableFocusChange,
DisableMouseCapture
)?;
disable_raw_mode()
}