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