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