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