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