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