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