Skip to content

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

Desktop: per-app notification rules and a day of history

Bee9a9eacea973d
diff --git a/README.md b/README.md
index bf00770..e8f29af 100644
--- a/README.md
+++ b/README.md
@@ -73,7 +73,9 @@ place and tested; the user-facing features of Phase 1 come next.
- **Notifications** from the phone on the PC, as Windows notifications and in
a feed in the app, with the app's icon. Reply inline, run their actions
(such as "Mark as read") or dismiss them from the PC; what's cleared on one
- side is cleared on the other.
+ side is cleared on the other. Per app, choose whether they pop up, show
+ only in the app, or stay hidden, and find the last day's notifications in
+ History.
- **Clipboard**: text and images you copy on the PC are ready to paste on the
phone. From the phone, send them with the Quick Settings tile, the share
sheet or a button in the app (Android lets only the app in front read the
@@ -99,7 +101,7 @@ place and tested; the user-facing features of Phase 1 come next.
connection service, and an identity key protected by the Android Keystore.
- **Command-line client** for development and testing (`nectarlink`).
-**Next (Phase 1)**: notification filters and history, and a Windows installer. Mirroring, messages, calls and the other
+**Next (Phase 1)**: a Windows installer. Mirroring, messages, calls and the other
features in the plan follow in later phases.
## Screenshots
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index 0f0f261..7309fba 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -25,6 +25,7 @@ const QML: &[&str] = &[
"qml/components/Chip.qml",
"qml/components/CodeDigits.qml",
"qml/components/Divider.qml",
+ "qml/components/HistoryItem.qml",
"qml/components/Icon.qml",
"qml/components/IconButton.qml",
"qml/components/ListRow.qml",
@@ -187,6 +188,7 @@ fn main() {
"src/bridge/native.rs",
"src/bridge/app.rs",
"src/bridge/devices.rs",
+ "src/bridge/history.rs",
"src/bridge/media.rs",
"src/bridge/notifications.rs",
"src/bridge/pairing.rs",
diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qml
index 2da8666..865582c 100644
--- a/desktop/app/qml/Icons.qml
+++ b/desktop/app/qml/Icons.qml
@@ -19,6 +19,8 @@ QtObject {
readonly property string pause: "M9 5v14M15 5v14"
readonly property string skipNext: "M5 6.2v11.6a1 1 0 0 0 1.6.8l7.4-5.8a1 1 0 0 0 0-1.6L6.6 5.4a1 1 0 0 0-1.6.8zM19 5v14"
readonly property string skipPrevious: "M19 6.2v11.6a1 1 0 0 1-1.6.8L10 12.8a1 1 0 0 1 0-1.6l7.4-5.8a1 1 0 0 1 1.6.8zM5 5v14"
+ readonly property string more: "M5 12a1.2 1.2 0 1 0 2.4 0 1.2 1.2 0 1 0-2.4 0M10.8 12a1.2 1.2 0 1 0 2.4 0 1.2 1.2 0 1 0-2.4 0M16.6 12a1.2 1.2 0 1 0 2.4 0 1.2 1.2 0 1 0-2.4 0"
+ readonly property string history: "M3 12a9 9 0 1 0 2.6-6.4L3 8M3 3v5h5M12 7v5l3 2"
readonly property string music: "M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"
readonly property string ring: "M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8M10 20a2 2 0 0 0 4 0M2 8c0-2 1-4 2-5M22 8c0-2-1-4-2-5"
readonly property string mic: "M12 2a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V5a3 3 0 0 1 3-3zM5 11a7 7 0 0 0 14 0M12 18v4"
diff --git a/desktop/app/qml/components/HistoryItem.qml b/desktop/app/qml/components/HistoryItem.qml
new file mode 100644
index 0000000..4d8c476
--- /dev/null
+++ b/desktop/app/qml/components/HistoryItem.qml
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A notification from the last day that's no longer on the phone: app,
+// when it arrived, title and text. Read-only.
+Item {
+ id: item
+ required property string appName
+ required property string title
+ required property string text
+ required property string sub
+ required property real when
+ required property string iconUrl
+
+ implicitHeight: Math.max(icon.height, content.height) + 20
+
+ function timeText() {
+ const date = new Date(when)
+ const today = new Date().toDateString() === date.toDateString()
+ return today ? date.toLocaleTimeString(Qt.locale(), Locale.ShortFormat)
+ : qsTr("Yesterday %1").arg(date.toLocaleTimeString(Qt.locale(), Locale.ShortFormat))
+ }
+
+ Item {
+ id: icon
+ x: 4; y: 10
+ width: 28; height: 28
+ Image {
+ id: image
+ anchors.fill: parent
+ source: item.iconUrl
+ sourceSize: Qt.size(56, 56)
+ 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: 4
+ y: 10
+ spacing: 2
+ Txt {
+ width: parent.width
+ role: "caption"
+ muted: true
+ text: [item.appName, item.sub, item.timeText()].filter(s => s.length > 0).join(" · ")
+ elide: Text.ElideRight
+ }
+ Txt {
+ width: parent.width
+ visible: item.title.length > 0
+ role: "title"
+ size: 14
+ text: item.title
+ elide: Text.ElideRight
+ }
+ Txt {
+ width: parent.width
+ visible: item.text.length > 0
+ role: "bodySmall"
+ text: item.text
+ wrapMode: Text.Wrap
+ maximumLineCount: 3
+ elide: Text.ElideRight
+ }
+ }
+}
diff --git a/desktop/app/qml/components/NotificationItem.qml b/desktop/app/qml/components/NotificationItem.qml
index 9215da8..739071f 100644
--- a/desktop/app/qml/components/NotificationItem.qml
+++ b/desktop/app/qml/components/NotificationItem.qml
@@ -3,11 +3,13 @@ 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.
+// an inline reply when the app offers one, and dismiss and options buttons
+// (what this app's notifications do on this PC).
Item {
id: item
required property string deviceId
required property string key
+ required property string app
required property string appName
required property string title
required property string text
@@ -24,6 +26,7 @@ Item {
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
+ signal optionsRequested
implicitHeight: content.height + 24
@@ -89,7 +92,7 @@ Item {
anchors.left: icon.right
anchors.leftMargin: 12
anchors.right: parent.right
- anchors.rightMargin: 44
+ anchors.rightMargin: 84
y: 12
spacing: 4
@@ -215,6 +218,18 @@ Item {
}
IconButton {
+ anchors.right: dismiss.left
+ y: 8
+ iconPath: Icons.more
+ label: qsTr("Options for %1").arg(item.appName)
+ // Like 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: item.optionsRequested()
+ }
+ IconButton {
+ id: dismiss
anchors.right: parent.right
anchors.rightMargin: 8
y: 8
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index cc3ca72..dd323c4 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -360,6 +360,17 @@ Item {
muted: true
text: feed.count > 0 ? qsTr("Notifications · %1").arg(feed.count) : qsTr("Notifications")
}
+ Button {
+ anchors.right: clearAll.visible ? clearAll.left : parent.right
+ anchors.rightMargin: clearAll.visible ? 8 : 0
+ anchors.verticalCenter: parent.verticalCenter
+ visible: NotificationList.historyEnabled && NotificationHistory.count > 0
+ variant: "text"
+ size: "sm"
+ iconPath: Icons.history
+ text: qsTr("History")
+ onClicked: historySheet.open()
+ }
Button {
id: clearAll
anchors.right: parent.right
@@ -394,6 +405,7 @@ Item {
clock: feedClock.minutes
visible: deviceId === home.deviceId
height: visible ? implicitHeight : 0
+ onOptionsRequested: appSheet.openFor(app, appName)
}
add: Transition {
enabled: !Theme.reduceMotion
@@ -552,6 +564,113 @@ Item {
}
}
+ // What one app's notifications do on this PC.
+ Sheet {
+ id: appSheet
+ property string app
+ property string appName
+ property string rule: "show"
+ cardWidth: 420
+ function openFor(app, name) {
+ appSheet.app = app
+ appSheet.appName = name
+ appSheet.rule = NotificationList.appRule(app)
+ open()
+ }
+ Column {
+ width: parent.width
+ spacing: 16
+ Txt { width: parent.width; text: qsTr("%1 notifications").arg(appSheet.appName); role: "headline"; wrapMode: Text.WordWrap }
+ Segmented {
+ options: [
+ { value: "show", label: qsTr("Show") },
+ { value: "quiet", label: qsTr("No pop-ups") },
+ { value: "hidden", label: qsTr("Hide") }
+ ]
+ value: appSheet.rule
+ onPicked: (value) => {
+ appSheet.rule = value
+ NotificationList.setAppRule(appSheet.app, value)
+ }
+ }
+ Txt {
+ width: parent.width
+ wrapMode: Text.WordWrap
+ role: "body"
+ muted: true
+ text: appSheet.rule === "hidden"
+ ? qsTr("Nothing from %1 shows on this PC. It still shows on your phone.").arg(appSheet.appName)
+ : appSheet.rule === "quiet"
+ ? qsTr("Notifications from %1 show here in Nectarlink, without Windows pop-ups or sounds.").arg(appSheet.appName)
+ : qsTr("Notifications from %1 show here and as Windows notifications.").arg(appSheet.appName)
+ }
+ Txt {
+ width: parent.width
+ wrapMode: Text.WordWrap
+ role: "bodySmall"
+ muted: true
+ text: qsTr("You can change this for every app in Settings.")
+ }
+ Row {
+ anchors.right: parent.right
+ Button { text: qsTr("Done"); onClicked: appSheet.close() }
+ }
+ }
+ }
+
+ // Notifications from the last day that are gone from the phone.
+ Sheet {
+ id: historySheet
+ cardWidth: 560
+ Column {
+ width: parent.width
+ spacing: 12
+ Item {
+ width: parent.width
+ height: Math.max(historyTitle.height, clearHistory.height)
+ Txt { id: historyTitle; anchors.verticalCenter: parent.verticalCenter; text: qsTr("History"); role: "headline" }
+ Button {
+ id: clearHistory
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ visible: NotificationHistory.count > 0
+ variant: "text"
+ size: "sm"
+ text: qsTr("Clear history")
+ onClicked: NotificationList.clearHistory()
+ }
+ }
+ Txt {
+ width: parent.width
+ wrapMode: Text.WordWrap
+ role: "bodySmall"
+ muted: true
+ text: NotificationHistory.count > 0
+ ? qsTr("Notifications that went away on your phone, or that you dismissed, for a day.")
+ : qsTr("Nothing here yet. Notifications that go away on your phone are kept here for a day.")
+ }
+ Flickable {
+ width: parent.width
+ height: Math.min(historyColumn.height, page.height - 260)
+ contentHeight: historyColumn.height
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+ Column {
+ id: historyColumn
+ width: parent.width
+ Repeater {
+ model: NotificationHistory
+ delegate: HistoryItem { width: historyColumn.width }
+ }
+ }
+ }
+ Row {
+ anchors.right: parent.right
+ Button { text: qsTr("Done"); onClicked: historySheet.close() }
+ }
+ }
+ }
+
// A quick action. Unavailable actions are dimmed and say what unlocks them.
component ActionTile: Rectangle {
id: tile
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index 579f337..ec153c4 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -157,7 +157,7 @@ Item {
width: parent.width
iconPath: Icons.clipboard
title: qsTr("Send what you copy to your phone")
- description: qsTr("Text you copy on this PC is ready to paste on your phone. Passwords from password managers are never sent.")
+ description: qsTr("Text and images you copy on this PC are ready to paste on your phone. Passwords from password managers are never sent.")
Toggle {
label: qsTr("Send what you copy to your phone")
checked: Preferences.autoClipboard
@@ -179,6 +179,76 @@ Item {
}
}
+ // ---- Notifications ----
+ Txt { text: qsTr("Notifications"); role: "label"; muted: true }
+ Card {
+ width: parent.width
+ Column {
+ width: parent.width
+ ListRow {
+ width: parent.width
+ iconPath: Icons.history
+ title: qsTr("Keep a day of history")
+ description: qsTr("Notifications that go away on your phone stay in History on this PC for a day.")
+ Toggle {
+ label: qsTr("Keep a day of history")
+ checked: NotificationList.historyEnabled
+ onToggled: (on) => NotificationList.setHistoryEnabled(on)
+ }
+ }
+ Repeater {
+ model: { try { return JSON.parse(NotificationList.apps) } catch (e) { return [] } }
+ delegate: Column {
+ id: appRow
+ required property var modelData
+ width: parent.width
+ Divider { width: parent.width }
+ Item {
+ width: parent.width
+ height: 60
+ Item {
+ id: appIcon
+ x: 4
+ anchors.verticalCenter: parent.verticalCenter
+ width: 28; height: 28
+ Image {
+ id: appImage
+ anchors.fill: parent
+ source: appRow.modelData.icon
+ sourceSize: Qt.size(56, 56)
+ mipmap: true
+ visible: status === Image.Ready
+ }
+ Avatar { anchors.fill: parent; visible: appImage.status !== Image.Ready; name: appRow.modelData.name }
+ }
+ Txt {
+ anchors.left: appIcon.right
+ anchors.leftMargin: 14
+ anchors.right: appChoice.left
+ anchors.rightMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ role: "body"
+ text: appRow.modelData.name
+ elide: Text.ElideRight
+ }
+ Segmented {
+ id: appChoice
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ options: [
+ { value: "show", label: qsTr("Show") },
+ { value: "quiet", label: qsTr("No pop-ups") },
+ { value: "hidden", label: qsTr("Hide") }
+ ]
+ value: appRow.modelData.rule
+ onPicked: (value) => NotificationList.setAppRule(appRow.modelData.app, value)
+ }
+ }
+ }
+ }
+ }
+ }
+
// ---- Devices ----
Row {
width: parent.width
diff --git a/desktop/app/src/bridge/history.rs b/desktop/app/src/bridge/history.rs
new file mode 100644
index 0000000..0e0096a
--- /dev/null
+++ b/desktop/app/src/bridge/history.rs
@@ -0,0 +1,213 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `NotificationHistory`: notifications that went away in the last day,
+//! newest first, as a Qt list model (apps the user hid are left out).
+
+use std::pin::Pin;
+
+use cxx_qt::{CxxQtType, Threading};
+use cxx_qt_lib::{QByteArray, QHash, QHashPair_i32_QByteArray, QList, QModelIndex, QString, QVariant};
+
+use super::{Edit, diff};
+use crate::{
+ core_host, icons,
+ state::{AppRule, Changes, HistoryEntry},
+};
+
+#[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>;
+ }
+
+ unsafe extern "RustQt" {
+ #[qobject]
+ #[base = QAbstractListModel]
+ #[qml_element]
+ #[qml_singleton]
+ #[qproperty(i32, count)]
+ type NotificationHistory = super::NotificationHistoryRust;
+ }
+
+ // Inherited from QAbstractListModel.
+ unsafe extern "RustQt" {
+ #[inherit]
+ #[cxx_name = "beginInsertRows"]
+ unsafe fn begin_insert_rows(
+ self: Pin<&mut NotificationHistory>,
+ parent: &QModelIndex,
+ first: i32,
+ last: i32,
+ );
+ #[inherit]
+ #[cxx_name = "endInsertRows"]
+ unsafe fn end_insert_rows(self: Pin<&mut NotificationHistory>);
+ #[inherit]
+ #[cxx_name = "beginRemoveRows"]
+ unsafe fn begin_remove_rows(
+ self: Pin<&mut NotificationHistory>,
+ parent: &QModelIndex,
+ first: i32,
+ last: i32,
+ );
+ #[inherit]
+ #[cxx_name = "endRemoveRows"]
+ unsafe fn end_remove_rows(self: Pin<&mut NotificationHistory>);
+ #[inherit]
+ fn index(self: &NotificationHistory, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex;
+
+ #[inherit]
+ #[qsignal]
+ #[cxx_name = "dataChanged"]
+ fn data_changed(
+ self: Pin<&mut NotificationHistory>,
+ top_left: &QModelIndex,
+ bottom_right: &QModelIndex,
+ roles: &QList_i32,
+ );
+ }
+
+ unsafe extern "RustQt" {
+ #[qinvokable]
+ #[cxx_override]
+ fn data(self: &NotificationHistory, index: &QModelIndex, role: i32) -> QVariant;
+ #[qinvokable]
+ #[cxx_override]
+ #[cxx_name = "roleNames"]
+ fn role_names(self: &NotificationHistory) -> QHash_i32_QByteArray;
+ #[qinvokable]
+ #[cxx_override]
+ #[cxx_name = "rowCount"]
+ fn row_count(self: &NotificationHistory, parent: &QModelIndex) -> i32;
+ }
+
+ impl cxx_qt::Threading for NotificationHistory {}
+ impl cxx_qt::Initialize for NotificationHistory {}
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct Row {
+ entry: HistoryEntry,
+ device_name: String,
+ icon_url: String,
+}
+
+#[derive(Default)]
+pub struct NotificationHistoryRust {
+ count: i32,
+ rows: Vec<Row>,
+}
+
+/// Model roles (Qt::UserRole + n).
+const ROLES: &[&str] =
+ &["deviceId", "deviceName", "app", "appName", "title", "text", "sub", "when", "removedAt", "iconUrl"];
+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.entry.notification;
+ match role {
+ "deviceId" => text(&row.entry.device.to_string()),
+ "deviceName" => text(&row.device_name),
+ "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)),
+ "removedAt" => QVariant::from(&(row.entry.removed_at as f64)),
+ "iconUrl" => text(&row.icon_url),
+ _ => QVariant::default(),
+ }
+}
+
+impl cxx_qt::Initialize for qobject::NotificationHistory {
+ fn initialize(self: Pin<&mut Self>) {
+ super::subscribe(
+ self.qt_thread(),
+ Changes::HISTORY | Changes::APPS | Changes::DEVICES | Changes::NOTIFICATIONS,
+ Self::refresh,
+ );
+ }
+}
+
+impl qobject::NotificationHistory {
+ fn refresh(mut self: Pin<&mut Self>) {
+ let new: Vec<Row> = core_host::host().hub.read(|s| {
+ s.history
+ .iter()
+ .filter(|h| s.app_rule(&h.notification.app) != AppRule::Hidden)
+ .map(|h| Row {
+ device_name: s.name_of(&h.device).unwrap_or_default(),
+ icon_url: s
+ .app_icons
+ .get(&h.notification.app)
+ .map(|p| icons::file_url(p))
+ .unwrap_or_default(),
+ entry: h.clone(),
+ })
+ .collect()
+ });
+ let root = QModelIndex::default();
+ let key = |r: &Row| (r.entry.device, r.entry.notification.key.clone(), r.entry.removed_at);
+ for edit in diff(&self.rows, &new, key) {
+ 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
+ }
+}
diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rs
index 66d9e24..c6332bf 100644
--- a/desktop/app/src/bridge/mod.rs
+++ b/desktop/app/src/bridge/mod.rs
@@ -10,6 +10,8 @@ pub mod app;
#[allow(unsafe_code)]
pub mod devices;
#[allow(unsafe_code)]
+pub mod history;
+#[allow(unsafe_code)]
pub mod media;
#[allow(unsafe_code)]
pub mod native;
diff --git a/desktop/app/src/bridge/notifications.rs b/desktop/app/src/bridge/notifications.rs
index 9b7974a..284e8af 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, SentReply},
+ state::{AppRule, AppState, Changes, NotificationView, SentReply},
};
#[cxx_qt::bridge]
@@ -38,6 +38,11 @@ pub mod qobject {
#[qml_element]
#[qml_singleton]
#[qproperty(i32, count)]
+ /// Keep a day of history.
+ #[qproperty(bool, history_enabled, cxx_name = "historyEnabled", READ, NOTIFY)]
+ /// Apps that sent notifications, as JSON sorted by name:
+ /// [{ "app", "name", "icon", "rule": "show" | "quiet" | "hidden" }].
+ #[qproperty(QString, apps, READ, NOTIFY)]
type NotificationList = super::NotificationListRust;
}
@@ -110,6 +115,19 @@ pub mod qobject {
/// Sends a reply through its reply action.
#[qinvokable]
fn reply(self: &NotificationList, device: &QString, key: &QString, action: &QString, text: &QString);
+ /// "show", "quiet" (no pop-ups) or "hidden".
+ #[qinvokable]
+ #[cxx_name = "appRule"]
+ fn app_rule(self: &NotificationList, app: &QString) -> QString;
+ #[qinvokable]
+ #[cxx_name = "setAppRule"]
+ fn set_app_rule(self: &NotificationList, app: &QString, rule: &QString);
+ #[qinvokable]
+ #[cxx_name = "setHistoryEnabled"]
+ fn set_history_enabled_by_user(self: &NotificationList, on: bool);
+ #[qinvokable]
+ #[cxx_name = "clearHistory"]
+ fn clear_history(self: &NotificationList);
}
impl cxx_qt::Threading for NotificationList {}
@@ -130,6 +148,8 @@ struct Row {
#[derive(Default)]
pub struct NotificationListRust {
count: i32,
+ history_enabled: bool,
+ apps: QString,
rows: Vec<Row>,
}
@@ -196,21 +216,54 @@ fn role_value(row: &Row, role: &str) -> QVariant {
}
}
+fn rule_name(rule: AppRule) -> &'static str {
+ match rule {
+ AppRule::Show => "show",
+ AppRule::Quiet => "quiet",
+ AppRule::Hidden => "hidden",
+ }
+}
+
+/// The apps list for Settings (see the `apps` property).
+fn apps_json(s: &AppState) -> String {
+ let mut apps: Vec<(&String, &String)> = s.app_names.iter().collect();
+ apps.sort_by_key(|(app, name)| (name.to_lowercase(), (*app).clone()));
+ serde_json::Value::from(
+ apps.into_iter()
+ .map(|(app, name)| {
+ serde_json::json!({
+ "app": app,
+ "name": name,
+ "icon": s.app_icons.get(app).map(|p| icons::file_url(p)).unwrap_or_default(),
+ "rule": rule_name(s.app_rule(app)),
+ })
+ })
+ .collect::<Vec<_>>(),
+ )
+ .to_string()
+}
+
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);
+ super::subscribe(
+ self.qt_thread(),
+ Changes::NOTIFICATIONS | Changes::DEVICES | Changes::APPS | Changes::HISTORY,
+ Self::refresh,
+ );
}
}
impl qobject::NotificationList {
fn refresh(mut self: Pin<&mut Self>) {
- let new: Vec<Row> = core_host::host().hub.read(|s| {
- s.notifications
+ let (new, apps, history): (Vec<Row>, String, bool) = core_host::host().hub.read(|s| {
+ let rows = s
+ .notifications
.iter()
+ .filter(|view| s.app_rule(&view.notification.app) != AppRule::Hidden)
.map(|view| Row {
device_name: s.name_of(&view.device).unwrap_or_default(),
icon_url: s
@@ -225,8 +278,13 @@ impl qobject::NotificationList {
.unwrap_or_default(),
view: view.clone(),
})
- .collect()
+ .collect();
+ (rows, apps_json(s), s.history_enabled)
});
+ if String::from(&self.apps) != apps {
+ self.as_mut().set_apps(QString::from(&apps));
+ }
+ self.as_mut().set_history_enabled(history);
let root = QModelIndex::default();
for edit in diff(&self.rows, &new, key_of) {
match edit {
@@ -305,6 +363,40 @@ impl qobject::NotificationList {
);
}
+ pub fn app_rule(&self, app: &QString) -> QString {
+ let rule = core_host::host().hub.read(|s| s.app_rule(&String::from(app)));
+ QString::from(rule_name(rule))
+ }
+
+ pub fn set_app_rule(&self, app: &QString, rule: &QString) {
+ let rule = match String::from(rule).as_str() {
+ "quiet" => AppRule::Quiet,
+ "hidden" => AppRule::Hidden,
+ _ => AppRule::Show,
+ };
+ crate::notifications::set_app_rule(&String::from(app), rule);
+ }
+
+ pub fn set_history_enabled_by_user(&self, on: bool) {
+ core_host::host().hub.update(|s| s.set_history_enabled(on));
+ }
+
+ pub fn clear_history(&self) {
+ core_host::host().hub.update(AppState::clear_history);
+ }
+
+ fn set_history_enabled(mut self: Pin<&mut Self>, on: bool) {
+ if self.history_enabled != on {
+ self.as_mut().rust_mut().history_enabled = on;
+ self.history_enabled_changed();
+ }
+ }
+
+ fn set_apps(mut self: Pin<&mut Self>, apps: QString) {
+ self.as_mut().rust_mut().apps = apps;
+ self.apps_changed();
+ }
+
pub fn reply(&self, device: &QString, key: &QString, action: &QString, text: &QString) {
let text = String::from(text).trim().to_owned();
if text.is_empty() {
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 37f2fb5..7c19bd0 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -16,6 +16,7 @@ mod launch;
mod logging;
mod mark;
mod media;
+mod notification_store;
mod notifications;
mod palette;
mod qr;
@@ -208,6 +209,11 @@ fn main() -> ExitCode {
tracing::error!(error = %e, "can't start the core runtime");
return ExitCode::FAILURE;
}
+ core_host::host().hub.update(|s| {
+ notification_store::load(&data_dir, s);
+ state::Changes::APPS | state::Changes::HISTORY
+ });
+ notification_store::start(data_dir.clone());
watch_network();
start_toasts();
clipboard::start();
diff --git a/desktop/app/src/notification_store.rs b/desktop/app/src/notification_store.rs
new file mode 100644
index 0000000..39a7d24
--- /dev/null
+++ b/desktop/app/src/notification_store.rs
@@ -0,0 +1,224 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! What the app keeps about notifications between runs: the user's rules
+//! for apps (and those apps' names), whether history is kept, and the
+//! history itself. Two JSON files in the data folder, written in the
+//! background shortly after a change.
+
+use std::{
+ collections::BTreeMap,
+ fs,
+ io::Write,
+ path::{Path, PathBuf},
+ sync::atomic::{AtomicBool, Ordering},
+ time::{Duration, SystemTime},
+};
+
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ core_host,
+ state::{AppRule, AppState, Changes, HistoryEntry, unix_ms},
+};
+
+const RULES_FILE: &str = "notification-rules.json";
+const HISTORY_FILE: &str = "notification-history.json";
+/// Changes come in bursts (a phone reconnecting resends everything).
+const SAVE_DELAY: Duration = Duration::from_secs(2);
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+struct Rules {
+ /// Keep a day of history.
+ history: bool,
+ /// Per app (package name): its name, and its rule if not "show".
+ apps: BTreeMap<String, AppEntry>,
+}
+
+impl Default for Rules {
+ fn default() -> Self {
+ Rules { history: true, apps: BTreeMap::new() }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+struct AppEntry {
+ name: String,
+ rule: AppRule,
+}
+
+impl Default for AppEntry {
+ fn default() -> Self {
+ AppEntry { name: String::new(), rule: AppRule::Show }
+ }
+}
+
+fn read<T: for<'de> Deserialize<'de> + Default>(path: &Path) -> T {
+ match fs::read(path) {
+ Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
+ tracing::warn!(error = %e, file = %path.display(), "unreadable; starting over");
+ T::default()
+ }),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => T::default(),
+ Err(e) => {
+ tracing::warn!(error = %e, file = %path.display(), "can't read");
+ T::default()
+ }
+ }
+}
+
+/// Writes a whole file or nothing (a temporary file renamed over it).
+fn write(path: &Path, value: &impl Serialize) -> std::io::Result<()> {
+ let partial = path.with_extension("json.tmp");
+ let mut file = fs::File::create(&partial)?;
+ file.write_all(&serde_json::to_vec(value).map_err(std::io::Error::other)?)?;
+ file.sync_all()?;
+ drop(file);
+ fs::rename(&partial, path)
+}
+
+/// Loads what was kept into the state.
+pub fn load(dir: &Path, state: &mut AppState) {
+ let rules: Rules = read(&dir.join(RULES_FILE));
+ state.history_enabled = rules.history;
+ for (app, entry) in rules.apps {
+ if !entry.name.is_empty() {
+ state.app_names.insert(app.clone(), entry.name);
+ }
+ if entry.rule != AppRule::Show {
+ state.app_rules.insert(app, entry.rule);
+ }
+ }
+ if state.history_enabled {
+ state.history = read(&dir.join(HISTORY_FILE));
+ state.prune_history(unix_ms(SystemTime::now()));
+ }
+}
+
+fn snapshot(state: &AppState) -> (Rules, Vec<HistoryEntry>) {
+ let apps = state
+ .app_names
+ .iter()
+ .map(|(app, name)| (app.clone(), AppEntry { name: name.clone(), rule: state.app_rule(app) }))
+ .chain(
+ state
+ .app_rules
+ .iter()
+ .filter(|(app, _)| !state.app_names.contains_key(*app))
+ .map(|(app, rule)| (app.clone(), AppEntry { name: String::new(), rule: *rule })),
+ )
+ .collect();
+ (Rules { history: state.history_enabled, apps }, state.history.clone())
+}
+
+/// Saves after changes from now on, and lets history older than a day go
+/// while the app runs.
+pub fn start(dir: PathBuf) {
+ static PENDING: AtomicBool = AtomicBool::new(false);
+ let pruner = std::thread::Builder::new().name("prune-history".into()).spawn(|| {
+ loop {
+ std::thread::sleep(Duration::from_secs(600));
+ core_host::host().hub.update(|s| s.prune_history(unix_ms(SystemTime::now())));
+ }
+ });
+ if let Err(e) = pruner {
+ tracing::warn!(error = %e, "history won't be trimmed while running");
+ }
+ core_host::host().hub.subscribe(Changes::APPS | Changes::HISTORY, move || {
+ if !PENDING.swap(true, Ordering::AcqRel) {
+ let dir = dir.clone();
+ let spawned = std::thread::Builder::new().name("save-notifications".into()).spawn(move || {
+ std::thread::sleep(SAVE_DELAY);
+ PENDING.store(false, Ordering::Release);
+ let (rules, history) = core_host::host().hub.read(snapshot);
+ if let Err(e) = write(&dir.join(RULES_FILE), &rules) {
+ tracing::warn!(error = %e, "can't save notification rules");
+ }
+ let history_file = dir.join(HISTORY_FILE);
+ let saved =
+ if rules.history { write(&history_file, &history) } else { remove(&history_file) };
+ if let Err(e) = saved {
+ tracing::warn!(error = %e, "can't save notification history");
+ }
+ });
+ if spawned.is_err() {
+ PENDING.store(false, Ordering::Release);
+ }
+ }
+ true
+ });
+}
+
+fn remove(path: &Path) -> std::io::Result<()> {
+ match fs::remove_file(path) {
+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
+ _ => Ok(()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use nectarlink_core::{DeviceId, Notification};
+
+ use super::*;
+
+ fn note(key: &str, app: &str) -> Notification {
+ Notification {
+ key: key.into(),
+ app: app.into(),
+ app_name: app.to_uppercase(),
+ title: Some("Hi".into()),
+ text: None,
+ sub: None,
+ when: 1,
+ actions: Vec::new(),
+ silent: false,
+ icon: None,
+ }
+ }
+
+ #[test]
+ fn rules_and_history_survive_a_restart() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut state = AppState { history_enabled: true, ..AppState::default() };
+ state.app_names.insert("com.chat".into(), "Chat".into());
+ state.set_app_rule("com.chat", AppRule::Quiet);
+ state.set_app_rule("com.game", AppRule::Hidden);
+ let now = unix_ms(SystemTime::now());
+ state.history.push(HistoryEntry {
+ device: DeviceId([1; 32]),
+ notification: note("a", "com.chat"),
+ removed_at: now,
+ });
+ state.history.push(HistoryEntry {
+ device: DeviceId([1; 32]),
+ notification: note("old", "com.chat"),
+ removed_at: now - crate::state::HISTORY_MS - 1,
+ });
+ let (rules, history) = snapshot(&state);
+ write(&dir.path().join(RULES_FILE), &rules).unwrap();
+ write(&dir.path().join(HISTORY_FILE), &history).unwrap();
+
+ let mut loaded = AppState::default();
+ load(dir.path(), &mut loaded);
+ assert!(loaded.history_enabled);
+ assert_eq!(loaded.app_rule("com.chat"), AppRule::Quiet);
+ assert_eq!(loaded.app_rule("com.game"), AppRule::Hidden);
+ assert_eq!(loaded.app_rule("com.other"), AppRule::Show);
+ assert_eq!(loaded.app_names.get("com.chat").map(String::as_str), Some("Chat"));
+ assert_eq!(loaded.history.len(), 1, "a day old is gone");
+ assert_eq!(loaded.history[0].notification.key, "a");
+ }
+
+ #[test]
+ fn missing_or_broken_files_start_fresh() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut state = AppState::default();
+ load(dir.path(), &mut state);
+ assert!(state.history_enabled, "on by default");
+ fs::write(dir.path().join(RULES_FILE), b"{ nope").unwrap();
+ let mut state = AppState::default();
+ load(dir.path(), &mut state);
+ assert!(state.app_rules.is_empty());
+ }
+}
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index 4e7ef22..d1f6a5b 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -13,7 +13,7 @@ use nectarlink_core::{DeviceId, Error, NodeEvent, Notification};
use crate::{
core_host, icons,
- state::Changes,
+ state::{AppRule, Changes},
win::toast::{self, Toast, ToastEvent},
};
@@ -89,8 +89,13 @@ pub fn update_toasts(event: &NodeEvent) {
}
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 (device_name, icon, rule) = core_host::host()
+ .hub
+ .read(|s| (s.name_of(&device), s.app_icons.get(&n.app).cloned(), s.app_rule(&n.app)));
+ // The user chose no pop-ups (or nothing at all) for this app.
+ if rule != AppRule::Show {
+ return;
+ }
let reply = n.actions.iter().find(|a| a.reply);
let toast = Toast {
device: device.to_string(),
@@ -140,6 +145,27 @@ pub fn on_toast(event: ToastEvent) {
}
}
+/// Sets what an app's notifications do on this PC. Pop-ups it no longer
+/// gets are taken away.
+pub fn set_app_rule(app: &str, rule: AppRule) {
+ let hub = &core_host::host().hub;
+ hub.update(|s| s.set_app_rule(app, rule));
+ if rule == AppRule::Show {
+ return;
+ }
+ let shown: Vec<(DeviceId, String)> = hub.read(|s| {
+ s.notifications
+ .iter()
+ .filter(|n| n.notification.app == app)
+ .map(|n| (n.device, n.notification.key.clone()))
+ .collect()
+ });
+ for (device, key) in shown {
+ toasted(|t| t.get_mut(&device).map(|keys| keys.remove(&key)));
+ toast::remove(&device.to_string(), &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 };
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index 8ca8e60..af330a8 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -4,7 +4,7 @@
//! changed so they can refresh. Nothing here touches Qt, so it is unit-tested.
use std::{
- collections::HashMap,
+ collections::{BTreeMap, HashMap},
path::PathBuf,
sync::{Arc, Mutex, MutexGuard},
time::{Instant, SystemTime},
@@ -30,6 +30,10 @@ impl Changes {
pub const NOTIFICATIONS: Changes = Changes(1 << 6);
pub const TRANSFERS: Changes = Changes(1 << 7);
pub const MEDIA: Changes = Changes(1 << 8);
+ /// Notification history, or whether it's kept.
+ pub const HISTORY: Changes = Changes(1 << 9);
+ /// Apps that sent notifications, and the user's rules for them.
+ pub const APPS: Changes = Changes(1 << 10);
pub fn is_empty(self) -> bool {
self.0 == 0
@@ -137,6 +141,33 @@ pub struct NotificationView {
pub notification: Notification,
}
+/// What the user wants from an app's notifications on this PC.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum AppRule {
+ /// In the feed, and as Windows notifications.
+ #[default]
+ Show,
+ /// In the feed only: no pop-ups or sounds.
+ Quiet,
+ /// Not shown at all.
+ Hidden,
+}
+
+/// A notification that went away on the phone (or was dismissed here).
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct HistoryEntry {
+ pub device: DeviceId,
+ pub notification: Notification,
+ /// Unix milliseconds.
+ pub removed_at: i64,
+}
+
+/// How long history is kept, and how much of it.
+pub const HISTORY_MS: i64 = 24 * 3600 * 1000;
+pub const MAX_HISTORY: usize = 300;
+
/// A reply sent from this PC to a notification, shown under it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SentReply {
@@ -155,6 +186,10 @@ pub struct TransferView {
pub(crate) sampled: Instant,
}
+pub fn unix_ms(time: SystemTime) -> i64 {
+ time.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64)
+}
+
/// Finished transfers kept in the list.
pub const MAX_FINISHED_TRANSFERS: usize = 20;
@@ -183,6 +218,13 @@ pub struct AppState {
pub transfers: Vec<TransferView>,
/// Media players on paired devices, each device's in its order.
pub media: Vec<PlayerView>,
+ /// Apps that sent notifications (package → name), and the user's rules
+ /// for those that aren't shown normally.
+ pub app_names: BTreeMap<String, String>,
+ pub app_rules: BTreeMap<String, AppRule>,
+ /// Notifications that went away, newest first, while history is kept.
+ pub history: Vec<HistoryEntry>,
+ pub history_enabled: bool,
}
impl AppState {
@@ -303,25 +345,36 @@ impl AppState {
NodeEvent::Pairing(event) => self.apply_pairing(event),
NodeEvent::NotificationsReset { device, items } => {
let before = self.notifications.len();
+ // What's gone since the last list went away on the phone.
+ let gone: Vec<NotificationView> = self
+ .notifications
+ .iter()
+ .filter(|n| n.device == *device && !items.iter().any(|i| i.key == n.notification.key))
+ .cloned()
+ .collect();
self.notifications.retain(|n| n.device != *device);
if before == self.notifications.len() && items.is_empty() {
return Changes::NONE;
}
+ let mut changes = Changes::NOTIFICATIONS;
for n in items {
- self.insert_notification(*device, n.clone());
+ changes |= self.insert_notification(*device, n.clone());
}
- Changes::NOTIFICATIONS
+ changes | self.remember(gone)
}
NodeEvent::NotificationPosted { device, notification } => {
self.notifications
.retain(|n| !(n.device == *device && n.notification.key == notification.key));
- self.insert_notification(*device, notification.clone());
- Changes::NOTIFICATIONS
+ Changes::NOTIFICATIONS | self.insert_notification(*device, notification.clone())
}
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 }
+ let Some(at) =
+ self.notifications.iter().position(|n| n.device == *device && n.notification.key == *key)
+ else {
+ return Changes::NONE;
+ };
+ let gone = self.notifications.remove(at);
+ Changes::NOTIFICATIONS | self.remember(vec![gone])
}
// Feedback only (see crate::clipboard); nothing to keep.
NodeEvent::ClipboardReceived { .. } => Changes::NONE,
@@ -410,11 +463,75 @@ impl AppState {
}
/// Adds a notification in time order (newest first), without its icon.
- fn insert_notification(&mut self, device: DeviceId, mut notification: Notification) {
+ fn insert_notification(&mut self, device: DeviceId, mut notification: Notification) -> Changes {
notification.icon = None;
+ let mut changes = Changes::NONE;
+ if self.app_names.get(&notification.app) != Some(&notification.app_name) {
+ self.app_names.insert(notification.app.clone(), notification.app_name.clone());
+ changes |= Changes::APPS;
+ }
let at = self.notifications.partition_point(|n| n.notification.when >= notification.when);
self.notifications.insert(at, NotificationView { device, notification });
self.notifications.truncate(MAX_NOTIFICATIONS);
+ changes
+ }
+
+ /// The rule for an app's notifications.
+ pub fn app_rule(&self, app: &str) -> AppRule {
+ self.app_rules.get(app).copied().unwrap_or_default()
+ }
+
+ pub fn set_app_rule(&mut self, app: &str, rule: AppRule) -> Changes {
+ let changed = match rule {
+ AppRule::Show => self.app_rules.remove(app).is_some(),
+ rule => self.app_rules.insert(app.to_owned(), rule) != Some(rule),
+ };
+ if changed { Changes::APPS | Changes::NOTIFICATIONS | Changes::HISTORY } else { Changes::NONE }
+ }
+
+ /// Keeps notifications that went away, while history is on.
+ fn remember(&mut self, gone: Vec<NotificationView>) -> Changes {
+ if !self.history_enabled || gone.is_empty() {
+ return Changes::NONE;
+ }
+ let now = unix_ms(SystemTime::now());
+ for view in gone {
+ self.history
+ .retain(|h| !(h.device == view.device && h.notification.key == view.notification.key));
+ self.history.insert(
+ 0,
+ HistoryEntry { device: view.device, notification: view.notification, removed_at: now },
+ );
+ }
+ self.prune_history(now);
+ Changes::HISTORY
+ }
+
+ /// Drops history older than a day, and beyond the most kept.
+ pub fn prune_history(&mut self, now: i64) -> Changes {
+ let before = self.history.len();
+ self.history.retain(|h| now - h.removed_at < HISTORY_MS);
+ self.history.truncate(MAX_HISTORY);
+ if self.history.len() == before { Changes::NONE } else { Changes::HISTORY }
+ }
+
+ pub fn set_history_enabled(&mut self, on: bool) -> Changes {
+ if self.history_enabled == on {
+ return Changes::NONE;
+ }
+ self.history_enabled = on;
+ if !on {
+ self.history.clear();
+ }
+ Changes::HISTORY
+ }
+
+ pub fn clear_history(&mut self) -> Changes {
+ if self.history.is_empty() {
+ return Changes::NONE;
+ }
+ self.history.clear();
+ Changes::HISTORY
}
/// Records where an app's icon is stored.
@@ -645,7 +762,7 @@ mod tests {
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);
+ assert_eq!(s.apply(&reset), Changes::NOTIFICATIONS | Changes::APPS, "and the app is new");
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");
@@ -768,4 +885,51 @@ mod tests {
hub.update(|_| Changes::NONE);
assert_eq!(devices.load(Ordering::SeqCst), 2, "empty changes notify nobody");
}
+
+ #[test]
+ fn gone_notifications_are_kept_for_a_day() {
+ let phone = DeviceId([1; 32]);
+ let mut s = AppState { history_enabled: true, ..AppState::default() };
+ s.apply(&NodeEvent::NotificationsReset { device: phone, items: vec![note("a", 10), note("b", 20)] });
+ assert!(s.history.is_empty());
+
+ // Removed on the phone (or dismissed here).
+ let changes = s.apply(&NodeEvent::NotificationRemoved { device: phone, key: "a".into() });
+ assert!(changes.intersects(Changes::HISTORY));
+ assert_eq!(s.history.iter().map(|h| h.notification.key.as_str()).collect::<Vec<_>>(), ["a"]);
+
+ // Gone while disconnected: the next full list leaves it out.
+ s.apply(&NodeEvent::NotificationsReset { device: phone, items: vec![note("c", 30)] });
+ assert_eq!(s.history.iter().map(|h| h.notification.key.as_str()).collect::<Vec<_>>(), ["b", "a"]);
+
+ // Old entries go.
+ let later = s.history[0].removed_at + HISTORY_MS + 1;
+ assert!(s.prune_history(later).intersects(Changes::HISTORY));
+ assert!(s.history.is_empty());
+
+ // Turned off: nothing kept, and what was is cleared.
+ s.apply(&NodeEvent::NotificationRemoved { device: phone, key: "c".into() });
+ assert_eq!(s.history.len(), 1);
+ s.set_history_enabled(false);
+ assert!(s.history.is_empty());
+ s.apply(&NodeEvent::NotificationPosted { device: phone, notification: note("d", 40) });
+ s.apply(&NodeEvent::NotificationRemoved { device: phone, key: "d".into() });
+ assert!(s.history.is_empty());
+ }
+
+ #[test]
+ fn apps_and_their_rules() {
+ let phone = DeviceId([1; 32]);
+ let mut s = AppState::default();
+ let changes = s.apply(&NodeEvent::NotificationPosted { device: phone, notification: note("a", 10) });
+ assert!(changes.intersects(Changes::APPS), "a new app");
+ let app = s.notifications[0].notification.app.clone();
+ assert!(s.app_names.contains_key(&app));
+ assert_eq!(s.app_rule(&app), AppRule::Show);
+ assert!(s.set_app_rule(&app, AppRule::Hidden).intersects(Changes::NOTIFICATIONS));
+ assert_eq!(s.app_rule(&app), AppRule::Hidden);
+ assert_eq!(s.set_app_rule(&app, AppRule::Hidden), Changes::NONE);
+ s.set_app_rule(&app, AppRule::Show);
+ assert!(s.app_rules.is_empty(), "the default isn't stored");
+ }
}