creddy/src-tauri/src/shortcuts.rs

90 lines
2.1 KiB
Rust

use serde::{Serialize, Deserialize};
use tauri::{
AppHandle,
Manager,
async_runtime as rt,
};
use tauri_plugin_global_shortcut::{
GlobalShortcutExt,
Error as ShortcutError,
};
use crate::app::APP;
use crate::config::HotkeysConfig;
use crate::errors::*;
use crate::terminal;
#[derive(Debug, Serialize, Deserialize)]
pub enum ShortcutAction {
ShowWindow,
LaunchTerminal,
}
pub fn exec_shortcut(action: ShortcutAction) {
match action {
ShortcutAction::LaunchTerminal => launch_terminal(),
ShortcutAction::ShowWindow => {
let app = APP.get().unwrap();
show_window(app);
},
}
}
fn show_window(app: &AppHandle) {
let handle = app.clone();
rt::spawn(async move {
handle.get_webview_window("main")
.ok_or("Couldn't find application main window")
.error_popup_passthrough("Failed to show window").await?
.show()
.error_popup("Failed to show window").await;
Ok::<(), ()>(())
});
// app.get_webview_window("main") // Option<Window>
// .ok_or("Couldn't find application main window") // Result<Window, &'static str>
// .map(|w| w.show().error_popup("Failed to show window"))
// .error_popup("Failed to show window");
}
fn launch_terminal() {
rt::spawn(async {
terminal::launch(false)
.await
.error_popup("Failed to launch terminal")
.await;
});
}
pub fn register_hotkeys(hotkeys: &HotkeysConfig) -> Result<(), ShortcutError> {
let app = APP.get().unwrap();
let shortcuts = app.global_shortcut();
shortcuts.unregister_all([
hotkeys.show_window.keys.as_str(),
hotkeys.launch_terminal.keys.as_str(),
])?;
if hotkeys.show_window.enabled {
shortcuts.on_shortcut(
hotkeys.show_window.keys.as_str(),
|app, _shortcut, _event| show_window(app)
)?;
}
if hotkeys.launch_terminal.enabled {
shortcuts.on_shortcut(
hotkeys.launch_terminal.keys.as_str(),
|_app, _shortcut, _event| launch_terminal()
)?;
}
Ok(())
}