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