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