Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
connect hotkeys
Brendan Allanf9466b91921f
diff --git a/Cargo.lock b/Cargo.lockindex 03192aa7b..862c879b0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1425,6 +1425,7 @@ dependencies = ["ffmpeg-sidecar 1.1.0 (git+https://github.com/CapSoftware/ffmpeg-sidecar?branch=main)","futures","futures-intrusive",+ "global-hotkey","image 0.25.2","indexmap 2.5.0","mp4",@@ -1448,6 +1449,7 @@ dependencies = ["tauri-plugin-decorum","tauri-plugin-dialog","tauri-plugin-fs",+ "tauri-plugin-global-shortcut","tauri-plugin-oauth","tauri-plugin-os","tauri-plugin-process",@@ -2301,6 +2303,24 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"+[[package]]+name = "global-hotkey"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b436093d1598b05e3b7fddc097b2bad32763f53a1beb25ab6f9718c6a60acd09"+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 = "glow"version = "0.13.1"@@ -6019,6 +6039,21 @@ dependencies = ["uuid",]+[[package]]+name = "tauri-plugin-global-shortcut"+version = "2.0.0-rc.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a596240a2ee580534e5d348b80b34ce4aa9c0219eaa63b393571d29201e9ea80"+dependencies = [+ "global-hotkey",+ "log",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "thiserror",+]+[[package]]name = "tauri-plugin-oauth"version = "0.0.0-alpha.0"diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex fb07e2a59..ee86011cd 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -31,6 +31,7 @@ tauri-plugin-decorum = "1.0.0"tauri-plugin-dialog = "2.0.0-rc.0"tauri-plugin-updater = "2.0.0-rc.0"tauri-plugin-oauth = { git = "https://github.com/FabianLars/tauri-plugin-oauth", branch = "v2" }+tauri-plugin-global-shortcut = "2.0.0-rc.0"tauri-specta = { version = "=2.0.0-rc.14", features = ["derive", "typescript"] }serde = { version = "1", features = ["derive"] }@@ -71,6 +72,7 @@ cap-rendering = { path = "../../../crates/rendering" }cap-ffmpeg = { path = "../../../crates/ffmpeg" }reqwest = { version = "0.12.7", features = ["json", "stream", "multipart"] }dotenvy_macro = "0.15.7"+global-hotkey = "0.5.5"[target.'cfg(target_os = "macos")'.dependencies]core-graphics = "0.24.0"diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rsindex 31417ab15..12a8fea93 100644--- a/apps/desktop/src-tauri/src/camera.rs+++ b/apps/desktop/src-tauri/src/camera.rs@@ -12,7 +12,7 @@ pub const WINDOW_LABEL: &str = "camera";const CAMERA_ROUTE: &str = "/camera";const WINDOW_SIZE: f64 = 230.0 * 2.0;-#[tauri::command]+#[tauri::command(async)]#[specta::specta]pub fn create_camera_window(app: AppHandle) {if let Some(window) = app.get_webview_window(WINDOW_LABEL) {diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rsnew file mode 100644index 000000000..a0f4391d2--- /dev/null+++ b/apps/desktop/src-tauri/src/hotkeys.rs@@ -0,0 +1,137 @@+use std::collections::HashMap;++use global_hotkey::HotKeyState;+use serde::{Deserialize, Serialize};+use specta::Type;+use std::sync::Mutex;+use tauri::{AppHandle, Manager, Wry};+use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut};+use tauri_plugin_store::{with_store, StoreCollection};++#[derive(Serialize, Deserialize, Type, PartialEq, Clone, Copy)]+pub struct Hotkey {+ #[specta(type = String)]+ code: Code,+ meta: bool,+ ctrl: bool,+ alt: bool,+ shift: bool,+}++impl Hotkey {+ fn to_shortcut(&self) -> Shortcut {+ let mut modifiers = Modifiers::empty();++ if self.meta {+ modifiers |= Modifiers::META;+ }+ if self.ctrl {+ modifiers |= Modifiers::CONTROL;+ }+ if self.alt {+ modifiers |= Modifiers::ALT;+ }+ if self.shift {+ modifiers |= Modifiers::SHIFT;+ }++ Shortcut::new(Some(modifiers), self.code)+ }+}++#[derive(Serialize, Deserialize, Type, PartialEq, Eq, Hash)]+#[serde(rename_all = "camelCase")]+pub enum HotkeyAction {+ StartRecording,+ StopRecording,+}++#[derive(Serialize, Deserialize, Type, Default)]+pub struct HotkeysStore {+ hotkeys: HashMap<HotkeyAction, Hotkey>,+}++impl HotkeysStore {+ pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {+ let stores = app+ .try_state::<StoreCollection<Wry>>()+ .ok_or("Store not found")?;+ with_store(app.clone(), stores, "store", |store| {+ let Some(store) = store.get("hotkeys").cloned() else {+ return Ok(None);+ };++ Ok(serde_json::from_value(store)?)+ })+ .map_err(|e| e.to_string())+ }+}++pub type HotkeysState = Mutex<HotkeysStore>;++pub fn init(app: &AppHandle) {+ app.plugin(+ tauri_plugin_global_shortcut::Builder::new()+ .with_handler(|app, shortcut, event| {+ if !matches!(event.state(), HotKeyState::Pressed) {+ return;+ }++ let state = app.state::<HotkeysState>();+ let store = state.lock().unwrap();++ for (action, hotkey) in &store.hotkeys {+ if &hotkey.to_shortcut() == shortcut {+ match action {+ HotkeyAction::StartRecording => {+ println!("start recording");+ }+ HotkeyAction::StopRecording => {+ println!("stop recording");+ }+ }+ }+ }+ })+ .build(),+ )+ .unwrap();++ let store = HotkeysStore::get(app).unwrap().unwrap_or_default();++ let global_shortcut = app.global_shortcut();++ for hotkey in store.hotkeys.values() {+ global_shortcut.register(hotkey.to_shortcut()).ok();+ }++ app.manage(Mutex::new(store));+}++#[tauri::command(async)]+#[specta::specta]+pub fn set_hotkey(app: AppHandle, action: HotkeyAction, hotkey: Option<Hotkey>) -> Result<(), ()> {+ let global_shortcut = app.global_shortcut();+ let state = app.state::<HotkeysState>();+ let mut store = state.lock().unwrap();++ let prev = store.hotkeys.get(&action).cloned();++ if let Some(hotkey) = hotkey {+ store.hotkeys.insert(action, hotkey);+ } else {+ store.hotkeys.remove(&action);+ }++ if let Some(prev) = prev {+ if !store.hotkeys.values().any(|h| h == &prev) {+ global_shortcut.unregister(prev.to_shortcut()).ok();+ }+ }++ if let Some(hotkey) = hotkey {+ global_shortcut.register(hotkey.to_shortcut()).ok();+ }++ Ok(())+}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex bb8e579fc..40f325106 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -4,6 +4,7 @@ mod camera;mod display;mod editor;mod editor_instance;+mod hotkeys;mod macos;mod permissions;mod playback;@@ -22,7 +23,6 @@ use display::{list_capture_windows, Bounds, CaptureTarget, FPS};use editor_instance::{EditorInstance, EditorState, FRAMES_WS_PATH};use image::{ImageBuffer, Rgba};use mp4::Mp4Reader;-use nix::libc::pthread_introspection_hook_t;use num_traits::ToBytes;use objc2_app_kit::NSScreenSaverWindowLevel;use project_recordings::ProjectRecordings;@@ -944,7 +944,7 @@ async fn remove_fake_window(const PREV_RECORDINGS_WINDOW: &str = "prev-recordings";// must not be async bc of panel-#[tauri::command]+#[tauri::command(async)]#[specta::specta]fn show_previous_recordings_window(app: AppHandle) {if let Some(window) = app.get_webview_window(PREV_RECORDINGS_WINDOW) {@@ -987,26 +987,33 @@ fn show_previous_recordings_window(app: AppHandle) {return;};- use tauri_nspanel::cocoa::appkit::NSWindowCollectionBehavior;- use tauri_nspanel::WebviewWindowExt as NSPanelWebviewWindowExt;use tauri_plugin_decorum::WebviewWindowExt;-window.make_transparent().ok();- let panel = window.to_panel().unwrap();- panel.set_level(NSMainMenuWindowLevel);+ app.run_on_main_thread({+ let window = window.clone();+ move || {+ use tauri_nspanel::cocoa::appkit::NSWindowCollectionBehavior;+ use tauri_nspanel::WebviewWindowExt as NSPanelWebviewWindowExt;- panel.set_collection_behaviour(- NSWindowCollectionBehavior::NSWindowCollectionBehaviorTransient- | NSWindowCollectionBehavior::NSWindowCollectionBehaviorMoveToActiveSpace- | NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary- | NSWindowCollectionBehavior::NSWindowCollectionBehaviorIgnoresCycle,- );+ let panel = window.to_panel().unwrap();- // seems like this doesn't work properly -_-- #[allow(non_upper_case_globals)]- const NSWindowStyleMaskNonActivatingPanel: i32 = 1 << 7;- panel.set_style_mask(NSWindowStyleMaskNonActivatingPanel);+ panel.set_level(NSMainMenuWindowLevel);++ panel.set_collection_behaviour(+ NSWindowCollectionBehavior::NSWindowCollectionBehaviorTransient+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorMoveToActiveSpace+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorIgnoresCycle,+ );++ // seems like this doesn't work properly -_-+ #[allow(non_upper_case_globals)]+ const NSWindowStyleMaskNonActivatingPanel: i32 = 1 << 7;+ panel.set_style_mask(NSWindowStyleMaskNonActivatingPanel);+ }+ })+ .ok();tokio::spawn(async move {let state = app.state::<FakeWindowBounds>();@@ -1393,7 +1400,8 @@ pub fn run() {upload_rendered_video,get_recording_meta,open_feedback_window,- open_settings_window+ open_settings_window,+ hotkeys::set_hotkey]).events(tauri_specta::collect_events![RecordingOptionsChanged,@@ -1408,7 +1416,8 @@ pub fn run() {RequestStopRecording,]).ty::<ProjectConfiguration>()- .ty::<AuthStore>();+ .ty::<AuthStore>()+ .ty::<hotkeys::HotkeysStore>();#[cfg(debug_assertions)] // <- Only export on non-release buildsspecta_builder@@ -1430,6 +1439,7 @@ pub fn run() {.invoke_handler(specta_builder.invoke_handler()).setup(move |app| {specta_builder.mount_events(app);+ hotkeys::init(app.handle());let app_handle = app.handle().clone();diff --git a/apps/desktop/src-tauri/src/permissions.rs b/apps/desktop/src-tauri/src/permissions.rsindex 3ac81ed6c..4e7d4e0d6 100644--- a/apps/desktop/src-tauri/src/permissions.rs+++ b/apps/desktop/src-tauri/src/permissions.rs@@ -12,7 +12,7 @@ pub enum OSPermission {Microphone,}-#[tauri::command]+#[tauri::command(async)]#[specta::specta]pub fn open_permission_settings(permission: OSPermission) {#[cfg(target_os = "macos")]@@ -107,7 +107,7 @@ impl OSPermissionsCheck {}}-#[tauri::command]+#[tauri::command(async)]#[specta::specta]pub fn do_permissions_check(initial_check: bool) -> OSPermissionsCheck {#[cfg(target_os = "macos")]@@ -150,7 +150,7 @@ pub fn check_av_permission(media_type: AVMediaType) -> OSPermissionStatus {}}-#[tauri::command]+#[tauri::command(async)]#[specta::specta]pub fn open_permissions_window(app: &impl Manager<Wry>) {if let Some(window) = app.get_webview_window("permissions") {diff --git a/apps/desktop/src/routes/(main)/index.tsx b/apps/desktop/src/routes/(main)/index.tsxindex 4056066ba..80268fef4 100644--- a/apps/desktop/src/routes/(main)/index.tsx+++ b/apps/desktop/src/routes/(main)/index.tsx@@ -114,12 +114,12 @@ export default function () {</div><div class="flex items-center justify-between pb-[0.25rem]"><IconCapLogoFull class="w-[90px] h-auto" />- {/*<button+ <buttontype="button"onClick={() => commands.openSettingsWindow()}><IconCapSettings class="text-gray-400 hover:text-gray-500" />- </button>*/}+ </button></div><KSelect<CaptureWindow | null>options={windows.data ?? []}diff --git a/apps/desktop/src/routes/settings.tsx b/apps/desktop/src/routes/settings.tsxindex 6d802a4b5..9bfd82783 100644--- a/apps/desktop/src/routes/settings.tsx+++ b/apps/desktop/src/routes/settings.tsx@@ -1,4 +1,5 @@-import type { RouteSectionProps } from "@solidjs/router";+import { A, type RouteSectionProps } from "@solidjs/router";+import { For } from "solid-js";import Header from "~/components/Header";@@ -8,10 +9,19 @@ export default function (props: RouteSectionProps) {<Header /><div class="h-full flex flex-row divide-x divide-gray-200 text-[0.875rem] leading-[1.25rem]"><ul class="min-w-[12rem] h-full p-[0.625rem]">- <li class="bg-gray-50 border border-gray-200 rounded-lg h-[2rem] px-[0.375rem] flex flex-row items-center gap-[0.375rem]">- <IconCapHotkeys class="size-[1.25rem]" />- <span>Shortcuts</span>- </li>+ <For each={[{ href: "hotkeys", name: "Shortcuts" }]}>+ {(item) => (+ <li>+ <A+ href={item.href}+ class="bg-gray-50 border border-gray-200 rounded-lg h-[2rem] px-[0.375rem] flex flex-row items-center gap-[0.375rem]"+ >+ <IconCapHotkeys class="size-[1.25rem]" />+ <span>{item.name}</span>+ </A>+ </li>+ )}+ </For></ul><div class="flex-1 bg-gray-50">{props.children}</div></div>diff --git a/apps/desktop/src/routes/settings/hotkeys.tsx b/apps/desktop/src/routes/settings/hotkeys.tsxindex f0ef72541..7cf5da9d1 100644--- a/apps/desktop/src/routes/settings/hotkeys.tsx+++ b/apps/desktop/src/routes/settings/hotkeys.tsx@@ -1,23 +1,170 @@import { Button } from "@cap/ui-solid";-import { For } from "solid-js";+import { createEventListener } from "@solid-primitives/event-listener";+import {+ Index,+ Match,+ Show,+ Switch,+ batch,+ createEffect,+ createResource,+ createSignal,+} from "solid-js";+import { createStore } from "solid-js/store";+import { hotkeysStore } from "~/store";++import {+ type Hotkey,+ type HotkeyAction,+ type HotkeysStore,+ commands,+} from "~/utils/tauri";++const ACTION_TEXT: Record<HotkeyAction, string> = {+ startRecording: "Start Recording",+ stopRecording: "Stop Recording",+};export default function () {+ const [store] = createResource(() => hotkeysStore.get());++ return (+ <Show+ when={(() => {+ const s = store();+ if (s === undefined) return;+ return [s];+ })()}+ >+ {(store) => <Inner store={store()[0]} />}+ </Show>+ );+}++function Inner(props: { store: HotkeysStore | null }) {+ const [hotkeys, setHotkeys] = createStore<{+ [K in HotkeyAction]?: Hotkey;+ }>(props.store?.hotkeys ?? {});++ createEffect(() => {+ // biome-ignore lint/suspicious/noExplicitAny: specta#283+ hotkeysStore.set({ hotkeys: hotkeys as any });+ });++ const [listening, setListening] = createSignal<{+ action: HotkeyAction;+ prev?: Hotkey;+ }>();++ createEventListener(window, "keydown", (e) => {+ const data = {+ code: e.code,+ ctrl: e.ctrlKey,+ shift: e.shiftKey,+ alt: e.altKey,+ meta: e.metaKey,+ };++ if (+ !(+ (data.code >= "KeyA" && data.code <= "KeyZ") ||+ data.code.startsWith("F")+ )+ )+ return;++ const l = listening();+ if (l) {+ e.preventDefault();++ setHotkeys(l.action, data);+ }+ });+return (<div class="flex flex-col w-full h-full divide-y divide-gray-200"><ul class="flex-1 p-[0.625rem] flex flex-col gap-[0.5rem] w-full">- <For each={["Start Recording", "Stop Recording"]}>- {(item) => (- <li class="w-full flex flex-row justify-between items-center">- <span>{item}</span>- <button- type="button"- class="w-[9rem] h-[2rem] border border-gray-200 rounded-lg text-gray-400"- >- Ctrl + Alt + R- </button>- </li>- )}- </For>+ <Index+ each={["startRecording", "stopRecording"] as Array<HotkeyAction>}+ >+ {(item) => {+ createEventListener(window, "click", () => {+ if (listening()?.action !== item()) return;++ console.log(listening());+ batch(() => {+ setHotkeys(item(), listening()?.prev);+ setListening();+ });+ });++ return (+ <li class="w-full flex flex-row justify-between items-center">+ <span>{ACTION_TEXT[item()]}</span>+ <div class="w-[9rem] h-[2rem]">+ <Switch>+ <Match when={listening()?.action === item()}>+ <div class="border border-blue-300 rounded-lg text-gray-500 w-full h-full bg-gray-100 flex flex-row items-center justify-between px-[0.375rem]">+ <Show when={hotkeys[item()]} fallback="Listening">+ {(binding) => <HotkeyText binding={binding()} />}+ </Show>+ <div class="flex flex-row items-center gap-[0.125rem]">+ <Show when={hotkeys[item()]}>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();++ setListening();+ commands.setHotkey(+ item(),+ hotkeys[item()] ?? null+ );+ }}+ >+ <IconCapCircleCheck class="size-[1.25rem] text-blue-300" />+ </button>+ </Show>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ batch(() => {+ setListening();+ // biome-ignore lint/style/noNonNullAssertion: store+ setHotkeys(item(), undefined!);+ commands.setHotkey(item(), null);+ });+ }}+ >+ <IconCapCircleX class="size-[1.25rem] text-gray-400" />+ </button>+ </div>+ </div>+ </Match>+ <Match when={listening()?.action !== item()}>+ <button+ type="button"+ class="border border-gray-200 rounded-lg text-gray-400 w-full h-full"+ onClick={(e) => {+ e.stopPropagation();+ setListening({+ action: item(),+ prev: hotkeys[item()],+ });+ }}+ >+ <Show when={hotkeys[item()]} fallback="None">+ {(binding) => <HotkeyText binding={binding()} />}+ </Show>+ </button>+ </Match>+ </Switch>+ </div>+ </li>+ );+ }}+ </Index></ul><div class="flex flex-row-reverse p-[1rem]"><Button variant="secondary">Restore Defaults</Button>@@ -25,3 +172,19 @@ export default function () {</div>);}++function HotkeyText(props: { binding: Hotkey }) {+ return (+ <span class="space-x-0.5">+ {props.binding.meta && <span>⌘</span>}+ {props.binding.ctrl && <span>⌃</span>}+ {props.binding.alt && <span>⌥</span>}+ {props.binding.shift && <span>⇧</span>}+ <span>+ {props.binding.code.startsWith("Key")+ ? props.binding.code[3]+ : props.binding.code}+ </span>+ </span>+ );+}diff --git a/apps/desktop/src/store.ts b/apps/desktop/src/store.tsindex cbcc4125c..754aa1ed5 100644--- a/apps/desktop/src/store.ts+++ b/apps/desktop/src/store.ts@@ -1,6 +1,10 @@import { Store } from "@tauri-apps/plugin-store";-import type { AuthStore, ProjectConfiguration } from "~/utils/tauri";+import type {+ AuthStore,+ ProjectConfiguration,+ HotkeysStore,+} from "~/utils/tauri";const store = new Store("store");@@ -31,3 +35,11 @@ export const authStore = {listen: (fn: (data: AuthStore | null) => void) =>store.onKeyChange<AuthStore>("presets", fn),};++export const hotkeysStore = {+ get: () => store.get<HotkeysStore>("hotkeys"),+ set: async (value: HotkeysStore) => {+ await store.set("hotkeys", value);+ await store.save();+ },+};diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 0e42e7875..15a7c11a6 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -176,6 +176,14 @@ async openFeedbackWindow() : Promise<void> {},async openSettingsWindow() : Promise<void> {await TAURI_INVOKE("open_settings_window");+},+async setHotkey(action: HotkeyAction, hotkey: Hotkey | null) : Promise<Result<null, null>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("set_hotkey", { action, hotkey }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}}}@@ -234,7 +242,10 @@ export type CursorType = "pointer" | "circle"export type Display = { path: string }export type DisplaySource = { variant: "screen" } | { variant: "window"; bounds: Bounds }export type EditorStateChanged = { playhead_position: number }+export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }+export type HotkeyAction = "startRecording" | "stopRecording"export type HotkeysConfiguration = { show: boolean }+export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }export type InProgressRecording = { recordingDir: string; displaySource: DisplaySource }export type JsonValue<T> = [T]export type NewRecordingAdded = { path: string }