mac-notification-sys 0.6.15

Thin wrapper around macOS Notifications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use std::{ffi::CStr, os::raw::c_char, sync::atomic::Ordering};

use crate::{NotificationResponse, pending_guard::pending};

/// Seconds to wait for async XPC delivery confirmation before giving up.
/// Matched by `kDeliveryTimeoutSecs` in notify.m.
const DELIVERY_TIMEOUT_SECS: u64 = 2;

unsafe fn str_from_ptr<'a>(ptr: *const c_char) -> Option<&'a str> {
    if ptr.is_null() {
        return None;
    }
    unsafe { CStr::from_ptr(ptr) }.to_str().ok()
}

unsafe fn uuid_from_ptr(ptr: *const u8) -> Option<[u8; 16]> {
    if ptr.is_null() {
        return None;
    }
    unsafe { std::slice::from_raw_parts(ptr, 16) }
        .try_into()
        .ok()
}

fn complete_notification(id: &[u8; 16], response: NotificationResponse) {
    if let Some(entry) = pending().lock().unwrap().get(id).cloned() {
        // Acquire result lock BEFORE checking done so the check-and-set is atomic.
        // Without this, two concurrent callers could both observe done=false,
        // both enter the block, and the second would overwrite the first's result.
        let mut result = entry.result.lock().unwrap();
        log::trace!("complete_notification: id: ..., response: {response:?}");
        if !entry.done.load(Ordering::Acquire) {
            *result = response;
            entry.done.store(true, Ordering::Release);
            entry.condvar.notify_all();
        }
    } else {
        log::debug!("complete_notification: no entry for id: {id:?}");
    }
}

/// Called from ObjC delegate when a notification is activated (clicked/replied/action).
/// `activation_type`: 0=none, 1=actionClicked, 2=contentsClicked, 3=replied
/// `_action_value_index`: selected dropdown index, or -1 if not applicable
#[unsafe(no_mangle)]
pub extern "C" fn rust_notification_activated(
    uuid: *const u8,
    activation_type: u8,
    action_value: *const c_char,
    _action_value_index: i64,
) {
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let id = match unsafe { uuid_from_ptr(uuid) } {
            Some(b) => b,
            None => return,
        };
        let action_value = unsafe { str_from_ptr(action_value) }
            .unwrap_or("")
            .to_owned();

        log::debug!("notification activated: type={activation_type}");

        let response = match activation_type {
            1 => NotificationResponse::ActionButton(action_value),
            2 => NotificationResponse::Click,
            3 => NotificationResponse::Reply(action_value),
            _ => NotificationResponse::None,
        };
        complete_notification(&id, response);
    }));
}

/// Called from ObjC delegate when a notification is dismissed via the close button.
#[unsafe(no_mangle)]
pub extern "C" fn rust_notification_dismissed(uuid: *const u8, button_title: *const c_char) {
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let id = match unsafe { uuid_from_ptr(uuid) } {
            Some(b) => b,
            None => return,
        };
        let title = unsafe { str_from_ptr(button_title) }
            .unwrap_or("")
            .to_owned();
        log::debug!("notification dismissed");
        complete_notification(&id, NotificationResponse::CloseButton(title));
    }));
}

/// Called from ObjC when a notification disappears without explicit user interaction.
#[unsafe(no_mangle)]
pub extern "C" fn rust_notification_auto_dismissed(uuid: *const u8) {
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let id = match unsafe { uuid_from_ptr(uuid) } {
            Some(b) => b,
            None => return,
        };
        log::debug!("notification auto-dismissed");
        complete_notification(&id, NotificationResponse::None);
    }));
}

/// Called from ObjC main-thread RunLoop spin to check whether waiting should stop.
#[unsafe(no_mangle)]
pub extern "C" fn rust_notification_is_done(uuid: *const u8) -> bool {
    // On panic return `true` so the RunLoop spin terminates instead of looping forever.
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let id = match unsafe { uuid_from_ptr(uuid) } {
            Some(b) => b,
            None => return true,
        };
        pending()
            .lock()
            .unwrap()
            .get(&id)
            .map(|e| e.done.load(Ordering::Acquire))
            .unwrap_or(true)
    }))
    .unwrap_or(true)
}

