tilo-notify 0.5.1

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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
//! The Linux backend on the session bus: the notification portal
//! (`org.freedesktop.portal.Notification`, which the Tilo shell and
//! xdg-desktop-portal implement), else `org.freedesktop.Notifications`.
//!
//! Every call runs on one bus thread and is bounded, so a stuck service delays the
//! caller by at most [`CALL_BUDGET`] and never by a D-Bus timeout.

use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;

use zbus::blocking::Connection;
use zbus::zvariant::Value;

use crate::{
    AlarmSchedule, AlarmState, CalendarAlarm, Notification, Notifier, NotifyError, PriorityContact,
    Scheduled, SystemTime,
};

type AlarmStateWire = (String, (u8, u8, u8, i64), Vec<i64>, Vec<i64>, String);

const CALL_BUDGET: Duration = Duration::from_secs(3);

const NOT_TILO: &str = "Only an app Tilo launched may name priority contacts.";

const PORTAL: (&str, &str, &str) = (
    "org.freedesktop.portal.Desktop",
    "/org/freedesktop/portal/desktop",
    "org.freedesktop.portal.Notification",
);
const FREEDESKTOP: (&str, &str, &str) = (
    "org.freedesktop.Notifications",
    "/org/freedesktop/Notifications",
    "org.freedesktop.Notifications",
);

type Job = Box<dyn FnOnce(Option<&Connection>) + Send>;

fn bus() -> Option<&'static Mutex<mpsc::Sender<Job>>> {
    static BUS: OnceLock<Option<Mutex<mpsc::Sender<Job>>>> = OnceLock::new();
    BUS.get_or_init(|| {
        let (tx, rx) = mpsc::channel::<Job>();
        tilo_rt::spawn_thread("tilo-notify-bus", move || {
            let connection = Connection::session()
                .inspect_err(|error| tracing::debug!(%error, "no session bus for notifications"))
                .ok();
            while let Ok(job) = rx.recv() {
                job(connection.as_ref());
            }
        })
        .ok()?;
        Some(Mutex::new(tx))
    })
    .as_ref()
}

fn on_bus<T: Send + 'static>(
    call: impl FnOnce(&Connection) -> Result<T, NotifyError> + Send + 'static,
) -> Result<T, NotifyError> {
    let (reply, answer) = mpsc::channel();
    let job: Job = Box::new(move |connection| {
        let _ = reply.send(connection.map_or(Err(NotifyError::Unavailable), call));
    });
    bus()
        .and_then(|bus| bus.lock().ok()?.send(job).ok())
        .ok_or(NotifyError::Unavailable)?;
    answer.recv_timeout(CALL_BUDGET).unwrap_or_else(|_| {
        Err(NotifyError::Failed(
            "the notification service did not answer".into(),
        ))
    })
}

fn missing(error: &zbus::Error) -> bool {
    let zbus::Error::MethodError(name, _, _) = error else {
        return false;
    };
    matches!(
        name.as_str(),
        "org.freedesktop.DBus.Error.ServiceUnknown"
            | "org.freedesktop.DBus.Error.UnknownInterface"
            | "org.freedesktop.DBus.Error.UnknownMethod"
            | "org.freedesktop.DBus.Error.UnknownObject"
            | "org.freedesktop.DBus.Error.NameHasNoOwner"
    )
}

#[allow(
    clippy::needless_pass_by_value,
    reason = "`map_err` hands it the error by value"
)]
fn failed(error: zbus::Error) -> NotifyError {
    NotifyError::Failed(error.to_string())
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Service {
    Portal,
    Freedesktop,
}

pub(crate) struct SessionNotifier {
    app_id: String,
}

/// Freedesktop ids by tag, so a tag replaces and withdraws its own notification.
/// Shared by every notifier in the process, since the service hands out ids per
/// connection, and there is one.
fn ids() -> &'static Mutex<HashMap<String, u32>> {
    static IDS: OnceLock<Mutex<HashMap<String, u32>>> = OnceLock::new();
    IDS.get_or_init(Mutex::default)
}

