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
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
#![cfg_attr(
    test,
    allow(
        clippy::disallowed_methods,
        reason = "in a test these are the assertion, not a hazard"
    )
)]

//! User notifications: one API on Linux, macOS and the web.
//!
//! A [`Notification`] is shown under a stable tag: showing the same tag again
//! replaces it, and [`Notifier::withdraw`] takes it away. Where the platform keeps
//! notifications for an app that is not running, [`Notifier::schedule`] hands one
//! over for later. [`system`] is this target's backend.
//!
//! | Target | Backend |
//! |---|---|
//! | Linux | the connection the app's session serves it ([`service`]); with `host-portals`, the notification portal or `org.freedesktop.Notifications` on the session bus instead |
//! | macOS | `UNUserNotificationCenter`, which needs the app bundle's identifier: an unbundled binary answers [`NotifyError::Unavailable`] |
//! | Web | the Notifications API, while the page is open |

use std::sync::{Arc, Mutex, OnceLock};

mod calendar;
mod caps;
pub use calendar::{AlarmSchedule, CalendarAlarm};
pub mod conformance;
#[cfg(all(target_os = "linux", feature = "host-portals"))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(unix)]
pub mod service;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod web;
#[cfg(windows)]
mod windows;

#[cfg(windows)]
#[doc(hidden)]
pub mod windows_toasts {
    pub use crate::windows::{HostNotifications, ScheduledNotice, register_shortcut};
}

pub use caps::{Availability, Feature, Unsupported, availability, available};
pub use tilo_clock::time::SystemTime;

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct Notification {
    /// A stable tag: showing the same tag again replaces the earlier one. Keep it to
    /// 15 ASCII characters, the shortest limit among the platforms.
    pub tag: String,
    pub title: String,
    pub body: String,
    pub activation: Option<String>,
    pub action: Option<String>,
    pub severity: Severity,
    pub buttons: Vec<NotificationButton>,
    /// Shown without a sound: one asked for so, or a change to one already shown (a
    /// download's progress), which would otherwise sound at every step. macOS plays no
    /// sound for any.
    pub silent: bool,
    /// The app it is from, by the name the person knows it by, when no window of that app sent
    /// it (a mention the session found in Chat's messages).
    pub app: Option<String>,
    /// The person or agent it is from: the notification names them and leads with their face,
    /// where the platform draws one.
    pub from: Option<NotificationSender>,
}

/// Who a notification is from: their name, the stable id their face is drawn from, and whether
/// they are an agent rather than a person.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct NotificationSender {
    pub name: String,
    pub id: String,
    pub agent: bool,
}

pub const MAX_BUTTONS: usize = 3;

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct NotificationButton {
    pub label: String,
    pub activation: String,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub enum Severity {
    #[default]
    Info,
    /// Something went wrong that the person can put right, such as a save that did not
    /// go through.
    Warning,
    Error,
}

impl Notification {
    pub fn new(tag: impl Into<String>, title: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            tag: tag.into(),
            title: title.into(),
            body: body.into(),
            activation: None,
            action: None,
            severity: Severity::Info,
            buttons: Vec::new(),
            silent: false,
            app: None,
            from: None,
        }
    }

    /// From the app called `name`; a blank name says nothing.
    #[must_use]
    pub fn from_app(mut self, name: &str) -> Self {
        let name = name.trim();
        self.app = (!name.is_empty()).then(|| name.to_owned());
        self
    }

    /// From the agent `name`, whose stable id is `id`.
    #[must_use]
    pub fn from_agent(mut self, name: impl Into<String>, id: impl Into<String>) -> Self {
        self.from = Some(NotificationSender {
            name: name.into(),
            id: id.into(),
            agent: true,
        });
        self
    }

    #[must_use]
    pub fn quietly(mut self) -> Self {
        self.silent = true;
        self
    }

    #[must_use]
    pub fn with_button(mut self, label: impl Into<String>, uri: impl Into<String>) -> Self {
        self.buttons.push(NotificationButton {
            label: label.into(),
            activation: uri.into(),
        });
        self
    }

    #[must_use]
    pub fn with_activation(mut self, uri: impl Into<String>) -> Self {
        self.activation = Some(uri.into());
        self
    }

    #[must_use]
    pub fn with_action(mut self, label: impl Into<String>) -> Self {
        self.action = Some(label.into());
        self
    }

    #[must_use]
    pub fn with_severity(mut self, severity: Severity) -> Self {
        self.severity = severity;
        self
    }
}

