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