fission-shell-winit 0.4.0

Shared winit shell runtime for desktop and mobile Fission hosts
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
#[cfg(target_os = "macos")]
use block::ConcreteBlock;
use fission_core::{
    CancelNotificationRequest, NotificationError, NotificationPermission,
    NotificationPermissionRequest, NotificationReceipt, NotificationRequest, NotificationSchedule,
    NotificationSettings, PushPlatform, PushRegistration, PushRegistrationRequest,
    SetBadgeCountRequest, CANCEL_ALL_NOTIFICATIONS, CANCEL_NOTIFICATION, GET_NOTIFICATION_SETTINGS,
    REGISTER_PUSH_NOTIFICATIONS, REQUEST_NOTIFICATION_PERMISSION, SCHEDULE_NOTIFICATION,
    SET_BADGE_COUNT, SHOW_NOTIFICATION, UNREGISTER_PUSH_NOTIFICATIONS,
};
use fission_shell::async_host::AsyncRegistry;
#[cfg(target_os = "ios")]
use objc::{class, msg_send, sel, sel_impl};
#[cfg(target_os = "macos")]
use objc::{class, msg_send, sel, sel_impl};
#[cfg(target_os = "macos")]
use std::ffi::CStr;
#[cfg(any(target_os = "ios", target_os = "macos"))]
use std::os::raw::c_void;
#[cfg(not(target_os = "ios"))]
use std::process::Command;
use std::sync::Arc;
#[cfg(target_os = "macos")]
use std::sync::{Condvar, Mutex};

#[cfg(target_os = "ios")]
#[link(name = "UIKit", kind = "framework")]
extern "C" {}

#[cfg(target_os = "macos")]
#[link(name = "AppKit", kind = "framework")]
extern "C" {}

#[cfg(target_os = "macos")]
#[link(name = "Foundation", kind = "framework")]
extern "C" {}

#[cfg(target_os = "macos")]
#[link(name = "UserNotifications", kind = "framework")]
extern "C" {}

/// Host-side notification provider used by the shell capability registry.
pub trait NotificationHost: Send + Sync + 'static {
    /// Requests permission for notification features such as alerts, badges, or sound.
    ///
    /// Implementations should map the typed request to the platform prompt and
    /// return the resulting settings without assuming permission was granted.
    fn request_permission(
        &self,
        request: NotificationPermissionRequest,
    ) -> Result<NotificationSettings, NotificationError>;

    /// Returns current notification settings without showing a platform prompt.
    ///
    /// Use this to report permission state, delivery support, scheduling support,
    /// badge support, and push support to reducers.
    fn settings(&self) -> Result<NotificationSettings, NotificationError>;

    /// Displays an immediate local notification.
    ///
    /// `request` contains the stable id, visible text, badge, sound, deep link,
    /// and action buttons. Return a receipt only after the host accepted the
    /// notification request.
    fn show(&self, request: NotificationRequest) -> Result<NotificationReceipt, NotificationError>;

    /// Schedules a local notification for later delivery.
    ///
    /// Implementations should persist or hand off the schedule according to the
    /// platform notification model and return an error when scheduled delivery is
    /// unavailable.
    fn schedule(
        &self,
        request: NotificationRequest,
    ) -> Result<NotificationReceipt, NotificationError>;

    /// Cancels one notification by id.
    ///
    /// `request.id` is the id originally used to show or schedule the
    /// notification. Hosts may treat an already-missing notification as success.
    fn cancel(&self, request: CancelNotificationRequest) -> Result<(), NotificationError>;

    /// Cancels all notifications owned by this app where the platform allows it.
    fn cancel_all(&self) -> Result<(), NotificationError>;

    /// Sets or clears the app badge count.
    ///
    /// `None` clears the badge. `Some(count)` asks the host to show the supplied
    /// count using the target platform badge mechanism.
    fn set_badge_count(&self, request: SetBadgeCountRequest) -> Result<(), NotificationError>;

    /// Registers this app instance for remote or push notification delivery.
    ///
    /// Provider credentials remain in host configuration. The request carries
    /// public registration inputs and the result returns token or endpoint data.
    fn register_push(
        &self,
        request: PushRegistrationRequest,
    ) -> Result<PushRegistration, NotificationError>;

    /// Removes or invalidates this app instance from remote notification delivery.
    fn unregister_push(&self) -> Result<(), NotificationError>;
}

