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