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