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