/// Default provider used until a shell installs a platform-specific host.
#[derive(Debug, Default)]
pub struct UnsupportedNotificationHost;

impl NotificationHost for UnsupportedNotificationHost {
    fn request_permission(
        &self,
        _request: NotificationPermissionRequest,
    ) -> Result<NotificationSettings, NotificationError> {
        Ok(NotificationSettings {
            permission: NotificationPermission::Unsupported,
            ..Default::default()
        })
    }

    fn settings(&self) -> Result<NotificationSettings, NotificationError> {
        Ok(NotificationSettings {
            permission: NotificationPermission::Unsupported,
            ..Default::default()
        })
    }

    fn show(
        &self,
        _request: NotificationRequest,
    ) -> Result<NotificationReceipt, NotificationError> {
        Err(NotificationError::unsupported("show"))
    }

    fn schedule(
        &self,
        _request: NotificationRequest,
    ) -> Result<NotificationReceipt, NotificationError> {
        Err(NotificationError::unsupported("schedule"))
    }

    fn cancel(&self, _request: CancelNotificationRequest) -> Result<(), NotificationError> {
        Err(NotificationError::unsupported("cancel"))
    }

    fn cancel_all(&self) -> Result<(), NotificationError> {
        Err(NotificationError::unsupported("cancel_all"))
    }

    fn set_badge_count(&self, _request: SetBadgeCountRequest) -> Result<(), NotificationError> {
        Err(NotificationError::unsupported("set_badge_count"))
    }

    fn register_push(
        &self,
        _request: PushRegistrationRequest,
    ) -> Result<PushRegistration, NotificationError> {
        Err(NotificationError::unsupported("register_push"))
    }

    fn unregister_push(&self) -> Result<(), NotificationError> {
        Err(NotificationError::unsupported("unregister_push"))
    }
}

/// Minimal in-process host useful for smoke tests and non-OS environments.
#[derive(Debug, Default)]
pub struct MemoryNotificationHost;

impl NotificationHost for MemoryNotificationHost {
    fn request_permission(
        &self,
        request: NotificationPermissionRequest,
    ) -> Result<NotificationSettings, NotificationError> {
        Ok(NotificationSettings {
            permission: NotificationPermission::Granted,
            alerts: request.alerts,
            badge: request.badge,
            sound: request.sound,
            scheduling: true,
            push: false,
        })
    }

    fn settings(&self) -> Result<NotificationSettings, NotificationError> {
        Ok(NotificationSettings {
            permission: NotificationPermission::Granted,
            alerts: true,
            badge: true,
            sound: true,
            scheduling: true,
            push: false,
        })
    }

    fn show(&self, request: NotificationRequest) -> Result<NotificationReceipt, NotificationError> {
        Ok(NotificationReceipt {
            id: request.id,
            scheduled: false,
            delivered: true,
        })
    }

    fn schedule(
        &self,
        request: NotificationRequest,
    ) -> Result<NotificationReceipt, NotificationError> {
        Ok(NotificationReceipt {
            id: request.id,
            scheduled: !matches!(request.schedule, NotificationSchedule::Immediate),
            delivered: matches!(request.schedule, NotificationSchedule::Immediate),
        })
    }

    fn cancel(&self, _request: CancelNotificationRequest) -> Result<(), NotificationError> {
        Ok(())
    }

    fn cancel_all(&self) -> Result<(), NotificationError> {
        Ok(())
    }

    fn set_badge_count(&self, _request: SetBadgeCountRequest) -> Result<(), NotificationError> {
        Ok(())
    }