fn chosen() -> &'static Mutex<Option<Service>> {
    static CHOSEN: OnceLock<Mutex<Option<Service>>> = OnceLock::new();
    CHOSEN.get_or_init(Mutex::default)
}

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

const PORTAL_ACTION: &str = "tilo-activate";
const DEFAULT_ACTION: &str = "default";
/// The action a notification's button invokes, after this its index.
const BUTTON_ACTION: &str = "tilo-button-";

fn button_action(index: usize) -> String {
    format!("{BUTTON_ACTION}{index}")
}

type Activations = Vec<(String, String)>;

fn activation_ids() -> &'static Mutex<HashMap<u32, Activations>> {
    static IDS: OnceLock<Mutex<HashMap<u32, Activations>>> = OnceLock::new();
    IDS.get_or_init(Mutex::default)
}

fn activations_of(n: &Notification) -> Activations {
    n.activation
        .iter()
        .map(|uri| (DEFAULT_ACTION.to_owned(), uri.clone()))
        .chain(
            n.buttons
                .iter()
                .enumerate()
                .map(|(index, button)| (button_action(index), button.activation.clone())),
        )
        .collect()
}

fn take_shown(id: u32) -> Option<String> {
    let tag = ids()
        .lock()
        .ok()?
        .iter()
        .find(|(_, shown)| **shown == id)
        .map(|(tag, _)| tag.clone())?;
    if let Ok(mut ids) = ids().lock() {
        ids.remove(&tag);
    }
    if let Ok(mut known) = activation_ids().lock() {
        known.remove(&id);
    }
    Some(tag)
}

fn freedesktop_closed(id: u32, code: u32) {
    let Some(tag) = take_shown(id) else {
        return;
    };
    let Some(reason) = crate::CloseReason::from_code(code) else {
        tracing::debug!(%code, %tag, "a notification closed for an unknown reason");
        return;
    };
    crate::closed(&tag, reason);
}

fn listen_for_reports(connection: &Connection) {
    static LISTENING: std::sync::Once = std::sync::Once::new();
    LISTENING.call_once(|| {
        let portal = connection.clone();
        let spawned = tilo_rt::spawn_thread("tilo-notify-portal-clicks", move || {
            let (dest, path, iface) = PORTAL;
            let Ok(proxy) = zbus::blocking::Proxy::new(&portal, dest, path, iface) else {
                return;
            };
            let Ok(signals) = proxy.receive_signal("ActionInvoked") else {
                return;
            };
            for signal in signals {
                let Ok((_app, _id, action, parameter)) =
                    signal
                        .body()
                        .deserialize::<(String, String, String, Vec<zbus::zvariant::OwnedValue>)>()
                else {
                    continue;
                };
                let uri = parameter
                    .first()
                    .and_then(|value| String::try_from(value.try_clone().ok()?).ok());
                if (action == PORTAL_ACTION || action.starts_with(BUTTON_ACTION))
                    && let Some(uri) = uri
                {
                    crate::activated(&uri);
                }
            }
        });
        let freedesktop = connection.clone();
        let spawned = spawned.and_then(|_| {
            tilo_rt::spawn_thread("tilo-notify-clicks", move || {
                let (dest, path, iface) = FREEDESKTOP;
                let Ok(proxy) = zbus::blocking::Proxy::new(&freedesktop, dest, path, iface) else {
                    return;
                };
                let Ok(signals) = proxy.receive_signal("ActionInvoked") else {
                    return;
                };
                for signal in signals {
                    let Ok((id, action)) = signal.body().deserialize::<(u32, String)>() else {
                        continue;
                    };
                    let uri = activation_ids().lock().ok().and_then(|ids| {
                        ids.get(&id)?
                            .iter()
                            .find(|(invoked, _)| *invoked == action)
                            .map(|(_, uri)| uri.clone())
                    });
                    if let Some(uri) = uri {
                        crate::activated(&uri);
                    }
                }
            })
        });
        // A service without the close signal leaves its iterator empty: the report simply
        // never comes.
        let closing = connection.clone();
        let spawned = spawned.and_then(|_| {
            tilo_rt::spawn_thread("tilo-notify-closes", move || {
                let (dest, path, iface) = FREEDESKTOP;
                let Ok(proxy) = zbus::blocking::Proxy::new(&closing, dest, path, iface) else {
                    return;
                };
                let Ok(signals) = proxy.receive_signal("NotificationClosed") else {
                    return;
                };
                for signal in signals {
                    let Ok((id, code)) = signal.body().deserialize::<(u32, u32)>() else {
                        continue;
                    };
                    freedesktop_closed(id, code);
                }
            })
        });
        if let Err(error) = spawned {
            tracing::debug!(%error, "cannot listen for what became of notifications");
        }
    });
}

