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