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