notifications.rs

  1use std::{any::TypeId, ops::DerefMut};
  2
  3use collections::HashSet;
  4use gpui::{AnyViewHandle, Entity, MutableAppContext, View, ViewContext, ViewHandle};
  5
  6use crate::Workspace;
  7
  8pub fn init(cx: &mut MutableAppContext) {
  9    cx.set_global(NotificationTracker::new());
 10    simple_message_notification::init(cx);
 11}
 12
 13pub trait Notification: View {
 14    fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool;
 15}
 16
 17pub trait NotificationHandle {
 18    fn id(&self) -> usize;
 19    fn to_any(&self) -> AnyViewHandle;
 20}
 21
 22impl<T: Notification> NotificationHandle for ViewHandle<T> {
 23    fn id(&self) -> usize {
 24        self.id()
 25    }
 26
 27    fn to_any(&self) -> AnyViewHandle {
 28        self.into()
 29    }
 30}
 31
 32impl From<&dyn NotificationHandle> for AnyViewHandle {
 33    fn from(val: &dyn NotificationHandle) -> Self {
 34        val.to_any()
 35    }
 36}
 37
 38struct NotificationTracker {
 39    notifications_sent: HashSet<TypeId>,
 40}
 41
 42impl std::ops::Deref for NotificationTracker {
 43    type Target = HashSet<TypeId>;
 44
 45    fn deref(&self) -> &Self::Target {
 46        &self.notifications_sent
 47    }
 48}
 49
 50impl DerefMut for NotificationTracker {
 51    fn deref_mut(&mut self) -> &mut Self::Target {
 52        &mut self.notifications_sent
 53    }
 54}
 55
 56impl NotificationTracker {
 57    fn new() -> Self {
 58        Self {
 59            notifications_sent: HashSet::default(),
 60        }
 61    }
 62}
 63
 64impl Workspace {
 65    pub fn show_notification_once<V: Notification>(
 66        &mut self,
 67        id: usize,
 68        cx: &mut ViewContext<Self>,
 69        build_notification: impl FnOnce(&mut ViewContext<Self>) -> ViewHandle<V>,
 70    ) {
 71        if !cx
 72            .global::<NotificationTracker>()
 73            .contains(&TypeId::of::<V>())
 74        {
 75            cx.update_global::<NotificationTracker, _, _>(|tracker, _| {
 76                tracker.insert(TypeId::of::<V>())
 77            });
 78
 79            self.show_notification::<V>(id, cx, build_notification)
 80        }
 81    }
 82
 83    pub fn show_notification<V: Notification>(
 84        &mut self,
 85        id: usize,
 86        cx: &mut ViewContext<Self>,
 87        build_notification: impl FnOnce(&mut ViewContext<Self>) -> ViewHandle<V>,
 88    ) {
 89        let type_id = TypeId::of::<V>();
 90        if self
 91            .notifications
 92            .iter()
 93            .all(|(existing_type_id, existing_id, _)| {
 94                (*existing_type_id, *existing_id) != (type_id, id)
 95            })
 96        {
 97            let notification = build_notification(cx);
 98            cx.subscribe(&notification, move |this, handle, event, cx| {
 99                if handle.read(cx).should_dismiss_notification_on_event(event) {
100                    this.dismiss_notification(type_id, id, cx);
101                }
102            })
103            .detach();
104            self.notifications
105                .push((type_id, id, Box::new(notification)));
106            cx.notify();
107        }
108    }
109
110    fn dismiss_notification(&mut self, type_id: TypeId, id: usize, cx: &mut ViewContext<Self>) {
111        self.notifications
112            .retain(|(existing_type_id, existing_id, _)| {
113                if (*existing_type_id, *existing_id) == (type_id, id) {
114                    cx.notify();
115                    false
116                } else {
117                    true
118                }
119            });
120    }
121}
122
123pub mod simple_message_notification {
124
125    use gpui::{
126        actions,
127        elements::{Flex, MouseEventHandler, Padding, ParentElement, Svg, Text},
128        impl_actions, Action, CursorStyle, Element, Entity, MouseButton, MutableAppContext, View,
129        ViewContext,
130    };
131    use menu::Cancel;
132    use serde::Deserialize;
133    use settings::Settings;
134
135    use crate::Workspace;
136
137    use super::Notification;
138
139    actions!(message_notifications, [CancelMessageNotification]);
140
141    #[derive(Clone, Default, Deserialize, PartialEq)]
142    pub struct OsOpen(pub String);
143
144    impl_actions!(message_notifications, [OsOpen]);
145
146    pub fn init(cx: &mut MutableAppContext) {
147        cx.add_action(MessageNotification::dismiss);
148        cx.add_action(
149            |_workspace: &mut Workspace, open_action: &OsOpen, cx: &mut ViewContext<Workspace>| {
150                cx.platform().open_url(open_action.0.as_str());
151            },
152        )
153    }
154
155    pub struct MessageNotification {
156        message: String,
157        click_action: Option<Box<dyn Action>>,
158        click_message: Option<String>,
159    }
160
161    pub enum MessageNotificationEvent {
162        Dismiss,
163    }
164
165    impl Entity for MessageNotification {
166        type Event = MessageNotificationEvent;
167    }
168
169    impl MessageNotification {
170        pub fn new_message<S: AsRef<str>>(message: S) -> MessageNotification {
171            Self {
172                message: message.as_ref().to_string(),
173                click_action: None,
174                click_message: None,
175            }
176        }
177
178        pub fn new<S1: AsRef<str>, A: Action, S2: AsRef<str>>(
179            message: S1,
180            click_action: A,
181            click_message: S2,
182        ) -> Self {
183            Self {
184                message: message.as_ref().to_string(),
185                click_action: Some(Box::new(click_action) as Box<dyn Action>),
186                click_message: Some(click_message.as_ref().to_string()),
187            }
188        }
189
190        pub fn dismiss(&mut self, _: &CancelMessageNotification, cx: &mut ViewContext<Self>) {
191            cx.emit(MessageNotificationEvent::Dismiss);
192        }
193    }
194
195    impl View for MessageNotification {
196        fn ui_name() -> &'static str {
197            "MessageNotification"
198        }
199
200        fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> gpui::ElementBox {
201            let theme = cx.global::<Settings>().theme.clone();
202            let theme = &theme.simple_message_notification;
203
204            enum MessageNotificationTag {}
205
206            let click_action = self
207                .click_action
208                .as_ref()
209                .map(|action| action.boxed_clone());
210            let click_message = self.click_message.as_ref().map(|message| message.clone());
211            let message = self.message.clone();
212
213            MouseEventHandler::<MessageNotificationTag>::new(0, cx, |state, cx| {
214                Flex::column()
215                    .with_child(
216                        Flex::row()
217                            .with_child(
218                                Text::new(message, theme.message.text.clone())
219                                    .contained()
220                                    .with_style(theme.message.container)
221                                    .aligned()
222                                    .top()
223                                    .left()
224                                    .flex(1., true)
225                                    .boxed(),
226                            )
227                            .with_child(
228                                MouseEventHandler::<Cancel>::new(0, cx, |state, _| {
229                                    let style = theme.dismiss_button.style_for(state, false);
230                                    Svg::new("icons/x_mark_8.svg")
231                                        .with_color(style.color)
232                                        .constrained()
233                                        .with_width(style.icon_width)
234                                        .aligned()
235                                        .contained()
236                                        .with_style(style.container)
237                                        .constrained()
238                                        .with_width(style.button_width)
239                                        .with_height(style.button_width)
240                                        .boxed()
241                                })
242                                .with_padding(Padding::uniform(5.))
243                                .on_click(MouseButton::Left, move |_, cx| {
244                                    cx.dispatch_action(CancelMessageNotification)
245                                })
246                                .aligned()
247                                .constrained()
248                                .with_height(
249                                    cx.font_cache().line_height(theme.message.text.font_size),
250                                )
251                                .aligned()
252                                .top()
253                                .flex_float()
254                                .boxed(),
255                            )
256                            .boxed(),
257                    )
258                    .with_children({
259                        let style = theme.action_message.style_for(state, false);
260                        if let Some(click_message) = click_message {
261                            Some(
262                                Text::new(click_message, style.text.clone())
263                                    .contained()
264                                    .with_style(style.container)
265                                    .boxed(),
266                            )
267                        } else {
268                            None
269                        }
270                        .into_iter()
271                    })
272                    .contained()
273                    .boxed()
274            })
275            .with_cursor_style(CursorStyle::PointingHand)
276            .on_click(MouseButton::Left, move |_, cx| {
277                if let Some(click_action) = click_action.as_ref() {
278                    cx.dispatch_any_action(click_action.boxed_clone())
279                }
280            })
281            .boxed()
282        }
283    }
284
285    impl Notification for MessageNotification {
286        fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool {
287            match event {
288                MessageNotificationEvent::Dismiss => true,
289            }
290        }
291    }
292}
293
294pub trait NotifyResultExt {
295    type Ok;
296
297    fn notify_err(
298        self,
299        workspace: &mut Workspace,
300        cx: &mut ViewContext<Workspace>,
301    ) -> Option<Self::Ok>;
302}
303
304impl<T, E> NotifyResultExt for Result<T, E>
305where
306    E: std::fmt::Debug,
307{
308    type Ok = T;
309
310    fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
311        match self {
312            Ok(value) => Some(value),
313            Err(err) => {
314                workspace.show_notification(0, cx, |cx| {
315                    cx.add_view(|_cx| {
316                        simple_message_notification::MessageNotification::new_message(format!(
317                            "Error: {:?}",
318                            err,
319                        ))
320                    })
321                });
322
323                None
324            }
325        }
326    }
327}