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