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