Skip to main content

waft_embedder/
notifications.rs

1//! Notifications. Not a dart:ui file: Flutter reaches them through plugins such as
2//! `flutter_local_notifications`.
3//!
4//! A notification is a value posted under an id, and posting the same id again replaces it, as
5//! every system's own model is (`UNNotificationRequest`'s identifier, Android's `notify(id, …)`,
6//! the web's `tag`, Linux's `replaces_id`, a Windows toast's `Tag`); not an object the app keeps,
7//! which a click after a restart could not reach. A click, at launch or while the app runs, reaches
8//! the app by the notification's id and the action chosen, through
9//! `EmbedderClient::notification_activated`.
10//!
11//! A typed reply ([`NotificationReplies`]) and delivery at a later time
12//! ([`NotificationScheduling`]) are capabilities, `None` where the system lacks them, as the
13//! user's permission is ([`NotificationPermission`]) where the system keeps none for the app. A
14//! host answers each from the system's own, and never stands in for one the system lacks.
15//!
16//! Only [`NotificationPermission::request`] asks the user, with the system's own question. A post
17//! or a schedule never does, and never reads the permission first: it answers
18//! [`NotificationError::Denied`] where the system refuses the post itself, and otherwise the
19//! system decides whether it shows. Whether the app may notify is the permission's question
20//! ([`NotificationPermission::state`]).
21
22use std::fmt;
23use std::future::Future;
24use std::pin::Pin;
25use std::time::SystemTime;
26
27use crate::IconImage;
28
29/// The system's notifications.
30pub trait Notifications {
31    /// Shows `notification`, in place of the one posted under its id while that is still there.
32    /// It never asks the user and never reads the permission first: it answers
33    /// [`NotificationError::Denied`] where the system refuses the post itself, and otherwise the
34    /// system decides whether it shows. Whether the app may notify, and asking, is
35    /// [`Notifications::permission`]'s.
36    fn post(&self, notification: &Notification) -> PostFuture;
37
38    /// Takes away the notification posted or scheduled under `id`.
39    fn remove(&self, id: &str);
40
41    /// The user's permission, where the system keeps one for the app; `None` where any app may
42    /// notify.
43    fn permission(&self) -> Option<&dyn NotificationPermission>;
44
45    /// A typed reply, where the system takes one.
46    fn replies(&self) -> Option<&dyn NotificationReplies>;
47
48    /// Delivery at a later time, held by the system whether or not the app runs.
49    fn scheduling(&self) -> Option<&dyn NotificationScheduling>;
50}
51
52/// A notification: what the system shows under its id.
53#[derive(Clone, Debug, PartialEq)]
54pub struct Notification {
55    /// The app's own name for it, which a later post replaces and a click names.
56    pub id: String,
57    pub title: String,
58    pub body: Option<String>,
59    pub image: Option<IconImage>,
60    /// Buttons, and reply fields from [`NotificationReplies::reply_action`], in order.
61    pub actions: Vec<NotificationAction>,
62    /// Shown without the system's sound.
63    pub silent: bool,
64}
65
66impl Notification {
67    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Notification {
68        Notification {
69            id: id.into(),
70            title: title.into(),
71            body: None,
72            image: None,
73            actions: Vec::new(),
74            silent: false,
75        }
76    }
77}
78
79/// A button on a notification, or a field to reply in.
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct NotificationAction {
82    /// The app's own name for it, which a click names.
83    pub id: String,
84    pub label: String,
85    /// The reply field's placeholder, for an action the host made a reply.
86    reply: Option<String>,
87}
88
89impl NotificationAction {
90    pub fn button(id: impl Into<String>, label: impl Into<String>) -> NotificationAction {
91        NotificationAction {
92            id: id.into(),
93            label: label.into(),
94            reply: None,
95        }
96    }
97
98    /// An action that asks for a typed reply, made only by [`NotificationReplies::reply_action`],
99    /// so an app has one only where the system takes replies.
100    pub(crate) fn with_reply(
101        id: impl Into<String>,
102        label: impl Into<String>,
103        placeholder: impl Into<String>,
104    ) -> NotificationAction {
105        NotificationAction {
106            id: id.into(),
107            label: label.into(),
108            reply: Some(placeholder.into()),
109        }
110    }
111
112    /// The placeholder of the reply field the action asks for; `None` for a button.
113    pub fn reply_placeholder(&self) -> Option<&str> {
114        self.reply.as_deref()
115    }
116}
117
118/// The user clicked a notification, or one of its actions, or replied.
119#[derive(Clone, Debug, PartialEq, Eq)]
120pub struct NotificationActivation {
121    /// The notification's id.
122    pub id: String,
123    /// The action's id; `None` for the notification itself.
124    pub action: Option<String>,
125    /// What the user typed, for a reply action.
126    pub reply: Option<String>,
127}
128
129/// What a post answers, once the system has the notification.
130pub type PostFuture = Pin<Box<dyn Future<Output = Result<(), NotificationError>>>>;
131
132/// Why a notification was not posted.
133#[derive(Clone, Debug, PartialEq, Eq)]
134pub enum NotificationError {
135    /// The user does not let the app notify.
136    Denied,
137    /// The system failed to post it.
138    Failed(String),
139}
140
141impl fmt::Display for NotificationError {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        match self {
144            NotificationError::Denied => f.write_str("the user does not let the app notify"),
145            NotificationError::Failed(reason) => write!(f, "the notification failed: {reason}"),
146        }
147    }
148}
149
150impl std::error::Error for NotificationError {}
151
152/// The user's permission to notify, as the system keeps it for the app and asks for it.
153pub trait NotificationPermission {
154    /// The permission as it stands, without asking.
155    fn state(&self) -> PermissionFuture;
156
157    /// Asks the user where they have not been asked, with the system's own question; answers the
158    /// permission after. Where they answered before, or the system has no question, it asks
159    /// nothing and answers the permission as it stands.
160    fn request(&self) -> PermissionFuture;
161}
162
163/// Where the user's permission stands.
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub enum PermissionState {
166    Granted,
167    /// The user, or the system's settings, do not let the app notify.
168    Denied,
169    /// The user has not been asked, and the system would ask.
170    NotAsked,
171}
172
173pub type PermissionFuture = Pin<Box<dyn Future<Output = PermissionState>>>;
174
175/// Typed replies, where the system takes them.
176pub trait NotificationReplies {
177    /// An action that asks for a reply, shown as a field with `placeholder` in it.
178    fn reply_action(&self, id: &str, label: &str, placeholder: &str) -> NotificationAction {
179        NotificationAction::with_reply(id, label, placeholder)
180    }
181}
182
183/// Delivery at a later time, which the system holds whether or not the app runs.
184pub trait NotificationScheduling {
185    /// Shows `notification` at `at`, or at once where `at` has passed; a later post or schedule
186    /// under its id replaces it, and [`Notifications::remove`] cancels it. It never asks the user,
187    /// as a post does not.
188    fn schedule(&self, notification: &Notification, at: SystemTime) -> PostFuture;
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn a_reply_action_carries_its_placeholder_and_a_button_none() {
197        struct Replies;
198        impl NotificationReplies for Replies {}
199        let reply = Replies.reply_action("answer", "Reply", "Your answer");
200        assert_eq!(reply.reply_placeholder(), Some("Your answer"));
201        assert_eq!(
202            NotificationAction::button("later", "Later").reply_placeholder(),
203            None
204        );
205        let mut notification = Notification::new("message-7", "New message");
206        notification.actions.push(reply);
207        assert_eq!(notification.actions[0].id, "answer");
208    }
209}