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