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