2019-12-11 07:07:15 +11:00
|
|
|
//! Demonstrates how to block read events.
|
|
|
|
//!
|
|
|
|
//! cargo run --example event-read
|
|
|
|
|
2020-12-28 17:56:32 +11:00
|
|
|
use std::io::stdout;
|
2019-11-19 07:50:57 +11:00
|
|
|
|
2020-12-28 20:15:50 +11:00
|
|
|
use crossterm::event::poll;
|
2019-11-19 07:50:57 +11:00
|
|
|
use crossterm::{
|
|
|
|
cursor::position,
|
|
|
|
event::{read, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
|
|
|
|
execute,
|
2019-12-05 03:40:11 +11:00
|
|
|
terminal::{disable_raw_mode, enable_raw_mode},
|
2019-11-19 07:50:57 +11:00
|
|
|
Result,
|
|
|
|
};
|
2020-12-28 20:15:50 +11:00
|
|
|
use std::time::Duration;
|
2019-11-19 07:50:57 +11:00
|
|
|
|
|
|
|
const HELP: &str = r#"Blocking read()
|
|
|
|
- Keyboard, mouse and terminal resize events enabled
|
|
|
|
- Hit "c" to print current cursor position
|
|
|
|
- Use Esc to quit
|
|
|
|
"#;
|
|
|
|
|
|
|
|
fn print_events() -> Result<()> {
|
|
|
|
loop {
|
|
|
|
// Blocking read
|
|
|
|
let event = read()?;
|
|
|
|
|
2019-12-11 07:07:15 +11:00
|
|
|
println!("Event: {:?}\r", event);
|
2019-11-19 07:50:57 +11:00
|
|
|
|
|
|
|
if event == Event::Key(KeyCode::Char('c').into()) {
|
|
|
|
println!("Cursor position: {:?}\r", position());
|
|
|
|
}
|
|
|
|
|
2020-12-28 20:15:50 +11:00
|
|
|
if let Event::Resize(_, _) = event {
|
|
|
|
let (original_size, new_size) = flush_resize_events(event);
|
|
|
|
println!("Resize from: {:?}, to: {:?}", original_size, new_size);
|
|
|
|
}
|
|
|
|
|
2019-11-19 07:50:57 +11:00
|
|
|
if event == Event::Key(KeyCode::Esc.into()) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-12-28 20:15:50 +11:00
|
|
|
// 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(event: Event) -> ((u16, u16), (u16, u16)) {
|
|
|
|
if let Event::Resize(x, y) = event {
|
|
|
|
let mut last_resize = (x, y);
|
2021-01-03 01:24:34 +11:00
|
|
|
while let Ok(true) = poll(Duration::from_millis(50)) {
|
|
|
|
if let Ok(Event::Resize(x, y)) = read() {
|
|
|
|
last_resize = (x, y);
|
2020-12-28 20:15:50 +11:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ((x, y), last_resize);
|
|
|
|
}
|
|
|
|
((0, 0), (0, 0))
|
|
|
|
}
|
|
|
|
|
2019-11-19 07:50:57 +11:00
|
|
|
fn main() -> Result<()> {
|
|
|
|
println!("{}", HELP);
|
|
|
|
|
2019-12-05 03:40:11 +11:00
|
|
|
enable_raw_mode()?;
|
2019-11-19 07:50:57 +11:00
|
|
|
|
|
|
|
let mut stdout = stdout();
|
|
|
|
execute!(stdout, EnableMouseCapture)?;
|
|
|
|
|
|
|
|
if let Err(e) = print_events() {
|
|
|
|
println!("Error: {:?}\r", e);
|
|
|
|
}
|
|
|
|
|
|
|
|
execute!(stdout, DisableMouseCapture)?;
|
2019-12-05 03:40:11 +11:00
|
|
|
|
|
|
|
disable_raw_mode()
|
2019-11-19 07:50:57 +11:00
|
|
|
}
|