Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(desktop-gpui): stop the Touch Bar finder's KVO exception from crashing the app
Richie McIlroy6f6442e099ce
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lockindex 469e8a146..dbe02fb1f 100644--- a/apps/desktop-gpui/Cargo.lock+++ b/apps/desktop-gpui/Cargo.lock@@ -1548,6 +1548,7 @@ dependencies = ["cap-timestamp","cap-utils","cap-verify",+ "cc","chrono","cidre","clipboard-rs",diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.tomlindex 50fccce29..d66f84793 100644--- a/apps/desktop-gpui/Cargo.toml+++ b/apps/desktop-gpui/Cargo.toml@@ -162,6 +162,7 @@ dirs = "6"whisper-rs = "0.11.0"[build-dependencies]+cc = "1.4"tauri-winres = "0.3.5"[dev-dependencies]diff --git a/apps/desktop-gpui/build.rs b/apps/desktop-gpui/build.rsindex b4885b3e5..d23d749a3 100644--- a/apps/desktop-gpui/build.rs+++ b/apps/desktop-gpui/build.rs@@ -3,6 +3,15 @@ mod diagnostic_build;fn main() {diagnostic_build::emit();+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {+ println!("cargo:rerun-if-changed=native/exception_guard.m");+ cc::Build::new()+ .file("native/exception_guard.m")+ .flag("-fobjc-exceptions")+ .flag("-fno-objc-arc")+ .compile("cap_exception_guard");+ println!("cargo:rustc-link-lib=framework=Foundation");+ }if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {return;}diff --git a/apps/desktop-gpui/native/exception_guard.m b/apps/desktop-gpui/native/exception_guard.mnew file mode 100644index 000000000..cda055fc2--- /dev/null+++ b/apps/desktop-gpui/native/exception_guard.m@@ -0,0 +1,26 @@+#import <Foundation/Foundation.h>++// Calls `imp` and catches an Objective-C exception it throws. No Rust frame+// sits between the throw and this catch, so the exception never unwinds+// through Rust. Returns the exception retained (caller releases), or nil.+id cap_call_void_imp_catching(void (*imp)(id, SEL), id receiver, SEL selector) {+ @try {+ imp(receiver, selector);+ return nil;+ } @catch (id exception) {+ return [exception retain];+ }+}++unsigned long cap_test_unbalanced_removal_calls = 0;++// Test fixture: the crash report's exception, removing a key-value observer+// that was never added.+void cap_test_unbalanced_kvo_removal(id receiver, SEL selector) {+ (void)receiver;+ (void)selector;+ cap_test_unbalanced_removal_calls += 1;+ NSObject *observed = [[NSObject new] autorelease];+ NSObject *observer = [[NSObject new] autorelease];+ [observed removeObserver:observer forKeyPath:@"touchBar"];+}diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rsindex ea6403351..eb4fe00f4 100644--- a/apps/desktop-gpui/src/main.rs+++ b/apps/desktop-gpui/src/main.rs@@ -264,6 +264,8 @@ fn main() {store::mark_handoff_session();}+ #[cfg(target_os = "macos")]+ platform::install_appkit_exception_guards();platform::install_url_scheme_handler();for argument in std::env::args().skip(1) {if argument.contains("token") || argument.contains("api_key") {diff --git a/apps/desktop-gpui/src/platform.rs b/apps/desktop-gpui/src/platform.rsindex 0e0944503..b5d42968c 100644--- a/apps/desktop-gpui/src/platform.rs+++ b/apps/desktop-gpui/src/platform.rs@@ -587,6 +587,9 @@ pub struct PanelBehavior {#[cfg(target_os = "macos")]pub use mac::*;+#[cfg(target_os = "macos")]+mod macos_exception_guard;+#[cfg(target_os = "macos")]mod macos_occlusion;@@ -615,6 +618,12 @@ mod mac {)}+ /// Keeps AppKit exceptions Cap cannot cause or prevent (the Touch Bar+ /// finder's) from crashing the app. Call on the main thread at startup.+ pub fn install_appkit_exception_guards() {+ super::macos_exception_guard::install();+ }+pub fn install_native_quit_handler() -> Result<flume::Receiver<()>, String> {use objc2::{class, ffi, msg_send, runtime::Imp, sel};use objc2_foundation::MainThreadMarker;diff --git a/apps/desktop-gpui/src/platform/macos_exception_guard.rs b/apps/desktop-gpui/src/platform/macos_exception_guard.rsnew file mode 100644index 000000000..ec2797203--- /dev/null+++ b/apps/desktop-gpui/src/platform/macos_exception_guard.rs@@ -0,0 +1,218 @@+//! AppKit methods whose Objective-C exceptions would otherwise end the app.+//!+//! On Macs with a Touch Bar, AppKit's Touch Bar finder watches the key+//! window's responder chain with key-value observing. When it rebuilds that+//! observation during a display-cycle flush, `-[_NSTouchBarFinderObservation+//! invalidate]` can throw "Cannot remove an observer ... because it is not+//! registered as an observer", and AppKit crashes the app from the commit+//! handler (a MacBookPro16,3 report, every time a recording started). Cap+//! never shows anything on the Touch Bar, so a failed teardown of that+//! observation is dropped instead.+//!+//! The catch lives in `native/exception_guard.m`: an exception must not+//! unwind through a Rust frame, so the original method is called from there.++use std::sync::OnceLock;++use objc2::{+ ffi, msg_send,+ rc::Id,+ runtime::{AnyClass, AnyObject, Imp, Sel},+ sel,+};++type VoidMethod = unsafe extern "C" fn(*mut AnyObject, Sel);++unsafe extern "C" {+ fn cap_call_void_imp_catching(+ imp: VoidMethod,+ receiver: *mut AnyObject,+ selector: Sel,+ ) -> *mut AnyObject;+}++struct GuardedMethod {+ original: OnceLock<VoidMethod>,+}++impl GuardedMethod {+ const fn new() -> Self {+ Self {+ original: OnceLock::new(),+ }+ }++ /// Routes `class`'s `selector` through `guard`. Returns false when the+ /// class does not implement it, or it is already guarded.+ fn install(&self, class: &AnyClass, selector: Sel, guard: VoidMethod) -> bool {+ if self.original.get().is_some() || class.verify_sel::<(), ()>(selector).is_err() {+ return false;+ }+ let method = unsafe {+ ffi::class_getInstanceMethod((class as *const AnyClass).cast(), selector.as_ptr())+ };+ if method.is_null() {+ return false;+ }+ let guard_imp = unsafe { std::mem::transmute::<VoidMethod, Imp>(guard) };+ let Some(current) = (unsafe { ffi::method_getImplementation(method) }) else {+ return false;+ };+ if std::ptr::fn_addr_eq(current, guard_imp) {+ return false;+ }+ let original = unsafe { std::mem::transmute::<Imp, VoidMethod>(current) };+ if self.original.set(original).is_err() {+ return false;+ }+ unsafe { ffi::method_setImplementation(method, Some(guard_imp)) };+ true+ }++ /// Calls the original implementation; an Objective-C exception it throws+ /// is logged and dropped. Returns whether one was.+ unsafe fn call(&self, receiver: *mut AnyObject, selector: Sel) -> bool {+ let Some(original) = self.original.get().copied() else {+ return false;+ };+ let exception = unsafe { cap_call_void_imp_catching(original, receiver, selector) };+ let Some(exception) = (unsafe { Id::from_raw(exception) }) else {+ return false;+ };+ tracing::warn!(+ exception = %describe(&exception),+ selector = %selector.name(),+ "ignored an AppKit exception that would have crashed the app"+ );+ true+ }+}++/// `name: reason` of an NSException.+fn describe(exception: &AnyObject) -> String {+ fn utf8(value: *mut AnyObject) -> String {+ if value.is_null() {+ return String::new();+ }+ let text: *const std::ffi::c_char = unsafe { msg_send![value, UTF8String] };+ if text.is_null() {+ return String::new();+ }+ unsafe { std::ffi::CStr::from_ptr(text) }+ .to_string_lossy()+ .into_owned()+ }+ let name: *mut AnyObject = unsafe { msg_send![exception, name] };+ let reason: *mut AnyObject = unsafe { msg_send![exception, reason] };+ format!("{}: {}", utf8(name), utf8(reason))+}++static TOUCH_BAR_FINDER_INVALIDATE: GuardedMethod = GuardedMethod::new();++unsafe extern "C" fn touch_bar_finder_invalidate(receiver: *mut AnyObject, selector: Sel) {+ unsafe { TOUCH_BAR_FINDER_INVALIDATE.call(receiver, selector) };+}++/// Call once on the main thread, before the app's run loop starts.+pub(super) fn install() {+ let Some(class) = AnyClass::get("_NSTouchBarFinderObservation") else {+ tracing::info!("AppKit has no Touch Bar finder observation class; nothing to guard");+ return;+ };+ if TOUCH_BAR_FINDER_INVALIDATE.install(class, sel!(invalidate), touch_bar_finder_invalidate) {+ tracing::info!("guarded the Touch Bar finder's observation teardown");+ }+}++#[cfg(test)]+mod tests {+ use std::sync::atomic::{AtomicUsize, Ordering};++ use objc2::{+ ClassType, msg_send, msg_send_id,+ runtime::{ClassBuilder, NSObject},+ };++ use super::*;++ unsafe extern "C" {+ static cap_test_unbalanced_removal_calls: AtomicUsize;+ fn cap_test_unbalanced_kvo_removal(receiver: *mut AnyObject, selector: Sel);+ }++ static TEST_GUARD: GuardedMethod = GuardedMethod::new();++ unsafe extern "C" fn guarded(receiver: *mut AnyObject, selector: Sel) {+ unsafe { TEST_GUARD.call(receiver, selector) };+ }++ fn test_class() -> &'static AnyClass {+ static CLASS: OnceLock<&'static AnyClass> = OnceLock::new();+ CLASS.get_or_init(|| {+ let mut builder =+ ClassBuilder::new("CapExceptionGuardTestObservation", NSObject::class()).unwrap();+ unsafe {+ builder.add_method(+ sel!(invalidate),+ cap_test_unbalanced_kvo_removal as unsafe extern "C" fn(*mut AnyObject, Sel),+ );+ }+ builder.register()+ })+ }++ fn removal_calls() -> usize {+ unsafe { cap_test_unbalanced_removal_calls.load(Ordering::SeqCst) }+ }++ #[test]+ fn an_unbalanced_kvo_removal_throws_the_reported_exception() {+ let before = removal_calls();+ let exception = unsafe {+ cap_call_void_imp_catching(+ cap_test_unbalanced_kvo_removal,+ std::ptr::null_mut(),+ sel!(invalidate),+ )+ };+ let exception = unsafe { Id::from_raw(exception) }+ .expect("removing an unregistered observer must throw");+ let description = describe(&exception);+ assert!(+ description.contains("Cannot remove an observer"),+ "{description}"+ );+ assert!(removal_calls() > before);+ }++ #[test]+ fn a_guarded_method_survives_the_exception_every_time() {+ let class = test_class();+ assert!(TEST_GUARD.install(class, sel!(invalidate), guarded));+ assert!(!TEST_GUARD.install(class, sel!(invalidate), guarded));++ let instance: Id<NSObject> = unsafe { msg_send_id![class, new] };+ for _ in 0..3 {+ let before = removal_calls();+ let _: () = unsafe { msg_send![&instance, invalidate] };+ assert!(removal_calls() > before);+ }+ }++ #[test]+ fn appkit_still_has_the_touch_bar_finder_method_this_guards() {+ assert!(+ AnyClass::get("NSApplication").is_some(),+ "AppKit is not loaded"+ );+ let class = AnyClass::get("_NSTouchBarFinderObservation")+ .expect("AppKit renamed _NSTouchBarFinderObservation; re-check the guard");+ assert!(class.verify_sel::<(), ()>(sel!(invalidate)).is_ok());+ }++ #[test]+ fn a_method_the_class_lacks_is_not_guarded() {+ static MISSING: GuardedMethod = GuardedMethod::new();+ assert!(!MISSING.install(test_class(), sel!(capNoSuchMethod), guarded));+ }+}