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