notifications.rs

  1use crate::{Toast, Workspace};
  2use collections::HashMap;
  3use gpui::{
  4    svg, AnyView, AppContext, AsyncWindowContext, ClipboardItem, DismissEvent, Entity, EntityId,
  5    EventEmitter, Global, PromptLevel, Render, ScrollHandle, Task, View, ViewContext,
  6    VisualContext, WindowContext,
  7};
  8use language::DiagnosticSeverity;
  9
 10use std::{any::TypeId, ops::DerefMut};
 11use ui::{prelude::*, Tooltip};
 12use util::ResultExt;
 13
 14pub fn init(cx: &mut AppContext) {
 15    cx.set_global(NotificationTracker::new());
 16}
 17
 18#[derive(Debug, PartialEq, Clone)]
 19pub struct NotificationId {
 20    /// A [`TypeId`] used to uniquely identify this notification.
 21    type_id: TypeId,
 22    /// A supplementary ID used to distinguish between multiple
 23    /// notifications that have the same [`type_id`](Self::type_id);
 24    id: Option<ElementId>,
 25}
 26
 27impl NotificationId {
 28    /// Returns a unique [`NotificationId`] for the given type.
 29    pub fn unique<T: 'static>() -> Self {
 30        Self {
 31            type_id: TypeId::of::<T>(),
 32            id: None,
 33        }
 34    }
 35
 36    /// Returns a [`NotificationId`] for the given type that is also identified
 37    /// by the provided ID.
 38    pub fn identified<T: 'static>(id: impl Into<ElementId>) -> Self {
 39        Self {
 40            type_id: TypeId::of::<T>(),
 41            id: Some(id.into()),
 42        }
 43    }
 44}
 45
 46pub trait Notification: EventEmitter<DismissEvent> + Render {}
 47
 48impl<V: EventEmitter<DismissEvent> + Render> Notification for V {}
 49
 50pub trait NotificationHandle: Send {
 51    fn id(&self) -> EntityId;
 52    fn to_any(&self) -> AnyView;
 53}
 54
 55impl<T: Notification> NotificationHandle for View<T> {
 56    fn id(&self) -> EntityId {
 57        self.entity_id()
 58    }
 59
 60    fn to_any(&self) -> AnyView {
 61        self.clone().into()
 62    }
 63}
 64
 65impl From<&dyn NotificationHandle> for AnyView {
 66    fn from(val: &dyn NotificationHandle) -> Self {
 67        val.to_any()
 68    }
 69}
 70
 71pub(crate) struct NotificationTracker {
 72    notifications_sent: HashMap<TypeId, Vec<NotificationId>>,
 73}
 74
 75impl Global for NotificationTracker {}
 76
 77impl std::ops::Deref for NotificationTracker {
 78    type Target = HashMap<TypeId, Vec<NotificationId>>;
 79
 80    fn deref(&self) -> &Self::Target {
 81        &self.notifications_sent
 82    }
 83}
 84
 85impl DerefMut for NotificationTracker {
 86    fn deref_mut(&mut self) -> &mut Self::Target {
 87        &mut self.notifications_sent
 88    }
 89}
 90
 91impl NotificationTracker {
 92    fn new() -> Self {
 93        Self {
 94            notifications_sent: Default::default(),
 95        }
 96    }
 97}
 98
 99impl Workspace {
100    pub fn has_shown_notification_once<V: Notification>(
101        &self,
102        id: &NotificationId,
103        cx: &ViewContext<Self>,
104    ) -> bool {
105        cx.global::<NotificationTracker>()
106            .get(&TypeId::of::<V>())
107            .map(|ids| ids.contains(id))
108            .unwrap_or(false)
109    }
110
111    pub fn show_notification_once<V: Notification>(
112        &mut self,
113        id: NotificationId,
114        cx: &mut ViewContext<Self>,
115        build_notification: impl FnOnce(&mut ViewContext<Self>) -> View<V>,
116    ) {
117        if !self.has_shown_notification_once::<V>(&id, cx) {
118            let tracker = cx.global_mut::<NotificationTracker>();
119            let entry = tracker.entry(TypeId::of::<V>()).or_default();
120            entry.push(id.clone());
121            self.show_notification::<V>(id, cx, build_notification)
122        }
123    }
124
125    #[cfg(any(test, feature = "test-support"))]
126    pub fn notification_ids(&self) -> Vec<NotificationId> {
127        self.notifications
128            .iter()
129            .map(|(id, _)| id)
130            .cloned()
131            .collect()
132    }
133
134    pub fn show_notification<V: Notification>(
135        &mut self,
136        id: NotificationId,
137        cx: &mut ViewContext<Self>,
138        build_notification: impl FnOnce(&mut ViewContext<Self>) -> View<V>,
139    ) {
140        self.dismiss_notification_internal(&id, cx);
141
142        let notification = build_notification(cx);
143        cx.subscribe(&notification, {
144            let id = id.clone();
145            move |this, _, _: &DismissEvent, cx| {
146                this.dismiss_notification_internal(&id, cx);
147            }
148        })
149        .detach();
150        self.notifications.push((id, Box::new(notification)));
151        cx.notify();
152    }
153
154    pub fn show_error<E>(&mut self, err: &E, cx: &mut ViewContext<Self>)
155    where
156        E: std::fmt::Debug + std::fmt::Display,
157    {
158        struct WorkspaceErrorNotification;
159
160        self.show_notification(
161            NotificationId::unique::<WorkspaceErrorNotification>(),
162            cx,
163            |cx| cx.new_view(|_cx| ErrorMessagePrompt::new(format!("Error: {err:#}"))),
164        );
165    }
166
167    pub fn show_portal_error(&mut self, err: String, cx: &mut ViewContext<Self>) {
168        struct PortalError;
169
170        self.show_notification(NotificationId::unique::<PortalError>(), cx, |cx| {
171            cx.new_view(|_cx| {
172                ErrorMessagePrompt::new(err.to_string()).with_link_button(
173                    "See docs",
174                    "https://zed.dev/docs/linux#i-cant-open-any-files",
175                )
176            })
177        });
178    }
179
180    pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
181        self.dismiss_notification_internal(id, cx)
182    }
183
184    pub fn show_toast(&mut self, toast: Toast, cx: &mut ViewContext<Self>) {
185        self.dismiss_notification(&toast.id, cx);
186        self.show_notification(toast.id, cx, |cx| {
187            cx.new_view(|_cx| match toast.on_click.as_ref() {
188                Some((click_msg, on_click)) => {
189                    let on_click = on_click.clone();
190                    simple_message_notification::MessageNotification::new(toast.msg.clone())
191                        .with_click_message(click_msg.clone())
192                        .on_click(move |cx| on_click(cx))
193                }
194                None => simple_message_notification::MessageNotification::new(toast.msg.clone()),
195            })
196        })
197    }
198
199    pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
200        self.dismiss_notification(id, cx);
201    }
202
203    pub fn clear_all_notifications(&mut self, cx: &mut ViewContext<Self>) {
204        self.notifications.clear();
205        cx.notify();
206    }
207
208    fn dismiss_notification_internal(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
209        self.notifications.retain(|(existing_id, _)| {
210            if existing_id == id {
211                cx.notify();
212                false
213            } else {
214                true
215            }
216        });
217    }
218}
219
220pub struct LanguageServerPrompt {
221    request: Option<project::LanguageServerPromptRequest>,
222    scroll_handle: ScrollHandle,
223}
224
225impl LanguageServerPrompt {
226    pub fn new(request: project::LanguageServerPromptRequest) -> Self {
227        Self {
228            request: Some(request),
229            scroll_handle: ScrollHandle::new(),
230        }
231    }
232
233    async fn select_option(this: View<Self>, ix: usize, mut cx: AsyncWindowContext) {
234        util::maybe!(async move {
235            let potential_future = this.update(&mut cx, |this, _| {
236                this.request.take().map(|request| request.respond(ix))
237            });
238
239            potential_future? // App Closed
240                .ok_or_else(|| anyhow::anyhow!("Response already sent"))?
241                .await
242                .ok_or_else(|| anyhow::anyhow!("Stream already closed"))?;
243
244            this.update(&mut cx, |_, cx| cx.emit(DismissEvent))?;
245
246            anyhow::Ok(())
247        })
248        .await
249        .log_err();
250    }
251}
252
253impl Render for LanguageServerPrompt {
254    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
255        let Some(request) = &self.request else {
256            return div().id("language_server_prompt_notification");
257        };
258
259        h_flex()
260            .id("language_server_prompt_notification")
261            .occlude()
262            .elevation_3(cx)
263            .items_start()
264            .justify_between()
265            .p_2()
266            .gap_2()
267            .w_full()
268            .max_h(vh(0.8, cx))
269            .overflow_y_scroll()
270            .track_scroll(&self.scroll_handle)
271            .group("")
272            .child(
273                v_flex()
274                    .w_full()
275                    .overflow_hidden()
276                    .child(
277                        h_flex()
278                            .w_full()
279                            .justify_between()
280                            .child(
281                                h_flex()
282                                    .flex_grow()
283                                    .children(
284                                        match request.level {
285                                            PromptLevel::Info => None,
286                                            PromptLevel::Warning => {
287                                                Some(DiagnosticSeverity::WARNING)
288                                            }
289                                            PromptLevel::Critical => {
290                                                Some(DiagnosticSeverity::ERROR)
291                                            }
292                                        }
293                                        .map(|severity| {
294                                            svg()
295                                                .size(cx.text_style().font_size)
296                                                .flex_none()
297                                                .mr_1()
298                                                .mt(px(-2.0))
299                                                .map(|icon| {
300                                                    if severity == DiagnosticSeverity::ERROR {
301                                                        icon.path(
302                                                            IconName::ExclamationTriangle.path(),
303                                                        )
304                                                        .text_color(Color::Error.color(cx))
305                                                    } else {
306                                                        icon.path(
307                                                            IconName::ExclamationTriangle.path(),
308                                                        )
309                                                        .text_color(Color::Warning.color(cx))
310                                                    }
311                                                })
312                                        }),
313                                    )
314                                    .child(
315                                        Label::new(request.lsp_name.clone())
316                                            .size(LabelSize::Default),
317                                    ),
318                            )
319                            .child(
320                                ui::IconButton::new("close", ui::IconName::Close)
321                                    .on_click(cx.listener(|_, _, cx| cx.emit(gpui::DismissEvent))),
322                            ),
323                    )
324                    .child(
325                        v_flex()
326                            .child(
327                                h_flex().absolute().right_0().rounded_md().child(
328                                    ui::IconButton::new("copy", ui::IconName::Copy)
329                                        .on_click({
330                                            let message = request.message.clone();
331                                            move |_, cx| {
332                                                cx.write_to_clipboard(ClipboardItem::new(
333                                                    message.clone(),
334                                                ))
335                                            }
336                                        })
337                                        .tooltip(|cx| Tooltip::text("Copy", cx))
338                                        .visible_on_hover(""),
339                                ),
340                            )
341                            .child(Label::new(request.message.to_string()).size(LabelSize::Small)),
342                    )
343                    .children(request.actions.iter().enumerate().map(|(ix, action)| {
344                        let this_handle = cx.view().clone();
345                        ui::Button::new(ix, action.title.clone())
346                            .size(ButtonSize::Large)
347                            .on_click(move |_, cx| {
348                                let this_handle = this_handle.clone();
349                                cx.spawn(|cx| async move {
350                                    LanguageServerPrompt::select_option(this_handle, ix, cx).await
351                                })
352                                .detach()
353                            })
354                    })),
355            )
356    }
357}
358
359impl EventEmitter<DismissEvent> for LanguageServerPrompt {}
360
361pub struct ErrorMessagePrompt {
362    message: SharedString,
363    label_and_url_button: Option<(SharedString, SharedString)>,
364}
365
366impl ErrorMessagePrompt {
367    pub fn new<S>(message: S) -> Self
368    where
369        S: Into<SharedString>,
370    {
371        Self {
372            message: message.into(),
373            label_and_url_button: None,
374        }
375    }
376
377    pub fn with_link_button<S>(mut self, label: S, url: S) -> Self
378    where
379        S: Into<SharedString>,
380    {
381        self.label_and_url_button = Some((label.into(), url.into()));
382        self
383    }
384}
385
386impl Render for ErrorMessagePrompt {
387    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
388        h_flex()
389            .id("error_message_prompt_notification")
390            .occlude()
391            .elevation_3(cx)
392            .items_start()
393            .justify_between()
394            .p_2()
395            .gap_2()
396            .w_full()
397            .child(
398                v_flex()
399                    .w_full()
400                    .child(
401                        h_flex()
402                            .w_full()
403                            .justify_between()
404                            .child(
405                                svg()
406                                    .size(cx.text_style().font_size)
407                                    .flex_none()
408                                    .mr_2()
409                                    .mt(px(-2.0))
410                                    .map(|icon| {
411                                        icon.path(IconName::ExclamationTriangle.path())
412                                            .text_color(Color::Error.color(cx))
413                                    }),
414                            )
415                            .child(
416                                ui::IconButton::new("close", ui::IconName::Close)
417                                    .on_click(cx.listener(|_, _, cx| cx.emit(gpui::DismissEvent))),
418                            ),
419                    )
420                    .child(
421                        div()
422                            .max_w_80()
423                            .child(Label::new(self.message.clone()).size(LabelSize::Small)),
424                    )
425                    .when_some(self.label_and_url_button.clone(), |elm, (label, url)| {
426                        elm.child(
427                            div().mt_2().child(
428                                ui::Button::new("error_message_prompt_notification_button", label)
429                                    .on_click(move |_, cx| cx.open_url(&url)),
430                            ),
431                        )
432                    }),
433            )
434    }
435}
436
437impl EventEmitter<DismissEvent> for ErrorMessagePrompt {}
438
439pub mod simple_message_notification {
440    use gpui::{
441        div, DismissEvent, EventEmitter, InteractiveElement, ParentElement, Render, SharedString,
442        StatefulInteractiveElement, Styled, ViewContext,
443    };
444    use std::sync::Arc;
445    use ui::prelude::*;
446    use ui::{h_flex, v_flex, Button, Icon, IconName, Label, StyledExt};
447
448    pub struct MessageNotification {
449        message: SharedString,
450        on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
451        click_message: Option<SharedString>,
452        secondary_click_message: Option<SharedString>,
453        secondary_on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
454    }
455
456    impl EventEmitter<DismissEvent> for MessageNotification {}
457
458    impl MessageNotification {
459        pub fn new<S>(message: S) -> MessageNotification
460        where
461            S: Into<SharedString>,
462        {
463            Self {
464                message: message.into(),
465                on_click: None,
466                click_message: None,
467                secondary_on_click: None,
468                secondary_click_message: None,
469            }
470        }
471
472        pub fn with_click_message<S>(mut self, message: S) -> Self
473        where
474            S: Into<SharedString>,
475        {
476            self.click_message = Some(message.into());
477            self
478        }
479
480        pub fn on_click<F>(mut self, on_click: F) -> Self
481        where
482            F: 'static + Fn(&mut ViewContext<Self>),
483        {
484            self.on_click = Some(Arc::new(on_click));
485            self
486        }
487
488        pub fn with_secondary_click_message<S>(mut self, message: S) -> Self
489        where
490            S: Into<SharedString>,
491        {
492            self.secondary_click_message = Some(message.into());
493            self
494        }
495
496        pub fn on_secondary_click<F>(mut self, on_click: F) -> Self
497        where
498            F: 'static + Fn(&mut ViewContext<Self>),
499        {
500            self.secondary_on_click = Some(Arc::new(on_click));
501            self
502        }
503
504        pub fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
505            cx.emit(DismissEvent);
506        }
507    }
508
509    impl Render for MessageNotification {
510        fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
511            v_flex()
512                .elevation_3(cx)
513                .p_4()
514                .child(
515                    h_flex()
516                        .justify_between()
517                        .child(div().max_w_80().child(Label::new(self.message.clone())))
518                        .child(
519                            div()
520                                .id("cancel")
521                                .child(Icon::new(IconName::Close))
522                                .cursor_pointer()
523                                .on_click(cx.listener(|this, _, cx| this.dismiss(cx))),
524                        ),
525                )
526                .child(
527                    h_flex()
528                        .gap_3()
529                        .children(self.click_message.iter().map(|message| {
530                            Button::new(message.clone(), message.clone()).on_click(cx.listener(
531                                |this, _, cx| {
532                                    if let Some(on_click) = this.on_click.as_ref() {
533                                        (on_click)(cx)
534                                    };
535                                    this.dismiss(cx)
536                                },
537                            ))
538                        }))
539                        .children(self.secondary_click_message.iter().map(|message| {
540                            Button::new(message.clone(), message.clone())
541                                .style(ButtonStyle::Filled)
542                                .on_click(cx.listener(|this, _, cx| {
543                                    if let Some(on_click) = this.secondary_on_click.as_ref() {
544                                        (on_click)(cx)
545                                    };
546                                    this.dismiss(cx)
547                                }))
548                        })),
549                )
550        }
551    }
552}
553
554pub trait NotifyResultExt {
555    type Ok;
556
557    fn notify_err(
558        self,
559        workspace: &mut Workspace,
560        cx: &mut ViewContext<Workspace>,
561    ) -> Option<Self::Ok>;
562
563    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
564}
565
566impl<T, E> NotifyResultExt for Result<T, E>
567where
568    E: std::fmt::Debug + std::fmt::Display,
569{
570    type Ok = T;
571
572    fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
573        match self {
574            Ok(value) => Some(value),
575            Err(err) => {
576                log::error!("TODO {err:?}");
577                workspace.show_error(&err, cx);
578                None
579            }
580        }
581    }
582
583    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
584        match self {
585            Ok(value) => Some(value),
586            Err(err) => {
587                log::error!("{err:?}");
588                cx.update_root(|view, cx| {
589                    if let Ok(workspace) = view.downcast::<Workspace>() {
590                        workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
591                    }
592                })
593                .ok();
594                None
595            }
596        }
597    }
598}
599
600pub trait NotifyTaskExt {
601    fn detach_and_notify_err(self, cx: &mut WindowContext);
602}
603
604impl<R, E> NotifyTaskExt for Task<Result<R, E>>
605where
606    E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
607    R: 'static,
608{
609    fn detach_and_notify_err(self, cx: &mut WindowContext) {
610        cx.spawn(|mut cx| async move { self.await.notify_async_err(&mut cx) })
611            .detach();
612    }
613}
614
615pub trait DetachAndPromptErr {
616    fn prompt_err(
617        self,
618        msg: &str,
619        cx: &mut WindowContext,
620        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
621    ) -> Task<()>;
622
623    fn detach_and_prompt_err(
624        self,
625        msg: &str,
626        cx: &mut WindowContext,
627        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
628    );
629}
630
631impl<R> DetachAndPromptErr for Task<anyhow::Result<R>>
632where
633    R: 'static,
634{
635    fn prompt_err(
636        self,
637        msg: &str,
638        cx: &mut WindowContext,
639        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
640    ) -> Task<()> {
641        let msg = msg.to_owned();
642        cx.spawn(|mut cx| async move {
643            if let Err(err) = self.await {
644                log::error!("{err:?}");
645                if let Ok(prompt) = cx.update(|cx| {
646                    let detail = f(&err, cx).unwrap_or_else(|| format!("{err}. Please try again."));
647                    cx.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"])
648                }) {
649                    prompt.await.ok();
650                }
651            }
652        })
653    }
654
655    fn detach_and_prompt_err(
656        self,
657        msg: &str,
658        cx: &mut WindowContext,
659        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
660    ) {
661        self.prompt_err(msg, cx, f).detach();
662    }
663}