Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Dispose/cleanup editor instances on app exit

Richie McIlroya402763c52c2
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs
index 3d070c7ba..a370f0d1b 100644
--- a/apps/desktop/src-tauri/src/editor_window.rs
+++ b/apps/desktop/src-tauri/src/editor_window.rs
@@ -148,6 +148,51 @@ impl PendingEditorInstances {
});
}
}
+
+ pub async fn dispose_all(app: &AppHandle) {
+ let Some(pending) = app.try_state::<Self>() else {
+ return;
+ };
+
+ let pending = {
+ let mut instances = pending.0.write().await;
+ std::mem::take(&mut *instances)
+ };
+
+ let count = pending.len();
+ for (_, mut rx) in pending {
+ let result = tokio::time::timeout(std::time::Duration::from_millis(500), async {
+ loop {
+ let instance_to_dispose = {
+ let borrowed = rx.borrow_and_update().clone();
+ match borrowed {
+ Some(Ok(instance)) => Some(instance),
+ Some(Err(_)) => break,
+ None => None,
+ }
+ };
+
+ if let Some(instance) = instance_to_dispose {
+ instance.dispose().await;
+ break;
+ }
+
+ if rx.changed().await.is_err() {
+ break;
+ }
+ }
+ })
+ .await;
+
+ if result.is_err() {
+ tracing::warn!("Timed out disposing pending editor instance during app exit");
+ }
+ }
+
+ if count > 0 {
+ tracing::info!(count, "Disposed pending editor instances during app exit");
+ }
+ }
}
impl EditorInstance {
@@ -159,6 +204,13 @@ impl EditorInstance {
}
}
+impl Drop for EditorInstance {
+ fn drop(&mut self) {
+ self.ws_shutdown_token.cancel();
+ self.app_handle.unlisten(self.render_frame_event_id);
+ }
+}
+
impl Deref for EditorInstance {
type Target = Arc<cap_editor::EditorInstance>;
@@ -346,4 +398,24 @@ impl EditorInstances {
instance.dispose().await;
}
}
+
+ pub async fn dispose_all(app: &AppHandle) {
+ let Some(instances) = app.try_state::<EditorInstances>() else {
+ return;
+ };
+
+ let instances = {
+ let mut instances = instances.0.write().await;
+ std::mem::take(&mut *instances)
+ };
+
+ let count = instances.len();
+ for (_, instance) in instances {
+ instance.dispose().await;
+ }
+
+ if count > 0 {
+ tracing::info!(count, "Disposed editor instances during app exit");
+ }
+ }
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index f12fec017..fae63be71 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -62,7 +62,7 @@ use cap_rendering::ProjectRecordingsMeta;
use clipboard_rs::common::RustImage;
use clipboard_rs::{Clipboard, ClipboardContext};
use cpal::StreamError;
-use editor_window::{EditorInstances, WindowEditorInstance};
+use editor_window::{EditorInstances, PendingEditorInstances, WindowEditorInstance};
use ffmpeg::ffi::AV_TIME_BASE;
use general_settings::GeneralSettingsStore;
use kameo::{Actor, actor::ActorRef};
@@ -91,7 +91,7 @@ use std::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
},
- time::{Duration, SystemTime, UNIX_EPOCH},
+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tauri::Listener;
use tauri::{AppHandle, Emitter, Manager, State, Window, WindowEvent, ipc::Channel};
@@ -193,16 +193,30 @@ where
E: std::fmt::Display,
F: Future<Output = Result<T, E>>,
{
+ let started = Instant::now();
match tokio::time::timeout(timeout, fut).await {
- Ok(Ok(value)) => Some(value),
+ Ok(Ok(value)) => {
+ info!(
+ step = name,
+ elapsed_ms = started.elapsed().as_millis(),
+ "Exit cleanup step completed"
+ );
+ Some(value)
+ }
Ok(Err(err)) => {
- warn!(step = name, error = %err, "Exit cleanup step failed");
+ warn!(
+ step = name,
+ elapsed_ms = started.elapsed().as_millis(),
+ error = %err,
+ "Exit cleanup step failed"
+ );
None
}
Err(_) => {
warn!(
step = name,
timeout_ms = timeout.as_millis(),
+ elapsed_ms = started.elapsed().as_millis(),
"Exit cleanup step timed out"
);
None
@@ -210,6 +224,40 @@ where
}
}
+fn log_process_memory_snapshot(stage: &'static str) {
+ let Ok(pid) = sysinfo::get_current_pid() else {
+ return;
+ };
+
+ let mut system = sysinfo::System::new();
+ system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
+
+ if let Some(process) = system.process(pid) {
+ info!(
+ stage = stage,
+ rss_mb = process.memory() / 1_048_576,
+ virtual_mb = process.virtual_memory() / 1_048_576,
+ "Process memory snapshot"
+ );
+ }
+}
+
+fn spawn_process_memory_sampler(app: AppHandle) {
+ tokio::spawn(async move {
+ let mut interval = tokio::time::interval(Duration::from_secs(60));
+
+ loop {
+ interval.tick().await;
+
+ if app_is_exiting(&app) {
+ break;
+ }
+
+ log_process_memory_snapshot("periodic");
+ }
+ });
+}
+
fn force_exit(code: i32) -> ! {
unsafe extern "C" {
fn _exit(code: i32) -> !;
@@ -1405,10 +1453,60 @@ async fn cleanup_camera_after_overlay_close(app: AppHandle, captured_session_id:
}
async fn cleanup_app_resources_for_exit(app: &AppHandle) {
+ let started = Instant::now();
+ log_process_memory_snapshot("exit_cleanup_begin");
+
power_observer::uninstall(app);
fake_window::cancel_all_fake_window_listeners(app);
close_target_select_overlays(app);
+ let app_for_pending_editors = app.clone();
+ let _ = await_exit_step(
+ "dispose_pending_editor_instances",
+ APP_EXIT_STEP_TIMEOUT,
+ async move {
+ PendingEditorInstances::dispose_all(&app_for_pending_editors).await;
+ Ok::<(), String>(())
+ },
+ )
+ .await;
+
+ let app_for_editors = app.clone();
+ let _ = await_exit_step(
+ "dispose_editor_instances",
+ APP_EXIT_STEP_TIMEOUT,
+ async move {
+ EditorInstances::dispose_all(&app_for_editors).await;
+ Ok::<(), String>(())
+ },
+ )
+ .await;
+
+ let app_for_pending_screenshot_editors = app.clone();
+ let _ = await_exit_step(
+ "dispose_pending_screenshot_editor_instances",
+ APP_EXIT_STEP_TIMEOUT,
+ async move {
+ PendingScreenshotEditorInstances::dispose_all(&app_for_pending_screenshot_editors)
+ .await;
+ Ok::<(), String>(())
+ },
+ )
+ .await;
+
+ let app_for_screenshot_editors = app.clone();
+ let _ = await_exit_step(
+ "dispose_screenshot_editor_instances",
+ APP_EXIT_STEP_TIMEOUT,
+ async move {
+ ScreenshotEditorInstances::dispose_all(&app_for_screenshot_editors).await;
+ Ok::<(), String>(())
+ },
+ )
+ .await;
+
+ log_process_memory_snapshot("exit_after_editor_dispose");
+
let (mic_feed, camera_feed, camera_shutdown) = {
let Some(state) = app.try_state::<ArcLock<App>>() else {
warn!("App state unavailable during exit cleanup");
@@ -1446,6 +1544,11 @@ async fn cleanup_app_resources_for_exit(app: &AppHandle) {
}
captions::release_ml_models().await;
+ log_process_memory_snapshot("exit_cleanup_end");
+ info!(
+ elapsed_ms = started.elapsed().as_millis(),
+ "Exit cleanup completed"
+ );
}
#[cfg(target_os = "macos")]
@@ -4099,6 +4202,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
app.manage(CameraWindowOperationLock::default());
app.manage(AppExitState::default());
app.manage(MainWindowReadyState::default());
+ spawn_process_memory_sampler(app.clone());
app.manage(Arc::new(RwLock::new(
ClipboardContext::new().expect("Failed to create clipboard context"),
diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rs
index d33468ed8..02bdb2cdb 100644
--- a/apps/desktop/src-tauri/src/screenshot_editor.rs
+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs
@@ -55,6 +55,12 @@ impl ScreenshotEditorInstance {
}
}
+impl Drop for ScreenshotEditorInstance {
+ fn drop(&mut self) {
+ self.ws_shutdown_token.cancel();
+ }
+}
+
#[derive(Clone, Default)]
pub struct PendingScreenshotEditorInstances(Arc<RwLock<HashMap<String, PendingReceiver>>>);
@@ -477,6 +483,29 @@ impl ScreenshotEditorInstances {
instance.dispose().await;
}
}
+
+ pub async fn dispose_all(app: &AppHandle) {
+ let Some(instances) = app.try_state::<ScreenshotEditorInstances>() else {
+ return;
+ };
+
+ let instances = {
+ let mut instances = instances.0.write().await;
+ std::mem::take(&mut *instances)
+ };
+
+ let count = instances.len();
+ for (_, instance) in instances {
+ instance.dispose().await;
+ }
+
+ if count > 0 {
+ tracing::info!(
+ count,
+ "Disposed screenshot editor instances during app exit"
+ );
+ }
+ }
}
impl PendingScreenshotEditorInstances {
@@ -553,6 +582,56 @@ impl PendingScreenshotEditorInstances {
});
}
}
+
+ pub async fn dispose_all(app: &AppHandle) {
+ let Some(pending) = app.try_state::<Self>() else {
+ return;
+ };
+
+ let pending = {
+ let mut instances = pending.0.write().await;
+ std::mem::take(&mut *instances)
+ };
+
+ let count = pending.len();
+ for (_, mut rx) in pending {
+ let result = tokio::time::timeout(std::time::Duration::from_millis(500), async {
+ loop {
+ let instance_to_dispose = {
+ let borrowed = rx.borrow_and_update().clone();
+ match borrowed {
+ Some(Ok(instance)) => Some(instance),
+ Some(Err(_)) => break,
+ None => None,
+ }
+ };
+
+ if let Some(instance) = instance_to_dispose {
+ instance.dispose().await;
+ break;
+ }
+
+ if rx.changed().await.is_err() {
+ break;
+ }
+ }
+ })
+ .await;
+
+ if result.is_err() {
+ tracing::warn!(
+ "Timed out disposing pending screenshot editor instance during app exit"
+ );
+ }
+ }
+
+ if count > 0 {
+ tracing::info!(
+ count,
+ "Disposed pending screenshot editor instances during app exit"
+ );
+ }
+ }
}
#[derive(Serialize, Type, Debug)]