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