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