Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

bring back No Camera option

Brendan Allan60cfb6bc3ad0
diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs
index f4da50798..a75e9e026 100644
--- a/apps/desktop/src-tauri/src/camera.rs
+++ b/apps/desktop/src-tauri/src/camera.rs
@@ -19,9 +19,7 @@ pub const WINDOW_LABEL: &str = "camera";
const CAMERA_ROUTE: &str = "/camera";
const WINDOW_SIZE: f64 = 230.0 * 2.0;
-#[tauri::command(async)]
-#[specta::specta]
-pub fn create_camera_window(app: AppHandle) {
+pub fn create_camera_window(app: AppHandle, ws_port: u16) {
if let Some(window) = app.get_webview_window(WINDOW_LABEL) {
window.set_focus().ok();
} else {
@@ -47,6 +45,12 @@ pub fn create_camera_window(app: AppHandle) {
100.0,
(monitor.size().height as f64) / monitor.scale_factor() - WINDOW_SIZE - 100.0,
)
+ .initialization_script(&format!(
+ "
+ window.__CAP__ = window.__CAP__ ?? {{}};
+ window.__CAP__.cameraWsPort = {ws_port};
+ ",
+ ))
.build()
.unwrap();
@@ -274,9 +278,7 @@ pub async fn create_camera_ws(frame_rx: watch::Receiver<Option<CameraFrame>>) ->
.route("/", get(ws_handler))
.with_state(Arc::new(Mutex::new(frame_rx)));
- let listener = tokio::net::TcpListener::bind("127.0.0.1:9182")
- .await
- .unwrap();
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
axum::serve(listener, router.into_make_service())
@@ -325,7 +327,7 @@ impl CameraFeed {
camera.open_stream().unwrap();
- setup_tx.send(camera.camera_format());
+ setup_tx.send(camera.camera_format()).unwrap();
loop {
if shutdown_rx.try_recv().is_ok() {
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index a63e2faf4..b0a99d9f7 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -46,6 +46,7 @@ use specta::Type;
use std::fs::File;
use std::io::BufWriter;
use std::io::{BufReader, Write};
+use std::sync::atomic::AtomicU16;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use std::{
collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,
@@ -92,6 +93,7 @@ pub struct App {
start_recording_options: RecordingOptions,
#[serde(skip)]
camera_tx: watch::Sender<camera::LatestFrame>,
+ camera_ws_port: u16,
#[serde(skip)]
camera_feed: Option<camera::CameraFeed>,
#[serde(skip)]
@@ -194,7 +196,7 @@ impl App {
}
None if new_options.camera_label.is_some() => {
println!("creating camera window");
- create_camera_window(self.handle.clone());
+ create_camera_window(self.handle.clone(), self.camera_ws_port);
}
_ => {}
}
@@ -1335,20 +1337,6 @@ fn close_previous_recordings_window(app: AppHandle) {
}
}
-fn on_recording_options_change(app: &AppHandle, options: &RecordingOptions) {
- match app.get_webview_window(camera::WINDOW_LABEL) {
- Some(window) if options.camera_label.is_none() => {
- window.close().ok();
- }
- None if options.camera_label.is_some() => {
- create_camera_window(app.clone());
- }
- _ => {}
- }
-
- RecordingOptionsChanged.emit(app).ok();
-}
-
#[tauri::command(async)]
#[specta::specta]
fn focus_captures_panel(app: AppHandle) {
@@ -2226,12 +2214,11 @@ async fn reset_microphone_permissions(app: AppHandle) -> Result<(), ()> {
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
-pub fn run() {
+pub async fn run() {
let specta_builder = tauri_specta::Builder::new()
.commands(tauri_specta::collect_commands![
get_recording_options,
set_recording_options,
- create_camera_window,
start_recording,
stop_recording,
pause_recording,
@@ -2312,6 +2299,9 @@ pub fn run() {
)
.expect("Failed to export typescript bindings");
+ let (camera_tx, camera_rx) = watch::channel(None);
+ let camera_ws_port = camera::create_camera_ws(camera_rx.clone()).await;
+
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.plugin(tauri_nspanel::init())
@@ -2348,13 +2338,10 @@ pub fn run() {
permissions::open_permissions_window(app_handle.clone());
}
- let (camera_tx, camera_rx) = watch::channel(None);
-
- tokio::spawn(camera::create_camera_ws(camera_rx.clone()));
-
app.manage(Arc::new(RwLock::new(App {
handle: app_handle.clone(),
camera_tx,
+ camera_ws_port,
camera_feed: None,
start_recording_options: RecordingOptions {
capture_target: CaptureTarget::Screen,
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 3b09b6188..6d742f68d 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -3,5 +3,5 @@
#[tokio::main]
async fn main() {
- desktop_solid_lib::run()
+ desktop_solid_lib::run().await
}
diff --git a/apps/desktop/src/routes/(window-chrome)/index.tsx b/apps/desktop/src/routes/(window-chrome)/index.tsx
index d42c986eb..1050c8725 100644
--- a/apps/desktop/src/routes/(window-chrome)/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/index.tsx
@@ -9,6 +9,7 @@ import {
Show,
type ValidComponent,
createEffect,
+ createMemo,
createResource,
createSignal,
onMount,
@@ -90,13 +91,14 @@ export default function () {
createUpdateCheck();
- const [changelogState, setChangelogState] = createStore({
- hasUpdate: false,
- lastOpenedVersion: localStorage.getItem("lastOpenedChangelogVersion") || "",
- changelogClicked: JSON.parse(
- localStorage.getItem("changelogClicked") || "false"
- ),
- });
+ const [changelogState, setChangelogState] = makePersisted(
+ createStore({
+ hasUpdate: false,
+ lastOpenedVersion: "",
+ changelogClicked: false,
+ }),
+ { name: "changelogState" }
+ );
const [currentVersion] = createResource(() => getVersion());
@@ -138,8 +140,6 @@ export default function () {
lastOpenedVersion: version,
changelogClicked: true,
});
- localStorage.setItem("lastOpenedChangelogVersion", version);
- localStorage.setItem("changelogClicked", "true");
}
};
@@ -161,6 +161,7 @@ export default function () {
} else if (type === "microphone") {
await commands.resetMicrophonePermissions();
}
+ await commands.requestPermission(type);
// Refresh permissions after request
await permissions.refetch();
} catch (error) {
@@ -168,27 +169,6 @@ export default function () {
}
};
- const handleCameraChange = async (item: string | null) => {
- console.log({ item });
- if (!item && permissions?.data?.camera !== "granted") {
- return requestPermission("camera");
- }
-
- if (!options.data) return;
-
- if (!item) {
- await commands.setRecordingOptions({
- ...options.data,
- cameraLabel: null,
- });
- } else {
- await commands.setRecordingOptions({
- ...options.data,
- cameraLabel: item,
- });
- }
- };
-
const handleMicrophoneChange = async (
item: { name: string; deviceId: string } | null
) => {
@@ -337,71 +317,124 @@ export default function () {
</KSelect>
<div class="flex flex-col gap-[0.25rem] items-stretch">
<label class="text-gray-400 text-[0.875rem]">Camera</label>
- <KSelect<string>
- options={videoDevices}
- placeholder="No Camera"
- value={options.data?.cameraLabel}
- disabled={isRecording()}
- onChange={handleCameraChange}
- itemComponent={(props) => (
- <MenuItem<typeof KSelect.Item> as={KSelect.Item} item={props.item}>
- <KSelect.ItemLabel class="flex-1">
- {props.item.rawValue}
- </KSelect.ItemLabel>
- </MenuItem>
- )}
- >
- <KSelect.Trigger
- class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect"
- onClick={(e) => {
- if (permissions?.data?.camera !== "granted") {
- requestPermission("camera");
+ <Show when>
+ {(_) => {
+ type Option = { isCamera: boolean; name: string };
+
+ const onChange = async (item: Option | null) => {
+ if (!item && permissions?.data?.camera !== "granted") {
+ return requestPermission("camera");
}
- }}
- >
- <IconCapCamera class="text-gray-400 size-[1.25rem]" />
- <KSelect.Value<string> class="flex-1 text-left truncate">
- {(state) => <span>{state.selectedOption()}</span>}
- </KSelect.Value>
- <button
- type="button"
- class={cx(
- "px-[0.375rem] rounded-full text-[0.75rem]",
- options.data?.cameraLabel
- ? "bg-blue-50 text-blue-300"
- : "bg-red-50 text-red-300"
- )}
- onClick={(e) => {
- e.stopPropagation();
- if (permissions?.data?.camera !== "granted") {
- return requestPermission("camera");
- }
- if (!options.data?.cameraLabel) return;
- commands.setRecordingOptions({
+
+ if (!options.data) return;
+
+ if (!item || !item.isCamera) {
+ await commands.setRecordingOptions({
...options.data,
cameraLabel: null,
});
- }}
- >
- {permissions?.data?.camera !== "granted"
- ? "Request Permission"
- : options.data?.cameraLabel
- ? "On"
- : "Off"}
- </button>
- </KSelect.Trigger>
- <KSelect.Portal>
- <PopperContent<typeof KSelect.Content>
- as={KSelect.Content}
- class={topLeftAnimateClasses}
- >
- <MenuItemList<typeof KSelect.Listbox>
- class="max-h-36 overflow-y-auto"
- as={KSelect.Listbox}
- />
- </PopperContent>
- </KSelect.Portal>
- </KSelect>
+ } else {
+ await commands.setRecordingOptions({
+ ...options.data,
+ cameraLabel: item.name,
+ });
+ }
+ };
+ const selectOptions = createMemo(() => [
+ { name: "No Camera", isCamera: false },
+ ...videoDevices.map((d) => ({ isCamera: true, name: d })),
+ ]);
+
+ const value = () =>
+ selectOptions()?.find(
+ (o) => o.name === options.data?.cameraLabel
+ ) ?? null;
+
+ return (
+ <KSelect<Option>
+ options={selectOptions()}
+ optionValue="name"
+ optionTextValue="name"
+ placeholder="No Camera"
+ value={value()}
+ disabled={isRecording()}
+ onChange={onChange}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {props.item.rawValue.name}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger
+ class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect"
+ onClick={(e) => {
+ if (permissions?.data?.camera !== "granted") {
+ requestPermission("camera");
+ }
+ }}
+ >
+ <IconCapCamera class="text-gray-400 size-[1.25rem]" />
+ <KSelect.Value<Option> class="flex-1 text-left truncate">
+ {(state) => <span>{state.selectedOption().name}</span>}
+ </KSelect.Value>
+ <button
+ type="button"
+ class={cx(
+ "px-[0.375rem] rounded-full text-[0.75rem]",
+ options.data?.cameraLabel
+ ? "bg-blue-50 text-blue-300"
+ : "bg-red-50 text-red-300"
+ )}
+ onPointerDown={(e) => {
+ const permission = permissions?.data?.camera;
+
+ if (
+ permission !== "granted" &&
+ permission !== "notNeeded"
+ ) {
+ e.stopPropagation();
+ }
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (permissions?.data?.camera !== "granted") {
+ console.log("requesting permission");
+ return requestPermission("camera");
+ }
+ if (!options.data?.cameraLabel) return;
+ commands.setRecordingOptions({
+ ...options.data,
+ cameraLabel: null,
+ });
+ }}
+ >
+ {permissions?.data?.camera !== "granted"
+ ? "Request Permission"
+ : options.data?.cameraLabel
+ ? "On"
+ : "Off"}
+ </button>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={topLeftAnimateClasses}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="max-h-36 overflow-y-auto"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ );
+ }}
+ </Show>
</div>
<div class="flex flex-col gap-[0.25rem] items-stretch">
<label class="text-gray-400">Microphone</label>
@@ -532,6 +565,7 @@ export default function () {
import * as dialog from "@tauri-apps/plugin-dialog";
import * as updater from "@tauri-apps/plugin-updater";
+import { makePersisted } from "@solid-primitives/storage";
let hasChecked = false;
function createUpdateCheck() {
diff --git a/apps/desktop/src/routes/camera.tsx b/apps/desktop/src/routes/camera.tsx
index 943e21a8d..32b1ed8d9 100644
--- a/apps/desktop/src/routes/camera.tsx
+++ b/apps/desktop/src/routes/camera.tsx
@@ -34,6 +34,8 @@ namespace CameraWindow {
const BAR_HEIGHT = 56;
+const { cameraWsPort } = (window as any).__CAP__;
+
export default function () {
const options = createOptionsQuery();
@@ -47,7 +49,7 @@ export default function () {
const [latestFrame, setLatestFrame] = createLazySignal<ImageData | null>();
- createImageDataWS("ws://localhost:9182", (imageData) => {
+ createImageDataWS(`ws://localhost:${cameraWsPort}`, (imageData) => {
setLatestFrame(imageData);
const ctx = cameraCanvasRef?.getContext("2d");
ctx?.putImageData(imageData, 0, 0);
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 94200e6d5..8e3059b2b 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -21,9 +21,6 @@ async setRecordingOptions(options: RecordingOptions) : Promise<Result<null, null
else return { status: "error", error: e as any };
}
},
-async createCameraWindow() : Promise<void> {
- await TAURI_INVOKE("create_camera_window");
-},
async startRecording() : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("start_recording") };