introduce fullscreen mode, fixes #803
[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     QtUiSettings s;
924     BufferId lastUsedBufferId(s.value("LastUsedBufferId").toInt());
925     if(lastUsedBufferId.isValid())
926       Client::bufferModel()->switchToBuffer(lastUsedBufferId);
927   }
928 }
929
930 void MainWin::loadLayout() {
931   QtUiSettings s;
932   int accountId = Client::currentCoreAccount().accountId().toInt();
933   QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
934   if(state.isEmpty()) {
935     foreach(BufferViewDock *view, _bufferViews)
936       view->show();
937     _layoutLoaded = true;
938     return;
939   }
940
941   restoreState(state, accountId);
942   int bufferViewId = s.value(QString("ActiveBufferView-%1").arg(accountId), -1).toInt();
943   if(bufferViewId >= 0)
944     changeActiveBufferView(bufferViewId);
945
946   _layoutLoaded = true;
947 }
948
949 void MainWin::saveLayout() {
950   QtUiSettings s;
951   int accountId = _bufferViews.count()? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
952   if(accountId > 0) {
953     s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
954     BufferView *view = activeBufferView();
955     s.setValue(QString("ActiveBufferView-%1").arg(accountId), view ? view->config()->bufferViewId() : -1);
956   }
957 }
958
959 void MainWin::disconnectedFromCore() {
960   // save core specific layout and remove bufferviews;
961   saveLayout();
962   _layoutLoaded = false;
963
964   QVariant actionData;
965   BufferViewDock *dock;
966   foreach(QAction *action, _bufferViewsMenu->actions()) {
967     actionData = action->data();
968     if(!actionData.isValid())
969       continue;
970
971     dock = qobject_cast<BufferViewDock *>(action->parent());
972     if(dock && actionData.toInt() != -1) {
973       removeAction(action);
974       _bufferViews.removeAll(dock);
975       dock->deleteLater();
976     }
977   }
978
979   QtUiSettings s;
980   restoreState(s.value("MainWinState").toByteArray());
981   setDisconnectedState();
982 }
983
984 void MainWin::setDisconnectedState() {
985   ActionCollection *coll = QtUi::actionCollection("General");
986   //ui.menuCore->setEnabled(false);
987   coll->action("ConnectCore")->setEnabled(true);
988   coll->action("DisconnectCore")->setEnabled(false);
989   coll->action("CoreInfo")->setEnabled(false);
990   //_viewMenu->setEnabled(false);
991   statusBar()->showMessage(tr("Not connected to core."));
992   if(_msgProcessorStatusWidget)
993     _msgProcessorStatusWidget->setProgress(0, 0);
994   updateIcon();
995   systemTray()->setState(SystemTray::Passive);
996 }
997
998 void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage) {
999   Q_UNUSED(errorMessage)
1000   CoreConnectAuthDlg dlg(account, this);
1001   *valid = (dlg.exec() == QDialog::Accepted);
1002 }
1003
1004 void MainWin::handleNoSslInClient(bool *accepted) {
1005   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
1006                   QMessageBox::Ignore|QMessageBox::Cancel, this);
1007   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
1008   box.setDefaultButton(QMessageBox::Ignore);
1009   *accepted = box.exec() == QMessageBox::Ignore;
1010 }
1011
1012 void MainWin::handleNoSslInCore(bool *accepted) {
1013   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
1014                   QMessageBox::Ignore|QMessageBox::Cancel, this);
1015   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
1016   box.setDefaultButton(QMessageBox::Ignore);
1017   *accepted = box.exec() == QMessageBox::Ignore;
1018
1019 }
1020
1021 #ifdef HAVE_SSL
1022
1023 void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently) {
1024   QString errorString = "<ul>";
1025   foreach(const QSslError error, socket->sslErrors())
1026     errorString += QString("<li>%1</li>").arg(error.errorString());
1027   errorString += "</ul>";
1028
1029   QMessageBox box(QMessageBox::Warning,
1030                   tr("Untrusted Security Certificate"),
1031                   tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
1032                   QMessageBox::Cancel, this);
1033   box.setInformativeText(errorString);
1034   box.addButton(tr("Continue"), QMessageBox::AcceptRole);
1035   box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
1036
1037   QMessageBox::ButtonRole role;
1038   do {
1039     box.exec();
1040     role = box.buttonRole(box.clickedButton());
1041     if(role == QMessageBox::HelpRole) {
1042       SslInfoDlg dlg(socket, this);
1043       dlg.exec();
1044     }
1045   } while(role == QMessageBox::HelpRole);
1046
1047   *accepted = role == QMessageBox::AcceptRole;
1048   if(*accepted) {
1049     QMessageBox box2(QMessageBox::Warning,
1050                      tr("Untrusted Security Certificate"),
1051                      tr("Would you like to accept this certificate forever without being prompted?"),
1052                      0, this);
1053     box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
1054     box2.addButton(tr("Forever"), QMessageBox::YesRole);
1055     box2.exec();
1056     *permanently =  box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
1057   }
1058 }
1059
1060 #endif /* HAVE_SSL */
1061
1062 void MainWin::handleCoreConnectionError(const QString &error) {
1063   QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
1064 }
1065
1066 void MainWin::showCoreConnectionDlg() {
1067   CoreConnectDlg dlg(this);
1068   if(dlg.exec() == QDialog::Accepted) {
1069     AccountId accId = dlg.selectedAccount();
1070     if(accId.isValid())
1071       Client::coreConnection()->connectToCore(accId);
1072   }
1073 }
1074
1075 void MainWin::showCoreConfigWizard(const QVariantList &backends) {
1076   CoreConfigWizard *wizard = new CoreConfigWizard(Client::coreConnection(), backends, this);
1077
1078   wizard->show();
1079 }
1080
1081 void MainWin::showChannelList(NetworkId netId) {
1082   ChannelListDlg *channelListDlg = new ChannelListDlg();
1083
1084   if(!netId.isValid()) {
1085     QAction *action = qobject_cast<QAction *>(sender());
1086     if(action)
1087       netId = action->data().value<NetworkId>();
1088   }
1089
1090   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
1091   channelListDlg->setNetwork(netId);
1092   channelListDlg->show();
1093 }
1094
1095 void MainWin::showIgnoreList(QString newRule) {
1096   SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
1097   // prepare config dialog for new rule
1098   if(!newRule.isEmpty())
1099     qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
1100   dlg.exec();
1101 }
1102
1103 void MainWin::showCoreInfoDlg() {
1104   CoreInfoDlg(this).exec();
1105 }
1106
1107 void MainWin::showAwayLog() {
1108   if(_awayLog)
1109     return;
1110   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
1111   _awayLog = new AwayLogView(filter, 0);
1112   filter->setParent(_awayLog);
1113   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
1114   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
1115   _awayLog->show();
1116 }
1117
1118 void MainWin::awayLogDestroyed() {
1119   _awayLog = 0;
1120 }
1121
1122 void MainWin::showSettingsDlg() {
1123   SettingsDlg *dlg = new SettingsDlg();
1124
1125   //Category: Interface
1126   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
1127   dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
1128   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
1129   dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
1130   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
1131   dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
1132   dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
1133   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
1134   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
1135   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
1136
1137   //Category: IRC
1138   dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
1139   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
1140   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
1141   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
1142   dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
1143
1144   // Category: Remote Cores
1145   if(Quassel::runMode() != Quassel::Monolithic) {
1146     dlg->registerSettingsPage(new CoreAccountSettingsPage(dlg));
1147     dlg->registerSettingsPage(new CoreConnectionSettingsPage(dlg));
1148   }
1149
1150   dlg->show();
1151 }
1152
1153 void MainWin::showAboutDlg() {
1154   AboutDlg(this).exec();
1155 }
1156
1157 void MainWin::showShortcutsDlg() {
1158 #ifdef HAVE_KDE
1159   KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed, this);
1160   foreach(KActionCollection *coll, QtUi::actionCollections())
1161     dlg.addCollection(coll, coll->property("Category").toString());
1162   dlg.exec();
1163 #else
1164   SettingsPageDlg dlg(new ShortcutsSettingsPage(QtUi::actionCollections(), this), this);
1165   dlg.exec();
1166 #endif
1167 }
1168
1169 void MainWin::toggleFullscreen() {
1170   QAction *action = QtUi::actionCollection("General")->action("ToggleFullscreen");
1171
1172   if(isFullScreen()) {
1173     showNormal();
1174     action->setIcon(SmallIcon("window_fullscreen"));
1175     action->setText(tr("&Fullscreen mode"));
1176   }
1177   else {
1178     showFullScreen();
1179     action->setIcon(SmallIcon("window_nofullscreen"));
1180     action->setText(tr("&Normal mode"));
1181   }
1182 }
1183
1184 /********************************************************************************************************/
1185
1186 bool MainWin::event(QEvent *event) {
1187   if(event->type() == QEvent::WindowActivate) {
1188     BufferId buffer = Client::bufferModel()->currentBuffer();
1189     if(buffer.isValid())
1190       Client::instance()->markBufferAsRead(buffer);
1191   }
1192   return QMainWindow::event(event);
1193 }
1194
1195 void MainWin::moveEvent(QMoveEvent *event) {
1196   if(!(windowState() & Qt::WindowMaximized))
1197     _normalPos = event->pos();
1198
1199   QMainWindow::moveEvent(event);
1200 }
1201
1202 void MainWin::resizeEvent(QResizeEvent *event) {
1203   if(!(windowState() & Qt::WindowMaximized))
1204     _normalSize = event->size();
1205
1206   QMainWindow::resizeEvent(event);
1207 }
1208
1209 void MainWin::closeEvent(QCloseEvent *event) {
1210   QtUiSettings s;
1211   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
1212   Q_ASSERT(app);
1213   if(!app->isAboutToQuit() && QtUi::haveSystemTray() && s.value("MinimizeOnClose").toBool()) {
1214     QtUi::hideMainWidget();
1215     event->ignore();
1216   } else {
1217     event->accept();
1218     quit();
1219   }
1220 }
1221
1222 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
1223   Q_UNUSED(parent);
1224
1225   bool hasFocus = QApplication::activeWindow() != 0;
1226
1227   for(int i = start; i <= end; i++) {
1228     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1229     if(!idx.isValid()) {
1230       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1231       continue;
1232     }
1233     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1234     if(flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1235       continue;
1236
1237     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1238     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1239
1240     if(hasFocus && bufId == Client::bufferModel()->currentBuffer())
1241       continue;
1242
1243     if((flags & Message::Highlight || bufType == BufferInfo::QueryBuffer)
1244       && !(Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(),
1245                                                                              Client::networkModel()->networkName(bufId))))
1246     {
1247       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1248       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1249       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1250       AbstractNotificationBackend::NotificationType type;
1251
1252       if(bufType == BufferInfo::QueryBuffer && !hasFocus)
1253         type = AbstractNotificationBackend::PrivMsg;
1254       else if(bufType == BufferInfo::QueryBuffer && hasFocus)
1255         type = AbstractNotificationBackend::PrivMsgFocused;
1256       else if(flags & Message::Highlight && !hasFocus)
1257         type = AbstractNotificationBackend::Highlight;
1258       else
1259         type = AbstractNotificationBackend::HighlightFocused;
1260
1261       QtUi::instance()->invokeNotification(bufId, type, sender, contents);
1262     }
1263   }
1264 }
1265
1266 void MainWin::currentBufferChanged(BufferId buffer) {
1267   if(buffer.isValid())
1268     Client::instance()->markBufferAsRead(buffer);
1269 }
1270
1271 void MainWin::clientNetworkCreated(NetworkId id) {
1272   const Network *net = Client::network(id);
1273   QAction *act = new QAction(net->networkName(), this);
1274   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1275   act->setData(QVariant::fromValue<NetworkId>(id));
1276   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1277   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1278
1279   QAction *beforeAction = 0;
1280   foreach(QAction *action, _networksMenu->actions()) {
1281     if(!action->data().isValid())  // ignore stock actions
1282       continue;
1283     if(net->networkName().localeAwareCompare(action->text()) < 0) {
1284       beforeAction = action;
1285       break;
1286     }
1287   }
1288   _networksMenu->insertAction(beforeAction, act);
1289 }
1290
1291 void MainWin::clientNetworkUpdated() {
1292   const Network *net = qobject_cast<const Network *>(sender());
1293   if(!net)
1294     return;
1295
1296   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1297   if(!action)
1298     return;
1299
1300   action->setText(net->networkName());
1301
1302   switch(net->connectionState()) {
1303   case Network::Initialized:
1304     action->setIcon(SmallIcon("network-connect"));
1305     break;
1306   case Network::Disconnected:
1307     action->setIcon(SmallIcon("network-disconnect"));
1308     break;
1309   default:
1310     action->setIcon(SmallIcon("network-wired"));
1311   }
1312 }
1313
1314 void MainWin::clientNetworkRemoved(NetworkId id) {
1315   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1316   if(!action)
1317     return;
1318
1319   action->deleteLater();
1320 }
1321
1322 void MainWin::connectOrDisconnectFromNet() {
1323   QAction *act = qobject_cast<QAction *>(sender());
1324   if(!act) return;
1325   const Network *net = Client::network(act->data().value<NetworkId>());
1326   if(!net) return;
1327   if(net->connectionState() == Network::Disconnected) net->requestConnect();
1328   else net->requestDisconnect();
1329 }
1330
1331 void MainWin::on_jumpHotBuffer_triggered() {
1332   if(!_bufferHotList->rowCount())
1333     return;
1334
1335   QModelIndex topIndex = _bufferHotList->index(0, 0);
1336   BufferId bufferId = _bufferHotList->data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
1337   Client::bufferModel()->switchToBuffer(bufferId);
1338 }
1339
1340 void MainWin::onJumpKey() {
1341   QAction *action = qobject_cast<QAction *>(sender());
1342   if(!action || !Client::bufferModel())
1343     return;
1344   int idx = action->property("Index").toInt();
1345
1346   if(_jumpKeyMap.isEmpty())
1347     _jumpKeyMap = CoreAccountSettings().jumpKeyMap();
1348
1349   if(!_jumpKeyMap.contains(idx))
1350     return;
1351
1352   BufferId buffer = _jumpKeyMap.value(idx);
1353   if(buffer.isValid())
1354     Client::bufferModel()->switchToBuffer(buffer);
1355
1356 }
1357
1358 void MainWin::bindJumpKey() {
1359   QAction *action = qobject_cast<QAction *>(sender());
1360   if(!action || !Client::bufferModel())
1361     return;
1362   int idx = action->property("Index").toInt();
1363
1364   _jumpKeyMap[idx] = Client::bufferModel()->currentBuffer();
1365   CoreAccountSettings().setJumpKeyMap(_jumpKeyMap);
1366 }
1367
1368 void MainWin::on_actionDebugNetworkModel_triggered() {
1369   QTreeView *view = new QTreeView;
1370   view->setAttribute(Qt::WA_DeleteOnClose);
1371   view->setWindowTitle("Debug NetworkModel View");
1372   view->setModel(Client::networkModel());
1373   view->setColumnWidth(0, 250);
1374   view->setColumnWidth(1, 250);
1375   view->setColumnWidth(2, 80);
1376   view->resize(610, 300);
1377   view->show();
1378 }
1379
1380 void MainWin::on_actionDebugHotList_triggered() {
1381   QTreeView *view = new QTreeView;
1382   view->setAttribute(Qt::WA_DeleteOnClose);
1383   view->setModel(_bufferHotList);
1384   view->show();
1385 }
1386
1387 void MainWin::on_actionDebugBufferViewOverlay_triggered() {
1388   DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1389   overlay->setAttribute(Qt::WA_DeleteOnClose);
1390   overlay->show();
1391 }
1392
1393 void MainWin::on_actionDebugMessageModel_triggered() {
1394   QTableView *view = new QTableView(0);
1395   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1396   filter->setSourceModel(Client::messageModel());
1397   view->setModel(filter);
1398   view->setAttribute(Qt::WA_DeleteOnClose, true);
1399   view->verticalHeader()->hide();
1400   view->horizontalHeader()->setStretchLastSection(true);
1401   view->show();
1402 }
1403
1404 void MainWin::on_actionDebugLog_triggered() {
1405   DebugLogWidget *logWidget = new DebugLogWidget(0);
1406   logWidget->show();
1407 }
1408
1409 void MainWin::showStatusBarMessage(const QString &message) {
1410   statusBar()->showMessage(message, 10000);
1411 }