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