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