1 /***************************************************************************
2 * Copyright (C) 2005-08 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 "bufferinfo.h"
26 #include "ircchannel.h"
29 #include "networkinfo.h"
30 #include "networkmodel.h"
31 #include "buffermodel.h"
32 #include "quasselui.h"
33 #include "signalproxy.h"
36 QPointer<Client> Client::instanceptr = 0;
38 /*** Initialization/destruction ***/
40 Client *Client::instance() {
42 instanceptr = new Client();
46 void Client::destroy() {
50 void Client::init(AbstractUi *ui) {
51 instance()->mainUi = ui;
55 Client::Client(QObject *parent)
58 _signalProxy(new SignalProxy(SignalProxy::Client, this)),
62 connectedToCore(false)
72 _networkModel = new NetworkModel(this);
73 _bufferModel = new BufferModel(_networkModel);
75 connect(this, SIGNAL(bufferSelected(Buffer *)),
76 _bufferModel, SLOT(selectBuffer(Buffer *)));
78 connect(this, SIGNAL(bufferUpdated(Buffer *)),
79 _networkModel, SLOT(bufferUpdated(Buffer *)));
80 connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)),
81 _networkModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
83 SignalProxy *p = signalProxy();
84 p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)),
85 SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
86 p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)),
87 this, SLOT(recvSessionData(const QString &, const QVariant &)));
88 p->attachSlot(SIGNAL(coreState(const QVariant &)),
89 this, SLOT(recvCoreState(const QVariant &)));
90 p->attachSlot(SIGNAL(networkConnected(uint)),
91 this, SLOT(networkConnected(uint)));
92 p->attachSlot(SIGNAL(networkDisconnected(uint)),
93 this, SLOT(networkDisconnected(uint)));
94 p->attachSlot(SIGNAL(displayMsg(const Message &)),
95 this, SLOT(recvMessage(const Message &)));
96 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
97 this, SLOT(recvStatusMsg(QString, QString)));
100 p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
101 p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
102 p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
103 p->attachSignal(this, SIGNAL(requestNetworkStates()));
105 p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &)), SIGNAL(createIdentity(const Identity &)));
106 p->attachSignal(this, SIGNAL(requestUpdateIdentity(const Identity &)), SIGNAL(updateIdentity(const Identity &)));
107 p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
108 p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
109 p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
111 connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
112 connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
113 connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
114 connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
116 layoutTimer = new QTimer(this);
117 layoutTimer->setInterval(0);
118 layoutTimer->setSingleShot(false);
119 connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
123 /*** public static methods ***/
126 QList<NetworkInfo *> Client::networkInfos() {
127 return instance()->_networkInfo.values();
130 NetworkInfo *Client::networkInfo(uint networkid) {
131 if(instance()->_networkInfo.contains(networkid))
132 return instance()->_networkInfo[networkid];
137 QList<BufferInfo> Client::allBufferInfos() {
138 QList<BufferInfo> bufferids;
139 foreach(Buffer *buffer, buffers()) {
140 bufferids << buffer->bufferInfo();
145 QList<Buffer *> Client::buffers() {
146 return instance()->_buffers.values();
149 Buffer *Client::buffer(uint bufferUid) {
150 if(instance()->_buffers.contains(bufferUid))
151 return instance()->_buffers[bufferUid];
156 Buffer *Client::buffer(BufferInfo id) {
157 Buffer *buff = buffer(id.uid());
160 Client *client = Client::instance();
161 buff = new Buffer(id, client);
163 connect(buff, SIGNAL(userInput(BufferInfo, QString)),
164 client, SLOT(userInput(BufferInfo, QString)));
165 connect(buff, SIGNAL(bufferUpdated(Buffer *)),
166 client, SIGNAL(bufferUpdated(Buffer *)));
167 connect(buff, SIGNAL(destroyed()),
168 client, SLOT(bufferDestroyed()));
169 client->_buffers[id.uid()] = buff;
170 emit client->bufferUpdated(buff);
176 // FIXME switch to netids!
177 // WHEN IS THIS NEEDED ANYHOW!?
178 // ...only for finding the Buffer for a channel, I guess...
179 BufferInfo Client::bufferInfo(QString net, QString buf) {
180 foreach(Buffer *buffer_, buffers()) {
181 BufferInfo bufferInfo = buffer_->bufferInfo();
182 if(!bufferInfo.network().compare(net, Qt::CaseInsensitive) && !bufferInfo.buffer().compare(buf, Qt::CaseInsensitive))
185 Q_ASSERT(false); // should never happen!
189 BufferInfo Client::statusBufferInfo(QString net) {
190 return bufferInfo(net, "");
193 NetworkModel *Client::networkModel() {
194 return instance()->_networkModel;
197 BufferModel *Client::bufferModel() {
198 return instance()->_bufferModel;
202 SignalProxy *Client::signalProxy() {
203 return instance()->_signalProxy;
207 /*** Identity handling ***/
209 QList<IdentityId> Client::identityIds() {
210 return instance()->_identities.keys();
213 const Identity * Client::identity(IdentityId id) {
214 if(instance()->_identities.contains(id)) return instance()->_identities[id];
219 void Client::createIdentity(const Identity &id) {
220 emit instance()->requestCreateIdentity(id);
223 void Client::updateIdentity(const Identity &id) {
224 emit instance()->requestUpdateIdentity(id);
227 void Client::removeIdentity(IdentityId id) {
228 emit instance()->requestRemoveIdentity(id);
231 void Client::coreIdentityCreated(const Identity &other) {
232 if(!_identities.contains(other.id())) {
233 Identity *identity = new Identity(other, this);
234 _identities[other.id()] = identity;
235 identity->setInitialized();
236 signalProxy()->synchronize(identity);
237 emit identityCreated(other.id());
239 qWarning() << tr("Identity already exists in client!");
243 void Client::coreIdentityRemoved(IdentityId id) {
244 if(_identities.contains(id)) {
245 emit identityRemoved(id);
246 Identity *i = _identities.take(id);
254 bool Client::isConnected() {
255 return instance()->connectedToCore;
258 void Client::fakeInput(uint bufferUid, QString message) {
259 Buffer *buff = buffer(bufferUid);
261 qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
263 emit instance()->sendInput(buff->bufferInfo(), message);
266 void Client::fakeInput(BufferInfo bufferInfo, QString message) {
267 fakeInput(bufferInfo, message);
270 void Client::connectToCore(const QVariantMap &conn) {
271 // TODO implement SSL
272 coreConnectionInfo = conn;
274 emit coreConnectionError(tr("Already connected to Core!"));
279 socket->deleteLater();
281 if(conn["Host"].toString().isEmpty()) {
282 clientMode = LocalCore;
283 socket = new QBuffer(this);
284 connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
285 socket->open(QIODevice::ReadWrite);
286 //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
288 coreSocketConnected();
290 clientMode = RemoteCore;
291 emit coreConnectionMsg(tr("Connecting..."));
293 QTcpSocket *sock = new QTcpSocket(this);
295 connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
296 connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
297 connect(signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
298 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
299 sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
303 void Client::disconnectFromCore() {
307 void Client::setCoreConfiguration(const QVariantMap &settings) {
308 SignalProxy::writeDataToDevice(socket, settings);
311 void Client::coreSocketConnected() {
312 connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
313 emit coreConnectionMsg(tr("Synchronizing to core..."));
314 QVariantMap clientInit;
315 clientInit["GuiProtocol"] = GUI_PROTOCOL;
316 clientInit["User"] = coreConnectionInfo["User"].toString();
317 clientInit["Password"] = coreConnectionInfo["Password"].toString();
318 SignalProxy::writeDataToDevice(socket, clientInit);
321 void Client::coreSocketDisconnected() {
322 instance()->connectedToCore = false;
324 emit coreConnectionStateChanged(false);
325 socket->deleteLater();
328 /* Clear internal data. Hopefully nothing relies on it at this point. */
329 _networkModel->clear();
331 QHash<BufferId, Buffer *>::iterator bufferIter = _buffers.begin();
332 while(bufferIter != _buffers.end()) {
333 Buffer *buffer = bufferIter.value();
334 disconnect(buffer, SIGNAL(destroyed()), this, 0);
335 bufferIter = _buffers.erase(bufferIter);
336 buffer->deleteLater();
338 Q_ASSERT(_buffers.isEmpty());
341 QHash<NetworkId, NetworkInfo*>::iterator netIter = _networkInfo.begin();
342 while(netIter != _networkInfo.end()) {
343 NetworkInfo *net = netIter.value();
344 disconnect(net, SIGNAL(destroyed()), this, 0);
345 netIter = _networkInfo.erase(netIter);
348 Q_ASSERT(_networkInfo.isEmpty());
350 QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
351 while(idIter != _identities.end()) {
352 Identity *id = idIter.value();
353 emit identityRemoved(id->id());
354 idIter = _identities.erase(idIter);
357 Q_ASSERT(_identities.isEmpty());
359 coreConnectionInfo.clear();
365 void Client::recvCoreState(const QVariant &state) {
366 disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
367 disconnect(socket, 0, this, 0); // rest of communication happens through SignalProxy
368 signalProxy()->addPeer(socket);
373 void Client::syncToCore(const QVariant &coreState) {
374 if(!coreState.toMap().contains("SessionState")) {
375 emit coreConnectionError(tr("Invalid data received from core!"));
376 disconnectFromCore();
380 QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
383 QVariantMap sessData = sessionState["SessionData"].toMap();
384 foreach(QString key, sessData.keys())
385 recvSessionData(key, sessData[key]);
388 foreach(QVariant vid, sessionState["Identities"].toList()) {
389 coreIdentityCreated(vid.value<Identity>());
392 // store Buffer details
393 QVariantList coreBuffers = sessionState["Buffers"].toList();
394 /* make lookups by id faster */
395 foreach(QVariant vid, coreBuffers) {
396 buffer(vid.value<BufferInfo>()); // create all buffers, so we see them in the network views
399 // create networkInfo objects
400 QVariantList networkids = sessionState["Networks"].toList();
401 foreach(QVariant networkid, networkids) {
402 networkConnected(networkid.toUInt());
405 instance()->connectedToCore = true;
406 updateCoreConnectionProgress();
410 void Client::updateCoreConnectionProgress() {
411 // we'll do this in three steps:
416 int numNets = networkInfos().count();
417 int numNetsWaiting = 0;
420 int numIrcUsersWaiting = 0;
423 int numChannelsWaiting = 0;
425 foreach(NetworkInfo *net, networkInfos()) {
426 if(! net->initialized())
429 numIrcUsers += net->ircUsers().count();
430 foreach(IrcUser *user, net->ircUsers()) {
431 if(! user->initialized())
432 numIrcUsersWaiting++;
435 numChannels += net->ircChannels().count();
436 foreach(IrcChannel *channel, net->ircChannels()) {
437 if(! channel->initialized())
438 numChannelsWaiting++;
442 if(numNetsWaiting > 0) {
443 emit coreConnectionMsg(tr("Requesting network states..."));
444 emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
448 if(numIrcUsersWaiting > 0) {
449 emit coreConnectionMsg(tr("Requesting User states..."));
450 emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
454 if(numChannelsWaiting > 0) {
455 emit coreConnectionMsg(tr("Requesting Channel states..."));
456 emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
460 emit coreConnectionProgress(1,1);
462 emit coreConnectionStateChanged(true);
463 foreach(NetworkInfo *net, networkInfos()) {
464 disconnect(net, 0, this, SLOT(updateCoreConnectionProgress()));
467 // signalProxy()->dumpProxyStats();
470 void Client::recvSessionData(const QString &key, const QVariant &data) {
471 sessionData[key] = data;
472 emit sessionDataChanged(key, data);
473 emit sessionDataChanged(key);
476 void Client::storeSessionData(const QString &key, const QVariant &data) {
477 // Not sure if this is a good idea, but we'll try it anyway:
478 // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
479 // rather than immediately.
480 emit instance()->sendSessionData(key, data);
483 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
484 if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
488 QStringList Client::sessionDataKeys() {
489 return instance()->sessionData.keys();
492 void Client::coreSocketError(QAbstractSocket::SocketError) {
493 emit coreConnectionError(socket->errorString());
494 socket->deleteLater();
497 void Client::coreHasData() {
499 if(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
500 emit recvPartialItem(1,1);
501 QVariantMap msg = item.toMap();
502 if (!msg["StartWizard"].toBool()) {
503 recvCoreState(msg["Reply"]);
505 qWarning("Core not configured!");
506 qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
507 emit showConfigWizard(msg);
513 emit recvPartialItem(socket->bytesAvailable(), blockSize);
517 void Client::networkConnected(uint netid) {
518 // TODO: create statusBuffer / switch to networkids
519 //BufferInfo id = statusBufferInfo(net);
520 //Buffer *b = buffer(id);
521 //b->setActive(true);
523 NetworkInfo *netinfo = new NetworkInfo(netid, this);
524 netinfo->setProxy(signalProxy());
525 networkModel()->attachNetworkInfo(netinfo);
528 connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
529 connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
530 connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
532 connect(netinfo, SIGNAL(ircChannelAdded(QString)), this, SLOT(ircChannelAdded(QString)));
533 connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkInfoDestroyed()));
534 _networkInfo[netid] = netinfo;
537 void Client::networkDisconnected(uint networkid) {
538 foreach(Buffer *buffer, buffers()) {
539 if(buffer->bufferInfo().networkId() != networkid)
542 //buffer->displayMsg(Message(bufferid, Message::Server, tr("Server disconnected."))); FIXME
543 buffer->setActive(false);
546 Q_ASSERT(networkInfo(networkid));
547 if(!networkInfo(networkid)->initialized()) {
548 qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
549 updateCoreConnectionProgress();
553 void Client::ircChannelAdded(QString chanName) {
554 NetworkInfo *netInfo = qobject_cast<NetworkInfo*>(sender());
556 Buffer *buf = buffer(bufferInfo(netInfo->networkName(), chanName));
558 buf->setIrcChannel(netInfo->ircChannel(chanName));
562 void Client::updateBufferInfo(BufferInfo id) {
563 buffer(id)->updateBufferInfo(id);
566 void Client::bufferDestroyed() {
567 Buffer *buffer = static_cast<Buffer *>(sender());
568 uint bufferUid = buffer->uid();
569 if(_buffers.contains(bufferUid))
570 _buffers.remove(bufferUid);
573 void Client::networkInfoDestroyed() {
574 NetworkInfo *netinfo = static_cast<NetworkInfo *>(sender());
575 uint networkId = netinfo->networkId();
576 if(_networkInfo.contains(networkId))
577 _networkInfo.remove(networkId);
580 void Client::recvMessage(const Message &msg) {
581 Buffer *b = buffer(msg.buffer());
583 Buffer::ActivityLevel level = Buffer::OtherActivity;
584 if(msg.type() == Message::Plain || msg.type() == Message::Notice){
585 level |= Buffer::NewMessage;
587 if(msg.flags() & Message::Highlight){
588 level |= Buffer::Highlight;
590 emit bufferActivity(level, b);
595 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
596 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
599 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
600 Buffer *b = buffer(id);
601 foreach(QVariant v, msgs) {
602 Message msg = v.value<Message>();
604 if(!layoutQueue.contains(b)) layoutQueue.append(b);
606 if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
609 void Client::layoutMsg() {
610 if(layoutQueue.count()) {
611 Buffer *b = layoutQueue.takeFirst(); // TODO make this the current buffer
613 layoutQueue.append(b); // Buffer has more messages in its queue --> Round Robin
616 if(!layoutQueue.count())
620 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
621 return instance()->mainUi->layoutMsg(msg);
624 void Client::userInput(BufferInfo id, QString msg) {
625 emit sendInput(id, msg);