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