@@ -11,8 +11,9 @@ use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
1111use input_event:: { Event , KeyboardEvent , PointerEvent } ;
1212use keycode:: { KeyMap , KeyMapping } ;
1313use std:: ops:: { Index , IndexMut } ;
14+ use std:: sync:: Arc ;
1415use std:: time:: Duration ;
15- use tokio:: task:: AbortHandle ;
16+ use tokio:: { sync :: Notify , task:: AbortHandle } ;
1617
1718use 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
2830struct 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