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 <noreply@anthropic.com>
This commit is contained in:
mxandClaude Opus 5.5 committed 2026-10-15 14:47:40 +02:00
1 parent d7f0498ba0
commit 395de70b26
17 files changed
+1132 -13

No files matched your search

+13
View File
@@ -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
}
]
},
@@ -39,6 +39,10 @@ Singleton {
power: {
title: "Power",
source: Qt.resolvedUrl("modules/Power.qml")
},
notifications: {
title: "Notifications",
source: Qt.resolvedUrl("modules/Notifications.qml")
}
})
}
+6 -4
View File
@@ -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)
}
@@ -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
}
}
+11 -3
View File
@@ -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')
@@ -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
}
}
}
}
}
@@ -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();
}
}
}
}
}
}
+2
View File
@@ -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); }
+281
View File
@@ -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
}))
});
}
}
}
+1
View File
@@ -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
+78 -1
View File
@@ -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"
}
}
}
+2
View File
@@ -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 {}