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