type ActivationHandler = Arc<dyn Fn(&str) + Send + Sync>;

/// The installed handlers by URI scheme, and the clicks that arrived before theirs
/// was (a click that launched the app). Several apps share a process on a Tilo
/// desktop, so each owns only its scheme's clicks.
#[derive(Default)]
struct Activations {
    handlers: std::collections::HashMap<String, ActivationHandler>,
    pending: Vec<String>,
}

fn scheme_of(uri: &str) -> &str {
    uri.split_once(':').map_or(uri, |(scheme, _)| scheme)
}

fn activations() -> &'static Mutex<Activations> {
    static ACTIVATIONS: OnceLock<Mutex<Activations>> = OnceLock::new();
    ACTIVATIONS.get_or_init(Mutex::default)
}

const PENDING_ACTIVATIONS: usize = 16;

pub fn set_activation_handler(scheme: &str, handler: impl Fn(&str) + Send + Sync + 'static) {
    let handler: ActivationHandler = Arc::new(handler);
    let pending = {
        let Ok(mut activations) = activations().lock() else {
            return;
        };
        activations
            .handlers
            .insert(scheme.to_owned(), handler.clone());
        let (mine, others) = std::mem::take(&mut activations.pending)
            .into_iter()
            .partition(|uri| scheme_of(uri) == scheme);
        activations.pending = others;
        mine
    };
    for uri in pending {
        handler(&uri);
    }
}

pub fn report_activation(uri: &str) {
    if valid_activation(uri) {
        activated(uri);
    }
}

pub(crate) fn activated(uri: &str) {
    let handler = {
        let Ok(mut activations) = activations().lock() else {
            return;
        };
        if let Some(handler) = activations.handlers.get(scheme_of(uri)) {
            handler.clone()
        } else {
            if activations.pending.len() == PENDING_ACTIVATIONS {
                activations.pending.remove(0);
            }
            activations.pending.push(uri.to_owned());
            return;
        }
    };
    handler(uri);
}

/// Why the platform closed a notification the app showed, before the app took it
/// back itself, as `org.freedesktop.Notifications`' `NotificationClosed` names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub enum CloseReason {
    Expired,
    Dismissed,
    /// The app withdrew it, or the platform closed it because the notification was
    /// replaced.
    Closed,
}

impl CloseReason {
    #[must_use]
    pub fn code(self) -> u32 {
        match self {
            Self::Expired => 1,
            Self::Dismissed => 2,
            Self::Closed => 3,
        }
    }

    #[must_use]
    pub fn from_code(code: u32) -> Option<Self> {
        match code {
            1 => Some(Self::Expired),
            2 => Some(Self::Dismissed),
            3 => Some(Self::Closed),
            _ => None,
        }
    }
}

type CloseHandler = Arc<dyn Fn(&str, CloseReason) + Send + Sync>;

/// The installed close handlers by tag prefix. Several apps share a process on a
/// Tilo desktop, so each owns only the tags it names.
fn close_handlers() -> &'static Mutex<std::collections::HashMap<String, CloseHandler>> {
    static HANDLERS: OnceLock<Mutex<std::collections::HashMap<String, CloseHandler>>> =
        OnceLock::new();
    HANDLERS.get_or_init(Mutex::default)
}

/// Call `handler` with the tag and reason of every notification whose tag starts
/// with `prefix` that the platform closes, on whatever thread reports it. Replaces
/// an earlier handler for `prefix`; where prefixes nest, the longest one wins.
///
/// Only some platforms report this ([`Feature::Close`]), and only for notifications
/// they closed themselves: a notification the app withdrew is not reported, and
/// [`CloseReason::Expired`] and [`CloseReason::Closed`] say nothing about the
/// person.
pub fn set_close_handler(
    prefix: &str,
    handler: impl Fn(&str, CloseReason) + Send + Sync + 'static,
) {
    let Ok(mut handlers) = close_handlers().lock() else {
        return;
    };
    handlers.insert(prefix.to_owned(), Arc::new(handler));
}

