refactor: unify and simplify the call of app_handle

This commit is contained in:
huzibaca
2024-09-23 16:31:58 +08:00
parent 0a9182519d
commit 60e0f972d0
10 changed files with 135 additions and 158 deletions

View File

@@ -1,3 +1,4 @@
use crate::core::handle;
use crate::{config::Config, feat, log_err};
use anyhow::{bail, Result};
use once_cell::sync::OnceCell;
@@ -7,7 +8,6 @@ use tauri::{AppHandle, Manager};
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, ShortcutState};
pub struct Hotkey {
current: Arc<Mutex<Vec<String>>>, // 保存当前的热键设置
app_handle: Arc<Mutex<Option<AppHandle>>>,
}
impl Hotkey {
@@ -16,12 +16,10 @@ impl Hotkey {
HOTKEY.get_or_init(|| Hotkey {
current: Arc::new(Mutex::new(Vec::new())),
app_handle: Arc::new(Mutex::new(None)),
})
}
pub fn init(&self, app_handle: &AppHandle) -> Result<()> {
*self.app_handle.lock() = Some(app_handle.clone());
pub fn init(&self) -> Result<()> {
let verge = Config::verge();
if let Some(hotkeys) = verge.latest().hotkeys.as_ref() {
@@ -48,11 +46,8 @@ impl Hotkey {
}
pub fn register(&self, hotkey: &str, func: &str) -> Result<()> {
let app_handle = self.app_handle.lock();
if app_handle.is_none() {
bail!("failed to get the hotkey manager");
}
let manager = app_handle.as_ref().unwrap().global_shortcut();
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let manager = app_handle.global_shortcut();
if manager.is_registered(hotkey) {
manager.unregister(hotkey)?;
@@ -88,11 +83,8 @@ impl Hotkey {
}
pub fn unregister(&self, hotkey: &str) -> Result<()> {
let app_handle = self.app_handle.lock();
if app_handle.is_none() {
bail!("failed to get the hotkey manager");
}
let manager = app_handle.as_ref().unwrap().global_shortcut();
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let manager = app_handle.global_shortcut();
manager.unregister(hotkey)?;
log::info!(target: "app", "unregister hotkey {hotkey}");
@@ -166,10 +158,9 @@ impl Hotkey {
impl Drop for Hotkey {
fn drop(&mut self) {
if let Some(app_handle) = self.app_handle.lock().as_ref() {
if let Err(e) = app_handle.global_shortcut().unregister_all() {
log::error!("Error unregistering all hotkeys: {:?}", e);
}
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
if let Err(e) = app_handle.global_shortcut().unregister_all() {
log::error!("Error unregistering all hotkeys: {:?}", e);
}
}
}