···
#![windows_subsystem = "windows"]
3
+
use std::collections::HashSet;
use std::{collections::HashMap, time::Duration};
6
-
use device_query::{DeviceEvents, DeviceEventsHandler, Keycode};
6
+
use device_query::{DeviceState, Keycode};
use quad_snd::{AudioContext, Sound};
···
let sound = sounds.get(name).unwrap();
sound.play(&ctx, Default::default());
28
+
let play_sound_for_key = |key: Keycode| match key {
29
+
Keycode::CapsLock => play_sound("caps"),
30
+
Keycode::Delete | Keycode::Backspace => play_sound("delete"),
31
+
Keycode::Up | Keycode::Down | Keycode::Left | Keycode::Right => play_sound("movement"),
33
+
let no = fastrand::u8(1..=4);
34
+
play_sound(&format!("press-{no}"));
29
-
let (tx, rx) = mpsc::channel();
38
+
let state = DeviceState::new();
39
+
let mut previously_held_keys = HashSet::<Keycode>::new();
40
+
let mut key_press_times = HashMap::<Keycode, std::time::Instant>::new();
41
+
let mut last_sound_time = std::time::Instant::now();
31
-
let query = DeviceEventsHandler::new(Duration::from_millis(10)).expect("already running");
32
-
let _guard = query.on_key_down(move |key| {
33
-
tx.send(*key).expect("tx");
43
+
let initial_delay = Duration::from_millis(500); // Wait 500ms before starting to repeat
44
+
let repeat_interval = Duration::from_millis(50); // Then repeat every 50ms
37
-
if let Ok(key) = rx.recv() {
39
-
Keycode::CapsLock => play_sound("caps"),
40
-
Keycode::Delete | Keycode::Backspace => play_sound("delete"),
41
-
Keycode::Up | Keycode::Down | Keycode::Left | Keycode::Right => {
42
-
play_sound("movement")
47
+
let currently_held_keys: HashSet<Keycode> = state.query_keymap().into_iter().collect();
49
+
// Track when keys were first pressed
50
+
for key in ¤tly_held_keys {
51
+
if !previously_held_keys.contains(key) {
52
+
// Key just pressed, record the time and play initial sound
53
+
key_press_times.insert(*key, std::time::Instant::now());
54
+
play_sound_for_key(*key);
58
+
// Remove timing info for released keys
59
+
key_press_times.retain(|key, _| currently_held_keys.contains(key));
61
+
// Play repeating sounds every 50ms, but only after initial delay
62
+
if last_sound_time.elapsed() >= repeat_interval {
63
+
let now = std::time::Instant::now();
64
+
for key in ¤tly_held_keys {
45
-
let no = fastrand::u8(1..=4);
46
-
play_sound(&format!("press-{no}"));
79
+
if let Some(press_time) = key_press_times.get(key) {
80
+
// Only repeat if key has been held longer than initial delay
81
+
if now.duration_since(*press_time) >= initial_delay {
82
+
play_sound_for_key(*key);
86
+
last_sound_time = now;
50
-
println!("handling new event");
89
+
previously_held_keys = currently_held_keys;
91
+
// Buffer inputs at lower interval (5ms)
92
+
std::thread::sleep(Duration::from_millis(5));