Skip to main content

strata_platform/
notifications.rs

1//! Cross-platform rich native OS notifications (`org.freedesktop.Notifications` over pure-Rust
2//! D-Bus on Linux, `UNUserNotificationCenter`/osascript on macOS, WinRT Toast on Windows)
3//! plus an in-memory deterministic recorder for headless CI testing.
4
5use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
6use std::sync::{Mutex, OnceLock};
7
8/// Semantic priority level of an OS notification.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum NotificationUrgency {
11    Low = 0,
12    #[default]
13    Normal = 1,
14    Critical = 2,
15}
16
17/// Interactive action button attached to a desktop notification.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct NotificationAction {
20    pub id: String,
21    pub label: String,
22}
23
24/// Full immutable record of a dispatched notification (also captured in recorder/CI mode).
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct NotificationRecord {
27    pub id: u32,
28    pub app_name: String,
29    pub title: String,
30    pub subtitle: Option<String>,
31    pub body: String,
32    pub icon: Option<String>,
33    pub urgency: NotificationUrgency,
34    pub category: Option<String>,
35    pub timeout_ms: i32,
36    pub replaces_id: u32,
37    pub actions: Vec<NotificationAction>,
38}
39
40static RECORDER_ENABLED: AtomicBool = AtomicBool::new(false);
41static NEXT_MOCK_ID: AtomicU32 = AtomicU32::new(1);
42static RECORDED: OnceLock<Mutex<Vec<NotificationRecord>>> = OnceLock::new();
43static CLOSED_IDS: OnceLock<Mutex<Vec<u32>>> = OnceLock::new();
44
45fn recorded_store() -> &'static Mutex<Vec<NotificationRecord>> {
46    RECORDED.get_or_init(|| Mutex::new(Vec::new()))
47}
48
49fn closed_store() -> &'static Mutex<Vec<u32>> {
50    CLOSED_IDS.get_or_init(|| Mutex::new(Vec::new()))
51}
52
53/// Enables or disables deterministic in-memory notification recording (skips live OS popups in CI).
54pub fn enable_notification_recorder(enabled: bool) {
55    RECORDER_ENABLED.store(enabled, Ordering::SeqCst);
56}
57
58/// Drains and returns all notifications captured while the recorder was enabled.
59pub fn take_recorded_notifications() -> Vec<NotificationRecord> {
60    recorded_store()
61        .lock()
62        .map(|mut v| std::mem::take(&mut *v))
63        .unwrap_or_default()
64}
65
66/// Drains and returns all notification IDs dismissed while the recorder was enabled.
67pub fn take_closed_notification_ids() -> Vec<u32> {
68    closed_store()
69        .lock()
70        .map(|mut v| std::mem::take(&mut *v))
71        .unwrap_or_default()
72}
73
74/// Fluent builder for rich cross-platform native OS notifications.
75#[derive(Debug, Clone)]
76pub struct NotificationBuilder {
77    app_name: String,
78    title: String,
79    subtitle: Option<String>,
80    body: String,
81    icon: Option<String>,
82    urgency: NotificationUrgency,
83    category: Option<String>,
84    timeout_ms: i32,
85    replaces_id: u32,
86    actions: Vec<NotificationAction>,
87}
88
89impl NotificationBuilder {
90    pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
91        Self {
92            app_name: "Strata".into(),
93            title: title.into(),
94            subtitle: None,
95            body: body.into(),
96            icon: None,
97            urgency: NotificationUrgency::Normal,
98            category: None,
99            timeout_ms: 5000,
100            replaces_id: 0,
101            actions: Vec::new(),
102        }
103    }
104
105    pub fn app_name(mut self, name: impl Into<String>) -> Self {
106        self.app_name = name.into();
107        self
108    }
109
110    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
111        self.subtitle = Some(subtitle.into());
112        self
113    }
114
115    pub fn icon(mut self, icon: impl Into<String>) -> Self {
116        self.icon = Some(icon.into());
117        self
118    }
119
120    pub fn urgency(mut self, urgency: NotificationUrgency) -> Self {
121        self.urgency = urgency;
122        self
123    }
124
125    pub fn category(mut self, category: impl Into<String>) -> Self {
126        self.category = Some(category.into());
127        self
128    }
129
130    pub fn timeout_ms(mut self, ms: i32) -> Self {
131        self.timeout_ms = ms;
132        self
133    }
134
135    pub fn replaces_id(mut self, id: u32) -> Self {
136        self.replaces_id = id;
137        self
138    }
139
140    pub fn action(mut self, id: impl Into<String>, label: impl Into<String>) -> Self {
141        self.actions.push(NotificationAction {
142            id: id.into(),
143            label: label.into(),
144        });
145        self
146    }
147
148    /// Dispatches the notification to the host OS notification daemon and returns its assigned ID.
149    pub fn send(self) -> Result<u32, String> {
150        if RECORDER_ENABLED.load(Ordering::SeqCst) {
151            let id = if self.replaces_id > 0 {
152                self.replaces_id
153            } else {
154                NEXT_MOCK_ID.fetch_add(1, Ordering::SeqCst)
155            };
156            if let Ok(mut store) = recorded_store().lock() {
157                store.push(NotificationRecord {
158                    id,
159                    app_name: self.app_name,
160                    title: self.title,
161                    subtitle: self.subtitle,
162                    body: self.body,
163                    icon: self.icon,
164                    urgency: self.urgency,
165                    category: self.category,
166                    timeout_ms: self.timeout_ms,
167                    replaces_id: self.replaces_id,
168                    actions: self.actions,
169                });
170            }
171            return Ok(id);
172        }
173
174        #[cfg(target_os = "linux")]
175        {
176            let action_pairs: Vec<(&str, &str)> = self
177                .actions
178                .iter()
179                .map(|a| (a.id.as_str(), a.label.as_str()))
180                .collect();
181            let full_body = match &self.subtitle {
182                Some(sub) => format!("{sub}\n{}", self.body),
183                None => self.body.clone(),
184            };
185            crate::dbus::show_desktop_notification_rich(
186                &self.app_name,
187                self.replaces_id,
188                self.icon.as_deref(),
189                &self.title,
190                &full_body,
191                &action_pairs,
192                self.urgency as u8,
193                self.category.as_deref(),
194                self.timeout_ms,
195            )
196        }
197
198        #[cfg(target_os = "macos")]
199        {
200            let esc = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"");
201            let mut script = format!(
202                "display notification \"{}\" with title \"{}\"",
203                esc(&self.body),
204                esc(&self.title)
205            );
206            if let Some(ref sub) = self.subtitle {
207                script.push_str(&format!(" subtitle \"{}\"", esc(sub)));
208            }
209            let status = std::process::Command::new("osascript")
210                .args(["-e", &script])
211                .status()
212                .map_err(|e| format!("macOS notification failed: {e}"))?;
213            if status.success() {
214                Ok(NEXT_MOCK_ID.fetch_add(1, Ordering::SeqCst))
215            } else {
216                Err("osascript notification exited non-zero".into())
217            }
218        }
219
220        #[cfg(windows)]
221        {
222            let esc = |s: &str| s.replace('\'', "''").replace('<', "&lt;").replace('>', "&gt;");
223            let ps = format!(
224                "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null; \
225                 $xml = New-Object Windows.Data.Xml.Dom.XmlDocument; \
226                 $xml.LoadXml('<toast><visual><binding template=\"ToastGeneric\"><text>{}</text><text>{}</text></binding></visual></toast>'); \
227                 $toast = New-Object Windows.UI.Notifications.ToastNotification $xml; \
228                 [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{}').Show($toast);",
229                esc(&self.title),
230                esc(&self.body),
231                esc(&self.app_name)
232            );
233            let status = std::process::Command::new("powershell")
234                .args(["-NoProfile", "-Command", &ps])
235                .status()
236                .map_err(|e| format!("Windows Toast failed: {e}"))?;
237            if status.success() {
238                Ok(NEXT_MOCK_ID.fetch_add(1, Ordering::SeqCst))
239            } else {
240                Err("Windows Toast exited non-zero".into())
241            }
242        }
243
244        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
245        {
246            Ok(NEXT_MOCK_ID.fetch_add(1, Ordering::SeqCst))
247        }
248    }
249}
250
251/// Dismisses a previously dispatched desktop notification by ID.
252pub fn close_notification(id: u32) -> Result<(), String> {
253    if RECORDER_ENABLED.load(Ordering::SeqCst) {
254        if let Ok(mut closed) = closed_store().lock() {
255            closed.push(id);
256        }
257        return Ok(());
258    }
259
260    #[cfg(target_os = "linux")]
261    {
262        crate::dbus::close_desktop_notification(id)
263    }
264
265    #[cfg(not(target_os = "linux"))]
266    {
267        let _ = id;
268        Ok(())
269    }
270}