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