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