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