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