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 "clientaliasmanager.h"
31 #include "clientbacklogmanager.h"
32 #include "clientbufferviewmanager.h"
33 #include "clientirclisthelper.h"
34 #include "clientidentity.h"
35 #include "clientuserinputhandler.h"
36 #include "ircchannel.h"
39 #include "messagemodel.h"
41 #include "networkmodel.h"
43 #include "signalproxy.h"
49 QPointer<Client> Client::instanceptr = 0;
50 AccountId Client::_currentCoreAccount = 0;
52 /*** Initialization/destruction ***/
54 bool Client::instanceExists()
59 Client *Client::instance() {
61 instanceptr = new Client();
65 void Client::destroy() {
67 delete instanceptr->mainUi();
68 instanceptr->deleteLater();
73 void Client::init(AbstractUi *ui) {
74 instance()->_mainUi = ui;
78 Client::Client(QObject *parent)
80 _signalProxy(new SignalProxy(SignalProxy::Client, this)),
86 _backlogManager(new ClientBacklogManager(this)),
87 _bufferViewManager(0),
88 _ircListHelper(new ClientIrcListHelper(this)),
92 _connectedToCore(false),
95 _debugLog(&_debugLogBuffer)
97 _signalProxy->synchronize(_ircListHelper);
101 disconnectFromCore();
104 void Client::init() {
105 _currentCoreAccount = 0;
106 _networkModel = new NetworkModel(this);
108 connect(this, SIGNAL(networkRemoved(NetworkId)),
109 _networkModel, SLOT(networkRemoved(NetworkId)));
111 _bufferModel = new BufferModel(_networkModel);
112 _messageModel = mainUi()->createMessageModel(this);
113 _messageProcessor = mainUi()->createMessageProcessor(this);
114 _inputHandler = new ClientUserInputHandler(this);
116 SignalProxy *p = signalProxy();
118 p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
119 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
121 p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo)));
122 p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString)));
123 p->attachSignal(this, SIGNAL(requestNetworkStates()));
125 p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &)));
126 p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
127 p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
128 p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
130 p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)));
131 p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
132 p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
133 p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
135 connect(p, SIGNAL(disconnected()), this, SLOT(disconnectedFromCore()));
137 //connect(mainUi(), SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
138 connect(mainUi(), SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
139 connect(this, SIGNAL(connected()), mainUi(), SLOT(connectedToCore()));
140 connect(this, SIGNAL(disconnected()), mainUi(), SLOT(disconnectedFromCore()));
142 // attach backlog manager
143 p->synchronize(backlogManager());
144 connect(backlogManager(), SIGNAL(messagesReceived(BufferId, int)), _messageModel, SLOT(messagesReceived(BufferId, int)));
147 /*** public static methods ***/
149 AbstractUi *Client::mainUi() {
150 return instance()->_mainUi;
153 AccountId Client::currentCoreAccount() {
154 return _currentCoreAccount;
157 void Client::setCurrentCoreAccount(AccountId id) {
158 _currentCoreAccount = id;
161 bool Client::isConnected() {
162 return instance()->_connectedToCore;
165 bool Client::isSynced() {
166 return instance()->_syncedToCore;
169 /*** Network handling ***/
171 QList<NetworkId> Client::networkIds() {
172 return instance()->_networks.keys();
175 const Network * Client::network(NetworkId networkid) {
176 if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
180 void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels) {
181 emit instance()->requestCreateNetwork(info, persistentChannels);
184 void Client::removeNetwork(NetworkId id) {
185 emit instance()->requestRemoveNetwork(id);
188 void Client::updateNetwork(const NetworkInfo &info) {
189 Network *netptr = instance()->_networks.value(info.networkId, 0);
191 qWarning() << "Update for unknown network requested:" << info;
194 netptr->requestSetNetworkInfo(info);
197 void Client::addNetwork(Network *net) {
198 net->setProxy(signalProxy());
199 signalProxy()->synchronize(net);
200 networkModel()->attachNetwork(net);
201 connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
202 instance()->_networks[net->networkId()] = net;
203 emit instance()->networkCreated(net->networkId());
206 void Client::coreNetworkCreated(NetworkId id) {
207 if(_networks.contains(id)) {
208 qWarning() << "Creation of already existing network requested!";
211 Network *net = new Network(id, this);
215 void Client::coreNetworkRemoved(NetworkId id) {
216 if(!_networks.contains(id))
218 Network *net = _networks.take(id);
219 emit networkRemoved(net->networkId());
223 /*** Identity handling ***/
225 QList<IdentityId> Client::identityIds() {
226 return instance()->_identities.keys();
229 const Identity *Client::identity(IdentityId id) {
230 if(instance()->_identities.contains(id)) return instance()->_identities[id];
234 void Client::createIdentity(const CertIdentity &id) {
235 QVariantMap additional;
237 additional["KeyPem"] = id.sslKey().toPem();
238 additional["CertPem"] = id.sslCert().toPem();
240 emit instance()->requestCreateIdentity(id, additional);
243 void Client::updateIdentity(IdentityId id, const QVariantMap &ser) {
244 Identity *idptr = instance()->_identities.value(id, 0);
246 qWarning() << "Update for unknown identity requested:" << id;
249 idptr->requestUpdate(ser);
252 void Client::removeIdentity(IdentityId id) {
253 emit instance()->requestRemoveIdentity(id);
256 void Client::coreIdentityCreated(const Identity &other) {
257 if(!_identities.contains(other.id())) {
258 Identity *identity = new Identity(other, this);
259 _identities[other.id()] = identity;
260 identity->setInitialized();
261 signalProxy()->synchronize(identity);
262 emit identityCreated(other.id());
264 qWarning() << tr("Identity already exists in client!");
268 void Client::coreIdentityRemoved(IdentityId id) {
269 if(_identities.contains(id)) {
270 emit identityRemoved(id);
271 Identity *i = _identities.take(id);
276 /*** User input handling ***/
278 void Client::userInput(const BufferInfo &bufferInfo, const QString &message) {
279 // we need to make sure that AliasManager is ready before processing input
280 if(aliasManager() && aliasManager()->isInitialized())
281 inputHandler()->handleUserInput(bufferInfo, message);
283 instance()-> _userInputBuffer.append(qMakePair(bufferInfo, message));
286 void Client::sendBufferedUserInput() {
287 for(int i = 0; i < _userInputBuffer.count(); i++)
288 userInput(_userInputBuffer.at(i).first, _userInputBuffer.at(i).second);
290 _userInputBuffer.clear();
293 /*** core connection stuff ***/
295 void Client::setConnectedToCore(AccountId id, QIODevice *socket) {
296 if(socket) { // external core
297 // if the socket is an orphan, the signalProxy adopts it.
298 // -> we don't need to care about it anymore
299 socket->setParent(0);
300 signalProxy()->addPeer(socket);
302 _internalCore = !socket;
303 _connectedToCore = true;
304 setCurrentCoreAccount(id);
307 void Client::setSyncedToCore() {
308 // create buffersyncer
309 Q_ASSERT(!_bufferSyncer);
310 _bufferSyncer = new BufferSyncer(this);
311 connect(bufferSyncer(), SIGNAL(lastSeenMsgSet(BufferId, MsgId)), _networkModel, SLOT(setLastSeenMsgId(BufferId, MsgId)));
312 connect(bufferSyncer(), SIGNAL(bufferRemoved(BufferId)), this, SLOT(bufferRemoved(BufferId)));
313 connect(bufferSyncer(), SIGNAL(bufferRenamed(BufferId, QString)), this, SLOT(bufferRenamed(BufferId, QString)));
314 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), this, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
315 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), _messageModel, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
316 connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
317 connect(networkModel(), SIGNAL(setLastSeenMsg(BufferId, MsgId)), bufferSyncer(), SLOT(requestSetLastSeenMsg(BufferId, const MsgId &)));
318 signalProxy()->synchronize(bufferSyncer());
320 // create a new BufferViewManager
321 Q_ASSERT(!_bufferViewManager);
322 _bufferViewManager = new ClientBufferViewManager(signalProxy(), this);
323 connect(bufferViewManager(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
324 connect(bufferViewManager(), SIGNAL(initDone()), this, SLOT(createDefaultBufferView()));
326 // create AliasManager
327 Q_ASSERT(!_aliasManager);
328 _aliasManager = new ClientAliasManager(this);
329 connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput()));
330 signalProxy()->synchronize(aliasManager());
332 _syncedToCore = true;
334 emit coreConnectionStateChanged(true);
337 void Client::requestInitialBacklog() {
338 if(bufferViewManager()->isInitialized() && bufferSyncer()->isInitialized())
339 Client::backlogManager()->requestInitialBacklog();
342 void Client::createDefaultBufferView() {
343 if(bufferViewManager()->bufferViewConfigs().isEmpty()) {
344 BufferViewConfig config(-1);
345 config.setBufferViewName(tr("All Buffers"));
346 config.initSetBufferList(networkModel()->allBufferIdsSorted());
347 bufferViewManager()->requestCreateBufferView(config.toVariantMap());
351 void Client::disconnectFromCore() {
355 signalProxy()->removeAllPeers();
358 void Client::disconnectedFromCore() {
359 _connectedToCore = false;
360 _syncedToCore = false;
362 emit coreConnectionStateChanged(false);
364 backlogManager()->reset();
365 messageProcessor()->reset();
367 // Clear internal data. Hopefully nothing relies on it at this point.
368 setCurrentCoreAccount(0);
371 _bufferSyncer->deleteLater();
375 if(_bufferViewManager) {
376 _bufferViewManager->deleteLater();
377 _bufferViewManager = 0;
381 _aliasManager->deleteLater();
385 // we probably don't want to save pending input for reconnect
386 _userInputBuffer.clear();
388 _messageModel->clear();
389 _networkModel->clear();
391 QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
392 while(netIter != _networks.end()) {
393 Network *net = netIter.value();
394 emit networkRemoved(net->networkId());
395 disconnect(net, SIGNAL(destroyed()), this, 0);
396 netIter = _networks.erase(netIter);
399 Q_ASSERT(_networks.isEmpty());
401 QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
402 while(idIter != _identities.end()) {
403 emit identityRemoved(idIter.key());
404 Identity *id = idIter.value();
405 idIter = _identities.erase(idIter);
408 Q_ASSERT(_identities.isEmpty());
414 void Client::networkDestroyed() {
415 Network *net = static_cast<Network *>(sender());
416 QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
417 while(netIter != _networks.end()) {
418 if(*netIter == net) {
419 netIter = _networks.erase(netIter);
427 // Hmm... we never used this...
428 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
429 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
432 void Client::recvMessage(const Message &msg) {
434 messageProcessor()->process(msg_);
437 void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) {
440 bufferSyncer()->requestSetLastSeenMsg(id, msgId);
443 void Client::removeBuffer(BufferId id) {
444 if(!bufferSyncer()) return;
445 bufferSyncer()->requestRemoveBuffer(id);
448 void Client::renameBuffer(BufferId bufferId, const QString &newName) {
451 bufferSyncer()->requestRenameBuffer(bufferId, newName);
454 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) {
457 bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
460 void Client::purgeKnownBufferIds() {
463 bufferSyncer()->requestPurgeBufferIds();
466 void Client::bufferRemoved(BufferId bufferId) {
467 // select a sane buffer (status buffer)
468 /* we have to manually select a buffer because otherwise inconsitent changes
469 * to the model might occur:
470 * the result of a buffer removal triggers a change in the selection model.
471 * the newly selected buffer might be a channel that hasn't been selected yet
472 * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
473 * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
475 QModelIndex current = bufferModel()->currentIndex();
476 if(current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
477 bufferModel()->setCurrentIndex(current.sibling(0,0));
480 // and remove it from the model
481 networkModel()->removeBuffer(bufferId);
484 void Client::bufferRenamed(BufferId bufferId, const QString &newName) {
485 QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
486 if(bufferIndex.isValid()) {
487 networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
491 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
492 QModelIndex idx = networkModel()->bufferIndex(bufferId1);
493 bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
494 networkModel()->removeBuffer(bufferId2);
497 void Client::logMessage(QtMsgType type, const char *msg) {
498 fprintf(stderr, "%s\n", msg);
500 if(type == QtFatalMsg) {
501 Quassel::logFatalMessage(msg);
503 QString msgString = QString("%1\n").arg(msg);
505 //Check to see if there is an instance around, else we risk recursions
506 //when calling instance() and creating new ones.
507 if (!instanceExists())
510 instance()->_debugLog << msgString;
511 emit instance()->logUpdated(msgString);