notifications.rs

   1use crate::{SuppressNotification, Toast, Workspace};
   2use anyhow::Context as _;
   3use gpui::{
   4    AnyView, App, AppContext as _, AsyncWindowContext, ClickEvent, Context, DismissEvent, Entity,
   5    EventEmitter, FocusHandle, Focusable, PromptLevel, Render, ScrollHandle, Task,
   6    TextStyleRefinement, UnderlineStyle, svg,
   7};
   8use markdown::{Markdown, MarkdownElement, MarkdownStyle};
   9use parking_lot::Mutex;
  10use settings::Settings;
  11use theme::ThemeSettings;
  12
  13use std::ops::Deref;
  14use std::sync::{Arc, LazyLock};
  15use std::{any::TypeId, time::Duration};
  16use ui::{CopyButton, Tooltip, prelude::*};
  17use util::ResultExt;
  18
  19#[derive(Default)]
  20pub struct Notifications {
  21    notifications: Vec<(NotificationId, AnyView)>,
  22}
  23
  24impl Deref for Notifications {
  25    type Target = Vec<(NotificationId, AnyView)>;
  26
  27    fn deref(&self) -> &Self::Target {
  28        &self.notifications
  29    }
  30}
  31
  32impl std::ops::DerefMut for Notifications {
  33    fn deref_mut(&mut self) -> &mut Self::Target {
  34        &mut self.notifications
  35    }
  36}
  37
  38#[derive(Debug, Eq, PartialEq, Clone, Hash)]
  39pub enum NotificationId {
  40    Unique(TypeId),
  41    Composite(TypeId, ElementId),
  42    Named(SharedString),
  43}
  44
  45impl NotificationId {
  46    /// Returns a unique [`NotificationId`] for the given type.
  47    pub const fn unique<T: 'static>() -> Self {
  48        Self::Unique(TypeId::of::<T>())
  49    }
  50
  51    /// Returns a [`NotificationId`] for the given type that is also identified
  52    /// by the provided ID.
  53    pub fn composite<T: 'static>(id: impl Into<ElementId>) -> Self {
  54        Self::Composite(TypeId::of::<T>(), id.into())
  55    }
  56
  57    /// Builds a `NotificationId` out of the given string.
  58    pub fn named(id: SharedString) -> Self {
  59        Self::Named(id)
  60    }
  61}
  62
  63pub trait Notification:
  64    EventEmitter<DismissEvent> + EventEmitter<SuppressEvent> + Focusable + Render
  65{
  66}
  67
  68pub struct SuppressEvent;
  69
  70impl Workspace {
  71    #[cfg(any(test, feature = "test-support"))]
  72    pub fn notification_ids(&self) -> Vec<NotificationId> {
  73        self.notifications
  74            .iter()
  75            .map(|(id, _)| id)
  76            .cloned()
  77            .collect()
  78    }
  79
  80    pub fn show_notification<V: Notification>(
  81        &mut self,
  82        id: NotificationId,
  83        cx: &mut Context<Self>,
  84        build_notification: impl FnOnce(&mut Context<Self>) -> Entity<V>,
  85    ) {
  86        self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
  87            let notification = build_notification(cx);
  88            cx.subscribe(&notification, {
  89                let id = id.clone();
  90                move |this, _, _: &DismissEvent, cx| {
  91                    this.dismiss_notification(&id, cx);
  92                }
  93            })
  94            .detach();
  95            cx.subscribe(&notification, {
  96                let id = id.clone();
  97                move |workspace: &mut Workspace, _, _: &SuppressEvent, cx| {
  98                    workspace.suppress_notification(&id, cx);
  99                }
 100            })
 101            .detach();
 102            notification.into()
 103        });
 104    }
 105
 106    /// Shows a notification in this workspace's window. Caller must handle dismiss.
 107    ///
 108    /// This exists so that the `build_notification` closures stored for app notifications can
 109    /// return `AnyView`. Subscribing to events from an `AnyView` is not supported, so instead that
 110    /// responsibility is pushed to the caller where the `V` type is known.
 111    pub(crate) fn show_notification_without_handling_dismiss_events(
 112        &mut self,
 113        id: &NotificationId,
 114        cx: &mut Context<Self>,
 115        build_notification: impl FnOnce(&mut Context<Self>) -> AnyView,
 116    ) {
 117        if self.suppressed_notifications.contains(id) {
 118            return;
 119        }
 120        self.dismiss_notification(id, cx);
 121        self.notifications
 122            .push((id.clone(), build_notification(cx)));
 123        cx.notify();
 124    }
 125
 126    pub fn show_error<E>(&mut self, err: &E, cx: &mut Context<Self>)
 127    where
 128        E: std::fmt::Debug + std::fmt::Display,
 129    {
 130        self.show_notification(workspace_error_notification_id(), cx, |cx| {
 131            cx.new(|cx| ErrorMessagePrompt::new(format!("Error: {err}"), cx))
 132        });
 133    }
 134
 135    pub fn show_portal_error(&mut self, err: String, cx: &mut Context<Self>) {
 136        struct PortalError;
 137
 138        self.show_notification(NotificationId::unique::<PortalError>(), cx, |cx| {
 139            cx.new(|cx| {
 140                ErrorMessagePrompt::new(err.to_string(), cx).with_link_button(
 141                    "See docs",
 142                    "https://zed.dev/docs/linux#i-cant-open-any-files",
 143                )
 144            })
 145        });
 146    }
 147
 148    pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
 149        self.notifications.retain(|(existing_id, _)| {
 150            if existing_id == id {
 151                cx.notify();
 152                false
 153            } else {
 154                true
 155            }
 156        });
 157    }
 158
 159    pub fn show_toast(&mut self, toast: Toast, cx: &mut Context<Self>) {
 160        self.dismiss_notification(&toast.id, cx);
 161        self.show_notification(toast.id.clone(), cx, |cx| {
 162            cx.new(|cx| match toast.on_click.as_ref() {
 163                Some((click_msg, on_click)) => {
 164                    let on_click = on_click.clone();
 165                    simple_message_notification::MessageNotification::new(toast.msg.clone(), cx)
 166                        .primary_message(click_msg.clone())
 167                        .primary_on_click(move |window, cx| on_click(window, cx))
 168                }
 169                None => {
 170                    simple_message_notification::MessageNotification::new(toast.msg.clone(), cx)
 171                }
 172            })
 173        });
 174        if toast.autohide {
 175            cx.spawn(async move |workspace, cx| {
 176                cx.background_executor()
 177                    .timer(Duration::from_millis(5000))
 178                    .await;
 179                workspace
 180                    .update(cx, |workspace, cx| workspace.dismiss_toast(&toast.id, cx))
 181                    .ok();
 182            })
 183            .detach();
 184        }
 185    }
 186
 187    pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
 188        self.dismiss_notification(id, cx);
 189    }
 190
 191    pub fn clear_all_notifications(&mut self, cx: &mut Context<Self>) {
 192        self.notifications.clear();
 193        cx.notify();
 194    }
 195
 196    /// Hide all notifications matching the given ID
 197    pub fn suppress_notification(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
 198        self.dismiss_notification(id, cx);
 199        self.suppressed_notifications.insert(id.clone());
 200    }
 201
 202    pub fn show_initial_notifications(&mut self, cx: &mut Context<Self>) {
 203        // Allow absence of the global so that tests don't need to initialize it.
 204        let app_notifications = GLOBAL_APP_NOTIFICATIONS
 205            .lock()
 206            .app_notifications
 207            .iter()
 208            .cloned()
 209            .collect::<Vec<_>>();
 210        for (id, build_notification) in app_notifications {
 211            self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
 212                build_notification(cx)
 213            });
 214        }
 215    }
 216}
 217
 218pub struct LanguageServerPrompt {
 219    focus_handle: FocusHandle,
 220    request: Option<project::LanguageServerPromptRequest>,
 221    scroll_handle: ScrollHandle,
 222    markdown: Entity<Markdown>,
 223}
 224
 225impl Focusable for LanguageServerPrompt {
 226    fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
 227        self.focus_handle.clone()
 228    }
 229}
 230
 231impl Notification for LanguageServerPrompt {}
 232
 233impl LanguageServerPrompt {
 234    pub fn new(request: project::LanguageServerPromptRequest, cx: &mut App) -> Self {
 235        let markdown = cx.new(|cx| Markdown::new(request.message.clone().into(), None, None, cx));
 236
 237        Self {
 238            focus_handle: cx.focus_handle(),
 239            request: Some(request),
 240            scroll_handle: ScrollHandle::new(),
 241            markdown,
 242        }
 243    }
 244
 245    async fn select_option(this: Entity<Self>, ix: usize, cx: &mut AsyncWindowContext) {
 246        util::maybe!(async move {
 247            let potential_future = this.update(cx, |this, _| {
 248                this.request.take().map(|request| request.respond(ix))
 249            });
 250
 251            potential_future? // App Closed
 252                .context("Response already sent")?
 253                .await
 254                .context("Stream already closed")?;
 255
 256            this.update(cx, |_, cx| cx.emit(DismissEvent))?;
 257
 258            anyhow::Ok(())
 259        })
 260        .await
 261        .log_err();
 262    }
 263}
 264
 265impl Render for LanguageServerPrompt {
 266    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 267        let Some(request) = &self.request else {
 268            return div().id("language_server_prompt_notification");
 269        };
 270
 271        let (icon, color) = match request.level {
 272            PromptLevel::Info => (IconName::Info, Color::Muted),
 273            PromptLevel::Warning => (IconName::Warning, Color::Warning),
 274            PromptLevel::Critical => (IconName::XCircle, Color::Error),
 275        };
 276
 277        let suppress = window.modifiers().shift;
 278        let (close_id, close_icon) = if suppress {
 279            ("suppress", IconName::Minimize)
 280        } else {
 281            ("close", IconName::Close)
 282        };
 283
 284        div()
 285            .id("language_server_prompt_notification")
 286            .group("language_server_prompt_notification")
 287            .occlude()
 288            .w_full()
 289            .max_h(vh(0.8, window))
 290            .elevation_3(cx)
 291            .overflow_y_scroll()
 292            .track_scroll(&self.scroll_handle)
 293            .on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
 294            .child(
 295                v_flex()
 296                    .p_3()
 297                    .overflow_hidden()
 298                    .child(
 299                        h_flex()
 300                            .justify_between()
 301                            .child(
 302                                h_flex()
 303                                    .gap_2()
 304                                    .child(Icon::new(icon).color(color).size(IconSize::Small))
 305                                    .child(Label::new(request.lsp_name.clone())),
 306                            )
 307                            .child(
 308                                h_flex()
 309                                    .gap_1()
 310                                    .child(
 311                                        CopyButton::new(request.message.clone())
 312                                            .tooltip_label("Copy Description"),
 313                                    )
 314                                    .child(
 315                                        IconButton::new(close_id, close_icon)
 316                                            .tooltip(move |_window, cx| {
 317                                                if suppress {
 318                                                    Tooltip::with_meta(
 319                                                        "Suppress",
 320                                                        Some(&SuppressNotification),
 321                                                        "Click to close",
 322                                                        cx,
 323                                                    )
 324                                                } else {
 325                                                    Tooltip::with_meta(
 326                                                        "Close",
 327                                                        Some(&menu::Cancel),
 328                                                        "Suppress with shift-click",
 329                                                        cx,
 330                                                    )
 331                                                }
 332                                            })
 333                                            .on_click(cx.listener(
 334                                                move |_, _: &ClickEvent, _, cx| {
 335                                                    if suppress {
 336                                                        cx.emit(SuppressEvent);
 337                                                    } else {
 338                                                        cx.emit(DismissEvent);
 339                                                    }
 340                                                },
 341                                            )),
 342                                    ),
 343                            ),
 344                    )
 345                    .child(
 346                        MarkdownElement::new(self.markdown.clone(), markdown_style(window, cx))
 347                            .text_size(TextSize::Small.rems(cx))
 348                            .code_block_renderer(markdown::CodeBlockRenderer::Default {
 349                                copy_button: false,
 350                                copy_button_on_hover: false,
 351                                border: false,
 352                            })
 353                            .on_url_click(|link, _, cx| cx.open_url(&link)),
 354                    )
 355                    .children(request.actions.iter().enumerate().map(|(ix, action)| {
 356                        let this_handle = cx.entity();
 357                        Button::new(ix, action.title.clone())
 358                            .size(ButtonSize::Large)
 359                            .on_click(move |_, window, cx| {
 360                                let this_handle = this_handle.clone();
 361                                window
 362                                    .spawn(cx, async move |cx| {
 363                                        LanguageServerPrompt::select_option(this_handle, ix, cx)
 364                                            .await
 365                                    })
 366                                    .detach()
 367                            })
 368                    })),
 369            )
 370    }
 371}
 372
 373impl EventEmitter<DismissEvent> for LanguageServerPrompt {}
 374impl EventEmitter<SuppressEvent> for LanguageServerPrompt {}
 375
 376fn workspace_error_notification_id() -> NotificationId {
 377    struct WorkspaceErrorNotification;
 378    NotificationId::unique::<WorkspaceErrorNotification>()
 379}
 380
 381fn markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
 382    let settings = ThemeSettings::get_global(cx);
 383    let ui_font_family = settings.ui_font.family.clone();
 384    let ui_font_fallbacks = settings.ui_font.fallbacks.clone();
 385    let buffer_font_family = settings.buffer_font.family.clone();
 386    let buffer_font_fallbacks = settings.buffer_font.fallbacks.clone();
 387
 388    let mut base_text_style = window.text_style();
 389    base_text_style.refine(&TextStyleRefinement {
 390        font_family: Some(ui_font_family),
 391        font_fallbacks: ui_font_fallbacks,
 392        color: Some(cx.theme().colors().text),
 393        ..Default::default()
 394    });
 395
 396    MarkdownStyle {
 397        base_text_style,
 398        selection_background_color: cx.theme().colors().element_selection_background,
 399        inline_code: TextStyleRefinement {
 400            background_color: Some(cx.theme().colors().editor_background.opacity(0.5)),
 401            font_family: Some(buffer_font_family),
 402            font_fallbacks: buffer_font_fallbacks,
 403            ..Default::default()
 404        },
 405        link: TextStyleRefinement {
 406            underline: Some(UnderlineStyle {
 407                thickness: px(1.),
 408                color: Some(cx.theme().colors().text_accent),
 409                wavy: false,
 410            }),
 411            ..Default::default()
 412        },
 413        ..Default::default()
 414    }
 415}
 416
 417#[derive(Debug, Clone)]
 418pub struct ErrorMessagePrompt {
 419    message: SharedString,
 420    focus_handle: gpui::FocusHandle,
 421    label_and_url_button: Option<(SharedString, SharedString)>,
 422}
 423
 424impl ErrorMessagePrompt {
 425    pub fn new<S>(message: S, cx: &mut App) -> Self
 426    where
 427        S: Into<SharedString>,
 428    {
 429        Self {
 430            message: message.into(),
 431            focus_handle: cx.focus_handle(),
 432            label_and_url_button: None,
 433        }
 434    }
 435
 436    pub fn with_link_button<S>(mut self, label: S, url: S) -> Self
 437    where
 438        S: Into<SharedString>,
 439    {
 440        self.label_and_url_button = Some((label.into(), url.into()));
 441        self
 442    }
 443}
 444
 445impl Render for ErrorMessagePrompt {
 446    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 447        h_flex()
 448            .id("error_message_prompt_notification")
 449            .occlude()
 450            .elevation_3(cx)
 451            .items_start()
 452            .justify_between()
 453            .p_2()
 454            .gap_2()
 455            .w_full()
 456            .child(
 457                v_flex()
 458                    .w_full()
 459                    .child(
 460                        h_flex()
 461                            .w_full()
 462                            .justify_between()
 463                            .child(
 464                                svg()
 465                                    .size(window.text_style().font_size)
 466                                    .flex_none()
 467                                    .mr_2()
 468                                    .mt(px(-2.0))
 469                                    .map(|icon| {
 470                                        icon.path(IconName::Warning.path())
 471                                            .text_color(Color::Error.color(cx))
 472                                    }),
 473                            )
 474                            .child(
 475                                ui::IconButton::new("close", ui::IconName::Close)
 476                                    .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
 477                            ),
 478                    )
 479                    .child(
 480                        div()
 481                            .id("error_message")
 482                            .max_w_96()
 483                            .max_h_40()
 484                            .overflow_y_scroll()
 485                            .child(Label::new(self.message.clone()).size(LabelSize::Small)),
 486                    )
 487                    .when_some(self.label_and_url_button.clone(), |elm, (label, url)| {
 488                        elm.child(
 489                            div().mt_2().child(
 490                                ui::Button::new("error_message_prompt_notification_button", label)
 491                                    .on_click(move |_, _, cx| cx.open_url(&url)),
 492                            ),
 493                        )
 494                    }),
 495            )
 496    }
 497}
 498
 499impl Focusable for ErrorMessagePrompt {
 500    fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
 501        self.focus_handle.clone()
 502    }
 503}
 504
 505impl EventEmitter<DismissEvent> for ErrorMessagePrompt {}
 506impl EventEmitter<SuppressEvent> for ErrorMessagePrompt {}
 507
 508impl Notification for ErrorMessagePrompt {}
 509
 510#[derive(IntoElement, RegisterComponent)]
 511pub struct NotificationFrame {
 512    title: Option<SharedString>,
 513    show_suppress_button: bool,
 514    show_close_button: bool,
 515    close: Option<Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
 516    contents: Option<AnyElement>,
 517    suffix: Option<AnyElement>,
 518}
 519
 520impl NotificationFrame {
 521    pub fn new() -> Self {
 522        Self {
 523            title: None,
 524            contents: None,
 525            suffix: None,
 526            show_suppress_button: true,
 527            show_close_button: true,
 528            close: None,
 529        }
 530    }
 531
 532    pub fn with_title(mut self, title: Option<impl Into<SharedString>>) -> Self {
 533        self.title = title.map(Into::into);
 534        self
 535    }
 536
 537    pub fn with_content(self, content: impl IntoElement) -> Self {
 538        Self {
 539            contents: Some(content.into_any_element()),
 540            ..self
 541        }
 542    }
 543
 544    /// Determines whether the given notification ID should be suppressible
 545    /// Suppressed notifications will not be shown anymore
 546    pub fn show_suppress_button(mut self, show: bool) -> Self {
 547        self.show_suppress_button = show;
 548        self
 549    }
 550
 551    pub fn show_close_button(mut self, show: bool) -> Self {
 552        self.show_close_button = show;
 553        self
 554    }
 555
 556    pub fn on_close(self, on_close: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
 557        Self {
 558            close: Some(Box::new(on_close)),
 559            ..self
 560        }
 561    }
 562
 563    pub fn with_suffix(mut self, suffix: impl IntoElement) -> Self {
 564        self.suffix = Some(suffix.into_any_element());
 565        self
 566    }
 567}
 568
 569impl RenderOnce for NotificationFrame {
 570    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
 571        let entity = window.current_view();
 572        let show_suppress_button = self.show_suppress_button;
 573        let suppress = show_suppress_button && window.modifiers().shift;
 574        let (close_id, close_icon) = if suppress {
 575            ("suppress", IconName::Minimize)
 576        } else {
 577            ("close", IconName::Close)
 578        };
 579
 580        v_flex()
 581            .occlude()
 582            .p_3()
 583            .gap_2()
 584            .elevation_3(cx)
 585            .child(
 586                h_flex()
 587                    .gap_4()
 588                    .justify_between()
 589                    .items_start()
 590                    .child(
 591                        v_flex()
 592                            .gap_0p5()
 593                            .when_some(self.title.clone(), |div, title| {
 594                                div.child(Label::new(title))
 595                            })
 596                            .child(div().max_w_96().children(self.contents)),
 597                    )
 598                    .when(self.show_close_button, |this| {
 599                        this.on_modifiers_changed(move |_, _, cx| cx.notify(entity))
 600                            .child(
 601                                IconButton::new(close_id, close_icon)
 602                                    .tooltip(move |_window, cx| {
 603                                        if suppress {
 604                                            Tooltip::for_action(
 605                                                "Suppress.\nClose with click.",
 606                                                &SuppressNotification,
 607                                                cx,
 608                                            )
 609                                        } else if show_suppress_button {
 610                                            Tooltip::for_action(
 611                                                "Close.\nSuppress with shift-click.",
 612                                                &menu::Cancel,
 613                                                cx,
 614                                            )
 615                                        } else {
 616                                            Tooltip::for_action("Close", &menu::Cancel, cx)
 617                                        }
 618                                    })
 619                                    .on_click({
 620                                        let close = self.close.take();
 621                                        move |_, window, cx| {
 622                                            if let Some(close) = &close {
 623                                                close(&suppress, window, cx)
 624                                            }
 625                                        }
 626                                    }),
 627                            )
 628                    }),
 629            )
 630            .children(self.suffix)
 631    }
 632}
 633
 634impl Component for NotificationFrame {}
 635
 636pub mod simple_message_notification {
 637    use std::sync::Arc;
 638
 639    use gpui::{
 640        AnyElement, DismissEvent, EventEmitter, FocusHandle, Focusable, ParentElement, Render,
 641        ScrollHandle, SharedString, Styled,
 642    };
 643    use ui::{WithScrollbar, prelude::*};
 644
 645    use crate::notifications::NotificationFrame;
 646
 647    use super::{Notification, SuppressEvent};
 648
 649    pub struct MessageNotification {
 650        focus_handle: FocusHandle,
 651        build_content: Box<dyn Fn(&mut Window, &mut Context<Self>) -> AnyElement>,
 652        primary_message: Option<SharedString>,
 653        primary_icon: Option<IconName>,
 654        primary_icon_color: Option<Color>,
 655        primary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
 656        secondary_message: Option<SharedString>,
 657        secondary_icon: Option<IconName>,
 658        secondary_icon_color: Option<Color>,
 659        secondary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
 660        more_info_message: Option<SharedString>,
 661        more_info_url: Option<Arc<str>>,
 662        show_close_button: bool,
 663        show_suppress_button: bool,
 664        title: Option<SharedString>,
 665        scroll_handle: ScrollHandle,
 666    }
 667
 668    impl Focusable for MessageNotification {
 669        fn focus_handle(&self, _: &App) -> FocusHandle {
 670            self.focus_handle.clone()
 671        }
 672    }
 673
 674    impl EventEmitter<DismissEvent> for MessageNotification {}
 675    impl EventEmitter<SuppressEvent> for MessageNotification {}
 676
 677    impl Notification for MessageNotification {}
 678
 679    impl MessageNotification {
 680        pub fn new<S>(message: S, cx: &mut App) -> MessageNotification
 681        where
 682            S: Into<SharedString>,
 683        {
 684            let message = message.into();
 685            Self::new_from_builder(cx, move |_, _| {
 686                Label::new(message.clone()).into_any_element()
 687            })
 688        }
 689
 690        pub fn new_from_builder<F>(cx: &mut App, content: F) -> MessageNotification
 691        where
 692            F: 'static + Fn(&mut Window, &mut Context<Self>) -> AnyElement,
 693        {
 694            Self {
 695                build_content: Box::new(content),
 696                primary_message: None,
 697                primary_icon: None,
 698                primary_icon_color: None,
 699                primary_on_click: None,
 700                secondary_message: None,
 701                secondary_icon: None,
 702                secondary_icon_color: None,
 703                secondary_on_click: None,
 704                more_info_message: None,
 705                more_info_url: None,
 706                show_close_button: true,
 707                show_suppress_button: true,
 708                title: None,
 709                focus_handle: cx.focus_handle(),
 710                scroll_handle: ScrollHandle::new(),
 711            }
 712        }
 713
 714        pub fn primary_message<S>(mut self, message: S) -> Self
 715        where
 716            S: Into<SharedString>,
 717        {
 718            self.primary_message = Some(message.into());
 719            self
 720        }
 721
 722        pub fn primary_icon(mut self, icon: IconName) -> Self {
 723            self.primary_icon = Some(icon);
 724            self
 725        }
 726
 727        pub fn primary_icon_color(mut self, color: Color) -> Self {
 728            self.primary_icon_color = Some(color);
 729            self
 730        }
 731
 732        pub fn primary_on_click<F>(mut self, on_click: F) -> Self
 733        where
 734            F: 'static + Fn(&mut Window, &mut Context<Self>),
 735        {
 736            self.primary_on_click = Some(Arc::new(on_click));
 737            self
 738        }
 739
 740        pub fn primary_on_click_arc<F>(mut self, on_click: Arc<F>) -> Self
 741        where
 742            F: 'static + Fn(&mut Window, &mut Context<Self>),
 743        {
 744            self.primary_on_click = Some(on_click);
 745            self
 746        }
 747
 748        pub fn secondary_message<S>(mut self, message: S) -> Self
 749        where
 750            S: Into<SharedString>,
 751        {
 752            self.secondary_message = Some(message.into());
 753            self
 754        }
 755
 756        pub fn secondary_icon(mut self, icon: IconName) -> Self {
 757            self.secondary_icon = Some(icon);
 758            self
 759        }
 760
 761        pub fn secondary_icon_color(mut self, color: Color) -> Self {
 762            self.secondary_icon_color = Some(color);
 763            self
 764        }
 765
 766        pub fn secondary_on_click<F>(mut self, on_click: F) -> Self
 767        where
 768            F: 'static + Fn(&mut Window, &mut Context<Self>),
 769        {
 770            self.secondary_on_click = Some(Arc::new(on_click));
 771            self
 772        }
 773
 774        pub fn secondary_on_click_arc<F>(mut self, on_click: Arc<F>) -> Self
 775        where
 776            F: 'static + Fn(&mut Window, &mut Context<Self>),
 777        {
 778            self.secondary_on_click = Some(on_click);
 779            self
 780        }
 781
 782        pub fn more_info_message<S>(mut self, message: S) -> Self
 783        where
 784            S: Into<SharedString>,
 785        {
 786            self.more_info_message = Some(message.into());
 787            self
 788        }
 789
 790        pub fn more_info_url<S>(mut self, url: S) -> Self
 791        where
 792            S: Into<Arc<str>>,
 793        {
 794            self.more_info_url = Some(url.into());
 795            self
 796        }
 797
 798        pub fn dismiss(&mut self, cx: &mut Context<Self>) {
 799            cx.emit(DismissEvent);
 800        }
 801
 802        pub fn show_close_button(mut self, show: bool) -> Self {
 803            self.show_close_button = show;
 804            self
 805        }
 806
 807        /// Determines whether the given notification ID should be suppressible
 808        /// Suppressed notifications will not be shown anymor
 809        pub fn show_suppress_button(mut self, show: bool) -> Self {
 810            self.show_suppress_button = show;
 811            self
 812        }
 813
 814        pub fn with_title<S>(mut self, title: S) -> Self
 815        where
 816            S: Into<SharedString>,
 817        {
 818            self.title = Some(title.into());
 819            self
 820        }
 821    }
 822
 823    impl Render for MessageNotification {
 824        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 825            NotificationFrame::new()
 826                .with_title(self.title.clone())
 827                .with_content(
 828                    div()
 829                        .child(
 830                            div()
 831                                .id("message-notification-content")
 832                                .max_h(vh(0.6, window))
 833                                .overflow_y_scroll()
 834                                .track_scroll(&self.scroll_handle.clone())
 835                                .child((self.build_content)(window, cx)),
 836                        )
 837                        .vertical_scrollbar_for(&self.scroll_handle, window, cx),
 838                )
 839                .show_close_button(self.show_close_button)
 840                .show_suppress_button(self.show_suppress_button)
 841                .on_close(cx.listener(|_, suppress, _, cx| {
 842                    if *suppress {
 843                        cx.emit(SuppressEvent);
 844                    } else {
 845                        cx.emit(DismissEvent);
 846                    }
 847                }))
 848                .with_suffix(
 849                    h_flex()
 850                        .gap_1()
 851                        .children(self.primary_message.iter().map(|message| {
 852                            let mut button = Button::new(message.clone(), message.clone())
 853                                .label_size(LabelSize::Small)
 854                                .on_click(cx.listener(|this, _, window, cx| {
 855                                    if let Some(on_click) = this.primary_on_click.as_ref() {
 856                                        (on_click)(window, cx)
 857                                    };
 858                                    this.dismiss(cx)
 859                                }));
 860
 861                            if let Some(icon) = self.primary_icon {
 862                                button = button
 863                                    .icon(icon)
 864                                    .icon_color(self.primary_icon_color.unwrap_or(Color::Muted))
 865                                    .icon_position(IconPosition::Start)
 866                                    .icon_size(IconSize::Small);
 867                            }
 868
 869                            button
 870                        }))
 871                        .children(self.secondary_message.iter().map(|message| {
 872                            let mut button = Button::new(message.clone(), message.clone())
 873                                .label_size(LabelSize::Small)
 874                                .on_click(cx.listener(|this, _, window, cx| {
 875                                    if let Some(on_click) = this.secondary_on_click.as_ref() {
 876                                        (on_click)(window, cx)
 877                                    };
 878                                    this.dismiss(cx)
 879                                }));
 880
 881                            if let Some(icon) = self.secondary_icon {
 882                                button = button
 883                                    .icon(icon)
 884                                    .icon_position(IconPosition::Start)
 885                                    .icon_size(IconSize::Small)
 886                                    .icon_color(self.secondary_icon_color.unwrap_or(Color::Muted));
 887                            }
 888
 889                            button
 890                        }))
 891                        .child(
 892                            h_flex().w_full().justify_end().children(
 893                                self.more_info_message
 894                                    .iter()
 895                                    .zip(self.more_info_url.iter())
 896                                    .map(|(message, url)| {
 897                                        let url = url.clone();
 898                                        Button::new(message.clone(), message.clone())
 899                                            .label_size(LabelSize::Small)
 900                                            .icon(IconName::ArrowUpRight)
 901                                            .icon_size(IconSize::Indicator)
 902                                            .icon_color(Color::Muted)
 903                                            .on_click(cx.listener(move |_, _, _, cx| {
 904                                                cx.open_url(&url);
 905                                            }))
 906                                    }),
 907                            ),
 908                        ),
 909                )
 910        }
 911    }
 912}
 913
 914static GLOBAL_APP_NOTIFICATIONS: LazyLock<Mutex<AppNotifications>> = LazyLock::new(|| {
 915    Mutex::new(AppNotifications {
 916        app_notifications: Vec::new(),
 917    })
 918});
 919
 920/// Stores app notifications so that they can be shown in new workspaces.
 921struct AppNotifications {
 922    app_notifications: Vec<(
 923        NotificationId,
 924        Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
 925    )>,
 926}
 927
 928impl AppNotifications {
 929    pub fn insert(
 930        &mut self,
 931        id: NotificationId,
 932        build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
 933    ) {
 934        self.remove(&id);
 935        self.app_notifications.push((id, build_notification))
 936    }
 937
 938    pub fn remove(&mut self, id: &NotificationId) {
 939        self.app_notifications
 940            .retain(|(existing_id, _)| existing_id != id);
 941    }
 942}
 943
 944/// Shows a notification in all workspaces. New workspaces will also receive the notification - this
 945/// is particularly to handle notifications that occur on initialization before any workspaces
 946/// exist. If the notification is dismissed within any workspace, it will be removed from all.
 947pub fn show_app_notification<V: Notification + 'static>(
 948    id: NotificationId,
 949    cx: &mut App,
 950    build_notification: impl Fn(&mut Context<Workspace>) -> Entity<V> + 'static + Send + Sync,
 951) {
 952    // Defer notification creation so that windows on the stack can be returned to GPUI
 953    cx.defer(move |cx| {
 954        // Handle dismiss events by removing the notification from all workspaces.
 955        let build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync> =
 956            Arc::new({
 957                let id = id.clone();
 958                move |cx| {
 959                    let notification = build_notification(cx);
 960                    cx.subscribe(&notification, {
 961                        let id = id.clone();
 962                        move |_, _, _: &DismissEvent, cx| {
 963                            dismiss_app_notification(&id, cx);
 964                        }
 965                    })
 966                    .detach();
 967                    cx.subscribe(&notification, {
 968                        let id = id.clone();
 969                        move |workspace: &mut Workspace, _, _: &SuppressEvent, cx| {
 970                            workspace.suppress_notification(&id, cx);
 971                        }
 972                    })
 973                    .detach();
 974                    notification.into()
 975                }
 976            });
 977
 978        // Store the notification so that new workspaces also receive it.
 979        GLOBAL_APP_NOTIFICATIONS
 980            .lock()
 981            .insert(id.clone(), build_notification.clone());
 982
 983        for window in cx.windows() {
 984            if let Some(workspace_window) = window.downcast::<Workspace>() {
 985                workspace_window
 986                    .update(cx, |workspace, _window, cx| {
 987                        workspace.show_notification_without_handling_dismiss_events(
 988                            &id,
 989                            cx,
 990                            |cx| build_notification(cx),
 991                        );
 992                    })
 993                    .ok(); // Doesn't matter if the windows are dropped
 994            }
 995        }
 996    });
 997}
 998
 999pub fn dismiss_app_notification(id: &NotificationId, cx: &mut App) {
1000    let id = id.clone();
1001    // Defer notification dismissal so that windows on the stack can be returned to GPUI
1002    cx.defer(move |cx| {
1003        GLOBAL_APP_NOTIFICATIONS.lock().remove(&id);
1004        for window in cx.windows() {
1005            if let Some(workspace_window) = window.downcast::<Workspace>() {
1006                let id = id.clone();
1007                workspace_window
1008                    .update(cx, |workspace, _window, cx| {
1009                        workspace.dismiss_notification(&id, cx)
1010                    })
1011                    .ok();
1012            }
1013        }
1014    });
1015}
1016
1017pub trait NotifyResultExt {
1018    type Ok;
1019
1020    fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>)
1021    -> Option<Self::Ok>;
1022
1023    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
1024
1025    /// Notifies the active workspace if there is one, otherwise notifies all workspaces.
1026    fn notify_app_err(self, cx: &mut App) -> Option<Self::Ok>;
1027}
1028
1029impl<T, E> NotifyResultExt for std::result::Result<T, E>
1030where
1031    E: std::fmt::Debug + std::fmt::Display,
1032{
1033    type Ok = T;
1034
1035    fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>) -> Option<T> {
1036        match self {
1037            Ok(value) => Some(value),
1038            Err(err) => {
1039                log::error!("Showing error notification in workspace: {err:?}");
1040                workspace.show_error(&err, cx);
1041                None
1042            }
1043        }
1044    }
1045
1046    fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
1047        match self {
1048            Ok(value) => Some(value),
1049            Err(err) => {
1050                log::error!("{err:?}");
1051                cx.update_root(|view, _, cx| {
1052                    if let Ok(workspace) = view.downcast::<Workspace>() {
1053                        workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
1054                    }
1055                })
1056                .ok();
1057                None
1058            }
1059        }
1060    }
1061
1062    fn notify_app_err(self, cx: &mut App) -> Option<T> {
1063        match self {
1064            Ok(value) => Some(value),
1065            Err(err) => {
1066                let message: SharedString = format!("Error: {err}").into();
1067                log::error!("Showing error notification in app: {message}");
1068                show_app_notification(workspace_error_notification_id(), cx, {
1069                    move |cx| {
1070                        cx.new({
1071                            let message = message.clone();
1072                            move |cx| ErrorMessagePrompt::new(message, cx)
1073                        })
1074                    }
1075                });
1076
1077                None
1078            }
1079        }
1080    }
1081}
1082
1083pub trait NotifyTaskExt {
1084    fn detach_and_notify_err(self, window: &mut Window, cx: &mut App);
1085}
1086
1087impl<R, E> NotifyTaskExt for Task<std::result::Result<R, E>>
1088where
1089    E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
1090    R: 'static,
1091{
1092    fn detach_and_notify_err(self, window: &mut Window, cx: &mut App) {
1093        window
1094            .spawn(cx, async move |cx| self.await.notify_async_err(cx))
1095            .detach();
1096    }
1097}
1098
1099pub trait DetachAndPromptErr<R> {
1100    fn prompt_err(
1101        self,
1102        msg: &str,
1103        window: &Window,
1104        cx: &App,
1105        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1106    ) -> Task<Option<R>>;
1107
1108    fn detach_and_prompt_err(
1109        self,
1110        msg: &str,
1111        window: &Window,
1112        cx: &App,
1113        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1114    );
1115}
1116
1117impl<R> DetachAndPromptErr<R> for Task<anyhow::Result<R>>
1118where
1119    R: 'static,
1120{
1121    fn prompt_err(
1122        self,
1123        msg: &str,
1124        window: &Window,
1125        cx: &App,
1126        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1127    ) -> Task<Option<R>> {
1128        let msg = msg.to_owned();
1129        window.spawn(cx, async move |cx| {
1130            let result = self.await;
1131            if let Err(err) = result.as_ref() {
1132                log::error!("{err:#}");
1133                if let Ok(prompt) = cx.update(|window, cx| {
1134                    let mut display = format!("{err:#}");
1135                    if !display.ends_with('\n') {
1136                        display.push('.');
1137                        display.push(' ')
1138                    }
1139                    let detail =
1140                        f(err, window, cx).unwrap_or_else(|| format!("{display}Please try again."));
1141                    window.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"], cx)
1142                }) {
1143                    prompt.await.ok();
1144                }
1145                return None;
1146            }
1147            Some(result.unwrap())
1148        })
1149    }
1150
1151    fn detach_and_prompt_err(
1152        self,
1153        msg: &str,
1154        window: &Window,
1155        cx: &App,
1156        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1157    ) {
1158        self.prompt_err(msg, window, cx, f).detach();
1159    }
1160}