diff --git a/packages/omamobile-shell/PKGBUILD b/packages/omamobile-shell/PKGBUILD index ed1f88a61..ef59cdd5d 100644 --- a/packages/omamobile-shell/PKGBUILD +++ b/packages/omamobile-shell/PKGBUILD @@ -7,7 +7,7 @@ pkgdesc="Omarchy Mobile's phone profile for the Omarchy shell: status bar, quick arch=(any) url="https://github.com/derekross/omarchy-mobile" license=(MIT GPL-3.0-or-later) # GPL: the squeekboard layout -depends=(omarchy omamobile-apps 'omamobile-omarchy>=0.1.11' 'omamobile-owl-widgets>=0.1.2' bash squeekboard bluez wf-recorder python python-dbus python-gobject +depends=(omarchy omamobile-apps 'omamobile-omarchy>=0.1.11' 'omamobile-notification-snapshot>=1' 'omamobile-owl-widgets>=0.1.2' bash squeekboard bluez wf-recorder python python-dbus python-gobject which # voice input: voxtype finds wtype and wl-copy with which pipewire-audio pipewire-pulse pipewire-alsa wireplumber inotify-tools qt6-declarative diff --git a/packages/omamobile-shell/plugins/README.md b/packages/omamobile-shell/plugins/README.md index c3105fb4e..48f15960b 100644 --- a/packages/omamobile-shell/plugins/README.md +++ b/packages/omamobile-shell/plugins/README.md @@ -79,7 +79,12 @@ service has no count to read through the host's proxy, so the bar watches the directory (`Qt.labs.folderlistmodel`, a file system watcher, not a poll). The shade records its mark in `~/.local/state/omamobile/notifications-seen` and calls `notificationsSeen` below. A toast that was acted on also lands in -history, so it counts until the shade has been opened. +history, so it counts until the shade has been opened. Omarchy 4.5 keeps the +history in one file instead, `~/.local/state/omarchy/notifications/history.json` +(a JSON array, each row's `ts` in seconds); while that file exists, the bar +counts its rows newer than the mark (`StatusModel.unreadStored`), watching +the file and re-reading it every 30 s, since the service replaces it with +rename(2). **Mobile network and calls:** the cellular icon and the call chip come from `omamobile-cell-watch` and `omamobile-call-watch --observe` (see @@ -169,7 +174,10 @@ history as toasts (`showHistory`) but returns none of it, so the shade reads the files the service keeps, `~/.local/state/omarchy/notifications/*.json` and `history/*.json` (format and rules in `NotificationsModel.js`, tests in `test/notifications-model.js`), when the sheet opens and every 3 s while it -is open. A tap on a row puts the sheet away and runs what a tap on the toast +is open. On Omarchy 4.5, which keeps them in `live.json` and `history.json` +in that directory instead (100 rows over 24 hours, `Store.js`), the shade +reads those two files whenever `history.json` exists, whatever the version +says; `test/notifications-store.sh` runs its commands on both layouts. A tap on a row puts the sheet away and runs what a tap on the toast runs: Omarchy's own action for its toasts (the `omarchy-exec-argv` hint the file keeps), otherwise `omarchy-hyprland-focus-app `. Other senders' live actions die with the toast, so they can't be run from history. @@ -177,6 +185,9 @@ live actions die with the toast, so they can't be run from history. **Clear all** (44 px, two taps: the first turns it into "Clear all?" for 4 s) calls the notification service on this shell instance, `dismissAll` (the toasts on screen move into history) and then `clear` (history is emptied). +Omarchy 4.5 has no `clear`: there, after `dismissAll`, the shade calls +`forget ` for every notification it read (patch 0019 for 4.5, in +omamobile-omarchy's 4.5 series; without it the rows come back). The card takes the room left under the sheet and scrolls past that; it hides in edit mode, or when the sheet leaves no room for it. diff --git a/packages/omamobile-shell/plugins/omamobile.bar/Bar.qml b/packages/omamobile-shell/plugins/omamobile.bar/Bar.qml index 96f73fdd2..13d0225f7 100644 --- a/packages/omamobile-shell/plugins/omamobile.bar/Bar.qml +++ b/packages/omamobile-shell/plugins/omamobile.bar/Bar.qml @@ -127,6 +127,12 @@ Item { // FolderListModel's file system watcher rather than polled. The shade // writes its mark to notifications-seen and tells this bar by IPC. readonly property string notificationsHistory: Quickshell.env("HOME") + "/.local/state/omarchy/notifications/history" + // Omarchy 4.5 keeps the history in one file in the directory above, + // history.json (StatusModel.unreadStored); while it exists, it is what + // the count reads. The service replaces it with rename(2), which a watch + // can miss, so it is also re-read now and then. + readonly property string notificationsStore: Quickshell.env("HOME") + "/.local/state/omarchy/notifications/history.json" + property bool storeLayout: false property double seenStamp: 0 property int unread: 0 @@ -151,7 +157,23 @@ Item { function onDataChanged() { Qt.callLater(root.countUnread) } } + FileView { + id: historyStore + path: root.notificationsStore + printErrors: false + watchChanges: true + onFileChanged: reload() + onLoaded: { root.storeLayout = true; Qt.callLater(root.countUnread) } + onLoadFailed: { root.storeLayout = false; Qt.callLater(root.countUnread) } + } + + Timer { interval: 30000; repeat: true; running: root.storeLayout; onTriggered: historyStore.reload() } + function countUnread() { + if (storeLayout) { + unread = StatusModel.unreadStored(historyStore.text(), seenStamp) + return + } var names = [] for (var i = 0; i < historyFiles.count; i++) names.push(historyFiles.get(i, "fileName")) unread = StatusModel.unreadCount(names, seenStamp) @@ -160,6 +182,7 @@ Item { // The notification service makes the directory when it starts; if the // bar got there first, watch it again once it can exist. function rewatchHistory() { + historyStore.reload() if (historyFiles.count > 0) return historyFiles.folder = "" historyFiles.folder = "file://" + root.notificationsHistory diff --git a/packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js b/packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js index f5b7931e3..05f08a757 100644 --- a/packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js +++ b/packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js @@ -120,6 +120,22 @@ function unreadCount(names, seen) { return count } +// Omarchy 4.5 keeps its history in one file, history.json: a JSON array of +// rows, each with `ts`, when it arrived, in seconds. The shade's mark is in +// milliseconds, rounded as its NotificationsModel.storeEntry rounds them. +function unreadStored(text, seen) { + var rows = null + try { rows = JSON.parse(String(text === undefined || text === null ? "" : text)) } catch (error) { return 0 } + if (!Array.isArray(rows)) return 0 + var since = parseStamp(seen) + var count = 0 + for (var i = 0; i < rows.length; i++) { + var ts = rows[i] && typeof rows[i] === "object" ? Number(rows[i].ts) : 0 + if (isFinite(ts) && ts > 0 && Math.round(ts * 1000) > since) count++ + } + return count +} + function batteryIcon(percent, charging, full) { if (percent < 0) return "" if (full) return "󰂅" @@ -134,6 +150,6 @@ if (typeof module !== "undefined") { findDevice: findDevice, connectedNetwork: connectedNetwork, wifiIcon: wifiIcon, networkIcon: networkIcon, cellularIcon: cellularIcon, cellGlyph: cellGlyph, cellText: cellText, parseCell: parseCell, callChip: callChip, elapsed: elapsed, batteryIcon: batteryIcon, - stampOf: stampOf, parseStamp: parseStamp, unreadCount: unreadCount + stampOf: stampOf, parseStamp: parseStamp, unreadCount: unreadCount, unreadStored: unreadStored } } diff --git a/packages/omamobile-shell/plugins/omamobile.quicksettings/NotificationRow.qml b/packages/omamobile-shell/plugins/omamobile.quicksettings/NotificationRow.qml index 27aed3a8d..e654f8f1b 100644 --- a/packages/omamobile-shell/plugins/omamobile.quicksettings/NotificationRow.qml +++ b/packages/omamobile-shell/plugins/omamobile.quicksettings/NotificationRow.qml @@ -22,6 +22,9 @@ Item { property var entry: ({}) // Off while the list is scrolling. property bool swipeEnabled: true + // Clear all may cancel a swipe before its request is accepted. + property bool clearing: false + property bool forgetAccepted: false readonly property bool actionable: !!NotificationsModel.tapArgv(entry) readonly property color foreground: host ? host.foreground : Commons.Color.popups.text @@ -32,15 +35,34 @@ Item { property bool dismissing: false // 1 in the list; down to 0 as the gap closes after a swipe away. property real fold: 1 - readonly property bool swiping: swipeHandler.active || swipeAnimation.running || dismissing + readonly property bool swiping: swipeHandler.active || swipeAnimation.running || restoreAnimation.running || dismissing readonly property real naturalHeight: Math.max(44, rowText.implicitHeight + Style.spacing.md * 2) height: naturalHeight * fold visible: fold > 0 clip: fold < 1 + function restoreSwipe() { + swipeAnimation.stop() + foldAnimation.stop() + fold = 1 + dismissing = false + forgetAccepted = false + restoreAnimation.restart() + } + + onClearingChanged: if (clearing && dismissing && !forgetAccepted) restoreSwipe() + + Connections { + target: row.host + ignoreUnknownSignals: true + function onNotificationForgetFailed(key) { + if (row.forgetAccepted && row.entry.key === key) row.restoreSwipe() + } + } + function finishSwipe() { - var way = NotificationsModel.swipeOutcome(swipeOffset, swipeVelocity, width, Style.space(900)) + var way = !clearing ? NotificationsModel.swipeOutcome(swipeOffset, swipeVelocity, width, Style.space(900)) : 0 swipeAnimation.dismiss = way !== 0 swipeAnimation.to = way * (width + Style.space(24)) if (way !== 0) dismissing = true @@ -146,6 +168,7 @@ Item { enabled: row.swipeEnabled && !row.dismissing onActiveChanged: { if (active) { + restoreAnimation.stop() swipeAnimation.stop() row.swipeVelocity = 0 } else { @@ -171,10 +194,22 @@ Item { easing.type: swipeAnimation.dismiss ? Easing.InQuad : Easing.OutBack } ScriptAction { - script: if (swipeAnimation.dismiss) foldAnimation.start() + script: if (swipeAnimation.dismiss) { + if (!row.clearing) foldAnimation.start() + else row.restoreSwipe() + } } } + NumberAnimation { + id: restoreAnimation + target: row + property: "swipeOffset" + to: 0 + duration: 200 + easing.type: Easing.OutBack + } + // The gap closes, then the host takes the entry out of the list (which // replaces this row) and forgets the notification. SequentialAnimation { @@ -187,7 +222,10 @@ Item { easing.type: Easing.OutCubic } ScriptAction { - script: if (row.host) row.host.forgetNotification(row.entry) + script: { + row.forgetAccepted = !!row.host && row.host.forgetNotification(row.entry) + if (!row.forgetAccepted) row.restoreSwipe() + } } } } diff --git a/packages/omamobile-shell/plugins/omamobile.quicksettings/NotificationsModel.js b/packages/omamobile-shell/plugins/omamobile.quicksettings/NotificationsModel.js index 3eac060e0..f06d2d856 100644 --- a/packages/omamobile-shell/plugins/omamobile.quicksettings/NotificationsModel.js +++ b/packages/omamobile-shell/plugins/omamobile.quicksettings/NotificationsModel.js @@ -13,6 +13,14 @@ // named -.json, the timestamp in milliseconds since the epoch. // One notification is taken away by that name through the service's forget // call (omamobile-omarchy patch 0019), never by deleting the file here. +// +// Omarchy 4.5 keeps the same notifications in two files instead (its +// shell/plugins/notifications/Store.js): live.json, the toasts on screen, +// and history.json, the closed ones, newest first. Each is one line, a JSON +// array of rows named by a `key` ("n" and base-36 digits), with `ts`, when +// the notification arrived, in seconds. Its forget call (patch 0019 for +// 4.5) takes that key. parse() reads either layout: a line holding an array +// is 4.5's, a line holding an object is one 4.0 file. var LIMIT = 10 @@ -69,51 +77,81 @@ function entry(value) { } } +// One row of Omarchy 4.5's live.json or history.json, in the shape entry() +// gives a 4.0 file: the key is the row's own, and so is the name forget +// takes (`file`); `ts` turns into milliseconds. Null for anything that +// isn't a row with a key 4.5 itself would accept (Store.js KEY). +function storeEntry(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) return null + var key = str(value.key) + if (!/^[A-Za-z0-9_-]{1,120}$/.test(key)) return null + var ts = Number(value.ts) + var timestamp = isFinite(ts) && ts > 0 ? Math.round(ts * 1000) : 0 + return { + key: key, + file: key, + app: str(value.app), + summary: str(value.summary).trim(), + body: plainBody(value.body), + glyph: str(value.glyph), + execArgv: str(value.execArgv), + urgency: typeof value.urgency === "number" ? value.urgency : 1, + timestamp: timestamp + } +} + // The concatenation of every history and on-screen file (`awk 1` over both -// directories), newest first, each notification once (a toast moving into -// history can be read in both places), at most `limit`. Torn lines from a -// crash mid-write are skipped, as Omarchy skips them. +// directories on 4.0, live.json and history.json on 4.5), newest first, +// each notification once (a toast moving into history can be read in both +// places), at most `limit`. Torn lines from a crash mid-write are skipped, +// as Omarchy skips them. function parse(raw, limit) { var max = typeof limit === "number" ? Math.max(0, limit) : LIMIT var lines = str(raw).split("\n") - var seen = {} + var seen = Object.create(null) var out = [] for (var i = 0; i < lines.length; i++) { var line = lines[i].trim() if (!line) continue var value = null try { value = JSON.parse(line) } catch (error) { continue } - if (!value || typeof value !== "object" || Array.isArray(value)) continue - var e = entry(value) - if (!e.summary && !e.body) continue - if (seen[e.key]) continue - seen[e.key] = true - out.push(e) + var rows + if (Array.isArray(value)) rows = value.map(storeEntry) + else if (value && typeof value === "object") rows = [entry(value)] + else continue + for (var j = 0; j < rows.length; j++) { + var e = rows[j] + if (!e || (!e.summary && !e.body)) continue + if (seen[e.key]) continue + seen[e.key] = true + out.push(e) + } } out.sort(function(a, b) { return b.timestamp - a.timestamp }) return out.slice(0, max) } // What the shade shows: parse(), less the notifications swiped away. -// `hidden` maps an entry's key to when it was swiped (ms). The service +// `hidden` maps an acknowledged logical key to its reply time (ms). The service // deletes its file a moment later, so until a read no longer finds the // file, the row stays out; a mark older than graceMs (a forget that never // happened, say on an Omarchy without the forget call) lapses, and the row // comes back rather than staying hidden for a notification that is still -// there. Returns the rows and the marks still needed. +// there. Returns the rows, the marks still needed and the forget name of +// every notification read, shown or not (retained for format compatibility). function shown(raw, hidden, now, graceMs) { var marks = hidden || {} var grace = typeof graceMs === "number" ? graceMs : 15000 var all = parse(raw, Infinity) - var present = {} + var present = Object.create(null) for (var i = 0; i < all.length; i++) present[all[i].key] = true var kept = {} for (var key in marks) { - if (!marks.hasOwnProperty(key) || !present[key]) continue - if (Number(now) - Number(marks[key]) <= grace) kept[key] = marks[key] + if (!Object.prototype.hasOwnProperty.call(marks, key) || !present[key]) continue + if (Number(now) - Number(marks[key]) <= grace) Object.defineProperty(kept, key, { value: marks[key], enumerable: true, writable: true, configurable: true }) } - var out = all.filter(function(e) { return !kept.hasOwnProperty(e.key) }) - return { entries: out.slice(0, LIMIT), hidden: kept } + var out = all.filter(function(e) { return !Object.prototype.hasOwnProperty.call(kept, e.key) }) + return { entries: out.slice(0, LIMIT), hidden: kept, files: all.map(function(e) { return e.file }) } } function without(entries, key) { @@ -168,12 +206,38 @@ function title(count) { return count > 0 ? "Notifications · " + count : "Notifications" } +// Hide only logical keys explicitly acknowledged by the daemon. +function clearResult(raw, code) { + if (code !== 0 || typeof raw !== "string" || raw.length > 65536) return { ok: false, keys: [] } + var value + try { value = JSON.parse(raw) } catch (error) { return { ok: false, keys: [] } } + if (!value || value.version !== 1) return { ok: false, keys: [] } + if (value.result === "legacy") return { ok: true, legacy: true, keys: [] } + if (value.result !== "ok" || !Array.isArray(value.keys) || value.keys.length > 300) return { ok: false, keys: [] } + var seen = Object.create(null), keys = [] + for (var i = 0; i < value.keys.length; i++) { + var key = value.keys[i] + if (typeof key !== "string" || !/^[A-Za-z0-9_-]{1,120}$/.test(key)) return { ok: false, keys: [] } + if (!seen[key]) { seen[key] = true; keys.push(key) } + } + return { ok: true, keys: keys } +} +function acknowledge(entries, hidden, keys, now) { + var marks = Object.create(null) + Object.keys(hidden || {}).forEach(function(key) { marks[key] = hidden[key] }) + keys.forEach(function(key) { marks[key] = now }) + return { hidden: marks, entries: (entries || []).filter(function(entry) { return keys.indexOf(entry.key) < 0 }) } +} + if (typeof module !== "undefined") { module.exports = { LIMIT: LIMIT, + clearResult: clearResult, + acknowledge: acknowledge, plainBody: plainBody, execArgv: execArgv, entry: entry, + storeEntry: storeEntry, parse: parse, shown: shown, without: without, diff --git a/packages/omamobile-shell/plugins/omamobile.quicksettings/QuickSettings.qml b/packages/omamobile-shell/plugins/omamobile.quicksettings/QuickSettings.qml index 23c455ebd..995df1248 100644 --- a/packages/omamobile-shell/plugins/omamobile.quicksettings/QuickSettings.qml +++ b/packages/omamobile-shell/plugins/omamobile.quicksettings/QuickSettings.qml @@ -797,11 +797,17 @@ Item { // Clear all goes through the service's own IPC, on this shell instance like // the DND tile: dismissAll moves the toasts on screen into history, then // clear empties history (both run in order on the service's file queue). + // Omarchy 4.5 keeps them in live.json and history.json in the same + // directory instead, and has no clear: where history.json exists, the + // shade reads those two files. Keyed Clear all uses one daemon-owned + // snapshot and hides only the keys acknowledged by its versioned reply. readonly property string notificationsDir: Quickshell.env("HOME") + "/.local/state/omarchy/notifications" // Where the bar's unread count starts from: the newest notification the // shade has shown (omamobile.bar reads it at start and hears it by IPC). readonly property string stateDir: Quickshell.env("HOME") + "/.local/state/omamobile" property var notifications: [] + // The forget name of every notification the last read found. + property var notificationFiles: [] property double nowMs: Date.now() property double seenStamp: 0 property double seenWritten: 0 @@ -816,39 +822,61 @@ Item { // closes without moving into history, and the history entry is deleted, // on the service's file queue. Deleting the file from here could race an // archive the service still has queued and come back. The row leaves the - // list at once; its key stays in hiddenNotifications until a read no - // longer finds the file (NotificationsModel.shown). The bar's unread count + // list only after a successful reply; its key stays in hiddenNotifications + // until a read no longer finds it (NotificationsModel.shown). The unread count // follows on its own: it counts the history files newer than the mark, // and a forget only takes one away. property var hiddenNotifications: ({}) property var forgetQueue: [] + property var pendingForget: null + property var pendingClearKeys: [] + property string notificationDeleteError: "" + + function acknowledgeNotifications(keys) { + var state = NotificationsModel.acknowledge(notifications, hiddenNotifications, keys, Date.now()) + hiddenNotifications = state.hidden + // A row may have requested deletion from its own delegate callback. + Qt.callLater(function() { + root.notifications = root.notifications.filter(function(entry) { return keys.indexOf(entry.key) < 0 }) + }) + } + + signal notificationForgetFailed(string key) function forgetNotification(entry) { if (!entry || !entry.key || !entry.file) return false - var marks = Object.assign({}, hiddenNotifications) - marks[entry.key] = Date.now() - hiddenNotifications = marks - forgetQueue = forgetQueue.concat([entry.file]) - // Later, not now: the row asking is a delegate of this list. - Qt.callLater(function() { - root.notifications = NotificationsModel.without(root.notifications, entry.key) - root.runForget() - }) + if (clearProc.running) { + notificationDeleteError = "Wait for Clear all to finish, then try again." + return false + } + if (pendingForget && pendingForget.key === entry.key) return true + for (var i = 0; i < forgetQueue.length; i++) if (forgetQueue[i].key === entry.key) return true + forgetQueue = forgetQueue.concat([{ key: entry.key, file: entry.file }]) + runForget() return true } function runForget() { if (forgetProc.running || forgetQueue.length === 0) return - forgetProc.command = ["sh", "-c", - "dir=$1; shift; for name; do qs ipc -p \"$dir\" call notifications forget \"$name\"; done; exit 0", - "sh", Quickshell.shellDir].concat(forgetQueue) - forgetQueue = [] + pendingForget = forgetQueue[0] + forgetQueue = forgetQueue.slice(1) + forgetProc.command = ["qs", "ipc", "-p", Quickshell.shellDir, + "call", "notifications", "forget", pendingForget.file] forgetProc.running = true } Process { id: forgetProc - onExited: { + stdout: StdioCollector { id: forgetResult; waitForEnd: true } + onExited: function(code) { + if (code === 0 && String(forgetResult.text || "").trim() === "ok" && root.pendingForget) { + root.acknowledgeNotifications([root.pendingForget.key]) + root.notificationDeleteError = "" + } else { + root.notificationDeleteError = "Notification could not be removed. Try again or update Omarchy Mobile." + if (root.pendingForget) root.notificationForgetFailed(root.pendingForget.key) + } + root.pendingForget = null root.runForget() notificationsLater.restart() } @@ -856,13 +884,16 @@ Item { Process { id: notificationsRead - command: ["sh", "-c", "for f in \"$1\"/*.json \"$1\"/history/*.json; do [ -f \"$f\" ] && awk 1 \"$f\"; done; exit 0", + command: ["sh", "-c", + "if [ -e \"$1/history.json\" ]; then for f in \"$1/live.json\" \"$1/history.json\"; do [ -f \"$f\" ] && awk 1 \"$f\"; done; " + + "else for f in \"$1\"/*.json \"$1\"/history/*.json; do [ -f \"$f\" ] && awk 1 \"$f\"; done; fi; exit 0", "sh", root.notificationsDir] stdout: StdioCollector { waitForEnd: true onStreamFinished: { var view = NotificationsModel.shown(text, root.hiddenNotifications, Date.now()) root.hiddenNotifications = view.hidden + root.notificationFiles = view.files // Only a change replaces the rows: a new list rebuilds every row, and // one being swiped would be dropped from under the finger. if (JSON.stringify(view.entries) !== JSON.stringify(root.notifications)) @@ -920,18 +951,28 @@ Item { } function clearAllNotifications() { - notifications = [] - if (clearProc.running) return + if (clearProc.running || forgetProc.running || forgetQueue.length > 0) return + pendingClearKeys = notifications.map(function(entry) { return entry.key }) clearProc.command = ["sh", "-c", - "qs ipc -p \"$1\" call notifications dismissAll; qs ipc -p \"$1\" call notifications clear", - "sh", Quickshell.shellDir] + "if [ -e \"$2/live.json\" ] || [ -e \"$2/history.json\" ]; then exec qs ipc -p \"$1\" call notifications forgetAll; " + + "else qs ipc -p \"$1\" call notifications dismissAll >/dev/null && qs ipc -p \"$1\" call notifications clear >/dev/null " + + "&& printf '%s\\n' '{\"version\":1,\"result\":\"legacy\"}'; fi", + "sh", Quickshell.shellDir, root.notificationsDir] clearProc.running = true } Process { id: clearProc - // The service's file queue runs after the IPC answers; read once it has. - onExited: notificationsLater.restart() + stdout: StdioCollector { id: clearResult; waitForEnd: true } + onExited: function(code) { + var result = NotificationsModel.clearResult(clearResult.text, code) + if (result.ok) { + root.acknowledgeNotifications(result.legacy ? root.pendingClearKeys : result.keys) + root.notificationDeleteError = "" + } else root.notificationDeleteError = "Notifications could not be cleared. Try again or update Omarchy Mobile." + root.pendingClearKeys = [] + notificationsLater.restart() + } } Timer { @@ -1995,11 +2036,22 @@ Item { label: root.confirmClear ? "Clear all?" : "Clear all" danger: root.confirmClear foreground: root.foreground - enabled: root.notifications.length > 0 + enabled: root.notifications.length > 0 && !clearProc.running && !forgetProc.running && root.forgetQueue.length === 0 onTapped: root.requestClearNotifications() } } + Text { + visible: root.notificationDeleteError !== "" + width: parent.width + text: root.notificationDeleteError + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.foreground + font.family: Style.font.family + font.pixelSize: Style.font.body + } + Text { id: shadeEmpty visible: root.notifications.length === 0 @@ -2032,7 +2084,8 @@ Item { host: root entry: modelData width: shadeRows.width - swipeEnabled: !shadeList.moving + swipeEnabled: !shadeList.moving && !clearProc.running + clearing: clearProc.running } } } diff --git a/packages/omamobile-shell/test/all b/packages/omamobile-shell/test/all index 4a242065b..c09690339 100755 --- a/packages/omamobile-shell/test/all +++ b/packages/omamobile-shell/test/all @@ -252,10 +252,15 @@ pass "touch navigation: back, home pill, drawer pull, undo, fields in view" # at its root, the shade reads the directories Omarchy's service writes, and # the bar hears the shade's mark on the IPC target it serves. qs=plugins/omamobile.quicksettings/QuickSettings.qml -grep -cF '"qs ipc -p \"$1\" call notifications dismissAll; qs ipc -p \"$1\" call notifications clear"' "$qs" >/dev/null || fail "Clear all dismisses the toasts, then clears the history" +grep -cF 'call notifications forgetAll' "$qs" >/dev/null || fail "keyed Clear all uses the daemon snapshot" +grep -cF '"call", "notifications", "forget", pendingForget.file' "$qs" >/dev/null || fail "single deletion uses fixed daemon argv" grep -cF 'Quickshell.execDetached(["omarchy-menu", "summon", "root"])' "$qs" >/dev/null || fail "the gear opens Omarchy's root menu" grep -cF '"/.local/state/omarchy/notifications"' "$qs" >/dev/null || fail "the shade reads Omarchy's notification files" grep -cF '"/.local/state/omarchy/notifications/history"' plugins/omamobile.bar/Bar.qml >/dev/null || fail "the bar counts Omarchy's notification history" +grep -cF '"/.local/state/omarchy/notifications/history.json"' plugins/omamobile.bar/Bar.qml >/dev/null || fail "the bar counts Omarchy 4.5's history.json" +# Omarchy 4.0's files and 4.5's live.json and history.json, chosen by what +# exists: test/notifications-store.sh runs the shade's own commands on both. +bash test/notifications-store.sh >/dev/null || { bash test/notifications-store.sh; fail "the shade reads and clears both notification layouts"; } grep -cF 'call omamobile.bar notificationsSeen' "$qs" >/dev/null || fail "the shade tells the bar what it has shown" grep -cF 'function notificationsSeen(stamp: string): string' plugins/omamobile.bar/Bar.qml >/dev/null || fail "the bar serves notificationsSeen" grep -cF '"/.local/state/omamobile/notifications-seen"' plugins/omamobile.bar/Bar.qml >/dev/null || fail "the bar reads the shade's mark at start" @@ -266,7 +271,6 @@ grep -cF '"omarchy-shell", "shell", "summon", "omarchy.clipboard"' "$qs" >/dev/n # list scrolls, and its tap is a DragThreshold TapHandler (no MouseArea, # which would take the press from the swipe). test/shade-touch drives it. row=plugins/omamobile.quicksettings/NotificationRow.qml -grep -cF 'call notifications forget \"$name\"' "$qs" >/dev/null || fail "a swiped row is forgotten through the service" grep -cF 'delegate: NotificationRow {' "$qs" >/dev/null && grep -cF 'swipeEnabled: !shadeList.moving' "$qs" >/dev/null \ || fail "the shade's rows are NotificationRow, not swiping while the list scrolls" grep -cE 'rm +(-f +)?.*notifications' "$qs" "$row" >/dev/null && fail "the shade deletes no notification files itself" @@ -327,6 +331,7 @@ if command -v node >/dev/null; then node test/sensor-model.js || fail "fingerprint sensor model" node test/tiles-model.js || fail "quick-settings tile layout" node test/notifications-model.js >/dev/null || { node test/notifications-model.js; fail "notification shade model"; } + node test/notification-delete.js || fail "acknowledged notification deletion" node test/media-model.js >/dev/null || { node test/media-model.js; fail "the shade's media card model"; } node test/home-model.js || fail "home screen model" node test/back-model.js || fail "back gesture model" diff --git a/packages/omamobile-shell/test/notification-delete.js b/packages/omamobile-shell/test/notification-delete.js new file mode 100644 index 000000000..c14147ef4 --- /dev/null +++ b/packages/omamobile-shell/test/notification-delete.js @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: MIT +const fs = require('fs'), path = require('path'), vm = require('vm'), assert = require('assert'), + os = require('os'), cp = require('child_process'); +const root = __dirname, + source = fs.readFileSync(path.join(root, '../plugins/omamobile.quicksettings/QuickSettings.qml'), 'utf8'), + M = require(process.argv[2] ? path.resolve(process.argv[2]) + : '../plugins/omamobile.quicksettings/NotificationsModel.js'); +function block(s, start) { + const begin = s.indexOf('{', start); + let depth = 1, end = begin + 1; + while (depth) { + depth += (s[end] === '{') - (s[end] === '}'); + end++ + } + return s.slice(begin, end) +} +function fn(name) { + const start = source.indexOf(' function ' + name + '('); + assert(start >= 0); + return source.slice(start, source.indexOf('{', start)) + block(source, start) +} +function handler(id) { + let start = source.indexOf('id: ' + id + '\n'); + start = source.indexOf('onExited: function(code)', start); + return '(function(code) ' + block(source, start) + ')' +} +let n = 0; +function test(name, cb) { + cb(); + n++; + console.log('PASS', name) +} +function context() { + let later = []; + const c = { + NotificationsModel : M, + Date, + JSON, + Object, + Quickshell : {shellDir : 'fixture-shell'}, + notifications : [ {key : 'old', file : 'old'}, {key : 'new', file : 'new'} ], + hiddenNotifications : {}, + forgetQueue : [], + pendingForget : null, + pendingClearKeys : [], + notificationDeleteError : '', + failedKeys : [], + notificationForgetFailed(key) { this.failedKeys.push(key) }, + forgetProc : {running : false}, + clearProc : {running : false}, + forgetResult : {text : ''}, + clearResult : {text : ''}, + notificationsDir : 'fixture', + notificationsLater : {restart() {}}, + Qt : {callLater : fn => later.push(fn)} + }; + c.root = c; + vm.createContext(c); + vm.runInContext( + [ 'acknowledgeNotifications', 'forgetNotification', 'runForget', 'clearAllNotifications' ] + .map(fn) + .join('\n'), + c); + c.forgetDone = vm.runInContext(handler('forgetProc'), c); + c.clearDone = vm.runInContext(handler('clearProc'), c); + c.settle = () => { + while (later.length) + later.shift()() + }; + return c +} +test('single delete does not hide until exact successful ACK', () => { + const c = context(); + assert(c.forgetNotification(c.notifications[0])); + assert.equal(c.notifications.length, 2); + assert.deepEqual(Object.keys(c.hiddenNotifications), []); + assert.deepEqual( + [...c.forgetProc.command ], + [ 'qs', 'ipc', '-p', 'fixture-shell', 'call', 'notifications', 'forget', 'old' ]); + c.forgetProc.running = false; + c.forgetResult.text = 'busy'; + c.forgetDone(0); + c.settle(); + assert.equal(c.notifications.length, 2); + assert(c.notificationDeleteError); +}); +test('single successful ACK suppresses only captured key', () => { + const c = context(); + c.forgetNotification(c.notifications[0]); + c.forgetProc.running = false; + c.forgetResult.text = 'ok\n'; + c.forgetDone(0); + c.settle(); + assert.deepEqual(c.notifications.map(x => x.key), [ 'new' ]); + assert.deepEqual(Object.keys(c.hiddenNotifications), [ 'old' ]); +}); +test('failed malformed old-version busy replies never clear visible rows', () => { + for (const text + of ['', 'ok', '{"result":"ok","keys":["old"]}', + '{"version":true,"result":"ok","keys":["old"]}', + '{"version":1,"result":"busy","keys":[]}', + '{"version":1,"result":"ok","keys":["../bad"]}', + JSON.stringify({version : 1, result : 'ok', keys : Array(301).fill('old')})]) { + const c = context(); + c.clearResult.text = text; + c.clearDone(0); + c.settle(); + assert.equal(c.notifications.length, 2); + assert.equal(Object.keys(c.hiddenNotifications).length, 0); + assert(c.notificationDeleteError) + } +}); +test('nonzero IPC exit cannot acknowledge valid-looking data', () => { + const c = context(); + c.clearResult.text = '{"version":1,"result":"ok","keys":["old"]}'; + c.clearDone(1); + c.settle(); + assert.equal(c.notifications.length, 2); + assert.equal(Object.keys(c.hiddenNotifications).length, 0); + assert(c.notificationDeleteError); +}); +test('bulk acknowledgment retains arrivals and in-flight stale reads', () => { + const c = context(); + c.clearResult.text = '{"version":1,"result":"ok","keys":["old"]}'; + c.clearDone(0); + c.settle(); + assert.deepEqual(c.notifications.map(x => x.key), [ 'new' ]); + const raw = JSON.stringify( + [ {key : 'old', ts : 1, summary : 'Old'}, {key : 'new', ts : 2, summary : 'New'} ]); + assert.deepEqual(M.shown(raw, c.hiddenNotifications, Date.now()).entries.map(x => x.key), + [ 'new' ]); + assert.deepEqual(M.shown(JSON.stringify([ {key : 'new', ts : 2, summary : 'New'} ]), + c.hiddenNotifications, Date.now()) + .hidden, + {}) +}); +test('arrival between ACK and deferred delegate removal survives', () => { + const c = context(); + c.clearResult.text = '{"version":1,"result":"ok","keys":["old"]}'; + c.clearDone(0); + c.notifications.push({key: 'later', file: 'later'}); + c.settle(); + assert.deepEqual(c.notifications.map(entry => entry.key), ['new', 'later']); +}); +test('dictionary-like keys deduplicate and retain safe own tombstones', () => { + const result = M.clearResult( + JSON.stringify( + {version : 1, result : 'ok', keys : [ '__proto__', 'hasOwnProperty', '__proto__' ]}), + 0); + assert.deepEqual(result.keys, [ '__proto__', 'hasOwnProperty' ]); + const state = M.acknowledge([ {key : '__proto__'}, {key : 'new'} ], {}, result.keys, 10); + assert.equal(Object.getPrototypeOf(state.hidden), null); + assert.deepEqual(state.entries, [ {key : 'new'} ]); + const raw = JSON.stringify([ + {key : '__proto__', ts : 1, summary : 'Proto'}, + {key : 'hasOwnProperty', ts : 2, summary : 'Own'}, {key : 'new', ts : 3, summary : 'New'} + ]); + assert.deepEqual(M.shown(raw, state.hidden, 11).entries.map(x => x.key), [ 'new' ]) +}); +test('legacy success hides only the rows captured before the call', () => { + const c = context(); + c.clearAllNotifications(); + assert.deepEqual([...c.pendingClearKeys], ['old', 'new']); + c.notifications.push({key: 'arrival', file: 'arrival'}); + assert.equal(c.notifications.length, 3, 'no optimistic removal before the reply'); + c.clearResult.text = '{"version":1,"result":"legacy"}'; + c.clearDone(0); + c.settle(); + assert.deepEqual(c.notifications.map(entry => entry.key), ['arrival']); + assert.deepEqual(Object.keys(c.hiddenNotifications), ['old', 'new']); + assert.deepEqual([...c.pendingClearKeys], []); + assert.equal(c.notificationDeleteError, ''); +}); +test('failed legacy clear retains the snapshot and new arrivals', () => { + const c = context(); + c.clearAllNotifications(); + c.notifications.push({key: 'arrival', file: 'arrival'}); + c.clearResult.text = '{"version":1,"result":"legacy"}'; + c.clearDone(1); + c.settle(); + assert.equal(c.notifications.length, 3); + assert.deepEqual(Object.keys(c.hiddenNotifications), []); + assert.deepEqual([...c.pendingClearKeys], []); + assert(c.notificationDeleteError); +}); +test('single delete refused during clear leaves rows and reports busy', () => { + const c = context(); + c.clearProc.running = true; + assert.equal(c.forgetNotification(c.notifications[0]), false); + assert.equal(c.notifications.length, 2); + assert.equal(c.forgetQueue.length, 0); + assert(c.notificationDeleteError); +}); +test('actual bulk command uses one keyed IPC and preserves legacy flow', () => { + const d = fs.mkdtempSync(path.join(os.tmpdir(), 'notification-ipc-')); + try { + const bin = path.join(d, 'bin'); + fs.mkdirSync(bin); + fs.symlinkSync('/bin/sh', path.join(bin, 'sh')); + const log = path.join(d, 'log'); + fs.writeFileSync( + path.join(bin, 'qs'), + '#!/bin/sh\nprintf "%s\\n" "$*" >> "$NOTIFY_LOG"\ncase "$*" in\n*forgetAll) [ "$NOTIFY_CAP" != old ] || exit 23; printf "%s" "$NOTIFY_ACK";;\n*dismissAll|*clear) printf "ok\\n";;\n*) exit 24;;\nesac\n', + {mode : 0o755}); + const c = context(); + c.notificationsDir = d; + c.clearAllNotifications(); + assert.equal(c.notifications.length, 2); + let env = { + ...process.env, + PATH : bin, + NOTIFY_LOG : log, + NOTIFY_ACK : '{"version":1,"result":"ok","keys":["old"]}' + }; + fs.writeFileSync(path.join(d, 'live.json'), '[]'); + let r = cp.spawnSync(c.clearProc.command[0], c.clearProc.command.slice(1), + {env, encoding : 'utf8'}); + assert.equal(r.status, 0); + assert(M.clearResult(r.stdout, r.status).ok); + assert.equal(fs.readFileSync(log, 'utf8').trim().split('\n').length, 1); + assert(fs.readFileSync(log, 'utf8').includes('forgetAll')); + r = cp.spawnSync(c.clearProc.command[0], c.clearProc.command.slice(1), + {env : {...env, NOTIFY_CAP : 'old'}, encoding : 'utf8'}); + assert.equal(r.status, 23); + assert(!M.clearResult(r.stdout, r.status).ok); + fs.unlinkSync(path.join(d, 'live.json')); + fs.writeFileSync(log, ''); + r = cp.spawnSync(c.clearProc.command[0], c.clearProc.command.slice(1), + {env, encoding : 'utf8'}); + assert.equal(r.status, 0); + assert(M.clearResult(r.stdout, 0).legacy); + assert.equal(fs.readFileSync(log, 'utf8').trim().split('\n').length, 2); + } finally { + fs.rmSync(d, {recursive : true, force : true}) + } +}); +test('async refusal identifies only the rejected key and continues the queue', () => { + const c = context(); + assert(c.forgetNotification(c.notifications[0])); + c.forgetProc.running = true; + assert(c.forgetNotification(c.notifications[1])); + c.forgetProc.running = false; + c.forgetResult.text = 'busy'; + c.forgetDone(1); + assert.deepEqual(c.failedKeys, ['old']); + assert.equal(c.pendingForget.key, 'new'); + assert.equal(c.notifications.length, 2); + c.forgetProc.running = false; + c.forgetResult.text = 'ok'; + c.forgetDone(0); + c.settle(); + assert.deepEqual(c.failedKeys, ['old']); + assert.deepEqual(c.notifications.map(entry => entry.key), ['old']); +}); +console.log('PASS total', n, 'actual source consumer cases; no real daemon/notification operation'); diff --git a/packages/omamobile-shell/test/notification-refusal.py b/packages/omamobile-shell/test/notification-refusal.py new file mode 100644 index 000000000..40ef87c5f --- /dev/null +++ b/packages/omamobile-shell/test/notification-refusal.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Insert actual QuickSettings callbacks into the real-row refusal fixture.""" +from pathlib import Path +import sys + +here = Path(__file__).resolve().parent +source = (here / "../plugins/omamobile.quicksettings/QuickSettings.qml").read_text() + + +def body(start): + begin = source.index("{", start) + depth = 1 + end = begin + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[begin:end] + + +def function(name): + start = source.index(" function " + name + "(") + begin = source.index("{", start) + return source[start:begin] + body(start) + + +callbacks = [function(name) for name in ( + "acknowledgeNotifications", "forgetNotification", "runForget")] +start = source.index("onExited: function(code)", source.index("id: forgetProc\n")) +callbacks.append(" function forgetDone(code) " + body(start)) +start = source.index("onStreamFinished:", source.index("id: notificationsRead\n")) +callbacks.append(" function readDone(text) " + body(start)) +fixture = (here / "notification-refusal.qml").read_text() +assert fixture.count("// PRODUCTION_CALLBACKS") == 1 +Path(sys.argv[1]).write_text(fixture.replace("// PRODUCTION_CALLBACKS", "\n".join(callbacks))) diff --git a/packages/omamobile-shell/test/notification-refusal.qml b/packages/omamobile-shell/test/notification-refusal.qml new file mode 100644 index 000000000..4b7ce1f5e --- /dev/null +++ b/packages/omamobile-shell/test/notification-refusal.qml @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: MIT +// Actual QuickSettings queue/completion/read callbacks are inserted by +// notification-refusal.py. Only process and IPC values are inert; rows and +// pointer gestures are real, including delegate preservation on unchanged reads. +import QtQuick +import QtTest +import Quickshell +import "quicksettings/NotificationsModel.js" as NotificationsModel +import "quicksettings" + +Item { + id: top + width: 412 + height: 892 + + QtObject { + id: root + property color foreground: "#c0caf5" + property double nowMs: Date.now() + property var notifications: [] + property bool clearing: false + property var forgetQueue: [] + property var pendingForget: null + property var hiddenNotifications: ({}) + property var notificationFiles: [] + property string notificationDeleteError: "" + property bool opened: false + property double seenStamp: 0 + property string rawNotifications: "" + function writeSeen() {} + + function openNotification(entry) {} + signal notificationForgetFailed(string key) + + // PRODUCTION_CALLBACKS + + } + + QtObject { id: clearProc; property bool running: false } + QtObject { id: forgetProc; property bool running: false; property var command: [] } + QtObject { id: forgetResult; property string text: "" } + QtObject { id: notificationsLater; function restart() {} } + Flickable { + id: list + x: 16 + y: 100 + width: 380 + height: 300 + contentWidth: width + contentHeight: rows.implicitHeight + boundsBehavior: Flickable.StopAtBounds + clip: true + + Column { + id: rows + width: list.width + spacing: 4 + + Repeater { + id: repeater + model: root.notifications + delegate: NotificationRow { + host: root + entry: modelData + width: rows.width + swipeEnabled: !list.moving && !root.clearing + clearing: root.clearing + } + } + } + } + + TestCase { + id: test + name: "NotificationRefusal" + when: windowShown + + function fill(n) { + var lines = [] + for (var i = 0; i < n; i++) + lines.push(JSON.stringify({ id: i + 1, originalId: i + 1, app: "app" + i, summary: "Note " + i, + body: "Body of note " + i + " that runs on to a second line of text", + execArgv: JSON.stringify(["omarchy-launch-" + i]), urgency: 1, + timestamp: 1760000000000 + i * 1000 })) + root.rawNotifications = lines.join("\n") + root.notifications = NotificationsModel.parse(root.rawNotifications) + root.clearing = false + root.forgetQueue = [] + root.pendingForget = null + root.hiddenNotifications = ({}) + root.notificationDeleteError = "" + forgetProc.running = false + forgetResult.text = "" + list.contentY = 0 + tryCompare(repeater, "count", n) + waitForRendering(list) + } + + function rowAt(i) { return repeater.itemAt(i) } + + // A finger from (x, y) on the row, moved by (dx, dy) in steps. + function drag(item, x, y, dx, dy, steps, stepMs) { + var t = touchEvent(top) + var p = item.mapToItem(top, x, y) + t.press(0, top, p.x, p.y).commit() + for (var s = 1; s <= steps; s++) { + wait(stepMs) + t.move(0, top, p.x + dx * s / steps, p.y + dy * s / steps).commit() + } + wait(stepMs) + t.release(0, top, p.x + dx, p.y + dy).commit() + } + + function test_refusal_restores_only_the_rejected_row() { + fill(3) + var first = rowAt(0), second = rowAt(1) + drag(first, 40, first.height / 2, 260, 0, 12, 16) + tryVerify(function() { return root.pendingForget !== null }, 2000) + var firstKey = first.entry.key, secondKey = second.entry.key + drag(second, 40, second.height / 2, 260, 0, 12, 16) + tryVerify(function() { return root.forgetQueue.length === 1 }, 2000) + compare(first.fold, 0) + compare(second.fold, 0) + forgetProc.running = false + forgetResult.text = "busy" + root.forgetDone(1) + root.readDone(root.rawNotifications) + tryCompare(first, "swipeOffset", 0, 1000) + compare(first.fold, 1, "the rejected row returns") + compare(second.fold, 0, "the other accepted row stays folded") + compare(rowAt(0), first) + compare(rowAt(1), second) + compare(root.pendingForget.key, secondKey, "the queue continues") + verify(firstKey !== secondKey) + forgetProc.running = false + forgetResult.text = "ok" + root.forgetDone(0) + tryCompare(repeater, "count", 2) + verify(root.notifications.some(function(entry) { return entry.key === firstKey })) + verify(!root.notifications.some(function(entry) { return entry.key === secondKey })) + } + + function test_async_refusal_restores_the_real_row() { + fill(3) + var row = rowAt(0) + drag(row, 40, row.height / 2, 260, 0, 12, 16) + tryVerify(function() { return root.pendingForget !== null }, 2000) + compare(row.fold, 0, "row folded before reply") + compare(root.notifications.length, 3) + forgetProc.running = false + forgetResult.text = "busy" + root.forgetDone(1) + verify(root.notificationDeleteError !== "") + root.readDone(root.rawNotifications) + compare(repeater.count, 3) + compare(rowAt(0), row, "unchanged read preserves delegate") + tryCompare(row, "swipeOffset", 0, 1000) + compare(row.fold, 1, "IPC refusal must restore folded row") + verify(row.visible) + verify(!row.dismissing) + } + } +} diff --git a/packages/omamobile-shell/test/notifications-model.js b/packages/omamobile-shell/test/notifications-model.js index e47a7ac03..262f77cfa 100644 --- a/packages/omamobile-shell/test/notifications-model.js +++ b/packages/omamobile-shell/test/notifications-model.js @@ -134,6 +134,68 @@ test("swipeOutcome: past 35% or a flick goes that way, else back", () => { assert.strictEqual(M.swipeOutcome(300, 0, 0, fling), 0, "no width yet") }) +// Omarchy 4.5's files (shell/plugins/notifications/Store.js): live.json and +// history.json, each one line, a JSON array of rows as Store.persistable and +// Store.closedEntry write them. These rows were made by 4.5.0-3's own +// Store.js (snapshot, persistable, closedEntry, serialise); a verification +// code is stored redacted. +const row45 = (o) => Object.assign({ + key: "nmgx1a2b3", originalId: 3, senderPid: 0, execArgv: "[\"omarchy-launch-wifi\"]", execActions: "", glyph: "", + app: "Signal", appIcon: "signal-desktop", summary: "Ana", body: "See you soon & bye", rawBody: "", + source: "Signal", groupKey: "app:signal", urgency: 1, expireTimeout: 0, duration: 0, ts: 1760000000.123 +}, o) +const closed45 = (o) => Object.assign(row45(o), { closed_ts: 1760000060.5, closed_reason: "dismissed" }, o) +const store45 = (live, history) => JSON.stringify(live) + "\n" + JSON.stringify(history) + "\n" + +test("parse reads Omarchy 4.5's live.json and history.json, newest first", () => { + const raw = store45([row45({ key: "nlive", summary: "on screen", ts: 1760000300.5 })], + [closed45({ key: "nnew", summary: "new", ts: 1760000200 }), closed45({ key: "nold", summary: "old", ts: 1760000100 }), + closed45({ key: "ncode", originalId: 9, app: "", appIcon: "", execArgv: "", source: "", groupKey: "", + summary: "Verification notification", body: "[redacted]", ts: 1760000150, closed_reason: "expired" })]) + const rows = M.parse(raw) + assert.deepStrictEqual(rows.map((r) => r.summary), ["on screen", "new", "Verification notification", "old"]) + assert.deepStrictEqual(rows.map((r) => r.key), ["nlive", "nnew", "ncode", "nold"]) + assert.strictEqual(rows[0].timestamp, 1760000300500, "ts in seconds, as milliseconds") + const [one] = M.parse(store45([], [closed45({})])) + assert.deepStrictEqual(one, { key: "nmgx1a2b3", file: "nmgx1a2b3", app: "Signal", summary: "Ana", body: "See you soon & bye", + glyph: "", execArgv: "[\"omarchy-launch-wifi\"]", urgency: 1, timestamp: 1760000000123 }) + assert.deepStrictEqual(M.tapArgv(one), ["omarchy-launch-wifi"]) +}) + +test("on 4.5 each row carries its key, which forget takes", () => { + const [row] = M.parse(store45([], [closed45({ key: "nabc_1-Z" })])) + assert.strictEqual(row.file, "nabc_1-Z") + assert.match(row.file, /^[A-Za-z0-9_-]{1,120}$/, "the shape 4.5's Store.KEY accepts") +}) + +test("4.5: a row in both files shows once; rows without a usable key or text are skipped", () => { + const raw = store45([row45({ key: "nsame", summary: "live copy" })], + [closed45({ key: "nsame", summary: "history copy" }), closed45({ key: "bad key" }), closed45({ key: "" }), + closed45({ key: "x".repeat(121) }), closed45({ key: "nempty", summary: "", body: "" }), 7, null, [1], "n"]) + const rows = M.parse(raw) + assert.deepStrictEqual(rows.map((r) => r.summary), ["live copy"]) + assert.deepStrictEqual(M.parse("\n\n"), [], "4.5's files as its service creates them: empty") + assert.deepStrictEqual(M.parse("[]\n[]\n"), []) + assert.strictEqual(M.parse(store45([], [closed45({ ts: "soon" })]))[0].timestamp, 0, "no usable ts: no age") +}) + +test("4.5: shown hides a swiped row until it is gone, and lists every key for Clear all", () => { + const history = Array.from({ length: 12 }, (_, i) => closed45({ key: "n" + i, ts: 1760000000 + i })) + let view = M.shown(store45([], history), { n11: 900 }, 1000) + assert.strictEqual(view.entries.length, M.LIMIT) + assert.strictEqual(view.entries[0].key, "n10") + assert.deepStrictEqual(view.hidden, { n11: 900 }) + assert.strictEqual(view.files.length, 12, "every row read, not only the ten shown") + view = M.shown(store45([], history.slice(0, 11)), view.hidden, 1000) + assert.deepStrictEqual(view.hidden, {}) +}) + +test("4.0: shown lists every file name for Clear all too", () => { + const raw = Array.from({ length: 11 }, (_, i) => file({ timestamp: 100 + i, id: i })).join("\n") + assert.strictEqual(M.shown(raw, {}, 0).files.length, 11) + assert.strictEqual(M.shown(raw, {}, 0).files[0], "110-10.json") +}) + let failed = 0 for (const [name, fn] of tests) { try { diff --git a/packages/omamobile-shell/test/notifications-store.sh b/packages/omamobile-shell/test/notifications-store.sh new file mode 100644 index 000000000..617f064f4 --- /dev/null +++ b/packages/omamobile-shell/test/notifications-store.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# The notification shade's shell commands, taken out of QuickSettings.qml +# and run against both of Omarchy's layouts in a throwaway directory: the +# read (one file per notification under notifications/ and history/ on +# 4.0; live.json and history.json on 4.5, chosen by whether history.json +# exists) and Clear all (dismissAll then clear on 4.0; one snapshot +# forgetAll call on 4.5), with a fake qs that only +# records its calls. The rows come out through NotificationsModel.js. +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +qs=plugins/omamobile.quicksettings/QuickSettings.qml +fail() { printf 'not ok - %s\n' "$1" >&2; exit 1; } +pass() { printf 'ok - %s\n' "$1"; } + +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +# The script of `.command = ["sh", "-c", "…" + "…",` as sh gets it: the +# QML string literals joined (they are JSON-compatible). +script() { + python3 - "$qs" "$1" <<'PY' +import json, re, sys +text = open(sys.argv[1]).read() +m = re.search(re.escape(sys.argv[2]) + r'\s*\[\s*"sh",\s*"-c",\s*((?:"(?:[^"\\]|\\.)*"\s*\+?\s*)+),', text) +if not m: sys.exit("no command for " + sys.argv[2]) +print("".join(json.loads(s) for s in re.findall(r'"(?:[^"\\]|\\.)*"', m.group(1))), end="") +PY +} +read_sh=$(script 'command:') && [[ $read_sh == *history.json* ]] || fail "found the shade's read in $qs" +clear_sh=$(script 'clearProc.command =') || fail "found Clear all in $qs" + +mkdir -p "$tmp/bin" +printf '#!/bin/sh\necho "qs $*" >>"%s/calls"\n' "$tmp" >"$tmp/bin/qs"; chmod +x "$tmp/bin/qs" +rows() { node -e ' + const M = require(process.argv[1]); let raw = "" + process.stdin.on("data", (d) => raw += d).on("end", () => { + const v = M.shown(raw, {}, 0) + console.log(v.entries.map((e) => e.summary).join(",") + " | " + v.files.join(",")) + })' "$PWD/plugins/omamobile.quicksettings/NotificationsModel.js"; } + +# Omarchy 4.0.6: a toast on screen and two in history, one file each, as +# its serializePopup writes them (NotificationLogic.js). +d=$tmp/v40/notifications; mkdir -p "$d/history" "$d/images" +one() { printf '{"id":%s,"originalId":%s,"app":"App","appIcon":"","summary":"%s","body":"","image":"","glyph":"","execArgv":"","urgency":1,"expireTimeout":0,"timestamp":%s}\n' "$2" "$2" "$3" "$1"; } +one 3000 3 live >"$d/3000-3.json" +one 2000 2 newer >"$d/history/2000-2.json" +one 1000 1 older >"$d/history/1000-1.json" +got=$(sh -c "$read_sh" sh "$d" | rows) +[[ $got == "live,newer,older | 3000-3.json,2000-2.json,1000-1.json" ]] || fail "4.0: the shade reads the toasts and history/ ($got)" +: >"$tmp/calls" +PATH=$tmp/bin:$PATH sh -c "$clear_sh" sh /shell "$d" 3000-3.json 2000-2.json 1000-1.json +[[ $(cat "$tmp/calls") == $'qs ipc -p /shell call notifications dismissAll\nqs ipc -p /shell call notifications clear' ]] \ + || fail "4.0: Clear all is dismissAll, then clear, and nothing else ($(cat "$tmp/calls"))" +pass "notification shade on Omarchy 4.0: reads one file each, clears through dismissAll and clear" + +# Omarchy 4.5.0: live.json and history.json, one JSON array each (Store.js), +# next to 4.0 leftovers its migration had not removed yet, which must not +# show; then the files as its service first creates them, empty. +d=$tmp/v45/notifications; mkdir -p "$d/history" +row() { printf '{"key":"%s","originalId":1,"senderPid":0,"execArgv":"","execActions":"","glyph":"","app":"App","appIcon":"","summary":"%s","body":"","rawBody":"","source":"App","groupKey":"app:app","urgency":1,"expireTimeout":0,"duration":0,"ts":%s%s}' "$@"; } +printf '[%s]\n' "$(row nlive live 3.5 '')" >"$d/live.json" +printf '[%s,%s]\n' "$(row nnew newer 2 ',"closed_ts":9,"closed_reason":"dismissed"')" "$(row nold older 1 ',"closed_ts":8,"closed_reason":"expired"')" >"$d/history.json" +one 5000 5 leftover >"$d/history/5000-5.json" +one 6000 6 stray >"$d/6000-6.json" +got=$(sh -c "$read_sh" sh "$d" | rows) +[[ $got == "live,newer,older | nlive,nnew,nold" ]] || fail "4.5: the shade reads live.json and history.json only ($got)" +: >"$tmp/calls" +PATH=$tmp/bin:$PATH sh -c "$clear_sh" sh /shell "$d" nlive nnew nold +[[ $(cat "$tmp/calls") == "qs ipc -p /shell call notifications forgetAll" ]] \ + || fail "4.5: Clear all is one daemon snapshot call ($(cat "$tmp/calls"))" +rm -rf "$d/history" "$d/6000-6.json"; : >"$d/live.json"; : >"$d/history.json" +got=$(sh -c "$read_sh" sh "$d" | rows) +[[ $got == " | " ]] || fail "4.5: empty files, no rows ($got)" +: >"$tmp/calls" +PATH=$tmp/bin:$PATH sh -c "$clear_sh" sh /shell "$d" +[[ $(cat "$tmp/calls") == "qs ipc -p /shell call notifications forgetAll" ]] || fail "4.5: empty Clear all still requests one daemon snapshot" +pass "notification shade on Omarchy 4.5: reads live.json and history.json, clears through one acknowledged snapshot" diff --git a/packages/omamobile-shell/test/quicksettings-render b/packages/omamobile-shell/test/quicksettings-render index fba4058e7..4c986065c 100755 --- a/packages/omamobile-shell/test/quicksettings-render +++ b/packages/omamobile-shell/test/quicksettings-render @@ -6,7 +6,9 @@ # fit the screen: the real QuickSettings.qml, its layer-shell window a # plain Item, over a throwaway $HOME with a few notifications of our own # in the shade. No backend answers here (no D-Bus, no scripts on PATH), so -# the tiles show as unavailable; it is the layout under review. Runs inside +# the tiles show as unavailable; it is the layout under review. The dark +# theme's notifications are Omarchy 4.0's files, the light theme's 4.5's +# live.json and history.json, so the shade's read runs on both. Runs inside # the OWL conformance container (tests/owl/Dockerfile), never on a desktop: # # docker run --rm --network none -u "$(id -u):$(id -g)" -v "$PWD:/src" \ @@ -53,17 +55,30 @@ for theme in tokyo-night catppuccin-latte; do home=/tmp/quicksettings-home-$theme rm -rf "$home"; mkdir -p "$home/.local/state/omarchy/current" "$home/.local/state/omarchy/notifications/history" "$home/.config/omamobile" ln -sfn "/themes/$theme" "$home/.local/state/omarchy/current/theme" - # Three notifications of our own in the history, as Omarchy's service - # writes them (one line each, named -.json). - python3 - "$home/.local/state/omarchy/notifications/history" <<'PY' + # Three notifications of our own, as Omarchy's service writes them: on + # 4.0 one line per file in history/, named -.json; on 4.5 + # one on screen in live.json and two in history.json (Store.js). + python3 - "$home/.local/state/omarchy/notifications" "$theme" <<'PY' import json, sys -d = sys.argv[1] +d, theme = sys.argv[1:] rows = [(1760000300000, 1, "Signal", "Ana", "See you soon"), (1760000200000, 2, "Omarchy", "Update available", "Omarchy 4.0.7 is ready to install"), (1760000100000, 3, "Clock", "Alarm", "Tomorrow 07:00")] -for ts, i, app, summary, body in rows: - with open("%s/%d-%d.json" % (d, ts, i), "w") as f: - f.write(json.dumps({"id": i, "originalId": i, "app": app, "appIcon": "", "summary": summary, "body": body, "image": "", "glyph": "", - "execArgv": "", "urgency": 1, "expireTimeout": 0, "timestamp": ts}) + "\n") +if theme == "catppuccin-latte": + def row(ts, i, app, summary, body, **closed): + return dict({"key": "n%d" % i, "originalId": i, "senderPid": 0, "execArgv": "", "execActions": "", "glyph": "", "app": app, "appIcon": "", + "summary": summary, "body": body, "rawBody": "", "source": app, "groupKey": "app:" + app.lower(), "urgency": 1, + "expireTimeout": 0, "duration": 0, "ts": ts / 1000}, **closed) + with open(d + "/live.json", "w") as f: + f.write(json.dumps([row(*rows[0])]) + "\n") + with open(d + "/history.json", "w") as f: + f.write(json.dumps([row(*r, closed_ts=r[0] / 1000 + 60, closed_reason="dismissed") for r in rows[1:]]) + "\n") + with open(d + "/quiet.json", "w") as f: + f.write(json.dumps({"dnd": False}) + "\n") +else: + for ts, i, app, summary, body in rows: + with open("%s/history/%d-%d.json" % (d, ts, i), "w") as f: + f.write(json.dumps({"id": i, "originalId": i, "app": app, "appIcon": "", "summary": summary, "body": body, "image": "", "glyph": "", + "execArgv": "", "urgency": 1, "expireTimeout": 0, "timestamp": ts}) + "\n") PY python3 - "$out" "$theme" > "$h/job-$theme.json" <<'PY' import json, sys @@ -122,6 +137,7 @@ for name, g in geo.items(): json.dumps([parts.get("handle"), parts.get("settingsButton")])) has_shade = "shade" in parts check(name + ": the notification shade shows", has_shade and inside(parts["shade"], screen, 1) and parts["shade"]["h"] >= 100, json.dumps(parts.get("shade"))) + check(name + ": the shade read all three notifications", g["notifications"] == 3, str(g["notifications"])) if has_shade: beside = parts["shade"]["x"] >= parts["sheet"]["x"] + parts["sheet"]["w"] if landscape else parts["shade"]["y"] >= parts["sheet"]["y"] + parts["sheet"]["h"] check(name + ": the shade is %s the sheet" % ("beside" if landscape else "under"), beside and apart(parts["sheet"], parts["shade"])) diff --git a/packages/omamobile-shell/test/shade-touch b/packages/omamobile-shell/test/shade-touch index bb3c3f2b3..53fc03fd2 100755 --- a/packages/omamobile-shell/test/shade-touch +++ b/packages/omamobile-shell/test/shade-touch @@ -17,6 +17,7 @@ trap 'rm -rf "$work"' EXIT mkdir -p "$work/quicksettings" cp "$plugin/NotificationRow.qml" "$plugin/NotificationsModel.js" "$plugin/Readable.js" "$work/quicksettings/" cp "$here/shade-touch.qml" "$work/tst_shade_touch.qml" +python3 "$here/notification-refusal.py" "$work/tst_notification_refusal.qml" export QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software QML_DISABLE_DISK_CACHE=1 -exec "$runner" -import "$here/qml-stubs" -input "$work/tst_shade_touch.qml" +exec "$runner" -import "$here/qml-stubs" -input "$work" diff --git a/packages/omamobile-shell/test/shade-touch.qml b/packages/omamobile-shell/test/shade-touch.qml index 8c975d32f..f5602f654 100644 --- a/packages/omamobile-shell/test/shade-touch.qml +++ b/packages/omamobile-shell/test/shade-touch.qml @@ -20,10 +20,16 @@ Item { property var notifications: [] property var opened: [] property var forgotten: [] + property bool clearing: false + property bool rejectForget: false + property bool holdReply: false + property var pendingEntry: null function openNotification(entry) { opened = opened.concat([entry.key]) } function forgetNotification(entry) { + if (clearing || rejectForget) return false forgotten = forgotten.concat([entry.file]) - Qt.callLater(function() { sheet.notifications = NotificationsModel.without(sheet.notifications, entry.key) }) + if (holdReply) pendingEntry = entry + else Qt.callLater(function() { sheet.notifications = NotificationsModel.without(sheet.notifications, entry.key) }) return true } } @@ -51,7 +57,8 @@ Item { host: sheet entry: modelData width: rows.width - swipeEnabled: !list.moving + swipeEnabled: !list.moving && !sheet.clearing + clearing: sheet.clearing } } } @@ -70,6 +77,10 @@ Item { execArgv: JSON.stringify(["omarchy-launch-" + i]), urgency: 1, timestamp: 1760000000000 + i * 1000 })) sheet.notifications = NotificationsModel.parse(lines.join("\n")) + sheet.clearing = false + sheet.rejectForget = false + sheet.holdReply = false + sheet.pendingEntry = null sheet.opened = [] sheet.forgotten = [] list.contentY = 0 @@ -138,6 +149,84 @@ Item { tryVerify(function() { return rowAt(0).y < start }, 1000, "the next row moves up") } + function test_clear_in_progress_keeps_the_row_visible() { + fill(3) + sheet.clearing = true + var row = rowAt(0) + drag(row, 40, row.height / 2, 260, 0, 12, 16) + wait(400) + compare(row.fold, 1) + compare(row.swipeOffset, 0) + verify(row.visible) + compare(sheet.forgotten.length, 0) + compare(repeater.count, 3) + } + + function test_clear_starting_during_fly_off_restores_the_row() { + fill(3) + var row = rowAt(0) + drag(row, 40, row.height / 2, 260, 0, 12, 16) + verify(row.dismissing) + sheet.clearing = true + tryCompare(row, "swipeOffset", 0, 1000) + compare(row.fold, 1) + verify(row.visible) + verify(!row.dismissing) + compare(sheet.forgotten.length, 0) + compare(repeater.count, 3) + } + + function test_refused_forget_restores_fold_and_position_without_refresh() { + fill(3) + sheet.rejectForget = true + var row = rowAt(0) + drag(row, 40, row.height / 2, 260, 0, 12, 16) + tryVerify(function() { return !row.dismissing }, 2000) + tryCompare(row, "swipeOffset", 0, 1000) + compare(row.fold, 1) + verify(row.visible) + compare(sheet.forgotten.length, 0) + compare(repeater.count, 3) + } + + function test_swipe_then_immediate_scroll_still_forgets_the_row() { + fill(10) + var row = rowAt(0) + var key = row.entry.key, file = row.entry.file + drag(row, 40, row.height / 2, 260, 0, 12, 16) + verify(row.dismissing) + compare(sheet.forgotten.length, 0, "the fly-off has not sent the request yet") + // Start a real vertical gesture while the dismissed row is flying off. + drag(list, list.width / 2, 220, 0, -180, 12, 16) + tryVerify(function() { return list.contentY > 40 }, 1000) + tryVerify(function() { return sheet.forgotten.length === 1 }, 2000) + compare(sheet.forgotten[0], file) + tryCompare(repeater, "count", 9) + for (var i = 0; i < repeater.count; i++) verify(rowAt(i).entry.key !== key) + } + + function test_scrolling_while_reply_is_pending_keeps_the_row_folded() { + fill(10) + sheet.holdReply = true + var row = rowAt(0) + var key = row.entry.key + drag(row, 40, row.height / 2, 260, 0, 12, 16) + tryVerify(function() { return sheet.forgotten.length === 1 }, 2000) + compare(row.fold, 0) + compare(repeater.count, 10, "the service reply is still pending") + drag(list, list.width / 2, 220, 0, -180, 12, 16) + tryVerify(function() { return list.contentY > 40 }, 1000) + compare(row.fold, 0, "scrolling does not unfold an accepted swipe") + verify(!row.visible) + compare(sheet.forgotten.length, 1) + // Clear all also cannot resurrect a row whose request was accepted. + sheet.clearing = true + compare(row.fold, 0) + sheet.notifications = NotificationsModel.without(sheet.notifications, sheet.pendingEntry.key) + tryCompare(repeater, "count", 9) + for (var i = 0; i < repeater.count; i++) verify(rowAt(i).entry.key !== key) + } + function test_a_short_swipe_springs_back() { fill(3) var row = rowAt(0) diff --git a/packages/omamobile-shell/test/status-model.js b/packages/omamobile-shell/test/status-model.js index 3fd059373..b239fb966 100644 --- a/packages/omamobile-shell/test/status-model.js +++ b/packages/omamobile-shell/test/status-model.js @@ -51,3 +51,22 @@ assert.strictEqual(M.unreadCount([], 0), 0) assert.strictEqual(M.unreadCount(files.filter((f) => f !== "3000-3.json"), "2000"), 0, "the unread one forgotten") assert.strictEqual(M.unreadCount(files.filter((f) => f !== "1000-1.json"), "2000"), 1, "a seen one forgotten") console.log("ok - status model: unread notifications") + +// Omarchy 4.5: history.json, a JSON array of rows with `ts` in seconds (as +// 4.5.0-3's Store.closedEntry writes them); the shade's mark is the newest +// ts it showed, in milliseconds. +const hist45 = JSON.stringify([{ key: "n3", ts: 3, closed_ts: 9, closed_reason: "dismissed" }, + { key: "n2", ts: 2.0004, closed_ts: 8, closed_reason: "expired" }, + { key: "n1", ts: 1, closed_ts: 7, closed_reason: "dismissed" }]) + "\n" +assert.strictEqual(M.unreadStored(hist45, 0), 3, "nothing seen yet: every history row") +assert.strictEqual(M.unreadStored(hist45, "2000"), 1, "only what arrived after the newest one the shade showed") +assert.strictEqual(M.unreadStored(hist45, 3000), 0) +assert.strictEqual(M.unreadStored(JSON.stringify([{ ts: 1.9996 }]), 2000), 0, "rounded as the shade rounds") +assert.strictEqual(M.unreadStored("", 0), 0, "the empty file the service creates") +assert.strictEqual(M.unreadStored("[]\n", 0), 0) +assert.strictEqual(M.unreadStored("{\"ts\": 5}", 0), 0, "not an array") +assert.strictEqual(M.unreadStored(JSON.stringify({ length: 1, 0: { ts: 5 } }), 0), 0, "not an array, even one that looks like it") +assert.strictEqual(M.unreadStored("[{\"ts\": 5", 0), 0, "torn") +assert.strictEqual(M.unreadStored(JSON.stringify([null, 4, { ts: "x" }, { ts: -1 }, {}, { ts: 5 }]), 0), 1) +assert.strictEqual(M.unreadStored(undefined, 0), 0) +console.log("ok - status model: unread notifications on Omarchy 4.5") diff --git a/packages/omamobile-shell/version b/packages/omamobile-shell/version index d8a838a1f..39f6e712d 100644 --- a/packages/omamobile-shell/version +++ b/packages/omamobile-shell/version @@ -1 +1 @@ -0.2.101 +0.2.103