Make sender column clickable
[quassel.git] / src / qtui / mainwin.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 #ifdef HAVE_KDE
23 #  include <KAction>
24 #  include <KActionCollection>
25 #  include <KHelpMenu>
26 #  include <KMenuBar>
27 #  include <KShortcutsDialog>
28 #  include <KStatusBar>
29 #  include <KToolBar>
30 #  include <KWindowSystem>
31 #endif
32
33 #ifdef Q_WS_X11
34 #  include <QX11Info>
35 #endif
36
37 #include "aboutdlg.h"
38 #include "awaylogfilter.h"
39 #include "awaylogview.h"
40 #include "action.h"
41 #include "actioncollection.h"
42 #include "bufferhotlistfilter.h"
43 #include "buffermodel.h"
44 #include "bufferview.h"
45 #include "bufferviewoverlay.h"
46 #include "bufferviewoverlayfilter.h"
47 #include "bufferwidget.h"
48 #include "channellistdlg.h"
49 #include "chatlinemodel.h"
50 #include "chatmonitorfilter.h"
51 #include "chatmonitorview.h"
52 #include "chatview.h"
53 #include "client.h"
54 #include "clientbacklogmanager.h"
55 #include "clientbufferviewconfig.h"
56 #include "clientbufferviewmanager.h"
57 #include "clientignorelistmanager.h"
58 #include "coreconfigwizard.h"
59 #include "coreconnectdlg.h"
60 #include "coreconnection.h"
61 #include "coreconnectionstatuswidget.h"
62 #include "coreinfodlg.h"
63 #include "contextmenuactionprovider.h"
64 #include "debugbufferviewoverlay.h"
65 #include "debuglogwidget.h"
66 #include "debugmessagemodelfilter.h"
67 #include "flatproxymodel.h"
68 #include "iconloader.h"
69 #include "inputwidget.h"
70 #include "irclistmodel.h"
71 #include "ircconnectionwizard.h"
72 #include "jumpkeyhandler.h"
73 #include "msgprocessorstatuswidget.h"
74 #include "nicklistwidget.h"
75 #include "qtuiapplication.h"
76 #include "qtuimessageprocessor.h"
77 #include "qtuisettings.h"
78 #include "qtuistyle.h"
79 #include "settingsdlg.h"
80 #include "settingspagedlg.h"
81 #include "systemtray.h"
82 #include "toolbaractionprovider.h"
83 #include "topicwidget.h"
84 #include "verticaldock.h"
85
86 #ifndef HAVE_KDE
87 #  ifdef HAVE_DBUS
88 #    include "desktopnotificationbackend.h"
89 #  endif
90 #  ifdef HAVE_PHONON
91 #    include "phononnotificationbackend.h"
92 #  endif
93 #  include "systraynotificationbackend.h"
94 #  include "taskbarnotificationbackend.h"
95 #else /* HAVE_KDE */
96 #  include "knotificationbackend.h"
97 #endif /* HAVE_KDE */
98
99 #ifdef HAVE_SSL
100 #  include "sslinfodlg.h"
101 #endif
102
103 #ifdef HAVE_INDICATEQT
104   #include "indicatornotificationbackend.h"
105 #endif
106
107 #include "settingspages/aliasessettingspage.h"
108 #include "settingspages/appearancesettingspage.h"
109 #include "settingspages/backlogsettingspage.h"
110 #include "settingspages/bufferviewsettingspage.h"
111 #include "settingspages/chatmonitorsettingspage.h"
112 #include "settingspages/chatviewsettingspage.h"
113 #include "settingspages/connectionsettingspage.h"
114 #include "settingspages/coreaccountsettingspage.h"
115 #include "settingspages/coreconnectionsettingspage.h"
116 #include "settingspages/highlightsettingspage.h"
117 #include "settingspages/identitiessettingspage.h"
118 #include "settingspages/ignorelistsettingspage.h"
119 #include "settingspages/inputwidgetsettingspage.h"
120 #include "settingspages/itemviewsettingspage.h"
121 #include "settingspages/networkssettingspage.h"
122 #include "settingspages/notificationssettingspage.h"
123 #include "settingspages/topicwidgetsettingspage.h"
124
125 MainWin::MainWin(QWidget *parent)
126 #ifdef HAVE_KDE
127   : KMainWindow(parent),
128   _kHelpMenu(new KHelpMenu(this, KGlobal::mainComponent().aboutData())),
129 #else
130   : QMainWindow(parent),
131 #endif
132     _msgProcessorStatusWidget(new MsgProcessorStatusWidget(this)),
133     _coreConnectionStatusWidget(new CoreConnectionStatusWidget(Client::coreConnection(), this)),
134     _titleSetter(this),
135     _awayLog(0),
136     _layoutLoaded(false)
137 {
138 #ifdef Q_WS_WIN
139   dwTickCount = 0;
140 #endif
141
142   QtUiSettings uiSettings;
143   QString style = uiSettings.value("Style", QString()).toString();
144   if(!style.isEmpty()) {
145     QApplication::setStyle(style);
146   }
147
148   QApplication::setQuitOnLastWindowClosed(false);
149
150   setWindowTitle("Quassel IRC");
151   setWindowIconText("Quassel IRC");
152   updateIcon();
153
154   installEventFilter(new JumpKeyHandler(this));
155 }
156
157 void MainWin::init() {
158   connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), SLOT(clientNetworkCreated(NetworkId)));
159   connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), SLOT(clientNetworkRemoved(NetworkId)));
160   connect(Client::messageModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
161            SLOT(messagesInserted(const QModelIndex &, int, int)));
162   connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showChannelList(NetworkId)), SLOT(showChannelList(NetworkId)));
163   connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showIgnoreList(QString)), SLOT(showIgnoreList(QString)));
164
165   connect(Client::coreConnection(), SIGNAL(startCoreSetup(QVariantList)), SLOT(showCoreConfigWizard(QVariantList)));
166   connect(Client::coreConnection(), SIGNAL(connectionErrorPopup(QString)), SLOT(handleCoreConnectionError(QString)));
167   connect(Client::coreConnection(), SIGNAL(userAuthenticationRequired(CoreAccount *, bool *, QString)), SLOT(userAuthenticationRequired(CoreAccount *, bool *, QString)));
168   connect(Client::coreConnection(), SIGNAL(handleNoSslInClient(bool*)), SLOT(handleNoSslInClient(bool *)));
169   connect(Client::coreConnection(), SIGNAL(handleNoSslInCore(bool*)), SLOT(handleNoSslInCore(bool *)));
170 #ifdef HAVE_SSL
171   connect(Client::coreConnection(), SIGNAL(handleSslErrors(const QSslSocket *, bool *, bool *)), SLOT(handleSslErrors(const QSslSocket *, bool *, bool *)));
172 #endif
173
174   // Setup Dock Areas
175   setDockNestingEnabled(true);
176   setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
177   setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
178   setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
179   setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
180
181   // Order is sometimes important
182   setupActions();
183   setupBufferWidget();
184   setupMenus();
185   setupTopicWidget();
186   setupNickWidget();
187   setupInputWidget();
188   setupChatMonitor();
189   setupStatusBar();
190   setupToolBars();
191   setupSystray();
192   setupTitleSetter();
193   setupHotList();
194
195 #ifndef HAVE_KDE
196   QtUi::registerNotificationBackend(new TaskbarNotificationBackend(this));
197 #  ifndef QT_NO_SYSTEMTRAYICON
198   QtUi::registerNotificationBackend(new SystrayNotificationBackend(this));
199 #  endif
200 #  ifdef HAVE_PHONON
201   QtUi::registerNotificationBackend(new PhononNotificationBackend(this));
202 #  endif
203 #  ifdef HAVE_DBUS
204   QtUi::registerNotificationBackend(new DesktopNotificationBackend(this));
205 #  endif
206
207 #else /* HAVE_KDE */
208   QtUi::registerNotificationBackend(new KNotificationBackend(this));
209 #endif /* HAVE_KDE */
210
211 #ifdef HAVE_INDICATEQT
212   QtUi::registerNotificationBackend(new IndicatorNotificationBackend(this));
213 #endif
214
215   connect(bufferWidget(), SIGNAL(currentChanged(BufferId)), SLOT(currentBufferChanged(BufferId)));
216
217   setDisconnectedState();  // Disable menus and stuff
218
219 #ifdef HAVE_KDE
220   setAutoSaveSettings();
221 #endif
222
223   // restore mainwin state
224   QtUiSettings s;
225   restoreStateFromSettings(s);
226
227   // restore locked state of docks
228   QtUi::actionCollection("General")->action("LockLayout")->setChecked(s.value("LockLayout", false).toBool());
229
230   CoreConnection *conn = Client::coreConnection();
231   if(!conn->connectToCore()) {
232     // No autoconnect selected (or no accounts)
233     showCoreConnectionDlg();
234   }
235 }
236
237 MainWin::~MainWin() {
238
239 }
240
241 void MainWin::quit() {
242   QtUiSettings s;
243   saveStateToSettings(s);
244   saveLayout();
245   QApplication::quit();
246 }
247
248 void MainWin::saveStateToSettings(UiSettings &s) {
249   s.setValue("MainWinSize", _normalSize);
250   s.setValue("MainWinPos", _normalPos);
251   s.setValue("MainWinState", saveState());
252   s.setValue("MainWinGeometry", saveGeometry());
253   s.setValue("MainWinMinimized", isMinimized());
254   s.setValue("MainWinMaximized", isMaximized());
255   s.setValue("MainWinHidden", !isVisible());
256
257 #ifdef HAVE_KDE
258   saveAutoSaveSettings();
259 #endif
260 }
261
262 void MainWin::restoreStateFromSettings(UiSettings &s) {
263   _normalSize = s.value("MainWinSize", size()).toSize();
264   _normalPos = s.value("MainWinPos", pos()).toPoint();
265   bool maximized = s.value("MainWinMaximized", false).toBool();
266
267 #ifndef HAVE_KDE
268   restoreGeometry(s.value("MainWinGeometry").toByteArray());
269
270   if(maximized) {
271     // restoreGeometry() fails if the windows was maximized, so we resize and position explicitly
272     resize(_normalSize);
273     move(_normalPos);
274   }
275
276   restoreState(s.value("MainWinState").toByteArray());
277
278 #else
279   move(_normalPos);
280 #endif
281
282 #ifndef QT_NO_SYSTEMTRAYICON
283   if(s.value("MainWinHidden").toBool()) {
284     hideToTray();
285     return;
286   }
287 #endif
288   if(s.value("MainWinMinimized").toBool())
289     showMinimized();
290   else if(maximized)
291     showMaximized();
292   else
293     show();
294 }
295
296 void MainWin::updateIcon() {
297 #ifdef Q_WS_MAC
298   const int size = 128;
299 #else
300   const int size = 48;
301 #endif
302
303   QPixmap icon;
304   if(Client::isConnected())
305     icon = DesktopIcon("quassel", size);
306   else
307     icon = DesktopIcon("quassel_inactive", size);
308   setWindowIcon(icon);
309   qApp->setWindowIcon(icon);
310 }
311
312 void MainWin::setupActions() {
313   ActionCollection *coll = QtUi::actionCollection("General");
314   // File
315   coll->addAction("ConnectCore", new Action(SmallIcon("network-connect"), tr("&Connect to Core..."), coll,
316                                              this, SLOT(showCoreConnectionDlg())));
317   coll->addAction("DisconnectCore", new Action(SmallIcon("network-disconnect"), tr("&Disconnect from Core"), coll,
318                                                 Client::instance(), SLOT(disconnectFromCore())));
319   coll->addAction("CoreInfo", new Action(SmallIcon("help-about"), tr("Core &Info..."), coll,
320                                           this, SLOT(showCoreInfoDlg())));
321   coll->addAction("ConfigureNetworks", new Action(SmallIcon("configure"), tr("Configure &Networks..."), coll,
322                                               this, SLOT(on_actionConfigureNetworks_triggered())));
323   coll->addAction("Quit", new Action(SmallIcon("application-exit"), tr("&Quit"), coll,
324                                       this, SLOT(quit()), tr("Ctrl+Q")));
325
326   // View
327   coll->addAction("ConfigureBufferViews", new Action(tr("&Configure Chat Lists..."), coll,
328                                              this, SLOT(on_actionConfigureViews_triggered())));
329
330   QAction *lockAct = coll->addAction("LockLayout", new Action(tr("&Lock Layout"), coll));
331   lockAct->setCheckable(true);
332   connect(lockAct, SIGNAL(toggled(bool)), SLOT(on_actionLockLayout_toggled(bool)));
333
334   coll->addAction("ToggleSearchBar", new Action(SmallIcon("edit-find"), tr("Show &Search Bar"), coll,
335                                                 0, 0, QKeySequence::Find))->setCheckable(true);
336   coll->addAction("ShowAwayLog", new Action(tr("Show Away Log"), coll,
337                                             this, SLOT(showAwayLog())));
338   coll->addAction("ToggleMenuBar", new Action(SmallIcon("show-menu"), tr("Show &Menubar"), coll,
339                                                 0, 0, tr("Ctrl+M")))->setCheckable(true);
340
341   coll->addAction("ToggleStatusBar", new Action(tr("Show Status &Bar"), coll,
342                                                 0, 0))->setCheckable(true);
343
344   // Settings
345   coll->addAction("ConfigureQuassel", new Action(SmallIcon("configure"), tr("&Configure Quassel..."), coll,
346                                                   this, SLOT(showSettingsDlg()), tr("F7")));
347
348   // Help
349   coll->addAction("AboutQuassel", new Action(SmallIcon("quassel"), tr("&About Quassel"), coll,
350                                               this, SLOT(showAboutDlg())));
351   coll->addAction("AboutQt", new Action(QIcon(":/pics/qt-logo.png"), tr("About &Qt"), coll,
352                                          qApp, SLOT(aboutQt())));
353   coll->addAction("DebugNetworkModel", new Action(SmallIcon("tools-report-bug"), tr("Debug &NetworkModel"), coll,
354                                        this, SLOT(on_actionDebugNetworkModel_triggered())));
355   coll->addAction("DebugBufferViewOverlay", new Action(SmallIcon("tools-report-bug"), tr("Debug &BufferViewOverlay"), coll,
356                                        this, SLOT(on_actionDebugBufferViewOverlay_triggered())));
357   coll->addAction("DebugMessageModel", new Action(SmallIcon("tools-report-bug"), tr("Debug &MessageModel"), coll,
358                                        this, SLOT(on_actionDebugMessageModel_triggered())));
359   coll->addAction("DebugHotList", new Action(SmallIcon("tools-report-bug"), tr("Debug &HotList"), coll,
360                                        this, SLOT(on_actionDebugHotList_triggered())));
361   coll->addAction("DebugLog", new Action(SmallIcon("tools-report-bug"), tr("Debug &Log"), coll,
362                                        this, SLOT(on_actionDebugLog_triggered())));
363   coll->addAction("ReloadStyle", new Action(SmallIcon("view-refresh"), tr("Reload Stylesheet"), coll,
364                                        QtUi::style(), SLOT(reload()), QKeySequence::Refresh));
365
366   // Navigation
367   coll->addAction("JumpHotBuffer", new Action(tr("Jump to hot chat"), coll,
368                                               this, SLOT(on_jumpHotBuffer_triggered()), QKeySequence(Qt::META + Qt::Key_A)));
369 }
370
371 void MainWin::setupMenus() {
372   ActionCollection *coll = QtUi::actionCollection("General");
373
374   _fileMenu = menuBar()->addMenu(tr("&File"));
375
376   static const QStringList coreActions = QStringList()
377     << "ConnectCore" << "DisconnectCore" << "CoreInfo";
378
379   QAction *coreAction;
380   foreach(QString actionName, coreActions) {
381     coreAction = coll->action(actionName);
382     _fileMenu->addAction(coreAction);
383     flagRemoteCoreOnly(coreAction);
384   }
385   flagRemoteCoreOnly(_fileMenu->addSeparator());
386
387   _networksMenu = _fileMenu->addMenu(tr("&Networks"));
388   _networksMenu->addAction(coll->action("ConfigureNetworks"));
389   _networksMenu->addSeparator();
390   _fileMenu->addSeparator();
391   _fileMenu->addAction(coll->action("Quit"));
392
393   _viewMenu = menuBar()->addMenu(tr("&View"));
394   _bufferViewsMenu = _viewMenu->addMenu(tr("&Chat Lists"));
395   _bufferViewsMenu->addAction(coll->action("ConfigureBufferViews"));
396   _toolbarMenu = _viewMenu->addMenu(tr("&Toolbars"));
397   _viewMenu->addSeparator();
398
399   _viewMenu->addAction(coll->action("ToggleMenuBar"));
400   _viewMenu->addAction(coll->action("ToggleStatusBar"));
401   _viewMenu->addAction(coll->action("ToggleSearchBar"));
402
403   coreAction = coll->action("ShowAwayLog");
404   flagRemoteCoreOnly(coreAction);
405   _viewMenu->addAction(coreAction);
406
407   _viewMenu->addSeparator();
408   _viewMenu->addAction(coll->action("LockLayout"));
409
410   _settingsMenu = menuBar()->addMenu(tr("&Settings"));
411 #ifdef HAVE_KDE
412   _settingsMenu->addAction(KStandardAction::configureNotifications(this, SLOT(showNotificationsDlg()), this));
413   _settingsMenu->addAction(KStandardAction::keyBindings(this, SLOT(showShortcutsDlg()), this));
414 #endif
415   _settingsMenu->addAction(coll->action("ConfigureQuassel"));
416
417   _helpMenu = menuBar()->addMenu(tr("&Help"));
418   _helpMenu->addAction(coll->action("AboutQuassel"));
419 #ifndef HAVE_KDE
420   _helpMenu->addAction(coll->action("AboutQt"));
421 #else
422   _helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, SLOT(aboutKDE()), this));
423 #endif
424   _helpMenu->addSeparator();
425   _helpDebugMenu = _helpMenu->addMenu(SmallIcon("tools-report-bug"), tr("Debug"));
426   _helpDebugMenu->addAction(coll->action("DebugNetworkModel"));
427   _helpDebugMenu->addAction(coll->action("DebugBufferViewOverlay"));
428   _helpDebugMenu->addAction(coll->action("DebugMessageModel"));
429   _helpDebugMenu->addAction(coll->action("DebugHotList"));
430   _helpDebugMenu->addAction(coll->action("DebugLog"));
431   _helpDebugMenu->addSeparator();
432   _helpDebugMenu->addAction(coll->action("ReloadStyle"));
433
434   // Toggle visibility
435   QAction *showMenuBar = QtUi::actionCollection("General")->action("ToggleMenuBar");
436
437   QtUiSettings uiSettings;
438   bool enabled = uiSettings.value("ShowMenuBar", QVariant(true)).toBool();
439   showMenuBar->setChecked(enabled);
440   enabled ? menuBar()->show() : menuBar()->hide();
441
442   connect(showMenuBar, SIGNAL(toggled(bool)), menuBar(), SLOT(setVisible(bool)));
443   connect(showMenuBar, SIGNAL(toggled(bool)), this, SLOT(saveMenuBarStatus(bool)));
444 }
445
446 void MainWin::setupBufferWidget() {
447   _bufferWidget = new BufferWidget(this);
448   _bufferWidget->setModel(Client::bufferModel());
449   _bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
450   setCentralWidget(_bufferWidget);
451 }
452
453 void MainWin::addBufferView(int bufferViewConfigId) {
454   addBufferView(Client::bufferViewManager()->clientBufferViewConfig(bufferViewConfigId));
455 }
456
457 void MainWin::addBufferView(ClientBufferViewConfig *config) {
458   if(!config)
459     return;
460
461   config->setLocked(QtUiSettings().value("LockLayout", false).toBool());
462   BufferViewDock *dock = new BufferViewDock(config, this);
463
464   //create the view and initialize it's filter
465   BufferView *view = new BufferView(dock);
466   view->setFilteredModel(Client::bufferModel(), config);
467   view->installEventFilter(_inputWidget); // for key presses
468
469   Client::bufferModel()->synchronizeView(view);
470
471   dock->setWidget(view);
472   dock->setVisible(_layoutLoaded); // don't show before state has been restored
473
474   addDockWidget(Qt::LeftDockWidgetArea, dock);
475   _bufferViewsMenu->addAction(dock->toggleViewAction());
476
477   connect(dock->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(bufferViewToggled(bool)));
478   _bufferViews.append(dock);
479 }
480
481 void MainWin::removeBufferView(int bufferViewConfigId) {
482   QVariant actionData;
483   BufferViewDock *dock;
484   foreach(QAction *action, _bufferViewsMenu->actions()) {
485     actionData = action->data();
486     if(!actionData.isValid())
487       continue;
488
489     dock = qobject_cast<BufferViewDock *>(action->parent());
490     if(dock && actionData.toInt() == bufferViewConfigId) {
491       removeAction(action);
492       _bufferViews.removeAll(dock);
493       Client::bufferViewOverlay()->removeView(dock->bufferViewId());
494       dock->deleteLater();
495     }
496   }
497 }
498
499 void MainWin::bufferViewToggled(bool enabled) {
500   QAction *action = qobject_cast<QAction *>(sender());
501   Q_ASSERT(action);
502   BufferViewDock *dock = qobject_cast<BufferViewDock *>(action->parent());
503   Q_ASSERT(dock);
504
505   // Make sure we don't toggle backlog fetch for a view we've already removed
506   if(!_bufferViews.contains(dock))
507     return;
508
509   if(enabled) {
510     Client::bufferViewOverlay()->addView(dock->bufferViewId());
511     BufferViewConfig *config = dock->config();
512     if(config && config->isInitialized()) {
513       BufferIdList buffers;
514       if(config->networkId().isValid()) {
515         foreach(BufferId bufferId, config->bufferList()) {
516           if(Client::networkModel()->networkId(bufferId) == config->networkId())
517             buffers << bufferId;
518         }
519         foreach(BufferId bufferId, config->temporarilyRemovedBuffers().toList()) {
520           if(Client::networkModel()->networkId(bufferId) == config->networkId())
521             buffers << bufferId;
522         }
523       } else {
524         buffers = BufferIdList::fromSet(config->bufferList().toSet() + config->temporarilyRemovedBuffers());
525       }
526       Client::backlogManager()->checkForBacklog(buffers);
527     }
528   } else {
529     Client::bufferViewOverlay()->removeView(dock->bufferViewId());
530   }
531 }
532
533 BufferView *MainWin::allBuffersView() const {
534   // "All Buffers" is always the first dock created
535   if(_bufferViews.count() > 0)
536     return _bufferViews[0]->bufferView();
537   return 0;
538 }
539
540 void MainWin::showNotificationsDlg() {
541   SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
542   dlg.exec();
543 }
544
545 void MainWin::on_actionConfigureNetworks_triggered() {
546   SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
547   dlg.exec();
548 }
549
550 void MainWin::on_actionConfigureViews_triggered() {
551   SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
552   dlg.exec();
553 }
554
555 void MainWin::on_actionLockLayout_toggled(bool lock) {
556   QList<VerticalDock *> docks = findChildren<VerticalDock *>();
557   foreach(VerticalDock *dock, docks) {
558     dock->showTitle(!lock);
559   }
560   if(Client::bufferViewManager()) {
561     foreach(ClientBufferViewConfig *config, Client::bufferViewManager()->clientBufferViewConfigs()) {
562       config->setLocked(lock);
563     }
564   }
565   QtUiSettings().setValue("LockLayout", lock);
566 }
567
568 void MainWin::setupNickWidget() {
569   // create nick dock
570   NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
571   nickDock->setObjectName("NickDock");
572   nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
573
574   _nickListWidget = new NickListWidget(nickDock);
575   nickDock->setWidget(_nickListWidget);
576
577   addDockWidget(Qt::RightDockWidgetArea, nickDock);
578   _viewMenu->addAction(nickDock->toggleViewAction());
579   nickDock->toggleViewAction()->setText(tr("Show Nick List"));
580
581   // See NickListDock::NickListDock();
582   // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
583
584   // attach the NickListWidget to the BufferModel and the default selection
585   _nickListWidget->setModel(Client::bufferModel());
586   _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
587 }
588
589 void MainWin::setupChatMonitor() {
590   VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
591   dock->setObjectName("ChatMonitorDock");
592
593   ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
594   _chatMonitorView = new ChatMonitorView(filter, this);
595   _chatMonitorView->setFocusProxy(_inputWidget);
596   _chatMonitorView->show();
597   dock->setWidget(_chatMonitorView);
598   dock->hide();
599
600   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
601   _viewMenu->addAction(dock->toggleViewAction());
602   dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
603 }
604
605 void MainWin::setupInputWidget() {
606   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
607   dock->setObjectName("InputDock");
608
609   _inputWidget = new InputWidget(dock);
610   dock->setWidget(_inputWidget);
611
612   addDockWidget(Qt::BottomDockWidgetArea, dock);
613
614   _viewMenu->addAction(dock->toggleViewAction());
615   dock->toggleViewAction()->setText(tr("Show Input Line"));
616
617   _inputWidget->setModel(Client::bufferModel());
618   _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
619
620   _bufferWidget->setFocusProxy(_inputWidget);
621
622   _inputWidget->inputLine()->installEventFilter(_bufferWidget);
623
624   connect(_topicWidget, SIGNAL(switchedPlain()), _bufferWidget, SLOT(setFocus()));
625 }
626
627 void MainWin::setupTopicWidget() {
628   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
629   dock->setObjectName("TopicDock");
630   _topicWidget = new TopicWidget(dock);
631
632   dock->setWidget(_topicWidget);
633
634   _topicWidget->setModel(Client::bufferModel());
635   _topicWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
636
637   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
638
639   _viewMenu->addAction(dock->toggleViewAction());
640   dock->toggleViewAction()->setText(tr("Show Topic Line"));
641 }
642
643 void MainWin::setupTitleSetter() {
644   _titleSetter.setModel(Client::bufferModel());
645   _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
646 }
647
648 void MainWin::setupStatusBar() {
649   // MessageProcessor progress
650   statusBar()->addPermanentWidget(_msgProcessorStatusWidget);
651
652   // Connection state
653   _coreConnectionStatusWidget->update();
654   statusBar()->addPermanentWidget(_coreConnectionStatusWidget);
655
656   QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
657
658   QtUiSettings uiSettings;
659
660   bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
661   showStatusbar->setChecked(enabled);
662   enabled ? statusBar()->show() : statusBar()->hide();
663
664   connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
665   connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
666
667   connect(Client::coreConnection(), SIGNAL(connectionMsg(QString)), statusBar(), SLOT(showMessage(QString)));
668 }
669
670 void MainWin::setupHotList() {
671   FlatProxyModel *flatProxy = new FlatProxyModel(this);
672   flatProxy->setSourceModel(Client::bufferModel());
673   _bufferHotList = new BufferHotListFilter(flatProxy);
674 }
675
676 void MainWin::saveMenuBarStatus(bool enabled) {
677   QtUiSettings uiSettings;
678   uiSettings.setValue("ShowMenuBar", enabled);
679 }
680
681 void MainWin::saveStatusBarStatus(bool enabled) {
682   QtUiSettings uiSettings;
683   uiSettings.setValue("ShowStatusBar", enabled);
684 }
685
686 void MainWin::setupSystray() {
687 #ifndef QT_NO_SYSTEMTRAYICON
688   _systemTray = new SystemTray(this);
689 #endif
690 }
691
692 void MainWin::setupToolBars() {
693   connect(_bufferWidget, SIGNAL(currentChanged(QModelIndex)),
694           QtUi::toolBarActionProvider(), SLOT(currentBufferChanged(QModelIndex)));
695   connect(_nickListWidget, SIGNAL(nickSelectionChanged(QModelIndexList)),
696           QtUi::toolBarActionProvider(), SLOT(nickSelectionChanged(QModelIndexList)));
697
698 #ifdef Q_WS_MAC
699   setUnifiedTitleAndToolBarOnMac(true);
700 #endif
701
702 #ifdef HAVE_KDE
703   _mainToolBar = new KToolBar("MainToolBar", this, Qt::TopToolBarArea, false, true, true);
704 #else
705   _mainToolBar = new QToolBar(this);
706   _mainToolBar->setObjectName("MainToolBar");
707 #endif
708   _mainToolBar->setWindowTitle(tr("Main Toolbar"));
709   addToolBar(_mainToolBar);
710
711   QtUi::toolBarActionProvider()->addActions(_mainToolBar, ToolBarActionProvider::MainToolBar);
712   _toolbarMenu->addAction(_mainToolBar->toggleViewAction());
713 }
714
715 void MainWin::connectedToCore() {
716   Q_CHECK_PTR(Client::bufferViewManager());
717   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
718   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
719   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
720
721   setConnectedState();
722 }
723
724 void MainWin::setConnectedState() {
725   ActionCollection *coll = QtUi::actionCollection("General");
726
727   coll->action("ConnectCore")->setEnabled(false);
728   coll->action("DisconnectCore")->setEnabled(true);
729   coll->action("CoreInfo")->setEnabled(true);
730
731   foreach(QAction *action, _fileMenu->actions()) {
732     if(isRemoteCoreOnly(action))
733       action->setVisible(!Client::internalCore());
734   }
735
736   disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
737   disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
738   disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
739   if(!Client::internalCore()) {
740     connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
741     connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
742     connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
743   }
744
745   // _viewMenu->setEnabled(true);
746   if(!Client::internalCore())
747     statusBar()->showMessage(tr("Connected to core."));
748   else
749     statusBar()->clearMessage();
750
751   _coreConnectionStatusWidget->setVisible(!Client::internalCore());
752   updateIcon();
753 #ifndef QT_NO_SYSTEMTRAYICON
754   systemTray()->setState(SystemTray::Active);
755 #endif
756
757   if(Client::networkIds().isEmpty()) {
758     IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
759     wizard->show();
760   }
761 }
762
763 void MainWin::loadLayout() {
764   QtUiSettings s;
765   int accountId = Client::currentCoreAccount().accountId().toInt();
766   QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
767   if(state.isEmpty()) {
768     // Make sure that the default bufferview is shown
769     if(_bufferViews.count())
770       _bufferViews.at(0)->show();
771     return;
772   }
773
774   restoreState(state, accountId);
775   _layoutLoaded = true;
776 }
777
778 void MainWin::saveLayout() {
779   QtUiSettings s;
780   int accountId = Client::currentCoreAccount().accountId().toInt();
781   if(accountId > 0) s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
782 }
783
784 void MainWin::disconnectedFromCore() {
785   // save core specific layout and remove bufferviews;
786   saveLayout();
787   _layoutLoaded = false;
788
789   QVariant actionData;
790   BufferViewDock *dock;
791   foreach(QAction *action, _bufferViewsMenu->actions()) {
792     actionData = action->data();
793     if(!actionData.isValid())
794       continue;
795
796     dock = qobject_cast<BufferViewDock *>(action->parent());
797     if(dock && actionData.toInt() != -1) {
798       removeAction(action);
799       _bufferViews.removeAll(dock);
800       Client::bufferViewOverlay()->removeView(dock->bufferViewId());
801       dock->deleteLater();
802     }
803   }
804
805   QtUiSettings s;
806   restoreState(s.value("MainWinState").toByteArray());
807   setDisconnectedState();
808 }
809
810 void MainWin::setDisconnectedState() {
811   ActionCollection *coll = QtUi::actionCollection("General");
812   //ui.menuCore->setEnabled(false);
813   coll->action("ConnectCore")->setEnabled(true);
814   coll->action("DisconnectCore")->setEnabled(false);
815   coll->action("CoreInfo")->setEnabled(false);
816   //_viewMenu->setEnabled(false);
817   statusBar()->showMessage(tr("Not connected to core."));
818   if(_msgProcessorStatusWidget)
819     _msgProcessorStatusWidget->setProgress(0, 0);
820   updateIcon();
821 #ifndef QT_NO_SYSTEMTRAYICON
822   systemTray()->setState(SystemTray::Inactive);
823 #endif
824 }
825
826 void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage) {
827   Q_UNUSED(errorMessage)
828   CoreConnectAuthDlg dlg(account, this);
829   *valid = (dlg.exec() == QDialog::Accepted);
830 }
831
832 void MainWin::handleNoSslInClient(bool *accepted) {
833   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
834                   QMessageBox::Ignore|QMessageBox::Cancel, this);
835   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
836   box.setDefaultButton(QMessageBox::Ignore);
837   *accepted = box.exec() == QMessageBox::Ignore;
838 }
839
840 void MainWin::handleNoSslInCore(bool *accepted) {
841   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
842                   QMessageBox::Ignore|QMessageBox::Cancel, this);
843   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
844   box.setDefaultButton(QMessageBox::Ignore);
845   *accepted = box.exec() == QMessageBox::Ignore;
846
847 }
848
849 #ifdef HAVE_SSL
850
851 void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently) {
852   QString errorString = "<ul>";
853   foreach(const QSslError error, socket->sslErrors())
854     errorString += QString("<li>%1</li>").arg(error.errorString());
855   errorString += "</ul>";
856
857   QMessageBox box(QMessageBox::Warning,
858                   tr("Untrusted Security Certificate"),
859                   tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
860                   QMessageBox::Cancel, this);
861   box.setInformativeText(errorString);
862   box.addButton(tr("Continue"), QMessageBox::AcceptRole);
863   box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
864
865   QMessageBox::ButtonRole role;
866   do {
867     box.exec();
868     role = box.buttonRole(box.clickedButton());
869     if(role == QMessageBox::HelpRole) {
870       SslInfoDlg dlg(socket, this);
871       dlg.exec();
872     }
873   } while(role == QMessageBox::HelpRole);
874
875   *accepted = role == QMessageBox::AcceptRole;
876   if(*accepted) {
877     QMessageBox box2(QMessageBox::Warning,
878                      tr("Untrusted Security Certificate"),
879                      tr("Would you like to accept this certificate forever without being prompted?"),
880                      0, this);
881     box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
882     box2.addButton(tr("Forever"), QMessageBox::YesRole);
883     box2.exec();
884     *permanently =  box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
885   }
886 }
887
888 #endif /* HAVE_SSL */
889
890 void MainWin::handleCoreConnectionError(const QString &error) {
891   QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
892 }
893
894 void MainWin::showCoreConnectionDlg() {
895   CoreConnectDlg dlg(this);
896   if(dlg.exec() == QDialog::Accepted) {
897     AccountId accId = dlg.selectedAccount();
898     if(accId.isValid())
899       Client::coreConnection()->connectToCore(accId);
900   }
901 }
902
903 void MainWin::showCoreConfigWizard(const QVariantList &backends) {
904   CoreConfigWizard *wizard = new CoreConfigWizard(Client::coreConnection(), backends, this);
905
906   wizard->show();
907 }
908
909 void MainWin::showChannelList(NetworkId netId) {
910   ChannelListDlg *channelListDlg = new ChannelListDlg();
911
912   if(!netId.isValid()) {
913     QAction *action = qobject_cast<QAction *>(sender());
914     if(action)
915       netId = action->data().value<NetworkId>();
916   }
917
918   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
919   channelListDlg->setNetwork(netId);
920   channelListDlg->show();
921 }
922
923 void MainWin::showIgnoreList(QString newRule) {
924   SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
925   // prepare config dialog for new rule
926   if(!newRule.isEmpty())
927     qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
928   dlg.exec();
929 }
930
931 void MainWin::showCoreInfoDlg() {
932   CoreInfoDlg(this).exec();
933 }
934
935 void MainWin::showAwayLog() {
936   if(_awayLog)
937     return;
938   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
939   _awayLog = new AwayLogView(filter, 0);
940   filter->setParent(_awayLog);
941   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
942   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
943   _awayLog->show();
944 }
945
946 void MainWin::awayLogDestroyed() {
947   _awayLog = 0;
948 }
949
950 void MainWin::showSettingsDlg() {
951   SettingsDlg *dlg = new SettingsDlg();
952
953   //Category: Interface
954   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
955   dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
956   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
957   dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
958   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
959   dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
960   dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
961   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
962   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
963   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
964
965   //Category: IRC
966   dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
967   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
968   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
969   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
970   dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
971
972   // Category: Remote Cores
973   if(Quassel::runMode() != Quassel::Monolithic) {
974     dlg->registerSettingsPage(new CoreAccountSettingsPage(dlg));
975     dlg->registerSettingsPage(new CoreConnectionSettingsPage(dlg));
976   }
977
978   dlg->show();
979 }
980
981 void MainWin::showAboutDlg() {
982   AboutDlg(this).exec();
983 }
984
985 #ifdef HAVE_KDE
986 void MainWin::showShortcutsDlg() {
987   KShortcutsDialog::configure(QtUi::actionCollection("General"), KShortcutsEditor::LetterShortcutsDisallowed);
988 }
989 #endif
990
991 /********************************************************************************************************/
992
993 bool MainWin::event(QEvent *event) {
994   if(event->type() == QEvent::WindowActivate) {
995     BufferId buffer = Client::bufferModel()->currentBuffer();
996     if(buffer.isValid())
997       QtUi::closeNotifications(buffer);
998   }
999   return QMainWindow::event(event);
1000 }
1001
1002 void MainWin::moveEvent(QMoveEvent *event) {
1003   if(!(windowState() & Qt::WindowMaximized))
1004     _normalPos = event->pos();
1005
1006   QMainWindow::moveEvent(event);
1007 }
1008
1009 void MainWin::resizeEvent(QResizeEvent *event) {
1010   if(!(windowState() & Qt::WindowMaximized))
1011     _normalSize = event->size();
1012
1013   QMainWindow::resizeEvent(event);
1014 }
1015
1016 void MainWin::closeEvent(QCloseEvent *event) {
1017 #ifndef QT_NO_SYSTEMTRAYICON
1018   QtUiSettings s;
1019   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
1020   Q_ASSERT(app);
1021   if(!app->isAboutToQuit() && s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnClose").toBool()) {
1022     hideToTray();
1023     event->ignore();
1024   } else {
1025     event->accept();
1026     quit();
1027   }
1028 #else
1029   event->accept();
1030   quit();
1031 #endif
1032 }
1033
1034 void MainWin::changeEvent(QEvent *event) {
1035 #ifdef Q_WS_WIN
1036   if(event->type() == QEvent::ActivationChange)
1037     dwTickCount = GetTickCount();  // needed for toggleMinimizedToTray()
1038 #endif
1039
1040   QMainWindow::changeEvent(event);
1041 }
1042
1043 #ifndef QT_NO_SYSTEMTRAYICON
1044
1045 void MainWin::hideToTray() {
1046   if(!systemTray()->isSystemTrayAvailable()) {
1047     qWarning() << Q_FUNC_INFO << "was called with no SystemTray available!";
1048     return;
1049   }
1050   hide();
1051   systemTray()->setIconVisible();
1052 }
1053
1054 void MainWin::toggleMinimizedToTray() {
1055 #ifdef Q_WS_WIN
1056   // the problem is that we lose focus when the systray icon is activated
1057   // and we don't know the former active window
1058   // therefore we watch for activation event and use our stopwatch :)
1059   // courtesy: KSystemTrayIcon
1060   if(GetTickCount() - dwTickCount >= 300)
1061     // we weren't active in the last 300ms -> activate
1062     forceActivated();
1063   else
1064     hideToTray();
1065
1066 #else
1067
1068   if(!isVisible() || isMinimized())
1069     // restore
1070     forceActivated();
1071   else
1072     hideToTray();
1073
1074 #endif
1075 }
1076
1077 #endif /* QT_NO_SYSTEMTRAYICON */
1078
1079 void MainWin::forceActivated() {
1080 #ifdef HAVE_KDE
1081   show();
1082   KWindowSystem::forceActiveWindow(winId());
1083 #else
1084
1085 #ifdef Q_WS_X11
1086   // Bypass focus stealing prevention
1087   QX11Info::setAppUserTime(QX11Info::appTime());
1088 #endif
1089
1090   if(windowState() & Qt::WindowMinimized) {
1091     // restore
1092     setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
1093   }
1094
1095   // this does not actually work on all platforms... and causes more evil than good
1096   // move(frameGeometry().topLeft()); // avoid placement policies
1097   show();
1098   raise();
1099   activateWindow();
1100 #endif /* HAVE_KDE */
1101 }
1102
1103 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
1104   Q_UNUSED(parent);
1105
1106   bool hasFocus = QApplication::activeWindow() != 0;
1107
1108   for(int i = start; i <= end; i++) {
1109     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1110     if(!idx.isValid()) {
1111       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1112       continue;
1113     }
1114     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1115     if(flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1116       continue;
1117
1118     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1119     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1120
1121     if(hasFocus && bufId == Client::bufferModel()->currentBuffer())
1122       continue;
1123
1124     if((flags & Message::Highlight || bufType == BufferInfo::QueryBuffer)
1125       && !(Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(),
1126                                                                              Client::networkModel()->networkName(bufId))))
1127     {
1128       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1129       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1130       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1131       AbstractNotificationBackend::NotificationType type;
1132
1133       if(bufType == BufferInfo::QueryBuffer && !hasFocus)
1134         type = AbstractNotificationBackend::PrivMsg;
1135       else if(bufType == BufferInfo::QueryBuffer && hasFocus)
1136         type = AbstractNotificationBackend::PrivMsgFocused;
1137       else if(flags & Message::Highlight && !hasFocus)
1138         type = AbstractNotificationBackend::Highlight;
1139       else
1140         type = AbstractNotificationBackend::HighlightFocused;
1141
1142       QtUi::invokeNotification(bufId, type, sender, contents);
1143     }
1144   }
1145 }
1146
1147 void MainWin::currentBufferChanged(BufferId buffer) {
1148   if(buffer.isValid())
1149     QtUi::closeNotifications(buffer);
1150 }
1151
1152 void MainWin::clientNetworkCreated(NetworkId id) {
1153   const Network *net = Client::network(id);
1154   QAction *act = new QAction(net->networkName(), this);
1155   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1156   act->setData(QVariant::fromValue<NetworkId>(id));
1157   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1158   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1159
1160   QAction *beforeAction = 0;
1161   foreach(QAction *action, _networksMenu->actions()) {
1162     if(!action->data().isValid())  // ignore stock actions
1163       continue;
1164     if(net->networkName().localeAwareCompare(action->text()) < 0) {
1165       beforeAction = action;
1166       break;
1167     }
1168   }
1169   _networksMenu->insertAction(beforeAction, act);
1170 }
1171
1172 void MainWin::clientNetworkUpdated() {
1173   const Network *net = qobject_cast<const Network *>(sender());
1174   if(!net)
1175     return;
1176
1177   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1178   if(!action)
1179     return;
1180
1181   action->setText(net->networkName());
1182
1183   switch(net->connectionState()) {
1184   case Network::Initialized:
1185     action->setIcon(SmallIcon("network-connect"));
1186     break;
1187   case Network::Disconnected:
1188     action->setIcon(SmallIcon("network-disconnect"));
1189     break;
1190   default:
1191     action->setIcon(SmallIcon("network-wired"));
1192   }
1193 }
1194
1195 void MainWin::clientNetworkRemoved(NetworkId id) {
1196   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1197   if(!action)
1198     return;
1199
1200   action->deleteLater();
1201 }
1202
1203 void MainWin::connectOrDisconnectFromNet() {
1204   QAction *act = qobject_cast<QAction *>(sender());
1205   if(!act) return;
1206   const Network *net = Client::network(act->data().value<NetworkId>());
1207   if(!net) return;
1208   if(net->connectionState() == Network::Disconnected) net->requestConnect();
1209   else net->requestDisconnect();
1210 }
1211
1212 void MainWin::on_jumpHotBuffer_triggered() {
1213   if(!_bufferHotList->rowCount())
1214     return;
1215
1216   QModelIndex topIndex = _bufferHotList->index(0, 0);
1217   BufferId bufferId = _bufferHotList->data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
1218   Client::bufferModel()->switchToBuffer(bufferId);
1219 }
1220
1221 void MainWin::on_actionDebugNetworkModel_triggered() {
1222   QTreeView *view = new QTreeView;
1223   view->setAttribute(Qt::WA_DeleteOnClose);
1224   view->setWindowTitle("Debug NetworkModel View");
1225   view->setModel(Client::networkModel());
1226   view->setColumnWidth(0, 250);
1227   view->setColumnWidth(1, 250);
1228   view->setColumnWidth(2, 80);
1229   view->resize(610, 300);
1230   view->show();
1231 }
1232
1233 void MainWin::on_actionDebugHotList_triggered() {
1234   QTreeView *view = new QTreeView;
1235   view->setAttribute(Qt::WA_DeleteOnClose);
1236   view->setModel(_bufferHotList);
1237   view->show();
1238 }
1239
1240 void MainWin::on_actionDebugBufferViewOverlay_triggered() {
1241   DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1242   overlay->setAttribute(Qt::WA_DeleteOnClose);
1243   overlay->show();
1244 }
1245
1246 void MainWin::on_actionDebugMessageModel_triggered() {
1247   QTableView *view = new QTableView(0);
1248   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1249   filter->setSourceModel(Client::messageModel());
1250   view->setModel(filter);
1251   view->setAttribute(Qt::WA_DeleteOnClose, true);
1252   view->verticalHeader()->hide();
1253   view->horizontalHeader()->setStretchLastSection(true);
1254   view->show();
1255 }
1256
1257 void MainWin::on_actionDebugLog_triggered() {
1258   DebugLogWidget *logWidget = new DebugLogWidget(0);
1259   logWidget->show();
1260 }
1261
1262 void MainWin::showStatusBarMessage(const QString &message) {
1263   statusBar()->showMessage(message, 10000);
1264 }
1265