refactor!(global-shortcut): better APIs DX (#969)

* feat(global-shortcut): add `GlobalShortcutExt::register_with_handler`

ref: https://github.com/tauri-apps/plugins-workspace/issues/965

* clippy

* refactor apis to take closure by default

* change file

* Update .changes/global-shortcut-refactor.md

Co-authored-by: Simon Hyll <hyllsimon@gmail.com>

* Update global-shortcut-refactor.md

* use option instead

* clippy

* update readme

* on_shortcut and with_shortcut

* map handler

* simplify events

* lint

---------

Co-authored-by: Simon Hyll <hyllsimon@gmail.com>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
pull/1048/head
Amr Bashir 1 year ago committed by GitHub
parent 644eb448bb
commit 62dafda652
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,9 @@
---
"global-shortcut": "patch"
---
**Breaking change** Refactored the plugin Rust APIs for better DX and flexibility:
- Changed `Builder::with_handler` to be a method instead of a static method, it will also be triggered for any and all shortcuts even if the shortcut is registered through JS.
- Added `Builder::with_shortcut` and `Builder::with_shortcuts` to register shortcuts on the plugin builder.
- Added `on_shortcut` and `on_all_shortcuts` to register shortcuts with a handler.

@ -57,20 +57,22 @@ fn main() {
.setup(|app| { .setup(|app| {
#[cfg(desktop)] #[cfg(desktop)]
{ {
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut}; use tauri::Manager;
use tauri_plugin_global_shortcut::{Code, Modifiers};
let ctrl_n_shortcut = Shortcut::new(Some(Modifiers::CONTROL), Code::KeyN);
app.handle().plugin( app.handle().plugin(
tauri_plugin_global_shortcut::Builder::with_handler(move |_app, shortcut| { tauri_plugin_global_shortcut::Builder::new()
println!("{:?}", shortcut); .with_shortcuts(["ctrl+d", "alt+space"])?
if shortcut == &ctrl_n_shortcut { .with_handler(|app, shortcut| {
println!("Ctrl-N Detected!"); if shortcut.matches(Modifiers::CONTROL, Code::KeyD) {
} let _ = app.emit("shortcut-event", "Ctrl+D triggered");
}) }
.build(), if shortcut.matches(Modifiers::ALT, Code::Space) {
let _ = app.emit("shortcut-event", "Alt+Space triggered");
}
})
.build(),
)?; )?;
app.global_shortcut().register(ctrl_n_shortcut)?;
} }
Ok(()) Ok(())

@ -35,20 +35,6 @@ type Result<T> = std::result::Result<T, Error>;
type HotKeyId = u32; type HotKeyId = u32;
type HandlerFn<R> = Box<dyn Fn(&AppHandle<R>, &Shortcut) + Send + Sync + 'static>; type HandlerFn<R> = Box<dyn Fn(&AppHandle<R>, &Shortcut) + Send + Sync + 'static>;
enum ShortcutSource {
Ipc(Channel),
Rust,
}
impl Clone for ShortcutSource {
fn clone(&self) -> Self {
match self {
Self::Ipc(channel) => Self::Ipc(channel.clone()),
Self::Rust => Self::Rust,
}
}
}
pub struct ShortcutWrapper(Shortcut); pub struct ShortcutWrapper(Shortcut);
impl From<Shortcut> for ShortcutWrapper { impl From<Shortcut> for ShortcutWrapper {
@ -64,52 +50,52 @@ impl TryFrom<&str> for ShortcutWrapper {
} }
} }
struct RegisteredShortcut { struct RegisteredShortcut<R: Runtime> {
source: ShortcutSource, shortcut: Shortcut,
shortcut: (Shortcut, Option<String>), handler: Option<Arc<HandlerFn<R>>>,
} }
pub struct GlobalShortcut<R: Runtime> { pub struct GlobalShortcut<R: Runtime> {
#[allow(dead_code)] #[allow(dead_code)]
app: AppHandle<R>, app: AppHandle<R>,
manager: std::result::Result<GlobalHotKeyManager, global_hotkey::Error>, manager: GlobalHotKeyManager,
shortcuts: Arc<Mutex<HashMap<HotKeyId, RegisteredShortcut>>>, shortcuts: Arc<Mutex<HashMap<HotKeyId, RegisteredShortcut<R>>>>,
} }
impl<R: Runtime> GlobalShortcut<R> { impl<R: Runtime> GlobalShortcut<R> {
fn register_internal( fn register_internal<F: Fn(&AppHandle<R>, &Shortcut) + Send + Sync + 'static>(
&self, &self,
shortcut: (Shortcut, Option<String>), shortcut: Shortcut,
source: ShortcutSource, handler: Option<F>,
) -> Result<()> { ) -> Result<()> {
let id = shortcut.0.id(); let id = shortcut.id();
acquire_manager(&self.manager)?.register(shortcut.0)?; let handler = handler.map(|h| Arc::new(Box::new(h) as HandlerFn<R>));
self.manager.register(shortcut)?;
self.shortcuts self.shortcuts
.lock() .lock()
.unwrap() .unwrap()
.insert(id, RegisteredShortcut { source, shortcut }); .insert(id, RegisteredShortcut { shortcut, handler });
Ok(()) Ok(())
} }
fn register_all_internal<S: IntoIterator<Item = (Shortcut, Option<String>)>>( fn register_all_internal<S, F>(&self, shortcuts: S, handler: Option<F>) -> Result<()>
&self, where
shortcuts: S, S: IntoIterator<Item = Shortcut>,
source: ShortcutSource, F: Fn(&AppHandle<R>, &Shortcut) + Send + Sync + 'static,
) -> Result<()> { {
let hotkeys = shortcuts let handler = handler.map(|h| Arc::new(Box::new(h) as HandlerFn<R>));
.into_iter()
.collect::<Vec<(Shortcut, Option<String>)>>();
let manager = acquire_manager(&self.manager)?; let hotkeys = shortcuts.into_iter().collect::<Vec<_>>();
let mut shortcuts = self.shortcuts.lock().unwrap();
for hotkey in hotkeys {
manager.register(hotkey.0)?;
let mut shortcuts = self.shortcuts.lock().unwrap();
for shortcut in hotkeys {
self.manager.register(shortcut)?;
shortcuts.insert( shortcuts.insert(
hotkey.0.id(), shortcut.id(),
RegisteredShortcut { RegisteredShortcut {
source: source.clone(), shortcut,
shortcut: hotkey, handler: handler.clone(),
}, },
); );
} }
@ -117,34 +103,65 @@ impl<R: Runtime> GlobalShortcut<R> {
Ok(()) Ok(())
} }
pub fn register<S: TryInto<ShortcutWrapper>>(&self, shortcut: S) -> Result<()> /// Register a shortcut.
pub fn register<S>(&self, shortcut: S) -> Result<()>
where where
S: TryInto<ShortcutWrapper>,
S::Error: std::error::Error, S::Error: std::error::Error,
{ {
self.register_internal((try_into_shortcut(shortcut)?, None), ShortcutSource::Rust) self.register_internal(
try_into_shortcut(shortcut)?,
None::<fn(&AppHandle<R>, &Shortcut)>,
)
} }
pub fn register_all<T: TryInto<ShortcutWrapper>, S: IntoIterator<Item = T>>( /// Register a shortcut with a handler.
&self, pub fn on_shortcut<S, F>(&self, shortcut: S, handler: F) -> Result<()>
shortcuts: S, where
) -> Result<()> S: TryInto<ShortcutWrapper>,
S::Error: std::error::Error,
F: Fn(&AppHandle<R>, &Shortcut) + Send + Sync + 'static,
{
self.register_internal(try_into_shortcut(shortcut)?, Some(handler))
}
/// Register multiple shortcuts.
pub fn register_all<S, T>(&self, shortcuts: S) -> Result<()>
where where
S: IntoIterator<Item = T>,
T: TryInto<ShortcutWrapper>,
T::Error: std::error::Error, T::Error: std::error::Error,
{ {
let mut s = Vec::new(); let mut s = Vec::new();
for shortcut in shortcuts { for shortcut in shortcuts {
s.push((try_into_shortcut(shortcut)?, None)); s.push(try_into_shortcut(shortcut)?);
} }
self.register_all_internal(s, ShortcutSource::Rust) self.register_all_internal(s, None::<fn(&AppHandle<R>, &Shortcut)>)
}
/// Register multiple shortcuts with a handler.
pub fn on_all_shortcuts<S, T, F>(&self, shortcuts: S, handler: F) -> Result<()>
where
S: IntoIterator<Item = T>,
T: TryInto<ShortcutWrapper>,
T::Error: std::error::Error,
F: Fn(&AppHandle<R>, &Shortcut) + Send + Sync + 'static,
{
let mut s = Vec::new();
for shortcut in shortcuts {
s.push(try_into_shortcut(shortcut)?);
}
self.register_all_internal(s, Some(handler))
} }
pub fn unregister<S: TryInto<ShortcutWrapper>>(&self, shortcut: S) -> Result<()> pub fn unregister<S: TryInto<ShortcutWrapper>>(&self, shortcut: S) -> Result<()>
where where
S::Error: std::error::Error, S::Error: std::error::Error,
{ {
acquire_manager(&self.manager)? let shortcut = try_into_shortcut(shortcut)?;
.unregister(try_into_shortcut(shortcut)?) self.manager.unregister(shortcut)?;
.map_err(Into::into) self.shortcuts.lock().unwrap().remove(&shortcut.id());
Ok(())
} }
pub fn unregister_all<T: TryInto<ShortcutWrapper>, S: IntoIterator<Item = T>>( pub fn unregister_all<T: TryInto<ShortcutWrapper>, S: IntoIterator<Item = T>>(
@ -158,9 +175,15 @@ impl<R: Runtime> GlobalShortcut<R> {
for shortcut in shortcuts { for shortcut in shortcuts {
s.push(try_into_shortcut(shortcut)?); s.push(try_into_shortcut(shortcut)?);
} }
acquire_manager(&self.manager)?
.unregister_all(&s) self.manager.unregister_all(&s)?;
.map_err(Into::into)
let mut shortcuts = self.shortcuts.lock().unwrap();
for s in s {
shortcuts.remove(&s.id());
}
Ok(())
} }
/// Determines whether the given shortcut is registered by this application or not. /// Determines whether the given shortcut is registered by this application or not.
@ -188,14 +211,6 @@ impl<R: Runtime, T: Manager<R>> GlobalShortcutExt<R> for T {
} }
} }
fn acquire_manager(
manager: &std::result::Result<GlobalHotKeyManager, global_hotkey::Error>,
) -> Result<&GlobalHotKeyManager> {
manager
.as_ref()
.map_err(|e| Error::GlobalHotkey(e.to_string()))
}
fn parse_shortcut<S: AsRef<str>>(shortcut: S) -> Result<Shortcut> { fn parse_shortcut<S: AsRef<str>>(shortcut: S) -> Result<Shortcut> {
shortcut.as_ref().parse().map_err(Into::into) shortcut.as_ref().parse().map_err(Into::into)
} }
@ -218,8 +233,10 @@ fn register<R: Runtime>(
handler: Channel, handler: Channel,
) -> Result<()> { ) -> Result<()> {
global_shortcut.register_internal( global_shortcut.register_internal(
(parse_shortcut(&shortcut)?, Some(shortcut)), parse_shortcut(&shortcut)?,
ShortcutSource::Ipc(handler), Some(move |_app: &AppHandle<R>, _shortcut: &Shortcut| {
let _ = handler.send(&shortcut);
}),
) )
} }
@ -231,10 +248,22 @@ fn register_all<R: Runtime>(
handler: Channel, handler: Channel,
) -> Result<()> { ) -> Result<()> {
let mut hotkeys = Vec::new(); let mut hotkeys = Vec::new();
let mut shortcut_map = HashMap::new();
for shortcut in shortcuts { for shortcut in shortcuts {
hotkeys.push((parse_shortcut(&shortcut)?, Some(shortcut))); let hotkey = parse_shortcut(&shortcut)?;
shortcut_map.insert(hotkey.id(), shortcut);
hotkeys.push(hotkey);
} }
global_shortcut.register_all_internal(hotkeys, ShortcutSource::Ipc(handler))
global_shortcut.register_all_internal(
hotkeys,
Some(move |_app: &AppHandle<R>, shortcut: &Shortcut| {
if let Some(shortcut_str) = shortcut_map.get(&shortcut.id()) {
let _ = handler.send(shortcut_str);
}
}),
)
} }
#[tauri::command] #[tauri::command]
@ -269,12 +298,14 @@ fn is_registered<R: Runtime>(
} }
pub struct Builder<R: Runtime> { pub struct Builder<R: Runtime> {
shortcuts: Vec<Shortcut>,
handler: Option<HandlerFn<R>>, handler: Option<HandlerFn<R>>,
} }
impl<R: Runtime> Default for Builder<R> { impl<R: Runtime> Default for Builder<R> {
fn default() -> Self { fn default() -> Self {
Self { Self {
shortcuts: Vec::new(),
handler: Default::default(), handler: Default::default(),
} }
} }
@ -285,16 +316,42 @@ impl<R: Runtime> Builder<R> {
Self::default() Self::default()
} }
/// Add a shortcut to be registerd.
pub fn with_shortcut<T>(mut self, shortcut: T) -> Result<Self>
where
T: TryInto<ShortcutWrapper>,
T::Error: std::error::Error,
{
self.shortcuts.push(try_into_shortcut(shortcut)?);
Ok(self)
}
/// Add multiple shortcuts to be registerd.
pub fn with_shortcuts<S, T>(mut self, shortcuts: S) -> Result<Self>
where
S: IntoIterator<Item = T>,
T: TryInto<ShortcutWrapper>,
T::Error: std::error::Error,
{
for shortcut in shortcuts {
self.shortcuts.push(try_into_shortcut(shortcut)?);
}
Ok(self)
}
/// Specify a global shortcut handler that will be triggered for any and all shortcuts.
pub fn with_handler<F: Fn(&AppHandle<R>, &Shortcut) + Send + Sync + 'static>( pub fn with_handler<F: Fn(&AppHandle<R>, &Shortcut) + Send + Sync + 'static>(
mut self,
handler: F, handler: F,
) -> Self { ) -> Self {
Self { self.handler.replace(Box::new(handler));
handler: Some(Box::new(handler)), self
}
} }
pub fn build(self) -> TauriPlugin<R> { pub fn build(self) -> TauriPlugin<R> {
let handler = self.handler; let handler = self.handler;
let shortcuts = self.shortcuts;
PluginBuilder::new("global-shortcut") PluginBuilder::new("global-shortcut")
.js_init_script(include_str!("api-iife.js").to_string()) .js_init_script(include_str!("api-iife.js").to_string())
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
@ -305,29 +362,37 @@ impl<R: Runtime> Builder<R> {
is_registered is_registered
]) ])
.setup(move |app, _api| { .setup(move |app, _api| {
let shortcuts = let manager = GlobalHotKeyManager::new()?;
Arc::new(Mutex::new(HashMap::<HotKeyId, RegisteredShortcut>::new())); let mut store = HashMap::<HotKeyId, RegisteredShortcut<R>>::new();
for shortcut in shortcuts {
manager.register(shortcut)?;
store.insert(
shortcut.id(),
RegisteredShortcut {
shortcut,
handler: None,
},
);
}
let shortcuts = Arc::new(Mutex::new(store));
let shortcuts_ = shortcuts.clone(); let shortcuts_ = shortcuts.clone();
let app_handle = app.clone(); let app_handle = app.clone();
GlobalHotKeyEvent::set_event_handler(Some(move |e: GlobalHotKeyEvent| { GlobalHotKeyEvent::set_event_handler(Some(move |e: GlobalHotKeyEvent| {
if let Some(shortcut) = shortcuts_.lock().unwrap().get(&e.id) { if let Some(shortcut) = shortcuts_.lock().unwrap().get(&e.id) {
match &shortcut.source { if let Some(handler) = &shortcut.handler {
ShortcutSource::Ipc(channel) => { handler(&app_handle, &shortcut.shortcut);
let _ = channel.send(&shortcut.shortcut.1); }
} if let Some(handler) = &handler {
ShortcutSource::Rust => { handler(&app_handle, &shortcut.shortcut);
if let Some(handler) = &handler {
handler(&app_handle, &shortcut.shortcut.0);
}
}
} }
} }
})); }));
app.manage(GlobalShortcut { app.manage(GlobalShortcut {
app: app.clone(), app: app.clone(),
manager: GlobalHotKeyManager::new(), manager,
shortcuts, shortcuts,
}); });
Ok(()) Ok(())

Loading…
Cancel
Save