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