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