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