Debian Codegraph @

src/macos/nsusernotifications.rs

raw symbols SCIP
1 use crate::{error::*, notification::Notification};
2
3 pub use mac_notification_sys::error::{ApplicationError, Error as MacOsError, NotificationError};
4
5 /// A handle to a shown notification (**`NSUserNotificationCenter`** path).
6 ///
7 /// This stack is deprecated on macOS 14+, but still works.
8 /// Enable the `preview-macos-un` feature to use the modern `UNUserNotificationCenter` path instead.
9 #[derive(Debug)]
10 pub struct NotificationHandle {
11 notification: Option<Notification>,
12 }
13
14 impl NotificationHandle {
15 /// Construct a handle wrapping the given notification.
16 // TODO: make private in 5.0
17 pub fn new(notification: Notification) -> Self {
18 Self {
19 notification: Some(notification),
20 }
21 }
22
23 /// Wait for the user to interact with the notification.
24 ///
25 /// The closure receives the action identifier as a `&str`.
26 /// The special value `"__closed"` is passed when the notification is
27 /// dismissed without activating any action.
28 ///
29 /// **Requires the main run loop to be running.** `NSUserNotificationCenter`
30 /// delivers delegate callbacks on the main thread; if nothing is pumping the
31 /// main run loop this call will block indefinitely.
32 pub fn wait_for_action<F>(mut self, invocation_closure: F)
33 where
34 F: FnOnce(&str),
35 {
36 log::trace!("wait_for_action");
37 // let n = build_mac_notification(&self.notification);
38 // n.wait_for_click(true);
39 let Some(notification) = self.notification.take() else {
40 return;
41 };
42 match send_mac_notification(
43 &notification,
44 Options {
45 asynchronous: false,
46 force_close_button: false,
47 delivery_date: None,
48 },
49 )
50 .unwrap_or(mac_notification_sys::NotificationResponse::None)
51 {
52 mac_notification_sys::NotificationResponse::ActionButton(ref label) => {
53 invocation_closure(label);
54 }
55 mac_notification_sys::NotificationResponse::Click => invocation_closure("default"),
56 mac_notification_sys::NotificationResponse::Reply(ref text) => {
57 invocation_closure(text);
58 }
59 mac_notification_sys::NotificationResponse::CloseButton(_)
60 | mac_notification_sys::NotificationResponse::None => invocation_closure("__closed"),
61 }
62 }
63
64 /// Waits for the user to act on the notification and then calls `handler`
65 /// with a typed [`NotificationResponse`](crate::NotificationResponse).
66 ///
67 /// This is the typed, forward-compatible replacement for
68 /// [`wait_for_action`](Self::wait_for_action).
69 ///
70 /// **Requires the main run loop to be running.** `NSUserNotificationCenter`
71 /// delivers delegate callbacks on the main thread; if nothing is pumping the
72 /// main run loop this call will block indefinitely.
73 pub fn wait_for_response(
74 mut self,
75 handler: impl crate::response::ResponseHandler,
76 ) -> Result<()> {
77 use crate::response::{CloseReason, NotificationResponse};
78
79 log::trace!("wait_for_response");
80 let Some(notification) = self.notification.take() else {
81 return Ok(());
82 };
83
84 let response = send_mac_notification(
85 &notification,
86 Options {
87 asynchronous: false,
88 force_close_button: false,
89 delivery_date: None,
90 },
91 )?;
92
93 use mac_notification_sys::NotificationResponse as MacResponse;
94 use NotificationResponse::*;
95
96 let response = match response {
97 MacResponse::ActionButton(label) => Action(label),
98 MacResponse::Click => Default,
99 MacResponse::Reply(text) => Reply(text),
100 MacResponse::CloseButton(_) => Closed(CloseReason::Dismissed),
101 MacResponse::None => Closed(CloseReason::Expired),
102 };
103
104 handler.call(&response);
105 Ok(())
106 }
107
108 /// Executes a closure after the notification has closed.
109 ///
110 /// **Requires the main run loop to be running.** `NSUserNotificationCenter`
111 /// delivers delegate callbacks on the main thread; if nothing is pumping the
112 /// main run loop this call will block indefinitely.
113 pub fn on_close<A>(mut self, handler: impl crate::response::CloseHandler<A>) {
114 let Some(notification) = self.notification.take() else {
115 return;
116 };
117
118 let response = send_mac_notification(
119 &notification,
120 Options {
121 asynchronous: false,
122 force_close_button: true,
123 delivery_date: None,
124 },
125 )
126 .unwrap_or(mac_notification_sys::NotificationResponse::None);
127 log::trace!("response: {response:?}");
128
129 match response {
130 mac_notification_sys::NotificationResponse::CloseButton(_) => {
131 handler.call(crate::CloseReason::Dismissed);
132 }
133 mac_notification_sys::NotificationResponse::None => {
134 handler.call(crate::CloseReason::Expired);
135 }
136 // user interacted — not a close event, handler not called
137 _ => {}
138 }
139 }
140 }
141
142 impl Drop for NotificationHandle {
143 fn drop(&mut self) {
144 log::trace!(
145 "not using handle, sending immediately: {:#?}",
146 self.notification
147 );
148 let Some(notification) = self.notification.take() else {
149 return;
150 };
151
152 send_mac_notification(
153 &notification,
154 Options {
155 asynchronous: true,
156 force_close_button: false,
157 delivery_date: None,
158 },
159 )
160 .ok();
161 }
162 }
163
164 struct Options {
165 asynchronous: bool,
166 force_close_button: bool,
167 delivery_date: Option<f64>,
168 }
169
170 fn send_mac_notification(
171 notification: &Notification,
172
173 Options {
174 asynchronous,
175 force_close_button,
176 delivery_date,
177 }: Options,
178 ) -> Result<mac_notification_sys::NotificationResponse> {
179 // actions is a flat [id, label, id, label, …] vec
180 let labels: Vec<&str> = notification
181 .actions
182 .chunks(2)
183 .filter_map(|pair| pair.get(1).map(|s| s.as_str()))
184 .collect();
185 // label -> id map for translating the response back
186 let label_to_id: std::collections::HashMap<&str, &str> = notification
187 .actions
188 .chunks(2)
189 .filter_map(|pair| match pair {
190 [id, label] => Some((label.as_str(), id.as_str())),
191 _ => None,
192 })
193 .collect();
194
195 let main_button = match labels.as_slice() {
196 [] => None,
197 [single] => Some(mac_notification_sys::MainButton::SingleAction(single)),
198 // "Options" is a neutral button title not present in labels, so no visual duplicate.
199 // Clicking the button directly (idx == LONG_MAX in ObjC) returns "Options"; we remap
200 // that below to the first action's id.
201 _ => Some(mac_notification_sys::MainButton::DropdownActions(
202 "Options", &labels,
203 )),
204 };
205
206 let mut n = mac_notification_sys::Notification::default();
207 n.title(notification.summary.as_str())
208 .message(&notification.body)
209 .maybe_subtitle(notification.subtitle.as_deref())
210 .maybe_sound(notification.sound_name.as_deref());
211 if let Some(ref btn) = main_button {
212 n.main_button(btn.clone());
213 }
214
215 if asynchronous {
216 log::trace!("Notification will be sent asynchronously");
217 } else {
218 log::trace!("Notification will be sent synchronously");
219 if force_close_button {
220 // on_close needs a close button to block until the user dismisses
221 n.close_button("Close");
222 }
223 }
224 n.asynchronous(asynchronous);
225
226 if let Some(ref image_path) = notification.path_to_image {
227 n.content_image(image_path);
228 }
229 if let Some(delivery_date) = delivery_date {
230 n.delivery_date(delivery_date);
231 }
232
233 let response = n.send().map_err(Into::<Error>::into)?;
234 // translate ActionButton(label) -> ActionButton(id)
235 let response = match response {
236 mac_notification_sys::NotificationResponse::ActionButton(ref label) => {
237 if let Some(&id) = label_to_id.get(label.as_str()) {
238 mac_notification_sys::NotificationResponse::ActionButton(id.to_owned())
239 } else if let Some(first_id) = notification.actions.first().map(|s| s.as_str()) {
240 // label didn't match (e.g. user clicked the dropdown button title directly);
241 // fall back to the first action
242 mac_notification_sys::NotificationResponse::ActionButton(first_id.to_owned())
243 } else {
244 response
245 }
246 }
247 other => other,
248 };
249 Ok(response)
250 }
251
252 pub(crate) fn show_notification(notification: &Notification) -> Result<NotificationHandle> {
253 Ok(
254 #[allow(deprecated)]
255 NotificationHandle::new(notification.clone()),
256 )
257 }
258
259 pub(crate) fn schedule_notification(
260 notification: &Notification,
261 delivery_date: f64,
262 ) -> Result<NotificationHandle> {
263 send_mac_notification(
264 notification,
265 Options {
266 asynchronous: true,
267 force_close_button: false,
268 delivery_date: Some(delivery_date),
269 },
270 )?;
271 Ok(
272 #[allow(deprecated)]
273 NotificationHandle { notification: None },
274 )
275 }