8eefba18ea132dc8b07ccd3f57d7513d4475b4fb
[quassel.git] / src / qtui / mainwin.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "mainwin.h"
22
23 #include <QIcon>
24 #include <QMenuBar>
25 #include <QMessageBox>
26 #include <QStatusBar>
27 #include <QTableView>
28 #include <QToolBar>
29 #include <QInputDialog>
30
31 #ifdef HAVE_KDE4
32 #  include <KHelpMenu>
33 #  include <KMenuBar>
34 #  include <KShortcutsDialog>
35 #  include <KStatusBar>
36 #  include <KToggleFullScreenAction>
37 #  include <KToolBar>
38 #endif
39
40 #ifdef HAVE_KF5
41 #  include <KConfigWidgets/KStandardAction>
42 #  include <KXmlGui/KHelpMenu>
43 #  include <KXmlGui/KShortcutsDialog>
44 #  include <KXmlGui/KToolBar>
45 #  include <KWidgetsAddons/KToggleFullScreenAction>
46 #endif
47
48 #ifdef Q_WS_X11
49 #  include <QX11Info>
50 #endif
51
52 #include "aboutdlg.h"
53 #include "awaylogfilter.h"
54 #include "awaylogview.h"
55 #include "action.h"
56 #include "actioncollection.h"
57 #include "bufferhotlistfilter.h"
58 #include "buffermodel.h"
59 #include "bufferview.h"
60 #include "bufferviewoverlay.h"
61 #include "bufferviewoverlayfilter.h"
62 #include "bufferwidget.h"
63 #include "channellistdlg.h"
64 #include "chatlinemodel.h"
65 #include "chatmonitorfilter.h"
66 #include "chatmonitorview.h"
67 #include "chatview.h"
68 #include "client.h"
69 #include "clientbacklogmanager.h"
70 #include "clientbufferviewconfig.h"
71 #include "clientbufferviewmanager.h"
72 #include "clientignorelistmanager.h"
73 #include "clienttransfer.h"
74 #include "clienttransfermanager.h"
75 #include "coreconfigwizard.h"
76 #include "coreconnectdlg.h"
77 #include "coreconnection.h"
78 #include "coreconnectionstatuswidget.h"
79 #include "coreinfodlg.h"
80 #include "contextmenuactionprovider.h"
81 #include "debugbufferviewoverlay.h"
82 #include "debuglogwidget.h"
83 #include "debugmessagemodelfilter.h"
84 #include "flatproxymodel.h"
85 #include "inputwidget.h"
86 #include "irclistmodel.h"
87 #include "ircconnectionwizard.h"
88 #include "legacysystemtray.h"
89 #include "msgprocessorstatuswidget.h"
90 #include "nicklistwidget.h"
91 #include "passwordchangedlg.h"
92 #include "qtuiapplication.h"
93 #include "qtuimessageprocessor.h"
94 #include "qtuisettings.h"
95 #include "qtuistyle.h"
96 #include "receivefiledlg.h"
97 #include "settingsdlg.h"
98 #include "settingspagedlg.h"
99 #include "statusnotifieritem.h"
100 #include "toolbaractionprovider.h"
101 #include "topicwidget.h"
102 #include "transfermodel.h"
103 #include "verticaldock.h"
104
105 #ifndef HAVE_KDE
106 #  ifdef HAVE_QTMULTIMEDIA
107 #    include "qtmultimedianotificationbackend.h"
108 #  endif
109 #  ifdef HAVE_PHONON
110 #    include "phononnotificationbackend.h"
111 #  endif
112 #  include "systraynotificationbackend.h"
113 #  include "taskbarnotificationbackend.h"
114 #else /* HAVE_KDE */
115 #  include "knotificationbackend.h"
116 #endif /* HAVE_KDE */
117
118
119 #ifdef HAVE_LIBSNORE
120 #  include "snorenotificationbackend.h"
121 #endif
122
123 #ifdef HAVE_SSL
124 #  include "sslinfodlg.h"
125 #endif
126
127 #ifdef HAVE_INDICATEQT
128   #include "indicatornotificationbackend.h"
129 #endif
130
131 #ifdef HAVE_NOTIFICATION_CENTER
132   #include "osxnotificationbackend.h"
133 #endif
134
135 #ifdef HAVE_DBUS
136   #include "dockmanagernotificationbackend.h"
137 #endif
138
139 #include "settingspages/aliasessettingspage.h"
140 #include "settingspages/appearancesettingspage.h"
141 #include "settingspages/backlogsettingspage.h"
142 #include "settingspages/bufferviewsettingspage.h"
143 #include "settingspages/chatmonitorsettingspage.h"
144 #include "settingspages/chatviewsettingspage.h"
145 #include "settingspages/chatviewcolorsettingspage.h"
146 #include "settingspages/connectionsettingspage.h"
147 #include "settingspages/coreaccountsettingspage.h"
148 #include "settingspages/coreconnectionsettingspage.h"
149 #include <settingspages/corehighlightsettingspage.h>
150 #include "settingspages/dccsettingspage.h"
151 #include "settingspages/highlightsettingspage.h"
152 #include "settingspages/identitiessettingspage.h"
153 #include "settingspages/ignorelistsettingspage.h"
154 #include "settingspages/inputwidgetsettingspage.h"
155 #include "settingspages/itemviewsettingspage.h"
156 #include "settingspages/networkssettingspage.h"
157 #include "settingspages/notificationssettingspage.h"
158 #include "settingspages/topicwidgetsettingspage.h"
159
160 #ifndef HAVE_KDE
161 #  include "settingspages/shortcutssettingspage.h"
162 #endif
163
164 #ifdef HAVE_SONNET
165 #  include "settingspages/sonnetsettingspage.h"
166 #endif
167
168
169 MainWin::MainWin(QWidget *parent)
170 #ifdef HAVE_KDE
171     : KMainWindow(parent), _kHelpMenu(new KHelpMenu(this)),
172 #else
173     : QMainWindow(parent),
174 #endif
175     _msgProcessorStatusWidget(new MsgProcessorStatusWidget(this)),
176     _coreConnectionStatusWidget(new CoreConnectionStatusWidget(Client::coreConnection(), this)),
177     _titleSetter(this),
178     _awayLog(0),
179     _layoutLoaded(false),
180     _activeBufferViewIndex(-1),
181     _aboutToQuit(false)
182 {
183     setAttribute(Qt::WA_DeleteOnClose, false); // we delete the mainwin manually
184
185     QtUiSettings uiSettings;
186     QString style = uiSettings.value("Style", QString()).toString();
187     if (!style.isEmpty()) {
188         QApplication::setStyle(style);
189     }
190
191     QApplication::setQuitOnLastWindowClosed(false);
192
193     setWindowTitle("Quassel IRC");
194     setWindowIconText("Quassel IRC");
195     updateIcon();
196 }
197
198
199 void MainWin::init()
200 {
201     connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), SLOT(clientNetworkCreated(NetworkId)));
202     connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), SLOT(clientNetworkRemoved(NetworkId)));
203     connect(Client::messageModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
204         SLOT(messagesInserted(const QModelIndex &, int, int)));
205     connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showChannelList(NetworkId)), SLOT(showChannelList(NetworkId)));
206     connect(Client::instance(), SIGNAL(showChannelList(NetworkId)), SLOT(showChannelList(NetworkId)));
207     connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showNetworkConfig(NetworkId)), SLOT(showNetworkConfig(NetworkId)));
208     connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showIgnoreList(QString)), SLOT(showIgnoreList(QString)));
209     connect(Client::instance(), SIGNAL(showIgnoreList(QString)), SLOT(showIgnoreList(QString)));
210
211     connect(Client::coreConnection(), SIGNAL(startCoreSetup(QVariantList, QVariantList)), SLOT(showCoreConfigWizard(QVariantList, QVariantList)));
212     connect(Client::coreConnection(), SIGNAL(connectionErrorPopup(QString)), SLOT(handleCoreConnectionError(QString)));
213     connect(Client::coreConnection(), SIGNAL(userAuthenticationRequired(CoreAccount *, bool *, QString)), SLOT(userAuthenticationRequired(CoreAccount *, bool *, QString)));
214     connect(Client::coreConnection(), SIGNAL(handleNoSslInClient(bool *)), SLOT(handleNoSslInClient(bool *)));
215     connect(Client::coreConnection(), SIGNAL(handleNoSslInCore(bool *)), SLOT(handleNoSslInCore(bool *)));
216 #ifdef HAVE_SSL
217     connect(Client::coreConnection(), SIGNAL(handleSslErrors(const QSslSocket *, bool *, bool *)), SLOT(handleSslErrors(const QSslSocket *, bool *, bool *)));
218 #endif
219
220     // Setup Dock Areas
221     setDockNestingEnabled(true);
222     setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
223     setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
224     setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
225     setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
226
227     // Order is sometimes important
228     setupActions();
229     setupBufferWidget();
230     setupMenus();
231     // setupTransferWidget(); not ready yet
232     setupChatMonitor();
233     setupTopicWidget();
234     setupInputWidget();
235     setupNickWidget();
236     setupViewMenuTail();
237     setupStatusBar();
238     setupToolBars();
239     setupSystray();
240     setupTitleSetter();
241     setupHotList();
242
243     _bufferWidget->setFocusProxy(_inputWidget);
244     _chatMonitorView->setFocusProxy(_inputWidget);
245
246 #ifndef HAVE_KDE
247 #  ifdef HAVE_QTMULTIMEDIA
248     QtUi::registerNotificationBackend(new QtMultimediaNotificationBackend(this));
249 #  endif
250 #  ifdef HAVE_PHONON
251     QtUi::registerNotificationBackend(new PhononNotificationBackend(this));
252 #  endif
253     QtUi::registerNotificationBackend(new TaskbarNotificationBackend(this));
254 #else /* HAVE_KDE */
255     QtUi::registerNotificationBackend(new KNotificationBackend(this));
256 #endif /* HAVE_KDE */
257
258
259 #ifdef HAVE_LIBSNORE
260     QtUi::registerNotificationBackend(new SnoreNotificationBackend(this));
261 #elif !defined(QT_NO_SYSTEMTRAYICON) && !defined(HAVE_KDE)
262     QtUi::registerNotificationBackend(new SystrayNotificationBackend(this));
263 #endif
264
265 #ifdef HAVE_INDICATEQT
266     QtUi::registerNotificationBackend(new IndicatorNotificationBackend(this));
267 #endif
268
269 #ifdef HAVE_NOTIFICATION_CENTER
270     QtUi::registerNotificationBackend(new OSXNotificationBackend(this));
271 #endif
272
273 #ifdef HAVE_DBUS
274     QtUi::registerNotificationBackend(new DockManagerNotificationBackend(this));
275 #endif
276
277     // we assume that at this point, all configurable actions are defined!
278     QtUi::loadShortcuts();
279
280     connect(bufferWidget(), SIGNAL(currentChanged(BufferId)), SLOT(currentBufferChanged(BufferId)));
281
282     setDisconnectedState(); // Disable menus and stuff
283
284 #ifdef HAVE_KDE
285     setAutoSaveSettings();
286 #endif
287
288     // restore mainwin state
289     QtUiSettings s;
290     restoreStateFromSettings(s);
291
292     // restore locked state of docks
293     QtUi::actionCollection("General")->action("LockLayout")->setChecked(s.value("LockLayout", false).toBool());
294
295     CoreConnection *conn = Client::coreConnection();
296     if (!conn->connectToCore()) {
297         // No autoconnect selected (or no accounts)
298         showCoreConnectionDlg();
299     }
300 }
301
302
303 MainWin::~MainWin()
304 {
305 }
306
307
308 void MainWin::quit()
309 {
310     QtUiSettings s;
311     saveStateToSettings(s);
312     saveLayout();
313     QApplication::quit();
314 }
315
316
317 void MainWin::saveStateToSettings(UiSettings &s)
318 {
319     s.setValue("MainWinSize", _normalSize);
320     s.setValue("MainWinPos", _normalPos);
321     s.setValue("MainWinState", saveState());
322     s.setValue("MainWinGeometry", saveGeometry());
323     s.setValue("MainWinMinimized", isMinimized());
324     s.setValue("MainWinMaximized", isMaximized());
325     s.setValue("MainWinHidden", !isVisible());
326     BufferId lastBufId = Client::bufferModel()->currentBuffer();
327     if (lastBufId.isValid())
328         s.setValue("LastUsedBufferId", lastBufId.toInt());
329
330 #ifdef HAVE_KDE
331     saveAutoSaveSettings();
332 #endif
333 }
334
335
336 void MainWin::restoreStateFromSettings(UiSettings &s)
337 {
338     _normalSize = s.value("MainWinSize", size()).toSize();
339     _normalPos = s.value("MainWinPos", pos()).toPoint();
340     bool maximized = s.value("MainWinMaximized", false).toBool();
341
342 #ifndef HAVE_KDE
343     restoreGeometry(s.value("MainWinGeometry").toByteArray());
344
345     if (maximized) {
346         // restoreGeometry() fails if the windows was maximized, so we resize and position explicitly
347         resize(_normalSize);
348         move(_normalPos);
349     }
350
351     restoreState(s.value("MainWinState").toByteArray());
352
353 #else
354     move(_normalPos);
355 #endif
356
357     if ((Quassel::isOptionSet("hidewindow")
358             || s.value("MainWinHidden").toBool())
359             && _systemTray->isSystemTrayAvailable())
360         QtUi::hideMainWidget();
361     else if (s.value("MainWinMinimized").toBool())
362         showMinimized();
363     else if (maximized)
364         showMaximized();
365     else
366         show();
367 }
368
369 QMenu *MainWin::createPopupMenu()
370 {
371     QMenu *popupMenu = QMainWindow::createPopupMenu();
372     popupMenu->addSeparator();
373     ActionCollection *coll = QtUi::actionCollection("General");
374     popupMenu->addAction(coll->action("ToggleMenuBar"));
375     return popupMenu;
376 }
377
378
379 void MainWin::updateIcon()
380 {
381     QIcon icon;
382     if (Client::isConnected())
383         icon = QIcon::fromTheme("quassel", QIcon(":/icons/quassel-128.png"));
384     else
385         icon = QIcon::fromTheme("inactive-quassel", QIcon(":/icons/inactive-quassel.png"));
386     setWindowIcon(icon);
387     qApp->setWindowIcon(icon);
388 }
389
390
391 void MainWin::setupActions()
392 {
393     ActionCollection *coll = QtUi::actionCollection("General", tr("General"));
394     // File
395     coll->addAction("ConnectCore", new Action(QIcon::fromTheme("connect-quassel", QIcon(":/icons/connect-quassel.png")), tr("&Connect to Core..."), coll,
396             this, SLOT(showCoreConnectionDlg())));
397     coll->addAction("DisconnectCore", new Action(QIcon::fromTheme("disconnect-quassel", QIcon(":/icons/disconnect-quassel.png")), tr("&Disconnect from Core"), coll,
398             Client::instance(), SLOT(disconnectFromCore())));
399     coll->addAction("ChangePassword", new Action(QIcon::fromTheme("dialog-password"), tr("Change &Password..."), coll,
400             this, SLOT(showPasswordChangeDlg())));
401     coll->addAction("CoreInfo", new Action(QIcon::fromTheme("help-about"), tr("Core &Info..."), coll,
402             this, SLOT(showCoreInfoDlg())));
403     coll->addAction("ConfigureNetworks", new Action(QIcon::fromTheme("configure"), tr("Configure &Networks..."), coll,
404             this, SLOT(on_actionConfigureNetworks_triggered())));
405     // QKeySequence::Quit was added in Qt 4.6, and could be used instead.  However, that key
406     // sequence is empty by default on Windows, which would remove Ctrl-Q to quit.  It may be best
407     // to just keep it this way.
408     //
409     // See https://doc.qt.io/qt-5/qkeysequence.html
410     coll->addAction("Quit", new Action(QIcon::fromTheme("application-exit"), tr("&Quit"), coll,
411             this, SLOT(quit()), Qt::CTRL + Qt::Key_Q));
412
413     // View
414     coll->addAction("ConfigureBufferViews", new Action(tr("&Configure Chat Lists..."), coll,
415             this, SLOT(on_actionConfigureViews_triggered())));
416
417     QAction *lockAct = coll->addAction("LockLayout", new Action(tr("&Lock Layout"), coll));
418     lockAct->setCheckable(true);
419     connect(lockAct, SIGNAL(toggled(bool)), SLOT(on_actionLockLayout_toggled(bool)));
420
421     coll->addAction("ToggleSearchBar", new Action(QIcon::fromTheme("edit-find"), tr("Show &Search Bar"), coll,
422             0, 0, QKeySequence::Find))->setCheckable(true);
423     coll->addAction("ShowAwayLog", new Action(tr("Show Away Log"), coll,
424             this, SLOT(showAwayLog())));
425     coll->addAction("ToggleMenuBar", new Action(QIcon::fromTheme("show-menu"), tr("Show &Menubar"), coll,
426             0, 0))->setCheckable(true);
427
428     coll->addAction("ToggleStatusBar", new Action(tr("Show Status &Bar"), coll,
429             0, 0))->setCheckable(true);
430
431 #ifdef HAVE_KDE
432     _fullScreenAction = KStandardAction::fullScreen(this, SLOT(onFullScreenToggled()), this, coll);
433 #else
434     _fullScreenAction = new Action(QIcon::fromTheme("view-fullscreen"), tr("&Full Screen Mode"), coll,
435         this, SLOT(onFullScreenToggled()), QKeySequence(Qt::Key_F11));
436     _fullScreenAction->setCheckable(true);
437     coll->addAction("ToggleFullScreen", _fullScreenAction);
438 #endif
439
440     // Settings
441     QAction *configureShortcutsAct = new Action(QIcon::fromTheme("configure-shortcuts"), tr("Configure &Shortcuts..."), coll,
442         this, SLOT(showShortcutsDlg()));
443     configureShortcutsAct->setMenuRole(QAction::NoRole);
444     coll->addAction("ConfigureShortcuts", configureShortcutsAct);
445
446 #ifdef Q_OS_MAC
447     QAction *configureQuasselAct = new Action(QIcon::fromTheme("configure"), tr("&Configure Quassel..."), coll,
448         this, SLOT(showSettingsDlg()));
449     configureQuasselAct->setMenuRole(QAction::PreferencesRole);
450 #else
451     QAction *configureQuasselAct = new Action(QIcon::fromTheme("configure"), tr("&Configure Quassel..."), coll,
452         this, SLOT(showSettingsDlg()), QKeySequence(Qt::Key_F7));
453 #endif
454     coll->addAction("ConfigureQuassel", configureQuasselAct);
455
456     // Help
457     QAction *aboutQuasselAct = new Action(QIcon(":/icons/quassel.png"), tr("&About Quassel"), coll,
458         this, SLOT(showAboutDlg()));
459     aboutQuasselAct->setMenuRole(QAction::AboutRole);
460     coll->addAction("AboutQuassel", aboutQuasselAct);
461
462     QAction *aboutQtAct = new Action(QIcon(":/pics/qt-logo.png"), tr("About &Qt"), coll,
463         qApp, SLOT(aboutQt()));
464     aboutQtAct->setMenuRole(QAction::AboutQtRole);
465     coll->addAction("AboutQt", aboutQtAct);
466     coll->addAction("DebugNetworkModel", new Action(QIcon::fromTheme("tools-report-bug"), tr("Debug &NetworkModel"), coll,
467             this, SLOT(on_actionDebugNetworkModel_triggered())));
468     coll->addAction("DebugBufferViewOverlay", new Action(QIcon::fromTheme("tools-report-bug"), tr("Debug &BufferViewOverlay"), coll,
469             this, SLOT(on_actionDebugBufferViewOverlay_triggered())));
470     coll->addAction("DebugMessageModel", new Action(QIcon::fromTheme("tools-report-bug"), tr("Debug &MessageModel"), coll,
471             this, SLOT(on_actionDebugMessageModel_triggered())));
472     coll->addAction("DebugHotList", new Action(QIcon::fromTheme("tools-report-bug"), tr("Debug &HotList"), coll,
473             this, SLOT(on_actionDebugHotList_triggered())));
474     coll->addAction("DebugLog", new Action(QIcon::fromTheme("tools-report-bug"), tr("Debug &Log"), coll,
475             this, SLOT(on_actionDebugLog_triggered())));
476     coll->addAction("ReloadStyle", new Action(QIcon::fromTheme("view-refresh"), tr("Reload Stylesheet"), coll,
477             QtUi::style(), SLOT(reload()), QKeySequence::Refresh));
478
479     coll->addAction("HideCurrentBuffer", new Action(tr("Hide Current Buffer"), coll,
480             this, SLOT(hideCurrentBuffer()), QKeySequence::Close));
481
482     // Navigation
483     coll = QtUi::actionCollection("Navigation", tr("Navigation"));
484
485     coll->addAction("JumpHotBuffer", new Action(tr("Jump to hot chat"), coll,
486             this, SLOT(on_jumpHotBuffer_triggered()), QKeySequence(Qt::META + Qt::Key_A)));
487
488     coll->addAction("ActivateBufferFilter", new Action(tr("Activate the buffer search"), coll,
489             this, SLOT(on_bufferSearch_triggered()), QKeySequence(Qt::CTRL + Qt::Key_S)));
490
491     // Jump keys
492 #ifdef Q_OS_MAC
493     const int bindModifier = Qt::ControlModifier | Qt::AltModifier;
494     const int jumpModifier = Qt::ControlModifier;
495 #else
496     const int bindModifier = Qt::ControlModifier;
497     const int jumpModifier = Qt::AltModifier;
498 #endif
499
500     coll->addAction("BindJumpKey0", new Action(tr("Set Quick Access #0"), coll, this, SLOT(bindJumpKey()),
501             QKeySequence(bindModifier + Qt::Key_0)))->setProperty("Index", 0);
502     coll->addAction("BindJumpKey1", new Action(tr("Set Quick Access #1"), coll, this, SLOT(bindJumpKey()),
503             QKeySequence(bindModifier + Qt::Key_1)))->setProperty("Index", 1);
504     coll->addAction("BindJumpKey2", new Action(tr("Set Quick Access #2"), coll, this, SLOT(bindJumpKey()),
505             QKeySequence(bindModifier + Qt::Key_2)))->setProperty("Index", 2);
506     coll->addAction("BindJumpKey3", new Action(tr("Set Quick Access #3"), coll, this, SLOT(bindJumpKey()),
507             QKeySequence(bindModifier + Qt::Key_3)))->setProperty("Index", 3);
508     coll->addAction("BindJumpKey4", new Action(tr("Set Quick Access #4"), coll, this, SLOT(bindJumpKey()),
509             QKeySequence(bindModifier + Qt::Key_4)))->setProperty("Index", 4);
510     coll->addAction("BindJumpKey5", new Action(tr("Set Quick Access #5"), coll, this, SLOT(bindJumpKey()),
511             QKeySequence(bindModifier + Qt::Key_5)))->setProperty("Index", 5);
512     coll->addAction("BindJumpKey6", new Action(tr("Set Quick Access #6"), coll, this, SLOT(bindJumpKey()),
513             QKeySequence(bindModifier + Qt::Key_6)))->setProperty("Index", 6);
514     coll->addAction("BindJumpKey7", new Action(tr("Set Quick Access #7"), coll, this, SLOT(bindJumpKey()),
515             QKeySequence(bindModifier + Qt::Key_7)))->setProperty("Index", 7);
516     coll->addAction("BindJumpKey8", new Action(tr("Set Quick Access #8"), coll, this, SLOT(bindJumpKey()),
517             QKeySequence(bindModifier + Qt::Key_8)))->setProperty("Index", 8);
518     coll->addAction("BindJumpKey9", new Action(tr("Set Quick Access #9"), coll, this, SLOT(bindJumpKey()),
519             QKeySequence(bindModifier + Qt::Key_9)))->setProperty("Index", 9);
520
521     coll->addAction("JumpKey0", new Action(tr("Quick Access #0"), coll, this, SLOT(onJumpKey()),
522             QKeySequence(jumpModifier + Qt::Key_0)))->setProperty("Index", 0);
523     coll->addAction("JumpKey1", new Action(tr("Quick Access #1"), coll, this, SLOT(onJumpKey()),
524             QKeySequence(jumpModifier + Qt::Key_1)))->setProperty("Index", 1);
525     coll->addAction("JumpKey2", new Action(tr("Quick Access #2"), coll, this, SLOT(onJumpKey()),
526             QKeySequence(jumpModifier + Qt::Key_2)))->setProperty("Index", 2);
527     coll->addAction("JumpKey3", new Action(tr("Quick Access #3"), coll, this, SLOT(onJumpKey()),
528             QKeySequence(jumpModifier + Qt::Key_3)))->setProperty("Index", 3);
529     coll->addAction("JumpKey4", new Action(tr("Quick Access #4"), coll, this, SLOT(onJumpKey()),
530             QKeySequence(jumpModifier + Qt::Key_4)))->setProperty("Index", 4);
531     coll->addAction("JumpKey5", new Action(tr("Quick Access #5"), coll, this, SLOT(onJumpKey()),
532             QKeySequence(jumpModifier + Qt::Key_5)))->setProperty("Index", 5);
533     coll->addAction("JumpKey6", new Action(tr("Quick Access #6"), coll, this, SLOT(onJumpKey()),
534             QKeySequence(jumpModifier + Qt::Key_6)))->setProperty("Index", 6);
535     coll->addAction("JumpKey7", new Action(tr("Quick Access #7"), coll, this, SLOT(onJumpKey()),
536             QKeySequence(jumpModifier + Qt::Key_7)))->setProperty("Index", 7);
537     coll->addAction("JumpKey8", new Action(tr("Quick Access #8"), coll, this, SLOT(onJumpKey()),
538             QKeySequence(jumpModifier + Qt::Key_8)))->setProperty("Index", 8);
539     coll->addAction("JumpKey9", new Action(tr("Quick Access #9"), coll, this, SLOT(onJumpKey()),
540             QKeySequence(jumpModifier + Qt::Key_9)))->setProperty("Index", 9);
541
542     // Buffer navigation
543     coll->addAction("NextBufferView", new Action(QIcon::fromTheme("go-next-view"), tr("Activate Next Chat List"), coll,
544             this, SLOT(nextBufferView()), QKeySequence(QKeySequence::Forward)));
545     coll->addAction("PreviousBufferView", new Action(QIcon::fromTheme("go-previous-view"), tr("Activate Previous Chat List"), coll,
546             this, SLOT(previousBufferView()), QKeySequence::Back));
547     coll->addAction("NextBuffer", new Action(QIcon::fromTheme("go-down"), tr("Go to Next Chat"), coll,
548             this, SLOT(nextBuffer()), QKeySequence(Qt::ALT + Qt::Key_Down)));
549     coll->addAction("PreviousBuffer", new Action(QIcon::fromTheme("go-up"), tr("Go to Previous Chat"), coll,
550             this, SLOT(previousBuffer()), QKeySequence(Qt::ALT + Qt::Key_Up)));
551 }
552
553
554 void MainWin::setupMenus()
555 {
556     ActionCollection *coll = QtUi::actionCollection("General");
557
558     _fileMenu = menuBar()->addMenu(tr("&File"));
559
560     static const QStringList coreActions = QStringList()
561         << "ConnectCore" << "DisconnectCore" << "ChangePassword" << "CoreInfo";
562
563     QAction *coreAction;
564     foreach(QString actionName, coreActions) {
565         coreAction = coll->action(actionName);
566         _fileMenu->addAction(coreAction);
567         flagRemoteCoreOnly(coreAction);
568     }
569     flagRemoteCoreOnly(_fileMenu->addSeparator());
570
571     _networksMenu = _fileMenu->addMenu(tr("&Networks"));
572     _networksMenu->addAction(coll->action("ConfigureNetworks"));
573     _networksMenu->addSeparator();
574     _fileMenu->addSeparator();
575     _fileMenu->addAction(coll->action("Quit"));
576
577     _viewMenu = menuBar()->addMenu(tr("&View"));
578     _bufferViewsMenu = _viewMenu->addMenu(tr("&Chat Lists"));
579     _bufferViewsMenu->addAction(coll->action("ConfigureBufferViews"));
580     _toolbarMenu = _viewMenu->addMenu(tr("&Toolbars"));
581     _viewMenu->addSeparator();
582
583     _viewMenu->addAction(coll->action("ToggleMenuBar"));
584     _viewMenu->addAction(coll->action("ToggleStatusBar"));
585     _viewMenu->addAction(coll->action("ToggleSearchBar"));
586
587     coreAction = coll->action("ShowAwayLog");
588     flagRemoteCoreOnly(coreAction);
589     _viewMenu->addAction(coreAction);
590
591     _viewMenu->addSeparator();
592     _viewMenu->addAction(coll->action("LockLayout"));
593
594     _settingsMenu = menuBar()->addMenu(tr("&Settings"));
595 #ifdef HAVE_KDE
596     _settingsMenu->addAction(KStandardAction::configureNotifications(this, SLOT(showNotificationsDlg()), this));
597     _settingsMenu->addAction(KStandardAction::keyBindings(this, SLOT(showShortcutsDlg()), this));
598 #else
599     _settingsMenu->addAction(coll->action("ConfigureShortcuts"));
600 #endif
601     _settingsMenu->addAction(coll->action("ConfigureQuassel"));
602
603
604     _helpMenu = menuBar()->addMenu(tr("&Help"));
605
606     _helpMenu->addAction(coll->action("AboutQuassel"));
607 #ifndef HAVE_KDE
608     _helpMenu->addAction(coll->action("AboutQt"));
609 #else
610     _helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, SLOT(aboutKDE()), this));
611 #endif
612     _helpMenu->addSeparator();
613     _helpDebugMenu = _helpMenu->addMenu(QIcon::fromTheme("tools-report-bug"), tr("Debug"));
614     _helpDebugMenu->addAction(coll->action("DebugNetworkModel"));
615     _helpDebugMenu->addAction(coll->action("DebugBufferViewOverlay"));
616     _helpDebugMenu->addAction(coll->action("DebugMessageModel"));
617     _helpDebugMenu->addAction(coll->action("DebugHotList"));
618     _helpDebugMenu->addAction(coll->action("DebugLog"));
619     _helpDebugMenu->addSeparator();
620     _helpDebugMenu->addAction(coll->action("ReloadStyle"));
621
622     // Toggle visibility
623     QAction *showMenuBar = QtUi::actionCollection("General")->action("ToggleMenuBar");
624
625     QtUiSettings uiSettings;
626     bool enabled = uiSettings.value("ShowMenuBar", QVariant(true)).toBool();
627     showMenuBar->setChecked(enabled);
628     enabled ? menuBar()->show() : menuBar()->hide();
629
630     connect(showMenuBar, SIGNAL(toggled(bool)), menuBar(), SLOT(setVisible(bool)));
631     connect(showMenuBar, SIGNAL(toggled(bool)), this, SLOT(saveMenuBarStatus(bool)));
632 }
633
634
635 void MainWin::setupBufferWidget()
636 {
637     _bufferWidget = new BufferWidget(this);
638     _bufferWidget->setModel(Client::bufferModel());
639     _bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
640     setCentralWidget(_bufferWidget);
641 }
642
643
644 void MainWin::addBufferView(int bufferViewConfigId)
645 {
646     addBufferView(Client::bufferViewManager()->clientBufferViewConfig(bufferViewConfigId));
647 }
648
649
650 void MainWin::addBufferView(ClientBufferViewConfig *config)
651 {
652     if (!config)
653         return;
654
655     config->setLocked(QtUiSettings().value("LockLayout", false).toBool());
656     BufferViewDock *dock = new BufferViewDock(config, this);
657
658     //create the view and initialize it's filter
659     BufferView *view = new BufferView(dock);
660     view->setFilteredModel(Client::bufferModel(), config);
661     view->installEventFilter(_inputWidget); // for key presses
662
663     Client::bufferModel()->synchronizeView(view);
664
665     dock->setLocked(QtUiSettings().value("LockLayout", false).toBool());
666
667     dock->setWidget(view);
668     dock->setVisible(_layoutLoaded); // don't show before state has been restored
669
670     addDockWidget(Qt::LeftDockWidgetArea, dock);
671     _bufferViewsMenu->addAction(dock->toggleViewAction());
672
673     connect(dock->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(bufferViewToggled(bool)));
674     connect(dock, SIGNAL(visibilityChanged(bool)), SLOT(bufferViewVisibilityChanged(bool)));
675     _bufferViews.append(dock);
676
677     if (!activeBufferView())
678         nextBufferView();
679 }
680
681
682 void MainWin::removeBufferView(int bufferViewConfigId)
683 {
684     QVariant actionData;
685     BufferViewDock *dock;
686     foreach(QAction *action, _bufferViewsMenu->actions()) {
687         actionData = action->data();
688         if (!actionData.isValid())
689             continue;
690
691         dock = qobject_cast<BufferViewDock *>(action->parent());
692         if (dock && actionData.toInt() == bufferViewConfigId) {
693             removeAction(action);
694             Client::bufferViewOverlay()->removeView(dock->bufferViewId());
695             _bufferViews.removeAll(dock);
696
697             if (dock->isActive()) {
698                 dock->setActive(false);
699                 _activeBufferViewIndex = -1;
700                 nextBufferView();
701             }
702
703             dock->deleteLater();
704         }
705     }
706 }
707
708
709 void MainWin::bufferViewToggled(bool enabled)
710 {
711     if (!enabled && !isMinimized()) {
712         // hiding the mainwindow triggers a toggle of the bufferview (which pretty much sucks big time)
713         // since this isn't our fault and we can't do anything about it, we suppress the resulting calls
714         return;
715     }
716     QAction *action = qobject_cast<QAction *>(sender());
717     Q_ASSERT(action);
718     BufferViewDock *dock = qobject_cast<BufferViewDock *>(action->parent());
719     Q_ASSERT(dock);
720
721     // Make sure we don't toggle backlog fetch for a view we've already removed
722     if (!_bufferViews.contains(dock))
723         return;
724
725     if (enabled)
726         Client::bufferViewOverlay()->addView(dock->bufferViewId());
727     else
728         Client::bufferViewOverlay()->removeView(dock->bufferViewId());
729 }
730
731
732 void MainWin::bufferViewVisibilityChanged(bool visible)
733 {
734     Q_UNUSED(visible);
735     BufferViewDock *dock = qobject_cast<BufferViewDock *>(sender());
736     Q_ASSERT(dock);
737     if ((!dock->isHidden() && !activeBufferView()) || (dock->isHidden() && dock->isActive()))
738         nextBufferView();
739 }
740
741
742 BufferView *MainWin::allBuffersView() const
743 {
744     // "All Buffers" is always the first dock created
745     if (_bufferViews.count() > 0)
746         return _bufferViews[0]->bufferView();
747     return 0;
748 }
749
750
751 BufferView *MainWin::activeBufferView() const
752 {
753     if (_activeBufferViewIndex < 0 || _activeBufferViewIndex >= _bufferViews.count())
754         return 0;
755     BufferViewDock *dock = _bufferViews.at(_activeBufferViewIndex);
756     return dock->isActive() ? dock->bufferView() : 0;
757 }
758
759
760 void MainWin::changeActiveBufferView(int bufferViewId)
761 {
762     if (bufferViewId < 0)
763         return;
764
765     if (_activeBufferViewIndex >= 0 && _activeBufferViewIndex < _bufferViews.count()) {
766         _bufferViews[_activeBufferViewIndex]->setActive(false);
767         _activeBufferViewIndex = -1;
768     }
769
770     for (int i = 0; i < _bufferViews.count(); i++) {
771         BufferViewDock *dock = _bufferViews.at(i);
772         if (dock->bufferViewId() == bufferViewId && !dock->isHidden()) {
773             _activeBufferViewIndex = i;
774             dock->setActive(true);
775             return;
776         }
777     }
778
779     nextBufferView(); // fallback
780 }
781
782
783 void MainWin::showPasswordChangeDlg()
784 {
785     if(Client::isCoreFeatureEnabled(Quassel::Feature::PasswordChange)) {
786         PasswordChangeDlg dlg(this);
787         dlg.exec();
788     }
789     else {
790         QMessageBox box(QMessageBox::Warning, tr("Feature Not Supported"),
791                         tr("<b>Your Quassel Core does not support this feature</b>"),
792                         QMessageBox::Ok, this);
793         box.setInformativeText(tr("You need a Quassel Core v0.12.0 or newer in order to be able to remotely change your password."));
794         box.exec();
795     }
796 }
797
798
799 void MainWin::changeActiveBufferView(bool backwards)
800 {
801     if (_activeBufferViewIndex >= 0 && _activeBufferViewIndex < _bufferViews.count()) {
802         _bufferViews[_activeBufferViewIndex]->setActive(false);
803     }
804
805     if (!_bufferViews.count())
806         return;
807
808     int c = _bufferViews.count();
809     while (c--) { // yes, this will reactivate the current active one if all others fail
810         if (backwards) {
811             if (--_activeBufferViewIndex < 0)
812                 _activeBufferViewIndex = _bufferViews.count()-1;
813         }
814         else {
815             if (++_activeBufferViewIndex >= _bufferViews.count())
816                 _activeBufferViewIndex = 0;
817         }
818
819         BufferViewDock *dock = _bufferViews.at(_activeBufferViewIndex);
820         if (dock->isHidden())
821             continue;
822
823         dock->setActive(true);
824         return;
825     }
826
827     _activeBufferViewIndex = -1;
828 }
829
830
831 void MainWin::nextBufferView()
832 {
833     changeActiveBufferView(false);
834 }
835
836
837 void MainWin::previousBufferView()
838 {
839     changeActiveBufferView(true);
840 }
841
842
843 void MainWin::nextBuffer()
844 {
845     BufferView *view = activeBufferView();
846     if (view)
847         view->nextBuffer();
848 }
849
850
851 void MainWin::previousBuffer()
852 {
853     BufferView *view = activeBufferView();
854     if (view)
855         view->previousBuffer();
856 }
857
858
859 void MainWin::hideCurrentBuffer()
860 {
861     BufferView *view = activeBufferView();
862     if (view)
863         view->hideCurrentBuffer();
864 }
865
866
867 void MainWin::showNotificationsDlg()
868 {
869     SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
870     dlg.exec();
871 }
872
873
874 void MainWin::on_actionConfigureNetworks_triggered()
875 {
876     SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
877     dlg.exec();
878 }
879
880
881 void MainWin::on_actionConfigureViews_triggered()
882 {
883     SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
884     dlg.exec();
885 }
886
887
888 void MainWin::on_actionLockLayout_toggled(bool lock)
889 {
890     QList<VerticalDock *> docks = findChildren<VerticalDock *>();
891     foreach(VerticalDock *dock, docks) {
892         dock->showTitle(!lock);
893     }
894
895     QList<NickListDock *> nickdocks = findChildren<NickListDock *>();
896     foreach(NickListDock *nickdock, nickdocks) {
897         nickdock->setLocked(lock);
898     }
899
900     QList<BufferViewDock *> bufferdocks = findChildren<BufferViewDock *>();
901     foreach(BufferViewDock *bufferdock, bufferdocks) {
902         bufferdock->setLocked(lock);
903     }
904
905     if (Client::bufferViewManager()) {
906         foreach(ClientBufferViewConfig *config, Client::bufferViewManager()->clientBufferViewConfigs()) {
907             config->setLocked(lock);
908         }
909     }
910
911     _mainToolBar->setMovable(!lock);
912     _nickToolBar->setMovable(!lock);
913
914     QtUiSettings().setValue("LockLayout", lock);
915 }
916
917
918 void MainWin::setupNickWidget()
919 {
920     // create nick dock
921     NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
922     nickDock->setObjectName("NickDock");
923     nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
924     nickDock->setLocked(QtUiSettings().value("LockLayout", false).toBool());
925
926     _nickListWidget = new NickListWidget(nickDock);
927     nickDock->setWidget(_nickListWidget);
928
929     addDockWidget(Qt::RightDockWidgetArea, nickDock);
930     _viewMenu->addAction(nickDock->toggleViewAction());
931     nickDock->toggleViewAction()->setText(tr("Show Nick List"));
932
933     // See NickListDock::NickListDock();
934     // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
935
936     // attach the NickListWidget to the BufferModel and the default selection
937     _nickListWidget->setModel(Client::bufferModel());
938     _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
939
940     _nickListWidget->setVisible(false);
941 }
942
943
944 void MainWin::setupChatMonitor()
945 {
946     VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
947     dock->setObjectName("ChatMonitorDock");
948
949     ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
950     _chatMonitorView = new ChatMonitorView(filter, this);
951     _chatMonitorView->show();
952     dock->setWidget(_chatMonitorView);
953     dock->hide();
954
955     addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
956     _viewMenu->addAction(dock->toggleViewAction());
957     dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
958 }
959
960
961 void MainWin::setupInputWidget()
962 {
963     VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
964     dock->setObjectName("InputDock");
965
966     _inputWidget = new InputWidget(dock);
967     dock->setWidget(_inputWidget);
968
969     addDockWidget(Qt::BottomDockWidgetArea, dock);
970
971     _viewMenu->addAction(dock->toggleViewAction());
972     dock->toggleViewAction()->setText(tr("Show Input Line"));
973
974     _inputWidget->setModel(Client::bufferModel());
975     _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
976
977     _inputWidget->inputLine()->installEventFilter(_bufferWidget);
978
979     connect(_topicWidget, SIGNAL(switchedPlain()), _bufferWidget, SLOT(setFocus()));
980 }
981
982
983 void MainWin::setupTopicWidget()
984 {
985     VerticalDock *dock = new VerticalDock(tr("Topic"), this);
986     dock->setObjectName("TopicDock");
987     _topicWidget = new TopicWidget(dock);
988
989     dock->setWidget(_topicWidget);
990
991     _topicWidget->setModel(Client::bufferModel());
992     _topicWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
993
994     addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
995
996     _viewMenu->addAction(dock->toggleViewAction());
997     dock->toggleViewAction()->setText(tr("Show Topic Line"));
998 }
999
1000
1001 void MainWin::setupTransferWidget()
1002 {
1003     auto dock = new QDockWidget(tr("Transfers"), this);
1004     dock->setObjectName("TransferDock");
1005     dock->setAllowedAreas(Qt::TopDockWidgetArea|Qt::BottomDockWidgetArea);
1006
1007     auto view = new QTableView(dock); // to be replaced by the real thing
1008     view->setModel(Client::transferModel());
1009     dock->setWidget(view);
1010     dock->hide(); // hidden by default
1011     addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
1012
1013     auto action = dock->toggleViewAction();
1014     action->setText(tr("Show File Transfers"));
1015     action->setIcon(QIcon::fromTheme("download"));
1016     action->setShortcut(QKeySequence(Qt::Key_F6));
1017     QtUi::actionCollection("General")->addAction("ShowTransferWidget", action);
1018     _viewMenu->addAction(action);
1019 }
1020
1021
1022 void MainWin::setupViewMenuTail()
1023 {
1024     _viewMenu->addSeparator();
1025     _viewMenu->addAction(_fullScreenAction);
1026 }
1027
1028
1029 void MainWin::setupTitleSetter()
1030 {
1031     _titleSetter.setModel(Client::bufferModel());
1032     _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
1033 }
1034
1035
1036 void MainWin::setupStatusBar()
1037 {
1038     // MessageProcessor progress
1039     statusBar()->addPermanentWidget(_msgProcessorStatusWidget);
1040
1041     // Connection state
1042     _coreConnectionStatusWidget->update();
1043     statusBar()->addPermanentWidget(_coreConnectionStatusWidget);
1044
1045     QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
1046
1047     QtUiSettings uiSettings;
1048
1049     bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
1050     showStatusbar->setChecked(enabled);
1051     enabled ? statusBar()->show() : statusBar()->hide();
1052
1053     connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
1054     connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
1055
1056     connect(Client::coreConnection(), SIGNAL(connectionMsg(QString)), statusBar(), SLOT(showMessage(QString)));
1057 }
1058
1059
1060 void MainWin::setupHotList()
1061 {
1062     FlatProxyModel *flatProxy = new FlatProxyModel(this);
1063     flatProxy->setSourceModel(Client::bufferModel());
1064     _bufferHotList = new BufferHotListFilter(flatProxy);
1065 }
1066
1067
1068 void MainWin::saveMenuBarStatus(bool enabled)
1069 {
1070     QtUiSettings uiSettings;
1071     uiSettings.setValue("ShowMenuBar", enabled);
1072 }
1073
1074
1075 void MainWin::saveStatusBarStatus(bool enabled)
1076 {
1077     QtUiSettings uiSettings;
1078     uiSettings.setValue("ShowStatusBar", enabled);
1079 }
1080
1081
1082 void MainWin::setupSystray()
1083 {
1084 #ifdef HAVE_DBUS
1085     _systemTray = new StatusNotifierItem(this);
1086 #elif !defined QT_NO_SYSTEMTRAYICON
1087     _systemTray = new LegacySystemTray(this);
1088 #else
1089     _systemTray = new SystemTray(this); // dummy
1090 #endif
1091     _systemTray->init();
1092 }
1093
1094
1095 void MainWin::setupToolBars()
1096 {
1097     connect(_bufferWidget, SIGNAL(currentChanged(QModelIndex)),
1098         QtUi::toolBarActionProvider(), SLOT(currentBufferChanged(QModelIndex)));
1099     connect(_nickListWidget, SIGNAL(nickSelectionChanged(QModelIndexList)),
1100         QtUi::toolBarActionProvider(), SLOT(nickSelectionChanged(QModelIndexList)));
1101
1102 #ifdef Q_OS_MAC
1103     setUnifiedTitleAndToolBarOnMac(true);
1104 #endif
1105
1106 #ifdef HAVE_KDE
1107     _mainToolBar = new KToolBar("MainToolBar", this, Qt::TopToolBarArea, false, true, true);
1108 #else
1109     _mainToolBar = new QToolBar(this);
1110     _mainToolBar->setObjectName("MainToolBar");
1111 #endif
1112     _mainToolBar->setWindowTitle(tr("Main Toolbar"));
1113     addToolBar(_mainToolBar);
1114
1115     if (Quassel::runMode() != Quassel::Monolithic) {
1116         ActionCollection *coll = QtUi::actionCollection("General");
1117         _mainToolBar->addAction(coll->action("ConnectCore"));
1118         _mainToolBar->addAction(coll->action("DisconnectCore"));
1119     }
1120
1121     _mainToolBar->setMovable(!QtUiSettings().value("LockLayout", false).toBool());
1122
1123     QtUi::toolBarActionProvider()->addActions(_mainToolBar, ToolBarActionProvider::MainToolBar);
1124     _toolbarMenu->addAction(_mainToolBar->toggleViewAction());
1125
1126 #ifdef HAVE_KDE
1127     _nickToolBar = new KToolBar("NickToolBar", this, Qt::TopToolBarArea, false, true, true);
1128 #else
1129     _nickToolBar = new QToolBar(this);
1130     _nickToolBar->setObjectName("NickToolBar");
1131 #endif
1132     _nickToolBar->setWindowTitle(tr("Nick Toolbar"));
1133     _nickToolBar->setVisible(false); //default: not visible
1134     addToolBar(_nickToolBar);
1135     _nickToolBar->setMovable(!QtUiSettings().value("LockLayout", false).toBool());
1136
1137     QtUi::toolBarActionProvider()->addActions(_nickToolBar, ToolBarActionProvider::NickToolBar);
1138     _toolbarMenu->addAction(_nickToolBar->toggleViewAction());
1139
1140 #ifdef Q_OS_MAC
1141     QtUiSettings uiSettings;
1142
1143     bool visible = uiSettings.value("ShowMainToolBar", QVariant(true)).toBool();
1144     _mainToolBar->setVisible(visible);
1145     connect(_mainToolBar, SIGNAL(visibilityChanged(bool)), this, SLOT(saveMainToolBarStatus(bool)));
1146 #endif
1147 }
1148
1149 void MainWin::saveMainToolBarStatus(bool enabled)
1150 {
1151 #ifdef Q_OS_MAC
1152     QtUiSettings uiSettings;
1153     uiSettings.setValue("ShowMainToolBar", enabled);
1154 #else
1155     Q_UNUSED(enabled);
1156 #endif
1157 }
1158
1159
1160 void MainWin::connectedToCore()
1161 {
1162     Q_CHECK_PTR(Client::bufferViewManager());
1163     connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
1164     connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
1165     connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
1166
1167     if (Client::transferManager()) {
1168         connect(Client::transferManager(), SIGNAL(transferAdded(QUuid)), SLOT(showNewTransferDlg(QUuid)));
1169     }
1170
1171     setConnectedState();
1172 }
1173
1174
1175 void MainWin::setConnectedState()
1176 {
1177     ActionCollection *coll = QtUi::actionCollection("General");
1178
1179     coll->action("ConnectCore")->setEnabled(false);
1180     coll->action("DisconnectCore")->setEnabled(true);
1181     coll->action("ChangePassword")->setEnabled(true);
1182     coll->action("CoreInfo")->setEnabled(true);
1183
1184     foreach(QAction *action, _fileMenu->actions()) {
1185         if (isRemoteCoreOnly(action))
1186             action->setVisible(!Client::internalCore());
1187     }
1188
1189     disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
1190     disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1191     disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1192     if (!Client::internalCore()) {
1193         connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
1194         connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1195         connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1196     }
1197
1198     // _viewMenu->setEnabled(true);
1199     if (!Client::internalCore())
1200         statusBar()->showMessage(tr("Connected to core."));
1201     else
1202         statusBar()->clearMessage();
1203
1204     _coreConnectionStatusWidget->setVisible(!Client::internalCore());
1205     updateIcon();
1206     systemTray()->setState(SystemTray::Active);
1207
1208     if (Client::networkIds().isEmpty()) {
1209         IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
1210         wizard->show();
1211     }
1212     else {
1213         // Monolithic always preselects last used buffer - Client only if the connection died
1214         if (Client::coreConnection()->wasReconnect() || Quassel::runMode() == Quassel::Monolithic) {
1215             QtUiSettings s;
1216             BufferId lastUsedBufferId(s.value("LastUsedBufferId").toInt());
1217             if (lastUsedBufferId.isValid())
1218                 Client::bufferModel()->switchToBuffer(lastUsedBufferId);
1219         }
1220     }
1221 }
1222
1223
1224 void MainWin::loadLayout()
1225 {
1226     QtUiSettings s;
1227     int accountId = Client::currentCoreAccount().accountId().toInt();
1228     QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
1229     if (state.isEmpty()) {
1230         foreach(BufferViewDock *view, _bufferViews)
1231         view->show();
1232         _layoutLoaded = true;
1233         return;
1234     }
1235     _nickListWidget->setVisible(true);
1236     restoreState(state, accountId);
1237     int bufferViewId = s.value(QString("ActiveBufferView-%1").arg(accountId), -1).toInt();
1238     if (bufferViewId >= 0)
1239         changeActiveBufferView(bufferViewId);
1240
1241     _layoutLoaded = true;
1242 }
1243
1244
1245 void MainWin::saveLayout()
1246 {
1247     QtUiSettings s;
1248     int accountId = _bufferViews.count() ? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
1249     if (accountId > 0) {
1250         s.setValue(QString("MainWinState-%1").arg(accountId), saveState(accountId));
1251         BufferView *view = activeBufferView();
1252         s.setValue(QString("ActiveBufferView-%1").arg(accountId), view ? view->config()->bufferViewId() : -1);
1253     }
1254 }
1255
1256
1257 void MainWin::disconnectedFromCore()
1258 {
1259     // save core specific layout and remove bufferviews;
1260     saveLayout();
1261     _layoutLoaded = false;
1262
1263     QVariant actionData;
1264     BufferViewDock *dock;
1265     foreach(QAction *action, _bufferViewsMenu->actions()) {
1266         actionData = action->data();
1267         if (!actionData.isValid())
1268             continue;
1269
1270         dock = qobject_cast<BufferViewDock *>(action->parent());
1271         if (dock && actionData.toInt() != -1) {
1272             removeAction(action);
1273             _bufferViews.removeAll(dock);
1274             dock->deleteLater();
1275         }
1276     }
1277
1278     // store last active buffer
1279     QtUiSettings s;
1280     BufferId lastBufId = _bufferWidget->currentBuffer();
1281     if (lastBufId.isValid()) {
1282         s.setValue("LastUsedBufferId", lastBufId.toInt());
1283         // clear the current selection
1284         Client::bufferModel()->standardSelectionModel()->clearSelection();
1285     }
1286     restoreState(s.value("MainWinState").toByteArray());
1287     setDisconnectedState();
1288 }
1289
1290
1291 void MainWin::setDisconnectedState()
1292 {
1293     ActionCollection *coll = QtUi::actionCollection("General");
1294     //ui.menuCore->setEnabled(false);
1295     coll->action("ConnectCore")->setEnabled(true);
1296     coll->action("DisconnectCore")->setEnabled(false);
1297     coll->action("CoreInfo")->setEnabled(false);
1298     coll->action("ChangePassword")->setEnabled(false);
1299     //_viewMenu->setEnabled(false);
1300     statusBar()->showMessage(tr("Not connected to core."));
1301     if (_msgProcessorStatusWidget)
1302         _msgProcessorStatusWidget->setProgress(0, 0);
1303     updateIcon();
1304     systemTray()->setState(SystemTray::Passive);
1305     _nickListWidget->setVisible(false);
1306 }
1307
1308
1309 void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage)
1310 {
1311     Q_UNUSED(errorMessage)
1312     CoreConnectAuthDlg dlg(account, this);
1313     *valid = (dlg.exec() == QDialog::Accepted);
1314 }
1315
1316
1317 void MainWin::handleNoSslInClient(bool *accepted)
1318 {
1319     QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
1320         QMessageBox::Ignore|QMessageBox::Cancel, this);
1321     box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
1322     box.setDefaultButton(QMessageBox::Ignore);
1323     *accepted = box.exec() == QMessageBox::Ignore;
1324 }
1325
1326
1327 void MainWin::handleNoSslInCore(bool *accepted)
1328 {
1329     QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
1330         QMessageBox::Ignore|QMessageBox::Cancel, this);
1331     box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
1332     box.setDefaultButton(QMessageBox::Ignore);
1333     *accepted = box.exec() == QMessageBox::Ignore;
1334 }
1335
1336
1337 #ifdef HAVE_SSL
1338
1339 void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently)
1340 {
1341     QString errorString = "<ul>";
1342     foreach(const QSslError error, socket->sslErrors())
1343     errorString += QString("<li>%1</li>").arg(error.errorString());
1344     errorString += "</ul>";
1345
1346     QMessageBox box(QMessageBox::Warning,
1347         tr("Untrusted Security Certificate"),
1348         tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
1349         QMessageBox::Cancel, this);
1350     box.setInformativeText(errorString);
1351     box.addButton(tr("Continue"), QMessageBox::AcceptRole);
1352     box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
1353
1354     QMessageBox::ButtonRole role;
1355     do {
1356         box.exec();
1357         role = box.buttonRole(box.clickedButton());
1358         if (role == QMessageBox::HelpRole) {
1359             SslInfoDlg dlg(socket, this);
1360             dlg.exec();
1361         }
1362     }
1363     while (role == QMessageBox::HelpRole);
1364
1365     *accepted = role == QMessageBox::AcceptRole;
1366     if (*accepted) {
1367         QMessageBox box2(QMessageBox::Warning,
1368             tr("Untrusted Security Certificate"),
1369             tr("Would you like to accept this certificate forever without being prompted?"),
1370             0, this);
1371         box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
1372         box2.addButton(tr("Forever"), QMessageBox::YesRole);
1373         box2.exec();
1374         *permanently =  box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
1375     }
1376 }
1377
1378
1379 #endif /* HAVE_SSL */
1380
1381 void MainWin::handleCoreConnectionError(const QString &error)
1382 {
1383     QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
1384 }
1385
1386
1387 void MainWin::showCoreConnectionDlg()
1388 {
1389     CoreConnectDlg dlg(this);
1390     if (dlg.exec() == QDialog::Accepted) {
1391         AccountId accId = dlg.selectedAccount();
1392         if (accId.isValid())
1393             Client::coreConnection()->connectToCore(accId);
1394     }
1395 }
1396
1397
1398 void MainWin::showCoreConfigWizard(const QVariantList &backends, const QVariantList &authenticators)
1399 {
1400     CoreConfigWizard *wizard = new CoreConfigWizard(Client::coreConnection(), backends, authenticators, this);
1401
1402     wizard->show();
1403 }
1404
1405
1406 void MainWin::showChannelList(NetworkId netId)
1407 {
1408     ChannelListDlg *channelListDlg = new ChannelListDlg();
1409
1410     if (!netId.isValid()) {
1411         QAction *action = qobject_cast<QAction *>(sender());
1412         if (action)
1413             netId = action->data().value<NetworkId>();
1414     }
1415
1416     channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
1417     channelListDlg->setNetwork(netId);
1418     channelListDlg->show();
1419 }
1420
1421
1422 void MainWin::showNetworkConfig(NetworkId netId)
1423 {
1424     SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
1425     if (netId.isValid())
1426         qobject_cast<NetworksSettingsPage *>(dlg.currentPage())->bufferList_Open(netId);
1427     dlg.exec();
1428 }
1429
1430
1431 void MainWin::showIgnoreList(QString newRule)
1432 {
1433     SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
1434     // prepare config dialog for new rule
1435     if (!newRule.isEmpty())
1436         qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
1437     dlg.exec();
1438 }
1439
1440
1441 void MainWin::showCoreInfoDlg()
1442 {
1443     CoreInfoDlg(this).exec();
1444 }
1445
1446
1447 void MainWin::showAwayLog()
1448 {
1449     if (_awayLog)
1450         return;
1451     AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
1452     _awayLog = new AwayLogView(filter, 0);
1453     filter->setParent(_awayLog);
1454     connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
1455     _awayLog->setAttribute(Qt::WA_DeleteOnClose);
1456     _awayLog->show();
1457 }
1458
1459
1460 void MainWin::awayLogDestroyed()
1461 {
1462     _awayLog = 0;
1463 }
1464
1465
1466 void MainWin::showSettingsDlg()
1467 {
1468     SettingsDlg *dlg = new SettingsDlg();
1469
1470     //Category: Interface
1471     dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
1472     dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
1473     dlg->registerSettingsPage(new ChatViewColorSettingsPage(dlg));
1474     dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
1475     dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
1476     dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
1477     dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
1478     dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
1479 #ifdef HAVE_SONNET
1480     dlg->registerSettingsPage(new SonnetSettingsPage(dlg));
1481 #endif
1482     dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
1483     dlg->registerSettingsPage(new CoreHighlightSettingsPage(dlg));
1484     dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
1485     dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
1486
1487     //Category: IRC
1488     dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
1489     dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
1490     dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
1491     dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
1492     dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
1493     // dlg->registerSettingsPage(new DccSettingsPage(dlg)); not ready yet
1494
1495     // Category: Remote Cores
1496     if (Quassel::runMode() != Quassel::Monolithic) {
1497         dlg->registerSettingsPage(new CoreAccountSettingsPage(dlg));
1498         dlg->registerSettingsPage(new CoreConnectionSettingsPage(dlg));
1499     }
1500
1501     dlg->show();
1502 }
1503
1504
1505 void MainWin::showAboutDlg()
1506 {
1507     AboutDlg(this).exec();
1508 }
1509
1510
1511 void MainWin::showShortcutsDlg()
1512 {
1513 #ifdef HAVE_KDE
1514     KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed, this);
1515     foreach(KActionCollection *coll, QtUi::actionCollections())
1516     dlg.addCollection(coll, coll->property("Category").toString());
1517     dlg.configure(true);
1518 #else
1519     SettingsPageDlg dlg(new ShortcutsSettingsPage(QtUi::actionCollections(), this), this);
1520     dlg.exec();
1521 #endif
1522 }
1523
1524
1525 void MainWin::showNewTransferDlg(const QUuid &transferId)
1526 {
1527     auto transfer = Client::transferManager()->transfer(transferId);
1528     if (transfer) {
1529         if (transfer->status() == Transfer::Status::New) {
1530             ReceiveFileDlg *dlg = new ReceiveFileDlg(transfer, this);
1531             dlg->show();
1532         }
1533     }
1534     else {
1535         qWarning() << "Unknown transfer ID" << transferId;
1536     }
1537 }
1538
1539
1540 void MainWin::onFullScreenToggled()
1541 {
1542     // Relying on QWidget::isFullScreen is discouraged, see the KToggleFullScreenAction docs
1543     // Also, one should not use showFullScreen() or showNormal(), as those reset all other window flags
1544
1545 #ifdef HAVE_KDE
1546     static_cast<KToggleFullScreenAction*>(_fullScreenAction)->setFullScreen(this, _fullScreenAction->isChecked());
1547 #else
1548     if (_fullScreenAction->isChecked())
1549         setWindowState(windowState() | Qt::WindowFullScreen);
1550     else
1551         setWindowState(windowState() & ~Qt::WindowFullScreen);
1552 #endif
1553 }
1554
1555
1556 /********************************************************************************************************/
1557
1558 bool MainWin::event(QEvent *event)
1559 {
1560     switch(event->type()) {
1561     case QEvent::WindowActivate: {
1562         BufferId bufferId = Client::bufferModel()->currentBuffer();
1563         if (bufferId.isValid())
1564             Client::instance()->markBufferAsRead(bufferId);
1565         break;
1566     }
1567     case QEvent::WindowDeactivate:
1568         if (bufferWidget()->autoMarkerLineOnLostFocus())
1569             bufferWidget()->setMarkerLine();
1570         break;
1571     default:
1572         break;
1573     }
1574     return QMainWindow::event(event);
1575 }
1576
1577
1578 void MainWin::moveEvent(QMoveEvent *event)
1579 {
1580     if (!(windowState() & Qt::WindowMaximized))
1581         _normalPos = event->pos();
1582
1583     QMainWindow::moveEvent(event);
1584 }
1585
1586
1587 void MainWin::resizeEvent(QResizeEvent *event)
1588 {
1589     if (!(windowState() & Qt::WindowMaximized))
1590         _normalSize = event->size();
1591
1592     QMainWindow::resizeEvent(event);
1593 }
1594
1595
1596 void MainWin::closeEvent(QCloseEvent *event)
1597 {
1598     QtUiSettings s;
1599     QtUiApplication *app = qobject_cast<QtUiApplication *> qApp;
1600     Q_ASSERT(app);
1601     // On OSX it can happen that the closeEvent occurs twice. (Especially if packaged with Frameworks)
1602     // This messes up MainWinState/MainWinHidden save/restore.
1603     // It's a bug in Qt: https://bugreports.qt.io/browse/QTBUG-43344
1604     if (!_aboutToQuit && !app->isAboutToQuit() && QtUi::haveSystemTray() && s.value("MinimizeOnClose").toBool()) {
1605         QtUi::hideMainWidget();
1606         event->ignore();
1607     }
1608     else if(!_aboutToQuit) {
1609         _aboutToQuit = true;
1610         event->accept();
1611         quit();
1612     }
1613     else {
1614         event->ignore();
1615     }
1616 }
1617
1618
1619 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end)
1620 {
1621     Q_UNUSED(parent);
1622
1623     bool hasFocus = QApplication::activeWindow() != 0;
1624
1625     for (int i = start; i <= end; i++) {
1626         QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1627         if (!idx.isValid()) {
1628             qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1629             continue;
1630         }
1631         Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1632         if (flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1633             continue;
1634
1635         BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1636         BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1637
1638         // check if bufferId belongs to the shown chatlists
1639         if (!(Client::bufferViewOverlay()->bufferIds().contains(bufId) ||
1640               Client::bufferViewOverlay()->tempRemovedBufferIds().contains(bufId)))
1641             continue;
1642
1643         // check if it's the buffer currently displayed
1644         if (hasFocus && bufId == Client::bufferModel()->currentBuffer())
1645             continue;
1646
1647         // only show notifications for higlights or queries
1648         if (bufType != BufferInfo::QueryBuffer && !(flags & Message::Highlight))
1649             continue;
1650
1651         // and of course: don't notify for ignored messages
1652         if (Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(), Client::networkModel()->networkName(bufId)))
1653             continue;
1654
1655         // seems like we have a legit notification candidate!
1656         QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1657         QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1658         QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1659         AbstractNotificationBackend::NotificationType type;
1660
1661         if (bufType == BufferInfo::QueryBuffer && !hasFocus)
1662             type = AbstractNotificationBackend::PrivMsg;
1663         else if (bufType == BufferInfo::QueryBuffer && hasFocus)
1664             type = AbstractNotificationBackend::PrivMsgFocused;
1665         else if (flags & Message::Highlight && !hasFocus)
1666             type = AbstractNotificationBackend::Highlight;
1667         else
1668             type = AbstractNotificationBackend::HighlightFocused;
1669
1670         QtUi::instance()->invokeNotification(bufId, type, sender, contents);
1671     }
1672 }
1673
1674
1675 void MainWin::currentBufferChanged(BufferId buffer)
1676 {
1677     if (buffer.isValid())
1678         Client::instance()->markBufferAsRead(buffer);
1679 }
1680
1681
1682 void MainWin::clientNetworkCreated(NetworkId id)
1683 {
1684     const Network *net = Client::network(id);
1685     QAction *act = new QAction(net->networkName(), this);
1686     act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1687     act->setData(QVariant::fromValue<NetworkId>(id));
1688     connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1689     connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1690
1691     QAction *beforeAction = 0;
1692     foreach(QAction *action, _networksMenu->actions()) {
1693         if (!action->data().isValid()) // ignore stock actions
1694             continue;
1695         if (net->networkName().localeAwareCompare(action->text()) < 0) {
1696             beforeAction = action;
1697             break;
1698         }
1699     }
1700     _networksMenu->insertAction(beforeAction, act);
1701 }
1702
1703
1704 void MainWin::clientNetworkUpdated()
1705 {
1706     const Network *net = qobject_cast<const Network *>(sender());
1707     if (!net)
1708         return;
1709
1710     QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1711     if (!action)
1712         return;
1713
1714     action->setText(net->networkName());
1715
1716     switch (net->connectionState()) {
1717     case Network::Initialized:
1718         action->setIcon(QIcon::fromTheme("network-connect"));
1719         // if we have no currently selected buffer, jump to the first connecting statusbuffer
1720         if (!bufferWidget()->currentBuffer().isValid()) {
1721             QModelIndex idx = Client::networkModel()->networkIndex(net->networkId());
1722             if (idx.isValid()) {
1723                 BufferId statusBufferId = idx.data(NetworkModel::BufferIdRole).value<BufferId>();
1724                 Client::bufferModel()->switchToBuffer(statusBufferId);
1725             }
1726         }
1727         break;
1728     case Network::Disconnected:
1729         action->setIcon(QIcon::fromTheme("network-disconnect"));
1730         break;
1731     default:
1732         action->setIcon(QIcon::fromTheme("network-wired"));
1733     }
1734 }
1735
1736
1737 void MainWin::clientNetworkRemoved(NetworkId id)
1738 {
1739     QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1740     if (!action)
1741         return;
1742
1743     action->deleteLater();
1744 }
1745
1746
1747 void MainWin::connectOrDisconnectFromNet()
1748 {
1749     QAction *act = qobject_cast<QAction *>(sender());
1750     if (!act) return;
1751     const Network *net = Client::network(act->data().value<NetworkId>());
1752     if (!net) return;
1753     if (net->connectionState() == Network::Disconnected) net->requestConnect();
1754     else net->requestDisconnect();
1755 }
1756
1757
1758 void MainWin::on_jumpHotBuffer_triggered()
1759 {
1760     if (!_bufferHotList->rowCount())
1761         return;
1762
1763     Client::bufferModel()->switchToBuffer(_bufferHotList->hottestBuffer());
1764 }
1765
1766 void MainWin::on_bufferSearch_triggered()
1767 {
1768     if (_activeBufferViewIndex < 0 || _activeBufferViewIndex >= _bufferViews.count()) {
1769         qWarning() << "Tried to activate filter on invalid bufferview:" << _activeBufferViewIndex;
1770         return;
1771     }
1772
1773     _bufferViews[_activeBufferViewIndex]->activateFilter();
1774 }
1775
1776
1777 void MainWin::onJumpKey()
1778 {
1779     QAction *action = qobject_cast<QAction *>(sender());
1780     if (!action || !Client::bufferModel())
1781         return;
1782     int idx = action->property("Index").toInt();
1783
1784     if (_jumpKeyMap.isEmpty())
1785         _jumpKeyMap = CoreAccountSettings().jumpKeyMap();
1786
1787     if (!_jumpKeyMap.contains(idx))
1788         return;
1789
1790     BufferId buffer = _jumpKeyMap.value(idx);
1791     if (buffer.isValid())
1792         Client::bufferModel()->switchToBuffer(buffer);
1793 }
1794
1795
1796 void MainWin::bindJumpKey()
1797 {
1798     QAction *action = qobject_cast<QAction *>(sender());
1799     if (!action || !Client::bufferModel())
1800         return;
1801     int idx = action->property("Index").toInt();
1802
1803     _jumpKeyMap[idx] = Client::bufferModel()->currentBuffer();
1804     CoreAccountSettings().setJumpKeyMap(_jumpKeyMap);
1805 }
1806
1807
1808 void MainWin::on_actionDebugNetworkModel_triggered()
1809 {
1810     QTreeView *view = new QTreeView;
1811     view->setAttribute(Qt::WA_DeleteOnClose);
1812     view->setWindowTitle("Debug NetworkModel View");
1813     view->setModel(Client::networkModel());
1814     view->setColumnWidth(0, 250);
1815     view->setColumnWidth(1, 250);
1816     view->setColumnWidth(2, 80);
1817     view->resize(610, 300);
1818     view->show();
1819 }
1820
1821
1822 void MainWin::on_actionDebugHotList_triggered()
1823 {
1824     _bufferHotList->invalidate();
1825     _bufferHotList->sort(0, Qt::DescendingOrder);
1826
1827     QTreeView *view = new QTreeView;
1828     view->setAttribute(Qt::WA_DeleteOnClose);
1829     view->setModel(_bufferHotList);
1830     view->show();
1831 }
1832
1833
1834 void MainWin::on_actionDebugBufferViewOverlay_triggered()
1835 {
1836     DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1837     overlay->setAttribute(Qt::WA_DeleteOnClose);
1838     overlay->show();
1839 }
1840
1841
1842 void MainWin::on_actionDebugMessageModel_triggered()
1843 {
1844     QTableView *view = new QTableView(0);
1845     DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1846     filter->setSourceModel(Client::messageModel());
1847     view->setModel(filter);
1848     view->setAttribute(Qt::WA_DeleteOnClose, true);
1849     view->verticalHeader()->hide();
1850     view->horizontalHeader()->setStretchLastSection(true);
1851     view->show();
1852 }
1853
1854
1855 void MainWin::on_actionDebugLog_triggered()
1856 {
1857     DebugLogWidget *logWidget = new DebugLogWidget(0);
1858     logWidget->show();
1859 }
1860
1861
1862 void MainWin::showStatusBarMessage(const QString &message)
1863 {
1864     statusBar()->showMessage(message, 10000);
1865 }