Introduce GraphicalUi (between QtUi and AbstractUi), rename NetworkModelActionProvider
[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 #endif
30
31 #include "aboutdlg.h"
32 #include "awaylogfilter.h"
33 #include "awaylogview.h"
34 #include "action.h"
35 #include "actioncollection.h"
36 #include "buffermodel.h"
37 #include "bufferview.h"
38 #include "bufferviewmanager.h"
39 #include "bufferwidget.h"
40 #include "channellistdlg.h"
41 #include "chatlinemodel.h"
42 #include "chatmonitorfilter.h"
43 #include "chatmonitorview.h"
44 #include "chatview.h"
45 #include "client.h"
46 #include "clientsyncer.h"
47 #include "clientbacklogmanager.h"
48 #include "coreinfodlg.h"
49 #include "coreconnectdlg.h"
50 #include "contextmenuactionprovider.h"
51 #include "debuglogwidget.h"
52 #include "debugmessagemodelfilter.h"
53 #include "iconloader.h"
54 #include "inputwidget.h"
55 #include "inputline.h"
56 #include "irclistmodel.h"
57 #include "jumpkeyhandler.h"
58 #include "msgprocessorstatuswidget.h"
59 #include "nicklistwidget.h"
60 #include "qtuiapplication.h"
61 #include "qtuimessageprocessor.h"
62 #include "qtuisettings.h"
63 #include "sessionsettings.h"
64 #include "settingsdlg.h"
65 #include "settingspagedlg.h"
66 #include "topicwidget.h"
67 #include "verticaldock.h"
68
69 #ifndef HAVE_KDE
70 #  ifdef HAVE_DBUS
71 #    include "desktopnotificationbackend.h"
72 #  endif
73 #  ifdef HAVE_PHONON
74 #    include "phononnotificationbackend.h"
75 #  endif
76 #  include "systraynotificationbackend.h"
77 #  include "taskbarnotificationbackend.h"
78 #else /* HAVE_KDE */
79 #  include "knotificationbackend.h"
80 #endif /* HAVE_KDE */
81
82 #include "settingspages/aliasessettingspage.h"
83 #include "settingspages/appearancesettingspage.h"
84 #include "settingspages/backlogsettingspage.h"
85 #include "settingspages/bufferviewsettingspage.h"
86 #include "settingspages/chatmonitorsettingspage.h"
87 #include "settingspages/colorsettingspage.h"
88 #include "settingspages/fontssettingspage.h"
89 #include "settingspages/generalsettingspage.h"
90 #include "settingspages/highlightsettingspage.h"
91 #include "settingspages/identitiessettingspage.h"
92 #include "settingspages/networkssettingspage.h"
93 #include "settingspages/notificationssettingspage.h"
94
95 MainWin::MainWin(QWidget *parent)
96 #ifdef HAVE_KDE
97   : KMainWindow(parent),
98   _kHelpMenu(new KHelpMenu(this, KGlobal::mainComponent().aboutData())),
99 #else
100   : QMainWindow(parent),
101 #endif
102     coreLagLabel(new QLabel()),
103     sslLabel(new QLabel()),
104     msgProcessorStatusWidget(new MsgProcessorStatusWidget()),
105     _titleSetter(this),
106     _trayIcon(new QSystemTrayIcon(this)),
107     _awayLog(0)
108 {
109   QtUiSettings uiSettings;
110   QString style = uiSettings.value("Style", QString()).toString();
111   if(!style.isEmpty()) {
112     QApplication::setStyle(style);
113   }
114
115   QApplication::setQuitOnLastWindowClosed(false);
116
117   setWindowTitle("Quassel IRC");
118   setWindowIconText("Quassel IRC");
119   updateIcon();
120
121   installEventFilter(new JumpKeyHandler(this));
122
123   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
124   connect(app, SIGNAL(saveStateToSession(const QString&)), SLOT(saveStateToSession(const QString&)));
125   connect(app, SIGNAL(saveStateToSessionSettings(SessionSettings&)), SLOT(saveStateToSessionSettings(SessionSettings&)));
126 }
127
128 void MainWin::init() {
129   QtUiSettings s;
130   if(s.value("MainWinSize").isValid())
131     resize(s.value("MainWinSize").toSize());
132   else
133     resize(QSize(800, 500));
134
135   connect(QApplication::instance(), SIGNAL(aboutToQuit()), SLOT(saveLayout()));
136   connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), SLOT(clientNetworkCreated(NetworkId)));
137   connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), SLOT(clientNetworkRemoved(NetworkId)));
138   connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showChannelList(NetworkId)), SLOT(showChannelList(NetworkId)));
139
140   // Setup Dock Areas
141   setDockNestingEnabled(true);
142   setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
143   setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
144   setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
145   setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
146
147   // Order is sometimes important
148   setupActions();
149   setupBufferWidget();
150   setupMenus();
151   setupTopicWidget();
152   setupChatMonitor();
153   setupNickWidget();
154   setupInputWidget();
155   setupStatusBar();
156   setupSystray();
157   setupTitleSetter();
158
159 #ifndef HAVE_KDE
160   QtUi::registerNotificationBackend(new TaskbarNotificationBackend(this));
161   QtUi::registerNotificationBackend(new SystrayNotificationBackend(this));
162 #  ifdef HAVE_PHONON
163   QtUi::registerNotificationBackend(new PhononNotificationBackend(this));
164 #  endif
165 #  ifdef HAVE_DBUS
166   QtUi::registerNotificationBackend(new DesktopNotificationBackend(this));
167 #  endif
168
169 #else /* HAVE_KDE */
170   QtUi::registerNotificationBackend(new KNotificationBackend(this));
171 #endif /* HAVE_KDE */
172
173   // restore mainwin state
174   restoreState(s.value("MainWinState").toByteArray());
175
176   // restore locked state of docks
177   QtUi::actionCollection("General")->action("LockDockPositions")->setChecked(s.value("LockDocks", false).toBool());
178
179   setDisconnectedState();  // Disable menus and stuff
180
181   show();
182   if(Quassel::runMode() != Quassel::Monolithic) {
183     showCoreConnectionDlg(true); // autoconnect if appropriate
184   } else {
185     startInternalCore();
186   }
187 }
188
189 MainWin::~MainWin() {
190   QtUiSettings s;
191   s.setValue("MainWinSize", size());
192   s.setValue("MainWinPos", pos());
193   s.setValue("MainWinState", saveState());
194 }
195
196 void MainWin::updateIcon() {
197   QPixmap icon;
198   if(Client::isConnected())
199     icon = DesktopIcon("quassel", IconLoader::SizeEnormous);
200   else
201     icon = DesktopIcon("quassel_disconnected", IconLoader::SizeEnormous);
202   setWindowIcon(icon);
203   qApp->setWindowIcon(icon);
204   systemTrayIcon()->setIcon(icon);
205 }
206
207 void MainWin::setupActions() {
208   ActionCollection *coll = QtUi::actionCollection("General");
209   // File
210   coll->addAction("ConnectCore", new Action(SmallIcon("network-connect"), tr("&Connect to Core..."), coll,
211                                              this, SLOT(showCoreConnectionDlg())));
212   coll->addAction("DisconnectCore", new Action(SmallIcon("network-disconnect"), tr("&Disconnect from Core"), coll,
213                                                 Client::instance(), SLOT(disconnectFromCore())));
214   coll->addAction("CoreInfo", new Action(SmallIcon("help-about"), tr("Core &Info..."), coll,
215                                           this, SLOT(showCoreInfoDlg())));
216   coll->addAction("ConfigureNetworks", new Action(SmallIcon("configure"), tr("Configure &Networks..."), coll,
217                                               this, SLOT(on_actionConfigureNetworks_triggered())));
218   coll->addAction("Quit", new Action(SmallIcon("application-exit"), tr("&Quit"), coll,
219                                       qApp, SLOT(quit()), tr("Ctrl+Q")));
220
221   // View
222   coll->addAction("ConfigureBufferViews", new Action(tr("&Configure Buffer Views..."), coll,
223                                              this, SLOT(on_actionConfigureViews_triggered())));
224   QAction *lockAct = coll->addAction("LockDockPositions", new Action(tr("&Lock Dock Positions"), coll));
225   lockAct->setCheckable(true);
226   connect(lockAct, SIGNAL(toggled(bool)), SLOT(on_actionLockDockPositions_toggled(bool)));
227
228   coll->addAction("ToggleSearchBar", new Action(SmallIcon("edit-find"), tr("Show &Search Bar"), coll,
229                                                 0, 0, tr("Ctrl+F")))->setCheckable(true);
230   coll->addAction("ShowAwayLog", new Action(tr("Show Away Log"), coll,
231                                             this, SLOT(showAwayLog())));
232   coll->addAction("ToggleStatusBar", new Action(tr("Show Status &Bar"), coll,
233                                                  0, 0))->setCheckable(true);
234
235   // Settings
236   coll->addAction("ConfigureQuassel", new Action(SmallIcon("configure"), tr("&Configure Quassel..."), coll,
237                                                   this, SLOT(showSettingsDlg()), tr("F7")));
238
239   // Help
240   coll->addAction("AboutQuassel", new Action(SmallIcon("quassel"), tr("&About Quassel"), coll,
241                                               this, SLOT(showAboutDlg())));
242   coll->addAction("AboutQt", new Action(QIcon(":/pics/qt-logo.png"), tr("About &Qt"), coll,
243                                          qApp, SLOT(aboutQt())));
244   coll->addAction("DebugNetworkModel", new Action(SmallIcon("tools-report-bug"), tr("Debug &NetworkModel"), coll,
245                                        this, SLOT(on_actionDebugNetworkModel_triggered())));
246   coll->addAction("DebugMessageModel", new Action(SmallIcon("tools-report-bug"), tr("Debug &MessageModel"), coll,
247                                        this, SLOT(on_actionDebugMessageModel_triggered())));
248   coll->addAction("DebugLog", new Action(SmallIcon("tools-report-bug"), tr("Debug &Log"), coll,
249                                        this, SLOT(on_actionDebugLog_triggered())));
250 }
251
252 void MainWin::setupMenus() {
253   ActionCollection *coll = QtUi::actionCollection("General");
254
255   _fileMenu = menuBar()->addMenu(tr("&File"));
256
257   static const QStringList coreActions = QStringList()
258     << "ConnectCore" << "DisconnectCore" << "CoreInfo";
259
260   QAction *coreAction;
261   foreach(QString actionName, coreActions) {
262     coreAction = coll->action(actionName);
263     _fileMenu->addAction(coreAction);
264     flagRemoteCoreOnly(coreAction);
265   }
266   flagRemoteCoreOnly(_fileMenu->addSeparator());
267
268   _networksMenu = _fileMenu->addMenu(tr("&Networks"));
269   _networksMenu->addAction(coll->action("ConfigureNetworks"));
270   _networksMenu->addSeparator();
271   _fileMenu->addSeparator();
272   _fileMenu->addAction(coll->action("Quit"));
273
274   _viewMenu = menuBar()->addMenu(tr("&View"));
275   _bufferViewsMenu = _viewMenu->addMenu(tr("&Buffer Views"));
276   _bufferViewsMenu->addAction(coll->action("ConfigureBufferViews"));
277   _viewMenu->addSeparator();
278   _viewMenu->addAction(coll->action("ToggleSearchBar"));
279
280   coreAction = coll->action("ShowAwayLog");
281   flagRemoteCoreOnly(coreAction);
282   _viewMenu->addAction(coreAction);
283
284   _viewMenu->addAction(coll->action("ToggleStatusBar"));
285   _viewMenu->addSeparator();
286   _viewMenu->addAction(coll->action("LockDockPositions"));
287
288   _settingsMenu = menuBar()->addMenu(tr("&Settings"));
289 #ifdef HAVE_KDE
290   _settingsMenu->addAction(KStandardAction::keyBindings(this, SLOT(showShortcutsDlg()), this));
291   _settingsMenu->addAction(KStandardAction::configureNotifications(this, SLOT(showNotificationsDlg()), this));
292 #endif
293   _settingsMenu->addAction(coll->action("ConfigureQuassel"));
294
295   _helpMenu = menuBar()->addMenu(tr("&Help"));
296   _helpMenu->addAction(coll->action("AboutQuassel"));
297 #ifndef HAVE_KDE
298   _helpMenu->addAction(coll->action("AboutQt"));
299 #else
300   _helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, SLOT(aboutKDE()), this));
301 #endif
302   _helpMenu->addSeparator();
303   _helpDebugMenu = _helpMenu->addMenu(SmallIcon("tools-report-bug"), tr("Debug"));
304   _helpDebugMenu->addAction(coll->action("DebugNetworkModel"));
305   _helpDebugMenu->addAction(coll->action("DebugMessageModel"));
306   _helpDebugMenu->addAction(coll->action("DebugLog"));
307 }
308
309 void MainWin::setupBufferWidget() {
310   _bufferWidget = new BufferWidget(this);
311   _bufferWidget->setModel(Client::bufferModel());
312   _bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
313   setCentralWidget(_bufferWidget);
314 }
315
316 void MainWin::addBufferView(int bufferViewConfigId) {
317   addBufferView(Client::bufferViewManager()->bufferViewConfig(bufferViewConfigId));
318 }
319
320 void MainWin::addBufferView(BufferViewConfig *config) {
321   if(!config)
322     return;
323
324   BufferViewDock *dock = new BufferViewDock(config, this);
325
326   //create the view and initialize it's filter
327   BufferView *view = new BufferView(dock);
328   view->setFilteredModel(Client::bufferModel(), config);
329   view->installEventFilter(_inputWidget->inputLine()); // for key presses
330   view->show();
331
332   Client::bufferModel()->synchronizeView(view);
333
334   dock->setWidget(view);
335   dock->show();
336
337   addDockWidget(Qt::LeftDockWidgetArea, dock);
338   _bufferViewsMenu->addAction(dock->toggleViewAction());
339
340   _bufferViews.append(dock);
341 }
342
343 void MainWin::removeBufferView(int bufferViewConfigId) {
344   QVariant actionData;
345   BufferViewDock *dock;
346   foreach(QAction *action, _bufferViewsMenu->actions()) {
347     actionData = action->data();
348     if(!actionData.isValid())
349       continue;
350
351     dock = qobject_cast<BufferViewDock *>(action->parent());
352     if(dock && actionData.toInt() == bufferViewConfigId) {
353       removeAction(action);
354       dock->deleteLater();
355     }
356   }
357 }
358
359 BufferView *MainWin::allBuffersView() const {
360   // "All Buffers" is always the first dock created
361   if(_bufferViews.count() > 0)
362     return _bufferViews[0]->bufferView();
363   return 0;
364 }
365
366 void MainWin::showNotificationsDlg() {
367   SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
368   dlg.exec();
369 }
370
371 void MainWin::on_actionConfigureNetworks_triggered() {
372   SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
373   dlg.exec();
374 }
375
376 void MainWin::on_actionConfigureViews_triggered() {
377   SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
378   dlg.exec();
379 }
380
381 void MainWin::on_actionLockDockPositions_toggled(bool lock) {
382   QList<VerticalDock *> docks = findChildren<VerticalDock *>();
383   foreach(VerticalDock *dock, docks) {
384     dock->showTitle(!lock);
385   }
386   QtUiSettings().setValue("LockDocks", lock);
387 }
388
389 void MainWin::setupNickWidget() {
390   // create nick dock
391   NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
392   nickDock->setObjectName("NickDock");
393   nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
394
395   _nickListWidget = new NickListWidget(nickDock);
396   nickDock->setWidget(_nickListWidget);
397
398   addDockWidget(Qt::RightDockWidgetArea, nickDock);
399   _viewMenu->addAction(nickDock->toggleViewAction());
400   nickDock->toggleViewAction()->setText(tr("Show Nick List"));
401   nickDock->toggleViewAction()->setIcon(SmallIcon("view-sidetree"));
402   // See NickListDock::NickListDock();
403   // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
404
405   // attach the NickListWidget to the BufferModel and the default selection
406   _nickListWidget->setModel(Client::bufferModel());
407   _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
408 }
409
410 void MainWin::setupChatMonitor() {
411   VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
412   dock->setObjectName("ChatMonitorDock");
413
414   ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
415   ChatMonitorView *chatView = new ChatMonitorView(filter, this);
416   chatView->show();
417   dock->setWidget(chatView);
418   dock->show();
419
420   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
421   _viewMenu->addAction(dock->toggleViewAction());
422   dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
423 }
424
425 void MainWin::setupInputWidget() {
426   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
427   dock->setObjectName("InputDock");
428
429   _inputWidget = new InputWidget(dock);
430   dock->setWidget(_inputWidget);
431
432   addDockWidget(Qt::BottomDockWidgetArea, dock);
433
434   _viewMenu->addAction(dock->toggleViewAction());
435   dock->toggleViewAction()->setText(tr("Show Input Line"));
436
437   _inputWidget->setModel(Client::bufferModel());
438   _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
439
440   _bufferWidget->setFocusProxy(_inputWidget);
441
442   _inputWidget->inputLine()->installEventFilter(_bufferWidget);
443 }
444
445 void MainWin::setupTopicWidget() {
446   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
447   dock->setObjectName("TopicDock");
448   TopicWidget *topicwidget = new TopicWidget(dock);
449
450   dock->setWidget(topicwidget);
451
452   topicwidget->setModel(Client::bufferModel());
453   topicwidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
454
455   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
456
457   _viewMenu->addAction(dock->toggleViewAction());
458   dock->toggleViewAction()->setText(tr("Show Topic Line"));
459 }
460
461 void MainWin::setupTitleSetter() {
462   _titleSetter.setModel(Client::bufferModel());
463   _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
464 }
465
466 void MainWin::setupStatusBar() {
467   // MessageProcessor progress
468   statusBar()->addPermanentWidget(msgProcessorStatusWidget);
469
470   // Core Lag:
471   updateLagIndicator();
472   statusBar()->addPermanentWidget(coreLagLabel);
473   coreLagLabel->hide();
474   connect(Client::signalProxy(), SIGNAL(lagUpdated(int)), this, SLOT(updateLagIndicator(int)));
475
476   // SSL indicator
477   sslLabel->setPixmap(QPixmap());
478   statusBar()->addPermanentWidget(sslLabel);
479   sslLabel->hide();
480
481   _viewMenu->addSeparator();
482   QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
483
484   QtUiSettings uiSettings;
485
486   bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
487   showStatusbar->setChecked(enabled);
488   enabled ? statusBar()->show() : statusBar()->hide();
489
490   connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
491   connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
492 }
493
494 void MainWin::saveStatusBarStatus(bool enabled) {
495   QtUiSettings uiSettings;
496   uiSettings.setValue("ShowStatusBar", enabled);
497 }
498
499 void MainWin::setupSystray() {
500   connect(Client::messageModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
501                                   SLOT(messagesInserted(const QModelIndex &, int, int)));
502
503   ActionCollection *coll = QtUi::actionCollection("General");
504   systrayMenu = new QMenu(this);
505   systrayMenu->addAction(coll->action("ConnectCore"));
506   systrayMenu->addAction(coll->action("DisconnectCore"));
507   systrayMenu->addAction(coll->action("CoreInfo"));
508   systrayMenu->addSeparator();
509   systrayMenu->addAction(coll->action("Quit"));
510
511   systemTrayIcon()->setContextMenu(systrayMenu);
512
513   QtUiSettings s;
514   if(s.value("UseSystemTrayIcon", QVariant(true)).toBool()) {
515     systemTrayIcon()->show();
516   }
517
518 #ifndef Q_WS_MAC
519   connect(systemTrayIcon(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systrayActivated(QSystemTrayIcon::ActivationReason)));
520 #endif
521 }
522
523 void MainWin::changeEvent(QEvent *event) {
524   if(event->type() == QEvent::WindowStateChange) {
525     if(windowState() & Qt::WindowMinimized) {
526       QtUiSettings s;
527       if(s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnMinimize").toBool()) {
528         hideToTray();
529         event->accept();
530       }
531     }
532   }
533 }
534
535 void MainWin::connectedToCore() {
536   Q_CHECK_PTR(Client::bufferViewManager());
537   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
538   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
539   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
540
541   setConnectedState();
542 }
543
544 void MainWin::setConnectedState() {
545   ActionCollection *coll = QtUi::actionCollection("General");
546
547   coll->action("ConnectCore")->setEnabled(false);
548   coll->action("DisconnectCore")->setEnabled(true);
549   coll->action("CoreInfo")->setEnabled(true);
550
551   foreach(QAction *action, _fileMenu->actions()) {
552     if(isRemoteCoreOnly(action))
553       action->setVisible(!Client::internalCore());
554   }
555
556   disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), msgProcessorStatusWidget, SLOT(setProgress(int, int)));
557   disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
558   disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
559   if(!Client::internalCore()) {
560     connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), msgProcessorStatusWidget, SLOT(setProgress(int, int)));
561     connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
562     connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
563   }
564
565   // _viewMenu->setEnabled(true);
566   if(!Client::internalCore())
567     statusBar()->showMessage(tr("Connected to core."));
568
569   if(Client::signalProxy()->isSecure()) {
570     sslLabel->setPixmap(SmallIcon("security-high"));
571   } else {
572     sslLabel->setPixmap(SmallIcon("security-low"));
573   }
574
575   sslLabel->setVisible(!Client::internalCore());
576   coreLagLabel->setVisible(!Client::internalCore());
577   updateIcon();
578 }
579
580 void MainWin::loadLayout() {
581   QtUiSettings s;
582   int accountId = Client::currentCoreAccount().toInt();
583   restoreState(s.value(QString("MainWinState-%1").arg(accountId)).toByteArray(), accountId);
584 }
585
586 void MainWin::saveLayout() {
587   QtUiSettings s;
588   int accountId = Client::currentCoreAccount().toInt();
589   if(accountId > 0) s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
590 }
591
592 void MainWin::updateLagIndicator(int lag) {
593   QString text = tr("Core Lag: %1");
594   if(lag == -1)
595     text = text.arg('-');
596   else
597     text = text.arg("%1 msec").arg(lag);
598   coreLagLabel->setText(text);
599 }
600
601 void MainWin::disconnectedFromCore() {
602   // save core specific layout and remove bufferviews;
603   saveLayout();
604   QVariant actionData;
605   BufferViewDock *dock;
606   foreach(QAction *action, _bufferViewsMenu->actions()) {
607     actionData = action->data();
608     if(!actionData.isValid())
609       continue;
610
611     dock = qobject_cast<BufferViewDock *>(action->parent());
612     if(dock && actionData.toInt() != -1) {
613       removeAction(action);
614       dock->deleteLater();
615     }
616   }
617   QtUiSettings s;
618   restoreState(s.value("MainWinState").toByteArray());
619   setDisconnectedState();
620 }
621
622 void MainWin::setDisconnectedState() {
623   ActionCollection *coll = QtUi::actionCollection("General");
624   //ui.menuCore->setEnabled(false);
625   coll->action("ConnectCore")->setEnabled(true);
626   coll->action("DisconnectCore")->setEnabled(false);
627   coll->action("CoreInfo")->setEnabled(false);
628   //_viewMenu->setEnabled(false);
629   statusBar()->showMessage(tr("Not connected to core."));
630   sslLabel->setPixmap(QPixmap());
631   sslLabel->hide();
632   updateLagIndicator();
633   coreLagLabel->hide();
634   updateIcon();
635 }
636
637 void MainWin::startInternalCore() {
638   ClientSyncer *syncer = new ClientSyncer();
639   Client::registerClientSyncer(syncer);
640   connect(syncer, SIGNAL(syncFinished()), syncer, SLOT(deleteLater()), Qt::QueuedConnection);
641   syncer->useInternalCore();
642 }
643
644 void MainWin::showCoreConnectionDlg(bool autoConnect) {
645   CoreConnectDlg(autoConnect, this).exec();
646 }
647
648 void MainWin::showChannelList(NetworkId netId) {
649   ChannelListDlg *channelListDlg = new ChannelListDlg();
650
651   if(!netId.isValid()) {
652     QAction *action = qobject_cast<QAction *>(sender());
653     if(action)
654       netId = action->data().value<NetworkId>();
655   }
656
657   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
658   channelListDlg->setNetwork(netId);
659   channelListDlg->show();
660 }
661
662 void MainWin::showCoreInfoDlg() {
663   CoreInfoDlg(this).exec();
664 }
665
666 void MainWin::showAwayLog() {
667   if(_awayLog)
668     return;
669   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
670   _awayLog = new AwayLogView(filter, 0);
671   filter->setParent(_awayLog);
672   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
673   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
674   _awayLog->show();
675 }
676
677 void MainWin::awayLogDestroyed() {
678   _awayLog = 0;
679 }
680
681 void MainWin::showSettingsDlg() {
682   SettingsDlg *dlg = new SettingsDlg();
683
684   //Category: Appearance
685   dlg->registerSettingsPage(new ColorSettingsPage(dlg));
686   dlg->registerSettingsPage(new FontsSettingsPage(dlg));
687   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg)); //General
688   //Category: Behaviour
689   dlg->registerSettingsPage(new GeneralSettingsPage(dlg));
690   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
691   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
692   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
693   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
694   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
695   //Category: General
696   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
697   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
698   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
699
700   dlg->show();
701 }
702
703 void MainWin::showAboutDlg() {
704   AboutDlg(this).exec();
705 }
706
707 #ifdef HAVE_KDE
708 void MainWin::showShortcutsDlg() {
709   KShortcutsDialog::configure(QtUi::actionCollection("General"), KShortcutsEditor::LetterShortcutsDisallowed);
710 }
711 #endif
712
713 void MainWin::closeEvent(QCloseEvent *event) {
714   QtUiSettings s;
715   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
716   Q_ASSERT(app);
717   if(!app->aboutToQuit() && s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnClose").toBool()) {
718     toggleMinimizedToTray();
719     event->ignore();
720   } else {
721     event->accept();
722     QApplication::quit();
723   }
724 }
725
726 void MainWin::systrayActivated(QSystemTrayIcon::ActivationReason activationReason) {
727   if(activationReason == QSystemTrayIcon::Trigger) {
728     toggleMinimizedToTray();
729   }
730 }
731
732 void MainWin::hideToTray() {
733   if(!systemTrayIcon()->isSystemTrayAvailable()) {
734     qWarning() << Q_FUNC_INFO << "was called with no SystemTray available!";
735     return;
736   }
737
738   clearFocus();
739   hide();
740   systemTrayIcon()->show();
741 }
742
743 void MainWin::toggleMinimizedToTray() {
744   if(windowState() & Qt::WindowMinimized) {
745     // restore
746     setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
747     show();
748     raise();
749   } else {
750     setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
751     hideToTray();
752   }
753 }
754
755 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
756   Q_UNUSED(parent);
757
758   if(QApplication::activeWindow() != 0)
759     return;
760
761   for(int i = start; i <= end; i++) {
762     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
763     if(!idx.isValid()) {
764       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
765       continue;
766     }
767     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
768     if(flags.testFlag(Message::Backlog)) continue;
769     flags |= Message::Backlog;  // we only want to trigger a highlight once!
770     Client::messageModel()->setData(idx, (int)flags, ChatLineModel::FlagsRole);
771
772     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
773     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
774
775     if(flags & Message::Highlight || bufType == BufferInfo::QueryBuffer) {
776       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
777       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
778       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
779       QtUi::invokeNotification(bufId, sender, contents);
780     }
781   }
782 }
783
784 bool MainWin::event(QEvent *event) {
785   if(event->type() == QEvent::WindowActivate)
786     QtUi::closeNotifications();
787   return QMainWindow::event(event);
788 }
789
790 void MainWin::clientNetworkCreated(NetworkId id) {
791   const Network *net = Client::network(id);
792   QAction *act = new QAction(net->networkName(), this);
793   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
794   act->setData(QVariant::fromValue<NetworkId>(id));
795   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
796   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
797
798   QAction *beforeAction = 0;
799   foreach(QAction *action, _networksMenu->actions()) {
800     if(!action->data().isValid())  // ignore stock actions
801       continue;
802     if(net->networkName().localeAwareCompare(action->text()) < 0) {
803       beforeAction = action;
804       break;
805     }
806   }
807   _networksMenu->insertAction(beforeAction, act);
808 }
809
810 void MainWin::clientNetworkUpdated() {
811   const Network *net = qobject_cast<const Network *>(sender());
812   if(!net)
813     return;
814
815   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
816   if(!action)
817     return;
818
819   action->setText(net->networkName());
820
821   switch(net->connectionState()) {
822   case Network::Initialized:
823     action->setIcon(SmallIcon("network-connect"));
824     break;
825   case Network::Disconnected:
826     action->setIcon(SmallIcon("network-disconnect"));
827     break;
828   default:
829     action->setIcon(SmallIcon("network-wired"));
830   }
831 }
832
833 void MainWin::clientNetworkRemoved(NetworkId id) {
834   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
835   if(!action)
836     return;
837
838   action->deleteLater();
839 }
840
841 void MainWin::connectOrDisconnectFromNet() {
842   QAction *act = qobject_cast<QAction *>(sender());
843   if(!act) return;
844   const Network *net = Client::network(act->data().value<NetworkId>());
845   if(!net) return;
846   if(net->connectionState() == Network::Disconnected) net->requestConnect();
847   else net->requestDisconnect();
848 }
849
850 void MainWin::on_actionDebugNetworkModel_triggered() {
851   QTreeView *view = new QTreeView;
852   view->setAttribute(Qt::WA_DeleteOnClose);
853   view->setWindowTitle("Debug NetworkModel View");
854   view->setModel(Client::networkModel());
855   view->setColumnWidth(0, 250);
856   view->setColumnWidth(1, 250);
857   view->setColumnWidth(2, 80);
858   view->resize(610, 300);
859   view->show();
860 }
861
862 void MainWin::on_actionDebugMessageModel_triggered() {
863   QTableView *view = new QTableView(0);
864   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
865   filter->setSourceModel(Client::messageModel());
866   view->setModel(filter);
867   view->setAttribute(Qt::WA_DeleteOnClose, true);
868   view->verticalHeader()->hide();
869   view->horizontalHeader()->setStretchLastSection(true);
870   view->show();
871 }
872
873 void MainWin::on_actionDebugLog_triggered() {
874   DebugLogWidget *logWidget = new DebugLogWidget(0);
875   logWidget->show();
876 }
877
878 void MainWin::saveStateToSession(const QString &sessionId) {
879   return;
880   SessionSettings s(sessionId);
881
882   s.setValue("MainWinSize", size());
883   s.setValue("MainWinPos", pos());
884   s.setValue("MainWinState", saveState());
885 }
886
887 void MainWin::saveStateToSessionSettings(SessionSettings & s)
888 {
889   s.setValue("MainWinSize", size());
890   s.setValue("MainWinPos", pos());
891   s.setValue("MainWinState", saveState());
892 }
893
894 void MainWin::showStatusBarMessage(const QString &message) {
895   statusBar()->showMessage(message, 10000);
896 }
897