Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve camera window resizing and positioning logic

Richie McIlroy756d29640781
diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs
index ee03d7680..dc2581139 100644
--- a/apps/desktop/src-tauri/src/camera.rs
+++ b/apps/desktop/src-tauri/src/camera.rs
@@ -186,8 +186,8 @@ impl InitializedCameraPreview {
1.0
};
- let size =
- resize_window(&window, default_state, aspect).context("Error resizing Tauri window")?;
+ let size = resize_window(&window, default_state, aspect, true)
+ .context("Error resizing Tauri window")?;
let (tx, rx) = oneshot::channel();
window
@@ -577,7 +577,7 @@ impl Renderer {
self.sync_ratio_uniform_and_resize_window_to_it(&window, &state, aspect_ratio);
self.update_state_uniforms(&state);
- if let Ok((width, height)) = resize_window(&window, &state, aspect_ratio)
+ if let Ok((width, height)) = resize_window(&window, &state, aspect_ratio, false)
.map_err(|err| error!("Error resizing camera preview window: {err}"))
{
self.reconfigure_gpu_surface(width, height);
@@ -662,7 +662,7 @@ impl Renderer {
bytemuck::cast_slice(&[camera_uniforms]),
);
- if let Ok((width, height)) = resize_window(window, state, aspect_ratio)
+ if let Ok((width, height)) = resize_window(window, state, aspect_ratio, false)
.map_err(|err| error!("Error resizing camera preview window: {err}"))
{
self.reconfigure_gpu_surface(width, height);
@@ -677,6 +677,7 @@ fn resize_window(
window: &WebviewWindow,
state: &CameraPreviewState,
aspect: f32,
+ should_move: bool,
) -> tauri::Result<(u32, u32)> {
trace!("CameraPreview/resize_window");
@@ -692,25 +693,68 @@ fn resize_window(
base
} + TOOLBAR_HEIGHT;
- let (monitor_size, monitor_offset, monitor_scale_factor): (
- PhysicalSize<u32>,
- LogicalPosition<u32>,
- _,
- ) = if let Some(monitor) = window.current_monitor()? {
- let size = monitor.position().to_logical(monitor.scale_factor());
- (*monitor.size(), size, monitor.scale_factor())
- } else {
- (PhysicalSize::new(640, 360), LogicalPosition::new(0, 0), 1.0)
- };
+ if should_move {
+ let (monitor_size, monitor_offset, monitor_scale_factor): (
+ PhysicalSize<u32>,
+ LogicalPosition<u32>,
+ _,
+ ) = if let Some(monitor) = window.current_monitor()? {
+ let size = monitor.position().to_logical(monitor.scale_factor());
+ (*monitor.size(), size, monitor.scale_factor())
+ } else {
+ (PhysicalSize::new(640, 360), LogicalPosition::new(0, 0), 1.0)
+ };
+
+ let x = (monitor_size.width as f64 / monitor_scale_factor - window_width as f64 - 100.0)
+ as u32
+ + monitor_offset.x;
+ let y = (monitor_size.height as f64 / monitor_scale_factor - window_height as f64 - 100.0)
+ as u32
+ + monitor_offset.y;
+
+ window.set_position(LogicalPosition::new(x, y))?;
+ } else if let Some(monitor) = window.current_monitor()? {
+ // Ensure the window stays within the monitor bounds when resizing
+ let scale_factor = monitor.scale_factor();
+ let monitor_pos = monitor.position().to_logical::<f64>(scale_factor);
+ let monitor_size = monitor.size().to_logical::<f64>(scale_factor);
+
+ let current_pos = window
+ .outer_position()
+ .map(|p| p.to_logical::<f64>(scale_factor))
+ .unwrap_or(monitor_pos);
+
+ let mut new_x = current_pos.x;
+ let mut new_y = current_pos.y;
+ let new_width = window_width as f64;
+ let new_height = window_height as f64;
+
+ // Check right edge
+ if new_x + new_width > monitor_pos.x + monitor_size.width {
+ new_x = monitor_pos.x + monitor_size.width - new_width;
+ }
+
+ // Check bottom edge
+ if new_y + new_height > monitor_pos.y + monitor_size.height {
+ new_y = monitor_pos.y + monitor_size.height - new_height;
+ }
+
+ // Check left edge
+ if new_x < monitor_pos.x {
+ new_x = monitor_pos.x;
+ }
- let x = (monitor_size.width as f64 / monitor_scale_factor - window_width as f64 - 100.0) as u32
- + monitor_offset.x;
- let y = (monitor_size.height as f64 / monitor_scale_factor - window_height as f64 - 100.0)
- as u32
- + monitor_offset.y;
+ // Check top edge
+ if new_y < monitor_pos.y {
+ new_y = monitor_pos.y;
+ }
+
+ if (new_x - current_pos.x).abs() > 1.0 || (new_y - current_pos.y).abs() > 1.0 {
+ window.set_position(LogicalPosition::new(new_x, new_y))?;
+ }
+ }
window.set_size(LogicalSize::new(window_width, window_height))?;
- window.set_position(LogicalPosition::new(x, y))?;
Ok((window_width as u32, window_height as u32))
}
diff --git a/apps/desktop/src/routes/camera.tsx b/apps/desktop/src/routes/camera.tsx
index 0953b05ea..6170e7b57 100644
--- a/apps/desktop/src/routes/camera.tsx
+++ b/apps/desktop/src/routes/camera.tsx
@@ -24,7 +24,7 @@ import { createStore } from "solid-js/store";
import { generalSettingsStore } from "~/store";
import { createTauriEventListener } from "~/utils/createEventListener";
import { createCameraMutation } from "~/utils/queries";
-import { createImageDataWS, createLazySignal } from "~/utils/socket";
+import { createLazySignal } from "~/utils/socket";
import { commands, events } from "~/utils/tauri";
import {
RecordingOptionsProvider,
@@ -293,6 +293,8 @@ function LegacyCameraPreviewPage(props: { disconnected: Accessor<boolean> }) {
corner: "",
});
+ const [hasPositioned, setHasPositioned] = createSignal(false);
+
const [latestFrame, setLatestFrame] = createLazySignal<{
width: number;
data: ImageData;
@@ -322,28 +324,107 @@ function LegacyCameraPreviewPage(props: { disconnected: Accessor<boolean> }) {
ctx?.putImageData(imageData.data, 0, 0);
}
- const { cameraWsPort } = (window as any).__CAP__;
- const [ws, isConnected] = createImageDataWS(
- `ws://localhost:${cameraWsPort}`,
- imageDataHandler,
- );
+ const { cameraWsPort } = window.__CAP__;
+ const [isConnected, setIsConnected] = createSignal(false);
+ let ws: WebSocket | undefined;
+
+ const createSocket = () => {
+ const socket = new WebSocket(`ws://localhost:${cameraWsPort}`);
+ socket.binaryType = "arraybuffer";
+
+ socket.addEventListener("open", () => {
+ console.log("WebSocket connected");
+ setIsConnected(true);
+ });
+
+ socket.addEventListener("close", () => {
+ console.log("WebSocket disconnected");
+ setIsConnected(false);
+ });
+
+ socket.addEventListener("error", (error) => {
+ console.error("WebSocket error:", error);
+ setIsConnected(false);
+ });
+
+ socket.onmessage = (event) => {
+ const buffer = event.data as ArrayBuffer;
+ const clamped = new Uint8ClampedArray(buffer);
+ if (clamped.length < 12) {
+ console.error("Received frame too small to contain metadata");
+ return;
+ }
+
+ const metadataOffset = clamped.length - 12;
+ const meta = new DataView(buffer, metadataOffset, 12);
+ const strideBytes = meta.getUint32(0, true);
+ const height = meta.getUint32(4, true);
+ const width = meta.getUint32(8, true);
+
+ if (!width || !height) {
+ console.error("Received invalid frame dimensions", { width, height });
+ return;
+ }
+
+ const source = clamped.subarray(0, metadataOffset);
+ const expectedRowBytes = width * 4;
+ const expectedLength = expectedRowBytes * height;
+ const availableLength = strideBytes * height;
+
+ if (
+ strideBytes === 0 ||
+ strideBytes < expectedRowBytes ||
+ source.length < availableLength
+ ) {
+ console.error("Received invalid frame stride", {
+ strideBytes,
+ expectedRowBytes,
+ height,
+ sourceLength: source.length,
+ });
+ return;
+ }
+
+ let pixels: Uint8ClampedArray;
+
+ if (strideBytes === expectedRowBytes) {
+ pixels = source.subarray(0, expectedLength);
+ } else {
+ pixels = new Uint8ClampedArray(expectedLength);
+ for (let row = 0; row < height; row += 1) {
+ const srcStart = row * strideBytes;
+ const destStart = row * expectedRowBytes;
+ pixels.set(
+ source.subarray(srcStart, srcStart + expectedRowBytes),
+ destStart,
+ );
+ }
+ }
+
+ const imageData = new ImageData(
+ new Uint8ClampedArray(pixels),
+ width,
+ height,
+ );
+ imageDataHandler({ width, data: imageData });
+ };
+
+ return socket;
+ };
+
+ ws = createSocket();
const reconnectInterval = setInterval(() => {
- if (!isConnected()) {
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
console.log("Attempting to reconnect...");
- ws.close();
-
- const newWs = createImageDataWS(
- `ws://localhost:${cameraWsPort}`,
- imageDataHandler,
- );
- Object.assign(ws, newWs[0]);
+ if (ws) ws.close();
+ ws = createSocket();
}
}, 5000);
onCleanup(() => {
clearInterval(reconnectInterval);
- ws.close();
+ ws?.close();
});
const scale = () => {
@@ -433,13 +514,56 @@ function LegacyCameraPreviewPage(props: { disconnected: Accessor<boolean> }) {
const height = monitor.size.height / scalingFactor - totalHeight - 100;
const currentWindow = getCurrentWindow();
- currentWindow.setSize(new LogicalSize(windowWidth, totalHeight));
- currentWindow.setPosition(
- new LogicalPosition(
- width + monitor.position.toLogical(scalingFactor).x,
- height + monitor.position.toLogical(scalingFactor).y,
- ),
- );
+
+ if (!hasPositioned()) {
+ currentWindow.setPosition(
+ new LogicalPosition(
+ width + monitor.position.toLogical(scalingFactor).x,
+ height + monitor.position.toLogical(scalingFactor).y,
+ ),
+ );
+ setHasPositioned(true);
+ } else {
+ const outerPos = await currentWindow.outerPosition();
+ const logicalPos = outerPos.toLogical(scalingFactor);
+ const monitorLogicalPos = monitor.position.toLogical(scalingFactor);
+ const monitorLogicalSize = monitor.size.toLogical(scalingFactor);
+
+ let newX = logicalPos.x;
+ let newY = logicalPos.y;
+
+ // Right edge
+ if (
+ newX + windowWidth >
+ monitorLogicalPos.x + monitorLogicalSize.width
+ ) {
+ newX = monitorLogicalPos.x + monitorLogicalSize.width - windowWidth;
+ }
+ // Bottom edge
+ if (
+ newY + totalHeight >
+ monitorLogicalPos.y + monitorLogicalSize.height
+ ) {
+ newY = monitorLogicalPos.y + monitorLogicalSize.height - totalHeight;
+ }
+ // Left edge
+ if (newX < monitorLogicalPos.x) {
+ newX = monitorLogicalPos.x;
+ }
+ // Top edge
+ if (newY < monitorLogicalPos.y) {
+ newY = monitorLogicalPos.y;
+ }
+
+ if (
+ Math.abs(newX - logicalPos.x) > 1 ||
+ Math.abs(newY - logicalPos.y) > 1
+ ) {
+ await currentWindow.setPosition(new LogicalPosition(newX, newY));
+ }
+ }
+
+ await currentWindow.setSize(new LogicalSize(windowWidth, totalHeight));
return { width, height, size: base, windowWidth, windowHeight };
},
@@ -541,73 +665,12 @@ function LegacyCameraPreviewPage(props: { disconnected: Accessor<boolean> }) {
data-tauri-drag-region
>
<Suspense fallback={<CameraLoadingState />}>
- <Show when={latestFrame()}>
- {(latestFrame) => {
- const style = () => {
- const aspectRatio =
- latestFrame().data.width / latestFrame().data.height;
-
- // Use state.size directly for immediate feedback
- const base = state.size;
-
- // Replicate window size logic synchronously for the canvas
- const winWidth =
- state.shape === "full"
- ? aspectRatio >= 1
- ? base * aspectRatio
- : base
- : base;
- const winHeight =
- state.shape === "full"
- ? aspectRatio >= 1
- ? base
- : base / aspectRatio
- : base;
-
- if (state.shape === "full") {
- return {
- width: `${winWidth}px`,
- height: `${winHeight}px`,
- transform: state.mirrored ? "scaleX(-1)" : "scaleX(1)",
- };
- }
-
- const size = (() => {
- if (aspectRatio > 1)
- return {
- width: base * aspectRatio,
- height: base,
- };
- else
- return {
- width: base,
- height: base * aspectRatio,
- };
- })();
-
- const left = aspectRatio > 1 ? (size.width - base) / 2 : 0;
- const top = aspectRatio > 1 ? 0 : (base - size.height) / 2;
-
- return {
- width: `${size.width}px`,
- height: `${size.height}px`,
- left: `-${left}px`,
- top: `-${top}px`,
- transform: state.mirrored ? "scaleX(-1)" : "scaleX(1)",
- };
- };
-
- return (
- <canvas
- data-tauri-drag-region
- class={cx("absolute")}
- style={style()}
- width={latestFrame().data.width}
- height={latestFrame().data.height}
- ref={cameraCanvasRef!}
- />
- );
- }}
+ <Show when={latestFrame() !== null && latestFrame() !== undefined}>
+ <Canvas
+ latestFrame={latestFrame}
+ state={state}
+ ref={cameraCanvasRef}
+ />
</Show>
</Suspense>
</div>
@@ -615,6 +678,79 @@ function LegacyCameraPreviewPage(props: { disconnected: Accessor<boolean> }) {
);
}
+function Canvas(props: {
+ latestFrame: Accessor<{ width: number; data: ImageData } | null | undefined>;
+ state: CameraWindowState;
+ ref: HTMLCanvasElement | undefined;
+}) {
+ const style = () => {
+ const frame = props.latestFrame();
+ if (!frame) return {};
+
+ const aspectRatio = frame.data.width / frame.data.height;
+
+ // Use state.size directly for immediate feedback
+ const base = props.state.size;
+
+ // Replicate window size logic synchronously for the canvas
+ const winWidth =
+ props.state.shape === "full"
+ ? aspectRatio >= 1
+ ? base * aspectRatio
+ : base
+ : base;
+ const winHeight =
+ props.state.shape === "full"
+ ? aspectRatio >= 1
+ ? base
+ : base / aspectRatio
+ : base;
+
+ if (props.state.shape === "full") {
+ return {
+ width: `${winWidth}px`,
+ height: `${winHeight}px`,
+ transform: props.state.mirrored ? "scaleX(-1)" : "scaleX(1)",
+ };
+ }
+
+ const size = (() => {
+ if (aspectRatio > 1)
+ return {
+ width: base * aspectRatio,
+ height: base,
+ };
+ else
+ return {
+ width: base,
+ height: base * aspectRatio,
+ };
+ })();
+
+ const left = aspectRatio > 1 ? (size.width - base) / 2 : 0;
+ const top = aspectRatio > 1 ? 0 : (base - size.height) / 2;
+
+ return {
+ width: `${size.width}px`,
+ height: `${size.height}px`,
+ left: `-${left}px`,
+ top: `-${top}px`,
+ transform: props.state.mirrored ? "scaleX(-1)" : "scaleX(1)",
+ };
+ };
+
+ return (
+ <canvas
+ data-tauri-drag-region
+ class={cx("absolute")}
+ style={style()}
+ width={props.latestFrame()?.data.width}
+ height={props.latestFrame()?.data.height}
+ ref={props.ref!}
+ />
+ );
+}
+
function CameraLoadingState() {
return (
<div class="w-full flex-1 flex items-center justify-center">