Preselect last used buffer at startup
[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 "legacysystemtray.h"
74 #include "msgprocessorstatuswidget.h"
75 #include "nicklistwidget.h"
76 #include "qtuiapplication.h"
77 #include "qtuimessageprocessor.h"
78 #include "qtuisettings.h"
79 #include "qtuistyle.h"
80 #include "settingsdlg.h"
81 #include "settingspagedlg.h"
82 #include "statusnotifieritem.h"
83 #include "toolbaractionprovider.h"
84 #include "topicwidget.h"
85 #include "verticaldock.h"
86
87 #ifndef HAVE_KDE
88 #  ifdef HAVE_PHONON
89 #    include "phononnotificationbackend.h"
90 #  endif
91 #  include "systraynotificationbackend.h"
92 #  include "taskbarnotificationbackend.h"
93 #else /* HAVE_KDE */
94 #  include "knotificationbackend.h"
95 #endif /* HAVE_KDE */
96
97 #ifdef HAVE_SSL
98 #  include "sslinfodlg.h"
99 #endif
100
101 #ifdef HAVE_INDICATEQT
102   #include "indicatornotificationbackend.h"
103 #endif
104
105 #include "settingspages/aliasessettingspage.h"
106 #include "settingspages/appearancesettingspage.h"
107 #include "settingspages/backlogsettingspage.h"
108 #include "settingspages/bufferviewsettingspage.h"
109 #include "settingspages/chatmonitorsettingspage.h"
110 #include "settingspages/chatviewsettingspage.h"
111 #include "settingspages/connectionsettingspage.h"
112 #include "settingspages/coreaccountsettingspage.h"
113 #include "settingspages/coreconnectionsettingspage.h"
114 #include "settingspages/highlightsettingspage.h"
115 #include "settingspages/identitiessettingspage.h"
116 #include "settingspages/ignorelistsettingspage.h"
117 #include "settingspages/inputwidgetsettingspage.h"
118 #include "settingspages/itemviewsettingspage.h"
119 #include "settingspages/networkssettingspage.h"
120 #include "settingspages/notificationssettingspage.h"
121 #include "settingspages/topicwidgetsettingspage.h"
122
123 MainWin::MainWin(QWidget *parent)
124 #ifdef HAVE_KDE
125   : KMainWindow(parent),
126   _kHelpMenu(new KHelpMenu(this, KGlobal::mainComponent().aboutData())),
127 #else
128   : QMainWindow(parent),
129 #endif
130     _msgProcessorStatusWidget(new MsgProcessorStatusWidget(this)),
131     _coreConnectionStatusWidget(new CoreConnectionStatusWidget(Client::coreConnection(), this)),
132     _titleSetter(this),
133     _awayLog(0),
134     _layoutLoaded(false)
135 {
136   setAttribute(Qt::WA_DeleteOnClose, false);  // we delete the mainwin manually
137
138   QtUiSettings uiSettings;
139   QString style = uiSettings.value("Style", QString()).toString();
140   if(!style.isEmpty()) {
141     QApplication::setStyle(style);
142   }
143
144   QApplication::setQuitOnLastWindowClosed(false);
145
146   setWindowTitle("Quassel IRC");
147   setWindowIconText("Quassel IRC");
148   updateIcon();
149
150   installEventFilter(new JumpKeyHandler(this));
151 }
152
153 void MainWin::init() {
154   connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), SLOT(clientNetworkCreated(NetworkId)));
155   connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), SLOT(clientNetworkRemoved(NetworkId)));
156   connect(Client::messageModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
157            SLOT(messagesInserted(const QModelIndex &, int, int)));
158   connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showChannelList(NetworkId)), SLOT(showChannelList(NetworkId)));
159   connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showIgnoreList(QString)), SLOT(showIgnoreList(QString)));
160
161   connect(Client::coreConnection(), SIGNAL(startCoreSetup(QVariantList)), SLOT(showCoreConfigWizard(QVariantList)));
162   connect(Client::coreConnection(), SIGNAL(connectionErrorPopup(QString)), SLOT(handleCoreConnectionError(QString)));
163   connect(Client::coreConnection(), SIGNAL(userAuthenticationRequired(CoreAccount *, bool *, QString)), SLOT(userAuthenticationRequired(CoreAccount *, bool *, QString)));
164   connect(Client::coreConnection(), SIGNAL(handleNoSslInClient(bool*)), SLOT(handleNoSslInClient(bool *)));
165   connect(Client::coreConnection(), SIGNAL(handleNoSslInCore(bool*)), SLOT(handleNoSslInCore(bool *)));
166 #ifdef HAVE_SSL
167   connect(Client::coreConnection(), SIGNAL(handleSslErrors(const QSslSocket *, bool *, bool *)), SLOT(handleSslErrors(const QSslSocket *, bool *, bool *)));
168 #endif
169
170   // Setup Dock Areas
171   setDockNestingEnabled(true);
172   setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
173   setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
174   setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
175   setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
176
177   // Order is sometimes important
178   setupActions();
179   setupBufferWidget();
180   setupMenus();
181   setupTopicWidget();
182   setupNickWidget();
183   setupInputWidget();
184   setupChatMonitor();
185   setupStatusBar();
186   setupToolBars();
187   setupSystray();
188   setupTitleSetter();
189   setupHotList();
190
191 #ifndef HAVE_KDE
192 #  ifdef HAVE_PHONON
193   QtUi::registerNotificationBackend(new PhononNotificationBackend(this));
194 #  endif
195 #  ifndef QT_NO_SYSTEMTRAYICON
196   QtUi::registerNotificationBackend(new SystrayNotificationBackend(this));
197 #  endif
198
199   QtUi::registerNotificationBackend(new TaskbarNotificationBackend(this));
200
201 #else /* HAVE_KDE */
202   QtUi::registerNotificationBackend(new KNotificationBackend(this));
203 #endif /* HAVE_KDE */
204
205 #ifdef HAVE_INDICATEQT
206   QtUi::registerNotificationBackend(new IndicatorNotificationBackend(this));
207 #endif
208
209   connect(bufferWidget(), SIGNAL(currentChanged(BufferId)), SLOT(currentBufferChanged(BufferId)));
210
211   setDisconnectedState();  // Disable menus and stuff
212
213 #ifdef HAVE_KDE
214   setAutoSaveSettings();
215 #endif
216
217   // restore mainwin state
218   QtUiSettings s;
219   restoreStateFromSettings(s);
220
221   // restore locked state of docks
222   QtUi::actionCollection("General")->action("LockLayout")->setChecked(s.value("LockLayout", false).toBool());
223
224   CoreConnection *conn = Client::coreConnection();
225   if(!conn->connectToCore()) {
226     // No autoconnect selected (or no accounts)
227     showCoreConnectionDlg();
228   }
229 }
230
231 MainWin::~MainWin() {
232
233 }
234
235 void MainWin::quit() {
236   QtUiSettings s;
237   saveStateToSettings(s);
238   saveLayout();
239   QApplication::quit();
240 }
241
242 void MainWin::saveStateToSettings(UiSettings &s) {
243   s.setValue("MainWinSize", _normalSize);
244   s.setValue("MainWinPos", _normalPos);
245   s.setValue("MainWinState", saveState());
246   s.setValue("MainWinGeometry", saveGeometry());
247   s.setValue("MainWinMinimized", isMinimized());
248   s.setValue("MainWinMaximized", isMaximized());
249   s.setValue("MainWinHidden", !isVisible());
250   s.setValue("LastUsedBufferId", Client::bufferModel()->currentBuffer().toInt());
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() && QtUi::haveSystemTray())
278     QtUi::hideMainWidget();
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 = new ChatMonitorView(filter, this);
586   _chatMonitorView->setFocusProxy(_inputWidget);
587   _chatMonitorView->show();
588   dock->setWidget(_chatMonitorView);
589   dock->hide();
590
591   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
592   _viewMenu->addAction(dock->toggleViewAction());
593   dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
594 }
595
596 void MainWin::setupInputWidget() {
597   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
598   dock->setObjectName("InputDock");
599
600   _inputWidget = new InputWidget(dock);
601   dock->setWidget(_inputWidget);
602
603   addDockWidget(Qt::BottomDockWidgetArea, dock);
604
605   _viewMenu->addAction(dock->toggleViewAction());
606   dock->toggleViewAction()->setText(tr("Show Input Line"));
607
608   _inputWidget->setModel(Client::bufferModel());
609   _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
610
611   _bufferWidget->setFocusProxy(_inputWidget);
612
613   _inputWidget->inputLine()->installEventFilter(_bufferWidget);
614
615   connect(_topicWidget, SIGNAL(switchedPlain()), _bufferWidget, SLOT(setFocus()));
616 }
617
618 void MainWin::setupTopicWidget() {
619   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
620   dock->setObjectName("TopicDock");
621   _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 #ifdef HAVE_DBUS
679   _systemTray = new StatusNotifierItem(this);
680 #elif !defined QT_NO_SYSTEMTRAYICON
681   _systemTray = new LegacySystemTray(this);
682 #else
683   _systemTray = new SystemTray(this); // dummy
684 #endif
685   _systemTray->init();
686 }
687
688 void MainWin::setupToolBars() {
689   connect(_bufferWidget, SIGNAL(currentChanged(QModelIndex)),
690           QtUi::toolBarActionProvider(), SLOT(currentBufferChanged(QModelIndex)));
691   connect(_nickListWidget, SIGNAL(nickSelectionChanged(QModelIndexList)),
692           QtUi::toolBarActionProvider(), SLOT(nickSelectionChanged(QModelIndexList)));
693
694 #ifdef Q_WS_MAC
695   setUnifiedTitleAndToolBarOnMac(true);
696 #endif
697
698 #ifdef HAVE_KDE
699   _mainToolBar = new KToolBar("MainToolBar", this, Qt::TopToolBarArea, false, true, true);
700 #else
701   _mainToolBar = new QToolBar(this);
702   _mainToolBar->setObjectName("MainToolBar");
703 #endif
704   _mainToolBar->setWindowTitle(tr("Main Toolbar"));
705   addToolBar(_mainToolBar);
706
707   QtUi::toolBarActionProvider()->addActions(_mainToolBar, ToolBarActionProvider::MainToolBar);
708   _toolbarMenu->addAction(_mainToolBar->toggleViewAction());
709 }
710
711 void MainWin::connectedToCore() {
712   Q_CHECK_PTR(Client::bufferViewManager());
713   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
714   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
715   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
716
717   setConnectedState();
718 }
719
720 void MainWin::setConnectedState() {
721   ActionCollection *coll = QtUi::actionCollection("General");
722
723   coll->action("ConnectCore")->setEnabled(false);
724   coll->action("DisconnectCore")->setEnabled(true);
725   coll->action("CoreInfo")->setEnabled(true);
726
727   foreach(QAction *action, _fileMenu->actions()) {
728     if(isRemoteCoreOnly(action))
729       action->setVisible(!Client::internalCore());
730   }
731
732   disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
733   disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
734   disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
735   if(!Client::internalCore()) {
736     connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
737     connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
738     connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
739   }
740
741   // _viewMenu->setEnabled(true);
742   if(!Client::internalCore())
743     statusBar()->showMessage(tr("Connected to core."));
744   else
745     statusBar()->clearMessage();
746
747   _coreConnectionStatusWidget->setVisible(!Client::internalCore());
748   updateIcon();
749   systemTray()->setState(SystemTray::Active);
750
751   if(Client::networkIds().isEmpty()) {
752     IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
753     wizard->show();
754   }
755   else {
756     QtUiSettings s;
757     BufferId lastUsedBufferId(s.value("LastUsedBufferId").toInt());
758     if(lastUsedBufferId.isValid())
759       Client::bufferModel()->switchToBuffer(lastUsedBufferId);
760   }
761 }
762
763 void MainWin::loadLayout() {
764   QtUiSettings s;
765   int accountId = Client::currentCoreAccount().accountId().toInt();
766   QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
767   if(state.isEmpty()) {
768     // Make sure that the default bufferview is shown
769     if(_bufferViews.count())
770       _bufferViews.at(0)->show();
771     return;
772   }
773
774   restoreState(state, accountId);
775   _layoutLoaded = true;
776 }
777
778 void MainWin::saveLayout() {
779   QtUiSettings s;
780   int accountId = _bufferViews.count()? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
781   if(accountId > 0)
782     s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
783 }
784
785 void MainWin::disconnectedFromCore() {
786   // save core specific layout and remove bufferviews;
787   saveLayout();
788   _layoutLoaded = false;
789
790   QVariant actionData;
791   BufferViewDock *dock;
792   foreach(QAction *action, _bufferViewsMenu->actions()) {
793     actionData = action->data();
794     if(!actionData.isValid())
795       continue;
796
797     dock = qobject_cast<BufferViewDock *>(action->parent());
798     if(dock && actionData.toInt() != -1) {
799       removeAction(action);
800       _bufferViews.removeAll(dock);
801       Client::bufferViewOverlay()->removeView(dock->bufferViewId());
802       dock->deleteLater();
803     }
804   }
805
806   QtUiSettings s;
807   restoreState(s.value("MainWinState").toByteArray());
808   setDisconnectedState();
809 }
810
811 void MainWin::setDisconnectedState() {
812   ActionCollection *coll = QtUi::actionCollection("General");
813   //ui.menuCore->setEnabled(false);
814   coll->action("ConnectCore")->setEnabled(true);
815   coll->action("DisconnectCore")->setEnabled(false);
816   coll->action("CoreInfo")->setEnabled(false);
817   //_viewMenu->setEnabled(false);
818   statusBar()->showMessage(tr("Not connected to core."));
819   if(_msgProcessorStatusWidget)
820     _msgProcessorStatusWidget->setProgress(0, 0);
821   updateIcon();
822   systemTray()->setState(SystemTray::Passive);
823 }
824
825 void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage) {
826   Q_UNUSED(errorMessage)
827   CoreConnectAuthDlg dlg(account, this);
828   *valid = (dlg.exec() == QDialog::Accepted);
829 }
830
831 void MainWin::handleNoSslInClient(bool *accepted) {
832   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
833                   QMessageBox::Ignore|QMessageBox::Cancel, this);
834   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
835   box.setDefaultButton(QMessageBox::Ignore);
836   *accepted = box.exec() == QMessageBox::Ignore;
837 }
838
839 void MainWin::handleNoSslInCore(bool *accepted) {
840   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
841                   QMessageBox::Ignore|QMessageBox::Cancel, this);
842   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
843   box.setDefaultButton(QMessageBox::Ignore);
844   *accepted = box.exec() == QMessageBox::Ignore;
845
846 }
847
848 #ifdef HAVE_SSL
849
850 void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently) {
851   QString errorString = "<ul>";
852   foreach(const QSslError error, socket->sslErrors())
853     errorString += QString("<li>%1</li>").arg(error.errorString());
854   errorString += "</ul>";
855
856   QMessageBox box(QMessageBox::Warning,
857                   tr("Untrusted Security Certificate"),
858                   tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
859                   QMessageBox::Cancel, this);
860   box.setInformativeText(errorString);
861   box.addButton(tr("Continue"), QMessageBox::AcceptRole);
862   box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
863
864   QMessageBox::ButtonRole role;
865   do {
866     box.exec();
867     role = box.buttonRole(box.clickedButton());
868     if(role == QMessageBox::HelpRole) {
869       SslInfoDlg dlg(socket, this);
870       dlg.exec();
871     }
872   } while(role == QMessageBox::HelpRole);
873
874   *accepted = role == QMessageBox::AcceptRole;
875   if(*accepted) {
876     QMessageBox box2(QMessageBox::Warning,
877                      tr("Untrusted Security Certificate"),
878                      tr("Would you like to accept this certificate forever without being prompted?"),
879                      0, this);
880     box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
881     box2.addButton(tr("Forever"), QMessageBox::YesRole);
882     box2.exec();
883     *permanently =  box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
884   }
885 }
886
887 #endif /* HAVE_SSL */
888
889 void MainWin::handleCoreConnectionError(const QString &error) {
890   QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
891 }
892
893 void MainWin::showCoreConnectionDlg() {
894   CoreConnectDlg dlg(this);
895   if(dlg.exec() == QDialog::Accepted) {
896     AccountId accId = dlg.selectedAccount();
897     if(accId.isValid())
898       Client::coreConnection()->connectToCore(accId);
899   }
900 }
901
902 void MainWin::showCoreConfigWizard(const QVariantList &backends) {
903   CoreConfigWizard *wizard = new CoreConfigWizard(Client::coreConnection(), backends, this);
904
905   wizard->show();
906 }
907
908 void MainWin::showChannelList(NetworkId netId) {
909   ChannelListDlg *channelListDlg = new ChannelListDlg();
910
911   if(!netId.isValid()) {
912     QAction *action = qobject_cast<QAction *>(sender());
913     if(action)
914       netId = action->data().value<NetworkId>();
915   }
916
917   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
918   channelListDlg->setNetwork(netId);
919   channelListDlg->show();
920 }
921
922 void MainWin::showIgnoreList(QString newRule) {
923   SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
924   // prepare config dialog for new rule
925   if(!newRule.isEmpty())
926     qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
927   dlg.exec();
928 }
929
930 void MainWin::showCoreInfoDlg() {
931   CoreInfoDlg(this).exec();
932 }
933
934 void MainWin::showAwayLog() {
935   if(_awayLog)
936     return;
937   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
938   _awayLog = new AwayLogView(filter, 0);
939   filter->setParent(_awayLog);
940   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
941   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
942   _awayLog->show();
943 }
944
945 void MainWin::awayLogDestroyed() {
946   _awayLog = 0;
947 }
948
949 void MainWin::showSettingsDlg() {
950   SettingsDlg *dlg = new SettingsDlg();
951
952   //Category: Interface
953   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
954   dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
955   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
956   dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
957   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
958   dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
959   dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
960   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
961   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
962   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
963
964   //Category: IRC
965   dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
966   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
967   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
968   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
969   dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
970
971   // Category: Remote Cores
972   if(Quassel::runMode() != Quassel::Monolithic) {
973     dlg->registerSettingsPage(new CoreAccountSettingsPage(dlg));
974     dlg->registerSettingsPage(new CoreConnectionSettingsPage(dlg));
975   }
976
977   dlg->show();
978 }
979
980 void MainWin::showAboutDlg() {
981   AboutDlg(this).exec();
982 }
983
984 #ifdef HAVE_KDE
985 void MainWin::showShortcutsDlg() {
986   KShortcutsDialog::configure(QtUi::actionCollection("General"), KShortcutsEditor::LetterShortcutsDisallowed);
987 }
988 #endif
989
990 /********************************************************************************************************/
991
992 bool MainWin::event(QEvent *event) {
993   if(event->type() == QEvent::WindowActivate) {
994     BufferId buffer = Client::bufferModel()->currentBuffer();
995     if(buffer.isValid())
996       QtUi::closeNotifications(buffer);
997   }
998   return QMainWindow::event(event);
999 }
1000
1001 void MainWin::moveEvent(QMoveEvent *event) {
1002   if(!(windowState() & Qt::WindowMaximized))
1003     _normalPos = event->pos();
1004
1005   QMainWindow::moveEvent(event);
1006 }
1007
1008 void MainWin::resizeEvent(QResizeEvent *event) {
1009   if(!(windowState() & Qt::WindowMaximized))
1010     _normalSize = event->size();
1011
1012   QMainWindow::resizeEvent(event);
1013 }
1014
1015 void MainWin::closeEvent(QCloseEvent *event) {
1016   QtUiSettings s;
1017   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
1018   Q_ASSERT(app);
1019   if(!app->isAboutToQuit() && QtUi::haveSystemTray() && s.value("MinimizeOnClose").toBool()) {
1020     QtUi::hideMainWidget();
1021     event->ignore();
1022   } else {
1023     event->accept();
1024     quit();
1025   }
1026 }
1027
1028 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
1029   Q_UNUSED(parent);
1030
1031   bool hasFocus = QApplication::activeWindow() != 0;
1032
1033   for(int i = start; i <= end; i++) {
1034     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1035     if(!idx.isValid()) {
1036       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1037       continue;
1038     }
1039     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1040     if(flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1041       continue;
1042
1043     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1044     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1045
1046     if(hasFocus && bufId == Client::bufferModel()->currentBuffer())
1047       continue;
1048
1049     if((flags & Message::Highlight || bufType == BufferInfo::QueryBuffer)
1050       && !(Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(),
1051                                                                              Client::networkModel()->networkName(bufId))))
1052     {
1053       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1054       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1055       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1056       AbstractNotificationBackend::NotificationType type;
1057
1058       if(bufType == BufferInfo::QueryBuffer && !hasFocus)
1059         type = AbstractNotificationBackend::PrivMsg;
1060       else if(bufType == BufferInfo::QueryBuffer && hasFocus)
1061         type = AbstractNotificationBackend::PrivMsgFocused;
1062       else if(flags & Message::Highlight && !hasFocus)
1063         type = AbstractNotificationBackend::Highlight;
1064       else
1065         type = AbstractNotificationBackend::HighlightFocused;
1066
1067       QtUi::invokeNotification(bufId, type, sender, contents);
1068     }
1069   }
1070 }
1071
1072 void MainWin::currentBufferChanged(BufferId buffer) {
1073   if(buffer.isValid())
1074     QtUi::closeNotifications(buffer);
1075 }
1076
1077 void MainWin::clientNetworkCreated(NetworkId id) {
1078   const Network *net = Client::network(id);
1079   QAction *act = new QAction(net->networkName(), this);
1080   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1081   act->setData(QVariant::fromValue<NetworkId>(id));
1082   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1083   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1084
1085   QAction *beforeAction = 0;
1086   foreach(QAction *action, _networksMenu->actions()) {
1087     if(!action->data().isValid())  // ignore stock actions
1088       continue;
1089     if(net->networkName().localeAwareCompare(action->text()) < 0) {
1090       beforeAction = action;
1091       break;
1092     }
1093   }
1094   _networksMenu->insertAction(beforeAction, act);
1095 }
1096
1097 void MainWin::clientNetworkUpdated() {
1098   const Network *net = qobject_cast<const Network *>(sender());
1099   if(!net)
1100     return;
1101
1102   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1103   if(!action)
1104     return;
1105
1106   action->setText(net->networkName());
1107
1108   switch(net->connectionState()) {
1109   case Network::Initialized:
1110     action->setIcon(SmallIcon("network-connect"));
1111     break;
1112   case Network::Disconnected:
1113     action->setIcon(SmallIcon("network-disconnect"));
1114     break;
1115   default:
1116     action->setIcon(SmallIcon("network-wired"));
1117   }
1118 }
1119
1120 void MainWin::clientNetworkRemoved(NetworkId id) {
1121   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1122   if(!action)
1123     return;
1124
1125   action->deleteLater();
1126 }
1127
1128 void MainWin::connectOrDisconnectFromNet() {
1129   QAction *act = qobject_cast<QAction *>(sender());
1130   if(!act) return;
1131   const Network *net = Client::network(act->data().value<NetworkId>());
1132   if(!net) return;
1133   if(net->connectionState() == Network::Disconnected) net->requestConnect();
1134   else net->requestDisconnect();
1135 }
1136
1137 void MainWin::on_jumpHotBuffer_triggered() {
1138   if(!_bufferHotList->rowCount())
1139     return;
1140
1141   QModelIndex topIndex = _bufferHotList->index(0, 0);
1142   BufferId bufferId = _bufferHotList->data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
1143   Client::bufferModel()->switchToBuffer(bufferId);
1144 }
1145
1146 void MainWin::on_actionDebugNetworkModel_triggered() {
1147   QTreeView *view = new QTreeView;
1148   view->setAttribute(Qt::WA_DeleteOnClose);
1149   view->setWindowTitle("Debug NetworkModel View");
1150   view->setModel(Client::networkModel());
1151   view->setColumnWidth(0, 250);
1152   view->setColumnWidth(1, 250);
1153   view->setColumnWidth(2, 80);
1154   view->resize(610, 300);
1155   view->show();
1156 }
1157
1158 void MainWin::on_actionDebugHotList_triggered() {
1159   QTreeView *view = new QTreeView;
1160   view->setAttribute(Qt::WA_DeleteOnClose);
1161   view->setModel(_bufferHotList);
1162   view->show();
1163 }
1164
1165 void MainWin::on_actionDebugBufferViewOverlay_triggered() {
1166   DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1167   overlay->setAttribute(Qt::WA_DeleteOnClose);
1168   overlay->show();
1169 }
1170
1171 void MainWin::on_actionDebugMessageModel_triggered() {
1172   QTableView *view = new QTableView(0);
1173   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1174   filter->setSourceModel(Client::messageModel());
1175   view->setModel(filter);
1176   view->setAttribute(Qt::WA_DeleteOnClose, true);
1177   view->verticalHeader()->hide();
1178   view->horizontalHeader()->setStretchLastSection(true);
1179   view->show();
1180 }
1181
1182 void MainWin::on_actionDebugLog_triggered() {
1183   DebugLogWidget *logWidget = new DebugLogWidget(0);
1184   logWidget->show();
1185 }
1186
1187 void MainWin::showStatusBarMessage(const QString &message) {
1188   statusBar()->showMessage(message, 10000);
1189 }