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