1use crate::{Toast, Workspace};
2use collections::HashMap;
3use gpui::{
4 svg, AnyView, AppContext, AsyncWindowContext, ClipboardItem, DismissEvent, Entity, EntityId,
5 EventEmitter, Global, PromptLevel, Render, ScrollHandle, Task, View, ViewContext,
6 VisualContext, WindowContext,
7};
8use language::DiagnosticSeverity;
9
10use std::{any::TypeId, ops::DerefMut};
11use ui::{prelude::*, Tooltip};
12use util::ResultExt;
13
14pub fn init(cx: &mut AppContext) {
15 cx.set_global(NotificationTracker::new());
16}
17
18#[derive(Debug, PartialEq, Clone)]
19pub struct NotificationId {
20 /// A [`TypeId`] used to uniquely identify this notification.
21 type_id: TypeId,
22 /// A supplementary ID used to distinguish between multiple
23 /// notifications that have the same [`type_id`](Self::type_id);
24 id: Option<ElementId>,
25}
26
27impl NotificationId {
28 /// Returns a unique [`NotificationId`] for the given type.
29 pub fn unique<T: 'static>() -> Self {
30 Self {
31 type_id: TypeId::of::<T>(),
32 id: None,
33 }
34 }
35
36 /// Returns a [`NotificationId`] for the given type that is also identified
37 /// by the provided ID.
38 pub fn identified<T: 'static>(id: impl Into<ElementId>) -> Self {
39 Self {
40 type_id: TypeId::of::<T>(),
41 id: Some(id.into()),
42 }
43 }
44}
45
46pub trait Notification: EventEmitter<DismissEvent> + Render {}
47
48impl<V: EventEmitter<DismissEvent> + Render> Notification for V {}
49
50pub trait NotificationHandle: Send {
51 fn id(&self) -> EntityId;
52 fn to_any(&self) -> AnyView;
53}
54
55impl<T: Notification> NotificationHandle for View<T> {
56 fn id(&self) -> EntityId {
57 self.entity_id()
58 }
59
60 fn to_any(&self) -> AnyView {
61 self.clone().into()
62 }
63}
64
65impl From<&dyn NotificationHandle> for AnyView {
66 fn from(val: &dyn NotificationHandle) -> Self {
67 val.to_any()
68 }
69}
70
71pub(crate) struct NotificationTracker {
72 notifications_sent: HashMap<TypeId, Vec<NotificationId>>,
73}
74
75impl Global for NotificationTracker {}
76
77impl std::ops::Deref for NotificationTracker {
78 type Target = HashMap<TypeId, Vec<NotificationId>>;
79
80 fn deref(&self) -> &Self::Target {
81 &self.notifications_sent
82 }
83}
84
85impl DerefMut for NotificationTracker {
86 fn deref_mut(&mut self) -> &mut Self::Target {
87 &mut self.notifications_sent
88 }
89}
90
91impl NotificationTracker {
92 fn new() -> Self {
93 Self {
94 notifications_sent: Default::default(),
95 }
96 }
97}
98
99impl Workspace {
100 pub fn has_shown_notification_once<V: Notification>(
101 &self,
102 id: &NotificationId,
103 cx: &ViewContext<Self>,
104 ) -> bool {
105 cx.global::<NotificationTracker>()
106 .get(&TypeId::of::<V>())
107 .map(|ids| ids.contains(id))
108 .unwrap_or(false)
109 }
110
111 pub fn show_notification_once<V: Notification>(
112 &mut self,
113 id: NotificationId,
114 cx: &mut ViewContext<Self>,
115 build_notification: impl FnOnce(&mut ViewContext<Self>) -> View<V>,
116 ) {
117 if !self.has_shown_notification_once::<V>(&id, cx) {
118 let tracker = cx.global_mut::<NotificationTracker>();
119 let entry = tracker.entry(TypeId::of::<V>()).or_default();
120 entry.push(id.clone());
121 self.show_notification::<V>(id, cx, build_notification)
122 }
123 }
124
125 #[cfg(any(test, feature = "test-support"))]
126 pub fn notification_ids(&self) -> Vec<NotificationId> {
127 self.notifications
128 .iter()
129 .map(|(id, _)| id)
130 .cloned()
131 .collect()
132 }
133
134 pub fn show_notification<V: Notification>(
135 &mut self,
136 id: NotificationId,
137 cx: &mut ViewContext<Self>,
138 build_notification: impl FnOnce(&mut ViewContext<Self>) -> View<V>,
139 ) {
140 self.dismiss_notification_internal(&id, cx);
141
142 let notification = build_notification(cx);
143 cx.subscribe(¬ification, {
144 let id = id.clone();
145 move |this, _, _: &DismissEvent, cx| {
146 this.dismiss_notification_internal(&id, cx);
147 }
148 })
149 .detach();
150 self.notifications.push((id, Box::new(notification)));
151 cx.notify();
152 }
153
154 pub fn show_error<E>(&mut self, err: &E, cx: &mut ViewContext<Self>)
155 where
156 E: std::fmt::Debug + std::fmt::Display,
157 {
158 struct WorkspaceErrorNotification;
159
160 self.show_notification(
161 NotificationId::unique::<WorkspaceErrorNotification>(),
162 cx,
163 |cx| {
164 cx.new_view(|_cx| {
165 simple_message_notification::MessageNotification::new(format!("Error: {err:#}"))
166 })
167 },
168 );
169 }
170
171 pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
172 self.dismiss_notification_internal(id, cx)
173 }
174
175 pub fn show_toast(&mut self, toast: Toast, cx: &mut ViewContext<Self>) {
176 self.dismiss_notification(&toast.id, cx);
177 self.show_notification(toast.id, cx, |cx| {
178 cx.new_view(|_cx| match toast.on_click.as_ref() {
179 Some((click_msg, on_click)) => {
180 let on_click = on_click.clone();
181 simple_message_notification::MessageNotification::new(toast.msg.clone())
182 .with_click_message(click_msg.clone())
183 .on_click(move |cx| on_click(cx))
184 }
185 None => simple_message_notification::MessageNotification::new(toast.msg.clone()),
186 })
187 })
188 }
189
190 pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
191 self.dismiss_notification(id, cx);
192 }
193
194 fn dismiss_notification_internal(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
195 self.notifications.retain(|(existing_id, _)| {
196 if existing_id == id {
197 cx.notify();
198 false
199 } else {
200 true
201 }
202 });
203 }
204}
205
206pub struct LanguageServerPrompt {
207 request: Option<project::LanguageServerPromptRequest>,
208 scroll_handle: ScrollHandle,
209}
210
211impl LanguageServerPrompt {
212 pub fn new(request: project::LanguageServerPromptRequest) -> Self {
213 Self {
214 request: Some(request),
215 scroll_handle: ScrollHandle::new(),
216 }
217 }
218
219 async fn select_option(this: View<Self>, ix: usize, mut cx: AsyncWindowContext) {
220 util::maybe!(async move {
221 let potential_future = this.update(&mut cx, |this, _| {
222 this.request.take().map(|request| request.respond(ix))
223 });
224
225 potential_future? // App Closed
226 .ok_or_else(|| anyhow::anyhow!("Response already sent"))?
227 .await
228 .ok_or_else(|| anyhow::anyhow!("Stream already closed"))?;
229
230 this.update(&mut cx, |_, cx| cx.emit(DismissEvent))?;
231
232 anyhow::Ok(())
233 })
234 .await
235 .log_err();
236 }
237}
238
239impl Render for LanguageServerPrompt {
240 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
241 let Some(request) = &self.request else {
242 return div().id("language_server_prompt_notification");
243 };
244
245 h_flex()
246 .id("language_server_prompt_notification")
247 .occlude()
248 .elevation_3(cx)
249 .items_start()
250 .justify_between()
251 .p_2()
252 .gap_2()
253 .w_full()
254 .max_h(vh(0.8, cx))
255 .overflow_y_scroll()
256 .track_scroll(&self.scroll_handle)
257 .group("")
258 .child(
259 v_flex()
260 .w_full()
261 .overflow_hidden()
262 .child(
263 h_flex()
264 .w_full()
265 .justify_between()
266 .child(
267 h_flex()
268 .flex_grow()
269 .children(
270 match request.level {
271 PromptLevel::Info => None,
272 PromptLevel::Warning => {
273 Some(DiagnosticSeverity::WARNING)
274 }
275 PromptLevel::Critical => {
276 Some(DiagnosticSeverity::ERROR)
277 }
278 }
279 .map(|severity| {
280 svg()
281 .size(cx.text_style().font_size)
282 .flex_none()
283 .mr_1()
284 .mt(px(-2.0))
285 .map(|icon| {
286 if severity == DiagnosticSeverity::ERROR {
287 icon.path(
288 IconName::ExclamationTriangle.path(),
289 )
290 .text_color(Color::Error.color(cx))
291 } else {
292 icon.path(
293 IconName::ExclamationTriangle.path(),
294 )
295 .text_color(Color::Warning.color(cx))
296 }
297 })
298 }),
299 )
300 .child(
301 Label::new(request.lsp_name.clone())
302 .size(LabelSize::Default),
303 ),
304 )
305 .child(
306 ui::IconButton::new("close", ui::IconName::Close)
307 .on_click(cx.listener(|_, _, cx| cx.emit(gpui::DismissEvent))),
308 ),
309 )
310 .child(
311 v_flex()
312 .child(
313 h_flex().absolute().right_0().rounded_md().child(
314 ui::IconButton::new("copy", ui::IconName::Copy)
315 .on_click({
316 let message = request.message.clone();
317 move |_, cx| {
318 cx.write_to_clipboard(ClipboardItem::new(
319 message.clone(),
320 ))
321 }
322 })
323 .tooltip(|cx| Tooltip::text("Copy", cx))
324 .visible_on_hover(""),
325 ),
326 )
327 .child(Label::new(request.message.to_string()).size(LabelSize::Small)),
328 )
329 .children(request.actions.iter().enumerate().map(|(ix, action)| {
330 let this_handle = cx.view().clone();
331 ui::Button::new(ix, action.title.clone())
332 .size(ButtonSize::Large)
333 .on_click(move |_, cx| {
334 let this_handle = this_handle.clone();
335 cx.spawn(|cx| async move {
336 LanguageServerPrompt::select_option(this_handle, ix, cx).await
337 })
338 .detach()
339 })
340 })),
341 )
342 }
343}
344
345impl EventEmitter<DismissEvent> for LanguageServerPrompt {}
346
347pub mod simple_message_notification {
348 use gpui::{
349 div, DismissEvent, EventEmitter, InteractiveElement, ParentElement, Render, SharedString,
350 StatefulInteractiveElement, Styled, ViewContext,
351 };
352 use std::sync::Arc;
353 use ui::prelude::*;
354 use ui::{h_flex, v_flex, Button, Icon, IconName, Label, StyledExt};
355
356 pub struct MessageNotification {
357 message: SharedString,
358 on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
359 click_message: Option<SharedString>,
360 secondary_click_message: Option<SharedString>,
361 secondary_on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
362 }
363
364 impl EventEmitter<DismissEvent> for MessageNotification {}
365
366 impl MessageNotification {
367 pub fn new<S>(message: S) -> MessageNotification
368 where
369 S: Into<SharedString>,
370 {
371 Self {
372 message: message.into(),
373 on_click: None,
374 click_message: None,
375 secondary_on_click: None,
376 secondary_click_message: None,
377 }
378 }
379
380 pub fn with_click_message<S>(mut self, message: S) -> Self
381 where
382 S: Into<SharedString>,
383 {
384 self.click_message = Some(message.into());
385 self
386 }
387
388 pub fn on_click<F>(mut self, on_click: F) -> Self
389 where
390 F: 'static + Fn(&mut ViewContext<Self>),
391 {
392 self.on_click = Some(Arc::new(on_click));
393 self
394 }
395
396 pub fn with_secondary_click_message<S>(mut self, message: S) -> Self
397 where
398 S: Into<SharedString>,
399 {
400 self.secondary_click_message = Some(message.into());
401 self
402 }
403
404 pub fn on_secondary_click<F>(mut self, on_click: F) -> Self
405 where
406 F: 'static + Fn(&mut ViewContext<Self>),
407 {
408 self.secondary_on_click = Some(Arc::new(on_click));
409 self
410 }
411
412 pub fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
413 cx.emit(DismissEvent);
414 }
415 }
416
417 impl Render for MessageNotification {
418 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
419 v_flex()
420 .elevation_3(cx)
421 .p_4()
422 .child(
423 h_flex()
424 .justify_between()
425 .child(div().max_w_80().child(Label::new(self.message.clone())))
426 .child(
427 div()
428 .id("cancel")
429 .child(Icon::new(IconName::Close))
430 .cursor_pointer()
431 .on_click(cx.listener(|this, _, cx| this.dismiss(cx))),
432 ),
433 )
434 .child(
435 h_flex()
436 .gap_3()
437 .children(self.click_message.iter().map(|message| {
438 Button::new(message.clone(), message.clone()).on_click(cx.listener(
439 |this, _, cx| {
440 if let Some(on_click) = this.on_click.as_ref() {
441 (on_click)(cx)
442 };
443 this.dismiss(cx)
444 },
445 ))
446 }))
447 .children(self.secondary_click_message.iter().map(|message| {
448 Button::new(message.clone(), message.clone())
449 .style(ButtonStyle::Filled)
450 .on_click(cx.listener(|this, _, cx| {
451 if let Some(on_click) = this.secondary_on_click.as_ref() {
452 (on_click)(cx)
453 };
454 this.dismiss(cx)
455 }))
456 })),
457 )
458 }
459 }
460}
461
462pub trait NotifyResultExt {
463 type Ok;
464
465 fn notify_err(
466 self,
467 workspace: &mut Workspace,
468 cx: &mut ViewContext<Workspace>,
469 ) -> Option<Self::Ok>;
470
471 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
472}
473
474impl<T, E> NotifyResultExt for Result<T, E>
475where
476 E: std::fmt::Debug + std::fmt::Display,
477{
478 type Ok = T;
479
480 fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
481 match self {
482 Ok(value) => Some(value),
483 Err(err) => {
484 log::error!("TODO {err:?}");
485 workspace.show_error(&err, cx);
486 None
487 }
488 }
489 }
490
491 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
492 match self {
493 Ok(value) => Some(value),
494 Err(err) => {
495 log::error!("{err:?}");
496 cx.update_root(|view, cx| {
497 if let Ok(workspace) = view.downcast::<Workspace>() {
498 workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
499 }
500 })
501 .ok();
502 None
503 }
504 }
505 }
506}
507
508pub trait NotifyTaskExt {
509 fn detach_and_notify_err(self, cx: &mut WindowContext);
510}
511
512impl<R, E> NotifyTaskExt for Task<Result<R, E>>
513where
514 E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
515 R: 'static,
516{
517 fn detach_and_notify_err(self, cx: &mut WindowContext) {
518 cx.spawn(|mut cx| async move { self.await.notify_async_err(&mut cx) })
519 .detach();
520 }
521}
522
523pub trait DetachAndPromptErr {
524 fn prompt_err(
525 self,
526 msg: &str,
527 cx: &mut WindowContext,
528 f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
529 ) -> Task<()>;
530
531 fn detach_and_prompt_err(
532 self,
533 msg: &str,
534 cx: &mut WindowContext,
535 f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
536 );
537}
538
539impl<R> DetachAndPromptErr for Task<anyhow::Result<R>>
540where
541 R: 'static,
542{
543 fn prompt_err(
544 self,
545 msg: &str,
546 cx: &mut WindowContext,
547 f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
548 ) -> Task<()> {
549 let msg = msg.to_owned();
550 cx.spawn(|mut cx| async move {
551 if let Err(err) = self.await {
552 log::error!("{err:?}");
553 if let Ok(prompt) = cx.update(|cx| {
554 let detail = f(&err, cx).unwrap_or_else(|| format!("{err}. Please try again."));
555 cx.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"])
556 }) {
557 prompt.await.ok();
558 }
559 }
560 })
561 }
562
563 fn detach_and_prompt_err(
564 self,
565 msg: &str,
566 cx: &mut WindowContext,
567 f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
568 ) {
569 self.prompt_err(msg, cx, f).detach();
570 }
571}