日本語

Notifications

Os::notify shows a notification among the system's, and tells whether the person clicked it.

Showing a notification

impl Os {
    pub async fn notify(&self, notification: Notification) -> Result<Notified, Error>;
}

impl Notification {
    pub fn new(title: impl Into<String>) -> Self;
    pub fn body(self, body: impl Into<String>) -> Self;
}

impl Notified {
    pub async fn clicked(self) -> bool;
}

Os::notify shows a Notification, a title and an optional body, among the system's notifications, and returns a Notified. Notified::clicked returns true once the person clicks the notification and false once they dismiss it, so it can wait for as long as the notification stays in the system's list. A handler spawns a task for it and answers the page at once:

use hypersig::Action;
use hypersig_desktop::{Notification, Os};

#[derive(Signals, Serialize, Deserialize)]
struct Chat {
    status: String,
}

#[derive(Clone)]
struct AppState {
    os: Os,
}

hypersig::routes! {
    fn pages(Router<AppState>);
    const CHAT: Route = "/" => chat;
    action RECEIVE: Action<Chat, String> = post "/receive" => receive;
}

/// Tells the person about a message, and brings a window forward if they click it.
async fn receive(state: AppState, message: String) -> Patches<Chat> {
    let notification = Notification::new("Ada").body(message);
    match state.os.notify(notification).await {
        Ok(shown) => {
            // `clicked` waits for the person, so a task waits for it.
            tokio::spawn(async move {
                if shown.clicked().await {
                    // Open or focus the chat's window here.
                }
            });
            Patches::new()
        }
        Err(error) => Chat::status().patch(format!("Not shown: {error}")).into(),
    }
}

It fails with ErrorKind::Notification when the system does not show it, as on Linux with no notification server running. In a test, FakeOs::notifications returns each notification the handlers showed, and FakeOs::click_notification clicks one.

On each system

  • macOS shows the notification under the application installed with the identifier App::new names, which a package from Packaging carries. A run of the executable outside that bundle, such as cargo run, shows it under another application's name. macOS asks the person once whether the application may notify, and shows nothing if they refuse.
  • Linux sends it to the notification server of the desktop over D-Bus, which GNOME, KDE, and most others run.
  • Windows shows it as a toast.
  • On macOS, Os::notify returned Ok; whether the notification appeared on screen has not been looked at on any system yet.

Next