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