Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
implement hotkeys backend with tauri plugin
Brendan Allan7e2cfedb2eed
diff --git a/Cargo.lock b/Cargo.lockindex 096703334..a48ed4c40 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -370,6 +370,9 @@ name = "bitflags"version = "2.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"+dependencies = [+ "serde",+][[package]]name = "block"@@ -529,6 +532,7 @@ dependencies = ["image","indexmap 2.3.0","jpeg-encoder",+ "keyboard-types","nix 0.20.0","num-traits","regex",@@ -543,6 +547,7 @@ dependencies = ["tauri-build","tauri-plugin-context-menu","tauri-plugin-deep-link",+ "tauri-plugin-global-shortcut","tauri-plugin-oauth","tauri-plugin-positioner","tauri-specta",@@ -1784,6 +1789,24 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"+[[package]]+name = "global-hotkey"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "89cb13e8c52c87e28a46eae3e5e65b8f0cd465c4c9e67b13d56c70412e792bc3"+dependencies = [+ "bitflags 2.6.0",+ "cocoa 0.25.0",+ "crossbeam-channel",+ "keyboard-types",+ "objc",+ "once_cell",+ "serde",+ "thiserror",+ "windows-sys 0.52.0",+ "x11-dl",+]+[[package]]name = "globset"version = "0.4.14"@@ -2456,6 +2479,17 @@ dependencies = ["thiserror",]+[[package]]+name = "keyboard-types"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"+dependencies = [+ "bitflags 2.6.0",+ "serde",+ "unicode-segmentation",+]+[[package]]name = "kuchikiki"version = "0.8.2"@@ -4978,6 +5012,18 @@ dependencies = ["winreg 0.52.0",]+[[package]]+name = "tauri-plugin-global-shortcut"+version = "1.0.0"+dependencies = [+ "global-hotkey",+ "log",+ "serde",+ "serde_json",+ "tauri",+ "thiserror",+]+[[package]]name = "tauri-plugin-oauth"version = "0.0.0-alpha.0"diff --git a/Cargo.toml b/Cargo.tomlindex 91b958b2a..91e408b4d 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,3 +1,3 @@[workspace]resolver = "2"-members = ["apps/desktop/src-tauri"]+members = ["apps/desktop/src-tauri", "crates/*"]diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 6458f9658..f573ee04b 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -30,7 +30,8 @@"react-router-dom": "^6.18.0","tailwindcss": "^3.3.4","tauri-plugin-context-menu": "^0.5.0",- "tauri-plugin-positioner-api": "^0.2.7"+ "tauri-plugin-positioner-api": "^0.2.7",+ "@tauri-apps/plugin-global-shortcut": "workspace:*"},"devDependencies": {"@tauri-apps/cli": "^1.5.11",diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex fc97d9abc..b9d17fa69 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -14,40 +14,41 @@ tauri-build = { version = "1.5.1", features = [] }ffmpeg-sidecar = { git = "https://github.com/CapSoftware/ffmpeg-sidecar", branch = "main" }[dependencies]-tauri = { version = "1.6.1", features = [- "system-tray",- "updater",- "macos-private-api",- "window-set-position",- "fs-write-file",- "fs-remove-file",- "fs-read-file",- "fs-rename-file",- "fs-exists",- "fs-remove-dir",- "fs-read-dir",- "fs-copy-file",- "fs-create-dir",- "window-set-ignore-cursor-events",- "window-unminimize",- "window-minimize",- "window-close",- "window-show",- "window-start-dragging",- "window-hide",- "window-unmaximize",- "window-maximize",- "window-set-always-on-top",- "shell-open",- "devtools",- "os-all",- "http-all",- "icon-png",+tauri = { version = "1.6.1", features = [ "window-create",+ "system-tray",+ "updater",+ "macos-private-api",+ "window-set-position",+ "fs-write-file",+ "fs-remove-file",+ "fs-read-file",+ "fs-rename-file",+ "fs-exists",+ "fs-remove-dir",+ "fs-read-dir",+ "fs-copy-file",+ "fs-create-dir",+ "window-set-ignore-cursor-events",+ "window-unminimize",+ "window-minimize",+ "window-close",+ "window-show",+ "window-start-dragging",+ "window-hide",+ "window-unmaximize",+ "window-maximize",+ "window-set-always-on-top",+ "shell-open",+ "devtools",+ "os-all",+ "http-all",+ "icon-png",] }serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"tauri-plugin-context-menu = "0.7.0"tauri-plugin-positioner = { version = "1.0.4", features = ["system-tray"] }+tauri-plugin-global-shortcut = { path = "../../../crates/tauri-plugin-global-shortcut" }ffmpeg-sidecar = { git = "https://github.com/CapSoftware/ffmpeg-sidecar", branch = "main" }cpal = "0.15.2"which = "4.2.2"@@ -81,9 +82,15 @@ tracing = "0.1"tracing-subscriber = "0.3"tracing-appender = "0.2"sentry-tracing = "0.34.0"+keyboard-types = "0.7.0"[target.'cfg(windows)'.dependencies]-winapi = { version = "0.3.9", features = ["fileapi", "winbase", "winnt", "handleapi"] }+winapi = { version = "0.3.9", features = [+ "fileapi",+ "winbase",+ "winnt",+ "handleapi",+] }[features]# this feature is used for production builds or when `devPath` points to the filesystemdiff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex 2baccab93..3a39259c1 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -166,12 +166,12 @@ fn main() {.with_menu(create_tray_menu(None)).with_menu_on_left_click(false).with_title("Cap");-+#[cfg(target_os = "windows")]let tray = SystemTray::new().with_menu(create_tray_menu(None)).with_id("Cap");-+tauri::Builder::default().plugin(tauri_plugin_oauth::init())@@ -203,7 +203,7 @@ fn main() {.unwrap_or_else(|| PathBuf::new());let recording_state = RecordingState {- active_recording: None,+ active_recording: None,data_dir: data_directory,max_screen_width: max_width as usize,max_screen_height: max_height as usize,@@ -331,6 +331,7 @@ fn main() {]).plugin(tauri_plugin_context_menu::init())+ .plugin(tauri_plugin_global_shortcut::Builder::new().build()).system_tray(tray).on_system_tray_event(move |app, event| {match event {diff --git a/apps/desktop/src-tauri/src/media/mod.rs b/apps/desktop/src-tauri/src/media/mod.rsindex 4e86630dd..66ffdae4a 100644--- a/apps/desktop/src-tauri/src/media/mod.rs+++ b/apps/desktop/src-tauri/src/media/mod.rs@@ -1,11 +1,14 @@use std::{- path::{ Path, PathBuf },+ path::{Path, PathBuf},process::Stdio,- sync::{ atomic::{ AtomicBool, Ordering }, Arc },- time::{ Duration, Instant },+ sync::{+ atomic::{AtomicBool, Ordering},+ Arc,+ },+ time::{Duration, Instant},};-use tokio::io::{ AsyncBufReadExt, AsyncWriteExt, BufReader };-use tokio::process::{ Child, ChildStdin, Command };+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+use tokio::process::{Child, ChildStdin, Command};use tokio::sync::Mutex;use tokio::task::JoinHandle;use tracing::Level;@@ -13,7 +16,7 @@ use tracing::Level;use crate::{app::config,recording::RecordingOptions,- utils::{ create_named_pipe, ffmpeg_path_as_str },+ utils::{create_named_pipe, ffmpeg_path_as_str},};mod audio;@@ -80,7 +83,7 @@ impl MediaRecorder {recording_dir: &Path,custom_device: Option<&str>,max_screen_width: usize,- max_screen_height: usize+ max_screen_height: usize,) -> Result<(), String> {if !scap::has_permission() {tracing::warn!("Screen capturing permission not granted. Requesting permission...");@@ -104,7 +107,7 @@ impl MediaRecorder {let mut video_capturer = VideoCapturer::new(max_screen_width,max_screen_height,- self.should_stop.clone()+ self.should_stop.clone(),);let adjusted_width = video_capturer.frame_width;let adjusted_height = video_capturer.frame_height;@@ -199,13 +202,19 @@ impl MediaRecorder {.args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"]).args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"]).args(["-movflags", "frag_keyframe+empty_moov"])- .args(["-vf", &format!("fps={fps},scale=in_range=full:out_range=limited")]);+ .args([+ "-vf",+ &format!("fps={fps},scale=in_range=full:out_range=limited"),+ ]);if self.audio_enabled {ffmpeg_command// audio.args(["-codec:a", "aac", "-b:a", "128k", "-async", "1"])- .args(["-af", "aresample=async=1:min_hard_comp=0.100000:first_pts=0"]);+ .args([+ "-af",+ "aresample=async=1:min_hard_comp=0.100000:first_pts=0",+ ]);} else {ffmpeg_command.args(["-an"]);}@@ -215,7 +224,8 @@ impl MediaRecorder {tracing::trace!("Starting FFmpeg process...");let (ffmpeg_child, ffmpeg_stdin) = self- .start_ffmpeg_process(ffmpeg_command).await+ .start_ffmpeg_process(ffmpeg_command)+ .await.map_err(|e| e.to_string())?;tracing::trace!("Ffmpeg process started");@@ -290,7 +300,7 @@ impl MediaRecorder {async fn start_ffmpeg_process(&self,- cmd: Command+ cmd: Command,) -> Result<(Child, ChildStdin), std::io::Error> {let mut video_process = start_recording_process(cmd).await.map_err(|e| {tracing::error!("Failed to start video recording process: {}", e);@@ -317,7 +327,7 @@ pub fn enumerate_audio_devices() -> Vec<String> {#[tracing::instrument]async fn start_recording_process(- mut cmd: Command+ mut cmd: Command,) -> Result<tokio::process::Child, std::io::Error> {let mut process = cmd.stdin(Stdio::piped()).stderr(Stdio::piped()).spawn()?;@@ -337,7 +347,7 @@ async fn start_recording_process(#[tracing::instrument]async fn wait_for_start_times(audio_start_time: &Mutex<Option<Instant>>,- video_start_time: &Mutex<Option<Instant>>+ video_start_time: &Mutex<Option<Instant>>,) -> (Instant, Instant) {loop {let audio_start_locked = audio_start_time.lock().await;@@ -362,7 +372,7 @@ pub enum TimeOffsetTarget {#[tracing::instrument]async fn create_time_offset_args(audio_start_time: &Mutex<Option<Instant>>,- video_start_time: &Mutex<Option<Instant>>+ video_start_time: &Mutex<Option<Instant>>,) -> Option<(TimeOffsetTarget, Vec<String>)> {let (audio_start, video_start) = wait_for_start_times(audio_start_time, video_start_time).await;let duration_difference = if audio_start > video_start {diff --git a/apps/desktop/src-tauri/src/utils.rs b/apps/desktop/src-tauri/src/utils.rsindex daf0a9a46..844bc65b5 100644--- a/apps/desktop/src-tauri/src/utils.rs+++ b/apps/desktop/src-tauri/src/utils.rs@@ -48,7 +48,7 @@ pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>>use std::os::windows::ffi::OsStrExt;use std::ptr::null_mut;use winapi::um::namedpipeapi::CreateNamedPipeW; // Corrected import- use winapi::um::winbase::{PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE, PIPE_READMODE_BYTE, PIPE_WAIT};+ use winapi::um::winbase::{PIPE_ACCESS_DUPLEX, PIPE_READMODE_BYTE, PIPE_TYPE_BYTE, PIPE_WAIT};let path_wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();let handle = unsafe {diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.jsonindex 7f1465752..6ec46d416 100644--- a/apps/desktop/src-tauri/tauri.conf.json+++ b/apps/desktop/src-tauri/tauri.conf.json@@ -23,6 +23,7 @@"window": {"all": false,"close": true,+ "create": true,"hide": true,"show": true,"maximize": true,diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex cc4b52d4c..2e3449314 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect } from "react";+import { useState, useEffect, useRef } from "react";import {Device,DeviceKind,@@ -18,6 +18,7 @@ import { Button } from "@cap/ui";import { Logo } from "@/components/icons/Logo";import { emit, listen, UnlistenFn } from "@tauri-apps/api/event";+import { register, unregister } from "@tauri-apps/plugin-global-shortcut";import { invoke } from "@tauri-apps/api/tauri";import {getLatestVideoId,@@ -209,6 +210,7 @@ export const Recorder = () => {};const handleStartAllRecordings = async () => {+ if (isRecording) return;try {console.log("bruh");setStartingRecording(true);@@ -235,14 +237,13 @@ export const Recorder = () => {};const handleStopAllRecordings = async () => {+ if (!isRecording) return;setStoppingRecording(true);try {tauriWindow.then(({ WebviewWindow }) => {const main = WebviewWindow.getByLabel("main");- if (main && main.isMinimized()) {- main.unminimize();- }+ if (main?.isMinimized()) main.unminimize();});} catch (error) {console.error("Error unminimizing main window:", error);@@ -292,6 +293,8 @@ export const Recorder = () => {setStoppingRecording(false);};+ useKeybinds(handleStartAllRecordings, handleStopAllRecordings);+useEffect(() => {if (stoppingRecording) {const messages = ["Processing video", "Almost done", "Finishing up"];@@ -492,3 +495,26 @@ export const Recorder = () => {</>);};++function useKeybinds(startRecording: () => void, stopRecording: () => void) {+ const handlers = useRef({+ startRecording,+ stopRecording,+ });+ handlers.current = {+ startRecording,+ stopRecording,+ };++ useEffect(() => {+ // register("CommandOrControl+Shift+R", () =>+ // handlers.current.startRecording()+ // );+ // register("CommandOrControl+Shift+S", () =>+ // handlers.current.stopRecording()+ // );+ // return () => {+ // unregister(["CommandOrControl+Shift+R", "CommandOrControl+Shift+S"]);+ // };+ }, []);+}diff --git a/crates/tauri-plugin-global-shortcut/Cargo.toml b/crates/tauri-plugin-global-shortcut/Cargo.tomlnew file mode 100644index 000000000..3cdd53483--- /dev/null+++ b/crates/tauri-plugin-global-shortcut/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "tauri-plugin-global-shortcut"+version = "1.0.0"+description = "Register global hotkeys listeners on your Tauri application."+edition = "2021"++[package.metadata.docs.rs]+rustc-args = ["--cfg", "docsrs"]+rustdoc-args = ["--cfg", "docsrs"]++[dependencies]+serde = { version = "1.0", features = ["derive"] }+serde_json = { version = "1.0" }+tauri = { version = "1.6.1" }+log = "0.4.22"+thiserror = "1.0.63"++global-hotkey = { version = "0.5", features = ["serde"] }diff --git a/crates/tauri-plugin-global-shortcut/guest-js/index.ts b/crates/tauri-plugin-global-shortcut/guest-js/index.tsnew file mode 100644index 000000000..12776a19c--- /dev/null+++ b/crates/tauri-plugin-global-shortcut/guest-js/index.ts@@ -0,0 +1,142 @@+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy+// SPDX-License-Identifier: Apache-2.0+// SPDX-License-Identifier: MIT++/**+ * Register global shortcuts.+ *+ * @module+ */++import { listen } from "@tauri-apps/api/event";+import { invoke } from "@tauri-apps/api/tauri";++export interface ShortcutEvent {+ shortcut: string;+ id: number;+ state: "Released" | "Pressed";+ callbackId: number;+}++export type ShortcutHandler = (event: ShortcutEvent) => void;++let idCounter = 0;+const listeners = new Map<number, ShortcutHandler>();++/**+ * Register a global shortcut or a list of shortcuts.+ *+ * The handler is called when any of the registered shortcuts are pressed by the user.+ *+ * If the shortcut is already taken by another application, the handler will not be triggered.+ * Make sure the shortcut is as unique as possible while still taking user experience into consideration.+ *+ * @example+ * ```typescript+ * import { register } from '@tauri-apps/plugin-global-shortcut';+ *+ * // register a single hotkey+ * await register('CommandOrControl+Shift+C', (event) => {+ * if (event.state === "Pressed") {+ * console.log('Shortcut triggered');+ * }+ * });+ *+ * // or register multiple hotkeys at once+ * await register(['CommandOrControl+Shift+C', 'Alt+A'], (event) => {+ * console.log(`Shortcut ${event.shortcut} triggered`);+ * });+ * ```+ *+ * @param shortcut Shortcut definition, modifiers and key separated by "+" e.g. CmdOrControl+Q+ * @param handler Shortcut handler callback - takes the triggered shortcut as argument+ *+ * @since 2.0.0+ */+async function register(+ shortcuts: string | string[],+ handler: ShortcutHandler+): Promise<void> {+ const id = idCounter++;++ // minor memory leak until tauri 2.0++ listeners.set(id, handler);++ await listen<ShortcutEvent>("shortcut_event", (event) => {+ if (event.payload.callbackId === id) {+ const listener = listeners.get(id);+ if (listener) {+ console.log(event);+ console.log(listeners);+ listener(event.payload);+ }+ }+ });++ return await invoke("plugin:global-shortcut|register", {+ shortcuts: Array.isArray(shortcuts) ? shortcuts : [shortcuts],+ callbackId: id,+ });+}++/**+ * Unregister a global shortcut or a list of shortcuts.+ *+ * @example+ * ```typescript+ * import { unregister } from '@tauri-apps/plugin-global-shortcut';+ *+ * // unregister a single hotkey+ * await unregister('CmdOrControl+Space');+ *+ * // or unregister multiple hotkeys at the same time+ * await unregister(['CmdOrControl+Space', 'Alt+A']);+ * ```+ *+ * @param shortcut shortcut definition (modifiers and key separated by "+" e.g. CmdOrControl+Q), also accepts a list of shortcuts+ *+ * @since 2.0.0+ */+async function unregister(shortcuts: string | string[]): Promise<void> {+ return await invoke("plugin:global-shortcut|unregister", {+ shortcuts: Array.isArray(shortcuts) ? shortcuts : [shortcuts],+ });+}++/**+ * Unregister all global shortcuts.+ *+ * @example+ * ```typescript+ * import { unregisterAll } from '@tauri-apps/plugin-global-shortcut';+ * await unregisterAll();+ * ```+ * @since 2.0.0+ */+async function unregisterAll(): Promise<void> {+ return await invoke("plugin:global-shortcut|unregister_all", {});+}++/**+ * Determines whether the given shortcut is registered by this application or not.+ *+ * If the shortcut is registered by another application, it will still return `false`.+ *+ * @example+ * ```typescript+ * import { isRegistered } from '@tauri-apps/plugin-global-shortcut';+ * const isRegistered = await isRegistered('CommandOrControl+P');+ * ```+ *+ * @param shortcut shortcut definition, modifiers and key separated by "+" e.g. CmdOrControl+Q+ *+ * @since 2.0.0+ */+async function isRegistered(shortcut: string): Promise<boolean> {+ return await invoke("plugin:global-shortcut|is_registered", {+ shortcut,+ });+}++export { register, unregister, unregisterAll, isRegistered };diff --git a/crates/tauri-plugin-global-shortcut/package.json b/crates/tauri-plugin-global-shortcut/package.jsonnew file mode 100644index 000000000..ff5f31a24--- /dev/null+++ b/crates/tauri-plugin-global-shortcut/package.json@@ -0,0 +1,18 @@+{+ "name": "@tauri-apps/plugin-global-shortcut",+ "version": "1.0.0",+ "license": "MIT or APACHE-2.0",+ "authors": [+ "Tauri Programme within The Commons Conservancy"+ ],+ "repository": "https://github.com/tauri-apps/plugins-workspace",+ "type": "module",+ "types": "./dist/index.d.ts",+ "main": "./dist/index.js",+ "scripts": {+ "postinstall": "tsc"+ },+ "dependencies": {+ "@tauri-apps/api": "1.6.0"+ }+}diff --git a/crates/tauri-plugin-global-shortcut/src/error.rs b/crates/tauri-plugin-global-shortcut/src/error.rsnew file mode 100644index 000000000..a1e366a79--- /dev/null+++ b/crates/tauri-plugin-global-shortcut/src/error.rs@@ -0,0 +1,32 @@+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy+// SPDX-License-Identifier: Apache-2.0+// SPDX-License-Identifier: MIT++use serde::{Serialize, Serializer};++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error("{0}")]+ GlobalHotkey(String),+}++impl Serialize for Error {+ fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>+ where+ S: Serializer,+ {+ serializer.serialize_str(self.to_string().as_ref())+ }+}++impl From<global_hotkey::Error> for Error {+ fn from(value: global_hotkey::Error) -> Self {+ Self::GlobalHotkey(value.to_string())+ }+}++impl From<global_hotkey::hotkey::HotKeyParseError> for Error {+ fn from(value: global_hotkey::hotkey::HotKeyParseError) -> Self {+ Self::GlobalHotkey(value.to_string())+ }+}diff --git a/crates/tauri-plugin-global-shortcut/src/lib.rs b/crates/tauri-plugin-global-shortcut/src/lib.rsnew file mode 100644index 000000000..7380f8ab9--- /dev/null+++ b/crates/tauri-plugin-global-shortcut/src/lib.rs@@ -0,0 +1,419 @@+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy+// SPDX-License-Identifier: Apache-2.0+// SPDX-License-Identifier: MIT++//! [](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/global-shortcut)+//!+//! Register global shortcuts.+//!+//! - Supported platforms: Windows, Linux and macOS.++#![doc(+ html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",+ html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"+)]+#![cfg(not(any(target_os = "android", target_os = "ios")))]++use std::{+ collections::HashMap,+ str::FromStr,+ sync::{Arc, Mutex},+};++pub use global_hotkey::{+ hotkey::{Code, HotKey as Shortcut, Modifiers},+ GlobalHotKeyEvent as ShortcutEvent, HotKeyState as ShortcutState,+};+use global_hotkey::{GlobalHotKeyEvent, GlobalHotKeyManager};+use serde::Serialize;+use tauri::{+ plugin::{Builder as PluginBuilder, TauriPlugin},+ AppHandle, Manager, Runtime, State,+};++mod error;++pub use error::Error;+type Result<T> = std::result::Result<T, Error>;++type HotKeyId = u32;+type HandlerFn<R> = Box<dyn Fn(&AppHandle<R>, &Shortcut, ShortcutEvent) + Send + Sync + 'static>;++pub struct ShortcutWrapper(Shortcut);++impl From<Shortcut> for ShortcutWrapper {+ fn from(value: Shortcut) -> Self {+ Self(value)+ }+}++impl TryFrom<&str> for ShortcutWrapper {+ type Error = global_hotkey::hotkey::HotKeyParseError;+ fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {+ Shortcut::from_str(value).map(ShortcutWrapper)+ }+}++struct RegisteredShortcut<R: Runtime> {+ shortcut: Shortcut,+ handler: Option<Arc<HandlerFn<R>>>,+}++pub struct GlobalShortcut<R: Runtime> {+ #[allow(dead_code)]+ app: AppHandle<R>,+ manager: GlobalHotKeyManager,+ shortcuts: Arc<Mutex<HashMap<HotKeyId, RegisteredShortcut<R>>>>,+}++impl<R: Runtime> GlobalShortcut<R> {+ fn register_internal<F: Fn(&AppHandle<R>, &Shortcut, ShortcutEvent) + Send + Sync + 'static>(+ &self,+ shortcut: Shortcut,+ handler: Option<F>,+ ) -> Result<()> {+ let id = shortcut.id();+ let handler = handler.map(|h| Arc::new(Box::new(h) as HandlerFn<R>));++ self.manager.register(shortcut)?;+ self.shortcuts+ .lock()+ .unwrap()+ .insert(id, RegisteredShortcut { shortcut, handler });+ Ok(())+ }++ fn register_multiple_internal<S, F>(&self, shortcuts: S, handler: Option<F>) -> Result<()>+ where+ S: IntoIterator<Item = Shortcut>,+ F: Fn(&AppHandle<R>, &Shortcut, ShortcutEvent) + Send + Sync + 'static,+ {+ let handler = handler.map(|h| Arc::new(Box::new(h) as HandlerFn<R>));++ let hotkeys = shortcuts.into_iter().collect::<Vec<_>>();++ let mut shortcuts = self.shortcuts.lock().unwrap();+ for shortcut in hotkeys {+ self.manager.register(shortcut)?;+ shortcuts.insert(+ shortcut.id(),+ RegisteredShortcut {+ shortcut,+ handler: handler.clone(),+ },+ );+ dbg!(&shortcut);+ }++ Ok(())+ }+}++impl<R: Runtime> GlobalShortcut<R> {+ /// Register a shortcut.+ pub fn register<S>(&self, shortcut: S) -> Result<()>+ where+ S: TryInto<ShortcutWrapper>,+ S::Error: std::error::Error,+ {+ self.register_internal(+ try_into_shortcut(shortcut)?,+ None::<fn(&AppHandle<R>, &Shortcut, ShortcutEvent)>,+ )+ }++ /// Register a shortcut with a handler.+ pub fn on_shortcut<S, F>(&self, shortcut: S, handler: F) -> Result<()>+ where+ S: TryInto<ShortcutWrapper>,+ S::Error: std::error::Error,+ F: Fn(&AppHandle<R>, &Shortcut, ShortcutEvent) + Send + Sync + 'static,+ {+ self.register_internal(try_into_shortcut(shortcut)?, Some(handler))+ }++ /// Register multiple shortcuts.+ pub fn register_multiple<S, T>(&self, shortcuts: S) -> Result<()>+ where+ S: IntoIterator<Item = T>,+ T: TryInto<ShortcutWrapper>,+ T::Error: std::error::Error,+ {+ let mut s = Vec::new();+ for shortcut in shortcuts {+ s.push(try_into_shortcut(shortcut)?);+ }+ self.register_multiple_internal(s, None::<fn(&AppHandle<R>, &Shortcut, ShortcutEvent)>)+ }++ /// Register multiple shortcuts with a handler.+ pub fn on_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, ShortcutEvent) + Send + Sync + 'static,+ {+ let mut s = Vec::new();+ for shortcut in shortcuts {+ s.push(try_into_shortcut(shortcut)?);+ }+ self.register_multiple_internal(s, Some(handler))+ }++ /// Unregister a shortcut+ pub fn unregister<S: TryInto<ShortcutWrapper>>(&self, shortcut: S) -> Result<()>+ where+ S::Error: std::error::Error,+ {+ let shortcut = try_into_shortcut(shortcut)?;+ self.manager.unregister(shortcut)?;+ self.shortcuts.lock().unwrap().remove(&shortcut.id());+ Ok(())+ }++ /// Unregister multiple shortcuts.+ pub fn unregister_multiple<T: TryInto<ShortcutWrapper>, S: IntoIterator<Item = T>>(+ &self,+ shortcuts: S,+ ) -> Result<()>+ where+ T::Error: std::error::Error,+ {+ let mut s = Vec::new();+ for shortcut in shortcuts {+ s.push(try_into_shortcut(shortcut)?);+ }++ self.manager.unregister_all(&s)?;++ let mut shortcuts = self.shortcuts.lock().unwrap();+ for s in s {+ shortcuts.remove(&s.id());+ }++ Ok(())+ }++ /// Unregister all registered shortcuts.+ pub fn unregister_all(&self) -> Result<()> {+ let mut shortcuts = self.shortcuts.lock().unwrap();+ let hotkeys = std::mem::take(&mut *shortcuts);+ let hotkeys = hotkeys.values().map(|s| s.shortcut).collect::<Vec<_>>();+ self.manager+ .unregister_all(hotkeys.as_slice())+ .map_err(Into::into)+ }++ /// Determines whether the given shortcut is registered by this application or not.+ ///+ /// If the shortcut is registered by another application, it will still return `false`.+ pub fn is_registered<S: TryInto<ShortcutWrapper>>(&self, shortcut: S) -> bool+ where+ S::Error: std::error::Error,+ {+ if let Ok(shortcut) = try_into_shortcut(shortcut) {+ self.shortcuts.lock().unwrap().contains_key(&shortcut.id())+ } else {+ false+ }+ }+}++pub trait GlobalShortcutExt<R: Runtime> {+ fn global_shortcut(&self) -> &GlobalShortcut<R>;+}++impl<R: Runtime, T: Manager<R>> GlobalShortcutExt<R> for T {+ fn global_shortcut(&self) -> &GlobalShortcut<R> {+ self.state::<GlobalShortcut<R>>().inner()+ }+}++fn parse_shortcut<S: AsRef<str>>(shortcut: S) -> Result<Shortcut> {+ shortcut.as_ref().parse().map_err(Into::into)+}++fn try_into_shortcut<S: TryInto<ShortcutWrapper>>(shortcut: S) -> Result<Shortcut>+where+ S::Error: std::error::Error,+{+ shortcut+ .try_into()+ .map(|s| s.0)+ .map_err(|e| Error::GlobalHotkey(e.to_string()))+}++#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+struct ShortcutJsEvent {+ shortcut: String,+ id: u32,+ state: ShortcutState,+ callback_id: i32,+}++#[tauri::command]+fn register<R: Runtime>(+ _app: AppHandle<R>,+ global_shortcut: State<'_, GlobalShortcut<R>>,+ shortcuts: Vec<String>,+ callback_id: i32,+) -> Result<()> {+ let mut hotkeys = Vec::new();++ let mut shortcut_map = HashMap::new();+ for shortcut in shortcuts {+ let hotkey = parse_shortcut(&shortcut)?;+ shortcut_map.insert(hotkey.id(), shortcut);+ hotkeys.push(hotkey);+ }++ global_shortcut.register_multiple_internal(+ hotkeys,+ Some(+ move |app: &AppHandle<R>, shortcut: &Shortcut, e: ShortcutEvent| {+ dbg!(&shortcut);+ let js_event = ShortcutJsEvent {+ id: e.id,+ state: e.state,+ shortcut: shortcut.into_string(),+ callback_id,+ };+ app.emit_all("shortcut_event", js_event).ok();+ },+ ),+ )+}++#[tauri::command]+fn unregister<R: Runtime>(+ _app: AppHandle<R>,+ global_shortcut: State<'_, GlobalShortcut<R>>,+ shortcuts: Vec<String>,+) -> Result<()> {+ let mut hotkeys = Vec::new();+ for shortcut in shortcuts {+ hotkeys.push(parse_shortcut(&shortcut)?);+ }+ global_shortcut.unregister_multiple(hotkeys)+}++#[tauri::command]+fn unregister_all<R: Runtime>(+ _app: AppHandle<R>,+ global_shortcut: State<'_, GlobalShortcut<R>>,+) -> Result<()> {+ global_shortcut.unregister_all()+}++#[tauri::command]+fn is_registered<R: Runtime>(+ _app: AppHandle<R>,+ global_shortcut: State<'_, GlobalShortcut<R>>,+ shortcut: String,+) -> Result<bool> {+ Ok(global_shortcut.is_registered(parse_shortcut(shortcut)?))+}++pub struct Builder<R: Runtime> {+ shortcuts: Vec<Shortcut>,+ handler: Option<HandlerFn<R>>,+}++impl<R: Runtime> Default for Builder<R> {+ fn default() -> Self {+ Self {+ shortcuts: Vec::new(),+ handler: Default::default(),+ }+ }+}++impl<R: Runtime> Builder<R> {+ pub fn new() -> Self {+ 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, ShortcutEvent) + Send + Sync + 'static>(+ mut self,+ handler: F,+ ) -> Self {+ self.handler.replace(Box::new(handler));+ self+ }++ pub fn build(self) -> TauriPlugin<R> {+ let handler = self.handler;+ let shortcuts = self.shortcuts;+ PluginBuilder::new("global-shortcut")+ .invoke_handler(tauri::generate_handler![+ register,+ unregister,+ unregister_all,+ is_registered,+ ])+ .setup(move |app| {+ let manager = GlobalHotKeyManager::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 app_handle = app.clone();+ GlobalHotKeyEvent::set_event_handler(Some(move |e: GlobalHotKeyEvent| {+ if let Some(shortcut) = shortcuts_.lock().unwrap().get(&e.id) {+ if let Some(handler) = &shortcut.handler {+ handler(&app_handle, &shortcut.shortcut, e);+ }+ if let Some(handler) = &handler {+ handler(&app_handle, &shortcut.shortcut, e);+ }+ }+ }));++ app.manage(GlobalShortcut {+ app: app.clone(),+ manager,+ shortcuts,+ });+ Ok(())+ })+ .build()+ }+}diff --git a/crates/tauri-plugin-global-shortcut/tsconfig.json b/crates/tauri-plugin-global-shortcut/tsconfig.jsonnew file mode 100644index 000000000..6f1b7b08a--- /dev/null+++ b/crates/tauri-plugin-global-shortcut/tsconfig.json@@ -0,0 +1,9 @@+{+ "compilerOptions": {+ "outDir": "dist",+ "declaration": true,+ "lib": ["DOM", "ES2020"],+ "module": "ESNext",+ "moduleResolution": "node"+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 770f10744..5cfe20382 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -41,9 +41,15 @@ importers:'@sentry/nextjs':specifier: ^7.105.0version: 7.105.0([email protected](@babel/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ '@tanstack/react-query':+ specifier: ^5.51.11+ version: 5.51.11([email protected])'@tauri-apps/api':specifier: ^1.5.3version: 1.5.3+ '@tauri-apps/plugin-global-shortcut':+ specifier: workspace:*+ version: link:../../crates/tauri-plugin-global-shortcut'@tensorflow-models/body-pix':specifier: ^2.2.1version: 2.2.1(@tensorflow/[email protected](@tensorflow/[email protected]))(@tensorflow/[email protected](@tensorflow/[email protected]))(@tensorflow/[email protected])@@ -490,6 +496,12 @@ importers:specifier: ^5.3.2version: 5.3.3+ crates/tauri-plugin-global-shortcut:+ dependencies:+ '@tauri-apps/api':+ specifier: 1.6.0+ version: 1.6.0+packages/config:dependencies:'@vitejs/plugin-react':@@ -3510,6 +3522,10 @@ packages:resolution: {integrity: sha512-zxnDjHHKjOsrIzZm6nO5Xapb/BxqUq1tc7cGkFXsFkGTsSWgCPH1D8mm0XS9weJY2OaR73I3k3S+b7eSzJDfqA==}engines: {node: '>= 14.6.0', npm: '>= 6.6.0', yarn: '>= 1.19.1'}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-rqI++FWClU5I2UBp4HXFvl+sBWkdigBkxnpJDQUWttNyG7IZP4FwQGhTNL5EOw0vI8i6eSAJ5frLqO7n7jbJdg==}+ engines: {node: '>= 14.6.0', npm: '>= 6.6.0', yarn: '>= 1.19.1'}+'@tauri-apps/[email protected]':resolution: {integrity: sha512-2NLSglDb5VfvTbMtmOKWyD+oaL/e8Z/ZZGovHtUFyUSFRabdXc6cZOlcD1BhFvYkHqm+TqGaz5qtPR5UbqDs8A==}engines: {node: '>= 10'}@@ -12341,6 +12357,8 @@ snapshots:'@tauri-apps/[email protected]': {}+ '@tauri-apps/[email protected]': {}+'@tauri-apps/[email protected]':optional: truediff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 3ff5faaaf..69a453bc9 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,3 +1,4 @@packages:- "apps/*"- "packages/*"+ - "crates/tauri-plugin-*"