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