Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add window-aware export cancellation and prompts
Richie McIlroy8b1120818164
diff --git a/apps/desktop/src-tauri/src/exit_shutdown.rs b/apps/desktop/src-tauri/src/exit_shutdown.rsindex 2fcd4639c..4d991642b 100644--- a/apps/desktop/src-tauri/src/exit_shutdown.rs+++ b/apps/desktop/src-tauri/src/exit_shutdown.rs@@ -83,23 +83,19 @@ pub(crate) fn app_exit_action(exit_code: i32) -> AppExitAction {pub(crate) enum ExitRequestDecision {StartCleanup,AlreadyExiting,- ExportActive,AllowRuntimeExit,}pub(crate) fn handle_exit_requested<FPrevent>(is_exiting: bool,- export_active: bool,+ _export_active: bool,runtime_exit_requested: bool,prevent_exit: FPrevent,) -> ExitRequestDecisionwhereFPrevent: FnOnce(),{- if export_active {- prevent_exit();- ExitRequestDecision::ExportActive- } else if is_exiting && runtime_exit_requested {+ if is_exiting && runtime_exit_requested {ExitRequestDecision::AllowRuntimeExit} else if is_exiting {prevent_exit();diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsindex 0d05690a9..0641bdda7 100644--- a/apps/desktop/src-tauri/src/export.rs+++ b/apps/desktop/src-tauri/src/export.rs@@ -89,6 +89,9 @@ const EXPORT_PROGRESS_FORWARD_INTERVAL: std::time::Duration = std::time::Duratiostatic ACTIVE_EXPORT_SESSIONS: AtomicUsize = AtomicUsize::new(0);static ACTIVE_EXPORT_CANCELLATIONS: LazyLock<Mutex<HashMap<String, ActiveExportCancellation>>> =LazyLock::new(|| Mutex::new(HashMap::new()));+static ACTIVE_EXPORT_WINDOW_SESSIONS: LazyLock<Mutex<HashMap<String, usize>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));+static NEXT_EXPORT_COMMAND_ID: AtomicUsize = AtomicUsize::new(1);#[cfg(windows)]const CREATE_NO_WINDOW: u32 = 0x0800_0000;@@ -205,6 +208,18 @@ fn active_export_cancellations() -> MutexGuard<'static, HashMap<String, ActiveEx}}+fn active_export_window_sessions() -> MutexGuard<'static, HashMap<String, usize>> {+ match ACTIVE_EXPORT_WINDOW_SESSIONS.lock() {+ Ok(guard) => guard,+ Err(err) => err.into_inner(),+ }+}++fn next_export_command_id(prefix: &str) -> String {+ let id = NEXT_EXPORT_COMMAND_ID.fetch_add(1, Ordering::AcqRel);+ format!("{prefix}-{id}")+}+fn cancel_export_by_id(export_id: &str) -> bool {let cancellations = active_export_cancellations();if let Some(active_export) = cancellations.get(export_id) {@@ -216,20 +231,50 @@ fn cancel_export_by_id(export_id: &str) -> bool {}pub fn cancel_exports_for_window(window_label: &str) {- let cancellations = active_export_cancellations();- let mut cancelled_count = 0;+ let tokens = {+ let cancellations = active_export_cancellations();+ cancellations+ .values()+ .filter(|active_export| active_export.window_label.as_deref() == Some(window_label))+ .map(|active_export| active_export.token.clone())+ .collect::<Vec<_>>()+ };- for active_export in cancellations.values() {- if active_export.window_label.as_deref() == Some(window_label) {- active_export.token.cancel();- cancelled_count += 1;- }+ for token in &tokens {+ token.cancel();}- if cancelled_count > 0 {+ let released_sessions = release_export_sessions_for_window(window_label);++ if !tokens.is_empty() || released_sessions > 0 {info!(window = window_label,- cancelled_count, "Cancelled window exports"+ cancelled_count = tokens.len(),+ released_sessions,+ "Cancelled window exports"+ );+ }+}++pub fn cancel_all_exports() {+ let tokens = {+ let cancellations = active_export_cancellations();+ cancellations+ .values()+ .map(|active_export| active_export.token.clone())+ .collect::<Vec<_>>()+ };++ for token in &tokens {+ token.cancel();+ }++ let released_sessions = release_all_window_export_sessions();++ if !tokens.is_empty() || released_sessions > 0 {+ info!(+ cancelled_count = tokens.len(),+ released_sessions, "Cancelled active exports");}}@@ -276,16 +321,71 @@ pub fn export_session_active() -> bool {ACTIVE_EXPORT_SESSIONS.load(Ordering::Acquire) > 0}+fn retain_export_session_for_window(window_label: &str) {+ retain_export_session();+ let mut sessions = active_export_window_sessions();+ *sessions.entry(window_label.to_string()).or_insert(0) += 1;+}++fn release_export_session_for_window(window_label: &str) {+ let should_release = {+ let mut sessions = active_export_window_sessions();+ if let Some(count) = sessions.get_mut(window_label) {+ *count -= 1;+ if *count == 0 {+ sessions.remove(window_label);+ }+ true+ } else {+ false+ }+ };++ if should_release {+ release_export_session();+ } else {+ tracing::warn!(+ window = window_label,+ "Export session guard release requested with no active window export"+ );+ }+}++fn release_export_sessions_for_window(window_label: &str) -> usize {+ let count = active_export_window_sessions()+ .remove(window_label)+ .unwrap_or(0);++ for _ in 0..count {+ release_export_session();+ }++ count+}++fn release_all_window_export_sessions() -> usize {+ let count = active_export_window_sessions()+ .drain()+ .map(|(_, count)| count)+ .sum::<usize>();++ for _ in 0..count {+ release_export_session();+ }++ count+}+#[tauri::command]#[specta::specta]-pub fn begin_export_session() {- retain_export_session();+pub fn begin_export_session(window: tauri::Window) {+ retain_export_session_for_window(window.label());}#[tauri::command]#[specta::specta]-pub fn end_export_session() {- release_export_session();+pub fn end_export_session(window: tauri::Window) {+ release_export_session_for_window(window.label());}struct ExportSessionGuard;@@ -805,20 +905,27 @@ fn should_use_out_of_process_export() -> bool {#[tauri::command]#[specta::specta]-#[instrument(skip(progress, editor))]+#[instrument(skip(window, progress, editor))]pub async fn export_video(+ window: tauri::Window,project_path: PathBuf,progress: tauri::ipc::Channel<FramesRendered>,settings: ExportSettings,editor: OptionalWindowEditorInstance,) -> Result<PathBuf, String> {- match AssertUnwindSafe(export_video_inner(- project_path,- settings,- editor,- ExportProgress(progress),- CancellationToken::new(),- ))+ let window_label = window.label().to_string();+ match AssertUnwindSafe(async move {+ let cancellation_guard =+ ExportCancellationGuard::new(next_export_command_id("export"), Some(window_label));+ export_video_inner(+ project_path,+ settings,+ editor,+ ExportProgress(progress),+ cancellation_guard.token(),+ )+ .await+ }).catch_unwind().await{@@ -860,9 +967,10 @@ pub async fn export_video_with_id(#[tauri::command]#[specta::specta]-#[instrument(skip(app, progress, editor))]+#[instrument(skip(app, window, progress, editor))]pub async fn export_video_to_file(app: tauri::AppHandle,+ window: tauri::Window,project_path: PathBuf,progress: tauri::ipc::Channel<FramesRendered>,settings: ExportSettings,@@ -870,15 +978,24 @@ pub async fn export_video_to_file(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,- ))+ let window_label = window.label().to_string();+ match AssertUnwindSafe(async move {+ let cancellation_guard = ExportCancellationGuard::new(+ next_export_command_id("export-to-file"),+ Some(window_label),+ );+ export_video_to_file_inner(+ app,+ project_path,+ progress,+ settings,+ file_name,+ file_type,+ editor,+ cancellation_guard.token(),+ )+ .await+ }).catch_unwind().await{@@ -895,6 +1012,7 @@ async fn export_video_to_file_inner(file_name: String,file_type: String,editor: OptionalWindowEditorInstance,+ cancel_token: CancellationToken,) -> Result<PathBuf, String> {let _session_guard = ExportSessionGuard::new();let Some(save_path) = show_export_save_dialog(&app, file_name, file_type).await? else {@@ -908,7 +1026,7 @@ async fn export_video_to_file_inner(settings,editor,ExportProgress(progress),- CancellationToken::new(),+ cancel_token,).await?;copy_export_to_path(&output_path, &save_path).await?;diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex c06ef7c77..149cb9611 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -1771,6 +1771,7 @@ async fn cleanup_app_resources_for_exit(app: &AppHandle) {let started = Instant::now();log_process_memory_snapshot("exit_cleanup_begin");+ export::cancel_all_exports();power_observer::uninstall(app);fake_window::cancel_all_fake_window_listeners(app);close_target_select_overlays(app);@@ -1887,13 +1888,9 @@ fn finalize_app_exit(app: &AppHandle, exit_code: i32) {}pub async fn request_app_exit(app: AppHandle) {- if export::export_session_active() {- warn!("Ignoring app exit request during active export");- return;- }-let Some(exit_state) = app.try_state::<AppExitState>() else {warn!("Exit state unavailable while requesting app exit");+ export::cancel_all_exports();finalize_app_exit(&app, 0);#[cfg(not(target_os = "macos"))]return;@@ -1904,6 +1901,7 @@ pub async fn request_app_exit(app: AppHandle) {}spawn_exit_watchdog();+ export::cancel_all_exports();if tokio::time::timeout(APP_EXIT_TOTAL_TIMEOUT, cleanup_app_resources_for_exit(&app)).await@@ -4730,13 +4728,12 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {match event {WindowEvent::CloseRequested { api, .. } => {let window_id = CapWindowId::from_str(label).ok();- if matches!(+ if !matches!(window_id,Some(CapWindowId::Editor { .. })| Some(CapWindowId::ScreenshotEditor { .. })- ) {- export::cancel_exports_for_window(label);- } else if export::export_session_active() {+ ) && export::export_session_active()+ {api.prevent_close();warn!(window = label,@@ -5246,9 +5243,6 @@ fn handle_run_event(_handle: &AppHandle, event: tauri::RunEvent) {});}ExitRequestDecision::AlreadyExiting => {}- ExitRequestDecision::ExportActive => {- warn!("Preventing app exit request during active export");- }ExitRequestDecision::AllowRuntimeExit => {}}}diff --git a/apps/desktop/src-tauri/tests/exit_shutdown.rs b/apps/desktop/src-tauri/tests/exit_shutdown.rsindex b40b6b3f9..477364651 100644--- a/apps/desktop/src-tauri/tests/exit_shutdown.rs+++ b/apps/desktop/src-tauri/tests/exit_shutdown.rs@@ -232,7 +232,20 @@ fn exit_requested_allows_runtime_exit_when_already_exiting() {}#[test]-fn exit_requested_prevents_runtime_exit_during_export() {+fn exit_requested_allows_runtime_exit_when_export_cancel_is_draining() {+ let prevented = Arc::new(AtomicBool::new(false));+ let prevented_flag = prevented.clone();++ let decision = handle_exit_requested(true, true, true, move || {+ prevented_flag.store(true, Ordering::Release);+ });++ assert_eq!(decision, ExitRequestDecision::AllowRuntimeExit);+ assert!(!prevented.load(Ordering::Acquire));+}++#[test]+fn exit_requested_starts_cleanup_during_export() {let prevented = Arc::new(AtomicBool::new(false));let prevented_flag = prevented.clone();@@ -240,6 +253,6 @@ fn exit_requested_prevents_runtime_exit_during_export() {prevented_flag.store(true, Ordering::Release);});- assert_eq!(decision, ExitRequestDecision::ExportActive);+ assert_eq!(decision, ExitRequestDecision::StartCleanup);assert!(prevented.load(Ordering::Acquire));}diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsxindex a916f5485..74743ce31 100644--- a/apps/desktop/src/routes/editor/Editor.tsx+++ b/apps/desktop/src/routes/editor/Editor.tsx@@ -8,6 +8,8 @@ import { createMutation, createQuery, skipToken } from "@tanstack/solid-query";import { convertFileSrc } from "@tauri-apps/api/core";import { LogicalPosition } from "@tauri-apps/api/dpi";import { Menu } from "@tauri-apps/api/menu";+import { getCurrentWindow } from "@tauri-apps/api/window";+import { ask } from "@tauri-apps/plugin-dialog";import {createEffect,createMemo,@@ -269,6 +271,7 @@ function Inner() {setEditorState,previewResolutionBase,dialog,+ exportState,} = useEditorContext();const isExportMode = () => {@@ -286,6 +289,47 @@ function Inner() {return "type" in d && d.type === "crop" && d.open;};+ const currentWindow = getCurrentWindow();+ let allowExportClose = false;+ let closePromptOpen = false;++ onMount(async () => {+ const unlisten = await currentWindow.onCloseRequested(async (event) => {+ if (+ allowExportClose ||+ exportState.type === "idle" ||+ exportState.type === "done"+ ) {+ return;+ }++ event.preventDefault();+ if (closePromptOpen) return;++ closePromptOpen = true;+ try {+ const resumeExport = await ask(+ "An export is currently running. Keep this editor open to continue it, or quit the editor and cancel the export.",+ {+ title: "Export in Progress",+ kind: "warning",+ okLabel: "Resume Export",+ cancelLabel: "Quit Editor",+ },+ );++ if (!resumeExport) {+ allowExportClose = true;+ await currentWindow.close();+ }+ } finally {+ closePromptOpen = false;+ }+ });++ onCleanup(() => unlisten());+ });+const [layoutRef, setLayoutRef] = createSignal<HTMLDivElement>();const layoutBounds = createElementBounds(layoutRef);const [storedTimelineHeight, setStoredTimelineHeight] = makePersisted(