a144904b304390b1f2245fd8ac5563cc7c80c1a1
[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(bool backwards) {
616   BufferView *current = activeBufferView();
617   if(current)
618     qobject_cast<BufferViewDock*>(current->parent())->setActive(false);
619
620   if(!_bufferViews.count())
621     return;
622
623   int c = _bufferViews.count();
624   while(c--) { // yes, this will reactivate the current active one if all others fail
625     if(backwards) {
626       if(--_activeBufferViewIndex < 0)
627         _activeBufferViewIndex = _bufferViews.count()-1;
628     } else {
629       if(++_activeBufferViewIndex >= _bufferViews.count())
630         _activeBufferViewIndex = 0;
631     }
632
633     BufferViewDock *dock = _bufferViews.at(_activeBufferViewIndex);
634     if(dock->isHidden())
635       continue;
636
637     dock->setActive(true);
638     return;
639   }
640
641   _activeBufferViewIndex = -1;
642 }
643
644 void MainWin::nextBufferView() {
645   changeActiveBufferView(false);
646 }
647
648 void MainWin::previousBufferView() {
649   changeActiveBufferView(true);
650 }
651
652 void MainWin::showNotificationsDlg() {
653   SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
654   dlg.exec();
655 }
656
657 void MainWin::on_actionConfigureNetworks_triggered() {
658   SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
659   dlg.exec();
660 }
661
662 void MainWin::on_actionConfigureViews_triggered() {
663   SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
664   dlg.exec();
665 }
666
667 void MainWin::on_actionLockLayout_toggled(bool lock) {
668   QList<VerticalDock *> docks = findChildren<VerticalDock *>();
669   foreach(VerticalDock *dock, docks) {
670     dock->showTitle(!lock);
671   }
672   if(Client::bufferViewManager()) {
673     foreach(ClientBufferViewConfig *config, Client::bufferViewManager()->clientBufferViewConfigs()) {
674       config->setLocked(lock);
675     }
676   }
677   QtUiSettings().setValue("LockLayout", lock);
678 }
679
680 void MainWin::setupNickWidget() {
681   // create nick dock
682   NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
683   nickDock->setObjectName("NickDock");
684   nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
685
686   _nickListWidget = new NickListWidget(nickDock);
687   nickDock->setWidget(_nickListWidget);
688
689   addDockWidget(Qt::RightDockWidgetArea, nickDock);
690   _viewMenu->addAction(nickDock->toggleViewAction());
691   nickDock->toggleViewAction()->setText(tr("Show Nick List"));
692
693   // See NickListDock::NickListDock();
694   // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
695
696   // attach the NickListWidget to the BufferModel and the default selection
697   _nickListWidget->setModel(Client::bufferModel());
698   _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
699 }
700
701 void MainWin::setupChatMonitor() {
702   VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
703   dock->setObjectName("ChatMonitorDock");
704
705   ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
706   _chatMonitorView = new ChatMonitorView(filter, this);
707   _chatMonitorView->setFocusProxy(_inputWidget);
708   _chatMonitorView->show();
709   dock->setWidget(_chatMonitorView);
710   dock->hide();
711
712   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
713   _viewMenu->addAction(dock->toggleViewAction());
714   dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
715 }
716
717 void MainWin::setupInputWidget() {
718   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
719   dock->setObjectName("InputDock");
720
721   _inputWidget = new InputWidget(dock);
722   dock->setWidget(_inputWidget);
723
724   addDockWidget(Qt::BottomDockWidgetArea, dock);
725
726   _viewMenu->addAction(dock->toggleViewAction());
727   dock->toggleViewAction()->setText(tr("Show Input Line"));
728
729   _inputWidget->setModel(Client::bufferModel());
730   _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
731
732   _bufferWidget->setFocusProxy(_inputWidget);
733
734   _inputWidget->inputLine()->installEventFilter(_bufferWidget);
735
736   connect(_topicWidget, SIGNAL(switchedPlain()), _bufferWidget, SLOT(setFocus()));
737 }
738
739 void MainWin::setupTopicWidget() {
740   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
741   dock->setObjectName("TopicDock");
742   _topicWidget = new TopicWidget(dock);
743
744   dock->setWidget(_topicWidget);
745
746   _topicWidget->setModel(Client::bufferModel());
747   _topicWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
748
749   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
750
751   _viewMenu->addAction(dock->toggleViewAction());
752   dock->toggleViewAction()->setText(tr("Show Topic Line"));
753 }
754
755 void MainWin::setupTitleSetter() {
756   _titleSetter.setModel(Client::bufferModel());
757   _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
758 }
759
760 void MainWin::setupStatusBar() {
761   // MessageProcessor progress
762   statusBar()->addPermanentWidget(_msgProcessorStatusWidget);
763
764   // Connection state
765   _coreConnectionStatusWidget->update();
766   statusBar()->addPermanentWidget(_coreConnectionStatusWidget);
767
768   QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
769
770   QtUiSettings uiSettings;
771
772   bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
773   showStatusbar->setChecked(enabled);
774   enabled ? statusBar()->show() : statusBar()->hide();
775
776   connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
777   connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
778
779   connect(Client::coreConnection(), SIGNAL(connectionMsg(QString)), statusBar(), SLOT(showMessage(QString)));
780 }
781
782 void MainWin::setupHotList() {
783   FlatProxyModel *flatProxy = new FlatProxyModel(this);
784   flatProxy->setSourceModel(Client::bufferModel());
785   _bufferHotList = new BufferHotListFilter(flatProxy);
786 }
787
788 void MainWin::saveMenuBarStatus(bool enabled) {
789   QtUiSettings uiSettings;
790   uiSettings.setValue("ShowMenuBar", enabled);
791 }
792
793 void MainWin::saveStatusBarStatus(bool enabled) {
794   QtUiSettings uiSettings;
795   uiSettings.setValue("ShowStatusBar", enabled);
796 }
797
798 void MainWin::setupSystray() {
799 #ifdef HAVE_DBUS
800   _systemTray = new StatusNotifierItem(this);
801 #elif !defined QT_NO_SYSTEMTRAYICON
802   _systemTray = new LegacySystemTray(this);
803 #else
804   _systemTray = new SystemTray(this); // dummy
805 #endif
806   _systemTray->init();
807 }
808
809 void MainWin::setupToolBars() {
810   connect(_bufferWidget, SIGNAL(currentChanged(QModelIndex)),
811           QtUi::toolBarActionProvider(), SLOT(currentBufferChanged(QModelIndex)));
812   connect(_nickListWidget, SIGNAL(nickSelectionChanged(QModelIndexList)),
813           QtUi::toolBarActionProvider(), SLOT(nickSelectionChanged(QModelIndexList)));
814
815 #ifdef Q_WS_MAC
816   setUnifiedTitleAndToolBarOnMac(true);
817 #endif
818
819 #ifdef HAVE_KDE
820   _mainToolBar = new KToolBar("MainToolBar", this, Qt::TopToolBarArea, false, true, true);
821 #else
822   _mainToolBar = new QToolBar(this);
823   _mainToolBar->setObjectName("MainToolBar");
824 #endif
825   _mainToolBar->setWindowTitle(tr("Main Toolbar"));
826   addToolBar(_mainToolBar);
827
828   QtUi::toolBarActionProvider()->addActions(_mainToolBar, ToolBarActionProvider::MainToolBar);
829   _toolbarMenu->addAction(_mainToolBar->toggleViewAction());
830 }
831
832 void MainWin::connectedToCore() {
833   Q_CHECK_PTR(Client::bufferViewManager());
834   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
835   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
836   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
837
838   setConnectedState();
839 }
840
841 void MainWin::setConnectedState() {
842   ActionCollection *coll = QtUi::actionCollection("General");
843
844   coll->action("ConnectCore")->setEnabled(false);
845   coll->action("DisconnectCore")->setEnabled(true);
846   coll->action("CoreInfo")->setEnabled(true);
847
848   foreach(QAction *action, _fileMenu->actions()) {
849     if(isRemoteCoreOnly(action))
850       action->setVisible(!Client::internalCore());
851   }
852
853   disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
854   disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
855   disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
856   if(!Client::internalCore()) {
857     connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
858     connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
859     connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
860   }
861
862   // _viewMenu->setEnabled(true);
863   if(!Client::internalCore())
864     statusBar()->showMessage(tr("Connected to core."));
865   else
866     statusBar()->clearMessage();
867
868   _coreConnectionStatusWidget->setVisible(!Client::internalCore());
869   updateIcon();
870   systemTray()->setState(SystemTray::Active);
871
872   if(Client::networkIds().isEmpty()) {
873     IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
874     wizard->show();
875   }
876   else {
877     QtUiSettings s;
878     BufferId lastUsedBufferId(s.value("LastUsedBufferId").toInt());
879     if(lastUsedBufferId.isValid())
880       Client::bufferModel()->switchToBuffer(lastUsedBufferId);
881   }
882 }
883
884 void MainWin::loadLayout() {
885   QtUiSettings s;
886   int accountId = Client::currentCoreAccount().accountId().toInt();
887   QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
888   if(state.isEmpty()) {
889     foreach(BufferViewDock *view, _bufferViews)
890       view->show();
891     _layoutLoaded = true;
892     return;
893   }
894
895   restoreState(state, accountId);
896   _layoutLoaded = true;
897 }
898
899 void MainWin::saveLayout() {
900   QtUiSettings s;
901   int accountId = _bufferViews.count()? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
902   if(accountId > 0)
903     s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
904 }
905
906 void MainWin::disconnectedFromCore() {
907   // save core specific layout and remove bufferviews;
908   saveLayout();
909   _layoutLoaded = false;
910
911   QVariant actionData;
912   BufferViewDock *dock;
913   foreach(QAction *action, _bufferViewsMenu->actions()) {
914     actionData = action->data();
915     if(!actionData.isValid())
916       continue;
917
918     dock = qobject_cast<BufferViewDock *>(action->parent());
919     if(dock && actionData.toInt() != -1) {
920       removeAction(action);
921       _bufferViews.removeAll(dock);
922       dock->deleteLater();
923     }
924   }
925
926   QtUiSettings s;
927   restoreState(s.value("MainWinState").toByteArray());
928   setDisconnectedState();
929 }
930
931 void MainWin::setDisconnectedState() {
932   ActionCollection *coll = QtUi::actionCollection("General");
933   //ui.menuCore->setEnabled(false);
934   coll->action("ConnectCore")->setEnabled(true);
935   coll->action("DisconnectCore")->setEnabled(false);
936   coll->action("CoreInfo")->setEnabled(false);
937   //_viewMenu->setEnabled(false);
938   statusBar()->showMessage(tr("Not connected to core."));
939   if(_msgProcessorStatusWidget)
940     _msgProcessorStatusWidget->setProgress(0, 0);
941   updateIcon();
942   systemTray()->setState(SystemTray::Passive);
943 }
944
945 void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage) {
946   Q_UNUSED(errorMessage)
947   CoreConnectAuthDlg dlg(account, this);
948   *valid = (dlg.exec() == QDialog::Accepted);
949 }
950
951 void MainWin::handleNoSslInClient(bool *accepted) {
952   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
953                   QMessageBox::Ignore|QMessageBox::Cancel, this);
954   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
955   box.setDefaultButton(QMessageBox::Ignore);
956   *accepted = box.exec() == QMessageBox::Ignore;
957 }
958
959 void MainWin::handleNoSslInCore(bool *accepted) {
960   QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
961                   QMessageBox::Ignore|QMessageBox::Cancel, this);
962   box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
963   box.setDefaultButton(QMessageBox::Ignore);
964   *accepted = box.exec() == QMessageBox::Ignore;
965
966 }
967
968 #ifdef HAVE_SSL
969
970 void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently) {
971   QString errorString = "<ul>";
972   foreach(const QSslError error, socket->sslErrors())
973     errorString += QString("<li>%1</li>").arg(error.errorString());
974   errorString += "</ul>";
975
976   QMessageBox box(QMessageBox::Warning,
977                   tr("Untrusted Security Certificate"),
978                   tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
979                   QMessageBox::Cancel, this);
980   box.setInformativeText(errorString);
981   box.addButton(tr("Continue"), QMessageBox::AcceptRole);
982   box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
983
984   QMessageBox::ButtonRole role;
985   do {
986     box.exec();
987     role = box.buttonRole(box.clickedButton());
988     if(role == QMessageBox::HelpRole) {
989       SslInfoDlg dlg(socket, this);
990       dlg.exec();
991     }
992   } while(role == QMessageBox::HelpRole);
993
994   *accepted = role == QMessageBox::AcceptRole;
995   if(*accepted) {
996     QMessageBox box2(QMessageBox::Warning,
997                      tr("Untrusted Security Certificate"),
998                      tr("Would you like to accept this certificate forever without being prompted?"),
999                      0, this);
1000     box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
1001     box2.addButton(tr("Forever"), QMessageBox::YesRole);
1002     box2.exec();
1003     *permanently =  box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
1004   }
1005 }
1006
1007 #endif /* HAVE_SSL */
1008
1009 void MainWin::handleCoreConnectionError(const QString &error) {
1010   QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
1011 }
1012
1013 void MainWin::showCoreConnectionDlg() {
1014   CoreConnectDlg dlg(this);
1015   if(dlg.exec() == QDialog::Accepted) {
1016     AccountId accId = dlg.selectedAccount();
1017     if(accId.isValid())
1018       Client::coreConnection()->connectToCore(accId);
1019   }
1020 }
1021
1022 void MainWin::showCoreConfigWizard(const QVariantList &backends) {
1023   CoreConfigWizard *wizard = new CoreConfigWizard(Client::coreConnection(), backends, this);
1024
1025   wizard->show();
1026 }
1027
1028 void MainWin::showChannelList(NetworkId netId) {
1029   ChannelListDlg *channelListDlg = new ChannelListDlg();
1030
1031   if(!netId.isValid()) {
1032     QAction *action = qobject_cast<QAction *>(sender());
1033     if(action)
1034       netId = action->data().value<NetworkId>();
1035   }
1036
1037   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
1038   channelListDlg->setNetwork(netId);
1039   channelListDlg->show();
1040 }
1041
1042 void MainWin::showIgnoreList(QString newRule) {
1043   SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
1044   // prepare config dialog for new rule
1045   if(!newRule.isEmpty())
1046     qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
1047   dlg.exec();
1048 }
1049
1050 void MainWin::showCoreInfoDlg() {
1051   CoreInfoDlg(this).exec();
1052 }
1053
1054 void MainWin::showAwayLog() {
1055   if(_awayLog)
1056     return;
1057   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
1058   _awayLog = new AwayLogView(filter, 0);
1059   filter->setParent(_awayLog);
1060   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
1061   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
1062   _awayLog->show();
1063 }
1064
1065 void MainWin::awayLogDestroyed() {
1066   _awayLog = 0;
1067 }
1068
1069 void MainWin::showSettingsDlg() {
1070   SettingsDlg *dlg = new SettingsDlg();
1071
1072   //Category: Interface
1073   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
1074   dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
1075   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
1076   dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
1077   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
1078   dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
1079   dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
1080   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
1081   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
1082   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
1083
1084   //Category: IRC
1085   dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
1086   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
1087   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
1088   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
1089   dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
1090
1091   // Category: Remote Cores
1092   if(Quassel::runMode() != Quassel::Monolithic) {
1093     dlg->registerSettingsPage(new CoreAccountSettingsPage(dlg));
1094     dlg->registerSettingsPage(new CoreConnectionSettingsPage(dlg));
1095   }
1096
1097   dlg->show();
1098 }
1099
1100 void MainWin::showAboutDlg() {
1101   AboutDlg(this).exec();
1102 }
1103
1104 void MainWin::showShortcutsDlg() {
1105 #ifdef HAVE_KDE
1106   KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed, this);
1107   foreach(KActionCollection *coll, QtUi::actionCollections())
1108     dlg.addCollection(coll, coll->property("Category").toString());
1109   dlg.exec();
1110 #else
1111   SettingsPageDlg dlg(new ShortcutsSettingsPage(QtUi::actionCollections(), this), this);
1112   dlg.exec();
1113 #endif
1114 }
1115
1116 /********************************************************************************************************/
1117
1118 bool MainWin::event(QEvent *event) {
1119   if(event->type() == QEvent::WindowActivate) {
1120     BufferId buffer = Client::bufferModel()->currentBuffer();
1121     if(buffer.isValid())
1122       Client::instance()->markBufferAsRead(buffer);
1123   }
1124   return QMainWindow::event(event);
1125 }
1126
1127 void MainWin::moveEvent(QMoveEvent *event) {
1128   if(!(windowState() & Qt::WindowMaximized))
1129     _normalPos = event->pos();
1130
1131   QMainWindow::moveEvent(event);
1132 }
1133
1134 void MainWin::resizeEvent(QResizeEvent *event) {
1135   if(!(windowState() & Qt::WindowMaximized))
1136     _normalSize = event->size();
1137
1138   QMainWindow::resizeEvent(event);
1139 }
1140
1141 void MainWin::closeEvent(QCloseEvent *event) {
1142   QtUiSettings s;
1143   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
1144   Q_ASSERT(app);
1145   if(!app->isAboutToQuit() && QtUi::haveSystemTray() && s.value("MinimizeOnClose").toBool()) {
1146     QtUi::hideMainWidget();
1147     event->ignore();
1148   } else {
1149     event->accept();
1150     quit();
1151   }
1152 }
1153
1154 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
1155   Q_UNUSED(parent);
1156
1157   bool hasFocus = QApplication::activeWindow() != 0;
1158
1159   for(int i = start; i <= end; i++) {
1160     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1161     if(!idx.isValid()) {
1162       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1163       continue;
1164     }
1165     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1166     if(flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1167       continue;
1168
1169     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1170     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1171
1172     if(hasFocus && bufId == Client::bufferModel()->currentBuffer())
1173       continue;
1174
1175     if((flags & Message::Highlight || bufType == BufferInfo::QueryBuffer)
1176       && !(Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(),
1177                                                                              Client::networkModel()->networkName(bufId))))
1178     {
1179       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1180       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1181       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1182       AbstractNotificationBackend::NotificationType type;
1183
1184       if(bufType == BufferInfo::QueryBuffer && !hasFocus)
1185         type = AbstractNotificationBackend::PrivMsg;
1186       else if(bufType == BufferInfo::QueryBuffer && hasFocus)
1187         type = AbstractNotificationBackend::PrivMsgFocused;
1188       else if(flags & Message::Highlight && !hasFocus)
1189         type = AbstractNotificationBackend::Highlight;
1190       else
1191         type = AbstractNotificationBackend::HighlightFocused;
1192
1193       QtUi::instance()->invokeNotification(bufId, type, sender, contents);
1194     }
1195   }
1196 }
1197
1198 void MainWin::currentBufferChanged(BufferId buffer) {
1199   if(buffer.isValid())
1200     Client::instance()->markBufferAsRead(buffer);
1201 }
1202
1203 void MainWin::clientNetworkCreated(NetworkId id) {
1204   const Network *net = Client::network(id);
1205   QAction *act = new QAction(net->networkName(), this);
1206   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1207   act->setData(QVariant::fromValue<NetworkId>(id));
1208   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1209   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1210
1211   QAction *beforeAction = 0;
1212   foreach(QAction *action, _networksMenu->actions()) {
1213     if(!action->data().isValid())  // ignore stock actions
1214       continue;
1215     if(net->networkName().localeAwareCompare(action->text()) < 0) {
1216       beforeAction = action;
1217       break;
1218     }
1219   }
1220   _networksMenu->insertAction(beforeAction, act);
1221 }
1222
1223 void MainWin::clientNetworkUpdated() {
1224   const Network *net = qobject_cast<const Network *>(sender());
1225   if(!net)
1226     return;
1227
1228   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1229   if(!action)
1230     return;
1231
1232   action->setText(net->networkName());
1233
1234   switch(net->connectionState()) {
1235   case Network::Initialized:
1236     action->setIcon(SmallIcon("network-connect"));
1237     break;
1238   case Network::Disconnected:
1239     action->setIcon(SmallIcon("network-disconnect"));
1240     break;
1241   default:
1242     action->setIcon(SmallIcon("network-wired"));
1243   }
1244 }
1245
1246 void MainWin::clientNetworkRemoved(NetworkId id) {
1247   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1248   if(!action)
1249     return;
1250
1251   action->deleteLater();
1252 }
1253
1254 void MainWin::connectOrDisconnectFromNet() {
1255   QAction *act = qobject_cast<QAction *>(sender());
1256   if(!act) return;
1257   const Network *net = Client::network(act->data().value<NetworkId>());
1258   if(!net) return;
1259   if(net->connectionState() == Network::Disconnected) net->requestConnect();
1260   else net->requestDisconnect();
1261 }
1262
1263 void MainWin::on_jumpHotBuffer_triggered() {
1264   if(!_bufferHotList->rowCount())
1265     return;
1266
1267   QModelIndex topIndex = _bufferHotList->index(0, 0);
1268   BufferId bufferId = _bufferHotList->data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
1269   Client::bufferModel()->switchToBuffer(bufferId);
1270 }
1271
1272 void MainWin::onJumpKey() {
1273   QAction *action = qobject_cast<QAction *>(sender());
1274   if(!action || !Client::bufferModel())
1275     return;
1276   int idx = action->property("Index").toInt();
1277
1278   if(_jumpKeyMap.isEmpty())
1279     _jumpKeyMap = CoreAccountSettings().jumpKeyMap();
1280
1281   if(!_jumpKeyMap.contains(idx))
1282     return;
1283
1284   BufferId buffer = _jumpKeyMap.value(idx);
1285   if(buffer.isValid())
1286     Client::bufferModel()->switchToBuffer(buffer);
1287
1288 }
1289
1290 void MainWin::bindJumpKey() {
1291   QAction *action = qobject_cast<QAction *>(sender());
1292   if(!action || !Client::bufferModel())
1293     return;
1294   int idx = action->property("Index").toInt();
1295
1296   _jumpKeyMap[idx] = Client::bufferModel()->currentBuffer();
1297   CoreAccountSettings().setJumpKeyMap(_jumpKeyMap);
1298 }
1299
1300 void MainWin::on_actionDebugNetworkModel_triggered() {
1301   QTreeView *view = new QTreeView;
1302   view->setAttribute(Qt::WA_DeleteOnClose);
1303   view->setWindowTitle("Debug NetworkModel View");
1304   view->setModel(Client::networkModel());
1305   view->setColumnWidth(0, 250);
1306   view->setColumnWidth(1, 250);
1307   view->setColumnWidth(2, 80);
1308   view->resize(610, 300);
1309   view->show();
1310 }
1311
1312 void MainWin::on_actionDebugHotList_triggered() {
1313   QTreeView *view = new QTreeView;
1314   view->setAttribute(Qt::WA_DeleteOnClose);
1315   view->setModel(_bufferHotList);
1316   view->show();
1317 }
1318
1319 void MainWin::on_actionDebugBufferViewOverlay_triggered() {
1320   DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1321   overlay->setAttribute(Qt::WA_DeleteOnClose);
1322   overlay->show();
1323 }
1324
1325 void MainWin::on_actionDebugMessageModel_triggered() {
1326   QTableView *view = new QTableView(0);
1327   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1328   filter->setSourceModel(Client::messageModel());
1329   view->setModel(filter);
1330   view->setAttribute(Qt::WA_DeleteOnClose, true);
1331   view->verticalHeader()->hide();
1332   view->horizontalHeader()->setStretchLastSection(true);
1333   view->show();
1334 }
1335
1336 void MainWin::on_actionDebugLog_triggered() {
1337   DebugLogWidget *logWidget = new DebugLogWidget(0);
1338   logWidget->show();
1339 }
1340
1341 void MainWin::showStatusBarMessage(const QString &message) {
1342   statusBar()->showMessage(message, 10000);
1343 }