1 //! Demonstrates how to block read events.
2 //!
3 //! cargo run --example event-read
4 
5 use std::io::{stdout, Write};
6 
7 use crossterm::{
8     cursor::position,
9     event::{read, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
10     execute,
11     terminal::{disable_raw_mode, enable_raw_mode},
12     Result,
13 };
14 
15 const HELP: &str = r#"Blocking read()
16  - Keyboard, mouse and terminal resize events enabled
17  - Hit "c" to print current cursor position
18  - Use Esc to quit
19 "#;
20 
print_events() -> Result<()>21 fn print_events() -> Result<()> {
22     loop {
23         // Blocking read
24         let event = read()?;
25 
26         println!("Event: {:?}\r", event);
27 
28         if event == Event::Key(KeyCode::Char('c').into()) {
29             println!("Cursor position: {:?}\r", position());
30         }
31 
32         if event == Event::Key(KeyCode::Esc.into()) {
33             break;
34         }
35     }
36 
37     Ok(())
38 }
39 
main() -> Result<()>40 fn main() -> Result<()> {
41     println!("{}", HELP);
42 
43     enable_raw_mode()?;
44 
45     let mut stdout = stdout();
46     execute!(stdout, EnableMouseCapture)?;
47 
48     if let Err(e) = print_events() {
49         println!("Error: {:?}\r", e);
50     }
51 
52     execute!(stdout, DisableMouseCapture)?;
53 
54     disable_raw_mode()
55 }
56