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