| 1 |
//! Demonstrates how to read events asynchronously with tokio. |
| 2 |
//! |
| 3 |
//! cargo run --features="event-stream" --example event-stream-tokio |
| 4 |
|
| 5 |
use std::{io::stdout, time::Duration}; |
| 6 |
|
| 7 |
use futures::{future::FutureExt, select, StreamExt}; |
| 8 |
use futures_timer::Delay; |
| 9 |
|
| 10 |
use crossterm::{ |
| 11 |
cursor::position, |
| 12 |
event::{DisableMouseCapture, EnableMouseCapture, Event, EventStream, KeyCode}, |
| 13 |
execute, |
| 14 |
terminal::{disable_raw_mode, enable_raw_mode}, |
| 15 |
}; |
| 16 |
|
| 17 |
const HELP: &str = r#"EventStream based on futures_util::Stream with tokio |
| 18 |
- Keyboard, mouse and terminal resize events enabled |
| 19 |
- Prints "." every second if there's no event |
| 20 |
- Hit "c" to print current cursor position |
| 21 |
- Use Esc to quit |
| 22 |
"#; |
| 23 |
|
| 24 |
async fn print_events() { |
| 25 |
let mut reader = EventStream::new(); |
| 26 |
|
| 27 |
loop { |
| 28 |
let mut delay = Delay::new(Duration::from_millis(1_000)).fuse(); |
| 29 |
let mut event = reader.next().fuse(); |
| 30 |
|
| 31 |
select! { |
| 32 |
_ = delay => { println!(".\r"); }, |
| 33 |
maybe_event = event => { |
| 34 |
match maybe_event { |
| 35 |
Some(Ok(event)) => { |
| 36 |
println!("Event::{:?}\r", event); |
| 37 |
|
| 38 |
if event == Event::Key(KeyCode::Char('c').into()) { |
| 39 |
println!("Cursor position: {:?}\r", position()); |
| 40 |
} |
| 41 |
|
| 42 |
if event == Event::Key(KeyCode::Esc.into()) { |
| 43 |
break; |
| 44 |
} |
| 45 |
} |
| 46 |
Some(Err(e)) => println!("Error: {:?}\r", e), |
| 47 |
None => break, |
| 48 |
} |
| 49 |
} |
| 50 |
}; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
#[tokio::main] |
| 55 |
async fn main() -> std::io::Result<()> { |
| 56 |
println!("{}", HELP); |
| 57 |
|
| 58 |
enable_raw_mode()?; |
| 59 |
|
| 60 |
let mut stdout = stdout(); |
| 61 |
execute!(stdout, EnableMouseCapture)?; |
| 62 |
|
| 63 |
print_events().await; |
| 64 |
|
| 65 |
execute!(stdout, DisableMouseCapture)?; |
| 66 |
|
| 67 |
disable_raw_mode() |
| 68 |
} |