pragma ComponentBehavior: Bound import QtQuick import Quickshell import Quickshell.Io import Quickshell.Services.Notifications Item { id: root property bool dnd: false property int unreadCount: 0 property var notifications: [] property var nativeNotifications: ({}) property var expandedGroups: [] property var activeToasts: [] property var toastById: ({}) property var replyDrafts: ({}) property var replyFailures: ({}) readonly property int defaultToastTimeoutMs: 5000 property var lastAction: ({}) readonly property int groupPreviewCount: 1 readonly property bool removalLifecycleLock: true function urgencyName(value) { if (value === NotificationUrgency.Critical) return "critical"; if (value === NotificationUrgency.Low) return "low"; if (String(value).toLowerCase().indexOf("critical") >= 0) return "critical"; if (String(value).toLowerCase().indexOf("low") >= 0) return "low"; return "normal"; } function actionList(record) { const source = record && record.actions ? record.actions : []; const rows = []; for (let i = 0; i < source.length; i++) { const action = source[i]; rows.push({ "id": action.id || action.identifier || `action-${i}`, "label": action.label || action.text || "action" }); } return rows; } function normalize(record) { const id = String(record.id); const actions = actionList(record); return { "id": id, "nativeId": record.nativeId, "appName": record.appName || "unknown", "appIcon": record.appIcon || "", "image": record.image || "", "summary": record.summary || "", "body": record.body || "", "time": Number(record.time || Date.now()), "urgency": urgencyName(record.urgency || "normal"), "expireTimeout": Number(record.expireTimeout !== undefined ? record.expireTimeout : -1), "transient": !!record.transient, "actions": actions, // KDE/Plasma de-facto progress hint (int:value 0-100); -1 = absent. "value": Number(record.value !== undefined ? record.value : -1), // resident: keep the notification after an action is invoked. "resident": !!record.resident, // action-icons: action identifiers double as freedesktop icon names. "hasActionIcons": !!record.hasActionIcons, // inline reply (chat apps): a quick-reply field + sendInlineReply(). "hasInlineReply": !!record.hasInlineReply, "inlineReplyPlaceholder": String(record.inlineReplyPlaceholder || ""), "popup": !dnd, "closed": false, "read": false, "removalLifecycleLock": false }; } function toastEligible(row, dndOn) { if (row.urgency === "critical") return true; return !dndOn; } // KDE/Plasma progress hint: hints.value (0-100), -1 when absent. Read live // off the native object so replace-in-place progress updates flow through. function hintValue(notification) { const h = notification && notification.hints ? notification.hints : null; return h && h.value !== undefined && h.value !== null ? Number(h.value) : -1; } // freedesktop sound hints. sound-file (path) plays via the PipeWire CLI; // sound-name (theme id) needs canberra + a sound theme. suppress-sound mutes. function playSound(notification) { const h = notification && notification.hints ? notification.hints : null; if (!h || h["suppress-sound"]) return; const file = h["sound-file"]; const name = h["sound-name"]; if (file) Quickshell.execDetached(["pw-play", String(file)]); else if (name) Quickshell.execDetached(["canberra-gtk-play", "-i", String(name)]); } function toastTimeoutMs(row) { if (row.urgency === "critical" || Number(row.expireTimeout) === 0) return 0; const et = Number(row.expireTimeout); return et > 0 ? et : defaultToastTimeoutMs; } function mergeRow(list, row) { const next = (list || []).slice(); for (let i = 0; i < next.length; i++) { if (next[i].id === row.id) { next[i] = Object.assign({}, next[i], row, { "read": next[i].read }); return next; } } next.push(row); return next; } function setReplyDraft(notificationId, text) { const id = String(notificationId); const drafts = Object.assign({}, replyDrafts); const failures = Object.assign({}, replyFailures); drafts[id] = String(text || ""); delete failures[id]; replyDrafts = drafts; replyFailures = failures; } function clearReplyState(notificationId) { const id = String(notificationId); const drafts = Object.assign({}, replyDrafts); const failures = Object.assign({}, replyFailures); delete drafts[id]; delete failures[id]; replyDrafts = drafts; replyFailures = failures; } function failReply(notificationId, reason) { const failures = Object.assign({}, replyFailures); failures[String(notificationId)] = String(reason); replyFailures = failures; } function acceptNativeNotification(notification) { if (!notification) return; const id = String(notification.id); const row = normalize({ "id": id, "nativeId": id, "appName": notification.appName, "appIcon": notification.appIcon, "image": notification.image, "summary": notification.summary, "body": notification.body, "time": Date.now(), "urgency": notification.urgency, "expireTimeout": notification.expireTimeout, "transient": notification.transient, "actions": notification.actions || [], "value": hintValue(notification), "resident": notification.resident, "hasActionIcons": notification.hasActionIcons, "hasInlineReply": notification.hasInlineReply, "inlineReplyPlaceholder": notification.inlineReplyPlaceholder }); const eligible = toastEligible(row, dnd); // Upstream owns native objects independently of JS references. // onNotification runs before insertion into trackedNotifications. if (row.transient && !eligible) notification.expire(); else { notification.tracked = true; notification.closed.connect(() => { const remaining = Object.assign({}, root.nativeNotifications); delete remaining[id]; root.nativeNotifications = remaining; }); const map = Object.assign({}, nativeNotifications); map[id] = notification; nativeNotifications = map; } if (!row.transient) { notifications = mergeRow(notifications, row); unreadCount = notifications.filter(n => !n.closed && !n.read).length; } if (eligible) { const tms = toastTimeoutMs(row); const map = Object.assign({}, toastById); // Stamp absolute expiry ONCE. The toast Repeater rebuilds every // delegate whenever the toast set changes; deriving the timer/drain // from a stored expiresAt lets a rebuilt delegate resume at the // right position instead of restarting from full. map[row.id] = Object.assign({}, row, { "toastTimeoutMs": tms, "expiresAt": tms > 0 ? Date.now() + tms : 0 }); toastById = map; activeToasts = activeToasts.filter(x => x !== row.id).concat([row.id]); playSound(notification); } lastAction = { "kind": "native-notification", "id": id }; } function actionRows(notification) { const rows = [ { "id": "close", "kind": "close", "label": "close", "route": "Notifications.qml" } ]; const serverActions = notification.actions || []; for (let i = 0; i < serverActions.length; i++) { const aid = serverActions[i].id || serverActions[i].identifier || `action-${i}`; rows.push({ "id": aid, "kind": "server-action", "label": serverActions[i].label || serverActions[i].text || "action", // with action-icons, the identifier IS a freedesktop icon name. "icon": notification.hasActionIcons ? aid : "", "route": "Notifications.qml" }); } rows.push({ "id": "copy-body", "kind": "copy-body", "label": "copy body", "route": "Notifications.qml" }); return rows; } function highestUrgency(rows) { if (rows.some(row => row.urgency === "critical")) return "critical"; return rows.some(row => row.urgency === "normal") ? "normal" : "low"; } function liveRow(row) { const n = nativeNotifications[String(row.nativeId || row.id)]; if (!n) return row; return Object.assign({}, row, { "summary": n.summary !== undefined ? String(n.summary) : row.summary, "body": n.body !== undefined ? String(n.body) : row.body, "appName": n.appName || row.appName, "appIcon": n.appIcon || row.appIcon, "image": n.image || row.image, "value": hintValue(n), "urgency": urgencyName(n.urgency) }); } function activeToastRows() { const rows = []; for (let t = 0; t < activeToasts.length; t++) { const stored = toastById[activeToasts[t]]; if (!stored) continue; const row = liveRow(stored); if (!row.closed) rows.push(Object.assign({}, row, { "actionRows": actionRows(row), "timeoutMs": row.toastTimeoutMs !== undefined ? row.toastTimeoutMs : toastTimeoutMs(row), "expiresAt": row.expiresAt || 0 })); } return rows; } function nativeIsLive(notification) { return notification && notification.tracked; } function pruneToasts(keep, expired) { const oldMap = toastById; const nextMap = ({}); const nextIds = []; const retainedNative = ({}); const removed = []; for (let i = 0; i < activeToasts.length; i++) { const tid = activeToasts[i]; const toast = oldMap[tid]; if (toast && keep(toast)) { nextIds.push(tid); nextMap[tid] = toast; retainedNative[String(toast.nativeId || toast.id)] = true; } else if (toast) { removed.push(toast); } } // Historical notifications own their native reference independently // from a toast, including replacement ids that alias nativeId. for (let h = 0; h < notifications.length; h++) retainedNative[String(notifications[h].nativeId || notifications[h].id)] = true; const nmap = Object.assign({}, nativeNotifications); let released = false; for (let r = 0; r < removed.length; r++) { const row = removed[r]; const nativeKey = String(row.nativeId || row.id); if (!retainedNative[nativeKey]) { const native = nmap[nativeKey]; if (nativeIsLive(native)) { if (expired) native.expire(); else native.dismiss(); } delete nmap[nativeKey]; released = true; } } activeToasts = nextIds; toastById = nextMap; // Reassign only on release: history bindings read nativeNotifications. if (released) nativeNotifications = nmap; } function dismissToast(id) { const sid = String(id); pruneToasts(toast => String(toast.id) !== sid); return stateJson(); } function expireToast(id) { const sid = String(id); pruneToasts(toast => String(toast.id) !== sid, true); return stateJson(); } function dismissToasts() { pruneToasts(() => false); return stateJson(); } function groups() { // No prototype: an app may be named constructor. const byApp = Object.create(null); for (let raw = 0; raw < notifications.length; raw++) { if (notifications[raw].closed) continue; const n = liveRow(notifications[raw]); if (!byApp[n.appName]) byApp[n.appName] = { "id": n.appName, "appName": n.appName, "latestTime": 0, "notifications": [], "expanded": expandedGroups.indexOf(n.appName) >= 0 }; byApp[n.appName].notifications.push(Object.assign({}, n, { "actionRows": actionRows(n), "replyDraft": String(replyDrafts[n.id] || ""), "replyError": String(replyFailures[n.id] || "") })); byApp[n.appName].latestTime = Math.max(byApp[n.appName].latestTime, n.time); } const result = []; for (const app in byApp) { byApp[app].notifications.sort((a, b) => { return b.time - a.time; }); byApp[app].count = byApp[app].notifications.length; byApp[app].urgency = highestUrgency(byApp[app].notifications); byApp[app].previewCount = groupPreviewCount; byApp[app].visibleNotifications = byApp[app].expanded ? byApp[app].notifications : byApp[app].notifications.slice(0, groupPreviewCount); byApp[app].expandCollapseState = byApp[app].expanded ? "expanded" : "collapsed"; byApp[app].animatedExpandHeight = true; result.push(byApp[app]); } result.sort((a, b) => { return b.latestTime - a.latestTime; }); return result; } function stateObject() { const active = notifications.filter(n => { return !n.closed; }); const grouped = groups(); return { "trackedNativeCount": Object.keys(nativeNotifications).length, "expandedGroups": expandedGroups.slice(0), "groupPreviewCount": groupPreviewCount, "dnd": dnd, "unreadCount": unreadCount, "activeCount": active.length, "groups": grouped, "removalLifecycleLock": removalLifecycleLock, "lastAction": lastAction, "activeToasts": activeToastRows() }; } function stateJson() { return JSON.stringify(stateObject()); } function toggleDnd() { dnd = !dnd; if (dnd) pruneToasts(toast => toast.urgency === "critical", true); lastAction = { "kind": "toggle-dnd", "enabled": dnd }; return stateJson(); } function closeNotification(row, skipNativeDismiss) { if (!row || row.closed) return; row.closed = true; row.removalLifecycleLock = removalLifecycleLock; // The row leaves history now: no tombstone keeps its body for the shell's lifetime. notifications = notifications.filter(n => n !== row); clearReplyState(row.id); unreadCount = notifications.filter(n => !n.closed && !n.read).length; const nativeNotification = nativeNotifications[String(row.nativeId || row.id)]; // Actions/replies may already have closed it. The native closed signal // drops externally closed objects from our owner map as well. if (!skipNativeDismiss && nativeIsLive(nativeNotification)) nativeNotification.dismiss(); activeToasts = activeToasts.filter(x => x !== String(row.id)); const tmap = Object.assign({}, toastById); delete tmap[String(row.id)]; toastById = tmap; // native object is dismissed; drop it so the map doesn't grow for the // life of the process (groups() skips closed rows before liveRow()). const nmap = Object.assign({}, nativeNotifications); delete nmap[String(row.nativeId || row.id)]; nativeNotifications = nmap; } function runAction(notificationId, actionId) { const id = String(notificationId); const action = String(actionId); for (let i = 0; i < notifications.length; i++) { const n = notifications[i]; if (n.id !== id) continue; if (action === "close") { closeNotification(n); lastAction = { "kind": "close", "id": id, "route": "Notifications.qml" }; } else if (action === "copy-body") { if (n.body.length > 0) copyProcess.createObject(root, { "payload": n.body }); lastAction = { "kind": "copy-body", "id": id, "bodyCopied": n.body.length > 0, "route": "Notifications.qml", "clipboardRoute": "wl-copy" }; } else { let invoked = false; const nativeNotification = nativeNotifications[String(n.nativeId || n.id)]; const live = nativeIsLive(nativeNotification); const resident = live ? nativeNotification.resident : n.resident; const nativeActions = live ? nativeNotification.actions : []; for (let j = 0; j < nativeActions.length; j++) { if (nativeActions[j].identifier === action && nativeActions[j].invoke) { nativeActions[j].invoke(); invoked = true; break; } } lastAction = { "kind": "server-action", "id": id, "actionId": action, "invoked": invoked, "resident": !!resident, "route": "Notifications.qml" }; // Native invoke already dismisses a nonresident notification. if (!resident) closeNotification(n, invoked); } notifications = notifications.slice(0); return stateJson(); } lastAction = { "kind": "missing", "id": id, "actionId": action, "route": "Notifications.qml" }; return stateJson(); } // inline reply: route the text to the native object's sendInlineReply(). // freedesktop convention closes the notification after a reply unless it // declared itself resident. function sendReply(notificationId, text) { const id = String(notificationId); const body = String(text || ""); setReplyDraft(id, body); for (let i = 0; i < notifications.length; i++) { const n = notifications[i]; if (n.id !== id) continue; let sent = false; const native = nativeNotifications[String(n.nativeId || n.id)]; const live = nativeIsLive(native); const resident = live ? native.resident : n.resident; if (body.length > 0 && live && native.hasInlineReply) { native.sendInlineReply(body); sent = true; } lastAction = { "kind": "inline-reply", "id": id, "sent": sent, "resident": !!resident, "route": "Notifications.qml" }; if (sent) { clearReplyState(id); if (!resident) closeNotification(n, true); } else { failReply(id, "reply not sent"); } notifications = notifications.slice(0); return stateJson(); } failReply(id, "notification no longer available"); lastAction = { "kind": "missing", "id": id, "sent": false, "route": "Notifications.qml" }; return stateJson(); } // Seen in the history popup: its cards turn neutral and the chip quiets. // Registry.qml calls this when the popup closes, so the accent stays while // the user reads. function markAllRead() { if (!notifications.some(n => !n.closed && !n.read)) return; notifications = notifications.map(n => n.closed || n.read ? n : Object.assign({}, n, { "read": true })); unreadCount = 0; } function toggleGroup(appName) { const app = String(appName); const expanded = expandedGroups.indexOf(app) < 0; expandedGroups = expanded ? expandedGroups.concat([app]) : expandedGroups.filter(row => { return row !== app; }); lastAction = { "kind": "toggleGroup", "appName": app, "expanded": expanded }; return stateJson(); } function discardAllNotifications() { for (const id in nativeNotifications) { const native = nativeNotifications[id]; if (nativeIsLive(native)) native.dismiss(); } notifications = []; unreadCount = 0; // "Clear all" means everything: drop showing toasts (incl. sticky // criticals) and release every tracked native object. activeToasts = []; toastById = ({}); nativeNotifications = ({}); replyDrafts = ({}); replyFailures = ({}); lastAction = { "kind": "discardAll", "route": "Notifications.qml" }; return stateJson(); } Component { id: copyProcess Process { property string payload command: ["wl-copy"] stdinEnabled: true running: true onStarted: { write(payload); stdinEnabled = false; payload = ""; } onRunningChanged: if (!running) destroy() } } NotificationServer { keepOnReload: false persistenceSupported: true bodySupported: true bodyMarkupSupported: true bodyHyperlinksSupported: true bodyImagesSupported: true actionsSupported: true actionIconsSupported: true imageSupported: true inlineReplySupported: true onNotification: notification => root.acceptNativeNotification(notification) } }