added session management
[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 "client.h"
33 #include "clientbacklogmanager.h"
34 #include "coreinfodlg.h"
35 #include "coreconnectdlg.h"
36 #include "msgprocessorstatuswidget.h"
37 #include "qtuimessageprocessor.h"
38 #include "qtuiapplication.h"
39 #include "networkmodel.h"
40 #include "buffermodel.h"
41 #include "nicklistwidget.h"
42 #include "settingsdlg.h"
43 #include "settingspagedlg.h"
44 #include "signalproxy.h"
45 #include "topicwidget.h"
46 #include "inputwidget.h"
47 #include "irclistmodel.h"
48 #include "verticaldock.h"
49 #include "uisettings.h"
50 #include "qtuisettings.h"
51 #include "jumpkeyhandler.h"
52 #include "sessionsettings.h"
53
54 #include "selectionmodelsynchronizer.h"
55 #include "mappedselectionmodel.h"
56
57 #include "settingspages/aliasessettingspage.h"
58 #include "settingspages/appearancesettingspage.h"
59 #include "settingspages/bufferviewsettingspage.h"
60 #include "settingspages/colorsettingspage.h"
61 #include "settingspages/fontssettingspage.h"
62 #include "settingspages/generalsettingspage.h"
63 #include "settingspages/highlightsettingspage.h"
64 #include "settingspages/identitiessettingspage.h"
65 #include "settingspages/networkssettingspage.h"
66 #include "settingspages/notificationssettingspage.h"
67
68 #include "global.h"
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 = dynamic_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   Client::signalProxy()->attachSignal(this, SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)));
126
127   connect(QApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(saveLayout()));
128
129   connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientNetworkCreated(NetworkId)));
130   connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientNetworkRemoved(NetworkId)));
131
132   show();
133
134   statusBar()->showMessage(tr("Not connected to core."));
135
136   // DOCK OPTIONS
137   setDockNestingEnabled(true);
138
139   setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
140   setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
141   setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
142   setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
143
144   // setup stuff...
145   setupMenus();
146   setupViews();
147   setupNickWidget();
148   setupTopicWidget();
149   setupChatMonitor();
150   setupInputWidget();
151   setupStatusBar();
152   setupSystray();
153
154   // restore mainwin state
155   restoreState(s.value("MainWinState").toByteArray());
156
157   // restore locked state of docks
158   ui.actionLockDockPositions->setChecked(s.value("LockDocks", false).toBool());
159
160   setDisconnectedState();  // Disable menus and stuff
161   showCoreConnectionDlg(true); // autoconnect if appropriate
162
163   // attach the BufferWidget to the BufferModel and the default selection
164   ui.bufferWidget->setModel(Client::bufferModel());
165   ui.bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
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   foreach(BufferInfo id, Client::allBufferInfos()) {
400     Client::backlogManager()->requestBacklog(id.bufferId(), 500, -1);
401   }
402   setConnectedState();
403 }
404
405 void MainWin::setConnectedState() {
406   //ui.menuCore->setEnabled(true);
407   ui.actionConnectCore->setEnabled(false);
408   ui.actionDisconnectCore->setEnabled(true);
409   ui.actionCoreInfo->setEnabled(true);
410   ui.menuViews->setEnabled(true);
411   ui.bufferWidget->show();
412   statusBar()->showMessage(tr("Connected to core."));
413   setWindowIcon(onlineTrayIcon);
414   qApp->setWindowIcon(onlineTrayIcon);
415   systray->setIcon(onlineTrayIcon);
416   if(sslLabel->width() == 0)
417     sslLabel->setPixmap(QPixmap::fromImage(QImage(":/16x16/status/no-ssl")));
418 }
419
420 void MainWin::loadLayout() {
421   QtUiSettings s;
422   int accountId = Client::currentCoreAccount().toInt();
423   restoreState(s.value(QString("MainWinState-%1").arg(accountId)).toByteArray(), accountId);
424 }
425
426 void MainWin::saveLayout() {
427   QtUiSettings s;
428   int accountId = Client::currentCoreAccount().toInt();
429   if(accountId > 0) s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
430 }
431
432 void MainWin::updateLagIndicator(int lag) {
433   coreLagLabel->setText(QString(tr("Core Lag: %1 msec")).arg(lag));
434 }
435
436
437 void MainWin::securedConnection() {
438   // todo: make status bar entry
439   sslLabel->setPixmap(QPixmap::fromImage(QImage(":/16x16/status/ssl")));
440 }
441
442 void MainWin::disconnectedFromCore() {
443   // save core specific layout and remove bufferviews;
444   saveLayout();
445   QVariant actionData;
446   BufferViewDock *dock;
447   foreach(QAction *action, ui.menuBufferViews->actions()) {
448     actionData = action->data();
449     if(!actionData.isValid())
450       continue;
451
452     dock = qobject_cast<BufferViewDock *>(action->parent());
453     if(dock && actionData.toInt() != -1) {
454       removeAction(action);
455       dock->deleteLater();
456     }
457   }
458   QtUiSettings s;
459   restoreState(s.value("MainWinState").toByteArray());
460   setDisconnectedState();
461 }
462
463 void MainWin::setDisconnectedState() {
464   //ui.menuCore->setEnabled(false);
465   ui.actionConnectCore->setEnabled(true);
466   ui.actionDisconnectCore->setEnabled(false);
467   ui.actionCoreInfo->setEnabled(false);
468   ui.menuViews->setEnabled(false);
469   ui.bufferWidget->hide();
470   statusBar()->showMessage(tr("Not connected to core."));
471   setWindowIcon(offlineTrayIcon);
472   qApp->setWindowIcon(offlineTrayIcon);
473   systray->setIcon(offlineTrayIcon);
474   sslLabel->setPixmap(QPixmap());
475 }
476
477 void MainWin::showCoreConnectionDlg(bool autoConnect) {
478   CoreConnectDlg(autoConnect, this).exec();
479 }
480
481 void MainWin::showChannelList(NetworkId netId) {
482   ChannelListDlg *channelListDlg = new ChannelListDlg();
483
484   if(!netId.isValid()) {
485     QAction *action = qobject_cast<QAction *>(sender());
486     if(action)
487       netId = action->data().value<NetworkId>();
488   }
489
490   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
491   channelListDlg->setNetwork(netId);
492   channelListDlg->show();
493 }
494
495 void MainWin::showCoreInfoDlg() {
496   CoreInfoDlg(this).exec();
497 }
498
499 void MainWin::showSettingsDlg() {
500   SettingsDlg *dlg = new SettingsDlg();
501
502   //Category: Appearance
503   dlg->registerSettingsPage(new ColorSettingsPage(dlg));
504   dlg->registerSettingsPage(new FontsSettingsPage(dlg));
505   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg)); //General
506   //Category: Behaviour
507   dlg->registerSettingsPage(new GeneralSettingsPage(dlg));
508   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
509   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
510   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
511   //Category: General
512   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
513   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
514   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
515
516   dlg->show();
517 }
518
519 void MainWin::showAboutDlg() {
520   AboutDlg(this).exec();
521 }
522
523 void MainWin::closeEvent(QCloseEvent *event) {
524   UiSettings s;
525   if(s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnClose").toBool()) {
526     toggleVisibility();
527     event->ignore();
528   } else {
529     event->accept();
530   }
531 }
532
533 void MainWin::systrayActivated( QSystemTrayIcon::ActivationReason activationReason) {
534   if(activationReason == QSystemTrayIcon::Trigger) {
535     toggleVisibility();
536   }
537 }
538
539 void MainWin::toggleVisibility() {
540   if(isHidden() /*|| !isActiveWindow()*/) {
541     show();
542     if(isMinimized()) {
543       if(isMaximized())
544         showMaximized();
545       else
546         showNormal();
547     }
548
549     raise();
550     activateWindow();
551     // setFocus(); //Qt::ActiveWindowFocusReason
552
553   } else {
554     if(systray->isSystemTrayAvailable ()) {
555       clearFocus();
556       hide();
557       if(!systray->isVisible()) {
558         systray->show();
559       }
560     } else {
561       lower();
562     }
563   }
564 }
565
566 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
567   Q_UNUSED(parent);
568
569   if(QApplication::activeWindow() != 0)
570     return;
571
572   for(int i = start; i <= end; i++) {
573     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
574     if(!idx.isValid()) {
575       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
576       continue;
577     }
578     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
579     if(flags.testFlag(Message::Backlog)) continue;
580     flags |= Message::Backlog;  // we only want to trigger a highlight once!
581     Client::messageModel()->setData(idx, (int)flags, ChatLineModel::FlagsRole);
582
583     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
584     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
585
586     if(flags & Message::Highlight || bufType == BufferInfo::QueryBuffer) {
587       QString title = Client::networkModel()->networkName(bufId) + " - " + Client::networkModel()->bufferName(bufId);
588
589       // FIXME Don't instantiate this for every highlight...
590       UiSettings uiSettings;
591
592       bool displayBubble = uiSettings.value("NotificationBubble", QVariant(true)).toBool();
593       bool displayDesktop = uiSettings.value("NotificationDesktop", QVariant(true)).toBool();
594       if(displayBubble || displayDesktop) {
595         if(uiSettings.value("DisplayPopupMessages", QVariant(true)).toBool()) {
596           QString text = idx.data(ChatLineModel::DisplayRole).toString();
597           if(displayBubble) displayTrayIconMessage(title, text);
598 #   ifdef HAVE_DBUS
599           if(displayDesktop) sendDesktopNotification(title, text);
600 #   endif
601         }
602         if(uiSettings.value("AnimateTrayIcon", QVariant(true)).toBool()) {
603           QApplication::alert(this);
604           setTrayIconActivity(true);
605         }
606       }
607     }
608   }
609 }
610
611 bool MainWin::event(QEvent *event) {
612   if(event->type() == QEvent::WindowActivate)
613     setTrayIconActivity(false);
614   return QMainWindow::event(event);
615 }
616
617 #ifdef HAVE_DBUS
618
619 /*
620 Using the notification-daemon from Freedesktop's Galago project
621 http://www.galago-project.org/specs/notification/0.9/x408.html#command-notify
622 */
623 void MainWin::sendDesktopNotification(const QString &title, const QString &message) {
624   QStringList actions;
625   QMap<QString, QVariant> hints;
626   UiSettings uiSettings;
627
628   hints["x"] = uiSettings.value("NotificationDesktopHintX", QVariant(0)).toInt(); // Standard hint: x location for the popup to show up
629   hints["y"] = uiSettings.value("NotificationDesktopHintY", QVariant(0)).toInt(); // Standard hint: y location for the popup to show up
630
631   actions << "click" << "Click Me!";
632
633   QDBusReply<uint> reply = desktopNotifications->Notify(
634                 "Quassel", // Application name
635                 notificationId, // ID of previous notification to replace
636                 "", // Icon to display
637                 title, // Summary / Header of the message to display
638                 QString("%1: %2:\n%3").arg(QTime::currentTime().toString()).arg(title).arg(message), // Body of the message to display
639                 actions, // Actions from which the user may choose
640                 hints, // Hints to the server displaying the message
641                 uiSettings.value("NotificationDesktopTimeout", QVariant(5000)).toInt() // Timeout in milliseconds
642         );
643
644   if(!reply.isValid()) {
645     /* ERROR */
646     // could also happen if no notification service runs, so... whatever :)
647     //qDebug() << "Error on sending notification..." << reply.error();
648     return;
649   }
650
651   notificationId = reply.value();
652
653   // qDebug() << "ID: " << notificationId << " Time: " << QTime::currentTime().toString();
654 }
655
656
657 void MainWin::desktopNotificationClosed(uint id, uint reason) {
658   Q_UNUSED(id); Q_UNUSED(reason);
659   // qDebug() << "OID: " << notificationId << " ID: " << id << " Reason: " << reason << " Time: " << QTime::currentTime().toString();
660   notificationId = 0;
661 }
662
663
664 void MainWin::desktopNotificationInvoked(uint id, const QString & action) {
665   Q_UNUSED(id); Q_UNUSED(action);
666   // qDebug() << "OID: " << notificationId << " ID: " << id << " Action: " << action << " Time: " << QTime::currentTime().toString();
667 }
668
669 #endif /* HAVE_DBUS */
670
671 void MainWin::displayTrayIconMessage(const QString &title, const QString &message) {
672   systray->showMessage(title, message);
673 }
674
675 void MainWin::setTrayIconActivity(bool active) {
676   if(active) {
677     if(!timer->isActive())
678       timer->start(500);
679   } else {
680     timer->stop();
681     systray->setIcon(onlineTrayIcon);
682   }
683 }
684
685 void MainWin::makeTrayIconBlink() {
686   if(trayIconActive) {
687     systray->setIcon(onlineTrayIcon);
688     trayIconActive = false;
689   } else {
690     systray->setIcon(activeTrayIcon);
691     trayIconActive = true;
692   }
693 }
694
695 void MainWin::clientNetworkCreated(NetworkId id) {
696   const Network *net = Client::network(id);
697   QAction *act = new QAction(net->networkName(), this);
698   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
699   act->setData(QVariant::fromValue<NetworkId>(id));
700   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
701   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
702
703   QAction *beforeAction = 0;
704   foreach(QAction *action, ui.menuNetworks->actions()) {
705     if(action->isSeparator()) {
706       beforeAction = action;
707       break;
708     }
709     if(net->networkName().localeAwareCompare(action->text()) < 0) {
710       beforeAction = action;
711       break;
712     }
713   }
714   Q_CHECK_PTR(beforeAction);
715   ui.menuNetworks->insertAction(beforeAction, act);
716 }
717
718 void MainWin::clientNetworkUpdated() {
719   const Network *net = qobject_cast<const Network *>(sender());
720   if(!net)
721     return;
722
723   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
724   if(!action)
725     return;
726
727   action->setText(net->networkName());
728
729   switch(net->connectionState()) {
730   case Network::Initialized:
731     action->setIcon(QIcon(":/16x16/actions/network-connect"));
732     break;
733   case Network::Disconnected:
734     action->setIcon(QIcon(":/16x16/actions/network-disconnect"));
735     break;
736   default:
737     action->setIcon(QIcon(":/16x16/actions/gear"));
738   }
739 }
740
741 void MainWin::clientNetworkRemoved(NetworkId id) {
742   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
743   if(!action)
744     return;
745
746   action->deleteLater();
747 }
748
749 void MainWin::connectOrDisconnectFromNet() {
750   QAction *act = qobject_cast<QAction *>(sender());
751   if(!act) return;
752   const Network *net = Client::network(act->data().value<NetworkId>());
753   if(!net) return;
754   if(net->connectionState() == Network::Disconnected) net->requestConnect();
755   else net->requestDisconnect();
756 }
757
758
759
760 void MainWin::on_actionDebugNetworkModel_triggered(bool) {
761   QTreeView *view = new QTreeView;
762   view->setAttribute(Qt::WA_DeleteOnClose);
763   view->setWindowTitle("Debug NetworkModel View");
764   view->setModel(Client::networkModel());
765   view->setColumnWidth(0, 250);
766   view->setColumnWidth(1, 250);
767   view->setColumnWidth(2, 80);
768   view->resize(610, 300);
769   view->show();
770 }
771
772 void MainWin::saveStateToSession(const QString &sessionId) {
773   return;
774   SessionSettings s(sessionId);
775   
776   s.setValue("MainWinSize", size());
777   s.setValue("MainWinPos", pos());
778   s.setValue("MainWinState", saveState());
779 }
780
781 void MainWin::saveStateToSessionSettings(SessionSettings & s)
782 {
783   s.setValue("MainWinSize", size());
784   s.setValue("MainWinPos", pos());
785   s.setValue("MainWinState", saveState());
786 }