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