Debian Codegraph @

src/macos/unusernotifications.rs

raw symbols SCIP
1 use crate::{
2 error::*,
3 notification::Notification,
4 notification_id::NotificationId,
5 response::{CloseHandler, NotificationResponse, ResponseHandler},
6 CloseReason, Timeout, Urgency,
7 };
8 use std::{ops::Deref, time::Duration};
9
10 pub use mac_usernotifications::Error as MacOsError;
11
12 /// A handle to a sent notification (**`UNUserNotificationCenter`** path).
13 ///
14 /// [`Notification::show`] returns this handle as soon as macOS accepts the
15 /// notification request — before the user has interacted. Call
16 /// [`response().await`](NotificationHandle::response) to wait for the user's
17 /// response, or drop the handle to stop observing it (the notification stays
18 /// visible; the response channel is cleaned up).
19 #[derive(Debug)]
20 pub struct NotificationHandle {
21 notification: Notification,
22 inner: mac_usernotifications::NotificationHandle,
23 }
24
25 impl NotificationHandle {
26 /// Send `notification` and return a handle for observing the response.
27 ///
28 /// Provided for source-compatibility.
29 /// Prefer [`Notification::show`](crate::Notification::show) for most use-cases.
30 ///
31 /// # Panics
32 ///
33 /// Panics if `UNUserNotificationCenter` refuses to deliver the notification
34 /// (e.g. no bundle identifier, authorisation not granted).
35 ///
36 // TODO: make private in 5.0
37 pub fn new(notification: Notification) -> Self {
38 show_notification_blocking(&notification)
39 .expect("UNUserNotificationCenter: failed to deliver notification")
40 }
41
42 pub(crate) fn from_parts(
43 notification: Notification,
44 inner: mac_usernotifications::NotificationHandle,
45 ) -> Self {
46 Self {
47 notification,
48 inner,
49 }
50 }
51
52 /* TODO: api not settled, reconsider in 5.0
53 /// The notification's request identifier.
54 ///
55 /// This is the UUID assigned by macOS to the `UNNotificationRequest`.
56 pub fn notification_id(&self) -> &str {
57 self.inner.notification_id()
58 }
59 */
60
61 /// Returns the handle's id as a [`NotificationId`].
62 pub fn id(&self) -> NotificationId {
63 NotificationId::Mac(self.inner.notification_id().to_owned())
64 }
65
66 /* save for 5.0
67 /// Wait for the user's response.
68 ///
69 /// Returns as soon as the user interacts with the notification or the
70 /// timeout elapses.
71 pub async fn response(self) -> NotificationResponse {
72 match self.inner.response().await {
73 Ok(resp) => resp.into(),
74 Err(_) => NotificationResponse::Closed(CloseReason::Expired),
75 }
76 }
77 */
78
79 /// Re-send the notification in-place, preserving its identifier.
80 ///
81 /// Mutate the handle via `DerefMut` first to change title, body, etc.,
82 /// then call `update()` to push the changes to Notification Center.
83 pub fn update(&mut self) -> Result<()> {
84 let nid = self.inner.notification_id().to_owned();
85 self.notification.id = Some(NotificationId::Mac(nid));
86 show_notification_blocking(&self.notification)?;
87 Ok(())
88 }
89
90 /// Async version of [`update`](Self::update).
91 pub async fn update_async(&mut self) -> Result<()> {
92 let nid = self.inner.notification_id().to_owned();
93 self.notification.id = Some(NotificationId::Mac(nid));
94 show_notification_async(&self.notification).await?;
95 Ok(())
96 }
97
98 /// Manually close the notification.
99 pub fn close(&self) {
100 mac_usernotifications::blocking::close_delivered(self.inner.notification_id());
101 }
102
103 /// Async version of [`close`](Self::close).
104 // TODO: make the async the default `fn clsoe()` in 5.0
105 pub async fn close_async(&self) {
106 mac_usernotifications::close_delivered(self.inner.notification_id()).await;
107 }
108
109 /// Wait for the user to interact and call `invocation_closure` with the action identifier.
110 ///
111 /// The special value `"__closed"` is passed when the notification is dismissed.
112 pub fn wait_for_action<F>(self, invocation_closure: F)
113 where
114 F: FnOnce(&str),
115 {
116 match mac_usernotifications::block_on_current(self.inner.response()).flatten() {
117 Ok(response) => {
118 let action = if response.is_dismiss_action() {
119 "__closed"
120 } else if response.is_default_action() {
121 "default"
122 } else {
123 &response.action_identifier
124 };
125 invocation_closure(action);
126 }
127 Err(error) => {
128 log::error!("failed to get response: {error}");
129 invocation_closure("__closed");
130 }
131 }
132 }
133
134 /// Waits for the user to act on the notification and then calls `handler`
135 /// with a typed [`NotificationResponse`].
136 ///
137 /// This is the typed, forward-compatible replacement for
138 /// [`wait_for_action`](Self::wait_for_action).
139 pub fn wait_for_response(self, handler: impl ResponseHandler) -> Result<()> {
140 match mac_usernotifications::block_on_current(self.inner.response()).flatten() {
141 Ok(response) => {
142 handler.call(&response.into());
143 Ok(())
144 }
145 Err(error) => {
146 log::error!("failed to get response: {error}");
147 Err(Error::from(ErrorKind::Msg(format!(
148 "failed to get notification response: {error}"
149 ))))
150 }
151 }
152 }
153
154 /// Executes a closure after the notification has closed.
155 pub fn on_close<A>(self, handler: impl CloseHandler<A>) {
156 match mac_usernotifications::block_on_current(self.inner.response()).flatten() {
157 Ok(response) => {
158 if let Some(close_reason) = response.close_reason {
159 handler.call(close_reason.into());
160 } else {
161 handler.call(CloseReason::Dismissed);
162 }
163 }
164 Err(error) => {
165 log::error!("failed to get response: {error}");
166 handler.call(CloseReason::Dismissed);
167 }
168 }
169 }
170 }
171
172 impl From<mac_usernotifications::CloseReason> for CloseReason {
173 fn from(close_reason: mac_usernotifications::CloseReason) -> Self {
174 match close_reason {
175 mac_usernotifications::CloseReason::Dismissed => CloseReason::Dismissed,
176 mac_usernotifications::CloseReason::Expired => CloseReason::Expired,
177 }
178 }
179 }
180
181 impl From<mac_usernotifications::NotificationResponse> for NotificationResponse {
182 fn from(resp: mac_usernotifications::NotificationResponse) -> Self {
183 if resp.is_dismiss_action() {
184 NotificationResponse::Closed(CloseReason::Dismissed)
185 } else if resp.is_default_action() {
186 NotificationResponse::Default
187 } else if let Some(ref text) = resp.reply_text {
188 NotificationResponse::Reply(text.clone())
189 } else {
190 NotificationResponse::Action(resp.action_identifier.clone())
191 }
192 }
193 }
194
195 impl From<Urgency> for mac_usernotifications::InterruptionLevel {
196 fn from(val: Urgency) -> Self {
197 match val {
198 Urgency::Low => mac_usernotifications::InterruptionLevel::Passive,
199 Urgency::Normal => mac_usernotifications::InterruptionLevel::Active,
200 Urgency::Critical => mac_usernotifications::InterruptionLevel::TimeSensitive,
201 }
202 }
203 }
204
205 // SAFETY: `mac_usernotifications::NotificationHandle` uses channels internally
206 // which are `Send + Sync` but not automatically `UnwindSafe`. The handle does
207 // not expose any raw pointers and panics cannot corrupt its state.
208 impl std::panic::UnwindSafe for NotificationHandle {}
209 impl std::panic::RefUnwindSafe for NotificationHandle {}
210
211 impl Deref for NotificationHandle {
212 type Target = Notification;
213
214 fn deref(&self) -> &Notification {
215 &self.notification
216 }
217 }
218
219 impl std::ops::DerefMut for NotificationHandle {
220 fn deref_mut(&mut self) -> &mut Notification {
221 &mut self.notification
222 }
223 }
224
225 impl From<&Notification> for mac_usernotifications::Notification {
226 fn from(n: &Notification) -> Self {
227 let mut un = mac_usernotifications::Notification::new()
228 .title(&n.summary)
229 .message(&n.body)
230 .maybe_subtitle(n.subtitle.as_deref())
231 .maybe_sound(n.sound_name.as_deref());
232
233 // 4.18: actions is Vec<String> with flat [id, label, id, label, …] pairs
234 for chunk in n.actions.chunks(2) {
235 if let (Some(id), Some(label)) = (chunk.first(), chunk.get(1)) {
236 un = un.action(mac_usernotifications::Action::button(id, label));
237 }
238 }
239
240 if let Timeout::Milliseconds(ms) = n.timeout {
241 un = un.timeout(Duration::from_millis(ms as u64));
242 }
243
244 if let Some(ref path) = n.path_to_image {
245 un = un.image_path(path);
246 }
247
248 if let Some(ref nid) = n.id {
249 let id_str = match nid {
250 NotificationId::Mac(ref string_id) => string_id.clone(),
251 NotificationId::Xdg(num) => num.to_string(),
252 };
253 un = un.id(&id_str);
254 }
255
256 if let Some(level) = n.interruption_level {
257 un = un.interruption_level(level);
258 }
259
260 un
261 }
262 }
263
264 pub(crate) fn show_notification(notification: &Notification) -> Result<NotificationHandle> {
265 show_notification_blocking(notification)
266 }
267
268 pub(crate) fn show_notification_blocking(
269 notification: &Notification,
270 ) -> Result<NotificationHandle> {
271 let un = mac_usernotifications::Notification::from(notification);
272 let inner = un.send_blocking()?;
273 Ok(NotificationHandle::from_parts(notification.clone(), inner))
274 }
275
276 pub(crate) async fn show_notification_async(
277 notification: &Notification,
278 ) -> Result<NotificationHandle> {
279 let un = mac_usernotifications::Notification::from(notification);
280 let inner = un.send().await?;
281 Ok(NotificationHandle::from_parts(notification.clone(), inner))
282 }
283
284 pub(crate) fn schedule_notification(
285 notification: &Notification,
286 delivery_date: f64,
287 ) -> Result<NotificationHandle> {
288 use std::time::{SystemTime, UNIX_EPOCH};
289 let now = SystemTime::now()
290 .duration_since(UNIX_EPOCH)
291 .unwrap_or_default()
292 .as_secs_f64();
293 let delay = (delivery_date - now).max(0.1);
294 let un = mac_usernotifications::Notification::from(notification)
295 .schedule_in(Duration::from_secs_f64(delay));
296 let inner = un.send_blocking()?;
297 Ok(NotificationHandle::from_parts(notification.clone(), inner))
298 }