    fn register_push(
        &self,
        _request: PushRegistrationRequest,
    ) -> Result<PushRegistration, NotificationError> {
        Ok(PushRegistration {
            platform: PushPlatform::Other("memory".into()),
            token: "memory-push-token".into(),
            endpoint: None,
            p256dh_key: None,
            auth_secret: None,
        })
    }

    fn unregister_push(&self) -> Result<(), NotificationError> {
        Ok(())
    }
}

#[derive(Debug, Default)]
pub struct NativeNotificationHost;

pub(crate) fn native_notification_host() -> impl NotificationHost {
    NativeNotificationHost
}

impl NativeNotificationHost {
    #[cfg(any(test, not(target_os = "macos")))]
    fn supported() -> bool {
        cfg!(target_os = "ios")
            || cfg!(target_os = "macos")
            || (cfg!(target_os = "linux") && command_exists("notify-send"))
    }

    #[cfg(any(test, not(target_os = "macos")))]
    fn native_settings() -> NotificationSettings {
        if Self::supported() {
            NotificationSettings {
                permission: NotificationPermission::Granted,
                alerts: true,
                badge: cfg!(any(target_os = "ios", target_os = "macos")),
                sound: true,
                scheduling: cfg!(any(target_os = "ios", target_os = "macos"))
                    || (cfg!(target_os = "linux") && command_exists("notify-send")),
                push: false,
            }
        } else {
            NotificationSettings {
                permission: NotificationPermission::Unsupported,
                ..Default::default()
            }
        }
    }

    fn show_now(&self, request: &NotificationRequest) -> Result<(), NotificationError> {
        #[cfg(target_os = "ios")]
        {
            ios_register_local_notifications();
            ios_show_local_notification(request, None);
            return Ok(());
        }

        #[cfg(not(target_os = "ios"))]
        {
            if cfg!(target_os = "macos") {
                #[cfg(target_os = "macos")]
                {
                    macos_deliver_notification(request, None)?;
                    return Ok(());
                }
            }

            if cfg!(target_os = "linux") {
                if !command_exists("notify-send") {
                    return Err(NotificationError::unsupported("show"));
                }
                Command::new("notify-send")
                    .arg(&request.title)
                    .arg(&request.body)
                    .spawn()
                    .map_err(notification_command_error)?
                    .wait()
                    .map_err(notification_command_error)?;
                return Ok(());
            }

            if cfg!(target_os = "windows") {
                return Err(NotificationError::unsupported("show_windows_toast"));
            }

            Err(NotificationError::unsupported("show"))
        }
    }
}

impl NotificationHost for NativeNotificationHost {
    fn request_permission(
        &self,
        _request: NotificationPermissionRequest,
    ) -> Result<NotificationSettings, NotificationError> {
        #[cfg(target_os = "macos")]
        {
            macos_request_notification_permission()
        }
        #[cfg(not(target_os = "macos"))]
        {
            #[cfg(target_os = "ios")]
            ios_register_local_notifications();
            Ok(Self::native_settings())
        }
    }

    fn settings(&self) -> Result<NotificationSettings, NotificationError> {
        #[cfg(target_os = "macos")]
        {
            macos_notification_settings()
        }
        #[cfg(not(target_os = "macos"))]
        {
            Ok(Self::native_settings())
        }
    }

    fn show(&self, request: NotificationRequest) -> Result<NotificationReceipt, NotificationError> {
        match request.schedule {
            NotificationSchedule::Immediate => {
                self.show_now(&request)?;
                Ok(NotificationReceipt {
                    id: request.id,
                    scheduled: false,
                    delivered: true,
                })
            }
            _ => Err(NotificationError::unsupported("schedule")),
        }
    }

