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