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(¬ification, 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 std::borrow::Cow;
126
127 use gpui::{
128 actions,
129 elements::{Flex, MouseEventHandler, Padding, ParentElement, Svg, Text},
130 impl_actions, Action, CursorStyle, Element, Entity, MouseButton, MutableAppContext, View,
131 ViewContext,
132 };
133 use menu::Cancel;
134 use serde::Deserialize;
135 use settings::Settings;
136
137 use crate::Workspace;
138
139 use super::Notification;
140
141 actions!(message_notifications, [CancelMessageNotification]);
142
143 #[derive(Clone, Default, Deserialize, PartialEq)]
144 pub struct OsOpen(pub String);
145
146 impl_actions!(message_notifications, [OsOpen]);
147
148 pub fn init(cx: &mut MutableAppContext) {
149 cx.add_action(MessageNotification::dismiss);
150 cx.add_action(
151 |_workspace: &mut Workspace, open_action: &OsOpen, cx: &mut ViewContext<Workspace>| {
152 cx.platform().open_url(open_action.0.as_str());
153 },
154 )
155 }
156
157 pub struct MessageNotification {
158 message: Cow<'static, str>,
159 click_action: Option<Box<dyn Action>>,
160 click_message: Option<Cow<'static, str>>,
161 }
162
163 pub enum MessageNotificationEvent {
164 Dismiss,
165 }
166
167 impl Entity for MessageNotification {
168 type Event = MessageNotificationEvent;
169 }
170
171 impl MessageNotification {
172 pub fn new_message<S: Into<Cow<'static, str>>>(message: S) -> MessageNotification {
173 Self {
174 message: message.into(),
175 click_action: None,
176 click_message: None,
177 }
178 }
179
180 pub fn new<S1: Into<Cow<'static, str>>, A: Action, S2: Into<Cow<'static, str>>>(
181 message: S1,
182 click_action: A,
183 click_message: S2,
184 ) -> Self {
185 Self {
186 message: message.into(),
187 click_action: Some(Box::new(click_action) as Box<dyn Action>),
188 click_message: Some(click_message.into()),
189 }
190 }
191
192 pub fn dismiss(&mut self, _: &CancelMessageNotification, cx: &mut ViewContext<Self>) {
193 cx.emit(MessageNotificationEvent::Dismiss);
194 }
195 }
196
197 impl View for MessageNotification {
198 fn ui_name() -> &'static str {
199 "MessageNotification"
200 }
201
202 fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> gpui::ElementBox {
203 let theme = cx.global::<Settings>().theme.clone();
204 let theme = &theme.simple_message_notification;
205
206 enum MessageNotificationTag {}
207
208 let click_action = self
209 .click_action
210 .as_ref()
211 .map(|action| action.boxed_clone());
212 let click_message = self.click_message.as_ref().map(|message| message.clone());
213 let message = self.message.clone();
214
215 let has_click_action = click_action.is_some();
216
217 MouseEventHandler::<MessageNotificationTag>::new(0, cx, |state, cx| {
218 Flex::column()
219 .with_child(
220 Flex::row()
221 .with_child(
222 Text::new(message, theme.message.text.clone())
223 .contained()
224 .with_style(theme.message.container)
225 .aligned()
226 .top()
227 .left()
228 .flex(1., true)
229 .boxed(),
230 )
231 .with_child(
232 MouseEventHandler::<Cancel>::new(0, cx, |state, _| {
233 let style = theme.dismiss_button.style_for(state, false);
234 Svg::new("icons/x_mark_8.svg")
235 .with_color(style.color)
236 .constrained()
237 .with_width(style.icon_width)
238 .aligned()
239 .contained()
240 .with_style(style.container)
241 .constrained()
242 .with_width(style.button_width)
243 .with_height(style.button_width)
244 .boxed()
245 })
246 .with_padding(Padding::uniform(5.))
247 .on_click(MouseButton::Left, move |_, cx| {
248 cx.dispatch_action(CancelMessageNotification)
249 })
250 .with_cursor_style(CursorStyle::PointingHand)
251 .aligned()
252 .constrained()
253 .with_height(
254 cx.font_cache().line_height(theme.message.text.font_size),
255 )
256 .aligned()
257 .top()
258 .flex_float()
259 .boxed(),
260 )
261 .boxed(),
262 )
263 .with_children({
264 let style = theme.action_message.style_for(state, false);
265 if let Some(click_message) = click_message {
266 Some(
267 Text::new(click_message, style.text.clone())
268 .contained()
269 .with_style(style.container)
270 .boxed(),
271 )
272 } else {
273 None
274 }
275 .into_iter()
276 })
277 .contained()
278 .boxed()
279 })
280 // Since we're not using a proper overlay, we have to capture these extra events
281 .on_down(MouseButton::Left, |_, _| {})
282 .on_up(MouseButton::Left, |_, _| {})
283 .on_click(MouseButton::Left, move |_, cx| {
284 if let Some(click_action) = click_action.as_ref() {
285 cx.dispatch_any_action(click_action.boxed_clone())
286 }
287 })
288 .with_cursor_style(if has_click_action {
289 CursorStyle::PointingHand
290 } else {
291 CursorStyle::Arrow
292 })
293 .boxed()
294 }
295 }
296
297 impl Notification for MessageNotification {
298 fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool {
299 match event {
300 MessageNotificationEvent::Dismiss => true,
301 }
302 }
303 }
304}
305
306pub trait NotifyResultExt {
307 type Ok;
308
309 fn notify_err(
310 self,
311 workspace: &mut Workspace,
312 cx: &mut ViewContext<Workspace>,
313 ) -> Option<Self::Ok>;
314}
315
316impl<T, E> NotifyResultExt for Result<T, E>
317where
318 E: std::fmt::Debug,
319{
320 type Ok = T;
321
322 fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
323 match self {
324 Ok(value) => Some(value),
325 Err(err) => {
326 workspace.show_notification(0, cx, |cx| {
327 cx.add_view(|_cx| {
328 simple_message_notification::MessageNotification::new_message(format!(
329 "Error: {:?}",
330 err,
331 ))
332 })
333 });
334
335 None
336 }
337 }
338 }
339}