Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add text overlay and timeline track to editor

Richie McIlroy5ca1132a84f3
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index af9b13617..2794eefc0 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1706,6 +1706,7 @@ fn project_config_from_recording(
zoom_segments,
scene_segments: Vec::new(),
mask_segments: Vec::new(),
+ text_segments: Vec::new(),
});
config
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index e2b1d74cf..e2e24332f 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -58,10 +58,12 @@ import IconLucideGrid from "~icons/lucide/grid";
import IconLucideMonitor from "~icons/lucide/monitor";
import IconLucideMoon from "~icons/lucide/moon";
import IconLucideMove from "~icons/lucide/move";
+import IconLucidePalette from "~icons/lucide/palette";
import IconLucideRabbit from "~icons/lucide/rabbit";
import IconLucideScan from "~icons/lucide/scan";
import IconLucideSparkles from "~icons/lucide/sparkles";
import IconLucideTimer from "~icons/lucide/timer";
+import IconLucideType from "~icons/lucide/type";
import IconLucideWind from "~icons/lucide/wind";
import { CaptionsTab } from "./CaptionsTab";
import { type CornerRoundingType, useEditorContext } from "./context";
@@ -73,6 +75,7 @@ import {
} from "./projectConfig";
import ShadowSettings from "./ShadowSettings";
import { TextInput } from "./TextInput";
+import type { TextSegment } from "./text";
import {
ComingSoonTooltip,
EditorButton,
@@ -384,7 +387,7 @@ export function ConfigSidebar() {
meta().type === "multiple" && (meta() as any).segments[0].cursor
),
},
- window.FLAGS.captions && {
+ {
id: "captions" as const,
icon: IconCapMessageBubble,
},
@@ -790,6 +793,73 @@ export function ConfigSidebar() {
<Show when={editorState.timeline.selection}>
{(selection) => (
<Suspense>
+ <Show
+ when={(() => {
+ const textSelection = selection();
+ if (textSelection.type !== "text") return;
+
+ const segments = textSelection.indices
+ .map((index) => ({
+ index,
+ segment: project.timeline?.textSegments?.[index],
+ }))
+ .filter(
+ (item): item is { index: number; segment: TextSegment } =>
+ item.segment !== undefined,
+ );
+
+ if (segments.length === 0) {
+ setEditorState("timeline", "selection", null);
+ return;
+ }
+ return { selection: textSelection, segments };
+ })()}
+ >
+ {(value) => (
+ <div class="space-y-4">
+ <div class="flex flex-row justify-between items-center">
+ <div class="flex gap-2 items-center">
+ <EditorButton
+ onClick={() =>
+ setEditorState("timeline", "selection", null)
+ }
+ leftIcon={<IconLucideCheck />}
+ >
+ Done
+ </EditorButton>
+ <span class="text-sm text-gray-10">
+ {value().segments.length} text{" "}
+ {value().segments.length === 1
+ ? "segment"
+ : "segments"}{" "}
+ selected
+ </span>
+ </div>
+ <EditorButton
+ variant="danger"
+ onClick={() =>
+ projectActions.deleteTextSegments(
+ value().segments.map((s) => s.index),
+ )
+ }
+ leftIcon={<IconCapTrash />}
+ >
+ Delete
+ </EditorButton>
+ </div>
+ <For each={value().segments}>
+ {(item) => (
+ <div class="p-4 rounded-lg border border-gray-200">
+ <TextSegmentConfig
+ segment={item.segment}
+ segmentIndex={item.index}
+ />
+ </div>
+ )}
+ </For>
+ </div>
+ )}
+ </Show>
<Show
when={(() => {
const maskSelection = selection();
@@ -2380,6 +2450,320 @@ function CornerStyleSelect(props: {
);
}
+const TEXT_FONT_OPTIONS = [
+ { value: "sans-serif", label: "Sans" },
+ { value: "serif", label: "Serif" },
+ { value: "monospace", label: "Monospace" },
+ { value: "Inter", label: "Inter" },
+ { value: "Geist Sans", label: "Geist Sans" },
+];
+
+const normalizeHexInput = (value: string, fallback: string) => {
+ const trimmed = value.trim();
+ const withHash = trimmed.startsWith("#") ? trimmed : `#${trimmed}`;
+ const shortMatch = /^#[0-9A-Fa-f]{3}$/.test(withHash);
+ if (shortMatch) {
+ const [, r, g, b] = withHash;
+ return `#${r}${r}${g}${g}${b}${b}`.toLowerCase();
+ }
+ const fullMatch = /^#[0-9A-Fa-f]{6}$/.test(withHash);
+ if (fullMatch) return withHash.toLowerCase();
+ return fallback;
+};
+
+function HexColorInput(props: {
+ value: string;
+ onChange: (value: string) => void;
+}) {
+ const [text, setText] = createWritableMemo(() => props.value);
+ let prevColor = props.value;
+ let colorInput: HTMLInputElement | undefined;
+
+ return (
+ <div class="flex items-center gap-3">
+ <button
+ type="button"
+ class="w-10 h-10 rounded-md border border-gray-4"
+ style={{ "background-color": text() }}
+ onClick={() => {
+ const input = colorInput as
+ | (HTMLInputElement & { showPicker?: () => void })
+ | undefined;
+ input?.showPicker?.();
+ input?.click();
+ }}
+ />
+ <input
+ ref={(el) => {
+ colorInput = el;
+ }}
+ type="color"
+ class="absolute w-0 h-0 opacity-0"
+ value={text()}
+ onInput={(e) => {
+ const next = e.currentTarget.value;
+ setText(next);
+ prevColor = next;
+ props.onChange(next);
+ }}
+ />
+ <TextInput
+ class="flex-1 px-3 py-2 rounded-lg border border-gray-3 bg-gray-2 text-sm text-gray-12"
+ value={text()}
+ onFocus={() => {
+ prevColor = props.value;
+ }}
+ onInput={(e) => {
+ setText(e.currentTarget.value);
+ }}
+ onBlur={(e) => {
+ const next = normalizeHexInput(e.currentTarget.value, prevColor);
+ setText(next);
+ prevColor = next;
+ props.onChange(next);
+ }}
+ />
+ </div>
+ );
+}
+
+function TextSegmentConfig(props: {
+ segmentIndex: number;
+ segment: TextSegment;
+}) {
+ const { setProject } = useEditorContext();
+ const clampNumber = (value: number, min: number, max: number) =>
+ Math.min(Math.max(Number.isFinite(value) ? value : min), max);
+ const textFontOptions = createMemo(() => {
+ const font = props.segment.fontFamily;
+ if (!font) return TEXT_FONT_OPTIONS;
+ const exists = TEXT_FONT_OPTIONS.some((option) => option.value === font);
+ return exists
+ ? TEXT_FONT_OPTIONS
+ : [...TEXT_FONT_OPTIONS, { value: font, label: font }];
+ });
+
+ const selectedFont = createMemo(
+ () =>
+ textFontOptions().find(
+ (option) => option.value === props.segment.fontFamily,
+ ) ?? textFontOptions()[0],
+ );
+
+ const updateSegment = (fn: (segment: TextSegment) => void) => {
+ setProject(
+ "timeline",
+ "textSegments",
+ produce((segments) => {
+ const target = segments?.[props.segmentIndex];
+ if (!target) return;
+ fn(target);
+ }),
+ );
+ };
+
+ return (
+ <div class="space-y-4">
+ <Field
+ name={`Text ${props.segmentIndex + 1}`}
+ icon={<IconLucideType class="size-4" />}
+ >
+ <div class="flex items-center gap-3">
+ <textarea
+ class="flex-1 px-3 py-2 rounded-lg border border-gray-3 bg-gray-2 text-gray-12 resize-none min-h-[80px]"
+ value={props.segment.content}
+ onInput={(e) =>
+ updateSegment((segment) => {
+ segment.content = e.currentTarget.value;
+ })
+ }
+ />
+ <div class="flex flex-col items-center gap-2">
+ <span class="text-xs text-gray-11">Enabled</span>
+ <Toggle
+ checked={props.segment.enabled}
+ onChange={(value) =>
+ updateSegment((segment) => {
+ segment.enabled = value;
+ })
+ }
+ />
+ </div>
+ </div>
+ </Field>
+ <Field name="Font" icon={<IconLucideType class="size-4" />}>
+ <div class="grid grid-cols-2 gap-3">
+ <KSelect<{ label: string; value: string }>
+ options={textFontOptions()}
+ optionValue="value"
+ optionTextValue="label"
+ value={selectedFont()}
+ onChange={(option) => {
+ if (option) {
+ updateSegment((segment) => {
+ segment.fontFamily = option.value;
+ });
+ }
+ }}
+ itemComponent={(selectProps) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={selectProps.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {selectProps.item.rawValue.label}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-9 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
+ <KSelect.Value<{
+ label: string;
+ value: string;
+ }> class="flex-1 text-sm text-left truncate text-[--gray-500] font-normal">
+ {(state) => <span>{state.selectedOption().label}</span>}
+ </KSelect.Value>
+ <KSelect.Icon<ValidComponent>
+ as={(selectProps) => (
+ <IconCapChevronDown
+ {...selectProps}
+ class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]"
+ />
+ )}
+ />
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={cx(topSlideAnimateClasses, "z-50")}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="overflow-y-auto max-h-40"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </div>
+ </Field>
+ <Field name="Size" icon={<IconCapEnlarge class="size-4" />}>
+ <Slider
+ value={[clampNumber(props.segment.fontSize, 8, 200)]}
+ onChange={([value]) =>
+ updateSegment((segment) => {
+ segment.fontSize = clampNumber(value, 8, 200);
+ })
+ }
+ minValue={8}
+ maxValue={200}
+ step={1}
+ />
+ </Field>
+ <Field name="Font Weight" icon={<IconLucideSparkles class="size-4" />}>
+ <div class="flex flex-col gap-2">
+ <KSelect
+ options={[
+ { label: "Thin", value: 100 },
+ { label: "Extra Light", value: 200 },
+ { label: "Light", value: 300 },
+ { label: "Normal", value: 400 },
+ { label: "Medium", value: 500 },
+ { label: "Semi Bold", value: 600 },
+ { label: "Bold", value: 700 },
+ { label: "Extra Bold", value: 800 },
+ { label: "Black", value: 900 },
+ ]}
+ optionValue="value"
+ optionTextValue="label"
+ value={{
+ label: "Custom",
+ value: props.segment.fontWeight,
+ }}
+ onChange={(value) => {
+ if (!value) return;
+ updateSegment((segment) => {
+ segment.fontWeight = value.value;
+ });
+ }}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {props.item.rawValue.label}
+ </KSelect.ItemLabel>
+ <KSelect.ItemIndicator class="ml-auto text-blue-9">
+ <IconCapCircleCheck />
+ </KSelect.ItemIndicator>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="flex w-full items-center justify-between rounded-md border border-gray-3 bg-gray-2 px-3 py-2 text-sm text-gray-12 transition-colors hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:outline-none focus:ring-1 focus:ring-blue-9">
+ <KSelect.Value<any> class="truncate">
+ {(state) => {
+ const selected = state.selectedOption();
+ if (selected) return selected.label;
+ // Find label for current weight
+ const weight = props.segment.fontWeight;
+ const option = [
+ { label: "Thin", value: 100 },
+ { label: "Extra Light", value: 200 },
+ { label: "Light", value: 300 },
+ { label: "Normal", value: 400 },
+ { label: "Medium", value: 500 },
+ { label: "Semi Bold", value: 600 },
+ { label: "Bold", value: 700 },
+ { label: "Extra Bold", value: 800 },
+ { label: "Black", value: 900 },
+ ].find((o) => o.value === weight);
+ return option ? option.label : weight.toString();
+ }}
+ </KSelect.Value>
+ <KSelect.Icon>
+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]" />
+ </KSelect.Icon>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={cx(topSlideAnimateClasses, "z-50")}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="overflow-y-auto max-h-40"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+
+ <div class="flex items-center justify-between pt-1">
+ <span class="text-xs text-gray-11">Italic</span>
+ <Toggle
+ checked={props.segment.italic}
+ onChange={(value) =>
+ updateSegment((segment) => {
+ segment.italic = value;
+ })
+ }
+ />
+ </div>
+ </div>
+ </Field>
+ <Field name="Color" icon={<IconLucidePalette class="size-4" />}>
+ <HexColorInput
+ value={props.segment.color}
+ onChange={(value) =>
+ updateSegment((segment) => {
+ segment.color = value;
+ })
+ }
+ />
+ </Field>
+ </div>
+ );
+}
+
function MaskSegmentConfig(props: {
segmentIndex: number;
segment: MaskSegment;
diff --git a/apps/desktop/src/routes/editor/ExportDialog.tsx b/apps/desktop/src/routes/editor/ExportDialog.tsx
index 354b5aefa..ba88a91f1 100644
--- a/apps/desktop/src/routes/editor/ExportDialog.tsx
+++ b/apps/desktop/src/routes/editor/ExportDialog.tsx
@@ -32,7 +32,7 @@ import Tooltip from "~/components/Tooltip";
import { authStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
import { createSignInMutation } from "~/utils/auth";
-import { exportVideo } from "~/utils/export";
+import { createExportTask } from "~/utils/export";
import { createOrganizationsQuery } from "~/utils/queries";
import {
commands,
@@ -124,6 +124,8 @@ export function ExportDialog() {
refetchMeta,
} = useEditorContext();
+ const projectPath = editorInstance.path;
+
const auth = authStore.createQuery();
const organisations = createOrganizationsQuery();
@@ -137,6 +139,11 @@ export function ExportDialog() {
);
};
+ const isCancellationError = (error: unknown) =>
+ error instanceof SilentError ||
+ error === "Export cancelled" ||
+ (error instanceof Error && error.message === "Export cancelled");
+
const [_settings, setSettings] = makePersisted(
createStore<Settings>({
format: "Mp4",
@@ -169,8 +176,12 @@ export function ExportDialog() {
return ret;
});
- const exportWithSettings = (onProgress: (progress: FramesRendered) => void) =>
- exportVideo(
+ let cancelCurrentExport: (() => void) | null = null;
+
+ const exportWithSettings = (
+ onProgress: (progress: FramesRendered) => void,
+ ) => {
+ const { promise, cancel } = createExportTask(
projectPath,
settings.format === "Mp4"
? {
@@ -193,6 +204,11 @@ export function ExportDialog() {
},
onProgress,
);
+ cancelCurrentExport = cancel;
+ return promise.finally(() => {
+ if (cancelCurrentExport === cancel) cancelCurrentExport = null;
+ });
+ };
const [outputPath, setOutputPath] = createSignal<string | null>(null);
const [isCancelled, setIsCancelled] = createSignal(false);
@@ -205,6 +221,8 @@ export function ExportDialog() {
})
) {
setIsCancelled(true);
+ cancelCurrentExport?.();
+ cancelCurrentExport = null;
setExportState({ type: "idle" });
const path = outputPath();
if (path) {
@@ -217,8 +235,6 @@ export function ExportDialog() {
}
};
- const projectPath = editorInstance.path;
-
const exportEstimates = createQuery(() => ({
// prevents flicker when modifying settings
placeholderData: keepPreviousData,
@@ -260,6 +276,10 @@ export function ExportDialog() {
await commands.copyVideoToClipboard(outputPath);
},
onError: (error) => {
+ if (isCancelled() || isCancellationError(error)) {
+ setExportState(reconcile({ type: "idle" }));
+ return;
+ }
commands.globalMessageDialog(
error instanceof Error ? error.message : "Failed to copy recording",
);
@@ -333,6 +353,10 @@ export function ExportDialog() {
setExportState({ type: "done" });
},
onError: (error) => {
+ if (isCancelled() || isCancellationError(error)) {
+ setExportState({ type: "idle" });
+ return;
+ }
commands.globalMessageDialog(
error instanceof Error
? error.message
@@ -446,6 +470,10 @@ export function ExportDialog() {
setExportState({ type: "done" });
},
onError: (error) => {
+ if (isCancelled() || isCancellationError(error)) {
+ setExportState(reconcile({ type: "idle" }));
+ return;
+ }
console.error(error);
if (!(error instanceof SilentError)) {
commands.globalMessageDialog(
@@ -896,7 +924,7 @@ export function ExportDialog() {
variant="ghost"
size="sm"
onClick={handleCancel}
- class="mt-4 hover:bg-red-9 hover:text-white"
+ class="mt-4 hover:bg-red-500 hover:text-white"
>
Cancel
</Button>
@@ -948,7 +976,7 @@ export function ExportDialog() {
variant="ghost"
size="sm"
onClick={handleCancel}
- class="mt-4 hover:bg-red-9 hover:text-white"
+ class="mt-4 hover:bg-red-500 hover:text-white"
>
Cancel
</Button>
@@ -1030,7 +1058,7 @@ export function ExportDialog() {
variant="ghost"
size="sm"
onClick={handleCancel}
- class="mt-4 hover:bg-red-9 hover:text-white"
+ class="mt-4 hover:bg-red-500 hover:text-white"
>
Cancel
</Button>
@@ -1059,90 +1087,101 @@ export function ExportDialog() {
</Switch>
</div>
</Dialog.Content>
- <Dialog.Footer>
- <Show
- when={
- exportState.action === "upload" &&
- exportState.type === "done"
- }
- >
- <div class="relative">
- <a
- href={meta().sharing?.link}
- target="_blank"
- rel="noreferrer"
- class="block"
- >
+ <Show
+ when={
+ exportState.type === "done" &&
+ (exportState.action === "save" ||
+ exportState.action === "upload")
+ }
+ >
+ <Dialog.Footer>
+ <Show
+ when={
+ exportState.action === "upload" &&
+ exportState.type === "done"
+ }
+ >
+ <div class="relative">
+ <a
+ href={meta().sharing?.link}
+ target="_blank"
+ rel="noreferrer"
+ class="block"
+ >
+ <Button
+ onClick={() => {
+ setCopyPressed(true);
+ setTimeout(() => {
+ setCopyPressed(false);
+ }, 2000);
+ navigator.clipboard.writeText(
+ meta().sharing?.link!,
+ );
+ }}
+ variant="dark"
+ class="flex gap-2 justify-center items-center"
+ >
+ {!copyPressed() ? (
+ <IconCapCopy class="transition-colors duration-200 text-gray-1 size-4 group-hover:text-gray-12" />
+ ) : (
+ <IconLucideCheck class="transition-colors duration-200 text-gray-1 size-4 svgpathanimation group-hover:text-gray-12" />
+ )}
+ <p>Open Link</p>
+ </Button>
+ </a>
+ </div>
+ </Show>
+
+ <Show
+ when={
+ exportState.action === "save" &&
+ exportState.type === "done"
+ }
+ >
+ <div class="flex gap-4 w-full">
<Button
+ variant="dark"
+ class="flex gap-2 items-center"
onClick={() => {
- setCopyPressed(true);
- setTimeout(() => {
- setCopyPressed(false);
- }, 2000);
- navigator.clipboard.writeText(meta().sharing?.link!);
+ const path = outputPath();
+ if (path) {
+ commands.openFilePath(path);
+ }
}}
+ >
+ <IconCapFile class="size-4" />
+ Open File
+ </Button>
+ <Button
variant="dark"
- class="flex gap-2 justify-center items-center"
+ class="flex gap-2 items-center"
+ onClick={async () => {
+ const path = outputPath();
+ if (path) {
+ setClipboardCopyPressed(true);
+ setTimeout(() => {
+ setClipboardCopyPressed(false);
+ }, 2000);
+ await commands.copyVideoToClipboard(path);
+ toast.success(
+ `${
+ settings.format === "Gif" ? "GIF" : "Video"
+ } copied to clipboard`,
+ );
+ }
+ }}
>
- {!copyPressed() ? (
- <IconCapCopy class="transition-colors duration-200 text-gray-1 size-4 group-hover:text-gray-12" />
+ {!clipboardCopyPressed() ? (
+ <IconCapCopy class="size-4" />
) : (
- <IconLucideCheck class="transition-colors duration-200 text-gray-1 size-4 svgpathanimation group-hover:text-gray-12" />
+ <IconLucideCheck class="size-4 svgpathanimation" />
)}
- <p>Open Link</p>
+ Copy to Clipboard
</Button>
- </a>
- </div>
- </Show>
-
- <Show
- when={
- exportState.action === "save" && exportState.type === "done"
- }
- >
- <div class="flex gap-4 w-full">
- <Button
- variant="dark"
- class="flex gap-2 items-center"
- onClick={() => {
- const path = outputPath();
- if (path) {
- commands.openFilePath(path);
- }
- }}
- >
- <IconCapFile class="size-4" />
- Open File
- </Button>
- <Button
- variant="dark"
- class="flex gap-2 items-center"
- onClick={async () => {
- const path = outputPath();
- if (path) {
- setClipboardCopyPressed(true);
- setTimeout(() => {
- setClipboardCopyPressed(false);
- }, 2000);
- await commands.copyVideoToClipboard(path);
- toast.success(
- `${
- settings.format === "Gif" ? "GIF" : "Video"
- } copied to clipboard`,
- );
- }
- }}
- >
- {!clipboardCopyPressed() ? (
- <IconCapCopy class="size-4" />
- ) : (
- <IconLucideCheck class="size-4 svgpathanimation" />
- )}
- Copy to Clipboard
- </Button>
- </div>
- </Show>
- </Dialog.Footer>
+ </div>
+ </Show>
+ </Dialog.Footer>
+ </Show>
</>
);
}}
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index b8f6d95f3..3b7fcc7ef 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -15,6 +15,7 @@ import {
useEditorContext,
} from "./context";
import { MaskOverlay } from "./MaskOverlay";
+import { TextOverlay } from "./TextOverlay";
import {
EditorButton,
MenuItem,
@@ -539,6 +540,7 @@ function PreviewCanvas() {
height={frameHeight()}
/>
<MaskOverlay size={size()} />
+ <TextOverlay size={size()} />
</div>
</div>
);
diff --git a/apps/desktop/src/routes/editor/TextOverlay.tsx b/apps/desktop/src/routes/editor/TextOverlay.tsx
new file mode 100644
index 000000000..d0560003c
--- /dev/null
+++ b/apps/desktop/src/routes/editor/TextOverlay.tsx
@@ -0,0 +1,372 @@
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { cx } from "cva";
+import { createEffect, createMemo, createRoot, on, Show } from "solid-js";
+import { produce } from "solid-js/store";
+
+import { useEditorContext } from "./context";
+import type { TextSegment } from "./text";
+
+type TextOverlayProps = {
+ size: { width: number; height: number };
+};
+
+export function TextOverlay(props: TextOverlayProps) {
+ const { project, setProject, editorState, projectHistory } =
+ useEditorContext();
+
+ const selectedText = createMemo(() => {
+ const selection = editorState.timeline.selection;
+ if (!selection || selection.type !== "text") return;
+ const index = selection.indices[0];
+ const segment = project.timeline?.textSegments?.[index];
+ if (!segment) return;
+ return { index, segment };
+ });
+
+ const clamp = (value: number, min: number, max: number) =>
+ Math.min(Math.max(value, min), max);
+
+ const updateSegment = (fn: (segment: TextSegment) => void) => {
+ const index = selectedText()?.index;
+ if (index === undefined) return;
+ setProject(
+ "timeline",
+ "textSegments",
+ index,
+ produce((segment) => {
+ if (!segment) return;
+ fn(segment);
+ }),
+ );
+ };
+
+ function createMouseDownDrag<T>(
+ setup: () => T,
+ update: (
+ e: MouseEvent,
+ value: T,
+ initialMouse: { x: number; y: number },
+ ) => void,
+ ) {
+ return (downEvent: MouseEvent) => {
+ downEvent.preventDefault();
+ downEvent.stopPropagation();
+
+ const initial = setup();
+ const initialMouse = { x: downEvent.clientX, y: downEvent.clientY };
+ const resumeHistory = projectHistory.pause();
+
+ function handleUpdate(event: MouseEvent) {
+ update(event, initial, initialMouse);
+ }
+
+ function finish() {
+ resumeHistory();
+ dispose();
+ }
+
+ const dispose = createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: handleUpdate,
+ mouseup: (event) => {
+ handleUpdate(event);
+ finish();
+ },
+ });
+ return dispose;
+ });
+ };
+ }
+
+ return (
+ <Show when={selectedText()}>
+ {(selected) => {
+ const segment = () => selected().segment;
+
+ // Measurement Logic
+ let hiddenMeasureRef: HTMLDivElement | undefined;
+
+ createEffect(
+ on(
+ () => ({
+ content: segment().content,
+ fontFamily: segment().fontFamily,
+ fontSize: segment().fontSize,
+ fontWeight: segment().fontWeight,
+ italic: segment().italic,
+ containerWidth: props.size.width,
+ containerHeight: props.size.height,
+ }),
+ (deps) => {
+ if (!hiddenMeasureRef) return;
+
+ const { width: naturalWidth, height: naturalHeight } =
+ hiddenMeasureRef.getBoundingClientRect();
+
+ if (
+ naturalWidth === 0 ||
+ naturalHeight === 0 ||
+ !deps.containerWidth ||
+ !deps.containerHeight
+ )
+ return;
+
+ // Normalize to [0-1]
+ const normalizedWidth = naturalWidth / deps.containerWidth;
+ const normalizedHeight = naturalHeight / deps.containerHeight;
+
+ const newFontSize = deps.fontSize;
+ const newSizeX = normalizedWidth;
+ const newSizeY = normalizedHeight;
+
+ // Logic simplified: Trust the measurement.
+
+ // Update if significant difference to avoid loops
+ const sizeXDiff = Math.abs(newSizeX - segment().size.x);
+ const sizeYDiff = Math.abs(newSizeY - segment().size.y);
+ // const fontDiff = Math.abs(newFontSize - segment().fontSize); // We aren't changing font size anymore
+
+ if (sizeXDiff > 0.001 || sizeYDiff > 0.001) {
+ updateSegment((s) => {
+ const oldHeight = s.size.y;
+ s.size.x = newSizeX;
+ s.size.y = newSizeY;
+ // s.fontSize = newFontSize; // Don't override font size
+
+ // Adjust Center Y to keep top anchor fixed (growing down)
+ // If height changes by diff, center moves by diff/2
+ const diff = newSizeY - oldHeight;
+ s.center.y += diff / 2;
+
+ // Frame constraints for center
+ const halfH = s.size.y / 2;
+ const halfW = s.size.x / 2;
+
+ if (s.center.y + halfH > 1) {
+ s.center.y -= s.center.y + halfH - 1;
+ }
+ if (s.center.y - halfH < 0) {
+ s.center.y += 0 - (s.center.y - halfH);
+ }
+ if (s.center.x + halfW > 1) {
+ s.center.x -= s.center.x + halfW - 1;
+ }
+ if (s.center.x - halfW < 0) {
+ s.center.x += 0 - (s.center.x - halfW);
+ }
+ });
+ }
+ },
+ ),
+ );
+
+ const rect = () => {
+ const width = segment().size.x * props.size.width;
+ const height = segment().size.y * props.size.height;
+ const left = segment().center.x * props.size.width - width / 2;
+ const top = segment().center.y * props.size.height - height / 2;
+ return { width, height, left, top };
+ };
+
+ const onMove = createMouseDownDrag(
+ () => ({
+ startPos: { ...segment().center },
+ startSize: { ...segment().size },
+ }),
+ (e, { startPos, startSize }, initialMouse) => {
+ const dx = (e.clientX - initialMouse.x) / props.size.width;
+ const dy = (e.clientY - initialMouse.y) / props.size.height;
+
+ updateSegment((s) => {
+ const newX = startPos.x + dx;
+ const newY = startPos.y + dy;
+
+ // Constrain to frame
+ const halfW = startSize.x / 2;
+ const halfH = startSize.y / 2;
+
+ s.center.x = clamp(newX, halfW, 1 - halfW);
+ s.center.y = clamp(newY, halfH, 1 - halfH);
+ });
+ },
+ );
+
+ const createResizeHandler = (dirX: -1 | 0 | 1, dirY: -1 | 0 | 1) => {
+ return createMouseDownDrag(
+ () => ({
+ startPos: { ...segment().center },
+ startSize: { ...segment().size },
+ startFontSize: segment().fontSize,
+ }),
+ (e, { startPos, startSize, startFontSize }, initialMouse) => {
+ const dx = (e.clientX - initialMouse.x) / props.size.width;
+ const dy = (e.clientY - initialMouse.y) / props.size.height;
+
+ updateSegment((s) => {
+ // If Corner Drag -> Scale (change fontSize and Width)
+ // If Side Drag -> Change Width (reflow)
+
+ const isCorner = dirX !== 0 && dirY !== 0;
+ const isSide = dirX !== 0 && dirY === 0;
+
+ if (isSide) {
+ // Standard resize logic: updates width, keeps center relative or fixed
+ const targetWidth = startSize.x + dx * dirX;
+ const clampedWidth = clamp(targetWidth, 0.05, 1);
+ const appliedDelta = clampedWidth - startSize.x;
+
+ s.size.x = clampedWidth;
+ s.center.x = clamp(
+ startPos.x + (dirX * appliedDelta) / 2,
+ s.size.x / 2,
+ 1 - s.size.x / 2,
+ );
+ } else if (isCorner) {
+ // Scale uniformly
+ const currentWidthPx = startSize.x * props.size.width;
+ const currentHeightPx = startSize.y * props.size.height;
+
+ const deltaPxX = dx * props.size.width * dirX;
+ const deltaPxY = dy * props.size.height * dirY;
+
+ const scaleY = (currentHeightPx + deltaPxY) / currentHeightPx;
+ const scale = scaleY;
+
+ if (scale > 0.1) {
+ s.fontSize = clamp(startFontSize * scale, 8, 400);
+ // Also scale width to maintain aspect ratio of the box
+ s.size.x = clamp(startSize.x * scale, 0.05, 1);
+
+ // Update center
+ const widthDiff = s.size.x - startSize.x;
+ const approxHeightDiff = startSize.y * scale - startSize.y;
+
+ s.center.x = clamp(
+ startPos.x + (widthDiff * dirX) / 2,
+ s.size.x / 2,
+ 1 - s.size.x / 2,
+ );
+ s.center.y = clamp(
+ startPos.y + (approxHeightDiff * dirY) / 2,
+ s.size.y / 2, // Use calculated height for clamping? Approximation
+ 1 - s.size.y / 2,
+ );
+ }
+ }
+ });
+ },
+ );
+ };
+
+ return (
+ <div class="absolute inset-0 pointer-events-none">
+ {/* Hidden Measurement Div */}
+ <div
+ ref={hiddenMeasureRef}
+ style={{
+ position: "absolute",
+ visibility: "hidden",
+ "white-space": "pre-wrap",
+ "word-break": "break-word",
+ "font-family": segment().fontFamily,
+ "font-size": `${segment().fontSize}px`,
+ "font-weight": segment().fontWeight,
+ "font-style": segment().italic ? "italic" : "normal",
+ "line-height": 1.2,
+ // Use fixed width if we want to support wrapping when large?
+ // Or max-width?
+ // If we allow wrapping, we should set max-width to container width.
+ "max-width": `${props.size.width}px`,
+ width: "fit-content",
+ height: "auto",
+ top: "0",
+ left: "0",
+ }}
+ >
+ {segment().content}
+ {/* Ensure height for empty lines if needed, though pre-wrap usually handles it */}
+ {segment().content.endsWith("\n") ? <br /> : null}
+ </div>
+
+ <div
+ class="absolute pointer-events-auto group"
+ style={{
+ left: `${rect().left}px`,
+ top: `${rect().top}px`,
+ width: `${rect().width}px`,
+ height: `${rect().height}px`,
+ }}
+ onMouseDown={onMove}
+ >
+ {/* Visual placeholder (not used for measurement anymore) */}
+ <div
+ style={{
+ "white-space": "pre-wrap",
+ "word-break": "break-word",
+ "font-family": segment().fontFamily,
+ "font-size": `${segment().fontSize}px`,
+ "font-weight": segment().fontWeight,
+ "font-style": segment().italic ? "italic" : "normal",
+ color: segment().color,
+ "line-height": 1.2,
+ width: "100%",
+ height: "100%",
+ display: "flex",
+ "align-items": "center",
+ "justify-content": "center",
+ "text-align": "center",
+ "pointer-events": "none",
+ opacity: 0,
+ }}
+ class="w-full h-full overflow-hidden"
+ >
+ {segment().content}
+ </div>
+
+ <div class="absolute inset-0 rounded-md border-2 border-blue-9 bg-blue-9/10 cursor-move" />
+ <ResizeHandle
+ class="top-0 left-0 -translate-x-1/2 -translate-y-1/2 cursor-nw-resize"
+ onMouseDown={createResizeHandler(-1, -1)}
+ />
+ <ResizeHandle
+ class="top-0 right-0 translate-x-1/2 -translate-y-1/2 cursor-ne-resize"
+ onMouseDown={createResizeHandler(1, -1)}
+ />
+ <ResizeHandle
+ class="bottom-0 left-0 -translate-x-1/2 translate-y-1/2 cursor-sw-resize"
+ onMouseDown={createResizeHandler(-1, 1)}
+ />
+ <ResizeHandle
+ class="bottom-0 right-0 translate-x-1/2 translate-y-1/2 cursor-se-resize"
+ onMouseDown={createResizeHandler(1, 1)}
+ />
+ <ResizeHandle
+ class="left-0 top-1/2 -translate-x-1/2 -translate-y-1/2 cursor-w-resize"
+ onMouseDown={createResizeHandler(-1, 0)}
+ />
+ <ResizeHandle
+ class="right-0 top-1/2 translate-x-1/2 -translate-y-1/2 cursor-e-resize"
+ onMouseDown={createResizeHandler(1, 0)}
+ />
+ </div>
+ </div>
+ );
+ }}
+ </Show>
+ );
+}
+
+function ResizeHandle(props: {
+ class?: string;
+ onMouseDown: (e: MouseEvent) => void;
+}) {
+ return (
+ <div
+ class={cx(
+ "absolute w-3 h-3 bg-blue-9 border border-white rounded-full shadow-sm transition-transform hover:scale-125",
+ props.class,
+ )}
+ onMouseDown={props.onMouseDown}
+ />
+ );
+}
diff --git a/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx b/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
new file mode 100644
index 000000000..88a4c9fac
--- /dev/null
+++ b/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
@@ -0,0 +1,371 @@
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { cx } from "cva";
+import { createMemo, createRoot, For } from "solid-js";
+import { produce } from "solid-js/store";
+
+import { useEditorContext } from "../context";
+import { defaultTextSegment } from "../text";
+import { useTimelineContext } from "./context";
+import { SegmentContent, SegmentHandle, SegmentRoot, TrackRoot } from "./Track";
+
+export type TextSegmentDragState =
+ | { type: "idle" }
+ | { type: "movePending" }
+ | { type: "moving" };
+
+const MIN_SEGMENT_SECS = 1;
+const MIN_SEGMENT_PIXELS = 80;
+
+export function TextTrack(props: {
+ onDragStateChanged: (v: TextSegmentDragState) => void;
+ handleUpdatePlayhead: (e: MouseEvent) => void;
+}) {
+ const {
+ project,
+ setProject,
+ editorState,
+ setEditorState,
+ totalDuration,
+ projectHistory,
+ projectActions,
+ } = useEditorContext();
+ const { secsPerPixel, timelineBounds } = useTimelineContext();
+
+ const minDuration = () =>
+ Math.max(MIN_SEGMENT_SECS, secsPerPixel() * MIN_SEGMENT_PIXELS);
+
+ const textSegments = () => project.timeline?.textSegments ?? [];
+
+ const neighborBounds = (index: number) => {
+ const segments = textSegments();
+ return {
+ prevEnd: segments[index - 1]?.end ?? 0,
+ nextStart: segments[index + 1]?.start ?? totalDuration(),
+ };
+ };
+
+ const findPlacement = (time: number, length: number) => {
+ const gaps: Array<{ start: number; end: number }> = [];
+ const sorted = textSegments()
+ .slice()
+ .sort((a, b) => a.start - b.start);
+
+ let cursor = 0;
+ for (const segment of sorted) {
+ if (segment.start - cursor >= length) {
+ gaps.push({ start: cursor, end: segment.start });
+ }
+ cursor = Math.max(cursor, segment.end);
+ }
+
+ if (totalDuration() - cursor >= length) {
+ gaps.push({ start: cursor, end: totalDuration() });
+ }
+
+ if (gaps.length === 0) return null;
+
+ const maxStart = Math.max(totalDuration() - length, 0);
+ const desiredStart = Math.min(Math.max(time - length / 2, 0), maxStart);
+
+ const containingGap =
+ gaps.find(
+ (gap) => desiredStart >= gap.start && desiredStart + length <= gap.end,
+ ) ??
+ gaps.find((gap) => gap.start >= desiredStart) ??
+ gaps[gaps.length - 1];
+
+ const start = Math.min(
+ Math.max(desiredStart, containingGap.start),
+ containingGap.end - length,
+ );
+
+ return { start, end: start + length };
+ };
+
+ const addSegmentAt = (time: number) => {
+ const length = Math.min(minDuration(), totalDuration());
+ if (length <= 0) return;
+
+ const placement = findPlacement(time, length);
+ if (!placement) return;
+
+ setProject(
+ "timeline",
+ "textSegments",
+ produce((segments) => {
+ segments ??= [];
+ segments.push(defaultTextSegment(placement.start, placement.end));
+ segments.sort((a, b) => a.start - b.start);
+ }),
+ );
+ };
+
+ const handleBackgroundMouseDown = (e: MouseEvent) => {
+ if (e.button !== 0) return;
+ if ((e.target as HTMLElement).closest("[data-text-segment]")) return;
+ const timelineTime =
+ editorState.previewTime ??
+ editorState.playbackTime ??
+ secsPerPixel() * (e.clientX - (timelineBounds.left ?? 0));
+ addSegmentAt(timelineTime);
+ };
+
+ function createMouseDownDrag<T>(
+ segmentIndex: () => number,
+ setup: () => T,
+ update: (e: MouseEvent, value: T, initialMouseX: number) => void,
+ ) {
+ return (downEvent: MouseEvent) => {
+ if (editorState.timeline.interactMode !== "seek") return;
+ downEvent.stopPropagation();
+ const initial = setup();
+ let moved = false;
+ let initialMouseX: number | null = null;
+
+ const resumeHistory = projectHistory.pause();
+ props.onDragStateChanged({ type: "movePending" });
+
+ function finish(e: MouseEvent) {
+ resumeHistory();
+ if (!moved) {
+ e.stopPropagation();
+ const currentSelection = editorState.timeline.selection;
+ const index = segmentIndex();
+ const isMultiSelect = e.ctrlKey || e.metaKey;
+ const isRangeSelect = e.shiftKey;
+
+ if (isRangeSelect && currentSelection?.type === "text") {
+ const existingIndices = currentSelection.indices;
+ const lastIndex = existingIndices[existingIndices.length - 1];
+ const start = Math.min(lastIndex, index);
+ const end = Math.max(lastIndex, index);
+ const rangeIndices: number[] = [];
+ for (let idx = start; idx <= end; idx++) rangeIndices.push(idx);
+ setEditorState("timeline", "selection", {
+ type: "text",
+ indices: rangeIndices,
+ });
+ } else if (isMultiSelect) {
+ if (currentSelection?.type === "text") {
+ const base = currentSelection.indices;
+ const exists = base.includes(index);
+ const next = exists
+ ? base.filter((i) => i !== index)
+ : [...base, index];
+ setEditorState(
+ "timeline",
+ "selection",
+ next.length > 0
+ ? {
+ type: "text",
+ indices: next,
+ }
+ : null,
+ );
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "text",
+ indices: [index],
+ });
+ }
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "text",
+ indices: [index],
+ });
+ }
+ props.handleUpdatePlayhead(e);
+ }
+ props.onDragStateChanged({ type: "idle" });
+ }
+
+ function handleUpdate(event: MouseEvent) {
+ if (Math.abs(event.clientX - downEvent.clientX) > 2) {
+ if (!moved) {
+ moved = true;
+ initialMouseX = event.clientX;
+ props.onDragStateChanged({ type: "moving" });
+ }
+ }
+
+ if (initialMouseX === null) return;
+ update(event, initial, initialMouseX);
+ }
+
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: (e) => handleUpdate(e),
+ mouseup: (e) => {
+ handleUpdate(e);
+ finish(e);
+ dispose();
+ },
+ });
+ });
+ };
+ }
+
+ return (
+ <TrackRoot
+ onMouseEnter={() => setEditorState("timeline", "hoveredTrack", "text")}
+ onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}
+ onMouseDown={handleBackgroundMouseDown}
+ >
+ <For
+ each={textSegments()}
+ fallback={
+ <div class="text-center text-sm text-[--text-tertiary] flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-none">
+ <div>Click to add text</div>
+ <div class="text-[10px] text-[--text-tertiary]/40 mt-0.5">
+ (Set a label over your video)
+ </div>
+ </div>
+ }
+ >
+ {(segment, i) => {
+ const isSelected = createMemo(() => {
+ const selection = editorState.timeline.selection;
+ if (!selection || selection.type !== "text") return false;
+ return selection.indices.includes(i());
+ });
+
+ const segmentWidth = () => segment.end - segment.start;
+
+ return (
+ <SegmentRoot
+ data-text-segment
+ data-index={i()}
+ class={cx(
+ "border duration-200 hover:border-blue-6 transition-colors group",
+ "bg-gradient-to-r from-[#111826] via-[#1c2232] to-[#111826]",
+ isSelected() ? "border-blue-7" : "border-transparent",
+ !segment.enabled && "opacity-60",
+ )}
+ innerClass="ring-blue-6"
+ segment={segment}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ if (editorState.timeline.interactMode === "split") {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const fraction = (e.clientX - rect.left) / rect.width;
+ const splitTime = fraction * segmentWidth();
+ projectActions.splitTextSegment(i(), splitTime);
+ }
+ }}
+ >
+ <SegmentHandle
+ position="start"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const bounds = neighborBounds(i());
+ const start = segment.start;
+ const minValue = bounds.prevEnd;
+ const maxValue = Math.max(
+ minValue,
+ Math.min(
+ segment.end - minDuration(),
+ bounds.nextStart - minDuration(),
+ ),
+ );
+ return { start, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const next = Math.max(
+ value.minValue,
+ Math.min(value.maxValue, value.start + delta),
+ );
+ setProject("timeline", "textSegments", i(), "start", next);
+ setProject(
+ "timeline",
+ "textSegments",
+ produce((items) => {
+ items.sort((a, b) => a.start - b.start);
+ }),
+ );
+ },
+ )}
+ />
+ <SegmentContent
+ class="flex justify-center items-center cursor-grab px-3"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const original = { ...segment };
+ const bounds = neighborBounds(i());
+ const minDelta = bounds.prevEnd - original.start;
+ const maxDelta = bounds.nextStart - original.end;
+ return {
+ original,
+ minDelta,
+ maxDelta,
+ };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const lowerBound = Math.min(value.minDelta, value.maxDelta);
+ const upperBound = Math.max(value.minDelta, value.maxDelta);
+ const clampedDelta = Math.min(
+ upperBound,
+ Math.max(lowerBound, delta),
+ );
+ setProject("timeline", "textSegments", i(), {
+ ...value.original,
+ start: value.original.start + clampedDelta,
+ end: value.original.end + clampedDelta,
+ });
+ setProject(
+ "timeline",
+ "textSegments",
+ produce((items) => {
+ items.sort((a, b) => a.start - b.start);
+ }),
+ );
+ },
+ )}
+ >
+ <div class="flex flex-col gap-0.5 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
+ <span class="opacity-70">Text</span>
+ <div class="flex gap-1 items-center text-md">
+ <span class="max-w-[10rem] truncate">
+ {segment.content || "Label"}
+ </span>
+ </div>
+ </div>
+ </SegmentContent>
+ <SegmentHandle
+ position="end"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const bounds = neighborBounds(i());
+ const end = segment.end;
+ const minValue = segment.start + minDuration();
+ const maxValue = Math.max(minValue, bounds.nextStart);
+ return { end, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const next = Math.max(
+ value.minValue,
+ Math.min(value.maxValue, value.end + delta),
+ );
+ setProject("timeline", "textSegments", i(), "end", next);
+ setProject(
+ "timeline",
+ "textSegments",
+ produce((items) => {
+ items.sort((a, b) => a.start - b.start);
+ }),
+ );
+ },
+ )}
+ />
+ </SegmentRoot>
+ );
+ }}
+ </For>
+ </TrackRoot>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx
index b209729d4..dd39fec1f 100644
--- a/apps/desktop/src/routes/editor/Timeline/index.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx
@@ -23,6 +23,7 @@ import { ClipTrack } from "./ClipTrack";
import { TimelineContextProvider, useTimelineContext } from "./context";
import { type MaskSegmentDragState, MaskTrack } from "./MaskTrack";
import { type SceneSegmentDragState, SceneTrack } from "./SceneTrack";
+import { type TextSegmentDragState, TextTrack } from "./TextTrack";
import { TrackIcon, TrackManager } from "./TrackManager";
import { type ZoomSegmentDragState, ZoomTrack } from "./ZoomTrack";
@@ -32,6 +33,7 @@ const TIMELINE_HEADER_HEIGHT = 32;
const trackIcons: Record<TimelineTrackType, JSX.Element> = {
clip: <IconLucideClapperboard class="size-4" />,
+ text: <IconLucideType class="size-4" />,
mask: <IconLucideBoxSelect class="size-4" />,
zoom: <IconLucideSearch class="size-4" />,
scene: <IconLucideVideo class="size-4" />,
@@ -51,6 +53,12 @@ const trackDefinitions: TrackDefinition[] = [
icon: trackIcons.clip,
locked: true,
},
+ {
+ type: "text",
+ label: "Text",
+ icon: trackIcons.text,
+ locked: false,
+ },
{
type: "mask",
label: "Mask",
@@ -103,12 +111,17 @@ export function Timeline() {
? trackState().scene
: definition.type === "mask"
? trackState().mask
- : true,
+ : definition.type === "text"
+ ? trackState().text
+ : true,
available: definition.type === "scene" ? sceneAvailable() : true,
}));
const sceneTrackVisible = () => trackState().scene && sceneAvailable();
const visibleTrackCount = () =>
- 2 + (trackState().mask ? 1 : 0) + (sceneTrackVisible() ? 1 : 0);
+ 2 +
+ (trackState().text ? 1 : 0) +
+ (trackState().mask ? 1 : 0) +
+ (sceneTrackVisible() ? 1 : 0);
const trackHeight = () => (visibleTrackCount() > 2 ? "3rem" : "3.25rem");
function handleToggleTrack(type: TimelineTrackType, next: boolean) {
@@ -117,6 +130,14 @@ export function Timeline() {
return;
}
+ if (type === "text") {
+ setEditorState("timeline", "tracks", "text", next);
+ if (!next && editorState.timeline.selection?.type === "text") {
+ setEditorState("timeline", "selection", null);
+ }
+ return;
+ }
+
if (type === "mask") {
setEditorState("timeline", "tracks", "mask", next);
if (!next && editorState.timeline.selection?.type === "mask") {
@@ -139,6 +160,7 @@ export function Timeline() {
zoomSegments: [],
sceneSegments: [],
maskSegments: [],
+ textSegments: [],
});
resume();
}
@@ -162,7 +184,9 @@ export function Timeline() {
if (
!project.timeline?.zoomSegments ||
- project.timeline.zoomSegments.length < 1
+ project.timeline.zoomSegments.length < 1 ||
+ !project.timeline?.maskSegments ||
+ !project.timeline?.textSegments
) {
setProject(
produce((project) => {
@@ -177,44 +201,28 @@ export function Timeline() {
zoomSegments: [],
sceneSegments: [],
maskSegments: [],
+ textSegments: [],
};
project.timeline.sceneSegments ??= [];
project.timeline.maskSegments ??= [];
+ project.timeline.textSegments ??= [];
project.timeline.zoomSegments ??= [];
}),
);
}
- if (!project.timeline?.maskSegments) {
- setProject(
- produce((project) => {
- project.timeline ??= {
- segments: [
- {
- start: 0,
- end: duration(),
- timescale: 1,
- },
- ],
- zoomSegments: [],
- sceneSegments: [],
- maskSegments: [],
- };
- project.timeline.maskSegments ??= [];
- }),
- );
- }
-
let zoomSegmentDragState = { type: "idle" } as ZoomSegmentDragState;
let sceneSegmentDragState = { type: "idle" } as SceneSegmentDragState;
let maskSegmentDragState = { type: "idle" } as MaskSegmentDragState;
+ let textSegmentDragState = { type: "idle" } as TextSegmentDragState;
async function handleUpdatePlayhead(e: MouseEvent) {
const { left } = timelineBounds;
if (
zoomSegmentDragState.type !== "moving" &&
sceneSegmentDragState.type !== "moving" &&
- maskSegmentDragState.type !== "moving"
+ maskSegmentDragState.type !== "moving" &&
+ textSegmentDragState.type !== "moving"
) {
// Guard against missing bounds and clamp computed time to [0, totalDuration()]
if (left == null) return;
@@ -251,6 +259,13 @@ export function Timeline() {
createEventListener(window, "keydown", (e) => {
const hasNoModifiers = !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey;
+ if (
+ document.activeElement instanceof HTMLInputElement ||
+ document.activeElement instanceof HTMLTextAreaElement
+ ) {
+ return;
+ }
+
if (e.code === "Backspace" || (e.code === "Delete" && hasNoModifiers)) {
const selection = editorState.timeline.selection;
if (!selection) return;
@@ -259,6 +274,8 @@ export function Timeline() {
projectActions.deleteZoomSegments(selection.indices);
} else if (selection.type === "mask") {
projectActions.deleteMaskSegments(selection.indices);
+ } else if (selection.type === "text") {
+ projectActions.deleteTextSegments(selection.indices);
} else if (selection.type === "clip") {
// Delete all selected clips in reverse order
[...selection.indices]
@@ -485,6 +502,16 @@ export function Timeline() {
handleUpdatePlayhead={handleUpdatePlayhead}
/>
</TrackRow>
+ <Show when={trackState().text}>
+ <TrackRow icon={trackIcons.text}>
+ <TextTrack
+ onDragStateChanged={(v) => {
+ textSegmentDragState = v;
+ }}
+ handleUpdatePlayhead={handleUpdatePlayhead}
+ />
+ </TrackRow>
+ </Show>
<Show when={trackState().mask}>
<TrackRow icon={trackIcons.mask}>
<MaskTrack
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 21a60f6e5..088fab417 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -15,6 +15,7 @@ import {
createSignal,
on,
onCleanup,
+ untrack,
} from "solid-js";
import { createStore, produce, reconcile, unwrap } from "solid-js/store";
@@ -37,6 +38,7 @@ import {
type ZoomSegment,
} from "~/utils/tauri";
import type { MaskSegment } from "./masks";
+import type { TextSegment } from "./text";
import { createProgressBar } from "./utils";
export type CurrentDialog =
@@ -72,7 +74,7 @@ export const getPreviewResolution = (quality: PreviewQuality): XY<number> => {
return { x: width, y: height };
};
-export type TimelineTrackType = "clip" | "zoom" | "scene" | "mask";
+export type TimelineTrackType = "clip" | "text" | "zoom" | "scene" | "mask";
export const MAX_ZOOM_IN = 3;
const PROJECT_SAVE_DEBOUNCE_MS = 250;
@@ -92,10 +94,11 @@ type WithCornerStyle<T> = T & { roundingType: CornerRoundingType };
type EditorTimelineConfiguration = Omit<
TimelineConfiguration,
- "sceneSegments"
+ "sceneSegments" | "maskSegments"
> & {
sceneSegments?: SceneSegment[];
maskSegments: MaskSegment[];
+ textSegments: TextSegment[];
};
export type EditorProjectConfiguration = Omit<
@@ -105,6 +108,7 @@ export type EditorProjectConfiguration = Omit<
background: WithCornerStyle<ProjectConfiguration["background"]>;
camera: WithCornerStyle<ProjectConfiguration["camera"]>;
timeline?: EditorTimelineConfiguration | null;
+ hiddenTextSegments?: number[];
};
function withCornerDefaults<
@@ -133,6 +137,12 @@ export function normalizeProject(
maskSegments?: MaskSegment[];
}
).maskSegments ?? [],
+ textSegments:
+ (
+ config.timeline as TimelineConfiguration & {
+ textSegments?: TextSegment[];
+ }
+ ).textSegments ?? [],
}
: undefined;
@@ -156,6 +166,7 @@ export function serializeProjectConfiguration(
? {
...project.timeline,
maskSegments: project.timeline.maskSegments ?? [],
+ textSegments: project.timeline.textSegments ?? [],
}
: project.timeline;
@@ -317,6 +328,45 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
setEditorState("timeline", "selection", null);
});
},
+ splitTextSegment: (index: number, time: number) => {
+ setProject(
+ "timeline",
+ "textSegments",
+ produce((segments) => {
+ const segment = segments?.[index];
+ if (!segment) return;
+
+ const duration = segment.end - segment.start;
+ const remaining = duration - time;
+ if (time < 1 || remaining < 1) return;
+
+ segments.splice(index + 1, 0, {
+ ...segment,
+ start: segment.start + time,
+ end: segment.end,
+ });
+ segments[index].end = segment.start + time;
+ }),
+ );
+ },
+ deleteTextSegments: (segmentIndices: number[]) => {
+ batch(() => {
+ setProject(
+ "timeline",
+ "textSegments",
+ produce((segments) => {
+ if (!segments) return;
+ const sorted = [...new Set(segmentIndices)]
+ .filter(
+ (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
+ )
+ .sort((a, b) => b - a);
+ for (const i of sorted) segments.splice(i, 1);
+ }),
+ );
+ setEditorState("timeline", "selection", null);
+ });
+ },
splitSceneSegment: (index: number, time: number) => {
setProject(
"timeline",
@@ -389,6 +439,11 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
maskSegment.end += diff(maskSegment.end);
}
+ for (const textSegment of timeline.textSegments) {
+ textSegment.start += diff(textSegment.start);
+ textSegment.end += diff(textSegment.end);
+ }
+
segment.timescale = timescale;
}),
);
@@ -412,7 +467,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
shouldResave = false;
hasPendingProjectSave = false;
try {
- await commands.setProjectConfig(serializeProjectConfiguration(project));
+ const config = serializeProjectConfiguration(project);
+ await commands.setProjectConfig(config);
} catch (error) {
console.error("Failed to persist project config", error);
} finally {
@@ -537,6 +593,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
const initialMaskTrackEnabled =
(project.timeline?.maskSegments?.length ?? 0) > 0;
+ const initialTextTrackEnabled =
+ (project.timeline?.textSegments?.length ?? 0) > 0;
const [editorState, setEditorState] = createStore({
previewTime: null as number | null,
@@ -549,7 +607,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
| { type: "zoom"; indices: number[] }
| { type: "clip"; indices: number[] }
| { type: "scene"; indices: number[] }
- | { type: "mask"; indices: number[] },
+ | { type: "mask"; indices: number[] }
+ | { type: "text"; indices: number[] },
transform: {
// visible seconds
zoom: zoomOutLimit(),
@@ -591,6 +650,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
zoom: true,
scene: true,
mask: initialMaskTrackEnabled,
+ text: initialTextTrackEnabled,
},
hoveredTrack: null as null | TimelineTrackType,
},
diff --git a/apps/desktop/src/routes/editor/text.ts b/apps/desktop/src/routes/editor/text.ts
new file mode 100644
index 000000000..d9cae709c
--- /dev/null
+++ b/apps/desktop/src/routes/editor/text.ts
@@ -0,0 +1,32 @@
+import type { XY } from "~/utils/tauri";
+
+export type TextSegment = {
+ start: number;
+ end: number;
+ enabled: boolean;
+ content: string;
+ center: XY<number>;
+ size: XY<number>;
+ fontFamily: string;
+ fontSize: number;
+ fontWeight: number;
+ italic: boolean;
+ color: string;
+};
+
+export const defaultTextSegment = (
+ start: number,
+ end: number,
+): TextSegment => ({
+ start,
+ end,
+ enabled: true,
+ content: "Text",
+ center: { x: 0.5, y: 0.5 },
+ size: { x: 0.35, y: 0.2 },
+ fontFamily: "sans-serif",
+ fontSize: 48,
+ fontWeight: 700,
+ italic: false,
+ color: "#ffffff",
+});
diff --git a/apps/desktop/src/utils/export.ts b/apps/desktop/src/utils/export.ts
index fd73dbc00..98e262c7d 100644
--- a/apps/desktop/src/utils/export.ts
+++ b/apps/desktop/src/utils/export.ts
@@ -1,7 +1,7 @@
import { Channel } from "@tauri-apps/api/core";
import { commands, type ExportSettings, type FramesRendered } from "./tauri";
-export async function exportVideo(
+export function createExportTask(
projectPath: string,
settings: ExportSettings,
onProgress: (progress: FramesRendered) => void,
@@ -9,5 +9,28 @@ export async function exportVideo(
const progress = new Channel<FramesRendered>((e) => {
onProgress(e);
});
- return await commands.exportVideo(projectPath, progress, settings);
+ let closed = false;
+ const cancel = () => {
+ if (closed) return;
+ closed = true;
+ const internals = (
+ globalThis as {
+ __TAURI_INTERNALS__?: { unregisterCallback?: (id: number) => void };
+ }
+ ).__TAURI_INTERNALS__;
+ internals?.unregisterCallback?.(progress.id);
+ };
+ const promise = commands
+ .exportVideo(projectPath, progress, settings)
+ .finally(cancel);
+ return { promise, cancel };
+}
+
+export async function exportVideo(
+ projectPath: string,
+ settings: ExportSettings,
+ onProgress: (progress: FramesRendered) => void,
+) {
+ const { promise } = createExportTask(projectPath, settings, onProgress);
+ return await promise;
}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 8b076dc2a..81690864d 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -119,6 +119,9 @@ async setPlayheadPosition(frameNumber: number) : Promise<null> {
async setProjectConfig(config: ProjectConfiguration) : Promise<null> {
return await TAURI_INVOKE("set_project_config", { config });
},
+async updateProjectConfigInMemory(config: ProjectConfiguration) : Promise<null> {
+ return await TAURI_INVOKE("update_project_config_in_memory", { config });
+},
async generateZoomSegmentsFromClicks() : Promise<ZoomSegment[]> {
return await TAURI_INVOKE("generate_zoom_segments_from_clicks");
},
@@ -229,57 +232,30 @@ async setCameraPreviewState(state: CameraPreviewState) : Promise<null> {
async awaitCameraPreviewReady() : Promise<boolean> {
return await TAURI_INVOKE("await_camera_preview_ready");
},
-/**
- * Function to handle creating directories for the model
- */
async createDir(path: string, recursive: boolean) : Promise<null> {
return await TAURI_INVOKE("create_dir", { path, recursive });
},
-/**
- * Function to save the model file
- */
async saveModelFile(path: string, data: number[]) : Promise<null> {
return await TAURI_INVOKE("save_model_file", { path, data });
},
-/**
- * Function to transcribe audio from a video file using Whisper
- */
async transcribeAudio(videoPath: string, modelPath: string, language: string) : Promise<CaptionData> {
return await TAURI_INVOKE("transcribe_audio", { videoPath, modelPath, language });
},
-/**
- * Function to save caption data to a file
- */
async saveCaptions(videoId: string, captions: CaptionData) : Promise<null> {
return await TAURI_INVOKE("save_captions", { videoId, captions });
},
-/**
- * Function to load caption data from a file
- */
async loadCaptions(videoId: string) : Promise<CaptionData | null> {
return await TAURI_INVOKE("load_captions", { videoId });
},
-/**
- * Helper function to download a Whisper model from Hugging Face Hub
- */
async downloadWhisperModel(modelName: string, outputPath: string) : Promise<null> {
return await TAURI_INVOKE("download_whisper_model", { modelName, outputPath });
},
-/**
- * Function to check if a model file exists
- */
async checkModelExists(modelPath: string) : Promise<boolean> {
return await TAURI_INVOKE("check_model_exists", { modelPath });
},
-/**
- * Function to delete a downloaded model
- */
async deleteWhisperModel(modelPath: string) : Promise<null> {
return await TAURI_INVOKE("delete_whisper_model", { modelPath });
},
-/**
- * Export captions to an SRT file
- */
async exportCaptionsSrt(videoId: string) : Promise<string | null> {
return await TAURI_INVOKE("export_captions_srt", { videoId });
},
@@ -387,8 +363,9 @@ export type CameraShape = "square" | "source"
export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
export type CaptionData = { segments: CaptionSegment[]; settings: CaptionSettings | null }
-export type CaptionSegment = { id: string; start: number; end: number; text: string }
-export type CaptionSettings = { enabled: boolean; font: string; size: number; color: string; backgroundColor: string; backgroundOpacity: number; position: string; bold: boolean; italic: boolean; outline: boolean; outlineColor: string; exportWithSubtitles: boolean }
+export type CaptionSegment = { id: string; start: number; end: number; text: string; words?: CaptionWord[] }
+export type CaptionSettings = { enabled: boolean; font: string; size: number; color: string; backgroundColor: string; backgroundOpacity: number; position?: string; bold: boolean; italic: boolean; outline: boolean; outlineColor: string; exportWithSubtitles: boolean; highlightColor?: string; fadeDuration?: number }
+export type CaptionWord = { text: string; start: number; end: number }
export type CaptionsData = { segments: CaptionSegment[]; settings: CaptionSettings }
export type CaptureDisplay = { id: DisplayId; name: string; refresh_rate: number }
export type CaptureDisplayWithThumbnail = { id: DisplayId; name: string; refresh_rate: number; thumbnail: string | null }
@@ -503,7 +480,8 @@ export type StereoMode = "stereo" | "monoL" | "monoR"
export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }
export type StudioRecordingStatus = { status: "InProgress" } | { status: "Failed"; error: string } | { status: "Complete" }
export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null }
-export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[] }
+export type TextSegment = { start: number; end: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string }
+export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[] }
export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number }
export type UploadMeta = { state: "MultipartUpload"; video_id: string; file_path: string; pre_created_video: VideoUploadInfo; recording_dir: string } | { state: "SinglePartUpload"; video_id: string; recording_dir: string; file_path: string; screenshot_path: string } | { state: "Failed"; error: string } | { state: "Complete" }
export type UploadMode = { Initial: { pre_created_video: VideoUploadInfo | null } } | "Reupload"
diff --git a/crates/export/src/mp4.rs b/crates/export/src/mp4.rs
index 00276ea43..080c53cb4 100644
--- a/crates/export/src/mp4.rs
+++ b/crates/export/src/mp4.rs
@@ -187,32 +187,41 @@ impl Mp4ExportSettings {
frame_count += 1;
}
+ drop(frame_tx);
+
if let Some(frame) = first_frame {
- let rgb_img = ImageBuffer::<image::Rgb<u8>, Vec<u8>>::from_raw(
- frame.width,
- frame.height,
- frame
- .data
- .chunks(frame.padded_bytes_per_row as usize)
- .flat_map(|row| {
- row[0..(frame.width * 4) as usize]
- .chunks(4)
- .flat_map(|chunk| [chunk[0], chunk[1], chunk[2]])
- })
- .collect::<Vec<_>>(),
- )
- .expect("Failed to create image from frame data");
+ let project_path = project_path.clone();
+ let screenshot_task = tokio::task::spawn_blocking(move || {
+ let rgb_img = ImageBuffer::<image::Rgb<u8>, Vec<u8>>::from_raw(
+ frame.width,
+ frame.height,
+ frame
+ .data
+ .chunks(frame.padded_bytes_per_row as usize)
+ .flat_map(|row| {
+ row[0..(frame.width * 4) as usize]
+ .chunks(4)
+ .flat_map(|chunk| [chunk[0], chunk[1], chunk[2]])
+ })
+ .collect::<Vec<_>>(),
+ );
+
+ let Some(rgb_img) = rgb_img else {
+ return;
+ };
- let screenshots_dir = project_path.join("screenshots");
- std::fs::create_dir_all(&screenshots_dir).unwrap_or_else(|e| {
- eprintln!("Failed to create screenshots directory: {e:?}");
- });
+ let screenshots_dir = project_path.join("screenshots");
+ if std::fs::create_dir_all(&screenshots_dir).is_err() {
+ return;
+ }
- // Save full-size screenshot
- let screenshot_path = screenshots_dir.join("display.jpg");
- rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
- eprintln!("Failed to save screenshot: {e:?}");
+ let screenshot_path = screenshots_dir.join("display.jpg");
+ let _ = rgb_img.save(&screenshot_path);
});
+
+ if let Err(e) = screenshot_task.await {
+ warn!("Screenshot task failed: {e}");
+ }
} else {
warn!("No frames were processed, cannot save screenshot or thumbnail");
}
diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rs
index 7b14a8795..536fbb3bf 100644
--- a/crates/rendering/src/layers/mod.rs
+++ b/crates/rendering/src/layers/mod.rs
@@ -5,6 +5,7 @@ mod captions;
mod cursor;
mod display;
mod mask;
+mod text;
pub use background::*;
pub use blur::*;
@@ -13,3 +14,4 @@ pub use captions::*;
pub use cursor::*;
pub use display::*;
pub use mask::*;
+pub use text::*;
diff --git a/crates/rendering/src/layers/text.rs b/crates/rendering/src/layers/text.rs
new file mode 100644
index 000000000..aac7b846a
--- /dev/null
+++ b/crates/rendering/src/layers/text.rs
@@ -0,0 +1,162 @@
+use glyphon::cosmic_text::Align;
+use glyphon::{
+ Attrs, Buffer, Cache, Color, Family, FontSystem, Metrics, Resolution, Shaping, Style,
+ SwashCache, TextArea, TextAtlas, TextBounds, TextRenderer, Viewport, Weight,
+};
+use log::warn;
+use wgpu::{Device, Queue};
+
+use crate::text::PreparedText;
+
+pub struct TextLayer {
+ font_system: FontSystem,
+ swash_cache: SwashCache,
+ text_atlas: TextAtlas,
+ text_renderer: TextRenderer,
+ viewport: Viewport,
+ buffers: Vec<Buffer>,
+}
+
+impl TextLayer {
+ pub fn new(device: &Device, queue: &Queue) -> Self {
+ let font_system = FontSystem::new();
+ let swash_cache = SwashCache::new();
+ let cache = Cache::new(device);
+ let viewport = Viewport::new(device, &cache);
+ let mut text_atlas =
+ TextAtlas::new(device, queue, &cache, wgpu::TextureFormat::Rgba8UnormSrgb);
+ let text_renderer = TextRenderer::new(
+ &mut text_atlas,
+ device,
+ wgpu::MultisampleState::default(),
+ None,
+ );
+
+ Self {
+ font_system,
+ swash_cache,
+ text_atlas,
+ text_renderer,
+ viewport,
+ buffers: Vec::new(),
+ }
+ }
+
+ pub fn prepare(
+ &mut self,
+ device: &Device,
+ queue: &Queue,
+ output_size: (u32, u32),
+ texts: &[PreparedText],
+ ) {
+ self.buffers.clear();
+ self.buffers.reserve(texts.len());
+ let mut text_area_data = Vec::with_capacity(texts.len());
+
+ for text in texts {
+ let color = Color::rgba(
+ (text.color[0].clamp(0.0, 1.0) * 255.0) as u8,
+ (text.color[1].clamp(0.0, 1.0) * 255.0) as u8,
+ (text.color[2].clamp(0.0, 1.0) * 255.0) as u8,
+ (text.color[3].clamp(0.0, 1.0) * 255.0) as u8,
+ );
+
+ let width = (text.bounds[2] - text.bounds[0]).max(1.0);
+ let height = (text.bounds[3] - text.bounds[1]).max(1.0);
+
+ let metrics = Metrics::new(text.font_size, text.font_size * 1.2);
+ let mut buffer = Buffer::new(&mut self.font_system, metrics);
+ buffer.set_size(&mut self.font_system, Some(width), Some(height));
+ buffer.set_wrap(&mut self.font_system, glyphon::Wrap::Word);
+
+ let family = match text.font_family.trim() {
+ "" => Family::SansSerif,
+ name => match name.to_ascii_lowercase().as_str() {
+ "sans" | "sans-serif" | "system sans" | "system sans-serif" => {
+ Family::SansSerif
+ }
+ "serif" | "system serif" => Family::Serif,
+ "mono" | "monospace" | "system mono" | "system monospace" => Family::Monospace,
+ _ => Family::Name(name.into()),
+ },
+ };
+ let weight = Weight(text.font_weight.round().clamp(100.0, 900.0) as u16);
+ let attrs = Attrs::new()
+ .family(family)
+ .color(color)
+ .weight(weight)
+ .style(if text.italic {
+ Style::Italic
+ } else {
+ Style::Normal
+ });
+
+ buffer.set_text(
+ &mut self.font_system,
+ &text.content,
+ &attrs,
+ Shaping::Advanced,
+ );
+
+ for line in buffer.lines.iter_mut() {
+ line.set_align(Some(Align::Center));
+ }
+
+ buffer.shape_until_scroll(&mut self.font_system, false);
+
+ let bounds = TextBounds {
+ left: text.bounds[0].floor() as i32,
+ top: text.bounds[1].floor() as i32,
+ right: (text.bounds[0] + width).ceil() as i32,
+ bottom: (text.bounds[1] + height).ceil() as i32,
+ };
+
+ self.buffers.push(buffer);
+ text_area_data.push((bounds, text.bounds[0], text.bounds[1], color));
+ }
+
+ let text_areas = self
+ .buffers
+ .iter()
+ .zip(text_area_data.into_iter())
+ .map(|(buffer, (bounds, left, top, color))| TextArea {
+ buffer,
+ left,
+ top,
+ scale: 1.0,
+ bounds,
+ default_color: color,
+ custom_glyphs: &[],
+ })
+ .collect::<Vec<_>>();
+
+ self.viewport.update(
+ queue,
+ Resolution {
+ width: output_size.0,
+ height: output_size.1,
+ },
+ );
+
+ if let Err(error) = self.text_renderer.prepare(
+ device,
+ queue,
+ &mut self.font_system,
+ &mut self.text_atlas,
+ &self.viewport,
+ text_areas,
+ &mut self.swash_cache,
+ ) {
+ warn!("Failed to prepare text: {error:?}");
+ }
+ }
+
+ pub fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>) {
+ if let Err(error) = self
+ .text_renderer
+ .render(&self.text_atlas, &self.viewport, pass)
+ {
+ warn!("Failed to render text: {error:?}");
+ }
+ }
+}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index b9cd8175b..b1cf3cb30 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,8 +1,7 @@
use anyhow::Result;
use cap_project::{
AspectRatio, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets, CornerStyle, Crop,
- CursorEvents, MaskKind, MaskSegment, ProjectConfiguration, RecordingMeta, StudioRecordingMeta,
- XY,
+ CursorEvents, MaskKind, ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY,
};
use composite_frame::CompositeVideoFrameUniforms;
use core::f64;
@@ -13,7 +12,7 @@ use futures::FutureExt;
use futures::future::OptionFuture;
use layers::{
Background, BackgroundLayer, BlurLayer, CameraLayer, CaptionsLayer, CursorLayer, DisplayLayer,
- MaskLayer,
+ MaskLayer, TextLayer,
};
use specta::Type;
use spring_mass_damper::SpringMassDamperSimulationConfig;
@@ -32,6 +31,7 @@ mod mask;
mod project_recordings;
mod scene;
mod spring_mass_damper;
+mod text;
mod zoom;
pub use coord::*;
@@ -41,6 +41,7 @@ pub use project_recordings::{ProjectRecordingsMeta, SegmentRecordings};
use mask::interpolate_masks;
use scene::*;
+use text::{PreparedText, prepare_texts};
use zoom::*;
const STANDARD_CURSOR_HEIGHT: f32 = 75.0;
@@ -423,6 +424,7 @@ pub struct ProjectUniforms {
pub display_parent_motion_px: XY<f32>,
pub motion_blur_amount: f32,
pub masks: Vec<PreparedMask>,
+ pub texts: Vec<PreparedText>,
}
#[derive(Debug, Clone)]
@@ -1474,6 +1476,19 @@ impl ProjectUniforms {
})
.unwrap_or_default();
+ let texts = project
+ .timeline
+ .as_ref()
+ .map(|timeline| {
+ prepare_texts(
+ XY::new(output_size.0, output_size.1),
+ frame_time as f64,
+ &timeline.text_segments,
+ &project.hidden_text_segments,
+ )
+ })
+ .unwrap_or_default();
+
Self {
output_size,
cursor_size: project.cursor.size as f32,
@@ -1490,6 +1505,7 @@ impl ProjectUniforms {
display_parent_motion_px: display_motion_parent,
motion_blur_amount: user_motion_blur,
masks,
+ texts,
}
}
}
@@ -1555,6 +1571,7 @@ pub struct RendererLayers {
camera: CameraLayer,
camera_only: CameraLayer,
mask: MaskLayer,
+ text: TextLayer,
#[allow(unused)]
captions: CaptionsLayer,
}
@@ -1569,6 +1586,7 @@ impl RendererLayers {
camera: CameraLayer::new(device),
camera_only: CameraLayer::new(device),
mask: MaskLayer::new(device),
+ text: TextLayer::new(device, queue),
captions: CaptionsLayer::new(device, queue),
}
}
@@ -1633,6 +1651,13 @@ impl RendererLayers {
})(),
);
+ self.text.prepare(
+ &constants.device,
+ &constants.queue,
+ uniforms.output_size,
+ &uniforms.texts,
+ );
+
Ok(())
}
@@ -1708,6 +1733,11 @@ impl RendererLayers {
self.mask.render(device, queue, session, encoder, mask);
}
}
+
+ if !uniforms.texts.is_empty() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ self.text.render(&mut pass);
+ }
}
}
diff --git a/crates/rendering/src/text.rs b/crates/rendering/src/text.rs
new file mode 100644
index 000000000..944c904f4
--- /dev/null
+++ b/crates/rendering/src/text.rs
@@ -0,0 +1,85 @@
+use cap_project::{TextSegment, XY};
+
+const BASE_TEXT_HEIGHT: f64 = 0.2;
+
+#[derive(Debug, Clone)]
+pub struct PreparedText {
+ pub content: String,
+ pub bounds: [f32; 4],
+ pub color: [f32; 4],
+ pub font_family: String,
+ pub font_size: f32,
+ pub font_weight: f32,
+ pub italic: bool,
+}
+
+fn parse_color(hex: &str) -> [f32; 4] {
+ let color = hex.trim_start_matches('#');
+ if color.len() == 6 {
+ if let (Ok(r), Ok(g), Ok(b)) = (
+ u8::from_str_radix(&color[0..2], 16),
+ u8::from_str_radix(&color[2..4], 16),
+ u8::from_str_radix(&color[4..6], 16),
+ ) {
+ return [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0];
+ }
+ }
+
+ [1.0, 1.0, 1.0, 1.0]
+}
+
+pub fn prepare_texts(
+ output_size: XY<u32>,
+ frame_time: f64,
+ segments: &[TextSegment],
+ hidden_indices: &[usize],
+) -> Vec<PreparedText> {
+ let mut prepared = Vec::new();
+ let height_scale = if output_size.y == 0 {
+ 1.0
+ } else {
+ output_size.y as f32 / 1080.0
+ };
+
+ for (i, segment) in segments.iter().enumerate() {
+ if !segment.enabled || hidden_indices.contains(&i) {
+ continue;
+ }
+
+ if frame_time < segment.start || frame_time > segment.end {
+ continue;
+ }
+
+ let center = XY::new(
+ segment.center.x.clamp(0.0, 1.0),
+ segment.center.y.clamp(0.0, 1.0),
+ );
+ let size = XY::new(
+ segment.size.x.clamp(0.01, 2.0),
+ segment.size.y.clamp(0.01, 2.0),
+ );
+ let size_scale = (size.y / BASE_TEXT_HEIGHT).clamp(0.25, 4.0) as f32;
+
+ let width = (size.x * output_size.x as f64).max(1.0) as f32;
+ let height = (size.y * output_size.y as f64).max(1.0) as f32;
+ let half_w = width / 2.0;
+ let half_h = height / 2.0;
+
+ let left = (center.x as f32 * output_size.x as f32 - half_w).max(0.0);
+ let top = (center.y as f32 * output_size.y as f32 - half_h).max(0.0);
+ let right = (left + width).min(output_size.x as f32);
+ let bottom = (top + height).min(output_size.y as f32);
+
+ prepared.push(PreparedText {
+ content: segment.content.clone(),
+ bounds: [left, top, right, bottom],
+ color: parse_color(&segment.color),
+ font_family: segment.font_family.clone(),
+ font_size: (segment.font_size * size_scale).max(1.0) * height_scale,
+ font_weight: segment.font_weight,
+ italic: segment.italic,
+ });
+ }
+
+ prepared
+}
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index c19129bd8..c5756a694 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -94,6 +94,7 @@ declare global {
const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']
const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']
const IconLucideTimer: typeof import('~icons/lucide/timer.jsx')['default']
+ const IconLucideType: typeof import('~icons/lucide/type.jsx')['default']
const IconLucideUnplug: typeof import('~icons/lucide/unplug.jsx')['default']
const IconLucideVideo: typeof import('~icons/lucide/video.jsx')['default']
const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']