/// Called from ObjC background threads to block until the notification completes.
#[unsafe(no_mangle)]
pub extern "C" fn rust_wait_for_notification(uuid: *const u8) {
    // On panic: return immediately so the ObjC background thread isn't stuck forever.
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let id = match unsafe { uuid_from_ptr(uuid) } {
            Some(b) => b,
            None => return,
        };
        let entry = match pending().lock().unwrap().get(&id).cloned() {
            Some(e) => e,
            None => return,
        };
        let guard = entry.result.lock().unwrap();
        let _unused = entry
            .condvar
            .wait_while(guard, |_| !entry.done.load(Ordering::Acquire));
    }));
}

/// Called from the ObjC delegate when `NSUserNotificationCenter` confirms delivery via
/// `didDeliverNotification:`. Used by fire-and-forget sends to ensure the process stays
/// alive until the notification actually reaches the notification daemon.
#[unsafe(no_mangle)]
pub extern "C" fn rust_notification_delivered(uuid: *const u8) {
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let id = match unsafe { uuid_from_ptr(uuid) } {
            Some(b) => b,
            None => return,
        };
        if let Some(entry) = pending().lock().unwrap().get(&id).cloned() {
            *entry.delivered.lock().unwrap() = true;
            entry.delivered_cv.notify_all();
        }
    }));
}

/// Polled from the ObjC main-thread run-loop spin (fire-and-forget path) to check
/// whether `didDeliverNotification:` has fired. Returns `true` on unknown uuid or
/// panic so the spin terminates instead of looping forever.
#[unsafe(no_mangle)]
pub extern "C" fn rust_notification_is_delivered(uuid: *const u8) -> bool {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let id = match unsafe { uuid_from_ptr(uuid) } {
            Some(b) => b,
            None => return true,
        };
        pending()
            .lock()
            .unwrap()
            .get(&id)
            .map(|e| *e.delivered.lock().unwrap())
            .unwrap_or(true)
    }))
    .unwrap_or(true)
}

/// Called from ObjC background threads (fire-and-forget path): block until
/// `didDeliverNotification:` fires, bounded by a 2-second safety timeout so the
/// caller can't hang indefinitely if the callback never arrives.
#[unsafe(no_mangle)]
pub extern "C" fn rust_wait_for_delivery(uuid: *const u8) {
    // On panic: return immediately so the ObjC background thread isn't stuck forever.
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let id = match unsafe { uuid_from_ptr(uuid) } {
            Some(b) => b,
            None => return,
        };
        let entry = match pending().lock().unwrap().get(&id).cloned() {
            Some(e) => e,
            None => return,
        };
        let guard = entry.delivered.lock().unwrap();
        let _ = entry.delivered_cv.wait_timeout_while(
            guard,
            std::time::Duration::from_secs(DELIVERY_TIMEOUT_SECS),
            |delivered| !*delivered,
        );
    }));
}

#[cfg(test)]
mod tests {
    use crate::{MainButton, Notification, pending_guard::PendingEntry};

    use super::*;
    use std::{
        ffi::CString,
        sync::{Arc, Condvar, Mutex, atomic::AtomicBool},
    };

    /// Insert a bare entry into PENDING so tests can drive callbacks directly.
    fn insert_test_entry(id: [u8; 16]) -> Arc<PendingEntry> {
        let entry = Arc::new(PendingEntry {
            result: Mutex::new(NotificationResponse::None),
            done: AtomicBool::new(false),
            condvar: Condvar::new(),
            delivered: Mutex::new(false),
            delivered_cv: Condvar::new(),
        });
        pending().lock().unwrap().insert(id, Arc::clone(&entry));
        entry
    }

    fn remove_entry(id: [u8; 16]) -> Option<Arc<PendingEntry>> {
        pending().lock().unwrap().remove(&id)
    }

    // --- needs_response truth table ---

    #[test]
    fn needs_response_false_by_default() {
        assert!(!Notification::new().needs_response());
    }

    #[test]
    fn needs_response_true_for_main_button() {
        assert!(
            Notification::new()
                .main_button(MainButton::SingleAction("ok"))
                .needs_response()
        );
    }

    #[test]
    fn needs_response_true_for_close_button() {
        assert!(Notification::new().close_button("X").needs_response());
    }

    #[test]
    fn needs_response_true_for_wait_for_click() {
        assert!(Notification::new().wait_for_click(true).needs_response());
    }

    #[test]
    fn needs_response_false_for_delivery_date() {
        // Scheduled notifications are fire-and-forget — delivery_date alone must not
        // cause the caller to block waiting for interaction.
        assert!(!Notification::new().delivery_date(1.0).needs_response());
    }

