Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Harden event handling and state access
Richie McIlroyf9d5245f7f81
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex b17aac540..865d58f95 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -1168,17 +1168,22 @@ pub(crate) fn schedule_resume_recovery(app_handle: AppHandle) {#[cfg(target_os = "macos")]{- let prewarmer = app_handle.state::<crate::platform::ScreenCapturePrewarmer>();- prewarmer.request(true).await;+ if let Some(prewarmer) =+ app_handle.try_state::<crate::platform::ScreenCapturePrewarmer>()+ {+ prewarmer.request(true).await;+ } else {+ warn!("ScreenCapturePrewarmer state unavailable during resume recovery");+ }}if !app_is_exiting(&app_handle) {- let _ = RequestScreenCapturePrewarm { force: true }.emit(&app_handle);+ emit_app_event_safely(&app_handle, RequestScreenCapturePrewarm { force: true });}if !app_is_exiting(&app_handle) {let snapshot = get_devices_snapshot().await;- let _ = snapshot.emit(&app_handle);+ emit_app_event_safely(&app_handle, snapshot);}});}@@ -2488,7 +2493,9 @@ async fn set_project_config(editor_instance: WindowEditorInstance,config: ProjectConfiguration,) -> Result<(), String> {- config.write(&editor_instance.project_path).unwrap();+ config+ .write(&editor_instance.project_path)+ .map_err(|error| format!("Failed to write project config: {error}"))?;editor_instance.project_config.0.send(config).ok();@@ -3443,8 +3450,10 @@ async fn set_camera_preview_state(#[specta::specta]#[instrument(skip(app))]fn set_camera_window_position(app: AppHandle, x: f64, y: f64) -> Result<(), String> {- let guard = app.state::<CameraWindowPositionGuard>();- if guard.should_ignore() {+ if app+ .try_state::<CameraWindowPositionGuard>()+ .is_some_and(|guard| guard.should_ignore())+ {return Ok(());}@@ -4127,30 +4136,31 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {Ok(())}).on_window_event(|window, event| {- let label = window.label();- let app = window.app_handle();-- if matches!(- event,- WindowEvent::CloseRequested { .. }- | WindowEvent::Moved(_)- | WindowEvent::Focused(_)- ) && app_is_exiting(app)- {- return;- }+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let label = window.label();+ let app = window.app_handle();++ if matches!(+ event,+ WindowEvent::CloseRequested { .. }+ | WindowEvent::Moved(_)+ | WindowEvent::Focused(_)+ ) && app_is_exiting(app)+ {+ return;+ }- match event {- WindowEvent::CloseRequested { api, .. } => {- if let Ok(window_id) = CapWindowId::from_str(label) {- match window_id {- CapWindowId::Camera => {- if app- .try_state::<CameraWindowCloseGate>()- .is_some_and(|close_gate| close_gate.allow_close())- {- return;- }+ match event {+ WindowEvent::CloseRequested { api, .. } => {+ if let Ok(window_id) = CapWindowId::from_str(label) {+ match window_id {+ CapWindowId::Camera => {+ if app+ .try_state::<CameraWindowCloseGate>()+ .is_some_and(|close_gate| close_gate.allow_close())+ {+ return;+ }api.prevent_close();let _ = window.hide();@@ -4448,8 +4458,10 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {);}CapWindowId::Camera => {- let guard = app.state::<CameraWindowPositionGuard>();- if guard.should_ignore() {+ if app+ .try_state::<CameraWindowPositionGuard>()+ .is_some_and(|guard| guard.should_ignore())+ {return;}window_position_persistence::queue_camera_position(@@ -4462,7 +4474,17 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {}}}- _ => {}+ _ => {}+ }+ }));++ if let Err(panic) = result {+ let message = panic_payload_message(&panic);+ tracing::error!(panic = %message, "Suppressed panic in Tauri WindowEvent handler");+ sentry::capture_message(+ &format!("Tauri WindowEvent panic suppressed: {message}"),+ sentry::Level::Error,+ );}}).build(tauri_context)@@ -4484,7 +4506,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {});}-fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {+pub(crate) fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {if let Some(s) = payload.downcast_ref::<&'static str>() {(*s).to_string()} else if let Some(s) = payload.downcast_ref::<String>() {@@ -4494,6 +4516,21 @@ fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {}}+fn emit_app_event_safely<E>(app: &AppHandle, event: E)+where+ E: Event + Serialize + Clone,+{+ let event_name = std::any::type_name::<E>();+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| event.emit(app))) {+ Ok(Ok(())) => {}+ Ok(Err(error)) => warn!(event = event_name, %error, "Failed to emit app event"),+ Err(panic) => {+ let message = panic_payload_message(&panic);+ error!(event = event_name, panic = %message, "Suppressed panic while emitting app event");+ }+ }+}+fn handle_run_event(_handle: &AppHandle, event: tauri::RunEvent) {match event {#[cfg(target_os = "macos")]diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 2ba78b137..03a762fb8 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -476,22 +476,36 @@ fn microphone_format_infos(device: &cpal::Device) -> Vec<MicrophoneFormatInfo> {#[specta::specta]#[instrument]pub async fn list_displays_with_thumbnails() -> Result<Vec<CaptureDisplayWithThumbnail>, String> {- tokio::task::spawn_blocking(|| {- tauri::async_runtime::block_on(collect_displays_with_thumbnails())- })- .await- .map_err(|e| e.to_string())?+ run_non_send_thumbnail_future(collect_displays_with_thumbnails())}#[tauri::command]#[specta::specta]#[instrument]pub async fn list_windows_with_thumbnails() -> Result<Vec<CaptureWindowWithThumbnail>, String> {- tokio::task::spawn_blocking(- || tauri::async_runtime::block_on(collect_windows_with_thumbnails()),- )- .await- .map_err(|e| e.to_string())?+ run_non_send_thumbnail_future(collect_windows_with_thumbnails())+}++fn run_non_send_thumbnail_future<T, F>(future: F) -> Result<T, String>+where+ F: std::future::Future<Output = Result<T, String>>,+{+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ if tokio::runtime::Handle::try_current().is_ok() {+ tokio::task::block_in_place(|| tauri::async_runtime::block_on(future))+ } else {+ tauri::async_runtime::block_on(future)+ }+ }));++ match result {+ Ok(result) => result,+ Err(panic) => {+ let message = crate::panic_payload_message(&panic);+ error!(panic = %message, "Suppressed panic while collecting capture thumbnails");+ Err(format!("Failed to collect capture thumbnails: {message}"))+ }+ }}#[derive(Deserialize, Type, Clone, Debug)]diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 0f62d9994..5071acc6c 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -96,6 +96,21 @@ pub fn show_overlay(window: &WebviewWindow) {let _ = window.show();}+fn emit_app_event<E>(app: &AppHandle, event: E)+where+ E: Event + serde::Serialize + Clone,+{+ let event_name = std::any::type_name::<E>();+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| event.emit(app))) {+ Ok(Ok(())) => {}+ Ok(Err(error)) => warn!(event = event_name, %error, "Failed to emit app event"),+ Err(panic) => {+ let message = crate::panic_payload_message(&panic);+ error!(event = event_name, panic = %message, "Suppressed panic while emitting app event");+ }+ }+}+fn hide_recording_windows(app: &AppHandle) {for (label, window) in app.webview_windows() {if let Ok(id) = CapWindowId::from_str(&label)@@ -148,8 +163,12 @@ async fn ensure_camera_input_active(app_state: &mut App) {}async fn restore_main_window_inputs(app: &AppHandle) {- let should_restore = app- .state::<ArcLock<App>>()+ let Some(state) = app.try_state::<ArcLock<App>>() else {+ warn!("App state unavailable while restoring main window inputs");+ return;+ };++ let should_restore = state.try_read().map(|state| !state.is_recording_active_or_pending()).unwrap_or(false);@@ -164,15 +183,17 @@ async fn restore_main_window_inputs(app: &AppHandle) {.unwrap_or_default();let stored_camera_id = settings.camera_id.clone();- if let Err(err) = crate::set_mic_input(app.state(), settings.mic_name).await {+ if let Err(err) = crate::set_mic_input(state.clone(), settings.mic_name).await {warn!("Failed to restore microphone input for main window: {err}");}- let operation_lock = app.state::<crate::CameraWindowOperationLock>();+ let Some(operation_lock) = app.try_state::<crate::CameraWindowOperationLock>() else {+ warn!("CameraWindowOperationLock unavailable while restoring main window inputs");+ return;+ };let operation_guard = operation_lock.lock().await;- let camera_to_restore = app- .state::<ArcLock<App>>()+ let camera_to_restore = state.try_read().map(|s| {if !s.camera_cleanup_done && !s.camera_in_use {@@ -186,7 +207,6 @@ async fn restore_main_window_inputs(app: &AppHandle) {.unwrap_or(None);if let Some(camera_id) = camera_to_restore {- let state = app.state::<ArcLock<App>>();let settings =crate::recording_settings::RecordingSettingsStore::camera_settings_for(app, &camera_id);@@ -424,11 +444,13 @@ impl CursorMonitorInfo {}fn center_camera_window(app: &AppHandle, window: &WebviewWindow) {- let state = app.state::<ArcLock<crate::App>>();- let camera_state = if let Ok(guard) = state.try_read() {- guard.camera_preview.get_state().ok().unwrap_or_default()- } else {- crate::camera::CameraPreviewState::default()+ let camera_state = match app.try_state::<ArcLock<crate::App>>() {+ Some(state) => state+ .try_read()+ .ok()+ .and_then(|guard| guard.camera_preview.get_state().ok())+ .unwrap_or_default(),+ None => crate::camera::CameraPreviewState::default(),};let toolbar_height = 56.0;@@ -443,10 +465,14 @@ fn center_camera_window(app: &AppHandle, window: &WebviewWindow) {let (pos_x, pos_y) = monitor_info.center_position(window_width, window_height);let _ = window.set_size(tauri::LogicalSize::new(window_width, window_height));- app.state::<CameraWindowPositionGuard>().ignore_for(1000);+ if let Some(guard) = app.try_state::<CameraWindowPositionGuard>() {+ guard.ignore_for(1000);+ }let _ = window.set_position(tauri::LogicalPosition::new(pos_x, pos_y));- if let Ok(guard) = state.try_read() {+ if let Some(state) = app.try_state::<ArcLock<crate::App>>()+ && let Ok(guard) = state.try_read()+ {guard.camera_preview.notify_window_resized(window_width as u32, window_height as u32);@@ -874,7 +900,10 @@ impl ShowCapWindow {panel_manager.mark_ready(PanelWindowType::Camera, 0).await;}- let state = app.state::<ArcLock<App>>();+ let Some(state) = app.try_state::<ArcLock<App>>() else {+ warn!("App state unavailable while showing camera window");+ return Err(tauri::Error::WindowNotFound);+ };let mut app_state = state.write().await;let enable_native_camera_preview = GeneralSettingsStore::get(app)@@ -956,7 +985,10 @@ impl ShowCapWindow {#[cfg(not(target_os = "macos"))]{- let state = app.state::<ArcLock<App>>();+ let Some(state) = app.try_state::<ArcLock<App>>() else {+ warn!("App state unavailable while showing camera window");+ return Err(tauri::Error::WindowNotFound);+ };let mut app_state = state.write().await;let enable_native_camera_preview = GeneralSettingsStore::get(app)@@ -1005,19 +1037,26 @@ impl ShowCapWindow {hide_recording_windows(app);let is_recording = app- .state::<ArcLock<App>>()- .try_read()- .map(|state| state.is_recording_active_or_pending())+ .try_state::<ArcLock<App>>()+ .and_then(|state| {+ state+ .try_read()+ .ok()+ .map(|state| state.is_recording_active_or_pending())+ }).unwrap_or(true);if !is_recording {let app = app.clone();tokio::spawn(async move {- let state = app.state::<ArcLock<App>>();- let app_state = &mut *state.write().await;- app_state.camera_preview.pause();- let _ = app_state.camera_feed.ask(feeds::camera::RemoveInput).await;- app_state.camera_in_use = false;+ if let Some(state) = app.try_state::<ArcLock<App>>() {+ let app_state = &mut *state.write().await;+ app_state.camera_preview.pause();+ let _ = app_state.camera_feed.ask(feeds::camera::RemoveInput).await;+ app_state.camera_in_use = false;+ } else {+ warn!("App state unavailable while pausing camera preview");+ }});}}@@ -1128,11 +1167,13 @@ impl ShowCapWindow {} = self{window.hide().ok();- let _ = RequestSetTargetMode {- target_mode: Some(*target_mode),- display_id: cursor_display_id,- }- .emit(app);+ emit_app_event(+ app,+ RequestSetTargetMode {+ target_mode: Some(*target_mode),+ display_id: cursor_display_id,+ },+ );} else {if let Self::Main { .. } = self {restore_main_window_inputs(app).await;@@ -1151,11 +1192,13 @@ impl ShowCapWindow {}if let Self::Main { init_target_mode } = self {- let _ = RequestSetTargetMode {- target_mode: *init_target_mode,- display_id: cursor_display_id,- }- .emit(app);+ emit_app_event(+ app,+ RequestSetTargetMode {+ target_mode: *init_target_mode,+ display_id: cursor_display_id,+ },+ );}}@@ -1263,14 +1306,18 @@ impl ShowCapWindow {let app_handle = app.clone();tauri::async_runtime::spawn(async move {- let prewarmer =- app_handle.state::<crate::platform::ScreenCapturePrewarmer>();- prewarmer.request(false).await;+ if let Some(prewarmer) =+ app_handle.try_state::<crate::platform::ScreenCapturePrewarmer>()+ {+ prewarmer.request(false).await;+ } else {+ warn!(+ "ScreenCapturePrewarmer state unavailable during main window creation"+ );+ }});- if let Err(error) = (RequestScreenCapturePrewarm { force: false }).emit(app) {- warn!(%error, "Failed to emit ScreenCaptureKit prewarm event");- }+ emit_app_event(app, RequestScreenCapturePrewarm { force: false });}#[cfg(not(target_os = "macos"))]@@ -1307,7 +1354,10 @@ impl ShowCapWindow {};let camera_ws_port = {- let state = app.state::<ArcLock<App>>();+ let Some(state) = app.try_state::<ArcLock<App>>() else {+ warn!("App state unavailable during target select overlay creation");+ return Err(tauri::Error::WindowNotFound);+ };let state = state.read().await;state.camera_ws_port};@@ -1705,7 +1755,10 @@ impl ShowCapWindow {.unwrap_or_default();{- let state = app.state::<ArcLock<App>>();+ let Some(state) = app.try_state::<ArcLock<App>>() else {+ warn!("App state unavailable while creating camera window");+ return Err(tauri::Error::WindowNotFound);+ };let mut state = state.write().await;let shutdown_preview =@@ -1830,7 +1883,9 @@ impl ShowCapWindow {#[cfg(not(target_os = "macos"))]{- app.state::<CameraWindowPositionGuard>().ignore_for(1000);+ if let Some(guard) = app.try_state::<CameraWindowPositionGuard>() {+ guard.ignore_for(1000);+ }let _ = window.set_position(tauri::LogicalPosition::new(camera_pos_x, camera_pos_y));}@@ -1887,7 +1942,9 @@ impl ShowCapWindow {unsafe { CGWindowLevelForKey(kCGMaximumWindowLevelKey) };panel.set_level(max_level);- app.state::<CameraWindowPositionGuard>().ignore_for(1000);+ if let Some(guard) = app.try_state::<CameraWindowPositionGuard>() {+ guard.ignore_for(1000);+ }let _ = window.set_position(tauri::LogicalPosition::new(camera_pos_x,camera_pos_y,diff --git a/vendor/tao/src/platform_impl/macos/app_delegate.rs b/vendor/tao/src/platform_impl/macos/app_delegate.rsindex 2f962a2d9..b6efed980 100644--- a/vendor/tao/src/platform_impl/macos/app_delegate.rs+++ b/vendor/tao/src/platform_impl/macos/app_delegate.rs@@ -130,9 +130,15 @@ extern "C" fn did_finish_launching(this: &Object, _: Sel, _: id) {}extern "C" fn application_will_terminate(_: &Object, _: Sel, _: id) {- trace!("Triggered `applicationWillTerminate`");- AppState::exit();- trace!("Completed `applicationWillTerminate`");+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ trace!("Triggered `applicationWillTerminate`");+ AppState::exit();+ trace!("Completed `applicationWillTerminate`");+ }));++ if result.is_err() {+ error!("Suppressed panic in `applicationWillTerminate`");+ }}extern "C" fn application_open_urls(_: &Object, _: Sel, _: id, urls: &NSArray<NSURL>) {diff --git a/vendor/tao/src/platform_impl/macos/window_delegate.rs b/vendor/tao/src/platform_impl/macos/window_delegate.rsindex b84edc98c..01a4797c0 100644--- a/vendor/tao/src/platform_impl/macos/window_delegate.rs+++ b/vendor/tao/src/platform_impl/macos/window_delegate.rs@@ -280,6 +280,19 @@ fn with_state<F: FnOnce(&mut WindowDelegateState) -> T, T>(this: &Object, callbacallback(state_ptr);}+fn suppress_delegate_panic<T, F>(selector: &'static str, fallback: T, operation: F) -> T+where+ F: FnOnce() -> T,+{+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(operation)) {+ Ok(value) => value,+ Err(_) => {+ error!("Suppressed panic in `{selector}`");+ fallback+ }+ }+}+extern "C" fn dealloc(this: &Object, _sel: Sel) {with_state(this, |state| unsafe {drop(Box::from_raw(state as *mut WindowDelegateState));@@ -325,23 +338,27 @@ extern "C" fn clear_is_checking_zoomed_in(this: &Object, _sel: Sel) {}extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {- trace!("Triggered `windowShouldClose:`");- with_state(this, |state| state.emit_event(WindowEvent::CloseRequested));- trace!("Completed `windowShouldClose:`");- NO+ suppress_delegate_panic("windowShouldClose:", NO, || {+ trace!("Triggered `windowShouldClose:`");+ with_state(this, |state| state.emit_event(WindowEvent::CloseRequested));+ trace!("Completed `windowShouldClose:`");+ NO+ })}extern "C" fn window_will_close(this: &Object, _: Sel, _: id) {- trace!("Triggered `windowWillClose:`");- with_state(this, |state| unsafe {- // `setDelegate:` retains the previous value and then autoreleases it- let _pool = NSAutoreleasePool::new();- // Since El Capitan, we need to be careful that delegate methods can't- // be called after the window closes.- let () = msg_send![&state.ns_window, setDelegate: nil];- state.emit_event(WindowEvent::Destroyed);+ suppress_delegate_panic("windowWillClose:", (), || {+ trace!("Triggered `windowWillClose:`");+ with_state(this, |state| unsafe {+ // `setDelegate:` retains the previous value and then autoreleases it+ let _pool = NSAutoreleasePool::new();+ // Since El Capitan, we need to be careful that delegate methods can't+ // be called after the window closes.+ let () = msg_send![&state.ns_window, setDelegate: nil];+ state.emit_event(WindowEvent::Destroyed);+ });+ trace!("Completed `windowWillClose:`");});- trace!("Completed `windowWillClose:`");}extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {@@ -373,45 +390,49 @@ extern "C" fn window_did_change_backing_properties(this: &Object, _: Sel, _: id)}extern "C" fn window_did_become_key(this: &Object, _: Sel, _: id) {- trace!("Triggered `windowDidBecomeKey:`");- with_state(this, |state| {- // TODO: center the cursor if the window had mouse grab when it- // lost focus- state.emit_event(WindowEvent::Focused(true));+ suppress_delegate_panic("windowDidBecomeKey:", (), || {+ trace!("Triggered `windowDidBecomeKey:`");+ with_state(this, |state| {+ // TODO: center the cursor if the window had mouse grab when it+ // lost focus+ state.emit_event(WindowEvent::Focused(true));+ });+ trace!("Completed `windowDidBecomeKey:`");});- trace!("Completed `windowDidBecomeKey:`");}extern "C" fn window_did_resign_key(this: &Object, _: Sel, _: id) {- trace!("Triggered `windowDidResignKey:`");- with_state(this, |state| {- // It happens rather often, e.g. when the user is Cmd+Tabbing, that the- // NSWindowDelegate will receive a didResignKey event despite no event- // being received when the modifiers are released. This is because- // flagsChanged events are received by the NSView instead of the- // NSWindowDelegate, and as a result a tracked modifiers state can quite- // easily fall out of synchrony with reality. This requires us to emit- // a synthetic ModifiersChanged event when we lose focus.- //- // Here we (very unsafely) acquire the taoState (a ViewState) from the- // Object referenced by state.ns_view (an IdRef, which is dereferenced- // to an id)- #[allow(deprecated)] // TODO: Use define_class!- let view_state: &mut ViewState = unsafe {- let ns_view: &Object = &state.ns_view;- let state_ptr: *mut c_void = *ns_view.get_ivar("taoState");- &mut *(state_ptr as *mut ViewState)- };+ suppress_delegate_panic("windowDidResignKey:", (), || {+ trace!("Triggered `windowDidResignKey:`");+ with_state(this, |state| {+ // It happens rather often, e.g. when the user is Cmd+Tabbing, that the+ // NSWindowDelegate will receive a didResignKey event despite no event+ // being received when the modifiers are released. This is because+ // flagsChanged events are received by the NSView instead of the+ // NSWindowDelegate, and as a result a tracked modifiers state can quite+ // easily fall out of synchrony with reality. This requires us to emit+ // a synthetic ModifiersChanged event when we lose focus.+ //+ // Here we (very unsafely) acquire the taoState (a ViewState) from the+ // Object referenced by state.ns_view (an IdRef, which is dereferenced+ // to an id)+ #[allow(deprecated)] // TODO: Use define_class!+ let view_state: &mut ViewState = unsafe {+ let ns_view: &Object = &state.ns_view;+ let state_ptr: *mut c_void = *ns_view.get_ivar("taoState");+ &mut *(state_ptr as *mut ViewState)+ };- // Both update the state and emit a ModifiersChanged event.- if !view_state.modifiers.is_empty() {- view_state.modifiers = ModifiersState::empty();- state.emit_event(WindowEvent::ModifiersChanged(view_state.modifiers));- }+ // Both update the state and emit a ModifiersChanged event.+ if !view_state.modifiers.is_empty() {+ view_state.modifiers = ModifiersState::empty();+ state.emit_event(WindowEvent::ModifiersChanged(view_state.modifiers));+ }- state.emit_event(WindowEvent::Focused(false));+ state.emit_event(WindowEvent::Focused(false));+ });+ trace!("Completed `windowDidResignKey:`");});- trace!("Completed `windowDidResignKey:`");}/// Invoked when the dragged image enters destination bounds or frame