1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This contains code from KStatusNotifierItem, part of the KDE libs *
6 * Copyright (C) 2009 Marco Martin <notmart@gmail.com> *
8 * This file is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU Library General Public License (LGPL) *
10 * as published by the Free Software Foundation; either version 2 of the *
11 * License, or (at your option) any later version. *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
22 ***************************************************************************/
26 #include <QApplication>
30 #include <QMouseEvent>
31 #include <QTextDocument>
35 #include "statusnotifieritem.h"
36 #include "statusnotifieritemdbus.h"
38 constexpr int kProtocolVersion {0};
40 const QString kSniWatcherService {QLatin1String{"org.kde.StatusNotifierWatcher"}};
41 const QString kSniWatcherPath {QLatin1String{"/StatusNotifierWatcher"}};
42 const QString kSniPath {QLatin1String{"/StatusNotifierItem"}};
43 const QString kXdgNotificationsService {QLatin1String{"org.freedesktop.Notifications"}};
44 const QString kXdgNotificationsPath {QLatin1String{"/org/freedesktop/Notifications"}};
45 const QString kMenuObjectPath {QLatin1String{"/MenuBar"}};
48 # include "dbusmenuexporter.h"
51 * Specialization to provide access to icon names
53 class QuasselDBusMenuExporter : public DBusMenuExporter
56 QuasselDBusMenuExporter(const QString &dbusObjectPath, QMenu *menu, const QDBusConnection &dbusConnection)
57 : DBusMenuExporter(dbusObjectPath, menu, dbusConnection)
61 virtual QString iconNameForAction(QAction *action) // TODO Qt 4.7: fixme when we have converted our iconloader
63 QIcon icon(action->icon());
64 return icon.isNull() ? QString() : icon.name();
68 #endif /* HAVE_DBUSMENU */
70 StatusNotifierItem::StatusNotifierItem(QWidget *parent)
71 : StatusNotifierItemParent(parent)
72 #if QT_VERSION >= 0x050000
73 , _iconThemeDir{QDir::tempPath() + QLatin1String{"/quassel-sni-XXXXXX"}}
76 static bool registered = []() -> bool {
77 qDBusRegisterMetaType<DBusImageStruct>();
78 qDBusRegisterMetaType<DBusImageVector>();
79 qDBusRegisterMetaType<DBusToolTipStruct>();
84 setMode(Mode::StatusNotifier);
86 connect(this, SIGNAL(visibilityChanged(bool)), this, SLOT(onVisibilityChanged(bool)));
87 connect(this, SIGNAL(modeChanged(Mode)), this, SLOT(onModeChanged(Mode)));
88 connect(this, SIGNAL(stateChanged(State)), this, SLOT(onStateChanged(State)));
90 trayMenu()->installEventFilter(this);
92 // Create a temporary directory that holds copies of the tray icons. That way, visualizers can find our icons.
93 // For Qt4 the relevant icons are installed in hicolor already, so nothing to be done.
94 #if QT_VERSION >= 0x050000
95 if (_iconThemeDir.isValid()) {
96 _iconThemePath = _iconThemeDir.path();
99 qWarning() << "Could not create temporary directory for themed tray icons!";
103 connect(this, SIGNAL(iconsChanged()), this, SLOT(refreshIcons()));
106 // Our own SNI service
107 _statusNotifierItemDBus = new StatusNotifierItemDBus(this);
108 connect(this, SIGNAL(currentIconNameChanged()), _statusNotifierItemDBus, SIGNAL(NewIcon()));
109 connect(this, SIGNAL(currentIconNameChanged()), _statusNotifierItemDBus, SIGNAL(NewAttentionIcon()));
110 connect(this, SIGNAL(toolTipChanged(QString, QString)), _statusNotifierItemDBus, SIGNAL(NewToolTip()));
112 // Service watcher to keep track of the StatusNotifierWatcher service
113 QDBusServiceWatcher *watcher = new QDBusServiceWatcher(kSniWatcherService,
114 QDBusConnection::sessionBus(),
115 QDBusServiceWatcher::WatchForOwnerChange,
117 connect(watcher, SIGNAL(serviceOwnerChanged(QString, QString, QString)), SLOT(serviceChange(QString, QString, QString)));
119 // Client instance for StatusNotifierWatcher
120 _statusNotifierWatcher = new org::kde::StatusNotifierWatcher(kSniWatcherService,
122 QDBusConnection::sessionBus(),
124 connect(_statusNotifierWatcher, SIGNAL(StatusNotifierHostRegistered()), SLOT(checkForRegisteredHosts()));
125 connect(_statusNotifierWatcher, SIGNAL(StatusNotifierHostUnregistered()), SLOT(checkForRegisteredHosts()));
127 // Client instance for notifications
128 _notificationsClient = new org::freedesktop::Notifications(kXdgNotificationsService,
129 kXdgNotificationsPath,
130 QDBusConnection::sessionBus(),
132 connect(_notificationsClient, SIGNAL(NotificationClosed(uint, uint)), SLOT(notificationClosed(uint, uint)));
133 connect(_notificationsClient, SIGNAL(ActionInvoked(uint, QString)), SLOT(notificationInvoked(uint, QString)));
135 if (_notificationsClient->isValid()) {
136 QStringList desktopCapabilities = _notificationsClient->GetCapabilities();
137 _notificationsClientSupportsMarkup = desktopCapabilities.contains("body-markup");
138 _notificationsClientSupportsActions = desktopCapabilities.contains("actions");
142 new QuasselDBusMenuExporter(menuObjectPath(), trayMenu(), _statusNotifierItemDBus->dbusConnection()); // will be added as menu child
147 void StatusNotifierItem::serviceChange(const QString &name, const QString &oldOwner, const QString &newOwner)
150 if (newOwner.isEmpty()) {
152 setMode(Mode::Legacy);
154 else if (oldOwner.isEmpty()) {
156 setMode(Mode::StatusNotifier);
161 void StatusNotifierItem::registerToWatcher()
163 if (_statusNotifierWatcher->isValid() && _statusNotifierWatcher->property("ProtocolVersion").toInt() == kProtocolVersion) {
164 auto registerMethod = QDBusMessage::createMethodCall(kSniWatcherService, kSniWatcherPath, kSniWatcherService,
165 QLatin1String{"RegisterStatusNotifierItem"});
166 registerMethod.setArguments(QVariantList() << _statusNotifierItemDBus->service());
167 _statusNotifierItemDBus->dbusConnection().callWithCallback(registerMethod, this, SLOT(checkForRegisteredHosts()), SLOT(onDBusError(QDBusError)));
170 setMode(Mode::Legacy);
175 void StatusNotifierItem::checkForRegisteredHosts()
177 if (!_statusNotifierWatcher || !_statusNotifierWatcher->property("IsStatusNotifierHostRegistered").toBool()) {
178 setMode(Mode::Legacy);
181 setMode(Mode::StatusNotifier);
186 void StatusNotifierItem::onDBusError(const QDBusError &error)
188 qWarning() << "StatusNotifierItem encountered a D-Bus error:" << error;
189 setMode(Mode::Legacy);
193 void StatusNotifierItem::refreshIcons()
195 #if QT_VERSION >= 0x050000
196 if (!_iconThemePath.isEmpty()) {
197 QDir baseDir{_iconThemePath + "/hicolor"};
198 baseDir.removeRecursively();
199 for (auto &&trayState : { State::Active, State::Passive, State::NeedsAttention }) {
200 auto iconName = SystemTray::iconName(trayState);
201 QIcon icon = QIcon::fromTheme(iconName);
202 if (!icon.isNull()) {
203 for (auto &&size : icon.availableSizes()) {
204 auto pixDir = QString{"%1/%2x%3/status"}.arg(baseDir.absolutePath()).arg(size.width()).arg(size.height());
205 QDir{}.mkpath(pixDir);
206 if (!icon.pixmap(size).save(pixDir + "/" + iconName + ".png")) {
207 qWarning() << "Could not save tray icon" << iconName << "for size" << size;
212 // No theme icon found; use fallback from resources
213 auto iconDir = QString{"%1/24x24/status"}.arg(baseDir.absolutePath());
214 QDir{}.mkpath(iconDir);
215 if (!QFile::copy(QString{":/icons/hicolor/24x24/status/%1.svg"}.arg(iconName),
216 QString{"%1/%2.svg"}.arg(iconDir, iconName))) {
217 qWarning() << "Could not access fallback tray icon" << iconName;
224 if (_statusNotifierItemDBus) {
225 emit _statusNotifierItemDBus->NewIcon();
226 emit _statusNotifierItemDBus->NewAttentionIcon();
231 bool StatusNotifierItem::isSystemTrayAvailable() const
233 if (mode() == Mode::StatusNotifier) {
234 return true; // else it should be set to legacy on registration
237 return StatusNotifierItemParent::isSystemTrayAvailable();
241 void StatusNotifierItem::onModeChanged(Mode mode)
243 if (mode == Mode::StatusNotifier) {
244 _statusNotifierItemDBus->registerTrayIcon();
248 _statusNotifierItemDBus->unregisterTrayIcon();
253 void StatusNotifierItem::onStateChanged(State state)
255 if (mode() == Mode::StatusNotifier) {
256 emit _statusNotifierItemDBus->NewStatus(metaObject()->enumerator(metaObject()->indexOfEnumerator("State")).valueToKey(state));
261 void StatusNotifierItem::onVisibilityChanged(bool isVisible)
263 if (mode() == Mode::StatusNotifier) {
265 _statusNotifierItemDBus->registerTrayIcon();
269 _statusNotifierItemDBus->unregisterTrayIcon();
275 QString StatusNotifierItem::title() const
277 return QString("Quassel IRC");
281 QString StatusNotifierItem::iconName() const
283 return currentIconName();
287 QString StatusNotifierItem::attentionIconName() const
289 return currentAttentionIconName();
293 QString StatusNotifierItem::toolTipIconName() const
299 QString StatusNotifierItem::iconThemePath() const
301 return _iconThemePath;
305 QString StatusNotifierItem::menuObjectPath() const
307 return kMenuObjectPath;
311 void StatusNotifierItem::activated(const QPoint &pos)
318 bool StatusNotifierItem::eventFilter(QObject *watched, QEvent *event)
320 if (mode() == StatusNotifier) {
321 //FIXME: ugly ugly workaround to weird QMenu's focus problems
323 if (watched == trayMenu() &&
324 (event->type() == QEvent::WindowDeactivate || (event->type() == QEvent::MouseButtonRelease && static_cast<QMouseEvent *>(event)->button() == Qt::LeftButton))) {
325 // put at the back of event queue to let the action activate anyways
326 QTimer::singleShot(0, trayMenu(), SLOT(hide()));
329 if (watched == trayMenu() && event->type() == QEvent::HoverLeave) {
334 return StatusNotifierItemParent::eventFilter(watched, event);
338 void StatusNotifierItem::showMessage(const QString &title, const QString &message_, SystemTray::MessageIcon icon, int timeout, uint notificationId)
340 QString message = message_;
341 if (_notificationsClient->isValid()) {
342 if (_notificationsClientSupportsMarkup)
343 #if QT_VERSION < 0x050000
344 message = Qt::escape(message);
346 message = message.toHtmlEscaped();
350 if (_notificationsClientSupportsActions)
351 actions << "activate" << "View";
353 // we always queue notifications right now
354 QDBusReply<uint> reply = _notificationsClient->Notify(title, 0, "quassel", title, message, actions, QVariantMap(), timeout);
355 if (reply.isValid()) {
356 uint dbusid = reply.value();
357 _notificationsIdMap.insert(dbusid, notificationId);
358 _lastNotificationsDBusId = dbusid;
362 StatusNotifierItemParent::showMessage(title, message, icon, timeout, notificationId);
366 void StatusNotifierItem::closeMessage(uint notificationId)
368 for (auto &&dbusid : _notificationsIdMap.keys()) {
369 if (_notificationsIdMap.value(dbusid) == notificationId) {
370 _notificationsIdMap.remove(dbusid);
371 _notificationsClient->CloseNotification(dbusid);
374 _lastNotificationsDBusId = 0;
376 StatusNotifierItemParent::closeMessage(notificationId);
380 void StatusNotifierItem::notificationClosed(uint dbusid, uint reason)
383 _lastNotificationsDBusId = 0;
384 emit messageClosed(_notificationsIdMap.take(dbusid));
388 void StatusNotifierItem::notificationInvoked(uint dbusid, const QString &action)
391 emit messageClicked(_notificationsIdMap.value(dbusid, 0));