#[cfg_attr(
    not(target_os = "linux"),
    allow(dead_code, reason = "only the freedesktop backend reports closes")
)]
pub(crate) fn closed(tag: &str, reason: CloseReason) {
    let handler = {
        let Ok(handlers) = close_handlers().lock() else {
            return;
        };
        handlers
            .iter()
            .filter(|(prefix, _)| tag.starts_with(prefix.as_str()))
            .max_by_key(|(prefix, _)| prefix.len())
            .map(|(_, handler)| Arc::clone(handler))
    };
    if let Some(handler) = handler {
        handler(tag, reason);
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotifyError {
    /// This host has no notification service, or this process may not use it (an
    /// unbundled macOS binary).
    Unavailable,
    Unsupported(Unsupported),
    /// The request itself is malformed (an empty tag).
    Invalid(&'static str),
    Failed(String),
}

impl std::fmt::Display for NotifyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unavailable => f.write_str("Notifications aren't available here"),
            Self::Unsupported(unsupported) => unsupported.fmt(f),
            Self::Invalid(reason) => f.write_str(reason),
            Self::Failed(reason) => f.write_str(reason),
        }
    }
}

impl std::error::Error for NotifyError {}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct Scheduled {
    pub tag: String,
    pub at: SystemTime,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AlarmState {
    pub tag: String,
    pub alarm: CalendarAlarm,
    pub enabled_at_ms: i64,
    pub next_at: Option<SystemTime>,
    pub last_at: Option<SystemTime>,
    pub last_rung: Option<jiff::civil::Date>,
}

pub trait Notifier: Send + Sync {
    fn show(&self, notification: &Notification) -> Result<(), NotifyError>;

    fn withdraw(&self, tag: &str) -> Result<(), NotifyError>;

    fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
        let _ = (notification, at);
        Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
    }

    fn schedule_alarm(
        &self,
        notification: &Notification,
        at: SystemTime,
        schedule: AlarmSchedule,
    ) -> Result<(), NotifyError> {
        if !schedule.alarm.valid() {
            return Err(NotifyError::Invalid("invalid alarm time or weekdays"));
        }
        self.schedule(notification, at)
    }

    /// Calendar handoffs and delivered occurrences owned by this app; a host that keeps
    /// only an absolute deadline returns none.
    fn alarm_states(&self) -> Result<Vec<AlarmState>, NotifyError> {
        Ok(Vec::new())
    }

    fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
        Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
    }

    fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
        let _ = tag;
        Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
    }
}

pub(crate) fn validate(notification: &Notification) -> Result<(), NotifyError> {
    validate_tag(&notification.tag)?;
    if notification.title.trim().is_empty() {
        return Err(NotifyError::Invalid("a notification needs a title"));
    }
    if let Some(uri) = &notification.activation
        && !valid_activation(uri)
    {
        return Err(NotifyError::Invalid(
            "a notification's activation must be a URI with a scheme",
        ));
    }
    if notification.buttons.len() > MAX_BUTTONS {
        return Err(NotifyError::Invalid("a notification has too many buttons"));
    }
    for button in &notification.buttons {
        if button.label.trim().is_empty() || button.label.chars().any(char::is_control) {
            return Err(NotifyError::Invalid("a notification's button needs a name"));
        }
        if !valid_activation(&button.activation) {
            return Err(NotifyError::Invalid(
                "a notification button's activation must be a URI with a scheme",
            ));
        }
    }
    Ok(())
}

/// `scheme:rest`, the scheme as RFC 3986 spells it, without control characters or
/// whitespace.
pub fn valid_activation(uri: &str) -> bool {
    let Some((scheme, _)) = uri.split_once(':') else {
        return false;
    };
    let mut letters = scheme.chars();
    letters
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic())
        && letters.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
        && uri.len() <= 2048
        && !uri.chars().any(|c| c.is_control() || c.is_whitespace())
}

pub(crate) fn validate_tag(tag: &str) -> Result<(), NotifyError> {
    if tag.is_empty() {
        return Err(NotifyError::Invalid("a notification needs a tag"));
    }
    if tag.chars().any(char::is_control) {
        return Err(NotifyError::Invalid(
            "a notification tag has control characters",
        ));
    }
    Ok(())
}

/// This target's notifications for the app `app_id`. A desktop attributes
/// notifications to an app, so without an id (a tool, a test, the shell) they are
/// unavailable there; a browser attributes them to the page's origin and needs
/// none.
///
/// An app process the launcher started holds a connection to its session's
/// notifier ([`service`]), and the session attributes what it sends to the app the
/// connection is for: this process needs no id of its own there.
pub fn system(app_id: Option<&str>) -> Arc<dyn Notifier> {
    #[cfg(unix)]
    if let Some(notifier) = service::ServiceNotifier::from_env() {
        return Arc::new(notifier);
    }
    match app_id.filter(|id| !id.is_empty()) {
        Some(app_id) => backend(app_id),
        None if cfg!(all(target_arch = "wasm32", target_os = "unknown")) => backend(""),
        None => unavailable(),
    }
}

