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            match event {
17                InputEvent::Key(Key::Char('q')) => break,
18                _ => (),
19            }
20            key_last_pressed = Some(event);
21        }
22
23        // Draw the frame
24        win.draw(|canvas| {
25            canvas.set_named_border(
26                "INPUTS",
27                Align::Right,
28                Attr::NORMAL,
29                Color::White,
30                Color::default(),
31            );
32            let display_text = match key_last_pressed {
33                Some(InputEvent::Key(key)) => format!("Key: {:?}", key),
34                Some(InputEvent::Mouse(mouse)) => match mouse {
35                    MouseEvent::Press { button, x, y } => {
36                        format!("Mouse Press: {:?} at ({},{})", button, x, y)
37                    }
38                    MouseEvent::Release { button, x, y } => {
39                        format!("Mouse Release: {:?} at ({},{})", button, x, y)
40                    }
41                    MouseEvent::Move { x, y } => {
42                        format!("Mouse Move: at ({},{})", x, y)
43                    }
44                },
45                Some(InputEvent::Unknown) => "Unknown input".to_string(),
46                None => "No input yet".to_string(),
47            };
48
49            let full_text = format!("{} (Press 'q' to quit)", display_text);
50
51            canvas.set_str(
52                canvas.width / 2,
53                canvas.height / 2,
54                &full_text,
55                Attr::NORMAL,
56                Color::White,
57                Color::default(),
58                Align::Center,
59            );
60        })?;
61
62        thread::sleep(time::Duration::from_millis(100)); // Sleep to prevent high CPU usage
63    }
64    Ok(())
65}