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