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