nsh_core/notifications.rs
1//! System notifications and the app's badge (`nsh`'s `Notifications`).
2//!
3//! The app asks the core ([`crate::element::notification_permission`],
4//! [`crate::element::show_notification`], ...), and the core asks the
5//! platform with [`Command::Notification`](crate::Command::Notification)s on
6//! the root ([`NotificationCommand`]), which it answers with the root's
7//! [`EventKind::Notification`](crate::EventKind::Notification)
8//! ([`NotificationEvent`] gives its payload's fields). Where
9//! [`Environment::notifications`](crate::platform::Environment::notifications)
10//! is false the core answers itself: `unavailable`, nothing shown.
11//!
12//! A notification the user pressed is reported the same way, without a
13//! request. The press can start the app, so the platform keeps what it has
14//! until the core sends [`NotificationCommand::Listen`], which it does once
15//! the app listens, and the core keeps presses until the app's listener
16//! takes them.
17//!
18//! The badge is a command of its own and is not answered: it works without a
19//! notification on macOS (the Dock's tile) and in an installed web app; iOS
20//! needs the user's permission, and Android has no count to set (launchers
21//! mark an app that has notifications showing).
22
23use crate::element::PropEnum;
24
25/// Whether the user lets the app show notifications.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
27pub enum NotificationPermission {
28 /// The user was not asked yet.
29 #[default]
30 Default,
31 /// Notifications show.
32 Granted,
33 /// The user refused: only the system's settings change that.
34 Denied,
35 /// This platform or build shows none.
36 Unavailable,
37}
38
39impl NotificationPermission {
40 /// Its name in the platforms' answers.
41 pub const fn as_str(self) -> &'static str {
42 match self {
43 Self::Default => "default",
44 Self::Granted => "granted",
45 Self::Denied => "denied",
46 Self::Unavailable => "unavailable",
47 }
48 }
49
50 /// The permission named `name` ([`Self::as_str`]).
51 pub fn from_name(name: &str) -> Option<Self> {
52 [
53 Self::Default,
54 Self::Granted,
55 Self::Denied,
56 Self::Unavailable,
57 ]
58 .into_iter()
59 .find(|p| p.as_str() == name)
60 }
61}
62
63/// A notification to show.
64#[derive(Debug, Clone, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct Notification {
67 /// The app's name for it: showing another with the same id replaces
68 /// it, and a press reports it.
69 pub id: String,
70 /// Its title.
71 pub title: String,
72 /// Its text, `""` for none.
73 pub body: String,
74 /// Shows it without a sound or vibration, as the web's `silent` does.
75 pub silent: bool,
76 /// A sound the app ships, played instead of the system's default: its
77 /// asset path (`sounds/ding.caf`, no `asset:/`). [`Self::silent`] wins
78 /// over it, and a platform that cannot play it plays the default. See
79 /// [`Self::sound`].
80 pub sound: Option<String>,
81}
82
83impl Notification {
84 /// A notification called `id`, titled `title`, with `body`.
85 pub fn new(id: impl Into<String>, title: impl Into<String>, body: impl Into<String>) -> Self {
86 Self {
87 id: id.into(),
88 title: title.into(),
89 body: body.into(),
90 silent: false,
91 sound: None,
92 }
93 }
94
95 /// Shows it without a sound or vibration ([`Self::silent`]).
96 pub fn silent(mut self, silent: bool) -> Self {
97 self.silent = silent;
98 self
99 }
100
101 /// Plays the app's sound `path` (an asset path, `asset:/` optional)
102 /// instead of the system's default ([`Self::sound`]). `nsh package`
103 /// copies the app's sounds where the system plays them from: macOS and
104 /// iOS read `.caf`, `.aiff` and `.wav` files of at most 30 s by file
105 /// name (so names must differ), Android `.ogg`, `.mp3` and `.wav` as raw
106 /// resources (by name, lowercased, other characters as `_`), Linux the
107 /// file itself. Windows (unpackaged) and the web play the default.
108 pub fn sound(mut self, path: impl Into<String>) -> Self {
109 let path: String = path.into();
110 let path = path.strip_prefix("asset:").unwrap_or(&path);
111 let path = path.trim_start_matches('/');
112 self.sound = (!path.is_empty()).then(|| path.to_owned());
113 self
114 }
115
116 /// The sound to play: [`Self::sound`] unless [`Self::silent`].
117 pub fn sound_path(&self) -> Option<&str> {
118 if self.silent {
119 None
120 } else {
121 self.sound.as_deref()
122 }
123 }
124
125 /// The sound's file name, `path`'s last component: Apple platforms
126 /// play it by that, from the app's `Library/Sounds`.
127 pub fn sound_file_name(path: &str) -> &str {
128 path.rsplit('/').next().unwrap_or(path)
129 }
130
131 /// The Android raw resource name of the sound at `path`
132 /// ([`Self::sound_file_name`]).
133 pub fn sound_resource_name(path: &str) -> String {
134 let file = Self::sound_file_name(path);
135 let stem = file.rsplit_once('.').map_or(file, |(stem, _)| stem);
136 let mut name: String = stem
137 .chars()
138 .map(|c| {
139 if c.is_ascii_alphanumeric() || c == '_' {
140 c.to_ascii_lowercase()
141 } else {
142 '_'
143 }
144 })
145 .collect();
146 if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
147 name.insert(0, '_');
148 }
149 name
150 }
151}
152
153/// What the core asks of the platform (on the root,
154/// [`crate::Command::Notification`]). Sent only where
155/// [`Environment::notifications`](crate::platform::Environment::notifications)
156/// holds, but for [`Self::SetBadge`].
157#[derive(Debug, Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub enum NotificationCommand {
160 /// Report the permission as request `id`; with `ask`, ask the user
161 /// first when they were not asked yet.
162 Permission {
163 /// The request.
164 id: u32,
165 /// Show the system's prompt when it has not shown yet.
166 ask: bool,
167 },
168 /// Show `notification` and report whether the system took it as
169 /// request `id`.
170 Show {
171 /// The request.
172 id: u32,
173 /// What to show.
174 notification: Notification,
175 },
176 /// Remove the notification called this, shown or waiting to show.
177 Close(String),
178 /// Remove every notification of the app's, shown or waiting to show,
179 /// those an earlier run of the app left included where the platform
180 /// can reach them.
181 CloseAll,
182 /// Report the notifications the user presses, those pressed before now
183 /// (which started the app) first.
184 Listen,
185 /// Shows `count` on the app's icon; 0 clears it. Where the platform has
186 /// no badge, nothing happens.
187 SetBadge(u32),
188}
189
190/// The fields of a platform's [`EventKind::Notification`](crate::EventKind::Notification)
191/// payload (an [`EventPayload::Map`](crate::EventPayload::Map)).
192#[non_exhaustive]
193pub struct NotificationEvent;
194
195impl NotificationEvent {
196 /// The answered request (a number), with [`Self::PERMISSION`] or
197 /// [`Self::SHOWN`].
198 pub const ID: &'static str = "id";
199 /// The permission's name ([`NotificationPermission::as_str`]).
200 pub const PERMISSION: &'static str = "permission";
201 /// Whether the system took the notification (a boolean).
202 pub const SHOWN: &'static str = "shown";
203 /// The id of the notification the user pressed.
204 pub const PRESSED: &'static str = "pressed";
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210
211 #[test]
212 fn a_sound_is_an_asset_path_that_silent_overrides() {
213 let n = Notification::new("a", "T", "").sound("asset:/sounds/Ding.caf");
214 assert_eq!(n.sound.as_deref(), Some("sounds/Ding.caf"));
215 assert_eq!(n.sound_path(), Some("sounds/Ding.caf"));
216 assert_eq!(n.clone().silent(true).sound_path(), None);
217 assert_eq!(Notification::new("a", "T", "").sound("").sound, None);
218 assert_eq!(Notification::sound_file_name("sounds/Ding.caf"), "Ding.caf");
219 }
220
221 #[test]
222 fn a_sound_s_android_name_is_a_valid_resource_name() {
223 assert_eq!(
224 Notification::sound_resource_name("sounds/New Message.ogg"),
225 "new_message"
226 );
227 assert_eq!(Notification::sound_resource_name("1-up.wav"), "_1_up");
228 assert_eq!(Notification::sound_resource_name("ding"), "ding");
229 }
230}
231
232/// Where Windows keeps an app's notification registration under
233/// `HKEY_CURRENT_USER`, derived from the app's id: `nsh-platform-windows`
234/// writes these keys, and `nsh package`'s uninstaller (and
235/// `--nsh-unregister`) removes them. Not public API.
236#[doc(hidden)]
237pub mod windows_registry {
238 /// The argument a Windows app built with `run_app` takes to remove its
239 /// notification registration and exit, for installers' uninstall steps.
240 pub const UNREGISTER_ARG: &str = "--nsh-unregister";
241
242 /// The key of the app's AppUserModelID registration.
243 pub fn app_key(id: &str) -> String {
244 format!("Software\\Classes\\AppUserModelId\\{id}")
245 }
246
247 /// The COM class that hears toast presses: derived from the id, so each
248 /// app has its own and a run finds what an earlier one registered. A
249 /// version 4 layout, in the RFC 4122 variant.
250 pub fn class_id(id: &str) -> u128 {
251 const PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013B;
252 const BASIS: u128 = 0x6C62_272E_07BB_0142_62B8_2175_6295_C58D;
253 let hash = format!("nsh.notifications:{id}")
254 .bytes()
255 .fold(BASIS, |hash, byte| {
256 (hash ^ u128::from(byte)).wrapping_mul(PRIME)
257 });
258 (hash & !(0xF_u128 << 76) & !(0x3_u128 << 62)) | (0x4_u128 << 76) | (0x2_u128 << 62)
259 }
260
261 /// The class as registry keys write it: `{XXXXXXXX-XXXX-...}`.
262 pub fn class_key(id: &str) -> String {
263 let bits = class_id(id);
264 format!(
265 "{{{:08X}-{:04X}-{:04X}-{:04X}-{:012X}}}",
266 (bits >> 96) as u32,
267 (bits >> 80) as u16,
268 (bits >> 64) as u16,
269 (bits >> 48) as u16,
270 bits & 0xFFFF_FFFF_FFFF,
271 )
272 }
273
274 /// The class's key, whose `LocalServer32` starts the app on a press.
275 pub fn class_registry_key(id: &str) -> String {
276 format!("Software\\Classes\\CLSID\\{}", class_key(id))
277 }
278
279 #[cfg(test)]
280 mod tests {
281 use super::*;
282
283 #[test]
284 fn keys_are_derived_from_the_id() {
285 let class = class_key("com.example.hopper");
286 assert_eq!(class.len(), 38);
287 assert!(class.starts_with('{') && class.ends_with('}'));
288 // Version 4, RFC 4122 variant.
289 assert_eq!(&class[15..16], "4");
290 assert!(matches!(&class[20..21], "8" | "9" | "A" | "B"));
291 assert_eq!(class, class_key("com.example.hopper"));
292 assert_ne!(class, class_key("com.example.other"));
293 assert_eq!(
294 app_key("com.example.hopper"),
295 r"Software\Classes\AppUserModelId\com.example.hopper"
296 );
297 assert_eq!(
298 class_registry_key("com.example.hopper"),
299 format!(r"Software\Classes\CLSID\{class}")
300 );
301 }
302 }
303}