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