fn portal_content(n: &Notification) -> HashMap<&'static str, Value<'_>> {
    let mut content: HashMap<&'static str, Value<'_>> = HashMap::new();
    content.insert("title", Value::from(n.title.as_str()));
    content.insert("body", Value::from(n.body.as_str()));
    if let Some(uri) = &n.activation {
        content.insert("default-action", Value::from(PORTAL_ACTION));
        content.insert("default-action-target", Value::from(uri.as_str()));
    }
    if !n.buttons.is_empty() {
        let buttons: Vec<HashMap<&str, Value<'_>>> = n
            .buttons
            .iter()
            .enumerate()
            .map(|(index, button)| {
                HashMap::from([
                    ("label", Value::from(button.label.as_str())),
                    ("action", Value::from(button_action(index))),
                    ("target", Value::from(button.activation.as_str())),
                ])
            })
            .collect();
        content.insert("buttons", Value::from(buttons));
    }
    if n.silent {
        content.insert("sound", Value::from("silent"));
    }
    content
}

fn portal_add(connection: &Connection, n: &Notification) -> zbus::Result<()> {
    let content = portal_content(n);
    let (dest, path, iface) = PORTAL;
    connection
        .call_method(
            Some(dest),
            path,
            Some(iface),
            "AddNotification",
            &(n.tag.as_str(), content),
        )
        .map(drop)
}

fn portal_remove(connection: &Connection, tag: &str) -> zbus::Result<()> {
    let (dest, path, iface) = PORTAL;
    connection
        .call_method(Some(dest), path, Some(iface), "RemoveNotification", &(tag,))
        .map(drop)
}

fn freedesktop_hints(n: &Notification) -> HashMap<&'static str, Value<'static>> {
    let mut hints = HashMap::new();
    // The specification has no warning level; only an error is critical.
    if n.severity == crate::Severity::Error {
        hints.insert("urgency", Value::U8(2));
    }
    if n.silent {
        hints.insert("suppress-sound", Value::Bool(true));
    }
    hints
}

fn freedesktop_notify(connection: &Connection, app: &str, n: &Notification) -> zbus::Result<()> {
    let replaces = ids()
        .lock()
        .ok()
        .and_then(|ids| ids.get(&n.tag).copied())
        .unwrap_or(0);
    let hints = freedesktop_hints(n);
    let activations = activations_of(n);
    let mut actions: Vec<&str> = Vec::new();
    if n.activation.is_some() {
        actions.extend([DEFAULT_ACTION, n.action.as_deref().unwrap_or("Open")]);
    }
    for ((action, _), button) in activations
        .iter()
        .skip(usize::from(n.activation.is_some()))
        .zip(&n.buttons)
    {
        actions.extend([action.as_str(), button.label.as_str()]);
    }
    let (dest, path, iface) = FREEDESKTOP;
    let reply = connection.call_method(
        Some(dest),
        path,
        Some(iface),
        "Notify",
        &(
            app,
            replaces,
            "",
            n.title.as_str(),
            n.body.as_str(),
            actions,
            hints,
            -1_i32,
        ),
    )?;
    let id: u32 = reply.body().deserialize()?;
    if let Ok(mut ids) = ids().lock() {
        ids.insert(n.tag.clone(), id);
    }
    if let Ok(mut known) = activation_ids().lock() {
        if activations.is_empty() {
            known.remove(&id);
        } else {
            known.insert(id, activations);
        }
    }
    Ok(())
}

