File indexing completed on 2024-04-28 05:36:51

0001 /*
0002  * SPDX-FileCopyrightText: 2020 Kai Uwe Broulik <kde@broulik.de>
0003  *
0004  * SPDX-License-Identifier: LGPL-2.0-or-later
0005  */
0006 
0007 #include "notificationinhibition.h"
0008 #include "notificationinhibition_debug.h"
0009 
0010 #include <QDBusConnection>
0011 #include <QDBusMessage>
0012 #include <QDBusPendingCall>
0013 #include <QDBusPendingCallWatcher>
0014 #include <QDBusPendingReply>
0015 #include <QPointer>
0016 
0017 static const auto s_notificationService = QStringLiteral("org.freedesktop.Notifications");
0018 static const auto s_notificationPath = QStringLiteral("/org/freedesktop/Notifications");
0019 static const auto s_notificationInterface = QStringLiteral("org.freedesktop.Notifications");
0020 
0021 NotificationInhibition::NotificationInhibition(const QString &appId, const QString &reason, QObject *parent)
0022     : QObject(parent)
0023 {
0024     QDBusMessage msg = QDBusMessage::createMethodCall(s_notificationService, s_notificationPath, s_notificationInterface, QStringLiteral("Inhibit"));
0025     msg.setArguments({appId, reason, QVariantMap()});
0026 
0027     QPointer<NotificationInhibition> guardedThis(this);
0028 
0029     QDBusPendingCall pendingCall = QDBusConnection::sessionBus().asyncCall(msg);
0030     QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pendingCall);
0031     connect(watcher, &QDBusPendingCallWatcher::finished, [guardedThis, appId, reason](QDBusPendingCallWatcher *watcher) {
0032         QDBusPendingReply<uint> reply = *watcher;
0033         watcher->deleteLater();
0034 
0035         if (reply.isError()) {
0036             qCDebug(XdgDesktopPortalKdeNotificationInhibition) << "Failed to inhibit: " << reply.error().message();
0037             return;
0038         }
0039 
0040         const auto cookie = reply.value();
0041 
0042         // In case the inhibition was revoked again before the async DBus reply arrived
0043         if (guardedThis) {
0044             qCDebug(XdgDesktopPortalKdeNotificationInhibition) << "Inhibiting notifications for" << appId << "with reason" << reason << "and cookie" << cookie;
0045             guardedThis->m_cookie = cookie;
0046         } else {
0047             uninhibit(cookie);
0048         }
0049     });
0050 }
0051 
0052 NotificationInhibition::~NotificationInhibition()
0053 {
0054     if (m_cookie) {
0055         uninhibit(m_cookie);
0056     }
0057 }
0058 
0059 void NotificationInhibition::uninhibit(uint cookie)
0060 {
0061     qCDebug(XdgDesktopPortalKdeNotificationInhibition) << "Removing inhibition with cookie" << cookie;
0062     QDBusMessage msg = QDBusMessage::createMethodCall(s_notificationService, s_notificationPath, s_notificationInterface, QStringLiteral("UnInhibit"));
0063     msg.setArguments({cookie});
0064     QDBusConnection::sessionBus().call(msg, QDBus::NoBlock);
0065 }