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