fn freedesktop_close(connection: &Connection, tag: &str) -> zbus::Result<()> {
    let Some(id) = ids().lock().ok().and_then(|mut ids| ids.remove(tag)) else {
        return Ok(());
    };
    let (dest, path, iface) = FREEDESKTOP;
    connection
        .call_method(Some(dest), path, Some(iface), "CloseNotification", &(id,))
        .map(drop)
}

fn either(
    connection: &Connection,
    portal: impl FnOnce(&Connection) -> zbus::Result<()>,
    freedesktop: impl FnOnce(&Connection) -> zbus::Result<()>,
) -> Result<(), NotifyError> {
    let known = chosen().lock().ok().and_then(|chosen| *chosen);
    if known != Some(Service::Freedesktop) {
        match portal(connection) {
            Ok(()) => {
                remember(Service::Portal);
                return Ok(());
            }
            Err(error) if known.is_none() && missing(&error) => {}
            Err(error) => return Err(failed(error)),
        }
    }
    match freedesktop(connection) {
        Ok(()) => {
            remember(Service::Freedesktop);
            Ok(())
        }
        Err(error) if missing(&error) => Err(NotifyError::Unavailable),
        Err(error) => Err(failed(error)),
    }
}

fn remember(service: Service) {
    if let Ok(mut chosen) = chosen().lock() {
        *chosen = Some(service);
    }
}

fn schedule_notification(
    notification: &Notification,
    at: SystemTime,
    calendar: Vec<(u8, u8, u8, i64, String)>,
) -> Result<(), NotifyError> {
    crate::validate(notification)?;
    let millis = at
        .duration_since(SystemTime::UNIX_EPOCH)
        .ok()
        .and_then(|d| i64::try_from(d.as_millis()).ok())
        .ok_or(NotifyError::Invalid("invalid notification deadline"))?;
    let args = (
        notification.tag.clone(),
        notification.title.clone(),
        notification.body.clone(),
        notification.activation.clone().unwrap_or_default(),
        millis,
        calendar,
    );
    on_bus(move |connection| {
        let (dest, path, iface) = FREEDESKTOP;
        connection
            .call_method(
                Some(dest),
                path,
                Some(iface),
                "XTiloScheduleNotification",
                &args,
            )
            .map(drop)
            .map_err(schedule_error)
    })
}

fn decode_deadline(values: &[i64]) -> Result<Option<SystemTime>, NotifyError> {
    match values {
        [] => Ok(None),
        [millis] => {
            let millis = u64::try_from(*millis)
                .map_err(|_| NotifyError::Invalid("invalid alarm deadline"))?;
            SystemTime::UNIX_EPOCH
                .checked_add(Duration::from_millis(millis))
                .map(Some)
                .ok_or(NotifyError::Invalid("invalid alarm deadline"))
        }
        _ => Err(NotifyError::Invalid("expected at most one alarm deadline")),
    }
}

fn schedule_error(error: zbus::Error) -> NotifyError {
    if missing(&error) {
        NotifyError::Unsupported(crate::Unsupported {
            feature: crate::Feature::Schedule,
            reason: "This desktop does not provide Tilo's durable notification scheduler.",
        })
    } else {
        failed(error)
    }
}

