1 /***************************************************************************
2 * Copyright (C) 2005-09 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
23 #include "abstractmessageprocessor.h"
24 #include "abstractui.h"
25 #include "bufferinfo.h"
26 #include "buffermodel.h"
27 #include "buffersettings.h"
28 #include "buffersyncer.h"
29 #include "bufferviewconfig.h"
30 #include "bufferviewoverlay.h"
31 #include "clientaliasmanager.h"
32 #include "clientbacklogmanager.h"
33 #include "clientbufferviewmanager.h"
34 #include "clientirclisthelper.h"
35 #include "clientidentity.h"
36 #include "clientuserinputhandler.h"
37 #include "ircchannel.h"
40 #include "messagemodel.h"
42 #include "networkconfig.h"
43 #include "networkmodel.h"
45 #include "signalproxy.h"
51 QPointer<Client> Client::instanceptr = 0;
52 AccountId Client::_currentCoreAccount = 0;
54 /*** Initialization/destruction ***/
56 bool Client::instanceExists()
61 Client *Client::instance() {
63 instanceptr = new Client();
67 void Client::destroy() {
69 delete instanceptr->mainUi();
70 instanceptr->deleteLater();
75 void Client::init(AbstractUi *ui) {
76 instance()->_mainUi = ui;
80 Client::Client(QObject *parent)
82 _signalProxy(new SignalProxy(SignalProxy::Client, this)),
88 _backlogManager(new ClientBacklogManager(this)),
89 _bufferViewManager(0),
90 _bufferViewOverlay(new BufferViewOverlay(this)),
91 _ircListHelper(new ClientIrcListHelper(this)),
96 _connectedToCore(false),
99 _debugLog(&_debugLogBuffer)
101 _signalProxy->synchronize(_ircListHelper);
105 disconnectFromCore();
108 void Client::init() {
109 _currentCoreAccount = 0;
110 _networkModel = new NetworkModel(this);
112 connect(this, SIGNAL(networkRemoved(NetworkId)),
113 _networkModel, SLOT(networkRemoved(NetworkId)));
115 _bufferModel = new BufferModel(_networkModel);
116 _messageModel = mainUi()->createMessageModel(this);
117 _messageProcessor = mainUi()->createMessageProcessor(this);
118 _inputHandler = new ClientUserInputHandler(this);
120 SignalProxy *p = signalProxy();
122 p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
123 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
125 p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo)));
126 p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString)));
127 p->attachSignal(this, SIGNAL(requestNetworkStates()));
129 p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &)));
130 p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
131 p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
132 p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
134 p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)));
135 p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
136 p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
137 p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
139 connect(p, SIGNAL(disconnected()), this, SLOT(disconnectedFromCore()));
141 //connect(mainUi(), SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
142 connect(mainUi(), SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
143 connect(this, SIGNAL(connected()), mainUi(), SLOT(connectedToCore()));
144 connect(this, SIGNAL(disconnected()), mainUi(), SLOT(disconnectedFromCore()));
146 // attach backlog manager
147 p->synchronize(backlogManager());
148 connect(backlogManager(), SIGNAL(messagesReceived(BufferId, int)), _messageModel, SLOT(messagesReceived(BufferId, int)));
151 /*** public static methods ***/
153 AbstractUi *Client::mainUi() {
154 return instance()->_mainUi;
157 AccountId Client::currentCoreAccount() {
158 return _currentCoreAccount;
161 void Client::setCurrentCoreAccount(AccountId id) {
162 _currentCoreAccount = id;
165 bool Client::isConnected() {
166 return instance()->_connectedToCore;
169 bool Client::isSynced() {
170 return instance()->_syncedToCore;
173 /*** Network handling ***/
175 QList<NetworkId> Client::networkIds() {
176 return instance()->_networks.keys();
179 const Network * Client::network(NetworkId networkid) {
180 if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
184 void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels) {
185 emit instance()->requestCreateNetwork(info, persistentChannels);
188 void Client::removeNetwork(NetworkId id) {
189 emit instance()->requestRemoveNetwork(id);
192 void Client::updateNetwork(const NetworkInfo &info) {
193 Network *netptr = instance()->_networks.value(info.networkId, 0);
195 qWarning() << "Update for unknown network requested:" << info;
198 netptr->requestSetNetworkInfo(info);
201 void Client::addNetwork(Network *net) {
202 net->setProxy(signalProxy());
203 signalProxy()->synchronize(net);
204 networkModel()->attachNetwork(net);
205 connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
206 instance()->_networks[net->networkId()] = net;
207 emit instance()->networkCreated(net->networkId());
210 void Client::coreNetworkCreated(NetworkId id) {
211 if(_networks.contains(id)) {
212 qWarning() << "Creation of already existing network requested!";
215 Network *net = new Network(id, this);
219 void Client::coreNetworkRemoved(NetworkId id) {
220 if(!_networks.contains(id))
222 Network *net = _networks.take(id);
223 emit networkRemoved(net->networkId());
227 /*** Identity handling ***/
229 QList<IdentityId> Client::identityIds() {
230 return instance()->_identities.keys();
233 const Identity *Client::identity(IdentityId id) {
234 if(instance()->_identities.contains(id)) return instance()->_identities[id];
238 void Client::createIdentity(const CertIdentity &id) {
239 QVariantMap additional;
241 additional["KeyPem"] = id.sslKey().toPem();
242 additional["CertPem"] = id.sslCert().toPem();
244 emit instance()->requestCreateIdentity(id, additional);
247 void Client::updateIdentity(IdentityId id, const QVariantMap &ser) {
248 Identity *idptr = instance()->_identities.value(id, 0);
250 qWarning() << "Update for unknown identity requested:" << id;
253 idptr->requestUpdate(ser);
256 void Client::removeIdentity(IdentityId id) {
257 emit instance()->requestRemoveIdentity(id);
260 void Client::coreIdentityCreated(const Identity &other) {
261 if(!_identities.contains(other.id())) {
262 Identity *identity = new Identity(other, this);
263 _identities[other.id()] = identity;
264 identity->setInitialized();
265 signalProxy()->synchronize(identity);
266 emit identityCreated(other.id());
268 qWarning() << tr("Identity already exists in client!");
272 void Client::coreIdentityRemoved(IdentityId id) {
273 if(_identities.contains(id)) {
274 emit identityRemoved(id);
275 Identity *i = _identities.take(id);
280 /*** User input handling ***/
282 void Client::userInput(const BufferInfo &bufferInfo, const QString &message) {
283 // we need to make sure that AliasManager is ready before processing input
284 if(aliasManager() && aliasManager()->isInitialized())
285 inputHandler()->handleUserInput(bufferInfo, message);
287 instance()-> _userInputBuffer.append(qMakePair(bufferInfo, message));
290 void Client::sendBufferedUserInput() {
291 for(int i = 0; i < _userInputBuffer.count(); i++)
292 userInput(_userInputBuffer.at(i).first, _userInputBuffer.at(i).second);
294 _userInputBuffer.clear();
297 /*** core connection stuff ***/
299 void Client::setConnectedToCore(AccountId id, QIODevice *socket) {
300 if(socket) { // external core
301 // if the socket is an orphan, the signalProxy adopts it.
302 // -> we don't need to care about it anymore
303 socket->setParent(0);
304 signalProxy()->addPeer(socket);
306 _internalCore = !socket;
307 _connectedToCore = true;
308 setCurrentCoreAccount(id);
311 void Client::setSyncedToCore() {
312 // create buffersyncer
313 Q_ASSERT(!_bufferSyncer);
314 _bufferSyncer = new BufferSyncer(this);
315 connect(bufferSyncer(), SIGNAL(lastSeenMsgSet(BufferId, MsgId)), _networkModel, SLOT(setLastSeenMsgId(BufferId, MsgId)));
316 connect(bufferSyncer(), SIGNAL(bufferRemoved(BufferId)), this, SLOT(bufferRemoved(BufferId)));
317 connect(bufferSyncer(), SIGNAL(bufferRenamed(BufferId, QString)), this, SLOT(bufferRenamed(BufferId, QString)));
318 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), this, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
319 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), _messageModel, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
320 connect(networkModel(), SIGNAL(setLastSeenMsg(BufferId, MsgId)), bufferSyncer(), SLOT(requestSetLastSeenMsg(BufferId, const MsgId &)));
321 signalProxy()->synchronize(bufferSyncer());
323 // create a new BufferViewManager
324 Q_ASSERT(!_bufferViewManager);
325 _bufferViewManager = new ClientBufferViewManager(signalProxy(), this);
326 connect(bufferViewManager(), SIGNAL(initDone()), this, SLOT(createDefaultBufferView()));
328 // create AliasManager
329 Q_ASSERT(!_aliasManager);
330 _aliasManager = new ClientAliasManager(this);
331 connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput()));
332 signalProxy()->synchronize(aliasManager());
334 // create NetworkConfig
335 Q_ASSERT(!_networkConfig);
336 _networkConfig = new NetworkConfig("GlobalNetworkConfig", this);
337 signalProxy()->synchronize(networkConfig());
339 // trigger backlog request once all active bufferviews are initialized
340 connect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
342 _syncedToCore = true;
344 emit coreConnectionStateChanged(true);
347 void Client::requestInitialBacklog() {
348 // usually it _should_ take longer until the bufferViews are initialized, so that's what
349 // triggers this slot. But we have to make sure that we know all buffers yet.
350 // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead
351 if(!bufferSyncer()->isInitialized()) {
352 connect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
353 connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
356 _backlogManager->requestInitialBacklog();
359 void Client::createDefaultBufferView() {
360 if(bufferViewManager()->bufferViewConfigs().isEmpty()) {
361 BufferViewConfig config(-1);
362 config.setBufferViewName(tr("All Buffers"));
363 config.initSetBufferList(networkModel()->allBufferIdsSorted());
364 bufferViewManager()->requestCreateBufferView(config.toVariantMap());
368 void Client::disconnectFromCore() {
372 signalProxy()->removeAllPeers();
375 void Client::disconnectedFromCore() {
376 _connectedToCore = false;
377 _syncedToCore = false;
379 emit coreConnectionStateChanged(false);
381 backlogManager()->reset();
382 messageProcessor()->reset();
384 // Clear internal data. Hopefully nothing relies on it at this point.
385 setCurrentCoreAccount(0);
388 _bufferSyncer->deleteLater();
392 if(_bufferViewManager) {
393 _bufferViewManager->deleteLater();
394 _bufferViewManager = 0;
398 _aliasManager->deleteLater();
402 // we probably don't want to save pending input for reconnect
403 _userInputBuffer.clear();
405 _messageModel->clear();
406 _networkModel->clear();
408 QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
409 while(netIter != _networks.end()) {
410 Network *net = netIter.value();
411 emit networkRemoved(net->networkId());
412 disconnect(net, SIGNAL(destroyed()), this, 0);
413 netIter = _networks.erase(netIter);
416 Q_ASSERT(_networks.isEmpty());
418 QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
419 while(idIter != _identities.end()) {
420 emit identityRemoved(idIter.key());
421 Identity *id = idIter.value();
422 idIter = _identities.erase(idIter);
425 Q_ASSERT(_identities.isEmpty());
428 _networkConfig->deleteLater();
435 void Client::networkDestroyed() {
436 Network *net = static_cast<Network *>(sender());
437 QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
438 while(netIter != _networks.end()) {
439 if(*netIter == net) {
440 netIter = _networks.erase(netIter);
448 // Hmm... we never used this...
449 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
450 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
453 void Client::recvMessage(const Message &msg) {
455 messageProcessor()->process(msg_);
458 void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) {
461 bufferSyncer()->requestSetLastSeenMsg(id, msgId);
464 void Client::removeBuffer(BufferId id) {
465 if(!bufferSyncer()) return;
466 bufferSyncer()->requestRemoveBuffer(id);
469 void Client::renameBuffer(BufferId bufferId, const QString &newName) {
472 bufferSyncer()->requestRenameBuffer(bufferId, newName);
475 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) {
478 bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
481 void Client::purgeKnownBufferIds() {
484 bufferSyncer()->requestPurgeBufferIds();
487 void Client::bufferRemoved(BufferId bufferId) {
488 // select a sane buffer (status buffer)
489 /* we have to manually select a buffer because otherwise inconsitent changes
490 * to the model might occur:
491 * the result of a buffer removal triggers a change in the selection model.
492 * the newly selected buffer might be a channel that hasn't been selected yet
493 * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
494 * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
496 QModelIndex current = bufferModel()->currentIndex();
497 if(current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
498 bufferModel()->setCurrentIndex(current.sibling(0,0));
501 // and remove it from the model
502 networkModel()->removeBuffer(bufferId);
505 void Client::bufferRenamed(BufferId bufferId, const QString &newName) {
506 QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
507 if(bufferIndex.isValid()) {
508 networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
512 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
513 QModelIndex idx = networkModel()->bufferIndex(bufferId1);
514 bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
515 networkModel()->removeBuffer(bufferId2);
518 void Client::logMessage(QtMsgType type, const char *msg) {
519 fprintf(stderr, "%s\n", msg);
521 if(type == QtFatalMsg) {
522 Quassel::logFatalMessage(msg);
524 QString msgString = QString("%1\n").arg(msg);
526 //Check to see if there is an instance around, else we risk recursions
527 //when calling instance() and creating new ones.
528 if (!instanceExists())
531 instance()->_debugLog << msgString;
532 emit instance()->logUpdated(msgString);