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