impl Notifier for SessionNotifier {
    fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
        schedule_notification(notification, at, Vec::new())
    }

    fn schedule_alarm(
        &self,
        notification: &Notification,
        at: SystemTime,
        schedule: AlarmSchedule,
    ) -> Result<(), NotifyError> {
        let alarm = schedule.alarm;
        if !alarm.valid() {
            return Err(NotifyError::Invalid("invalid alarm time or weekdays"));
        }
        schedule_notification(
            notification,
            at,
            vec![(
                alarm.hour,
                alarm.minute,
                alarm.weekdays,
                schedule.enabled_at_ms,
                schedule
                    .last_rung
                    .map(|date| date.to_string())
                    .unwrap_or_default(),
            )],
        )
    }

    fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
        on_bus(|connection| {
            let (dest, path, iface) = FREEDESKTOP;
            let response = connection
                .call_method(
                    Some(dest),
                    path,
                    Some(iface),
                    "XTiloScheduledNotifications",
                    &(),
                )
                .map_err(schedule_error)?;
            let rows: Vec<(String, i64)> = response.body().deserialize().map_err(failed)?;
            rows.into_iter()
                .map(|(tag, at)| {
                    let millis = u64::try_from(at)
                        .map_err(|_| NotifyError::Invalid("invalid stored deadline"))?;
                    let at = SystemTime::UNIX_EPOCH
                        .checked_add(Duration::from_millis(millis))
                        .ok_or(NotifyError::Invalid("invalid stored deadline"))?;
                    Ok(Scheduled { tag, at })
                })
                .collect()
        })
    }

    fn alarm_states(&self) -> Result<Vec<AlarmState>, NotifyError> {
        on_bus(|connection| {
            let (dest, path, iface) = FREEDESKTOP;
            let response = connection
                .call_method(Some(dest), path, Some(iface), "XTiloScheduledAlarms", &())
                .map_err(schedule_error)?;
            let rows: Vec<AlarmStateWire> = response.body().deserialize().map_err(failed)?;
            rows.into_iter()
                .map(
                    |(tag, (hour, minute, weekdays, enabled_at_ms), next, last, date)| {
                        let last_rung = if date.is_empty() {
                            None
                        } else {
                            Some(jiff::civil::Date::strptime("%Y-%m-%d", &date).map_err(|_| {
                                NotifyError::Invalid("invalid delivered alarm date")
                            })?)
                        };
                        Ok(AlarmState {
                            tag,
                            alarm: CalendarAlarm {
                                hour,
                                minute,
                                weekdays,
                            },
                            enabled_at_ms,
                            next_at: decode_deadline(&next)?,
                            last_at: decode_deadline(&last)?,
                            last_rung,
                        })
                    },
                )
                .collect()
        })
    }

    fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
        crate::validate_tag(tag)?;
        let tag = tag.to_owned();
        on_bus(move |connection| {
            let (dest, path, iface) = FREEDESKTOP;
            connection
                .call_method(
                    Some(dest),
                    path,
                    Some(iface),
                    "XTiloCancelScheduledNotification",
                    &(tag,),
                )
                .map(drop)
                .map_err(schedule_error)
        })
    }

    fn show(&self, notification: &Notification) -> Result<(), NotifyError> {
        crate::validate(notification)?;
        let notification = notification.clone();
        let app = self.app_id.clone();
        on_bus(move |connection| {
            listen_for_reports(connection);
            either(
                connection,
                |c| portal_add(c, &notification),
                |c| freedesktop_notify(c, &app, &notification),
            )
        })
    }

    fn withdraw(&self, tag: &str) -> Result<(), NotifyError> {
        crate::validate_tag(tag)?;
        let tag = tag.to_owned();
        on_bus(move |connection| {
            either(
                connection,
                |c| portal_remove(c, &tag),
                |c| freedesktop_close(c, &tag),
            )
        })
    }
}

