555ac5d4d8d5ca3f4deef9a12b482047c6a716fe
[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   _viewMenu->addAction(coll->action("ShowAwayLog"));
279   _viewMenu->addAction(coll->action("ToggleStatusBar"));
280   _viewMenu->addSeparator();
281   _viewMenu->addAction(coll->action("LockDockPositions"));
282
283   _settingsMenu = menuBar()->addMenu(tr("&Settings"));
284 #ifdef HAVE_KDE
285   _settingsMenu->addAction(KStandardAction::keyBindings(this, SLOT(showShortcutsDlg()), this));
286   _settingsMenu->addAction(KStandardAction::configureNotifications(this, SLOT(showNotificationsDlg()), this));
287 #endif
288   _settingsMenu->addAction(coll->action("ConfigureQuassel"));
289
290   _helpMenu = menuBar()->addMenu(tr("&Help"));
291   _helpMenu->addAction(coll->action("AboutQuassel"));
292 #ifndef HAVE_KDE
293   _helpMenu->addAction(coll->action("AboutQt"));
294 #else
295   _helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, SLOT(aboutKDE()), this));
296 #endif
297   _helpMenu->addSeparator();
298   _helpDebugMenu = _helpMenu->addMenu(SmallIcon("tools-report-bug"), tr("Debug"));
299   _helpDebugMenu->addAction(coll->action("DebugNetworkModel"));
300   _helpDebugMenu->addAction(coll->action("DebugMessageModel"));
301   _helpDebugMenu->addAction(coll->action("DebugLog"));
302 }
303
304 void MainWin::setupBufferWidget() {
305   _bufferWidget = new BufferWidget(this);
306   _bufferWidget->setModel(Client::bufferModel());
307   _bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
308   setCentralWidget(_bufferWidget);
309 }
310
311 void MainWin::addBufferView(int bufferViewConfigId) {
312   addBufferView(Client::bufferViewManager()->bufferViewConfig(bufferViewConfigId));
313 }
314
315 void MainWin::addBufferView(BufferViewConfig *config) {
316   if(!config)
317     return;
318
319   BufferViewDock *dock = new BufferViewDock(config, this);
320
321   //create the view and initialize it's filter
322   BufferView *view = new BufferView(dock);
323   view->setFilteredModel(Client::bufferModel(), config);
324   view->installEventFilter(_inputWidget->inputLine()); // for key presses
325   view->show();
326
327   Client::bufferModel()->synchronizeView(view);
328
329   dock->setWidget(view);
330   dock->show();
331
332   addDockWidget(Qt::LeftDockWidgetArea, dock);
333   _bufferViewsMenu->addAction(dock->toggleViewAction());
334
335   _bufferViews.append(dock);
336 }
337
338 void MainWin::removeBufferView(int bufferViewConfigId) {
339   QVariant actionData;
340   BufferViewDock *dock;
341   foreach(QAction *action, _bufferViewsMenu->actions()) {
342     actionData = action->data();
343     if(!actionData.isValid())
344       continue;
345
346     dock = qobject_cast<BufferViewDock *>(action->parent());
347     if(dock && actionData.toInt() == bufferViewConfigId) {
348       removeAction(action);
349       dock->deleteLater();
350     }
351   }
352 }
353
354 BufferView *MainWin::allBuffersView() const {
355   // "All Buffers" is always the first dock created
356   if(_bufferViews.count() > 0)
357     return _bufferViews[0]->bufferView();
358   return 0;
359 }
360
361 void MainWin::showNotificationsDlg() {
362   SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
363   dlg.exec();
364 }
365
366 void MainWin::on_actionConfigureNetworks_triggered() {
367   SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
368   dlg.exec();
369 }
370
371 void MainWin::on_actionConfigureViews_triggered() {
372   SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
373   dlg.exec();
374 }
375
376 void MainWin::on_actionLockDockPositions_toggled(bool lock) {
377   QList<VerticalDock *> docks = findChildren<VerticalDock *>();
378   foreach(VerticalDock *dock, docks) {
379     dock->showTitle(!lock);
380   }
381   QtUiSettings().setValue("LockDocks", lock);
382 }
383
384 void MainWin::setupNickWidget() {
385   // create nick dock
386   NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
387   nickDock->setObjectName("NickDock");
388   nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
389
390   _nickListWidget = new NickListWidget(nickDock);
391   nickDock->setWidget(_nickListWidget);
392
393   addDockWidget(Qt::RightDockWidgetArea, nickDock);
394   _viewMenu->addAction(nickDock->toggleViewAction());
395   nickDock->toggleViewAction()->setText(tr("Show Nick List"));
396   nickDock->toggleViewAction()->setIcon(SmallIcon("view-sidetree"));
397   // See NickListDock::NickListDock();
398   // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
399
400   // attach the NickListWidget to the BufferModel and the default selection
401   _nickListWidget->setModel(Client::bufferModel());
402   _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
403 }
404
405 void MainWin::setupChatMonitor() {
406   VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
407   dock->setObjectName("ChatMonitorDock");
408
409   ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
410   ChatMonitorView *chatView = new ChatMonitorView(filter, this);
411   chatView->show();
412   dock->setWidget(chatView);
413   dock->show();
414
415   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
416   _viewMenu->addAction(dock->toggleViewAction());
417   dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
418 }
419
420 void MainWin::setupInputWidget() {
421   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
422   dock->setObjectName("InputDock");
423
424   _inputWidget = new InputWidget(dock);
425   dock->setWidget(_inputWidget);
426
427   addDockWidget(Qt::BottomDockWidgetArea, dock);
428
429   _viewMenu->addAction(dock->toggleViewAction());
430   dock->toggleViewAction()->setText(tr("Show Input Line"));
431
432   _inputWidget->setModel(Client::bufferModel());
433   _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
434
435   _bufferWidget->setFocusProxy(_inputWidget);
436
437   _inputWidget->inputLine()->installEventFilter(_bufferWidget);
438 }
439
440 void MainWin::setupTopicWidget() {
441   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
442   dock->setObjectName("TopicDock");
443   TopicWidget *topicwidget = new TopicWidget(dock);
444
445   dock->setWidget(topicwidget);
446
447   topicwidget->setModel(Client::bufferModel());
448   topicwidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
449
450   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
451
452   _viewMenu->addAction(dock->toggleViewAction());
453   dock->toggleViewAction()->setText(tr("Show Topic Line"));
454 }
455
456 void MainWin::setupTitleSetter() {
457   _titleSetter.setModel(Client::bufferModel());
458   _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
459 }
460
461 void MainWin::setupStatusBar() {
462   // MessageProcessor progress
463   statusBar()->addPermanentWidget(msgProcessorStatusWidget);
464
465   // Core Lag:
466   updateLagIndicator();
467   statusBar()->addPermanentWidget(coreLagLabel);
468   coreLagLabel->hide();
469   connect(Client::signalProxy(), SIGNAL(lagUpdated(int)), this, SLOT(updateLagIndicator(int)));
470
471   // SSL indicator
472   sslLabel->setPixmap(QPixmap());
473   statusBar()->addPermanentWidget(sslLabel);
474   sslLabel->hide();
475
476   _viewMenu->addSeparator();
477   QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
478
479   QtUiSettings uiSettings;
480
481   bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
482   showStatusbar->setChecked(enabled);
483   enabled ? statusBar()->show() : statusBar()->hide();
484
485   connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
486   connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
487 }
488
489 void MainWin::saveStatusBarStatus(bool enabled) {
490   QtUiSettings uiSettings;
491   uiSettings.setValue("ShowStatusBar", enabled);
492 }
493
494 void MainWin::setupSystray() {
495   connect(Client::messageModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
496                                   SLOT(messagesInserted(const QModelIndex &, int, int)));
497
498   ActionCollection *coll = QtUi::actionCollection("General");
499   systrayMenu = new QMenu(this);
500   systrayMenu->addAction(coll->action("ConnectCore"));
501   systrayMenu->addAction(coll->action("DisconnectCore"));
502   systrayMenu->addAction(coll->action("CoreInfo"));
503   systrayMenu->addSeparator();
504   systrayMenu->addAction(coll->action("Quit"));
505
506   systemTrayIcon()->setContextMenu(systrayMenu);
507
508   QtUiSettings s;
509   if(s.value("UseSystemTrayIcon", QVariant(true)).toBool()) {
510     systemTrayIcon()->show();
511   }
512
513 #ifndef Q_WS_MAC
514   connect(systemTrayIcon(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systrayActivated(QSystemTrayIcon::ActivationReason)));
515 #endif
516 }
517
518 void MainWin::changeEvent(QEvent *event) {
519   if(event->type() == QEvent::WindowStateChange) {
520     if(windowState() & Qt::WindowMinimized) {
521       QtUiSettings s;
522       if(s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnMinimize").toBool()) {
523         hideToTray();
524         event->accept();
525       }
526     }
527   }
528 }
529
530 void MainWin::connectedToCore() {
531   Q_CHECK_PTR(Client::bufferViewManager());
532   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
533   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
534   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
535
536   setConnectedState();
537 }
538
539 void MainWin::setConnectedState() {
540   ActionCollection *coll = QtUi::actionCollection("General");
541
542   coll->action("ConnectCore")->setEnabled(false);
543   coll->action("DisconnectCore")->setEnabled(true);
544   coll->action("CoreInfo")->setEnabled(true);
545
546   foreach(QAction *action, _fileMenu->actions()) {
547     if(isRemoteCoreOnly(action))
548       action->setVisible(!Client::internalCore());
549   }
550
551   disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), msgProcessorStatusWidget, SLOT(setProgress(int, int)));
552   disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
553   disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
554   if(!Client::internalCore()) {
555     connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), msgProcessorStatusWidget, SLOT(setProgress(int, int)));
556     connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
557     connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
558   }
559
560   // _viewMenu->setEnabled(true);
561   if(!Client::internalCore())
562     statusBar()->showMessage(tr("Connected to core."));
563
564   if(Client::signalProxy()->isSecure()) {
565     sslLabel->setPixmap(SmallIcon("security-high"));
566   } else {
567     sslLabel->setPixmap(SmallIcon("security-low"));
568   }
569
570   sslLabel->setVisible(!Client::internalCore());
571   coreLagLabel->setVisible(!Client::internalCore());
572   updateIcon();
573 }
574
575 void MainWin::loadLayout() {
576   QtUiSettings s;
577   int accountId = Client::currentCoreAccount().toInt();
578   restoreState(s.value(QString("MainWinState-%1").arg(accountId)).toByteArray(), accountId);
579 }
580
581 void MainWin::saveLayout() {
582   QtUiSettings s;
583   int accountId = Client::currentCoreAccount().toInt();
584   if(accountId > 0) s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
585 }
586
587 void MainWin::updateLagIndicator(int lag) {
588   QString text = tr("Core Lag: %1");
589   if(lag == -1)
590     text = text.arg('-');
591   else
592     text = text.arg("%1 msec").arg(lag);
593   coreLagLabel->setText(text);
594 }
595
596 void MainWin::disconnectedFromCore() {
597   // save core specific layout and remove bufferviews;
598   saveLayout();
599   QVariant actionData;
600   BufferViewDock *dock;
601   foreach(QAction *action, _bufferViewsMenu->actions()) {
602     actionData = action->data();
603     if(!actionData.isValid())
604       continue;
605
606     dock = qobject_cast<BufferViewDock *>(action->parent());
607     if(dock && actionData.toInt() != -1) {
608       removeAction(action);
609       dock->deleteLater();
610     }
611   }
612   QtUiSettings s;
613   restoreState(s.value("MainWinState").toByteArray());
614   setDisconnectedState();
615 }
616
617 void MainWin::setDisconnectedState() {
618   ActionCollection *coll = QtUi::actionCollection("General");
619   //ui.menuCore->setEnabled(false);
620   coll->action("ConnectCore")->setEnabled(true);
621   coll->action("DisconnectCore")->setEnabled(false);
622   coll->action("CoreInfo")->setEnabled(false);
623   //_viewMenu->setEnabled(false);
624   statusBar()->showMessage(tr("Not connected to core."));
625   sslLabel->setPixmap(QPixmap());
626   sslLabel->hide();
627   updateLagIndicator();
628   coreLagLabel->hide();
629   updateIcon();
630 }
631
632 void MainWin::startInternalCore() {
633   ClientSyncer *syncer = new ClientSyncer();
634   Client::registerClientSyncer(syncer);
635   connect(syncer, SIGNAL(syncFinished()), syncer, SLOT(deleteLater()), Qt::QueuedConnection);
636   syncer->useInternalCore();
637 }
638
639 void MainWin::showCoreConnectionDlg(bool autoConnect) {
640   CoreConnectDlg(autoConnect, this).exec();
641 }
642
643 void MainWin::showChannelList(NetworkId netId) {
644   ChannelListDlg *channelListDlg = new ChannelListDlg();
645
646   if(!netId.isValid()) {
647     QAction *action = qobject_cast<QAction *>(sender());
648     if(action)
649       netId = action->data().value<NetworkId>();
650   }
651
652   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
653   channelListDlg->setNetwork(netId);
654   channelListDlg->show();
655 }
656
657 void MainWin::showCoreInfoDlg() {
658   CoreInfoDlg(this).exec();
659 }
660
661 void MainWin::showAwayLog() {
662   if(_awayLog)
663     return;
664   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
665   _awayLog = new AwayLogView(filter, 0);
666   filter->setParent(_awayLog);
667   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
668   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
669   _awayLog->show();
670 }
671
672 void MainWin::awayLogDestroyed() {
673   _awayLog = 0;
674 }
675
676 void MainWin::showSettingsDlg() {
677   SettingsDlg *dlg = new SettingsDlg();
678
679   //Category: Appearance
680   dlg->registerSettingsPage(new ColorSettingsPage(dlg));
681   dlg->registerSettingsPage(new FontsSettingsPage(dlg));
682   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg)); //General
683   //Category: Behaviour
684   dlg->registerSettingsPage(new GeneralSettingsPage(dlg));
685   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
686   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
687   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
688   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
689   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
690   //Category: General
691   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
692   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
693   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
694
695   dlg->show();
696 }
697
698 void MainWin::showAboutDlg() {
699   AboutDlg(this).exec();
700 }
701
702 #ifdef HAVE_KDE
703 void MainWin::showShortcutsDlg() {
704   KShortcutsDialog::configure(QtUi::actionCollection("General"), KShortcutsEditor::LetterShortcutsDisallowed);
705 }
706 #endif
707
708 void MainWin::closeEvent(QCloseEvent *event) {
709   QtUiSettings s;
710   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
711   Q_ASSERT(app);
712   if(!app->aboutToQuit() && s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnClose").toBool()) {
713     toggleMinimizedToTray();
714     event->ignore();
715   } else {
716     event->accept();
717     QApplication::quit();
718   }
719 }
720
721 void MainWin::systrayActivated(QSystemTrayIcon::ActivationReason activationReason) {
722   if(activationReason == QSystemTrayIcon::Trigger) {
723     toggleMinimizedToTray();
724   }
725 }
726
727 void MainWin::hideToTray() {
728   if(!systemTrayIcon()->isSystemTrayAvailable()) {
729     qWarning() << Q_FUNC_INFO << "was called with no SystemTray available!";
730     return;
731   }
732
733   clearFocus();
734   hide();
735   systemTrayIcon()->show();
736 }
737
738 void MainWin::toggleMinimizedToTray() {
739   if(windowState() & Qt::WindowMinimized) {
740     // restore
741     setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
742     show();
743     raise();
744   } else {
745     setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
746     hideToTray();
747   }
748 }
749
750 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
751   Q_UNUSED(parent);
752
753   if(QApplication::activeWindow() != 0)
754     return;
755
756   for(int i = start; i <= end; i++) {
757     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
758     if(!idx.isValid()) {
759       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
760       continue;
761     }
762     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
763     if(flags.testFlag(Message::Backlog)) continue;
764     flags |= Message::Backlog;  // we only want to trigger a highlight once!
765     Client::messageModel()->setData(idx, (int)flags, ChatLineModel::FlagsRole);
766
767     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
768     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
769
770     if(flags & Message::Highlight || bufType == BufferInfo::QueryBuffer) {
771       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
772       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
773       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
774       QtUi::invokeNotification(bufId, sender, contents);
775     }
776   }
777 }
778
779 bool MainWin::event(QEvent *event) {
780   if(event->type() == QEvent::WindowActivate)
781     QtUi::closeNotifications();
782   return QMainWindow::event(event);
783 }
784
785 void MainWin::clientNetworkCreated(NetworkId id) {
786   const Network *net = Client::network(id);
787   QAction *act = new QAction(net->networkName(), this);
788   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
789   act->setData(QVariant::fromValue<NetworkId>(id));
790   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
791   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
792
793   QAction *beforeAction = 0;
794   foreach(QAction *action, _networksMenu->actions()) {
795     if(!action->data().isValid())  // ignore stock actions
796       continue;
797     if(net->networkName().localeAwareCompare(action->text()) < 0) {
798       beforeAction = action;
799       break;
800     }
801   }
802   _networksMenu->insertAction(beforeAction, act);
803 }
804
805 void MainWin::clientNetworkUpdated() {
806   const Network *net = qobject_cast<const Network *>(sender());
807   if(!net)
808     return;
809
810   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
811   if(!action)
812     return;
813
814   action->setText(net->networkName());
815
816   switch(net->connectionState()) {
817   case Network::Initialized:
818     action->setIcon(SmallIcon("network-connect"));
819     break;
820   case Network::Disconnected:
821     action->setIcon(SmallIcon("network-disconnect"));
822     break;
823   default:
824     action->setIcon(SmallIcon("network-wired"));
825   }
826 }
827
828 void MainWin::clientNetworkRemoved(NetworkId id) {
829   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
830   if(!action)
831     return;
832
833   action->deleteLater();
834 }
835
836 void MainWin::connectOrDisconnectFromNet() {
837   QAction *act = qobject_cast<QAction *>(sender());
838   if(!act) return;
839   const Network *net = Client::network(act->data().value<NetworkId>());
840   if(!net) return;
841   if(net->connectionState() == Network::Disconnected) net->requestConnect();
842   else net->requestDisconnect();
843 }
844
845 void MainWin::on_actionDebugNetworkModel_triggered() {
846   QTreeView *view = new QTreeView;
847   view->setAttribute(Qt::WA_DeleteOnClose);
848   view->setWindowTitle("Debug NetworkModel View");
849   view->setModel(Client::networkModel());
850   view->setColumnWidth(0, 250);
851   view->setColumnWidth(1, 250);
852   view->setColumnWidth(2, 80);
853   view->resize(610, 300);
854   view->show();
855 }
856
857 void MainWin::on_actionDebugMessageModel_triggered() {
858   QTableView *view = new QTableView(0);
859   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
860   filter->setSourceModel(Client::messageModel());
861   view->setModel(filter);
862   view->setAttribute(Qt::WA_DeleteOnClose, true);
863   view->verticalHeader()->hide();
864   view->horizontalHeader()->setStretchLastSection(true);
865   view->show();
866 }
867
868 void MainWin::on_actionDebugLog_triggered() {
869   DebugLogWidget *logWidget = new DebugLogWidget(0);
870   logWidget->show();
871 }
872
873 void MainWin::saveStateToSession(const QString &sessionId) {
874   return;
875   SessionSettings s(sessionId);
876
877   s.setValue("MainWinSize", size());
878   s.setValue("MainWinPos", pos());
879   s.setValue("MainWinState", saveState());
880 }
881
882 void MainWin::saveStateToSessionSettings(SessionSettings & s)
883 {
884   s.setValue("MainWinSize", size());
885   s.setValue("MainWinPos", pos());
886   s.setValue("MainWinState", saveState());
887 }
888
889 void MainWin::showStatusBarMessage(const QString &message) {
890   statusBar()->showMessage(message, 10000);
891 }
892