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);
100 connect(this, SIGNAL(requestInitialBacklog()), _backlogManager, SLOT(requestInitialBacklog()), Qt::QueuedConnection);
104 disconnectFromCore();
107 void Client::init() {
108 _currentCoreAccount = 0;
109 _networkModel = new NetworkModel(this);
111 connect(this, SIGNAL(networkRemoved(NetworkId)),
112 _networkModel, SLOT(networkRemoved(NetworkId)));
114 _bufferModel = new BufferModel(_networkModel);
115 _messageModel = mainUi()->createMessageModel(this);
116 _messageProcessor = mainUi()->createMessageProcessor(this);
117 _inputHandler = new ClientUserInputHandler(this);
119 SignalProxy *p = signalProxy();
121 p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
122 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
124 p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo)));
125 p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString)));
126 p->attachSignal(this, SIGNAL(requestNetworkStates()));
128 p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &)));
129 p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
130 p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
131 p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
133 p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)));
134 p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
135 p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
136 p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
138 connect(p, SIGNAL(disconnected()), this, SLOT(disconnectedFromCore()));
140 //connect(mainUi(), SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
141 connect(mainUi(), SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
142 connect(this, SIGNAL(connected()), mainUi(), SLOT(connectedToCore()));
143 connect(this, SIGNAL(disconnected()), mainUi(), SLOT(disconnectedFromCore()));
145 // attach backlog manager
146 p->synchronize(backlogManager());
147 connect(backlogManager(), SIGNAL(messagesReceived(BufferId, int)), _messageModel, SLOT(messagesReceived(BufferId, int)));
150 /*** public static methods ***/
152 AbstractUi *Client::mainUi() {
153 return instance()->_mainUi;
156 AccountId Client::currentCoreAccount() {
157 return _currentCoreAccount;
160 void Client::setCurrentCoreAccount(AccountId id) {
161 _currentCoreAccount = id;
164 bool Client::isConnected() {
165 return instance()->_connectedToCore;
168 bool Client::isSynced() {
169 return instance()->_syncedToCore;
172 /*** Network handling ***/
174 QList<NetworkId> Client::networkIds() {
175 return instance()->_networks.keys();
178 const Network * Client::network(NetworkId networkid) {
179 if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
183 void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels) {
184 emit instance()->requestCreateNetwork(info, persistentChannels);
187 void Client::removeNetwork(NetworkId id) {
188 emit instance()->requestRemoveNetwork(id);
191 void Client::updateNetwork(const NetworkInfo &info) {
192 Network *netptr = instance()->_networks.value(info.networkId, 0);
194 qWarning() << "Update for unknown network requested:" << info;
197 netptr->requestSetNetworkInfo(info);
200 void Client::addNetwork(Network *net) {
201 net->setProxy(signalProxy());
202 signalProxy()->synchronize(net);
203 networkModel()->attachNetwork(net);
204 connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
205 instance()->_networks[net->networkId()] = net;
206 emit instance()->networkCreated(net->networkId());
209 void Client::coreNetworkCreated(NetworkId id) {
210 if(_networks.contains(id)) {
211 qWarning() << "Creation of already existing network requested!";
214 Network *net = new Network(id, this);
218 void Client::coreNetworkRemoved(NetworkId id) {
219 if(!_networks.contains(id))
221 Network *net = _networks.take(id);
222 emit networkRemoved(net->networkId());
226 /*** Identity handling ***/
228 QList<IdentityId> Client::identityIds() {
229 return instance()->_identities.keys();
232 const Identity *Client::identity(IdentityId id) {
233 if(instance()->_identities.contains(id)) return instance()->_identities[id];
237 void Client::createIdentity(const CertIdentity &id) {
238 QVariantMap additional;
240 additional["KeyPem"] = id.sslKey().toPem();
241 additional["CertPem"] = id.sslCert().toPem();
243 emit instance()->requestCreateIdentity(id, additional);
246 void Client::updateIdentity(IdentityId id, const QVariantMap &ser) {
247 Identity *idptr = instance()->_identities.value(id, 0);
249 qWarning() << "Update for unknown identity requested:" << id;
252 idptr->requestUpdate(ser);
255 void Client::removeIdentity(IdentityId id) {
256 emit instance()->requestRemoveIdentity(id);
259 void Client::coreIdentityCreated(const Identity &other) {
260 if(!_identities.contains(other.id())) {
261 Identity *identity = new Identity(other, this);
262 _identities[other.id()] = identity;
263 identity->setInitialized();
264 signalProxy()->synchronize(identity);
265 emit identityCreated(other.id());
267 qWarning() << tr("Identity already exists in client!");
271 void Client::coreIdentityRemoved(IdentityId id) {
272 if(_identities.contains(id)) {
273 emit identityRemoved(id);
274 Identity *i = _identities.take(id);
279 /*** User input handling ***/
281 void Client::userInput(const BufferInfo &bufferInfo, const QString &message) {
282 // we need to make sure that AliasManager is ready before processing input
283 if(aliasManager() && aliasManager()->isInitialized())
284 inputHandler()->handleUserInput(bufferInfo, message);
286 instance()-> _userInputBuffer.append(qMakePair(bufferInfo, message));
289 void Client::sendBufferedUserInput() {
290 for(int i = 0; i < _userInputBuffer.count(); i++)
291 userInput(_userInputBuffer.at(i).first, _userInputBuffer.at(i).second);
293 _userInputBuffer.clear();
296 /*** core connection stuff ***/
298 void Client::setConnectedToCore(AccountId id, QIODevice *socket) {
299 if(socket) { // external core
300 // if the socket is an orphan, the signalProxy adopts it.
301 // -> we don't need to care about it anymore
302 socket->setParent(0);
303 signalProxy()->addPeer(socket);
305 _internalCore = !socket;
306 _connectedToCore = true;
307 setCurrentCoreAccount(id);
310 void Client::setSyncedToCore() {
311 // create buffersyncer
312 Q_ASSERT(!_bufferSyncer);
313 _bufferSyncer = new BufferSyncer(this);
314 connect(bufferSyncer(), SIGNAL(lastSeenMsgSet(BufferId, MsgId)), _networkModel, SLOT(setLastSeenMsgId(BufferId, MsgId)));
315 connect(bufferSyncer(), SIGNAL(bufferRemoved(BufferId)), this, SLOT(bufferRemoved(BufferId)));
316 connect(bufferSyncer(), SIGNAL(bufferRenamed(BufferId, QString)), this, SLOT(bufferRenamed(BufferId, QString)));
317 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), this, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
318 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), _messageModel, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
319 connect(networkModel(), SIGNAL(setLastSeenMsg(BufferId, MsgId)), bufferSyncer(), SLOT(requestSetLastSeenMsg(BufferId, const MsgId &)));
320 signalProxy()->synchronize(bufferSyncer());
322 // create a new BufferViewManager
323 Q_ASSERT(!_bufferViewManager);
324 _bufferViewManager = new ClientBufferViewManager(signalProxy(), this);
325 connect(bufferViewManager(), SIGNAL(initDone()), this, SLOT(createDefaultBufferView()));
326 connect(bufferViewManager(), SIGNAL(viewsInitialized()), this, SLOT(requestInitialBacklogBarrier()));
328 // create AliasManager
329 Q_ASSERT(!_aliasManager);
330 _aliasManager = new ClientAliasManager(this);
331 connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput()));
332 signalProxy()->synchronize(aliasManager());
334 _syncedToCore = true;
336 emit coreConnectionStateChanged(true);
339 void Client::requestInitialBacklogBarrier() {
340 // usually it _should_ take longer until the bufferViews are initialized, so that's what
341 // triggers this slot. But we have to make sure that we know all buffers yet.
342 // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead
343 if(!bufferSyncer()->isInitialized()) {
344 disconnect(bufferViewManager(), SIGNAL(viewsInitialized()), this, SLOT(requestInitialBacklogBarrier()));
345 connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklogBarrier()));
348 emit requestInitialBacklog();
351 void Client::createDefaultBufferView() {
352 if(bufferViewManager()->bufferViewConfigs().isEmpty()) {
353 BufferViewConfig config(-1);
354 config.setBufferViewName(tr("All Buffers"));
355 config.initSetBufferList(networkModel()->allBufferIdsSorted());
356 bufferViewManager()->requestCreateBufferView(config.toVariantMap());
360 void Client::disconnectFromCore() {
364 signalProxy()->removeAllPeers();
367 void Client::disconnectedFromCore() {
368 _connectedToCore = false;
369 _syncedToCore = false;
371 emit coreConnectionStateChanged(false);
373 backlogManager()->reset();
374 messageProcessor()->reset();
376 // Clear internal data. Hopefully nothing relies on it at this point.
377 setCurrentCoreAccount(0);
380 _bufferSyncer->deleteLater();
384 if(_bufferViewManager) {
385 _bufferViewManager->deleteLater();
386 _bufferViewManager = 0;
390 _aliasManager->deleteLater();
394 // we probably don't want to save pending input for reconnect
395 _userInputBuffer.clear();
397 _messageModel->clear();
398 _networkModel->clear();
400 QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
401 while(netIter != _networks.end()) {
402 Network *net = netIter.value();
403 emit networkRemoved(net->networkId());
404 disconnect(net, SIGNAL(destroyed()), this, 0);
405 netIter = _networks.erase(netIter);
408 Q_ASSERT(_networks.isEmpty());
410 QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
411 while(idIter != _identities.end()) {
412 emit identityRemoved(idIter.key());
413 Identity *id = idIter.value();
414 idIter = _identities.erase(idIter);
417 Q_ASSERT(_identities.isEmpty());
423 void Client::networkDestroyed() {
424 Network *net = static_cast<Network *>(sender());
425 QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
426 while(netIter != _networks.end()) {
427 if(*netIter == net) {
428 netIter = _networks.erase(netIter);
436 // Hmm... we never used this...
437 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
438 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
441 void Client::recvMessage(const Message &msg) {
443 messageProcessor()->process(msg_);
446 void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) {
449 bufferSyncer()->requestSetLastSeenMsg(id, msgId);
452 void Client::removeBuffer(BufferId id) {
453 if(!bufferSyncer()) return;
454 bufferSyncer()->requestRemoveBuffer(id);
457 void Client::renameBuffer(BufferId bufferId, const QString &newName) {
460 bufferSyncer()->requestRenameBuffer(bufferId, newName);
463 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) {
466 bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
469 void Client::purgeKnownBufferIds() {
472 bufferSyncer()->requestPurgeBufferIds();
475 void Client::bufferRemoved(BufferId bufferId) {
476 // select a sane buffer (status buffer)
477 /* we have to manually select a buffer because otherwise inconsitent changes
478 * to the model might occur:
479 * the result of a buffer removal triggers a change in the selection model.
480 * the newly selected buffer might be a channel that hasn't been selected yet
481 * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
482 * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
484 QModelIndex current = bufferModel()->currentIndex();
485 if(current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
486 bufferModel()->setCurrentIndex(current.sibling(0,0));
489 // and remove it from the model
490 networkModel()->removeBuffer(bufferId);
493 void Client::bufferRenamed(BufferId bufferId, const QString &newName) {
494 QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
495 if(bufferIndex.isValid()) {
496 networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
500 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
501 QModelIndex idx = networkModel()->bufferIndex(bufferId1);
502 bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
503 networkModel()->removeBuffer(bufferId2);
506 void Client::logMessage(QtMsgType type, const char *msg) {
507 fprintf(stderr, "%s\n", msg);
509 if(type == QtFatalMsg) {
510 Quassel::logFatalMessage(msg);
512 QString msgString = QString("%1\n").arg(msg);
514 //Check to see if there is an instance around, else we risk recursions
515 //when calling instance() and creating new ones.
516 if (!instanceExists())
519 instance()->_debugLog << msgString;
520 emit instance()->logUpdated(msgString);