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, time::Duration};
 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.clone(), 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        if toast.autohide {
198            cx.spawn(|workspace, mut cx| async move {
199                cx.background_executor()
200                    .timer(Duration::from_millis(5000))
201                    .await;
202                workspace
203                    .update(&mut cx, |workspace, cx| {
204                        workspace.dismiss_toast(&toast.id, cx)
205                    })
206                    .ok();
207            })
208            .detach();
209        }
210    }
211
212    pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
213        self.dismiss_notification(id, cx);
214    }
215
216    pub fn clear_all_notifications(&mut self, cx: &mut ViewContext<Self>) {
217        self.notifications.clear();
218        cx.notify();
219    }
220
221    fn dismiss_notification_internal(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
222        self.notifications.retain(|(existing_id, _)| {
223            if existing_id == id {
224                cx.notify();
225                false
226            } else {
227                true
228            }
229        });
230    }
231}
232
233pub struct LanguageServerPrompt {
234    request: Option<project::LanguageServerPromptRequest>,
235    scroll_handle: ScrollHandle,
236}
237
238impl LanguageServerPrompt {
239    pub fn new(request: project::LanguageServerPromptRequest) -> Self {
240        Self {
241            request: Some(request),
242            scroll_handle: ScrollHandle::new(),
243        }
244    }
245
246    async fn select_option(this: View<Self>, ix: usize, mut cx: AsyncWindowContext) {
247        util::maybe!(async move {
248            let potential_future = this.update(&mut cx, |this, _| {
249                this.request.take().map(|request| request.respond(ix))
250            });
251
252            potential_future? // App Closed
253                .ok_or_else(|| anyhow::anyhow!("Response already sent"))?
254                .await
255                .ok_or_else(|| anyhow::anyhow!("Stream already closed"))?;
256
257            this.update(&mut cx, |_, cx| cx.emit(DismissEvent))?;
258
259            anyhow::Ok(())
260        })
261        .await
262        .log_err();
263    }
264}
265
266impl Render for LanguageServerPrompt {
267    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
268        let Some(request) = &self.request else {
269            return div().id("language_server_prompt_notification");
270        };
271
272        h_flex()
273            .id("language_server_prompt_notification")
274            .occlude()
275            .elevation_3(cx)
276            .items_start()
277            .justify_between()
278            .p_2()
279            .gap_2()
280            .w_full()
281            .max_h(vh(0.8, cx))
282            .overflow_y_scroll()
283            .track_scroll(&self.scroll_handle)
284            .group("")
285            .child(
286                v_flex()
287                    .w_full()
288                    .overflow_hidden()
289                    .child(
290                        h_flex()
291                            .w_full()
292                            .justify_between()
293                            .child(
294                                h_flex()
295                                    .flex_grow()
296                                    .children(
297                                        match request.level {
298                                            PromptLevel::Info => None,
299                                            PromptLevel::Warning => {
300                                                Some(DiagnosticSeverity::WARNING)
301                                            }
302                                            PromptLevel::Critical => {
303                                                Some(DiagnosticSeverity::ERROR)
304                                            }
305                                        }
306                                        .map(|severity| {
307                                            svg()
308                                                .size(cx.text_style().font_size)
309                                                .flex_none()
310                                                .mr_1()
311                                                .mt(px(-2.0))
312                                                .map(|icon| {
313                                                    if severity == DiagnosticSeverity::ERROR {
314                                                        icon.path(IconName::Warning.path())
315                                                            .text_color(Color::Error.color(cx))
316                                                    } else {
317                                                        icon.path(IconName::Warning.path())
318                                                            .text_color(Color::Warning.color(cx))
319                                                    }
320                                                })
321                                        }),
322                                    )
323                                    .child(
324                                        Label::new(request.lsp_name.clone())
325                                            .size(LabelSize::Default),
326                                    ),
327                            )
328                            .child(
329                                ui::IconButton::new("close", ui::IconName::Close)
330                                    .on_click(cx.listener(|_, _, cx| cx.emit(gpui::DismissEvent))),
331                            ),
332                    )
333                    .child(
334                        v_flex()
335                            .child(
336                                h_flex().absolute().right_0().rounded_md().child(
337                                    ui::IconButton::new("copy", ui::IconName::Copy)
338                                        .on_click({
339                                            let message = request.message.clone();
340                                            move |_, cx| {
341                                                cx.write_to_clipboard(ClipboardItem::new_string(
342                                                    message.clone(),
343                                                ))
344                                            }
345                                        })
346                                        .tooltip(|cx| Tooltip::text("Copy", cx))
347                                        .visible_on_hover(""),
348                                ),
349                            )
350                            .child(Label::new(request.message.to_string()).size(LabelSize::Small)),
351                    )
352                    .children(request.actions.iter().enumerate().map(|(ix, action)| {
353                        let this_handle = cx.view().clone();
354                        ui::Button::new(ix, action.title.clone())
355                            .size(ButtonSize::Large)
356                            .on_click(move |_, cx| {
357                                let this_handle = this_handle.clone();
358                                cx.spawn(|cx| async move {
359                                    LanguageServerPrompt::select_option(this_handle, ix, cx).await
360                                })
361                                .detach()
362                            })
363                    })),
364            )
365    }
366}
367
368impl EventEmitter<DismissEvent> for LanguageServerPrompt {}
369
370pub struct ErrorMessagePrompt {
371    message: SharedString,
372    label_and_url_button: Option<(SharedString, SharedString)>,
373}
374
375impl ErrorMessagePrompt {
376    pub fn new<S>(message: S) -> Self
377    where
378        S: Into<SharedString>,
379    {
380        Self {
381            message: message.into(),
382            label_and_url_button: None,
383        }
384    }
385
386    pub fn with_link_button<S>(mut self, label: S, url: S) -> Self
387    where
388        S: Into<SharedString>,
389    {
390        self.label_and_url_button = Some((label.into(), url.into()));
391        self
392    }
393}
394
395impl Render for ErrorMessagePrompt {
396    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
397        h_flex()
398            .id("error_message_prompt_notification")
399            .occlude()
400            .elevation_3(cx)
401            .items_start()
402            .justify_between()
403            .p_2()
404            .gap_2()
405            .w_full()
406            .child(
407                v_flex()
408                    .w_full()
409                    .child(
410                        h_flex()
411                            .w_full()
412                            .justify_between()
413                            .child(
414                                svg()
415                                    .size(cx.text_style().font_size)
416                                    .flex_none()
417                                    .mr_2()
418                                    .mt(px(-2.0))
419                                    .map(|icon| {
420                                        icon.path(IconName::Warning.path())
421                                            .text_color(Color::Error.color(cx))
422                                    }),
423                            )
424                            .child(
425                                ui::IconButton::new("close", ui::IconName::Close)
426                                    .on_click(cx.listener(|_, _, cx| cx.emit(gpui::DismissEvent))),
427                            ),
428                    )
429                    .child(
430                        div()
431                            .max_w_80()
432                            .child(Label::new(self.message.clone()).size(LabelSize::Small)),
433                    )
434                    .when_some(self.label_and_url_button.clone(), |elm, (label, url)| {
435                        elm.child(
436                            div().mt_2().child(
437                                ui::Button::new("error_message_prompt_notification_button", label)
438                                    .on_click(move |_, cx| cx.open_url(&url)),
439                            ),
440                        )
441                    }),
442            )
443    }
444}
445
446impl EventEmitter<DismissEvent> for ErrorMessagePrompt {}
447
448pub mod simple_message_notification {
449    use gpui::{
450        div, DismissEvent, EventEmitter, InteractiveElement, ParentElement, Render, SharedString,
451        StatefulInteractiveElement, Styled, ViewContext,
452    };
453    use std::sync::Arc;
454    use ui::prelude::*;
455    use ui::{h_flex, v_flex, Button, Icon, IconName, Label, StyledExt};
456
457    pub struct MessageNotification {
458        message: SharedString,
459        on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
460        click_message: Option<SharedString>,
461        secondary_click_message: Option<SharedString>,
462        secondary_on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
463    }
464
465    impl EventEmitter<DismissEvent> for MessageNotification {}
466
467    impl MessageNotification {
468        pub fn new<S>(message: S) -> MessageNotification
469        where
470            S: Into<SharedString>,
471        {
472            Self {
473                message: message.into(),
474                on_click: None,
475                click_message: None,
476                secondary_on_click: None,
477                secondary_click_message: None,
478            }
479        }
480
481        pub fn with_click_message<S>(mut self, message: S) -> Self
482        where
483            S: Into<SharedString>,
484        {
485            self.click_message = Some(message.into());
486            self
487        }
488
489        pub fn on_click<F>(mut self, on_click: F) -> Self
490        where
491            F: 'static + Fn(&mut ViewContext<Self>),
492        {
493            self.on_click = Some(Arc::new(on_click));
494            self
495        }
496
497        pub fn with_secondary_click_message<S>(mut self, message: S) -> Self
498        where
499            S: Into<SharedString>,
500        {
501            self.secondary_click_message = Some(message.into());
502            self
503        }
504
505        pub fn on_secondary_click<F>(mut self, on_click: F) -> Self
506        where
507            F: 'static + Fn(&mut ViewContext<Self>),
508        {
509            self.secondary_on_click = Some(Arc::new(on_click));
510            self
511        }
512
513        pub fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
514            cx.emit(DismissEvent);
515        }
516    }
517
518    impl Render for MessageNotification {
519        fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
520            v_flex()
521                .elevation_3(cx)
522                .p_4()
523                .child(
524                    h_flex()
525                        .justify_between()
526                        .child(div().max_w_80().child(Label::new(self.message.clone())))
527                        .child(
528                            div()
529                                .id("cancel")
530                                .child(Icon::new(IconName::Close))
531                                .cursor_pointer()
532                                .on_click(cx.listener(|this, _, cx| this.dismiss(cx))),
533                        ),
534                )
535                .child(
536                    h_flex()
537                        .gap_3()
538                        .children(self.click_message.iter().map(|message| {
539                            Button::new(message.clone(), message.clone()).on_click(cx.listener(
540                                |this, _, cx| {
541                                    if let Some(on_click) = this.on_click.as_ref() {
542                                        (on_click)(cx)
543                                    };
544                                    this.dismiss(cx)
545                                },
546                            ))
547                        }))
548                        .children(self.secondary_click_message.iter().map(|message| {
549                            Button::new(message.clone(), message.clone())
550                                .style(ButtonStyle::Filled)
551                                .on_click(cx.listener(|this, _, cx| {
552                                    if let Some(on_click) = this.secondary_on_click.as_ref() {
553                                        (on_click)(cx)
554                                    };
555                                    this.dismiss(cx)
556                                }))
557                        })),
558                )
559        }
560    }
561}
562
563pub trait NotifyResultExt {
564    type Ok;
565
566    fn notify_err(
567        self,
568        workspace: &mut Workspace,
569        cx: &mut ViewContext<Workspace>,
570    ) -> Option<Self::Ok>;
571
572    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
573}
574
575impl<T, E> NotifyResultExt for Result<T, E>
576where
577    E: std::fmt::Debug + std::fmt::Display,
578{
579    type Ok = T;
580
581    fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
582        match self {
583            Ok(value) => Some(value),
584            Err(err) => {
585                log::error!("TODO {err:?}");
586                workspace.show_error(&err, cx);
587                None
588            }
589        }
590    }
591
592    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
593        match self {
594            Ok(value) => Some(value),
595            Err(err) => {
596                log::error!("{err:?}");
597                cx.update_root(|view, cx| {
598                    if let Ok(workspace) = view.downcast::<Workspace>() {
599                        workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
600                    }
601                })
602                .ok();
603                None
604            }
605        }
606    }
607}
608
609pub trait NotifyTaskExt {
610    fn detach_and_notify_err(self, cx: &mut WindowContext);
611}
612
613impl<R, E> NotifyTaskExt for Task<Result<R, E>>
614where
615    E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
616    R: 'static,
617{
618    fn detach_and_notify_err(self, cx: &mut WindowContext) {
619        cx.spawn(|mut cx| async move { self.await.notify_async_err(&mut cx) })
620            .detach();
621    }
622}
623
624pub trait DetachAndPromptErr<R> {
625    fn prompt_err(
626        self,
627        msg: &str,
628        cx: &mut WindowContext,
629        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
630    ) -> Task<Option<R>>;
631
632    fn detach_and_prompt_err(
633        self,
634        msg: &str,
635        cx: &mut WindowContext,
636        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
637    );
638}
639
640impl<R> DetachAndPromptErr<R> for Task<anyhow::Result<R>>
641where
642    R: 'static,
643{
644    fn prompt_err(
645        self,
646        msg: &str,
647        cx: &mut WindowContext,
648        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
649    ) -> Task<Option<R>> {
650        let msg = msg.to_owned();
651        cx.spawn(|mut cx| async move {
652            let result = self.await;
653            if let Err(err) = result.as_ref() {
654                log::error!("{err:?}");
655                if let Ok(prompt) = cx.update(|cx| {
656                    let detail = f(err, cx).unwrap_or_else(|| format!("{err}. Please try again."));
657                    cx.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"])
658                }) {
659                    prompt.await.ok();
660                }
661                return None;
662            }
663            Some(result.unwrap())
664        })
665    }
666
667    fn detach_and_prompt_err(
668        self,
669        msg: &str,
670        cx: &mut WindowContext,
671        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
672    ) {
673        self.prompt_err(msg, cx, f).detach();
674    }
675}