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