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