    fn schedule(
        &self,
        request: NotificationRequest,
    ) -> Result<NotificationReceipt, NotificationError> {
        match request.schedule {
            NotificationSchedule::Immediate => self.show(request),
            #[cfg(target_os = "ios")]
            NotificationSchedule::AfterMillis(ms) => {
                ios_register_local_notifications();
                ios_show_local_notification(&request, Some(ms as f64 / 1000.0));
                Ok(NotificationReceipt {
                    id: request.id,
                    scheduled: true,
                    delivered: false,
                })
            }
            #[cfg(target_os = "ios")]
            NotificationSchedule::AtUnixMillis(ms) => {
                let now_ms = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|duration| duration.as_millis() as u64)
                    .unwrap_or(ms);
                ios_register_local_notifications();
                ios_show_local_notification(
                    &request,
                    Some(ms.saturating_sub(now_ms) as f64 / 1000.0),
                );
                Ok(NotificationReceipt {
                    id: request.id,
                    scheduled: true,
                    delivered: false,
                })
            }
            #[cfg(not(target_os = "ios"))]
            NotificationSchedule::AfterMillis(ms) => {
                if cfg!(target_os = "macos") {
                    #[cfg(target_os = "macos")]
                    {
                        macos_deliver_notification(&request, Some(ms as f64 / 1000.0))?;
                        return Ok(NotificationReceipt {
                            id: request.id,
                            scheduled: true,
                            delivered: false,
                        });
                    }
                }
                if !(cfg!(target_os = "linux") && command_exists("notify-send")) {
                    return Err(NotificationError::unsupported("schedule"));
                }
                let id = request.id.clone();
                let request = request.clone();
                std::thread::spawn(move || {
                    std::thread::sleep(std::time::Duration::from_millis(ms));
                    let host = NativeNotificationHost;
                    let _ = host.show_now(&request);
                });
                Ok(NotificationReceipt {
                    id,
                    scheduled: true,
                    delivered: false,
                })
            }
            #[cfg(not(target_os = "ios"))]
            NotificationSchedule::AtUnixMillis(ms) => {
                let now_ms = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|duration| duration.as_millis() as u64)
                    .unwrap_or(ms);
                if cfg!(target_os = "macos") {
                    #[cfg(target_os = "macos")]
                    {
                        macos_deliver_notification(
                            &request,
                            Some(ms.saturating_sub(now_ms) as f64 / 1000.0),
                        )?;
                        return Ok(NotificationReceipt {
                            id: request.id,
                            scheduled: true,
                            delivered: false,
                        });
                    }
                }
                if !(cfg!(target_os = "linux") && command_exists("notify-send")) {
                    return Err(NotificationError::unsupported("schedule"));
                }
                let id = request.id.clone();
                let request = request.clone();
                std::thread::spawn(move || {
                    std::thread::sleep(std::time::Duration::from_millis(ms.saturating_sub(now_ms)));
                    let host = NativeNotificationHost;
                    let _ = host.show_now(&request);
                });
                Ok(NotificationReceipt {
                    id,
                    scheduled: true,
                    delivered: false,
                })
            }
        }
    }

    fn cancel(&self, request: CancelNotificationRequest) -> Result<(), NotificationError> {
        #[cfg(target_os = "macos")]
        {
            macos_cancel_notification(&request.id.0);
            Ok(())
        }
        #[cfg(not(target_os = "macos"))]
        {
            let _ = request;
            Err(NotificationError::unsupported("cancel"))
        }
    }

    fn cancel_all(&self) -> Result<(), NotificationError> {
        #[cfg(target_os = "macos")]
        {
            macos_cancel_all_notifications();
            Ok(())
        }
        #[cfg(not(target_os = "macos"))]
        {
            Err(NotificationError::unsupported("cancel_all"))
        }
    }

    fn set_badge_count(&self, request: SetBadgeCountRequest) -> Result<(), NotificationError> {
        #[cfg(target_os = "ios")]
        {
            ios_set_badge_count(request.count);
            return Ok(());
        }
        #[cfg(target_os = "macos")]
        {
            macos_set_badge_count(request.count);
            return Ok(());
        }
        #[cfg(not(any(target_os = "ios", target_os = "macos")))]
        {
            let _ = request;
            Err(NotificationError::unsupported("set_badge_count"))
        }
    }

    fn register_push(
        &self,
        _request: PushRegistrationRequest,
    ) -> Result<PushRegistration, NotificationError> {
        Err(NotificationError::unsupported("register_push"))
    }

    fn unregister_push(&self) -> Result<(), NotificationError> {
        Err(NotificationError::unsupported("unregister_push"))
    }
}

