Skip to main content

cranpose_services/
notifier.rs

1//! Local notifications: ask permission and post user-visible notifications.
2//!
3//! The compiled-in default is a no-op; platform backends install a real
4//! notifier through [`set_platform_notifier`] (iOS `UNUserNotificationCenter`,
5//! Android `NotificationManager`, the web Notifications API). Desktop has a
6//! zero-dependency built-in behind the `notifier-native` feature (notify-send
7//! / osascript / PowerShell toast); CI without a notification service simply
8//! drops them.
9
10use std::{
11    cell::RefCell,
12    sync::{Arc, OnceLock},
13};
14
15use cranpose_core::{CompositionLocal, CompositionLocalProvider, compositionLocalOfWithPolicy};
16use cranpose_macros::composable;
17use parking_lot::Mutex;
18
19use crate::registry::ServiceRegistry;
20
21/// A local notification to post.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct NotifyRequest {
24    /// Stable identifier: re-posting with the same id replaces the previous
25    /// notification (used for progress updates).
26    pub id: String,
27    pub title: String,
28    pub body: String,
29    /// Whether this is an ongoing/progress notification (best-effort; platforms
30    /// without ongoing notifications post a normal one).
31    pub ongoing: bool,
32    /// Optional deep-link payload delivered to the app when the user taps it.
33    pub deeplink: Option<String>,
34}
35
36impl NotifyRequest {
37    pub fn new(id: impl Into<String>, title: impl Into<String>, body: impl Into<String>) -> Self {
38        Self {
39            id: id.into(),
40            title: title.into(),
41            body: body.into(),
42            ongoing: false,
43            deeplink: None,
44        }
45    }
46
47    pub fn ongoing(mut self, ongoing: bool) -> Self {
48        self.ongoing = ongoing;
49        self
50    }
51
52    pub fn with_deeplink(mut self, deeplink: impl Into<String>) -> Self {
53        self.deeplink = Some(deeplink.into());
54        self
55    }
56}
57
58/// Posts local notifications. Installed by the platform backend; the default is
59/// a no-op.
60pub trait Notifier: Send + Sync {
61    /// Request permission to show notifications (idempotent; safe to call more
62    /// than once).
63    fn request_permission(&self);
64    /// Post (or replace, by id) a local notification.
65    fn notify(&self, request: NotifyRequest);
66    /// Remove a delivered or pending notification by id.
67    fn cancel(&self, id: &str);
68}
69
70pub type NotifierRef = Arc<dyn Notifier>;
71
72fn pending_deeplink_slot() -> &'static Mutex<Option<String>> {
73    static SLOT: OnceLock<Mutex<Option<String>>> = OnceLock::new();
74    SLOT.get_or_init(|| Mutex::new(None))
75}
76
77/// Record the deep-link payload of a notification the user just tapped. Called
78/// by the platform backend's notification delegate; the app drains it via
79/// [`take_notification_deeplink`].
80pub fn push_notification_deeplink(link: String) {
81    *pending_deeplink_slot().lock() = Some(link);
82}
83
84/// Take (and clear) the deep-link payload of the most recently tapped
85/// notification, if any. Polled by the app's deep-link handling.
86pub fn take_notification_deeplink() -> Option<String> {
87    pending_deeplink_slot().lock().take()
88}
89
90#[cfg(not(all(
91    feature = "notifier-native",
92    not(target_arch = "wasm32"),
93    not(target_os = "android"),
94    not(target_os = "ios")
95)))]
96struct NoopNotifier;
97
98#[cfg(not(all(
99    feature = "notifier-native",
100    not(target_arch = "wasm32"),
101    not(target_os = "android"),
102    not(target_os = "ios")
103)))]
104impl Notifier for NoopNotifier {
105    fn request_permission(&self) {}
106    fn notify(&self, _request: NotifyRequest) {}
107    fn cancel(&self, _id: &str) {}
108}
109
110static PLATFORM_NOTIFIER: ServiceRegistry<dyn Notifier> = ServiceRegistry::new();
111static DEFAULT_NOTIFIER: OnceLock<NotifierRef> = OnceLock::new();
112
113struct PlatformNotifier;
114
115fn registered_notifier() -> NotifierRef {
116    PLATFORM_NOTIFIER
117        .get_or_warn("notifier")
118        .unwrap_or_else(|| {
119            #[cfg(all(
120                feature = "notifier-native",
121                not(target_arch = "wasm32"),
122                not(target_os = "android"),
123                not(target_os = "ios")
124            ))]
125            {
126                Arc::new(desktop::DesktopNotifier)
127            }
128            #[cfg(not(all(
129                feature = "notifier-native",
130                not(target_arch = "wasm32"),
131                not(target_os = "android"),
132                not(target_os = "ios")
133            )))]
134            {
135                Arc::new(NoopNotifier)
136            }
137        })
138}
139
140impl Notifier for PlatformNotifier {
141    fn request_permission(&self) {
142        registered_notifier().request_permission();
143    }
144
145    fn notify(&self, request: NotifyRequest) {
146        registered_notifier().notify(request);
147    }
148
149    fn cancel(&self, id: &str) {
150        registered_notifier().cancel(id);
151    }
152}
153
154pub fn set_platform_notifier(notifier: NotifierRef) {
155    PLATFORM_NOTIFIER.set(notifier);
156}
157
158pub fn clear_platform_notifier() {
159    PLATFORM_NOTIFIER.clear();
160}
161
162pub fn default_notifier() -> NotifierRef {
163    DEFAULT_NOTIFIER
164        .get_or_init(|| Arc::new(PlatformNotifier))
165        .clone()
166}
167
168#[cfg(all(
169    feature = "notifier-native",
170    not(target_arch = "wasm32"),
171    not(target_os = "android"),
172    not(target_os = "ios")
173))]
174mod desktop {
175    use std::process::{Command, Stdio};
176
177    use super::{Notifier, NotifyRequest};
178
179    pub(super) struct DesktopNotifier;
180
181    #[cfg(target_os = "linux")]
182    fn numeric_id(id: &str) -> u32 {
183        let mut hash: u32 = 0x811c_9dc5;
184        for byte in id.as_bytes() {
185            hash ^= u32::from(*byte);
186            hash = hash.wrapping_mul(0x0100_0193);
187        }
188        hash.max(1)
189    }
190
191    fn spawn_silent(mut command: Command) {
192        let _ = command
193            .stdin(Stdio::null())
194            .stdout(Stdio::null())
195            .stderr(Stdio::null())
196            .spawn();
197    }
198
199    impl Notifier for DesktopNotifier {
200        fn request_permission(&self) {}
201
202        fn notify(&self, request: NotifyRequest) {
203            #[cfg(target_os = "linux")]
204            {
205                let mut command = crate::windowless_command("notify-send");
206                command
207                    .arg("--replace-id")
208                    .arg(numeric_id(&request.id).to_string())
209                    .arg("--app-name")
210                    .arg("cranpose")
211                    .arg(&request.title)
212                    .arg(&request.body);
213                spawn_silent(command);
214            }
215            #[cfg(target_os = "macos")]
216            {
217                let script = format!(
218                    "display notification \"{}\" with title \"{}\"",
219                    request.body.replace('\\', "\\\\").replace('"', "\\\""),
220                    request.title.replace('\\', "\\\\").replace('"', "\\\"")
221                );
222                let mut command = crate::windowless_command("osascript");
223                command.arg("-e").arg(script);
224                spawn_silent(command);
225            }
226            #[cfg(target_os = "windows")]
227            {
228                let script = format!(
229                    "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null; \
230                     $t = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02); \
231                     $n = $t.GetElementsByTagName('text'); \
232                     $n.Item(0).AppendChild($t.CreateTextNode('{}')) > $null; \
233                     $n.Item(1).AppendChild($t.CreateTextNode('{}')) > $null; \
234                     [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('cranpose').Show([Windows.UI.Notifications.ToastNotification]::new($t))",
235                    request.title.replace('\'', "''"),
236                    request.body.replace('\'', "''")
237                );
238                let mut command = crate::windowless_command("powershell");
239                command.arg("-NoProfile").arg("-Command").arg(script);
240                spawn_silent(command);
241            }
242        }
243
244        #[allow(unused_variables)]
245        fn cancel(&self, id: &str) {
246            #[cfg(target_os = "linux")]
247            {
248                let mut command = crate::windowless_command("gdbus");
249                command.args([
250                    "call",
251                    "--session",
252                    "--dest",
253                    "org.freedesktop.Notifications",
254                    "--object-path",
255                    "/org/freedesktop/Notifications",
256                    "--method",
257                    "org.freedesktop.Notifications.CloseNotification",
258                ]);
259                command.arg(numeric_id(id).to_string());
260                spawn_silent(command);
261            }
262        }
263    }
264}
265
266pub fn local_notifier() -> CompositionLocal<NotifierRef> {
267    thread_local! {
268        static LOCAL_NOTIFIER: RefCell<Option<CompositionLocal<NotifierRef>>> = const { RefCell::new(None) };
269    }
270
271    LOCAL_NOTIFIER.with(|cell| {
272        let mut local = cell.borrow_mut();
273        local
274            .get_or_insert_with(|| compositionLocalOfWithPolicy(default_notifier, Arc::ptr_eq))
275            .clone()
276    })
277}
278
279#[composable]
280pub fn ProvideNotifier(content: impl FnOnce()) {
281    let notifier = cranpose_core::remember(default_notifier).with(|state| state.clone());
282    let local = local_notifier();
283    CompositionLocalProvider(vec![local.provides(notifier)], move || {
284        content();
285    });
286}
287
288#[cfg(test)]
289#[path = "tests/notifier_tests.rs"]
290mod tests;