/// The Tilo shell's extension of the notification service: it verifies the sender's
/// process ancestry, so only the app it launched is believed.
pub(crate) fn publish_priority_contacts(
    app_id: &str,
    contacts: &[PriorityContact],
) -> Result<(), NotifyError> {
    if std::env::var("TILO_PACKAGE_ID").as_deref() != Ok(app_id) {
        return Err(NotifyError::Unsupported(crate::Unsupported {
            feature: crate::Feature::PriorityContacts,
            reason: NOT_TILO,
        }));
    }
    let wire: Vec<(String, String, Vec<String>)> = contacts
        .iter()
        .map(|c| (c.id.clone(), c.name.clone(), c.endpoints.clone()))
        .collect();
    on_bus(move |connection| {
        let (dest, path, iface) = FREEDESKTOP;
        connection
            .call_method(
                Some(dest),
                path,
                Some(iface),
                "XTiloReplacePriorityContacts",
                &(wire,),
            )
            .map(drop)
            .map_err(|error| {
                if missing(&error) {
                    NotifyError::Unavailable
                } else {
                    failed(error)
                }
            })
    })
}

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

    #[test]
    fn a_quiet_notification_asks_both_services_for_no_sound() {
        let loud = Notification::new("t", "Title", "");
        assert!(!portal_content(&loud).contains_key("sound"));
        assert!(!freedesktop_hints(&loud).contains_key("suppress-sound"));
        let quiet = loud.quietly();
        assert_eq!(
            portal_content(&quiet).get("sound"),
            Some(&Value::from("silent"))
        );
        assert_eq!(
            freedesktop_hints(&quiet).get("suppress-sound"),
            Some(&Value::Bool(true))
        );
    }

    fn closings(tag: &str) -> Arc<Mutex<Vec<(String, crate::CloseReason)>>> {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&seen);
        crate::set_close_handler(tag, move |tag, reason| {
            sink.lock().unwrap().push((tag.to_owned(), reason));
        });
        seen
    }

    #[test]
    fn what_the_service_closed_is_reported_under_its_tag_and_reason() {
        let seen = closings("closing-test:");
        let id = 41_001;
        if let Ok(mut ids) = ids().lock() {
            ids.insert("closing-test:expired".to_owned(), id);
        }
        if let Ok(mut known) = activation_ids().lock() {
            known.insert(
                id,
                vec![(DEFAULT_ACTION.to_owned(), "tilo-test:open".into())],
            );
        }
        freedesktop_closed(id, 1);
        assert_eq!(
            *seen.lock().unwrap(),
            [(
                "closing-test:expired".to_owned(),
                crate::CloseReason::Expired
            )],
            "an expiry says so"
        );
        assert!(
            !ids().lock().unwrap().contains_key("closing-test:expired"),
            "the tag is forgotten"
        );
        assert!(
            !activation_ids().lock().unwrap().contains_key(&id),
            "its actions are forgotten"
        );
        freedesktop_closed(id, 1);
        assert_eq!(seen.lock().unwrap().len(), 1, "reported once");
    }

    #[test]
    fn a_dismissal_and_an_apps_own_close_are_told_apart() {
        let seen = closings("dismissed-test:");
        for (id, tag, code, reason) in [
            (
                41_011,
                "dismissed-test:person",
                2,
                crate::CloseReason::Dismissed,
            ),
            (41_012, "dismissed-test:app", 3, crate::CloseReason::Closed),
        ] {
            if let Ok(mut ids) = ids().lock() {
                ids.insert(tag.to_owned(), id);
            }
            freedesktop_closed(id, code);
            assert_eq!(
                seen.lock().unwrap().pop(),
                Some((tag.to_owned(), reason)),
                "code {code} under {tag}"
            );
        }
    }

    #[test]
    fn a_close_for_a_notification_shown_elsewhere_or_a_reason_the_spec_leaves_open_says_nothing() {
        let seen = closings("unknown-test:");
        if let Ok(mut ids) = ids().lock() {
            ids.insert("elsewhere-test:1".to_owned(), 41_021);
        }
        freedesktop_closed(41_021, 2);
        freedesktop_closed(41_022, 2);
        if let Ok(mut ids) = ids().lock() {
            ids.insert("unknown-test:1".to_owned(), 41_023);
        }
        freedesktop_closed(41_023, 7);
        assert!(
            seen.lock().unwrap().is_empty(),
            "nothing to report: {:#?}",
            seen.lock().unwrap()
        );
    }
}