tilo-notify 0.5.0

User notifications on Linux, macOS and the web: what an app shows its session over its connection, and what each platform keeps.
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
//! Native Windows notifications for installed desktop apps.
//!
//! The installer must register a Start menu shortcut with the same app ID. Successful
//! submission does not mean Windows displayed a banner, since notification settings
//! stay under the person's control.

#![allow(
    clippy::missing_errors_doc,
    clippy::arithmetic_side_effects,
    clippy::needless_pass_by_value,
    clippy::cmp_owned,
    clippy::borrow_as_ptr,
    reason = "moved unchanged from tilo-host's Windows toasts, which no Windows lint job covers yet"
)]

use std::{marker::PhantomData, path::Path, rc::Rc, sync::OnceLock};

use tilo_clock::time::{Duration, SystemTime, UNIX_EPOCH};
use windows::Data::Xml::Dom::XmlDocument;
use windows::UI::Notifications::{
    NotificationSetting, ScheduledToastNotification, ToastNotification, ToastNotificationManager,
    ToastNotifier,
};
use windows::Win32::Foundation::{PROPERTYKEY, RPC_E_CHANGED_MODE};
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
use windows::Win32::System::Com::{
    CLSCTX_INPROC_SERVER, CoCreateInstance, CoIncrementMTAUsage, IPersistFile, STGM_READWRITE,
};
use windows::Win32::System::Variant::VT_LPWSTR;
use windows::Win32::System::WinRT::{RO_INIT_SINGLETHREADED, RoInitialize, RoUninitialize};
use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore;
use windows::Win32::UI::Shell::{IShellLinkW, SHStrDupW, ShellLink};
use windows::core::{GUID, HSTRING, Interface, PCWSTR};

struct Apartment {
    acquired: bool,
    // Initialization must be balanced on its original thread.
    _thread: PhantomData<Rc<()>>,
}

impl Apartment {
    fn new() -> windows::core::Result<Self> {
        // windows-core caches agile activation factories for the process lifetime, so keep
        // the COM runtime alive just as long, even when the last thread-local STA guard goes
        // away between notifications.
        static RUNTIME: OnceLock<Result<(), windows::core::HRESULT>> = OnceLock::new();
        let initialized = RUNTIME.get_or_init(|| {
            // SAFETY: once per process. The opaque usage cookie is intentionally
            // retained until process exit, just like the binding's factory cache.
            unsafe { CoIncrementMTAUsage() }
                .map(|_cookie| ())
                .map_err(|error| error.code())
        });
        if let Err(code) = initialized {
            return Err(windows::core::Error::from_hresult(*code));
        }
        // SAFETY: thread-bound guard balances each successful initialization.
        let result = unsafe { RoInitialize(RO_INIT_SINGLETHREADED) };
        let acquired = match result {
            Ok(()) => true,
            Err(error) if error.code() == RPC_E_CHANGED_MODE => false,
            Err(error) => return Err(error),
        };
        Ok(Self {
            acquired,
            _thread: PhantomData,
        })
    }
}

impl Drop for Apartment {
    fn drop(&mut self) {
        if self.acquired {
            // SAFETY: !Send guard, one uninitialize per successful initialize.
            unsafe { RoUninitialize() };
        }
    }
}

pub struct HostNotifications {
    notifier: ToastNotifier,
    app_id: HSTRING,
    activation_uri: Option<String>,
    _apartment: Apartment,
}

#[derive(Debug)]
pub struct ScheduledNotice {
    pub id: String,
    pub delivery_time: SystemTime,
}

impl HostNotifications {
    pub fn new(app_id: &str) -> windows::core::Result<Self> {
        let apartment = Apartment::new()?;
        let app_id = HSTRING::from(app_id);
        let notifier = ToastNotificationManager::CreateToastNotifierWithId(&app_id)?;
        Ok(Self {
            notifier,
            app_id,
            activation_uri: None,
            _apartment: apartment,
        })
    }

    /// Let Windows open the application's registered URI when an alert is
    /// activated, including after the submitting process has exited.
    pub fn with_protocol_activation(mut self, uri: &str) -> windows::core::Result<Self> {
        let uri = url::Url::parse(uri).map_err(|_| {
            windows::core::Error::from_hresult(windows::Win32::Foundation::E_INVALIDARG)
        })?;
        self.activation_uri = Some(uri.into());
        Ok(self)
    }

    fn notification_xml(&self, title: &str, body: &str) -> windows::core::Result<XmlDocument> {
        let activation = self
            .activation_uri
            .as_deref()
            .map_or_else(String::new, |uri| {
                format!(
                    " activationType=\"protocol\" launch=\"{}\"",
                    escape_xml(uri)
                )
            });
        let xml = XmlDocument::new()?;
        xml.LoadXml(&HSTRING::from(format!(
            "<toast{activation}><visual><binding template=\"ToastGeneric\"><text>{}</text><text>{}</text></binding></visual></toast>",
            escape_xml(title), escape_xml(body)
        )))?;
        Ok(xml)
    }

