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