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