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| {
164                cx.new_view(|_cx| {
165                    simple_message_notification::MessageNotification::new(format!("Error: {err:#}"))
166                })
167            },
168        );
169    }
170
171    pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
172        self.dismiss_notification_internal(id, cx)
173    }
174
175    pub fn show_toast(&mut self, toast: Toast, cx: &mut ViewContext<Self>) {
176        self.dismiss_notification(&toast.id, cx);
177        self.show_notification(toast.id, cx, |cx| {
178            cx.new_view(|_cx| match toast.on_click.as_ref() {
179                Some((click_msg, on_click)) => {
180                    let on_click = on_click.clone();
181                    simple_message_notification::MessageNotification::new(toast.msg.clone())
182                        .with_click_message(click_msg.clone())
183                        .on_click(move |cx| on_click(cx))
184                }
185                None => simple_message_notification::MessageNotification::new(toast.msg.clone()),
186            })
187        })
188    }
189
190    pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
191        self.dismiss_notification(id, cx);
192    }
193
194    pub fn clear_all_notifications(&mut self, cx: &mut ViewContext<Self>) {
195        self.notifications.clear();
196        cx.notify();
197    }
198
199    fn dismiss_notification_internal(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
200        self.notifications.retain(|(existing_id, _)| {
201            if existing_id == id {
202                cx.notify();
203                false
204            } else {
205                true
206            }
207        });
208    }
209}
210
211pub struct LanguageServerPrompt {
212    request: Option<project::LanguageServerPromptRequest>,
213    scroll_handle: ScrollHandle,
214}
215
216impl LanguageServerPrompt {
217    pub fn new(request: project::LanguageServerPromptRequest) -> Self {
218        Self {
219            request: Some(request),
220            scroll_handle: ScrollHandle::new(),
221        }
222    }
223
224    async fn select_option(this: View<Self>, ix: usize, mut cx: AsyncWindowContext) {
225        util::maybe!(async move {
226            let potential_future = this.update(&mut cx, |this, _| {
227                this.request.take().map(|request| request.respond(ix))
228            });
229
230            potential_future? // App Closed
231                .ok_or_else(|| anyhow::anyhow!("Response already sent"))?
232                .await
233                .ok_or_else(|| anyhow::anyhow!("Stream already closed"))?;
234
235            this.update(&mut cx, |_, cx| cx.emit(DismissEvent))?;
236
237            anyhow::Ok(())
238        })
239        .await
240        .log_err();
241    }
242}
243
244impl Render for LanguageServerPrompt {
245    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
246        let Some(request) = &self.request else {
247            return div().id("language_server_prompt_notification");
248        };
249
250        h_flex()
251            .id("language_server_prompt_notification")
252            .occlude()
253            .elevation_3(cx)
254            .items_start()
255            .justify_between()
256            .p_2()
257            .gap_2()
258            .w_full()
259            .max_h(vh(0.8, cx))
260            .overflow_y_scroll()
261            .track_scroll(&self.scroll_handle)
262            .group("")
263            .child(
264                v_flex()
265                    .w_full()
266                    .overflow_hidden()
267                    .child(
268                        h_flex()
269                            .w_full()
270                            .justify_between()
271                            .child(
272                                h_flex()
273                                    .flex_grow()
274                                    .children(
275                                        match request.level {
276                                            PromptLevel::Info => None,
277                                            PromptLevel::Warning => {
278                                                Some(DiagnosticSeverity::WARNING)
279                                            }
280                                            PromptLevel::Critical => {
281                                                Some(DiagnosticSeverity::ERROR)
282                                            }
283                                        }
284                                        .map(|severity| {
285                                            svg()
286                                                .size(cx.text_style().font_size)
287                                                .flex_none()
288                                                .mr_1()
289                                                .mt(px(-2.0))
290                                                .map(|icon| {
291                                                    if severity == DiagnosticSeverity::ERROR {
292                                                        icon.path(
293                                                            IconName::ExclamationTriangle.path(),
294                                                        )
295                                                        .text_color(Color::Error.color(cx))
296                                                    } else {
297                                                        icon.path(
298                                                            IconName::ExclamationTriangle.path(),
299                                                        )
300                                                        .text_color(Color::Warning.color(cx))
301                                                    }
302                                                })
303                                        }),
304                                    )
305                                    .child(
306                                        Label::new(request.lsp_name.clone())
307                                            .size(LabelSize::Default),
308                                    ),
309                            )
310                            .child(
311                                ui::IconButton::new("close", ui::IconName::Close)
312                                    .on_click(cx.listener(|_, _, cx| cx.emit(gpui::DismissEvent))),
313                            ),
314                    )
315                    .child(
316                        v_flex()
317                            .child(
318                                h_flex().absolute().right_0().rounded_md().child(
319                                    ui::IconButton::new("copy", ui::IconName::Copy)
320                                        .on_click({
321                                            let message = request.message.clone();
322                                            move |_, cx| {
323                                                cx.write_to_clipboard(ClipboardItem::new(
324                                                    message.clone(),
325                                                ))
326                                            }
327                                        })
328                                        .tooltip(|cx| Tooltip::text("Copy", cx))
329                                        .visible_on_hover(""),
330                                ),
331                            )
332                            .child(Label::new(request.message.to_string()).size(LabelSize::Small)),
333                    )
334                    .children(request.actions.iter().enumerate().map(|(ix, action)| {
335                        let this_handle = cx.view().clone();
336                        ui::Button::new(ix, action.title.clone())
337                            .size(ButtonSize::Large)
338                            .on_click(move |_, cx| {
339                                let this_handle = this_handle.clone();
340                                cx.spawn(|cx| async move {
341                                    LanguageServerPrompt::select_option(this_handle, ix, cx).await
342                                })
343                                .detach()
344                            })
345                    })),
346            )
347    }
348}
349
350impl EventEmitter<DismissEvent> for LanguageServerPrompt {}
351
352pub mod simple_message_notification {
353    use gpui::{
354        div, DismissEvent, EventEmitter, InteractiveElement, ParentElement, Render, SharedString,
355        StatefulInteractiveElement, Styled, ViewContext,
356    };
357    use std::sync::Arc;
358    use ui::prelude::*;
359    use ui::{h_flex, v_flex, Button, Icon, IconName, Label, StyledExt};
360
361    pub struct MessageNotification {
362        message: SharedString,
363        on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
364        click_message: Option<SharedString>,
365        secondary_click_message: Option<SharedString>,
366        secondary_on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
367    }
368
369    impl EventEmitter<DismissEvent> for MessageNotification {}
370
371    impl MessageNotification {
372        pub fn new<S>(message: S) -> MessageNotification
373        where
374            S: Into<SharedString>,
375        {
376            Self {
377                message: message.into(),
378                on_click: None,
379                click_message: None,
380                secondary_on_click: None,
381                secondary_click_message: None,
382            }
383        }
384
385        pub fn with_click_message<S>(mut self, message: S) -> Self
386        where
387            S: Into<SharedString>,
388        {
389            self.click_message = Some(message.into());
390            self
391        }
392
393        pub fn on_click<F>(mut self, on_click: F) -> Self
394        where
395            F: 'static + Fn(&mut ViewContext<Self>),
396        {
397            self.on_click = Some(Arc::new(on_click));
398            self
399        }
400
401        pub fn with_secondary_click_message<S>(mut self, message: S) -> Self
402        where
403            S: Into<SharedString>,
404        {
405            self.secondary_click_message = Some(message.into());
406            self
407        }
408
409        pub fn on_secondary_click<F>(mut self, on_click: F) -> Self
410        where
411            F: 'static + Fn(&mut ViewContext<Self>),
412        {
413            self.secondary_on_click = Some(Arc::new(on_click));
414            self
415        }
416
417        pub fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
418            cx.emit(DismissEvent);
419        }
420    }
421
422    impl Render for MessageNotification {
423        fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
424            v_flex()
425                .elevation_3(cx)
426                .p_4()
427                .child(
428                    h_flex()
429                        .justify_between()
430                        .child(div().max_w_80().child(Label::new(self.message.clone())))
431                        .child(
432                            div()
433                                .id("cancel")
434                                .child(Icon::new(IconName::Close))
435                                .cursor_pointer()
436                                .on_click(cx.listener(|this, _, cx| this.dismiss(cx))),
437                        ),
438                )
439                .child(
440                    h_flex()
441                        .gap_3()
442                        .children(self.click_message.iter().map(|message| {
443                            Button::new(message.clone(), message.clone()).on_click(cx.listener(
444                                |this, _, cx| {
445                                    if let Some(on_click) = this.on_click.as_ref() {
446                                        (on_click)(cx)
447                                    };
448                                    this.dismiss(cx)
449                                },
450                            ))
451                        }))
452                        .children(self.secondary_click_message.iter().map(|message| {
453                            Button::new(message.clone(), message.clone())
454                                .style(ButtonStyle::Filled)
455                                .on_click(cx.listener(|this, _, cx| {
456                                    if let Some(on_click) = this.secondary_on_click.as_ref() {
457                                        (on_click)(cx)
458                                    };
459                                    this.dismiss(cx)
460                                }))
461                        })),
462                )
463        }
464    }
465}
466
467pub trait NotifyResultExt {
468    type Ok;
469
470    fn notify_err(
471        self,
472        workspace: &mut Workspace,
473        cx: &mut ViewContext<Workspace>,
474    ) -> Option<Self::Ok>;
475
476    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
477}
478
479impl<T, E> NotifyResultExt for Result<T, E>
480where
481    E: std::fmt::Debug + std::fmt::Display,
482{
483    type Ok = T;
484
485    fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
486        match self {
487            Ok(value) => Some(value),
488            Err(err) => {
489                log::error!("TODO {err:?}");
490                workspace.show_error(&err, cx);
491                None
492            }
493        }
494    }
495
496    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
497        match self {
498            Ok(value) => Some(value),
499            Err(err) => {
500                log::error!("{err:?}");
501                cx.update_root(|view, cx| {
502                    if let Ok(workspace) = view.downcast::<Workspace>() {
503                        workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
504                    }
505                })
506                .ok();
507                None
508            }
509        }
510    }
511}
512
513pub trait NotifyTaskExt {
514    fn detach_and_notify_err(self, cx: &mut WindowContext);
515}
516
517impl<R, E> NotifyTaskExt for Task<Result<R, E>>
518where
519    E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
520    R: 'static,
521{
522    fn detach_and_notify_err(self, cx: &mut WindowContext) {
523        cx.spawn(|mut cx| async move { self.await.notify_async_err(&mut cx) })
524            .detach();
525    }
526}
527
528pub trait DetachAndPromptErr {
529    fn prompt_err(
530        self,
531        msg: &str,
532        cx: &mut WindowContext,
533        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
534    ) -> Task<()>;
535
536    fn detach_and_prompt_err(
537        self,
538        msg: &str,
539        cx: &mut WindowContext,
540        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
541    );
542}
543
544impl<R> DetachAndPromptErr for Task<anyhow::Result<R>>
545where
546    R: 'static,
547{
548    fn prompt_err(
549        self,
550        msg: &str,
551        cx: &mut WindowContext,
552        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
553    ) -> Task<()> {
554        let msg = msg.to_owned();
555        cx.spawn(|mut cx| async move {
556            if let Err(err) = self.await {
557                log::error!("{err:?}");
558                if let Ok(prompt) = cx.update(|cx| {
559                    let detail = f(&err, cx).unwrap_or_else(|| format!("{err}. Please try again."));
560                    cx.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"])
561                }) {
562                    prompt.await.ok();
563                }
564            }
565        })
566    }
567
568    fn detach_and_prompt_err(
569        self,
570        msg: &str,
571        cx: &mut WindowContext,
572        f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
573    ) {
574        self.prompt_err(msg, cx, f).detach();
575    }
576}