| 1 |
//! Demonstrates how to match on modifiers like: Control, alt, shift. |
| 2 |
//! |
| 3 |
//! cargo run --example event-poll-read |
| 4 |
|
| 5 |
use std::{io, time::Duration}; |
| 6 |
|
| 7 |
use crossterm::{ |
| 8 |
cursor::position, |
| 9 |
event::{poll, read, DisableMouseCapture, EnableMouseCapture, Event, KeyCode}, |
| 10 |
execute, |
| 11 |
terminal::{disable_raw_mode, enable_raw_mode}, |
| 12 |
}; |
| 13 |
|
| 14 |
const HELP: &str = r#"Blocking poll() & non-blocking read() |
| 15 |
- Keyboard, mouse and terminal resize events enabled |
| 16 |
- Prints "." every second if there's no event |
| 17 |
- Hit "c" to print current cursor position |
| 18 |
- Use Esc to quit |
| 19 |
"#; |
| 20 |
|
| 21 |
fn print_events() -> io::Result<()> { |
| 22 |
loop { |
| 23 |
// Wait up to 1s for another event |
| 24 |
if poll(Duration::from_millis(1_000))? { |
| 25 |
// It's guaranteed that read() won't block if `poll` returns `Ok(true)` |
| 26 |
let event = read()?; |
| 27 |
|
| 28 |
println!("Event::{:?}\r", event); |
| 29 |
|
| 30 |
if event == Event::Key(KeyCode::Char('c').into()) { |
| 31 |
println!("Cursor position: {:?}\r", position()); |
| 32 |
} |
| 33 |
|
| 34 |
if event == Event::Key(KeyCode::Esc.into()) { |
| 35 |
break; |
| 36 |
} |
| 37 |
} else { |
| 38 |
// Timeout expired, no event for 1s |
| 39 |
println!(".\r"); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
Ok(()) |
| 44 |
} |
| 45 |
|
| 46 |
fn main() -> io::Result<()> { |
| 47 |
println!("{}", HELP); |
| 48 |
|
| 49 |
enable_raw_mode()?; |
| 50 |
|
| 51 |
let mut stdout = io::stdout(); |
| 52 |
execute!(stdout, EnableMouseCapture)?; |
| 53 |
|
| 54 |
if let Err(e) = print_events() { |
| 55 |
println!("Error: {:?}\r", e); |
| 56 |
} |
| 57 |
|
| 58 |
execute!(stdout, DisableMouseCapture)?; |
| 59 |
|
| 60 |
disable_raw_mode() |
| 61 |
} |