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