inputs/
inputs.rs

1use rustui::*;
2use std::{thread, time};
3
4const RENDERING_RATE: time::Duration = time::Duration::from_millis(16); // ms
5const INPUT_CAPTURING_RATE: time::Duration = time::Duration::from_millis(10); // ms
6
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let mut win = Window::new(false)?;
9    win.initialize(RENDERING_RATE)?; // Initialize the window and start the rendering thread
10    let input_rx = InputListener::new(INPUT_CAPTURING_RATE); // Create an input listener
11    let mut key_last_pressed = None;
12
13    loop {
14        // Check for key presses
15        if let Ok(event) = input_rx.try_recv() {
16            if let InputEvent::Key(Key::Char('q')) = event {
17                break;
18            }
19            key_last_pressed = Some(event);
20        }
21
22        // Draw the frame
23        win.draw(|canvas| {
24            canvas.set_named_border(
25                "INPUTS",
26                Align::Right,
27                Attr::default(),
28                Color::White,
29                Color::default(),
30            );
31            let display_text = match key_last_pressed {
32                Some(InputEvent::Key(key)) => format!("Key: {:?}", key),
33                Some(InputEvent::Mouse(mouse)) => match mouse {
34                    MouseEvent::Press { button, x, y } => {
35                        format!("Mouse Press: {:?} at ({},{})", button, x, y)
36                    }
37                    MouseEvent::Release { button, x, y } => {
38                        format!("Mouse Release: {:?} at ({},{})", button, x, y)
39                    }
40                    MouseEvent::Move { x, y } => {
41                        format!("Mouse Move: at ({},{})", x, y)
42                    }
43                },
44                Some(InputEvent::Unknown) => "Unknown input".to_string(),
45                None => "No input yet".to_string(),
46            };
47
48            let full_text = format!("{} (Press 'q' to quit)", display_text);
49
50            canvas.set_str(
51                canvas.width / 2,
52                canvas.height / 2,
53                &full_text,
54                Attr::default(),
55                Color::White,
56                Color::default(),
57                Align::Center,
58            );
59        })?;
60
61        thread::sleep(time::Duration::from_millis(100)); // Sleep to prevent high CPU usage
62    }
63    Ok(())
64}