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