From 395de70b268f826d8ee50779ac646f337da406b2 Mon Sep 17 00:00:00 2001 From: mx Date: Thu, 15 Oct 2026 14:47:40 +0200 Subject: [PATCH] Add native notifications with OSD-style banners and a Control Center module glassMxrph now owns org.freedesktop.Notifications. Banners drop out of the bar like the OSD; Control Center stacks history per app like macOS Notification Center. Do Not Disturb lives in the shell and falls back to SwayNC while another daemon holds the bus name. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 16 +- quickshell/config/defaults.json | 13 + quickshell/controlcenter/ControlRegistry.qml | 4 + quickshell/controlcenter/modules/Dnd.qml | 10 +- .../controlcenter/modules/Notifications.qml | 189 ++++++++++++ quickshell/helpers/system.py | 14 +- quickshell/notifications/NotificationCard.qml | 266 +++++++++++++++++ .../notifications/NotificationPopups.qml | 164 ++++++++++ quickshell/services/ConfigLogic.js | 2 + quickshell/services/NotificationService.qml | 281 ++++++++++++++++++ quickshell/services/qmldir | 1 + quickshell/settings/pages/Notifications.qml | 79 ++++- quickshell/shell.qml | 2 + scripts/glassmxrph | 8 +- tests/config.test.cjs | 2 + tests/notifications_runtime.py | 77 +++++ tests/system_providers_test.py | 17 +- 17 files changed, 1132 insertions(+), 13 deletions(-) create mode 100644 quickshell/controlcenter/modules/Notifications.qml create mode 100644 quickshell/notifications/NotificationCard.qml create mode 100644 quickshell/notifications/NotificationPopups.qml create mode 100644 quickshell/services/NotificationService.qml create mode 100644 tests/notifications_runtime.py diff --git a/docs/architecture.md b/docs/architecture.md index 76c2c47..8cf4bf7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -123,7 +123,7 @@ confirmation before logout/reboot/shutdown and uses argv arrays with timeouts. The same modules are reused by detailed Settings pages. Wi-Fi credentials pass to NetworkManager's native API, not subprocess arguments or shell preferences. BlueZ -pairing uses the existing manager. No notification or pairing daemon is registered. +pairing uses the existing manager. No pairing daemon is registered. ## Phase 8 telemetry @@ -132,3 +132,17 @@ MetricsService owns a single demand-driven streaming Python collector. MetricsCa ## Phase 9 polish Theme owns contrast selection and reduced-motion intensity. Shared glass components add inexpensive highlights and reversible motion without per-panel blur effects. ScreenService validates captured output references. MetricsService owns bounded restart backoff. The optional compositor example and read-only doctor keep host integration separate from UI state. + +## Notifications + +`NotificationService` owns the one native `NotificationServer` (org.freedesktop.Notifications), +history (the server's tracked notifications), the banner queue and Do Not Disturb, which is +persisted as `notifications.doNotDisturb`. The server is loaded lazily while enabled. Only one +process can own the bus name: the system helper reports the owner, and while another daemon +(e.g. SwayNC) holds it the shell stays inactive, says so, and the DND tile controls SwayNC instead. + +`NotificationPopups` shows banners in a bar drawer like the OSD and yields its spot while the OSD +is up. Banners time out into history, pause while hovered, and are cleared when Control Center +opens. `controlcenter/modules/Notifications.qml` stacks history per app (macOS Notification +Center); `NotificationCard` is shared by both. Critical notifications stay until dismissed and +may break through DND. `tests/notifications_runtime.py` runs on a private session bus. diff --git a/quickshell/config/defaults.json b/quickshell/config/defaults.json index 163e87a..440d7c5 100644 --- a/quickshell/config/defaults.json +++ b/quickshell/config/defaults.json @@ -114,6 +114,15 @@ "step": 5, "animation": "slide" }, + "notifications": { + "enabled": true, + "doNotDisturb": false, + "position": "top-right", + "animation": "slide", + "timeout": 5000, + "maxPopups": 3, + "criticalInDnd": true + }, "media": { "showAlbumArt": true, "showProgress": true, @@ -173,6 +182,10 @@ { "id": "power", "enabled": true + }, + { + "id": "notifications", + "enabled": true } ] }, diff --git a/quickshell/controlcenter/ControlRegistry.qml b/quickshell/controlcenter/ControlRegistry.qml index 0e6e20b..956f016 100644 --- a/quickshell/controlcenter/ControlRegistry.qml +++ b/quickshell/controlcenter/ControlRegistry.qml @@ -39,6 +39,10 @@ Singleton { power: { title: "Power", source: Qt.resolvedUrl("modules/Power.qml") + }, + notifications: { + title: "Notifications", + source: Qt.resolvedUrl("modules/Notifications.qml") } }) } diff --git a/quickshell/controlcenter/modules/Dnd.qml b/quickshell/controlcenter/modules/Dnd.qml index dc7b199..0d53d0f 100644 --- a/quickshell/controlcenter/modules/Dnd.qml +++ b/quickshell/controlcenter/modules/Dnd.qml @@ -2,17 +2,19 @@ import QtQuick import ".." import "../../services" +// Built-in notifications keep DND in the shell; SwayNC is controlled over DBus. CCTile { readonly property var info: SystemService.state.dnd || ({ available: false }) + readonly property bool shellOwned: NotificationService.active objectName: "dndToggle" title: "Do Not Disturb" - detail: !info.available ? "No SwayNC running" : info.enabled ? "On" : "Off" + detail: shellOwned ? (NotificationService.dnd ? "On" : "Off") : !info.available ? (info.notice || "No notification server") : info.enabled ? "On" : "Off" glyph: "󰽥" fallback: "☾" // Shows acknowledged provider state; a failed request leaves it unchanged. - checked: !!info.enabled - enabled: !!info.available && !SystemService.acting - onClicked: SystemService.action("dnd", !info.enabled, false) + checked: shellOwned ? NotificationService.dnd : !!info.enabled + enabled: shellOwned || (!!info.available && !SystemService.acting) + onClicked: shellOwned ? NotificationService.setDnd(!NotificationService.dnd) : SystemService.action("dnd", !info.enabled, false) } diff --git a/quickshell/controlcenter/modules/Notifications.qml b/quickshell/controlcenter/modules/Notifications.qml new file mode 100644 index 0000000..b45ecef --- /dev/null +++ b/quickshell/controlcenter/modules/Notifications.qml @@ -0,0 +1,189 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell +import ".." +import "../../notifications" +import "../../services" +import "../../theme" + +// macOS-style Notification Center: one stack per app, newest first. A stack +// shows its latest notification with the rest peeking out underneath; clicking +// expands it, "Show Less" folds it back and × clears the app's notifications. +ColumnLayout { + id: root + objectName: "notificationCenter" + spacing: 8 + // Group key -> expanded. Reassigned so bindings update. + property var expanded: ({}) + property bool showAll: false + readonly property int groupLimit: 4 + readonly property var groups: NotificationService.groups + readonly property var shownGroups: showAll ? groups : groups.slice(0, groupLimit) + function setExpanded(key, on) { + const next = Object.assign({}, expanded); + next[key] = on; + expanded = next; + } + + component Pill: Rectangle { + id: pill + property string text + signal clicked + implicitWidth: label.implicitWidth + 18 + implicitHeight: 22 + radius: 11 + color: pillArea.containsMouse ? Theme.hover : Theme.surfaceVariant + border.width: 1 + border.color: Theme.hairline + Accessible.role: Accessible.Button + Accessible.name: text + Text { + id: label + anchors.centerIn: parent + text: pill.text + color: Theme.text + font.pixelSize: 11 + font.weight: Font.Medium + } + MouseArea { + id: pillArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: pill.clicked() + } + } + + RowLayout { + Layout.fillWidth: true + Layout.leftMargin: 4 + spacing: 6 + Text { + text: "Notifications" + color: Theme.text + font.pixelSize: 13 + font.weight: Font.DemiBold + Layout.fillWidth: true + } + Text { + visible: NotificationService.dnd + text: (Icons.available ? "󰽥 " : "") + "Do Not Disturb" + color: Theme.textSecondary + font.pixelSize: 11 + } + Pill { + objectName: "notificationsClearAll" + visible: NotificationService.count > 0 + text: "Clear All" + onClicked: { + NotificationService.clearAll(); + root.expanded = {}; + root.showAll = false; + } + } + } + + ControlCard { + visible: !NotificationService.active || NotificationService.count === 0 + Layout.fillWidth: true + heading: false + padding: 14 + Text { + objectName: "notificationsEmpty" + Layout.fillWidth: true + horizontalAlignment: Text.AlignHCenter + wrapMode: Text.Wrap + text: NotificationService.active ? "No Notifications" : NotificationService.notice || "Starting notifications…" + color: Theme.textSecondary + font.pixelSize: 12 + } + } + + Repeater { + model: ScriptModel { + values: root.shownGroups + } + ColumnLayout { + id: group + required property var modelData + readonly property var items: modelData.items + readonly property bool open: items.length > 1 && !!root.expanded[modelData.key] + Layout.fillWidth: true + spacing: 6 + // Expanded stack header. + RowLayout { + visible: group.open + Layout.fillWidth: true + Layout.leftMargin: 4 + spacing: 6 + Text { + text: group.modelData.name + color: Theme.text + font.pixelSize: 12 + font.weight: Font.DemiBold + elide: Text.ElideRight + Layout.fillWidth: true + } + Pill { + text: "Show Less" + onClicked: root.setExpanded(group.modelData.key, false) + } + Pill { + text: "×" + implicitWidth: 22 + Accessible.name: "Clear " + group.modelData.name + onClicked: NotificationService.dismissGroup(group.modelData.key) + } + } + // Collapsed: the newest card with up to two slivers beneath it. + Item { + visible: !group.open + Layout.fillWidth: true + implicitHeight: top.implicitHeight + Math.min(2, group.items.length - 1) * 6 + Repeater { + model: Math.min(2, group.items.length - 1) + Rectangle { + required property int index + x: parent.width * 0.04 * (index + 1) + width: parent.width - 2 * x + y: top.height + index * 6 - 1 + height: 7 + z: -1 - index + radius: 3.5 + color: Qt.alpha(Theme.tint, 0.22 - index * 0.06) + border.width: 1 + border.color: Theme.hairline + } + } + NotificationCard { + id: top + objectName: "notificationStack" + width: parent.width + notification: group.items[0] + bodyLines: 2 + stackKey: group.items.length > 1 ? group.modelData.key : "" + stackCount: group.items.length + onExpand: root.setExpanded(group.modelData.key, true) + } + } + Repeater { + model: ScriptModel { + values: group.open ? group.items : [] + } + NotificationCard { + required property var modelData + Layout.fillWidth: true + notification: modelData + } + } + } + } + + Pill { + visible: !root.showAll && root.groups.length > root.groupLimit + Layout.alignment: Qt.AlignHCenter + text: "Show " + (root.groups.length - root.groupLimit) + " more" + onClicked: root.showAll = true + } +} diff --git a/quickshell/helpers/system.py b/quickshell/helpers/system.py index d1bf744..1b1526d 100644 --- a/quickshell/helpers/system.py +++ b/quickshell/helpers/system.py @@ -57,9 +57,17 @@ def night(options): return {'available':True,'enabled':temp<6500,'temperature':temp,'provider':'wl-gammarelay'} def notifications(): - value=bus('user','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','GetDnd')[0] + # The shell keeps its own DND state; only SwayNC is controlled over DBus. + try:owner=bus('user','call','org.freedesktop.DBus','/org/freedesktop/DBus','org.freedesktop.DBus','GetConnectionUnixProcessID','s','org.freedesktop.Notifications')[0] + except ValueError:return {'available':False,'provider':'','notice':'No notification server is running'} + if owner==os.getppid():return {'available':True,'provider':'shell'} + try:value=bus('user','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','GetDnd')[0] + except ValueError: + try:name=Path(f'/proc/{owner}/comm').read_text().strip().lstrip('.').removesuffix('-wrapped') + except OSError:name='Another program' + return {'available':False,'provider':name,'notice':name+' handles notifications'} if type(value) is not bool:raise ValueError('SwayNC did not return a DND state') - return {'available':True,'enabled':value} + return {'available':True,'enabled':value,'provider':'swaync'} def profiles(): service='net.hadess.PowerProfiles';path='/net/hadess/PowerProfiles' @@ -111,7 +119,7 @@ def action(req): run(['busctl','--user','--auto-start=no','--timeout=3','set-property','rs.wl-gammarelay','/','rs.wl.gammarelay','Temperature','q',str(temperature)]) elif kind=='dnd': if type(value) is not bool:raise ValueError('DND expects a boolean') - notifications() + if notifications().get('provider')!='swaync':raise ValueError('No external Do Not Disturb provider') run(['busctl','--user','--auto-start=no','--timeout=3','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','SetDnd','b',str(value).lower()]) elif kind=='profile': if value not in profiles()['profiles']:raise ValueError('Unsupported power profile') diff --git a/quickshell/notifications/NotificationCard.qml b/quickshell/notifications/NotificationCard.qml new file mode 100644 index 0000000..cec89f9 --- /dev/null +++ b/quickshell/notifications/NotificationCard.qml @@ -0,0 +1,266 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import "../components" +import "../services" +import "../theme" + +// One notification: app icon, app and age, summary, body, image and action +// buttons. Clicking runs the default action; the corner button dismisses it. +// Shared by the popup drawer (unframed) and the Control Center (framed card). +Item { + id: root + required property var notification + property bool framed: true + // Body lines before eliding. + property int bodyLines: 3 + // A popup swipes away to the Control Center instead of being dismissed. + property bool swipeable: false + signal swiped + // Top card of a collapsed stack: a click expands it and the dismiss + // button clears the whole app group. + property string stackKey: "" + property int stackCount: 1 + signal expand + readonly property bool hovered: hover.hovered + readonly property var n: notification + readonly property bool critical: NotificationService.critical(n) + readonly property string icon: NotificationService.iconFor(n) + readonly property string image: NotificationService.imageFor(n) + readonly property var buttons: NotificationService.buttons(n) + implicitWidth: 360 + implicitHeight: layout.implicitHeight + 24 + Accessible.role: Accessible.Button + Accessible.name: n ? NotificationService.appLabel(n) + ": " + n.summary : "" + + HoverHandler { + id: hover + } + // Drag sideways to hide a popup into the Control Center. + property real swipe: 0 + DragHandler { + id: drag + enabled: root.swipeable + target: null + xAxis.enabled: true + yAxis.enabled: false + onTranslationChanged: root.swipe = Math.max(0, translation.x) + onActiveChanged: if (!active) { + if (root.swipe > root.width * 0.3) + root.swiped(); + else + root.swipe = 0; + } + } + Behavior on swipe { + enabled: !drag.active + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + + Item { + id: face + width: root.width + height: root.height + x: root.swipe + opacity: 1 - Math.min(1, root.swipe / root.width) + Rectangle { + anchors.fill: parent + visible: root.framed + radius: Math.max(12, Theme.radius * 0.75) + color: area.containsMouse ? Theme.hover : Theme.fill + border.width: 1 + border.color: root.critical ? Qt.alpha(Theme.urgent, 0.6) : Theme.hairline + } + Rectangle { + anchors.fill: parent + visible: !root.framed && area.containsMouse + radius: Math.max(10, Theme.radius * 0.6) + color: Theme.hover + } + MouseArea { + id: area + anchors.fill: parent + hoverEnabled: true + acceptedButtons: Qt.LeftButton | Qt.MiddleButton | Qt.RightButton + cursorShape: Qt.PointingHandCursor + onClicked: mouse => { + if (mouse.button === Qt.LeftButton && root.stackKey) + root.expand(); + else if (mouse.button === Qt.LeftButton) + NotificationService.activate(root.n); + else if (root.stackKey) + NotificationService.dismissGroup(root.stackKey); + else if (mouse.button === Qt.MiddleButton || !root.swipeable) + NotificationService.dismiss(root.n); + else + root.swiped(); + } + } + RowLayout { + id: layout + anchors { + left: parent.left + right: parent.right + top: parent.top + margins: 12 + } + spacing: 12 + Rectangle { + Layout.alignment: Qt.AlignTop + Layout.preferredWidth: 38 + Layout.preferredHeight: 38 + radius: 10 + color: appIcon.status === Image.Ready ? Theme.transparent : Theme.surfaceVariant + border.width: root.critical ? 1.5 : 0 + border.color: Theme.urgent + Text { + anchors.centerIn: parent + visible: appIcon.status !== Image.Ready + text: Icons.available ? "󰂚" : "!" + color: Theme.text + font.pixelSize: 18 + } + Image { + id: appIcon + anchors.fill: parent + anchors.margins: 2 + // Without an app icon the image (often an avatar) takes its place. + source: root.icon || root.image + sourceSize: Qt.size(76, 76) + fillMode: Image.PreserveAspectFit + asynchronous: true + smooth: true + mipmap: true + } + } + ColumnLayout { + Layout.fillWidth: true + Layout.alignment: Qt.AlignTop + spacing: 2 + RowLayout { + Layout.fillWidth: true + spacing: 6 + Text { + text: root.n ? NotificationService.appLabel(root.n) + (root.stackCount > 1 ? " · " + root.stackCount : "") : "" + color: Theme.textSecondary + font.pixelSize: 11 + font.weight: Font.Medium + elide: Text.ElideRight + Layout.fillWidth: true + } + // The age gives way to a dismiss button while hovered. + Item { + implicitWidth: Math.max(age.implicitWidth, 18) + implicitHeight: 16 + Text { + id: age + objectName: "notificationAge" + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + visible: !root.hovered + text: root.n ? NotificationService.since(root.n) : "" + color: Theme.textSecondary + font.pixelSize: 11 + } + Rectangle { + objectName: "notificationClose" + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + width: 18 + height: 18 + radius: 9 + visible: root.hovered + color: closeArea.containsMouse ? Theme.hover : Theme.surfaceVariant + border.width: 1 + border.color: Theme.hairline + Accessible.role: Accessible.Button + Accessible.name: root.stackKey ? "Clear notifications" : "Dismiss notification" + Text { + anchors.centerIn: parent + text: "×" + color: Theme.text + font.pixelSize: 12 + } + MouseArea { + id: closeArea + anchors.fill: parent + anchors.margins: -3 + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.stackKey ? NotificationService.dismissGroup(root.stackKey) : NotificationService.dismiss(root.n) + } + } + } + } + Text { + objectName: "notificationSummary" + text: root.n ? root.n.summary : "" + visible: text !== "" + color: root.critical ? Theme.urgent : Theme.text + font.pixelSize: 13 + font.weight: Font.DemiBold + textFormat: Text.PlainText + wrapMode: Text.Wrap + maximumLineCount: 2 + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: root.n ? root.n.body : "" + visible: text !== "" + color: Theme.textSecondary + linkColor: Theme.accentVivid + font.pixelSize: 12 + // Spec markup subset (b, i, u, a); StyledText never loads remote images. + textFormat: Text.StyledText + wrapMode: Text.Wrap + maximumLineCount: root.bodyLines + elide: Text.ElideRight + Layout.fillWidth: true + onLinkActivated: link => Qt.openUrlExternally(link) + HoverHandler { + enabled: parent.hoveredLink !== "" + cursorShape: Qt.PointingHandCursor + } + } + Flow { + visible: root.buttons.length > 0 + Layout.fillWidth: true + Layout.topMargin: 6 + spacing: 6 + Repeater { + model: root.buttons + GlassButton { + required property var modelData + implicitHeight: 28 + text: modelData.text + font.pixelSize: 11 + onClicked: NotificationService.invoke(root.n, modelData) + } + } + } + } + Rectangle { + visible: root.icon !== "" && root.image !== "" && thumb.status !== Image.Error + Layout.alignment: Qt.AlignTop + Layout.preferredWidth: 46 + Layout.preferredHeight: 46 + radius: 8 + color: Theme.surfaceVariant + clip: true + Image { + id: thumb + anchors.fill: parent + source: root.icon !== "" ? root.image : "" + sourceSize: Qt.size(92, 92) + fillMode: Image.PreserveAspectCrop + asynchronous: true + } + } + } + + } +} diff --git a/quickshell/notifications/NotificationPopups.qml b/quickshell/notifications/NotificationPopups.qml new file mode 100644 index 0000000..0247235 --- /dev/null +++ b/quickshell/notifications/NotificationPopups.qml @@ -0,0 +1,164 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import Quickshell.Wayland +import "../components" +import "../services" +import "../core" +import "../theme" + +// Notification banners in a glass drawer that drops out of the bar, styled +// like the OSD. Banners stack newest first; hovering pauses their timers, +// swiping or right-clicking hides one into the Control Center. +// qmllint disable uncreatable-type +PanelWindow { + id: root + readonly property var options: NotificationService.options + readonly property var items: NotificationService.popups + property var targetScreen: null + screen: ScreenService.current(targetScreen) + readonly property int screenWidth: screen ? screen.width : 1920 + // The OSD capsule takes this spot while it is up; banners wait behind it. + readonly property var osd: ShellState.osdWindow + readonly property bool yielding: !!osd && osd.shown && osd.options.position === options.position + readonly property bool shown: NotificationService.active && items.length > 0 && !yielding && !ShellState.controlCenterOpen + onItemsChanged: if (items.length > 0 && !drawer.shown) + targetScreen = ScreenService.active + // Control Center lists everything; banners would cover it. + Connections { + target: ShellState + function onControlCenterOpenChanged() { + if (ShellState.controlCenterOpen) + NotificationService.clearPopups(); + } + } + + anchors { + top: true + right: root.options.position === "top-right" + } + // Margins is present at runtime but unresolved in 0.3.1 qmltypes. + // qmllint disable unqualified unresolved-type + margins { + right: BarDrawers.margin + BarDrawers.radius + } + // qmllint enable unqualified unresolved-type + implicitWidth: Math.round(drawer.width) + implicitHeight: Math.round(BarDrawers.bottom + drawer.contentHeight) + mask: Region { + item: drawer.body + } + visible: shown || drawer.shown + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.namespace: "glassMxrph-notifications" + WlrLayershell.keyboardFocus: WlrKeyboardFocus.None + + BarDrawer { + id: drawer + objectName: "notificationSurface" + y: BarDrawers.bottom + open: root.shown + style: root.options.animation + contentWidth: 380 + // Keeps the last height while the drawer closes around its final banner. + property real lastHeight: 80 + readonly property real wanted: list.contentHeight + 12 + onWantedChanged: if (list.count > 0) + lastHeight = wanted + contentHeight: list.count > 0 ? wanted : lastHeight + Behavior on contentHeight { + enabled: drawer.settled + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + drawerId: "notifications" + screenName: root.screen ? root.screen.name : "" + screenX: root.options.position === "top-right" ? root.screenWidth - BarDrawers.margin - BarDrawers.radius - width : (root.screenWidth - width) / 2 + + ListView { + id: list + objectName: "notificationPopupList" + anchors.fill: parent + anchors.margins: 6 + interactive: false + spacing: 0 + model: ScriptModel { + values: root.items + } + add: Transition { + NumberAnimation { + property: "opacity" + from: 0 + to: 1 + duration: Theme.duration + } + } + remove: Transition { + NumberAnimation { + property: "opacity" + to: 0 + duration: Theme.duration / 2 + } + } + // Also finishes an add interrupted by a newer banner; otherwise the + // displaced delegate keeps its partial opacity. + displaced: Transition { + NumberAnimation { + property: "y" + duration: Theme.duration + easing.type: Easing.OutCubic + } + NumberAnimation { + property: "opacity" + to: 1 + duration: Theme.duration + } + } + delegate: Item { + id: banner + required property var modelData + required property int index + width: list.width + height: card.implicitHeight + Rectangle { + visible: banner.index > 0 + anchors.left: parent.left + anchors.right: parent.right + anchors.margins: 12 + height: 1 + color: Theme.hairline + } + NotificationCard { + id: card + objectName: "notificationPopup" + width: parent.width + notification: banner.modelData + framed: false + swipeable: true + onSwiped: NotificationService.hidePopup(banner.modelData) + } + // 0 (critical) stays until dismissed. Not read from the Timer's own + // interval: that is still the 1000 ms default when running first binds. + readonly property int lifetime: NotificationService.timeoutFor(modelData) + Timer { + id: life + interval: Math.max(1, banner.lifetime) + // Restarts from the full time after a hover, like macOS banners. + running: banner.lifetime > 0 && root.shown && !drawer.hovered + onTriggered: NotificationService.hidePopup(banner.modelData) + } + Connections { + target: NotificationService + function onPopupShown(n) { + if (n === banner.modelData && banner.lifetime > 0) + life.restart(); + } + } + } + } + } +} diff --git a/quickshell/services/ConfigLogic.js b/quickshell/services/ConfigLogic.js index 0ac32d9..f68a18a 100644 --- a/quickshell/services/ConfigLogic.js +++ b/quickshell/services/ConfigLogic.js @@ -85,6 +85,8 @@ function validate(c) { const dashTabs=new Set(); for(const t of dash.tabs) { if(!t || typeof t.id!=="string" || dashTabs.has(t.id) || typeof t.enabled!=="boolean")throw Error("Invalid dashboard tab"); dashTabs.add(t.id); } if(typeof c.osd.enabled!=="boolean" || !["slide","drop","fade","shrink"].includes(c.osd.animation) || !["top-right","top-center","bottom-center"].includes(c.osd.position) || !Number.isInteger(c.osd.timeout) || c.osd.timeout<500 || c.osd.timeout>5000 || !Number.isInteger(c.osd.step) || c.osd.step<1 || c.osd.step>20)throw Error("Invalid OSD preferences"); + const notes=c.notifications; + if(!notes || ["enabled","doNotDisturb","criticalInDnd"].some(k=>typeof notes[k]!=="boolean") || !["slide","drop","fade","shrink"].includes(notes.animation) || !["top-right","top-center"].includes(notes.position) || !Number.isInteger(notes.timeout) || notes.timeout<1000 || notes.timeout>30000 || !Number.isInteger(notes.maxPopups) || notes.maxPopups<1 || notes.maxPopups>6)throw Error("Invalid notification preferences"); if(c.controlCenter.version !== 1 || !Number.isFinite(c.controlCenter.width) || c.controlCenter.width < 320 || c.controlCenter.width > 600 || !Array.isArray(c.controlCenter.modules))throw Error("Invalid Control Center configuration"); const controlIds=new Set(); for(const m of c.controlCenter.modules) { if(!m || typeof m.id!=="string" || controlIds.has(m.id) || typeof m.enabled!=="boolean")throw Error("Invalid Control Center module"); controlIds.add(m.id); } diff --git a/quickshell/services/NotificationService.qml b/quickshell/services/NotificationService.qml new file mode 100644 index 0000000..933c78a --- /dev/null +++ b/quickshell/services/NotificationService.qml @@ -0,0 +1,281 @@ +pragma Singleton +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import Quickshell.Io +import Quickshell.Services.Notifications + +// The shell's freedesktop notification server. It owns history (the server's +// tracked notifications), the popup queue and Do Not Disturb. Only one process +// can own org.freedesktop.Notifications: while another daemon (e.g. SwayNC) +// holds the name, `active` stays false and the UI says so. +Singleton { + id: root + readonly property var options: ConfigService.ready ? ConfigService.data.notifications : ({ + enabled: false, + doNotDisturb: false, + position: "top-right", + animation: "slide", + timeout: 5000, + maxPopups: 3, + criticalInDnd: true + }) + readonly property bool enabled: ConfigService.ready && options.enabled + readonly property bool dnd: enabled && options.doNotDisturb + readonly property var server: loader.item + // Who owns the notification bus name: "shell", "swaync", a process name, or "" (unknown/none). + // A live Control Center/Settings status poll is fresher than the startup check. + property string checkedOwner: "" + readonly property string owner: SystemService.state.dnd && SystemService.state.dnd.provider !== undefined ? SystemService.state.dnd.provider : checkedOwner + readonly property bool active: enabled && owner === "shell" + readonly property string notice: !enabled ? "Built-in notifications are turned off" : owner === "shell" || owner === "" ? "" : owner + " is handling notifications. Stop it to use glassMxrph notifications." + + // Newest first. + readonly property var list: server ? server.trackedNotifications.values.slice().reverse() : [] + readonly property int count: list.length + // Notifications currently shown as popups, newest first. + property var popups: [] + // id -> arrival time (ms); reassigned so bindings update. + property var times: ({}) + property real now: Date.now() + // Ids whose change signals are connected (not bound; mutated in place). + property var connected: ({}) + + // Per-app stacks for the Control Center, newest group first. + readonly property var groups: { + const order = [], byKey = {}; + for (const n of list) { + const key = groupKey(n); + if (!byKey[key]) { + byKey[key] = { + key: key, + name: appLabel(n), + items: [] + }; + order.push(byKey[key]); + } + byKey[key].items.push(n); + } + return order; + } + + function groupKey(n) { + return (n.desktopEntry || n.appName || "notifications").toLowerCase(); + } + function entryFor(n) { + return (n.desktopEntry ? ApplicationsService.byId(n.desktopEntry) : null) || (n.appName ? ApplicationsService.byId(n.appName) : null); + } + function appLabel(n) { + const entry = n.appName ? null : entryFor(n); + return n.appName || (entry ? entry.name : "") || "Notification"; + } + // App icon: the notification's own icon, else its desktop entry's. + function iconFor(n) { + if (!n) + return ""; + const icon = n.appIcon || ""; + if (icon.startsWith("/") || icon.startsWith("file:") || icon.startsWith("image:")) + return icon.startsWith("/") ? "file://" + icon : icon; + return (icon ? Quickshell.iconPath(icon, true) : "") || ApplicationsService.icon(entryFor(n)); + } + function imageFor(n) { + const image = n ? n.image || "" : ""; + return image.startsWith("/") ? "file://" + image : image; + } + function critical(n) { + return !!n && n.urgency === NotificationUrgency.Critical; + } + // Popup lifetime in ms; 0 keeps it until dismissed. + function timeoutFor(n) { + if (critical(n)) + return 0; + return n.expireTimeout > 0 ? Math.round(Math.max(1, n.expireTimeout) * 1000) : options.timeout; + } + function since(n) { + const at = n ? times[n.id] : undefined; + if (at === undefined) + return ""; + const minutes = Math.floor((now - at) / 60000); + if (minutes < 1) + return "now"; + if (minutes < 60) + return minutes + "m ago"; + const hours = Math.floor(minutes / 60); + if (hours < 24) + return hours + "h ago"; + return Qt.formatDate(new Date(at), "d MMM"); + } + // The default action is the notification body; the rest become buttons. + function defaultAction(n) { + return n ? n.actions.find(a => a.identifier === "default") || null : null; + } + function buttons(n) { + return n ? n.actions.filter(a => a.identifier !== "default" && a.text) : []; + } + + function setDnd(on) { + return ConfigService.setValue("notifications.doNotDisturb", !!on); + } + // Leave the popup stack; the notification stays in the Control Center. + function hidePopup(n) { + if (!popups.includes(n)) + return; + popups = popups.filter(p => p !== n); + if (n.transient) + n.expire(); + } + // Clicking a notification runs its default action; it always leaves view. + function activate(n) { + const action = defaultAction(n); + if (action) + action.invoke(); + if (!action || !n.resident) + n.dismiss(); + } + function invoke(n, action) { + action.invoke(); + if (!n.resident) + n.dismiss(); + } + function dismiss(n) { + n.dismiss(); + } + function dismissGroup(key) { + for (const n of list.filter(n => groupKey(n) === key)) + n.dismiss(); + } + function clearAll() { + for (const n of list) + n.dismiss(); + popups = []; + } + function clearPopups() { + for (const n of popups.slice()) + hidePopup(n); + } + + function forget(n) { + delete connected[n.id]; + popups = popups.filter(p => p !== n); + const next = Object.assign({}, times); + delete next[n.id]; + times = next; + } + function show(n) { + // Do Not Disturb keeps everything in history; critical alerts may break through. + if (dnd && !(critical(n) && options.criticalInDnd)) { + if (n.transient) + n.expire(); + return; + } + const rest = popups.filter(p => p !== n); + // Overflow leaves the oldest popups in history rather than queueing them. + popups = [n].concat(rest).slice(0, options.maxPopups); + for (const p of rest.slice(options.maxPopups - 1)) + if (p.transient) + p.expire(); + popupShown(n); + } + // Restarts the popup timer of a replaced notification. + signal popupShown(var notification) + + function receive(n) { + n.tracked = true; + const next = Object.assign({}, times); + next[n.id] = Date.now(); + times = next; + now = Date.now(); + if (!connected[n.id]) { + connected[n.id] = true; + n.closed.connect(() => root.forget(n)); + // In-place replacements (progress, volume scripts) pop up again. + const again = () => { + if (n.tracked) + root.show(n); + }; + n.summaryChanged.connect(again); + n.bodyChanged.connect(again); + } + show(n); + } + + LazyLoader { + id: loader + active: root.enabled + component: NotificationServer { + keepOnReload: true + persistenceSupported: true + bodySupported: true + bodyMarkupSupported: true + bodyHyperlinksSupported: true + actionsSupported: true + imageSupported: true + onNotification: n => root.receive(n) + } + } + onEnabledChanged: if (!enabled) + popups = [] + // Popups follow DND turning on. + onDndChanged: if (dnd) + popups = popups.filter(n => critical(n) && options.criticalInDnd) + + Timer { + interval: 30000 + repeat: true + running: root.count > 0 + onTriggered: root.now = Date.now() + } + + // One-shot ownership check after the server registers; Control Center and + // Settings polls refresh it through SystemService. + ProviderJob { + id: check + helper: "helpers/system.py" + onFinished: (request, result) => { + const dnd = result.ok && result.state ? result.state.dnd : null; + root.checkedOwner = dnd && dnd.provider ? dnd.provider : ""; + } + } + Timer { + running: root.enabled && ConfigService.ready + interval: 1500 + onTriggered: check.start({ + op: "status", + features: ["dnd"], + options: ConfigService.data.system + }) + } + + IpcHandler { + target: "notifications" + function toggleDnd(): bool { + root.setDnd(!root.dnd); + return !root.dnd; + } + function setDnd(on: bool): bool { + return root.setDnd(on); + } + // Clears the whole history. + function clear(): void { + root.clearAll(); + } + // Hides the visible popups; they stay in the Control Center. + function dismiss(): void { + root.clearPopups(); + } + function status(): string { + return JSON.stringify({ + enabled: root.enabled, + active: root.active, + owner: root.owner, + dnd: root.dnd, + count: root.count, + popups: root.popups.length, + groups: root.groups.map(g => ({ + app: g.name, + count: g.items.length + })) + }); + } + } +} diff --git a/quickshell/services/qmldir b/quickshell/services/qmldir index 3d1337c..7ed596c 100644 --- a/quickshell/services/qmldir +++ b/quickshell/services/qmldir @@ -16,3 +16,4 @@ singleton MetricsService 1.0 MetricsService.qml singleton GlassService 1.0 GlassService.qml singleton EasyEffectsService 1.0 EasyEffectsService.qml singleton PluginService 1.0 PluginService.qml +singleton NotificationService 1.0 NotificationService.qml diff --git a/quickshell/settings/pages/Notifications.qml b/quickshell/settings/pages/Notifications.qml index de8e82a..665acfe 100644 --- a/quickshell/settings/pages/Notifications.qml +++ b/quickshell/settings/pages/Notifications.qml @@ -1,8 +1,11 @@ import QtQuick import QtQuick.Layouts +import Quickshell import "../controls" +import "../../components" import "../../controlcenter/modules" as Modules import "../../services" +import "../../theme" SettingsPage { Modules.Dnd { @@ -10,6 +13,80 @@ SettingsPage { } SettingNote { warning: true - text: SystemService.error + text: NotificationService.enabled ? NotificationService.notice : "" + } + SettingsSection { + title: "Notifications" + description: "glassMxrph shows banners from the bar and keeps them in Control Center. Only one notification server can run; stop SwayNC, mako or dunst to use it." + PreferenceToggle { + label: "Built-in notifications" + description: "Takes effect when no other notification server is running" + icon: "󰂚" + setting: "notifications.enabled" + } + PreferenceToggle { + label: "Critical alerts during Do Not Disturb" + description: "Urgent notifications still show a banner" + icon: "󰀦" + setting: "notifications.criticalInDnd" + } + } + SettingsSection { + title: "Banners" + PreferenceChoice { + label: "Position" + icon: "󰹑" + setting: "notifications.position" + choices: ["top-right", "top-center"] + } + PreferenceChoice { + label: "Animation" + description: "Slide out of the bar, drop down, fade, or shrink to nothing" + icon: "󰕮" + setting: "notifications.animation" + choices: ["slide", "drop", "fade", "shrink"] + } + PreferenceSlider { + label: "Duration" + description: "Unless the app sets its own; critical alerts stay until dismissed" + icon: "󰔟" + setting: "notifications.timeout" + from: 1000 + to: 30000 + step: 500 + unit: " ms" + } + PreferenceSlider { + label: "Banners at once" + description: "Older banners move to Control Center" + icon: "󰁝" + setting: "notifications.maxPopups" + from: 1 + to: 6 + step: 1 + } + SettingRow { + title: "Test" + icon: "󰈈" + GlassButton { + objectName: "notificationTest" + text: "Send test notification" + enabled: NotificationService.active + onClicked: Quickshell.execDetached(["notify-send", "-a", "glassMxrph", "-i", "preferences-desktop-notification", "Notifications are working", "This is how banners from your apps will look."]) + } + } + } + SettingsSection { + title: "Keybinds" + padded: true + Text { + Layout.fillWidth: true + wrapMode: Text.Wrap + color: Theme.text + font.family: "monospace" + font.pixelSize: 11 + textFormat: Text.PlainText + text: "bind = $mod, M, exec, glassmxrph controlcenter\nbind = $mod SHIFT, N, exec, glassmxrph notifications dismiss\nbind = $mod CTRL, N, exec, glassmxrph notifications dnd" + } } } diff --git a/quickshell/shell.qml b/quickshell/shell.qml index 4f0f667..7588b5c 100644 --- a/quickshell/shell.qml +++ b/quickshell/shell.qml @@ -16,6 +16,7 @@ import "wallpaper" import "controlcenter" import "dashboard" import "osd" +import "notifications" import "lock" import "plugins" @@ -37,6 +38,7 @@ ShellRoot { Dashboard {} PluginHost {} Osd {} + NotificationPopups {} Lock {} Settings {} Launcher {} diff --git a/scripts/glassmxrph b/scripts/glassmxrph index 7b8de58..fe6659c 100755 --- a/scripts/glassmxrph +++ b/scripts/glassmxrph @@ -58,8 +58,14 @@ case "${1:-run}" in fi exec quickshell ipc --path "$project_dir/quickshell" call osd "$action" ;; + notifications) + # glassmxrph notifications [dismiss|clear|dnd|status] + action=${2:-status} + [ "$action" = dnd ] && action=toggleDnd + exec quickshell ipc --path "$project_dir/quickshell" call notifications "$action" + ;; settings|close|status) exec quickshell ipc --path "$project_dir/quickshell" call shell "$1" ;; - *) echo 'Usage: glassmxrph [run|wallpaper|launcher|dashboard [TAB]|plugin ACTION|controlcenter|lock|widgets|osd ACTION|settings|close|status|doctor]' >&2; exit 2 ;; + *) echo 'Usage: glassmxrph [run|wallpaper|launcher|dashboard [TAB]|plugin ACTION|controlcenter|lock|widgets|osd ACTION|notifications ACTION|settings|close|status|doctor]' >&2; exit 2 ;; esac diff --git a/tests/config.test.cjs b/tests/config.test.cjs index 78d766c..5859ad9 100644 --- a/tests/config.test.cjs +++ b/tests/config.test.cjs @@ -25,6 +25,8 @@ assert.deepEqual(loaded.desktopWidgets.items,[]); assert.equal(loaded.lock.backdrop,'wallpaper');assert.equal(loaded.lock.pamService,'');assert.equal(api.update(loaded,'lock.pamService','hyprlock').lock.pamService,'hyprlock'); for(const [k,v] of [['lock.backdrop','video'],['lock.pamService','../etc/shadow'],['lock.glass','yes']])assert.throws(()=>api.update(loaded,k,v),/lock screen/);assert.equal(api.update(loaded,'desktopWidgets.items',[widget,Object.assign({},widget,{id:'w-2',type:'future'})]).desktopWidgets.items.length,2); for(const bad of [[widget,widget],[Object.assign({},widget,{w:10})],[Object.assign({},widget,{opacity:2})],[Object.assign({},widget,{id:'Bad id'})],[Object.assign({},widget,{options:[]})]])assert.throws(()=>api.update(loaded,'desktopWidgets.items',bad),/desktop widget/);assert.equal(api.update(loaded, 'bar.workspaces.style', 'pacman').bar.workspaces.style, 'pacman');assert.throws(() => api.update(loaded, 'bar.workspaces.style', 'emoji'), /bar module options/);assert.throws(() => api.update(loaded, 'osd.position', 'left'), /OSD/);assert.throws(() => api.update(loaded, 'osd.timeout', 50), /OSD/);assert.throws(() => api.update(loaded, 'appearance.glassTint', 'grey'), /Glass tint/); +assert.equal(loaded.notifications.enabled, true);assert.equal(loaded.notifications.doNotDisturb, false);assert.equal(api.update(loaded, 'notifications.doNotDisturb', true).notifications.doNotDisturb, true); +for(const [k,v] of [['notifications.position','bottom-center'],['notifications.timeout',200],['notifications.maxPopups',0],['notifications.doNotDisturb','yes']])assert.throws(()=>api.update(loaded,k,v),/notification/); assert.throws(() => api.update(loaded, '__proto__.polluted', true)); console.log('Configuration preservation, validation and update tests passed.'); diff --git a/tests/notifications_runtime.py b/tests/notifications_runtime.py new file mode 100644 index 0000000..e717209 --- /dev/null +++ b/tests/notifications_runtime.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Real Wayland notification test on a private session bus (the user's daemon is untouched). +Run inside one: dbus-run-session -- python3 tests/notifications_runtime.py [screenshot-dir]""" +import json,os,subprocess,sys,tempfile,time +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call'] +SHOTS=Path(sys.argv[1]) if len(sys.argv)>1 else None +def ipc(target,method,*args): + r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True) + out=r.stdout.strip() + if r.returncode or not out:return None + try:return json.loads(out) + except ValueError:return out +def status():return ipc('notifications','status') or {} +def wait(check,label,timeout=15): + end=time.monotonic()+timeout + while time.monotonic()noon? The usual place.') + wait(lambda:status()['count']==1 and status()['popups']==1,'banner shown') + shot('1-banner') + notify('-a','Chat','Ada','Did you see the build?') + notify('-a','Chat','Grace','Ship it 🚀') + notify('-a','Chat','Linus','One more thing…') + notify('-u','critical','-a','Battery','Battery low','5% remaining') + wait(lambda:status()['count']==5,'history keeps everything') + wait(lambda:status()['popups']==3,'banner stack capped at maxPopups') + shot('2-stack') + # Non-critical banners time out into history; the critical one stays. + wait(lambda:status()['popups']==1,'banners expire',timeout=10) + assert status()['count']==5 + groups={g['app']:g['count'] for g in status()['groups']} + assert groups=={'Mail':1,'Chat':3,'Battery':1},groups + ipc('controlcenter','open') + wait(lambda:ipc('controlcenter','status')['opened'],'control center opens') + wait(lambda:status()['popups']==0,'opening Control Center clears banners') + shot('3-controlcenter') + ipc('controlcenter','close') + assert ipc('notifications','setDnd','true') + wait(lambda:status()['dnd'],'dnd on') + notify('-a','Mail','Quiet','Should not pop up') + wait(lambda:status()['count']==6,'dnd still records') + time.sleep(.5);assert status()['popups']==0,'dnd suppresses banners' + notify('-u','critical','-a','Alarm','Wake up','Critical breaks through') + wait(lambda:status()['popups']==1,'critical alerts break through dnd') + ipc('notifications','setDnd','false');ipc('notifications','dismiss') + wait(lambda:status()['popups']==0 and status()['count']==7,'dismiss hides banners but keeps history') + ipc('notifications','clear') + wait(lambda:status()['count']==0,'clear empties history') + wait(lambda:json.loads(cfg.read_text())['notifications']['doNotDisturb'] is False,'dnd persisted') + print('Notification server, banners, stacking, expiry, DND, Control Center grouping and clearing passed.') + finally: + shell.terminate() + try:shell.wait(5) + except subprocess.TimeoutExpired:shell.kill() diff --git a/tests/system_providers_test.py b/tests/system_providers_test.py index 447fdf1..3b99eee 100644 --- a/tests/system_providers_test.py +++ b/tests/system_providers_test.py @@ -40,13 +40,24 @@ class Providers(unittest.TestCase): with self.assertRaises(ValueError):system.action({'options':OPTIONS,'action':'power','value':'suspend'}) run.assert_not_called() def test_dnd_never_activates_notification_daemon(self): - with patch.object(system,'run',return_value='{"type":"b","data":[true]}') as run: - self.assertTrue(system.notifications()['enabled']) + with patch.object(system,'run',side_effect=['{"type":"u","data":[1]}','{"type":"b","data":[true]}']) as run: + state=system.notifications() + self.assertTrue(state['enabled']);self.assertEqual(state['provider'],'swaync') args=run.call_args.args[0] self.assertIn('--auto-start=no',args);self.assertEqual(args[-1],'GetDnd') - with patch.object(system,'notifications',return_value={'available':True}),patch.object(system,'snapshot',return_value={}),patch.object(system,'run') as run: + with patch.object(system,'notifications',return_value={'available':True,'provider':'swaync'}),patch.object(system,'snapshot',return_value={}),patch.object(system,'run') as run: system.action({'options':OPTIONS,'action':'dnd','value':False}) self.assertIn('--auto-start=no',run.call_args.args[0]);self.assertEqual(run.call_args.args[0][-3:],['SetDnd','b','false']) + def test_shell_owned_notifications_keep_dnd_in_the_shell(self): + with patch.object(system,'run',return_value='{"type":"u","data":[%d]}'%system.os.getppid()) as run: + self.assertEqual(system.notifications(),{'available':True,'provider':'shell'}) + self.assertEqual(run.call_count,1) + with patch.object(system,'notifications',return_value={'available':True,'provider':'shell'}),patch.object(system,'run') as run: + with self.assertRaises(ValueError):system.action({'options':OPTIONS,'action':'dnd','value':True}) + run.assert_not_called() + def test_missing_notification_server_is_reported(self): + with patch.object(system,'run',side_effect=ValueError('NameHasNoOwner')): + self.assertFalse(system.notifications()['available']) def test_cli_errors_are_json(self): p=subprocess.run([sys.executable,str(ROOT/'quickshell/helpers/system.py'),'{"op":"unknown"}'],capture_output=True,text=True) self.assertFalse(json.loads(p.stdout)['ok']);self.assertEqual(p.returncode,1);self.assertEqual(p.stderr,'')