Skip to main content

hypersig_desktop/
notification.rs

1//! The system's notifications, which tell the person something while the
2//! application's windows are in the background.
3
4use notify_rust::NotificationResponse;
5use tokio::sync::oneshot;
6
7use crate::error::Error;
8
9/// A notification for [`Os::notify`](crate::Os::notify): a title and an optional body.
10#[derive(Debug, Clone, PartialEq, Eq)]
11#[must_use = "a notification shows only when it is given to `Os::notify`"]
12pub struct Notification {
13    pub(crate) title: String,
14    pub(crate) body: Option<String>,
15}
16
17impl Notification {
18    /// A notification titled `title`, such as the sender of a message.
19    pub fn new(title: impl Into<String>) -> Self {
20        Self {
21            title: title.into(),
22            body: None,
23        }
24    }
25
26    /// Writes `body` under the title, such as the message itself.
27    pub fn body(mut self, body: impl Into<String>) -> Self {
28        self.body = Some(body.into());
29        self
30    }
31
32    /// The title the notification shows.
33    #[must_use]
34    pub fn title(&self) -> &str {
35        &self.title
36    }
37
38    /// The text under the title, if it has one.
39    #[must_use]
40    pub fn text(&self) -> Option<&str> {
41        self.body.as_deref()
42    }
43}
44
45/// A notification the system showed, from [`Os::notify`](crate::Os::notify).
46#[derive(Debug)]
47pub struct Notified {
48    pub(crate) clicked: oneshot::Receiver<bool>,
49}
50
51impl Notified {
52    /// Whether the person clicked the notification, once they have clicked
53    /// or dismissed it.
54    ///
55    /// It waits as long as the notification stays on screen or in the
56    /// system's list of notifications, so a handler that needs it spawns a
57    /// task rather than awaiting it before it answers. Until then, each
58    /// notification shown keeps a thread of the process waiting for it.
59    pub async fn clicked(self) -> bool {
60        self.clicked.await.unwrap_or(false)
61    }
62}
63
64/// Shows `notification` and sends whether it was clicked to `clicked`, from
65/// a thread of its own, since the system's call waits for the person.
66pub(crate) fn show(notification: &Notification) -> Result<Notified, Error> {
67    let (clicked, heard) = oneshot::channel();
68    let mut system = notify_rust::Notification::new();
69    system.summary(&notification.title);
70    if let Some(body) = &notification.body {
71        system.body(body);
72    }
73    // The freedesktop servers report a click on the body as the action
74    // named "default", and only when the notification offers it.
75    #[cfg(target_os = "linux")]
76    system.action("default", "Open");
77    let handle = system.show().map_err(Error::notification)?;
78    std::thread::Builder::new()
79        .name("hypersig-desktop-notification".to_owned())
80        .spawn(move || {
81            // On Windows, `wait_for_action` reports a click on the body as
82            // `"__closed"`; the typed response tells the two apart everywhere.
83            let waited = handle.wait_for_response(|response: &NotificationResponse| {
84                let _ = clicked.send(!matches!(response, NotificationResponse::Closed(_)));
85            });
86            if let Err(error) = waited {
87                tracing::warn!(%error, "the notification's click was not heard");
88            }
89        })
90        .map_err(Error::notification)?;
91    Ok(Notified { clicked: heard })
92}
93
94/// Names `id` as the application the notifications come from, so macOS
95/// shows them under the application installed with that identifier. A run
96/// outside such a bundle keeps the default, and its notifications appear
97/// under another application's name.
98#[cfg(target_os = "macos")]
99pub(crate) fn name_application(id: &str) {
100    if let Err(error) = notify_rust::set_application(id) {
101        tracing::debug!(%error, "notifications keep the default application, since no bundle has this identifier");
102    }
103}