#[cfg(target_os = "ios")]
fn ios_register_local_notifications() {
    unsafe {
        let app: *mut objc::runtime::Object = msg_send![class!(UIApplication), sharedApplication];
        if app.is_null() {
            return;
        }
        let settings: *mut objc::runtime::Object = msg_send![
            class!(UIUserNotificationSettings),
            settingsForTypes: 7usize
            categories: std::ptr::null_mut::<objc::runtime::Object>()
        ];
        if !settings.is_null() {
            let _: () = msg_send![app, registerUserNotificationSettings: settings];
        }
    }
}

#[cfg(target_os = "ios")]
fn ios_show_local_notification(request: &NotificationRequest, delay_seconds: Option<f64>) {
    unsafe {
        let notification: *mut objc::runtime::Object = msg_send![class!(UILocalNotification), new];
        if notification.is_null() {
            return;
        }
        let title = ns_string(&request.title);
        let body = ns_string(&request.body);
        let _: () = msg_send![notification, setAlertTitle: title];
        let _: () = msg_send![notification, setAlertBody: body];
        if !matches!(request.sound, fission_core::NotificationSound::Silent) {
            let default_sound: *mut objc::runtime::Object =
                msg_send![class!(UILocalNotification), defaultSoundName];
            let _: () = msg_send![notification, setSoundName: default_sound];
        }
        if let Some(badge) = request.badge {
            let _: () = msg_send![notification, setApplicationIconBadgeNumber: badge as isize];
        }
        let app: *mut objc::runtime::Object = msg_send![class!(UIApplication), sharedApplication];
        if app.is_null() {
            return;
        }
        if let Some(delay) = delay_seconds {
            let date: *mut objc::runtime::Object =
                msg_send![class!(NSDate), dateWithTimeIntervalSinceNow: delay.max(0.0)];
            let _: () = msg_send![notification, setFireDate: date];
            let _: () = msg_send![app, scheduleLocalNotification: notification];
        } else {
            let _: () = msg_send![app, presentLocalNotificationNow: notification];
        }
    }
}

#[cfg(target_os = "ios")]
fn ios_set_badge_count(count: Option<u32>) {
    unsafe {
        let app: *mut objc::runtime::Object = msg_send![class!(UIApplication), sharedApplication];
        if !app.is_null() {
            let _: () = msg_send![app, setApplicationIconBadgeNumber: count.unwrap_or(0) as isize];
        }
    }
}

#[cfg(target_os = "macos")]
fn macos_request_notification_permission() -> Result<NotificationSettings, NotificationError> {
    let pair = Arc::new((Mutex::new(None), Condvar::new()));
    let pair_for_block = pair.clone();
    let block = ConcreteBlock::new(move |granted: bool, _error: *mut objc::runtime::Object| {
        let (lock, cvar) = &*pair_for_block;
        if let Ok(mut result) = lock.lock() {
            *result = Some(granted);
            cvar.notify_all();
        }
    })
    .copy();
    unsafe {
        let center: *mut objc::runtime::Object =
            msg_send![class!(UNUserNotificationCenter), currentNotificationCenter];
        if center.is_null() {
            return Err(NotificationError::unsupported("notifications"));
        }
        let options = 1usize | 2usize | 4usize;
        let _: () = msg_send![
            center,
            requestAuthorizationWithOptions: options
            completionHandler: &*block
        ];
    }
    let (lock, cvar) = &*pair;
    let guard = lock.lock().unwrap();
    let (guard, _) = cvar
        .wait_timeout_while(guard, std::time::Duration::from_secs(30), |value| {
            value.is_none()
        })
        .unwrap();
    let granted = (*guard).unwrap_or(false);
    Ok(NotificationSettings {
        permission: if granted {
            NotificationPermission::Granted
        } else {
            NotificationPermission::Denied
        },
        alerts: granted,
        badge: granted,
        sound: granted,
        scheduling: granted,
        push: false,
    })
}

