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