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