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::prelude::*;
185 use ui::{h_stack, v_stack, Button, Icon, IconElement, Label, StyledExt};
186
187 #[derive(Clone, Default, Deserialize, PartialEq)]
188 pub struct OsOpen(pub Cow<'static, str>);
189
190 impl OsOpen {
191 pub fn new<I: Into<Cow<'static, str>>>(url: I) -> Self {
192 OsOpen(url.into())
193 }
194 }
195
196 // todo!()
197 // impl_actions!(message_notifications, [OsOpen]);
198 //
199 // todo!()
200 // pub fn init(cx: &mut AppContext) {
201 // cx.add_action(MessageNotification::dismiss);
202 // cx.add_action(
203 // |_workspace: &mut Workspace, open_action: &OsOpen, cx: &mut ViewContext<Workspace>| {
204 // cx.platform().open_url(open_action.0.as_ref());
205 // },
206 // )
207 // }
208
209 enum NotificationMessage {
210 Text(SharedString),
211 Element(fn(TextStyle, &AppContext) -> AnyElement),
212 }
213
214 pub struct MessageNotification {
215 message: NotificationMessage,
216 on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>) + Send + Sync>>,
217 click_message: Option<SharedString>,
218 }
219
220 impl EventEmitter<DismissEvent> for MessageNotification {}
221
222 impl MessageNotification {
223 pub fn new<S>(message: S) -> MessageNotification
224 where
225 S: Into<SharedString>,
226 {
227 Self {
228 message: NotificationMessage::Text(message.into()),
229 on_click: None,
230 click_message: None,
231 }
232 }
233
234 // not needed I think (only for the "new panel" toast, which is outdated now)
235 // pub fn new_element(
236 // message: fn(TextStyle, &AppContext) -> AnyElement,
237 // ) -> MessageNotification {
238 // Self {
239 // message: NotificationMessage::Element(message),
240 // on_click: None,
241 // click_message: None,
242 // }
243 // }
244
245 pub fn with_click_message<S>(mut self, message: S) -> Self
246 where
247 S: Into<SharedString>,
248 {
249 self.click_message = Some(message.into());
250 self
251 }
252
253 pub fn on_click<F>(mut self, on_click: F) -> Self
254 where
255 F: 'static + Send + Sync + Fn(&mut ViewContext<Self>),
256 {
257 self.on_click = Some(Arc::new(on_click));
258 self
259 }
260
261 pub fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
262 cx.emit(DismissEvent);
263 }
264 }
265
266 impl Render for MessageNotification {
267 type Element = Div;
268
269 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
270 v_stack()
271 .elevation_3(cx)
272 .p_4()
273 .child(
274 h_stack()
275 .justify_between()
276 .child(div().max_w_80().child(match &self.message {
277 NotificationMessage::Text(text) => Label::new(text.clone()),
278 NotificationMessage::Element(element) => {
279 todo!()
280 }
281 }))
282 .child(
283 div()
284 .id("cancel")
285 .child(IconElement::new(Icon::Close))
286 .cursor_pointer()
287 .on_click(cx.listener(|this, event, cx| this.dismiss(cx))),
288 ),
289 )
290 .children(self.click_message.iter().map(|message| {
291 Button::new(message.clone(), message.clone()).on_click(cx.listener(
292 |this, _, cx| {
293 if let Some(on_click) = this.on_click.as_ref() {
294 (on_click)(cx)
295 };
296 this.dismiss(cx)
297 },
298 ))
299 }))
300 }
301 }
302 // todo!()
303 // impl View for MessageNotification {
304 // fn ui_name() -> &'static str {
305 // "MessageNotification"
306 // }
307
308 // fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> gpui::AnyElement<Self> {
309 // let theme = theme2::current(cx).clone();
310 // let theme = &theme.simple_message_notification;
311
312 // enum MessageNotificationTag {}
313
314 // let click_message = self.click_message.clone();
315 // let message = match &self.message {
316 // NotificationMessage::Text(text) => {
317 // Text::new(text.to_owned(), theme.message.text.clone()).into_any()
318 // }
319 // NotificationMessage::Element(e) => e(theme.message.text.clone(), cx),
320 // };
321 // let on_click = self.on_click.clone();
322 // let has_click_action = on_click.is_some();
323
324 // Flex::column()
325 // .with_child(
326 // Flex::row()
327 // .with_child(
328 // message
329 // .contained()
330 // .with_style(theme.message.container)
331 // .aligned()
332 // .top()
333 // .left()
334 // .flex(1., true),
335 // )
336 // .with_child(
337 // MouseEventHandler::new::<Cancel, _>(0, cx, |state, _| {
338 // let style = theme.dismiss_button.style_for(state);
339 // Svg::new("icons/x.svg")
340 // .with_color(style.color)
341 // .constrained()
342 // .with_width(style.icon_width)
343 // .aligned()
344 // .contained()
345 // .with_style(style.container)
346 // .constrained()
347 // .with_width(style.button_width)
348 // .with_height(style.button_width)
349 // })
350 // .with_padding(Padding::uniform(5.))
351 // .on_click(MouseButton::Left, move |_, this, cx| {
352 // this.dismiss(&Default::default(), cx);
353 // })
354 // .with_cursor_style(CursorStyle::PointingHand)
355 // .aligned()
356 // .constrained()
357 // .with_height(cx.font_cache().line_height(theme.message.text.font_size))
358 // .aligned()
359 // .top()
360 // .flex_float(),
361 // ),
362 // )
363 // .with_children({
364 // click_message
365 // .map(|click_message| {
366 // MouseEventHandler::new::<MessageNotificationTag, _>(
367 // 0,
368 // cx,
369 // |state, _| {
370 // let style = theme.action_message.style_for(state);
371
372 // Flex::row()
373 // .with_child(
374 // Text::new(click_message, style.text.clone())
375 // .contained()
376 // .with_style(style.container),
377 // )
378 // .contained()
379 // },
380 // )
381 // .on_click(MouseButton::Left, move |_, this, cx| {
382 // if let Some(on_click) = on_click.as_ref() {
383 // on_click(cx);
384 // this.dismiss(&Default::default(), cx);
385 // }
386 // })
387 // // Since we're not using a proper overlay, we have to capture these extra events
388 // .on_down(MouseButton::Left, |_, _, _| {})
389 // .on_up(MouseButton::Left, |_, _, _| {})
390 // .with_cursor_style(if has_click_action {
391 // CursorStyle::PointingHand
392 // } else {
393 // CursorStyle::Arrow
394 // })
395 // })
396 // .into_iter()
397 // })
398 // .into_any()
399 // }
400 // }
401}
402
403pub trait NotifyResultExt {
404 type Ok;
405
406 fn notify_err(
407 self,
408 workspace: &mut Workspace,
409 cx: &mut ViewContext<Workspace>,
410 ) -> Option<Self::Ok>;
411
412 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
413}
414
415impl<T, E> NotifyResultExt for Result<T, E>
416where
417 E: std::fmt::Debug,
418{
419 type Ok = T;
420
421 fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
422 match self {
423 Ok(value) => Some(value),
424 Err(err) => {
425 log::error!("TODO {err:?}");
426 workspace.show_error(&err, cx);
427 None
428 }
429 }
430 }
431
432 fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<T> {
433 match self {
434 Ok(value) => Some(value),
435 Err(err) => {
436 log::error!("TODO {err:?}");
437 cx.update(|view, cx| {
438 if let Ok(workspace) = view.downcast::<Workspace>() {
439 workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
440 }
441 })
442 .ok();
443 None
444 }
445 }
446 }
447}