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