Make sure to properly remove bufferViews from the overlay
[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       Client::bufferViewOverlay()->removeView(dock->bufferViewId());
473       dock->deleteLater();
474     }
475   }
476 }
477
478 void MainWin::bufferViewToggled(bool enabled) {
479   QAction *action = qobject_cast<QAction *>(sender());
480   Q_ASSERT(action);
481   BufferViewDock *dock = qobject_cast<BufferViewDock *>(action->parent());
482   Q_ASSERT(dock);
483
484   // Make sure we don't toggle backlog fetch for a view we've already removed
485   if(!_bufferViews.contains(dock))
486     return;
487
488   if(enabled) {
489     Client::bufferViewOverlay()->addView(dock->bufferViewId());
490     BufferViewConfig *config = dock->config();
491     if(config && config->isInitialized()) {
492       BufferIdList buffers;
493       if(config->networkId().isValid()) {
494         foreach(BufferId bufferId, config->bufferList()) {
495           if(Client::networkModel()->networkId(bufferId) == config->networkId())
496             buffers << bufferId;
497         }
498         foreach(BufferId bufferId, config->temporarilyRemovedBuffers().toList()) {
499           if(Client::networkModel()->networkId(bufferId) == config->networkId())
500             buffers << bufferId;
501         }
502       } else {
503         buffers = BufferIdList::fromSet(config->bufferList().toSet() + config->temporarilyRemovedBuffers());
504       }
505       Client::backlogManager()->checkForBacklog(buffers);
506     }
507   } else {
508     Client::bufferViewOverlay()->removeView(dock->bufferViewId());
509   }
510 }
511
512 BufferView *MainWin::allBuffersView() const {
513   // "All Buffers" is always the first dock created
514   if(_bufferViews.count() > 0)
515     return _bufferViews[0]->bufferView();
516   return 0;
517 }
518
519 void MainWin::showNotificationsDlg() {
520   SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
521   dlg.exec();
522 }
523
524 void MainWin::on_actionConfigureNetworks_triggered() {
525   SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
526   dlg.exec();
527 }
528
529 void MainWin::on_actionConfigureViews_triggered() {
530   SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
531   dlg.exec();
532 }
533
534 void MainWin::on_actionLockLayout_toggled(bool lock) {
535   QList<VerticalDock *> docks = findChildren<VerticalDock *>();
536   foreach(VerticalDock *dock, docks) {
537     dock->showTitle(!lock);
538   }
539   if(Client::bufferViewManager()) {
540     foreach(ClientBufferViewConfig *config, Client::bufferViewManager()->clientBufferViewConfigs()) {
541       config->setLocked(lock);
542     }
543   }
544   QtUiSettings().setValue("LockLayout", lock);
545 }
546
547 void MainWin::setupNickWidget() {
548   // create nick dock
549   NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
550   nickDock->setObjectName("NickDock");
551   nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
552
553   _nickListWidget = new NickListWidget(nickDock);
554   nickDock->setWidget(_nickListWidget);
555
556   addDockWidget(Qt::RightDockWidgetArea, nickDock);
557   _viewMenu->addAction(nickDock->toggleViewAction());
558   nickDock->toggleViewAction()->setText(tr("Show Nick List"));
559
560   // See NickListDock::NickListDock();
561   // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
562
563   // attach the NickListWidget to the BufferModel and the default selection
564   _nickListWidget->setModel(Client::bufferModel());
565   _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
566 }
567
568 void MainWin::setupChatMonitor() {
569   VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
570   dock->setObjectName("ChatMonitorDock");
571
572   ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
573   ChatMonitorView *chatView = new ChatMonitorView(filter, this);
574   chatView->show();
575   dock->setWidget(chatView);
576   dock->hide();
577
578   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
579   _viewMenu->addAction(dock->toggleViewAction());
580   dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
581 }
582
583 void MainWin::setupInputWidget() {
584   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
585   dock->setObjectName("InputDock");
586
587   _inputWidget = new InputWidget(dock);
588   dock->setWidget(_inputWidget);
589
590   addDockWidget(Qt::BottomDockWidgetArea, dock);
591
592   _viewMenu->addAction(dock->toggleViewAction());
593   dock->toggleViewAction()->setText(tr("Show Input Line"));
594
595   _inputWidget->setModel(Client::bufferModel());
596   _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
597
598   _bufferWidget->setFocusProxy(_inputWidget);
599
600   _inputWidget->inputLine()->installEventFilter(_bufferWidget);
601 }
602
603 void MainWin::setupTopicWidget() {
604   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
605   dock->setObjectName("TopicDock");
606   TopicWidget *topicwidget = new TopicWidget(dock);
607
608   dock->setWidget(topicwidget);
609
610   topicwidget->setModel(Client::bufferModel());
611   topicwidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
612
613   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
614
615   _viewMenu->addAction(dock->toggleViewAction());
616   dock->toggleViewAction()->setText(tr("Show Topic Line"));
617 }
618
619 void MainWin::setupTitleSetter() {
620   _titleSetter.setModel(Client::bufferModel());
621   _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
622 }
623
624 void MainWin::setupStatusBar() {
625   // MessageProcessor progress
626   statusBar()->addPermanentWidget(msgProcessorStatusWidget);
627
628   // Core Lag:
629   updateLagIndicator();
630   statusBar()->addPermanentWidget(coreLagLabel);
631   coreLagLabel->hide();
632   connect(Client::signalProxy(), SIGNAL(lagUpdated(int)), this, SLOT(updateLagIndicator(int)));
633
634   // SSL indicator
635   sslLabel->setPixmap(QPixmap());
636   statusBar()->addPermanentWidget(sslLabel);
637   sslLabel->hide();
638
639   QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
640
641   QtUiSettings uiSettings;
642
643   bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
644   showStatusbar->setChecked(enabled);
645   enabled ? statusBar()->show() : statusBar()->hide();
646
647   connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
648   connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
649 }
650
651 void MainWin::setupHotList() {
652   FlatProxyModel *flatProxy = new FlatProxyModel(this);
653   flatProxy->setSourceModel(Client::bufferModel());
654   _bufferHotList = new BufferHotListFilter(flatProxy);
655 }
656
657 void MainWin::saveMenuBarStatus(bool enabled) {
658   QtUiSettings uiSettings;
659   uiSettings.setValue("ShowMenuBar", enabled);
660 }
661
662 void MainWin::saveStatusBarStatus(bool enabled) {
663   QtUiSettings uiSettings;
664   uiSettings.setValue("ShowStatusBar", enabled);
665 }
666
667 void MainWin::setupSystray() {
668   _systemTray = new SystemTray(this);
669 }
670
671 void MainWin::setupToolBars() {
672   connect(_bufferWidget, SIGNAL(currentChanged(QModelIndex)),
673           QtUi::toolBarActionProvider(), SLOT(currentBufferChanged(QModelIndex)));
674   connect(_nickListWidget, SIGNAL(nickSelectionChanged(QModelIndexList)),
675           QtUi::toolBarActionProvider(), SLOT(nickSelectionChanged(QModelIndexList)));
676
677 #ifdef Q_WS_MAC
678   setUnifiedTitleAndToolBarOnMac(true);
679 #endif
680
681 #ifdef HAVE_KDE
682   _mainToolBar = new KToolBar("MainToolBar", this, Qt::TopToolBarArea, false, true, true);
683 #else
684   _mainToolBar = new QToolBar(this);
685   _mainToolBar->setObjectName("MainToolBar");
686 #endif
687   _mainToolBar->setWindowTitle(tr("Main Toolbar"));
688   addToolBar(_mainToolBar);
689
690   QtUi::toolBarActionProvider()->addActions(_mainToolBar, ToolBarActionProvider::MainToolBar);
691   _toolbarMenu->addAction(_mainToolBar->toggleViewAction());
692 }
693
694 void MainWin::connectedToCore() {
695   Q_CHECK_PTR(Client::bufferViewManager());
696   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
697   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
698   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
699
700   setConnectedState();
701 }
702
703 void MainWin::setConnectedState() {
704   ActionCollection *coll = QtUi::actionCollection("General");
705
706   coll->action("ConnectCore")->setEnabled(false);
707   coll->action("DisconnectCore")->setEnabled(true);
708   coll->action("CoreInfo")->setEnabled(true);
709
710   foreach(QAction *action, _fileMenu->actions()) {
711     if(isRemoteCoreOnly(action))
712       action->setVisible(!Client::internalCore());
713   }
714
715   disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), msgProcessorStatusWidget, SLOT(setProgress(int, int)));
716   disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
717   disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
718   if(!Client::internalCore()) {
719     connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), msgProcessorStatusWidget, SLOT(setProgress(int, int)));
720     connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
721     connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
722   }
723
724   // _viewMenu->setEnabled(true);
725   if(!Client::internalCore())
726     statusBar()->showMessage(tr("Connected to core."));
727   else
728     statusBar()->clearMessage();
729
730   if(Client::signalProxy()->isSecure()) {
731     sslLabel->setPixmap(SmallIcon("security-high"));
732   } else {
733     sslLabel->setPixmap(SmallIcon("security-low"));
734   }
735
736   sslLabel->setVisible(!Client::internalCore());
737   coreLagLabel->setVisible(!Client::internalCore());
738   updateIcon();
739   systemTray()->setState(SystemTray::Active);
740
741   if(Client::networkIds().isEmpty()) {
742     IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
743     wizard->show();
744   }
745 }
746
747 void MainWin::loadLayout() {
748   QtUiSettings s;
749   int accountId = Client::currentCoreAccount().toInt();
750   restoreState(s.value(QString("MainWinState-%1").arg(accountId)).toByteArray(), accountId);
751   _layoutLoaded = true;
752 }
753
754 void MainWin::saveLayout() {
755   QtUiSettings s;
756   int accountId = Client::currentCoreAccount().toInt();
757   if(accountId > 0) s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
758 }
759
760 void MainWin::updateLagIndicator(int lag) {
761   QString text = tr("Core Lag: %1");
762   if(lag == -1)
763     text = text.arg('-');
764   else
765     text = text.arg("%1 msec").arg(lag);
766   coreLagLabel->setText(text);
767 }
768
769 void MainWin::disconnectedFromCore() {
770   // save core specific layout and remove bufferviews;
771   saveLayout();
772   _layoutLoaded = false;
773
774   QVariant actionData;
775   BufferViewDock *dock;
776   foreach(QAction *action, _bufferViewsMenu->actions()) {
777     actionData = action->data();
778     if(!actionData.isValid())
779       continue;
780
781     dock = qobject_cast<BufferViewDock *>(action->parent());
782     if(dock && actionData.toInt() != -1) {
783       removeAction(action);
784       _bufferViews.removeAll(dock);
785       Client::bufferViewOverlay()->removeView(dock->bufferViewId());
786       dock->deleteLater();
787     }
788   }
789
790   QtUiSettings s;
791   restoreState(s.value("MainWinState").toByteArray());
792   setDisconnectedState();
793 }
794
795 void MainWin::setDisconnectedState() {
796   ActionCollection *coll = QtUi::actionCollection("General");
797   //ui.menuCore->setEnabled(false);
798   coll->action("ConnectCore")->setEnabled(true);
799   coll->action("DisconnectCore")->setEnabled(false);
800   coll->action("CoreInfo")->setEnabled(false);
801   //_viewMenu->setEnabled(false);
802   statusBar()->showMessage(tr("Not connected to core."));
803   sslLabel->setPixmap(QPixmap());
804   sslLabel->hide();
805   updateLagIndicator();
806   coreLagLabel->hide();
807   if(msgProcessorStatusWidget)
808     msgProcessorStatusWidget->setProgress(0, 0);
809   updateIcon();
810   systemTray()->setState(SystemTray::Inactive);
811 }
812
813 void MainWin::startInternalCore() {
814   ClientSyncer *syncer = new ClientSyncer();
815   Client::registerClientSyncer(syncer);
816   connect(syncer, SIGNAL(syncFinished()), syncer, SLOT(deleteLater()), Qt::QueuedConnection);
817   syncer->useInternalCore();
818 }
819
820 void MainWin::showCoreConnectionDlg(bool autoConnect) {
821   CoreConnectDlg(autoConnect, this).exec();
822 }
823
824 void MainWin::showChannelList(NetworkId netId) {
825   ChannelListDlg *channelListDlg = new ChannelListDlg();
826
827   if(!netId.isValid()) {
828     QAction *action = qobject_cast<QAction *>(sender());
829     if(action)
830       netId = action->data().value<NetworkId>();
831   }
832
833   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
834   channelListDlg->setNetwork(netId);
835   channelListDlg->show();
836 }
837
838 void MainWin::showIgnoreList(QString newRule) {
839   SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
840   // prepare config dialog for new rule
841   if(!newRule.isEmpty())
842     qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
843   dlg.exec();
844 }
845
846 void MainWin::showCoreInfoDlg() {
847   CoreInfoDlg(this).exec();
848 }
849
850 void MainWin::showAwayLog() {
851   if(_awayLog)
852     return;
853   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
854   _awayLog = new AwayLogView(filter, 0);
855   filter->setParent(_awayLog);
856   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
857   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
858   _awayLog->show();
859 }
860
861 void MainWin::awayLogDestroyed() {
862   _awayLog = 0;
863 }
864
865 void MainWin::showSettingsDlg() {
866   SettingsDlg *dlg = new SettingsDlg();
867
868   //Category: Interface
869   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
870   dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
871   dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
872   dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
873   dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
874   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
875   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
876   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
877   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
878   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
879
880   //Category: Misc
881   dlg->registerSettingsPage(new GeneralSettingsPage(dlg));
882   dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
883   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
884   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
885   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
886   dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
887
888   dlg->show();
889 }
890
891 void MainWin::showAboutDlg() {
892   AboutDlg(this).exec();
893 }
894
895 #ifdef HAVE_KDE
896 void MainWin::showShortcutsDlg() {
897   KShortcutsDialog::configure(QtUi::actionCollection("General"), KShortcutsEditor::LetterShortcutsDisallowed);
898 }
899 #endif
900
901 /********************************************************************************************************/
902
903 bool MainWin::event(QEvent *event) {
904   if(event->type() == QEvent::WindowActivate) {
905     BufferId buffer = Client::bufferModel()->currentBuffer();
906     if(buffer.isValid())
907       QtUi::closeNotifications(buffer);
908   }
909   return QMainWindow::event(event);
910 }
911
912 void MainWin::moveEvent(QMoveEvent *event) {
913   if(!(windowState() & Qt::WindowMaximized))
914     _normalPos = event->pos();
915
916   QMainWindow::moveEvent(event);
917 }
918
919 void MainWin::resizeEvent(QResizeEvent *event) {
920   if(!(windowState() & Qt::WindowMaximized))
921     _normalSize = event->size();
922
923   QMainWindow::resizeEvent(event);
924 }
925
926 void MainWin::closeEvent(QCloseEvent *event) {
927   QtUiSettings s;
928   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
929   Q_ASSERT(app);
930   if(!app->isAboutToQuit() && s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnClose").toBool()) {
931     hideToTray();
932     event->ignore();
933   } else {
934     event->accept();
935     quit();
936   }
937 }
938
939 void MainWin::changeEvent(QEvent *event) {
940 #ifdef Q_WS_WIN
941   if(event->type() == QEvent::ActivationChange)
942     dwTickCount = GetTickCount();  // needed for toggleMinimizedToTray()
943 #endif
944
945   QMainWindow::changeEvent(event);
946 }
947
948 void MainWin::hideToTray() {
949   if(!systemTray()->isSystemTrayAvailable()) {
950     qWarning() << Q_FUNC_INFO << "was called with no SystemTray available!";
951     return;
952   }
953   hide();
954   systemTray()->setIconVisible();
955 }
956
957 void MainWin::toggleMinimizedToTray() {
958 #ifdef Q_WS_WIN
959   // the problem is that we lose focus when the systray icon is activated
960   // and we don't know the former active window
961   // therefore we watch for activation event and use our stopwatch :)
962   // courtesy: KSystemTrayIcon
963   if(GetTickCount() - dwTickCount >= 300)
964     // we weren't active in the last 300ms -> activate
965     forceActivated();
966   else
967     hideToTray();
968
969 #else
970
971   if(!isVisible() || isMinimized())
972     // restore
973     forceActivated();
974   else
975     hideToTray();
976
977 #endif
978 }
979
980 void MainWin::forceActivated() {
981 #ifdef HAVE_KDE
982   show();
983   KWindowSystem::forceActiveWindow(winId());
984 #else
985
986 #ifdef Q_WS_X11
987   // Bypass focus stealing prevention
988   QX11Info::setAppUserTime(QX11Info::appTime());
989 #endif
990
991   if(windowState() & Qt::WindowMinimized) {
992     // restore
993     setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
994   }
995
996   // this does not actually work on all platforms... and causes more evil than good
997   // move(frameGeometry().topLeft()); // avoid placement policies
998   show();
999   raise();
1000   activateWindow();
1001 #endif /* HAVE_KDE */
1002 }
1003
1004 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
1005   Q_UNUSED(parent);
1006
1007   bool hasFocus = QApplication::activeWindow() != 0;
1008
1009   for(int i = start; i <= end; i++) {
1010     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1011     if(!idx.isValid()) {
1012       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1013       continue;
1014     }
1015     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1016     if(flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1017       continue;
1018
1019     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1020     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1021
1022     if(hasFocus && bufId == Client::bufferModel()->currentBuffer())
1023       continue;
1024
1025     if((flags & Message::Highlight || bufType == BufferInfo::QueryBuffer)
1026       && !(Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(),
1027                                                                              Client::networkModel()->networkName(bufId))))
1028     {
1029       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1030       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1031       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1032       AbstractNotificationBackend::NotificationType type;
1033
1034       if(bufType == BufferInfo::QueryBuffer && !hasFocus)
1035         type = AbstractNotificationBackend::PrivMsg;
1036       else if(bufType == BufferInfo::QueryBuffer && hasFocus)
1037         type = AbstractNotificationBackend::PrivMsgFocused;
1038       else if(flags & Message::Highlight && !hasFocus)
1039         type = AbstractNotificationBackend::Highlight;
1040       else
1041         type = AbstractNotificationBackend::HighlightFocused;
1042
1043       QtUi::invokeNotification(bufId, type, sender, contents);
1044     }
1045   }
1046 }
1047
1048 void MainWin::currentBufferChanged(BufferId buffer) {
1049   if(buffer.isValid())
1050     QtUi::closeNotifications(buffer);
1051 }
1052
1053 void MainWin::clientNetworkCreated(NetworkId id) {
1054   const Network *net = Client::network(id);
1055   QAction *act = new QAction(net->networkName(), this);
1056   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1057   act->setData(QVariant::fromValue<NetworkId>(id));
1058   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1059   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1060
1061   QAction *beforeAction = 0;
1062   foreach(QAction *action, _networksMenu->actions()) {
1063     if(!action->data().isValid())  // ignore stock actions
1064       continue;
1065     if(net->networkName().localeAwareCompare(action->text()) < 0) {
1066       beforeAction = action;
1067       break;
1068     }
1069   }
1070   _networksMenu->insertAction(beforeAction, act);
1071 }
1072
1073 void MainWin::clientNetworkUpdated() {
1074   const Network *net = qobject_cast<const Network *>(sender());
1075   if(!net)
1076     return;
1077
1078   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1079   if(!action)
1080     return;
1081
1082   action->setText(net->networkName());
1083
1084   switch(net->connectionState()) {
1085   case Network::Initialized:
1086     action->setIcon(SmallIcon("network-connect"));
1087     break;
1088   case Network::Disconnected:
1089     action->setIcon(SmallIcon("network-disconnect"));
1090     break;
1091   default:
1092     action->setIcon(SmallIcon("network-wired"));
1093   }
1094 }
1095
1096 void MainWin::clientNetworkRemoved(NetworkId id) {
1097   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1098   if(!action)
1099     return;
1100
1101   action->deleteLater();
1102 }
1103
1104 void MainWin::connectOrDisconnectFromNet() {
1105   QAction *act = qobject_cast<QAction *>(sender());
1106   if(!act) return;
1107   const Network *net = Client::network(act->data().value<NetworkId>());
1108   if(!net) return;
1109   if(net->connectionState() == Network::Disconnected) net->requestConnect();
1110   else net->requestDisconnect();
1111 }
1112
1113 void MainWin::on_jumpHotBuffer_triggered() {
1114   if(!_bufferHotList->rowCount())
1115     return;
1116
1117   QModelIndex topIndex = _bufferHotList->index(0, 0);
1118   BufferId bufferId = _bufferHotList->data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
1119   Client::bufferModel()->switchToBuffer(bufferId);
1120 }
1121
1122 void MainWin::on_actionDebugNetworkModel_triggered() {
1123   QTreeView *view = new QTreeView;
1124   view->setAttribute(Qt::WA_DeleteOnClose);
1125   view->setWindowTitle("Debug NetworkModel View");
1126   view->setModel(Client::networkModel());
1127   view->setColumnWidth(0, 250);
1128   view->setColumnWidth(1, 250);
1129   view->setColumnWidth(2, 80);
1130   view->resize(610, 300);
1131   view->show();
1132 }
1133
1134 void MainWin::on_actionDebugHotList_triggered() {
1135   QTreeView *view = new QTreeView;
1136   view->setAttribute(Qt::WA_DeleteOnClose);
1137   view->setModel(_bufferHotList);
1138   view->show();
1139 }
1140
1141 void MainWin::on_actionDebugBufferViewOverlay_triggered() {
1142   DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1143   overlay->setAttribute(Qt::WA_DeleteOnClose);
1144   overlay->show();
1145 }
1146
1147 void MainWin::on_actionDebugMessageModel_triggered() {
1148   QTableView *view = new QTableView(0);
1149   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1150   filter->setSourceModel(Client::messageModel());
1151   view->setModel(filter);
1152   view->setAttribute(Qt::WA_DeleteOnClose, true);
1153   view->verticalHeader()->hide();
1154   view->horizontalHeader()->setStretchLastSection(true);
1155   view->show();
1156 }
1157
1158 void MainWin::on_actionDebugLog_triggered() {
1159   DebugLogWidget *logWidget = new DebugLogWidget(0);
1160   logWidget->show();
1161 }
1162
1163 void MainWin::showStatusBarMessage(const QString &message) {
1164   statusBar()->showMessage(message, 10000);
1165 }
1166