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