Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add export-to-file flow with save dialog

Richie McIlroydc22b58135e0
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index f73cfb018..1f1b39d69 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -20,8 +20,9 @@ use std::{
atomic::{AtomicBool, AtomicUsize, Ordering},
},
};
+use tauri_plugin_dialog::DialogExt;
use tokio::io::AsyncBufReadExt;
-use tracing::{error, info, instrument};
+use tracing::{error, info, instrument, warn};
fn panic_message(panic: Box<dyn Any + Send>) -> String {
if let Some(msg) = panic.downcast_ref::<&str>() {
@@ -33,6 +34,20 @@ fn panic_message(panic: Box<dyn Any + Send>) -> String {
}
}
+fn export_panic_error(panic: Box<dyn Any + Send>) -> String {
+ let panic_msg = panic_message(panic);
+ error!(
+ target: "cap_desktop_export",
+ panic = %panic_msg,
+ "export command panicked"
+ );
+ sentry::capture_message(
+ &format!("Export command panicked: {panic_msg}"),
+ sentry::Level::Error,
+ );
+ "Export failed unexpectedly".to_string()
+}
+
async fn run_protected_export(
project_path: &Path,
settings: &ExportSettings,
@@ -656,7 +671,69 @@ pub async fn export_video(
settings: ExportSettings,
editor: OptionalWindowEditorInstance,
) -> Result<PathBuf, String> {
- export_video_inner(project_path, settings, editor, ExportProgress(progress)).await
+ match AssertUnwindSafe(export_video_inner(
+ project_path,
+ settings,
+ editor,
+ ExportProgress(progress),
+ ))
+ .catch_unwind()
+ .await
+ {
+ Ok(result) => result,
+ Err(panic) => Err(export_panic_error(panic)),
+ }
+}
+
+#[tauri::command]
+#[specta::specta]
+#[instrument(skip(app, progress, editor))]
+pub async fn export_video_to_file(
+ app: tauri::AppHandle,
+ project_path: PathBuf,
+ progress: tauri::ipc::Channel<FramesRendered>,
+ settings: ExportSettings,
+ file_name: String,
+ file_type: String,
+ editor: OptionalWindowEditorInstance,
+) -> Result<PathBuf, String> {
+ match AssertUnwindSafe(export_video_to_file_inner(
+ app,
+ project_path,
+ progress,
+ settings,
+ file_name,
+ file_type,
+ editor,
+ ))
+ .catch_unwind()
+ .await
+ {
+ Ok(result) => result,
+ Err(panic) => Err(export_panic_error(panic)),
+ }
+}
+
+async fn export_video_to_file_inner(
+ app: tauri::AppHandle,
+ project_path: PathBuf,
+ progress: tauri::ipc::Channel<FramesRendered>,
+ settings: ExportSettings,
+ file_name: String,
+ file_type: String,
+ editor: OptionalWindowEditorInstance,
+) -> Result<PathBuf, String> {
+ let _session_guard = ExportSessionGuard::new();
+ let Some(save_path) = show_export_save_dialog(&app, file_name, file_type).await? else {
+ return Err("Save dialog cancelled".to_string());
+ };
+
+ info!(path = %save_path.display(), "Export save path selected");
+
+ let output_path =
+ export_video_inner(project_path, settings, editor, ExportProgress(progress)).await?;
+ copy_export_to_path(&output_path, &save_path).await?;
+ Ok(save_path)
}
async fn export_video_inner(
@@ -730,6 +807,73 @@ async fn export_video_inner(
}
}
+async fn show_export_save_dialog(
+ app: &tauri::AppHandle,
+ file_name: String,
+ file_type: String,
+) -> Result<Option<PathBuf>, String> {
+ info!(file_name, file_type, "Save file dialog requested");
+
+ let (name, extension) = match file_type.as_str() {
+ "mp4" => ("MP4 Video", "mp4"),
+ "gif" => ("GIF Image", "gif"),
+ "mov" => ("MOV Video", "mov"),
+ _ => {
+ warn!(file_type, "Invalid export save file dialog type");
+ return Err("Invalid file type".to_string());
+ }
+ };
+
+ info!(file_name, name, extension, "Showing save file dialog");
+
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ app.dialog()
+ .file()
+ .set_title("Save File")
+ .set_file_name(file_name)
+ .add_filter(name, &[extension])
+ .save_file(move |path| {
+ let _ = tx.send(path.and_then(|p| p.as_path().map(PathBuf::from)));
+ });
+
+ rx.await.map_err(|e| e.to_string()).inspect(|result| {
+ info!(path = ?result, "Save file dialog completed");
+ })
+}
+
+async fn copy_export_to_path(src: &Path, dst: &Path) -> Result<(), String> {
+ info!(
+ src = %src.display(),
+ dst = %dst.display(),
+ "Copying exported video to selected path"
+ );
+
+ if let Some(parent) = dst.parent() {
+ tokio::fs::create_dir_all(parent)
+ .await
+ .map_err(|e| format!("Failed to create export target directory: {e}"))?;
+ }
+
+ let bytes = tokio::fs::copy(src, dst)
+ .await
+ .map_err(|e| format!("Failed to copy exported file: {e}"))?;
+
+ let src_size = tokio::fs::metadata(src)
+ .await
+ .map_err(|e| format!("Failed to read exported file metadata: {e}"))?
+ .len();
+
+ if bytes != src_size {
+ let _ = tokio::fs::remove_file(dst).await;
+ return Err(format!(
+ "Export copy verification failed: copied {bytes} bytes but source is {src_size} bytes"
+ ));
+ }
+
+ info!(bytes, dst = %dst.display(), "Copied exported video to selected path");
+ Ok(())
+}
+
#[derive(Debug, serde::Serialize, specta::Type)]
pub struct ExportEstimates {
pub duration_seconds: f64,
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 799901ab0..078b19f73 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -3917,6 +3917,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
export::begin_export_session,
export::end_export_session,
export::export_video,
+ export::export_video_to_file,
export::get_export_estimates,
export::generate_export_preview,
export::generate_export_preview_fast,
diff --git a/apps/desktop/src/routes/editor/ExportPage.tsx b/apps/desktop/src/routes/editor/ExportPage.tsx
index ddc54e09b..aee09fef1 100644
--- a/apps/desktop/src/routes/editor/ExportPage.tsx
+++ b/apps/desktop/src/routes/editor/ExportPage.tsx
@@ -28,7 +28,11 @@ import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionCont
import { authStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
import { createSignInMutation } from "~/utils/auth";
-import { beginExportSessionGuard, createExportTask } from "~/utils/export";
+import {
+ beginExportSessionGuard,
+ createExportTask,
+ createExportToFileTask,
+} from "~/utils/export";
import { createSelectedOrganization } from "~/utils/organization-branding";
import {
commands,
@@ -185,7 +189,10 @@ export function ExportPage() {
const isCancellationError = (error: unknown) =>
error instanceof SilentError ||
error === "Export cancelled" ||
- (error instanceof Error && error.message === "Export cancelled");
+ error === "Save dialog cancelled" ||
+ (error instanceof Error &&
+ (error.message === "Export cancelled" ||
+ error.message === "Save dialog cancelled"));
const [_settings, setSettings] = makePersisted(
createStore<Settings>({
@@ -572,42 +579,37 @@ export function ExportPage() {
mutationFn: async () => {
setIsCancelled(false);
if (exportState.type !== "idle") return;
- const releaseExportSession = await beginExportSessionGuard();
- try {
- const extension = exportFileExtension();
- const savePath = await commands.saveFileDialog(
- `${meta().prettyName}.${extension}`,
- extension,
- );
- if (!savePath) {
- throw new SilentError("Save dialog cancelled");
- }
-
- setExportState(reconcile({ action: "save", type: "starting" }));
-
- setOutputPath(savePath);
-
- trackEvent("export_started", {
- resolution: settings.resolution,
- fps: settings.fps,
- path: savePath,
- });
-
- const videoPath = await exportWithSettings((progress) => {
+ const extension = exportFileExtension();
+ const customBpp =
+ advancedMode() && isCustomBpp() ? compressionBpp() : null;
+ const exportSettings = buildExportSettings(
+ settings,
+ isMovCursorOnlyExport(),
+ customBpp,
+ forceFfmpegDecoder(),
+ );
+ const { promise, cancel } = createExportToFileTask(
+ projectPath,
+ exportSettings,
+ `${meta().prettyName}.${extension}`,
+ extension,
+ (progress) => {
if (isCancelled()) throw new SilentError("Cancelled");
setExportState({ type: "rendering", progress });
- });
+ },
+ );
+ cancelCurrentExport = cancel;
- if (isCancelled()) throw new SilentError("Cancelled");
+ setExportState(reconcile({ action: "save", type: "starting" }));
- setExportState({ type: "copying" });
+ const savePath = await promise.finally(() => {
+ if (cancelCurrentExport === cancel) cancelCurrentExport = null;
+ });
- await commands.copyFileToPath(videoPath, savePath);
+ if (isCancelled()) throw new SilentError("Cancelled");
- setExportState({ type: "done" });
- } finally {
- await releaseExportSession();
- }
+ setOutputPath(savePath);
+ setExportState({ type: "done" });
},
onError: (error) => {
if (isCancelled() || isCancellationError(error)) {
diff --git a/apps/desktop/src/routes/recordings-overlay.tsx b/apps/desktop/src/routes/recordings-overlay.tsx
index 93fe63d79..d1942c4c2 100644
--- a/apps/desktop/src/routes/recordings-overlay.tsx
+++ b/apps/desktop/src/routes/recordings-overlay.tsx
@@ -25,7 +25,7 @@ import { createStore, produce, type SetStoreFunction } from "solid-js/store";
import { TransitionGroup } from "solid-transition-group";
import { authStore } from "~/store";
import { createTauriEventListener } from "~/utils/createEventListener";
-import { exportVideo } from "~/utils/export";
+import { createExportToFileTask, exportVideo } from "~/utils/export";
import {
commands,
events,
@@ -645,7 +645,7 @@ function createRecordingMutations(
: media.path.split(".cap/")[1];
const suggestedName = meta.pretty_name || defaultName;
- const fileType = isRecording ? "recording" : "screenshot";
+ const fileType = isRecording ? "mp4" : "screenshot";
const extension = isRecording ? ".mp4" : ".png";
const fullFileName = suggestedName.endsWith(extension)
@@ -660,29 +660,30 @@ function createRecordingMutations(
},
});
- const savePath = await commands.saveFileDialog(fullFileName, fileType);
-
- if (!savePath) {
- setActionState({ type: "idle" });
- return false;
- }
-
- setActionState({
- type: "save",
- state: {
- type: "rendering",
- state: { type: "starting" },
- },
- });
-
if (isRecording) {
- const outputPath = await exportWithDefaultSettings(
+ const { promise } = createExportToFileTask(
+ media.path,
+ {
+ format: "Mp4",
+ fps: FPS,
+ resolution_base: OUTPUT_SIZE,
+ compression: "Web",
+ custom_bpp: null,
+ },
+ fullFileName,
+ fileType,
createRenderProgressCallback("save", setActionState),
);
- await commands.copyFileToPath(outputPath, savePath);
+ await promise;
} else {
- // For screenshots, show quick progress animation
+ const savePath = await commands.saveFileDialog(fullFileName, fileType);
+
+ if (!savePath) {
+ setActionState({ type: "idle" });
+ return false;
+ }
+
setActionState({ type: "save", state: { type: "saving" } });
await commands.copyFileToPath(media.path, savePath);
diff --git a/apps/desktop/src/utils/export.ts b/apps/desktop/src/utils/export.ts
index 0fb5321ba..5583828bb 100644
--- a/apps/desktop/src/utils/export.ts
+++ b/apps/desktop/src/utils/export.ts
@@ -38,6 +38,37 @@ export function createExportTask(
return { promise, cancel };
}
+export function createExportToFileTask(
+ projectPath: string,
+ settings: ExportSettings,
+ fileName: string,
+ fileType: string,
+ onProgress: (progress: FramesRendered) => void,
+) {
+ const progress = new Channel<FramesRendered>((e) => {
+ onProgress(e);
+ });
+ 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 = invoke<string>("export_video_to_file", {
+ projectPath,
+ progress,
+ settings,
+ fileName,
+ fileType,
+ }).finally(cancel);
+ return { promise, cancel };
+}
+
export async function exportVideo(
projectPath: string,
settings: ExportSettings,