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