#[cfg(target_os = "linux")]
fn backend(app_id: &str) -> Arc<dyn Notifier> {
    #[cfg(feature = "host-portals")]
    {
        Arc::new(linux::SessionNotifier::new(app_id))
    }
    #[cfg(not(feature = "host-portals"))]
    {
        let _ = app_id;
        // An app process inside Tilo, handed no connection, and a build of the SDK that speaks
        // no D-Bus: this host has no notification service to reach, so the app's id names none.
        let _ = app_id;
        unavailable()
    }
}

#[cfg(target_os = "macos")]
fn backend(_app_id: &str) -> Arc<dyn Notifier> {
    macos::notifier()
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
fn backend(_app_id: &str) -> Arc<dyn Notifier> {
    Arc::new(web::PageNotifier)
}

#[cfg(windows)]
fn backend(app_id: &str) -> Arc<dyn Notifier> {
    Arc::new(windows::Toasts::new(app_id))
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "macos",
    windows,
    all(target_arch = "wasm32", target_os = "unknown")
)))]
fn backend(_app_id: &str) -> Arc<dyn Notifier> {
    unavailable()
}

pub fn unavailable() -> Arc<dyn Notifier> {
    Arc::new(UnavailableNotifier)
}

struct UnavailableNotifier;

impl Notifier for UnavailableNotifier {
    fn show(&self, _notification: &Notification) -> Result<(), NotifyError> {
        Err(NotifyError::Unavailable)
    }

    fn withdraw(&self, _tag: &str) -> Result<(), NotifyError> {
        Err(NotifyError::Unavailable)
    }

    fn schedule(&self, _notification: &Notification, _at: SystemTime) -> Result<(), NotifyError> {
        Err(schedule_refusal())
    }

    fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
        Err(schedule_refusal())
    }

    fn cancel_scheduled(&self, _tag: &str) -> Result<(), NotifyError> {
        Err(schedule_refusal())
    }
}

