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 use std::process::Command;
125
126 use gpui::{
127 actions,
128 elements::{Flex, MouseEventHandler, Padding, ParentElement, Svg, Text},
129 impl_actions, Action, CursorStyle, Element, Entity, MouseButton, MutableAppContext, View,
130 ViewContext,
131 };
132 use menu::Cancel;
133 use serde::Deserialize;
134 use settings::Settings;
135
136 use crate::Workspace;
137
138 use super::Notification;
139
140 actions!(message_notifications, [CancelMessageNotification]);
141
142 #[derive(Clone, Default, Deserialize, PartialEq)]
143 pub struct OsOpen(pub String);
144
145 impl_actions!(message_notifications, [OsOpen]);
146
147 pub fn init(cx: &mut MutableAppContext) {
148 cx.add_action(MessageNotification::dismiss);
149 cx.add_action(
150 |_workspace: &mut Workspace, open_action: &OsOpen, _cx: &mut ViewContext<Workspace>| {
151 #[cfg(target_os = "macos")]
152 {
153 let mut command = Command::new("open");
154 command.arg(open_action.0.clone());
155
156 command.spawn().ok();
157 }
158 },
159 )
160 }
161
162 pub struct MessageNotification {
163 message: String,
164 click_action: Box<dyn Action>,
165 click_message: String,
166 }
167
168 pub enum MessageNotificationEvent {
169 Dismiss,
170 }
171
172 impl Entity for MessageNotification {
173 type Event = MessageNotificationEvent;
174 }
175
176 impl MessageNotification {
177 pub fn new<S1: AsRef<str>, A: Action, S2: AsRef<str>>(
178 message: S1,
179 click_action: A,
180 click_message: S2,
181 ) -> Self {
182 Self {
183 message: message.as_ref().to_string(),
184 click_action: Box::new(click_action) as Box<dyn Action>,
185 click_message: click_message.as_ref().to_string(),
186 }
187 }
188
189 pub fn dismiss(&mut self, _: &CancelMessageNotification, cx: &mut ViewContext<Self>) {
190 cx.emit(MessageNotificationEvent::Dismiss);
191 }
192 }
193
194 impl View for MessageNotification {
195 fn ui_name() -> &'static str {
196 "MessageNotification"
197 }
198
199 fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> gpui::ElementBox {
200 let theme = cx.global::<Settings>().theme.clone();
201 let theme = &theme.update_notification;
202
203 enum MessageNotificationTag {}
204
205 let click_action = self.click_action.boxed_clone();
206 let click_message = self.click_message.clone();
207 let message = self.message.clone();
208
209 MouseEventHandler::<MessageNotificationTag>::new(0, cx, |state, cx| {
210 Flex::column()
211 .with_child(
212 Flex::row()
213 .with_child(
214 Text::new(message, theme.message.text.clone())
215 .contained()
216 .with_style(theme.message.container)
217 .aligned()
218 .top()
219 .left()
220 .flex(1., true)
221 .boxed(),
222 )
223 .with_child(
224 MouseEventHandler::<Cancel>::new(0, cx, |state, _| {
225 let style = theme.dismiss_button.style_for(state, false);
226 Svg::new("icons/x_mark_8.svg")
227 .with_color(style.color)
228 .constrained()
229 .with_width(style.icon_width)
230 .aligned()
231 .contained()
232 .with_style(style.container)
233 .constrained()
234 .with_width(style.button_width)
235 .with_height(style.button_width)
236 .boxed()
237 })
238 .with_padding(Padding::uniform(5.))
239 .on_click(MouseButton::Left, move |_, cx| {
240 cx.dispatch_action(CancelMessageNotification)
241 })
242 .aligned()
243 .constrained()
244 .with_height(
245 cx.font_cache().line_height(theme.message.text.font_size),
246 )
247 .aligned()
248 .top()
249 .flex_float()
250 .boxed(),
251 )
252 .boxed(),
253 )
254 .with_child({
255 let style = theme.action_message.style_for(state, false);
256
257 Text::new(click_message, style.text.clone())
258 .contained()
259 .with_style(style.container)
260 .boxed()
261 })
262 .contained()
263 .boxed()
264 })
265 .with_cursor_style(CursorStyle::PointingHand)
266 .on_click(MouseButton::Left, move |_, cx| {
267 cx.dispatch_any_action(click_action.boxed_clone())
268 })
269 .boxed()
270 }
271 }
272
273 impl Notification for MessageNotification {
274 fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool {
275 match event {
276 MessageNotificationEvent::Dismiss => true,
277 }
278 }
279 }
280}