@@ -2,7 +2,7 @@ use rdev::{Event, EventType, listen};
22use serde:: Serialize ;
33use serde_json:: { Value , json} ;
44use std:: sync:: atomic:: { AtomicBool , Ordering } ;
5- use tauri:: { AppHandle , Emitter } ;
5+ use tauri:: { AppHandle , Emitter , Runtime , command } ;
66
77static IS_RUNNING : AtomicBool = AtomicBool :: new ( false ) ;
88
@@ -21,15 +21,16 @@ pub struct DeviceEvent {
2121 value : Value ,
2222}
2323
24- pub fn start_listening ( app_handle : AppHandle ) {
24+ #[ command]
25+ pub async fn start_device_listening < R : Runtime > ( app_handle : AppHandle < R > ) -> Result < ( ) , String > {
2526 if IS_RUNNING . load ( Ordering :: SeqCst ) {
26- return ;
27+ return Err ( "Device is already listening" . to_string ( ) ) ;
2728 }
2829
2930 IS_RUNNING . store ( true , Ordering :: SeqCst ) ;
3031
3132 let callback = move |event : Event | {
32- let device = match event. event_type {
33+ let device_event = match event. event_type {
3334 EventType :: ButtonPress ( button) => DeviceEvent {
3435 kind : DeviceKind :: MousePress ,
3536 value : json ! ( format!( "{:?}" , button) ) ,
@@ -53,20 +54,10 @@ pub fn start_listening(app_handle: AppHandle) {
5354 _ => return ,
5455 } ;
5556
56- if let Err ( e) = app_handle. emit ( "device-changed" , device) {
57- eprintln ! ( "Failed to emit event: {:?}" , e) ;
58- }
57+ let _ = app_handle. emit ( "device-changed" , device_event) ;
5958 } ;
6059
61- #[ cfg( target_os = "macos" ) ]
62- if let Err ( e) = listen ( callback) {
63- eprintln ! ( "Device listening error: {:?}" , e) ;
64- }
60+ listen ( callback) . map_err ( |err| format ! ( "Failed to listen device: {:?}" , err) ) ?;
6561
66- #[ cfg( not( target_os = "macos" ) ) ]
67- std:: thread:: spawn ( move || {
68- if let Err ( e) = listen ( callback) {
69- eprintln ! ( "Device listening error: {:?}" , e) ;
70- }
71- } ) ;
62+ Ok ( ( ) )
7263}
0 commit comments