clazy: Convert many old-style connects into function pointer based
[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(), SIGNAL(currentChanged(BufferId)), SLOT(currentBufferChanged(BufferId)));
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, SIGNAL(toggled(bool)), menuBar(), SLOT(setVisible(bool)));
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(), 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     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     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, &QAction::toggled, statusBar(), &QWidget::setVisible);
1099     connect(showStatusbar, &QAction::toggled, this, &MainWin::saveStatusBarStatus);
1100
1101     connect(Client::coreConnection(), SIGNAL(connectionMsg(QString)), statusBar(), SLOT(showMessage(QString)));
1102 }
1103
1104
1105 void MainWin::setupHotList()
1106 {
1107     auto *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(), &BufferViewManager::bufferViewConfigDeleted, this, &MainWin::removeBufferView);
1218     connect(Client::bufferViewManager(), &SyncableObject::initDone, this, &MainWin::loadLayout);
1219
1220     if (Client::transferManager()) {
1221         connect(Client::transferManager(), &TransferManager::transferAdded, this, &MainWin::showNewTransferDlg);
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(), &ClientBacklogManager::updateProgress, _msgProcessorStatusWidget, &MsgProcessorStatusWidget::setProgress);
1243     disconnect(Client::backlogManager(), &ClientBacklogManager::messagesRequested, this, &MainWin::showStatusBarMessage);
1244     disconnect(Client::backlogManager(), &ClientBacklogManager::messagesProcessed, this, &MainWin::showStatusBarMessage);
1245     if (!Client::internalCore()) {
1246         connect(Client::backlogManager(), &ClientBacklogManager::updateProgress, _msgProcessorStatusWidget, &MsgProcessorStatusWidget::setProgress);
1247         connect(Client::backlogManager(), &ClientBacklogManager::messagesRequested, this, &MainWin::showStatusBarMessage);
1248         connect(Client::backlogManager(), &ClientBacklogManager::messagesProcessed, this, &MainWin::showStatusBarMessage);
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     auto *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         auto *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     auto *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     auto *filter = new AwayLogFilter(Client::messageModel());
1520     _awayLog = new AwayLogView(filter, nullptr);
1521     filter->setParent(_awayLog);
1522     connect(_awayLog, &QObject::destroyed, this, &MainWin::awayLogDestroyed);
1523     _awayLog->setAttribute(Qt::WA_DeleteOnClose);
1524     _awayLog->show();
1525 }
1526
1527
1528 void MainWin::awayLogDestroyed()
1529 {
1530     _awayLog = nullptr;
1531 }
1532
1533
1534 void MainWin::showSettingsDlg()
1535 {
1536     auto *dlg = new SettingsDlg();
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             auto *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     auto *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() != nullptr;
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     auto *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, &SyncableObject::updatedRemotely, this, &MainWin::clientNetworkUpdated);
1756     connect(act, &QAction::triggered, this, &MainWin::connectOrDisconnectFromNet);
1757
1758     QAction *beforeAction = nullptr;
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 auto *net = qobject_cast<const Network *>(sender());
1774     if (!net)
1775         return;
1776
1777     auto *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     auto *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     auto *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     auto *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     auto *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     auto *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     auto *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     auto *overlay = new DebugBufferViewOverlay(nullptr);
1958     overlay->setAttribute(Qt::WA_DeleteOnClose);
1959     overlay->show();
1960 }
1961
1962
1963 void MainWin::on_actionDebugMessageModel_triggered()
1964 {
1965     auto *view = new QTableView(nullptr);
1966     auto *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);  // will be deleted on close
1979     dlg->show();
1980 }
1981
1982 void MainWin::on_actionShowResourceTree_triggered()
1983 {
1984     auto dlg = new ResourceTreeDlg(this);  // will be deleted on close
1985     dlg->show();
1986 }
1987
1988 void MainWin::showStatusBarMessage(const QString &message)
1989 {
1990     statusBar()->showMessage(message, 10000);
1991 }