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