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