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