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