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 "statusnotifieritem.h"
28 #include <QApplication>
33 #include <QMouseEvent>
34 #include <QTextDocument>
39 #include "statusnotifieritemdbus.h"
41 constexpr int kProtocolVersion {0};
43 const QString kSniWatcherService {QLatin1String{"org.kde.StatusNotifierWatcher"}};
44 const QString kSniWatcherPath {QLatin1String{"/StatusNotifierWatcher"}};
45 const QString kSniPath {QLatin1String{"/StatusNotifierItem"}};
46 const QString kXdgNotificationsService {QLatin1String{"org.freedesktop.Notifications"}};
47 const QString kXdgNotificationsPath {QLatin1String{"/org/freedesktop/Notifications"}};
48 const QString kMenuObjectPath {QLatin1String{"/MenuBar"}};
51 # include "dbusmenuexporter.h"
54 * Specialization to provide access to icon names
56 class QuasselDBusMenuExporter : public DBusMenuExporter
59 QuasselDBusMenuExporter(const QString &dbusObjectPath, QMenu *menu, const QDBusConnection &dbusConnection)
60 : DBusMenuExporter(dbusObjectPath, menu, dbusConnection)
64 QString iconNameForAction(QAction *action) override // TODO Qt 4.7: fixme when we have converted our iconloader
66 QIcon icon(action->icon());
67 return icon.isNull() ? QString() : icon.name();
71 #endif /* HAVE_DBUSMENU */
73 StatusNotifierItem::StatusNotifierItem(QWidget *parent)
74 : StatusNotifierItemParent(parent)
75 , _iconThemeDir{QDir::tempPath() + QLatin1String{"/quassel-sni-XXXXXX"}}
77 static bool registered = []() -> bool {
78 qDBusRegisterMetaType<DBusImageStruct>();
79 qDBusRegisterMetaType<DBusImageVector>();
80 qDBusRegisterMetaType<DBusToolTipStruct>();
85 setMode(Mode::StatusNotifier);
87 connect(this, SIGNAL(visibilityChanged(bool)), this, SLOT(onVisibilityChanged(bool)));
88 connect(this, SIGNAL(modeChanged(Mode)), this, SLOT(onModeChanged(Mode)));
89 connect(this, SIGNAL(stateChanged(State)), this, SLOT(onStateChanged(State)));
91 trayMenu()->installEventFilter(this);
93 // Create a temporary directory that holds copies of the tray icons. That way, visualizers can find our icons.
94 if (_iconThemeDir.isValid()) {
95 _iconThemePath = _iconThemeDir.path();
98 qWarning() << "Could not create temporary directory for themed tray icons!";
101 connect(this, SIGNAL(iconsChanged()), this, SLOT(refreshIcons()));
104 // Our own SNI service
105 _statusNotifierItemDBus = new StatusNotifierItemDBus(this);
106 connect(this, SIGNAL(currentIconNameChanged()), _statusNotifierItemDBus, SIGNAL(NewIcon()));
107 connect(this, SIGNAL(currentIconNameChanged()), _statusNotifierItemDBus, SIGNAL(NewAttentionIcon()));
108 connect(this, SIGNAL(toolTipChanged(QString, QString)), _statusNotifierItemDBus, SIGNAL(NewToolTip()));
110 // Service watcher to keep track of the StatusNotifierWatcher service
111 _serviceWatcher = new QDBusServiceWatcher(kSniWatcherService,
112 QDBusConnection::sessionBus(),
113 QDBusServiceWatcher::WatchForOwnerChange,
115 connect(_serviceWatcher, SIGNAL(serviceOwnerChanged(QString, QString, QString)), SLOT(serviceChange(QString, QString, QString)));
117 // Client instance for StatusNotifierWatcher
118 _statusNotifierWatcher = new org::kde::StatusNotifierWatcher(kSniWatcherService,
120 QDBusConnection::sessionBus(),
122 connect(_statusNotifierWatcher, SIGNAL(StatusNotifierHostRegistered()), SLOT(checkForRegisteredHosts()));
123 connect(_statusNotifierWatcher, SIGNAL(StatusNotifierHostUnregistered()), SLOT(checkForRegisteredHosts()));
125 // Client instance for notifications
126 _notificationsClient = new org::freedesktop::Notifications(kXdgNotificationsService,
127 kXdgNotificationsPath,
128 QDBusConnection::sessionBus(),
130 connect(_notificationsClient, SIGNAL(NotificationClosed(uint, uint)), SLOT(notificationClosed(uint, uint)));
131 connect(_notificationsClient, SIGNAL(ActionInvoked(uint, QString)), SLOT(notificationInvoked(uint, QString)));
133 if (_notificationsClient->isValid()) {
134 QStringList desktopCapabilities = _notificationsClient->GetCapabilities();
135 _notificationsClientSupportsMarkup = desktopCapabilities.contains("body-markup");
136 _notificationsClientSupportsActions = desktopCapabilities.contains("actions");
140 new QuasselDBusMenuExporter(menuObjectPath(), trayMenu(), _statusNotifierItemDBus->dbusConnection()); // will be added as menu child
145 void StatusNotifierItem::serviceChange(const QString &name, const QString &oldOwner, const QString &newOwner)
148 if (newOwner.isEmpty()) {
150 setMode(Mode::Legacy);
152 else if (oldOwner.isEmpty()) {
154 setMode(Mode::StatusNotifier);
159 void StatusNotifierItem::registerToWatcher()
161 if (_statusNotifierWatcher->isValid() && _statusNotifierWatcher->property("ProtocolVersion").toInt() == kProtocolVersion) {
162 auto registerMethod = QDBusMessage::createMethodCall(kSniWatcherService, kSniWatcherPath, kSniWatcherService,
163 QLatin1String{"RegisterStatusNotifierItem"});
164 registerMethod.setArguments(QVariantList() << _statusNotifierItemDBus->service());
165 _statusNotifierItemDBus->dbusConnection().callWithCallback(registerMethod, this, SLOT(checkForRegisteredHosts()), SLOT(onDBusError(QDBusError)));
168 setMode(Mode::Legacy);
173 void StatusNotifierItem::checkForRegisteredHosts()
175 if (!_statusNotifierWatcher || !_statusNotifierWatcher->property("IsStatusNotifierHostRegistered").toBool()) {
176 setMode(Mode::Legacy);
179 setMode(Mode::StatusNotifier);
184 void StatusNotifierItem::onDBusError(const QDBusError &error)
186 qWarning() << "StatusNotifierItem encountered a D-Bus error:" << error;
187 setMode(Mode::Legacy);
191 void StatusNotifierItem::refreshIcons()
193 if (!_iconThemePath.isEmpty()) {
194 QDir baseDir{_iconThemePath + "/hicolor"};
195 baseDir.removeRecursively();
196 for (auto &&trayState : { State::Active, State::Passive, State::NeedsAttention }) {
197 auto iconName = SystemTray::iconName(trayState);
198 QIcon icon = icon::get(iconName);
199 if (!icon.isNull()) {
200 for (auto &&size : icon.availableSizes()) {
201 auto pixDir = QString{"%1/%2x%3/status"}.arg(baseDir.absolutePath()).arg(size.width()).arg(size.height());
202 QDir{}.mkpath(pixDir);
203 if (!icon.pixmap(size).save(pixDir + "/" + iconName + ".png")) {
204 qWarning() << "Could not save tray icon" << iconName << "for size" << size;
209 // No theme icon found; use fallback from resources
210 auto iconDir = QString{"%1/24x24/status"}.arg(baseDir.absolutePath());
211 QDir{}.mkpath(iconDir);
212 if (!QFile::copy(QString{":/icons/hicolor/24x24/status/%1.svg"}.arg(iconName),
213 QString{"%1/%2.svg"}.arg(iconDir, iconName))) {
214 qWarning() << "Could not access fallback tray icon" << iconName;
221 if (_statusNotifierItemDBus) {
222 emit _statusNotifierItemDBus->NewIcon();
223 emit _statusNotifierItemDBus->NewAttentionIcon();
228 bool StatusNotifierItem::isSystemTrayAvailable() const
230 if (mode() == Mode::StatusNotifier) {
231 return true; // else it should be set to legacy on registration
234 return StatusNotifierItemParent::isSystemTrayAvailable();
238 void StatusNotifierItem::onModeChanged(Mode mode)
240 if (mode == Mode::StatusNotifier) {
241 _statusNotifierItemDBus->registerTrayIcon();
245 _statusNotifierItemDBus->unregisterTrayIcon();
250 void StatusNotifierItem::onStateChanged(State state)
252 if (mode() == Mode::StatusNotifier) {
253 emit _statusNotifierItemDBus->NewStatus(metaObject()->enumerator(metaObject()->indexOfEnumerator("State")).valueToKey(state));
258 void StatusNotifierItem::onVisibilityChanged(bool isVisible)
260 if (mode() == Mode::StatusNotifier) {
262 _statusNotifierItemDBus->registerTrayIcon();
266 _statusNotifierItemDBus->unregisterTrayIcon();
272 QString StatusNotifierItem::title() const
274 return QString("Quassel IRC");
278 QString StatusNotifierItem::iconName() const
280 return currentIconName();
284 QString StatusNotifierItem::attentionIconName() const
286 return currentAttentionIconName();
290 QString StatusNotifierItem::toolTipIconName() const
296 QString StatusNotifierItem::iconThemePath() const
298 return _iconThemePath;
302 QString StatusNotifierItem::menuObjectPath() const
304 return kMenuObjectPath;
308 void StatusNotifierItem::activated(const QPoint &pos)
315 bool StatusNotifierItem::eventFilter(QObject *watched, QEvent *event)
317 if (mode() == StatusNotifier) {
318 if (watched == trayMenu() && event->type() == QEvent::HoverLeave) {
322 return StatusNotifierItemParent::eventFilter(watched, event);
326 void StatusNotifierItem::showMessage(const QString &title, const QString &message_, SystemTray::MessageIcon icon, int timeout, uint notificationId)
328 QString message = message_;
329 if (_notificationsClient->isValid()) {
330 if (_notificationsClientSupportsMarkup) {
331 message = message.toHtmlEscaped();
335 if (_notificationsClientSupportsActions)
336 actions << "activate" << "View";
338 // we always queue notifications right now
339 QDBusReply<uint> reply = _notificationsClient->Notify(title, 0, "quassel", title, message, actions, QVariantMap(), timeout);
340 if (reply.isValid()) {
341 uint dbusid = reply.value();
342 _notificationsIdMap.insert(dbusid, notificationId);
343 _lastNotificationsDBusId = dbusid;
347 StatusNotifierItemParent::showMessage(title, message, icon, timeout, notificationId);
351 void StatusNotifierItem::closeMessage(uint notificationId)
353 for (auto &&dbusid : _notificationsIdMap.keys()) {
354 if (_notificationsIdMap.value(dbusid) == notificationId) {
355 _notificationsIdMap.remove(dbusid);
356 _notificationsClient->CloseNotification(dbusid);
359 _lastNotificationsDBusId = 0;
361 StatusNotifierItemParent::closeMessage(notificationId);
365 void StatusNotifierItem::notificationClosed(uint dbusid, uint reason)
368 _lastNotificationsDBusId = 0;
369 emit messageClosed(_notificationsIdMap.take(dbusid));
373 void StatusNotifierItem::notificationInvoked(uint dbusid, const QString &action)
376 emit messageClicked(_notificationsIdMap.value(dbusid, 0));