Improved support for org.freedesktop.Notifications.
[quassel.git] / src / qtui / mainwin.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20 #include "mainwin.h"
21
22 #include "aboutdlg.h"
23 #include "chatwidget.h"
24 #include "bufferview.h"
25 #include "bufferviewconfig.h"
26 #include "bufferviewfilter.h"
27 #include "bufferviewmanager.h"
28 #include "channellistdlg.h"
29 #include "client.h"
30 #include "clientbacklogmanager.h"
31 #include "coreinfodlg.h"
32 #include "coreconnectdlg.h"
33 #include "networkmodel.h"
34 #include "buffermodel.h"
35 #include "nicklistwidget.h"
36 #include "settingsdlg.h"
37 #include "settingspagedlg.h"
38 #include "signalproxy.h"
39 #include "topicwidget.h"
40 #include "inputwidget.h"
41 #include "irclistmodel.h"
42 #include "verticaldock.h"
43 #include "uisettings.h"
44 #include "util.h"
45 #include "qtuisettings.h"
46 #include "jumpkeyhandler.h"
47
48 #include "uisettings.h"
49
50 #include "selectionmodelsynchronizer.h"
51 #include "mappedselectionmodel.h"
52
53 #include "settingspages/aliasessettingspage.h"
54 #include "settingspages/appearancesettingspage.h"
55 #include "settingspages/bufferviewsettingspage.h"
56 #include "settingspages/colorsettingspage.h"
57 #include "settingspages/fontssettingspage.h"
58 #include "settingspages/generalsettingspage.h"
59 #include "settingspages/highlightsettingspage.h"
60 #include "settingspages/identitiessettingspage.h"
61 #include "settingspages/networkssettingspage.h"
62
63
64 #include "debugconsole.h"
65 #include "global.h"
66 #include "qtuistyle.h"
67
68 #include "desktopnotifications.h"
69
70
71 MainWin::MainWin(QtUi *_gui, QWidget *parent)
72   : QMainWindow(parent),
73     gui(_gui),
74     coreLagLabel(new QLabel()),
75     sslLabel(new QLabel()),
76     _titleSetter(this),
77     systray(new QSystemTrayIcon(this)),
78     activeTrayIcon(":/icons/quassel-icon-active.png"),
79     onlineTrayIcon(":/icons/quassel-icon.png"),
80     offlineTrayIcon(":/icons/quassel-icon-offline.png"),
81     trayIconActive(false),
82     timer(new QTimer(this)),
83     channelListDlg(new ChannelListDlg(this)),
84     settingsDlg(new SettingsDlg(this)),
85     debugConsole(new DebugConsole(this)),
86         desktopNotifications(new org::freedesktop::Notifications(
87                 "org.freedesktop.Notifications",
88                 "/org/freedesktop/Notifications",
89                 QDBusConnection::sessionBus(), this)),
90         notificationId(0)
91 {
92   UiSettings uiSettings;
93   loadTranslation(uiSettings.value("Locale", QLocale::system()).value<QLocale>());
94   
95   QString style = uiSettings.value("Style", QString("")).toString();
96   if(style != "") {
97     QApplication::setStyle(style);
98   }
99   
100   ui.setupUi(this);
101   setWindowTitle("Quassel IRC");
102   setWindowIcon(offlineTrayIcon);
103   qApp->setWindowIcon(offlineTrayIcon);
104   systray->setIcon(offlineTrayIcon);
105   setWindowIconText("Quassel IRC");
106
107   statusBar()->showMessage(tr("Waiting for core..."));
108
109   installEventFilter(new JumpKeyHandler(this));
110
111   UiSettings uiSettings;
112   QString style = uiSettings.value("Style", QString("")).toString();
113   if(style != "") {
114     QApplication::setStyle(style);
115   }
116
117   connect(desktopNotifications, SIGNAL(NotificationClosed(uint, uint)), this, SLOT(desktopNotificationClosed(uint, uint)));
118   connect(desktopNotifications, SIGNAL(ActionInvoked(uint, const QString&)), this, SLOT(desktopNotificationInvoked(uint, const QString&)));
119 }
120
121 void MainWin::init() {
122   QtUiSettings s;
123   if(s.value("MainWinSize").isValid())
124     resize(s.value("MainWinSize").toSize());
125   else
126     resize(QSize(800, 500));
127
128   Client::signalProxy()->attachSignal(this, SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)));
129
130   connect(QApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(saveLayout()));
131
132   connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientNetworkCreated(NetworkId)));
133   connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientNetworkRemoved(NetworkId)));
134
135   show();
136
137   statusBar()->showMessage(tr("Not connected to core."));
138
139   // DOCK OPTIONS
140   setDockNestingEnabled(true);
141
142   setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
143   setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
144   setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
145   setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
146
147   // setup stuff...
148   setupMenus();
149   setupViews();
150   setupNickWidget();
151   setupTopicWidget();
152   setupChatMonitor();
153   setupInputWidget();
154   setupStatusBar();
155   setupSystray();
156
157   setupSettingsDlg();
158
159   // restore mainwin state
160   restoreState(s.value("MainWinState").toByteArray());
161
162   // restore locked state of docks  
163   ui.actionLockDockPositions->setChecked(s.value("LockDocks", false).toBool());
164   
165
166   setDisconnectedState();  // Disable menus and stuff
167   showCoreConnectionDlg(true); // autoconnect if appropriate
168
169   // attach the BufferWidget to the BufferModel and the default selection
170   ui.bufferWidget->setModel(Client::bufferModel());
171   ui.bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
172
173   _titleSetter.setModel(Client::bufferModel());
174   _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
175 }
176
177 MainWin::~MainWin() {
178   QtUiSettings s;
179   s.setValue("MainWinSize", size());
180   s.setValue("MainWinPos", pos());
181   s.setValue("MainWinState", saveState());
182 }
183
184 void MainWin::setupMenus() {
185   connect(ui.actionConnectCore, SIGNAL(triggered()), this, SLOT(showCoreConnectionDlg()));
186   connect(ui.actionDisconnectCore, SIGNAL(triggered()), Client::instance(), SLOT(disconnectFromCore()));
187   connect(ui.actionCoreInfo, SIGNAL(triggered()), this, SLOT(showCoreInfoDlg()));
188   connect(ui.actionQuit, SIGNAL(triggered()), QCoreApplication::instance(), SLOT(quit()));
189   connect(ui.actionSettingsDlg, SIGNAL(triggered()), this, SLOT(showSettingsDlg()));
190   // connect(ui.actionDebug_Console, SIGNAL(triggered()), this, SLOT(showDebugConsole()));
191   connect(ui.actionAboutQuassel, SIGNAL(triggered()), this, SLOT(showAboutDlg()));
192   connect(ui.actionAboutQt, SIGNAL(triggered()), QApplication::instance(), SLOT(aboutQt()));
193 }
194
195 void MainWin::setupViews() {
196   addBufferView();
197 }
198
199 void MainWin::addBufferView(int bufferViewConfigId) {
200   addBufferView(Client::bufferViewManager()->bufferViewConfig(bufferViewConfigId));
201 }
202
203 void MainWin::addBufferView(BufferViewConfig *config) {
204   BufferViewDock *dock;
205   if(config)
206     dock = new BufferViewDock(config, this);
207   else
208     dock = new BufferViewDock(this);
209
210   //create the view and initialize it's filter
211   BufferView *view = new BufferView(dock);
212   view->setFilteredModel(Client::bufferModel(), config);
213   view->show();
214
215   connect(&view->showChannelList, SIGNAL(triggered()), this, SLOT(showChannelList()));
216   
217   Client::bufferModel()->synchronizeView(view);
218
219   dock->setWidget(view);
220   dock->show();
221
222   addDockWidget(Qt::LeftDockWidgetArea, dock);
223   ui.menuBufferViews->addAction(dock->toggleViewAction());
224
225   _netViews.append(dock);
226 }
227
228 void MainWin::removeBufferView(int bufferViewConfigId) {
229   QVariant actionData;
230   BufferViewDock *dock;
231   foreach(QAction *action, ui.menuBufferViews->actions()) {
232     actionData = action->data();
233     if(!actionData.isValid())
234       continue;
235
236     dock = qobject_cast<BufferViewDock *>(action->parent());
237     if(dock && actionData.toInt() == bufferViewConfigId) {
238       removeAction(action);
239       dock->deleteLater();
240     }
241   }
242 }
243
244 void MainWin::setupSettingsDlg() {
245   //Category: Appearance
246   settingsDlg->registerSettingsPage(new ColorSettingsPage(settingsDlg));
247   settingsDlg->registerSettingsPage(new FontsSettingsPage(settingsDlg));
248   settingsDlg->registerSettingsPage(new AppearanceSettingsPage(settingsDlg)); //General
249   //Category: Behaviour
250   settingsDlg->registerSettingsPage(new GeneralSettingsPage(settingsDlg));
251   settingsDlg->registerSettingsPage(new HighlightSettingsPage(settingsDlg));
252   settingsDlg->registerSettingsPage(new AliasesSettingsPage(settingsDlg));
253   //Category: General
254   settingsDlg->registerSettingsPage(new IdentitiesSettingsPage(settingsDlg));
255   settingsDlg->registerSettingsPage(new NetworksSettingsPage(settingsDlg));
256   settingsDlg->registerSettingsPage(new BufferViewSettingsPage(settingsDlg));
257 }
258
259 void MainWin::on_actionEditNetworks_triggered() {
260   SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
261   dlg.exec();
262 }
263
264 void MainWin::on_actionManageViews_triggered() {
265   SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
266   dlg.exec();
267 }
268
269 void MainWin::on_actionLockDockPositions_toggled(bool lock) {
270   QList<VerticalDock *> docks = findChildren<VerticalDock *>();
271   foreach(VerticalDock *dock, docks) {
272     dock->showTitle(!lock);
273   }
274   QtUiSettings().setValue("LockDocks", lock);
275 }
276
277 void MainWin::setupNickWidget() {
278   // create nick dock
279   NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
280   nickDock->setObjectName("NickDock");
281   nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
282
283   nickListWidget = new NickListWidget(nickDock);
284   nickDock->setWidget(nickListWidget);
285
286   addDockWidget(Qt::RightDockWidgetArea, nickDock);
287   ui.menuViews->addAction(nickDock->toggleViewAction());
288   // See NickListDock::NickListDock();
289   // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
290
291   // attach the NickListWidget to the BufferModel and the default selection
292   nickListWidget->setModel(Client::bufferModel());
293   nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
294 }
295
296 void MainWin::setupChatMonitor() {
297 #ifndef SPUTDEV
298   VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
299   dock->setObjectName("ChatMonitorDock");
300
301   ChatWidget *chatWidget = new ChatWidget(0, this);
302   chatWidget->show();
303   dock->setWidget(chatWidget);
304   dock->show();
305
306   Buffer *buf = Client::monitorBuffer();
307   if(!buf)
308     return;
309
310   chatWidget->setContents(buf->contents());
311   connect(buf, SIGNAL(msgAppended(AbstractUiMsg *)), chatWidget, SLOT(appendMsg(AbstractUiMsg *)));
312   connect(buf, SIGNAL(msgPrepended(AbstractUiMsg *)), chatWidget, SLOT(prependMsg(AbstractUiMsg *)));
313
314   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
315   ui.menuViews->addAction(dock->toggleViewAction());
316 #endif /* SPUTDEV */
317 }
318
319 void MainWin::setupInputWidget() {
320   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
321   dock->setObjectName("InputDock");
322
323   InputWidget *inputWidget = new InputWidget(dock);
324   dock->setWidget(inputWidget);
325
326   addDockWidget(Qt::BottomDockWidgetArea, dock);
327
328   ui.menuViews->addAction(dock->toggleViewAction());
329
330   inputWidget->setModel(Client::bufferModel());
331   inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
332
333   ui.bufferWidget->setFocusProxy(inputWidget);
334 }
335
336 void MainWin::setupTopicWidget() {
337   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
338   dock->setObjectName("TopicDock");
339   TopicWidget *topicwidget = new TopicWidget(dock);
340   connect(topicwidget, SIGNAL(topicChanged(const QString &)), this, SLOT(changeTopic(const QString &)));
341
342   dock->setWidget(topicwidget);
343
344   topicwidget->setModel(Client::bufferModel());
345   topicwidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
346
347   addDockWidget(Qt::TopDockWidgetArea, dock);
348
349   ui.menuViews->addAction(dock->toggleViewAction());
350 }
351
352 void MainWin::setupStatusBar() {
353   // Core Lag:
354   updateLagIndicator(0);
355   statusBar()->addPermanentWidget(coreLagLabel);
356   connect(Client::signalProxy(), SIGNAL(lagUpdated(int)), this, SLOT(updateLagIndicator(int)));
357
358   // SSL indicator
359   connect(Client::instance(), SIGNAL(securedConnection()), this, SLOT(securedConnection()));
360   sslLabel->setPixmap(QPixmap());
361   statusBar()->addPermanentWidget(sslLabel);
362
363   ui.menuViews->addSeparator();
364   QAction *showStatusbar = ui.menuViews->addAction(tr("Statusbar"));
365   showStatusbar->setCheckable(true);
366
367   UiSettings uiSettings;
368
369   bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
370   showStatusbar->setChecked(enabled);
371   enabled ? statusBar()->show() : statusBar()->hide();
372
373   connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
374   connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
375 }
376
377 void MainWin::saveStatusBarStatus(bool enabled) {
378   UiSettings uiSettings;
379   uiSettings.setValue("ShowStatusBar", enabled);
380 }
381
382 void MainWin::setupSystray() {
383   connect(timer, SIGNAL(timeout()), this, SLOT(makeTrayIconBlink()));
384   connect(Client::instance(), SIGNAL(messageReceived(const Message &)), this, SLOT(receiveMessage(const Message &)));
385
386   systrayMenu = new QMenu(this);
387   systrayMenu->addAction(ui.actionAboutQuassel);
388   systrayMenu->addSeparator();
389   systrayMenu->addAction(ui.actionConnectCore);
390   systrayMenu->addAction(ui.actionDisconnectCore);
391   systrayMenu->addSeparator();
392   systrayMenu->addAction(ui.actionQuit);
393
394   systray->setContextMenu(systrayMenu);
395
396   UiSettings s;
397   if(s.value("UseSystemTrayIcon", QVariant(true)).toBool()) {
398     systray->show();
399   }
400
401 #ifndef Q_WS_MAC
402   connect(systray, SIGNAL(activated( QSystemTrayIcon::ActivationReason )),
403           this, SLOT(systrayActivated( QSystemTrayIcon::ActivationReason )));
404 #endif
405
406 }
407
408 void MainWin::changeEvent(QEvent *event) {
409   if(event->type() == QEvent::WindowStateChange) {
410     if(windowState() & Qt::WindowMinimized) {
411       UiSettings s;
412       if(s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnMinimize").toBool()) {
413         toggleVisibility();
414         event->ignore();
415       }
416     }
417   }
418 }
419
420 // FIXME this should be made prettier...
421 void MainWin::changeTopic(const QString &topic) {
422   BufferId id = ui.bufferWidget->currentBuffer();
423   if(!id.isValid()) return;
424   Buffer *buffer = Client::buffer(id);
425   if(buffer) Client::userInput(buffer->bufferInfo(), QString("/topic %1").arg(topic));
426 }
427
428 void MainWin::connectedToCore() {
429   Q_CHECK_PTR(Client::bufferViewManager());
430   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
431   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
432   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
433
434   foreach(BufferInfo id, Client::allBufferInfos()) {
435     Client::backlogManager()->requestBacklog(id.bufferId(), 500, -1);
436   }
437   setConnectedState();
438 }
439
440 void MainWin::setConnectedState() {
441   //ui.menuCore->setEnabled(true);
442   ui.actionConnectCore->setEnabled(false);
443   ui.actionDisconnectCore->setEnabled(true);
444   ui.actionCoreInfo->setEnabled(true);
445   ui.menuViews->setEnabled(true);
446   ui.bufferWidget->show();
447   statusBar()->showMessage(tr("Connected to core."));
448   setWindowIcon(onlineTrayIcon);
449   qApp->setWindowIcon(onlineTrayIcon);
450   systray->setIcon(onlineTrayIcon);
451   if(sslLabel->width() == 0)
452     sslLabel->setPixmap(QPixmap::fromImage(QImage(":/16x16/status/no-ssl")));
453 }
454
455 void MainWin::loadLayout() {
456   QtUiSettings s;
457   int accountId = Client::currentCoreAccount().toInt();
458   restoreState(s.value(QString("MainWinState-%1").arg(accountId)).toByteArray(), accountId);
459 }
460
461 void MainWin::saveLayout() {
462   QtUiSettings s;
463   int accountId = Client::currentCoreAccount().toInt();
464   if(accountId > 0) s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
465 }
466
467 void MainWin::updateLagIndicator(int lag) {
468   coreLagLabel->setText(QString("Core Lag: %1 msec").arg(lag));
469 }
470
471
472 void MainWin::securedConnection() {
473   // todo: make status bar entry
474   sslLabel->setPixmap(QPixmap::fromImage(QImage(":/16x16/status/ssl")));
475 }
476
477 void MainWin::disconnectedFromCore() {
478   // save core specific layout and remove bufferviews;
479   saveLayout();
480   QVariant actionData;
481   BufferViewDock *dock;
482   foreach(QAction *action, ui.menuBufferViews->actions()) {
483     actionData = action->data();
484     if(!actionData.isValid())
485       continue;
486
487     dock = qobject_cast<BufferViewDock *>(action->parent());
488     if(dock && actionData.toInt() != -1) {
489       removeAction(action);
490       dock->deleteLater();
491     }
492   }
493   QtUiSettings s;
494   restoreState(s.value("MainWinState").toByteArray());
495   setDisconnectedState();
496 }
497
498 void MainWin::setDisconnectedState() {
499   //ui.menuCore->setEnabled(false);
500   ui.actionConnectCore->setEnabled(true);
501   ui.actionDisconnectCore->setEnabled(false);
502   ui.actionCoreInfo->setEnabled(false);
503   ui.menuViews->setEnabled(false);
504   ui.bufferWidget->hide();
505   statusBar()->showMessage(tr("Not connected to core."));
506   setWindowIcon(offlineTrayIcon);
507   qApp->setWindowIcon(offlineTrayIcon);
508   systray->setIcon(offlineTrayIcon);
509   sslLabel->setPixmap(QPixmap());
510 }
511
512 void MainWin::showCoreConnectionDlg(bool autoConnect) {
513   coreConnectDlg = new CoreConnectDlg(this, autoConnect);
514   connect(coreConnectDlg, SIGNAL(finished(int)), this, SLOT(coreConnectionDlgFinished(int)));
515   coreConnectDlg->setModal(true);
516   coreConnectDlg->show();
517 }
518
519 void MainWin::coreConnectionDlgFinished(int /*code*/) {
520   coreConnectDlg->close();
521   //exit(1);
522 }
523
524 void MainWin::showChannelList(NetworkId netId) {
525   if(!netId.isValid()) {
526     QAction *action = qobject_cast<QAction *>(sender());
527     if(action)
528       netId = action->data().value<NetworkId>();
529   }
530   channelListDlg->setNetwork(netId);
531   channelListDlg->show();
532 }
533
534 void MainWin::showCoreInfoDlg() {
535   CoreInfoDlg dlg(this);
536   dlg.exec();
537 }
538
539 void MainWin::showSettingsDlg() {
540   settingsDlg->show();
541 }
542
543 void MainWin::showDebugConsole() {
544   debugConsole->show();
545 }
546
547 void MainWin::showAboutDlg() {
548   AboutDlg dlg(this);
549   dlg.exec();
550 }
551
552 void MainWin::closeEvent(QCloseEvent *event) {
553   UiSettings s;
554   if(s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnClose").toBool()) {
555     toggleVisibility();
556     event->ignore();
557   } else {
558     event->accept();
559   }
560 }
561
562 void MainWin::systrayActivated( QSystemTrayIcon::ActivationReason activationReason) {
563   if(activationReason == QSystemTrayIcon::Trigger) {
564     toggleVisibility();
565   }
566 }
567
568 void MainWin::toggleVisibility() {
569   if(isHidden() /*|| !isActiveWindow()*/) {
570     show();
571     if(isMinimized()) {
572       if(isMaximized())
573         showMaximized();
574       else
575         showNormal();
576     }
577
578     raise();
579     activateWindow();
580     // setFocus(); //Qt::ActiveWindowFocusReason
581
582   } else {
583     if(systray->isSystemTrayAvailable ()) {
584       clearFocus();
585       hide();
586       if(!systray->isVisible()) {
587         systray->show();
588       }
589     } else {
590       lower();
591     }
592   }
593 }
594
595 void MainWin::receiveMessage(const Message &msg) {
596   if(QApplication::activeWindow() != 0)
597     return;
598
599   if(msg.flags() & Message::Highlight || msg.bufferInfo().type() == BufferInfo::QueryBuffer) {
600     QString title = msg.bufferInfo().bufferName();;
601     if(msg.bufferInfo().type() != BufferInfo::QueryBuffer) {
602       QString sender = msg.sender();
603       int i = sender.indexOf("!");
604       if(i != -1)
605         sender = sender.left(i);
606       title += QString(" - %1").arg(sender);
607     }
608
609     UiSettings uiSettings;
610
611 #ifndef SPUTDEV
612     if(uiSettings.value("DisplayPopupMessages", QVariant(true)).toBool()) {
613       // FIXME don't invoke style engine for this!
614       QString text = QtUi::style()->styleString(Message::mircToInternal(msg.contents())).plainText;
615       displayTrayIconMessage(title, text);
616           sendDesktopNotification(title, text);
617     }
618 #endif
619     if(uiSettings.value("AnimateTrayIcon", QVariant(true)).toBool()) {
620       QApplication::alert(this);
621       setTrayIconActivity(true);
622     }
623   }
624 }
625
626 bool MainWin::event(QEvent *event) {
627   if(event->type() == QEvent::WindowActivate)
628     setTrayIconActivity(false);
629   return QMainWindow::event(event);
630 }
631
632
633 /*
634 Using the notification-daemon from Freedesktop's Galago project
635 http://www.galago-project.org/specs/notification/0.9/x408.html#command-notify
636 */
637 void MainWin::sendDesktopNotification(const QString &title, const QString &message)
638 {
639         QStringList actions;
640         QMap<QString, QVariant> hints;
641
642         hints["x"] = 100; // Standard hint: x location for the popup to show up
643         hints["y"] = 100; // Standard hint: y location for the popup to show up
644
645         actions << "click" << "Click Me!";
646
647         QDBusReply<uint> reply = desktopNotifications->Notify(
648                 "Quassel", // Application name
649                 notificationId, // ID of previous notification to replace
650                 "", // Icon to display
651                 title, // Summary / Header of the message to display
652                 QString("%1: %2:\n%2").arg(QTime::currentTime().toString()).arg(title).arg(message), // Body of the message to display
653                 actions, // Actions from which the user may choose
654                 hints, // Hints to the server displaying the message
655                 5000 // Timeout in milliseconds
656         );
657
658         if (!reply.isValid())
659         {
660                 /* ERROR */
661                 qDebug() << "Error on sending notification...";
662                 return;
663         }
664
665         notificationId = reply.value();
666
667         qDebug() << "ID: " << notificationId << " Time: " << QTime::currentTime().toString();
668 }
669
670
671 void MainWin::desktopNotificationClosed(uint id, uint reason)
672 {
673         qDebug() << "OID: " << notificationId << " ID: " << id << " Reason: " << reason << " Time: " << QTime::currentTime().toString();
674         notificationId = 0;
675 }
676
677
678 void MainWin::desktopNotificationInvoked(uint id, const QString & action)
679 {
680         qDebug() << "OID: " << notificationId << " ID: " << id << " Action: " << action << " Time: " << QTime::currentTime().toString();
681 }
682
683
684 void MainWin::displayTrayIconMessage(const QString &title, const QString &message) {
685   systray->showMessage(title, message);
686 }
687
688 void MainWin::setTrayIconActivity(bool active) {
689   if(active) {
690     if(!timer->isActive())
691       timer->start(500);
692   } else {
693     timer->stop();
694     systray->setIcon(onlineTrayIcon);
695   }
696 }
697
698 void MainWin::makeTrayIconBlink() {
699   if(trayIconActive) {
700     systray->setIcon(onlineTrayIcon);
701     trayIconActive = false;
702   } else {
703     systray->setIcon(activeTrayIcon);
704     trayIconActive = true;
705   }
706 }
707
708 void MainWin::clientNetworkCreated(NetworkId id) {
709   const Network *net = Client::network(id);
710   QAction *act = new QAction(net->networkName(), this);
711   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
712   act->setData(QVariant::fromValue<NetworkId>(id));
713   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
714   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
715
716   QAction *beforeAction = 0;
717   foreach(QAction *action, ui.menuNetworks->actions()) {
718     if(action->isSeparator()) {
719       beforeAction = action;
720       break;
721     }
722     if(net->networkName().localeAwareCompare(action->text()) < 0) {
723       beforeAction = action;
724       break;
725     }
726   }
727   Q_CHECK_PTR(beforeAction);
728   ui.menuNetworks->insertAction(beforeAction, act);
729 }
730
731 void MainWin::clientNetworkUpdated() {
732   const Network *net = qobject_cast<const Network *>(sender());
733   if(!net)
734     return;
735
736   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
737   if(!action)
738     return;
739
740   action->setText(net->networkName());
741
742   switch(net->connectionState()) {
743   case Network::Initialized:
744     action->setIcon(QIcon(":/16x16/actions/network-connect"));
745     break;
746   case Network::Disconnected:
747     action->setIcon(QIcon(":/16x16/actions/network-disconnect"));
748     break;
749   default:
750     action->setIcon(QIcon(":/16x16/actions/gear"));
751   }
752 }
753
754 void MainWin::clientNetworkRemoved(NetworkId id) {
755   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
756   if(!action)
757     return;
758   
759   action->deleteLater();
760 }
761
762 void MainWin::connectOrDisconnectFromNet() {
763   QAction *act = qobject_cast<QAction *>(sender());
764   if(!act) return;
765   const Network *net = Client::network(act->data().value<NetworkId>());
766   if(!net) return;
767   if(net->connectionState() == Network::Disconnected) net->requestConnect();
768   else net->requestDisconnect();
769 }
770