Update ChatViews whenever the stylesheet is reloaded
[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 "settingsdlg.h"
76 #include "settingspagedlg.h"
77 #include "systemtray.h"
78 #include "toolbaractionprovider.h"
79 #include "topicwidget.h"
80 #include "verticaldock.h"
81
82 #ifndef HAVE_KDE
83 #  ifdef HAVE_DBUS
84 #    include "desktopnotificationbackend.h"
85 #  endif
86 #  ifdef HAVE_PHONON
87 #    include "phononnotificationbackend.h"
88 #  endif
89 #  include "systraynotificationbackend.h"
90 #  include "taskbarnotificationbackend.h"
91 #else /* HAVE_KDE */
92 #  include "knotificationbackend.h"
93 #endif /* HAVE_KDE */
94
95 #include "settingspages/aliasessettingspage.h"
96 #include "settingspages/appearancesettingspage.h"
97 #include "settingspages/backlogsettingspage.h"
98 #include "settingspages/bufferviewsettingspage.h"
99 #include "settingspages/chatmonitorsettingspage.h"
100 #include "settingspages/colorsettingspage.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
322   // Navigation
323   coll->addAction("JumpHotBuffer", new Action(tr("Jump to hot buffer"), coll,
324                                               this, SLOT(on_jumpHotBuffer_triggered()), QKeySequence(Qt::META + Qt::Key_A)));
325 }
326
327 void MainWin::setupMenus() {
328   ActionCollection *coll = QtUi::actionCollection("General");
329
330   _fileMenu = menuBar()->addMenu(tr("&File"));
331
332   static const QStringList coreActions = QStringList()
333     << "ConnectCore" << "DisconnectCore" << "CoreInfo";
334
335   QAction *coreAction;
336   foreach(QString actionName, coreActions) {
337     coreAction = coll->action(actionName);
338     _fileMenu->addAction(coreAction);
339     flagRemoteCoreOnly(coreAction);
340   }
341   flagRemoteCoreOnly(_fileMenu->addSeparator());
342
343   _networksMenu = _fileMenu->addMenu(tr("&Networks"));
344   _networksMenu->addAction(coll->action("ConfigureNetworks"));
345   _networksMenu->addSeparator();
346   _fileMenu->addSeparator();
347   _fileMenu->addAction(coll->action("Quit"));
348
349   _viewMenu = menuBar()->addMenu(tr("&View"));
350   _bufferViewsMenu = _viewMenu->addMenu(tr("&Buffer Views"));
351   _bufferViewsMenu->addAction(coll->action("ConfigureBufferViews"));
352   _toolbarMenu = _viewMenu->addMenu(tr("&Toolbars"));
353   _viewMenu->addSeparator();
354   _viewMenu->addAction(coll->action("ToggleSearchBar"));
355
356   coreAction = coll->action("ShowAwayLog");
357   flagRemoteCoreOnly(coreAction);
358   _viewMenu->addAction(coreAction);
359
360   _viewMenu->addAction(coll->action("ToggleStatusBar"));
361   _viewMenu->addSeparator();
362   _viewMenu->addAction(coll->action("LockLayout"));
363
364   _settingsMenu = menuBar()->addMenu(tr("&Settings"));
365 #ifdef HAVE_KDE
366   _settingsMenu->addAction(KStandardAction::keyBindings(this, SLOT(showShortcutsDlg()), this));
367   _settingsMenu->addAction(KStandardAction::configureNotifications(this, SLOT(showNotificationsDlg()), this));
368 #endif
369   _settingsMenu->addAction(coll->action("ConfigureQuassel"));
370
371   _helpMenu = menuBar()->addMenu(tr("&Help"));
372   _helpMenu->addAction(coll->action("AboutQuassel"));
373 #ifndef HAVE_KDE
374   _helpMenu->addAction(coll->action("AboutQt"));
375 #else
376   _helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, SLOT(aboutKDE()), this));
377 #endif
378   _helpMenu->addSeparator();
379   _helpDebugMenu = _helpMenu->addMenu(SmallIcon("tools-report-bug"), tr("Debug"));
380   _helpDebugMenu->addAction(coll->action("DebugNetworkModel"));
381   _helpDebugMenu->addAction(coll->action("DebugBufferViewOverlay"));
382   _helpDebugMenu->addAction(coll->action("DebugMessageModel"));
383   _helpDebugMenu->addAction(coll->action("DebugHotList"));
384   _helpDebugMenu->addAction(coll->action("DebugLog"));
385 }
386
387 void MainWin::setupBufferWidget() {
388   _bufferWidget = new BufferWidget(this);
389   _bufferWidget->setModel(Client::bufferModel());
390   _bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
391   setCentralWidget(_bufferWidget);
392 }
393
394 void MainWin::addBufferView(int bufferViewConfigId) {
395   addBufferView(Client::bufferViewManager()->clientBufferViewConfig(bufferViewConfigId));
396 }
397
398 void MainWin::addBufferView(ClientBufferViewConfig *config) {
399   if(!config)
400     return;
401
402   config->setLocked(QtUiSettings().value("LockLayout", false).toBool());
403   BufferViewDock *dock = new BufferViewDock(config, this);
404
405   //create the view and initialize it's filter
406   BufferView *view = new BufferView(dock);
407   view->setFilteredModel(Client::bufferModel(), config);
408   view->installEventFilter(_inputWidget->inputLine()); // for key presses
409   view->show();
410
411   Client::bufferModel()->synchronizeView(view);
412
413   dock->setWidget(view);
414   dock->show();
415
416   addDockWidget(Qt::LeftDockWidgetArea, dock);
417   _bufferViewsMenu->addAction(dock->toggleViewAction());
418
419   connect(dock->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(bufferViewToggled(bool)));
420   _bufferViews.append(dock);
421 }
422
423 void MainWin::removeBufferView(int bufferViewConfigId) {
424   QVariant actionData;
425   BufferViewDock *dock;
426   foreach(QAction *action, _bufferViewsMenu->actions()) {
427     actionData = action->data();
428     if(!actionData.isValid())
429       continue;
430
431     dock = qobject_cast<BufferViewDock *>(action->parent());
432     if(dock && actionData.toInt() == bufferViewConfigId) {
433       removeAction(action);
434       dock->deleteLater();
435     }
436   }
437 }
438
439 void MainWin::bufferViewToggled(bool enabled) {
440   QAction *action = qobject_cast<QAction *>(sender());
441   Q_ASSERT(action);
442   BufferViewDock *dock = qobject_cast<BufferViewDock *>(action->parent());
443   Q_ASSERT(dock);
444   if(enabled) {
445     Client::bufferViewOverlay()->addView(dock->bufferViewId());
446     BufferViewConfig *config = dock->config();
447     if(config && config->isInitialized()) {
448       BufferIdList buffers;
449       if(config->networkId().isValid()) {
450         foreach(BufferId bufferId, config->bufferList()) {
451           if(Client::networkModel()->networkId(bufferId) == config->networkId())
452             buffers << bufferId;
453         }
454         foreach(BufferId bufferId, config->temporarilyRemovedBuffers().toList()) {
455           if(Client::networkModel()->networkId(bufferId) == config->networkId())
456             buffers << bufferId;
457         }
458       } else {
459         buffers = BufferIdList::fromSet(config->bufferList().toSet() + config->temporarilyRemovedBuffers());
460       }
461       Client::backlogManager()->checkForBacklog(buffers);
462     }
463   } else {
464     Client::bufferViewOverlay()->removeView(dock->bufferViewId());
465   }
466 }
467
468 BufferView *MainWin::allBuffersView() const {
469   // "All Buffers" is always the first dock created
470   if(_bufferViews.count() > 0)
471     return _bufferViews[0]->bufferView();
472   return 0;
473 }
474
475 void MainWin::showNotificationsDlg() {
476   SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
477   dlg.exec();
478 }
479
480 void MainWin::on_actionConfigureNetworks_triggered() {
481   SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
482   dlg.exec();
483 }
484
485 void MainWin::on_actionConfigureViews_triggered() {
486   SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
487   dlg.exec();
488 }
489
490 void MainWin::on_actionLockLayout_toggled(bool lock) {
491   QList<VerticalDock *> docks = findChildren<VerticalDock *>();
492   foreach(VerticalDock *dock, docks) {
493     dock->showTitle(!lock);
494   }
495   if(Client::bufferViewManager()) {
496     foreach(ClientBufferViewConfig *config, Client::bufferViewManager()->clientBufferViewConfigs()) {
497       config->setLocked(lock);
498     }
499   }
500   QtUiSettings().setValue("LockLayout", lock);
501 }
502
503 void MainWin::setupNickWidget() {
504   // create nick dock
505   NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
506   nickDock->setObjectName("NickDock");
507   nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
508
509   _nickListWidget = new NickListWidget(nickDock);
510   nickDock->setWidget(_nickListWidget);
511
512   addDockWidget(Qt::RightDockWidgetArea, nickDock);
513   _viewMenu->addAction(nickDock->toggleViewAction());
514   nickDock->toggleViewAction()->setText(tr("Show Nick List"));
515
516   // See NickListDock::NickListDock();
517   // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
518
519   // attach the NickListWidget to the BufferModel and the default selection
520   _nickListWidget->setModel(Client::bufferModel());
521   _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
522 }
523
524 void MainWin::setupChatMonitor() {
525   VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
526   dock->setObjectName("ChatMonitorDock");
527
528   ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
529   ChatMonitorView *chatView = new ChatMonitorView(filter, this);
530   chatView->show();
531   dock->setWidget(chatView);
532   dock->hide();
533
534   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
535   _viewMenu->addAction(dock->toggleViewAction());
536   dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
537 }
538
539 void MainWin::setupInputWidget() {
540   VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
541   dock->setObjectName("InputDock");
542
543   _inputWidget = new InputWidget(dock);
544   dock->setWidget(_inputWidget);
545
546   addDockWidget(Qt::BottomDockWidgetArea, dock);
547
548   _viewMenu->addAction(dock->toggleViewAction());
549   dock->toggleViewAction()->setText(tr("Show Input Line"));
550
551   _inputWidget->setModel(Client::bufferModel());
552   _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
553
554   _bufferWidget->setFocusProxy(_inputWidget);
555
556   _inputWidget->inputLine()->installEventFilter(_bufferWidget);
557 }
558
559 void MainWin::setupTopicWidget() {
560   VerticalDock *dock = new VerticalDock(tr("Topic"), this);
561   dock->setObjectName("TopicDock");
562   TopicWidget *topicwidget = new TopicWidget(dock);
563
564   dock->setWidget(topicwidget);
565
566   topicwidget->setModel(Client::bufferModel());
567   topicwidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
568
569   addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
570
571   _viewMenu->addAction(dock->toggleViewAction());
572   dock->toggleViewAction()->setText(tr("Show Topic Line"));
573 }
574
575 void MainWin::setupTitleSetter() {
576   _titleSetter.setModel(Client::bufferModel());
577   _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
578 }
579
580 void MainWin::setupStatusBar() {
581   // MessageProcessor progress
582   statusBar()->addPermanentWidget(msgProcessorStatusWidget);
583
584   // Core Lag:
585   updateLagIndicator();
586   statusBar()->addPermanentWidget(coreLagLabel);
587   coreLagLabel->hide();
588   connect(Client::signalProxy(), SIGNAL(lagUpdated(int)), this, SLOT(updateLagIndicator(int)));
589
590   // SSL indicator
591   sslLabel->setPixmap(QPixmap());
592   statusBar()->addPermanentWidget(sslLabel);
593   sslLabel->hide();
594
595   QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
596
597   QtUiSettings uiSettings;
598
599   bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
600   showStatusbar->setChecked(enabled);
601   enabled ? statusBar()->show() : statusBar()->hide();
602
603   connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
604   connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
605 }
606
607 void MainWin::setupHotList() {
608   FlatProxyModel *flatProxy = new FlatProxyModel(this);
609   flatProxy->setSourceModel(Client::bufferModel());
610   _bufferHotList = new BufferHotListFilter(flatProxy);
611 }
612
613 void MainWin::saveStatusBarStatus(bool enabled) {
614   QtUiSettings uiSettings;
615   uiSettings.setValue("ShowStatusBar", enabled);
616 }
617
618 void MainWin::setupSystray() {
619   _systemTray = new SystemTray(this);
620 }
621
622 void MainWin::setupToolBars() {
623   connect(_bufferWidget, SIGNAL(currentChanged(QModelIndex)),
624           QtUi::toolBarActionProvider(), SLOT(currentBufferChanged(QModelIndex)));
625   connect(_nickListWidget, SIGNAL(nickSelectionChanged(QModelIndexList)),
626           QtUi::toolBarActionProvider(), SLOT(nickSelectionChanged(QModelIndexList)));
627
628 #ifdef Q_WS_MAC
629   setUnifiedTitleAndToolBarOnMac(true);
630 #endif
631
632 #ifdef HAVE_KDE
633   _mainToolBar = new KToolBar("MainToolBar", this, Qt::TopToolBarArea, false, true, true);
634 #else
635   _mainToolBar = new QToolBar(this);
636   _mainToolBar->setObjectName("MainToolBar");
637 #endif
638   _mainToolBar->setWindowTitle(tr("Main Toolbar"));
639   addToolBar(_mainToolBar);
640
641   QtUi::toolBarActionProvider()->addActions(_mainToolBar, ToolBarActionProvider::MainToolBar);
642   _toolbarMenu->addAction(_mainToolBar->toggleViewAction());
643 }
644
645 void MainWin::connectedToCore() {
646   Q_CHECK_PTR(Client::bufferViewManager());
647   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
648   connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
649   connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
650
651   setConnectedState();
652 }
653
654 void MainWin::setConnectedState() {
655   ActionCollection *coll = QtUi::actionCollection("General");
656
657   coll->action("ConnectCore")->setEnabled(false);
658   coll->action("DisconnectCore")->setEnabled(true);
659   coll->action("CoreInfo")->setEnabled(true);
660
661   foreach(QAction *action, _fileMenu->actions()) {
662     if(isRemoteCoreOnly(action))
663       action->setVisible(!Client::internalCore());
664   }
665
666   disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), msgProcessorStatusWidget, SLOT(setProgress(int, int)));
667   disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
668   disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
669   if(!Client::internalCore()) {
670     connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), msgProcessorStatusWidget, SLOT(setProgress(int, int)));
671     connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
672     connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
673   }
674
675   // _viewMenu->setEnabled(true);
676   if(!Client::internalCore())
677     statusBar()->showMessage(tr("Connected to core."));
678   else
679     statusBar()->clearMessage();
680
681   if(Client::signalProxy()->isSecure()) {
682     sslLabel->setPixmap(SmallIcon("security-high"));
683   } else {
684     sslLabel->setPixmap(SmallIcon("security-low"));
685   }
686
687   sslLabel->setVisible(!Client::internalCore());
688   coreLagLabel->setVisible(!Client::internalCore());
689   updateIcon();
690   systemTray()->setState(SystemTray::Active);
691
692   if(Client::networkIds().isEmpty()) {
693     IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
694     wizard->show();
695   }
696 }
697
698 void MainWin::loadLayout() {
699   QtUiSettings s;
700   int accountId = Client::currentCoreAccount().toInt();
701   restoreState(s.value(QString("MainWinState-%1").arg(accountId)).toByteArray(), accountId);
702 }
703
704 void MainWin::saveLayout() {
705   QtUiSettings s;
706   int accountId = Client::currentCoreAccount().toInt();
707   if(accountId > 0) s.setValue(QString("MainWinState-%1").arg(accountId) , saveState(accountId));
708 }
709
710 void MainWin::updateLagIndicator(int lag) {
711   QString text = tr("Core Lag: %1");
712   if(lag == -1)
713     text = text.arg('-');
714   else
715     text = text.arg("%1 msec").arg(lag);
716   coreLagLabel->setText(text);
717 }
718
719 void MainWin::disconnectedFromCore() {
720   // save core specific layout and remove bufferviews;
721   saveLayout();
722   QVariant actionData;
723   BufferViewDock *dock;
724   foreach(QAction *action, _bufferViewsMenu->actions()) {
725     actionData = action->data();
726     if(!actionData.isValid())
727       continue;
728
729     dock = qobject_cast<BufferViewDock *>(action->parent());
730     if(dock && actionData.toInt() != -1) {
731       removeAction(action);
732       dock->deleteLater();
733     }
734   }
735   QtUiSettings s;
736   restoreState(s.value("MainWinState").toByteArray());
737   setDisconnectedState();
738 }
739
740 void MainWin::setDisconnectedState() {
741   ActionCollection *coll = QtUi::actionCollection("General");
742   //ui.menuCore->setEnabled(false);
743   coll->action("ConnectCore")->setEnabled(true);
744   coll->action("DisconnectCore")->setEnabled(false);
745   coll->action("CoreInfo")->setEnabled(false);
746   //_viewMenu->setEnabled(false);
747   statusBar()->showMessage(tr("Not connected to core."));
748   sslLabel->setPixmap(QPixmap());
749   sslLabel->hide();
750   updateLagIndicator();
751   coreLagLabel->hide();
752   if(msgProcessorStatusWidget)
753     msgProcessorStatusWidget->setProgress(0, 0);
754   updateIcon();
755   systemTray()->setState(SystemTray::Inactive);
756 }
757
758 void MainWin::startInternalCore() {
759   ClientSyncer *syncer = new ClientSyncer();
760   Client::registerClientSyncer(syncer);
761   connect(syncer, SIGNAL(syncFinished()), syncer, SLOT(deleteLater()), Qt::QueuedConnection);
762   syncer->useInternalCore();
763 }
764
765 void MainWin::showCoreConnectionDlg(bool autoConnect) {
766   CoreConnectDlg(autoConnect, this).exec();
767 }
768
769 void MainWin::showChannelList(NetworkId netId) {
770   ChannelListDlg *channelListDlg = new ChannelListDlg();
771
772   if(!netId.isValid()) {
773     QAction *action = qobject_cast<QAction *>(sender());
774     if(action)
775       netId = action->data().value<NetworkId>();
776   }
777
778   channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
779   channelListDlg->setNetwork(netId);
780   channelListDlg->show();
781 }
782
783 void MainWin::showCoreInfoDlg() {
784   CoreInfoDlg(this).exec();
785 }
786
787 void MainWin::showAwayLog() {
788   if(_awayLog)
789     return;
790   AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
791   _awayLog = new AwayLogView(filter, 0);
792   filter->setParent(_awayLog);
793   connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
794   _awayLog->setAttribute(Qt::WA_DeleteOnClose);
795   _awayLog->show();
796 }
797
798 void MainWin::awayLogDestroyed() {
799   _awayLog = 0;
800 }
801
802 void MainWin::showSettingsDlg() {
803   SettingsDlg *dlg = new SettingsDlg();
804
805   //Category: Appearance
806   dlg->registerSettingsPage(new AppearanceSettingsPage(dlg)); //General
807   dlg->registerSettingsPage(new ColorSettingsPage(dlg));
808   dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
809   dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
810   dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
811   dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
812   dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
813
814   //Category: Misc
815   dlg->registerSettingsPage(new GeneralSettingsPage(dlg));
816   dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
817   dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
818   dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
819   dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
820
821   dlg->show();
822 }
823
824 void MainWin::showAboutDlg() {
825   AboutDlg(this).exec();
826 }
827
828 #ifdef HAVE_KDE
829 void MainWin::showShortcutsDlg() {
830   KShortcutsDialog::configure(QtUi::actionCollection("General"), KShortcutsEditor::LetterShortcutsDisallowed);
831 }
832 #endif
833
834 /********************************************************************************************************/
835
836 bool MainWin::event(QEvent *event) {
837   if(event->type() == QEvent::WindowActivate)
838     QtUi::closeNotifications();
839   return QMainWindow::event(event);
840 }
841
842 void MainWin::moveEvent(QMoveEvent *event) {
843   if(!(windowState() & Qt::WindowMaximized))
844     _normalPos = event->pos();
845
846   QMainWindow::moveEvent(event);
847 }
848
849 void MainWin::resizeEvent(QResizeEvent *event) {
850   if(!(windowState() & Qt::WindowMaximized))
851     _normalSize = event->size();
852
853   QMainWindow::resizeEvent(event);
854 }
855
856 void MainWin::closeEvent(QCloseEvent *event) {
857   QtUiSettings s;
858   QtUiApplication* app = qobject_cast<QtUiApplication*> qApp;
859   Q_ASSERT(app);
860   if(!app->isAboutToQuit() && s.value("UseSystemTrayIcon").toBool() && s.value("MinimizeOnClose").toBool()) {
861     hideToTray();
862     event->ignore();
863   } else {
864     event->accept();
865     quit();
866   }
867 }
868
869 void MainWin::changeEvent(QEvent *event) {
870 #ifdef Q_WS_WIN
871   if(event->type() == QEvent::ActivationChange)
872     dwTickCount = GetTickCount();  // needed for toggleMinimizedToTray()
873 #endif
874
875   QMainWindow::changeEvent(event);
876 }
877
878 void MainWin::hideToTray() {
879   if(!systemTray()->isSystemTrayAvailable()) {
880     qWarning() << Q_FUNC_INFO << "was called with no SystemTray available!";
881     return;
882   }
883   hide();
884   systemTray()->setIconVisible();
885 }
886
887 void MainWin::toggleMinimizedToTray() {
888 #ifdef Q_WS_WIN
889   // the problem is that we lose focus when the systray icon is activated
890   // and we don't know the former active window
891   // therefore we watch for activation event and use our stopwatch :)
892   // courtesy: KSystemTrayIcon
893   if(GetTickCount() - dwTickCount >= 300)
894     // we weren't active in the last 300ms -> activate
895     forceActivated();
896   else
897     hideToTray();
898
899 #else
900
901   if(!isVisible() || isMinimized())
902     // restore
903     forceActivated();
904   else
905     hideToTray();
906
907 #endif
908 }
909
910 void MainWin::forceActivated() {
911 #ifdef Q_WS_X11
912   // Bypass focus stealing prevention
913   QX11Info::setAppUserTime(QX11Info::appTime());
914 #endif
915
916   if(windowState() & Qt::WindowMinimized) {
917     // restore
918     setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
919   }
920
921   // this does not actually work on all platforms... and causes more evil than good
922   // move(frameGeometry().topLeft()); // avoid placement policies
923   show();
924   raise();
925   activateWindow();
926 }
927
928 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end) {
929   Q_UNUSED(parent);
930
931   bool hasFocus = QApplication::activeWindow() != 0;
932
933   for(int i = start; i <= end; i++) {
934     QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
935     if(!idx.isValid()) {
936       qDebug() << "MainWin::messagesInserted(): Invalid model index!";
937       continue;
938     }
939     Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
940     if(flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
941       continue;
942     flags |= Message::Backlog;  // we only want to trigger a highlight once!
943     Client::messageModel()->setData(idx, (int)flags, ChatLineModel::FlagsRole);
944
945     BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
946     BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
947
948     if(hasFocus && bufId == _bufferWidget->currentBuffer())
949       continue;
950
951     if(flags & Message::Highlight || bufType == BufferInfo::QueryBuffer) {
952       QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
953       QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
954       QString contents = idx.data(ChatLineModel::DisplayRole).toString();
955       AbstractNotificationBackend::NotificationType type;
956
957       if(bufType == BufferInfo::QueryBuffer && !hasFocus)
958         type = AbstractNotificationBackend::PrivMsg;
959       else if(bufType == BufferInfo::QueryBuffer && hasFocus)
960         type = AbstractNotificationBackend::PrivMsgFocused;
961       else if(flags & Message::Highlight && !hasFocus)
962         type = AbstractNotificationBackend::Highlight;
963       else
964         type = AbstractNotificationBackend::HighlightFocused;
965
966       QtUi::invokeNotification(bufId, type, sender, contents);
967     }
968   }
969 }
970
971 void MainWin::clientNetworkCreated(NetworkId id) {
972   const Network *net = Client::network(id);
973   QAction *act = new QAction(net->networkName(), this);
974   act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
975   act->setData(QVariant::fromValue<NetworkId>(id));
976   connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
977   connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
978
979   QAction *beforeAction = 0;
980   foreach(QAction *action, _networksMenu->actions()) {
981     if(!action->data().isValid())  // ignore stock actions
982       continue;
983     if(net->networkName().localeAwareCompare(action->text()) < 0) {
984       beforeAction = action;
985       break;
986     }
987   }
988   _networksMenu->insertAction(beforeAction, act);
989 }
990
991 void MainWin::clientNetworkUpdated() {
992   const Network *net = qobject_cast<const Network *>(sender());
993   if(!net)
994     return;
995
996   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
997   if(!action)
998     return;
999
1000   action->setText(net->networkName());
1001
1002   switch(net->connectionState()) {
1003   case Network::Initialized:
1004     action->setIcon(SmallIcon("network-connect"));
1005     break;
1006   case Network::Disconnected:
1007     action->setIcon(SmallIcon("network-disconnect"));
1008     break;
1009   default:
1010     action->setIcon(SmallIcon("network-wired"));
1011   }
1012 }
1013
1014 void MainWin::clientNetworkRemoved(NetworkId id) {
1015   QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1016   if(!action)
1017     return;
1018
1019   action->deleteLater();
1020 }
1021
1022 void MainWin::connectOrDisconnectFromNet() {
1023   QAction *act = qobject_cast<QAction *>(sender());
1024   if(!act) return;
1025   const Network *net = Client::network(act->data().value<NetworkId>());
1026   if(!net) return;
1027   if(net->connectionState() == Network::Disconnected) net->requestConnect();
1028   else net->requestDisconnect();
1029 }
1030
1031 void MainWin::on_jumpHotBuffer_triggered() {
1032   if(!_bufferHotList->rowCount())
1033     return;
1034
1035   QModelIndex topIndex = _bufferHotList->index(0, 0);
1036   BufferId bufferId = _bufferHotList->data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
1037   Client::bufferModel()->switchToBuffer(bufferId);
1038 }
1039
1040 void MainWin::on_actionDebugNetworkModel_triggered() {
1041   QTreeView *view = new QTreeView;
1042   view->setAttribute(Qt::WA_DeleteOnClose);
1043   view->setWindowTitle("Debug NetworkModel View");
1044   view->setModel(Client::networkModel());
1045   view->setColumnWidth(0, 250);
1046   view->setColumnWidth(1, 250);
1047   view->setColumnWidth(2, 80);
1048   view->resize(610, 300);
1049   view->show();
1050 }
1051
1052 void MainWin::on_actionDebugHotList_triggered() {
1053   QTreeView *view = new QTreeView;
1054   view->setAttribute(Qt::WA_DeleteOnClose);
1055   view->setModel(_bufferHotList);
1056   view->show();
1057 }
1058
1059 void MainWin::on_actionDebugBufferViewOverlay_triggered() {
1060   DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1061   overlay->setAttribute(Qt::WA_DeleteOnClose);
1062   overlay->show();
1063 }
1064
1065 void MainWin::on_actionDebugMessageModel_triggered() {
1066   QTableView *view = new QTableView(0);
1067   DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1068   filter->setSourceModel(Client::messageModel());
1069   view->setModel(filter);
1070   view->setAttribute(Qt::WA_DeleteOnClose, true);
1071   view->verticalHeader()->hide();
1072   view->horizontalHeader()->setStretchLastSection(true);
1073   view->show();
1074 }
1075
1076 void MainWin::on_actionDebugLog_triggered() {
1077   DebugLogWidget *logWidget = new DebugLogWidget(0);
1078   logWidget->show();
1079 }
1080
1081 void MainWin::showStatusBarMessage(const QString &message) {
1082   statusBar()->showMessage(message, 10000);
1083 }
1084