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 "networkmodel.h"
44 #include "signalproxy.h"
50 QPointer<Client> Client::instanceptr = 0;
51 AccountId Client::_currentCoreAccount = 0;
53 /*** Initialization/destruction ***/
55 bool Client::instanceExists()
60 Client *Client::instance() {
62 instanceptr = new Client();
66 void Client::destroy() {
68 delete instanceptr->mainUi();
69 instanceptr->deleteLater();
74 void Client::init(AbstractUi *ui) {
75 instance()->_mainUi = ui;
79 Client::Client(QObject *parent)
81 _signalProxy(new SignalProxy(SignalProxy::Client, this)),
87 _backlogManager(new ClientBacklogManager(this)),
88 _bufferViewManager(0),
89 _bufferViewOverlay(new BufferViewOverlay(this)),
90 _ircListHelper(new ClientIrcListHelper(this)),
94 _connectedToCore(false),
97 _debugLog(&_debugLogBuffer)
99 _signalProxy->synchronize(_ircListHelper);
103 disconnectFromCore();
106 void Client::init() {
107 _currentCoreAccount = 0;
108 _networkModel = new NetworkModel(this);
110 connect(this, SIGNAL(networkRemoved(NetworkId)),
111 _networkModel, SLOT(networkRemoved(NetworkId)));
113 _bufferModel = new BufferModel(_networkModel);
114 _messageModel = mainUi()->createMessageModel(this);
115 _messageProcessor = mainUi()->createMessageProcessor(this);
116 _inputHandler = new ClientUserInputHandler(this);
118 SignalProxy *p = signalProxy();
120 p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
121 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
123 p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo)));
124 p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString)));
125 p->attachSignal(this, SIGNAL(requestNetworkStates()));
127 p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &)));
128 p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
129 p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
130 p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
132 p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)));
133 p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
134 p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
135 p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
137 connect(p, SIGNAL(disconnected()), this, SLOT(disconnectedFromCore()));
139 //connect(mainUi(), SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
140 connect(mainUi(), SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
141 connect(this, SIGNAL(connected()), mainUi(), SLOT(connectedToCore()));
142 connect(this, SIGNAL(disconnected()), mainUi(), SLOT(disconnectedFromCore()));
144 // attach backlog manager
145 p->synchronize(backlogManager());
146 connect(backlogManager(), SIGNAL(messagesReceived(BufferId, int)), _messageModel, SLOT(messagesReceived(BufferId, int)));
149 /*** public static methods ***/
151 AbstractUi *Client::mainUi() {
152 return instance()->_mainUi;
155 AccountId Client::currentCoreAccount() {
156 return _currentCoreAccount;
159 void Client::setCurrentCoreAccount(AccountId id) {
160 _currentCoreAccount = id;
163 bool Client::isConnected() {
164 return instance()->_connectedToCore;
167 bool Client::isSynced() {
168 return instance()->_syncedToCore;
171 /*** Network handling ***/
173 QList<NetworkId> Client::networkIds() {
174 return instance()->_networks.keys();
177 const Network * Client::network(NetworkId networkid) {
178 if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
182 void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels) {
183 emit instance()->requestCreateNetwork(info, persistentChannels);
186 void Client::removeNetwork(NetworkId id) {
187 emit instance()->requestRemoveNetwork(id);
190 void Client::updateNetwork(const NetworkInfo &info) {
191 Network *netptr = instance()->_networks.value(info.networkId, 0);
193 qWarning() << "Update for unknown network requested:" << info;
196 netptr->requestSetNetworkInfo(info);
199 void Client::addNetwork(Network *net) {
200 net->setProxy(signalProxy());
201 signalProxy()->synchronize(net);
202 networkModel()->attachNetwork(net);
203 connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
204 instance()->_networks[net->networkId()] = net;
205 emit instance()->networkCreated(net->networkId());
208 void Client::coreNetworkCreated(NetworkId id) {
209 if(_networks.contains(id)) {
210 qWarning() << "Creation of already existing network requested!";
213 Network *net = new Network(id, this);
217 void Client::coreNetworkRemoved(NetworkId id) {
218 if(!_networks.contains(id))
220 Network *net = _networks.take(id);
221 emit networkRemoved(net->networkId());
225 /*** Identity handling ***/
227 QList<IdentityId> Client::identityIds() {
228 return instance()->_identities.keys();
231 const Identity *Client::identity(IdentityId id) {
232 if(instance()->_identities.contains(id)) return instance()->_identities[id];
236 void Client::createIdentity(const CertIdentity &id) {
237 QVariantMap additional;
239 additional["KeyPem"] = id.sslKey().toPem();
240 additional["CertPem"] = id.sslCert().toPem();
242 emit instance()->requestCreateIdentity(id, additional);
245 void Client::updateIdentity(IdentityId id, const QVariantMap &ser) {
246 Identity *idptr = instance()->_identities.value(id, 0);
248 qWarning() << "Update for unknown identity requested:" << id;
251 idptr->requestUpdate(ser);
254 void Client::removeIdentity(IdentityId id) {
255 emit instance()->requestRemoveIdentity(id);
258 void Client::coreIdentityCreated(const Identity &other) {
259 if(!_identities.contains(other.id())) {
260 Identity *identity = new Identity(other, this);
261 _identities[other.id()] = identity;
262 identity->setInitialized();
263 signalProxy()->synchronize(identity);
264 emit identityCreated(other.id());
266 qWarning() << tr("Identity already exists in client!");
270 void Client::coreIdentityRemoved(IdentityId id) {
271 if(_identities.contains(id)) {
272 emit identityRemoved(id);
273 Identity *i = _identities.take(id);
278 /*** User input handling ***/
280 void Client::userInput(const BufferInfo &bufferInfo, const QString &message) {
281 // we need to make sure that AliasManager is ready before processing input
282 if(aliasManager() && aliasManager()->isInitialized())
283 inputHandler()->handleUserInput(bufferInfo, message);
285 instance()-> _userInputBuffer.append(qMakePair(bufferInfo, message));
288 void Client::sendBufferedUserInput() {
289 for(int i = 0; i < _userInputBuffer.count(); i++)
290 userInput(_userInputBuffer.at(i).first, _userInputBuffer.at(i).second);
292 _userInputBuffer.clear();
295 /*** core connection stuff ***/
297 void Client::setConnectedToCore(AccountId id, QIODevice *socket) {
298 if(socket) { // external core
299 // if the socket is an orphan, the signalProxy adopts it.
300 // -> we don't need to care about it anymore
301 socket->setParent(0);
302 signalProxy()->addPeer(socket);
304 _internalCore = !socket;
305 _connectedToCore = true;
306 setCurrentCoreAccount(id);
309 void Client::setSyncedToCore() {
310 // create buffersyncer
311 Q_ASSERT(!_bufferSyncer);
312 _bufferSyncer = new BufferSyncer(this);
313 connect(bufferSyncer(), SIGNAL(lastSeenMsgSet(BufferId, MsgId)), _networkModel, SLOT(setLastSeenMsgId(BufferId, MsgId)));
314 connect(bufferSyncer(), SIGNAL(bufferRemoved(BufferId)), this, SLOT(bufferRemoved(BufferId)));
315 connect(bufferSyncer(), SIGNAL(bufferRenamed(BufferId, QString)), this, SLOT(bufferRenamed(BufferId, QString)));
316 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), this, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
317 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), _messageModel, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
318 connect(networkModel(), SIGNAL(setLastSeenMsg(BufferId, MsgId)), bufferSyncer(), SLOT(requestSetLastSeenMsg(BufferId, const MsgId &)));
319 signalProxy()->synchronize(bufferSyncer());
321 // create a new BufferViewManager
322 Q_ASSERT(!_bufferViewManager);
323 _bufferViewManager = new ClientBufferViewManager(signalProxy(), this);
324 connect(bufferViewManager(), SIGNAL(initDone()), this, SLOT(createDefaultBufferView()));
325 connect(bufferViewManager(), SIGNAL(viewsInitialized()), this, SLOT(requestInitialBacklog()));
327 // create AliasManager
328 Q_ASSERT(!_aliasManager);
329 _aliasManager = new ClientAliasManager(this);
330 connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput()));
331 signalProxy()->synchronize(aliasManager());
333 _syncedToCore = true;
335 emit coreConnectionStateChanged(true);
338 void Client::requestInitialBacklog() {
339 // usually it _should_ take longer until the bufferViews are initialized, so that's what
340 // triggers this slot. But we have to make sure that we know all buffers yet.
341 // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead
342 if(!bufferSyncer()->isInitialized()) {
343 disconnect(bufferViewManager(), SIGNAL(viewsInitialized()), this, SLOT(requestInitialBacklog()));
344 connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
347 _backlogManager->requestInitialBacklog();
350 void Client::createDefaultBufferView() {
351 if(bufferViewManager()->bufferViewConfigs().isEmpty()) {
352 BufferViewConfig config(-1);
353 config.setBufferViewName(tr("All Buffers"));
354 config.initSetBufferList(networkModel()->allBufferIdsSorted());
355 bufferViewManager()->requestCreateBufferView(config.toVariantMap());
359 void Client::disconnectFromCore() {
363 signalProxy()->removeAllPeers();
366 void Client::disconnectedFromCore() {
367 _connectedToCore = false;
368 _syncedToCore = false;
370 emit coreConnectionStateChanged(false);
372 backlogManager()->reset();
373 messageProcessor()->reset();
375 // Clear internal data. Hopefully nothing relies on it at this point.
376 setCurrentCoreAccount(0);
379 _bufferSyncer->deleteLater();
383 if(_bufferViewManager) {
384 _bufferViewManager->deleteLater();
385 _bufferViewManager = 0;
389 _aliasManager->deleteLater();
393 // we probably don't want to save pending input for reconnect
394 _userInputBuffer.clear();
396 _messageModel->clear();
397 _networkModel->clear();
399 QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
400 while(netIter != _networks.end()) {
401 Network *net = netIter.value();
402 emit networkRemoved(net->networkId());
403 disconnect(net, SIGNAL(destroyed()), this, 0);
404 netIter = _networks.erase(netIter);
407 Q_ASSERT(_networks.isEmpty());
409 QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
410 while(idIter != _identities.end()) {
411 emit identityRemoved(idIter.key());
412 Identity *id = idIter.value();
413 idIter = _identities.erase(idIter);
416 Q_ASSERT(_identities.isEmpty());
422 void Client::networkDestroyed() {
423 Network *net = static_cast<Network *>(sender());
424 QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
425 while(netIter != _networks.end()) {
426 if(*netIter == net) {
427 netIter = _networks.erase(netIter);
435 // Hmm... we never used this...
436 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
437 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
440 void Client::recvMessage(const Message &msg) {
442 messageProcessor()->process(msg_);
445 void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) {
448 bufferSyncer()->requestSetLastSeenMsg(id, msgId);
451 void Client::removeBuffer(BufferId id) {
452 if(!bufferSyncer()) return;
453 bufferSyncer()->requestRemoveBuffer(id);
456 void Client::renameBuffer(BufferId bufferId, const QString &newName) {
459 bufferSyncer()->requestRenameBuffer(bufferId, newName);
462 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) {
465 bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
468 void Client::purgeKnownBufferIds() {
471 bufferSyncer()->requestPurgeBufferIds();
474 void Client::bufferRemoved(BufferId bufferId) {
475 // select a sane buffer (status buffer)
476 /* we have to manually select a buffer because otherwise inconsitent changes
477 * to the model might occur:
478 * the result of a buffer removal triggers a change in the selection model.
479 * the newly selected buffer might be a channel that hasn't been selected yet
480 * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
481 * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
483 QModelIndex current = bufferModel()->currentIndex();
484 if(current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
485 bufferModel()->setCurrentIndex(current.sibling(0,0));
488 // and remove it from the model
489 networkModel()->removeBuffer(bufferId);
492 void Client::bufferRenamed(BufferId bufferId, const QString &newName) {
493 QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
494 if(bufferIndex.isValid()) {
495 networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
499 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
500 QModelIndex idx = networkModel()->bufferIndex(bufferId1);
501 bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
502 networkModel()->removeBuffer(bufferId2);
505 void Client::logMessage(QtMsgType type, const char *msg) {
506 fprintf(stderr, "%s\n", msg);
508 if(type == QtFatalMsg) {
509 Quassel::logFatalMessage(msg);
511 QString msgString = QString("%1\n").arg(msg);
513 //Check to see if there is an instance around, else we risk recursions
514 //when calling instance() and creating new ones.
515 if (!instanceExists())
518 instance()->_debugLog << msgString;
519 emit instance()->logUpdated(msgString);