    #[test]
    fn asynchronous_overrides_needs_response() {
        let mut n = Notification::new();
        n.main_button(MainButton::SingleAction("ok"));
        n.asynchronous(true);
        assert!(!n.needs_response());
    }

    // --- round-trip callback tests ---

    #[test]
    fn bridge_reply() {
        let id: [u8; 16] = [0x9a, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
        insert_test_entry(id);

        let value = CString::new("hello world").unwrap();

        rust_notification_activated(id.as_ptr(), 3, value.as_ptr(), -1);

        assert!(rust_notification_is_done(id.as_ptr()));
        let entry = remove_entry(id).unwrap();
        assert_eq!(
            *entry.result.lock().unwrap(),
            NotificationResponse::Reply("hello world".into())
        );
    }

    #[test]
    fn bridge_action_button() {
        let id: [u8; 16] = [0x9b, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2];
        insert_test_entry(id);

        let value = CString::new("Delete").unwrap();

        rust_notification_activated(id.as_ptr(), 1, value.as_ptr(), -1);

        assert!(rust_notification_is_done(id.as_ptr()));
        let entry = remove_entry(id).unwrap();
        assert_eq!(
            *entry.result.lock().unwrap(),
            NotificationResponse::ActionButton("Delete".into())
        );
    }

    #[test]
    fn bridge_close_button() {
        let id: [u8; 16] = [0x9c, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3];
        insert_test_entry(id);

        let button = CString::new("Nevermind").unwrap();

        rust_notification_dismissed(id.as_ptr(), button.as_ptr());

        assert!(rust_notification_is_done(id.as_ptr()));
        let entry = remove_entry(id).unwrap();
        assert_eq!(
            *entry.result.lock().unwrap(),
            NotificationResponse::CloseButton("Nevermind".into())
        );
    }

    #[test]
    fn bridge_auto_dismissed() {
        let id: [u8; 16] = [0x9d, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4];
        insert_test_entry(id);

        rust_notification_auto_dismissed(id.as_ptr());

        assert!(rust_notification_is_done(id.as_ptr()));
        let entry = remove_entry(id).unwrap();
        assert_eq!(*entry.result.lock().unwrap(), NotificationResponse::None);
    }

    // --- first-wins guard ---

    #[test]
    fn first_wins_guard() {
        let id: [u8; 16] = [0x9e, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5];
        insert_test_entry(id);

        let first = CString::new("first").unwrap();
        let second = CString::new("second").unwrap();

        rust_notification_activated(id.as_ptr(), 3, first.as_ptr(), -1);
        // Second call must be ignored because done=true after the first.
        rust_notification_activated(id.as_ptr(), 3, second.as_ptr(), -1);

        let entry = remove_entry(id).unwrap();
        assert_eq!(
            *entry.result.lock().unwrap(),
            NotificationResponse::Reply("first".into())
        );
    }

    // --- delivery confirmation bridge ---

    #[test]
    fn bridge_delivered_fires_signal() {
        let id: [u8; 16] = [0x9f, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6];
        let entry = insert_test_entry(id);

        assert!(!rust_notification_is_delivered(id.as_ptr()));

        rust_notification_delivered(id.as_ptr());

        assert!(rust_notification_is_delivered(id.as_ptr()));
        assert!(*entry.delivered.lock().unwrap());
        // done must NOT be set — delivered is orthogonal to the interaction/done flow.
        assert!(!entry.done.load(Ordering::Acquire));

        remove_entry(id);
    }

    #[test]
    fn unknown_uuid_is_delivered_returns_true() {
        let unknown: [u8; 16] = [0xff; 16];
        assert!(rust_notification_is_delivered(unknown.as_ptr()));
    }

    #[test]
    fn unknown_uuid_wait_for_delivery_returns_immediately() {
        let unknown: [u8; 16] = [0xfe; 16];
        rust_wait_for_delivery(unknown.as_ptr());
    }

    // --- unknown-uuid safety ---

    #[test]
    fn unknown_uuid_is_done_returns_true() {
        let unknown: [u8; 16] = [0xfd; 16];
        assert!(rust_notification_is_done(unknown.as_ptr()));
    }

    #[test]
    fn unknown_uuid_complete_is_noop() {
        let unknown: [u8; 16] = [0xfc; 16];
        complete_notification(&unknown, NotificationResponse::None);
    }

    #[test]
    fn unknown_uuid_wait_returns_immediately() {
        let unknown: [u8; 16] = [0xfb; 16];
        rust_wait_for_notification(unknown.as_ptr());
    }
}