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