Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Desktop: a smoother notification feed, sent replies, cleaner Mica

Bee88fa5bf5eaa4
diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qml
index be6de93..3cad59f 100644
--- a/desktop/app/qml/MainWindow.qml
+++ b/desktop/app/qml/MainWindow.qml
@@ -16,7 +16,39 @@ NativeWindow {
minimumWidth: Theme.layout.minWindow[0]
minimumHeight: Theme.layout.minWindow[1]
title: "Nectarlink"
- backdrop: Preferences.backdrop
+ // Mica is applied by Windows a moment after it's requested. Showing
+ // through before it's there reveals the bare desktop (a flash), so the
+ // window turns translucent only once Mica is in place, and opaque again
+ // before Mica is removed.
+ property bool micaApplied: false
+ property bool micaVisible: false
+ backdrop: micaApplied
+ Timer {
+ id: micaSettle
+ interval: 280
+ onTriggered: window.micaVisible = Preferences.backdrop
+ }
+ Timer {
+ id: micaRelease
+ interval: Theme.fadeNormal + 60
+ onTriggered: window.micaApplied = Preferences.backdrop
+ }
+ function followBackdrop() {
+ if (Preferences.backdrop) {
+ micaRelease.stop()
+ micaApplied = true
+ micaSettle.restart()
+ } else {
+ micaSettle.stop()
+ micaVisible = false
+ micaRelease.restart()
+ }
+ }
+ Connections {
+ target: Preferences
+ function onBackdropChanged() { window.followBackdrop() }
+ }
+ Component.onCompleted: followBackdrop()
darkFrame: Theme.dark
captionHeight: Theme.topBarHeight
@@ -37,11 +69,12 @@ NativeWindow {
function openPairing() { pairingSheet.open() }
- // Window background: translucent over Mica, opaque otherwise.
+ // Window background: a light veil of the theme over Mica (so the
+ // desktop's colors come through, as Mica is meant to), opaque otherwise.
Rectangle {
anchors.fill: parent
- color: Preferences.backdrop ? Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.7 : 0.62)
- : Theme.surface
+ color: window.micaVisible ? Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.45 : 0.32)
+ : Theme.surface
Behavior on color { ColorAnimation { duration: Theme.fadeNormal } }
}
@@ -51,7 +84,7 @@ NativeWindow {
visible: !window.welcome
width: Theme.railWidth
height: parent.height
- color: Preferences.backdrop ? "transparent" : Theme.railColor
+ color: window.micaVisible ? "transparent" : Theme.railColor
Rectangle {
id: mark
diff --git a/desktop/app/qml/components/NotificationItem.qml b/desktop/app/qml/components/NotificationItem.qml
index 117c4ba..9215da8 100644
--- a/desktop/app/qml/components/NotificationItem.qml
+++ b/desktop/app/qml/components/NotificationItem.qml
@@ -17,13 +17,18 @@ Item {
required property string actions
required property string replyAction
required property string replyLabel
+ required property string replies
+ // Bumped by the feed every minute, so relative times stay right.
+ property int clock: 0
readonly property var buttons: { try { return JSON.parse(actions) } catch (e) { return [] } }
+ readonly property var sent: { try { return JSON.parse(replies) } catch (e) { return [] } }
property bool replying: false
implicitHeight: content.height + 24
function timeText() {
+ clock // re-evaluated each minute
const minutes = Math.round((Date.now() - when) / 60000)
if (minutes < 1) return qsTr("now")
if (minutes < 60) return qsTr("%n min", "", minutes)
@@ -40,13 +45,22 @@ Item {
item.replying = false
}
- HoverHandler { id: hover }
+ // Hover tracking only: clicks go to the buttons inside.
+ MouseArea {
+ id: hover
+ anchors.fill: parent
+ hoverEnabled: true
+ acceptedButtons: Qt.NoButton
+ readonly property bool hovered: containsMouse
+ }
+ // A light wash of the text color, so hovering never looks like selection.
Rectangle {
anchors.fill: parent
radius: Theme.radiusMd
- color: hover.hovered ? (Theme.graphite ? Theme.surfaceContainer : Theme.surfaceContainerHigh) : "transparent"
- Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+ color: Theme.surfaceContent
+ opacity: hover.hovered ? 0.045 : 0
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }
}
// App icon, or its initial when the phone didn't send one.
@@ -101,6 +115,32 @@ Item {
maximumLineCount: 4
}
+ // Replies sent from this PC.
+ Repeater {
+ model: item.sent
+ delegate: Row {
+ required property var modelData
+ width: content.width
+ spacing: 6
+ opacity: modelData.pending ? 0.55 : 1
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }
+ Icon {
+ width: 14; height: 14
+ anchors.verticalCenter: parent.verticalCenter
+ path: modelData.pending ? Icons.send : Icons.check
+ color: Theme.primary
+ }
+ Txt {
+ width: parent.width - 20
+ role: "bodySmall"
+ muted: true
+ wrapMode: Text.Wrap
+ maximumLineCount: 3
+ text: modelData.pending ? qsTr("Sending: %1").arg(modelData.text) : qsTr("You: %1").arg(modelData.text)
+ }
+ }
+ }
+
Flow {
width: parent.width
spacing: 6
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index 7c15cfa..e1f81e0 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -254,22 +254,65 @@ Item {
Button {
id: clearAll
anchors.right: parent.right
- visible: feed.count > 1
- variant: "text"
+ visible: feed.count > 0
+ variant: "tonal"
size: "sm"
+ iconPath: Icons.close
text: qsTr("Clear all")
onClicked: NotificationList.dismissAll(home.deviceId)
}
}
- Column {
+ // Ticks every minute so "5 min" ages without new events.
+ Timer {
+ id: feedClock
+ property int minutes: 0
+ interval: 60000
+ repeat: true
+ running: feed.count > 0
+ onTriggered: minutes++
+ }
+ // The page scrolls; this list only lays out and animates:
+ // new notifications fade and slide in, dismissed ones fade
+ // out, and the rest glide into place.
+ ListView {
+ id: list
width: parent.width
- Repeater {
- model: NotificationList
- delegate: NotificationItem {
- width: parent.width
- visible: deviceId === home.deviceId
+ height: contentHeight
+ interactive: false
+ model: NotificationList
+ delegate: NotificationItem {
+ width: list.width
+ clock: feedClock.minutes
+ visible: deviceId === home.deviceId
+ height: visible ? implicitHeight : 0
+ }
+ add: Transition {
+ enabled: !Theme.reduceMotion
+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 220; easing.type: Easing.OutCubic }
+ NumberAnimation {
+ property: "y"
+ from: ViewTransition.destination.y - 10
+ to: ViewTransition.destination.y
+ duration: 260
+ easing.type: Easing.OutCubic
}
}
+ addDisplaced: Transition {
+ enabled: !Theme.reduceMotion
+ NumberAnimation { property: "y"; duration: 240; easing.type: Easing.OutCubic }
+ }
+ remove: Transition {
+ enabled: !Theme.reduceMotion
+ NumberAnimation { property: "opacity"; to: 0; duration: 160 }
+ }
+ removeDisplaced: Transition {
+ enabled: !Theme.reduceMotion
+ NumberAnimation { property: "y"; duration: 240; easing.type: Easing.OutCubic }
+ }
+ Behavior on height {
+ enabled: !Theme.reduceMotion
+ NumberAnimation { duration: 240; easing.type: Easing.OutCubic }
+ }
}
// Empty: say why, and what turns it on.
Txt {
diff --git a/desktop/app/src/bridge/devices.rs b/desktop/app/src/bridge/devices.rs
index 4859589..f94629f 100644
--- a/desktop/app/src/bridge/devices.rs
+++ b/desktop/app/src/bridge/devices.rs
@@ -54,12 +54,6 @@ pub mod qobject {
#[cxx_name = "endRemoveRows"]
unsafe fn end_remove_rows(self: Pin<&mut DeviceList>);
#[inherit]
- #[cxx_name = "beginResetModel"]
- unsafe fn begin_reset_model(self: Pin<&mut DeviceList>);
- #[inherit]
- #[cxx_name = "endResetModel"]
- unsafe fn end_reset_model(self: Pin<&mut DeviceList>);
- #[inherit]
fn index(self: &DeviceList, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex;
#[inherit]
@@ -182,43 +176,31 @@ 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, |d| d.id) {
- 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();
+ for edit in diff(&self.rows, &new, |d| d.id) {
+ 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();
+ }
}
- }
- 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());
- }
+ 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;
@@ -276,44 +258,6 @@ 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, |d| d.id).expect("incremental") {
- match edit {
- Edit::Remove(r) => {
- rows.remove(r);
- }
- Edit::Insert(r) => rows.insert(r, new[r].clone()),
- Edit::Change(r) => rows[r] = new[r].clone(),
- }
- }
- rows
- }
-
- #[test]
- fn inserts_removes_and_changes() {
- let (a, b, c, d) = (device(1, "a"), device(2, "b"), device(3, "c"), device(4, "d"));
- let old = vec![a.clone(), b.clone(), c.clone()];
- let mut b2 = b.clone();
- b2.info.name = "b2".into();
- let new = vec![a.clone(), b2.clone(), d.clone()];
- 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, |d| d.id).unwrap(), []);
- let interleaved = vec![d.clone(), a.clone(), c.clone(), b2.clone()];
- assert_eq!(apply(&[a.clone(), b2.clone()], &interleaved), interleaved);
- }
-
- #[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], |d| d.id), None);
- }
-
#[test]
fn roles_cover_the_device() {
let mut d = device(5, "Pixel");
diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rs
index 251e253..6b15a4f 100644
--- a/desktop/app/src/bridge/mod.rs
+++ b/desktop/app/src/bridge/mod.rs
@@ -68,34 +68,85 @@ pub(crate) enum Edit {
}
/// 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>> {
+/// so QML delegates keep their state and animate. A row that moved (e.g. an
+/// updated notification going to the top) is removed and inserted again;
+/// the model is never reset.
+pub(crate) fn diff<T: PartialEq, K: PartialEq>(old: &[T], new: &[T], key: impl Fn(&T) -> K) -> 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)) {
+ // Rows as they are after each edit so far.
+ let mut rows: Vec<&T> = old.iter().collect();
+ // Removals first, from the end so earlier indices stay valid.
+ for row in (0..rows.len()).rev() {
+ if !new.iter().any(|n| key(n) == key(rows[row])) {
+ rows.remove(row);
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));
+ let k = key(item);
+ if rows.get(row).is_some_and(|r| key(r) == k) {
+ if *rows[row] != *item {
+ rows[row] = item;
+ edits.push(Edit::Change(row));
+ }
+ continue;
+ }
+ // Moved here from further down: take it out there first.
+ if let Some(from) = rows.iter().skip(row).position(|r| key(r) == k).map(|i| i + row) {
+ rows.remove(from);
+ edits.push(Edit::Remove(from));
+ }
+ rows.insert(row, item);
+ edits.push(Edit::Insert(row));
+ }
+ edits
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Applies edits the way the models do.
+ fn apply(old: &[(u8, &str)], new: &[(u8, &str)]) -> Vec<(u8, String)> {
+ let mut rows: Vec<(u8, String)> = old.iter().map(|(k, v)| (*k, (*v).to_owned())).collect();
+ for edit in diff(old, new, |r| r.0) {
+ match edit {
+ Edit::Remove(r) => {
+ rows.remove(r);
}
- next_kept += 1;
+ Edit::Insert(r) => rows.insert(r, (new[r].0, new[r].1.to_owned())),
+ Edit::Change(r) => rows[r] = (new[r].0, new[r].1.to_owned()),
}
- // 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)),
}
+ rows
+ }
+
+ fn owned(rows: &[(u8, &str)]) -> Vec<(u8, String)> {
+ rows.iter().map(|(k, v)| (*k, (*v).to_owned())).collect()
+ }
+
+ #[test]
+ fn edits_turn_old_rows_into_new_ones() {
+ type Rows<'a> = &'a [(u8, &'a str)];
+ let cases: &[(Rows, Rows)] = &[
+ (&[], &[(1, "a"), (2, "b")]),
+ (&[(1, "a"), (2, "b")], &[]),
+ (&[(1, "a"), (2, "b"), (3, "c")], &[(1, "a"), (2, "B"), (4, "d")]),
+ // An update moves to the top.
+ (&[(1, "a"), (2, "b"), (3, "c")], &[(3, "C"), (1, "a"), (2, "b")]),
+ // Reversed, with additions and removals.
+ (&[(1, "a"), (2, "b"), (3, "c"), (4, "d")], &[(5, "e"), (4, "d"), (2, "b"), (1, "a")]),
+ ];
+ for (old, new) in cases {
+ assert_eq!(apply(old, new), owned(new), "{old:?} -> {new:?}");
+ }
+ }
+
+ #[test]
+ fn unchanged_rows_need_no_edits_and_moves_touch_only_the_moved_row() {
+ let rows = [(1, "a"), (2, "b"), (3, "c")];
+ assert_eq!(diff(&rows, &rows, |r| r.0), []);
+ let moved = [(3, "c"), (1, "a"), (2, "b")];
+ assert_eq!(diff(&rows, &moved, |r| r.0), [Edit::Remove(2), Edit::Insert(0)]);
}
- Some(edits)
}
diff --git a/desktop/app/src/bridge/notifications.rs b/desktop/app/src/bridge/notifications.rs
index 2c9c5d5..9b7974a 100644
--- a/desktop/app/src/bridge/notifications.rs
+++ b/desktop/app/src/bridge/notifications.rs
@@ -11,7 +11,7 @@ use nectarlink_core::DeviceId;
use super::{Edit, diff};
use crate::{
core_host, icons,
- state::{Changes, NotificationView},
+ state::{Changes, NotificationView, SentReply},
};
#[cxx_qt::bridge]
@@ -66,12 +66,6 @@ pub mod qobject {
#[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]
@@ -129,6 +123,8 @@ struct Row {
device_name: String,
/// A file URL, or "" (the UI then shows the app's initial).
icon_url: String,
+ /// Replies sent from this PC.
+ replies: Vec<SentReply>,
}
#[derive(Default)]
@@ -153,6 +149,7 @@ const ROLES: &[&str] = &[
"replyAction",
"replyLabel",
"silent",
+ "replies",
];
const USER_ROLE: i32 = 0x0100;
@@ -185,6 +182,16 @@ fn role_value(row: &Row, role: &str) -> QVariant {
"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),
+ // As JSON: [{ "text", "pending" }].
+ "replies" => text(
+ &serde_json::Value::from(
+ row.replies
+ .iter()
+ .map(|r| serde_json::json!({ "text": r.text, "pending": r.pending }))
+ .collect::<Vec<_>>(),
+ )
+ .to_string(),
+ ),
_ => QVariant::default(),
}
}
@@ -211,48 +218,41 @@ impl qobject::NotificationList {
.get(&view.notification.app)
.map(|p| icons::file_url(p))
.unwrap_or_default(),
+ replies: s
+ .replies
+ .get(&(view.device, view.notification.key.clone()))
+ .cloned()
+ .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();
+ for edit in diff(&self.rows, &new, key_of) {
+ 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();
+ }
}
- }
- 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());
- }
+ 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;
@@ -348,6 +348,7 @@ mod tests {
},
device_name: "Pixel".into(),
icon_url: String::new(),
+ replies: vec![SentReply { text: "On my way".into(), pending: true }],
};
let text = |role| role_value(&row, role).value::<QString>().map(String::from).unwrap_or_default();
assert_eq!(text("title"), "Sam");
@@ -355,5 +356,6 @@ mod tests {
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));
+ assert_eq!(text("replies"), r#"[{"pending":true,"text":"On my way"}]"#);
}
}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 3a75e0f..a3d4f5f 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -99,12 +99,7 @@ fn watch_network() {
/// 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);
+ win::toast::start(icon, notifications::on_toast);
}
fn install_panic_logging() {
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index 5fb1036..d60ae97 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -135,8 +135,18 @@ pub fn dismiss(device: &str, key: String) {
/// 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 };
+ let hub = &core_host::host().hub;
+ // A reply shows under its notification right away, faded until the
+ // phone has taken it.
+ if let Some(text) = &reply {
+ hub.update(|s| s.reply_sending(device, &key, text));
+ }
core_host::spawn(async move {
- if let Err(e) = node.run_notification_action(device, key, action, reply).await {
+ let result = node.run_notification_action(device, key.clone(), action, reply.clone()).await;
+ if let Some(text) = &reply {
+ core_host::host().hub.update(|s| s.reply_done(device, &key, text, result.is_ok()));
+ }
+ if let Err(e) = result {
report(&e);
}
});
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index cc78574..f409e46 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -124,6 +124,14 @@ pub struct NotificationView {
pub notification: Notification,
}
+/// A reply sent from this PC to a notification, shown under it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SentReply {
+ pub text: String,
+ /// Still on its way to the phone.
+ pub pending: bool,
+}
+
/// The most notifications kept; the oldest go first.
pub const MAX_NOTIFICATIONS: usize = 200;
@@ -143,6 +151,8 @@ pub struct AppState {
pub notifications: Vec<NotificationView>,
/// App icon files by package name.
pub app_icons: HashMap<String, PathBuf>,
+ /// Replies sent from this PC, per notification, oldest first.
+ pub replies: HashMap<(DeviceId, String), Vec<SentReply>>,
}
impl AppState {
@@ -174,6 +184,14 @@ impl AppState {
/// Folds one core event into the state.
pub fn apply(&mut self, event: &NodeEvent) -> Changes {
+ let changes = self.apply_event(event);
+ if changes.intersects(Changes::NOTIFICATIONS) {
+ self.prune_replies();
+ }
+ changes
+ }
+
+ fn apply_event(&mut self, event: &NodeEvent) -> Changes {
match event {
NodeEvent::DeviceAdded(device) => {
match self.device_mut(&device.id) {
@@ -271,6 +289,34 @@ impl AppState {
}
}
+ /// Records a reply on its way to the phone.
+ pub fn reply_sending(&mut self, device: DeviceId, key: &str, text: &str) -> Changes {
+ let reply = SentReply { text: text.to_owned(), pending: true };
+ self.replies.entry((device, key.to_owned())).or_default().push(reply);
+ Changes::NOTIFICATIONS
+ }
+
+ /// The phone took the reply (`delivered`), or it failed and is dropped.
+ pub fn reply_done(&mut self, device: DeviceId, key: &str, text: &str, delivered: bool) -> Changes {
+ let id = (device, key.to_owned());
+ let Some(replies) = self.replies.get_mut(&id) else { return Changes::NONE };
+ let Some(at) = replies.iter().position(|r| r.pending && r.text == text) else { return Changes::NONE };
+ if delivered {
+ replies[at].pending = false;
+ } else {
+ replies.remove(at);
+ }
+ Changes::NOTIFICATIONS
+ }
+
+ /// Forgets replies to notifications that are gone.
+ fn prune_replies(&mut self) {
+ let notifications = &self.notifications;
+ self.replies.retain(|(device, key), _| {
+ notifications.iter().any(|n| n.device == *device && n.notification.key == *key)
+ });
+ }
+
/// Adds a notification in time order (newest first), without its icon.
fn insert_notification(&mut self, device: DeviceId, mut notification: Notification) {
notification.icon = None;
@@ -538,6 +584,26 @@ mod tests {
assert!(s.notifications.is_empty());
}
+ #[test]
+ fn replies_show_until_their_notification_goes() {
+ let mut s = AppState::default();
+ let phone = DeviceId([1; 32]);
+ s.apply(&NodeEvent::NotificationPosted { device: phone, notification: note("a", 10) });
+ s.reply_sending(phone, "a", "On my way");
+ s.reply_sending(phone, "a", "Five minutes");
+ s.reply_done(phone, "a", "On my way", true);
+ s.reply_done(phone, "a", "Five minutes", false);
+ let replies = &s.replies[&(phone, "a".to_owned())];
+ assert_eq!(
+ replies,
+ &[SentReply { text: "On my way".into(), pending: false }],
+ "failed ones are dropped"
+ );
+
+ s.apply(&NodeEvent::NotificationRemoved { device: phone, key: "a".into() });
+ assert!(s.replies.is_empty());
+ }
+
#[test]
fn the_feed_is_bounded() {
let mut s = AppState::default();
diff --git a/desktop/app/src/win/toast.rs b/desktop/app/src/win/toast.rs
index 7d770ef..6339dc1 100644
--- a/desktop/app/src/win/toast.rs
+++ b/desktop/app/src/win/toast.rs
@@ -105,15 +105,13 @@ pub fn set_process_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");
- }
+/// Starts the toast thread, which registers the app for toasts with its
+/// icon (written to `icon` as a PNG if missing); `on_event` gets what the
+/// user does with toasts.
+pub fn start(icon: PathBuf, on_event: impl Fn(ToastEvent) + Send + Sync + 'static) {
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));
+ let spawned = std::thread::Builder::new().name("toasts".into()).spawn(move || run(&icon, queue, handler));
match spawned {
Ok(_) => {
let _ = TOASTER.set(Mutex::new(Toaster { commands }));
@@ -184,12 +182,21 @@ fn register(icon: &Path) -> windows::core::Result<()> {
result
}
-fn run(queue: mpsc::Receiver<Command>, handler: Handler) {
+fn run(icon: &Path, 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;
}
+ // WIC needs COM, which is why this happens here and not on the UI thread.
+ if !icon.exists()
+ && let Err(e) = super::icon::write_png(icon, 256)
+ {
+ tracing::warn!(error = %e, "can't write the app icon");
+ }
+ if let Err(e) = register(icon) {
+ tracing::warn!(error = %e, "can't register for notifications");
+ }
let notifier = match ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(AUMID)) {
Ok(notifier) => notifier,
Err(e) => {