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()));
326 // create AliasManager
327 Q_ASSERT(!_aliasManager);
328 _aliasManager = new ClientAliasManager(this);
329 connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput()));
330 signalProxy()->synchronize(aliasManager());
332 // trigger backlog request once all active bufferviews are initialized
333 connect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
335 _syncedToCore = true;
337 emit coreConnectionStateChanged(true);
340 void Client::requestInitialBacklog() {
341 // usually it _should_ take longer until the bufferViews are initialized, so that's what
342 // triggers this slot. But we have to make sure that we know all buffers yet.
343 // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead
344 if(!bufferSyncer()->isInitialized()) {
345 connect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
346 connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
349 _backlogManager->requestInitialBacklog();
352 void Client::createDefaultBufferView() {
353 if(bufferViewManager()->bufferViewConfigs().isEmpty()) {
354 BufferViewConfig config(-1);
355 config.setBufferViewName(tr("All Buffers"));
356 config.initSetBufferList(networkModel()->allBufferIdsSorted());
357 bufferViewManager()->requestCreateBufferView(config.toVariantMap());
361 void Client::disconnectFromCore() {
365 signalProxy()->removeAllPeers();
368 void Client::disconnectedFromCore() {
369 _connectedToCore = false;
370 _syncedToCore = false;
372 emit coreConnectionStateChanged(false);
374 backlogManager()->reset();
375 messageProcessor()->reset();
377 // Clear internal data. Hopefully nothing relies on it at this point.
378 setCurrentCoreAccount(0);
381 _bufferSyncer->deleteLater();
385 if(_bufferViewManager) {
386 _bufferViewManager->deleteLater();
387 _bufferViewManager = 0;
391 _aliasManager->deleteLater();
395 // we probably don't want to save pending input for reconnect
396 _userInputBuffer.clear();
398 _messageModel->clear();
399 _networkModel->clear();
401 QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
402 while(netIter != _networks.end()) {
403 Network *net = netIter.value();
404 emit networkRemoved(net->networkId());
405 disconnect(net, SIGNAL(destroyed()), this, 0);
406 netIter = _networks.erase(netIter);
409 Q_ASSERT(_networks.isEmpty());
411 QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
412 while(idIter != _identities.end()) {
413 emit identityRemoved(idIter.key());
414 Identity *id = idIter.value();
415 idIter = _identities.erase(idIter);
418 Q_ASSERT(_identities.isEmpty());
424 void Client::networkDestroyed() {
425 Network *net = static_cast<Network *>(sender());
426 QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
427 while(netIter != _networks.end()) {
428 if(*netIter == net) {
429 netIter = _networks.erase(netIter);
437 // Hmm... we never used this...
438 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
439 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
442 void Client::recvMessage(const Message &msg) {
444 messageProcessor()->process(msg_);
447 void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) {
450 bufferSyncer()->requestSetLastSeenMsg(id, msgId);
453 void Client::removeBuffer(BufferId id) {
454 if(!bufferSyncer()) return;
455 bufferSyncer()->requestRemoveBuffer(id);
458 void Client::renameBuffer(BufferId bufferId, const QString &newName) {
461 bufferSyncer()->requestRenameBuffer(bufferId, newName);
464 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) {
467 bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
470 void Client::purgeKnownBufferIds() {
473 bufferSyncer()->requestPurgeBufferIds();
476 void Client::bufferRemoved(BufferId bufferId) {
477 // select a sane buffer (status buffer)
478 /* we have to manually select a buffer because otherwise inconsitent changes
479 * to the model might occur:
480 * the result of a buffer removal triggers a change in the selection model.
481 * the newly selected buffer might be a channel that hasn't been selected yet
482 * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
483 * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
485 QModelIndex current = bufferModel()->currentIndex();
486 if(current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
487 bufferModel()->setCurrentIndex(current.sibling(0,0));
490 // and remove it from the model
491 networkModel()->removeBuffer(bufferId);
494 void Client::bufferRenamed(BufferId bufferId, const QString &newName) {
495 QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
496 if(bufferIndex.isValid()) {
497 networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
501 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
502 QModelIndex idx = networkModel()->bufferIndex(bufferId1);
503 bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
504 networkModel()->removeBuffer(bufferId2);
507 void Client::logMessage(QtMsgType type, const char *msg) {
508 fprintf(stderr, "%s\n", msg);
510 if(type == QtFatalMsg) {
511 Quassel::logFatalMessage(msg);
513 QString msgString = QString("%1\n").arg(msg);
515 //Check to see if there is an instance around, else we risk recursions
516 //when calling instance() and creating new ones.
517 if (!instanceExists())
520 instance()->_debugLog << msgString;
521 emit instance()->logUpdated(msgString);