Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add camera overlay bounds update and revert logic
Richie McIlroy0066eb13db21
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 284f8b322..e3c3f1ffa 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -2294,6 +2294,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {captions::export_captions_srt,target_select_overlay::open_target_select_overlays,target_select_overlay::close_target_select_overlays,+ target_select_overlay::update_camera_overlay_bounds,target_select_overlay::display_information,target_select_overlay::get_window_icon,target_select_overlay::focus_window,diff --git a/apps/desktop/src-tauri/src/target_select_overlay.rs b/apps/desktop/src-tauri/src/target_select_overlay.rsindex a1c3fd216..d52424235 100644--- a/apps/desktop/src-tauri/src/target_select_overlay.rs+++ b/apps/desktop/src-tauri/src/target_select_overlay.rs@@ -148,6 +148,36 @@ fn should_skip_window(window: &Window, exclusions: &[WindowExclusion]) -> bool {})}+#[specta::specta]+#[tauri::command]+#[instrument(skip(app))]+pub async fn update_camera_overlay_bounds(+ app: AppHandle,+ x: f64,+ y: f64,+ width: f64,+ height: f64,+) -> Result<(), String> {+ let window = app+ .get_webview_window("camera")+ .ok_or("Camera window not found")?;++ window+ .set_size(tauri::Size::Physical(tauri::PhysicalSize {+ width: width as u32,+ height: height as u32,+ }))+ .map_err(|e| e.to_string())?;+ window+ .set_position(tauri::Position::Physical(tauri::PhysicalPosition {+ x: x as i32,+ y: y as i32,+ }))+ .map_err(|e| e.to_string())?;++ Ok(())+}+#[specta::specta]#[tauri::command]#[instrument(skip(app))]diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 3d567e579..12cde9fef 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -521,6 +521,8 @@ impl ShowCapWindow {#[cfg(target_os = "macos")]{+ crate::platform::set_window_level(window.as_ref().window(), 60);+_ = window.run_on_main_thread({let window = window.as_ref().window();move || unsafe {diff --git a/apps/desktop/src/routes/target-select-overlay.tsx b/apps/desktop/src/routes/target-select-overlay.tsxindex 6a08d85c5..1d1f9a17f 100644--- a/apps/desktop/src/routes/target-select-overlay.tsx+++ b/apps/desktop/src/routes/target-select-overlay.tsx@@ -3,7 +3,12 @@ import { createEventListener } from "@solid-primitives/event-listener";import { createElementSize } from "@solid-primitives/resize-observer";import { useSearchParams } from "@solidjs/router";import { createMutation, useQuery } from "@tanstack/solid-query";-import { LogicalPosition } from "@tauri-apps/api/dpi";+import { invoke } from "@tauri-apps/api/core";+import {+ LogicalPosition,+ type PhysicalPosition,+ type PhysicalSize,+} from "@tauri-apps/api/dpi";import { emit } from "@tauri-apps/api/event";import {CheckMenuItem,@@ -11,6 +16,7 @@ import {MenuItem,PredefinedMenuItem,} from "@tauri-apps/api/menu";+import { WebviewWindow } from "@tauri-apps/api/webviewWindow";import { type as ostype } from "@tauri-apps/plugin-os";import {createEffect,@@ -19,6 +25,7 @@ import {Match,mergeProps,onCleanup,+ onMount,Show,Suspense,Switch,@@ -213,6 +220,16 @@ function Inner() {const unsubOnEscapePress = events.onEscapePress.listen(() => {setOptions("targetMode", null);commands.closeTargetSelectOverlays();++ // We can't easily access `revertCamera` here because it's inside the Match.+ // However, if we close overlays, the camera might stay moved?+ // The user request says "if the user cancels the selection".+ // Pressing Escape cancels the selection mode entirely.+ // Ideally we should revert the camera position if we moved it.+ // But `revertCamera` is scoped to `Inner` -> `Match`.+ // We can rely on the fact that `originalCameraBounds` state is local to that Match block.+ // If the block unmounts, we might want to revert?+ // `onCleanup` inside the Match block is the right place.});onCleanup(() => unsubOnEscapePress.then((f) => f()));@@ -381,12 +398,25 @@ function Inner() {let controlsEl: HTMLDivElement | undefined;let cropperRef: CropperRef | undefined;+ const [cameraWindow, setCameraWindow] =+ createSignal<WebviewWindow | null>(null);+ const [originalCameraBounds, setOriginalCameraBounds] = createSignal<{+ position: PhysicalPosition;+ size: PhysicalSize;+ } | null>(null);+ const [cachedScaleFactor, setCachedScaleFactor] = createSignal<+ number | null+ >(null);++ onMount(async () => {+ const win = await WebviewWindow.getByLabel("camera");+ if (win) setCameraWindow(win);+ });+const [aspect, setAspect] = createSignal<Ratio | null>(null);const [snapToRatioEnabled, setSnapToRatioEnabled] =createSignal(true);const [isInteracting, setIsInteracting] = createSignal(false);- const [committedCrop, setCommittedCrop] =- createSignal<CropBounds>(CROP_ZERO);const shouldShowSelectionHint = createMemo(() => {if (initialAreaBounds() !== undefined) return false;const bounds = crop();@@ -397,14 +427,153 @@ function Inner() {const b = crop();return b.width >= MIN_SIZE.width && b.height >= MIN_SIZE.height;});- const committedIsValid = createMemo(() => {- const b = committedCrop();- return b.width >= MIN_SIZE.width && b.height >= MIN_SIZE.height;++ const [targetState, setTargetState] = createSignal<{+ x: number;+ y: number;+ width: number;+ height: number;+ } | null>(null);++ let lastApplied: {+ x: number;+ y: number;+ width: number;+ height: number;+ } | null = null;++ onMount(() => {+ let processing = false;++ const loop = async () => {+ const target = targetState();+ if (target && !processing) {+ const changed =+ !lastApplied ||+ Math.abs(lastApplied.x - target.x) > 1 ||+ Math.abs(lastApplied.y - target.y) > 1 ||+ Math.abs(lastApplied.width - target.width) > 1 ||+ Math.abs(lastApplied.height - target.height) > 1;++ if (changed) {+ processing = true;+ try {+ await invoke("update_camera_overlay_bounds", {+ x: target.x,+ y: target.y,+ width: target.width,+ height: target.height,+ });+ lastApplied = target;+ } catch (e) {+ console.error("Failed to update camera window", e);+ }+ processing = false;+ }+ }+ requestAnimationFrame(loop);+ };+ const raf = requestAnimationFrame(loop);+ onCleanup(() => cancelAnimationFrame(raf));});- createEffect(() => {- if (isInteracting()) return;- setCommittedCrop(crop());+ createEffect(async () => {+ const bounds = crop();+ const interacting = isInteracting();++ // Find the camera window if we haven't yet+ let win = cameraWindow();+ if (!win) {+ // Try to find it+ try {+ win = await WebviewWindow.getByLabel("camera");+ if (!win) {+ // Fallback: check all windows+ const all = await WebviewWindow.getAll();+ win = all.find((w) => w.label.includes("camera")) ?? null;+ }+ if (win) setCameraWindow(win);+ } catch (e) {+ console.error("Failed to find camera window", e);+ }+ }++ if (!win || !interacting) return;++ // Initialize data+ if (!originalCameraBounds() || cachedScaleFactor() === null) {+ try {+ const pos = await win.outerPosition();+ const size = await win.outerSize();+ const factor = await win.scaleFactor();+ setOriginalCameraBounds({ position: pos, size });+ setCachedScaleFactor(factor);+ } catch (e) {+ console.error("Failed to init camera bounds", e);+ }+ return;+ }++ const original = originalCameraBounds();+ const scaleFactor = cachedScaleFactor() ?? 1;++ if (!original) return;++ const originalLogicalSize = original.size.toLogical(scaleFactor);++ const padding = 16;+ const selectionMinDim = Math.min(bounds.width, bounds.height);+ const targetMaxDim = Math.max(+ 150,+ Math.min(+ Math.max(originalLogicalSize.width, originalLogicalSize.height),+ selectionMinDim * 0.5,+ ),+ );++ const originalMaxDim = Math.max(+ originalLogicalSize.width,+ originalLogicalSize.height,+ );+ const scale = targetMaxDim / originalMaxDim;++ const newWidth = Math.round(originalLogicalSize.width * scale);+ const newHeight = Math.round(originalLogicalSize.height * scale);++ if (+ bounds.width > newWidth + padding * 2 &&+ bounds.height > newHeight + padding * 2+ ) {+ const newX = Math.round(+ bounds.x + bounds.width - newWidth - padding,+ );+ const newY = Math.round(+ bounds.y + bounds.height - newHeight - padding,+ );++ setTargetState({+ x: newX * scaleFactor,+ y: newY * scaleFactor,+ width: newWidth * scaleFactor,+ height: newHeight * scaleFactor,+ });+ }+ });++ async function revertCamera() {+ const original = originalCameraBounds();+ const win = cameraWindow();+ if (original && win) {+ await win.setPosition(original.position);+ await win.setSize(original.size);+ setOriginalCameraBounds(null);+ setTargetState(null);+ lastApplied = null;+ }+ }++ onCleanup(() => {+ revertCamera();});async function showCropOptionsMenu(e: UIEvent) {@@ -416,6 +585,7 @@ function Inner() {cropperRef?.reset();setAspect(null);setPendingAreaTarget(null);+ revertCamera();},},await PredefinedMenuItem.new({@@ -503,10 +673,10 @@ function Inner() {createEffect(() => {if (isInteracting()) return;- if (!committedIsValid()) return;+ if (!isValid()) return;const screenId = displayId();if (!screenId) return;- const bounds = committedCrop();+ const bounds = crop();setPendingAreaTarget({variant: "area",screen: screenId,@@ -518,7 +688,7 @@ function Inner() {});return (- <div class="fixed w-screen h-screen bg-black/60 relative">+ <div class="fixed w-screen h-screen bg-black/60"><divref={controlsEl}class="fixed z-50 transition-opacity"@@ -531,17 +701,18 @@ function Inner() {screen: displayId(),bounds: {position: {- x: committedCrop().x,- y: committedCrop().y,+ x: crop().x,+ y: crop().y,},size: {- width: committedCrop().width,- height: committedCrop().height,+ width: crop().width,+ height: crop().height,},},}}disabled={!isValid()}showBackground={controllerInside()}+ onRecordingStart={() => setOriginalCameraBounds(null)}/><Show when={!isValid()}><div class="flex flex-col gap-1 items-center p-2.5 my-2 rounded-xl border min-w-fit w-fit bg-red-2 shadow-sm border-red-4 text-sm">@@ -587,6 +758,7 @@ function RecordingControls(props: {setToggleModeSelect?: (value: boolean) => void;showBackground?: boolean;disabled?: boolean;+ onRecordingStart?: () => void;}) {const auth = authStore.createQuery();const { setOptions, rawOptions } = useRecordingOptions();@@ -724,6 +896,8 @@ function RecordingControls(props: {);}+ props.onRecordingStart?.();+commands.startRecording({capture_target: props.target,mode: rawOptions.mode,diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 05762f698..80ada5de5 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -277,6 +277,9 @@ async openTargetSelectOverlays(focusedTarget: ScreenCaptureTarget | null) : Promasync closeTargetSelectOverlays() : Promise<null> {return await TAURI_INVOKE("close_target_select_overlays");},+async updateCameraOverlayBounds(x: number, y: number, width: number, height: number) : Promise<null> {+ return await TAURI_INVOKE("update_camera_overlay_bounds", { x, y, width, height });+},async displayInformation(displayId: string) : Promise<DisplayInformation> {return await TAURI_INVOKE("display_information", { displayId });},