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