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