    /// A stable tag replaces a previous submission instead of duplicating it.
    /// Windows allows at most 16 UTF-16 code units per tag.
    pub fn show(&self, tag: &str, title: &str, body: &str) -> windows::core::Result<()> {
        if tag.is_empty() || tag.encode_utf16().count() > 16 {
            return Err(windows::core::Error::from_hresult(
                windows::Win32::Foundation::E_INVALIDARG,
            ));
        }
        let xml = self.notification_xml(title, body)?;
        let toast = ToastNotification::CreateToastNotification(&xml)?;
        toast.SetTag(&HSTRING::from(tag))?;
        toast.SetGroup(&HSTRING::from("tilo"))?;
        self.notifier.Show(&toast)
    }

    /// Windows can return `ERROR_NOT_FOUND` before this app's first submission.
    /// Do not use this query as a prerequisite for `show`.
    pub fn enabled(&self) -> windows::core::Result<bool> {
        Ok(self.notifier.Setting()? == NotificationSetting::Enabled)
    }

    /// Inspect only this application's notification history.
    pub fn history(&self) -> windows::core::Result<Vec<(String, String)>> {
        let history = ToastNotificationManager::History()?.GetHistoryWithId(&self.app_id)?;
        history
            .into_iter()
            .map(|toast| {
                Ok((
                    toast.Tag()?.to_string(),
                    toast.Content()?.GetXml()?.to_string(),
                ))
            })
            .collect()
    }

    pub fn remove(&self, tag: &str) -> windows::core::Result<()> {
        ToastNotificationManager::History()?.RemoveGroupedTagWithId(
            &HSTRING::from(tag),
            &HSTRING::from("tilo"),
            &self.app_id,
        )
    }

    /// Persist a one-time notification in Windows' scheduler. An identical
    /// request is a no-op; changing its time or contents replaces that ID.
    /// IDs allow 15 UTF-16 units: this Windows host counts the terminator in
    /// the documented 16-character limit (unlike ordinary toast tags).
    pub fn schedule(
        &self,
        id: &str,
        title: &str,
        body: &str,
        delivery_time: SystemTime,
    ) -> windows::core::Result<()> {
        if id.is_empty() || id.encode_utf16().count() > 15 {
            return Err(windows::core::Error::from_hresult(
                windows::Win32::Foundation::E_INVALIDARG,
            ));
        }
        let delivery = to_windows_time(delivery_time)?;
        let xml = self.notification_xml(title, body)?;
        let expected_xml = xml.GetXml()?;
        for pending in self.pending()? {
            if pending.Id()?.to_string() == id {
                if pending.DeliveryTime()? == delivery
                    && pending.Content()?.GetXml()? == expected_xml
                {
                    return Ok(());
                }
                self.notifier.RemoveFromSchedule(&pending)?;
            }
        }
        let toast = ScheduledToastNotification::CreateScheduledToastNotification(&xml, delivery)?;
        toast.SetId(&HSTRING::from(id))?;
        toast.SetTag(&HSTRING::from(id))?;
        toast.SetGroup(&HSTRING::from("tilo"))?;
        self.notifier.AddToSchedule(&toast)
    }

    pub fn scheduled(&self) -> windows::core::Result<Vec<ScheduledNotice>> {
        self.pending()?
            .into_iter()
            .map(|notice| {
                Ok(ScheduledNotice {
                    id: notice.Id()?.to_string(),
                    delivery_time: from_windows_time(notice.DeliveryTime()?)?,
                })
            })
            .collect()
    }

    pub fn cancel_schedule(&self, id: &str) -> windows::core::Result<()> {
        for notice in self.pending()? {
            if notice.Id()?.to_string() == id {
                self.notifier.RemoveFromSchedule(&notice)?;
            }
        }
        Ok(())
    }

    fn pending(&self) -> windows::core::Result<Vec<ScheduledToastNotification>> {
        match self.notifier.Setting() {
            Ok(_) => {}
            Err(error)
                if error.code() == windows::Win32::Foundation::ERROR_NOT_FOUND.to_hresult() =>
            {
                // Unpackaged apps must submit once before using the scheduler.
                // Register silently, with an expiry as a backstop if removal fails.
                let xml = XmlDocument::new()?;
                xml.LoadXml(&HSTRING::from("<toast><visual><binding template=\"ToastGeneric\"><text>Tilo</text></binding></visual></toast>"))?;
                let toast = ToastNotification::CreateToastNotification(&xml)?;
                toast.SetTag(&HSTRING::from("tilo-register"))?;
                toast.SetGroup(&HSTRING::from("tilo"))?;
                toast.SetSuppressPopup(true)?;
                let expiry: windows::Foundation::IReference<windows::Foundation::DateTime> =
                    windows::Foundation::PropertyValue::CreateDateTime(to_windows_time(
                        tilo_clock::wall() + Duration::from_secs(15),
                    )?)?
                    .cast()?;
                toast.SetExpirationTime(&expiry)?;
                self.notifier.Show(&toast)?;
                self.remove("tilo-register")?;
            }
            Err(error) => return Err(error),
        }
        Ok(self
            .notifier
            .GetScheduledToastNotifications()?
            .into_iter()
            .collect())
    }
}

