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