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