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