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