fix buffer sorting for hot buffer hotkey
[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 void MainWin::saveMainToolBarStatus(bool enabled)
1026 {
1027 #ifdef Q_OS_MAC
1028     QtUiSettings uiSettings;
1029     uiSettings.setValue("ShowMainToolBar", enabled);
1030 #else
1031     Q_UNUSED(enabled);
1032 #endif
1033 }
1034
1035
1036 void MainWin::connectedToCore()
1037 {
1038     Q_CHECK_PTR(Client::bufferViewManager());
1039     connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigAdded(int)), this, SLOT(addBufferView(int)));
1040     connect(Client::bufferViewManager(), SIGNAL(bufferViewConfigDeleted(int)), this, SLOT(removeBufferView(int)));
1041     connect(Client::bufferViewManager(), SIGNAL(initDone()), this, SLOT(loadLayout()));
1042
1043     setConnectedState();
1044 }
1045
1046
1047 void MainWin::setConnectedState()
1048 {
1049     ActionCollection *coll = QtUi::actionCollection("General");
1050
1051     coll->action("ConnectCore")->setEnabled(false);
1052     coll->action("DisconnectCore")->setEnabled(true);
1053     coll->action("CoreInfo")->setEnabled(true);
1054
1055     foreach(QAction *action, _fileMenu->actions()) {
1056         if (isRemoteCoreOnly(action))
1057             action->setVisible(!Client::internalCore());
1058     }
1059
1060     disconnect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
1061     disconnect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1062     disconnect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1063     if (!Client::internalCore()) {
1064         connect(Client::backlogManager(), SIGNAL(updateProgress(int, int)), _msgProcessorStatusWidget, SLOT(setProgress(int, int)));
1065         connect(Client::backlogManager(), SIGNAL(messagesRequested(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1066         connect(Client::backlogManager(), SIGNAL(messagesProcessed(const QString &)), this, SLOT(showStatusBarMessage(const QString &)));
1067     }
1068
1069     // _viewMenu->setEnabled(true);
1070     if (!Client::internalCore())
1071         statusBar()->showMessage(tr("Connected to core."));
1072     else
1073         statusBar()->clearMessage();
1074
1075     _coreConnectionStatusWidget->setVisible(!Client::internalCore());
1076     updateIcon();
1077     systemTray()->setState(SystemTray::Active);
1078
1079     if (Client::networkIds().isEmpty()) {
1080         IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
1081         wizard->show();
1082     }
1083     else {
1084         // Monolithic always preselects last used buffer - Client only if the connection died
1085         if (Client::coreConnection()->wasReconnect() || Quassel::runMode() == Quassel::Monolithic) {
1086             QtUiSettings s;
1087             BufferId lastUsedBufferId(s.value("LastUsedBufferId").toInt());
1088             if (lastUsedBufferId.isValid())
1089                 Client::bufferModel()->switchToBuffer(lastUsedBufferId);
1090         }
1091     }
1092 }
1093
1094
1095 void MainWin::loadLayout()
1096 {
1097     QtUiSettings s;
1098     int accountId = Client::currentCoreAccount().accountId().toInt();
1099     QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
1100     if (state.isEmpty()) {
1101         foreach(BufferViewDock *view, _bufferViews)
1102         view->show();
1103         _layoutLoaded = true;
1104         return;
1105     }
1106
1107     restoreState(state, accountId);
1108     int bufferViewId = s.value(QString("ActiveBufferView-%1").arg(accountId), -1).toInt();
1109     if (bufferViewId >= 0)
1110         changeActiveBufferView(bufferViewId);
1111
1112     _layoutLoaded = true;
1113 }
1114
1115
1116 void MainWin::saveLayout()
1117 {
1118     QtUiSettings s;
1119     int accountId = _bufferViews.count() ? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
1120     if (accountId > 0) {
1121         s.setValue(QString("MainWinState-%1").arg(accountId), saveState(accountId));
1122         BufferView *view = activeBufferView();
1123         s.setValue(QString("ActiveBufferView-%1").arg(accountId), view ? view->config()->bufferViewId() : -1);
1124     }
1125 }
1126
1127
1128 void MainWin::disconnectedFromCore()
1129 {
1130     // save core specific layout and remove bufferviews;
1131     saveLayout();
1132     _layoutLoaded = false;
1133
1134     QVariant actionData;
1135     BufferViewDock *dock;
1136     foreach(QAction *action, _bufferViewsMenu->actions()) {
1137         actionData = action->data();
1138         if (!actionData.isValid())
1139             continue;
1140
1141         dock = qobject_cast<BufferViewDock *>(action->parent());
1142         if (dock && actionData.toInt() != -1) {
1143             removeAction(action);
1144             _bufferViews.removeAll(dock);
1145             dock->deleteLater();
1146         }
1147     }
1148
1149     // store last active buffer
1150     QtUiSettings s;
1151     BufferId lastBufId = _bufferWidget->currentBuffer();
1152     if (lastBufId.isValid()) {
1153         s.setValue("LastUsedBufferId", lastBufId.toInt());
1154         // clear the current selection
1155         Client::bufferModel()->standardSelectionModel()->clearSelection();
1156     }
1157     restoreState(s.value("MainWinState").toByteArray());
1158     setDisconnectedState();
1159 }
1160
1161
1162 void MainWin::setDisconnectedState()
1163 {
1164     ActionCollection *coll = QtUi::actionCollection("General");
1165     //ui.menuCore->setEnabled(false);
1166     coll->action("ConnectCore")->setEnabled(true);
1167     coll->action("DisconnectCore")->setEnabled(false);
1168     coll->action("CoreInfo")->setEnabled(false);
1169     //_viewMenu->setEnabled(false);
1170     statusBar()->showMessage(tr("Not connected to core."));
1171     if (_msgProcessorStatusWidget)
1172         _msgProcessorStatusWidget->setProgress(0, 0);
1173     updateIcon();
1174     systemTray()->setState(SystemTray::Passive);
1175 }
1176
1177
1178 void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage)
1179 {
1180     Q_UNUSED(errorMessage)
1181     CoreConnectAuthDlg dlg(account, this);
1182     *valid = (dlg.exec() == QDialog::Accepted);
1183 }
1184
1185
1186 void MainWin::handleNoSslInClient(bool *accepted)
1187 {
1188     QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
1189         QMessageBox::Ignore|QMessageBox::Cancel, this);
1190     box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
1191     box.setDefaultButton(QMessageBox::Ignore);
1192     *accepted = box.exec() == QMessageBox::Ignore;
1193 }
1194
1195
1196 void MainWin::handleNoSslInCore(bool *accepted)
1197 {
1198     QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
1199         QMessageBox::Ignore|QMessageBox::Cancel, this);
1200     box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
1201     box.setDefaultButton(QMessageBox::Ignore);
1202     *accepted = box.exec() == QMessageBox::Ignore;
1203 }
1204
1205
1206 #ifdef HAVE_SSL
1207
1208 void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently)
1209 {
1210     QString errorString = "<ul>";
1211     foreach(const QSslError error, socket->sslErrors())
1212     errorString += QString("<li>%1</li>").arg(error.errorString());
1213     errorString += "</ul>";
1214
1215     QMessageBox box(QMessageBox::Warning,
1216         tr("Untrusted Security Certificate"),
1217         tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
1218         QMessageBox::Cancel, this);
1219     box.setInformativeText(errorString);
1220     box.addButton(tr("Continue"), QMessageBox::AcceptRole);
1221     box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
1222
1223     QMessageBox::ButtonRole role;
1224     do {
1225         box.exec();
1226         role = box.buttonRole(box.clickedButton());
1227         if (role == QMessageBox::HelpRole) {
1228             SslInfoDlg dlg(socket, this);
1229             dlg.exec();
1230         }
1231     }
1232     while (role == QMessageBox::HelpRole);
1233
1234     *accepted = role == QMessageBox::AcceptRole;
1235     if (*accepted) {
1236         QMessageBox box2(QMessageBox::Warning,
1237             tr("Untrusted Security Certificate"),
1238             tr("Would you like to accept this certificate forever without being prompted?"),
1239             0, this);
1240         box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
1241         box2.addButton(tr("Forever"), QMessageBox::YesRole);
1242         box2.exec();
1243         *permanently =  box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
1244     }
1245 }
1246
1247
1248 #endif /* HAVE_SSL */
1249
1250 void MainWin::handleCoreConnectionError(const QString &error)
1251 {
1252     QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
1253 }
1254
1255
1256 void MainWin::showCoreConnectionDlg()
1257 {
1258     CoreConnectDlg dlg(this);
1259     if (dlg.exec() == QDialog::Accepted) {
1260         AccountId accId = dlg.selectedAccount();
1261         if (accId.isValid())
1262             Client::coreConnection()->connectToCore(accId);
1263     }
1264 }
1265
1266
1267 void MainWin::showCoreConfigWizard(const QVariantList &backends)
1268 {
1269     CoreConfigWizard *wizard = new CoreConfigWizard(Client::coreConnection(), backends, this);
1270
1271     wizard->show();
1272 }
1273
1274
1275 void MainWin::showChannelList(NetworkId netId)
1276 {
1277     ChannelListDlg *channelListDlg = new ChannelListDlg();
1278
1279     if (!netId.isValid()) {
1280         QAction *action = qobject_cast<QAction *>(sender());
1281         if (action)
1282             netId = action->data().value<NetworkId>();
1283     }
1284
1285     channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
1286     channelListDlg->setNetwork(netId);
1287     channelListDlg->show();
1288 }
1289
1290
1291 void MainWin::showIgnoreList(QString newRule)
1292 {
1293     SettingsPageDlg dlg(new IgnoreListSettingsPage(this), this);
1294     // prepare config dialog for new rule
1295     if (!newRule.isEmpty())
1296         qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
1297     dlg.exec();
1298 }
1299
1300
1301 void MainWin::showCoreInfoDlg()
1302 {
1303     CoreInfoDlg(this).exec();
1304 }
1305
1306
1307 void MainWin::showAwayLog()
1308 {
1309     if (_awayLog)
1310         return;
1311     AwayLogFilter *filter = new AwayLogFilter(Client::messageModel());
1312     _awayLog = new AwayLogView(filter, 0);
1313     filter->setParent(_awayLog);
1314     connect(_awayLog, SIGNAL(destroyed()), this, SLOT(awayLogDestroyed()));
1315     _awayLog->setAttribute(Qt::WA_DeleteOnClose);
1316     _awayLog->show();
1317 }
1318
1319
1320 void MainWin::awayLogDestroyed()
1321 {
1322     _awayLog = 0;
1323 }
1324
1325
1326 void MainWin::showSettingsDlg()
1327 {
1328     SettingsDlg *dlg = new SettingsDlg();
1329
1330     //Category: Interface
1331     dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
1332     dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
1333     dlg->registerSettingsPage(new ChatMonitorSettingsPage(dlg));
1334     dlg->registerSettingsPage(new ItemViewSettingsPage(dlg));
1335     dlg->registerSettingsPage(new BufferViewSettingsPage(dlg));
1336     dlg->registerSettingsPage(new InputWidgetSettingsPage(dlg));
1337     dlg->registerSettingsPage(new TopicWidgetSettingsPage(dlg));
1338     dlg->registerSettingsPage(new HighlightSettingsPage(dlg));
1339     dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
1340     dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
1341
1342     //Category: IRC
1343     dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
1344     dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
1345     dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
1346     dlg->registerSettingsPage(new AliasesSettingsPage(dlg));
1347     dlg->registerSettingsPage(new IgnoreListSettingsPage(dlg));
1348
1349     // Category: Remote Cores
1350     if (Quassel::runMode() != Quassel::Monolithic) {
1351         dlg->registerSettingsPage(new CoreAccountSettingsPage(dlg));
1352         dlg->registerSettingsPage(new CoreConnectionSettingsPage(dlg));
1353     }
1354
1355     dlg->show();
1356 }
1357
1358
1359 void MainWin::showAboutDlg()
1360 {
1361     AboutDlg(this).exec();
1362 }
1363
1364
1365 void MainWin::showShortcutsDlg()
1366 {
1367 #ifdef HAVE_KDE
1368     KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed, this);
1369     foreach(KActionCollection *coll, QtUi::actionCollections())
1370     dlg.addCollection(coll, coll->property("Category").toString());
1371     dlg.exec();
1372 #else
1373     SettingsPageDlg dlg(new ShortcutsSettingsPage(QtUi::actionCollections(), this), this);
1374     dlg.exec();
1375 #endif
1376 }
1377
1378
1379 void MainWin::onFullScreenToggled()
1380 {
1381     // Relying on QWidget::isFullScreen is discouraged, see the KToggleFullScreenAction docs
1382     // Also, one should not use showFullScreen() or showNormal(), as those reset all other window flags
1383
1384     QAction *action = QtUi::actionCollection("General")->action("ToggleFullScreen");
1385     if (!action)
1386         return;
1387
1388 #ifdef HAVE_KDE
1389     KToggleFullScreenAction *kAct = static_cast<KToggleFullScreenAction *>(action);
1390     kAct->setFullScreen(this, kAct->isChecked());
1391 #else
1392     if (action->isChecked())
1393         setWindowState(windowState() | Qt::WindowFullScreen);
1394     else
1395         setWindowState(windowState() & ~Qt::WindowFullScreen);
1396 #endif
1397 }
1398
1399
1400 /********************************************************************************************************/
1401
1402 bool MainWin::event(QEvent *event)
1403 {
1404     switch(event->type()) {
1405     case QEvent::WindowActivate: {
1406         BufferId bufferId = Client::bufferModel()->currentBuffer();
1407         if (bufferId.isValid())
1408             Client::instance()->markBufferAsRead(bufferId);
1409         break;
1410     }
1411     case QEvent::WindowDeactivate:
1412         if (bufferWidget()->autoMarkerLineOnLostFocus())
1413             bufferWidget()->setMarkerLine();
1414         break;
1415     default:
1416         break;
1417     }
1418     return QMainWindow::event(event);
1419 }
1420
1421
1422 void MainWin::moveEvent(QMoveEvent *event)
1423 {
1424     if (!(windowState() & Qt::WindowMaximized))
1425         _normalPos = event->pos();
1426
1427     QMainWindow::moveEvent(event);
1428 }
1429
1430
1431 void MainWin::resizeEvent(QResizeEvent *event)
1432 {
1433     if (!(windowState() & Qt::WindowMaximized))
1434         _normalSize = event->size();
1435
1436     QMainWindow::resizeEvent(event);
1437 }
1438
1439
1440 void MainWin::closeEvent(QCloseEvent *event)
1441 {
1442     QtUiSettings s;
1443     QtUiApplication *app = qobject_cast<QtUiApplication *> qApp;
1444     Q_ASSERT(app);
1445     if (!app->isAboutToQuit() && QtUi::haveSystemTray() && s.value("MinimizeOnClose").toBool()) {
1446         QtUi::hideMainWidget();
1447         event->ignore();
1448     }
1449     else {
1450         event->accept();
1451         quit();
1452     }
1453 }
1454
1455
1456 void MainWin::messagesInserted(const QModelIndex &parent, int start, int end)
1457 {
1458     Q_UNUSED(parent);
1459
1460     bool hasFocus = QApplication::activeWindow() != 0;
1461
1462     for (int i = start; i <= end; i++) {
1463         QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn);
1464         if (!idx.isValid()) {
1465             qDebug() << "MainWin::messagesInserted(): Invalid model index!";
1466             continue;
1467         }
1468         Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt();
1469         if (flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self))
1470             continue;
1471
1472         BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>();
1473         BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
1474
1475         // check if bufferId belongs to the shown chatlists
1476         if (!(Client::bufferViewOverlay()->bufferIds().contains(bufId) ||
1477               Client::bufferViewOverlay()->tempRemovedBufferIds().contains(bufId)))
1478             continue;
1479
1480         // check if it's the buffer currently displayed
1481         if (hasFocus && bufId == Client::bufferModel()->currentBuffer())
1482             continue;
1483
1484         // only show notifications for higlights or queries
1485         if (bufType != BufferInfo::QueryBuffer && !(flags & Message::Highlight))
1486             continue;
1487
1488         // and of course: don't notify for ignored messages
1489         if (Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(), Client::networkModel()->networkName(bufId)))
1490             continue;
1491
1492         // seems like we have a legit notification candidate!
1493         QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn);
1494         QString sender = senderIdx.data(ChatLineModel::EditRole).toString();
1495         QString contents = idx.data(ChatLineModel::DisplayRole).toString();
1496         AbstractNotificationBackend::NotificationType type;
1497
1498         if (bufType == BufferInfo::QueryBuffer && !hasFocus)
1499             type = AbstractNotificationBackend::PrivMsg;
1500         else if (bufType == BufferInfo::QueryBuffer && hasFocus)
1501             type = AbstractNotificationBackend::PrivMsgFocused;
1502         else if (flags & Message::Highlight && !hasFocus)
1503             type = AbstractNotificationBackend::Highlight;
1504         else
1505             type = AbstractNotificationBackend::HighlightFocused;
1506
1507         QtUi::instance()->invokeNotification(bufId, type, sender, contents);
1508     }
1509 }
1510
1511
1512 void MainWin::currentBufferChanged(BufferId buffer)
1513 {
1514     if (buffer.isValid())
1515         Client::instance()->markBufferAsRead(buffer);
1516 }
1517
1518
1519 void MainWin::clientNetworkCreated(NetworkId id)
1520 {
1521     const Network *net = Client::network(id);
1522     QAction *act = new QAction(net->networkName(), this);
1523     act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
1524     act->setData(QVariant::fromValue<NetworkId>(id));
1525     connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
1526     connect(act, SIGNAL(triggered()), this, SLOT(connectOrDisconnectFromNet()));
1527
1528     QAction *beforeAction = 0;
1529     foreach(QAction *action, _networksMenu->actions()) {
1530         if (!action->data().isValid()) // ignore stock actions
1531             continue;
1532         if (net->networkName().localeAwareCompare(action->text()) < 0) {
1533             beforeAction = action;
1534             break;
1535         }
1536     }
1537     _networksMenu->insertAction(beforeAction, act);
1538 }
1539
1540
1541 void MainWin::clientNetworkUpdated()
1542 {
1543     const Network *net = qobject_cast<const Network *>(sender());
1544     if (!net)
1545         return;
1546
1547     QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
1548     if (!action)
1549         return;
1550
1551     action->setText(net->networkName());
1552
1553     switch (net->connectionState()) {
1554     case Network::Initialized:
1555         action->setIcon(SmallIcon("network-connect"));
1556         // if we have no currently selected buffer, jump to the first connecting statusbuffer
1557         if (!bufferWidget()->currentBuffer().isValid()) {
1558             QModelIndex idx = Client::networkModel()->networkIndex(net->networkId());
1559             if (idx.isValid()) {
1560                 BufferId statusBufferId = idx.data(NetworkModel::BufferIdRole).value<BufferId>();
1561                 Client::bufferModel()->switchToBuffer(statusBufferId);
1562             }
1563         }
1564         break;
1565     case Network::Disconnected:
1566         action->setIcon(SmallIcon("network-disconnect"));
1567         break;
1568     default:
1569         action->setIcon(SmallIcon("network-wired"));
1570     }
1571 }
1572
1573
1574 void MainWin::clientNetworkRemoved(NetworkId id)
1575 {
1576     QAction *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
1577     if (!action)
1578         return;
1579
1580     action->deleteLater();
1581 }
1582
1583
1584 void MainWin::connectOrDisconnectFromNet()
1585 {
1586     QAction *act = qobject_cast<QAction *>(sender());
1587     if (!act) return;
1588     const Network *net = Client::network(act->data().value<NetworkId>());
1589     if (!net) return;
1590     if (net->connectionState() == Network::Disconnected) net->requestConnect();
1591     else net->requestDisconnect();
1592 }
1593
1594
1595 void MainWin::on_jumpHotBuffer_triggered()
1596 {
1597     if (!_bufferHotList->rowCount())
1598         return;
1599
1600     Client::bufferModel()->switchToBuffer(_bufferHotList->hottestBuffer());
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     _bufferHotList->invalidate();
1652     _bufferHotList->sort(0, Qt::DescendingOrder);
1653
1654     QTreeView *view = new QTreeView;
1655     view->setAttribute(Qt::WA_DeleteOnClose);
1656     view->setModel(_bufferHotList);
1657     view->show();
1658 }
1659
1660
1661 void MainWin::on_actionDebugBufferViewOverlay_triggered()
1662 {
1663     DebugBufferViewOverlay *overlay = new DebugBufferViewOverlay(0);
1664     overlay->setAttribute(Qt::WA_DeleteOnClose);
1665     overlay->show();
1666 }
1667
1668
1669 void MainWin::on_actionDebugMessageModel_triggered()
1670 {
1671     QTableView *view = new QTableView(0);
1672     DebugMessageModelFilter *filter = new DebugMessageModelFilter(view);
1673     filter->setSourceModel(Client::messageModel());
1674     view->setModel(filter);
1675     view->setAttribute(Qt::WA_DeleteOnClose, true);
1676     view->verticalHeader()->hide();
1677     view->horizontalHeader()->setStretchLastSection(true);
1678     view->show();
1679 }
1680
1681
1682 void MainWin::on_actionDebugLog_triggered()
1683 {
1684     DebugLogWidget *logWidget = new DebugLogWidget(0);
1685     logWidget->show();
1686 }
1687
1688
1689 void MainWin::showStatusBarMessage(const QString &message)
1690 {
1691     statusBar()->showMessage(message, 10000);
1692 }