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