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