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 h_flex()
523 .gap_1()
524 .child(
525 CopyButton::new("copy-error-message", self.message.clone())
526 .tooltip_label("Copy Error Message"),
527 )
528 .child(
529 ui::IconButton::new("close", ui::IconName::Close).on_click(
530 cx.listener(|_, _, _, cx| cx.emit(DismissEvent)),
531 ),
532 ),
533 ),
534 )
535 .child(
536 div()
537 .id("error_message")
538 .max_w_96()
539 .max_h_40()
540 .overflow_y_scroll()
541 .child(Label::new(self.message.clone()).size(LabelSize::Small)),
542 )
543 .when_some(self.label_and_url_button.clone(), |elm, (label, url)| {
544 elm.child(
545 div().mt_2().child(
546 ui::Button::new("error_message_prompt_notification_button", label)
547 .on_click(move |_, _, cx| cx.open_url(&url)),
548 ),
549 )
550 }),
551 )
552 }
553}
554
555impl Focusable for ErrorMessagePrompt {
556 fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
557 self.focus_handle.clone()
558 }
559}
560
561impl EventEmitter<DismissEvent> for ErrorMessagePrompt {}
562impl EventEmitter<SuppressEvent> for ErrorMessagePrompt {}
563
564impl Notification for ErrorMessagePrompt {}
565
566#[derive(IntoElement, RegisterComponent)]
567pub struct NotificationFrame {
568 title: Option<SharedString>,
569 show_suppress_button: bool,
570 show_close_button: bool,
571 close: Option<Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
572 contents: Option<AnyElement>,
573 suffix: Option<AnyElement>,
574}
575
576impl NotificationFrame {
577 pub fn new() -> Self {
578 Self {
579 title: None,
580 contents: None,
581 suffix: None,
582 show_suppress_button: true,
583 show_close_button: true,
584 close: None,
585 }
586 }
587
588 pub fn with_title(mut self, title: Option<impl Into<SharedString>>) -> Self {
589 self.title = title.map(Into::into);
590 self
591 }
592
593 pub fn with_content(self, content: impl IntoElement) -> Self {
594 Self {
595 contents: Some(content.into_any_element()),
596 ..self
597 }
598 }
599
600 /// Determines whether the given notification ID should be suppressible
601 /// Suppressed notifications will not be shown anymore
602 pub fn show_suppress_button(mut self, show: bool) -> Self {
603 self.show_suppress_button = show;
604 self
605 }
606
607 pub fn show_close_button(mut self, show: bool) -> Self {
608 self.show_close_button = show;
609 self
610 }
611
612 pub fn on_close(self, on_close: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
613 Self {
614 close: Some(Box::new(on_close)),
615 ..self
616 }
617 }
618
619 pub fn with_suffix(mut self, suffix: impl IntoElement) -> Self {
620 self.suffix = Some(suffix.into_any_element());
621 self
622 }
623}
624
625impl RenderOnce for NotificationFrame {
626 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
627 let entity = window.current_view();
628 let show_suppress_button = self.show_suppress_button;
629 let suppress = show_suppress_button && window.modifiers().shift;
630 let (close_id, close_icon) = if suppress {
631 ("suppress", IconName::Minimize)
632 } else {
633 ("close", IconName::Close)
634 };
635
636 v_flex()
637 .occlude()
638 .p_3()
639 .gap_2()
640 .elevation_3(cx)
641 .child(
642 h_flex()
643 .gap_4()
644 .justify_between()
645 .items_start()
646 .child(
647 v_flex()
648 .gap_0p5()
649 .when_some(self.title.clone(), |div, title| {
650 div.child(Label::new(title))
651 })
652 .child(div().max_w_96().children(self.contents)),
653 )
654 .when(self.show_close_button, |this| {
655 this.on_modifiers_changed(move |_, _, cx| cx.notify(entity))
656 .child(
657 IconButton::new(close_id, close_icon)
658 .tooltip(move |_window, cx| {
659 if suppress {
660 Tooltip::for_action(
661 "Suppress.\nClose with click.",
662 &SuppressNotification,
663 cx,
664 )
665 } else if show_suppress_button {
666 Tooltip::for_action(
667 "Close.\nSuppress with shift-click.",
668 &menu::Cancel,
669 cx,
670 )
671 } else {
672 Tooltip::for_action("Close", &menu::Cancel, cx)
673 }
674 })
675 .on_click({
676 let close = self.close.take();
677 move |_, window, cx| {
678 if let Some(close) = &close {
679 close(&suppress, window, cx)
680 }
681 }
682 }),
683 )
684 }),
685 )
686 .children(self.suffix)
687 }
688}
689
690impl Component for NotificationFrame {}
691
692pub mod simple_message_notification {
693 use std::sync::Arc;
694
695 use gpui::{
696 AnyElement, DismissEvent, EventEmitter, FocusHandle, Focusable, ParentElement, Render,
697 ScrollHandle, SharedString, Styled,
698 };
699 use ui::{WithScrollbar, prelude::*};
700
701 use crate::notifications::NotificationFrame;
702
703 use super::{Notification, SuppressEvent};
704
705 pub struct MessageNotification {
706 focus_handle: FocusHandle,
707 build_content: Box<dyn Fn(&mut Window, &mut Context<Self>) -> AnyElement>,
708 primary_message: Option<SharedString>,
709 primary_icon: Option<IconName>,
710 primary_icon_color: Option<Color>,
711 primary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
712 secondary_message: Option<SharedString>,
713 secondary_icon: Option<IconName>,
714 secondary_icon_color: Option<Color>,
715 secondary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
716 more_info_message: Option<SharedString>,
717 more_info_url: Option<Arc<str>>,
718 show_close_button: bool,
719 show_suppress_button: bool,
720 title: Option<SharedString>,
721 scroll_handle: ScrollHandle,
722 }
723
724 impl Focusable for MessageNotification {
725 fn focus_handle(&self, _: &App) -> FocusHandle {
726 self.focus_handle.clone()
727 }
728 }
729
730 impl EventEmitter<DismissEvent> for MessageNotification {}
731 impl EventEmitter<SuppressEvent> for MessageNotification {}
732
733 impl Notification for MessageNotification {}
734
735 impl MessageNotification {
736 pub fn new<S>(message: S, cx: &mut App) -> MessageNotification
737 where
738 S: Into<SharedString>,
739 {
740 let message = message.into();
741 Self::new_from_builder(cx, move |_, _| {
742 Label::new(message.clone()).into_any_element()
743 })
744 }
745
746 pub fn new_from_builder<F>(cx: &mut App, content: F) -> MessageNotification
747 where
748 F: 'static + Fn(&mut Window, &mut Context<Self>) -> AnyElement,
749 {
750 Self {
751 build_content: Box::new(content),
752 primary_message: None,
753 primary_icon: None,
754 primary_icon_color: None,
755 primary_on_click: None,
756 secondary_message: None,
757 secondary_icon: None,
758 secondary_icon_color: None,
759 secondary_on_click: None,
760 more_info_message: None,
761 more_info_url: None,
762 show_close_button: true,
763 show_suppress_button: true,
764 title: None,
765 focus_handle: cx.focus_handle(),
766 scroll_handle: ScrollHandle::new(),
767 }
768 }
769
770 pub fn primary_message<S>(mut self, message: S) -> Self
771 where
772 S: Into<SharedString>,
773 {
774 self.primary_message = Some(message.into());
775 self
776 }
777
778 pub fn primary_icon(mut self, icon: IconName) -> Self {
779 self.primary_icon = Some(icon);
780 self
781 }
782
783 pub fn primary_icon_color(mut self, color: Color) -> Self {
784 self.primary_icon_color = Some(color);
785 self
786 }
787
788 pub fn primary_on_click<F>(mut self, on_click: F) -> Self
789 where
790 F: 'static + Fn(&mut Window, &mut Context<Self>),
791 {
792 self.primary_on_click = Some(Arc::new(on_click));
793 self
794 }
795
796 pub fn primary_on_click_arc<F>(mut self, on_click: Arc<F>) -> Self
797 where
798 F: 'static + Fn(&mut Window, &mut Context<Self>),
799 {
800 self.primary_on_click = Some(on_click);
801 self
802 }
803
804 pub fn secondary_message<S>(mut self, message: S) -> Self
805 where
806 S: Into<SharedString>,
807 {
808 self.secondary_message = Some(message.into());
809 self
810 }
811
812 pub fn secondary_icon(mut self, icon: IconName) -> Self {
813 self.secondary_icon = Some(icon);
814 self
815 }
816
817 pub fn secondary_icon_color(mut self, color: Color) -> Self {
818 self.secondary_icon_color = Some(color);
819 self
820 }
821
822 pub fn secondary_on_click<F>(mut self, on_click: F) -> Self
823 where
824 F: 'static + Fn(&mut Window, &mut Context<Self>),
825 {
826 self.secondary_on_click = Some(Arc::new(on_click));
827 self
828 }
829
830 pub fn secondary_on_click_arc<F>(mut self, on_click: Arc<F>) -> Self
831 where
832 F: 'static + Fn(&mut Window, &mut Context<Self>),
833 {
834 self.secondary_on_click = Some(on_click);
835 self
836 }
837
838 pub fn more_info_message<S>(mut self, message: S) -> Self
839 where
840 S: Into<SharedString>,
841 {
842 self.more_info_message = Some(message.into());
843 self
844 }
845
846 pub fn more_info_url<S>(mut self, url: S) -> Self
847 where
848 S: Into<Arc<str>>,
849 {
850 self.more_info_url = Some(url.into());
851 self
852 }
853
854 pub fn dismiss(&mut self, cx: &mut Context<Self>) {
855 cx.emit(DismissEvent);
856 }
857
858 pub fn show_close_button(mut self, show: bool) -> Self {
859 self.show_close_button = show;
860 self
861 }
862
863 /// Determines whether the given notification ID should be suppressible
864 /// Suppressed notifications will not be shown anymor
865 pub fn show_suppress_button(mut self, show: bool) -> Self {
866 self.show_suppress_button = show;
867 self
868 }
869
870 pub fn with_title<S>(mut self, title: S) -> Self
871 where
872 S: Into<SharedString>,
873 {
874 self.title = Some(title.into());
875 self
876 }
877 }
878
879 impl Render for MessageNotification {
880 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
881 NotificationFrame::new()
882 .with_title(self.title.clone())
883 .with_content(
884 div()
885 .child(
886 div()
887 .id("message-notification-content")
888 .max_h(vh(0.6, window))
889 .overflow_y_scroll()
890 .track_scroll(&self.scroll_handle.clone())
891 .child((self.build_content)(window, cx)),
892 )
893 .vertical_scrollbar_for(&self.scroll_handle, window, cx),
894 )
895 .show_close_button(self.show_close_button)
896 .show_suppress_button(self.show_suppress_button)
897 .on_close(cx.listener(|_, suppress, _, cx| {
898 if *suppress {
899 cx.emit(SuppressEvent);
900 } else {
901 cx.emit(DismissEvent);
902 }
903 }))
904 .with_suffix(
905 h_flex()
906 .gap_1()
907 .children(self.primary_message.iter().map(|message| {
908 let mut button = Button::new(message.clone(), message.clone())
909 .label_size(LabelSize::Small)
910 .on_click(cx.listener(|this, _, window, cx| {
911 if let Some(on_click) = this.primary_on_click.as_ref() {
912 (on_click)(window, cx)
913 };
914 this.dismiss(cx)
915 }));
916
917 if let Some(icon) = self.primary_icon {
918 button = button
919 .icon(icon)
920 .icon_color(self.primary_icon_color.unwrap_or(Color::Muted))
921 .icon_position(IconPosition::Start)
922 .icon_size(IconSize::Small);
923 }
924
925 button
926 }))
927 .children(self.secondary_message.iter().map(|message| {
928 let mut button = Button::new(message.clone(), message.clone())
929 .label_size(LabelSize::Small)
930 .on_click(cx.listener(|this, _, window, cx| {
931 if let Some(on_click) = this.secondary_on_click.as_ref() {
932 (on_click)(window, cx)
933 };
934 this.dismiss(cx)
935 }));
936
937 if let Some(icon) = self.secondary_icon {
938 button = button
939 .icon(icon)
940 .icon_position(IconPosition::Start)
941 .icon_size(IconSize::Small)
942 .icon_color(self.secondary_icon_color.unwrap_or(Color::Muted));
943 }
944
945 button
946 }))
947 .child(
948 h_flex().w_full().justify_end().children(
949 self.more_info_message
950 .iter()
951 .zip(self.more_info_url.iter())
952 .map(|(message, url)| {
953 let url = url.clone();
954 Button::new(message.clone(), message.clone())
955 .label_size(LabelSize::Small)
956 .icon(IconName::ArrowUpRight)
957 .icon_size(IconSize::Indicator)
958 .icon_color(Color::Muted)
959 .on_click(cx.listener(move |_, _, _, cx| {
960 cx.open_url(&url);
961 }))
962 }),
963 ),
964 ),
965 )
966 }
967 }
968}
969
970static GLOBAL_APP_NOTIFICATIONS: LazyLock<Mutex<AppNotifications>> = LazyLock::new(|| {
971 Mutex::new(AppNotifications {
972 app_notifications: Vec::new(),
973 })
974});
975
976/// Stores app notifications so that they can be shown in new workspaces.
977struct AppNotifications {
978 app_notifications: Vec<(
979 NotificationId,
980 Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
981 )>,
982}
983
984impl AppNotifications {
985 pub fn insert(
986 &mut self,
987 id: NotificationId,
988 build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
989 ) {
990 self.remove(&id);
991 self.app_notifications.push((id, build_notification))
992 }
993
994 pub fn remove(&mut self, id: &NotificationId) {
995 self.app_notifications
996 .retain(|(existing_id, _)| existing_id != id);
997 }
998}
999
1000/// Shows a notification in all workspaces. New workspaces will also receive the notification - this
1001/// is particularly to handle notifications that occur on initialization before any workspaces
1002/// exist. If the notification is dismissed within any workspace, it will be removed from all.
1003pub fn show_app_notification<V: Notification + 'static>(
1004 id: NotificationId,
1005 cx: &mut App,
1006 build_notification: impl Fn(&mut Context<Workspace>) -> Entity<V> + 'static + Send + Sync,
1007) {
1008 // Defer notification creation so that windows on the stack can be returned to GPUI
1009 cx.defer(move |cx| {
1010 // Handle dismiss events by removing the notification from all workspaces.
1011 let build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync> =
1012 Arc::new({
1013 let id = id.clone();
1014 move |cx| {
1015 let notification = build_notification(cx);
1016 cx.subscribe(¬ification, {
1017 let id = id.clone();
1018 move |_, _, _: &DismissEvent, cx| {
1019 dismiss_app_notification(&id, cx);
1020 }
1021 })
1022 .detach();
1023 cx.subscribe(¬ification, {
1024 let id = id.clone();
1025 move |workspace: &mut Workspace, _, _: &SuppressEvent, cx| {
1026 workspace.suppress_notification(&id, cx);
1027 }
1028 })
1029 .detach();
1030 notification.into()
1031 }
1032 });
1033
1034 // Store the notification so that new workspaces also receive it.
1035 GLOBAL_APP_NOTIFICATIONS
1036 .lock()
1037 .insert(id.clone(), build_notification.clone());
1038
1039 for window in cx.windows() {
1040 if let Some(workspace_window) = window.downcast::<Workspace>() {
1041 workspace_window
1042 .update(cx, |workspace, _window, cx| {
1043 workspace.show_notification_without_handling_dismiss_events(
1044 &id,
1045 cx,
1046 |cx| build_notification(cx),
1047 );
1048 })
1049 .ok(); // Doesn't matter if the windows are dropped
1050 }
1051 }
1052 });
1053}
1054
1055pub fn dismiss_app_notification(id: &NotificationId, cx: &mut App) {
1056 let id = id.clone();
1057 // Defer notification dismissal so that windows on the stack can be returned to GPUI
1058 cx.defer(move |cx| {
1059 GLOBAL_APP_NOTIFICATIONS.lock().remove(&id);
1060 for window in cx.windows() {
1061 if let Some(workspace_window) = window.downcast::<Workspace>() {
1062 let id = id.clone();
1063 workspace_window
1064 .update(cx, |workspace, _window, cx| {
1065 workspace.dismiss_notification(&id, cx)
1066 })
1067 .ok();
1068 }
1069 }
1070 });
1071}
1072
1073pub trait NotifyResultExt {
1074 type Ok;
1075
1076 fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>)
1077 -> Option<Self::Ok>;
1078
1079 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
1080
1081 /// Notifies the active workspace if there is one, otherwise notifies all workspaces.
1082 fn notify_app_err(self, cx: &mut App) -> Option<Self::Ok>;
1083}
1084
1085impl<T, E> NotifyResultExt for std::result::Result<T, E>
1086where
1087 E: std::fmt::Debug + std::fmt::Display,
1088{
1089 type Ok = T;
1090
1091 fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>) -> Option<T> {
1092 match self {
1093 Ok(value) => Some(value),
1094 Err(err) => {
1095 log::error!("Showing error notification in workspace: {err:?}");
1096 workspace.show_error(&err, cx);
1097 None
1098 }
1099 }
1100 }
1101
1102 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
1103 match self {
1104 Ok(value) => Some(value),
1105 Err(err) => {
1106 log::error!("{err:?}");
1107 cx.update_root(|view, _, cx| {
1108 if let Ok(workspace) = view.downcast::<Workspace>() {
1109 workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
1110 }
1111 })
1112 .ok();
1113 None
1114 }
1115 }
1116 }
1117
1118 fn notify_app_err(self, cx: &mut App) -> Option<T> {
1119 match self {
1120 Ok(value) => Some(value),
1121 Err(err) => {
1122 let message: SharedString = format!("Error: {err}").into();
1123 log::error!("Showing error notification in app: {message}");
1124 show_app_notification(workspace_error_notification_id(), cx, {
1125 move |cx| {
1126 cx.new({
1127 let message = message.clone();
1128 move |cx| ErrorMessagePrompt::new(message, cx)
1129 })
1130 }
1131 });
1132
1133 None
1134 }
1135 }
1136 }
1137}
1138
1139pub trait NotifyTaskExt {
1140 fn detach_and_notify_err(self, window: &mut Window, cx: &mut App);
1141}
1142
1143impl<R, E> NotifyTaskExt for Task<std::result::Result<R, E>>
1144where
1145 E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
1146 R: 'static,
1147{
1148 fn detach_and_notify_err(self, window: &mut Window, cx: &mut App) {
1149 window
1150 .spawn(cx, async move |cx| self.await.notify_async_err(cx))
1151 .detach();
1152 }
1153}
1154
1155pub trait DetachAndPromptErr<R> {
1156 fn prompt_err(
1157 self,
1158 msg: &str,
1159 window: &Window,
1160 cx: &App,
1161 f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1162 ) -> Task<Option<R>>;
1163
1164 fn detach_and_prompt_err(
1165 self,
1166 msg: &str,
1167 window: &Window,
1168 cx: &App,
1169 f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1170 );
1171}
1172
1173impl<R> DetachAndPromptErr<R> for Task<anyhow::Result<R>>
1174where
1175 R: 'static,
1176{
1177 fn prompt_err(
1178 self,
1179 msg: &str,
1180 window: &Window,
1181 cx: &App,
1182 f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1183 ) -> Task<Option<R>> {
1184 let msg = msg.to_owned();
1185 window.spawn(cx, async move |cx| {
1186 let result = self.await;
1187 if let Err(err) = result.as_ref() {
1188 log::error!("{err:#}");
1189 if let Ok(prompt) = cx.update(|window, cx| {
1190 let mut display = format!("{err:#}");
1191 if !display.ends_with('\n') {
1192 display.push('.');
1193 display.push(' ')
1194 }
1195 let detail =
1196 f(err, window, cx).unwrap_or_else(|| format!("{display}Please try again."));
1197 window.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"], cx)
1198 }) {
1199 prompt.await.ok();
1200 }
1201 return None;
1202 }
1203 Some(result.unwrap())
1204 })
1205 }
1206
1207 fn detach_and_prompt_err(
1208 self,
1209 msg: &str,
1210 window: &Window,
1211 cx: &App,
1212 f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1213 ) {
1214 self.prompt_err(msg, window, cx, f).detach();
1215 }
1216}
1217
1218#[cfg(test)]
1219mod tests {
1220 use fs::FakeFs;
1221 use gpui::TestAppContext;
1222 use project::{LanguageServerPromptRequest, Project};
1223
1224 use crate::tests::init_test;
1225
1226 use super::*;
1227
1228 #[gpui::test]
1229 async fn test_notification_auto_dismiss_with_notifications_from_multiple_language_servers(
1230 cx: &mut TestAppContext,
1231 ) {
1232 init_test(cx);
1233
1234 let fs = FakeFs::new(cx.executor());
1235 let project = Project::test(fs, [], cx).await;
1236
1237 let (workspace, cx) =
1238 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1239
1240 let count_notifications = |workspace: &Entity<Workspace>, cx: &mut TestAppContext| {
1241 workspace.read_with(cx, |workspace, _| workspace.notification_ids().len())
1242 };
1243
1244 let show_notification = |workspace: &Entity<Workspace>,
1245 cx: &mut TestAppContext,
1246 lsp_name: &str| {
1247 workspace.update(cx, |workspace, cx| {
1248 let request = LanguageServerPromptRequest::test(
1249 gpui::PromptLevel::Warning,
1250 "Test notification".to_string(),
1251 vec![], // Empty actions triggers auto-dismiss
1252 lsp_name.to_string(),
1253 );
1254 let notification_id = NotificationId::composite::<LanguageServerPrompt>(request.id);
1255 workspace.show_notification(notification_id, cx, |cx| {
1256 cx.new(|cx| LanguageServerPrompt::new(request, cx))
1257 });
1258 })
1259 };
1260
1261 show_notification(&workspace, cx, "Lsp1");
1262 assert_eq!(count_notifications(&workspace, cx), 1);
1263
1264 cx.executor().advance_clock(Duration::from_millis(1000));
1265
1266 show_notification(&workspace, cx, "Lsp2");
1267 assert_eq!(count_notifications(&workspace, cx), 2);
1268
1269 cx.executor().advance_clock(Duration::from_millis(1000));
1270
1271 show_notification(&workspace, cx, "Lsp3");
1272 assert_eq!(count_notifications(&workspace, cx), 3);
1273
1274 cx.executor().advance_clock(Duration::from_millis(3000));
1275 assert_eq!(count_notifications(&workspace, cx), 2);
1276
1277 cx.executor().advance_clock(Duration::from_millis(1000));
1278 assert_eq!(count_notifications(&workspace, cx), 1);
1279
1280 cx.executor().advance_clock(Duration::from_millis(1000));
1281 assert_eq!(count_notifications(&workspace, cx), 0);
1282 }
1283
1284 #[gpui::test]
1285 async fn test_notification_auto_dismiss_with_multiple_notifications_from_single_language_server(
1286 cx: &mut TestAppContext,
1287 ) {
1288 init_test(cx);
1289
1290 let lsp_name = "server1";
1291
1292 let fs = FakeFs::new(cx.executor());
1293 let project = Project::test(fs, [], cx).await;
1294 let (workspace, cx) =
1295 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1296
1297 let count_notifications = |workspace: &Entity<Workspace>, cx: &mut TestAppContext| {
1298 workspace.read_with(cx, |workspace, _| workspace.notification_ids().len())
1299 };
1300
1301 let show_notification = |lsp_name: &str,
1302 workspace: &Entity<Workspace>,
1303 cx: &mut TestAppContext| {
1304 workspace.update(cx, |workspace, cx| {
1305 let lsp_name = lsp_name.to_string();
1306 let request = LanguageServerPromptRequest::test(
1307 gpui::PromptLevel::Warning,
1308 "Test notification".to_string(),
1309 vec![], // Empty actions triggers auto-dismiss
1310 lsp_name,
1311 );
1312 let notification_id = NotificationId::composite::<LanguageServerPrompt>(request.id);
1313
1314 workspace.show_notification(notification_id, cx, |cx| {
1315 cx.new(|cx| LanguageServerPrompt::new(request, cx))
1316 });
1317 })
1318 };
1319
1320 show_notification(lsp_name, &workspace, cx);
1321 assert_eq!(count_notifications(&workspace, cx), 1);
1322
1323 cx.executor().advance_clock(Duration::from_millis(1000));
1324
1325 show_notification(lsp_name, &workspace, cx);
1326 assert_eq!(count_notifications(&workspace, cx), 2);
1327
1328 cx.executor().advance_clock(Duration::from_millis(4000));
1329 assert_eq!(count_notifications(&workspace, cx), 1);
1330
1331 cx.executor().advance_clock(Duration::from_millis(1000));
1332 assert_eq!(count_notifications(&workspace, cx), 0);
1333 }
1334
1335 #[gpui::test]
1336 async fn test_notification_auto_dismiss_turned_off(cx: &mut TestAppContext) {
1337 init_test(cx);
1338
1339 cx.update(|cx| {
1340 let mut settings = ProjectSettings::get_global(cx).clone();
1341 settings
1342 .global_lsp_settings
1343 .notifications
1344 .dismiss_timeout_ms = Some(0);
1345 ProjectSettings::override_global(settings, cx);
1346 });
1347
1348 let fs = FakeFs::new(cx.executor());
1349 let project = Project::test(fs, [], cx).await;
1350 let (workspace, cx) =
1351 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1352
1353 let count_notifications = |workspace: &Entity<Workspace>, cx: &mut TestAppContext| {
1354 workspace.read_with(cx, |workspace, _| workspace.notification_ids().len())
1355 };
1356
1357 workspace.update(cx, |workspace, cx| {
1358 let request = LanguageServerPromptRequest::test(
1359 gpui::PromptLevel::Warning,
1360 "Test notification".to_string(),
1361 vec![], // Empty actions would trigger auto-dismiss if enabled
1362 "test_server".to_string(),
1363 );
1364 let notification_id = NotificationId::composite::<LanguageServerPrompt>(request.id);
1365 workspace.show_notification(notification_id, cx, |cx| {
1366 cx.new(|cx| LanguageServerPrompt::new(request, cx))
1367 });
1368 });
1369
1370 assert_eq!(count_notifications(&workspace, cx), 1);
1371
1372 // Advance time beyond the default auto-dismiss duration
1373 cx.executor().advance_clock(Duration::from_millis(10000));
1374 assert_eq!(count_notifications(&workspace, cx), 1);
1375 }
1376
1377 #[gpui::test]
1378 async fn test_notification_auto_dismiss_with_custom_duration(cx: &mut TestAppContext) {
1379 init_test(cx);
1380
1381 let custom_duration_ms: u64 = 2000;
1382 cx.update(|cx| {
1383 let mut settings = ProjectSettings::get_global(cx).clone();
1384 settings
1385 .global_lsp_settings
1386 .notifications
1387 .dismiss_timeout_ms = Some(custom_duration_ms);
1388 ProjectSettings::override_global(settings, cx);
1389 });
1390
1391 let fs = FakeFs::new(cx.executor());
1392 let project = Project::test(fs, [], cx).await;
1393 let (workspace, cx) =
1394 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1395
1396 let count_notifications = |workspace: &Entity<Workspace>, cx: &mut TestAppContext| {
1397 workspace.read_with(cx, |workspace, _| workspace.notification_ids().len())
1398 };
1399
1400 workspace.update(cx, |workspace, cx| {
1401 let request = LanguageServerPromptRequest::test(
1402 gpui::PromptLevel::Warning,
1403 "Test notification".to_string(),
1404 vec![], // Empty actions triggers auto-dismiss
1405 "test_server".to_string(),
1406 );
1407 let notification_id = NotificationId::composite::<LanguageServerPrompt>(request.id);
1408 workspace.show_notification(notification_id, cx, |cx| {
1409 cx.new(|cx| LanguageServerPrompt::new(request, cx))
1410 });
1411 });
1412
1413 assert_eq!(count_notifications(&workspace, cx), 1);
1414
1415 // Advance time less than custom duration
1416 cx.executor()
1417 .advance_clock(Duration::from_millis(custom_duration_ms - 500));
1418 assert_eq!(count_notifications(&workspace, cx), 1);
1419
1420 // Advance time past the custom duration
1421 cx.executor().advance_clock(Duration::from_millis(1000));
1422 assert_eq!(count_notifications(&workspace, cx), 0);
1423 }
1424}