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