/// The Windows [`crate::Notifier`]: toasts under the installer-registered
/// app id. Each call opens its own notifier: the COM apartment it needs is
/// bound to the calling thread.
pub(crate) struct Toasts {
    app_id: String,
}

impl Toasts {
    pub(crate) fn new(app_id: &str) -> Self {
        Self {
            app_id: app_id.to_owned(),
        }
    }

    fn host(&self) -> Result<HostNotifications, crate::NotifyError> {
        HostNotifications::new(&self.app_id).map_err(failed)
    }
}

fn failed(error: windows::core::Error) -> crate::NotifyError {
    crate::NotifyError::Failed(error.to_string())
}

impl crate::Notifier for Toasts {
    fn show(&self, notification: &crate::Notification) -> Result<(), crate::NotifyError> {
        crate::validate(notification)?;
        self.host()?
            .show(&notification.tag, &notification.title, &notification.body)
            .map_err(failed)
    }

    fn withdraw(&self, tag: &str) -> Result<(), crate::NotifyError> {
        crate::validate_tag(tag)?;
        self.host()?.remove(tag).map_err(failed)
    }

    fn schedule(
        &self,
        notification: &crate::Notification,
        at: SystemTime,
    ) -> Result<(), crate::NotifyError> {
        crate::validate(notification)?;
        self.host()?
            .schedule(
                &notification.tag,
                &notification.title,
                &notification.body,
                at,
            )
            .map_err(failed)
    }

    fn scheduled(&self) -> Result<Vec<crate::Scheduled>, crate::NotifyError> {
        Ok(self
            .host()?
            .scheduled()
            .map_err(failed)?
            .into_iter()
            .map(|notice| crate::Scheduled {
                tag: notice.id,
                at: notice.delivery_time,
            })
            .collect())
    }

    fn cancel_scheduled(&self, tag: &str) -> Result<(), crate::NotifyError> {
        crate::validate_tag(tag)?;
        self.host()?.cancel_schedule(tag).map_err(failed)
    }
}

const WINDOWS_UNIX_EPOCH_TICKS: i64 = 116_444_736_000_000_000;

fn to_windows_time(time: SystemTime) -> windows::core::Result<windows::Foundation::DateTime> {
    let ticks = time
        .duration_since(UNIX_EPOCH)
        .ok()
        .and_then(|duration| i64::try_from(duration.as_nanos() / 100).ok())
        .and_then(|ticks| ticks.checked_add(WINDOWS_UNIX_EPOCH_TICKS))
        .ok_or_else(|| {
            windows::core::Error::from_hresult(windows::Win32::Foundation::E_INVALIDARG)
        })?;
    Ok(windows::Foundation::DateTime {
        UniversalTime: ticks,
    })
}

fn from_windows_time(time: windows::Foundation::DateTime) -> windows::core::Result<SystemTime> {
    let ticks = time
        .UniversalTime
        .checked_sub(WINDOWS_UNIX_EPOCH_TICKS)
        .and_then(|ticks| u64::try_from(ticks).ok())
        .ok_or_else(|| {
            windows::core::Error::from_hresult(windows::Win32::Foundation::E_INVALIDARG)
        })?;
    UNIX_EPOCH
        .checked_add(
            Duration::from_secs(ticks / 10_000_000)
                + Duration::from_nanos((ticks % 10_000_000) * 100),
        )
        .ok_or_else(|| windows::core::Error::from_hresult(windows::Win32::Foundation::E_INVALIDARG))
}

