Skip to content

Commit ede9232

Browse files
committed
macos: fix key-release with repeat logic
1 parent b071201 commit ede9232

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

input-emulation/src/macos.rs

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
1111
use input_event::{Event, KeyboardEvent, PointerEvent};
1212
use keycode::{KeyMap, KeyMapping};
1313
use std::ops::{Index, IndexMut};
14+
use std::sync::Arc;
1415
use std::time::Duration;
15-
use tokio::task::AbortHandle;
16+
use tokio::{sync::Notify, task::AbortHandle};
1617

1718
use super::error::MacOSEmulationCreationError;
1819

@@ -23,6 +24,7 @@ pub(crate) struct MacOSEmulation {
2324
event_source: CGEventSource,
2425
repeat_task: Option<AbortHandle>,
2526
button_state: ButtonState,
27+
notify_repeat_task: Arc<Notify>,
2628
}
2729

2830
struct ButtonState {
@@ -79,20 +81,27 @@ impl MacOSEmulation {
7981
async fn spawn_repeat_task(&mut self, key: u16) {
8082
// there can only be one repeating key and it's
8183
// always the last to be pressed
82-
self.kill_repeat_task();
84+
self.cancel_repeat_task().await;
8385
let event_source = self.event_source.clone();
86+
let notify = self.notify_repeat_task.clone();
8487
let repeat_task = tokio::task::spawn_local(async move {
85-
tokio::time::sleep(DEFAULT_REPEAT_DELAY).await;
8688
loop {
89+
tokio::select! {
90+
_ = tokio::time::sleep(DEFAULT_REPEAT_INTERVAL) => {},
91+
_ = notify.notified() => break,
92+
}
8793
key_event(event_source.clone(), key, 1);
88-
tokio::time::sleep(DEFAULT_REPEAT_INTERVAL).await;
8994
}
95+
// release key when cancelled
96+
key_event(event_source.clone(), key, 0);
9097
});
9198
self.repeat_task = Some(repeat_task.abort_handle());
9299
}
93-
fn kill_repeat_task(&mut self) {
100+
101+
async fn cancel_repeat_task(&mut self) {
94102
if let Some(task) = self.repeat_task.take() {
95-
task.abort();
103+
self.notify_repeat_task.notify_waiters();
104+
task.await;
96105
}
97106
}
98107
}
@@ -346,7 +355,7 @@ impl Emulation for MacOSEmulation {
346355
match state {
347356
// pressed
348357
1 => self.spawn_repeat_task(code).await,
349-
_ => self.kill_repeat_task(),
358+
_ => self.cancel_repeat_task().await,
350359
}
351360
key_event(self.event_source.clone(), code, state)
352361
}

0 commit comments

Comments
 (0)