diff --git a/crates/gpui/examples/system_notifications.rs b/crates/gpui/examples/system_notifications.rs index faf6919120e..0deff83d241 100644 --- a/crates/gpui/examples/system_notifications.rs +++ b/crates/gpui/examples/system_notifications.rs @@ -63,7 +63,7 @@ impl Render for SystemNotificationExample { ))) .child( button("dismiss", "Dismiss").on_click(cx.listener(|this, _, _, cx| { - cx.dismiss_system_notification(NOTIFICATION_TAG); + cx.dismiss_system_notification(NOTIFICATION_TAG).detach(); this.status = "Dismissed the notification".into(); cx.notify(); })), diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs index f102819ae5c..64a79c79421 100644 --- a/crates/gpui/src/app.rs +++ b/crates/gpui/src/app.rs @@ -2085,8 +2085,11 @@ impl App { /// /// Best-effort: some platforms cannot retract a notification once shown, /// in which case it ages out of the notification center on its own. - pub fn dismiss_system_notification(&self, tag: &str) { - self.platform.dismiss_system_notification(tag); + /// The task completes after the platform calls return, not after any + /// asynchronous work inside the operating system. Dropping it does not + /// cancel dismissal. + pub fn dismiss_system_notification(&self, tag: &str) -> Task<()> { + self.platform.dismiss_system_notification(tag) } /// Registers the handler invoked when the user activates a system diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rs index beff5ea7a8f..4e6bf835798 100644 --- a/crates/gpui/src/app/test_context.rs +++ b/crates/gpui/src/app/test_context.rs @@ -1424,7 +1424,7 @@ mod tests { }] ); - cx.update(|cx| cx.dismiss_system_notification("thread-1")); + cx.update(|cx| cx.dismiss_system_notification("thread-1").detach()); assert!(cx.delivered_system_notifications().is_empty()); assert_eq!(cx.dismissed_system_notifications(), ["thread-1"]); } @@ -1499,7 +1499,7 @@ mod tests { actions: Vec::new(), }); cx.on_system_notification_response(|response, cx| { - cx.dismiss_system_notification(&response.tag); + cx.dismiss_system_notification(&response.tag).detach(); }); }); diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index 1f344f2f46a..86520ab0498 100644 --- a/crates/gpui/src/platform.rs +++ b/crates/gpui/src/platform.rs @@ -579,8 +579,12 @@ pub trait Platform: 'static { /// /// Best-effort: some platforms cannot retract a notification once shown, /// in which case it ages out of the notification center on its own. - fn dismiss_system_notification(&self, tag: &str) { + /// The task completes after the platform calls return, not after any + /// asynchronous work inside the operating system. Dropping it does not + /// cancel dismissal. + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { _ = tag; + Task::ready(()) } /// Registers the callback invoked when the user activates a system diff --git a/crates/gpui/src/platform/test/platform.rs b/crates/gpui/src/platform/test/platform.rs index 9d112b30836..64fb2a67383 100644 --- a/crates/gpui/src/platform/test/platform.rs +++ b/crates/gpui/src/platform/test/platform.rs @@ -735,7 +735,7 @@ impl Platform for TestPlatform { system_notifications.shown.push(notification); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { let mut system_notifications = self.system_notifications.borrow_mut(); system_notifications .delivered @@ -743,6 +743,7 @@ impl Platform for TestPlatform { system_notifications .dismissed .push(SharedString::from(tag.to_string())); + Task::ready(()) } fn on_system_notification_response( diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rs index b24300bbc25..c9bbd2defd8 100644 --- a/crates/gpui_linux/src/linux/platform.rs +++ b/crates/gpui_linux/src/linux/platform.rs @@ -1005,8 +1005,9 @@ impl Platform for LinuxPlatform { }); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { self.with_common(|common| common.system_notifications.dismiss(tag)); + Task::ready(()) } fn on_system_notification_response( diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs index d42ac63f2a9..218b296d0f0 100644 --- a/crates/gpui_macos/src/platform.rs +++ b/crates/gpui_macos/src/platform.rs @@ -2,6 +2,7 @@ use crate::{ AppleActivity, AppleDispatcher, BoolExt, MacDisplay, MacKeyboardLayout, MacKeyboardMapper, MacWindow, events::key_to_menu_equivalent, main_thread_marker, ns_string, pasteboard::Pasteboard, renderer, set_active_window_cursor_style, + system_notifications::NotificationCommand, }; use anyhow::{Context as _, anyhow}; use block2::RcBlock; @@ -1128,14 +1129,27 @@ impl Platform for MacPlatform { fn show_system_notification(&self, notification: gpui::SystemNotification) { let mut state = self.0.lock(); - let executor = state.foreground_executor.clone(); - state.system_notifications.show(&executor, notification); + let foreground_executor = state.foreground_executor.clone(); + let background_executor = state.background_executor.clone(); + state + .system_notifications + .send( + &foreground_executor, + &background_executor, + NotificationCommand::Show(notification), + ) + .detach(); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { let mut state = self.0.lock(); - let executor = state.foreground_executor.clone(); - state.system_notifications.dismiss(&executor, tag); + let foreground_executor = state.foreground_executor.clone(); + let background_executor = state.background_executor.clone(); + state.system_notifications.send( + &foreground_executor, + &background_executor, + NotificationCommand::Dismiss(gpui::SharedString::from(tag.to_owned())), + ) } fn on_system_notification_response( diff --git a/crates/gpui_macos/src/system_notifications.rs b/crates/gpui_macos/src/system_notifications.rs index 4bfd9522cac..8c1df527776 100644 --- a/crates/gpui_macos/src/system_notifications.rs +++ b/crates/gpui_macos/src/system_notifications.rs @@ -4,19 +4,24 @@ //! so nothing can trigger the authorization prompt or the framework's //! not-in-a-bundle abort) until the application posts a notification or //! registers a response callback. +//! +//! Notification-center calls can synchronously wait for the macOS service. +//! A single worker owns the center so those waits never block the UI, while +//! preserving the order of posting and dismissing notifications. -use std::cell::{Cell, RefCell}; +use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; +use std::sync::mpsc::{Sender, channel}; use block2::RcBlock; use futures::StreamExt as _; -use futures::channel::mpsc; +use futures::channel::{mpsc, oneshot}; use gpui::{ - ForegroundExecutor, SharedString, SystemNotification, SystemNotificationAction, - SystemNotificationResponse, Task, + BackgroundExecutor, ForegroundExecutor, SharedString, SystemNotification, + SystemNotificationAction, SystemNotificationResponse, Task, }; -use objc2::rc::Retained; +use objc2::rc::{Retained, autoreleasepool}; use objc2::runtime::{Bool, ProtocolObject}; use objc2::{AnyThread, DefinedClass, define_class, msg_send}; use objc2_foundation::{NSArray, NSBundle, NSError, NSObject, NSObjectProtocol, NSSet, NSString}; @@ -30,10 +35,19 @@ use objc2_user_notifications::{ type ResponseCallback = Rc>>>; +#[cfg_attr(test, derive(Debug, PartialEq, Eq))] +pub(crate) enum NotificationCommand { + Show(SystemNotification), + Dismiss(SharedString), +} + pub(crate) struct SystemNotificationState { initialized: bool, - center: Option, + commands: Option)>>, callback: ResponseCallback, + /// The center's `delegate` property is weak; keeping the delegate retained + /// here keeps response handling alive for the app's lifetime. + _delegate: Option>, _response_task: Option>, } @@ -41,24 +55,35 @@ impl SystemNotificationState { pub(crate) fn new() -> Self { Self { initialized: false, - center: None, + commands: None, callback: Rc::new(RefCell::new(None)), + _delegate: None, _response_task: None, } } - pub(crate) fn show(&mut self, executor: &ForegroundExecutor, notification: SystemNotification) { - self.initialize(executor); - if let Some(center) = &self.center { - center.show(notification); - } - } - - pub(crate) fn dismiss(&mut self, executor: &ForegroundExecutor, tag: &str) { - self.initialize(executor); - if let Some(center) = &self.center { - center.dismiss(tag); + pub(crate) fn send( + &mut self, + foreground_executor: &ForegroundExecutor, + background_executor: &BackgroundExecutor, + command: NotificationCommand, + ) -> Task<()> { + self.initialize(foreground_executor); + let Some(commands) = &self.commands else { + return Task::ready(()); + }; + let (completed, completion) = oneshot::channel(); + if let Err(error) = commands.send((command, completed)) { + log::error!("system notification worker disconnected: {error}"); + return Task::ready(()); } + background_executor.spawn(async move { + if let Err(error) = completion.await { + log::error!( + "system notification worker stopped before completing a command: {error}" + ); + } + }) } pub(crate) fn on_response( @@ -76,12 +101,46 @@ impl SystemNotificationState { } self.initialized = true; - let (sender, mut receiver) = mpsc::unbounded(); - self.center = NotificationCenter::new(sender); - if self.center.is_none() { + // UserNotifications aborts outside an app bundle. Checking the bundle + // does not contact the notification service. + if NSBundle::mainBundle().bundleIdentifier().is_none() { + log::info!("system notifications disabled: not running from an app bundle"); return; } + let (sender, mut receiver) = mpsc::unbounded(); + // Install the delegate before returning so a response delivered right + // after registration (e.g. the click that launched the app) has + // somewhere to go. Setting the delegate doesn't wait on the + // notification service, unlike the calls handled by the worker. + let delegate = autoreleasepool(|_| { + let delegate = NotificationResponseDelegate::new(sender); + UNUserNotificationCenter::currentNotificationCenter() + .setDelegate(Some(ProtocolObject::from_ref(&*delegate))); + delegate + }); + self._delegate = Some(delegate); + + let (commands, pending_commands) = channel::<(NotificationCommand, oneshot::Sender<()>)>(); + let worker = std::thread::Builder::new() + .name("system-notifications".into()) + .spawn(move || { + let mut center = autoreleasepool(|_| NotificationCenter::new()); + for (command, completed) in pending_commands { + autoreleasepool(|_| match command { + NotificationCommand::Show(notification) => center.show(notification), + NotificationCommand::Dismiss(tag) => center.dismiss(&tag), + }); + // The caller may stop waiting without cancelling the operation. + _ = completed.send(()); + } + }); + if let Err(error) = worker { + log::error!("failed to start system notification worker: {error}"); + return; + } + self.commands = Some(commands); + // Responses arrive from the delegate on an arbitrary thread; this task // hands them to the registered callback on the main thread. let callback = self.callback.clone(); @@ -102,46 +161,28 @@ impl SystemNotificationState { struct NotificationCenter { center: Retained, - /// The center's `delegate` property is weak; keeping the delegate retained - /// here keeps response handling alive for the app's lifetime. - _delegate: Retained, /// The union of every action set registered so far. Categories are shared /// by notifications with identical actions because macOS replaces the /// entire registered set whenever a category is added. - categories: RefCell< + categories: HashMap, (SharedString, Retained)>, - >, - authorization_requested: Cell, + authorization_requested: bool, } impl NotificationCenter { - fn new(sender: mpsc::UnboundedSender) -> Option { - // `UNUserNotificationCenter` raises `NSInternalInconsistencyException` - // ("bundleProxyForCurrentProcess is nil"), aborting the process, when - // the binary isn't part of an app bundle — which is how dev builds run - // via `cargo run`. A bundle identifier is only present when launched - // from a real `.app`, so use it as the guard. - if NSBundle::mainBundle().bundleIdentifier().is_none() { - log::info!("system notifications disabled: not running from an app bundle"); - return None; + fn new() -> Self { + Self { + center: UNUserNotificationCenter::currentNotificationCenter(), + categories: HashMap::new(), + authorization_requested: false, } - - let center = UNUserNotificationCenter::currentNotificationCenter(); - let delegate = NotificationResponseDelegate::new(sender); - center.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); - - Some(Self { - center, - _delegate: delegate, - categories: RefCell::new(HashMap::new()), - authorization_requested: Cell::new(false), - }) } - fn request_authorization(&self) { - if self.authorization_requested.replace(true) { + fn request_authorization(&mut self) { + if self.authorization_requested { return; } + self.authorization_requested = true; let completion = RcBlock::new(|granted: Bool, error: *mut NSError| { // SAFETY: when non-null, `error` is a valid `NSError` for the // duration of the callback. @@ -161,7 +202,7 @@ impl NotificationCenter { ); } - fn show(&self, notification: SystemNotification) { + fn show(&mut self, notification: SystemNotification) { self.request_authorization(); let content = UNMutableNotificationContent::new(); @@ -194,14 +235,15 @@ impl NotificationCenter { .addNotificationRequest_withCompletionHandler(&request, Some(&completion)); } - fn register_category(&self, actions: &[SystemNotificationAction]) -> SharedString { - let mut categories = self.categories.borrow_mut(); - if let Some((identifier, _category)) = categories.get(actions) { + fn register_category(&mut self, actions: &[SystemNotificationAction]) -> SharedString { + if let Some((identifier, _category)) = self.categories.get(actions) { return identifier.clone(); } - let identifier = - SharedString::from(format!("gpui-system-notification-{}", categories.len())); + let identifier = SharedString::from(format!( + "gpui-system-notification-{}", + self.categories.len() + )); let platform_actions: Vec> = actions .iter() .map(|action| { @@ -220,8 +262,10 @@ impl NotificationCenter { UNNotificationCategoryOptions::empty(), ); - categories.insert(actions.to_vec(), (identifier.clone(), category)); - let all: Vec> = categories + self.categories + .insert(actions.to_vec(), (identifier.clone(), category)); + let all: Vec> = self + .categories .values() .map(|(_identifier, category)| category.clone()) .collect(); @@ -307,3 +351,65 @@ impl NotificationResponseDelegate { unsafe { msg_send![super(this), init] } } } + +#[cfg(test)] +mod tests { + use super::*; + use futures::FutureExt as _; + + #[gpui::test] + async fn test_notification_commands_do_not_wait_for_the_service(cx: &mut gpui::TestAppContext) { + let (sender, receiver) = channel(); + let mut state = SystemNotificationState { + initialized: true, + commands: Some(sender), + ..SystemNotificationState::new() + }; + let notification = SystemNotification { + tag: "thread".into(), + title: "Finished".into(), + body: "Ready for input".into(), + actions: vec![], + }; + + // No service consumes commands until after every UI call has returned. + let mut tasks = [ + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Show(notification.clone()), + ), + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Dismiss("thread".into()), + ), + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Show(notification.clone()), + ), + ]; + for task in &mut tasks { + assert!(task.now_or_never().is_none()); + } + + let (commands, completions): (Vec<_>, Vec<_>) = receiver.try_iter().unzip(); + assert_eq!( + commands, + vec![ + NotificationCommand::Show(notification.clone()), + NotificationCommand::Dismiss("thread".into()), + NotificationCommand::Show(notification), + ] + ); + for completed in completions { + completed + .send(()) + .expect("caller is waiting for completion"); + } + for task in tasks { + task.await; + } + } +} diff --git a/crates/gpui_windows/src/platform.rs b/crates/gpui_windows/src/platform.rs index 4cf4b6be35f..a5f0d49e704 100644 --- a/crates/gpui_windows/src/platform.rs +++ b/crates/gpui_windows/src/platform.rs @@ -927,8 +927,9 @@ impl Platform for WindowsPlatform { .log_err(); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { self.system_notifications.borrow_mut().dismiss(tag); + Task::ready(()) } fn on_system_notification_response(