#[cfg(target_os = "macos")]
fn macos_notification_settings() -> Result<NotificationSettings, NotificationError> {
    let pair = Arc::new((Mutex::new(None), Condvar::new()));
    let pair_for_block = pair.clone();
    let block = ConcreteBlock::new(move |settings: *mut objc::runtime::Object| {
        let status: i64 = if settings.is_null() {
            0
        } else {
            unsafe { msg_send![settings, authorizationStatus] }
        };
        let permission = match status {
            2 => NotificationPermission::Granted,
            3 | 4 => NotificationPermission::Provisional,
            1 => NotificationPermission::Denied,
            _ => NotificationPermission::NotDetermined,
        };
        let enabled = matches!(
            permission,
            NotificationPermission::Granted | NotificationPermission::Provisional
        );
        let (lock, cvar) = &*pair_for_block;
        if let Ok(mut result) = lock.lock() {
            *result = Some(NotificationSettings {
                permission,
                alerts: enabled,
                badge: enabled,
                sound: enabled,
                scheduling: enabled,
                push: false,
            });
            cvar.notify_all();
        }
    })
    .copy();
    unsafe {
        let center: *mut objc::runtime::Object =
            msg_send![class!(UNUserNotificationCenter), currentNotificationCenter];
        if center.is_null() {
            return Err(NotificationError::unsupported("notifications"));
        }
        let _: () = msg_send![center, getNotificationSettingsWithCompletionHandler: &*block];
    }
    let (lock, cvar) = &*pair;
    let guard = lock.lock().unwrap();
    let (guard, _) = cvar
        .wait_timeout_while(guard, std::time::Duration::from_secs(30), |value| {
            value.is_none()
        })
        .unwrap();
    Ok(guard.clone().unwrap_or(NotificationSettings {
        permission: NotificationPermission::NotDetermined,
        ..Default::default()
    }))
}

#[cfg(target_os = "macos")]
fn macos_deliver_notification(
    request: &NotificationRequest,
    delay_seconds: Option<f64>,
) -> Result<(), NotificationError> {
    let settings = macos_request_notification_permission()?;
    if !matches!(
        settings.permission,
        NotificationPermission::Granted | NotificationPermission::Provisional
    ) {
        return Err(NotificationError::new(
            "permission_denied",
            "macOS notification permission is not granted",
        ));
    }

    let pair = Arc::new((Mutex::new(None), Condvar::new()));
    let pair_for_block = pair.clone();
    let block = ConcreteBlock::new(move |error: *mut objc::runtime::Object| {
        let message = if error.is_null() {
            None
        } else {
            Some(macos_error_description(error))
        };
        let (lock, cvar) = &*pair_for_block;
        if let Ok(mut result) = lock.lock() {
            *result = Some(message);
            cvar.notify_all();
        }
    })
    .copy();

    unsafe {
        let content: *mut objc::runtime::Object =
            msg_send![class!(UNMutableNotificationContent), new];
        if content.is_null() {
            return Err(NotificationError::unsupported("notification_content"));
        }
        let title = ns_string(&request.title);
        let body = ns_string(&request.body);
        let _: () = msg_send![content, setTitle: title];
        let _: () = msg_send![content, setBody: body];
        if let Some(subtitle) = request.subtitle.as_deref() {
            let subtitle = ns_string(subtitle);
            let _: () = msg_send![content, setSubtitle: subtitle];
        }
        if !matches!(request.sound, fission_core::NotificationSound::Silent) {
            let sound: *mut objc::runtime::Object =
                msg_send![class!(UNNotificationSound), defaultSound];
            let _: () = msg_send![content, setSound: sound];
        }
        if let Some(badge) = request.badge {
            let badge: *mut objc::runtime::Object =
                msg_send![class!(NSNumber), numberWithUnsignedInteger: badge as usize];
            let _: () = msg_send![content, setBadge: badge];
        }

        let trigger: *mut objc::runtime::Object = if let Some(delay) = delay_seconds {
            msg_send![
                class!(UNTimeIntervalNotificationTrigger),
                triggerWithTimeInterval: delay.max(1.0)
                repeats: false
            ]
        } else {
            std::ptr::null_mut()
        };
        let identifier = ns_string(&request.id.0);
        let notification_request: *mut objc::runtime::Object = msg_send![
            class!(UNNotificationRequest),
            requestWithIdentifier: identifier
            content: content
            trigger: trigger
        ];
        if notification_request.is_null() {
            return Err(NotificationError::unsupported("notification_request"));
        }
        let center: *mut objc::runtime::Object =
            msg_send![class!(UNUserNotificationCenter), currentNotificationCenter];
        if center.is_null() {
            return Err(NotificationError::unsupported("notifications"));
        }
        let _: () = msg_send![center, addNotificationRequest: notification_request withCompletionHandler: &*block];
    }

    let (lock, cvar) = &*pair;
    let guard = lock.lock().unwrap();
    let (guard, _) = cvar
        .wait_timeout_while(guard, std::time::Duration::from_secs(30), |value| {
            value.is_none()
        })
        .unwrap();
    if let Some(Some(message)) = guard.clone() {
        Err(NotificationError::new("host_error", message))
    } else {
        Ok(())
    }
}

