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