Skip to main content

tilo_notify/
lib.rs

1#![cfg_attr(
2    test,
3    allow(
4        clippy::disallowed_methods,
5        reason = "in a test these are the assertion, not a hazard"
6    )
7)]
8
9//! User notifications: one API on Linux, macOS and the web.
10//!
11//! A [`Notification`] is shown under a stable tag: showing the same tag again
12//! replaces it, and [`Notifier::withdraw`] takes it away. Where the platform keeps
13//! notifications for an app that is not running, [`Notifier::schedule`] hands one
14//! over for later. [`system`] is this target's backend.
15//!
16//! | Target | Backend |
17//! |---|---|
18//! | 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 |
19//! | macOS | `UNUserNotificationCenter`, which needs the app bundle's identifier: an unbundled binary answers [`NotifyError::Unavailable`] |
20//! | Web | the Notifications API, while the page is open |
21
22use std::sync::{Arc, Mutex, OnceLock};
23
24mod calendar;
25mod caps;
26pub use calendar::{AlarmSchedule, CalendarAlarm};
27pub mod conformance;
28#[cfg(all(target_os = "linux", feature = "host-portals"))]
29mod linux;
30#[cfg(target_os = "macos")]
31mod macos;
32#[cfg(unix)]
33pub mod service;
34#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
35mod web;
36#[cfg(windows)]
37mod windows;
38
39#[cfg(windows)]
40#[doc(hidden)]
41pub mod windows_toasts {
42    pub use crate::windows::{HostNotifications, ScheduledNotice, register_shortcut};
43}
44
45pub use caps::{Availability, Feature, Unsupported, availability, available};
46pub use tilo_clock::time::SystemTime;
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
50pub struct Notification {
51    /// A stable tag: showing the same tag again replaces the earlier one. Keep it to
52    /// 15 ASCII characters, the shortest limit among the platforms.
53    pub tag: String,
54    pub title: String,
55    pub body: String,
56    pub activation: Option<String>,
57    pub action: Option<String>,
58    pub severity: Severity,
59    pub buttons: Vec<NotificationButton>,
60    /// Shown without a sound: one asked for so, or a change to one already shown (a
61    /// download's progress), which would otherwise sound at every step. macOS plays no
62    /// sound for any.
63    pub silent: bool,
64    /// The app it is from, by the name the person knows it by, when no window of that app sent
65    /// it (a mention the session found in Chat's messages).
66    pub app: Option<String>,
67    /// The person or agent it is from: the notification names them and leads with their face,
68    /// where the platform draws one.
69    pub from: Option<NotificationSender>,
70}
71
72/// Who a notification is from: their name, the stable id their face is drawn from, and whether
73/// they are an agent rather than a person.
74#[derive(Debug, Clone, PartialEq, Eq)]
75#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
76pub struct NotificationSender {
77    pub name: String,
78    pub id: String,
79    pub agent: bool,
80}
81
82pub const MAX_BUTTONS: usize = 3;
83
84#[derive(Debug, Clone, PartialEq, Eq)]
85#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
86pub struct NotificationButton {
87    pub label: String,
88    pub activation: String,
89}
90
91#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
92#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
93pub enum Severity {
94    #[default]
95    Info,
96    /// Something went wrong that the person can put right, such as a save that did not
97    /// go through.
98    Warning,
99    Error,
100}
101
102impl Notification {
103    pub fn new(tag: impl Into<String>, title: impl Into<String>, body: impl Into<String>) -> Self {
104        Self {
105            tag: tag.into(),
106            title: title.into(),
107            body: body.into(),
108            activation: None,
109            action: None,
110            severity: Severity::Info,
111            buttons: Vec::new(),
112            silent: false,
113            app: None,
114            from: None,
115        }
116    }
117
118    /// From the app called `name`; a blank name says nothing.
119    #[must_use]
120    pub fn from_app(mut self, name: &str) -> Self {
121        let name = name.trim();
122        self.app = (!name.is_empty()).then(|| name.to_owned());
123        self
124    }
125
126    /// From the agent `name`, whose stable id is `id`.
127    #[must_use]
128    pub fn from_agent(mut self, name: impl Into<String>, id: impl Into<String>) -> Self {
129        self.from = Some(NotificationSender {
130            name: name.into(),
131            id: id.into(),
132            agent: true,
133        });
134        self
135    }
136
137    #[must_use]
138    pub fn quietly(mut self) -> Self {
139        self.silent = true;
140        self
141    }
142
143    #[must_use]
144    pub fn with_button(mut self, label: impl Into<String>, uri: impl Into<String>) -> Self {
145        self.buttons.push(NotificationButton {
146            label: label.into(),
147            activation: uri.into(),
148        });
149        self
150    }
151
152    #[must_use]
153    pub fn with_activation(mut self, uri: impl Into<String>) -> Self {
154        self.activation = Some(uri.into());
155        self
156    }
157
158    #[must_use]
159    pub fn with_action(mut self, label: impl Into<String>) -> Self {
160        self.action = Some(label.into());
161        self
162    }
163
164    #[must_use]
165    pub fn with_severity(mut self, severity: Severity) -> Self {
166        self.severity = severity;
167        self
168    }
169}
170
171type ActivationHandler = Arc<dyn Fn(&str) + Send + Sync>;
172
173/// The installed handlers by URI scheme, and the clicks that arrived before theirs
174/// was (a click that launched the app). Several apps share a process on a Tilo
175/// desktop, so each owns only its scheme's clicks.
176#[derive(Default)]
177struct Activations {
178    handlers: std::collections::HashMap<String, ActivationHandler>,
179    pending: Vec<String>,
180}
181
182fn scheme_of(uri: &str) -> &str {
183    uri.split_once(':').map_or(uri, |(scheme, _)| scheme)
184}
185
186fn activations() -> &'static Mutex<Activations> {
187    static ACTIVATIONS: OnceLock<Mutex<Activations>> = OnceLock::new();
188    ACTIVATIONS.get_or_init(Mutex::default)
189}
190
191const PENDING_ACTIVATIONS: usize = 16;
192
193pub fn set_activation_handler(scheme: &str, handler: impl Fn(&str) + Send + Sync + 'static) {
194    let handler: ActivationHandler = Arc::new(handler);
195    let pending = {
196        let Ok(mut activations) = activations().lock() else {
197            return;
198        };
199        activations
200            .handlers
201            .insert(scheme.to_owned(), handler.clone());
202        let (mine, others) = std::mem::take(&mut activations.pending)
203            .into_iter()
204            .partition(|uri| scheme_of(uri) == scheme);
205        activations.pending = others;
206        mine
207    };
208    for uri in pending {
209        handler(&uri);
210    }
211}
212
213pub fn report_activation(uri: &str) {
214    if valid_activation(uri) {
215        activated(uri);
216    }
217}
218
219pub(crate) fn activated(uri: &str) {
220    let handler = {
221        let Ok(mut activations) = activations().lock() else {
222            return;
223        };
224        if let Some(handler) = activations.handlers.get(scheme_of(uri)) {
225            handler.clone()
226        } else {
227            if activations.pending.len() == PENDING_ACTIVATIONS {
228                activations.pending.remove(0);
229            }
230            activations.pending.push(uri.to_owned());
231            return;
232        }
233    };
234    handler(uri);
235}
236
237/// Why the platform closed a notification the app showed, before the app took it
238/// back itself, as `org.freedesktop.Notifications`' `NotificationClosed` names it.
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
241pub enum CloseReason {
242    Expired,
243    Dismissed,
244    /// The app withdrew it, or the platform closed it because the notification was
245    /// replaced.
246    Closed,
247}
248
249impl CloseReason {
250    #[must_use]
251    pub fn code(self) -> u32 {
252        match self {
253            Self::Expired => 1,
254            Self::Dismissed => 2,
255            Self::Closed => 3,
256        }
257    }
258
259    #[must_use]
260    pub fn from_code(code: u32) -> Option<Self> {
261        match code {
262            1 => Some(Self::Expired),
263            2 => Some(Self::Dismissed),
264            3 => Some(Self::Closed),
265            _ => None,
266        }
267    }
268}
269
270type CloseHandler = Arc<dyn Fn(&str, CloseReason) + Send + Sync>;
271
272/// The installed close handlers by tag prefix. Several apps share a process on a
273/// Tilo desktop, so each owns only the tags it names.
274fn close_handlers() -> &'static Mutex<std::collections::HashMap<String, CloseHandler>> {
275    static HANDLERS: OnceLock<Mutex<std::collections::HashMap<String, CloseHandler>>> =
276        OnceLock::new();
277    HANDLERS.get_or_init(Mutex::default)
278}
279
280/// Call `handler` with the tag and reason of every notification whose tag starts
281/// with `prefix` that the platform closes, on whatever thread reports it. Replaces
282/// an earlier handler for `prefix`; where prefixes nest, the longest one wins.
283///
284/// Only some platforms report this ([`Feature::Close`]), and only for notifications
285/// they closed themselves: a notification the app withdrew is not reported, and
286/// [`CloseReason::Expired`] and [`CloseReason::Closed`] say nothing about the
287/// person.
288pub fn set_close_handler(
289    prefix: &str,
290    handler: impl Fn(&str, CloseReason) + Send + Sync + 'static,
291) {
292    let Ok(mut handlers) = close_handlers().lock() else {
293        return;
294    };
295    handlers.insert(prefix.to_owned(), Arc::new(handler));
296}
297
298#[cfg_attr(
299    not(target_os = "linux"),
300    allow(dead_code, reason = "only the freedesktop backend reports closes")
301)]
302pub(crate) fn closed(tag: &str, reason: CloseReason) {
303    let handler = {
304        let Ok(handlers) = close_handlers().lock() else {
305            return;
306        };
307        handlers
308            .iter()
309            .filter(|(prefix, _)| tag.starts_with(prefix.as_str()))
310            .max_by_key(|(prefix, _)| prefix.len())
311            .map(|(_, handler)| Arc::clone(handler))
312    };
313    if let Some(handler) = handler {
314        handler(tag, reason);
315    }
316}
317
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub enum NotifyError {
320    /// This host has no notification service, or this process may not use it (an
321    /// unbundled macOS binary).
322    Unavailable,
323    Unsupported(Unsupported),
324    /// The request itself is malformed (an empty tag).
325    Invalid(&'static str),
326    Failed(String),
327}
328
329impl std::fmt::Display for NotifyError {
330    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331        match self {
332            Self::Unavailable => f.write_str("Notifications aren't available here"),
333            Self::Unsupported(unsupported) => unsupported.fmt(f),
334            Self::Invalid(reason) => f.write_str(reason),
335            Self::Failed(reason) => f.write_str(reason),
336        }
337    }
338}
339
340impl std::error::Error for NotifyError {}
341
342#[derive(Debug, Clone, PartialEq, Eq)]
343#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
344pub struct Scheduled {
345    pub tag: String,
346    pub at: SystemTime,
347}
348
349#[derive(Clone, Debug, PartialEq, Eq)]
350pub struct AlarmState {
351    pub tag: String,
352    pub alarm: CalendarAlarm,
353    pub enabled_at_ms: i64,
354    pub next_at: Option<SystemTime>,
355    pub last_at: Option<SystemTime>,
356    pub last_rung: Option<jiff::civil::Date>,
357}
358
359pub trait Notifier: Send + Sync {
360    fn show(&self, notification: &Notification) -> Result<(), NotifyError>;
361
362    fn withdraw(&self, tag: &str) -> Result<(), NotifyError>;
363
364    fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
365        let _ = (notification, at);
366        Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
367    }
368
369    fn schedule_alarm(
370        &self,
371        notification: &Notification,
372        at: SystemTime,
373        schedule: AlarmSchedule,
374    ) -> Result<(), NotifyError> {
375        if !schedule.alarm.valid() {
376            return Err(NotifyError::Invalid("invalid alarm time or weekdays"));
377        }
378        self.schedule(notification, at)
379    }
380
381    /// Calendar handoffs and delivered occurrences owned by this app; a host that keeps
382    /// only an absolute deadline returns none.
383    fn alarm_states(&self) -> Result<Vec<AlarmState>, NotifyError> {
384        Ok(Vec::new())
385    }
386
387    fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
388        Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
389    }
390
391    fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
392        let _ = tag;
393        Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
394    }
395}
396
397pub(crate) fn validate(notification: &Notification) -> Result<(), NotifyError> {
398    validate_tag(&notification.tag)?;
399    if notification.title.trim().is_empty() {
400        return Err(NotifyError::Invalid("a notification needs a title"));
401    }
402    if let Some(uri) = &notification.activation
403        && !valid_activation(uri)
404    {
405        return Err(NotifyError::Invalid(
406            "a notification's activation must be a URI with a scheme",
407        ));
408    }
409    if notification.buttons.len() > MAX_BUTTONS {
410        return Err(NotifyError::Invalid("a notification has too many buttons"));
411    }
412    for button in &notification.buttons {
413        if button.label.trim().is_empty() || button.label.chars().any(char::is_control) {
414            return Err(NotifyError::Invalid("a notification's button needs a name"));
415        }
416        if !valid_activation(&button.activation) {
417            return Err(NotifyError::Invalid(
418                "a notification button's activation must be a URI with a scheme",
419            ));
420        }
421    }
422    Ok(())
423}
424
425/// `scheme:rest`, the scheme as RFC 3986 spells it, without control characters or
426/// whitespace.
427pub fn valid_activation(uri: &str) -> bool {
428    let Some((scheme, _)) = uri.split_once(':') else {
429        return false;
430    };
431    let mut letters = scheme.chars();
432    letters
433        .next()
434        .is_some_and(|first| first.is_ascii_alphabetic())
435        && letters.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
436        && uri.len() <= 2048
437        && !uri.chars().any(|c| c.is_control() || c.is_whitespace())
438}
439
440pub(crate) fn validate_tag(tag: &str) -> Result<(), NotifyError> {
441    if tag.is_empty() {
442        return Err(NotifyError::Invalid("a notification needs a tag"));
443    }
444    if tag.chars().any(char::is_control) {
445        return Err(NotifyError::Invalid(
446            "a notification tag has control characters",
447        ));
448    }
449    Ok(())
450}
451
452/// This target's notifications for the app `app_id`. A desktop attributes
453/// notifications to an app, so without an id (a tool, a test, the shell) they are
454/// unavailable there; a browser attributes them to the page's origin and needs
455/// none.
456///
457/// An app process the launcher started holds a connection to its session's
458/// notifier ([`service`]), and the session attributes what it sends to the app the
459/// connection is for: this process needs no id of its own there.
460pub fn system(app_id: Option<&str>) -> Arc<dyn Notifier> {
461    #[cfg(unix)]
462    if let Some(notifier) = service::ServiceNotifier::from_env() {
463        return Arc::new(notifier);
464    }
465    match app_id.filter(|id| !id.is_empty()) {
466        Some(app_id) => backend(app_id),
467        None if cfg!(all(target_arch = "wasm32", target_os = "unknown")) => backend(""),
468        None => unavailable(),
469    }
470}
471
472#[cfg(target_os = "linux")]
473fn backend(app_id: &str) -> Arc<dyn Notifier> {
474    #[cfg(feature = "host-portals")]
475    {
476        Arc::new(linux::SessionNotifier::new(app_id))
477    }
478    #[cfg(not(feature = "host-portals"))]
479    {
480        let _ = app_id;
481        // An app process inside Tilo, handed no connection, and a build of the SDK that speaks
482        // no D-Bus: this host has no notification service to reach, so the app's id names none.
483        let _ = app_id;
484        unavailable()
485    }
486}
487
488#[cfg(target_os = "macos")]
489fn backend(_app_id: &str) -> Arc<dyn Notifier> {
490    macos::notifier()
491}
492
493#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
494fn backend(_app_id: &str) -> Arc<dyn Notifier> {
495    Arc::new(web::PageNotifier)
496}
497
498#[cfg(windows)]
499fn backend(app_id: &str) -> Arc<dyn Notifier> {
500    Arc::new(windows::Toasts::new(app_id))
501}
502
503#[cfg(not(any(
504    target_os = "linux",
505    target_os = "macos",
506    windows,
507    all(target_arch = "wasm32", target_os = "unknown")
508)))]
509fn backend(_app_id: &str) -> Arc<dyn Notifier> {
510    unavailable()
511}
512
513pub fn unavailable() -> Arc<dyn Notifier> {
514    Arc::new(UnavailableNotifier)
515}
516
517struct UnavailableNotifier;
518
519impl Notifier for UnavailableNotifier {
520    fn show(&self, _notification: &Notification) -> Result<(), NotifyError> {
521        Err(NotifyError::Unavailable)
522    }
523
524    fn withdraw(&self, _tag: &str) -> Result<(), NotifyError> {
525        Err(NotifyError::Unavailable)
526    }
527
528    fn schedule(&self, _notification: &Notification, _at: SystemTime) -> Result<(), NotifyError> {
529        Err(schedule_refusal())
530    }
531
532    fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
533        Err(schedule_refusal())
534    }
535
536    fn cancel_scheduled(&self, _tag: &str) -> Result<(), NotifyError> {
537        Err(schedule_refusal())
538    }
539}
540
541/// Why a host without notifications cannot schedule: this target never can
542/// ([`Feature::Schedule`] unsupported), or this host has no service.
543fn schedule_refusal() -> NotifyError {
544    match availability(Feature::Schedule) {
545        Availability::Unsupported(_) => {
546            NotifyError::Unsupported(Unsupported::of(Feature::Schedule))
547        }
548        Availability::Available | Availability::Prompt => NotifyError::Unavailable,
549    }
550}
551
552#[derive(Debug, Clone, PartialEq, Eq)]
553#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
554pub struct PriorityContact {
555    pub id: String,
556    pub name: String,
557    pub endpoints: Vec<String>,
558}
559
560/// Replace the people whose notifications break through Do Not Disturb with
561/// `contacts`. Only the Tilo shell takes such a list, and only from an app it
562/// launched as `app_id` ([`Feature::PriorityContacts`]). Blocks on the session bus:
563/// call it off the UI thread.
564///
565/// An app process the launcher started sends it over its session connection, where
566/// the connection names the app; `app_id` is checked only on a host that reaches the
567/// shell's service directly ([`host-portals`](crate::service)).
568pub fn publish_priority_contacts(
569    app_id: &str,
570    contacts: &[PriorityContact],
571) -> Result<(), NotifyError> {
572    priority_contacts(app_id, contacts)
573}
574
575#[cfg(unix)]
576fn priority_contacts(app_id: &str, contacts: &[PriorityContact]) -> Result<(), NotifyError> {
577    if service::inherited_service() {
578        return service::publish_priority_contacts(contacts);
579    }
580    #[cfg(all(target_os = "linux", feature = "host-portals"))]
581    {
582        linux::publish_priority_contacts(app_id, contacts)
583    }
584    #[cfg(not(all(target_os = "linux", feature = "host-portals")))]
585    {
586        let _ = app_id;
587        Err(NotifyError::Unsupported(Unsupported::of(
588            Feature::PriorityContacts,
589        )))
590    }
591}
592
593#[cfg(not(unix))]
594fn priority_contacts(_app_id: &str, _contacts: &[PriorityContact]) -> Result<(), NotifyError> {
595    Err(NotifyError::Unsupported(Unsupported::of(
596        Feature::PriorityContacts,
597    )))
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603
604    #[test]
605    fn notifiers_that_reach_no_platform_conform() {
606        let absent = unavailable();
607        let recording = conformance::Recording::default();
608        let rows: [(&str, &dyn Notifier); 2] = [
609            ("the_unavailable_notifier_conforms", &*absent),
610            ("a_recording_notifier_conforms", &recording),
611        ];
612        for (row, notifier) in rows {
613            eprintln!("row: {row}");
614            conformance::check_contract(notifier);
615        }
616    }
617
618    #[test]
619    fn the_system_notifier_refuses_malformed_requests_before_the_platform() {
620        conformance::check_system(&*system(Some("so.tilo.notify-test")));
621        conformance::check_system(&*system(None));
622    }
623
624    #[test]
625    fn activations_wait_for_a_handler_and_then_reach_it() {
626        activated("tilo-test:launch");
627        let seen = Arc::new(Mutex::new(Vec::new()));
628        let sink = seen.clone();
629        activated("tilo-other:launch");
630        set_activation_handler("tilo-test", move |uri| {
631            sink.lock().unwrap().push(uri.to_owned());
632        });
633        activated("tilo-test:later");
634        activated("tilo-other:later");
635        assert_eq!(
636            *seen.lock().unwrap(),
637            ["tilo-test:launch", "tilo-test:later"],
638            "a handler sees only its scheme's clicks"
639        );
640    }
641
642    #[test]
643    fn an_activation_must_be_a_uri() {
644        let notification = |uri: &str| Notification::new("t", "Title", "").with_activation(uri);
645        assert_eq!(validate(&notification("tilo-clocks:timer/1")), Ok(()));
646        for bad in ["no scheme", "1x:y", "tilo:a b", "tilo:\n"] {
647            assert!(validate(&notification(bad)).is_err(), "{bad:?}");
648        }
649    }
650
651    #[test]
652    fn buttons_are_named_bounded_and_carry_uris() {
653        let notification =
654            Notification::new("t", "Title", "").with_button("Pause", "tilo-test:pause");
655        assert_eq!(validate(&notification), Ok(()));
656        for bad in [
657            Notification::new("t", "Title", "").with_button(" ", "tilo-test:pause"),
658            Notification::new("t", "Title", "").with_button("Pause", "no scheme"),
659            (0..=MAX_BUTTONS).fold(Notification::new("t", "Title", ""), |n, i| {
660                n.with_button(format!("B{i}"), "tilo-test:b")
661            }),
662        ] {
663            assert!(validate(&bad).is_err(), "{bad:?}");
664        }
665    }
666
667    #[test]
668    fn a_close_reason_is_the_specifications_code() {
669        for (reason, code) in [
670            (CloseReason::Expired, 1),
671            (CloseReason::Dismissed, 2),
672            (CloseReason::Closed, 3),
673        ] {
674            assert_eq!(reason.code(), code);
675            assert_eq!(CloseReason::from_code(code), Some(reason));
676        }
677        assert_eq!(CloseReason::from_code(0), None);
678        assert_eq!(CloseReason::from_code(4), None);
679    }
680
681    #[test]
682    fn a_close_reaches_the_handler_that_names_its_tag_and_nothing_else() {
683        let seen = Arc::new(Mutex::new(Vec::new()));
684        let sink = seen.clone();
685        set_close_handler("tilo-close-test:", move |tag, reason| {
686            sink.lock().unwrap().push((tag.to_owned(), reason));
687        });
688        closed("tilo-close-other:1", CloseReason::Dismissed);
689        closed("tilo-close-test:1", CloseReason::Dismissed);
690        closed("tilo-close-test:2", CloseReason::Expired);
691        closed("tilo-close-test:3", CloseReason::Closed);
692        assert_eq!(
693            *seen.lock().unwrap(),
694            [
695                ("tilo-close-test:1".to_owned(), CloseReason::Dismissed),
696                ("tilo-close-test:2".to_owned(), CloseReason::Expired),
697                ("tilo-close-test:3".to_owned(), CloseReason::Closed),
698            ],
699            "every reason reaches it, and only its own tags"
700        );
701    }
702
703    #[test]
704    fn the_longest_matching_prefix_receives_a_close() {
705        let narrow = Arc::new(Mutex::new(Vec::new()));
706        let wide = Arc::new(Mutex::new(Vec::new()));
707        for (prefix, seen) in [
708            ("tilo-narrow-test:", Arc::clone(&narrow)),
709            ("tilo-narrow-test:one/", Arc::clone(&wide)),
710        ] {
711            set_close_handler(prefix, move |tag, _| {
712                seen.lock().unwrap().push(tag.to_owned());
713            });
714        }
715        closed("tilo-narrow-test:one/1", CloseReason::Dismissed);
716        closed("tilo-narrow-test:two/1", CloseReason::Dismissed);
717        assert_eq!(*wide.lock().unwrap(), ["tilo-narrow-test:one/1"]);
718        assert_eq!(*narrow.lock().unwrap(), ["tilo-narrow-test:two/1"]);
719    }
720}