Debian Codegraph @

misc/dbusnotification.cpp

raw symbols SCIP
1 #include "./dbusnotification.h"
2 #include "notificationsinterface.h"
3
4 #include <QCoreApplication>
5 #include <QDBusConnection>
6 #include <QDBusPendingReply>
7 #include <QImage>
8 #include <QMutex>
9 #include <QMutexLocker>
10
11 #include <limits>
12 #include <map>
13
14 using namespace std;
15
16 namespace QtUtilities {
17
18 /*!
19 * \class DBusNotification
20 * \brief The DBusNotification class emits D-Bus notifications.
21 *
22 * D-Bus notifications are only available if the library has been compiled with
23 * support for it by specifying CMake option `DBUS_NOTIFICATIONS`. If support is
24 * available, the macro `QT_UTILITIES_SUPPORT_DBUS_NOTIFICATIONS` is defined.
25 *
26 * **Usage**
27 *
28 * First create a new instance. The constructor allows to set basic parameters.
29 * To set more parameters, use setter methods. Call show() to actually show the
30 * notification. This method can also be used to update the currently shown notification
31 * (it will not be updated automatically by just using the setter methods).
32 *
33 * Instances of this class share static data. So do not call the member functions
34 * from different threads without proper synchronization - even if using different
35 * instances. The destructor is safe to call, though.
36 *
37 * \sa https://developer.gnome.org/notification-spec
38 */
39
40 /// \cond
41 using IDType = uint;
42 static QMutex pendingNotificationsMutex;
43 static std::map<IDType, DBusNotification *> pendingNotifications;
44 OrgFreedesktopNotificationsInterface *DBusNotification::s_dbusInterface = nullptr;
45 constexpr auto initialId = std::numeric_limits<IDType>::min();
46 constexpr auto pendingId = std::numeric_limits<IDType>::max();
47 constexpr auto pendingId2 = pendingId - 1;
48 /// \endcond
49
50 /*!
51 * \brief The SwappedImage struct represents RGB-interved version of the image specified on construction.
52 */
53 struct SwappedImage : public QImage {
54 SwappedImage(const QImage &image);
55 };
56
57 inline SwappedImage::SwappedImage(const QImage &image)
58 : QImage(image.rgbSwapped())
59 {
60 }
61
62 /*!
63 * \brief The NotificationImage struct is a raw data image format.
64 *
65 * It describes the width, height, rowstride, has alpha, bits per sample, channels and image data respectively.
66 */
67 struct NotificationImage : public QDBusArgument {
68 NotificationImage();
69 NotificationImage(SwappedImage image);
70 QImage toQImage() const;
71 QVariant toDBusArgument() const;
72 static NotificationImage fromDBusArgument(const QVariant &variant);
73
74 qint32 width;
75 qint32 height;
76 qint32 rowstride;
77 bool hasAlpha;
78 qint32 channels;
79 qint32 bitsPerSample;
80 QByteArray data;
81 bool isValid;
82
83 private:
84 NotificationImage(const QImage &image);
85 };
86
87 QDBusArgument &operator<<(QDBusArgument &argument, const NotificationImage &img)
88 {
89 argument.beginStructure();
90 argument << img.width << img.height << img.rowstride << img.hasAlpha << img.bitsPerSample << img.channels << img.data;
91 argument.endStructure();
92 return argument;
93 }
94
95 const QDBusArgument &operator>>(const QDBusArgument &argument, NotificationImage &img)
96 {
97 argument.beginStructure();
98 argument >> img.width >> img.height >> img.rowstride >> img.hasAlpha >> img.bitsPerSample >> img.channels >> img.data;
99 argument.endStructure();
100 return argument;
101 }
102
103 inline NotificationImage::NotificationImage()
104 : isValid(false)
105 {
106 }
107
108 inline NotificationImage::NotificationImage(SwappedImage image)
109 : NotificationImage(static_cast<const QImage &>(image))
110 {
111 }
112
113 inline NotificationImage::NotificationImage(const QImage &image)
114 : width(image.width())
115 , height(image.height())
116 , rowstride(static_cast<qint32>(image.bytesPerLine()))
117 , hasAlpha(image.hasAlphaChannel())
118 , channels(image.isGrayscale() ? 1
119 : hasAlpha ? 4
120 : 3)
121 , bitsPerSample(image.depth() / channels)
122 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
123 , data(reinterpret_cast<const char *>(image.bits()), static_cast<int>(image.sizeInBytes()))
124 #else
125 , data(reinterpret_cast<const char *>(image.bits()), image.byteCount())
126 #endif
127 , isValid(!image.isNull())
128 {
129 if (isValid) {
130 // populate QDBusArgument structure
131 // note: Just use the operator overload which is required for qDBusMarshallHelper().
132 *this << *this;
133 }
134 }
135
136 inline QImage NotificationImage::toQImage() const
137 {
138 return isValid ? QImage(reinterpret_cast<const uchar *>(data.constData()), width, height, hasAlpha ? QImage::Format_ARGB32 : QImage::Format_RGB32)
139 .rgbSwapped()
140 : QImage();
141 }
142
143 inline QVariant NotificationImage::toDBusArgument() const
144 {
145 return QVariant::fromValue(*this);
146 }
147
148 inline NotificationImage NotificationImage::fromDBusArgument(const QVariant &variant)
149 {
150 return variant.canConvert<NotificationImage>() ? variant.value<NotificationImage>() : NotificationImage();
151 }
152
153 } // namespace QtUtilities
154
155 Q_DECLARE_METATYPE(QtUtilities::NotificationImage);
156
157 namespace QtUtilities {
158
159 /*!
160 * \brief Creates a new notification (which is *not* shown instantly).
161 */
162 DBusNotification::DBusNotification(const QString &title, NotificationIcon icon, int timeout, QObject *parent)
163 : QObject(parent)
164 , m_id(initialId)
165 , m_watcher(nullptr)
166 , m_title(title)
167 , m_timeout(timeout)
168 {
169 initInterface();
170 setIcon(icon);
171 }
172
173 /*!
174 * \brief Creates a new notification (which is *not* shown instantly).
175 */
176 DBusNotification::DBusNotification(const QString &title, const QString &icon, int timeout, QObject *parent)
177 : QObject(parent)
178 , m_id(initialId)
179 , m_watcher(nullptr)
180 , m_title(title)
181 , m_icon(icon)
182 , m_timeout(timeout)
183 {
184 initInterface();
185 }
186
187 /*!
188 * \brief Initializes the static interface object if not done yet.
189 */
190 void DBusNotification::initInterface()
191 {
192 if (!s_dbusInterface) {
193 qDBusRegisterMetaType<NotificationImage>();
194 s_dbusInterface = new OrgFreedesktopNotificationsInterface(
195 QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("/org/freedesktop/Notifications"), QDBusConnection::sessionBus());
196 connect(s_dbusInterface, &OrgFreedesktopNotificationsInterface::ActionInvoked, &DBusNotification::handleActionInvoked);
197 connect(s_dbusInterface, &OrgFreedesktopNotificationsInterface::NotificationClosed, &DBusNotification::handleNotificationClosed);
198 }
199 }
200
201 /*!
202 * \brief Closes the notification if still shown and delete the object.
203 */
204 DBusNotification::~DBusNotification()
205 {
206 {
207 QMutexLocker lock(&pendingNotificationsMutex);
208 auto i = pendingNotifications.find(m_id);
209 if (i != pendingNotifications.end()) {
210 pendingNotifications.erase(i);
211 }
212 }
213 hide();
214 }
215
216 /*!
217 * \brief Returns whether the notification D-Bus daemon is running.
218 */
219 bool DBusNotification::isAvailable()
220 {
221 initInterface();
222 return s_dbusInterface->isValid();
223 }
224
225 /*!
226 * \brief Sets the icon to one of the pre-defined notification icons.
227 */
228 void DBusNotification::setIcon(NotificationIcon icon)
229 {
230 switch (icon) {
231 case NotificationIcon::Information:
232 m_icon = QStringLiteral("dialog-information");
233 break;
234 case NotificationIcon::Warning:
235 m_icon = QStringLiteral("dialog-warning");
236 break;
237 case NotificationIcon::Critical:
238 m_icon = QStringLiteral("dialog-critical");
239 break;
240 default:;
241 }
242 }
243
244 /*!
245 * \brief Returns the image.
246 * \sa setImage() for more details
247 */
248 const QImage DBusNotification::image() const
249 {
250 return NotificationImage::fromDBusArgument(hint(QStringLiteral("image-data"), QStringLiteral("image_data"))).toQImage();
251 }
252
253 /*!
254 * \brief Sets the image.
255 * \remarks
256 * \a image is a raw data image format which describes the width, height, rowstride,
257 * has alpha, bits per sample, channels and image data respectively.
258 */
259 void DBusNotification::setImage(const QImage &image)
260 {
261 m_hints[QStringLiteral("image-data")] = NotificationImage(SwappedImage(image)).toDBusArgument();
262 }
263
264 /*!
265 * \brief
266 * Returns whether the notification is about to be shown after calling show() or update() but has not been shown yet.
267 * \remarks
268 * This is the case when show() or update() has been called but the notification daemon has not responded yet. When
269 * the notification daemon has responded or an error occurred isPending() will return false again. On success, isVisible()
270 * should return true instead.
271 */
272 bool DBusNotification::isPending() const
273 {
274 return m_id == pendingId || m_id == pendingId2;
275 }
276
277 /*!
278 * \brief Makes the notification object delete itself when the notification has
279 * been closed or an error occurred.
280 */
281 void DBusNotification::deleteOnCloseOrError()
282 {
283 connect(this, &DBusNotification::closed, this, &DBusNotification::deleteLater);
284 connect(this, &DBusNotification::error, this, &DBusNotification::deleteLater);
285 }
286
287 /*!
288 * \brief Shows the notification.
289 * \remarks
290 * - If called when a previous notification is still shown, the previous notification is updated.
291 * - If called when a previous notification is about to be shown (isShowing() returns true) no second notification
292 * is spawned immediately. Instead, the previously started notification will be updated once it has been shown to
293 * apply changes.
294 * \returns Returns false is the D-Bus daemon isn't reachable and true otherwise.
295 */
296 bool DBusNotification::show()
297 {
298 if (isPending()) {
299 m_id = pendingId2;
300 return true;
301 }
302 if (!s_dbusInterface->isValid()) {
303 emit error();
304 return false;
305 }
306
307 delete m_watcher;
308 m_watcher
309 = new QDBusPendingCallWatcher(s_dbusInterface->Notify(m_applicationName.isEmpty() ? QCoreApplication::applicationName() : m_applicationName,
310 m_id, m_icon, m_title, m_msg, m_actions, m_hints, m_timeout),
311 this);
312 connect(m_watcher, &QDBusPendingCallWatcher::finished, this, &DBusNotification::handleNotifyResult);
313 m_id = pendingId;
314 return true;
315 }
316
317 /*!
318 * \brief Updates the message and shows/updates the notification.
319 * \remarks If called when a previous notification is still shown, the previous
320 * notification is updated.
321 * \returns Returns false is the D-Bus daemon isn't reachable and true
322 * otherwise. The message is updated in any case.
323 */
324 bool DBusNotification::show(const QString &message)
325 {
326 m_msg = message;
327 return show();
328 }
329
330 /*!
331 * \brief Updates the message and shows/updates the notification.
332 * \remarks
333 * - If called when a previous notification is still shown, the previous
334 * notification is updated. In this
335 * case the specified \a line will be appended to the current message.
336 * - If called when no previous notification is still shown, the previous
337 * message is completely replaced
338 * by \a line and shown as a new notification.
339 * \returns Returns false is the D-Bus daemon isn't reachable and true
340 * otherwise. The message is updated in any case.
341 */
342 bool DBusNotification::update(const QString &line)
343 {
344 if ((!isPending() && !isVisible()) || m_msg.isEmpty()) {
345 m_msg = line;
346 } else {
347 if (!m_msg.startsWith(QStringLiteral("•"))) {
348 m_msg.insert(0, QStringLiteral("• "));
349 }
350 m_msg.append(QStringLiteral("\n• "));
351 m_msg.append(line);
352 }
353 return show();
354 }
355
356 bool DBusNotification::queryCapabilities(const std::function<void(Capabilities &&capabilities)> &callback)
357 {
358 // ensure DBus-interface is initialized and valid
359 initInterface();
360 if (!s_dbusInterface->isValid()) {
361 return false;
362 }
363
364 // invoke GetCapabilities() and pass the return value to the callback when available
365 const auto *const newWatcher = new QDBusPendingCallWatcher(s_dbusInterface->GetCapabilities());
366 connect(newWatcher, &QDBusPendingCallWatcher::finished, [&callback](QDBusPendingCallWatcher *watcher) {
367 watcher->deleteLater();
368 const QDBusPendingReply<QStringList> returnValue(*watcher);
369 if (returnValue.isError()) {
370 callback(Capabilities());
371 } else {
372 callback(Capabilities(std::move(returnValue.value())));
373 }
374 });
375 return true;
376 }
377
378 /*!
379 * \brief Hides the notification (if still visible).
380 * \remarks On success, the signal closed() is emitted with the reason
381 * NotificationCloseReason::Manually.
382 */
383 bool DBusNotification::hide()
384 {
385 if (m_id) {
386 s_dbusInterface->CloseNotification(m_id);
387 return true;
388 }
389 return false;
390 }
391
392 /*!
393 * \brief Handles the results of the Notify D-Bus call.
394 */
395 void DBusNotification::handleNotifyResult(QDBusPendingCallWatcher *watcher)
396 {
397 if (watcher != m_watcher) {
398 return;
399 }
400
401 watcher->deleteLater();
402 m_watcher = nullptr;
403
404 QDBusPendingReply<uint> returnValue = *watcher;
405 if (returnValue.isError()) {
406 m_id = initialId;
407 emit error();
408 return;
409 }
410
411 const auto needsUpdate = m_id == pendingId2;
412 {
413 QMutexLocker lock(&pendingNotificationsMutex);
414 pendingNotifications[m_id = returnValue.argumentAt<0>()] = this;
415 }
416 emit shown();
417
418 // update the notification again if show() was called before we've got the ID
419 if (needsUpdate) {
420 show();
421 }
422 }
423
424 /*!
425 * \brief Handles the NotificationClosed D-Bus signal.
426 */
427 void DBusNotification::handleNotificationClosed(IDType id, uint reason)
428 {
429 QMutexLocker lock(&pendingNotificationsMutex);
430 auto i = pendingNotifications.find(id);
431 if (i != pendingNotifications.end()) {
432 DBusNotification *notification = i->second;
433 notification->m_id = initialId;
434 emit notification->closed(reason >= 1 && reason <= 3 ? static_cast<NotificationCloseReason>(reason) : NotificationCloseReason::Undefined);
435 pendingNotifications.erase(i);
436 }
437 }
438
439 /*!
440 * \brief Handles the ActionInvoked D-Bus signal.
441 */
442 void DBusNotification::handleActionInvoked(IDType id, const QString &action)
443 {
444 QMutexLocker lock(&pendingNotificationsMutex);
445 auto i = pendingNotifications.find(id);
446 if (i != pendingNotifications.end()) {
447 DBusNotification *notification = i->second;
448 emit notification->actionInvoked(action);
449 // Plasma 5 also closes the notification but doesn't emit the
450 // NotificationClose signal
451 // -> just consider the notification closed
452 emit notification->closed(NotificationCloseReason::ActionInvoked);
453 notification->m_id = initialId;
454 pendingNotifications.erase(i);
455 // however, lxqt-notificationd does not close the notification
456 // -> close manually for consistent behaviour
457 s_dbusInterface->CloseNotification(i->first);
458 }
459 }
460
461 /*!
462 * \fn DBusNotification::message()
463 * \brief Returns the assigned message.
464 * \sa setMessage() for more details.
465 */
466
467 /*!
468 * \fn DBusNotification::setMessage()
469 * \brief Sets the message to be shown.
470 * \remarks
471 * - Might also be set via show() and update().
472 * - Can contain the following HTML tags: `<b>`, `<i>`, `<u>`, `<a href="...">`
473 * and `<img src="..." alt="..."/>`
474 */
475
476 /*!
477 * \fn DBusNotification::timeout()
478 * \brief Returns the number of milliseconds the notification will be visible
479 * after calling show().
480 * \sa setTimeout() for more details.
481 */
482
483 /*!
484 * \fn DBusNotification::setTimeout()
485 * \brief Sets the number of milliseconds the notification will be visible after
486 * calling show().
487 * \remarks
488 * - Set to 0 for non-expiring notifications.
489 * - Set to -1 to let the notification daemon decide.
490 */
491
492 /*!
493 * \fn DBusNotification::actions()
494 * \brief Returns the assigned actions.
495 * \sa setActions() for more details.
496 */
497
498 /*!
499 * \fn DBusNotification::setActions()
500 * \brief Sets the list of available actions.
501 * \remarks
502 * The list consists of pairs of action IDs and action labels, eg.
503 * `QStringList({QStringLiteral("first_id"), tr("First action"),
504 * QStringLiteral("second_id"), tr("Second action"), ...})`
505 * \sa actionInvoked() signal
506 */
507
508 /*!
509 * \fn DBusNotification::isVisible()
510 * \brief Returns whether the notification is (still) visible.
511 */
512 } // namespace QtUtilities