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