Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Polish, sync frontend picker with tray picker, refactors of relevant areas

Ilyab5f3975c4a4a
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index b5e399abd..91bb5c6da 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -170,15 +170,11 @@ fn main() {
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct MediaDevice {
- // index: i8,
- #[serde(rename(deserialize="deviceId"))]
id: String,
kind: DeviceKind,
label: String
}
- // let mut media_devices: LinkedList<MediaDevice> = LinkedList::new();
-
fn create_tray_menu(submenus: Option<Vec<SystemTraySubmenu>>) -> SystemTrayMenu {
let mut tray_menu = SystemTrayMenu::new();
@@ -247,25 +243,35 @@ fn main() {
#[serde(rename_all = "camelCase")]
struct Payload {
media_devices: Vec<MediaDevice>,
- selected_video: MediaDevice,
- selected_audio: 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: &MediaDevice, kind: DeviceKind) -> SystemTrayMenu {
+ 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(SystemTrayMenu::new(), |mut tray_items, device| {
- let item_id_prefix = if kind == DeviceKind::Video { "video" } else { "audio" };
- let mut menu_item = CustomMenuItem::new(format!("in_{}_{}", item_id_prefix, device.id), &device.label);
-
- if selected_device.label == device.label {
- menu_item = menu_item.selected();
+ .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 = tray_items.add_item(menu_item);
- tray_items
+
+ tray_items.add_item(menu_item)
})
}
@@ -308,23 +314,26 @@ fn main() {
app.exit(0);
}
item_id => {
- let pattern = Regex::new(r"^in_(video|audio)_").unwrap();
+ 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) {
- let device_id = pattern.replace_all(item_id, "").into_owned();
- let kind = if item_id.contains("video") {
- "videoinput"
- } else {
- "audioinput"
- };
#[derive(Clone, serde::Serialize)]
- struct Payload {
+ struct SetDevicePayload {
#[serde(rename(serialize="type"))]
device_type: String,
- id: String
+ id: Option<String>
}
- app.emit_all("tray_set_device", Payload { device_type: kind.to_string(), id: device_id }).expect("Failed to emit tray set media device event to windows");
+ 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");
}
}
},
diff --git a/apps/desktop/src/components/windows/Camera.tsx b/apps/desktop/src/components/windows/Camera.tsx
index 833d1d2bc..a0de0e25b 100644
--- a/apps/desktop/src/components/windows/Camera.tsx
+++ b/apps/desktop/src/components/windows/Camera.tsx
@@ -15,7 +15,7 @@ export const Camera = () => {
const video = videoRef.current;
const constraints = {
video: {
- deviceId: selectedVideoDevice.deviceId,
+ deviceId: selectedVideoDevice.id,
},
};
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index b3f4b5b83..33a7dce00 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect } from "react";
-import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";
+import { Device, useMediaDevices } from "@/utils/recording/MediaDeviceContext";
import { Video } from "@/components/icons/Video";
import { Microphone } from "@/components/icons/Microphone";
import { Screen } from "@/components/icons/Screen";
@@ -43,52 +43,49 @@ export const Recorder = () => {
const [canStopRecording, setCanStopRecording] = useState(false);
const [hasStartedRecording, setHasStartedRecording] = useState(false);
- const handleContextClick = async (option: string) => {
+ const handleContextClick = async (option: "video" | "audio") => {
const { showMenu } = await import("tauri-plugin-context-menu");
+ const deviceKind = option === "video" ? "videoinput" : "audioinput";
+ const isSelected = (device: Device | null) => {
+ if (device === null) {
+ return deviceKind === "videoinput"
+ ? selectedVideoDevice === null
+ : selectedAudioDevice === null;
+ }
+
+ return deviceKind === "videoinput"
+ ? device.index === selectedVideoDevice?.index
+ : device.index === selectedAudioDevice?.index;
+ }
+ const select = async (device: Device | null) => {
+ // if (isSelected(device)) {
+ // return
+ // }
+ emit("change-device", { type: deviceKind, device: device }).catch((error) => {
+ console.log("Failed to emit change-device event:", error);
+ });
+ }
- const filteredDevices = devices
- .filter((device) =>
- option === "video"
- ? device.kind === "videoinput"
- : device.kind === "audioinput"
- )
- .map((device) => ({
- label: device.label,
- disabled:
- option === "video"
- ? device.index === selectedVideoDevice?.index
- : device.index === selectedAudioDevice?.index,
- event: async () => {
- try {
- await emit("change-device", { type: option, device });
- } catch (error) {
- console.error("Failed to emit change-device event:", error);
- }
- },
- }));
-
- filteredDevices.push({
- label: "None",
- disabled: false,
- event: async () => {
- try {
- await emit("change-device", {
- type: option,
- device: {
- index: -1,
- label: "None",
- kind: option === "video" ? "videoinput" : "audioinput",
- },
- });
- } catch (error) {
- console.error("Failed to emit change-device event:", error);
- }
- },
- });
+ const devicesOfKind = devices.filter((device) => device.kind === deviceKind);
+ const menuItems = [
+ {
+ label: "None",
+ checked: isSelected(null),
+ event: async() => select(null)
+ },
+ ...devicesOfKind.map((device) => (
+ {
+ label: device.label,
+ checked: isSelected(device),
+ event: async() => select(device)
+ }
+ ))
+ ]
+
await showMenu({
- items: [...filteredDevices],
- ...(filteredDevices.length === 0 && {
+ items: [...menuItems],
+ ...(devicesOfKind.length === 0 && {
items: [
{
label: "Nothing found.",
@@ -377,7 +374,7 @@ export const Recorder = () => {
width="full"
handler={() => handleContextClick("video")}
icon={<Video className="w-5 h-5" />}
- label={selectedVideoDevice?.label || "Video"}
+ label={devices.length === 0 ? "Video" : selectedVideoDevice?.label || "None"}
active={selectedVideoDevice !== null}
recordingOption={true}
optionName="Video"
@@ -386,7 +383,7 @@ export const Recorder = () => {
width="full"
handler={() => handleContextClick("audio")}
icon={<Microphone className="w-5 h-5" />}
- label={selectedAudioDevice?.label || "Mic"}
+ label={devices.length === 0 ? "Mic" : selectedAudioDevice?.label || "None"}
active={selectedAudioDevice !== null}
recordingOption={true}
optionName="Audio"
diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
index d6785119d..63c513898 100644
--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
@@ -15,23 +15,24 @@ import {
initializeCameraWindow,
} from "./utils";
-export interface Devices {
+export type DeviceKind = "videoinput" | "audioinput";
+export interface Device {
index: number;
+ id: string;
label: string;
- kind: "videoinput" | "audioinput";
- deviceId: string;
+ kind: DeviceKind;
}
export interface MediaDeviceContextData {
- selectedVideoDevice: Devices | null;
- setSelectedVideoDevice: React.Dispatch<React.SetStateAction<Devices | null>>;
- selectedAudioDevice: Devices | null;
- setSelectedAudioDevice: React.Dispatch<React.SetStateAction<Devices | null>>;
+ selectedVideoDevice: Device | null;
+ setSelectedVideoDevice: React.Dispatch<React.SetStateAction<Device | null>>;
+ selectedAudioDevice: Device | null;
+ setSelectedAudioDevice: React.Dispatch<React.SetStateAction<Device | null>>;
selectedDisplayType: "screen" | "window" | "area";
setSelectedDisplayType: React.Dispatch<
React.SetStateAction<"screen" | "window" | "area">
>;
- devices: Devices[];
+ devices: Device[];
getDevices: () => Promise<void>;
isRecording: boolean;
setIsRecording: React.Dispatch<React.SetStateAction<boolean>>;
@@ -47,13 +48,13 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
children,
}) => {
const [selectedVideoDevice, setSelectedVideoDevice] =
- useState<Devices | null>(null);
+ useState<Device | null>(null);
const [selectedAudioDevice, setSelectedAudioDevice] =
- useState<Devices | null>(null);
+ useState<Device | null>(null);
const [selectedDisplayType, setSelectedDisplayType] = useState<
"screen" | "window" | "area"
>("screen");
- const [devices, setDevices] = useState<Devices[]>([]);
+ const [devices, setDevices] = useState<Device[]>([]);
const [isRecording, setIsRecording] = useState(false);
const [startingRecording, setStartingRecording] = useState(false);
const getDevicesCalled = useRef(false);
@@ -69,14 +70,14 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
index: index,
label: device.label,
kind: "videoinput",
- deviceId: device.deviceId,
- })) as Devices[]),
+ id: device.deviceId,
+ })) as Device[]),
...(audioDevices.map((device: MediaDeviceInfo, index: number) => ({
index: index,
label: device.label,
kind: "audioinput",
- deviceId: device.deviceId,
- })) as Devices[]),
+ id: device.deviceId ? device.deviceId : device.label,
+ })) as Device[]),
];
setDevices(formattedDevices);
@@ -106,98 +107,77 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
}
}, []);
- const changeDevice = (type: "video" | "audio", device: Devices) => {
- console.log(`Change-device recieved, previous selected: audio: ${selectedAudioDevice?.index} vid: ${selectedVideoDevice?.index}`);
-
- if (type && device) {
- if (window.fathom !== undefined) {
- window.fathom.trackEvent(`${type}_device_change`);
- }
- if (type === "video") {
- import("@tauri-apps/api/window").then(({ WebviewWindow }) => {
- if (WebviewWindow.getByLabel("camera")) {
- WebviewWindow.getByLabel("camera").close();
- } else {
- initializeCameraWindow();
- }
- });
- if (selectedVideoDevice?.index !== device.index) {
- setSelectedVideoDevice(device);
+ const updateSelectedDevice = (type: DeviceKind, device: Device | null) => {
+ if (!type) {
+ return;
+ }
+ if (window.fathom !== undefined) {
+ window.fathom.trackEvent(`${type === "videoinput" ? "video" : "audio"}_device_change`);
+ }
+ if (type === "videoinput") {
+ import("@tauri-apps/api/window").then(({ WebviewWindow }) => {
+ if (WebviewWindow.getByLabel("camera")) {
+ WebviewWindow.getByLabel("camera").close();
+ } else if (type === "videoinput" && device) {
+ initializeCameraWindow();
}
+ });
+
+ if ((!device && selectedVideoDevice) || (selectedVideoDevice?.index !== device?.index)) {
+ setSelectedVideoDevice(device);
}
+ }
- if (type === "audio") {
- if (selectedAudioDevice?.index !== device.index) {
- setSelectedAudioDevice(device);
- }
+ if (type === "audioinput") {
+ if ((!device && selectedAudioDevice) || (selectedAudioDevice?.index !== device?.index)) {
+ setSelectedAudioDevice(device);
}
}
}
useEffect(() => {
- let unlistenChangeDevice: any;
- let unlistenTraySetDevice: any;
+ let unlistenFnChangeDevice: any;
+ let unlistenFnTraySetDevice: any;
- const setupChangeDeviceListener = async () => {
+ const setupListeners = async () => {
try {
- unlistenChangeDevice = await listen(
- "change-device",
- ({
- payload,
- }: {
- payload: { type: "video" | "audio"; device: Devices };
- }) => {
- changeDevice(payload.type, payload.device);
- }
- );
+ unlistenFnChangeDevice = await listen<{ type: string, device: Device | null }>("change-device", (event) => {
+ updateSelectedDevice(event.payload.type as DeviceKind, event.payload.device);
+ });
} catch (error) {
- console.error("Error setting up listener:", error);
+ console.error("Error setting up change-device listener:", error);
}
- };
-
- const createNonDevice = (kind: "videoinput" | "audioinput") => {
- return {
- index: -1,
- label: "None",
- kind: kind,
- deviceId: "none",
- } as Devices;
- }
-
- const setupTraySetDeviceListener = async () => {
- unlistenTraySetDevice = await listen<{type: string, id: string}>("tray_set_device", (event) => {
- const id = event.payload.id;
- const option = event.payload.type as "videoinput" | "audioinput";
- const newDevice = id === "none" ? createNonDevice(option) :
- devices.find((device) => option === device.kind && event.payload.id === device.deviceId);
-
- console.log(`Trying to set ${newDevice?.label} from ${newDevice?.kind === "videoinput" ? selectedVideoDevice?.label : selectedAudioDevice?.label}`)
- changeDevice(event.payload.type === "videoinput" ? "video" : "audio", newDevice);
- });
+ 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);
+ }
};
- setupChangeDeviceListener();
- setupTraySetDeviceListener();
+ setupListeners();
if (devices.length !== 0) {
emit("media-devices-set", {
mediaDevices: [
- createNonDevice("videoinput"),
- createNonDevice("audioinput"),
- ...(devices as Omit<Devices, 'index'>[])
+ ...(devices as Omit<Device, 'index'>[])
],
- selectedVideo: selectedVideoDevice?.label === "None" ? createNonDevice("videoinput") : selectedVideoDevice,
- selectedAudio: selectedAudioDevice?.label === "None" ? createNonDevice("audioinput") : selectedAudioDevice,
+ selectedVideo: selectedVideoDevice,
+ selectedAudio: selectedAudioDevice,
});
}
return () => {
- if (unlistenChangeDevice) {
- unlistenChangeDevice();
+ if (unlistenFnChangeDevice) {
+ unlistenFnChangeDevice();
}
- if (unlistenTraySetDevice) {
- unlistenTraySetDevice();
+ if (unlistenFnTraySetDevice) {
+ unlistenFnTraySetDevice();
}
};
}, [selectedVideoDevice, selectedAudioDevice]);
diff --git a/apps/desktop/src/utils/recording/utils.ts b/apps/desktop/src/utils/recording/utils.ts
index cea295f0b..384e21d30 100644
--- a/apps/desktop/src/utils/recording/utils.ts
+++ b/apps/desktop/src/utils/recording/utils.ts
@@ -13,10 +13,9 @@ export const enumerateAndStoreDevices = async () => {
const videoDevices = video.filter((device) => device.kind === "videoinput");
const audioDevices = audio.map((device) => {
return {
- deviceId: device,
- groupId: "",
- kind: "audioinput",
+ id: device,
label: device,
+ kind: "audioinput",
};
});