Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Show phone notifications on Windows
Bee888791c0c4f1
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex a5b00e3..dd851e2 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -10,7 +10,8 @@ use anyhow::{Context, Result, bail};use clap::{Parser, Subcommand, ValueEnum};use nectarlink_core::{Battery, ConnectionPath, DeviceId, DeviceInfo, DeviceKind, FeatureState, LinkState, Node, NodeConfig,- NodeEvent, PairedDevice, PairingEvent, Platform, PowerLevel,+ NodeEvent, Notification, NotificationAction, NotificationError, PairedDevice, PairingEvent, Platform,+ PowerLevel,features::{Effort, FEATURES, Role, UnsupportedReason, Upgrade, UpgradeAction},};use tokio::sync::broadcast::error::RecvError;@@ -110,6 +111,21 @@ enum Command {},/// Stay online and print events until Ctrl+C.Run,+ /// Show a notification on paired PCs as if this were a phone (use with+ /// --as-phone), then stay online to show what the PC does with it.+ Notify {+ title: String,+ text: String,+ /// App name shown with it.+ #[arg(long, default_value = "Messages")]+ app: String,+ /// Offer an inline reply.+ #[arg(long)]+ reply: bool,+ /// Don't alert (like a silent notification on the phone).+ #[arg(long)]+ silent: bool,+ },}#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]@@ -136,6 +152,22 @@ impl Platform for TerminalPlatform {fn stop_ringing(&self) {println!("🔕 Stopped ringing.");}+ fn dismiss_notification(&self, key: &str) -> Result<(), NotificationError> {+ println!("The PC dismissed {key}");+ Ok(())+ }+ fn run_notification_action(+ &self,+ key: &str,+ action: &str,+ reply: Option<&str>,+ ) -> Result<(), NotificationError> {+ match reply {+ Some(text) => println!("The PC replied to {key}: {text}"),+ None => println!("The PC ran action {action} of {key}"),+ }+ Ok(())+ }}#[tokio::main]@@ -166,12 +198,7 @@ async fn start_node(cli: &Cli) -> Result<Node> {(DeviceKind::Desktop, std::env::consts::OS.into(), String::new())};let device = DeviceInfo { name, kind, os, os_ver, model: None, accent: None };- let power = match (cli.as_phone, cli.power) {- (false, _) => PowerLevel::NotApplicable,- (true, Power::Basic) => PowerLevel::Basic,- (true, Power::Assist) => PowerLevel::Assist,- (true, Power::Elevated) => PowerLevel::Elevated,- };+ let power = node_power(cli);let mut config = NodeConfig::new(data_dir, device, env!("CARGO_PKG_VERSION"));config.port = cli.port;config.lan_discovery = !cli.no_lan;@@ -188,6 +215,15 @@ async fn start_node(cli: &Cli) -> Result<Node> {Ok(node)}+fn node_power(cli: &Cli) -> PowerLevel {+ match (cli.as_phone, cli.power) {+ (false, _) => PowerLevel::NotApplicable,+ (true, Power::Basic) => PowerLevel::Basic,+ (true, Power::Assist) => PowerLevel::Assist,+ (true, Power::Elevated) => PowerLevel::Elevated,+ }+}+async fn run(cli: &Cli, node: &Node) -> Result<()> {match &cli.command {Command::Id => {@@ -273,6 +309,36 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {println!("{name} is now {}", if on { "on" } else { "off" });}Command::Run => watch(node).await?,+ Command::Notify { title, text, app, reply, silent } => {+ if !cli.as_phone {+ bail!("notifications come from phones: add --as-phone");+ }+ let mut offers = cli.offers.clone();+ offers.extend(["notify.mirror".to_owned(), "notify.reply".to_owned()]);+ node.update_power(node_power(cli), offers).await;+ let when = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;+ let mut actions =+ vec![NotificationAction { id: "read".into(), title: "Mark as read".into(), reply: false }];+ if *reply {+ actions+ .insert(0, NotificationAction { id: "reply".into(), title: "Reply".into(), reply: true });+ }+ node.notification_posted(Notification {+ key: format!("cli|{when}"),+ app: "dev.nectarlink.cli".into(),+ app_name: app.clone(),+ title: Some(title.clone()),+ text: Some(text.clone()),+ sub: None,+ when,+ actions,+ silent: *silent,+ icon: None,+ })+ .await;+ println!("Notification sent to connected PCs (and to others when they connect).");+ watch(node).await?;+ }}Ok(())}@@ -385,6 +451,18 @@ fn print_event(node: &Node, event: &NodeEvent) {let available = m.features.values().filter(|s| **s == FeatureState::Available).count();println!("{}: {available} of {} features available", name(&m.device), m.features.len())}+ NodeEvent::NotificationsReset { device, items } => {+ println!("{}: {} notifications showing", name(device), items.len())+ }+ NodeEvent::NotificationPosted { device, notification: n } => println!(+ "{}: {} · {}",+ name(device),+ n.app_name,+ n.title.as_deref().or(n.text.as_deref()).unwrap_or_default()+ ),+ NodeEvent::NotificationRemoved { device, .. } => {+ println!("{}: a notification went away", name(device))+ }_ => {}}}diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 34868bf..9e417bd 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -134,6 +134,44 @@ pub struct Feature {pub status: FeatureStatus,}+/// A button on a notification.+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct NotificationAction {+ pub id: String,+ pub title: String,+ /// Takes text (an inline reply).+ pub reply: bool,+}++/// A notification, as mirrored between devices+/// (docs/protocol/notifications.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct Notification {+ /// This device's ID for it (Android: the StatusBarNotification key).+ pub key: String,+ /// Package name.+ pub app: String,+ pub app_name: String,+ pub title: Option<String>,+ pub text: Option<String>,+ pub sub: Option<String>,+ /// Unix milliseconds.+ pub when: i64,+ pub actions: Vec<NotificationAction>,+ /// Arrived without sound or pop-up.+ pub silent: bool,+ /// The app icon as PNG; pass it every time, the core sends it once per+ /// device and connection.+ pub icon: Option<Vec<u8>>,+}++/// Never prints content (protocol v0 §11).+impl std::fmt::Debug for Notification {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Notification").field("app", &self.app).finish_non_exhaustive()+ }+}+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]pub struct DeviceToggle {pub name: String,@@ -191,6 +229,18 @@ pub enum Event {id: String,features: Vec<Feature>,},+ NotificationsReset {+ id: String,+ items: Vec<Notification>,+ },+ NotificationPosted {+ id: String,+ notification: Notification,+ },+ NotificationRemoved {+ id: String,+ key: String,+ },}#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]@@ -211,6 +261,8 @@ pub enum NectarlinkError {VersionTooOld { this_device: bool },#[error("not supported by the other device")]Unsupported,+ #[error("it no longer exists")]+ NotFound,#[error("no pairing in progress")]NotPairing,#[error("invalid pairing link")]@@ -237,6 +289,7 @@ impl From<core::Error> for NectarlinkError {NectarlinkError::VersionTooOld { this_device: side == core::Side::Local }}core::Error::Unsupported => NectarlinkError::Unsupported,+ core::Error::NotFound => NectarlinkError::NotFound,core::Error::NotPairing => NectarlinkError::NotPairing,core::Error::InvalidPairingLink(_) => NectarlinkError::InvalidPairingLink,core::Error::Network(reason) => NectarlinkError::Network { reason },@@ -378,6 +431,48 @@ impl From<core::PairingFailure> for PairingFailure {}}+impl From<core::Notification> for Notification {+ fn from(n: core::Notification) -> Self {+ Notification {+ key: n.key,+ app: n.app,+ app_name: n.app_name,+ title: n.title,+ text: n.text,+ sub: n.sub,+ when: n.when,+ actions: n+ .actions+ .into_iter()+ .map(|a| NotificationAction { id: a.id, title: a.title, reply: a.reply })+ .collect(),+ silent: n.silent,+ icon: n.icon,+ }+ }+}++impl From<Notification> for core::Notification {+ fn from(n: Notification) -> Self {+ core::Notification {+ key: n.key,+ app: n.app,+ app_name: n.app_name,+ title: n.title,+ text: n.text,+ sub: n.sub,+ when: n.when,+ actions: n+ .actions+ .into_iter()+ .map(|a| core::NotificationAction { id: a.id, title: a.title, reply: a.reply })+ .collect(),+ silent: n.silent,+ icon: n.icon,+ }+ }+}+fn upgrade(u: core::features::Upgrade) -> Upgrade {let (action, target) = u.action.describe();Upgrade { action: action.into(), target, minutes: u.effort.minutes() }@@ -430,6 +525,16 @@ impl From<NodeEvent> for Event {NodeEvent::Capabilities(matrix) => {Event::Capabilities { id: matrix.device.to_string(), features: features(&matrix) }}+ NodeEvent::NotificationsReset { device, items } => Event::NotificationsReset {+ id: device.to_string(),+ items: items.into_iter().map(Into::into).collect(),+ },+ NodeEvent::NotificationPosted { device, notification } => {+ Event::NotificationPosted { id: device.to_string(), notification: notification.into() }+ }+ NodeEvent::NotificationRemoved { device, key } => {+ Event::NotificationRemoved { id: device.to_string(), key }+ }}}}@@ -440,12 +545,53 @@ fn parse_id(id: &str) -> Result<DeviceId> {// ---- Foreign interfaces (implemented in Kotlin) -----/// What the app does for the core: ring the phone.+/// Why a notification couldn't be dismissed or its action run.+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]+pub enum NotificationFailure {+ /// The notification or action is gone.+ #[error("no longer exists")]+ NotFound,+ /// Not possible here (e.g. notification access was revoked).+ #[error("not available")]+ Unsupported,+ /// `reason` is for logs; never put notification content in it.+ #[error("failed: {reason}")]+ Failed { reason: String },+}++impl From<uniffi::UnexpectedUniFFICallbackError> for NotificationFailure {+ fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self {+ NotificationFailure::Failed { reason: e.reason }+ }+}++impl From<NotificationFailure> for core::NotificationError {+ fn from(f: NotificationFailure) -> Self {+ match f {+ NotificationFailure::NotFound => core::NotificationError::NotFound,+ NotificationFailure::Unsupported => core::NotificationError::Unsupported,+ NotificationFailure::Failed { reason } => core::NotificationError::Failed(reason),+ }+ }+}++/// What the app does for the core: ring the phone, act on its+/// notifications.#[uniffi::export(with_foreign)]pub trait Platform: Send + Sync {/// Ring loudly, even in silent mode, until `stop_ringing`.fn start_ringing(&self);fn stop_ringing(&self);+ /// A PC dismissed this notification.+ fn dismiss_notification(&self, key: String) -> Result<(), NotificationFailure>;+ /// A PC ran this notification's action; `reply` is the text for a reply+ /// action.+ fn run_notification_action(+ &self,+ key: String,+ action: String,+ reply: Option<String>,+ ) -> Result<(), NotificationFailure>;}/// Encrypts the device key at rest (Android: a Keystore key).@@ -476,6 +622,17 @@ impl core::Platform for PlatformAdapter {fn stop_ringing(&self) {self.0.stop_ringing();}+ fn dismiss_notification(&self, key: &str) -> Result<(), core::NotificationError> {+ Ok(self.0.dismiss_notification(key.to_owned())?)+ }+ fn run_notification_action(+ &self,+ key: &str,+ action: &str,+ reply: Option<&str>,+ ) -> Result<(), core::NotificationError> {+ Ok(self.0.run_notification_action(key.to_owned(), action.to_owned(), reply.map(str::to_owned))?)+ }}struct KeyProtectorAdapter(Arc<dyn KeyProtector>);@@ -656,6 +813,27 @@ impl NectarlinkNode {Ok(self.node.set_device_toggle(parse_id(&id)?, &name, enabled)?)}+ // ---- Notifications ----++ /// A notification appeared or changed on this phone.+ pub async fn notification_posted(&self, notification: Notification) {+ let node = self.node.clone();+ self.run(async move { node.notification_posted(notification.into()).await }).await;+ }++ pub async fn notification_removed(&self, key: String) {+ let node = self.node.clone();+ self.run(async move { node.notification_removed(key).await }).await;+ }++ /// Everything this phone shows now (listener connected), or nothing+ /// (access revoked).+ pub async fn notifications_reset(&self, items: Vec<Notification>) {+ let node = self.node.clone();+ self.run(async move { node.notifications_reset(items.into_iter().map(Into::into).collect()).await })+ .await;+ }+// ---- This device ----pub async fn update_battery(&self, battery: Battery) {diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.tomlindex ea396f6..a387894 100644--- a/desktop/app/Cargo.toml+++ b/desktop/app/Cargo.toml@@ -32,6 +32,10 @@ tracing-subscriber.workspace = true[target.'cfg(windows)'.dependencies]windows = { workspace = true, features = [+ "Data_Xml_Dom",+ "Foundation",+ "Foundation_Collections",+ "UI_Notifications","Win32_Foundation","Win32_Graphics_Dwm","Win32_Graphics_Gdi",@@ -39,6 +43,7 @@ windows = { workspace = true, features = ["Win32_System_LibraryLoader","Win32_Security","Win32_System_Com",+ "Win32_System_Com_StructuredStorage","Win32_System_Power","Win32_System_Registry","Win32_System_Threading",diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex d56bb1c..cfa6d91 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -25,6 +25,7 @@ const QML: &[&str] = &["qml/components/ListRow.qml","qml/components/LockChip.qml","qml/components/NavItem.qml",+ "qml/components/NotificationItem.qml","qml/components/QrCode.qml","qml/components/Segmented.qml","qml/components/Sheet.qml",@@ -77,6 +78,7 @@ fn main() {"src/bridge/native.rs","src/bridge/app.rs","src/bridge/devices.rs",+ "src/bridge/notifications.rs","src/bridge/pairing.rs","src/bridge/prefs.rs",])diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qmlindex 2f9067b..be6de93 100644--- a/desktop/app/qml/MainWindow.qml+++ b/desktop/app/qml/MainWindow.qml@@ -28,6 +28,11 @@ NativeWindow {close.accepted = truewindow.closeRequested()}+ // Back from Settings, maybe with Windows notifications turned on.+ function onActiveChanged() {+ if (window.active)+ AppController.refreshToastsEnabled()+ }}function openPairing() { pairingSheet.open() }diff --git a/desktop/app/qml/components/NotificationItem.qml b/desktop/app/qml/components/NotificationItem.qmlnew file mode 100644index 0000000..117c4ba--- /dev/null+++ b/desktop/app/qml/components/NotificationItem.qml@@ -0,0 +1,188 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import QtQuick+import app.nectarlink++// One phone notification in the feed: app, title and text, its actions,+// an inline reply when the app offers one, and a dismiss button on hover.+Item {+ id: item+ required property string deviceId+ required property string key+ required property string appName+ required property string title+ required property string text+ required property string sub+ required property real when+ required property string iconUrl+ required property string actions+ required property string replyAction+ required property string replyLabel++ readonly property var buttons: { try { return JSON.parse(actions) } catch (e) { return [] } }+ property bool replying: false++ implicitHeight: content.height + 24++ function timeText() {+ const minutes = Math.round((Date.now() - when) / 60000)+ if (minutes < 1) return qsTr("now")+ if (minutes < 60) return qsTr("%n min", "", minutes)+ const date = new Date(when)+ if (Date.now() - when < 24 * 3600 * 1000) return date.toLocaleTimeString(Qt.locale(), Locale.ShortFormat)+ return date.toLocaleDateString(Qt.locale(), Locale.ShortFormat)+ }++ function send() {+ if (input.text.trim().length === 0)+ return+ NotificationList.reply(item.deviceId, item.key, item.replyAction, input.text)+ input.text = ""+ item.replying = false+ }++ HoverHandler { id: hover }++ Rectangle {+ anchors.fill: parent+ radius: Theme.radiusMd+ color: hover.hovered ? (Theme.graphite ? Theme.surfaceContainer : Theme.surfaceContainerHigh) : "transparent"+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ }++ // App icon, or its initial when the phone didn't send one.+ Item {+ id: icon+ x: 12; y: 12+ width: 32; height: 32+ Image {+ id: image+ anchors.fill: parent+ source: item.iconUrl+ sourceSize: Qt.size(64, 64)+ smooth: true+ mipmap: true+ visible: status === Image.Ready+ }+ Avatar {+ anchors.fill: parent+ visible: image.status !== Image.Ready+ name: item.appName+ }+ }++ Column {+ id: content+ anchors.left: icon.right+ anchors.leftMargin: 12+ anchors.right: parent.right+ anchors.rightMargin: 44+ y: 12+ spacing: 4++ Txt {+ width: parent.width+ role: "caption"+ muted: true+ text: [item.appName, item.sub, item.timeText()].filter(s => s.length > 0).join(" · ")+ }+ Txt {+ width: parent.width+ visible: item.title.length > 0+ role: "title"+ size: 14+ text: item.title+ }+ Txt {+ width: parent.width+ visible: item.text.length > 0+ role: "body"+ text: item.text+ wrapMode: Text.Wrap+ maximumLineCount: 4+ }++ Flow {+ width: parent.width+ spacing: 6+ topPadding: 4+ visible: !item.replying && (item.replyAction.length > 0 || item.buttons.length > 0)+ Button {+ visible: item.replyAction.length > 0+ variant: "tonal"+ size: "sm"+ text: item.replyLabel.length > 0 ? item.replyLabel : qsTr("Reply")+ onClicked: { item.replying = true; input.forceActiveFocus() }+ }+ Repeater {+ model: item.buttons+ delegate: Button {+ required property var modelData+ variant: "text"+ size: "sm"+ text: modelData.title+ onClicked: NotificationList.runAction(item.deviceId, item.key, modelData.id)+ }+ }+ }++ // Inline reply.+ Rectangle {+ width: parent.width+ height: 40+ visible: item.replying+ radius: Theme.graphite ? Theme.radiusSm : height / 2+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest+ border.width: input.activeFocus ? 2 : 1+ border.color: input.activeFocus ? Theme.primary : Theme.outlineVariant++ TextInput {+ id: input+ anchors.left: parent.left+ anchors.leftMargin: 16+ anchors.right: sendButton.left+ anchors.rightMargin: 8+ anchors.verticalCenter: parent.verticalCenter+ font.family: Theme.fontUi+ font.pixelSize: 14+ color: Theme.surfaceContent+ selectionColor: Theme.primaryContainer+ selectedTextColor: Theme.primaryContainerContent+ clip: true+ Keys.onReturnPressed: item.send()+ Keys.onEnterPressed: item.send()+ Keys.onEscapePressed: { text = ""; item.replying = false }+ Accessible.name: qsTr("Reply to %1").arg(item.title)++ Txt {+ anchors.verticalCenter: parent.verticalCenter+ visible: input.text.length === 0+ role: "body"+ muted: true+ text: qsTr("Reply to %1").arg(item.title.length > 0 ? item.title : item.appName)+ }+ }+ IconButton {+ id: sendButton+ anchors.right: parent.right+ anchors.rightMargin: 4+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.send+ label: qsTr("Send")+ enabled: input.text.trim().length > 0+ onClicked: item.send()+ }+ }+ }++ IconButton {+ anchors.right: parent.right+ anchors.rightMargin: 8+ y: 8+ iconPath: Icons.close+ label: qsTr("Dismiss")+ // Always there (for keyboards and screen readers), quiet until hovered.+ opacity: hover.hovered || activeFocus ? 1 : 0.55+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }+ onClicked: NotificationList.dismiss(item.deviceId, item.key)+ }+}diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 45cf1fd..7c15cfa 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -230,6 +230,97 @@ Item {ready: false}}++ // ---- Notifications ----+ Card {+ id: feed+ width: parent.width+ readonly property var state: home.feature("notifications.mirror")+ readonly property int count: NotificationList.count >= 0 ? NotificationList.countFor(home.deviceId) : 0++ Column {+ width: parent.width+ spacing: 8+ Item {+ width: parent.width+ height: Math.max(header.height, clearAll.height)+ Txt {+ id: header+ anchors.verticalCenter: parent.verticalCenter+ role: "label"+ muted: true+ text: feed.count > 0 ? qsTr("Notifications · %1").arg(feed.count) : qsTr("Notifications")+ }+ Button {+ id: clearAll+ anchors.right: parent.right+ visible: feed.count > 1+ variant: "text"+ size: "sm"+ text: qsTr("Clear all")+ onClicked: NotificationList.dismissAll(home.deviceId)+ }+ }+ Column {+ width: parent.width+ Repeater {+ model: NotificationList+ delegate: NotificationItem {+ width: parent.width+ visible: deviceId === home.deviceId+ }+ }+ }+ // Empty: say why, and what turns it on.+ Txt {+ width: parent.width+ visible: feed.count === 0 && !lockedHint.visible+ role: "bodySmall"+ muted: true+ wrapMode: Text.WordWrap+ text: feed.state.state === "available"+ ? qsTr("Notifications from %1 show up here and as Windows notifications.").arg(home.name)+ : home.lastSeen > 0 || home.online+ ? qsTr("Notifications from %1 aren't available yet.").arg(home.name)+ : qsTr("Notifications show up here once %1 has connected.").arg(home.name)+ }+ LockChip { id: lockedHint; visible: feed.count === 0 && label.length > 0; feature: feed.state }+ // Windows hides every app's notifications when they're+ // turned off in Settings; say so instead of staying quiet.+ Rectangle {+ width: parent.width+ height: toastsOff.height + 20+ visible: !AppController.toastsEnabled && feed.state.state === "available"+ radius: Theme.radiusMd+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHigh+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant+ Row {+ id: toastsOff+ x: 12+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 24+ spacing: 12+ Icon { anchors.verticalCenter: parent.verticalCenter; path: Icons.bell; color: Theme.surfaceContentVariant }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 32 - turnOn.width - 24+ role: "bodySmall"+ wrapMode: Text.WordWrap+ text: qsTr("Windows notifications are turned off, so these only show up here.")+ }+ Button {+ id: turnOn+ anchors.verticalCenter: parent.verticalCenter+ variant: "tonal"+ size: "sm"+ text: qsTr("Turn on")+ onClicked: Qt.openUrlExternally("ms-settings:notifications")+ }+ }+ }+ }+ }}// ---- Details ----diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rsindex 6e3b072..8868605 100644--- a/desktop/app/src/bridge/app.rs+++ b/desktop/app/src/bridge/app.rs@@ -57,6 +57,8 @@ pub mod qobject {/// Bloom colors from the desktop wallpaper, as JSON in the shape of/// a tokens.json seed (`{ seed, light, dark }`); "" until known.#[qproperty(QString, wallpaper_colors)]+ /// Whether Windows shows this app's notifications.+ #[qproperty(bool, toasts_enabled)]#[qproperty(QString, version)]type AppController = super::AppControllerRust;@@ -79,6 +81,12 @@ pub mod qobject {#[qinvokable]fn set_device_toggle(self: Pin<&mut AppController>, device: &QString, name: &QString, on: bool);+ /// Re-reads whether Windows shows this app's notifications (the user+ /// may have changed it in Settings).+ #[qinvokable]+ #[cxx_name = "refreshToastsEnabled"]+ fn refresh_toasts_enabled(self: Pin<&mut AppController>);+/// The folder with the app's logs, as a file URL.#[qinvokable]fn logs_url(self: &AppController) -> QString;@@ -111,6 +119,7 @@ pub struct AppControllerRust {system_dark: bool,reduce_motion: bool,wallpaper_colors: QString,+ toasts_enabled: bool,version: QString,tray: Option<tray::Tray>,}@@ -130,8 +139,8 @@ pub fn request_activation() {}}-/// Shows a toast (from any thread).-fn toast(message: impl Into<String>) {+/// Shows a short message in the app (from any thread).+pub(crate) fn show_message(message: impl Into<String>) {let message = message.into();if let Some(qt) = controller() {let _ = qt.queue(move |object| object.toast(QString::from(&message)));@@ -139,7 +148,7 @@ fn toast(message: impl Into<String>) {}/// Explains a failed command in a sentence the user understands.-fn describe(error: &Error) -> String {+pub(crate) fn describe(error: &Error) -> String {match error {Error::Offline => "The device isn't connected right now.".into(),Error::NotPaired => "That device isn't paired anymore.".into(),@@ -234,7 +243,7 @@ fn ring_device(device: DeviceId, on: bool) {let Some(node) = core_host::node() else { return };core_host::spawn(async move {if let Err(e) = node.ring(device, on).await {- toast(describe(&e));+ show_message(describe(&e));}});}@@ -278,6 +287,11 @@ impl qobject::AppController {self.as_mut().set_system_dark(win::system_dark());self.as_mut().set_reduce_motion(win::reduce_motion());refresh_wallpaper_colors(self.qt_thread());+ self.refresh_toasts_enabled();+ }++ pub fn refresh_toasts_enabled(self: Pin<&mut Self>) {+ self.set_toasts_enabled(win::toast::enabled());}pub fn ring(self: Pin<&mut Self>, device: &QString, on: bool) {@@ -297,7 +311,7 @@ impl qobject::AppController {let (Some(id), Some(node)) = (super::parse_device(device), core_host::node()) else { return };core_host::spawn(async move {if let Err(e) = node.unpair(id).await {- toast(describe(&e));+ show_message(describe(&e));}});}@@ -325,7 +339,7 @@ impl qobject::AppController {pub fn set_device_toggle(mut self: Pin<&mut Self>, device: &QString, name: &QString, on: bool) {let (Some(id), Some(node)) = (super::parse_device(device), core_host::node()) else { return };if let Err(e) = node.set_device_toggle(id, &String::from(name), on) {- toast(describe(&e));+ show_message(describe(&e));}let revision = self.toggles_revision.wrapping_add(1);self.as_mut().set_toggles_revision(revision);diff --git a/desktop/app/src/bridge/devices.rs b/desktop/app/src/bridge/devices.rsindex 98b3fd4..4859589 100644--- a/desktop/app/src/bridge/devices.rs+++ b/desktop/app/src/bridge/devices.rs@@ -8,6 +8,7 @@ use cxx_qt::{CxxQtType, Threading};use cxx_qt_lib::{QByteArray, QHash, QHashPair_i32_QByteArray, QList, QModelIndex, QString, QVariant};use nectarlink_core::{ConnectionPath, DeviceKind, LinkState, PowerLevel};+use super::{Edit, diff};use crate::{core_host,state::{Changes, DeviceView},@@ -181,7 +182,7 @@ impl qobject::DeviceList {fn refresh(mut self: Pin<&mut Self>) {let new = core_host::host().hub.read(|s| s.devices.clone());let root = QModelIndex::default();- match diff(&self.rows, &new) {+ match diff(&self.rows, &new, |d| d.id) {None => {// SAFETY: begin/end pairs are balanced around the swap.unsafe {@@ -251,42 +252,6 @@ impl qobject::DeviceList {}}-/// One step turning the current rows into the new ones.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum Edit {- Remove(usize),- Insert(usize),- Change(usize),-}--/// Edits from `old` to `new`, applied in order. `None` when the devices that-/// stay changed their relative order (then the model is reset).-fn diff(old: &[DeviceView], new: &[DeviceView]) -> Option<Vec<Edit>> {- let mut edits = Vec::new();- // Removals, from the end so earlier indices stay valid.- for (row, device) in old.iter().enumerate().rev() {- if !new.iter().any(|d| d.id == device.id) {- edits.push(Edit::Remove(row));- }- }- let kept: Vec<&DeviceView> = old.iter().filter(|d| new.iter().any(|n| n.id == d.id)).collect();- let mut next_kept = 0;- for (row, device) in new.iter().enumerate() {- match kept.get(next_kept) {- Some(k) if k.id == device.id => {- if *k != device {- edits.push(Edit::Change(row));- }- next_kept += 1;- }- // Devices already in the list must come in the same order.- _ if kept.iter().any(|k| k.id == device.id) => return None,- _ => edits.push(Edit::Insert(row)),- }- }- Some(edits)-}-#[cfg(test)]mod tests {use nectarlink_core::{DeviceId, DeviceInfo};@@ -314,7 +279,7 @@ mod tests {/// Applies edits the way the model does and checks the result.fn apply(old: &[DeviceView], new: &[DeviceView]) -> Vec<DeviceView> {let mut rows = old.to_vec();- for edit in diff(old, new).expect("incremental") {+ for edit in diff(old, new, |d| d.id).expect("incremental") {match edit {Edit::Remove(r) => {rows.remove(r);@@ -333,12 +298,12 @@ mod tests {let mut b2 = b.clone();b2.info.name = "b2".into();let new = vec![a.clone(), b2.clone(), d.clone()];- assert_eq!(diff(&old, &new).unwrap(), [Edit::Remove(2), Edit::Change(1), Edit::Insert(2)]);+ assert_eq!(diff(&old, &new, |d| d.id).unwrap(), [Edit::Remove(2), Edit::Change(1), Edit::Insert(2)]);assert_eq!(apply(&old, &new), new);assert_eq!(apply(&[], &new), new);assert_eq!(apply(&new, &[]), Vec::<DeviceView>::new());- assert_eq!(diff(&new, &new).unwrap(), []);+ assert_eq!(diff(&new, &new, |d| d.id).unwrap(), []);let interleaved = vec![d.clone(), a.clone(), c.clone(), b2.clone()];assert_eq!(apply(&[a.clone(), b2.clone()], &interleaved), interleaved);}@@ -346,7 +311,7 @@ mod tests {#[test]fn reordering_falls_back_to_a_reset() {let (a, b) = (device(1, "a"), device(2, "b"));- assert_eq!(diff(&[a.clone(), b.clone()], &[b, a]), None);+ assert_eq!(diff(&[a.clone(), b.clone()], &[b, a], |d| d.id), None);}#[test]diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rsindex 7df4e0f..251e253 100644--- a/desktop/app/src/bridge/mod.rs+++ b/desktop/app/src/bridge/mod.rs@@ -12,6 +12,8 @@ pub mod devices;#[allow(unsafe_code)]pub mod native;#[allow(unsafe_code)]+pub mod notifications;+#[allow(unsafe_code)]pub mod pairing;#[allow(unsafe_code)]pub mod prefs;@@ -56,3 +58,44 @@ wherepub(crate) fn parse_device(id: &QString) -> Option<DeviceId> {String::from(id).parse().ok()}++/// One step turning a list model's rows into new ones.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum Edit {+ Remove(usize),+ Insert(usize),+ Change(usize),+}++/// Edits from `old` to `new` (rows identified by `key`), applied in order,+/// so QML delegates keep their state and animate. `None` when rows that stay+/// changed their relative order (then the model is reset).+pub(crate) fn diff<T: PartialEq, K: PartialEq>(+ old: &[T],+ new: &[T],+ key: impl Fn(&T) -> K,+) -> Option<Vec<Edit>> {+ let mut edits = Vec::new();+ // Removals, from the end so earlier indices stay valid.+ for (row, item) in old.iter().enumerate().rev() {+ if !new.iter().any(|n| key(n) == key(item)) {+ edits.push(Edit::Remove(row));+ }+ }+ let kept: Vec<&T> = old.iter().filter(|o| new.iter().any(|n| key(n) == key(o))).collect();+ let mut next_kept = 0;+ for (row, item) in new.iter().enumerate() {+ match kept.get(next_kept) {+ Some(k) if key(k) == key(item) => {+ if *k != item {+ edits.push(Edit::Change(row));+ }+ next_kept += 1;+ }+ // Rows already in the list must come in the same order.+ _ if kept.iter().any(|k| key(k) == key(item)) => return None,+ _ => edits.push(Edit::Insert(row)),+ }+ }+ Some(edits)+}diff --git a/desktop/app/src/bridge/notifications.rs b/desktop/app/src/bridge/notifications.rsnew file mode 100644index 0000000..2c9c5d5--- /dev/null+++ b/desktop/app/src/bridge/notifications.rs@@ -0,0 +1,359 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! `NotificationList`: phone notifications (newest first) as a Qt list+//! model, plus the commands QML runs on them.++use std::pin::Pin;++use cxx_qt::{CxxQtType, Threading};+use cxx_qt_lib::{QByteArray, QHash, QHashPair_i32_QByteArray, QList, QModelIndex, QString, QVariant};+use nectarlink_core::DeviceId;++use super::{Edit, diff};+use crate::{+ core_host, icons,+ state::{Changes, NotificationView},+};++#[cxx_qt::bridge]+pub mod qobject {+ unsafe extern "C++" {+ include!(<QtCore/QAbstractListModel>);+ type QAbstractListModel;++ include!("cxx-qt-lib/qmodelindex.h");+ type QModelIndex = cxx_qt_lib::QModelIndex;+ include!("cxx-qt-lib/qvariant.h");+ type QVariant = cxx_qt_lib::QVariant;+ include!("cxx-qt-lib/qhash.h");+ type QHash_i32_QByteArray = cxx_qt_lib::QHash<cxx_qt_lib::QHashPair_i32_QByteArray>;+ include!("cxx-qt-lib/qlist.h");+ type QList_i32 = cxx_qt_lib::QList<i32>;+ include!("cxx-qt-lib/qstring.h");+ type QString = cxx_qt_lib::QString;+ }++ unsafe extern "RustQt" {+ #[qobject]+ #[base = QAbstractListModel]+ #[qml_element]+ #[qml_singleton]+ #[qproperty(i32, count)]+ type NotificationList = super::NotificationListRust;+ }++ // Inherited from QAbstractListModel.+ unsafe extern "RustQt" {+ #[inherit]+ #[cxx_name = "beginInsertRows"]+ unsafe fn begin_insert_rows(+ self: Pin<&mut NotificationList>,+ parent: &QModelIndex,+ first: i32,+ last: i32,+ );+ #[inherit]+ #[cxx_name = "endInsertRows"]+ unsafe fn end_insert_rows(self: Pin<&mut NotificationList>);+ #[inherit]+ #[cxx_name = "beginRemoveRows"]+ unsafe fn begin_remove_rows(+ self: Pin<&mut NotificationList>,+ parent: &QModelIndex,+ first: i32,+ last: i32,+ );+ #[inherit]+ #[cxx_name = "endRemoveRows"]+ unsafe fn end_remove_rows(self: Pin<&mut NotificationList>);+ #[inherit]+ #[cxx_name = "beginResetModel"]+ unsafe fn begin_reset_model(self: Pin<&mut NotificationList>);+ #[inherit]+ #[cxx_name = "endResetModel"]+ unsafe fn end_reset_model(self: Pin<&mut NotificationList>);+ #[inherit]+ fn index(self: &NotificationList, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex;++ #[inherit]+ #[qsignal]+ #[cxx_name = "dataChanged"]+ fn data_changed(+ self: Pin<&mut NotificationList>,+ top_left: &QModelIndex,+ bottom_right: &QModelIndex,+ roles: &QList_i32,+ );+ }++ unsafe extern "RustQt" {+ #[qinvokable]+ #[cxx_override]+ fn data(self: &NotificationList, index: &QModelIndex, role: i32) -> QVariant;+ #[qinvokable]+ #[cxx_override]+ #[cxx_name = "roleNames"]+ fn role_names(self: &NotificationList) -> QHash_i32_QByteArray;+ #[qinvokable]+ #[cxx_override]+ #[cxx_name = "rowCount"]+ fn row_count(self: &NotificationList, parent: &QModelIndex) -> i32;++ /// How many notifications a device has here.+ #[qinvokable]+ #[cxx_name = "countFor"]+ fn count_for(self: &NotificationList, device: &QString) -> i32;+ /// Dismisses it here and on the phone.+ #[qinvokable]+ fn dismiss(self: &NotificationList, device: &QString, key: &QString);+ /// Dismisses all of a device's notifications.+ #[qinvokable]+ #[cxx_name = "dismissAll"]+ fn dismiss_all(self: &NotificationList, device: &QString);+ /// Runs one of its actions on the phone.+ #[qinvokable]+ #[cxx_name = "runAction"]+ fn run_action(self: &NotificationList, device: &QString, key: &QString, action: &QString);+ /// Sends a reply through its reply action.+ #[qinvokable]+ fn reply(self: &NotificationList, device: &QString, key: &QString, action: &QString, text: &QString);+ }++ impl cxx_qt::Threading for NotificationList {}+ impl cxx_qt::Initialize for NotificationList {}+}++/// A row: the notification plus what the UI needs to show it.+#[derive(Debug, Clone, PartialEq, Eq)]+struct Row {+ view: NotificationView,+ device_name: String,+ /// A file URL, or "" (the UI then shows the app's initial).+ icon_url: String,+}++#[derive(Default)]+pub struct NotificationListRust {+ count: i32,+ rows: Vec<Row>,+}++/// Model roles (Qt::UserRole + n).+const ROLES: &[&str] = &[+ "deviceId",+ "deviceName",+ "key",+ "app",+ "appName",+ "title",+ "text",+ "sub",+ "when",+ "iconUrl",+ "actions",+ "replyAction",+ "replyLabel",+ "silent",+];+const USER_ROLE: i32 = 0x0100;++fn role_value(row: &Row, role: &str) -> QVariant {+ let text = |s: &str| QVariant::from(&QString::from(s));+ let n = &row.view.notification;+ let reply = n.actions.iter().find(|a| a.reply);+ match role {+ "deviceId" => text(&row.view.device.to_string()),+ "deviceName" => text(&row.device_name),+ "key" => text(&n.key),+ "app" => text(&n.app),+ "appName" => text(&n.app_name),+ "title" => text(n.title.as_deref().unwrap_or_default()),+ "text" => text(n.text.as_deref().unwrap_or_default()),+ "sub" => text(n.sub.as_deref().unwrap_or_default()),+ "when" => QVariant::from(&(n.when as f64)),+ "iconUrl" => text(&row.icon_url),+ // Buttons other than the reply, as JSON: [{ "id", "title" }].+ "actions" => text(+ &serde_json::Value::from(+ n.actions+ .iter()+ .filter(|a| !a.reply)+ .map(|a| serde_json::json!({ "id": a.id, "title": a.title }))+ .collect::<Vec<_>>(),+ )+ .to_string(),+ ),+ "replyAction" => text(reply.map_or("", |a| a.id.as_str())),+ "replyLabel" => text(reply.map_or("", |a| a.title.as_str())),+ "silent" => QVariant::from(&n.silent),+ _ => QVariant::default(),+ }+}++fn key_of(row: &Row) -> (DeviceId, String) {+ (row.view.device, row.view.notification.key.clone())+}++impl cxx_qt::Initialize for qobject::NotificationList {+ fn initialize(self: Pin<&mut Self>) {+ super::subscribe(self.qt_thread(), Changes::NOTIFICATIONS | Changes::DEVICES, Self::refresh);+ }+}++impl qobject::NotificationList {+ fn refresh(mut self: Pin<&mut Self>) {+ let new: Vec<Row> = core_host::host().hub.read(|s| {+ s.notifications+ .iter()+ .map(|view| Row {+ device_name: s.name_of(&view.device).unwrap_or_default(),+ icon_url: s+ .app_icons+ .get(&view.notification.app)+ .map(|p| icons::file_url(p))+ .unwrap_or_default(),+ view: view.clone(),+ })+ .collect()+ });+ let root = QModelIndex::default();+ match diff(&self.rows, &new, key_of) {+ None => {+ // SAFETY: begin/end pairs are balanced around the swap.+ unsafe {+ self.as_mut().begin_reset_model();+ self.as_mut().rust_mut().rows = new;+ self.as_mut().end_reset_model();+ }+ }+ Some(edits) => {+ for edit in edits {+ match edit {+ Edit::Remove(row) => {+ let r = row as i32;+ // SAFETY: row exists; begin/end are balanced.+ unsafe {+ self.as_mut().begin_remove_rows(&root, r, r);+ self.as_mut().rust_mut().rows.remove(row);+ self.as_mut().end_remove_rows();+ }+ }+ Edit::Insert(row) => {+ let r = row as i32;+ // SAFETY: row <= len; begin/end are balanced.+ unsafe {+ self.as_mut().begin_insert_rows(&root, r, r);+ self.as_mut().rust_mut().rows.insert(row, new[row].clone());+ self.as_mut().end_insert_rows();+ }+ }+ Edit::Change(row) => {+ self.as_mut().rust_mut().rows[row] = new[row].clone();+ let index = self.index(row as i32, 0, &root);+ self.as_mut().data_changed(&index, &index, &QList::default());+ }+ }+ }+ }+ }+ let count = self.rows.len() as i32;+ self.set_count(count);+ }++ pub fn data(&self, index: &QModelIndex, role: i32) -> QVariant {+ let row = usize::try_from(index.row()).ok();+ let role = usize::try_from(role - USER_ROLE).ok().and_then(|r| ROLES.get(r));+ match (row.and_then(|r| self.rows.get(r)), role) {+ (Some(row), Some(role)) => role_value(row, role),+ _ => QVariant::default(),+ }+ }++ pub fn role_names(&self) -> QHash<QHashPair_i32_QByteArray> {+ let mut roles = QHash::<QHashPair_i32_QByteArray>::default();+ for (i, name) in ROLES.iter().enumerate() {+ roles.insert(USER_ROLE + i as i32, QByteArray::from(*name));+ }+ roles+ }++ pub fn row_count(&self, _parent: &QModelIndex) -> i32 {+ self.rows.len() as i32+ }++ pub fn count_for(&self, device: &QString) -> i32 {+ let device = String::from(device);+ self.rows.iter().filter(|r| r.view.device.to_string() == device).count() as i32+ }++ pub fn dismiss(&self, device: &QString, key: &QString) {+ crate::notifications::dismiss(&String::from(device), String::from(key));+ }++ pub fn dismiss_all(&self, device: &QString) {+ let device = String::from(device);+ for row in self.rows.iter().filter(|r| r.view.device.to_string() == device) {+ crate::notifications::dismiss(&row.view.device.to_string(), row.view.notification.key.clone());+ }+ }++ pub fn run_action(&self, device: &QString, key: &QString, action: &QString) {+ crate::notifications::run_action(+ &String::from(device),+ String::from(key),+ String::from(action),+ None,+ );+ }++ pub fn reply(&self, device: &QString, key: &QString, action: &QString, text: &QString) {+ let text = String::from(text).trim().to_owned();+ if text.is_empty() {+ return;+ }+ crate::notifications::run_action(+ &String::from(device),+ String::from(key),+ String::from(action),+ Some(text),+ );+ }+}++#[cfg(test)]+mod tests {+ use nectarlink_core::{Notification, NotificationAction};++ use super::*;++ #[test]+ fn roles_describe_the_notification() {+ let row = Row {+ view: NotificationView {+ device: DeviceId([7; 32]),+ notification: Notification {+ key: "k".into(),+ app: "com.chat".into(),+ app_name: "Chat".into(),+ title: Some("Sam".into()),+ text: None,+ sub: None,+ when: 1_760_000_000_000,+ actions: vec![+ NotificationAction { id: "r".into(), title: "Reply".into(), reply: true },+ NotificationAction { id: "m".into(), title: "Mute".into(), reply: false },+ ],+ silent: false,+ icon: None,+ },+ },+ device_name: "Pixel".into(),+ icon_url: String::new(),+ };+ let text = |role| role_value(&row, role).value::<QString>().map(String::from).unwrap_or_default();+ assert_eq!(text("title"), "Sam");+ assert_eq!(text("text"), "");+ assert_eq!(text("replyAction"), "r");+ assert_eq!(text("actions"), r#"[{"id":"m","title":"Mute"}]"#);+ assert_eq!(role_value(&row, "when").value::<f64>(), Some(1_760_000_000_000.0));+ }+}diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex eababf4..1f54bd6 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -104,7 +104,10 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {loop {match events.recv().await {- Ok(event) => host.hub.update(|s| s.apply(&event)),+ Ok(event) => {+ crate::notifications::apply(&event);+ crate::notifications::update_toasts(&event);+ }Err(RecvError::Lagged(missed)) => {// Resynchronize what can be re-read; transient events are lost.tracing::warn!(missed, "UI fell behind core events; resyncing");diff --git a/desktop/app/src/icons.rs b/desktop/app/src/icons.rsnew file mode 100644index 0000000..49a84bc--- /dev/null+++ b/desktop/app/src/icons.rs@@ -0,0 +1,67 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! App icons that phones send with their notifications, kept as PNG files+//! (`<data>\cache\icons`) so QML and Windows toasts can show them.++use std::{+ fs,+ path::{Path, PathBuf},+};++const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";++pub fn icons_dir(data_dir: &Path) -> PathBuf {+ data_dir.join("cache").join("icons")+}++/// A file name for a package: package names are already safe+/// (`[A-Za-z0-9._]`); anything else is replaced.+fn file_name(app: &str) -> String {+ let safe: String = app+ .chars()+ .map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '_' { c } else { '_' })+ .collect();+ let safe = safe.trim_matches('.');+ format!("{}.png", if safe.is_empty() { "_" } else { safe })+}++/// Stores an app's icon and returns its path. Only PNG data is accepted.+pub fn save(data_dir: &Path, app: &str, png: &[u8]) -> std::io::Result<PathBuf> {+ if !png.starts_with(PNG_SIGNATURE) {+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "not a PNG"));+ }+ let dir = icons_dir(data_dir);+ fs::create_dir_all(&dir)?;+ let path = dir.join(file_name(app));+ if fs::read(&path).is_ok_and(|existing| existing == png) {+ return Ok(path);+ }+ let tmp = path.with_extension("png.tmp");+ fs::write(&tmp, png)?;+ fs::rename(&tmp, &path)?;+ Ok(path)+}++/// A `file:///` URL for QML and toasts.+pub fn file_url(path: &Path) -> String {+ format!("file:///{}", path.to_string_lossy().replace('\\', "/"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn stores_png_icons_under_safe_names() {+ let dir = tempfile::tempdir().unwrap();+ let png = [PNG_SIGNATURE, b"rest"].concat();+ let path = save(dir.path(), "com.whatsapp", &png).unwrap();+ assert_eq!(path.file_name().unwrap(), "com.whatsapp.png");+ assert_eq!(fs::read(&path).unwrap(), png);+ // Saving the same icon again is a no-op; a new one replaces it.+ assert_eq!(save(dir.path(), "com.whatsapp", &png).unwrap(), path);++ assert_eq!(file_name("../../evil\\x"), "_.._evil_x.png");+ assert!(save(dir.path(), "com.bad", b"GIF89a").is_err(), "only PNG");+ assert!(file_url(Path::new(r"C:\a\b.png")).starts_with("file:///C:/a/b.png"));+ }+}diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex a6c33c1..3a75e0f 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -10,7 +10,9 @@mod bridge;mod core_host;+mod icons;mod logging;+mod notifications;mod palette;mod qr;mod settings;@@ -93,6 +95,18 @@ fn watch_network() {});}+/// Phone notifications as Windows toasts, sent by "Nectarlink" with the+/// app's icon (written as a PNG, which Windows needs as a file).+fn start_toasts() {+ let icon = core_host::host().data_dir.join("cache").join("nectarlink.png");+ if !icon.exists()+ && let Err(e) = win::icon::write_png(&icon, 256)+ {+ tracing::warn!(error = %e, "can't write the app icon");+ }+ win::toast::start(&icon, notifications::on_toast);+}+fn install_panic_logging() {let default = std::panic::take_hook();std::panic::set_hook(Box::new(move |info| {@@ -124,11 +138,14 @@ fn main() -> ExitCode {}};+ // Before any window: toasts and the taskbar both go by this ID.+ win::toast::set_process_id();if let Err(e) = core_host::start(data_dir, Arc::new(DesktopPlatform)) {tracing::error!(error = %e, "can't start the core runtime");return ExitCode::FAILURE;}watch_network();+ start_toasts();bridge::native::ffi::prepare_qt();let mut app = QGuiApplication::new();diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rsnew file mode 100644index 0000000..5fb1036--- /dev/null+++ b/desktop/app/src/notifications.rs@@ -0,0 +1,151 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! Phone notifications on this PC: app icons are saved for QML and toasts,+//! notifications become Windows toasts (removed again when the phone clears+//! them), and what the user does with a toast or the feed goes back to the+//! phone.++use std::{+ collections::{HashMap, HashSet},+ sync::Mutex,+};++use nectarlink_core::{DeviceId, Error, NodeEvent, Notification};++use crate::{+ core_host, icons,+ state::Changes,+ win::toast::{self, Toast, ToastEvent},+};++/// Keys that have a toast, per device, so a snapshot can remove the toasts+/// of notifications that went away meanwhile.+static TOASTED: Mutex<Option<HashMap<DeviceId, HashSet<String>>>> = Mutex::new(None);++fn toasted<T>(f: impl FnOnce(&mut HashMap<DeviceId, HashSet<String>>) -> T) -> T {+ f(TOASTED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new))+}++/// Saves the app icons an event carries; returns where each app's went.+fn save_icons(event: &NodeEvent) -> Vec<(String, std::path::PathBuf)> {+ let items: Vec<&Notification> = match event {+ NodeEvent::NotificationsReset { items, .. } => items.iter().collect(),+ NodeEvent::NotificationPosted { notification, .. } => vec![notification],+ _ => return Vec::new(),+ };+ let data_dir = &core_host::host().data_dir;+ items+ .into_iter()+ .filter_map(|n| {+ let icon = n.icon.as_ref()?;+ match icons::save(data_dir, &n.app, icon) {+ Ok(path) => Some((n.app.clone(), path)),+ Err(e) => {+ tracing::debug!(app = %n.app, error = %e, "can't save an app icon");+ None+ }+ }+ })+ .collect()+}++/// Folds an event into the hub, saving icons first.+pub fn apply(event: &NodeEvent) {+ let icons = save_icons(event);+ core_host::host().hub.update(|s| {+ let mut changes = Changes::NONE;+ for (app, path) in icons {+ changes |= s.set_app_icon(&app, path);+ }+ changes | s.apply(event)+ });+}++/// Shows, updates or removes toasts after an event.+pub fn update_toasts(event: &NodeEvent) {+ match event {+ NodeEvent::NotificationPosted { device, notification } => show(*device, notification),+ NodeEvent::NotificationRemoved { device, key } => {+ toasted(|t| t.get_mut(device).map(|keys| keys.remove(key)));+ toast::remove(&device.to_string(), key);+ }+ NodeEvent::NotificationsReset { device, items } => {+ let keep: HashSet<&str> = items.iter().map(|n| n.key.as_str()).collect();+ let gone: Vec<String> = toasted(|t| {+ let keys = t.entry(*device).or_default();+ let gone = keys.iter().filter(|k| !keep.contains(k.as_str())).cloned().collect();+ keys.retain(|k| keep.contains(k.as_str()));+ gone+ });+ for key in gone {+ toast::remove(&device.to_string(), &key);+ }+ }+ NodeEvent::DeviceRemoved(device) => {+ toasted(|t| t.remove(device));+ toast::remove_device(&device.to_string());+ }+ _ => {}+ }+}++fn show(device: DeviceId, n: &Notification) {+ let (device_name, icon) =+ core_host::host().hub.read(|s| (s.name_of(&device), s.app_icons.get(&n.app).cloned()));+ let reply = n.actions.iter().find(|a| a.reply);+ let toast = Toast {+ device: device.to_string(),+ key: n.key.clone(),+ title: n.title.clone().unwrap_or_else(|| n.app_name.clone()),+ body: n.text.clone().unwrap_or_default(),+ attribution: match device_name {+ Some(name) => format!("{} · {name}", n.app_name),+ None => n.app_name.clone(),+ },+ icon,+ actions: n.actions.iter().filter(|a| !a.reply).map(|a| (a.id.clone(), a.title.clone())).collect(),+ reply: reply.map(|a| (a.id.clone(), a.title.clone())),+ silent: n.silent,+ };+ toasted(|t| t.entry(device).or_default().insert(n.key.clone()));+ toast::show(toast);+}++/// What the user did with a toast.+pub fn on_toast(event: ToastEvent) {+ match event {+ ToastEvent::Opened { .. } => crate::bridge::app::request_activation(),+ ToastEvent::Action { device, key, action } => run_action(&device, key, action, None),+ ToastEvent::Reply { device, key, action, text } => run_action(&device, key, action, Some(text)),+ ToastEvent::Dismissed { device, key } => dismiss(&device, key),+ }+}++/// Dismisses a phone notification there (and here right away).+pub fn dismiss(device: &str, key: String) {+ let (Ok(device), Some(node)) = (device.parse::<DeviceId>(), core_host::node()) else { return };+ core_host::host().hub.update(|s| s.apply(&NodeEvent::NotificationRemoved { device, key: key.clone() }));+ toast::remove(&device.to_string(), &key);+ core_host::spawn(async move {+ if let Err(e) = node.dismiss_notification(device, key).await {+ report(&e);+ }+ });+}++/// Runs a notification's action on the phone (`reply` for a reply action).+pub fn run_action(device: &str, key: String, action: String, reply: Option<String>) {+ let (Ok(device), Some(node)) = (device.parse::<DeviceId>(), core_host::node()) else { return };+ core_host::spawn(async move {+ if let Err(e) = node.run_notification_action(device, key, action, reply).await {+ report(&e);+ }+ });+}++fn report(error: &Error) {+ let message = match error {+ Error::NotFound => "That notification is gone from the phone.".to_owned(),+ other => crate::bridge::app::describe(other),+ };+ crate::bridge::app::show_message(message);+}diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex cb5c327..cc78574 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -5,13 +5,14 @@use std::{collections::HashMap,+ path::PathBuf,sync::{Arc, Mutex, MutexGuard},time::SystemTime,};use nectarlink_core::{- Battery, CapabilityMatrix, DeviceId, DeviceInfo, DiscoveredDevice, LinkState, NodeEvent, PairedDevice,- PairingEvent, PairingFailure, PowerLevel,+ Battery, CapabilityMatrix, DeviceId, DeviceInfo, DiscoveredDevice, LinkState, NodeEvent, Notification,+ PairedDevice, PairingEvent, PairingFailure, PowerLevel,};/// Which parts of the state changed, so listeners refresh only what they show.@@ -26,6 +27,7 @@ impl Changes {pub const PAIRING: Changes = Changes(1 << 3);pub const CAPABILITIES: Changes = Changes(1 << 4);pub const RINGING: Changes = Changes(1 << 5);+ pub const NOTIFICATIONS: Changes = Changes(1 << 6);pub fn is_empty(self) -> bool {self.0 == 0@@ -114,6 +116,17 @@ pub enum PairingView {Failed(PairingFailure),}+/// A phone notification as the UI shows it. The icon bytes are kept on disk+/// (see [`AppState::app_icons`]), not here.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NotificationView {+ pub device: DeviceId,+ pub notification: Notification,+}++/// The most notifications kept; the oldest go first.+pub const MAX_NOTIFICATIONS: usize = 200;+#[derive(Debug, Default)]pub struct AppState {pub status: Option<CoreStatus>,@@ -126,6 +139,10 @@ pub struct AppState {pub matrices_version: u32,/// The device that asked this PC to ring, while it rings.pub ringing_from: Option<DeviceId>,+ /// Phone notifications, newest first.+ pub notifications: Vec<NotificationView>,+ /// App icon files by package name.+ pub app_icons: HashMap<String, PathBuf>,}impl AppState {@@ -186,6 +203,11 @@ impl AppState {self.ringing_from = None;changes |= Changes::RINGING;}+ let notifications = self.notifications.len();+ self.notifications.retain(|n| n.device != *id);+ if self.notifications.len() != notifications {+ changes |= Changes::NOTIFICATIONS;+ }changes}NodeEvent::LinkChanged { device, link } => self.update_device(device, |d| d.link = link.clone()),@@ -224,9 +246,48 @@ impl AppState {if self.discovered.len() == before { Changes::NONE } else { Changes::DISCOVERED }}NodeEvent::Pairing(event) => self.apply_pairing(event),+ NodeEvent::NotificationsReset { device, items } => {+ let before = self.notifications.len();+ self.notifications.retain(|n| n.device != *device);+ if before == self.notifications.len() && items.is_empty() {+ return Changes::NONE;+ }+ for n in items {+ self.insert_notification(*device, n.clone());+ }+ Changes::NOTIFICATIONS+ }+ NodeEvent::NotificationPosted { device, notification } => {+ self.notifications+ .retain(|n| !(n.device == *device && n.notification.key == notification.key));+ self.insert_notification(*device, notification.clone());+ Changes::NOTIFICATIONS+ }+ NodeEvent::NotificationRemoved { device, key } => {+ let before = self.notifications.len();+ self.notifications.retain(|n| !(n.device == *device && n.notification.key == *key));+ if before == self.notifications.len() { Changes::NONE } else { Changes::NOTIFICATIONS }+ }}}+ /// Adds a notification in time order (newest first), without its icon.+ fn insert_notification(&mut self, device: DeviceId, mut notification: Notification) {+ notification.icon = None;+ let at = self.notifications.partition_point(|n| n.notification.when >= notification.when);+ self.notifications.insert(at, NotificationView { device, notification });+ self.notifications.truncate(MAX_NOTIFICATIONS);+ }++ /// Records where an app's icon is stored.+ pub fn set_app_icon(&mut self, app: &str, path: PathBuf) -> Changes {+ if self.app_icons.get(app) == Some(&path) {+ return Changes::NONE;+ }+ self.app_icons.insert(app.to_owned(), path);+ Changes::NOTIFICATIONS+ }+fn update_device(&mut self, id: &DeviceId, f: impl FnOnce(&mut DeviceView)) -> Changes {let Some(device) = self.device_mut(id) else { return Changes::NONE };let before = device.clone();@@ -421,6 +482,75 @@ mod tests {assert!(s.discovered.is_empty());}+ fn note(key: &str, when: i64) -> Notification {+ Notification {+ key: key.into(),+ app: "com.chat".into(),+ app_name: "Chat".into(),+ title: Some(key.to_uppercase()),+ text: Some("hi".into()),+ sub: None,+ when,+ actions: Vec::new(),+ silent: false,+ icon: Some(vec![1, 2, 3]),+ }+ }++ fn keys(s: &AppState) -> Vec<&str> {+ s.notifications.iter().map(|n| n.notification.key.as_str()).collect()+ }++ #[test]+ fn notifications_stay_newest_first_and_follow_the_phone() {+ let mut s = AppState::default();+ let (phone, other) = (DeviceId([1; 32]), DeviceId([2; 32]));+ let reset =+ NodeEvent::NotificationsReset { device: phone, items: vec![note("a", 10), note("b", 30)] };+ assert_eq!(s.apply(&reset), Changes::NOTIFICATIONS);+ s.apply(&NodeEvent::NotificationPosted { device: other, notification: note("c", 20) });+ assert_eq!(keys(&s), ["b", "c", "a"]);+ assert!(s.notifications.iter().all(|n| n.notification.icon.is_none()), "icons live on disk");++ // An update replaces the old version and moves to its new time.+ s.apply(&NodeEvent::NotificationPosted { device: phone, notification: note("a", 40) });+ assert_eq!(keys(&s), ["a", "b", "c"]);++ assert_eq!(+ s.apply(&NodeEvent::NotificationRemoved { device: phone, key: "b".into() }),+ Changes::NOTIFICATIONS+ );+ assert_eq!(+ s.apply(&NodeEvent::NotificationRemoved { device: phone, key: "b".into() }),+ Changes::NONE+ );++ // A snapshot replaces only that phone's notifications.+ s.apply(&NodeEvent::NotificationsReset { device: phone, items: Vec::new() });+ assert_eq!(keys(&s), ["c"]);+ assert_eq!(+ s.apply(&NodeEvent::NotificationsReset { device: phone, items: Vec::new() }),+ Changes::NONE+ );++ // Unpairing forgets them.+ assert!(s.apply(&NodeEvent::DeviceRemoved(other)).intersects(Changes::NOTIFICATIONS));+ assert!(s.notifications.is_empty());+ }++ #[test]+ fn the_feed_is_bounded() {+ let mut s = AppState::default();+ for i in 0..(MAX_NOTIFICATIONS as i64 + 10) {+ s.apply(&NodeEvent::NotificationPosted {+ device: DeviceId([1; 32]),+ notification: note(&i.to_string(), i),+ });+ }+ assert_eq!(s.notifications.len(), MAX_NOTIFICATIONS);+ assert_eq!(s.notifications[0].notification.when, MAX_NOTIFICATIONS as i64 + 9, "the oldest go first");+ }+#[test]fn hub_notifies_interested_listeners_and_drops_dead_ones() {let hub = Hub::new();diff --git a/desktop/app/src/win/icon.rs b/desktop/app/src/win/icon.rsindex 6f5888d..597e457 100644--- a/desktop/app/src/win/icon.rs+++ b/desktop/app/src/win/icon.rs@@ -80,6 +80,47 @@ fn dist_to_segment(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {((p.0 - qx).powi(2) + (p.1 - qy).powi(2)).sqrt()}+/// Writes the mark as a PNG file (for places that want an image file, such+/// as the notification sender icon).+pub fn write_png(path: &std::path::Path, size: u32) -> windows::core::Result<()> {+ use windows::{+ Win32::{+ Foundation::GENERIC_WRITE,+ Graphics::Imaging::{+ CLSID_WICImagingFactory, GUID_ContainerFormatPng, GUID_WICPixelFormat32bppBGRA,+ IWICImagingFactory, WICBitmapEncoderNoCache,+ },+ System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance},+ },+ core::HSTRING,+ };+ let rgba = render(size as usize);+ let bgra: Vec<u8> = rgba.as_chunks::<4>().0.iter().flat_map(|&[r, g, b, a]| [b, g, r, a]).collect();+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)+ .map_err(|e| windows::core::Error::new(windows::core::HRESULT(-1), e.to_string()))?;+ }+ // SAFETY: plain WIC calls on live interfaces; the pixel buffer holds+ // size * size BGRA pixels, matching the frame size and stride.+ unsafe {+ let factory: IWICImagingFactory =+ CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;+ let stream = factory.CreateStream()?;+ stream.InitializeFromFilename(&HSTRING::from(path.as_os_str()), GENERIC_WRITE.0)?;+ let encoder = factory.CreateEncoder(&GUID_ContainerFormatPng, std::ptr::null())?;+ encoder.Initialize(&stream, WICBitmapEncoderNoCache)?;+ let mut frame = None;+ encoder.CreateNewFrame(&mut frame, std::ptr::null_mut())?;+ let frame = frame.ok_or_else(|| windows::core::Error::from(windows::Win32::Foundation::E_FAIL))?;+ frame.Initialize(None)?;+ frame.SetSize(size, size)?;+ let mut format = GUID_WICPixelFormat32bppBGRA;+ frame.SetPixelFormat(&mut format)?;+ frame.WritePixels(size, size * 4, &bgra)?;+ frame.Commit()?;+ encoder.Commit()+ }+}#[cfg(test)]mod tests {use super::*;diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rsindex 762660f..a5664ef 100644--- a/desktop/app/src/win/mod.rs+++ b/desktop/app/src/win/mod.rs@@ -9,6 +9,7 @@ pub mod icon;pub mod net;pub mod single_instance;pub mod sound;+pub mod toast;pub mod tray;pub mod wallpaper;diff --git a/desktop/app/src/win/toast.rs b/desktop/app/src/win/toast.rsnew file mode 100644index 0000000..7d770ef--- /dev/null+++ b/desktop/app/src/win/toast.rs@@ -0,0 +1,392 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! Phone notifications as Windows toasts, with the app's icon, its actions+//! and an inline reply field.+//!+//! Nectarlink isn't a packaged app, so it registers an AppUserModelID under+//! HKCU (display name and icon) and gives the process that ID. Toasts are+//! driven from one thread with COM initialized; clicks, replies and+//! dismissals come back through per-toast handlers while the app runs.+//! Toasts left over from an earlier run are cleared at startup, since their+//! handlers are gone.++use std::{+ path::{Path, PathBuf},+ sync::{Mutex, OnceLock, mpsc},+};++use windows::{+ Data::Xml::Dom::XmlDocument,+ Foundation::{IPropertyValue, TypedEventHandler},+ UI::Notifications::{+ NotificationSetting, ToastActivatedEventArgs, ToastDismissalReason, ToastDismissedEventArgs,+ ToastNotification, ToastNotificationManager, ToastNotifier,+ },+ Win32::{+ System::{+ Com::{COINIT_MULTITHREADED, CoInitializeEx},+ Registry::{+ HKEY, HKEY_CURRENT_USER, KEY_WRITE, REG_OPTION_NON_VOLATILE, REG_SZ, RegCloseKey,+ RegCreateKeyExW, RegSetValueExW,+ },+ },+ UI::Shell::SetCurrentProcessExplicitAppUserModelID,+ },+ core::{HSTRING, IInspectable, Interface},+};++/// The app's AppUserModelID: toasts are grouped and attributed by it.+pub const AUMID: &str = "Nectarlink.Desktop";++/// What the user did with a toast.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ToastEvent {+ /// Clicked the toast itself.+ Opened { device: String, key: String },+ /// Clicked an action button.+ Action { device: String, key: String, action: String },+ /// Sent text from the reply field.+ Reply { device: String, key: String, action: String, text: String },+ /// Closed it (not timed out).+ Dismissed { device: String, key: String },+}++/// One toast to show.+#[derive(Clone)]+pub struct Toast {+ /// The phone's device ID (the toast group).+ pub device: String,+ /// The notification key (hashed into the toast tag).+ pub key: String,+ pub title: String,+ pub body: String,+ /// "WhatsApp · Pixel 9".+ pub attribution: String,+ pub icon: Option<PathBuf>,+ /// `(action id, label)`.+ pub actions: Vec<(String, String)>,+ /// `(action id, placeholder)` for an inline reply.+ pub reply: Option<(String, String)>,+ pub silent: bool,+}++impl std::fmt::Debug for Toast {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Toast").field("device", &self.device).finish_non_exhaustive()+ }+}++enum Command {+ Show(Box<Toast>),+ Remove { device: String, key: String },+ RemoveDevice { device: String },+}++type Handler = Box<dyn Fn(ToastEvent) + Send + Sync>;++struct Toaster {+ commands: mpsc::Sender<Command>,+}++static TOASTER: OnceLock<Mutex<Toaster>> = OnceLock::new();++/// Whether Windows shows this app's notifications. The user can turn them+/// off for all apps or for this one (Settings > System > Notifications).+pub fn enabled() -> bool {+ ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(AUMID))+ .and_then(|notifier| notifier.Setting())+ .map_or(true, |setting| setting == NotificationSetting::Enabled)+}++/// Gives the process the app's ID. Call before any window is created.+pub fn set_process_id() {+ // SAFETY: the ID is a valid null-terminated string for the call.+ if let Err(e) = unsafe { SetCurrentProcessExplicitAppUserModelID(&HSTRING::from(AUMID)) } {+ tracing::warn!(error = %e, "can't set the app's ID");+ }+}++/// Registers the app for toasts and starts the toast thread. `icon` is a+/// PNG of the app icon; `on_event` gets what the user does with toasts.+pub fn start(icon: &Path, on_event: impl Fn(ToastEvent) + Send + Sync + 'static) {+ if let Err(e) = register(icon) {+ tracing::warn!(error = %e, "can't register for notifications");+ }+ let (commands, queue) = mpsc::channel();+ let handler: Handler = Box::new(on_event);+ let spawned = std::thread::Builder::new().name("toasts".into()).spawn(move || run(queue, handler));+ match spawned {+ Ok(_) => {+ let _ = TOASTER.set(Mutex::new(Toaster { commands }));+ }+ Err(e) => tracing::warn!(error = %e, "can't start notifications"),+ }+}++fn send(command: Command) {+ if let Some(toaster) = TOASTER.get() {+ let _ = toaster.lock().unwrap_or_else(|e| e.into_inner()).commands.send(command);+ }+}++pub fn show(toast: Toast) {+ send(Command::Show(Box::new(toast)));+}++pub fn remove(device: &str, key: &str) {+ send(Command::Remove { device: device.to_owned(), key: key.to_owned() });+}++/// Removes every toast of a device (it stopped sharing, or was unpaired).+pub fn remove_device(device: &str) {+ send(Command::RemoveDevice { device: device.to_owned() });+}++/// `HKCU\Software\Classes\AppUserModelId\<AUMID>`: how Windows names the+/// sender of toasts from an unpackaged app.+fn register(icon: &Path) -> windows::core::Result<()> {+ let key_path = HSTRING::from(format!(r"Software\Classes\AppUserModelId\{AUMID}"));+ let mut key = HKEY::default();+ // SAFETY: creating/opening a key under HKCU with a valid path; the handle+ // is closed below.+ unsafe {+ RegCreateKeyExW(+ HKEY_CURRENT_USER,+ &key_path,+ None,+ None,+ REG_OPTION_NON_VOLATILE,+ KEY_WRITE,+ None,+ &mut key,+ None,+ )+ .ok()?;+ }+ let set = |name: &str, value: &str| {+ let wide: Vec<u16> = value.encode_utf16().chain(std::iter::once(0)).collect();+ // SAFETY: the data is a null-terminated UTF-16 string of the given size.+ unsafe {+ RegSetValueExW(+ key,+ &HSTRING::from(name),+ None,+ REG_SZ,+ Some(std::slice::from_raw_parts(wide.as_ptr().cast::<u8>(), wide.len() * 2)),+ )+ }+ .ok()+ };+ let result = set("DisplayName", "Nectarlink").and_then(|()| set("IconUri", &icon.to_string_lossy()));+ // SAFETY: the key was opened above.+ unsafe {+ let _ = RegCloseKey(key);+ }+ result+}++fn run(queue: mpsc::Receiver<Command>, handler: Handler) {+ // SAFETY: initializes COM for this thread, which lives as long as the app.+ if let Err(e) = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok() {+ tracing::warn!(error = %e, "notifications are unavailable");+ return;+ }+ let notifier = match ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(AUMID)) {+ Ok(notifier) => notifier,+ Err(e) => {+ tracing::warn!(error = %e, "notifications are unavailable");+ return;+ }+ };+ let history = ToastNotificationManager::History().ok();+ let aumid = HSTRING::from(AUMID);+ if let Some(history) = &history {+ let _ = history.ClearWithId(&aumid);+ }+ let handler: &'static Handler = Box::leak(Box::new(handler));+ while let Ok(command) = queue.recv() {+ let result = match command {+ Command::Show(toast) => show_now(¬ifier, *toast, handler),+ Command::Remove { device, key } => match &history {+ Some(h) => h.RemoveGroupedTagWithId(+ &HSTRING::from(tag(&key)),+ &HSTRING::from(group(&device)),+ &aumid,+ ),+ None => Ok(()),+ },+ Command::RemoveDevice { device } => match &history {+ Some(h) => h.RemoveGroupWithId(&HSTRING::from(group(&device)), &aumid),+ None => Ok(()),+ },+ };+ if let Err(e) = result {+ tracing::debug!(error = %e, "toast command failed");+ }+ }+}++fn show_now(notifier: &ToastNotifier, toast: Toast, handler: &'static Handler) -> windows::core::Result<()> {+ let xml = XmlDocument::new()?;+ xml.LoadXml(&HSTRING::from(toast_xml(&toast)))?;+ let notification = ToastNotification::CreateToastNotification(&xml)?;+ notification.SetTag(&HSTRING::from(tag(&toast.key)))?;+ notification.SetGroup(&HSTRING::from(group(&toast.device)))?;+ // Silent on the phone: straight to the notification center, no pop-up.+ notification.SetSuppressPopup(toast.silent)?;++ let (device, key) = (toast.device.clone(), toast.key.clone());+ notification.Activated(&TypedEventHandler::<ToastNotification, IInspectable>::new(move |_, args| {+ let Some(args) = args.as_ref().and_then(|a| a.cast::<ToastActivatedEventArgs>().ok()) else {+ return Ok(());+ };+ let arguments = args.Arguments()?.to_string();+ let event = match arguments.strip_prefix("a:") {+ None => ToastEvent::Opened { device: device.clone(), key: key.clone() },+ Some(action) => match reply_text(&args) {+ Some(text) => ToastEvent::Reply {+ device: device.clone(),+ key: key.clone(),+ action: action.into(),+ text,+ },+ None => {+ ToastEvent::Action { device: device.clone(), key: key.clone(), action: action.into() }+ }+ },+ };+ handler(event);+ Ok(())+ }))?;+ let (device, key) = (toast.device.clone(), toast.key.clone());+ notification.Dismissed(&TypedEventHandler::<ToastNotification, ToastDismissedEventArgs>::new(+ move |_, args| {+ if let Some(args) = args.as_ref()+ && args.Reason()? == ToastDismissalReason::UserCanceled+ {+ handler(ToastEvent::Dismissed { device: device.clone(), key: key.clone() });+ }+ Ok(())+ },+ ))?;+ notifier.Show(¬ification)+}++/// The text typed in the reply field, if any.+fn reply_text(args: &ToastActivatedEventArgs) -> Option<String> {+ let value = args.UserInput().ok()?.Lookup(&HSTRING::from(REPLY_INPUT)).ok()?;+ let text = value.cast::<IPropertyValue>().ok()?.GetString().ok()?.to_string();+ let text = text.trim();+ (!text.is_empty()).then(|| text.to_owned())+}++const REPLY_INPUT: &str = "reply";++/// Toast tags are short; a stable hash of the key (FNV-1a) fits and stays+/// the same across runs.+fn tag(key: &str) -> String {+ let hash =+ key.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));+ format!("{hash:016x}")+}++fn group(device: &str) -> String {+ device.chars().take(16).collect()+}++fn escape(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ for c in text.chars() {+ match c {+ '&' => out.push_str("&"),+ '<' => out.push_str("<"),+ '>' => out.push_str(">"),+ '"' => out.push_str("""),+ '\'' => out.push_str("'"),+ // Characters XML 1.0 can't hold.+ c if (c as u32) < 0x20 && !matches!(c, '\t' | '\n' | '\r') => {}+ c => out.push(c),+ }+ }+ out+}++/// The toast's XML (Windows toast schema).+fn toast_xml(toast: &Toast) -> String {+ let mut xml = String::from(r#"<toast launch="open"><visual><binding template="ToastGeneric">"#);+ xml.push_str(&format!(r#"<text hint-maxLines="1">{}</text>"#, escape(&toast.title)));+ if !toast.body.is_empty() {+ xml.push_str(&format!("<text>{}</text>", escape(&toast.body)));+ }+ xml.push_str(&format!(r#"<text placement="attribution">{}</text>"#, escape(&toast.attribution)));+ if let Some(icon) = &toast.icon {+ xml.push_str(&format!(+ r#"<image placement="appLogoOverride" src="{}"/>"#,+ escape(&crate::icons::file_url(icon))+ ));+ }+ xml.push_str("</binding></visual>");+ if toast.reply.is_some() || !toast.actions.is_empty() {+ xml.push_str("<actions>");+ if let Some((action, placeholder)) = &toast.reply {+ xml.push_str(&format!(+ r#"<input id="{REPLY_INPUT}" type="text" placeHolderContent="{}"/>"#,+ escape(placeholder)+ ));+ xml.push_str(&format!(+ r#"<action content="Send" arguments="a:{}" hint-inputId="{REPLY_INPUT}"/>"#,+ escape(action)+ ));+ }+ // Windows shows at most five buttons, the send button included.+ let room = 5 - usize::from(toast.reply.is_some());+ for (id, label) in toast.actions.iter().take(room) {+ xml.push_str(&format!(r#"<action content="{}" arguments="a:{}"/>"#, escape(label), escape(id)));+ }+ xml.push_str("</actions>");+ }+ if toast.silent {+ xml.push_str(r#"<audio silent="true"/>"#);+ }+ xml.push_str("</toast>");+ xml+}++#[cfg(test)]+mod tests {+ use super::*;++ fn toast() -> Toast {+ Toast {+ device: "abcdefgh12345678xyz".into(),+ key: "0|com.chat|1|null|10123".into(),+ title: "Sam & <Alex>".into(),+ body: "Lunch \"today\"?\u{7}".into(),+ attribution: "Chat · Pixel".into(),+ icon: Some(PathBuf::from(r"C:\data\cache\icons\com.chat.png")),+ actions: (0..6).map(|i| (i.to_string(), format!("Action {i}"))).collect(),+ reply: Some(("r".into(), "Reply".into())),+ silent: true,+ }+ }++ #[test]+ fn builds_valid_toast_xml() {+ let xml = toast_xml(&toast());+ assert!(xml.contains("Sam & <Alex>"), "{xml}");+ assert!(xml.contains("Lunch "today"?</text>"), "control characters are dropped: {xml}");+ assert!(xml.contains(r#"src="file:///C:/data/cache/icons/com.chat.png""#));+ assert!(xml.contains(r#"arguments="a:r" hint-inputId="reply""#));+ assert_eq!(xml.matches("<action ").count(), 5, "five buttons at most");+ assert!(xml.ends_with(r#"<audio silent="true"/></toast>"#));+ // Windows parses it.+ XmlDocument::new().unwrap().LoadXml(&HSTRING::from(xml)).expect("well-formed XML");+ }++ #[test]+ fn tags_are_short_and_stable() {+ assert_eq!(tag("a"), tag("a"));+ assert_ne!(tag("a"), tag("b"));+ assert_eq!(tag("0|com.chat|1|null|10123").len(), 16);+ assert_eq!(group("abcdefgh12345678xyz"), "abcdefgh12345678");+ }+}