#[cfg(target_os = "macos")]
fn macos_error_description(error: *mut objc::runtime::Object) -> String {
    unsafe {
        let description: *mut objc::runtime::Object = msg_send![error, localizedDescription];
        ns_string_to_string(description).unwrap_or_else(|| "macOS notification error".into())
    }
}

#[cfg(target_os = "macos")]
fn macos_cancel_notification(id: &str) {
    unsafe {
        let center: *mut objc::runtime::Object =
            msg_send![class!(UNUserNotificationCenter), currentNotificationCenter];
        if center.is_null() {
            return;
        }
        let identifier = ns_string(id);
        let ids: *mut objc::runtime::Object =
            msg_send![class!(NSArray), arrayWithObject: identifier];
        let _: () = msg_send![center, removePendingNotificationRequestsWithIdentifiers: ids];
        let _: () = msg_send![center, removeDeliveredNotificationsWithIdentifiers: ids];
    }
}

#[cfg(target_os = "macos")]
fn macos_cancel_all_notifications() {
    unsafe {
        let center: *mut objc::runtime::Object =
            msg_send![class!(UNUserNotificationCenter), currentNotificationCenter];
        if center.is_null() {
            return;
        }
        let _: () = msg_send![center, removeAllPendingNotificationRequests];
        let _: () = msg_send![center, removeAllDeliveredNotifications];
    }
}

#[cfg(target_os = "macos")]
fn macos_set_badge_count(count: Option<u32>) {
    unsafe {
        let app: *mut objc::runtime::Object = msg_send![class!(NSApplication), sharedApplication];
        if app.is_null() {
            return;
        }
        let dock_tile: *mut objc::runtime::Object = msg_send![app, dockTile];
        if dock_tile.is_null() {
            return;
        }
        let label = count
            .filter(|count| *count > 0)
            .map(|count| ns_string(&count.to_string()))
            .unwrap_or(std::ptr::null_mut());
        let _: () = msg_send![dock_tile, setBadgeLabel: label];
    }
}

#[cfg(any(target_os = "ios", target_os = "macos"))]
fn ns_string(value: &str) -> *mut objc::runtime::Object {
    unsafe {
        let string: *mut objc::runtime::Object = msg_send![class!(NSString), alloc];
        msg_send![
            string,
            initWithBytes: value.as_ptr() as *const c_void
            length: value.len()
            encoding: 4usize
        ]
    }
}

