Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(editor): support manual camera and display positioning

Richie McIlroy9ba56179d162
diff --git a/apps/desktop/src/routes/editor/CaptionOverlay.tsx b/apps/desktop/src/routes/editor/CaptionOverlay.tsx
index 17516a1a9..d0652a0d1 100644
--- a/apps/desktop/src/routes/editor/CaptionOverlay.tsx
+++ b/apps/desktop/src/routes/editor/CaptionOverlay.tsx
@@ -11,7 +11,9 @@ import {
import { produce } from "solid-js/store";
import { defaultCaptionSettings } from "~/store/captions";
import type { CaptionTrackSegment } from "~/utils/tauri";
+import { useCanvasSnapTargets } from "./CanvasElementsOverlay";
import { FPS, useEditorContext } from "./context";
+import { SNAP_PX, type SnapTargets, snapMovingRect } from "./snapping";
type CaptionOverlayProps = {
size: { width: number; height: number };
@@ -41,8 +43,15 @@ function positionYFactor(position: string) {
}
export function CaptionOverlay(props: CaptionOverlayProps) {
- const { project, setProject, editorState, setEditorState, projectHistory } =
- useEditorContext();
+ const {
+ project,
+ setProject,
+ editorState,
+ setEditorState,
+ projectHistory,
+ setSnapGuides,
+ } = useEditorContext();
+ const snapTargetsFor = useCanvasSnapTargets();
const [measuredSize, setMeasuredSize] = createSignal({ width: 1, height: 1 });
let hiddenMeasureRef: HTMLDivElement | undefined;
@@ -188,12 +197,14 @@ export function CaptionOverlay(props: CaptionOverlayProps) {
setup: () => {
center: { x: number; y: number };
rect: ReturnType<typeof rect>;
+ targets: SnapTargets;
},
update: (
event: MouseEvent,
initial: {
center: { x: number; y: number };
rect: ReturnType<typeof rect>;
+ targets: SnapTargets;
},
initialMouse: { x: number; y: number },
) => void,
@@ -216,6 +227,7 @@ export function CaptionOverlay(props: CaptionOverlayProps) {
throttledUpdate.clear();
handleUpdate(finalEvent);
resumeHistory();
+ setSnapGuides([]);
dispose();
}
@@ -242,7 +254,7 @@ export function CaptionOverlay(props: CaptionOverlayProps) {
x: (currentRect.left + currentRect.width / 2) / props.size.width,
y: (currentRect.top + currentRect.height / 2) / props.size.height,
};
- return { center, rect: currentRect };
+ return { center, rect: currentRect, targets: snapTargetsFor(null) };
},
(event, initial, initialMouse) => {
if (props.size.width <= 0 || props.size.height <= 0) return;
@@ -252,9 +264,30 @@ export function CaptionOverlay(props: CaptionOverlayProps) {
const halfWidth = initial.rect.width / props.size.width / 2;
const halfHeight = initial.rect.height / props.size.height / 2;
+ let snapDx = 0;
+ let snapDy = 0;
+ if (event.shiftKey) {
+ setSnapGuides([]);
+ } else {
+ const snap = snapMovingRect(
+ {
+ x: initial.center.x + dx - halfWidth,
+ y: initial.center.y + dy - halfHeight,
+ w: halfWidth * 2,
+ h: halfHeight * 2,
+ },
+ initial.targets,
+ SNAP_PX / props.size.width,
+ SNAP_PX / props.size.height,
+ );
+ snapDx = snap.dx;
+ snapDy = snap.dy;
+ setSnapGuides(snap.guides);
+ }
+
updateManualPosition({
- x: clamp(initial.center.x + dx, halfWidth, 1 - halfWidth),
- y: clamp(initial.center.y + dy, halfHeight, 1 - halfHeight),
+ x: clamp(initial.center.x + dx + snapDx, halfWidth, 1 - halfWidth),
+ y: clamp(initial.center.y + dy + snapDy, halfHeight, 1 - halfHeight),
});
},
);
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 070ae7c34..fd534d722 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -17,11 +17,13 @@ import {
createSignal,
ErrorBoundary,
For,
+ lazy,
Match,
on,
onCleanup,
onMount,
Show,
+ Suspense,
Switch,
} from "solid-js";
import { createStore } from "solid-js/store";
@@ -39,7 +41,6 @@ import { Toggle } from "~/components/Toggle";
import { composeEventHandlers } from "~/utils/composeEventHandlers";
import { createTauriEventListener } from "~/utils/createEventListener";
import { commands, events } from "~/utils/tauri";
-import { ClipsSidebar } from "./ClipsSidebar";
import { ConfigSidebar } from "./ConfigSidebar";
import {
EditorContextProvider,
@@ -51,14 +52,28 @@ import {
useEditorInstanceContext,
} from "./context";
import { EditorErrorScreen } from "./EditorErrorScreen";
-import { ExportPage } from "./ExportPage";
import { Header } from "./Header";
import { ImportProgress } from "./ImportProgress";
import { PlayerContent } from "./Player";
import { Timeline } from "./Timeline";
-import { TranscriptPanel } from "./TranscriptPage";
import { Dialog, DialogContent, EditorButton, Input, Subfield } from "./ui";
+// Deferred surfaces: these are not visible at first paint (export mode,
+// transcript panel, clips sidebar), so their code is split out of the editor
+// chunk to keep webview parse time — the dominant editor-open cost on
+// WebView2 — off the critical path. Each render site wraps them in a local
+// <Suspense> so the chunk load never bubbles up to the top-level editor
+// Suspense (which would flash the whole UI back to the skeleton).
+const ClipsSidebar = lazy(() =>
+ import("./ClipsSidebar").then((m) => ({ default: m.ClipsSidebar })),
+);
+const ExportPage = lazy(() =>
+ import("./ExportPage").then((m) => ({ default: m.ExportPage })),
+);
+const TranscriptPanel = lazy(() =>
+ import("./TranscriptPage").then((m) => ({ default: m.TranscriptPanel })),
+);
+
const DEFAULT_TIMELINE_HEIGHT = 260;
const MIN_PLAYER_CONTENT_HEIGHT = 320;
const MIN_TIMELINE_HEIGHT = 240;
@@ -639,7 +654,14 @@ function Inner() {
};
return (
- <Show when={!fullscreenMode()} fallback={<ExportPage />}>
+ <Show
+ when={!fullscreenMode()}
+ fallback={
+ <Suspense>
+ <ExportPage />
+ </Suspense>
+ }
+ >
<div class="flex flex-col flex-1 min-h-0">
<Header />
<div
@@ -707,10 +729,12 @@ function Inner() {
<ConfigSidebar />
</div>
<Show when={clipsSidebarMounted()}>
- <ClipsSidebar
- open={isClipsMode()}
- class={isClipsMode() ? undefined : "hidden"}
- />
+ <Suspense>
+ <ClipsSidebar
+ open={isClipsMode()}
+ class={isClipsMode() ? undefined : "hidden"}
+ />
+ </Suspense>
</Show>
</div>
</Show>
@@ -739,7 +763,9 @@ function Inner() {
"min-width": "0",
}}
>
- <TranscriptPanel />
+ <Suspense>
+ <TranscriptPanel />
+ </Suspense>
</div>
</Show>
</div>
diff --git a/apps/desktop/src/routes/editor/MaskOverlay.tsx b/apps/desktop/src/routes/editor/MaskOverlay.tsx
index ec11f144b..9fb59b8c1 100644
--- a/apps/desktop/src/routes/editor/MaskOverlay.tsx
+++ b/apps/desktop/src/routes/editor/MaskOverlay.tsx
@@ -3,8 +3,10 @@ import { cx } from "cva";
import { createMemo, createRoot, For, Show } from "solid-js";
import { produce } from "solid-js/store";
+import { useCanvasSnapTargets } from "./CanvasElementsOverlay";
import { useEditorContext } from "./context";
import { evaluateMask, type MaskSegment } from "./masks";
+import { SNAP_PX, snapMovingRect } from "./snapping";
type MaskOverlayProps = {
size: { width: number; height: number };
@@ -186,6 +188,7 @@ export function MaskOverlay(props: MaskOverlayProps) {
>
<MaskOverlayContent
size={props.size}
+ maskIndex={index}
maskState={maskState}
updateSegment={updateSegment}
projectHistory={projectHistory}
@@ -200,11 +203,14 @@ export function MaskOverlay(props: MaskOverlayProps) {
function MaskOverlayContent(props: {
size: { width: number; height: number };
+ maskIndex: number;
maskState: () => ReturnType<typeof evaluateMask>;
updateSegment: (fn: (segment: MaskSegment) => void) => void;
projectHistory: ReturnType<typeof useEditorContext>["projectHistory"];
}) {
const { projectHistory, updateSegment } = props;
+ const { setSnapGuides } = useEditorContext();
+ const snapTargetsFor = useCanvasSnapTargets();
function createMouseDownDrag<T>(
setup: () => T,
@@ -228,6 +234,7 @@ function MaskOverlayContent(props: {
function finish() {
resumeHistory();
+ setSnapGuides([]);
dispose();
}
@@ -255,14 +262,37 @@ function MaskOverlayContent(props: {
const onMove = createMouseDownDrag(
() => ({
startPos: { ...state().position },
+ startSize: { ...state().size },
+ targets: snapTargetsFor({ mask: props.maskIndex }),
}),
- (e, { startPos }, initialMouse) => {
+ (e, { startPos, startSize, targets }, initialMouse) => {
const dx = (e.clientX - initialMouse.x) / props.size.width;
const dy = (e.clientY - initialMouse.y) / props.size.height;
+ let snapDx = 0;
+ let snapDy = 0;
+ if (e.shiftKey) {
+ setSnapGuides([]);
+ } else {
+ const snap = snapMovingRect(
+ {
+ x: startPos.x + dx - startSize.x / 2,
+ y: startPos.y + dy - startSize.y / 2,
+ w: startSize.x,
+ h: startSize.y,
+ },
+ targets,
+ SNAP_PX / props.size.width,
+ SNAP_PX / props.size.height,
+ );
+ snapDx = snap.dx;
+ snapDy = snap.dy;
+ setSnapGuides(snap.guides);
+ }
+
updateSegment((s) => {
- s.center.x = Math.max(0, Math.min(1, startPos.x + dx));
- s.center.y = Math.max(0, Math.min(1, startPos.y + dy));
+ s.center.x = Math.max(0, Math.min(1, startPos.x + dx + snapDx));
+ s.center.y = Math.max(0, Math.min(1, startPos.y + dy + snapDy));
});
},
);
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 091977d90..a27c0bb20 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -11,6 +11,10 @@ import Tooltip from "~/components/Tooltip";
import { captionsStore } from "~/store/captions";
import { commands } from "~/utils/tauri";
import AspectRatioSelect from "./AspectRatioSelect";
+import {
+ CanvasElementsOverlay,
+ SnapGuidesOverlay,
+} from "./CanvasElementsOverlay";
import { CaptionOverlay } from "./CaptionOverlay";
import { CaptionsRegenerateBadge } from "./CaptionsRegenerateBadge";
import { createCaptionTrackSegments } from "./captions";
@@ -626,10 +630,12 @@ function PreviewCanvas() {
id="canvas"
/>
<Show when={hasFrame()}>
+ <CanvasElementsOverlay size={size()} />
<MaskOverlay size={size()} />
<CaptionOverlay size={size()} />
<TextOverlay size={size()} />
<SplitScreenOverlay size={size()} />
+ <SnapGuidesOverlay size={size()} />
<PerformanceOverlay size={size()} />
</Show>
</div>
diff --git a/apps/desktop/src/routes/editor/SplitScreenOverlay.tsx b/apps/desktop/src/routes/editor/SplitScreenOverlay.tsx
index 5b45e1c7c..904e058e2 100644
--- a/apps/desktop/src/routes/editor/SplitScreenOverlay.tsx
+++ b/apps/desktop/src/routes/editor/SplitScreenOverlay.tsx
@@ -18,6 +18,12 @@ const MAX_ZOOM = 3;
// An outward drag of roughly one pane-extent maps to this much zoom change.
const ZOOM_DRAG_RANGE = 2.5;
+// Floating-cards geometry. Matches the renderer's FLOATING_* constants
+// (crates/rendering/src/lib.rs) so the drag panes line up with the cards.
+const FLOATING_PADDING_FRAC = 0.05;
+const FLOATING_CAMERA_FRAC = 0.3;
+const FLOATING_CAMERA_FRAC_STACKED = 0.4;
+
const clamp = (v: number, min: number, max: number) =>
Math.max(min, Math.min(max, v));
@@ -62,12 +68,13 @@ const HANDLES: { dir: Dir; class: string }[] = [
},
];
-// In-canvas controls for the split-screen panes. Drag a pane to pan its focal
-// point; drag a resize handle to scale (zoom) its content. Writes the same
-// `splitLayout` fields the sidebar sliders use, so the two stay in sync. The
-// pane outline and handles only appear on hover, and the overlay is shown only
-// while a split-screen scene segment is selected with the playhead inside it
-// (so the handles line up with the rendered halves).
+// In-canvas controls for the split-screen and floating-cards panes. Drag a
+// pane to pan its focal point; drag a resize handle to scale (zoom) its
+// content. Writes the same `splitLayout` fields the sidebar sliders use, so
+// the two stay in sync. The pane outline and handles only appear on hover, and
+// the overlay is shown only while a split-screen/floating scene segment is
+// selected with the playhead inside it (so the handles line up with the
+// rendered panes).
export function SplitScreenOverlay(props: Props) {
const { project, setProject, editorState, projectHistory } =
useEditorContext();
@@ -81,7 +88,11 @@ export function SplitScreenOverlay(props: Props) {
const index = selection.indices[0];
if (index === undefined) return null;
const segment = project.timeline?.sceneSegments?.[index];
- if (!segment || segment.mode !== "splitScreen") return null;
+ if (
+ !segment ||
+ (segment.mode !== "splitScreen" && segment.mode !== "floating")
+ )
+ return null;
const time = currentTime();
if (time < segment.start || time >= segment.end) return null;
return { index, segment };
@@ -90,38 +101,67 @@ export function SplitScreenOverlay(props: Props) {
const split = (): SplitLayout =>
active()?.segment.splitLayout ?? DEFAULT_SPLIT_LAYOUT;
+ const floating = () => active()?.segment.mode === "floating";
+
// Matches the renderer: landscape output lays panes left/right, portrait
// stacks them top/bottom (crates/rendering SPLIT_STACK_ASPECT_THRESHOLD).
const horizontal = () => props.size.width >= props.size.height;
- const screenRect = (): Rect =>
- horizontal()
- ? {
- left: 0,
- top: 0,
- width: props.size.width / 2,
- height: props.size.height,
- }
- : {
- left: 0,
- top: 0,
- width: props.size.width,
- height: props.size.height / 2,
+ // Screen + camera pane rects, mirroring the renderer's geometry for the
+ // active mode: full-bleed halves for split-screen, padded cards for
+ // floating.
+ const rects = (): { screen: Rect; camera: Rect } => {
+ const { width: w, height: h } = props.size;
+ if (floating()) {
+ const pad = Math.min(w, h) * FLOATING_PADDING_FRAC;
+ if (horizontal()) {
+ const contentW = Math.max(w - pad * 3, 2);
+ const cameraW = contentW * FLOATING_CAMERA_FRAC;
+ return {
+ screen: {
+ left: pad,
+ top: pad,
+ width: contentW - cameraW,
+ height: h - pad * 2,
+ },
+ camera: {
+ left: w - pad - cameraW,
+ top: pad,
+ width: cameraW,
+ height: h - pad * 2,
+ },
};
- const cameraRect = (): Rect =>
- horizontal()
+ }
+ const contentH = Math.max(h - pad * 3, 2);
+ const cameraH = contentH * FLOATING_CAMERA_FRAC_STACKED;
+ return {
+ screen: {
+ left: pad,
+ top: pad,
+ width: w - pad * 2,
+ height: contentH - cameraH,
+ },
+ camera: {
+ left: pad,
+ top: h - pad - cameraH,
+ width: w - pad * 2,
+ height: cameraH,
+ },
+ };
+ }
+ return horizontal()
? {
- left: props.size.width / 2,
- top: 0,
- width: props.size.width / 2,
- height: props.size.height,
+ screen: { left: 0, top: 0, width: w / 2, height: h },
+ camera: { left: w / 2, top: 0, width: w / 2, height: h },
}
: {
- left: 0,
- top: props.size.height / 2,
- width: props.size.width,
- height: props.size.height / 2,
+ screen: { left: 0, top: 0, width: w, height: h / 2 },
+ camera: { left: 0, top: h / 2, width: w, height: h / 2 },
};
+ };
+
+ const screenRect = (): Rect => rects().screen;
+ const cameraRect = (): Rect => rects().camera;
const updateSplit = (patch: Partial<SplitLayout>) => {
const a = active();
@@ -200,6 +240,7 @@ export function SplitScreenOverlay(props: Props) {
<div class="absolute inset-0 pointer-events-none">
<Pane
rect={screenRect()}
+ rounded={floating()}
onPan={makePan(
() => split().screenPosition,
() => split().screenZoom,
@@ -217,6 +258,7 @@ export function SplitScreenOverlay(props: Props) {
/>
<Pane
rect={cameraRect()}
+ rounded={floating()}
onPan={makePan(
() => split().cameraPosition,
() => split().cameraZoom,
@@ -239,6 +281,7 @@ export function SplitScreenOverlay(props: Props) {
function Pane(props: {
rect: Rect;
+ rounded?: boolean;
onPan: (e: MouseEvent) => void;
makeResize: (dir: Dir) => (e: MouseEvent) => void;
}) {
@@ -253,7 +296,12 @@ function Pane(props: {
}}
onMouseDown={props.onPan}
>
- <div class="absolute inset-0 rounded-sm border-2 border-blue-9/80 bg-blue-9/10 opacity-0 transition-opacity duration-150 pointer-events-none group-hover:opacity-100" />
+ <div
+ class={cx(
+ "absolute inset-0 border-2 border-blue-9/80 bg-blue-9/10 opacity-0 transition-opacity duration-150 pointer-events-none group-hover:opacity-100",
+ props.rounded ? "rounded-2xl" : "rounded-sm",
+ )}
+ />
<For each={HANDLES}>
{(handle) => (
<div
diff --git a/apps/desktop/src/routes/editor/TextOverlay.tsx b/apps/desktop/src/routes/editor/TextOverlay.tsx
index 7c98efdd1..c4d75cd7c 100644
--- a/apps/desktop/src/routes/editor/TextOverlay.tsx
+++ b/apps/desktop/src/routes/editor/TextOverlay.tsx
@@ -13,7 +13,9 @@ import {
} from "solid-js";
import { produce } from "solid-js/store";
import type { TextSegment as TauriTextSegment } from "~/utils/tauri";
+import { useCanvasSnapTargets } from "./CanvasElementsOverlay";
import { FPS, useEditorContext } from "./context";
+import { SNAP_PX, snapMovingRect } from "./snapping";
import type { TextSegment } from "./text";
type TextOverlayProps = {
@@ -21,8 +23,14 @@ type TextOverlayProps = {
};
export function TextOverlay(props: TextOverlayProps) {
- const { project, setProject, editorState, setEditorState, projectHistory } =
- useEditorContext();
+ const {
+ project,
+ setProject,
+ editorState,
+ setEditorState,
+ projectHistory,
+ setSnapGuides,
+ } = useEditorContext();
const currentAbsoluteTime = () =>
editorState.previewTime ?? editorState.playbackTime ?? 0;
@@ -89,6 +97,7 @@ export function TextOverlay(props: TextOverlayProps) {
throttledUpdate.clear();
handleUpdate(finalEvent);
resumeHistory();
+ setSnapGuides([]);
dispose();
}
@@ -195,6 +204,8 @@ function TextSegmentOverlay(props: {
clamp: (value: number, min: number, max: number) => number;
}) {
const segment = createMemo(() => normalizeSegment(props.segment));
+ const { setSnapGuides } = useEditorContext();
+ const snapTargetsFor = useCanvasSnapTargets();
let hiddenMeasureRef: HTMLDivElement | undefined;
const [mounted, setMounted] = createSignal(false);
const [isResizing, setIsResizing] = createSignal(false);
@@ -312,17 +323,39 @@ function TextSegmentOverlay(props: {
return {
startPos: { ...seg.center },
startSize: { ...seg.size },
+ targets: snapTargetsFor({ text: props.index }),
};
},
- (e, { startPos }, initialMouse) => {
+ (e, { startPos, startSize, targets }, initialMouse) => {
const dx = (e.clientX - initialMouse.x) / props.size.width;
const dy = (e.clientY - initialMouse.y) / props.size.height;
const minPadding = 0.02;
+ let snapDx = 0;
+ let snapDy = 0;
+ if (e.shiftKey) {
+ setSnapGuides([]);
+ } else {
+ const snap = snapMovingRect(
+ {
+ x: startPos.x + dx - startSize.x / 2,
+ y: startPos.y + dy - startSize.y / 2,
+ w: startSize.x,
+ h: startSize.y,
+ },
+ targets,
+ SNAP_PX / props.size.width,
+ SNAP_PX / props.size.height,
+ );
+ snapDx = snap.dx;
+ snapDy = snap.dy;
+ setSnapGuides(snap.guides);
+ }
+
props.updateSegment((s) => {
- const newX = startPos.x + dx;
- const newY = startPos.y + dy;
+ const newX = startPos.x + dx + snapDx;
+ const newY = startPos.y + dy + snapDy;
const halfW = s.size.x / 2;
const halfH = s.size.y / 2;
diff --git a/apps/desktop/src/routes/editor/Timeline/SceneTrack.tsx b/apps/desktop/src/routes/editor/Timeline/SceneTrack.tsx
index ac6facf39..9850bfab0 100644
--- a/apps/desktop/src/routes/editor/Timeline/SceneTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/SceneTrack.tsx
@@ -82,6 +82,8 @@ export function SceneTrack(props: {
return <IconLucideEyeOff class="size-3.5" />;
case "splitScreen":
return <IconLucideColumns2 class="size-3.5" />;
+ case "floating":
+ return <IconLucidePanelRight class="size-3.5" />;
default:
return <IconLucideMonitor class="size-3.5" />;
}
@@ -95,6 +97,8 @@ export function SceneTrack(props: {
return "Hide Camera";
case "splitScreen":
return "Split Screen";
+ case "floating":
+ return "Floating";
default:
return "Default";
}
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 5114e45e3..a4a7d9f60 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -27,7 +27,7 @@ import {
normalizeCaptionSettings,
} from "~/store/captions";
import { defaultKeyboardSettings } from "~/store/keyboard";
-
+import { createTauriEventListener } from "~/utils/createEventListener";
import { createPresets } from "~/utils/createPresets";
import { createCustomDomainQuery } from "~/utils/queries";
import {
@@ -40,6 +40,7 @@ import {
commands,
type EditorPreviewQuality,
events,
+ type FrameLayoutEvent,
type FramesRendered,
type ImportedAudioTrack,
type MultipleSegments,
@@ -59,6 +60,7 @@ import {
} from "./audio";
import { deriveCaptionTrackSegments, mapEditedTimeToSource } from "./captions";
import type { MaskSegment } from "./masks";
+import type { SnapGuide } from "./snapping";
import type { TextSegment } from "./text";
import {
getUsedTrackCount,
@@ -1006,6 +1008,10 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
previewTime: null as number | null,
playbackTime: 0,
playing: false,
+ // On-canvas selection of the screen recording / camera boxes.
+ // Kept separate from timeline.selection, which drives the sidebar
+ // selection panel and is pattern-matched by many consumers.
+ canvasSelection: null as null | { type: "display" } | { type: "camera" },
captions: {
isGenerating: false,
isDownloading: false,
@@ -1080,6 +1086,10 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
},
});
+ // Active smart-guide lines while an overlay drag is snapping; published
+ // by whichever overlay owns the drag, rendered once above the canvas.
+ const [snapGuides, setSnapGuides] = createSignal<SnapGuide[]>([]);
+
// Plain signals, not resources: audio decodes in the background after
// the editor opens, so these can resolve late — they must never suspend
// the editor UI back to the skeleton. Waveforms simply appear once
@@ -1271,6 +1281,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
projectHistory: createStoreHistory(project, setProject),
editorState,
setEditorState,
+ snapGuides,
+ setSnapGuides,
totalDuration,
zoomOutLimit,
exportState,
@@ -1338,6 +1350,12 @@ export type TransformedMeta = ReturnType<typeof transformMeta>;
const createEditorInstanceContext = () => {
const [latestFrame, setLatestFrame] = createLazySignal<FrameData>();
+ // Rendered display/camera placement of the latest preview frame, emitted
+ // by the renderer so on-canvas overlays hit-test exactly what was drawn.
+ const [latestFrameLayout, setLatestFrameLayout] =
+ createSignal<FrameLayoutEvent | null>(null);
+ createTauriEventListener(events.frameLayoutEvent, setLatestFrameLayout);
+
const [_isConnected, setIsConnected] = createSignal(false);
const [isWorkerReady, setIsWorkerReady] = createSignal(false);
const [canvasControls, setCanvasControls] =
@@ -1433,6 +1451,7 @@ const createEditorInstanceContext = () => {
editorInstance,
refetchEditorInstance,
latestFrame,
+ latestFrameLayout,
presets: createPresets(),
metaQuery,
isWorkerReady,
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 27caab900..4f2f6b9f5 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -478,6 +478,7 @@ devicesUpdated: DevicesUpdated,
downloadProgress: DownloadProgress,
editorRecordingAdded: EditorRecordingAdded,
editorStateChanged: EditorStateChanged,
+frameLayoutEvent: FrameLayoutEvent,
newNotification: NewNotification,
newScreenshotAdded: NewScreenshotAdded,
newStudioRecordingAdded: NewStudioRecordingAdded,
@@ -505,6 +506,7 @@ devicesUpdated: "devices-updated",
downloadProgress: "download-progress",
editorRecordingAdded: "editor-recording-added",
editorStateChanged: "editor-state-changed",
+frameLayoutEvent: "frame-layout-event",
newNotification: "new-notification",
newScreenshotAdded: "new-screenshot-added",
newStudioRecordingAdded: "new-studio-recording-added",
@@ -594,10 +596,20 @@ export type AutomationTestReport = { ruleId: string; ruleName: string; actionChe
export type AutomationsStore = { version?: number; rules?: AutomationRule[] }
export type BackgroundBlurConfig = { mode: BackgroundBlurMode }
export type BackgroundBlurMode = "off" | "light" | "heavy"
-export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; roundingType: CornerStyle; inset: number; crop: Crop | null; shadow: number; advancedShadow: ShadowConfiguration | null; border: BorderConfiguration | null }
+export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; roundingType: CornerStyle; inset: number; crop: Crop | null;
+/**
+ * Normalized (0-1) center of the display rect in output-frame space.
+ * `None` keeps the display centered.
+ */
+displayPosition: XY<number> | null; shadow: number; advancedShadow: ShadowConfiguration | null; border: BorderConfiguration | null }
export type BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number]; alpha?: number } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number; noise_intensity?: number | null; noise_scale?: number | null; animated?: boolean | null; animation_speed?: number | null }
export type BorderConfiguration = { enabled: boolean; width: number; color: [number, number, number]; opacity: number }
-export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoomSize: number | null; rounding: number; shadow: number; advancedShadow: ShadowConfiguration | null; shape: CameraShape; roundingType: CornerStyle; scaleDuringZoom?: number; backgroundBlur?: BackgroundBlurConfig }
+export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition;
+/**
+ * Normalized (0-1) center of the camera rect in output-frame space.
+ * Overrides `position` when set.
+ */
+manualPosition: XY<number> | null; size: number; zoomSize: number | null; rounding: number; shadow: number; advancedShadow: ShadowConfiguration | null; shape: CameraShape; roundingType: CornerStyle; scaleDuringZoom?: number; backgroundBlur?: BackgroundBlurConfig }
export type CameraDeviceSettings = { width: number | null; height: number | null; frameRate: number | null }
export type CameraFormatInfo = { width: number; height: number; frameRate: number }
export type CameraInfo = { device_id: string; model_id: ModelIDType | null; display_name: string }
@@ -668,6 +680,11 @@ export type ExportProfile = { format: ExportFormat; fps?: number; resolutionBase
export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ format: "Gif" } & GifExportSettings) | ({ format: "Mov" } & MovExportSettings)
export type FileType = "recording" | "screenshot"
export type Flags = { captions: boolean }
+/**
+ * Rendered display/camera placement of the latest preview frame, in
+ * output-frame pixels — consumed by the editor's on-canvas layout overlay.
+ */
+export type FrameLayoutEvent = { display: [number, number, number, number]; camera: [number, number, number, number] | null; output_width: number; output_height: number }
export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }
export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; captureKeyboardEvents?: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number; defaultProjectNameTemplate?: string | null; crashRecoveryRecording?: boolean; maxFps?: number; transcriptionHints?: string[]; editorPreviewQuality?: EditorPreviewQuality; studioRecordingQuality?: StudioRecordingQuality; mainWindowPosition?: WindowPosition | null; cameraWindowPosition?: WindowPosition | null; cameraWindowPositionsByMonitorName?: { [key in string]: WindowPosition }; hasCompletedOnboarding?: boolean; enableTelemetry?: boolean; outOfProcessMuxer?: boolean; recordingsPath?: string | null }
export type GifExportSettings = { fps: number; resolution_base: XY<number>; quality: GifQuality | null }
@@ -761,7 +778,13 @@ export type RequestScrollToSettingsSection = { section: string }
export type RequestSetTargetMode = { target_mode: RecordingTargetMode | null; display_id: string | null }
export type RequestStartRecording = { mode: RecordingMode }
export type S3UploadMeta = { id: string }
-export type SceneMode = "default" | "cameraOnly" | "hideCamera" | "splitScreen"
+export type SceneMode = "default" | "cameraOnly" | "hideCamera" | "splitScreen" |
+/**
+ * Like [`SceneMode::SplitScreen`], but the screen and camera render as
+ * padded, rounded, shadowed cards floating over the background instead
+ * of full-bleed halves. Shares [`SplitLayout`] for per-pane pan/zoom.
+ */
+"floating"
export type SceneSegment = { start: number; end: number; mode?: SceneMode; splitLayout?: SplitLayout | null; transitionIn?: number; transitionOut?: number }
export type ScreenCaptureTarget = { variant: "window"; id: WindowId } | { variant: "display"; id: DisplayId } | { variant: "area"; screen: DisplayId; bounds: LogicalBounds } | { variant: "cameraOnly" }
export type ScreenMovementSpring = { stiffness: number; damping: number; mass: number }
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 743b944a3..d9b0e0c07 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -3,8 +3,8 @@ use std::time::Instant;
use cap_project::{CursorEvents, ProjectConfiguration};
use cap_rendering::{
- DecodedSegmentFrames, FrameRenderer, Nv12RenderedFrame, ProjectUniforms, RenderVideoConstants,
- RenderedFrame, RendererLayers,
+ DecodedSegmentFrames, FrameLayout, FrameRenderer, Nv12RenderedFrame, ProjectUniforms,
+ RenderVideoConstants, RenderedFrame, RendererLayers,
};
use tokio::sync::{mpsc, oneshot};
@@ -35,9 +35,11 @@ pub enum EditorFrameOutput {
pub type RendererLayersReceiver = oneshot::Receiver<RendererLayers>;
+pub type EditorFrameCallback = Box<dyn FnMut(EditorFrameOutput, FrameLayout) + Send>;
+
pub struct Renderer {
rx: mpsc::Receiver<RendererMessage>,
- frame_cb: Box<dyn FnMut(EditorFrameOutput) + Send>,
+ frame_cb: EditorFrameCallback,
render_constants: Arc<RenderVideoConstants>,
layers_rx: RendererLayersReceiver,
telemetry: Option<PlaybackTelemetry>,
@@ -84,7 +86,7 @@ pub async fn finish_renderer_layers_creation(
impl Renderer {
pub fn spawn(
render_constants: Arc<RenderVideoConstants>,
- frame_cb: Box<dyn FnMut(EditorFrameOutput) + Send>,
+ frame_cb: EditorFrameCallback,
layers_rx: RendererLayersReceiver,
) -> Result<RendererHandle, String> {
Self::spawn_with_telemetry(render_constants, frame_cb, layers_rx, None)
@@ -92,7 +94,7 @@ impl Renderer {
pub fn spawn_with_telemetry(
render_constants: Arc<RenderVideoConstants>,
- frame_cb: Box<dyn FnMut(EditorFrameOutput) + Send>,
+ frame_cb: EditorFrameCallback,
layers_rx: RendererLayersReceiver,
telemetry: Option<PlaybackTelemetry>,
) -> Result<RendererHandle, String> {
@@ -242,6 +244,7 @@ impl Renderer {
let render_start = Instant::now();
let input_frame_number = current.uniforms.frame_number;
+ let frame_layout = current.uniforms.frame_layout();
match frame_renderer
.render_immediate_with_timings(
current.segment_frames,
@@ -257,7 +260,7 @@ impl Renderer {
let frame_number = frame.frame_number;
let output_format = PlaybackRenderOutputFormat::Rgba;
let callback_start = Instant::now();
- (frame_cb)(EditorFrameOutput::Rgba(frame));
+ (frame_cb)(EditorFrameOutput::Rgba(frame), frame_layout);
let callback_duration = callback_start.elapsed();
if let Some(telemetry) = &telemetry {
telemetry.emit(PlaybackTelemetryEvent::RendererFrame {
diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rs
index 6b4dfd1bd..726bfa70b 100644
--- a/crates/editor/src/lib.rs
+++ b/crates/editor/src/lib.rs
@@ -10,9 +10,10 @@ pub use audio::{AudioRenderer, MusicTracks};
pub use audio_output::{
AudioOutput, HEADLESS_BLOCK_FRAMES, HEADLESS_CHANNELS, HEADLESS_SAMPLE_RATE, HeadlessAudioTap,
};
+pub use cap_rendering::FrameLayout;
pub use editor::{
- EditorFrameOutput, Renderer, RendererHandle, finish_renderer_layers_creation,
- start_renderer_layers_creation,
+ EditorFrameCallback, EditorFrameOutput, Renderer, RendererHandle,
+ finish_renderer_layers_creation, start_renderer_layers_creation,
};
pub use editor_instance::{
AudioLoader, EditorInstance, EditorState, SegmentMedia, create_segments,
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 414bc3226..06c317ec5 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -238,6 +238,9 @@ pub struct BackgroundConfiguration {
pub rounding_type: CornerStyle,
pub inset: u32,
pub crop: Option<Crop>,
+ /// Normalized (0-1) center of the display rect in output-frame space.
+ /// `None` keeps the display centered.
+ pub display_position: Option<XY<f64>>,
pub shadow: f32,
pub advanced_shadow: Option<ShadowConfiguration>,
pub border: Option<BorderConfiguration>,
@@ -264,6 +267,7 @@ impl Default for BackgroundConfiguration {
rounding_type: CornerStyle::default(),
inset: 0,
crop: None,
+ display_position: None,
shadow: 73.6,
advanced_shadow: Some(ShadowConfiguration::default()),
border: None, // Border is disabled by default for backwards compatibility
@@ -330,6 +334,9 @@ pub struct Camera {
pub hide: bool,
pub mirror: bool,
pub position: CameraPosition,
+ /// Normalized (0-1) center of the camera rect in output-frame space.
+ /// Overrides `position` when set.
+ pub manual_position: Option<XY<f64>>,
pub size: f32,
#[serde(alias = "zoom_size")]
pub zoom_size: Option<f32>,
@@ -374,6 +381,7 @@ impl Default for Camera {
hide: false,
mirror: false,
position: CameraPosition::default(),
+ manual_position: None,
size: 30.0,
zoom_size: Some(Self::default_zoom_size()),
rounding: Self::default_rounding(),
@@ -824,6 +832,10 @@ pub enum SceneMode {
CameraOnly,
HideCamera,
SplitScreen,
+ /// Like [`SceneMode::SplitScreen`], but the screen and camera render as
+ /// padded, rounded, shadowed cards floating over the background instead
+ /// of full-bleed halves. Shares [`SplitLayout`] for per-pane pan/zoom.
+ Floating,
}
#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug)]
@@ -1527,4 +1539,136 @@ mod tests {
assert_eq!(config.cursor.motion_blur, 1.0);
assert_eq!(config.screen_motion_blur, 1.0);
}
+
+ #[test]
+ fn load_without_manual_positions_defaults_to_none() {
+ let dir = tempfile::tempdir().unwrap();
+
+ let mut value = serde_json::to_value(ProjectConfiguration::default()).unwrap();
+ let object = value.as_object_mut().unwrap();
+ object
+ .get_mut("camera")
+ .unwrap()
+ .as_object_mut()
+ .unwrap()
+ .remove("manualPosition");
+ object
+ .get_mut("background")
+ .unwrap()
+ .as_object_mut()
+ .unwrap()
+ .remove("displayPosition");
+ std::fs::write(
+ dir.path().join("project-config.json"),
+ serde_json::to_string(&value).unwrap(),
+ )
+ .unwrap();
+
+ let config = ProjectConfiguration::load(dir.path()).unwrap();
+
+ assert!(config.camera.manual_position.is_none());
+ assert!(config.background.display_position.is_none());
+ }
+
+ #[test]
+ fn manual_positions_round_trip() {
+ let dir = tempfile::tempdir().unwrap();
+
+ let mut config = ProjectConfiguration::default();
+ config.camera.manual_position = Some(XY::new(0.25, 0.75));
+ config.background.display_position = Some(XY::new(0.5, 0.4));
+ std::fs::write(
+ dir.path().join("project-config.json"),
+ serde_json::to_string(&config).unwrap(),
+ )
+ .unwrap();
+
+ let loaded = ProjectConfiguration::load(dir.path()).unwrap();
+
+ assert_eq!(loaded.camera.manual_position, Some(XY::new(0.25, 0.75)));
+ assert_eq!(loaded.background.display_position, Some(XY::new(0.5, 0.4)));
+ }
+
+ #[test]
+ fn legacy_config_without_motion_rework_fields_resolves_defaults() {
+ let dir = tempfile::tempdir().unwrap();
+
+ // Hand-written pre-rework project-config.json: zoom segments carry
+ // only start/end/amount/mode (no glideDirection / glideSpeed /
+ // instantAnimation / edgeSnapRatio), the cursor uses the old spring
+ // triple, and the camera uses the position enum.
+ let legacy_json = r#"{
+ "camera": {
+ "hide": false,
+ "mirror": false,
+ "position": { "x": "left", "y": "top" },
+ "size": 25.0
+ },
+ "cursor": {
+ "animationStyle": "custom",
+ "tension": 120.0,
+ "mass": 2.0,
+ "friction": 32.0
+ },
+ "timeline": {
+ "segments": [
+ { "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 10.0 }
+ ],
+ "zoomSegments": [
+ { "start": 1.0, "end": 3.0, "amount": 2.0, "mode": "auto" },
+ {
+ "start": 5.0,
+ "end": 7.0,
+ "amount": 1.5,
+ "mode": { "manual": { "x": 0.25, "y": 0.75 } }
+ }
+ ]
+ }
+ }"#;
+ std::fs::write(dir.path().join("project-config.json"), legacy_json).unwrap();
+
+ let config = ProjectConfiguration::load(dir.path()).unwrap();
+
+ let timeline = config.timeline.as_ref().expect("timeline should load");
+ assert_eq!(timeline.zoom_segments.len(), 2);
+ for segment in &timeline.zoom_segments {
+ assert_eq!(segment.glide_direction, GlideDirection::None);
+ assert_eq!(segment.glide_speed, 0.5);
+ assert!(!segment.instant_animation);
+ assert_eq!(segment.edge_snap_ratio, 0.25);
+ }
+ assert!(matches!(timeline.zoom_segments[0].mode, ZoomMode::Auto));
+ assert!(matches!(
+ timeline.zoom_segments[1].mode,
+ ZoomMode::Manual { x, y }
+ if (x - 0.25).abs() < f32::EPSILON && (y - 0.75).abs() < f32::EPSILON
+ ));
+
+ // The old cursor spring triple survives untouched.
+ assert_eq!(config.cursor.animation_style, CursorAnimationStyle::Custom);
+ assert_eq!(config.cursor.tension, 120.0);
+ assert_eq!(config.cursor.mass, 2.0);
+ assert_eq!(config.cursor.friction, 32.0);
+
+ // The camera position enum still parses.
+ assert!(matches!(config.camera.position.x, CameraXPosition::Left));
+ assert!(matches!(config.camera.position.y, CameraYPosition::Top));
+
+ // Config written back by the load migration must round-trip with the
+ // resolved defaults intact.
+ let reloaded = ProjectConfiguration::load(dir.path()).unwrap();
+ let reloaded_timeline = reloaded.timeline.as_ref().unwrap();
+ assert_eq!(reloaded_timeline.zoom_segments.len(), 2);
+ assert_eq!(reloaded_timeline.zoom_segments[0].glide_speed, 0.5);
+ assert_eq!(reloaded_timeline.zoom_segments[0].edge_snap_ratio, 0.25);
+ assert!(!reloaded_timeline.zoom_segments[0].instant_animation);
+
+ // The screen movement spring (which drives the new zoom timeline)
+ // resolves to its default for legacy configs.
+ let spring = config.screen_movement_spring;
+ let default_spring = ScreenMovementSpring::default();
+ assert_eq!(spring.stiffness, default_spring.stiffness);
+ assert_eq!(spring.damping, default_spring.damping);
+ assert_eq!(spring.mass, default_spring.mass);
+ }
}
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index 3b683c1a0..b5706b13b 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -103,6 +103,7 @@ declare global {
const IconLucideMove: typeof import('~icons/lucide/move.jsx')['default']
const IconLucideMusic: typeof import('~icons/lucide/music.jsx')['default']
const IconLucideMusic2: typeof import('~icons/lucide/music2.jsx')['default']
+ const IconLucidePanelRight: typeof import('~icons/lucide/panel-right.jsx')['default']
const IconLucidePause: typeof import('~icons/lucide/pause.jsx')['default']
const IconLucidePencil: typeof import('~icons/lucide/pencil.jsx')['default']
const IconLucidePersonStanding: typeof import('~icons/lucide/person-standing.jsx')['default']