/// Why a host without notifications cannot schedule: this target never can
/// ([`Feature::Schedule`] unsupported), or this host has no service.
fn schedule_refusal() -> NotifyError {
    match availability(Feature::Schedule) {
        Availability::Unsupported(_) => {
            NotifyError::Unsupported(Unsupported::of(Feature::Schedule))
        }
        Availability::Available | Availability::Prompt => NotifyError::Unavailable,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct PriorityContact {
    pub id: String,
    pub name: String,
    pub endpoints: Vec<String>,
}

/// Replace the people whose notifications break through Do Not Disturb with
/// `contacts`. Only the Tilo shell takes such a list, and only from an app it
/// launched as `app_id` ([`Feature::PriorityContacts`]). Blocks on the session bus:
/// call it off the UI thread.
///
/// An app process the launcher started sends it over its session connection, where
/// the connection names the app; `app_id` is checked only on a host that reaches the
/// shell's service directly ([`host-portals`](crate::service)).
pub fn publish_priority_contacts(
    app_id: &str,
    contacts: &[PriorityContact],
) -> Result<(), NotifyError> {
    priority_contacts(app_id, contacts)
}

#[cfg(unix)]
fn priority_contacts(app_id: &str, contacts: &[PriorityContact]) -> Result<(), NotifyError> {
    if service::inherited_service() {
        return service::publish_priority_contacts(contacts);
    }
    #[cfg(all(target_os = "linux", feature = "host-portals"))]
    {
        linux::publish_priority_contacts(app_id, contacts)
    }
    #[cfg(not(all(target_os = "linux", feature = "host-portals")))]
    {
        let _ = app_id;
        Err(NotifyError::Unsupported(Unsupported::of(
            Feature::PriorityContacts,
        )))
    }
}

#[cfg(not(unix))]
fn priority_contacts(_app_id: &str, _contacts: &[PriorityContact]) -> Result<(), NotifyError> {
    Err(NotifyError::Unsupported(Unsupported::of(
        Feature::PriorityContacts,
    )))
}

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

    #[test]
    fn notifiers_that_reach_no_platform_conform() {
        let absent = unavailable();
        let recording = conformance::Recording::default();
        let rows: [(&str, &dyn Notifier); 2] = [
            ("the_unavailable_notifier_conforms", &*absent),
            ("a_recording_notifier_conforms", &recording),
        ];
        for (row, notifier) in rows {
            eprintln!("row: {row}");
            conformance::check_contract(notifier);
        }
    }

    #[test]
    fn the_system_notifier_refuses_malformed_requests_before_the_platform() {
        conformance::check_system(&*system(Some("so.tilo.notify-test")));
        conformance::check_system(&*system(None));
    }

    #[test]
    fn activations_wait_for_a_handler_and_then_reach_it() {
        activated("tilo-test:launch");
        let seen = Arc::new(Mutex::new(Vec::new()));
        let sink = seen.clone();
        activated("tilo-other:launch");
        set_activation_handler("tilo-test", move |uri| {
            sink.lock().unwrap().push(uri.to_owned());
        });
        activated("tilo-test:later");
        activated("tilo-other:later");
        assert_eq!(
            *seen.lock().unwrap(),
            ["tilo-test:launch", "tilo-test:later"],
            "a handler sees only its scheme's clicks"
        );
    }

    #[test]
    fn an_activation_must_be_a_uri() {
        let notification = |uri: &str| Notification::new("t", "Title", "").with_activation(uri);
        assert_eq!(validate(&notification("tilo-clocks:timer/1")), Ok(()));
        for bad in ["no scheme", "1x:y", "tilo:a b", "tilo:\n"] {
            assert!(validate(&notification(bad)).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn buttons_are_named_bounded_and_carry_uris() {
        let notification =
            Notification::new("t", "Title", "").with_button("Pause", "tilo-test:pause");
        assert_eq!(validate(&notification), Ok(()));
        for bad in [
            Notification::new("t", "Title", "").with_button(" ", "tilo-test:pause"),
            Notification::new("t", "Title", "").with_button("Pause", "no scheme"),
            (0..=MAX_BUTTONS).fold(Notification::new("t", "Title", ""), |n, i| {
                n.with_button(format!("B{i}"), "tilo-test:b")
            }),
        ] {
            assert!(validate(&bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn a_close_reason_is_the_specifications_code() {
        for (reason, code) in [
            (CloseReason::Expired, 1),
            (CloseReason::Dismissed, 2),
            (CloseReason::Closed, 3),
        ] {
            assert_eq!(reason.code(), code);
            assert_eq!(CloseReason::from_code(code), Some(reason));
        }
        assert_eq!(CloseReason::from_code(0), None);
        assert_eq!(CloseReason::from_code(4), None);
    }

    #[test]
    fn a_close_reaches_the_handler_that_names_its_tag_and_nothing_else() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let sink = seen.clone();
        set_close_handler("tilo-close-test:", move |tag, reason| {
            sink.lock().unwrap().push((tag.to_owned(), reason));
        });
        closed("tilo-close-other:1", CloseReason::Dismissed);
        closed("tilo-close-test:1", CloseReason::Dismissed);
        closed("tilo-close-test:2", CloseReason::Expired);
        closed("tilo-close-test:3", CloseReason::Closed);
        assert_eq!(
            *seen.lock().unwrap(),
            [
                ("tilo-close-test:1".to_owned(), CloseReason::Dismissed),
                ("tilo-close-test:2".to_owned(), CloseReason::Expired),
                ("tilo-close-test:3".to_owned(), CloseReason::Closed),
            ],
            "every reason reaches it, and only its own tags"
        );
    }

    #[test]
    fn the_longest_matching_prefix_receives_a_close() {
        let narrow = Arc::new(Mutex::new(Vec::new()));
        let wide = Arc::new(Mutex::new(Vec::new()));
        for (prefix, seen) in [
            ("tilo-narrow-test:", Arc::clone(&narrow)),
            ("tilo-narrow-test:one/", Arc::clone(&wide)),
        ] {
            set_close_handler(prefix, move |tag, _| {
                seen.lock().unwrap().push(tag.to_owned());
            });
        }
        closed("tilo-narrow-test:one/1", CloseReason::Dismissed);
        closed("tilo-narrow-test:two/1", CloseReason::Dismissed);
        assert_eq!(*wide.lock().unwrap(), ["tilo-narrow-test:one/1"]);
        assert_eq!(*narrow.lock().unwrap(), ["tilo-narrow-test:two/1"]);
    }
}