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