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