Revert rudimentary DCC support for the 0.10 release
[quassel.git] / src / qtui / mainwin.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2014 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "mainwin.h"
22
23 #include <QMenuBar>
24 #include <QMessageBox>
25 #include <QStatusBar>
26 #include <QToolBar>
27
28 #ifdef HAVE_KDE
29 #  include <KAction>
30 #  include <KActionCollection>
31 #  include <KHelpMenu>
32 #  include <KMenuBar>
33 #  include <KShortcutsDialog>
34 #  include <KStatusBar>
35 #  include <KToggleFullScreenAction>
36 #  include <KToolBar>
37 #  include <KWindowSystem>
38 #endif
39
40 #ifdef Q_WS_X11
41 #  include <QX11Info>
42 #endif
43
44 #include "aboutdlg.h"
45 #include "awaylogfilter.h"
46 #include "awaylogview.h"
47 #include "action.h"
48 #include "actioncollection.h"
49 #include "bufferhotlistfilter.h"
50 #include "buffermodel.h"
51 #include "bufferview.h"
52 #include "bufferviewoverlay.h"
53 #include "bufferviewoverlayfilter.h"
54 #include "bufferwidget.h"
55 #include "channellistdlg.h"
56 #include "chatlinemodel.h"
57 #include "chatmonitorfilter.h"
58 #include "chatmonitorview.h"
59 #include "chatview.h"
60 #include "client.h"
61 #include "clientbacklogmanager.h"
62 #include "clientbufferviewconfig.h"
63 #include "clientbufferviewmanager.h"
64 #include "clientignorelistmanager.h"
65 #include "coreconfigwizard.h"
66 #include "coreconnectdlg.h"
67 #include "coreconnection.h"
68 #include "coreconnectionstatuswidget.h"
69 #include "coreinfodlg.h"
70 #include "contextmenuactionprovider.h"
71 #include "debugbufferviewoverlay.h"
72 #include "debuglogwidget.h"
73 #include "debugmessagemodelfilter.h"
74 #include "flatproxymodel.h"
75 #include "iconloader.h"
76 #include "inputwidget.h"
77 #include "irclistmodel.h"
78 #include "ircconnectionwizard.h"
79 #include "legacysystemtray.h"
80 #include "msgprocessorstatuswidget.h"
81 #include "nicklistwidget.h"
82 #include "qtuiapplication.h"
83 #include "qtuimessageprocessor.h"
84 #include "qtuisettings.h"
85 #include "qtuistyle.h"
86 #include "settingsdlg.h"
87 #include "settingspagedlg.h"
88 #include "statusnotifieritem.h"
89 #include "toolbaractionprovider.h"
90 #include "topicwidget.h"
91 #include "verticaldock.h"
92
93 #ifndef HAVE_KDE
94 #  ifdef HAVE_PHONON
95 #    include "phononnotificationbackend.h"
96 #  endif
97 #  ifdef HAVE_LIBSNORE
98 #    include "snorenotificationbackend.h"
99 #  endif
100 #  include "systraynotificationbackend.h"
101 #  include "taskbarnotificationbackend.h"
102 #else /* HAVE_KDE */
103 #  include "knotificationbackend.h"
104 #endif /* HAVE_KDE */
105
106 #ifdef HAVE_SSL
107 #  include "sslinfodlg.h"
108 #endif
109
110 #ifdef HAVE_INDICATEQT
111   #include "indicatornotificationbackend.h"
112 #endif
113
114 #ifdef HAVE_NOTIFICATION_CENTER
115   #include "osxnotificationbackend.h"
116 #endif
117
118 #ifdef HAVE_DBUS
119   #include "dockmanagernotificationbackend.h"
120 #endif
121
122 #include "settingspages/aliasessettingspage.h"
123 #include "settingspages/appearancesettingspage.h"
124 #include "settingspages/backlogsettingspage.h"
125 #include "settingspages/bufferviewsettingspage.h"
126 #include "settingspages/chatmonitorsettingspage.h"
127 #include "settingspages/chatviewsettingspage.h"
128 #include "settingspages/connectionsettingspage.h"
129 #include "settingspages/coreaccountsettingspage.h"
130 #include "settingspages/coreconnectionsettingspage.h"
131 #include "settingspages/highlightsettingspage.h"
132 #include "settingspages/identitiessettingspage.h"
133 #include "settingspages/ignorelistsettingspage.h"
134 #include "settingspages/inputwidgetsettingspage.h"
135 #include "settingspages/itemviewsettingspage.h"
136 #include "settingspages/networkssettingspage.h"
137 #include "settingspages/notificationssettingspage.h"
138 #include "settingspages/topicwidgetsettingspage.h"
139
140 #ifndef HAVE_KDE
141 #  include "settingspages/shortcutssettingspage.h"
142 #endif
143
144 MainWin::MainWin(QWidget *parent)
145 #ifdef HAVE_KDE
146     : KMainWindow(parent),
147     _kHelpMenu(new KHelpMenu(this, KGlobal::mainComponent().aboutData())),
148 #else
149     : QMainWindow(parent),
150 #endif
151     _msgProcessorStatusWidget(new MsgProcessorStatusWidget(this)),
152     _coreConnectionStatusWidget(new CoreConnectionStatusWidget(Client::coreConnection(), this)),
153     _titleSetter(this),
154     _awayLog(0),
155     _layoutLoaded(false),
156     _activeBufferViewIndex(-1)
157 {
158     setAttribute(Qt::WA_DeleteOnClose, false); // we delete the mainwin manually
159
160     QtUiSettings uiSettings;
161     QString style = uiSettings.value("Style", QString()).toString();
162     if (!style.isEmpty()) {
163         QApplication::setStyle(style);
164     }
165
166     QApplication::setQuitOnLastWindowClosed(false);
167
168     setWindowTitle("Quassel IRC");
169     setWindowIconText("Quassel IRC");
170     updateIcon();
171 }
172
173
174 void MainWin::init()
175 {
176     connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), SLOT(clientNetworkCreated(NetworkId)));
177     connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), SLOT(clientNetworkRemoved(NetworkId)));
178     connect(Client::messageModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
179         SLOT(messagesInserted(const QModelIndex &, int, int)));
180     connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showChannelList(NetworkId)), SLOT(showChannelList(NetworkId)));
181     connect(GraphicalUi::contextMenuActionProvider(), SIGNAL(showIgnoreList(QString)), SLOT(showIgnoreList(QString)));
182
183     connect(Client::coreConnection(), SIGNAL(startCoreSetup(QVariantList)), SLOT(showCoreConfigWizard(QVariantList)));
184     connect(Client::coreConnection(), SIGNAL(connectionErrorPopup(QString)), SLOT(handleCoreConnectionError(QString)));
185     connect(Client::coreConnection(), SIGNAL(userAuthenticationRequired(CoreAccount *, bool *, QString)), SLOT(userAuthenticationRequired(CoreAccount *, bool *, QString)));
186     connect(Client::coreConnection(), SIGNAL(handleNoSslInClient(bool *)), SLOT(handleNoSslInClient(bool *)));
187     connect(Client::coreConnection(), SIGNAL(handleNoSslInCore(bool *)), SLOT(handleNoSslInCore(bool *)));
188 #ifdef HAVE_SSL
189     connect(Client::coreConnection(), SIGNAL(handleSslErrors(const QSslSocket *, bool *, bool *)), SLOT(handleSslErrors(const QSslSocket *, bool *, bool *)));
190 #endif
191
192     // Setup Dock Areas
193     setDockNestingEnabled(true);
194     setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
195     setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
196     setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
197     setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
198
199     // Order is sometimes important
200     setupActions();
201     setupBufferWidget();
202     setupMenus();
203     setupTopicWidget();
204     setupNickWidget();
205     setupInputWidget();
206     setupChatMonitor();
207     setupViewMenuTail();
208     setupStatusBar();
209     setupToolBars();
210     setupSystray();
211     setupTitleSetter();
212     setupHotList();
213
214 #ifndef HAVE_KDE
215 #  ifdef HAVE_PHONON
216     QtUi::registerNotificationBackend(new PhononNotificationBackend(this));
217 #  endif
218 #  ifdef HAVE_LIBSNORE
219     QtUi::registerNotificationBackend(new SnoreNotificationBackend(this));
220 #  elif !defined(QT_NO_SYSTEMTRAYICON)
221     QtUi::registerNotificationBackend(new SystrayNotificationBackend(this));
222 #  endif
223
224     QtUi::registerNotificationBackend(new TaskbarNotificationBackend(this));
225
226 #else /* HAVE_KDE */
227     QtUi::registerNotificationBackend(new KNotificationBackend(this));
228 #endif /* HAVE_KDE */
229
230 #ifdef HAVE_INDICATEQT
231     QtUi::registerNotificationBackend(new IndicatorNotificationBackend(this));
232 #endif
233
234 #ifdef HAVE_NOTIFICATION_CENTER
235     QtUi::registerNotificationBackend(new OSXNotificationBackend(this));
236 #endif
237
238 #ifdef HAVE_DBUS
239     QtUi::registerNotificationBackend(new DockManagerNotificationBackend(this));
240 #endif
241
242     // we assume that at this point, all configurable actions are defined!
243     QtUi::loadShortcuts();
244
245     connect(bufferWidget(), SIGNAL(currentChanged(BufferId)), SLOT(currentBufferChanged(BufferId)));
246
247     setDisconnectedState(); // Disable menus and stuff
248
249 #ifdef HAVE_KDE
250     setAutoSaveSettings();
251 #endif
252
253     // restore mainwin state
254     QtUiSettings s;
255     restoreStateFromSettings(s);
256
257     // restore locked state of docks
258     QtUi::actionCollection("General")->action("LockLayout")->setChecked(s.value("LockLayout", false).toBool());
259
260     CoreConnection *conn = Client::coreConnection();
261     if (!conn->connectToCore()) {
262         // No autoconnect selected (or no accounts)
263         showCoreConnectionDlg();
264     }
265 }
266
267
268 MainWin::~MainWin()
269 {
270 }
271
272
273 void MainWin::quit()
274 {
275     QtUiSettings s;
276     saveStateToSettings(s);
277     saveLayout();
278     QApplication::quit();
279 }
280
281
282 void MainWin::saveStateToSettings(UiSettings &s)
283 {
284     s.setValue("MainWinSize", _normalSize);
285     s.setValue("MainWinPos", _normalPos);
286     s.setValue("MainWinState", saveState());
287     s.setValue("MainWinGeometry", saveGeometry());
288     s.setValue("MainWinMinimized", isMinimized());
289     s.setValue("MainWinMaximized", isMaximized());
290     s.setValue("MainWinHidden", !isVisible());
291     BufferId lastBufId = Client::bufferModel()->currentBuffer();
292     if (lastBufId.isValid())
293         s.setValue("LastUsedBufferId", lastBufId.toInt());
294
295 #ifdef HAVE_KDE
296     saveAutoSaveSettings();
297 #endif
298 }
299
300
301 void MainWin::restoreStateFromSettings(UiSettings &s)
302 {
303     _normalSize = s.value("MainWinSize", size()).toSize();
304     _normalPos = s.value("MainWinPos", pos()).toPoint();
305     bool maximized = s.value("MainWinMaximized", false).toBool();
306
307 #ifndef HAVE_KDE
308     restoreGeometry(s.value("MainWinGeometry").toByteArray());
309
310     if (maximized) {
311         // restoreGeometry() fails if the windows was maximized, so we resize and position explicitly
312         resize(_normalSize);
313         move(_normalPos);
314     }
315
316     restoreState(s.value("MainWinState").toByteArray());
317
318 #else
319     move(_normalPos);
320 #endif
321
322     if ((Quassel::isOptionSet("hidewindow")
323             || s.value("MainWinHidden").toBool())
324             && _systemTray->isSystemTrayAvailable())
325         QtUi::hideMainWidget();
326     else if (s.value("MainWinMinimized").toBool())
327         showMinimized();
328     else if (maximized)
329         showMaximized();
330     else
331         show();
332 }
333
334
335 void MainWin::updateIcon()
336 {
337 #ifdef Q_WS_MAC
338     const int size = 128;
339 #else
340     const int size = 48;
341 #endif
342
343     QPixmap icon;
344     if (Client::isConnected())
345         icon = DesktopIcon("quassel", size);
346     else
347         icon = DesktopIcon("quassel-inactive", size);
348     setWindowIcon(icon);
349     qApp->setWindowIcon(icon);
350 }
351
352
353 void MainWin::setupActions()
354 {
355     ActionCollection *coll = QtUi::actionCollection("General", tr("General"));
356     // File
357     coll->addAction("ConnectCore", new Action(SmallIcon("network-connect"), tr("&Connect to Core..."), coll,
358             this, SLOT(showCoreConnectionDlg())));
359     coll->addAction("DisconnectCore", new Action(SmallIcon("network-disconnect"), tr("&Disconnect from Core"), coll,
360             Client::instance(), SLOT(disconnectFromCore())));
361     coll->addAction("CoreInfo", new Action(SmallIcon("help-about"), tr("Core &Info..."), coll,
362             this, SLOT(showCoreInfoDlg())));
363     coll->addAction("ConfigureNetworks", new Action(SmallIcon("configure"), tr("Configure &Networks..."), coll,
364             this, SLOT(on_actionConfigureNetworks_triggered())));
365     // FIXME: use QKeySequence::Quit once we depend on Qt 4.6
366     coll->addAction("Quit", new Action(SmallIcon("application-exit"), tr("&Quit"), coll,
367             this, SLOT(quit()), Qt::CTRL + Qt::Key_Q));
368
369     // View
370     coll->addAction("ConfigureBufferViews", new Action(tr("&Configure Chat Lists..."), coll,
371             this, SLOT(on_actionConfigureViews_triggered())));
372
373     QAction *lockAct = coll->addAction("LockLayout", new Action(tr("&Lock Layout"), coll));
374     lockAct->setCheckable(true);
375     connect(lockAct, SIGNAL(toggled(bool)), SLOT(on_actionLockLayout_toggled(bool)));
376
377     coll->addAction("ToggleSearchBar", new Action(SmallIcon("edit-find"), tr("Show &Search Bar"), coll,
378             0, 0, QKeySequence::Find))->setCheckable(true);
379     coll->addAction("ShowAwayLog", new Action(tr("Show Away Log"), coll,
380             this, SLOT(showAwayLog())));
381     coll->addAction("ToggleMenuBar", new Action(SmallIcon("show-menu"), tr("Show &Menubar"), coll,
382             0, 0, QKeySequence(Qt::CTRL + Qt::Key_M)))->setCheckable(true);
383
384     coll->addAction("ToggleStatusBar", new Action(tr("Show Status &Bar"), coll,
385             0, 0))->setCheckable(true);
386
387 #ifdef HAVE_KDE
388     QAction *fullScreenAct = KStandardAction::fullScreen(this, SLOT(onFullScreenToggled()), this, coll);
389 #else
390     QAction *fullScreenAct = new Action(SmallIcon("view-fullscreen"), tr("&Full Screen Mode"), coll,
391         this, SLOT(onFullScreenToggled()), QKeySequence(Qt::Key_F11));
392     fullScreenAct->setCheckable(true);
393 #endif
394     coll->addAction("ToggleFullScreen", fullScreenAct);
395
396     // Settings
397     QAction *configureShortcutsAct = new Action(SmallIcon("configure-shortcuts"), tr("Configure &Shortcuts..."), coll,
398         this, SLOT(showShortcutsDlg()));
399     configureShortcutsAct->setMenuRole(QAction::NoRole);
400     coll->addAction("ConfigureShortcuts", configureShortcutsAct);
401
402   #ifdef Q_WS_MAC
403     QAction *configureQuasselAct = new Action(SmallIcon("configure"), tr("&Configure Quassel..."), coll,
404         this, SLOT(showSettingsDlg()));
405     configureQuasselAct->setMenuRole(QAction::PreferencesRole);
406   #else
407     QAction *configureQuasselAct = new Action(SmallIcon("configure"), tr("&Configure Quassel..."), coll,
408         this, SLOT(showSettingsDlg()), QKeySequence(Qt::Key_F7));
409   #endif
410     coll->addAction("ConfigureQuassel", configureQuasselAct);
411
412     // Help
413     QAction *aboutQuasselAct = new Action(SmallIcon("quassel"), tr("&About Quassel"), coll,
414         this, SLOT(showAboutDlg()));
415     aboutQuasselAct->setMenuRole(QAction::AboutRole);
416     coll->addAction("AboutQuassel", aboutQuasselAct);
417
418     QAction *aboutQtAct = new Action(QIcon(":/pics/qt-logo.png"), tr("About &Qt"), coll,
419         qApp, SLOT(aboutQt()));
420     aboutQtAct->setMenuRole(QAction::AboutQtRole);
421     coll->addAction("AboutQt", aboutQtAct);
422     coll->addAction("DebugNetworkModel", new Action(SmallIcon("tools-report-bug"), tr("Debug &NetworkModel"), coll,
423             this, SLOT(on_actionDebugNetworkModel_triggered())));
424     coll->addAction("DebugBufferViewOverlay", new Action(SmallIcon("tools-report-bug"), tr("Debug &BufferViewOverlay"), coll,
425             this, SLOT(on_actionDebugBufferViewOverlay_triggered())));
426     coll->addAction("DebugMessageModel", new Action(SmallIcon("tools-report-bug"), tr("Debug &MessageModel"), coll,
427             this, SLOT(on_actionDebugMessageModel_triggered())));
428     coll->addAction("DebugHotList", new Action(SmallIcon("tools-report-bug"), tr("Debug &HotList"), coll,
429             this, SLOT(on_actionDebugHotList_triggered())));
430     coll->addAction("DebugLog", new Action(SmallIcon("tools-report-bug"), tr("Debug &Log"), coll,
431             this, SLOT(on_actionDebugLog_triggered())));
432     coll->addAction("ReloadStyle", new Action(SmallIcon("view-refresh"), tr("Reload Stylesheet"), coll,
433             QtUi::style(), SLOT(reload()), QKeySequence::Refresh));
434
435     coll->addAction("HideCurrentBuffer", new Action(tr("Hide Current Buffer"), coll,
436             this, SLOT(hideCurrentBuffer()), QKeySequence::Close));
437
438     // Navigation
439     coll = QtUi::actionCollection("Navigation", tr("Navigation"));
440
441     coll->addAction("JumpHotBuffer", new Action(tr("Jump to hot chat"), coll,
442             this, SLOT(on_jumpHotBuffer_triggered()), QKeySequence(Qt::META + Qt::Key_A)));
443
444     // Jump keys
445 #ifdef Q_WS_MAC
446     const int bindModifier = Qt::ControlModifier | Qt::AltModifier;
447     const int jumpModifier = Qt::ControlModifier;
448 #else
449     const int bindModifier = Qt::ControlModifier;
450     const int jumpModifier = Qt::AltModifier;
451 #endif
452
453     coll->addAction("BindJumpKey0", new Action(tr("Set Quick Access #0"), coll, this, SLOT(bindJumpKey()),
454             QKeySequence(bindModifier + Qt::Key_0)))->setProperty("Index", 0);
455     coll->addAction("BindJumpKey1", new Action(tr("Set Quick Access #1"), coll, this, SLOT(bindJumpKey()),
456             QKeySequence(bindModifier + Qt::Key_1)))->setProperty("Index", 1);
457     coll->addAction("BindJumpKey2", new Action(tr("Set Quick Access #2"), coll, this, SLOT(bindJumpKey()),
458             QKeySequence(bindModifier + Qt::Key_2)))->setProperty("Index", 2);
459     coll->addAction("BindJumpKey3", new Action(tr("Set Quick Access #3"), coll, this, SLOT(bindJumpKey()),
460             QKeySequence(bindModifier + Qt::Key_3)))->setProperty("Index", 3);
461     coll->addAction("BindJumpKey4", new Action(tr("Set Quick Access #4"), coll, this, SLOT(bindJumpKey()),
462             QKeySequence(bindModifier + Qt::Key_4)))->setProperty("Index", 4);
463     coll->addAction("BindJumpKey5", new Action(tr("Set Quick Access #5"), coll, this, SLOT(bindJumpKey()),
464             QKeySequence(bindModifier + Qt::Key_5)))->setProperty("Index", 5);
465     coll->addAction("BindJumpKey6", new Action(tr("Set Quick Access #6"), coll, this, SLOT(bindJumpKey()),
466             QKeySequence(bindModifier + Qt::Key_6)))->setProperty("Index", 6);
467     coll->addAction("BindJumpKey7", new Action(tr("Set Quick Access #7"), coll, this, SLOT(bindJumpKey()),
468             QKeySequence(bindModifier + Qt::Key_7)))->setProperty("Index", 7);
469     coll->addAction("BindJumpKey8", new Action(tr("Set Quick Access #8"), coll, this, SLOT(bindJumpKey()),
470             QKeySequence(bindModifier + Qt::Key_8)))->setProperty("Index", 8);
471     coll->addAction("BindJumpKey9", new Action(tr("Set Quick Access #9"), coll, this, SLOT(bindJumpKey()),
472             QKeySequence(bindModifier + Qt::Key_9)))->setProperty("Index", 9);
473
474     coll->addAction("JumpKey0", new Action(tr("Quick Access #0"), coll, this, SLOT(onJumpKey()),
475             QKeySequence(jumpModifier + Qt::Key_0)))->setProperty("Index", 0);
476     coll->addAction("JumpKey1", new Action(tr("Quick Access #1"), coll, this, SLOT(onJumpKey()),
477             QKeySequence(jumpModifier + Qt::Key_1)))->setProperty("Index", 1);
478     coll->addAction("JumpKey2", new Action(tr("Quick Access #2"), coll, this, SLOT(onJumpKey()),
479             QKeySequence(jumpModifier + Qt::Key_2)))->setProperty("Index", 2);
480     coll->addAction("JumpKey3", new Action(tr("Quick Access #3"), coll, this, SLOT(onJumpKey()),
481             QKeySequence(jumpModifier + Qt::Key_3)))->setProperty("Index", 3);
482     coll->addAction("JumpKey4", new Action(tr("Quick Access #4"), coll, this, SLOT(onJumpKey()),
483             QKeySequence(jumpModifier + Qt::Key_4)))->setProperty("Index", 4);
484     coll->addAction("JumpKey5", new Action(tr("Quick Access #5"), coll, this, SLOT(onJumpKey()),
485             QKeySequence(jumpModifier + Qt::Key_5)))->setProperty("Index", 5);
486     coll->addAction("JumpKey6", new Action(tr("Quick Access #6"), coll, this, SLOT(onJumpKey()),
487             QKeySequence(jumpModifier + Qt::Key_6)))->setProperty("Index", 6);
488     coll->addAction("JumpKey7", new Action(tr("Quick Access #7"), coll, this, SLOT(onJumpKey()),
489             QKeySequence(jumpModifier + Qt::Key_7)))->setProperty("Index", 7);
490     coll->addAction("JumpKey8", new Action(tr("Quick Access #8"), coll, this, SLOT(onJumpKey()),
491             QKeySequence(jumpModifier + Qt::Key_8)))->setProperty("Index", 8);
492     coll->addAction("JumpKey9", new Action(tr("Quick Access #9"), coll, this, SLOT(onJumpKey()),
493             QKeySequence(jumpModifier + Qt::Key_9)))->setProperty("Index", 9);
494
495     // Buffer navigation
496     coll->addAction("NextBufferView", new Action(SmallIcon("go-next-view"), tr("Activate Next Chat List"), coll,
497             this, SLOT(nextBufferView()), QKeySequence(QKeySequence::Forward)));
498     coll->addAction("PreviousBufferView", new Action(SmallIcon("go-previous-view"), tr("Activate Previous Chat List"), coll,
499             this, SLOT(previousBufferView()), QKeySequence::Back));
500     coll->addAction("NextBuffer", new Action(SmallIcon("go-down"), tr("Go to Next Chat"), coll,
501             this, SLOT(nextBuffer()), QKeySequence(Qt::ALT + Qt::Key_Down)));
502     coll->addAction("PreviousBuffer", new Action(SmallIcon("go-up"), tr("Go to Previous Chat"), coll,
503             this, SLOT(previousBuffer()), QKeySequence(Qt::ALT + Qt::Key_Up)));
504 }
505
506
507 void MainWin::setupMenus()
508 {
509     ActionCollection *coll = QtUi::actionCollection("General");
510
511     _fileMenu = menuBar()->addMenu(tr("&File"));
512
513     static const QStringList coreActions = QStringList()
514                                            << "ConnectCore" << "DisconnectCore" << "CoreInfo";
515
516     QAction *coreAction;
517     foreach(QString actionName, coreActions) {
518         coreAction = coll->action(actionName);
519         _fileMenu->addAction(coreAction);
520         flagRemoteCoreOnly(coreAction);
521     }
522     flagRemoteCoreOnly(_fileMenu->addSeparator());
523
524     _networksMenu = _fileMenu->addMenu(tr("&Networks"));
525     _networksMenu->addAction(coll->action("ConfigureNetworks"));
526     _networksMenu->addSeparator();
527     _fileMenu->addSeparator();
528     _fileMenu->addAction(coll->action("Quit"));
529
530     _viewMenu = menuBar()->addMenu(tr("&View"));
531     _bufferViewsMenu = _viewMenu->addMenu(tr("&Chat Lists"));
532     _bufferViewsMenu->addAction(coll->action("ConfigureBufferViews"));
533     _toolbarMenu = _viewMenu->addMenu(tr("&Toolbars"));
534     _viewMenu->addSeparator();
535
536     _viewMenu->addAction(coll->action("ToggleMenuBar"));
537     _viewMenu->addAction(coll->action("ToggleStatusBar"));
538     _viewMenu->addAction(coll->action("ToggleSearchBar"));
539
540     coreAction = coll->action("ShowAwayLog");
541     flagRemoteCoreOnly(coreAction);
542     _viewMenu->addAction(coreAction);
543
544     _viewMenu->addSeparator();
545     _viewMenu->addAction(coll->action("LockLayout"));
546
547     _settingsMenu = menuBar()->addMenu(tr("&Settings"));
548 #ifdef HAVE_KDE
549     _settingsMenu->addAction(KStandardAction::configureNotifications(this, SLOT(showNotificationsDlg()), this));
550     _settingsMenu->addAction(KStandardAction::keyBindings(this, SLOT(showShortcutsDlg()), this));
551 #else
552     _settingsMenu->addAction(coll->action("ConfigureShortcuts"));
553 #endif
554     _settingsMenu->addAction(coll->action("ConfigureQuassel"));
555
556     _helpMenu = menuBar()->addMenu(tr("&Help"));
557     _helpMenu->addAction(coll->action("AboutQuassel"));
558 #ifndef HAVE_KDE
559     _helpMenu->addAction(coll->action("AboutQt"));
560 #else
561     _helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, SLOT(aboutKDE()), this));
562 #endif
563     _helpMenu->addSeparator();
564     _helpDebugMenu = _helpMenu->addMenu(SmallIcon("tools-report-bug"), tr("Debug"));
565     _helpDebugMenu->addAction(coll->action("DebugNetworkModel"));
566     _helpDebugMenu->addAction(coll->action("DebugBufferViewOverlay"));
567     _helpDebugMenu->addAction(coll->action("DebugMessageModel"));
568     _helpDebugMenu->addAction(coll->action("DebugHotList"));
569     _helpDebugMenu->addAction(coll->action("DebugLog"));
570     _helpDebugMenu->addSeparator();
571     _helpDebugMenu->addAction(coll->action("ReloadStyle"));
572
573     // Toggle visibility
574     QAction *showMenuBar = QtUi::actionCollection("General")->action("ToggleMenuBar");
575
576     QtUiSettings uiSettings;
577     bool enabled = uiSettings.value("ShowMenuBar", QVariant(true)).toBool();
578     showMenuBar->setChecked(enabled);
579     enabled ? menuBar()->show() : menuBar()->hide();
580
581     connect(showMenuBar, SIGNAL(toggled(bool)), menuBar(), SLOT(setVisible(bool)));
582     connect(showMenuBar, SIGNAL(toggled(bool)), this, SLOT(saveMenuBarStatus(bool)));
583 }
584
585
586 void MainWin::setupBufferWidget()
587 {
588     _bufferWidget = new BufferWidget(this);
589     _bufferWidget->setModel(Client::bufferModel());
590     _bufferWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
591     setCentralWidget(_bufferWidget);
592 }
593
594
595 void MainWin::addBufferView(int bufferViewConfigId)
596 {
597     addBufferView(Client::bufferViewManager()->clientBufferViewConfig(bufferViewConfigId));
598 }
599
600
601 void MainWin::addBufferView(ClientBufferViewConfig *config)
602 {
603     if (!config)
604         return;
605
606     config->setLocked(QtUiSettings().value("LockLayout", false).toBool());
607     BufferViewDock *dock = new BufferViewDock(config, this);
608
609     //create the view and initialize it's filter
610     BufferView *view = new BufferView(dock);
611     view->setFilteredModel(Client::bufferModel(), config);
612     view->installEventFilter(_inputWidget); // for key presses
613
614     Client::bufferModel()->synchronizeView(view);
615
616     dock->setWidget(view);
617     dock->setVisible(_layoutLoaded); // don't show before state has been restored
618
619     addDockWidget(Qt::LeftDockWidgetArea, dock);
620     _bufferViewsMenu->addAction(dock->toggleViewAction());
621
622     connect(dock->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(bufferViewToggled(bool)));
623     connect(dock, SIGNAL(visibilityChanged(bool)), SLOT(bufferViewVisibilityChanged(bool)));
624     _bufferViews.append(dock);
625
626     if (!activeBufferView())
627         nextBufferView();
628 }
629
630
631 void MainWin::removeBufferView(int bufferViewConfigId)
632 {
633     QVariant actionData;
634     BufferViewDock *dock;
635     foreach(QAction *action, _bufferViewsMenu->actions()) {
636         actionData = action->data();
637         if (!actionData.isValid())
638             continue;
639
640         dock = qobject_cast<BufferViewDock *>(action->parent());
641         if (dock && actionData.toInt() == bufferViewConfigId) {
642             removeAction(action);
643             Client::bufferViewOverlay()->removeView(dock->bufferViewId());
644             _bufferViews.removeAll(dock);
645
646             if (dock->isActive()) {
647                 dock->setActive(false);
648                 _activeBufferViewIndex = -1;
649                 nextBufferView();
650             }
651
652             dock->deleteLater();
653         }
654     }
655 }
656
657
658 void MainWin::bufferViewToggled(bool enabled)
659 {
660     if (!enabled && !isMinimized()) {
661         // hiding the mainwindow triggers a toggle of the bufferview (which pretty much sucks big time)
662         // since this isn't our fault and we can't do anything about it, we suppress the resulting calls
663         return;
664     }
665     QAction *action = qobject_cast<QAction *>(sender());
666     Q_ASSERT(action);
667     BufferViewDock *dock = qobject_cast<BufferViewDock *>(action->parent());
668     Q_ASSERT(dock);
669
670     // Make sure we don't toggle backlog fetch for a view we've already removed
671     if (!_bufferViews.contains(dock))
672         return;
673
674     if (enabled)
675         Client::bufferViewOverlay()->addView(dock->bufferViewId());
676     else
677         Client::bufferViewOverlay()->removeView(dock->bufferViewId());
678 }
679
680
681 void MainWin::bufferViewVisibilityChanged(bool visible)
682 {
683     Q_UNUSED(visible);
684     BufferViewDock *dock = qobject_cast<BufferViewDock *>(sender());
685     Q_ASSERT(dock);
686     if ((!dock->isHidden() && !activeBufferView()) || (dock->isHidden() && dock->isActive()))
687         nextBufferView();
688 }
689
690
691 BufferView *MainWin::allBuffersView() const
692 {
693     // "All Buffers" is always the first dock created
694     if (_bufferViews.count() > 0)
695         return _bufferViews[0]->bufferView();
696     return 0;
697 }
698
699
700 BufferView *MainWin::activeBufferView() const
701 {
702     if (_activeBufferViewIndex < 0 || _activeBufferViewIndex >= _bufferViews.count())
703         return 0;
704     BufferViewDock *dock = _bufferViews.at(_activeBufferViewIndex);
705     return dock->isActive() ? qobject_cast<BufferView *>(dock->widget()) : 0;
706 }
707
708
709 void MainWin::changeActiveBufferView(int bufferViewId)
710 {
711     if (bufferViewId < 0)
712         return;
713
714     BufferView *current = activeBufferView();
715     if (current) {
716         qobject_cast<BufferViewDock *>(current->parent())->setActive(false);
717         _activeBufferViewIndex = -1;
718     }
719
720     for (int i = 0; i < _bufferViews.count(); i++) {
721         BufferViewDock *dock = _bufferViews.at(i);
722         if (dock->bufferViewId() == bufferViewId && !dock->isHidden()) {
723             _activeBufferViewIndex = i;
724             dock->setActive(true);
725             return;
726         }
727     }
728
729     nextBufferView(); // fallback
730 }
731
732
733 void MainWin::changeActiveBufferView(bool backwards)
734 {
735     BufferView *current = activeBufferView();
736     if (current)
737         qobject_cast<BufferViewDock *>(current->parent())->setActive(false);
738
739     if (!_bufferViews.count())
740         return;
741
742     int c = _bufferViews.count();
743     while (c--) { // yes, this will reactivate the current active one if all others fail
744         if (backwards) {
745             if (--_activeBufferViewIndex < 0)
746                 _activeBufferViewIndex = _bufferViews.count()-1;
747         }
748         else {
749             if (++_activeBufferViewIndex >= _bufferViews.count())
750                 _activeBufferViewIndex = 0;
751         }
752
753         BufferViewDock *dock = _bufferViews.at(_activeBufferViewIndex);
754         if (dock->isHidden())
755             continue;
756
757         dock->setActive(true);
758         return;
759     }
760
761     _activeBufferViewIndex = -1;
762 }
763
764
765 void MainWin::nextBufferView()
766 {
767     changeActiveBufferView(false);
768 }
769
770
771 void MainWin::previousBufferView()
772 {
773     changeActiveBufferView(true);
774 }
775
776
777 void MainWin::nextBuffer()
778 {
779     BufferView *view = activeBufferView();
780     if (view)
781         view->nextBuffer();
782 }
783
784
785 void MainWin::previousBuffer()
786 {
787     BufferView *view = activeBufferView();
788     if (view)
789         view->previousBuffer();
790 }
791
792
793 void MainWin::hideCurrentBuffer()
794 {
795     BufferView *view = activeBufferView();
796     if (view)
797         view->hideCurrentBuffer();
798 }
799
800
801 void MainWin::showNotificationsDlg()
802 {
803     SettingsPageDlg dlg(new NotificationsSettingsPage(this), this);
804     dlg.exec();
805 }
806
807
808 void MainWin::on_actionConfigureNetworks_triggered()
809 {
810     SettingsPageDlg dlg(new NetworksSettingsPage(this), this);
811     dlg.exec();
812 }
813
814
815 void MainWin::on_actionConfigureViews_triggered()
816 {
817     SettingsPageDlg dlg(new BufferViewSettingsPage(this), this);
818     dlg.exec();
819 }
820
821
822 void MainWin::on_actionLockLayout_toggled(bool lock)
823 {
824     QList<VerticalDock *> docks = findChildren<VerticalDock *>();
825     foreach(VerticalDock *dock, docks) {
826         dock->showTitle(!lock);
827     }
828     if (Client::bufferViewManager()) {
829         foreach(ClientBufferViewConfig *config, Client::bufferViewManager()->clientBufferViewConfigs()) {
830             config->setLocked(lock);
831         }
832     }
833     QtUiSettings().setValue("LockLayout", lock);
834 }
835
836
837 void MainWin::setupNickWidget()
838 {
839     // create nick dock
840     NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
841     nickDock->setObjectName("NickDock");
842     nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
843
844     _nickListWidget = new NickListWidget(nickDock);
845     nickDock->setWidget(_nickListWidget);
846
847     addDockWidget(Qt::RightDockWidgetArea, nickDock);
848     _viewMenu->addAction(nickDock->toggleViewAction());
849     nickDock->toggleViewAction()->setText(tr("Show Nick List"));
850
851     // See NickListDock::NickListDock();
852     // connect(nickDock->toggleViewAction(), SIGNAL(triggered(bool)), nickListWidget, SLOT(showWidget(bool)));
853
854     // attach the NickListWidget to the BufferModel and the default selection
855     _nickListWidget->setModel(Client::bufferModel());
856     _nickListWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
857 }
858
859
860 void MainWin::setupChatMonitor()
861 {
862     VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
863     dock->setObjectName("ChatMonitorDock");
864
865     ChatMonitorFilter *filter = new ChatMonitorFilter(Client::messageModel(), this);
866     _chatMonitorView = new ChatMonitorView(filter, this);
867     _chatMonitorView->setFocusProxy(_inputWidget);
868     _chatMonitorView->show();
869     dock->setWidget(_chatMonitorView);
870     dock->hide();
871
872     addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
873     _viewMenu->addAction(dock->toggleViewAction());
874     dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
875 }
876
877
878 void MainWin::setupInputWidget()
879 {
880     VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
881     dock->setObjectName("InputDock");
882
883     _inputWidget = new InputWidget(dock);
884     dock->setWidget(_inputWidget);
885
886     addDockWidget(Qt::BottomDockWidgetArea, dock);
887
888     _viewMenu->addAction(dock->toggleViewAction());
889     dock->toggleViewAction()->setText(tr("Show Input Line"));
890
891     _inputWidget->setModel(Client::bufferModel());
892     _inputWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
893
894     _bufferWidget->setFocusProxy(_inputWidget);
895
896     _inputWidget->inputLine()->installEventFilter(_bufferWidget);
897
898     connect(_topicWidget, SIGNAL(switchedPlain()), _bufferWidget, SLOT(setFocus()));
899 }
900
901
902 void MainWin::setupTopicWidget()
903 {
904     VerticalDock *dock = new VerticalDock(tr("Topic"), this);
905     dock->setObjectName("TopicDock");
906     _topicWidget = new TopicWidget(dock);
907
908     dock->setWidget(_topicWidget);
909
910     _topicWidget->setModel(Client::bufferModel());
911     _topicWidget->setSelectionModel(Client::bufferModel()->standardSelectionModel());
912
913     addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
914
915     _viewMenu->addAction(dock->toggleViewAction());
916     dock->toggleViewAction()->setText(tr("Show Topic Line"));
917 }
918
919
920 void MainWin::setupViewMenuTail()
921 {
922     _viewMenu->addSeparator();
923     _viewMenu->addAction(QtUi::actionCollection("General")->action("ToggleFullScreen"));
924 }
925
926
927 void MainWin::setupTitleSetter()
928 {
929     _titleSetter.setModel(Client::bufferModel());
930     _titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
931 }
932
933
934 void MainWin::setupStatusBar()
935 {
936     // MessageProcessor progress
937     statusBar()->addPermanentWidget(_msgProcessorStatusWidget);
938
939     // Connection state
940     _coreConnectionStatusWidget->update();
941     statusBar()->addPermanentWidget(_coreConnectionStatusWidget);
942
943     QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
944
945     QtUiSettings uiSettings;
946
947     bool enabled = uiSettings.value("ShowStatusBar", QVariant(true)).toBool();
948     showStatusbar->setChecked(enabled);
949     enabled ? statusBar()->show() : statusBar()->hide();
950
951     connect(showStatusbar, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
952     connect(showStatusbar, SIGNAL(toggled(bool)), this, SLOT(saveStatusBarStatus(bool)));
953
954     connect(Client::coreConnection(), SIGNAL(connectionMsg(QString)), statusBar(), SLOT(showMessage(QString)));
955 }
956
957
958 void MainWin::setupHotList()
959 {
960     FlatProxyModel *flatProxy = new FlatProxyModel(this);
961     flatProxy->setSourceModel(Client::bufferModel());
962     _bufferHotList = new BufferHotListFilter(flatProxy);
963 }
964
965
966 void MainWin::saveMenuBarStatus(bool enabled)
967 {
968     QtUiSettings uiSettings;
969     uiSettings.setValue("ShowMenuBar", enabled);
970 }
971
972
973 void MainWin::saveStatusBarStatus(bool enabled)
974 {
975     QtUiSettings uiSettings;
976     uiSettings.setValue("ShowStatusBar", enabled);
977 }
978
979
980 void MainWin::setupSystray()
981 {
982 #ifdef HAVE_DBUS
983     _systemTray = new StatusNotifierItem(this);
984 #elif !defined QT_NO_SYSTEMTRAYICON
985     _systemTray = new LegacySystemTray(this);
986 #else
987     _systemTray = new SystemTray(this); // dummy
988 #endif
989     _systemTray->init();
990 }
991
992
993 void MainWin::setupToolBars()
994 {
995     connect(_bufferWidget, SIGNAL(currentChanged(QModelIndex)),
996         QtUi::toolBarActionProvider(), SLOT(currentBufferChanged(QModelIndex)));
997     connect(_nickListWidget, SIGNAL(nickSelectionChanged(QModelIndexList)),
998         QtUi::toolBarActionProvider(), SLOT(nickSelectionChanged(QModelIndexList)));
999
1000 #ifdef Q_WS_MAC
1001     setUnifiedTitleAndToolBarOnMac(true);
1002 #endif
1003
1004 #ifdef HAVE_KDE
1005     _mainToolBar = new KToolBar("MainToolBar", this, Qt::TopToolBarArea, false, true, true);
1006 #else
1007     _mainToolBar = new QToolBar(this);
1008     _mainToolBar->setObjectName("MainToolBar");
1009 #endif
1010     _mainToolBar->setWindowTitle(tr("Main Toolbar"));
1011     addToolBar(_mainToolBar);
1012
1013     QtUi::toolBarActionProvider()->addActions(_mainToolBar, ToolBarActionProvider::MainToolBar);
1014     _toolbarMenu->addAction(_mainToolBar->toggleViewAction());
1015
1016 #ifdef Q_WS_MAC
1017     QtUiSettings uiSettings;
1018
1019     bool visible = uiSettings.value("ShowMainToolBar", QVariant(true)).toBool();
1020     _mainToolBar->setVisible(visible);
1021     connect(_mainToolBar, SIGNAL(visibilityChanged(bool)), this, SLOT(saveMainToolBarStatus(bool)));
1022 #endif
1023 }
1024
1025 #ifdef Q_WS_MAC
1026 void MainWin::saveMainToolBarStatus(bool enabled)
1027 {
1028     QtUiSettings uiSettings;
1029     uiSettings.setValue("ShowMainToolBar", enabled);
1030 }
1031 #endif
1032
1033
1034 void MainWin::connectedToCore()
1035 {
1036     Q_CHECK_PTR(Client::bufferViewManager());
1037     connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
1038     connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
1039     connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
1040
1041     setConnectedState();
1042 }
1043
1044
1045 void MainWin::setConnectedState()
1046 {
1047     ActionCollection *coll = QtUi::actionCollection("General");
1048
1049     coll->action("ConnectCore")->setEnabled(false);
1050     coll->action("DisconnectCore")->setEnabled(true);
1051     coll->action("CoreInfo")->setEnabled(true);
1052
1053     foreach(QAction *action, _fileMenu->actions()) {
1054         if (isRemoteCoreOnly(action))
1055             action->setVisible(!Client::internalCore());
1056     }
1057
1058     disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
1059     disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1060     disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1061     if (!Client::internalCore()) {
1062         connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
1063         connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1064         connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1065     }
1066
1067     // _viewMenu->setEnabled(true);
1068     if (!Client::internalCore())
1069         statusBar()->showMessage(tr("Connected to core."));
1070     else
1071         statusBar()->clearMessage();
1072
1073     _coreConnectionStatusWidget->setVisible(!Client::internalCore());
1074     updateIcon();
1075     systemTray()->setState(SystemTray::Active);
1076
1077     if (Client::networkIds().isEmpty()) {
1078         IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
1079         wizard->show();
1080     }
1081     else {
1082         // Monolithic always preselects last used buffer - Client only if the connection died
1083         if (Client::coreConnection()->wasReconnect() || Quassel::runMode() == Quassel::Monolithic) {
1084             QtUiSettings s;
1085             BufferId lastUsedBufferId(s.value("LastUsedBufferId").toInt());
1086             if (lastUsedBufferId.isValid())
1087                 Client::bufferModel()->switchToBuffer(lastUsedBufferId);
1088         }
1089     }
1090 }
1091
1092
1093 void MainWin::loadLayout()
1094 {
1095     QtUiSettings s;
1096     int accountId = Client::currentCoreAccount().accountId().toInt();
1097     QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
1098     if (state.isEmpty()) {
1099         foreach(BufferViewDock *view, _bufferViews)
1100         view->show();
1101         _layoutLoaded = true;
1102         return;
1103     }
1104
1105     restoreState(state, accountId);
1106     int bufferViewId = s.value(QString("ActiveBufferView-%1").arg(accountId), -1).toInt();
1107     if (bufferViewId >= 0)
1108         changeActiveBufferView(bufferViewId);
1109
1110     _layoutLoaded = true;
1111 }
1112
1113
1114 void MainWin::saveLayout()
1115 {
1116     QtUiSettings s;
1117     int accountId = _bufferViews.count() ? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
1118     if (accountId > 0) {
1119         s.setValue(QString("MainWinState-%1").arg(accountId), saveState(accountId));
1120         BufferView *view = activeBufferView();
1121         s.setValue(QString("ActiveBufferView-%1").arg(accountId), view ? view->config()->bufferViewId() : -1);
1122     }
1123 }
1124
1125
1126 void MainWin::disconnectedFromCore()
1127 {
1128     // save core specific layout and remove bufferviews;
1129     saveLayout();
1130     _layoutLoaded = false;
1131
1132     QVariant actionData;
1133     BufferViewDock *dock;
1134     foreach(QAction *action, _bufferViewsMenu->actions()) {
1135         actionData = action->data();
1136         if (!actionData.isValid())
1137             continue;
1138
1139         dock = qobject_cast<BufferViewDock *>(action->parent());
1140         if (dock && actionData.toInt() != -1) {
1141             removeAction(action);
1142             _bufferViews.removeAll(dock);
1143             dock->deleteLater();
1144         }
1145     }
1146
1147     // store last active buffer
1148     QtUiSettings s;
1149     BufferId lastBufId = _bufferWidget->currentBuffer();
1150     if (lastBufId.isValid()) {
1151         s.setValue("LastUsedBufferId", lastBufId.toInt());
1152         // clear the current selection
1153         Client::bufferModel()->standardSelectionModel()->clearSelection();
1154     }
1155     restoreState(s.value("MainWinState").toByteArray());
1156     setDisconnectedState();
1157 }
1158
1159
1160 void MainWin::setDisconnectedState()
1161 {
1162     ActionCollection *coll = QtUi::actionCollection("General");
1163     //ui.menuCore->setEnabled(false);
1164     coll->action("ConnectCore")->setEnabled(true);
1165     coll->action("DisconnectCore")->setEnabled(false);
1166     coll->action("CoreInfo")->setEnabled(false);
1167     //_viewMenu->setEnabled(false);
1168     statusBar()->showMessage(tr("Not connected to core."));
1169     if (_msgProcessorStatusWidget)
1170         _msgProcessorStatusWidget->setProgress(0, 0);
1171     updateIcon();
1172     systemTray()->setState(SystemTray::Passive);
1173 }
1174
1175
1176 void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage)
1177 {
1178     Q_UNUSED(errorMessage)
1179     CoreConnectAuthDlg dlg(account, this);
1180     *valid = (dlg.exec() == QDialog::Accepted);
1181 }
1182
1183
1184 void MainWin::handleNoSslInClient(bool *accepted)
1185 {
1186     QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
1187         QMessageBox::Ignore|QMessageBox::Cancel, this);
1188     box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
1189     box.setDefaultButton(QMessageBox::Ignore);
1190     *accepted = box.exec() == QMessageBox::Ignore;
1191 }
1192
1193
1194 void MainWin::handleNoSslInCore(bool *accepted)
1195 {
1196     QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
1197         QMessageBox::Ignore|QMessageBox::Cancel, this);
1198     box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
1199     box.setDefaultButton(QMessageBox::Ignore);
1200     *accepted = box.exec() == QMessageBox::Ignore;
1201 }
1202
1203
1204 #ifdef HAVE_SSL
1205
1206 void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently)
1207 {
1208     QString errorString = "<ul>";
1209     foreach(const QSslError error, socket->sslErrors())
1210     errorString += QString("<li>%1</li>").arg(error.errorString());
1211     errorString += "</ul>";
1212
1213     QMessageBox box(QMessageBox::Warning,
1214         tr("Untrusted Security Certificate"),
1215         tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
1216         QMessageBox::Cancel, this);
1217     box.setInformativeText(errorString);
1218     box.addButton(tr("Continue"), QMessageBox::AcceptRole);
1219     box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
1220
1221     QMessageBox::ButtonRole role;
1222     do {
1223         box.exec();
1224         role = box.buttonRole(box.clickedButton());
1225         if (role == QMessageBox::HelpRole) {
1226             SslInfoDlg dlg(socket, this);
1227             dlg.exec();
1228         }
1229     }
1230     while (role == QMessageBox::HelpRole);
1231
1232     *accepted = role == QMessageBox::AcceptRole;
1233     if (*accepted) {
1234         QMessageBox box2(QMessageBox::Warning,
1235             tr("Untrusted Security Certificate"),
1236             tr("Would you like to accept this certificate forever without being prompted?"),
1237             0, this);
1238         box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
1239         box2.addButton(tr("Forever"), QMessageBox::YesRole);
1240         box2.exec();
1241         *permanently =  box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
1242     }
1243 }
1244
1245
1246 #endif /* HAVE_SSL */
1247
1248 void MainWin::handleCoreConnectionError(const QString &error)
1249 {
1250     QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
1251 }
1252
1253
1254 void MainWin::showCoreConnectionDlg()
1255 {
1256     CoreConnectDlg dlg(this);
1257     if (dlg.exec() == QDialog::Accepted) {
1258         AccountId accId = dlg.selectedAccount();
1259         if (accId.isValid())
1260             Client::coreConnection()->connectToCore(accId);
1261     }
1262 }
1263
1264
1265 void MainWin::showCoreConfigWizard(const QVariantList &backends)
1266 {
1267     CoreConfigWizard *wizard = new CoreConfigWizard(Client::coreConnection(), backends, this);
1268
1269     wizard->show();
1270 }
1271
1272
1273 void MainWin::showChannelList(NetworkId netId)
1274 {
1275     ChannelListDlg *channelListDlg = new ChannelListDlg();
1276
1277     if (!netId.isValid()) {
1278         QAction *action = qobject_cast<QAction *>(sender());
1279         if (action)
1280             netId = action->data().value<NetworkId>();
1281     }
1282
1283     channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
1284     channelListDlg->setNetwork(netId);
1285     channelListDlg->show();
1286 }
1287
1288
1289 void MainWin::showIgnoreList(QString newRule)
1290 {
1291     SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
1292     // prepare config dialog for new rule
1293     if (!newRule.isEmpty())
1294         qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
1295     dlg.exec();
1296 }
1297
1298
1299 void MainWin::showCoreInfoDlg()
1300 {
1301     CoreInfoDlg(this).exec();
1302 }
1303
1304
1305 void MainWin::showAwayLog()
1306 {
1307     if (_awayLog)
1308         return;
1309     AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
1310     _awayLog = new AwayLogView(filter, 0);
1311     filter->setParent(_awayLog);
1312     connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
1313     _awayLog->setAttribute(Qt::WA_DeleteOnClose);
1314     _awayLog->show();
1315 }
1316
1317
1318 void MainWin::awayLogDestroyed()
1319 {
1320     _awayLog = 0;
1321 }
1322
1323
1324 void MainWin::showSettingsDlg()
1325 {
1326     SettingsDlg *dlg = new SettingsDlg();
1327
1328     //Category: Interface
1329     dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
1330     dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
1331     dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
1332     dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
1333     dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
1334     dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
1335     dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
1336     dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
1337     dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
1338     dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
1339
1340     //Category: IRC
1341     dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
1342     dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
1343     dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
1344     dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
1345     dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
1346
1347     // Category: Remote Cores
1348     if (Quassel::runMode() != Quassel::Monolithic) {
1349         dlg->registerSettingsPage(new CoreAccountSettingsPage(dlg));
1350         dlg->registerSettingsPage(new CoreConnectionSettingsPage(dlg));
1351     }
1352
1353     dlg->show();
1354 }
1355
1356
1357 void MainWin::showAboutDlg()
1358 {
1359     AboutDlg(this).exec();
1360 }
1361
1362
1363 void MainWin::showShortcutsDlg()
1364 {
1365 #ifdef HAVE_KDE
1366     KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed, this);
1367     foreach(KActionCollection *coll, QtUi::actionCollections())
1368     dlg.addCollection(coll, coll->property("Category").toString());
1369     dlg.exec();
1370 #else
1371     SettingsPageDlg dlg(new ShortcutsSettingsPage(QtUi::actionCollections(), this), this);
1372     dlg.exec();
1373 #endif
1374 }
1375
1376
1377 void MainWin::onFullScreenToggled()
1378 {
1379     // Relying on QWidget::isFullScreen is discouraged, see the KToggleFullScreenAction docs
1380     // Also, one should not use showFullScreen() or showNormal(), as those reset all other window flags
1381
1382     QAction *action = QtUi::actionCollection("General")->action("ToggleFullScreen");
1383     if (!action)
1384         return;
1385
1386 #ifdef HAVE_KDE
1387     KToggleFullScreenAction *kAct = static_cast<KToggleFullScreenAction *>(action);
1388     kAct->setFullScreen(this, kAct->isChecked());
1389 #else
1390     if (action->isChecked())
1391         setWindowState(windowState() | Qt::WindowFullScreen);
1392     else
1393         setWindowState(windowState() & ~Qt::WindowFullScreen);
1394 #endif
1395 }
1396
1397
1398 /********************************************************************************************************/
1399
1400 bool MainWin::event(QEvent *event)
1401 {
1402     switch(event->type()) {
1403     case QEvent::WindowActivate: {
1404         BufferId bufferId = Client::bufferModel()->currentBuffer();
1405         if (bufferId.isValid())
1406             Client::instance()->markBufferAsRead(bufferId);
1407         break;
1408     }
1409     case QEvent::WindowDeactivate:
1410         if (bufferWidget()->autoMarkerLineOnLostFocus())
1411             bufferWidget()->setMarkerLine();
1412         break;
1413     default:
1414         break;
1415     }
1416     return QMainWindow::event(event);
1417 }
1418
1419
1420 void MainWin::moveEvent(QMoveEvent *event)
1421 {
1422     if (!(windowState() & Qt::WindowMaximized))
1423         _normalPos = event->pos();
1424
1425     QMainWindow::moveEvent(event);
1426 }
1427
1428
1429 void MainWin::resizeEvent(QResizeEvent *event)
1430 {
1431     if (!(windowState() & Qt::WindowMaximized))
1432         _normalSize = event->size();
1433
1434     QMainWindow::resizeEvent(event);
1435 }
1436
1437
1438 void MainWin::closeEvent(QCloseEvent *event)
1439 {
1440     QtUiSettings s;
1441     QtUiApplication *app = qobject_cast<QtUiApplication *> qApp;
1442     Q_ASSERT(app);
1443     if (!app->isAboutToQuit() && QtUi::haveSystemTray() && s.value("MinimizeOnClose").toBool()) {
1444         QtUi::hideMainWidget();
1445         event->ignore();
1446     }
1447     else {
1448         event->accept();
1449         quit();
1450     }
1451 }
1452
1453
1454 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end)
1455 {
1456     Q_UNUSED(parent);
1457
1458     bool hasFocus = QApplication::activeWindow() != 0;
1459
1460     for (int i = start; i <= end; i++) {
1461         QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1462         if (!idx.isValid()) {
1463             qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1464             continue;
1465         }
1466         Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1467         if (flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1468             continue;
1469
1470         BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1471         BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1472
1473         // check if bufferId belongs to the shown chatlists
1474         if (!(Client::bufferViewOverlay()->bufferIds().contains(bufId) ||
1475               Client::bufferViewOverlay()->tempRemovedBufferIds().contains(bufId)))
1476             continue;
1477
1478         // check if it's the buffer currently displayed
1479         if (hasFocus && bufId == Client::bufferModel()->currentBuffer())
1480             continue;
1481
1482         // only show notifications for higlights or queries
1483         if (bufType != BufferInfo::QueryBuffer && !(flags & Message::Highlight))
1484             continue;
1485
1486         // and of course: don't notify for ignored messages
1487         if (Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(), Client::networkModel()->networkName(bufId)))
1488             continue;
1489
1490         // seems like we have a legit notification candidate!
1491         QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1492         QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1493         QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1494         AbstractNotificationBackend::NotificationType type;
1495
1496         if (bufType == BufferInfo::QueryBuffer && !hasFocus)
1497             type = AbstractNotificationBackend::PrivMsg;
1498         else if (bufType == BufferInfo::QueryBuffer && hasFocus)
1499             type = AbstractNotificationBackend::PrivMsgFocused;
1500         else if (flags & Message::Highlight && !hasFocus)
1501             type = AbstractNotificationBackend::Highlight;
1502         else
1503             type = AbstractNotificationBackend::HighlightFocused;
1504
1505         QtUi::instance()->invokeNotification(bufId, type, sender, contents);
1506     }
1507 }
1508
1509
1510 void MainWin::currentBufferChanged(BufferId buffer)
1511 {
1512     if (buffer.isValid())
1513         Client::instance()->markBufferAsRead(buffer);
1514 }
1515
1516
1517 void MainWin::clientNetworkCreated(NetworkId id)
1518 {
1519     const Network *net = Client::network(id);
1520     QAction *act = new QAction(net->networkName(), this);
1521     act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1522     act->setData(QVariant::fromValue<NetworkId>(id));
1523     connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1524     connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1525
1526     QAction *beforeAction = 0;
1527     foreach(QAction *action, _networksMenu->actions()) {
1528         if (!action->data().isValid()) // ignore stock actions
1529             continue;
1530         if (net->networkName().localeAwareCompare(action->text()) < 0) {
1531             beforeAction = action;
1532             break;
1533         }
1534     }
1535     _networksMenu->insertAction(beforeAction, act);
1536 }
1537
1538
1539 void MainWin::clientNetworkUpdated()
1540 {
1541     const Network *net = qobject_cast<const Network *>(sender());
1542     if (!net)
1543         return;
1544
1545     QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1546     if (!action)
1547         return;
1548
1549     action->setText(net->networkName());
1550
1551     switch (net->connectionState()) {
1552     case Network::Initialized:
1553         action->setIcon(SmallIcon("network-connect"));
1554         // if we have no currently selected buffer, jump to the first connecting statusbuffer
1555         if (!bufferWidget()->currentBuffer().isValid()) {
1556             QModelIndex idx = Client::networkModel()->networkIndex(net->networkId());
1557             if (idx.isValid()) {
1558                 BufferId statusBufferId = idx.data(NetworkModel::BufferIdRole).value<BufferId>();
1559                 Client::bufferModel()->switchToBuffer(statusBufferId);
1560             }
1561         }
1562         break;
1563     case Network::Disconnected:
1564         action->setIcon(SmallIcon("network-disconnect"));
1565         break;
1566     default:
1567         action->setIcon(SmallIcon("network-wired"));
1568     }
1569 }
1570
1571
1572 void MainWin::clientNetworkRemoved(NetworkId id)
1573 {
1574     QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1575     if (!action)
1576         return;
1577
1578     action->deleteLater();
1579 }
1580
1581
1582 void MainWin::connectOrDisconnectFromNet()
1583 {
1584     QAction *act = qobject_cast<QAction *>(sender());
1585     if (!act) return;
1586     const Network *net = Client::network(act->data().value<NetworkId>());
1587     if (!net) return;
1588     if (net->connectionState() == Network::Disconnected) net->requestConnect();
1589     else net->requestDisconnect();
1590 }
1591
1592
1593 void MainWin::on_jumpHotBuffer_triggered()
1594 {
1595     if (!_bufferHotList->rowCount())
1596         return;
1597
1598     QModelIndex topIndex = _bufferHotList->index(0, 0);
1599     BufferId bufferId = _bufferHotList->data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
1600     Client::bufferModel()->switchToBuffer(bufferId);
1601 }
1602
1603
1604 void MainWin::onJumpKey()
1605 {
1606     QAction *action = qobject_cast<QAction *>(sender());
1607     if (!action || !Client::bufferModel())
1608         return;
1609     int idx = action->property("Index").toInt();
1610
1611     if (_jumpKeyMap.isEmpty())
1612         _jumpKeyMap = CoreAccountSettings().jumpKeyMap();
1613
1614     if (!_jumpKeyMap.contains(idx))
1615         return;
1616
1617     BufferId buffer = _jumpKeyMap.value(idx);
1618     if (buffer.isValid())
1619         Client::bufferModel()->switchToBuffer(buffer);
1620 }
1621
1622
1623 void MainWin::bindJumpKey()
1624 {
1625     QAction *action = qobject_cast<QAction *>(sender());
1626     if (!action || !Client::bufferModel())
1627         return;
1628     int idx = action->property("Index").toInt();
1629
1630     _jumpKeyMap[idx] = Client::bufferModel()->currentBuffer();
1631     CoreAccountSettings().setJumpKeyMap(_jumpKeyMap);
1632 }
1633
1634
1635 void MainWin::on_actionDebugNetworkModel_triggered()
1636 {
1637     QTreeView *view = new QTreeView;
1638     view->setAttribute(Qt::WA_DeleteOnClose);
1639     view->setWindowTitle("Debug NetworkModel View");
1640     view->setModel(Client::networkModel());
1641     view->setColumnWidth(0, 250);
1642     view->setColumnWidth(1, 250);
1643     view->setColumnWidth(2, 80);
1644     view->resize(610, 300);
1645     view->show();
1646 }
1647
1648
1649 void MainWin::on_actionDebugHotList_triggered()
1650 {
1651     QTreeView *view = new QTreeView;
1652     view->setAttribute(Qt::WA_DeleteOnClose);
1653     view->setModel(_bufferHotList);
1654     view->show();
1655 }
1656
1657
1658 void MainWin::on_actionDebugBufferViewOverlay_triggered()
1659 {
1660     DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1661     overlay->setAttribute(Qt::WA_DeleteOnClose);
1662     overlay->show();
1663 }
1664
1665
1666 void MainWin::on_actionDebugMessageModel_triggered()
1667 {
1668     QTableView *view = new QTableView(0);
1669     DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1670     filter->setSourceModel(Client::messageModel());
1671     view->setModel(filter);
1672     view->setAttribute(Qt::WA_DeleteOnClose, true);
1673     view->verticalHeader()->hide();
1674     view->horizontalHeader()->setStretchLastSection(true);
1675     view->show();
1676 }
1677
1678
1679 void MainWin::on_actionDebugLog_triggered()
1680 {
1681     DebugLogWidget *logWidget = new DebugLogWidget(0);
1682     logWidget->show();
1683 }
1684
1685
1686 void MainWin::showStatusBarMessage(const QString &message)
1687 {
1688     statusBar()->showMessage(message, 10000);
1689 }