Make shortcut categories work
[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", tr("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 = QtUi::actionCollection("Navigation", tr("Navigation"));
371
372   coll->addAction("JumpHotBuffer", new Action(tr("Jump to hot chat"), coll,
373                                               this, SLOT(on_jumpHotBuffer_triggered()), QKeySequence(Qt::META + Qt::Key_A)));
374 }
375
376 void MainWin::setupMenus() {
377   ActionCollection *coll = QtUi::actionCollection("General");
378
379   _fileMenu = menuBar()->addMenu(tr("&File"));
380
381   static const QStringList coreActions = QStringList()
382     << "ConnectCore" << "DisconnectCore" << "CoreInfo";
383
384   QAction *coreAction;
385   foreach(QString actionName, coreActions) {
386     coreAction = coll->action(actionName);
387     _fileMenu->addAction(coreAction);
388     flagRemoteCoreOnly(coreAction);
389   }
390   flagRemoteCoreOnly(_fileMenu->addSeparator());
391
392   _networksMenu = _fileMenu->addMenu(tr("&Networks"));
393   _networksMenu->addAction(coll->action("ConfigureNetworks"));
394   _networksMenu->addSeparator();
395   _fileMenu->addSeparator();
396   _fileMenu->addAction(coll->action("Quit"));
397
398   _viewMenu = menuBar()->addMenu(tr("&View"));
399   _bufferViewsMenu = _viewMenu->addMenu(tr("&Chat Lists"));
400   _bufferViewsMenu->addAction(coll->action("ConfigureBufferViews"));
401   _toolbarMenu = _viewMenu->addMenu(tr("&Toolbars"));
402   _viewMenu->addSeparator();
403
404   _viewMenu->addAction(coll->action("ToggleMenuBar"));
405   _viewMenu->addAction(coll->action("ToggleStatusBar"));
406   _viewMenu->addAction(coll->action("ToggleSearchBar"));
407
408   coreAction = coll->action("ShowAwayLog");
409   flagRemoteCoreOnly(coreAction);
410   _viewMenu->addAction(coreAction);
411
412   _viewMenu->addSeparator();
413   _viewMenu->addAction(coll->action("LockLayout"));
414
415   _settingsMenu = menuBar()->addMenu(tr("&Settings"));
416 #ifdef HAVE_KDE
417   _settingsMenu->addAction(KStandardAction::configureNotifications(this, SLOT(showNotificationsDlg()), this));
418   _settingsMenu->addAction(KStandardAction::keyBindings(this, SLOT(showShortcutsDlg()), this));
419 #else
420   _settingsMenu->addAction(coll->action("ConfigureShortcuts"));
421 #endif
422   _settingsMenu->addAction(coll->action("ConfigureQuassel"));
423
424   _helpMenu = menuBar()->addMenu(tr("&Help"));
425   _helpMenu->addAction(coll->action("AboutQuassel"));
426 #ifndef HAVE_KDE
427   _helpMenu->addAction(coll->action("AboutQt"));
428 #else
429   _helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, SLOT(aboutKDE()), this));
430 #endif
431   _helpMenu->addSeparator();
432   _helpDebugMenu = _helpMenu->addMenu(SmallIcon("tools-report-bug"), tr("Debug"));
433   _helpDebugMenu->addAction(coll->action("DebugNetworkModel"));
434   _helpDebugMenu->addAction(coll->action("DebugBufferViewOverlay"));
435   _helpDebugMenu->addAction(coll->action("DebugMessageModel"));
436   _helpDebugMenu->addAction(coll->action("DebugHotList"));
437   _helpDebugMenu->addAction(coll->action("DebugLog"));
438   _helpDebugMenu->addSeparator();
439   _helpDebugMenu->addAction(coll->action("ReloadStyle"));
440
441   // Toggle visibility
442   QAction *showMenuBar = QtUi::actionCollection("General")->action("ToggleMenuBar");
443
444   QtUiSettings uiSettings;
445   bool enabled = uiSettings.value("ShowMenuBar", QVariant(true)).toBool();
446   showMenuBar->setChecked(enabled);
447   enabled ? menuBar()->show() : menuBar()->hide();
448
449   connect(showMenuBar, SIGNAL(toggled(bool)), menuBar(), SLOT(setVisible(bool)));
450   connect(showMenuBar, SIGNAL(toggled(bool)), this, SLOT(saveMenuBarStatus(bool)));
451 }
452
453 void MainWin::setupBufferWidget() {
454   _bufferWidget = new BufferWidget(this);
455   _bufferWidget->setModel(Client::bufferModel());
456   _bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
457   setCentralWidget(_bufferWidget);
458 }
459
460 void MainWin::addBufferView(int bufferViewConfigId) {
461   addBufferView(Client::bufferViewManager()->clientBufferViewConfig(bufferViewConfigId));
462 }
463
464 void MainWin::addBufferView(ClientBufferViewConfig *config) {
465   if(!config)
466     return;
467
468   config->setLocked(QtUiSettings().value("LockLayout", false).toBool());
469   BufferViewDock *dock = new BufferViewDock(config, this);
470
471   //create the view and initialize it's filter
472   BufferView *view = new BufferView(dock);
473   view->setFilteredModel(Client::bufferModel(), config);
474   view->installEventFilter(_inputWidget); // for key presses
475
476   Client::bufferModel()->synchronizeView(view);
477
478   dock->setWidget(view);
479   dock->setVisible(_layoutLoaded); // don't show before state has been restored
480
481   addDockWidget(Qt::LeftDockWidgetArea, dock);
482   _bufferViewsMenu->addAction(dock->toggleViewAction());
483
484   connect(dock->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(bufferViewToggled(bool)));
485   _bufferViews.append(dock);
486 }
487
488 void MainWin::removeBufferView(int bufferViewConfigId) {
489   QVariant actionData;
490   BufferViewDock *dock;
491   foreach(QAction *action, _bufferViewsMenu->actions()) {
492     actionData = action->data();
493     if(!actionData.isValid())
494       continue;
495
496     dock = qobject_cast<BufferViewDock *>(action->parent());
497     if(dock && actionData.toInt() == bufferViewConfigId) {
498       removeAction(action);
499       _bufferViews.removeAll(dock);
500       Client::bufferViewOverlay()->removeView(dock->bufferViewId());
501       dock->deleteLater();
502     }
503   }
504 }
505
506 void MainWin::bufferViewToggled(bool enabled) {
507   if(!enabled && !isVisible()) {
508     // hiding the mainwindow triggers a toggle of the bufferview (which pretty much sucks big time)
509     // since this isn't our fault and we can't do anything about it, we suppress the resulting calls
510     return;
511   }
512   QAction *action = qobject_cast<QAction *>(sender());
513   Q_ASSERT(action);
514   BufferViewDock *dock = qobject_cast<BufferViewDock *>(action->parent());
515   Q_ASSERT(dock);
516
517   // Make sure we don't toggle backlog fetch for a view we've already removed
518   if(!_bufferViews.contains(dock))
519     return;
520
521   if(enabled) {
522     Client::bufferViewOverlay()->addView(dock->bufferViewId());
523   } else {
524     Client::bufferViewOverlay()->removeView(dock->bufferViewId());
525   }
526 }
527
528 BufferView *MainWin::allBuffersView() const {
529   // "All Buffers" is always the first dock created
530   if(_bufferViews.count() > 0)
531     return _bufferViews[0]->bufferView();
532   return 0;
533 }
534
535 void MainWin::showNotificationsDlg() {
536   SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
537   dlg.exec();
538 }
539
540 void MainWin::on_actionConfigureNetworks_triggered() {
541   SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
542   dlg.exec();
543 }
544
545 void MainWin::on_actionConfigureViews_triggered() {
546   SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
547   dlg.exec();
548 }
549
550 void MainWin::on_actionLockLayout_toggled(bool lock) {
551   QList<VerticalDock *> docks = findChildren<VerticalDock *>();
552   foreach(VerticalDock *dock, docks) {
553     dock->showTitle(!lock);
554   }
555   if(Client::bufferViewManager()) {
556     foreach(ClientBufferViewConfig *config, Client::bufferViewManager()->clientBufferViewConfigs()) {
557       config->setLocked(lock);
558     }
559   }
560   QtUiSettings().setValue("LockLayout", lock);
561 }
562
563 void MainWin::setupNickWidget() {
564   // create nick dock
565   NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
566   nickDock->setObjectName("NickDock");
567   nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
568
569   _nickListWidget = new NickListWidget(nickDock);
570   nickDock->setWidget(_nickListWidget);
571
572   addDockWidget(Qt::RightDockWidgetArea, nickDock);
573   _viewMenu->addAction(nickDock->toggleViewAction());
574   nickDock->toggleViewAction()->setText(tr("Show Nick List"));
575
576   // See NickListDock::NickListDock();
577   // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
578
579   // attach the NickListWidget to the BufferModel and the default selection
580   _nickListWidget->setModel(Client::bufferModel());
581   _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
582 }
583
584 void MainWin::setupChatMonitor() {
585   VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
586   dock->setObjectName("ChatMonitorDock");
587
588   ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
589   _chatMonitorView = new ChatMonitorView(filter, this);
590   _chatMonitorView->setFocusProxy(_inputWidget);
591   _chatMonitorView->show();
592   dock->setWidget(_chatMonitorView);
593   dock->hide();
594
595   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
596   _viewMenu->addAction(dock->toggleViewAction());
597   dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
598 }
599
600 void MainWin::setupInputWidget() {
601   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
602   dock->setObjectName("InputDock");
603
604   _inputWidget = new InputWidget(dock);
605   dock->setWidget(_inputWidget);
606
607   addDockWidget(Qt::BottomDockWidgetArea, dock);
608
609   _viewMenu->addAction(dock->toggleViewAction());
610   dock->toggleViewAction()->setText(tr("Show Input Line"));
611
612   _inputWidget->setModel(Client::bufferModel());
613   _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
614
615   _bufferWidget->setFocusProxy(_inputWidget);
616
617   _inputWidget->inputLine()->installEventFilter(_bufferWidget);
618
619   connect(_topicWidget, SIGNAL(switchedPlain()), _bufferWidget, SLOT(setFocus()));
620 }
621
622 void MainWin::setupTopicWidget() {
623   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
624   dock->setObjectName("TopicDock");
625   _topicWidget = new TopicWidget(dock);
626
627   dock->setWidget(_topicWidget);
628
629   _topicWidget->setModel(Client::bufferModel());
630   _topicWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
631
632   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
633
634   _viewMenu->addAction(dock->toggleViewAction());
635   dock->toggleViewAction()->setText(tr("Show Topic Line"));
636 }
637
638 void MainWin::setupTitleSetter() {
639   _titleSetter.setModel(Client::bufferModel());
640   _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
641 }
642
643 void MainWin::setupStatusBar() {
644   // MessageProcessor progress
645   statusBar()->addPermanentWidget(_msgProcessorStatusWidget);
646
647   // Connection state
648   _coreConnectionStatusWidget->update();
649   statusBar()->addPermanentWidget(_coreConnectionStatusWidget);
650
651   QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
652
653   QtUiSettings uiSettings;
654
655   bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
656   showStatusbar->setChecked(enabled);
657   enabled ? statusBar()->show() : statusBar()->hide();
658
659   connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
660   connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
661
662   connect(Client::coreConnection(), SIGNAL(connectionMsg(QString)), statusBar(), SLOT(showMessage(QString)));
663 }
664
665 void MainWin::setupHotList() {
666   FlatProxyModel *flatProxy = new FlatProxyModel(this);
667   flatProxy->setSourceModel(Client::bufferModel());
668   _bufferHotList = new BufferHotListFilter(flatProxy);
669 }
670
671 void MainWin::saveMenuBarStatus(bool enabled) {
672   QtUiSettings uiSettings;
673   uiSettings.setValue("ShowMenuBar", enabled);
674 }
675
676 void MainWin::saveStatusBarStatus(bool enabled) {
677   QtUiSettings uiSettings;
678   uiSettings.setValue("ShowStatusBar", enabled);
679 }
680
681 void MainWin::setupSystray() {
682 #ifdef HAVE_DBUS
683   _systemTray = new StatusNotifierItem(this);
684 #elif !defined QT_NO_SYSTEMTRAYICON
685   _systemTray = new LegacySystemTray(this);
686 #else
687   _systemTray = new SystemTray(this); // dummy
688 #endif
689   _systemTray->init();
690 }
691
692 void MainWin::setupToolBars() {
693   connect(_bufferWidget, SIGNAL(currentChanged(QModelIndex)),
694           QtUi::toolBarActionProvider(), SLOT(currentBufferChanged(QModelIndex)));
695   connect(_nickListWidget, SIGNAL(nickSelectionChanged(QModelIndexList)),
696           QtUi::toolBarActionProvider(), SLOT(nickSelectionChanged(QModelIndexList)));
697
698 #ifdef Q_WS_MAC
699   setUnifiedTitleAndToolBarOnMac(true);
700 #endif
701
702 #ifdef HAVE_KDE
703   _mainToolBar = new KToolBar("MainToolBar", this, Qt::TopToolBarArea, false, true, true);
704 #else
705   _mainToolBar = new QToolBar(this);
706   _mainToolBar->setObjectName("MainToolBar");
707 #endif
708   _mainToolBar->setWindowTitle(tr("Main Toolbar"));
709   addToolBar(_mainToolBar);
710
711   QtUi::toolBarActionProvider()->addActions(_mainToolBar, ToolBarActionProvider::MainToolBar);
712   _toolbarMenu->addAction(_mainToolBar->toggleViewAction());
713 }
714
715 void MainWin::connectedToCore() {
716   Q_CHECK_PTR(Client::bufferViewManager());
717   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
718   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
719   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
720
721   setConnectedState();
722 }
723
724 void MainWin::setConnectedState() {
725   ActionCollection *coll = QtUi::actionCollection("General");
726
727   coll->action("ConnectCore")->setEnabled(false);
728   coll->action("DisconnectCore")->setEnabled(true);
729   coll->action("CoreInfo")->setEnabled(true);
730
731   foreach(QAction *action, _fileMenu->actions()) {
732     if(isRemoteCoreOnly(action))
733       action->setVisible(!Client::internalCore());
734   }
735
736   disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
737   disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
738   disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
739   if(!Client::internalCore()) {
740     connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
741     connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
742     connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
743   }
744
745   // _viewMenu->setEnabled(true);
746   if(!Client::internalCore())
747     statusBar()->showMessage(tr("Connected to core."));
748   else
749     statusBar()->clearMessage();
750
751   _coreConnectionStatusWidget->setVisible(!Client::internalCore());
752   updateIcon();
753   systemTray()->setState(SystemTray::Active);
754
755   if(Client::networkIds().isEmpty()) {
756     IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
757     wizard->show();
758   }
759   else {
760     QtUiSettings s;
761     BufferId lastUsedBufferId(s.value("LastUsedBufferId").toInt());
762     if(lastUsedBufferId.isValid())
763       Client::bufferModel()->switchToBuffer(lastUsedBufferId);
764   }
765 }
766
767 void MainWin::loadLayout() {
768   QtUiSettings s;
769   int accountId = Client::currentCoreAccount().accountId().toInt();
770   QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
771   if(state.isEmpty()) {
772     foreach(BufferViewDock *view, _bufferViews)
773       view->show();
774     _layoutLoaded = true;
775     return;
776   }
777
778   restoreState(state, accountId);
779   _layoutLoaded = true;
780 }
781
782 void MainWin::saveLayout() {
783   QtUiSettings s;
784   int accountId = _bufferViews.count()? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
785   if(accountId > 0)
786     s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
787 }
788
789 void MainWin::disconnectedFromCore() {
790   // save core specific layout and remove bufferviews;
791   saveLayout();
792   _layoutLoaded = false;
793
794   QVariant actionData;
795   BufferViewDock *dock;
796   foreach(QAction *action, _bufferViewsMenu->actions()) {
797     actionData = action->data();
798     if(!actionData.isValid())
799       continue;
800
801     dock = qobject_cast<BufferViewDock *>(action->parent());
802     if(dock && actionData.toInt() != -1) {
803       removeAction(action);
804       _bufferViews.removeAll(dock);
805       dock->deleteLater();
806     }
807   }
808
809   QtUiSettings s;
810   restoreState(s.value("MainWinState").toByteArray());
811   setDisconnectedState();
812 }
813
814 void MainWin::setDisconnectedState() {
815   ActionCollection *coll = QtUi::actionCollection("General");
816   //ui.menuCore->setEnabled(false);
817   coll->action("ConnectCore")->setEnabled(true);
818   coll->action("DisconnectCore")->setEnabled(false);
819   coll->action("CoreInfo")->setEnabled(false);
820   //_viewMenu->setEnabled(false);
821   statusBar()->showMessage(tr("Not connected to core."));
822   if(_msgProcessorStatusWidget)
823     _msgProcessorStatusWidget->setProgress(0, 0);
824   updateIcon();
825   systemTray()->setState(SystemTray::Passive);
826 }
827
828 void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage) {
829   Q_UNUSED(errorMessage)
830   CoreConnectAuthDlg dlg(account, this);
831   *valid = (dlg.exec() == QDialog::Accepted);
832 }
833
834 void MainWin::handleNoSslInClient(bool *accepted) {
835   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
836                   QMessageBox::Ignore|QMessageBox::Cancel, this);
837   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
838   box.setDefaultButton(QMessageBox::Ignore);
839   *accepted = box.exec() == QMessageBox::Ignore;
840 }
841
842 void MainWin::handleNoSslInCore(bool *accepted) {
843   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
844                   QMessageBox::Ignore|QMessageBox::Cancel, this);
845   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
846   box.setDefaultButton(QMessageBox::Ignore);
847   *accepted = box.exec() == QMessageBox::Ignore;
848
849 }
850
851 #ifdef HAVE_SSL
852
853 void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently) {
854   QString errorString = "<ul>";
855   foreach(const QSslError error, socket->sslErrors())
856     errorString += QString("<li>%1</li>").arg(error.errorString());
857   errorString += "</ul>";
858
859   QMessageBox box(QMessageBox::Warning,
860                   tr("Untrusted Security Certificate"),
861                   tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
862                   QMessageBox::Cancel, this);
863   box.setInformativeText(errorString);
864   box.addButton(tr("Continue"), QMessageBox::AcceptRole);
865   box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
866
867   QMessageBox::ButtonRole role;
868   do {
869     box.exec();
870     role = box.buttonRole(box.clickedButton());
871     if(role == QMessageBox::HelpRole) {
872       SslInfoDlg dlg(socket, this);
873       dlg.exec();
874     }
875   } while(role == QMessageBox::HelpRole);
876
877   *accepted = role == QMessageBox::AcceptRole;
878   if(*accepted) {
879     QMessageBox box2(QMessageBox::Warning,
880                      tr("Untrusted Security Certificate"),
881                      tr("Would you like to accept this certificate forever without being prompted?"),
882                      0, this);
883     box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
884     box2.addButton(tr("Forever"), QMessageBox::YesRole);
885     box2.exec();
886     *permanently =  box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
887   }
888 }
889
890 #endif /* HAVE_SSL */
891
892 void MainWin::handleCoreConnectionError(const QString &error) {
893   QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
894 }
895
896 void MainWin::showCoreConnectionDlg() {
897   CoreConnectDlg dlg(this);
898   if(dlg.exec() == QDialog::Accepted) {
899     AccountId accId = dlg.selectedAccount();
900     if(accId.isValid())
901       Client::coreConnection()->connectToCore(accId);
902   }
903 }
904
905 void MainWin::showCoreConfigWizard(const QVariantList &backends) {
906   CoreConfigWizard *wizard = new CoreConfigWizard(Client::coreConnection(), backends, this);
907
908   wizard->show();
909 }
910
911 void MainWin::showChannelList(NetworkId netId) {
912   ChannelListDlg *channelListDlg = new ChannelListDlg();
913
914   if(!netId.isValid()) {
915     QAction *action = qobject_cast<QAction *>(sender());
916     if(action)
917       netId = action->data().value<NetworkId>();
918   }
919
920   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
921   channelListDlg->setNetwork(netId);
922   channelListDlg->show();
923 }
924
925 void MainWin::showIgnoreList(QString newRule) {
926   SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
927   // prepare config dialog for new rule
928   if(!newRule.isEmpty())
929     qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
930   dlg.exec();
931 }
932
933 void MainWin::showCoreInfoDlg() {
934   CoreInfoDlg(this).exec();
935 }
936
937 void MainWin::showAwayLog() {
938   if(_awayLog)
939     return;
940   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
941   _awayLog = new AwayLogView(filter, 0);
942   filter->setParent(_awayLog);
943   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
944   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
945   _awayLog->show();
946 }
947
948 void MainWin::awayLogDestroyed() {
949   _awayLog = 0;
950 }
951
952 void MainWin::showSettingsDlg() {
953   SettingsDlg *dlg = new SettingsDlg();
954
955   //Category: Interface
956   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
957   dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
958   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
959   dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
960   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
961   dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
962   dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
963   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
964   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
965   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
966
967   //Category: IRC
968   dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
969   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
970   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
971   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
972   dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
973
974   // Category: Remote Cores
975   if(Quassel::runMode() != Quassel::Monolithic) {
976     dlg->registerSettingsPage(new CoreAccountSettingsPage(dlg));
977     dlg->registerSettingsPage(new CoreConnectionSettingsPage(dlg));
978   }
979
980   dlg->show();
981 }
982
983 void MainWin::showAboutDlg() {
984   AboutDlg(this).exec();
985 }
986
987 void MainWin::showShortcutsDlg() {
988 #ifdef HAVE_KDE
989   KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed, this);
990   foreach(KActionCollection *coll, QtUi::actionCollections())
991     dlg.addCollection(coll, coll->property("Category").toString());
992   dlg.exec();
993 #else
994   SettingsPageDlg dlg(new ShortcutsSettingsPage(QtUi::actionCollections(), this), this);
995   dlg.exec();
996 #endif
997 }
998
999 /********************************************************************************************************/
1000
1001 bool MainWin::event(QEvent *event) {
1002   if(event->type() == QEvent::WindowActivate) {
1003     BufferId buffer = Client::bufferModel()->currentBuffer();
1004     if(buffer.isValid())
1005       Client::instance()->markBufferAsRead(buffer);
1006   }
1007   return QMainWindow::event(event);
1008 }
1009
1010 void MainWin::moveEvent(QMoveEvent *event) {
1011   if(!(windowState() & Qt::WindowMaximized))
1012     _normalPos = event->pos();
1013
1014   QMainWindow::moveEvent(event);
1015 }
1016
1017 void MainWin::resizeEvent(QResizeEvent *event) {
1018   if(!(windowState() & Qt::WindowMaximized))
1019     _normalSize = event->size();
1020
1021   QMainWindow::resizeEvent(event);
1022 }
1023
1024 void MainWin::closeEvent(QCloseEvent *event) {
1025   QtUiSettings s;
1026   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
1027   Q_ASSERT(app);
1028   if(!app->isAboutToQuit() && QtUi::haveSystemTray() && s.value("MinimizeOnClose").toBool()) {
1029     QtUi::hideMainWidget();
1030     event->ignore();
1031   } else {
1032     event->accept();
1033     quit();
1034   }
1035 }
1036
1037 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
1038   Q_UNUSED(parent);
1039
1040   bool hasFocus = QApplication::activeWindow() != 0;
1041
1042   for(int i = start; i <= end; i++) {
1043     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1044     if(!idx.isValid()) {
1045       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1046       continue;
1047     }
1048     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1049     if(flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1050       continue;
1051
1052     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1053     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1054
1055     if(hasFocus && bufId == Client::bufferModel()->currentBuffer())
1056       continue;
1057
1058     if((flags & Message::Highlight || bufType == BufferInfo::QueryBuffer)
1059       && !(Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(),
1060                                                                              Client::networkModel()->networkName(bufId))))
1061     {
1062       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1063       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1064       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1065       AbstractNotificationBackend::NotificationType type;
1066
1067       if(bufType == BufferInfo::QueryBuffer && !hasFocus)
1068         type = AbstractNotificationBackend::PrivMsg;
1069       else if(bufType == BufferInfo::QueryBuffer && hasFocus)
1070         type = AbstractNotificationBackend::PrivMsgFocused;
1071       else if(flags & Message::Highlight && !hasFocus)
1072         type = AbstractNotificationBackend::Highlight;
1073       else
1074         type = AbstractNotificationBackend::HighlightFocused;
1075
1076       QtUi::instance()->invokeNotification(bufId, type, sender, contents);
1077     }
1078   }
1079 }
1080
1081 void MainWin::currentBufferChanged(BufferId buffer) {
1082   if(buffer.isValid())
1083     Client::instance()->markBufferAsRead(buffer);
1084 }
1085
1086 void MainWin::clientNetworkCreated(NetworkId id) {
1087   const Network *net = Client::network(id);
1088   QAction *act = new QAction(net->networkName(), this);
1089   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1090   act->setData(QVariant::fromValue<NetworkId>(id));
1091   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1092   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1093
1094   QAction *beforeAction = 0;
1095   foreach(QAction *action, _networksMenu->actions()) {
1096     if(!action->data().isValid())  // ignore stock actions
1097       continue;
1098     if(net->networkName().localeAwareCompare(action->text()) < 0) {
1099       beforeAction = action;
1100       break;
1101     }
1102   }
1103   _networksMenu->insertAction(beforeAction, act);
1104 }
1105
1106 void MainWin::clientNetworkUpdated() {
1107   const Network *net = qobject_cast<const Network *>(sender());
1108   if(!net)
1109     return;
1110
1111   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1112   if(!action)
1113     return;
1114
1115   action->setText(net->networkName());
1116
1117   switch(net->connectionState()) {
1118   case Network::Initialized:
1119     action->setIcon(SmallIcon("network-connect"));
1120     break;
1121   case Network::Disconnected:
1122     action->setIcon(SmallIcon("network-disconnect"));
1123     break;
1124   default:
1125     action->setIcon(SmallIcon("network-wired"));
1126   }
1127 }
1128
1129 void MainWin::clientNetworkRemoved(NetworkId id) {
1130   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1131   if(!action)
1132     return;
1133
1134   action->deleteLater();
1135 }
1136
1137 void MainWin::connectOrDisconnectFromNet() {
1138   QAction *act = qobject_cast<QAction *>(sender());
1139   if(!act) return;
1140   const Network *net = Client::network(act->data().value<NetworkId>());
1141   if(!net) return;
1142   if(net->connectionState() == Network::Disconnected) net->requestConnect();
1143   else net->requestDisconnect();
1144 }
1145
1146 void MainWin::on_jumpHotBuffer_triggered() {
1147   if(!_bufferHotList->rowCount())
1148     return;
1149
1150   QModelIndex topIndex = _bufferHotList->index(0, 0);
1151   BufferId bufferId = _bufferHotList->data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
1152   Client::bufferModel()->switchToBuffer(bufferId);
1153 }
1154
1155 void MainWin::on_actionDebugNetworkModel_triggered() {
1156   QTreeView *view = new QTreeView;
1157   view->setAttribute(Qt::WA_DeleteOnClose);
1158   view->setWindowTitle("Debug NetworkModel View");
1159   view->setModel(Client::networkModel());
1160   view->setColumnWidth(0, 250);
1161   view->setColumnWidth(1, 250);
1162   view->setColumnWidth(2, 80);
1163   view->resize(610, 300);
1164   view->show();
1165 }
1166
1167 void MainWin::on_actionDebugHotList_triggered() {
1168   QTreeView *view = new QTreeView;
1169   view->setAttribute(Qt::WA_DeleteOnClose);
1170   view->setModel(_bufferHotList);
1171   view->show();
1172 }
1173
1174 void MainWin::on_actionDebugBufferViewOverlay_triggered() {
1175   DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1176   overlay->setAttribute(Qt::WA_DeleteOnClose);
1177   overlay->show();
1178 }
1179
1180 void MainWin::on_actionDebugMessageModel_triggered() {
1181   QTableView *view = new QTableView(0);
1182   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1183   filter->setSourceModel(Client::messageModel());
1184   view->setModel(filter);
1185   view->setAttribute(Qt::WA_DeleteOnClose, true);
1186   view->verticalHeader()->hide();
1187   view->horizontalHeader()->setStretchLastSection(true);
1188   view->show();
1189 }
1190
1191 void MainWin::on_actionDebugLog_triggered() {
1192   DebugLogWidget *logWidget = new DebugLogWidget(0);
1193   logWidget->show();
1194 }
1195
1196 void MainWin::showStatusBarMessage(const QString &message) {
1197   statusBar()->showMessage(message, 10000);
1198 }