1use crate::{Toast, Workspace};
2use collections::HashMap;
3use gpui::{
4 AnyView, AppContext, AsyncWindowContext, DismissEvent, Entity, EntityId, EventEmitter, Render,
5 View, ViewContext, VisualContext,
6};
7use std::{any::TypeId, ops::DerefMut};
8
9pub fn init(cx: &mut AppContext) {
10 cx.set_global(NotificationTracker::new());
11 // todo!()
12 // simple_message_notification::init(cx);
13}
14
15pub trait Notification: EventEmitter<DismissEvent> + Render {}
16
17impl<V: EventEmitter<DismissEvent> + Render> Notification for V {}
18
19pub trait NotificationHandle: Send {
20 fn id(&self) -> EntityId;
21 fn to_any(&self) -> AnyView;
22}
23
24impl<T: Notification> NotificationHandle for View<T> {
25 fn id(&self) -> EntityId {
26 self.entity_id()
27 }
28
29 fn to_any(&self) -> AnyView {
30 self.clone().into()
31 }
32}
33
34impl From<&dyn NotificationHandle> for AnyView {
35 fn from(val: &dyn NotificationHandle) -> Self {
36 val.to_any()
37 }
38}
39
40pub(crate) struct NotificationTracker {
41 notifications_sent: HashMap<TypeId, Vec<usize>>,
42}
43
44impl std::ops::Deref for NotificationTracker {
45 type Target = HashMap<TypeId, Vec<usize>>;
46
47 fn deref(&self) -> &Self::Target {
48 &self.notifications_sent
49 }
50}
51
52impl DerefMut for NotificationTracker {
53 fn deref_mut(&mut self) -> &mut Self::Target {
54 &mut self.notifications_sent
55 }
56}
57
58impl NotificationTracker {
59 fn new() -> Self {
60 Self {
61 notifications_sent: Default::default(),
62 }
63 }
64}
65
66impl Workspace {
67 pub fn has_shown_notification_once<V: Notification>(
68 &self,
69 id: usize,
70 cx: &ViewContext<Self>,
71 ) -> bool {
72 cx.global::<NotificationTracker>()
73 .get(&TypeId::of::<V>())
74 .map(|ids| ids.contains(&id))
75 .unwrap_or(false)
76 }
77
78 pub fn show_notification_once<V: Notification>(
79 &mut self,
80 id: usize,
81 cx: &mut ViewContext<Self>,
82 build_notification: impl FnOnce(&mut ViewContext<Self>) -> View<V>,
83 ) {
84 if !self.has_shown_notification_once::<V>(id, cx) {
85 let tracker = cx.global_mut::<NotificationTracker>();
86 let entry = tracker.entry(TypeId::of::<V>()).or_default();
87 entry.push(id);
88 self.show_notification::<V>(id, cx, build_notification)
89 }
90 }
91
92 pub fn show_notification<V: Notification>(
93 &mut self,
94 id: usize,
95 cx: &mut ViewContext<Self>,
96 build_notification: impl FnOnce(&mut ViewContext<Self>) -> View<V>,
97 ) {
98 let type_id = TypeId::of::<V>();
99 if self
100 .notifications
101 .iter()
102 .all(|(existing_type_id, existing_id, _)| {
103 (*existing_type_id, *existing_id) != (type_id, id)
104 })
105 {
106 let notification = build_notification(cx);
107 cx.subscribe(
108 ¬ification,
109 move |this, handle, event: &DismissEvent, cx| {
110 this.dismiss_notification_internal(type_id, id, cx);
111 },
112 )
113 .detach();
114 self.notifications
115 .push((type_id, id, Box::new(notification)));
116 cx.notify();
117 }
118 }
119
120 pub fn show_error<E>(&mut self, err: &E, cx: &mut ViewContext<Self>)
121 where
122 E: std::fmt::Debug,
123 {
124 self.show_notification(0, cx, |cx| {
125 cx.build_view(|_cx| {
126 simple_message_notification::MessageNotification::new(format!("Error: {err:?}"))
127 })
128 });
129 }
130
131 pub fn dismiss_notification<V: Notification>(&mut self, id: usize, cx: &mut ViewContext<Self>) {
132 let type_id = TypeId::of::<V>();
133
134 self.dismiss_notification_internal(type_id, id, cx)
135 }
136
137 pub fn show_toast(&mut self, toast: Toast, cx: &mut ViewContext<Self>) {
138 todo!()
139 // self.dismiss_notification::<simple_message_notification::MessageNotification>(toast.id, cx);
140 // self.show_notification(toast.id, cx, |cx| {
141 // cx.add_view(|_cx| match toast.on_click.as_ref() {
142 // Some((click_msg, on_click)) => {
143 // let on_click = on_click.clone();
144 // simple_message_notification::MessageNotification::new(toast.msg.clone())
145 // .with_click_message(click_msg.clone())
146 // .on_click(move |cx| on_click(cx))
147 // }
148 // None => simple_message_notification::MessageNotification::new(toast.msg.clone()),
149 // })
150 // })
151 }
152
153 pub fn dismiss_toast(&mut self, id: usize, cx: &mut ViewContext<Self>) {
154 todo!()
155 // self.dismiss_notification::<simple_message_notification::MessageNotification>(id, cx);
156 }
157
158 fn dismiss_notification_internal(
159 &mut self,
160 type_id: TypeId,
161 id: usize,
162 cx: &mut ViewContext<Self>,
163 ) {
164 self.notifications
165 .retain(|(existing_type_id, existing_id, _)| {
166 if (*existing_type_id, *existing_id) == (type_id, id) {
167 cx.notify();
168 false
169 } else {
170 true
171 }
172 });
173 }
174}
175
176pub mod simple_message_notification {
177 use gpui::{
178 div, AnyElement, AppContext, DismissEvent, Div, EventEmitter, InteractiveElement,
179 ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, TextStyle,
180 ViewContext,
181 };
182 use serde::Deserialize;
183 use std::{borrow::Cow, sync::Arc};
184 use ui::{h_stack, v_stack, Button, Icon, IconElement, Label, StyledExt};
185
186 #[derive(Clone, Default, Deserialize, PartialEq)]
187 pub struct OsOpen(pub Cow<'static, str>);
188
189 impl OsOpen {
190 pub fn new<I: Into<Cow<'static, str>>>(url: I) -> Self {
191 OsOpen(url.into())
192 }
193 }
194
195 // todo!()
196 // impl_actions!(message_notifications, [OsOpen]);
197 //
198 // todo!()
199 // pub fn init(cx: &mut AppContext) {
200 // cx.add_action(MessageNotification::dismiss);
201 // cx.add_action(
202 // |_workspace: &mut Workspace, open_action: &OsOpen, cx: &mut ViewContext<Workspace>| {
203 // cx.platform().open_url(open_action.0.as_ref());
204 // },
205 // )
206 // }
207
208 enum NotificationMessage {
209 Text(SharedString),
210 Element(fn(TextStyle, &AppContext) -> AnyElement),
211 }
212
213 pub struct MessageNotification {
214 message: NotificationMessage,
215 on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>) + Send + Sync>>,
216 click_message: Option<SharedString>,
217 }
218
219 impl EventEmitter<DismissEvent> for MessageNotification {}
220
221 impl MessageNotification {
222 pub fn new<S>(message: S) -> MessageNotification
223 where
224 S: Into<SharedString>,
225 {
226 Self {
227 message: NotificationMessage::Text(message.into()),
228 on_click: None,
229 click_message: None,
230 }
231 }
232
233 // not needed I think (only for the "new panel" toast, which is outdated now)
234 // pub fn new_element(
235 // message: fn(TextStyle, &AppContext) -> AnyElement,
236 // ) -> MessageNotification {
237 // Self {
238 // message: NotificationMessage::Element(message),
239 // on_click: None,
240 // click_message: None,
241 // }
242 // }
243
244 pub fn with_click_message<S>(mut self, message: S) -> Self
245 where
246 S: Into<SharedString>,
247 {
248 self.click_message = Some(message.into());
249 self
250 }
251
252 pub fn on_click<F>(mut self, on_click: F) -> Self
253 where
254 F: 'static + Send + Sync + Fn(&mut ViewContext<Self>),
255 {
256 self.on_click = Some(Arc::new(on_click));
257 self
258 }
259
260 pub fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
261 cx.emit(DismissEvent);
262 }
263 }
264
265 impl Render for MessageNotification {
266 type Element = Div;
267
268 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
269 v_stack()
270 .elevation_3(cx)
271 .p_4()
272 .child(
273 h_stack()
274 .justify_between()
275 .child(div().max_w_80().child(match &self.message {
276 NotificationMessage::Text(text) => Label::new(text.clone()),
277 NotificationMessage::Element(element) => {
278 todo!()
279 }
280 }))
281 .child(
282 div()
283 .id("cancel")
284 .child(IconElement::new(Icon::Close))
285 .cursor_pointer()
286 .on_click(cx.listener(|this, event, cx| this.dismiss(cx))),
287 ),
288 )
289 .children(self.click_message.iter().map(|message| {
290 Button::new(message.clone()).on_click(cx.listener(|this, _, cx| {
291 if let Some(on_click) = this.on_click.as_ref() {
292 (on_click)(cx)
293 };
294 this.dismiss(cx)
295 }))
296 }))
297 }
298 }
299 // todo!()
300 // impl View for MessageNotification {
301 // fn ui_name() -> &'static str {
302 // "MessageNotification"
303 // }
304
305 // fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> gpui::AnyElement<Self> {
306 // let theme = theme2::current(cx).clone();
307 // let theme = &theme.simple_message_notification;
308
309 // enum MessageNotificationTag {}
310
311 // let click_message = self.click_message.clone();
312 // let message = match &self.message {
313 // NotificationMessage::Text(text) => {
314 // Text::new(text.to_owned(), theme.message.text.clone()).into_any()
315 // }
316 // NotificationMessage::Element(e) => e(theme.message.text.clone(), cx),
317 // };
318 // let on_click = self.on_click.clone();
319 // let has_click_action = on_click.is_some();
320
321 // Flex::column()
322 // .with_child(
323 // Flex::row()
324 // .with_child(
325 // message
326 // .contained()
327 // .with_style(theme.message.container)
328 // .aligned()
329 // .top()
330 // .left()
331 // .flex(1., true),
332 // )
333 // .with_child(
334 // MouseEventHandler::new::<Cancel, _>(0, cx, |state, _| {
335 // let style = theme.dismiss_button.style_for(state);
336 // Svg::new("icons/x.svg")
337 // .with_color(style.color)
338 // .constrained()
339 // .with_width(style.icon_width)
340 // .aligned()
341 // .contained()
342 // .with_style(style.container)
343 // .constrained()
344 // .with_width(style.button_width)
345 // .with_height(style.button_width)
346 // })
347 // .with_padding(Padding::uniform(5.))
348 // .on_click(MouseButton::Left, move |_, this, cx| {
349 // this.dismiss(&Default::default(), cx);
350 // })
351 // .with_cursor_style(CursorStyle::PointingHand)
352 // .aligned()
353 // .constrained()
354 // .with_height(cx.font_cache().line_height(theme.message.text.font_size))
355 // .aligned()
356 // .top()
357 // .flex_float(),
358 // ),
359 // )
360 // .with_children({
361 // click_message
362 // .map(|click_message| {
363 // MouseEventHandler::new::<MessageNotificationTag, _>(
364 // 0,
365 // cx,
366 // |state, _| {
367 // let style = theme.action_message.style_for(state);
368
369 // Flex::row()
370 // .with_child(
371 // Text::new(click_message, style.text.clone())
372 // .contained()
373 // .with_style(style.container),
374 // )
375 // .contained()
376 // },
377 // )
378 // .on_click(MouseButton::Left, move |_, this, cx| {
379 // if let Some(on_click) = on_click.as_ref() {
380 // on_click(cx);
381 // this.dismiss(&Default::default(), cx);
382 // }
383 // })
384 // // Since we're not using a proper overlay, we have to capture these extra events
385 // .on_down(MouseButton::Left, |_, _, _| {})
386 // .on_up(MouseButton::Left, |_, _, _| {})
387 // .with_cursor_style(if has_click_action {
388 // CursorStyle::PointingHand
389 // } else {
390 // CursorStyle::Arrow
391 // })
392 // })
393 // .into_iter()
394 // })
395 // .into_any()
396 // }
397 // }
398}
399
400pub trait NotifyResultExt {
401 type Ok;
402
403 fn notify_err(
404 self,
405 workspace: &mut Workspace,
406 cx: &mut ViewContext<Workspace>,
407 ) -> Option<Self::Ok>;
408
409 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
410}
411
412impl<T, E> NotifyResultExt for Result<T, E>
413where
414 E: std::fmt::Debug,
415{
416 type Ok = T;
417
418 fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
419 match self {
420 Ok(value) => Some(value),
421 Err(err) => {
422 log::error!("TODO {err:?}");
423 workspace.show_error(&err, cx);
424 None
425 }
426 }
427 }
428
429 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
430 match self {
431 Ok(value) => Some(value),
432 Err(err) => {
433 log::error!("TODO {err:?}");
434 cx.update(|view, cx| {
435 if let Ok(workspace) = view.downcast::<Workspace>() {
436 workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
437 }
438 })
439 .ok();
440 None
441 }
442 }
443 }
444}