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                #[cfg(target_os = "macos")]
151                {
152                    util::open(&open_action.0);
153                }
154            },
155        )
156    }
157
158    pub struct MessageNotification {
159        message: String,
160        click_action: Option<Box<dyn Action>>,
161        click_message: Option<String>,
162    }
163
164    pub enum MessageNotificationEvent {
165        Dismiss,
166    }
167
168    impl Entity for MessageNotification {
169        type Event = MessageNotificationEvent;
170    }
171
172    impl MessageNotification {
173        pub fn new_message<S: AsRef<str>>(message: S) -> MessageNotification {
174            Self {
175                message: message.as_ref().to_string(),
176                click_action: None,
177                click_message: None,
178            }
179        }
180
181        pub fn new<S1: AsRef<str>, A: Action, S2: AsRef<str>>(
182            message: S1,
183            click_action: A,
184            click_message: S2,
185        ) -> Self {
186            Self {
187                message: message.as_ref().to_string(),
188                click_action: Some(Box::new(click_action) as Box<dyn Action>),
189                click_message: Some(click_message.as_ref().to_string()),
190            }
191        }
192
193        pub fn dismiss(&mut self, _: &CancelMessageNotification, cx: &mut ViewContext<Self>) {
194            cx.emit(MessageNotificationEvent::Dismiss);
195        }
196    }
197
198    impl View for MessageNotification {
199        fn ui_name() -> &'static str {
200            "MessageNotification"
201        }
202
203        fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> gpui::ElementBox {
204            let theme = cx.global::<Settings>().theme.clone();
205            let theme = &theme.simple_message_notification;
206
207            enum MessageNotificationTag {}
208
209            let click_action = self
210                .click_action
211                .as_ref()
212                .map(|action| action.boxed_clone());
213            let click_message = self.click_message.as_ref().map(|message| message.clone());
214            let message = self.message.clone();
215
216            MouseEventHandler::<MessageNotificationTag>::new(0, cx, |state, cx| {
217                Flex::column()
218                    .with_child(
219                        Flex::row()
220                            .with_child(
221                                Text::new(message, theme.message.text.clone())
222                                    .contained()
223                                    .with_style(theme.message.container)
224                                    .aligned()
225                                    .top()
226                                    .left()
227                                    .flex(1., true)
228                                    .boxed(),
229                            )
230                            .with_child(
231                                MouseEventHandler::<Cancel>::new(0, cx, |state, _| {
232                                    let style = theme.dismiss_button.style_for(state, false);
233                                    Svg::new("icons/x_mark_8.svg")
234                                        .with_color(style.color)
235                                        .constrained()
236                                        .with_width(style.icon_width)
237                                        .aligned()
238                                        .contained()
239                                        .with_style(style.container)
240                                        .constrained()
241                                        .with_width(style.button_width)
242                                        .with_height(style.button_width)
243                                        .boxed()
244                                })
245                                .with_padding(Padding::uniform(5.))
246                                .on_click(MouseButton::Left, move |_, cx| {
247                                    cx.dispatch_action(CancelMessageNotification)
248                                })
249                                .aligned()
250                                .constrained()
251                                .with_height(
252                                    cx.font_cache().line_height(theme.message.text.font_size),
253                                )
254                                .aligned()
255                                .top()
256                                .flex_float()
257                                .boxed(),
258                            )
259                            .boxed(),
260                    )
261                    .with_children({
262                        let style = theme.action_message.style_for(state, false);
263                        if let Some(click_message) = click_message {
264                            Some(
265                                Text::new(click_message, style.text.clone())
266                                    .contained()
267                                    .with_style(style.container)
268                                    .boxed(),
269                            )
270                        } else {
271                            None
272                        }
273                        .into_iter()
274                    })
275                    .contained()
276                    .boxed()
277            })
278            .with_cursor_style(CursorStyle::PointingHand)
279            .on_click(MouseButton::Left, move |_, cx| {
280                if let Some(click_action) = click_action.as_ref() {
281                    cx.dispatch_any_action(click_action.boxed_clone())
282                }
283            })
284            .boxed()
285        }
286    }
287
288    impl Notification for MessageNotification {
289        fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool {
290            match event {
291                MessageNotificationEvent::Dismiss => true,
292            }
293        }
294    }
295}
296
297pub trait NotifyResultExt {
298    type Ok;
299
300    fn notify_err(
301        self,
302        workspace: &mut Workspace,
303        cx: &mut ViewContext<Workspace>,
304    ) -> Option<Self::Ok>;
305}
306
307impl<T, E> NotifyResultExt for Result<T, E>
308where
309    E: std::fmt::Debug,
310{
311    type Ok = T;
312
313    fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
314        match self {
315            Ok(value) => Some(value),
316            Err(err) => {
317                workspace.show_notification(0, cx, |cx| {
318                    cx.add_view(|_cx| {
319                        simple_message_notification::MessageNotification::new_message(format!(
320                            "Error: {:?}",
321                            err,
322                        ))
323                    })
324                });
325
326                None
327            }
328        }
329    }
330}