Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Refactor device and permission queries to use unified snapshot

Richie McIlroy1c7c56504270
diff --git a/apps/desktop/src-tauri/src/permissions.rs b/apps/desktop/src-tauri/src/permissions.rs
index 9e6ad00f2..29c2b6196 100644
--- a/apps/desktop/src-tauri/src/permissions.rs
+++ b/apps/desktop/src-tauri/src/permissions.rs
@@ -111,7 +111,7 @@ pub async fn request_permission(_permission: OSPermission) {
}
}
-#[derive(Serialize, Deserialize, Debug, specta::Type)]
+#[derive(Serialize, Deserialize, Debug, specta::Type, Clone)]
#[serde(rename_all = "camelCase")]
pub enum OSPermissionStatus {
// This platform does not require this permission
@@ -130,7 +130,7 @@ impl OSPermissionStatus {
}
}
-#[derive(Serialize, Deserialize, Debug, specta::Type)]
+#[derive(Serialize, Deserialize, Debug, specta::Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct OSPermissionsCheck {
pub screen_recording: OSPermissionStatus,
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 92cce11b7..474a70f07 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -50,6 +50,7 @@ use tracing::*;
use crate::camera::{CameraPreviewManager, CameraPreviewShape};
#[cfg(target_os = "macos")]
use crate::general_settings;
+use crate::permissions;
use crate::web_api::AuthedApiError;
use crate::{
App, CurrentRecordingChanged, FinalizingRecordings, MutableState, NewStudioRecordingAdded,
@@ -302,6 +303,9 @@ pub async fn list_capture_windows() -> Vec<CaptureWindow> {
#[tauri::command(async)]
#[specta::specta]
pub fn list_cameras() -> Vec<cap_camera::CameraInfo> {
+ if !permissions::do_permissions_check(false).camera.permitted() {
+ return vec![];
+ }
cap_camera::list_cameras().collect()
}
diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
index 6fc0bff1b..23f6e178a 100644
--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
@@ -33,16 +33,14 @@ import { Input } from "~/routes/editor/ui";
import { authStore, generalSettingsStore } from "~/store";
import { createSignInMutation } from "~/utils/auth";
import { createTauriEventListener } from "~/utils/createEventListener";
+import { createDevicesQuery } from "~/utils/devices";
import {
createCameraMutation,
createCurrentRecordingQuery,
createLicenseQuery,
- createPermissionsQuery,
- listAudioDevices,
listDisplaysWithThumbnails,
listRecordings,
listScreens,
- listVideoDevices,
listWindows,
listWindowsWithThumbnails,
} from "~/utils/queries";
@@ -664,9 +662,10 @@ function Page() {
});
});
- const cameras = useQuery(() => listVideoDevices);
- const mics = useQuery(() => listAudioDevices);
- const permissions = createPermissionsQuery();
+ const devices = createDevicesQuery();
+ const cameras = createMemo(() => devices.data?.cameras ?? []);
+ const mics = createMemo(() => devices.data?.microphones ?? []);
+ const permissions = createMemo(() => devices.data?.permissions);
const windowListSignature = createMemo(() =>
createWindowSignature(windows.data),
@@ -710,14 +709,16 @@ function Page() {
void displayTargets.refetch();
});
- cameras.promise.then((cameras) => {
- if (rawOptions.cameraID && findCamera(cameras, rawOptions.cameraID)) {
+ createEffect(() => {
+ const cameraList = cameras();
+ if (rawOptions.cameraID && findCamera(cameraList, rawOptions.cameraID)) {
setOptions("cameraLabel", null);
}
});
- mics.promise.then((mics) => {
- if (rawOptions.micName && !mics.includes(rawOptions.micName)) {
+ createEffect(() => {
+ const micList = mics();
+ if (rawOptions.micName && !micList.includes(rawOptions.micName)) {
setOptions("micName", null);
}
});
@@ -750,9 +751,9 @@ function Page() {
},
camera: () => {
if (!rawOptions.cameraID) return undefined;
- return findCamera(cameras.data || [], rawOptions.cameraID);
+ return findCamera(cameras(), rawOptions.cameraID);
},
- micName: () => mics.data?.find((name) => name === rawOptions.micName),
+ micName: () => mics().find((name) => name === rawOptions.micName),
target: (): ScreenCaptureTarget | undefined => {
switch (rawOptions.captureTarget.variant) {
case "display": {
@@ -830,24 +831,22 @@ function Page() {
const BaseControls = () => (
<div class="space-y-2">
<CameraSelect
- disabled={cameras.isPending}
- options={cameras.data ?? []}
+ disabled={devices.isPending}
+ options={cameras()}
value={options.camera() ?? null}
onChange={(c) => {
if (!c) setCamera.mutate(null);
else if (c.model_id) setCamera.mutate({ ModelID: c.model_id });
else setCamera.mutate({ DeviceID: c.device_id });
}}
- permissions={permissions.data}
+ permissions={permissions()}
/>
<MicrophoneSelect
- disabled={mics.isPending}
- options={mics.isPending ? [] : (mics.data ?? [])}
- value={
- mics.isPending ? rawOptions.micName : (options.micName() ?? null)
- }
+ disabled={devices.isPending}
+ options={mics()}
+ value={options.micName() ?? null}
onChange={(v) => setMicInput.mutate(v)}
- permissions={permissions.data}
+ permissions={permissions()}
/>
<SystemAudio />
</div>
diff --git a/apps/desktop/src/routes/target-select-overlay.tsx b/apps/desktop/src/routes/target-select-overlay.tsx
index 64f2e452c..638974c36 100644
--- a/apps/desktop/src/routes/target-select-overlay.tsx
+++ b/apps/desktop/src/routes/target-select-overlay.tsx
@@ -43,12 +43,11 @@ import {
import ModeSelect from "~/components/ModeSelect";
import SelectionHint from "~/components/selection-hint";
import { authStore, generalSettingsStore } from "~/store";
+import { createDevicesQuery } from "~/utils/devices";
import {
createCameraMutation,
createOptionsQuery,
createOrganizationsQuery,
- listAudioDevices,
- listVideoDevices,
} from "~/utils/queries";
import {
type CameraInfo,
@@ -836,8 +835,10 @@ function RecordingControls(props: {
const { setOptions, rawOptions } = useRecordingOptions();
const generalSetings = generalSettingsStore.createQuery();
- const cameras = useQuery(() => listVideoDevices);
- const mics = useQuery(() => listAudioDevices);
+ const devices = createDevicesQuery();
+ const cameras = createMemo(() => devices.data?.cameras ?? []);
+ const mics = createMemo(() => devices.data?.microphones ?? []);
+ const permissions = createMemo(() => devices.data?.permissions);
const setMicInput = createMutation(() => ({
mutationFn: async (name: string | null) => {
await commands.setMicInput(name);
@@ -848,14 +849,12 @@ function RecordingControls(props: {
const selectedCamera = createMemo(() => {
if (!rawOptions.cameraID) return null;
- return findCamera(cameras.data ?? [], rawOptions.cameraID) ?? null;
+ return findCamera(cameras(), rawOptions.cameraID) ?? null;
});
const selectedMicName = createMemo(() => {
if (!rawOptions.micName) return null;
- return (
- (mics.data ?? []).find((name) => name === rawOptions.micName) ?? null
- );
+ return mics().find((name) => name === rawOptions.micName) ?? null;
});
const menuModes = async () =>
@@ -935,7 +934,7 @@ function RecordingControls(props: {
return (
<>
- <div class="flex flex-col gap-2.5 items-stretch my-2.5 w-[22rem] max-w-[90vw]">
+ <div class="flex flex-col gap-2.5 items-stretch my-2.5 w-[26rem] max-w-[90vw]">
<div class="p-3 rounded-2xl border border-white/30 dark:border-white/10 bg-white/70 dark:bg-gray-2/70 shadow-lg backdrop-blur-xl">
<div class="flex gap-2.5 items-center">
<div
@@ -950,7 +949,7 @@ function RecordingControls(props: {
<div
data-inactive={rawOptions.mode === "instant" && !auth.data}
data-disabled={startDisabled()}
- class="flex flex-1 min-w-0 max-w-[15rem] overflow-hidden flex-row h-11 rounded-full text-white bg-gradient-to-r from-blue-10 via-blue-10 to-blue-11 dark:from-blue-9 dark:via-blue-9 dark:to-blue-10 group"
+ class="flex flex-1 min-w-0 max-w-[18rem] overflow-hidden flex-row h-11 rounded-full text-white bg-gradient-to-r from-blue-10 via-blue-10 to-blue-11 dark:from-blue-9 dark:via-blue-9 dark:to-blue-10 group"
onClick={async () => {
if (rawOptions.mode === "instant" && !auth.data) {
emit("start-sign-in");
@@ -1056,8 +1055,8 @@ function RecordingControls(props: {
<div class="p-3 rounded-2xl border border-white/30 dark:border-white/10 bg-white/70 dark:bg-gray-2/70 shadow-lg backdrop-blur-xl">
<div class="grid grid-cols-2 gap-2 w-full">
<CameraSelect
- disabled={cameras.isPending}
- options={cameras.data ?? []}
+ disabled={devices.isPending}
+ options={cameras()}
value={selectedCamera() ?? null}
onChange={(camera) => {
if (!camera) setCamera.mutate(null);
@@ -1065,16 +1064,14 @@ function RecordingControls(props: {
setCamera.mutate({ ModelID: camera.model_id });
else setCamera.mutate({ DeviceID: camera.device_id });
}}
+ permissions={permissions()}
/>
<MicrophoneSelect
- disabled={mics.isPending}
- options={mics.isPending ? [] : (mics.data ?? [])}
- value={
- mics.isPending
- ? (rawOptions.micName ?? null)
- : selectedMicName()
- }
+ disabled={devices.isPending}
+ options={mics()}
+ value={selectedMicName()}
onChange={(value) => setMicInput.mutate(value)}
+ permissions={permissions()}
/>
</div>
</div>
diff --git a/apps/desktop/src/utils/devices.ts b/apps/desktop/src/utils/devices.ts
new file mode 100644
index 000000000..a7da6163e
--- /dev/null
+++ b/apps/desktop/src/utils/devices.ts
@@ -0,0 +1,37 @@
+import { queryOptions, useQuery } from "@tanstack/solid-query";
+import { createEffect, onCleanup } from "solid-js";
+import {
+ type CameraInfo,
+ commands,
+ events,
+ type OSPermissionsCheck,
+} from "./tauri";
+
+export type DevicesSnapshot = {
+ cameras: CameraInfo[];
+ microphones: string[];
+ permissions: OSPermissionsCheck;
+};
+
+export const devicesSnapshot = queryOptions({
+ queryKey: ["devicesSnapshot"] as const,
+ queryFn: () => commands.getDevicesSnapshot(),
+ staleTime: 3_000,
+ refetchInterval: 5_000,
+});
+
+export function createDevicesQuery() {
+ const query = useQuery(() => devicesSnapshot);
+
+ createEffect(() => {
+ const unlisten = events.devicesUpdated.listen((event) => {
+ query.refetch();
+ });
+
+ onCleanup(() => {
+ unlisten.then((fn) => fn());
+ });
+ });
+
+ return query;
+}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 76ce95e4a..6894f1d24 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -149,6 +149,9 @@ async doPermissionsCheck(initialCheck: boolean) : Promise<OSPermissionsCheck> {
async requestPermission(permission: OSPermission) : Promise<void> {
await TAURI_INVOKE("request_permission", { permission });
},
+async getDevicesSnapshot() : Promise<DevicesUpdated> {
+ return await TAURI_INVOKE("get_devices_snapshot");
+},
async uploadExportedVideo(path: string, mode: UploadMode, channel: TAURI_CHANNEL<UploadProgress>, organizationId: string | null) : Promise<UploadResult> {
return await TAURI_INVOKE("upload_exported_video", { path, mode, channel, organizationId });
},
@@ -318,6 +321,7 @@ async discardIncompleteRecording(projectPath: string) : Promise<null> {
export const events = __makeEvents__<{
audioInputLevelChange: AudioInputLevelChange,
currentRecordingChanged: CurrentRecordingChanged,
+devicesUpdated: DevicesUpdated,
downloadProgress: DownloadProgress,
editorStateChanged: EditorStateChanged,
newNotification: NewNotification,
@@ -340,6 +344,7 @@ uploadProgressEvent: UploadProgressEvent
}>({
audioInputLevelChange: "audio-input-level-change",
currentRecordingChanged: "current-recording-changed",
+devicesUpdated: "devices-updated",
downloadProgress: "download-progress",
editorStateChanged: "editor-state-changed",
newNotification: "new-notification",
@@ -411,6 +416,7 @@ export type CursorMeta = { imagePath: string; hotspot: XY<number>; shape?: strin
export type CursorType = "auto" | "pointer" | "circle"
export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }
export type DeviceOrModelID = { DeviceID: string } | { ModelID: ModelIDType }
+export type DevicesUpdated = { cameras: CameraInfo[]; microphones: string[]; permissions: OSPermissionsCheck }
export type DisplayId = string
export type DisplayInformation = { name: string | null; physical_size: PhysicalSize | null; logical_size: LogicalSize | null; refresh_rate: string }
export type DownloadProgress = { progress: number; message: string }