1use crate::{Toast, Workspace};
2use gpui::{
3 svg, AnyView, App, AppContext as _, AsyncWindowContext, ClipboardItem, Context, DismissEvent,
4 Entity, EventEmitter, Global, PromptLevel, Render, ScrollHandle, Task,
5};
6use parking_lot::Mutex;
7use std::sync::{Arc, LazyLock};
8use std::{any::TypeId, time::Duration};
9use ui::{prelude::*, Tooltip};
10use util::ResultExt;
11
12#[derive(Debug, PartialEq, Clone)]
13pub enum NotificationId {
14 Unique(TypeId),
15 Composite(TypeId, ElementId),
16 Named(SharedString),
17}
18
19impl NotificationId {
20 /// Returns a unique [`NotificationId`] for the given type.
21 pub fn unique<T: 'static>() -> Self {
22 Self::Unique(TypeId::of::<T>())
23 }
24
25 /// Returns a [`NotificationId`] for the given type that is also identified
26 /// by the provided ID.
27 pub fn composite<T: 'static>(id: impl Into<ElementId>) -> Self {
28 Self::Composite(TypeId::of::<T>(), id.into())
29 }
30
31 /// Builds a `NotificationId` out of the given string.
32 pub fn named(id: SharedString) -> Self {
33 Self::Named(id)
34 }
35}
36
37pub trait Notification: EventEmitter<DismissEvent> + Render {}
38
39impl<V: EventEmitter<DismissEvent> + Render> Notification for V {}
40
41impl Workspace {
42 #[cfg(any(test, feature = "test-support"))]
43 pub fn notification_ids(&self) -> Vec<NotificationId> {
44 self.notifications
45 .iter()
46 .map(|(id, _)| id)
47 .cloned()
48 .collect()
49 }
50
51 pub fn show_notification<V: Notification>(
52 &mut self,
53 id: NotificationId,
54 cx: &mut Context<Self>,
55 build_notification: impl FnOnce(&mut Context<Self>) -> Entity<V>,
56 ) {
57 self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
58 let notification = build_notification(cx);
59 cx.subscribe(¬ification, {
60 let id = id.clone();
61 move |this, _, _: &DismissEvent, cx| {
62 this.dismiss_notification(&id, cx);
63 }
64 })
65 .detach();
66 notification.into()
67 });
68 }
69
70 /// Shows a notification in this workspace's window. Caller must handle dismiss.
71 ///
72 /// This exists so that the `build_notification` closures stored for app notifications can
73 /// return `AnyView`. Subscribing to events from an `AnyView` is not supported, so instead that
74 /// responsibility is pushed to the caller where the `V` type is known.
75 pub(crate) fn show_notification_without_handling_dismiss_events(
76 &mut self,
77 id: &NotificationId,
78 cx: &mut Context<Self>,
79 build_notification: impl FnOnce(&mut Context<Self>) -> AnyView,
80 ) {
81 self.dismiss_notification(id, cx);
82 self.notifications
83 .push((id.clone(), build_notification(cx)));
84 cx.notify();
85 }
86
87 pub fn show_error<E>(&mut self, err: &E, cx: &mut Context<Self>)
88 where
89 E: std::fmt::Debug + std::fmt::Display,
90 {
91 self.show_notification(workspace_error_notification_id(), cx, |cx| {
92 cx.new(|_| ErrorMessagePrompt::new(format!("Error: {err}")))
93 });
94 }
95
96 pub fn show_portal_error(&mut self, err: String, cx: &mut Context<Self>) {
97 struct PortalError;
98
99 self.show_notification(NotificationId::unique::<PortalError>(), cx, |cx| {
100 cx.new(|_| {
101 ErrorMessagePrompt::new(err.to_string()).with_link_button(
102 "See docs",
103 "https://zed.dev/docs/linux#i-cant-open-any-files",
104 )
105 })
106 });
107 }
108
109 pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
110 self.notifications.retain(|(existing_id, _)| {
111 if existing_id == id {
112 cx.notify();
113 false
114 } else {
115 true
116 }
117 });
118 }
119
120 pub fn show_toast(&mut self, toast: Toast, cx: &mut Context<Self>) {
121 self.dismiss_notification(&toast.id, cx);
122 self.show_notification(toast.id.clone(), cx, |cx| {
123 cx.new(|_| match toast.on_click.as_ref() {
124 Some((click_msg, on_click)) => {
125 let on_click = on_click.clone();
126 simple_message_notification::MessageNotification::new(toast.msg.clone())
127 .with_click_message(click_msg.clone())
128 .on_click(move |window, cx| on_click(window, cx))
129 }
130 None => simple_message_notification::MessageNotification::new(toast.msg.clone()),
131 })
132 });
133 if toast.autohide {
134 cx.spawn(|workspace, mut cx| async move {
135 cx.background_executor()
136 .timer(Duration::from_millis(5000))
137 .await;
138 workspace
139 .update(&mut cx, |workspace, cx| {
140 workspace.dismiss_toast(&toast.id, cx)
141 })
142 .ok();
143 })
144 .detach();
145 }
146 }
147
148 pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
149 self.dismiss_notification(id, cx);
150 }
151
152 pub fn clear_all_notifications(&mut self, cx: &mut Context<Self>) {
153 self.notifications.clear();
154 cx.notify();
155 }
156
157 pub fn show_initial_notifications(&mut self, cx: &mut Context<Self>) {
158 // Allow absence of the global so that tests don't need to initialize it.
159 let app_notifications = cx
160 .try_global::<AppNotifications>()
161 .iter()
162 .flat_map(|global| global.app_notifications.iter().cloned())
163 .collect::<Vec<_>>();
164 for (id, build_notification) in app_notifications {
165 self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
166 build_notification(cx)
167 });
168 }
169 }
170}
171
172pub struct LanguageServerPrompt {
173 request: Option<project::LanguageServerPromptRequest>,
174 scroll_handle: ScrollHandle,
175}
176
177impl LanguageServerPrompt {
178 pub fn new(request: project::LanguageServerPromptRequest) -> Self {
179 Self {
180 request: Some(request),
181 scroll_handle: ScrollHandle::new(),
182 }
183 }
184
185 async fn select_option(this: Entity<Self>, ix: usize, mut cx: AsyncWindowContext) {
186 util::maybe!(async move {
187 let potential_future = this.update(&mut cx, |this, _| {
188 this.request.take().map(|request| request.respond(ix))
189 });
190
191 potential_future? // App Closed
192 .ok_or_else(|| anyhow::anyhow!("Response already sent"))?
193 .await
194 .ok_or_else(|| anyhow::anyhow!("Stream already closed"))?;
195
196 this.update(&mut cx, |_, cx| cx.emit(DismissEvent))?;
197
198 anyhow::Ok(())
199 })
200 .await
201 .log_err();
202 }
203}
204
205impl Render for LanguageServerPrompt {
206 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
207 let Some(request) = &self.request else {
208 return div().id("language_server_prompt_notification");
209 };
210
211 let (icon, color) = match request.level {
212 PromptLevel::Info => (IconName::Info, Color::Accent),
213 PromptLevel::Warning => (IconName::Warning, Color::Warning),
214 PromptLevel::Critical => (IconName::XCircle, Color::Error),
215 };
216
217 div()
218 .id("language_server_prompt_notification")
219 .group("language_server_prompt_notification")
220 .occlude()
221 .w_full()
222 .max_h(vh(0.8, window))
223 .elevation_3(cx)
224 .overflow_y_scroll()
225 .track_scroll(&self.scroll_handle)
226 .child(
227 v_flex()
228 .p_3()
229 .overflow_hidden()
230 .child(
231 h_flex()
232 .justify_between()
233 .items_start()
234 .child(
235 h_flex()
236 .gap_2()
237 .child(Icon::new(icon).color(color))
238 .child(Label::new(request.lsp_name.clone())),
239 )
240 .child(
241 h_flex()
242 .child(
243 IconButton::new("copy", IconName::Copy)
244 .on_click({
245 let message = request.message.clone();
246 move |_, _, cx| {
247 cx.write_to_clipboard(
248 ClipboardItem::new_string(message.clone()),
249 )
250 }
251 })
252 .tooltip(Tooltip::text("Copy Description")),
253 )
254 .child(IconButton::new("close", IconName::Close).on_click(
255 cx.listener(|_, _, _, cx| cx.emit(gpui::DismissEvent)),
256 )),
257 ),
258 )
259 .child(Label::new(request.message.to_string()).size(LabelSize::Small))
260 .children(request.actions.iter().enumerate().map(|(ix, action)| {
261 let this_handle = cx.entity().clone();
262 Button::new(ix, action.title.clone())
263 .size(ButtonSize::Large)
264 .on_click(move |_, window, cx| {
265 let this_handle = this_handle.clone();
266 window
267 .spawn(cx, |cx| async move {
268 LanguageServerPrompt::select_option(this_handle, ix, cx)
269 .await
270 })
271 .detach()
272 })
273 })),
274 )
275 }
276}
277
278impl EventEmitter<DismissEvent> for LanguageServerPrompt {}
279
280fn workspace_error_notification_id() -> NotificationId {
281 struct WorkspaceErrorNotification;
282 NotificationId::unique::<WorkspaceErrorNotification>()
283}
284
285#[derive(Debug, Clone)]
286pub struct ErrorMessagePrompt {
287 message: SharedString,
288 label_and_url_button: Option<(SharedString, SharedString)>,
289}
290
291impl ErrorMessagePrompt {
292 pub fn new<S>(message: S) -> Self
293 where
294 S: Into<SharedString>,
295 {
296 Self {
297 message: message.into(),
298 label_and_url_button: None,
299 }
300 }
301
302 pub fn with_link_button<S>(mut self, label: S, url: S) -> Self
303 where
304 S: Into<SharedString>,
305 {
306 self.label_and_url_button = Some((label.into(), url.into()));
307 self
308 }
309}
310
311impl Render for ErrorMessagePrompt {
312 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
313 h_flex()
314 .id("error_message_prompt_notification")
315 .occlude()
316 .elevation_3(cx)
317 .items_start()
318 .justify_between()
319 .p_2()
320 .gap_2()
321 .w_full()
322 .child(
323 v_flex()
324 .w_full()
325 .child(
326 h_flex()
327 .w_full()
328 .justify_between()
329 .child(
330 svg()
331 .size(window.text_style().font_size)
332 .flex_none()
333 .mr_2()
334 .mt(px(-2.0))
335 .map(|icon| {
336 icon.path(IconName::Warning.path())
337 .text_color(Color::Error.color(cx))
338 }),
339 )
340 .child(
341 ui::IconButton::new("close", ui::IconName::Close).on_click(
342 cx.listener(|_, _, _, cx| cx.emit(gpui::DismissEvent)),
343 ),
344 ),
345 )
346 .child(
347 div()
348 .id("error_message")
349 .max_w_96()
350 .max_h_40()
351 .overflow_y_scroll()
352 .child(Label::new(self.message.clone()).size(LabelSize::Small)),
353 )
354 .when_some(self.label_and_url_button.clone(), |elm, (label, url)| {
355 elm.child(
356 div().mt_2().child(
357 ui::Button::new("error_message_prompt_notification_button", label)
358 .on_click(move |_, _, cx| cx.open_url(&url)),
359 ),
360 )
361 }),
362 )
363 }
364}
365
366impl EventEmitter<DismissEvent> for ErrorMessagePrompt {}
367
368pub mod simple_message_notification {
369 use std::sync::Arc;
370
371 use gpui::{
372 div, AnyElement, DismissEvent, EventEmitter, ParentElement, Render, SharedString, Styled,
373 };
374 use ui::prelude::*;
375
376 pub struct MessageNotification {
377 build_content: Box<dyn Fn(&mut Window, &mut Context<Self>) -> AnyElement>,
378 on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
379 click_message: Option<SharedString>,
380 secondary_click_message: Option<SharedString>,
381 secondary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
382 }
383
384 impl EventEmitter<DismissEvent> for MessageNotification {}
385
386 impl MessageNotification {
387 pub fn new<S>(message: S) -> MessageNotification
388 where
389 S: Into<SharedString>,
390 {
391 let message = message.into();
392 Self::new_from_builder(move |_, _| Label::new(message.clone()).into_any_element())
393 }
394
395 pub fn new_from_builder<F>(content: F) -> MessageNotification
396 where
397 F: 'static + Fn(&mut Window, &mut Context<Self>) -> AnyElement,
398 {
399 Self {
400 build_content: Box::new(content),
401 on_click: None,
402 click_message: None,
403 secondary_on_click: None,
404 secondary_click_message: None,
405 }
406 }
407
408 pub fn with_click_message<S>(mut self, message: S) -> Self
409 where
410 S: Into<SharedString>,
411 {
412 self.click_message = Some(message.into());
413 self
414 }
415
416 pub fn on_click<F>(mut self, on_click: F) -> Self
417 where
418 F: 'static + Fn(&mut Window, &mut Context<Self>),
419 {
420 self.on_click = Some(Arc::new(on_click));
421 self
422 }
423
424 pub fn with_secondary_click_message<S>(mut self, message: S) -> Self
425 where
426 S: Into<SharedString>,
427 {
428 self.secondary_click_message = Some(message.into());
429 self
430 }
431
432 pub fn on_secondary_click<F>(mut self, on_click: F) -> Self
433 where
434 F: 'static + Fn(&mut Window, &mut Context<Self>),
435 {
436 self.secondary_on_click = Some(Arc::new(on_click));
437 self
438 }
439
440 pub fn dismiss(&mut self, cx: &mut Context<Self>) {
441 cx.emit(DismissEvent);
442 }
443 }
444
445 impl Render for MessageNotification {
446 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
447 v_flex()
448 .p_3()
449 .gap_2()
450 .elevation_3(cx)
451 .child(
452 h_flex()
453 .gap_4()
454 .justify_between()
455 .items_start()
456 .child(div().max_w_96().child((self.build_content)(window, cx)))
457 .child(
458 IconButton::new("close", IconName::Close)
459 .on_click(cx.listener(|this, _, _, cx| this.dismiss(cx))),
460 ),
461 )
462 .child(
463 h_flex()
464 .gap_2()
465 .children(self.click_message.iter().map(|message| {
466 Button::new(message.clone(), message.clone())
467 .label_size(LabelSize::Small)
468 .icon(IconName::Check)
469 .icon_position(IconPosition::Start)
470 .icon_size(IconSize::Small)
471 .icon_color(Color::Success)
472 .on_click(cx.listener(|this, _, window, cx| {
473 if let Some(on_click) = this.on_click.as_ref() {
474 (on_click)(window, cx)
475 };
476 this.dismiss(cx)
477 }))
478 }))
479 .children(self.secondary_click_message.iter().map(|message| {
480 Button::new(message.clone(), message.clone())
481 .label_size(LabelSize::Small)
482 .icon(IconName::Close)
483 .icon_position(IconPosition::Start)
484 .icon_size(IconSize::Small)
485 .icon_color(Color::Error)
486 .on_click(cx.listener(|this, _, window, cx| {
487 if let Some(on_click) = this.secondary_on_click.as_ref() {
488 (on_click)(window, cx)
489 };
490 this.dismiss(cx)
491 }))
492 })),
493 )
494 }
495 }
496}
497
498static GLOBAL_APP_NOTIFICATIONS: LazyLock<Mutex<AppNotifications>> = LazyLock::new(|| {
499 Mutex::new(AppNotifications {
500 app_notifications: Vec::new(),
501 })
502});
503
504/// Stores app notifications so that they can be shown in new workspaces.
505struct AppNotifications {
506 app_notifications: Vec<(
507 NotificationId,
508 Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
509 )>,
510}
511
512impl Global for AppNotifications {}
513
514impl AppNotifications {
515 pub fn insert(
516 &mut self,
517 id: NotificationId,
518 build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
519 ) {
520 self.remove(&id);
521 self.app_notifications.push((id, build_notification))
522 }
523
524 pub fn remove(&mut self, id: &NotificationId) {
525 self.app_notifications
526 .retain(|(existing_id, _)| existing_id != id);
527 }
528}
529
530/// Shows a notification in all workspaces. New workspaces will also receive the notification - this
531/// is particularly to handle notifications that occur on initialization before any workspaces
532/// exist. If the notification is dismissed within any workspace, it will be removed from all.
533pub fn show_app_notification<V: Notification + 'static>(
534 id: NotificationId,
535 cx: &mut App,
536 build_notification: impl Fn(&mut Context<Workspace>) -> Entity<V> + 'static + Send + Sync,
537) {
538 // Defer notification creation so that windows on the stack can be returned to GPUI
539 cx.defer(move |cx| {
540 // Handle dismiss events by removing the notification from all workspaces.
541 let build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync> =
542 Arc::new({
543 let id = id.clone();
544 move |cx| {
545 let notification = build_notification(cx);
546 cx.subscribe(¬ification, {
547 let id = id.clone();
548 move |_, _, _: &DismissEvent, cx| {
549 dismiss_app_notification(&id, cx);
550 }
551 })
552 .detach();
553 notification.into()
554 }
555 });
556
557 // Store the notification so that new workspaces also receive it.
558 GLOBAL_APP_NOTIFICATIONS
559 .lock()
560 .insert(id.clone(), build_notification.clone());
561
562 for window in cx.windows() {
563 if let Some(workspace_window) = window.downcast::<Workspace>() {
564 workspace_window
565 .update(cx, |workspace, _window, cx| {
566 workspace.show_notification_without_handling_dismiss_events(
567 &id,
568 cx,
569 |cx| build_notification(cx),
570 );
571 })
572 .ok(); // Doesn't matter if the windows are dropped
573 }
574 }
575 });
576}
577
578pub fn dismiss_app_notification(id: &NotificationId, cx: &mut App) {
579 let id = id.clone();
580 // Defer notification dismissal so that windows on the stack can be returned to GPUI
581 cx.defer(move |cx| {
582 GLOBAL_APP_NOTIFICATIONS.lock().remove(&id);
583 for window in cx.windows() {
584 if let Some(workspace_window) = window.downcast::<Workspace>() {
585 let id = id.clone();
586 workspace_window
587 .update(cx, |workspace, _window, cx| {
588 workspace.dismiss_notification(&id, cx)
589 })
590 .ok();
591 }
592 }
593 });
594}
595
596pub trait NotifyResultExt {
597 type Ok;
598
599 fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>)
600 -> Option<Self::Ok>;
601
602 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
603
604 /// Notifies the active workspace if there is one, otherwise notifies all workspaces.
605 fn notify_app_err(self, cx: &mut App) -> Option<Self::Ok>;
606}
607
608impl<T, E> NotifyResultExt for std::result::Result<T, E>
609where
610 E: std::fmt::Debug + std::fmt::Display,
611{
612 type Ok = T;
613
614 fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>) -> Option<T> {
615 match self {
616 Ok(value) => Some(value),
617 Err(err) => {
618 log::error!("Showing error notification in workspace: {err:?}");
619 workspace.show_error(&err, cx);
620 None
621 }
622 }
623 }
624
625 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
626 match self {
627 Ok(value) => Some(value),
628 Err(err) => {
629 log::error!("{err:?}");
630 cx.update_root(|view, _, cx| {
631 if let Ok(workspace) = view.downcast::<Workspace>() {
632 workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
633 }
634 })
635 .ok();
636 None
637 }
638 }
639 }
640
641 fn notify_app_err(self, cx: &mut App) -> Option<T> {
642 match self {
643 Ok(value) => Some(value),
644 Err(err) => {
645 let message: SharedString = format!("Error: {err}").into();
646 log::error!("Showing error notification in app: {message}");
647 show_app_notification(workspace_error_notification_id(), cx, {
648 let message = message.clone();
649 move |cx| {
650 cx.new({
651 let message = message.clone();
652 move |_cx| ErrorMessagePrompt::new(message)
653 })
654 }
655 });
656
657 None
658 }
659 }
660 }
661}
662
663pub trait NotifyTaskExt {
664 fn detach_and_notify_err(self, window: &mut Window, cx: &mut App);
665}
666
667impl<R, E> NotifyTaskExt for Task<std::result::Result<R, E>>
668where
669 E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
670 R: 'static,
671{
672 fn detach_and_notify_err(self, window: &mut Window, cx: &mut App) {
673 window
674 .spawn(
675 cx,
676 |mut cx| async move { self.await.notify_async_err(&mut cx) },
677 )
678 .detach();
679 }
680}
681
682pub trait DetachAndPromptErr<R> {
683 fn prompt_err(
684 self,
685 msg: &str,
686 window: &Window,
687 cx: &App,
688 f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
689 ) -> Task<Option<R>>;
690
691 fn detach_and_prompt_err(
692 self,
693 msg: &str,
694 window: &Window,
695 cx: &App,
696 f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
697 );
698}
699
700impl<R> DetachAndPromptErr<R> for Task<anyhow::Result<R>>
701where
702 R: 'static,
703{
704 fn prompt_err(
705 self,
706 msg: &str,
707 window: &Window,
708 cx: &App,
709 f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
710 ) -> Task<Option<R>> {
711 let msg = msg.to_owned();
712 window.spawn(cx, |mut cx| async move {
713 let result = self.await;
714 if let Err(err) = result.as_ref() {
715 log::error!("{err:?}");
716 if let Ok(prompt) = cx.update(|window, cx| {
717 let detail =
718 f(err, window, cx).unwrap_or_else(|| format!("{err}. Please try again."));
719 window.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"], cx)
720 }) {
721 prompt.await.ok();
722 }
723 return None;
724 }
725 Some(result.unwrap())
726 })
727 }
728
729 fn detach_and_prompt_err(
730 self,
731 msg: &str,
732 window: &Window,
733 cx: &App,
734 f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
735 ) {
736 self.prompt_err(msg, window, cx, f).detach();
737 }
738}