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