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