@@ -14,10 +14,9 @@ use evdev_rs::{
1414} ;
1515
1616use crate :: {
17- config:: KeyBehaviorMode ,
17+ config:: { KeyBehaviorMode , ModifierBehaviorMode } ,
1818 constants:: {
1919 SIMULATION_HOLD_DELAY_MS ,
20- SIMULATION_HOLD_INTERVAL_MS ,
2120 MAX_RETRIES ,
2221 RETRY_DELAY_MS ,
2322 MAX_DEVICE_INIT_RETRIES ,
@@ -26,25 +25,39 @@ use crate::{
2625 error:: { SimulatorError , Result } ,
2726} ;
2827
29- fn write_event_with_retry ( device : & UInputDevice , event : & InputEvent ) -> Result < ( ) > {
28+ fn retry < T , F > ( mut operation : F , max_retries : u32 , delay_ms : u64 , log_fn : impl Fn ( usize ) ) -> Result < T >
29+ where
30+ F : FnMut ( ) -> Result < T > ,
31+ {
3032 let mut last_error = None ;
31- for attempt in 0 ..MAX_RETRIES {
32- match device . write_event ( event ) {
33- Ok ( _ ) => return Ok ( ( ) ) ,
33+ for attempt in 0 ..max_retries {
34+ match operation ( ) {
35+ Ok ( result ) => return Ok ( result ) ,
3436 Err ( e) => {
3537 last_error = Some ( e) ;
36- if attempt < MAX_RETRIES - 1 {
37- log :: debug! ( "Write event attempt {} failed, retrying..." , attempt + 1 ) ;
38- thread:: sleep ( Duration :: from_millis ( RETRY_DELAY_MS ) ) ;
38+ if attempt < max_retries - 1 {
39+ log_fn ( ( attempt + 1 ) as usize ) ;
40+ thread:: sleep ( Duration :: from_millis ( delay_ms ) ) ;
3941 }
4042 }
4143 }
4244 }
43- Err ( SimulatorError :: KeySimulation ( format ! (
44- "Failed after {} retries: {:?}" ,
45- MAX_RETRIES ,
46- last_error. unwrap( )
47- ) ) . into ( ) )
45+ Err ( last_error. unwrap ( ) )
46+ }
47+
48+ fn write_event_with_retry ( device : & UInputDevice , event : & InputEvent ) -> Result < ( ) > {
49+ retry (
50+ || {
51+ device. write_event ( event)
52+ . map_err ( |e| SimulatorError :: KeySimulation ( format ! ( "Failed event: {:?}" , e) ) . into ( ) )
53+ } ,
54+ MAX_RETRIES ,
55+ RETRY_DELAY_MS ,
56+ |attempt| {
57+ log:: debug!( "Write event attempt {} failed, retrying..." , attempt) ;
58+ } ,
59+ )
60+ . map_err ( |e| e)
4861}
4962
5063fn write_key_events ( device : & UInputDevice , keys : & [ EventCode ] , value : i32 , timeval : & TimeVal ) -> Result < ( ) > {
@@ -81,37 +94,68 @@ fn setup_device(selected_keys: &Arc<Mutex<Vec<EventCode>>>) -> Result<UInputDevi
8194}
8295
8396fn setup_device_with_retry ( selected_keys : & Arc < Mutex < Vec < EventCode > > > ) -> Result < UInputDevice > {
84- let mut last_error = None ;
85- for attempt in 0 ..MAX_DEVICE_INIT_RETRIES {
86- match setup_device ( selected_keys) {
87- Ok ( device) => return Ok ( device) ,
88- Err ( e) => {
89- last_error = Some ( e) ;
90- if attempt < MAX_DEVICE_INIT_RETRIES - 1 {
91- log:: warn!( "Device initialization attempt {} failed, retrying..." , attempt + 1 ) ;
92- thread:: sleep ( Duration :: from_millis ( DEVICE_INIT_RETRY_DELAY_MS ) ) ;
97+ retry (
98+ || setup_device ( selected_keys) ,
99+ MAX_DEVICE_INIT_RETRIES ,
100+ DEVICE_INIT_RETRY_DELAY_MS ,
101+ |attempt| {
102+ log:: warn!( "Device initialization attempt {} failed, retrying..." , attempt) ;
103+ } ,
104+ )
105+ . map_err ( |e| SimulatorError :: DeviceInitialization ( format ! ( "Failed after {} retries: {:?}" , MAX_DEVICE_INIT_RETRIES , e) ) . into ( ) )
106+ }
107+
108+ // New function to initialize simulation keys
109+ pub fn initialize_simulation_keys (
110+ app_data : & crate :: config:: AppData ,
111+ selected_keys : & mut Vec < evdev_rs:: enums:: EventCode > ,
112+ key_behavior : & mut crate :: config:: KeyBehaviorMode ,
113+ ) {
114+ selected_keys. clear ( ) ;
115+ * key_behavior = app_data. key_behavior ;
116+
117+ log:: debug!( "Initializing simulation with keys: {:?}" , app_data. selected_keys) ;
118+
119+ for raw in & app_data. selected_keys {
120+ if let Some ( device_key) = crate :: utils:: key_utils:: raw_key_to_device_keycode ( raw) {
121+ if let Some ( ev_key) = crate :: utils:: key_utils:: keycode_to_evkey ( device_key) {
122+ // Handle modifier keys based on modifier behavior setting
123+ if crate :: utils:: key_utils:: is_modifier_key ( raw) &&
124+ app_data. modifier_behavior == crate :: config:: ModifierBehaviorMode :: Click {
125+ selected_keys. push ( evdev_rs:: enums:: EventCode :: EV_KEY ( ev_key) ) ;
126+ } else {
127+ selected_keys. push ( evdev_rs:: enums:: EventCode :: EV_KEY ( ev_key) ) ;
93128 }
129+ log:: debug!( "Added key: {:?}" , ev_key) ;
94130 }
131+ } else {
132+ log:: warn!( "Failed to map key: {}" , raw) ;
95133 }
96134 }
97- Err ( SimulatorError :: DeviceInitialization ( format ! (
98- "Failed after {} retries: {:?}" ,
99- MAX_DEVICE_INIT_RETRIES ,
100- last_error. unwrap( )
101- ) ) . into ( ) )
135+
136+ if selected_keys. is_empty ( ) {
137+ log:: warn!( "No valid keys initialized for simulation" ) ;
138+ } else {
139+ log:: info!( "Simulation initialized with {} keys" , selected_keys. len( ) ) ;
140+ }
102141}
103142
104143// Main simulation loop that handles both click and hold modes
105144pub fn simulate_keys (
106145 running : Arc < Mutex < bool > > ,
107146 interval_ms : Arc < Mutex < u64 > > ,
108147 selected_keys : Arc < Mutex < Vec < EventCode > > > ,
109- modifier_mode : Arc < Mutex < KeyBehaviorMode > > ,
148+ key_behavior : Arc < Mutex < KeyBehaviorMode > > ,
149+ modifier_behavior : ModifierBehaviorMode ,
110150) -> Result < ( ) > {
111151 let uinput_device = setup_device_with_retry ( & selected_keys) ?;
112152 let timeval = TimeVal :: new ( 0 , 0 ) ;
113- let keys = selected_keys. lock ( ) . unwrap ( ) . clone ( ) ;
114- let mode = * modifier_mode. lock ( ) . unwrap ( ) ;
153+ // Combine acquisitions for keys and mode.
154+ let ( keys, mode) = {
155+ let keys = selected_keys. lock ( ) . unwrap ( ) . clone ( ) ;
156+ let mode = * key_behavior. lock ( ) . unwrap ( ) ;
157+ ( keys, mode)
158+ } ;
115159
116160 log:: info!( "Device initialized with keys: {:?}" , keys) ;
117161 log:: info!( "Key behavior mode set to: {:?}" , mode) ;
@@ -127,24 +171,42 @@ pub fn simulate_keys(
127171 write_key_events ( & uinput_device, & keys, 1 , & timeval) ?;
128172
129173 while * running. lock ( ) . unwrap ( ) {
130- write_key_events ( & uinput_device, & [ ] , 0 , & timeval) ?; // Just sync
131- thread:: sleep ( Duration :: from_millis ( SIMULATION_HOLD_INTERVAL_MS ) ) ;
174+ write_key_events ( & uinput_device, & [ ] , 0 , & timeval) ?;
132175 }
133176
134177 // Release keys
135178 write_key_events ( & uinput_device, & keys, 0 , & timeval) ?;
136179 }
137180 KeyBehaviorMode :: Click => {
138- while * running. lock ( ) . unwrap ( ) {
139- let interval = * interval_ms. lock ( ) . unwrap ( ) ;
181+ if modifier_behavior == ModifierBehaviorMode :: Click {
182+ let ( mod_keys, non_mod_keys) : ( Vec < EventCode > , Vec < EventCode > ) =
183+ keys. iter ( ) . cloned ( ) . partition ( |k| crate :: utils:: key_utils:: is_modifier_evcode ( k) ) ;
184+
185+ while * running. lock ( ) . unwrap ( ) {
186+ let interval = * interval_ms. lock ( ) . unwrap ( ) ;
187+ for nm in & non_mod_keys {
188+ if !mod_keys. is_empty ( ) {
189+ write_key_events ( & uinput_device, & mod_keys, 1 , & timeval) ?;
190+ }
191+ write_key_events ( & uinput_device, & [ * nm] , 1 , & timeval) ?;
192+ write_key_events ( & uinput_device, & [ * nm] , 0 , & timeval) ?;
193+ if !mod_keys. is_empty ( ) {
194+ write_key_events ( & uinput_device, & mod_keys, 0 , & timeval) ?;
195+ }
196+ thread:: sleep ( Duration :: from_millis ( interval) ) ;
197+ }
198+ }
199+ } else {
200+ while * running. lock ( ) . unwrap ( ) {
201+ let interval = * interval_ms. lock ( ) . unwrap ( ) ;
140202
141- // Press keys
142- write_key_events ( & uinput_device, & keys, 1 , & timeval) ?;
143- thread:: sleep ( Duration :: from_millis ( SIMULATION_HOLD_DELAY_MS ) ) ;
203+ // Press keys
204+ write_key_events ( & uinput_device, & keys, 1 , & timeval) ?;
144205
145- // Release keys
146- write_key_events ( & uinput_device, & keys, 0 , & timeval) ?;
147- thread:: sleep ( Duration :: from_millis ( interval) ) ;
206+ // Release keys
207+ write_key_events ( & uinput_device, & keys, 0 , & timeval) ?;
208+ thread:: sleep ( Duration :: from_millis ( interval) ) ;
209+ }
148210 }
149211 }
150212 }
0 commit comments