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