notifications.rs

  1use crate::{Toast, Workspace};
  2use gpui::{
  3    svg, AnyView, App, AppContext as _, AsyncWindowContext, ClipboardItem, Context, DismissEvent,
  4    Entity, EventEmitter, Global, PromptLevel, Render, ScrollHandle, Task,
  5};
  6use parking_lot::Mutex;
  7use std::sync::{Arc, LazyLock};
  8use std::{any::TypeId, time::Duration};
  9use ui::{prelude::*, Tooltip};
 10use util::ResultExt;
 11
 12#[derive(Debug, PartialEq, Clone)]
 13pub enum NotificationId {
 14    Unique(TypeId),
 15    Composite(TypeId, ElementId),
 16    Named(SharedString),
 17}
 18
 19impl NotificationId {
 20    /// Returns a unique [`NotificationId`] for the given type.
 21    pub fn unique<T: 'static>() -> Self {
 22        Self::Unique(TypeId::of::<T>())
 23    }
 24
 25    /// Returns a [`NotificationId`] for the given type that is also identified
 26    /// by the provided ID.
 27    pub fn composite<T: 'static>(id: impl Into<ElementId>) -> Self {
 28        Self::Composite(TypeId::of::<T>(), id.into())
 29    }
 30
 31    /// Builds a `NotificationId` out of the given string.
 32    pub fn named(id: SharedString) -> Self {
 33        Self::Named(id)
 34    }
 35}
 36
 37pub trait Notification: EventEmitter<DismissEvent> + Render {}
 38
 39impl<V: EventEmitter<DismissEvent> + Render> Notification for V {}
 40
 41impl Workspace {
 42    #[cfg(any(test, feature = "test-support"))]
 43    pub fn notification_ids(&self) -> Vec<NotificationId> {
 44        self.notifications
 45            .iter()
 46            .map(|(id, _)| id)
 47            .cloned()
 48            .collect()
 49    }
 50
 51    pub fn show_notification<V: Notification>(
 52        &mut self,
 53        id: NotificationId,
 54        cx: &mut Context<Self>,
 55        build_notification: impl FnOnce(&mut Context<Self>) -> Entity<V>,
 56    ) {
 57        self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
 58            let notification = build_notification(cx);
 59            cx.subscribe(&notification, {
 60                let id = id.clone();
 61                move |this, _, _: &DismissEvent, cx| {
 62                    this.dismiss_notification(&id, cx);
 63                }
 64            })
 65            .detach();
 66            notification.into()
 67        });
 68    }
 69
 70    /// Shows a notification in this workspace's window. Caller must handle dismiss.
 71    ///
 72    /// This exists so that the `build_notification` closures stored for app notifications can
 73    /// return `AnyView`. Subscribing to events from an `AnyView` is not supported, so instead that
 74    /// responsibility is pushed to the caller where the `V` type is known.
 75    pub(crate) fn show_notification_without_handling_dismiss_events(
 76        &mut self,
 77        id: &NotificationId,
 78        cx: &mut Context<Self>,
 79        build_notification: impl FnOnce(&mut Context<Self>) -> AnyView,
 80    ) {
 81        self.dismiss_notification(id, cx);
 82        self.notifications
 83            .push((id.clone(), build_notification(cx)));
 84        cx.notify();
 85    }
 86
 87    pub fn show_error<E>(&mut self, err: &E, cx: &mut Context<Self>)
 88    where
 89        E: std::fmt::Debug + std::fmt::Display,
 90    {
 91        self.show_notification(workspace_error_notification_id(), cx, |cx| {
 92            cx.new(|_| ErrorMessagePrompt::new(format!("Error: {err}")))
 93        });
 94    }
 95
 96    pub fn show_portal_error(&mut self, err: String, cx: &mut Context<Self>) {
 97        struct PortalError;
 98
 99        self.show_notification(NotificationId::unique::<PortalError>(), cx, |cx| {
100            cx.new(|_| {
101                ErrorMessagePrompt::new(err.to_string()).with_link_button(
102                    "See docs",
103                    "https://zed.dev/docs/linux#i-cant-open-any-files",
104                )
105            })
106        });
107    }
108
109    pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
110        self.notifications.retain(|(existing_id, _)| {
111            if existing_id == id {
112                cx.notify();
113                false
114            } else {
115                true
116            }
117        });
118    }
119
120    pub fn show_toast(&mut self, toast: Toast, cx: &mut Context<Self>) {
121        self.dismiss_notification(&toast.id, cx);
122        self.show_notification(toast.id.clone(), cx, |cx| {
123            cx.new(|_| match toast.on_click.as_ref() {
124                Some((click_msg, on_click)) => {
125                    let on_click = on_click.clone();
126                    simple_message_notification::MessageNotification::new(toast.msg.clone())
127                        .primary_message(click_msg.clone())
128                        .primary_on_click(move |window, cx| on_click(window, cx))
129                }
130                None => simple_message_notification::MessageNotification::new(toast.msg.clone()),
131            })
132        });
133        if toast.autohide {
134            cx.spawn(|workspace, mut cx| async move {
135                cx.background_executor()
136                    .timer(Duration::from_millis(5000))
137                    .await;
138                workspace
139                    .update(&mut cx, |workspace, cx| {
140                        workspace.dismiss_toast(&toast.id, cx)
141                    })
142                    .ok();
143            })
144            .detach();
145        }
146    }
147
148    pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
149        self.dismiss_notification(id, cx);
150    }
151
152    pub fn clear_all_notifications(&mut self, cx: &mut Context<Self>) {
153        self.notifications.clear();
154        cx.notify();
155    }
156
157    pub fn show_initial_notifications(&mut self, cx: &mut Context<Self>) {
158        // Allow absence of the global so that tests don't need to initialize it.
159        let app_notifications = cx
160            .try_global::<AppNotifications>()
161            .iter()
162            .flat_map(|global| global.app_notifications.iter().cloned())
163            .collect::<Vec<_>>();
164        for (id, build_notification) in app_notifications {
165            self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
166                build_notification(cx)
167            });
168        }
169    }
170}
171
172pub struct LanguageServerPrompt {
173    request: Option<project::LanguageServerPromptRequest>,
174    scroll_handle: ScrollHandle,
175}
176
177impl LanguageServerPrompt {
178    pub fn new(request: project::LanguageServerPromptRequest) -> Self {
179        Self {
180            request: Some(request),
181            scroll_handle: ScrollHandle::new(),
182        }
183    }
184
185    async fn select_option(this: Entity<Self>, ix: usize, mut cx: AsyncWindowContext) {
186        util::maybe!(async move {
187            let potential_future = this.update(&mut cx, |this, _| {
188                this.request.take().map(|request| request.respond(ix))
189            });
190
191            potential_future? // App Closed
192                .ok_or_else(|| anyhow::anyhow!("Response already sent"))?
193                .await
194                .ok_or_else(|| anyhow::anyhow!("Stream already closed"))?;
195
196            this.update(&mut cx, |_, cx| cx.emit(DismissEvent))?;
197
198            anyhow::Ok(())
199        })
200        .await
201        .log_err();
202    }
203}
204
205impl Render for LanguageServerPrompt {
206    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
207        let Some(request) = &self.request else {
208            return div().id("language_server_prompt_notification");
209        };
210
211        let (icon, color) = match request.level {
212            PromptLevel::Info => (IconName::Info, Color::Accent),
213            PromptLevel::Warning => (IconName::Warning, Color::Warning),
214            PromptLevel::Critical => (IconName::XCircle, Color::Error),
215        };
216
217        div()
218            .id("language_server_prompt_notification")
219            .group("language_server_prompt_notification")
220            .occlude()
221            .w_full()
222            .max_h(vh(0.8, window))
223            .elevation_3(cx)
224            .overflow_y_scroll()
225            .track_scroll(&self.scroll_handle)
226            .child(
227                v_flex()
228                    .p_3()
229                    .overflow_hidden()
230                    .child(
231                        h_flex()
232                            .justify_between()
233                            .items_start()
234                            .child(
235                                h_flex()
236                                    .gap_2()
237                                    .child(Icon::new(icon).color(color))
238                                    .child(Label::new(request.lsp_name.clone())),
239                            )
240                            .child(
241                                h_flex()
242                                    .child(
243                                        IconButton::new("copy", IconName::Copy)
244                                            .on_click({
245                                                let message = request.message.clone();
246                                                move |_, _, cx| {
247                                                    cx.write_to_clipboard(
248                                                        ClipboardItem::new_string(message.clone()),
249                                                    )
250                                                }
251                                            })
252                                            .tooltip(Tooltip::text("Copy Description")),
253                                    )
254                                    .child(IconButton::new("close", IconName::Close).on_click(
255                                        cx.listener(|_, _, _, cx| cx.emit(gpui::DismissEvent)),
256                                    )),
257                            ),
258                    )
259                    .child(Label::new(request.message.to_string()).size(LabelSize::Small))
260                    .children(request.actions.iter().enumerate().map(|(ix, action)| {
261                        let this_handle = cx.entity().clone();
262                        Button::new(ix, action.title.clone())
263                            .size(ButtonSize::Large)
264                            .on_click(move |_, window, cx| {
265                                let this_handle = this_handle.clone();
266                                window
267                                    .spawn(cx, |cx| async move {
268                                        LanguageServerPrompt::select_option(this_handle, ix, cx)
269                                            .await
270                                    })
271                                    .detach()
272                            })
273                    })),
274            )
275    }
276}
277
278impl EventEmitter<DismissEvent> for LanguageServerPrompt {}
279
280fn workspace_error_notification_id() -> NotificationId {
281    struct WorkspaceErrorNotification;
282    NotificationId::unique::<WorkspaceErrorNotification>()
283}
284
285#[derive(Debug, Clone)]
286pub struct ErrorMessagePrompt {
287    message: SharedString,
288    label_and_url_button: Option<(SharedString, SharedString)>,
289}
290
291impl ErrorMessagePrompt {
292    pub fn new<S>(message: S) -> Self
293    where
294        S: Into<SharedString>,
295    {
296        Self {
297            message: message.into(),
298            label_and_url_button: None,
299        }
300    }
301
302    pub fn with_link_button<S>(mut self, label: S, url: S) -> Self
303    where
304        S: Into<SharedString>,
305    {
306        self.label_and_url_button = Some((label.into(), url.into()));
307        self
308    }
309}
310
311impl Render for ErrorMessagePrompt {
312    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
313        h_flex()
314            .id("error_message_prompt_notification")
315            .occlude()
316            .elevation_3(cx)
317            .items_start()
318            .justify_between()
319            .p_2()
320            .gap_2()
321            .w_full()
322            .child(
323                v_flex()
324                    .w_full()
325                    .child(
326                        h_flex()
327                            .w_full()
328                            .justify_between()
329                            .child(
330                                svg()
331                                    .size(window.text_style().font_size)
332                                    .flex_none()
333                                    .mr_2()
334                                    .mt(px(-2.0))
335                                    .map(|icon| {
336                                        icon.path(IconName::Warning.path())
337                                            .text_color(Color::Error.color(cx))
338                                    }),
339                            )
340                            .child(
341                                ui::IconButton::new("close", ui::IconName::Close).on_click(
342                                    cx.listener(|_, _, _, cx| cx.emit(gpui::DismissEvent)),
343                                ),
344                            ),
345                    )
346                    .child(
347                        div()
348                            .id("error_message")
349                            .max_w_96()
350                            .max_h_40()
351                            .overflow_y_scroll()
352                            .child(Label::new(self.message.clone()).size(LabelSize::Small)),
353                    )
354                    .when_some(self.label_and_url_button.clone(), |elm, (label, url)| {
355                        elm.child(
356                            div().mt_2().child(
357                                ui::Button::new("error_message_prompt_notification_button", label)
358                                    .on_click(move |_, _, cx| cx.open_url(&url)),
359                            ),
360                        )
361                    }),
362            )
363    }
364}
365
366impl EventEmitter<DismissEvent> for ErrorMessagePrompt {}
367
368pub mod simple_message_notification {
369    use std::sync::Arc;
370
371    use gpui::{
372        div, AnyElement, DismissEvent, EventEmitter, ParentElement, Render, SharedString, Styled,
373    };
374    use ui::prelude::*;
375
376    pub struct MessageNotification {
377        build_content: Box<dyn Fn(&mut Window, &mut Context<Self>) -> AnyElement>,
378        primary_message: Option<SharedString>,
379        primary_icon: Option<IconName>,
380        primary_icon_color: Option<Color>,
381        primary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
382        secondary_message: Option<SharedString>,
383        secondary_icon: Option<IconName>,
384        secondary_icon_color: Option<Color>,
385        secondary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
386        more_info_message: Option<SharedString>,
387        more_info_url: Option<Arc<str>>,
388        show_close_button: bool,
389        title: Option<SharedString>,
390    }
391
392    impl EventEmitter<DismissEvent> for MessageNotification {}
393
394    impl MessageNotification {
395        pub fn new<S>(message: S) -> MessageNotification
396        where
397            S: Into<SharedString>,
398        {
399            let message = message.into();
400            Self::new_from_builder(move |_, _| Label::new(message.clone()).into_any_element())
401        }
402
403        pub fn new_from_builder<F>(content: F) -> MessageNotification
404        where
405            F: 'static + Fn(&mut Window, &mut Context<Self>) -> AnyElement,
406        {
407            Self {
408                build_content: Box::new(content),
409                primary_message: None,
410                primary_icon: None,
411                primary_icon_color: None,
412                primary_on_click: None,
413                secondary_message: None,
414                secondary_icon: None,
415                secondary_icon_color: None,
416                secondary_on_click: None,
417                more_info_message: None,
418                more_info_url: None,
419                show_close_button: true,
420                title: None,
421            }
422        }
423
424        pub fn primary_message<S>(mut self, message: S) -> Self
425        where
426            S: Into<SharedString>,
427        {
428            self.primary_message = Some(message.into());
429            self
430        }
431
432        pub fn primary_icon(mut self, icon: IconName) -> Self {
433            self.primary_icon = Some(icon);
434            self
435        }
436
437        pub fn primary_icon_color(mut self, color: Color) -> Self {
438            self.primary_icon_color = Some(color);
439            self
440        }
441
442        pub fn primary_on_click<F>(mut self, on_click: F) -> Self
443        where
444            F: 'static + Fn(&mut Window, &mut Context<Self>),
445        {
446            self.primary_on_click = Some(Arc::new(on_click));
447            self
448        }
449
450        pub fn secondary_message<S>(mut self, message: S) -> Self
451        where
452            S: Into<SharedString>,
453        {
454            self.secondary_message = Some(message.into());
455            self
456        }
457
458        pub fn secondary_icon(mut self, icon: IconName) -> Self {
459            self.secondary_icon = Some(icon);
460            self
461        }
462
463        pub fn secondary_icon_color(mut self, color: Color) -> Self {
464            self.secondary_icon_color = Some(color);
465            self
466        }
467
468        pub fn secondary_on_click<F>(mut self, on_click: F) -> Self
469        where
470            F: 'static + Fn(&mut Window, &mut Context<Self>),
471        {
472            self.secondary_on_click = Some(Arc::new(on_click));
473            self
474        }
475
476        pub fn more_info_message<S>(mut self, message: S) -> Self
477        where
478            S: Into<SharedString>,
479        {
480            self.more_info_message = Some(message.into());
481            self
482        }
483
484        pub fn more_info_url<S>(mut self, url: S) -> Self
485        where
486            S: Into<Arc<str>>,
487        {
488            self.more_info_url = Some(url.into());
489            self
490        }
491
492        pub fn dismiss(&mut self, cx: &mut Context<Self>) {
493            cx.emit(DismissEvent);
494        }
495
496        pub fn show_close_button(mut self, show: bool) -> Self {
497            self.show_close_button = show;
498            self
499        }
500
501        pub fn with_title<S>(mut self, title: S) -> Self
502        where
503            S: Into<SharedString>,
504        {
505            self.title = Some(title.into());
506            self
507        }
508    }
509
510    impl Render for MessageNotification {
511        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
512            v_flex()
513                .occlude()
514                .p_3()
515                .gap_3()
516                .elevation_3(cx)
517                .child(
518                    h_flex()
519                        .gap_4()
520                        .justify_between()
521                        .items_start()
522                        .child(
523                            v_flex()
524                                .gap_0p5()
525                                .when_some(self.title.clone(), |element, title| {
526                                    element.child(Label::new(title))
527                                })
528                                .child(div().max_w_96().child((self.build_content)(window, cx))),
529                        )
530                        .when(self.show_close_button, |this| {
531                            this.child(
532                                IconButton::new("close", IconName::Close)
533                                    .on_click(cx.listener(|this, _, _, cx| this.dismiss(cx))),
534                            )
535                        }),
536                )
537                .child(
538                    h_flex()
539                        .gap_1()
540                        .children(self.primary_message.iter().map(|message| {
541                            let mut button = Button::new(message.clone(), message.clone())
542                                .label_size(LabelSize::Small)
543                                .on_click(cx.listener(|this, _, window, cx| {
544                                    if let Some(on_click) = this.primary_on_click.as_ref() {
545                                        (on_click)(window, cx)
546                                    };
547                                    this.dismiss(cx)
548                                }));
549
550                            if let Some(icon) = self.primary_icon {
551                                button = button
552                                    .icon(icon)
553                                    .icon_color(self.primary_icon_color.unwrap_or(Color::Muted))
554                                    .icon_position(IconPosition::Start)
555                                    .icon_size(IconSize::Small);
556                            }
557
558                            button
559                        }))
560                        .children(self.secondary_message.iter().map(|message| {
561                            let mut button = Button::new(message.clone(), message.clone())
562                                .label_size(LabelSize::Small)
563                                .on_click(cx.listener(|this, _, window, cx| {
564                                    if let Some(on_click) = this.secondary_on_click.as_ref() {
565                                        (on_click)(window, cx)
566                                    };
567                                    this.dismiss(cx)
568                                }));
569
570                            if let Some(icon) = self.secondary_icon {
571                                button = button
572                                    .icon(icon)
573                                    .icon_position(IconPosition::Start)
574                                    .icon_size(IconSize::Small)
575                                    .icon_color(self.secondary_icon_color.unwrap_or(Color::Muted));
576                            }
577
578                            button
579                        }))
580                        .child(
581                            h_flex().w_full().justify_end().children(
582                                self.more_info_message
583                                    .iter()
584                                    .zip(self.more_info_url.iter())
585                                    .map(|(message, url)| {
586                                        let url = url.clone();
587                                        Button::new(message.clone(), message.clone())
588                                            .label_size(LabelSize::Small)
589                                            .icon(IconName::ArrowUpRight)
590                                            .icon_size(IconSize::Indicator)
591                                            .icon_color(Color::Muted)
592                                            .on_click(cx.listener(move |_, _, _, cx| {
593                                                cx.open_url(&url);
594                                            }))
595                                    }),
596                            ),
597                        ),
598                )
599        }
600    }
601}
602
603static GLOBAL_APP_NOTIFICATIONS: LazyLock<Mutex<AppNotifications>> = LazyLock::new(|| {
604    Mutex::new(AppNotifications {
605        app_notifications: Vec::new(),
606    })
607});
608
609/// Stores app notifications so that they can be shown in new workspaces.
610struct AppNotifications {
611    app_notifications: Vec<(
612        NotificationId,
613        Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
614    )>,
615}
616
617impl Global for AppNotifications {}
618
619impl AppNotifications {
620    pub fn insert(
621        &mut self,
622        id: NotificationId,
623        build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
624    ) {
625        self.remove(&id);
626        self.app_notifications.push((id, build_notification))
627    }
628
629    pub fn remove(&mut self, id: &NotificationId) {
630        self.app_notifications
631            .retain(|(existing_id, _)| existing_id != id);
632    }
633}
634
635/// Shows a notification in all workspaces. New workspaces will also receive the notification - this
636/// is particularly to handle notifications that occur on initialization before any workspaces
637/// exist. If the notification is dismissed within any workspace, it will be removed from all.
638pub fn show_app_notification<V: Notification + 'static>(
639    id: NotificationId,
640    cx: &mut App,
641    build_notification: impl Fn(&mut Context<Workspace>) -> Entity<V> + 'static + Send + Sync,
642) {
643    // Defer notification creation so that windows on the stack can be returned to GPUI
644    cx.defer(move |cx| {
645        // Handle dismiss events by removing the notification from all workspaces.
646        let build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync> =
647            Arc::new({
648                let id = id.clone();
649                move |cx| {
650                    let notification = build_notification(cx);
651                    cx.subscribe(&notification, {
652                        let id = id.clone();
653                        move |_, _, _: &DismissEvent, cx| {
654                            dismiss_app_notification(&id, cx);
655                        }
656                    })
657                    .detach();
658                    notification.into()
659                }
660            });
661
662        // Store the notification so that new workspaces also receive it.
663        GLOBAL_APP_NOTIFICATIONS
664            .lock()
665            .insert(id.clone(), build_notification.clone());
666
667        for window in cx.windows() {
668            if let Some(workspace_window) = window.downcast::<Workspace>() {
669                workspace_window
670                    .update(cx, |workspace, _window, cx| {
671                        workspace.show_notification_without_handling_dismiss_events(
672                            &id,
673                            cx,
674                            |cx| build_notification(cx),
675                        );
676                    })
677                    .ok(); // Doesn't matter if the windows are dropped
678            }
679        }
680    });
681}
682
683pub fn dismiss_app_notification(id: &NotificationId, cx: &mut App) {
684    let id = id.clone();
685    // Defer notification dismissal so that windows on the stack can be returned to GPUI
686    cx.defer(move |cx| {
687        GLOBAL_APP_NOTIFICATIONS.lock().remove(&id);
688        for window in cx.windows() {
689            if let Some(workspace_window) = window.downcast::<Workspace>() {
690                let id = id.clone();
691                workspace_window
692                    .update(cx, |workspace, _window, cx| {
693                        workspace.dismiss_notification(&id, cx)
694                    })
695                    .ok();
696            }
697        }
698    });
699}
700
701pub trait NotifyResultExt {
702    type Ok;
703
704    fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>)
705        -> Option<Self::Ok>;
706
707    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
708
709    /// Notifies the active workspace if there is one, otherwise notifies all workspaces.
710    fn notify_app_err(self, cx: &mut App) -> Option<Self::Ok>;
711}
712
713impl<T, E> NotifyResultExt for std::result::Result<T, E>
714where
715    E: std::fmt::Debug + std::fmt::Display,
716{
717    type Ok = T;
718
719    fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>) -> Option<T> {
720        match self {
721            Ok(value) => Some(value),
722            Err(err) => {
723                log::error!("Showing error notification in workspace: {err:?}");
724                workspace.show_error(&err, cx);
725                None
726            }
727        }
728    }
729
730    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
731        match self {
732            Ok(value) => Some(value),
733            Err(err) => {
734                log::error!("{err:?}");
735                cx.update_root(|view, _, cx| {
736                    if let Ok(workspace) = view.downcast::<Workspace>() {
737                        workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
738                    }
739                })
740                .ok();
741                None
742            }
743        }
744    }
745
746    fn notify_app_err(self, cx: &mut App) -> Option<T> {
747        match self {
748            Ok(value) => Some(value),
749            Err(err) => {
750                let message: SharedString = format!("Error: {err}").into();
751                log::error!("Showing error notification in app: {message}");
752                show_app_notification(workspace_error_notification_id(), cx, {
753                    let message = message.clone();
754                    move |cx| {
755                        cx.new({
756                            let message = message.clone();
757                            move |_cx| ErrorMessagePrompt::new(message)
758                        })
759                    }
760                });
761
762                None
763            }
764        }
765    }
766}
767
768pub trait NotifyTaskExt {
769    fn detach_and_notify_err(self, window: &mut Window, cx: &mut App);
770}
771
772impl<R, E> NotifyTaskExt for Task<std::result::Result<R, E>>
773where
774    E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
775    R: 'static,
776{
777    fn detach_and_notify_err(self, window: &mut Window, cx: &mut App) {
778        window
779            .spawn(
780                cx,
781                |mut cx| async move { self.await.notify_async_err(&mut cx) },
782            )
783            .detach();
784    }
785}
786
787pub trait DetachAndPromptErr<R> {
788    fn prompt_err(
789        self,
790        msg: &str,
791        window: &Window,
792        cx: &App,
793        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
794    ) -> Task<Option<R>>;
795
796    fn detach_and_prompt_err(
797        self,
798        msg: &str,
799        window: &Window,
800        cx: &App,
801        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
802    );
803}
804
805impl<R> DetachAndPromptErr<R> for Task<anyhow::Result<R>>
806where
807    R: 'static,
808{
809    fn prompt_err(
810        self,
811        msg: &str,
812        window: &Window,
813        cx: &App,
814        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
815    ) -> Task<Option<R>> {
816        let msg = msg.to_owned();
817        window.spawn(cx, |mut cx| async move {
818            let result = self.await;
819            if let Err(err) = result.as_ref() {
820                log::error!("{err:?}");
821                if let Ok(prompt) = cx.update(|window, cx| {
822                    let detail =
823                        f(err, window, cx).unwrap_or_else(|| format!("{err}. Please try again."));
824                    window.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"], cx)
825                }) {
826                    prompt.await.ok();
827                }
828                return None;
829            }
830            Some(result.unwrap())
831        })
832    }
833
834    fn detach_and_prompt_err(
835        self,
836        msg: &str,
837        window: &Window,
838        cx: &App,
839        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
840    ) {
841        self.prompt_err(msg, window, cx, f).detach();
842    }
843}