#[cfg(target_os = "macos")]
fn ns_string_to_string(value: *mut objc::runtime::Object) -> Option<String> {
    if value.is_null() {
        return None;
    }
    unsafe {
        let ptr: *const std::os::raw::c_char = msg_send![value, UTF8String];
        (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_string_lossy().into_owned())
    }
}

fn command_exists(name: &str) -> bool {
    std::env::var_os("PATH")
        .and_then(|paths| {
            std::env::split_paths(&paths)
                .map(|path| path.join(name))
                .find(|path| path.is_file())
        })
        .is_some()
}

#[cfg(not(target_os = "ios"))]
fn notification_command_error(error: std::io::Error) -> NotificationError {
    NotificationError::new("host_error", error.to_string())
}

pub(crate) fn register_notification_capabilities(
    async_registry: &mut AsyncRegistry,
    host: Arc<dyn NotificationHost>,
) {
    let request_host = host.clone();
    async_registry.register_operation_capability(
        REQUEST_NOTIFICATION_PERMISSION,
        move |request, _| {
            let host = request_host.clone();
            async move { host.request_permission(request) }
        },
    );

    let settings_host = host.clone();
    async_registry.register_operation_capability(GET_NOTIFICATION_SETTINGS, move |(), _| {
        let host = settings_host.clone();
        async move { host.settings() }
    });

    let show_host = host.clone();
    async_registry.register_operation_capability(SHOW_NOTIFICATION, move |request, _| {
        let host = show_host.clone();
        async move { host.show(request) }
    });

    let schedule_host = host.clone();
    async_registry.register_operation_capability(SCHEDULE_NOTIFICATION, move |request, _| {
        let host = schedule_host.clone();
        async move { host.schedule(request) }
    });

    let cancel_host = host.clone();
    async_registry.register_operation_capability(CANCEL_NOTIFICATION, move |request, _| {
        let host = cancel_host.clone();
        async move { host.cancel(request) }
    });

    let cancel_all_host = host.clone();
    async_registry.register_operation_capability(CANCEL_ALL_NOTIFICATIONS, move |(), _| {
        let host = cancel_all_host.clone();
        async move { host.cancel_all() }
    });

    let badge_host = host.clone();
    async_registry.register_operation_capability(SET_BADGE_COUNT, move |request, _| {
        let host = badge_host.clone();
        async move { host.set_badge_count(request) }
    });

    let push_host = host.clone();
    async_registry.register_operation_capability(REGISTER_PUSH_NOTIFICATIONS, move |request, _| {
        let host = push_host.clone();
        async move { host.register_push(request) }
    });

    async_registry.register_operation_capability(UNREGISTER_PUSH_NOTIFICATIONS, move |(), _| {
        let host = host.clone();
        async move { host.unregister_push() }
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use fission_core::NotificationId;

    #[test]
    fn unsupported_host_reports_permission_without_panicking() {
        let host = UnsupportedNotificationHost;
        let settings = host
            .request_permission(NotificationPermissionRequest::default())
            .unwrap();
        assert_eq!(settings.permission, NotificationPermission::Unsupported);
        assert_eq!(
            host.show(NotificationRequest::default()).unwrap_err().code,
            "unsupported"
        );
    }

    #[test]
    fn memory_host_returns_receipts() {
        let host = MemoryNotificationHost;
        let receipt = host
            .show(NotificationRequest {
                id: NotificationId::new("n1"),
                title: "Title".into(),
                body: "Body".into(),
                ..Default::default()
            })
            .unwrap();
        assert_eq!(receipt.id, NotificationId::new("n1"));
        assert!(receipt.delivered);
    }

    #[test]
    fn native_host_settings_are_honest_about_support() {
        let settings = NativeNotificationHost::native_settings();
        if NativeNotificationHost::supported() {
            assert_eq!(settings.permission, NotificationPermission::Granted);
            assert!(settings.alerts);
            assert!(!settings.push);
        } else {
            assert_eq!(settings.permission, NotificationPermission::Unsupported);
            assert!(!settings.alerts);
        }
    }
}