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