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