fn escape_xml(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

/// Install a shortcut using the same identity used by `HostNotifications`.
/// Called by the Windows installer, never as a side effect of showing a toast.
pub fn register_shortcut(
    app_id: &str,
    title: &str,
    executable: &Path,
    shortcut: &Path,
) -> windows::core::Result<()> {
    let _apartment = Apartment::new()?;
    let existing = shortcut.exists();
    let executable = HSTRING::from(executable.as_os_str());
    let shortcut = HSTRING::from(shortcut.as_os_str());
    let app_id = HSTRING::from(app_id);
    // SAFETY: initialized apartment; all referenced UTF-16 buffers outlive calls.
    // PROPVARIANT's Drop calls PropVariantClear. SHStrDupW allocates the string
    // with the matching COM allocator; never borrow an HSTRING's storage here.
    unsafe {
        let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?;
        let file: IPersistFile = link.cast()?;
        if existing {
            file.Load(PCWSTR(shortcut.as_ptr()), STGM_READWRITE)?;
        }
        link.SetPath(&executable)?;
        link.SetDescription(&HSTRING::from(title))?;
        let store: IPropertyStore = link.cast()?;
        let mut value = PROPVARIANT::default();
        (*value.Anonymous.Anonymous).vt = VT_LPWSTR;
        (*value.Anonymous.Anonymous).Anonymous.pwszVal = SHStrDupW(&app_id)?;
        let key = PROPERTYKEY {
            fmtid: GUID::from_u128(0x9f4c2855_9f79_4b39_a8d0_e1d42de1d5f3),
            pid: 5,
        };
        store.SetValue(&key, &value)?;
        store.Commit()?;
        file.Save(PCWSTR(shortcut.as_ptr()), true)?;
    }
    Ok(())
}

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

    #[test]
    fn notification_hosts_registrations_and_schedules_are_owned_and_exact() {
        {
            for _ in 0..4 {
                std::thread::spawn(|| {
                    let host = HostNotifications::new("so.tilo.clocks").unwrap();
                    let xml = host.notification_xml("Timer", "Ready").unwrap();
                    assert!(xml.GetXml().unwrap().to_string().contains("Ready"));
                })
                .join()
                .unwrap();
            }
        }
        {
            let directory = tempfile::tempdir().unwrap();
            let shortcut = directory.path().join("Clocks test.lnk");
            for id in [
                "so.tilo.test.first",
                "so.tilo.test.second",
                "so.tilo.test.third",
            ] {
                register_shortcut(
                    id,
                    "Tilo test",
                    &std::env::current_exe().unwrap(),
                    &shortcut,
                )
                .unwrap();
                let _apartment = Apartment::new().unwrap();
                // SAFETY: thread apartment initialized, all interfaces owned locally.
                unsafe {
                    let link: IShellLinkW =
                        CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).unwrap();
                    let file: IPersistFile = link.cast().unwrap();
                    file.Load(&HSTRING::from(shortcut.as_os_str()), STGM_READWRITE)
                        .unwrap();
                    let store: IPropertyStore = link.cast().unwrap();
                    let key = PROPERTYKEY {
                        fmtid: GUID::from_u128(0x9f4c2855_9f79_4b39_a8d0_e1d42de1d5f3),
                        pid: 5,
                    };
                    let value = store.GetValue(&key).unwrap();
                    assert_eq!(
                        windows::core::BSTR::try_from(&value).unwrap().to_string(),
                        id
                    );
                }
            }
        }
        {
            let time = UNIX_EPOCH + Duration::new(1_800_000_000, 123_456_700);
            assert_eq!(
                from_windows_time(to_windows_time(time).unwrap()).unwrap(),
                time
            );
            assert!(to_windows_time(UNIX_EPOCH - Duration::from_secs(1)).is_err());
            assert!(
                from_windows_time(windows::Foundation::DateTime {
                    UniversalTime: i64::MIN
                })
                .is_err()
            );
        }
    }

    #[test]
    fn notification_content_is_preserved_without_markup_or_xml_injection() {
        {
            let uri = "tilo-clocks:open?one=1&two=2";
            let host = HostNotifications::new("so.tilo.clocks")
                .unwrap()
                .with_protocol_activation(uri)
                .unwrap();
            let xml = host.notification_xml("Tea <ready>", "A & B").unwrap();
            let root = xml.DocumentElement().unwrap();
            assert_eq!(
                root.GetAttribute(&HSTRING::from("activationType"))
                    .unwrap()
                    .to_string(),
                "protocol"
            );
            assert_eq!(
                root.GetAttribute(&HSTRING::from("launch"))
                    .unwrap()
                    .to_string(),
                uri
            );
            assert_eq!(
                xml.GetElementsByTagName(&HSTRING::from("text"))
                    .unwrap()
                    .Length()
                    .unwrap(),
                2
            );
            drop(root);
            drop(xml);
            assert!(host.with_protocol_activation("not a URI").is_err());
        }
        {
            let _apartment = Apartment::new().unwrap();
            let value = "Tea & <coffee> \"ready\" 'now'";
            let xml = XmlDocument::new().unwrap();
            xml.LoadXml(&HSTRING::from(format!(
                "<text>{}</text>",
                escape_xml(value)
            )))
            .unwrap();
            assert_eq!(
                xml.DocumentElement()
                    .unwrap()
                    .InnerText()
                    .unwrap()
                    .to_string(),
                value
            );
        }
    }
}