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