qa: Remove lots of superfluous semicolons
[quassel.git] / src / qtui / statusnotifieritem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This contains code from KStatusNotifierItem, part of the KDE libs     *
6  *   Copyright (C) 2009 Marco Martin <notmart@gmail.com>                   *
7  *                                                                         *
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.                       *
12  *                                                                         *
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.                          *
17  *                                                                         *
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  ***************************************************************************/
23
24 #ifdef HAVE_DBUS
25
26 #include "statusnotifieritem.h"
27
28 #include <QApplication>
29 #include <QDir>
30 #include <QFile>
31 #include <QIcon>
32 #include <QMenu>
33 #include <QMouseEvent>
34 #include <QTextDocument>
35
36 #include "icon.h"
37 #include "qtui.h"
38 #include "quassel.h"
39 #include "statusnotifieritemdbus.h"
40
41 constexpr int kProtocolVersion {0};
42
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"}};
49
50 #ifdef HAVE_DBUSMENU
51 #  include "dbusmenuexporter.h"
52
53 /**
54  * Specialization to provide access to icon names
55  */
56 class QuasselDBusMenuExporter : public DBusMenuExporter
57 {
58 public:
59     QuasselDBusMenuExporter(const QString &dbusObjectPath, QMenu *menu, const QDBusConnection &dbusConnection)
60         : DBusMenuExporter(dbusObjectPath, menu, dbusConnection)
61     {}
62
63 protected:
64     virtual QString iconNameForAction(QAction *action) // TODO Qt 4.7: fixme when we have converted our iconloader
65     {
66         QIcon icon(action->icon());
67         return icon.isNull() ? QString() : icon.name();
68     }
69 };
70
71 #endif /* HAVE_DBUSMENU */
72
73 StatusNotifierItem::StatusNotifierItem(QWidget *parent)
74     : StatusNotifierItemParent(parent)
75     , _iconThemeDir{QDir::tempPath() + QLatin1String{"/quassel-sni-XXXXXX"}}
76 {
77     static bool registered = []() -> bool {
78         qDBusRegisterMetaType<DBusImageStruct>();
79         qDBusRegisterMetaType<DBusImageVector>();
80         qDBusRegisterMetaType<DBusToolTipStruct>();
81         return true;
82     }();
83     Q_UNUSED(registered)
84
85     setMode(Mode::StatusNotifier);
86
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)));
90
91     trayMenu()->installEventFilter(this);
92
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();
96     }
97     else {
98         qWarning() << "Could not create temporary directory for themed tray icons!";
99     }
100
101     connect(this, SIGNAL(iconsChanged()), this, SLOT(refreshIcons()));
102     refreshIcons();
103
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()));
109
110     // Service watcher to keep track of the StatusNotifierWatcher service
111     _serviceWatcher = new QDBusServiceWatcher(kSniWatcherService,
112                                               QDBusConnection::sessionBus(),
113                                               QDBusServiceWatcher::WatchForOwnerChange,
114                                               this);
115     connect(_serviceWatcher, SIGNAL(serviceOwnerChanged(QString, QString, QString)), SLOT(serviceChange(QString, QString, QString)));
116
117     // Client instance for StatusNotifierWatcher
118     _statusNotifierWatcher = new org::kde::StatusNotifierWatcher(kSniWatcherService,
119                                                                  kSniWatcherPath,
120                                                                  QDBusConnection::sessionBus(),
121                                                                  this);
122     connect(_statusNotifierWatcher, SIGNAL(StatusNotifierHostRegistered()), SLOT(checkForRegisteredHosts()));
123     connect(_statusNotifierWatcher, SIGNAL(StatusNotifierHostUnregistered()), SLOT(checkForRegisteredHosts()));
124
125     // Client instance for notifications
126     _notificationsClient = new org::freedesktop::Notifications(kXdgNotificationsService,
127                                                                kXdgNotificationsPath,
128                                                                QDBusConnection::sessionBus(),
129                                                                this);
130     connect(_notificationsClient, SIGNAL(NotificationClosed(uint, uint)), SLOT(notificationClosed(uint, uint)));
131     connect(_notificationsClient, SIGNAL(ActionInvoked(uint, QString)), SLOT(notificationInvoked(uint, QString)));
132
133     if (_notificationsClient->isValid()) {
134         QStringList desktopCapabilities = _notificationsClient->GetCapabilities();
135         _notificationsClientSupportsMarkup = desktopCapabilities.contains("body-markup");
136         _notificationsClientSupportsActions = desktopCapabilities.contains("actions");
137     }
138
139 #ifdef HAVE_DBUSMENU
140     new QuasselDBusMenuExporter(menuObjectPath(), trayMenu(), _statusNotifierItemDBus->dbusConnection()); // will be added as menu child
141 #endif
142 }
143
144
145 void StatusNotifierItem::serviceChange(const QString &name, const QString &oldOwner, const QString &newOwner)
146 {
147     Q_UNUSED(name);
148     if (newOwner.isEmpty()) {
149         //unregistered
150         setMode(Mode::Legacy);
151     }
152     else if (oldOwner.isEmpty()) {
153         //registered
154         setMode(Mode::StatusNotifier);
155     }
156 }
157
158
159 void StatusNotifierItem::registerToWatcher()
160 {
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)));
166     }
167     else {
168         setMode(Mode::Legacy);
169     }
170 }
171
172
173 void StatusNotifierItem::checkForRegisteredHosts()
174 {
175     if (!_statusNotifierWatcher || !_statusNotifierWatcher->property("IsStatusNotifierHostRegistered").toBool()) {
176         setMode(Mode::Legacy);
177     }
178     else {
179         setMode(Mode::StatusNotifier);
180     }
181 }
182
183
184 void StatusNotifierItem::onDBusError(const QDBusError &error)
185 {
186     qWarning() << "StatusNotifierItem encountered a D-Bus error:" << error;
187     setMode(Mode::Legacy);
188 }
189
190
191 void StatusNotifierItem::refreshIcons()
192 {
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;
205                     }
206                 }
207             }
208             else {
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;
215                     continue;
216                 }
217             }
218         }
219     }
220
221     if (_statusNotifierItemDBus) {
222         emit _statusNotifierItemDBus->NewIcon();
223         emit _statusNotifierItemDBus->NewAttentionIcon();
224     }
225 }
226
227
228 bool StatusNotifierItem::isSystemTrayAvailable() const
229 {
230     if (mode() == Mode::StatusNotifier) {
231         return true;  // else it should be set to legacy on registration
232     }
233
234     return StatusNotifierItemParent::isSystemTrayAvailable();
235 }
236
237
238 void StatusNotifierItem::onModeChanged(Mode mode)
239 {
240     if (mode == Mode::StatusNotifier) {
241         _statusNotifierItemDBus->registerTrayIcon();
242         registerToWatcher();
243     }
244     else {
245         _statusNotifierItemDBus->unregisterTrayIcon();
246     }
247 }
248
249
250 void StatusNotifierItem::onStateChanged(State state)
251 {
252     if (mode() == Mode::StatusNotifier) {
253         emit _statusNotifierItemDBus->NewStatus(metaObject()->enumerator(metaObject()->indexOfEnumerator("State")).valueToKey(state));
254     }
255 }
256
257
258 void StatusNotifierItem::onVisibilityChanged(bool isVisible)
259 {
260     if (mode() == Mode::StatusNotifier) {
261         if (isVisible) {
262             _statusNotifierItemDBus->registerTrayIcon();
263             registerToWatcher();
264         }
265         else {
266             _statusNotifierItemDBus->unregisterTrayIcon();
267         }
268     }
269 }
270
271
272 QString StatusNotifierItem::title() const
273 {
274     return QString("Quassel IRC");
275 }
276
277
278 QString StatusNotifierItem::iconName() const
279 {
280     return currentIconName();
281 }
282
283
284 QString StatusNotifierItem::attentionIconName() const
285 {
286     return currentAttentionIconName();
287 }
288
289
290 QString StatusNotifierItem::toolTipIconName() const
291 {
292     return "quassel";
293 }
294
295
296 QString StatusNotifierItem::iconThemePath() const
297 {
298     return _iconThemePath;
299 }
300
301
302 QString StatusNotifierItem::menuObjectPath() const
303 {
304     return kMenuObjectPath;
305 }
306
307
308 void StatusNotifierItem::activated(const QPoint &pos)
309 {
310     Q_UNUSED(pos)
311     activate(Trigger);
312 }
313
314
315 bool StatusNotifierItem::eventFilter(QObject *watched, QEvent *event)
316 {
317     if (mode() == StatusNotifier) {
318         if (watched == trayMenu() && event->type() == QEvent::HoverLeave) {
319             trayMenu()->hide();
320         }
321     }
322     return StatusNotifierItemParent::eventFilter(watched, event);
323 }
324
325
326 void StatusNotifierItem::showMessage(const QString &title, const QString &message_, SystemTray::MessageIcon icon, int timeout, uint notificationId)
327 {
328     QString message = message_;
329     if (_notificationsClient->isValid()) {
330         if (_notificationsClientSupportsMarkup) {
331             message = message.toHtmlEscaped();
332         }
333
334         QStringList actions;
335         if (_notificationsClientSupportsActions)
336             actions << "activate" << "View";
337
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;
344         }
345     }
346     else
347         StatusNotifierItemParent::showMessage(title, message, icon, timeout, notificationId);
348 }
349
350
351 void StatusNotifierItem::closeMessage(uint notificationId)
352 {
353     for (auto &&dbusid : _notificationsIdMap.keys()) {
354         if (_notificationsIdMap.value(dbusid) == notificationId) {
355             _notificationsIdMap.remove(dbusid);
356             _notificationsClient->CloseNotification(dbusid);
357         }
358     }
359     _lastNotificationsDBusId = 0;
360
361     StatusNotifierItemParent::closeMessage(notificationId);
362 }
363
364
365 void StatusNotifierItem::notificationClosed(uint dbusid, uint reason)
366 {
367     Q_UNUSED(reason)
368     _lastNotificationsDBusId = 0;
369     emit messageClosed(_notificationsIdMap.take(dbusid));
370 }
371
372
373 void StatusNotifierItem::notificationInvoked(uint dbusid, const QString &action)
374 {
375     Q_UNUSED(action)
376     emit messageClicked(_notificationsIdMap.value(dbusid, 0));
377 }
378
379
380 #endif