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