English

通知

Os::notify は OS の通知を表示し、利用者がクリックしたかどうかを知らせます。

通知を表示する

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 は、タイトルと省略できる本文から成る Notification を OS の通知として表示し、Notified を返します。Notified::clicked は、利用者が通知をクリックすると true を、閉じると false を返します。通知が OS の一覧に残っている間はずっと待つことがあるので、ハンドラはこれをタスクで待ち、ページにはすぐに応答します。

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(),
    }
}

OS が通知を表示しなかったとき(通知のサーバーが動いていない Linux など)は、ErrorKind::Notification で失敗します。テストでは、FakeOs::notifications がハンドラが表示した通知を順に返し、FakeOs::click_notification が通知をクリックします。

OS ごとの違い

  • macOS は App::new で指定した識別子でインストールされたアプリの名前で通知を表示します。パッケージの作成 で作ったパッケージには、この識別子が入っています。cargo run のようにバンドルの外で実行ファイルを動かすと、ほかのアプリの名前で表示されます。macOS は通知してよいかを利用者に一度だけ尋ね、拒否されると何も表示しません。
  • Linux では、デスクトップの通知のサーバーに D-Bus で送ります。GNOME や KDE をはじめ、多くのデスクトップがこのサーバーを動かしています。
  • Windows ではトーストとして表示します。
  • macOS では Os::notify が Ok を返すことを確かめました。通知が画面に表示されるかは、まだどの OS でも見ていません。

次に読むページ