Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Re-implement system tray menu

Ilya15081bcdef3e
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 0443081c8..67c8e167d 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -1,8 +1,6 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
-use regex::Regex;
use sentry_tracing::EventFilter;
-use serde::{Deserialize, Serialize};
use specta_typescript::Typescript;
use std::path::PathBuf;
use std::sync::Arc;
@@ -10,7 +8,7 @@ use std::vec;
use tauri::Manager;
use tauri_plugin_decorum::WebviewWindowExt;
use tauri_specta::{collect_commands, Builder};
-use tokio::sync::{oneshot, Mutex};
+use tokio::sync::Mutex;
use tracing::Level;
use tracing_subscriber::prelude::*;
@@ -128,48 +126,6 @@ fn main() {
}
};
- #[derive(serde::Deserialize, PartialEq)]
- enum DeviceKind {
- #[serde(alias = "videoinput")]
- Video,
- #[serde(alias = "audioinput")]
- Audio,
- }
-
- #[derive(serde::Deserialize)]
- #[serde(rename_all = "camelCase")]
- struct MediaDevice {
- id: String,
- kind: DeviceKind,
- label: String,
- }
-
- // fn create_tray_menu(submenus: Option<Vec<SystemTraySubmenu>>) -> SystemTrayMenu {
- // let mut tray_menu = SystemTrayMenu::new();
-
- // if let Some(items) = submenus {
- // for submenu in items {
- // tray_menu = tray_menu.add_submenu(submenu);
- // }
- // tray_menu = tray_menu.add_native_item(tauri::SystemTrayMenuItem::Separator);
- // }
-
- // tray_menu
- // .add_item(CustomMenuItem::new("show-window".to_string(), "Show Cap"))
- // .add_item(CustomMenuItem::new("quit".to_string(), "Quit").accelerator("CmdOrControl+Q"))
- // }
-
- // #[cfg(target_os = "macos")]
- // let tray = SystemTray::new()
- // .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");
-
let specta_builder = Builder::<tauri::Wry>::new().commands(collect_commands![
start_dual_recording,
stop_all_recordings,
@@ -260,150 +216,9 @@ fn main() {
// }
// }
// });
-
- // let tray_handle = app.tray_handle();
- // app.listen_global("media-devices-set", move |event| {
- // #[derive(serde::Deserialize)]
- // #[serde(rename_all = "camelCase")]
- // struct Payload {
- // media_devices: Vec<MediaDevice>,
- // selected_video: Option<MediaDevice>,
- // selected_audio: Option<MediaDevice>,
- // }
- // let payload: Payload = serde_json
- // ::from_str(event.payload().expect("Error wile openning event payload"))
- // .expect("Error while deserializing media devices from event payload");
-
- // fn create_submenu_items(
- // devices: &Vec<MediaDevice>,
- // selected_device: &Option<MediaDevice>,
- // kind: DeviceKind
- // ) -> SystemTrayMenu {
- // let id_prefix = if kind == DeviceKind::Video { "video" } else { "audio" };
- // let mut none_item = CustomMenuItem::new(
- // format!("in_{}_none", id_prefix),
- // "None"
- // );
- // if selected_device.is_none() {
- // none_item = none_item.selected();
- // }
- // let initial = SystemTrayMenu::new().add_item(none_item);
- // devices
- // .iter()
- // .filter(|device| device.kind == kind)
- // .fold(initial, |tray_items, device| {
- // let mut menu_item = CustomMenuItem::new(
- // format!("in_{}_{}", id_prefix, device.id),
- // &device.label
- // );
-
- // if let Some(selected) = selected_device {
- // if selected.label == device.label {
- // menu_item = menu_item.selected();
- // }
- // }
-
- // tray_items.add_item(menu_item)
- // })
- // }
-
- // let new_menu = create_tray_menu(
- // Some(
- // vec![
- // SystemTraySubmenu::new(
- // "Camera",
- // create_submenu_items(
- // &payload.media_devices,
- // &payload.selected_video,
- // DeviceKind::Video
- // )
- // ),
- // SystemTraySubmenu::new(
- // "Microphone",
- // create_submenu_items(
- // &payload.media_devices,
- // &payload.selected_audio,
- // DeviceKind::Audio
- // )
- // )
- // ]
- // )
- // );
-
- // tray_handle.set_menu(new_menu).expect("Error while updating the tray menu items");
- // });
-
Ok(())
})
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
- // .system_tray(tray)
- // .on_system_tray_event(move |app, event| match event {
- // SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
- // "show-window" => {
- // let window = app
- // .get_window("main")
- // .expect("Error while trying to get the main window.");
- // window
- // .show()
- // .expect("Error while trying to show main window");
- // if !window.is_focused().unwrap_or(false) {
- // window
- // .set_focus()
- // .expect("Error while trying to set focus on main window");
- // }
- // if window.is_minimized().unwrap_or(false) {
- // window
- // .unminimize()
- // .expect("Error while trying to unminimize main window");
- // }
- // }
- // "quit" => {
- // app.exit(0);
- // }
- // item_id => {
- // if !item_id.starts_with("in") {
- // return;
- // }
- // let pattern = Regex::new(r"^in_(video|audio)_")
- // .expect("Failed to create regex for checking tray item events");
- // if pattern.is_match(item_id) {
- // #[derive(Clone, serde::Serialize)]
- // struct SetDevicePayload {
- // #[serde(rename(serialize = "type"))]
- // device_type: String,
- // id: Option<String>,
- // }
- // let device_id = pattern.replace_all(item_id, "").into_owned();
- // let kind = if item_id.contains("video") {
- // "videoinput"
- // } else {
- // "audioinput"
- // };
- // app.emit_all(
- // "tray-set-device-id",
- // SetDevicePayload {
- // device_type: kind.to_string(),
- // id: if device_id == "none" {
- // None
- // } else {
- // Some(device_id)
- // },
- // },
- // )
- // .expect("Failed to emit tray set media device event to windows");
- // }
- // }
- // },
- // SystemTrayEvent::LeftClick {
- // position: _,
- // size: _,
- // ..
- // } => {
- // app.emit_all("tray-on-left-click", Some(()))
- // .expect("Failed to emit tray left click event to windows");
- // }
- // _ => {}
- // })
.run(context)
.expect("Error while running tauri application");
}
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index 5207bc53d..f4ee6be9a 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -61,6 +61,8 @@
},
"macOSPrivateApi": false,
"trayIcon": {
+ "id": "cap_main",
+ "menuOnLeftClick": false,
"iconPath": "icons/tray-default-icon.png",
"iconAsTemplate": true
}
diff --git a/apps/desktop/src/app/page.tsx b/apps/desktop/src/app/page.tsx
index bf9a9a9f2..26d38d74d 100644
--- a/apps/desktop/src/app/page.tsx
+++ b/apps/desktop/src/app/page.tsx
@@ -12,6 +12,7 @@ import { getVersion } from "@tauri-apps/api/app";
import toast from "react-hot-toast";
import { authFetch } from "@/utils/auth/helpers";
import { commands } from "@/utils/commands";
+import { setTrayMenu } from "@/utils/tray";
export const dynamic = "force-static";
@@ -52,6 +53,10 @@ export default function CameraPage() {
checkVersion();
}, []);
+ useEffect(() => {
+ setTrayMenu();
+ }, []);
+
useEffect(() => {
const checkPermissions = setInterval(() => {
const updatedPermissions = getPermissions();
diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
index d4558fcba..1ff13a843 100644
--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
@@ -14,7 +14,8 @@ import {
enumerateAndStoreDevices,
initializeCameraWindow,
} from "./utils";
-import { closeWebview } from "../commands";
+import { commands } from "../commands";
+import { setTrayMenu } from "../tray";
export type DeviceKind = "videoinput" | "audioinput";
export interface Device {
@@ -138,7 +139,7 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
setSelectedVideoDevice(device);
localStorage.setItem("selected-videoinput", device?.label || "none");
if (!device) {
- closeWebview("camera");
+ commands.closeWebview("camera");
} else if (!previous && device) {
initializeCameraWindow();
}
@@ -155,8 +156,6 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
useEffect(() => {
let unlistenFnChangeDevice: any;
- let unlistenFnTraySetDevice: any;
-
const setupListeners = async () => {
try {
unlistenFnChangeDevice = await listen<{
@@ -171,41 +170,16 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
} catch (error) {
console.error("Error setting up change-device listener:", error);
}
-
- try {
- unlistenFnTraySetDevice = await listen<{
- type: string;
- id: string | null;
- }>("tray-set-device-id", (event) => {
- const id = event.payload.id;
- const kind = event.payload.type as DeviceKind;
- const newDevice = id
- ? devices.find((device) => kind === device.kind && id === device.id)
- : null;
- updateSelectedDevice(kind, newDevice);
- });
- } catch (error) {
- console.error("Error setting up tray-set-device-id listener:", error);
- }
};
setupListeners();
if (devices.length !== 0) {
- emit("media-devices-set", {
- mediaDevices: [...(devices as Omit<Device, "index">[])],
- selectedVideo: selectedVideoDevice,
- selectedAudio: selectedAudioDevice,
- });
+ setTrayMenu(devices, selectedAudioDevice, selectedVideoDevice);
}
-
+
return () => {
- if (unlistenFnChangeDevice) {
- unlistenFnChangeDevice();
- }
- if (unlistenFnTraySetDevice) {
- unlistenFnTraySetDevice();
- }
+ unlistenFnChangeDevice?.();
};
}, [selectedVideoDevice, selectedAudioDevice]);
diff --git a/apps/desktop/src/utils/tray.ts b/apps/desktop/src/utils/tray.ts
new file mode 100644
index 000000000..1707049f7
--- /dev/null
+++ b/apps/desktop/src/utils/tray.ts
@@ -0,0 +1,78 @@
+import { CheckMenuItem, Menu, PredefinedMenuItem, Submenu } from "@tauri-apps/api/menu";
+import { TrayIcon } from "@tauri-apps/api/tray";
+import { Device, DeviceKind } from "./recording/MediaDeviceContext";
+import { emit } from "@tauri-apps/api/event";
+
+// TODO: Improve this. This might not work properly on Linux.
+export const setTrayMenu = async (
+ devices: Device[] = [],
+ selectedAudio: Device | null = null,
+ selectedVideo: Device | null = null,
+) => {
+ const tray = await TrayIcon.getById("cap_main");
+ console.log(`Setting tray with devices: ${devices.length} for tray: ${tray}`);
+
+ if (!tray) {
+ console.error("No system tray found.");
+ return;
+ }
+
+ const createDeviceSubmenu = async (kind: DeviceKind, selected: Device | null) => {
+ const filteredDevices = devices.filter((device) => device.kind === kind);
+ const menuItems: CheckMenuItem[] = [];
+
+ if (filteredDevices.length === 0) {
+ menuItems.push(await CheckMenuItem.new({ text: "No devices found.", enabled: false }));
+ } else {
+ menuItems.push(await CheckMenuItem.new({
+ id: `none_${kind}`,
+ text: "None",
+ checked: selected === null,
+ action: (_) => selectDevice(kind, null),
+ }));
+
+ menuItems.push(...await Promise.all(
+ filteredDevices.map(async (device) =>
+ await CheckMenuItem.new({
+ id: device.id,
+ text: device.label || `Unknown ${kind}`,
+ checked: device?.index === selected?.index,
+ action: (_) => selectDevice(kind, device),
+ })
+ )
+ ));
+ }
+
+ return menuItems;
+ };
+
+ tray.setMenu(await Menu.new({
+ items: [
+ await Submenu.new({
+ id: "audio_submenu",
+ text: "Microphone",
+ items: [...await createDeviceSubmenu("audioinput", selectedAudio)]
+ }),
+ await Submenu.new({
+ id: "video_submenu",
+ text: "Camera",
+ items: [...await createDeviceSubmenu("videoinput", selectedVideo)]
+ }),
+ await PredefinedMenuItem.new({
+ item: "Separator"
+ }),
+ await PredefinedMenuItem.new({
+ item: "ShowAll"
+ }),
+ await PredefinedMenuItem.new({
+ text: "Quit",
+ item: "Quit"
+ }),
+ ]
+ }));
+};
+
+const selectDevice = (kind: DeviceKind, device: Device | null) =>
+ emit("change-device", { type: kind, device: device }).catch((error) =>
+ console.log("Failed to emit change-device event:", error)
+ );