From c2103c91bcdb1f6177772a4392c6c89edf8562ba Mon Sep 17 00:00:00 2001 From: Amr Bashir Date: Mon, 16 Oct 2023 20:39:27 +0300 Subject: [PATCH] feat(global-shortcut): pass app handle to the closure, closes #657 (#658) * feat(global-shortcut): pass app handle to the closure, closes #657 * Update global-shortcut-app-handle.md --- .changes/global-shortcut-app-handle.md | 5 +++++ plugins/global-shortcut/src/lib.rs | 26 ++++++++++++++++++-------- 2 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 .changes/global-shortcut-app-handle.md diff --git a/.changes/global-shortcut-app-handle.md b/.changes/global-shortcut-app-handle.md new file mode 100644 index 00000000..37dd286f --- /dev/null +++ b/.changes/global-shortcut-app-handle.md @@ -0,0 +1,5 @@ +--- +"global-shortcut": "patch" +--- + +**Breaking Change**: Changed `Builder::with_handler` closure to take `&AppHandle` as the first argument and the shortcut as the second argument. diff --git a/plugins/global-shortcut/src/lib.rs b/plugins/global-shortcut/src/lib.rs index 85e0910a..1cb9d25c 100644 --- a/plugins/global-shortcut/src/lib.rs +++ b/plugins/global-shortcut/src/lib.rs @@ -33,7 +33,7 @@ mod error; pub use error::Error; type Result = std::result::Result; type HotKeyId = u32; -type HandlerFn = Box; +type HandlerFn = Box, &Shortcut) + Send + Sync + 'static>; enum ShortcutSource { Ipc(Channel), @@ -268,23 +268,32 @@ fn is_registered( Ok(global_shortcut.is_registered(parse_shortcut(shortcut)?)) } -#[derive(Default)] -pub struct Builder { - handler: Option, +pub struct Builder { + handler: Option>, } -impl Builder { +impl Default for Builder { + fn default() -> Self { + Self { + handler: Default::default(), + } + } +} + +impl Builder { pub fn new() -> Self { Self::default() } - pub fn with_handler(handler: F) -> Self { + pub fn with_handler, &Shortcut) + Send + Sync + 'static>( + handler: F, + ) -> Self { Self { handler: Some(Box::new(handler)), } } - pub fn build(self) -> TauriPlugin { + pub fn build(self) -> TauriPlugin { let handler = self.handler; PluginBuilder::new("globalShortcut") .js_init_script(include_str!("api-iife.js").to_string()) @@ -300,6 +309,7 @@ impl Builder { Arc::new(Mutex::new(HashMap::::new())); let shortcuts_ = shortcuts.clone(); + let app_handle = app.clone(); GlobalHotKeyEvent::set_event_handler(Some(move |e: GlobalHotKeyEvent| { if let Some(shortcut) = shortcuts_.lock().unwrap().get(&e.id) { match &shortcut.source { @@ -308,7 +318,7 @@ impl Builder { } ShortcutSource::Rust => { if let Some(handler) = &handler { - handler(&shortcut.shortcut.0); + handler(&app_handle, &shortcut.shortcut.0); } } }