Fix license for statusnotifieritem*
[quassel.git] / src / qtui / statusnotifieritem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 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  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23
24 #ifdef HAVE_DBUS
25
26 #include <QApplication>
27 #include <QMenu>
28 #include <QMouseEvent>
29 #include <QTextDocument>
30
31 #include "quassel.h"
32 #include "statusnotifieritem.h"
33 #include "statusnotifieritemdbus.h"
34
35 const int StatusNotifierItem::_protocolVersion = 0;
36 const QString StatusNotifierItem::_statusNotifierWatcherServiceName("org.kde.StatusNotifierWatcher");
37
38 #ifdef HAVE_DBUSMENU
39 #  include "dbusmenuexporter.h"
40
41 /**
42  * Specialization to provide access to icon names
43  */
44 class QuasselDBusMenuExporter : public DBusMenuExporter {
45 public:
46   QuasselDBusMenuExporter(const QString &dbusObjectPath, QMenu *menu, const QDBusConnection &dbusConnection)
47     : DBusMenuExporter(dbusObjectPath, menu, dbusConnection)
48   {}
49
50 protected:
51   virtual QString iconNameForAction(QAction *action) { // TODO Qt 4.7: fixme when we have converted our iconloader
52     Icon icon(action->icon());
53 #if QT_VERSION >= 0x040701
54     // QIcon::name() is in the 4.7 git branch, but it is not in 4.7 TP.
55     // If you get a build error here, you need to update your pre-release
56     // of Qt 4.7.
57     return icon.isNull() ? QString() : icon.name();
58 #else
59     return QString();
60 #endif
61   }
62 };
63
64 #endif /* HAVE_DBUSMENU */
65
66 StatusNotifierItem::StatusNotifierItem(QWidget *parent)
67   : StatusNotifierItemParent(parent),
68   _statusNotifierItemDBus(0),
69   _statusNotifierWatcher(0),
70   _notificationsClient(0),
71   _notificationsClientSupportsMarkup(true),
72   _lastNotificationsDBusId(0)
73 {
74
75 }
76
77 StatusNotifierItem::~StatusNotifierItem() {
78   delete _statusNotifierWatcher;
79 }
80
81 void StatusNotifierItem::init() {
82   qDBusRegisterMetaType<DBusImageStruct>();
83   qDBusRegisterMetaType<DBusImageVector>();
84   qDBusRegisterMetaType<DBusToolTipStruct>();
85
86   _statusNotifierItemDBus = new StatusNotifierItemDBus(this);
87
88   connect(this, SIGNAL(toolTipChanged(QString,QString)), _statusNotifierItemDBus, SIGNAL(NewToolTip()));
89   connect(this, SIGNAL(animationEnabledChanged(bool)), _statusNotifierItemDBus, SIGNAL(NewAttentionIcon()));
90
91   QDBusServiceWatcher *watcher = new QDBusServiceWatcher(_statusNotifierWatcherServiceName,
92                                                          QDBusConnection::sessionBus(),
93                                                          QDBusServiceWatcher::WatchForOwnerChange,
94                                                          this);
95   connect(watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)), SLOT(serviceChange(QString,QString,QString)));
96
97   setMode(StatusNotifier);
98
99   _notificationsClient = new org::freedesktop::Notifications("org.freedesktop.Notifications", "/org/freedesktop/Notifications",
100                                                              QDBusConnection::sessionBus(), this);
101
102   connect(_notificationsClient, SIGNAL(NotificationClosed(uint,uint)), SLOT(notificationClosed(uint,uint)));
103   connect(_notificationsClient, SIGNAL(ActionInvoked(uint,QString)), SLOT(notificationInvoked(uint,QString)));
104
105   if(_notificationsClient->isValid()) {
106     QStringList desktopCapabilities = _notificationsClient->GetCapabilities();
107     _notificationsClientSupportsMarkup = desktopCapabilities.contains("body-markup");
108   }
109
110   StatusNotifierItemParent::init();
111   trayMenu()->installEventFilter(this);
112
113   // use the appdata icon folder for now
114   _iconThemePath = Quassel::findDataFilePath("icons");
115
116 #ifdef HAVE_DBUSMENU
117   _menuObjectPath = "/MenuBar";
118   new QuasselDBusMenuExporter(menuObjectPath(), trayMenu(), _statusNotifierItemDBus->dbusConnection()); // will be added as menu child
119 #endif
120 }
121
122 void StatusNotifierItem::registerToDaemon() {
123   if(!_statusNotifierWatcher) {
124     _statusNotifierWatcher = new org::kde::StatusNotifierWatcher(_statusNotifierWatcherServiceName,
125                                                                  "/StatusNotifierWatcher",
126                                                                  QDBusConnection::sessionBus());
127     connect(_statusNotifierWatcher, SIGNAL(StatusNotifierHostRegistered()), SLOT(checkForRegisteredHosts()));
128     connect(_statusNotifierWatcher, SIGNAL(StatusNotifierHostUnregistered()), SLOT(checkForRegisteredHosts()));
129   }
130   if(_statusNotifierWatcher->isValid()
131     && _statusNotifierWatcher->property("ProtocolVersion").toInt() == _protocolVersion) {
132
133     _statusNotifierWatcher->RegisterStatusNotifierItem(_statusNotifierItemDBus->service());
134     checkForRegisteredHosts();
135
136   } else {
137     //qDebug() << "StatusNotifierWatcher not reachable!";
138     setMode(Legacy);
139   }
140 }
141
142 void StatusNotifierItem::serviceChange(const QString& name, const QString& oldOwner, const QString& newOwner) {
143   Q_UNUSED(name);
144   if(newOwner.isEmpty()) {
145     //unregistered
146     //qDebug() << "Connection to the StatusNotifierWatcher lost";
147     delete _statusNotifierWatcher;
148     _statusNotifierWatcher = 0;
149     setMode(Legacy);
150   } else if(oldOwner.isEmpty()) {
151     //registered
152     setMode(StatusNotifier);
153   }
154 }
155
156 void StatusNotifierItem::checkForRegisteredHosts() {
157   if(!_statusNotifierWatcher || !_statusNotifierWatcher->property("IsStatusNotifierHostRegistered").toBool())
158     setMode(Legacy);
159   else
160     setMode(StatusNotifier);
161 }
162
163 bool StatusNotifierItem::isSystemTrayAvailable() const {
164   if(mode() == StatusNotifier)
165     return true; // else it should be set to legacy on registration
166
167   return StatusNotifierItemParent::isSystemTrayAvailable();
168 }
169
170 bool StatusNotifierItem::isVisible() const {
171   if(mode() == StatusNotifier)
172     return shouldBeVisible(); // we don't have a way to check, so we need to trust everything went right
173
174   return StatusNotifierItemParent::isVisible();
175 }
176
177 void StatusNotifierItem::setMode(Mode mode_) {
178   if(mode_ == mode())
179     return;
180
181   if(mode_ != StatusNotifier) {
182     _statusNotifierItemDBus->unregisterService();
183   }
184
185   StatusNotifierItemParent::setMode(mode_);
186
187   if(mode() == StatusNotifier) {
188     _statusNotifierItemDBus->registerService();
189     registerToDaemon();
190   }
191 }
192
193 void StatusNotifierItem::setState(State state_) {
194   StatusNotifierItemParent::setState(state_);
195
196   emit _statusNotifierItemDBus->NewStatus(metaObject()->enumerator(metaObject()->indexOfEnumerator("State")).valueToKey(state()));
197   emit _statusNotifierItemDBus->NewIcon();
198 }
199
200 void StatusNotifierItem::setVisible(bool visible) {
201   if(visible == isVisible())
202     return;
203
204   LegacySystemTray::setVisible(visible);
205
206   if(mode() == StatusNotifier) {
207     if(shouldBeVisible()) {
208       _statusNotifierItemDBus->registerService();
209       registerToDaemon();
210     } else {
211       _statusNotifierItemDBus->unregisterService();
212       _statusNotifierWatcher->deleteLater();
213       _statusNotifierWatcher = 0;
214     }
215   }
216 }
217
218 QString StatusNotifierItem::title() const {
219   return QString("Quassel IRC");
220 }
221
222 QString StatusNotifierItem::iconName() const {
223   if(state() == Passive)
224     return QString("quassel_inactive");
225   else
226     return QString("quassel");
227 }
228
229 QString StatusNotifierItem::attentionIconName() const {
230   if(animationEnabled())
231     return QString("quassel_message");
232   else
233     return QString("quassel");
234 }
235
236 QString StatusNotifierItem::toolTipIconName() const {
237   return QString("quassel");
238 }
239
240 QString StatusNotifierItem::iconThemePath() const {
241   return _iconThemePath;
242 }
243
244 QString StatusNotifierItem::menuObjectPath() const {
245   return _menuObjectPath;
246 }
247
248 void StatusNotifierItem::activated(const QPoint &pos) {
249   Q_UNUSED(pos)
250   activate(Trigger);
251 }
252
253 bool StatusNotifierItem::eventFilter(QObject *watched, QEvent *event) {
254   if(mode() == StatusNotifier) {
255     //FIXME: ugly ugly workaround to weird QMenu's focus problems
256 #ifdef HAVE_KDE
257     if(watched == trayMenu() &&
258        (event->type() == QEvent::WindowDeactivate || (event->type() == QEvent::MouseButtonRelease && static_cast<QMouseEvent*>(event)->button() == Qt::LeftButton))) {
259       // put at the back of event queue to let the action activate anyways
260       QTimer::singleShot(0, trayMenu(), SLOT(hide()));
261     }
262 #else
263     if(watched == trayMenu() && event->type() == QEvent::HoverLeave) {
264       trayMenu()->hide();
265     }
266 #endif
267   }
268   return StatusNotifierItemParent::eventFilter(watched, event);
269 }
270
271 void StatusNotifierItem::showMessage(const QString &title, const QString &message_, SystemTray::MessageIcon icon, int timeout, uint notificationId) {
272   QString message = message_;
273   if(_notificationsClient->isValid()) {
274     if(_notificationsClientSupportsMarkup)
275       message = Qt::escape(message);
276
277     QStringList actions = QStringList() << "activate" << "View";
278
279     // we always queue notifications right now
280     QDBusReply<uint> reply = _notificationsClient->Notify(title, 0, "quassel", title, message, actions, QVariantMap(), timeout);
281     if(reply.isValid()) {
282       uint dbusid = reply.value();
283       _notificationsIdMap.insert(dbusid, notificationId);
284       _lastNotificationsDBusId = dbusid;
285     }
286   } else
287     StatusNotifierItemParent::showMessage(title, message, icon, timeout, notificationId);
288 }
289
290 void StatusNotifierItem::closeMessage(uint notificationId) {
291   foreach(uint dbusid, _notificationsIdMap.keys()) {
292     if(_notificationsIdMap.value(dbusid) == notificationId) {
293       _notificationsIdMap.remove(dbusid);
294       _notificationsClient->CloseNotification(dbusid);
295     }
296   }
297   _lastNotificationsDBusId = 0;
298 }
299
300 void StatusNotifierItem::notificationClosed(uint dbusid, uint reason) {
301   Q_UNUSED(reason)
302   _lastNotificationsDBusId = 0;
303   emit messageClosed(_notificationsIdMap.take(dbusid));
304 }
305
306 void StatusNotifierItem::notificationInvoked(uint dbusid, const QString &action) {
307   Q_UNUSED(action)
308   emit messageClicked(_notificationsIdMap.value(dbusid, 0));
309 }
310
311 #endif