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