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