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